UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

7 lines • 15.5 kB
import"./src-0ci69Prg.mjs";import{t as expectDefined}from"./expect-DkJCbmLj.mjs";import{r as defaultRuntime}from"./runtime-DIcLIHcp.mjs";import{o as getAsyncWorkSignal}from"./async-work-scope-DBcxYU4O.mjs";import{r as terminalText}from"./safe-text-B_QTgn0s.mjs";import{a as displayPath}from"./utils-Dlk0IYAa.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import"./session-key-BPgKfU2m.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{A as tryResolveLegacyCompatibilityAgentId,_ as resolveDefaultAgentId,f as resolveAgentWorkspaceDir,h as resolveConfiguredAgentId}from"./agent-scope-config-CG9CFpGX.mjs";import{i as GATEWAY_CLIENT_NAMES,r as GATEWAY_CLIENT_MODES}from"./client-info-Dr3-kuD1.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{t as captureRuntimeConfigAsyncReader}from"./io.runtime-BvSeVFIY.mjs";import{a as transformConfigFile}from"./mutate-DcH8aT_4.mjs";import"./config-DkZ8y8Gv.mjs";import{r as theme}from"./theme-DS2CtI9X.mjs";import{t as summarizeStringEntries}from"./string-sample-Bbl8b2yp.mjs";import{n as loadGatewayStartupPluginPlanWithMetadata}from"./gateway-startup-plugin-loader-DRGYPMGh.mjs";import"./channel-plugin-ids--iuNYdtE.mjs";import{r as resolveHookEntries}from"./policy-Vh7w_DtI.mjs";import{t as ExpectedCliError}from"./expected-cli-error-oDVmXYil.mjs";import{d as rethrowExpectedCliError,r as formatCliJsonFailure}from"./failure-output-Gn9zHEk3.mjs";import{n as requestExitAfterOneShotOutput}from"./one-shot-exit-LLy48Ehj.mjs";import{i as canFallbackToImplicitLocalGateway}from"./gateway-rpc-17pTfL8i.mjs";import{t as runWithLocalStateOwner}from"./local-state-owner-fjzTarAw.mjs";import{n as decorativePrefix,t as decorativeEmoji}from"./decorative-emoji-pSMDjFKZ.mjs";import{t as resolveOptionFromCommand}from"./cli-utils-Dm67QQ71.mjs";import{t as formatDocsHelp}from"./help-format-DLfgiheF.mjs";import{c as withPluginDiagnosticsReport}from"./status-BHzK174N.mjs";import{t as loadWorkspaceHookEntries}from"./workspace-BN88LYQB.mjs";import{t as buildWorkspaceHookStatus}from"./hooks-status-B5_drx-U.mjs";import{t as runNativeHookRelayCli}from"./native-hook-relay-cli-C4F2OVNs.mjs";import{n as formatCliStatusTable,t as formatCliRequirements}from"./skills-hooks-cli.format-CpV-UrOm.mjs"; //!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(` `)}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(` `)}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=getAsyncWorkSignal();const r=await captureRuntimeConfigAsyncReader({skipPluginValidation:true})();const i=resolveHooksReportTarget(r,e);const{callGateway:a}=await import(`./call-CggG9h6i.mjs`);let o;try{o=await a({config:r,method:`hooks.status`,signal:n,params:{agentId:i.agentId},timeoutMs:GATEWAY_HOOKS_STATUS_TIMEOUT_MS,clientName:GATEWAY_CLIENT_NAMES.CLI,mode:GATEWAY_CLIENT_MODES.CLI})}catch(e){if(n?.aborted)return;if(!await canFallbackToImplicitLocalGateway({config:r,error:e,legacyMethod:`hooks.status`,legacyAgentId:true}))throw e;return withHooksReport(r,i,t)}return n?.aborted?void 0:t(o)}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)}function hooksCliFailure(e){const t=`${theme.error(`Error:`)} ${e.split(` `).map(e=>terminalText`${e}`).join(` `)}`;return new ExpectedCliError({message:e,humanOutput:t,machineOutput:e})}async function runOneShotHooksCliAction(e,t=`command`){const n=await e().catch(e=>{rethrowExpectedCliError(e);const n=hooksCliFailure(formatErrorMessage(e));if(t===`root`)throw n;defaultRuntime.error(n.humanOutput);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 hooksCliFailure(`--agent must not be blank`);if(r&&n!==t&&!(/* @__PURE__ */ new Set([`list`,`info`,`check`,`enable`,`disable`])).has(n.name()))throw hooksCliFailure(`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);const i=await loadHooksReport(resolveOptionFromCommand(n,`agent`),n=>e(n,{...t,json:r}));if(i!==void 0)writeHooksOutput(i,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}});if(i===void 0)return;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-u1a1aVgu.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-jfpSeCQN.mjs`);defaultRuntime.log(theme.warn("`openclaw hooks update` is deprecated; use `openclaw plugins update`."));await n({ids:e?[e]:[],opts:t})});t.action(n)}export{registerHooksCli};