openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
11 lines • 24 kB
JavaScript
import{t as toStringifiedError}from"./stringified-error-B2ELAgdP.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{d as sleepWithAbort}from"./src-De06gkOi.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{c as redactSensitiveText}from"./redact-BT59pdZ_.mjs";import{n as createAsyncLock}from"./json-files-BBQ_0Np0.mjs";import{t as captureEffectAuthority}from"./effect-authority-CpQjcEYQ.mjs";import{n as buildTimeoutAbortSignal}from"./fetch-timeout-ByCuX83h.mjs";import{g as readProviderTextResponse,h as readProviderJsonResponse}from"./provider-http-errors-CWZQ78Qm.mjs";import"./string-coerce-runtime-BYDH9Quw.mjs";import"./state-paths-CQWnUQJM.mjs";import"./extension-shared--VNeNF-V.mjs";import"./logging-core-CC7KLfEO.mjs";import{t as WebSocket}from"./websocket-runtime-CpCoIxKG.mjs";import"./error-runtime-DW-sj0iq.mjs";import"./fetch-runtime-BnxPLWBI.mjs";import"./runtime-env-Qb8DG6sI.mjs";import"./async-lock-runtime-ohV_CILK.mjs";import"./channel-secret-basic-runtime-CAWk-hCB.mjs";import"./provider-http-D0sVd8r_.mjs";import{C as utf8ToBytes,n as sha256Hex}from"./canonical-DsNGLZ3r.mjs";import"./audit-state-format-TlRRP96X.mjs";import"./pipeline-D5CsuXRG.mjs";import{O as signDeviceRequest,w as fingerprint}from"./state-format-0Qjzduzr.mjs";import"./envelope-wKiS-TmF.mjs";import{a as assertPinnedModel,i as assertGuardRules,n as admitGuardAdapter,s as guardInstructions}from"./guard-C1kFJuP6.mjs";import{i as normalizeReefTarget}from"./config-schema-C4_lwVNs.mjs";import{a as resolveLegacyReefStateDir}from"./doctor-state-paths-BZpEiSYd.mjs";import fs from"node:fs/promises";import os from"node:os";
//!extensions/reef/protocol/guard-adapters.ts
const verdictSchema={type:`object`,additionalProperties:false,properties:{decision:{type:`string`,enum:[`allow`,`deny`,`review`]},category:{type:`string`},reason:{type:`string`},policyVersion:{type:`string`}},required:[`decision`,`category`,`reason`,`policyVersion`]};const OPENAI_DATED_MODEL_ID=/-(?:\d{8}|\d{4}-\d{2}-\d{2})$/;const OPENAI_DATED_MODEL_SUFFIX=/^-(?:\d{8}|\d{4}-\d{2}-\d{2})$/;function matchesOpenAiPinnedModel(e,t){if(e===void 0)return false;if(e===t)return true;return!OPENAI_DATED_MODEL_ID.test(t)&&e.startsWith(t)&&OPENAI_DATED_MODEL_SUFFIX.test(e.slice(t.length))}function createOpenAiGuard(e){assertPinnedModel(e.pinnedModel);assertGuardRules(e.rules);const t={providerId:`openai`,pinnedModel:e.pinnedModel,async classifyRaw(t,n){const r=await parseJsonResponse(await e.fetch(`https://api.openai.com/v1/responses`,{method:`POST`,signal:n,headers:{"content-type":`application/json`,authorization:`Bearer ${e.apiKey}`},body:JSON.stringify({model:e.pinnedModel,instructions:instructionFor(t,e.rules),input:JSON.stringify(t),store:false,background:false,tools:[],text:{format:{type:`json_schema`,name:`reef_guard_verdict`,strict:true,schema:verdictSchema}}})}));if(!isRecord(r)||typeof r.model!==`string`||r.model!==e.pinnedModel||r.status!==`completed`||!Array.isArray(r.output))throw new Error(`invalid OpenAI guard response`);const i=[];for(const e of r.output){if(!isRecord(e)||e.type!==`message`||!Array.isArray(e.content))continue;for(const t of e.content)if(isRecord(t)&&t.type===`output_text`&&typeof t.text===`string`)i.push(t.text)}if(i.length!==1)throw new Error(`guard must return one OpenAI output object`);return attachProviderModel(parseStrictJson(i[0],true),r.model)}};return admitGuardAdapter(t,e.timeoutMs)}function createHostOpenAiGuard(e){assertPinnedModel(e.pinnedModel);assertGuardRules(e.rules);const t={providerId:`openai`,pinnedModel:e.pinnedModel,async classifyRaw(t,n){const r=await e.complete({systemPrompt:`${instructionFor(t,e.rules)} The object must exactly match this schema: ${JSON.stringify(verdictSchema)}`,input:JSON.stringify(t),maxTokens:512,responseFormat:{type:`json_schema`,json_schema:{name:`reef_guard_verdict`,strict:true,schema:verdictSchema}},signal:n});if(r.provider!==`openai`||r.model!==e.pinnedModel||!matchesOpenAiPinnedModel(r.responseModel,e.pinnedModel)||r.stopReason!==`stop`)throw new Error(`invalid host OpenAI guard response`);return attachProviderModel(parseStrictJson(r.text,true),e.pinnedModel)}};return admitGuardAdapter(t,e.timeoutMs)}function createAnthropicGuard(e){assertPinnedModel(e.pinnedModel);assertGuardRules(e.rules);const t={providerId:`anthropic`,pinnedModel:e.pinnedModel,async classifyRaw(t,n){const r=await parseJsonResponse(await e.fetch(`https://api.anthropic.com/v1/messages`,{method:`POST`,signal:n,headers:{"content-type":`application/json`,"x-api-key":e.apiKey,"anthropic-version":`2023-06-01`},body:JSON.stringify({model:e.pinnedModel,max_tokens:512,system:`${instructionFor(t,e.rules)} The object must exactly match this schema: ${JSON.stringify(verdictSchema)}`,output_config:{format:{type:`json_schema`,schema:verdictSchema}},messages:[{role:`user`,content:JSON.stringify(t)}]})}));if(!isRecord(r)||typeof r.model!==`string`||r.model!==e.pinnedModel||!Array.isArray(r.content)||r.stop_reason!==`end_turn`)throw new Error(`invalid Anthropic guard response`);if(r.content.length!==1)throw new Error(`invalid Anthropic guard content`);const i=r.content[0];if(!isRecord(i)||i.type!==`text`||typeof i.text!==`string`)throw new Error(`missing Anthropic guard output`);return attachProviderModel(parseStrictJson(i.text,true),r.model)}};return admitGuardAdapter(t,e.timeoutMs)}function instructionFor(e,t){return`${guardInstructions(e.direction,t)} Set policyVersion to exactly ${JSON.stringify(e.policyVersion)}.`}function attachProviderModel(e,t){if(!isRecord(e)||Object.hasOwn(e,`model`))throw new Error(`invalid model guard verdict`);return{...e,model:t}}async function parseJsonResponse(e){if(!e.ok){await e.body?.cancel().catch(()=>void 0);throw new Error(`guard HTTP ${e.status}`)}return parseStrictJson(await readProviderTextResponse(e,`Reef guard response`,{maxBytes:262144}))}function parseStrictJson(e,t=false){const n=e.trim();if(!n.startsWith(`{`)||!n.endsWith(`}`))throw new Error(`guard returned non-object JSON`);if(t&&hasDuplicateKeys(n))throw new Error(`guard returned duplicate JSON keys`);return JSON.parse(n)}function hasDuplicateKeys(e){const t=/* @__PURE__ */ new Set;for(let n=0;n<e.length;n++){if(e[n]!==`"`)continue;const r=n;for(n++;n<e.length;n++)if(e[n]===`\\`)n++;else if(e[n]===`"`)break;let i=n+1;while(/\s/.test(e[i]??``))i++;if(e[i]!==`:`)continue;const a=JSON.parse(e.slice(r,n+1));if(t.has(a))return true;t.add(a)}return false}
//!extensions/reef/src/transport-errors.ts
function redactReefRelayErrorMessage(e,t){let n=e;for(const e of t)if(e.length>0)n=n.replaceAll(e,`<redacted>`);return redactSensitiveText(n,{mode:`tools`})}
//!extensions/reef/src/transport.ts
const REEF_RELAY_JSON_MAX_BYTES=16777216;const REEF_RELAY_ERROR_JSON_MAX_BYTES=65536;const REEF_RELAY_ERROR_CODE_PATTERN=/^[a-z][a-z0-9_]{0,127}$/;const REEF_RELAY_WEBSOCKET_MAX_PAYLOAD_BYTES=65536;const REEF_INBOX_LIVE_BUFFER_MAX_ENTRIES=256;const REEF_INBOX_REST_PAGE_SIZE=200;const REEF_WS_HANDSHAKE_MS=3e4;const REEF_INBOX_KEEPALIVE_MS=45e3;const REEF_RELAY_REQUEST_TIMEOUT_MS=15e3;var ReefRelayError=class extends Error{constructor(e,t,n){super(t);this.status=e;this.code=n;this.name=`ReefRelayError`}};var ReefProtocolCompatibilityError=class extends ReefRelayError{constructor(e,t,n,r){super(e,r,t);this.upgradeRequired=n;this.name=`ReefProtocolCompatibilityError`}};var ReefRelayUnavailableError=class extends Error{constructor(e){super(e instanceof Error?e.message:String(e),{cause:e});this.name=`ReefRelayUnavailableError`}};function isDefinitiveReefRegistrationFailure(e){return e instanceof ReefRelayError&&e.status>=400&&e.status<500&&e.status!==408&&e.status!==429}function isRetryableReefRelayFailure(e){if(e instanceof ReefRelayError)return e.status===408||e.status===429||e.status>=500;return e instanceof ReefRelayUnavailableError||e instanceof Error&&e.name===`TimeoutError`}function isReefOwnershipRejection(e){return e instanceof ReefRelayError&&e.message===`unknown_handle`}async function readReefRelaySuccessJson(e,t){try{return await readProviderJsonResponse(e,`reef.relay`,{maxBytes:REEF_RELAY_JSON_MAX_BYTES})}catch(e){if(t?.aborted)throw t.reason;if(e instanceof TypeError)throw new ReefRelayUnavailableError(e);throw e}}var ReefTransportClient=class{constructor(e,t,n,r=fetch,i=()=>Math.floor(Date.now()/1e3),a=REEF_RELAY_REQUEST_TIMEOUT_MS){this.relayUrl=e;this.handle=t;this.keys=n;this.fetcher=r;this.clock=i;this.requestTimeoutMs=a;this.lastTs=0}async authStart(e){return await this.unsigned(`POST`,`/v1/auth/start`,{email:e})}async authComplete(e){return await this.unsigned(`POST`,`/v1/auth/complete`,{token:e},{},[e])}async createHandle(e,t){return await this.unsigned(`POST`,`/v1/handles`,{handle:this.handle,ed25519_pub:this.keys.signing.publicKey,x25519_pub:this.keys.encryption.publicKey,request_policy:t},{authorization:`Bearer ${e}`},[e])}listOwnHandles(e){return this.unsigned(`GET`,`/v1/handles`,void 0,{authorization:`Bearer ${e}`},[e])}mintFriendCode(e){return this.signed(`POST`,`/v1/friend-codes`,void 0,e)}requestFriend(e,t,n){return this.signed(`POST`,`/v1/friends/request`,t?{to:e,code:t}:{to:e},n,t?[t]:[])}async respondFriend(e,t,n){const r={peer:e.peer,accept:t,expected_key_epoch:e.key_epoch,expected_ed25519_pub:e.ed25519_pub,expected_x25519_pub:e.x25519_pub};let i;try{i=await this.signed(`POST`,`/v1/friends/respond`,r,n)}catch(e){if(e instanceof ReefRelayError){if(e.status===400&&e.code===`invalid_request`)throw new ReefProtocolCompatibilityError(400,e.code,`reef-relay`,`The Reef relay is likely incompatible or outdated. Update OpenClaw and the Reef relay together, then approve the fresh pairing challenge again.`);if(e.status===409&&e.code===`client_upgrade_required`)throw new ReefProtocolCompatibilityError(409,e.code,`openclaw-client`,`OpenClaw is outdated for this Reef relay. Update OpenClaw, then approve the fresh pairing challenge again.`)}throw e}const a=t?`active`:`blocked`;if(!isRecord(i)||i.peer!==e.peer||i.status!==a)throw new Error(`invalid Reef relay friendship response`);return{peer:e.peer,status:a}}listFriends(e){return this.signed(`GET`,`/v1/friends`,void 0,e)}removeFriend(e,t){return this.signed(`DELETE`,`/v1/friends/${encodeURIComponent(e)}`,void 0,t)}sendEnvelope(e,t,n,r){return this.signed(`POST`,`/v1/mail/${encodeURIComponent(e)}`,t,n,[],r)}acknowledge(e,t,n){return this.signed(`POST`,`/v1/mail/${encodeURIComponent(e)}/ack`,{id:t,receipt:n})}pull(e,t){return this.signed(`GET`,`/v1/mail?after=${e}`,void 0,t)}websocketUrl(){const e=`/v1/mail/ws`;const t=this.auth(e,/* @__PURE__ */ new Uint8Array,`GET`);const n=new URL(e,this.relayUrl);n.protocol=n.protocol===`https:`?`wss:`:`ws:`;n.searchParams.set(`handle`,this.handle);n.searchParams.set(`ts`,String(t.ts));n.searchParams.set(`sig`,t.signature);return n.toString()}async signed(e,t,n,r,i=[],a){const o=n===void 0?/* @__PURE__ */ new Uint8Array:utf8ToBytes(JSON.stringify(n));const s=this.auth(t,o,e);return await this.request(e,t,o,{"x-reef-handle":this.handle,"x-reef-ts":String(s.ts),"x-reef-sig":s.signature},r,[s.signature,...i],a)}auth(e,t,n){const r=Math.max(this.clock(),this.lastTs+1);this.lastTs=r;return{ts:r,signature:signDeviceRequest({method:n.toUpperCase(),path:e,ts:r,bodySha256:sha256Hex(t)},this.keys.signing.secretKey)}}async unsigned(e,t,n,r={},i=[]){const a=n===void 0?/* @__PURE__ */ new Uint8Array:utf8ToBytes(JSON.stringify(n));return await this.request(e,t,a,r,void 0,i)}async request(e,t,n,r,i,a=[],o){const s=captureEffectAuthority();const c=new URL(t,this.relayUrl).toString();const l=buildTimeoutAbortSignal({timeoutMs:this.requestTimeoutMs,signal:i,operation:`reef.relay`,url:c});try{let t;let i=false;try{const initiate=()=>{l.signal?.throwIfAborted();o?.();i=true;return this.fetcher(c,{method:e,headers:{...r,...n.length?{"content-type":`application/json`}:{}},...n.length?{body:n}:{},signal:l.signal})};t=await s.initiate(initiate)}catch(e){if(!i)throw e;if(l.signal?.aborted)throw l.signal.reason;throw new ReefRelayUnavailableError(e)}if(!t.ok){let e=`relay HTTP ${t.status}`;let n;try{const r=await readProviderJsonResponse(t,`reef.relay.error`,{maxBytes:REEF_RELAY_ERROR_JSON_MAX_BYTES});if(isRecord(r)&&typeof r.error===`string`&&r.error){e=redactReefRelayErrorMessage(r.error,a);if(REEF_RELAY_ERROR_CODE_PATTERN.test(r.error))n=r.error}}catch{if(l.signal?.aborted)throw l.signal.reason}throw new ReefRelayError(t.status,e,n)}if(t.status===204)return;return await readReefRelaySuccessJson(t,l.signal)}finally{l.cleanup()}}};var ReefInboxEntryParkedError=class extends Error{constructor(e){super(e);this.name=`ReefInboxEntryParkedError`}};function createReefWebSocket(e,t={}){return new WebSocket(e,{maxPayload:REEF_RELAY_WEBSOCKET_MAX_PAYLOAD_BYTES,handshakeTimeout:t.handshakeTimeoutMs??REEF_WS_HANDSHAKE_MS})}var ReefInboxConnection=class{constructor(e,t,n,r={}){this.client=e;this.onEntries=t;this.webSocketFactory=n;this.options=r;this.processing=Promise.resolve();this.stopped=false;this.parked=false;this.reconciledThrough=0;this.processedAboveCursor=/* @__PURE__ */ new Set;const i=r.initialCursor??0;if(!Number.isSafeInteger(i)||i<0)throw new Error(`invalid Reef inbox cursor`);this.cursor=i}async start(e){let t=250;for(;;){if(this.stopped||e?.aborted){await this.processing;return}try{await this.live(e,()=>{t=250})}catch(n){this.options.onError?.(toStringifiedError(n));await sleepWithAbort(t,e).catch(()=>{});t=Math.min(t*2,3e4)}}}stop(){this.stopped=true}async drain(e){while(true){e?.throwIfAborted();const t=await this.client.pull(this.cursor,e);e?.throwIfAborted();if(!Number.isSafeInteger(t.cursor)||t.cursor<this.cursor)throw new Error(`invalid Reef relay inbox cursor`);const n=this.cursor;const r=await this.processEntries(t.entries,t.cursor,e);e?.throwIfAborted();if(!t.entries.length||this.cursor===n){this.parked=r;return}}}async processEntries(e,t,n){let r=0;for(const t of e){if(!Number.isSafeInteger(t.seq)||t.seq<1)throw new Error(`invalid Reef relay inbox sequence`);r=Math.max(r,t.seq)}if(t!==void 0&&e.length>0&&t!==r)throw new Error(`Reef relay inbox cursor does not match its entries`);const i=e.toSorted((e,t)=>e.seq-t.seq);let a=t===void 0&&this.parked;for(const e of i){if(e.seq<=this.cursor||t===void 0&&e.seq<=this.reconciledThrough)continue;n?.throwIfAborted();if(!this.processedAboveCursor.has(e.seq))try{await this.onEntries([e])}catch(e){if(e instanceof ReefInboxEntryParkedError){this.parked=a=true;continue}throw e}if(a)this.processedAboveCursor.add(e.seq);else await this.advanceCursor(e.seq)}if(t!==void 0){const e=new Set(i.map(e=>e.seq));this.reconciledThrough=Math.max(this.reconciledThrough,t);for(const n of this.processedAboveCursor)if((n<=t||i.length<REEF_INBOX_REST_PAGE_SIZE)&&!e.has(n)){this.processedAboveCursor.delete(n);this.reconciledThrough=Math.max(this.reconciledThrough,n)}if(i.length===0)await this.advanceCursor(this.reconciledThrough)}return a}async poll(e){if(this.stopped||e?.aborted)return;await this.serialize(()=>this.drain(e))}async advanceCursor(e){if(e<=this.cursor)return;await this.options.persistCursor?.(e);if(e<=this.cursor)return;this.cursor=e;for(const t of this.processedAboveCursor)if(t<=e)this.processedAboveCursor.delete(t)}serialize(e){const t=this.processing.then(e);this.processing=t.catch(()=>{});return t}live(e,t){return new Promise((n,r)=>{const i=this.client.websocketUrl();const a=new URL(i).searchParams.get(`sig`)??``;const o=this.webSocketFactory(i);const s=new Promise(e=>{o.addEventListener(`close`,()=>e())});const c=new AbortController;let l=false;let u=false;let d=false;let f=false;let p=false;let m=false;let h=false;let g;const _=[];const abortListener=()=>{if(l)return;d=true;markDisconnected();o.terminate();this.processing.then(()=>finish(),()=>finish())};const finish=t=>{if(l)return;l=true;if(g!==void 0)clearInterval(g);e?.removeEventListener(`abort`,abortListener);s.then(()=>t?r(t):n())};const markDisconnected=()=>{if(u)return;u=true;_.length=0;c.abort();this.options.onState?.(`disconnected`)};const disconnect=e=>{if(l)return;markDisconnected();if(d)return;finish(e);if(e)o.terminate()};const pump=()=>{if(u||!f||m||!p&&_.length===0)return;m=true;this.serialize(async()=>{if(u)return;if(p){p=false;await this.drain(c.signal);t?.()}while(_.length>0){if(u)return;const e=_.shift();if(!e)return;await this.processEntries([e],void 0,c.signal)}}).then(()=>{m=false;pump()},e=>{m=false;if(!u)disconnect(toStringifiedError(e))})};e?.addEventListener(`abort`,abortListener,{once:true});o.addEventListener(`open`,()=>{if(u)return;f=true;p=true;g=setInterval(()=>{if(u||l)return;if(h){disconnect(/* @__PURE__ */ new Error(`reef inbox keepalive timed out`));return}h=true;try{o.send(`ping`)}catch(e){disconnect(toStringifiedError(e))}},REEF_INBOX_KEEPALIVE_MS);g.unref?.();this.options.onState?.(`connected`);pump()});o.addEventListener(`message`,e=>{if(String(e.data)===`pong`){h=false;return}try{const t=JSON.parse(String(e.data));if(t.type!==`entry`||!t.entry)return;if(_.length>=REEF_INBOX_LIVE_BUFFER_MAX_ENTRIES){disconnect(/* @__PURE__ */ new Error(`Reef inbox live buffer overflow; reconnecting for REST recovery`));return}_.push(t.entry);pump()}catch(e){disconnect(toStringifiedError(e))}});o.addEventListener(`close`,e=>{if(d||l)return;disconnect(reefInboxCloseError(e,[a]))});o.addEventListener(`error`,e=>disconnect(new Error(e.message?.trim()||`reef inbox socket error`)));if(e?.aborted)abortListener()})}};function reefInboxCloseError(e,t=[]){const n=Number.isInteger(e.code)?` code=${e.code}`:``;const r=e.reason?.trim()?` reason=${redactReefRelayErrorMessage(e.reason.trim(),t)}`:``;return/* @__PURE__ */ new Error(`reef inbox socket closed unexpectedly${n}${r}`)}
//!extensions/reef/src/friends.ts
function keysChanged(e,t){return e.keyEpoch!==t.key_epoch||e.ed25519PublicKey!==t.ed25519_pub||e.x25519PublicKey!==t.x25519_pub}var ReefFriendManager=class{#e=createAsyncLock();constructor(e,t,n,r){this.transport=e;this.trust=t;this.pairing=n;this.authoritySignal=r}mintCode(e){return this.#r(t=>{e?.();return this.transport.mintFriendCode(t)})}request(e,t,n){return this.#r(async r=>{const i=normalizeReefTarget(e);if(!i)throw new Error(`Invalid Reef peer handle: ${e}`);n?.();const a=await this.trust.beginRequest(i,Date.now(),n);try{let e=false;let o;try{r?.throwIfAborted();n?.();e=true;o=await this.transport.requestFriend(i,t,r)}catch(t){const n=t instanceof ReefRelayError&&t.status>=400&&t.status<500&&t.status!==409;if(!e||n)await a.remove();else if(await a.status()===`revoked`)try{await this.transport.removeFriend(i)}catch(e){throw new AggregateError([t,e],`Reef friend request to @${i} failed after concurrent revocation`,{cause:e})}throw t}if(await a.status()===`revoked`){await this.transport.removeFriend(i);throw new Error(`Reef friend request to @${i} was concurrently revoked`)}return o}finally{a.close()}})}remove(e,t){return this.#r(async()=>{const n=normalizeReefTarget(e);if(!n)throw new Error(`Invalid Reef peer handle: ${e}`);t?.();const r=await this.trust.beginRemoval(n,t);const i=(await Promise.allSettled([this.#t(n),this.#n(n,r)])).flatMap(e=>e.status===`rejected`?[e.reason instanceof Error?e.reason:new Error(`Reef friendship removal failed`,{cause:e.reason})]:[]);if(i.length===1)throw i[0];if(i.length>1)throw new AggregateError(i,`Reef friendship removal failed`)})}setAutonomy(e,t,n){return this.#r(async()=>{n?.();await this.trust.setAutonomy(e,t,n)})}async list(){const e=this.authoritySignal;e?.throwIfAborted();const t=new Map((await this.trust.list()).map(e=>[e.peer,e.trust]));const{friendships:n}=await this.transport.listFriends(e);e?.throwIfAborted();const r=[];for(const e of n){const n=t.get(e.peer)?.autonomy;r.push({...e,fingerprint:fingerprint(e.ed25519_pub,e.x25519_pub),...n?{autonomy:n}:{}})}return r}reconcile(e,t){return this.#r(async e=>{const{friendships:n}=await this.transport.listFriends(e);e?.throwIfAborted();const r=new Set(await this.pairing.list());const remove=async e=>{const t=await this.pairing.remove(e);r.delete(e);return t};const loadApprovals=async e=>{const t=new Map(e.map(e=>[e.peer,e]));const n=/* @__PURE__ */ new Map;for(const e of r){const r=this.trust.parsePairingApproval(e);if(!r){await remove(e);continue}const i=t.get(r.peer);if(!i||i.status===`blocked`||!await this.trust.matchesPairingApproval(e,i)){await remove(e);continue}n.set(r.peer,{entry:e,trustRevision:r.trustRevision})}return n};const i=await loadApprovals(n);const a=/* @__PURE__ */ new Set;for(const t of n){e?.throwIfAborted();if(t.status===`blocked`)continue;const n=await this.trust.snapshot(t.peer);const r=n.trust;const o=i.get(t.peer);const s=o?.trustRevision===n.revision?o:void 0;if(o&&!s)await remove(o.entry);const c=s?.entry;const l=s!==void 0;const u=Object.keys(n.outboundRequests??{}).toSorted()[0];const d=r?keysChanged(r,t):false;if(d&&r&&!l){if(!r.safetyNumberChanged&&await this.trust.markSafetyNumberChanged(t.peer,n.revision))a.add(t.peer);continue}const f=t.status===`active`&&!r&&u!==void 0;if(!(f||l&&(!r||d||r.safetyNumberChanged||t.status===`pending`||t.status===`reapprove_required`))){if(t.status===`active`&&r&&u!==void 0)await this.trust.removeOutboundRequest(t.peer);if(c!==void 0&&r&&!d&&!r.safetyNumberChanged)await remove(c);continue}if(t.status!==`active`&&!l)continue;if(c&&!await remove(c))continue;e?.throwIfAborted();if(t.status===`pending`||t.status===`reapprove_required`){await this.transport.respondFriend(t,true,e);e?.throwIfAborted()}if(await this.trust.commitPeerTrust(t,{expectedRevision:n.revision,...f&&u!==void 0?{expectedOutboundRequestId:u}:{}})){a.add(t.peer);continue}const p=await this.trust.snapshot(t.peer);if(p.revision>n.revision&&!p.trust&&Object.keys(p.outboundRequests??{}).length===0)await this.transport.removeFriend(t.peer)}if(t){const{friendships:n}=await this.transport.listFriends(e);e?.throwIfAborted();const r=await loadApprovals(n);for(const i of n){if(i.status===`blocked`)continue;const n=await this.trust.snapshot(i.peer);const a=r.get(i.peer);if(a?.trustRevision===n.revision)continue;if(a)await remove(a.entry);const o=n.trust;const s=o?keysChanged(o,i):false;const c=i.status===`pending`&&i.initiated_by!==this.transport.handle;const l=(i.status===`active`||i.status===`reapprove_required`)&&!o&&Object.keys(n.outboundRequests??{}).length===0;const u=i.status===`reapprove_required`||i.status===`active`&&Boolean(o&&(s||o.safetyNumberChanged));if(!c&&!l&&!u)continue;e?.throwIfAborted();await t({peer:i.peer,fingerprint:fingerprint(i.ed25519_pub,i.x25519_pub),code:i.peer,approvalToken:this.trust.createPairingApproval(i,n.revision)})}}return[...a].toSorted()},e)}async#t(e){for(const t of await this.pairing.list())if(this.trust.parsePairingApproval(t)?.peer===e||normalizeReefTarget(t)===e)await this.pairing.remove(t)}async#n(e,t){await this.transport.removeFriend(e);await t()}#r(e,t){const n=t&&this.authoritySignal?AbortSignal.any([t,this.authoritySignal]):t??this.authoritySignal;return this.#e(async()=>{n?.throwIfAborted();const t=await e(n);n?.throwIfAborted();return t})}};
//!extensions/reef/src/legacy-key-guard.ts
const REEF_LEGACY_KEYS_PENDING_CODE=`REEF_LEGACY_KEYS_PENDING`;async function assertLegacyReefKeysMigrated(e,t=process.env,n=os.homedir()){const r=`${resolveLegacyReefStateDir({config:e?{channels:{reef:{stateDir:e}}}:{},env:t,stateDir:resolveStateDir(t,()=>n),homeDir:n})}/keys.json`;try{await fs.stat(r)}catch(e){if(e.code===`ENOENT`)return;throw e}throw Object.assign(/* @__PURE__ */ new Error("Legacy Reef identity keys must be imported before registration. Run `openclaw doctor --fix`, then retry."),{code:REEF_LEGACY_KEYS_PENDING_CODE})}export{ReefInboxEntryParkedError as a,createReefWebSocket as c,isRetryableReefRelayFailure as d,createAnthropicGuard as f,ReefInboxConnection as i,isDefinitiveReefRegistrationFailure as l,createOpenAiGuard as m,assertLegacyReefKeysMigrated as n,ReefProtocolCompatibilityError as o,createHostOpenAiGuard as p,ReefFriendManager as r,ReefTransportClient as s,REEF_LEGACY_KEYS_PENDING_CODE as t,isReefOwnershipRejection as u};