openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
333 lines (332 loc) • 12.8 kB
JavaScript
import { t as mutateConfigFile } from "./mutate-DhAOi0-2.mjs";
import "./config-mutation-CGDddIEg.mjs";
import { n as createChannelPairingController } from "./channel-pairing-R9ineSO_.mjs";
import { C as saveReefSetupSession, S as reserveReefIdentityBinding, _ as loadReefIdentityBinding, g as finalizeReefIdentityBinding, h as clearReefSetupSession, m as assertReefIdentityBinding, v as loadReefSetupSession, w as fingerprint, x as releaseReefIdentityReservation } from "./state-format-BYNwYsrm.mjs";
import { l as isDefinitiveReefRegistrationFailure, n as assertLegacyReefKeysMigrated, r as ReefFriendManager, s as ReefTransportClient, t as REEF_LEGACY_KEYS_PENDING_CODE, u as isReefOwnershipRejection } from "./legacy-key-guard-Dr-RTpsH.mjs";
import { a as parseReefRelayUrl, n as ReefChannelConfigSchema } from "./config-schema-ChhvoCSi.mjs";
import { h as loadKeys, p as generateAndStoreKeys, s as openReefTrustStore } from "./doctor-state-paths-B2MyXhWh.mjs";
import { t as ReefAutonomySchema } from "./friend-types-C3bcCe8d.mjs";
import { i as getReefRuntime } from "./runtime-B3XbM5sw.mjs";
//#region extensions/reef/src/cli.ts
const HANDLE_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
const GUARD_DEFAULTS = {
openai: {
pinnedModel: "gpt-5.6-terra",
apiKeyEnv: "REEF_GUARD_OPENAI_KEY"
},
anthropic: {
pinnedModel: "claude-haiku-4-5-20251001",
apiKeyEnv: "REEF_GUARD_ANTHROPIC_KEY"
}
};
function emit(e, t, n) {
if (e.json) {
process.stdout.write(`${JSON.stringify(t)}\n`);
return;
}
for (const e of n) process.stdout.write(`${e}\n`);
}
function reefCliAction(e) {
return async (...t) => {
const n = t.length - 2;
const r = t[n];
const i = t.slice(0, n);
const a = { json: r.json };
try {
await e(a, r, ...i);
} catch (e) {
if (a.json) throw e;
const t = e instanceof Error ? e.message : String(e);
process.stderr.write(`${t}\n`);
process.exitCode = 1;
}
};
}
async function loadOrCreateKeys(e, t) {
const n = getReefRuntime();
try {
return await loadKeys(n);
} catch (r) {
if (e && r.code === "ENOENT") {
await assertLegacyReefKeysMigrated(t);
return await generateAndStoreKeys(n);
}
throw r;
}
}
function currentReefConfig() {
const e = getReefRuntime().config.current().channels?.reef;
if (!e) return;
const t = ReefChannelConfigSchema.safeParse(e);
return t.success ? t.data : void 0;
}
async function loadConfiguredManager() {
const e = currentReefConfig();
if (!e?.handle) throw new Error("Reef is not configured. Run `openclaw reef register` first.");
const t = await loadOrCreateKeys(false);
const n = getReefRuntime();
const r = parseReefRelayUrl(e.relayUrl);
await assertReefIdentityBinding(n, {
handle: e.handle,
relayUrl: r
});
const i = new ReefTransportClient(r, e.handle, t);
const a = createChannelPairingController({
core: n,
channel: "reef",
accountId: "default"
});
return {
config: e,
keys: t,
manager: new ReefFriendManager(i, openReefTrustStore(n, e), {
list: a.readAllowFromStore,
remove: async (e) => {
return (await a.removeAllowFromStoreEntry(e)).changed;
}
})
};
}
async function writeReefRegistration(e) {
await mutateConfigFile({
afterWrite: { mode: "auto" },
mutate(t) {
t.channels = {
...t.channels,
reef: e
};
}
});
}
async function writeReefMigrationStateDir(e) {
await mutateConfigFile({
afterWrite: { mode: "auto" },
mutate(t) {
const n = t.channels?.reef;
t.channels = {
...t.channels,
reef: {
...n && typeof n === "object" && !Array.isArray(n) ? n : {},
stateDir: e
}
};
}
});
}
async function runRegister(e, t) {
if (!t.email.includes("@")) throw new Error("A valid --email is required.");
const n = t.guardProvider;
const r = GUARD_DEFAULTS[n];
if (!r) throw new Error("--guard-provider must be one of: anthropic, openai.");
const i = parseReefRelayUrl(t.relay);
const a = t.stateDir ?? currentReefConfig()?.stateDir;
const o = t.handle?.toLowerCase();
const s = getReefRuntime();
const c = await loadReefIdentityBinding(s);
if (c?.handle && (c.relayUrl !== i || o !== void 0 && c.handle !== o)) throw new Error(`This OpenClaw state already holds the Reef identity @${c.handle} on ${c.relayUrl}. Re-register the same handle and relay.`);
const l = o ?? c?.handle;
let u;
try {
u = await loadOrCreateKeys(true, a);
} catch (e) {
if (t.stateDir && e.code === "REEF_LEGACY_KEYS_PENDING") try {
await writeReefMigrationStateDir(t.stateDir);
} catch (e) {
throw new Error("Failed to save the Reef legacy state directory for Doctor", { cause: e });
}
throw e;
}
const d = new ReefTransportClient(i, l ?? "pending", u);
const f = await loadReefSetupSession(s);
const p = t.token?.trim();
const m = !t.session?.trim() && f?.relayUrl === i && f?.email === t.email ? f.session : void 0;
const h = t.session?.trim() || m;
if (!h && !p) {
const n = await d.authStart(t.email);
emit(e, {
status: "email_sent",
email: t.email,
...n.magicLink ? { magicLink: n.magicLink } : {},
next: "Open the magic link, copy the token from the URL fragment, then rerun the exact same command with --token <token> added (or --session from the welcome page)."
}, [
`Sign-in link sent to ${t.email}.`,
...n.magicLink ? [`Development magic link: ${n.magicLink}`] : [],
"Open the link, copy the token from the URL fragment, then rerun the exact",
"same command with --token <token> added."
]);
return;
}
const g = l;
if (!g || !HANDLE_PATTERN.test(g)) throw new Error("A valid --handle is required (lowercase letters, digits, - or _).");
const _ = {
provider: n,
pinnedModel: t.guardModel ?? r.pinnedModel,
apiKeyEnv: t.guardEnv ?? r.apiKeyEnv,
policyVersion: t.guardPolicy,
timeoutMs: 3e4
};
const v = {
enabled: true,
relayUrl: i,
handle: g,
email: t.email,
requestPolicy: t.policy,
...a ? { stateDir: a } : {},
guard: _
};
ReefChannelConfigSchema.parse(v);
const y = await reserveReefIdentityBinding(s, {
handle: g,
relayUrl: i
});
let b = h;
if (!b) {
try {
b = (await d.authComplete(p ?? "")).session;
} catch (e) {
if (isDefinitiveReefRegistrationFailure(e)) await releaseReefIdentityReservation(s, y);
else await finalizeReefIdentityBinding(s, y);
throw e;
}
try {
await saveReefSetupSession(s, {
session: b,
relayUrl: i,
email: t.email
});
} catch (e) {
await releaseReefIdentityReservation(s, y);
throw e;
}
}
const x = new ReefTransportClient(i, g, u);
let S = t.policy;
try {
await x.createHandle(b, t.policy);
} catch (e) {
const t = e instanceof Error && e.message.includes("handle_unavailable");
let n = false;
if (t) try {
await x.listFriends();
n = true;
} catch (e) {
if (isReefOwnershipRejection(e)) await releaseReefIdentityReservation(s, y);
else await finalizeReefIdentityBinding(s, y);
throw e;
}
if (!n) {
if (isDefinitiveReefRegistrationFailure(e)) await releaseReefIdentityReservation(s, y);
else await finalizeReefIdentityBinding(s, y);
throw e;
}
await finalizeReefIdentityBinding(s, y);
const { handles: r } = await x.listOwnHandles(b);
const i = r.find((e) => e.handle === g);
if (!i) throw new Error(`Handle @${g} is owned by this claw's keys, but the supplied session belongs to a different relay account. Use a session for the account that registered the handle.`, { cause: e });
S = i.request_policy;
}
await finalizeReefIdentityBinding(s, y);
const C = ReefChannelConfigSchema.parse({
...v,
requestPolicy: S
});
try {
await writeReefRegistration(C);
} catch (e) {
throw new Error(`Handle @${g} is claimed, but writing the local config failed: ${e instanceof Error ? e.message : String(e)}. Fix the local issue and rerun the exact same command — the retry reuses the stored session and recognizes the existing claim.`, { cause: e });
}
await clearReefSetupSession(s);
const w = fingerprint(u.signing.publicKey, u.encryption.publicKey);
emit(e, {
status: "registered",
handle: g,
relayUrl: i,
fingerprint: w
}, [
`Registered @${g} on ${i}.`,
`Safety fingerprint (share out of band): ${w}`,
"Restart the gateway to connect: openclaw gateway restart"
]);
}
function registerReefCli({ program: e }) {
const t = e.command("reef").description("Register on a Reef relay and manage guarded claw-to-claw friendships");
t.command("register").description("Claim a handle and configure the Reef channel without the wizard").requiredOption("--email <email>", "Owner email registered with the relay").option("--handle <handle>", "Unlisted handle for this claw").option("--session <session>", "Setup session from the relay welcome page").option("--token <token>", "Magic-link token to exchange for a session").option("--relay <url>", "Relay origin URL", "https://reefwire.ai").option("--policy <policy>", "Inbound friend-request policy", "code-only").option("--state-dir <dir>", "Legacy Reef file directory for Doctor import").option("--guard-provider <provider>", "Guard provider (anthropic|openai)", "openai").option("--guard-model <model>", "Immutable guard model id (default depends on provider)").option("--guard-env <name>", "Env var holding the guard API key (default depends on provider)").option("--guard-policy <version>", "Guard policy version", "reef-v1").option("--json", "Emit JSON", false).action(reefCliAction(runRegister));
t.command("status").description("Show Reef configuration and relay-side friendships").option("--json", "Emit JSON", false).action(reefCliAction(async (e) => {
const { config: t, keys: n, manager: r } = await loadConfiguredManager();
const i = await r.list();
const a = fingerprint(n.signing.publicKey, n.encryption.publicKey);
emit(e, {
handle: t.handle,
relayUrl: t.relayUrl,
requestPolicy: t.requestPolicy,
guard: {
provider: t.guard?.provider,
pinnedModel: t.guard?.pinnedModel
},
fingerprint: a,
friends: i.map((e) => ({
peer: e.peer,
status: e.status,
autonomy: e.autonomy ?? null,
fingerprint: e.fingerprint
}))
}, [
`@${t.handle} on ${t.relayUrl} (policy ${t.requestPolicy})`,
`Guard: ${t.guard?.provider}/${t.guard?.pinnedModel}`,
`Fingerprint: ${a}`,
...i.map((e) => `- @${e.peer}: ${e.status}${e.autonomy ? ` (${e.autonomy})` : ""}`),
...i.length === 0 ? ["No friendships yet."] : []
]);
}));
const n = t.command("friend").description("Manage Reef friendships");
n.command("code").description("Mint a short-lived code a friend can use to request pairing").option("--json", "Emit JSON", false).action(reefCliAction(async (e) => {
const { manager: t } = await loadConfiguredManager();
const n = await t.mintCode();
const r = (/* @__PURE__ */ new Date(n.expires * 1e3)).toISOString();
emit(e, {
code: n.code,
expires: r
}, [`Friend code: ${n.code} (expires ${r})`]);
}));
n.command("autonomy <handle> <tier>").description("Set a trusted friend's autonomy tier").option("--json", "Emit JSON", false).action(reefCliAction(async (e, t, n, r) => {
const { manager: i } = await loadConfiguredManager();
const a = n.replace(/^@/, "").toLowerCase();
const o = ReefAutonomySchema.parse(r);
await i.setAutonomy(a, o);
emit(e, {
peer: a,
autonomy: o
}, [`Set @${a} autonomy to ${o}.`]);
}));
n.command("request <handle>").description("Request a friendship (adopted automatically once accepted)").option("--code <code>", "Friend code minted by the recipient").option("--json", "Emit JSON", false).action(reefCliAction(async (e, t, n) => {
const { manager: r } = await loadConfiguredManager();
const i = n.replace(/^@/, "").toLowerCase();
const a = await r.request(i, t.code);
emit(e, {
peer: i,
status: a.status
}, [`Friend request to @${i}: ${a.status}. Adopted automatically once the peer accepts.`]);
}));
n.command("list").description("List relay-side friendships with local autonomy").option("--json", "Emit JSON", false).action(reefCliAction(async (e) => {
const { manager: t } = await loadConfiguredManager();
const n = await t.list();
emit(e, { friends: n.map((e) => ({
peer: e.peer,
status: e.status,
autonomy: e.autonomy ?? null,
keyEpoch: e.key_epoch,
fingerprint: e.fingerprint
})) }, n.length ? n.map((e) => `@${e.peer} ${e.status} epoch=${e.key_epoch} fingerprint=${e.fingerprint}${e.autonomy ? ` autonomy=${e.autonomy}` : ""}`) : ["No friendships yet."]);
}));
n.command("remove <handle>").description("Remove or block a friendship").option("--json", "Emit JSON", false).action(reefCliAction(async (e, t, n) => {
const { manager: r } = await loadConfiguredManager();
const i = n.replace(/^@/, "").toLowerCase();
await r.remove(i);
emit(e, {
peer: i,
status: "removed"
}, [`Removed @${i}.`]);
}));
}
//#endregion
export { registerReefCli };