openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
850 lines (849 loc) • 30.5 kB
JavaScript
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs";
import { n as coerceErrorMessage } from "./error-coercion-hDrHOSGy.mjs";
import "./src-H3RMXyFL.mjs";
import { r as resolvePathViaExistingAncestorSync$1 } from "./boundary-path-C2gXEiXe.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs";
import "./utils-C8YECn2Q.mjs";
import "./paths-DAcAg5aV.mjs";
import { t as FsSafeError, w as root } from "./fs-safe-BbWvmdVn.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import "./kysely-sync-YJo2lmGV.mjs";
import "./openclaw-state-db-schema-helpers-nImZNMq_.mjs";
import "./sqlite-number-D8n3srri.mjs";
import { t as parseDurationMs } from "./parse-duration-D6UJm52I.mjs";
import { n as digestTemplateValue, t as digestTemplateBytes } from "./digest-DN38l3Q9.mjs";
import { r as templateOwnedAgentConfig } from "./agent-config-ownership-UJZNVNDG.mjs";
import { t as canonicalizeConfiguredMcpServer } from "./mcp-config-normalize-DxJwGDsa.mjs";
import { n as assertCronJobScratchContent } from "./scratch-contract-COS3OFt4.mjs";
import { a as MAX_MANAGED_WORKSPACE_BYTES, d as materializeTemplateToolProfile, i as MAX_MANAGED_FILE_BYTES, r as templateWorkspaceSourceFailure, u as templateManifestWorkspaceConflictsWithPath } from "./reader-L_dBhbIJ.mjs";
import { t as TEMPLATE_BOOTSTRAP_FILE_NAMES } from "./manifest-contract-lY73bdoM.mjs";
import { a as withMcpLifecycleLease, n as unsetConfiguredMcpServer, o as listConfiguredMcpServers, t as setConfiguredMcpServer } from "./mcp-config-mutation-IMdOtmrs.mjs";
import { t as analyzeLegacyHeartbeatTasks } from "./heartbeat-task-legacy-B_GDgmyR.mjs";
import { i as planHeartbeatTaskMigration } from "./doctor-heartbeat-task-migration.kernel-CjVQSulO.mjs";
import { n as createDefaultProactiveJob } from "./default-proactive-job-BlkkHKu0.mjs";
import { relative, resolve } from "node:path";
import { lstat, realpath } from "node:fs/promises";
import { assertNoSymlinkParents } from "@openclaw/fs-safe/advanced";
//#region 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;
}
//#endregion
//#region 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
});
}
function blocker$1(e, t, n) {
return {
level: "error",
code: e,
phase: "plan",
path: t,
message: n
};
}
function findTemplateExtensionPackageCollisions(e) {
const t = new Set(e.packages.map((e) => `${e.kind}:${e.ref}`));
const n = [];
for (const [r, i] of e.extensions.entries()) {
const e = `plugin:${i.ref}`;
if (t.has(e)) {
n.push({
index: r,
diagnostic: blocker$1("extension_package_collision", `$.profiles.openclaw.extensions[${r}]`, `Extension package ${JSON.stringify(e)} is already declared by the portable manifest or another profile extension.`)
});
continue;
}
t.add(e);
}
return n;
}
async function planTemplateExtensions(e) {
const t = [];
const n = [];
const r = [];
const i = [];
const a = [];
for (const [o, s] of e.extensions.entries()) {
const c = e.packagePreflight ? await e.packagePreflight({
kind: "plugin",
source: s.source,
ref: s.ref,
version: s.version
}, e.workspace) : {
ok: false,
code: "package_install_unavailable",
message: "Extension preflight is unavailable."
};
const l = c.ok && Boolean(c.integrity && c.installId && c.action && c.detectedFormat && c.adapterIdentity && c.declaredCapabilities && c.capabilityGrants && c.capabilityGrantsByPluginId);
const u = c.ok && !l ? blocker$1("extension_provenance_incomplete", `$.profiles.openclaw.extensions[${o}]`, `Extension ${JSON.stringify(s.id)} did not resolve complete identity and adapter provenance.`) : void 0;
const d = c.ok && l && c.detectedFormat !== s.format ? blocker$1("extension_format_mismatch", `$.profiles.openclaw.extensions[${o}].format`, `Extension ${JSON.stringify(s.id)} declares format ${JSON.stringify(s.format)}, but the plugin detector found ${JSON.stringify(c.detectedFormat ?? "unknown")}.`) : void 0;
const f = !c.ok ? blocker$1(c.code ?? "extension_preflight_failed", `$.profiles.openclaw.extensions[${o}]`, c.message ?? "Extension preflight failed.") : u ?? d;
if (f) a.push(f);
if (c.ok && c.requirements) i.push(...c.requirements);
const p = f ? "conflicting" : c.action === "install" ? "missing-installable" : c.requirements && c.requirements.length > 0 ? "setup-required" : "satisfied";
const m = {
...s,
...c.detectedFormat ? { detectedFormat: c.detectedFormat } : {},
...c.integrity ? { integrity: c.integrity } : {},
...c.installId ? { installId: c.installId } : {},
...c.action ? { ownerAction: c.action } : {},
...c.declaredCapabilities ? { declaredCapabilities: c.declaredCapabilities } : {},
...c.capabilityGrants ? { capabilityGrants: c.capabilityGrants } : {},
...c.capabilityGrantsByPluginId ? { capabilityGrantsByPluginId: c.capabilityGrantsByPluginId } : {},
requirementState: p,
mapped: c.mapped ?? [],
unavailable: c.unavailable ?? [],
...c.adapterIdentity ? { adapterIdentity: c.adapterIdentity } : {},
blocked: Boolean(f)
};
t.push(m);
n.push({
kind: "package",
id: `plugin:${s.ref}`,
action: c.ok && c.action === "reuse" ? "reuse" : "install",
target: `${s.source}:${s.ref}@${s.version}`,
...c.integrity ? { digest: c.integrity } : {},
details: {
kind: "plugin",
source: s.source,
ref: s.ref,
version: s.version,
...c.integrity ? { integrity: c.integrity } : {},
...c.installId ? { installId: c.installId } : {},
...c.action ? { ownerAction: c.action } : {},
...c.declaredCapabilities ? { declaredCapabilities: c.declaredCapabilities } : {},
...c.capabilityGrants ? { capabilityGrants: c.capabilityGrants } : {},
...c.capabilityGrantsByPluginId ? { capabilityGrantsByPluginId: c.capabilityGrantsByPluginId } : {},
requirementState: p,
...c.requirements ? { prerequisites: c.requirements } : {},
...l ? { extension: {
id: s.id,
format: s.format,
detectedFormat: c.detectedFormat,
mapped: c.mapped ?? [],
unavailable: c.unavailable ?? [],
adapterIdentity: c.adapterIdentity
} } : {},
expectedState: !c.ok ? "unresolved" : c.action === "reuse" ? "present-exact" : "absent",
...c.warning ? { riskWarning: c.warning } : {}
},
blocked: m.blocked,
...f ? { reason: f.message } : {}
});
const h = {
id: s.id,
source: s.source,
ref: s.ref,
version: s.version,
expectedFormat: s.format,
detectedFormat: c.detectedFormat ?? "unresolved",
integrity: c.integrity ?? "unresolved",
mapped: c.mapped ?? [],
unavailable: c.unavailable ?? [],
adapterIdentity: c.adapterIdentity ?? "unresolved",
declaredCapabilities: c.declaredCapabilities ?? {},
capabilityGrants: c.capabilityGrants ?? {},
capabilityGrantsByPluginId: c.capabilityGrantsByPluginId ?? {},
...c.installId ? { installId: c.installId } : {},
...c.warning ? { riskWarning: c.warning } : {}
};
const g = {
kind: "package",
id: `extension:${s.id}`,
path: `openclaw.extensions.${s.id}`,
action: c.action === "reuse" ? "reuse" : "install",
reason: c.action === "reuse" ? "The OpenClaw profile requires access to an existing native extension." : "The OpenClaw profile requires installation of native extension content or executable code.",
effect: h
};
r.push(templateAddCapabilityChange(g));
}
return {
extensions: t,
actions: n,
capabilityChanges: r,
requirements: i,
blockers: a
};
}
//#endregion
//#region src/templates/mcp-records.ts
const TEMPLATE_MCP_REF_SCHEMA_VERSION = "openclaw.templateMcpServerRef.v1";
//#endregion
//#region 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 normalizeTemplateMcpServer(e) {
const t = canonicalizeConfiguredMcpServer(e);
for (const [e, n] of [["timeout", "requestTimeoutMs"], ["connectTimeout", "connectionTimeoutMs"]]) {
const r = t[e];
if (t[n] === void 0 && typeof r === "number" && r > 0 && Number.isFinite(r * 1e3)) t[n] = r * 1e3;
delete t[e];
}
return t;
}
function digestTemplateMcpServer(e) {
return digestTemplateValue(normalizeTemplateMcpServer(e));
}
/**
* Add a shared MCP requirement without creating a Template ownership record.
* Each ref is recorded in the caller's `refs` before its write, because a write
* that throws may still have committed. Rollback re-reads the config and drops
* refs with no matching entry.
*/
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: normalizeTemplateMcpServer(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();
}
});
}
/** Remove unchanged MCP entries introduced before a failed Add published its agent. */
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;
}
//#endregion
//#region 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;
}
/** Deprecated package input becomes ordinary jobs before consent and installation. */
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);
}
//#endregion
//#region 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";
//#endregion
//#region 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 ? t.agentId : selectNextTemplateAgentId(e.manifest.agent.id, t.existingAgentIds ?? []);
const r = templateAgentCopyNumber(e.manifest.agent.id, n);
const i = canonicalWorkspacePath(t.workspace ?? resolve(resolveStateDir(), `workspace-${n}`));
const a = await realpath(e.source.packageRoot).catch(() => e.source.packageRoot);
const o = resolvePathViaExistingAncestorSync$1(resolve(e.source.manifestPath));
const s = {
...e.source,
packageRoot: a,
manifestPath: o
};
const c = t.sourceReferenceRoot ? {
...s,
packageRoot: t.sourceReferenceRoot,
manifestPath: sourceReferencePath(t.sourceReferenceRoot, relative(a, o))
} : s;
const planSourcePath = (e, n) => t.sourceReferenceRoot ? sourceReferencePath(t.sourceReferenceRoot, e) : n;
const l = await root(a);
const u = [];
const d = [];
const f = [];
const p = [];
if (!AGENT_ID_PATTERN.test(n)) u.push(blocker("invalid_agent_id", "$.agent.id", `Final agent id ${JSON.stringify(n)} is not a valid portable agent id.`));
const m = new Set(t.existingAgentIds ?? []).has(n);
const h = e.openClawProfile?.agent ?? {};
const { heartbeat: g, ..._ } = h;
const v = materializeTemplateToolProfile(_);
const y = templateOwnedAgentConfig({
...e.manifest.agent,
...v,
...r > 1 ? { name: `${e.manifest.agent.name} ${r}` } : {},
id: n,
workspace: i
});
if (m) u.push(blocker("agent_id_collision", "$.agent.id", `Agent id ${JSON.stringify(n)} already exists; Templates never merge into existing agents.`));
d.push({
kind: "agent",
id: n,
action: "create",
target: `agents.entries[${JSON.stringify(n)}]`,
details: {
...y,
expectedState: "absent"
},
blocked: m || !AGENT_ID_PATTERN.test(n)
});
const b = templateAgentCapabilityChange(n, h);
if (b) f.push(b);
const x = [...t.existingWorkspacePaths ?? []].map((e) => canonicalWorkspacePath(e)).some((e) => isPathInside(e, i) || isPathInside(i, e));
const S = await lstat(i).then(() => true).catch(() => false);
const C = x || S;
const w = x ? `Workspace ${JSON.stringify(i)} overlaps an existing agent workspace.` : `Workspace ${JSON.stringify(i)} already exists.`;
if (C) u.push(blocker("workspace_collision", "$.workspace", `${w} A Template requires a new workspace.`));
d.push({
kind: "workspace",
id: n,
action: "create",
target: i,
details: { expectedState: "absent" },
blocked: C,
...C ? { reason: w } : {}
});
if (e.packageBootstrap) d.push({
kind: "bootstrap",
id: "BOOTSTRAP.md",
action: "write",
target: resolve(i, "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: C,
...C ? { reason: `Workspace ${JSON.stringify(i)} already exists.` } : {}
});
const T = [];
async function addWorkspaceFileInspection(e) {
let t;
const n = resolve(s.packageRoot, e.sourcePath);
const r = resolve(i, e.targetPath);
try {
await assertNoSymlinkParents({
rootDir: s.packageRoot,
targetPath: n,
allowMissing: false,
messagePrefix: "Workspace source"
});
const i = await l.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: a } = t;
if (a.source) a.source = planSourcePath(e.sourcePath, a.source);
a.blocked ||= C;
if (C) a.reason = `Workspace ${JSON.stringify(i)} already exists.`;
d.push(a);
if ("blocker" in t) u.push(t.blocker);
else T.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.");
u.push(e);
d.push({
kind: "workspaceFile",
id: "SOUL.md",
action: "write",
target: resolve(i, "SOUL.md"),
source: c.manifestPath,
sourceKind: "templateMarkdownBody",
blocked: true,
reason: e.message
});
} else {
const t = {
sourcePath: s.manifestPath,
manifestPath: "$body",
byteLength: e.templateMarkdownBody.byteLength,
content: e.templateMarkdownBody,
action: {
kind: "workspaceFile",
id: "SOUL.md",
action: "write",
target: resolve(i, "SOUL.md"),
source: c.manifestPath,
sourceKind: "templateMarkdownBody",
details: { expectedState: "absent" },
blocked: false
}
};
T.push(t);
d.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 (T.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.`);
u.push(e);
for (const t of T) {
t.action.blocked = true;
t.action.reason = e.message;
}
} else for (const e of T) {
if (e.content) {
e.action.digest = digestTemplateBytes(e.content);
continue;
}
try {
await assertNoSymlinkParents({
rootDir: s.packageRoot,
targetPath: resolve(s.packageRoot, e.sourcePath),
allowMissing: false,
messagePrefix: "Workspace source"
});
const t = await l.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;
u.push(i);
}
}
for (const [n, r] of e.manifest.packages.entries()) {
const e = t.packagePreflight ? await t.packagePreflight(r, i) : {
ok: false,
code: "package_install_unavailable",
message: "Package preflight is unavailable."
};
const a = !e.ok ? blocker(e.code ?? "package_install_unavailable", `$.packages[${n}]`, e.message ?? "Package preflight failed.") : r.kind === "plugin" && (!e.declaredCapabilities || !e.capabilityGrants || !e.capabilityGrantsByPluginId) ? blocker("plugin_capability_provenance_incomplete", `$.packages[${n}]`, `Plugin ${JSON.stringify(r.ref)} did not resolve its declared capability surface.`) : void 0;
if (a) u.push(a);
if (e.ok && e.requirements) p.push(...e.requirements);
d.push({
kind: "package",
id: `${r.kind}:${r.ref}`,
action: e.ok && e.action === "reuse" ? "reuse" : "install",
target: `${r.source}:${r.ref}@${r.version}`,
digest: e.integrity,
details: {
...r,
...e.integrity ? { integrity: e.integrity } : {},
...e.installId ? { installId: e.installId } : {},
...e.declaredCapabilities ? { declaredCapabilities: e.declaredCapabilities } : {},
...e.capabilityGrants ? { capabilityGrants: e.capabilityGrants } : {},
...e.capabilityGrantsByPluginId ? { capabilityGrantsByPluginId: e.capabilityGrantsByPluginId } : {},
...e.warning ? { riskWarning: e.warning } : {},
...e.requirements ? { prerequisites: e.requirements } : {},
expectedState: a ? "unresolved" : e.action === "reuse" ? "present-exact" : "absent",
ownerAction: e.action,
requirementState: a ? "conflicting" : e.action === "install" ? "missing-installable" : e.requirements && e.requirements.length > 0 ? "setup-required" : "satisfied"
},
blocked: Boolean(a),
...a ? { reason: a.message } : {}
});
f.push(templateAddCapabilityChange({
kind: "package",
id: `${r.kind}:${r.ref}`,
path: `packages.${r.kind}.${r.ref}`,
action: e.ok && e.action === "reuse" ? "reuse" : "install",
reason: e.ok && e.action === "reuse" ? "The Template requires access to an existing package capability." : "The Template requires downloadable package content or executable code.",
effect: {
kind: r.kind,
source: r.source,
ref: r.ref,
version: r.version,
integrity: e.integrity ?? "unresolved",
...e.installId ? { installId: e.installId } : {},
...e.declaredCapabilities ? { declaredCapabilities: e.declaredCapabilities } : {},
...e.capabilityGrants ? { capabilityGrants: e.capabilityGrants } : {},
...e.capabilityGrantsByPluginId ? { capabilityGrantsByPluginId: e.capabilityGrantsByPluginId } : {},
...e.warning ? { riskWarning: e.warning } : {}
}
}));
}
const E = await planTemplateExtensions({
extensions: e.openClawProfile?.extensions ?? [],
workspace: i,
packagePreflight: t.packagePreflight
});
const D = E.extensions;
const O = findTemplateExtensionPackageCollisions({
packages: e.manifest.packages,
extensions: e.openClawProfile?.extensions ?? []
});
const k = new Set(O.map(({ index: e }) => e));
u.push(...O.map(({ diagnostic: e }) => e));
for (const [e, t] of E.actions.entries()) {
if (k.has(e)) continue;
d.push(t);
}
f.push(...E.capabilityChanges);
p.push(...E.requirements);
u.push(...E.blockers);
const A = 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 && (A.has(n) || e !== void 0);
if (a) u.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 ?? {})) p.push({
kind: "environment",
mcpServer: n,
name: e.slice(2, -1)
});
if ("auth" in r && r.auth === "oauth") p.push({
kind: "oauth",
mcpServer: n
});
d.push({
kind: "mcpServer",
id: n,
action: "configure",
target: `mcp.servers.${n}`,
details: {
...r,
expectedState: i ? "present-exact" : "absent",
prerequisites: p.filter((e) => e.kind !== "plugin-setup" && e.mcpServer === n)
},
blocked: a
});
f.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: d,
heartbeat: h.heartbeat,
content: T.find((e) => e.action.id === "HEARTBEAT.md")?.content,
config: t.config ?? {},
agentId: n
});
for (const t of e.manifest.cronJobs) {
d.push({
kind: "cronJob",
id: t.id,
action: "schedule",
target: `cron:${t.id}:agent=${n}`,
details: {
...t,
agentId: n,
expectedState: "absent",
...t.delivery?.channel === "last" ? { deliveryResolution: "local-channel-state:last" } : {}
},
blocked: false
});
f.push(templateAddCapabilityChange({
kind: "cronJob",
id: t.id,
path: `cronJobs.${t.id}`,
action: "schedule",
reason: "The Template declares recurring scheduled work.",
effect: {
...t,
agentId: n
}
}));
}
f.sort((e, t) => `${e.kind}:${e.id}:${e.path}`.localeCompare(`${t.kind}:${t.id}:${t.path}`));
const j = digestTemplateValue({
manifestSchemaVersion: e.manifest.schemaVersion,
templateIntegrity: s.integrity,
finalId: n,
workspace: i,
actions: d,
capabilityChanges: f,
blockers: u,
extensions: D
});
return {
schemaVersion: TEMPLATE_ADD_PLAN_SCHEMA_VERSION,
manifestSchemaVersion: e.manifest.schemaVersion,
stability: TEMPLATE_OUTPUT_STABILITY,
dryRun: true,
mutationAllowed: false,
planIntegrity: j,
template: c,
agent: {
requestedId: e.manifest.agent.id,
finalId: n,
workspace: i,
config: y
},
summary: {
totalActions: d.length,
agentActions: d.filter((e) => e.kind === "agent").length,
workspaceActions: d.filter((e) => e.kind === "workspace" || e.kind === "bootstrap" || e.kind === "workspaceFile").length,
packageActions: d.filter((e) => e.kind === "package").length,
mcpServerActions: d.filter((e) => e.kind === "mcpServer").length,
cronJobActions: d.filter((e) => e.kind === "cronJob").length,
blockedActions: d.filter((e) => e.blocked).length,
capabilityEscalations: f.length
},
actions: d,
capabilityChanges: f,
readiness: {
ready: p.length === 0,
requirements: p
},
extensions: D,
blockers: u,
diagnostics: e.diagnostics ?? []
};
}
//#endregion
export { digestTemplateMcpServer as a, findTemplateExtensionPackageCollisions as c, TEMPLATE_OUTPUT_STABILITY as i, planTemplateExtensions as l, TEMPLATE_ADD_PLAN_SCHEMA_VERSION as n, installTemplateMcpServersStateless as o, TEMPLATE_INSPECT_RESULT_SCHEMA_VERSION as r, rollbackStatelessTemplateMcpServers as s, buildTemplateAddPlan as t, selectNextTemplateAgentId as u };