openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
13 lines • 25.5 kB
JavaScript
import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{n as sanitizeTerminalText}from"./safe-text-B_QTgn0s.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{x as root}from"./fs-safe-Bxzu1j4h.mjs";import"./paths-D_FOvGon.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{t as normalizeClawHubSha256Hex}from"./clawhub-integrity-Cvu00MBR.mjs";import{t as flattenMarkdownToPlainText}from"./markdown-plain-text-VmGCJXBJ.mjs";import{t as digestTemplateBytes}from"./digest-DTImQMv1.mjs";import{i as stripFrontmatterBlock}from"./frontmatter-juE3lAL1.mjs";import{i as isExactSemVer,r as isCanonicalClawHubPackageName,t as clawHubTemplateRef}from"./schema-portability-CAdw2HFf.mjs";import{l as templateDependencyInventory,m as MAX_MANAGED_FILE_BYTES,n as readTemplateManifestFile}from"./reader-j_g75PYq.mjs";import{v as resolveClawHubBaseUrl,y as resolveClawHubImageUrl}from"./clawhub-client-BqChQ9oR.mjs";import{a as fetchClawHubTemplatesOverview,i as fetchClawHubPackageVersion,n as fetchClawHubPackageDetail,o as listClawHubPackages,r as fetchClawHubPackageSecurity,t as fetchClawHubPackageArtifact,u as searchClawHubPackages}from"./clawhub-packages-CwQhHItm.mjs";import{n as downloadClawHubPackageArchive}from"./clawhub-artifacts-DMR6H5O9.mjs";import{r as checkClawHubPackageTrust}from"./clawhub-install-trust-D7ZZy2yb.mjs";import{i as fetchClawHubSkillCard}from"./clawhub-skills-C-RPCCPF.mjs";import{l as parseRequestedClawHubSkillRef}from"./clawhub-store-xP-XC4fY.mjs";import{n as withExtractedArchiveRoot}from"./install-flow-wXl8VgRG.mjs";import{createReadStream}from"node:fs";import path from"node:path";import{createHash}from"node:crypto";import fs$1 from"node:fs/promises";import{AsyncLocalStorage}from"node:async_hooks";import{performance}from"node:perf_hooks";import{isUtf8}from"node:buffer";
//!src/templates/timings.ts
const log=createSubsystemLogger(`gateway/templates-add/timing`);const timingContext=new AsyncLocalStorage;async function withTemplateAddTimings(e,t){return await timingContext.run({requestId:e,started:performance.now(),sequence:0},()=>measureTemplateAddStage(`add.total`,t))}function startTemplateAddStage(e,t={}){const n=timingContext.getStore();const r=performance.now();const i=n?++n.sequence:0;let a=false;const record=(a,o)=>{if(!n)return;log.debug(`Template Add timing`,{requestId:n.requestId,spanId:i,stage:e,phase:a,elapsedMs:Math.round((performance.now()-n.started)*100)/100,...o?{outcome:o,durationMs:Math.round((performance.now()-r)*100)/100}:{},...t})};record(`start`);const end=e=>{if(!a){a=true;record(`end`,e)}};return{end,[Symbol.dispose]:()=>end(`error`)}}async function measureTemplateAddStage(e,t,n){try{var r=_usingCtx();const i=r.u(startTemplateAddStage(e,n));const a=await t();i.end(`ok`);return a}catch(e){r.e=e}finally{r.d()}}
//!src/templates/catalog-dependencies.ts
function projectTemplateCatalogDependencies(e,t){const n=templateDependencyInventory(e,t);return{skills:n.filter(e=>e.kind===`skill`).map(e=>e.source===`bundled`?{name:e.name??e.path,source:e.source,path:e.path}:{name:e.ref,source:e.source,ref:e.ref,version:e.version}),integrations:[...n.filter(e=>e.kind===`plugin`).map(e=>e.source===`bundled`?{name:e.name??e.path,source:e.source,path:e.path,kind:`plugin`}:{name:e.ref,source:e.source,ref:e.ref,version:e.version,kind:`plugin`}),...Object.keys(e.mcpServers).map(e=>({name:e,kind:`mcpServer`}))]}}
//!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`}};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 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 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})}}const MAX_REPORTED_MANIFEST_DIAGNOSTICS=3;async function describeManifestDiagnostics(e,t){const n=await fs$1.realpath(e).catch(()=>e);const r=[.../* @__PURE__ */ new Set([n,e])].toSorted((e,t)=>t.length-e.length);const i=t.slice(0,MAX_REPORTED_MANIFEST_DIAGNOSTICS).map(e=>{let t=e.message;for(const e of r)t=t.replaceAll(`${e}${path.sep}`,``).replaceAll(e,`.`);return sanitizeTerminalText(`${e.code} at ${e.path}: ${t}`)});const a=t.length-i.length;return` ${i.join(`; `)}${a>0?` (${a} more)`:``}`}async function readVerifiedArtifactSource(e){const t=await readTemplateManifestFile(e.sourceRoot);if(!t.ok)throw new ClawHubSourceError(`clawhub_manifest_invalid`,`Downloaded Template package manifest is invalid.${await describeManifestDiagnostics(e.sourceRoot,t.diagnostics)}`);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}}}
//!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{id:t.id,...t.name!==void 0?{name:t.name}:{},...t.description!==void 0?{description:t.description}:{}}}
//!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.`);if(!isUtf8(t.buffer))throw new ClawHubSourceError(`clawhub_preview_not_text`,`This workspace file is not text, so it has no 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;if(e.source===`bundled`){const t=(i.snapshot.bundledSources?.find(t=>t.kind===`skill`&&t.path===e.path))?.snapshot.files.find(e=>e.path===`SKILL.md`);if(!t)throw new ClawHubSourceError(`clawhub_preview_unavailable`,`This bundled skill is unavailable in the verified release.`);const n=await(await root(a)).read(`${e.path}/SKILL.md`,{hardlinks:`reject`,symlinks:`reject`,maxBytes:MAX_MANAGED_FILE_BYTES});if(n.buffer.byteLength!==t.byteLength||digestTemplateBytes(n.buffer)!==t.digest)throw new ClawHubSourceError(`clawhub_preview_unavailable`,`This bundled skill changed during preview.`);return{kind:`skill`,name:e.name,content:n.buffer.toString(`utf8`)}}const n=parseRequestedClawHubSkillRef(e.name);const s=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:s}}}async function readClawHubCatalogExcerpt(e){return await readClawHubCatalogPreview(e).catch(e=>{if(e instanceof ClawHubSourceError&&e.code===`clawhub_preview_not_text`)return;throw e})}
//!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)||!matchesTemplatePublisher(n.name,r)||n.name!==t&&clawHubTemplateRef(n.name,r)!==t||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 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)}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 readClawHubTemplatesOverview(e={}){const t=await fetchClawHubTemplatesOverview(e);if(isRecord(t)&&t.complete===false)return;if(!isRecord(t)||t.complete!==true||!Array.isArray(t.featured)||!Array.isArray(t.sections)||!t.sections.every(e=>isRecord(e)&&typeof e.category===`string`&&Array.isArray(e.items)))throw new ClawHubSourceError(`clawhub_catalog_invalid`,`ClawHub returned a malformed Template overview.`);const n=e.limit??8;return{featured:projectPublicEntries(t.featured,e.baseUrl).slice(0,n),sections:t.sections.map(t=>({category:t.category,entries:projectPublicEntries(t.items,e.baseUrl).toSorted(rankByInstalls).slice(0,n)}))}}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);if(e.version!==void 0)requireExactVersion(e.version);const t=fetchClawHubPackageDetail({...e,name:e.packageName}).then(t=>requirePublicTemplatePackage(t,e.packageName));const n=e.version!==void 0?Promise.resolve(e.version):t.then(e=>{if(!e.latestVersion)throw new ClawHubSourceError(`clawhub_version_unavailable`,`ClawHub has no published version.`);requireExactVersion(e.latestVersion);return e.latestVersion});const r=n.then(t=>fetchClawHubPackageVersion({...e,name:e.packageName,version:t}));const i=n.then(t=>fetchClawHubPackageSecurity({...e,name:e.packageName,version:t})).catch(()=>void 0);const a=new AbortController;const o=n.then(t=>downloadClawHubPackageArchive({...e,signal:e.signal?AbortSignal.any([e.signal,a.signal]):a.signal,name:e.packageName,version:t,artifact:`clawpack`,timeoutMs:e.timeoutMs??3e4}));try{const[a,s,c,l,u]=await Promise.all([t,r,o,n,i]);if(s.package?.name!==a.name||s.package.family!==`template`)throw new ClawHubSourceError(`clawhub_identity_mismatch`,`ClawHub release identity changed.`);if(!s.version||s.version.version!==l)throw new ClawHubSourceError(`clawhub_version_unavailable`,`ClawHub release identity changed.`);const d=parseTemplateManifestSummary(s.version.templateManifestSummary);const f=Array.isArray(a.categories)?a.categories.filter(e=>typeof e===`string`&&e.length>0):[];const{contents:p}=await readClawHubTemplateContents({...e,packageName:a.name,version:l},void 0,{download:c,artifact:{package:s.package,version:l,artifact:s.version.artifact}});return{...projectCatalogEntry({...a,icon:s.version.icon},e.baseUrl),version:l,agentId:d.id,...d.name?{agentName:d.name}:{},...d.description?{agentDescription:d.description}:{},workspaceFiles:p.instructions.length,skills:p.skills.length,plugins:p.integrations.filter(e=>e.kind===`plugin`).length,mcpServers:p.integrations.filter(e=>e.kind===`mcpServer`).length,scheduledJobs:p.automations.length,contents:p,...Number.isFinite(a.createdAt)?{createdAtMs:Math.max(0,a.createdAt)}:{},...f.length?{categories:f}:{},...u?.package?.name===a.name&&u.release?.version===l?{security:{...u.verdict?{verdict:u.verdict}:{},auditUrl:u.securityAuditUrl}}:{}}}catch(e){a.abort(e);throw e}finally{await o.then(e=>e.cleanup(),()=>void 0)}}async function readClawHubTemplatePreview(e){requireTemplateName(e.packageName);requireExactVersion(e.version);const t=requirePublicTemplatePackage(await fetchClawHubPackageDetail({...e,name:e.packageName}),e.packageName);const{preview:n}=await readClawHubTemplateContents({...e,packageName:t.name},{kind:e.kind,name:e.name});if(!n)throw new ClawHubSourceError(`clawhub_preview_unavailable`,`This item is not in the Template release.`);return n}async function readClawHubTemplateContents(e,t,n){const r=n?.artifact??await fetchClawHubPackageArtifact({...e,name:e.packageName});const i=readExactTemplateArtifact(r,e);const a=n?.download??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(a,i);const n=(await fs$1.stat(a.archivePath)).size;const r=await withExtractedArchiveRoot({archivePath:a.archivePath,tempDirPrefix:`openclaw-template-catalog-`,timeoutMs:e.timeoutMs??3e4,rootMarkers:[`package.json`,`CLAW.md`],onExtracted:async r=>{const a=await readVerifiedArtifactSource({sourceRoot:r,packageName:e.packageName,version:e.version,artifactSha256:i.sha256,artifactByteLength:n});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{skills:c,integrations:l}=projectTemplateCatalogDependencies(o,a.snapshot.bundledSources);const[u,d]=t?[s,c]:await Promise.all([Promise.all(s.map(async t=>{const n=toCatalogExcerpt((await readClawHubCatalogExcerpt({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 f=await readClawHubCatalogPreview({params:e,requested:t,instructions:s,skills:c,verified:a,rootDir:r});return{ok:true,value:{contents:{instructions:u,skills:d,integrations:l,automations:o.automations.map(e=>({name:e.name||e.id,enabled:e.enabled??true,schedule:e.schedule.cron,timezone:e.schedule.timezone}))},...f?{preview:f}:{}}}}});if(!r.ok||!(`value`in r))throw new ClawHubSourceError(`clawhub_extract_failed`,r.error);return r.value}finally{if(!n)await a.cleanup()}}async function withResolvedClawHubSource(e){const t=e.coordinate.packageName;requireTemplateName(t);if(e.coordinate.version!==void 0)requireExactVersion(e.coordinate.version);const[n,r]=await measureTemplateAddStage(`source.metadata`,()=>Promise.all([measureTemplateAddStage(`source.metadata.detail`,()=>fetchClawHubPackageDetail({...e,name:t})),e.coordinate.version===void 0?Promise.resolve(void 0):fetchClawHubPackageArtifact({...e,name:t,version:e.coordinate.version})]));const i=requirePublicTemplatePackage(n,t);const a=i.name;const o=e.coordinate.version??i.latestVersion;if(!o)throw new ClawHubSourceError(`clawhub_version_unavailable`,`ClawHub has no published version.`);requireExactVersion(o);const s=r??await fetchClawHubPackageArtifact({...e,name:a,version:o});const c=readExactTemplateArtifact(s,{packageName:a,version:o});const l=c.sha256;const u=await measureTemplateAddStage(`source.trust`,()=>checkClawHubPackageTrust({subject:{kind:`template`,packageName:a},version:o,expectedTemplateArtifact:{sha256:l,npmIntegrity:c.npmIntegrity,...c.npmShasum!==void 0?{npmShasum:c.npmShasum}:{}},baseUrl:e.baseUrl,token:e.token,timeoutMs:e.timeoutMs}));if(!u.ok)throw new ClawHubSourceError(u.code??`clawhub_trust_failed`,u.error,u.warning);const d=u.trustInstallRecordFields.clawhubTrustDisposition===`review-required`;if(e.mode===`apply`&&d&&!e.acknowledgeClawHubRisk)throw new ClawHubSourceError(`clawhub_risk_acknowledgement_required`,`Explicit acknowledgement is required for this ClawHub release.`,u.warning);const f={...u.warning?{trustWarning:u.warning}:{},riskAcknowledgementRequired:d,trustRecord:u.trustInstallRecordFields};const p=await measureTemplateAddStage(`source.download`,()=>downloadClawHubPackageArchive({name:a,version:o,artifact:`clawpack`,baseUrl:e.baseUrl,token:e.token,timeoutMs:e.timeoutMs??3e4}));try{try{var m=_usingCtx();assertClawHubDownloadIntegrity(p,c);const t=(await fs$1.stat(p.archivePath)).size;const n=m.u(startTemplateAddStage(`source.extract`));const r=await withExtractedArchiveRoot({archivePath:p.archivePath,tempDirPrefix:`openclaw-template-source-`,timeoutMs:e.timeoutMs??3e4,rootMarkers:[`package.json`,`CLAW.md`],onExtracted:async r=>{n.end(`ok`);const i=await measureTemplateAddStage(`source.verify`,()=>readVerifiedArtifactSource({sourceRoot:r,packageName:a,version:o,artifactSha256:l,artifactByteLength:t}));if(e.baseUrl!==void 0&&resolveClawHubBaseUrl(e.baseUrl)!==resolveClawHubBaseUrl()&&templateDependencyInventory(i.manifest).length>0)throw new ClawHubSourceError(`clawhub_registry_mismatch`,`ClawHub Template dependencies require the configured registry.`);let s;const persistSource=async()=>{if(e.mode!==`apply`)throw new ClawHubSourceError(`clawhub_preview_persistence_forbidden`,`A ClawHub preview cannot persist package content.`);s??=(async()=>{const n=await measureTemplateAddStage(`source.persist`,()=>persistExtractedSource({rootDir:r,archivePath:p.archivePath,artifactSha256:l,artifactByteLength:t,stateDir:e.stateDir}));return await measureTemplateAddStage(`source.verify`,()=>readVerifiedArtifactSource({sourceRoot:n,packageName:a,version:o,artifactSha256:l,artifactByteLength:t}))})();return await s};return{ok:true,value:await e.run(i,f,persistSource)}}});if(!r.ok||!(`value`in r))throw new ClawHubSourceError(`clawhub_extract_failed`,r.error);return{value:r.value,...f}}catch(e){m.e=e}finally{m.d()}}finally{await p.cleanup()}}export{searchClawHubTemplates as a,measureTemplateAddStage as c,readClawHubTemplatesOverview as i,withTemplateAddTimings as l,readClawHubTemplateDetail as n,withResolvedClawHubSource as o,readClawHubTemplatePreview as r,ClawHubSourceError as s,listClawHubTemplates as t};