Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions agents/openclaw/manifest.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ messaging_platforms:
- slack
- wechat
- whatsapp
- mattermost

# ── Inference ───────────────────────────────────────────────────
inference:
Expand Down
2 changes: 1 addition & 1 deletion ci/test-file-size-budget.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"nemoclaw/src/commands/migration-state.test.ts": 1566,
"src/lib/inference/nim.test.ts": 2068,
"src/lib/onboard/preflight.test.ts": 1905,
"test/channels-add-preset.test.ts": 1871,
"test/channels-add-preset.test.ts": 1838,
"test/generate-openclaw-config.test.ts": 1984,
"test/install-preflight.test.ts": 4207,
"test/nemoclaw-start.test.ts": 5160,
Expand Down
37 changes: 37 additions & 0 deletions nemoclaw-blueprint/policies/templates/mattermost.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

preset:
name: mattermost
description: "Mattermost self-hosted API and WebSocket access"
template:
sourceType: http-url

network_policies:
mattermost:
name: mattermost
endpoints:
# Mattermost serves REST and WebSocket traffic from the same self-hosted
# host:port. Keep them on one inspected endpoint so policy matching does
# not collapse duplicate endpoint keys while credential rewrite still
# resolves the bot-token placeholder before egress.
- host: "{{url.host}}"
port: "{{url.port}}"
protocol: rest
enforcement: enforce
request_body_credential_rewrite: true
websocket_credential_rewrite: true
allowed_ips:
- 10.0.0.0/8
- 172.16.0.0/12
- 192.168.0.0/16
rules:
- allow: { method: GET, path: "{{url.basePath}}/api/v4/websocket" }
- allow: { method: WEBSOCKET_TEXT, path: "{{url.basePath}}/api/v4/websocket" }
- allow: { method: GET, path: "{{url.basePath}}/api/v4/**" }
- allow: { method: POST, path: "{{url.basePath}}/api/v4/**" }
- allow: { method: PUT, path: "{{url.basePath}}/api/v4/**" }
- allow: { method: PATCH, path: "{{url.basePath}}/api/v4/**" }
- allow: { method: DELETE, path: "{{url.basePath}}/api/v4/**" }
binaries:
- path: "{{agent.binaries}}"
60 changes: 43 additions & 17 deletions src/lib/actions/sandbox/policy-channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const onboardProviders = require("../../onboard/providers");

import { filterSetupPolicyPresetsForAgent } from "../../onboard/agent-policy-presets";
import { getStoredMessagingChannelConfig } from "../../onboard/messaging-config";
import { applyGeneratedMessagingPolicyTemplates } from "../../onboard/messaging-policy-templates";
import * as policies from "../../policy";

const onboardSession =
Expand Down Expand Up @@ -908,19 +909,21 @@ export async function addSandboxChannel(
process.exit(1);
}

const presetContent = policies.loadPreset(canonical);
const presetPolicyKeys =
presetContent === null ? [] : policies.parsePresetPolicyKeys(presetContent);
if (presetContent === null || presetPolicyKeys.length === 0) {
if (presetContent !== null && presetPolicyKeys.length === 0) {
for (const presetName of manifestPolicyPresetNames(manifest)) {
const presetContent = policies.loadPreset(presetName);
const presetPolicyKeys =
presetContent === null ? [] : policies.parsePresetPolicyKeys(presetContent);
if (presetContent === null || presetPolicyKeys.length === 0) {
if (presetContent !== null && presetPolicyKeys.length === 0) {
console.error(
` Preset YAML for channel '${canonical}' has no parseable entries under 'network_policies:'.`,
);
}
console.error(
` Preset YAML for channel '${canonical}' has no parseable entries under 'network_policies:'.`,
` Restore the preset YAML and re-run: ${CLI_NAME} ${sandboxName} channels add ${canonical}`,
);
process.exit(1);
}
console.error(
` Restore the preset YAML and re-run: ${CLI_NAME} ${sandboxName} channels add ${canonical}`,
);
process.exit(1);
}

if (dryRun) {
Expand All @@ -944,7 +947,7 @@ export async function addSandboxChannel(
// host-side credential to acquire; register the bridge now and let the
// operator complete pairing after rebuild.
if (manifest.auth.mode === "in-sandbox-qr") {
if (!applyChannelPresetIfAvailable(sandboxName, canonical)) {
if (!applyChannelPolicyIfAvailable(sandboxName, canonical, plan)) {
process.exit(1);
}
await applyChannelAddToGatewayAndRegistry(sandboxName, canonical, {});
Expand Down Expand Up @@ -993,7 +996,7 @@ export async function addSandboxChannel(
await applyChannelAddToGatewayAndRegistry(sandboxName, canonical, acquired);
console.log(` ${G}✓${R} Registered ${canonical} bridge with the OpenShell gateway.`);

if (!applyChannelPresetIfAvailable(sandboxName, canonical)) {
if (!applyChannelPolicyIfAvailable(sandboxName, canonical, plan)) {
await rollbackChannelAdd(sandboxName, channelDef, canonical, {
wasAlreadyEnabled,
priorCreds,
Expand Down Expand Up @@ -1073,6 +1076,12 @@ async function rollbackChannelAdd(
return result;
}

function manifestPolicyPresetNames(manifest: ChannelManifest): string[] {
return (manifest.policyPresets ?? []).map((preset) =>
typeof preset === "string" ? preset : preset.name,
);
}

export function applyChannelPresetIfAvailable(sandboxName: string, channelName: string): boolean {
try {
const applied = policies.applyPreset(sandboxName, channelName);
Expand All @@ -1098,6 +1107,28 @@ export function applyChannelPresetIfAvailable(sandboxName: string, channelName:
}
}

export function applyChannelPolicyIfAvailable(
sandboxName: string,
channelName: string,
plan: SandboxMessagingPlan,
): boolean {
try {
const appliedGenerated = applyGeneratedMessagingPolicyTemplates(sandboxName, plan, {
channelId: channelName,
});
if (appliedGenerated.length > 0) {
refreshSandboxPolicyContextFile(sandboxName);
return true;
}
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
console.error(` ${YW}⚠${R} Failed to apply generated '${channelName}' policy: ${msg}`);
return false;
}

return applyChannelPresetIfAvailable(sandboxName, channelName);
}

function getSandboxChannelStatePaths(agent: AgentDefinition, channelName: string): string[] {
const configDir = agent.configPaths.dir;
const stateDirs = new Set(agent.stateDirs);
Expand Down Expand Up @@ -1206,11 +1237,6 @@ function syncSessionPolicyPresetsWithRegistry(
// not abort the remove flow — the bridge teardown has already succeeded;
// the operator can run `policy-remove <channel>` manually if cleanup falters.
export function removeChannelPresetIfPresent(sandboxName: string, channelName: string): void {
const builtinPresets = new Set(policies.listPresets().map((p) => p.name));
if (!builtinPresets.has(channelName)) {
syncSessionPolicyPresetsWithRegistry(sandboxName, channelName, "remove");
return;
}
if (!policies.getAppliedPresets(sandboxName).includes(channelName)) {
syncSessionPolicyPresetsWithRegistry(sandboxName, channelName, "remove");
return;
Expand Down
1 change: 1 addition & 0 deletions src/lib/agent/defs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ describe("agent definitions", () => {
"slack",
"wechat",
"whatsapp",
"mattermost",
]);
expect(openclaw.inferenceProviderOptions).toEqual([]);
// #5027: openclaw.json must be declared as a durable state file so
Expand Down
10 changes: 10 additions & 0 deletions src/lib/messaging-channel-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,14 @@ describe("messaging channel config", () => {
"SLACK_ALLOWED_USERS",
"SLACK_ALLOWED_CHANNELS",
"WHATSAPP_ALLOWED_IDS",
"MATTERMOST_ALLOWED_USERS",
"MATTERMOST_ALLOWED_CHANNELS",
"MATTERMOST_REQUIRE_MENTION",
"TELEGRAM_GROUP_POLICY",
"WECHAT_ACCOUNT_ID",
"WECHAT_BASE_URL",
"WECHAT_USER_ID",
"MATTERMOST_URL",
]);
});

Expand All @@ -40,6 +44,9 @@ describe("messaging channel config", () => {
DISCORD_REQUIRE_MENTION: "0",
SLACK_ALLOWED_USERS: " U01ABC2DEF3, U04GHI5JKL6 ",
SLACK_ALLOWED_CHANNELS: " C012AB3CD, C987ZY6XW ",
MATTERMOST_URL: " https://mattermost.com ",
MATTERMOST_ALLOWED_CHANNELS: " town-square, ops ",
MATTERMOST_REQUIRE_MENTION: "1",
NVIDIA_INFERENCE_API_KEY: "not-channel-config",
}),
).toEqual({
Expand All @@ -49,6 +56,9 @@ describe("messaging channel config", () => {
DISCORD_REQUIRE_MENTION: "0",
SLACK_ALLOWED_USERS: "U01ABC2DEF3, U04GHI5JKL6",
SLACK_ALLOWED_CHANNELS: "C012AB3CD, C987ZY6XW",
MATTERMOST_URL: "https://mattermost.com",
MATTERMOST_ALLOWED_CHANNELS: "town-square, ops",
MATTERMOST_REQUIRE_MENTION: "1",
});
});

Expand Down
5 changes: 5 additions & 0 deletions src/lib/messaging/applier/host-state-applier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ function mergeSandboxMessagingPlans(
existing.networkPolicy.entries,
incoming.networkPolicy.entries,
);
const networkTemplates = mergeByChannelId(
existing.networkPolicy.templates ?? [],
incoming.networkPolicy.templates ?? [],
);

return clonePlan({
...incoming,
Expand All @@ -104,6 +108,7 @@ function mergeSandboxMessagingPlans(
networkPolicy: {
presets: uniqueStrings(networkEntries.map((entry) => entry.presetName)),
entries: networkEntries,
...(networkTemplates.length > 0 ? { templates: networkTemplates } : {}),
},
agentRender: mergeByChannelId(existing.agentRender, incoming.agentRender),
buildSteps: mergeByChannelId(existing.buildSteps, incoming.buildSteps),
Expand Down
26 changes: 25 additions & 1 deletion src/lib/messaging/applier/policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,13 @@ export function applyPolicyAtOpenShell(
options: MessagingPolicyApplyOptions,
): MessagingPolicyApplyResult {
const activeEntries = filterEnabledPlanEntries(plan, plan.networkPolicy.entries);
const activeTemplates = filterEnabledPlanEntries(plan, plan.networkPolicy.templates ?? []);
const activePresets = uniqueStrings(activeEntries.map((entry) => entry.presetName));
const activePolicyKeys = uniqueStrings(activeEntries.flatMap((entry) => entry.policyKeys));
const activeTemplatePresets = uniqueStrings(activeTemplates.map((entry) => entry.presetName));
const activePolicyKeys = uniqueStrings([
...activeEntries.flatMap((entry) => entry.policyKeys),
...activeTemplates.flatMap((entry) => entry.policyKeys),
]);
if (
activePresets.length > 0 &&
!options.applyPresets(plan.sandboxName, activePresets, {
Expand All @@ -23,9 +28,28 @@ export function applyPolicyAtOpenShell(
throw new Error(`Failed to apply messaging policy preset(s): ${activePresets.join(", ")}`);
}

if (activeTemplates.length > 0 && !options.applyPresetContent) {
throw new Error(
`Cannot apply generated messaging policy template(s): ${activeTemplatePresets.join(", ")}`,
);
}

for (const template of activeTemplates) {
if (
!options.applyPresetContent?.(plan.sandboxName, template.presetName, template.content, {
agent: plan.agent,
entries: activeEntries,
policyKeys: activePolicyKeys,
})
) {
throw new Error(`Failed to apply generated messaging policy: ${template.presetName}`);
}
}

return {
appliedPresets: activePresets,
appliedPolicyKeys: activePolicyKeys,
...(activeTemplatePresets.length > 0 ? { appliedTemplatePresets: activeTemplatePresets } : {}),
};
}

Expand Down
44 changes: 44 additions & 0 deletions src/lib/messaging/applier/setup-applier.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const TEST_CREDENTIALS: Readonly<Record<string, string>> = {
WECHAT_BOT_TOKEN: "test-wechat-token",
SLACK_BOT_TOKEN: "xoxb-test-slack-token",
SLACK_APP_TOKEN: "xapp-test-slack-token",
MATTERMOST_BOT_TOKEN: "test-mattermost-token",
};

async function withEnv<T>(
Expand All @@ -36,6 +37,7 @@ async function withEnv<T>(
): Promise<T> {
const scopedValues = {
NEMOCLAW_SKIP_TELEGRAM_REACHABILITY: "1",
NEMOCLAW_SKIP_MATTERMOST_AUTH_VALIDATION: "1",
...values,
};
const previous = Object.fromEntries(
Expand Down Expand Up @@ -804,6 +806,48 @@ describe("MessagingSetupApplier", () => {
});
});

it("applies generated policy template content directly from the serializable plan", async () => {
const plan = await buildOnboardPlan(
{
MATTERMOST_BOT_TOKEN: "test-mattermost-token",
MATTERMOST_URL: "https://chat.example.com/team",
},
["mattermost"],
);
const presetCalls: string[][] = [];
const contentCalls: string[][] = [];

const result = MessagingSetupApplier.applyPolicyAtOpenShell(plan, {
applyPresets: (sandboxName, presetNames) => {
presetCalls.push([sandboxName, ...presetNames]);
return true;
},
applyPresetContent: (sandboxName, presetName, content, context) => {
contentCalls.push([sandboxName, presetName, content]);
expect(context.policyKeys).toEqual(["mattermost"]);
return true;
},
});

expect(presetCalls).toEqual([]);
expect(contentCalls).toHaveLength(1);
expect(contentCalls[0][0]).toBe("demo");
expect(contentCalls[0][1]).toBe("mattermost");
expect(contentCalls[0][2]).toContain("chat.example.com");
expect(contentCalls[0][2]).toContain("protocol: rest");
expect(contentCalls[0][2]).toContain("request_body_credential_rewrite: true");
expect(contentCalls[0][2]).toContain("websocket_credential_rewrite: true");
expect(contentCalls[0][2]).toContain("path: /team/api/v4/**");
expect(contentCalls[0][2]).toContain("method: WEBSOCKET_TEXT");
expect(contentCalls[0][2]).not.toContain("access: full");
expect(contentCalls[0][2]).not.toContain("tls: skip");
expect(result).toEqual({
appliedPresets: [],
appliedPolicyKeys: ["mattermost"],
appliedTemplatePresets: ["mattermost"],
});
});

it("passes concrete policy keys for agent-aware preset application", async () => {
const plan = await buildOnboardPlan(
{
Expand Down
7 changes: 7 additions & 0 deletions src/lib/messaging/applier/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,11 +103,18 @@ export interface MessagingPolicyApplyOptions {
presetNames: string[],
context: MessagingPolicyApplyContext,
) => boolean;
readonly applyPresetContent?: (
sandboxName: string,
presetName: string,
presetContent: string,
context: MessagingPolicyApplyContext,
) => boolean;
}

export interface MessagingPolicyApplyResult {
readonly appliedPresets: readonly string[];
readonly appliedPolicyKeys: readonly string[];
readonly appliedTemplatePresets?: readonly string[];
}

export type MessagingSerializablePlan = SandboxMessagingPlan;
Expand Down
3 changes: 3 additions & 0 deletions src/lib/messaging/channels/built-ins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@
import type { ChannelManifestRegistry } from "../manifest";
import { createChannelManifestRegistry } from "../manifest";
import { discordManifest } from "./discord/manifest";
import { mattermostManifest } from "./mattermost/manifest";
import { slackManifest } from "./slack/manifest";
import { telegramManifest } from "./telegram/manifest";
import { wechatManifest } from "./wechat/manifest";
import { whatsappManifest } from "./whatsapp/manifest";

export { discordManifest } from "./discord/manifest";
export { mattermostManifest } from "./mattermost/manifest";
export { slackManifest } from "./slack/manifest";
export { telegramManifest } from "./telegram/manifest";
export { wechatManifest } from "./wechat/manifest";
Expand All @@ -21,6 +23,7 @@ export const BUILT_IN_CHANNEL_MANIFESTS = [
wechatManifest,
slackManifest,
whatsappManifest,
mattermostManifest,
] as const;

export function createBuiltInChannelManifestRegistry(): ChannelManifestRegistry {
Expand Down
Loading
Loading