UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

387 lines (386 loc) • 15.3 kB
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { h as normalizeUniqueSingleOrTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs"; import { m as isPathInsideWithRealpath } from "./includes-wjVi5Ymt.mjs"; import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs"; import "./abort-signal-D4Q6SEw7.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { k as walkDirectorySync } from "./fs-safe-BbWvmdVn.mjs"; import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs"; import { f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { i as hasExplicitPluginConfig, p as resolveEffectivePluginActivationState, u as normalizePluginsConfig } from "./config-state-B1JlHgba.mjs"; import { a as mergeBundlePathLists, n as CLAUDE_BUNDLE_MANIFEST_RELATIVE_PATH } from "./bundle-manifest-js7o0H7U.mjs"; import { c as readRootJsonObjectSync } from "./json-files-Cb1h8pYs.mjs"; import { t as createDedupeCache } from "./dedupe-DxT0h2gR.mjs"; import { n as loadPluginManifestRegistryForPluginRegistry } from "./plugin-registry-contributions-iAw3gSDD.mjs"; import { n as resolveEffectiveAgentSkillFilter } from "./agent-filter-B8NbzRsF.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { t as warnPluginSdkDeprecation } from "./sdk-deprecation-D5N9acnu.mjs"; import { r as resolveSkillFileHost } from "./skill-file-host-DYVvMKod.mjs"; import { r as recordSkillCommandFileHost } from "./skill-command-provenance-M2bVzkat.mjs"; import { r as logVerbose } from "./globals-CgepmiqE.mjs"; import { o as resolveNodeExecEligibilityAsync } from "./exec-defaults-BaVI-sJD.mjs"; import { i as stripFrontmatterBlock, n as parseFrontmatterBlock } from "./frontmatter-CLR6jwh6.mjs"; import { r as parseFrontmatterBool } from "./frontmatter-DZeA7qC4.mjs"; import { n as resolveSkillTelemetrySource } from "./source-CoV2hxdc.mjs"; import { a as isWorkspaceAccessUnavailableError, i as getAgentWorkspaceAccess } from "./workspace-access-CnjZBg1i.mjs"; import { t as getRemoteSkillEligibility } from "./remote-BFNOi3gh.mjs"; import { n as prepareRemoteSkillConnections } from "./remote-skills-DesALNDd.mjs"; import { t as canonicalizePath } from "./paths-CS5Q7ATF.mjs"; import { n as isSkillUserInvocable, t as isSkillPromptVisible } from "./skill-index-CXWWhRXT.mjs"; import { n as listReservedChatSlashCommandNames } from "./commands-registry.data-CoxL3Db3.mjs"; import { _ as sanitizeSkillCommandName } from "./store-COiMIkwC.mjs"; import { i as prepareWorkspaceSkills, o as filterSkillEntries, t as loadVisibleSkills } from "./workspace-skill-loader-BvWyDxJi.mjs"; import { n as resolveNodeExecEligibilityLegacy } from "./exec-defaults.legacy-CMYOpmjT.mjs"; import fs from "node:fs"; import path from "node:path"; import { readRegularFileSync } from "@openclaw/fs-safe/advanced"; //#region 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("\n"); 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 }; } /** Builds user-invocable slash command specs for synchronous SDK consumers. */ function buildWorkspaceSkillCommandSpecs(e, t) { const n = resolveCommandSkillLoadOptions(t); return assembleWorkspaceSkillCommandSpecs(e, t?.entries ? filterSkillEntries(t.entries, n) : loadVisibleSkills(e, n), t); } /** Prepares eligibility once before sharing the synchronous command assembly. */ 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; } //#endregion //#region src/skills/discovery/chat-commands.ts function resolveWorkspaceSkillCommandOptions(e, t) { const n = { nodeSkills: t, remote: getRemoteSkillEligibility({ advertiseExecNode: t.canExec }) }; return { config: e.cfg, agentId: e.agentId, skillFilter: e.skillFilter, includeAllowlistHidden: e.includeAllowlistHidden, eligibility: n, pluginMetadataSnapshot: e.pluginMetadataSnapshot, librarySelections: e.sessionEntry?.skillLibrarySelections }; } function hasRemoteWorkspace(e) { try { return Boolean(getAgentWorkspaceAccess(e, "loadSkills")?.loadSkills); } catch (e) { if (isWorkspaceAccessUnavailableError(e)) return true; throw e; } } /** @deprecated Await prepareSkillCommandsForWorkspace; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */ 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; } /** Resolve Gateway-bundled commands with the active Harness eligibility checks. */ 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 } : {} }, gatewayOnly: o }; } function appendSkillCommands(e, t, n) { for (const r of n) { t.add(r.name); e.push(r); } } /** @deprecated Await prepareSkillCommandsForAgents; final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */ 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); } //#endregion export { prepareSkillCommandsForWorkspace as a, prepareSkillCommandsForAgents as i, listSkillCommandsForWorkspace as n, prepareBundledSkillCommandForWorkspace as r, listSkillCommandsForAgents as t };