UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 2.12 kB
import"./src-BTTzpNjb.mjs"; //!src/gateway/openclaw-id/mailbox-reader.ts const BACKOFF_INITIAL_MS=5e3;const BACKOFF_MAX_MS=6e4;async function applyMailboxMessage(e,t,n=async()=>{},r){const i=e.payload;const a=[];const record=async e=>{a.push(e);await n(e)};if(i.kind===`invite_redemption`){if(e.from.account_id===null){await record({ok:false,code:`audience_mismatch`,detail:`redeeming account is not the invite audience`});return a}await record(await t.redeem(i.redemption,{account_id:e.from.account_id,email:e.from.email,display_name:e.from.display_name,location_hint:e.location_hint}))}else if(i.kind===`node_redemption`)await record(await t.redeemNode(i.redemption));else if(i.kind===`revocation`)await record(await t.submit(i.revocation));else if(i.kind===`root_statement`)for(const e of i.statements){if(r?.aborted)break;await record(await t.submit(e))}else await record({ok:false,code:`unsupported`,detail:`mailbox kind ${i.kind} is not for the Gateway`});return a}function startMailboxReader(e){const t=new AbortController;let n=e.cursor;const loop=async()=>{let r=BACKOFF_INITIAL_MS;let i=false;while(!t.signal.aborted)try{const a=await e.client.receiveMail(e.clawId,n,30,t.signal);if(t.signal.aborted)return;if(!i){i=true;e.onConnected?.()}for(const n of a.messages){if(t.signal.aborted)return;await applyMailboxMessage(n,e.sink,async t=>{if(!t.ok){const r=n.payload.kind===`invite_redemption`&&t.code===`invite_used`?`: ${t.detail}`:``;e.log.warn(`openclaw-id: mailbox ${n.payload.kind} refused (${t.code})${r}`);await e.onRefused?.(n,t).catch(t=>e.log.warn(`openclaw-id: mailbox refusal handling failed: ${String(t)}`))}if(t.ok)await e.onEffects(t.events)},t.signal)}if(a.messages.length>0&&!t.signal.aborted){await e.client.ackMail(e.clawId,a.cursor);await e.sink.saveCursor(a.cursor)}n=a.cursor;r=BACKOFF_INITIAL_MS}catch(n){if(t.signal.aborted)return;i=false;e.log.warn(`openclaw-id: mailbox read failed: ${n instanceof Error?n.message:String(n)}`);await new Promise(e=>{setTimeout(e,r).unref()});r=Math.min(BACKOFF_MAX_MS,r*2)}};loop();return{stop(){t.abort()}}}export{applyMailboxMessage,startMailboxReader};