UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

398 lines (397 loc) • 17.5 kB
import "./src-H3RMXyFL.mjs"; import { t as expectDefined } from "./expect-DDakjvvQ.mjs"; import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { r as terminalText } from "./safe-text-C80HAQ2e.mjs"; import { a as displayPath } from "./utils-C8YECn2Q.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import "./session-key-CqAyZeVk.mjs"; import { A as tryResolveLegacyCompatibilityAgentId, _ as resolveDefaultAgentId, f as resolveAgentWorkspaceDir, h as resolveConfiguredAgentId } from "./agent-scope-config-DmXgFGKP.mjs"; import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES } from "./client-info-Cm1BcrMm.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { t as captureRuntimeConfigAsyncReader } from "./io.runtime-DsJ2dLCQ.mjs"; import { a as transformConfigFile } from "./mutate-DhAOi0-2.mjs"; import "./config-CMA-J084.mjs"; import { r as theme } from "./theme-BOI0xyRZ.mjs"; import { t as summarizeStringEntries } from "./string-sample-DyCB5Vr0.mjs"; import { r as resolveHookEntries } from "./policy-9WWlcycM.mjs"; import { n as loadGatewayStartupPluginPlanWithMetadata } from "./gateway-startup-plugin-loader-CvtjWt_C.mjs"; import "./channel-plugin-ids-DZDzcpUB.mjs"; import { r as formatCliJsonFailure, t as ExpectedCliError, u as rethrowExpectedCliError } from "./failure-output-DVVDqwuu.mjs"; import { n as requestExitAfterOneShotOutput } from "./one-shot-exit-DkbGSQD5.mjs"; import { i as canFallbackToImplicitLocalGateway } from "./gateway-rpc-CxUN2f1a.mjs"; import { t as runWithLocalStateOwner } from "./local-state-owner-DTl7OHpC.mjs"; import { n as decorativePrefix, t as decorativeEmoji } from "./decorative-emoji-CIP77smZ.mjs"; import { t as resolveOptionFromCommand } from "./cli-utils-BPmaaZlG.mjs"; import { t as formatDocsHelp } from "./help-format-D2ytHW5E.mjs"; import { c as withPluginDiagnosticsReport } from "./status-dU3VsouW.mjs"; import { t as loadWorkspaceHookEntries } from "./workspace-DyN-emhI.mjs"; import { t as buildWorkspaceHookStatus } from "./hooks-status-BhCdWZTN.mjs"; import { t as runNativeHookRelayCli } from "./native-hook-relay-cli-CJNH2dZE.mjs"; import { n as formatCliStatusTable, t as formatCliRequirements } from "./skills-hooks-cli.format-CCWlEumT.mjs"; //#region src/cli/hooks-cli.ts function formatHookStatus(e, t = false) { if (e.loadable) return theme.success(t ? "✓ Ready" : "✓ ready"); if (!e.enabledByConfig) return theme.warn(decorativePrefix("⏸", t ? "Disabled" : "disabled")); const n = e.blockedReason && e.blockedReason !== "missing requirements" ? e.blockedReason : t ? "missing requirements" : "missing"; return theme.error(terminalText`✗ ${t ? `${n.charAt(0).toUpperCase()}${n.slice(1)}` : n}`); } const HOOK_REQUIREMENT_GROUPS = [ ["bins", "Binaries"], ["anyBins", "Any binary"], ["env", "Environment"], ["config", "Config"], ["os", "OS"] ]; function formatHookMissingRequirements(e, t) { const formatEntries = (e) => t === void 0 ? e.join(", ") : summarizeStringEntries({ entries: e, limit: t }); return HOOK_REQUIREMENT_GROUPS.filter(([t]) => e.missing[t].length > 0).map(([t]) => `${t}: ${formatEntries(e.missing[t])}`); } function formatHookMissingSummary(e, t) { const n = formatHookMissingRequirements(e, t); if (e.enabledByConfig && e.blockedReason && e.blockedReason !== "missing requirements") n.unshift(e.blockedReason); return n.join("; "); } function formatHooksList(e, t) { const n = t.eligible ? e.hooks.filter((e) => e.loadable) : e.hooks; if (t.json) { const t = { workspaceDir: e.workspaceDir, managedHooksDir: e.managedHooksDir, hooks: n.map((e) => ({ name: e.name, description: e.description, emoji: e.emoji, eligible: e.loadable, disabled: !e.enabledByConfig, enabledByConfig: e.enabledByConfig, requirementsSatisfied: e.requirementsSatisfied, loadable: e.loadable, blockedReason: e.blockedReason, source: e.source, pluginId: e.pluginId, events: e.events, unknownEvents: e.unknownEvents, homepage: e.homepage, missing: e.missing, managedByPlugin: e.managedByPlugin })) }; return JSON.stringify(t, null, 2); } if (n.length === 0) return t.eligible ? `No eligible hooks found. Run \`${formatCliCommand("openclaw hooks list")}\` to see all hooks.` : "No hooks found."; return formatCliStatusTable({ title: "Hooks", ready: n.filter((e) => e.loadable).length, nameColumn: { key: "Hook", header: "Hook", minWidth: 18, flex: true }, sourceColumn: { key: "Source", header: "Source", minWidth: 12, flex: true }, verbose: t.verbose, rows: n.map((e) => { const n = terminalText`${e.emoji ?? decorativeEmoji("🔗")}`; const r = theme.command(terminalText`${e.name}`); return { Status: formatHookStatus(e), Hook: n ? `${n} ${r}` : r, Description: theme.muted(terminalText`${e.description}`), Source: terminalText`${e.managedByPlugin ? `plugin:${e.pluginId ?? "unknown"}` : e.source}`, Missing: t.verbose ? theme.warn(terminalText`${formatHookMissingSummary(e)}`) : "" }; }) }); } function formatHookInfo(e, t, n) { if (!e) { if (n.json) { const e = formatCliJsonFailure(`Hook "${t}" not found.`); return JSON.stringify({ ...e, hook: t }, null, 2); } return terminalText`Hook "${t}" not found. Run \`${formatCliCommand("openclaw hooks list")}\` to see available hooks.`; } if (n.json) return JSON.stringify({ ...e, eligible: e.loadable, disabled: !e.enabledByConfig }, null, 2); const r = terminalText`${e.emoji ?? decorativeEmoji("🔗")}`; const i = [ `${r ? `${r} ` : ""}${theme.heading(terminalText`${e.name}`)} ${formatHookStatus(e, true)}`, "", terminalText`${e.description}`, "", theme.heading("Details:"), `${theme.muted(" Source:")} ${terminalText`${e.source}${e.managedByPlugin ? ` (${e.pluginId ?? "unknown"})` : ""}`}`, `${theme.muted(" Path:")} ${displayPath(e.filePath)}`, `${theme.muted(" Handler:")} ${displayPath(e.handlerPath)}` ]; if (e.homepage) i.push(`${theme.muted(" Homepage:")} ${terminalText`${e.homepage}`}`); if (e.events.length > 0) i.push(`${theme.muted(" Events:")} ${terminalText`${e.events.join(", ")}`}`); if (e.unknownEvents.length > 0) i.push(theme.warn(terminalText` ⚠ Event${e.unknownEvents.length === 1 ? "" : "s"} not emitted by core (likely typo): ${e.unknownEvents.join(", ")}`)); if (e.managedByPlugin) i.push(theme.muted(" Managed by plugin; enable/disable via hooks CLI not available.")); if (e.blockedReason) i.push(`${theme.muted(" Blocked reason:")} ${terminalText`${e.blockedReason}`}`); i.push(...formatCliRequirements(e, HOOK_REQUIREMENT_GROUPS, e.configChecks)); return i.join("\n"); } function formatHooksCheck(e, t) { const n = e.hooks.filter((e) => e.loadable); const r = e.hooks.filter((e) => !e.loadable); if (t.json) return JSON.stringify({ total: e.hooks.length, eligible: n.length, notEligible: r.length, hooks: { eligible: n.map((e) => e.name), notEligible: r.map((e) => ({ name: e.name, blockedReason: e.blockedReason, missing: e.missing })) } }, null, 2); const i = [ theme.heading("Hooks Status"), "", `${theme.muted("Total hooks:")} ${e.hooks.length}`, `${theme.success("Ready:")} ${n.length}`, `${theme.warn("Not ready:")} ${r.length}` ]; if (r.length > 0) { i.push(""); i.push(theme.heading("Hooks not ready:")); for (const e of r) { const t = formatHookMissingRequirements(e); if (e.blockedReason && e.blockedReason !== "missing requirements") t.unshift(e.blockedReason); const n = e.emoji ?? decorativeEmoji("🔗"); i.push(terminalText` ${n ? `${n} ` : ""}${e.name} - ${t.join("; ")}`); } } return i.join("\n"); } const GATEWAY_HOOKS_STATUS_TIMEOUT_MS = 1500; function resolveHooksReportTarget(e, t) { const n = t?.trim(); if (t !== void 0 && !n) throw new Error("--agent must not be blank"); const r = n ? normalizeAgentId(n) : void 0; if (r) resolveConfiguredAgentId(e, r); const i = r ?? tryResolveLegacyCompatibilityAgentId(e) ?? resolveDefaultAgentId(e, { surface: "hooks status reporting", hint: "Pass --agent <id> to select a configured agent." }); return { agentId: i, workspaceDir: resolveAgentWorkspaceDir(e, i) }; } async function withHooksReport(e, t, n) { const r = t.workspaceDir; const i = loadWorkspaceHookEntries(r, { config: e }); const a = loadGatewayStartupPluginPlanWithMetadata({ config: e, workspaceDir: r, env: process.env }); return withPluginDiagnosticsReport({ config: e, workspaceDir: r, onlyPluginIds: a.plan.pluginIds, metadataSnapshot: a.metadataSnapshot }, (t) => { const a = t.hooks.map((e) => e.entry); const o = resolveHookEntries([...a, ...i]); return n(buildWorkspaceHookStatus(r, { config: e, entries: o })); }); } async function loadHooksReport(e, t) { const n = await captureRuntimeConfigAsyncReader({ skipPluginValidation: true })(); const r = resolveHooksReportTarget(n, e); const { callGateway: i } = await import("./call-CT5jlfNe.mjs"); let a; try { a = await i({ config: n, method: "hooks.status", params: { agentId: r.agentId }, timeoutMs: GATEWAY_HOOKS_STATUS_TIMEOUT_MS, clientName: GATEWAY_CLIENT_NAMES.CLI, mode: GATEWAY_CLIENT_MODES.CLI }); } catch (e) { if (!await canFallbackToImplicitLocalGateway({ config: n, error: e, legacyMethod: "hooks.status", legacyAgentId: true })) throw e; return withHooksReport(n, r, t); } return t(a); } function resolveHookSelection(e, t) { const n = e.hooks.filter((e) => e.name === t); const r = n.length > 0 ? n : e.hooks.filter((e) => e.hookKey === t); if (r.length > 1) { const e = summarizeStringEntries({ entries: r.map((e) => `${e.name} (${e.hookKey})`), limit: 5 }); throw new Error(`Hook "${t}" is ambiguous; matches: ${e}. Use a unique hook name or hook key.`); } return r[0]; } function writeHooksOutput(e, t) { if (t) { defaultRuntime.writeStdout(e); return; } defaultRuntime.log(e); } async function runOneShotHooksCliAction(e, t = "command") { const n = await e().catch((e) => { rethrowExpectedCliError(e); const n = formatErrorMessage(e); const r = `${theme.error("Error:")} ${n.split("\n").map((e) => terminalText`${e}`).join("\n")}`; if (t === "root") throw new ExpectedCliError({ message: n, humanOutput: r, machineOutput: n }); defaultRuntime.error(r); defaultRuntime.exit(1); throw new Error("unreachable"); }); requestExitAfterOneShotOutput(defaultRuntime, typeof n === "number" ? n : 0); } function registerHooksCli(e) { const t = e.command("hooks").description("Manage internal agent hooks").option("--agent <id>", "Agent id to inspect").option("--json", "Output as JSON", false).addHelpText("after", () => formatDocsHelp("/cli/hooks")); const hasJsonOutput = (e) => Boolean(e?.json || t.opts().json); t.hook("preAction", (e, n) => { const r = t.opts().agent; if (r !== void 0 && !r.trim()) throw new Error("--agent must not be blank"); if (r && n !== t && !(/* @__PURE__ */ new Set([ "list", "info", "check", "enable", "disable" ])).has(n.name())) throw new Error(`openclaw hooks ${n.name()} does not support --agent; the option only selects an owner for read-only hook reports.`); }); const reportAction = (e) => (t, n) => runOneShotHooksCliAction(async () => { const r = hasJsonOutput(t); writeHooksOutput(await loadHooksReport(resolveOptionFromCommand(n, "agent"), (n) => e(n, { ...t, json: r })), r); }, "root"); const n = reportAction(formatHooksList); t.command("list").description("List all hooks").option("--agent <id>", "Agent id to inspect").option("--eligible", "Show only eligible hooks", false).option("--json", "Output as JSON", false).option("-v, --verbose", "Show more details including missing requirements", false).action(n); t.command("info <name>").description("Show detailed information about a hook").option("--agent <id>", "Agent id to inspect").option("--json", "Output as JSON", false).action(async (e, t, n) => runOneShotHooksCliAction(async () => { const r = hasJsonOutput(t); const i = await loadHooksReport(resolveOptionFromCommand(n, "agent"), (n) => { const i = resolveHookSelection(n, e); return { output: formatHookInfo(i, e, { ...t, json: r }), exitCode: i ? 0 : 1 }; }); writeHooksOutput(i.output, r); return i.exitCode; }, "root")); t.command("check").description("Check hooks eligibility status").option("--agent <id>", "Agent id to inspect").option("--json", "Output as JSON", false).action(reportAction(formatHooksCheck)); for (const e of [true, false]) t.command(`${e ? "enable" : "disable"} <name>`).description(e ? "Enable a hook" : "Disable a hook").option("--agent <id>", "Agent id whose workspace to inspect").action(async (t, n, r) => runOneShotHooksCliAction(async () => { const n = resolveOptionFromCommand(r, "agent"); return await runWithLocalStateOwner({ method: `hooks.${e ? "enable" : "disable"}`, params: {}, target: `hook "${t}"`, onForeignOwner: "refuse", runLocal: async ({ assertCurrent: r }) => { const i = await transformConfigFile({ writeOptions: { assertConfigPathForWrite: r }, transform: (r) => withHooksReport(r, resolveHooksReportTarget(r, n), (n) => { const i = resolveHookSelection(n, t); if (!i) throw new Error(`Hook "${t}" not found. Run \`${formatCliCommand("openclaw hooks list")}\` to see available hooks.`); if (i.managedByPlugin) throw new Error(`Hook "${t}" is managed by plugin "${i.pluginId ?? "unknown"}" and cannot be enabled/disabled.`); if (e && !i.requirementsSatisfied) { const e = formatHookMissingSummary(i, 3); const n = i.install.length ? ` Install options: ${summarizeStringEntries({ entries: i.install.map((e) => e.label), limit: 3 })}.` : ""; throw new Error(`Hook "${t}" is not eligible; missing ${e}.${n} Run \`${formatCliCommand(`openclaw hooks info ${t}`)}\` for details.`); } const a = { ...r.hooks?.internal?.entries }; a[i.hookKey] = { ...a[i.hookKey], enabled: e }; return { nextConfig: { ...r, hooks: { ...r.hooks, internal: { ...r.hooks?.internal, ...e ? { enabled: true } : {}, entries: a } } }, result: { name: i.name, emoji: i.emoji } }; }) }); const a = expectDefined(i.result, "hook mutation result"); const o = e ? `${theme.success("✓")} Enabled hook:` : theme.warn(decorativePrefix("⏸", "Disabled hook:")); const s = a.emoji ? `${terminalText`${a.emoji} `}${theme.command(terminalText`${a.name}`)}` : decorativePrefix("🔗", theme.command(terminalText`${a.name}`)); defaultRuntime.log(`${o} ${s}`); } }); })); t.command("relay", { hidden: true }).description("Internal native harness hook relay").requiredOption("--provider <provider>", "Native harness provider").requiredOption("--relay-id <id>", "Native hook relay id").option("--state-db <path>", "Shared state database path").option("--remote-credential <path>", "Dedicated harness relay credential file").option("--generation <generation>", "Native hook relay registration generation").requiredOption("--event <event>", "Native hook event").option("--pre-tool-use-unavailable <mode>", "PreToolUse fallback mode when the originating relay is unavailable").option("--timeout <ms>", "Gateway timeout in ms", "5000").action(async (e) => runOneShotHooksCliAction(() => runNativeHookRelayCli(e))); t.command("install").description("Deprecated: install a hook pack via `openclaw plugins install`").argument("<path-or-spec>", "Path to a hook pack or npm package spec").option("-l, --link", "Link a local path instead of copying", false).option("--pin", "Record npm installs as exact resolved <name>@<version>", false).option("--force", "Confirm non-ClawHub sources and overwrite an existing hook pack", false).option("--acknowledge-install-policy-warning", "Acknowledge security.installPolicy warnings without prompting; blocks and failures remain terminal", false).action(async (e, t) => { const { runPluginInstallCommand: n } = await import("./plugins-install-command-CU_KIyyO.mjs"); defaultRuntime.log(theme.warn("`openclaw hooks install` is deprecated; use `openclaw plugins install`.")); await n({ raw: e, opts: t, allowInstallPolicyWarningPrompt: true, invalidateRuntimeCache: false }); }); t.command("update").description("Deprecated: update hook packs via `openclaw plugins update`").argument("[id]", "Hook pack id (omit with --all)").option("--all", "Update all tracked hooks", false).option("--dry-run", "Show what would change without writing", false).option("--acknowledge-install-policy-warning", "Acknowledge security.installPolicy warnings without prompting; blocks and failures remain terminal", false).action(async (e, t) => { const { runPluginUpdateCommand: n } = await import("./plugins-update-command-CxoUyUxO.mjs"); defaultRuntime.log(theme.warn("`openclaw hooks update` is deprecated; use `openclaw plugins update`.")); await n({ ids: e ? [e] : [], opts: t }); }); t.action(n); } //#endregion export { registerHooksCli };