@okxweb3/a2a-openclaw 0.2.16 → 0.2.17-beta-a72a480b58-261013200517
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 +12 -12
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
var __importMetaUrl=require('url').pathToFileURL(__filename).href;
|
|
2
|
-
"use strict";var Wr=Object.create;var Ie=Object.defineProperty;var zr=Object.getOwnPropertyDescriptor;var Jr=Object.getOwnPropertyNames;var Qr=Object.getPrototypeOf,Zr=Object.prototype.hasOwnProperty;var m=(e,n)=>()=>(e&&(n=e(e=0)),n);var Se=(e,n)=>{for(var t in n)Ie(e,t,{get:n[t],enumerable:!0})},dt=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Jr(n))!Zr.call(e,o)&&o!==t&&Ie(e,o,{get:()=>n[o],enumerable:!(r=zr(n,o))||r.enumerable});return e};var eo=(e,n,t)=>(t=e!=null?Wr(Qr(e)):{},dt(n||!e||!e.__esModule?Ie(t,"default",{value:e,enumerable:!0}):t,e)),no=e=>dt(Ie({},"__esModule",{value:!0}),e);function to(e=new Date){return e.toISOString()}function ct(e){return[`[${to()}]`,...e]}function u(...e){console.error(...ct(e))}function ut(...e){console.warn(...ct(e))}var I=m(()=>{"use strict"});function lt(e){ze=e}function Ae(){if(!ze)throw new Error("[xmtp] PluginRuntime not initialized \u2014 ensure setXmtpRuntime is called in register()");return ze}var ze,he=m(()=>{"use strict";ze=null});var a,Te=m(()=>{"use strict";a={GATEWAY_STARTED:"Gateway started",GATEWAY_STOPPED:"Gateway stopped",BOOTSTRAP_APPLIED:"Bootstrap applied",CHANNEL_READY:"Channel ready",CONVERSATION_STARTED:"Conversation started",EVALUATE_CONVERSATION_STARTED:"Evaluate conversation started",CONVERSATION_DELETED:"Conversation deleted",PENDING_CONVERSATION_DENIED:"Pending conversation denied",AGENTS_REFRESHED:"Agents refreshed",USER_DISPATCHED:"User dispatched",SESSION_DISPATCHED:"Session dispatched",SYNC_TICK_COMPLETED:"Sync tick completed",INBOUND_HANDLER_ENTERED:"Inbound handler entered",MESSAGE_RECEIVED:"Message received",MESSAGE_SENT:"Message sent",INBOUND_BUYER_PENDING:"Inbound buyer: no session, group still Unknown (pending)",INBOUND_BUYER_SESSION_AUTO_RECOVERED:"Inbound buyer: session missing for Allowed group, auto-recovered",INBOUND_BLOCKED_SENSITIVE:"Inbound blocked: sensitive word; reply sent",INBOUND_BLOCKED_ADDRESS_MISMATCH:"Inbound blocked: address mismatch",INBOUND_BLOCKED_INELIGIBLE:"Inbound blocked: message-eligible check failed",INBOUND_DROP_EMPTY_CONTENT:"Inbound drop: empty content",INBOUND_DROP_MISSING_JOBID:"Inbound drop: missing jobId",INBOUND_DROP_INVALID_JOBID:"Inbound drop: invalid jobId",INBOUND_DROP_UNSUPPORTED_MSGTYPE:"Inbound drop: unsupported msgType",INBOUND_DROP_DM_NON_SYSTEM:"Inbound drop: DM sender not in system whitelist",INBOUND_DROP_DM_INVALID_PAYLOAD:"Inbound drop: DM payload invalid",INBOUND_DROP_DM_UNKNOWN_AGENT:"Inbound drop: DM target agent not local",DM_FALLBACK_TO_BACKUP:"DM fallback to backup session",DM_WHITELIST_FAIL_OPEN:"DM whitelist fail-open (empty system accounts)",FILE_UPLOADED:"File uploaded",FILE_DOWNLOADED:"File downloaded",PENDING_LIST_QUERIED:"Pending list queried",AGENT_LIST_QUERIED:"Agent list queried",SESSION_KEY_DERIVED:"Session key derived",CONVERSATION_HISTORY_QUERIED:"Conversation history queried",SESSIONS_QUERIED:"Sessions queried",GROUP_CONSENT_CHANGED:"Group consent changed",SESSION_CREATED:"Session created",SESSION_DELETED:"Session deleted",SESSION_AUTO_RECOVERED:"Session auto-recovered",INBOUND_DELIVERED:"Inbound delivered to session",DM_DELIVERED:"DM delivered to session",OUTBOUND_ELIGIBILITY_CHECKED:"Outbound eligibility checked",MESSAGE_ELIGIBILITY_CHECKED:"Message eligibility checked",AGENT_CLIENT_CREATED:"Agent client created",AGENT_INSTALLATION_SUMMARY:"Agent installation summary",XMTP_HISTORY_SYNC_REQUESTED:"XMTP history sync requested",XMTP_DEBUG_SYNC_REQUESTED:"XMTP debug sync requested",XMTP_DEBUG_SYNC_COMPLETED:"XMTP debug sync completed",AGENT_CLIENT_REMOVED:"Agent client removed",AGENT_STREAM_RECOVERED:"Agent stream recovered",AGENT_STREAM_RECOVERY_REPLAY_COMPLETED:"Agent stream recovery replay completed",AGENT_STREAM_RECOVERY_REPLAY_TERMINATED:"Agent stream recovery replay terminated",ADDRESS_SYNC_COMPLETED:"Address sync completed",AGENT_REFRESH_SESSION_EXPIRED:"Agent refresh aborted: onchainos session expired, local clients taken offline",OFFLINE_REPLAY_MESSAGE_REPLAYED:"Offline replay message replayed",AGENTS_WAKEUP_NOTIFIED:"Agents wakeup notified",CONFIG_SENSITIVE_WORDS_REFRESHED:"Sensitive words config refreshed",CONFIG_SYSTEM_REFRESHED:"System config refreshed",GATEWAY_DISCONNECTED:"Gateway disconnected",GATEWAY_REQUEST:"Gateway request",GATEWAY_DELIVERY_BUFFERED:"Gateway delivery buffered",DAEMON_LIFECYCLE_SKIPPED:"Daemon lifecycle skipped",DAEMON_LIFECYCLE_REQUESTED:"Daemon lifecycle requested",PROMPT_USER_CHECKPOINT:"Prompt user checkpoint",USER_WATCH_STARTED:"User watch started",USER_WATCH_EVENT_DELIVERED:"User watch event delivered",INBOUND_DM_RAW:"Inbound DM raw",INBOUND_GROUP_RAW:"Inbound group raw",INBOUND_IGNORED_DUPLICATE:"Inbound ignored: duplicate message",INBOUND_IGNORED_NON_BUSINESS:"Inbound ignored: non-business message",AI_RUN_STARTED:"AI run started",AI_RUN_COMPLETED:"AI run completed",AI_RUN_SKIPPED:"AI run skipped",RUNTIME_DETECTED:"Runtime detected",PROVIDER_READINESS_CHECKED:"Provider readiness checked",PROVIDER_SWITCHED:"Provider switched",JOB_PROVIDER_BOUND:"Job provider bound",ONCHAINOS_VERSION_OBSERVED:"OnchainOS version observed",USER_CHANNEL_MESSAGE_DELIVERED:"User channel message delivered",SYSTEM_NOTIFICATION_RECEIVED:"System notification received",SYSTEM_NOTIFICATION_ROUTED:"System notification routed",HERMES_SESSION_ROUTE_BINDING:"Hermes session route binding",DOCTOR_REPORT:"Doctor report",XMTP_CONNECTION_FAILED:"XMTP connection failed",CONVERSATIONS_STREAM_FAILED:"conversations.stream failed",AGENT_START_FAILED:"agent.start failed",AGENT_STREAM_ERROR:"agent stream error",AGENT_UNHANDLED_ERROR:"Agent unhandled error",AGENT_STREAM_RECOVERY_TIMEOUT:"Agent stream recovery timeout",BOOTSTRAP_FAILED:"Bootstrap failed",ONCHAINOS_SESSION_EXPIRED:"Onchainos session expired",ONCHAINOS_CLI_ERROR:"Onchainos CLI error",HEARTBEAT_FAILED:"Heartbeat failed",HEARTBEAT_SKIPPED:"Heartbeat skipped",HEARTBEAT_GATEWAY_CHECK_FAILED:"Heartbeat gateway check failed",MESSAGE_PARSE_FAILED:"Message parse failed",MESSAGE_HANDLER_ERROR:"Message handler error",INBOUND_DISPATCH_FAILED:"Inbound dispatch failed",INBOUND_REPLAY_GATE_DRAIN_FAILED:"Inbound replay gate drain failed",FATAL_UNCAUGHT:"Fatal uncaught error",OFFLINE_REPLAY_FAILED:"Offline replay failed",INBOUND_ROUTING_FAILED:"Inbound routing failed",CONVERSATION_NOT_FOUND:"Conversation not found for send",XMTP_SEND_FAILED:"XMTP send failed",AGENT_REFRESH_FAILED:"Agent refresh failed",GROUP_CONSENT_UPDATE_FAILED:"Group consent update failed",TOOL_EXECUTE_FAILED:"Tool execute failed",AGENT_RESOLUTION_FAILED:"Agent resolution failed",USER_DISPATCH_FAILED:"User dispatch failed",INBOUND_ELIGIBILITY_BYPASSED:"Inbound eligibility bypassed",INBOUND_ADDRESS_CHECK_FAILED:"Inbound address check failed",INBOUND_ADDRESS_CHECK_BYPASSED:"Inbound address check bypassed",INBOUND_SENSITIVE_CHECK_FAILED:"Inbound sensitive check failed",FILE_UPLOAD_FAILED:"File upload failed",FILE_DOWNLOAD_FAILED:"File download failed",OFFLINE_REPLAY_MESSAGE_FAILED:"Offline replay message failed",PENDING_NOTIFICATION_FAILED:"Pending notification failed",GATEWAY_CONNECT_FAILED:"Gateway connect failed",GATEWAY_REQUEST_FAILED:"Gateway request failed",PROMPT_USER_FAILED:"Prompt user failed",DAEMON_COMMAND_FAILED:"Daemon command failed",DAEMON_COMMAND_TIMEOUT:"Daemon command timeout",DAEMON_COMMAND_STALE:"Daemon command stale",DAEMON_LIFECYCLE_FAILED:"Daemon lifecycle failed",DAEMON_TICK_FAILED:"Daemon tick failed",DIRECT_CLI_FAILED:"Direct CLI failed",DOCTOR_NOT_READY:"Doctor not ready",DOCTOR_CRASHED:"Doctor crashed",AI_RUN_FAILED:"AI run failed",AI_RUN_TIMEOUT:"AI run timeout",AI_RUN_TOOL_FAILED:"AI run tool failed",IPC_FAILED:"IPC failed",NOTIFY_AGENTS_WAKEUP_FAILED:"Notify agents wakeup failed",OUTBOUND_AGENT_LOOKUP_FAILED:"Outbound agent lookup failed",OUTBOUND_ELIGIBILITY_CHECK_FAILED:"Outbound eligibility check failed",OUTBOUND_ELIGIBILITY_BYPASSED:"Outbound eligibility bypassed",OUTBOUND_BLOCKED_INELIGIBLE:"Outbound blocked: message-eligible check failed",CACHE_LOAD_FAILED:"Cache load failed",CACHE_WRITE_FAILED:"Cache write failed",CONFIG_LOAD_FAILED:"Config load failed",SENTRY_INIT_SKIPPED:"Sentry init skipped",AGENT_DB_DIR_CREATE_FAILED:"Agent DB dir create failed",AGENT_INSTALLATION_LIMIT_NEAR:"Agent installation limit near",XMTP_HISTORY_SYNC_REQUEST_FAILED:"XMTP history sync request failed",XMTP_DEBUG_SYNC_FAILED:"XMTP debug sync failed"}});function z(e){return typeof e=="string"&&e.trim().length>0}function ft(e){let n=z(e.messageId)?e.messageId.trim():"";if(n&&ro.test(n))return n;let t=[n,e.jobId,e.sessionKey,e.attentionId].map(o=>z(o)?o.trim():"");if(t.every(o=>o===""))return U;let r=(0,gt.createHash)("sha256").update(t.join("|")).digest("hex");return`${oo}${r.slice(0,so)}`}function pt(e){if(!z(e))return{...Je};let[n,...t]=e.trim().split("-"),r=n.split(".");if(r.length<3)return{...Je};let[o,s,i]=r.map(d=>Number(d));return[o,s,i].every(d=>Number.isInteger(d)&&d>=0)?{releaseBase:n,releaseChannel:co(t[0]),releaseCode:o*io+s*ao+i}:{...Je}}function co(e){if(!z(e))return"release";let n=e.toLowerCase().replace(/[^a-z0-9]/g,"");return n?n.startsWith("beta")?"beta":n:"release"}function J(e){return[["checkpoint",e.checkpoint],["outcome",e.outcome],["transport",e.transport],["eventFamily",e.eventFamily],["workloadClass",e.workloadClass],["taskMode",e.taskMode],["originPlatform",e.originPlatform],["deliveryId",e.deliveryId]].reduce((t,[r,o])=>(z(o)&&(t[r]=o.trim()),t),{})}function we(e){if(typeof e!="string")return;let n=e.trim();if(!(!n||n===U||n==="*"))return n}function Re(...e){return e.map(we).find(n=>!!n)}function Qe(e){let n={...e},t=Re(e.jobId,e.taskId);t&&(n.jobId=t,n.taskId=t);let r=we(e.stage)??"",o=r.startsWith("inbound/"),s=r.startsWith("outbound/"),i=Re(e.onchainosAgentId,e.myAgentId,e.agentId),d=[e.peerAgentId,e.providerAgentId,e.clientAgentId].map(we).find(_=>!!_&&_!==i),c=Re(e.fromAgentId,e.senderAgentId,o?d:void 0,s?i:void 0),l=Re(e.toAgentId,e.receiverAgentId,o?i:void 0,s?d:void 0);c&&(n.fromAgentId=c),l&&(n.toAgentId=l);let g=[c,l,e.agentId,e.onchainosAgentId,e.peerAgentId,e.providerAgentId,e.clientAgentId,e.sessionAgentId,e.myAgentId].map(we).filter(_=>!!_),p=[...new Set(g)].sort();return p.length>0&&(n.participantAgentIds=p.join(",")),n}var gt,ro,oo,so,io,ao,U,Je,Ne=m(()=>{"use strict";gt=require("node:crypto"),ro=/^[0-9a-f]{16,}$/i,oo="dlv",so=24,io=1e6,ao=1e3,U="unknown";Je={releaseBase:U,releaseChannel:U,releaseCode:0}});function Z(){return M||(process.env.OKX_AGENT_TASK_HOME?(M=Oe((0,Q.resolve)(process.env.OKX_AGENT_TASK_HOME)),M):(M=Oe((0,Q.join)(lo(),".okx-agent-task")),M))}function Oe(e){return uo(e)}function uo(e){(0,De.mkdirSync)(e,{recursive:!0,mode:mt});try{(0,De.chmodSync)(e,mt)}catch(n){let t=n.code;if(t!=="EPERM"&&t!=="EACCES")throw n}return e}function lo(){try{let e=(0,yt.homedir)();if(e)return e}catch(e){}return(0,Q.resolve)(process.cwd())}var yt,Q,De,M,mt,Ze=m(()=>{"use strict";yt=require("node:os"),Q=require("node:path"),De=require("node:fs"),M=null,mt=448});function en(e,n,t){if(fo.has(n))try{let r=Z(),o=(0,D.join)(r,"xmtp-tests"),s=(0,D.join)(o,"active.json");if(!(0,$.existsSync)(s))return;let i=JSON.parse((0,$.readFileSync)(s,"utf8")),d=typeof i.runId=="string"?i.runId:"";if(!go.test(d))return;let c=(0,D.resolve)(o,d),l=`${(0,D.resolve)(o)}${D.sep}`;if(!c.startsWith(l))return;(0,$.appendFileSync)((0,D.join)(c,"events.jsonl"),`${JSON.stringify({timestamp:new Date().toISOString(),level:e,eventName:n,runId:d,...t})}
|
|
3
|
-
`,{encoding:"utf8",mode:384})}catch{}}var $,D,go,fo,Et=m(()=>{"use strict";$=require("node:fs"),D=require("node:path");Ze();go=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/,fo=new Set(["Address sync completed","Agent client created","Agent client removed","agent stream error","Agent stream recovered","Agent stream recovery replay completed","Agent stream recovery timeout","conversations.stream failed","Inbound delivered to session","Inbound dispatch failed","Inbound handler entered","Inbound ignored: duplicate message","Message handler error","Message received","Message sent","Offline replay failed","Offline replay message failed","Offline replay message replayed","System notification received","System notification routed","XMTP connection failed"])});function Ot(e){return e instanceof Error?e:void 0}function nn(e){if(typeof e!="string"&&typeof e!="number")return;let n=String(e).trim();if(!(!n||/^(?:null|undefined|unknown)$/i.test(n))&&/^[A-Za-z0-9_.:-]+$/.test(n))return n.slice(0,po)}function _t(e){if(typeof e!="string")return;let n=nn(e.trim().split(/\s+/,1)[0])?.toLowerCase();return n&&Eo.has(n)?n:void 0}function It(e){let n=nn(e)?.toUpperCase();return n&&yo.has(n)?n:void 0}function St(e){return It(e?.code)??It(e?.errno)}function At(e,n){let t=n?.toUpperCase(),r=e?.name.toLowerCase()??"",o=e?.message.toLowerCase()??"";return t&&ht.has(t)?"resource_exhausted":t&&Tt.has(t)?"connection_interrupted":t&&Rt.has(t)?"network_unavailable":t&&wt.has(t)?"timeout":t&&Nt.has(t)?"permission_denied":t==="ENOENT"?"missing_dependency":t==="ABORT_ERR"||r==="aborterror"?"cancelled":r==="syntaxerror"?"invalid_response":/connection\s+(?:reset|closed|interrupted)|broken\s+pipe|unexpected\s+eof/.test(o)?"connection_interrupted":/(?:json|response).*(?:parse|invalid)/.test(o)?"invalid_response":/session\s+(?:is\s+)?expired|login\s+expired/.test(o)?"session_expired":/timed?\s*out|timeout/.test(o)?"timeout":"unknown"}function _o(e){switch(e){case"connection_interrupted":case"network_unavailable":case"resource_exhausted":case"timeout":return"retryable";case"invalid_response":case"missing_dependency":case"permission_denied":case"session_expired":return"non_retryable";default:return"unknown"}}function Io(e){let n=[],t=new Set,r=e;for(;r&&n.length<mo&&!t.has(r);)n.push(r),t.add(r),r=Ot(r.cause);return n}function Dt(e,n,t){let r=Ot(n),o={};if(r&&(o.errorName=r.name,o.errorMessageLength=String(r.message.length)),!r||e===a.AGENT_STREAM_ERROR)return o;let s=Io(r),i=s[0],d=s.length>1?s[s.length-1]:void 0,c=nn(t.exitCode),l=St(i),g=At(i,l),p=_t(i.syscall),_=St(d),L=d?At(d,_):void 0,We=_t(d?.syscall),ot=g==="unknown"&&L?L:g,st=ot==="unknown"&&c&&c!=="0"?"process_exit":ot,it=l??_,at=p??We;return{...o,errorCategory:st,errorRetryability:_o(st),errorCauseDepth:String(Math.max(0,s.length-1)),...it?{errorCode:it}:{},...at?{errorSyscall:at}:{},...d?{causeErrorMessageLength:String(d.message.length),causeErrorCategory:L??"unknown",..._?{causeErrorCode:_}:{},...We?{causeErrorSyscall:We}:{}}:{}}}var po,mo,ht,Tt,Rt,wt,Nt,yo,Eo,bt=m(()=>{"use strict";Te();po=64,mo=4,ht=new Set(["EAGAIN","EMFILE","ENFILE","ENOMEM"]),Tt=new Set(["ECONNRESET","EPIPE"]),Rt=new Set(["EAI_AGAIN","ECONNREFUSED","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND"]),wt=new Set(["ETIMEDOUT","ESOCKETTIMEDOUT"]),Nt=new Set(["EACCES","EPERM"]),yo=new Set([...ht,...Tt,...Rt,...wt,...Nt,"ABORT_ERR","ENOENT"]),Eo=new Set(["access","bind","close","connect","getaddrinfo","kill","listen","mkdir","open","read","readdir","readlink","rename","rmdir","spawn","stat","unlink","write"])});function be(e){let n=e?.trim().toLowerCase();return n==="codex"?"codex":n==="claude"||n==="claude-code"?"claude-code":n==="openclaw"?"openclaw":n==="hermes"?"hermes":"unknown"}function Ct(e,n=process.env){let t=n.OKX_A2A_RUNTIME_SURFACE?.trim().toLowerCase();if(t==="desktop"||t==="cli"||t==="unknown")return t;let r=be(e);return r==="codex"?n.CODEX_INTERNAL_ORIGINATOR_OVERRIDE==="Codex Desktop"?"desktop":"cli":r==="claude-code"?n.CLAUDE_CODE_ENTRYPOINT?.trim().toLowerCase()==="remote_cowork"?"desktop":"cli":"unknown"}function rn(e={}){let n=Number(e.onchainosVersionObservedAtMs);return{aiProvider:be(e.aiProvider),runtimeSurface:e.runtimeSurface==="desktop"||e.runtimeSurface==="cli"?e.runtimeSurface:tn,onchainosVersion:typeof e.onchainosVersion=="string"&&e.onchainosVersion.trim()?e.onchainosVersion.trim().slice(0,128):tn,onchainosVersionObservedAtMs:Number.isFinite(n)&&n>0?String(Math.trunc(n)):"0",onchainosVersionProbeStatus:typeof e.onchainosVersionProbeStatus=="string"&&e.onchainosVersionProbeStatus.trim()?e.onchainosVersionProbeStatus.trim().toLowerCase().slice(0,32):tn}}var tn,on=m(()=>{"use strict";tn="unknown"});function an(e){let n=rn({...G,...e});G=n;try{y.setTags({aiProvider:n.aiProvider,runtimeSurface:n.runtimeSurface,onchainosVersion:n.onchainosVersion,onchainosVersionProbeStatus:n.onchainosVersionProbeStatus})}catch{}}function wo(e){try{let n=e?.extra?.eventName??e?.tags?.eventName;if(typeof n=="string"&&n.trim().length>0)return e;let t=e;t.extra={...ke,...G,...t.extra??{},eventName:a.FATAL_UNCAUGHT,eventFamily:"diagnostics",outcome:"failed",transport:"local"},t.tags={...t.tags??{},eventName:a.FATAL_UNCAUGHT,eventFamily:"diagnostics",outcome:"failed"},t.fingerprint=["a2a",a.FATAL_UNCAUGHT]}catch{}return e}var y,Kt,kt,vt,So,Ao,ho,To,Ro,Ce,Pt,ke,G,sn,f,xt,Lt,k=m(()=>{"use strict";I();y=eo(require("@sentry/node")),Kt=require("node:crypto");Te();Ne();Et();bt();on();Te();Ne();kt=(0,Kt.randomUUID)(),vt=new Set(["args","apikey","argv","auth","authorization","authtoken","bearer","body","cache","command","content","credential","credentials","cwd","data","error","failures","filename","file_name","filepath","file_path","headers","input","logpath","message","output","password","params","path","payload","privatekey","prompt","raw","rawevent","rawtext","request","response","accesstoken","refreshtoken","digest","nonce","salt","secret","token","stderr","stdout","title","tooloutput"]),So=["accesstoken","apikey","authorization","authtoken","content","credential","filepath","logpath","outputpath","password","payload","privatekey","prompt","rawevent","rawtext","refreshtoken","requestbody","responsebody","secret","stderr","stdout","token","tooloutput"],Ao=new Set(["onchainosagentlistresultjson","onchainosagentlistdiagnostictext","systemconfigjson"]),ho=new Set(["agentId","agentPlatform","aiProvider","cacheName","causeCode","causeType","causeVariant","checkpoint","code","communicationClass","component","eventFamily","eventName","endpoint","errorCategory","errorCode","errorRetryability","errorSyscall","exitCode","fromAgentId","grpcMethod","jobId","kind","method","onchainosAgentId","onchainosVersion","onchainosVersionProbeStatus","operation","originPlatform","outcome","participantAgentIds","peerAgentId","phase","platform","provider","reason","releaseBase","releaseChannel","releaseCode","replayOutcome","role","runId","runtimeContainer","runtimeSurface","senderAgentId","source","stage","status","streamErrorCode","streamType","subcommand","systemEvent","taskId","taskMode","toAgentId","transport","transportFailure","transportProtocol","type","workloadClass"]),To=["eventName","errorCategory","errorCode","errorSyscall","cacheName","component","method","operation","phase","reason","code","provider","type","kind","status","subcommand"],Ro=new Set([a.GATEWAY_STARTED,a.GATEWAY_STOPPED,a.GATEWAY_DISCONNECTED,a.GATEWAY_REQUEST,a.GATEWAY_DELIVERY_BUFFERED,a.DAEMON_LIFECYCLE_SKIPPED,a.DAEMON_LIFECYCLE_REQUESTED,a.PROMPT_USER_CHECKPOINT,a.USER_WATCH_STARTED,a.USER_WATCH_EVENT_DELIVERED,a.CHANNEL_READY,a.CONVERSATION_STARTED,a.EVALUATE_CONVERSATION_STARTED,a.CONVERSATION_DELETED,a.USER_DISPATCHED,a.SESSION_DISPATCHED,a.SESSION_CREATED,a.SESSION_DELETED,a.SESSION_AUTO_RECOVERED,a.INBOUND_DELIVERED,a.INBOUND_DM_RAW,a.INBOUND_GROUP_RAW,a.INBOUND_IGNORED_DUPLICATE,a.INBOUND_IGNORED_NON_BUSINESS,a.AI_RUN_STARTED,a.AI_RUN_COMPLETED,a.AI_RUN_SKIPPED,a.RUNTIME_DETECTED,a.PROVIDER_READINESS_CHECKED,a.PROVIDER_SWITCHED,a.JOB_PROVIDER_BOUND,a.ONCHAINOS_VERSION_OBSERVED,a.USER_CHANNEL_MESSAGE_DELIVERED,a.SYSTEM_NOTIFICATION_RECEIVED,a.SYSTEM_NOTIFICATION_ROUTED,a.HERMES_SESSION_ROUTE_BINDING,a.INBOUND_BLOCKED_ADDRESS_MISMATCH,a.INBOUND_BLOCKED_INELIGIBLE,a.MESSAGE_ELIGIBILITY_CHECKED,a.INBOUND_BLOCKED_SENSITIVE,a.INBOUND_DROP_DM_INVALID_PAYLOAD,a.INBOUND_DROP_DM_NON_SYSTEM,a.INBOUND_DROP_DM_UNKNOWN_AGENT,a.INBOUND_DROP_EMPTY_CONTENT,a.INBOUND_DROP_MISSING_JOBID,a.INBOUND_DROP_INVALID_JOBID,a.INBOUND_DROP_UNSUPPORTED_MSGTYPE,a.DM_DELIVERED,a.DM_FALLBACK_TO_BACKUP,a.DM_WHITELIST_FAIL_OPEN,a.INBOUND_BUYER_PENDING,a.INBOUND_BUYER_SESSION_AUTO_RECOVERED,a.MESSAGE_SENT,a.AGENT_CLIENT_CREATED,a.AGENT_CLIENT_REMOVED,a.AGENT_STREAM_ERROR,a.AGENT_STREAM_RECOVERED,a.AGENT_STREAM_RECOVERY_REPLAY_COMPLETED,a.AGENT_STREAM_RECOVERY_REPLAY_TERMINATED,a.ADDRESS_SYNC_COMPLETED,a.AGENTS_REFRESHED,a.AGENTS_WAKEUP_NOTIFIED,a.AGENT_LIST_QUERIED,a.BOOTSTRAP_APPLIED,a.CONFIG_SENSITIVE_WORDS_REFRESHED,a.CONFIG_SYSTEM_REFRESHED,a.CONVERSATION_HISTORY_QUERIED,a.FILE_DOWNLOADED,a.FILE_UPLOADED,a.GROUP_CONSENT_CHANGED,a.INBOUND_HANDLER_ENTERED,a.MESSAGE_RECEIVED,a.OFFLINE_REPLAY_MESSAGE_REPLAYED,a.AGENT_REFRESH_SESSION_EXPIRED,a.OUTBOUND_ELIGIBILITY_CHECKED,a.OUTBOUND_BLOCKED_INELIGIBLE,a.AGENT_INSTALLATION_SUMMARY,a.XMTP_HISTORY_SYNC_REQUESTED,a.XMTP_DEBUG_SYNC_REQUESTED,a.XMTP_DEBUG_SYNC_COMPLETED,a.PENDING_CONVERSATION_DENIED,a.PENDING_LIST_QUERIED,a.SESSION_KEY_DERIVED,a.SESSIONS_QUERIED,a.SYNC_TICK_COMPLETED]),Ce=256,Pt=128,ke={},G=rn(),sn=class e{static instance;initialized=!1;buffer=[];constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}init(n){if(this.initialized){ut("[logger] Already initialized, skipping.");return}try{ke=pt(n.release),n.runtimeMetadata&&an(n.runtimeMetadata),y.init({dsn:n.dsn,release:n.release,environment:n.environment,maxBreadcrumbs:0,beforeBreadcrumb:()=>null,beforeSend:r=>wo(r),isInner:!1});let t={projectName:n.projectName,agentPlatform:n.agentPlatform};n.runtimeContainer&&(t.runtimeContainer=n.runtimeContainer);for(let r of["aiProvider","runtimeSurface","onchainosVersion","onchainosVersionProbeStatus"])t[r]=G[r]??"unknown";y.setTags(t)}catch{return}this.initialized=!0,this.flush()}info(n,t){let r=e.sanitizeExtra(Qe({flowId:kt,...ke,...G,...t??{}}));if(en("info",n,r),!!Ro.has(n)){if(!this.initialized){this.buffer.push({level:"info",message:n,extra:r});return}this.captureInfo(n,r)}}captureInfo(n,t){try{y.withScope(r=>{e.applyDiagnostics(r,n,t),y.captureEvent({level:"info",message:n,extra:{...t,eventName:n}})})}catch{}}error(n,t,r){let o=e.sanitizeExtra(Qe({flowId:kt,...ke,...G,...r??{}}));if(en("error",n,o),!this.initialized){this.buffer.push({level:"error",message:n,error:t,extra:o});return}this.captureError(n,t,o)}captureError(n,t,r){try{let o=Dt(n,t,r),s={...r,...o};y.withScope(i=>{i.setLevel("error"),e.applyDiagnostics(i,n,s),y.captureException(e.createSentryEvent(n),{extra:{...s,eventName:n}})})}catch{}}async shutdown(){try{await y.close(5e3)}catch{await y.flush(5e3)}}flush(){for(;this.buffer.length>0;){let n=this.buffer.shift();n.level==="info"?this.captureInfo(n.message,n.extra??{}):this.captureError(n.message,n.error,n.extra??{})}}static sanitizeExtra(n){return Object.fromEntries(Object.entries(n).filter(([,t])=>t!==void 0).filter(([t])=>!e.isBlockedExtraKey(t)).map(([t,r])=>[t,e.safeValueForKey(t,r)]))}static isBlockedExtraKey(n){let t=n.toLowerCase(),r=e.normalizeSensitiveKey(n);return vt.has(t)||vt.has(r)?!0:e.isSafeMetricKey(r)?!1:So.some(o=>r.includes(o))}static isSafeMetricKey(n){return/(bytes|count|length|ms|size)$/.test(n)}static safeValueForKey(n,t){return typeof t=="string"&&Ao.has(e.normalizeSensitiveKey(n))?t:e.safeValue(t)}static normalizeSensitiveKey(n){return n.toLowerCase().replace(/[^a-z0-9]/g,"")}static safeValue(n){if(typeof n=="string")return n.length<=Ce?n:`${n.slice(0,Ce)}...`;if(n==null||typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="bigint")return n.toString();if(n instanceof Error)return{name:n.name,messageLength:n.message.length};if(Array.isArray(n))return n.slice(0,20).map(r=>e.safeValue(r));if(typeof n=="object")return Object.fromEntries(Object.entries(n).slice(0,50).filter(([,r])=>r!==void 0).filter(([r])=>!e.isBlockedExtraKey(r)).map(([r,o])=>[r,e.safeValueForKey(r,o)]));let t=String(n);return t.length<=Ce?t:`${t.slice(0,Ce)}...`}static tagValue(n){let t=String(n);return t.length<=Pt?t:`${t.slice(0,Pt)}...`}static normalizeTagKey(n){return n.replace(/[^A-Za-z0-9_.:-]+/g,"_").slice(0,32)||"unknown"}static applyDiagnostics(n,t,r){let o={eventName:t,...r};for(let[i,d]of Object.entries(o))ho.has(i)&&n.setTag(e.normalizeTagKey(i),e.tagValue(d));let s=["a2a",t];for(let i of To){let d=o[i];d&&s.push(`${i}:${e.tagValue(d)}`)}n.setFingerprint(s)}static toPascalCase(n){return n.split(/[\s:]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}static createSentryEvent(n){let t=new Error(n);return t.name=e.toPascalCase(n),t.stack=`${t.name}: ${n}`,t}},f=sn.getInstance(),xt=e=>f.init(e),Lt=()=>f.shutdown()});function ve(){return Ae()}function $t(e){Mt.has(e)||(Mt.add(e),u(`[okx-a2a:runtime] using legacy OpenClaw PluginRuntime API api=${e}`))}function ee(){let e=ve().config;if(typeof e.current=="function")return e.current();if(typeof e.loadConfig=="function")return $t("config.loadConfig"),e.loadConfig();throw new Error("Unsupported OpenClaw PluginRuntime: neither config.current nor config.loadConfig is available")}function Oo(e){let n=e.split(":");return n[0]==="agent"&&n[1]?n[1]:"main"}function Do(){try{let e=ee().agents?.list?.map(n=>n.id).filter(Boolean)??[];if(e.length>0)return[...new Set(e)]}catch{}return["main"]}function Gt(e){let n=ve().agent.session;if(typeof n.resolveStorePath!="function"||typeof n.loadSessionStore!="function")throw new Error("Unsupported OpenClaw PluginRuntime: no row-level or legacy session reader is available");$t("agent.session.loadSessionStore");let t=n.resolveStorePath(void 0,{agentId:e});return n.loadSessionStore(t,{skipCache:!0})}function jt(e){let n=ve().agent.session,t=Oo(e);return typeof n.getSessionEntry=="function"?n.getSessionEntry({agentId:t,sessionKey:e,readConsistency:"latest"}):Gt(t)[e]}function dn(){let e=ve().agent.session,n=[],t=new Set;for(let r of Do()){let o=typeof e.listSessionEntries=="function"?e.listSessionEntries({agentId:r,readConsistency:"latest",readOnly:!0}):Object.entries(Gt(r)).map(([s,i])=>({sessionKey:s,entry:i}));for(let s of o)t.has(s.sessionKey)||(t.add(s.sessionKey),n.push(s))}return n}function Ft(){return Object.fromEntries(dn().map(({sessionKey:e,entry:n})=>[e,n]))}var Mt,cn=m(()=>{"use strict";I();he();Mt=new Set});function bo(e=Z()){return(0,Bt.join)(e,"openclaw-gateway.json")}function Ht(e,n=Z()){let t=Oe(n),r=bo(t),o=`${r}.${process.pid}.tmp`,s={version:1,url:e.url,...e.password?{password:e.password}:{},...e.token?{token:e.token}:{},updatedAt:new Date().toISOString(),source:"openclaw-plugin"};(0,b.writeFileSync)(o,`${JSON.stringify(s,null,2)}
|
|
4
|
-
`,{encoding:"utf8",mode:384});try{(0,b.chmodSync)(o,384)}catch{}(0,b.renameSync)(o,r);try{(0,b.chmodSync)(r,384)}catch{}return r}var b,Bt,qt=m(()=>{"use strict";b=require("node:fs"),Bt=require("node:path");Ze()});function oe(e){return e.includes(te)||e.includes(`:${re}:`)}function Pe(e){if(!(!e||e==="direct"||e==="@direct"))return e.startsWith("telegram:")||e.startsWith("@")?e:`telegram:${e}`}function ne(e){if(typeof e=="number"&&Number.isFinite(e))return String(Math.trunc(e));if(typeof e=="string")return e.trim()||void 0}function Xt(e){if(e.length!==0)return e[0]==="topic"?ne(e[1]):e[0]==="thread"?e.length>=3?ne(e.slice(2).join(":")):ne(e[1]):ne(e[0])}function un(e,n){return!e||!n||!e.startsWith("telegram:")||/:topic:\d+$/.test(e)?e:`${e}:topic:${n}`}function Co(e,n){let t=e.split(":");if(n==="telegram"){let r=t.indexOf("telegram"),o=r>=0?t.slice(r+1):t.slice(3),s=o.findIndex(d=>d==="direct"||d==="dm");if(s>=0){let d=s>0?o[s-1]:void 0,c=o[s+1]==="telegram"&&o[s+2]?`telegram:${o[s+2]}`:o[s+1],l=Xt(o.slice(s+2));return{to:un(Pe(c),l),accountId:d,threadId:l}}let i=o.indexOf("group");if(i>=0){let d=i>0?o[i-1]:void 0,c=o[i+1]==="telegram"&&o[i+2]?`telegram:${o[i+2]}`:o[i+1],l=Xt(o.slice(i+2));return{to:un(Pe(c),l),accountId:d,threadId:l}}if(o[0]==="telegram"&&o[1])return{to:`telegram:${o[1]}`,accountId:void 0};if(o[1]==="telegram"&&o[2])return{to:`telegram:${o[2]}`,accountId:o[0]};if(o.length>=2)return{to:Pe(o[1]),accountId:o[0]};if(o.length===1)return{to:Pe(o[0]),accountId:void 0}}return{to:t[4],accountId:void 0}}function Yt(e,n){return typeof e!="string"||e==="direct"||e==="@direct"?n:e}function Vt(e){return ko[e]??e}function Wt(e){let n=[e],t=e.split(":");if(t.length<6||t[0]!=="agent"||t[2]!=="telegram"||t[3]!=="direct"&&t[3]!=="dm"||!t[4])return n;let r=t[4],o=t.slice(5),s;if(o[0]==="topic"&&o[1])s=`agent:${t[1]}:telegram:direct:${r}:thread:${r}:${o.slice(1).join(":")}`;else if(o[0]==="thread"){let i=o.length>=3?o.slice(2).join(":"):o[1];i&&(s=`agent:${t[1]}:telegram:direct:${r}:topic:${i}`)}return s&&s!==e&&n.push(s),n}function vo(e){if(e==="agent:main")return"main";let n=e.split(":");return n.length<4||n[0]!=="agent"||!n[1]||!n[2]||oe(e)||n[2]==="backup"?null:n[2]}function ln(e,n){if(!Jt(n))return null;let t=n,r=t.deliveryContext?.channel??t.lastChannel??t.origin?.provider??vo(e);if(!r)return null;let o=Vt(r),s=Co(e,o),i=Yt(t.deliveryContext?.to,s.to)??Yt(t.lastTo,s.to)??s.to,d=t.deliveryContext?.accountId??s.accountId,c=ne(t.deliveryContext?.threadId??t.origin?.threadId??t.lastThreadId??s.threadId);return{channel:o,target:{sessionKey:e,to:o==="telegram"?un(i,c):i,accountId:d,threadId:c,updatedAt:t.lastInteractionAt??t.updatedAt??Date.now()}}}function zt(e){let n=new Map,t=new Map;for(let[r,o]of Object.entries(e)){if(oe(r)||!Jt(o))continue;let s=o;if(s.spawnedBy||s.subagentRole)continue;let i=ln(r,o);if(!i)continue;let{channel:d,target:c}=i,{to:l,updatedAt:g}=c;l&&(!t.get(d)||g>(n.get(d)?.updatedAt??0))&&t.set(d,l);let p=n.get(d);(!p||g>p.updatedAt)&&n.set(d,c)}for(let[r,o]of n)if(!o.to){let s=t.get(r);s&&(o.to=s)}for(let[r,o]of n)u(`[findLatestUserSessions] channel=${r} winner=${o.sessionKey} to=${o.to??"(none)"} accountId=${o.accountId??"(none)"} interactedAt=${o.updatedAt}`);return n}function Jt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var te,re,ko,Qt=m(()=>{"use strict";I();te="okx-xmtp",re="okx-a2a";ko={dashboard:"webchat"}});function er(e){if(oe(e))return null;try{for(let n of Wt(e)){let t=ln(n,jt(n));if(t)return t}return null}catch(n){return nr("find_user_session_target",n),null}}function Zt(e){return e.toLowerCase().startsWith("0x")}function Po(e){if(typeof e=="string")return`${te}:${e}`;let n="myAgentId"in e&&"toAgentId"in e?new URLSearchParams({my:e.myAgentId,to:e.toAgentId,job:e.jobId}):new URLSearchParams({my:e.myXmtpAddress,to:e.toXmtpAddress,job:e.jobId});return`${te}:${n.toString()}`}function gn(e){let n=`${te}:`,t=e.indexOf(n);if(t===-1)return null;let r=new URLSearchParams(e.slice(t+n.length)),o=r.get("myAgentId")||r.get("myagentid"),s=r.get("toAgentId")||r.get("toagentid"),i=r.get("my"),d=r.get("to"),c=r.get("job"),l=r.get("gid");return o&&s&&c?{format:"agent",myAgentId:o,toAgentId:s,jobId:c,xmtpGroupId:l??""}:!i||!d||!c?null:!Zt(i)&&(d==="_"||!Zt(d))?{format:"agent",myAgentId:i,toAgentId:d,jobId:c,xmtpGroupId:l??""}:{format:"address",myXmtpAddress:i,toXmtpAddress:d,jobId:c,xmtpGroupId:l??""}}function se(e){if(!e)return"";let n=gn(e);return n?.jobId?n.jobId:/(?:^|:)backup:([^:&]+)/.exec(e)?.[1]??""}function ae(e){let n=e.taskId?.trim()||se(e.scopeKey)||se(e.sessionKey);return n?{taskId:n}:{}}function nr(e,n){u(`[okx-a2a:session] session-store lookup failed; continuing phase=${e} error=${n instanceof Error?n.message:String(n)}`)}function Ko(e){let n=typeof e=="string"?e:Po(e);return(0,ie.buildAgentSessionKey)({agentId:"main",channel:re,peer:{kind:"group",id:n}})}function tr(){let e=ee().agents?.list;if(e&&e.length>0){let n=e.find(t=>t.id==="main");return n?n.id:e[0].id}return"main"}function rr(){return(0,ie.buildAgentSessionKey)({agentId:tr(),channel:re,peer:{kind:"group",id:"backup"}})}function xo(e){return(0,ie.buildAgentSessionKey)({agentId:tr(),channel:re,peer:{kind:"group",id:`backup:${e}`}})}function v(){try{return zt(Ft())}catch(e){return nr("find_latest_user_sessions",e),new Map}}function or(e){let n=new Set,t=[...e.sessionKey?[e.sessionKey]:[],...Array.isArray(e.sessionKeys)?e.sessionKeys:[]].filter(o=>o.trim()),r=[];e.jobId&&r.push({jobId:e.jobId,myAgentId:e.myAgentId,toAgentId:e.toAgentId,myXmtpAddress:e.myXmtpAddress,toXmtpAddress:e.toXmtpAddress});for(let o of t){if(o.startsWith("agent:")){n.add(o);continue}let s=$o(o);if(s){n.add(xo(s));continue}let i=sr(o);if(i){r.push(i);continue}let d=gn(o);if(d){r.push(Mo(d));continue}n.add(Ko(o))}for(let o of Lo())for(let s of r)if(Uo(o,s)){n.add(o);break}return[...n].sort()}function Lo(){return dn().map(({sessionKey:e})=>e).filter(oe)}function Uo(e,n){let t=gn(e);if(t)return Go(t,n);let r=sr(e);return r?!(n.jobId&&r.jobId!==n.jobId||n.myAgentId&&r.myAgentId!==n.myAgentId||n.toAgentId&&r.toAgentId!==n.toAgentId||n.myXmtpAddress&&!n.myAgentId||n.toXmtpAddress&&!n.toAgentId):!n.jobId||n.myAgentId||n.toAgentId||n.myXmtpAddress||n.toXmtpAddress?!1:se(e)===n.jobId}function Mo(e){return"myAgentId"in e?{myAgentId:e.myAgentId,toAgentId:e.toAgentId,jobId:e.jobId}:{myXmtpAddress:e.myXmtpAddress,toXmtpAddress:e.toXmtpAddress,jobId:e.jobId}}function sr(e){let n=e.split(":"),t=n.indexOf("job");return t<0||n[t+2]!=="my"||n[t+4]!=="to"||!n[t+1]||!n[t+3]||!n[t+5]?null:{jobId:Ke(n[t+1]),myAgentId:Ke(n[t+3]),toAgentId:Ke(n[t+5])}}function $o(e){return e.startsWith("backup:")?Ke(e.slice(7)):null}function Go(e,n){return n.jobId&&e.jobId!==n.jobId?!1:"myAgentId"in e?!(n.myAgentId&&e.myAgentId!==n.myAgentId||n.toAgentId&&e.toAgentId!==n.toAgentId||n.myXmtpAddress&&!n.myAgentId||n.toXmtpAddress&&!n.toAgentId):!(n.myXmtpAddress&&e.myXmtpAddress.toLowerCase()!==n.myXmtpAddress.toLowerCase()||n.toXmtpAddress&&e.toXmtpAddress.toLowerCase()!==n.toXmtpAddress.toLowerCase()||n.myAgentId&&!n.myXmtpAddress||n.toAgentId&&!n.toXmtpAddress)}function Ke(e){try{return decodeURIComponent(e)}catch{return e}}var ie,j=m(()=>{"use strict";I();ie=require("openclaw/plugin-sdk/routing");cn();Qt()});function ir(e){return e.reduce((n,[t,r])=>(r!=null&&(n[t]=String(r)),n),{})}function ar(e){let n=ft({jobId:e.jobId,sessionKey:e.sessionKey});return n===U?null:n}function C(e){return{...J({checkpoint:e.checkpoint,outcome:e.outcome,transport:"user_channel",eventFamily:"user_channel",deliveryId:ar(e)}),...ir([["component",jo],["source",e.source],["channel",e.channel],["sessionKey",e.sessionKey],["jobId",e.jobId],["direction",e.direction],["senderAgentId",e.senderAgentId],["receiverAgentId",e.receiverAgentId],["hasTo",e.hasTo===void 0?void 0:e.hasTo?"1":"0"]])}}function xe(e,n="success"){let t={};for(let[o,s]of Object.entries(e))s!=null&&(t[o]=String(s));let r=t.phase?.trim()??"";return{...J({checkpoint:r?`${Ho}${r}`:null,outcome:n,transport:"gateway_rpc",eventFamily:"lifecycle"}),...t}}function T(e){let n=Object.entries({component:Fo,operation:Bo,checkpoint:e.checkpoint,sessionKey:e.sessionKey,channel:e.channel??"",taskId:e.taskId??"",runId:e.runId??"",reason:e.reason??"",status:e.status??"",queued:e.queued??"",delayMs:e.delayMs??"",durationMs:e.durationMs??"",running:e.running??"",processing:e.processing??""}).filter(([,t])=>t!=="");return{...J({outcome:Yo[e.checkpoint],transport:"user_channel",eventFamily:"user_channel",deliveryId:ar({jobId:e.taskId,sessionKey:e.sessionKey})}),...n.reduce((t,[r,o])=>(t[r]=String(o),t),{})}}function fn(e){let{delivered:n,failed:t,abandoned:r}=e,o=n>0||t>0||r>0;return t===0&&r===0?{shouldEmit:o,outcome:"success"}:{shouldEmit:o,outcome:n>0?"partial":"failed"}}function dr(e){return{...J({checkpoint:qo,outcome:fn(e).outcome,transport:"gateway_rpc",eventFamily:"outbound"}),...ir([["onchainosAgentId","*"],["source",Xo],["deliveredCount",e.delivered],["failedCount",e.failed],["abandonedCount",e.abandoned],["batchSize",e.batchSize]])}}var jo,Fo,Bo,Ho,qo,Xo,Yo,de=m(()=>{"use strict";Ne();jo="openclaw_user_dispatch",Fo="openclaw_prompt_user_queue",Bo="xmtp_prompt_user",Ho="gateway/",qo="outbound/outbox_drained",Xo="gateway_outbox_drain";Yo={fallback_scheduled:"pending",queued:"pending",run_pending:"pending",dispatch_started:"pending",dispatch_completed:"success",run_completed:"success",dispatch_failed:"failed",fallback_fired:"timeout"}});var mr={};Se(mr,{callChatInject:()=>ue,callGateway:()=>A,callSessionsCreate:()=>ce,callSessionsDelete:()=>hn,callSessionsSend:()=>Tn,formatPairingErrorHint:()=>Me,gatewayExtra:()=>xe,onGatewayEvent:()=>_n,resolveGatewayRuntimeConfig:()=>In,stopGatewayClient:()=>An,syncGatewayConfigForNodeDaemon:()=>Sn});function pn(e){if(e){if(typeof e=="string")return e;if(typeof e=="object"&&e!==null&&"env"in e)return process.env[e.env]||void 0}}function Jo(e){return e&&(typeof e=="string"?{type:"string",configured:!0}:typeof e=="object"&&e!==null&&"env"in e?{type:"env",env:String(e.env),configured:!!pn(e)}:{type:typeof e,configured:!0})}function mn(e){if(!e||typeof e!="object")return e??null;if(Array.isArray(e))return e.map(t=>mn(t));let n={};for(let[t,r]of Object.entries(e)){if(/password|token|secret/i.test(t)){n[t]=Jo(r);continue}n[t]=mn(r)}return n}function Qo(e){try{return JSON.stringify(e)}catch{return"[unserializable]"}}function Zo(e){let n=e.params;if(!n||typeof n!="object"||Array.isArray(n))return ae({taskId:e.taskId});let t=n;return ae({taskId:e.taskId,sessionKey:typeof t.sessionKey=="string"?t.sessionKey:typeof t.key=="string"?t.key:""})}function S(e,n={}){let t=xe({phase:e,...n});u(`[gateway] ${e}: ${JSON.stringify(t)}`),f.info(e.startsWith("request_")?a.GATEWAY_REQUEST:a.GATEWAY_STARTED,{component:"openclaw_gateway",...t})}function B(e,n,t={},r=a.GATEWAY_CONNECT_FAILED){let o=xe({phase:e,component:"openclaw_gateway",...t},"failed");u(`[gateway] ${e}:`,n),f.error(r,n instanceof Error?n:new Error(String(n)),o)}function es(e){for(let n of yn)try{n(e)}catch(t){u("[gateway] event handler failed:",t)}}function _n(e){return yn.add(e),()=>{yn.delete(e)}}function ur(){S("ready_gate_reset",{hasSharedClient:!!w,hasConnected:R}),F=new Promise((e,n)=>{Le=e,Ue=n})}function lr(e,n,t){if(w!==e){S(`${n}_skip_clear_noncurrent`,t);return}try{e.stop?.()}catch(r){B(`${n}_stop_failed`,r,t)}w=null,R=!1,F=null,Le=null,Ue=null,S(`${n}_cleared_client`,t)}function ns(){if(w)return S("reuse_client",{hasConnected:R,hasReadyPromise:!!F}),{client:w,ready:F};let e=In(),{url:n,password:t,token:r}=e,o=(0,En.randomUUID)(),s=++zo;ur(),S("init_client",{clientSeq:s,instanceId:o,url:n,hasGatewayConfig:!!e.rawGatewayConfig,gatewayConfig:Qo(mn(e.rawGatewayConfig)),passwordConfigured:!!t,tokenConfigured:!!r,scopes:cr.join(",")});let i=new pr.GatewayClient({url:n,password:t,token:r,instanceId:o,clientName:"gateway-client",clientDisplayName:"okx-a2a-plugin",mode:"backend",role:"operator",scopes:[...cr],onHelloOk:()=>{S("hello_ok",{clientSeq:s,instanceId:o,url:n}),R=!0,Le?.()},onEvent:es,onClose:(d,c)=>{if(u(`[gateway] closed (${d}): ${c||"no reason"}`),f.info(a.GATEWAY_DISCONNECTED,{clientSeq:String(s),instanceId:o,url:n,code:String(d),reason:c||"no-reason",hadConnected:String(R)}),R){R=!1,ur();return}lr(i,"close_before_connect",{clientSeq:s,instanceId:o,url:n,code:d,reason:c||"no-reason"})},onConnectError:d=>{let c=d;if(c?.retryable){B("connect_error_retryable",d,{clientSeq:s,instanceId:o,url:n,retryable:"true",reason:c?.details?.reason??"retryable",code:c?.gatewayCode??c?.details?.code});return}B("connect_error",d,{clientSeq:s,instanceId:o,url:n,retryable:"false",code:c?.gatewayCode??c?.details?.code}),Ue?.(d instanceof Error?d:new Error(String(d))),lr(i,"connect_error",{clientSeq:s,instanceId:o,url:n,code:c?.gatewayCode??c?.details?.code,reason:c?.details?.reason})}});return w=i,S("start_client",{clientSeq:s,instanceId:o,url:n}),i.start(),{client:i,ready:F}}function In(){let n=ee().gateway;return{url:`ws://127.0.0.1:${gr(process.env.OPENCLAW_GATEWAY_PORT)??gr(n?.port)??Wo}`,password:pn(n?.auth?.password),token:pn(n?.auth?.token),rawGatewayConfig:n}}function gr(e){if(typeof e=="number"&&Number.isFinite(e)){let r=Math.trunc(e);return r>0&&r<=65535?r:null}if(typeof e!="string")return null;let n=e.trim();if(!/^\d+$/.test(n))return null;let t=Number.parseInt(n,10);return t>0&&t<=65535?t:null}function Sn(){let e=In();try{let n=Ht({url:e.url,password:e.password,token:e.token});return S("synced_node_gateway_config",{path:n,url:e.url,passwordConfigured:!!e.password,tokenConfigured:!!e.token}),n}catch(n){return B("sync_node_gateway_config_failed",n,{url:e.url,passwordConfigured:!!e.password,tokenConfigured:!!e.token},a.GATEWAY_CONNECT_FAILED),null}}function An(){if(w){try{w.stop()}catch{}w=null,F=null,Le=null,Ue=null,R=!1}}function Me(e){let n=e,t=n?.gatewayCode??n?.details?.code;if(!t)return null;let r=n?.details??{},o=[`code=${t}`];r.reason&&o.push(`reason=${r.reason}`),r.authReason&&o.push(`authReason=${r.authReason}`),Array.isArray(r.requestedScopes)&&r.requestedScopes.length&&o.push(`requestedScopes=${r.requestedScopes.join(",")}`),r.deviceId&&o.push(`deviceId=${r.deviceId}`),r.requestId&&o.push(`requestId=${r.requestId}`);let s=` (${o.join(", ")})`;switch(t){case"NOT_PAIRED":case"PAIRING_REQUIRED":return`Device pairing approval pending${s}. On the openclaw host run \`openclaw devices approve --latest\` to review and approve the pending request, then retry.`;case"AUTH_SCOPE_MISMATCH":return`Existing device token lacks the required scope${s}. On the openclaw host run \`openclaw devices list\` to find the operator deviceId, then \`openclaw devices rotate --device <id> --role operator --scope operator.admin\` to reissue a token with operator.admin, and restart openclaw.`;case"AUTH_TOKEN_MISSING":case"AUTH_TOKEN_MISMATCH":case"AUTH_DEVICE_TOKEN_MISMATCH":return`Gateway device token is missing or stale${s}. On the openclaw host run \`openclaw devices list\`, then \`openclaw devices remove <deviceId>\`, then restart openclaw to re-pair.`;default:return null}}async function A(e){let n=e.timeoutMs??Vo,t=Date.now(),r=Zo(e);S("request_start",{method:e.method,timeoutMs:n,hasSharedClient:!!w,hasConnected:R,...r});let{client:o,ready:s}=ns();try{await s}catch(d){let c=Date.now()-t;throw B("request_ready_failed",d,{method:e.method,durationMs:c,timeoutMs:n,...r,code:d?.gatewayCode??d?.code??d?.details?.code,reason:"gateway_ready_failed",communicationClass:"openclaw_gateway_connect"},a.GATEWAY_REQUEST_FAILED),d}let i=Date.now()-t;S("request_ready",{method:e.method,readyWaitMs:i,timeoutMs:n,hasConnected:R,...r});try{let d=await o.request(e.method,e.params,{timeoutMs:n});return S("request_done",{method:e.method,durationMs:Date.now()-t,timeoutMs:n,...r}),d}catch(d){let c=Date.now()-t,l=/timeout|timed out/i.test(String(d?.message??d??""));B("request_error",d,{method:e.method,durationMs:c,timeoutMs:n,readyWaitMs:i,...r,isTimeout:l,code:d?.gatewayCode??d?.code??d?.details?.code,reason:l?"gateway_request_timeout":"gateway_request_error",communicationClass:"openclaw_gateway_rpc"},a.GATEWAY_REQUEST_FAILED);let g=Me(d);if(g){let p=d?.message??String(d);try{d.message=`${p}
|
|
5
|
-
${g}`}catch{}}throw d}}async function ce(e){return A({method:"sessions.create",params:e})}async function hn(e){return A({method:"sessions.delete",params:e})}async function Tn(e){let n=e.idempotencyKey??(0,En.randomUUID)(),t={key:e.key,message:e.message,idempotencyKey:n};try{let r=await A({method:"sessions.send",params:t});return{runId:fr(r),raw:r}}catch(r){let o=r?.gatewayCode??r?.code,s=String(r?.message??"");if(o==="INVALID_REQUEST"&&s.includes("session not found")){await ce({key:e.key}),f.info(a.SESSION_AUTO_RECOVERED,{sessionKey:e.key,trigger:"sessions.send"});let i=await A({method:"sessions.send",params:t});return{runId:fr(i),raw:i}}throw r}}function fr(e){if(!e||typeof e!="object")return;let n=e.runId;return typeof n=="string"&&n.trim()?n:void 0}async function ue(e){try{return await A({method:"chat.inject",params:e})}catch(n){let t=n?.gatewayCode??n?.code,r=String(n?.message??"");if(t==="INVALID_REQUEST"&&r.includes("session not found"))return await ce({key:e.sessionKey}),f.info(a.SESSION_AUTO_RECOVERED,{sessionKey:e.sessionKey,trigger:"chat.inject"}),await A({method:"chat.inject",params:e});throw n}}var pr,En,Vo,Wo,cr,zo,w,F,
|
|
6
|
-
`,{encoding:"utf8",mode:384}),(0,
|
|
2
|
+
"use strict";var Wr=Object.create;var Ie=Object.defineProperty;var zr=Object.getOwnPropertyDescriptor;var Jr=Object.getOwnPropertyNames;var Qr=Object.getPrototypeOf,Zr=Object.prototype.hasOwnProperty;var m=(e,n)=>()=>(e&&(n=e(e=0)),n);var Se=(e,n)=>{for(var t in n)Ie(e,t,{get:n[t],enumerable:!0})},dt=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Jr(n))!Zr.call(e,o)&&o!==t&&Ie(e,o,{get:()=>n[o],enumerable:!(r=zr(n,o))||r.enumerable});return e};var eo=(e,n,t)=>(t=e!=null?Wr(Qr(e)):{},dt(n||!e||!e.__esModule?Ie(t,"default",{value:e,enumerable:!0}):t,e)),no=e=>dt(Ie({},"__esModule",{value:!0}),e);function to(e=new Date){return e.toISOString()}function ct(e){return[`[${to()}]`,...e]}function u(...e){console.error(...ct(e))}function ut(...e){console.warn(...ct(e))}var I=m(()=>{"use strict"});function lt(e){ze=e}function Ae(){if(!ze)throw new Error("[xmtp] PluginRuntime not initialized \u2014 ensure setXmtpRuntime is called in register()");return ze}var ze,he=m(()=>{"use strict";ze=null});var a,Te=m(()=>{"use strict";a={GATEWAY_STARTED:"Gateway started",GATEWAY_STOPPED:"Gateway stopped",BOOTSTRAP_APPLIED:"Bootstrap applied",CHANNEL_READY:"Channel ready",CONVERSATION_STARTED:"Conversation started",EVALUATE_CONVERSATION_STARTED:"Evaluate conversation started",CONVERSATION_DELETED:"Conversation deleted",PENDING_CONVERSATION_DENIED:"Pending conversation denied",AGENTS_REFRESHED:"Agents refreshed",USER_DISPATCHED:"User dispatched",SESSION_DISPATCHED:"Session dispatched",SYNC_TICK_COMPLETED:"Sync tick completed",INBOUND_HANDLER_ENTERED:"Inbound handler entered",MESSAGE_RECEIVED:"Message received",MESSAGE_SENT:"Message sent",INBOUND_BUYER_PENDING:"Inbound buyer: no session, group still Unknown (pending)",INBOUND_BUYER_SESSION_AUTO_RECOVERED:"Inbound buyer: session missing for Allowed group, auto-recovered",INBOUND_BLOCKED_SENSITIVE:"Inbound blocked: sensitive word; reply sent",INBOUND_BLOCKED_ADDRESS_MISMATCH:"Inbound blocked: address mismatch",INBOUND_BLOCKED_INELIGIBLE:"Inbound blocked: message-eligible check failed",INBOUND_DROP_EMPTY_CONTENT:"Inbound drop: empty content",INBOUND_DROP_MISSING_JOBID:"Inbound drop: missing jobId",INBOUND_DROP_INVALID_JOBID:"Inbound drop: invalid jobId",INBOUND_DROP_UNSUPPORTED_MSGTYPE:"Inbound drop: unsupported msgType",INBOUND_DROP_DM_NON_SYSTEM:"Inbound drop: DM sender not in system whitelist",INBOUND_DROP_DM_INVALID_PAYLOAD:"Inbound drop: DM payload invalid",INBOUND_DROP_DM_UNKNOWN_AGENT:"Inbound drop: DM target agent not local",DM_FALLBACK_TO_BACKUP:"DM fallback to backup session",DM_WHITELIST_FAIL_OPEN:"DM whitelist fail-open (empty system accounts)",FILE_UPLOADED:"File uploaded",FILE_DOWNLOADED:"File downloaded",PENDING_LIST_QUERIED:"Pending list queried",AGENT_LIST_QUERIED:"Agent list queried",SESSION_KEY_DERIVED:"Session key derived",CONVERSATION_HISTORY_QUERIED:"Conversation history queried",SESSIONS_QUERIED:"Sessions queried",GROUP_CONSENT_CHANGED:"Group consent changed",SESSION_CREATED:"Session created",SESSION_DELETED:"Session deleted",SESSION_AUTO_RECOVERED:"Session auto-recovered",INBOUND_DELIVERED:"Inbound delivered to session",DM_DELIVERED:"DM delivered to session",OUTBOUND_ELIGIBILITY_CHECKED:"Outbound eligibility checked",MESSAGE_ELIGIBILITY_CHECKED:"Message eligibility checked",AGENT_CLIENT_CREATED:"Agent client created",AGENT_INSTALLATION_SUMMARY:"Agent installation summary",XMTP_HISTORY_SYNC_REQUESTED:"XMTP history sync requested",XMTP_DEBUG_SYNC_REQUESTED:"XMTP debug sync requested",XMTP_DEBUG_SYNC_COMPLETED:"XMTP debug sync completed",AGENT_CLIENT_REMOVED:"Agent client removed",AGENT_STREAM_RECOVERED:"Agent stream recovered",AGENT_STREAM_RECOVERY_REPLAY_COMPLETED:"Agent stream recovery replay completed",AGENT_STREAM_RECOVERY_REPLAY_TERMINATED:"Agent stream recovery replay terminated",ADDRESS_SYNC_COMPLETED:"Address sync completed",AGENT_REFRESH_SESSION_EXPIRED:"Agent refresh aborted: onchainos session expired, local clients taken offline",OFFLINE_REPLAY_MESSAGE_REPLAYED:"Offline replay message replayed",AGENTS_WAKEUP_NOTIFIED:"Agents wakeup notified",CONFIG_SENSITIVE_WORDS_REFRESHED:"Sensitive words config refreshed",CONFIG_SYSTEM_REFRESHED:"System config refreshed",GATEWAY_DISCONNECTED:"Gateway disconnected",GATEWAY_REQUEST:"Gateway request",GATEWAY_DELIVERY_BUFFERED:"Gateway delivery buffered",DAEMON_LIFECYCLE_SKIPPED:"Daemon lifecycle skipped",DAEMON_LIFECYCLE_REQUESTED:"Daemon lifecycle requested",PROMPT_USER_CHECKPOINT:"Prompt user checkpoint",USER_WATCH_STARTED:"User watch started",USER_WATCH_EVENT_DELIVERED:"User watch event delivered",INBOUND_DM_RAW:"Inbound DM raw",INBOUND_GROUP_RAW:"Inbound group raw",INBOUND_IGNORED_DUPLICATE:"Inbound ignored: duplicate message",INBOUND_IGNORED_NON_BUSINESS:"Inbound ignored: non-business message",AI_RUN_STARTED:"AI run started",AI_RUN_COMPLETED:"AI run completed",AI_RUN_SKIPPED:"AI run skipped",RUNTIME_DETECTED:"Runtime detected",PROVIDER_READINESS_CHECKED:"Provider readiness checked",PROVIDER_SWITCHED:"Provider switched",JOB_PROVIDER_BOUND:"Job provider bound",ONCHAINOS_VERSION_OBSERVED:"OnchainOS version observed",USER_CHANNEL_MESSAGE_DELIVERED:"User channel message delivered",SYSTEM_NOTIFICATION_RECEIVED:"System notification received",SYSTEM_NOTIFICATION_ROUTED:"System notification routed",HERMES_SESSION_ROUTE_BINDING:"Hermes session route binding",DOCTOR_REPORT:"Doctor report",XMTP_RATE_LIMIT_COOLDOWN_STARTED:"XMTP rate limit cooldown started",XMTP_RATE_LIMIT_CREATE_SUPPRESSED:"XMTP rate limit create suppressed",XMTP_RATE_LIMIT_PROBE:"XMTP rate limit probe",XMTP_RATE_LIMIT_RECOVERED:"XMTP rate limit recovered",XMTP_CONNECTION_FAILED:"XMTP connection failed",CONVERSATIONS_STREAM_FAILED:"conversations.stream failed",AGENT_START_FAILED:"agent.start failed",AGENT_STREAM_ERROR:"agent stream error",AGENT_UNHANDLED_ERROR:"Agent unhandled error",AGENT_STREAM_RECOVERY_TIMEOUT:"Agent stream recovery timeout",BOOTSTRAP_FAILED:"Bootstrap failed",ONCHAINOS_SESSION_EXPIRED:"Onchainos session expired",ONCHAINOS_CLI_ERROR:"Onchainos CLI error",HEARTBEAT_FAILED:"Heartbeat failed",HEARTBEAT_SKIPPED:"Heartbeat skipped",HEARTBEAT_GATEWAY_CHECK_FAILED:"Heartbeat gateway check failed",MESSAGE_PARSE_FAILED:"Message parse failed",MESSAGE_HANDLER_ERROR:"Message handler error",INBOUND_DISPATCH_FAILED:"Inbound dispatch failed",INBOUND_REPLAY_GATE_DRAIN_FAILED:"Inbound replay gate drain failed",FATAL_UNCAUGHT:"Fatal uncaught error",OFFLINE_REPLAY_FAILED:"Offline replay failed",INBOUND_ROUTING_FAILED:"Inbound routing failed",CONVERSATION_NOT_FOUND:"Conversation not found for send",XMTP_SEND_FAILED:"XMTP send failed",AGENT_REFRESH_FAILED:"Agent refresh failed",GROUP_CONSENT_UPDATE_FAILED:"Group consent update failed",TOOL_EXECUTE_FAILED:"Tool execute failed",AGENT_RESOLUTION_FAILED:"Agent resolution failed",USER_DISPATCH_FAILED:"User dispatch failed",INBOUND_ELIGIBILITY_BYPASSED:"Inbound eligibility bypassed",INBOUND_ADDRESS_CHECK_FAILED:"Inbound address check failed",INBOUND_ADDRESS_CHECK_BYPASSED:"Inbound address check bypassed",INBOUND_SENSITIVE_CHECK_FAILED:"Inbound sensitive check failed",FILE_UPLOAD_FAILED:"File upload failed",FILE_DOWNLOAD_FAILED:"File download failed",OFFLINE_REPLAY_MESSAGE_FAILED:"Offline replay message failed",PENDING_NOTIFICATION_FAILED:"Pending notification failed",GATEWAY_CONNECT_FAILED:"Gateway connect failed",GATEWAY_REQUEST_FAILED:"Gateway request failed",PROMPT_USER_FAILED:"Prompt user failed",DAEMON_COMMAND_FAILED:"Daemon command failed",DAEMON_COMMAND_TIMEOUT:"Daemon command timeout",DAEMON_COMMAND_STALE:"Daemon command stale",DAEMON_LIFECYCLE_FAILED:"Daemon lifecycle failed",DAEMON_TICK_FAILED:"Daemon tick failed",DIRECT_CLI_FAILED:"Direct CLI failed",DOCTOR_NOT_READY:"Doctor not ready",DOCTOR_CRASHED:"Doctor crashed",AI_RUN_FAILED:"AI run failed",AI_RUN_TIMEOUT:"AI run timeout",AI_RUN_TOOL_FAILED:"AI run tool failed",IPC_FAILED:"IPC failed",NOTIFY_AGENTS_WAKEUP_FAILED:"Notify agents wakeup failed",OUTBOUND_AGENT_LOOKUP_FAILED:"Outbound agent lookup failed",OUTBOUND_ELIGIBILITY_CHECK_FAILED:"Outbound eligibility check failed",OUTBOUND_ELIGIBILITY_BYPASSED:"Outbound eligibility bypassed",OUTBOUND_BLOCKED_INELIGIBLE:"Outbound blocked: message-eligible check failed",CACHE_LOAD_FAILED:"Cache load failed",CACHE_WRITE_FAILED:"Cache write failed",CONFIG_LOAD_FAILED:"Config load failed",SENTRY_INIT_SKIPPED:"Sentry init skipped",AGENT_DB_DIR_CREATE_FAILED:"Agent DB dir create failed",AGENT_INSTALLATION_LIMIT_NEAR:"Agent installation limit near",XMTP_HISTORY_SYNC_REQUEST_FAILED:"XMTP history sync request failed",XMTP_DEBUG_SYNC_FAILED:"XMTP debug sync failed",XMTP_CLIENT_CLOSE_FAILED:"XMTP client close failed"}});function z(e){return typeof e=="string"&&e.trim().length>0}function ft(e){let n=z(e.messageId)?e.messageId.trim():"";if(n&&ro.test(n))return n;let t=[n,e.jobId,e.sessionKey,e.attentionId].map(o=>z(o)?o.trim():"");if(t.every(o=>o===""))return U;let r=(0,gt.createHash)("sha256").update(t.join("|")).digest("hex");return`${oo}${r.slice(0,so)}`}function pt(e){if(!z(e))return{...Je};let[n,...t]=e.trim().split("-"),r=n.split(".");if(r.length<3)return{...Je};let[o,s,i]=r.map(d=>Number(d));return[o,s,i].every(d=>Number.isInteger(d)&&d>=0)?{releaseBase:n,releaseChannel:co(t[0]),releaseCode:o*io+s*ao+i}:{...Je}}function co(e){if(!z(e))return"release";let n=e.toLowerCase().replace(/[^a-z0-9]/g,"");return n?n.startsWith("beta")?"beta":n:"release"}function J(e){return[["checkpoint",e.checkpoint],["outcome",e.outcome],["transport",e.transport],["eventFamily",e.eventFamily],["workloadClass",e.workloadClass],["taskMode",e.taskMode],["originPlatform",e.originPlatform],["deliveryId",e.deliveryId]].reduce((t,[r,o])=>(z(o)&&(t[r]=o.trim()),t),{})}function we(e){if(typeof e!="string")return;let n=e.trim();if(!(!n||n===U||n==="*"))return n}function Re(...e){return e.map(we).find(n=>!!n)}function Qe(e){let n={...e},t=Re(e.jobId,e.taskId);t&&(n.jobId=t,n.taskId=t);let r=we(e.stage)??"",o=r.startsWith("inbound/"),s=r.startsWith("outbound/"),i=Re(e.onchainosAgentId,e.myAgentId,e.agentId),d=[e.peerAgentId,e.providerAgentId,e.clientAgentId].map(we).find(_=>!!_&&_!==i),c=Re(e.fromAgentId,e.senderAgentId,o?d:void 0,s?i:void 0),l=Re(e.toAgentId,e.receiverAgentId,o?i:void 0,s?d:void 0);c&&(n.fromAgentId=c),l&&(n.toAgentId=l);let g=[c,l,e.agentId,e.onchainosAgentId,e.peerAgentId,e.providerAgentId,e.clientAgentId,e.sessionAgentId,e.myAgentId].map(we).filter(_=>!!_),p=[...new Set(g)].sort();return p.length>0&&(n.participantAgentIds=p.join(",")),n}var gt,ro,oo,so,io,ao,U,Je,Ne=m(()=>{"use strict";gt=require("node:crypto"),ro=/^[0-9a-f]{16,}$/i,oo="dlv",so=24,io=1e6,ao=1e3,U="unknown";Je={releaseBase:U,releaseChannel:U,releaseCode:0}});function Z(){return M||(process.env.OKX_AGENT_TASK_HOME?(M=Oe((0,Q.resolve)(process.env.OKX_AGENT_TASK_HOME)),M):(M=Oe((0,Q.join)(lo(),".okx-agent-task")),M))}function Oe(e){return uo(e)}function uo(e){(0,De.mkdirSync)(e,{recursive:!0,mode:mt});try{(0,De.chmodSync)(e,mt)}catch(n){let t=n.code;if(t!=="EPERM"&&t!=="EACCES")throw n}return e}function lo(){try{let e=(0,yt.homedir)();if(e)return e}catch(e){}return(0,Q.resolve)(process.cwd())}var yt,Q,De,M,mt,Ze=m(()=>{"use strict";yt=require("node:os"),Q=require("node:path"),De=require("node:fs"),M=null,mt=448});function en(e,n,t){if(fo.has(n))try{let r=Z(),o=(0,D.join)(r,"xmtp-tests"),s=(0,D.join)(o,"active.json");if(!(0,$.existsSync)(s))return;let i=JSON.parse((0,$.readFileSync)(s,"utf8")),d=typeof i.runId=="string"?i.runId:"";if(!go.test(d))return;let c=(0,D.resolve)(o,d),l=`${(0,D.resolve)(o)}${D.sep}`;if(!c.startsWith(l))return;(0,$.appendFileSync)((0,D.join)(c,"events.jsonl"),`${JSON.stringify({timestamp:new Date().toISOString(),level:e,eventName:n,runId:d,...t})}
|
|
3
|
+
`,{encoding:"utf8",mode:384})}catch{}}var $,D,go,fo,Et=m(()=>{"use strict";$=require("node:fs"),D=require("node:path");Ze();go=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/,fo=new Set(["Address sync completed","Agent client created","Agent client removed","agent stream error","Agent stream recovered","Agent stream recovery replay completed","Agent stream recovery timeout","conversations.stream failed","Inbound delivered to session","Inbound dispatch failed","Inbound handler entered","Inbound ignored: duplicate message","Message handler error","Message received","Message sent","Offline replay failed","Offline replay message failed","Offline replay message replayed","System notification received","System notification routed","XMTP connection failed"])});function Ot(e){return e instanceof Error?e:void 0}function nn(e){if(typeof e!="string"&&typeof e!="number")return;let n=String(e).trim();if(!(!n||/^(?:null|undefined|unknown)$/i.test(n))&&/^[A-Za-z0-9_.:-]+$/.test(n))return n.slice(0,po)}function _t(e){if(typeof e!="string")return;let n=nn(e.trim().split(/\s+/,1)[0])?.toLowerCase();return n&&Eo.has(n)?n:void 0}function It(e){let n=nn(e)?.toUpperCase();return n&&yo.has(n)?n:void 0}function St(e){return It(e?.code)??It(e?.errno)}function At(e,n){let t=n?.toUpperCase(),r=e?.name.toLowerCase()??"",o=e?.message.toLowerCase()??"";return t&&ht.has(t)?"resource_exhausted":t&&Tt.has(t)?"connection_interrupted":t&&Rt.has(t)?"network_unavailable":t&&wt.has(t)?"timeout":t&&Nt.has(t)?"permission_denied":t==="ENOENT"?"missing_dependency":t==="ABORT_ERR"||r==="aborterror"?"cancelled":r==="syntaxerror"?"invalid_response":/connection\s+(?:reset|closed|interrupted)|broken\s+pipe|unexpected\s+eof/.test(o)?"connection_interrupted":/(?:json|response).*(?:parse|invalid)/.test(o)?"invalid_response":/session\s+(?:is\s+)?expired|login\s+expired/.test(o)?"session_expired":/timed?\s*out|timeout/.test(o)?"timeout":"unknown"}function _o(e){switch(e){case"connection_interrupted":case"network_unavailable":case"resource_exhausted":case"timeout":return"retryable";case"invalid_response":case"missing_dependency":case"permission_denied":case"session_expired":return"non_retryable";default:return"unknown"}}function Io(e){let n=[],t=new Set,r=e;for(;r&&n.length<mo&&!t.has(r);)n.push(r),t.add(r),r=Ot(r.cause);return n}function Dt(e,n,t){let r=Ot(n),o={};if(r&&(o.errorName=r.name,o.errorMessageLength=String(r.message.length)),!r||e===a.AGENT_STREAM_ERROR)return o;let s=Io(r),i=s[0],d=s.length>1?s[s.length-1]:void 0,c=nn(t.exitCode),l=St(i),g=At(i,l),p=_t(i.syscall),_=St(d),x=d?At(d,_):void 0,We=_t(d?.syscall),ot=g==="unknown"&&x?x:g,st=ot==="unknown"&&c&&c!=="0"?"process_exit":ot,it=l??_,at=p??We;return{...o,errorCategory:st,errorRetryability:_o(st),errorCauseDepth:String(Math.max(0,s.length-1)),...it?{errorCode:it}:{},...at?{errorSyscall:at}:{},...d?{causeErrorMessageLength:String(d.message.length),causeErrorCategory:x??"unknown",..._?{causeErrorCode:_}:{},...We?{causeErrorSyscall:We}:{}}:{}}}var po,mo,ht,Tt,Rt,wt,Nt,yo,Eo,bt=m(()=>{"use strict";Te();po=64,mo=4,ht=new Set(["EAGAIN","EMFILE","ENFILE","ENOMEM"]),Tt=new Set(["ECONNRESET","EPIPE"]),Rt=new Set(["EAI_AGAIN","ECONNREFUSED","EHOSTUNREACH","ENETDOWN","ENETUNREACH","ENOTFOUND"]),wt=new Set(["ETIMEDOUT","ESOCKETTIMEDOUT"]),Nt=new Set(["EACCES","EPERM"]),yo=new Set([...ht,...Tt,...Rt,...wt,...Nt,"ABORT_ERR","ENOENT"]),Eo=new Set(["access","bind","close","connect","getaddrinfo","kill","listen","mkdir","open","read","readdir","readlink","rename","rmdir","spawn","stat","unlink","write"])});function be(e){let n=e?.trim().toLowerCase();return n==="codex"?"codex":n==="claude"||n==="claude-code"?"claude-code":n==="openclaw"?"openclaw":n==="hermes"?"hermes":"unknown"}function Ct(e,n=process.env){let t=n.OKX_A2A_RUNTIME_SURFACE?.trim().toLowerCase();if(t==="desktop"||t==="cli"||t==="unknown")return t;let r=be(e);return r==="codex"?n.CODEX_INTERNAL_ORIGINATOR_OVERRIDE==="Codex Desktop"?"desktop":"cli":r==="claude-code"?n.CLAUDE_CODE_ENTRYPOINT?.trim().toLowerCase()==="remote_cowork"?"desktop":"cli":"unknown"}function rn(e={}){let n=Number(e.onchainosVersionObservedAtMs);return{aiProvider:be(e.aiProvider),runtimeSurface:e.runtimeSurface==="desktop"||e.runtimeSurface==="cli"?e.runtimeSurface:tn,onchainosVersion:typeof e.onchainosVersion=="string"&&e.onchainosVersion.trim()?e.onchainosVersion.trim().slice(0,128):tn,onchainosVersionObservedAtMs:Number.isFinite(n)&&n>0?String(Math.trunc(n)):"0",onchainosVersionProbeStatus:typeof e.onchainosVersionProbeStatus=="string"&&e.onchainosVersionProbeStatus.trim()?e.onchainosVersionProbeStatus.trim().toLowerCase().slice(0,32):tn}}var tn,on=m(()=>{"use strict";tn="unknown"});function an(e){let n=rn({...G,...e});G=n;try{y.setTags({aiProvider:n.aiProvider,runtimeSurface:n.runtimeSurface,onchainosVersion:n.onchainosVersion,onchainosVersionProbeStatus:n.onchainosVersionProbeStatus})}catch{}}function wo(e){try{let n=e?.extra?.eventName??e?.tags?.eventName;if(typeof n=="string"&&n.trim().length>0)return e;let t=e;t.extra={...ke,...G,...t.extra??{},eventName:a.FATAL_UNCAUGHT,eventFamily:"diagnostics",outcome:"failed",transport:"local"},t.tags={...t.tags??{},eventName:a.FATAL_UNCAUGHT,eventFamily:"diagnostics",outcome:"failed"},t.fingerprint=["a2a",a.FATAL_UNCAUGHT]}catch{}return e}var y,Kt,kt,Pt,So,Ao,ho,To,Ro,Ce,vt,ke,G,sn,f,Lt,xt,k=m(()=>{"use strict";I();y=eo(require("@sentry/node")),Kt=require("node:crypto");Te();Ne();Et();bt();on();Te();Ne();kt=(0,Kt.randomUUID)(),Pt=new Set(["args","apikey","argv","auth","authorization","authtoken","bearer","body","cache","command","content","credential","credentials","cwd","data","error","failures","filename","file_name","filepath","file_path","headers","input","logpath","message","output","password","params","path","payload","privatekey","prompt","raw","rawevent","rawtext","request","response","accesstoken","refreshtoken","digest","nonce","salt","secret","token","stderr","stdout","title","tooloutput"]),So=["accesstoken","apikey","authorization","authtoken","content","credential","filepath","logpath","outputpath","password","payload","privatekey","prompt","rawevent","rawtext","refreshtoken","requestbody","responsebody","secret","stderr","stdout","token","tooloutput"],Ao=new Set(["onchainosagentlistresultjson","onchainosagentlistdiagnostictext","systemconfigjson"]),ho=new Set(["agentId","agentPlatform","aiProvider","cacheName","causeCode","causeType","causeVariant","checkpoint","code","communicationClass","component","eventFamily","eventName","endpoint","errorCategory","errorCode","errorRetryability","errorSyscall","exitCode","fromAgentId","grpcMethod","jobId","kind","method","onchainosAgentId","onchainosVersion","onchainosVersionProbeStatus","operation","originPlatform","outcome","participantAgentIds","peerAgentId","phase","platform","provider","reason","releaseBase","releaseChannel","releaseCode","replayOutcome","role","runId","runtimeContainer","runtimeSurface","senderAgentId","source","stage","status","streamErrorCode","streamType","subcommand","systemEvent","taskId","taskMode","toAgentId","transport","transportFailure","transportProtocol","type","workloadClass"]),To=["eventName","errorCategory","errorCode","errorSyscall","cacheName","component","method","operation","phase","reason","code","provider","type","kind","status","subcommand"],Ro=new Set([a.GATEWAY_STARTED,a.GATEWAY_STOPPED,a.GATEWAY_DISCONNECTED,a.GATEWAY_REQUEST,a.GATEWAY_DELIVERY_BUFFERED,a.DAEMON_LIFECYCLE_SKIPPED,a.DAEMON_LIFECYCLE_REQUESTED,a.PROMPT_USER_CHECKPOINT,a.USER_WATCH_STARTED,a.USER_WATCH_EVENT_DELIVERED,a.CHANNEL_READY,a.CONVERSATION_STARTED,a.EVALUATE_CONVERSATION_STARTED,a.CONVERSATION_DELETED,a.USER_DISPATCHED,a.SESSION_DISPATCHED,a.SESSION_CREATED,a.SESSION_DELETED,a.SESSION_AUTO_RECOVERED,a.INBOUND_DELIVERED,a.INBOUND_DM_RAW,a.INBOUND_GROUP_RAW,a.INBOUND_IGNORED_DUPLICATE,a.INBOUND_IGNORED_NON_BUSINESS,a.AI_RUN_STARTED,a.AI_RUN_COMPLETED,a.AI_RUN_SKIPPED,a.RUNTIME_DETECTED,a.PROVIDER_READINESS_CHECKED,a.PROVIDER_SWITCHED,a.JOB_PROVIDER_BOUND,a.ONCHAINOS_VERSION_OBSERVED,a.USER_CHANNEL_MESSAGE_DELIVERED,a.SYSTEM_NOTIFICATION_RECEIVED,a.SYSTEM_NOTIFICATION_ROUTED,a.HERMES_SESSION_ROUTE_BINDING,a.INBOUND_BLOCKED_ADDRESS_MISMATCH,a.INBOUND_BLOCKED_INELIGIBLE,a.MESSAGE_ELIGIBILITY_CHECKED,a.INBOUND_BLOCKED_SENSITIVE,a.INBOUND_DROP_DM_INVALID_PAYLOAD,a.INBOUND_DROP_DM_NON_SYSTEM,a.INBOUND_DROP_DM_UNKNOWN_AGENT,a.INBOUND_DROP_EMPTY_CONTENT,a.INBOUND_DROP_MISSING_JOBID,a.INBOUND_DROP_INVALID_JOBID,a.INBOUND_DROP_UNSUPPORTED_MSGTYPE,a.DM_DELIVERED,a.DM_FALLBACK_TO_BACKUP,a.DM_WHITELIST_FAIL_OPEN,a.INBOUND_BUYER_PENDING,a.INBOUND_BUYER_SESSION_AUTO_RECOVERED,a.MESSAGE_SENT,a.AGENT_CLIENT_CREATED,a.AGENT_CLIENT_REMOVED,a.AGENT_STREAM_ERROR,a.AGENT_STREAM_RECOVERED,a.AGENT_STREAM_RECOVERY_REPLAY_COMPLETED,a.AGENT_STREAM_RECOVERY_REPLAY_TERMINATED,a.ADDRESS_SYNC_COMPLETED,a.AGENTS_REFRESHED,a.AGENTS_WAKEUP_NOTIFIED,a.AGENT_LIST_QUERIED,a.BOOTSTRAP_APPLIED,a.CONFIG_SENSITIVE_WORDS_REFRESHED,a.CONFIG_SYSTEM_REFRESHED,a.CONVERSATION_HISTORY_QUERIED,a.FILE_DOWNLOADED,a.FILE_UPLOADED,a.GROUP_CONSENT_CHANGED,a.INBOUND_HANDLER_ENTERED,a.MESSAGE_RECEIVED,a.OFFLINE_REPLAY_MESSAGE_REPLAYED,a.AGENT_REFRESH_SESSION_EXPIRED,a.OUTBOUND_ELIGIBILITY_CHECKED,a.OUTBOUND_BLOCKED_INELIGIBLE,a.AGENT_INSTALLATION_SUMMARY,a.XMTP_HISTORY_SYNC_REQUESTED,a.XMTP_DEBUG_SYNC_REQUESTED,a.XMTP_DEBUG_SYNC_COMPLETED,a.PENDING_CONVERSATION_DENIED,a.PENDING_LIST_QUERIED,a.SESSION_KEY_DERIVED,a.SESSIONS_QUERIED,a.SYNC_TICK_COMPLETED,a.XMTP_RATE_LIMIT_COOLDOWN_STARTED,a.XMTP_RATE_LIMIT_CREATE_SUPPRESSED,a.XMTP_RATE_LIMIT_PROBE,a.XMTP_RATE_LIMIT_RECOVERED]),Ce=256,vt=128,ke={},G=rn(),sn=class e{static instance;initialized=!1;buffer=[];constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}init(n){if(this.initialized){ut("[logger] Already initialized, skipping.");return}try{ke=pt(n.release),n.runtimeMetadata&&an(n.runtimeMetadata),y.init({dsn:n.dsn,release:n.release,environment:n.environment,maxBreadcrumbs:0,beforeBreadcrumb:()=>null,beforeSend:r=>wo(r),isInner:!1});let t={projectName:n.projectName,agentPlatform:n.agentPlatform};n.runtimeContainer&&(t.runtimeContainer=n.runtimeContainer);for(let r of["aiProvider","runtimeSurface","onchainosVersion","onchainosVersionProbeStatus"])t[r]=G[r]??"unknown";y.setTags(t)}catch{return}this.initialized=!0,this.flush()}info(n,t){let r=e.sanitizeExtra(Qe({flowId:kt,...ke,...G,...t??{}}));if(en("info",n,r),!!Ro.has(n)){if(!this.initialized){this.buffer.push({level:"info",message:n,extra:r});return}this.captureInfo(n,r)}}captureInfo(n,t){try{y.withScope(r=>{e.applyDiagnostics(r,n,t),y.captureEvent({level:"info",message:n,extra:{...t,eventName:n}})})}catch{}}error(n,t,r){let o=e.sanitizeExtra(Qe({flowId:kt,...ke,...G,...r??{}}));if(en("error",n,o),!this.initialized){this.buffer.push({level:"error",message:n,error:t,extra:o});return}this.captureError(n,t,o)}captureError(n,t,r){try{let o=Dt(n,t,r),s={...r,...o};y.withScope(i=>{i.setLevel("error"),e.applyDiagnostics(i,n,s),y.captureException(e.createSentryEvent(n),{extra:{...s,eventName:n}})})}catch{}}async shutdown(){try{await y.close(5e3)}catch{await y.flush(5e3)}}flush(){for(;this.buffer.length>0;){let n=this.buffer.shift();n.level==="info"?this.captureInfo(n.message,n.extra??{}):this.captureError(n.message,n.error,n.extra??{})}}static sanitizeExtra(n){return Object.fromEntries(Object.entries(n).filter(([,t])=>t!==void 0).filter(([t])=>!e.isBlockedExtraKey(t)).map(([t,r])=>[t,e.safeValueForKey(t,r)]))}static isBlockedExtraKey(n){let t=n.toLowerCase(),r=e.normalizeSensitiveKey(n);return Pt.has(t)||Pt.has(r)?!0:e.isSafeMetricKey(r)?!1:So.some(o=>r.includes(o))}static isSafeMetricKey(n){return/(bytes|count|length|ms|size)$/.test(n)}static safeValueForKey(n,t){return typeof t=="string"&&Ao.has(e.normalizeSensitiveKey(n))?t:e.safeValue(t)}static normalizeSensitiveKey(n){return n.toLowerCase().replace(/[^a-z0-9]/g,"")}static safeValue(n){if(typeof n=="string")return n.length<=Ce?n:`${n.slice(0,Ce)}...`;if(n==null||typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="bigint")return n.toString();if(n instanceof Error)return{name:n.name,messageLength:n.message.length};if(Array.isArray(n))return n.slice(0,20).map(r=>e.safeValue(r));if(typeof n=="object")return Object.fromEntries(Object.entries(n).slice(0,50).filter(([,r])=>r!==void 0).filter(([r])=>!e.isBlockedExtraKey(r)).map(([r,o])=>[r,e.safeValueForKey(r,o)]));let t=String(n);return t.length<=Ce?t:`${t.slice(0,Ce)}...`}static tagValue(n){let t=String(n);return t.length<=vt?t:`${t.slice(0,vt)}...`}static normalizeTagKey(n){return n.replace(/[^A-Za-z0-9_.:-]+/g,"_").slice(0,32)||"unknown"}static applyDiagnostics(n,t,r){let o={eventName:t,...r};for(let[i,d]of Object.entries(o))ho.has(i)&&n.setTag(e.normalizeTagKey(i),e.tagValue(d));let s=["a2a",t];for(let i of To){let d=o[i];d&&s.push(`${i}:${e.tagValue(d)}`)}n.setFingerprint(s)}static toPascalCase(n){return n.split(/[\s:]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}static createSentryEvent(n){let t=new Error(n);return t.name=e.toPascalCase(n),t.stack=`${t.name}: ${n}`,t}},f=sn.getInstance(),Lt=e=>f.init(e),xt=()=>f.shutdown()});function Pe(){return Ae()}function $t(e){Mt.has(e)||(Mt.add(e),u(`[okx-a2a:runtime] using legacy OpenClaw PluginRuntime API api=${e}`))}function ee(){let e=Pe().config;if(typeof e.current=="function")return e.current();if(typeof e.loadConfig=="function")return $t("config.loadConfig"),e.loadConfig();throw new Error("Unsupported OpenClaw PluginRuntime: neither config.current nor config.loadConfig is available")}function Oo(e){let n=e.split(":");return n[0]==="agent"&&n[1]?n[1]:"main"}function Do(){try{let e=ee().agents?.list?.map(n=>n.id).filter(Boolean)??[];if(e.length>0)return[...new Set(e)]}catch{}return["main"]}function Gt(e){let n=Pe().agent.session;if(typeof n.resolveStorePath!="function"||typeof n.loadSessionStore!="function")throw new Error("Unsupported OpenClaw PluginRuntime: no row-level or legacy session reader is available");$t("agent.session.loadSessionStore");let t=n.resolveStorePath(void 0,{agentId:e});return n.loadSessionStore(t,{skipCache:!0})}function jt(e){let n=Pe().agent.session,t=Oo(e);return typeof n.getSessionEntry=="function"?n.getSessionEntry({agentId:t,sessionKey:e,readConsistency:"latest"}):Gt(t)[e]}function dn(){let e=Pe().agent.session,n=[],t=new Set;for(let r of Do()){let o=typeof e.listSessionEntries=="function"?e.listSessionEntries({agentId:r,readConsistency:"latest",readOnly:!0}):Object.entries(Gt(r)).map(([s,i])=>({sessionKey:s,entry:i}));for(let s of o)t.has(s.sessionKey)||(t.add(s.sessionKey),n.push(s))}return n}function Ft(){return Object.fromEntries(dn().map(({sessionKey:e,entry:n})=>[e,n]))}var Mt,cn=m(()=>{"use strict";I();he();Mt=new Set});function bo(e=Z()){return(0,Bt.join)(e,"openclaw-gateway.json")}function Ht(e,n=Z()){let t=Oe(n),r=bo(t),o=`${r}.${process.pid}.tmp`,s={version:1,url:e.url,...e.password?{password:e.password}:{},...e.token?{token:e.token}:{},updatedAt:new Date().toISOString(),source:"openclaw-plugin"};(0,b.writeFileSync)(o,`${JSON.stringify(s,null,2)}
|
|
4
|
+
`,{encoding:"utf8",mode:384});try{(0,b.chmodSync)(o,384)}catch{}(0,b.renameSync)(o,r);try{(0,b.chmodSync)(r,384)}catch{}return r}var b,Bt,Xt=m(()=>{"use strict";b=require("node:fs"),Bt=require("node:path");Ze()});function oe(e){return e.includes(te)||e.includes(`:${re}:`)}function ve(e){if(!(!e||e==="direct"||e==="@direct"))return e.startsWith("telegram:")||e.startsWith("@")?e:`telegram:${e}`}function ne(e){if(typeof e=="number"&&Number.isFinite(e))return String(Math.trunc(e));if(typeof e=="string")return e.trim()||void 0}function qt(e){if(e.length!==0)return e[0]==="topic"?ne(e[1]):e[0]==="thread"?e.length>=3?ne(e.slice(2).join(":")):ne(e[1]):ne(e[0])}function un(e,n){return!e||!n||!e.startsWith("telegram:")||/:topic:\d+$/.test(e)?e:`${e}:topic:${n}`}function Co(e,n){let t=e.split(":");if(n==="telegram"){let r=t.indexOf("telegram"),o=r>=0?t.slice(r+1):t.slice(3),s=o.findIndex(d=>d==="direct"||d==="dm");if(s>=0){let d=s>0?o[s-1]:void 0,c=o[s+1]==="telegram"&&o[s+2]?`telegram:${o[s+2]}`:o[s+1],l=qt(o.slice(s+2));return{to:un(ve(c),l),accountId:d,threadId:l}}let i=o.indexOf("group");if(i>=0){let d=i>0?o[i-1]:void 0,c=o[i+1]==="telegram"&&o[i+2]?`telegram:${o[i+2]}`:o[i+1],l=qt(o.slice(i+2));return{to:un(ve(c),l),accountId:d,threadId:l}}if(o[0]==="telegram"&&o[1])return{to:`telegram:${o[1]}`,accountId:void 0};if(o[1]==="telegram"&&o[2])return{to:`telegram:${o[2]}`,accountId:o[0]};if(o.length>=2)return{to:ve(o[1]),accountId:o[0]};if(o.length===1)return{to:ve(o[0]),accountId:void 0}}return{to:t[4],accountId:void 0}}function Yt(e,n){return typeof e!="string"||e==="direct"||e==="@direct"?n:e}function Vt(e){return ko[e]??e}function Wt(e){let n=[e],t=e.split(":");if(t.length<6||t[0]!=="agent"||t[2]!=="telegram"||t[3]!=="direct"&&t[3]!=="dm"||!t[4])return n;let r=t[4],o=t.slice(5),s;if(o[0]==="topic"&&o[1])s=`agent:${t[1]}:telegram:direct:${r}:thread:${r}:${o.slice(1).join(":")}`;else if(o[0]==="thread"){let i=o.length>=3?o.slice(2).join(":"):o[1];i&&(s=`agent:${t[1]}:telegram:direct:${r}:topic:${i}`)}return s&&s!==e&&n.push(s),n}function Po(e){if(e==="agent:main")return"main";let n=e.split(":");return n.length<4||n[0]!=="agent"||!n[1]||!n[2]||oe(e)||n[2]==="backup"?null:n[2]}function ln(e,n){if(!Jt(n))return null;let t=n,r=t.deliveryContext?.channel??t.lastChannel??t.origin?.provider??Po(e);if(!r)return null;let o=Vt(r),s=Co(e,o),i=Yt(t.deliveryContext?.to,s.to)??Yt(t.lastTo,s.to)??s.to,d=t.deliveryContext?.accountId??s.accountId,c=ne(t.deliveryContext?.threadId??t.origin?.threadId??t.lastThreadId??s.threadId);return{channel:o,target:{sessionKey:e,to:o==="telegram"?un(i,c):i,accountId:d,threadId:c,updatedAt:t.lastInteractionAt??t.updatedAt??Date.now()}}}function zt(e){let n=new Map,t=new Map;for(let[r,o]of Object.entries(e)){if(oe(r)||!Jt(o))continue;let s=o;if(s.spawnedBy||s.subagentRole)continue;let i=ln(r,o);if(!i)continue;let{channel:d,target:c}=i,{to:l,updatedAt:g}=c;l&&(!t.get(d)||g>(n.get(d)?.updatedAt??0))&&t.set(d,l);let p=n.get(d);(!p||g>p.updatedAt)&&n.set(d,c)}for(let[r,o]of n)if(!o.to){let s=t.get(r);s&&(o.to=s)}for(let[r,o]of n)u(`[findLatestUserSessions] channel=${r} winner=${o.sessionKey} to=${o.to??"(none)"} accountId=${o.accountId??"(none)"} interactedAt=${o.updatedAt}`);return n}function Jt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var te,re,ko,Qt=m(()=>{"use strict";I();te="okx-xmtp",re="okx-a2a";ko={dashboard:"webchat"}});function er(e){if(oe(e))return null;try{for(let n of Wt(e)){let t=ln(n,jt(n));if(t)return t}return null}catch(n){return nr("find_user_session_target",n),null}}function Zt(e){return e.toLowerCase().startsWith("0x")}function vo(e){if(typeof e=="string")return`${te}:${e}`;let n="myAgentId"in e&&"toAgentId"in e?new URLSearchParams({my:e.myAgentId,to:e.toAgentId,job:e.jobId}):new URLSearchParams({my:e.myXmtpAddress,to:e.toXmtpAddress,job:e.jobId});return`${te}:${n.toString()}`}function gn(e){let n=`${te}:`,t=e.indexOf(n);if(t===-1)return null;let r=new URLSearchParams(e.slice(t+n.length)),o=r.get("myAgentId")||r.get("myagentid"),s=r.get("toAgentId")||r.get("toagentid"),i=r.get("my"),d=r.get("to"),c=r.get("job"),l=r.get("gid");return o&&s&&c?{format:"agent",myAgentId:o,toAgentId:s,jobId:c,xmtpGroupId:l??""}:!i||!d||!c?null:!Zt(i)&&(d==="_"||!Zt(d))?{format:"agent",myAgentId:i,toAgentId:d,jobId:c,xmtpGroupId:l??""}:{format:"address",myXmtpAddress:i,toXmtpAddress:d,jobId:c,xmtpGroupId:l??""}}function se(e){if(!e)return"";let n=gn(e);return n?.jobId?n.jobId:/(?:^|:)backup:([^:&]+)/.exec(e)?.[1]??""}function ae(e){let n=e.taskId?.trim()||se(e.scopeKey)||se(e.sessionKey);return n?{taskId:n}:{}}function nr(e,n){u(`[okx-a2a:session] session-store lookup failed; continuing phase=${e} error=${n instanceof Error?n.message:String(n)}`)}function Ko(e){let n=typeof e=="string"?e:vo(e);return(0,ie.buildAgentSessionKey)({agentId:"main",channel:re,peer:{kind:"group",id:n}})}function tr(){let e=ee().agents?.list;if(e&&e.length>0){let n=e.find(t=>t.id==="main");return n?n.id:e[0].id}return"main"}function rr(){return(0,ie.buildAgentSessionKey)({agentId:tr(),channel:re,peer:{kind:"group",id:"backup"}})}function Lo(e){return(0,ie.buildAgentSessionKey)({agentId:tr(),channel:re,peer:{kind:"group",id:`backup:${e}`}})}function P(){try{return zt(Ft())}catch(e){return nr("find_latest_user_sessions",e),new Map}}function or(e){let n=new Set,t=[...e.sessionKey?[e.sessionKey]:[],...Array.isArray(e.sessionKeys)?e.sessionKeys:[]].filter(o=>o.trim()),r=[];e.jobId&&r.push({jobId:e.jobId,myAgentId:e.myAgentId,toAgentId:e.toAgentId,myXmtpAddress:e.myXmtpAddress,toXmtpAddress:e.toXmtpAddress});for(let o of t){if(o.startsWith("agent:")){n.add(o);continue}let s=$o(o);if(s){n.add(Lo(s));continue}let i=sr(o);if(i){r.push(i);continue}let d=gn(o);if(d){r.push(Mo(d));continue}n.add(Ko(o))}for(let o of xo())for(let s of r)if(Uo(o,s)){n.add(o);break}return[...n].sort()}function xo(){return dn().map(({sessionKey:e})=>e).filter(oe)}function Uo(e,n){let t=gn(e);if(t)return Go(t,n);let r=sr(e);return r?!(n.jobId&&r.jobId!==n.jobId||n.myAgentId&&r.myAgentId!==n.myAgentId||n.toAgentId&&r.toAgentId!==n.toAgentId||n.myXmtpAddress&&!n.myAgentId||n.toXmtpAddress&&!n.toAgentId):!n.jobId||n.myAgentId||n.toAgentId||n.myXmtpAddress||n.toXmtpAddress?!1:se(e)===n.jobId}function Mo(e){return"myAgentId"in e?{myAgentId:e.myAgentId,toAgentId:e.toAgentId,jobId:e.jobId}:{myXmtpAddress:e.myXmtpAddress,toXmtpAddress:e.toXmtpAddress,jobId:e.jobId}}function sr(e){let n=e.split(":"),t=n.indexOf("job");return t<0||n[t+2]!=="my"||n[t+4]!=="to"||!n[t+1]||!n[t+3]||!n[t+5]?null:{jobId:Ke(n[t+1]),myAgentId:Ke(n[t+3]),toAgentId:Ke(n[t+5])}}function $o(e){return e.startsWith("backup:")?Ke(e.slice(7)):null}function Go(e,n){return n.jobId&&e.jobId!==n.jobId?!1:"myAgentId"in e?!(n.myAgentId&&e.myAgentId!==n.myAgentId||n.toAgentId&&e.toAgentId!==n.toAgentId||n.myXmtpAddress&&!n.myAgentId||n.toXmtpAddress&&!n.toAgentId):!(n.myXmtpAddress&&e.myXmtpAddress.toLowerCase()!==n.myXmtpAddress.toLowerCase()||n.toXmtpAddress&&e.toXmtpAddress.toLowerCase()!==n.toXmtpAddress.toLowerCase()||n.myAgentId&&!n.myXmtpAddress||n.toAgentId&&!n.toXmtpAddress)}function Ke(e){try{return decodeURIComponent(e)}catch{return e}}var ie,j=m(()=>{"use strict";I();ie=require("openclaw/plugin-sdk/routing");cn();Qt()});function ir(e){return e.reduce((n,[t,r])=>(r!=null&&(n[t]=String(r)),n),{})}function ar(e){let n=ft({jobId:e.jobId,sessionKey:e.sessionKey});return n===U?null:n}function C(e){return{...J({checkpoint:e.checkpoint,outcome:e.outcome,transport:"user_channel",eventFamily:"user_channel",deliveryId:ar(e)}),...ir([["component",jo],["source",e.source],["channel",e.channel],["sessionKey",e.sessionKey],["jobId",e.jobId],["direction",e.direction],["senderAgentId",e.senderAgentId],["receiverAgentId",e.receiverAgentId],["hasTo",e.hasTo===void 0?void 0:e.hasTo?"1":"0"]])}}function Le(e,n="success"){let t={};for(let[o,s]of Object.entries(e))s!=null&&(t[o]=String(s));let r=t.phase?.trim()??"";return{...J({checkpoint:r?`${Ho}${r}`:null,outcome:n,transport:"gateway_rpc",eventFamily:"lifecycle"}),...t}}function T(e){let n=Object.entries({component:Fo,operation:Bo,checkpoint:e.checkpoint,sessionKey:e.sessionKey,channel:e.channel??"",taskId:e.taskId??"",runId:e.runId??"",reason:e.reason??"",status:e.status??"",queued:e.queued??"",delayMs:e.delayMs??"",durationMs:e.durationMs??"",running:e.running??"",processing:e.processing??""}).filter(([,t])=>t!=="");return{...J({outcome:Yo[e.checkpoint],transport:"user_channel",eventFamily:"user_channel",deliveryId:ar({jobId:e.taskId,sessionKey:e.sessionKey})}),...n.reduce((t,[r,o])=>(t[r]=String(o),t),{})}}function fn(e){let{delivered:n,failed:t,abandoned:r}=e,o=n>0||t>0||r>0;return t===0&&r===0?{shouldEmit:o,outcome:"success"}:{shouldEmit:o,outcome:n>0?"partial":"failed"}}function dr(e){return{...J({checkpoint:Xo,outcome:fn(e).outcome,transport:"gateway_rpc",eventFamily:"outbound"}),...ir([["onchainosAgentId","*"],["source",qo],["deliveredCount",e.delivered],["failedCount",e.failed],["abandonedCount",e.abandoned],["batchSize",e.batchSize]])}}var jo,Fo,Bo,Ho,Xo,qo,Yo,de=m(()=>{"use strict";Ne();jo="openclaw_user_dispatch",Fo="openclaw_prompt_user_queue",Bo="xmtp_prompt_user",Ho="gateway/",Xo="outbound/outbox_drained",qo="gateway_outbox_drain";Yo={fallback_scheduled:"pending",queued:"pending",run_pending:"pending",dispatch_started:"pending",dispatch_completed:"success",run_completed:"success",dispatch_failed:"failed",fallback_fired:"timeout"}});var mr={};Se(mr,{callChatInject:()=>ue,callGateway:()=>A,callSessionsCreate:()=>ce,callSessionsDelete:()=>hn,callSessionsSend:()=>Tn,formatPairingErrorHint:()=>Me,gatewayExtra:()=>Le,onGatewayEvent:()=>_n,resolveGatewayRuntimeConfig:()=>In,stopGatewayClient:()=>An,syncGatewayConfigForNodeDaemon:()=>Sn});function pn(e){if(e){if(typeof e=="string")return e;if(typeof e=="object"&&e!==null&&"env"in e)return process.env[e.env]||void 0}}function Jo(e){return e&&(typeof e=="string"?{type:"string",configured:!0}:typeof e=="object"&&e!==null&&"env"in e?{type:"env",env:String(e.env),configured:!!pn(e)}:{type:typeof e,configured:!0})}function mn(e){if(!e||typeof e!="object")return e??null;if(Array.isArray(e))return e.map(t=>mn(t));let n={};for(let[t,r]of Object.entries(e)){if(/password|token|secret/i.test(t)){n[t]=Jo(r);continue}n[t]=mn(r)}return n}function Qo(e){try{return JSON.stringify(e)}catch{return"[unserializable]"}}function Zo(e){let n=e.params;if(!n||typeof n!="object"||Array.isArray(n))return ae({taskId:e.taskId});let t=n;return ae({taskId:e.taskId,sessionKey:typeof t.sessionKey=="string"?t.sessionKey:typeof t.key=="string"?t.key:""})}function S(e,n={}){let t=Le({phase:e,...n});u(`[gateway] ${e}: ${JSON.stringify(t)}`),f.info(e.startsWith("request_")?a.GATEWAY_REQUEST:a.GATEWAY_STARTED,{component:"openclaw_gateway",...t})}function B(e,n,t={},r=a.GATEWAY_CONNECT_FAILED){let o=Le({phase:e,component:"openclaw_gateway",...t},"failed");u(`[gateway] ${e}:`,n),f.error(r,n instanceof Error?n:new Error(String(n)),o)}function es(e){for(let n of yn)try{n(e)}catch(t){u("[gateway] event handler failed:",t)}}function _n(e){return yn.add(e),()=>{yn.delete(e)}}function ur(){S("ready_gate_reset",{hasSharedClient:!!w,hasConnected:R}),F=new Promise((e,n)=>{xe=e,Ue=n})}function lr(e,n,t){if(w!==e){S(`${n}_skip_clear_noncurrent`,t);return}try{e.stop?.()}catch(r){B(`${n}_stop_failed`,r,t)}w=null,R=!1,F=null,xe=null,Ue=null,S(`${n}_cleared_client`,t)}function ns(){if(w)return S("reuse_client",{hasConnected:R,hasReadyPromise:!!F}),{client:w,ready:F};let e=In(),{url:n,password:t,token:r}=e,o=(0,En.randomUUID)(),s=++zo;ur(),S("init_client",{clientSeq:s,instanceId:o,url:n,hasGatewayConfig:!!e.rawGatewayConfig,gatewayConfig:Qo(mn(e.rawGatewayConfig)),passwordConfigured:!!t,tokenConfigured:!!r,scopes:cr.join(",")});let i=new pr.GatewayClient({url:n,password:t,token:r,instanceId:o,clientName:"gateway-client",clientDisplayName:"okx-a2a-plugin",mode:"backend",role:"operator",scopes:[...cr],onHelloOk:()=>{S("hello_ok",{clientSeq:s,instanceId:o,url:n}),R=!0,xe?.()},onEvent:es,onClose:(d,c)=>{if(u(`[gateway] closed (${d}): ${c||"no reason"}`),f.info(a.GATEWAY_DISCONNECTED,{clientSeq:String(s),instanceId:o,url:n,code:String(d),reason:c||"no-reason",hadConnected:String(R)}),R){R=!1,ur();return}lr(i,"close_before_connect",{clientSeq:s,instanceId:o,url:n,code:d,reason:c||"no-reason"})},onConnectError:d=>{let c=d;if(c?.retryable){B("connect_error_retryable",d,{clientSeq:s,instanceId:o,url:n,retryable:"true",reason:c?.details?.reason??"retryable",code:c?.gatewayCode??c?.details?.code});return}B("connect_error",d,{clientSeq:s,instanceId:o,url:n,retryable:"false",code:c?.gatewayCode??c?.details?.code}),Ue?.(d instanceof Error?d:new Error(String(d))),lr(i,"connect_error",{clientSeq:s,instanceId:o,url:n,code:c?.gatewayCode??c?.details?.code,reason:c?.details?.reason})}});return w=i,S("start_client",{clientSeq:s,instanceId:o,url:n}),i.start(),{client:i,ready:F}}function In(){let n=ee().gateway;return{url:`ws://127.0.0.1:${gr(process.env.OPENCLAW_GATEWAY_PORT)??gr(n?.port)??Wo}`,password:pn(n?.auth?.password),token:pn(n?.auth?.token),rawGatewayConfig:n}}function gr(e){if(typeof e=="number"&&Number.isFinite(e)){let r=Math.trunc(e);return r>0&&r<=65535?r:null}if(typeof e!="string")return null;let n=e.trim();if(!/^\d+$/.test(n))return null;let t=Number.parseInt(n,10);return t>0&&t<=65535?t:null}function Sn(){let e=In();try{let n=Ht({url:e.url,password:e.password,token:e.token});return S("synced_node_gateway_config",{path:n,url:e.url,passwordConfigured:!!e.password,tokenConfigured:!!e.token}),n}catch(n){return B("sync_node_gateway_config_failed",n,{url:e.url,passwordConfigured:!!e.password,tokenConfigured:!!e.token},a.GATEWAY_CONNECT_FAILED),null}}function An(){if(w){try{w.stop()}catch{}w=null,F=null,xe=null,Ue=null,R=!1}}function Me(e){let n=e,t=n?.gatewayCode??n?.details?.code;if(!t)return null;let r=n?.details??{},o=[`code=${t}`];r.reason&&o.push(`reason=${r.reason}`),r.authReason&&o.push(`authReason=${r.authReason}`),Array.isArray(r.requestedScopes)&&r.requestedScopes.length&&o.push(`requestedScopes=${r.requestedScopes.join(",")}`),r.deviceId&&o.push(`deviceId=${r.deviceId}`),r.requestId&&o.push(`requestId=${r.requestId}`);let s=` (${o.join(", ")})`;switch(t){case"NOT_PAIRED":case"PAIRING_REQUIRED":return`Device pairing approval pending${s}. On the openclaw host run \`openclaw devices approve --latest\` to review and approve the pending request, then retry.`;case"AUTH_SCOPE_MISMATCH":return`Existing device token lacks the required scope${s}. On the openclaw host run \`openclaw devices list\` to find the operator deviceId, then \`openclaw devices rotate --device <id> --role operator --scope operator.admin\` to reissue a token with operator.admin, and restart openclaw.`;case"AUTH_TOKEN_MISSING":case"AUTH_TOKEN_MISMATCH":case"AUTH_DEVICE_TOKEN_MISMATCH":return`Gateway device token is missing or stale${s}. On the openclaw host run \`openclaw devices list\`, then \`openclaw devices remove <deviceId>\`, then restart openclaw to re-pair.`;default:return null}}async function A(e){let n=e.timeoutMs??Vo,t=Date.now(),r=Zo(e);S("request_start",{method:e.method,timeoutMs:n,hasSharedClient:!!w,hasConnected:R,...r});let{client:o,ready:s}=ns();try{await s}catch(d){let c=Date.now()-t;throw B("request_ready_failed",d,{method:e.method,durationMs:c,timeoutMs:n,...r,code:d?.gatewayCode??d?.code??d?.details?.code,reason:"gateway_ready_failed",communicationClass:"openclaw_gateway_connect"},a.GATEWAY_REQUEST_FAILED),d}let i=Date.now()-t;S("request_ready",{method:e.method,readyWaitMs:i,timeoutMs:n,hasConnected:R,...r});try{let d=await o.request(e.method,e.params,{timeoutMs:n});return S("request_done",{method:e.method,durationMs:Date.now()-t,timeoutMs:n,...r}),d}catch(d){let c=Date.now()-t,l=/timeout|timed out/i.test(String(d?.message??d??""));B("request_error",d,{method:e.method,durationMs:c,timeoutMs:n,readyWaitMs:i,...r,isTimeout:l,code:d?.gatewayCode??d?.code??d?.details?.code,reason:l?"gateway_request_timeout":"gateway_request_error",communicationClass:"openclaw_gateway_rpc"},a.GATEWAY_REQUEST_FAILED);let g=Me(d);if(g){let p=d?.message??String(d);try{d.message=`${p}
|
|
5
|
+
${g}`}catch{}}throw d}}async function ce(e){return A({method:"sessions.create",params:e})}async function hn(e){return A({method:"sessions.delete",params:e})}async function Tn(e){let n=e.idempotencyKey??(0,En.randomUUID)(),t={key:e.key,message:e.message,idempotencyKey:n};try{let r=await A({method:"sessions.send",params:t});return{runId:fr(r),raw:r}}catch(r){let o=r?.gatewayCode??r?.code,s=String(r?.message??"");if(o==="INVALID_REQUEST"&&s.includes("session not found")){await ce({key:e.key}),f.info(a.SESSION_AUTO_RECOVERED,{sessionKey:e.key,trigger:"sessions.send"});let i=await A({method:"sessions.send",params:t});return{runId:fr(i),raw:i}}throw r}}function fr(e){if(!e||typeof e!="object")return;let n=e.runId;return typeof n=="string"&&n.trim()?n:void 0}async function ue(e){try{return await A({method:"chat.inject",params:e})}catch(n){let t=n?.gatewayCode??n?.code,r=String(n?.message??"");if(t==="INVALID_REQUEST"&&r.includes("session not found"))return await ce({key:e.sessionKey}),f.info(a.SESSION_AUTO_RECOVERED,{sessionKey:e.sessionKey,trigger:"chat.inject"}),await A({method:"chat.inject",params:e});throw n}}var pr,En,Vo,Wo,cr,zo,w,F,xe,Ue,R,yn,H=m(()=>{"use strict";I();pr=require("openclaw/plugin-sdk/gateway-runtime"),En=require("node:crypto");cn();k();Xt();j();de();Vo=2e4,Wo=18789,cr=["operator.admin"],zo=0;w=null,F=null,xe=null,Ue=null,R=!1,yn=new Set});function Ir(e){if(e.toolName!=="exec")return null;let n=e.sessionKey?.trim(),t=new Set;for(let s of e.routeSessionKeys??[]){let i=s?.trim();i&&t.add(i)}if(n&&t.add(n),t.size===0)return null;wn(n);let r=e.params??{},o=ms(r.env)?r.env:{};return{...r,env:{...o,[os]:"openclaw",[ss]:"openclaw-gateway",[is]:"1",[ts]:n??[...t][0],[rs]:JSON.stringify([...t])}}}function Sr(e){let n=e.runId?.trim(),t=e.sessionKey?.trim();if(!t||!pe(t))return!1;Nn();let r=fs([t,...e.routeSessionKeys??[]]);return us(t,r),n&&fe.set(n,{sessionKeys:r,updatedAt:Date.now()}),!0}function Ar(e){let n=typeof e=="string"?e.trim():e?.runId?.trim(),t=typeof e=="string"?null:e?.sessionKey?.trim();n&&fe.delete(n),t&&pe(t)&&ls(t)}function $e(e){let n=new Set,t=e.sessionKey?.trim();t&&pe(t)&&n.add(t);let r=e.runId?.trim();if(r){Nn(e.now??Date.now());let o=fe.get(r);for(let s of o?.sessionKeys??[])n.add(s)}else if(!t||!pe(t))for(let o of gs(e.now??Date.now()))n.add(o);return[...n]}function wn(e){let n=e?.trim();!n||!cs(n)||(le={sessionKey:n,updatedAt:Date.now()})}function hr(e=Date.now()){return le?e-le.updatedAt>as?(le=null,null):le.sessionKey:null}function cs(e){return e.startsWith("job:")||e.startsWith("backup:")||/(?:^|[?&:])job=([^:&]+)/.test(e)}function pe(e){if(e==="agent:main")return!0;let n=e.split(":");if(n.length<4||n[0]!=="agent"||!n[1])return!1;let t=n[2];return!!(t&&t!=="okx-a2a"&&!ds.has(t))}function Nn(e=Date.now()){for(let[n,t]of fe)e-t.updatedAt>Er&&fe.delete(n);for(let[n,t]of N)e-t.updatedAt>Er&&N.delete(n)}function us(e,n){let t=N.get(e);N.set(e,{count:(t?.count??0)+1,updatedAt:Date.now(),routeSessionKeys:n}),Rn()}function ls(e){let n=N.get(e);if(n){if(n.count<=1){N.delete(e),Rn();return}N.set(e,{count:n.count-1,updatedAt:Date.now(),routeSessionKeys:n.routeSessionKeys}),Rn()}}function gs(e=Date.now()){Nn(e);let n=[...N.keys()];return n.length!==1?[]:N.get(n[0])?.routeSessionKeys??[]}function fs(e){let n=new Set;for(let t of e){let r=t?.trim();r&&pe(r)&&n.add(r)}return[...n]}function Rn(){try{let e=ps();(0,X.mkdirSync)((0,ge.dirname)(e),{recursive:!0,mode:448});let t={version:1,updatedAt:Date.now(),origins:[...N.entries()].map(([o,s])=>({sessionKey:o,count:s.count,updatedAt:s.updatedAt,routeSessionKeys:s.routeSessionKeys}))},r=`${e}.${process.pid}.tmp`;(0,X.writeFileSync)(r,`${JSON.stringify(t)}
|
|
6
|
+
`,{encoding:"utf8",mode:384}),(0,X.renameSync)(r,e)}catch(e){console.log(`[okx-a2a:hook] failed to persist gateway route origins: ${e instanceof Error?e.message:String(e)}`)}}function ps(e=process.env){let n=e.OKX_AGENT_TASK_HOME?.trim()||(0,ge.join)((0,_r.homedir)(),".okx-agent-task");return(0,ge.join)(n,"run","gateway-route-origins.json")}function ms(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var X,_r,ge,ts,rs,os,ss,is,as,Er,ds,le,fe,N,On=m(()=>{"use strict";X=require("node:fs"),_r=require("node:os"),ge=require("node:path"),ts="OKX_A2A_CURRENT_GATEWAY_SESSION_KEY",rs="OKX_A2A_CURRENT_GATEWAY_SESSION_KEYS",os="OKX_A2A_GATEWAY_PROVIDER",ss="OKX_A2A_RUNTIME_CONTEXT",is="OKX_A2A_IN_GATEWAY",as=12e4,Er=30*6e4,ds=new Set(["heartbeat","cron","webhook","voice"]),le=null,fe=new Map,N=new Map});function Es(e=process.env){return e.OKX_AGENT_TASK_HOME?.trim()||(0,bn.join)((0,Rr.homedir)(),".okx-agent-task")}function _s(e=process.env){return e.OKX_A2A_SESSION_STORE_DB_PATH?.trim()||(0,bn.join)(Es(e),"sqlite","session-store.sqlite")}function Ge(e){let n=h(e.jobId)??se(e.sessionKey);return n?Is(Ss(n,e.dbPath??_s())):[]}function Is(e){let n=new Set,t=[];for(let r of e){let o=Dn(h(r.gatewaySessionKey)??h(r.sessionKey)??""),s=Ts(o);!o||!s||n.has(s)||(n.add(s),t.push(o))}return t}function Ss(e,n){if(!(0,Tr.existsSync)(n))return[];let{DatabaseSync:t}=As(),r=new t(n,{readOnly:!0});try{if(r.exec("PRAGMA busy_timeout=5000"),!r.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='job_provider_bindings'").get())return[];let s=r.prepare("SELECT provider, gateway_routes_json FROM job_provider_bindings WHERE job_id = ?").get(e);return s?.provider!=="openclaw"||typeof s.gateway_routes_json!="string"?[]:hs(s.gateway_routes_json)}catch(o){return console.log(`[okx-a2a:stored-routes] failed to resolve job route jobId=${e}: ${o instanceof Error?o.message:String(o)}`),[]}finally{r.close()}}function As(){let e=process.emitWarning;process.emitWarning=((n,...t)=>{if(!((typeof n=="string"?n:n.message).includes("SQLite is an experimental feature")&&t.some(o=>o==="ExperimentalWarning")))return e.call(process,n,...t)});try{return require("node:sqlite")}finally{process.emitWarning=e}}function hs(e){try{let n=JSON.parse(e);if(!Array.isArray(n))return[];let t=[];for(let r of n){if(!ws(r))continue;let o=h(typeof r.platform=="string"?r.platform:null),s=Dn(h(typeof r.sessionKey=="string"?r.sessionKey:null)??"");if(!o||!s)continue;let i=Dn(h(typeof r.gatewaySessionKey=="string"?r.gatewaySessionKey:null)??""),d=h(typeof r.chatId=="string"?r.chatId:null),c=h(typeof r.threadId=="string"?r.threadId:null),l=h(typeof r.updatedAt=="string"?r.updatedAt:null);t.push({platform:o,sessionKey:s,...i?{gatewaySessionKey:i}:{},...d?{chatId:d}:{},...c?{threadId:c}:{},...l?{updatedAt:l}:{}})}return t}catch{return[]}}function Ts(e){let n=h(e);if(!n)return null;if(n==="agent:main")return"main";if(n.startsWith("backup:"))return null;let t=n.split(":");if(t.length<4||t[0]!=="agent"||!t[1])return null;let r=t[2];return!r||r==="okx-a2a"||r==="backup"||ys.has(r)?null:r}function Dn(e){let n=h(e);if(!n)return"";let t=n.split(":");if(t.length<4||t[0]!=="agent")return n;let r=t[2],o=t[3];if(r!=="telegram")return n;if((o==="direct"||o==="dm")&&t[4]){if(t[5]==="thread")return n;let s=Rs(t.slice(5));return s?`agent:${t[1]}:telegram:direct:${t[4]}:topic:${s}`:`agent:${t[1]}:telegram:direct:${t[4]}`}if(o==="group"&&t[4]){let s=t[5]==="topic"?t[6]:t[5];return s?`agent:${t[1]}:telegram:group:${t[4]}:topic:${s}`:`agent:${t[1]}:telegram:group:${t[4]}`}return n}function Rs(e){if(e.length!==0)return e[0]==="topic"?e[1]||void 0:e[0]==="thread"?e.length>=3?e.slice(2).join(":")||void 0:e[1]||void 0:e[0]||void 0}function ws(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function h(e){let n=e?.trim();return n||null}var Tr,Rr,bn,ys,Cn=m(()=>{"use strict";Tr=require("node:fs"),Rr=require("node:os"),bn=require("node:path");j();ys=new Set(["heartbeat","cron","webhook","voice"])});function vn(e){let n=v(e.jobId)??Cs([e.content,...e.contents??[]]);if(!n)return console.log("[okx-a2a:stored-routes] skipped delivered route bind reason=missing_job_id"),[];let t=e.sessionKeys.map(i=>Os(i)).filter(i=>!!i);if(t.length===0)return[];let r=e.dbPath??Ps(),{DatabaseSync:o}=vs(),s=new o(r);try{s.exec("PRAGMA busy_timeout=5000"),s.exec(`
|
|
7
7
|
CREATE TABLE IF NOT EXISTS job_provider_bindings (
|
|
8
8
|
job_id TEXT PRIMARY KEY,
|
|
9
9
|
provider TEXT NOT NULL CHECK (provider IN ('codex', 'claude', 'hermes', 'openclaw')),
|
|
@@ -11,20 +11,20 @@ ${g}`}catch{}}throw d}}async function ce(e){return A({method:"sessions.create",p
|
|
|
11
11
|
created_at TEXT NOT NULL,
|
|
12
12
|
updated_at TEXT NOT NULL
|
|
13
13
|
)
|
|
14
|
-
`);let i=new Date().toISOString();s.prepare("INSERT OR IGNORE INTO job_provider_bindings(job_id, provider, created_at, updated_at) VALUES (?, 'openclaw', ?, ?)").run(n,i,i);let d=s.prepare("SELECT provider, gateway_routes_json FROM job_provider_bindings WHERE job_id = ?").get(n);if(d?.provider!=="openclaw")return[];let c=Ds(d.gateway_routes_json),l=new Set(c.map(p=>p.platform)),g=[];for(let p of t)l.has(p.platform)||(c.push(p),l.add(p.platform),g.push(p.gatewaySessionKey));return g.length===0?[]:(s.prepare("UPDATE job_provider_bindings SET gateway_routes_json = ?, updated_at = ? WHERE job_id = ? AND provider = 'openclaw'").run(JSON.stringify(c),i,n),console.log(`[okx-a2a:stored-routes] bound delivered route jobId=${n} sessionKeys=${g.join(",")}`),g)}catch(i){return console.log(`[okx-a2a:stored-routes] failed to bind delivered route jobId=${n}: ${i instanceof Error?i.message:String(i)}`),[]}finally{s.close()}}function Os(e){let n=Nr(P(e)??"");if(!n)return null;let t=Or(n);if(!t)return null;let r=bs(n);return{platform:t,sessionKey:n,gatewaySessionKey:n,...r.chatId?{chatId:r.chatId}:{},...r.threadId?{threadId:r.threadId}:{},updatedAt:new Date().toISOString()}}function Ds(e){if(typeof e!="string"||!e.trim())return[];try{let n=JSON.parse(e);if(!Array.isArray(n))return[];let t=[];for(let r of n){if(!Ks(r))continue;let o=Nr(P(typeof r.gatewaySessionKey=="string"?r.gatewaySessionKey:null)??P(typeof r.sessionKey=="string"?r.sessionKey:null)??""),s=Or(o);!o||!s||t.push({platform:s,sessionKey:o,gatewaySessionKey:o,...typeof r.chatId=="string"&&r.chatId.trim()?{chatId:r.chatId.trim()}:{},...typeof r.threadId=="string"&&r.threadId.trim()?{threadId:r.threadId.trim()}:{},...typeof r.updatedAt=="string"&&r.updatedAt.trim()?{updatedAt:r.updatedAt.trim()}:{updatedAt:new Date().toISOString()}})}return t}catch{return[]}}function bs(e){let n=e.split(":");if(n.length<4||n[0]!=="agent")return{};let t=n[2],r=n[3];if(t==="discord"&&r==="thread")return{...n[4]?{chatId:n[4]}:{},...n[5]?{threadId:n[5]}:{}};if(t==="discord"&&(r==="channel"||r==="dm"))return n[4]?{chatId:n[4]}:{};if(t==="telegram"&&r==="direct"){let o=kn(n.slice(5));return{...n[4]?{chatId:n[4]}:{},...o?{threadId:o}:{}}}if(t==="telegram"&&r==="dm"){let o=kn(n.slice(5));return{...n[4]?{chatId:n[4]}:{},...o?{threadId:o}:{}}}if(t==="telegram"&&r==="group"){let o=n[5]==="topic"?n[6]:n[5];return{...n[4]?{chatId:n[4]}:{},...o?{threadId:o}:{}}}return{}}function Nr(e){let n=P(e);if(!n)return"";let t=n.split(":");if(t.length<4||t[0]!=="agent")return n;let r=t[2],o=t[3];if(r!=="telegram")return n;if((o==="direct"||o==="dm")&&t[4]){if(t[5]==="thread")return n;let s=kn(t.slice(5));return s?`agent:${t[1]}:telegram:direct:${t[4]}:topic:${s}`:`agent:${t[1]}:telegram:direct:${t[4]}`}if(o==="group"&&t[4]){let s=t[5]==="topic"?t[6]:t[5];return s?`agent:${t[1]}:telegram:group:${t[4]}:topic:${s}`:`agent:${t[1]}:telegram:group:${t[4]}`}return n}function kn(e){if(e.length!==0)return e[0]==="topic"?e[1]||void 0:e[0]==="thread"?e.length>=3?e.slice(2).join(":")||void 0:e[1]||void 0:e[0]||void 0}function Cs(e){for(let n of e){let t=P(n);if(!t)continue;let r=/\b0x[a-fA-F0-9]{64}\b/.exec(t);if(r?.[0])return r[0]}return null}function Or(e){let n=P(e);if(!n)return null;if(n==="agent:main")return"main";if(n.startsWith("backup:"))return null;let t=n.split(":");if(t.length<4||t[0]!=="agent"||!t[1])return null;let r=t[2];return!r||r==="okx-a2a"||r==="backup"||Ns.has(r)?null:r}function ks(e=process.env){return e.OKX_AGENT_TASK_HOME?.trim()||(0,vn.join)((0,wr.homedir)(),".okx-agent-task")}function vs(e=process.env){return e.OKX_A2A_SESSION_STORE_DB_PATH?.trim()||(0,vn.join)(ks(e),"sqlite","session-store.sqlite")}function Ps(){let e=process.emitWarning;process.emitWarning=((n,...t)=>{if(!((typeof n=="string"?n:n.message).includes("SQLite is an experimental feature")&&t.some(o=>o==="ExperimentalWarning")))return e.call(process,n,...t)});try{return require("node:sqlite")}finally{process.emitWarning=e}}function Ks(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function P(e){let n=e?.trim();return n||null}var wr,vn,Ns,Dr=m(()=>{"use strict";wr=require("node:os"),vn=require("node:path"),Ns=new Set(["heartbeat","cron","webhook","voice"])});var Fe={};Se(Fe,{isPromptUserSessionRunning:()=>xs,markPromptUserSessionEnded:()=>Un,markPromptUserSessionRunning:()=>Ln,promptUserSentryExtra:()=>T,queuePromptUserAction:()=>Ls});function K(e){let n=br.get(e);return n||(n={running:!1,processing:!1,queue:[]},br.set(e,n)),n}function Kn(e,n,t){e.fallbackTimer&&(clearTimeout(e.fallbackTimer),e.fallbackTimer=void 0,n&&u(`[xmtp_prompt_user:queue] fallback cleared sessionKey=${n}${t?` reason=${t}`:""}`))}function xn(e,n){Kn(n,e,"reschedule");let t=n.queue[0];if(!t||n.processing)return;let r=Math.max(0,t.deadlineAt-Date.now());u(`[xmtp_prompt_user:queue] fallback scheduled sessionKey=${e} channel=${t.channel} delayMs=${r} queued=${n.queue.length}`),f.info(a.PROMPT_USER_CHECKPOINT,T({checkpoint:"fallback_scheduled",sessionKey:e,channel:t.channel,taskId:t.taskId,delayMs:r,queued:n.queue.length})),n.fallbackTimer=setTimeout(()=>{let o=K(e);o.fallbackTimer=void 0,u(`[xmtp_prompt_user:queue] fallback fired sessionKey=${e} queued=${o.queue.length}`),f.info(a.PROMPT_USER_CHECKPOINT,T({checkpoint:"fallback_fired",sessionKey:e,taskId:o.queue[0]?.taskId,queued:o.queue.length,reason:"fallback_timeout"})),ye(e,"fallback_timeout")},r)}async function ye(e,n){let t=K(e);if(t.processing)return;let r=t.queue.shift();if(!r){Kn(t,e,"empty_queue"),u(`[xmtp_prompt_user:queue] dispatch skipped empty sessionKey=${e} reason=${n}`);return}Kn(t,e,n),t.processing=!0;try{u(`[xmtp_prompt_user:queue] dispatch sessionKey=${e} channel=${r.channel} reason=${n} remaining=${t.queue.length}`),f.info(a.PROMPT_USER_CHECKPOINT,T({checkpoint:"dispatch_started",sessionKey:e,channel:r.channel,taskId:r.taskId,reason:n,queued:t.queue.length}));let o=await Mn({...r,onRunStarted:s=>{let i=je.get(s);if(i){u(`[xmtp_prompt_user:queue] run already completed sessionKey=${e} channel=${r.channel} runId=${s} state=${i.state} completedAt=${i.completedAt}`),je.delete(s);return}me.set(s,{sessionKey:e,channel:r.channel,taskId:r.taskId,startedAt:Date.now()}),u(`[xmtp_prompt_user:queue] run pending sessionKey=${e} channel=${r.channel} runId=${s}`),f.info(a.PROMPT_USER_CHECKPOINT,T({checkpoint:"run_pending",sessionKey:e,channel:r.channel,taskId:r.taskId,runId:s}))}});t.running=!o.runId||me.has(o.runId),u(`[xmtp_prompt_user:queue] dispatch completed sessionKey=${e} channel=${r.channel} reason=${n} running=${t.running?1:0} runId=${o.runId??"(none)"}`),f.info(a.PROMPT_USER_CHECKPOINT,T({checkpoint:"dispatch_completed",sessionKey:e,channel:r.channel,taskId:r.taskId,reason:n,running:t.running?1:0,runId:o.runId,queued:t.queue.length}))}catch(o){u(`[xmtp_prompt_user:queue] dispatch failed sessionKey=${e} channel=${r.channel} reason=${n}:`,o),f.error(a.PROMPT_USER_FAILED,o instanceof Error?o:new Error(String(o)),T({checkpoint:"dispatch_failed",sessionKey:e,channel:r.channel,taskId:r.taskId,reason:n,queued:t.queue.length}))}finally{t.processing=!1}if(t.queue.length===0){u(`[xmtp_prompt_user:queue] queue drained sessionKey=${e}`);return}if(t.running){u(`[xmtp_prompt_user:queue] queue waiting sessionKey=${e} queued=${t.queue.length} running=1`),xn(e,t);return}u(`[xmtp_prompt_user:queue] queue continues sessionKey=${e} queued=${t.queue.length} running=0`),ye(e,"session_idle")}function xs(e){return K(e).running}async function Ls(e){let n=e.target.sessionKey,t=K(n);return t.queue.push({...e,deadlineAt:Date.now()+kr}),t.running||t.processing||t.queue.length>1?(t.queue.length===1&&xn(n,t),u(`[xmtp_prompt_user:queue] queued sessionKey=${n} channel=${e.channel} size=${t.queue.length}`),f.info(a.PROMPT_USER_CHECKPOINT,T({checkpoint:"queued",sessionKey:n,channel:e.channel,taskId:e.taskId,queued:t.queue.length,running:t.running?1:0,processing:t.processing?1:0})),{status:"queued",size:t.queue.length}):(await ye(n,"session_idle"),{status:"dispatched",size:t.queue.length})}function Ln(e){let n=K(e);n.running=!0;let t=n.queue[0];t&&(t.deadlineAt=Date.now()+kr,u(`[xmtp_prompt_user:queue] fallback reset sessionKey=${e} channel=${t.channel} queued=${n.queue.length}`),xn(e,n)),u(`[xmtp_prompt_user:queue] agent_start sessionKey=${e} queued=${n.queue.length}`)}function Un(e){let n=K(e),t=Us(e);if(t.length>0){u(`[xmtp_prompt_user:queue] agent_end sessionKey=${e} queued=${n.queue.length} pendingRunIds=${t.join(",")} waiting=run_final`);return}n.running=!1,u(`[xmtp_prompt_user:queue] agent_end sessionKey=${e} queued=${n.queue.length}`),n.queue.length>0&&ye(e,"agent_end")}function Us(e){let n=[];for(let[t,r]of me)r.sessionKey===e&&n.push(t);return n}function Cr(e,n,t){je.set(e,{state:n,sessionKey:t,completedAt:Date.now()}),setTimeout(()=>{je.delete(e)},60*1e3)}function Ms(e,n,t,r,o){let s=K(e);s.running=!1,u(`[xmtp_prompt_user:queue] run completed sessionKey=${e} runId=${n} state=${t} durationMs=${r} queued=${s.queue.length}`),f.info(a.PROMPT_USER_CHECKPOINT,T({checkpoint:"run_completed",sessionKey:e,taskId:o,runId:n,status:t,durationMs:r,queued:s.queue.length})),s.queue.length>0&&ye(e,`run_${t}`)}var kr,br,me,je,Ee=m(()=>{"use strict";I();_e();H();k();de();kr=300*1e3,br=new Map,me=new Map,je=new Map;_n(e=>{let n=e;if(n.event!=="chat"||!n.payload||typeof n.payload!="object")return;let t=n.payload,r=typeof t.runId=="string"?t.runId:"";if(!r)return;let o=typeof t.state=="string"?t.state:"",s=me.get(r);if(!s){(o==="final"||o==="error")&&Cr(r,o,String(t.sessionKey??""));return}u(`[xmtp_prompt_user:queue] observed chat event runId=${r} state=${o||"(none)"} sessionKey=${String(t.sessionKey??"")}`),!(o!=="final"&&o!=="error")&&(me.delete(r),Cr(r,o,String(t.sessionKey??"")),Ms(s.sessionKey,r,o,Date.now()-s.startedAt,s.taskId))})});var Qn={};Se(Qn,{AgentMessageDirection:()=>Ur,INJECT_ONLY_CHANNELS:()=>Ye,NON_DELIVERY_CHANNELS:()=>Y,buildAgentMessageNotice:()=>Mr,buildSystemMessageNotice:()=>$r,buildUserDispatchExtra:()=>C,dispatchPromptToUserSession:()=>Mn,dispatchToUser:()=>Bn,dispatchUserToLatestSessions:()=>Hn,dispatchUserToRoutedSessions:()=>Xn,dispatchUserToSession:()=>Yn,notifyAgentMessageToUser:()=>Bs,notifySystemMessageToUser:()=>qs,promptUserToLatestSessions:()=>Vn,promptUserToRoutedSessions:()=>Wn,promptUserToSession:()=>zn,sendLlmToLatestUserSessions:()=>Jn});function Gs(e){return e?e.length<=vr+Pr+1?e:`${e.slice(0,vr)}\u2026${e.slice(-Pr)}`:""}function js(e){return e.length<=Kr+xr+$n.length?e:`${e.slice(0,Kr)}${$n}${e.slice(-xr)}`}function Lr(e){return e.name?e.agentId?`${e.name}#${e.agentId}`:e.name:e.walletAddress?Gs(e.walletAddress):"unknown"}function Fs(e){let n=e.split(`
|
|
14
|
+
`);let i=new Date().toISOString();s.prepare("INSERT OR IGNORE INTO job_provider_bindings(job_id, provider, created_at, updated_at) VALUES (?, 'openclaw', ?, ?)").run(n,i,i);let d=s.prepare("SELECT provider, gateway_routes_json FROM job_provider_bindings WHERE job_id = ?").get(n);if(d?.provider!=="openclaw")return[];let c=Ds(d.gateway_routes_json),l=new Set(c.map(p=>p.platform)),g=[];for(let p of t)l.has(p.platform)||(c.push(p),l.add(p.platform),g.push(p.gatewaySessionKey));return g.length===0?[]:(s.prepare("UPDATE job_provider_bindings SET gateway_routes_json = ?, updated_at = ? WHERE job_id = ? AND provider = 'openclaw'").run(JSON.stringify(c),i,n),console.log(`[okx-a2a:stored-routes] bound delivered route jobId=${n} sessionKeys=${g.join(",")}`),g)}catch(i){return console.log(`[okx-a2a:stored-routes] failed to bind delivered route jobId=${n}: ${i instanceof Error?i.message:String(i)}`),[]}finally{s.close()}}function Os(e){let n=Nr(v(e)??"");if(!n)return null;let t=Or(n);if(!t)return null;let r=bs(n);return{platform:t,sessionKey:n,gatewaySessionKey:n,...r.chatId?{chatId:r.chatId}:{},...r.threadId?{threadId:r.threadId}:{},updatedAt:new Date().toISOString()}}function Ds(e){if(typeof e!="string"||!e.trim())return[];try{let n=JSON.parse(e);if(!Array.isArray(n))return[];let t=[];for(let r of n){if(!Ks(r))continue;let o=Nr(v(typeof r.gatewaySessionKey=="string"?r.gatewaySessionKey:null)??v(typeof r.sessionKey=="string"?r.sessionKey:null)??""),s=Or(o);!o||!s||t.push({platform:s,sessionKey:o,gatewaySessionKey:o,...typeof r.chatId=="string"&&r.chatId.trim()?{chatId:r.chatId.trim()}:{},...typeof r.threadId=="string"&&r.threadId.trim()?{threadId:r.threadId.trim()}:{},...typeof r.updatedAt=="string"&&r.updatedAt.trim()?{updatedAt:r.updatedAt.trim()}:{updatedAt:new Date().toISOString()}})}return t}catch{return[]}}function bs(e){let n=e.split(":");if(n.length<4||n[0]!=="agent")return{};let t=n[2],r=n[3];if(t==="discord"&&r==="thread")return{...n[4]?{chatId:n[4]}:{},...n[5]?{threadId:n[5]}:{}};if(t==="discord"&&(r==="channel"||r==="dm"))return n[4]?{chatId:n[4]}:{};if(t==="telegram"&&r==="direct"){let o=kn(n.slice(5));return{...n[4]?{chatId:n[4]}:{},...o?{threadId:o}:{}}}if(t==="telegram"&&r==="dm"){let o=kn(n.slice(5));return{...n[4]?{chatId:n[4]}:{},...o?{threadId:o}:{}}}if(t==="telegram"&&r==="group"){let o=n[5]==="topic"?n[6]:n[5];return{...n[4]?{chatId:n[4]}:{},...o?{threadId:o}:{}}}return{}}function Nr(e){let n=v(e);if(!n)return"";let t=n.split(":");if(t.length<4||t[0]!=="agent")return n;let r=t[2],o=t[3];if(r!=="telegram")return n;if((o==="direct"||o==="dm")&&t[4]){if(t[5]==="thread")return n;let s=kn(t.slice(5));return s?`agent:${t[1]}:telegram:direct:${t[4]}:topic:${s}`:`agent:${t[1]}:telegram:direct:${t[4]}`}if(o==="group"&&t[4]){let s=t[5]==="topic"?t[6]:t[5];return s?`agent:${t[1]}:telegram:group:${t[4]}:topic:${s}`:`agent:${t[1]}:telegram:group:${t[4]}`}return n}function kn(e){if(e.length!==0)return e[0]==="topic"?e[1]||void 0:e[0]==="thread"?e.length>=3?e.slice(2).join(":")||void 0:e[1]||void 0:e[0]||void 0}function Cs(e){for(let n of e){let t=v(n);if(!t)continue;let r=/\b0x[a-fA-F0-9]{64}\b/.exec(t);if(r?.[0])return r[0]}return null}function Or(e){let n=v(e);if(!n)return null;if(n==="agent:main")return"main";if(n.startsWith("backup:"))return null;let t=n.split(":");if(t.length<4||t[0]!=="agent"||!t[1])return null;let r=t[2];return!r||r==="okx-a2a"||r==="backup"||Ns.has(r)?null:r}function ks(e=process.env){return e.OKX_AGENT_TASK_HOME?.trim()||(0,Pn.join)((0,wr.homedir)(),".okx-agent-task")}function Ps(e=process.env){return e.OKX_A2A_SESSION_STORE_DB_PATH?.trim()||(0,Pn.join)(ks(e),"sqlite","session-store.sqlite")}function vs(){let e=process.emitWarning;process.emitWarning=((n,...t)=>{if(!((typeof n=="string"?n:n.message).includes("SQLite is an experimental feature")&&t.some(o=>o==="ExperimentalWarning")))return e.call(process,n,...t)});try{return require("node:sqlite")}finally{process.emitWarning=e}}function Ks(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function v(e){let n=e?.trim();return n||null}var wr,Pn,Ns,Dr=m(()=>{"use strict";wr=require("node:os"),Pn=require("node:path"),Ns=new Set(["heartbeat","cron","webhook","voice"])});var Fe={};Se(Fe,{isPromptUserSessionRunning:()=>Ls,markPromptUserSessionEnded:()=>Un,markPromptUserSessionRunning:()=>xn,promptUserSentryExtra:()=>T,queuePromptUserAction:()=>xs});function K(e){let n=br.get(e);return n||(n={running:!1,processing:!1,queue:[]},br.set(e,n)),n}function Kn(e,n,t){e.fallbackTimer&&(clearTimeout(e.fallbackTimer),e.fallbackTimer=void 0,n&&u(`[xmtp_prompt_user:queue] fallback cleared sessionKey=${n}${t?` reason=${t}`:""}`))}function Ln(e,n){Kn(n,e,"reschedule");let t=n.queue[0];if(!t||n.processing)return;let r=Math.max(0,t.deadlineAt-Date.now());u(`[xmtp_prompt_user:queue] fallback scheduled sessionKey=${e} channel=${t.channel} delayMs=${r} queued=${n.queue.length}`),f.info(a.PROMPT_USER_CHECKPOINT,T({checkpoint:"fallback_scheduled",sessionKey:e,channel:t.channel,taskId:t.taskId,delayMs:r,queued:n.queue.length})),n.fallbackTimer=setTimeout(()=>{let o=K(e);o.fallbackTimer=void 0,u(`[xmtp_prompt_user:queue] fallback fired sessionKey=${e} queued=${o.queue.length}`),f.info(a.PROMPT_USER_CHECKPOINT,T({checkpoint:"fallback_fired",sessionKey:e,taskId:o.queue[0]?.taskId,queued:o.queue.length,reason:"fallback_timeout"})),ye(e,"fallback_timeout")},r)}async function ye(e,n){let t=K(e);if(t.processing)return;let r=t.queue.shift();if(!r){Kn(t,e,"empty_queue"),u(`[xmtp_prompt_user:queue] dispatch skipped empty sessionKey=${e} reason=${n}`);return}Kn(t,e,n),t.processing=!0;try{u(`[xmtp_prompt_user:queue] dispatch sessionKey=${e} channel=${r.channel} reason=${n} remaining=${t.queue.length}`),f.info(a.PROMPT_USER_CHECKPOINT,T({checkpoint:"dispatch_started",sessionKey:e,channel:r.channel,taskId:r.taskId,reason:n,queued:t.queue.length}));let o=await Mn({...r,onRunStarted:s=>{let i=je.get(s);if(i){u(`[xmtp_prompt_user:queue] run already completed sessionKey=${e} channel=${r.channel} runId=${s} state=${i.state} completedAt=${i.completedAt}`),je.delete(s);return}me.set(s,{sessionKey:e,channel:r.channel,taskId:r.taskId,startedAt:Date.now()}),u(`[xmtp_prompt_user:queue] run pending sessionKey=${e} channel=${r.channel} runId=${s}`),f.info(a.PROMPT_USER_CHECKPOINT,T({checkpoint:"run_pending",sessionKey:e,channel:r.channel,taskId:r.taskId,runId:s}))}});t.running=!o.runId||me.has(o.runId),u(`[xmtp_prompt_user:queue] dispatch completed sessionKey=${e} channel=${r.channel} reason=${n} running=${t.running?1:0} runId=${o.runId??"(none)"}`),f.info(a.PROMPT_USER_CHECKPOINT,T({checkpoint:"dispatch_completed",sessionKey:e,channel:r.channel,taskId:r.taskId,reason:n,running:t.running?1:0,runId:o.runId,queued:t.queue.length}))}catch(o){u(`[xmtp_prompt_user:queue] dispatch failed sessionKey=${e} channel=${r.channel} reason=${n}:`,o),f.error(a.PROMPT_USER_FAILED,o instanceof Error?o:new Error(String(o)),T({checkpoint:"dispatch_failed",sessionKey:e,channel:r.channel,taskId:r.taskId,reason:n,queued:t.queue.length}))}finally{t.processing=!1}if(t.queue.length===0){u(`[xmtp_prompt_user:queue] queue drained sessionKey=${e}`);return}if(t.running){u(`[xmtp_prompt_user:queue] queue waiting sessionKey=${e} queued=${t.queue.length} running=1`),Ln(e,t);return}u(`[xmtp_prompt_user:queue] queue continues sessionKey=${e} queued=${t.queue.length} running=0`),ye(e,"session_idle")}function Ls(e){return K(e).running}async function xs(e){let n=e.target.sessionKey,t=K(n);return t.queue.push({...e,deadlineAt:Date.now()+kr}),t.running||t.processing||t.queue.length>1?(t.queue.length===1&&Ln(n,t),u(`[xmtp_prompt_user:queue] queued sessionKey=${n} channel=${e.channel} size=${t.queue.length}`),f.info(a.PROMPT_USER_CHECKPOINT,T({checkpoint:"queued",sessionKey:n,channel:e.channel,taskId:e.taskId,queued:t.queue.length,running:t.running?1:0,processing:t.processing?1:0})),{status:"queued",size:t.queue.length}):(await ye(n,"session_idle"),{status:"dispatched",size:t.queue.length})}function xn(e){let n=K(e);n.running=!0;let t=n.queue[0];t&&(t.deadlineAt=Date.now()+kr,u(`[xmtp_prompt_user:queue] fallback reset sessionKey=${e} channel=${t.channel} queued=${n.queue.length}`),Ln(e,n)),u(`[xmtp_prompt_user:queue] agent_start sessionKey=${e} queued=${n.queue.length}`)}function Un(e){let n=K(e),t=Us(e);if(t.length>0){u(`[xmtp_prompt_user:queue] agent_end sessionKey=${e} queued=${n.queue.length} pendingRunIds=${t.join(",")} waiting=run_final`);return}n.running=!1,u(`[xmtp_prompt_user:queue] agent_end sessionKey=${e} queued=${n.queue.length}`),n.queue.length>0&&ye(e,"agent_end")}function Us(e){let n=[];for(let[t,r]of me)r.sessionKey===e&&n.push(t);return n}function Cr(e,n,t){je.set(e,{state:n,sessionKey:t,completedAt:Date.now()}),setTimeout(()=>{je.delete(e)},60*1e3)}function Ms(e,n,t,r,o){let s=K(e);s.running=!1,u(`[xmtp_prompt_user:queue] run completed sessionKey=${e} runId=${n} state=${t} durationMs=${r} queued=${s.queue.length}`),f.info(a.PROMPT_USER_CHECKPOINT,T({checkpoint:"run_completed",sessionKey:e,taskId:o,runId:n,status:t,durationMs:r,queued:s.queue.length})),s.queue.length>0&&ye(e,`run_${t}`)}var kr,br,me,je,Ee=m(()=>{"use strict";I();_e();H();k();de();kr=300*1e3,br=new Map,me=new Map,je=new Map;_n(e=>{let n=e;if(n.event!=="chat"||!n.payload||typeof n.payload!="object")return;let t=n.payload,r=typeof t.runId=="string"?t.runId:"";if(!r)return;let o=typeof t.state=="string"?t.state:"",s=me.get(r);if(!s){(o==="final"||o==="error")&&Cr(r,o,String(t.sessionKey??""));return}u(`[xmtp_prompt_user:queue] observed chat event runId=${r} state=${o||"(none)"} sessionKey=${String(t.sessionKey??"")}`),!(o!=="final"&&o!=="error")&&(me.delete(r),Cr(r,o,String(t.sessionKey??"")),Ms(s.sessionKey,r,o,Date.now()-s.startedAt,s.taskId))})});var Qn={};Se(Qn,{AgentMessageDirection:()=>Ur,INJECT_ONLY_CHANNELS:()=>Ye,NON_DELIVERY_CHANNELS:()=>Y,buildAgentMessageNotice:()=>Mr,buildSystemMessageNotice:()=>$r,buildUserDispatchExtra:()=>C,dispatchPromptToUserSession:()=>Mn,dispatchToUser:()=>Bn,dispatchUserToLatestSessions:()=>Hn,dispatchUserToRoutedSessions:()=>qn,dispatchUserToSession:()=>Yn,notifyAgentMessageToUser:()=>Bs,notifySystemMessageToUser:()=>Xs,promptUserToLatestSessions:()=>Vn,promptUserToRoutedSessions:()=>Wn,promptUserToSession:()=>zn,sendLlmToLatestUserSessions:()=>Jn});function Gs(e){return e?e.length<=Pr+vr+1?e:`${e.slice(0,Pr)}\u2026${e.slice(-vr)}`:""}function js(e){return e.length<=Kr+Lr+$n.length?e:`${e.slice(0,Kr)}${$n}${e.slice(-Lr)}`}function xr(e){return e.name?e.agentId?`${e.name}#${e.agentId}`:e.name:e.walletAddress?Gs(e.walletAddress):"unknown"}function Fs(e){let n=e.split(`
|
|
15
15
|
`);if(n.length<=Be)return e;let t=n.slice(0,Be);return t[Be-1]=`${t[Be-1]}${$n}`,t.join(`
|
|
16
|
-
`)}function Mr(e){let n=
|
|
17
|
-
`)}function Bs(e){let n=Mr(e),t="[notifyAgentMessageToUser]";Bn(n,{jobId:e.jobId}).then(r=>{u(`${t} direction=${e.direction} senderAgentId=${e.sender.agentId??""} senderName=${e.sender.name??""} senderWalletAddress=${e.sender.walletAddress??""} receiverAgentId=${e.receiver.agentId??""} receiverName=${e.receiver.name??""} receiverWalletAddress=${e.receiver.walletAddress??""} jobId=${e.jobId} delivered=${r.dispatched.join(",")} failed=${r.failed.join(",")}`)},r=>{u(`${t} error direction=${e.direction} senderAgentId=${e.sender.agentId??""} receiverAgentId=${e.receiver.agentId??""} jobId=${e.jobId} err=${r instanceof Error?r.message:String(r)}`),f.error(a.USER_DISPATCH_FAILED,r instanceof Error?r:new Error(String(r)),C({checkpoint:"user_channel/agent_message_notify_failed",outcome:"failed",source:"notifyAgentMessageToUser",direction:e.direction,jobId:e.jobId,senderAgentId:e.sender.agentId??"",receiverAgentId:e.receiver.agentId??""}))})}function Hs(e){try{return JSON.stringify(e,null,2)??String(e)}catch{return JSON.stringify(e,(n,t)=>typeof t=="bigint"?t.toString():t instanceof Uint8Array?Buffer.from(t).toString("hex"):t,2)??String(e)}}function $r(e){return["System Message",
|
|
18
|
-
`)}function qs(e){let n=$r(e),t="[notifySystemMessageToUser]";Bn(n).then(r=>{u(`${t} delivered=${r.dispatched.join(",")} failed=${r.failed.join(",")}`)},r=>{u(`${t} error err=${r instanceof Error?r.message:String(r)}`),f.error(a.USER_DISPATCH_FAILED,r instanceof Error?r:new Error(String(r)),C({checkpoint:"user_channel/system_message_notify_failed",outcome:"failed",source:"notifySystemMessageToUser"}))})}function Gn(e){let n=e.base?.trim();if(!n)return(0,X.randomUUID)();let t=(0,X.createHash)("sha256").update(n).update("\0").update(e.purpose).update("\0").update(e.channel).update("\0").update(e.sessionKey).digest("hex");return`okx-a2a:${e.purpose}:${t}`}function jn(e){let n=er(e);return!n||Y.has(n.channel)?null:n}function Fn(e,n){let t=n.threadId?.trim();t&&(e.threadId=t)}async function Gr(e){let n=e.label?`[${e.label}] ${e.content}`:e.content;if(e.target.to&&!Ye.has(e.channel)){let t={to:e.target.to,message:n,channel:e.channel,sessionKey:e.target.sessionKey,idempotencyKey:Gn({base:e.idempotencyKey,purpose:"dispatch-user",channel:e.channel,sessionKey:e.target.sessionKey})};e.target.accountId&&(t.accountId=e.target.accountId),Fn(t,e.target),await A({method:"send",params:t});return}await ue({sessionKey:e.target.sessionKey,message:e.content,label:e.label})}async function Mn(e){let{channel:n,target:t,llmContent:r,userContent:o}=e,s=await Tn({key:t.sessionKey,message:r,idempotencyKey:Gn({base:e.idempotencyKey,purpose:"prompt-llm",channel:n,sessionKey:t.sessionKey})});if(s.runId?e.onRunStarted?.(s.runId):u(`[xmtp_prompt_user:queue] sessions.send returned without runId sessionKey=${t.sessionKey} channel=${n}`),t.to&&!Ye.has(n)){let i={to:t.to,message:o,channel:n,sessionKey:t.sessionKey,idempotencyKey:Gn({base:e.idempotencyKey,purpose:"prompt-user",channel:n,sessionKey:t.sessionKey})};return t.accountId&&(i.accountId=t.accountId),Fn(i,t),await A({method:"send",params:i}),{runId:s.runId}}return await ue({sessionKey:t.sessionKey,message:o}),{runId:s.runId}}async function Bn(e,n){let r=Ve({jobId:n?.jobId,currentSessionKey:n?.currentSessionKey})?.targets??v();if(r.size===0)return u("[dispatchToUser] no deliverable user session found"),{dispatched:[],failed:[]};let o=[],s=[],i=n?.label,d=i?`[${i}] ${e}`:e;for(let[c,l]of r)if(!Y.has(c))try{if(l.to&&!Ye.has(c)){let g={to:l.to,message:d,channel:c,sessionKey:l.sessionKey,idempotencyKey:(0,X.randomUUID)()};l.accountId&&(g.accountId=l.accountId),Fn(g,l),await A({method:"send",params:g})}else await ue({sessionKey:l.sessionKey,message:e,label:i});o.push(c),u(`[dispatchToUser] delivered to ${c}${l.to?` \u2192 ${l.to}`:" (inject)"} sessionKey=${l.sessionKey} accountId=${l.accountId??"(none)"}`),f.info(a.USER_DISPATCHED,C({checkpoint:"user_channel/dispatch_delivered",outcome:"success",source:"dispatchToUser",channel:c,sessionKey:l.sessionKey,jobId:n?.jobId,hasTo:!!l.to}))}catch(g){s.push(c),u(`[dispatchToUser] delivery to ${c} failed:`,g),f.error(a.USER_DISPATCH_FAILED,g instanceof Error?g:new Error(String(g)),C({checkpoint:"user_channel/dispatch_failed",outcome:"failed",source:"dispatchToUser",channel:c,sessionKey:l.sessionKey,jobId:n?.jobId,hasTo:!!l.to}))}return{dispatched:o,failed:s}}async function Hn(e){let n=Ve({jobId:e.jobId,currentSessionKey:e.currentSessionKey});if(n)return console.log(`[okx-a2a:gateway-method] dispatch_user stored routes jobId=${e.jobId??"(none)"} currentSessionKey=${e.currentSessionKey??"(none)"} routeCount=${n.targets.size} failed=${n.failed.length}`),He(n.targets,e,n.failed);let t=jr({jobId:e.jobId,currentSessionKey:e.currentSessionKey,contents:[e.content]});if(t)return console.log(`[okx-a2a:gateway-method] dispatch_user rebound remembered route jobId=${e.jobId??"(none)"} routeCount=${t.targets.size} failed=${t.failed.length}`),He(t.targets,e,t.failed);let r=await He(v(),e);return Fr(e.jobId,r.dispatched,[e.content]),r}function qn(e){let n=new Map,t=[];for(let r of e){let o=jn(r);if(!o){t.push({channel:"",sessionKey:r,error:"invalid user gateway session"});continue}n.set(o.channel,o.target)}return{targets:n,failed:t}}function Ve(e){let n=e.currentSessionKey?.trim()||hr(),t=Ge({jobId:e.jobId,sessionKey:n});return t.length>0?qn(t):null}async function He(e,n,t=[]){if(e.size===0)return u("[okx-a2a:gateway-method] dispatch_user no deliverable user session found"),{ok:!1,dispatched:[],failed:t};let r=[],o=[...t];for(let[s,i]of e)if(!Y.has(s))try{await Gr({channel:s,target:i,content:n.content,label:n.label,idempotencyKey:n.idempotencyKey}),r.push({channel:s,sessionKey:i.sessionKey}),u(`[okx-a2a:gateway-method] dispatch_user delivered channel=${s} sessionKey=${i.sessionKey}`)}catch(d){let c=d instanceof Error?d.message:String(d);o.push({channel:s,sessionKey:i.sessionKey,error:c}),u(`[okx-a2a:gateway-method] dispatch_user failed channel=${s} sessionKey=${i.sessionKey}: ${c}`),f.error(a.USER_DISPATCH_FAILED,d instanceof Error?d:new Error(String(d)),C({checkpoint:"user_channel/fanout_dispatch_failed",outcome:"failed",source:"okx-a2a.dispatch_user",channel:s,sessionKey:i.sessionKey,hasTo:!!i.to}))}return{ok:r.length>0&&o.length===0,dispatched:r,failed:o}}async function Xn(e){let{targets:n,failed:t}=qn(e.sessionKeys);return He(n,{content:e.content,label:e.label,idempotencyKey:e.idempotencyKey},t)}async function Yn(e){let n=jn(e.sessionKey);if(!n)return{ok:!1,dispatched:[],failed:[{channel:"",sessionKey:e.sessionKey,error:"invalid user gateway session"}]};try{return await Gr({channel:n.channel,target:n.target,content:e.content,label:e.label,idempotencyKey:e.idempotencyKey}),console.log(`[okx-a2a:gateway-method] dispatch_user delivered routed channel=${n.channel} sessionKey=${e.sessionKey}`),{ok:!0,dispatched:[{channel:n.channel,sessionKey:e.sessionKey}],failed:[]}}catch(t){let r=t instanceof Error?t.message:String(t);return f.error(a.USER_DISPATCH_FAILED,t instanceof Error?t:new Error(String(t)),C({checkpoint:"user_channel/routed_dispatch_failed",outcome:"failed",source:"okx-a2a.dispatch_user",channel:n.channel,sessionKey:e.sessionKey,hasTo:!!n.target.to})),{ok:!1,dispatched:[],failed:[{channel:n.channel,sessionKey:e.sessionKey,error:r}]}}}async function Vn(e){let{queuePromptUserAction:n}=await Promise.resolve().then(()=>(Ee(),Fe)),t=Ve({jobId:e.jobId,currentSessionKey:e.currentSessionKey});if(t)return console.log(`[okx-a2a:gateway-method] prompt_user stored routes jobId=${e.jobId??"(none)"} currentSessionKey=${e.currentSessionKey??"(none)"} routeCount=${t.targets.size} failed=${t.failed.length}`),qe(t.targets,e,t.failed,n);let r=jr({jobId:e.jobId,currentSessionKey:e.currentSessionKey,contents:[e.userContent,e.llmContent]});if(r)return console.log(`[okx-a2a:gateway-method] prompt_user rebound remembered route jobId=${e.jobId??"(none)"} routeCount=${r.targets.size} failed=${r.failed.length}`),qe(r.targets,e,r.failed,n);let o=await qe(v(),e,[],n);return Fr(e.jobId,o.dispatched,[e.userContent,e.llmContent]),o}function jr(e){let n=$e({sessionKey:e.currentSessionKey});return n.length===0||Pn({jobId:e.jobId,contents:e.contents,sessionKeys:n}).length===0?null:Ve({jobId:e.jobId,currentSessionKey:e.currentSessionKey})}function Fr(e,n,t){let r=n.map(o=>o.sessionKey).filter(Boolean);r.length!==0&&Pn({jobId:e,contents:t,sessionKeys:r})}async function qe(e,n,t=[],r){if(e.size===0)return u("[okx-a2a:gateway-method] prompt_user no deliverable user session found"),{ok:!1,dispatched:[],failed:t};let o=[],s=[...t];for(let[i,d]of e)if(!Y.has(i))try{let c=await r({channel:i,target:d,llmContent:n.llmContent,userContent:n.userContent,idempotencyKey:n.idempotencyKey});o.push({channel:i,sessionKey:d.sessionKey,status:c.status,size:c.size}),u(`[okx-a2a:gateway-method] prompt_user ${c.status} channel=${i} sessionKey=${d.sessionKey} size=${c.size}`)}catch(c){let l=c instanceof Error?c.message:String(c);s.push({channel:i,sessionKey:d.sessionKey,error:l}),u(`[okx-a2a:gateway-method] prompt_user failed channel=${i} sessionKey=${d.sessionKey}: ${l}`),f.error(a.PROMPT_USER_FAILED,c instanceof Error?c:new Error(String(c)),{source:"okx-a2a.prompt_user",channel:i,sessionKey:d.sessionKey})}return{ok:o.length>0&&s.length===0,dispatched:o,failed:s}}async function Wn(e){let{queuePromptUserAction:n}=await Promise.resolve().then(()=>(Ee(),Fe)),{targets:t,failed:r}=qn(e.sessionKeys);return qe(t,{llmContent:e.llmContent,userContent:e.userContent,idempotencyKey:e.idempotencyKey},r,n)}async function zn(e){let{queuePromptUserAction:n}=await Promise.resolve().then(()=>(Ee(),Fe)),t=jn(e.sessionKey);if(!t)return{ok:!1,dispatched:[],failed:[{channel:"",sessionKey:e.sessionKey,error:"invalid user gateway session"}]};try{let r=await n({channel:t.channel,target:t.target,llmContent:e.llmContent,userContent:e.userContent,idempotencyKey:e.idempotencyKey});return console.log(`[okx-a2a:gateway-method] prompt_user ${r.status} routed channel=${t.channel} sessionKey=${e.sessionKey} size=${r.size}`),{ok:!0,dispatched:[{channel:t.channel,sessionKey:e.sessionKey,status:r.status,size:r.size}],failed:[]}}catch(r){let o=r instanceof Error?r.message:String(r);return f.error(a.PROMPT_USER_FAILED,r instanceof Error?r:new Error(String(r)),{source:"okx-a2a.prompt_user",channel:t.channel,sessionKey:e.sessionKey}),{ok:!1,dispatched:[],failed:[{channel:t.channel,sessionKey:e.sessionKey,error:o}]}}}async function Jn(e,n){let t=v();if(t.size===0)return u("[sendLlmToLatestUserSessions] no latest user session found"),{dispatched:[],failed:[]};let r=[],o=[];for(let[s,i]of t)if(!Y.has(s))try{await Ae().subagent.run({sessionKey:i.sessionKey,message:e,deliver:!0,idempotencyKey:(0,X.randomUUID)()}),r.push(s),u(`[sendLlmToLatestUserSessions] sent to ${s} sessionKey=${i.sessionKey}`)}catch(d){o.push(s),u(`[sendLlmToLatestUserSessions] send to ${s} failed:`,d),f.error(a.USER_DISPATCH_FAILED,d instanceof Error?d:new Error(String(d)),C({checkpoint:"user_channel/llm_send_failed",outcome:"failed",source:n?.source??"sendLlmToLatestUserSessions",channel:s,sessionKey:i.sessionKey}))}return{dispatched:r,failed:o}}var X,Ur,$s,Xe,vr,Pr,Kr,xr,$n,Be,Y,Ye,_e=m(()=>{"use strict";I();X=require("node:crypto");H();j();On();Cn();Dr();k();he();de();Ur=(t=>(t.OUTBOUND="outbound",t.INBOUND="inbound",t))(Ur||{}),$s={outbound:"\u{1F4E4} [Sent]",inbound:"\u{1F4E5} [Received]"},Xe="\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",vr=6,Pr=4,Kr=6,xr=4,$n="...",Be=8;Y=new Set(["heartbeat","cron","webhook","voice"]),Ye=new Set(["webchat","tui"])});var ui={};Se(ui,{default:()=>ci});module.exports=no(ui);I();he();I();k();var No="main",Ut={id:"okx-a2a",meta:{id:"okx-a2a",label:"OKX A2A",selectionLabel:"OKX A2A",docsPath:"channels/okx-a2a",blurb:"E2E encrypted communication (wallet-to-agent)",order:101},capabilities:{chatTypes:["group"],media:!1,reply:!0},reload:{configPrefixes:["channels.okx-a2a"]},config:{resolveAccount:async()=>({}),listAccountIds:()=>[No]},outbound:{deliveryMode:"direct"},gateway:{startAccount:async e=>{e.setStatus({accountId:e.accountId,connected:!0,lastConnectedAt:Date.now(),lastEventAt:Date.now()}),u(`[okx-a2a:${e.accountId}] startAccount activated`),await new Promise(n=>{e.abortSignal.addEventListener("abort",()=>n(),{once:!0})}),u(`[okx-a2a:${e.accountId}] received abort signal, cleaning up...`)},stopAccount:async()=>{u("[okx-a2a] stopAccount"),await Lt()}}};I();H();j();k();var yr=async e=>{let n=or(e),t=[];for(let r of n)await hn({key:r,...e.deleteTranscript!==void 0?{deleteTranscript:e.deleteTranscript}:{}}),t.push(r),u(`[okx-a2a] session deleted: ${r}`),f.info(a.SESSION_DELETED,{sessionKey:r,...ae({sessionKey:r})});return{ok:!0,deleted:t.length,deletedSessionKeys:t,matched:n.length}};H();j();_e();Ee();On();Cn();I();var Hr=require("node:os"),Zn=require("node:path"),qr=require("node:fs");k();de();var Xs=15e3,Ys=50,Vs=1;function Ws(e=process.env){return e.OKX_AGENT_TASK_HOME?.trim()||(0,Zn.join)((0,Hr.homedir)(),".okx-agent-task")}function zs(e=process.env){return e.OKX_A2A_OUTBOX_DB_PATH?.trim()||(0,Zn.join)(Ws(e),"sqlite","session-store.sqlite")}function Js(){let e=process.emitWarning;process.emitWarning=((n,...t)=>{if(!((typeof n=="string"?n:n.message).includes("SQLite is an experimental feature")&&t.some(o=>o==="ExperimentalWarning")))return e.call(process,n,...t)});try{return require("node:sqlite")}finally{process.emitWarning=e}}function Br(e,n){let t=Array.isArray(n.dispatched)?n.dispatched.length:0,r=Array.isArray(n.failed)?n.failed.length:0,o=`${e} delivered=${t} failed=${r}`;return{delivered:t>0,message:o,partial:t>0&&r>0}}async function Qs(e){let n=e.message_id??void 0;if(e.kind==="dispatch_user_latest"){let{dispatchUserToLatestSessions:o}=await Promise.resolve().then(()=>(_e(),Qn)),s=await o({content:e.content,jobId:e.job_id,idempotencyKey:n});return Br(e.kind,s)}if(e.kind==="prompt_user_latest"){if(!e.llm_content)throw new Error("prompt_user_latest missing llm_content");let{promptUserToLatestSessions:o}=await Promise.resolve().then(()=>(_e(),Qn)),s=await o({userContent:e.content,llmContent:e.llm_content,jobId:e.job_id,idempotencyKey:n});return Br(e.kind,s)}let{callChatInject:t,callSessionsSend:r}=await Promise.resolve().then(()=>(H(),mr));return e.kind==="chat_inject"?(e.llm_content&&await r({key:e.session_key,message:e.llm_content,idempotencyKey:n}),await t({sessionKey:e.session_key,message:e.content}),{delivered:!0}):(await r({key:e.session_key,message:e.content,idempotencyKey:n}),{delivered:!0})}async function Zs(e={}){let n=e.dbPath??zs();if(!(0,qr.existsSync)(n))return{delivered:0,failed:0,abandoned:0,skipped:!0};let{DatabaseSync:t}=Js(),r=new t(n);try{if(r.exec("PRAGMA busy_timeout=5000"),r.exec("PRAGMA journal_mode=WAL"),!r.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='pending_gateway_deliveries'").get())return{delivered:0,failed:0,abandoned:0,skipped:!0};let s=r.prepare(`
|
|
16
|
+
`)}function Mr(e){let n=xr(e.sender),t=xr(e.receiver),r=e.direction==="outbound"?`${n} (you) \u2192 ${t}`:`${n} \u2192 ${t} (you)`;return[`${$s[e.direction]} ${r}`,`Job: ${js(e.jobId)}`,qe,`\u300C${Fs(e.content)}\u300D`,qe].join(`
|
|
17
|
+
`)}function Bs(e){let n=Mr(e),t="[notifyAgentMessageToUser]";Bn(n,{jobId:e.jobId}).then(r=>{u(`${t} direction=${e.direction} senderAgentId=${e.sender.agentId??""} senderName=${e.sender.name??""} senderWalletAddress=${e.sender.walletAddress??""} receiverAgentId=${e.receiver.agentId??""} receiverName=${e.receiver.name??""} receiverWalletAddress=${e.receiver.walletAddress??""} jobId=${e.jobId} delivered=${r.dispatched.join(",")} failed=${r.failed.join(",")}`)},r=>{u(`${t} error direction=${e.direction} senderAgentId=${e.sender.agentId??""} receiverAgentId=${e.receiver.agentId??""} jobId=${e.jobId} err=${r instanceof Error?r.message:String(r)}`),f.error(a.USER_DISPATCH_FAILED,r instanceof Error?r:new Error(String(r)),C({checkpoint:"user_channel/agent_message_notify_failed",outcome:"failed",source:"notifyAgentMessageToUser",direction:e.direction,jobId:e.jobId,senderAgentId:e.sender.agentId??"",receiverAgentId:e.receiver.agentId??""}))})}function Hs(e){try{return JSON.stringify(e,null,2)??String(e)}catch{return JSON.stringify(e,(n,t)=>typeof t=="bigint"?t.toString():t instanceof Uint8Array?Buffer.from(t).toString("hex"):t,2)??String(e)}}function $r(e){return["System Message",qe,"```json",Hs(e),"```",qe].join(`
|
|
18
|
+
`)}function Xs(e){let n=$r(e),t="[notifySystemMessageToUser]";Bn(n).then(r=>{u(`${t} delivered=${r.dispatched.join(",")} failed=${r.failed.join(",")}`)},r=>{u(`${t} error err=${r instanceof Error?r.message:String(r)}`),f.error(a.USER_DISPATCH_FAILED,r instanceof Error?r:new Error(String(r)),C({checkpoint:"user_channel/system_message_notify_failed",outcome:"failed",source:"notifySystemMessageToUser"}))})}function Gn(e){let n=e.base?.trim();if(!n)return(0,q.randomUUID)();let t=(0,q.createHash)("sha256").update(n).update("\0").update(e.purpose).update("\0").update(e.channel).update("\0").update(e.sessionKey).digest("hex");return`okx-a2a:${e.purpose}:${t}`}function jn(e){let n=er(e);return!n||Y.has(n.channel)?null:n}function Fn(e,n){let t=n.threadId?.trim();t&&(e.threadId=t)}async function Gr(e){let n=e.label?`[${e.label}] ${e.content}`:e.content;if(e.target.to&&!Ye.has(e.channel)){let t={to:e.target.to,message:n,channel:e.channel,sessionKey:e.target.sessionKey,idempotencyKey:Gn({base:e.idempotencyKey,purpose:"dispatch-user",channel:e.channel,sessionKey:e.target.sessionKey})};e.target.accountId&&(t.accountId=e.target.accountId),Fn(t,e.target),await A({method:"send",params:t});return}await ue({sessionKey:e.target.sessionKey,message:e.content,label:e.label})}async function Mn(e){let{channel:n,target:t,llmContent:r,userContent:o}=e,s=await Tn({key:t.sessionKey,message:r,idempotencyKey:Gn({base:e.idempotencyKey,purpose:"prompt-llm",channel:n,sessionKey:t.sessionKey})});if(s.runId?e.onRunStarted?.(s.runId):u(`[xmtp_prompt_user:queue] sessions.send returned without runId sessionKey=${t.sessionKey} channel=${n}`),t.to&&!Ye.has(n)){let i={to:t.to,message:o,channel:n,sessionKey:t.sessionKey,idempotencyKey:Gn({base:e.idempotencyKey,purpose:"prompt-user",channel:n,sessionKey:t.sessionKey})};return t.accountId&&(i.accountId=t.accountId),Fn(i,t),await A({method:"send",params:i}),{runId:s.runId}}return await ue({sessionKey:t.sessionKey,message:o}),{runId:s.runId}}async function Bn(e,n){let r=Ve({jobId:n?.jobId,currentSessionKey:n?.currentSessionKey})?.targets??P();if(r.size===0)return u("[dispatchToUser] no deliverable user session found"),{dispatched:[],failed:[]};let o=[],s=[],i=n?.label,d=i?`[${i}] ${e}`:e;for(let[c,l]of r)if(!Y.has(c))try{if(l.to&&!Ye.has(c)){let g={to:l.to,message:d,channel:c,sessionKey:l.sessionKey,idempotencyKey:(0,q.randomUUID)()};l.accountId&&(g.accountId=l.accountId),Fn(g,l),await A({method:"send",params:g})}else await ue({sessionKey:l.sessionKey,message:e,label:i});o.push(c),u(`[dispatchToUser] delivered to ${c}${l.to?` \u2192 ${l.to}`:" (inject)"} sessionKey=${l.sessionKey} accountId=${l.accountId??"(none)"}`),f.info(a.USER_DISPATCHED,C({checkpoint:"user_channel/dispatch_delivered",outcome:"success",source:"dispatchToUser",channel:c,sessionKey:l.sessionKey,jobId:n?.jobId,hasTo:!!l.to}))}catch(g){s.push(c),u(`[dispatchToUser] delivery to ${c} failed:`,g),f.error(a.USER_DISPATCH_FAILED,g instanceof Error?g:new Error(String(g)),C({checkpoint:"user_channel/dispatch_failed",outcome:"failed",source:"dispatchToUser",channel:c,sessionKey:l.sessionKey,jobId:n?.jobId,hasTo:!!l.to}))}return{dispatched:o,failed:s}}async function Hn(e){let n=Ve({jobId:e.jobId,currentSessionKey:e.currentSessionKey});if(n)return console.log(`[okx-a2a:gateway-method] dispatch_user stored routes jobId=${e.jobId??"(none)"} currentSessionKey=${e.currentSessionKey??"(none)"} routeCount=${n.targets.size} failed=${n.failed.length}`),He(n.targets,e,n.failed);let t=jr({jobId:e.jobId,currentSessionKey:e.currentSessionKey,contents:[e.content]});if(t)return console.log(`[okx-a2a:gateway-method] dispatch_user rebound remembered route jobId=${e.jobId??"(none)"} routeCount=${t.targets.size} failed=${t.failed.length}`),He(t.targets,e,t.failed);let r=await He(P(),e);return Fr(e.jobId,r.dispatched,[e.content]),r}function Xn(e){let n=new Map,t=[];for(let r of e){let o=jn(r);if(!o){t.push({channel:"",sessionKey:r,error:"invalid user gateway session"});continue}n.set(o.channel,o.target)}return{targets:n,failed:t}}function Ve(e){let n=e.currentSessionKey?.trim()||hr(),t=Ge({jobId:e.jobId,sessionKey:n});return t.length>0?Xn(t):null}async function He(e,n,t=[]){if(e.size===0)return u("[okx-a2a:gateway-method] dispatch_user no deliverable user session found"),{ok:!1,dispatched:[],failed:t};let r=[],o=[...t];for(let[s,i]of e)if(!Y.has(s))try{await Gr({channel:s,target:i,content:n.content,label:n.label,idempotencyKey:n.idempotencyKey}),r.push({channel:s,sessionKey:i.sessionKey}),u(`[okx-a2a:gateway-method] dispatch_user delivered channel=${s} sessionKey=${i.sessionKey}`)}catch(d){let c=d instanceof Error?d.message:String(d);o.push({channel:s,sessionKey:i.sessionKey,error:c}),u(`[okx-a2a:gateway-method] dispatch_user failed channel=${s} sessionKey=${i.sessionKey}: ${c}`),f.error(a.USER_DISPATCH_FAILED,d instanceof Error?d:new Error(String(d)),C({checkpoint:"user_channel/fanout_dispatch_failed",outcome:"failed",source:"okx-a2a.dispatch_user",channel:s,sessionKey:i.sessionKey,hasTo:!!i.to}))}return{ok:r.length>0&&o.length===0,dispatched:r,failed:o}}async function qn(e){let{targets:n,failed:t}=Xn(e.sessionKeys);return He(n,{content:e.content,label:e.label,idempotencyKey:e.idempotencyKey},t)}async function Yn(e){let n=jn(e.sessionKey);if(!n)return{ok:!1,dispatched:[],failed:[{channel:"",sessionKey:e.sessionKey,error:"invalid user gateway session"}]};try{return await Gr({channel:n.channel,target:n.target,content:e.content,label:e.label,idempotencyKey:e.idempotencyKey}),console.log(`[okx-a2a:gateway-method] dispatch_user delivered routed channel=${n.channel} sessionKey=${e.sessionKey}`),{ok:!0,dispatched:[{channel:n.channel,sessionKey:e.sessionKey}],failed:[]}}catch(t){let r=t instanceof Error?t.message:String(t);return f.error(a.USER_DISPATCH_FAILED,t instanceof Error?t:new Error(String(t)),C({checkpoint:"user_channel/routed_dispatch_failed",outcome:"failed",source:"okx-a2a.dispatch_user",channel:n.channel,sessionKey:e.sessionKey,hasTo:!!n.target.to})),{ok:!1,dispatched:[],failed:[{channel:n.channel,sessionKey:e.sessionKey,error:r}]}}}async function Vn(e){let{queuePromptUserAction:n}=await Promise.resolve().then(()=>(Ee(),Fe)),t=Ve({jobId:e.jobId,currentSessionKey:e.currentSessionKey});if(t)return console.log(`[okx-a2a:gateway-method] prompt_user stored routes jobId=${e.jobId??"(none)"} currentSessionKey=${e.currentSessionKey??"(none)"} routeCount=${t.targets.size} failed=${t.failed.length}`),Xe(t.targets,e,t.failed,n);let r=jr({jobId:e.jobId,currentSessionKey:e.currentSessionKey,contents:[e.userContent,e.llmContent]});if(r)return console.log(`[okx-a2a:gateway-method] prompt_user rebound remembered route jobId=${e.jobId??"(none)"} routeCount=${r.targets.size} failed=${r.failed.length}`),Xe(r.targets,e,r.failed,n);let o=await Xe(P(),e,[],n);return Fr(e.jobId,o.dispatched,[e.userContent,e.llmContent]),o}function jr(e){let n=$e({sessionKey:e.currentSessionKey});return n.length===0||vn({jobId:e.jobId,contents:e.contents,sessionKeys:n}).length===0?null:Ve({jobId:e.jobId,currentSessionKey:e.currentSessionKey})}function Fr(e,n,t){let r=n.map(o=>o.sessionKey).filter(Boolean);r.length!==0&&vn({jobId:e,contents:t,sessionKeys:r})}async function Xe(e,n,t=[],r){if(e.size===0)return u("[okx-a2a:gateway-method] prompt_user no deliverable user session found"),{ok:!1,dispatched:[],failed:t};let o=[],s=[...t];for(let[i,d]of e)if(!Y.has(i))try{let c=await r({channel:i,target:d,llmContent:n.llmContent,userContent:n.userContent,idempotencyKey:n.idempotencyKey});o.push({channel:i,sessionKey:d.sessionKey,status:c.status,size:c.size}),u(`[okx-a2a:gateway-method] prompt_user ${c.status} channel=${i} sessionKey=${d.sessionKey} size=${c.size}`)}catch(c){let l=c instanceof Error?c.message:String(c);s.push({channel:i,sessionKey:d.sessionKey,error:l}),u(`[okx-a2a:gateway-method] prompt_user failed channel=${i} sessionKey=${d.sessionKey}: ${l}`),f.error(a.PROMPT_USER_FAILED,c instanceof Error?c:new Error(String(c)),{source:"okx-a2a.prompt_user",channel:i,sessionKey:d.sessionKey})}return{ok:o.length>0&&s.length===0,dispatched:o,failed:s}}async function Wn(e){let{queuePromptUserAction:n}=await Promise.resolve().then(()=>(Ee(),Fe)),{targets:t,failed:r}=Xn(e.sessionKeys);return Xe(t,{llmContent:e.llmContent,userContent:e.userContent,idempotencyKey:e.idempotencyKey},r,n)}async function zn(e){let{queuePromptUserAction:n}=await Promise.resolve().then(()=>(Ee(),Fe)),t=jn(e.sessionKey);if(!t)return{ok:!1,dispatched:[],failed:[{channel:"",sessionKey:e.sessionKey,error:"invalid user gateway session"}]};try{let r=await n({channel:t.channel,target:t.target,llmContent:e.llmContent,userContent:e.userContent,idempotencyKey:e.idempotencyKey});return console.log(`[okx-a2a:gateway-method] prompt_user ${r.status} routed channel=${t.channel} sessionKey=${e.sessionKey} size=${r.size}`),{ok:!0,dispatched:[{channel:t.channel,sessionKey:e.sessionKey,status:r.status,size:r.size}],failed:[]}}catch(r){let o=r instanceof Error?r.message:String(r);return f.error(a.PROMPT_USER_FAILED,r instanceof Error?r:new Error(String(r)),{source:"okx-a2a.prompt_user",channel:t.channel,sessionKey:e.sessionKey}),{ok:!1,dispatched:[],failed:[{channel:t.channel,sessionKey:e.sessionKey,error:o}]}}}async function Jn(e,n){let t=P();if(t.size===0)return u("[sendLlmToLatestUserSessions] no latest user session found"),{dispatched:[],failed:[]};let r=[],o=[];for(let[s,i]of t)if(!Y.has(s))try{await Ae().subagent.run({sessionKey:i.sessionKey,message:e,deliver:!0,idempotencyKey:(0,q.randomUUID)()}),r.push(s),u(`[sendLlmToLatestUserSessions] sent to ${s} sessionKey=${i.sessionKey}`)}catch(d){o.push(s),u(`[sendLlmToLatestUserSessions] send to ${s} failed:`,d),f.error(a.USER_DISPATCH_FAILED,d instanceof Error?d:new Error(String(d)),C({checkpoint:"user_channel/llm_send_failed",outcome:"failed",source:n?.source??"sendLlmToLatestUserSessions",channel:s,sessionKey:i.sessionKey}))}return{dispatched:r,failed:o}}var q,Ur,$s,qe,Pr,vr,Kr,Lr,$n,Be,Y,Ye,_e=m(()=>{"use strict";I();q=require("node:crypto");H();j();On();Cn();Dr();k();he();de();Ur=(t=>(t.OUTBOUND="outbound",t.INBOUND="inbound",t))(Ur||{}),$s={outbound:"\u{1F4E4} [Sent]",inbound:"\u{1F4E5} [Received]"},qe="\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",Pr=6,vr=4,Kr=6,Lr=4,$n="...",Be=8;Y=new Set(["heartbeat","cron","webhook","voice"]),Ye=new Set(["webchat","tui"])});var ui={};Se(ui,{default:()=>ci});module.exports=no(ui);I();he();I();k();var No="main",Ut={id:"okx-a2a",meta:{id:"okx-a2a",label:"OKX A2A",selectionLabel:"OKX A2A",docsPath:"channels/okx-a2a",blurb:"E2E encrypted communication (wallet-to-agent)",order:101},capabilities:{chatTypes:["group"],media:!1,reply:!0},reload:{configPrefixes:["channels.okx-a2a"]},config:{resolveAccount:async()=>({}),listAccountIds:()=>[No]},outbound:{deliveryMode:"direct"},gateway:{startAccount:async e=>{e.setStatus({accountId:e.accountId,connected:!0,lastConnectedAt:Date.now(),lastEventAt:Date.now()}),u(`[okx-a2a:${e.accountId}] startAccount activated`),await new Promise(n=>{e.abortSignal.addEventListener("abort",()=>n(),{once:!0})}),u(`[okx-a2a:${e.accountId}] received abort signal, cleaning up...`)},stopAccount:async()=>{u("[okx-a2a] stopAccount"),await xt()}}};I();H();j();k();var yr=async e=>{let n=or(e),t=[];for(let r of n)await hn({key:r,...e.deleteTranscript!==void 0?{deleteTranscript:e.deleteTranscript}:{}}),t.push(r),u(`[okx-a2a] session deleted: ${r}`),f.info(a.SESSION_DELETED,{sessionKey:r,...ae({sessionKey:r})});return{ok:!0,deleted:t.length,deletedSessionKeys:t,matched:n.length}};H();j();_e();Ee();On();Cn();I();var Hr=require("node:os"),Zn=require("node:path"),Xr=require("node:fs");k();de();var qs=15e3,Ys=50,Vs=1;function Ws(e=process.env){return e.OKX_AGENT_TASK_HOME?.trim()||(0,Zn.join)((0,Hr.homedir)(),".okx-agent-task")}function zs(e=process.env){return e.OKX_A2A_OUTBOX_DB_PATH?.trim()||(0,Zn.join)(Ws(e),"sqlite","session-store.sqlite")}function Js(){let e=process.emitWarning;process.emitWarning=((n,...t)=>{if(!((typeof n=="string"?n:n.message).includes("SQLite is an experimental feature")&&t.some(o=>o==="ExperimentalWarning")))return e.call(process,n,...t)});try{return require("node:sqlite")}finally{process.emitWarning=e}}function Br(e,n){let t=Array.isArray(n.dispatched)?n.dispatched.length:0,r=Array.isArray(n.failed)?n.failed.length:0,o=`${e} delivered=${t} failed=${r}`;return{delivered:t>0,message:o,partial:t>0&&r>0}}async function Qs(e){let n=e.message_id??void 0;if(e.kind==="dispatch_user_latest"){let{dispatchUserToLatestSessions:o}=await Promise.resolve().then(()=>(_e(),Qn)),s=await o({content:e.content,jobId:e.job_id,idempotencyKey:n});return Br(e.kind,s)}if(e.kind==="prompt_user_latest"){if(!e.llm_content)throw new Error("prompt_user_latest missing llm_content");let{promptUserToLatestSessions:o}=await Promise.resolve().then(()=>(_e(),Qn)),s=await o({userContent:e.content,llmContent:e.llm_content,jobId:e.job_id,idempotencyKey:n});return Br(e.kind,s)}let{callChatInject:t,callSessionsSend:r}=await Promise.resolve().then(()=>(H(),mr));return e.kind==="chat_inject"?(e.llm_content&&await r({key:e.session_key,message:e.llm_content,idempotencyKey:n}),await t({sessionKey:e.session_key,message:e.content}),{delivered:!0}):(await r({key:e.session_key,message:e.content,idempotencyKey:n}),{delivered:!0})}async function Zs(e={}){let n=e.dbPath??zs();if(!(0,Xr.existsSync)(n))return{delivered:0,failed:0,abandoned:0,skipped:!0};let{DatabaseSync:t}=Js(),r=new t(n);try{if(r.exec("PRAGMA busy_timeout=5000"),r.exec("PRAGMA journal_mode=WAL"),!r.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='pending_gateway_deliveries'").get())return{delivered:0,failed:0,abandoned:0,skipped:!0};let s=r.prepare(`
|
|
19
19
|
SELECT id, kind, provider, session_key, job_id, content, llm_content, message_id, attempts
|
|
20
20
|
FROM pending_gateway_deliveries
|
|
21
21
|
WHERE provider = 'openclaw'
|
|
22
22
|
ORDER BY created_at ASC, id ASC
|
|
23
23
|
LIMIT ?
|
|
24
|
-
`).all(e.limit??Ys),i=0,d=0,c=0,l=e.deliver??Qs;for(let g of s)try{let p=await l(g);if(!p.delivered)throw new Error(p.message??`${g.kind} did not deliver to any user session`);r.prepare("DELETE FROM pending_gateway_deliveries WHERE id = ?").run(g.id),i+=1,p.partial&&u(`[okx-a2a:outbox-drain] delivery partially delivered id=${g.id} kind=${g.kind}: ${p.message??""}`)}catch(p){d+=1;let _=p instanceof Error?p.message:String(p),
|
|
24
|
+
`).all(e.limit??Ys),i=0,d=0,c=0,l=e.deliver??Qs;for(let g of s)try{let p=await l(g);if(!p.delivered)throw new Error(p.message??`${g.kind} did not deliver to any user session`);r.prepare("DELETE FROM pending_gateway_deliveries WHERE id = ?").run(g.id),i+=1,p.partial&&u(`[okx-a2a:outbox-drain] delivery partially delivered id=${g.id} kind=${g.kind}: ${p.message??""}`)}catch(p){d+=1;let _=p instanceof Error?p.message:String(p),x=g.attempts+1;g.attempts>=Vs?(r.prepare("DELETE FROM pending_gateway_deliveries WHERE id = ?").run(g.id),c+=1,u(`[okx-a2a:outbox-drain] delivery abandoned id=${g.id} kind=${g.kind} attempts=${x}: ${_}`)):(r.prepare(`
|
|
25
25
|
UPDATE pending_gateway_deliveries
|
|
26
26
|
SET attempts = attempts + 1, last_error = ?, last_attempt_at = ?
|
|
27
27
|
WHERE id = ?
|
|
28
|
-
`).run(_,new Date().toISOString(),g.id),u(`[okx-a2a:outbox-drain] delivery failed id=${g.id} kind=${g.kind} attempts=${
|
|
29
|
-
`)}function si(){ce({key:rr()}).then(()=>{u("[okx-a2a:service] gateway client admin precheck succeeded"),f.info(a.GATEWAY_STARTED,{source:"gateway_preconnect",outcome:"ok"})},e=>{u("[okx-a2a:service] gateway client admin precheck failed:",e),f.error(a.GATEWAY_CONNECT_FAILED,e instanceof Error?e:new Error(String(e)),{source:"gateway_preconnect",code:String(e?.gatewayCode??e?.details?.code??""),reason:String(e?.details?.reason??""),requestId:String(e?.details?.requestId??"")}),Jn(oi(e),{source:"gateway_preconnect"}).then(({dispatched:n,failed:t})=>{f.info(a.USER_DISPATCHED,{source:"gateway_preconnect",outcome:t.length===0?"all_ok":"partial",dispatchedChannels:n.join(","),failedChannels:t.join(","),dispatchedCount:String(n.length),failedCount:String(t.length)})},n=>{f.error(a.USER_DISPATCH_FAILED,n instanceof Error?n:new Error(String(n)),{source:"gateway_preconnect"})})})}function ii(){let e=process.env.OKX_A2A_SENTRY_DSN?.trim()||process.env.SENTRY_DSN?.trim()||ti,n=be("openclaw");an({aiProvider:n,runtimeSurface:Ct(n)}),
|
|
28
|
+
`).run(_,new Date().toISOString(),g.id),u(`[okx-a2a:outbox-drain] delivery failed id=${g.id} kind=${g.kind} attempts=${x}: ${_}`))}return fn({delivered:i,failed:d,abandoned:c}).shouldEmit&&f.info(a.SESSION_DISPATCHED,dr({delivered:i,failed:d,abandoned:c,batchSize:s.length})),{delivered:i,failed:d,abandoned:c,skipped:!1}}finally{r.close()}}function qr(e={}){let n=e.intervalMs??qs,t=!1,r=async()=>{if(!t){t=!0;try{await Zs({...e.dbPath!==void 0?{dbPath:e.dbPath}:{},...e.limit!==void 0?{limit:e.limit}:{}})}catch(s){u("[okx-a2a:outbox-drain] tick failed:",s)}finally{t=!1}}},o=setInterval(()=>{r()},n);return o.unref?.(),r(),()=>{clearInterval(o)}}k();var ei=process.env.SENTRY_ENV==="dev"?"dev":"prod";function ni(e){return e?.trim().toLowerCase().replace(/[^a-z0-9_.:-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,128)||void 0}var Yr={projectName:"okx/openclaw-okx-a2a-extension",release:"0.2.17-beta-a72a480b58-261013200517",environment:ei,runtimeContainer:ni(process.env.OKX_A2A_RUNTIME_CONTAINER)};on();var V,W,ti="https://e20ff987c945887733de9ec6cca87aba@sentry.coinall.ltd/apmfe/70295";function ri(e){let n=e?.details?.requestId;return typeof n=="string"&&n.trim()?`openclaw devices approve ${n}`:"openclaw devices approve --latest"}function oi(e){let n=e?.details??{},t=Me(e);return["OKX A2A plugin needs OpenClaw gateway `operator.admin` scope before it can create sessions, inject chat messages, and route XMTP conversations.","","Ask the user whether they approve granting this scope to the OKX A2A plugin.","","If the user approves, ask them to run this command on the OpenClaw host:","","```bash",ri(e),"```","",`requestId: ${n.requestId??""}`,`deviceId: ${n.deviceId??""}`,`requestedScopes: ${Array.isArray(n.requestedScopes)?n.requestedScopes.join(","):""}`,`approvedScopes: ${Array.isArray(n.approvedScopes)?n.approvedScopes.join(","):""}`,t?`hint: ${t}`:""].filter(Boolean).join(`
|
|
29
|
+
`)}function si(){ce({key:rr()}).then(()=>{u("[okx-a2a:service] gateway client admin precheck succeeded"),f.info(a.GATEWAY_STARTED,{source:"gateway_preconnect",outcome:"ok"})},e=>{u("[okx-a2a:service] gateway client admin precheck failed:",e),f.error(a.GATEWAY_CONNECT_FAILED,e instanceof Error?e:new Error(String(e)),{source:"gateway_preconnect",code:String(e?.gatewayCode??e?.details?.code??""),reason:String(e?.details?.reason??""),requestId:String(e?.details?.requestId??"")}),Jn(oi(e),{source:"gateway_preconnect"}).then(({dispatched:n,failed:t})=>{f.info(a.USER_DISPATCHED,{source:"gateway_preconnect",outcome:t.length===0?"all_ok":"partial",dispatchedChannels:n.join(","),failedChannels:t.join(","),dispatchedCount:String(n.length),failedCount:String(t.length)})},n=>{f.error(a.USER_DISPATCH_FAILED,n instanceof Error?n:new Error(String(n)),{source:"gateway_preconnect"})})})}function ii(){let e=process.env.OKX_A2A_SENTRY_DSN?.trim()||process.env.SENTRY_DSN?.trim()||ti,n=be("openclaw");an({aiProvider:n,runtimeSurface:Ct(n)}),Lt({dsn:e,...Yr,agentPlatform:"openclaw"})}function et(e,n){let t=[e?.sessionKey,e?.context?.sessionKey,e?.ctx?.sessionKey,e?.hookContext?.sessionKey,n?.sessionKey];for(let r of t)if(typeof r=="string"&&r.trim())return r;return null}function nt(e,n){let t=[e?.runId,e?.agentRunId,e?.context?.runId,e?.context?.agentRunId,e?.ctx?.runId,e?.ctx?.agentRunId,e?.hookContext?.runId,e?.hookContext?.agentRunId,n?.runId,n?.agentRunId];for(let r of t)if(typeof r=="string"&&r.trim())return r;return null}function ai(e){let n=Vr(e),t=new Set([e]);for(let[r,o]of P())r&&r!==n&&o.sessionKey&&t.add(o.sessionKey);return[...t]}function Vr(e){let n=e.split(":");return n.length>=4&&n[0]==="agent"?n[2]??null:null}function O(e,n,t,r){let o="0.2.17-beta-a72a480b58-261013200517",s=r.sessionKey?Vr(r.sessionKey)??"unknown":"missing",i=t instanceof Error?t.message:String(t);u(`[okx-a2a:hook] ${e} bookkeeping failed; continuing phase=${n} pluginVersion=${o} channel=${s} hasRunId=${r.runId?"true":"false"} error=${i}`)}function tt(e,n){let t=e[n];if(typeof t!="string"||!t.trim())throw new Error(`Missing required param ${n}`);return t}function E(e,n){let t=e[n];return typeof t=="string"&&t.trim()?t:void 0}function rt(e,n){let t=e[n];if(!Array.isArray(t))return;let r=t.filter(o=>typeof o=="string"&&o.trim().length>0).map(o=>o.trim());return r.length>0?r:void 0}function di(e,n){let t=e[n];return typeof t=="boolean"?t:void 0}var L={id:"okx-a2a",name:"OKX A2A Plugin",version:"0.2.17-beta-a72a480b58-261013200517",register(e){lt(e.runtime),e.registerChannel({plugin:Ut}),e.registerGatewayMethod("okx-a2a.health",async({respond:n})=>{n(!0,{ok:!0,provider:"openclaw",pluginId:L.id,pluginVersion:L.version,startedAt:W??null})},{scope:"operator.admin"}),e.registerGatewayMethod("okx-a2a.dispatch_user",async({params:n,respond:t})=>{try{let r=tt(n,"content"),o=E(n,"label"),s=E(n,"sessionKey"),i=rt(n,"sessionKeys"),d=E(n,"jobId"),c=E(n,"currentSessionKey"),l=E(n,"idempotencyKey");t(!0,i?await qn({sessionKeys:i,content:r,label:o,idempotencyKey:l}):s?await Yn({sessionKey:s,content:r,label:o,idempotencyKey:l}):await Hn({content:r,label:o,jobId:d,currentSessionKey:c,idempotencyKey:l}))}catch(r){t(!1,void 0,{code:"INVALID_REQUEST",message:r instanceof Error?r.message:String(r)})}},{scope:"operator.admin"}),e.registerGatewayMethod("okx-a2a.prompt_user",async({params:n,respond:t})=>{try{let r=tt(n,"userContent"),o=tt(n,"llmContent"),s=E(n,"sessionKey"),i=rt(n,"sessionKeys"),d=E(n,"jobId"),c=E(n,"currentSessionKey"),l=E(n,"idempotencyKey");t(!0,i?await Wn({sessionKeys:i,userContent:r,llmContent:o,idempotencyKey:l}):s?await zn({sessionKey:s,userContent:r,llmContent:o,idempotencyKey:l}):await Vn({userContent:r,llmContent:o,jobId:d,currentSessionKey:c,idempotencyKey:l}))}catch(r){t(!1,void 0,{code:"INVALID_REQUEST",message:r instanceof Error?r.message:String(r)})}},{scope:"operator.admin"}),e.registerGatewayMethod("okx-a2a.delete_sessions",async({params:n,respond:t})=>{try{let r=E(n,"sessionKey"),o=rt(n,"sessionKeys"),s=E(n,"jobId");if(!r&&!o&&!s)throw new Error("Missing required selector: sessionKey, sessionKeys, or jobId");let i=E(n,"myAgentId"),d=E(n,"toAgentId"),c=E(n,"myXmtpAddress"),l=E(n,"toXmtpAddress"),g=di(n,"deleteTranscript");t(!0,await yr({...r?{sessionKey:r}:{},...o?{sessionKeys:o}:{},...s?{jobId:s}:{},...i?{myAgentId:i}:{},...d?{toAgentId:d}:{},...c?{myXmtpAddress:c}:{},...l?{toXmtpAddress:l}:{},...g!==void 0?{deleteTranscript:g}:{}}))}catch(r){t(!1,void 0,{code:"INVALID_REQUEST",message:r instanceof Error?r.message:String(r)})}},{scope:"operator.admin"}),e.registerHook("agent:bootstrap",async n=>{let t=n.context,r=t.bootstrapFiles;if(Array.isArray(r))try{let o=r.map(i=>`${i.name}(${i.missing?"missing":`${i.content?.length??0}b`})`).join(", ");u(`[okx-a2a:hook] agent:bootstrap agentId=${t.agentId??"?"} files=[${o}]`);let s=r.reduce((i,d)=>i+(d.content?.length??0),0);f.info(a.BOOTSTRAP_APPLIED,{openclawAgentId:t.agentId??"",promptSize:String(s),fileCount:String(r.length),missingCount:String(r.filter(i=>i.missing).length)})}catch(o){f.error(a.BOOTSTRAP_FAILED,o instanceof Error?o:void 0,{openclawAgentId:t.agentId??""})}},{name:"okx-a2a-agent-bootstrap"}),e.on("before_agent_run",async(n,t)=>{let r=et(n,t),o=nt(n,t);if(!r){u("[xmtp_prompt_user:queue] before_agent_run ignored: missing sessionKey");return}let s=[r];try{s=ai(r)}catch(i){O("before_agent_run","route_discovery",i,{runId:o,sessionKey:r})}try{Sr({runId:o,sessionKey:r,routeSessionKeys:s})&&console.log(`[okx-a2a:hook] remembered gateway route origin runId=${o} sessionKey=${r} routeSessionKeys=${s.join(",")}`)}catch(i){O("before_agent_run","route_origin",i,{runId:o,sessionKey:r})}try{xn(r)}catch(i){O("before_agent_run","prompt_user_running",i,{runId:o,sessionKey:r})}}),e.on("before_tool_call",async(n,t)=>{let r=null,o=null;try{r=et(n,t),o=nt(n,t)}catch(i){O("before_tool_call","context",i,{runId:o,sessionKey:r});return}try{wn(r)}catch(i){O("before_tool_call","remember_recent_session",i,{runId:o,sessionKey:r})}let s=r?[r]:[];try{s=[...new Set([...Ge({sessionKey:r}),...$e({runId:o,sessionKey:r})])]}catch(i){O("before_tool_call","route_discovery",i,{runId:o,sessionKey:r})}try{let i=Ir({toolName:n?.toolName,params:n?.params,sessionKey:r,routeSessionKeys:s});return i?(console.log(`[okx-a2a:hook] injected gateway session env tool=${n?.toolName??"?"} sessionKey=${r} routeSessionKeys=${s.join(",")}`),{params:i}):void 0}catch(i){O("before_tool_call","env_injection",i,{runId:o,sessionKey:r});return}},{priority:50}),e.on("agent_end",async(n,t)=>{let r=null,o=null;try{r=et(n,t),o=nt(n,t)}catch(s){O("agent_end","context",s,{runId:o,sessionKey:r});return}try{Ar({runId:o,sessionKey:r})}catch(s){O("agent_end","route_origin_cleanup",s,{runId:o,sessionKey:r})}if(!r){u("[xmtp_prompt_user:queue] agent_end ignored: missing sessionKey");return}try{Un(r)}catch(s){O("agent_end","prompt_user_ended",s,{runId:o,sessionKey:r})}}),e.registerService({id:"okx-a2a:core",start:async()=>{u("[okx-a2a:service] okx-a2a:core starting (multi-identity mode); initializing communication identities..."),W=Date.now(),ii(),f.info(a.GATEWAY_STARTED,{onchainosAgentId:"*",pid:String(process.pid),pluginId:L.id,pluginVersion:L.version,nodeVersion:process.version,startedAt:String(W)}),Sn(),si(),V&&V(),V=qr(),u("[okx-a2a:service] OpenClaw lightweight gateway initialized; node daemon owns XMTP receive/send/agent sync.")},stop:async()=>{V&&(V(),V=void 0),An(),u("[okx-a2a:service] okx-a2a:core stopped");let n=Date.now();f.info(a.GATEWAY_STOPPED,{onchainosAgentId:"*",pid:String(process.pid),pluginId:L.id,pluginVersion:L.version,stoppedAt:String(n),uptimeMs:W?String(n-W):"unknown"}),W=void 0}})}},ci=L;
|
|
30
30
|
if(module.exports&&module.exports.__esModule&&module.exports.default){module.exports=module.exports.default;}
|
package/openclaw.plugin.json
CHANGED
package/package.json
CHANGED