UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

35 lines (34 loc) • 49.9 kB
import{c as resolveUserPath}from"./home-dir-DEN5DisQ.mjs";import"./src-0ci69Prg.mjs";import{n as coerceErrorMessage}from"./error-coercion-DlKnt6w-.mjs";import{t as stableStringify}from"./stable-stringify-Cy0VZ0ci.mjs";import{r as defaultRuntime}from"./runtime-DIcLIHcp.mjs";import{r as isPathInside}from"./path-guards-DGttsOJI.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import"./utils-Dlk0IYAa.mjs";import{t as FsSafeError,x as root}from"./fs-safe-Bxzu1j4h.mjs";import{t as resolvePathViaExistingAncestorSync$1}from"./boundary-path-BeuXNL_4.mjs";import{c as normalizePluginId,f as resolveEffectiveEnableState,u as normalizePluginsConfig}from"./config-state-C1eV6UWf.mjs";import"./paths-D_FOvGon.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import{t as _usingCtx}from"./usingCtx-CUVyQ_FT.mjs";import{r as resolvePreferredOpenClawTmpDir}from"./tmp-openclaw-dir-DapBruir.mjs";import"./kysely-sync-R08Pt8qn.mjs";import"./openclaw-state-db-schema-helpers-rYTimzjJ.mjs";import"./sqlite-number-B9pFqi3P.mjs";import{a as loadInstalledPluginIndex}from"./installed-plugin-index-B04a42mO.mjs";import{n as isBundledPluginInsideDevSourceRoot}from"./dev-source-root-DAAlxKxb.mjs";import{a as resolveDefaultPluginExtensionsDir,c as resolvePluginInstallDir,m as validatePluginId}from"./install-paths-BDaSzd4l.mjs";import{n as normalizeClawHubSha256Integrity}from"./clawhub-integrity-Cvu00MBR.mjs";import{G as parseClawHubPluginSpec}from"./official-external-plugin-catalog-BkSwu5lo.mjs";import{o as preparePluginMetadataMachineStateAsync}from"./installed-plugin-index-record-state-Dlesa-xK.mjs";import{r as loadInstalledPluginIndexInstallRecords}from"./installed-plugin-index-record-reader-rJXlMUQ8.mjs";import{t as parseDurationMs}from"./parse-duration-BueP0M46.mjs";import{a as migrateLegacyConfiguredMcpServer}from"./mcp-config-normalize-CYgCUSX3.mjs";import{l as readConfigFileSnapshotForWrite}from"./io.runtime-BvSeVFIY.mjs";import"./config-DkZ8y8Gv.mjs";import{n as digestTemplateValue,t as digestTemplateBytes}from"./digest-DTImQMv1.mjs";import{r as templateOwnedAgentConfig}from"./agent-config-ownership-BlIgOfK5.mjs";import{s as withPluginLifecycleLeaseAsync}from"./plugin-lifecycle-lease-D-y0xYkr.mjs";import"./installed-plugin-index-records-DMOoWiOF.mjs";import{a as resolveLocalProviderAuthEvidence}from"./model-auth-env-B6Hhnpzd.mjs";import{n as buildPluginCapabilitySummary}from"./capability-summary-D1Y-zikG.mjs";import{t as PLUGIN_ARTIFACT_ADAPTER_IDENTITY}from"./install-artifact-inspection-BgOrqbn9.mjs";import{n as assertCronJobScratchContent}from"./scratch-contract-Bpgs8Aix.mjs";import{c as materializeTemplateToolProfile,d as inspectTemplateBundledPluginDirectory,f as materializeTemplateDependencyDirectory,h as MAX_MANAGED_WORKSPACE_BYTES,l as templateDependencyInventory,m as MAX_MANAGED_FILE_BYTES,p as snapshotTemplateDependencyDirectory,r as templateWorkspaceSourceFailure,s as templateManifestWorkspaceConflictsWithPath,u as inspectTemplateBundledSkill}from"./reader-j_g75PYq.mjs";import{n as resolveWorkspaceSkillInstallDir}from"./install-paths-BKn-LpNW.mjs";import{t as TEMPLATE_BOOTSTRAP_FILE_NAMES}from"./manifest-contract-NrRo60yf.mjs";import{t as evaluateSkillInstallPolicy}from"./install-security-scan-B80uEcmb.mjs";import{r as preparePluginFromPath}from"./install-BIl_Ot-i.mjs";import{t as TEMPLATE_PACKAGE_REF_SCHEMA_VERSION}from"./package-extension-provenance-CimQN9gd.mjs";import{t as inspectPluginCapabilityArtifact}from"./capability-artifact-Cti5hEse.mjs";import{t as installPluginFromClawHub}from"./clawhub-DnaA_iz9.mjs";import{n as setConfiguredMcpServer,o as withMcpLifecycleLease,r as unsetConfiguredMcpServer,s as listConfiguredMcpServers}from"./mcp-config-mutation-QKXJnupf.mjs";import{t as createPluginInstallLogger}from"./plugins-command-helpers-BkCdlVjv.mjs";import{t as installManagedPlugin}from"./management-mutations-BW9zaleO.mjs";import{l as parseRequestedClawHubSkillRef}from"./clawhub-store-xP-XC4fY.mjs";import{r as installExtractedSkillRoot}from"./archive-install-CwgfowU8.mjs";import{n as preflightSkillFromClawHub}from"./clawhub-B8Bo_teO.mjs";import{n as formatInstallPolicyNotice}from"./install-policy-notice-CcFtr2ZC.mjs";import{r as uninstallPluginWithPolicy}from"./management-uninstall-COkRRKZm.mjs";import{t as analyzeLegacyHeartbeatTasks}from"./heartbeat-task-legacy-Ds3dLJd-.mjs";import{i as planHeartbeatTaskMigration}from"./doctor-heartbeat-task-migration.kernel-DRyxd-HY.mjs";import{n as createDefaultProactiveJob}from"./default-proactive-job-CQ6QQtCs.mjs";import path,{relative,resolve}from"node:path";import{lstat,readFile,realpath}from"node:fs/promises";import{assertNoSymlinkParents}from"@openclaw/fs-safe/advanced";import{tempWorkspace}from"@openclaw/fs-safe/temp"; //!src/templates/add-agent-id.ts function templateAgentCopyNumber(e,t){const n=`${normalizeAgentId(e)}-`;if(!t.startsWith(n))return 1;const r=t.slice(n.length);const i=Number(r);return/^[1-9]\d*$/.test(r)&&Number.isSafeInteger(i)&&i>=2?i:1}function selectNextTemplateAgentId(e,t){const n=normalizeAgentId(e);let r=0;for(const e of t){const t=normalizeAgentId(e);if(t===n)r=Math.max(r,1);else{const e=templateAgentCopyNumber(n,t);if(e>1)r=Math.max(r,e)}}if(r===0)return n;const i=`${n}-${r+1}`;if(!Number.isSafeInteger(r+1)||i.length>64)throw new Error(`No portable agent ID remains for ${JSON.stringify(n)}.`);return i} //!src/templates/application-plan.ts function templateAddCapabilityChange(e){return{...e,classification:`escalation`,requiresDistinctConsent:true,digest:digestTemplateValue(e.effect)}}function templateAgentCapabilityChange(e,t){const n={...t.sandbox?{sandbox:t.sandbox}:{},...t.tools?{tools:t.tools}:{},...t.memory?{memory:t.memory}:{},...t.heartbeat?{heartbeat:t.heartbeat}:{}};if(Object.keys(n).length===0)return;return templateAddCapabilityChange({kind:`agent`,id:e,path:`agent`,action:`create`,reason:`The new agent declares sandbox, tool, memory-search, or recurring heartbeat capabilities.`,effect:n})} //!src/plugins/plugin-install-preflight.ts async function resolveInstalledClawHubPlugin(e){const t=await loadInstalledPluginIndexInstallRecords();const n=Object.entries(t).filter(([,t])=>(t.clawhubPackage??parseClawHubPluginSpec(t.spec??``)?.name??parseClawHubPluginSpec(t.resolvedSpec??``)?.name)===e.clawhubPackage);if(n.length===0)return{status:`missing`};if(n.length>1)return{status:`ambiguous`,pluginIds:n.map(([e])=>e).toSorted()};const[r,i]=n[0];return{status:`found`,pluginId:r,record:i,installedVersion:i.resolvedVersion??i.version}}async function preflightPluginInstall(e){const t=await loadInstalledPluginIndexInstallRecords();const n=Object.entries(t).find(([,t])=>(t.clawhubPackage??parseClawHubPluginSpec(t.spec??``)?.name)===e.clawhubPackage);const r=n?.[0];const i=n?.[1];const a=i?.resolvedVersion??i?.version;if(!a||!r)return{ok:true,action:`install`};if(a===e.expectedVersion)return{ok:true,action:`reuse`,installedId:r,...i?.installPath?{installedPath:i.installPath}:{},...i?.integrity?{installedIntegrity:i.integrity}:{},...i?.installedAt?{installedAt:i.installedAt}:{}};return{ok:false,code:`plugin_version_conflict`,...i?.installPath?{installedPath:i.installPath}:{},installedVersion:a}} //!src/templates/package-setup-requirements.ts function resolveTemplatePluginSetupRequirements(e){const t=e.setup?.providers??[];if(t.some(t=>(t.envVars??[]).some(t=>Boolean(e.env[t]?.trim()))||resolveLocalProviderAuthEvidence(t.authEvidence,e.env)))return[];return t.flatMap(t=>{const n=t.envVars??[];const r=t.authEvidence??[];if(n.length===0&&r.length===0)return[];return[{kind:`plugin-setup`,plugin:e.pluginId,provider:t.id,envVars:n,authMethods:t.authMethods??[]}]})} //!src/templates/package-stateless-receipt.ts function createStatelessTemplatePackageReceipt(e,t,n){if(t.source===`bundled`)return createBundledTemplatePackageReceipt(e,t,n);const r=n.nowMs??Date.now();return{schemaVersion:TEMPLATE_PACKAGE_REF_SCHEMA_VERSION,agentId:e.agent.finalId,templateName:e.template.name,kind:t.kind,source:t.source,ref:t.ref,version:t.version,integrity:t.integrity,status:n.status,relationship:n.relationship,origin:n.origin,independentOwner:n.independentOwner,...t.extension?{extension:t.extension}:{},installedAtMs:r,updatedAtMs:r}}function createBundledTemplatePackageReceipt(e,t,n){const r=n.nowMs??Date.now();return{schemaVersion:TEMPLATE_PACKAGE_REF_SCHEMA_VERSION,agentId:e.agent.finalId,templateName:e.template.name,kind:t.kind,source:`bundled`,path:t.path,name:t.name,installId:t.installId,digest:t.snapshot.digest,...t.extension?{extension:t.extension}:{},status:n.status,relationship:n.relationship,origin:n.origin,independentOwner:n.independentOwner,installedAtMs:r,updatedAtMs:r}} //!src/templates/plugin-allowlist-blocker.ts const DISPLAYABLE_PLUGIN_ID=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i;const MAX_DISPLAYABLE_PLUGIN_ID_LENGTH=214;function displayableTemplatePluginId(e){const t=e?.trim();if(!t||t.length>MAX_DISPLAYABLE_PLUGIN_ID_LENGTH||!DISPLAYABLE_PLUGIN_ID.test(t)||validatePluginId(t)!==null)return;return t}function templatePluginAllowlistMessage(e,t){return`Plugin ${e} has plugin id "${t}", which is not in plugins.allow. Add "${t}" to plugins.allow before adding this Template.`}function templatePluginAllowlistReviewMessage(e){return`Plugin "${e}" is not in plugins.allow. Add "${e}" to plugins.allow, then add this Template again.`} //!src/templates/plugin-capability-probe.ts function inspectTemplatePluginCapabilities(e,t,n,r={},i){const{declared:a,manifest:o,manifests:s}=inspectPluginCapabilityArtifact(e,n,{config:r,currentArtifactDir:i});return{declared:a,grants:buildPluginCapabilitySummary({manifest:o??{},origin:`global`,entryConfig:r.plugins?.entries?.[t]}).grants,grantsByPluginId:Object.fromEntries(s.toSorted((e,t)=>e.id<t.id?-1:e.id>t.id?1:0).map(e=>[e.id,buildPluginCapabilitySummary({manifest:e,origin:`global`,entryConfig:r.plugins?.entries?.[e.id]}).grants]))}}function configuredPathSelectsPlugin(e,t,n){const r=resolvePathViaExistingAncestorSync$1(resolveUserPath(e,n));const i=resolvePathViaExistingAncestorSync$1(t);return r===i||r===path.dirname(i)||isPathInside(i,r)}async function sourceHostPluginConflict(e,t,n){const r=n.env??process.env;const i=await preparePluginMetadataMachineStateAsync({env:r});const a=await loadInstalledPluginIndexInstallRecords({env:r});i();const o=loadInstalledPluginIndex({config:n.config,env:r,installRecords:a}).plugins.find(e=>e.pluginId===t);if(o?.origin!==`bundled`||!isBundledPluginInsideDevSourceRoot({rootDir:o.rootDir,env:r}))return;const s=resolvePluginInstallDir(t,resolveDefaultPluginExtensionsDir(r));for(const e of n.config?.plugins?.load?.paths??[]){if(configuredPathSelectsPlugin(e,o.rootDir,r))break;if(configuredPathSelectsPlugin(e,s,r))return}return`Plugin ${e.source===`bundled`?e.path:`${e.ref}@${e.version}`} cannot become active because this source build prioritizes its bundled plugin ${t}. Use a packaged OpenClaw build or a plugin with a distinct ID.`}async function probeTemplatePluginArtifact(e,t,n){const r=n.probePlugin??installPluginFromClawHub;const i=n.inspectPluginCapabilities??inspectTemplatePluginCapabilities;let a;let o;const s={spec:`clawhub:${e.ref}@${e.version}`,dryRun:true,requireClawHubTrust:true,config:n.config,onPluginArtifactInspect:async e=>{try{a=i(e.stagedArtifactDir,e.pluginId,n.env,n.config,n.currentArtifactDir??e.currentArtifactDir)}catch(e){o=e}}};const c=t?await tempWorkspace({rootDir:resolvePreferredOpenClawTmpDir(),prefix:`openclaw-template-plugin-probe-`}):void 0;let l;try{l=await r(c?{...s,extensionsDir:c.dir}:s)}finally{await c?.cleanup().catch(()=>void 0)}if(!l.ok)return l;if(o!==void 0||!a)return{ok:false,error:o?`Plugin ${e.ref}@${e.version} capability inspection failed: ${coerceErrorMessage(o)}`:`Plugin ${e.ref}@${e.version} did not expose staged capability inspection.`};return{...l,declaredCapabilities:a.declared,capabilityGrants:a.grants,capabilityGrantsByPluginId:a.grantsByPluginId}}async function preflightTemplatePluginPackage(e,t={}){const n=await(t.deps?.preflightPlugin??preflightPluginInstall)({clawhubPackage:e.ref,expectedVersion:e.version});const r=await probeTemplatePluginArtifact(e,!(n.ok&&n.action===`install`),{...t.deps,env:t.env,config:t.config,currentArtifactDir:n.installedPath});if(!r.ok)return{ok:false,code:r.code??`plugin_preflight_failed`,message:r.error};if(!r.artifactInspection)return{ok:false,code:`plugin_artifact_inspection_unavailable`,message:`Plugin ${e.ref}@${e.version} did not return canonical artifact inspection.`};if(r.artifactInspection.format===`agent`)return{ok:false,code:`plugin_artifact_format_unsupported`,message:`Plugin ${e.ref}@${e.version} uses unsupported Template extension format agent.`};const i=r.clawhub.integrity?normalizeClawHubSha256Integrity(r.clawhub.integrity):null;if(!i)return{ok:false,code:`plugin_integrity_unavailable`,message:`Plugin ${e.ref}@${e.version} did not resolve an artifact integrity.`};const a=resolveTemplatePluginSetupRequirements({pluginId:r.pluginId,setup:r.setup,env:t.env??process.env});const o={integrity:i,installId:r.pluginId,...a.length>0?{requirements:a}:{},detectedFormat:r.artifactInspection.format,mapped:r.artifactInspection.mapped,unavailable:r.artifactInspection.unavailable,adapterIdentity:PLUGIN_ARTIFACT_ADAPTER_IDENTITY,...r.warning?{warning:r.warning}:{},declaredCapabilities:r.declaredCapabilities,capabilityGrants:r.capabilityGrants,capabilityGrantsByPluginId:r.capabilityGrantsByPluginId};const s=await sourceHostPluginConflict(e,r.pluginId,t);if(s)return{ok:false,code:`plugin_source_host_conflict`,message:s};if(t.config){const i=normalizePluginsConfig(t.config.plugins);const a=i.entries[normalizePluginId(r.pluginId)]?.enabled===false;const o=resolveEffectiveEnableState({id:r.pluginId,origin:`global`,config:i,rootConfig:t.config});if(!o.enabled){const t=o.reason===`not in allowlist`&&(!n.ok||n.action===`install`)?displayableTemplatePluginId(r.pluginId):void 0;if(t)return{ok:false,code:`plugin_disabled`,allowlistPluginId:t,message:templatePluginAllowlistMessage(`${e.ref}@${e.version}`,t)};return{ok:false,code:`plugin_disabled`,message:!n.ok||n.action===`install`?a?`Plugin ${e.ref}@${e.version} was explicitly disabled or uninstalled. Install and enable it in Plugins before adding this Template.`:!i.enabled?`Plugin ${e.ref}@${e.version} cannot be enabled because plugins are disabled. Enable plugins in Plugins before adding this Template.`:`Plugin ${e.ref}@${e.version} is blocked by host policy (${o.reason??`unknown`}). Change its policy in Plugins before adding this Template.`:`Plugin ${e.ref}@${e.version} is installed but disabled (${o.reason??`host policy`}). Enable it in Plugins before continuing.`}}}if(!n.ok)return{ok:false,code:n.code,installedVersion:n.installedVersion,...o,message:`Plugin ${e.ref}@${e.version} conflicts with installed version ${n.installedVersion}.`};if(n.action===`reuse`&&(n.installedId!==r.pluginId||!n.installedIntegrity||normalizeClawHubSha256Integrity(n.installedIntegrity)!==i))return{ok:false,code:`plugin_integrity_conflict`,message:`Plugin ${e.ref}@${e.version} is installed as ${n.installedId} with integrity ${n.installedIntegrity??`unknown`}, expected ${r.pluginId} with ${i}.`};return{ok:true,action:n.action,...o,...n.action===`reuse`&&n.installedIntegrity?{installedIntegrity:n.installedIntegrity}:{},...n.action===`reuse`&&n.installedAt?{installedAt:n.installedAt}:{}}} //!src/templates/bundled-plugin.ts const policySource={kind:`archive`,authority:`third-party`,mutable:false,network:false};const installStamps=/* @__PURE__ */ new WeakMap;function policyWarningDigest(e){return e.length?digestTemplateValue([...new Set(e.map(e=>stableStringify(e)))].toSorted()):void 0}var BundledTemplatePluginInstallError=class extends Error{constructor(e,t,n){super(e,n);this.receipt=t;this.name=`BundledTemplatePluginInstallError`;this.code=n?.code??`package_install_failed`}};async function preflightBundledTemplatePlugin(e){const{dependency:t,config:n,env:r}=e;try{try{var i=_usingCtx();const a=i.a(await materializeTemplateDependencyDirectory({rootDir:e.rootDir,path:t.path,snapshot:e.snapshot}));const o=i.a(await tempWorkspace({rootDir:resolvePreferredOpenClawTmpDir(),prefix:`openclaw-template-plugin-probe-`}));const s=await loadInstalledPluginIndexInstallRecords({env:r});let c;const l=[];const u={path:await a.createArchive(),extensionsDir:o.dir,config:n,installPolicyRequest:{kind:`plugin-archive`,source:policySource},onPluginArtifactInspect:async e=>{c=inspectTemplatePluginCapabilities(e.stagedArtifactDir,e.pluginId,r,n,s[e.pluginId]?.installPath)}};const d=await preparePluginFromPath({...u,onInstallPolicyWarning:async e=>{l.push(e);return{status:`approved`}}});if(!d.ok)return{ok:false,code:d.code??`bundled_plugin_invalid`,message:d.error};if(!c||!d.artifactInspection||d.artifactInspection.format===`agent`)return{ok:false,code:`plugin_artifact_inspection_unavailable`,message:`Plugin ${t.path} has no supported canonical artifact inspection.`};const f=await sourceHostPluginConflict(t,d.pluginId,e);if(f)return{ok:false,code:`plugin_source_host_conflict`,message:f};if(n){const e=normalizePluginsConfig(n.plugins);const r=resolveEffectiveEnableState({id:normalizePluginId(d.pluginId),origin:`global`,config:e,rootConfig:n});if(!r.enabled){const e=r.reason===`not in allowlist`?displayableTemplatePluginId(d.pluginId):void 0;if(e)return{ok:false,code:`plugin_disabled`,allowlistPluginId:e,message:templatePluginAllowlistMessage(t.path,e)};return{ok:false,code:`plugin_disabled`,message:`Plugin ${t.path} is disabled by host policy (${r.reason??`disabled`}). Enable it in Plugins before adding this Template.`}}}const p=s[d.pluginId];const m=p?.installPath??resolvePluginInstallDir(d.pluginId,resolveDefaultPluginExtensionsDir(r));const h=await lstat(m).catch(e=>{if(typeof e===`object`&&e!==null&&`code`in e&&e.code===`ENOENT`)return;throw e});if(p||h){if(!p||!h||(await snapshotTemplateDependencyDirectory({rootDir:m})).digest!==e.snapshot.digest)return{ok:false,code:`bundled_plugin_conflict`,message:`Plugin ${d.pluginId} already exists with different or unmanaged contents.`}}const g=resolveTemplatePluginSetupRequirements({pluginId:d.pluginId,setup:d.setup,env:r??process.env});return{ok:true,action:p?`reuse`:`install`,snapshot:e.snapshot,name:inspectTemplateBundledPluginDirectory(a.directory).name,installId:d.pluginId,detectedFormat:d.artifactInspection.format,mapped:d.artifactInspection.mapped,unavailable:d.artifactInspection.unavailable,adapterIdentity:PLUGIN_ARTIFACT_ADAPTER_IDENTITY,declaredCapabilities:c.declared,capabilityGrants:c.grants,capabilityGrantsByPluginId:c.grantsByPluginId,...g.length?{requirements:g}:{},...l.length?{warning:[...new Set(l.map(e=>formatInstallPolicyNotice({...e,decision:`warn`})))].join(` `),installPolicyWarningDigest:policyWarningDigest(l)}:{}}}catch(e){i.e=e}finally{await i.d()}}catch(e){return{ok:false,code:`bundled_plugin_invalid`,message:coerceErrorMessage(e)}}}async function installBundledTemplatePlugin(e){try{var t=_usingCtx();const{plan:n,dependency:r,options:i}=e;const changed=()=>new BundledTemplatePluginInstallError(`Plugin ${r.path} changed after planning; review the Template again.`,void 0,{code:`package_owner_state_changed`});const a=await preflightBundledTemplatePlugin({dependency:r,rootDir:n.template.packageRoot,snapshot:r.snapshot,config:i.config,env:i.env});if(!a.ok||a.action!==r.ownerAction||a.name!==r.name||a.installId!==r.installId||a.warning!==r.riskWarning||a.installPolicyWarningDigest!==r.installPolicyWarningDigest||!r.extension||stableStringify({detectedFormat:a.detectedFormat,mapped:a.mapped,unavailable:a.unavailable,adapterIdentity:a.adapterIdentity})!==stableStringify({detectedFormat:r.extension.detectedFormat,mapped:r.extension.mapped,unavailable:r.extension.unavailable,adapterIdentity:r.extension.adapterIdentity})||!r.declaredCapabilities||!r.capabilityGrants||!r.capabilityGrantsByPluginId||stableStringify(a.declaredCapabilities)!==stableStringify(r.declaredCapabilities)||stableStringify(a.capabilityGrants)!==stableStringify(r.capabilityGrants)||stableStringify(a.capabilityGrantsByPluginId)!==stableStringify(r.capabilityGrantsByPluginId))throw changed();i.assertCurrent?.();if(a.action===`reuse`)return createStatelessTemplatePackageReceipt(n,r,{nowMs:i.nowMs,status:`complete`,relationship:`referenced`,origin:`pre-existing`,independentOwner:true});const o=i.pluginConsent;if(!o)throw new BundledTemplatePluginInstallError(`Plugin ${r.path} requires an explicit Template capability acknowledgment.`,void 0,{code:`plugin_consent_required`});const s=createStatelessTemplatePackageReceipt(n,r,{nowMs:i.nowMs,status:`pending`,relationship:`referenced`,origin:`template-introduced`,independentOwner:false});const c=await t.a(await materializeTemplateDependencyDirectory({rootDir:n.template.packageRoot,path:r.path,snapshot:r.snapshot})).createArchive();const l=digestTemplateBytes(await readFile(c));const u=resolve(n.template.packageRoot,r.path);const stampInstalled=async()=>{const e=(await loadInstalledPluginIndexInstallRecords({env:i.env}))[r.installId];if(e?.integrity===l&&e.sourcePath===u)installStamps.set(s,digestTemplateValue(e))};const assertCurrent=()=>{i.assertCurrent?.();i.assertForwardCurrent?.()};try{assertCurrent();const e=i.runtime??defaultRuntime;const t=[];const n=await installManagedPlugin({request:{source:`local`,path:c,mode:`install`},localArtifact:{sourcePath:u,integrity:l,policySource},env:i.env,logger:createPluginInstallLogger(e),templateManaged:true,invalidateRuntimeCache:false,deferRuntime:i.runtimeBatch?.install(),beforePersistentApply:assertCurrent,beforePersistentEffect:async()=>{await i.prepareEffect?.();assertCurrent()},safetyOverrides:{onInstallPolicyWarning:async e=>{assertCurrent();if(!r.riskWarning||!await o.confirmInstall?.(r.installId,r.riskWarning))throw changed();t.push(e);return{status:`approved`}}},onCapabilityConsent:async e=>{assertCurrent();if(stableStringify(e.declared)!==stableStringify(r.declaredCapabilities)||stableStringify(e.grants)!==stableStringify(r.capabilityGrants))throw changed();return await o.onCapabilityConsent(e)},onBeforePluginArtifactCommit:async e=>{assertCurrent();if(policyWarningDigest(t)!==r.installPolicyWarningDigest)throw changed();if(e.pluginId!==r.installId||(await snapshotTemplateDependencyDirectory({rootDir:e.stagedArtifactDir})).digest!==r.snapshot.digest)throw changed();const{snapshot:n}=await readConfigFileSnapshotForWrite();const a=inspectTemplatePluginCapabilities(e.stagedArtifactDir,e.pluginId,i.env,n.sourceConfig,e.currentArtifactDir);if(stableStringify(a.grantsByPluginId)!==stableStringify(r.capabilityGrantsByPluginId))throw changed()}});for(const t of n.warnings??[])e.log(t);await stampInstalled();assertCurrent();s.status=`complete`;s.updatedAtMs=i.nowMs??Date.now();return s}catch(e){let t=e;try{await stampInstalled()}catch(n){t=new AggregateError([e,n],coerceErrorMessage(e))}throw new BundledTemplatePluginInstallError(coerceErrorMessage(t),s,{cause:t,code:e instanceof BundledTemplatePluginInstallError?e.code:void 0})}}catch(e){t.e=e}finally{await t.d()}}async function rollbackBundledTemplatePlugins(e,t={}){if(!e.some(e=>e.source===`bundled`&&e.kind===`plugin`&&installStamps.has(e)))return[];return await withPluginLifecycleLeaseAsync(t,async()=>{const n=[];for(const r of e.toReversed()){const e=installStamps.get(r);if(r.source!==`bundled`||r.kind!==`plugin`||!e||r.origin!==`template-introduced`)continue;try{const assertRecord=async()=>{t.assertCurrent?.();const n=(await loadInstalledPluginIndexInstallRecords({env:t.env}))[r.installId];if(!n||digestTemplateValue(n)!==e)throw new Error(`Plugin ownership changed before cleanup.`)};await assertRecord();const n=await uninstallPluginWithPolicy({pluginId:r.installId,env:t.env,caller:`cli`,templateManaged:true,invalidateRuntimeCache:false,beforePersistentApply:t.assertCurrent,beforePersistentEffect:async()=>{await t.prepareEffect?.();t.assertCurrent?.()},onWarning:e=>(t.runtime??defaultRuntime).log(e)});if(!n.ok)throw new Error(n.error);r.status=`rolled_back`}catch(e){n.push(`Plugin ${r.path} cleanup failed: ${coerceErrorMessage(e)}`)}}return n})} //!src/templates/bundled-skill.ts async function preflightBundledTemplateSkill(e){try{try{var t=_usingCtx();const n=e.snapshot??await snapshotTemplateDependencyDirectory({rootDir:e.rootDir,path:e.path});const r=inspectTemplateBundledSkill(e.rootDir,e.path,n);const i=resolveWorkspaceSkillInstallDir(e.workspace,r.installId);const a=await lstat(i).catch(e=>{if(typeof e===`object`&&e!==null&&`code`in e&&e.code===`ENOENT`)return;throw e});if(a){if((await snapshotTemplateDependencyDirectory({rootDir:i})).digest!==n.digest)return{ok:false,code:`bundled_skill_conflict`,message:`Skill ${r.name} already exists with different contents.`}}if(a)return{ok:true,action:`reuse`,...r,snapshot:n};const o=t.a(await materializeTemplateDependencyDirectory({rootDir:e.rootDir,path:e.path,snapshot:n}));const s=await evaluateSkillInstallPolicy({...bundledSkillPolicy(e.path,e.config),logger:{},skillName:r.installId,sourceDir:o.directory,mode:`install`});if(s?.blocked&&!s.blocked.installPolicyWarning)return{ok:false,code:s.blocked.code??`bundled_skill_policy_blocked`,message:s.blocked.reason};return{ok:true,action:`install`,...r,snapshot:n,...s?.blocked?.installPolicyWarning?{warning:s.blocked.reason,installPolicyWarningDigest:digestTemplateValue(s.blocked.installPolicyWarning)}:{}}}catch(e){t.e=e}finally{await t.d()}}catch(e){return{ok:false,code:`bundled_skill_invalid`,message:e instanceof Error?e.message:String(e)}}}async function installBundledTemplateSkill(e){try{var t=_usingCtx();const{dependency:n,options:r}=e;const i=await preflightBundledTemplateSkill({rootDir:e.rootDir,path:n.path,workspace:e.workspace,config:r.config});if(!i.ok||i.snapshot?.digest!==n.snapshot.digest||i.action!==n.ownerAction||i.installId!==n.installId||i.name!==n.name||i.warning!==n.riskWarning||i.installPolicyWarningDigest!==n.installPolicyWarningDigest)throw new Error(`Bundled skill changed after planning; create a fresh Add plan.`);r.assertCurrent?.();if(i.action===`reuse`)return;if(n.riskWarning){if(!r.skillConsent)throw new Error(`Bundled skill requires an explicit trust warning acknowledgement.`);r.skillConsent.assertApproved({source:`bundled`,path:n.path,name:n.name,digest:n.snapshot.digest,riskWarning:n.riskWarning})}const a=t.a(await materializeTemplateDependencyDirectory({rootDir:e.rootDir,path:n.path,snapshot:n.snapshot}));const o=await installExtractedSkillRoot({workspaceDir:e.workspace,slug:n.installId,extractedRoot:a.directory,mode:`install`,beforePersistentApply:()=>{r.assertCurrent?.();r.assertForwardCurrent?.()},beforePersistentEffect:async()=>{await r.prepareEffect?.();r.assertCurrent?.();r.assertForwardCurrent?.()},policy:{...bundledSkillPolicy(n.path,r.config),onInstallPolicyWarning:async e=>{if(!n.riskWarning||digestTemplateValue(e)!==n.installPolicyWarningDigest||!r.skillConsent)return{status:`declined`};r.assertCurrent?.();r.assertForwardCurrent?.();r.skillConsent.assertApproved({source:`bundled`,path:n.path,name:n.name,digest:n.snapshot.digest,riskWarning:n.riskWarning});return{status:`approved`}}}});if(!o.ok)throw new Error(o.error)}catch(e){t.e=e}finally{await t.d()}}function bundledSkillPolicy(e,t){return{config:t,installId:`template-bundled`,origin:{type:`path`,spec:e},source:{kind:`local-path`,authority:`third-party`,mutable:false,network:false},requestedSpecifier:e}} //!src/templates/package-preflight.ts async function preflightTemplatePackage(e,t,n={}){if(e.source===`bundled`){if(!n.packageRoot)return{ok:false,code:`bundled_source_unavailable`,message:`Bundled dependency has no package root.`};return e.kind===`skill`?preflightBundledTemplateSkill({rootDir:n.packageRoot,path:e.path,workspace:t,snapshot:n.snapshot,config:n.config}):n.snapshot?preflightBundledTemplatePlugin({dependency:e,rootDir:n.packageRoot,snapshot:n.snapshot,config:n.config,env:n.env}):{ok:false,code:`bundled_source_unavailable`,message:`Bundled plugin has no reviewed snapshot.`}}if(e.kind===`skill`){const n=await preflightSkillFromClawHub({workspaceDir:t,slug:e.ref,version:e.version});return n.ok?n:{ok:false,code:n.code,message:n.error,...n.integrity?{integrity:n.integrity}:{},...n.warning?{warning:n.warning}:{}}}return await preflightTemplatePluginPackage(e,n)} //!src/templates/bundled-dependency-plan.ts async function planBundledTemplateDependency(e){const{dependency:t,workspace:n,packageRoot:r,snapshot:i}=e;const a=e.packagePreflight?await e.packagePreflight(t,n,{packageRoot:r,snapshot:i}):await preflightTemplatePackage(t,n,{packageRoot:r,snapshot:i,config:e.config});const o=t.kind===`skill`&&a.installId&&(e.referencedSkillTargets.has(a.installId.toLowerCase())||e.skillTargets.has(a.installId.toLowerCase())||a.name&&e.skillNames.has(a.name.normalize(`NFC`).toLowerCase())||templateManifestWorkspaceConflictsWithPath(e.manifest,`skills/${a.installId}`));const s=t.kind===`plugin`&&a.installId?e.pluginTargets.get(a.installId):void 0;const c=t.kind===`plugin`&&(!a.detectedFormat||!a.adapterIdentity||!a.declaredCapabilities||!a.capabilityGrants||!a.capabilityGrantsByPluginId||Object.keys(a.capabilityGrantsByPluginId).length===0);const l=!a.ok||!a.snapshot||!a.name||!a.installId||Boolean(o)||s!==void 0||c;if(t.kind===`skill`){if(a.name)e.skillNames.add(a.name.normalize(`NFC`).toLowerCase());if(a.installId)e.skillTargets.add(a.installId.toLowerCase())}else if(a.installId&&s===void 0)e.pluginTargets.set(a.installId,t.path);const u=l?{level:`error`,phase:`plan`,path:e.declarationPath,code:o?`bundled_skill_collision`:s!==void 0?`bundled_plugin_collision`:a.code??(c?`plugin_capability_provenance_incomplete`:`bundled_dependency_invalid`),message:o?`Bundled skill identity or destination conflicts with another declaration.`:s!==void 0?`Bundled plugins ${s} and ${t.path} both have plugin id ${JSON.stringify(a.installId)}; keep one of them.`:a.message??`Bundled dependency identity is incomplete.`,...!o&&s===void 0&&a.code===`plugin_disabled`&&a.allowlistPluginId?{allowlistPluginId:a.allowlistPluginId}:{}}:void 0;const d={kind:`package`,id:`${t.kind}:bundled:${t.path}`,action:a.action===`reuse`?`reuse`:`install`,target:`bundled:${t.path}`,digest:a.snapshot?.digest,blocked:l,details:{...t,name:a.name,installId:a.installId,snapshot:a.snapshot,ownerAction:a.action??`install`,requirementState:l?`conflicting`:a.action===`reuse`?`satisfied`:`missing-installable`,...a.warning?{riskWarning:a.warning}:{},...a.installPolicyWarningDigest?{installPolicyWarningDigest:a.installPolicyWarningDigest}:{},...a.declaredCapabilities?{declaredCapabilities:a.declaredCapabilities}:{},...a.capabilityGrants?{capabilityGrants:a.capabilityGrants}:{},...a.capabilityGrantsByPluginId?{capabilityGrantsByPluginId:a.capabilityGrantsByPluginId}:{},...a.installId&&a.detectedFormat&&a.adapterIdentity?{extension:{id:a.installId,format:a.detectedFormat,detectedFormat:a.detectedFormat,mapped:a.mapped??[],unavailable:a.unavailable??[],adapterIdentity:a.adapterIdentity}}:{},...a.requirements?{prerequisites:a.requirements}:{}}};return{action:d,diagnostic:u,requirements:a.ok?a.requirements??[]:[],capabilityChange:templateAddCapabilityChange({kind:`package`,id:d.id,path:`${t.kind===`skill`?`skills`:`plugins`}.${t.path}`,action:d.action===`reuse`?`reuse`:`install`,reason:`The Template includes bundled dependency content.`,effect:{...t,name:a.name??t.path,digest:a.snapshot?.digest??`unresolved`}})}} //!src/templates/mcp-records.ts const TEMPLATE_MCP_REF_SCHEMA_VERSION=`openclaw.templateMcpServerRef.v1`; //!src/templates/mcp.ts function mcpServerFromActionDetails(e){const{expectedState:t,prerequisites:n,...r}=e;return`command`in r||`url`in r?r:void 0}function digestTemplateMcpServer(e){return digestTemplateValue(migrateLegacyConfiguredMcpServer(e))}async function installTemplateMcpServersStateless(e,t){const{refs:n}=t;for(const r of e.actions.filter(e=>e.kind===`mcpServer`))await withMcpLifecycleLease(r.id,t,async i=>{const assertCurrent=()=>{i.assertCurrent();t.assertCurrent?.();t.assertForwardCurrent?.()};const a=r.details?mcpServerFromActionDetails(r.details):void 0;if(!a)throw new Error(`MCP server action ${JSON.stringify(r.id)} is invalid.`);const o=await listConfiguredMcpServers();assertCurrent();if(!o.ok)throw new Error(o.error);const s=o.authoredConfig?.mcp?.servers?.[r.id];const c=digestTemplateMcpServer(a);if(s&&digestTemplateMcpServer(s)!==c)throw new Error(`MCP server ${JSON.stringify(r.id)} already exists with different configuration.`);const l=t.nowMs??Date.now();const u={schemaVersion:TEMPLATE_MCP_REF_SCHEMA_VERSION,agentId:e.agent.finalId,name:r.id,configDigest:c,relationship:s?`referenced`:`managed`,origin:s?`pre-existing`:`template-introduced`,independentOwner:true,status:`complete`,createdAtMs:l,updatedAtMs:l};n.push(u);if(!s){const e=await setConfiguredMcpServer({name:r.id,server:migrateLegacyConfiguredMcpServer(a),createOnly:true,skipLifecycleLease:true,assertCurrent,assertCurrentAsync:async()=>{await t.prepareEffect?.();await i.assertOwned();assertCurrent()}});if(!e.ok){n.pop();throw new Error(e.error)}assertCurrent()}})}async function rollbackStatelessTemplateMcpServers(e,t={}){const n=[];for(const r of e.toReversed()){if(r.origin!==`template-introduced`||r.status!==`complete`)continue;try{await withMcpLifecycleLease(r.name,t,async n=>{const assertCurrent=()=>{n.assertCurrent();t.assertCurrent?.()};const i=await listConfiguredMcpServers();assertCurrent();if(!i.ok)throw new Error(i.error);const a=i.authoredConfig?.mcp?.servers?.[r.name];if(!a){e.splice(e.indexOf(r),1);return}if(digestTemplateMcpServer(a)!==r.configDigest)return;const o=await unsetConfiguredMcpServer({name:r.name,expectedServer:i.mcpServers[r.name],skipLifecycleLease:true,assertCurrent,assertCurrentAsync:async()=>{await t.prepareEffect?.();await n.assertOwned();assertCurrent()}});assertCurrent();if(!o.ok){if(o.error.includes(`changed and was not removed`))return;throw new Error(o.error)}e.splice(e.indexOf(r),1)})}catch(e){n.push(`MCP server ${r.name} cleanup failed: ${coerceErrorMessage(e)}`)}}return n} //!src/templates/portable-automation.ts function createInput(e){const{id:t,createdAtMs:n,updatedAtMs:r,state:i,...a}=e;if(a.schedule.kind===`every`)a.schedule={kind:`every`,everyMs:a.schedule.everyMs};return a}function planTemplatePortableAutomation(e){const t=e.actions.findIndex(e=>e.kind===`workspaceFile`&&e.id===`HEARTBEAT.md`);if(e.heartbeat===void 0&&t<0)return;const n=e.heartbeat??{};const r=t<0?void 0:e.actions.splice(t,1)[0];const i=parseDurationMs(n.every??`30m`,{defaultUnit:`m`});const a=createDefaultProactiveJob(e.config,e.agentId,0,i||18e5);a.id=`$portable-heartbeat`;a.enabled=i>0;a.sessionTarget=n.isolatedSession?`isolated`:a.sessionTarget;const o=n.activeHours;a.activeHours=o?.start&&o.end?{start:o.start,end:o.end,...o.timezone?{timezone:o.timezone}:{}}:void 0;if(a.payload.kind===`agentTurn`){a.payload.timeoutSeconds=n.timeoutSeconds??e.config.agents?.defaults?.timeoutSeconds??Math.max(1,Math.min(600,Math.ceil((i||6e5)/1e3)));if(n.lightContext!==void 0)a.payload.lightContext=n.lightContext}let s;const c=[];if(e.content){s=new TextDecoder(`utf-8`,{fatal:true,ignoreBOM:true}).decode(e.content);assertCronJobScratchContent(s);if(analyzeLegacyHeartbeatTasks(s).hasTasksBlock){const t=planHeartbeatTaskMigration({snapshot:{jobs:[a],sortOrderByJobId:/* @__PURE__ */ new Map,nextSortOrder:0},agentId:e.agentId,jobId:a.id,scratch:{content:s,revision:0,updatedAtMs:0},nowMs:0});s=t.strippedContent;for(const[n,{job:i}]of t.jobs.entries()){i.description=`Imported from portable HEARTBEAT.md by Template Add.`;c.push({kind:`cronJob`,id:`$portable-heartbeat-task-${n+1}`,action:`schedule`,target:`automation:${e.agentId}`,automation:createInput(i),blocked:r?.blocked??false})}}}e.actions.push({...r,kind:`cronJob`,id:`$portable-heartbeat`,action:`schedule`,target:`automation:${e.agentId}`,automation:createInput(a),...s!==void 0?{scratch:s}:{},blocked:r?.blocked??false,reason:a.enabled?`Import deprecated heartbeat input as ordinary automations and bounded scratch.`:`Import deprecated heartbeat input as a disabled automation with its retained cadence and bounded scratch.`},...c)} //!src/templates/types.ts const TEMPLATE_ADD_PLAN_SCHEMA_VERSION=`openclaw.templateAddPlan.v1`;const TEMPLATE_INSPECT_RESULT_SCHEMA_VERSION=`openclaw.templateInspect.v1`;const TEMPLATE_OUTPUT_STABILITY=`experimental`; //!src/templates/lifecycle.ts const AGENT_ID_PATTERN=/^[a-z][a-z0-9_-]{0,63}$/;function sourceReferencePath(e,t){return`${e.replace(/\/+$/u,``)}/${t.replaceAll(`\\`,`/`)}`}function canonicalWorkspacePath(e){return resolvePathViaExistingAncestorSync$1(resolve(resolveUserPath(e)))}function blocker(e,t,n){return{level:`error`,code:e,phase:`plan`,path:t,message:n}}async function buildTemplateAddPlan(e){const t=e.context??{};const n=t.agentId??selectNextTemplateAgentId(e.manifest.agent.id,t.existingAgentIds??[]);const r=templateAgentCopyNumber(e.manifest.agent.id,n);const i=e.manifest.agent.name??e.manifest.agent.identity?.name;const a=canonicalWorkspacePath(t.workspace??resolve(resolveStateDir(),`workspace-${n}`));const o=await realpath(e.source.packageRoot).catch(()=>e.source.packageRoot);const s=resolvePathViaExistingAncestorSync$1(resolve(e.source.manifestPath));const c={...e.source,packageRoot:o,manifestPath:s};const l=t.sourceReferenceRoot?{...c,packageRoot:t.sourceReferenceRoot,manifestPath:sourceReferencePath(t.sourceReferenceRoot,relative(o,s))}:c;const planSourcePath=(e,n)=>t.sourceReferenceRoot?sourceReferencePath(t.sourceReferenceRoot,e):n;const u=await root(o);const d=[];const f=[];const p=[];const m=[];if(!AGENT_ID_PATTERN.test(n))d.push(blocker(`invalid_agent_id`,`$.agent.id`,`Final agent id ${JSON.stringify(n)} is not a valid portable agent id.`));const h=new Set(t.existingAgentIds??[]).has(n);const g=e.manifest.agent;const{heartbeat:_,...v}=g;const y=materializeTemplateToolProfile(v);const b=templateOwnedAgentConfig({...v,...y,...r>1&&i?{name:`${i} ${r}`}:{},id:n,workspace:a});if(h)d.push(blocker(`agent_id_collision`,`$.agent.id`,`Agent id ${JSON.stringify(n)} already exists; Templates never merge into existing agents.`));f.push({kind:`agent`,id:n,action:`create`,target:`agents.entries[${JSON.stringify(n)}]`,details:{...b,expectedState:`absent`},blocked:h||!AGENT_ID_PATTERN.test(n)});const x=templateAgentCapabilityChange(n,g);if(x)p.push(x);const S=[...t.existingWorkspacePaths??[]].map(e=>canonicalWorkspacePath(e)).some(e=>isPathInside(e,a)||isPathInside(a,e));const C=await lstat(a).then(()=>true).catch(()=>false);const w=t.admittedWorkspace===void 0?void 0:canonicalWorkspacePath(t.admittedWorkspace);const T=S||C&&w!==a;const E=S?`Workspace ${JSON.stringify(a)} overlaps an existing agent workspace.`:`Workspace ${JSON.stringify(a)} already exists.`;if(T)d.push(blocker(`workspace_collision`,`$.workspace`,`${E} A Template requires a new workspace.`));f.push({kind:`workspace`,id:n,action:`create`,target:a,details:{expectedState:`absent`},blocked:T,...T?{reason:E}:{}});if(e.packageBootstrap)f.push({kind:`bootstrap`,id:`BOOTSTRAP.md`,action:`write`,target:resolve(a,`BOOTSTRAP.md`),source:planSourcePath(e.packageBootstrap.sourcePath,e.packageBootstrap.realPath),digest:e.packageBootstrap.digest,details:{sourcePath:e.packageBootstrap.sourcePath,byteLength:e.packageBootstrap.byteLength,expectedState:`absent-or-native-consumed`,lifecycle:`native-seed-once`},blocked:T,...T?{reason:`Workspace ${JSON.stringify(a)} already exists.`}:{}});const D=[];async function addWorkspaceFileInspection(e){let t;const n=resolve(c.packageRoot,e.sourcePath);const r=resolve(a,e.targetPath);try{await assertNoSymlinkParents({rootDir:c.packageRoot,targetPath:n,allowMissing:false,messagePrefix:`Workspace source`});const i=await u.open(e.sourcePath,{hardlinks:`reject`,symlinks:`reject`});await i[Symbol.asyncDispose]();if(i.stat.size>1048576)throw new FsSafeError(`too-large`,`file exceeds limit of ${MAX_MANAGED_FILE_BYTES} bytes (got ${i.stat.size})`);t={sourcePath:e.sourcePath,manifestPath:e.manifestPath,byteLength:i.stat.size,action:{kind:`workspaceFile`,id:e.id,action:`write`,target:r,source:i.realPath,details:{expectedState:`absent`},blocked:false}}}catch(i){const{code:a,message:o}=templateWorkspaceSourceFailure(i,e.sourcePath,`package`);const s=blocker(a,e.manifestPath,o);t={action:{kind:`workspaceFile`,id:e.id,action:`write`,target:r,source:n,blocked:true,reason:s.message},blocker:s}}const{action:i}=t;if(i.source)i.source=planSourcePath(e.sourcePath,i.source);i.blocked||=T;if(T)i.reason=`Workspace ${JSON.stringify(a)} already exists.`;f.push(i);if(`blocker`in t)d.push(t.blocker);else D.push(t)}if(e.templateMarkdownBody&&e.templateMarkdownBody.toString(`utf8`).trim().length>0){if(templateManifestWorkspaceConflictsWithPath(e.manifest,`SOUL.md`)){const e=blocker(`template_body_soul_conflict`,`$.workspace`,`CLAW.md body content and an explicit SOUL.md workspace declaration cannot both be present.`);d.push(e);f.push({kind:`workspaceFile`,id:`SOUL.md`,action:`write`,target:resolve(a,`SOUL.md`),source:l.manifestPath,sourceKind:`templateMarkdownBody`,blocked:true,reason:e.message})}else{const t={sourcePath:c.manifestPath,manifestPath:`$body`,byteLength:e.templateMarkdownBody.byteLength,content:e.templateMarkdownBody,action:{kind:`workspaceFile`,id:`SOUL.md`,action:`write`,target:resolve(a,`SOUL.md`),source:l.manifestPath,sourceKind:`templateMarkdownBody`,details:{expectedState:`absent`},blocked:false}};D.push(t);f.push(t.action)}}for(const t of TEMPLATE_BOOTSTRAP_FILE_NAMES){const n=e.manifest.workspace.bootstrapFiles[t];if(!n)continue;await addWorkspaceFileInspection({sourcePath:n.source,targetPath:t,id:t,manifestPath:`$.workspace.bootstrapFiles.${t}`})}for(const[t,n]of e.manifest.workspace.files.entries())await addWorkspaceFileInspection({sourcePath:n.source,targetPath:n.path,id:n.path,manifestPath:`$.workspace.files[${t}]`});if(D.reduce((e,t)=>e+t.byteLength,0)>4194304){const e=blocker(`workspace_sources_too_large`,`$.workspace`,`Workspace sources exceed ${MAX_MANAGED_WORKSPACE_BYTES} aggregate bytes.`);d.push(e);for(const t of D){t.action.blocked=true;t.action.reason=e.message}}else for(const e of D){if(e.content){e.action.digest=digestTemplateBytes(e.content);continue}try{await assertNoSymlinkParents({rootDir:c.packageRoot,targetPath:resolve(c.packageRoot,e.sourcePath),allowMissing:false,messagePrefix:`Workspace source`});const t=await u.read(e.sourcePath,{hardlinks:`reject`,maxBytes:MAX_MANAGED_FILE_BYTES,symlinks:`reject`});e.action.source=planSourcePath(e.sourcePath,t.realPath);e.action.digest=digestTemplateBytes(t.buffer);if(e.action.id===`HEARTBEAT.md`)e.content=t.buffer}catch(t){const{code:n,message:r}=templateWorkspaceSourceFailure(t,e.sourcePath,`package`);const i=blocker(n,e.manifestPath,r);e.action.blocked=true;e.action.reason=i.message;d.push(i)}}const O=new Set(templateDependencyInventory(e.manifest).flatMap(e=>e.kind===`skill`&&e.source===`clawhub`?[parseRequestedClawHubSkillRef(e.ref).slug.toLowerCase()]:[]));const k=/* @__PURE__ */ new Set;const A=/* @__PURE__ */ new Set;const j=/* @__PURE__ */ new Map;for(const n of templateDependencyInventory(e.manifest)){const r=n.kind===`skill`?`skills`:`plugins`;const i=`$.${r}[${e.manifest[r].findIndex(e=>n.source===`bundled`?`path`in e&&e.path===n.path:`ref`in e&&e.ref===n.ref)}]`;if(n.source===`bundled`){const r=await planBundledTemplateDependency({dependency:n,manifest:e.manifest,declarationPath:i,packageRoot:o,workspace:a,snapshot:e.bundledSources?.find(e=>e.kind===n.kind&&e.path===n.path)?.snapshot,config:t.config,packagePreflight:t.packagePreflight,skillNames:k,skillTargets:A,referencedSkillTargets:O,pluginTargets:j});f.push(r.action);p.push(r.capabilityChange);if(r.diagnostic)d.push(r.diagnostic);m.push(...r.requirements);continue}const s=t.packagePreflight?await t.packagePreflight(n,a,{packageRoot:o}):{ok:false,code:`package_install_unavailable`,message:`Package preflight is unavailable.`};const c=!s.ok?blocker(s.code??`package_install_unavailable`,i,s.message??`Package preflight failed.`):n.kind===`plugin`&&(!s.integrity||!s.installId||!s.detectedFormat||!s.adapterIdentity||!s.declaredCapabilities||!s.capabilityGrants||!s.capabilityGrantsByPluginId)?blocker(`plugin_capability_provenance_incomplete`,i,`Plugin ${JSON.stringify(n.ref)} did not resolve its declared capability surface.`):void 0;if(c){if(!s.ok&&s.allowlistPluginId)c.allowlistPluginId=s.allowlistPluginId;d.push(c)}if(s.ok&&s.requirements)m.push(...s.requirements);f.push({kind:`package`,id:`${n.kind}:${n.ref}`,action:s.ok&&s.action===`reuse`?`reuse`:`install`,target:`${n.source}:${n.ref}@${n.version}`,digest:s.integrity,details:{...n,...s.integrity?{integrity:s.integrity}:{},...s.installId?{installId:s.installId}:{},...n.kind===`plugin`&&s.installId&&s.detectedFormat&&s.adapterIdentity?{extension:{id:s.installId,format:s.detectedFormat,detectedFormat:s.detectedFormat,mapped:s.mapped??[],unavailable:s.unavailable??[],adapterIdentity:s.adapterIdentity}}:{},...s.declaredCapabilities?{declaredCapabilities:s.declaredCapabilities}:{},...s.capabilityGrants?{capabilityGrants:s.capabilityGrants}:{},...s.capabilityGrantsByPluginId?{capabilityGrantsByPluginId:s.capabilityGrantsByPluginId}:{},...s.warning?{riskWarning:s.warning}:{},...s.requirements?{prerequisites:s.requirements}:{},expectedState:c?`unresolved`:s.action===`reuse`?`present-exact`:`absent`,ownerAction:s.action,requirementState:c?`conflicting`:s.action===`install`?`missing-installable`:s.requirements&&s.requirements.length>0?`setup-required`:`satisfied`},blocked:Boolean(c),...c?{reason:c.message}:{}});p.push(templateAddCapabilityChange({kind:`package`,id:`${n.kind}:${n.ref}`,path:`${n.kind===`skill`?`skills`:`plugins`}.${n.ref}`,action:s.ok&&s.action===`reuse`?`reuse`:`install`,reason:s.ok&&s.action===`reuse`?`The Template requires access to an existing package capability.`:`The Template requires downloadable package content or executable code.`,effect:{kind:n.kind,source:n.source,ref:n.ref,version:n.version,integrity:s.integrity??`unresolved`,...s.installId?{installId:s.installId}:{},...s.declaredCapabilities?{declaredCapabilities:s.declaredCapabilities}:{},...s.capabilityGrants?{capabilityGrants:s.capabilityGrants}:{},...s.capabilityGrantsByPluginId?{capabilityGrantsByPluginId:s.capabilityGrantsByPluginId}:{},...s.warning?{riskWarning:s.warning}:{}}}))}const M=new Set(t.existingMcpServerNames??[]);for(const[n,r]of Object.entries(e.manifest.mcpServers)){const e=t.existingMcpServers?.[n];const i=e!==void 0&&digestTemplateMcpServer(e)===digestTemplateMcpServer(r);const a=!i&&(M.has(n)||e!==void 0);if(a)d.push(blocker(`mcp_server_collision`,`$.mcpServers.${n}`,`MCP server ${JSON.stringify(n)} already exists with different or unresolved configuration and will not be overwritten.`));if(`env`in r)for(const e of Object.values(r.env??{}))m.push({kind:`environment`,mcpServer:n,name:e.slice(2,-1)});if(`auth`in r&&r.auth===`oauth`)m.push({kind:`oauth`,mcpServer:n});f.push({kind:`mcpServer`,id:n,action:`configure`,target:`mcp.servers.${n}`,details:{...r,expectedState:i?`present-exact`:`absent`,prerequisites:m.filter(e=>e.kind!==`plugin-setup`&&e.mcpServer===n)},blocked:a});p.push(templateAddCapabilityChange({kind:`mcpServer`,id:n,path:`mcpServers.${n}`,action:`configure`,reason:`The Template declares an MCP execution or network tool surface.`,effect:{...r,...`env`in r&&r.env?{env:Object.keys(r.env).toSorted()}:{}}}))}planTemplatePortableAutomation({actions:f,heartbeat:g.heartbeat,content:D.find(e=>e.action.id===`HEARTBEAT.md`)?.content,config:t.config??{},agentId:n});for(const{delivery:t,...r}of e.manifest.automations){f.push({kind:`cronJob`,id:r.id,action:`schedule`,target:`cron:${r.id}:agent=${n}`,details:{...r,agentId:n,expectedState:`absent`},blocked:false});p.push(templateAddCapabilityChange({kind:`cronJob`,id:r.id,path:`automations.${r.id}`,action:`schedule`,reason:`The Template declares recurring scheduled work.`,effect:{...r,agentId:n}}))}p.sort((e,t)=>`${e.kind}:${e.id}:${e.path}`.localeCompare(`${t.kind}:${t.id}:${t.path}`));const N=digestTemplateValue({manifestSchemaVersion:e.manifest.schemaVersion,templateIntegrity:c.integrity,finalId:n,workspace:a,actions:f,capabilityChanges:p,blockers:d});return{schemaVersion:TEMPLATE_ADD_PLAN_SCHEMA_VERSION,manifestSchemaVersion:e.manifest.schemaVersion,stability:TEMPLATE_OUTPUT_STABILITY,dryRun:true,mutationAllowed:false,planIntegrity:N,template:l,agent:{requestedId:e.manifest.agent.id,finalId:n,workspace:a,config:b},summary:{totalActions:f.length,agentActions:f.filter(e=>e.kind===`agent`).length,workspaceActions:f.filter(e=>e.kind===`workspace`||e.kind===`bootstrap`||e.kind===`workspaceFile`).length,packageActions:f.filter(e=>e.kind===`package`).length,mcpServerActions:f.filter(e=>e.kind===`mcpServer`).length,cronJobActions:f.filter(e=>e.kind===`cronJob`).length,blockedActions:f.filter(e=>e.blocked).length,capabilityEscalations:p.length},actions:f,capabilityChanges:p,readiness:{ready:m.length===0,requirements:m},blockers:d,diagnostics:e.diagnostics??[]}}export{createBundledTemplatePackageReceipt as _,digestTemplateMcpServer as a,resolveInstalledClawHubPlugin as b,preflightTemplatePackage as c,installBundledTemplatePlugin as d,rollbackBundledTemplatePlugins as f,templatePluginAllowlistReviewMessage as g,sourceHostPluginConflict as h,TEMPLATE_OUTPUT_STABILITY as i,installBundledTemplateSkill as l,probeTemplatePluginArtifact as m,TEMPLATE_ADD_PLAN_SCHEMA_VERSION as n,installTemplateMcpServersStateless as o,inspectTemplatePluginCapabilities as p,TEMPLATE_INSPECT_RESULT_SCHEMA_VERSION as r,rollbackStatelessTemplateMcpServers as s,buildTemplateAddPlan as t,BundledTemplatePluginInstallError as u,createStatelessTemplatePackageReceipt as v,selectNextTemplateAgentId as x,preflightPluginInstall as y};