UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

6 lines • 13.5 kB
import{c as normalizeOptionalLowercaseString,l as normalizeOptionalString,o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{h as normalizeUniqueSingleOrTrimmedStringList}from"./string-normalization-D_oBUpO3.mjs";import{o as racePromiseWithAbortSignal}from"./src-De06gkOi.mjs";import"./abort-signal-BKkRe6pu.mjs";import{E as walkDirectorySync}from"./fs-safe-Bxzu1j4h.mjs";import{i as hasExplicitPluginConfig,p as resolveEffectivePluginActivationState,u as normalizePluginsConfig}from"./config-state-C1eV6UWf.mjs";import{m as isPathInsideWithRealpath}from"./includes-gwK90iIZ.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{i as listAgentIds}from"./agent-roster-4XrgUgPK.mjs";import{f as resolveAgentWorkspaceDir}from"./agent-scope-config-CG9CFpGX.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{a as mergeBundlePathLists,n as CLAUDE_BUNDLE_MANIFEST_RELATIVE_PATH}from"./bundle-manifest-CeCINH5W.mjs";import{c as readRootJsonObjectSync}from"./json-files-BBQ_0Np0.mjs";import{t as createDedupeCache}from"./dedupe-CsfmSvUH.mjs";import{n as loadPluginManifestRegistryForPluginRegistry}from"./plugin-registry-contributions-C4xBwxaW.mjs";import{n as resolveEffectiveAgentSkillFilter}from"./agent-filter-8R8dGJaG.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{t as warnPluginSdkDeprecation}from"./sdk-deprecation-BDUCyBrU.mjs";import{a as isWorkspaceAccessUnavailableError,i as getAgentWorkspaceAccess}from"./workspace-access-GnBgOJqh.mjs";import{r as resolveSkillFileHost}from"./skill-file-host-D4Dltnrr.mjs";import{r as recordSkillCommandFileHost}from"./skill-command-provenance-35qanYwG.mjs";import{r as logVerbose}from"./globals-l9I53ZKA.mjs";import{o as resolveNodeExecEligibilityAsync}from"./exec-defaults-CnnR7oU0.mjs";import{i as stripFrontmatterBlock,n as parseFrontmatterBlock}from"./frontmatter-juE3lAL1.mjs";import{r as parseFrontmatterBool}from"./frontmatter-PSDPkpAf.mjs";import{n as resolveSkillTelemetrySource}from"./source-BOELnZ7V.mjs";import{t as getRemoteSkillEligibility}from"./remote-C-n5L_-0.mjs";import{n as prepareRemoteSkillConnections}from"./remote-skills-B1qhcfgp.mjs";import{n as resolveSessionSkillExecutionWorkspace}from"./workspace-skill-roots-CD1E2Fy3.mjs";import{t as canonicalizePath}from"./paths-Bavn25Xo.mjs";import{n as isSkillUserInvocable,t as isSkillPromptVisible}from"./skill-index-BJoqmyxP.mjs";import{n as listReservedChatSlashCommandNames}from"./commands-registry.data-IaSrmBM9.mjs";import{_ as sanitizeSkillCommandName}from"./store-3FXuh3B5.mjs";import{i as prepareWorkspaceSkills,o as filterSkillEntries,t as loadVisibleSkills}from"./workspace-skill-loader-OBUxHIUy.mjs";import{n as resolveNodeExecEligibilityLegacy}from"./exec-defaults.legacy-BNH4Yepj.mjs";import fs from"node:fs";import path from"node:path";import{readRegularFileSync}from"@openclaw/fs-safe/advanced"; //!src/skills/discovery/command-specs.ts const skillsLogger=createSubsystemLogger(`skills`);const skillCommandDebugOnce=createDedupeCache({ttlMs:0,maxSize:1024});const BUNDLE_COMMAND_MAX_BYTES=1048576;const bundleCommandsLogger=createSubsystemLogger(`plugins/bundle-commands`);function readClaudeBundleManifest(e){const t=readRootJsonObjectSync({rootDir:e,relativePath:CLAUDE_BUNDLE_MANIFEST_RELATIVE_PATH,boundaryLabel:`plugin root`,rejectHardlinks:true});return t.ok?t.value:{}}function resolveClaudeCommandRootDirs(e){const t=readClaudeBundleManifest(e);const n=normalizeUniqueSingleOrTrimmedStringList(t.commands);const r=fs.existsSync(path.join(e,`commands`))?[`commands`]:[];return mergeBundlePathLists(r,n)}function listMarkdownFilesRecursive(e){return walkDirectorySync(e,{symlinks:`skip`,descend:({name:e})=>!e.startsWith(`.`),include:({kind:e,name:t})=>e===`file`&&!t.startsWith(`.`)&&Boolean(normalizeOptionalLowercaseString(t)?.endsWith(`.md`))}).entries.map(e=>e.path).toSorted((e,t)=>e.localeCompare(t))}function toDefaultCommandName(e,t){return path.relative(e,t).replace(/\.[^.]+$/u,``).split(path.sep).join(`:`)}function toDefaultDescription(e){const t=e.indexOf(` `);return(t<0?e:e.slice(0,t)).trimEnd()}function logSkillCommandOnce(e,t,n,r=`debug`){if(skillCommandDebugOnce.check(e))return;skillsLogger[r](t,n)}function resolveUniqueSkillCommandName(e,t){if(!t.has(e))return e;for(let n=2;n<1e3;n+=1){const r=`_${n}`;const i=`${e.slice(0,32-r.length)}${r}`;if(!t.has(i))return i}return`${e.slice(0,32-2)}_x`}function resolveCommandSkillLoadOptions(e){return{bundledSkillName:e?.bundledSkillName,config:e?.config,managedSkillsDir:e?.managedSkillsDir,bundledSkillsDir:e?.bundledSkillsDir,librarySelections:e?.librarySelections,agentId:e?.agentId,agentSkillFilter:e?.includeAllowlistHidden?`ignore`:`apply`,skillFilter:e?.includeAllowlistHidden?void 0:e?.skillFilter??resolveEffectiveAgentSkillFilter(e?.config,e?.agentId),eligibility:e?.eligibility,pluginMetadataSnapshot:e?.pluginMetadataSnapshot,gatewayOnly:e?.gatewayOnly,executionWorkspaceDir:e?.executionWorkspaceDir,executionWorkspaceFileHost:e?.executionWorkspaceFileHost}}function buildWorkspaceSkillCommandSpecs(e,t){const n=resolveCommandSkillLoadOptions(t);return assembleWorkspaceSkillCommandSpecs(e,t?.entries?filterSkillEntries(t.entries,n):loadVisibleSkills(e,n),t)}async function prepareWorkspaceSkillCommandSpecs(e,t,n){const r=await prepareWorkspaceSkills(e,resolveCommandSkillLoadOptions(t),n);n?.();return assembleWorkspaceSkillCommandSpecs(e,r,t)}function assembleWorkspaceSkillCommandSpecs(e,t,n){const r=t.filter(isSkillUserInvocable);const i=/* @__PURE__ */ new Set;for(const e of n?.reservedNames??[]){i.add(normalizeLowercaseStringOrEmpty(e));i.add(sanitizeSkillCommandName(e))}const a=[];const claimName=(e,t=false)=>{const n=t?`bundle-`:``;const r=t?`bundle`:`skill`;const a=t?`debug`:`trace`;const o=sanitizeSkillCommandName(e);if(o!==e)logSkillCommandOnce(`${n}sanitize:${e}:${o}`,`Sanitized ${r} command name "${e}" to "/${o}".`,{rawName:e,sanitized:`/${o}`},a);const s=resolveUniqueSkillCommandName(o,i);if(s!==o)logSkillCommandOnce(`${n}dedupe:${e}:${s}`,`De-duplicated ${r} command name for "${e}" to "/${s}".`,{rawName:e,deduped:`/${s}`},a);i.add(s);return s};for(const e of r){const t=e.skill.name;const n=claimName(t);const r=e.skill.description?.trim()||t;const i=e.disableCommandDispatch?void 0:(()=>{const readCommandField=t=>e.frontmatter?.[t]??e.frontmatter?.[t.replaceAll(`-`,`_`)]??``;if(normalizeLowercaseStringOrEmpty(readCommandField(`command-dispatch`))!==`tool`)return;const r=readCommandField(`command-tool`).trim();if(!r){logSkillCommandOnce(`dispatch:missingTool:${t}`,`Skill command "/${n}" requested tool dispatch but did not provide command-tool. Ignoring dispatch.`,{skillName:t,command:n});return}const i=normalizeOptionalLowercaseString(readCommandField(`command-arg-mode`));if(i&&i!==`raw`)logSkillCommandOnce(`dispatch:badArgMode:${t}:${i}`,`Skill command "/${n}" requested tool dispatch but has unknown command-arg-mode. Falling back to raw.`,{skillName:t,command:n,argMode:i});return{kind:`tool`,toolName:r,argMode:`raw`}})();const o={name:n,displayName:e.skill.displayName??t,skillFile:canonicalizePath(e.skill.filePath),skillName:t,description:r,modelVisible:isSkillPromptVisible(e),skillSource:resolveSkillTelemetrySource(e.skill),...i?{dispatch:i}:{}};const s=resolveSkillFileHost(e.skill);if(s)recordSkillCommandFileHost(o,s);a.push(o)}if(hasExplicitPluginConfig(n?.config?.plugins)){const t=loadPluginManifestRegistryForPluginRegistry({workspaceDir:e,config:n?.config,includeDisabled:true});const r=normalizePluginsConfig(n?.config?.plugins);for(const e of t.plugins){if(e.format!==`bundle`||e.bundleFormat!==`claude`||!(e.bundleCapabilities??[]).includes(`commands`))continue;if(!resolveEffectivePluginActivationState({id:e.id,origin:e.origin,channelIds:e.channels,config:r,rootConfig:n?.config}).activated)continue;for(const t of resolveClaudeCommandRootDirs(e.rootDir)){const n=path.resolve(e.rootDir,t);if(!fs.existsSync(n))continue;if(!isPathInsideWithRealpath(e.rootDir,n,{requireRealpath:true}))continue;for(const e of listMarkdownFilesRecursive(n)){let t;try{t=readRegularFileSync({filePath:e,maxBytes:BUNDLE_COMMAND_MAX_BYTES}).buffer.toString(`utf-8`)}catch(t){bundleCommandsLogger.warn(`skipping unreadable bundle command file ${e}: ${formatErrorMessage(t)}`);continue}const r=parseFrontmatterBlock(t);if(!parseFrontmatterBool(r[`user-invocable`],true))continue;const i=stripFrontmatterBlock(t);if(!i)continue;const o=normalizeOptionalString(r.name)||toDefaultCommandName(n,e);if(!o)continue;const s=normalizeOptionalString(r.description)||toDefaultDescription(i);a.push({name:claimName(o,true),skillName:o,description:s,modelVisible:false,promptTemplate:i,sourceFilePath:e})}}}}return a} //!src/skills/discovery/chat-commands.ts function resolveWorkspaceSkillCommandOptions(e,t){const n={nodeSkills:t,remote:getRemoteSkillEligibility({advertiseExecNode:t.canExec})};const r=e.executionWorkspaceDir!==void 0?{executionWorkspaceDir:e.executionWorkspaceDir,executionWorkspaceFileHost:e.executionWorkspaceFileHost}:e.sessionEntry?resolveSessionSkillExecutionWorkspace(e.sessionEntry,e.sessionEntry.spawnedCwd):{};return{config:e.cfg,agentId:e.agentId,skillFilter:e.skillFilter,includeAllowlistHidden:e.includeAllowlistHidden,eligibility:n,pluginMetadataSnapshot:e.pluginMetadataSnapshot,librarySelections:e.sessionEntry?.skillLibrarySelections,executionWorkspaceDir:r.executionWorkspaceDir,executionWorkspaceFileHost:r.executionWorkspaceFileHost}}function hasRemoteWorkspace(e){try{return Boolean(getAgentWorkspaceAccess(e,`loadSkills`)?.loadSkills)}catch(e){if(isWorkspaceAccessUnavailableError(e))return true;throw e}}function listSkillCommandsForWorkspace(e){warnPluginSdkDeprecation({family:`skill-command-discovery`,method:`listSkillCommandsForWorkspace`,replacement:`prepareSkillCommandsForWorkspace`});return buildWorkspaceSkillCommandSpecs(e.workspaceDir,{...resolveWorkspaceSkillCommandOptions(e,resolveNodeExecEligibilityLegacy(e)),reservedNames:listReservedChatSlashCommandNames(),gatewayOnly:hasRemoteWorkspace(e.workspaceDir)})}async function prepareSkillCommandsForWorkspace(e,t){t?.();await prepareRemoteSkillConnections();t?.();const n=await resolveNodeExecEligibilityAsync(e);t?.();const r=await prepareWorkspaceSkillCommandSpecs(e.workspaceDir,{...resolveWorkspaceSkillCommandOptions(e,n),reservedNames:listReservedChatSlashCommandNames()},t);t?.();return r}async function prepareBundledSkillCommandForWorkspace(e){await prepareRemoteSkillConnections();const t=await resolveNodeExecEligibilityAsync(e);return(await prepareWorkspaceSkillCommandSpecs(e.workspaceDir,{...resolveWorkspaceSkillCommandOptions(e,t),reservedNames:listReservedChatSlashCommandNames(),bundledSkillName:e.skillName})).find(t=>t.skillSource===`bundled`&&t.skillName.trim().toLowerCase()===e.skillName.trim().toLowerCase())}function finalizeSkillCommands(e){const t=/* @__PURE__ */ new Set;return e.filter(e=>{const n=normalizeOptionalLowercaseString(e.skillName);if(n&&t.has(n))return false;if(n)t.add(n);return true}).toSorted((e,t)=>e.skillName.localeCompare(t.skillName,`en`))}function*resolveAgentSkillCommandWorkspaces(e,t=false){const n=e.agentIds??listAgentIds(e.cfg);const r=n.length===1;const i=[];for(const r of n){const n=resolveAgentWorkspaceDir(e.cfg,r);const a=t?Boolean(getAgentWorkspaceAccess(n,`loadSkills`)?.loadSkills):hasRemoteWorkspace(n);if(!a){if(!fs.existsSync(n)){logVerbose(`Skipping agent "${r}": workspace does not exist: ${n}`);continue}try{fs.realpathSync(n)}catch{logVerbose(`Skipping agent "${r}": cannot resolve workspace: ${n}`);continue}}i.push({agentId:r,workspaceDir:n,gatewayOnly:a&&!t,skillFilter:resolveEffectiveAgentSkillFilter(e.cfg,r)})}for(const{agentId:t,workspaceDir:n,skillFilter:a,gatewayOnly:o}of i)yield{workspaceDir:n,params:{cfg:e.cfg,agentId:t,workspaceDir:n,skillFilter:a,...r?{sessionEntry:e.sessionEntry,sessionKey:e.sessionKey,execOverrides:e.execOverrides,executionWorkspaceDir:e.executionWorkspaceDir,executionWorkspaceFileHost:e.executionWorkspaceFileHost}:{}},gatewayOnly:o}}function appendSkillCommands(e,t,n){for(const r of n){t.add(r.name);e.push(r)}}function listSkillCommandsForAgents(e){warnPluginSdkDeprecation({family:`skill-command-discovery`,method:`listSkillCommandsForAgents`,replacement:`prepareSkillCommandsForAgents`});const t=listReservedChatSlashCommandNames();const n=[];for(const{workspaceDir:r,params:i,gatewayOnly:a}of resolveAgentSkillCommandWorkspaces(e))appendSkillCommands(n,t,buildWorkspaceSkillCommandSpecs(r,{...resolveWorkspaceSkillCommandOptions(i,resolveNodeExecEligibilityLegacy(i)),gatewayOnly:a,reservedNames:t}));return finalizeSkillCommands(n)}async function prepareSkillCommandsForAgents(e){e.signal?.throwIfAborted();await prepareRemoteSkillConnections();e.signal?.throwIfAborted();const t=listReservedChatSlashCommandNames();const n=[];for(const{workspaceDir:r,params:i,gatewayOnly:a}of resolveAgentSkillCommandWorkspaces(e,true)){const o=await resolveNodeExecEligibilityAsync(i);e.signal?.throwIfAborted();const s=await racePromiseWithAbortSignal(prepareWorkspaceSkillCommandSpecs(r,{...resolveWorkspaceSkillCommandOptions(i,o),gatewayOnly:a,reservedNames:t}),e.signal);e.signal?.throwIfAborted();appendSkillCommands(n,t,s)}return finalizeSkillCommands(n)}export{prepareSkillCommandsForWorkspace as a,prepareSkillCommandsForAgents as i,listSkillCommandsForWorkspace as n,prepareBundledSkillCommandForWorkspace as r,listSkillCommandsForAgents as t};