UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 17.5 kB
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{c as resolveUserPath,i as resolveOsHomeRelativePath}from"./home-dir-DEN5DisQ.mjs";import{r as isPathInside}from"./path-guards-DGttsOJI.mjs";import{n as sanitizeForLog}from"./ansi-54CEWBZf.mjs";import{r as terminalText}from"./safe-text-B_QTgn0s.mjs";import"./utils-Dlk0IYAa.mjs";import{l as pathExists,x as root}from"./fs-safe-Bxzu1j4h.mjs";import{o as redactSensitiveUrlLikeString}from"./redact-sensitive-url-Byg68d6v.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{r as resolvePreferredOpenClawTmpDir}from"./tmp-openclaw-dir-DapBruir.mjs";import{l as tryReadJson}from"./json-files-BBQ_0Np0.mjs";import{t as hasHttpUrlPrefix}from"./url-protocol-BLfSvQhh.mjs";import{i as fetchWithSsrFGuard}from"./fetch-guard-B_7-F5Lc.mjs";import{d as resolveArchiveKind}from"./archive-BAuHVLxp.mjs";import{i as acquireGitSource,n as isImmutableGitCommitRef}from"./git-install-D5rgS26L.mjs";import{P as copyPluginInstallTransactionRequest}from"./npm-managed-root-BH-RZlFm.mjs";import{n as installPluginFromPath}from"./install-BIl_Ot-i.mjs";import path from"node:path";import fs from"node:fs/promises";import os from"node:os";import{readRegularFile}from"@openclaw/fs-safe/advanced";import{tempWorkspace}from"@openclaw/fs-safe/temp"; //!src/plugins/marketplace.ts const DEFAULT_MARKETPLACE_DOWNLOAD_TIMEOUT_MS=12e4;const MAX_MARKETPLACE_ARCHIVE_BYTES=268435456;const MAX_MARKETPLACE_MANIFEST_BYTES=16777216;const MARKETPLACE_MANIFEST_CANDIDATES=[path.join(`.claude-plugin`,`marketplace.json`),`marketplace.json`];const CLAUDE_KNOWN_MARKETPLACES_PATH=path.join(`~`,`.claude`,`plugins`,`known_marketplaces.json`);function isGitUrl(e){return/^git@/i.test(e)||/^ssh:\/\//i.test(e)||/^https?:\/\/.+\.git(?:#.*)?$/i.test(e)}function looksLikeGitHubRepoShorthand(e){return/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:#.+)?$/.test(e.trim())}function splitRef(e){const t=e.trim();const n=t.lastIndexOf(`#`);if(n<=0||n>=t.length-1)return{base:t};return{base:t.slice(0,n),ref:normalizeOptionalString(t.slice(n+1))}}function normalizeEntrySource(e){if(typeof e===`string`){const t=e.trim();if(!t)return{ok:false,error:`empty plugin source`};if(hasHttpUrlPrefix(t))return{ok:true,source:{kind:`url`,url:t}};return{ok:true,source:{kind:`path`,path:t}}}if(!e||typeof e!==`object`)return{ok:false,error:`plugin source must be a string or object`};const t=e;const n=normalizeOptionalString(t.type)??normalizeOptionalString(t.source);if(!n)return{ok:false,error:`plugin source object missing "type" or "source"`};if(n===`path`||n===`url`){const e=normalizeOptionalString(t[n]);if(!e)return{ok:false,error:`${n} source missing "${n}"`};return{ok:true,source:n===`path`?{kind:n,path:e}:{kind:n,url:e}}}if(n===`github`||n===`git`||n===`git-subdir`){const e=n===`github`?normalizeOptionalString(t.repo)??normalizeOptionalString(t.url):normalizeOptionalString(t.url)??normalizeOptionalString(t.repo);if(!e)return{ok:false,error:`${n} source missing "${n===`github`?`repo`:`url`}"`};const r=normalizeOptionalString(t.path)??(n===`git-subdir`?normalizeOptionalString(t.subdir):void 0);if(n===`git-subdir`&&!r)return{ok:false,error:`git-subdir source missing "path"`};const i=normalizeOptionalString(t.ref)??normalizeOptionalString(t.branch)??normalizeOptionalString(t.tag);return{ok:true,source:n===`github`?{kind:n,repo:e,path:r,ref:i}:n===`git-subdir`?{kind:n,url:e,path:r,ref:i}:{kind:n,url:e,path:r,ref:i}}}return{ok:false,error:`unsupported plugin source kind: ${n}`}}function marketplaceEntrySourceToInput(e){switch(e.kind){case`path`:return e.path;case`github`:return`${e.repo}${e.ref?`#${e.ref}`:``}`;case`git`:case`git-subdir`:return`${e.url}${e.ref?`#${e.ref}`:``}`;default:return e.url}}function marketplaceEntryGitRef(e){switch(e.kind){case`github`:case`git`:case`git-subdir`:return e.ref;case`url`:return resolveArchiveKind(e.url)?void 0:normalizeGitCloneSource(e.url)?.ref;default:return}}function marketplaceInstallPolicyRequest(e){const t=Boolean(resolveArchiveKind(e.resolvedPath));const n=e.marketplaceOrigin===`remote`;const r=e.source.kind===`github`||e.source.kind===`git`||e.source.kind===`git-subdir`||e.source.kind===`url`&&!resolveArchiveKind(e.source.url);let i;if(e.source.kind===`path`&&!hasHttpUrlPrefix(e.source.path))i={kind:t?`archive`:n?`git`:`local-path`,authority:n?`third-party`:`user`,mutable:n?!isImmutableGitCommitRef(e.marketplaceRef):true,network:n};else i={kind:t||e.source.kind===`path`||!r?`archive`:`git`,authority:`third-party`,mutable:!isImmutableGitCommitRef(marketplaceEntryGitRef(e.source)),network:true};return{kind:t?`plugin-archive`:n||r?`plugin-git`:`plugin-dir`,requestedSpecifier:e.requestedSpecifier,source:i}}function parseMarketplaceManifest(e,t){let n;try{n=JSON.parse(e)}catch(e){return{ok:false,error:`invalid marketplace JSON at ${t}: ${String(e)}`}}if(!n||typeof n!==`object`)return{ok:false,error:`invalid marketplace JSON at ${t}: expected object`};const r=n;if(!Array.isArray(r.plugins))return{ok:false,error:`invalid marketplace JSON at ${t}: missing plugins[]`};const i=[];for(const e of r.plugins){if(!e||typeof e!==`object`)return{ok:false,error:`invalid marketplace entry in ${t}: expected object`};const n=e;const r=normalizeOptionalString(n.name);if(!r)return{ok:false,error:`invalid marketplace entry in ${t}: missing name`};const a=normalizeEntrySource(n.source);if(!a.ok)return{ok:false,error:`invalid marketplace entry "${r}" in ${t}: ${a.error}`};i.push({name:r,version:normalizeOptionalString(n.version),description:normalizeOptionalString(n.description),source:a.source})}return{ok:true,manifest:{name:normalizeOptionalString(r.name),version:normalizeOptionalString(r.version),plugins:i}}}async function readClaudeKnownMarketplaces(){const e=resolveOsHomeRelativePath(CLAUDE_KNOWN_MARKETPLACES_PATH);const t=await tryReadJson(e);if(!t||typeof t!==`object`)return{};const n=t;const r={};for(const[e,t]of Object.entries(n)){if(!t||typeof t!==`object`)continue;const n=t;r[e]={installLocation:normalizeOptionalString(n.installLocation),source:n.source}}return r}function deriveMarketplaceRootFromManifestPath(e){const t=path.dirname(e);return path.basename(t)===`.claude-plugin`?path.dirname(t):t}async function findMarketplaceManifestPath(e){for(const t of MARKETPLACE_MANIFEST_CANDIDATES){const n=path.join(e,t);if(await pathExists(n))return n}}async function resolveLocalMarketplaceSource(e){const t=resolveUserPath(e);if(!await pathExists(t))return null;const n=await fs.stat(t);if(n.isFile())return{ok:true,rootDir:deriveMarketplaceRootFromManifestPath(t),manifestPath:t};if(!n.isDirectory())return{ok:false,error:`unsupported marketplace source: ${t}`};const r=path.basename(t)===`.claude-plugin`?path.dirname(t):t;const i=await findMarketplaceManifestPath(r);if(i)return{ok:true,rootDir:r,manifestPath:i};return{ok:false,error:`marketplace manifest not found under ${t}`}}function normalizeGitCloneSource(e){const t=splitRef(e);if(looksLikeGitHubRepoShorthand(t.base))return{url:`https://github.com/${t.base}.git`,ref:t.ref,label:t.base};if(isGitUrl(e))return{url:t.base,ref:t.ref,label:t.base};if(hasHttpUrlPrefix(e))try{const e=new URL(t.base);if(e.hostname!==`github.com`)return null;const n=e.pathname.replace(/\/+$/,``).split(`/`).filter(Boolean);if(n.length<2)return null;const r=`${n[0]}/${n[1]?.replace(/\.git$/i,``)}`;return{url:`https://github.com/${r}.git`,ref:t.ref,label:r}}catch{return null}return null}async function cloneMarketplaceRepo(e){const t=normalizeGitCloneSource(e.source);if(!t)return{ok:false,error:`unsupported marketplace source: ${e.source}`};const n=await fs.mkdtemp(path.join(os.tmpdir(),`openclaw-marketplace-`));const r=path.join(n,`repo`);const cleanup=()=>fs.rm(n,{recursive:true,force:true}).catch(()=>void 0);e.logger?.info?.(terminalText`Cloning marketplace source ${t.label}...`);const i=await acquireGitSource({...t,repoDir:r,refMode:isImmutableGitCommitRef(t.ref)?`detached`:`shallow-branch`,timeoutMs:e.timeoutMs,cloneSeparator:false,recordCommit:false,cleanupOnFailure:cleanup,formatFailure:({action:e,stdout:n,stderr:r})=>{const i=r.trim()||n.trim()||`git ${e} failed`;return`failed to ${e} marketplace source ${t.label}: ${i}`}});if(!i.ok)return i;return{ok:true,rootDir:r,label:t.label,...t.ref?{ref:t.ref}:{},cleanup}}async function loadMarketplace(e){const loadMarketplaceFromManifestFile=async e=>{let t;try{const n=await fs.realpath(e.manifestPath);const{buffer:r}=await readRegularFile({filePath:n,maxBytes:MAX_MARKETPLACE_MANIFEST_BYTES});t=r.toString(`utf-8`)}catch(t){await e.cleanup?.();const n=t instanceof Error?t.message:String(t);if(n.startsWith(`File exceeds`))return{ok:false,error:`Marketplace manifest too large`};return{ok:false,error:`Marketplace manifest unreadable: ${n}`}}const n=parseMarketplaceManifest(t,e.manifestPath);if(!n.ok){await e.cleanup?.();return n}const r=await validateMarketplaceManifest({manifest:n.manifest,sourceLabel:e.sourceLabel,rootDir:e.rootDir,origin:e.origin});if(!r.ok){await e.cleanup?.();return r}return{ok:true,marketplace:{manifest:r.manifest,rootDir:e.rootDir,sourceLabel:e.sourceLabel,origin:e.origin,...e.remoteRef?{remoteRef:e.remoteRef}:{},cleanup:e.cleanup}}};const t=await readClaudeKnownMarketplaces();const n=/* @__PURE__ */ new Set;let r=e.source;while(true){const e=t[r];if(!e)break;if(n.has(r))return{ok:false,error:`known marketplace source cycle: ${[...n,r].join(` -> `)}`};n.add(r);if(e.installLocation){const t=await resolveLocalMarketplaceSource(e.installLocation);if(t?.ok)return await loadMarketplaceFromManifestFile({...t,sourceLabel:r,origin:`local`})}const i=normalizeEntrySource(e.source);if(!i.ok)break;r=marketplaceEntrySourceToInput(i.source)}const i=await resolveLocalMarketplaceSource(r);if(i?.ok===false)return i;if(i?.ok)return await loadMarketplaceFromManifestFile({...i,sourceLabel:i.manifestPath,origin:`local`});const a=await cloneMarketplaceRepo({source:r,timeoutMs:e.timeoutMs,logger:e.logger});if(!a.ok)return a;const o=await findMarketplaceManifestPath(a.rootDir);if(!o){await a.cleanup();return{ok:false,error:`marketplace manifest not found in ${a.label}`}}return await loadMarketplaceFromManifestFile({manifestPath:o,sourceLabel:a.label,rootDir:a.rootDir,origin:`remote`,...a.ref?{remoteRef:a.ref}:{},cleanup:a.cleanup})}function resolveSafeMarketplaceDownloadFileName(e,t){const n=new URL(e).pathname;const r=path.basename(n).trim()||t;if(r===`.`||r===`..`||/^[a-zA-Z]:/.test(r)||path.isAbsolute(r)||r.includes(`/`)||r.includes(`\\`))throw new Error(`invalid download filename`);return r}function resolveMarketplaceDownloadTimeoutMs(e){return Math.max(1e3,Math.floor(typeof e===`number`&&Number.isFinite(e)?e:DEFAULT_MARKETPLACE_DOWNLOAD_TIMEOUT_MS))}function formatMarketplaceDownloadError(e,t){return`failed to download ${sanitizeForLog(redactSensitiveUrlLikeString(e))}: `+sanitizeForLog(t)}function parseMarketplaceContentLength(e){const t=e.trim();if(!/^\d+$/.test(t))throw new Error(`invalid content-length header: ${e}`);const n=Number(t);if(!Number.isSafeInteger(n))throw new Error(`invalid content-length header: ${e}`);return n}async function downloadUrlToTempFile(e,t){let n;try{const r=resolveSafeMarketplaceDownloadFileName(e,`plugin.tgz`);const i=resolveMarketplaceDownloadTimeoutMs(t);const{response:a,finalUrl:o,release:s}=await fetchWithSsrFGuard({url:e,timeoutMs:i,auditContext:`marketplace-plugin-download`});try{if(!a.ok)return{ok:false,error:formatMarketplaceDownloadError(e,`HTTP ${a.status}`)};if(!a.body)return{ok:false,error:formatMarketplaceDownloadError(e,`empty response body`)};const t=a.headers.get(`content-length`);if(t){const e=parseMarketplaceContentLength(t);if(e>MAX_MARKETPLACE_ARCHIVE_BYTES)throw new Error(`download too large: ${e} bytes (limit: ${MAX_MARKETPLACE_ARCHIVE_BYTES} bytes)`)}const i=resolveSafeMarketplaceDownloadFileName(o,r);const s=resolveArchiveKind(i)?i:r;n=await tempWorkspace({rootDir:resolvePreferredOpenClawTmpDir(),prefix:`openclaw-marketplace-download-`});const c=n;const l=n.path(s);await(await root(n.dir)).create(s,a.body,{maxBytes:MAX_MARKETPLACE_ARCHIVE_BYTES,mode:438&~process.umask(),durable:false});return{ok:true,path:l,cleanup:async()=>{await c.cleanup().catch(()=>void 0)}}}finally{a.body?.cancel().catch(()=>void 0);await s().catch(()=>void 0)}}catch(t){await n?.cleanup().catch(()=>void 0);return{ok:false,error:formatMarketplaceDownloadError(e,formatErrorMessage(t))}}}async function ensureInsideMarketplaceRoot(e,t,n){const r=path.resolve(e,t);const i=await pathExists(r);const a={ok:false,error:`plugin source escapes marketplace root: ${t}`};if(!isPathInside(e,r))return a;if(n?.canonicalRootDir){if(!(await fs.lstat(n.canonicalRootDir)).isDirectory())return a;const e=await fs.realpath(n.canonicalRootDir);let t=r;while(!await pathExists(t)){const e=path.dirname(t);if(e===t)return a;t=e}const i=await fs.realpath(t);if(!isPathInside(e,i))return a}if(!i)return{ok:false,error:`plugin source not found in marketplace root: ${t}`};return{ok:true,path:r}}async function validateMarketplaceManifest(e){if(e.origin===`local`)return{ok:true,manifest:e.manifest};const t=await fs.realpath(e.rootDir);for(const n of e.manifest.plugins){const r=n.source;let i;if(r.kind!==`path`)i=`remote marketplaces may not use ${r.kind} plugin sources`;else if(hasHttpUrlPrefix(r.path))i=`remote marketplaces may not use HTTP(S) plugin paths`;else if(path.isAbsolute(r.path))i=`remote marketplaces may only use relative plugin paths`;else{const n=await ensureInsideMarketplaceRoot(e.rootDir,r.path,{canonicalRootDir:t});if(!n.ok)i=n.error}if(i)return{ok:false,error:`invalid marketplace entry "${n.name}" in ${e.sourceLabel}: ${i}`}}return{ok:true,manifest:e.manifest}}async function resolveMarketplaceEntryInstallPath(e){if(e.source.kind===`path`){if(hasHttpUrlPrefix(e.source.path)){if(resolveArchiveKind(e.source.path))return await downloadUrlToTempFile(e.source.path,e.timeoutMs);return{ok:false,error:`unsupported remote plugin path source: ${e.source.path}`}}const t=e.marketplaceOrigin===`remote`?await fs.realpath(e.marketplaceRootDir):void 0;return path.isAbsolute(e.source.path)?{ok:true,path:e.source.path}:await ensureInsideMarketplaceRoot(e.marketplaceRootDir,e.source.path,{canonicalRootDir:t})}if(e.source.kind===`url`){if(resolveArchiveKind(e.source.url))return await downloadUrlToTempFile(e.source.url,e.timeoutMs);if(!normalizeGitCloneSource(e.source.url))return{ok:false,error:`unsupported URL plugin source: ${e.source.url}`}}const t=await cloneMarketplaceRepo({source:marketplaceEntrySourceToInput(e.source),timeoutMs:e.timeoutMs,logger:e.logger});if(!t.ok)return t;if(e.source.kind===`url`)return{ok:true,path:t.rootDir,cleanup:t.cleanup};const n=e.source.path??`.`;const r=await fs.realpath(t.rootDir);const i=await ensureInsideMarketplaceRoot(t.rootDir,n,{canonicalRootDir:r});if(!i.ok){await t.cleanup();return i}return{ok:true,path:i.path,cleanup:t.cleanup}}async function listMarketplacePlugins(e){const t=await loadMarketplace({source:e.marketplace,logger:e.logger,timeoutMs:e.timeoutMs});if(!t.ok)return t;try{return{ok:true,manifest:t.marketplace.manifest,sourceLabel:t.marketplace.sourceLabel}}finally{await t.marketplace.cleanup?.()}}async function resolveMarketplaceInstallShortcut(e){const t=e.trim();const n=t.lastIndexOf(`@`);if(n<=0||n>=t.length-1)return null;const r=t.slice(0,n).trim();const i=t.slice(n+1).trim();if(!r||!i||r.includes(`/`))return null;const a=(await readClaudeKnownMarketplaces())[i];if(!a)return null;if(!a.installLocation){const e=normalizeEntrySource(a.source);if(!e.ok)return{ok:false,error:`known Claude marketplace "${i}" has an invalid source: ${e.error}`}}return{ok:true,plugin:r,marketplaceSource:i}}async function installPluginFromMarketplace(e){const t=await loadMarketplace({source:e.marketplace,logger:e.logger,timeoutMs:e.timeoutMs});if(!t.ok)return t;let n;try{const r=t.marketplace.manifest.plugins.filter(t=>t.name===e.plugin);if(r.length>1)return{ok:false,error:`plugin "${e.plugin}" is ambiguous in marketplace ${t.marketplace.sourceLabel}: ${r.length} entries share this name; remove or rename the duplicate entries`};const[i]=r;if(!i){const n=t.marketplace.manifest.plugins.map(e=>e.name).toSorted();return{ok:false,error:`plugin "${e.plugin}" not found in marketplace ${t.marketplace.sourceLabel}`+(n.length>0?` (available: ${n.join(`, `)})`:``)}}const a=await resolveMarketplaceEntryInstallPath({source:i.source,marketplaceRootDir:t.marketplace.rootDir,marketplaceOrigin:t.marketplace.origin,logger:e.logger,timeoutMs:e.timeoutMs});if(!a.ok)return a;n=a.cleanup;const o=await installPluginFromPath(copyPluginInstallTransactionRequest(e,{onInstallPolicyWarning:e.onInstallPolicyWarning,config:e.config,path:a.path,logger:e.logger,mode:e.mode,extensionsDir:e.extensionsDir,timeoutMs:e.timeoutMs,workTimeoutMs:e.workTimeoutMs,dryRun:e.dryRun,expectedPluginId:e.expectedPluginId,onBeforePluginArtifactCommit:e.onBeforePluginArtifactCommit,beforePersistentApply:e.beforePersistentApply,installPolicyRequest:marketplaceInstallPolicyRequest({marketplaceOrigin:t.marketplace.origin,marketplaceRef:t.marketplace.remoteRef,resolvedPath:a.path,source:i.source,requestedSpecifier:`${i.name}@${e.marketplace}`})}));if(!o.ok)return o;return{...o,marketplaceName:t.marketplace.manifest.name,marketplacePlugin:i.name,marketplaceSource:e.marketplace}}finally{await n?.();await t.marketplace.cleanup?.()}}export{listMarketplacePlugins as n,resolveMarketplaceInstallShortcut as r,installPluginFromMarketplace as t};