openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
264 lines (263 loc) • 10.6 kB
JavaScript
import { c as normalizeOptionalLowercaseString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import "./utils-C8YECn2Q.mjs";
import { d as withPluginRuntimeRegistryScope } from "./gateway-request-scope-BvvDhs5D.mjs";
import { _ as wrapCurrentPluginInstance } from "./plugin-instance-scope-oezVdCr2.mjs";
import { Q as getPluginCommandExecutionCount, p as getPluginRegistrationContext, v as requireActivePluginRegistry } from "./runtime-ezCEpumg.mjs";
import { f as isOperatorScope } from "./operator-scopes-CULmYfyY.mjs";
import { n as normalizeAgentPromptSurfaceKind } from "./agent-prompt-surface-kind-Pc74Jn6j.mjs";
import "./command-registry-state-D8aXLQW8.mjs";
//#region src/plugins/plugin-command.types.ts
const AGENT_PROMPT_SURFACE_KINDS = [
"openclaw_main",
"pi_main",
"codex_app_server",
"cli_backend",
"acp_backend",
"subagent"
];
//#endregion
//#region src/plugins/command-registration.ts
/**
* Reserved command names that plugins cannot override (built-in commands).
*
* Constructed lazily inside validateCommandName to avoid TDZ errors: the
* bundler can place this module's body after call sites within the same
* output chunk, so any module-level const/let would be uninitialized when
* first accessed during plugin registration.
*/
let reservedCommands;
let agentPromptSurfaces;
function hasExactKeys(e, t) {
const n = Object.keys(e);
return n.length === t.length && n.every((e) => t.includes(e));
}
function validateNonemptyString(e, t) {
if (typeof e !== "string") return `${t} must be a string`;
return e.trim() ? null : `${t} cannot be empty`;
}
function getReservedCommands() {
reservedCommands ??= /* @__PURE__ */ new Set([
"help",
"commands",
"status",
"diagnostics",
"codex",
"whoami",
"context",
"btw",
"stop",
"restart",
"reset",
"new",
"compact",
"config",
"debug",
"allowlist",
"activation",
"skill",
"learn",
"loop",
"subagents",
"kill",
"steer",
"tell",
"model",
"models",
"queue",
"send",
"bash",
"exec",
"think",
"verbose",
"reasoning",
"elevated",
"usage"
]);
return reservedCommands;
}
function isReservedCommandName(e) {
const t = normalizeOptionalLowercaseString(e) ?? "";
return Boolean(t && getReservedCommands().has(t));
}
function validateCommandName(e, t) {
const n = normalizeOptionalLowercaseString(e) ?? "";
if (!n) return "Command name cannot be empty";
if (!/^[a-z][a-z0-9_-]*$/.test(n)) return "Command name must start with a letter and contain only letters, numbers, hyphens, and underscores";
if (!t?.allowReservedCommandNames && getReservedCommands().has(n)) return `Command name "${n}" is reserved by a built-in command`;
return null;
}
const commandCapabilityRules = {
subagents: {
requireAuth: true,
manifestContract: true
},
models: {
requireAuth: false,
manifestContract: false
},
scheduledTurns: {
requireAuth: true,
manifestContract: true
}
};
function validatePluginCommandDefinition(e, t) {
if (typeof e.handler !== "function") return "Command handler must be a function";
if (typeof e.name !== "string") return "Command name must be a string";
const n = validateNonemptyString(e.description, "Command description");
if (n) return n;
if (e.agentPromptGuidance !== void 0 && !Array.isArray(e.agentPromptGuidance)) return "Agent prompt guidance must be an array of strings or objects";
for (const [t, n] of (e.agentPromptGuidance ?? []).entries()) {
const e = validateAgentPromptGuidance(t, n);
if (e) return e;
}
if (e.runtimeCapabilities !== void 0) {
if (!Array.isArray(e.runtimeCapabilities) || e.runtimeCapabilities.some((e) => typeof e !== "string" || !Object.hasOwn(commandCapabilityRules, e))) return "Command runtimeCapabilities must contain supported capability names";
if (e.runtimeCapabilities.some((e) => commandCapabilityRules[e].requireAuth) && e.requireAuth !== true) return "Command runtime capabilities require requireAuth: true";
if (e.runtimeCapabilities.includes("scheduledTurns") && !e.runtimeCapabilities.includes("subagents")) return "Scheduled command turns require the subagents runtime capability";
}
if (e.requiredScopes !== void 0) {
if (!Array.isArray(e.requiredScopes)) return "Command requiredScopes must be an array of operator scopes";
const t = e.requiredScopes.findIndex((e) => !isOperatorScope(e));
if (t !== -1) {
const n = e.requiredScopes[t];
return typeof n === "string" ? `Command requiredScopes contains unknown operator scope: ${n}` : "Command requiredScopes contains unknown operator scope";
}
}
if (e.clientPresentation !== void 0) {
if (!isRecord(e.clientPresentation)) return "Command clientPresentation must be an object";
if (!hasExactKeys(e.clientPresentation, ["when", "action"])) return "Command clientPresentation must contain only when and action";
if (e.clientPresentation.when !== "no-arguments") return "Command clientPresentation when must be \"no-arguments\"";
if (!isRecord(e.clientPresentation.action)) return "Command clientPresentation action must be an object";
if (!hasExactKeys(e.clientPresentation.action, ["kind"])) return "Command clientPresentation action must contain only kind";
if (e.clientPresentation.action.kind !== "device-pairing") return "Command clientPresentation action kind is not supported";
}
if (e.exposeSenderIsOwner !== void 0 && typeof e.exposeSenderIsOwner !== "boolean") return "Command exposeSenderIsOwner must be a boolean";
if (e.channels !== void 0) {
if (!Array.isArray(e.channels)) return "Command channels must be an array of channel ids";
for (const [t, n] of e.channels.entries()) {
const e = validateNonemptyString(n, `Command channel ${t + 1}`);
if (e) return e;
}
}
const r = validateCommandName(e.name, t);
if (r) return r;
if (e.nativeNames !== void 0 && !isRecord(e.nativeNames)) return "Command nativeNames must be an object";
for (const [t, n] of Object.entries(e.nativeNames ?? {})) {
if (typeof n !== "string") continue;
const e = validateCommandName(n);
if (e) return `Native command alias "${t}" invalid: ${e}`;
}
for (const [t, n] of [["nativeProgressMessages", "Native progress message"], ["descriptionLocalizations", "Description localization"]]) {
const r = e[t];
if (r !== void 0 && !isRecord(r)) return `Command ${t} must be an object`;
for (const [e, t] of Object.entries(r ?? {})) {
const r = validateNonemptyString(t, `${n} "${e}"`);
if (r) return r;
}
}
return null;
}
function validateAgentPromptGuidance(e, t) {
const n = `Agent prompt guidance ${e + 1}`;
if (typeof t === "string") return t.trim() ? null : `${n} cannot be empty`;
if (!isRecord(t)) return `${n} must be a string or object`;
const r = validateNonemptyString(t.text, `${n} text`);
if (r) return r;
if (t.surfaces === void 0) return null;
if (!Array.isArray(t.surfaces)) return `${n} surfaces must be an array of prompt surface ids`;
if (t.surfaces.length === 0) return `${n} surfaces cannot be empty`;
for (const [e, r] of t.surfaces.entries()) {
const t = typeof r === "string" ? r.trim() : "";
if (!(agentPromptSurfaces ??= new Set(AGENT_PROMPT_SURFACE_KINDS)).has(t)) {
const t = AGENT_PROMPT_SURFACE_KINDS.join(", ");
return `${n} surface ${e + 1} must be one of: ${t}`;
}
}
return null;
}
function normalizeAgentPromptGuidance(e) {
return e.map((e) => {
if (typeof e === "string") return e.trim();
const t = { text: e.text.trim() };
if (e.surfaces) t.surfaces = e.surfaces.map((e) => normalizeAgentPromptSurfaceKind(e.trim()));
return t;
});
}
function listPluginInvocationKeys(e) {
const t = [e.name, ...Object.values(e.nativeNames ?? {})].flatMap((e) => {
const t = normalizeOptionalLowercaseString(e);
return t ? [`/${t}`] : [];
});
return [...new Set(t)];
}
function registerPluginCommand(e, t, n) {
const r = getPluginRegistrationContext();
return registerPluginCommandInRegistry(r?.registry ?? requireActivePluginRegistry(), r?.pluginId ?? e, t, n);
}
/**
* Read caller-owned runtime capabilities once into a plain array, so validation, manifest
* contract checks and the stored registration all observe the same values.
*/
function snapshotPluginCommandRuntimeCapabilities(e) {
return Array.isArray(e.runtimeCapabilities) ? {
...e,
runtimeCapabilities: Array.from(e.runtimeCapabilities)
} : e;
}
function registerPluginCommandInRegistry(e, t, n, r, i) {
const a = snapshotPluginCommandRuntimeCapabilities(n);
if (getPluginCommandExecutionCount(e) > 0) return {
ok: false,
error: "Cannot register commands while processing is in progress"
};
if (a.ownership === "reserved") return {
ok: false,
error: "Reserved command ownership is only available to bundled reserved commands"
};
const o = validatePluginCommandDefinition(a, r);
if (o) return {
ok: false,
error: o
};
const s = i ?? [];
const c = a.runtimeCapabilities?.filter((e) => commandCapabilityRules[e].manifestContract && !s.some((t) => t === e)) ?? [];
if (c.length > 0) return {
ok: false,
error: `Plugin must declare contracts.commandRuntimeCapabilities for: ${c.join(", ")}`
};
const l = a.name.trim();
const u = a.description.trim();
const d = {
...a,
...a.runtimeCapabilities ? { runtimeCapabilities: Object.freeze([...new Set(a.runtimeCapabilities)]) } : {},
handler: wrapCurrentPluginInstance(a.handler, (t) => (n) => withPluginRuntimeRegistryScope(e, () => t(n))),
name: l,
description: u,
...a.channels ? { channels: a.channels.map((e) => normalizeLowercaseStringOrEmpty(e)) } : {},
...a.agentPromptGuidance ? { agentPromptGuidance: normalizeAgentPromptGuidance(a.agentPromptGuidance) } : {},
...a.clientPresentation ? { clientPresentation: {
when: "no-arguments",
action: { kind: "device-pairing" }
} } : {}
};
const f = listPluginInvocationKeys(d);
for (const t of f) {
const n = e.commands.find((e) => listPluginInvocationKeys(e.command).includes(t));
if (n) return {
ok: false,
error: `Command "${t.slice(1)}" already registered by plugin "${n.pluginId}"`
};
}
e.commands.push({
pluginId: t,
pluginName: r?.pluginName,
rootDir: r?.pluginRoot,
source: r?.pluginRoot ?? "runtime",
command: d,
...r?.allowOwnerStatusExposure === true && d.exposeSenderIsOwner === true ? { trustedOwnerStatusExposure: true } : {}
});
return { ok: true };
}
//#endregion
export { snapshotPluginCommandRuntimeCapabilities as i, registerPluginCommand as n, registerPluginCommandInRegistry as r, isReservedCommandName as t };