UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 10.5 kB
import{n as containsAsciiControlCharacter}from"./string-normalization-D_oBUpO3.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{T as walkDirectory,i as ensureAbsoluteDirectory,x as root}from"./fs-safe-Bxzu1j4h.mjs";import{r as isErrno,t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import"./paths-D_FOvGon.mjs";import{n as sha256Hex}from"./node-crypto-DPk8agfR.mjs";import"./crypto-digest-T8X5EZni.mjs";import{t as SkillLibraryError}from"./skill-library-error-CRoBQyXe.mjs";import{n as SKILL_LIBRARY_MAX_FILES,r as SKILL_LIBRARY_MAX_FILE_BYTES,t as SKILL_LIBRARY_MAX_BUNDLE_BYTES}from"./skill-library-QNfZhm1-.mjs";import{t as parseSkillFrontmatter}from"./frontmatter-CvGHA96F.mjs";import{t as retainMutationAuthority}from"./mutation-authority-EJgpxwvk.mjs";import path from"node:path";import fs from"node:fs/promises";import{isAscii}from"node:buffer";import{Value}from"typebox/value";import{Type}from"typebox";import{getFsSafeNativeConfig}from"@openclaw/fs-safe/config"; //!src/skills/library/bundle.ts const SKILL_LIBRARY_MAX_PATH_COMPONENTS=16;const SKILL_LIBRARY_MAX_TREE_ENTRIES=256*2;var SkillTreeDirectoryError=class extends SkillLibraryError{constructor(e,t,n){super(`INVALID_BUNDLE`,`Skill tree directory could not be read: root=${JSON.stringify(e)} path=${JSON.stringify(t)} error=${describeSkillTreeFailure(n)}`,void 0,{cause:n});this.rootPath=e;this.failedPath=t}};const portableCompare=(e,t)=>e<t?-1:e>t?1:0;const manifestSchema=Type.Array(Type.Object({path:Type.String({maxLength:512}),sha256:Type.String({pattern:`^[a-f0-9]{64}$`}),sizeBytes:Type.Integer({minimum:0,maximum:SKILL_LIBRARY_MAX_FILE_BYTES}),executable:Type.Boolean()},{additionalProperties:false}),{minItems:1,maxItems:256});async function readSkillLibraryManifestTree(e,t,n){const r=getFsSafeNativeConfig().mode;const{runSkillLibraryFilesystemTask:i}=await import(`./refresh-DDFbJ_aI.mjs`);const a=await i({kind:`manifest`,directory:e,manifestJson:t,revision:n},r);if(a.kind!==`manifest`)throw new Error(`Unexpected skill library manifest response`);return a.files}async function readSkillLibraryManifestTreeOnWorker(e,t,n){const r=JSON.parse(t);if(!Value.Check(manifestSchema,r))throw new SkillLibraryError(`INVALID_BUNDLE`,`Published skill manifest is invalid.`);const i=await root(e);const a=[];let o=0;for(const e of r){validateSkillLibraryPath(e.path);o+=e.sizeBytes;if(o>8388608)throw new SkillLibraryError(`INVALID_BUNDLE`,`Published skill manifest exceeds bundle limits.`);const{buffer:t}=await i.read(e.path,{hardlinks:`reject`,symlinks:`reject`,maxBytes:e.sizeBytes});if(t.length!==e.sizeBytes||sha256Hex(t)!==e.sha256)throw new SkillLibraryError(`INVALID_BUNDLE`,`Published skill file failed integrity verification: ${e.path}`);a.push({path:e.path,...encodeSkillLibraryFile(t),executable:e.executable})}if(prepareSkillLibraryBundle(a).revision!==n)throw new SkillLibraryError(`INVALID_BUNDLE`,`Published skill revision failed integrity verification.`);return a}function validateSkillLibraryPath(e){validateSkillBundlePath(e);if(e.split(`/`).some(e=>[`.git`,`node_modules`,`.openclaw`].includes(e.toLowerCase())))throw new SkillLibraryError(`INVALID_BUNDLE`,`Non-portable skill file path: ${e}`)}function validateSkillBundlePath(e){const t=e.split(`/`);if(e.length>512||Buffer.from(e,`utf8`).toString(`utf8`)!==e||t.length>16||t.some(e=>!e||e===`.`||e===`..`||/[\\<>:"|?*]/u.test(e)||containsAsciiControlCharacter(e)||/[ .]$/u.test(e)||e!==e.normalize(`NFC`)||/^(con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/iu.test(e)||/^(conin|conout)\$$/iu.test(e)))throw new SkillLibraryError(`INVALID_BUNDLE`,`Non-portable skill file path: ${e}`)}function decodeSkillLibraryFile(e){const t=Buffer.from(e.content,e.encoding===`base64`?`base64`:`utf8`);if(e.encoding===`base64`&&t.toString(`base64`)!==e.content)throw new SkillLibraryError(`INVALID_BUNDLE`,`Invalid base64: ${e.path}`);return t}function encodeSkillLibraryFile(e){if(isAscii(e)){const t=e.toString(`utf8`);if(!t.includes(`\0`)&&JSON.stringify(t).length-2<=Math.ceil(e.length/3)*4)return{content:t,encoding:`utf8`}}return{content:e.toString(`base64`),encoding:`base64`}}function prepareSkillBundle(e){if(e.length>256)throw new SkillLibraryError(`INVALID_BUNDLE`,`Skill bundle exceeds 256 files.`);const t=/* @__PURE__ */ new Set;let n=0;const r=e.map(e=>{validateSkillBundlePath(e.path);const r=e.path.toLowerCase();if(t.has(r))throw new SkillLibraryError(`INVALID_BUNDLE`,`Duplicate skill file: ${e.path}`);t.add(r);const i=decodeSkillLibraryFile(e);n+=i.length;if(i.length>1048576||n>8388608)throw new SkillLibraryError(`INVALID_BUNDLE`,`Skill bundle exceeds file (1 MiB) or total (8 MiB) limit.`);return{path:e.path,bytes:i,sha256:sha256Hex(i),sizeBytes:i.length,executable:e.executable===true}}).toSorted((e,t)=>portableCompare(e.path,t.path));for(const e of r){const n=e.path.toLowerCase().split(`/`);n.pop();while(n.length){if(t.has(n.join(`/`)))throw new SkillLibraryError(`INVALID_BUNDLE`,`File/directory collision: ${e.path}`);n.pop()}}const i=r.find(e=>e.path===`SKILL.md`);if(!i||!Buffer.from(i.bytes.toString(`utf8`)).equals(i.bytes))throw new SkillLibraryError(`INVALID_BUNDLE`,`Bundle requires a UTF-8 SKILL.md.`);const a=r.map(({bytes:e,...t})=>t);return{revision:sha256Hex(JSON.stringify([`openclaw.skill-library.tree.v1`,a])),files:r}}function prepareSkillLibraryBundle(e){const t=prepareSkillBundle(e);for(const e of t.files)validateSkillLibraryPath(e.path);const n=parseSkillFrontmatter(t.files.find(e=>e.path===`SKILL.md`).bytes.toString(`utf8`));if(!n.name?.trim()||!n.description?.trim()||n.description.length>1024)throw new SkillLibraryError(`INVALID_BUNDLE`,`SKILL.md requires name and description (at most 1,024 characters).`);return{...t,description:n.description}}function skillLibraryRevisionDir(e,t,n){if(!/^[a-f0-9-]{36}$/u.test(e)||!/^[a-f0-9]{64}$/u.test(t))throw new SkillLibraryError(`INVALID_BUNDLE`,`Invalid skill revision reference.`);return path.join(resolveStateDir(n),`skill-library`,e,`revisions`,t)}async function syncDirectory(e){try{const t=await fs.open(e,`r`);try{await t.sync()}finally{await t.close()}}catch(e){if(!isErrno(e)||![`EINVAL`,`ENOTSUP`,`EISDIR`,`EPERM`].includes(e.code??``))throw e}}async function cleanAbandonedSkillStaging(e){for(const t of await fs.readdir(e,{withFileTypes:true})){const n=/^\.staging-([0-9]+)-[a-zA-Z0-9]+$/u.exec(t.name);if(!n||!t.isDirectory())continue;const r=path.join(e,t.name);const i=await fs.lstat(r);if(Date.now()-i.mtimeMs<36e5)continue;try{process.kill(Number(n[1]),0)}catch(e){if(hasErrnoCode(e,`ESRCH`))await fs.rm(r,{recursive:true,force:true})}}}async function stageSkillLibraryBundle(e,t,n,r){const i=r?retainMutationAuthority(r):void 0;i?.();const a=skillLibraryRevisionDir(e,t.revision,n);const o=path.dirname(a);const s=await ensureAbsoluteDirectory(o,{mode:448});if(!s.ok)throw s.error;await cleanAbandonedSkillStaging(o);i?.();const c=await fs.mkdtemp(path.join(o,`.staging-${process.pid}-`));try{const e=await root(c,{assertBeforeMutation:i});const n=/* @__PURE__ */ new Set([c]);for(const r of t.files){const t=path.join(c,r.path);i?.();await fs.mkdir(path.dirname(t),{recursive:true,mode:448});let a=path.dirname(t);while(a!==o){n.add(a);a=path.dirname(a)}await e.create(`./${r.path}`,r.bytes,{mode:(r.executable?320:256)&~process.umask(),mkdir:false,durable:`file`})}for(const e of[...n].toSorted((e,t)=>t.length-e.length))await syncDirectory(e);return{staging:c,async publish(){i?.();try{await fs.rename(c,a)}catch(e){if(!isErrno(e)||![`EEXIST`,`ENOTEMPTY`].includes(e.code??``))throw e;await readSkillLibraryManifestTree(a,JSON.stringify(t.files.map(({bytes:e,...t})=>t)),t.revision)}await syncDirectory(o);await syncDirectory(path.dirname(o));await syncDirectory(path.dirname(path.dirname(o)));await syncDirectory(path.dirname(path.dirname(path.dirname(o))));return a},async cleanup(){await fs.rm(c,{recursive:true,force:true})}}}catch(e){await fs.rm(c,{recursive:true,force:true});throw e}}async function readSkillLibraryTree(e){const t=await readSkillBundleTree(e);for(const e of t)validateSkillLibraryPath(e.path);return t}function describeSkillTreeFailure(e){if(isErrno(e)&&e.code)return`${e.code}: ${e.message}`;return e instanceof Error?e.message:String(e)}async function readSkillBundleTree(e,t,n){const r=n?.symlinks??`reject`;const i=t?e=>t(e.path):void 0;const a=await walkDirectory(e,{maxDepth:17,maxEntries:SKILL_LIBRARY_MAX_TREE_ENTRIES,symlinks:`include`,include:i,descend:i});if(a.truncated||a.entries.some(e=>e.depth>16))throw new SkillLibraryError(`INVALID_BUNDLE`,`Skill tree exceeds traversal limits.`);if(a.failedDirs.length){const t=a.failedDirs[0];throw new SkillTreeDirectoryError(e,t.path,t.error)}const o=await root(e).catch(t=>{throw new SkillTreeDirectoryError(e,e,t)});const s=new Set(a.entries.filter(e=>e.kind===`file`).map(e=>e.relativePath));const c=[];let l=0;for(const t of a.entries){if(t.kind===`directory`)continue;if(t.kind!==`file`&&!(t.kind===`symlink`&&r===`follow-within-root`))throw new SkillLibraryError(`INVALID_BUNDLE`,`Skill trees cannot contain links or special files: root=${JSON.stringify(e)} path=${JSON.stringify(t.path)} kind=${t.kind}.`);const i=t.relativePath.split(path.sep).join(`/`);validateSkillBundlePath(i);const a=await o.read(t.relativePath,{hardlinks:`reject`,symlinks:r,maxBytes:SKILL_LIBRARY_MAX_FILE_BYTES}).catch(n=>{throw new SkillLibraryError(`INVALID_BUNDLE`,`Skill tree file could not be read: root=${JSON.stringify(e)} path=${JSON.stringify(t.path)} error=${describeSkillTreeFailure(n)}`,void 0,{cause:n})});if(r===`follow-within-root`&&!s.has(path.relative(o.rootReal,a.realPath)))throw new SkillLibraryError(`INVALID_BUNDLE`,`Skill tree link target is not an included regular file: root=${JSON.stringify(e)} path=${JSON.stringify(t.path)}.`);n?.assertFileAccess?.(t.path,a.realPath);const{buffer:u,stat:d}=a;l+=u.length;if(l>8388608||c.length>=256)throw new SkillLibraryError(`INVALID_BUNDLE`,`Skill tree exceeds bundle limits.`);c.push({path:i,...encodeSkillLibraryFile(u),executable:(d.mode&73)!==0})}return c.toSorted((e,t)=>portableCompare(e.path,t.path))}export{prepareSkillLibraryBundle as a,readSkillLibraryManifestTreeOnWorker as c,stageSkillLibraryBundle as d,validateSkillLibraryPath as f,prepareSkillBundle as i,readSkillLibraryTree as l,SkillTreeDirectoryError as n,readSkillBundleTree as o,decodeSkillLibraryFile as r,readSkillLibraryManifestTree as s,SKILL_LIBRARY_MAX_TREE_ENTRIES as t,skillLibraryRevisionDir as u};