UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

8 lines โ€ข 7.51 kB
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{m as normalizeTrimmedStringList}from"./string-normalization-D_oBUpO3.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{n as sha256Hex}from"./node-crypto-DPk8agfR.mjs";import{i as listDevicePairing}from"./device-pairing-DUQvqwi7.mjs";import"./string-coerce-runtime-BYDH9Quw.mjs";import"./error-runtime-DW-sj0iq.mjs";import"./device-bootstrap-CN1VfSZm.mjs";import{a as DEVICE_PAIR_NOTIFY_SUBSCRIBER_NAMESPACE,i as DEVICE_PAIR_NOTIFY_SUBSCRIBER_MAX_ENTRIES,n as DEVICE_PAIR_NOTIFY_SEEN_REQUEST_MAX_ENTRIES,o as notifySubscriberStoreKey,r as DEVICE_PAIR_NOTIFY_SEEN_REQUEST_NAMESPACE,t as DEVICE_PAIR_NOTIFY_MAX_SEEN_AGE_MS}from"./notify-state-CWeb3YDA.mjs";import{randomUUID}from"node:crypto"; //!extensions/device-pair/notify.ts const NOTIFY_POLL_INTERVAL_MS=1e4;let wakeNotifier;async function writeNotifyState(e){try{return await e()}finally{wakeNotifier?.()}}function formatStringList(e){return normalizeTrimmedStringList(e).join(`, `)||`none`}function formatRoleList(e){return normalizeOptionalString(e.role)??formatStringList(e.roles)}function formatPendingRequests(e){if(e.length===0)return`No pending device pairing requests.`;const t=[`Pending device pairing requests:`];for(const n of e){const e=normalizeOptionalString(n.displayName)||n.deviceId;const r=normalizeOptionalString(n.platform);const i=normalizeOptionalString(n.remoteIp);const a=[`- ${n.requestId}`,e?`name=${e}`:null,r?`platform=${r}`:null,`role=${formatRoleList(n)}`,`scopes=${formatStringList(n.scopes)}`,i?`ip=${i}`:null].filter(Boolean);t.push(a.join(` ยท `))}return t.join(` `)}function openNotifySubscriberStore(e){return e.runtime.state.openKeyedStoreV2({namespace:DEVICE_PAIR_NOTIFY_SUBSCRIBER_NAMESPACE,maxEntries:DEVICE_PAIR_NOTIFY_SUBSCRIBER_MAX_ENTRIES})}function resolveNotifyTarget(e){const t=normalizeOptionalString(e.senderId)||normalizeOptionalString(e.from)||normalizeOptionalString(e.to)||``;if(!t)return null;return{to:t,...e.accountId?{accountId:e.accountId}:{},...e.messageThreadId!=null?{messageThreadId:e.messageThreadId}:{}}}async function registerNotifySubscriber(e){const t=e.assertCurrent;const n=openNotifySubscriberStore(e.api);const r=notifySubscriberStoreKey(e.target);const i=await n.lookup(r);if(!e.refresh&&i?.mode===e.mode)return false;await writeNotifyState(()=>n.register(r,{...e.target,mode:e.mode,addedAtMs:Date.now(),armId:randomUUID()},{assertCurrent:t}));return true}function requestTimestampMs(e){if(typeof e.ts!==`number`||!Number.isFinite(e.ts))return null;const t=Math.trunc(e.ts);return t>0?t:null}function shouldNotifySubscriberForRequest(e,t){if(e.mode!==`once`)return true;const n=requestTimestampMs(t);if(n==null)return false;return n>=e.addedAtMs}async function notifyPendingPairingRequests(e){const t=openNotifySubscriberStore(e.api);const n=e.api.runtime.state.openKeyedStore({namespace:DEVICE_PAIR_NOTIFY_SEEN_REQUEST_NAMESPACE,maxEntries:DEVICE_PAIR_NOTIFY_SEEN_REQUEST_MAX_ENTRIES,defaultTtlMs:DEVICE_PAIR_NOTIFY_MAX_SEEN_AGE_MS});const[r,i]=await Promise.all([t.entries(),n.entries()]);if(r.length===0&&i.length===0)return false;const a=await listDevicePairing();const o=r.toSorted((e,t)=>e.value.addedAtMs-t.value.addedAtMs);const s=a.pending;const c=Date.now();const l=new Set(s.map(e=>e.requestId));const u=/* @__PURE__ */ new Set;for(const e of i){const t=normalizeOptionalString(e.value.requestId);const r=e.value.notifiedAtMs;if(!t||!Number.isFinite(r)||r<=0||!l.has(t)||c-r>864e5){await writeNotifyState(()=>n.delete(e.key));continue}u.add(t)}if(o.length>0){const r=/* @__PURE__ */ new Set;for(const i of s){if(u.has(i.requestId))continue;const a=normalizeOptionalString(i.displayName)||i.deviceId;const s=normalizeOptionalString(i.platform);const l=normalizeOptionalString(i.remoteIp);const d=formatRoleList(i);const f=formatStringList(i.scopes);const p=[`๐Ÿ“ฒ New device pairing request`,`ID: ${i.requestId}`,`Name: ${a}`,...s?[`Platform: ${s}`]:[],`Role: ${d}`,`Scopes: ${f}`,...l?[`IP: ${l}`]:[],``,`Approve: /pair approve ${i.requestId}`,`List pending: /pair pending`].join(` `);let m=false;for(const n of o){if(r.has(n.key))continue;const a=(await e.api.runtime.channel.outbound.loadAdapter(`telegram`))?.sendText;if(!a){e.api.logger.warn(`device-pair: telegram outbound adapter unavailable for pairing notifications`);continue}const o=await t.observe(n.key);const s=o.value;if(!s||!shouldNotifySubscriberForRequest(s,i))continue;try{await a({cfg:e.api.config,to:s.to,text:p,...s.accountId?{accountId:s.accountId}:{},...s.messageThreadId!=null?{threadId:s.messageThreadId}:{}})}catch(t){e.api.logger.warn(`device-pair: failed to send pairing notification to ${s.to}: ${formatErrorMessage(t)}`);continue}m=true;if(s.mode===`once`){r.add(n.key);await writeNotifyState(()=>t.compareAndApply(n.key,o.comparison,{operation:`delete`,action:`delete`}))}}if(m){await writeNotifyState(()=>n.register(sha256Hex(i.requestId),{requestId:i.requestId,notifiedAtMs:c},{ttlMs:DEVICE_PAIR_NOTIFY_MAX_SEEN_AGE_MS}));u.add(i.requestId)}}}return true}async function armPairNotifyOnce(e){if(e.ctx.channel!==`telegram`)return false;const t=resolveNotifyTarget(e.ctx);if(!t)return false;await registerNotifySubscriber({api:e.api,target:t,mode:`once`,refresh:true,assertCurrent:e.ctx.assertOwnerCurrent});return true}async function handleNotifyCommand(e){const t=e.ctx.assertOwnerCurrent;if(e.ctx.channel!==`telegram`)return{text:`Pairing notifications are currently supported only on Telegram.`};const n=resolveNotifyTarget(e.ctx);if(!n)return{text:`Could not resolve Telegram target for this chat.`};const r=openNotifySubscriberStore(e.api);const i=notifySubscriberStoreKey(n);if(e.action===`on`||e.action===`enable`){await registerNotifySubscriber({api:e.api,target:n,mode:`persistent`,refresh:false,assertCurrent:t});return{text:`โœ… Pair request notifications enabled for this Telegram chat. I will ping here when a new device pairing request arrives.`}}if(e.action===`off`||e.action===`disable`){await writeNotifyState(()=>r.delete(i,{assertCurrent:t}));return{text:`โœ… Pair request notifications disabled for this Telegram chat.`}}if(e.action===`once`||e.action===`arm`){await armPairNotifyOnce({api:e.api,ctx:e.ctx});return{text:`โœ… One-shot pairing notification armed for this Telegram chat. I will notify on the next new pairing request, then auto-disable.`}}if(e.action===`status`||e.action===``){const[e,n,a]=await Promise.all([r.lookup(i),r.count(),listDevicePairing()]);const o=Boolean(e);t?.();const s=e?.mode??`off`;return{text:[`Pair request notifications: ${o?`enabled`:`disabled`} for this chat.`,`Mode: ${s}`,`Subscribers: ${n}`,`Pending requests: ${a.pending.length}`,``,`Use /pair notify on|off|once`].join(` `)}}return{text:`Usage: /pair notify on|off|once|status`}}function startPairingNotifier(e,t){if(t.signal.aborted)return;let n=false;let r=false;let i=false;function scheduleNext(){if(t.signal.aborted||n||r)return;n=true;t.schedule({id:`notifications`,delayMs:NOTIFY_POLL_INTERVAL_MS,run:async()=>{n=false;r=true;i=false;let t=true;try{t=await notifyPendingPairingRequests({api:e})}catch(t){e.logger.warn(`device-pair: notify poll failed: ${formatErrorMessage(t)}`)}finally{r=false;if(t||i)scheduleNext()}}})}wakeNotifier=()=>{if(r)i=true;else scheduleNext()};t.signal.addEventListener(`abort`,()=>{wakeNotifier=void 0},{once:true});scheduleNext()}export{startPairingNotifier as i,formatPendingRequests as n,handleNotifyCommand as r,armPairNotifyOnce as t};