@coremail/lunkr-openclaw 1.1.5 → 1.1.6

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/index.js CHANGED
@@ -13,7 +13,7 @@ Minimum version required to store current data is: `+s+`.
13
13
  `+a,d=a;for(let m=-1;m<t+1;m+=2){for(let f=-1;f<t;f++)d+=u[Hr(i,t,f,m)];d+=u[Hr(i,t,t,m)]+p}return d+=pn,typeof o=="function"&&o(null,d),d}});var Yr=A(Jr=>{var vd=zr(),bd=Wr();Jr.render=function(n,e,o){return e&&e.small?bd.render(n,e,o):vd.render(n,e,o)}});var ei=A(Xr=>{var yd=Qn();function Qr(n,e){let o=n.a/255,t=e+'="'+n.hex+'"';return o<1?t+" "+e+'-opacity="'+o.toFixed(2).slice(1)+'"':t}function Zt(n,e,o){let t=n+e;return typeof o<"u"&&(t+=" "+o),t}function kd(n,e,o){let t="",i=0,s=!1,a=0;for(let r=0;r<n.length;r++){let c=Math.floor(r%e),u=Math.floor(r/e);!c&&!s&&(s=!0),n[r]?(a++,r>0&&c>0&&n[r-1]||(t+=s?Zt("M",c+o,.5+u+o):Zt("m",i,0),i=0,s=!1),c+1<e&&n[r+1]||(t+=Zt("h",a),a=0)):i++}return t}Xr.render=function(e,o,t){let i=yd.getOptions(o),s=e.modules.size,a=e.modules.data,r=s+i.margin*2,c=i.color.light.a?"<path "+Qr(i.color.light,"fill")+' d="M0 0h'+r+"v"+r+'H0z"/>':"",u="<path "+Qr(i.color.dark,"stroke")+' d="'+kd(a,s,i.margin)+'"/>',p='viewBox="0 0 '+r+" "+r+'"',m='<svg xmlns="http://www.w3.org/2000/svg" '+(i.width?'width="'+i.width+'" height="'+i.width+'" ':"")+p+' shape-rendering="crispEdges">'+c+u+`</svg>
14
14
  `;return typeof t=="function"&&t(null,m),m}});var Zr=A(To=>{var wd=ei();To.render=wd.render;To.renderToFile=function(e,o,t,i){typeof i>"u"&&(i=t,t=void 0);let s=G("fs"),r='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+To.render(o,t);s.writeFile(e,r,i)}});var ec=A(Oo=>{var ni=Qn();function Cd(n,e,o){n.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=o,e.width=o,e.style.height=o+"px",e.style.width=o+"px"}function _d(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Oo.render=function(e,o,t){let i=t,s=o;typeof i>"u"&&(!o||!o.getContext)&&(i=o,o=void 0),o||(s=_d()),i=ni.getOptions(i);let a=ni.getImageWidth(e.modules.size,i),r=s.getContext("2d"),c=r.createImageData(a,a);return ni.qrToImageData(c.data,e,i),Cd(r,s,a),r.putImageData(c,0,0),s};Oo.renderToDataURL=function(e,o,t){let i=t;typeof i>"u"&&(!o||!o.getContext)&&(i=o,o=void 0),i||(i={});let s=Oo.render(e,o,i),a=i.type||"image/png",r=i.rendererOpts||{};return s.toDataURL(a,r.quality)}});var oc=A(Xn=>{var Sd=gt(),oi=Et(),nc=ec(),Ad=ei();function ti(n,e,o,t,i){let s=[].slice.call(arguments,1),a=s.length,r=typeof s[a-1]=="function";if(!r&&!Sd())throw new Error("Callback required as last argument");if(r){if(a<2)throw new Error("Too few arguments provided");a===2?(i=o,o=e,e=t=void 0):a===3&&(e.getContext&&typeof i>"u"?(i=t,t=void 0):(i=t,t=o,o=e,e=void 0))}else{if(a<1)throw new Error("Too few arguments provided");return a===1?(o=e,e=t=void 0):a===2&&!e.getContext&&(t=o,o=e,e=void 0),new Promise(function(c,u){try{let p=oi.create(o,t);c(n(p,e,t))}catch(p){u(p)}})}try{let c=oi.create(o,t);i(null,n(c,e,t))}catch(c){i(c)}}Xn.create=oi.create;Xn.toCanvas=ti.bind(null,nc.render);Xn.toDataURL=ti.bind(null,nc.renderToDataURL);Xn.toString=ti.bind(null,function(n,e,o){return Ad.render(n,o)})});var ac=A(Xe=>{var tc=gt(),ii=Et(),Rd=Mr(),ic=Br(),Ld=Yr(),sc=Zr();function Zn(n,e,o){if(typeof n>"u")throw new Error("String required as first argument");if(typeof o>"u"&&(o=e,e={}),typeof o!="function")if(tc())e=o||{},o=null;else throw new Error("Callback required as last argument");return{opts:e,cb:o}}function Id(n){return n.slice((n.lastIndexOf(".")-1>>>0)+2).toLowerCase()}function Eo(n){switch(n){case"svg":return sc;case"txt":case"utf8":return ic;case"png":case"image/png":default:return Rd}}function Pd(n){switch(n){case"svg":return sc;case"terminal":return Ld;case"utf8":default:return ic}}function eo(n,e,o){if(!o.cb)return new Promise(function(t,i){try{let s=ii.create(e,o.opts);return n(s,o.opts,function(a,r){return a?i(a):t(r)})}catch(s){i(s)}});try{let t=ii.create(e,o.opts);return n(t,o.opts,o.cb)}catch(t){o.cb(t)}}Xe.create=ii.create;Xe.toCanvas=oc().toCanvas;Xe.toString=function(e,o,t){let i=Zn(e,o,t),s=i.opts?i.opts.type:void 0,a=Pd(s);return eo(a.render,e,i)};Xe.toDataURL=function(e,o,t){let i=Zn(e,o,t),s=Eo(i.opts.type);return eo(s.renderToDataURL,e,i)};Xe.toBuffer=function(e,o,t){let i=Zn(e,o,t),s=Eo(i.opts.type);return eo(s.renderToBuffer,e,i)};Xe.toFile=function(e,o,t,i){if(typeof e!="string"||!(typeof o=="string"||typeof o=="object"))throw new Error("Invalid argument");if(arguments.length<3&&!tc())throw new Error("Too few arguments provided");let s=Zn(o,t,i),a=s.opts.type||Id(e),c=Eo(a).renderToFile.bind(null,e);return eo(c,o,s)};Xe.toFileStream=function(e,o,t){if(arguments.length<2)throw new Error("Too few arguments provided");let i=Zn(o,t,e.emit.bind(e,"error")),a=Eo("png").renderToFileStream.bind(null,e);eo(a,o,i)}});var cc=A((Ug,rc)=>{rc.exports=ac()});import*as Fo from"https";import*as pc from"crypto";import{WebSocket as lc}from"ws";import{v4 as uc}from"uuid";async function jo(n,e,o,t){return new Promise((i,s)=>{let a=JSON.stringify(o),r=`${n}?func=${e}`;t?.sid&&(r+=`&sid=${encodeURIComponent(t.sid)}`);let c=t?.baseUrl||no,u={...Ud,"Content-Length":Buffer.byteLength(a)};t?.cookies&&Object.keys(t.cookies).length>0&&(u.Cookie=Object.entries(t.cookies).map(([m,f])=>`${m}=${f}`).join("; "));let d=Fo.request({hostname:c,port:443,path:r,method:"POST",headers:u},m=>{let f="",h={},x=m.headers["set-cookie"];if(x)for(let g of x){let v=g.match(/^([^=]+)=([^;]+)/);v&&(h[v[1].trim()]=v[2].trim())}m.on("data",g=>f+=g),m.on("end",()=>{try{i({data:JSON.parse(f),cookies:h})}catch{s(new Error(`Invalid JSON: ${f}`))}})});d.on("error",s),d.write(a),d.end()})}async function Td(n){return new Promise((e,o)=>{Fo.get(n,t=>{let i="";t.on("data",s=>i+=s),t.on("end",()=>e(i))}).on("error",o)})}async function si(n={}){let{debug:e=!1,timeout:o=12e4,device:t}=n,i=s=>{e&&console.log(`[QR Login] ${s}`)};try{i("[1] Generating temporary session...");let s=await jo("/lunkr/s/json","cim.user:genTempSession",{type:"qrLogin"});if(s.data.code!=="S_OK")return{success:!1,error:`genTempSession failed: ${s.data.code} - ${s.data.msg||s.data.reason}`};let a=s.data.var?.sid;if(!a)return{success:!1,error:"No sid in response"};i(`Temporary session ID: ${a}`),i("[2] Socket.IO HTTP handshake...");let r=`https://${no}/socket.io/1/?t=${Date.now()}&EIO=3&transport=polling`,c=await Td(r),u=c.indexOf('0{"sid"'),p=u>=0?c.substring(u):c;if(!p.startsWith("0{"))return{success:!1,error:"Handshake format error"};let d=JSON.parse(p.substring(1)),m=d.sid,f=d.pingInterval??25e3;i(`eioSid: ${m}, pingInterval: ${f}`),i("[3] WebSocket connection...");let h=`wss://${no}/socket.io/1/websocket/?EIO=3&transport=websocket&sid=${encodeURIComponent(m)}`;return new Promise(x=>{let g=setTimeout(()=>{v.close(),x({success:!1,error:"Timeout waiting for QR scan"})},o),v=new lc(h,{headers:{Host:no,Origin:`https://${no}`,"User-Agent":"Mozilla/5.0"}}),w=!1,y;v.on("open",()=>{i("WebSocket connected, sending 2probe..."),v.send("2probe")}),v.on("message",k=>{let C=k.toString();if(i(`Received: ${C.substring(0,100)}`),C.includes("3probe")){i("Received 3probe, sending 5 and auth"),v.send("5");let b={clientId:`webmail:${a}`,sid:a,msg_v:100,uuid:uc(),TmpSes:1};v.send(`42["auth",${JSON.stringify(b)}]`);let S=`https://www.coremail.cn/app/poster.html?action=qrLogin&sid=${encodeURIComponent(a)}`;console.log(""),console.log(` ${l("login.qrcode_title")}`),console.log(""),dc.toString(S,{type:"terminal",small:!0},(T,R)=>{T?console.error("QR code generation failed:",T.message):console.log(R)}),console.log(` ${l("login.qrcode_scan_prompt")}`),console.log(""),e&&console.log(`QR URL: ${S}
15
15
  `),y=setInterval(()=>{v.readyState===lc.OPEN&&v.send("2")},f)}if(C.startsWith("42"))try{let b=JSON.parse(C.substring(2)),S=b[0],T=b[1];if(S==="ready"&&!w){w=!0,i("Auth ready, subscribing to scan events...");let R=`/onstat/mail/${a}/op_app_scanqrcode`;v.send(`42["subscribe",{"topic":"${R}"}]`)}if(S==="message"&&T?.payload){let R=typeof T.payload=="string"?JSON.parse(T.payload):T.payload;if(i(`Scan status: ${R.status}`),R.status==="verify"&&console.log(l("login.qrcode_scanned")),R.status==="auth"){i(`Confirmed: ${R.user?.email}`);let q=R.user?.email,B={uid:q,authSid:a,authToken:R.token};i("Calling checkVersionAndLogin..."),jo("/lunkr/s/json","cim.user:checkVersionAndLogin",B).then(N=>{let O=N.data,V=N.cookies;if(i(`Login result: ${JSON.stringify(O)}`),O.code==="S_OK"&&O.var?.sid){let oe=O.var.sid,pe=q,Oe=O.var.self_uid;i(`Login successful, sid: ${oe}, email: ${pe}, selfUid: ${Oe}`),i("Calling getApiToken...");let Ee=t||{device_uuid:uc(),device_os:"Unknown",device_model:"pc",device_name:"OpenClaw"};jo("/lunkr/s/json","cim.user:getApiToken",Ee,{sid:oe,baseUrl:"betaweb.lunkr.cn",cookies:V}).then(ao=>{let ls=ao.data;i(`Token result: ${JSON.stringify(ls)}`),clearTimeout(g),clearInterval(y),v.close(),x({success:!0,apiToken:ls.var?.api_token,email:pe,selfUid:Oe,deviceUuid:Ee.device_uuid})}).catch(ao=>{console.error(`getApiToken failed: ${ao.message}`),clearTimeout(g),clearInterval(y),v.close(),x({success:!1,error:`getApiToken failed: ${ao.message}`})})}else clearTimeout(g),clearInterval(y),v.close(),x({success:!1,error:`Login failed: ${JSON.stringify(O)}`})}).catch(N=>{clearTimeout(g),clearInterval(y),v.close(),x({success:!1,error:N.message})})}}}catch(b){i(`Event parse failed: ${b.message}`)}C==="2"&&v.send("3")}),v.on("error",k=>{i(`WebSocket error: ${k.message}`),clearTimeout(g),clearInterval(y),x({success:!1,error:k.message})}),v.on("close",()=>{i("WebSocket closed"),clearTimeout(g),clearInterval(y)})})}catch(s){return{success:!1,error:s.message}}}async function Le(n,e,o,t={}){let{debug:i=!1}=t,s=a=>{i&&console.log(`[API Token Login] ${a}`)};try{s("Calling getLunkrSid..."),s(`email: ${n}`),s(`deviceUuid: ${o}`);let a=Date.now().toString(),r=pc.createHash("sha256").update(`${a}:${o}:${e}`).digest("base64");s(`timestamp: ${a}`),s(`token_hash: ${r}`);let c=await jo("/lunkr/s/json","cim.user:getLunkrSid",{email:n,timestamp:a,device_uuid:o,token_hash:r},{baseUrl:"betaweb.lunkr.cn"});if(s(`Result: ${JSON.stringify(c.data)}`),c.data.code==="S_OK"&&c.data.var?.sid){let u=c.data.var.cookie?`Cim=${c.data.var.cookie}`:c.cookies?.Cim?`Cim=${c.cookies.Cim}`:void 0;return{success:!0,sid:c.data.var.sid,email:n,selfUid:c.data.var.uid,cookie:u}}else return c.data.code==="FA_REQUEST_EXPIRED"?{success:!1,error:l("login.clock_error")}:{success:!1,error:`getLunkrSid failed: ${c.data.code} - ${c.data.msg||"Unknown error"}`}}catch(a){return{success:!1,error:a.message}}}var dc,no,Ud,Rn=se(()=>{dc=Jo(cc(),1);U();no="lunkr.coremail.cn",Ud={Accept:"text/x-json","Accept-Language":"zh-CN,zh;q=0.9,en;q=0.8","Cache-Control":"no-cache",Connection:"keep-alive","Content-Type":"text/x-json; charset=UTF-8"}});import*as qo from"path";function mc(n,e){return l("message.prefix",{sender:n||"Unknown",bot:e||"Bot"})}function qe(n,e,o,t=!1){return t?n:mc(e,o)+n}function ai(n){return Od.test(n.trim())}function ri(n){return Ed.test(n.trim())}function $o(n){return jd.test(n.trim())}function ci(n){return Fd.test(n.trim())}function Ie(n){let e=n.trim();return ai(e)||ri(e)||$o(e)||ci(e)}function Do(n){let e=n.trim();return ai(e)||ci(e)&&!$o(e)?"user":ri(e)||$o(e)?"group":"unknown"}function li(n){let e=n.replace(/[<>:"/\\|?*\x00-\x1f]/g,"_").replace(/\.\./g,"_").replace(/^\.+/,"_").replace(/\.+$/,"_").trim();if(e.length>200){let o=qo.extname(e);e=qo.basename(e,o).substring(0,200-o.length)+o}return e||"download"}function ue(n){if(!n)return"";let e;if(typeof n=="string"?e=new Date(n):e=new Date(n<=1e10?n*1e3:n),isNaN(e.getTime()))return"";try{return e.toLocaleString("zh-CN",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch{return""}}function dn(n){if(n==null)return"";let e=["B","KB","MB","GB"],o=n,t=0;for(;o>=1024&&t<e.length-1;)o/=1024,t++;return`${o.toFixed(1)} ${e[t]}`}function $d(n){let e=0;for(let o of n){let t=o.codePointAt(0);e+=t>=11904&&t<=40959||t>=63744&&t<=64255||t>=65072&&t<=65103||t>=65280&&t<=65376||t>=131072&&t<=195103?2:1}return e}function I(n,e){let o=Math.max(0,e-$d(n));return n+" ".repeat(o)}var Od,Ed,jd,Fd,De=se(()=>{U();Od=/^#\d+#U$/,Ed=/^#\d+#T$/,jd=/^t\.\./i,Fd=/^[^\s@]+@[^\s@]+\.[^\s@]+$/});function Ln(n){return qd.includes(n)}function fc(n){let e=["ETIMEDOUT","ECONNREFUSED","ECONNRESET","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH","EPIPE","socket hang up","network","timeout","fetch failed"],o=n.toLowerCase();return e.some(t=>o.includes(t.toLowerCase()))?"network":"rejected"}async function he(n,e){let o=L(),t=o.accounts?.find(c=>c.accountId===n);if(!t)return{success:!1,error:`Account not found: ${n}`,reason:"no_credentials"};if(!t.apiToken)return{success:!1,error:"No apiToken available for refresh",reason:"no_credentials"};let i=e||o.device_uuid;if(!i)return{success:!1,error:"No device UUID available",reason:"no_credentials"};let s=t.email||n,a;try{a=await Le(s,t.apiToken,i)}catch(c){let u=c instanceof Error?c.message:String(c);return{success:!1,error:u,reason:fc(u)}}if(a.success&&a.sid&&a.cookie){let c={sid:a.sid,cookie:a.cookie,baseUrl:t.session?.baseUrl||"https://lunkr.coremail.cn",apiPath:t.session?.apiPath||"/lunkr/s/json",selfUid:a.selfUid||t.session?.selfUid||"",senderName:t.session?.senderName},u=o.accounts?.findIndex(p=>p.accountId===n)??-1;return u>=0&&o.accounts&&(o.accounts[u].session=c,E(o)),{success:!0,session:c}}let r=a.error||"Unknown error during token login";return{success:!1,error:r,reason:fc(r)}}var qd,oo=se(()=>{re();Rn();qd=["FA_SESSION_EXPIRED","FA_AUTH_FAILED","FA_NO_SESSION","FA_SID_INVALID","FA_INVALID_SESSION"]});import*as we from"fs";import*as In from"path";import*as Rc from"os";function Wd(n){let e={...n,_clients:new Map,_lastValidation:new Map,_validationInterval:3e5};return Vd=e,e}function Lc(n){Wd(n)}function Pc(n,e){Ic.set(n,{...e,lastAccess:Date.now()})}function Mo(){let n;for(let[e,o]of Ic)(!n||o.lastAccess>n.context.lastAccess)&&(n={key:e,context:o});if(n)return{workspaceKey:n.key,workspaceDir:n.context.workspaceDir,filesDir:n.context.filesDir,accountId:n.context.accountId}}function Tc(n,e,o){if(!(!n||o.length===0)&&(Ne.set(n,{mid:n,time:e,attachments:o.map(t=>({fileId:t.fileId,uid:t.uid,title:t.title,contentType:t.contentType||null,fileSize:t.fileSize||null,type:t.type||null,inline:t.inline||!1})),cachedAt:Date.now()}),Ne.size>pi)){let t=Date.now();for(let[i,s]of Ne)t-s.cachedAt>Uc&&Ne.delete(i);if(Ne.size>pi){let i=[...Ne.entries()].sort((s,a)=>s[1].cachedAt-a[1].cachedAt);for(let s=0;s<i.length-pi/2;s++)Ne.delete(i[s][0])}}}function Oc(n){let e=Ne.get(n);return e?Date.now()-e.cachedAt>Uc?(Ne.delete(n),null):e.attachments:null}function di(){return In.join(Rc.homedir(),".lunkr")}function mi(n){return n.replace(/#/g,"").replace(/:/g,"_")}function Ec(n){let e=mi(n),o=In.join(di(),"session-workspaces",e);return we.existsSync(o)||we.mkdirSync(o,{recursive:!0}),o}function jc(n){let e=mi(n),o=In.join(di(),"session-workspaces",e);if(we.existsSync(o))for(let t of we.readdirSync(o))we.rmSync(In.join(o,t),{recursive:!0,force:!0})}function Fc(n){let e=mi(n),o=In.join(di(),"session-files",e);return we.existsSync(o)||we.mkdirSync(o,{recursive:!0}),o}var Vd,Ic,Ne,Uc,pi,mn=se(()=>{re();Vd=null;Ic=new Map;Ne=new Map,Uc=1440*60*1e3,pi=1e3});import*as ce from"fs";import*as Ce from"path";import*as Wc from"os";import*as Jc from"crypto";function M(n){let e=ie.fromConfig(n);if(!e)throw new Error(l("api.no_account"));return e}var hi,ie,en=se(()=>{hi=Jo(lt(),1);U();vn();tn();yo();Rn();De();re();mn();ie=class n{client;sid;session;botName;senderName;role;cookies;constructor(e){this.session=e.session,this.sid=e.session.sid,this.botName=e.botName||"Bot",this.senderName=e.senderName||"",this.role=e.role||"standard",this.client=new F(e.session.baseUrl,{apiPath:e.session.apiPath}),this.cookies={};for(let o of e.session.cookie.split(";")){let t=o.trim();if(t.includes("=")){let i=t.indexOf("="),s=t.substring(0,i).trim(),a=t.substring(i+1).trim();this.cookies[s]=a}}this.client.setCookies(this.cookies)}static fromConfig(e){let o=L(),t=e?o.accounts?.find(i=>i.accountId===e&&i.session):mo(o);return t?.session?new n({session:t.session,botName:o.bot_name,senderName:t.session.senderName||"",role:t.role}):null}static fromAccount(e,o){if(!e.session)return null;let t=o||L();return new n({session:e.session,botName:t.bot_name,senderName:e.session.senderName||"",role:e.role})}async checkSession(){try{if((await this.client.postJson({func:"cim.common:getOrgInfo",sid:this.sid})).code==="S_OK")return!0}catch{}let e=await this.tryApiTokenRelogin();return e||(console.error(""),console.error(l("api.session_expired_relogin")),console.error(l("api.session_expired_qrcode")),console.error(l("api.session_expired_password"))),e}async tryApiTokenRelogin(){let e=L(),o=e.accounts.find(a=>a.session?.selfUid===this.session.selfUid);if(!o?.apiToken)return!1;let t=o.email||o.accountId,i=await Le(t,o.apiToken,e.device_uuid);if(!i.success||!i.sid||!i.cookie)return!1;o.session={...o.session,sid:i.sid,cookie:i.cookie,selfUid:i.selfUid||o.session.selfUid},E(e),this.sid=i.sid,this.session=o.session;let s={};for(let a of i.cookie.split(";")){let r=a.trim();if(r.includes("=")){let c=r.indexOf("="),u=r.substring(0,c).trim(),p=r.substring(c+1).trim();s[u]=p}}return this.cookies=s,this.client.setCookies(this.cookies),!0}getSelfUid(){return this.session.selfUid}async callApi(e){return this.client.postJson({func:e.func,sid:this.sid,query:e.query,payload:e.payload})}async fetchSenderName(){try{let e=await this.client.postJson({func:"cim.common:getCimPrefAttr",sid:this.sid,payload:{return_field:"nickname,true_name,name"}});if(e.code==="S_OK"&&e.var){let o=e.var,t=o.nickname||o.true_name||o.name;return t?String(t).trim():null}}catch{}return null}async ensureSenderName(){if(this.senderName)return this.senderName;let e=await this.fetchSenderName();if(e)return this.senderName=e,e;let o=this.session.selfUid;return o&&o.includes("@")?o.split("@")[0]:o||"Unknown"}async searchContacts(e,o=20){let t=[],i=new Set;try{let s=await this.client.postJson({func:"cim.pab:getRecentContacts",sid:this.sid});if(s.code==="S_OK"&&Array.isArray(s.var))for(let a of s.var){if(typeof a!="object"||!a)continue;let r=a,c=String(r.uid||""),u=String(r.email||"").toLowerCase(),p=String(r.true_name||"").toLowerCase();if(u.includes(e.toLowerCase())||p.includes(e.toLowerCase())){if(i.has(c))continue;i.add(c),r.email&&i.add(String(r.email)),t.push({uid:c,email:r.email,trueName:r.true_name,name:r.name})}}}catch{}try{let s=await this.client.postJson({func:"cim.container:searchContacts",sid:this.sid,payload:{keyword:e,windowSize:o}});if(s.code==="S_OK"&&Array.isArray(s.var))for(let a of s.var){if(typeof a!="object"||!a)continue;let r=a,c=String(r.uid||"");i.has(c)||(i.add(c),r.email&&i.add(String(r.email)),t.push({uid:c,email:r.email,trueName:r.true_name,name:r.name}))}}catch{}try{let s=await this.client.postJson({func:"oab:autoMatch",sid:this.sid,payload:{keyword:e,limit:o}});if(s.code==="S_OK"&&Array.isArray(s.var))for(let a of s.var){if(typeof a!="object"||!a)continue;let r=a,c=String(r.email||"");!c||i.has(c)||(i.add(c),t.push({uid:c,email:c,trueName:r.true_name,name:r.true_name}))}}catch{}return t.slice(0,o)}async searchGroups(e,o=20){try{let t=await this.client.postJson({func:"cim.group:search",sid:this.sid,payload:{keyword:e,limit:o,return_field:"uid,email,true_name,name,description"}});if(t.code==="S_OK"&&Array.isArray(t.var))return t.var.map(i=>({uid:String(i.uid||""),name:i.name,trueName:i.true_name,email:i.email,description:i.description}))}catch{}return[]}async resolveRecipient(e){let o=e.trim();if(Ie(o)){let s=Do(o);return{uid:o,type:s==="group"?"group":"user",name:o}}let t=await this.searchContacts(o,5);if(t.length>0){let s=t[0];return{uid:s.uid,type:"user",name:s.trueName||s.name||o,email:s.email||void 0}}let i=await this.searchGroups(o,5);if(i.length>0){let s=i[0];return{uid:s.uid,type:"group",name:s.name||s.trueName||o,email:s.email||void 0}}throw new Error(l("api.recipient_not_found",{name:o}))}async resolveRecipientInteractive(e,o){let t=e.trim();if(Ie(t)){let a=Do(t);return{uid:t,type:a==="group"?"group":"user",name:t}}let i=await this.searchContacts(t,10);if(i.length>0){let a=i.filter(u=>u.name===t||u.trueName===t);if(a.length===1){let u=a[0];return{uid:u.uid,type:"user",name:u.trueName||u.name||t,email:u.email||void 0}}let r=0;if(i.length>1&&o){let u=i.map(p=>({uid:p.uid,name:p.trueName||p.name||p.email||p.uid,type:"user"}));r=o(u)}r<0&&(r=0);let c=i[r];return{uid:c.uid,type:"user",name:c.trueName||c.name||t,email:c.email||void 0}}let s=await this.searchGroups(t,10);if(s.length>0){let a=s.filter(u=>u.name===t||u.trueName===t);if(a.length===1){let u=a[0];return{uid:u.uid,type:"group",name:u.name||u.trueName||t,email:u.email||void 0}}let r=0;if(s.length>1&&o){let u=s.map(p=>({uid:p.uid,name:p.name||p.trueName||p.email||p.uid,type:"group"}));r=o(u)}r<0&&(r=0);let c=s[r];return{uid:c.uid,type:"group",name:c.name||c.trueName||t,email:c.email||void 0}}throw new Error(l("api.recipient_not_found",{name:t}))}async listMessages(e,o={}){let{limit:t=20,latestFirst:i=!0}=o,s={limit:t,export_field:"rf,cim,data,mail,attachments,flags,flags_detail,template,card,action,refer"};e.type==="user"?(s.uid=this.session.selfUid,s.filter={chatWithAddress:e.uid}):s.uid=e.uid,i&&(s.order="date",s.desc=!0,s.listOrder="desc");let r=await this.client.postJson({func:"cim.msg:list",sid:this.sid,payload:s});if(r.code!=="S_OK"||!Array.isArray(r.var))return[];let c=[];for(let d of r.var){if(typeof d!="object"||!d)continue;let m=d,f=m.data,h=f&&typeof f=="object"&&!Array.isArray(f)&&Object.keys(f).length>0?f:m,x=h.from||{},g=[],v=m.attachments||h.attachments;if(Array.isArray(v))for(let k of v){let C=String(k.uid||"");g.push({file_id:String(k.fileId||k.file_id||""),uid:C||null,title:String(k.title||k.filename||"")||null,content_type:k.content_type||k.ctype,file_size:Number(k.file_size||k.size||0)||null,type:Number(k.t||k.type||0)||null,inline:k.inline===!0})}let w=String(h.mid||h.uid||""),y=g;if(g.length===0){let k=Oc(w);k&&(y=k.map(C=>({file_id:C.fileId,uid:C.uid,title:C.title,content_type:C.contentType,file_size:C.fileSize,type:C.type,inline:C.inline})))}c.push({mid:w,time:ue(h.time),subject:h.subject||h.content||"",content:h.content,senderUid:x.uid||h.sender_uid||h.fromUid,senderName:x.true_name||x.email||h.sender_name||h.fromName,senderEmail:x.email||h.sender_email||h.fromEmail,attachments:y})}let u=5,p=c.filter(d=>d.attachments.length===0&&d.mid);for(let d=0;d<p.length;d+=u)await Promise.all(p.slice(d,d+u).map(async m=>{let f=await this.getMessage(m.mid);f&&f.attachments.length>0&&(m.attachments=f.attachments)}));return c}async getMessage(e){let o=await this.client.postJson({func:"cim.msg:getInfo",sid:this.sid,payload:{mid:e,export_field:"rf,cim,data,mail,attachments,flags,flags_detail,template,card,action,refer"}});if(o.code!=="S_OK"||!o.var)return null;let t=o.var,i=t.data||t,s=i.from||{},a=[],r=i.attachments;if(Array.isArray(r))for(let c of r){let u=String(c.uid||"");a.push({file_id:String(c.fileId||c.file_id||""),uid:u||null,title:String(c.title||c.filename||"")||null,content_type:c.content_type||c.ctype,file_size:Number(c.file_size||c.size||0)||null,type:Number(c.t||c.type||0)||null,inline:c.inline===!0})}return{mid:String(i.mid||i.uid||e),time:ue(i.time),subject:i.subject||i.content||"",content:i.content,sender_uid:s.uid||i.sender_uid||i.fromUid,sender_name:s.true_name||s.email||i.sender_name||i.fromName,sender_email:s.email||i.sender_email||i.fromEmail,source_id:i.gid,source_name:null,attachments:a,raw:t}}async sendMessage(e,o,t={}){let i=t.botName||this.botName,s=t.senderName||await this.ensureSenderName(),a=t.skipPrefix??(this.role==="agent"||this.role==="standard+agent"),r=qe(o,s,i,a),c=await this.client.postJson({func:"cim.msg:reply",sid:this.sid,payload:{uid:e.uid,content:r,type:"text"}});if(c.code!=="S_OK")throw new Error(l("api.send_reply_failed",{code:c.code,msg:c.msg||"Unknown error"}));let u=c.var?.[0];return{mid:String(u?.mid||""),to:e.uid,type:e.type}}async sendFile(e,o,t={}){let i=t.botName||this.botName,s=t.senderName||await this.ensureSenderName(),a=t.skipPrefix??(this.role==="agent"||this.role==="standard+agent"),r=qe(t.content||"",s,i,a),c=`c:nf:cim${Math.floor(Math.random()*9999)+1}`,u=Jc.randomUUID(),d=e.type==="user"?this.session.selfUid:e.uid,m=[];for(let x of o){let g=await this.uploadFileWithFlow(x,d,c);m.push({fileId:g.fileId,uid:g.fileUid})}let f=await this.client.postJson({func:"cim.msg:reply",sid:this.sid,payload:{uid:e.uid,content:r,type:"text",clientMid:u,attachments:m}});if(f.code!=="S_OK")throw new Error(l("api.send_reply_failed",{code:f.code,msg:f.msg||"Unknown error"}));let h=f.var?.[0];return{mid:String(h?.mid||""),to:e.uid,files:o}}async uploadFile(e,o,t){let i=Ce.resolve(e),s=Ce.basename(i);if(!ce.existsSync(i))throw new Error(l("errors.file_not_found",{path:e}));let a=ce.statSync(i),r=hi.lookup(i)||"application/octet-stream",c=ce.readFileSync(i),u=await this.client.postJson({func:"cim.file:prepare",sid:this.sid,payload:{size:a.size,composeId:t,fileName:s,uid:o,contentType:r}});if(u.code!=="S_OK")throw new Error(l("api.upload_prepare_failed",{code:u.code}));let d=u.var?.attachmentId;if(!d)throw new Error(l("api.upload_no_attachment_id"));let m=`${this.session.baseUrl}${this.session.apiPath}?func=cim.file:directData&sid=${encodeURIComponent(this.sid)}&composeId=${encodeURIComponent(t)}&attachmentId=${d}&offset=0&uid=${encodeURIComponent(o)}`,h={"Content-Type":"application/octet-stream",Cookie:Object.entries(this.cookies).map(([b,S])=>`${b}=${S}`).join("; ")},x=await on(m,c,h,6e4),g=x.headers["set-cookie"];if(g)for(let b of g.split(",")){let S=b.match(/^([^=]+)=([^;]+)/);S&&(this.cookies[S[1].trim()]=S[2].trim())}let v;try{v=JSON.parse(x.data)}catch{throw new Error(l("api.upload_invalid_response",{data:x.data?.substring?.(0,400)}))}if(v.code!=="S_OK")throw new Error(l("api.upload_data_failed",{code:v.code}));let w=await this.client.postJson({func:"cim.file:moveToNetFolder",sid:this.sid,payload:{composeId:t,fileName:s,item:"fileName",attachmentId:d,uid:o}});if(w.code!=="S_OK")throw new Error(l("api.upload_move_failed",{code:w.code}));let y=w.var,k=y?.fileId,C=y?.uid;if(!k)throw new Error(l("api.upload_no_file_id"));return{fileId:k,fileUid:C||"",fileName:s}}async uploadFileWithFlow(e,o,t){let i=Ce.resolve(e),s=Ce.basename(i);if(!ce.existsSync(i))throw new Error(l("errors.file_not_found",{path:e}));let a=ce.statSync(i),r=hi.lookup(i)||"application/octet-stream",c=ce.readFileSync(i),u=await this.client.postJson({func:"cim.file:prepare",sid:this.sid,payload:{size:a.size,composeId:t,fileName:s,uid:o,contentType:r}});if(u.code!=="S_OK")throw new Error(l("api.upload_prepare_failed",{code:u.code}));let d=u.var?.attachmentId;if(!d)throw new Error(l("api.upload_no_attachment_id"));let m=`${this.session.baseUrl}${this.session.apiPath}?func=cim.file:directData&sid=${encodeURIComponent(this.sid)}&composeId=${encodeURIComponent(t)}&attachmentId=${d}&offset=0&uid=${encodeURIComponent(o)}`,h={"Content-Type":"application/octet-stream",Cookie:Object.entries(this.cookies).map(([b,S])=>`${b}=${S}`).join("; ")},x=await on(m,c,h,6e4),g=x.headers["set-cookie"];if(g)for(let b of g.split(",")){let S=b.match(/^([^=]+)=([^;]+)/);S&&(this.cookies[S[1].trim()]=S[2].trim())}let v;try{v=JSON.parse(x.data)}catch{throw new Error(l("api.upload_invalid_response",{data:x.data?.substring?.(0,400)}))}if(v.code!=="S_OK")throw new Error(l("api.upload_data_failed",{code:v.code}));let w=await this.client.postJson({func:"cim.file:moveToNetFolder",sid:this.sid,payload:{composeId:t,fileName:s,item:"fileName",attachmentId:d,uid:o}});if(w.code!=="S_OK")throw new Error(l("api.upload_move_failed",{code:w.code}));let y=w.var,k=y?.fileId,C=y?.uid;if(!k)throw new Error(l("api.upload_no_file_id"));return{fileId:k,fileUid:C||"",fileName:s}}async downloadFile(e,o,t,i){let s=`${this.session.baseUrl}/lunkr/f?func=cim.file:getFileData&mode=download&uid=${encodeURIComponent(o)}&mid=${encodeURIComponent(e)}&sid=${encodeURIComponent(this.sid)}&fallback=false`,a={Cookie:`Cim.sid=${this.sid}; Cim=${this.cookies.Cim||""}`},r=await hn(s,a);if(r.status!==200){let m=r.data.toString("utf-8").substring(0,500);throw new Error(l("api.download_http_failed",{status:r.status,body:m}))}if(r.data.length<1e3)try{let m=JSON.parse(r.data.toString("utf-8"));if(m.code&&m.code!=="S_OK")throw new Error(l("api.download_failed",{error:`${m.code} - ${m.msg||""}`}))}catch(m){if(!(m instanceof SyntaxError))throw m}if(!i)throw new Error(l("api.filename_required"));let c=li(i),u=t?Ce.resolve(t):Ce.join(Wc.tmpdir(),c),p=Ce.dirname(u);ce.existsSync(p)||ce.mkdirSync(p,{recursive:!0});let d=r.data;if(c.endsWith(".ilbc")&&!r.data.subarray(0,6).equals(Buffer.from("#!iLBC"))){let m=r.data.length%38===0?"20":"30",f=Buffer.from(`#!iLBC${m}
16
- `);d=Buffer.concat([f,r.data])}return ce.writeFileSync(u,d),{filePath:u,fileName:c,fileSize:d.length}}async convertAudio(e,o="wav"){let t=o.startsWith(".")?o:`.${o}`,i=e.replace(/\.[^.]+$/,t),{execFile:s}=await import("child_process"),{promisify:a}=await import("util"),r=a(s);try{await r("ffmpeg",["-y","-i",e,"-ar","16000","-ac","1",i],{timeout:3e4})}catch(c){throw new Error(l("api.audio_convert_failed",{error:c.message||String(c)}))}return{filePath:i,format:o}}async createGroup(e,o){let t=await this.searchGroups(e,1);if(t.length>0&&t[0].name===e)return{uid:t[0].uid,name:t[0].name||e};let i={true_name:e,group_type:"topic"};o&&(i.description=o);let s=await this.client.postJson({func:"cim.group:create",sid:this.sid,payload:i});if(s.code!=="S_OK")throw new Error(l("api.create_group_failed",{code:s.code,msg:s.msg||""}));let a=s.var;return{uid:String(a.uid||""),name:e}}async deleteGroup(e){let o=await this.client.postJson({func:"cim.group:discard",sid:this.sid,payload:{uid:e}});if(o.code!=="S_OK")throw new Error(l("api.delete_group_failed",{code:o.code,msg:o.msg||""}));return!0}createSocketClient(e){return sn.fromLunkrConfig(this.session.baseUrl,this.sid,this.session.cookie,{uid:this.session.selfUid,username:this.senderName,eventCallbacks:{connect:()=>e.onConnect?.(),disconnect:()=>e.onDisconnect?.(),ready:()=>e.onReady?.(),message:o=>e.onMessage?.(o),error:o=>{let t=o&&typeof o=="object"&&"message"in o?String(o.message):"Unknown error";e.onError?.(new Error(t))}}})}}});var K=se(()=>{re();oo();De();en()});var Qc={};us(Qc,{loginCommand:()=>Pn,loginCommandMeta:()=>Yc});async function cm(n){try{let e=new F(n.baseUrl,{apiPath:n.apiPath}),o={};for(let t of n.cookie.split(";")){let i=t.trim();if(i.includes("=")){let s=i.indexOf("="),a=i.substring(0,s).trim(),r=i.substring(s+1).trim();o[a]=r}}return e.setCookies(o),await e.checkSessionValid(n.sid)}catch{return!1}}async function xi(n){try{let e=new F(n.baseUrl,{apiPath:n.apiPath}),o={};for(let i of n.cookie.split(";")){let s=i.trim();if(s.includes("=")){let a=s.indexOf("="),r=s.substring(0,a).trim(),c=s.substring(a+1).trim();o[r]=c}}e.setCookies(o);let t=await e.postJson({func:"cim.common:getCimPrefAttr",sid:n.sid,payload:{return_field:"nickname,true_name,name"}});if(t.code==="S_OK"&&t.var){let i=t.var,s=i.nickname||i.true_name||i.name;return s?String(s).trim():null}}catch{}return null}async function Pn(n,e){let o=e.verbose??!1,t=e.debug??!1,i=e.force??!1,s=e.temp??!1;console.log(""),console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(` ${l("login.qrcode_login_intro")}`),console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(""),console.log(s?` ${l("messages.mode_temporary_desc")}`:` ${l("messages.mode_persistent_desc")}`),console.log("");let a=L();if(i)console.log(l("messages.force_relogin"));else{let g=a.accounts?.[0];if(g?.session?.sid){if(await cm(g.session)){let w=await xi(g.session);w&&(g.session.senderName=w,E(a)),console.log(l("messages.already_logged_in")),w&&console.log(`${l("labels.name")}: ${w}`),console.log(`UID: ${g.session.selfUid}`),console.log("");return}o&&(console.log(l("errors.session_expired_login")),console.log(""),console.log(l("status.login_hint")))}}let r=a.accounts?.[0];if(r?.apiToken&&!i){console.log(l("messages.authenticating_token"));let g=await Le(r.email||r.accountId,r.apiToken,a.device_uuid,{debug:t});if(g.success&&g.sid&&g.cookie){let v=g.selfUid||r.session?.selfUid;r.session={sid:g.sid,cookie:g.cookie,baseUrl:vo,apiPath:xn,selfUid:v};let w=await xi(r.session);w&&(r.session.senderName=w),E(a);let y=10;console.log(""),console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(` ${l("messages.login_successful_token")}`),console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(""),w&&console.log(` ${I(l("labels.name")+":",y)} ${w}`),console.log(` ${I(l("labels.email")+":",y)} ${g.email}`),console.log(` ${I(l("labels.bot")+":",y)} ${ae()}`),console.log(""),console.log(` ${I(l("labels.config")+":",y)} ${de()}`),console.log("");return}console.log(l("login.token_expired_need_rescan")),t&&console.log(l("login.token_login_error",{error:g.error||"Unknown"}))}let c=await si({device:{device_uuid:a.device_uuid,device_os:a.device_os,device_model:a.device_model,device_name:a.device_name},debug:t});c.success||(console.error(""),console.error(l("login.qrcode_login_failed",{error:c.error||"Unknown"})),process.exit(1)),(!c.apiToken||!c.email)&&(console.error(""),console.error(l("login.qrcode_login_no_token")),process.exit(1)),console.log(""),console.log(l("messages.authenticating_with_token"));let u=await Le(c.email,c.apiToken,c.deviceUuid||a.device_uuid,{debug:t});u.success||(console.error(""),console.error(l("login.token_login_failed",{error:u.error||"Unknown"})),process.exit(1)),(!u.sid||!u.cookie)&&(console.error(""),console.error(l("login.token_login_no_session")),process.exit(1));let p=u.selfUid||c.selfUid,d={sid:u.sid,cookie:u.cookie,baseUrl:vo,apiPath:xn,selfUid:p},m=await xi(d);m&&(d.senderName=m);let f={accountId:c.email,email:c.email,enabled:!0,session:d,apiToken:s?void 0:c.apiToken};a=L();let h=a.accounts?.findIndex(g=>g.accountId===c.email)??-1;if(h>=0&&a.accounts){let g=a.accounts[h];g.session=f.session,g.enabled=!0,f.apiToken!==void 0&&(g.apiToken=f.apiToken)}else a.accounts||(a.accounts=[]),a.accounts.push(f);E(a);let x=10;console.log(""),console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(` ${l("messages.login_successful_qrcode")}`),console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(""),m&&console.log(` ${I(l("labels.name")+":",x)} ${m}`),console.log(` ${I(l("labels.email")+":",x)} ${c.email}`),console.log(` ${I(l("labels.bot")+":",x)} ${ae()}`),console.log(` ${I("UID:",x)} ${p}`),console.log(s?` ${I(l("labels.mode")+":",x)} ${l("messages.mode_temporary")}`:` ${I(l("labels.mode")+":",x)} ${l("messages.mode_persistent")}`),console.log(""),console.log(` ${I(l("labels.config")+":",x)} ${de()}`),console.log("")}var Yc,zo=se(()=>{K();vn();Rn();U();Yc={name:"login",description:"Login to Lunkr using QR code",options:[{name:"verbose",alias:"v",description:"Verbose output",type:"boolean",required:!1},{name:"debug",alias:"d",description:"Debug output (show network requests)",type:"boolean",required:!1},{name:"force",alias:"f",description:"Force re-login even if session is valid",type:"boolean",required:!1},{name:"temp",alias:"t",description:"Temporary login (do not save api_token)",type:"boolean",required:!1}]}});fn();U();function hs(n){return{}}function xs(n){return{accountId:n.accountId}}function vs(n){return{}}import{Type as _}from"@sinclair/typebox";import{Value as Jm}from"@sinclair/typebox/value";var Ml=_.Object({name:_.String({minLength:1,description:"Discussion name is required"}),agentId:_.Optional(_.String()),creatorUid:_.String({minLength:1,description:"Creator UID is required"}),createdAt:_.Union([_.String(),_.Number()],{description:"Creation timestamp"})}),Bl=_.Union([_.Literal("open"),_.Literal("allowlist"),_.Literal("disabled")]),bs=_.Union([_.Literal("open"),_.Literal("allowlist"),_.Literal("disabled")]),Gl=_.Object({enabled:_.Optional(_.Boolean()),allowFrom:_.Optional(_.Array(_.String())),policy:_.Optional(bs),requireMention:_.Optional(_.Boolean())}),zl=_.Object({policy:_.Union([_.Literal("disabled"),_.Literal("mentionOnly"),_.Literal("open")])}),Zo=_.Object({enabled:_.Optional(_.Boolean({default:!0})),commandPrefix:_.Optional(_.String({minLength:1,default:"/"})),botDiscussions:_.Optional(_.Record(_.String(),Ml)),dmPolicy:_.Optional(Bl),allowFrom:_.Optional(_.Array(_.String())),groupPolicy:_.Optional(bs),groups:_.Optional(_.Array(_.String())),discussions:_.Optional(_.Record(_.String(),Gl)),groupTypeRules:_.Optional(_.Record(_.String(),zl))}),Kl=_.Object({email:_.String({minLength:1,description:"Email is required"}),password:_.String({minLength:1,description:"Password is required"}),deviceUuid:_.Optional(_.String()),deviceName:_.Optional(_.String())}),Hl=_.Object({sid:_.String(),selfUid:_.String(),cookie:_.String(),baseUrl:_.String(),apiPath:_.String()}),Vl=_.Object({accountId:_.String({minLength:1,description:"Account ID is required"}),name:_.Optional(_.String()),enabled:_.Optional(_.Boolean({default:!0})),credentials:Kl,config:Zo,session:_.Optional(Hl)}),Ym=_.Record(_.String(),Vl);var Se="default";re();var be="agent:";function Xl(n){let e=L(),o=e.accounts||[];if(n&&n.startsWith(be)){let i=n.slice(be.length),s=o.find(a=>a.email===i&&a.role==="agent");return s?{accountId:s.accountId,name:s.name,enabled:s.enabled,session:s.session,config:s.config,apiToken:s.apiToken,role:s.role,agentId:s.agentId}:null}if(!n||n===Se){let i=W(e);if(!i)return null;let s=o.find(a=>a.accountId===i.accountId||a.email===i.email);return{accountId:i.accountId,name:s?.name,enabled:i.enabled,session:i.session,config:s?.config,apiToken:i.apiToken,role:i.role,agentId:i.agentId}}let t=o.find(i=>i.accountId===n);return t?{accountId:t.accountId,name:t.name,enabled:t.enabled,session:t.session,config:t.config,apiToken:t.apiToken,role:t.role,agentId:t.agentId}:null}function Ps(n){return n.channels?.["lunkr-openclaw"]}var Zl={enabled:!0,commandPrefix:"/bot",botDiscussions:{},dmPolicy:"open",allowFrom:[],groupPolicy:"open",groups:[]};function Ls(n){switch(n){case"allow":case"any":case"pairing":return"open";case"deny":return"disabled";case"whitelist":return"allowlist";case"open":case"allowlist":case"disabled":return n;default:return"open"}}function Is(n){switch(n){case"allow":case"any":return"open";case"deny":return"disabled";case"whitelist":return"allowlist";case"open":case"allowlist":case"disabled":return n;default:return"open"}}function eu(n,e){let o={...Zl,...n};return e?{...o,...e,dmPolicy:Ls(e.dmPolicy??o.dmPolicy),groupPolicy:Is(e.groupPolicy??o.groupPolicy),botDiscussions:{...o.botDiscussions,...e.botDiscussions},discussions:{...o.discussions,...e.discussions},groupTypeRules:{...o.groupTypeRules,...e.groupTypeRules},allowFrom:e.allowFrom??o.allowFrom,groups:e.groups??o.groups}:{...o,dmPolicy:Ls(o.dmPolicy),groupPolicy:Is(o.groupPolicy)}}function me(n,e){let o=Ps(n),i=Xl(e??Se);if(!i?.session||o?.enabled===!1)return null;let s=o?.enabled??!0,a=eu(o,i.config),r=i.session;return{accountId:i.accountId,name:i.name??ae(),enabled:s,selfUid:i.session.selfUid,sid:i.session.sid,cookie:i.session.cookie,botName:ae(),commandPrefix:a.commandPrefix,botDiscussions:a.botDiscussions,senderName:r.senderName,config:a,lunkrConfig:i.session,hasApiToken:!!i.apiToken,role:i.role||"standard",agentId:i.agentId}}function $n(n,e){return{...n,sid:e.sid,cookie:e.cookie,selfUid:e.selfUid||n.selfUid,lunkrConfig:e}}var Us={listAccountIds:n=>{let e=[],o=L();W(o)?.session&&e.push(Se);let i=Fn(o);for(let s of i)s.session?.sid&&e.push(`${be}${s.email}`);return e},resolveAccount:(n,e)=>me(n,e),defaultAccountId:()=>Se,isConfigured:n=>n?!!((n.sid||n.hasApiToken)&&n.selfUid):!1,isEnabled:n=>n?n.enabled??!0:!1,describeAccount:n=>{if(!n)return{accountId:"default",configured:!1,enabled:!1};let e=!!((n.sid||n.hasApiToken)&&n.selfUid);return{accountId:n.accountId,name:n.name,enabled:n.enabled,configured:e}},setAccountEnabled:n=>{let{cfg:e,enabled:o}=n,t=Ps(e)??{};return{...e,channels:{...e.channels,lunkr:{...t,enabled:o}}}},unconfiguredReason:n=>n?n.sid?n.selfUid?"Account not configured":"Lunkr user ID not available. Please re-authenticate.":"Lunkr session not configured. Run: openclaw lunkr login":"Lunkr account not configured. Run: openclaw lunkr login"};function Ts(n){return n.replace(/^lunkr:/i,"")}function nu(n,e,o){let t=o.config.dmPolicy??"open",i=o.config.allowFrom??[];return{policy:t,allowFrom:i.map(Ts),policyPath:"channels.lunkr-openclaw.dmPolicy",allowFromPath:"channels.lunkr-openclaw.allowFrom",approveHint:"openclaw pairing approve lunkr <code>",normalizeEntry:Ts}}async function ou(n){let e=[],{account:o}=n;return o.config.groupPolicy==="allowlist"&&!o.config.groups?.length&&e.push('Group policy is set to "allowlist" but no groups are configured. Bot will not respond in any group.'),o.config.dmPolicy==="allowlist"&&!o.config.allowFrom?.length&&e.push('DM policy is set to "allowlist" but allowFrom is empty. Bot will not respond to any DM.'),e}var Os={resolveDmPolicy:n=>{let{cfg:e,accountId:o,account:t}=n;return nu(e,o??Se,t)},collectWarnings:n=>ou(n)};var yc=Jo(lt(),1);import*as xe from"fs";import*as Ze from"path";import*as bc from"os";tn();uo();vn();yo();var Zs={"cim.cal:createEvents":{func:"cim.cal:createEvents",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:createEventsForLunkr":{func:"cim.cal:createEventsForLunkr",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:deleteEvents":{func:"cim.cal:deleteEvents",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:deleteEventsForLunkr":{func:"cim.cal:deleteEventsForLunkr",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:deleteReminder":{func:"cim.cal:deleteReminder",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:getMeetingRooms":{func:"cim.cal:getMeetingRooms",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:getReminder":{func:"cim.cal:getReminder",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:getReminderWithAutoCheck":{func:"cim.cal:getReminderWithAutoCheck",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:setReminder":{func:"cim.cal:setReminder",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:setReminderForLunkr":{func:"cim.cal:setReminderForLunkr",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:updateEvents":{func:"cim.cal:updateEvents",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:updateEventsForLunkr":{func:"cim.cal:updateEventsForLunkr",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:api":{func:"cim.common:api",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:autoKeepSession":{func:"cim.common:autoKeepSession",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:checkModuleVersion":{func:"cim.common:checkModuleVersion",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:checkVersion":{func:"cim.common:checkVersion",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:clickLog":{func:"cim.common:clickLog",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:customOpLog":{func:"cim.common:customOpLog",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:delayClickLog":{func:"cim.common:delayClickLog",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:feedback":{func:"cim.common:feedback",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:flashMailLog":{func:"cim.common:flashMailLog",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getAdminFunctionSetting":{func:"cim.common:getAdminFunctionSetting",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getAttrs":{func:"cim.common:getAttrs",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getAvatar":{func:"cim.common:getAvatar",path:"/lunkr/f",requiresFunc:!0,defaultUseGet:!0},"cim.common:getBigAvatar":{func:"cim.common:getBigAvatar",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getCimPrefAttr":{func:"cim.common:getCimPrefAttr",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getConfig":{func:"cim.common:getConfig",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getCustomDomain":{func:"cim.common:getCustomDomain",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getEnfDetail":{func:"cim.common:getEnfDetail",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getInitConfig":{func:"cim.common:getInitConfig",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getLastLoginStatus":{func:"cim.common:getLastLoginStatus",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getMaterial":{func:"cim.common:getMaterial",path:"/lunkr/f",requiresFunc:!0,defaultUseGet:!0},"cim.common:getNSISDownloadURL":{func:"cim.common:getNSISDownloadURL",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getOrgInfo":{func:"cim.common:getOrgInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getRemindList":{func:"cim.common:getRemindList",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getRevision":{func:"cim.common:getRevision",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getSysUserInfo":{func:"cim.common:getSysUserInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getUserType":{func:"cim.common:getUserType",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getValueByKey":{func:"cim.common:getValueByKey",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getWebSocketURL":{func:"cim.common:getWebSocketURL",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:iosHotfix":{func:"cim.common:iosHotfix",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:listAuthDevice":{func:"cim.common:listAuthDevice",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:listFlagUser":{func:"cim.common:listFlagUser",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:logCollapse":{func:"cim.common:logCollapse",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:logRecord":{func:"cim.common:logRecord",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:onlineStatus":{func:"cim.common:onlineStatus",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:resetTopicAvatar":{func:"cim.common:resetTopicAvatar",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:searchFlagUser":{func:"cim.common:searchFlagUser",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:sendNetDiskOperateNotice":{func:"cim.common:sendNetDiskOperateNotice",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:sendShake":{func:"cim.common:sendShake",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:setApplePushSwitch":{func:"cim.common:setApplePushSwitch",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:setAvatar":{func:"cim.common:setAvatar",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:setCimPrefAttr":{func:"cim.common:setCimPrefAttr",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:setFlag":{func:"cim.common:setFlag",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:setMiscFlag":{func:"cim.common:setMiscFlag",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:setRevision":{func:"cim.common:setRevision",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:sioSubscribe":{func:"cim.common:sioSubscribe",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:transEmail":{func:"cim.common:transEmail",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:verify":{func:"cim.common:verify",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.company:getCompanyInfoById":{func:"cim.company:getCompanyInfoById",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.company:getSensitiveWord":{func:"cim.company:getSensitiveWord",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.company:listCompanyInfo":{func:"cim.company:listCompanyInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.container:searchContacts":{func:"cim.container:searchContacts",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.extSys:opRedpacket":{func:"cim.extSys:opRedpacket",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.extSys:push":{func:"cim.extSys:push",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.extSys:pushRegister":{func:"cim.extSys:pushRegister",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:addCollect":{func:"cim.file:addCollect",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:cancelCollect":{func:"cim.file:cancelCollect",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:directData":{func:"cim.file:directData",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:getFileData":{func:"cim.file:getFileData",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:getSearchResult":{func:"cim.file:getSearchResult",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:getThumbnail":{func:"cim.file:getThumbnail",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:listCollect":{func:"cim.file:listCollect",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:moveToNetFolder":{func:"cim.file:moveToNetFolder",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:prepare":{func:"cim.file:prepare",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:search":{func:"cim.file:search",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:searchCollect":{func:"cim.file:searchCollect",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:uploadPost":{func:"cim.file:uploadPost",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:uploadSnippet":{func:"cim.file:uploadSnippet",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:uploadVoice":{func:"cim.file:uploadVoice",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:viewFile":{func:"cim.file:viewFile",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:attendance":{func:"cim.group:attendance",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:create":{func:"cim.group:create",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:delete":{func:"cim.group:delete",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:discard":{func:"cim.group:discard",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:getInfo":{func:"cim.group:getInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:getMembersInfo":{func:"cim.group:getMembersInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:getRelate":{func:"cim.group:getRelate",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:invite":{func:"cim.group:invite",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:listVipUserTopic":{func:"cim.group:listVipUserTopic",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:notifyFlag":{func:"cim.group:notifyFlag",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:search":{func:"cim.group:search",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:transfer":{func:"cim.group:transfer",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:updateDescription":{func:"cim.group:updateDescription",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:updateName":{func:"cim.group:updateName",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.link:generate":{func:"cim.link:generate",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.link:getInfo":{func:"cim.link:getInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.link:prolong":{func:"cim.link:prolong",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.link:sendInviteMail":{func:"cim.link:sendInviteMail",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.link:shorten":{func:"cim.link:shorten",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:compose":{func:"cim.mail:compose",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:getPushFolder":{func:"cim.mail:getPushFolder",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:getShareNF":{func:"cim.mail:getShareNF",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:readMail":{func:"cim.mail:readMail",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:readShare":{func:"cim.mail:readShare",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:refreshToken":{func:"cim.mail:refreshToken",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:remoteCompose":{func:"cim.mail:remoteCompose",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:remoteRequest":{func:"cim.mail:remoteRequest",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:searchMessages":{func:"cim.mail:searchMessages",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:setAllRead":{func:"cim.mail:setAllRead",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:setPushFolder":{func:"cim.mail:setPushFolder",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:share":{func:"cim.mail:share",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:ssoLunkr":{func:"cim.mail:ssoLunkr",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:uploadToPersonalNF":{func:"cim.mail:uploadToPersonalNF",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:batchReply":{func:"cim.msg:batchReply",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:broadcast":{func:"cim.msg:broadcast",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:clearUnread":{func:"cim.msg:clearUnread",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:collect":{func:"cim.msg:collect",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:deleteUploadFile":{func:"cim.msg:deleteUploadFile",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:getInfo":{func:"cim.msg:getInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:getLastMsgByType":{func:"cim.msg:getLastMsgByType",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:getLastMsgByUID":{func:"cim.msg:getLastMsgByUID",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:getSearchResult":{func:"cim.msg:getSearchResult",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:getShare":{func:"cim.msg:getShare",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:list":{func:"cim.msg:list",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:operate":{func:"cim.msg:operate",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:p2p":{func:"cim.msg:p2p",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:reply":{func:"cim.msg:reply",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:search":{func:"cim.msg:search",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:searchByGroup":{func:"cim.msg:searchByGroup",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:setVip":{func:"cim.msg:setVip",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:share":{func:"cim.msg:share",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:stats":{func:"cim.msg:stats",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:updateLastMsg":{func:"cim.msg:updateLastMsg",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:updateRcptMsg":{func:"cim.msg:updateRcptMsg",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.oabEx:getAttrs":{func:"cim.oabEx:getAttrs",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.oabEx:getUserInfo":{func:"cim.oabEx:getUserInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.oabEx:setAttrs":{func:"cim.oabEx:setAttrs",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:deleteLotterySetting":{func:"cim.operation:deleteLotterySetting",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:deleteOperateActivityById":{func:"cim.operation:deleteOperateActivityById",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:exportUserLottery":{func:"cim.operation:exportUserLottery",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:getCommentByCode":{func:"cim.operation:getCommentByCode",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:getLotteryResultByCode":{func:"cim.operation:getLotteryResultByCode",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:getOperateActivityById":{func:"cim.operation:getOperateActivityById",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:getPrizeInfoByCode":{func:"cim.operation:getPrizeInfoByCode",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:listActiveOperateActivity":{func:"cim.operation:listActiveOperateActivity",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:listLotterySetting":{func:"cim.operation:listLotterySetting",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:saveComment":{func:"cim.operation:saveComment",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:saveLotterySetting":{func:"cim.operation:saveLotterySetting",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:saveOperateActivity":{func:"cim.operation:saveOperateActivity",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:saveUserCommentForPrize":{func:"cim.operation:saveUserCommentForPrize",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:sendGreetingCard":{func:"cim.operation:sendGreetingCard",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:startLottery":{func:"cim.operation:startLottery",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:updateOperateActivity":{func:"cim.operation:updateOperateActivity",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:addContact":{func:"cim.pab:addContact",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:addGroup":{func:"cim.pab:addGroup",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:addToBlacklist":{func:"cim.pab:addToBlacklist",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:deleteGroup":{func:"cim.pab:deleteGroup",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:getAllContacts":{func:"cim.pab:getAllContacts",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:getBlacklist":{func:"cim.pab:getBlacklist",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:getCombinedContacts":{func:"cim.pab:getCombinedContacts",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:getRecentContacts":{func:"cim.pab:getRecentContacts",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:getWholeContacts":{func:"cim.pab:getWholeContacts",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:removeFromBlacklist":{func:"cim.pab:removeFromBlacklist",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:searchContact":{func:"cim.pab:searchContact",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:updateContact":{func:"cim.pab:updateContact",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.qrcode:generate":{func:"cim.qrcode:generate",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.qrcode:qrcodeInfo":{func:"cim.qrcode:qrcodeInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.qrcode:register":{func:"cim.qrcode:register",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.remind:get":{func:"cim.remind:get",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.remind:getMobile":{func:"cim.remind:getMobile",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.remind:set":{func:"cim.remind:set",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.remind:setMobile":{func:"cim.remind:setMobile",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.revision:getRevision":{func:"cim.revision:getRevision",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.state:getNotify":{func:"cim.state:getNotify",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.state:query":{func:"cim.state:query",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.state:queryHasLogin":{func:"cim.state:queryHasLogin",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.state:queryUserState":{func:"cim.state:queryUserState",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.state:set":{func:"cim.state:set",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.state:setNotify":{func:"cim.state:setNotify",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.third:checkToken":{func:"cim.third:checkToken",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.third:genLinkNonce":{func:"cim.third:genLinkNonce",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.third:listApp":{func:"cim.third:listApp",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.thread:getThreadInfo":{func:"cim.thread:getThreadInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.thread:listBulletin":{func:"cim.thread:listBulletin",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.thread:listRevision":{func:"cim.thread:listRevision",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.thread:listThreadNew":{func:"cim.thread:listThreadNew",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.thread:setTop":{func:"cim.thread:setTop",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:changePassword":{func:"cim.user:changePassword",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:checkVersionAndLogin":{func:"cim.user:checkVersionAndLogin",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:genTempSession":{func:"cim.user:genTempSession",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:getCard":{func:"cim.user:getCard",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:getEmojiList":{func:"cim.user:getEmojiList",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:getLunkrMailData":{func:"cim.user:getLunkrMailData",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:getRecentUnread":{func:"cim.user:getRecentUnread",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:getTempSession":{func:"cim.user:getTempSession",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:getTempShareSession":{func:"cim.user:getTempShareSession",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:kickOffLine":{func:"cim.user:kickOffLine",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:kickOnlineDevice":{func:"cim.user:kickOnlineDevice",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:kickOnlineUserForAdmin":{func:"cim.user:kickOnlineUserForAdmin",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:listKickOffLineLog":{func:"cim.user:listKickOffLineLog",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:listLoginHistory":{func:"cim.user:listLoginHistory",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:logout":{func:"cim.user:logout",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:queryOnlineDevice":{func:"cim.user:queryOnlineDevice",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:removeKickOffLine":{func:"cim.user:removeKickOffLine",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:saveCard":{func:"cim.user:saveCard",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:saveEmoji":{func:"cim.user:saveEmoji",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:shareCard":{func:"cim.user:shareCard",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:updateName":{func:"cim.user:updateName",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:updateOrgUserLastModified":{func:"cim.user:updateOrgUserLastModified",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:updateTempSession":{func:"cim.user:updateTempSession",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"nfEx:getFileData":{func:"nfEx:getFileData",path:"/crux/adm_api/filePreview",requiresFunc:!0,defaultUseGet:!0},"nfEx:getShareFile":{func:"nfEx:getShareFile",path:"/lunkr/f",requiresFunc:!0,defaultUseGet:!0},"oab:autoMatch":{func:"oab:autoMatch",path:"/coremail/s/json",requiresFunc:!0,defaultUseGet:!1},"oab:get":{func:"oab:get",path:"/coremail/s/json",requiresFunc:!0,defaultUseGet:!1},"oab:getDirectories":{func:"oab:getDirectories",path:"/coremail/s/json",requiresFunc:!0,defaultUseGet:!1},"oab:listEx":{func:"oab:listEx",path:"/coremail/s/json",requiresFunc:!0,defaultUseGet:!1},"oab:searchEx":{func:"oab:searchEx",path:"/coremail/s/json",requiresFunc:!0,defaultUseGet:!1},"pab:createContact":{func:"pab:createContact",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"pab:deleteContact":{func:"pab:deleteContact",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"pab:getAllContactsByType":{func:"pab:getAllContactsByType",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"pab:getContactByEmail":{func:"pab:getContactByEmail",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"pab:getContactsByGroup":{func:"pab:getContactsByGroup",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"user:config":{func:"user:config",path:"/lunkr/common/config",requiresFunc:!1,defaultUseGet:!0},"user:init":{func:"user:init",path:"/lunkr/init",requiresFunc:!1,defaultUseGet:!0}},fu=Object.keys(Zs);tn();Rn();De();U();oo();var gc=1e3;async function hc(n,e){try{let o=await n.postJson({func:"cim.common:getCimPrefAttr",sid:e,payload:{return_field:"nickname,true_name,name"}});if(o.code==="S_OK"&&o.var){let t=o.var,i=t.nickname||t.true_name||t.name;return i?String(i).trim():null}}catch{}return null}async function xc(n,e){let o=me(n,e);if(!o)throw new Error(l("errors.account_not_configured"));let t=new F(o.lunkrConfig.baseUrl,{apiPath:o.lunkrConfig.apiPath}),i={"Cim.sid":o.sid};for(let s of o.cookie.split(";")){let a=s.trim();if(a.includes("=")){let[r,c]=a.split("=",2);i[r.trim()]=c.trim()}}return t.setCookies(i),{client:t,account:o}}async function Dd(n,e){let{to:o,content:t,sid:i,accountId:s,lunkrConfig:a}=e,r=await n.postJson({func:"cim.msg:reply",sid:i,payload:{uid:o,content:t,type:"text"}});if(r.code!=="S_OK"&&Ln(String(r.code))){let u=await he(s);if(u.success&&u.session){let p=new F(a.baseUrl,{apiPath:a.apiPath}),d={"Cim.sid":u.session.sid};for(let f of u.session.cookie.split(";")){let h=f.trim();if(h.includes("=")){let[x,g]=h.split("=",2);d[x.trim()]=g.trim()}}p.setCookies(d);let m=await p.postJson({func:"cim.msg:reply",sid:u.session.sid,payload:{uid:o,content:t,type:"text"}});if(m.code==="S_OK")return{msgId:m.var?.msgId??`msg-${Date.now()}`};throw new Error(l("api.send_failed",{code:String(m.code)}))}else console.error(`[${s}] Session refresh failed: ${u.error}. Please run: lunkr login`)}if(r.code!=="S_OK")throw new Error(l("api.send_failed",{code:String(r.code)}));return{msgId:r.var?.msgId??`msg-${Date.now()}`}}async function Nd(n,e){let{to:o,content:t,sid:i,accountId:s,lunkrConfig:a}=e,r=await n.postJson({func:"cim.msg:reply",sid:i,payload:{uid:o,content:t,type:"post"}});if(r.code!=="S_OK"&&Ln(String(r.code))){let u=await he(s);if(u.success&&u.session){let p=new F(a.baseUrl,{apiPath:a.apiPath}),d={"Cim.sid":u.session.sid};for(let f of u.session.cookie.split(";")){let h=f.trim();if(h.includes("=")){let[x,g]=h.split("=",2);d[x.trim()]=g.trim()}}p.setCookies(d);let m=await p.postJson({func:"cim.msg:reply",sid:u.session.sid,payload:{uid:o,content:t,type:"post"}});if(m.code==="S_OK")return{msgId:m.var?.msgId??`post-${Date.now()}`};throw new Error(l("api.send_post_failed",{code:String(m.code)}))}else console.error(`[${s}] Session refresh failed: ${u.error}. Please run: lunkr login`)}if(r.code!=="S_OK")throw new Error(l("api.send_post_failed",{code:String(r.code)}));return{msgId:r.var?.msgId??`post-${Date.now()}`}}function vc(n){let e=n.replace(/^lunkr:/i,"");return e.startsWith("discussion:")?{chatId:e.replace("discussion:",""),chatType:"group"}:e.startsWith("channel:")?{chatId:e.replace("channel:",""),chatType:"channel"}:{chatId:e,chatType:"p2p"}}async function Md(n){if(n.startsWith("http://")||n.startsWith("https://")){let o=bc.tmpdir(),t=`lunkr-media-${Date.now()}-${Ze.basename(new URL(n).pathname)||"file"}`,i=Ze.join(o,t),s=await hn(n,{},6e4);return xe.writeFileSync(i,s.data),{filePath:i,cleanup:()=>{try{xe.existsSync(i)&&xe.unlinkSync(i)}catch{}}}}let e=Ze.resolve(n);if(!xe.existsSync(e))throw new Error(l("errors.file_not_found",{path:n}));return{filePath:e,cleanup:()=>{}}}async function Bd(n,e){let{filePath:o,sid:t,uploadUid:i,cookies:s,baseUrl:a,apiPath:r}=e,c=Ze.resolve(o),u=Ze.basename(c);if(!xe.existsSync(c))throw new Error(l("errors.file_not_found",{path:o}));let p=xe.statSync(c),d=yc.lookup(c)||"application/octet-stream",m=xe.readFileSync(c),f=`c:nf:cim${Math.floor(Math.random()*9999)+1}`,h=await n.postJson({func:"cim.file:prepare",sid:t,payload:{size:p.size,composeId:f,fileName:u,uid:i,contentType:d}});if(h.code!=="S_OK")throw new Error(l("api.upload_prepare_failed",{code:String(h.code)}));let g=h.var?.attachmentId;if(!g)throw new Error(l("api.upload_no_attachment_id"));let v=`${a}${r}?func=cim.file:directData&sid=${encodeURIComponent(t)}&composeId=${encodeURIComponent(f)}&attachmentId=${g}&offset=0&uid=${encodeURIComponent(i)}`,y={"Content-Type":"application/octet-stream",Cookie:Object.entries(s).map(([q,B])=>`${q}=${B}`).join("; ")},k=await on(v,m,y,6e4),C;try{C=JSON.parse(k.data)}catch{throw new Error(l("api.upload_invalid_response",{data:k.data?.substring?.(0,200)}))}if(C.code!=="S_OK")throw new Error(l("api.upload_data_failed",{code:String(C.code)}));let b=await n.postJson({func:"cim.file:moveToNetFolder",sid:t,payload:{composeId:f,fileName:u,item:"fileName",attachmentId:g,uid:i}});if(b.code!=="S_OK")throw new Error(l("api.upload_move_failed",{code:String(b.code)}));let S=b.var,T=S?.fileId,R=S?.uid;if(!T)throw new Error(l("api.upload_no_file_id"));return{fileId:T,fileUid:R||""}}var kc={deliveryMode:"direct",textChunkLimit:gc,sendText:async n=>{let{cfg:e,to:o,text:t,replyToId:i,accountId:s}=n,{client:a,account:r}=await xc(e,s),{chatId:c,chatType:u}=vc(o),p=r.botName??"Bot",d=r.senderName;d||(d=await hc(a,r.sid)),d||(d=r.selfUid?.includes("@")?r.selfUid.split("@")[0]:"User");let m=r.role==="agent",f=qe(t,d,p,m),h;return f.length>gc?h=await Nd(a,{to:c,content:f,sid:r.sid,accountId:r.accountId,lunkrConfig:r.lunkrConfig}):h=await Dd(a,{to:c,content:f,sid:r.sid,accountId:r.accountId,lunkrConfig:r.lunkrConfig}),{ok:!0,channel:"lunkr-openclaw",messageId:h.msgId}},sendMedia:async n=>{let{cfg:e,to:o,text:t,mediaUrl:i,accountId:s}=n;if(!i)throw new Error(l("errors.media_url_required"));let{client:a,account:r}=await xc(e,s),{chatId:c,chatType:u}=vc(o),p=r.botName??"Bot",d=r.senderName;d||(d=await hc(a,r.sid)),d||(d=r.selfUid?.includes("@")?r.selfUid.split("@")[0]:"User");let m=r.role==="agent",f=qe(t||"",d,p,m),h={"Cim.sid":r.sid};for(let k of r.cookie.split(";")){let C=k.trim();if(C.includes("=")){let[b,S]=C.split("=",2);h[b.trim()]=S.trim()}}let x=a,g=r.sid;if((await a.postJson({func:"cim.common:getOrgInfo",sid:r.sid})).code!=="S_OK"){let k=await he(r.accountId);if(!k.success||!k.session)throw new Error(l("errors.session_expired"));g=k.session.sid,x=new F(r.lunkrConfig.baseUrl,{apiPath:r.lunkrConfig.apiPath}),h={"Cim.sid":g};for(let C of k.session.cookie.split(";")){let b=C.trim();if(b.includes("=")){let[S,T]=b.split("=",2);h[S.trim()]=T.trim()}}x.setCookies(h)}let w,y;try{let k=await Md(i);w=k.filePath,y=k.cleanup;let C=u==="p2p"?r.selfUid:c,{fileId:b,fileUid:S}=await Bd(x,{filePath:w,sid:g,uploadUid:C,cookies:h,baseUrl:r.lunkrConfig.baseUrl,apiPath:r.lunkrConfig.apiPath}),T=await x.postJson({func:"cim.msg:reply",sid:g,payload:{uid:c,content:f,type:"text",attachments:[{fileId:b,uid:S}]}});if(T.code!=="S_OK")throw new Error(l("api.send_media_failed",{code:String(T.code)}));return{ok:!0,channel:"lunkr-openclaw",messageId:T.var?.msgId??`media-${Date.now()}`}}finally{y&&y()}}};yo();function _c(n,e){let o=n.chatType==="group"?n.chatId:null;return o&&(e.botDiscussions||{})[o]||null}function ui(n,e){return _c(n,e)!==null}function Gd(n,e){return n.trim().toLowerCase().startsWith(e.toLowerCase())}function wc(n,e){let o=n.fromUid===e.selfUid,t=o&&/^\[@!.+?\]/.test(n.content),i=o&&!t;if(t)return{isBotMention:!1,isFromBot:!0,isFromSelf:!1};let s=_c(n,e);return s?{isBotMention:!0,isFromBot:!1,isFromSelf:i,agentId:s.agentId}:o&&Gd(n.content,e.commandPrefix)?{isBotMention:!0,isFromBot:!1,isFromSelf:!0}:{isBotMention:!1,isFromBot:!1,isFromSelf:i}}function Cc(n,e){let o=n.fromUid===e.selfUid;return o&&/^\[@!.+?\]/.test(n.content)?{isBotMention:!1,isFromBot:!0,isFromSelf:!1}:o?{isBotMention:!1,isFromBot:!1,isFromSelf:!0}:n.chatType==="p2p"?{isBotMention:!0,isFromBot:!1,isFromSelf:!1,agentId:e.agentId,workspaceKey:`${e.selfUid}:${n.fromUid}`}:{isBotMention:!0,isFromBot:!1,isFromSelf:!1,agentId:e.agentId,workspaceKey:`${e.selfUid}:${n.chatId}`}}function zd(n,e){let o=n.trim();return o.toLowerCase().startsWith(e.toLowerCase())?o.slice(e.length).trim():n}function Sc(n,e){let o=e.role||"standard",t;if(o==="agent")t=Cc(n,e);else if(o==="standard+agent"){let r=Cc(n,e),c=wc(n,e);r.isBotMention?t=r:(c.isBotMention,t=c)}else t=wc(n,e);let s=ui(n,e)?n.content:zd(n.content,e.commandPrefix),a=n.chatType==="p2p"?"direct":n.chatType;return{externalId:n.msgId,channel:"lunkr-openclaw",chatType:a,peerId:n.chatId,senderId:n.fromUid,text:s,timestamp:n.timestamp,replyTo:n.threadId,mentions:n.mentionedUids,isBotMention:t.isBotMention,isFromBot:t.isFromBot,isFromSelf:t.isFromSelf,agentId:t.agentId,workspaceKey:t.workspaceKey,contentType:n.contentType,attachments:n.attachments}}function Kd(n){let e=n.indexOf("(");return e>0?n.substring(0,e):n}function No(n,e){if(!e||e.length===0)return!1;let o=n.replace(/^lunkr:/i,"");return e.some(t=>Kd(t).replace(/^lunkr:/i,"")===o)}function Hd(n){let e=n.match(/(#[A-Z])$/);return e?e[1]:null}function Ac(n,e,o){let t=e.config;if(n.chatType!=="direct"){let c={chatType:"group",chatId:n.peerId};if(ui(c,e))return{allowed:!0,reason:"bot discussion"}}if(n.chatType==="direct"){let c=t.dmPolicy||"open";return c==="disabled"?{allowed:!1,reason:"DM blocked: policy is disabled"}:c==="allowlist"?No(n.senderId,t.allowFrom)?{allowed:!0,reason:"sender in DM allowlist"}:{allowed:!1,reason:`DM blocked: sender ${n.senderId} not in allowFrom`}:{allowed:!0,reason:"DM policy is open"}}let i=n.peerId,s=t.discussions?.[i];if(s?.enabled===!1)return{allowed:!1,reason:`group blocked: discussion ${i} is disabled`};if(!(s&&(s.policy!==void 0||s.allowFrom!==void 0||s.requireMention!==void 0))){let c=Hd(i);if(c){let u=t.groupTypeRules?.[c];if(u){if(u.policy==="disabled")return{allowed:!1,reason:`group blocked: type rule ${c} is disabled`};if(u.policy==="mentionOnly"&&!(n.mentions?.includes(e.selfUid)||n.mentions?.includes("all")))return{allowed:!1,reason:`group blocked: type rule ${c} requires mention`}}}}if(s?.requireMention===!0&&!(n.mentions?.includes(e.selfUid)||n.mentions?.includes("all")))return{allowed:!1,reason:`group blocked: discussion ${i} requires mention`};let r=s?.policy||t.groupPolicy||"open";if(r==="disabled")return{allowed:!1,reason:"group blocked: policy is disabled"};if(r==="allowlist"){let c=No(i,t.groups);return s?.allowFrom&&s.allowFrom.length>0?No(n.senderId,s.allowFrom)?{allowed:!0,reason:"sender in discussion allowFrom"}:{allowed:!1,reason:`group blocked: sender ${n.senderId} not in discussion allowFrom for ${i}`}:c?{allowed:!0,reason:"group in allowlist"}:{allowed:!1,reason:`group blocked: ${i} not in groups allowlist`}}return s?.allowFrom&&s.allowFrom.length>0&&!No(n.senderId,s.allowFrom)?{allowed:!1,reason:`group blocked: sender ${n.senderId} not in discussion allowFrom for ${i}`}:{allowed:!0,reason:"group policy is open"}}De();U();oo();mn();var Pe=new Map,to=new Map,$c=5e3;function Jd(n){let e=Date.now(),o=to.get(n);if(o&&e-o<$c)return!0;if(to.set(n,e),to.size>1e3)for(let[t,i]of to)e-i>$c*2&&to.delete(t);return!1}function Yd(n,e){let o=e.role||"standard";return o==="agent"||o==="standard+agent"?n.chatType==="direct"?!0:n.mentions?.includes(e.selfUid)||n.mentions?.includes("all")||!1:n.isFromSelf}function Qd(n){let o=n.replace(/^(@\S+\s+)*/g,"").trim().toLowerCase();return o==="/help"||o.startsWith("/help ")?"/help":o==="/new"||o.startsWith("/new ")?"/new":null}var qc=1e3;async function Dc(n,e,o){let{to:t,text:i,chatType:s}=e;o?.debug?.(`[sendLunkrReply] to=${t}, chatType=${s}, textLen=${i.length}`);let a=n.botName??"Bot",r=n.senderName;r||(r=n.selfUid?.includes("@")?n.selfUid.split("@")[0]:"User");let c=e.skipPrefix??n.role==="agent",u=qe(i,r,a,c),p=n.sid,d=n.cookie,m=n;if(p){let f=new F(n.lunkrConfig.baseUrl,{apiPath:n.lunkrConfig.apiPath}),h={"Cim.sid":p};for(let g of d.split(";")){let v=g.trim();if(v.includes("=")){let[w,y]=v.split("=",2);h[w.trim()]=y.trim()}}f.setCookies(h);let x=await f.postJson({func:"cim.msg:reply",sid:p,payload:{uid:t,content:u,type:u.length>qc?"post":"text"}});if(o?.debug?.(`[sendLunkrReply] Response: code=${x.code}`),x.code==="S_OK"){let g=x.var?.msgId;return o?.info(`[sendLunkrReply] Message sent successfully${g?`: msgId=${g}`:""}`),{msgId:g??`msg-${Date.now()}`,account:m}}if(Ln(String(x.code)))o?.info(`[${n.accountId}] Session expired, clearing sid...`),p="",d="";else throw new Error(l("api.send_reply_failed",{code:String(x.code),msg:String(x.msg||"Unknown")}))}if(!p){o?.info(`[${n.accountId}] No valid session, attempting refresh with apiToken...`);let f=await he(n.accountId);if(f.success&&f.session){o?.info(`[${n.accountId}] Session refreshed, sending message...`),p=f.session.sid,d=f.session.cookie;let h=new F(n.lunkrConfig.baseUrl,{apiPath:n.lunkrConfig.apiPath}),x={"Cim.sid":p};for(let v of d.split(";")){let w=v.trim();if(w.includes("=")){let[y,k]=w.split("=",2);x[y.trim()]=k.trim()}}h.setCookies(x);let g=await h.postJson({func:"cim.msg:reply",sid:p,payload:{uid:t,content:u,type:u.length>qc?"post":"text"}});if(g.code==="S_OK"){let v=$n(n,f.session),w=g.var?.msgId;return o?.info(`[sendLunkrReply] Message sent successfully after refresh: msgId=${w}`),{msgId:w??`msg-${Date.now()}`,account:v}}throw o?.warn?.(`[${n.accountId}] Send failed after refresh: ${g.code}. Will retry later.`),new Error(l("api.send_reply_failed",{code:String(g.code),msg:String(g.msg||"Unknown")}))}throw o?.warn?.(`[${n.accountId}] Session refresh failed: ${f.error}. Will retry later.`),new Error(l("api.no_session"))}throw new Error(l("api.send_reply_failed",{code:"UNKNOWN",msg:"Unexpected state"}))}function Bo(n,e){let{log:o}=e;return sn.fromLunkrConfig(n.lunkrConfig.baseUrl,n.sid,n.cookie,{uid:n.selfUid,username:n.botName,autoReconnect:e.autoReconnect,eventCallbacks:{message:i=>{try{let s=Xd(i,o);if(s){s.attachments&&s.attachments.length>0&&(Tc(s.msgId,s.timestamp,s.attachments.map(r=>({fileId:r.fileId,uid:r.uid,title:r.title,contentType:r.contentType,fileSize:r.fileSize,type:r.type,inline:r.inline}))),o?.debug?.(`[gateway] Cached ${s.attachments.length} attachments for message ${s.msgId}`));let a=Sc(s,n);e.onMessage(a)}}catch(s){e.onError(s instanceof Error?s:new Error(String(s)))}},reaction:i=>{if(e.onReaction&&i&&typeof i=="object"){let s=i;e.onReaction({msgId:String(s.msgId??""),userId:String(s.fromUid??""),emoji:String(s.emoji??"")})}},disconnect:()=>{e.onDisconnect()},error:i=>{let s=i&&typeof i=="object"&&"message"in i?String(i.message):"Unknown socket error";e.onError(new Error(s))}}})}function Xd(n,e){if(!n||typeof n!="object")return null;let o=n,t=o.topic||"",i=o.payload||"",s;try{s=JSON.parse(i)}catch{return null}if(!s.mid&&!s.subject)return null;let a=Object.keys(s),r=s.attachments;e?.debug?.(`[parseSocketMessage] MSG keys=[${a.join(", ")}], attachments=${JSON.stringify(r)?.substring(0,200)}`);let c=String(s.mid||""),u=s.from||{},p=s.to||{},d=String(u.uid||""),m=String(u.true_name||u.email||""),f=String(s.subject||"");try{f=decodeURIComponent(f.replace(/\+/g," "))}catch{}let h=String(s.type||s.group_type||"p2p"),x=String(s.uid||p.uid||""),g;x.endsWith("#U")?g="p2p":x.endsWith("#T")?g="group":g=h==="p2p"?"p2p":h==="topic"||h==="group"?"group":"channel";let v=s.attachments||[],w=v.map(R=>{let q=String(R.uid||"");return{fileId:String(R.fileId||R.file_id||""),uid:q,title:String(R.title||""),fileSize:Number(R.file_size||R.fileSize||0),type:Number(R.t||R.type||0),ctype:R.ctype?String(R.ctype):void 0,inline:!!R.inline,duration:R.duration?Number(R.duration):void 0}});if(w.length===0){let R=Object.keys(s),q=R.some(O=>O.toLowerCase().includes("file")||O.toLowerCase().includes("att")||O.toLowerCase().includes("attach")||O.toLowerCase().includes("media")||O.toLowerCase().includes("image")||O.toLowerCase().includes("audio")),B=String(s.type||""),N=["file","image","audio","video","attachment"].some(O=>B.toLowerCase().includes(O));if(q||N){e?.info(`[parseSocketMessage] \u26A0\uFE0F No attachments parsed but message has file-related fields. type="${B}", keys=${R.join(", ")}`),e?.debug?.("[parseSocketMessage] No attachments found, but message might have file content"),e?.debug?.(`[parseSocketMessage] msg.type="${B}", msg keys: ${R.join(", ")}`);for(let O of R){let V=O.toLowerCase();if(V.includes("file")||V.includes("att")||V.includes("attach")||V.includes("media")||V.includes("image")||V.includes("audio")){let oe=s[O];e?.debug?.(`[parseSocketMessage] Field "${O}": ${JSON.stringify(oe).substring(0,500)}`)}}}}let y="text",k=w[0];if(k){let R=k.title?.split(".").pop()?.toLowerCase();R==="ilbc"?y="audio":["jpg","jpeg","png","gif","bmp","webp"].includes(R||"")?y="image":["mp4","mov","avi","mkv"].includes(R||"")?y="video":y="file"}let C=f;if(w.length>0){let R=[];for(let B of w){let N=B.title?.split(".").pop()?.toLowerCase();N==="ilbc"?R.push(l("attachment.voice",{duration:B.duration||""})):["jpg","jpeg","png","gif","bmp","webp"].includes(N||"")?R.push(l("attachment.image",{title:B.title})):["mp4","mov","avi","mkv"].includes(N||"")?R.push(l("attachment.video",{title:B.title})):R.push(l("attachment.file",{title:B.title}))}let q=R.join(" ");f.trim()?C=`${f}
16
+ `);d=Buffer.concat([f,r.data])}return ce.writeFileSync(u,d),{filePath:u,fileName:c,fileSize:d.length}}async convertAudio(e,o="wav"){let t=o.startsWith(".")?o:`.${o}`,i=e.replace(/\.[^.]+$/,t),a=await import(["child","process"].join("_")),{promisify:r}=await import("util"),c=r(a.execFile);try{await c("ffmpeg",["-y","-i",e,"-ar","16000","-ac","1",i],{timeout:3e4})}catch(u){throw new Error(l("api.audio_convert_failed",{error:u.message||String(u)}))}return{filePath:i,format:o}}async createGroup(e,o){let t=await this.searchGroups(e,1);if(t.length>0&&t[0].name===e)return{uid:t[0].uid,name:t[0].name||e};let i={true_name:e,group_type:"topic"};o&&(i.description=o);let s=await this.client.postJson({func:"cim.group:create",sid:this.sid,payload:i});if(s.code!=="S_OK")throw new Error(l("api.create_group_failed",{code:s.code,msg:s.msg||""}));let a=s.var;return{uid:String(a.uid||""),name:e}}async deleteGroup(e){let o=await this.client.postJson({func:"cim.group:discard",sid:this.sid,payload:{uid:e}});if(o.code!=="S_OK")throw new Error(l("api.delete_group_failed",{code:o.code,msg:o.msg||""}));return!0}createSocketClient(e){return sn.fromLunkrConfig(this.session.baseUrl,this.sid,this.session.cookie,{uid:this.session.selfUid,username:this.senderName,eventCallbacks:{connect:()=>e.onConnect?.(),disconnect:()=>e.onDisconnect?.(),ready:()=>e.onReady?.(),message:o=>e.onMessage?.(o),error:o=>{let t=o&&typeof o=="object"&&"message"in o?String(o.message):"Unknown error";e.onError?.(new Error(t))}}})}}});var K=se(()=>{re();oo();De();en()});var Qc={};us(Qc,{loginCommand:()=>Pn,loginCommandMeta:()=>Yc});async function cm(n){try{let e=new F(n.baseUrl,{apiPath:n.apiPath}),o={};for(let t of n.cookie.split(";")){let i=t.trim();if(i.includes("=")){let s=i.indexOf("="),a=i.substring(0,s).trim(),r=i.substring(s+1).trim();o[a]=r}}return e.setCookies(o),await e.checkSessionValid(n.sid)}catch{return!1}}async function xi(n){try{let e=new F(n.baseUrl,{apiPath:n.apiPath}),o={};for(let i of n.cookie.split(";")){let s=i.trim();if(s.includes("=")){let a=s.indexOf("="),r=s.substring(0,a).trim(),c=s.substring(a+1).trim();o[r]=c}}e.setCookies(o);let t=await e.postJson({func:"cim.common:getCimPrefAttr",sid:n.sid,payload:{return_field:"nickname,true_name,name"}});if(t.code==="S_OK"&&t.var){let i=t.var,s=i.nickname||i.true_name||i.name;return s?String(s).trim():null}}catch{}return null}async function Pn(n,e){let o=e.verbose??!1,t=e.debug??!1,i=e.force??!1,s=e.temp??!1;console.log(""),console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(` ${l("login.qrcode_login_intro")}`),console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(""),console.log(s?` ${l("messages.mode_temporary_desc")}`:` ${l("messages.mode_persistent_desc")}`),console.log("");let a=L();if(i)console.log(l("messages.force_relogin"));else{let g=a.accounts?.[0];if(g?.session?.sid){if(await cm(g.session)){let w=await xi(g.session);w&&(g.session.senderName=w,E(a)),console.log(l("messages.already_logged_in")),w&&console.log(`${l("labels.name")}: ${w}`),console.log(`UID: ${g.session.selfUid}`),console.log("");return}o&&(console.log(l("errors.session_expired_login")),console.log(""),console.log(l("status.login_hint")))}}let r=a.accounts?.[0];if(r?.apiToken&&!i){console.log(l("messages.authenticating_token"));let g=await Le(r.email||r.accountId,r.apiToken,a.device_uuid,{debug:t});if(g.success&&g.sid&&g.cookie){let v=g.selfUid||r.session?.selfUid;r.session={sid:g.sid,cookie:g.cookie,baseUrl:vo,apiPath:xn,selfUid:v};let w=await xi(r.session);w&&(r.session.senderName=w),E(a);let y=10;console.log(""),console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(` ${l("messages.login_successful_token")}`),console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(""),w&&console.log(` ${I(l("labels.name")+":",y)} ${w}`),console.log(` ${I(l("labels.email")+":",y)} ${g.email}`),console.log(` ${I(l("labels.bot")+":",y)} ${ae()}`),console.log(""),console.log(` ${I(l("labels.config")+":",y)} ${de()}`),console.log("");return}console.log(l("login.token_expired_need_rescan")),t&&console.log(l("login.token_login_error",{error:g.error||"Unknown"}))}let c=await si({device:{device_uuid:a.device_uuid,device_os:a.device_os,device_model:a.device_model,device_name:a.device_name},debug:t});c.success||(console.error(""),console.error(l("login.qrcode_login_failed",{error:c.error||"Unknown"})),process.exit(1)),(!c.apiToken||!c.email)&&(console.error(""),console.error(l("login.qrcode_login_no_token")),process.exit(1)),console.log(""),console.log(l("messages.authenticating_with_token"));let u=await Le(c.email,c.apiToken,c.deviceUuid||a.device_uuid,{debug:t});u.success||(console.error(""),console.error(l("login.token_login_failed",{error:u.error||"Unknown"})),process.exit(1)),(!u.sid||!u.cookie)&&(console.error(""),console.error(l("login.token_login_no_session")),process.exit(1));let p=u.selfUid||c.selfUid,d={sid:u.sid,cookie:u.cookie,baseUrl:vo,apiPath:xn,selfUid:p},m=await xi(d);m&&(d.senderName=m);let f={accountId:c.email,email:c.email,enabled:!0,session:d,apiToken:s?void 0:c.apiToken};a=L();let h=a.accounts?.findIndex(g=>g.accountId===c.email)??-1;if(h>=0&&a.accounts){let g=a.accounts[h];g.session=f.session,g.enabled=!0,f.apiToken!==void 0&&(g.apiToken=f.apiToken)}else a.accounts||(a.accounts=[]),a.accounts.push(f);E(a);let x=10;console.log(""),console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(` ${l("messages.login_successful_qrcode")}`),console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(""),m&&console.log(` ${I(l("labels.name")+":",x)} ${m}`),console.log(` ${I(l("labels.email")+":",x)} ${c.email}`),console.log(` ${I(l("labels.bot")+":",x)} ${ae()}`),console.log(` ${I("UID:",x)} ${p}`),console.log(s?` ${I(l("labels.mode")+":",x)} ${l("messages.mode_temporary")}`:` ${I(l("labels.mode")+":",x)} ${l("messages.mode_persistent")}`),console.log(""),console.log(` ${I(l("labels.config")+":",x)} ${de()}`),console.log("")}var Yc,zo=se(()=>{K();vn();Rn();U();Yc={name:"login",description:"Login to Lunkr using QR code",options:[{name:"verbose",alias:"v",description:"Verbose output",type:"boolean",required:!1},{name:"debug",alias:"d",description:"Debug output (show network requests)",type:"boolean",required:!1},{name:"force",alias:"f",description:"Force re-login even if session is valid",type:"boolean",required:!1},{name:"temp",alias:"t",description:"Temporary login (do not save api_token)",type:"boolean",required:!1}]}});fn();U();function hs(n){return{}}function xs(n){return{accountId:n.accountId}}function vs(n){return{}}import{Type as _}from"@sinclair/typebox";import{Value as Jm}from"@sinclair/typebox/value";var Ml=_.Object({name:_.String({minLength:1,description:"Discussion name is required"}),agentId:_.Optional(_.String()),creatorUid:_.String({minLength:1,description:"Creator UID is required"}),createdAt:_.Union([_.String(),_.Number()],{description:"Creation timestamp"})}),Bl=_.Union([_.Literal("open"),_.Literal("allowlist"),_.Literal("disabled")]),bs=_.Union([_.Literal("open"),_.Literal("allowlist"),_.Literal("disabled")]),Gl=_.Object({enabled:_.Optional(_.Boolean()),allowFrom:_.Optional(_.Array(_.String())),policy:_.Optional(bs),requireMention:_.Optional(_.Boolean())}),zl=_.Object({policy:_.Union([_.Literal("disabled"),_.Literal("mentionOnly"),_.Literal("open")])}),Zo=_.Object({enabled:_.Optional(_.Boolean({default:!0})),commandPrefix:_.Optional(_.String({minLength:1,default:"/"})),botDiscussions:_.Optional(_.Record(_.String(),Ml)),dmPolicy:_.Optional(Bl),allowFrom:_.Optional(_.Array(_.String())),groupPolicy:_.Optional(bs),groups:_.Optional(_.Array(_.String())),discussions:_.Optional(_.Record(_.String(),Gl)),groupTypeRules:_.Optional(_.Record(_.String(),zl))}),Kl=_.Object({email:_.String({minLength:1,description:"Email is required"}),password:_.String({minLength:1,description:"Password is required"}),deviceUuid:_.Optional(_.String()),deviceName:_.Optional(_.String())}),Hl=_.Object({sid:_.String(),selfUid:_.String(),cookie:_.String(),baseUrl:_.String(),apiPath:_.String()}),Vl=_.Object({accountId:_.String({minLength:1,description:"Account ID is required"}),name:_.Optional(_.String()),enabled:_.Optional(_.Boolean({default:!0})),credentials:Kl,config:Zo,session:_.Optional(Hl)}),Ym=_.Record(_.String(),Vl);var Se="default";re();var be="agent:";function Xl(n){let e=L(),o=e.accounts||[];if(n&&n.startsWith(be)){let i=n.slice(be.length),s=o.find(a=>a.email===i&&a.role==="agent");return s?{accountId:s.accountId,name:s.name,enabled:s.enabled,session:s.session,config:s.config,apiToken:s.apiToken,role:s.role,agentId:s.agentId}:null}if(!n||n===Se){let i=W(e);if(!i)return null;let s=o.find(a=>a.accountId===i.accountId||a.email===i.email);return{accountId:i.accountId,name:s?.name,enabled:i.enabled,session:i.session,config:s?.config,apiToken:i.apiToken,role:i.role,agentId:i.agentId}}let t=o.find(i=>i.accountId===n);return t?{accountId:t.accountId,name:t.name,enabled:t.enabled,session:t.session,config:t.config,apiToken:t.apiToken,role:t.role,agentId:t.agentId}:null}function Ps(n){return n.channels?.["lunkr-openclaw"]}var Zl={enabled:!0,commandPrefix:"/bot",botDiscussions:{},dmPolicy:"open",allowFrom:[],groupPolicy:"open",groups:[]};function Ls(n){switch(n){case"allow":case"any":case"pairing":return"open";case"deny":return"disabled";case"whitelist":return"allowlist";case"open":case"allowlist":case"disabled":return n;default:return"open"}}function Is(n){switch(n){case"allow":case"any":return"open";case"deny":return"disabled";case"whitelist":return"allowlist";case"open":case"allowlist":case"disabled":return n;default:return"open"}}function eu(n,e){let o={...Zl,...n};return e?{...o,...e,dmPolicy:Ls(e.dmPolicy??o.dmPolicy),groupPolicy:Is(e.groupPolicy??o.groupPolicy),botDiscussions:{...o.botDiscussions,...e.botDiscussions},discussions:{...o.discussions,...e.discussions},groupTypeRules:{...o.groupTypeRules,...e.groupTypeRules},allowFrom:e.allowFrom??o.allowFrom,groups:e.groups??o.groups}:{...o,dmPolicy:Ls(o.dmPolicy),groupPolicy:Is(o.groupPolicy)}}function me(n,e){let o=Ps(n),i=Xl(e??Se);if(!i?.session||o?.enabled===!1)return null;let s=o?.enabled??!0,a=eu(o,i.config),r=i.session;return{accountId:i.accountId,name:i.name??ae(),enabled:s,selfUid:i.session.selfUid,sid:i.session.sid,cookie:i.session.cookie,botName:ae(),commandPrefix:a.commandPrefix,botDiscussions:a.botDiscussions,senderName:r.senderName,config:a,lunkrConfig:i.session,hasApiToken:!!i.apiToken,role:i.role||"standard",agentId:i.agentId}}function $n(n,e){return{...n,sid:e.sid,cookie:e.cookie,selfUid:e.selfUid||n.selfUid,lunkrConfig:e}}var Us={listAccountIds:n=>{let e=[],o=L();W(o)?.session&&e.push(Se);let i=Fn(o);for(let s of i)s.session?.sid&&e.push(`${be}${s.email}`);return e},resolveAccount:(n,e)=>me(n,e),defaultAccountId:()=>Se,isConfigured:n=>n?!!((n.sid||n.hasApiToken)&&n.selfUid):!1,isEnabled:n=>n?n.enabled??!0:!1,describeAccount:n=>{if(!n)return{accountId:"default",configured:!1,enabled:!1};let e=!!((n.sid||n.hasApiToken)&&n.selfUid);return{accountId:n.accountId,name:n.name,enabled:n.enabled,configured:e}},setAccountEnabled:n=>{let{cfg:e,enabled:o}=n,t=Ps(e)??{};return{...e,channels:{...e.channels,lunkr:{...t,enabled:o}}}},unconfiguredReason:n=>n?n.sid?n.selfUid?"Account not configured":"Lunkr user ID not available. Please re-authenticate.":"Lunkr session not configured. Run: openclaw lunkr login":"Lunkr account not configured. Run: openclaw lunkr login"};function Ts(n){return n.replace(/^lunkr:/i,"")}function nu(n,e,o){let t=o.config.dmPolicy??"open",i=o.config.allowFrom??[];return{policy:t,allowFrom:i.map(Ts),policyPath:"channels.lunkr-openclaw.dmPolicy",allowFromPath:"channels.lunkr-openclaw.allowFrom",approveHint:"openclaw pairing approve lunkr <code>",normalizeEntry:Ts}}async function ou(n){let e=[],{account:o}=n;return o.config.groupPolicy==="allowlist"&&!o.config.groups?.length&&e.push('Group policy is set to "allowlist" but no groups are configured. Bot will not respond in any group.'),o.config.dmPolicy==="allowlist"&&!o.config.allowFrom?.length&&e.push('DM policy is set to "allowlist" but allowFrom is empty. Bot will not respond to any DM.'),e}var Os={resolveDmPolicy:n=>{let{cfg:e,accountId:o,account:t}=n;return nu(e,o??Se,t)},collectWarnings:n=>ou(n)};var yc=Jo(lt(),1);import*as xe from"fs";import*as Ze from"path";import*as bc from"os";tn();uo();vn();yo();var Zs={"cim.cal:createEvents":{func:"cim.cal:createEvents",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:createEventsForLunkr":{func:"cim.cal:createEventsForLunkr",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:deleteEvents":{func:"cim.cal:deleteEvents",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:deleteEventsForLunkr":{func:"cim.cal:deleteEventsForLunkr",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:deleteReminder":{func:"cim.cal:deleteReminder",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:getMeetingRooms":{func:"cim.cal:getMeetingRooms",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:getReminder":{func:"cim.cal:getReminder",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:getReminderWithAutoCheck":{func:"cim.cal:getReminderWithAutoCheck",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:setReminder":{func:"cim.cal:setReminder",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:setReminderForLunkr":{func:"cim.cal:setReminderForLunkr",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:updateEvents":{func:"cim.cal:updateEvents",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.cal:updateEventsForLunkr":{func:"cim.cal:updateEventsForLunkr",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:api":{func:"cim.common:api",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:autoKeepSession":{func:"cim.common:autoKeepSession",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:checkModuleVersion":{func:"cim.common:checkModuleVersion",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:checkVersion":{func:"cim.common:checkVersion",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:clickLog":{func:"cim.common:clickLog",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:customOpLog":{func:"cim.common:customOpLog",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:delayClickLog":{func:"cim.common:delayClickLog",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:feedback":{func:"cim.common:feedback",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:flashMailLog":{func:"cim.common:flashMailLog",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getAdminFunctionSetting":{func:"cim.common:getAdminFunctionSetting",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getAttrs":{func:"cim.common:getAttrs",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getAvatar":{func:"cim.common:getAvatar",path:"/lunkr/f",requiresFunc:!0,defaultUseGet:!0},"cim.common:getBigAvatar":{func:"cim.common:getBigAvatar",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getCimPrefAttr":{func:"cim.common:getCimPrefAttr",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getConfig":{func:"cim.common:getConfig",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getCustomDomain":{func:"cim.common:getCustomDomain",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getEnfDetail":{func:"cim.common:getEnfDetail",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getInitConfig":{func:"cim.common:getInitConfig",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getLastLoginStatus":{func:"cim.common:getLastLoginStatus",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getMaterial":{func:"cim.common:getMaterial",path:"/lunkr/f",requiresFunc:!0,defaultUseGet:!0},"cim.common:getNSISDownloadURL":{func:"cim.common:getNSISDownloadURL",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getOrgInfo":{func:"cim.common:getOrgInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getRemindList":{func:"cim.common:getRemindList",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getRevision":{func:"cim.common:getRevision",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getSysUserInfo":{func:"cim.common:getSysUserInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getUserType":{func:"cim.common:getUserType",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getValueByKey":{func:"cim.common:getValueByKey",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:getWebSocketURL":{func:"cim.common:getWebSocketURL",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:iosHotfix":{func:"cim.common:iosHotfix",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:listAuthDevice":{func:"cim.common:listAuthDevice",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:listFlagUser":{func:"cim.common:listFlagUser",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:logCollapse":{func:"cim.common:logCollapse",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:logRecord":{func:"cim.common:logRecord",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:onlineStatus":{func:"cim.common:onlineStatus",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:resetTopicAvatar":{func:"cim.common:resetTopicAvatar",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:searchFlagUser":{func:"cim.common:searchFlagUser",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:sendNetDiskOperateNotice":{func:"cim.common:sendNetDiskOperateNotice",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:sendShake":{func:"cim.common:sendShake",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:setApplePushSwitch":{func:"cim.common:setApplePushSwitch",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:setAvatar":{func:"cim.common:setAvatar",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:setCimPrefAttr":{func:"cim.common:setCimPrefAttr",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:setFlag":{func:"cim.common:setFlag",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:setMiscFlag":{func:"cim.common:setMiscFlag",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:setRevision":{func:"cim.common:setRevision",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:sioSubscribe":{func:"cim.common:sioSubscribe",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:transEmail":{func:"cim.common:transEmail",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.common:verify":{func:"cim.common:verify",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.company:getCompanyInfoById":{func:"cim.company:getCompanyInfoById",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.company:getSensitiveWord":{func:"cim.company:getSensitiveWord",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.company:listCompanyInfo":{func:"cim.company:listCompanyInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.container:searchContacts":{func:"cim.container:searchContacts",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.extSys:opRedpacket":{func:"cim.extSys:opRedpacket",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.extSys:push":{func:"cim.extSys:push",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.extSys:pushRegister":{func:"cim.extSys:pushRegister",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:addCollect":{func:"cim.file:addCollect",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:cancelCollect":{func:"cim.file:cancelCollect",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:directData":{func:"cim.file:directData",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:getFileData":{func:"cim.file:getFileData",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:getSearchResult":{func:"cim.file:getSearchResult",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:getThumbnail":{func:"cim.file:getThumbnail",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:listCollect":{func:"cim.file:listCollect",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:moveToNetFolder":{func:"cim.file:moveToNetFolder",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:prepare":{func:"cim.file:prepare",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:search":{func:"cim.file:search",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:searchCollect":{func:"cim.file:searchCollect",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:uploadPost":{func:"cim.file:uploadPost",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:uploadSnippet":{func:"cim.file:uploadSnippet",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:uploadVoice":{func:"cim.file:uploadVoice",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.file:viewFile":{func:"cim.file:viewFile",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:attendance":{func:"cim.group:attendance",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:create":{func:"cim.group:create",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:delete":{func:"cim.group:delete",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:discard":{func:"cim.group:discard",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:getInfo":{func:"cim.group:getInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:getMembersInfo":{func:"cim.group:getMembersInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:getRelate":{func:"cim.group:getRelate",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:invite":{func:"cim.group:invite",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:listVipUserTopic":{func:"cim.group:listVipUserTopic",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:notifyFlag":{func:"cim.group:notifyFlag",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:search":{func:"cim.group:search",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:transfer":{func:"cim.group:transfer",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:updateDescription":{func:"cim.group:updateDescription",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.group:updateName":{func:"cim.group:updateName",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.link:generate":{func:"cim.link:generate",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.link:getInfo":{func:"cim.link:getInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.link:prolong":{func:"cim.link:prolong",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.link:sendInviteMail":{func:"cim.link:sendInviteMail",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.link:shorten":{func:"cim.link:shorten",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:compose":{func:"cim.mail:compose",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:getPushFolder":{func:"cim.mail:getPushFolder",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:getShareNF":{func:"cim.mail:getShareNF",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:readMail":{func:"cim.mail:readMail",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:readShare":{func:"cim.mail:readShare",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:refreshToken":{func:"cim.mail:refreshToken",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:remoteCompose":{func:"cim.mail:remoteCompose",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:remoteRequest":{func:"cim.mail:remoteRequest",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:searchMessages":{func:"cim.mail:searchMessages",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:setAllRead":{func:"cim.mail:setAllRead",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:setPushFolder":{func:"cim.mail:setPushFolder",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:share":{func:"cim.mail:share",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:ssoLunkr":{func:"cim.mail:ssoLunkr",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.mail:uploadToPersonalNF":{func:"cim.mail:uploadToPersonalNF",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:batchReply":{func:"cim.msg:batchReply",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:broadcast":{func:"cim.msg:broadcast",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:clearUnread":{func:"cim.msg:clearUnread",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:collect":{func:"cim.msg:collect",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:deleteUploadFile":{func:"cim.msg:deleteUploadFile",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:getInfo":{func:"cim.msg:getInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:getLastMsgByType":{func:"cim.msg:getLastMsgByType",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:getLastMsgByUID":{func:"cim.msg:getLastMsgByUID",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:getSearchResult":{func:"cim.msg:getSearchResult",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:getShare":{func:"cim.msg:getShare",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:list":{func:"cim.msg:list",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:operate":{func:"cim.msg:operate",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:p2p":{func:"cim.msg:p2p",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:reply":{func:"cim.msg:reply",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:search":{func:"cim.msg:search",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:searchByGroup":{func:"cim.msg:searchByGroup",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:setVip":{func:"cim.msg:setVip",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:share":{func:"cim.msg:share",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:stats":{func:"cim.msg:stats",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:updateLastMsg":{func:"cim.msg:updateLastMsg",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.msg:updateRcptMsg":{func:"cim.msg:updateRcptMsg",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.oabEx:getAttrs":{func:"cim.oabEx:getAttrs",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.oabEx:getUserInfo":{func:"cim.oabEx:getUserInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.oabEx:setAttrs":{func:"cim.oabEx:setAttrs",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:deleteLotterySetting":{func:"cim.operation:deleteLotterySetting",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:deleteOperateActivityById":{func:"cim.operation:deleteOperateActivityById",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:exportUserLottery":{func:"cim.operation:exportUserLottery",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:getCommentByCode":{func:"cim.operation:getCommentByCode",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:getLotteryResultByCode":{func:"cim.operation:getLotteryResultByCode",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:getOperateActivityById":{func:"cim.operation:getOperateActivityById",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:getPrizeInfoByCode":{func:"cim.operation:getPrizeInfoByCode",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:listActiveOperateActivity":{func:"cim.operation:listActiveOperateActivity",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:listLotterySetting":{func:"cim.operation:listLotterySetting",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:saveComment":{func:"cim.operation:saveComment",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:saveLotterySetting":{func:"cim.operation:saveLotterySetting",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:saveOperateActivity":{func:"cim.operation:saveOperateActivity",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:saveUserCommentForPrize":{func:"cim.operation:saveUserCommentForPrize",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:sendGreetingCard":{func:"cim.operation:sendGreetingCard",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:startLottery":{func:"cim.operation:startLottery",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.operation:updateOperateActivity":{func:"cim.operation:updateOperateActivity",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:addContact":{func:"cim.pab:addContact",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:addGroup":{func:"cim.pab:addGroup",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:addToBlacklist":{func:"cim.pab:addToBlacklist",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:deleteGroup":{func:"cim.pab:deleteGroup",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:getAllContacts":{func:"cim.pab:getAllContacts",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:getBlacklist":{func:"cim.pab:getBlacklist",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:getCombinedContacts":{func:"cim.pab:getCombinedContacts",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:getRecentContacts":{func:"cim.pab:getRecentContacts",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:getWholeContacts":{func:"cim.pab:getWholeContacts",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:removeFromBlacklist":{func:"cim.pab:removeFromBlacklist",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:searchContact":{func:"cim.pab:searchContact",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.pab:updateContact":{func:"cim.pab:updateContact",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.qrcode:generate":{func:"cim.qrcode:generate",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.qrcode:qrcodeInfo":{func:"cim.qrcode:qrcodeInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.qrcode:register":{func:"cim.qrcode:register",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.remind:get":{func:"cim.remind:get",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.remind:getMobile":{func:"cim.remind:getMobile",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.remind:set":{func:"cim.remind:set",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.remind:setMobile":{func:"cim.remind:setMobile",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.revision:getRevision":{func:"cim.revision:getRevision",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.state:getNotify":{func:"cim.state:getNotify",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.state:query":{func:"cim.state:query",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.state:queryHasLogin":{func:"cim.state:queryHasLogin",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.state:queryUserState":{func:"cim.state:queryUserState",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.state:set":{func:"cim.state:set",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.state:setNotify":{func:"cim.state:setNotify",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.third:checkToken":{func:"cim.third:checkToken",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.third:genLinkNonce":{func:"cim.third:genLinkNonce",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.third:listApp":{func:"cim.third:listApp",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.thread:getThreadInfo":{func:"cim.thread:getThreadInfo",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.thread:listBulletin":{func:"cim.thread:listBulletin",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.thread:listRevision":{func:"cim.thread:listRevision",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.thread:listThreadNew":{func:"cim.thread:listThreadNew",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.thread:setTop":{func:"cim.thread:setTop",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:changePassword":{func:"cim.user:changePassword",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:checkVersionAndLogin":{func:"cim.user:checkVersionAndLogin",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:genTempSession":{func:"cim.user:genTempSession",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:getCard":{func:"cim.user:getCard",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:getEmojiList":{func:"cim.user:getEmojiList",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:getLunkrMailData":{func:"cim.user:getLunkrMailData",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:getRecentUnread":{func:"cim.user:getRecentUnread",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:getTempSession":{func:"cim.user:getTempSession",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:getTempShareSession":{func:"cim.user:getTempShareSession",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:kickOffLine":{func:"cim.user:kickOffLine",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:kickOnlineDevice":{func:"cim.user:kickOnlineDevice",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:kickOnlineUserForAdmin":{func:"cim.user:kickOnlineUserForAdmin",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:listKickOffLineLog":{func:"cim.user:listKickOffLineLog",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:listLoginHistory":{func:"cim.user:listLoginHistory",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:logout":{func:"cim.user:logout",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:queryOnlineDevice":{func:"cim.user:queryOnlineDevice",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:removeKickOffLine":{func:"cim.user:removeKickOffLine",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:saveCard":{func:"cim.user:saveCard",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:saveEmoji":{func:"cim.user:saveEmoji",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:shareCard":{func:"cim.user:shareCard",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:updateName":{func:"cim.user:updateName",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:updateOrgUserLastModified":{func:"cim.user:updateOrgUserLastModified",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"cim.user:updateTempSession":{func:"cim.user:updateTempSession",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"nfEx:getFileData":{func:"nfEx:getFileData",path:"/crux/adm_api/filePreview",requiresFunc:!0,defaultUseGet:!0},"nfEx:getShareFile":{func:"nfEx:getShareFile",path:"/lunkr/f",requiresFunc:!0,defaultUseGet:!0},"oab:autoMatch":{func:"oab:autoMatch",path:"/coremail/s/json",requiresFunc:!0,defaultUseGet:!1},"oab:get":{func:"oab:get",path:"/coremail/s/json",requiresFunc:!0,defaultUseGet:!1},"oab:getDirectories":{func:"oab:getDirectories",path:"/coremail/s/json",requiresFunc:!0,defaultUseGet:!1},"oab:listEx":{func:"oab:listEx",path:"/coremail/s/json",requiresFunc:!0,defaultUseGet:!1},"oab:searchEx":{func:"oab:searchEx",path:"/coremail/s/json",requiresFunc:!0,defaultUseGet:!1},"pab:createContact":{func:"pab:createContact",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"pab:deleteContact":{func:"pab:deleteContact",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"pab:getAllContactsByType":{func:"pab:getAllContactsByType",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"pab:getContactByEmail":{func:"pab:getContactByEmail",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"pab:getContactsByGroup":{func:"pab:getContactsByGroup",path:"/lunkr/s/json",requiresFunc:!0,defaultUseGet:!1},"user:config":{func:"user:config",path:"/lunkr/common/config",requiresFunc:!1,defaultUseGet:!0},"user:init":{func:"user:init",path:"/lunkr/init",requiresFunc:!1,defaultUseGet:!0}},fu=Object.keys(Zs);tn();Rn();De();U();oo();var gc=1e3;async function hc(n,e){try{let o=await n.postJson({func:"cim.common:getCimPrefAttr",sid:e,payload:{return_field:"nickname,true_name,name"}});if(o.code==="S_OK"&&o.var){let t=o.var,i=t.nickname||t.true_name||t.name;return i?String(i).trim():null}}catch{}return null}async function xc(n,e){let o=me(n,e);if(!o)throw new Error(l("errors.account_not_configured"));let t=new F(o.lunkrConfig.baseUrl,{apiPath:o.lunkrConfig.apiPath}),i={"Cim.sid":o.sid};for(let s of o.cookie.split(";")){let a=s.trim();if(a.includes("=")){let[r,c]=a.split("=",2);i[r.trim()]=c.trim()}}return t.setCookies(i),{client:t,account:o}}async function Dd(n,e){let{to:o,content:t,sid:i,accountId:s,lunkrConfig:a}=e,r=await n.postJson({func:"cim.msg:reply",sid:i,payload:{uid:o,content:t,type:"text"}});if(r.code!=="S_OK"&&Ln(String(r.code))){let u=await he(s);if(u.success&&u.session){let p=new F(a.baseUrl,{apiPath:a.apiPath}),d={"Cim.sid":u.session.sid};for(let f of u.session.cookie.split(";")){let h=f.trim();if(h.includes("=")){let[x,g]=h.split("=",2);d[x.trim()]=g.trim()}}p.setCookies(d);let m=await p.postJson({func:"cim.msg:reply",sid:u.session.sid,payload:{uid:o,content:t,type:"text"}});if(m.code==="S_OK")return{msgId:m.var?.msgId??`msg-${Date.now()}`};throw new Error(l("api.send_failed",{code:String(m.code)}))}else console.error(`[${s}] Session refresh failed: ${u.error}. Please run: lunkr login`)}if(r.code!=="S_OK")throw new Error(l("api.send_failed",{code:String(r.code)}));return{msgId:r.var?.msgId??`msg-${Date.now()}`}}async function Nd(n,e){let{to:o,content:t,sid:i,accountId:s,lunkrConfig:a}=e,r=await n.postJson({func:"cim.msg:reply",sid:i,payload:{uid:o,content:t,type:"post"}});if(r.code!=="S_OK"&&Ln(String(r.code))){let u=await he(s);if(u.success&&u.session){let p=new F(a.baseUrl,{apiPath:a.apiPath}),d={"Cim.sid":u.session.sid};for(let f of u.session.cookie.split(";")){let h=f.trim();if(h.includes("=")){let[x,g]=h.split("=",2);d[x.trim()]=g.trim()}}p.setCookies(d);let m=await p.postJson({func:"cim.msg:reply",sid:u.session.sid,payload:{uid:o,content:t,type:"post"}});if(m.code==="S_OK")return{msgId:m.var?.msgId??`post-${Date.now()}`};throw new Error(l("api.send_post_failed",{code:String(m.code)}))}else console.error(`[${s}] Session refresh failed: ${u.error}. Please run: lunkr login`)}if(r.code!=="S_OK")throw new Error(l("api.send_post_failed",{code:String(r.code)}));return{msgId:r.var?.msgId??`post-${Date.now()}`}}function vc(n){let e=n.replace(/^lunkr:/i,"");return e.startsWith("discussion:")?{chatId:e.replace("discussion:",""),chatType:"group"}:e.startsWith("channel:")?{chatId:e.replace("channel:",""),chatType:"channel"}:{chatId:e,chatType:"p2p"}}async function Md(n){if(n.startsWith("http://")||n.startsWith("https://")){let o=bc.tmpdir(),t=`lunkr-media-${Date.now()}-${Ze.basename(new URL(n).pathname)||"file"}`,i=Ze.join(o,t),s=await hn(n,{},6e4);return xe.writeFileSync(i,s.data),{filePath:i,cleanup:()=>{try{xe.existsSync(i)&&xe.unlinkSync(i)}catch{}}}}let e=Ze.resolve(n);if(!xe.existsSync(e))throw new Error(l("errors.file_not_found",{path:n}));return{filePath:e,cleanup:()=>{}}}async function Bd(n,e){let{filePath:o,sid:t,uploadUid:i,cookies:s,baseUrl:a,apiPath:r}=e,c=Ze.resolve(o),u=Ze.basename(c);if(!xe.existsSync(c))throw new Error(l("errors.file_not_found",{path:o}));let p=xe.statSync(c),d=yc.lookup(c)||"application/octet-stream",m=xe.readFileSync(c),f=`c:nf:cim${Math.floor(Math.random()*9999)+1}`,h=await n.postJson({func:"cim.file:prepare",sid:t,payload:{size:p.size,composeId:f,fileName:u,uid:i,contentType:d}});if(h.code!=="S_OK")throw new Error(l("api.upload_prepare_failed",{code:String(h.code)}));let g=h.var?.attachmentId;if(!g)throw new Error(l("api.upload_no_attachment_id"));let v=`${a}${r}?func=cim.file:directData&sid=${encodeURIComponent(t)}&composeId=${encodeURIComponent(f)}&attachmentId=${g}&offset=0&uid=${encodeURIComponent(i)}`,y={"Content-Type":"application/octet-stream",Cookie:Object.entries(s).map(([q,B])=>`${q}=${B}`).join("; ")},k=await on(v,m,y,6e4),C;try{C=JSON.parse(k.data)}catch{throw new Error(l("api.upload_invalid_response",{data:k.data?.substring?.(0,200)}))}if(C.code!=="S_OK")throw new Error(l("api.upload_data_failed",{code:String(C.code)}));let b=await n.postJson({func:"cim.file:moveToNetFolder",sid:t,payload:{composeId:f,fileName:u,item:"fileName",attachmentId:g,uid:i}});if(b.code!=="S_OK")throw new Error(l("api.upload_move_failed",{code:String(b.code)}));let S=b.var,T=S?.fileId,R=S?.uid;if(!T)throw new Error(l("api.upload_no_file_id"));return{fileId:T,fileUid:R||""}}var kc={deliveryMode:"direct",textChunkLimit:gc,sendText:async n=>{let{cfg:e,to:o,text:t,replyToId:i,accountId:s}=n,{client:a,account:r}=await xc(e,s),{chatId:c,chatType:u}=vc(o),p=r.botName??"Bot",d=r.senderName;d||(d=await hc(a,r.sid)),d||(d=r.selfUid?.includes("@")?r.selfUid.split("@")[0]:"User");let m=r.role==="agent",f=qe(t,d,p,m),h;return f.length>gc?h=await Nd(a,{to:c,content:f,sid:r.sid,accountId:r.accountId,lunkrConfig:r.lunkrConfig}):h=await Dd(a,{to:c,content:f,sid:r.sid,accountId:r.accountId,lunkrConfig:r.lunkrConfig}),{ok:!0,channel:"lunkr-openclaw",messageId:h.msgId}},sendMedia:async n=>{let{cfg:e,to:o,text:t,mediaUrl:i,accountId:s}=n;if(!i)throw new Error(l("errors.media_url_required"));let{client:a,account:r}=await xc(e,s),{chatId:c,chatType:u}=vc(o),p=r.botName??"Bot",d=r.senderName;d||(d=await hc(a,r.sid)),d||(d=r.selfUid?.includes("@")?r.selfUid.split("@")[0]:"User");let m=r.role==="agent",f=qe(t||"",d,p,m),h={"Cim.sid":r.sid};for(let k of r.cookie.split(";")){let C=k.trim();if(C.includes("=")){let[b,S]=C.split("=",2);h[b.trim()]=S.trim()}}let x=a,g=r.sid;if((await a.postJson({func:"cim.common:getOrgInfo",sid:r.sid})).code!=="S_OK"){let k=await he(r.accountId);if(!k.success||!k.session)throw new Error(l("errors.session_expired"));g=k.session.sid,x=new F(r.lunkrConfig.baseUrl,{apiPath:r.lunkrConfig.apiPath}),h={"Cim.sid":g};for(let C of k.session.cookie.split(";")){let b=C.trim();if(b.includes("=")){let[S,T]=b.split("=",2);h[S.trim()]=T.trim()}}x.setCookies(h)}let w,y;try{let k=await Md(i);w=k.filePath,y=k.cleanup;let C=u==="p2p"?r.selfUid:c,{fileId:b,fileUid:S}=await Bd(x,{filePath:w,sid:g,uploadUid:C,cookies:h,baseUrl:r.lunkrConfig.baseUrl,apiPath:r.lunkrConfig.apiPath}),T=await x.postJson({func:"cim.msg:reply",sid:g,payload:{uid:c,content:f,type:"text",attachments:[{fileId:b,uid:S}]}});if(T.code!=="S_OK")throw new Error(l("api.send_media_failed",{code:String(T.code)}));return{ok:!0,channel:"lunkr-openclaw",messageId:T.var?.msgId??`media-${Date.now()}`}}finally{y&&y()}}};yo();function _c(n,e){let o=n.chatType==="group"?n.chatId:null;return o&&(e.botDiscussions||{})[o]||null}function ui(n,e){return _c(n,e)!==null}function Gd(n,e){return n.trim().toLowerCase().startsWith(e.toLowerCase())}function wc(n,e){let o=n.fromUid===e.selfUid,t=o&&/^\[@!.+?\]/.test(n.content),i=o&&!t;if(t)return{isBotMention:!1,isFromBot:!0,isFromSelf:!1};let s=_c(n,e);return s?{isBotMention:!0,isFromBot:!1,isFromSelf:i,agentId:s.agentId}:o&&Gd(n.content,e.commandPrefix)?{isBotMention:!0,isFromBot:!1,isFromSelf:!0}:{isBotMention:!1,isFromBot:!1,isFromSelf:i}}function Cc(n,e){let o=n.fromUid===e.selfUid;return o&&/^\[@!.+?\]/.test(n.content)?{isBotMention:!1,isFromBot:!0,isFromSelf:!1}:o?{isBotMention:!1,isFromBot:!1,isFromSelf:!0}:n.chatType==="p2p"?{isBotMention:!0,isFromBot:!1,isFromSelf:!1,agentId:e.agentId,workspaceKey:`${e.selfUid}:${n.fromUid}`}:{isBotMention:!0,isFromBot:!1,isFromSelf:!1,agentId:e.agentId,workspaceKey:`${e.selfUid}:${n.chatId}`}}function zd(n,e){let o=n.trim();return o.toLowerCase().startsWith(e.toLowerCase())?o.slice(e.length).trim():n}function Sc(n,e){let o=e.role||"standard",t;if(o==="agent")t=Cc(n,e);else if(o==="standard+agent"){let r=Cc(n,e),c=wc(n,e);r.isBotMention?t=r:(c.isBotMention,t=c)}else t=wc(n,e);let s=ui(n,e)?n.content:zd(n.content,e.commandPrefix),a=n.chatType==="p2p"?"direct":n.chatType;return{externalId:n.msgId,channel:"lunkr-openclaw",chatType:a,peerId:n.chatId,senderId:n.fromUid,text:s,timestamp:n.timestamp,replyTo:n.threadId,mentions:n.mentionedUids,isBotMention:t.isBotMention,isFromBot:t.isFromBot,isFromSelf:t.isFromSelf,agentId:t.agentId,workspaceKey:t.workspaceKey,contentType:n.contentType,attachments:n.attachments}}function Kd(n){let e=n.indexOf("(");return e>0?n.substring(0,e):n}function No(n,e){if(!e||e.length===0)return!1;let o=n.replace(/^lunkr:/i,"");return e.some(t=>Kd(t).replace(/^lunkr:/i,"")===o)}function Hd(n){let e=n.match(/(#[A-Z])$/);return e?e[1]:null}function Ac(n,e,o){let t=e.config;if(n.chatType!=="direct"){let c={chatType:"group",chatId:n.peerId};if(ui(c,e))return{allowed:!0,reason:"bot discussion"}}if(n.chatType==="direct"){let c=t.dmPolicy||"open";return c==="disabled"?{allowed:!1,reason:"DM blocked: policy is disabled"}:c==="allowlist"?No(n.senderId,t.allowFrom)?{allowed:!0,reason:"sender in DM allowlist"}:{allowed:!1,reason:`DM blocked: sender ${n.senderId} not in allowFrom`}:{allowed:!0,reason:"DM policy is open"}}let i=n.peerId,s=t.discussions?.[i];if(s?.enabled===!1)return{allowed:!1,reason:`group blocked: discussion ${i} is disabled`};if(!(s&&(s.policy!==void 0||s.allowFrom!==void 0||s.requireMention!==void 0))){let c=Hd(i);if(c){let u=t.groupTypeRules?.[c];if(u){if(u.policy==="disabled")return{allowed:!1,reason:`group blocked: type rule ${c} is disabled`};if(u.policy==="mentionOnly"&&!(n.mentions?.includes(e.selfUid)||n.mentions?.includes("all")))return{allowed:!1,reason:`group blocked: type rule ${c} requires mention`}}}}if(s?.requireMention===!0&&!(n.mentions?.includes(e.selfUid)||n.mentions?.includes("all")))return{allowed:!1,reason:`group blocked: discussion ${i} requires mention`};let r=s?.policy||t.groupPolicy||"open";if(r==="disabled")return{allowed:!1,reason:"group blocked: policy is disabled"};if(r==="allowlist"){let c=No(i,t.groups);return s?.allowFrom&&s.allowFrom.length>0?No(n.senderId,s.allowFrom)?{allowed:!0,reason:"sender in discussion allowFrom"}:{allowed:!1,reason:`group blocked: sender ${n.senderId} not in discussion allowFrom for ${i}`}:c?{allowed:!0,reason:"group in allowlist"}:{allowed:!1,reason:`group blocked: ${i} not in groups allowlist`}}return s?.allowFrom&&s.allowFrom.length>0&&!No(n.senderId,s.allowFrom)?{allowed:!1,reason:`group blocked: sender ${n.senderId} not in discussion allowFrom for ${i}`}:{allowed:!0,reason:"group policy is open"}}De();U();oo();mn();var Pe=new Map,to=new Map,$c=5e3;function Jd(n){let e=Date.now(),o=to.get(n);if(o&&e-o<$c)return!0;if(to.set(n,e),to.size>1e3)for(let[t,i]of to)e-i>$c*2&&to.delete(t);return!1}function Yd(n,e){let o=e.role||"standard";return o==="agent"||o==="standard+agent"?n.chatType==="direct"?!0:n.mentions?.includes(e.selfUid)||n.mentions?.includes("all")||!1:n.isFromSelf}function Qd(n){let o=n.replace(/^(@\S+\s+)*/g,"").trim().toLowerCase();return o==="/help"||o.startsWith("/help ")?"/help":o==="/new"||o.startsWith("/new ")?"/new":null}var qc=1e3;async function Dc(n,e,o){let{to:t,text:i,chatType:s}=e;o?.debug?.(`[sendLunkrReply] to=${t}, chatType=${s}, textLen=${i.length}`);let a=n.botName??"Bot",r=n.senderName;r||(r=n.selfUid?.includes("@")?n.selfUid.split("@")[0]:"User");let c=e.skipPrefix??n.role==="agent",u=qe(i,r,a,c),p=n.sid,d=n.cookie,m=n;if(p){let f=new F(n.lunkrConfig.baseUrl,{apiPath:n.lunkrConfig.apiPath}),h={"Cim.sid":p};for(let g of d.split(";")){let v=g.trim();if(v.includes("=")){let[w,y]=v.split("=",2);h[w.trim()]=y.trim()}}f.setCookies(h);let x=await f.postJson({func:"cim.msg:reply",sid:p,payload:{uid:t,content:u,type:u.length>qc?"post":"text"}});if(o?.debug?.(`[sendLunkrReply] Response: code=${x.code}`),x.code==="S_OK"){let g=x.var?.msgId;return o?.info(`[sendLunkrReply] Message sent successfully${g?`: msgId=${g}`:""}`),{msgId:g??`msg-${Date.now()}`,account:m}}if(Ln(String(x.code)))o?.info(`[${n.accountId}] Session expired, clearing sid...`),p="",d="";else throw new Error(l("api.send_reply_failed",{code:String(x.code),msg:String(x.msg||"Unknown")}))}if(!p){o?.info(`[${n.accountId}] No valid session, attempting refresh with apiToken...`);let f=await he(n.accountId);if(f.success&&f.session){o?.info(`[${n.accountId}] Session refreshed, sending message...`),p=f.session.sid,d=f.session.cookie;let h=new F(n.lunkrConfig.baseUrl,{apiPath:n.lunkrConfig.apiPath}),x={"Cim.sid":p};for(let v of d.split(";")){let w=v.trim();if(w.includes("=")){let[y,k]=w.split("=",2);x[y.trim()]=k.trim()}}h.setCookies(x);let g=await h.postJson({func:"cim.msg:reply",sid:p,payload:{uid:t,content:u,type:u.length>qc?"post":"text"}});if(g.code==="S_OK"){let v=$n(n,f.session),w=g.var?.msgId;return o?.info(`[sendLunkrReply] Message sent successfully after refresh: msgId=${w}`),{msgId:w??`msg-${Date.now()}`,account:v}}throw o?.warn?.(`[${n.accountId}] Send failed after refresh: ${g.code}. Will retry later.`),new Error(l("api.send_reply_failed",{code:String(g.code),msg:String(g.msg||"Unknown")}))}throw o?.warn?.(`[${n.accountId}] Session refresh failed: ${f.error}. Will retry later.`),new Error(l("api.no_session"))}throw new Error(l("api.send_reply_failed",{code:"UNKNOWN",msg:"Unexpected state"}))}function Bo(n,e){let{log:o}=e;return sn.fromLunkrConfig(n.lunkrConfig.baseUrl,n.sid,n.cookie,{uid:n.selfUid,username:n.botName,autoReconnect:e.autoReconnect,eventCallbacks:{message:i=>{try{let s=Xd(i,o);if(s){s.attachments&&s.attachments.length>0&&(Tc(s.msgId,s.timestamp,s.attachments.map(r=>({fileId:r.fileId,uid:r.uid,title:r.title,contentType:r.contentType,fileSize:r.fileSize,type:r.type,inline:r.inline}))),o?.debug?.(`[gateway] Cached ${s.attachments.length} attachments for message ${s.msgId}`));let a=Sc(s,n);e.onMessage(a)}}catch(s){e.onError(s instanceof Error?s:new Error(String(s)))}},reaction:i=>{if(e.onReaction&&i&&typeof i=="object"){let s=i;e.onReaction({msgId:String(s.msgId??""),userId:String(s.fromUid??""),emoji:String(s.emoji??"")})}},disconnect:()=>{e.onDisconnect()},error:i=>{let s=i&&typeof i=="object"&&"message"in i?String(i.message):"Unknown socket error";e.onError(new Error(s))}}})}function Xd(n,e){if(!n||typeof n!="object")return null;let o=n,t=o.topic||"",i=o.payload||"",s;try{s=JSON.parse(i)}catch{return null}if(!s.mid&&!s.subject)return null;let a=Object.keys(s),r=s.attachments;e?.debug?.(`[parseSocketMessage] MSG keys=[${a.join(", ")}], attachments=${JSON.stringify(r)?.substring(0,200)}`);let c=String(s.mid||""),u=s.from||{},p=s.to||{},d=String(u.uid||""),m=String(u.true_name||u.email||""),f=String(s.subject||"");try{f=decodeURIComponent(f.replace(/\+/g," "))}catch{}let h=String(s.type||s.group_type||"p2p"),x=String(s.uid||p.uid||""),g;x.endsWith("#U")?g="p2p":x.endsWith("#T")?g="group":g=h==="p2p"?"p2p":h==="topic"||h==="group"?"group":"channel";let v=s.attachments||[],w=v.map(R=>{let q=String(R.uid||"");return{fileId:String(R.fileId||R.file_id||""),uid:q,title:String(R.title||""),fileSize:Number(R.file_size||R.fileSize||0),type:Number(R.t||R.type||0),ctype:R.ctype?String(R.ctype):void 0,inline:!!R.inline,duration:R.duration?Number(R.duration):void 0}});if(w.length===0){let R=Object.keys(s),q=R.some(O=>O.toLowerCase().includes("file")||O.toLowerCase().includes("att")||O.toLowerCase().includes("attach")||O.toLowerCase().includes("media")||O.toLowerCase().includes("image")||O.toLowerCase().includes("audio")),B=String(s.type||""),N=["file","image","audio","video","attachment"].some(O=>B.toLowerCase().includes(O));if(q||N){e?.info(`[parseSocketMessage] \u26A0\uFE0F No attachments parsed but message has file-related fields. type="${B}", keys=${R.join(", ")}`),e?.debug?.("[parseSocketMessage] No attachments found, but message might have file content"),e?.debug?.(`[parseSocketMessage] msg.type="${B}", msg keys: ${R.join(", ")}`);for(let O of R){let V=O.toLowerCase();if(V.includes("file")||V.includes("att")||V.includes("attach")||V.includes("media")||V.includes("image")||V.includes("audio")){let oe=s[O];e?.debug?.(`[parseSocketMessage] Field "${O}": ${JSON.stringify(oe).substring(0,500)}`)}}}}let y="text",k=w[0];if(k){let R=k.title?.split(".").pop()?.toLowerCase();R==="ilbc"?y="audio":["jpg","jpeg","png","gif","bmp","webp"].includes(R||"")?y="image":["mp4","mov","avi","mkv"].includes(R||"")?y="video":y="file"}let C=f;if(w.length>0){let R=[];for(let B of w){let N=B.title?.split(".").pop()?.toLowerCase();N==="ilbc"?R.push(l("attachment.voice",{duration:B.duration||""})):["jpg","jpeg","png","gif","bmp","webp"].includes(N||"")?R.push(l("attachment.image",{title:B.title})):["mp4","mov","avi","mkv"].includes(N||"")?R.push(l("attachment.video",{title:B.title})):R.push(l("attachment.file",{title:B.title}))}let q=R.join(" ");f.trim()?C=`${f}
17
17
  ${q}`:C=q}if(w.length>0){e?.info(`[parseSocketMessage] Parsed ${w.length} attachment(s): ${w.map(q=>`${q.title}(uid=${q.uid||"EMPTY!"})`).join(", ")}`),v[0]&&(e?.debug(`[parseSocketMessage] Raw attachment[0] keys: ${Object.keys(v[0]).join(", ")}`),e?.debug(`[parseSocketMessage] Raw attachment[0]: ${JSON.stringify(v[0])}`));let R=w.filter(q=>!q.uid);R.length>0&&(e?.warn?.(`[parseSocketMessage] \u26A0\uFE0F ${R.length} attachment(s) have empty uid - download will fail!`),v[0]&&e?.warn?.(`[parseSocketMessage] Available fields in raw attachment: ${Object.keys(v[0]).join(", ")}`))}let b,S=s.at_uid;typeof S=="string"&&S&&(S==="all"?b=["all"]:S.includes(",")?b=S.split(",").map(R=>R.trim()).filter(Boolean):b=[S]);let T=b?b.length>0:!1;return{msgId:c,threadId:s.threadId?String(s.threadId):void 0,parentId:s.parentId?String(s.parentId):void 0,fromUid:d,fromName:m||void 0,toUid:String(p.uid||""),chatType:g,chatId:x||(g==="p2p"?d:""),content:C,contentType:y,timestamp:typeof s.time=="number"?s.time:Date.now(),mentioned:T,mentionedUids:b,attachments:w.length>0?w:void 0}}async function Zd(n){let{msg:e,account:o,sessionFilesDir:t,log:i}=n,s=e.attachments?.[0];if(s?.fileId)try{let a=new F(o.lunkrConfig.baseUrl,{apiPath:o.lunkrConfig.apiPath}),r={"Cim.sid":o.sid};for(let v of o.cookie.split(";")){let w=v.trim();if(w.includes("=")){let[y,k]=w.split("=",2);r[y.trim()]=k.trim()}}a.setCookies(r);let c=s.title||`file-${s.fileId}`,u=`${t}/${c}`,p=s.uid||e.peerId,d=`${o.lunkrConfig.baseUrl}/lunkr/f?func=cim.file:getFileData&mode=download&uid=${encodeURIComponent(p)}&mid=${encodeURIComponent(s.fileId)}&sid=${encodeURIComponent(o.sid)}&fallback=false`,m={Cookie:`Cim.sid=${o.sid}; Cim=${r.Cim||""}`},{default:f}=await import("fs"),{default:h}=await import("path"),{httpsGetBuffer:x}=await Promise.resolve().then(()=>(tn(),Ys)),g=await x(d,m);if(g.status!==200){i?.warn?.(`[autoDownload] HTTP ${g.status} for ${c}`);return}if(g.data.length<1e3)try{let v=JSON.parse(g.data.toString("utf-8"));if(v.code&&v.code!=="S_OK"){i?.warn?.(`[autoDownload] API error: ${v.code}`);return}}catch{}return f.mkdirSync(h.dirname(u),{recursive:!0}),f.writeFileSync(u,g.data),i?.info(`[autoDownload] Saved ${c} (${g.data.length} bytes) \u2192 ${u}`),u}catch(a){i?.warn?.(`[autoDownload] Failed: ${a instanceof Error?a.message:String(a)}`);return}}async function em(n){let{msg:e,account:o,sessionKey:t,accountId:i,log:s}=n,a=e.chatType!=="direct",r=a?`group:${e.peerId}`:e.senderId,c=a?"group":"direct",u=e.attachments?.[0],p;u&&(e.contentType==="audio"?p="audio/ilbc":e.contentType==="image"?p=`image/${u.title?.split(".").pop()||"jpeg"}`:e.contentType==="video"?p=`video/${u.title?.split(".").pop()||"mp4"}`:p="application/octet-stream");let d=t,m=Ec(d),f=Fc(d);Pc(d,{workspaceDir:m,filesDir:f,accountId:i});let h;return u&&(h=await Zd({msg:e,account:o,sessionFilesDir:f,log:s})),{Body:e.text,BodyForAgent:e.text,RawBody:e.text,CommandBody:e.text,From:a?`lunkr:group:${e.peerId}`:`lunkr:${e.senderId}`,To:`lunkr:${e.peerId}`,SessionKey:t,AccountId:i,ChatType:c,ConversationLabel:r,SenderName:void 0,SenderId:e.senderId,CommandAuthorized:!0,Provider:"lunkr",Surface:"lunkr",MessageSid:e.externalId,MediaPath:h,MediaType:p,MediaUrl:void 0,Attachments:e.attachments,OriginatingChannel:"lunkr",OriginatingTo:`lunkr:${e.peerId}`,LunkrSessionWorkspaceDir:m,LunkrSessionFilesDir:f,LunkrWorkspaceKey:d}}var Nc={startAccount:async n=>{let{account:e,abortSignal:o,log:t}=n,i=e,s=new Map;t?.info(`[${i.accountId}] Starting Lunkr gateway`);let a=!i.sid;if(i.sid&&(await new F(i.lunkrConfig.baseUrl).checkSessionValid(i.sid)||(t?.warn?.(`[${i.accountId}] Session invalid on startup, will refresh...`),a=!0)),a){t?.info(`[${i.accountId}] No valid session on startup, attempting refresh...`);let g=await he(i.accountId);g.success&&g.session?(i=$n(i,g.session),t?.info(`[${i.accountId}] Session refreshed on startup`)):t?.warn?.(`[${i.accountId}] Session refresh failed on startup: ${g.error}. Will retry when sending messages.`)}let r,c=3,u=5e3,p=12e4,d=0,m=0,f={onMessage:async g=>{if(!g.isBotMention)return;if(Jd(g.externalId)){t?.debug?.(`[${i.accountId}] Skipping duplicate message: ${g.externalId}`);return}let v=g.chatType==="direct"?"DM":"Group";if(t?.info(`[${i.accountId}] [${v}:${g.peerId}] Received msg from ${g.senderId}: ${g.text?.substring(0,50)}...`),t?.debug?.(`[${i.accountId}] Attachments check: count=${g.attachments?.length||0}, contentType=${g.contentType}`),g.attachments&&g.attachments.length>0){let C=g.attachments.map(b=>{let S=b.title?.split(".").pop()?.toLowerCase();return S==="ilbc"?l("attachment.voice_short",{duration:b.duration||"?"}):["jpg","jpeg","png","gif","bmp","webp"].includes(S||"")?l("attachment.image_short",{title:b.title}):["mp4","mov","avi","mkv"].includes(S||"")?l("attachment.video_short",{title:b.title}):l("attachment.file_short",{title:b.title})}).join(", ");t?.info(`[${i.accountId}] [${v}:${g.peerId}] Attachments: ${C}`)}let w=Ac(g,i,t);if(!w.allowed){t?.info(`[${i.accountId}] Message discarded: ${w.reason}`);return}let y=i.role||"standard",k=y==="agent"||y==="standard+agent"&&!g.isFromSelf;if(Yd(g,i)){let C=Qd(g.text);if(C){let b=g.workspaceKey||`${i.selfUid}:${g.peerId}`,S;C==="/help"?S=l("commands.help.text"):(s.set(b,(s.get(b)||0)+1),jc(b),S=l("commands.new.done")),t?.info(`[${i.accountId}] Built-in command ${C} from ${g.senderId}`);try{let T=await Dc(i,{to:g.peerId,chatType:g.chatType,text:S,skipPrefix:k},t);T.account!==i&&(i=T.account)}catch(T){t?.error?.(`[${i.accountId}] Command reply failed: ${T instanceof Error?T.message:String(T)}`)}return}}if(!n.channelRuntime){t?.warn?.(`[${i.accountId}] channelRuntime not available - skipping AI dispatch`);return}try{let C=new Set,b=g.chatType!=="direct",S=n.channelRuntime.routing.buildAgentSessionKey({peerId:g.peerId,channelId:"lunkr-openclaw",accountId:n.accountId}),T=n.channelRuntime.routing.resolveAgentRoute({cfg:n.cfg,channel:"lunkr-openclaw",peer:{kind:b?"group":"direct",id:g.peerId},accountId:n.accountId}),R=g.workspaceKey||T.sessionKey,q=s.get(R)||0,B=q>0?`${R}:r${q}`:R,N=await em({msg:g,account:i,sessionKey:B,accountId:T.accountId,log:t}),V=n.cfg.session?.store;V&&await n.channelRuntime.session.recordInboundSession({storePath:V,sessionKey:N.SessionKey,ctx:N,onRecordError:oe=>{t?.error?.(`[${i.accountId}] Failed to record session: ${String(oe)}`)}}),await n.channelRuntime.reply.dispatchReplyWithBufferedBlockDispatcher({ctx:N,cfg:n.cfg,dispatcherOptions:{deliver:async(oe,pe)=>{let Oe=oe.text??"";if(Oe.trim()){if(pe.kind==="block"){t?.debug?.(`[${i.accountId}] Skipping block chunk (waiting for final)`);return}if(pe.kind==="final"&&C.has(Oe)){t?.debug?.(`[${i.accountId}] Skipping duplicate final reply`);return}pe.kind==="final"&&C.add(Oe),t?.info(`[${i.accountId}] Deliver ${pe.kind} reply to ${g.peerId}: ${Oe.substring(0,50)}...`);try{let Ee=await Dc(i,{to:g.peerId,chatType:g.chatType,text:Oe,skipPrefix:k},t);Ee.account!==i&&(i=Ee.account,t?.info(`[${i.accountId}] Session updated after refresh`))}catch(Ee){t?.error?.(`[${i.accountId}] Failed to send reply: ${Ee instanceof Error?Ee.message:String(Ee)}`)}}},onError:(oe,pe)=>{t?.error?.(`[${i.accountId}] AI ${pe.kind} failed: ${String(oe)}`)}}})}catch(C){t?.error?.(`[${i.accountId}] Message dispatch error: ${C instanceof Error?C.message:String(C)}`)}},onReaction:g=>{t?.debug(`[${i.accountId}] Received reaction: ${g.emoji} on ${g.msgId}`)},onError:g=>{t?.error(`[${i.accountId}] Socket error: ${g.message}`)},onDisconnect:async()=>{if(t?.info(`[${i.accountId}] Socket disconnected`),Pe.delete(i.accountId),o.aborted)return;d++;let g=Math.min(u*Math.pow(2,d-1),p);if(t?.warn?.(`[${i.accountId}] Reconnect attempt ${d}, delay ${g/1e3}s...`),await new Promise(y=>setTimeout(y,g)),o.aborted)return;let v=await he(i.accountId);if(v.success&&v.session){if(i=$n(i,v.session),t?.info(`[${i.accountId}] Session refreshed, reconnecting...`),h=Bo(i,f),await h.connect()){t?.info(`[${i.accountId}] Reconnected with refreshed session`),d=0,m=0,r.socket=h,Pe.set(i.accountId,r);return}t?.warn?.(`[${i.accountId}] Reconnect with refreshed session failed`)}else{let y=v.reason||"rejected";if(t?.warn?.(`[${i.accountId}] Session refresh failed (${y}): ${v.error}`),y==="no_credentials"){t?.error?.(`[${i.accountId}] Missing credentials \u2014 giving up reconnect. Fix config and restart.`);return}if(y==="rejected"&&(m++,m>=c)){t?.error?.(`[${i.accountId}] Server rejected ${m} consecutive refreshes \u2014 giving up. Check apiToken and restart.`);return}}if(o.aborted)return;h=Bo(i,f),await h.connect()?(t?.info(`[${i.accountId}] Reconnected with existing session`),d=0,m=0,r.socket=h,Pe.set(i.accountId,r)):(t?.warn?.(`[${i.accountId}] Reconnect attempt ${d} failed, will retry on next disconnect`),o.aborted||f.onDisconnect())},log:t,autoReconnect:!1},h=Bo(i,f),x=await h.connect();if(!x){t?.warn?.(`[${i.accountId}] Socket connect failed, attempting session refresh...`);let g=await he(i.accountId);g.success&&g.session&&(i=$n(i,g.session),t?.info(`[${i.accountId}] Session refreshed, retrying socket connection...`),h=Bo(i,f),x=await h.connect())}if(!x)throw new Error(l("api.socket_connect_failed",{accountId:i.accountId}));return t?.info(`[${i.accountId}] Lunkr gateway connected`),r={socket:h,connected:!0,startedAt:Date.now()},Pe.set(i.accountId,r),o.addEventListener("abort",()=>{t?.info(`[${i.accountId}] Stopping Lunkr gateway`),h.disconnect(),Pe.delete(i.accountId)}),new Promise(g=>{let v=()=>{o.removeEventListener("abort",w),g(r)},w=()=>{t?.info(`[${i.accountId}] Gateway abort signal received`),v()};o.addEventListener("abort",w),h.onDisconnect(()=>{t?.info(`[${e.accountId}] Socket disconnected`),Pe.delete(e.accountId),v()})})},stopAccount:async n=>{let{account:e,log:o}=n;o?.info(`[${e.accountId}] Stopping Lunkr gateway`);let t=Pe.get(e.accountId);t&&(t.socket.disconnect(),Pe.delete(e.accountId))},logoutAccount:async n=>{let{account:e,log:o}=n;o?.info(`[${e.accountId}] Logging out Lunkr account`);let t=Pe.get(e.accountId);return t&&(t.socket.disconnect(),Pe.delete(e.accountId)),{cleared:!0,loggedOut:!0}}};oo();U();async function Mc(n,e=5e3){let o=Date.now();if(!n)return{ok:!1,error:l("errors.account_not_configured"),elapsedMs:Date.now()-o};if(!n.sid||!n.lunkrConfig){if(n.hasApiToken){let t=await he(n.accountId);if(t.success&&t.session){let i={...n,sid:t.session.sid,lunkrConfig:t.session};return Mc(i,e)}}return{ok:!1,error:l("errors.session_not_configured"),elapsedMs:Date.now()-o}}try{let t=new F(n.lunkrConfig.baseUrl,{apiPath:n.lunkrConfig.apiPath,timeout:e/1e3}),i={"Cim.sid":n.sid};for(let a of n.cookie.split(";")){let r=a.trim();if(r.includes("=")){let[c,u]=r.split("=",2);i[c.trim()]=u.trim()}}t.setCookies(i);let s=await t.checkSessionValid(n.sid);return{ok:s,sessionValid:s,elapsedMs:Date.now()-o}}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t),elapsedMs:Date.now()-o}}}function nm(n){let e=[];for(let o of n){let t=o.accountId??Se;o.configured===!1&&e.push({channel:"lunkr-openclaw",accountId:t,kind:"config",message:l("status.session_not_configured_fix"),fix:l("status.run_login")}),o.lastError&&e.push({channel:"lunkr-openclaw",accountId:t,kind:"runtime",message:l("status.channel_error",{error:o.lastError})});let i=o.probe;i&&!i.ok&&i.sessionValid===!1&&e.push({channel:"lunkr-openclaw",accountId:t,kind:"auth",message:l("errors.session_expired"),fix:l("status.run_login_refresh")})}return e}function om(n){return vs({configured:n.snapshot.configured,running:n.snapshot.running,lastStartAt:n.snapshot.lastStartAt,lastStopAt:n.snapshot.lastStopAt,lastError:n.snapshot.lastError,probe:n.snapshot.probe,lastProbeAt:n.snapshot.lastProbeAt,tokenSource:n.snapshot.configured?"session":null})}function tm(n){let{account:e,runtime:o,probe:t}=n,i=!!((e.sid||e.hasApiToken)&&e.selfUid);return xs({accountId:e.accountId,name:e.name,enabled:e.enabled,configured:i,runtime:o,probe:t})}var Bc={defaultRuntime:{accountId:Se,running:!1,lastStartAt:null,lastStopAt:null,lastError:null},collectStatusIssues:nm,buildChannelSummary:({snapshot:n})=>om({snapshot:n}),probeAccount:async({account:n,timeoutMs:e})=>Mc(n??null,e??5e3),buildAccountSnapshot:({account:n,runtime:e,probe:o})=>tm({account:n,runtime:e,probe:o}),logSelfId:({account:n,includeChannelPrefix:e})=>{console.log(`Self ID: ${e?"lunkr:":""}${n.selfUid}`)},resolveAccountState:({configured:n,enabled:e})=>n?e?"configured":"disabled":"not configured"};U();async function io(n,e){let o=me(n,e);if(!o)throw new Error(l("errors.account_not_configured"));let t=new F(o.lunkrConfig.baseUrl,{apiPath:o.lunkrConfig.apiPath}),i={"Cim.sid":o.sid};for(let s of o.cookie.split(";")){let a=s.trim();if(a.includes("=")){let[r,c]=a.split("=",2);i[r.trim()]=c.trim()}}return t.setCookies(i),{client:t,account:o}}function fi(n){return{kind:"user",id:`lunkr:${n.uid}`,name:n.name??n.uid,email:n.email,avatarUrl:n.avatar}}function Gc(n){return{kind:n.type==="channel"?"channel":"group",id:`lunkr:discussion:${n.gid}`,name:n.name??n.gid,avatarUrl:n.avatar}}async function zc(n,e,o,t){let i=await n.postJson({func:"cim.contacts:search",sid:e,query:{keyword:o,limit:t}});return i.code!=="S_OK"?[]:i.var?.users??[]}async function Kc(n,e){let o=await n.postJson({func:"cim.discussion:list",sid:e});if(o.code!=="S_OK")return[];let t=o.var?.discussions;return t?t.map(i=>({gid:String(i.id??i.gid??""),name:i.name?String(i.name):void 0,memberCount:typeof i.memberCount=="number"?i.memberCount:void 0,avatar:i.avatar?String(i.avatar):void 0,type:i.type??"group"})):[]}async function im(n,e,o,t){let i=await n.postJson({func:"cim.discussion:getMembers",sid:e,query:{gid:o,limit:t}});if(i.code!=="S_OK")return[];let s=i.var?.members;return s?s.map(a=>({uid:String(a.uid??""),name:a.name?String(a.name):void 0,email:a.email?String(a.email):void 0,avatar:a.avatar?String(a.avatar):void 0,department:a.department?String(a.department):void 0})):[]}var Hc={self:async({cfg:n,accountId:e})=>{let o=me(n,e);return o?.selfUid?{kind:"user",id:`lunkr:${o.selfUid}`,name:o.name??o.selfUid}:null},listPeers:async({cfg:n,accountId:e,query:o,limit:t})=>{let{client:i,account:s}=await io(n,e),a=o?.trim()??"",r=t&&t>0?t:20;return a?(await zc(i,s.sid,a,r)).map(fi):[]},listPeersLive:async({cfg:n,accountId:e,query:o,limit:t})=>{let{client:i,account:s}=await io(n,e),a=o?.trim()??"",r=t&&t>0?t:20;return a?(await zc(i,s.sid,a,r)).map(fi):[]},listGroups:async({cfg:n,accountId:e,query:o,limit:t})=>{let{client:i,account:s}=await io(n,e),a=await Kc(i,s.sid),r=a;if(o){let c=o.toLowerCase();r=a.filter(u=>u.name?.toLowerCase().includes(c)||u.gid.toLowerCase().includes(c))}return t&&t>0&&(r=r.slice(0,t)),r.map(Gc)},listGroupsLive:async({cfg:n,accountId:e,query:o,limit:t})=>{let{client:i,account:s}=await io(n,e),a=await Kc(i,s.sid),r=a;if(o){let c=o.toLowerCase();r=a.filter(u=>u.name?.toLowerCase().includes(c)||u.gid.toLowerCase().includes(c))}return t&&t>0&&(r=r.slice(0,t)),r.map(Gc)},listGroupMembers:async({cfg:n,accountId:e,groupId:o,limit:t})=>{let{client:i,account:s}=await io(n,e),a=o.replace(/^lunkr:discussion:/,"").replace(/^lunkr:/,"");return(await im(i,s.sid,a,t??100)).map(fi)}};function Vc(n){let{cfg:e,accountId:o,groupId:t}=n,i=me(e,o);if(!i||!t)return!1;let s=t.replace(/^lunkr:discussion:/,"").replace(/^lunkr:/,"");if(i.botDiscussions[s])return!1;let a=i.config.discussions?.[s];if(a?.requireMention!==void 0)return a.requireMention;let r=s.match(/(#[A-Z])$/)?.[1];return r&&i.config.groupTypeRules?.[r]?.policy==="mentionOnly",!0}function sm(n){let{cfg:e,accountId:o,groupId:t}=n,i=me(e,o);if(!i||!t)return;let s=t.replace(/^lunkr:discussion:/,"").replace(/^lunkr:/,"");if(i.botDiscussions[s])return"Bot discussion - all messages will trigger the bot";let a=i.config.groups??[];if(a.includes(s)||a.includes("*"))return Vc({cfg:e,accountId:o,groupId:t})?"Mention the bot to trigger a response":"Bot will respond to all messages"}function am(n){let{cfg:e,accountId:o,groupId:t}=n;me(e,o)}var gi={resolveRequireMention:Vc,resolveGroupIntroHint:sm,resolveToolPolicy:am};U();var rm={id:"lunkr-openclaw",label:"Lunkr",get selectionLabel(){return l("meta.selection_label")},get detailLabel(){return l("meta.detail_label")},docsPath:"/channels/lunkr",docsLabel:"lunkr",get blurb(){return l("meta.blurb")}},Go={id:"lunkr-openclaw",meta:{...rm,quickstartAllowFrom:!0},capabilities:{chatTypes:["direct","group"],polls:!1,reactions:!0,edit:!0,unsend:!0,reply:!0,effects:!1,groupManagement:!1,threads:!1,media:!0,nativeCommands:!1,blockStreaming:!0},reload:{configPrefixes:["channels.lunkr-openclaw"]},configSchema:hs(Zo),config:Us,security:Os,group:gi,groups:gi,messaging:{normalizeTarget:n=>{let e=n.trim();if(e)return e.replace(/^lunkr:(?:discussion:)?/i,"")},targetResolver:{looksLikeId:n=>{let e=n?.trim();return e?/^#[0-9]+#[UT]$/.test(e)||/^[a-zA-Z0-9_-]+$/.test(e)||/^lunkr:/i.test(e):!1},hint:"<uid|gid>"}},directory:Hc,outbound:kc,status:Bc,gateway:Nc,pairing:{idLabel:"lunkrUserId",normalizeAllowEntry:n=>n.replace(/^lunkr:/i,"")}};mn();zo();fn();import*as ki from"readline";import*as Zc from"readline";mn();U();var yi=class extends Error{constructor(o,t,i){super(o);this.sid=t;this.authType=i;this.name="OtpRequiredError"}};var vi="https://lunkr.coremail.cn",bi="/lunkr/s/json",$x=300*1e3;function el(n){let e={};for(let o of n.split(";")){let[t,i]=o.trim().split("=");t&&i&&(e[t]=i)}return e}async function nl(n,e){try{let o=e?.verbose??!1,t=e?.debug??!1;(o||t)&&console.log(`Discovering server for: ${n.email}`);let[i,s]=await Mn.discoverAvailableServer(n.email);(o||t)&&(console.log(`Found server: ${i.apiUrl}`),console.log(`Auth type: ${s.authType}`),console.log(`RSA sid: ${s.sid}`));let a=new F(i.baseUrl,{apiPath:i.apiPath}),r=ut({device_uuid:e?.deviceUuid||n.deviceUuid,device_name:e?.deviceName||n.deviceName});return t&&console.log(`Device info: ${JSON.stringify(r,null,2)}`),{success:!0,session:await lm(a,n.email,n.password,s,r,i,o,t)}}catch(o){return o instanceof yi?{success:!1,requiresOtp:!0,otpSid:o.sid,error:o.message}:{success:!1,error:o instanceof Error?o.message:String(o)}}}async function lm(n,e,o,t,i,s,a,r=!1){let c={type:t.authType,e:t.rsaE,n:t.rsaN},u=c.type;r&&(console.log(`[Login] authType: ${u}`),console.log(`[Login] RSA e: ${c.e?c.e.substring(0,20)+"...":"(empty)"}`),console.log(`[Login] RSA n: ${c.n?c.n.substring(0,40)+"...":"(empty)"}`));let p;u&&u.toLowerCase()==="rsa"&&c?.e&&c?.n?((a||r)&&console.log("Encrypting password with RSA"),p=nt(o,c.e,c.n),r&&console.log(`[Login] Encrypted password length: ${p.length}`)):(r&&console.log(`[Login] WARNING: Password NOT encrypted (authType=${u})`),p=o);let d=Math.floor(Date.now()/1e3).toString(),m=pt(i.uuid,e,i.friendlyName),f=dt(m),h=mt(m,d,f,"");r&&(console.log(`[Login] timestamp: ${d}`),console.log(`[Login] accessToken: ${m.substring(0,20)}...`),console.log(`[Login] signature: ${h.substring(0,20)}...`));let x={uid:e,password:p,authType:u,device:{uuid:i.uuid,os:i.os,model:i.model,friendlyName:i.friendlyName},locale:"zh_CN",timestamp:d,accessToken:m,signature:h,supportDynamicPwd:!0,supportBind2FA:!0,supportPermDomains:!0,supportSms:1,forceIPCheck:!1,forceCookieCheck:!0,returnCookie:!0,returnMainURL:!1};if(r){let b={...x},S=String(b.password||"");b.password=S.length>10?S.substring(0,20)+`...(length: ${S.length})`:"***",console.log(`[Login] Payload: ${JSON.stringify(b,null,2)}`)}let g=await n.postJson({func:"user:login",sid:t.sid,payload:x,debug:r||a});r&&console.log(`[Login] Response: ${JSON.stringify(g,null,2)}`);let v=g.code,w=g.var||{};if(v==="FA_NEED_VERIFY_CODE"||v==="FA_USER_IN_GRAYLIST"){let b=s.uri||`${s.baseUrl}/coremail/`;throw new j(l("auth.captcha_required",{code:v,uri:b}))}if(v==="FA_NEED_DYNAMIC_PWD"){console.log(`
18
18
  ${l("auth.otp_required")}`);let b={tempSid:t.sid,trans:"login",device:{token:m,secret:f,uuid:i.uuid,friendlyName:i.friendlyName,model:i.model,os:i.os,deviceType:i.deviceType},type:"OTP"},S=await n.postJson({func:"user:triggerSecondAuth",sid:t.sid,payload:b});if(S.code!=="S_OK")throw new j(l("auth.otp_trigger_failed",{code:S.code}));console.log(` ${l("auth.otp_verify_prompt")}`),console.log(` ${l("auth.otp_trust_hint")}`),await um(` ${l("auth.otp_press_enter")}`);let T=await n.postJson({func:"user:querySecondAuthValidateStage",sid:t.sid,payload:{tempSid:t.sid,trans:"login"}});if(T.code!=="S_OK")throw new j(l("auth.otp_query_failed",{code:T.code}));let q=(T.var||{}).stage;if(q!=="VALIDATED")throw new j(l("auth.otp_not_completed",{stage:q}));console.log(` ${l("auth.otp_success")}`),(a||r)&&console.log(`
19
19
  ${l("auth.relogin")}`);let B={uid:e,password:"",authType:u,device:{uuid:i.uuid,os:i.os,model:i.model,friendlyName:i.friendlyName},locale:"zh_CN",timestamp:d,accessToken:m,signature:h,supportDynamicPwd:!0,supportBind2FA:!0,supportPermDomains:!0,supportSms:1,forceIPCheck:!1,forceCookieCheck:!0,returnCookie:!0,returnMainURL:!1},N=await n.postJson({func:"user:login",sid:t.sid,payload:B,debug:r||a});r&&console.log(`[Login] Re-login Response: ${JSON.stringify(N,null,2)}`);let O=N.code,V=N.var||{};if(O!=="S_OK"&&O!=="FA_NEED_ACCESS_SECRET")throw new j(l("auth.relogin_failed",{code:O}));let oe=V.sid;if(!oe)throw new j(l("auth.relogin_no_sid"));let pe=n.cookies.Coremail||"";if(!pe)throw new j(l("auth.relogin_no_cookie"));return(a||r)&&console.log(l("auth.otp_verified_getting_session")),await Xc(oe,pe,e,i,a,r)}if(v!=="S_OK"&&v!=="FA_NEED_ACCESS_SECRET"){let b=String(w.error||w.msg||g.msg||v);throw b.includes("\u5BC6\u7801")||b.toLowerCase().includes("password")||["PASSWORD_ERROR","AUTH_FAILED"].includes(v)?new Nn(`Password error: ${b}`):new j(`Login failed: ${b}`)}let y=w.sid;if(!y)throw new j("Login response missing sid");r&&console.log(`[Login] Client cookies: ${JSON.stringify(n.cookies)}`);let k=n.cookies.Coremail||"";if(!k){let b=Object.keys(n.cookies);throw new j(`Login succeeded but no Coremail cookie received. Available cookies: ${b.join(", ")||"none"}`)}return(a||r)&&(console.log(`Coremail login succeeded, sid: ${y.substring(0,20)}...`),console.log(`Coremail cookie: ${k.substring(0,30)}...`),console.log("Now getting Lunkr session...")),await Xc(y,k,e,i,a,r)}async function Xc(n,e,o,t,i,s){(i||s)&&console.log(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coremail/lunkr-openclaw",
3
- "version": "1.1.5",
3
+ "version": "1.1.6",
4
4
  "description": "OpenClaw Lunkr/Coremail channel plugin",
5
5
  "license": "MIT",
6
6
  "type": "module",