UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

947 lines (946 loc) • 26.1 kB
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { f as safeStat } from "./path-existence-Co7-GyVr.mjs"; import { n as createAsyncLock } from "./json-files-Cb1h8pYs.mjs"; import "./path-existence-runtime-LOpU--Vt.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import "./async-lock-runtime-CocCmTYQ.mjs"; import "./account-resolution-BlF3HfnR.mjs"; import { a as decodeUtf8, o as fromBase64, r as base64, s as fromBase64url, t as canonicalBytes } from "./canonical-DuZhyO3R.mjs"; import { a as REEF_AUDIT_MIGRATION_NAMESPACE, h as gcm, n as REEF_AUDIT_HEAD_NAMESPACE, o as REEF_AUDIT_NAMESPACE, r as REEF_AUDIT_MAX_ENTRIES } from "./audit-state-format-BgwDlxZw.mjs"; import { p as randomBytes$1, u as concatBytes } from "./sha2-C0YCEfVG.mjs"; import { a as REEF_KEYS_MIGRATION_NAMESPACE, c as REEF_REVIEWS_NAMESPACE, f as REEF_REGISTRATION_NAMESPACE, n as REEF_DURABLE_MIGRATION_NAMESPACE, o as REEF_KEYS_NAMESPACE, s as REEF_REVIEWS_MAX_ENTRIES } from "./state-format-BYNwYsrm.mjs"; import { c as validateMessageBody, t as REEF_ENVELOPE_MAX_AGE_SECONDS } from "./envelope-BcvciVfE.mjs"; import { a as reefPeerIdentity, i as matchesReefPeerIdentity, r as ReefPeerTrustSchema, t as ReefAutonomySchema } from "./friend-types-C3bcCe8d.mjs"; import { S as resolveReefIdentityScope, a as REEF_TRUST_STORE_OPTIONS, d as ReefRejectionNoticeStateSchema, f as createReefPairingApproval, n as REEF_DELIVERY_STORE_OPTIONS, o as ReefOutboundDeliveryBindingSchema, t as MESSAGE_ID_PATTERN, u as ReefPeerTrustChangedError, v as parseReefPairingApproval, x as requirePeer } from "./trust-store-format-BRoJw2u0.mjs"; import path from "node:path"; import { createHash, randomUUID } from "node:crypto"; import os from "node:os"; //#region extensions/reef/src/audit-state.ts const auditOperationHandler = { moduleName: "audit-state-operation-api.js", exportName: "executeReefAuditOperation" }; var ReefSqliteAuditStore = class { #e; #t; constructor(e, t, n, r = REEF_AUDIT_MAX_ENTRIES, i) { if (t.length !== 32) throw new Error("audit key must be 32 bytes"); const a = e.state.openKeyedStoreV2({ namespace: REEF_AUDIT_MIGRATION_NAMESPACE, maxEntries: 1, overflowPolicy: "reject-new" }); const o = e.state.openKeyedStoreV2({ namespace: REEF_AUDIT_NAMESPACE, maxEntries: r + 1, overflowPolicy: "reject-new" }); this.operationState = { head: n, migration: a, entries: o, auditKey: t.slice(), maxEntries: r }; this.#t = { head: 0, migration: 1, entries: 2, auditKey: this.operationState.auditKey, maxEntries: r }; this.#e = n.createOperation([ n, a, o ], auditOperationHandler, { assertCurrent: () => i?.throwIfAborted() }); } async appendEvent(e, t, n = Math.floor(Date.now() / 1e3)) { return (await this.appendEvents([{ type: e, payload: t, ts: n }]))[0]; } async appendEvents(e) { return (await this.#e.execute({ type: "append", input: { ...this.#t, events: structuredClone(e) } }, { writeStores: [this.#t.head, this.#t.entries] })).value; } async entries() { return (await this.#e.execute({ type: "entries", input: this.#t }, { writeStores: [], missingValue: [] })).value; } }; function getReefAuditOperationState(e) { if (!(e instanceof ReefSqliteAuditStore)) return; return { ...e.operationState, auditKey: e.operationState.auditKey.slice() }; } function openReefAuditStore(e, t, n, r) { const i = e.state.openKeyedStoreV2({ namespace: REEF_AUDIT_HEAD_NAMESPACE, maxEntries: 1, overflowPolicy: "reject-new" }); return new ReefSqliteAuditStore(e, t, i, n, r); } //#endregion //#region extensions/reef/src/replay-store.ts const REEF_REPLAY_NAMESPACE = "replay"; const REEF_REPLAY_MAX_ENTRIES = 3e3; const REEF_REPLAY_TTL_MS = (REEF_ENVELOPE_MAX_AGE_SECONDS + 86400) * 1e3; const REEF_REPLAY_CLAIM_LEASE_MS = 3e5; function reefReplayStoreKey(e, t) { return `binding:${createHash("sha256").update(JSON.stringify([e, t])).digest("hex")}`; } function parseReplayRecord(e) { if (!e) return; if (typeof e.peer !== "string" || typeof e.id !== "string" || typeof e.envelopeHash !== "string" || ![ "available", "in_flight", "completed", "consumed" ].includes(e.state) || e.state === "in_flight" && (typeof e.claimOwner !== "string" || e.claimOwner.length === 0 || !Number.isSafeInteger(e.claimExpiresAt) || (e.claimExpiresAt ?? 0) <= 0)) throw new Error("invalid Reef replay state"); return e; } function encryptReplayBody(e, t) { validateMessageBody(e); const n = randomBytes$1(12); if (n.length !== 12) throw new Error("replay body rng returned invalid nonce"); return { enc: base64(concatBytes(n, gcm(t, n).encrypt(canonicalBytes(e)))) }; } function decryptReplayBody(e, t) { const n = fromBase64(e.enc); if (n.length < 28) throw new Error("invalid encrypted replay body"); const r = JSON.parse(decodeUtf8(gcm(t, n.slice(0, 12)).decrypt(n.slice(12)))); validateMessageBody(r); return r; } function validateReplayCompletion(e, t) { if (e.status === "accepted" !== (t !== void 0)) throw new Error("accepted replay completion requires body; rejected completion forbids body"); } var ReefSqliteReplayStore = class { #e; #t; #n = /* @__PURE__ */ new Map(); #r = createAsyncLock(); constructor(e, t) { if (t.length !== 32) throw new Error("replay body key must be 32 bytes"); this.#e = t.slice(); const n = { namespace: REEF_REPLAY_NAMESPACE, maxEntries: REEF_REPLAY_MAX_ENTRIES, overflowPolicy: "reject-new", defaultTtlMs: REEF_REPLAY_TTL_MS }; this.#t = e.state.openKeyedStoreV2(n); } #i(e, t) { const n = this.#t; return this.#r(async () => { const r = t(); let i = await n.observe(e); for (;;) { const t = r.decide(parseReplayRecord(i.value)); const a = await n.compareAndApply(e, i.comparison, t.value === void 0 ? { operation: "update", action: "keep" } : { operation: "update", action: "set", value: t.value }); if (a.status === "conflict") { i = a.current; continue; } r.publish?.(t.result); return t.result; } }); } async claim(e, t, n) { const r = reefReplayStoreKey(e, t); return this.#i(r, () => { const i = randomUUID(); const a = { claimOwner: i, claimExpiresAt: Date.now() + REEF_REPLAY_CLAIM_LEASE_MS }; return { decide: (r) => { if (!r) return { value: { peer: e, id: t, envelopeHash: n, state: "in_flight", ...a }, result: "new" }; if (r.peer !== e || r.id !== t || r.envelopeHash !== n) return { value: r, result: "mismatch" }; if (r.state === "completed" || r.state === "consumed") return { value: r, result: "duplicate" }; if (r.state === "in_flight" && (r.claimExpiresAt ?? 0) > Date.now()) return { value: r, result: "in_flight" }; return { value: { ...r, state: "in_flight", ...a }, result: "new" }; }, publish: (e) => { if (e === "new") this.#n.set(r, i); } }; }); } async refresh(e, t) { const n = reefReplayStoreKey(e, t); const refresh = () => { const e = this.#n.get(n); if (!e) throw new Error("replay claim is not in flight"); const t = Date.now() + REEF_REPLAY_CLAIM_LEASE_MS; return { decide: (n) => ({ value: n?.state === "in_flight" && n.claimOwner === e ? { ...n, claimExpiresAt: t } : n, result: n?.state === "in_flight" && n.claimOwner === e }), publish: (e) => { if (!e) { this.#n.delete(n); throw new Error("replay claim is not in flight"); } } }; }; await this.#i(n, refresh); } async complete(e, t, n, r) { if (n.id !== t) throw new Error("receipt id does not match replay claim"); validateReplayCompletion(n, r); let i; const a = reefReplayStoreKey(e, t); await this.#i(a, () => { const e = this.#n.get(a); return { decide: (t) => { if (t?.state !== "in_flight" || t.claimOwner !== e) return { value: t, result: false }; const { claimOwner: a, claimExpiresAt: o, ...s } = t; i ??= { receipt: n, ...r ? { body: encryptReplayBody(r, this.#e) } : {} }; return { value: { ...s, state: "completed", ...i }, result: true }; }, publish: (e) => { if (!e) throw new Error("replay claim is not in flight"); this.#n.delete(a); } }; }); } async release(e, t) { const n = reefReplayStoreKey(e, t); await this.#i(n, () => { const e = this.#n.get(n); return { decide: (t) => ({ value: t?.state === "in_flight" && t.claimOwner === e ? { peer: t.peer, id: t.id, envelopeHash: t.envelopeHash, state: "available" } : t, result: void 0 }), publish: () => { this.#n.delete(n); } }; }); } async completed(e, t) { const read = (n) => { const r = parseReplayRecord(n); if (r?.peer !== e || r.id !== t || r.state !== "completed" || !r.receipt) return; return r.body ? { receipt: r.receipt, body: decryptReplayBody(r.body, this.#e) } : { receipt: r.receipt }; }; const n = reefReplayStoreKey(e, t); return this.#r(async () => read(await this.#t.lookup(n))); } }; //#endregion //#region extensions/reef/src/state.ts const REEF_DELIVERED_NAMESPACE = "delivered"; const REEF_DELIVERED_MAX_ENTRIES = 5e3; const REEF_DELIVERED_TTL_MS = REEF_REPLAY_TTL_MS; const REEF_INBOX_CURSOR_NAMESPACE = "inbox-cursor"; const REEF_INBOX_CURSOR_MAX_ENTRIES = 1; const stateOperationHandler = { moduleName: "state-operation-api.js", exportName: "runReefStateOperation" }; function openIdentityState(e, t) { const n = [ e.state.openKeyedStoreV2({ namespace: REEF_DURABLE_MIGRATION_NAMESPACE, maxEntries: 1, overflowPolicy: "reject-new" }), e.state.openKeyedStoreV2({ namespace: REEF_KEYS_MIGRATION_NAMESPACE, maxEntries: 1, overflowPolicy: "reject-new" }), e.state.openKeyedStoreV2({ namespace: REEF_KEYS_NAMESPACE, maxEntries: 1, overflowPolicy: "reject-new" }), e.state.openKeyedStoreV2({ namespace: REEF_REGISTRATION_NAMESPACE, maxEntries: 2, overflowPolicy: "reject-new" }) ]; return n[0].createOperation(n, stateOperationHandler, t ? { assertCurrent: t } : void 0); } async function generateAndStoreKeys(e, t) { return (await openIdentityState(e, t).execute({ type: "identity.generate", input: void 0 }, { writeStores: [2] })).value; } async function loadKeys(e, t) { const n = await openIdentityState(e, t).execute({ type: "identity.load", input: void 0 }, { writeStores: [], watchStores: [ 0, 1, 2 ], missingValue: void 0 }); n.assertCurrent(); if (!n.value) throw Object.assign(/* @__PURE__ */ new Error("Reef keys are missing from plugin state"), { code: "ENOENT" }); return n.value; } const reviewOperationStates = /* @__PURE__ */ new WeakMap(); function getReefReviewOperationState(e) { return reviewOperationStates.get(e); } var ReviewApprovalStore = class { #e; #t; constructor(e, t = REEF_REVIEWS_MAX_ENTRIES, n) { this.authoritySignal = n; this.#t = t; this.#e = e.state.openKeyedStoreV2({ namespace: REEF_REVIEWS_NAMESPACE, maxEntries: t, overflowPolicy: "reject-new" }); reviewOperationStates.set(this, { store: this.#e, maxEntries: t }); } #n(e) { return this.#e.createOperation([this.#e], stateOperationHandler, { assertCurrent: () => { this.authoritySignal?.throwIfAborted(); e?.(); } }); } async request(e) { return (await this.#n().execute({ type: "review.request", input: { review: e, maxEntries: this.#t } }, { writeStores: [0] })).value; } async observeDecision(e) { const t = await this.#n().execute({ type: "review.lookup", input: { digest: e } }, { writeStores: [], watchStores: [0], missingValue: "none" }); t.assertCurrent(); return t; } async decide(e, t, n) { return (await this.#n(n).execute({ type: "review.decide", input: { digest: e, approved: t } }, { writeStores: [0] })).value; } async list() { const e = await this.#n().execute({ type: "review.list", input: void 0 }, { writeStores: [], watchStores: [0], missingValue: [] }); e.assertCurrent(); return e.value; } }; var ReefDeliveredStore = class { #e; constructor(e, t = REEF_DELIVERED_MAX_ENTRIES) { this.#e = e.state.openKeyedStoreV2({ namespace: REEF_DELIVERED_NAMESPACE, maxEntries: t, overflowPolicy: "reject-new", defaultTtlMs: REEF_DELIVERED_TTL_MS }); } async status(e) { return (await this.#e.lookup(e))?.id === e ? "delivered" : void 0; } async confirm(e) { if (!await this.#e.registerIfAbsent(e, { id: e }) && (await this.#e.lookup(e))?.id !== e) throw new Error("Failed persisting Reef delivered marker"); } }; /** Durable relay progress for the single Reef identity bound to this state DB. */ var ReefInboxCursorStore = class { #e; #t; constructor(e, t, n) { this.authoritySignal = n; this.#t = { ...t }; const r = { namespace: REEF_INBOX_CURSOR_NAMESPACE, maxEntries: REEF_INBOX_CURSOR_MAX_ENTRIES, overflowPolicy: "reject-new" }; this.#e = e.state.openKeyedStoreV2(r); } #n() { return this.#e.createOperation([this.#e], stateOperationHandler, { assertCurrent: () => this.authoritySignal?.throwIfAborted() }); } async load() { this.authoritySignal?.throwIfAborted(); const e = await this.#n().execute({ type: "cursor.load", input: this.#t }, { writeStores: [], watchStores: [0], missingValue: 0 }); e.assertCurrent(); return e.value; } async advance(e) { this.authoritySignal?.throwIfAborted(); if (!Number.isSafeInteger(e) || e < 0) throw new Error("invalid Reef inbox cursor"); await this.#n().execute({ type: "cursor.advance", input: { ...this.#t, cursor: e } }, { writeStores: [0] }); } }; async function openStores$1(e, t, n = {}) { const { authoritySignal: r } = n; const assertCurrent = () => r?.throwIfAborted(); const i = openIdentityState(e, assertCurrent); const a = { audit: openReefAuditStore(e, fromBase64url(t.auditKey), n.auditMaxEntries, n.authoritySignal), replay: new ReefSqliteReplayStore(e, fromBase64url(t.replayKey)), reviews: new ReviewApprovalStore(e, void 0, n.authoritySignal), delivered: new ReefDeliveredStore(e, n.deliveredMaxEntries) }; (await i.execute({ type: "identity.admit", input: void 0 }, { writeStores: [], watchStores: [0, 1], missingValue: void 0 })).assertCurrent(); return a; } //#endregion //#region extensions/reef/src/trust-store-authority.ts function validateReefPeerIdentity(e, t, n, r) { if (!e || !matchesReefPeerIdentity(e, n) || r !== void 0 && e.autonomy !== r) throw new ReefPeerTrustChangedError(t); return e; } function createReefPeerAssertion(e, t, n, r, i) { const a = n ? { ...n } : void 0; const o = { ...r }; return () => { e.assertCurrent(); validateReefPeerIdentity(a, t, o, i); }; } //#endregion //#region extensions/reef/src/trust-store-delivery.ts const recoveryStates = /* @__PURE__ */ new WeakMap(); function getReefRecoveryOperationState(e) { return recoveryStates.get(e); } async function readReefOutboundDelivery(e, t, n) { const r = { ...t }; const i = { ...n }; const a = await e.execute({ type: "readDelivery", input: r }, { writeStores: [], watchStores: [0], missingValue: void 0 }); a.assertCurrent(); if (!a.value) return; const { delivery: o, trust: s } = a.value; const c = ReefOutboundDeliveryBindingSchema.parse({ bodyHash: o.bodyHash, textHash: o.textHash, recipient: o.recipient }); let l = createReefPeerAssertion(a, r.peer, s, c.recipient); let u = true; const settle = async (t, n) => { if (!u) throw new Error("Reef delivery settlement was already consumed"); u = false; return (await e.execute({ type: t, input: n }, { writeStores: [1], watchStores: [0] })).value; }; return { delivery: o, recovery: createReefRejectionRecovery(e, r, c.recipient, a, i, () => l()), async currentPeer() { const t = await e.execute({ type: "snapshot", input: { key: r.peerKey } }, { writeStores: [], watchStores: [0], missingValue: { revision: 0 } }); t.assertCurrent(); l = createReefPeerAssertion(t, r.peer, t.value.trust, c.recipient); return t.value.trust; }, assertCurrent: () => l(), consume: () => settle("consumeDelivery", { ...r, expected: c }), discard: () => settle("discardDelivery", { ...r, expected: c }), reject: (e) => settle("rejectDelivery", { ...r, expected: c, category: e, rejectedAt: Date.now() }) }; } function createReefRejectionRecovery(e, t, n, r, i, a) { const o = { ...t }; const s = { ...n }; let c = r; let assertCurrent = a ?? (() => r.assertCurrent()); const l = { assertCurrent: () => assertCurrent(), async loadState() { const t = await e.execute({ type: "snapshot", input: { key: o.peerKey } }, { writeStores: [], watchStores: [0], missingValue: { revision: 0 } }); t.assertCurrent(); return t.value.rejectionNotice; }, async reserve(t) { const n = ReefRejectionNoticeStateSchema.parse(t); assertCurrent = () => { throw new Error("Reef rejection reservation did not settle"); }; const r = await e.execute({ type: "reserveRejection", input: { ...o, recipient: s, notice: n } }, { writeStores: [1], watchStores: [0] }); if (r.value.kind === "peer-changed") throw new Error(`Reef peer @${o.peer} changed keys before rejection recovery`); if (r.value.kind === "unavailable") throw new Error(`Reef rejection ${o.id} lost its durable delivery state`); c = r; assertCurrent = () => r.assertCurrent(); return r.value; }, async complete(t) { const n = ReefRejectionNoticeStateSchema.parse(t); return (await e.execute({ type: "completeRejection", input: { ...o, notice: n } }, { writeStores: [0, 1] })).value; } }; recoveryStates.set(l, { ...i, get sourceReceipt() { return c; }, assertCurrent: () => l.assertCurrent() }); return l; } //#endregion //#region extensions/reef/src/trust-store.ts const operationHandler = { moduleName: "trust-state-operation-api.js", exportName: "runReefTrustStateOperation" }; function openStores(e) { return { peers: e(REEF_TRUST_STORE_OPTIONS), deliveries: e(REEF_DELIVERY_STORE_OPTIONS) }; } var ReefTrustStore = class { #e; #t; #n; constructor(e, t, n) { const r = resolveReefIdentityScope(t); this.#e = `${r}:`; this.operationState = { ...e, identityScope: r, assertCurrent: () => n?.() }; } #r(e, t, n = false) { const r = this.operationState; return r.peers.createOperation(n ? [r.peers] : [r.peers, r.deliveries], operationHandler, { assertCurrent: () => { if (!t?.()) { r.assertCurrent(); e?.(); } } }); } async #i(e, t, n, r = [0], i) { const a = await (r.length === 1 ? this.#n ??= this.#r(void 0, void 0, true) : this.#t ??= this.#r()).execute({ type: e, input: t }, { writeStores: [], watchStores: r, missingValue: n, ifEmpty: i === void 0 ? void 0 : { store: i, value: n } }); a.assertCurrent(); return a; } async #a(e, t, n, r) { return (await this.#r(r).execute({ type: e, input: t }, { writeStores: n })).value; } async snapshot(e) { return (await this.#i("snapshot", { key: this.#o(e) }, { revision: 0 })).value; } async get(e) { return (await this.snapshot(e)).trust; } async observePeer(e) { const t = requirePeer(e); const n = await this.#i("snapshot", { key: this.#o(t) }, { revision: 0 }); const r = n.value.trust; return r ? { trust: r, assertCurrent: createReefPeerAssertion(n, t, r, reefPeerIdentity(r), r.autonomy) } : void 0; } async list() { return (await this.#i("list", { prefix: this.#e }, [])).value; } async set(e, t) { await this.#a("set", { key: this.#o(e), trust: ReefPeerTrustSchema.parse(t) }, [0]); } remove(e, t) { return this.#a("remove", { key: this.#o(e) }, [0], t); } async beginRemoval(e, t) { const n = this.#o(e); let r = false; const i = this.#r(t, () => r); const revoke = () => i.execute({ type: "remove", input: { key: n } }, { writeStores: [0] }); await revoke(); r = true; let a = true; return async () => { if (!a) throw new Error("Reef removal settlement was already consumed"); a = false; await revoke(); }; } async setAutonomy(e, t, n) { if (!await this.#a("setAutonomy", { key: this.#o(e), autonomy: ReefAutonomySchema.parse(t) }, [0], n)) throw new Error(`Reef peer @${requirePeer(e)} is not locally trusted`); } markSafetyNumberChanged(e, t) { return this.#a("markSafetyNumberChanged", { key: this.#o(e), expectedRevision: t }, [0]); } commitPeerTrust(e, t, n = Date.now()) { return this.#a("commitPeerTrust", { key: this.#o(e.peer), friend: { ...e }, ...t, approvedAt: n }, [0]); } createPairingApproval(e, t) { return createReefPairingApproval(this.operationState.identityScope, e, t); } parsePairingApproval(e) { return parseReefPairingApproval(this.operationState.identityScope, e); } async matchesPairingApproval(e, t) { const n = { ...t }; return e.trim() === this.createPairingApproval(n, (await this.snapshot(n.peer)).revision); } async beginRequest(e, t = Date.now(), n) { const r = randomUUID(); const i = this.#o(e); let a = false; const o = this.#r(n, () => a); await o.execute({ type: "beginRequest", input: { key: i, requestId: r, requestedAt: t } }, { writeStores: [0] }); a = true; let s = true; const consume = async (e) => { if (!s) throw new Error("Reef request settlement was already consumed"); s = false; return e(); }; return { requestId: r, status: () => consume(async () => (await o.execute({ type: "requestStatus", input: { key: i, requestId: r } }, { writeStores: [], missingValue: "revoked" })).value), remove: () => consume(async () => { await o.execute({ type: "removeRequest", input: { key: i, requestId: r } }, { writeStores: [0] }); }), close: () => { s = false; } }; } async hasOutboundRequest(e) { return Object.keys((await this.snapshot(e)).outboundRequests ?? {}).length > 0; } removeOutboundRequest(e, t) { return this.#a("removeRequest", { key: this.#o(e), requestId: t }, [0]); } async overdueOutboundDeliveries(e, t = Date.now()) { return (await this.#i("overdueDeliveries", { prefix: this.#e, olderThanMs: e, now: t }, [], [0, 1], 1)).value; } markOutboundDeliveryOverdueNotified(e, t) { return this.#a("markDeliveryOverdue", { ...this.#s(e, t), now: Date.now() }, [1]); } readOutboundDelivery(e, t) { return readReefOutboundDelivery(this.#r(), this.#s(e, t), this.operationState); } async pendingOutboundRejections() { const e = this.#t ??= this.#r(); const t = await e.execute({ type: "pendingRejections", input: { prefix: this.#e } }, { writeStores: [], missingValue: [], watchStores: [0, 1], ifEmpty: { store: 1, value: [] } }); t.assertCurrent(); return t.value.map((n) => Object.assign({}, n, { recovery: createReefRejectionRecovery(e, this.#s(n.peer, n.id), n.recipient, t, this.operationState) })); } async rejectionNoticeState(e) { return (await this.snapshot(e)).rejectionNotice; } #o(e) { return `${this.#e}${requirePeer(e)}`; } #s(e, t) { if (!MESSAGE_ID_PATTERN.test(t)) throw new Error(`Invalid Reef delivery id: ${t}`); const n = requirePeer(e); const r = this.#o(n); return { peer: n, peerKey: r, deliveryKey: `${r}:${t}`, id: t }; } }; function getReefTrustOperationState(e) { return e.operationState; } function openReefTrustStore(e, t, n) { const r = openStores(e.state.openKeyedStoreV2); return new ReefTrustStore(r, t, n); } //#endregion //#region extensions/reef/src/doctor-state-paths.ts const REEF_DURABLE_LEGACY_FILENAMES = [ "keys.json", "identity.json", "setup-session.json", "audit.jsonl", "replay.jsonl", "reviews.json", "delivered.json" ]; function resolveLegacyReefStateDir(e) { const t = e.config.channels?.reef; const n = isRecord(t) && typeof t.stateDir === "string" ? t.stateDir : null; const r = resolveDefaultLegacyReefStateDir(e.homeDir); const i = n ? resolveUserPath(n, e.env) : null; if (i) return i; const a = path.relative(path.resolve(e.stateDir), r); return a === "" || !a.startsWith(`..${path.sep}`) && a !== ".." && !path.isAbsolute(a) ? r : path.join(e.stateDir, "data", "reef"); } function resolveDefaultLegacyReefStateDir(e = os.homedir()) { return path.join(e, ".openclaw", "data", "reef"); } const collectLegacyReefStateBackupResources = (e) => [{ path: resolveLegacyReefStateDir(e), kind: "directory" }]; async function legacyReefFileExists(e) { return (await safeStat(e))?.isFile() === true; } async function listLegacyReefFiles(e, t) { return (await Promise.all(t.map(async (t) => ({ filename: t, exists: await legacyReefFileExists(path.join(e, t)) })))).filter((e) => e.exists).map((e) => e.filename); } //#endregion export { REEF_REPLAY_MAX_ENTRIES as _, resolveLegacyReefStateDir as a, reefReplayStoreKey as b, getReefRecoveryOperationState as c, REEF_DELIVERED_TTL_MS as d, ReefInboxCursorStore as f, openStores$1 as g, loadKeys as h, listLegacyReefFiles as i, REEF_DELIVERED_MAX_ENTRIES as l, getReefReviewOperationState as m, collectLegacyReefStateBackupResources as n, getReefTrustOperationState as o, generateAndStoreKeys as p, legacyReefFileExists as r, openReefTrustStore as s, REEF_DURABLE_LEGACY_FILENAMES as t, REEF_DELIVERED_NAMESPACE as u, REEF_REPLAY_NAMESPACE as v, getReefAuditOperationState as x, REEF_REPLAY_TTL_MS as y };