openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
227 lines (226 loc) • 8.77 kB
JavaScript
import { l as normalizeOptionalString, p as normalizeStringifiedOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs";
import { n as sanitizeTerminalText } from "./safe-text-C80HAQ2e.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as captureRuntimeConfigAsyncReader } from "./io.runtime-DsJ2dLCQ.mjs";
import "./config-CMA-J084.mjs";
import { r as theme } from "./theme-BOI0xyRZ.mjs";
import { t as danger } from "./globals-CgepmiqE.mjs";
import { t as applyPluginAutoEnable } from "./plugin-auto-enable-CPcwS2II.mjs";
import { t as commitConfigWithPendingPluginInstalls } from "./install-record-commit-BBhtfevs.mjs";
import { i as resolveChannelDefaultAccountId } from "./helpers-ELZNDAnv.mjs";
import { r as renderTerminalSafeTable, t as getTerminalTableWidth } from "./table-D2a-pD4_.mjs";
import { u as getScopedChannelsCommandSecretTargets } from "./command-secret-targets-CH2XIeV_.mjs";
import { r as resolveMessageChannelSelection } from "./channel-selection-DBeuWpKq.mjs";
import { n as formatHelpExamples, t as formatDocsHelp } from "./help-format-D2ytHW5E.mjs";
import { i as nullChannelDirectorySelf } from "./directory-adapters-12LLH43Y.mjs";
import { t as parseOptionalPositiveInteger } from "./parse-positive-integer-DrSNo4LV.mjs";
import { t as resolveCommandConfigWithSecrets } from "./command-config-resolution-Bv3V6f3-.mjs";
import { t as parseAccountSelector } from "./account-selector-DYSCYrB8.mjs";
import { t as resolveInstallableChannelPlugin } from "./channel-plugin-resolution-Umf-XLaZ.mjs";
import { t as parseChannelSelector } from "./channel-selector-C0_uoV_u.mjs";
import { r as requireValidConfigForWrite } from "./config-validation-Cy6dkTWs.mjs";
//#region src/cli/directory-cli.ts
const DIRECTORY_LIST_LABELS = {
listPeers: [
"Peers",
"No peers found",
"directory peers"
],
listGroups: [
"Groups",
"No groups found",
"directory groups"
],
listGroupMembers: [
"Group Members",
"No group members found",
"group members listing"
]
};
function formatDirectoryTable(e, t) {
return renderTerminalSafeTable({
width: t,
columns: [{
key: "ID",
header: "ID",
minWidth: 16,
flex: true
}, {
key: "Name",
header: "Name",
minWidth: 18,
flex: true
}],
rows: e.map((e) => ({
ID: e.id,
Name: normalizeOptionalString(e.name) ?? ""
}))
}).trimEnd();
}
function formatDirectoryScope(e, t) {
return `channel ${JSON.stringify(sanitizeTerminalText(e))}, account ${JSON.stringify(sanitizeTerminalText(t))}`;
}
/** Register directory lookup commands and shared channel/account resolution. */
function registerDirectoryCli(e) {
const t = e.command("directory").description("Lookup contact and group IDs (self, peers, groups) for supported chat channels").addHelpText("after", () => `\n${theme.heading("Examples:")}\n${formatHelpExamples([
["openclaw directory self --channel slack", "Show the connected account identity."],
["openclaw directory peers list --channel slack --query \"alice\"", "Search contact/user IDs by name."],
["openclaw directory groups list --channel discord", "List available groups/channels."],
["openclaw directory groups members --channel discord --group-id <id>", "List members for a specific group."]
])}\n${formatDocsHelp("/cli/directory")}`).action(() => {
t.help({ error: true });
});
const withChannel = (e) => e.option("--channel <name>", "Channel (auto when only one is configured)", parseChannelSelector).option("--account <id>", "Account id (accountId)", parseAccountSelector).option("--json", "Output JSON", false);
const resolve = async (e) => {
const t = await requireValidConfigForWrite(defaultRuntime);
if (!t) return null;
const n = applyPluginAutoEnable({
config: t.snapshot.sourceConfig,
env: process.env
});
const r = n.config;
const i = e.channel?.trim();
const a = i ? await resolveInstallableChannelPlugin({
cfg: r,
runtime: defaultRuntime,
rawChannel: i,
allowInstall: true,
preferRegisteredPlugin: true,
supports: (e) => Boolean(e.directory)
}) : null;
if (a?.configChanged || n.changes.length > 0) await commitConfigWithPendingPluginInstalls({
sourceConfig: a?.cfg ?? r,
baseHash: t.snapshot.hash,
writeOptions: t.writeOptions
});
const o = await captureRuntimeConfigAsyncReader()();
const s = i ? {
channel: a?.channelId,
plugin: a?.plugin
} : await resolveMessageChannelSelection({
cfg: o,
channel: e.channel ?? null,
accountResolution: "read_only"
});
const c = s.channel;
const l = s.plugin;
if (!l) throw new Error(`Unsupported channel: ${String(c)}`);
const u = c ?? l.id;
const d = normalizeOptionalString(e.account) || resolveChannelDefaultAccountId({
plugin: l,
cfg: o
});
const f = getScopedChannelsCommandSecretTargets({
config: o,
channel: u,
accountId: d
});
const { effectiveConfig: p } = await resolveCommandConfigWithSecrets({
config: o,
commandName: "directory",
targetIds: f.targetIds,
...f.allowedPaths ? { allowedPaths: f.allowedPaths } : {},
mode: "read_only_operational",
runtime: defaultRuntime
});
return {
cfg: p,
channelId: u,
accountId: d,
plugin: l
};
};
const runDirectoryList = async (e, t) => {
const [n, r, i] = DIRECTORY_LIST_LABELS[t];
const a = parseOptionalPositiveInteger(e.limit ?? void 0, "--limit", ".") ?? null;
const o = normalizeStringifiedOptionalString(e.groupId) ?? "";
if (t === "listGroupMembers" && !o) throw new Error("Missing --group-id");
const s = await resolve(e);
if (!s) return;
const { cfg: c, channelId: l, accountId: u, plugin: d } = s;
const f = {
cfg: c,
accountId: u,
limit: a,
runtime: defaultRuntime
};
const p = t === "listGroupMembers" ? d.directory?.listGroupMembers?.bind(void 0, {
...f,
groupId: o
}) : (t === "listPeers" ? d.directory?.listPeersLive ?? d.directory?.listPeers : d.directory?.listGroupsLive ?? d.directory?.listGroups)?.bind(void 0, {
...f,
query: e.query ?? null
});
if (!p) throw new Error(`Channel ${l} does not support ${i}`);
const m = await p();
if (e.json) {
defaultRuntime.writeJson(m);
return;
}
const h = `${r} for ${t === "listGroupMembers" ? `group ${JSON.stringify(sanitizeTerminalText(o))}, ` : ""}${formatDirectoryScope(l, u)}.`;
if (m.length === 0) {
defaultRuntime.log(theme.muted(h));
return;
}
const g = getTerminalTableWidth();
defaultRuntime.log(`${theme.heading(n)} ${theme.muted(`(${m.length})`)}`);
defaultRuntime.log(formatDirectoryTable(m, g));
};
const runDirectoryAction = async (e, t) => {
try {
await t();
} catch (t) {
if (e.json) throw t;
defaultRuntime.error(danger(formatErrorMessage(t)));
defaultRuntime.exit(1);
}
};
withChannel(t.command("self").description("Show the current account user")).action((e) => runDirectoryAction(e, async () => {
const t = await resolve({
channel: e.channel,
account: e.account
});
if (!t) return;
const { cfg: n, channelId: r, accountId: i, plugin: a } = t;
const o = a.directory?.self;
if (!o) throw new Error(`Channel ${r} does not support directory self`);
const s = await o({
cfg: n,
accountId: i,
runtime: defaultRuntime
});
if (!s) {
const t = o === nullChannelDirectorySelf;
if (e.json) defaultRuntime.writeJson({
status: "unavailable",
channel: r,
accountId: i,
reason: t ? "self-identity-unsupported" : "plugin-returned-no-self-identity"
});
else defaultRuntime.log(theme.muted(t ? `Channel ${JSON.stringify(sanitizeTerminalText(r))} does not expose a self identity.` : `No self identity was returned for ${formatDirectoryScope(r, i)}. Verify the account is configured and authenticated, then retry.`));
return;
}
if (e.json) {
defaultRuntime.writeJson(s);
return;
}
const c = getTerminalTableWidth();
defaultRuntime.log(theme.heading("Self"));
defaultRuntime.log(formatDirectoryTable([s], c));
}));
const n = t.command("peers").description("Peer directory (contacts/users)");
const r = t.command("groups").description("Group directory");
for (const [e, t, i] of [[
n,
"listPeers",
"peers"
], [
r,
"listGroups",
"groups"
]]) withChannel(e.command("list").description(`List ${i}`)).option("--query <text>", "Optional search query").option("--limit <n>", "Limit results").action((e) => runDirectoryAction(e, () => runDirectoryList(e, t)));
withChannel(r.command("members").description("List group members").requiredOption("--group-id <id>", "Group id")).option("--limit <n>", "Limit results").action((e) => runDirectoryAction(e, () => runDirectoryList(e, "listGroupMembers")));
}
//#endregion
export { registerDirectoryCli };