openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
571 lines (570 loc) • 22.9 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import "./paths-DAcAg5aV.mjs";
import { w as root } from "./fs-safe-BbWvmdVn.mjs";
import { t as normalizeClawHubSha256Hex } from "./clawhub-integrity-DTNmm7ZL.mjs";
import { t as flattenMarkdownToPlainText } from "./markdown-plain-text-B3XtgPwD.mjs";
import { t as digestTemplateBytes } from "./digest-DN38l3Q9.mjs";
import { i as stripFrontmatterBlock } from "./frontmatter-CLR6jwh6.mjs";
import { f as isCanonicalClawHubPackageName, i as MAX_MANAGED_FILE_BYTES, n as readTemplateManifestFile, p as isExactSemVer } from "./reader-L_dBhbIJ.mjs";
import { v as resolveClawHubBaseUrl, y as resolveClawHubImageUrl } from "./clawhub-client-BLg-dsn2.mjs";
import { a as listClawHubPackages, i as fetchClawHubPackageVersion, l as searchClawHubPackages, n as fetchClawHubPackageDetail, t as fetchClawHubPackageArtifact } from "./clawhub-packages-BkEmBO-h.mjs";
import { i as fetchClawHubSkillCard } from "./clawhub-skills-C1KFinHC.mjs";
import { l as parseRequestedClawHubSkillRef } from "./clawhub-store-BhwTU-Sz.mjs";
import { n as downloadClawHubPackageArchive } from "./clawhub-artifacts-tomgAvzv.mjs";
import { r as checkClawHubPackageTrust } from "./clawhub-install-trust-CL-GzwYX.mjs";
import { n as withExtractedArchiveRoot } from "./install-flow-C68L8OqQ.mjs";
import { createReadStream } from "node:fs";
import path from "node:path";
import { createHash } from "node:crypto";
import fs$1 from "node:fs/promises";
//#region src/templates/clawhub-source-artifact.ts
const TEMPLATE_SOURCE_CACHE_DIR = "templates/sources";
const CLAWHUB_TIMEOUT_MS = 3e4;
var ClawHubSourceError = class extends Error {
constructor(e, t, n) {
super(t);
this.code = e;
this.warning = n;
this.name = "ClawHubSourceError";
}
};
async function sourceDirectoriesMatch(e, t) {
const [n, r] = await Promise.all([fs$1.lstat(e), fs$1.lstat(t)]);
if (!n.isDirectory() || !r.isDirectory()) return false;
const [i, a] = await Promise.all([fs$1.readdir(e, { withFileTypes: true }), fs$1.readdir(t, { withFileTypes: true })]);
if (i.length !== a.length) return false;
const o = new Map(a.map((e) => [e.name, e]));
for (const n of i) {
const r = o.get(n.name);
if (!r) return false;
const i = path.join(e, n.name);
const a = path.join(t, n.name);
if (n.isDirectory() && r.isDirectory()) {
if (!await sourceDirectoriesMatch(i, a)) return false;
} else if (n.isFile() && r.isFile()) {
if (!(await fs$1.readFile(i)).equals(await fs$1.readFile(a))) return false;
} else return false;
}
return true;
}
async function archiveMatches(e, t, n) {
const r = await fs$1.lstat(e).catch(() => void 0);
if (!r?.isFile() || r.size !== n) return false;
const i = createHash("sha256");
for await (const t of createReadStream(e)) i.update(t);
return i.digest("hex") === t;
}
async function persistExtractedSource(e) {
const t = path.join(e.stateDir ?? resolveStateDir(), TEMPLATE_SOURCE_CACHE_DIR);
const n = path.join(t, e.artifactSha256);
const r = path.join(t, `${e.artifactSha256}.tgz`);
await fs$1.mkdir(t, {
recursive: true,
mode: 448
});
const i = await fs$1.mkdtemp(path.join(t, ".staging-"));
const a = path.join(i, "package");
const o = path.join(i, "source.tgz");
try {
await fs$1.cp(e.rootDir, a, {
recursive: true,
force: false,
errorOnExist: true,
preserveTimestamps: false,
verbatimSymlinks: true
});
await fs$1.copyFile(e.archivePath, o);
if (!await archiveMatches(o, e.artifactSha256, e.artifactByteLength)) throw new ClawHubSourceError("clawhub_artifact_integrity_mismatch", "The staged Template archive differs from the verified release artifact.");
try {
await fs$1.link(o, r);
} catch (t) {
if ((t && typeof t === "object" && "code" in t ? t.code : void 0) !== "EEXIST") throw t;
if (!await archiveMatches(r, e.artifactSha256, e.artifactByteLength)) throw new ClawHubSourceError("clawhub_cached_artifact_mismatch", "A retained Template archive differs from the verified release artifact.");
}
try {
await fs$1.rename(a, n);
} catch (e) {
const t = e && typeof e === "object" && "code" in e ? e.code : void 0;
if (t !== "EEXIST" && t !== "ENOTEMPTY") throw e;
if (!await sourceDirectoriesMatch(a, n)) throw new ClawHubSourceError("clawhub_cached_source_mismatch", "A cached Template source differs from the verified release artifact.");
}
return n;
} finally {
await fs$1.rm(i, {
recursive: true,
force: true
});
}
}
async function readVerifiedArtifactSource(e) {
const t = await readTemplateManifestFile(e.sourceRoot, { allowPublishedLegacyClawSelector: true });
if (!t.ok) throw new ClawHubSourceError("clawhub_manifest_invalid", "Downloaded Template package manifest is invalid.");
if (t.source.kind !== "package" || t.source.name !== e.packageName || t.source.version !== e.version) throw new ClawHubSourceError("clawhub_identity_mismatch", "Downloaded Template package identity does not match the selected release.");
return {
...t,
source: {
...t.source,
integrityKind: "artifact",
integrity: `sha256:${e.artifactSha256}`,
byteLength: e.artifactByteLength
}
};
}
//#endregion
//#region src/templates/clawhub-manifest-summary.ts
function parseTemplateManifestSummary(e) {
if (!isRecord(e) || e.schemaVersion !== 1) throw new ClawHubSourceError("clawhub_manifest_summary_missing", "ClawHub did not return a validated Template summary.");
const { agent: t, workspace: n, packages: r } = e;
const isCount = (e) => typeof e === "number" && Number.isSafeInteger(e) && e >= 0;
if (!isRecord(t) || typeof t.id !== "string" || !t.id || t.name !== void 0 && typeof t.name !== "string" || t.description !== void 0 && typeof t.description !== "string" || !isRecord(n) || !Array.isArray(n.bootstrapFiles) || !n.bootstrapFiles.every((e) => typeof e === "string") || !isCount(n.fileCount) || !isRecord(r) || !isCount(r.skillCount) || !isCount(r.pluginCount) || !isCount(e.mcpServerCount) || !isCount(e.cronJobCount)) throw new ClawHubSourceError("clawhub_manifest_summary_missing", "ClawHub did not return a validated Template summary.");
return {
...typeof t.name === "string" ? { name: t.name } : {},
...typeof t.description === "string" ? { description: t.description } : {}
};
}
//#endregion
//#region src/templates/clawhub-preview-content.ts
async function readClawHubCatalogPreview(e) {
const { requested: t, instructions: n, skills: r, verified: i, rootDir: a, params: o } = e;
if (t?.kind === "instruction") {
const e = n.find((e) => e.name === t.name);
if (!e) return;
const r = i.packageBootstrap?.sourcePath === e.source ? i.packageBootstrap : i.snapshot.workspaceSources.find((t) => t.sourcePath === e.source);
if (e.source !== "CLAW.md#body" && !r) throw new ClawHubSourceError("clawhub_preview_unavailable", "This workspace file is not available in the verified Template release.");
let o;
if (e.source === "CLAW.md#body") o = i.templateMarkdownBody?.toString("utf8");
else {
const t = await (await root(a)).read(e.source, {
hardlinks: "reject",
maxBytes: MAX_MANAGED_FILE_BYTES,
symlinks: "reject"
});
if (t.buffer.byteLength !== r.byteLength || digestTemplateBytes(t.buffer) !== r.digest) throw new ClawHubSourceError("clawhub_preview_unavailable", "This workspace file changed during preview.");
o = t.buffer.toString("utf8");
}
return o === void 0 ? void 0 : {
kind: "instruction",
name: e.name,
content: o
};
}
if (t?.kind === "skill") {
const e = r.find((e) => e.name === t.name);
if (!e) return;
const n = parseRequestedClawHubSkillRef(e.name);
const i = await fetchClawHubSkillCard({
...o,
slug: n.slug,
...n.ownerHandle ? { ownerHandle: n.ownerHandle } : {},
version: e.version
}).catch(() => {
throw new ClawHubSourceError("clawhub_preview_unavailable", "This skill's content is unavailable from the configured ClawHub.");
});
return {
kind: "skill",
name: e.name,
content: i
};
}
}
//#endregion
//#region src/templates/clawhub-source.ts
const CATALOG_PAGE_SIZE = 100;
const MAX_CATALOG_PAGES = 20;
const MAX_CONTENT_EXCERPT_CHARS = 2048;
function toCatalogExcerpt(e) {
return e ? flattenMarkdownToPlainText(e).slice(0, MAX_CONTENT_EXCERPT_CHARS) : "";
}
function isPublicTemplatePackage(e) {
return isRecord(e) && typeof e.name === "string" && typeof e.displayName === "string" && typeof e.updatedAt === "number" && Number.isFinite(e.updatedAt) && (e.summary === void 0 || e.summary === null || typeof e.summary === "string") && (e.latestVersion === void 0 || e.latestVersion === null || typeof e.latestVersion === "string") && e.family === "template" && (e.channel === "official" && e.isOfficial === true || e.channel === "community" && e.isOfficial === false) && isCanonicalClawHubPackageName(e.name);
}
function matchesTemplatePublisher(e, t) {
return typeof t === "string" && t.length > 0 && (!e.startsWith("@") || e.slice(1, e.indexOf("/")) === t);
}
function isPublicTemplateListItem(e) {
return isPublicTemplatePackage(e) && matchesTemplatePublisher(e.name, e.ownerHandle);
}
function requirePublicTemplatePackage(e, t) {
const n = e.package;
const r = e.owner?.handle;
if (!isPublicTemplatePackage(n) || n.name !== t || !matchesTemplatePublisher(n.name, r) || n.ownerHandle !== void 0 && n.ownerHandle !== null && n.ownerHandle !== r) throw new ClawHubSourceError("clawhub_identity_mismatch", "ClawHub returned a different public Template package identity.");
return {
...n,
ownerHandle: r,
ownerOfficial: e.owner?.official === true
};
}
function requireTemplateName(e) {
if (!isCanonicalClawHubPackageName(e)) throw new ClawHubSourceError("clawhub_package_name_invalid", "Select a canonical ClawHub package name without a version selector.");
}
function requireExactVersion(e) {
if (!isExactSemVer(e)) throw new ClawHubSourceError("clawhub_version_unavailable", "Select an exact published Template version.");
}
function projectCatalogEntry(e, t) {
const n = resolveClawHubImageUrl(typeof e.icon === "string" ? e.icon : void 0, t);
const r = e.stats?.downloads;
const i = e.stats?.installs;
return {
packageName: e.name,
...n ? { iconUrl: n } : {},
displayName: e.displayName,
...e.summary ? { summary: e.summary } : {},
...e.latestVersion ? { latestVersion: e.latestVersion } : {},
channel: e.channel,
official: e.ownerOfficial === true,
ownerHandle: e.ownerHandle,
downloads: typeof r === "number" && Number.isFinite(r) ? Math.max(0, r) : 0,
installs: typeof i === "number" && Number.isFinite(i) ? Math.max(0, i) : 0,
...typeof e.featuredAt === "number" ? { featuredAt: e.featuredAt } : {},
updatedAtMs: Math.max(0, e.updatedAt)
};
}
function projectPublicEntries(e, t) {
return e.filter(isPublicTemplateListItem).map((e) => projectCatalogEntry(e, t));
}
function rankByInstalls(e, t) {
return t.installs - e.installs || e.packageName.localeCompare(t.packageName);
}
function readExactTemplateArtifact(e, t) {
const n = typeof e.version === "string" ? e.version : e.version?.version;
if (e.package?.name !== t.packageName || e.package.family !== "template" || n !== t.version) throw new ClawHubSourceError("clawhub_identity_mismatch", "ClawHub artifact identity does not match the selected release.");
const r = e.artifact;
if (!isRecord(r)) throw new ClawHubSourceError("clawhub_artifact_unavailable", "ClawHub returned no Template artifact.");
if ((r.kind ?? r.artifactKind) !== "npm-pack" || r.kind !== void 0 && r.artifactKind !== void 0 && r.kind !== r.artifactKind || r.source !== void 0 && r.source !== "clawhub" || r.packageName !== void 0 && r.packageName !== t.packageName || r.version !== void 0 && r.version !== t.version) throw new ClawHubSourceError("clawhub_identity_mismatch", "ClawHub artifact identity does not match the selected release.");
const i = typeof r.sha256 === "string" ? normalizeClawHubSha256Hex(r.sha256) : null;
const a = typeof r.artifactSha256 === "string" ? normalizeClawHubSha256Hex(r.artifactSha256) : null;
const o = i ?? a;
if (!o || r.sha256 !== void 0 && !i || r.artifactSha256 !== void 0 && !a || i && a && i !== a || typeof r.npmIntegrity !== "string" || !r.npmIntegrity.trim()) throw new ClawHubSourceError("clawhub_artifact_unavailable", "ClawHub did not return valid immutable Template artifact integrity.");
return {
sha256: o,
npmIntegrity: r.npmIntegrity,
...typeof r.npmShasum === "string" ? { npmShasum: r.npmShasum } : {}
};
}
function assertClawHubDownloadIntegrity(e, t) {
if (e.artifact !== "clawpack" || e.sha256Hex !== t.sha256 || e.npmIntegrity !== t.npmIntegrity || t.npmShasum !== void 0 && e.npmShasum !== t.npmShasum) throw new ClawHubSourceError("clawhub_artifact_integrity_mismatch", "ClawHub artifact integrity changed during download.");
}
async function listClawHubTemplates(e = {}) {
const t = /* @__PURE__ */ new Map();
const finish = () => {
const n = [...t.values()];
return e.category && !e.featured ? n.toSorted(rankByInstalls) : n;
};
const n = /* @__PURE__ */ new Set();
const r = !e.category && e.limit && e.limit > 0 ? e.limit : void 0;
let i;
for (let a = 0; a < MAX_CATALOG_PAGES; a += 1) {
const a = await listClawHubPackages({
...e,
family: "template",
category: e.category,
featured: e.featured,
limit: Math.min(CATALOG_PAGE_SIZE, r ? r - t.size : CATALOG_PAGE_SIZE),
...i ? { cursor: i } : {}
});
for (const n of projectPublicEntries(a.items, e.baseUrl)) {
t.set(n.packageName, n);
if (r && t.size >= r) return finish();
}
if (a.nextCursor === null) return finish();
if (!a.nextCursor || n.has(a.nextCursor)) throw new ClawHubSourceError("clawhub_catalog_cursor_invalid", "ClawHub returned a repeating catalog cursor.");
n.add(a.nextCursor);
i = a.nextCursor;
}
throw new ClawHubSourceError("clawhub_catalog_too_large", "ClawHub returned too many catalog pages for this request.");
}
async function searchClawHubTemplates(e) {
const t = e.query.trim();
if (!t) return await listClawHubTemplates(e);
const n = projectPublicEntries((await searchClawHubPackages({
...e,
query: t,
family: "template",
category: e.category,
limit: e.limit ?? CATALOG_PAGE_SIZE
})).map((e) => e.package), e.baseUrl);
return e.category ? n.toSorted(rankByInstalls) : n;
}
async function readClawHubTemplateDetail(e) {
requireTemplateName(e.packageName);
const t = requirePublicTemplatePackage(await fetchClawHubPackageDetail({
...e,
name: e.packageName
}), e.packageName);
const n = e.version ?? t.latestVersion;
if (!n) throw new ClawHubSourceError("clawhub_version_unavailable", "ClawHub has no published version.");
requireExactVersion(n);
const r = await fetchClawHubPackageVersion({
...e,
name: t.name,
version: n
});
if (r.package?.name !== t.name || r.package.family !== "template") throw new ClawHubSourceError("clawhub_identity_mismatch", "ClawHub release identity changed.");
if (!r.version || r.version.version !== n) throw new ClawHubSourceError("clawhub_version_unavailable", "ClawHub release identity changed.");
const i = parseTemplateManifestSummary(r.version.templateManifestSummary);
const { contents: a } = await readClawHubTemplateContents({
...e,
packageName: t.name,
version: n
});
return {
...projectCatalogEntry({
...t,
icon: r.version.icon
}, e.baseUrl),
version: n,
...i.name ? { agentName: i.name } : {},
...i.description ? { agentDescription: i.description } : {},
workspaceFiles: a.instructions.length,
skills: a.skills.length,
plugins: a.integrations.filter((e) => e.kind === "plugin").length,
mcpServers: a.integrations.filter((e) => e.kind === "mcpServer").length,
scheduledJobs: a.automations.length,
contents: a
};
}
async function readClawHubTemplatePreview(e) {
requireTemplateName(e.packageName);
requireExactVersion(e.version);
requirePublicTemplatePackage(await fetchClawHubPackageDetail({
...e,
name: e.packageName
}), e.packageName);
const { preview: t } = await readClawHubTemplateContents(e, {
kind: e.kind,
name: e.name
});
if (!t) throw new ClawHubSourceError("clawhub_preview_unavailable", "This item is not in the Template release.");
return t;
}
async function readClawHubTemplateContents(e, t) {
const n = readExactTemplateArtifact(await fetchClawHubPackageArtifact({
...e,
name: e.packageName
}), e);
const r = await downloadClawHubPackageArchive({
name: e.packageName,
version: e.version,
artifact: "clawpack",
...e.baseUrl ? { baseUrl: e.baseUrl } : {},
...e.token ? { token: e.token } : {},
timeoutMs: e.timeoutMs ?? 3e4
});
try {
assertClawHubDownloadIntegrity(r, n);
const i = (await fs$1.stat(r.archivePath)).size;
const a = await withExtractedArchiveRoot({
archivePath: r.archivePath,
tempDirPrefix: "openclaw-template-catalog-",
timeoutMs: e.timeoutMs ?? 3e4,
rootMarkers: [
"package.json",
"CLAW.md",
"template.json"
],
onExtracted: async (r) => {
const a = await readVerifiedArtifactSource({
sourceRoot: r,
packageName: e.packageName,
version: e.version,
artifactSha256: n.sha256,
artifactByteLength: i
});
const o = a.manifest;
const s = [...Object.entries(o.workspace.bootstrapFiles).filter(([, e]) => Boolean(e)).map(([e, t]) => ({
name: e,
source: t.source
})), ...o.workspace.files.map((e) => ({
name: e.path,
source: e.source
}))];
if (a.packageBootstrap) s.push({
name: "BOOTSTRAP.md",
source: a.packageBootstrap.sourcePath
});
if (a.templateMarkdownBody && !s.some((e) => e.name === "SOUL.md")) s.push({
name: "SOUL.md",
source: "CLAW.md#body"
});
const c = o.packages.filter((e) => e.kind === "skill").map((e) => ({
name: e.ref,
version: e.version
}));
const [l, u] = t ? [s, c] : await Promise.all([Promise.all(s.map(async (t) => {
const n = toCatalogExcerpt((await readClawHubCatalogPreview({
params: e,
requested: {
kind: "instruction",
name: t.name
},
instructions: s,
skills: c,
verified: a,
rootDir: r
}))?.content);
return {
...t,
...n ? { excerpt: n } : {}
};
})), Promise.all(c.map(async (t) => {
const n = await readClawHubCatalogPreview({
params: e,
requested: {
kind: "skill",
name: t.name
},
instructions: s,
skills: c,
verified: a,
rootDir: r
}).catch(() => void 0);
const i = toCatalogExcerpt(n?.content ? stripFrontmatterBlock(n.content) : void 0);
return {
...t,
...i ? { excerpt: i } : {}
};
}))]);
const d = await readClawHubCatalogPreview({
params: e,
requested: t,
instructions: s,
skills: c,
verified: a,
rootDir: r
});
return {
ok: true,
value: {
contents: {
instructions: l,
skills: u,
integrations: [...o.packages.filter((e) => e.kind === "plugin").map((e) => ({
name: e.ref,
kind: "plugin",
version: e.version
})), ...Object.keys(o.mcpServers).map((e) => ({
name: e,
kind: "mcpServer"
}))],
automations: o.cronJobs.map((e) => ({
name: e.name || e.id,
schedule: e.schedule.cron,
timezone: e.schedule.timezone
}))
},
...d ? { preview: d } : {}
}
};
}
});
if (!a.ok || !("value" in a)) throw new ClawHubSourceError("clawhub_extract_failed", a.error);
return a.value;
} finally {
await r.cleanup();
}
}
async function withResolvedClawHubSource(e) {
const { packageName: t, version: n } = e.coordinate;
requireTemplateName(t);
requireExactVersion(n);
requirePublicTemplatePackage(await fetchClawHubPackageDetail({
...e,
name: t
}), t);
const r = readExactTemplateArtifact(await fetchClawHubPackageArtifact({
...e,
name: t,
version: n
}), e.coordinate);
const i = r.sha256;
const a = await checkClawHubPackageTrust({
subject: {
kind: "template",
packageName: t
},
version: n,
expectedTemplateArtifact: {
sha256: i,
npmIntegrity: r.npmIntegrity,
...r.npmShasum !== void 0 ? { npmShasum: r.npmShasum } : {}
},
baseUrl: e.baseUrl,
token: e.token,
timeoutMs: e.timeoutMs
});
if (!a.ok) throw new ClawHubSourceError(a.code ?? "clawhub_trust_failed", a.error, a.warning);
const o = a.trustInstallRecordFields.clawhubTrustDisposition === "review-required";
if (e.mode === "apply" && o && !e.acknowledgeClawHubRisk) throw new ClawHubSourceError("clawhub_risk_acknowledgement_required", "Explicit acknowledgement is required for this ClawHub release.", a.warning);
const s = {
...a.warning ? { trustWarning: a.warning } : {},
riskAcknowledgementRequired: o,
trustRecord: a.trustInstallRecordFields
};
const c = await downloadClawHubPackageArchive({
name: t,
version: n,
artifact: "clawpack",
baseUrl: e.baseUrl,
token: e.token,
timeoutMs: e.timeoutMs ?? 3e4
});
try {
assertClawHubDownloadIntegrity(c, r);
const a = (await fs$1.stat(c.archivePath)).size;
const o = await withExtractedArchiveRoot({
archivePath: c.archivePath,
tempDirPrefix: "openclaw-template-source-",
timeoutMs: e.timeoutMs ?? 3e4,
rootMarkers: [
"package.json",
"CLAW.md",
"template.json"
],
onExtracted: async (r) => {
const o = await readVerifiedArtifactSource({
sourceRoot: r,
packageName: t,
version: n,
artifactSha256: i,
artifactByteLength: a
});
if (e.baseUrl !== void 0 && resolveClawHubBaseUrl(e.baseUrl) !== resolveClawHubBaseUrl() && o.manifest.packages.length > 0) throw new ClawHubSourceError("clawhub_registry_mismatch", "ClawHub Template dependencies require the configured registry.");
let l;
const persistSource = async () => {
if (e.mode !== "apply") throw new ClawHubSourceError("clawhub_preview_persistence_forbidden", "A ClawHub preview cannot persist package content.");
l ??= (async () => {
const o = await persistExtractedSource({
rootDir: r,
archivePath: c.archivePath,
artifactSha256: i,
artifactByteLength: a,
stateDir: e.stateDir
});
return await readVerifiedArtifactSource({
sourceRoot: o,
packageName: t,
version: n,
artifactSha256: i,
artifactByteLength: a
});
})();
return await l;
};
return {
ok: true,
value: await e.run(o, s, persistSource)
};
}
});
if (!o.ok || !("value" in o)) throw new ClawHubSourceError("clawhub_extract_failed", o.error);
return {
value: o.value,
...s
};
} finally {
await c.cleanup();
}
}
//#endregion
export { withResolvedClawHubSource as a, searchClawHubTemplates as i, readClawHubTemplateDetail as n, ClawHubSourceError as o, readClawHubTemplatePreview as r, listClawHubTemplates as t };