diff --git a/agents/hermes/policy-additions.yaml b/agents/hermes/policy-additions.yaml index 4b602692c5b..704b1a0757a 100644 --- a/agents/hermes/policy-additions.yaml +++ b/agents/hermes/policy-additions.yaml @@ -149,231 +149,3 @@ network_policies: - { path: /usr/local/bin/curl } - { path: /usr/bin/python3* } - { path: /opt/hermes/.venv/bin/python } - - # ── Messaging policy templates ───────────────────────────────── - # These entries are agent-specific channel templates. During sandbox - # creation, NemoClaw filters out entries for messaging channels that were not - # selected, so a Discord-only Hermes sandbox does not retain Telegram, Slack, - # or WeChat egress. - telegram: - name: telegram - endpoints: - - host: api.telegram.org - port: 443 - protocol: rest - enforcement: enforce - rules: - - allow: { method: GET, path: "/bot*/**" } - - allow: { method: POST, path: "/bot*/**" } - - allow: { method: GET, path: "/file/bot*/**" } - binaries: - - { path: /usr/local/bin/node } - - { path: /usr/bin/python3* } - - { path: /opt/hermes/.venv/bin/python } - - discord: - name: discord - endpoints: - - host: discord.com - port: 443 - protocol: rest - enforcement: enforce - rules: - - allow: { method: GET, path: "/**" } - - allow: { method: POST, path: "/**" } - - allow: { method: GET, path: "/gateway*" } - - allow: { method: GET, path: "/api/v*/gateway/bot" } - - allow: { method: GET, path: "/api/v*/applications/@me" } - - allow: { method: PUT, path: "/api/v*/applications/*/commands" } - - allow: { method: PUT, path: "/api/v*/channels/*/messages/*/reactions/*/@me" } - - allow: { method: PATCH, path: "/api/v*/applications/*" } - - allow: { method: PATCH, path: "/api/v*/applications/*/commands/*" } - - allow: { method: PATCH, path: "/api/v*/channels/*/messages/*" } - - allow: { method: PATCH, path: "/api/v*/webhooks/*/*/messages/*" } - - allow: { method: DELETE, path: "/api/v*/applications/*/commands/*" } - - allow: { method: DELETE, path: "/api/v*/channels/*/messages/*" } - - allow: { method: DELETE, path: "/api/v*/channels/*/messages/*/reactions/*/*" } - - allow: { method: DELETE, path: "/api/v*/webhooks/*/*/messages/*" } - - host: gateway.discord.gg - port: 443 - protocol: websocket - enforcement: enforce - websocket_credential_rewrite: true - rules: - - allow: { method: GET, path: "/**" } - - allow: { method: WEBSOCKET_TEXT, path: "/**" } - - host: "*.discord.gg" - port: 443 - protocol: websocket - enforcement: enforce - websocket_credential_rewrite: true - rules: - - allow: { method: GET, path: "/**" } - - allow: { method: WEBSOCKET_TEXT, path: "/**" } - - host: cdn.discordapp.com - port: 443 - protocol: rest - enforcement: enforce - rules: - - allow: { method: GET, path: "/**" } - binaries: - - { path: /usr/local/bin/node } - - { path: /usr/bin/python3* } - - { path: /opt/hermes/.venv/bin/python } - - slack: - name: slack - endpoints: - - host: slack.com - port: 443 - protocol: rest - enforcement: enforce - request_body_credential_rewrite: true - rules: - - allow: { method: GET, path: "/**" } - - allow: { method: POST, path: "/**" } - - host: api.slack.com - port: 443 - protocol: rest - enforcement: enforce - request_body_credential_rewrite: true - rules: - - allow: { method: GET, path: "/**" } - - allow: { method: POST, path: "/**" } - - host: hooks.slack.com - port: 443 - protocol: rest - enforcement: enforce - request_body_credential_rewrite: true - rules: - - allow: { method: GET, path: "/**" } - - allow: { method: POST, path: "/**" } - - host: wss-primary.slack.com - port: 443 - protocol: websocket - enforcement: enforce - websocket_credential_rewrite: true - rules: - - allow: { method: GET, path: "/**" } - - allow: { method: WEBSOCKET_TEXT, path: "/**" } - - host: wss-backup.slack.com - port: 443 - protocol: websocket - enforcement: enforce - websocket_credential_rewrite: true - rules: - - allow: { method: GET, path: "/**" } - - allow: { method: WEBSOCKET_TEXT, path: "/**" } - binaries: - - { path: /usr/local/bin/hermes } - - { path: /usr/bin/python3* } - - { path: /opt/hermes/.venv/bin/python } - - teams: - name: teams - endpoints: - - host: login.microsoftonline.com - port: 443 - protocol: rest - enforcement: enforce - request_body_credential_rewrite: true - rules: - - allow: { method: GET, path: "/**" } - - allow: { method: POST, path: "/**" } - - host: login.botframework.com - port: 443 - protocol: rest - enforcement: enforce - request_body_credential_rewrite: true - rules: - - allow: { method: GET, path: "/**" } - - allow: { method: POST, path: "/**" } - - host: api.botframework.com - port: 443 - protocol: rest - enforcement: enforce - request_body_credential_rewrite: true - rules: - - allow: { method: GET, path: "/**" } - - allow: { method: POST, path: "/**" } - # The SDK follows Bot Connector serviceUrl values from inbound Teams - # activities, so this host remains method-scoped while Graph/media hosts - # stay read-only. - - host: smba.trafficmanager.net - port: 443 - protocol: rest - enforcement: enforce - request_body_credential_rewrite: true - rules: - - allow: { method: GET, path: "/**" } - - allow: { method: POST, path: "/**" } - - allow: { method: PUT, path: "/**" } - - allow: { method: DELETE, path: "/**" } - - host: graph.microsoft.com - port: 443 - protocol: rest - enforcement: enforce - request_body_credential_rewrite: true - rules: - - allow: { method: GET, path: "/**" } - - host: teams.microsoft.com - port: 443 - protocol: rest - enforcement: enforce - rules: - - allow: { method: GET, path: "/**" } - - host: teams.cdn.office.net - port: 443 - protocol: rest - enforcement: enforce - rules: - - allow: { method: GET, path: "/**" } - - host: statics.teams.cdn.office.net - port: 443 - protocol: rest - enforcement: enforce - rules: - - allow: { method: GET, path: "/**" } - - host: "*.sharepoint.com" - port: 443 - protocol: rest - enforcement: enforce - rules: - - allow: { method: GET, path: "/**" } - - host: 1drv.ms - port: 443 - protocol: rest - enforcement: enforce - rules: - - allow: { method: GET, path: "/**" } - binaries: - - { path: /usr/local/bin/hermes } - - { path: /usr/bin/python3* } - - { path: /opt/hermes/.venv/bin/python } - - # WeChat (personal) via Tencent's iLink Bot API. The Hermes adapter uses - # HTTP long-polling (no WebSocket). WEIXIN_TOKEN is L7-resolved at egress - # from WECHAT_BOT_TOKEN (same credential slot OpenClaw's bridge uses) via - # manifest hook render outputs. See nemoclaw-blueprint/policies/presets/wechat.yaml - # for the shared host set. - wechat_bridge: - name: wechat_bridge - endpoints: - - host: ilinkai.weixin.qq.com - port: 443 - protocol: rest - enforcement: enforce - rules: - - allow: { method: GET, path: "/**" } - - allow: { method: POST, path: "/**" } - - host: ilinkai.wechat.com - port: 443 - protocol: rest - enforcement: enforce - rules: - - allow: { method: GET, path: "/**" } - - allow: { method: POST, path: "/**" } - binaries: - - { path: /usr/local/bin/hermes } - - { path: /usr/bin/python3* } - - { path: /opt/hermes/.venv/bin/python } diff --git a/ci/platform-matrix.json b/ci/platform-matrix.json index da84d3ae0e8..9c2fda8c6c0 100644 --- a/ci/platform-matrix.json +++ b/ci/platform-matrix.json @@ -301,7 +301,7 @@ { "name": "WhatsApp", "status": "caveated", - "notes": "Supported by both OpenClaw and Hermes through the channel manifest `supportedAgents` declaration in `src/lib/messaging/channels/whatsapp/manifest.ts`. Pairing happens in the sandbox through WhatsApp Web by scanning a QR code at first run; the Hermes flow exposes this as `hermes whatsapp` and persists session credentials under `~/.hermes/platforms/whatsapp/session` (`agents/hermes/manifest.yaml:69-71`). Sandbox egress goes through the `whatsapp` policy preset, which carries the WebSocket / Noise / h1-ALPN caveats documented in `nemoclaw-blueprint/policies/presets/whatsapp.yaml`. No Meta Business API integration today; that path is out of scope for this matrix." + "notes": "Supported by both OpenClaw and Hermes through the channel manifest `supportedAgents` declaration in `src/lib/messaging/channels/whatsapp/manifest.ts`. Pairing happens in the sandbox through WhatsApp Web by scanning a QR code at first run; the Hermes flow exposes this as `hermes whatsapp` and persists session credentials under `~/.hermes/platforms/whatsapp/session` (`agents/hermes/manifest.yaml:69-71`). Sandbox egress goes through the `whatsapp` policy preset, which carries the WebSocket / Noise / h1-ALPN caveats documented in `src/lib/messaging/channels/whatsapp/policy/openclaw.yaml` and `src/lib/messaging/channels/whatsapp/policy/hermes.yaml`. No Meta Business API integration today; that path is out of scope for this matrix." }, { "name": "Microsoft Teams", diff --git a/ci/test-file-size-budget.json b/ci/test-file-size-budget.json index 916cc2a9f85..bb7e003f9fb 100644 --- a/ci/test-file-size-budget.json +++ b/ci/test-file-size-budget.json @@ -12,6 +12,6 @@ "test/onboard-messaging.test.ts": 2062, "test/onboard-selection.test.ts": 6867, "test/onboard.test.ts": 4774, - "test/policies.test.ts": 2475 + "test/policies.test.ts": 2332 } } diff --git a/docs/network-policy/customize-network-policy.mdx b/docs/network-policy/customize-network-policy.mdx index 8375c67effa..9c1bd9495e1 100644 --- a/docs/network-policy/customize-network-policy.mdx +++ b/docs/network-policy/customize-network-policy.mdx @@ -204,6 +204,7 @@ For guided post-install examples, refer to [Common Integration Policy Examples]( During onboarding, the [policy tier](../reference/network-policies#policy-tiers) you select determines which presets are enabled by default. You can add or remove individual presets in the interactive preset screen that follows tier selection. +Built-in preset choices are scoped to the sandbox's active agent, so unsupported messaging channel presets do not appear in `policy-list` or the interactive `policy-add` picker for agents without matching channel policy files. Available presets: diff --git a/docs/network-policy/integration-policy-examples.mdx b/docs/network-policy/integration-policy-examples.mdx index 073d98c497f..adf66e940ef 100644 --- a/docs/network-policy/integration-policy-examples.mdx +++ b/docs/network-policy/integration-policy-examples.mdx @@ -47,6 +47,7 @@ An approval updates the running policy, but it does not create a reviewable Nemo ## Supported Integration Presets NemoClaw ships maintained policy presets for common services in `nemoclaw-blueprint/policies/presets/`. +Messaging channel presets are scoped to the sandbox's active agent; if an agent does not have a matching channel policy, that channel preset is omitted from `policy-list` and `policy-add ` reports it as unknown. | Workflow | Preset | |----------|--------| diff --git a/docs/reference/commands-nemohermes.mdx b/docs/reference/commands-nemohermes.mdx index 4f0f716d472..b28a22af488 100644 --- a/docs/reference/commands-nemohermes.mdx +++ b/docs/reference/commands-nemohermes.mdx @@ -828,8 +828,7 @@ nemohermes my-assistant policy-add pypi --yes The positional form is required in scripted workflows. Set `NEMOCLAW_NON_INTERACTIVE=1` instead of `--yes` if you want the same behavior from an environment variable. If the preset name is unknown or already applied, the command exits non-zero with a clear error. -Messaging channel presets such as `telegram`, `discord`, `slack`, `wechat`, and `whatsapp` apply only to agents that support those channels. -On a terminal-runtime agent such as DeepAgents, which has no inbound messaging gateway, `policy-add` rejects the preset with a clear error before any endpoint disclosure or prompt, matching `channels add`. +Built-in preset choices are scoped to the sandbox's active agent. Messaging channel presets appear only when NemoClaw has a matching channel policy for that agent; unavailable channel presets use the standard unknown-preset error before endpoint preview or confirmation. Custom preset files are tracked with the sandbox that applied them. `policy-list`, `policy-add`, and `policy-remove` compare the local registry and live gateway state using that sandbox-scoped preset metadata, so custom presets do not appear missing just because they are not part of the built-in preset catalog. Before `policy-add` writes a merged policy, it reads and parses the current live policy from OpenShell. @@ -869,6 +868,7 @@ Custom presets bypass the built-in preset review process and can widen sandbox e ### `nemohermes policy-list` List available policy presets and show which ones are applied to the sandbox. +The available built-in rows are scoped to the sandbox's active agent, so unsupported messaging channel policies are not listed for agents without matching channel policy files. The command cross-references the local registry against the live gateway state (via `openshell policy get`), so it flags presets that are applied in one place but not the other. This catches desync caused by external edits to the gateway policy or stale registry entries after a manual rollback. Preset summaries come only from the YAML `preset.description` field. diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 0dac54e74c2..080c6b3fb57 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -1132,8 +1132,7 @@ $$nemoclaw my-assistant policy-add pypi --yes The positional form is required in scripted workflows. Set `NEMOCLAW_NON_INTERACTIVE=1` instead of `--yes` if you want the same behavior from an environment variable. If the preset name is unknown or already applied, the command exits non-zero with a clear error. -Messaging channel presets such as `telegram`, `discord`, `slack`, `wechat`, and `whatsapp` apply only to agents that support those channels. -On a terminal-runtime agent such as DeepAgents, which has no inbound messaging gateway, `policy-add` rejects the preset with a clear error before any endpoint disclosure or prompt, matching `channels add`. +Built-in preset choices are scoped to the sandbox's active agent. Messaging channel presets appear only when NemoClaw has a matching channel policy for that agent; unavailable channel presets use the standard unknown-preset error before endpoint preview or confirmation. Custom preset files are tracked with the sandbox that applied them. `policy-list`, `policy-add`, and `policy-remove` compare the local registry and live gateway state using that sandbox-scoped preset metadata, so custom presets do not appear missing just because they are not part of the built-in preset catalog. Before `policy-add` writes a merged policy, it reads and parses the current live policy from OpenShell. @@ -1173,6 +1172,7 @@ Custom presets bypass the built-in preset review process and can widen sandbox e ### `$$nemoclaw policy-list` List available policy presets and show which ones are applied to the sandbox. +The available built-in rows are scoped to the sandbox's active agent, so unsupported messaging channel policies are not listed for agents without matching channel policy files. The command cross-references the local registry against the live gateway state (via `openshell policy get`), so it flags presets that are applied in one place but not the other. This catches desync caused by external edits to the gateway policy or stale registry entries after a manual rollback. Preset summaries come only from the YAML `preset.description` field. diff --git a/docs/reference/network-policies.mdx b/docs/reference/network-policies.mdx index d4062cf7f83..a1b9395d08b 100644 --- a/docs/reference/network-policies.mdx +++ b/docs/reference/network-policies.mdx @@ -73,8 +73,8 @@ The baseline policy is always applied regardless of the selected tier. | Open | `npm`, `pypi`, `huggingface`, `brew`, `brave when supported`, `weather`, `public-reference`, `slack`, `discord`, `telegram`, `wechat` (experimental), `whatsapp` (experimental), `jira`, `outlook` | Broad access across third-party services including messaging, productivity, weather, and public-reference APIs. | After selecting a tier, a combined preset and access-mode screen lets you include or exclude individual presets and toggle each between read (GET only) and read-write (GET + POST/PUT/PATCH) access. -Tier-default presets are pre-selected; additional presets can be added from the full list. -NemoClaw filters tier defaults by the active agent's supported integrations. +Tier-default presets are pre-selected; additional presets can be added from the built-in preset list available to the sandbox's active agent. +NemoClaw filters tier defaults and built-in preset choices by the active agent's supported integrations. For example, Hermes onboarding omits the Brave Search preset because Hermes does not use NemoClaw's OpenClaw web-search configuration. Hermes managed-tool gateway selections can add Hermes-specific presets, such as Nous-hosted web, image, audio, browser, or code tools, without applying unsupported OpenClaw-only presets. OpenClaw onboarding also adds the `openclaw-pricing` preset on top of tier defaults so session-cost records can populate from LiteLLM and OpenRouter without manual configuration. diff --git a/docs/reference/platform-support.mdx b/docs/reference/platform-support.mdx index 1b9f163fe68..62938bcdcb5 100644 --- a/docs/reference/platform-support.mdx +++ b/docs/reference/platform-support.mdx @@ -117,7 +117,7 @@ NemoClaw configures messaging channels during onboarding. The OpenShell gateway | Discord | Tested | Configured through an OpenShell-managed channel during onboarding. Sandbox egress allowed by the `discord` policy preset. | | Telegram | Tested | Configured through an OpenShell-managed channel during onboarding. | | WeChat | Tested with limitations | Channel hook available. Verify regional account access before relying on this path. | -| WhatsApp | Tested with limitations | Supported by both OpenClaw and Hermes through the channel manifest `supportedAgents` declaration in `src/lib/messaging/channels/whatsapp/manifest.ts`. Pairing happens in the sandbox through WhatsApp Web by scanning a QR code at first run; the Hermes flow exposes this as `hermes whatsapp` and persists session credentials under `~/.hermes/platforms/whatsapp/session` (`agents/hermes/manifest.yaml:69-71`). Sandbox egress goes through the `whatsapp` policy preset, which carries the WebSocket / Noise / h1-ALPN caveats documented in `nemoclaw-blueprint/policies/presets/whatsapp.yaml`. No Meta Business API integration today; that path is out of scope for this matrix. | +| WhatsApp | Tested with limitations | Supported by both OpenClaw and Hermes through the channel manifest `supportedAgents` declaration in `src/lib/messaging/channels/whatsapp/manifest.ts`. Pairing happens in the sandbox through WhatsApp Web by scanning a QR code at first run; the Hermes flow exposes this as `hermes whatsapp` and persists session credentials under `~/.hermes/platforms/whatsapp/session` (`agents/hermes/manifest.yaml:69-71`). Sandbox egress goes through the `whatsapp` policy preset, which carries the WebSocket / Noise / h1-ALPN caveats documented in `src/lib/messaging/channels/whatsapp/policy/openclaw.yaml` and `src/lib/messaging/channels/whatsapp/policy/hermes.yaml`. No Meta Business API integration today; that path is out of scope for this matrix. | | Microsoft Teams | Experimental | Supported by both OpenClaw and Hermes through the manifest-first messaging channel contract. Requires Bot Framework app credentials, a tenant ID, and a public HTTPS endpoint that reaches the sandbox webhook path `/api/messages`. Sandbox egress goes through the `teams` policy preset, and only one active Teams sandbox can use a given local `MSTEAMS_PORT` forward. | {/* integration-status:end */} diff --git a/package.json b/package.json index a85efcba28c..2aa6cbfd314 100644 --- a/package.json +++ b/package.json @@ -81,6 +81,7 @@ ".version", "bin/", "dist/", + "src/lib/messaging/channels/**/policy/*.{yaml,yml}", "nemoclaw/dist/", "nemoclaw/openclaw.plugin.json", "nemoclaw/package.json", diff --git a/schemas/policy-preset.schema.json b/schemas/policy-preset.schema.json index bcf674942ff..cd30ce52444 100644 --- a/schemas/policy-preset.schema.json +++ b/schemas/policy-preset.schema.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://github.com/NVIDIA/NemoClaw/schemas/policy-preset.schema.json", "title": "NemoClaw Policy Preset", - "description": "Schema for policy presets (nemoclaw-blueprint/policies/presets/*.yaml) — named network policy bundles that can be merged into the base sandbox policy.", + "description": "Schema for policy presets (nemoclaw-blueprint/policies/presets/*.yaml and src/lib/messaging/channels/*/policy/*.yaml) — named network policy bundles that can be merged into the base sandbox policy.", "type": "object", "required": ["preset", "network_policies"], "additionalProperties": false, diff --git a/scripts/find-source-shape-tests.ts b/scripts/find-source-shape-tests.ts index fffe5cb82c5..d547bb1573b 100755 --- a/scripts/find-source-shape-tests.ts +++ b/scripts/find-source-shape-tests.ts @@ -133,6 +133,7 @@ function looksLikeDeclarativeConfigPath(text: string): boolean { return ( /nemoclaw-blueprint\/blueprint\.yaml/.test(normalized) || /nemoclaw-blueprint\/policies\//.test(normalized) || + /src\/lib\/messaging\/channels\/[^/]+\/policy\/[^/]+\.yaml/.test(normalized) || /nemoclaw-blueprint\/provider-profiles\//.test(normalized) || /nemoclaw-blueprint\/router\/pool-config\.yaml/.test(normalized) || /nemoclaw-blueprint\/model-specific-setup\//.test(normalized) || diff --git a/scripts/validate-configs.ts b/scripts/validate-configs.ts index cd24310fd43..8e4799146fe 100755 --- a/scripts/validate-configs.ts +++ b/scripts/validate-configs.ts @@ -107,26 +107,48 @@ function discoverTargets(): ConfigTarget[] { // Discover all preset YAML files dynamically. const presetsDir = join(REPO_ROOT, "nemoclaw-blueprint/policies/presets"); + const presetFiles: string[] = []; try { - const presetFiles = readdirSync(presetsDir) - .filter((f) => f.endsWith(".yaml") || f.endsWith(".yml")) - .map((f) => `nemoclaw-blueprint/policies/presets/${f}`); - if (presetFiles.length > 0) { - targets.push({ - schema: "schemas/policy-preset.schema.json", - files: presetFiles, - }); - } else { - console.warn( - "WARN: presets directory exists but contains no .yaml/.yml files — no preset validation performed", - ); - } + presetFiles.push( + ...readdirSync(presetsDir) + .filter((f) => f.endsWith(".yaml") || f.endsWith(".yml")) + .map((f) => `nemoclaw-blueprint/policies/presets/${f}`), + ); } catch (err) { const code = typeof err === "object" && err !== null && "code" in err ? err.code : undefined; if (code !== "ENOENT" && code !== "ENOTDIR") throw err; // presets directory may not exist — not an error } + const channelPoliciesDir = join(REPO_ROOT, "src/lib/messaging/channels"); + try { + const walkChannelPolicies = (dir: string): void => { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const abs = join(dir, entry.name); + if (entry.isDirectory()) { + walkChannelPolicies(abs); + } else if (entry.isFile() && /\.ya?ml$/.test(entry.name)) { + const repoPath = pathRelativeToRepo(abs); + if (/(^|\/)policy\/[^/]+\.ya?ml$/.test(repoPath)) presetFiles.push(repoPath); + } + } + }; + walkChannelPolicies(channelPoliciesDir); + } catch (err) { + const code = typeof err === "object" && err !== null && "code" in err ? err.code : undefined; + if (code !== "ENOENT" && code !== "ENOTDIR") throw err; + // channel policy directories may not exist — not an error + } + + if (presetFiles.length > 0) { + targets.push({ + schema: "schemas/policy-preset.schema.json", + files: presetFiles.sort(), + }); + } else { + console.warn("WARN: no preset .yaml/.yml files discovered — no preset validation performed"); + } + return targets; } diff --git a/src/lib/actions/sandbox/policy-add-agent-gate.test.ts b/src/lib/actions/sandbox/policy-add-agent-gate.test.ts deleted file mode 100644 index b11495de097..00000000000 --- a/src/lib/actions/sandbox/policy-add-agent-gate.test.ts +++ /dev/null @@ -1,218 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { createRequire } from "node:module"; - -import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest"; - -const requireSource = createRequire(import.meta.url); -const D = (p: string) => requireSource(`../../${p}`); - -const registry = D("state/registry.js"); -const defs = D("agent/defs.js"); -const policy = D("policy/index.js"); -const store = D("credentials/store.js"); -const onboardSession = D("state/onboard-session.js"); -const contextRefresh = D("actions/sandbox/policy-context-refresh.js"); - -const { addSandboxPolicy } = D("actions/sandbox/policy-channel.js") as { - addSandboxPolicy: ( - name: string, - options?: { - preset?: string; - dryRun?: boolean; - yes?: boolean; - force?: boolean; - fromFile?: string; - fromDir?: string; - }, - ) => Promise; -}; - -const MESSAGING_POLICY_KEYS = [ - ["telegram_bot", "api.telegram.org"], - ["discord", "discord.com"], - ["slack", "api.slack.com"], - ["wechat_bridge", "api.weixin.qq.com"], - ["whatsapp", "graph.facebook.com"], - ["teams", "graph.microsoft.com"], -] as const; - -const MESSAGING_CHANNELS = ["telegram", "discord", "slack", "wechat", "whatsapp"] as const; - -const PRESETS = [ - { name: "pypi", description: "Python Package Index access" }, - { name: "telegram", description: "Telegram API access" }, - { name: "discord", description: "Discord API access" }, - { name: "slack", description: "Slack API access" }, - { name: "wechat", description: "WeChat API access" }, - { name: "whatsapp", description: "WhatsApp API access" }, -]; - -let errSpy: MockInstance; -let logSpy: MockInstance; -let applyPresetMock: MockInstance; -let selectFromListMock: MockInstance; -let promptMock: MockInstance; - -function exitCodeFromError(err: unknown): number | null { - const message = err instanceof Error ? err.message : String(err); - const match = message.match(/^process\.exit\((\d+)\)$/); - return match ? Number(match[1]) : null; -} - -function errorText(): string { - return (errSpy.mock.calls as unknown[][]).map((call) => call.map(String).join(" ")).join("\n"); -} - -function logText(): string { - return (logSpy.mock.calls as unknown[][]).map((call) => call.map(String).join(" ")).join("\n"); -} - -async function captureExit(action: () => Promise): Promise { - try { - await action(); - } catch (err) { - return exitCodeFromError(err); - } - return null; -} - -beforeEach(() => { - delete process.env.NEMOCLAW_NON_INTERACTIVE; - - logSpy = vi.spyOn(console, "log").mockImplementation(() => undefined); - errSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); - vi.spyOn(process, "exit").mockImplementation(((code?: number) => { - throw new Error(`process.exit(${code})`); - }) as never); - - vi.spyOn(registry, "getSandbox").mockReturnValue({ - name: "da-test", - agent: "langchain-deepagents-code", - policies: [], - }); - vi.spyOn(policy, "listPresets").mockReturnValue(PRESETS); - vi.spyOn(policy, "listCustomPresets").mockReturnValue([]); - vi.spyOn(policy, "getAppliedPresets").mockReturnValue([]); - vi.spyOn(policy, "loadPreset").mockImplementation((name: unknown) => { - const presetName = String(name); - return `network_policies:\n ${presetName}:\n host: ${presetName}.example.com\n`; - }); - applyPresetMock = vi.spyOn(policy, "applyPreset").mockReturnValue(true); - selectFromListMock = vi.spyOn(policy, "selectFromList").mockResolvedValue("pypi"); - promptMock = vi.spyOn(store, "prompt").mockResolvedValue("y"); - - vi.spyOn(onboardSession, "loadSession").mockReturnValue(null); - vi.spyOn(onboardSession, "updateSession").mockImplementation(() => undefined); - vi.spyOn(contextRefresh, "refreshSandboxPolicyContextFile").mockImplementation(() => undefined); -}); - -afterEach(() => { - vi.restoreAllMocks(); -}); - -describe("addSandboxPolicy channel-agent gate", () => { - it.each( - MESSAGING_CHANNELS, - )("refuses the '%s' channel preset on a terminal-runtime agent before any disclosure, prompt, or apply", async (channel) => { - vi.spyOn(defs, "loadAgent").mockReturnValue({ name: "langchain-deepagents-code" }); - - const code = await captureExit(() => - addSandboxPolicy("da-test", { preset: channel, yes: true }), - ); - - expect(code).toBe(1); - expect(errorText()).toMatch( - new RegExp(`Channel '${channel}' does not support agent 'langchain-deepagents-code'`), - ); - expect(errorText()).toMatch(/Channel-supported agents: openclaw, hermes/); - expect(errorText()).toMatch( - /Channels supported by agent 'langchain-deepagents-code': \(none\)/, - ); - expect(logText()).not.toContain("Endpoints that would be opened"); - expect(promptMock).not.toHaveBeenCalled(); - expect(applyPresetMock).not.toHaveBeenCalled(); - }); - - it("still applies a non-messaging preset on a terminal-runtime agent", async () => { - vi.spyOn(defs, "loadAgent").mockReturnValue({ name: "langchain-deepagents-code" }); - - await addSandboxPolicy("da-test", { preset: "pypi", yes: true }); - - expect(errorText()).not.toMatch(/does not support agent/); - expect(applyPresetMock).toHaveBeenCalledWith("da-test", "pypi"); - }); - - it("does not gate a messaging-capable agent (openclaw applies a channel preset)", async () => { - vi.spyOn(registry, "getSandbox").mockReturnValue({ - name: "oc-test", - agent: "openclaw", - policies: [], - }); - vi.spyOn(defs, "loadAgent").mockReturnValue({ name: "openclaw" }); - - await addSandboxPolicy("oc-test", { preset: "telegram", yes: true }); - - expect(errorText()).not.toMatch(/does not support agent/); - expect(applyPresetMock).toHaveBeenCalledWith("oc-test", "telegram"); - }); - - it("omits unsupported channel presets from the interactive picker for a terminal-runtime agent", async () => { - vi.spyOn(defs, "loadAgent").mockReturnValue({ name: "langchain-deepagents-code" }); - - await addSandboxPolicy("da-test"); - - expect(selectFromListMock).toHaveBeenCalledTimes(1); - const offered = (selectFromListMock.mock.calls[0][0] as Array<{ name: string }>).map( - (preset) => preset.name, - ); - expect(offered).toContain("pypi"); - for (const channel of MESSAGING_CHANNELS) { - expect(offered).not.toContain(channel); - } - }); -}); - -describe("addSandboxPolicy custom preset (--from-file) agent gate", () => { - it.each( - MESSAGING_POLICY_KEYS, - )("rejects a custom preset with a '%s' policy key on a terminal-runtime agent before any disclosure, prompt, or apply", async (policyKey, host) => { - vi.spyOn(defs, "loadAgent").mockReturnValue({ name: "langchain-deepagents-code" }); - vi.spyOn(policy, "loadPresetFromFile").mockReturnValue({ - presetName: "my-custom", - content: `preset:\n name: my-custom\nnetwork_policies:\n ${policyKey}:\n host: ${host}\n`, - }); - const applyPresetContentMock = vi.spyOn(policy, "applyPresetContent"); - - const code = await captureExit(() => - addSandboxPolicy("da-test", { fromFile: "/tmp/my-custom.yaml", yes: true }), - ); - - expect(code).toBe(1); - expect(errorText()).toMatch(/does not support agent 'langchain-deepagents-code'/); - expect(logText()).not.toContain("Endpoints that would be opened"); - expect(promptMock).not.toHaveBeenCalled(); - expect(applyPresetContentMock).not.toHaveBeenCalled(); - }); - - it("still applies a non-messaging custom preset on a terminal-runtime agent", async () => { - vi.spyOn(defs, "loadAgent").mockReturnValue({ name: "langchain-deepagents-code" }); - vi.spyOn(policy, "loadPresetFromFile").mockReturnValue({ - presetName: "my-pypi-mirror", - content: - "preset:\n name: my-pypi-mirror\nnetwork_policies:\n pypi_mirror:\n host: pypi.example.com\n", - }); - const applyPresetContentMock = vi.spyOn(policy, "applyPresetContent").mockReturnValue(true); - - await addSandboxPolicy("da-test", { fromFile: "/tmp/my-pypi-mirror.yaml", yes: true }); - - expect(errorText()).not.toMatch(/does not support agent/); - expect(applyPresetContentMock).toHaveBeenCalledWith( - "da-test", - "my-pypi-mirror", - expect.stringContaining("pypi_mirror"), - { custom: { sourcePath: expect.stringContaining("my-pypi-mirror.yaml") } }, - ); - }); -}); diff --git a/src/lib/actions/sandbox/policy-channel-agent-gate.test.ts b/src/lib/actions/sandbox/policy-channel-agent-gate.test.ts index 9fc5c1e9f2b..8e83abed79a 100644 --- a/src/lib/actions/sandbox/policy-channel-agent-gate.test.ts +++ b/src/lib/actions/sandbox/policy-channel-agent-gate.test.ts @@ -41,7 +41,7 @@ let upsertMock: MockInstance; let updateSandboxMock: MockInstance; let runOpenshellMock: MockInstance; let applyPresetMock: MockInstance; -let loadPresetMock: MockInstance; +let loadPresetForSandboxMock: MockInstance; let saveCredentialMock: MockInstance; let getCredentialMock: MockInstance; let promptMock: MockInstance; @@ -68,8 +68,8 @@ beforeEach(() => { runOpenshellMock = vi .spyOn(runtime, "runOpenshell") .mockReturnValue({ status: 0, stdout: "", stderr: "" }); - loadPresetMock = vi - .spyOn(policy, "loadPreset") + loadPresetForSandboxMock = vi + .spyOn(policy, "loadPresetForSandbox") .mockReturnValue("network_policies:\n stub: {}\n"); vi.spyOn(policy, "parsePresetPolicyKeys").mockReturnValue(["stub"]); vi.spyOn(policy, "listPresets").mockReturnValue([]); @@ -106,7 +106,7 @@ describe("addSandboxChannel agent gate", () => { expect(errorText).toMatch(/Channel-supported agents: openclaw, hermes/); expect(errorText).toMatch(/Channels supported by agent 'custom-agent': \(none\)/); - expect(loadPresetMock).not.toHaveBeenCalled(); + expect(loadPresetForSandboxMock).not.toHaveBeenCalled(); expect(applyPresetMock).not.toHaveBeenCalled(); expect(upsertMock).not.toHaveBeenCalled(); expect(updateSandboxMock).not.toHaveBeenCalled(); @@ -130,7 +130,7 @@ describe("addSandboxChannel agent gate", () => { } expect(exitCodeFromError(caught)).toBe(1); - expect(loadPresetMock).not.toHaveBeenCalled(); + expect(loadPresetForSandboxMock).not.toHaveBeenCalled(); expect(applyPresetMock).not.toHaveBeenCalled(); expect(upsertMock).not.toHaveBeenCalled(); expect(updateSandboxMock).not.toHaveBeenCalled(); @@ -153,7 +153,7 @@ describe("addSandboxChannel agent gate", () => { .map((call) => call.map(String).join(" ")) .join("\n"); expect(errorText).not.toMatch(/does not support agent/); - expect(loadPresetMock).toHaveBeenCalled(); + expect(loadPresetForSandboxMock).toHaveBeenCalled(); void caught; void exitMock; void logSpy; diff --git a/src/lib/actions/sandbox/policy-channel-list.test.ts b/src/lib/actions/sandbox/policy-channel-list.test.ts index 19fd9b43fde..cbd64716204 100644 --- a/src/lib/actions/sandbox/policy-channel-list.test.ts +++ b/src/lib/actions/sandbox/policy-channel-list.test.ts @@ -11,7 +11,7 @@ type PresetInfo = { const moduleMocks = vi.hoisted(() => ({ getSandbox: vi.fn<(sandboxName: string) => Record | null>(), getCustomPolicies: vi.fn<(sandboxName: string) => PresetInfo[]>(), - listPresets: vi.fn<() => PresetInfo[]>(), + listPresets: vi.fn<(options?: { agent?: string | null }) => PresetInfo[]>(), listCustomPresets: vi.fn<(sandboxName: string) => PresetInfo[]>(), getAppliedPresets: vi.fn<(sandboxName: string) => string[]>(), getGatewayPresets: vi.fn<(sandboxName: string) => string[] | null>(), @@ -172,6 +172,33 @@ describe("listSandboxPolicies provenance", () => { expect(output).not.toMatch(/○ pypi \[/); }); + it("omits channel policy presets that are not available for the sandbox agent (#6185)", () => { + arrangeListing({ + appliedNames: [], + gatewayNames: [], + tier: "balanced", + agent: "langchain-deepagents-code", + }); + moduleMocks.listPresets.mockImplementation((options) => + options?.agent === "langchain-deepagents-code" + ? [ + { name: "npm", description: "npm and Yarn registry access" }, + { name: "pypi", description: "Python Package Index access" }, + ] + : POLICY_PRESETS, + ); + + listSandboxPolicies("test-sandbox"); + + expect(moduleMocks.listPresets).toHaveBeenCalledWith({ + agent: "langchain-deepagents-code", + }); + const output = printedText(); + expect(output).toContain("○ npm"); + expect(output).not.toContain("discord"); + expect(output).not.toContain("telegram"); + }); + it.each([ { agent: "hermes", diff --git a/src/lib/actions/sandbox/policy-channel-policy.test.ts b/src/lib/actions/sandbox/policy-channel-policy.test.ts index 4caebf8857f..0e4424a6d95 100644 --- a/src/lib/actions/sandbox/policy-channel-policy.test.ts +++ b/src/lib/actions/sandbox/policy-channel-policy.test.ts @@ -61,6 +61,7 @@ let getSandboxMock: MockInstance; let getAppliedPresetsMock: MockInstance; let selectFromListMock: MockInstance; let selectForRemovalMock: MockInstance; +let loadPresetForSandboxMock: MockInstance; let applyPresetMock: MockInstance; let removePresetMock: MockInstance; @@ -113,6 +114,12 @@ beforeEach(() => { const presetName = String(name); return `network_policies:\n ${presetName}:\n host: ${presetName}.example.com\n`; }); + loadPresetForSandboxMock = vi + .spyOn(policies, "loadPresetForSandbox") + .mockImplementation((_sandboxName: unknown, name: unknown) => { + const presetName = String(name); + return `network_policies:\n ${presetName}:\n host: ${presetName}.example.com\n`; + }); applyPresetMock = vi.spyOn(policies, "applyPreset").mockReturnValue(true); removePresetMock = vi.spyOn(policies, "removePreset").mockReturnValue(true); }); @@ -228,6 +235,30 @@ describe("addSandboxPolicy", () => { expect(applyPresetMock).not.toHaveBeenCalled(); }); + it("treats messaging channel policy presets unavailable to terminal-runtime agents as unknown before preview or prompt", async () => { + arrangeSandbox("langchain-deepagents-code"); + vi.spyOn(policies, "listPresets").mockReturnValue([ + { name: "npm", description: "npm and Yarn registry access" }, + { name: "pypi", description: "Python Package Index access" }, + { name: "tavily", description: "Tavily Search API access" }, + ]); + + await expect( + captureExit(() => addSandboxPolicy("test-sandbox", { preset: "telegram", yes: true })), + ).resolves.toBe(1); + + const output = printedText(); + expect(output).toContain("Unknown preset 'telegram'."); + expect(output).toContain("Valid presets: npm, pypi, tavily"); + expect(output).not.toContain("not supported for agent"); + expect(output).not.toContain("Channels supported by agent"); + expect(output).not.toContain("Preset not found"); + expect(output).not.toContain("Endpoints that would be opened"); + expect(promptMock).not.toHaveBeenCalled(); + expect(loadPresetForSandboxMock).not.toHaveBeenCalled(); + expect(applyPresetMock).not.toHaveBeenCalled(); + }); + it.each([ { preset: "telegram", diff --git a/src/lib/actions/sandbox/policy-channel-refresh.test.ts b/src/lib/actions/sandbox/policy-channel-refresh.test.ts index 9d2c1f6ed0a..e7705a04ec4 100644 --- a/src/lib/actions/sandbox/policy-channel-refresh.test.ts +++ b/src/lib/actions/sandbox/policy-channel-refresh.test.ts @@ -96,6 +96,10 @@ beforeEach(() => { vi.spyOn(policies, "loadPreset").mockImplementation((name: unknown) => { return `network_policies:\n ${String(name)}:\n host: ${String(name)}.example.com\n`; }); + vi.spyOn(policies, "loadPresetForSandbox").mockImplementation( + (_sandboxName: unknown, name: unknown) => + `network_policies:\n ${String(name)}:\n host: ${String(name)}.example.com\n`, + ); applyPresetMock = vi.spyOn(policies, "applyPreset").mockReturnValue(true); removePresetMock = vi.spyOn(policies, "removePreset").mockReturnValue(true); applyPresetContentMock = vi.spyOn(policies, "applyPresetContent").mockReturnValue(true); diff --git a/src/lib/actions/sandbox/policy-channel.ts b/src/lib/actions/sandbox/policy-channel.ts index ec9b8a9697c..39faa945ba2 100644 --- a/src/lib/actions/sandbox/policy-channel.ts +++ b/src/lib/actions/sandbox/policy-channel.ts @@ -4,7 +4,7 @@ import fs from "node:fs"; import path from "node:path"; -import type { AgentDefinition } from "../../agent/defs"; +import { type AgentDefinition, loadAgent } from "../../agent/defs"; import { CLI_DISPLAY_NAME, CLI_NAME } from "../../cli/branding"; import { prompt as askPrompt, getCredential } from "../../credentials/store"; import { recoverNamedGatewayRuntime } from "../../gateway-runtime-action"; @@ -18,7 +18,6 @@ import { getMessagingManifestAvailabilityContext, isMessagingChannelSupportedByAgent, isMessagingHookConflictError, - listMessagingPolicyPresetMetadata, MessagingHostStateApplier, MessagingSetupApplier, MessagingWorkflowPlanner, @@ -29,7 +28,6 @@ import { tryGetMessagingAgentId, } from "../../messaging"; import { hydrateMessagingChannelConfig } from "../../messaging-channel-config"; -import { resolveAgentForSandbox } from "../../sandbox/version"; import { hashCredential } from "../../security/credential-hash"; import { getSandboxTargetGatewayName } from "./gateway-target"; @@ -140,31 +138,15 @@ export async function addSandboxPolicy( } const sandboxAgent = registry.getSandbox(sandboxName)?.agent ?? null; - const agent = resolveAgentForSandbox(sandboxName); - const allPresets = filterSetupPolicyPresetsForAgent(policies.listPresets(), sandboxAgent).filter( - (preset: { name: string }) => { - const manifest = resolveChannelManifest(preset.name); - return !manifest || channelSupportedByAgent(manifest, agent); - }, + const allPresets = filterSetupPolicyPresetsForAgent( + policies.listPresets({ agent: sandboxAgent }), + sandboxAgent, ); const applied = policies.getAppliedPresets(sandboxName); let answer = null; if (presetArg) { const normalized = presetArg.trim().toLowerCase(); - const channelManifest = resolveChannelManifest(normalized); - if (channelManifest && !channelSupportedByAgent(channelManifest, agent)) { - console.error( - ` Channel '${channelManifest.id}' does not support agent '${agent.name}' for sandbox '${sandboxName}'.`, - ); - console.error( - ` Channel-supported agents: ${formatSupportedMessagingAgentIds(channelManifest.supportedAgents)}.`, - ); - console.error( - ` Channels supported by agent '${agent.name}': ${formatAvailableChannelsForAgent(agent)}.`, - ); - process.exit(1); - } const preset = allPresets.find((item: { name: string }) => item.name === normalized); if (!preset) { console.error(` Unknown preset '${presetArg}'.`); @@ -188,7 +170,7 @@ export async function addSandboxPolicy( } if (!answer) return; - const presetContent = policies.loadPreset(answer); + const presetContent = policies.loadPresetForSandbox(sandboxName, answer); if (!presetContent) return; const endpoints = policies.getPresetEndpoints(presetContent); @@ -243,21 +225,6 @@ async function applyExternalPreset( } if (!loaded) return false; - const agent = resolveAgentForSandbox(sandboxName); - const unsupportedChannel = unsupportedMessagingChannelForPresetContent(loaded.content, agent); - if (unsupportedChannel) { - console.error( - ` Preset '${loaded.presetName}' targets the '${unsupportedChannel.id}' channel, which does not support agent '${agent.name}' for sandbox '${sandboxName}'.`, - ); - console.error( - ` Channel-supported agents: ${formatSupportedMessagingAgentIds(unsupportedChannel.supportedAgents)}.`, - ); - console.error( - ` Channels supported by agent '${agent.name}': ${formatAvailableChannelsForAgent(agent)}.`, - ); - return false; - } - const endpoints = policies.getPresetEndpoints(loaded.content); if (endpoints.length > 0) { console.log(` [${loaded.presetName}] Endpoints that would be opened: ${endpoints.join(", ")}`); @@ -297,7 +264,8 @@ async function applyExternalPreset( } export function listSandboxPolicies(sandboxName: string) { - const builtin = policies.listPresets(); + const sandboxEntry = registry.getSandbox(sandboxName); + const builtin = policies.listPresets({ agent: sandboxEntry?.agent ?? null }); const custom = policies.listCustomPresets(sandboxName); const allPresets = [...builtin, ...custom]; const registryPresets = policies.getAppliedPresets(sandboxName); @@ -306,7 +274,6 @@ export function listSandboxPolicies(sandboxName: string) { // array of matched preset names when reachable (possibly empty). const gatewayPresets = policies.getGatewayPresets(sandboxName); - const sandboxEntry = registry.getSandbox(sandboxName); const provenanceContext = { tierName: sandboxEntry?.policyTier ?? null, agentName: sandboxEntry?.agent ?? null, @@ -347,6 +314,12 @@ export function listSandboxPolicies(sandboxName: string) { // ── Messaging channels ─────────────────────────────────────────── +function resolveAgentForSandbox(sandboxName: string): AgentDefinition { + const entry = registry.getSandbox(sandboxName); + const agentName = entry?.agent || "openclaw"; + return loadAgent(agentName); +} + function knownManifestChannelNames(): string[] { return messagingManifestRegistry.list().map((manifest) => manifest.id); } @@ -365,30 +338,6 @@ function channelSupportedByAgent(manifest: ChannelManifest, agent: AgentDefiniti return isMessagingChannelSupportedByAgent(manifest, agent); } -// Custom presets (--from-file / --from-dir) have no channel identity of -// their own, so the built-in name-based gate above cannot see them. Detect -// a messaging channel by content instead: match the preset's network_policies -// keys against every channel's known policy keys, then apply the same -// agent-support gate as the built-in path. -function unsupportedMessagingChannelForPresetContent( - content: string, - agent: AgentDefinition, -): ChannelManifest | null { - if (typeof content !== "string") return null; - const policyKeys = new Set(policies.parsePresetPolicyKeys(content)); - if (policyKeys.size === 0) return null; - for (const preset of listMessagingPolicyPresetMetadata()) { - const channelPolicyKeys = [ - ...preset.policyKeys, - ...Object.values(preset.agentPolicyKeys).flatMap((keys) => keys ?? []), - ]; - if (!channelPolicyKeys.some((key) => policyKeys.has(key))) continue; - const manifest = resolveChannelManifest(preset.channelId); - if (manifest && !channelSupportedByAgent(manifest, agent)) return manifest; - } - return null; -} - export function listSandboxChannels(sandboxName: string) { const agent = resolveAgentForSandbox(sandboxName); const availableChannels = availableManifestChannelsForAgent(agent); @@ -999,7 +948,7 @@ export async function addSandboxChannel( process.exit(1); } - const presetContent = policies.loadPreset(canonical); + const presetContent = policies.loadPresetForSandbox(sandboxName, canonical); const presetPolicyKeys = presetContent === null ? [] : policies.parsePresetPolicyKeys(presetContent); if (presetContent === null || presetPolicyKeys.length === 0) { @@ -1563,7 +1512,7 @@ export async function removeSandboxPolicy( // Resolve preset content: built-in first, then custom (persisted in // registry). Needed only for the endpoint preview below — removePreset() // itself re-resolves on the library side. - let presetContent: string | null = policies.loadPreset(answer); + let presetContent: string | null = policies.loadPresetForSandbox(sandboxName, answer); if (!presetContent) { const entry = customPresets.find((p: { name: string }) => p.name === answer); if (entry) { diff --git a/src/lib/messaging/AGENTS.md b/src/lib/messaging/AGENTS.md index a8f62ff3a7e..311fefcc749 100644 --- a/src/lib/messaging/AGENTS.md +++ b/src/lib/messaging/AGENTS.md @@ -54,7 +54,7 @@ Start with `channels//manifest.ts`. 3. Add hook implementations under `channels//hooks/` only for side effects or checks that cannot be represented as static manifest data. 4. Register hook handlers in the channel `hooks/index.ts` and in `hooks/builtins.ts`. 5. Add runtime preload assets under `channels//runtime/` only when the agent runtime needs boot/connect-time shims or diagnostics. -6. Add or update `nemoclaw-blueprint/policies/presets/.yaml` when the manifest declares a channel policy preset. +6. Add or update `src/lib/messaging/channels//policy/.yaml` when the manifest declares a channel policy preset. 7. Cover the behavior with manifest/compiler tests plus applier/onboard/channel CLI tests when host effects change. ## Where Changes Belong diff --git a/src/lib/messaging/README.md b/src/lib/messaging/README.md index 5d1954d6299..3675050e0cb 100644 --- a/src/lib/messaging/README.md +++ b/src/lib/messaging/README.md @@ -467,7 +467,7 @@ Add the channel through the manifest-first path. 5. Register template resolution in `channels/template-resolver.ts`. 6. Register hook handlers in `channels//hooks/index.ts` and `hooks/builtins.ts`. 7. Add runtime preload assets under `channels//runtime/` only when the agent runtime needs boot or connect-time shims. -8. Add `nemoclaw-blueprint/policies/presets/.yaml` when `policyPresets` declares a new policy preset. +8. Add `src/lib/messaging/channels//policy/.yaml` when `policyPresets` declares a new policy preset. 9. Add manifest, compiler, applier, lifecycle, build-applier, and policy tests for the behavior you changed. ## Invariants diff --git a/src/lib/messaging/channels/discord/policy/hermes.yaml b/src/lib/messaging/channels/discord/policy/hermes.yaml new file mode 100644 index 00000000000..6ade14673f2 --- /dev/null +++ b/src/lib/messaging/channels/discord/policy/hermes.yaml @@ -0,0 +1,57 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +preset: + name: discord + description: "Hermes Discord API, gateway, and CDN access" + +network_policies: + discord: + name: discord + endpoints: + - host: discord.com + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/**" } + - allow: { method: POST, path: "/**" } + - allow: { method: GET, path: "/gateway*" } + - allow: { method: GET, path: "/api/v*/gateway/bot" } + - allow: { method: GET, path: "/api/v*/applications/@me" } + - allow: { method: PUT, path: "/api/v*/applications/*/commands" } + - allow: { method: PUT, path: "/api/v*/channels/*/messages/*/reactions/*/@me" } + - allow: { method: PATCH, path: "/api/v*/applications/*" } + - allow: { method: PATCH, path: "/api/v*/applications/*/commands/*" } + - allow: { method: PATCH, path: "/api/v*/channels/*/messages/*" } + - allow: { method: PATCH, path: "/api/v*/webhooks/*/*/messages/*" } + - allow: { method: DELETE, path: "/api/v*/applications/*/commands/*" } + - allow: { method: DELETE, path: "/api/v*/channels/*/messages/*" } + - allow: { method: DELETE, path: "/api/v*/channels/*/messages/*/reactions/*/*" } + - allow: { method: DELETE, path: "/api/v*/webhooks/*/*/messages/*" } + - host: gateway.discord.gg + port: 443 + protocol: websocket + enforcement: enforce + websocket_credential_rewrite: true + rules: + - allow: { method: GET, path: "/**" } + - allow: { method: WEBSOCKET_TEXT, path: "/**" } + - host: "*.discord.gg" + port: 443 + protocol: websocket + enforcement: enforce + websocket_credential_rewrite: true + rules: + - allow: { method: GET, path: "/**" } + - allow: { method: WEBSOCKET_TEXT, path: "/**" } + - host: cdn.discordapp.com + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/**" } + binaries: + - { path: /usr/local/bin/node } + - { path: /usr/bin/python3* } + - { path: /opt/hermes/.venv/bin/python } diff --git a/nemoclaw-blueprint/policies/presets/discord.yaml b/src/lib/messaging/channels/discord/policy/openclaw.yaml similarity index 100% rename from nemoclaw-blueprint/policies/presets/discord.yaml rename to src/lib/messaging/channels/discord/policy/openclaw.yaml diff --git a/src/lib/messaging/channels/index.ts b/src/lib/messaging/channels/index.ts index 04823f39f2f..e5b6ccd6a33 100644 --- a/src/lib/messaging/channels/index.ts +++ b/src/lib/messaging/channels/index.ts @@ -3,5 +3,6 @@ export * from "./built-ins"; export * from "./metadata"; +export * from "./policy"; export * from "./rendered-config-parser"; export { createBuiltInRenderTemplateResolver } from "./template-resolver"; diff --git a/src/lib/messaging/channels/policy.test.ts b/src/lib/messaging/channels/policy.test.ts new file mode 100644 index 00000000000..eda57a434dc --- /dev/null +++ b/src/lib/messaging/channels/policy.test.ts @@ -0,0 +1,132 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; +import YAML from "yaml"; + +import { + listBuiltInMessagingChannelManifests, + listMessagingPolicyPresetMetadata, +} from "./metadata"; +import { + createMessagingChannelPolicyResolver, + listMessagingChannelPolicyPresets, + loadMessagingChannelPolicyPreset, + resolveMessagingChannelPolicyPresetPath, +} from "./policy"; + +type PolicyFixture = { + readonly channelId: string; + readonly presetName: string; +}; + +function fixtureContentFor( + file: string, + filesByChannel: Readonly>, +): string | null { + const normalized = file.replaceAll("\\", "/"); + return ( + Object.entries(filesByChannel).find(([channelId]) => + normalized.endsWith(`/src/lib/messaging/channels/${channelId}/policy/openclaw.yaml`), + )?.[1] ?? null + ); +} + +function createPolicyWithFixtures( + presets: readonly PolicyFixture[], + filesByChannel: Readonly> = {}, +): ReturnType { + return createMessagingChannelPolicyResolver({ + existsSync: (file) => fixtureContentFor(file, filesByChannel) !== null, + readFileSync: (file) => fixtureContentFor(file, filesByChannel) ?? "", + listPresetMetadata: () => presets, + }); +} + +function policyKeys(content: string | null): string[] { + expect(content).toBeTruthy(); + const parsed = YAML.parse(content ?? ""); + return Object.keys(parsed?.network_policies ?? {}); +} + +describe("messaging channel policy presets", () => { + it("loads OpenClaw and Hermes channel-specific Telegram policy keys", () => { + expect(policyKeys(loadMessagingChannelPolicyPreset("telegram", { agent: "openclaw" }))).toEqual( + ["telegram_bot"], + ); + expect(policyKeys(loadMessagingChannelPolicyPreset("telegram", { agent: "hermes" }))).toEqual([ + "telegram", + ]); + }); + + it("lists operator-facing preset names from channel-owned policy files", () => { + const presets = listMessagingChannelPolicyPresets(); + expect(presets.map((preset) => preset.name).sort()).toEqual([ + "discord", + "slack", + "teams", + "telegram", + "wechat", + "whatsapp", + ]); + expect(presets.find((preset) => preset.name === "slack")?.file).toBe( + "src/lib/messaging/channels/slack/policy/openclaw.yaml", + ); + }); + + it("does not fall back to OpenClaw policies for unsupported agents", () => { + expect( + loadMessagingChannelPolicyPreset("telegram", { agent: "langchain-deepagents-code" }), + ).toBeNull(); + expect( + resolveMessagingChannelPolicyPresetPath("telegram", "langchain-deepagents-code"), + ).toBeNull(); + expect(listMessagingChannelPolicyPresets({ agent: "langchain-deepagents-code" })).toEqual([]); + }); + + it("returns null for unknown channel policy presets", () => { + expect(loadMessagingChannelPolicyPreset("nonexistent", { agent: "hermes" })).toBeNull(); + expect(resolveMessagingChannelPolicyPresetPath("nonexistent", "hermes")).toBeNull(); + }); + + it("rejects path traversal channel ids from preset metadata", () => { + const policy = createPolicyWithFixtures([{ channelId: "../telegram", presetName: "telegram" }]); + expect(policy.resolveMessagingChannelPolicyPresetPath("telegram")).toBeNull(); + expect(policy.loadMessagingChannelPolicyPreset("telegram")).toBeNull(); + }); + + it("returns null when channel policy files are missing", () => { + const policy = createPolicyWithFixtures([{ channelId: "missing", presetName: "slack" }]); + expect(policy.resolveMessagingChannelPolicyPresetPath("slack")).toBeNull(); + expect(policy.loadMessagingChannelPolicyPreset("slack")).toBeNull(); + }); + + it("skips channel policy files whose preset header has the wrong name", () => { + const policy = createPolicyWithFixtures([{ channelId: "slack", presetName: "slack" }], { + slack: "preset:\n name: discord\nnetwork_policies:\n discord: {}\n", + }); + expect(policy.loadMessagingChannelPolicyPreset("slack")).toBeNull(); + expect(policy.listMessagingChannelPolicyPresets()).toEqual([]); + }); + + it("returns null for malformed channel policy YAML", () => { + const policy = createPolicyWithFixtures([{ channelId: "slack", presetName: "slack" }], { + slack: "preset:\n name: [\nnetwork_policies:\n slack: {}\n", + }); + expect(policy.loadMessagingChannelPolicyPreset("slack")).toBeNull(); + expect(policy.listMessagingChannelPolicyPresets()).toEqual([]); + }); + + it("ships a policy file for every manifest-supported agent and preset", () => { + const missing = listBuiltInMessagingChannelManifests().flatMap((manifest) => + manifest.supportedAgents.flatMap((agent) => + listMessagingPolicyPresetMetadata({ manifests: [manifest], agent }).flatMap((preset) => + resolveMessagingChannelPolicyPresetPath(preset.presetName, agent) + ? [] + : [`${manifest.id}/${agent}/${preset.presetName}`], + ), + ), + ); + expect(missing).toEqual([]); + }); +}); diff --git a/src/lib/messaging/channels/policy.ts b/src/lib/messaging/channels/policy.ts new file mode 100644 index 00000000000..8705378b8db --- /dev/null +++ b/src/lib/messaging/channels/policy.ts @@ -0,0 +1,188 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; +import YAML from "yaml"; + +import { ROOT } from "../../state/paths"; +import type { MessagingAgentId } from "../manifest"; +import { listMessagingPolicyPresetMetadata } from "./metadata"; + +type PolicyPresetLocator = { + readonly channelId: string; + readonly presetName: string; +}; + +type PolicyPresetMetadataReader = (options: { + readonly agent?: MessagingAgentId; +}) => readonly PolicyPresetLocator[]; + +const CHANNELS_ROOT = path.join(ROOT, "src", "lib", "messaging", "channels"); +const POLICY_FILE_BY_AGENT: Readonly> = { + openclaw: "openclaw.yaml", + hermes: "hermes.yaml", +}; + +export interface MessagingChannelPolicyPresetInfo { + readonly file: string; + readonly name: string; + readonly description: string; + readonly channelId: string; + readonly agent: MessagingAgentId; +} + +export interface MessagingChannelPolicyResolver { + readonly resolveMessagingChannelPolicyPresetPath: ( + presetName: string, + agent?: MessagingAgentId | string | null | undefined, + ) => string | null; + readonly loadMessagingChannelPolicyPreset: ( + presetName: string, + options?: { readonly agent?: MessagingAgentId | string | null }, + ) => string | null; + readonly listMessagingChannelPolicyPresets: (options?: { + readonly agent?: MessagingAgentId | string | null; + }) => MessagingChannelPolicyPresetInfo[]; +} + +export interface MessagingChannelPolicyResolverDeps { + readonly existsSync: (file: string) => boolean; + readonly readFileSync: (file: string, encoding: BufferEncoding) => string; + readonly listPresetMetadata: PolicyPresetMetadataReader; +} + +function normalizeAgent( + agent: MessagingAgentId | string | null | undefined, +): MessagingAgentId | null { + if (agent == null) return "openclaw"; + if (agent === "openclaw" || agent === "hermes") return agent; + return null; +} + +function isSafeId(value: string): boolean { + return /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(value); +} + +function channelPolicyPath(channelId: string, agent: MessagingAgentId): string | null { + if (!isSafeId(channelId)) return null; + return path.join(CHANNELS_ROOT, channelId, "policy", POLICY_FILE_BY_AGENT[agent]); +} + +function readPresetHeader(content: string): { name: string; description: string } | null { + let parsed: { preset?: unknown } | null; + try { + parsed = YAML.parse(content); + } catch { + return null; + } + const preset = parsed?.preset; + if (!preset || typeof preset !== "object" || Array.isArray(preset)) return null; + const fields = preset as Record; + const name = fields.name; + if (typeof name !== "string" || name.trim().length === 0) return null; + const description = typeof fields.description === "string" ? fields.description.trim() : ""; + return { name: name.trim(), description }; +} + +function readChannelPolicyInfo( + channelId: string, + expectedPresetName: string, + agent: MessagingAgentId, + deps: MessagingChannelPolicyResolverDeps, +): MessagingChannelPolicyPresetInfo | null { + const file = channelPolicyPath(channelId, agent); + if (!file || !deps.existsSync(file)) return null; + const content = deps.readFileSync(file, "utf-8"); + const header = readPresetHeader(content); + if (!header || header.name !== expectedPresetName) return null; + return { + file: path.relative(ROOT, file).replaceAll(path.sep, "/"), + name: header.name, + description: header.description, + channelId, + agent, + }; +} + +export function createMessagingChannelPolicyResolver( + deps: MessagingChannelPolicyResolverDeps, +): MessagingChannelPolicyResolver { + function resolveMessagingChannelPolicyPresetPath( + presetName: string, + agent: MessagingAgentId | string | null | undefined = "openclaw", + ): string | null { + const normalizedAgent = normalizeAgent(agent); + if (!normalizedAgent) return null; + for (const preset of deps.listPresetMetadata({ agent: normalizedAgent })) { + if (preset.presetName !== presetName) continue; + const file = channelPolicyPath(preset.channelId, normalizedAgent); + if (file && deps.existsSync(file)) return file; + } + return null; + } + + function loadMessagingChannelPolicyPreset( + presetName: string, + options: { readonly agent?: MessagingAgentId | string | null } = {}, + ): string | null { + const file = resolveMessagingChannelPolicyPresetPath(presetName, options.agent); + if (!file) return null; + const content = deps.readFileSync(file, "utf-8"); + const header = readPresetHeader(content); + return header?.name === presetName ? content : null; + } + + function listMessagingChannelPolicyPresets( + options: { readonly agent?: MessagingAgentId | string | null } = {}, + ): MessagingChannelPolicyPresetInfo[] { + const agent = normalizeAgent(options.agent); + if (!agent) return []; + const result: MessagingChannelPolicyPresetInfo[] = []; + const seen = new Set(); + for (const preset of deps.listPresetMetadata({ agent })) { + if (seen.has(preset.presetName)) continue; + const info = readChannelPolicyInfo(preset.channelId, preset.presetName, agent, deps); + if (!info) continue; + result.push(info); + seen.add(preset.presetName); + } + return result; + } + + return { + listMessagingChannelPolicyPresets, + loadMessagingChannelPolicyPreset, + resolveMessagingChannelPolicyPresetPath, + }; +} + +const defaultPolicyResolver = createMessagingChannelPolicyResolver({ + existsSync: (file) => fs.existsSync(file), + readFileSync: (file, encoding) => fs.readFileSync(file, encoding), + listPresetMetadata: listMessagingPolicyPresetMetadata, +}); + +export function resolveMessagingChannelPolicyPresetPath( + presetName: string, + agent: MessagingAgentId | string | null | undefined = "openclaw", +): string | null { + return defaultPolicyResolver.resolveMessagingChannelPolicyPresetPath(presetName, agent); +} + +export function loadMessagingChannelPolicyPreset( + presetName: string, + options: { readonly agent?: MessagingAgentId | string | null } = {}, +): string | null { + return defaultPolicyResolver.loadMessagingChannelPolicyPreset(presetName, options); +} + +export function listMessagingChannelPolicyPresets( + options: { readonly agent?: MessagingAgentId | string | null } = {}, +): MessagingChannelPolicyPresetInfo[] { + return defaultPolicyResolver.listMessagingChannelPolicyPresets(options); +} + +export function isMessagingChannelPolicyPreset(presetName: string): boolean { + return listMessagingPolicyPresetMetadata().some((preset) => preset.presetName === presetName); +} diff --git a/src/lib/messaging/channels/slack/policy/hermes.yaml b/src/lib/messaging/channels/slack/policy/hermes.yaml new file mode 100644 index 00000000000..a026778e700 --- /dev/null +++ b/src/lib/messaging/channels/slack/policy/hermes.yaml @@ -0,0 +1,55 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +preset: + name: slack + description: "Hermes Slack API, Socket Mode, and webhooks access" + +network_policies: + slack: + name: slack + endpoints: + - host: slack.com + port: 443 + protocol: rest + enforcement: enforce + request_body_credential_rewrite: true + rules: + - allow: { method: GET, path: "/**" } + - allow: { method: POST, path: "/**" } + - host: api.slack.com + port: 443 + protocol: rest + enforcement: enforce + request_body_credential_rewrite: true + rules: + - allow: { method: GET, path: "/**" } + - allow: { method: POST, path: "/**" } + - host: hooks.slack.com + port: 443 + protocol: rest + enforcement: enforce + request_body_credential_rewrite: true + rules: + - allow: { method: GET, path: "/**" } + - allow: { method: POST, path: "/**" } + - host: wss-primary.slack.com + port: 443 + protocol: websocket + enforcement: enforce + websocket_credential_rewrite: true + rules: + - allow: { method: GET, path: "/**" } + - allow: { method: WEBSOCKET_TEXT, path: "/**" } + - host: wss-backup.slack.com + port: 443 + protocol: websocket + enforcement: enforce + websocket_credential_rewrite: true + rules: + - allow: { method: GET, path: "/**" } + - allow: { method: WEBSOCKET_TEXT, path: "/**" } + binaries: + - { path: /usr/local/bin/hermes } + - { path: /usr/bin/python3* } + - { path: /opt/hermes/.venv/bin/python } diff --git a/nemoclaw-blueprint/policies/presets/slack.yaml b/src/lib/messaging/channels/slack/policy/openclaw.yaml similarity index 100% rename from nemoclaw-blueprint/policies/presets/slack.yaml rename to src/lib/messaging/channels/slack/policy/openclaw.yaml diff --git a/src/lib/messaging/channels/teams/policy/hermes.yaml b/src/lib/messaging/channels/teams/policy/hermes.yaml new file mode 100644 index 00000000000..e476c21371e --- /dev/null +++ b/src/lib/messaging/channels/teams/policy/hermes.yaml @@ -0,0 +1,86 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +preset: + name: teams + description: "Hermes Microsoft Teams Bot Framework and Graph API access" + +network_policies: + teams: + name: teams + endpoints: + - host: login.microsoftonline.com + port: 443 + protocol: rest + enforcement: enforce + request_body_credential_rewrite: true + rules: + - allow: { method: GET, path: "/**" } + - allow: { method: POST, path: "/**" } + - host: login.botframework.com + port: 443 + protocol: rest + enforcement: enforce + request_body_credential_rewrite: true + rules: + - allow: { method: GET, path: "/**" } + - allow: { method: POST, path: "/**" } + - host: api.botframework.com + port: 443 + protocol: rest + enforcement: enforce + request_body_credential_rewrite: true + rules: + - allow: { method: GET, path: "/**" } + - allow: { method: POST, path: "/**" } + - host: smba.trafficmanager.net + port: 443 + protocol: rest + enforcement: enforce + request_body_credential_rewrite: true + rules: + - allow: { method: GET, path: "/**" } + - allow: { method: POST, path: "/**" } + - allow: { method: PUT, path: "/**" } + - allow: { method: DELETE, path: "/**" } + - host: graph.microsoft.com + port: 443 + protocol: rest + enforcement: enforce + request_body_credential_rewrite: true + rules: + - allow: { method: GET, path: "/**" } + - host: teams.microsoft.com + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/**" } + - host: teams.cdn.office.net + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/**" } + - host: statics.teams.cdn.office.net + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/**" } + - host: "*.sharepoint.com" + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/**" } + - host: 1drv.ms + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/**" } + binaries: + - { path: /usr/local/bin/hermes } + - { path: /usr/bin/python3* } + - { path: /opt/hermes/.venv/bin/python } diff --git a/nemoclaw-blueprint/policies/presets/teams.yaml b/src/lib/messaging/channels/teams/policy/openclaw.yaml similarity index 100% rename from nemoclaw-blueprint/policies/presets/teams.yaml rename to src/lib/messaging/channels/teams/policy/openclaw.yaml diff --git a/src/lib/messaging/channels/telegram/policy/hermes.yaml b/src/lib/messaging/channels/telegram/policy/hermes.yaml new file mode 100644 index 00000000000..823d6ea4a1e --- /dev/null +++ b/src/lib/messaging/channels/telegram/policy/hermes.yaml @@ -0,0 +1,23 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +preset: + name: telegram + description: "Hermes Telegram Bot API access" + +network_policies: + telegram: + name: telegram + endpoints: + - host: api.telegram.org + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/bot*/**" } + - allow: { method: POST, path: "/bot*/**" } + - allow: { method: GET, path: "/file/bot*/**" } + binaries: + - { path: /usr/local/bin/node } + - { path: /usr/bin/python3* } + - { path: /opt/hermes/.venv/bin/python } diff --git a/nemoclaw-blueprint/policies/presets/telegram.yaml b/src/lib/messaging/channels/telegram/policy/openclaw.yaml similarity index 100% rename from nemoclaw-blueprint/policies/presets/telegram.yaml rename to src/lib/messaging/channels/telegram/policy/openclaw.yaml diff --git a/src/lib/messaging/channels/wechat/policy/hermes.yaml b/src/lib/messaging/channels/wechat/policy/hermes.yaml new file mode 100644 index 00000000000..d4069e750e5 --- /dev/null +++ b/src/lib/messaging/channels/wechat/policy/hermes.yaml @@ -0,0 +1,29 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +preset: + name: wechat + description: "Hermes WeChat (personal) iLink API access" + +network_policies: + wechat_bridge: + name: wechat_bridge + endpoints: + - host: ilinkai.weixin.qq.com + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/**" } + - allow: { method: POST, path: "/**" } + - host: ilinkai.wechat.com + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/**" } + - allow: { method: POST, path: "/**" } + binaries: + - { path: /usr/local/bin/hermes } + - { path: /usr/bin/python3* } + - { path: /opt/hermes/.venv/bin/python } diff --git a/nemoclaw-blueprint/policies/presets/wechat.yaml b/src/lib/messaging/channels/wechat/policy/openclaw.yaml similarity index 100% rename from nemoclaw-blueprint/policies/presets/wechat.yaml rename to src/lib/messaging/channels/wechat/policy/openclaw.yaml diff --git a/nemoclaw-blueprint/policies/presets/whatsapp.yaml b/src/lib/messaging/channels/whatsapp/policy/hermes.yaml similarity index 100% rename from nemoclaw-blueprint/policies/presets/whatsapp.yaml rename to src/lib/messaging/channels/whatsapp/policy/hermes.yaml diff --git a/src/lib/messaging/channels/whatsapp/policy/openclaw.yaml b/src/lib/messaging/channels/whatsapp/policy/openclaw.yaml new file mode 100644 index 00000000000..9119a926778 --- /dev/null +++ b/src/lib/messaging/channels/whatsapp/policy/openclaw.yaml @@ -0,0 +1,69 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +preset: + name: whatsapp + description: "WhatsApp Web WebSocket and media access" +network_policies: + whatsapp: + name: whatsapp + endpoints: + # WhatsApp Web Noise-over-WebSocket. The /ws/chat upgrade requires + # HTTP/1.1; OpenShell's proxy negotiates h2 ALPN by default when it + # terminates TLS, and Meta's edge returns HTTP/2 405/400 because + # there is no 101 Switching Protocols flow over h2. OpenShell + # v0.0.15+ also auto-terminates TLS unconditionally on REST hosts, + # which would break the Noise handshake even if h1 were negotiated. + # Declaring the endpoint as a raw L4 CONNECT tunnel (`access: full, + # tls: skip`) tells the proxy to pass the encrypted bytes through + # unmodified, so Baileys negotiates h1 ALPN directly with Meta + # inside TLS and the Noise frames survive untouched. Falls back to + # numbered nodes (w1.web.whatsapp.com, w2.web.whatsapp.com, ...) + # when the primary connection drops; the wildcard covers them with + # the same shape. + - host: web.whatsapp.com + port: 443 + access: full + tls: skip + - host: "*.web.whatsapp.com" + port: 443 + access: full + tls: skip + # Baileys hits a handful of *.whatsapp.net subdomains during pairing + # and steady-state: mmg (media gateway), static (location maps and + # other static assets), cdn (CDN), pps (profile pictures), v + # (variants), e1/f/s (encrypted/file/signal media routes). All are + # Meta-controlled, so a wildcard keeps the preset future-proof without + # expanding trust beyond WhatsApp infrastructure. Follows the + # `*.atlassian.net` precedent in the jira preset. The apex is listed + # separately because OpenShell's wildcard matcher does not cover it. + - host: whatsapp.net + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/**" } + - allow: { method: POST, path: "/**" } + - host: "*.whatsapp.net" + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: { method: GET, path: "/**" } + - allow: { method: POST, path: "/**" } + # Baileys calls `fetchLatestBaileysVersion()` at session creation, + # fetching the current WhatsApp Web protocol version from the + # WhiskeySockets/Baileys master branch. Without this rule the fetch + # fails closed and Baileys advertises its bundled (stale) constant, + # which Meta now rejects with `` on pair. + # Scope is pinned to the single file the fetch reads, GET only. + - host: raw.githubusercontent.com + port: 443 + protocol: rest + enforcement: enforce + rules: + - allow: + method: GET + path: "/WhiskeySockets/Baileys/master/src/Defaults/index.ts" + binaries: + - { path: /usr/local/bin/node } + - { path: /usr/bin/node } diff --git a/src/lib/onboard/initial-policy-real-policy.test.ts b/src/lib/onboard/initial-policy-real-policy.test.ts new file mode 100644 index 00000000000..0b39eacfc22 --- /dev/null +++ b/src/lib/onboard/initial-policy-real-policy.test.ts @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; +import YAML from "yaml"; + +import { prepareInitialSandboxCreatePolicy } from "./initial-policy"; + +type PolicyRule = { + allow?: { + method?: string; + path?: string; + }; +}; + +type PolicyEndpoint = { + host?: string; + rules?: PolicyRule[]; +}; + +type PolicyEntry = { + binaries?: Array<{ path?: string }>; + endpoints?: PolicyEndpoint[]; +}; + +type PolicyDocument = { + network_policies?: Record; +}; + +const cleanupFns: Array<() => boolean | undefined> = []; + +afterEach(() => { + for (const cleanup of cleanupFns.splice(0)) { + cleanup(); + } +}); + +function repoPath(...segments: string[]): string { + return path.join(import.meta.dirname, "..", "..", "..", ...segments); +} + +function readPreparedPolicy(prepared: { + policyPath: string; + cleanup?: () => boolean; +}): PolicyDocument { + cleanupFns.push(() => prepared.cleanup?.()); + return YAML.parse(fs.readFileSync(prepared.policyPath, "utf-8")) as PolicyDocument; +} + +describe("initial sandbox policy real preset merge", () => { + it("uses Hermes channel YAML when the Hermes base policy path implies the agent", () => { + const prepared = prepareInitialSandboxCreatePolicy( + repoPath("agents", "hermes", "policy-additions.yaml"), + ["discord", "slack"], + ); + const policy = readPreparedPolicy(prepared); + + expect(prepared.appliedPresets).toEqual(["discord", "slack"]); + + const slackBinaries = + policy.network_policies?.slack?.binaries?.map((binary) => binary.path) ?? []; + expect(slackBinaries).toEqual([ + "/usr/local/bin/hermes", + "/usr/bin/python3*", + "/opt/hermes/.venv/bin/python", + ]); + + const discordBinaries = + policy.network_policies?.discord?.binaries?.map((binary) => binary.path) ?? []; + expect(discordBinaries).toContain("/usr/bin/python3*"); + expect(discordBinaries).toContain("/opt/hermes/.venv/bin/python"); + expect(discordBinaries).not.toContain("/usr/bin/node"); + + const discordRules = + policy.network_policies?.discord?.endpoints + ?.find((endpoint) => endpoint.host === "discord.com") + ?.rules?.map((rule) => rule.allow) ?? []; + expect(discordRules).not.toContainEqual({ method: "PUT", path: "/**" }); + expect(discordRules).not.toContainEqual({ method: "PATCH", path: "/**" }); + }); +}); diff --git a/src/lib/onboard/initial-policy.test.ts b/src/lib/onboard/initial-policy.test.ts index 0135c254ff0..1567aa363b2 100644 --- a/src/lib/onboard/initial-policy.test.ts +++ b/src/lib/onboard/initial-policy.test.ts @@ -10,7 +10,9 @@ import YAML from "yaml"; vi.mock("../policy", () => ({ mergePresetNamesIntoPolicy: (policy: string, presetNames: string[]) => ({ - policy: `${policy.trimEnd()}\n slack: {}\n`, + policy: `${policy.trimEnd()}\n${presetNames + .map((preset) => ` ${preset === "wechat" ? "wechat_bridge" : preset}: {}`) + .join("\n")}\n`, appliedPresets: presetNames, missingPresets: [], }), diff --git a/src/lib/onboard/initial-policy.ts b/src/lib/onboard/initial-policy.ts index fe66d74dd94..8ddfda55554 100644 --- a/src/lib/onboard/initial-policy.ts +++ b/src/lib/onboard/initial-policy.ts @@ -7,7 +7,10 @@ import YAML from "yaml"; import { getMessagingPolicyKeysByChannel } from "../messaging/channels"; import * as policies from "../policy"; -import { requiredMessagingChannelPolicyPresets } from "./messaging-policy-presets"; +import { + allMessagingChannelPolicyPresets, + requiredMessagingChannelPolicyPresets, +} from "./messaging-policy-presets"; import { requiredOpenclawOtelPolicyPresets } from "./openclaw-otel-policy-presets"; import { filterSuppressedAgentRequiredPresets } from "./policy-tier-suppression"; import { cleanupTempDir, secureTempFile } from "./temp-files"; @@ -228,10 +231,16 @@ export function prepareInitialSandboxCreatePolicy( tierKnown && options.policyTier !== "restricted" ? requiredOpenclawOtelPolicyPresets(options.agentName ?? "openclaw") : []; + const isHermesPolicyFromPath = isHermesPolicyPath(basePolicyPath); + const isHermesPolicy = options.agentName === "hermes" || isHermesPolicyFromPath; + const policyAgent = options.agentName ?? (isHermesPolicyFromPath ? "hermes" : null); + const messagingCreateTimePresets = isHermesPolicy + ? allMessagingChannelPolicyPresets(activeMessagingChannels) + : requiredMessagingChannelPolicyPresets(activeMessagingChannels); const requestedCreateTimePresets = filterSuppressedAgentRequiredPresets( [ ...new Set([ - ...requiredMessagingChannelPolicyPresets(activeMessagingChannels), + ...messagingCreateTimePresets, ...otelCreateTimePresets, ...(options.additionalPresets || []), ]), @@ -242,7 +251,7 @@ export function prepareInitialSandboxCreatePolicy( const dedupe = (values: string[]) => [...new Set(values.filter(Boolean))]; let basePolicy = fs.readFileSync(effectiveBasePolicyPath, "utf-8"); - if (options.agentName === "hermes" || isHermesPolicyPath(basePolicyPath)) { + if (isHermesPolicy) { const filtered = filterHermesInactiveMessagingPolicies(basePolicy, activeMessagingChannels); if (filtered.changed) { const policyPath = secureTempFile("nemoclaw-agent-policy", ".yaml"); @@ -294,7 +303,9 @@ export function prepareInitialSandboxCreatePolicy( }; } - const mergedPolicy = policies.mergePresetNamesIntoPolicy(basePolicy, createTimePresets); + const mergedPolicy = policies.mergePresetNamesIntoPolicy(basePolicy, createTimePresets, { + agent: policyAgent, + }); if (mergedPolicy.missingPresets.length > 0) { throw new Error( `Cannot prepare sandbox create policy; missing policy preset(s): ${mergedPolicy.missingPresets.join(", ")}`, diff --git a/src/lib/onboard/policy-resume-selection.ts b/src/lib/onboard/policy-resume-selection.ts index d87fe916ae7..8a184effcbf 100644 --- a/src/lib/onboard/policy-resume-selection.ts +++ b/src/lib/onboard/policy-resume-selection.ts @@ -23,11 +23,11 @@ type Preset = { name: string; access?: string }; type PoliciesApi = { setupPolicyPresetSupported( name: string, - options?: { webSearchSupported?: boolean | null }, + options?: { webSearchSupported?: boolean | null; agent?: string | null }, ): boolean; listSetupPolicyPresets( sandboxName: string, - options?: { webSearchSupported?: boolean | null }, + options?: { webSearchSupported?: boolean | null; agent?: string | null }, ): Preset[]; listCustomPresets(sandboxName: string): Preset[]; getAppliedPresets(sandboxName: string): string[]; @@ -54,7 +54,7 @@ export function preparePolicyPresetResumeSelection( tierName?: string | null; }, ): PreparedPolicyResumeSelection { - const supportOptions = { webSearchSupported: options.webSearchSupported }; + const supportOptions = { webSearchSupported: options.webSearchSupported, agent: options.agent }; const appliedPolicyPresets = deps.policies.getAppliedPresets(sandboxName); const selectablePolicyPresets = [ ...filterSetupPolicyPresetsForAgent( diff --git a/src/lib/onboard/policy-selection.ts b/src/lib/onboard/policy-selection.ts index 804a4723577..e72f1fe67ca 100644 --- a/src/lib/onboard/policy-selection.ts +++ b/src/lib/onboard/policy-selection.ts @@ -30,7 +30,7 @@ import { withPolicyApplicationTrace } from "./tracing"; export { suppressedAgentRequiredPresets } from "./policy-tier-suppression"; type Preset = { name: string; access?: string }; -type SupportOptions = { webSearchSupported?: boolean | null }; +type SupportOptions = { webSearchSupported?: boolean | null; agent?: string | null }; type PoliciesApi = { setupPolicyPresetSupported(name: string, options?: SupportOptions): boolean; listSetupPolicyPresets(sandboxName: string, options?: SupportOptions): Preset[]; @@ -234,7 +234,7 @@ async function setupPoliciesWithSelectionInner( deps.step(8, 8, "Policy presets"); - const supportOptions = { webSearchSupported: options.webSearchSupported }; + const supportOptions = { webSearchSupported: options.webSearchSupported, agent }; const allPresets = filterSetupPolicyPresetsForAgent( deps.policies.listSetupPolicyPresets(sandboxName, supportOptions), agent, diff --git a/src/lib/policy/context.test.ts b/src/lib/policy/context.test.ts index 6223f539309..dfab4b8fde9 100644 --- a/src/lib/policy/context.test.ts +++ b/src/lib/policy/context.test.ts @@ -14,6 +14,7 @@ vi.mock(".", () => ({ listCustomPresets: vi.fn(), listPresets: vi.fn(), loadPreset: vi.fn(), + loadPresetForSandbox: vi.fn(), })); vi.mock("./tiers", () => ({ @@ -58,6 +59,9 @@ function mockBuiltinPresets() { ]); vi.mocked(policies.listCustomPresets).mockReturnValue([]); vi.mocked(policies.loadPreset).mockImplementation((name: string) => PRESET_CONTENT[name] ?? null); + vi.mocked(policies.loadPresetForSandbox).mockImplementation( + (_sandboxName: string, name: string) => PRESET_CONTENT[name] ?? null, + ); vi.mocked(policies.getPresetEndpoints).mockImplementation((content: string) => { const hosts: string[] = []; const regex = /host:\s*(\S+)/g; @@ -93,6 +97,7 @@ function resetMocks() { vi.mocked(policies.listPresets).mockReset(); vi.mocked(policies.listCustomPresets).mockReset(); vi.mocked(policies.loadPreset).mockReset(); + vi.mocked(policies.loadPresetForSandbox).mockReset(); vi.mocked(policies.getPresetEndpoints).mockReset(); vi.mocked(policies.getGatewayPresets).mockReset(); vi.mocked(policies.getGatewayPresets).mockReturnValue(null); diff --git a/src/lib/policy/context.ts b/src/lib/policy/context.ts index 86fd2827342..6ccc0776954 100644 --- a/src/lib/policy/context.ts +++ b/src/lib/policy/context.ts @@ -7,7 +7,7 @@ import { getPresetEndpoints, listCustomPresets, listPresets, - loadPreset, + loadPresetForSandbox, } from "."; import { hostStemsFromEndpoints } from "./host-redaction"; import { getTier } from "./tiers"; @@ -146,7 +146,12 @@ function partitionPresets( const isApplied = applied.has(info.name); const verification = resolveVerification(info.name, isApplied, gatewayPresets); const onGatewayOnly = !isApplied && verification === "gateway-only"; - const entry = presetEntry(info, "builtin", loadPreset(info.name), verification); + const entry = presetEntry( + info, + "builtin", + loadPresetForSandbox(sandboxName, info.name), + verification, + ); if (isApplied || onGatewayOnly) { active.push(entry); } else { diff --git a/src/lib/policy/failure-classifier.test.ts b/src/lib/policy/failure-classifier.test.ts index d197571dd70..ea150670652 100644 --- a/src/lib/policy/failure-classifier.test.ts +++ b/src/lib/policy/failure-classifier.test.ts @@ -14,6 +14,7 @@ vi.mock(".", () => ({ listCustomPresets: vi.fn(), listPresets: vi.fn(), loadPreset: vi.fn(), + loadPresetForSandbox: vi.fn(), })); vi.mock("./tiers", () => ({ @@ -58,6 +59,9 @@ function mockBuiltinPresets() { ]); vi.mocked(policies.listCustomPresets).mockReturnValue([]); vi.mocked(policies.loadPreset).mockImplementation((name: string) => PRESET_CONTENT[name] ?? null); + vi.mocked(policies.loadPresetForSandbox).mockImplementation( + (_sandboxName: string, name: string) => PRESET_CONTENT[name] ?? null, + ); vi.mocked(policies.getPresetEndpoints).mockImplementation((content: string) => { const hosts: string[] = []; const regex = /host:\s*(\S+)/g; @@ -93,6 +97,7 @@ function resetMocks() { vi.mocked(policies.listPresets).mockReset(); vi.mocked(policies.listCustomPresets).mockReset(); vi.mocked(policies.loadPreset).mockReset(); + vi.mocked(policies.loadPresetForSandbox).mockReset(); vi.mocked(policies.getPresetEndpoints).mockReset(); vi.mocked(policies.getGatewayPresets).mockReset(); vi.mocked(policies.getGatewayPresets).mockReturnValue(null); diff --git a/src/lib/policy/index.ts b/src/lib/policy/index.ts index 3602cd746a9..42c4a80b08e 100644 --- a/src/lib/policy/index.ts +++ b/src/lib/policy/index.ts @@ -7,8 +7,11 @@ import type { JsonObject, JsonValue } from "../core/json-types"; import { getMessagingPolicyKeyAliases, getMessagingPolicyPresetValidationWarnings, + isMessagingChannelPolicyPreset, listBuiltInMessagingChannelManifests, + listMessagingChannelPolicyPresets, listMessagingPolicyPresetMetadata, + loadMessagingChannelPolicyPreset, } from "../messaging/channels"; import { buildPolicyGetCommand, @@ -56,8 +59,21 @@ type SelectionOptions = { applied?: string[]; }; +type PresetLoadOptions = { + agent?: string | null; +}; + +type PresetListOptions = { + agent?: string | null; +}; + +type MergePresetNamesOptions = { + agent?: string | null; +}; + type SetupPolicyPresetSupportOptions = { webSearchSupported?: boolean | null; + agent?: string | null; }; function isPolicyDocument(value: PolicyValue): value is PolicyDocument { @@ -65,13 +81,22 @@ function isPolicyDocument(value: PolicyValue): value is PolicyDocument { } /** - * Enumerate every preset YAML under `nemoclaw-blueprint/policies/presets/` - * and return `{ file, name, description }` triples parsed from the file's - * `preset:` header. + * Enumerate every built-in preset and return `{ file, name, description }` + * triples parsed from each file's `preset:` header. Non-messaging presets live + * under `nemoclaw-blueprint/policies/presets/`; messaging channel presets live + * beside their channel manifests under `src/lib/messaging/channels//policy/`. */ -function listPresets(): PresetInfo[] { - if (!fs.existsSync(PRESETS_DIR)) return []; - return fs +function listPresets(options: PresetListOptions = {}): PresetInfo[] { + const channelPresets = listMessagingChannelPolicyPresets({ agent: options.agent }).map( + ({ file, name, description }) => ({ + file, + name, + description, + }), + ); + const channelPresetNames = new Set(channelPresets.map((preset) => preset.name)); + if (!fs.existsSync(PRESETS_DIR)) return channelPresets; + const centralPresets = fs .readdirSync(PRESETS_DIR) .filter((f: string) => f.endsWith(".yaml")) .map((f: string) => { @@ -83,26 +108,40 @@ function listPresets(): PresetInfo[] { name: nameMatch ? nameMatch[1].trim() : f.replace(".yaml", ""), description: descMatch ? descMatch[1].trim() : "", }; - }); + }) + .filter((preset: PresetInfo) => !channelPresetNames.has(preset.name)); + return [...centralPresets, ...channelPresets]; } /** - * Read a built-in preset by short name from `PRESETS_DIR`. Guards against - * path traversal and returns `null` if the preset does not exist. + * Read a non-messaging built-in preset by short name from `PRESETS_DIR`. + * Guards against path traversal and returns `null` if the preset does not + * exist. */ -function loadPreset(name: string): string | null { +function loadCentralPreset(name: string, options: { reportMissing?: boolean } = {}): string | null { const file = path.resolve(PRESETS_DIR, `${name}.yaml`); if (!file.startsWith(PRESETS_DIR + path.sep) && file !== PRESETS_DIR) { console.error(` Invalid preset name: ${name}`); return null; } if (!fs.existsSync(file)) { - console.error(` Preset not found: ${name}`); + if (options.reportMissing !== false) console.error(` Preset not found: ${name}`); return null; } return fs.readFileSync(file, "utf-8"); } +function loadPresetForAgent(name: string, options: PresetLoadOptions = {}): string | null { + const channelPreset = loadMessagingChannelPolicyPreset(name, { agent: options.agent }); + if (channelPreset) return channelPreset; + if (isMessagingChannelPolicyPreset(name)) return null; + return loadCentralPreset(name); +} + +function loadPreset(name: string): string | null { + return loadPresetForAgent(name, { agent: "openclaw" }); +} + function isPolicyObject(value: PolicyValue): value is PolicyObject { return typeof value === "object" && value !== null && !Array.isArray(value); } @@ -232,7 +271,20 @@ function loadAgentPresetContent( } function loadPresetForSandbox(sandboxName: string, presetName: string): string | null { - const builtinPresetContent = loadPreset(presetName); + let sandboxAgent: string | null = null; + try { + sandboxAgent = registry.getSandbox(sandboxName)?.agent ?? null; + } catch { + sandboxAgent = null; + } + + const channelPresetContent = loadMessagingChannelPolicyPreset(presetName, { + agent: sandboxAgent, + }); + if (channelPresetContent) return channelPresetContent; + if (isMessagingChannelPolicyPreset(presetName)) return null; + + const builtinPresetContent = loadCentralPreset(presetName); if (!builtinPresetContent) return null; return ( loadAgentPresetContent(sandboxName, presetName, builtinPresetContent) || builtinPresetContent @@ -323,7 +375,16 @@ function listSetupPolicyPresets( sandboxName: string, options: SetupPolicyPresetSupportOptions = {}, ): PresetInfo[] { - return [...filterSetupPolicyPresets(listPresets(), options), ...listCustomPresets(sandboxName)]; + let sandboxAgent: string | null = null; + try { + sandboxAgent = registry.getSandbox(sandboxName)?.agent ?? null; + } catch { + sandboxAgent = null; + } + return [ + ...filterSetupPolicyPresets(listPresets({ agent: options.agent ?? sandboxAgent }), options), + ...listCustomPresets(sandboxName), + ]; } function clampSetupPolicyPresetNames( @@ -499,13 +560,14 @@ function mergePresetIntoPolicy(currentPolicy: string, presetEntries: string): st function mergePresetNamesIntoPolicy( currentPolicy: string, presetNames: string[], + options: MergePresetNamesOptions = {}, ): { policy: string; appliedPresets: string[]; missingPresets: string[] } { let merged = currentPolicy; const appliedPresets: string[] = []; const missingPresets: string[] = []; for (const presetName of [...new Set(presetNames)]) { - const presetContent = loadPreset(presetName); + const presetContent = loadPresetForAgent(presetName, { agent: options.agent }); const presetEntries = extractPresetEntries(presetContent); if (!presetEntries) { missingPresets.push(presetName); @@ -891,9 +953,10 @@ function applyPresetContent( } /** - * Apply a built-in preset (by name) to a running sandbox. Loads the preset - * from `nemoclaw-blueprint/policies/presets/.yaml` and delegates to - * `applyPresetContent`. Returns `false` if the named preset does not exist. + * Apply a built-in preset (by name) to a running sandbox. Loads messaging + * presets from channel-owned policy files and non-messaging presets from the + * central preset directory, then delegates to `applyPresetContent`. Returns + * `false` if the named preset does not exist. */ function applyPreset( sandboxName: string, @@ -1227,8 +1290,14 @@ function getGatewayPresets(sandboxName: string): string[] | null { const gatewayPolicyNames = new Set(Object.keys(gatewayPolicies)); const matched: string[] = []; + let sandboxAgent: string | null = null; + try { + sandboxAgent = registry.getSandbox(sandboxName)?.agent ?? null; + } catch { + sandboxAgent = null; + } - for (const preset of listPresets()) { + for (const preset of listPresets({ agent: sandboxAgent })) { if (presetMatchesGateway(loadPresetForSandbox(sandboxName, preset.name), gatewayPolicyNames)) { matched.push(preset.name); } @@ -1367,10 +1436,12 @@ export { getGatewayPresets, getPresetEndpoints, getPresetValidationWarning, + isMessagingChannelPolicyPreset, listCustomPresets, listPresets, listSetupPolicyPresets, loadPreset, + loadPresetForSandbox, loadPresetFromFile, mergePresetIntoPolicy, mergePresetNamesIntoPolicy, diff --git a/src/lib/sandbox/version.ts b/src/lib/sandbox/version.ts index adf16bd9363..9f6ec42e943 100644 --- a/src/lib/sandbox/version.ts +++ b/src/lib/sandbox/version.ts @@ -73,7 +73,7 @@ export interface VersionCheckOptions { * Resolve the agent definition for a sandbox. * Falls back to "openclaw" when the sandbox has no agent set. */ -export function resolveAgentForSandbox(sandboxName: string): ReturnType { +function resolveAgentForSandbox(sandboxName: string): ReturnType { const sb = registry.getSandbox(sandboxName); const agentName = sb?.agent || "openclaw"; return loadAgent(agentName); diff --git a/test/channels-add-deepagents-rejection.test.ts b/test/channels-add-deepagents-rejection.test.ts index b6110d45a62..8c35ee937cf 100644 --- a/test/channels-add-deepagents-rejection.test.ts +++ b/test/channels-add-deepagents-rejection.test.ts @@ -93,6 +93,7 @@ const policies = require(${d("policy/index.js")}); const policyCalls = { loadPreset: [], applyPreset: [] }; policies.listPresets = () => []; policies.loadPreset = (name) => { policyCalls.loadPreset.push(name); return "network_policies:\n stub: {}\n"; }; +policies.loadPresetForSandbox = (_sandboxName, name) => policies.loadPreset(name); policies.parsePresetPolicyKeys = () => ["stub"]; policies.applyPreset = (name, preset) => { policyCalls.applyPreset.push({ name, preset }); return true; }; policies.getAppliedPresets = () => []; diff --git a/test/channels-add-preset.test.ts b/test/channels-add-preset.test.ts index 6a7ed85ee85..05e0e57910e 100644 --- a/test/channels-add-preset.test.ts +++ b/test/channels-add-preset.test.ts @@ -176,12 +176,14 @@ const appliedCalls = []; const removedCalls = []; const callOrder = []; policies.listPresets = () => ${JSON.stringify(presetNamesAvailable.map((name) => ({ name })))}; -policies.loadPreset = (name) => { +function stubPresetContent(name) { if (${JSON.stringify(presetFileMissing)}) return null; if (${JSON.stringify(presetMissingNetworkPolicies)}) return "name: " + name + "\ndescription: \"stub preset without network_policies\"\n"; if (${JSON.stringify(presetMalformedYaml)}) return "network_policies:\n - [unclosed\n"; return "network_policies:\n " + name + ":\n egress:\n - host: example.com"; -}; +} +policies.loadPreset = (name) => stubPresetContent(name); +policies.loadPresetForSandbox = (sandboxName, name) => { callOrder.push("loadPresetForSandbox:" + sandboxName + ":" + name); return stubPresetContent(name); }; policies.applyPreset = (sandboxName, presetName) => { appliedCalls.push({ sandboxName, presetName }); callOrder.push("applyPreset:" + presetName); @@ -339,10 +341,8 @@ const ctx = module.exports; [{ sandboxName: "test-sb", presetName: channel }], `expected applyPreset("test-sb", "${channel}") exactly once; got ${JSON.stringify(payload.appliedCalls)}`, ); + assert.ok(payload.callOrder.includes(`loadPresetForSandbox:test-sb:${channel}`)); - // Contract 2: ordering invariant — preset apply must precede rebuild, - // otherwise the rebuild's backup manifest will not capture it and - // Step 5.5 of rebuild.ts has nothing to restore. const applyIdx = payload.callOrder.indexOf(`applyPreset:${channel}`); const rebuildIdx = payload.callOrder.indexOf("promptAndRebuild"); assert.ok( diff --git a/test/onboard-messaging.test.ts b/test/onboard-messaging.test.ts index 1f60c30939e..ade58b87bf7 100644 --- a/test/onboard-messaging.test.ts +++ b/test/onboard-messaging.test.ts @@ -461,7 +461,7 @@ const { createSandbox } = require(${onboardPath}); assert.ok(payload.createCommand.command.includes("sandbox create")); assert.match(payload.createCommand.command, /--provider my-assistant-slack-bridge/); assert.match(payload.createCommand.command, /--provider my-assistant-slack-app/); - assert.doesNotMatch(payload.createCommand.policyPath, /nemoclaw-initial-policy/); + assert.match(payload.createCommand.policyPath, /nemoclaw-initial-policy/); assert.equal(payload.createCommand.policyReadError, null); assert.deepEqual(payload.registeredPolicies, ["slack"]); assert.deepEqual(payload.slackBinaryPaths, [ diff --git a/test/package-contract/cli/policy-dispatch.test.ts b/test/package-contract/cli/policy-dispatch.test.ts index c673473157a..2e9e4101f34 100644 --- a/test/package-contract/cli/policy-dispatch.test.ts +++ b/test/package-contract/cli/policy-dispatch.test.ts @@ -3,10 +3,12 @@ import { spawnSync } from "node:child_process"; import fs from "node:fs"; +import { createRequire } from "node:module"; import os from "node:os"; import path from "node:path"; import { describe, expect, it } from "vitest"; +const requireForTest = createRequire(import.meta.url); const REPO_ROOT = path.join(import.meta.dirname, "../../.."); const CLI_PATH = JSON.stringify(path.join(REPO_ROOT, "dist", "nemoclaw.js")); const CREDENTIALS_PATH = JSON.stringify( @@ -14,6 +16,7 @@ const CREDENTIALS_PATH = JSON.stringify( ); const POLICIES_PATH = JSON.stringify(path.join(REPO_ROOT, "dist", "lib", "policy", "index.js")); const REGISTRY_PATH = JSON.stringify(path.join(REPO_ROOT, "dist", "lib", "state", "registry.js")); +const YAML_PATH = JSON.stringify(requireForTest.resolve("yaml")); type PolicyCall = { type: string; @@ -24,6 +27,33 @@ type PolicyCall = { }; describe("compiled CLI policy contracts", () => { + it("loads channel-owned messaging YAML from the packaged source layout", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-policy-packaged-channel-")); + const scriptPath = path.join(tmpDir, "packaged-channel-policy-check.js"); + const script = String.raw` +const YAML = require(${YAML_PATH}); +const registry = require(${REGISTRY_PATH}); +const policies = require(${POLICIES_PATH}); +registry.registerSandbox({ name: "hermes-contract", agent: "hermes", policies: [] }); +const openclaw = YAML.parse(policies.loadPreset("telegram")); +const hermes = YAML.parse(policies.loadPresetForSandbox("hermes-contract", "telegram")); +process.stdout.write("__RESULT__" + JSON.stringify({ + openclawKeys: Object.keys(openclaw.network_policies || {}), + hermesKeys: Object.keys(hermes.network_policies || {}), +})); +`; + fs.writeFileSync(scriptPath, script); + const result = spawnSync(process.execPath, [scriptPath], { + cwd: REPO_ROOT, + encoding: "utf-8", + env: { ...process.env, HOME: tmpDir }, + }); + expect(result.status).toBe(0); + const payload = JSON.parse(result.stdout.split("__RESULT__")[1].trim()); + expect(payload.openclawKeys).toEqual(["telegram_bot"]); + expect(payload.hermesKeys).toEqual(["telegram"]); + }); + describe("policy-remove custom presets", () => { function runPolicyRemoveCustom( presetName: string, @@ -44,6 +74,7 @@ policies.listCustomPresets = () => [ ]; policies.getAppliedPresets = () => ["my-api"]; policies.loadPreset = () => null; // built-in lookup misses +policies.loadPresetForSandbox = () => null; // built-in lookup misses policies.getPresetEndpoints = () => ["api.example.internal"]; policies.removePreset = (sandboxName, presetName) => { calls.push({ type: "remove", sandboxName, presetName }); diff --git a/test/policies.test.ts b/test/policies.test.ts index ce684f9ce6c..430764e9cae 100644 --- a/test/policies.test.ts +++ b/test/policies.test.ts @@ -50,6 +50,12 @@ function parseRepoYaml(relativePath: string): Record { >; } +function presetInfoPath(preset: { file: string }): string { + return preset.file.includes("/") + ? path.join(REPO_ROOT, preset.file) + : path.join(REPO_ROOT, "nemoclaw-blueprint/policies/presets", preset.file); +} + function parseResultPayload(stdout: string): any { const marker = "__RESULT__"; const markerIndex = stdout.indexOf(marker); @@ -1603,151 +1609,6 @@ exit 1 } }); - it("Slack REST endpoints opt into OpenShell request-body credential rewrite", () => { - const policySources = [ - fs.readFileSync( - path.join(REPO_ROOT, "nemoclaw-blueprint/policies/presets/slack.yaml"), - "utf8", - ), - fs.readFileSync(path.join(REPO_ROOT, "agents/hermes/policy-additions.yaml"), "utf8"), - fs.readFileSync(path.join(REPO_ROOT, "agents/hermes/policy-permissive.yaml"), "utf8"), - fs.readFileSync( - path.join(REPO_ROOT, "nemoclaw-blueprint/policies/openclaw-sandbox-permissive.yaml"), - "utf8", - ), - ]; - const slackRestHosts = new Set(["slack.com", "api.slack.com", "hooks.slack.com"]); - - for (const content of policySources) { - const parsed = YAML.parse(content) as { - network_policies?: Record< - string, - { - endpoints?: Array<{ - host?: string; - protocol?: string; - request_body_credential_rewrite?: boolean; - }>; - } - >; - }; - const endpoints = Object.values(parsed.network_policies ?? {}).flatMap( - (policy) => policy.endpoints ?? [], - ); - for (const endpoint of endpoints.filter((candidate) => - slackRestHosts.has(candidate.host ?? ""), - )) { - expect(endpoint).toMatchObject({ - protocol: "rest", - request_body_credential_rewrite: true, - }); - } - } - }); - - it("Hermes messaging gateway policies use native inspected WebSocket policy", () => { - const policyFiles = [ - path.join(REPO_ROOT, "agents/hermes/policy-additions.yaml"), - path.join(REPO_ROOT, "agents/hermes/policy-permissive.yaml"), - ]; - const cases = [ - "gateway.discord.gg", - "*.discord.gg", - "wss-primary.slack.com", - "wss-backup.slack.com", - ]; - - for (const file of policyFiles) { - const content = fs.readFileSync(file, "utf8"); - const parsed = YAML.parse(content) as { - network_policies?: Record< - string, - { - endpoints?: Array<{ - host?: string; - protocol?: string; - access?: string; - tls?: string; - websocket_credential_rewrite?: boolean; - rules?: Array<{ allow?: { method?: string; path?: string } }>; - }>; - } - >; - }; - const endpoints = Object.values(parsed.network_policies ?? {}).flatMap( - (policy) => policy.endpoints ?? [], - ); - for (const host of cases) { - const endpoint = endpoints.find((candidate) => candidate.host === host); - expect(endpoint).toBeTruthy(); - expect(endpoint).toMatchObject({ - protocol: "websocket", - enforcement: "enforce", - websocket_credential_rewrite: true, - }); - expect(endpoint).not.toHaveProperty("access"); - expect(endpoint).not.toHaveProperty("tls"); - expect(endpoint?.rules).toEqual( - expect.arrayContaining([ - { allow: { method: "GET", path: "/**" } }, - { allow: { method: "WEBSOCKET_TEXT", path: "/**" } }, - ]), - ); - } - } - }); - - it("Hermes Discord REST mutations are scoped to discord.com", () => { - const parsed = parseRepoYaml("agents/hermes/policy-additions.yaml"); - const networkPolicies = parsed.network_policies as Record< - string, - { - endpoints?: Array<{ - host?: string; - rules?: Array<{ allow?: { method?: string; path?: string } }>; - }>; - } - >; - const rulesFor = (policy: string, host: string) => - (networkPolicies[policy]?.endpoints ?? []) - .filter((endpoint) => endpoint.host === host) - .flatMap((endpoint) => endpoint.rules ?? []) - .map((rule) => rule.allow) - .filter((rule): rule is { method: string; path: string } => - Boolean(rule?.method && rule?.path), - ); - const sortRules = (rules: Array<{ method: string; path: string }>) => - [...rules].sort((a, b) => `${a.method} ${a.path}`.localeCompare(`${b.method} ${b.path}`)); - - const nousRules = rulesFor("nous_research", "nousresearch.com"); - expect(nousRules).not.toContainEqual({ method: "PUT", path: "/**" }); - expect(nousRules).not.toContainEqual({ method: "PATCH", path: "/**" }); - expect(nousRules.filter((rule) => ["PUT", "PATCH", "DELETE"].includes(rule.method))).toEqual( - [], - ); - - const discordMutationRules = sortRules( - rulesFor("discord", "discord.com").filter((rule) => - ["PUT", "PATCH", "DELETE"].includes(rule.method), - ), - ); - expect(discordMutationRules).toEqual( - sortRules([ - { method: "PUT", path: "/api/v*/applications/*/commands" }, - { method: "PUT", path: "/api/v*/channels/*/messages/*/reactions/*/@me" }, - { method: "PATCH", path: "/api/v*/applications/*" }, - { method: "PATCH", path: "/api/v*/applications/*/commands/*" }, - { method: "PATCH", path: "/api/v*/channels/*/messages/*" }, - { method: "PATCH", path: "/api/v*/webhooks/*/*/messages/*" }, - { method: "DELETE", path: "/api/v*/applications/*/commands/*" }, - { method: "DELETE", path: "/api/v*/channels/*/messages/*" }, - { method: "DELETE", path: "/api/v*/channels/*/messages/*/reactions/*/*" }, - { method: "DELETE", path: "/api/v*/webhooks/*/*/messages/*" }, - ]), - ); - expect(discordMutationRules.some((rule) => rule.path === "/**")).toBe(false); - }); - it("Hermes PyPI policy lets curl verify read-only package index access (#4014)", () => { const parsed = parseRepoYaml("agents/hermes/policy-additions.yaml"); const pypiPolicy = parsed.network_policies?.pypi as @@ -1809,11 +1670,7 @@ exit 1 : []; const policyFiles = [ path.join(REPO_ROOT, "nemoclaw-blueprint/policies/openclaw-sandbox.yaml"), - ...policies - .listPresets() - .map((preset) => - path.join(REPO_ROOT, "nemoclaw-blueprint/policies/presets", preset.file), - ), + ...policies.listPresets().map((preset) => presetInfoPath(preset)), ...agentPolicyFiles, ]; diff --git a/test/policy-add-deepagents-rejection.test.ts b/test/policy-add-deepagents-rejection.test.ts deleted file mode 100644 index 7f695004144..00000000000 --- a/test/policy-add-deepagents-rejection.test.ts +++ /dev/null @@ -1,241 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import assert from "node:assert/strict"; -import { type SpawnSyncReturns, spawnSync } from "node:child_process"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import { describe, it } from "vitest"; - -const repoRoot = path.join(import.meta.dirname, ".."); - -const MESSAGING_CHANNELS = ["telegram", "discord", "slack", "wechat", "whatsapp"] as const; - -function runScript( - scriptBody: string, - extraFiles: Record = {}, -): SpawnSyncReturns { - const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-6185-")); - const scriptPath = path.join(tmpDir, "script.js"); - fs.writeFileSync(scriptPath, scriptBody); - for (const [name, content] of Object.entries(extraFiles)) { - fs.writeFileSync(path.join(tmpDir, name), content); - } - const result = spawnSync(process.execPath, [scriptPath], { - cwd: repoRoot, - encoding: "utf-8", - env: { - ...process.env, - HOME: tmpDir, - NEMOCLAW_NON_INTERACTIVE: "1", - }, - timeout: 15000, - }); - fs.rmSync(tmpDir, { recursive: true, force: true }); - return result; -} - -function parseResultPayload>( - result: SpawnSyncReturns, -): T { - const marker = result.stdout.lastIndexOf("__RESULT__"); - assert.ok( - marker >= 0, - `no __RESULT__ marker in stdout:\n${result.stdout}\n---stderr---\n${result.stderr}`, - ); - return JSON.parse(result.stdout.slice(marker + "__RESULT__".length).trim()) as T; -} - -function buildPreamble(agentName: string): string { - const d = (p: string) => - JSON.stringify(path.join(repoRoot, "src", "lib", p.replace(/\.js$/, ".ts"))); - return String.raw` -const onboard = require(${d("onboard.js")}); -onboard.isNonInteractive = () => true; - -const credentials = require(${d("credentials/store.js")}); -const promptCalls = []; -credentials.prompt = async (msg) => { promptCalls.push(msg); return ""; }; - -const registry = require(${d("state/registry.js")}); -registry.getSandbox = () => ({ name: "test-sb", agent: ${JSON.stringify(agentName)} }); - -const agentDefs = require(${d("agent/defs.js")}); -agentDefs.loadAgent = () => ({ name: ${JSON.stringify(agentName)} }); - -const policies = require(${d("policy/index.js")}); -const policyCalls = { loadPreset: [], applyPreset: [] }; -policies.listPresets = () => [ - { name: "pypi", description: "Python Package Index access" }, - { name: "telegram", description: "Telegram API access" }, - { name: "discord", description: "Discord API access" }, - { name: "slack", description: "Slack API access" }, - { name: "wechat", description: "WeChat API access" }, - { name: "whatsapp", description: "WhatsApp API access" }, -]; -policies.getAppliedPresets = () => []; -policies.loadPreset = (name) => { policyCalls.loadPreset.push(name); return "network_policies:\n stub: {}\n"; }; -policies.getPresetEndpoints = () => ["api.telegram.org"]; -policies.getPresetValidationWarning = () => null; -policies.applyPreset = (name, preset) => { policyCalls.applyPreset.push({ name, preset }); return true; }; -policies.selectFromList = async () => null; - -const policyModule = require(${d("actions/sandbox/policy-channel.js")}); - -let exitCode = null; -process.exit = (code) => { exitCode = code; throw new Error("__INTERCEPTED_EXIT__:" + code); }; - -const logs = []; -console.log = (...args) => { logs.push(args.map(String).join(" ")); }; -const errors = []; -console.error = (...args) => { errors.push(args.map(String).join(" ")); }; - -module.exports = { - policyModule, - policyCalls, - promptCalls, - logs, - errors, - getExitCode: () => exitCode, -}; -`; -} - -function runPolicyAdd(agentName: string, preset: string) { - const script = `${buildPreamble(agentName)} -const ctx = module.exports; -(async () => { - let caught = null; - try { - await ctx.policyModule.addSandboxPolicy("test-sb", { preset: ${JSON.stringify(preset)}, yes: true }); - } catch (err) { - if (!String(err && err.message).startsWith("__INTERCEPTED_EXIT__")) { - caught = { message: String(err && err.message), stack: err && err.stack }; - } - } - process.stdout.write("\\n__RESULT__" + JSON.stringify({ - exitCode: ctx.getExitCode(), - logs: ctx.logs, - errors: ctx.errors, - policyCalls: ctx.policyCalls, - promptCalls: ctx.promptCalls, - unexpectedError: caught, - }) + "\\n"); -})(); -`; - const result = runScript(script); - assert.equal(result.status, 0, `script crashed: ${result.stderr}\n${result.stdout}`); - return parseResultPayload<{ - exitCode: number; - logs: string[]; - errors: string[]; - policyCalls: { loadPreset: string[]; applyPreset: unknown[] }; - promptCalls: string[]; - unexpectedError: { message: string; stack: string } | null; - }>(result); -} - -const MESSAGING_POLICY_KEYS = [ - ["telegram_bot", "api.telegram.org"], - ["discord", "discord.com"], - ["slack", "api.slack.com"], - ["wechat_bridge", "api.weixin.qq.com"], - ["whatsapp", "graph.facebook.com"], - ["teams", "graph.microsoft.com"], -] as const; - -function runPolicyAddFromFile(agentName: string, presetYamlContent: string) { - const script = `${buildPreamble(agentName)} -const path = require("node:path"); -const ctx = module.exports; -(async () => { - let caught = null; - try { - const filePath = path.join(process.env.HOME, "custom-preset.yaml"); - await ctx.policyModule.addSandboxPolicy("test-sb", { fromFile: filePath, yes: true }); - } catch (err) { - if (!String(err && err.message).startsWith("__INTERCEPTED_EXIT__")) { - caught = { message: String(err && err.message), stack: err && err.stack }; - } - } - process.stdout.write("\\n__RESULT__" + JSON.stringify({ - exitCode: ctx.getExitCode(), - logs: ctx.logs, - errors: ctx.errors, - policyCalls: ctx.policyCalls, - promptCalls: ctx.promptCalls, - unexpectedError: caught, - }) + "\\n"); -})(); -`; - const result = runScript(script, { "custom-preset.yaml": presetYamlContent }); - assert.equal(result.status, 0, `script crashed: ${result.stderr}\n${result.stdout}`); - return parseResultPayload<{ - exitCode: number; - logs: string[]; - errors: string[]; - policyCalls: { loadPreset: string[]; applyPreset: unknown[] }; - promptCalls: string[]; - unexpectedError: { message: string; stack: string } | null; - }>(result); -} - -describe("addSandboxPolicy custom preset (--from-file) channel/agent gate (behaviour)", () => { - it.each( - MESSAGING_POLICY_KEYS, - )("DeepAgents policy-add --from-file with a '%s' policy key exits nonzero before any disclosure, prompt, or apply", (policyKey, host) => { - const presetYaml = `preset:\n name: my-custom-${policyKey.replace(/_/g, "-")}\nnetwork_policies:\n ${policyKey}:\n host: ${host}\n`; - const payload = runPolicyAddFromFile("langchain-deepagents-code", presetYaml); - - assert.equal( - payload.unexpectedError, - null, - `unexpected exception: ${payload.unexpectedError?.stack}`, - ); - assert.equal(payload.exitCode, 1, "expected addSandboxPolicy to exit with code 1"); - assert.ok( - payload.errors.some((msg) => /does not support agent 'langchain-deepagents-code'/.test(msg)), - `missing unsupported channel-agent error in stderr: ${JSON.stringify(payload.errors)}`, - ); - assert.ok( - payload.logs.every((msg) => !/Endpoints that would be opened/.test(msg)), - `endpoint disclosure must not print before the gate: ${JSON.stringify(payload.logs)}`, - ); - assert.deepEqual(payload.promptCalls, [], "prompt must not run before the gate"); - }); -}); - -describe("addSandboxPolicy channel/agent gate (behaviour)", () => { - it.each( - MESSAGING_CHANNELS, - )("DeepAgents policy-add %s exits nonzero before any disclosure, prompt, or apply", (channel) => { - const payload = runPolicyAdd("langchain-deepagents-code", channel); - - assert.equal( - payload.unexpectedError, - null, - `unexpected exception: ${payload.unexpectedError?.stack}`, - ); - assert.equal(payload.exitCode, 1, "expected addSandboxPolicy to exit with code 1"); - assert.ok( - payload.errors.some((msg) => - new RegExp(`Channel '${channel}' does not support agent 'langchain-deepagents-code'`).test( - msg, - ), - ), - `missing unsupported channel-agent error in stderr: ${JSON.stringify(payload.errors)}`, - ); - assert.ok( - payload.logs.every((msg) => !/Endpoints that would be opened/.test(msg)), - `endpoint disclosure must not print before the gate: ${JSON.stringify(payload.logs)}`, - ); - assert.deepEqual(payload.promptCalls, [], "prompt must not run before the gate"); - assert.deepEqual( - payload.policyCalls.applyPreset, - [], - "applyPreset must not run before the gate", - ); - assert.deepEqual(payload.policyCalls.loadPreset, [], "loadPreset must not run before the gate"); - }); -}); diff --git a/test/policy-add-remove-session-sync.test.ts b/test/policy-add-remove-session-sync.test.ts index 5ee0ce987e2..1b352e42c58 100644 --- a/test/policy-add-remove-session-sync.test.ts +++ b/test/policy-add-remove-session-sync.test.ts @@ -82,6 +82,7 @@ const calls = { apply: [], applyContent: [], remove: [] }; policies.listPresets = () => ${JSON.stringify(presetNamesAvailable.map((name) => ({ name })))}; policies.getAppliedPresets = () => ${JSON.stringify(appliedPresets)}; policies.loadPreset = (name) => ({ name, network_policies: {} }); +policies.loadPresetForSandbox = (_sandboxName, name) => policies.loadPreset(name); policies.getPresetEndpoints = () => []; policies.getPresetValidationWarning = () => null; policies.selectFromList = async (items) => items[0]?.name || null; diff --git a/test/policy-channel-agent-resolution.test.ts b/test/policy-channel-agent-resolution.test.ts new file mode 100644 index 00000000000..b7d3b06d260 --- /dev/null +++ b/test/policy-channel-agent-resolution.test.ts @@ -0,0 +1,169 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +const REPO_ROOT = path.join(import.meta.dirname, ".."); +const ACTION_PATH = JSON.stringify( + path.join(REPO_ROOT, "src", "lib", "actions", "sandbox", "policy-channel.ts"), +); +const POLICIES_PATH = JSON.stringify(path.join(REPO_ROOT, "src", "lib", "policy", "index.ts")); +const REGISTRY_PATH = JSON.stringify(path.join(REPO_ROOT, "src", "lib", "state", "registry.ts")); +const SOURCE_NODE_ARGS = ["--import", "tsx"]; + +describe("sandbox-aware messaging policy resolution", () => { + it("loadPresetForSandbox fails closed for unknown messaging agents without blocking central presets", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-policy-agent-resolution-")); + const script = String.raw` +const registry = require(${REGISTRY_PATH}); +const policies = require(${POLICIES_PATH}); +registry.registerSandbox({ + name: "deepagents-sandbox", + agent: "langchain-deepagents-code", + policies: [], +}); +const channelPreset = policies.loadPresetForSandbox("deepagents-sandbox", "telegram"); +const centralPreset = policies.loadPresetForSandbox("deepagents-sandbox", "npm"); +process.stdout.write("__RESULT__" + JSON.stringify({ + channelPreset, + centralPresetHasNpmPolicy: String(centralPreset).includes("npm_yarn:"), +})); +`; + const result = spawnSync(process.execPath, [...SOURCE_NODE_ARGS, "-e", script], { + cwd: REPO_ROOT, + encoding: "utf-8", + env: { ...process.env, HOME: tmpDir }, + }); + fs.rmSync(tmpDir, { recursive: true, force: true }); + + expect(result.status).toBe(0); + const payload = JSON.parse(result.stdout.split("__RESULT__")[1].trim()); + expect(payload.channelPreset).toBeNull(); + expect(payload.centralPresetHasNpmPolicy).toBe(true); + expect(result.stderr).not.toContain("Preset not found"); + }); + + it("gateway preset matching skips unsupported Deep Agents messaging policies without lookup noise (#6185)", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-policy-gateway-agent-")); + const openshellPath = path.join(tmpDir, "openshell"); + fs.writeFileSync( + openshellPath, + [ + "#!/usr/bin/env bash", + "cat <<'EOF'", + "Version: 1", + "---", + "version: 1", + "network_policies:", + " npm_yarn:", + " endpoints: []", + "EOF", + "", + ].join("\n"), + ); + fs.chmodSync(openshellPath, 0o755); + const script = String.raw` +const registry = require(${REGISTRY_PATH}); +const policies = require(${POLICIES_PATH}); +registry.registerSandbox({ + name: "deepagents-sandbox", + agent: "langchain-deepagents-code", + policies: [], +}); +const gatewayPresets = policies.getGatewayPresets("deepagents-sandbox"); +process.stdout.write("__RESULT__" + JSON.stringify({ gatewayPresets })); +`; + const result = spawnSync(process.execPath, [...SOURCE_NODE_ARGS, "-e", script], { + cwd: REPO_ROOT, + encoding: "utf-8", + env: { ...process.env, HOME: tmpDir, NEMOCLAW_OPENSHELL_BIN: openshellPath }, + }); + fs.rmSync(tmpDir, { recursive: true, force: true }); + + expect(result.status).toBe(0); + expect(result.stderr).not.toContain("Preset not found"); + const payload = JSON.parse(result.stdout.split("__RESULT__")[1].trim()); + expect(payload.gatewayPresets).toEqual(["npm"]); + }); + it("setup policy preset catalog omits unsupported Deep Agents messaging policies (#6185)", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-policy-setup-agent-")); + const script = String.raw` +const registry = require(${REGISTRY_PATH}); +const policies = require(${POLICIES_PATH}); +registry.registerSandbox({ + name: "deepagents-sandbox", + agent: "langchain-deepagents-code", + policies: [], +}); +const names = policies.listSetupPolicyPresets("deepagents-sandbox").map((preset) => preset.name); +process.stdout.write("__RESULT__" + JSON.stringify({ names })); +`; + const result = spawnSync(process.execPath, [...SOURCE_NODE_ARGS, "-e", script], { + cwd: REPO_ROOT, + encoding: "utf-8", + env: { ...process.env, HOME: tmpDir }, + }); + fs.rmSync(tmpDir, { recursive: true, force: true }); + + expect(result.status).toBe(0); + const payload = JSON.parse(result.stdout.split("__RESULT__")[1].trim()); + expect(payload.names).toContain("npm"); + expect(payload.names).not.toContain("telegram"); + expect(payload.names).not.toContain("discord"); + expect(payload.names).not.toContain("slack"); + expect(payload.names).not.toContain("teams"); + expect(payload.names).not.toContain("whatsapp"); + expect(payload.names).not.toContain("wechat"); + }); + + it("policy-add treats unsupported Deep Agents messaging policy as unknown before preview or prompt (#6185)", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-policy-agent-gate-")); + const script = String.raw` +const registry = require(${REGISTRY_PATH}); +const { addSandboxPolicy } = require(${ACTION_PATH}); +const output = []; +const errors = []; +console.log = (...args) => output.push(args.join(" ")); +console.error = (...args) => errors.push(args.join(" ")); +process.exit = (code) => { throw new Error("EXIT:" + String(code)); }; +registry.registerSandbox({ + name: "deepagents-sandbox", + agent: "langchain-deepagents-code", + policies: [], +}); +(async () => { + let exitCode = null; + try { + await addSandboxPolicy("deepagents-sandbox", { preset: "telegram", yes: true }); + } catch (error) { + exitCode = String(error && error.message) === "EXIT:1" ? 1 : "unexpected"; + errors.push(String(error && (error.stack || error.message || error))); + } + process.stdout.write("__RESULT__" + JSON.stringify({ exitCode, output, errors })); +})(); +`; + const result = spawnSync(process.execPath, [...SOURCE_NODE_ARGS, "-e", script], { + cwd: REPO_ROOT, + encoding: "utf-8", + env: { ...process.env, HOME: tmpDir }, + }); + fs.rmSync(tmpDir, { recursive: true, force: true }); + + expect(result.status).toBe(0); + const payload = JSON.parse(result.stdout.split("__RESULT__")[1].trim()); + const text = [...payload.output, ...payload.errors].join("\n"); + expect(payload.exitCode).toBe(1); + expect(text).toContain("Unknown preset 'telegram'."); + expect(text).toContain("Valid presets:"); + expect(text).not.toContain("telegram,"); + expect(text).not.toContain("not supported for agent"); + expect(text).not.toContain("Terminal-runtime agents do not run inbound messaging bridges."); + expect(text).not.toContain("Preset not found"); + expect(text).not.toContain("Endpoints that would be opened"); + expect(text).not.toContain("Apply 'telegram'"); + }); +}); diff --git a/test/policy-channel-yaml-contract.test.ts b/test/policy-channel-yaml-contract.test.ts new file mode 100644 index 00000000000..fe9207204b8 --- /dev/null +++ b/test/policy-channel-yaml-contract.test.ts @@ -0,0 +1,158 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; +import YAML from "yaml"; + +const REPO_ROOT = path.resolve(import.meta.dirname, ".."); + +type Endpoint = { + host?: string; + protocol?: string; + enforcement?: string; + access?: string; + tls?: string; + request_body_credential_rewrite?: boolean; + websocket_credential_rewrite?: boolean; + rules?: Array<{ allow?: { method?: string; path?: string } }>; +}; + +function channelPolicy(channel: string, agent: "openclaw" | "hermes"): Record { + const file = path.join( + REPO_ROOT, + "src/lib/messaging/channels", + channel, + "policy", + `${agent}.yaml`, + ); + return YAML.parse(fs.readFileSync(file, "utf8")) as Record; +} + +function allEndpoints(policy: Record): Endpoint[] { + return Object.values( + (policy.network_policies ?? {}) as Record, + ).flatMap((entry) => entry.endpoints ?? []); +} + +function requireNonEmpty(items: T[], label: string): T[] { + expect(items[0], label).toBeDefined(); + return items; +} + +function expectInspectedWebSocket(endpoint: Endpoint | undefined): void { + expect(endpoint).toBeTruthy(); + expect(endpoint).toMatchObject({ + protocol: "websocket", + enforcement: "enforce", + websocket_credential_rewrite: true, + }); + expect(endpoint).not.toHaveProperty("access"); + expect(endpoint).not.toHaveProperty("tls"); + expect(endpoint?.rules).toEqual( + expect.arrayContaining([ + { allow: { method: "GET", path: "/**" } }, + { allow: { method: "WEBSOCKET_TEXT", path: "/**" } }, + ]), + ); +} + +describe("channel-owned messaging policy YAML", () => { + it("Slack REST endpoints opt into OpenShell request-body credential rewrite", () => { + const sources = [ + channelPolicy("slack", "openclaw"), + channelPolicy("slack", "hermes"), + YAML.parse( + fs.readFileSync(path.join(REPO_ROOT, "agents/hermes/policy-permissive.yaml"), "utf8"), + ), + YAML.parse( + fs.readFileSync( + path.join(REPO_ROOT, "nemoclaw-blueprint/policies/openclaw-sandbox-permissive.yaml"), + "utf8", + ), + ), + ]; + const slackRestHosts = new Set(["slack.com", "api.slack.com", "hooks.slack.com"]); + const slackRestEndpoints = requireNonEmpty( + sources.flatMap(allEndpoints).filter((entry) => slackRestHosts.has(entry.host ?? "")), + "expected Slack REST endpoints in channel and permissive policies", + ); + + for (const endpoint of slackRestEndpoints) { + expect(endpoint).toMatchObject({ + protocol: "rest", + request_body_credential_rewrite: true, + }); + } + }); + + it("Hermes messaging gateway policies use native inspected WebSocket policy", () => { + const cases = [ + { policy: channelPolicy("discord", "hermes"), hosts: ["gateway.discord.gg", "*.discord.gg"] }, + { + policy: channelPolicy("slack", "hermes"), + hosts: ["wss-primary.slack.com", "wss-backup.slack.com"], + }, + ]; + + for (const { policy, hosts } of cases) { + const endpoints = allEndpoints(policy); + for (const host of hosts) { + expectInspectedWebSocket(endpoints.find((endpoint) => endpoint.host === host)); + } + } + }); + + it("Hermes Discord REST mutations are scoped to discord.com", () => { + const networkPolicies = channelPolicy("discord", "hermes").network_policies as Record< + string, + { endpoints?: Endpoint[] } + >; + const rulesFor = (policy: string, host: string) => + (networkPolicies[policy]?.endpoints ?? []) + .filter((endpoint) => endpoint.host === host) + .flatMap((endpoint) => endpoint.rules ?? []) + .map((rule) => rule.allow) + .filter((rule): rule is { method: string; path: string } => + Boolean(rule?.method && rule?.path), + ); + const sortRules = (rules: Array<{ method: string; path: string }>) => + [...rules].sort((a, b) => `${a.method} ${a.path}`.localeCompare(`${b.method} ${b.path}`)); + + const discordEndpoints = requireNonEmpty( + networkPolicies.discord?.endpoints ?? [], + "expected Hermes Discord endpoints", + ); + const nonDiscordMutationRules = discordEndpoints + .filter((endpoint) => endpoint.host !== "discord.com") + .flatMap((endpoint) => endpoint.rules ?? []) + .map((rule) => rule.allow) + .filter((rule): rule is { method: string; path: string } => + Boolean(rule?.method && rule?.path), + ) + .filter((rule) => ["PUT", "PATCH", "DELETE"].includes(rule.method)); + expect(nonDiscordMutationRules).toEqual([]); + + const discordMutationRules = sortRules( + rulesFor("discord", "discord.com").filter((rule) => + ["PUT", "PATCH", "DELETE"].includes(rule.method), + ), + ); + expect(discordMutationRules).toEqual( + sortRules([ + { method: "PUT", path: "/api/v*/applications/*/commands" }, + { method: "PUT", path: "/api/v*/channels/*/messages/*/reactions/*/@me" }, + { method: "PATCH", path: "/api/v*/applications/*" }, + { method: "PATCH", path: "/api/v*/applications/*/commands/*" }, + { method: "PATCH", path: "/api/v*/channels/*/messages/*" }, + { method: "PATCH", path: "/api/v*/webhooks/*/*/messages/*" }, + { method: "DELETE", path: "/api/v*/applications/*/commands/*" }, + { method: "DELETE", path: "/api/v*/channels/*/messages/*" }, + { method: "DELETE", path: "/api/v*/channels/*/messages/*/reactions/*/*" }, + { method: "DELETE", path: "/api/v*/webhooks/*/*/messages/*" }, + ]), + ); + expect(discordMutationRules.some((rule) => rule.path === "/**")).toBe(false); + }); +}); diff --git a/test/pr-review-advisor.test.ts b/test/pr-review-advisor.test.ts index 612c0c68215..57e309b38cb 100644 --- a/test/pr-review-advisor.test.ts +++ b/test/pr-review-advisor.test.ts @@ -214,9 +214,9 @@ describe("PR review advisor", () => { }); it("classifies sandbox and workflow changes as requiring deeper validation", () => { - expect(classifyTestDepth(["nemoclaw-blueprint/policies/presets/slack.yaml"]).verdict).toBe( - "runtime_validation_recommended", - ); + expect( + classifyTestDepth(["src/lib/messaging/channels/slack/policy/openclaw.yaml"]).verdict, + ).toBe("runtime_validation_recommended"); expect(classifyTestDepth(["src/lib/credentials.ts"]).verdict).toBe("mocks_recommended"); expect(classifyTestDepth(["docs/get-started/quickstart.mdx"]).verdict).toBe("unit_sufficient"); }); diff --git a/test/validate-blueprint.test.ts b/test/validate-blueprint.test.ts index 22d9cc05dcd..e3e50d039ea 100644 --- a/test/validate-blueprint.test.ts +++ b/test/validate-blueprint.test.ts @@ -731,11 +731,11 @@ describe("jira preset", () => { describe("messaging WebSocket presets", () => { const DISCORD_PRESET_PATH = new URL( - "../nemoclaw-blueprint/policies/presets/discord.yaml", + "../src/lib/messaging/channels/discord/policy/openclaw.yaml", import.meta.url, ); const SLACK_PRESET_PATH = new URL( - "../nemoclaw-blueprint/policies/presets/slack.yaml", + "../src/lib/messaging/channels/slack/policy/openclaw.yaml", import.meta.url, ); @@ -791,7 +791,7 @@ describe("messaging WebSocket presets", () => { describe("Slack REST credential rewrite", () => { const SLACK_PRESET_PATH = new URL( - "../nemoclaw-blueprint/policies/presets/slack.yaml", + "../src/lib/messaging/channels/slack/policy/openclaw.yaml", import.meta.url, ); const data = loadYaml(SLACK_PRESET_PATH); diff --git a/test/validate-config-schemas.test.ts b/test/validate-config-schemas.test.ts index 85ee98dcbc8..372d130a612 100644 --- a/test/validate-config-schemas.test.ts +++ b/test/validate-config-schemas.test.ts @@ -9,7 +9,7 @@ * Vitest project. */ -import { existsSync, readFileSync, readdirSync } from "node:fs"; +import { existsSync, readFileSync } from "node:fs"; import { join, dirname } from "node:path"; import { fileURLToPath } from "node:url"; import { describe, it, expect } from "vitest"; @@ -96,6 +96,7 @@ describe("config validation target discovery", () => { const targets = discoverTargets(); const filesBySchema = new Map(targets.map((target) => [target.schema, target.files])); const sandboxPolicyFiles = filesBySchema.get("schemas/sandbox-policy.schema.json") ?? []; + const presetFiles = filesBySchema.get("schemas/policy-preset.schema.json") ?? []; it("includes every binary-scoped sandbox policy family", () => { expect(sandboxPolicyFiles).toEqual( @@ -116,6 +117,17 @@ describe("config validation target discovery", () => { ]), ); }); + + it("discovers channel-owned messaging policy presets", () => { + expect(presetFiles).toEqual( + expect.arrayContaining([ + "src/lib/messaging/channels/slack/policy/openclaw.yaml", + "src/lib/messaging/channels/slack/policy/hermes.yaml", + "src/lib/messaging/channels/telegram/policy/openclaw.yaml", + "src/lib/messaging/channels/telegram/policy/hermes.yaml", + ]), + ); + }); }); // ── Blueprint ──────────────────────────────────────────────────────────────── @@ -384,20 +396,13 @@ describe("sandbox-policy.schema.json", () => { describe("policy-preset.schema.json", () => { const validate = compileSchema("schemas/policy-preset.schema.json"); - const presetsDir = repoPath("nemoclaw-blueprint/policies/presets"); - - let presetFiles: string[] = []; - try { - presetFiles = readdirSync(presetsDir).filter((f) => f.endsWith(".yaml") || f.endsWith(".yml")); - } catch (err) { - const code = typeof err === "object" && err !== null && "code" in err ? err.code : undefined; - if (code !== "ENOENT") throw err; - // directory may not exist - } + const presetFiles = + discoverTargets().find((target) => target.schema === "schemas/policy-preset.schema.json") + ?.files ?? []; for (const file of presetFiles) { it(`${file} passes schema validation`, () => { - const data = loadYAML(join(presetsDir, file)); + const data = loadYAML(repoPath(file)); expectValid(validate, data, file); }); } diff --git a/tools/pr-review-advisor/analyze.mts b/tools/pr-review-advisor/analyze.mts index 39cefc05fb5..ac8173cb448 100755 --- a/tools/pr-review-advisor/analyze.mts +++ b/tools/pr-review-advisor/analyze.mts @@ -709,6 +709,7 @@ export function classifyTestDepth( file.endsWith("Dockerfile") || /(^|\/)(install|setup|brev-setup|nemoclaw-start)\.sh$/.test(file) || file.startsWith("nemoclaw-blueprint/policies/") || + (file.startsWith("src/lib/messaging/channels/") && file.includes("/policy/")) || file.startsWith("nemoclaw/src/blueprint/") || file.startsWith("test/e2e/") || file.includes("sandbox") ||