openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
506 lines (505 loc) • 21.7 kB
JavaScript
import { r as resolveGlobalMap } from "./global-singleton-D7yf05nR.mjs";
import { n as ignoreMissingPath } from "./errno-DFcoqIT9.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { d as pathExists, w as root } from "./fs-safe-BbWvmdVn.mjs";
import { f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { n as listDirectoryTreeStrict } from "./directory-walk-C8lZf9Dd.mjs";
import { C as registerOpenClawStatePathCacheInvalidation } from "./openclaw-state-db-cache-CkwtTqzF.mjs";
import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import { n as executeOpenClawStateWorker } from "./openclaw-state-worker-store-2LoAv_8B.mjs";
import { t as KeyedAsyncQueue } from "./keyed-async-queue-DewLnYvW.mjs";
import { t as parseSkillFrontmatter } from "./frontmatter-CetkUJdW.mjs";
import { n as resolveWorkshopSkillsDir } from "./skills-root-DFNOcDAR.mjs";
import { r as removePathWithinRoot } from "./fs-safe-remove-mw1k_RwN.mjs";
import { t as resolveSkillWorkshopConfig } from "./config-DO1phBEt.mjs";
import { a as readWorkspaceSkillFile, n as assertInsideSkillsRoot, o as readWorkspaceSupportFile, r as normalizeWorkspaceSkillSupportPath, t as MAX_WORKSPACE_SKILL_SUPPORT_FILE_BYTES } from "./workspace-skill-write-DINtvFgf.mjs";
import { i as snapshotCommittedSkillArtifactBestEffort, n as hasCommittedSkillChangeHooks, t as dispatchCommittedSkillChangeBestEffort } from "./skill-change-hook-Cfaf7WZN.mjs";
import { i as scanSupportFilePath, r as scanSkillFile } from "./skill-bundle-scan-QSSm31Zc.mjs";
import { i as snapshotSkill, n as listVersions, r as pruneVersions } from "./skill-versions-cYAE4ZnO.mjs";
import path from "node:path";
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
//#region src/skills/workshop/changes.ts
const MAX_CHANGES_LIMIT = 500;
const stores = resolveGlobalMap(Symbol.for("openclaw.skillWorkshopChanges"), "close-and-restart");
registerOpenClawStatePathCacheInvalidation(stores);
function captureStore() {
const e = captureOpenClawStateWorkerContext();
const t = e.admission.coordinationKey;
let n = stores.get(t);
if (!n) {
n = {
path: e.admission.identity.canonicalPath,
agents: /* @__PURE__ */ new Map()
};
stores.set(t, n);
}
return {
context: e,
store: n
};
}
async function recordWorkshopChange(e) {
const { context: t, store: n } = captureStore();
n.agents.delete(e.agentId);
try {
await executeOpenClawStateWorker(t, {
type: "skills.workshop.changes.record",
input: e
});
} finally {
n.agents.delete(e.agentId);
}
}
async function listWorkshopChanges(e, t = {}) {
const { context: n, store: r } = captureStore();
let i = r.agents.get(e);
if (!i) {
if (r.agents.size >= 128) r.agents.delete(r.agents.keys().next().value);
i = executeOpenClawStateWorker(n, {
type: "skills.workshop.changes.list",
input: {
agentId: e,
limit: MAX_CHANGES_LIMIT
}
});
r.agents.set(e, i);
}
let a;
try {
a = await i;
} catch (t) {
if (r.agents.get(e) === i) r.agents.delete(e);
throw t;
}
return structuredClone(a.filter((e) => (t.beforeMs === void 0 || e.createdAtMs < t.beforeMs) && (!t.runId || e.runId === t.runId)).slice(0, Math.min(Math.max(Math.trunc(t.limit ?? 50), 1), MAX_CHANGES_LIMIT)));
}
//#endregion
//#region src/skills/workshop/library.ts
/** Refusal the model (or operator) can act on; the message says what to change. */
var WorkshopWriteError = class extends Error {
constructor(...e) {
super(...e);
this.name = "WorkshopWriteError";
}
};
const SKILL_FILE = "SKILL.md";
const ARCHIVE_DIR = ".archive";
const MAX_DESCRIPTION_BYTES = 1024;
const NEW_SKILL_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,62}$/;
const EXISTING_SKILL_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,254}$/;
const skillLocks = new KeyedAsyncQueue();
const log = createSubsystemLogger("skills/workshop");
function resolveSkillPaths(e, t, n) {
if (!EXISTING_SKILL_NAME_PATTERN.test(n)) throw new WorkshopWriteError(`Invalid skill name "${n}": use lowercase letters, digits, or hyphens, starting with a letter or digit (e.g. "deploy-staging").`);
const r = resolveWorkshopSkillsDir(e, t);
return {
root: r,
skillDir: path.join(r, n),
versionsDir: path.join(r, ARCHIVE_DIR, n)
};
}
function normalizeSkillFilePath(e) {
const t = e?.trim();
if (!t || t === "SKILL.md") return SKILL_FILE;
try {
return normalizeWorkspaceSkillSupportPath(t);
} catch (e) {
throw new WorkshopWriteError(`Invalid file_path "${t}": ${formatErrorMessage(e)} Use "SKILL.md" or a file like "references/notes.md".`);
}
}
async function readSkillFile(e, t) {
return t === "SKILL.md" ? await readWorkspaceSkillFile(path.join(e, SKILL_FILE)) : await readWorkspaceSupportFile({
skillDir: e,
relativePath: t
});
}
/** Regular files below one skill directory, SKILL.md first; links and dot entries are skipped. */
async function listSkillFiles(e) {
const t = await listDirectoryTreeStrict(e, { skipDirectory: ({ dirent: e }) => e.name.startsWith(".") || e.name === "node_modules" });
const n = [];
let r = 0;
let i = 0;
for (const { relativePath: a, dirent: o } of t) {
if (!o.isFile()) continue;
const t = a.split(path.sep);
if (t.some((e) => e.startsWith("."))) continue;
const s = await fs.stat(path.join(e, a));
r += s.size;
i = Math.max(i, s.mtimeMs);
n.push(t.join("/"));
}
n.sort((e, t) => e === "SKILL.md" ? -1 : t === "SKILL.md" ? 1 : e.localeCompare(t));
return {
files: n,
sizeBytes: r,
updatedAtMs: Math.trunc(i)
};
}
function validateSkillMarkdown(e, t, n) {
const r = Buffer.byteLength(t);
if (r > n) throw new WorkshopWriteError(`SKILL.md is ${r} bytes; the limit is ${n}. Keep SKILL.md to the procedure and move detail into references/<topic>.md with action=write_file.`);
let i;
try {
i = parseSkillFrontmatter(t);
} catch (t) {
throw new WorkshopWriteError(`SKILL.md frontmatter is invalid (${formatErrorMessage(t)}). Start the file with:\n---\nname: ${e}\ndescription: <when to use this skill>\n---`);
}
if (i.name?.trim() !== e) throw new WorkshopWriteError(`SKILL.md frontmatter must contain "name: ${e}" (the skill directory name); found ${i.name ? `"${i.name}"` : "no name"}.`);
const a = i.description?.trim() ?? "";
const o = Buffer.byteLength(a);
if (o === 0 || o > MAX_DESCRIPTION_BYTES) throw new WorkshopWriteError(`SKILL.md frontmatter "description" must be 1-${MAX_DESCRIPTION_BYTES} bytes (found ${o}). Lead with the situations that should trigger the skill.`);
return a;
}
function assertSafeContent(e, t, n) {
const r = `${e}/${t}`;
const i = scanSkillFile(n, r).find((e) => e.severity === "critical");
if (!i) return;
const a = i.ruleId === "literal-secret" ? "Replace the credential with a placeholder such as <API_KEY>; never store real secrets in skills." : "Remove or rewrite that line, then retry.";
throw new WorkshopWriteError(`Refused: ${r} line ${i.line} matches security rule "${i.ruleId}" (${i.message}). ${a}`);
}
/** Validates one file's next content: path, SKILL.md shape or support size, then the security scan. */
function validateSkillFile(e, t, n, r) {
if (n.split("/").includes("node_modules")) throw new WorkshopWriteError("node_modules is not a skill support directory. Put authored files in scripts/ or references/ instead.");
if (n !== "SKILL.md" && scanSupportFilePath(n).length > 0) throw new WorkshopWriteError(`Refused: a file path in "${t}" looks like it contains a credential. Name the file after its topic (e.g. "references/api.md"); never store real secrets in skills.`);
const i = n === "SKILL.md" ? validateSkillMarkdown(t, r, resolveSkillWorkshopConfig(e).maxSkillBytes) : void 0;
if (n !== "SKILL.md" && Buffer.byteLength(r) > 262144) throw new WorkshopWriteError(`${n} exceeds ${MAX_WORKSPACE_SKILL_SUPPORT_FILE_BYTES} bytes; split it into smaller files.`);
assertSafeContent(t, n, r);
return i;
}
/** Reads a saved version only when a normal write could have produced every file in it. */
async function readRestorableVersion(e, t, n, r) {
const refuse = (e) => new WorkshopWriteError(`Cannot restore "${t}" version ${n}: ${e} The live skill is unchanged; restore a different version instead.`);
if (!(await fs.lstat(r)).isDirectory()) throw refuse("the saved version is not a directory.");
const i = await root(r);
const a = [];
for (const { relativePath: n, dirent: o } of await listDirectoryTreeStrict(r)) {
const r = n.split(path.sep).join("/");
if (o.isDirectory() || r.split("/").some((e) => e.startsWith("."))) continue;
if (!o.isFile()) throw refuse(`${r} is a symlink or special file.`);
if (r !== "SKILL.md") {
let e;
try {
e = normalizeWorkspaceSkillSupportPath(r);
} catch (e) {
throw refuse(`${r} is not an allowed skill file (${formatErrorMessage(e)})`);
}
if (e !== r) throw refuse(`${r} is not a valid skill file path.`);
}
let s;
try {
s = (await i.read(r, {
hardlinks: "reject",
maxBytes: r === "SKILL.md" ? resolveSkillWorkshopConfig(e).maxSkillBytes : MAX_WORKSPACE_SKILL_SUPPORT_FILE_BYTES,
symlinks: "reject"
})).buffer;
} catch (e) {
throw refuse(`${r} could not be read safely (${formatErrorMessage(e)}).`);
}
try {
validateSkillFile(e, t, r, s.toString("utf8"));
} catch (e) {
throw refuse(formatErrorMessage(e));
}
a.push([r, s]);
}
if (!a.some(([e]) => e === "SKILL.md")) throw refuse("SKILL.md is missing.");
return a;
}
async function writeSkillFile(e, t, n) {
await fs.mkdir(e.root, { recursive: true });
assertInsideSkillsRoot(e.root, e.skillDir, "skill directory");
await fs.mkdir(e.skillDir, { recursive: true });
await (await root(e.skillDir)).write(t, n, {
encoding: "utf8",
mkdir: true,
overwrite: true,
assertBeforeMutation: e.assertLive
});
}
async function requireLiveSkill(e, t) {
if (await pathExists(path.join(e.skillDir, "SKILL.md"))) return;
const n = (await listVersions(e.versionsDir)).length > 0;
throw new WorkshopWriteError(n ? `Skill "${t}" is archived. Restore it first with action=restore name=${t}.` : `No workshop skill named "${t}". Call action=list to see skills, or action=create to add one.`);
}
/** Sorted acquisition keeps overlapping multi-skill mutations from deadlocking. */
async function withSkillLocks(e, t) {
const [n, ...r] = [...new Set(e)].toSorted((e, t) => e.localeCompare(t));
return n === void 0 ? await t() : await skillLocks.enqueue(n, () => withSkillLocks(r, t));
}
/** Serializes one skill's mutation, then refreshes discovery and records the change. */
async function mutateSkill(e, t, n, r, i = []) {
const a = resolveSkillPaths(e.config, e.agentId, t);
return await withSkillLocks([a.skillDir, ...i.map((e) => e.skillDir)], async () => {
e.assertLive?.();
const i = hasCommittedSkillChangeHooks();
const snapshotArtifact = async () => i && await pathExists(path.join(a.skillDir, "SKILL.md")) ? await snapshotCommittedSkillArtifactBestEffort({
skillDir: a.skillDir,
skillKey: t,
source: "workshop"
}) : void 0;
const o = await snapshotArtifact();
const { summary: s, versionId: c } = await r({
...a,
assertLive: () => e.assertLive?.()
});
const l = await snapshotArtifact();
await pruneVersions(a.versionsDir);
try {
const { refreshSkillsDiscovery: t } = await import("./refresh-CwpO2622.mjs");
await t({
config: e.config,
reason: "workshop"
});
} catch (e) {
log.warn(`Skill changed, but discovery refresh failed: ${formatErrorMessage(e)}`);
}
const u = {
id: randomUUID(),
agentId: e.agentId,
skillName: t,
action: n,
actor: e.actor,
summary: s,
...c ? { versionId: c } : {},
...e.sessionKey ? { sessionKey: e.sessionKey } : {},
...e.runId ? { runId: e.runId } : {},
createdAtMs: Date.now()
};
await recordWorkshopChange(u);
if (o || l) await dispatchCommittedSkillChangeBestEffort({
action: !o ? "created" : l ? "updated" : "removed",
source: "workshop",
workspaceDir: resolveAgentWorkspaceDir(e.config, e.agentId),
...o ? { before: o } : {},
...l ? { after: l } : {}
});
return u;
});
}
async function listWorkshopSkills(e, t) {
const n = resolveWorkshopSkillsDir(e, t);
const r = await fs.readdir(n, { withFileTypes: true }).catch((e) => ignoreMissingPath(e) ?? []);
const i = [];
for (const e of r) {
if (!e.isDirectory() || !EXISTING_SKILL_NAME_PATTERN.test(e.name)) continue;
const t = path.join(n, e.name);
const r = await readWorkspaceSkillFile(path.join(t, SKILL_FILE));
if (r === null) continue;
let a = "";
try {
a = parseSkillFrontmatter(r).description?.trim() ?? "";
} catch {}
i.push({
name: e.name,
description: a,
...await listSkillFiles(t)
});
}
return i.toSorted((e, t) => e.name.localeCompare(t.name));
}
async function listWorkshopArchive(e, t) {
const n = resolveWorkshopSkillsDir(e, t);
const r = await fs.readdir(path.join(n, ARCHIVE_DIR)).catch((e) => ignoreMissingPath(e) ?? []);
const i = [];
for (const e of r.toSorted()) {
if (!EXISTING_SKILL_NAME_PATTERN.test(e)) continue;
const t = await listVersions(path.join(n, ARCHIVE_DIR, e));
if (t.length > 0) {
const r = await pathExists(path.join(n, e, SKILL_FILE));
i.push({
name: e,
live: r,
versions: t
});
}
}
return i;
}
async function viewWorkshopSkill(e, t, n, r, i) {
const a = resolveSkillPaths(e, t, n);
const o = normalizeSkillFilePath(r);
let s = a.skillDir;
if (i) {
const e = await listVersions(a.versionsDir);
if (!e.some((e) => e.id === i)) throw new WorkshopWriteError(`Skill "${n}" has no version "${i}". Versions: ${e.map((e) => e.id).join(", ") || "none"}.`);
s = path.join(a.versionsDir, i);
} else await requireLiveSkill(a, n);
const { files: c } = await listSkillFiles(s);
const l = await readSkillFile(s, o);
if (l === null) throw new WorkshopWriteError(`${o} does not exist in "${n}". Files: ${c.join(", ")}.`);
return {
name: n,
filePath: o,
content: l,
files: c
};
}
async function createWorkshopSkill(e, t) {
if (!NEW_SKILL_NAME_PATTERN.test(t.name)) throw new WorkshopWriteError(`Invalid skill name "${t.name}": use 1-63 lowercase letters, digits, or hyphens, starting with a letter or digit (e.g. "deploy-staging").`);
return await mutateSkill(e, t.name, "create", async (n) => {
if (await pathExists(n.skillDir)) throw new WorkshopWriteError(`Skill "${t.name}" already exists. View it and use action=patch, or choose another name.`);
const r = validateSkillFile(e.config, t.name, SKILL_FILE, t.content);
try {
await writeSkillFile(n, SKILL_FILE, t.content);
} catch (e) {
await fs.rm(n.skillDir, {
recursive: true,
force: true
});
throw e;
}
return { summary: t.summary ?? `created: ${r}` };
});
}
async function patchWorkshopSkill(e, t) {
const n = normalizeSkillFilePath(t.filePath);
return await mutateSkill(e, t.name, "patch", async (r) => {
await requireLiveSkill(r, t.name);
if (!t.oldText) throw new WorkshopWriteError("old_text is required: copy the exact text to replace from view.");
if (t.oldText === t.newText) throw new WorkshopWriteError("old_text and new_text are identical; nothing to change.");
const i = await readSkillFile(r.skillDir, n);
if (i === null) throw new WorkshopWriteError(`${n} does not exist in "${t.name}". Use action=write_file to add it.`);
const { oldText: a } = t;
let o = 0;
for (let e = i.indexOf(a); e !== -1; e = i.indexOf(a, e + 1)) o++;
if (o !== 1) throw new WorkshopWriteError(o === 0 ? `old_text was not found in ${t.name}/${n}. View the file again and copy the exact text, including whitespace.` : `old_text matches ${o} places in ${t.name}/${n}. Include more surrounding text so it matches once.`);
const s = i.replace(t.oldText, () => t.newText);
validateSkillFile(e.config, t.name, n, s);
const c = await snapshotSkill(r, "patch");
await writeSkillFile(r, n, s);
return {
summary: t.summary ?? `patched ${n}`,
versionId: c
};
});
}
async function writeWorkshopSkillFile(e, t) {
const n = normalizeSkillFilePath(t.filePath);
return await mutateSkill(e, t.name, "write_file", async (r) => {
await requireLiveSkill(r, t.name);
if (await readSkillFile(r.skillDir, n) === t.content) throw new WorkshopWriteError(`${t.name}/${n} already has this content; nothing changed.`);
validateSkillFile(e.config, t.name, n, t.content);
const i = await snapshotSkill(r, "write_file");
await writeSkillFile(r, n, t.content);
return {
summary: t.summary ?? (n === "SKILL.md" ? "rewrote SKILL.md" : `wrote ${n}`),
versionId: i
};
});
}
/** Deletes one support file; SKILL.md goes only with the whole skill, through archive. */
async function removeWorkshopSkillFile(e, t) {
const n = normalizeSkillFilePath(t.filePath);
if (n === "SKILL.md") throw new WorkshopWriteError(`SKILL.md cannot be removed. Archive the skill with action=archive name=${t.name} instead.`);
return await mutateSkill(e, t.name, "remove_file", async (e) => {
await requireLiveSkill(e, t.name);
const { files: r } = await listSkillFiles(e.skillDir);
if (!r.includes(n)) throw new WorkshopWriteError(`${n} does not exist in "${t.name}". Files: ${r.join(", ")}.`);
const i = await snapshotSkill(e, "remove_file");
await removePathWithinRoot({
rootDir: e.skillDir,
relativePath: n,
force: false,
assertBeforeMutation: e.assertLive
});
return {
summary: t.summary ?? `removed ${n}`,
versionId: i
};
});
}
async function archiveWorkshopSkill(e, t) {
const n = t.absorbedInto === void 0 ? void 0 : resolveSkillPaths(e.config, e.agentId, t.absorbedInto);
return await mutateSkill(e, t.name, "archive", async (e) => {
await requireLiveSkill(e, t.name);
if (n && (t.absorbedInto === t.name || !await pathExists(path.join(n.skillDir, "SKILL.md")))) throw new WorkshopWriteError(`absorbed_into must name another live workshop skill; "${t.absorbedInto}" is not one.`);
const r = await snapshotSkill(e, "archive");
const i = path.join(e.root, ARCHIVE_DIR, `.archiving-${randomUUID()}`);
e.assertLive();
await fs.rename(e.skillDir, i);
await fs.rm(i, {
recursive: true,
force: true
});
const a = [t.absorbedInto ? `merged into ${t.absorbedInto}` : void 0, t.reason?.trim() || void 0].filter(Boolean);
return {
summary: a.length > 0 ? `archived: ${a.join("; ")}` : "archived",
versionId: r
};
}, n ? [n] : []);
}
/** Restores a saved version (default: newest); the live copy is versioned first, so undo is undoable. */
async function restoreWorkshopSkill(e, t) {
return await mutateSkill(e, t.name, "restore", async (n) => {
const r = await listVersions(n.versionsDir);
const i = t.versionId ? r.find((e) => e.id === t.versionId) : r[0];
if (!i) throw new WorkshopWriteError(r.length === 0 ? `Skill "${t.name}" has no saved versions to restore.` : `Skill "${t.name}" has no version "${t.versionId}". Versions: ${r.map((e) => e.id).join(", ")}.`);
const a = await readRestorableVersion(e.config, t.name, i.id, path.join(n.versionsDir, i.id));
const o = await publishSkillBundle(n, "restore", async (e) => {
for (const [t, n] of a) await writeStagedFile(e, t, n);
});
return {
summary: t.summary ?? (i.action === "archive" ? "restored from archive" : t.versionId ? `restored version ${i.id}` : `undid ${i.action.replace("_", " ")}`),
versionId: o
};
});
}
/**
* Publishes the live skill with `files` written over it as one versioned swap. Files not listed
* are kept byte for byte, binary assets included; without a live skill the files are the skill.
*/
async function publishSkillOverlay(e, t) {
const n = await pathExists(e.skillDir);
return await publishSkillBundle(e, "write_file", async (r) => {
if (n) await fs.cp(e.skillDir, r, {
recursive: true,
filter: async (e) => !(await fs.lstat(e)).isSymbolicLink()
});
for (const [e, n] of t) await writeStagedFile(r, e, n);
});
}
async function writeStagedFile(e, t, n) {
const r = path.join(e, ...t.split("/"));
await fs.mkdir(path.dirname(r), { recursive: true });
await fs.writeFile(r, n);
}
/**
* Publishes a whole skill at once: `fill` builds the complete next copy in a staging directory,
* the live skill is snapshotted, and the copies swap by rename. A failed fill, refused authority,
* or failed rename leaves the previous live skill in place. Returns the snapshot's version id.
*/
async function publishSkillBundle(e, t, n) {
const r = path.join(e.root, ARCHIVE_DIR, `.${t}-${randomUUID()}`);
const i = path.join(e.root, ARCHIVE_DIR, `.${t}-previous-${randomUUID()}`);
try {
await fs.mkdir(r, { recursive: true });
await n(r);
const a = await snapshotSkill(e, t);
const o = await pathExists(e.skillDir);
if (o) {
e.assertLive();
await fs.rename(e.skillDir, i);
}
try {
e.assertLive();
await fs.rename(r, e.skillDir);
} catch (t) {
if (o) await fs.rename(i, e.skillDir);
throw t;
}
await fs.rm(i, {
recursive: true,
force: true
});
return a;
} finally {
await fs.rm(r, {
recursive: true,
force: true
});
}
}
//#endregion
export { listWorkshopChanges as S, restoreWorkshopSkill as _, archiveWorkshopSkill as a, writeStagedFile as b, listWorkshopArchive as c, normalizeSkillFilePath as d, patchWorkshopSkill as f, removeWorkshopSkillFile as g, readSkillFile as h, WorkshopWriteError as i, listWorkshopSkills as l, publishSkillOverlay as m, NEW_SKILL_NAME_PATTERN as n, createWorkshopSkill as o, publishSkillBundle as p, SKILL_FILE as r, listSkillFiles as s, EXISTING_SKILL_NAME_PATTERN as t, mutateSkill as u, validateSkillFile as v, writeWorkshopSkillFile as x, viewWorkshopSkill as y };