From 4b34b634f9fb22eeafaa7b8ccc2c5b5b54ce0feb Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Mon, 16 Nov 2026 19:56:30 -0800 Subject: [PATCH 01/17] fix(mcp): reuse shared-host address pins on mcp add A second `mcp add` on a host that publishes several DNS addresses pinned whichever address that lookup returned. OpenShell rejects two endpoints for one host and port when their `allowed_ips` differ, so the second add failed with a bare "network endpoint ambiguity validation failed" even though the two servers use distinct paths and credentials. When another managed server already records pins for the same host and port, `mcp add` now validates those pins again and uses them for the new server instead of the address it just resolved. If the existing servers already record different pins, or the pins are trusted-private and the new answer differs, the add stops before changing anything and names the servers, the pins and the `mcp remove` recovery. Command scope is unchanged: `mcp update` still acts on the one named server. Fixes #13800 Signed-off-by: Deepak Jain --- .../actions/sandbox/mcp-bridge-add-restart.ts | 18 ++ .../mcp-bridge/shared-host-pins.test.ts | 302 ++++++++++++++++++ .../sandbox/mcp-bridge/shared-host-pins.ts | 117 +++++++ 3 files changed, 437 insertions(+) create mode 100644 src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts create mode 100644 src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts diff --git a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts index 350f52f2652..3bab3a3a902 100644 --- a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts +++ b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts @@ -58,6 +58,7 @@ import { waitForDetachedMcpCredential, } from "./mcp-bridge-provider"; import { createMcpProviderAdapterBoundary } from "./mcp-bridge-provider-inspection"; +import { alignMcpAddTargetWithSharedHostPins } from "./mcp-bridge/shared-host-pins"; import { assertNoAmbiguousMcpCredentialTarget, assertNoAmbiguousMcpCredentialTargets, @@ -778,6 +779,23 @@ async function addMcpBridgeUnlocked( trustedPrivateHosts: matchingTrustedPrivateHosts, requireTrustedPrivateEndpoint: explicitTrustedPrivateHosts.length > 0, }); + // A host that publishes several addresses can answer each add differently, + // and OpenShell rejects endpoints that share a host and port but list + // different allowed IPs. Keep a new server's pins equal to its siblings'. + const aligned = alignMcpAddTargetWithSharedHostPins({ + sandboxName, + server: options.server, + url: normalizedUrl, + target, + bridges: observed.bridges, + }); + if (!aligned.ok) throw new McpBridgeError(aligned.message, 2); + target = aligned.target; + if (aligned.reusedFrom.length > 0) { + console.log( + ` Reusing the address pins already recorded for MCP server ${aligned.reusedFrom.map((name) => `'${name}'`).join(", ")} on ${urlHost}.`, + ); + } } const envNames = uniqueEnvNames(options.env); diff --git a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts new file mode 100644 index 00000000000..958a30d2e6b --- /dev/null +++ b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts @@ -0,0 +1,302 @@ +// 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"; + +import { trailingJsonPayload } from "../../../../../test/helpers/host-process-harness"; + +import type { McpSourceEntry } from "../mcp-bridge-contracts"; +import { alignMcpAddTargetWithSharedHostPins } from "./shared-host-pins"; + +function entry(server: string, overrides: Partial = {}): McpSourceEntry { + return { + server, + agent: "deepagents", + url: `https://mcp.example.test/${server}`, + env: [`${server.toUpperCase()}_TOKEN`], + policyName: `mcp-bridge-${server}`, + allowedIps: ["8.8.8.8"], + ...overrides, + }; +} + +function align( + bridges: Record, + addresses: string[], + url = "https://mcp.example.test/two", + target: Partial<{ trustedPrivateHost: string }> = {}, +) { + return alignMcpAddTargetWithSharedHostPins({ + sandboxName: "alpha", + server: "two", + url, + target: { addresses, ...target }, + bridges, + }); +} + +describe("MCP shared-host address pins", () => { + it("leaves the target alone when no other server uses the host and port", () => { + const target = { addresses: ["1.1.1.1"] }; + expect( + alignMcpAddTargetWithSharedHostPins({ + sandboxName: "alpha", + server: "two", + url: "https://mcp.example.test/two", + target, + bridges: { + other: entry("other", { url: "https://elsewhere.example.test/mcp" }), + sameHostOtherPort: entry("sameHostOtherPort", { + url: "https://mcp.example.test:8443/mcp", + }), + }, + }), + ).toEqual({ ok: true, target, reusedFrom: [] }); + }); + + it("reuses the recorded pins when the new answer is a different address of the same host (#13800)", () => { + const aligned = align({ one: entry("one", { allowedIps: ["8.8.8.8"] }) }, ["1.1.1.1"]); + expect(aligned).toEqual({ + ok: true, + target: { addresses: ["8.8.8.8"] }, + reusedFrom: ["one"], + }); + }); + + it("treats an explicit default port as the same endpoint", () => { + const aligned = align({ one: entry("one", { url: "https://mcp.example.test:443/one" }) }, [ + "1.1.1.1", + ]); + expect(aligned).toMatchObject({ ok: true, reusedFrom: ["one"] }); + }); + + it("keeps the target when its answer already equals the recorded pins", () => { + const target = { addresses: ["1.1.1.1", "8.8.8.8"] }; + const aligned = alignMcpAddTargetWithSharedHostPins({ + sandboxName: "alpha", + server: "two", + url: "https://mcp.example.test/two", + target, + bridges: { one: entry("one", { allowedIps: ["8.8.8.8", "1.1.1.1"] }) }, + }); + expect(aligned).toEqual({ ok: true, target, reusedFrom: [] }); + }); + + it("reuses one pin set recorded by several servers", () => { + const aligned = align( + { one: entry("one"), three: entry("three", { allowedIps: ["8.8.8.8"] }) }, + ["1.1.1.1"], + ); + expect(aligned).toMatchObject({ ok: true, reusedFrom: ["one", "three"] }); + }); + + it("ignores the server being added and servers whose live policy points elsewhere", () => { + const aligned = align( + { + two: entry("two", { allowedIps: ["9.9.9.9"] }), + stale: entry("stale", { allowedIps: ["4.4.4.4"], policyConflict: "URL differs" }), + unpinned: entry("unpinned", { allowedIps: undefined }), + }, + ["1.1.1.1"], + ); + expect(aligned).toEqual({ ok: true, target: { addresses: ["1.1.1.1"] }, reusedFrom: [] }); + }); + + it("names the servers and pins when existing servers already disagree", () => { + const refused = align( + { + one: entry("one", { allowedIps: ["8.8.8.8"] }), + three: entry("three", { allowedIps: ["8.8.4.4"] }), + }, + ["1.1.1.1"], + ); + expect(refused).toMatchObject({ ok: false }); + expect(refused.ok ? "" : refused.message).toMatch( + /'two' was not added.*mcp\.example\.test:443.*'one': 8\.8\.8\.8; 'three': 8\.8\.4\.4.*nemoclaw alpha mcp remove /, + ); + }); + + it("refuses to reuse or replace trusted-private pins", () => { + const privateSibling = entry("one", { + url: "https://mcp.corp.example/one", + allowedIps: ["10.20.30.40"], + trustedPrivateHost: "mcp.corp.example", + }); + const privateTarget = align( + { one: privateSibling }, + ["10.20.30.41"], + "https://mcp.corp.example/two", + { trustedPrivateHost: "mcp.corp.example" }, + ); + expect(privateTarget.ok ? "" : privateTarget.message).toMatch( + /'one' records 10\.20\.30\.40.*does not reuse or replace trusted-private pins/, + ); + const publicTarget = align( + { one: privateSibling }, + ["1.1.1.1"], + "https://mcp.corp.example/two", + ); + expect(publicTarget.ok ? "" : publicTarget.message).toMatch( + /does not reuse or replace trusted-private pins/, + ); + }); + + it("accepts trusted-private siblings whose pins already match", () => { + const privateSibling = entry("one", { + url: "https://mcp.corp.example/one", + allowedIps: ["10.20.30.40"], + trustedPrivateHost: "mcp.corp.example", + }); + const target = { addresses: ["10.20.30.40"], trustedPrivateHost: "mcp.corp.example" }; + expect( + alignMcpAddTargetWithSharedHostPins({ + sandboxName: "alpha", + server: "two", + url: "https://mcp.corp.example/two", + target, + bridges: { one: privateSibling }, + }), + ).toEqual({ ok: true, target, reusedFrom: [] }); + }); + + it("rejects recorded public pins that are private or special-use", () => { + expect(() => align({ one: entry("one", { allowedIps: ["127.0.0.1"] }) }, ["1.1.1.1"])).toThrow( + /private, local, or special-use address pin/, + ); + }); +}); + +describe("mcp add on a host that rotates DNS answers (#13800)", () => { + function runAdd(options: { siblings: Record; dnsAnswer: string }) { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-mcp-shared-host-")); + const sourceRequireHook = path.resolve("test/helpers/onboard-script-mocks.cjs"); + const script = ` +process.env.HOME = ${JSON.stringify(home)}; +process.env.T_MCP_02 = "host-only-secret"; +require("node:dns/promises").lookup = async () => [{ address: ${JSON.stringify(options.dnsAnswer)}, family: 4 }]; +const replace = (module, name, value) => Object.defineProperty(module, name, { + configurable: true, enumerable: true, value, writable: true, +}); +const registry = require("./src/lib/state/registry.js"); +const policies = require("./src/lib/policy/index.js"); +const adapters = require("./src/lib/actions/sandbox/mcp-bridge-adapters.js"); +const policy = require("./src/lib/actions/sandbox/mcp-bridge-policy.js"); +const provider = require("./src/lib/actions/sandbox/mcp-bridge-provider.js"); +const processRecovery = require("./src/lib/actions/sandbox/process-recovery.js"); +const state = require("./src/lib/actions/sandbox/mcp-bridge-state.js"); +const sourceState = require("./src/lib/actions/sandbox/mcp-bridge-source.js"); +const validation = require("./src/lib/actions/sandbox/mcp-bridge-validation.js"); +let appliedTarget; +let mutated = false; +replace(policies, "getPresetContentGatewayState", () => "absent"); +replace(adapters, "assertAgentMcpMutationRuntimeCapability", () => {}); +replace(adapters, "inspectAgentAdapterRegistration", () => ({ state: "absent" })); +replace(adapters, "registerAgentAdapterAtCurrentCredentialRevision", () => { mutated = true; return "v1"; }); +replace(policy, "applyGeneratedPolicy", (_sandbox, _entry, target) => { mutated = true; appliedTarget = target; }); +replace(state, "ensureSandboxGatewaySelected", async () => {}); +replace(validation, "assertMcpCredentialBoundaryRuntimeVersion", () => {}); +replace(provider, "assertNoProviderCredentialCollisions", () => {}); +replace(provider, "getMcpProviderInspectionRuntimeSelection", () => ({ gatewayName: "nemoclaw-9090", workspace: "default" })); +replace(provider, "ensureMcpBridgeProviderProfile", () => {}); +replace(provider, "inspectMcpProvider", () => ({ + credentialKeys: null, exists: false, id: null, resourceVersion: null, type: null, +})); +replace(provider, "inspectMcpProviderAttachments", () => ({ attachments: [] })); +replace(provider, "upsertMcpProvider", () => { + mutated = true; + return { + action: "created", + inspection: { + credentialKeys: ["T_MCP_02"], exists: true, + id: "11111111-2222-4333-8444-555555555555", resourceVersion: 1, type: "nemoclaw-mcp-v1", + }, + }; +}); +replace(provider, "attachProvider", () => {}); +replace(provider, "refreshMcpProviderEnvironment", () => {}); +replace(provider, "observeMcpCredentialRevision", () => "v1"); +replace(provider, "waitForAttachedMcpCredential", () => "v1"); +replace(processRecovery, "restartSandboxGateway", () => ({ + ok: true, restarted: true, healthPassed: true, forwardRecovered: true, +})); +replace(sourceState, "inspectSourceBridgeState", () => ({ + bridges: ${JSON.stringify(options.siblings)}, sources: { native: {}, legacy: {} }, +})); +registry.registerSandbox({ + name: "alpha", agent: "openclaw", gatewayName: "nemoclaw-9090", gatewayPort: 9090, +}); +const finish = (error) => process.stdout.write(JSON.stringify({ + message: error ? String(error.message || error) : null, + appliedAddresses: appliedTarget ? appliedTarget.addresses : null, + mutated, +}), () => process.exit(0)); +require("./src/lib/actions/sandbox/mcp-bridge.js").addMcpBridge("alpha", { + server: "two", + url: "https://mcp.example.test/mcp/two", + env: [{ name: "T_MCP_02" }], +}).then(() => finish(null), finish); +`; + try { + const result = spawnSync(process.execPath, ["-e", script], { + cwd: process.cwd(), + encoding: "utf8", + env: { + ...process.env, + HOME: home, + NODE_OPTIONS: [process.env.NODE_OPTIONS, `--require=${sourceRequireHook}`] + .filter(Boolean) + .join(" "), + }, + timeout: 30_000, + }); + expect(result.status, `${result.stdout}\n${result.stderr}`).toBe(0); + expect(`${result.stdout}\n${result.stderr}`).not.toContain("host-only-secret"); + return trailingJsonPayload<{ + message: string | null; + appliedAddresses: string[] | null; + mutated: boolean; + }>(result.stdout); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + } + } + + const sibling = (server: string, allowedIps: string[]) => ({ + server, + agent: "openclaw", + adapter: "openclaw-config", + url: `https://mcp.example.test/mcp/${server}`, + env: [`${server.toUpperCase()}_TOKEN`], + allowedIps, + providerName: `nemoclaw-mcp-${server}`, + policyName: `mcp-bridge-${server}`, + source: "native", + }); + + it("applies the first server's pins instead of the second answer", { timeout: 40_000 }, () => { + const outcome = runAdd({ + siblings: { one: sibling("one", ["8.8.8.8"]) }, + dnsAnswer: "8.8.4.4", + }); + expect(outcome.message).toBeNull(); + expect(outcome.appliedAddresses).toEqual(["8.8.8.8"]); + }); + + it( + "fails before changing anything when the existing servers disagree", + { timeout: 40_000 }, + () => { + const outcome = runAdd({ + siblings: { one: sibling("one", ["8.8.8.8"]), three: sibling("three", ["9.9.9.9"]) }, + dnsAnswer: "8.8.4.4", + }); + expect(outcome.message).toMatch(/'one': 8\.8\.8\.8; 'three': 9\.9\.9\.9/); + expect(outcome.mutated).toBe(false); + }, + ); +}); diff --git a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts new file mode 100644 index 00000000000..3987731fce1 --- /dev/null +++ b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts @@ -0,0 +1,117 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { McpSourceEntry } from "../mcp-bridge-contracts"; +import { + parseMcpUrlWithValidatedTarget, + type McpBridgeTargetValidation, +} from "../mcp-bridge-url-validation"; + +export type McpSharedHostPinAlignment = + | { + ok: true; + target: McpBridgeTargetValidation; + /** Servers whose recorded pins the new server reuses; empty when nothing changed. */ + reusedFrom: string[]; + } + | { + ok: false; + /** Operator-facing reason the add cannot proceed; the caller reports it as a usage error. */ + message: string; + }; + +interface PinGroup { + pins: string[]; + servers: string[]; + trustedPrivate: boolean; +} + +function endpointAuthority(rawUrl: string): string | null { + try { + const parsed = new URL(rawUrl); + return `${parsed.hostname.toLowerCase()}:${parsed.port || "443"}`; + } catch { + return null; + } +} + +function sortedPins(addresses: readonly string[]): string[] { + return [...new Set(addresses.map((address) => address.toLowerCase()))].sort(); +} + +function describePins(pins: readonly string[]): string { + return pins.join(", "); +} + +function describeServers(servers: readonly string[]): string { + return servers.map((server) => `'${server}'`).join(", "); +} + +/** + * OpenShell rejects a sandbox policy when two endpoints share a host and port + * but list different `allowed_ips`. A host that publishes several DNS addresses + * can answer each `mcp add` differently, so a second server on the same host + * and port would be pinned to an address set that disagrees with the first. + * + * Keep the new server's pins identical to the ones already recorded for that + * host and port. Fail before any mutation when the recorded pins already + * disagree with each other, or when they cannot be reused safely. + */ +export function alignMcpAddTargetWithSharedHostPins(options: { + sandboxName: string; + server: string; + url: string; + target: McpBridgeTargetValidation; + bridges: Readonly>; +}): McpSharedHostPinAlignment { + const { sandboxName, server, url, target, bridges } = options; + const authority = endpointAuthority(url); + if (!authority) return { ok: true, target, reusedFrom: [] }; + + const groups = new Map(); + for (const entry of Object.values(bridges)) { + if ( + entry.server === server || + entry.policyConflict || + !entry.allowedIps?.length || + endpointAuthority(entry.url) !== authority + ) { + continue; + } + const pins = sortedPins(entry.allowedIps); + const key = pins.join(","); + const group = groups.get(key) ?? { pins, servers: [], trustedPrivate: false }; + group.servers.push(entry.server); + group.trustedPrivate ||= Boolean(entry.trustedPrivateHost); + groups.set(key, group); + } + if (groups.size === 0) return { ok: true, target, reusedFrom: [] }; + + const [firstGroup, ...otherGroups] = [...groups.values()]; + if (otherGroups.length > 0) { + const recorded = [firstGroup, ...otherGroups] + .map((group) => `${describeServers(group.servers)}: ${describePins(group.pins)}`) + .join("; "); + return { + ok: false, + message: `MCP server '${server}' was not added: managed servers on ${authority} already record different address pins (${recorded}). OpenShell rejects endpoints that share a host and port but list different allowed IPs. Remove the servers whose pins differ with \`nemoclaw ${sandboxName} mcp remove \`, then add them again so they record the same pins.`, + }; + } + + const requested = sortedPins(target.addresses); + if (requested.join(",") === firstGroup.pins.join(",")) + return { ok: true, target, reusedFrom: [] }; + + if (firstGroup.trustedPrivate || target.trustedPrivateHost) { + return { + ok: false, + message: `MCP server '${server}' was not added: it resolves to ${describePins(requested)} on ${authority}, but ${describeServers(firstGroup.servers)} record${firstGroup.servers.length === 1 ? "s" : ""} ${describePins(firstGroup.pins)}, and OpenShell rejects endpoints that share a host and port but list different allowed IPs. NemoClaw does not reuse or replace trusted-private pins on its own. Remove ${describeServers(firstGroup.servers)} with \`nemoclaw ${sandboxName} mcp remove \`, then add the servers on this host again.`, + }; + } + + const reused = { addresses: [...firstGroup.pins] }; + // The recorded pins were validated when they were written; check them again + // so a tampered or hand-edited policy cannot widen a new server's egress. + parseMcpUrlWithValidatedTarget(url, reused); + return { ok: true, target: reused, reusedFrom: [...firstGroup.servers] }; +} From 39776db411390f4c48b71ac5bb8178fbfe9db71a Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Mon, 16 Nov 2026 23:43:51 -0800 Subject: [PATCH 02/17] fix(mcp): complete shared-host recovery and integration coverage The shared-host refusal messages omitted retained providers, so removing and re-adding a server could leave its registration unrestored. Name the credential export and provider-cleanup prerequisites and link the owning recovery procedure. Exercise two credential-bound paths on one host with different add-time DNS inputs in the existing MCP suite. Apply real policies, inspect their pins, verify credential isolation and denial, and remove both registrations and providers. Keep deterministic fixture checks below live E2E. Record the approved assertion delta and retain the existing test size and time limits. Regenerate the stale Hermes startup bundle from its source. Register the shared-host helper and its existing fast support test under the MCP suite in the parity manifest, so CLI coverage validates their changed-source evidence. Refs #13800 Signed-off-by: Deepak Jain --- .../managed-startup-image-runtime.bundle | 12 +- ci/e2e-assertion-budget.json | 22 +- ci/e2e-assertion-growth-exceptions.json | 6 +- .../mcp-bridge/shared-host-pins.test.ts | 17 ++ .../sandbox/mcp-bridge/shared-host-pins.ts | 5 +- test/e2e/live/mcp-bridge-reliability.ts | 2 + test/e2e/live/mcp-bridge-servers.ts | 11 +- test/e2e/live/mcp-bridge-shared-host.ts | 265 ++++++++++++++++++ test/e2e/live/mcp-bridge.test.ts | 45 ++- test/e2e/mock-parity.json | 2 + .../support/mcp-bridge-shared-host.test.ts | 97 +++++++ 11 files changed, 440 insertions(+), 44 deletions(-) create mode 100644 test/e2e/live/mcp-bridge-shared-host.ts create mode 100644 test/e2e/support/mcp-bridge-shared-host.test.ts diff --git a/agents/hermes/managed-startup-image-runtime.bundle b/agents/hermes/managed-startup-image-runtime.bundle index 28a57f748da..d0d0238829d 100644 --- a/agents/hermes/managed-startup-image-runtime.bundle +++ b/agents/hermes/managed-startup-image-runtime.bundle @@ -11,7 +11,7 @@ try { identity(file) !== expected) process.exit(1); fs.unlinkSync(target); } catch { process.exit(1); } -`;function unlinkHermesGeneratedFile(target2){try{import_node_fs.default.unlinkSync(target2);return}catch(error){const code=error.code;if(typeof target2!=="string"||!GENERATED_FILES.has(target2)||code!=="EACCES"&&code!=="EPERM")throw error}trustedExecutable("/usr/bin/id");trustedExecutable(process.execPath);const uid=sandboxId("-u");const gid=sandboxId("-g");const source=import_node_fs.default.lstatSync(target2,{bigint:true});const parent=import_node_fs.default.lstatSync("/sandbox/.hermes",{bigint:true});if(!source.isFile()||source.isSymbolicLink()||source.nlink!==1n||source.uid!==BigInt(uid)||source.gid!==BigInt(gid)||(source.mode&0o777n)!==0o600n||!parent.isDirectory()||parent.isSymbolicLink()||parent.uid!==BigInt(uid)||parent.gid!==BigInt(gid)||(parent.mode&0o022n)!==0n&&(parent.mode&0o7777n)!==0o3770n)throw new Error("Hermes generated source has unsafe ownership or metadata");const result=(0,import_node_child_process.spawnSync)(process.execPath,["--input-type=commonjs","-e",REMOVE_AS_OWNER,"--",target2,identity(source),identity(parent)],{uid,gid,env:FIXED_ENV,encoding:"utf8",timeout:TIMEOUT_MS});if(result.error||result.status!==0){throw new Error("Hermes generated source cleanup failed as the sandbox user")}try{import_node_fs.default.lstatSync(target2)}catch(error){if(error.code==="ENOENT")return;throw new Error("Hermes generated source removal could not be verified")}throw new Error("Hermes generated source remains after cleanup")}var managed_startup_filesystem_default=Object.create(import_node_fs.default,{unlinkSync:{value:unlinkHermesGeneratedFile,enumerable:true}});var import_node_path3=__toESM(require("node:path"));var MAX_CORPORATE_CA_BYTES=128*1024;var PEM_CERTIFICATE_RE_GLOBAL=/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g;var deep_agents_code_runtime_identity_default={uid:999,gid:999};var DEEP_AGENTS_CODE_RUNTIME_IDENTITY=Object.freeze(deep_agents_code_runtime_identity_default);var DEEP_AGENTS_CODE_SANDBOX_USER=`${DEEP_AGENTS_CODE_RUNTIME_IDENTITY.uid}:${DEEP_AGENTS_CODE_RUNTIME_IDENTITY.gid}`;var SHIPPED_MANAGED_IMAGE_AGENTS=["openclaw","hermes","langchain-deepagents-code"];var CANDIDATE_MANAGED_IMAGE_AGENTS=["pi"];var MANAGED_IMAGE_AGENTS=[...SHIPPED_MANAGED_IMAGE_AGENTS,...CANDIDATE_MANAGED_IMAGE_AGENTS];var MANAGED_IMAGE_RUNTIME_IDENTITIES=Object.freeze({openclaw:Object.freeze({uid:998,gid:998,workdir:"/sandbox"}),hermes:Object.freeze({uid:998,gid:999,workdir:"/sandbox"}),"langchain-deepagents-code":Object.freeze({...DEEP_AGENTS_CODE_RUNTIME_IDENTITY,workdir:"/sandbox"}),pi:Object.freeze({uid:999,gid:999,workdir:"/sandbox"})});function managedImageRuntimeIdentity(agent){return MANAGED_IMAGE_RUNTIME_IDENTITIES[agent]}var import_node_buffer=require("node:buffer");var HERMES_SWITCHYARD_ROUTING_SCHEMA_VERSION=1;var HERMES_SWITCHYARD_ROUTE_ID="switchyard";var HERMES_SWITCHYARD_ROUTING_ENV="NEMOCLAW_HERMES_SWITCHYARD_ROUTING_B64";var HERMES_RELAY_PLUGINS_FILE="/usr/local/share/nemoclaw/hermes-relay-plugins.toml";var HERMES_RELAY_PLUGIN_STATE_FILE="/usr/local/share/nemoclaw/.dynamic-plugins.json";var HERMES_SWITCHYARD_DEPLOYMENT_FILE="/usr/local/share/nemoclaw/hermes-switchyard-v1.toml";var HERMES_SWITCHYARD_PLUGIN_MANIFEST="/opt/nemo-relay/plugins/switchyard/relay-plugin.toml";var HERMES_RELAY_PLUGINS_STAGING_FILE="hermes-relay-plugins.toml";var HERMES_RELAY_PLUGIN_STATE_STAGING_FILE="hermes-relay-plugin-state.json";var HERMES_SWITCHYARD_DEPLOYMENT_STAGING_FILE="hermes-switchyard-v1.toml";var MAX_MODEL_BYTES=512;var MAX_ROUTING_BYTES=8*1024;var STANDARD_BASE64_RE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;var MODEL_PATTERN=/^[A-Za-z0-9][A-Za-z0-9._:+/-]*$/u;var CREDENTIAL_ENV_PATTERN=/^[A-Z_][A-Z0-9_]*$/u;var HEADER_NAME_PATTERN=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;var SECRET_VALUE_PATTERNS=[/(?:nvapi|nvcf|sk-(?:proj-|ant-)?|ghp_|github_pat_|hf_|glpat-|gsk_|pypi-|tvly-)/u,/Bearer\s+/iu,/-----BEGIN (?:[A-Z0-9]+ )?PRIVATE KEY-----/u];var HOSTED_SWITCHYARD_PROVIDER_DEFINITIONS=HOSTED_NATIVE_PROVIDERS.filter(definition=>definition.logicalProvider!=="hermes-provider");var HERMES_SWITCHYARD_PROVIDERS=[NVIDIA_HOSTED_LOGICAL_PROVIDER,...HOSTED_SWITCHYARD_PROVIDER_DEFINITIONS.map(definition=>definition.logicalProvider)];var HermesSwitchyardRoutingError=class extends Error{constructor(message){super(`Invalid Hermes Switchyard routing: ${message}`);this.name="HermesSwitchyardRoutingError"}};function fail(message){throw new HermesSwitchyardRoutingError(message)}function record(value,where){if(typeof value!=="object"||value===null||Array.isArray(value)){return fail(`${where} must be an object`)}return value}function rejectUnknownKeys(value,allowed,where){const unknown=Object.keys(value).filter(key=>!allowed.has(key));if(unknown.length>0)fail(`${where} contains unknown fields`)}function provider(value,where){if(typeof value!=="string"||!HERMES_SWITCHYARD_PROVIDERS.includes(value)){return fail(`${where} must name an approved fixed hosted provider profile`)}return value}function model(value,where){if(typeof value!=="string"||import_node_buffer.Buffer.byteLength(value,"utf8")===0||import_node_buffer.Buffer.byteLength(value,"utf8")>MAX_MODEL_BYTES||!MODEL_PATTERN.test(value)||value.includes("://")||value.includes("//")||value.includes("..")||value.includes("${")||value.toLowerCase().includes("openshell:resolve")||SECRET_VALUE_PATTERNS.some(pattern=>pattern.test(value))){return fail(`${where} must be a bounded provider model ID without credentials or endpoints`)}return value}function target(value,where){const selection=record(value,where);rejectUnknownKeys(selection,new Set(["provider","model"]),where);return{provider:provider(selection.provider,`${where}.provider`),model:model(selection.model,`${where}.model`)}}function validateHermesSwitchyardRoutingIntent(value){const routing=record(value,"routing");rejectUnknownKeys(routing,new Set(["schemaVersion","routeId","efficient","capable","judge"]),"routing");if(routing.schemaVersion!==HERMES_SWITCHYARD_ROUTING_SCHEMA_VERSION){fail(`schemaVersion must be ${String(HERMES_SWITCHYARD_ROUTING_SCHEMA_VERSION)}`)}if(routing.routeId!==HERMES_SWITCHYARD_ROUTE_ID){fail(`routeId must be ${HERMES_SWITCHYARD_ROUTE_ID}`)}const efficient=target(routing.efficient,"routing.efficient");const capable=target(routing.capable,"routing.capable");if(efficient.model===capable.model){fail("efficient and capable must select different model IDs")}const requestedJudge=record(routing.judge,"routing.judge");let judge;if(requestedJudge.mode==="dedicated"){rejectUnknownKeys(requestedJudge,new Set(["mode","target","provider","model"]),"routing.judge");if(requestedJudge.target!=="judge")fail("routing.judge.target must be judge");const selection=target({provider:requestedJudge.provider,model:requestedJudge.model},"routing.judge");if(selection.model===capable.model||selection.model===efficient.model)fail("routing.judge must select a dedicated model ID");judge={mode:"dedicated",target:"judge",...selection}}else{rejectUnknownKeys(requestedJudge,new Set(["mode","target"]),"routing.judge");if(requestedJudge.mode!=="reuse-capable"||requestedJudge.target!=="capable")fail("routing.judge must reuse capable or select a dedicated judge");judge={mode:"reuse-capable",target:"capable"}}return{schemaVersion:HERMES_SWITCHYARD_ROUTING_SCHEMA_VERSION,routeId:HERMES_SWITCHYARD_ROUTE_ID,efficient,capable,judge}}function switchyardJudgeSelection(routing){return routing.judge.mode==="dedicated"?{provider:routing.judge.provider,model:routing.judge.model}:routing.capable}function switchyardPhysicalProviders(routing){return[...new Set([routing.efficient.provider,routing.capable.provider,switchyardJudgeSelection(routing).provider])]}function encodeHermesSwitchyardRoutingIntent(value){const routing=validateHermesSwitchyardRoutingIntent(value);return import_node_buffer.Buffer.from(JSON.stringify(routing),"utf8").toString("base64")}function decodeHermesSwitchyardRoutingIntent(encoded){if(encoded.length===0||encoded.length>Math.ceil(MAX_ROUTING_BYTES/3)*4||!STANDARD_BASE64_RE.test(encoded)){return fail("encoded routing transport is invalid")}const decoded=import_node_buffer.Buffer.from(encoded,"base64");if(decoded.length>MAX_ROUTING_BYTES||decoded.toString("base64")!==encoded){return fail("encoded routing transport is invalid")}let parsed;try{parsed=JSON.parse(decoded.toString("utf8"))}catch{return fail("encoded routing transport must contain JSON")}return validateHermesSwitchyardRoutingIntent(parsed)}function readHermesSwitchyardRoutingEnvironment(env){const encoded=env[HERMES_SWITCHYARD_ROUTING_ENV];return encoded===void 0||encoded===""?null:decodeHermesSwitchyardRoutingIntent(encoded)}function validateClientProfile(profile){let endpoint;try{endpoint=new URL(profile.baseUrl)}catch{return fail("provider profile has an invalid endpoint")}if(endpoint.protocol!=="https:"||endpoint.username||endpoint.password||endpoint.search||endpoint.hash||endpoint.hostname==="inference.local"||/[\\\s]/u.test(profile.baseUrl)||!CREDENTIAL_ENV_PATTERN.test(profile.apiKeyEnv)){return fail("provider profile is not safe for Switchyard onboarding")}for(const[name,value]of Object.entries(profile.extraHeaders)){if(!HEADER_NAME_PATTERN.test(name)||/[\r\n]/u.test(value)||["authorization","proxy-authorization","x-api-key"].includes(name.toLowerCase())){return fail("provider profile contains an unsafe Switchyard header")}}return profile}function switchyardClientProfile(providerId){if(providerId===NVIDIA_HOSTED_LOGICAL_PROVIDER){return validateClientProfile({baseUrl:NVIDIA_HOSTED_NATIVE_ENDPOINT,apiKeyEnv:NVIDIA_HOSTED_CREDENTIAL_ENV,format:"openai_chat",extraHeaders:{}})}const definition=hostedNativeProvider(providerId);if(!definition||definition.logicalProvider==="hermes-provider"){return fail("provider profile is not supported by Switchyard onboarding")}const agentConfig=nativeHostedAgentConfig(providerId,definition.endpoint);if(!agentConfig)return fail("provider profile has no managed credential binding");return validateClientProfile({baseUrl:definition.endpoint,apiKeyEnv:definition.credentialEnv,format:definition.api==="anthropic-messages"?"anthropic_messages":"openai_chat",extraHeaders:agentConfig.headers??{}})}function tomlString(value){return JSON.stringify(value)}function tomlStringMap(value){const fields=Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([name,headerValue])=>`${tomlString(name)} = ${tomlString(headerValue)}`);return`{ ${fields.join(", ")} }`}function clientAndTargetToml(role,selection,bindings){const client=switchyardClientProfile(selection.provider);const observed=bindings.providers.find(p=>p.providerId===bindings[role].providerId);if(!observed)return fail("a target has no observed provider binding");return[`[llm_clients.${role}]`,`format = ${tomlString(client.format)}`,`base_url = ${tomlString(observed.endpointUrl)}`,`api_key_env = ${tomlString(observed.credentialEnv)}`,"forward_auth = false",...Object.keys(client.extraHeaders).length>0?[`extra_headers = ${tomlStringMap(client.extraHeaders)}`]:[],"",`[targets.${role}]`,`id = ${tomlString(bindings[role].model)}`,`llm_client = ${tomlString(role)}`,""]}function serializeHermesSwitchyardRouting(value,observedBindings){const routing=validateHermesSwitchyardRoutingIntent(value);const bindings=validateSwitchyardProviderBindings(observedBindings,routing);const relayPluginsToml=["version = 1","","[[plugins.dynamic]]",`manifest = ${tomlString(HERMES_SWITCHYARD_PLUGIN_MANIFEST)}`,"","[plugins.dynamic.config]","priority = 0",`switchyard_config_path = ${tomlString(HERMES_SWITCHYARD_DEPLOYMENT_FILE)}`,"",'[plugins.policy.overrides."nvidia.switchyard"]','attestation = "integrity_only"',""].join("\n");const switchyardDeploymentToml=["schema_version = 1","",...clientAndTargetToml("efficient",routing.efficient,bindings),...clientAndTargetToml("capable",routing.capable,bindings),...routing.judge.mode==="dedicated"?clientAndTargetToml("judge",switchyardJudgeSelection(routing),bindings):[],`[routes.${routing.routeId}]`,`id = ${tomlString(routing.routeId)}`,'type = "llm_classifier"','mode = "capability"',`classifier_target = ${tomlString(routing.judge.target)}`,'strong_target = "capable"','weak_target = "efficient"',"base_threshold = 0.5",'classify_trigger = "new_session"',"message_hash_fallback = true",""].join("\n");const relayPluginStateJson=`${JSON.stringify({schema_version:1,records:[{metadata:{id:"nvidia.switchyard",kind:"rust_dynamic",generation:1},source:{manifest_ref:HERMES_SWITCHYARD_PLUGIN_MANIFEST},spec:{present:true,enabled:true},compatibility:{rust_dynamic:{relay:">=0.8.0, <1.0.0",native_api:"1"}},load:{rust_dynamic:{library:"libswitchyard_nemo_relay_plugin.so",symbol:"nemo_relay_register_plugin"}},status:{}}]},null,2)} +`;function unlinkHermesGeneratedFile(target2){try{import_node_fs.default.unlinkSync(target2);return}catch(error){const code=error.code;if(typeof target2!=="string"||!GENERATED_FILES.has(target2)||code!=="EACCES"&&code!=="EPERM")throw error}trustedExecutable("/usr/bin/id");trustedExecutable(process.execPath);const uid=sandboxId("-u");const gid=sandboxId("-g");const source=import_node_fs.default.lstatSync(target2,{bigint:true});const parent=import_node_fs.default.lstatSync("/sandbox/.hermes",{bigint:true});if(!source.isFile()||source.isSymbolicLink()||source.nlink!==1n||source.uid!==BigInt(uid)||source.gid!==BigInt(gid)||(source.mode&0o777n)!==0o600n||!parent.isDirectory()||parent.isSymbolicLink()||parent.uid!==BigInt(uid)||parent.gid!==BigInt(gid)||(parent.mode&0o022n)!==0n&&(parent.mode&0o7777n)!==0o3770n)throw new Error("Hermes generated source has unsafe ownership or metadata");const result=(0,import_node_child_process.spawnSync)(process.execPath,["--input-type=commonjs","-e",REMOVE_AS_OWNER,"--",target2,identity(source),identity(parent)],{uid,gid,env:FIXED_ENV,encoding:"utf8",timeout:TIMEOUT_MS});if(result.error||result.status!==0){throw new Error("Hermes generated source cleanup failed as the sandbox user")}try{import_node_fs.default.lstatSync(target2)}catch(error){if(error.code==="ENOENT")return;throw new Error("Hermes generated source removal could not be verified")}throw new Error("Hermes generated source remains after cleanup")}var managed_startup_filesystem_default=Object.create(import_node_fs.default,{unlinkSync:{value:unlinkHermesGeneratedFile,enumerable:true}});var import_node_path3=__toESM(require("node:path"));var MAX_CORPORATE_CA_BYTES=128*1024;var PEM_CERTIFICATE_RE_GLOBAL=/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g;var deep_agents_code_runtime_identity_default={uid:999,gid:999};var DEEP_AGENTS_CODE_RUNTIME_IDENTITY=Object.freeze(deep_agents_code_runtime_identity_default);var DEEP_AGENTS_CODE_SANDBOX_USER=`${DEEP_AGENTS_CODE_RUNTIME_IDENTITY.uid}:${DEEP_AGENTS_CODE_RUNTIME_IDENTITY.gid}`;var SHIPPED_MANAGED_IMAGE_AGENTS=["openclaw","hermes","langchain-deepagents-code"];var CANDIDATE_MANAGED_IMAGE_AGENTS=["pi"];var MANAGED_IMAGE_AGENTS=[...SHIPPED_MANAGED_IMAGE_AGENTS,...CANDIDATE_MANAGED_IMAGE_AGENTS];var MANAGED_IMAGE_RUNTIME_IDENTITIES=Object.freeze({openclaw:Object.freeze({uid:998,gid:998,workdir:"/sandbox"}),hermes:Object.freeze({uid:998,gid:999,workdir:"/sandbox"}),"langchain-deepagents-code":Object.freeze({...DEEP_AGENTS_CODE_RUNTIME_IDENTITY,workdir:"/sandbox"}),pi:Object.freeze({uid:999,gid:999,workdir:"/sandbox"})});function managedImageRuntimeIdentity(agent){return MANAGED_IMAGE_RUNTIME_IDENTITIES[agent]}var import_node_buffer=require("node:buffer");var HERMES_SWITCHYARD_ROUTING_SCHEMA_VERSION=1;var HERMES_SWITCHYARD_ROUTE_ID="switchyard";var HERMES_SWITCHYARD_ROUTING_ENV="NEMOCLAW_HERMES_SWITCHYARD_ROUTING_B64";var HERMES_RELAY_PLUGINS_FILE="/usr/local/share/nemoclaw/hermes-relay-plugins.toml";var HERMES_RELAY_PLUGIN_STATE_FILE="/usr/local/share/nemoclaw/.dynamic-plugins.json";var HERMES_SWITCHYARD_DEPLOYMENT_FILE="/usr/local/share/nemoclaw/hermes-switchyard-v1.toml";var HERMES_SWITCHYARD_PLUGIN_MANIFEST="/opt/nemo-relay/plugins/switchyard/relay-plugin.toml";var HERMES_RELAY_PLUGINS_STAGING_FILE="hermes-relay-plugins.toml";var HERMES_RELAY_PLUGIN_STATE_STAGING_FILE="hermes-relay-plugin-state.json";var HERMES_SWITCHYARD_DEPLOYMENT_STAGING_FILE="hermes-switchyard-v1.toml";var MAX_MODEL_BYTES=512;var MAX_ROUTING_BYTES=8*1024;var STANDARD_BASE64_RE=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;var MODEL_PATTERN=/^[A-Za-z0-9][A-Za-z0-9._:+/-]*$/u;var CREDENTIAL_ENV_PATTERN=/^[A-Z_][A-Z0-9_]*$/u;var HEADER_NAME_PATTERN=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u;var SECRET_VALUE_PATTERNS=[/(?:nvapi|nvcf|sk-(?:proj-|ant-)?|ghp_|github_pat_|hf_|glpat-|gsk_|pypi-|tvly-)/u,/Bearer\s+/iu,/-----BEGIN (?:[A-Z0-9]+ )?PRIVATE KEY-----/u];var HOSTED_SWITCHYARD_PROVIDER_DEFINITIONS=HOSTED_NATIVE_PROVIDERS.filter(definition=>definition.logicalProvider!=="hermes-provider");var HERMES_SWITCHYARD_PROVIDERS=[NVIDIA_HOSTED_LOGICAL_PROVIDER,...HOSTED_SWITCHYARD_PROVIDER_DEFINITIONS.map(definition=>definition.logicalProvider)];var HermesSwitchyardRoutingError=class extends Error{constructor(message){super(`Invalid Hermes Switchyard routing: ${message}`);this.name="HermesSwitchyardRoutingError"}};function fail(message){throw new HermesSwitchyardRoutingError(message)}function record(value,where){if(typeof value!=="object"||value===null||Array.isArray(value)){return fail(`${where} must be an object`)}return value}function rejectUnknownKeys(value,allowed,where){const unknown=Object.keys(value).filter(key=>!allowed.has(key));if(unknown.length>0)fail(`${where} contains unknown fields`)}function provider(value,where){if(typeof value!=="string"||!HERMES_SWITCHYARD_PROVIDERS.includes(value)){return fail(`${where} must name an approved fixed hosted provider profile`)}return value}function model(value,where){if(typeof value!=="string"||import_node_buffer.Buffer.byteLength(value,"utf8")===0||import_node_buffer.Buffer.byteLength(value,"utf8")>MAX_MODEL_BYTES||!MODEL_PATTERN.test(value)||value.includes("://")||value.includes("//")||value.includes("..")||value.includes("${")||value.toLowerCase().includes("openshell:resolve")||SECRET_VALUE_PATTERNS.some(pattern=>pattern.test(value))){return fail(`${where} must be a bounded provider model ID without credentials or endpoints`)}return value}function target(value,where){const selection=record(value,where);rejectUnknownKeys(selection,new Set(["provider","model"]),where);return{provider:provider(selection.provider,`${where}.provider`),model:model(selection.model,`${where}.model`)}}function validateHermesSwitchyardRoutingIntent(value){const routing=record(value,"routing");rejectUnknownKeys(routing,new Set(["schemaVersion","routeId","efficient","capable","judge"]),"routing");if(routing.schemaVersion!==HERMES_SWITCHYARD_ROUTING_SCHEMA_VERSION){fail(`schemaVersion must be ${String(HERMES_SWITCHYARD_ROUTING_SCHEMA_VERSION)}`)}if(routing.routeId!==HERMES_SWITCHYARD_ROUTE_ID){fail(`routeId must be ${HERMES_SWITCHYARD_ROUTE_ID}`)}const efficient=target(routing.efficient,"routing.efficient");const capable=target(routing.capable,"routing.capable");if(efficient.model===capable.model){fail("efficient and capable must select different model IDs")}const requestedJudge=record(routing.judge,"routing.judge");let judge;if(requestedJudge.mode==="dedicated"){rejectUnknownKeys(requestedJudge,new Set(["mode","target","provider","model"]),"routing.judge");if(requestedJudge.target!=="judge")fail("routing.judge.target must be judge");const selection=target({provider:requestedJudge.provider,model:requestedJudge.model},"routing.judge");if(selection.model===capable.model||selection.model===efficient.model)fail("routing.judge must select a dedicated model ID");judge={mode:"dedicated",target:"judge",...selection}}else{rejectUnknownKeys(requestedJudge,new Set(["mode","target"]),"routing.judge");if(requestedJudge.mode!=="reuse-capable"||requestedJudge.target!=="capable")fail("routing.judge must reuse capable or select a dedicated judge");judge={mode:"reuse-capable",target:"capable"}}return{schemaVersion:HERMES_SWITCHYARD_ROUTING_SCHEMA_VERSION,routeId:HERMES_SWITCHYARD_ROUTE_ID,efficient,capable,judge}}function switchyardJudgeSelection(routing){return routing.judge.mode==="dedicated"?{provider:routing.judge.provider,model:routing.judge.model}:routing.capable}function switchyardPhysicalProviders(routing){return[...new Set([routing.efficient.provider,routing.capable.provider,switchyardJudgeSelection(routing).provider])]}function encodeHermesSwitchyardRoutingIntent(value){const routing=validateHermesSwitchyardRoutingIntent(value);return import_node_buffer.Buffer.from(JSON.stringify(routing),"utf8").toString("base64")}function decodeHermesSwitchyardRoutingIntent(encoded){if(encoded.length===0||encoded.length>Math.ceil(MAX_ROUTING_BYTES/3)*4||!STANDARD_BASE64_RE.test(encoded)){return fail("encoded routing transport is invalid")}const decoded=import_node_buffer.Buffer.from(encoded,"base64");if(decoded.length>MAX_ROUTING_BYTES||decoded.toString("base64")!==encoded){return fail("encoded routing transport is invalid")}let parsed;try{parsed=JSON.parse(decoded.toString("utf8"))}catch{return fail("encoded routing transport must contain JSON")}return validateHermesSwitchyardRoutingIntent(parsed)}function readHermesSwitchyardRoutingEnvironment(env){const encoded=env[HERMES_SWITCHYARD_ROUTING_ENV];return encoded===void 0||encoded===""?null:decodeHermesSwitchyardRoutingIntent(encoded)}function validateClientProfile(profile){let endpoint;try{endpoint=new URL(profile.baseUrl)}catch{return fail("provider profile has an invalid endpoint")}if(endpoint.protocol!=="https:"||endpoint.username||endpoint.password||endpoint.search||endpoint.hash||endpoint.hostname==="inference.local"||/[\\\s]/u.test(profile.baseUrl)||!CREDENTIAL_ENV_PATTERN.test(profile.apiKeyEnv)){return fail("provider profile is not safe for Switchyard onboarding")}for(const[name,value]of Object.entries(profile.extraHeaders)){if(!HEADER_NAME_PATTERN.test(name)||/[\r\n]/u.test(value)||["authorization","proxy-authorization","x-api-key"].includes(name.toLowerCase())){return fail("provider profile contains an unsafe Switchyard header")}}return profile}function switchyardClientProfile(providerId){if(providerId===NVIDIA_HOSTED_LOGICAL_PROVIDER){return validateClientProfile({baseUrl:NVIDIA_HOSTED_NATIVE_ENDPOINT,apiKeyEnv:NVIDIA_HOSTED_CREDENTIAL_ENV,format:"openai_chat",extraHeaders:{}})}const definition=hostedNativeProvider(providerId);if(!definition||definition.logicalProvider==="hermes-provider"){return fail("provider profile is not supported by Switchyard onboarding")}const agentConfig=nativeHostedAgentConfig(providerId,definition.endpoint);if(!agentConfig)return fail("provider profile has no managed credential binding");return validateClientProfile({baseUrl:definition.endpoint,apiKeyEnv:definition.credentialEnv,format:definition.api==="anthropic-messages"?"anthropic_messages":"openai_chat",extraHeaders:agentConfig.headers??{}})}function tomlString(value){return JSON.stringify(value)}function tomlStringMap(value){const fields=Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([name,headerValue])=>`${tomlString(name)} = ${tomlString(headerValue)}`);return`{ ${fields.join(", ")} }`}function clientAndTargetToml(role,selection,bindings){const client=switchyardClientProfile(selection.provider);const observed=bindings.providers.find(p=>p.providerId===bindings[role].providerId);if(!observed)return fail("a target has no observed provider binding");return[`[llm_clients.${role}]`,`format = ${tomlString(client.format)}`,`base_url = ${tomlString(observed.endpointUrl)}`,`api_key_env = ${tomlString(observed.credentialEnv)}`,"forward_auth = false","timeout_ms = 120000","max_retries = 0",...Object.keys(client.extraHeaders).length>0?[`extra_headers = ${tomlStringMap(client.extraHeaders)}`]:[],"",`[targets.${role}]`,`id = ${tomlString(bindings[role].model)}`,`llm_client = ${tomlString(role)}`,""]}function serializeHermesSwitchyardRouting(value,observedBindings){const routing=validateHermesSwitchyardRoutingIntent(value);const bindings=validateSwitchyardProviderBindings(observedBindings,routing);const relayPluginsToml=["version = 1","","[[plugins.dynamic]]",`manifest = ${tomlString(HERMES_SWITCHYARD_PLUGIN_MANIFEST)}`,"","[plugins.dynamic.config]","priority = 0",`switchyard_config_path = ${tomlString(HERMES_SWITCHYARD_DEPLOYMENT_FILE)}`,"",'[plugins.policy.overrides."nvidia.switchyard"]','attestation = "integrity_only"',""].join("\n");const switchyardDeploymentToml=["schema_version = 1","",...clientAndTargetToml("efficient",routing.efficient,bindings),...clientAndTargetToml("capable",routing.capable,bindings),...routing.judge.mode==="dedicated"?clientAndTargetToml("judge",switchyardJudgeSelection(routing),bindings):[],`[routes.${routing.routeId}]`,`id = ${tomlString(routing.routeId)}`,'type = "llm_classifier"','mode = "capability"',`classifier_target = ${tomlString(routing.judge.target)}`,'strong_target = "capable"','weak_target = "efficient"',"base_threshold = 0.5",'classify_trigger = "new_session"',"message_hash_fallback = true",""].join("\n");const relayPluginStateJson=`${JSON.stringify({schema_version:1,records:[{metadata:{id:"nvidia.switchyard",kind:"rust_dynamic",generation:1},source:{manifest_ref:HERMES_SWITCHYARD_PLUGIN_MANIFEST},spec:{present:true,enabled:true},compatibility:{rust_dynamic:{relay:">=0.8.0, <1.0.0",native_api:"1"}},load:{rust_dynamic:{library:"libswitchyard_nemo_relay_plugin.so",symbol:"nemo_relay_register_plugin"}},status:{}}]},null,2)} `;return{relayPluginsToml,relayPluginStateJson,switchyardDeploymentToml}}var HERMES_SWITCHYARD_BINDINGS_ENV="NEMOCLAW_HERMES_SWITCHYARD_BINDINGS_B64";function validateSwitchyardBindingState(value){const state=bindingRecord(value,["routing","bindings"]);const routing=validateHermesSwitchyardRoutingIntent(state.routing);return{routing,bindings:validateSwitchyardProviderBindings(state.bindings,routing)}}var SwitchyardProviderBindingError=class extends Error{constructor(message){super("Hermes Switchyard provider binding: "+message);this.name="SwitchyardProviderBindingError"}};function failBinding(){throw new SwitchyardProviderBindingError("missing, invalid, or ambiguous provider state.")}function bindingRecord(value,keys){if(!value||typeof value!=="object"||Array.isArray(value))return failBinding();const result=value;if(Object.keys(result).length!==keys.length||keys.some(key=>!Object.hasOwn(result,key)))return failBinding();return result}function isSwitchyardProviderIdentity(value){return typeof value==="string"&&/^[A-Za-z0-9][A-Za-z0-9_-]{0,255}$/u.test(value)&&!/(?:nvapi-|nvcf-|sk-|ghp_|github_pat_)/u.test(value)}function validateSwitchyardProviderBindings(value,intent){const routing=validateHermesSwitchyardRoutingIntent(intent);const bindings=bindingRecord(value,["schemaVersion","providers","efficient","capable","judge"]);const logicalProviders=switchyardPhysicalProviders(routing);if(bindings.schemaVersion!==1||!Array.isArray(bindings.providers)||bindings.providers.length!==logicalProviders.length)return failBinding();const providers=bindings.providers.map((input,index)=>{const entry=bindingRecord(input,["logicalProvider","providerName","providerId","resourceVersion","profileId","profileSha256","endpointUrl","credentialEnv"]);const logicalProvider=logicalProviders[index];const definition=hostedNativeProvider(logicalProvider);const profileId=logicalProvider==="nvidia-prod"?NVIDIA_HOSTED_NATIVE_PROFILE_ID:definition?.profileId;const endpointUrl=logicalProvider==="nvidia-prod"?NVIDIA_HOSTED_NATIVE_ENDPOINT:definition?.endpoint;const credentialEnv=logicalProvider==="nvidia-prod"?NVIDIA_HOSTED_CREDENTIAL_ENV:definition?.credentialEnv;if(!logicalProvider||!profileId||!endpointUrl||!credentialEnv||entry.logicalProvider!==logicalProvider||entry.profileId!==profileId||entry.endpointUrl!==endpointUrl||entry.credentialEnv!==credentialEnv||typeof entry.providerName!=="string"||!/^[a-z0-9][a-z0-9-]{0,62}$/u.test(entry.providerName)||!isSwitchyardProviderIdentity(entry.providerId)||typeof entry.resourceVersion!=="number"||!Number.isSafeInteger(entry.resourceVersion)||entry.resourceVersion<1||typeof entry.profileSha256!=="string"||!/^[a-f0-9]{64}$/u.test(entry.profileSha256))return failBinding();return{logicalProvider,providerName:entry.providerName,providerId:entry.providerId,resourceVersion:entry.resourceVersion,profileId,profileSha256:entry.profileSha256,endpointUrl,credentialEnv}});if(new Set(providers.map(p=>p.providerId)).size!==providers.length||new Set(providers.map(p=>p.providerName)).size!==providers.length)return failBinding();const role=key=>{const selected=routing[key];const binding=providers.find(p=>p.logicalProvider===selected.provider);const entry=bindingRecord(bindings[key],["providerId","model"]);if(!binding||entry.providerId!==binding.providerId||entry.model!==selected.model)return failBinding();return{providerId:binding.providerId,model:selected.model}};const efficient=role("efficient");const capable=role("capable");const judge=bindingRecord(bindings.judge,["providerId","model","mode","target"]);const judgeSelection=switchyardJudgeSelection(routing);const judgeProvider=providers.find(p=>p.logicalProvider===judgeSelection.provider);if(!judgeProvider||judge.mode!==routing.judge.mode||judge.target!==routing.judge.target||judge.providerId!==judgeProvider.providerId||judge.model!==judgeSelection.model)return failBinding();return{schemaVersion:1,providers,efficient,capable,judge:{providerId:judgeProvider.providerId,model:judgeSelection.model,mode:routing.judge.mode,target:routing.judge.target}}}function encodeSwitchyardProviderBindings(value,routing){return import_node_buffer.Buffer.from(JSON.stringify(validateSwitchyardProviderBindings(value,routing)),"utf8").toString("base64")}function readSwitchyardProviderBindingsEnvironment(env,routing){const encoded=env[HERMES_SWITCHYARD_BINDINGS_ENV];if(!encoded||encoded.length>16384||!/^[A-Za-z0-9+/]+={0,2}$/u.test(encoded))return failBinding();let parsed;try{const bytes=import_node_buffer.Buffer.from(encoded,"base64");if(bytes.toString("base64")!==encoded)return failBinding();parsed=JSON.parse(bytes.toString("utf8"))}catch{return failBinding()}return validateSwitchyardProviderBindings(parsed,routing)}function assertSwitchyardRootApplyEnvironment(env,state){const validated=validateSwitchyardBindingState(state);for(const provider2 of validated.bindings.providers){if(env[provider2.credentialEnv]!==void 0)throw new SwitchyardProviderBindingError("managed startup must not supply provider credentials or credential placeholders.")}}var import_node_buffer3=require("node:buffer");var PROVIDERLESS_INFERENCE_ENV=Object.freeze({NEMOCLAW_MODEL:"",NEMOCLAW_INFERENCE_PROVIDER_ID:"",NEMOCLAW_UPSTREAM_PROVIDER:"",NEMOCLAW_INFERENCE_BASE_URL:"",NEMOCLAW_INFERENCE_API:""});function isObjectRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}var ChannelManifestRegistry=class{manifests=new Map;constructor(manifests=[]){for(const manifest of manifests){this.register(manifest)}}register(manifest){if(this.manifests.has(manifest.id)){throw new Error(`Duplicate channel manifest id '${manifest.id}'`)}this.manifests.set(manifest.id,manifest);return this}get(channelId){return this.manifests.get(channelId)}list(){return Array.from(this.manifests.values())}listAvailable(ctx={}){const supportedChannelIds=Array.isArray(ctx.supportedChannelIds)?new Set(ctx.supportedChannelIds):null;return this.list().filter(manifest=>{if(ctx.agent&&!manifest.supportedAgents.includes(ctx.agent)){return false}if(supportedChannelIds&&!supportedChannelIds.has(manifest.id)){return false}return true})}};function createChannelManifestRegistry(manifests=[]){return new ChannelManifestRegistry(manifests)}var discordManifest={schemaVersion:1,id:"discord",displayName:"Discord",description:"Discord bot messaging",supportedAgents:["openclaw","hermes"],state:{hermes:["platforms/discord"]},auth:{mode:"token-paste"},inputs:[{id:"botToken",kind:"secret",required:true,envKey:"DISCORD_BOT_TOKEN",formatPattern:"^(?!$)\\S+$",formatHint:"Replace the documentation placeholder with your real Discord bot token.",prompt:{label:"Discord Bot Token",help:"Discord Developer Portal \u2192 Applications \u2192 Bot \u2192 Reset/Copy Token."}},{id:"serverId",kind:"config",required:false,envKey:"DISCORD_SERVER_ID",statePath:"discordGuilds.serverId",prompt:{label:"Discord Server ID (for guild workspace access)",help:"Enable Developer Mode in Discord, then right-click your server and copy the Server ID.",emptyValueMessage:"guild channels stay disabled"}},{id:"requireMention",kind:"config",required:false,envKey:"DISCORD_REQUIRE_MENTION",statePath:"discordGuilds.requireMention",promptWhenInput:"serverId",validValues:["0","1"],defaultValue:"1",prompt:{label:"Discord mention mode",help:"Choose whether the bot should reply only when @mentioned or to all messages in this server."}},{id:"userId",kind:"config",required:false,envKey:"DISCORD_USER_ID",statePath:"discordGuilds.userIds",promptWhenInput:"serverId",prompt:{label:"Discord User ID (optional guild allowlist)",help:"Optional: enable Developer Mode in Discord, then right-click your user/avatar and copy the User ID. Leave blank to allow any member of the configured server to message the bot.",emptyValueMessage:"any member in the configured server can message the bot"}}],credentials:[{id:"discordBotToken",sourceInput:"botToken",providerName:"{sandboxName}-discord-bridge",providerEnvKey:"DISCORD_BOT_TOKEN",placeholder:"openshell:resolve:env:DISCORD_BOT_TOKEN"}],policyPresets:[{name:"discord",requiredAtCreate:true,validationWarningLines:["For Discord preset validation, do not use curl as the success signal:","curl is not in the preset binary allowlist, so curl probes can fail even","when the policy is working. Validate the configured messaging bridge/gateway path.",'DNS-only checks such as dns.resolve("gateway.discord.gg")',"can also be inconclusive behind a proxy.","The agent-specific gateway probe prints an HTTP status when it reaches Discord.","Any HTTP response confirms reachability. A transport error or OpenShell policy","denial means validation failed."],validationWarningLinesByAgent:{openclaw:["OpenClaw validation uses its Node runtime:",`node -e "require('node:https').get('https://discord.com/api/v10/gateway',r=>console.log(r.statusCode)).on('error',e=>{console.error(e.message);process.exitCode=1})"`],hermes:["Hermes validation uses its virtual-environment Python runtime:",`nemohermes exec -- /opt/hermes/.venv/bin/python -c "import urllib.error, urllib.request; u='https://discord.com/api/v10/gateway'; try: print(urllib.request.urlopen(u, timeout=20).status) except urllib.error.HTTPError as error: print(error.code)"`]}}],render:[{id:"discord-openclaw-channel",kind:"json-fragment",agent:"openclaw",target:"openclaw.json",fragment:{path:"channels.discord",value:{enabled:true,accounts:{default:{enabled:true,healthMonitor:{enabled:false},proxy:"{{discordProxyUrl}}",dmPolicy:"{{discord.allowedUsers.dmPolicy}}",allowFrom:"{{discord.allowedUsers.values}}"}}}}},{id:"discord-openclaw-guilds",kind:"json-fragment",agent:"openclaw",target:"openclaw.json",when:"{{discord.hasGuilds}}",fragment:{path:"channels.discord",value:{groupPolicy:"allowlist",guilds:"{{discord.guilds}}"}}},{id:"discord-openclaw-plugin",kind:"json-fragment",agent:"openclaw",target:"openclaw.json",fragment:{path:"plugins.entries.discord",value:{enabled:true}}},{id:"discord-hermes-env",kind:"env-lines",agent:"hermes",target:"~/.hermes/.env",lines:["NEMOCLAW_DISCORD_GUILD_IDS={{discord.guildIds.csv}}","DISCORD_ALLOWED_USERS={{discord.allowedUsers.csv}}","DISCORD_ALLOW_ALL_USERS={{discord.allowAllUsers}}"]},{id:"discord-hermes-config",kind:"json-fragment",agent:"hermes",target:"~/.hermes/config.yaml",fragment:{path:"discord",value:{require_mention:"{{discord.requireMention}}",free_response_channels:"",allowed_channels:"",auto_thread:true,reactions:true,channel_prompts:{}}}},{id:"discord-hermes-platform",kind:"json-fragment",agent:"hermes",target:"~/.hermes/config.yaml",fragment:{path:"platforms.discord",value:{enabled:true}}}],runtime:{openclaw:{channelName:"discord",visibility:{configKeys:["discord"],logPatterns:["discord"]}}},agentPackages:[{id:"openclawPluginPackage",agent:"openclaw",manager:"openclaw-plugin",spec:"npm:@openclaw/discord@{{openclaw.version}}",pin:true,integrityByVersion:{"2026.10.5":"sha512-Gy2FmMF7cnCyhodvYQHVtOPoPm7daZ1djSS7ymLHsJ5nWIO9GFsW8Y/mlnZAMSGWlgmWedERkVbVDMlli9vgOw==","2026.9.2":"sha512-j+fSHxbXA+DSxwbL8SvtsDNL6tvBX4+RmH+EerVW6dCbeIwSconXj6J/+AaN/mhzZI4g0jPPj30TUhdCRRbc2w==","2026.9.5":"sha512-kPEbPiYAnJqxqLHqBnZCr3zowsxzboW0Q7ZdqX52X7IENLrU4CBdK4+ndqzQf+255ilffrYBTDrHBg8a137cgQ==","2026.9.1":"sha512-qNmN2a8A9dET4igPp0RML171sEn8PDMyNCYNp/DqcJ4tn3XTHpacSOTkqBmv5yXTycJRC9rfFP8FT/SdW0Rldg=="},tarballUrlByVersion:{"2026.10.5":"https://registry.npmjs.org/@openclaw/discord/-/discord-2026.10.5.tgz","2026.9.2":"https://registry.npmjs.org/@openclaw/discord/-/discord-2026.9.2.tgz","2026.9.5":"https://registry.npmjs.org/@openclaw/discord/-/discord-2026.9.5.tgz","2026.9.1":"https://registry.npmjs.org/@openclaw/discord/-/discord-2026.9.1.tgz"},required:true}],hooks:[{id:"discord-hermes-status-health",phase:"status",handler:"discord.statusHealth",agents:["hermes"],outputs:[{id:"channelHealth",kind:"status"}]},{id:"discord-openclaw-bridge-health",phase:"health-check",handler:"discord.openclawBridgeHealth",agents:["openclaw"],onFailure:"abort"},{id:"discord-token-paste",phase:"enroll",handler:"discord.tokenPaste",outputs:[{id:"botToken",kind:"secret",required:true}],onFailure:"skip-channel"},{id:"discord-config-prompt",phase:"enroll",handler:"common.configPrompt",outputs:[{id:"serverId",kind:"config"},{id:"requireMention",kind:"config"},{id:"userId",kind:"config"}]}]};var googlechatManifest={schemaVersion:1,id:"googlechat",displayName:"Google Chat",description:"Google Chat (Chat API) bot messaging (experimental)",supportedAgents:["openclaw","hermes"],state:{hermes:["platforms/googlechat"]},auth:{mode:"token-paste"},inputs:[{id:"serviceAccount",kind:"secret",required:true,envKey:"GOOGLECHAT_SERVICE_ACCOUNT",allowLineBreaks:true,maskCap:40,formatHint:"Paste the entire service-account JSON key on one line (minified), or set GOOGLECHAT_SERVICE_ACCOUNT to the downloaded JSON, including line breaks.",maxTokenAttempts:3,prompt:{label:"Google Chat service account JSON",help:["\u2503 GOOGLE CHAT \u2014 service account key","\u2503","\u2503 Google Cloud Console \u2192 IAM & Admin \u2192 Service Accounts","\u2503 \u2192 your bot's SA \u2192 Keys \u2192 Add key \u2192 Create new key \u2192 JSON","\u2503","\u2503 A .json file downloads. Paste its contents below as ONE line (minified).","\u2503 Alternatively, GOOGLECHAT_SERVICE_ACCOUNT accepts the formatted JSON file contents.",""].join("\n")}},{id:"audienceType",kind:"config",required:false,envKey:"GOOGLECHAT_AUDIENCE_TYPE",statePath:"googlechatConfig.audienceType",validValues:["app-url","project-number"],defaultValue:"app-url"},{id:"audience",kind:"config",required:false,envKey:"GOOGLECHAT_AUDIENCE",statePath:"googlechatConfig.audience",prompt:{label:"Google Chat webhook audience",help:"Usually filled automatically from the public tunnel URL. For audienceType 'project-number', enter your GCP project number instead.",emptyValueMessage:"inbound webhook verification will be unconfigured"}},{id:"appPrincipal",kind:"config",required:false,envKey:"GOOGLECHAT_APP_PRINCIPAL",statePath:"googlechatConfig.appPrincipal",formatPattern:"^[0-9]{6,32}$",formatHint:"appPrincipal is the add-on's numeric OAuth client ID (uniqueId, ~21 digits), not an email.",prompt:{label:"Google Chat appPrincipal",help:[" Workspace account \u2192 leave blank, done."," Personal Gmail \u2192 needs the add-on's ~21-digit ID (not an email), stable across rebuilds.",""," If you already know it, paste it at the prompt and you're done."," If not, leave it blank \u2014 the first DM reveals it once the sandbox is live:",""," 1. Watch the gateway log:",' nemoclaw logs --follow | grep "unexpected add-on principal"'," 2. DM the bot once \u2014 it won't reply yet, that's expected. The log prints:"," unexpected add-on principal: "," 3. Save that and rebuild:"," GOOGLECHAT_APP_PRINCIPAL= nemoclaw channels add googlechat"," nemoclaw rebuild --yes"].join("\n"),emptyValueMessage:"Workspace accounts do not need it; personal accounts must set it later"}},{id:"allowFrom",kind:"config",required:false,envKey:"GOOGLECHAT_ALLOWED_USERS",statePath:"allowedIds.googlechat",prompt:{label:"Google Chat DM allowlist (comma-separated)",help:["Optional: restrict who can DM the bot."," OpenClaw: users/NNN (emails ignored)"," Hermes: email (users/NNN ignored)"," Blank: pairing mode (recommended) \u2014 OpenClaw's pairing reply shows your users/NNN"," Filling this switches DM policy to allowlist \u2014 a wrong-form entry is dropped silently, with no pairing code."].join("\n"),emptyValueMessage:"bot will require manual pairing"}},{id:"projectId",kind:"config",required:false,envKey:"GOOGLE_CHAT_PROJECT_ID",statePath:"googlechatConfig.projectId",prompt:{label:"Google Chat GCP project ID (Hermes Pub/Sub pull)",help:"The Google Cloud project that owns the Pub/Sub subscription Hermes pulls Chat events from. OpenClaw ignores this.",emptyValueMessage:"required for the Hermes Google Chat channel"}},{id:"subscriptionName",kind:"config",required:false,envKey:"GOOGLE_CHAT_SUBSCRIPTION_NAME",statePath:"googlechatConfig.subscriptionName",prompt:{label:"Google Chat Pub/Sub subscription (projects/

/subscriptions/)",help:["The pull subscription bound to the Chat events topic. Hermes pulls from it over the Pub/Sub REST API; the gateway-minted token is scoped to both chat.bot and pubsub."," Its topic must grant roles/pubsub.publisher to the app's push account:"," Interactive features service-@gcp-sa-gsuiteaddons.iam.gserviceaccount.com"," Classic bot chat-api-push@system.gserviceaccount.com"," Shown at Chat API \u2192 Configuration \u2192 Connection settings"," Missing it channel connects, no event arrives, Chat says the bot is not responding"].join("\n"),emptyValueMessage:"required for the Hermes Google Chat channel"}}],credentials:[],policyPresets:[{name:"googlechat",policyKeys:["googlechat"],agentPolicyKeys:{hermes:["googlechat_hermes"]}}],render:[{id:"googlechat-openclaw-channel",kind:"json-fragment",agent:"openclaw",target:"openclaw.json",fragment:{path:"channels.googlechat",value:{enabled:true,serviceAccount:{},audienceType:"{{googlechatConfig.audienceType}}",audience:"{{googlechatConfig.audience}}",appPrincipal:"{{googlechatConfig.appPrincipal}}",webhookPath:"/googlechat",healthMonitor:{enabled:false},dmPolicy:"{{allowedIds.googlechat.dmPolicy}}",allowFrom:"{{allowedIds.googlechat.values}}"}}},{id:"googlechat-openclaw-plugin",kind:"json-fragment",agent:"openclaw",target:"openclaw.json",fragment:{path:"plugins.entries.googlechat",value:{enabled:true}}},{id:"googlechat-openclaw-gateway-reload-off",kind:"json-fragment",agent:"openclaw",target:"openclaw.json",fragment:{path:"gateway.reload",value:{mode:"off"}}},{id:"googlechat-hermes-env",kind:"env-lines",agent:"hermes",target:"~/.hermes/.env",lines:["GOOGLE_CHAT_PROJECT_ID={{googlechatConfig.projectId}}","GOOGLE_CHAT_SUBSCRIPTION_NAME={{googlechatConfig.subscriptionName}}","GOOGLE_CHAT_ALLOWED_USERS={{allowedIds.googlechat.csv}}"]},{id:"googlechat-hermes-platform",kind:"json-fragment",agent:"hermes",target:"~/.hermes/config.yaml",fragment:{path:"platforms.google_chat",value:{enabled:true}}}],runtime:{openclaw:{channelName:"googlechat",visibility:{configKeys:["googlechat"],logPatterns:["googlechat"]},nodePreloads:[{module:"googlechat-trusted-proxy-fetch",injectInto:["boot"],optional:false,installMessage:"[channels] Installing Google Chat trusted-proxy-fetch patch (route googleapis via trusted env proxy)",installedMessage:"[channels] Google Chat trusted-proxy-fetch patch installed (NODE_OPTIONS updated)"},{module:"googlechat-outbound-auth",injectInto:["boot"],optional:false,installMessage:"[channels] Installing Google Chat outbound-auth patch (gateway-minted bearer)",installedMessage:"[channels] Google Chat outbound-auth patch installed (NODE_OPTIONS updated)"}],secretScans:[{path:"/sandbox/.openclaw/openclaw.json",pattern:"-----BEGIN (?:RSA )?PRIVATE KEY-----",message:"[SECURITY] Google Chat service account private key leaked into {path} - refusing to serve",exitCode:78}]}},agentPackages:[{id:"openclawPluginPackage",agent:"openclaw",manager:"openclaw-plugin",spec:"npm:@openclaw/googlechat@{{openclaw.version}}",pin:true,integrityByVersion:{"2026.10.5":"sha512-FWJm5S7oaAdbq8k4BL1EopvF8D/wVpILRKY4seJ7MzxURLMIjF6a6mIBgx34VIFH40KEO5lszDgc/iRwPEjHcg==","2026.9.2":"sha512-LUO8Lg07IhzJfEzxn+GSij8WMS/uX3hTmv0SydTy/0fKSN7iZksf74TaZg50kOoBi8FzeqeXo/zoGVuk0Mj1Ig==","2026.9.5":"sha512-8yX3i7u6044gyq+W4tMbJH5CRXLBsJSbdDMzysAxJYDgPimYB5DS+fTNU924tt8zhzkruqRjUzz7FjTtMTn0jA==","2026.9.1":"sha512-Q5VTAJpfcrI7BSEw5Ugq3wf7JEg5QhTBwpi+BByGbfZsTTVjwZc7OIvNbKsVTh16I5/EWqHEnD+0WNeHqsteqw=="},tarballUrlByVersion:{"2026.10.5":"https://registry.npmjs.org/@openclaw/googlechat/-/googlechat-2026.10.5.tgz","2026.9.2":"https://registry.npmjs.org/@openclaw/googlechat/-/googlechat-2026.9.2.tgz","2026.9.5":"https://registry.npmjs.org/@openclaw/googlechat/-/googlechat-2026.9.5.tgz","2026.9.1":"https://registry.npmjs.org/@openclaw/googlechat/-/googlechat-2026.9.1.tgz"},required:true},{id:"hermesGooglePubsubPackage",agent:"hermes",manager:"hermes-uv-pip",spec:"google-cloud-pubsub==2.39.0",required:true},{id:"hermesGoogleApiClientPackage",agent:"hermes",manager:"hermes-uv-pip",spec:"google-api-python-client==2.194.0",required:true},{id:"hermesGoogleAuthPackage",agent:"hermes",manager:"hermes-uv-pip",spec:"google-auth==2.55.1",required:true}],hooks:[{id:"googlechat-tunnel-audience-gate",phase:"enroll",handler:"googlechat.tunnelAudienceGate",agents:["openclaw"],inputs:["audienceType","audience"],outputs:[{id:"audience",kind:"config"}],onFailure:"skip-channel"},{id:"googlechat-service-account",phase:"enroll",handler:"googlechat.tokenPaste",outputs:[{id:"serviceAccount",kind:"secret",required:true}],onFailure:"skip-channel"},{id:"googlechat-config-prompt",phase:"enroll",handler:"common.configPrompt",outputs:[{id:"allowFrom",kind:"config"}]},{id:"googlechat-openclaw-config-prompt",phase:"enroll",handler:"common.configPrompt",agents:["openclaw"],outputs:[{id:"appPrincipal",kind:"config"}]},{id:"googlechat-hermes-config-prompt",phase:"enroll",handler:"common.configPrompt",agents:["hermes"],outputs:[{id:"projectId",kind:"config"},{id:"subscriptionName",kind:"config"}]}]};var slackManifest={schemaVersion:1,id:"slack",displayName:"Slack",description:"Slack bot messaging",supportedAgents:["openclaw","hermes"],state:{hermes:["platforms/slack"]},auth:{mode:"token-paste"},inputs:[{id:"botToken",kind:"secret",required:true,envKey:"SLACK_BOT_TOKEN",formatPattern:"^xoxb-[A-Za-z0-9_-]+$",formatHint:"Slack bot tokens start with 'xoxb-' (e.g. xoxb---).",prompt:{label:"Slack Bot Token",help:"Slack API \u2192 Your Apps \u2192 OAuth & Permissions \u2192 Bot User OAuth Token (xoxb-...)."}},{id:"appToken",kind:"secret",required:true,envKey:"SLACK_APP_TOKEN",formatPattern:"^xapp-[A-Za-z0-9_-]+$",formatHint:"Slack app tokens start with 'xapp-' (e.g. xapp----).",prompt:{label:"Slack App Token (Socket Mode)",help:"Slack API \u2192 Your Apps \u2192 Basic Information \u2192 App-Level Tokens (xapp-...)."}},{id:"allowedUsers",kind:"config",required:false,envKey:"SLACK_ALLOWED_USERS",statePath:"allowedIds.slack",prompt:{label:"Slack Member IDs (comma-separated allowlist)",help:"In Slack, open each allowed human user's profile -> More -> Copy member ID. Enter one or more comma-separated member IDs, not the app or bot user ID. Member IDs look like U01ABC2DEF3.",emptyValueMessage:"bot will require manual pairing"}},{id:"allowedChannels",kind:"config",required:false,envKey:"SLACK_ALLOWED_CHANNELS",statePath:"slackConfig.allowedChannels",prompt:{label:"Slack Channel IDs (comma-separated allowlist)",help:"Optional: enter comma-separated Slack channel IDs where the bot may answer @mentions. Channel IDs look like C012AB3CD.",emptyValueMessage:"channel @mentions stay unrestricted by channel ID"}}],credentials:[{id:"slackBotToken",sourceInput:"botToken",providerName:"{sandboxName}-slack-bridge",providerEnvKey:"SLACK_BOT_TOKEN",placeholder:"xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN",primary:true},{id:"slackAppToken",sourceInput:"appToken",providerName:"{sandboxName}-slack-app",providerEnvKey:"SLACK_APP_TOKEN",placeholder:"xapp-OPENSHELL-RESOLVE-ENV-SLACK_APP_TOKEN"}],policyPresets:[{name:"slack",requiredAtCreate:true}],render:[{id:"slack-openclaw-channel",kind:"json-fragment",agent:"openclaw",target:"openclaw.json",fragment:{path:"channels.slack",value:{enabled:true,accounts:{default:{enabled:true,healthMonitor:{enabled:false},dmPolicy:"{{allowedIds.slack.dmPolicy}}",allowFrom:"{{allowedIds.slack.values}}",groupPolicy:"{{allowedIds.slack.groupPolicy}}",channels:"{{allowedIds.slack.channels}}"}}}}},{id:"slack-openclaw-plugin",kind:"json-fragment",agent:"openclaw",target:"openclaw.json",fragment:{path:"plugins.entries.slack",value:{enabled:true}}},{id:"slack-hermes-env",kind:"env-lines",agent:"hermes",target:"~/.hermes/.env",lines:["SLACK_ALLOWED_USERS={{allowedIds.slack.csv}}","SLACK_ALLOWED_CHANNELS={{slackConfig.allowedChannels.csv}}"]},{id:"slack-hermes-platform",kind:"json-fragment",agent:"hermes",target:"~/.hermes/config.yaml",fragment:{path:"platforms.slack",value:{enabled:true,extra:{rich_blocks:true}}}}],runtime:{openclaw:{channelName:"slack",visibility:{configKeys:["slack"],logPatterns:["slack"]},nodePreloads:[{module:"slack-channel-guard",injectInto:["boot","connect"],optional:false,installMessage:"[channels] Installing Slack channel guard (unhandled-rejection safety net)",installedMessage:"[channels] Slack channel guard installed (NODE_OPTIONS updated)"}],secretScans:[{path:"/sandbox/.openclaw/openclaw.json",pattern:"(?:xoxb|xapp)-(?!OPENSHELL-RESOLVE-ENV-)",message:"[SECURITY] Slack token leaked into {path} - refusing to serve",exitCode:78}]},hermes:{}},agentPackages:[{id:"openclawPluginPackage",agent:"openclaw",manager:"openclaw-plugin",spec:"npm:@openclaw/slack@{{openclaw.version}}",pin:true,integrityByVersion:{"2026.10.5":"sha512-AzWaSLfUQZWPwDdrLXzXeQ/AraXPEnkTTWKTKq4MFO39futFAxy+FulsYSStDYEd1B0YjtWGvXswBjdrmwRlBw==","2026.9.2":"sha512-6M1M6gL3iXahpalNsYAUuA+wvnV8lbMlNNH2ToegFvaSJcIll4S9kFa5mv3GFoquhMRHQjEjnkXPHP/pXwaWcA==","2026.9.5":"sha512-Q45q/ZW+zw6Gr5Fg8J8V8xMWYXegMVEn3q8TcRBJyuD0nP0PtuW9FdkPF82KJ/yCP0tj18VPCgLPOuhYaiwR7A==","2026.9.1":"sha512-tU372jE40nnPcKQ6oxmDHf2/UhGtdz8ysi4JKsRZIO1QBAEkZd2YfsOw8aucmb2r0B0vjcFD3OmIV/Qzb57COg=="},tarballUrlByVersion:{"2026.10.5":"https://registry.npmjs.org/@openclaw/slack/-/slack-2026.10.5.tgz","2026.9.2":"https://registry.npmjs.org/@openclaw/slack/-/slack-2026.9.2.tgz","2026.9.5":"https://registry.npmjs.org/@openclaw/slack/-/slack-2026.9.5.tgz","2026.9.1":"https://registry.npmjs.org/@openclaw/slack/-/slack-2026.9.1.tgz"},required:true}],hooks:[{id:"slack-socket-mode-gateway-conflict",phase:"pre-enable",handler:"slack.socketModeGatewayConflict",onFailure:"abort"},{id:"slack-openclaw-bridge-health",phase:"health-check",handler:"slack.openclawBridgeHealth",agents:["openclaw"],onFailure:"abort"},{id:"slack-socket-mode-gateway-status",phase:"status",handler:"slack.socketModeGatewayStatus",outputs:[{id:"gatewayOverlaps",kind:"status"}]},{id:"slack-status-health",phase:"status",handler:"slack.statusHealth",providesReadiness:true,agents:["openclaw"],outputs:[{id:"channelHealth",kind:"status"}]},{id:"slack-token-paste",phase:"enroll",handler:"common.tokenPaste",outputs:[{id:"botToken",kind:"secret",required:true},{id:"appToken",kind:"secret",required:true}],onFailure:"skip-channel"},{id:"slack-config-prompt",phase:"enroll",handler:"common.configPrompt",outputs:[{id:"allowedUsers",kind:"config"},{id:"allowedChannels",kind:"config"}]},{id:"slack-credential-validation",phase:"reachability-check",handler:"slack.validateCredentials",inputs:["botToken","appToken"],onFailure:"skip-channel"}]};var TEAMS_OPENCLAW_WEBHOOK_RENDER_CONTRACT={channelId:"teams",renderId:"teams-openclaw-channel",hookId:"teams-openclaw-channel",handlerId:"common.staticOutputs",kind:"json-fragment",agent:"openclaw",target:"openclaw.json",configPath:"channels.msteams",webhookPath:"/api/messages"};function authorizeTeamsOpenClawWebhookField(entry){if(!isPlainDataObject(entry))return[];const contract=TEAMS_OPENCLAW_WEBHOOK_RENDER_CONTRACT;if(ownDataPropertyValue(entry,"channelId")!==contract.channelId||ownDataPropertyValue(entry,"renderId")!==contract.renderId||ownDataPropertyValue(entry,"hookId")!==contract.hookId||ownDataPropertyValue(entry,"handler")!==contract.handlerId||ownDataPropertyValue(entry,"kind")!==contract.kind||ownDataPropertyValue(entry,"agent")!==contract.agent||ownDataPropertyValue(entry,"target")!==contract.target||ownDataPropertyValue(entry,"path")!==contract.configPath){return[]}const value=ownDataPropertyValue(entry,"value");if(!isPlainDataObject(value))return[];const webhook=ownDataPropertyValue(value,"webhook");const legacyWebhook=ownDataPropertyValue(value,"legacyWebhook");if(!isPlainDataObject(webhook)||!hasExactlyOwnDataProperties(webhook,["path"])||!isPlainDataObject(legacyWebhook)||!hasExactlyOwnDataProperties(legacyWebhook,["port"])||!isTcpPort(ownDataPropertyValue(legacyWebhook,"port"))||ownDataPropertyValue(webhook,"path")!==contract.webhookPath){return[]}return[{path:["value","webhook"],value:webhook}]}function isPlainDataObject(value){if(value===null||typeof value!=="object"||Array.isArray(value))return false;const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function ownDataPropertyValue(value,key){const descriptor=Object.getOwnPropertyDescriptor(value,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}function hasExactlyOwnDataProperties(value,expected){const actual=Object.getOwnPropertyNames(value).sort();return actual.length===expected.length&&actual.every((key,index)=>key===expected[index])}function isTcpPort(value){return Number.isInteger(value)&&value>=1&&value<=65535}var teamsManifest={schemaVersion:1,id:"teams",displayName:"Microsoft Teams",description:"Microsoft Teams bot messaging (experimental)",enrollmentNotes:["Microsoft Teams requires a public HTTPS webhook endpoint at /api/messages; expose the configured Teams webhook port before installing the Teams app.","Use Azure AD object IDs in TEAMS_ALLOWED_USERS so only authorized users can interact with the bot."],supportedAgents:["openclaw","hermes"],auth:{mode:"token-paste"},inputs:[{id:"appId",kind:"config",required:true,envKey:"MSTEAMS_APP_ID",statePath:"teamsConfig.appId",prompt:{label:"Microsoft Teams Client ID",help:"Run `teams app create --endpoint https:///api/messages`, then copy CLIENT_ID."}},{id:"clientSecret",kind:"secret",required:true,envKey:"MSTEAMS_APP_PASSWORD",prompt:{label:"Microsoft Teams Client Secret",help:"Use the CLIENT_SECRET printed by `teams app create`. It is shown once; rotate it in Entra ID if it was lost."}},{id:"tenantId",kind:"config",required:true,envKey:"MSTEAMS_TENANT_ID",statePath:"teamsConfig.tenantId",prompt:{label:"Microsoft Teams Tenant ID",help:"Use the TENANT_ID printed by `teams app create` or shown by `teams status --verbose`."}},{id:"allowedUsers",kind:"config",required:false,envKey:"TEAMS_ALLOWED_USERS",statePath:"allowedIds.teams",prompt:{label:"Microsoft Teams AAD Object IDs (comma-separated allowlist)",help:"Recommended: run `teams status --verbose` and enter the Azure AD object IDs allowed to use the bot."}},{id:"webhookPort",kind:"config",required:false,envKey:"MSTEAMS_PORT",statePath:"teamsConfig.webhookPort",defaultValue:"3978",prompt:{label:"Microsoft Teams webhook port",help:"Local bot webhook port to expose publicly. Defaults to 3978 and serves /api/messages."}},{id:"requireMention",kind:"config",required:false,envKey:"TEAMS_REQUIRE_MENTION",statePath:"teamsConfig.requireMention",validValues:["0","1"],defaultValue:"1",prompt:{label:"Microsoft Teams mention mode",help:"Controls OpenClaw group and channel behavior only. Direct messages are unaffected."}}],credentials:[{id:"teamsClientSecret",sourceInput:"clientSecret",providerName:"{sandboxName}-teams-bridge",providerEnvKey:"MSTEAMS_APP_PASSWORD",placeholder:"openshell:resolve:env:MSTEAMS_APP_PASSWORD",primary:true}],policyPresets:[{name:"teams",policyKeys:["teams"],requiredAtCreate:true}],hostForward:{port:"{{teamsConfig.webhookPort}}",label:"Microsoft Teams webhook"},render:[{id:TEAMS_OPENCLAW_WEBHOOK_RENDER_CONTRACT.renderId,kind:TEAMS_OPENCLAW_WEBHOOK_RENDER_CONTRACT.kind,agent:TEAMS_OPENCLAW_WEBHOOK_RENDER_CONTRACT.agent,target:TEAMS_OPENCLAW_WEBHOOK_RENDER_CONTRACT.target,fragment:{path:TEAMS_OPENCLAW_WEBHOOK_RENDER_CONTRACT.configPath,value:{enabled:true,appId:"{{teamsConfig.appId}}",tenantId:"{{teamsConfig.tenantId}}",webhook:{path:TEAMS_OPENCLAW_WEBHOOK_RENDER_CONTRACT.webhookPath},legacyWebhook:{port:"{{teamsConfig.webhookPort}}"},healthMonitor:{enabled:false},streaming:{mode:"off"},dmPolicy:"{{allowedIds.teams.dmPolicy}}",allowFrom:"{{allowedIds.teams.values}}",groupPolicy:"open",requireMention:"{{teamsConfig.requireMention}}"}}},{id:"teams-openclaw-plugin",kind:"json-fragment",agent:"openclaw",target:"openclaw.json",fragment:{path:"plugins.entries.msteams",value:{enabled:true}}},{id:"teams-hermes-env",kind:"env-lines",agent:"hermes",target:"~/.hermes/.env",lines:["TEAMS_CLIENT_ID={{teamsConfig.appId}}","TEAMS_TENANT_ID={{teamsConfig.tenantId}}","TEAMS_ALLOWED_USERS={{allowedIds.teams.csv}}","TEAMS_PORT={{teamsConfig.webhookPort}}"]},{id:"teams-hermes-platform",kind:"json-fragment",agent:"hermes",target:"~/.hermes/config.yaml",fragment:{path:"platforms.teams",value:{enabled:true}}}],runtime:{openclaw:{channelName:"msteams",visibility:{configKeys:["msteams"],logPatterns:["msteams","teams"]},nodePreloads:[{module:"msteams-message-hints",injectInto:["boot","connect"],optional:false,installMessage:"[channels] Installing Microsoft Teams message hint patch (native mentions)",installedMessage:"[channels] Microsoft Teams message hint patch installed (NODE_OPTIONS updated)"}]},hermes:{envAliases:[{envKey:"MSTEAMS_APP_PASSWORD",targetEnvKey:"TEAMS_CLIENT_SECRET",match:"^openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_MSTEAMS_APP_PASSWORD$",value:"openshell:resolve:env:MSTEAMS_APP_PASSWORD"}]}},agentPackages:[{id:"openclawPluginPackage",agent:"openclaw",manager:"openclaw-plugin",spec:"npm:@openclaw/msteams@{{openclaw.version}}",pin:true,integrityByVersion:{"2026.10.5":"sha512-Up5NG2C0vVJBNIX92Lv7SB8qoCQ9SX86LMLh2MTow71AglyVy20OjNc/rGpOco2YTwWl7HcjhSz9MJbqWcvvDQ==","2026.9.2":"sha512-py5KvGOTcd0qGGRf3EuqbH2jO+kZtvMquDMjwGkT6x9F4XZtaCBL/lmLitb4hDb5xaIpPP8ZLIbT8GIMXQr3Og==","2026.9.5":"sha512-8zOP4qjEhaVxwT2NsmGKhwxDz2ZRBSBIjtwpkTcLnyHyj/u9e2RnM4yhYumdwHjpmwniIuDvkc91DCKBg9DHSA==","2026.9.1":"sha512-seRGr9/X6Vk9xU5elLVpDwq8R+TO0QFvUmxPEitqkngqDnMoXW0LEEXkriG6jgue74w2YLcNnAv/Rjf0a9jong=="},tarballUrlByVersion:{"2026.10.5":"https://registry.npmjs.org/@openclaw/msteams/-/msteams-2026.10.5.tgz","2026.9.2":"https://registry.npmjs.org/@openclaw/msteams/-/msteams-2026.9.2.tgz","2026.9.5":"https://registry.npmjs.org/@openclaw/msteams/-/msteams-2026.9.5.tgz","2026.9.1":"https://registry.npmjs.org/@openclaw/msteams/-/msteams-2026.9.1.tgz"},required:true},{id:"hermesTeamsAppsPackage",agent:"hermes",manager:"hermes-uv-pip",spec:"microsoft-teams-apps==2.0.13.4",required:true}],hooks:[{id:"teams-host-forward-port-conflict",phase:"pre-enable",handler:"teams.hostForwardPortConflict",inputs:["webhookPort"],onFailure:"abort"},{id:"teams-host-forward-port-status",phase:"status",handler:"teams.hostForwardPortStatus",outputs:[{id:"hostForwardPortOverlaps",kind:"status"}]},{id:"teams-token-paste",phase:"enroll",handler:"common.tokenPaste",outputs:[{id:"clientSecret",kind:"secret",required:true}],onFailure:"skip-channel"},{id:"teams-config-prompt",phase:"enroll",handler:"common.configPrompt",outputs:[{id:"appId",kind:"config",required:true},{id:"tenantId",kind:"config",required:true},{id:"allowedUsers",kind:"config"},{id:"webhookPort",kind:"config"},{id:"requireMention",kind:"config"}]}],state:{}};var telegramManifest={schemaVersion:1,id:"telegram",displayName:"Telegram",description:"Telegram bot messaging",diagnosticsProbe:"log-tail",enrollmentNotes:["For Telegram group chats, disable privacy mode in @BotFather (/setprivacy -> your bot -> Disable).","After changing privacy mode, remove and re-add the bot to each group before testing @mentions."],supportedAgents:["openclaw","hermes"],state:{openclaw:["telegram"],hermes:["platforms/telegram"]},auth:{mode:"token-paste"},inputs:[{id:"botToken",kind:"secret",required:true,envKey:"TELEGRAM_BOT_TOKEN",prompt:{label:"Telegram Bot Token",help:"Create a bot via @BotFather on Telegram, then copy the token."}},{id:"allowedIds",kind:"config",required:false,envKey:"TELEGRAM_ALLOWED_IDS",statePath:"allowedIds.telegram",prompt:{label:"Telegram User ID (for DM access)",help:"Send /start to @userinfobot on Telegram to get your numeric user ID.",emptyValueMessage:"bot will require manual pairing"}},{id:"requireMention",kind:"config",required:false,envKey:"TELEGRAM_REQUIRE_MENTION",statePath:"telegramConfig.requireMention",validValues:["0","1"],defaultValue:"1",prompt:{label:"Telegram group mention mode",help:"Controls Telegram group-chat behavior only \u2014 reply only when @mentioned vs. to all group messages. Direct messages are unaffected by this setting and remain subject to pairing and TELEGRAM_ALLOWED_IDS."}},{id:"groupPolicy",kind:"config",required:false,envKey:"TELEGRAM_GROUP_POLICY",statePath:"telegramConfig.groupPolicy",validValues:["open","allowlist","disabled"],defaultValue:"open",prompt:{label:"Telegram group policy",help:"Controls OpenClaw Telegram group access. Hermes does not expose an equivalent disable-groups policy."}}],credentials:[{id:"telegramBotToken",sourceInput:"botToken",providerName:"{sandboxName}-telegram-bridge",providerEnvKey:"TELEGRAM_BOT_TOKEN",placeholder:"openshell:resolve:env:TELEGRAM_BOT_TOKEN"}],policyPresets:[{name:"telegram",requiredAtCreate:true,policyKeys:["telegram_bot"],agentPolicyKeys:{hermes:["telegram"]}}],render:[{id:"telegram-openclaw-channel",kind:"json-fragment",agent:"openclaw",target:"openclaw.json",fragment:{path:"channels.telegram",value:{enabled:true,accounts:{default:{enabled:true,healthMonitor:{enabled:false},proxy:"{{proxyUrl}}",groupPolicy:"{{telegramConfig.groupPolicy}}",dmPolicy:"{{allowedIds.telegram.dmPolicy}}",allowFrom:"{{allowedIds.telegram.values}}"}}}}},{id:"telegram-openclaw-groups",kind:"json-fragment",agent:"openclaw",target:"openclaw.json",when:"{{telegramConfig.openclawGroups}}",fragment:{path:"channels.telegram.groups",value:"{{telegramConfig.openclawGroups}}"}},{id:"telegram-openclaw-plugin",kind:"json-fragment",agent:"openclaw",target:"openclaw.json",fragment:{path:"plugins.entries.telegram",value:{enabled:true}}},{id:"telegram-hermes-env",kind:"env-lines",agent:"hermes",target:"~/.hermes/.env",lines:["TELEGRAM_ALLOWED_USERS={{allowedIds.telegram.csv}}"]},{id:"telegram-hermes-config",kind:"json-fragment",agent:"hermes",target:"~/.hermes/config.yaml",fragment:{path:"telegram",value:{require_mention:"{{telegramConfig.requireMention}}"}}},{id:"telegram-hermes-platform",kind:"json-fragment",agent:"hermes",target:"~/.hermes/config.yaml",fragment:{path:"platforms.telegram",value:{enabled:true}}}],runtime:{openclaw:{channelName:"telegram",visibility:{configKeys:["telegram"],logPatterns:["telegram"]},nodePreloads:[{module:"telegram-diagnostics",injectInto:["boot","connect"],optional:false,installMessage:"[channels] Installing Telegram diagnostics (provider readiness + inference errors)",installedMessage:"[channels] Telegram diagnostics installed (NODE_OPTIONS updated)"}]}},hooks:[{id:"telegram-token-paste",phase:"enroll",handler:"common.tokenPaste",outputs:[{id:"botToken",kind:"secret",required:true}],onFailure:"skip-channel"},{id:"telegram-allowlist-aliases",phase:"enroll",handler:"telegram.allowlistAliases",outputs:[{id:"allowedIds",kind:"config"}]},{id:"telegram-config-prompt",phase:"enroll",handler:"common.configPrompt",outputs:[{id:"requireMention",kind:"config"},{id:"allowedIds",kind:"config"}]},{id:"telegram-openclaw-config-prompt",phase:"enroll",handler:"common.configPrompt",agents:["openclaw"],outputs:[{id:"groupPolicy",kind:"config"}]},{id:"telegram-get-me-reachability",phase:"reachability-check",handler:"telegram.getMeReachability",inputs:["botToken"],onFailure:"skip-channel"},{id:"telegram-openclaw-bridge-health",phase:"health-check",handler:"telegram.openclawBridgeHealth",agents:["openclaw"],onFailure:"abort"},{id:"telegram-gateway-conflict-status",phase:"status",handler:"telegram.gatewayConflictStatus",outputs:[{id:"bridgeHealth",kind:"status"}]},{id:"telegram-status-health",phase:"status",handler:"telegram.statusHealth",agents:["openclaw"],outputs:[{id:"channelHealth",kind:"status"}]}]};var WECHAT_OPENCLAW_ACCOUNT_FILE_CONTRACT={channelId:"wechat",planHookId:"wechat-seed-openclaw-account",handlerId:"wechat.seedOpenClawAccount",outputId:"openclawWeixinAccountFile",kind:"build-file",required:true,mode:"0600"};var WECHAT_SEED_OPENCLAW_ACCOUNT_HOOK_ID=WECHAT_OPENCLAW_ACCOUNT_FILE_CONTRACT.handlerId;var WECHAT_SEED_OPENCLAW_ACCOUNT_PLAN_HOOK_ID=WECHAT_OPENCLAW_ACCOUNT_FILE_CONTRACT.planHookId;var WECHAT_OPENCLAW_ACCOUNT_FILE_OUTPUT_ID=WECHAT_OPENCLAW_ACCOUNT_FILE_CONTRACT.outputId;var WECHAT_TOKEN_PLACEHOLDER="openshell:resolve:env:WECHAT_BOT_TOKEN";function authorizeWechatAccountFilePlaceholders(value){const content=isPlainDataObject2(value)?ownDataPropertyValue2(value,"content"):void 0;if(!isPlainDataObject2(value)||!hasExactlyOwnDataProperties2(value,["content","mode","path"])||!isWechatAccountFilePath(ownDataPropertyValue2(value,"path"))||ownDataPropertyValue2(value,"mode")!==WECHAT_OPENCLAW_ACCOUNT_FILE_CONTRACT.mode||!isPlainDataObject2(content)||!hasOnlyOwnDataProperties(content,["baseUrl","savedAt","token","userId"])||!hasOwnDataProperty(content,"savedAt")||!hasOwnDataProperty(content,"token")||ownDataPropertyValue2(content,"token")!==WECHAT_TOKEN_PLACEHOLDER||!isNonEmptyString(ownDataPropertyValue2(content,"savedAt"))||!isOptionalNonEmptyString(content,"baseUrl")||!isOptionalNonEmptyString(content,"userId")){return[]}return[{path:["content","token"],value:WECHAT_TOKEN_PLACEHOLDER}]}function isWechatAccountFilePath(value){if(typeof value!=="string")return false;const prefix="openclaw-weixin/accounts/";const suffix=".json";if(!value.startsWith(prefix)||!value.endsWith(suffix))return false;const accountId=value.slice(prefix.length,-suffix.length);return accountId===accountId.trim()&&isSafeWechatAccountId(accountId)}function isSafeWechatAccountId(accountId){return accountId.length>0&&accountId!=="."&&accountId!==".."&&!/[\\/\0-\x1F\x7F]/.test(accountId)&&!accountId.includes("..")}function isPlainDataObject2(value){if(value===null||typeof value!=="object"||Array.isArray(value))return false;const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function ownDataPropertyValue2(value,key){const descriptor=Object.getOwnPropertyDescriptor(value,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}function hasOwnDataProperty(value,key){const descriptor=Object.getOwnPropertyDescriptor(value,key);return descriptor!==void 0&&"value"in descriptor}function hasExactlyOwnDataProperties2(value,expected){const actual=Object.getOwnPropertyNames(value).sort();return actual.length===expected.length&&actual.every((key,index)=>key===expected[index])}function hasOnlyOwnDataProperties(value,allowed){return Object.getOwnPropertyNames(value).every(key=>allowed.includes(key))}function isNonEmptyString(value){return typeof value==="string"&&value.length>0}function isOptionalNonEmptyString(value,key){return!hasOwnDataProperty(value,key)||isNonEmptyString(ownDataPropertyValue2(value,key))}var wechatManifest={schemaVersion:1,id:"wechat",displayName:"WeChat",description:"WeChat (personal) bot messaging",enrollmentHelp:"Captured automatically via a host-side QR scan during onboard \u2014 pair the bot by scanning the QR with WeChat on your phone (Discover \u2192 Scan). DM-only.",supportedAgents:["openclaw","hermes"],auth:{mode:"host-qr"},inputs:[{id:"botToken",kind:"secret",required:true,envKey:"WECHAT_BOT_TOKEN",prompt:{label:"WeChat Bot Token",help:"Captured automatically via a host-side QR scan during onboard \u2014 pair the bot by scanning the QR with WeChat on your phone (Discover \u2192 Scan). DM-only."}},{id:"accountId",kind:"config",required:true,envKey:"WECHAT_ACCOUNT_ID",statePath:"wechatConfig.accountId"},{id:"baseUrl",kind:"config",required:false,envKey:"WECHAT_BASE_URL",statePath:"wechatConfig.baseUrl"},{id:"userId",kind:"config",required:false,envKey:"WECHAT_USER_ID",statePath:"wechatConfig.userId"},{id:"allowedIds",kind:"config",required:false,envKey:"WECHAT_ALLOWED_IDS",statePath:"allowedIds.wechat",prompt:{label:"WeChat User ID(s) (DM allowlist)",help:"Optional: restrict who can DM the bot. The WeChat user id of the operator who scanned is added automatically; supply additional ids as a comma-separated list.",emptyValueMessage:"bot will require manual pairing"}}],credentials:[{id:"wechatBotToken",sourceInput:"botToken",providerName:"{sandboxName}-wechat-bridge",providerEnvKey:"WECHAT_BOT_TOKEN",placeholder:"openshell:resolve:env:WECHAT_BOT_TOKEN"}],state:{openclaw:["wechat","openclaw-weixin"],hermes:["platforms/wechat"]},policyPresets:[{name:"wechat",policyKeys:["wechat_bridge"],requiredAtCreate:true}],render:[{id:"wechat-openclaw-plugin",kind:"json-fragment",agent:"openclaw",target:"openclaw.json",fragment:{path:"plugins.entries.openclaw-weixin",value:{enabled:true}}},{id:"wechat-openclaw-channel",kind:"json-fragment",agent:"openclaw",target:"openclaw.json",fragment:{path:"channels.openclaw-weixin",value:{enabled:true}}},{id:"wechat-hermes-env",kind:"env-lines",agent:"hermes",target:"~/.hermes/.env",lines:["WEIXIN_ACCOUNT_ID={{wechatConfig.accountId}}","WEIXIN_BASE_URL={{wechatConfig.baseUrl}}","WEIXIN_ALLOWED_USERS={{allowedIds.wechat.csv}}"]},{id:"wechat-hermes-platform",kind:"json-fragment",agent:"hermes",target:"~/.hermes/config.yaml",fragment:{path:"platforms.weixin",value:{enabled:true}}}],runtime:{openclaw:{channelName:"openclaw-weixin",visibility:{configKeys:["openclaw-weixin"],logPatterns:["wechat","openclaw-weixin"]},nodePreloads:[{module:"wechat-account-placeholder",injectInto:["boot"],optional:false},{module:"wechat-diagnostics",injectInto:["boot","connect"],optional:false,installMessage:"[channels] Installing WeChat diagnostics (provider readiness + inference errors)",installedMessage:"[channels] WeChat diagnostics installed (NODE_OPTIONS updated)"}]},hermes:{envAliases:[{envKey:"WECHAT_BOT_TOKEN",targetEnvKey:"WEIXIN_TOKEN",match:"^openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_WECHAT_BOT_TOKEN$",value:"openshell:resolve:env:WECHAT_BOT_TOKEN"}]}},agentPackages:[{id:"openclawPluginPackage",agent:"openclaw",manager:"openclaw-plugin",spec:"npm:@tencent-weixin/openclaw-weixin@2.4.10",pin:true,integrity:"sha512-qCN7rFtBK5BO/i5YGEJLdpC/8WQrm0dtPlQ0xNxku4RSyzGaRsiBoLVheU5hgpoOIBvfc5pUwKTktMbROLcIVg==",tarballUrl:"https://registry.npmjs.org/@tencent-weixin/openclaw-weixin/-/openclaw-weixin-2.4.10.tgz",runtimeLock:{cachePath:"/usr/local/share/nemoclaw/wechat-npm-cache",installCacheEnvKey:"NEMOCLAW_WECHAT_NPM_INSTALL_CACHE",lockFile:"/usr/local/lib/nemoclaw/wechat-runtime/package-lock.json",projectsRoot:"/sandbox/.openclaw/npm/projects",verifierPath:"/usr/local/lib/nemoclaw/verify-wechat-runtime-lock.mts",offline:true,legacyPeerDeps:true},required:true}],hooks:[{id:"wechat-host-qr",phase:"enroll",handler:"wechat.ilinkLogin",inputs:["allowedIds"],outputs:[{id:"botToken",kind:"secret",required:true},{id:"accountId",kind:"config",required:true},{id:"baseUrl",kind:"config"},{id:"userId",kind:"config"},{id:"allowedIds",kind:"config"}],onFailure:"skip-channel"},{id:"wechat-config-prompt",phase:"enroll",handler:"common.configPrompt",outputs:[{id:"allowedIds",kind:"config"}]},{id:WECHAT_OPENCLAW_ACCOUNT_FILE_CONTRACT.planHookId,phase:"post-agent-install",handler:WECHAT_OPENCLAW_ACCOUNT_FILE_CONTRACT.handlerId,agents:["openclaw"],inputs:["wechatConfig.accountId","wechatConfig.baseUrl","wechatConfig.userId","credential.wechatBotToken.placeholder"],outputs:[{id:"openclawWeixinAccountsIndex",kind:"build-file",required:true},{id:WECHAT_OPENCLAW_ACCOUNT_FILE_CONTRACT.outputId,kind:WECHAT_OPENCLAW_ACCOUNT_FILE_CONTRACT.kind,required:WECHAT_OPENCLAW_ACCOUNT_FILE_CONTRACT.required},{id:"openclawConfigPatch",kind:"build-file",required:true}],onFailure:"abort"},{id:"wechat-health-check",phase:"health-check",handler:"wechat.healthCheck",inputs:["wechatConfig.accountId"],onFailure:"abort"}]};var whatsappManifest={schemaVersion:1,id:"whatsapp",displayName:"WhatsApp",description:"WhatsApp Web messaging (QR pairing)",enrollmentHelp:"WhatsApp Web pairs via QR code scanned with your phone \u2014 no host-side token. After the sandbox is running, run `openshell term` and then use `openclaw channels login --channel whatsapp` for OpenClaw or `hermes whatsapp` for Hermes to display the QR.",enrollmentNotes:["After pairing, run `nemoclaw channels status --channel whatsapp`. OpenClaw reports inbound delivery evidence; Hermes reports gateway and dashboard session-path diagnostics."],supportedAgents:["openclaw","hermes"],auth:{mode:"in-sandbox-qr"},inputs:[{id:"mode",kind:"config",required:false,envKey:"WHATSAPP_MODE",statePath:"whatsappConfig.mode",validValues:["self-chat","bot"],defaultValue:"self-chat",prompt:{label:"WhatsApp reply mode",help:"self-chat replies only to messages the paired account sends to itself. bot replies to other senders and stops replying to that self-chat: an unknown sender receives a pairing code you approve with `hermes pairing approve whatsapp `, unless you set WHATSAPP_ALLOWED_IDS to a fixed sender list before this command.",emptyValueMessage:"the sandbox replies only in your own self-chat"}},{id:"allowedIds",kind:"config",required:false,envKey:"WHATSAPP_ALLOWED_IDS",statePath:"allowedIds.whatsapp"}],credentials:[],state:{openclaw:["whatsapp"],hermes:["platforms/whatsapp","profiles/dashboard-home/platforms/whatsapp/session","dashboard-home/platforms/whatsapp/session"]},policyPresets:["whatsapp"],render:[{id:"whatsapp-openclaw-channel",kind:"json-fragment",agent:"openclaw",target:"openclaw.json",fragment:{path:"channels.whatsapp",value:{enabled:true,accounts:{default:{enabled:true,healthMonitor:{enabled:false}}}}}},{id:"whatsapp-openclaw-plugin",kind:"json-fragment",agent:"openclaw",target:"openclaw.json",fragment:{path:"plugins.entries.whatsapp",value:{enabled:true}}},{id:"whatsapp-hermes-env",kind:"env-lines",agent:"hermes",target:"~/.hermes/.env",lines:["WHATSAPP_ENABLED=true","WHATSAPP_MODE={{whatsappConfig.mode}}","WHATSAPP_DM_POLICY={{whatsappConfig.dmPolicy}}","WHATSAPP_ALLOWED_USERS={{allowedIds.whatsapp.csv}}"]},{id:"whatsapp-hermes-platform",kind:"json-fragment",agent:"hermes",target:"~/.hermes/config.yaml",fragment:{path:"platforms.whatsapp",value:{enabled:true}}}],runtime:{openclaw:{channelName:"whatsapp",visibility:{configKeys:["whatsapp"],logPatterns:["whatsapp"]},nodePreloads:[{module:"whatsapp-qr-compact",injectInto:["connect"],optional:true,installMessage:"[channels] Installing WhatsApp compact-QR renderer (scan-friendly pairing)"}]}},agentPackages:[{id:"openclawPluginPackage",agent:"openclaw",manager:"openclaw-plugin",spec:"npm:@openclaw/whatsapp@{{openclaw.version}}",pin:true,integrityByVersion:{"2026.10.5":"sha512-3Dbv0p60yuz6tzuZNUMHzIYjhGL816BfOPBfz2YIpszQ7kx2j1uZfgpa0xTaxH4Spbg0AFakIp0kIcWOU1ODEQ==","2026.9.2":"sha512-vOWQIk7FpLHrhMmO+FaLi+pnFB82hiWNJJFJONkBuofERh2SMEz7EMut/vECFFEjFnmOZSVlYfRlxhbNkd/R6g==","2026.9.5":"sha512-V7o/ckrk0N0iN4fKk5jMBs4nqe4Ftc4/drJWY374fREY8gEMzmdvXMB2pfM2VrmptJfoPMMhI78C+1+mGUtwJw==","2026.9.1":"sha512-llIcoMa6FM4SgYn7GG1FQIeTTA5JDdcHW5D7PT+3aGYT3/E2eLFutKwDvD/w7G0hvDwSftzZgLi3iA8dzK7a3A=="},tarballUrlByVersion:{"2026.10.5":"https://registry.npmjs.org/@openclaw/whatsapp/-/whatsapp-2026.10.5.tgz","2026.9.2":"https://registry.npmjs.org/@openclaw/whatsapp/-/whatsapp-2026.9.2.tgz","2026.9.5":"https://registry.npmjs.org/@openclaw/whatsapp/-/whatsapp-2026.9.5.tgz","2026.9.1":"https://registry.npmjs.org/@openclaw/whatsapp/-/whatsapp-2026.9.1.tgz"},required:true}],hooks:[{id:"whatsapp-config-prompt",phase:"enroll",handler:"common.configPrompt",agents:["hermes"],outputs:[{id:"mode",kind:"config"}]},{id:"whatsapp-status-health",phase:"status",handler:"whatsapp.statusHealth",agents:["openclaw","hermes"],outputs:[{id:"channelHealth",kind:"status"}]}]};var BUILT_IN_CHANNEL_MANIFESTS=[telegramManifest,discordManifest,wechatManifest,slackManifest,whatsappManifest,teamsManifest,googlechatManifest];function createBuiltInChannelManifestRegistry(){return createChannelManifestRegistry(BUILT_IN_CHANNEL_MANIFESTS)}var EXACT_TEMPLATE_PATTERN=/^\{\{\s*([^}]+?)\s*\}\}$/;var TEMPLATE_REFERENCE_PATTERN=/\{\{\s*([^}]+?)\s*\}\}/g;function resolvedRenderTemplateReference(value){return{matched:true,value}}function resolveSandboxNameTemplate(value,sandboxName){return value.replaceAll("{sandboxName}",sandboxName)}function resolveRenderTemplatesInValue(value,context){if(typeof value==="string")return resolveRenderTemplatesInString(value,context);if(Array.isArray(value)){if(value.length===0)return value;const resolved=value.map(entry=>resolveRenderTemplatesInValue(entry,context)).filter(entry=>entry!==void 0);return resolved.length>0?resolved:void 0}if(value&&typeof value==="object"){const sourceEntries=Object.entries(value);if(sourceEntries.length===0)return value;const entries=sourceEntries.map(([key,entry])=>[key,resolveRenderTemplatesInValue(entry,context)]).filter(entry=>entry[1]!==void 0);return entries.length>0?Object.fromEntries(entries):void 0}return value}function isTruthyRenderTemplate(value,context){if(!value)return true;const resolved=resolveRenderTemplatesInString(value,context);if(resolved===void 0||resolved===null||resolved===false)return false;if(Array.isArray(resolved))return resolved.length>0;if(typeof resolved==="object")return Object.keys(resolved).length>0;if(typeof resolved==="string")return resolved.trim().length>0;return true}function resolveRenderTemplatesInString(value,context){const exact=value.match(EXACT_TEMPLATE_PATTERN);if(exact?.[1])return resolveTemplateReference(exact[1].trim(),context);let omitted=false;const resolved=value.replace(TEMPLATE_REFERENCE_PATTERN,(match,reference)=>{const replacement=resolveTemplateReference(reference.trim(),context);if(replacement===void 0||replacement===null){omitted=true;return""}if(Array.isArray(replacement))return replacement.map(String).join(",");if(typeof replacement==="object")return JSON.stringify(replacement);return String(replacement)});return omitted?void 0:resolved}function resolveTemplateReference(reference,context){const resolved=context.referenceResolver?.(reference,context);return resolved?.matched?resolved.value:"{{"+reference+"}}"}function allowedIds(context,channel){return parseList(stateValue(context,`allowedIds.${channel}`))}function stateValue(context,path4){const stateInput=context.inputs.find(input=>input.statePath===path4);if(stateInput?.value!==void 0)return stateInput.value;const inputId=path4.split(".").at(-1);return context.inputs.find(input=>input.inputId===inputId)?.value}function parseList(value){if(Array.isArray(value))return unique(value.map(String).map(cleanString).filter(Boolean));const text=cleanString(value);if(!text)return[];return unique(text.split(",").map(cleanString).filter(Boolean))}function parseBoolean(value){if(typeof value==="boolean")return value;const text=cleanString(value)?.toLowerCase();if(text==="1"||text==="true"||text==="yes"||text==="on")return true;if(text==="0"||text==="false"||text==="no"||text==="off")return false;return void 0}function nonEmptyString(value){return cleanString(value)||void 0}function cleanString(value){const text=String(value??"");if(/[\r\n]/.test(text)){throw new Error("Messaging template values must not contain line breaks.")}return text.trim()}function nonEmptyArray(values){return values.length>0?[...values]:void 0}function nonEmptyCsv(values){return values.length>0?values.join(","):void 0}function nonEmptyObject(value){return Object.keys(value).length>0?value:void 0}function unique(values){return[...new Set(values)]}var resolveDiscordTemplateReference=(reference,context)=>{if(reference==="discordProxyUrl")return resolvedRenderTemplateReference(void 0);switch(reference){case"discord.guilds":return resolvedRenderTemplateReference(nonEmptyObject(discordGuilds(context)));case"discord.hasGuilds":return resolvedRenderTemplateReference(Object.keys(discordGuilds(context)).length>0);case"discord.guildIds.csv":return resolvedRenderTemplateReference(nonEmptyCsv(Object.keys(discordGuilds(context))));case"discord.allowedUsers.values":return resolvedRenderTemplateReference(nonEmptyArray(discordAllowedUsers(context)));case"discord.allowedUsers.csv":return resolvedRenderTemplateReference(nonEmptyCsv(discordAllowedUsers(context)));case"discord.allowedUsers.dmPolicy":return resolvedRenderTemplateReference(discordAllowedUsers(context).length>0?"allowlist":void 0);case"discord.allowAllUsers":return resolvedRenderTemplateReference(Object.keys(discordGuilds(context)).length>0&&discordAllowedUsers(context).length===0?true:void 0);case"discord.requireMention":return resolvedRenderTemplateReference(discordRequireMention(context));default:return void 0}};function discordGuilds(context){const serverIds=parseList(stateValue(context,"discordGuilds.serverId"));if(serverIds.length===0)return{};const users=parseList(stateValue(context,"discordGuilds.userIds"));const requireMention=parseBoolean(stateValue(context,"discordGuilds.requireMention"))??true;return Object.fromEntries(serverIds.map(serverId=>[serverId,{requireMention,...users.length>0?{users}:{}}]))}function discordAllowedUsers(context){const users=new Set(allowedIds(context,"discord"));for(const guild of Object.values(discordGuilds(context))){for(const user of guild.users??[])users.add(String(user))}return[...users]}function discordRequireMention(context){for(const guild of Object.values(discordGuilds(context))){if(typeof guild.requireMention==="boolean")return guild.requireMention}return true}var DEFAULT_AUDIENCE_TYPE="app-url";var APP_PRINCIPAL_DISCOVERY_SENTINEL="000000000000000000000";var resolveGooglechatTemplateReference=(reference,context)=>{switch(reference){case"googlechatConfig.audienceType":return resolvedRenderTemplateReference(nonEmptyString(stateValue(context,"googlechatConfig.audienceType"))??DEFAULT_AUDIENCE_TYPE);case"googlechatConfig.audience":return resolvedRenderTemplateReference(nonEmptyString(stateValue(context,"googlechatConfig.audience")));case"googlechatConfig.appPrincipal":return resolvedRenderTemplateReference(nonEmptyString(stateValue(context,"googlechatConfig.appPrincipal"))??APP_PRINCIPAL_DISCOVERY_SENTINEL);case"googlechatConfig.projectId":return resolvedRenderTemplateReference(nonEmptyString(stateValue(context,"googlechatConfig.projectId")));case"googlechatConfig.subscriptionName":return resolvedRenderTemplateReference(nonEmptyString(stateValue(context,"googlechatConfig.subscriptionName")));default:break}const allowReference=reference.match(/^allowedIds[.]googlechat[.](values|dmPolicy|csv)$/);if(!allowReference?.[1])return void 0;const ids=allowedIds(context,"googlechat");switch(allowReference[1]){case"values":return resolvedRenderTemplateReference(nonEmptyArray(ids));case"dmPolicy":return resolvedRenderTemplateReference(ids.length>0?"allowlist":void 0);case"csv":return resolvedRenderTemplateReference(ids.length>0?ids.join(","):void 0);default:return void 0}};var resolveSlackTemplateReference=(reference,context)=>{if(reference==="slackConfig.allowedChannels.csv"){return resolvedRenderTemplateReference(nonEmptyCsv(slackAllowedChannels(context)))}const allowedIdsReference=reference.match(/^allowedIds[.]slack[.](values|csv|dmPolicy|groupPolicy|channels)$/);if(!allowedIdsReference?.[1])return void 0;const ids=allowedIds(context,"slack");switch(allowedIdsReference[1]){case"values":return resolvedRenderTemplateReference(nonEmptyArray(ids));case"csv":return resolvedRenderTemplateReference(nonEmptyCsv(ids));case"dmPolicy":return resolvedRenderTemplateReference(ids.length>0?"allowlist":void 0);case"groupPolicy":return resolvedRenderTemplateReference(ids.length>0||slackAllowedChannels(context).length>0?"allowlist":void 0);case"channels":return resolvedRenderTemplateReference(slackChannelConfig(context,ids));default:return void 0}};function slackChannelConfig(context,users){const allowedChannels=slackAllowedChannels(context);const entry={enabled:true,requireMention:true,...users.length>0?{users:[...users]}:{}};if(allowedChannels.length>0){return Object.fromEntries(allowedChannels.map(channelId=>[channelId,{...entry}]))}return users.length>0?{"*":entry}:void 0}function slackAllowedChannels(context){return parseList(stateValue(context,"slackConfig.allowedChannels"))}var DEFAULT_TEAMS_WEBHOOK_PORT=3978;var resolveTeamsTemplateReference=(reference,context)=>{switch(reference){case"teamsConfig.appId":return resolvedRenderTemplateReference(nonEmptyString(stateValue(context,"teamsConfig.appId")));case"teamsConfig.tenantId":return resolvedRenderTemplateReference(nonEmptyString(stateValue(context,"teamsConfig.tenantId")));case"teamsConfig.webhookPort":return resolvedRenderTemplateReference(teamsWebhookPort(context));case"teamsConfig.requireMention":return resolvedRenderTemplateReference(parseBoolean(stateValue(context,"teamsConfig.requireMention")));default:break}const allowedIdsReference=reference.match(/^allowedIds[.]teams[.](values|csv|dmPolicy)$/);if(!allowedIdsReference?.[1])return void 0;const ids=allowedIds(context,"teams");switch(allowedIdsReference[1]){case"values":return resolvedRenderTemplateReference(nonEmptyArray(ids));case"csv":return resolvedRenderTemplateReference(nonEmptyCsv(ids));case"dmPolicy":return resolvedRenderTemplateReference(ids.length>0?"allowlist":void 0);default:return void 0}};function teamsWebhookPort(context){const raw=nonEmptyString(stateValue(context,"teamsConfig.webhookPort"));if(!raw)return DEFAULT_TEAMS_WEBHOOK_PORT;const port=Number(raw);if(!Number.isInteger(port)||port<1||port>65535){throw new Error("Microsoft Teams webhook port must be an integer TCP port between 1 and 65535.")}return port}var DEFAULT_PROXY_HOST="10.200.0.1";var DEFAULT_PROXY_PORT="3128";var DEFAULT_TELEGRAM_GROUP_POLICY="open";var TELEGRAM_GROUP_POLICIES=new Set(["open","allowlist","disabled"]);var resolveTelegramTemplateReference=(reference,context)=>{if(reference==="proxyUrl")return resolvedRenderTemplateReference(proxyUrl(context.env));if(reference==="telegramConfig.groupPolicy"){return resolvedRenderTemplateReference(telegramGroupPolicy(context))}if(reference==="telegramConfig.openclawGroups"){return resolvedRenderTemplateReference(telegramOpenClawGroups(context))}if(reference==="telegramConfig.requireMention"){return resolvedRenderTemplateReference(parseBoolean(stateValue(context,"telegramConfig.requireMention")))}const allowedIdsReference=reference.match(/^allowedIds[.]telegram[.](values|csv|dmPolicy)$/);if(!allowedIdsReference?.[1])return void 0;const ids=allowedIds(context,"telegram");switch(allowedIdsReference[1]){case"values":return resolvedRenderTemplateReference(nonEmptyArray(ids));case"csv":return resolvedRenderTemplateReference(nonEmptyCsv(ids));case"dmPolicy":return resolvedRenderTemplateReference(ids.length>0?"allowlist":void 0);default:return void 0}};function proxyUrl(env){const host=nonEmptyString(env?.NEMOCLAW_PROXY_HOST)??DEFAULT_PROXY_HOST;const port=nonEmptyString(env?.NEMOCLAW_PROXY_PORT)??DEFAULT_PROXY_PORT;return`http://${host}:${port}`}function telegramGroupPolicy(context){const value=nonEmptyString(stateValue(context,"telegramConfig.groupPolicy"));return value&&TELEGRAM_GROUP_POLICIES.has(value)?value:DEFAULT_TELEGRAM_GROUP_POLICY}function telegramOpenClawGroups(context){if(telegramGroupPolicy(context)!=="open")return void 0;const requireMention=parseBoolean(stateValue(context,"telegramConfig.requireMention"));return requireMention===true?{"*":{requireMention:true}}:void 0}var WECHAT_ILINK_HOSTS=new Set(["ilinkai.weixin.qq.com","ilinkai.wechat.com"]);var WECHAT_ILINK_IDC_HOST_PATTERN=/^idc-[0-9]+[.]weixin[.]qq[.]com$/u;function normalizeWechatIlinkBaseUrl(value){const raw=String(value??"");if(/[\r\n]/.test(raw)){throw new Error("WeChat baseUrl must not contain line breaks.")}const text=raw.trim();if(!text)return void 0;let url;try{url=new URL(text)}catch{throw new Error("WeChat baseUrl must be a valid URL.")}if(url.protocol!=="https:"){throw new Error("WeChat baseUrl must use HTTPS.")}if(url.username||url.password){throw new Error("WeChat baseUrl must not include credentials.")}const authority=text.match(/^[a-z][a-z0-9+.-]*:\/\/([^/?#]*)/iu)?.[1]??"";if(authority.includes(":")){throw new Error("WeChat baseUrl must not include an explicit port.")}if(!isWechatIlinkHost(url.hostname)){throw new Error("WeChat baseUrl must use an expected iLink host.")}if(url.pathname&&url.pathname!=="/"||url.search||url.hash){throw new Error("WeChat baseUrl must be an iLink origin URL.")}return url.origin}function isWechatIlinkHost(hostname){const normalized=hostname.toLowerCase();return WECHAT_ILINK_HOSTS.has(normalized)||isWechatIlinkIdcHost(normalized)}function isWechatIlinkIdcHost(hostname){return WECHAT_ILINK_IDC_HOST_PATTERN.test(hostname.toLowerCase())}var resolveWechatTemplateReference=(reference,context)=>{const wechatConfig=reference.match(/^wechatConfig[.](accountId|baseUrl|userId)$/);if(wechatConfig?.[1]){if(wechatConfig[1]==="baseUrl"){return resolvedRenderTemplateReference(normalizeWechatIlinkBaseUrl(stateValue(context,"wechatConfig.baseUrl")))}return resolvedRenderTemplateReference(nonEmptyString(stateValue(context,"wechatConfig."+wechatConfig[1])))}const allowedIdsReference=reference.match(/^allowedIds[.]wechat[.](values|csv|dmPolicy)$/);if(!allowedIdsReference?.[1])return void 0;const ids=wechatAllowedIds(context);switch(allowedIdsReference[1]){case"values":return resolvedRenderTemplateReference(nonEmptyArray(ids));case"csv":return resolvedRenderTemplateReference(nonEmptyCsv(ids));case"dmPolicy":return resolvedRenderTemplateReference(ids.length>0?"allowlist":void 0);default:return void 0}};function wechatAllowedIds(context){const ids=allowedIds(context,"wechat");const userId=nonEmptyString(stateValue(context,"wechatConfig.userId"));return userId&&!ids.includes(userId)?[userId,...ids]:ids}var DEFAULT_WHATSAPP_MODE="self-chat";var BOT_WHATSAPP_MODE="bot";var WHATSAPP_MODES=new Set([DEFAULT_WHATSAPP_MODE,BOT_WHATSAPP_MODE]);var resolveWhatsappTemplateReference=(reference,context)=>{if(reference==="whatsappConfig.mode"){return resolvedRenderTemplateReference(whatsappMode(context))}if(reference==="whatsappConfig.dmPolicy"){return resolvedRenderTemplateReference(whatsappDmPolicy(context))}const allowedIdsReference=reference.match(/^allowedIds[.]whatsapp[.](values|csv)$/);if(!allowedIdsReference?.[1])return void 0;const ids=allowedIds(context,"whatsapp");switch(allowedIdsReference[1]){case"values":return resolvedRenderTemplateReference(nonEmptyArray(ids));case"csv":return resolvedRenderTemplateReference(nonEmptyCsv(ids));default:return void 0}};function whatsappMode(context){const value=nonEmptyString(stateValue(context,"whatsappConfig.mode"));return value&&WHATSAPP_MODES.has(value)?value:DEFAULT_WHATSAPP_MODE}function whatsappDmPolicy(context){if(whatsappMode(context)!==BOT_WHATSAPP_MODE)return void 0;return allowedIds(context,"whatsapp").length>0?"allowlist":"pairing"}var BUILT_IN_TEMPLATE_REFERENCE_RESOLVERS=[resolveTelegramTemplateReference,resolveDiscordTemplateReference,resolveWechatTemplateReference,resolveSlackTemplateReference,resolveWhatsappTemplateReference,resolveTeamsTemplateReference,resolveGooglechatTemplateReference];function createBuiltInRenderTemplateResolver(){return(reference,context)=>{for(const resolver of BUILT_IN_TEMPLATE_REFERENCE_RESOLVERS){const resolved=resolver(reference,context);if(resolved)return resolved}return void 0}}var import_node_crypto2=__toESM(require("node:crypto"));function hashCredential(value){const normalized=String(value??"").trim();if(!normalized)return null;return import_node_crypto2.default.createHash("sha256").update(normalized).digest("hex")}function planCredentialBindings(manifest,context,inputs,environment=process.env){return manifest.credentials.map(credential=>{const sourceInput=inputs.find(input=>input.inputId===credential.sourceInput);const credentialAvailable=sourceInput?.credentialAvailable===true||context.credentialAvailability?.[credential.id]===true||context.credentialAvailability?.[`${manifest.id}.${credential.id}`]===true;const envKey=sourceInput?.sourceEnv??credential.providerEnvKey;const credentialHash=credentialAvailable?hashCredential(environment[envKey])??void 0:void 0;return{channelId:manifest.id,credentialId:credential.id,sourceInput:credential.sourceInput,providerName:resolveSandboxNameTemplate(credential.providerName,context.sandboxName),providerEnvKey:credential.providerEnvKey,placeholder:credential.placeholder,credentialAvailable,...credentialHash!==void 0?{credentialHash}:{}}})}function planHostForward(manifest,inputs,active,referenceResolver,environment=process.env){if(!active||!manifest.hostForward)return void 0;const context={inputs,env:environment,referenceResolver};if(!isTruthyRenderTemplate(manifest.hostForward.when,context))return void 0;const portValue=resolveRenderTemplatesInValue(manifest.hostForward.port,context);const port=normalizeForwardPort(manifest.id,portValue);return{channelId:manifest.id,port,label:manifest.hostForward.label}}function normalizeForwardPort(channelId,value){const port=typeof value==="number"?value:Number(String(value??"").trim());if(!Number.isInteger(port)||port<1||port>65535){throw new Error(`Channel manifest '${channelId}' declares invalid host forward port '${String(value)}'.`)}return port}var OPENSHELL_ENV_PLACEHOLDER_PREFIX="openshell:resolve:env:";var OPENSHELL_ALIAS_PLACEHOLDER_RE=/^[A-Za-z0-9]+-OPENSHELL-RESOLVE-ENV-(.+)$/;function normalizeProviderPlaceholderForEnvKey(value,envKey){if(value.startsWith(OPENSHELL_ENV_PLACEHOLDER_PREFIX)){return placeholderSuffixMatchesEnvKey(value.slice(OPENSHELL_ENV_PLACEHOLDER_PREFIX.length),envKey)?`${OPENSHELL_ENV_PLACEHOLDER_PREFIX}${envKey}`:null}const aliasMatch=value.match(OPENSHELL_ALIAS_PLACEHOLDER_RE);if(!aliasMatch||!placeholderSuffixMatchesEnvKey(aliasMatch[1],envKey)){return null}return value.replace(/-OPENSHELL-RESOLVE-ENV-.+$/,`-OPENSHELL-RESOLVE-ENV-${envKey}`)}function placeholderSuffixMatchesEnvKey(suffix,envKey){if(suffix===envKey)return true;const generationMatch=suffix.match(/^(?:v[0-9]{1,20}|s[a-f0-9]{64})_(.+)$/);return generationMatch?.[1]===envKey}function hasFullPersistedCredentialBindingShape(binding){return typeof binding.channelId==="string"&&typeof binding.credentialId==="string"&&typeof binding.sourceInput==="string"&&typeof binding.providerName==="string"&&typeof binding.providerEnvKey==="string"&&typeof binding.placeholder==="string"&&typeof binding.credentialAvailable==="boolean"}function normalizeFullPersistedCredentialBindings(bindings){return bindings.map(binding=>({channelId:binding.channelId,credentialId:binding.credentialId,sourceInput:binding.sourceInput,providerName:binding.providerName,providerEnvKey:binding.providerEnvKey,placeholder:normalizeProviderPlaceholderForEnvKey(binding.placeholder,binding.providerEnvKey)??binding.placeholder,credentialAvailable:binding.credentialAvailable===true,...typeof binding.credentialHash==="string"?{credentialHash:binding.credentialHash}:{}}))}function normalizePersistedAgentCredentialPlaceholders(render,credentialBindings){const credentialEnvKeys=new Set(credentialBindings.map(binding=>binding.providerEnvKey).filter(Boolean));if(credentialEnvKeys.size===0)return[...render];return render.map(entry=>{if(entry.kind!=="env-lines")return entry;return{...entry,lines:entry.lines.map(line=>normalizeCredentialEnvLine(line,credentialEnvKeys))}})}function normalizeCredentialEnvLine(line,credentialEnvKeys){const index=line.indexOf("=");if(index<=0)return line;const envKey=line.slice(0,index).trim();if(!credentialEnvKeys.has(envKey))return line;const value=line.slice(index+1);const normalized=normalizeProviderPlaceholderForEnvKey(value,envKey);return normalized?`${envKey}=${normalized}`:line}function normalizePersistedSandboxMessagingPlanShape(plan,environment=process.env){const manifestRegistry=createBuiltInChannelManifestRegistry();const disabledChannels=plan.disabledChannels.filter(channelId=>typeof channelId==="string");const disabledSet=new Set(disabledChannels);const channels=plan.channels.map(channel=>normalizePersistedChannel(channel,disabledSet,manifestRegistry.get(channel.channelId),environment));const credentialBindings=normalizePersistedCredentialBindings(plan,channels,manifestRegistry,environment);const normalizedPlan={...plan,channels,disabledChannels,credentialBindings,networkPolicy:plan.networkPolicy&&Array.isArray(plan.networkPolicy.entries)?plan.networkPolicy:{presets:[],entries:[]},agentRender:normalizePersistedAgentCredentialPlaceholders(Array.isArray(plan.agentRender)?[...plan.agentRender]:[],credentialBindings),buildSteps:Array.isArray(plan.buildSteps)?[...plan.buildSteps]:[],...plan.runtimeSetup!==void 0?{runtimeSetup:normalizeRuntimeSetup(plan.runtimeSetup)}:{},stateUpdates:Array.isArray(plan.stateUpdates)?[...plan.stateUpdates]:[],healthChecks:Array.isArray(plan.healthChecks)?[...plan.healthChecks]:[]};return normalizedPlan}function normalizePersistedChannel(channel,disabledSet,manifest,environment){const disabled=channel.disabled??disabledSet.has(channel.channelId);const configured=channel.configured??true;const hasFullShape=hasFullChannelShape(channel);const inputs=hasFullShape?normalizeFullInputs(channel.channelId,channel.inputs??[]):normalizePersistedInputs(channel,manifest);const active=channel.active??(configured&&!disabled&&requiredInputsAvailable(manifest,inputs));const hostForward=manifest?planHostForward(manifest,inputs,active&&!disabled,createBuiltInRenderTemplateResolver(),environment):void 0;return{channelId:channel.channelId,displayName:channel.displayName??manifest?.displayName??channel.channelId,authMode:channel.authMode??manifest?.auth.mode??"none",active,selected:channel.selected??configured,configured,disabled,...channel.pendingRemoval===true?{pendingRemoval:true}:{},inputs,...hostForward?{hostForward}:{},hooks:Array.isArray(channel.hooks)?[...channel.hooks]:[]}}function normalizePersistedInputs(channel,manifest){const persistedById=new Map((channel.inputs??[]).filter(input=>typeof input.inputId==="string").map(input=>[input.inputId,input]));const fromManifest=(manifest?.inputs??[]).map(input=>inputReferenceFromManifest(channel.channelId,input,persistedById.get(input.id)));const manifestInputIds=new Set((manifest?.inputs??[]).map(input=>input.id));const unknownInputs=[...persistedById.values()].flatMap(input=>{if(!input.inputId||manifestInputIds.has(input.inputId))return[];return[normalizeUnknownInput(channel.channelId,input)]});return[...fromManifest,...unknownInputs]}function normalizeFullInputs(channelId,inputs){return inputs.filter(input=>typeof input.inputId==="string").map(input=>({channelId:typeof input.channelId==="string"?input.channelId:channelId,inputId:input.inputId,kind:input.kind==="secret"||input.kind==="config"?input.kind:"config",required:typeof input.required==="boolean"?input.required:false,...typeof input.sourceEnv==="string"?{sourceEnv:input.sourceEnv}:{},...typeof input.statePath==="string"?{statePath:input.statePath}:{},...input.credentialAvailable!==void 0?{credentialAvailable:input.credentialAvailable}:{},...input.value!==void 0?{value:input.value}:{}}))}function inputReferenceFromManifest(channelId,input,persisted){return{channelId,inputId:input.id,kind:input.kind,required:input.required,...input.envKey?{sourceEnv:input.envKey}:{},...input.kind==="config"&&input.statePath?{statePath:input.statePath}:{},...persisted?.credentialAvailable!==void 0?{credentialAvailable:persisted.credentialAvailable}:{},...persisted?.value!==void 0?{value:persisted.value}:{}}}function normalizeUnknownInput(channelId,input){const kind=input.kind==="secret"||input.kind==="config"?input.kind:"config";return{channelId,inputId:input.inputId,kind,required:input.required===true,...typeof input.sourceEnv==="string"?{sourceEnv:input.sourceEnv}:{},...typeof input.statePath==="string"?{statePath:input.statePath}:{},...input.credentialAvailable!==void 0?{credentialAvailable:input.credentialAvailable}:{},...input.value!==void 0?{value:input.value}:{}}}function requiredInputsAvailable(manifest,inputs){if(!manifest)return true;return manifest.inputs.every(manifestInput=>{if(!manifestInput.required)return true;const input=inputs.find(entry=>entry.inputId===manifestInput.id);if(!input)return false;if(input.kind==="secret")return input.credentialAvailable===true;if(input.value===void 0)return false;return typeof input.value==="string"?input.value.trim().length>0:true})}function normalizePersistedCredentialBindings(plan,channels,manifestRegistry,environment){const persisted=plan.credentialBindings??[];if(Array.isArray(plan.credentialBindings)&&plan.channels.every(hasFullChannelShape)&&persisted.every(hasFullPersistedCredentialBindingShape)){return normalizeFullPersistedCredentialBindings(persisted)}const manifests=channels.flatMap(channel=>{const manifest=manifestRegistry.get(channel.channelId);return manifest?[manifest]:[]});const planForBindings={...plan,channels,credentialBindings:[],networkPolicy:{presets:[],entries:[]},agentRender:[],buildSteps:[],runtimeSetup:{nodePreloads:[],envAliases:[],secretScans:[]},stateUpdates:[],healthChecks:[]};const generated=credentialBindingsFromManifests(planForBindings,manifests,new Map(channels.map(channel=>[channel.channelId,channel.inputs])),environment);return generated.map(binding=>overlayPersistedCredentialBinding(binding,persisted))}function credentialBindingsFromManifests(plan,manifests,inputRegistry,environment){const context=compilerContext(plan);return manifests.flatMap(manifest=>planCredentialBindings(manifest,context,inputRegistry.get(manifest.id)??[],environment).map(binding=>overlayPersistedCredentialBinding(binding,plan.credentialBindings)))}function overlayPersistedCredentialBinding(binding,persisted){const match=persisted.find(candidate=>credentialBindingMatches(binding,candidate));if(!match)return binding;return{...binding,credentialAvailable:typeof match.credentialAvailable==="boolean"?match.credentialAvailable:binding.credentialAvailable,...typeof match.credentialHash==="string"&&match.credentialHash.length>0?{credentialHash:match.credentialHash}:binding.credentialHash?{credentialHash:binding.credentialHash}:{}}}function credentialBindingMatches(binding,candidate){if(candidate.channelId&&candidate.channelId!==binding.channelId)return false;if(candidate.providerEnvKey&&candidate.providerEnvKey===binding.providerEnvKey)return true;if(candidate.credentialId&&candidate.credentialId===binding.credentialId)return true;if(candidate.sourceInput&&candidate.sourceInput===binding.sourceInput)return true;return false}function hasFullChannelShape(channel){return typeof channel.displayName==="string"&&typeof channel.authMode==="string"&&typeof channel.active==="boolean"&&typeof channel.selected==="boolean"&&typeof channel.configured==="boolean"&&typeof channel.disabled==="boolean"&&Array.isArray(channel.inputs)}function normalizeRuntimeSetup(setup){return{nodePreloads:Array.isArray(setup?.nodePreloads)?[...setup.nodePreloads]:[],envAliases:Array.isArray(setup?.envAliases)?[...setup.envAliases]:[],secretScans:Array.isArray(setup?.secretScans)?[...setup.secretScans]:[]}}function compilerContext(plan){return{sandboxName:plan.sandboxName,agent:plan.agent,workflow:plan.workflow,isInteractive:false,configuredChannels:plan.channels.map(channel=>channel.channelId),disabledChannels:plan.disabledChannels,credentialAvailability:credentialAvailabilityFromPlan(plan)}}function credentialAvailabilityFromPlan(plan){const availability={};for(const channel of plan.channels){for(const input of channel.inputs){if(input.kind!=="secret"||input.credentialAvailable!==true)continue;availability[`${channel.channelId}.${input.inputId}`]=true;if(input.sourceEnv)availability[input.sourceEnv]=true}}for(const credential of plan.credentialBindings){if(!credential.credentialAvailable)continue;availability[credential.credentialId]=true;availability[`${credential.channelId}.${credential.credentialId}`]=true;availability[`${credential.channelId}.${credential.sourceInput}`]=true;availability[credential.providerEnvKey]=true}return availability}function normalizeMessagingChannelId(channelId){return channelId.trim().toLowerCase()}function enabledPlanChannels(plan){const disabled=new Set((plan.disabledChannels??[]).map(normalizeMessagingChannelId).filter(Boolean));return plan.channels.filter(channel=>{const channelId=normalizeMessagingChannelId(channel.channelId);return channelId.length>0&&channel.active&&!channel.disabled&&!disabled.has(channelId)})}function selectActiveMessagingChannelIds(plan){const seen=new Set;const channels=[];for(const item of enabledPlanChannels(plan)){const channel=normalizeMessagingChannelId(item.channelId);if(!channel||seen.has(channel))continue;seen.add(channel);channels.push(channel)}return channels}function selectEnabledMessagingAgentRender(plan){const active=new Set(selectActiveMessagingChannelIds(plan));return plan.agentRender.filter(render=>render.agent===plan.agent&&active.has(normalizeMessagingChannelId(render.channelId)))}function selectEnabledPostAgentInstallBuildFiles(plan){const active=new Set(selectActiveMessagingChannelIds(plan));const channels=enabledPlanChannels(plan);return plan.buildSteps.filter(step=>{const channelId=normalizeMessagingChannelId(step.channelId);if(!active.has(channelId)||step.kind!=="build-file")return false;if(!step.hookId)return true;const matchingChannels=channels.filter(channel=>normalizeMessagingChannelId(channel.channelId)===channelId);if(matchingChannels.length!==1)return false;const matchedHook=matchingChannels[0]?.hooks?.find(hook=>hook.id===step.hookId);return matchedHook!==void 0&&matchedHook.phase==="post-agent-install"})}function parseSandboxMessagingPlan(value,options={}){if(!isObjectRecord(value)||value.schemaVersion!==1||typeof value.sandboxName!=="string"||typeof value.agent!=="string"||typeof value.workflow!=="string"||!Array.isArray(value.channels)||!Array.isArray(value.disabledChannels)||!isOptionalObjectArray(value,"credentialBindings")||Object.hasOwn(value,"networkPolicy")&&!isObjectRecord(value.networkPolicy)||!isOptionalObjectArray(value,"agentRender")||!isOptionalObjectArray(value,"buildSteps")||!isRuntimeSetup(value.runtimeSetup)||!isOptionalObjectArray(value,"stateUpdates")||!isOptionalObjectArray(value,"healthChecks")){return null}if(options.sandboxName&&value.sandboxName!==options.sandboxName)return null;if(options.agent&&value.agent!==options.agent)return null;const supported=Array.isArray(options.supportedChannelIds)?new Set(options.supportedChannelIds):null;const normalizedChannelIds=new Set;for(const channel of value.channels){if(!isObjectRecord(channel)||typeof channel.channelId!=="string")return null;const normalizedChannelId=normalizeMessagingChannelId(channel.channelId);if(!normalizedChannelId||normalizedChannelId!==channel.channelId||normalizedChannelIds.has(normalizedChannelId)){return null}if(Object.hasOwn(channel,"configured")&&typeof channel.configured!=="boolean"){return null}if(Object.hasOwn(channel,"active")&&typeof channel.active!=="boolean")return null;if(Object.hasOwn(channel,"disabled")&&typeof channel.disabled!=="boolean")return null;if(Object.hasOwn(channel,"pendingRemoval")&&typeof channel.pendingRemoval!=="boolean"){return null}if(Object.hasOwn(channel,"inputs")&&!Array.isArray(channel.inputs))return null;if(Object.hasOwn(channel,"hostForward")&&!isHostForward(channel.hostForward))return null;if(Object.hasOwn(channel,"hooks")&&!Array.isArray(channel.hooks))return null;if(Array.isArray(channel.inputs)&&channel.inputs.some(input=>!isObjectRecord(input)||typeof input.inputId!=="string"||Object.hasOwn(input,"channelId")&&input.channelId!==normalizedChannelId)){return null}if(Array.isArray(channel.hooks)&&channel.hooks.some(hook=>!isObjectRecord(hook)||Object.hasOwn(hook,"channelId")&&hook.channelId!==normalizedChannelId)){return null}if(Object.hasOwn(channel,"hostForward")&&isObjectRecord(channel.hostForward)&&channel.hostForward.channelId!==normalizedChannelId){return null}if(supported&&!supported.has(channel.channelId))return null;normalizedChannelIds.add(normalizedChannelId)}if(!value.disabledChannels.every(isCanonicalMessagingChannelId))return null;const disabledChannelIds=new Set(value.disabledChannels);if(disabledChannelIds.size!==value.disabledChannels.length||[...disabledChannelIds].some(channelId=>!normalizedChannelIds.has(channelId))||value.channels.some(channel=>isObjectRecord(channel)&&channel.disabled===true!==disabledChannelIds.has(String(channel.channelId)))){return null}if(!hasCanonicalChannelReferences(value.credentialBindings)||!hasMatchingAgentRenderEntries(value.agentRender,value.agent)||!hasCanonicalChannelReferences(value.agentRender)||!hasCanonicalChannelReferences(value.buildSteps)||!hasCanonicalChannelReferences(value.stateUpdates)||!hasCanonicalChannelReferences(value.healthChecks)||!hasCanonicalNetworkPolicyReferences(value.networkPolicy)||!hasCanonicalRuntimeSetupReferences(value.runtimeSetup)){return null}return cloneSandboxMessagingPlan(normalizePersistedSandboxMessagingPlanShape(value,options.environment))}function hasMatchingAgentRenderEntries(value,agent){return!Array.isArray(value)||value.every(render=>isObjectRecord(render)&&render.agent===agent)}function hasCanonicalNetworkPolicyReferences(value){if(!isObjectRecord(value)||!Object.hasOwn(value,"entries"))return true;return hasCanonicalChannelReferences(value.entries)}function cloneSandboxMessagingPlan(plan){return JSON.parse(JSON.stringify(plan))}function isOptionalObjectArray(value,key){if(!Object.hasOwn(value,key))return true;const entries=value[key];return Array.isArray(entries)&&entries.every(isObjectRecord)}function isHostForward(value){return isObjectRecord(value)&&typeof value.channelId==="string"&&typeof value.port==="number"&&Number.isInteger(value.port)&&value.port>=1&&value.port<=65535&&typeof value.label==="string"}function isRuntimeSetup(value){if(value===void 0)return true;return isObjectRecord(value)&&Array.isArray(value.nodePreloads)&&Array.isArray(value.envAliases)&&Array.isArray(value.secretScans)&&value.nodePreloads.every(isObjectRecord)&&value.envAliases.every(isObjectRecord)&&value.secretScans.every(isObjectRecord)}function isCanonicalMessagingChannelId(value){return typeof value==="string"&&value.length>0&&normalizeMessagingChannelId(value)===value}function hasCanonicalChannelReferences(value){return value===void 0||Array.isArray(value)&&value.every(entry=>isObjectRecord(entry)&&isCanonicalMessagingChannelId(entry.channelId))}function hasCanonicalRuntimeSetupReferences(value){if(value===void 0)return true;if(!isObjectRecord(value))return false;return["nodePreloads","envAliases","secretScans"].every(field=>hasCanonicalChannelReferences(value[field]))}var import_node_buffer2=require("node:buffer");var import_node_crypto3=require("node:crypto");var import_node_util=require("node:util");function isLoopbackHostname(hostname=""){const normalized=String(hostname||"").trim().toLowerCase().replace(/^\[|\]$/g,"");return normalized==="localhost"||normalized==="::1"||/^127(?:\.\d{1,3}){3}$/.test(normalized)}function isLoopbackDashboardUrl(value){return isLoopbackHostname(new URL(value).hostname)}function listMessagingCredentialEnvAssignments(options={}){return selectManifests(options).flatMap(manifest=>{const credentialsByTemplate=new Map(manifest.credentials.map(credential=>[`{{credential.${credential.id}.placeholder}}`,credential]));const renderedAssignments=manifest.render.flatMap(render=>{if(options.agent&&render.agent!==options.agent)return[];if(render.kind!=="env-lines")return[];return render.lines.flatMap(line=>{const separator=line.indexOf("=");if(separator<=0)return[];const credential=credentialsByTemplate.get(line.slice(separator+1));if(!credential)return[];return[{channelId:manifest.id,agent:render.agent,sourceEnvKey:credential.providerEnvKey,targetEnvKey:line.slice(0,separator),placeholder:credential.placeholder}]})});const runtimeAssignments=["openclaw","hermes"].flatMap(agent=>{if(options.agent&&agent!==options.agent)return[];if(!manifest.supportedAgents.includes(agent))return[];return(manifest.runtime?.[agent]?.envAliases??[]).flatMap(alias=>{if(!alias.targetEnvKey)return[];const credential=manifest.credentials.find(candidate=>candidate.providerEnvKey===alias.envKey);if(!credential)return[];return[{channelId:manifest.id,agent,sourceEnvKey:alias.envKey,targetEnvKey:alias.targetEnvKey,placeholder:credential.placeholder}]})});return[...renderedAssignments,...runtimeAssignments]})}function selectManifests(options){const manifests=options.manifests??BUILT_IN_CHANNEL_MANIFESTS;const agent=options.agent;const selected=agent?manifests.filter(manifest=>manifest.supportedAgents.includes(agent)):manifests;return[...selected]}function authorizeMessagingManagedStartupFields(entry,section){if(section==="agentRender")return authorizeTeamsOpenClawWebhookField(entry);if(!isPlainDataObject3(entry))return[];const contract=WECHAT_OPENCLAW_ACCOUNT_FILE_CONTRACT;if(ownDataPropertyValue3(entry,"channelId")!==contract.channelId||ownDataPropertyValue3(entry,"hookId")!==contract.planHookId||ownDataPropertyValue3(entry,"handler")!==contract.handlerId||ownDataPropertyValue3(entry,"outputId")!==contract.outputId||ownDataPropertyValue3(entry,"kind")!==contract.kind||ownDataPropertyValue3(entry,"required")!==contract.required){return[]}return authorizeWechatAccountFilePlaceholders(ownDataPropertyValue3(entry,"value")).map(authorization=>({...authorization,path:["value",...authorization.path]}))}function isPlainDataObject3(value){if(value===null||typeof value!=="object"||Array.isArray(value))return false;const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function ownDataPropertyValue3(value,key){const descriptor=Object.getOwnPropertyDescriptor(value,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}var DCODE_UPSTREAM_PROVIDER_RE=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u;function isValidDcodeUpstreamProvider(value){return DCODE_UPSTREAM_PROVIDER_RE.test(value)}var LEGACY_MANAGED_STARTUP_PROFILE_SCHEMA_VERSION=1;var MANAGED_STARTUP_PROFILE_SCHEMA_VERSION=2;var MANAGED_STARTUP_PROFILE_MAX_BYTES=64*1024;var MANAGED_STARTUP_PROFILE_MAX_ENCODED_BYTES=Math.ceil(MANAGED_STARTUP_PROFILE_MAX_BYTES/3)*4;var MAX_IDENTIFIER_BYTES=256;var MAX_MODEL_BYTES2=1024;var MAX_URL_BYTES=2048;var MAX_LIST_ITEMS=128;var MAX_JSON_NODES=4096;var MAX_JSON_DEPTH=32;var MAX_TUNING_INTEGER=1e9;var MIN_HERMES_CONTEXT_WINDOW=64e3;var SHA256_RE=/^[a-f0-9]{64}$/;var CONTROL_CHARACTER_RE=/[\u0000-\u001f\u007f-\u009f]/u;var BASE64URL_RE=/^[A-Za-z0-9_-]+$/;var RAW_CA_PEM_RE=/-----BEGIN (?:TRUSTED )?CERTIFICATE-----/iu;var RAW_CA_PEM_BASE64_RE=/^LS0tLS1CRUdJTi(?:BDRVJUSUZJQ0FURS0tLS0t|BUlVTVEVEIENFUlRJRklDQVRFLS0tLS0)/u;var RAW_CA_DER_BASE64_RE=/^MII[A-Za-z0-9+/=\r\n]{253,}$/u;var RAW_CA_DATA_URI_RE=/data:application\/(?:pkix-cert|x-x509-ca-cert);base64,MII[A-Za-z0-9+/=]{253,}/iu;var URL_CANDIDATE_RE=/[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'<>]+/gu;var UTF8_DECODER=new import_node_util.TextDecoder("utf-8",{fatal:true});var CREDENTIAL_SHAPED_NAME_PATTERN=/(?:^|[_-])(?:api[_-]?key|access[_-]?key|secret[_-]?key|auth[_-]?token|refresh[_-]?token|access[_-]?token|client[_-]?secret|private[_-]?key|pass[_-]?code|personal[_-]?access[_-]?token|connection[_-]?string|webhook(?:[_-]?url)?|key|secret|token|password|passwd|passcode|auth|authorization|credential|credentials|bearer|bearer[_-]?token|cookie|cookies|pat|private|privatekey|pin|webhookurl|dsn|connectionstring)(?:$|[_-])/iu;var CREDENTIAL_COMPOUND_NAME_PATTERN=/^(?:access|refresh|client|bearer|auth|api|private|signing|session|bot|app|resolved)(?:token|key|secret|password)$/iu;var CREDENTIAL_CAMEL_SUFFIX_PATTERN=/(?:apiKey|accessKey|secretKey|authToken|refreshToken|accessToken|clientSecret|privateKey|passcode|password|passwd|passphrase|bearerToken|botToken|appToken|sessionToken|signingKey|secretPublicKey|personalAccessToken|connectionString|webhookUrl)$/iu;var CREDENTIAL_CAMEL_BOUNDARY_PATTERN=/[a-z0-9](?:Token|Key|Secret|Password|Passphrase|Pat)$/u;var CREDENTIAL_ENV_NAME_PATTERN=/^(?:[A-Z0-9]+_)*(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD|PASS|PASSPHRASE|CREDENTIAL)S?$/u;var CREDENTIAL_HEADER_NAME_PATTERN=/^(?:authorization|proxy-authorization|cookie|set-cookie|.+-(?:key|token|secret|password|passphrase|credential|auth)s?)$/iu;var PUBLIC_KEY_NAME_PATTERN=/^public[-_]?keys?$/iu;var PASS_CREDENTIAL_NAME_PATTERN=/(?:^|[-_])pass(?:wd)?$/iu;var NON_SECRET_KEY_METADATA_NAMES=new Set(["envKey","installCacheEnvKey","providerEnvKey","stateKey","targetEnvKey"]);var MESSAGING_CREDENTIAL_PLACEHOLDER_RE=/^(?:openshell:resolve:env:|[A-Za-z0-9]+-OPENSHELL-RESOLVE-ENV-)(?:(?:v[0-9]{1,20}|s[a-f0-9]{64})_)?[A-Z][A-Z0-9_]*$/u;var MESSAGING_CREDENTIAL_ENV_ALIASES=new Set(listMessagingCredentialEnvAssignments().filter(({sourceEnvKey,targetEnvKey})=>sourceEnvKey!==targetEnvKey).map(({agent,sourceEnvKey,targetEnvKey})=>`${agent}\0${sourceEnvKey}\0${targetEnvKey}`));var MESSAGING_CREDENTIAL_RUNTIME_ENV_ALIASES=new Set(listMessagingCredentialEnvAssignments().filter(({sourceEnvKey,targetEnvKey})=>sourceEnvKey!==targetEnvKey).map(({agent,channelId,sourceEnvKey,targetEnvKey})=>`${agent}\0${channelId}\0${sourceEnvKey}\0${targetEnvKey}`));var JSON_ARRAY_INDEX_SEGMENT_RE=/^\[(?:0|[1-9][0-9]*)\]$/u;var SECRET_VALUE_PATTERNS2=[/nvapi-[A-Za-z0-9_-]{10,}/u,/nvcf-[A-Za-z0-9_-]{10,}/u,/ghp_[A-Za-z0-9_-]{10,}/u,/github_pat_[A-Za-z0-9_]{30,}/u,/sk-(?:proj-|ant-)?[A-Za-z0-9_-]{10,}/u,/(?:xox[bpas]|xapp)-[A-Za-z0-9-]{10,}/u,/A(?:K|S)IA[A-Z0-9]{16}/u,/hf_[A-Za-z0-9]{10,}/u,/glpat-[A-Za-z0-9_-]{10,}/u,/gsk_[A-Za-z0-9]{10,}/u,/pypi-[A-Za-z0-9_-]{10,}/u,/tvly-[A-Za-z0-9_-]{10,}/u,/lsv2_(?:pt|sk)_[A-Za-z0-9]{10,}(?:_[A-Za-z0-9]+)*/u,/\bbot\d{8,10}:[A-Za-z0-9_-]{35}\b/u,/\b\d{8,10}:[A-Za-z0-9_-]{35}\b/u,/\b[A-Za-z0-9]{24}\.[A-Za-z0-9_-]{6}\.[A-Za-z0-9_-]{27,}\b/u,/\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{2,}\.[A-Za-z0-9_-]{10,}\b/u,/\bBearer\s+[A-Za-z0-9_.+/=-]{10,}/iu,/-----BEGIN (?:[A-Z0-9]+ )?PRIVATE KEY-----/u];var MANAGED_STARTUP_INFERENCE_APIS=["openai-completions","openai-responses","anthropic-messages"];var MANAGED_STARTUP_REASONING_EFFORTS=["default","low","medium","high"];var MANAGED_STARTUP_DCODE_AUTO_APPROVAL_MODES=["disabled","thread-opt-in"];var MANAGED_STARTUP_HERMES_TOOL_GATEWAYS=["nous-web","nous-image","nous-audio","nous-browser","nous-code"];var MANAGED_STARTUP_AGENTS=["openclaw","hermes","langchain-deepagents-code","pi"];var MANAGED_STARTUP_MESSAGING_AGENTS=["openclaw","hermes"];function freezeAgentCapabilities(capabilities){return Object.freeze({...capabilities,inferenceApis:Object.freeze([...capabilities.inferenceApis]),dashboardModes:Object.freeze([...capabilities.dashboardModes]),inputModalities:Object.freeze([...capabilities.inputModalities]),webSearchProviders:Object.freeze([...capabilities.webSearchProviders]),toolGateways:Object.freeze([...capabilities.toolGateways]),tuningFields:Object.freeze([...capabilities.tuningFields])})}var PROFILE_CAPABILITIES={openclaw:{inferenceApis:[...MANAGED_STARTUP_INFERENCE_APIS],dashboardModes:["loopback","remote"],inputModalities:["text","image"],webSearchProviders:["brave","tavily"],toolGateways:[],tuningFields:["contextWindow","maxTokens","reasoning","reasoningEffort"],supportsMessaging:true,supportsInferenceCompatibility:true,supportsUpstreamEndpoint:false,supportsHostProxyIntent:true,supportsPrimaryModelRef:true,supportsAgentTimeout:true,supportsHeartbeat:true,supportsExtraAgents:true,supportsDeviceAuth:false,observability:"openclaw-otel",supportsMinimalBootstrap:true},hermes:{inferenceApis:[...MANAGED_STARTUP_INFERENCE_APIS],dashboardModes:["disabled","loopback-forwarded"],inputModalities:[],webSearchProviders:["tavily"],toolGateways:[...MANAGED_STARTUP_HERMES_TOOL_GATEWAYS],tuningFields:["contextWindow"],supportsMessaging:true,supportsInferenceCompatibility:false,supportsUpstreamEndpoint:false,supportsHostProxyIntent:true,supportsPrimaryModelRef:false,supportsAgentTimeout:false,supportsHeartbeat:false,supportsExtraAgents:false,supportsDeviceAuth:false,observability:"none",supportsMinimalBootstrap:false},"langchain-deepagents-code":{inferenceApis:["openai-completions"],dashboardModes:["disabled"],inputModalities:[],webSearchProviders:[],toolGateways:[],tuningFields:["reasoningEffort"],supportsMessaging:false,supportsInferenceCompatibility:false,supportsUpstreamEndpoint:true,supportsHostProxyIntent:true,supportsPrimaryModelRef:false,supportsAgentTimeout:false,supportsHeartbeat:false,supportsExtraAgents:false,supportsDeviceAuth:false,observability:"dcode-marker",supportsMinimalBootstrap:false},pi:{inferenceApis:["openai-completions"],dashboardModes:["disabled"],inputModalities:[],webSearchProviders:[],toolGateways:[],tuningFields:["contextWindow","maxTokens","reasoning"],supportsMessaging:false,supportsInferenceCompatibility:false,supportsUpstreamEndpoint:false,supportsHostProxyIntent:true,supportsPrimaryModelRef:false,supportsAgentTimeout:false,supportsHeartbeat:false,supportsExtraAgents:false,supportsDeviceAuth:false,observability:"none",supportsMinimalBootstrap:false}};for(const agent of MANAGED_STARTUP_AGENTS){Object.defineProperty(PROFILE_CAPABILITIES,agent,{configurable:false,enumerable:true,value:freezeAgentCapabilities(PROFILE_CAPABILITIES[agent]),writable:false})}var MANAGED_STARTUP_PROFILE_CAPABILITIES=Object.freeze(PROFILE_CAPABILITIES);function affordance(input,profilePath,source="docker-arg",representation="value"){return{input,profilePath,source,representation}}var HOST_PROXY_AFFORDANCES=[affordance("HTTP_PROXY","proxy.hostHttpUrl","runtime-env"),affordance("http_proxy","proxy.hostHttpUrl","runtime-env","derived"),affordance("HTTPS_PROXY","proxy.hostHttpsUrl","runtime-env"),affordance("https_proxy","proxy.hostHttpsUrl","runtime-env","derived"),affordance("NO_PROXY","proxy.hostNoProxy","runtime-env"),affordance("no_proxy","proxy.hostNoProxy","runtime-env","derived")];var MANAGED_STARTUP_PROFILE_AFFORDANCE_INVENTORY={openclaw:[affordance("NEMOCLAW_MODEL","inference.model"),affordance("NEMOCLAW_INFERENCE_PROVIDER_ID","inference.routeProvider"),affordance("NEMOCLAW_UPSTREAM_PROVIDER","inference.upstreamProvider"),affordance("NEMOCLAW_SERVING_PRESET","inference.servingPreset"),affordance("NEMOCLAW_PRIMARY_MODEL_REF","inference.primaryModelRef"),affordance("NEMOCLAW_INFERENCE_BASE_URL","inference.routedBaseUrl"),affordance("NEMOCLAW_INFERENCE_API","inference.api"),affordance("NEMOCLAW_INFERENCE_COMPAT_B64","inference.compatibility"),affordance("NEMOCLAW_INFERENCE_INPUTS","inference.inputModalities"),affordance("NEMOCLAW_CONTEXT_WINDOW","tuning.contextWindow"),affordance("NEMOCLAW_MAX_TOKENS","tuning.maxTokens"),affordance("NEMOCLAW_REASONING","tuning.reasoning"),affordance("NEMOCLAW_REASONING_EFFORT","tuning.reasoningEffort"),affordance("NEMOCLAW_TOOL_DISCLOSURE","tools.disclosure"),affordance("NEMOCLAW_AGENT_TIMEOUT","agentConfig.agentTimeoutSeconds"),affordance("NEMOCLAW_AGENT_HEARTBEAT_EVERY","agentConfig.heartbeatEvery"),affordance("NEMOCLAW_EXTRA_AGENTS_JSON_B64","agentConfig.extraAgents"),affordance("NEMOCLAW_WEB_SEARCH_ENABLED","agentConfig.webSearch.enabled"),affordance("NEMOCLAW_WEB_SEARCH_PROVIDER","agentConfig.webSearch.provider"),affordance("NEMOCLAW_OPENCLAW_OTEL","agentConfig.otel.enabled"),affordance("NEMOCLAW_OPENCLAW_OTEL_ENDPOINT","agentConfig.otel.endpointUrl"),affordance("NEMOCLAW_OPENCLAW_OTEL_SERVICE_NAME","agentConfig.otel.serviceName"),affordance("NEMOCLAW_OPENCLAW_OTEL_SAMPLE_RATE","agentConfig.otel.sampleRate"),affordance("CHAT_UI_URL","dashboard.url"),affordance("NEMOCLAW_DASHBOARD_BIND","dashboard.bindAddress"),affordance("NEMOCLAW_WSL_DASHBOARD_EXPOSURE","dashboard.wslExposure"),affordance("NEMOCLAW_DASHBOARD_PORT","dashboard.port","runtime-env"),affordance("NEMOCLAW_PROXY_HOST","proxy.managedHost"),affordance("NEMOCLAW_PROXY_PORT","proxy.managedPort"),affordance("NEMOCLAW_MESSAGING_PLAN_B64","messaging.plan"),affordance("NEMOCLAW_MINIMAL_BOOTSTRAP","agentConfig.minimalBootstrap","runtime-env"),affordance("NEMOCLAW_CORPORATE_CA_B64","corporateCa.bundleSha256","host-material","digest-handoff"),...HOST_PROXY_AFFORDANCES],hermes:[affordance("NEMOCLAW_MODEL","inference.model"),affordance("NEMOCLAW_INFERENCE_PROVIDER_ID","inference.routeProvider"),affordance("NEMOCLAW_UPSTREAM_PROVIDER","inference.upstreamProvider"),affordance("NEMOCLAW_INFERENCE_BASE_URL","inference.routedBaseUrl"),affordance("NEMOCLAW_INFERENCE_API","inference.api"),affordance("NEMOCLAW_CONTEXT_WINDOW","tuning.contextWindow"),affordance("NEMOCLAW_TOOL_DISCLOSURE","tools.disclosure"),affordance("NEMOCLAW_HERMES_TOOL_GATEWAY_BROKER","tools.enabledGateways","docker-arg","derived"),affordance("NEMOCLAW_HERMES_TOOL_GATEWAY_PRESETS_B64","tools.enabledGateways"),affordance("NEMOCLAW_HERMES_SWITCHYARD_ROUTING_B64","agentConfig.switchyardRouting","runtime-env"),affordance("NEMOCLAW_HERMES_SWITCHYARD_BINDINGS_B64","agentConfig.switchyardBindings","runtime-env"),affordance("NEMOCLAW_WEB_SEARCH_ENABLED","agentConfig.webSearch.enabled"),affordance("NEMOCLAW_WEB_SEARCH_PROVIDER","agentConfig.webSearch.provider"),affordance("NEMOCLAW_MESSAGING_PLAN_B64","messaging.plan"),affordance("CHAT_UI_URL","dashboard.browserUrl"),affordance("NEMOCLAW_DASHBOARD_PORT","dashboard.publicPort","runtime-env"),affordance("NEMOCLAW_HERMES_DASHBOARD","dashboard.mode","runtime-env"),affordance("NEMOCLAW_HERMES_DASHBOARD_PORT","dashboard.publicPort","runtime-env"),affordance("NEMOCLAW_HERMES_DASHBOARD_INTERNAL_PORT","dashboard.internalPort","runtime-env"),affordance("NEMOCLAW_HERMES_DASHBOARD_TUI","dashboard.tuiEnabled","runtime-env"),affordance("NEMOCLAW_PROXY_HOST","proxy.managedHost","runtime-env"),affordance("NEMOCLAW_PROXY_PORT","proxy.managedPort","runtime-env"),affordance("NEMOCLAW_CORPORATE_CA_B64","corporateCa.bundleSha256","host-material","digest-handoff"),...HOST_PROXY_AFFORDANCES],"langchain-deepagents-code":[affordance("NEMOCLAW_MODEL","inference.model"),affordance("NEMOCLAW_INFERENCE_PROVIDER_ID","inference.routeProvider"),affordance("NEMOCLAW_UPSTREAM_PROVIDER","inference.upstreamProvider"),affordance("NEMOCLAW_UPSTREAM_ENDPOINT_URL","inference.upstreamEndpointUrl"),affordance("NEMOCLAW_INFERENCE_BASE_URL","inference.routedBaseUrl"),affordance("NEMOCLAW_INFERENCE_API","inference.api"),affordance("NEMOCLAW_REASONING_EFFORT","tuning.reasoningEffort"),affordance("NEMOCLAW_TOOL_DISCLOSURE","tools.disclosure"),affordance("NEMOCLAW_DCODE_AUTO_APPROVAL","agentConfig.autoApprovalMode"),affordance("NEMOCLAW_PROXY_HOST","proxy.managedHost"),affordance("NEMOCLAW_PROXY_PORT","proxy.managedPort"),affordance("NEMOCLAW_OBSERVABILITY","agentConfig.observabilityEnabled","runtime-env"),affordance("NEMOCLAW_CORPORATE_CA_B64","corporateCa.bundleSha256","host-material","digest-handoff"),...HOST_PROXY_AFFORDANCES],pi:[affordance("NEMOCLAW_MODEL","inference.model"),affordance("NEMOCLAW_INFERENCE_PROVIDER_ID","inference.routeProvider"),affordance("NEMOCLAW_UPSTREAM_PROVIDER","inference.upstreamProvider"),affordance("NEMOCLAW_INFERENCE_BASE_URL","inference.routedBaseUrl"),affordance("NEMOCLAW_INFERENCE_API","inference.api"),affordance("NEMOCLAW_CONTEXT_WINDOW","tuning.contextWindow"),affordance("NEMOCLAW_MAX_TOKENS","tuning.maxTokens"),affordance("NEMOCLAW_REASONING","tuning.reasoning"),affordance("NEMOCLAW_TOOL_DISCLOSURE","tools.disclosure"),affordance("NEMOCLAW_PROXY_HOST","proxy.managedHost"),affordance("NEMOCLAW_PROXY_PORT","proxy.managedPort"),affordance("NEMOCLAW_CORPORATE_CA_B64","corporateCa.bundleSha256","host-material","digest-handoff"),...HOST_PROXY_AFFORDANCES]};function deferredRuntimeInput(input,owner,reason,admission="managed-launch-forwarded"){return Object.freeze({input,owner,admission,reason})}var MANAGED_STARTUP_PROFILE_DEFERRED_RUNTIME_INPUTS=Object.freeze({openclaw:Object.freeze([deferredRuntimeInput("NEMOCLAW_AUTO_PAIR_DEADLINE_SECS","application-environment","operator scheduler tuning is applied by the application environment transaction"),deferredRuntimeInput("NEMOCLAW_AUTO_PAIR_FAST_DEADLINE_SECS","application-environment","operator scheduler tuning is applied by the application environment transaction"),deferredRuntimeInput("NEMOCLAW_AUTO_PAIR_FAST_REENTRY_INTERVAL_SECS","application-environment","operator scheduler tuning is applied by the application environment transaction"),deferredRuntimeInput("NEMOCLAW_AUTO_PAIR_FAST_REENTRY_POLLS","application-environment","operator scheduler tuning is applied by the application environment transaction"),deferredRuntimeInput("NEMOCLAW_AUTO_PAIR_RUN_TIMEOUT_SECS","application-environment","operator scheduler tuning is applied by the application environment transaction"),deferredRuntimeInput("NEMOCLAW_AUTO_PAIR_SLOW_INTERVAL_SECS","application-environment","operator scheduler tuning is applied by the application environment transaction"),deferredRuntimeInput("NEMOCLAW_MCP_SHADOW_DIAGNOSTICS","application-environment","operator shadow-diagnostics tuning is applied by the application environment transaction"),deferredRuntimeInput("NEMOCLAW_MCP_TOOLS_LIST_TIMEOUT_MS","application-environment","operator MCP discovery timeout tuning is applied by the application environment transaction"),deferredRuntimeInput("OPENCLAW_HOME","fixed-image-contract","the managed image and agent definition own this fixed runtime layout path"),deferredRuntimeInput("OPENCLAW_STATE_DIR","fixed-image-contract","the managed image and agent definition own this fixed runtime layout path"),deferredRuntimeInput("OPENCLAW_WORKSPACE_DIR","fixed-image-contract","the managed image and agent definition own this fixed runtime layout path"),deferredRuntimeInput("NEMOCLAW_EXTRA_PLACEHOLDER_KEYS","credential-plumbing","credential provider construction owns key metadata outside the secret-free profile")]),hermes:Object.freeze([deferredRuntimeInput("NEMOCLAW_EXTRA_PLACEHOLDER_KEYS","credential-plumbing","credential provider construction owns key metadata outside the secret-free profile")]),"langchain-deepagents-code":Object.freeze([deferredRuntimeInput("NEMOCLAW_SANDBOX_NAME","engine-identity","the lifecycle engine owns instance identity outside reusable startup intent"),deferredRuntimeInput("NEMOCLAW_EXTRA_PLACEHOLDER_KEYS","credential-plumbing","credential provider construction owns key metadata outside the secret-free profile")]),pi:Object.freeze([deferredRuntimeInput("NEMOCLAW_EXTRA_PLACEHOLDER_KEYS","credential-plumbing","credential provider construction owns key metadata outside the secret-free profile")])});function runtimeCleanupObligation(input,emittedFor,supportedFor,reason){return Object.freeze({input,emittedFor:Object.freeze([...emittedFor]),supportedFor:Object.freeze([...supportedFor]),owner:"application-environment",reason})}var MANAGED_STARTUP_RUNTIME_CLEANUP_OBLIGATIONS=Object.freeze([runtimeCleanupObligation("NEMOCLAW_DASHBOARD_BIND",["hermes"],["openclaw"],"generic managed-dashboard construction currently emits the OpenClaw-only bind control for Hermes"),runtimeCleanupObligation("NEMOCLAW_MINIMAL_BOOTSTRAP",["hermes","langchain-deepagents-code"],["openclaw"],"generic host-proxy construction currently emits the OpenClaw-only bootstrap control for other agents")]);var ManagedStartupProfileError=class extends Error{constructor(message){super(`Invalid managed startup profile: ${message}`);this.name="ManagedStartupProfileError"}};var PROFILE_KEYS=new Set(["schemaVersion","agent","agentConfig","inference","proxy","dashboard","tools","messaging","tuning","corporateCa"]);var INFERENCE_KEYS=new Set(["routeProvider","upstreamProvider","servingPreset","model","routedBaseUrl","upstreamEndpointUrl","api","primaryModelRef","compatibility","inputModalities"]);var PROXY_KEYS=new Set(["managedHost","managedPort","hostHttpUrl","hostHttpsUrl","hostNoProxy"]);var OPENCLAW_DASHBOARD_KEYS=new Set(["agent","mode","url","port","bindAddress","wslExposure"]);var HERMES_DASHBOARD_KEYS=new Set(["agent","mode","url","browserUrl","publicPort","internalPort","tuiEnabled"]);var DCODE_DASHBOARD_KEYS=new Set(["agent","mode"]);var TOOLS_KEYS=new Set(["disclosure","enabledGateways"]);var MESSAGING_KEYS=new Set(["plan"]);var TUNING_FIELD_ORDER=["contextWindow","maxTokens","reasoning","reasoningEffort"];var TUNING_KEYS=new Set(TUNING_FIELD_ORDER);var CORPORATE_CA_KEYS=new Set(["bundleSha256"]);var OPENCLAW_CONFIG_KEYS=new Set(["agent","webSearch","otel","agentTimeoutSeconds","heartbeatEvery","extraAgents","minimalBootstrap"]);var LEGACY_OPENCLAW_CONFIG_KEYS=new Set([...OPENCLAW_CONFIG_KEYS,"deviceAuth"]);var LEGACY_DEVICE_AUTH_KEYS=new Set(["disabled","optOutSource"]);var LEGACY_DEVICE_AUTH_OPT_OUT_SOURCES=new Set(["operator","managed-onboard"]);var HERMES_CONFIG_KEYS=new Set(["agent","webSearch","switchyardRouting","switchyardBindings"]);var DCODE_CONFIG_KEYS=new Set(["agent","autoApprovalMode","observabilityEnabled"]);var PI_CONFIG_KEYS=new Set(["agent"]);var PI_DASHBOARD_KEYS=new Set(["agent","mode"]);var WEB_SEARCH_KEYS=new Set(["enabled","provider"]);var OTEL_KEYS=new Set(["enabled","endpointUrl","serviceName","sampleRate"]);var EXTRA_AGENTS_KEYS=new Set(["agents","defaults","main"]);var MANAGED_STARTUP_AGENT_SET=new Set(MANAGED_STARTUP_AGENTS);var DCODE_AUTO_APPROVAL_MODE_SET=new Set(MANAGED_STARTUP_DCODE_AUTO_APPROVAL_MODES);var REASONING_EFFORT_SET=new Set(MANAGED_STARTUP_REASONING_EFFORTS);var HERMES_INTERNAL_API_PORT=18642;var HERMES_API_PORT_RANGE_START=8642;var HERMES_API_PORT_RANGE_END=8652;function isHermesApiPort(port){return port>=HERMES_API_PORT_RANGE_START&&port<=HERMES_API_PORT_RANGE_END}function isHermesReservedApiPort(port){return port===HERMES_INTERNAL_API_PORT||isHermesApiPort(port)}var HERMES_RESERVED_API_PORT_LABEL=`${HERMES_API_PORT_RANGE_START}-${HERMES_API_PORT_RANGE_END} or ${HERMES_INTERNAL_API_PORT}`;function isPlainObject(value){if(typeof value!=="object"||value===null||Array.isArray(value))return false;const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function isCredentialShapedName(name){if(PUBLIC_KEY_NAME_PATTERN.test(name)||NON_SECRET_KEY_METADATA_NAMES.has(name))return false;return CREDENTIAL_SHAPED_NAME_PATTERN.test(name)||CREDENTIAL_COMPOUND_NAME_PATTERN.test(name)||CREDENTIAL_CAMEL_SUFFIX_PATTERN.test(name)||CREDENTIAL_CAMEL_BOUNDARY_PATTERN.test(name)||CREDENTIAL_ENV_NAME_PATTERN.test(name)||CREDENTIAL_HEADER_NAME_PATTERN.test(name)||PASS_CREDENTIAL_NAME_PATTERN.test(name)}function valueLooksLikeSecret(value){for(let index=0;index=5&&path4[0]==="messaging"&&path4[1]==="plan"&&path4[2]==="agentRender"&&JSON_ARRAY_INDEX_SEGMENT_RE.test(path4[3]??"")&&path4[4]==="value";const isAuthorizedBuildStepPlaceholder=allowedBuildStepPlaceholders.has(buildStepPlaceholderKey(path4,value));return isCredentialBindingPlaceholder||isAgentRenderValuePlaceholder||isAuthorizedBuildStepPlaceholder}function requiresMessagingSchemaFieldAuthorization(path4){const fieldName=path4[path4.length-1];return fieldName==="webhook"}function messagingAuthorizedFieldKey(path4){return JSON.stringify(path4)}function buildStepPlaceholderKey(path4,value){return JSON.stringify([path4,value])}function messagingCredentialPlaceholderEnvKey(value){if(!MESSAGING_CREDENTIAL_PLACEHOLDER_RE.test(value))return null;const marker=value.startsWith("openshell:resolve:env:")?"openshell:resolve:env:":"-OPENSHELL-RESOLVE-ENV-";const key=value.slice(value.indexOf(marker)+marker.length);return key.replace(/^(?:v[0-9]{1,20}|s[a-f0-9]{64})_/u,"")}function containsMessagingCredentialPlaceholder(value){return value.includes("openshell:resolve:env:")||value.includes("-OPENSHELL-RESOLVE-ENV-")}function isMessagingCredentialPlaceholderAssignment(selectedAgent,path4,value){if(path4.length!==6||path4[0]!=="messaging"||path4[1]!=="plan"||path4[2]!=="agentRender"||!JSON_ARRAY_INDEX_SEGMENT_RE.test(path4[3]??"")||path4[4]!=="lines"||!JSON_ARRAY_INDEX_SEGMENT_RE.test(path4[5]??"")){return false}const separator=value.indexOf("=");if(separator<=0||value.indexOf("=",separator+1)!==-1)return false;const envKey=value.slice(0,separator);const placeholder=value.slice(separator+1);const placeholderEnvKey=messagingCredentialPlaceholderEnvKey(placeholder);return CREDENTIAL_ENV_NAME_PATTERN.test(envKey)&&placeholderEnvKey!==null&&(envKey===placeholderEnvKey||typeof selectedAgent==="string"&&MESSAGING_CREDENTIAL_ENV_ALIASES.has(`${selectedAgent}\0${placeholderEnvKey}\0${envKey}`))}function isMessagingRuntimeEnvAliasPath(path4){return path4.length===5&&path4[0]==="messaging"&&path4[1]==="plan"&&path4[2]==="runtimeSetup"&&path4[3]==="envAliases"&&JSON_ARRAY_INDEX_SEGMENT_RE.test(path4[4]??"")}function ownDataPropertyValue4(value,key){const descriptor=Object.getOwnPropertyDescriptor(value,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}function isCanonicalMessagingRuntimeEnvAlias(selectedAgent,path4,value){if(!isMessagingRuntimeEnvAliasPath(path4))return false;const channelId=ownDataPropertyValue4(value,"channelId");const envKey=ownDataPropertyValue4(value,"envKey");const targetEnvKey=ownDataPropertyValue4(value,"targetEnvKey");const match=ownDataPropertyValue4(value,"match");const placeholder=ownDataPropertyValue4(value,"value");const expectedMatch=targetEnvKey===void 0?`^openshell:resolve:env:((?:v[0-9]{1,20}|s[a-f0-9]{64})_)?${envKey}$`:`^openshell:resolve:env:(?:v[0-9]{1,20}|s[a-f0-9]{64})_${envKey}$`;return typeof envKey==="string"&&CREDENTIAL_ENV_NAME_PATTERN.test(envKey)&&match===expectedMatch&&typeof placeholder==="string"&&messagingCredentialPlaceholderEnvKey(placeholder)===envKey&&(targetEnvKey===void 0||typeof selectedAgent==="string"&&typeof channelId==="string"&&typeof targetEnvKey==="string"&&CREDENTIAL_ENV_NAME_PATTERN.test(targetEnvKey)&&MESSAGING_CREDENTIAL_RUNTIME_ENV_ALIASES.has(`${selectedAgent}\0${channelId}\0${envKey}\0${targetEnvKey}`))}function isAllowedMessagingRuntimeAliasStringPath(path4,allowedAliasIndexes){return path4.length===6&&path4[0]==="messaging"&&path4[1]==="plan"&&path4[2]==="runtimeSetup"&&path4[3]==="envAliases"&&allowedAliasIndexes.has(path4[4]??"")&&(path4[5]==="match"||path4[5]==="value"||path4[5]==="targetEnvKey")}function isMessagingPackagePin(path4,value){return path4.length===6&&path4[0]==="messaging"&&path4[1]==="plan"&&path4[2]==="buildSteps"&&JSON_ARRAY_INDEX_SEGMENT_RE.test(path4[3]??"")&&path4[4]==="value"&&path4[5]==="pin"&&typeof value==="boolean"}function containsUrlWithCredentialMaterial(value){const candidates=value.match(URL_CANDIDATE_RE)??[];for(let index=0;index{if(isCredentialShapedName(key))credentialQuery=true});const fragment=url.hash.startsWith("#")?url.hash.slice(1):url.hash;const queryStart=fragment.indexOf("?");const fragmentParameters=new URLSearchParams(queryStart>=0?fragment.slice(queryStart+1):fragment);let credentialFragment=false;fragmentParameters.forEach((_fragmentValue,key)=>{if(isCredentialShapedName(key))credentialFragment=true});if(url.username||url.password||credentialQuery||credentialFragment)return true}catch{}}return false}function invalid(reason){throw new ManagedStartupProfileError(reason)}function payloadPath(path4){return path4.reduce((result,segment)=>segment.startsWith("[")?`${result}${segment}`:`${result}${result?".":""}${segment}`,"")}function mapArrayByIndex(values,mapper){const mapped=[];for(let index=0;index0&&values[insertion-1]>selected){Object.defineProperty(values,String(insertion),{configurable:true,enumerable:true,value:values[insertion-1],writable:true});insertion-=1}Object.defineProperty(values,String(insertion),{configurable:true,enumerable:true,value:selected,writable:true})}return values}function requireRecord(value,where){if(!isPlainObject(value))invalid(`${where} must be an object`);return value}function rejectUnknownKeys2(value,allowed,where){const keys=Object.keys(value);for(let index=0;indexmaxBytes||CONTROL_CHARACTER_RE.test(value)){invalid(`${where} must be a bounded, non-empty string without control characters`)}return value}function requireStringEnum(value,allowed,where){const normalized=requireBoundedString(value,where);if(!allowed.has(normalized))invalid(`${where} is not supported`);return normalized}function requireNullablePositiveInteger(value,where){if(value===null)return null;if(typeof value!=="number"||!Number.isSafeInteger(value)||value<1||value>MAX_TUNING_INTEGER){invalid(`${where} must be null or a bounded positive integer`)}return value}function requirePositiveInteger(value,where,maximum=MAX_TUNING_INTEGER){if(typeof value!=="number"||!Number.isSafeInteger(value)||value<1||value>maximum){invalid(`${where} must be a bounded positive integer`)}return value}function requirePort(value,where,minimum=1){if(typeof value!=="number"||!Number.isInteger(value)||value<1||value>65535){invalid(`${where} must be a valid TCP port`)}if(valueMAX_LIST_ITEMS){invalid(`${where} must be a bounded string list`)}const items=mapArrayByIndex(value,item=>requireBoundedString(item,`${where} item`));const unique2=new Set;for(let index=0;index{if(depth>MAX_JSON_DEPTH)invalid(`${where} exceeds the JSON depth limit`);if(current===null||typeof current==="string"||typeof current==="boolean"){return current}if(typeof current==="number"){if(!Number.isFinite(current))invalid(`${where} contains a non-finite number`);return current}if(Array.isArray(current)){return mapArrayByIndex(current,item=>clone(item,depth+1))}if(!isPlainObject(current))invalid(`${where} contains a non-JSON value`);const result=options.nullPrototypeObjects?Object.create(null):{};const keys=Object.getOwnPropertyNames(current);for(let index=0;indexMAX_IDENTIFIER_BYTES||CONTROL_CHARACTER_RE.test(key)){invalid(`${where} contains an invalid object key`)}const descriptor=Object.getOwnPropertyDescriptor(current,key);if(!descriptor||!("value"in descriptor)){invalid(`${where} contains a non-JSON value`)}Object.defineProperty(result,key,{configurable:true,enumerable:true,value:clone(descriptor.value,depth+1),writable:true})}return result};return clone(value,0)}function requireJsonObjectOrNull(value,where){if(value===null)return null;if(!isPlainObject(value))invalid(`${where} must be null or a plain JSON object`);return cloneJsonValue(value,where,{nullPrototypeObjects:true})}function requireJsonObject(value,where){const object=requireJsonObjectOrNull(value,where);if(object===null)invalid(`${where} must be a plain JSON object`);return object}function requireHttpUrl(value,where){const raw=requireBoundedString(value,where,MAX_URL_BYTES);let parsed;try{parsed=new URL(raw)}catch{invalid(`${where} must be a valid HTTP(S) URL`)}if(parsed.protocol!=="http:"&&parsed.protocol!=="https:"||parsed.username||parsed.password||parsed.search||parsed.hash){invalid(`${where} must be a credential-free HTTP(S) URL without query or fragment data`)}const pathname=parsed.pathname.replace(/\/+$/u,"");return pathname===""?parsed.origin:`${parsed.origin}${pathname}`}function requireProxyUrl(value,allowedSchemes,where){if(value===null)return null;const raw=requireBoundedString(value,where,MAX_URL_BYTES);let parsed;try{parsed=new URL(raw)}catch{invalid(`${where} must be a valid HTTP(S) proxy URL`)}if(!allowedSchemes.has(parsed.protocol)||parsed.username||parsed.password||parsed.pathname!=="/"||parsed.search||parsed.hash){invalid(`${where} must be a credential-free HTTP(S) proxy origin`)}return parsed.origin}function requireManagedProxyHost(value,where){const host=requireBoundedString(value,where);if(!/^[A-Za-z0-9._-]+$/u.test(host)){invalid(`${where} must be a hostname or IPv4 address without a scheme or separators`)}return host}function configuredDashboardPort(value){const explicit=new URL(value).port;return explicit===""?18789:Number(explicit)}function requireSampleRate(value,where){if(typeof value!=="number"||!Number.isFinite(value)||value<0||value>1){invalid(`${where} must be a number between 0 and 1`)}return value}function assertPayloadStructureAndCredentialShapes(root){const pending=[{value:root,depth:0,path:[]}];const allowedRuntimeAliasIndexes=new Set;const allowedMessagingCredentialFields=new Set;const allowedBuildStepPlaceholders=new Set;const selectedAgent=isPlainObject(root)?ownDataPropertyValue4(root,"agent"):void 0;let discoveredNodes=1;let observedBytes=0;const observeText=value=>{observedBytes+=import_node_buffer2.Buffer.byteLength(value,"utf8");if(observedBytes>MANAGED_STARTUP_PROFILE_MAX_BYTES){invalid(`payload exceeds ${String(MANAGED_STARTUP_PROFILE_MAX_BYTES)} bytes`)}};const reserveNode=depth=>{discoveredNodes+=1;if(discoveredNodes>MAX_JSON_NODES||depth>MAX_JSON_DEPTH){invalid("payload structure exceeds the complexity limit")}observedBytes+=1};while(pending.length>0){const current=pending.pop();if(!current)break;if(current.depth>MAX_JSON_DEPTH){invalid("payload structure exceeds the complexity limit")}if(typeof current.value==="string"){observeText(current.value);if(!isAllowedMessagingRuntimeAliasStringPath(current.path,allowedRuntimeAliasIndexes)&&!isMessagingCredentialPlaceholder(current.path,current.value,allowedBuildStepPlaceholders,allowedMessagingCredentialFields)&&!isMessagingCredentialPlaceholderAssignment(selectedAgent,current.path,current.value)&&(valueLooksLikeSecret(current.value)||containsMessagingCredentialPlaceholder(current.value))){invalid(`payload field ${payloadPath(current.path)} contains credential-shaped string data`)}if(RAW_CA_PEM_RE.test(current.value)||RAW_CA_PEM_BASE64_RE.test(current.value)||RAW_CA_DER_BASE64_RE.test(current.value)||RAW_CA_DATA_URI_RE.test(current.value)){invalid(`payload field ${payloadPath(current.path)} contains raw certificate data; provide only the CA SHA-256 digest`)}if(containsUrlWithCredentialMaterial(current.value)){invalid(`payload field ${payloadPath(current.path)} contains a URL with embedded credentials`)}continue}if(Array.isArray(current.value)){if(Object.getPrototypeOf(current.value)!==Array.prototype){invalid("payload arrays must use the standard JSON prototype")}if("toJSON"in current.value){invalid("payload must not define a custom JSON serializer")}if(Object.getOwnPropertySymbols(current.value).length>0||Object.getOwnPropertyNames(current.value).length!==current.value.length+1){invalid("payload arrays must contain only indexed JSON values")}for(let index=0;index0||discoveredNodes+keys.length>MAX_JSON_NODES){invalid("payload structure exceeds the complexity limit")}for(let index=0;indexMANAGED_STARTUP_PROFILE_MAX_BYTES){invalid(`payload exceeds ${String(MANAGED_STARTUP_PROFILE_MAX_BYTES)} bytes`)}}function validateWebSearch(value,agent){const webSearch=requireRecord(value,"agentConfig.webSearch");rejectUnknownKeys2(webSearch,WEB_SEARCH_KEYS,"agentConfig.webSearch");const provider2=requireStringEnum(webSearch.provider,new Set(MANAGED_STARTUP_PROFILE_CAPABILITIES[agent].webSearchProviders),"agentConfig.webSearch.provider");return{enabled:requireBoolean(webSearch.enabled,"agentConfig.webSearch.enabled"),provider:provider2}}function validateOpenClawOtel(value){const otel=requireRecord(value,"agentConfig.otel");rejectUnknownKeys2(otel,OTEL_KEYS,"agentConfig.otel");return{enabled:requireBoolean(otel.enabled,"agentConfig.otel.enabled"),endpointUrl:requireHttpUrl(otel.endpointUrl,"agentConfig.otel.endpointUrl"),serviceName:requireBoundedString(otel.serviceName,"agentConfig.otel.serviceName",MAX_IDENTIFIER_BYTES),sampleRate:requireSampleRate(otel.sampleRate,"agentConfig.otel.sampleRate")}}function validateExtraAgents(value){const extraAgents=requireRecord(value,"agentConfig.extraAgents");rejectUnknownKeys2(extraAgents,EXTRA_AGENTS_KEYS,"agentConfig.extraAgents");if(!Array.isArray(extraAgents.agents)||extraAgents.agents.length>MAX_LIST_ITEMS){invalid("agentConfig.extraAgents.agents must be a bounded JSON object list")}return{agents:mapArrayByIndex(extraAgents.agents,(agent,index)=>requireJsonObject(agent,`agentConfig.extraAgents.agents[${String(index)}]`)),defaults:requireJsonObject(extraAgents.defaults,"agentConfig.extraAgents.defaults"),main:requireJsonObject(extraAgents.main,"agentConfig.extraAgents.main")}}function validateAgentConfig(value,expectedAgent,allowStoredLegacyRouting){const config=requireRecord(value,"agentConfig");const agent=requireStringEnum(config.agent,MANAGED_STARTUP_AGENT_SET,"agentConfig.agent");if(agent!==expectedAgent)invalid("agentConfig.agent must match agent");if(agent==="openclaw"){rejectUnknownKeys2(config,OPENCLAW_CONFIG_KEYS,"agentConfig");const heartbeatEvery=config.heartbeatEvery===null?null:requireBoundedString(config.heartbeatEvery,"agentConfig.heartbeatEvery",MAX_IDENTIFIER_BYTES);if(heartbeatEvery!==null&&!/^\d+(?:s|m|h)$/u.test(heartbeatEvery)){invalid("agentConfig.heartbeatEvery must be null or a duration ending in s, m, or h")}return{agent,webSearch:validateWebSearch(config.webSearch,agent),otel:validateOpenClawOtel(config.otel),agentTimeoutSeconds:requirePositiveInteger(config.agentTimeoutSeconds,"agentConfig.agentTimeoutSeconds"),heartbeatEvery,extraAgents:validateExtraAgents(config.extraAgents),minimalBootstrap:requireBoolean(config.minimalBootstrap,"agentConfig.minimalBootstrap")}}if(agent==="hermes"){rejectUnknownKeys2(config,HERMES_CONFIG_KEYS,"agentConfig");const hasSwitchyardRouting=Object.hasOwn(config,"switchyardRouting");const switchyardRouting=!hasSwitchyardRouting||config.switchyardRouting===null?null:validateHermesSwitchyardRoutingIntent(config.switchyardRouting);const hasBindings=Object.hasOwn(config,"switchyardBindings");const legacyUnboundRouting=allowStoredLegacyRouting&&switchyardRouting?.judge.mode==="reuse-capable"&&!hasBindings;const switchyardBindings=switchyardRouting&&!legacyUnboundRouting?validateSwitchyardProviderBindings(config.switchyardBindings,switchyardRouting):null;if(!switchyardRouting&&config.switchyardBindings!=null)invalid("Switchyard bindings require an explicit routing configuration");return{agent,webSearch:validateWebSearch(config.webSearch,agent),...hasSwitchyardRouting?{switchyardRouting}:{},...hasBindings||switchyardRouting&&!legacyUnboundRouting?{switchyardBindings}:{}}}if(agent==="pi"){rejectUnknownKeys2(config,PI_CONFIG_KEYS,"agentConfig");return{agent}}rejectUnknownKeys2(config,DCODE_CONFIG_KEYS,"agentConfig");return{agent,autoApprovalMode:requireStringEnum(config.autoApprovalMode,DCODE_AUTO_APPROVAL_MODE_SET,"agentConfig.autoApprovalMode"),observabilityEnabled:requireBoolean(config.observabilityEnabled,"agentConfig.observabilityEnabled")}}function validateDashboard(value,expectedAgent){const dashboard=requireRecord(value,"dashboard");const agent=requireStringEnum(dashboard.agent,MANAGED_STARTUP_AGENT_SET,"dashboard.agent");if(agent!==expectedAgent)invalid("dashboard.agent must match agent");if(agent==="openclaw"){rejectUnknownKeys2(dashboard,OPENCLAW_DASHBOARD_KEYS,"dashboard");const mode=requireStringEnum(dashboard.mode,new Set(MANAGED_STARTUP_PROFILE_CAPABILITIES[agent].dashboardModes),"dashboard.mode");const url=requireHttpUrl(dashboard.url,"dashboard.url");const bindAddress=requireStringEnum(dashboard.bindAddress,new Set(["127.0.0.1","0.0.0.0"]),"dashboard.bindAddress");const wslExposure=requireBoolean(dashboard.wslExposure,"dashboard.wslExposure");const hasRemoteExposure=!isLoopbackDashboardUrl(url)||bindAddress==="0.0.0.0"||wslExposure;if(mode==="remote"!==hasRemoteExposure){invalid("OpenClaw dashboard.mode must reflect its URL, bind address, and WSL exposure")}const port=requirePort(dashboard.port,"dashboard.port",1024);if(isHermesApiPort(port))invalid(`OpenClaw dashboard.port must not use a reserved Hermes API port (${HERMES_API_PORT_RANGE_START}-${HERMES_API_PORT_RANGE_END})`);if(configuredDashboardPort(url)!==port){invalid("OpenClaw dashboard.port must match dashboard.url")}return{agent,mode,url,port,bindAddress,wslExposure}}if(agent==="hermes"){rejectUnknownKeys2(dashboard,HERMES_DASHBOARD_KEYS,"dashboard");const mode=requireStringEnum(dashboard.mode,new Set(MANAGED_STARTUP_PROFILE_CAPABILITIES[agent].dashboardModes),"dashboard.mode");const url=requireHttpUrl(dashboard.url,"dashboard.url");if(!isLoopbackDashboardUrl(url)){invalid("Hermes dashboard.url must remain loopback; OpenShell owns the host forward")}const browserUrl=dashboard.browserUrl===void 0?void 0:requireHttpUrl(dashboard.browserUrl,"dashboard.browserUrl");if(browserUrl!==void 0&&!isLoopbackDashboardUrl(browserUrl)&&new URL(browserUrl).protocol!=="https:"){invalid("Hermes dashboard.browserUrl must use HTTPS unless it is loopback")}if(mode==="disabled"){if(dashboard.publicPort!==null||dashboard.internalPort!==null||dashboard.tuiEnabled!==false){invalid("disabled Hermes dashboard must not configure ports or TUI")}return{agent,mode,url,...browserUrl===void 0?{}:{browserUrl},publicPort:null,internalPort:null,tuiEnabled:false}}const publicPort=requirePort(dashboard.publicPort,"dashboard.publicPort",1024);const internalPort=requirePort(dashboard.internalPort,"dashboard.internalPort",1024);if(publicPort===internalPort){invalid("Hermes dashboard publicPort and internalPort must differ")}if(isHermesReservedApiPort(publicPort)||isHermesReservedApiPort(internalPort)){invalid(`Hermes dashboard ports must not use reserved API ports ${HERMES_RESERVED_API_PORT_LABEL}`)}if(configuredDashboardPort(url)!==publicPort){invalid("Hermes dashboard.publicPort must match dashboard.url")}if(browserUrl!==void 0&&isLoopbackDashboardUrl(browserUrl)&&configuredDashboardPort(browserUrl)!==publicPort){invalid("Hermes dashboard.publicPort must match dashboard.browserUrl")}return{agent,mode,url,...browserUrl===void 0?{}:{browserUrl},publicPort,internalPort,tuiEnabled:requireBoolean(dashboard.tuiEnabled,"dashboard.tuiEnabled")}}if(agent==="pi"){rejectUnknownKeys2(dashboard,PI_DASHBOARD_KEYS,"dashboard");if(dashboard.mode!=="disabled")invalid("pi dashboard.mode must be disabled");return{agent,mode:"disabled"}}rejectUnknownKeys2(dashboard,DCODE_DASHBOARD_KEYS,"dashboard");if(dashboard.mode!=="disabled"){invalid("langchain-deepagents-code dashboard.mode must be disabled")}return{agent,mode:"disabled"}}function validateInference(value,agent){if(value===null){if(agent!=="openclaw"&&agent!=="hermes")invalid(`${agent} requires inference configuration`);return null}const inference=requireRecord(value,"inference");rejectUnknownKeys2(inference,INFERENCE_KEYS,"inference");const routeProvider=requireBoundedString(inference.routeProvider,"inference.routeProvider");const upstreamProvider=requireBoundedString(inference.upstreamProvider,"inference.upstreamProvider");const servingPreset=inference.servingPreset===void 0?void 0:inference.servingPreset===null?null:requireBoundedString(inference.servingPreset,"inference.servingPreset");const model2=requireBoundedString(inference.model,"inference.model",MAX_MODEL_BYTES2);const api=requireStringEnum(inference.api,new Set(MANAGED_STARTUP_PROFILE_CAPABILITIES[agent].inferenceApis),"inference.api");const upstreamEndpointUrl=inference.upstreamEndpointUrl===null?null:requireHttpUrl(inference.upstreamEndpointUrl,"inference.upstreamEndpointUrl");const primaryModelRef=inference.primaryModelRef===null?null:requireBoundedString(inference.primaryModelRef,"inference.primaryModelRef",MAX_MODEL_BYTES2);const compatibility=requireJsonObjectOrNull(inference.compatibility,"inference.compatibility");const inputModalities=inference.inputModalities===null?null:requireEnumList(inference.inputModalities,new Set(MANAGED_STARTUP_PROFILE_CAPABILITIES[agent].inputModalities),"inference.inputModalities",{allowEmpty:false});if(upstreamEndpointUrl!==null&&!MANAGED_STARTUP_PROFILE_CAPABILITIES[agent].supportsUpstreamEndpoint){invalid(`inference.upstreamEndpointUrl must be null for ${agent}`)}if(agent==="openclaw"){if(primaryModelRef===null||inputModalities===null){invalid("openclaw requires primaryModelRef and inputModalities")}if(primaryModelRef!==`${routeProvider}/${model2}`){invalid("openclaw primaryModelRef must match routeProvider and model")}}else{if(primaryModelRef!==null||compatibility!==null||inputModalities!==null){invalid(`${agent} does not support primaryModelRef, compatibility, or inputModalities`)}if(agent==="langchain-deepagents-code"&&!isValidDcodeUpstreamProvider(upstreamProvider)){invalid("inference.upstreamProvider must start with an ASCII letter or digit and contain 1-64 ASCII letters, digits, dots, underscores, or hyphens for DCode")}}return{routeProvider,upstreamProvider,...servingPreset===void 0?{}:{servingPreset},model:model2,routedBaseUrl:requireHttpUrl(inference.routedBaseUrl,"inference.routedBaseUrl"),upstreamEndpointUrl,api,primaryModelRef,compatibility,inputModalities}}function validateProxy(value,agent){const proxy=requireRecord(value,"proxy");rejectUnknownKeys2(proxy,PROXY_KEYS,"proxy");const hostHttpUrl=requireProxyUrl(proxy.hostHttpUrl,new Set(["http:"]),"proxy.hostHttpUrl");const hostHttpsUrl=requireProxyUrl(proxy.hostHttpsUrl,new Set(["http:","https:"]),"proxy.hostHttpsUrl");const hostNoProxy=requireStringList(proxy.hostNoProxy,"proxy.hostNoProxy");if(!MANAGED_STARTUP_PROFILE_CAPABILITIES[agent].supportsHostProxyIntent&&(hostHttpUrl!==null||hostHttpsUrl!==null||hostNoProxy.length>0)){invalid(`${agent} rejects host proxy intent and accepts only its root-owned managed route`)}return{managedHost:requireManagedProxyHost(proxy.managedHost,"proxy.managedHost"),managedPort:requirePort(proxy.managedPort,"proxy.managedPort"),hostHttpUrl,hostHttpsUrl,hostNoProxy}}function validateTools(value,agent){const tools=requireRecord(value,"tools");rejectUnknownKeys2(tools,TOOLS_KEYS,"tools");const enabledGateways=requireEnumList(tools.enabledGateways,new Set(MANAGED_STARTUP_PROFILE_CAPABILITIES[agent].toolGateways),"tools.enabledGateways",{allowEmpty:true});return{disclosure:requireStringEnum(tools.disclosure,new Set(["progressive","direct"]),"tools.disclosure"),enabledGateways}}function validateTuning(value,agent){const tuning=requireRecord(value,"tuning");rejectUnknownKeys2(tuning,TUNING_KEYS,"tuning");const result={contextWindow:requireNullablePositiveInteger(tuning.contextWindow,"tuning.contextWindow"),maxTokens:requireNullablePositiveInteger(tuning.maxTokens,"tuning.maxTokens"),reasoning:requireNullableBoolean(tuning.reasoning,"tuning.reasoning"),reasoningEffort:tuning.reasoningEffort===null?null:requireStringEnum(tuning.reasoningEffort,REASONING_EFFORT_SET,"tuning.reasoningEffort")};const advertised=new Set(MANAGED_STARTUP_PROFILE_CAPABILITIES[agent].tuningFields);const unsupported=TUNING_FIELD_ORDER.filter(field=>result[field]!==null&&!advertised.has(field));if(unsupported.length>0){invalid(`${agent} does not support startup tuning fields: ${unsupported.join(", ")}`)}if(agent==="openclaw"){const missing=TUNING_FIELD_ORDER.filter(field=>advertised.has(field)&&result[field]===null);if(missing.length>0){invalid(`openclaw requires ${missing.join(", ")} tuning`)}}if(agent==="hermes"&&result.contextWindow!==null&&result.contextWindowcanonicalizeJson(item));if(!isPlainObject(value))return value;const result={};const keys=sortStrings(Object.keys(value));for(let index=0;indexMANAGED_STARTUP_PROFILE_MAX_BYTES){invalid(`canonical payload exceeds ${String(MANAGED_STARTUP_PROFILE_MAX_BYTES)} bytes`)}return serialized}function serializeManagedStartupProfile(profile){return serializeValidatedManagedStartupProfile(validateManagedStartupProfile(profile))}function decodeManagedStartupProfile(encoded){return decodeManagedStartupProfileValue(encoded,false)}function decodeManagedStartupProfileValue(encoded,allowStoredLegacyRouting){if(typeof encoded!=="string"||encoded.length===0||import_node_buffer2.Buffer.byteLength(encoded,"ascii")>MANAGED_STARTUP_PROFILE_MAX_ENCODED_BYTES||!BASE64URL_RE.test(encoded)||encoded.length%4===1){invalid("encoded payload is malformed or exceeds the size limit")}const bytes=import_node_buffer2.Buffer.from(encoded,"base64url");if(bytes.length===0||bytes.length>MANAGED_STARTUP_PROFILE_MAX_BYTES||bytes.toString("base64url")!==encoded){invalid("encoded payload is malformed or exceeds the size limit")}let raw;try{raw=UTF8_DECODER.decode(bytes)}catch{invalid("payload is not valid UTF-8")}let parsed;try{parsed=JSON.parse(raw)}catch{invalid("payload is not valid JSON")}const migration=migrateDecodedManagedStartupProfile(parsed);const profile=validateManagedStartupProfileValue(migration.value,allowStoredLegacyRouting);const canonicalPayload=migration.migratedLegacyProfile?JSON.stringify(canonicalizeJson(parsed)):serializeValidatedManagedStartupProfile(profile);if(canonicalPayload!==raw){invalid("payload is not in canonical form")}return profile}function fingerprintManagedStartupProfile(profile){return(0,import_node_crypto3.createHash)("sha256").update(serializeManagedStartupProfile(profile),"utf8").digest("hex")}var ManagedStartupAgentEnvironmentError=class extends Error{constructor(message){super(`Cannot map managed startup profile: ${message}`);this.name="ManagedStartupAgentEnvironmentError"}};var EMPTY_APPLICATION_ENVIRONMENT=Object.freeze({});var OPENCLAW_APPLICATION_RUNTIME_INPUTS=Object.freeze([["NEMOCLAW_AUTO_PAIR_DEADLINE_SECS","positive-finite-seconds"],["NEMOCLAW_AUTO_PAIR_FAST_DEADLINE_SECS","positive-finite-seconds"],["NEMOCLAW_AUTO_PAIR_FAST_REENTRY_INTERVAL_SECS","positive-finite-seconds"],["NEMOCLAW_AUTO_PAIR_FAST_REENTRY_POLLS","positive-safe-integer"],["NEMOCLAW_AUTO_PAIR_RUN_TIMEOUT_SECS","positive-finite-seconds"],["NEMOCLAW_AUTO_PAIR_SLOW_INTERVAL_SECS","positive-finite-seconds"]]);function booleanFlag(value){return value?"1":"0"}function canonicalizeJson2(value){if(Array.isArray(value))return value.map(item=>canonicalizeJson2(item));if(value===null||typeof value!=="object")return value;const record2=value;return Object.fromEntries(Object.keys(record2).sort().map(key=>[key,canonicalizeJson2(record2[key])]))}function encodeCanonicalJson(value){return import_node_buffer3.Buffer.from(JSON.stringify(canonicalizeJson2(value)),"utf8").toString("base64")}function sortedEnvironment(environment){return Object.freeze(Object.fromEntries(Object.entries(environment).sort(([left],[right])=>leftright?1:0)))}function canonicalApplicationRuntimeValue(name,raw,kind){if(raw.includes("\0")||/[\r\n]/u.test(raw)){throw new ManagedStartupAgentEnvironmentError(`${name} must be single-line text`)}const value=Number(raw.trim());const valid=kind==="positive-safe-integer"?Number.isSafeInteger(value)&&value>0:Number.isFinite(value)&&value>0;if(!valid){throw new ManagedStartupAgentEnvironmentError(`${name} must be ${kind==="positive-safe-integer"?"a positive safe integer":"finite positive seconds"}`)}return String(value)}function applicationRuntimePlan(profile,environment){const exportEnvironment={};if(profile.agent==="openclaw"){for(const[name,kind]of OPENCLAW_APPLICATION_RUNTIME_INPUTS){const raw=environment[name];if(raw!==void 0){exportEnvironment[name]=canonicalApplicationRuntimeValue(name,raw,kind)}}}const unsetEnvironment=new Set(MANAGED_STARTUP_RUNTIME_CLEANUP_OBLIGATIONS.filter(({supportedFor})=>!supportedFor.includes(profile.agent)).map(({input})=>input));if(profile.agent!=="openclaw"){for(const[name]of OPENCLAW_APPLICATION_RUNTIME_INPUTS){unsetEnvironment.add(name)}}return Object.freeze({exportEnvironment:sortedEnvironment(exportEnvironment),unsetEnvironment:Object.freeze([...unsetEnvironment].sort())})}function commonConfigurationEnvironment(profile){if(profile.inference===null)return{...PROVIDERLESS_INFERENCE_ENV,NEMOCLAW_TOOL_DISCLOSURE:profile.tools.disclosure};return{NEMOCLAW_INFERENCE_API:profile.inference.api,NEMOCLAW_INFERENCE_BASE_URL:profile.inference.routedBaseUrl,NEMOCLAW_INFERENCE_PROVIDER_ID:profile.inference.routeProvider,NEMOCLAW_MODEL:profile.inference.model,NEMOCLAW_TOOL_DISCLOSURE:profile.tools.disclosure,NEMOCLAW_UPSTREAM_PROVIDER:profile.inference.upstreamProvider}}function appendHostProxyEnvironment(environment,profile,options={}){if(options.preserveAmbientWhenAbsent===true&&profile.proxy.hostHttpUrl===null&&profile.proxy.hostHttpsUrl===null&&profile.proxy.hostNoProxy.length===0){return}const httpProxy=profile.proxy.hostHttpUrl??"";const httpsProxy=profile.proxy.hostHttpsUrl??"";const noProxy=profile.proxy.hostNoProxy.join(",");environment.HTTP_PROXY=httpProxy;environment.HTTPS_PROXY=httpsProxy;environment.NO_PROXY=noProxy;environment.http_proxy=httpProxy;environment.https_proxy=httpsProxy;environment.no_proxy=noProxy}function messagingEnvironment(profile,expectedAgent){if(profile.messaging.plan===null)return{};const plan=parseSandboxMessagingPlan(profile.messaging.plan,{agent:expectedAgent});if(!plan){throw new ManagedStartupAgentEnvironmentError(`messaging.plan must contain a validated ${expectedAgent} messaging plan`)}const{workflow:_workflow,...imageBuildPlan}=plan;return{NEMOCLAW_MESSAGING_PLAN_B64:encodeCanonicalJson(imageBuildPlan)}}function corporateCaMaterial(profile){return Object.freeze({kind:"corporate-ca-handoff",legacyInput:"NEMOCLAW_CORPORATE_CA_B64",expectedSha256:profile.corporateCa.bundleSha256})}function rootOwnedFile(legacyInput,path4,value){return Object.freeze({kind:"root-owned-file",legacyInput,path:path4,contents:`${value} @@ -19,7 +19,15 @@ except urllib.error.HTTPError as error: print(error.code)"`]}}],render:[{id:"dis `;if(Buffer.byteLength(serialized,"utf8")>MANAGED_STARTUP_ROOT_APPLY_MAX_BYTES){fail4("serialized request exceeds its bounded transport")}return serialized}function parseManagedStartupRootApplyRequest(text){if(text.length===0||Buffer.byteLength(text,"utf8")>MANAGED_STARTUP_ROOT_APPLY_MAX_BYTES){fail4("serialized request is empty or too large")}let parsed;try{parsed=JSON.parse(text)}catch{fail4("serialized request is not valid JSON")}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){fail4("serialized request must be an object")}const record2=parsed;const expectedKeys=["agent","corporateCaB64","encodedProfile","profileFingerprint","schemaVersion"];if(Object.keys(record2).sort().join(",")!==expectedKeys.sort().join(",")||record2.schemaVersion!==MANAGED_STARTUP_ROOT_APPLY_SCHEMA_VERSION||typeof record2.encodedProfile!=="string"||typeof record2.profileFingerprint!=="string"||record2.corporateCaB64!==null&&typeof record2.corporateCaB64!=="string"){fail4("serialized request has an invalid schema")}const request=createManagedStartupRootApplyRequest({agent:exactAgent(record2.agent),encodedProfile:record2.encodedProfile,...record2.corporateCaB64===null?{}:{corporateCaB64:record2.corporateCaB64}});if(record2.profileFingerprint!==request.profileFingerprint||!SHA256_RE3.test(record2.profileFingerprint)){fail4("profile fingerprint does not match the encoded profile")}if(serializeManagedStartupRootApplyRequest(request)!==text){fail4("serialized request is not canonical")}return request}var import_node_crypto6=require("node:crypto");var import_node_fs3=__toESM(require("node:fs"));var import_node_path2=__toESM(require("node:path"));var MANAGED_HERMES_STATE_ROOT="/sandbox/.hermes";var MANAGED_OPENCLAW_STATE_ROOT="/sandbox/.openclaw";var HERMES_STATE_VOLUME_NAME_PREFIX="nemoclaw-hermes-state-v1";var OPENCLAW_STATE_VOLUME_NAME_PREFIX="nemoclaw-openclaw-state-v1";var MANAGED_AGENT_STATE_ROOTS=Object.freeze({openclaw:Object.freeze([Object.freeze({mountTarget:MANAGED_OPENCLAW_STATE_ROOT,resourceIdentity:sandboxName=>`${OPENCLAW_STATE_VOLUME_NAME_PREFIX}-${sandboxName}`,ownershipLabels:(sandboxName,mountTarget)=>Object.freeze({"io.nvidia.nemoclaw.openclaw-state.managed":"true","io.nvidia.nemoclaw.openclaw-state.schema":"1","io.nvidia.nemoclaw.openclaw-state.sandbox":sandboxName,"io.nvidia.nemoclaw.openclaw-state.target":mountTarget}),uidAuthority:"agent",gidAuthority:"agent",mode:1528,readWrite:true})]),hermes:Object.freeze([Object.freeze({mountTarget:MANAGED_HERMES_STATE_ROOT,resourceIdentity:sandboxName=>`${HERMES_STATE_VOLUME_NAME_PREFIX}-${sandboxName}`,ownershipLabels:(sandboxName,mountTarget)=>Object.freeze({"io.nvidia.nemoclaw.hermes-state.managed":"true","io.nvidia.nemoclaw.hermes-state.schema":"1","io.nvidia.nemoclaw.hermes-state.sandbox":sandboxName,"io.nvidia.nemoclaw.hermes-state.target":mountTarget}),uidAuthority:"agent",gidAuthority:"agent",mode:2040,readWrite:true})]),"langchain-deepagents-code":Object.freeze([]),pi:Object.freeze([])});function managedStartupStateRootMountTargets(agent){return Object.freeze(MANAGED_AGENT_STATE_ROOTS[agent].map(({mountTarget})=>mountTarget))}var MANAGED_AGENT_WORKSPACE_ROOTS=Object.freeze({openclaw:Object.freeze({uidAuthority:"agent",gidAuthority:"agent",mode:493}),hermes:Object.freeze({uidAuthority:"agent",gidAuthority:"agent",mode:493}),"langchain-deepagents-code":Object.freeze({uidAuthority:"root",gidAuthority:"agent",mode:1021}),pi:Object.freeze({uidAuthority:"agent",gidAuthority:"agent",mode:493})});function exactAgentIdentity(value,label){if(!Number.isSafeInteger(value)||value<0||value>2147483647){throw new Error(`Managed startup state-root ${label} authority is invalid.`)}return value}function managedStartupWorkspaceRoot(input){const uid=exactAgentIdentity(input.agentIdentity.uid,"workspace UID");const gid=exactAgentIdentity(input.agentIdentity.gid,"workspace GID");const declaration=MANAGED_AGENT_WORKSPACE_ROOTS[input.agent];return Object.freeze({uid:declaration.uidAuthority==="root"?0:uid,gid,mode:declaration.mode})}var TRANSACTION_SCHEMA_VERSION=1;var MAX_TRANSACTION_FILES=128;var MAX_TRANSACTION_FILE_BYTES=8*1024*1024;var MAX_TRANSACTION_TOTAL_BYTES=32*1024*1024;var MAX_MANIFEST_BYTES=256*1024;var MAX_COMMIT_RECEIPT_BYTES=4096;var MANAGED_STARTUP_SHARED_CAPTURE_MAX_BYTES=4*Math.ceil(MAX_TRANSACTION_TOTAL_BYTES/3)+MAX_MANIFEST_BYTES*2;var TRANSACTION_PARENT_DIRECTORY_MODE=493;var TRANSACTION_DIRECTORY_MODE=448;var TRANSACTION_FILE_MODE=256;var ATOMIC_TEMPORARY_FILE_MODE=384;var MANAGED_STARTUP_SHARED_TRANSACTION_DIRECTORY="/var/lib/nemoclaw/managed-startup-shared-state-transaction-v1";var MANAGED_STARTUP_SHARED_ROLLBACK_RECEIPT_DIRECTORY="/run/nemoclaw/managed-startup-shared-rollback-receipt-v1";var MANAGED_STARTUP_SHARED_COMMIT_RECEIPT_DIRECTORY="/var/lib/nemoclaw/managed-startup-shared-state-commit-v1";var MANAGED_STARTUP_SHARED_COMMIT_RECEIPT_FILE="receipt.json";function fail5(message){throw new Error(`Managed startup shared-state transaction failed: ${message}`)}function resolveOptions(options={}){const sandboxRoot=import_node_path2.default.resolve(options.sandboxRoot??"/sandbox");const transactionDirectory=import_node_path2.default.resolve(options.transactionDirectory??MANAGED_STARTUP_SHARED_TRANSACTION_DIRECTORY);const commitReceiptDirectory=import_node_path2.default.resolve(options.commitReceiptDirectory??(options.transactionDirectory?import_node_path2.default.join(import_node_path2.default.dirname(transactionDirectory),import_node_path2.default.basename(MANAGED_STARTUP_SHARED_COMMIT_RECEIPT_DIRECTORY)):MANAGED_STARTUP_SHARED_COMMIT_RECEIPT_DIRECTORY));if(transactionDirectory===sandboxRoot||transactionDirectory.startsWith(`${sandboxRoot}${import_node_path2.default.sep}`)||commitReceiptDirectory===sandboxRoot||commitReceiptDirectory.startsWith(`${sandboxRoot}${import_node_path2.default.sep}`)||import_node_path2.default.dirname(commitReceiptDirectory)!==import_node_path2.default.dirname(transactionDirectory)||commitReceiptDirectory===transactionDirectory){fail5("transaction and commit receipts require distinct paths outside sandbox-shared state")}const bootstrapIdentity=options.bootstrapIdentity??null;if(bootstrapIdentity!==null&&!/^[a-f0-9]{64}$/u.test(bootstrapIdentity)){fail5("bootstrap identity must encode 32 lowercase-hex bytes")}return{sandboxRoot,transactionParentDirectory:import_node_path2.default.dirname(transactionDirectory),transactionDirectory,backupDirectory:import_node_path2.default.join(transactionDirectory,"backups"),manifestFile:import_node_path2.default.join(transactionDirectory,"manifest.json"),commitReceiptDirectory,commitReceiptFile:import_node_path2.default.join(commitReceiptDirectory,MANAGED_STARTUP_SHARED_COMMIT_RECEIPT_FILE),trustedUid:options.trustedUid??0,trustedGid:options.trustedGid??0,readOnlyReceipt:options.readOnlyReceipt??false,bootstrapIdentity}}function modeOf2(stat){if(typeof stat.mode==="bigint"){return Number(stat.mode&0o7777n)}return stat.mode&4095}function requireTransactionIdentity(options){const expectedUid=options.readOnlyReceipt?0:options.trustedUid;const expectedGid=options.readOnlyReceipt?0:options.trustedGid;if(process.geteuid?.()!==expectedUid||process.getegid?.()!==expectedGid){fail5("transaction control requires the trusted effective identity")}}function pathExistsNoFollow(target2){try{import_node_fs3.default.lstatSync(target2);return true}catch(error){if(error.code==="ENOENT")return false;fail5(`could not inspect ${target2}`)}}function requireDirectory(target2,options,expectedMode=null){let stat;try{stat=import_node_fs3.default.lstatSync(target2)}catch{fail5(`required directory is missing: ${target2}`)}if(stat.isSymbolicLink()||!stat.isDirectory()){fail5(`required directory is unsafe: ${target2}`)}if(expectedMode!==null&&(stat.uid!==options.trustedUid||stat.gid!==options.trustedGid||modeOf2(stat)!==expectedMode)){fail5(`${target2} must be ${options.trustedUid}:${options.trustedGid} mode ${expectedMode.toString(8)}`)}return stat}function requireTransactionBoundaries(options){requireDirectory(options.sandboxRoot,options);requireDirectory(options.transactionParentDirectory,options,TRANSACTION_PARENT_DIRECTORY_MODE)}function sameStableMetadata(left,right){return left.dev===right.dev&&left.ino===right.ino&&left.mode===right.mode&&left.nlink===right.nlink&&left.uid===right.uid&&left.gid===right.gid&&left.size===right.size&&left.mtimeNs===right.mtimeNs&&left.ctimeNs===right.ctimeNs}function readStableFile(target2,maxBytes){const noFollow=import_node_fs3.default.constants.O_NOFOLLOW;if(typeof noFollow!=="number")fail5("O_NOFOLLOW is unavailable");let descriptor;try{descriptor=import_node_fs3.default.openSync(target2,import_node_fs3.default.constants.O_RDONLY|noFollow)}catch{fail5(`could not safely open ${target2}`)}try{const before=import_node_fs3.default.fstatSync(descriptor,{bigint:true});if(!before.isFile()||before.nlink!==1n||before.size<0n||before.size>BigInt(maxBytes)){fail5(`refusing unsafe or oversized transaction file ${target2}`)}const bytes=Buffer.alloc(Number(before.size));let offset=0;while(offset!segment||segment==="."||segment==="..")){fail5(`unsafe transaction path ${JSON.stringify(value)}`)}return segments.join("/")}function absoluteTarget(relativePath,options){const safe=safeRelativePath(relativePath);const target2=import_node_path2.default.resolve(options.sandboxRoot,safe);if(!target2.startsWith(`${options.sandboxRoot}${import_node_path2.default.sep}`)){fail5(`transaction target escapes the sandbox root: ${relativePath}`)}return target2}function relativeTarget(target2,options){return safeRelativePath(import_node_path2.default.relative(options.sandboxRoot,target2))}function isDeclaredAgentStateRoot(expectedAgent,outputRoot,options){const relative=import_node_path2.default.relative(options.sandboxRoot,outputRoot).split(import_node_path2.default.sep).join("/");const canonicalTarget=import_node_path2.default.posix.join("/sandbox",relative);return managedStartupStateRootMountTargets(expectedAgent).includes(canonicalTarget)}function validateExistingAncestors(target2,expectedAgent,options){const relative=relativeTarget(target2,options);const sandboxStat=requireDirectory(options.sandboxRoot,options);const outputRoot=agentRoot(expectedAgent,options.sandboxRoot);if(target2!==outputRoot&&!target2.startsWith(`${outputRoot}${import_node_path2.default.sep}`)){fail5(`transaction target escapes the ${expectedAgent} state root: ${target2}`)}let current=options.sandboxRoot;let expectedDevice=sandboxStat.dev;const segments=relative.split("/").slice(0,-1);for(const segment of segments){current=import_node_path2.default.join(current,segment);let stat;try{stat=import_node_fs3.default.lstatSync(current)}catch(error){if(error.code==="ENOENT")return;fail5(`could not inspect transaction path ancestor ${current}`)}if(stat.isSymbolicLink()||!stat.isDirectory()){fail5(`transaction path ancestor is unsafe: ${current}`)}if(current===outputRoot&&isDeclaredAgentStateRoot(expectedAgent,outputRoot,options)){expectedDevice=stat.dev}else if(stat.dev!==expectedDevice){fail5(`transaction path crosses a nested filesystem mount: ${current}`)}}}function managedOutputDevice(expectedAgent,options){const sandboxStat=requireDirectory(options.sandboxRoot,options);const outputRoot=agentRoot(expectedAgent,options.sandboxRoot);let stat;try{stat=import_node_fs3.default.lstatSync(outputRoot)}catch(error){if(error.code==="ENOENT")return sandboxStat.dev;fail5(`could not inspect managed output root ${outputRoot}`)}if(stat.isSymbolicLink()||!stat.isDirectory()){fail5(`managed output root is unsafe: ${outputRoot}`)}if(!isDeclaredAgentStateRoot(expectedAgent,outputRoot,options)&&stat.dev!==sandboxStat.dev){fail5(`managed output root crosses a nested filesystem mount: ${outputRoot}`)}return stat.dev}function agentRoot(agent,sandboxRoot){switch(agent){case"openclaw":return import_node_path2.default.join(sandboxRoot,".openclaw");case"hermes":return import_node_path2.default.join(sandboxRoot,".hermes");case"langchain-deepagents-code":return import_node_path2.default.join(sandboxRoot,".deepagents");case"pi":return import_node_path2.default.join(sandboxRoot,".pi")}}function resolveUnderAgentRoot(root,relativePath){const safe=safeRelativePath(relativePath);const target2=import_node_path2.default.resolve(root,safe);if(!target2.startsWith(`${root}${import_node_path2.default.sep}`)){fail5(`managed output escapes the agent root: ${relativePath}`)}return target2}function renderTarget(root,agent,target2){if(agent==="openclaw"&&target2==="openclaw.json"){return import_node_path2.default.join(root,"openclaw.json")}const prefix=agent==="openclaw"?"~/.openclaw/":agent==="hermes"?"~/.hermes/":null;if(!prefix||!target2.startsWith(prefix)){fail5(`unsupported managed messaging render target ${JSON.stringify(target2)}`)}return resolveUnderAgentRoot(root,target2.slice(prefix.length))}function managedOutputTargets(profile,options){const root=agentRoot(profile.agent,options.sandboxRoot);const files=new Set;const directories=new Set([root]);switch(profile.agent){case"openclaw":files.add(import_node_path2.default.join(root,"openclaw.json"));break;case"hermes":files.add(import_node_path2.default.join(root,"config.yaml"));files.add(import_node_path2.default.join(root,".env"));files.add(import_node_path2.default.join(root,".config-hash"));break;case"langchain-deepagents-code":files.add(import_node_path2.default.join(root,"config.toml"));directories.add(import_node_path2.default.join(root,".state"));break;case"pi":directories.add(import_node_path2.default.join(root,"agent"));files.add(import_node_path2.default.join(root,"agent","models.json"));files.add(import_node_path2.default.join(root,"agent","settings.json"));break}if(profile.messaging.plan!==null){const plan=parseSandboxMessagingPlan(profile.messaging.plan,{agent:profile.agent});if(!plan)fail5("managed messaging plan is invalid");for(const render of selectEnabledMessagingAgentRender(plan)){if(typeof render.target!=="string")continue;files.add(renderTarget(root,profile.agent,render.target))}for(const step of selectEnabledPostAgentInstallBuildFiles(plan)){if(typeof step.value!=="object"||step.value===null){continue}const outputPath=step.value.path;if(typeof outputPath==="string"){files.add(resolveUnderAgentRoot(root,outputPath))}}}for(const file of files){let parent=import_node_path2.default.dirname(file);while(parent!==options.sandboxRoot&&parent.startsWith(`${root}${import_node_path2.default.sep}`)){directories.add(parent);if(parent===root)break;parent=import_node_path2.default.dirname(parent)}}return{files:[...files].sort(),directories:[...directories].sort((left,right)=>left.split(import_node_path2.default.sep).length-right.split(import_node_path2.default.sep).length)}}function snapshotFile(target2,index,expectedAgent,options){validateExistingAncestors(target2,expectedAgent,options);let stat;try{stat=import_node_fs3.default.lstatSync(target2)}catch(error){if(error.code==="ENOENT"){return{receipt:{path:relativeTarget(target2,options),state:"absent"},bytes:null}}fail5(`could not inspect managed output ${target2}`)}if(stat.isSymbolicLink()||!stat.isFile()||stat.nlink!==1){fail5(`managed output is not a safe regular file: ${target2}`)}if(stat.dev!==managedOutputDevice(expectedAgent,options)){fail5(`managed output crosses a nested filesystem mount: ${target2}`)}const stable=readStableFile(target2,MAX_TRANSACTION_FILE_BYTES);const size=Number(stable.stat.size);const backup=`${String(index).padStart(3,"0")}.bin`;return{receipt:{path:relativeTarget(target2,options),state:"file",backup,sha256:(0,import_node_crypto6.createHash)("sha256").update(stable.bytes).digest("hex"),size,uid:Number(stable.stat.uid),gid:Number(stable.stat.gid),mode:Number(stable.stat.mode&0o7777n)},bytes:stable.bytes}}function snapshotDirectory(target2,expectedAgent,options){validateExistingAncestors(import_node_path2.default.join(target2,".receipt"),expectedAgent,options);let stat;try{stat=import_node_fs3.default.lstatSync(target2)}catch(error){if(error.code==="ENOENT"){return{path:relativeTarget(target2,options),state:"absent"}}fail5(`could not inspect managed output directory ${target2}`)}if(stat.isSymbolicLink()||!stat.isDirectory()){fail5(`managed output directory is unsafe: ${target2}`)}if(stat.dev!==managedOutputDevice(expectedAgent,options)){fail5(`managed output directory crosses a nested filesystem mount: ${target2}`)}return{path:relativeTarget(target2,options),state:"directory",uid:stat.uid,gid:stat.gid,mode:modeOf2(stat)}}function atomicWriteTrustedFile(target2,contents,mode,uid,gid){const parent=import_node_path2.default.dirname(target2);const temporary=import_node_path2.default.join(parent,`.${import_node_path2.default.basename(target2)}.${(0,import_node_crypto6.randomBytes)(12).toString("hex")}`);let descriptor;try{descriptor=import_node_fs3.default.openSync(temporary,import_node_fs3.default.constants.O_CREAT|import_node_fs3.default.constants.O_EXCL|import_node_fs3.default.constants.O_WRONLY|import_node_fs3.default.constants.O_NOFOLLOW,384);import_node_fs3.default.writeFileSync(descriptor,contents);import_node_fs3.default.fchownSync(descriptor,uid,gid);import_node_fs3.default.fchmodSync(descriptor,mode);import_node_fs3.default.fsyncSync(descriptor);import_node_fs3.default.closeSync(descriptor);descriptor=void 0;import_node_fs3.default.renameSync(temporary,target2)}catch(error){if(descriptor!==void 0)import_node_fs3.default.closeSync(descriptor);try{import_node_fs3.default.unlinkSync(temporary)}catch{}fail5(`could not atomically write ${target2}: ${error.message}`)}}function fsyncDirectory(directory){const descriptor=import_node_fs3.default.openSync(directory,import_node_fs3.default.constants.O_RDONLY);try{import_node_fs3.default.fsyncSync(descriptor)}finally{import_node_fs3.default.closeSync(descriptor)}}function canonicalManifest(manifest){return`${JSON.stringify(manifest,null,2)} `}function canonicalLegacyManifest(manifest){return`${JSON.stringify({schemaVersion:manifest.schemaVersion,agent:manifest.agent,profileFingerprint:manifest.profileFingerprint,files:manifest.files,directories:manifest.directories},null,2)} `}function canonicalCommitReceipt(receipt){return`${JSON.stringify(receipt,null,2)} -`}function requireExactKeys(record2,keys){if(Object.keys(record2).sort().join(",")!==[...keys].sort().join(",")){fail5("transaction manifest contains unexpected fields")}}function parseCommitReceipt(text){let parsed;try{parsed=JSON.parse(text)}catch{fail5("commit receipt is not valid JSON")}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){fail5("commit receipt must be an object")}const record2=parsed;requireExactKeys(record2,["agent","bootstrapIdentity","profileFingerprint","schemaVersion"]);if(record2.schemaVersion!==TRANSACTION_SCHEMA_VERSION||!MANAGED_STARTUP_AGENTS.includes(String(record2.agent))||typeof record2.profileFingerprint!=="string"||!/^[a-f0-9]{64}$/u.test(record2.profileFingerprint)||typeof record2.bootstrapIdentity!=="string"||!/^[a-f0-9]{64}$/u.test(record2.bootstrapIdentity)){fail5("commit receipt has an invalid envelope")}const receipt={schemaVersion:TRANSACTION_SCHEMA_VERSION,agent:record2.agent,profileFingerprint:record2.profileFingerprint,bootstrapIdentity:record2.bootstrapIdentity};if(canonicalCommitReceipt(receipt)!==text){fail5("commit receipt is not canonical")}return receipt}function safeMetadata(value){return Number.isSafeInteger(value)&&value>=0}function parseManifest(text){let parsed;try{parsed=JSON.parse(text)}catch{fail5("transaction manifest is not valid JSON")}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){fail5("transaction manifest must be an object")}const record2=parsed;const hasBootstrapIdentity=Object.hasOwn(record2,"bootstrapIdentity");requireExactKeys(record2,hasBootstrapIdentity?["agent","bootstrapIdentity","directories","files","profileFingerprint","schemaVersion"]:["agent","directories","files","profileFingerprint","schemaVersion"]);const bootstrapIdentity=hasBootstrapIdentity?record2.bootstrapIdentity:null;if(record2.schemaVersion!==TRANSACTION_SCHEMA_VERSION||!MANAGED_STARTUP_AGENTS.includes(String(record2.agent))||typeof record2.profileFingerprint!=="string"||!/^[a-f0-9]{64}$/u.test(record2.profileFingerprint)||!(bootstrapIdentity===null||typeof bootstrapIdentity==="string"&&/^[a-f0-9]{64}$/u.test(bootstrapIdentity))||!Array.isArray(record2.files)||!Array.isArray(record2.directories)||record2.files.length>MAX_TRANSACTION_FILES||record2.directories.length>MAX_TRANSACTION_FILES*4){fail5("transaction manifest has an invalid envelope")}const files=record2.files.map(value=>{if(typeof value!=="object"||value===null||Array.isArray(value)){return fail5("transaction file receipt must be an object")}const receipt=value;if(typeof receipt.path!=="string"){return fail5("transaction file receipt path must be a string")}const receiptPath=safeRelativePath(receipt.path);if(receipt.state==="absent"){requireExactKeys(receipt,["path","state"]);return{path:receiptPath,state:"absent"}}requireExactKeys(receipt,["backup","gid","mode","path","sha256","size","state","uid"]);if(receipt.state!=="file"||typeof receipt.backup!=="string"||!/^[0-9]{3}\.bin$/u.test(receipt.backup)||typeof receipt.sha256!=="string"||!/^[a-f0-9]{64}$/u.test(receipt.sha256)||!safeMetadata(receipt.size)||receipt.size>MAX_TRANSACTION_FILE_BYTES||!safeMetadata(receipt.uid)||!safeMetadata(receipt.gid)||!safeMetadata(receipt.mode)||receipt.mode>4095){return fail5("transaction file receipt is invalid")}return{path:receiptPath,state:"file",backup:receipt.backup,sha256:receipt.sha256,size:receipt.size,uid:receipt.uid,gid:receipt.gid,mode:receipt.mode}});const directories=record2.directories.map(value=>{if(typeof value!=="object"||value===null||Array.isArray(value)){return fail5("transaction directory receipt must be an object")}const receipt=value;if(typeof receipt.path!=="string"){return fail5("transaction directory receipt path must be a string")}const receiptPath=safeRelativePath(receipt.path);if(receipt.state==="absent"){requireExactKeys(receipt,["path","state"]);return{path:receiptPath,state:"absent"}}requireExactKeys(receipt,["gid","mode","path","state","uid"]);if(receipt.state!=="directory"||!safeMetadata(receipt.uid)||!safeMetadata(receipt.gid)||!safeMetadata(receipt.mode)||receipt.mode>4095){return fail5("transaction directory receipt is invalid")}return{path:receiptPath,state:"directory",uid:receipt.uid,gid:receipt.gid,mode:receipt.mode}});const filePaths=files.map(receipt=>receipt.path);const directoryPaths=directories.map(receipt=>receipt.path);const backupNames=files.filter(receipt=>receipt.state==="file").map(receipt=>receipt.backup);if(new Set(filePaths).size!==filePaths.length||new Set(directoryPaths).size!==directoryPaths.length||new Set(backupNames).size!==backupNames.length){fail5("transaction manifest contains duplicate receipts")}const manifest={schemaVersion:TRANSACTION_SCHEMA_VERSION,agent:record2.agent,profileFingerprint:record2.profileFingerprint,bootstrapIdentity,files,directories};const canonical=hasBootstrapIdentity?canonicalManifest(manifest):canonicalLegacyManifest(manifest);if(canonical!==text){fail5("transaction manifest is not canonical")}return manifest}function requireTrustedTransactionPath(target2,mode,options){const stat=import_node_fs3.default.lstatSync(target2);if(stat.isSymbolicLink()||(mode===TRANSACTION_DIRECTORY_MODE?!stat.isDirectory():!stat.isFile())||!options.readOnlyReceipt&&(stat.uid!==options.trustedUid||stat.gid!==options.trustedGid)||modeOf2(stat)!==mode){fail5(`transaction artifact has unsafe metadata: ${target2}`)}}function requireReadOnlyReceiptMount(target2,options){if(!options.readOnlyReceipt)return;const probe=import_node_path2.default.join(target2,".nemoclaw-write-probe");let descriptor;try{descriptor=import_node_fs3.default.openSync(probe,import_node_fs3.default.constants.O_CREAT|import_node_fs3.default.constants.O_EXCL|import_node_fs3.default.constants.O_WRONLY|import_node_fs3.default.constants.O_NOFOLLOW,384);import_node_fs3.default.closeSync(descriptor);descriptor=void 0;import_node_fs3.default.unlinkSync(probe)}catch(error){if(descriptor!==void 0)import_node_fs3.default.closeSync(descriptor);if(error.code==="EROFS")return;fail5("copied receipt must be mounted on a read-only filesystem")}fail5("copied receipt mount is writable")}function loadManifest(options){requireTransactionBoundaries(options);if(!pathExistsNoFollow(options.transactionDirectory))return null;requireTrustedTransactionPath(options.transactionDirectory,TRANSACTION_DIRECTORY_MODE,options);requireReadOnlyReceiptMount(options.transactionDirectory,options);requireTrustedTransactionPath(options.backupDirectory,TRANSACTION_DIRECTORY_MODE,options);requireTrustedTransactionPath(options.manifestFile,TRANSACTION_FILE_MODE,options);const stable=readStableFile(options.manifestFile,MAX_MANIFEST_BYTES);if(!options.readOnlyReceipt&&(Number(stable.stat.uid)!==options.trustedUid||Number(stable.stat.gid)!==options.trustedGid)||Number(stable.stat.mode&0o7777n)!==TRANSACTION_FILE_MODE){fail5("transaction manifest ownership changed while it was read")}return parseManifest(stable.bytes.toString("utf8"))}function transactionOptionsAt(options,transactionDirectory){return{...options,transactionDirectory,backupDirectory:import_node_path2.default.join(transactionDirectory,"backups"),manifestFile:import_node_path2.default.join(transactionDirectory,"manifest.json")}}function loadCommitReceipt(options){requireTransactionBoundaries(options);if(!pathExistsNoFollow(options.commitReceiptDirectory))return null;requireTrustedTransactionPath(options.commitReceiptDirectory,TRANSACTION_DIRECTORY_MODE,options);if(pathExistsNoFollow(options.commitReceiptFile)){requireReadOnlyReceiptMount(options.commitReceiptDirectory,options);requireTrustedTransactionPath(options.commitReceiptFile,TRANSACTION_FILE_MODE,options);const stable=readStableFile(options.commitReceiptFile,MAX_COMMIT_RECEIPT_BYTES);if(!options.readOnlyReceipt&&(Number(stable.stat.uid)!==options.trustedUid||Number(stable.stat.gid)!==options.trustedGid)||Number(stable.stat.mode&0o7777n)!==TRANSACTION_FILE_MODE){fail5("commit receipt ownership changed while it was read")}return{receipt:parseCommitReceipt(stable.bytes.toString("utf8")),compact:true}}const stagedOptions=transactionOptionsAt(options,options.commitReceiptDirectory);const staged=loadManifest(stagedOptions);if(!staged||staged.bootstrapIdentity===null){fail5("durable commit staging receipt is incomplete")}verifyAllBackups(staged.files,stagedOptions);return{receipt:{schemaVersion:TRANSACTION_SCHEMA_VERSION,agent:staged.agent,profileFingerprint:staged.profileFingerprint,bootstrapIdentity:staged.bootstrapIdentity},compact:false}}function verifyBackup(receipt,options){const backupPath=import_node_path2.default.join(options.backupDirectory,receipt.backup);requireTrustedTransactionPath(backupPath,TRANSACTION_FILE_MODE,options);const stable=readStableFile(backupPath,MAX_TRANSACTION_FILE_BYTES);const digest=(0,import_node_crypto6.createHash)("sha256").update(stable.bytes).digest("hex");if(stable.bytes.length!==receipt.size||digest!==receipt.sha256){fail5(`transaction backup does not match its receipt: ${receipt.path}`)}return stable.bytes}function verifyAllBackups(receipts,options){const backups=new Map;for(const receipt of receipts){if(receipt.state==="file"){backups.set(receipt.path,verifyBackup(receipt,options))}}return backups}function fileMatchesReceipt(target2,receipt){let stat;try{stat=import_node_fs3.default.lstatSync(target2)}catch(error){if(error.code==="ENOENT")return false;fail5(`could not inspect managed output ${target2}`)}if(stat.isSymbolicLink()||!stat.isFile()||stat.nlink!==1)return false;const stable=readStableFile(target2,MAX_TRANSACTION_FILE_BYTES);return stable.bytes.length===receipt.size&&(0,import_node_crypto6.createHash)("sha256").update(stable.bytes).digest("hex")===receipt.sha256&&Number(stable.stat.uid)===receipt.uid&&Number(stable.stat.gid)===receipt.gid&&Number(stable.stat.mode&0o7777n)===receipt.mode}function directoryMatchesReceipt(target2,receipt){let stat;try{stat=import_node_fs3.default.lstatSync(target2)}catch(error){if(error.code==="ENOENT")return false;fail5(`could not inspect managed output directory ${target2}`)}return!stat.isSymbolicLink()&&stat.isDirectory()&&stat.uid===receipt.uid&&stat.gid===receipt.gid&&modeOf2(stat)===receipt.mode}function removeTransactionDirectory(options){requireTrustedTransactionPath(options.transactionDirectory,TRANSACTION_DIRECTORY_MODE,options);import_node_fs3.default.rmSync(options.transactionDirectory,{force:false,recursive:true});fsyncDirectory(options.transactionParentDirectory);if(pathExistsNoFollow(options.transactionDirectory)){fail5("transaction directory remained after cleanup")}}function assertCommitReceiptMatches(receipt,expected){if(receipt.agent!==expected.agent||expected.profileFingerprint!==void 0&&receipt.profileFingerprint!==expected.profileFingerprint||receipt.bootstrapIdentity!==expected.bootstrapIdentity){fail5("durable commit receipt belongs to a different bootstrap attempt")}}function loadCommitStagingManifest(options){if(!pathExistsNoFollow(options.manifestFile))return null;requireTrustedTransactionPath(options.manifestFile,TRANSACTION_FILE_MODE,options);const stable=readStableFile(options.manifestFile,MAX_MANIFEST_BYTES);if(Number(stable.stat.uid)!==options.trustedUid||Number(stable.stat.gid)!==options.trustedGid||Number(stable.stat.mode&0o7777n)!==TRANSACTION_FILE_MODE){fail5("durable commit staging manifest ownership changed while it was read")}return parseManifest(stable.bytes.toString("utf8"))}function retireInterruptedCommitReceiptWrites(receipt,options){const temporaryPattern=new RegExp(`^\\.${MANAGED_STARTUP_SHARED_COMMIT_RECEIPT_FILE.replace(".","\\.")}\\.[a-f0-9]{24}$`,"u");for(const entry of import_node_fs3.default.readdirSync(options.commitReceiptDirectory)){if(!temporaryPattern.test(entry))continue;const target2=import_node_path2.default.join(options.commitReceiptDirectory,entry);const stat=import_node_fs3.default.lstatSync(target2);if(stat.isSymbolicLink()||!stat.isFile()||stat.nlink!==1||stat.uid!==options.trustedUid||stat.gid!==options.trustedGid||![ATOMIC_TEMPORARY_FILE_MODE,TRANSACTION_FILE_MODE].includes(modeOf2(stat))){fail5("interrupted durable commit receipt write has unsafe metadata")}const stable=readStableFile(target2,MAX_COMMIT_RECEIPT_BYTES);const mode=Number(stable.stat.mode&0o7777n);if(Number(stable.stat.uid)!==options.trustedUid||Number(stable.stat.gid)!==options.trustedGid||![ATOMIC_TEMPORARY_FILE_MODE,TRANSACTION_FILE_MODE].includes(mode)){fail5("interrupted durable commit receipt write changed during verification")}if(stable.bytes.length>0){let interruptedReceipt=null;try{interruptedReceipt=parseCommitReceipt(stable.bytes.toString("utf8"))}catch{}if(interruptedReceipt)assertCommitReceiptMatches(interruptedReceipt,receipt)}import_node_fs3.default.unlinkSync(target2);fsyncDirectory(options.commitReceiptDirectory)}}function compactDurableCommitReceipt(state,options){if(!state.compact){atomicWriteTrustedFile(options.commitReceiptFile,canonicalCommitReceipt(state.receipt),TRANSACTION_FILE_MODE,options.trustedUid,options.trustedGid);fsyncDirectory(options.commitReceiptDirectory)}retireInterruptedCommitReceiptWrites(state.receipt,options);const stagedOptions=transactionOptionsAt(options,options.commitReceiptDirectory);const manifestExists=pathExistsNoFollow(stagedOptions.manifestFile);const backupsExist=pathExistsNoFollow(stagedOptions.backupDirectory);const unexpectedBeforeCleanup=import_node_fs3.default.readdirSync(options.commitReceiptDirectory).filter(entry=>![MANAGED_STARTUP_SHARED_COMMIT_RECEIPT_FILE,import_node_path2.default.basename(stagedOptions.backupDirectory),import_node_path2.default.basename(stagedOptions.manifestFile)].includes(entry));if(unexpectedBeforeCleanup.length!==0){fail5("durable commit receipt directory contains unexpected artifacts")}if(manifestExists){const staged=loadCommitStagingManifest(stagedOptions);if(!staged||staged.bootstrapIdentity===null){fail5("durable commit staging receipt disappeared during cleanup")}assertCommitReceiptMatches(state.receipt,{agent:staged.agent,profileFingerprint:staged.profileFingerprint,bootstrapIdentity:staged.bootstrapIdentity})}if(backupsExist){requireTrustedTransactionPath(stagedOptions.backupDirectory,TRANSACTION_DIRECTORY_MODE,options);import_node_fs3.default.rmSync(stagedOptions.backupDirectory,{force:false,recursive:true});fsyncDirectory(options.commitReceiptDirectory)}if(manifestExists){requireTrustedTransactionPath(stagedOptions.manifestFile,TRANSACTION_FILE_MODE,options);import_node_fs3.default.unlinkSync(stagedOptions.manifestFile);fsyncDirectory(options.commitReceiptDirectory)}const unexpected=import_node_fs3.default.readdirSync(options.commitReceiptDirectory).filter(entry=>entry!==MANAGED_STARTUP_SHARED_COMMIT_RECEIPT_FILE);if(unexpected.length!==0){fail5("durable commit receipt directory contains unexpected artifacts")}const verified=loadCommitReceipt(options);if(!verified?.compact)fail5("durable commit receipt did not compact successfully");assertCommitReceiptMatches(verified.receipt,state.receipt)}function beginManagedStartupSharedStateTransaction(profile,inputOptions={}){const options=resolveOptions(inputOptions);requireTransactionIdentity(options);if(options.readOnlyReceipt){fail5("cannot begin a transaction from a read-only rollback receipt")}requireTransactionBoundaries(options);const profileFingerprint=fingerprintManagedStartupProfile(profile);const committed=loadCommitReceipt(options);if(committed){if(options.bootstrapIdentity===null){fail5("a durable managed bootstrap commit receipt already exists")}assertCommitReceiptMatches(committed.receipt,{agent:profile.agent,profileFingerprint,bootstrapIdentity:options.bootstrapIdentity});fail5("this managed bootstrap attempt is already durably committed")}const pending=loadManifest(options);if(pending){if(pending.agent!==profile.agent||pending.profileFingerprint!==profileFingerprint||pending.bootstrapIdentity!==options.bootstrapIdentity){fail5("a pending managed startup transaction belongs to a different agent, profile fingerprint, or bootstrap attempt")}verifyAllBackups(pending.files,options);return false}const targets=managedOutputTargets(profile,options);if(targets.files.length>MAX_TRANSACTION_FILES){fail5("managed startup transaction has too many file targets")}const snapshots=targets.files.map((target2,index)=>snapshotFile(target2,index,profile.agent,options));const totalBytes=snapshots.reduce((sum,snapshot)=>sum+(snapshot.bytes?.length??0),0);if(totalBytes>MAX_TRANSACTION_TOTAL_BYTES){fail5("managed startup transaction backup exceeds the total size limit")}const directories=targets.directories.map(target2=>snapshotDirectory(target2,profile.agent,options));const manifest={schemaVersion:TRANSACTION_SCHEMA_VERSION,agent:profile.agent,profileFingerprint,bootstrapIdentity:options.bootstrapIdentity,files:snapshots.map(({receipt})=>receipt),directories};let createdTransactionIdentity;try{import_node_fs3.default.mkdirSync(options.transactionDirectory,{mode:TRANSACTION_DIRECTORY_MODE});const created=import_node_fs3.default.lstatSync(options.transactionDirectory,{bigint:true});if(!created.isDirectory()||created.isSymbolicLink()){fail5("new transaction path is not a directory")}createdTransactionIdentity={dev:created.dev,ino:created.ino,uid:created.uid,gid:created.gid};import_node_fs3.default.chownSync(options.transactionDirectory,options.trustedUid,options.trustedGid);import_node_fs3.default.chmodSync(options.transactionDirectory,TRANSACTION_DIRECTORY_MODE);fsyncDirectory(options.transactionParentDirectory);import_node_fs3.default.mkdirSync(options.backupDirectory,{mode:TRANSACTION_DIRECTORY_MODE});import_node_fs3.default.chownSync(options.backupDirectory,options.trustedUid,options.trustedGid);import_node_fs3.default.chmodSync(options.backupDirectory,TRANSACTION_DIRECTORY_MODE);fsyncDirectory(options.transactionDirectory);for(const snapshot of snapshots){if(snapshot.receipt.state!=="file"||snapshot.bytes===null)continue;atomicWriteTrustedFile(import_node_path2.default.join(options.backupDirectory,snapshot.receipt.backup),snapshot.bytes,TRANSACTION_FILE_MODE,options.trustedUid,options.trustedGid)}fsyncDirectory(options.backupDirectory);atomicWriteTrustedFile(options.manifestFile,canonicalManifest(manifest),TRANSACTION_FILE_MODE,options.trustedUid,options.trustedGid);fsyncDirectory(options.transactionDirectory);loadManifest(options)}catch(error){try{if(createdTransactionIdentity&&pathExistsNoFollow(options.transactionDirectory)){const current=import_node_fs3.default.lstatSync(options.transactionDirectory,{bigint:true});if(!current.isSymbolicLink()&¤t.isDirectory()&¤t.dev===createdTransactionIdentity.dev&¤t.ino===createdTransactionIdentity.ino&¤t.uid===createdTransactionIdentity.uid&¤t.gid===createdTransactionIdentity.gid){import_node_fs3.default.chmodSync(options.transactionDirectory,TRANSACTION_DIRECTORY_MODE);import_node_fs3.default.chownSync(options.transactionDirectory,options.trustedUid,options.trustedGid)}requireTrustedTransactionPath(options.transactionDirectory,TRANSACTION_DIRECTORY_MODE,options);import_node_fs3.default.rmSync(options.transactionDirectory,{force:true,recursive:true})}}catch{}throw error}return true}function ensureOriginalDirectories(receipts,expectedAgent,options){for(const receipt of receipts){if(receipt.state!=="directory")continue;const target2=absoluteTarget(receipt.path,options);validateExistingAncestors(import_node_path2.default.join(target2,".restore"),expectedAgent,options);let stat=null;try{stat=import_node_fs3.default.lstatSync(target2)}catch(error){if(error.code!=="ENOENT"){fail5(`could not inspect restore directory ${target2}`)}}if(stat&&(stat.isSymbolicLink()||!stat.isDirectory())){fail5(`restore directory is unsafe: ${target2}`)}if(stat&&directoryMatchesReceipt(target2,receipt))continue;if(!stat)import_node_fs3.default.mkdirSync(target2,{mode:receipt.mode});import_node_fs3.default.chownSync(target2,receipt.uid,receipt.gid);import_node_fs3.default.chmodSync(target2,receipt.mode)}}function restoreFiles(receipts,backups,expectedAgent,options){for(const receipt of receipts){const target2=absoluteTarget(receipt.path,options);validateExistingAncestors(target2,expectedAgent,options);if(receipt.state==="absent"){let stat;try{stat=import_node_fs3.default.lstatSync(target2)}catch(error){if(error.code==="ENOENT")continue;fail5(`could not inspect new managed output ${target2}`)}if(stat.isDirectory()){fail5(`new managed output unexpectedly became a directory: ${target2}`)}import_node_fs3.default.unlinkSync(target2);continue}if(fileMatchesReceipt(target2,receipt))continue;const bytes=backups.get(receipt.path);if(!bytes)fail5(`verified transaction backup is missing: ${receipt.path}`);let current=null;try{current=import_node_fs3.default.lstatSync(target2)}catch(error){if(error.code!=="ENOENT"){fail5(`could not inspect managed output before restore: ${target2}`)}}if(current?.isDirectory()){fail5(`managed output unexpectedly became a directory: ${target2}`)}atomicWriteTrustedFile(target2,bytes,receipt.mode,receipt.uid,receipt.gid)}}function restoreDirectoryMetadata(receipts,options){for(const receipt of[...receipts].reverse()){const target2=absoluteTarget(receipt.path,options);if(receipt.state==="absent"){try{import_node_fs3.default.rmdirSync(target2)}catch(error){if(error.code==="ENOENT")continue;fail5(`could not remove newly created managed directory ${target2}`)}continue}if(directoryMatchesReceipt(target2,receipt))continue;const stat=import_node_fs3.default.lstatSync(target2);if(stat.isSymbolicLink()||!stat.isDirectory()){fail5(`managed directory changed type during restore: ${target2}`)}import_node_fs3.default.chownSync(target2,receipt.uid,receipt.gid);import_node_fs3.default.chmodSync(target2,receipt.mode)}}function verifyRestoration(manifest,options){for(const receipt of manifest.files){const target2=absoluteTarget(receipt.path,options);if(receipt.state==="absent"){if(pathExistsNoFollow(target2)){fail5(`new managed output remained after rollback: ${target2}`)}continue}const stable=readStableFile(target2,MAX_TRANSACTION_FILE_BYTES);if(stable.bytes.length!==receipt.size||(0,import_node_crypto6.createHash)("sha256").update(stable.bytes).digest("hex")!==receipt.sha256||Number(stable.stat.uid)!==receipt.uid||Number(stable.stat.gid)!==receipt.gid||Number(stable.stat.mode&0o7777n)!==receipt.mode){fail5(`managed output was not restored exactly: ${target2}`)}}for(const receipt of manifest.directories){const target2=absoluteTarget(receipt.path,options);if(receipt.state==="absent"){if(pathExistsNoFollow(target2)){fail5(`new managed directory remained after rollback: ${target2}`)}continue}const stat=import_node_fs3.default.lstatSync(target2);if(stat.isSymbolicLink()||!stat.isDirectory()||stat.uid!==receipt.uid||stat.gid!==receipt.gid||modeOf2(stat)!==receipt.mode){fail5(`managed directory metadata was not restored exactly: ${target2}`)}}}function rollbackManagedStartupSharedStateTransaction(expectedAgent,inputOptions={}){const options=resolveOptions(inputOptions);requireTransactionIdentity(options);const committed=loadCommitReceipt(options);if(committed){if(options.bootstrapIdentity===null){fail5("shared state is already durably committed")}assertCommitReceiptMatches(committed.receipt,{agent:expectedAgent,bootstrapIdentity:options.bootstrapIdentity});fail5("shared state is already durably committed and cannot be rolled back")}const manifest=loadManifest(options);if(!manifest)return false;if(manifest.agent!==expectedAgent){fail5(`pending transaction targets ${manifest.agent}, expected ${expectedAgent}`)}if(manifest.bootstrapIdentity!==options.bootstrapIdentity){fail5("pending transaction belongs to a different bootstrap attempt")}const backups=verifyAllBackups(manifest.files,options);ensureOriginalDirectories(manifest.directories,expectedAgent,options);restoreFiles(manifest.files,backups,expectedAgent,options);restoreDirectoryMetadata(manifest.directories,options);verifyRestoration(manifest,options);if(!options.readOnlyReceipt){removeTransactionDirectory(options)}return true}function commitManagedStartupSharedStateTransaction(expectedAgent,inputOptions={}){const options=resolveOptions(inputOptions);requireTransactionIdentity(options);if(options.readOnlyReceipt){fail5("cannot commit a read-only rollback receipt")}const committed=loadCommitReceipt(options);if(committed){if(options.bootstrapIdentity===null){fail5("durable commit receipt is missing its expected bootstrap identity")}assertCommitReceiptMatches(committed.receipt,{agent:expectedAgent,bootstrapIdentity:options.bootstrapIdentity});compactDurableCommitReceipt(committed,options);return true}const manifest=loadManifest(options);if(!manifest)return false;if(manifest.agent!==expectedAgent){fail5(`pending transaction targets ${manifest.agent}, expected ${expectedAgent}`)}if(manifest.bootstrapIdentity!==options.bootstrapIdentity){fail5("pending transaction belongs to a different bootstrap attempt")}if(manifest.bootstrapIdentity===null){removeTransactionDirectory(options);return true}verifyAllBackups(manifest.files,options);if(pathExistsNoFollow(options.commitReceiptDirectory)){fail5("durable commit receipt path appeared before transaction commit")}try{import_node_fs3.default.renameSync(options.transactionDirectory,options.commitReceiptDirectory);fsyncDirectory(options.transactionParentDirectory)}catch(error){fail5(`could not atomically establish durable commit state: ${error.message}`)}const renamed=loadCommitReceipt(options);if(!renamed)fail5("durable commit state disappeared after atomic rename");assertCommitReceiptMatches(renamed.receipt,{agent:expectedAgent,profileFingerprint:manifest.profileFingerprint,bootstrapIdentity:manifest.bootstrapIdentity});compactDurableCommitReceipt(renamed,options);return true}function clearManagedStartupSharedStateCommitReceipt(expectedAgent,inputOptions={}){const options=resolveOptions(inputOptions);requireTransactionIdentity(options);if(options.readOnlyReceipt){fail5("cannot clear a durable commit from a read-only receipt")}if(options.bootstrapIdentity===null){fail5("durable commit cleanup requires its bootstrap identity")}const committed=loadCommitReceipt(options);if(!committed)return false;assertCommitReceiptMatches(committed.receipt,{agent:expectedAgent,bootstrapIdentity:options.bootstrapIdentity});compactDurableCommitReceipt(committed,options);requireTrustedTransactionPath(options.commitReceiptDirectory,TRANSACTION_DIRECTORY_MODE,options);requireTrustedTransactionPath(options.commitReceiptFile,TRANSACTION_FILE_MODE,options);const entries=import_node_fs3.default.readdirSync(options.commitReceiptDirectory);if(entries.length!==1||entries[0]!==MANAGED_STARTUP_SHARED_COMMIT_RECEIPT_FILE){fail5("durable commit receipt directory contains unexpected artifacts")}import_node_fs3.default.rmSync(options.commitReceiptDirectory,{force:false,recursive:true});fsyncDirectory(options.transactionParentDirectory);if(pathExistsNoFollow(options.commitReceiptDirectory)){fail5("durable commit receipt remained after cleanup")}return true}function getManagedStartupSharedStateTransactionStatus(expected,inputOptions={}){const options=resolveOptions({...inputOptions,bootstrapIdentity:expected.bootstrapIdentity});requireTransactionIdentity(options);const manifest=loadManifest(options);if(manifest){if(manifest.agent!==expected.agent||manifest.profileFingerprint!==expected.profileFingerprint||manifest.bootstrapIdentity!==expected.bootstrapIdentity){fail5("pending transaction does not match the expected agent, profile fingerprint, or bootstrap identity")}verifyAllBackups(manifest.files,options);return"pending"}const committed=loadCommitReceipt(options);if(!committed)return"none";assertCommitReceiptMatches(committed.receipt,expected);return"committed"}var MANAGED_STARTUP_PROFILE_ENV="NEMOCLAW_STARTUP_PROFILE_B64";var MANAGED_STARTUP_CA_ENV="NEMOCLAW_CORPORATE_CA_B64";var MANAGED_STARTUP_EXCHANGE_DIRECTORY="/tmp";var MANAGED_STARTUP_RUNTIME_ENV_FILE=`${MANAGED_STARTUP_EXCHANGE_DIRECTORY}/nemoclaw-managed-startup-runtime.env`;var MANAGED_STARTUP_RUNTIME_EXECUTABLE="/usr/local/lib/nemoclaw/managed-startup-image-runtime.cjs";var MANAGED_STARTUP_MERGED_CA_FILE=`${MANAGED_STARTUP_EXCHANGE_DIRECTORY}/nemoclaw-managed-startup-ca-bundle.pem`;var MANAGED_STARTUP_COMPLETION_FILE=`${MANAGED_STARTUP_EXCHANGE_DIRECTORY}/nemoclaw-managed-startup-complete.json`;var MANAGED_STARTUP_CORPORATE_CA_FILE="/usr/local/share/nemoclaw/corporate-ca.pem";var MANAGED_STARTUP_SYSTEM_CA_ANCHOR_DIRECTORY="/usr/local/share/ca-certificates";var MANAGED_STARTUP_SYSTEM_CA_ANCHOR_RE=/^nemoclaw-corporate-ca-[0-9]{2}\.crt$/u;var SYSTEM_CA_BUNDLE_FILE="/etc/ssl/certs/ca-certificates.crt";var UPDATE_CA_CERTIFICATES_EXECUTABLE="/usr/sbin/update-ca-certificates";var MANAGED_STARTUP_TLS_ENV_NAMES=new Set(["CURL_CA_BUNDLE","GIT_SSL_CAINFO","NODE_EXTRA_CA_CERTS","REQUESTS_CA_BUNDLE","SSL_CERT_FILE"]);var MESSAGING_RUNTIME_PLAN_FILE="/usr/local/share/nemoclaw/messaging-runtime-plan.json";var ROOT_STATE_PARENT="/var/lib/nemoclaw";var ROOT_RUNTIME_DIRECTORY="/run/nemoclaw";var ROOT_OWNED_DIRECTORY_MODE=493;var MAX_TRUST_BUNDLE_BYTES=4*1024*1024;var HERMES_MANAGED_CONFIG_FILES=["/sandbox/.hermes/config.yaml","/sandbox/.hermes/.env"];var HERMES_GENERATED_MANAGED_POLICY_FILE="/sandbox/.hermes/managed-policy.json";var HERMES_INSTALLED_MANAGED_POLICY_FILE="/usr/local/share/nemoclaw/hermes-managed-policy.json";var MAX_HERMES_MANAGED_POLICY_BYTES=4*1024*1024;var MAX_HERMES_SWITCHYARD_CONFIG_BYTES=128*1024;var MANAGED_STARTUP_OWNER_RESULT_MAX_BYTES=4*Math.ceil(MAX_HERMES_MANAGED_POLICY_BYTES/3)+4096;var FIXED_PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";var SHA256_RE4=/^[a-f0-9]{64}$/u;var MANAGED_STARTUP_COMPLETION_SCHEMA_VERSION=1;var MAX_MANAGED_STARTUP_COMPLETION_BYTES=4096;var MAX_MANAGED_STARTUP_RUNTIME_ENVIRONMENT_BYTES=512*1024;var defaultWorkspaceRootApplyDeps={lstat:target2=>managed_startup_filesystem_default.lstatSync(target2),chown:(target2,uid,gid)=>managed_startup_filesystem_default.chownSync(target2,uid,gid),chmod:(target2,mode)=>managed_startup_filesystem_default.chmodSync(target2,mode)};function normalizeManagedStartupWorkspaceRoot(agent,deps=defaultWorkspaceRootApplyDeps){const target2=managedImageRuntimeIdentity(agent).workdir;const before=deps.lstat(target2);if(before.isSymbolicLink()||!before.isDirectory()){fail6("managed startup workspace root must be one real directory")}const expected=managedStartupWorkspaceRoot({agent,agentIdentity:managedImageRuntimeIdentity(agent)});try{deps.chown(target2,expected.uid,expected.gid);deps.chmod(target2,expected.mode)}catch{fail6("managed startup workspace-root normalization failed")}const after=deps.lstat(target2);if(after.isSymbolicLink()||!after.isDirectory()||after.uid!==expected.uid||after.gid!==expected.gid||(after.mode&4095)!==expected.mode){fail6("managed startup workspace root does not match its declared posture")}}var ManagedStartupImageActionPlanError=class extends Error{constructor(message){super(`Cannot build managed startup image action plan: ${message}`);this.name="ManagedStartupImageActionPlanError"}};var ManagedStartupImageRuntimeError=class extends Error{constructor(message){super(`Managed startup image application failed: ${message}`);this.name="ManagedStartupImageRuntimeError"}};function failActionPlan(message){throw new ManagedStartupImageActionPlanError(message)}function exactActionPlanAgent(value){if(MANAGED_STARTUP_AGENTS.includes(value)){return value}return failActionPlan(`unsupported agent ${JSON.stringify(value)}`)}function fail6(message){throw new ManagedStartupImageRuntimeError(message)}function validateManagedStartupApplicationRuntimePlan(plan){if(typeof plan!=="object"||plan===null){return fail6("application runtime plan must be an object")}const exportEnvironment=plan.exportEnvironment;const unsetEnvironment=plan.unsetEnvironment;if(typeof exportEnvironment!=="object"||exportEnvironment===null||Array.isArray(exportEnvironment)||!Array.isArray(unsetEnvironment)){return fail6("application runtime plan must contain exports and unsets")}const exports2={};for(const[name,value]of Object.entries(exportEnvironment)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name)){return fail6(`invalid application runtime environment key ${JSON.stringify(name)}`)}if(typeof value!=="string"||value.includes("\0")||/[\r\n]/u.test(value)){return fail6(`application runtime environment value for ${name} must be single-line text`)}exports2[name]=value}const unsets=new Set;for(const name of unsetEnvironment){if(typeof name!=="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name)){return fail6(`invalid application runtime unset ${JSON.stringify(name)}`)}if(unsets.has(name)){return fail6(`duplicate application runtime unset ${name}`)}if(Object.hasOwn(exports2,name)){return fail6(`application runtime cannot both export and unset ${name}`)}unsets.add(name)}return Object.freeze({exportEnvironment:Object.freeze(Object.fromEntries(Object.entries(exports2).sort(([left],[right])=>left.localeCompare(right)))),unsetEnvironment:Object.freeze([...unsets].sort())})}function applyManagedStartupCommandEnvironmentPlan(environment,plan){const validated=validateManagedStartupApplicationRuntimePlan(plan);const applied={...environment};for(const name of[...Object.keys(validated.exportEnvironment),...validated.unsetEnvironment]){delete applied[name]}return applied}function exactAgent2(value){if(MANAGED_STARTUP_AGENTS.includes(value)){return value}return fail6(`unsupported agent ${JSON.stringify(value)}`)}function managedTransactionProfile(expectedAgentInput,env=process.env){requireRoot();const expectedAgent=exactAgent2(expectedAgentInput);if(env.NEMOCLAW_MANAGED_IMAGE_CAPABILITY_UNION!=="1"){fail6("shared-state transactions require a complete managed image")}const encodedProfile=env[MANAGED_STARTUP_PROFILE_ENV];if(!encodedProfile)fail6(`${MANAGED_STARTUP_PROFILE_ENV} is required`);const profile=decodeManagedStartupProfile(encodedProfile);if(profile.agent!==expectedAgent){fail6(`shared-state transaction profile targets ${profile.agent}, expected ${expectedAgent}`)}return profile}function requireRoot(){if(process.geteuid?.()!==0){fail6("managed startup requires container effective uid 0")}}function modeOf3(stat){return stat.mode&511}function requireManagedStartupExchangeDirectory(exchangeDirectory=MANAGED_STARTUP_EXCHANGE_DIRECTORY){const stat=managed_startup_filesystem_default.lstatSync(exchangeDirectory);if(stat.isSymbolicLink()||!stat.isDirectory()||stat.uid!==0||stat.gid!==0||(stat.mode&4095)!==1023){fail6("managed startup exchange directory must be root:root mode 1777")}}function requireRootOwnedDirectory(target2,mode){let stat;try{stat=managed_startup_filesystem_default.lstatSync(target2)}catch{fail6(`required root-owned directory is missing: ${target2}`)}if(stat.isSymbolicLink()||!stat.isDirectory()||stat.uid!==0||stat.gid!==0||modeOf3(stat)!==mode){fail6(`${target2} must be a root:root directory with mode ${mode.toString(8)}`)}}function ensureRootOwnedDirectory(target2,mode=ROOT_OWNED_DIRECTORY_MODE){const parent=import_node_path3.default.dirname(target2);const parentStat=managed_startup_filesystem_default.lstatSync(parent);if(parentStat.isSymbolicLink()||!parentStat.isDirectory()||parentStat.uid!==0||parentStat.gid!==0||(modeOf3(parentStat)&18)!==0){fail6(`refusing unsafe parent directory for ${target2}`)}try{managed_startup_filesystem_default.mkdirSync(target2,{mode});managed_startup_filesystem_default.chownSync(target2,0,0);managed_startup_filesystem_default.chmodSync(target2,mode)}catch(error){if(error.code!=="EEXIST"){fail6(`could not create ${target2}`)}}requireRootOwnedDirectory(target2,mode)}function requireSafeExistingRootTarget(target2){let stat;try{stat=managed_startup_filesystem_default.lstatSync(target2)}catch(error){if(error.code==="ENOENT")return;fail6(`could not inspect ${target2}`)}if(stat.isSymbolicLink()||!stat.isFile()||stat.nlink!==1||stat.uid!==0||stat.gid!==0){fail6(`refusing to replace unsafe root-owned file ${target2}`)}}function atomicWriteRootFile(target2,contents,mode){const parent=import_node_path3.default.dirname(target2);const parentStat=managed_startup_filesystem_default.lstatSync(parent);const trustedStickyExchange=parent===MANAGED_STARTUP_EXCHANGE_DIRECTORY&&(parentStat.mode&4095)===1023;if(parentStat.isSymbolicLink()||!parentStat.isDirectory()||parentStat.uid!==0||parentStat.gid!==0||(modeOf3(parentStat)&18)!==0&&!trustedStickyExchange){fail6(`refusing unsafe root-owned file parent ${parent}`)}requireSafeExistingRootTarget(target2);const temporary=import_node_path3.default.join(parent,`.${import_node_path3.default.basename(target2)}.${(0,import_node_crypto7.randomBytes)(12).toString("hex")}`);let descriptor;try{descriptor=managed_startup_filesystem_default.openSync(temporary,managed_startup_filesystem_default.constants.O_CREAT|managed_startup_filesystem_default.constants.O_EXCL|managed_startup_filesystem_default.constants.O_WRONLY|managed_startup_filesystem_default.constants.O_NOFOLLOW,384);managed_startup_filesystem_default.fchownSync(descriptor,0,0);managed_startup_filesystem_default.writeFileSync(descriptor,contents);managed_startup_filesystem_default.fchmodSync(descriptor,mode);managed_startup_filesystem_default.fsyncSync(descriptor);managed_startup_filesystem_default.closeSync(descriptor);descriptor=void 0;managed_startup_filesystem_default.renameSync(temporary,target2)}catch(error){if(descriptor!==void 0)managed_startup_filesystem_default.closeSync(descriptor);try{managed_startup_filesystem_default.unlinkSync(temporary)}catch{}fail6(`could not atomically write ${target2}: ${error.message}`)}const stat=managed_startup_filesystem_default.lstatSync(target2);if(stat.isSymbolicLink()||!stat.isFile()||stat.nlink!==1||stat.uid!==0||stat.gid!==0||modeOf3(stat)!==mode){fail6(`root-owned output failed metadata verification: ${target2}`)}}function removeSafeRootFile(target2){requireSafeExistingRootTarget(target2);try{managed_startup_filesystem_default.unlinkSync(target2)}catch(error){if(error.code!=="ENOENT"){fail6(`could not remove ${target2}`)}}}function trustedExecutable2(target2){try{const stat=managed_startup_filesystem_default.lstatSync(target2);return!stat.isSymbolicLink()&&stat.isFile()&&stat.uid===0&&stat.gid===0&&(modeOf3(stat)&18)===0&&(modeOf3(stat)&73)!==0}catch{return false}}function readSandboxIdentity(){const readId=flag=>{const result=(0,import_node_child_process2.spawnSync)("/usr/bin/id",[flag,"sandbox"],{encoding:"utf8",env:{PATH:FIXED_PATH}});const value=result.stdout.trim();if(result.status!==0||!/^[1-9][0-9]*$/u.test(value)){fail6("could not resolve the sandbox account")}return value};return{uid:readId("-u"),gid:readId("-g")}}function managedStartupSandboxPrefix(){if(trustedExecutable2("/usr/bin/setpriv")){const identity2=readSandboxIdentity();return["/usr/bin/setpriv",`--reuid=${identity2.uid}`,`--regid=${identity2.gid}`,"--init-groups","--"]}return fail6("a trusted setpriv executable is required")}function commandEnvironment(configurationEnvironment,applicationRuntime){const env=applyManagedStartupCommandEnvironmentPlan({...process.env,...configurationEnvironment,HOME:"/sandbox",PATH:FIXED_PATH,NPM_CONFIG_OFFLINE:"true",npm_config_offline:"true",PIP_DISABLE_PIP_VERSION_CHECK:"1",PIP_NO_INDEX:"1",UV_OFFLINE:"1"},applicationRuntime);delete env[MANAGED_STARTUP_PROFILE_ENV];delete env[MANAGED_STARTUP_CA_ENV];return env}function execute(argv,runAs,configurationEnvironment,applicationRuntime,capture=false){if(argv.length===0)fail6("refusing an empty managed startup command");const command=runAs==="sandbox"?[...managedStartupSandboxPrefix(),...argv]:[...argv];const result=(0,import_node_child_process2.spawnSync)(command[0],command.slice(1),{encoding:"utf8",env:commandEnvironment(configurationEnvironment,applicationRuntime),stdio:capture?"pipe":"inherit"});if(result.error){fail6(`could not execute ${argv[0]}: ${result.error.message}`)}if(result.status!==0){const detail=capture?`: ${(result.stderr||result.stdout).trim()}`:"";fail6(`${argv[0]} exited with status ${String(result.status??"unknown")}${detail}`)}return{status:result.status,stdout:result.stdout??"",stderr:result.stderr??""}}function generatorCommand(agent){switch(agent){case"openclaw":return["/usr/local/bin/node","/scripts/generate-openclaw-config.mts"];case"hermes":return["/usr/local/bin/node","/opt/nemoclaw-hermes-config/generate-config.ts"];case"langchain-deepagents-code":return["/usr/local/bin/node","/opt/nemoclaw-deepagents-code/generate-config.ts"];case"pi":return["/usr/local/bin/node","/opt/nemoclaw-pi/generate-config.ts"]}}function messagingCommand(agent,phase,mode){return["/usr/local/bin/node","/src/lib/messaging/applier/build/messaging-build-applier.mts","--agent",agent,"--phase",phase,"--mode",mode,...phase==="post-agent-install"?["--managed-startup-runtime"]:[]]}function assertActionAgent(inputAgent,actionAgent){if(inputAgent!==actionAgent){failActionPlan(`action for ${actionAgent} cannot be used by ${inputAgent}`)}}function buildManagedStartupImageActionPlan(input){const inputAgent=exactActionPlanAgent(input.agent);const commands=[];let dashboardActions=0;let generateActions=0;let runtimeMessagingActions=0;let postMessagingActions=0;for(const action of input.actions){switch(action.kind){case"configure-dashboard":{if(action.dashboard.agent!==input.agent){failActionPlan(`dashboard for ${action.dashboard.agent} cannot be used by ${input.agent}`)}dashboardActions+=1;break}case"generate-agent-config":{assertActionAgent(inputAgent,exactActionPlanAgent(action.agent));if(action.runAs!=="sandbox"){failActionPlan("agent configuration generation must run as sandbox")}generateActions+=1;commands.push({action:"generate-agent-config",runAs:action.runAs,argv:generatorCommand(action.agent)});break}case"apply-messaging-plan":{assertActionAgent(inputAgent,exactActionPlanAgent(action.agent));if(action.mode!=="apply"&&action.mode!=="clear"){failActionPlan("messaging intent must be apply or clear")}if(action.phase==="runtime-setup"){if(action.runAs!=="root"){failActionPlan("messaging runtime setup must run as root")}runtimeMessagingActions+=1;commands.push({action:"messaging-runtime-setup",runAs:action.runAs,argv:messagingCommand(action.agent,action.phase,action.mode)})}else if(action.phase==="post-agent-install"){if(action.runAs!=="sandbox"){failActionPlan("messaging post-agent configuration must run as sandbox")}postMessagingActions+=1;commands.push({action:"messaging-post-agent-install",runAs:action.runAs,argv:messagingCommand(action.agent,action.phase,action.mode)})}else{failActionPlan("unsupported messaging construction phase")}break}default:failActionPlan("unsupported managed startup construction action")}}if(dashboardActions!==1){failActionPlan("exactly one dashboard construction action is required")}if(generateActions!==1){failActionPlan("exactly one agent config construction action is required")}const supportsMessaging=MANAGED_STARTUP_MESSAGING_AGENTS.includes(inputAgent);const expectedMessagingActions=supportsMessaging?1:0;if(runtimeMessagingActions!==expectedMessagingActions||postMessagingActions!==expectedMessagingActions){failActionPlan(`${inputAgent} requires ${String(expectedMessagingActions)} action for each messaging phase`)}const expectedOrder=supportsMessaging?["messaging-runtime-setup","generate-agent-config","messaging-post-agent-install"]:["generate-agent-config"];if(commands.some((command,index)=>command.action!==expectedOrder[index])){failActionPlan(`${inputAgent} image actions are not in the required construction order`)}return Object.freeze(commands.map(command=>Object.freeze({...command,argv:Object.freeze([...command.argv])})))}function prepareMessagingRuntimeTarget(mode){if(mode==="clear"){removeSafeRootFile(MESSAGING_RUNTIME_PLAN_FILE);return}requireSafeExistingRootTarget(MESSAGING_RUNTIME_PLAN_FILE);try{managed_startup_filesystem_default.unlinkSync(MESSAGING_RUNTIME_PLAN_FILE)}catch(error){if(error.code!=="ENOENT"){fail6("could not prepare the messaging runtime-plan target")}}}function verifyMessagingRuntimeTarget(mode){if(mode==="clear"){if(managed_startup_filesystem_default.existsSync(MESSAGING_RUNTIME_PLAN_FILE)){fail6("clear messaging profile left a runtime-plan artifact")}return}const stat=managed_startup_filesystem_default.lstatSync(MESSAGING_RUNTIME_PLAN_FILE);if(stat.isSymbolicLink()||!stat.isFile()||stat.nlink!==1||stat.uid!==0||stat.gid!==0||modeOf3(stat)!==420){fail6("messaging runtime-plan artifact failed root ownership validation")}}function runInternalSandboxAction(action,configurationEnvironment,applicationRuntime,extraEnvironment={}){execute(["/usr/local/bin/node",MANAGED_STARTUP_RUNTIME_EXECUTABLE,`--internal-${action}`],"sandbox",{...configurationEnvironment,...extraEnvironment},applicationRuntime)}function validateOpenClawConfiguration(configurationEnvironment,applicationRuntime){const validation=execute(["/usr/local/bin/openclaw","config","validate","--json"],"sandbox",{...configurationEnvironment,OPENCLAW_CONFIG_PATH:"/sandbox/.openclaw/openclaw.json"},applicationRuntime,true);let parsed;try{parsed=JSON.parse(validation.stdout)}catch{fail6("OpenClaw config validation did not emit JSON")}if(typeof parsed!=="object"||parsed===null||parsed.valid!==true){fail6("OpenClaw rejected the generated managed startup config")}}function sameStableFileMetadata(left,right){return left.dev===right.dev&&left.ino===right.ino&&left.mode===right.mode&&left.nlink===right.nlink&&left.uid===right.uid&&left.gid===right.gid&&left.size===right.size&&left.mtimeNs===right.mtimeNs&&left.ctimeNs===right.ctimeNs}function readStableRegularFileSnapshot(target2,maxBytes){if(typeof managed_startup_filesystem_default.constants.O_NOFOLLOW!=="number"){fail6("O_NOFOLLOW is unavailable for managed startup file reads")}const nonblock=typeof managed_startup_filesystem_default.constants.O_NONBLOCK==="number"?managed_startup_filesystem_default.constants.O_NONBLOCK:0;let descriptor;try{descriptor=managed_startup_filesystem_default.openSync(target2,managed_startup_filesystem_default.constants.O_RDONLY|managed_startup_filesystem_default.constants.O_NOFOLLOW|nonblock)}catch(error){if(error.code==="ENOENT")throw error;fail6(`refusing unsafe or unreadable file ${target2}`)}try{const before=managed_startup_filesystem_default.fstatSync(descriptor,{bigint:true});if(!before.isFile()||before.nlink!==1n||before.size<1n||before.size>BigInt(maxBytes)){fail6(`refusing unsafe or oversized file ${target2}`)}const bytes=Buffer.alloc(Number(before.size));let offset=0;while(offset{const identity2=readSandboxIdentity();return{uid:Number(identity2.uid),gid:Number(identity2.gid)}})();const relaySource=expectedSandboxOwnedRoutingSource(paths.relayPluginsSource,expectedRelay,sandboxIdentity);const relayStateSource=expectedSandboxOwnedRoutingSource(paths.relayPluginStateSource,expectedRelayState,sandboxIdentity);const deploymentSource=expectedSandboxOwnedRoutingSource(paths.switchyardDeploymentSource,expectedDeployment,sandboxIdentity);atomicWriteRootFile(paths.switchyardDeploymentTarget,expectedDeployment,292);atomicWriteRootFile(paths.relayPluginStateTarget,expectedRelayState,292);atomicWriteRootFile(paths.relayPluginsTarget,expectedRelay,292);verifyCommittedRoutingFile(paths.switchyardDeploymentTarget,expectedDeployment);verifyCommittedRoutingFile(paths.relayPluginStateTarget,expectedRelayState);verifyCommittedRoutingFile(paths.relayPluginsTarget,expectedRelay);removeStableRoutingSource(paths.switchyardDeploymentSource,deploymentSource);removeStableRoutingSource(paths.relayPluginStateSource,relayStateSource);removeStableRoutingSource(paths.relayPluginsSource,relaySource)}function verifyHermesSwitchyardRoutingFiles(configurationEnvironment,paths=HERMES_SWITCHYARD_ROUTING_PATHS){const routing=readHermesSwitchyardRoutingEnvironment(configurationEnvironment);if(!routing){assertRoutingFileAbsent(paths.relayPluginsTarget);assertRoutingFileAbsent(paths.relayPluginStateTarget);assertRoutingFileAbsent(paths.switchyardDeploymentTarget);return}const serialized=serializeHermesSwitchyardRouting(routing,readSwitchyardProviderBindingsEnvironment(configurationEnvironment,routing));verifyCommittedRoutingFile(paths.relayPluginsTarget,Buffer.from(serialized.relayPluginsToml,"utf8"));verifyCommittedRoutingFile(paths.relayPluginStateTarget,Buffer.from(serialized.relayPluginStateJson,"utf8"));verifyCommittedRoutingFile(paths.switchyardDeploymentTarget,Buffer.from(serialized.switchyardDeploymentToml,"utf8"))}function normalizeHermesManagedConfigDescriptor(target2,sandboxIdentity){if(!Number.isSafeInteger(sandboxIdentity.uid)||sandboxIdentity.uid<=0||!Number.isSafeInteger(sandboxIdentity.gid)||sandboxIdentity.gid<=0){fail6("invalid sandbox identity for Hermes descriptor normalization")}if(typeof managed_startup_filesystem_default.constants.O_NOFOLLOW!=="number"){fail6("O_NOFOLLOW is unavailable for Hermes descriptor normalization")}const nonblock=typeof managed_startup_filesystem_default.constants.O_NONBLOCK==="number"?managed_startup_filesystem_default.constants.O_NONBLOCK:0;let descriptor;try{descriptor=managed_startup_filesystem_default.openSync(target2,managed_startup_filesystem_default.constants.O_RDONLY|managed_startup_filesystem_default.constants.O_NOFOLLOW|nonblock)}catch{fail6(`refusing unsafe Hermes managed config descriptor ${target2}`)}try{const before=managed_startup_filesystem_default.fstatSync(descriptor,{bigint:true});const beforeMode=Number(before.mode&0o777n);const mutable=before.uid===BigInt(sandboxIdentity.uid)&&before.gid===BigInt(sandboxIdentity.gid)&&(beforeMode===384||beforeMode===416);if(!before.isFile()||before.nlink!==1n||!mutable){fail6(`refusing unexpected Hermes managed config descriptor ${target2}`)}const expectedMode=416;if(beforeMode===384){try{managed_startup_filesystem_default.fchmodSync(descriptor,expectedMode)}catch{fail6(`could not normalize Hermes managed config descriptor ${target2}`)}}const after=managed_startup_filesystem_default.fstatSync(descriptor,{bigint:true});let pathAfter;try{pathAfter=managed_startup_filesystem_default.lstatSync(target2,{bigint:true})}catch{fail6(`Hermes managed config descriptor disappeared during normalization: ${target2}`)}const expectedUid=BigInt(sandboxIdentity.uid);const expectedGid=BigInt(sandboxIdentity.gid);if(!after.isFile()||after.nlink!==1n||after.dev!==before.dev||after.ino!==before.ino||after.uid!==expectedUid||after.gid!==expectedGid||Number(after.mode&0o777n)!==expectedMode||after.size!==before.size||after.mtimeNs!==before.mtimeNs||pathAfter.isSymbolicLink()||!pathAfter.isFile()||!sameStableFileMetadata(after,pathAfter)){fail6(`Hermes managed config descriptor changed during normalization: ${target2}`)}}finally{try{managed_startup_filesystem_default.closeSync(descriptor)}catch{fail6(`could not close Hermes managed config descriptor ${target2}`)}}}function normalizeHermesManagedConfiguration(){const identity2=readSandboxIdentity();const sandboxIdentity={uid:Number(identity2.uid),gid:Number(identity2.gid)};for(const target2 of HERMES_MANAGED_CONFIG_FILES){normalizeHermesManagedConfigDescriptor(target2,sandboxIdentity)}}function sealHermesConfiguration(configurationEnvironment,applicationRuntime){const configPath="/sandbox/.hermes/config.yaml";const envPath="/sandbox/.hermes/.env";const config=readStableRegularFile(configPath,4*1024*1024);const env=readStableRegularFile(envPath,512*1024);const hashText=[`${(0,import_node_crypto7.createHash)("sha256").update(config).digest("hex")} ${configPath}`,`${(0,import_node_crypto7.createHash)("sha256").update(env).digest("hex")} ${envPath}`,""].join("\n");atomicWriteRootFile("/etc/nemoclaw/hermes.config-hash",hashText,292);runInternalSandboxAction("write-hermes-compat-hash",configurationEnvironment,applicationRuntime,{NEMOCLAW_MANAGED_HERMES_HASH_B64:Buffer.from(hashText,"utf8").toString("base64")})}function installRootOwnedMaterials(materials){for(const material of materials){if(material.kind!=="root-owned-file")continue;if(material.owner!=="root"||material.group!=="root"||material.mode!==292){fail6(`unsupported root-owned material contract for ${material.path}`)}atomicWriteRootFile(material.path,material.contents,material.mode)}}function verifyRootOwnedMaterials(materials){for(const material of materials){if(material.kind!=="root-owned-file")continue;const expected=Buffer.from(material.contents,"utf8");const{bytes,stat}=readStableRegularFileSnapshot(material.path,expected.length);if(stat.nlink!==1n||stat.uid!==0n||stat.gid!==0n||Number(stat.mode&0o777n)!==material.mode||!bytes.equals(expected)){fail6(`committed root-owned material drifted: ${material.path}`)}}}function installCorporateCa(corporateCaPath){if(corporateCaPath===null){removeSafeRootFile(MANAGED_STARTUP_CORPORATE_CA_FILE);return}const bytes=readStableRegularFile(corporateCaPath,128*1024);atomicWriteRootFile(MANAGED_STARTUP_CORPORATE_CA_FILE,bytes,292)}function corporateCaCertificateBlocks(corporateCaPath){const corporate=readStableRegularFile(corporateCaPath,128*1024).toString("utf8");const blocks=corporate.match(PEM_CERTIFICATE_RE_GLOBAL);if(!blocks||blocks.length===0){fail6("corporate CA material contains no certificate")}for(const block of blocks){try{if(!new import_node_crypto7.X509Certificate(block).ca){fail6("corporate CA material contains a certificate that is not a CA")}}catch(error){if(error instanceof ManagedStartupImageRuntimeError)throw error;fail6("corporate CA material contains an invalid certificate")}}return blocks.map(block=>`${block.trim()} +`}function requireExactKeys(record2,keys){if(Object.keys(record2).sort().join(",")!==[...keys].sort().join(",")){fail5("transaction manifest contains unexpected fields")}}function parseCommitReceipt(text){let parsed;try{parsed=JSON.parse(text)}catch{fail5("commit receipt is not valid JSON")}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){fail5("commit receipt must be an object")}const record2=parsed;requireExactKeys(record2,["agent","bootstrapIdentity","profileFingerprint","schemaVersion"]);if(record2.schemaVersion!==TRANSACTION_SCHEMA_VERSION||!MANAGED_STARTUP_AGENTS.includes(String(record2.agent))||typeof record2.profileFingerprint!=="string"||!/^[a-f0-9]{64}$/u.test(record2.profileFingerprint)||typeof record2.bootstrapIdentity!=="string"||!/^[a-f0-9]{64}$/u.test(record2.bootstrapIdentity)){fail5("commit receipt has an invalid envelope")}const receipt={schemaVersion:TRANSACTION_SCHEMA_VERSION,agent:record2.agent,profileFingerprint:record2.profileFingerprint,bootstrapIdentity:record2.bootstrapIdentity};if(canonicalCommitReceipt(receipt)!==text){fail5("commit receipt is not canonical")}return receipt}function safeMetadata(value){return Number.isSafeInteger(value)&&value>=0}function parseManifest(text){let parsed;try{parsed=JSON.parse(text)}catch{fail5("transaction manifest is not valid JSON")}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){fail5("transaction manifest must be an object")}const record2=parsed;const hasBootstrapIdentity=Object.hasOwn(record2,"bootstrapIdentity");requireExactKeys(record2,hasBootstrapIdentity?["agent","bootstrapIdentity","directories","files","profileFingerprint","schemaVersion"]:["agent","directories","files","profileFingerprint","schemaVersion"]);const bootstrapIdentity=hasBootstrapIdentity?record2.bootstrapIdentity:null;if(record2.schemaVersion!==TRANSACTION_SCHEMA_VERSION||!MANAGED_STARTUP_AGENTS.includes(String(record2.agent))||typeof record2.profileFingerprint!=="string"||!/^[a-f0-9]{64}$/u.test(record2.profileFingerprint)||!(bootstrapIdentity===null||typeof bootstrapIdentity==="string"&&/^[a-f0-9]{64}$/u.test(bootstrapIdentity))||!Array.isArray(record2.files)||!Array.isArray(record2.directories)||record2.files.length>MAX_TRANSACTION_FILES||record2.directories.length>MAX_TRANSACTION_FILES*4){fail5("transaction manifest has an invalid envelope")}const files=record2.files.map(value=>{if(typeof value!=="object"||value===null||Array.isArray(value)){return fail5("transaction file receipt must be an object")}const receipt=value;if(typeof receipt.path!=="string"){return fail5("transaction file receipt path must be a string")}const receiptPath=safeRelativePath(receipt.path);if(receipt.state==="absent"){requireExactKeys(receipt,["path","state"]);return{path:receiptPath,state:"absent"}}requireExactKeys(receipt,["backup","gid","mode","path","sha256","size","state","uid"]);if(receipt.state!=="file"||typeof receipt.backup!=="string"||!/^[0-9]{3}\.bin$/u.test(receipt.backup)||typeof receipt.sha256!=="string"||!/^[a-f0-9]{64}$/u.test(receipt.sha256)||!safeMetadata(receipt.size)||receipt.size>MAX_TRANSACTION_FILE_BYTES||!safeMetadata(receipt.uid)||!safeMetadata(receipt.gid)||!safeMetadata(receipt.mode)||receipt.mode>4095){return fail5("transaction file receipt is invalid")}return{path:receiptPath,state:"file",backup:receipt.backup,sha256:receipt.sha256,size:receipt.size,uid:receipt.uid,gid:receipt.gid,mode:receipt.mode}});const directories=record2.directories.map(value=>{if(typeof value!=="object"||value===null||Array.isArray(value)){return fail5("transaction directory receipt must be an object")}const receipt=value;if(typeof receipt.path!=="string"){return fail5("transaction directory receipt path must be a string")}const receiptPath=safeRelativePath(receipt.path);if(receipt.state==="absent"){requireExactKeys(receipt,["path","state"]);return{path:receiptPath,state:"absent"}}requireExactKeys(receipt,["gid","mode","path","state","uid"]);if(receipt.state!=="directory"||!safeMetadata(receipt.uid)||!safeMetadata(receipt.gid)||!safeMetadata(receipt.mode)||receipt.mode>4095){return fail5("transaction directory receipt is invalid")}return{path:receiptPath,state:"directory",uid:receipt.uid,gid:receipt.gid,mode:receipt.mode}});const filePaths=files.map(receipt=>receipt.path);const directoryPaths=directories.map(receipt=>receipt.path);const backupNames=files.filter(receipt=>receipt.state==="file").map(receipt=>receipt.backup);if(new Set(filePaths).size!==filePaths.length||new Set(directoryPaths).size!==directoryPaths.length||new Set(backupNames).size!==backupNames.length){fail5("transaction manifest contains duplicate receipts")}const manifest={schemaVersion:TRANSACTION_SCHEMA_VERSION,agent:record2.agent,profileFingerprint:record2.profileFingerprint,bootstrapIdentity,files,directories};const canonical=hasBootstrapIdentity?canonicalManifest(manifest):canonicalLegacyManifest(manifest);if(canonical!==text){fail5("transaction manifest is not canonical")}return manifest}function requireTrustedTransactionPath(target2,mode,options){const stat=import_node_fs3.default.lstatSync(target2);if(stat.isSymbolicLink()||(mode===TRANSACTION_DIRECTORY_MODE?!stat.isDirectory():!stat.isFile())||!options.readOnlyReceipt&&(stat.uid!==options.trustedUid||stat.gid!==options.trustedGid)||modeOf2(stat)!==mode){fail5(`transaction artifact has unsafe metadata: ${target2}`)}}function requireReadOnlyReceiptMount(target2,options){if(!options.readOnlyReceipt)return;const probe=import_node_path2.default.join(target2,".nemoclaw-write-probe");let descriptor;try{descriptor=import_node_fs3.default.openSync(probe,import_node_fs3.default.constants.O_CREAT|import_node_fs3.default.constants.O_EXCL|import_node_fs3.default.constants.O_WRONLY|import_node_fs3.default.constants.O_NOFOLLOW,384);import_node_fs3.default.closeSync(descriptor);descriptor=void 0;import_node_fs3.default.unlinkSync(probe)}catch(error){if(descriptor!==void 0)import_node_fs3.default.closeSync(descriptor);if(error.code==="EROFS")return;fail5("copied receipt must be mounted on a read-only filesystem")}fail5("copied receipt mount is writable")}function loadManifest(options){requireTransactionBoundaries(options);if(!pathExistsNoFollow(options.transactionDirectory))return null;requireTrustedTransactionPath(options.transactionDirectory,TRANSACTION_DIRECTORY_MODE,options);requireReadOnlyReceiptMount(options.transactionDirectory,options);requireTrustedTransactionPath(options.backupDirectory,TRANSACTION_DIRECTORY_MODE,options);requireTrustedTransactionPath(options.manifestFile,TRANSACTION_FILE_MODE,options);const stable=readStableFile(options.manifestFile,MAX_MANIFEST_BYTES);if(!options.readOnlyReceipt&&(Number(stable.stat.uid)!==options.trustedUid||Number(stable.stat.gid)!==options.trustedGid)||Number(stable.stat.mode&0o7777n)!==TRANSACTION_FILE_MODE){fail5("transaction manifest ownership changed while it was read")}return parseManifest(stable.bytes.toString("utf8"))}function transactionOptionsAt(options,transactionDirectory){return{...options,transactionDirectory,backupDirectory:import_node_path2.default.join(transactionDirectory,"backups"),manifestFile:import_node_path2.default.join(transactionDirectory,"manifest.json")}}function loadCommitReceipt(options){requireTransactionBoundaries(options);if(!pathExistsNoFollow(options.commitReceiptDirectory))return null;requireTrustedTransactionPath(options.commitReceiptDirectory,TRANSACTION_DIRECTORY_MODE,options);if(pathExistsNoFollow(options.commitReceiptFile)){requireReadOnlyReceiptMount(options.commitReceiptDirectory,options);requireTrustedTransactionPath(options.commitReceiptFile,TRANSACTION_FILE_MODE,options);const stable=readStableFile(options.commitReceiptFile,MAX_COMMIT_RECEIPT_BYTES);if(!options.readOnlyReceipt&&(Number(stable.stat.uid)!==options.trustedUid||Number(stable.stat.gid)!==options.trustedGid)||Number(stable.stat.mode&0o7777n)!==TRANSACTION_FILE_MODE){fail5("commit receipt ownership changed while it was read")}return{receipt:parseCommitReceipt(stable.bytes.toString("utf8")),compact:true}}const stagedOptions=transactionOptionsAt(options,options.commitReceiptDirectory);const staged=loadManifest(stagedOptions);if(!staged||staged.bootstrapIdentity===null){fail5("durable commit staging receipt is incomplete")}verifyAllBackups(staged.files,stagedOptions);return{receipt:{schemaVersion:TRANSACTION_SCHEMA_VERSION,agent:staged.agent,profileFingerprint:staged.profileFingerprint,bootstrapIdentity:staged.bootstrapIdentity},compact:false}}function verifyBackup(receipt,options){const backupPath=import_node_path2.default.join(options.backupDirectory,receipt.backup);requireTrustedTransactionPath(backupPath,TRANSACTION_FILE_MODE,options);const stable=readStableFile(backupPath,MAX_TRANSACTION_FILE_BYTES);const digest=(0,import_node_crypto6.createHash)("sha256").update(stable.bytes).digest("hex");if(stable.bytes.length!==receipt.size||digest!==receipt.sha256){fail5(`transaction backup does not match its receipt: ${receipt.path}`)}return stable.bytes}function verifyAllBackups(receipts,options){const backups=new Map;for(const receipt of receipts){if(receipt.state==="file"){backups.set(receipt.path,verifyBackup(receipt,options))}}return backups}function fileMatchesReceipt(target2,receipt){let stat;try{stat=import_node_fs3.default.lstatSync(target2)}catch(error){if(error.code==="ENOENT")return false;fail5(`could not inspect managed output ${target2}`)}if(stat.isSymbolicLink()||!stat.isFile()||stat.nlink!==1)return false;const stable=readStableFile(target2,MAX_TRANSACTION_FILE_BYTES);return stable.bytes.length===receipt.size&&(0,import_node_crypto6.createHash)("sha256").update(stable.bytes).digest("hex")===receipt.sha256&&Number(stable.stat.uid)===receipt.uid&&Number(stable.stat.gid)===receipt.gid&&Number(stable.stat.mode&0o7777n)===receipt.mode}function directoryMatchesReceipt(target2,receipt){let stat;try{stat=import_node_fs3.default.lstatSync(target2)}catch(error){if(error.code==="ENOENT")return false;fail5(`could not inspect managed output directory ${target2}`)}return!stat.isSymbolicLink()&&stat.isDirectory()&&stat.uid===receipt.uid&&stat.gid===receipt.gid&&modeOf2(stat)===receipt.mode}function removeTransactionDirectory(options){requireTrustedTransactionPath(options.transactionDirectory,TRANSACTION_DIRECTORY_MODE,options);import_node_fs3.default.rmSync(options.transactionDirectory,{force:false,recursive:true});fsyncDirectory(options.transactionParentDirectory);if(pathExistsNoFollow(options.transactionDirectory)){fail5("transaction directory remained after cleanup")}}function assertCommitReceiptMatches(receipt,expected){if(receipt.agent!==expected.agent||expected.profileFingerprint!==void 0&&receipt.profileFingerprint!==expected.profileFingerprint||receipt.bootstrapIdentity!==expected.bootstrapIdentity){fail5("durable commit receipt belongs to a different bootstrap attempt")}}function loadCommitStagingManifest(options){if(!pathExistsNoFollow(options.manifestFile))return null;requireTrustedTransactionPath(options.manifestFile,TRANSACTION_FILE_MODE,options);const stable=readStableFile(options.manifestFile,MAX_MANIFEST_BYTES);if(Number(stable.stat.uid)!==options.trustedUid||Number(stable.stat.gid)!==options.trustedGid||Number(stable.stat.mode&0o7777n)!==TRANSACTION_FILE_MODE){fail5("durable commit staging manifest ownership changed while it was read")}return parseManifest(stable.bytes.toString("utf8"))}function retireInterruptedCommitReceiptWrites(receipt,options){const temporaryPattern=new RegExp(`^\\.${MANAGED_STARTUP_SHARED_COMMIT_RECEIPT_FILE.replace(".","\\.")}\\.[a-f0-9]{24}$`,"u");for(const entry of import_node_fs3.default.readdirSync(options.commitReceiptDirectory)){if(!temporaryPattern.test(entry))continue;const target2=import_node_path2.default.join(options.commitReceiptDirectory,entry);const stat=import_node_fs3.default.lstatSync(target2);if(stat.isSymbolicLink()||!stat.isFile()||stat.nlink!==1||stat.uid!==options.trustedUid||stat.gid!==options.trustedGid||![ATOMIC_TEMPORARY_FILE_MODE,TRANSACTION_FILE_MODE].includes(modeOf2(stat))){fail5("interrupted durable commit receipt write has unsafe metadata")}const stable=readStableFile(target2,MAX_COMMIT_RECEIPT_BYTES);const mode=Number(stable.stat.mode&0o7777n);if(Number(stable.stat.uid)!==options.trustedUid||Number(stable.stat.gid)!==options.trustedGid||![ATOMIC_TEMPORARY_FILE_MODE,TRANSACTION_FILE_MODE].includes(mode)){fail5("interrupted durable commit receipt write changed during verification")}if(stable.bytes.length>0){let interruptedReceipt=null;try{interruptedReceipt=parseCommitReceipt(stable.bytes.toString("utf8"))}catch{}if(interruptedReceipt)assertCommitReceiptMatches(interruptedReceipt,receipt)}import_node_fs3.default.unlinkSync(target2);fsyncDirectory(options.commitReceiptDirectory)}}function compactDurableCommitReceipt(state,options){if(!state.compact){atomicWriteTrustedFile(options.commitReceiptFile,canonicalCommitReceipt(state.receipt),TRANSACTION_FILE_MODE,options.trustedUid,options.trustedGid);fsyncDirectory(options.commitReceiptDirectory)}retireInterruptedCommitReceiptWrites(state.receipt,options);const stagedOptions=transactionOptionsAt(options,options.commitReceiptDirectory);const manifestExists=pathExistsNoFollow(stagedOptions.manifestFile);const backupsExist=pathExistsNoFollow(stagedOptions.backupDirectory);const unexpectedBeforeCleanup=import_node_fs3.default.readdirSync(options.commitReceiptDirectory).filter(entry=>![MANAGED_STARTUP_SHARED_COMMIT_RECEIPT_FILE,import_node_path2.default.basename(stagedOptions.backupDirectory),import_node_path2.default.basename(stagedOptions.manifestFile)].includes(entry));if(unexpectedBeforeCleanup.length!==0){fail5("durable commit receipt directory contains unexpected artifacts")}if(manifestExists){const staged=loadCommitStagingManifest(stagedOptions);if(!staged||staged.bootstrapIdentity===null){fail5("durable commit staging receipt disappeared during cleanup")}assertCommitReceiptMatches(state.receipt,{agent:staged.agent,profileFingerprint:staged.profileFingerprint,bootstrapIdentity:staged.bootstrapIdentity})}if(backupsExist){requireTrustedTransactionPath(stagedOptions.backupDirectory,TRANSACTION_DIRECTORY_MODE,options);import_node_fs3.default.rmSync(stagedOptions.backupDirectory,{force:false,recursive:true});fsyncDirectory(options.commitReceiptDirectory)}if(manifestExists){requireTrustedTransactionPath(stagedOptions.manifestFile,TRANSACTION_FILE_MODE,options);import_node_fs3.default.unlinkSync(stagedOptions.manifestFile);fsyncDirectory(options.commitReceiptDirectory)}const unexpected=import_node_fs3.default.readdirSync(options.commitReceiptDirectory).filter(entry=>entry!==MANAGED_STARTUP_SHARED_COMMIT_RECEIPT_FILE);if(unexpected.length!==0){fail5("durable commit receipt directory contains unexpected artifacts")}const verified=loadCommitReceipt(options);if(!verified?.compact)fail5("durable commit receipt did not compact successfully");assertCommitReceiptMatches(verified.receipt,state.receipt)}function beginManagedStartupSharedStateTransaction(profile,inputOptions={}){const options=resolveOptions(inputOptions);requireTransactionIdentity(options);if(options.readOnlyReceipt){fail5("cannot begin a transaction from a read-only rollback receipt")}requireTransactionBoundaries(options);const profileFingerprint=fingerprintManagedStartupProfile(profile);const committed=loadCommitReceipt(options);if(committed){if(options.bootstrapIdentity===null){fail5("a durable managed bootstrap commit receipt already exists")}assertCommitReceiptMatches(committed.receipt,{agent:profile.agent,profileFingerprint,bootstrapIdentity:options.bootstrapIdentity});fail5("this managed bootstrap attempt is already durably committed")}const pending=loadManifest(options);if(pending){if(pending.agent!==profile.agent||pending.profileFingerprint!==profileFingerprint||pending.bootstrapIdentity!==options.bootstrapIdentity){fail5("a pending managed startup transaction belongs to a different agent, profile fingerprint, or bootstrap attempt")}verifyAllBackups(pending.files,options);return false}const targets=managedOutputTargets(profile,options);if(targets.files.length>MAX_TRANSACTION_FILES){fail5("managed startup transaction has too many file targets")}const snapshots=targets.files.map((target2,index)=>snapshotFile(target2,index,profile.agent,options));const totalBytes=snapshots.reduce((sum,snapshot)=>sum+(snapshot.bytes?.length??0),0);if(totalBytes>MAX_TRANSACTION_TOTAL_BYTES){fail5("managed startup transaction backup exceeds the total size limit")}const directories=targets.directories.map(target2=>snapshotDirectory(target2,profile.agent,options));const manifest={schemaVersion:TRANSACTION_SCHEMA_VERSION,agent:profile.agent,profileFingerprint,bootstrapIdentity:options.bootstrapIdentity,files:snapshots.map(({receipt})=>receipt),directories};let createdTransactionIdentity;try{import_node_fs3.default.mkdirSync(options.transactionDirectory,{mode:TRANSACTION_DIRECTORY_MODE});const created=import_node_fs3.default.lstatSync(options.transactionDirectory,{bigint:true});if(!created.isDirectory()||created.isSymbolicLink()){fail5("new transaction path is not a directory")}createdTransactionIdentity={dev:created.dev,ino:created.ino,uid:created.uid,gid:created.gid};import_node_fs3.default.chownSync(options.transactionDirectory,options.trustedUid,options.trustedGid);import_node_fs3.default.chmodSync(options.transactionDirectory,TRANSACTION_DIRECTORY_MODE);fsyncDirectory(options.transactionParentDirectory);import_node_fs3.default.mkdirSync(options.backupDirectory,{mode:TRANSACTION_DIRECTORY_MODE});import_node_fs3.default.chownSync(options.backupDirectory,options.trustedUid,options.trustedGid);import_node_fs3.default.chmodSync(options.backupDirectory,TRANSACTION_DIRECTORY_MODE);fsyncDirectory(options.transactionDirectory);for(const snapshot of snapshots){if(snapshot.receipt.state!=="file"||snapshot.bytes===null)continue;atomicWriteTrustedFile(import_node_path2.default.join(options.backupDirectory,snapshot.receipt.backup),snapshot.bytes,TRANSACTION_FILE_MODE,options.trustedUid,options.trustedGid)}fsyncDirectory(options.backupDirectory);atomicWriteTrustedFile(options.manifestFile,canonicalManifest(manifest),TRANSACTION_FILE_MODE,options.trustedUid,options.trustedGid);fsyncDirectory(options.transactionDirectory);loadManifest(options)}catch(error){try{if(createdTransactionIdentity&&pathExistsNoFollow(options.transactionDirectory)){const current=import_node_fs3.default.lstatSync(options.transactionDirectory,{bigint:true});if(!current.isSymbolicLink()&¤t.isDirectory()&¤t.dev===createdTransactionIdentity.dev&¤t.ino===createdTransactionIdentity.ino&¤t.uid===createdTransactionIdentity.uid&¤t.gid===createdTransactionIdentity.gid){import_node_fs3.default.chmodSync(options.transactionDirectory,TRANSACTION_DIRECTORY_MODE);import_node_fs3.default.chownSync(options.transactionDirectory,options.trustedUid,options.trustedGid)}requireTrustedTransactionPath(options.transactionDirectory,TRANSACTION_DIRECTORY_MODE,options);import_node_fs3.default.rmSync(options.transactionDirectory,{force:true,recursive:true})}}catch{}throw error}return true}function ensureOriginalDirectories(receipts,expectedAgent,options){for(const receipt of receipts){if(receipt.state!=="directory")continue;const target2=absoluteTarget(receipt.path,options);validateExistingAncestors(import_node_path2.default.join(target2,".restore"),expectedAgent,options);let stat=null;try{stat=import_node_fs3.default.lstatSync(target2)}catch(error){if(error.code!=="ENOENT"){fail5(`could not inspect restore directory ${target2}`)}}if(stat&&(stat.isSymbolicLink()||!stat.isDirectory())){fail5(`restore directory is unsafe: ${target2}`)}if(stat&&directoryMatchesReceipt(target2,receipt))continue;if(!stat)import_node_fs3.default.mkdirSync(target2,{mode:receipt.mode});import_node_fs3.default.chownSync(target2,receipt.uid,receipt.gid);import_node_fs3.default.chmodSync(target2,receipt.mode)}}function restoreFiles(receipts,backups,expectedAgent,options){for(const receipt of receipts){const target2=absoluteTarget(receipt.path,options);validateExistingAncestors(target2,expectedAgent,options);if(receipt.state==="absent"){let stat;try{stat=import_node_fs3.default.lstatSync(target2)}catch(error){if(error.code==="ENOENT")continue;fail5(`could not inspect new managed output ${target2}`)}if(stat.isDirectory()){fail5(`new managed output unexpectedly became a directory: ${target2}`)}import_node_fs3.default.unlinkSync(target2);continue}if(fileMatchesReceipt(target2,receipt))continue;const bytes=backups.get(receipt.path);if(!bytes)fail5(`verified transaction backup is missing: ${receipt.path}`);let current=null;try{current=import_node_fs3.default.lstatSync(target2)}catch(error){if(error.code!=="ENOENT"){fail5(`could not inspect managed output before restore: ${target2}`)}}if(current?.isDirectory()){fail5(`managed output unexpectedly became a directory: ${target2}`)}atomicWriteTrustedFile(target2,bytes,receipt.mode,receipt.uid,receipt.gid)}}function restoreDirectoryMetadata(receipts,options){for(const receipt of[...receipts].reverse()){const target2=absoluteTarget(receipt.path,options);if(receipt.state==="absent"){try{import_node_fs3.default.rmdirSync(target2)}catch(error){if(error.code==="ENOENT")continue;fail5(`could not remove newly created managed directory ${target2}`)}continue}if(directoryMatchesReceipt(target2,receipt))continue;const stat=import_node_fs3.default.lstatSync(target2);if(stat.isSymbolicLink()||!stat.isDirectory()){fail5(`managed directory changed type during restore: ${target2}`)}import_node_fs3.default.chownSync(target2,receipt.uid,receipt.gid);import_node_fs3.default.chmodSync(target2,receipt.mode)}}function verifyRestoration(manifest,options){for(const receipt of manifest.files){const target2=absoluteTarget(receipt.path,options);if(receipt.state==="absent"){if(pathExistsNoFollow(target2)){fail5(`new managed output remained after rollback: ${target2}`)}continue}const stable=readStableFile(target2,MAX_TRANSACTION_FILE_BYTES);if(stable.bytes.length!==receipt.size||(0,import_node_crypto6.createHash)("sha256").update(stable.bytes).digest("hex")!==receipt.sha256||Number(stable.stat.uid)!==receipt.uid||Number(stable.stat.gid)!==receipt.gid||Number(stable.stat.mode&0o7777n)!==receipt.mode){fail5(`managed output was not restored exactly: ${target2}`)}}for(const receipt of manifest.directories){const target2=absoluteTarget(receipt.path,options);if(receipt.state==="absent"){if(pathExistsNoFollow(target2)){fail5(`new managed directory remained after rollback: ${target2}`)}continue}const stat=import_node_fs3.default.lstatSync(target2);if(stat.isSymbolicLink()||!stat.isDirectory()||stat.uid!==receipt.uid||stat.gid!==receipt.gid||modeOf2(stat)!==receipt.mode){fail5(`managed directory metadata was not restored exactly: ${target2}`)}}}function rollbackManagedStartupSharedStateTransaction(expectedAgent,inputOptions={}){const options=resolveOptions(inputOptions);requireTransactionIdentity(options);const committed=loadCommitReceipt(options);if(committed){if(options.bootstrapIdentity===null){fail5("shared state is already durably committed")}assertCommitReceiptMatches(committed.receipt,{agent:expectedAgent,bootstrapIdentity:options.bootstrapIdentity});fail5("shared state is already durably committed and cannot be rolled back")}const manifest=loadManifest(options);if(!manifest)return false;if(manifest.agent!==expectedAgent){fail5(`pending transaction targets ${manifest.agent}, expected ${expectedAgent}`)}if(manifest.bootstrapIdentity!==options.bootstrapIdentity){fail5("pending transaction belongs to a different bootstrap attempt")}const backups=verifyAllBackups(manifest.files,options);ensureOriginalDirectories(manifest.directories,expectedAgent,options);restoreFiles(manifest.files,backups,expectedAgent,options);restoreDirectoryMetadata(manifest.directories,options);verifyRestoration(manifest,options);if(!options.readOnlyReceipt){removeTransactionDirectory(options)}return true}function commitManagedStartupSharedStateTransaction(expectedAgent,inputOptions={}){const options=resolveOptions(inputOptions);requireTransactionIdentity(options);if(options.readOnlyReceipt){fail5("cannot commit a read-only rollback receipt")}const committed=loadCommitReceipt(options);if(committed){if(options.bootstrapIdentity===null){fail5("durable commit receipt is missing its expected bootstrap identity")}assertCommitReceiptMatches(committed.receipt,{agent:expectedAgent,bootstrapIdentity:options.bootstrapIdentity});compactDurableCommitReceipt(committed,options);return true}const manifest=loadManifest(options);if(!manifest)return false;if(manifest.agent!==expectedAgent){fail5(`pending transaction targets ${manifest.agent}, expected ${expectedAgent}`)}if(manifest.bootstrapIdentity!==options.bootstrapIdentity){fail5("pending transaction belongs to a different bootstrap attempt")}if(manifest.bootstrapIdentity===null){removeTransactionDirectory(options);return true}verifyAllBackups(manifest.files,options);if(pathExistsNoFollow(options.commitReceiptDirectory)){fail5("durable commit receipt path appeared before transaction commit")}try{import_node_fs3.default.renameSync(options.transactionDirectory,options.commitReceiptDirectory);fsyncDirectory(options.transactionParentDirectory)}catch(error){fail5(`could not atomically establish durable commit state: ${error.message}`)}const renamed=loadCommitReceipt(options);if(!renamed)fail5("durable commit state disappeared after atomic rename");assertCommitReceiptMatches(renamed.receipt,{agent:expectedAgent,profileFingerprint:manifest.profileFingerprint,bootstrapIdentity:manifest.bootstrapIdentity});compactDurableCommitReceipt(renamed,options);return true}function clearManagedStartupSharedStateCommitReceipt(expectedAgent,inputOptions={}){const options=resolveOptions(inputOptions);requireTransactionIdentity(options);if(options.readOnlyReceipt){fail5("cannot clear a durable commit from a read-only receipt")}if(options.bootstrapIdentity===null){fail5("durable commit cleanup requires its bootstrap identity")}const committed=loadCommitReceipt(options);if(!committed)return false;assertCommitReceiptMatches(committed.receipt,{agent:expectedAgent,bootstrapIdentity:options.bootstrapIdentity});compactDurableCommitReceipt(committed,options);requireTrustedTransactionPath(options.commitReceiptDirectory,TRANSACTION_DIRECTORY_MODE,options);requireTrustedTransactionPath(options.commitReceiptFile,TRANSACTION_FILE_MODE,options);const entries=import_node_fs3.default.readdirSync(options.commitReceiptDirectory);if(entries.length!==1||entries[0]!==MANAGED_STARTUP_SHARED_COMMIT_RECEIPT_FILE){fail5("durable commit receipt directory contains unexpected artifacts")}import_node_fs3.default.rmSync(options.commitReceiptDirectory,{force:false,recursive:true});fsyncDirectory(options.transactionParentDirectory);if(pathExistsNoFollow(options.commitReceiptDirectory)){fail5("durable commit receipt remained after cleanup")}return true}function getManagedStartupSharedStateTransactionStatus(expected,inputOptions={}){const options=resolveOptions({...inputOptions,bootstrapIdentity:expected.bootstrapIdentity});requireTransactionIdentity(options);const manifest=loadManifest(options);if(manifest){if(manifest.agent!==expected.agent||manifest.profileFingerprint!==expected.profileFingerprint||manifest.bootstrapIdentity!==expected.bootstrapIdentity){fail5("pending transaction does not match the expected agent, profile fingerprint, or bootstrap identity")}verifyAllBackups(manifest.files,options);return"pending"}const committed=loadCommitReceipt(options);if(!committed)return"none";assertCommitReceiptMatches(committed.receipt,expected);return"committed"}var MANAGED_STARTUP_PROFILE_ENV="NEMOCLAW_STARTUP_PROFILE_B64";var MANAGED_STARTUP_CA_ENV="NEMOCLAW_CORPORATE_CA_B64";var MANAGED_STARTUP_EXCHANGE_DIRECTORY="/tmp";var MANAGED_STARTUP_RUNTIME_ENV_FILE=`${MANAGED_STARTUP_EXCHANGE_DIRECTORY}/nemoclaw-managed-startup-runtime.env`;var MANAGED_STARTUP_RUNTIME_EXECUTABLE="/usr/local/lib/nemoclaw/managed-startup-image-runtime.cjs";var MANAGED_STARTUP_MERGED_CA_FILE=`${MANAGED_STARTUP_EXCHANGE_DIRECTORY}/nemoclaw-managed-startup-ca-bundle.pem`;var MANAGED_STARTUP_COMPLETION_FILE=`${MANAGED_STARTUP_EXCHANGE_DIRECTORY}/nemoclaw-managed-startup-complete.json`;var MANAGED_STARTUP_CORPORATE_CA_FILE="/usr/local/share/nemoclaw/corporate-ca.pem";var MANAGED_STARTUP_SYSTEM_CA_ANCHOR_DIRECTORY="/usr/local/share/ca-certificates";var MANAGED_STARTUP_SYSTEM_CA_ANCHOR_RE=/^nemoclaw-corporate-ca-[0-9]{2}\.crt$/u;var SYSTEM_CA_BUNDLE_FILE="/etc/ssl/certs/ca-certificates.crt";var UPDATE_CA_CERTIFICATES_EXECUTABLE="/usr/sbin/update-ca-certificates";var MANAGED_STARTUP_TLS_ENV_NAMES=new Set(["CURL_CA_BUNDLE","GIT_SSL_CAINFO","NODE_EXTRA_CA_CERTS","REQUESTS_CA_BUNDLE","SSL_CERT_FILE"]);var MESSAGING_RUNTIME_PLAN_FILE="/usr/local/share/nemoclaw/messaging-runtime-plan.json";var ROOT_STATE_PARENT="/var/lib/nemoclaw";var ROOT_RUNTIME_DIRECTORY="/run/nemoclaw";var ROOT_OWNED_DIRECTORY_MODE=493;var MAX_TRUST_BUNDLE_BYTES=4*1024*1024;var HERMES_MANAGED_CONFIG_FILES=["/sandbox/.hermes/config.yaml","/sandbox/.hermes/.env"];var HERMES_GENERATED_MANAGED_POLICY_FILE="/sandbox/.hermes/managed-policy.json";var HERMES_INSTALLED_MANAGED_POLICY_FILE="/usr/local/share/nemoclaw/hermes-managed-policy.json";var MAX_HERMES_MANAGED_POLICY_BYTES=4*1024*1024;var MAX_HERMES_SWITCHYARD_CONFIG_BYTES=128*1024;var MANAGED_STARTUP_OWNER_RESULT_MAX_BYTES=4*Math.ceil(MAX_HERMES_MANAGED_POLICY_BYTES/3)+4096;var FIXED_PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin";var SHA256_RE4=/^[a-f0-9]{64}$/u;var MANAGED_STARTUP_COMPLETION_SCHEMA_VERSION=1;var MAX_MANAGED_STARTUP_COMPLETION_BYTES=4096;var MAX_MANAGED_STARTUP_RUNTIME_ENVIRONMENT_BYTES=512*1024;var defaultWorkspaceRootApplyDeps={lstat:target2=>managed_startup_filesystem_default.lstatSync(target2),chown:(target2,uid,gid)=>managed_startup_filesystem_default.chownSync(target2,uid,gid),chmod:(target2,mode)=>managed_startup_filesystem_default.chmodSync(target2,mode)};function normalizeManagedStartupWorkspaceRoot(agent,deps=defaultWorkspaceRootApplyDeps){const target2=managedImageRuntimeIdentity(agent).workdir;const before=deps.lstat(target2);if(before.isSymbolicLink()||!before.isDirectory()){fail6("managed startup workspace root must be one real directory")}const expected=managedStartupWorkspaceRoot({agent,agentIdentity:managedImageRuntimeIdentity(agent)});try{deps.chown(target2,expected.uid,expected.gid);deps.chmod(target2,expected.mode)}catch{fail6("managed startup workspace-root normalization failed")}const after=deps.lstat(target2);if(after.isSymbolicLink()||!after.isDirectory()||after.uid!==expected.uid||after.gid!==expected.gid||(after.mode&4095)!==expected.mode){fail6("managed startup workspace root does not match its declared posture")}}var ManagedStartupImageActionPlanError=class extends Error{constructor(message){super(`Cannot build managed startup image action plan: ${message}`);this.name="ManagedStartupImageActionPlanError"}};var ManagedStartupImageRuntimeError=class extends Error{constructor(message){super(`Managed startup image application failed: ${message}`);this.name="ManagedStartupImageRuntimeError"}};function failActionPlan(message){throw new ManagedStartupImageActionPlanError(message)}function exactActionPlanAgent(value){if(MANAGED_STARTUP_AGENTS.includes(value)){return value}return failActionPlan(`unsupported agent ${JSON.stringify(value)}`)}function fail6(message){throw new ManagedStartupImageRuntimeError(message)}function validateManagedStartupApplicationRuntimePlan(plan){if(typeof plan!=="object"||plan===null){return fail6("application runtime plan must be an object")}const exportEnvironment=plan.exportEnvironment;const unsetEnvironment=plan.unsetEnvironment;if(typeof exportEnvironment!=="object"||exportEnvironment===null||Array.isArray(exportEnvironment)||!Array.isArray(unsetEnvironment)){return fail6("application runtime plan must contain exports and unsets")}const exports2={};for(const[name,value]of Object.entries(exportEnvironment)){if(!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name)){return fail6(`invalid application runtime environment key ${JSON.stringify(name)}`)}if(typeof value!=="string"||value.includes("\0")||/[\r\n]/u.test(value)){return fail6(`application runtime environment value for ${name} must be single-line text`)}exports2[name]=value}const unsets=new Set;for(const name of unsetEnvironment){if(typeof name!=="string"||!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name)){return fail6(`invalid application runtime unset ${JSON.stringify(name)}`)}if(unsets.has(name)){return fail6(`duplicate application runtime unset ${name}`)}if(Object.hasOwn(exports2,name)){return fail6(`application runtime cannot both export and unset ${name}`)}unsets.add(name)}return Object.freeze({exportEnvironment:Object.freeze(Object.fromEntries(Object.entries(exports2).sort(([left],[right])=>left.localeCompare(right)))),unsetEnvironment:Object.freeze([...unsets].sort())})}function applyManagedStartupCommandEnvironmentPlan(environment,plan){const validated=validateManagedStartupApplicationRuntimePlan(plan);const applied={...environment};for(const name of[...Object.keys(validated.exportEnvironment),...validated.unsetEnvironment]){delete applied[name]}return applied}function exactAgent2(value){if(MANAGED_STARTUP_AGENTS.includes(value)){return value}return fail6(`unsupported agent ${JSON.stringify(value)}`)}function managedTransactionProfile(expectedAgentInput,env=process.env){requireRoot();const expectedAgent=exactAgent2(expectedAgentInput);if(env.NEMOCLAW_MANAGED_IMAGE_CAPABILITY_UNION!=="1"){fail6("shared-state transactions require a complete managed image")}const encodedProfile=env[MANAGED_STARTUP_PROFILE_ENV];if(!encodedProfile)fail6(`${MANAGED_STARTUP_PROFILE_ENV} is required`);const profile=decodeManagedStartupProfile(encodedProfile);if(profile.agent!==expectedAgent){fail6(`shared-state transaction profile targets ${profile.agent}, expected ${expectedAgent}`)}return profile}function requireRoot(){if(process.geteuid?.()!==0){fail6("managed startup requires container effective uid 0")}}function modeOf3(stat){return stat.mode&511}function requireManagedStartupExchangeDirectory(exchangeDirectory=MANAGED_STARTUP_EXCHANGE_DIRECTORY){const stat=managed_startup_filesystem_default.lstatSync(exchangeDirectory);if(stat.isSymbolicLink()||!stat.isDirectory()||stat.uid!==0||stat.gid!==0||(stat.mode&4095)!==1023){fail6("managed startup exchange directory must be root:root mode 1777")}}function requireRootOwnedDirectory(target2,mode){let stat;try{stat=managed_startup_filesystem_default.lstatSync(target2)}catch{fail6(`required root-owned directory is missing: ${target2}`)}if(stat.isSymbolicLink()||!stat.isDirectory()||stat.uid!==0||stat.gid!==0||modeOf3(stat)!==mode){fail6(`${target2} must be a root:root directory with mode ${mode.toString(8)}`)}}function ensureRootOwnedDirectory(target2,mode=ROOT_OWNED_DIRECTORY_MODE){const parent=import_node_path3.default.dirname(target2);const parentStat=managed_startup_filesystem_default.lstatSync(parent);if(parentStat.isSymbolicLink()||!parentStat.isDirectory()||parentStat.uid!==0||parentStat.gid!==0||(modeOf3(parentStat)&18)!==0){fail6(`refusing unsafe parent directory for ${target2}`)}try{managed_startup_filesystem_default.mkdirSync(target2,{mode});managed_startup_filesystem_default.chownSync(target2,0,0);managed_startup_filesystem_default.chmodSync(target2,mode)}catch(error){if(error.code!=="EEXIST"){fail6(`could not create ${target2}`)}}requireRootOwnedDirectory(target2,mode)}function requireSafeExistingRootTarget(target2){let stat;try{stat=managed_startup_filesystem_default.lstatSync(target2)}catch(error){if(error.code==="ENOENT")return;fail6(`could not inspect ${target2}`)}if(stat.isSymbolicLink()||!stat.isFile()||stat.nlink!==1||stat.uid!==0||stat.gid!==0){fail6(`refusing to replace unsafe root-owned file ${target2}`)}}function atomicWriteRootFile(target2,contents,mode){const parent=import_node_path3.default.dirname(target2);const parentStat=managed_startup_filesystem_default.lstatSync(parent);const trustedStickyExchange=parent===MANAGED_STARTUP_EXCHANGE_DIRECTORY&&(parentStat.mode&4095)===1023;if(parentStat.isSymbolicLink()||!parentStat.isDirectory()||parentStat.uid!==0||parentStat.gid!==0||(modeOf3(parentStat)&18)!==0&&!trustedStickyExchange){fail6(`refusing unsafe root-owned file parent ${parent}`)}requireSafeExistingRootTarget(target2);const temporary=import_node_path3.default.join(parent,`.${import_node_path3.default.basename(target2)}.${(0,import_node_crypto7.randomBytes)(12).toString("hex")}`);let descriptor;try{descriptor=managed_startup_filesystem_default.openSync(temporary,managed_startup_filesystem_default.constants.O_CREAT|managed_startup_filesystem_default.constants.O_EXCL|managed_startup_filesystem_default.constants.O_WRONLY|managed_startup_filesystem_default.constants.O_NOFOLLOW,384);managed_startup_filesystem_default.fchownSync(descriptor,0,0);managed_startup_filesystem_default.writeFileSync(descriptor,contents);managed_startup_filesystem_default.fchmodSync(descriptor,mode);managed_startup_filesystem_default.fsyncSync(descriptor);managed_startup_filesystem_default.closeSync(descriptor);descriptor=void 0;managed_startup_filesystem_default.renameSync(temporary,target2)}catch(error){if(descriptor!==void 0)managed_startup_filesystem_default.closeSync(descriptor);try{managed_startup_filesystem_default.unlinkSync(temporary)}catch{}fail6(`could not atomically write ${target2}: ${error.message}`)}const stat=managed_startup_filesystem_default.lstatSync(target2);if(stat.isSymbolicLink()||!stat.isFile()||stat.nlink!==1||stat.uid!==0||stat.gid!==0||modeOf3(stat)!==mode){fail6(`root-owned output failed metadata verification: ${target2}`)}}function removeSafeRootFile(target2){requireSafeExistingRootTarget(target2);try{managed_startup_filesystem_default.unlinkSync(target2)}catch(error){if(error.code!=="ENOENT"){fail6(`could not remove ${target2}`)}}}function trustedExecutable2(target2){try{const stat=managed_startup_filesystem_default.lstatSync(target2);return!stat.isSymbolicLink()&&stat.isFile()&&stat.uid===0&&stat.gid===0&&(modeOf3(stat)&18)===0&&(modeOf3(stat)&73)!==0}catch{return false}}function readSandboxIdentity(){const readId=flag=>{const result=(0,import_node_child_process2.spawnSync)("/usr/bin/id",[flag,"sandbox"],{encoding:"utf8",env:{PATH:FIXED_PATH}});const value=result.stdout.trim();if(result.status!==0||!/^[1-9][0-9]*$/u.test(value)){fail6("could not resolve the sandbox account")}return value};return{uid:readId("-u"),gid:readId("-g")}}function managedStartupSandboxPrefix(){if(trustedExecutable2("/usr/bin/setpriv")){const identity2=readSandboxIdentity();return["/usr/bin/setpriv",`--reuid=${identity2.uid}`,`--regid=${identity2.gid}`,"--init-groups","--"]}return fail6("a trusted setpriv executable is required")}function commandEnvironment(configurationEnvironment,applicationRuntime){const env=applyManagedStartupCommandEnvironmentPlan({...process.env,...configurationEnvironment,HOME:"/sandbox",PATH:FIXED_PATH,NPM_CONFIG_OFFLINE:"true",npm_config_offline:"true",PIP_DISABLE_PIP_VERSION_CHECK:"1",PIP_NO_INDEX:"1",UV_OFFLINE:"1"},applicationRuntime);delete env[MANAGED_STARTUP_PROFILE_ENV];delete env[MANAGED_STARTUP_CA_ENV];return env}function execute(argv,runAs,configurationEnvironment,applicationRuntime,capture=false){if(argv.length===0)fail6("refusing an empty managed startup command");const command=runAs==="sandbox"?[...managedStartupSandboxPrefix(),...argv]:[...argv];const result=(0,import_node_child_process2.spawnSync)(command[0],command.slice(1),{encoding:"utf8",env:commandEnvironment(configurationEnvironment,applicationRuntime),stdio:capture?"pipe":"inherit"});if(result.error){fail6(`could not execute ${argv[0]}: ${result.error.message}`)}if(result.status!==0){const detail=capture?`: ${(result.stderr||result.stdout).trim()}`:"";fail6(`${argv[0]} exited with status ${String(result.status??"unknown")}${detail}`)}return{status:result.status,stdout:result.stdout??"",stderr:result.stderr??""}}function generatorCommand(agent){switch(agent){case"openclaw":return["/usr/local/bin/node","/scripts/generate-openclaw-config.mts"];case"hermes":return["/usr/local/bin/node","/opt/nemoclaw-hermes-config/generate-config.ts"];case"langchain-deepagents-code":return["/usr/local/bin/node","/opt/nemoclaw-deepagents-code/generate-config.ts"];case"pi":return["/usr/local/bin/node","/opt/nemoclaw-pi/generate-config.ts"]}}function messagingCommand(agent,phase,mode){return["/usr/local/bin/node","/src/lib/messaging/applier/build/messaging-build-applier.mts","--agent",agent,"--phase",phase,"--mode",mode,...phase==="post-agent-install"?["--managed-startup-runtime"]:[]]}function assertActionAgent(inputAgent,actionAgent){if(inputAgent!==actionAgent){failActionPlan(`action for ${actionAgent} cannot be used by ${inputAgent}`)}}function buildManagedStartupImageActionPlan(input){const inputAgent=exactActionPlanAgent(input.agent);const commands=[];let dashboardActions=0;let generateActions=0;let runtimeMessagingActions=0;let postMessagingActions=0;for(const action of input.actions){switch(action.kind){case"configure-dashboard":{if(action.dashboard.agent!==input.agent){failActionPlan(`dashboard for ${action.dashboard.agent} cannot be used by ${input.agent}`)}dashboardActions+=1;break}case"generate-agent-config":{assertActionAgent(inputAgent,exactActionPlanAgent(action.agent));if(action.runAs!=="sandbox"){failActionPlan("agent configuration generation must run as sandbox")}generateActions+=1;commands.push({action:"generate-agent-config",runAs:action.runAs,argv:generatorCommand(action.agent)});break}case"apply-messaging-plan":{assertActionAgent(inputAgent,exactActionPlanAgent(action.agent));if(action.mode!=="apply"&&action.mode!=="clear"){failActionPlan("messaging intent must be apply or clear")}if(action.phase==="runtime-setup"){if(action.runAs!=="root"){failActionPlan("messaging runtime setup must run as root")}runtimeMessagingActions+=1;commands.push({action:"messaging-runtime-setup",runAs:action.runAs,argv:messagingCommand(action.agent,action.phase,action.mode)})}else if(action.phase==="post-agent-install"){if(action.runAs!=="sandbox"){failActionPlan("messaging post-agent configuration must run as sandbox")}postMessagingActions+=1;commands.push({action:"messaging-post-agent-install",runAs:action.runAs,argv:messagingCommand(action.agent,action.phase,action.mode)})}else{failActionPlan("unsupported messaging construction phase")}break}default:failActionPlan("unsupported managed startup construction action")}}if(dashboardActions!==1){failActionPlan("exactly one dashboard construction action is required")}if(generateActions!==1){failActionPlan("exactly one agent config construction action is required")}const supportsMessaging=MANAGED_STARTUP_MESSAGING_AGENTS.includes(inputAgent);const expectedMessagingActions=supportsMessaging?1:0;if(runtimeMessagingActions!==expectedMessagingActions||postMessagingActions!==expectedMessagingActions){failActionPlan(`${inputAgent} requires ${String(expectedMessagingActions)} action for each messaging phase`)}const expectedOrder=supportsMessaging?["messaging-runtime-setup","generate-agent-config","messaging-post-agent-install"]:["generate-agent-config"];if(commands.some((command,index)=>command.action!==expectedOrder[index])){failActionPlan(`${inputAgent} image actions are not in the required construction order`)}return Object.freeze(commands.map(command=>Object.freeze({...command,argv:Object.freeze([...command.argv])})))}function prepareMessagingRuntimeTarget(mode){if(mode==="clear"){removeSafeRootFile(MESSAGING_RUNTIME_PLAN_FILE);return}requireSafeExistingRootTarget(MESSAGING_RUNTIME_PLAN_FILE);try{managed_startup_filesystem_default.unlinkSync(MESSAGING_RUNTIME_PLAN_FILE)}catch(error){if(error.code!=="ENOENT"){fail6("could not prepare the messaging runtime-plan target")}}}function verifyMessagingRuntimeTarget(mode){if(mode==="clear"){if(managed_startup_filesystem_default.existsSync(MESSAGING_RUNTIME_PLAN_FILE)){fail6("clear messaging profile left a runtime-plan artifact")}return}const stat=managed_startup_filesystem_default.lstatSync(MESSAGING_RUNTIME_PLAN_FILE);if(stat.isSymbolicLink()||!stat.isFile()||stat.nlink!==1||stat.uid!==0||stat.gid!==0||modeOf3(stat)!==420){fail6("messaging runtime-plan artifact failed root ownership validation")}}function runInternalSandboxAction(action,configurationEnvironment,applicationRuntime,extraEnvironment={}){execute(["/usr/local/bin/node",MANAGED_STARTUP_RUNTIME_EXECUTABLE,`--internal-${action}`],"sandbox",{...configurationEnvironment,...extraEnvironment},applicationRuntime)}function validateOpenClawConfiguration(configurationEnvironment,applicationRuntime){const validation=execute(["/usr/local/bin/openclaw","config","validate","--json"],"sandbox",{...configurationEnvironment,OPENCLAW_CONFIG_PATH:"/sandbox/.openclaw/openclaw.json"},applicationRuntime,true);let parsed;try{parsed=JSON.parse(validation.stdout)}catch{fail6("OpenClaw config validation did not emit JSON")}if(typeof parsed!=="object"||parsed===null||parsed.valid!==true){fail6("OpenClaw rejected the generated managed startup config")}}function sameStableFileMetadata(left,right){return left.dev===right.dev&&left.ino===right.ino&&left.mode===right.mode&&left.nlink===right.nlink&&left.uid===right.uid&&left.gid===right.gid&&left.size===right.size&&left.mtimeNs===right.mtimeNs&&left.ctimeNs===right.ctimeNs}function readStableRegularFileSnapshot(target2,maxBytes){if(typeof managed_startup_filesystem_default.constants.O_NOFOLLOW!=="number"){fail6("O_NOFOLLOW is unavailable for managed startup file reads")}const nonblock=typeof managed_startup_filesystem_default.constants.O_NONBLOCK==="number"?managed_startup_filesystem_default.constants.O_NONBLOCK:0;let descriptor;try{descriptor=managed_startup_filesystem_default.openSync(target2,managed_startup_filesystem_default.constants.O_RDONLY|managed_startup_filesystem_default.constants.O_NOFOLLOW|nonblock)}catch(error){if(error.code==="ENOENT")throw error;fail6(`refusing unsafe or unreadable file ${target2}`)}try{const before=managed_startup_filesystem_default.fstatSync(descriptor,{bigint:true});if(!before.isFile()||before.nlink!==1n||before.size<1n||before.size>BigInt(maxBytes)){fail6(`refusing unsafe or oversized file ${target2}`)}const bytes=Buffer.alloc(Number(before.size));let offset=0;while(offset --switchyard-config +Replace with an unused sandbox name and with your Switchyard routing JSON file. +This creates a fresh workspace; it does not recover data from the failed sandbox. +Restoring your previous data requires an independently maintained backup. +Do not delete the failed sandbox while data recovery is unresolved.`)}}function assertRoutingFileAbsent(target2){try{managed_startup_filesystem_default.lstatSync(target2)}catch(error){if(error.code==="ENOENT")return;fail6(`could not inspect disabled Hermes routing artifact: ${target2}`)}fail6(`disabled Hermes routing left a stale artifact: ${target2}`)}function removeStableRoutingSource(target2,snapshot){const current=managed_startup_filesystem_default.lstatSync(target2,{bigint:true});if(!sameStableFileMetadata(snapshot.stat,current)){fail6(`Hermes routing artifact changed before source cleanup: ${target2}`)}managed_startup_filesystem_default.unlinkSync(target2)}function installHermesSwitchyardRoutingFiles(configurationEnvironment,paths=HERMES_SWITCHYARD_ROUTING_PATHS,sandboxIdentityInput){const routing=readHermesSwitchyardRoutingEnvironment(configurationEnvironment);if(!routing){removeSafeRootFile(paths.relayPluginsTarget);removeSafeRootFile(paths.relayPluginStateTarget);removeSafeRootFile(paths.switchyardDeploymentTarget);return}const serialized=serializeHermesSwitchyardRouting(routing,readSwitchyardProviderBindingsEnvironment(configurationEnvironment,routing));const expectedRelay=Buffer.from(serialized.relayPluginsToml,"utf8");const expectedRelayState=Buffer.from(serialized.relayPluginStateJson,"utf8");const expectedDeployment=Buffer.from(serialized.switchyardDeploymentToml,"utf8");const sandboxIdentity=sandboxIdentityInput??(()=>{const identity2=readSandboxIdentity();return{uid:Number(identity2.uid),gid:Number(identity2.gid)}})();const relaySource=expectedSandboxOwnedRoutingSource(paths.relayPluginsSource,expectedRelay,sandboxIdentity);const relayStateSource=expectedSandboxOwnedRoutingSource(paths.relayPluginStateSource,expectedRelayState,sandboxIdentity);const deploymentSource=expectedSandboxOwnedRoutingSource(paths.switchyardDeploymentSource,expectedDeployment,sandboxIdentity);atomicWriteRootFile(paths.switchyardDeploymentTarget,expectedDeployment,292);atomicWriteRootFile(paths.relayPluginStateTarget,expectedRelayState,292);atomicWriteRootFile(paths.relayPluginsTarget,expectedRelay,292);verifyCommittedRoutingFile(paths.switchyardDeploymentTarget,expectedDeployment);verifyCommittedRoutingFile(paths.relayPluginStateTarget,expectedRelayState);verifyCommittedRoutingFile(paths.relayPluginsTarget,expectedRelay);removeStableRoutingSource(paths.switchyardDeploymentSource,deploymentSource);removeStableRoutingSource(paths.relayPluginStateSource,relayStateSource);removeStableRoutingSource(paths.relayPluginsSource,relaySource)}function verifyHermesSwitchyardRoutingFiles(configurationEnvironment,paths=HERMES_SWITCHYARD_ROUTING_PATHS){const routing=readHermesSwitchyardRoutingEnvironment(configurationEnvironment);if(!routing){assertRoutingFileAbsent(paths.relayPluginsTarget);assertRoutingFileAbsent(paths.relayPluginStateTarget);assertRoutingFileAbsent(paths.switchyardDeploymentTarget);return}const serialized=serializeHermesSwitchyardRouting(routing,readSwitchyardProviderBindingsEnvironment(configurationEnvironment,routing));verifyCommittedRoutingFile(paths.relayPluginsTarget,Buffer.from(serialized.relayPluginsToml,"utf8"));verifyCommittedRoutingFile(paths.relayPluginStateTarget,Buffer.from(serialized.relayPluginStateJson,"utf8"));verifyCommittedRoutingFile(paths.switchyardDeploymentTarget,Buffer.from(serialized.switchyardDeploymentToml,"utf8"))}function normalizeHermesManagedConfigDescriptor(target2,sandboxIdentity){if(!Number.isSafeInteger(sandboxIdentity.uid)||sandboxIdentity.uid<=0||!Number.isSafeInteger(sandboxIdentity.gid)||sandboxIdentity.gid<=0){fail6("invalid sandbox identity for Hermes descriptor normalization")}if(typeof managed_startup_filesystem_default.constants.O_NOFOLLOW!=="number"){fail6("O_NOFOLLOW is unavailable for Hermes descriptor normalization")}const nonblock=typeof managed_startup_filesystem_default.constants.O_NONBLOCK==="number"?managed_startup_filesystem_default.constants.O_NONBLOCK:0;let descriptor;try{descriptor=managed_startup_filesystem_default.openSync(target2,managed_startup_filesystem_default.constants.O_RDONLY|managed_startup_filesystem_default.constants.O_NOFOLLOW|nonblock)}catch{fail6(`refusing unsafe Hermes managed config descriptor ${target2}`)}try{const before=managed_startup_filesystem_default.fstatSync(descriptor,{bigint:true});const beforeMode=Number(before.mode&0o777n);const mutable=before.uid===BigInt(sandboxIdentity.uid)&&before.gid===BigInt(sandboxIdentity.gid)&&(beforeMode===384||beforeMode===416);if(!before.isFile()||before.nlink!==1n||!mutable){fail6(`refusing unexpected Hermes managed config descriptor ${target2}`)}const expectedMode=416;if(beforeMode===384){try{managed_startup_filesystem_default.fchmodSync(descriptor,expectedMode)}catch{fail6(`could not normalize Hermes managed config descriptor ${target2}`)}}const after=managed_startup_filesystem_default.fstatSync(descriptor,{bigint:true});let pathAfter;try{pathAfter=managed_startup_filesystem_default.lstatSync(target2,{bigint:true})}catch{fail6(`Hermes managed config descriptor disappeared during normalization: ${target2}`)}const expectedUid=BigInt(sandboxIdentity.uid);const expectedGid=BigInt(sandboxIdentity.gid);if(!after.isFile()||after.nlink!==1n||after.dev!==before.dev||after.ino!==before.ino||after.uid!==expectedUid||after.gid!==expectedGid||Number(after.mode&0o777n)!==expectedMode||after.size!==before.size||after.mtimeNs!==before.mtimeNs||pathAfter.isSymbolicLink()||!pathAfter.isFile()||!sameStableFileMetadata(after,pathAfter)){fail6(`Hermes managed config descriptor changed during normalization: ${target2}`)}}finally{try{managed_startup_filesystem_default.closeSync(descriptor)}catch{fail6(`could not close Hermes managed config descriptor ${target2}`)}}}function normalizeHermesManagedConfiguration(){const identity2=readSandboxIdentity();const sandboxIdentity={uid:Number(identity2.uid),gid:Number(identity2.gid)};for(const target2 of HERMES_MANAGED_CONFIG_FILES){normalizeHermesManagedConfigDescriptor(target2,sandboxIdentity)}}function sealHermesConfiguration(configurationEnvironment,applicationRuntime){const configPath="/sandbox/.hermes/config.yaml";const envPath="/sandbox/.hermes/.env";const config=readStableRegularFile(configPath,4*1024*1024);const env=readStableRegularFile(envPath,512*1024);const hashText=[`${(0,import_node_crypto7.createHash)("sha256").update(config).digest("hex")} ${configPath}`,`${(0,import_node_crypto7.createHash)("sha256").update(env).digest("hex")} ${envPath}`,""].join("\n");atomicWriteRootFile("/etc/nemoclaw/hermes.config-hash",hashText,292);runInternalSandboxAction("write-hermes-compat-hash",configurationEnvironment,applicationRuntime,{NEMOCLAW_MANAGED_HERMES_HASH_B64:Buffer.from(hashText,"utf8").toString("base64")})}function installRootOwnedMaterials(materials){for(const material of materials){if(material.kind!=="root-owned-file")continue;if(material.owner!=="root"||material.group!=="root"||material.mode!==292){fail6(`unsupported root-owned material contract for ${material.path}`)}atomicWriteRootFile(material.path,material.contents,material.mode)}}function verifyRootOwnedMaterials(materials){for(const material of materials){if(material.kind!=="root-owned-file")continue;const expected=Buffer.from(material.contents,"utf8");const{bytes,stat}=readStableRegularFileSnapshot(material.path,expected.length);if(stat.nlink!==1n||stat.uid!==0n||stat.gid!==0n||Number(stat.mode&0o777n)!==material.mode||!bytes.equals(expected)){fail6(`committed root-owned material drifted: ${material.path}`)}}}function installCorporateCa(corporateCaPath){if(corporateCaPath===null){removeSafeRootFile(MANAGED_STARTUP_CORPORATE_CA_FILE);return}const bytes=readStableRegularFile(corporateCaPath,128*1024);atomicWriteRootFile(MANAGED_STARTUP_CORPORATE_CA_FILE,bytes,292)}function corporateCaCertificateBlocks(corporateCaPath){const corporate=readStableRegularFile(corporateCaPath,128*1024).toString("utf8");const blocks=corporate.match(PEM_CERTIFICATE_RE_GLOBAL);if(!blocks||blocks.length===0){fail6("corporate CA material contains no certificate")}for(const block of blocks){try{if(!new import_node_crypto7.X509Certificate(block).ca){fail6("corporate CA material contains a certificate that is not a CA")}}catch(error){if(error instanceof ManagedStartupImageRuntimeError)throw error;fail6("corporate CA material contains an invalid certificate")}}return blocks.map(block=>`${block.trim()} `)}function managedSystemCaAnchorNames(){try{managed_startup_filesystem_default.lstatSync(MANAGED_STARTUP_SYSTEM_CA_ANCHOR_DIRECTORY)}catch(error){if(error.code==="ENOENT")return[];fail6("could not inspect the managed system CA anchor directory")}requireRootOwnedDirectory(MANAGED_STARTUP_SYSTEM_CA_ANCHOR_DIRECTORY,ROOT_OWNED_DIRECTORY_MODE);try{return managed_startup_filesystem_default.readdirSync(MANAGED_STARTUP_SYSTEM_CA_ANCHOR_DIRECTORY).filter(name=>MANAGED_STARTUP_SYSTEM_CA_ANCHOR_RE.test(name)).sort()}catch(error){fail6("could not inspect the managed system CA anchors")}}function refreshSystemCaBundle(){if(!trustedExecutable2(UPDATE_CA_CERTIFICATES_EXECUTABLE)){fail6(`a trusted ${UPDATE_CA_CERTIFICATES_EXECUTABLE} executable is required`)}const result=(0,import_node_child_process2.spawnSync)(UPDATE_CA_CERTIFICATES_EXECUTABLE,[],{encoding:"utf8",env:{PATH:FIXED_PATH},stdio:"inherit"});if(result.error){fail6(`could not execute ${UPDATE_CA_CERTIFICATES_EXECUTABLE}: ${result.error.message}`)}if(result.status!==0){fail6(`${UPDATE_CA_CERTIFICATES_EXECUTABLE} exited with status ${String(result.status??"unknown")}`)}}function requireSystemCaBundleContains(blocks){const systemBundle=safeTrustBundle(SYSTEM_CA_BUNDLE_FILE);if(systemBundle===null)fail6("the refreshed system CA bundle is missing");const systemBlocks=systemBundle.toString("utf8").match(PEM_CERTIFICATE_RE_GLOBAL)??[];const systemFingerprints=new Set;for(const block of systemBlocks){try{systemFingerprints.add(new import_node_crypto7.X509Certificate(block).fingerprint256)}catch{fail6("the refreshed system CA bundle contains an invalid certificate")}}for(const block of blocks){if(!systemFingerprints.has(new import_node_crypto7.X509Certificate(block).fingerprint256)){fail6("the refreshed system CA bundle does not contain the corporate CA")}}}function installCorporateCaSystemAnchors(corporateCaPath){const existingNames=managedSystemCaAnchorNames();if(corporateCaPath===null){for(const name of existingNames){removeSafeRootFile(import_node_path3.default.join(MANAGED_STARTUP_SYSTEM_CA_ANCHOR_DIRECTORY,name))}refreshSystemCaBundle();return}ensureRootOwnedDirectory(MANAGED_STARTUP_SYSTEM_CA_ANCHOR_DIRECTORY);const blocks=corporateCaCertificateBlocks(corporateCaPath);const expectedNames=blocks.map((_block,index)=>`nemoclaw-corporate-ca-${String(index+1).padStart(2,"0")}.crt`);for(const name of existingNames){if(!expectedNames.includes(name)){removeSafeRootFile(import_node_path3.default.join(MANAGED_STARTUP_SYSTEM_CA_ANCHOR_DIRECTORY,name))}}for(const[index,name]of expectedNames.entries()){atomicWriteRootFile(import_node_path3.default.join(MANAGED_STARTUP_SYSTEM_CA_ANCHOR_DIRECTORY,name),blocks[index],292)}refreshSystemCaBundle();requireSystemCaBundleContains(blocks)}function safeTrustBundle(target2){try{const{bytes,stat}=readStableRegularFileSnapshot(target2,MAX_TRUST_BUNDLE_BYTES);if(Number(stat.mode&0o022n)!==0){fail6(`refusing unsafe trust bundle ${target2}`)}return bytes}catch(error){if(error.code==="ENOENT")return null;throw error}}function mergeCorporateCa(corporateCaPath){if(corporateCaPath===null){removeSafeRootFile(MANAGED_STARTUP_MERGED_CA_FILE);return false}const corporate=readStableRegularFile(corporateCaPath,128*1024);const candidates=["/etc/openshell-tls/ca-bundle.pem",process.env.SSL_CERT_FILE??"","/etc/ssl/certs/ca-certificates.crt"].filter((candidate,index,values)=>candidate&&candidate!==MANAGED_STARTUP_MERGED_CA_FILE&&values.indexOf(candidate)===index);let base=null;for(const candidate of candidates){base=safeTrustBundle(candidate);if(base)break}const merged=Buffer.concat([...base?[base,Buffer.from("\n","utf8")]:[],corporate,...corporate.at(-1)===10?[]:[Buffer.from("\n","utf8")]]);atomicWriteRootFile(MANAGED_STARTUP_MERGED_CA_FILE,merged,292);return true}function shellSingleQuote(value){if(value.includes("\0")||/[\r\n]/u.test(value)){fail6("runtime environment values must be single-line text")}return`'${value.replaceAll("'",`'"'"'`)}'`}function serializeManagedStartupRuntimeEnvironment(environment,corporateCaMerged,configurationEnvironment={},applicationRuntime={exportEnvironment:{},unsetEnvironment:[]}){const{output,unsetNames}=materializeManagedStartupRuntimeEnvironment(environment,corporateCaMerged,configurationEnvironment,applicationRuntime);const unsetLines=unsetNames.map(name=>`unset ${name}`);const exportLines=Object.entries(output).sort(([left],[right])=>left.localeCompare(right)).map(([name,value])=>`export ${name}=${shellSingleQuote(value)}`);return`${[...unsetLines,...exportLines].join("\n")} `}function materializeManagedStartupRuntimeEnvironment(environment,corporateCaMerged,configurationEnvironment={},applicationRuntime={exportEnvironment:{},unsetEnvironment:[]}){const validatedApplicationRuntime=validateManagedStartupApplicationRuntimePlan(applicationRuntime);const output={...environment,...validatedApplicationRuntime.exportEnvironment,NEMOCLAW_MANAGED_STARTUP_APPLIED:"1"};if(corporateCaMerged){for(const name of MANAGED_STARTUP_TLS_ENV_NAMES){delete output[name]}output._NEMOCLAW_CORPORATE_CA_MERGED="1"}for(const name of[...Object.keys(configurationEnvironment),...Object.keys(output)]){if(!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name)){fail6(`invalid runtime environment key ${JSON.stringify(name)}`)}}const unsetNames=new Set([...Object.keys(configurationEnvironment).filter(name=>!Object.hasOwn(output,name)&&(!corporateCaMerged||!MANAGED_STARTUP_TLS_ENV_NAMES.has(name))),...validatedApplicationRuntime.unsetEnvironment.filter(name=>!corporateCaMerged||!MANAGED_STARTUP_TLS_ENV_NAMES.has(name))]);for(const name of validatedApplicationRuntime.unsetEnvironment){if(Object.hasOwn(output,name)){fail6(`runtime environment cannot both export and unset ${name}`)}}for(const name of unsetNames){if(!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name)){fail6(`invalid runtime environment key ${JSON.stringify(name)}`)}}return{output,unsetNames:[...unsetNames].sort()}}function serializeManagedStartupCompletionMarker(marker){if(marker.schemaVersion!==MANAGED_STARTUP_COMPLETION_SCHEMA_VERSION||!MANAGED_STARTUP_AGENTS.includes(marker.agent)||!SHA256_RE4.test(marker.profileFingerprint)||!SHA256_RE4.test(marker.runtimeEnvironmentSha256)||typeof marker.corporateCaMerged!=="boolean"){fail6("managed startup completion marker is invalid")}return`${JSON.stringify({agent:marker.agent,corporateCaMerged:marker.corporateCaMerged,profileFingerprint:marker.profileFingerprint,runtimeEnvironmentSha256:marker.runtimeEnvironmentSha256,schemaVersion:marker.schemaVersion})} `}function publishManagedStartupImageCompletion(agent,profileFingerprint,runtimeEnvironment,corporateCaMerged,completionFile=MANAGED_STARTUP_COMPLETION_FILE){atomicWriteRootFile(completionFile,serializeManagedStartupCompletionMarker({schemaVersion:MANAGED_STARTUP_COMPLETION_SCHEMA_VERSION,agent,profileFingerprint,runtimeEnvironmentSha256:(0,import_node_crypto7.createHash)("sha256").update(runtimeEnvironment).digest("hex"),corporateCaMerged}),292)}function parseManagedStartupCompletionMarker(text){let parsed;try{parsed=JSON.parse(text)}catch{fail6("managed startup completion marker is not valid JSON")}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){fail6("managed startup completion marker must be an object")}const record2=parsed;const expectedKeys=["agent","corporateCaMerged","profileFingerprint","runtimeEnvironmentSha256","schemaVersion"];if(Object.keys(record2).sort().join(",")!==expectedKeys.sort().join(",")||record2.schemaVersion!==MANAGED_STARTUP_COMPLETION_SCHEMA_VERSION||typeof record2.agent!=="string"||!MANAGED_STARTUP_AGENTS.includes(record2.agent)||typeof record2.profileFingerprint!=="string"||!SHA256_RE4.test(record2.profileFingerprint)||typeof record2.runtimeEnvironmentSha256!=="string"||!SHA256_RE4.test(record2.runtimeEnvironmentSha256)||typeof record2.corporateCaMerged!=="boolean"){fail6("managed startup completion marker has an invalid schema")}const marker={schemaVersion:MANAGED_STARTUP_COMPLETION_SCHEMA_VERSION,agent:record2.agent,profileFingerprint:record2.profileFingerprint,runtimeEnvironmentSha256:record2.runtimeEnvironmentSha256,corporateCaMerged:record2.corporateCaMerged};if(serializeManagedStartupCompletionMarker(marker)!==text){fail6("managed startup completion marker is not canonical")}return marker}function verifyManagedStartupImageCompletion(expectedAgentInput,expectedFingerprint,completionFile=MANAGED_STARTUP_COMPLETION_FILE,runtimeEnvironmentFile=MANAGED_STARTUP_RUNTIME_ENV_FILE){const exchangeDirectory=import_node_path3.default.dirname(completionFile);if(import_node_path3.default.dirname(runtimeEnvironmentFile)!==exchangeDirectory){fail6("managed startup handoff files must share one exchange directory")}requireManagedStartupExchangeDirectory(exchangeDirectory);const expectedAgent=exactAgent2(expectedAgentInput);if(!SHA256_RE4.test(expectedFingerprint)){fail6("startup completion expected profile fingerprint is invalid")}const{bytes,stat}=readStableRegularFileSnapshot(completionFile,MAX_MANAGED_STARTUP_COMPLETION_BYTES);if(stat.nlink!==1n||stat.uid!==0n||stat.gid!==0n||Number(stat.mode&0o777n)!==292){fail6("managed startup completion marker must be root:root mode 0444")}const marker=parseManagedStartupCompletionMarker(bytes.toString("utf8"));if(marker.agent!==expectedAgent||marker.profileFingerprint!==expectedFingerprint){fail6("managed startup completion marker does not match the requested profile")}const runtimeEnvironment=readStableRegularFileSnapshot(runtimeEnvironmentFile,MAX_MANAGED_STARTUP_RUNTIME_ENVIRONMENT_BYTES);if(runtimeEnvironment.stat.nlink!==1n||runtimeEnvironment.stat.uid!==0n||runtimeEnvironment.stat.gid!==0n||Number(runtimeEnvironment.stat.mode&0o777n)!==292){fail6("managed startup runtime environment must be root:root mode 0444")}const runtimeEnvironmentSha256=(0,import_node_crypto7.createHash)("sha256").update(runtimeEnvironment.bytes).digest("hex");if(runtimeEnvironmentSha256!==marker.runtimeEnvironmentSha256){fail6("managed startup completion marker runtime environment digest mismatch")}return{agent:expectedAgent,fingerprint:expectedFingerprint}}function waitForManagedStartupImageCompletion(expectedAgentInput,expectedFingerprint,timeoutSeconds=600){if(!Number.isSafeInteger(timeoutSeconds)||timeoutSeconds<1||timeoutSeconds>3600){fail6("startup completion wait timeout must be an integer from 1 to 3600 seconds")}const deadline=Date.now()+timeoutSeconds*1e3;while(true){try{return verifyManagedStartupImageCompletion(expectedAgentInput,expectedFingerprint)}catch(error){if(error.code!=="ENOENT")throw error;if(Date.now()>=deadline){fail6(`startup completion was not published within ${String(timeoutSeconds)} seconds`)}Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,250)}}}function publishManagedStartupCompletionAfterCommit(expectedAgentInput,expectedFingerprint,bootstrapIdentity,completionFile=MANAGED_STARTUP_COMPLETION_FILE,runtimeEnvironmentFile=MANAGED_STARTUP_RUNTIME_ENV_FILE){requireRoot();requireManagedStartupExchangeDirectory();const expectedAgent=exactAgent2(expectedAgentInput);if(getManagedStartupSharedStateTransactionStatus({agent:expectedAgent,profileFingerprint:expectedFingerprint,bootstrapIdentity})!=="committed"){fail6("managed startup completion requires a committed shared-state transaction")}try{verifyManagedStartupImageCompletion(expectedAgent,expectedFingerprint,completionFile,runtimeEnvironmentFile);return}catch(error){if(error.code!=="ENOENT")throw error}const runtimeEnvironment=readStableRegularFileSnapshot(runtimeEnvironmentFile,MAX_MANAGED_STARTUP_RUNTIME_ENVIRONMENT_BYTES);if(runtimeEnvironment.stat.nlink!==1n||runtimeEnvironment.stat.uid!==0n||runtimeEnvironment.stat.gid!==0n||Number(runtimeEnvironment.stat.mode&0o777n)!==292){fail6("managed startup runtime environment must be root:root mode 0444")}const corporateCaMerged=runtimeEnvironment.bytes.toString("utf8").split("\n").includes("export _NEMOCLAW_CORPORATE_CA_MERGED='1'");publishManagedStartupImageCompletion(expectedAgent,expectedFingerprint,runtimeEnvironment.bytes,corporateCaMerged,completionFile);verifyManagedStartupImageCompletion(expectedAgent,expectedFingerprint,completionFile,runtimeEnvironmentFile)}function applyAdapter(context,mapped){if(mapped.agent!==context.agent){fail6(`mapped ${mapped.agent} environment for ${context.agent}`)}if(context.agent==="openclaw"){execute(["/usr/local/bin/node","/usr/local/lib/nemoclaw/openclaw-legacy-migrations.mts","--wait-gateway-executable","/usr/local/bin/openclaw","2026.10.5"],"sandbox",mapped.configurationEnvironment,mapped.applicationRuntime)}const commandPlan=buildManagedStartupImageActionPlan({agent:mapped.agent,actions:mapped.actions});let commandIndex=0;for(const action of mapped.actions){if(action.kind==="configure-dashboard")continue;const command=commandPlan[commandIndex];if(!command)fail6(`missing image command for ${action.kind}`);commandIndex+=1;if(action.kind==="apply-messaging-plan"){if(action.phase==="runtime-setup"){prepareMessagingRuntimeTarget(action.mode)}execute(command.argv,command.runAs,mapped.configurationEnvironment,mapped.applicationRuntime);if(action.phase==="runtime-setup"){verifyMessagingRuntimeTarget(action.mode)}continue}execute(command.argv,command.runAs,mapped.configurationEnvironment,mapped.applicationRuntime)}if(commandIndex!==commandPlan.length){fail6("image action plan contains an unmatched command")}switch(context.agent){case"openclaw":validateOpenClawConfiguration(mapped.configurationEnvironment,mapped.applicationRuntime);break;case"hermes":installHermesManagedPolicy();installHermesSwitchyardRoutingFiles(mapped.configurationEnvironment);sealHermesConfiguration(mapped.configurationEnvironment,mapped.applicationRuntime);normalizeHermesManagedConfiguration();break;case"langchain-deepagents-code":break}installRootOwnedMaterials(mapped.materials);installCorporateCa(context.corporateCaPath);installCorporateCaSystemAnchors(context.corporateCaPath);mergeCorporateCa(context.corporateCaPath)}function adapters(mapped){return MANAGED_STARTUP_AGENTS.map(agent=>({agent,apply:context=>applyAdapter(context,mapped)}))}async function applyManagedStartupImageProfile(expectedAgentInput,env=process.env,options={}){requireRoot();const expectedAgent=exactAgent2(expectedAgentInput);if(env.NEMOCLAW_MANAGED_IMAGE_CAPABILITY_UNION!=="1"){fail6("startup profiles require a complete managed image")}const encodedProfile=env[MANAGED_STARTUP_PROFILE_ENV];if(!encodedProfile)fail6(`${MANAGED_STARTUP_PROFILE_ENV} is required`);let profile;try{profile=decodeManagedStartupProfile(encodedProfile)}catch(error){fail6(error.message)}if(profile.agent!==expectedAgent){fail6(`managed startup profile targets ${profile.agent}, expected ${expectedAgent}`)}if(profile.agentConfig.agent==="hermes"&&profile.agentConfig.switchyardRouting){if(!profile.agentConfig.switchyardBindings)fail6("Switchyard provider bindings are missing");assertSwitchyardRootApplyEnvironment(env,{routing:profile.agentConfig.switchyardRouting,bindings:profile.agentConfig.switchyardBindings})}requireManagedStartupExchangeDirectory();const mapped=mapManagedStartupProfileToAgentEnvironment(profile,env);validateManagedStartupApplicationRuntimePlan(mapped.applicationRuntime);ensureRootOwnedDirectory(ROOT_STATE_PARENT);ensureRootOwnedDirectory(ROOT_RUNTIME_DIRECTORY);const result=await coordinateManagedStartupApplication({encodedProfile,expectedAgent,...env[MANAGED_STARTUP_CA_ENV]===void 0?{}:{corporateCaB64:env[MANAGED_STARTUP_CA_ENV]}},adapters(mapped));if(mapped.agent!==result.application.profile.agent){fail6(`mapped ${mapped.agent} environment for ${result.application.profile.agent}`)}if(expectedAgent==="hermes"&&!result.adapterApplied){normalizeHermesManagedConfiguration();verifyHermesSwitchyardRoutingFiles(mapped.configurationEnvironment)}let corporateCaMerged;if(result.adapterApplied){corporateCaMerged=result.application.corporateCaPath!==null}else{verifyRootOwnedMaterials(mapped.materials);if(result.application.corporateCaPath===null){if(managed_startup_filesystem_default.existsSync(MANAGED_STARTUP_CORPORATE_CA_FILE)){fail6("committed profile without a corporate CA has a stale CA material")}}else{const expected=readStableRegularFile(result.application.corporateCaPath,128*1024);const installed=readStableRegularFile(MANAGED_STARTUP_CORPORATE_CA_FILE,128*1024);if(!expected.equals(installed)){fail6("committed corporate CA material drifted")}}installCorporateCaSystemAnchors(result.application.corporateCaPath);corporateCaMerged=mergeCorporateCa(result.application.corporateCaPath)}const runtimeEnvironment=serializeManagedStartupRuntimeEnvironment(mapped.runtimeEnvironment,corporateCaMerged,mapped.configurationEnvironment,mapped.applicationRuntime);atomicWriteRootFile(MANAGED_STARTUP_RUNTIME_ENV_FILE,runtimeEnvironment,292);if(options.publishCompletion!==false){publishManagedStartupImageCompletion(expectedAgent,result.application.fingerprint,runtimeEnvironment,corporateCaMerged)}return{agent:expectedAgent,adapterApplied:result.adapterApplied,fingerprint:result.application.fingerprint,runtimeEnvironmentFile:MANAGED_STARTUP_RUNTIME_ENV_FILE}}function completionAlreadyPublished(request){try{verifyManagedStartupImageCompletion(request.agent,request.profileFingerprint);return true}catch(error){if(error.code==="ENOENT")return false;throw error}}async function applyManagedStartupRootRequest(request,env=process.env,options={}){requireRoot();const profile=decodeManagedStartupProfile(request.encodedProfile);if(profile.agent!==request.agent||fingerprintManagedStartupProfile(profile)!==request.profileFingerprint){fail6("root application request identity does not match its profile")}const imageEnvironment={HOME:"/root",PATH:FIXED_PATH,NEMOCLAW_MANAGED_IMAGE_CAPABILITY_UNION:"1",...selectManagedStartupApplicationRuntimeEnvironment(env),[MANAGED_STARTUP_PROFILE_ENV]:request.encodedProfile,...request.corporateCaB64===null?{}:{[MANAGED_STARTUP_CA_ENV]:request.corporateCaB64}};mapManagedStartupProfileToAgentEnvironment(profile,imageEnvironment);normalizeManagedStartupWorkspaceRoot(request.agent);const alreadyPublished=completionAlreadyPublished(request);const bootstrapIdentity=options.bootstrapIdentity??null;const transactionStatus=alreadyPublished&&bootstrapIdentity!==null?getManagedStartupSharedStateTransactionStatus({agent:request.agent,profileFingerprint:request.profileFingerprint,bootstrapIdentity}):null;if(transactionStatus==="none"){fail6("completed startup profile has no shared-state authority for this bootstrap attempt")}if(!alreadyPublished){ensureRootOwnedDirectory(ROOT_STATE_PARENT);beginManagedStartupSharedStateTransaction(profile,{bootstrapIdentity})}const result=await applyManagedStartupImageProfile(request.agent,imageEnvironment,{publishCompletion:bootstrapIdentity===null||alreadyPublished});return{...result,transactionPending:!alreadyPublished||transactionStatus==="pending"}}function readBoundedRootApplyStdin(){const chunks=[];let total=0;while(true){const chunk=Buffer.alloc(16*1024);const read=managed_startup_filesystem_default.readSync(0,chunk,0,chunk.length,null);if(read===0)break;total+=read;if(total>MANAGED_STARTUP_ROOT_APPLY_MAX_BYTES){fail6("root application stdin exceeds its bounded transport")}chunks.push(chunk.subarray(0,read))}const bytes=Buffer.concat(chunks,total);const text=bytes.toString("utf8");if(text.includes("\0")||!Buffer.from(text,"utf8").equals(bytes)){fail6("root application stdin must be valid UTF-8 without NUL bytes")}return text}function writeSandboxFileAtomically(target2,contents,mode){const parent=import_node_path3.default.dirname(target2);const parentStat=managed_startup_filesystem_default.lstatSync(parent);if(parentStat.isSymbolicLink()||!parentStat.isDirectory()||parentStat.uid!==process.geteuid?.()||parentStat.gid!==process.getegid?.()){fail6(`refusing unsafe sandbox-owned directory ${parent}`)}const temporary=import_node_path3.default.join(parent,`.${import_node_path3.default.basename(target2)}.${(0,import_node_crypto7.randomBytes)(12).toString("hex")}`);let descriptor;try{descriptor=managed_startup_filesystem_default.openSync(temporary,managed_startup_filesystem_default.constants.O_CREAT|managed_startup_filesystem_default.constants.O_EXCL|managed_startup_filesystem_default.constants.O_WRONLY|managed_startup_filesystem_default.constants.O_NOFOLLOW,384);managed_startup_filesystem_default.writeFileSync(descriptor,contents);managed_startup_filesystem_default.fchmodSync(descriptor,mode);managed_startup_filesystem_default.fsyncSync(descriptor);managed_startup_filesystem_default.closeSync(descriptor);descriptor=void 0;managed_startup_filesystem_default.renameSync(temporary,target2)}catch(error){if(descriptor!==void 0)managed_startup_filesystem_default.closeSync(descriptor);try{managed_startup_filesystem_default.unlinkSync(temporary)}catch{}fail6(`could not write sandbox-owned file ${target2}: ${error.message}`)}}function internalWriteHermesCompatHash(){if(process.geteuid?.()===0)fail6("sandbox hash writer must not run as root");const encoded=process.env.NEMOCLAW_MANAGED_HERMES_HASH_B64??"";if(encoded.length===0||encoded.length>4096||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(encoded)){fail6("Hermes compatibility hash transport is invalid")}const decoded=Buffer.from(encoded,"base64");if(decoded.toString("base64")!==encoded){fail6("Hermes compatibility hash transport is non-canonical")}writeSandboxFileAtomically("/sandbox/.hermes/.config-hash",decoded.toString("utf8"),416)}function readCliAgent(argv,expectedLength=2){const index=argv.indexOf("--agent");if(index<0||index+1>=argv.length||argv.length!==expectedLength){fail6("usage: managed-startup-image-runtime [--apply-root-stdin|--release-startup-hold|--wait-for-completion|--verify-completion|--begin-shared-state-transaction|--commit-shared-state-transaction|--rollback-shared-state-transaction|--clear-shared-state-commit-receipt|--shared-state-transaction-status] --agent ")}return argv[index+1]}function readCliFingerprint(argv){const index=argv.indexOf("--profile-fingerprint");if(index<0||index+1>=argv.length){fail6("managed startup profile fingerprint argument is missing")}return argv[index+1]}function readCliBootstrapIdentity(argv){const index=argv.indexOf("--bootstrap-identity");if(index<0||index+1>=argv.length||!SHA256_RE4.test(String(argv[index+1]??""))){fail6("managed bootstrap identity argument is missing or invalid")}return argv[index+1]}async function main(argv=process.argv.slice(2)){if(argv.length===1&&argv[0]==="--internal-write-hermes-compat-hash"){internalWriteHermesCompatHash();return}if((argv.length===3||argv.length===5)&&argv[0]==="--apply-root-stdin"){const expectedAgent=exactAgent2(readCliAgent(argv,argv.length));const request=parseManagedStartupRootApplyRequest(readBoundedRootApplyStdin());if(request.agent!==expectedAgent){fail6(`root application request targets ${request.agent}, expected ${expectedAgent}`)}const result2=await applyManagedStartupRootRequest(request,process.env,{bootstrapIdentity:argv.length===5?readCliBootstrapIdentity(argv):null});console.log(result2.transactionPending?`[managed-startup] applied ${result2.agent} profile ${result2.fingerprint}; transaction pending`:`[managed-startup] ${result2.agent} profile ${result2.fingerprint} was already complete`);return}if(argv.length===7&&argv[0]==="--release-startup-hold"){const agent=readCliAgent(argv,7);const fingerprint=readCliFingerprint(argv);const bootstrapIdentity=readCliBootstrapIdentity(argv);publishManagedStartupCompletionAfterCommit(agent,fingerprint,bootstrapIdentity);console.log(`[managed-startup] released ${agent} profile ${fingerprint} startup hold`);return}if((argv.length===5||argv.length===7)&&(argv[0]==="--verify-completion"||argv[0]==="--wait-for-completion")){const agent=readCliAgent(argv,argv.length);const fingerprint=readCliFingerprint(argv);if(argv.length===7)readCliBootstrapIdentity(argv);const result2=argv[0]==="--wait-for-completion"?waitForManagedStartupImageCompletion(agent,fingerprint):verifyManagedStartupImageCompletion(agent,fingerprint);console.log(`[managed-startup] verified ${result2.agent} profile ${result2.fingerprint} completion`);return}if(argv.length===3&&argv[0]==="--begin-shared-state-transaction"){const profile=managedTransactionProfile(readCliAgent(argv,3));ensureRootOwnedDirectory(ROOT_STATE_PARENT);const created=beginManagedStartupSharedStateTransaction(profile);process.stdout.write(created?"created\n":"pending\n");return}if((argv.length===4||argv.length===6)&&argv[0]==="--rollback-shared-state-transaction"&&argv[argv.length-1]==="--read-only-receipt"){requireRoot();const agent=exactAgent2(readCliAgent(argv,argv.length));const rolledBack=rollbackManagedStartupSharedStateTransaction(agent,{transactionDirectory:MANAGED_STARTUP_SHARED_ROLLBACK_RECEIPT_DIRECTORY,readOnlyReceipt:true,bootstrapIdentity:argv.length===6?readCliBootstrapIdentity(argv):null});if(!rolledBack)fail6("read-only shared-state rollback receipt is missing");console.log(`[managed-startup] verified and restored ${agent} shared state`);return}if((argv.length===3||argv.length===5)&&argv[0]==="--rollback-shared-state-transaction"){requireRoot();const agent=exactAgent2(readCliAgent(argv,argv.length));const rolledBack=rollbackManagedStartupSharedStateTransaction(agent,{bootstrapIdentity:argv.length===5?readCliBootstrapIdentity(argv):null});if(!rolledBack)fail6("managed startup transaction is missing at rollback");console.log(`[managed-startup] verified and restored ${agent} shared state`);return}if((argv.length===3||argv.length===5)&&argv[0]==="--commit-shared-state-transaction"){requireRoot();const agent=exactAgent2(readCliAgent(argv,argv.length));if(!commitManagedStartupSharedStateTransaction(agent,{bootstrapIdentity:argv.length===5?readCliBootstrapIdentity(argv):null})){fail6("managed startup transaction is missing at commit")}console.log(`[managed-startup] committed ${agent} shared state`);return}if(argv.length===5&&argv[0]==="--clear-shared-state-commit-receipt"){requireRoot();const agent=exactAgent2(readCliAgent(argv,5));const bootstrapIdentity=readCliBootstrapIdentity(argv);if(!clearManagedStartupSharedStateCommitReceipt(agent,{bootstrapIdentity})){fail6("managed startup durable commit receipt is missing at cleanup")}console.log(`[managed-startup] cleared ${agent} durable shared-state commit receipt`);return}if(argv.length===7&&argv[0]==="--shared-state-transaction-status"){requireRoot();const agent=exactAgent2(readCliAgent(argv,7));const profileFingerprint=readCliFingerprint(argv);const bootstrapIdentity=readCliBootstrapIdentity(argv);process.stdout.write(`${getManagedStartupSharedStateTransactionStatus({agent,profileFingerprint,bootstrapIdentity})} diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index 4351058c95e..c156a43647a 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -13,30 +13,30 @@ }, "limits": { "testFileCount": 76, - "liveFileCount": 187, + "liveFileCount": 188, "direct": { "expectCalls": 1305, "matcherAssertions": 1290, "nodeAssertions": 109, - "namedAssertionHelpers": 433, + "namedAssertionHelpers": 434, "failCalls": 0, "throwGuards": 50, "objectFieldAssertions": 184, - "assertionPoints": 2066, + "assertionPoints": 2067, "generatedProbeBlocks": 91, "generatedProbeConditions": 214 }, "unique": { - "expectCalls": 1732, - "matcherAssertions": 1712, + "expectCalls": 1737, + "matcherAssertions": 1717, "nodeAssertions": 132, - "namedAssertionHelpers": 680, + "namedAssertionHelpers": 686, "failCalls": 1, - "throwGuards": 531, + "throwGuards": 533, "objectFieldAssertions": 266, - "assertionPoints": 3322, - "generatedProbeBlocks": 220, - "generatedProbeConditions": 726 + "assertionPoints": 3335, + "generatedProbeBlocks": 221, + "generatedProbeConditions": 727 }, "fileMetricOrder": [ "directExpectCalls", @@ -84,7 +84,7 @@ "test/e2e/live/managed-image-activation-e2e.test.ts": [0,0,12,25,0], "test/e2e/live/managed-image-multiarch-startup.test.ts": [1,3,1,9,0], "test/e2e/live/managed-image-protected-runtime.test.ts": [0,0,39,81,16], - "test/e2e/live/mcp-bridge.test.ts": [39,138,193,518,46], + "test/e2e/live/mcp-bridge.test.ts": [39,139,198,531,47], "test/e2e/live/messaging-compatible-endpoint.test.ts": [13,19,13,28,2], "test/e2e/live/messaging-providers.test.ts": [0,11,6,51,11], "test/e2e/live/native-runtime-qualification-case.test.ts": [0,0,9,84,0], diff --git a/ci/e2e-assertion-growth-exceptions.json b/ci/e2e-assertion-growth-exceptions.json index e3b1220ea2b..49a2122d3ae 100644 --- a/ci/e2e-assertion-growth-exceptions.json +++ b/ci/e2e-assertion-growth-exceptions.json @@ -1,5 +1,5 @@ { - "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12718 is the prerequisite for the PR #12382 budget transition recorded below. The exception matches only PR #12382 and both budget digests. A changed base or candidate budget invalidates it. The independent check reads trusted base policy, so this prerequisite must land on main before #12382 uses the exception. Remove after #12382 merges.\n\nMaintainer Prekshi Vyas (@prekshivyas) approved this exact refreshed PR #12382 transition on 2026-10-08: base budget SHA-256 53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441 to candidate budget SHA-256 8162408384d7a6b97ef0062042c73d4bc9486f54d2dfa6c0c5732e42d1060e2a. Acceptance record: https://github.com/NVIDIA/NemoClaw/pull/12840#issuecomment-6066319444. It includes one additional unique assertion point and one generated probe condition. This refresh preserves the #12608 concurrent-gateway-ports reduction and the previously reviewed runtime assertion changes. The independent check is not waived: the refreshed exception must land on main before enforcement can accept it. A different PR or budget digest remains rejected. Remove after #12382 merges.\n\nPR #12777 adds exactly two approved live assertions for native host-local inference success and sibling provider isolation. Deterministic behavior remains in unit/integration tests. Approval transcription: https://github.com/NVIDIA/NemoClaw/pull/12777#issuecomment-6048385152. The independent check reads trusted base policy; this entry does not disable it. Remove after #12777 merges.\n\nThe #12777 budget digests account for main #12608 removing seven assertions from concurrent-gateway-ports. The candidate preserves that reduction and adds only the same two approved inference-routing assertions. No other file budget increases.\n\nPR #12886 approved the provider-smoke transition extracted by #12955. Approval: https://github.com/NVIDIA/NemoClaw/pull/12886#issuecomment-6083839176. The unchanged change digest binds the same nine assertion points and companion inventory. This entry supports local preliminary validation and the Slice 2 consumer. Independent CI for the prerequisite requires its own maintainer approval record; this entry does not approve that PR.\n\nPR #12958 extracts the same approved provider-smoke budget transition for #12955. Its exact, unedited maintainer approval is https://github.com/NVIDIA/NemoClaw/pull/12958#issuecomment-6093851571. This candidate entry supports static hooks; the independent check continues to verify the PR-specific approval on GitHub. Remove after #12958 merges.\n\nPR #13203 adds the approved 19 assertion points for real authenticated and credentialless DCode native-local requests, credential isolation and sibling denial. Approval: https://github.com/NVIDIA/NemoClaw/pull/13203#issuecomment-6180239679. This exact change digest supports local hooks and candidate CI. Independent enforcement still verifies the PR-specific maintainer approval on GitHub. Remove after #13203 merges.\n\nPR #13201 adds one generated probe block and one counted probe condition in the existing full E2E owner to verify the selected sandbox agent endpoint, API, model and credential reference. Rebecca Sliter approved this exact delta: https://github.com/NVIDIA/NemoClaw/pull/13201#issuecomment-6180464605. This entry supports local validation; the independent check must verify the maintainer record. Remove after #13201 merges.\n\nPR #13293 consolidates OpenClaw native-local scenarios into the existing switching owner and removes duplicated deterministic metadata checks and the redundant mock curl probe. Suite totals fall by 16 expect calls and 10 assertion points without adding live files. Only the owning file transitive allocation grows because it now imports existing live helpers. Maintainer authorization: https://github.com/NVIDIA/NemoClaw/pull/13293#issuecomment-6211036786. This exact transition supports candidate CI; independent enforcement still verifies the maintainer record.\n\nPR #13007 retains the same ten Pi native-local live assertion points approved at https://github.com/NVIDIA/NemoClaw/pull/13007#issuecomment-6175787892. The exact change digest is unchanged against its replacement OpenClaw parent #13293. This entry supports local checks against that stacked base; independent enforcement still checks the authenticated PR approval.\n\nPR #13582 adds eight live assertion points for the WSL2 IPv6 native-local policy boundary. Only openclaw-inference-switch.test.ts increases, by seven direct expectations and the existing onboard-success helper. Deterministic CIDR and receipt coverage remain in source tests. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13582#issuecomment-6308860348. Independent enforcement verifies that PR-specific record. Remove this preliminary local exception after merge.\n\nPR #13645 adds three approved live assertion points for engine-down uninstall diagnostics inside rebuild-openclaw. Exact approval: https://github.com/NVIDIA/NemoClaw/pull/13645#issuecomment-6429899630. This entry enables candidate CI; independent enforcement still verifies the PR-specific maintainer record. Remove after merge.\n\nPR #13771 adds four Hermes OpenRouter rebuild assertions and a bounded diagnostic probe. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13771#issuecomment-6427647915. The independent PR check verifies that comment. Remove after #13771 merges.\n\nPR #13873 adds two live command assertions for the CLI build and native Hermes Discord qualification when consuming protected evidence from an older trusted producer. Approval: https://github.com/NVIDIA/NemoClaw/pull/13873#issuecomment-6488667052. The parser and identity cases stay in e2e-support tests. Remove after #13873 merges.\n\nPR #13651 moves the native NVIDIA Discord rebuild proof from hermes-discord to hermes-inference-switch, which receives the public endpoint credential. The native switch target also checks status through its installed credential verifier after rebuild. This adds four assertion points for the live status and restored-provider boundary; deterministic rejection and command-failure cases remain in fast tests. This entry permits the approved transition in local and candidate checks; independent enforcement verifies the maintainer record at https://github.com/NVIDIA/NemoClaw/pull/13651#issuecomment-6377201610. The typed helper extraction retains every live predicate and the same unique and transitive totals; the direct census decreases because the phase now lives in the existing helper.\n\nPR #13635 adds the approved protected-runtime deadline companion and five unique assertion points, one generated probe block, and one probe condition. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13635#issuecomment-6383152261. This entry supports local hooks and candidate CI; independent enforcement verifies the PR-specific GitHub approval. Remove after #13635 merges.\n\nPR #13596 adds four live assertion points to the existing double-onboard target for #13595: the managed OpenClaw state volume exists before `nemoclaw uninstall`, uninstall succeeds, the volume is gone afterwards, and same-name onboarding succeeds. Deterministic removal and failure cases remain in fast tests. This entry permits the approved transition in local and candidate checks; independent enforcement verifies the maintainer record at https://github.com/NVIDIA/NemoClaw/pull/13596#issuecomment-6365742624. Remove after #13596 merges.\n\nPR #13515 extends dashboard-remote-bind with Hermes host-listener coverage. The dashboard remains remotely reachable, API health works on loopback, and the non-loopback API port refuses TCP connections. Approval: https://github.com/NVIDIA/NemoClaw/pull/13515#issuecomment-6295553350. This entry supports local and candidate checks; independent enforcement verifies the authenticated maintainer record.\n\nPR #13515 also checks Hermes loopback API health and non-loopback refusal after stop/start, preserving the onboarding assertions. The combined delta is approved at https://github.com/NVIDIA/NemoClaw/pull/13515#issuecomment-6298021751.\n\nPR #13515 verifies the Hermes API forward identity before health probes after onboarding and restart. These two additional process-ownership assertions are approved at https://github.com/NVIDIA/NemoClaw/pull/13515#issuecomment-6322568985.\n\nPR #13927 reuses the verified public HTTPS fixture transport for two Podman inference targets. Direct and unique assertion counts are unchanged. Each target gains eleven transitive assertion points from existing package and tunnel prerequisites; the extracted Anthropic response helper adds one live companion file. This exact transition supports local validation. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13927#issuecomment-6524030655. Independent enforcement verifies this PR-specific record. Remove after merge.\n\nPR #14062 adds one live Ollama cleanup helper, three existing port-validation guards reached by gpu-double-onboard, and one shared shell probe. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14062#issuecomment-6582340290. This entry supports local hooks and candidate CI; independent enforcement verifies the PR-specific approval. Remove after merge.\n\nPR #13607 adds two live assertions and one read-only configuration probe to the existing balanced OpenClaw egress case for unavailable-search replies. The refreshed delta removes the unrelated public-fetch precondition guard while retaining both live assertions and the probe. Approved delta: https://github.com/NVIDIA/NemoClaw/pull/13607#issuecomment-6327887365. Remove after #13607 merges.\n\nPR #14000 replaces #12872 and retains one approved assertion point for owning-gateway connect sessions. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14000#issuecomment-6506269922. This entry enables candidate CI; independent enforcement verifies the PR-specific approval.\n\nPR #14122 retains the production bearerless provider-validation proof and private-publication proof in both Express targets. Spark and Station each request health on the two allowed addresses and require connection refusal on all discovered unintended addresses. Four added Spark assertions protect its separate physical-host path; deterministic URL construction remains in the support tests. The combined delta adds seven assertion points and one generated probe relative to main. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14122#issuecomment-6661407269. Independent enforcement verifies this PR-specific approval. Remove after merge.\n\nPR #14252 adds twelve live assertion points to the existing sandbox-survival owner for first-invocation cold public OpenClaw recovery, native and forwarded health, and retained sandbox/container identities on Docker and native Podman. Existing raw OpenShell survival evidence and target timeouts are unchanged. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14252#issuecomment-6676328443. This entry supports local and candidate checks; independent enforcement verifies the PR-specific approval record. Remove after merge.\n\nPR #14303 replaces #14201 and retains its two assertion points in hermes-root-entrypoint-smoke for qualification through the real entrypoint before gateway readiness. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14303#issuecomment-6713570086. This entry supports local hooks and candidate CI. Independent enforcement still verifies the PR-specific maintainer record. Remove after merge.", + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12718 is the prerequisite for the PR #12382 budget transition recorded below. The exception matches only PR #12382 and both budget digests. A changed base or candidate budget invalidates it. The independent check reads trusted base policy, so this prerequisite must land on main before #12382 uses the exception. Remove after #12382 merges.\n\nMaintainer Prekshi Vyas (@prekshivyas) approved this exact refreshed PR #12382 transition on 2026-10-08: base budget SHA-256 53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441 to candidate budget SHA-256 8162408384d7a6b97ef0062042c73d4bc9486f54d2dfa6c0c5732e42d1060e2a. Acceptance record: https://github.com/NVIDIA/NemoClaw/pull/12840#issuecomment-6066319444. It includes one additional unique assertion point and one generated probe condition. This refresh preserves the #12608 concurrent-gateway-ports reduction and the previously reviewed runtime assertion changes. The independent check is not waived: the refreshed exception must land on main before enforcement can accept it. A different PR or budget digest remains rejected. Remove after #12382 merges.\n\nPR #12777 adds exactly two approved live assertions for native host-local inference success and sibling provider isolation. Deterministic behavior remains in unit/integration tests. Approval transcription: https://github.com/NVIDIA/NemoClaw/pull/12777#issuecomment-6048385152. The independent check reads trusted base policy; this entry does not disable it. Remove after #12777 merges.\n\nThe #12777 budget digests account for main #12608 removing seven assertions from concurrent-gateway-ports. The candidate preserves that reduction and adds only the same two approved inference-routing assertions. No other file budget increases.\n\nPR #12886 approved the provider-smoke transition extracted by #12955. Approval: https://github.com/NVIDIA/NemoClaw/pull/12886#issuecomment-6083839176. The unchanged change digest binds the same nine assertion points and companion inventory. This entry supports local preliminary validation and the Slice 2 consumer. Independent CI for the prerequisite requires its own maintainer approval record; this entry does not approve that PR.\n\nPR #12958 extracts the same approved provider-smoke budget transition for #12955. Its exact, unedited maintainer approval is https://github.com/NVIDIA/NemoClaw/pull/12958#issuecomment-6093851571. This candidate entry supports static hooks; the independent check continues to verify the PR-specific approval on GitHub. Remove after #12958 merges.\n\nPR #13203 adds the approved 19 assertion points for real authenticated and credentialless DCode native-local requests, credential isolation and sibling denial. Approval: https://github.com/NVIDIA/NemoClaw/pull/13203#issuecomment-6180239679. This exact change digest supports local hooks and candidate CI. Independent enforcement still verifies the PR-specific maintainer approval on GitHub. Remove after #13203 merges.\n\nPR #13201 adds one generated probe block and one counted probe condition in the existing full E2E owner to verify the selected sandbox agent endpoint, API, model and credential reference. Rebecca Sliter approved this exact delta: https://github.com/NVIDIA/NemoClaw/pull/13201#issuecomment-6180464605. This entry supports local validation; the independent check must verify the maintainer record. Remove after #13201 merges.\n\nPR #13293 consolidates OpenClaw native-local scenarios into the existing switching owner and removes duplicated deterministic metadata checks and the redundant mock curl probe. Suite totals fall by 16 expect calls and 10 assertion points without adding live files. Only the owning file transitive allocation grows because it now imports existing live helpers. Maintainer authorization: https://github.com/NVIDIA/NemoClaw/pull/13293#issuecomment-6211036786. This exact transition supports candidate CI; independent enforcement still verifies the maintainer record.\n\nPR #13007 retains the same ten Pi native-local live assertion points approved at https://github.com/NVIDIA/NemoClaw/pull/13007#issuecomment-6175787892. The exact change digest is unchanged against its replacement OpenClaw parent #13293. This entry supports local checks against that stacked base; independent enforcement still checks the authenticated PR approval.\n\nPR #13582 adds eight live assertion points for the WSL2 IPv6 native-local policy boundary. Only openclaw-inference-switch.test.ts increases, by seven direct expectations and the existing onboard-success helper. Deterministic CIDR and receipt coverage remain in source tests. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13582#issuecomment-6308860348. Independent enforcement verifies that PR-specific record. Remove this preliminary local exception after merge.\n\nPR #13645 adds three approved live assertion points for engine-down uninstall diagnostics inside rebuild-openclaw. Exact approval: https://github.com/NVIDIA/NemoClaw/pull/13645#issuecomment-6429899630. This entry enables candidate CI; independent enforcement still verifies the PR-specific maintainer record. Remove after merge.\n\nPR #13771 adds four Hermes OpenRouter rebuild assertions and a bounded diagnostic probe. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13771#issuecomment-6427647915. The independent PR check verifies that comment. Remove after #13771 merges.\n\nPR #13873 adds two live command assertions for the CLI build and native Hermes Discord qualification when consuming protected evidence from an older trusted producer. Approval: https://github.com/NVIDIA/NemoClaw/pull/13873#issuecomment-6488667052. The parser and identity cases stay in e2e-support tests. Remove after #13873 merges.\n\nPR #13651 moves the native NVIDIA Discord rebuild proof from hermes-discord to hermes-inference-switch, which receives the public endpoint credential. The native switch target also checks status through its installed credential verifier after rebuild. This adds four assertion points for the live status and restored-provider boundary; deterministic rejection and command-failure cases remain in fast tests. This entry permits the approved transition in local and candidate checks; independent enforcement verifies the maintainer record at https://github.com/NVIDIA/NemoClaw/pull/13651#issuecomment-6377201610. The typed helper extraction retains every live predicate and the same unique and transitive totals; the direct census decreases because the phase now lives in the existing helper.\n\nPR #13635 adds the approved protected-runtime deadline companion and five unique assertion points, one generated probe block, and one probe condition. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13635#issuecomment-6383152261. This entry supports local hooks and candidate CI; independent enforcement verifies the PR-specific GitHub approval. Remove after #13635 merges.\n\nPR #13596 adds four live assertion points to the existing double-onboard target for #13595: the managed OpenClaw state volume exists before `nemoclaw uninstall`, uninstall succeeds, the volume is gone afterwards, and same-name onboarding succeeds. Deterministic removal and failure cases remain in fast tests. This entry permits the approved transition in local and candidate checks; independent enforcement verifies the maintainer record at https://github.com/NVIDIA/NemoClaw/pull/13596#issuecomment-6365742624. Remove after #13596 merges.\n\nPR #13515 extends dashboard-remote-bind with Hermes host-listener coverage. The dashboard remains remotely reachable, API health works on loopback, and the non-loopback API port refuses TCP connections. Approval: https://github.com/NVIDIA/NemoClaw/pull/13515#issuecomment-6295553350. This entry supports local and candidate checks; independent enforcement verifies the authenticated maintainer record.\n\nPR #13515 also checks Hermes loopback API health and non-loopback refusal after stop/start, preserving the onboarding assertions. The combined delta is approved at https://github.com/NVIDIA/NemoClaw/pull/13515#issuecomment-6298021751.\n\nPR #13515 verifies the Hermes API forward identity before health probes after onboarding and restart. These two additional process-ownership assertions are approved at https://github.com/NVIDIA/NemoClaw/pull/13515#issuecomment-6322568985.\n\nPR #13927 reuses the verified public HTTPS fixture transport for two Podman inference targets. Direct and unique assertion counts are unchanged. Each target gains eleven transitive assertion points from existing package and tunnel prerequisites; the extracted Anthropic response helper adds one live companion file. This exact transition supports local validation. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13927#issuecomment-6524030655. Independent enforcement verifies this PR-specific record. Remove after merge.\n\nPR #14062 adds one live Ollama cleanup helper, three existing port-validation guards reached by gpu-double-onboard, and one shared shell probe. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14062#issuecomment-6582340290. This entry supports local hooks and candidate CI; independent enforcement verifies the PR-specific approval. Remove after merge.\n\nPR #13607 adds two live assertions and one read-only configuration probe to the existing balanced OpenClaw egress case for unavailable-search replies. The refreshed delta removes the unrelated public-fetch precondition guard while retaining both live assertions and the probe. Approved delta: https://github.com/NVIDIA/NemoClaw/pull/13607#issuecomment-6327887365. Remove after #13607 merges.\n\nPR #14000 replaces #12872 and retains one approved assertion point for owning-gateway connect sessions. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14000#issuecomment-6506269922. This entry enables candidate CI; independent enforcement verifies the PR-specific approval.\n\nPR #14122 retains the production bearerless provider-validation proof and private-publication proof in both Express targets. Spark and Station each request health on the two allowed addresses and require connection refusal on all discovered unintended addresses. Four added Spark assertions protect its separate physical-host path; deterministic URL construction remains in the support tests. The combined delta adds seven assertion points and one generated probe relative to main. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14122#issuecomment-6661407269. Independent enforcement verifies this PR-specific approval. Remove after merge.\n\nPR #14252 adds twelve live assertion points to the existing sandbox-survival owner for first-invocation cold public OpenClaw recovery, native and forwarded health, and retained sandbox/container identities on Docker and native Podman. Existing raw OpenShell survival evidence and target timeouts are unchanged. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14252#issuecomment-6676328443. This entry supports local and candidate checks; independent enforcement verifies the PR-specific approval record. Remove after merge.\n\nPR #14303 replaces #14201 and retains its two assertion points in hermes-root-entrypoint-smoke for qualification through the real entrypoint before gateway readiness. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14303#issuecomment-6713570086. This entry supports local hooks and candidate CI. Independent enforcement still verifies the PR-specific maintainer record. Remove after merge.\n\nPR #14517 adds the required real shared-host MCP policy and credential composition proof: distinct paths and credentials, differing add-time DNS inputs, strict out-of-binding denial, and owned cleanup. The approved delta adds 13 unique assertion points and one companion file. Approval: https://github.com/NVIDIA/NemoClaw/pull/14517#issuecomment-6942719509. This branch entry supports preliminary local and candidate checks; independent enforcement verifies the recorded approval. Remove after merge.", "schemaVersion": 1, "exceptions": [ { @@ -150,6 +150,10 @@ { "pullRequest": 14003, "changeSha256": "de6458a7ed45f7bd82fe27eccb91af8f780be499af9f1215af86f05302af6fc2" + }, + { + "pullRequest": 14517, + "changeSha256": "7f129199e585c9f9e65b7fd6dee1b9c5e504ca70377b859464ed17f9e5851686" } ] } diff --git a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts index 958a30d2e6b..0629d12b95b 100644 --- a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts @@ -146,6 +146,23 @@ describe("MCP shared-host address pins", () => { ); }); + it.each([ + [ + "conflicting public pins", + { one: entry("one"), three: entry("three", { allowedIps: ["8.8.4.4"] }) }, + ], + ["trusted-private mismatch", { one: entry("one", { trustedPrivateHost: "mcp.example.test" }) }], + ])("explains complete retained-provider recovery for %s", (_label, bridges) => { + const refused = align(bridges, ["1.1.1.1"]); + expect(refused.ok).toBe(false); + const message = refused.ok ? "" : refused.message; + expect(message).toContain("re-export the affected credential variables"); + expect(message).toContain("Removal preserves providers"); + expect(message).toContain("explicit provider cleanup"); + expect(message).toContain("no other sandbox uses them"); + expect(message).toContain("manage-mcp-servers#rotate-a-credential"); + }); + it("accepts trusted-private siblings whose pins already match", () => { const privateSibling = entry("one", { url: "https://mcp.corp.example/one", diff --git a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts index 3987731fce1..7735c657462 100644 --- a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts +++ b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts @@ -68,6 +68,7 @@ export function alignMcpAddTargetWithSharedHostPins(options: { const authority = endpointAuthority(url); if (!authority) return { ok: true, target, reusedFrom: [] }; + const recovery = `Before removing registrations with \`nemoclaw ${sandboxName} mcp remove \`, re-export the affected credential variables. Removal preserves providers. Before re-adding, perform explicit provider cleanup after confirming no other sandbox uses them. Follow https://docs.nvidia.com/nemoclaw/latest/user-guide/openclaw/manage-sandboxes/mcp-servers/manage-mcp-servers#rotate-a-credential before adding the servers again.`; const groups = new Map(); for (const entry of Object.values(bridges)) { if ( @@ -94,7 +95,7 @@ export function alignMcpAddTargetWithSharedHostPins(options: { .join("; "); return { ok: false, - message: `MCP server '${server}' was not added: managed servers on ${authority} already record different address pins (${recorded}). OpenShell rejects endpoints that share a host and port but list different allowed IPs. Remove the servers whose pins differ with \`nemoclaw ${sandboxName} mcp remove \`, then add them again so they record the same pins.`, + message: `MCP server '${server}' was not added: managed servers on ${authority} already record different address pins (${recorded}). OpenShell rejects endpoints that share a host and port but list different allowed IPs. ${recovery}`, }; } @@ -105,7 +106,7 @@ export function alignMcpAddTargetWithSharedHostPins(options: { if (firstGroup.trustedPrivate || target.trustedPrivateHost) { return { ok: false, - message: `MCP server '${server}' was not added: it resolves to ${describePins(requested)} on ${authority}, but ${describeServers(firstGroup.servers)} record${firstGroup.servers.length === 1 ? "s" : ""} ${describePins(firstGroup.pins)}, and OpenShell rejects endpoints that share a host and port but list different allowed IPs. NemoClaw does not reuse or replace trusted-private pins on its own. Remove ${describeServers(firstGroup.servers)} with \`nemoclaw ${sandboxName} mcp remove \`, then add the servers on this host again.`, + message: `MCP server '${server}' was not added: it resolves to ${describePins(requested)} on ${authority}, but ${describeServers(firstGroup.servers)} record${firstGroup.servers.length === 1 ? "s" : ""} ${describePins(firstGroup.pins)}, and OpenShell rejects endpoints that share a host and port but list different allowed IPs. NemoClaw does not reuse or replace trusted-private pins on its own. ${recovery}`, }; } diff --git a/test/e2e/live/mcp-bridge-reliability.ts b/test/e2e/live/mcp-bridge-reliability.ts index 8928d05721c..6aac59ab4e4 100644 --- a/test/e2e/live/mcp-bridge-reliability.ts +++ b/test/e2e/live/mcp-bridge-reliability.ts @@ -56,6 +56,7 @@ export async function addBridgeAndReadStatus( serverName?: string; credentialEnvName?: string; applyHostPolicyEdit?: boolean; + addNodeOptions?: string; }, ): Promise { await (options.applyHostPolicyEdit === false @@ -80,6 +81,7 @@ export async function addBridgeAndReadStatus( artifactName: `${options.artifactPrefix}-mcp-add-fake-server`, env: { ...buildAvailabilityProbeEnv(), + ...(options.addNodeOptions ? { NODE_OPTIONS: options.addNodeOptions } : {}), [credentialEnvName]: credential, }, redactionValues: [credential], diff --git a/test/e2e/live/mcp-bridge-servers.ts b/test/e2e/live/mcp-bridge-servers.ts index 12148027c2b..1462a8ba2c1 100644 --- a/test/e2e/live/mcp-bridge-servers.ts +++ b/test/e2e/live/mcp-bridge-servers.ts @@ -1072,6 +1072,7 @@ export async function startCompatibleMock(options: { export async function startFakeMcpHttpsServer(options: { secret: string; + additionalPaths?: Readonly>; challenge?: string; resultToken?: string; tls?: { cert: Buffer; key: Buffer }; @@ -1203,7 +1204,9 @@ export async function startFakeMcpHttpsServer(options: { res.writeHead(202); res.end(); }; - if (requestPath !== "/mcp") { + const requestSecret = + requestPath === "/mcp" ? expectedSecret : options.additionalPaths?.[requestPath]; + if (requestSecret === undefined) { respondJson(404, { error: { message: "not found" } }); return; } @@ -1212,7 +1215,7 @@ export async function startFakeMcpHttpsServer(options: { return; } if (req.method === "GET") { - if (auth !== `Bearer ${expectedSecret}`) { + if (auth !== `Bearer ${requestSecret}`) { respondJson(401, { error: { message: "missing rewritten bearer credential" } }); return; } @@ -1241,7 +1244,7 @@ export async function startFakeMcpHttpsServer(options: { "cache-control": "no-cache", connection: "keep-alive", }); - res.write(`event: endpoint\ndata: /mcp?legacySessionId=${eventSessionId}\n\n`); + res.write(`event: endpoint\ndata: ${requestPath}?legacySessionId=${eventSessionId}\n\n`); serverEventStreams.add(res); res.once("close", () => { eventSession.phase = "closed"; @@ -1270,7 +1273,7 @@ export async function startFakeMcpHttpsServer(options: { respondJson(405, { error: { message: "method not allowed" } }); return; } - if (auth !== `Bearer ${expectedSecret}`) { + if (auth !== `Bearer ${requestSecret}`) { respondJson(401, { error: { message: "missing rewritten bearer credential" } }); return; } diff --git a/test/e2e/live/mcp-bridge-shared-host.ts b/test/e2e/live/mcp-bridge-shared-host.ts new file mode 100644 index 00000000000..07fb9f02c47 --- /dev/null +++ b/test/e2e/live/mcp-bridge-shared-host.ts @@ -0,0 +1,265 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import dns from "node:dns/promises"; +import fs from "node:fs"; +import path from "node:path"; +import { expect } from "vitest"; + +import type { ArtifactSink } from "../fixtures/artifacts.ts"; +import type { CleanupRegistry } from "../fixtures/cleanup.ts"; +import { assertCleanupSucceededOrAbsent } from "../fixtures/cleanup-resources.ts"; +import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; +import { assertExitZero } from "../fixtures/clients/command.ts"; +import type { HostCliClient } from "../fixtures/clients/host.ts"; +import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; +import { MCP_BRIDGE_TEST_CREDENTIALS } from "../fixtures/mcp-bridge-credentials.ts"; +import type { TestProgress } from "../fixtures/progress.ts"; +import { buildMcpBridgePolicyKey } from "../../../src/lib/actions/sandbox/mcp-bridge-policy-render"; +import { cleanupMcpBridge } from "./mcp-bridge-cleanup.ts"; +import { addBridgeAndReadStatus, runMcpProviderRewriteProbe } from "./mcp-bridge-reliability.ts"; +import { captureManagedMcpPolicy, expectExitNonZero } from "./mcp-bridge-sandbox.ts"; +import { startFakeMcpHttpsServer, startPublicMcpHttpsTunnel } from "./mcp-bridge-servers.ts"; + +type Address = { address: string; family: number }; + +/** Control the add process's DNS input without replacing policy or provider operations. */ +export async function withMcpDnsAnswers( + hostname: string, + addresses: readonly Address[], + run: (nodeOptions: string) => Promise, +): Promise { + const scratch = path.resolve(".ws-tmp", "tmp"); + fs.mkdirSync(scratch, { recursive: true, mode: 0o700 }); + const directory = fs.mkdtempSync(path.join(scratch, "mcp-shared-host-dns-")); + const preload = path.join(directory, "lookup.cjs"); + const observed = path.join(directory, "observed.json"); + try { + fs.writeFileSync( + preload, + ` +const dns = require("node:dns/promises"); +const original = dns.lookup; +const answers = ${JSON.stringify(addresses)}; +dns.lookup = async (hostname, options) => { + if (hostname !== ${JSON.stringify(hostname)} || options?.all !== true) { + return original.call(dns, hostname, options); + } + require("node:fs").writeFileSync(${JSON.stringify(observed)}, JSON.stringify(answers)); + return answers.map(answer => ({ ...answer })); +}; +`, + { mode: 0o600 }, + ); + const result = await run(`--require=${JSON.stringify(preload)}`); + // An unused preload cannot establish that the real add saw the intended DNS input. + if (fs.readFileSync(observed, "utf8") !== JSON.stringify(addresses)) { + throw new Error("MCP add did not consume the controlled DNS answers"); + } + return result; + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } +} + +export async function assertSharedHostMcpComposition(options: { + host: HostCliClient; + sandbox: SandboxClient; + cleanup: CleanupRegistry; + artifacts: ArtifactSink; + progress: TestProgress; + sandboxName: string; +}): Promise { + const { host, sandbox, cleanup, artifacts, progress, sandboxName } = options; + const endpoint = await startFakeMcpHttpsServer({ + secret: MCP_BRIDGE_TEST_CREDENTIALS.host, + additionalPaths: { "/mcp-peer": MCP_BRIDGE_TEST_CREDENTIALS.rotatedHost }, + }); + cleanup.add("stop shared-host MCP endpoint", () => endpoint.close()); + const tunnel = await startPublicMcpHttpsTunnel({ + cleanup, + progress, + server: endpoint, + label: "shared-host MCP", + }); + const hostname = new URL(tunnel.origin).hostname; + const resolved = await dns.lookup(hostname, { all: true, verbatim: true }); + const answers = [ + ...new Map( + resolved.map((answer) => [ + answer.address.toLowerCase(), + { ...answer, address: answer.address.toLowerCase() }, + ]), + ).values(), + ].sort((a, b) => a.address.localeCompare(b.address)); + if (answers.length < 2) + throw new Error("Shared-host MCP fixture requires multiple public DNS answers"); + const firstPins = answers.map((answer) => answer.address).sort(); + const entries = [ + { + server: "shared-one", + pathname: "/mcp", + key: "SHARED_ONE_MCP_SECRET", + secret: MCP_BRIDGE_TEST_CREDENTIALS.host, + answers, + }, + { + server: "shared-two", + pathname: "/mcp-peer", + key: "SHARED_TWO_MCP_SECRET", + secret: MCP_BRIDGE_TEST_CREDENTIALS.rotatedHost, + answers: answers.slice(1), + }, + ]; + await artifacts.writeJson( + "mcp-shared-host-dns-answers.json", + entries.map(({ server, answers }) => ({ server, answers })), + ); + const remove = entries.map((entry) => { + let complete = false; + const provider = `${sandboxName}-mcp-${entry.server}`; + const run = async () => { + if (complete) return; + await cleanupMcpBridge(host, sandboxName, entry.server, "openclaw-config"); + const deleted = await host.command( + host.openshellCommandPath, + ["provider", "delete", provider], + { + env: buildAvailabilityProbeEnv(), + artifactName: `shared-host-delete-${entry.server}`, + timeoutMs: 60_000, + }, + ); + assertCleanupSucceededOrAbsent( + deleted, + /provider[^\n]*(?:not found|does not exist)|NOT_FOUND/iu, + `remove owned shared-host provider ${provider}`, + ); + complete = true; + }; + cleanup.add(`remove shared-host MCP registration and provider ${entry.server}`, run); + return run; + }); + for (const entry of entries) { + await withMcpDnsAnswers(hostname, entry.answers, (addNodeOptions) => + addBridgeAndReadStatus(host, sandbox, { + sandboxName, + mcpUrl: `${tunnel.origin}${entry.pathname}`, + expectedAdapter: "openclaw-config", + artifactPrefix: entry.server, + serverName: entry.server, + credentialEnvName: entry.key, + credential: entry.secret, + applyHostPolicyEdit: false, + addNodeOptions, + }), + ); + } + for (const entry of entries) { + const captured = await captureManagedMcpPolicy(sandbox, { + sandboxName, + url: `${tunnel.origin}${entry.pathname}`, + policyKey: buildMcpBridgePolicyKey(entry.server), + artifactName: `${entry.server}-effective-pins`, + label: "shared-host effective pins", + }); + expect(captured.policy.endpoints?.[0]?.allowed_ips).toEqual(firstPins); + const requestOffset = endpoint.requests.length; + const accepted = await runMcpProviderRewriteProbe( + sandbox, + sandboxName, + `${tunnel.origin}${entry.pathname}`, + "tools/list", + "allow", + `${entry.server}-authenticated`, + entry.key, + ); + assertExitZero(accepted, `${entry.server} authenticated request after both adds`); + const observed = endpoint.requests + .slice(requestOffset) + .filter((request) => request.path === entry.pathname); + expect(observed.length).toBeGreaterThan(0); + expect( + observed.every( + (request) => request.auth === `Bearer ${entry.secret}` && request.responseStatus === 200, + ), + ).toBe(true); + } + const requestOffset = endpoint.requests.length; + for (const entry of entries) { + const denied = await runMcpProviderRewriteProbe( + sandbox, + sandboxName, + `${tunnel.origin}/unconfigured`, + "tools/list", + "deny-strict", + `${entry.server}-outside-binding`, + entry.key, + ); + assertExitZero(denied, `${entry.server} credential cannot reach an unconfigured path`); + } + expect( + endpoint.requests.slice(requestOffset).filter((request) => request.path === "/unconfigured"), + ).toHaveLength(0); + for (const run of remove) await run(); + const list = await host.nemoclaw([sandboxName, "mcp", "list", "--json"], { + env: buildAvailabilityProbeEnv(), + artifactName: "shared-host-registrations-removed", + timeoutMs: 60_000, + }); + assertExitZero(list, "list registrations after shared-host cleanup"); + const names = (JSON.parse(list.stdout).bridges as Array<{ server: string }>).map( + (entry) => entry.server, + ); + expect(names.filter((name) => entries.some((entry) => entry.server === name))).toEqual([]); + for (const entry of entries) { + const absent = await host.command( + host.openshellCommandPath, + ["provider", "get", `${sandboxName}-mcp-${entry.server}`], + { + env: buildAvailabilityProbeEnv(), + artifactName: `${entry.server}-provider-absent`, + timeoutMs: 60_000, + }, + ); + expectExitNonZero( + absent, + "shared-host provider removed", + /not found|does not exist|NOT_FOUND/iu, + ); + } +} + +/** Keep the existing different-host credential case beside the same-host composition case. */ +export async function addDistinctCredentialMcpEndpoint(options: { + host: HostCliClient; + sandbox: SandboxClient; + cleanup: CleanupRegistry; + progress: TestProgress; + sandboxName: string; + serverOptions: Parameters[0]; +}) { + const { host, sandbox, cleanup, progress, sandboxName, serverOptions } = options; + const endpoint = await startFakeMcpHttpsServer(serverOptions); + cleanup.add("stop distinct MCP HTTPS server", () => endpoint.close()); + const tunnel = await startPublicMcpHttpsTunnel({ + cleanup, + label: "distinct credential MCP HTTPS server", + progress, + server: endpoint, + }); + cleanup.add("remove distinct credential bridge", () => + cleanupMcpBridge(host, sandboxName, "distinct", "openclaw-config"), + ); + await addBridgeAndReadStatus(host, sandbox, { + sandboxName, + mcpUrl: tunnel.url, + expectedAdapter: "openclaw-config", + serverName: "distinct", + credentialEnvName: "DISTINCT_MCP_SECRET", + credential: serverOptions.secret, + artifactPrefix: "openclaw-distinct", + applyHostPolicyEdit: false, + }); + return { endpoint, tunnel }; +} diff --git a/test/e2e/live/mcp-bridge.test.ts b/test/e2e/live/mcp-bridge.test.ts index b166e73e5b0..f5acae8e4d3 100644 --- a/test/e2e/live/mcp-bridge.test.ts +++ b/test/e2e/live/mcp-bridge.test.ts @@ -58,6 +58,10 @@ import { requireMcpBridgeTlsCaCert, } from "./mcp-bridge-onboard-env.ts"; import { MCP_BRIDGE_PHASES } from "./mcp-bridge-phases.ts"; +import { + addDistinctCredentialMcpEndpoint, + assertSharedHostMcpComposition, +} from "./mcp-bridge-shared-host.ts"; import { DEEPAGENTS_MCP_DENIED_TOOL_PROBE, HERMES_MCP_ENV_LOAD_COMMANDS, @@ -815,30 +819,15 @@ test( expect(aliasState.policyAbsent).toBe(true); expect(aliasState.adapterAbsent).toBe(true); // Exercise both native adapters with both credentials and policy entries present. - const distinctMcp = await startFakeMcpHttpsServer({ - ...MCP_SERVER_OPTIONS, - secret: ROTATED_HOST_SECRET, - }); - cleanup.add("stop distinct MCP HTTPS server", () => distinctMcp.close()); - const distinctTunnel = await startPublicMcpHttpsTunnel({ - cleanup, - label: "distinct credential MCP HTTPS server", - progress, - server: distinctMcp, - }); - cleanup.add("remove distinct credential bridge", () => - cleanupMcpBridge(host, OPENCLAW_SANDBOX_NAME, "distinct", "openclaw-config"), - ); - await addBridgeAndReadStatus(host, sandbox, { - ...bridge, - mcpUrl: distinctTunnel.url, - expectedAdapter: "openclaw-config", - serverName: "distinct", - credentialEnvName: "DISTINCT_MCP_SECRET", - credential: ROTATED_HOST_SECRET, - artifactPrefix: "openclaw-distinct", - applyHostPolicyEdit: false, - }); + const { endpoint: distinctMcp, tunnel: distinctTunnel } = + await addDistinctCredentialMcpEndpoint({ + host, + sandbox, + cleanup, + progress, + sandboxName: OPENCLAW_SANDBOX_NAME, + serverOptions: { ...MCP_SERVER_OPTIONS, secret: ROTATED_HOST_SECRET }, + }); await assertRealAdapterToolCall(host, sandbox, fakeMcp, { ...bridge, resultToken: MCP_RESULT, @@ -866,6 +855,14 @@ test( openClawToolSearch.toolNames = ["fake__fake_echo"]; } await cleanupMcpBridge(host, OPENCLAW_SANDBOX_NAME, "distinct", "openclaw-config"); + await assertSharedHostMcpComposition({ + host, + sandbox, + cleanup, + artifacts, + progress, + sandboxName: OPENCLAW_SANDBOX_NAME, + }); await assertBridgeInfrastructure(host, sandbox, { ...bridge, providerName, diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 19202ac9eae..1a1f64dda6d 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -824,6 +824,7 @@ "test/e2e/live/mcp-bridge-onboard-env.ts", "test/e2e/live/mcp-bridge-reliability.ts", "test/e2e/live/mcp-bridge-servers.ts", + "test/e2e/live/mcp-bridge-shared-host.ts", "test/e2e/fixtures/mcp-fixture-tls.ts", "test/e2e/live/mcp-bridge-hermes-lifecycle.ts", "test/e2e/live/mcp-bridge-phases.ts", @@ -857,6 +858,7 @@ "test/e2e/support/mcp-bridge-hermes-http.test.ts", "test/e2e/support/mcp-bridge-onboard-env.test.ts", "test/e2e/support/mcp-bridge-reliability.test.ts", + "test/e2e/support/mcp-bridge-shared-host.test.ts", "test/e2e/support/retry-policy.test.ts", "test/e2e/support/mcp-bridge-sandbox.test.ts", "test/e2e/support/mcp-bridge-tool-discovery.test.ts", diff --git a/test/e2e/support/mcp-bridge-shared-host.test.ts b/test/e2e/support/mcp-bridge-shared-host.test.ts new file mode 100644 index 00000000000..2cf9aa6aced --- /dev/null +++ b/test/e2e/support/mcp-bridge-shared-host.test.ts @@ -0,0 +1,97 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import https from "node:https"; +import path from "node:path"; +import { afterAll, expect, it } from "vitest"; +import { createMcpFixtureTls } from "../fixtures/mcp-fixture-tls.ts"; +import { withMcpDnsAnswers } from "../live/mcp-bridge-shared-host.ts"; +import { startFakeMcpHttpsServer } from "../live/mcp-bridge-servers.ts"; + +const { tls, close } = createMcpFixtureTls(); +afterAll(close); + +it("controls only the selected host lookup and removes its DNS preload afterward", async () => { + const answers = [ + { address: "8.8.8.8", family: 4 }, + { address: "8.8.4.4", family: 4 }, + ]; + let directory = ""; + await withMcpDnsAnswers("shared.example.test", answers, async (nodeOptions) => { + directory = path.dirname(JSON.parse(nodeOptions.slice("--require=".length)) as string); + const script = ` +const dns = require("node:dns/promises"); +Promise.all([ + dns.lookup("shared.example.test", { all: true, verbatim: true }), + dns.lookup("127.0.0.1", { all: true, verbatim: true }), +]).then(result => process.stdout.write(JSON.stringify(result))); +`; + const output = execFileSync(process.execPath, ["-e", script], { + env: { ...process.env, NODE_OPTIONS: nodeOptions }, + encoding: "utf8", + timeout: 10_000, + }); + expect(JSON.parse(output)).toEqual([answers, [{ address: "127.0.0.1", family: 4 }]]); + }); + expect(fs.existsSync(directory)).toBe(false); +}); + +it("rejects an unused DNS preload and removes it when the add fails", async () => { + const answers = [{ address: "8.8.8.8", family: 4 }]; + let directory = ""; + await expect( + withMcpDnsAnswers("shared.example.test", answers, async (nodeOptions) => { + directory = path.dirname(JSON.parse(nodeOptions.slice("--require=".length)) as string); + }), + ).rejects.toThrow(/ENOENT/u); + expect(fs.existsSync(directory)).toBe(false); + await expect( + withMcpDnsAnswers("shared.example.test", answers, async (nodeOptions) => { + directory = path.dirname(JSON.parse(nodeOptions.slice("--require=".length)) as string); + throw new Error("add refused"); + }), + ).rejects.toThrow("add refused"); + expect(fs.existsSync(directory)).toBe(false); +}); + +it("authenticates each MCP path with its own credential through real HTTPS", async () => { + const server = await startFakeMcpHttpsServer({ + secret: "first", + additionalPaths: { "/mcp-peer": "second" }, + tls, + }); + async function request(pathname: string, secret: string): Promise { + return new Promise((resolve, reject) => { + const request = https.request( + `https://127.0.0.1:${server.port}${pathname}`, + { + ca: tls.cert, + method: "POST", + timeout: 5_000, + headers: { authorization: `Bearer ${secret}`, "content-type": "application/json" }, + }, + (response) => { + response.resume(); + response.once("end", () => resolve(response.statusCode ?? 0)); + }, + ); + request.once("error", reject); + request.once("timeout", () => request.destroy(new Error("MCP fixture request timed out"))); + request.end(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" })); + }); + } + try { + expect(await request("/mcp", "first")).toBe(200); + expect(await request("/mcp-peer", "second")).toBe(200); + expect(await request("/mcp", "second")).toBe(401); + expect(await request("/mcp-peer", "first")).toBe(401); + expect(await request("/unconfigured", "first")).toBe(404); + server.setSecret("replacement"); + expect(await request("/mcp", "replacement")).toBe(200); + expect(await request("/mcp-peer", "second")).toBe(200); + } finally { + await server.close(); + } +}); From 364ad2d3df384a8c375e69bec0ddb53407eb242b Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 17 Nov 2026 02:42:16 -0800 Subject: [PATCH 03/17] fix(mcp): refuse conflicting shared-host pin refreshes Public MCP registrations can share pins, but refreshing one could write a different set and fail OpenShell policy activation. Use the existing shared-host pin check for both add and refresh. Refuse divergent refreshes before mutation and preserve independent or matching-pin refreshes. Document sibling-pin reuse, the refresh constraint, and coordinated recovery. Link retained-provider cleanup from the existing procedures and replace the incomplete troubleshooting recipe. Refs #13800 Signed-off-by: Deepak Jain --- docs/manage-sandboxes/add-mcp-server.mdx | 8 +- docs/manage-sandboxes/manage-mcp-servers.mdx | 42 ++++++++- docs/reference/commands.mdx | 8 +- docs/reference/troubleshoot-mcp-servers.mdx | 15 +-- .../actions/sandbox/mcp-bridge-add-restart.ts | 16 +++- .../actions/sandbox/mcp-bridge-update.test.ts | 91 +++++++++++++++++++ .../mcp-bridge/shared-host-pins.test.ts | 14 ++- .../sandbox/mcp-bridge/shared-host-pins.ts | 32 ++++--- 8 files changed, 184 insertions(+), 42 deletions(-) diff --git a/docs/manage-sandboxes/add-mcp-server.mdx b/docs/manage-sandboxes/add-mcp-server.mdx index 581c596ef84..46e38968a0e 100644 --- a/docs/manage-sandboxes/add-mcp-server.mdx +++ b/docs/manage-sandboxes/add-mcp-server.mdx @@ -150,7 +150,7 @@ NemoClaw records the normalized host and every validated address as OpenShell po The raw bearer value passes transiently to the OpenShell provider and remains absent from NemoClaw state, sandbox configuration, command arguments, and logs. The sandbox configuration contains only an OpenShell resolver placeholder for `LOCAL_MCP_TOKEN`, not the raw bearer value. You can unset the host variable after `mcp add` returns because OpenShell retains the credential. -To replace it, remove and re-add the server with the replacement exported under the same host variable name. `mcp remove` detaches the provider, and sandbox destroy may leave the detached provider for explicit operator cleanup. +To replace it, follow [Rotate a Credential](manage-mcp-servers#rotate-a-credential), including explicit cleanup of the retained provider before re-adding. Inspect the registration after the add returns: @@ -208,7 +208,11 @@ Deep Agents Code supports at most 64 managed MCP servers in one sandbox. Endpoint paths cannot contain percent escapes, backslashes, semicolons, or OpenShell glob metacharacters. Endpoint URLs cannot use port `0`. -NemoClaw resolves hostnames before registration and pins the validated addresses in the generated policy. +NemoClaw validates DNS before registration. +When another managed server in the sandbox uses the same hostname and port, a public add revalidates and reuses its recorded address pins, even if current DNS differs. +Otherwise, the generated policy pins the validated DNS addresses. +NemoClaw refuses the add before mutation if sibling pin sets conflict or trusted-private pins would need to change. +Refer to [Refresh Shared-Host Registrations](manage-mcp-servers#refresh-shared-host-registrations) to change pins for every registration on that hostname and port. Public endpoints need no trusted-private declaration. Private endpoints require a trust declaration and can use only RFC1918, CGNAT, or IPv6 unique local addresses. Supply the declaration with `--trusted-private-host` or the generic `NEMOCLAW_TRUSTED_PRIVATE_HOSTS` environment variable. diff --git a/docs/manage-sandboxes/manage-mcp-servers.mdx b/docs/manage-sandboxes/manage-mcp-servers.mdx index bfbee1704c3..57ba6f6a0b1 100644 --- a/docs/manage-sandboxes/manage-mcp-servers.mdx +++ b/docs/manage-sandboxes/manage-mcp-servers.mdx @@ -139,20 +139,29 @@ The bare `mcp list` and `mcp status` forms never probe, so they stay fast. Endpo ## Rotate a Credential -Export the replacement under the same host environment name used by `mcp add`, remove the native registration, and add it again so NemoClaw creates a fresh provider binding: +Export the replacement under the same host environment name used by `mcp add`, then remove the native registration: ```bash export GITHUB_MCP_TOKEN='replacement-value' $$nemoclaw my-sandbox mcp remove github +``` + +`remove` deletes the agent-native registration and detaches the exact managed provider, but preserves the provider object. +Confirm that no sandbox uses that provider before you delete it with `openshell provider delete `. +Keep the original URL, credential variable name, and any denied-tool or trusted-private options for the replacement. +Then add the server again to create a fresh provider binding: + +```bash $$nemoclaw my-sandbox mcp add github \ --url https://api.githubcopilot.com/mcp/ \ --env GITHUB_MCP_TOKEN unset GITHUB_MCP_TOKEN ``` -`remove` deletes the agent-native registration and detaches the exact managed provider, but conservatively preserves the provider object. Remove that preserved provider explicitly after confirming no sandbox uses it; then `add` creates a new provider with the replacement credential and reconnects the native registration. - -For a trusted-private entry, pass the same reviewed `--trusted-private-host` value to `add`; NemoClaw resolves and records the replacement pins again. For a public entry, `add` resolves the hostname and creates a policy for the current validated public addresses. +For a trusted-private entry, pass the same reviewed `--trusted-private-host` value to `add`. +For a public entry, `add` validates current DNS but reuses revalidated sibling pins when another managed server uses the same hostname and port. +Remove-and-add therefore does not independently refresh shared public pins. +Refer to [Change Endpoint Pins](#change-endpoint-pins) for pin changes. The raw value passes only through the OpenShell provider command's process environment and is not added to argv, NemoClaw state, or sandbox config. Revoke the old credential upstream after the new add succeeds. @@ -204,6 +213,22 @@ Correct a reported source conflict before retrying. If the write cannot be confirmed, inspect `mcp status` and the live OpenShell policy before retrying. Successful tool discovery verifies that the endpoint is reachable through its existing credential binding. +### Refresh Shared-Host Registrations + +Registrations on one hostname and port must use identical address pins, even when their paths and credentials differ. +A per-server refresh stops before mutation if its new DNS answers differ from a sibling's recorded pins or the siblings already disagree. +Adding or re-adding one public registration reuses the sibling pins instead of refreshing them. + +To change the shared pin set, plan an interruption for every affected registration. +Keep each server's original add options and re-export its credential from your secret manager before removal. +Remove every registration on that hostname and port, and complete the [retained-provider cleanup](#rotate-a-credential) for each one. +Add the servers again with their original options. +The first public add records current validated DNS addresses; later adds reuse that set. +Run `mcp status --tools` for each server and confirm readiness and successful discovery. +If DNS still differs from the recorded pins, coordinate the endpoint's DNS before repeating the procedure. + +### Change Trusted-Private Pins + For a trusted-private server, review every destination change before NemoClaw records new pins. Neither status, restart, rebuild, nor restore changes the recorded address set. If the endpoint moves to another address, remove and re-add the server: @@ -211,6 +236,11 @@ If the endpoint moves to another address, remove and re-add the server: ```bash export LOCAL_MCP_TOKEN='replace-with-secret-manager-value' $$nemoclaw my-sandbox mcp remove local-tools +``` + +Complete the [retained-provider cleanup](#rotate-a-credential), then re-add the server: + +```bash $$nemoclaw my-sandbox mcp add local-tools \ --url https://mcp-host.corp.example/mcp \ --env LOCAL_MCP_TOKEN \ @@ -218,7 +248,9 @@ $$nemoclaw my-sandbox mcp add local-tools \ unset LOCAL_MCP_TOKEN ``` -Removing the server deletes the agent-native entry, removes its generated key from the current OpenShell policy, and detaches the provider. The provider itself is preserved for explicit cleanup. The re-add performs a new DNS preflight and records the reviewed exact address set. +Removing the server deletes the agent-native entry, removes its generated key from the current OpenShell policy, and detaches the provider. Complete the [retained-provider cleanup](#rotate-a-credential) before re-adding. +The re-add performs a new DNS preflight and records the reviewed exact address set. +For registrations sharing a hostname and port, coordinate removal and re-addition for all of them so their reviewed pins agree. ## Remove a Server diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index d62153c2272..89ec8733142 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -2978,6 +2978,10 @@ $$nemoclaw my-assistant mcp list [--json] Add an MCP Streamable HTTP server to a sandbox. Pass `--url` for the MCP endpoint and the required single `--env KEY` bearer credential for the sandbox-side MCP client. Pass repeatable `--deny-tool ` options to block matching `tools/call` requests at the OpenShell proxy. The generated deny rules match tool names only and do not inspect arguments. Pass a repeatable `--trusted-private-host ` option to admit an exact RFC1918, CGNAT, or IPv6 unique local destination for the current command. The declaration must equal the normalized host from `--url`. For managed MCP, use a DNS hostname for an IPv6 unique local address because NemoClaw has not qualified direct IPv6-literal MCP URLs. You can supply exact hosts through `NEMOCLAW_TRUSTED_PRIVATE_HOSTS` instead, and NemoClaw combines the variable with command options. NemoClaw records the resulting exact trust intent and address pins, so restart, rebuild, and restore do not depend on the ambient environment. NemoClaw registers that credential in an OpenShell provider, installs a generated OpenShell `protocol: mcp` policy for the target endpoint, attaches the provider to the running sandbox, and writes only an OpenShell resolver placeholder for the recorded key into the agent configuration. Inline `--env KEY=VALUE` is rejected because it would expose the value in NemoClaw process arguments. Load the variable from a secret manager or masked prompt, export it without recording the value in shell history, and pass only `--env KEY`. All endpoints must use HTTPS. The full URL and path are persisted and displayed, so URLs cannot contain userinfo, query strings, fragments, known secret-shaped path material, percent-escaped or glob-style paths, or port zero. Server names must start with a letter and contain at most 64 letters, digits, hyphens, or underscores, and endpoint hostnames must use canonical lowercase DNS labels. NemoClaw rejects invalid names and endpoints before it writes lifecycle state or changes OpenShell resources. NemoClaw generates a narrow `protocol: mcp` policy for the destination, literal path, adapter binaries, pinned addresses, explicit MCP methods, and a 131,072-byte request-body limit. OpenShell `0.0.116` evaluates that policy before replacing the attached provider placeholder in the allowed request header. NemoClaw imports the endpointless `nemoclaw-mcp-v1` profile and binds the dedicated provider to that endpoint with `credential_binding.provider`. OpenShell withholds the credential before the binding is active and outside the bound host, port, and path. The sandbox client connects directly through OpenShell's existing egress path, and NemoClaw does not run a host-side MCP data-plane bridge, proxy, relay, or listener. After the add commits, NemoClaw freshly verifies the exact generated policy, expected provider attachment, recorded provider ID, `nemoclaw-mcp-v1` type, valid resource version, and exactly one credential key matching the recorded key. If those readiness checks pass, it sends a differential pair of wire-level MCP `initialize` requests from inside the sandbox — one with the placeholder header and one with an unresolvable control bearer — to verify that OpenShell resolves the credential on egress; otherwise it reports an inconclusive `probe skipped` result and sends no request. Neither outcome fails the committed add, and `--no-probe` skips this check. For full setup details, see [Add an MCP Server](../manage-sandboxes/mcp-servers/add-an-mcp-server). +Public registrations on the same hostname and port reuse revalidated sibling address pins when current DNS differs. +Conflicting sibling pins or trusted-private pin changes stop the add before mutation. +Refer to [Change Endpoint Pins](../manage-sandboxes/mcp-servers/manage-mcp-servers#change-endpoint-pins) for coordinated recovery. + Credential-bound managed definitions may share a normalized endpoint only when they intentionally share one credential binding. NemoClaw rejects the same endpoint with different credential bindings; use a distinct endpoint URL when different credentials are required. The generated policy is also binary-scoped: the selected agent's adapter binaries are allowed, while an interactive `/usr/bin/curl` request to the same endpoint is denied. @@ -3059,12 +3063,14 @@ $$nemoclaw my-assistant mcp update github --refresh-public-pins Public-pin refresh requires matching current sources and existing exact public pins. It preserves all other policy fields, including denied tools, methods, binary grants, and credential bindings. It rejects private or special-use answers, address ranges, and conflicting sources before writing. +It also refuses a refresh that would disagree with sibling pins on the same hostname and port. +Refer to [Refresh Shared-Host Registrations](../manage-sandboxes/mcp-servers/manage-mcp-servers#refresh-shared-host-registrations) for coordinated pin changes. If the update is not confirmed, inspect status and the live policy before retrying. Restart, rebuild, and restore do not refresh pins. ### `$$nemoclaw mcp status` -Inspect MCP server state for one server or for all servers discovered from the agent-native configuration. Status joins that source with the live OpenShell policy, provider, attachment, and credential-key shape; no MCP registry row is consulted or created. Status also compares current DNS answers with recorded pins without changing the policy. Text output reports `public address pins:` or `private address pins:` with `match`, `drift`, or `unresolved`; public targets that resolve to private or special-use addresses report `rejected`. JSON output reports the state, recorded pins, and validated current pins when available in `publicTarget` or `trustedPrivateTarget`. Public drift directs you to `mcp update --refresh-public-pins`, which changes only the live endpoint address pins. Trusted-private drift still requires review and remove-and-add approval. When a single server is named, status requests a differential wire-level credential-resolution probe. It sends no probe traffic unless the policy binding is present, the expected provider attachment is confirmed, and the live provider has the `nemoclaw-mcp-v1` type, a valid resource version, and exactly one credential key matching the source placeholder; a readiness failure reports `unknown` with a `probe skipped` detail. When ready, the same MCP `initialize` is sent from inside the sandbox once with the recorded resolver placeholder header and once with a deliberately-unresolvable control bearer. Classification uses the two HTTP status codes plus curl exit codes for transport, timeout, and policy-denial outcomes; response bodies are never captured or printed. A `verified` verdict requires the placeholder request to be accepted (HTTP 2xx) while the control is rejected — the only outcome that proves a valid credential was on the wire. Identical HTTP 400, 401, or 403 rejections raise a warning that names the hypotheses — the placeholder forwarded verbatim, an expired or revoked credential that resolved correctly, or (for HTTP 400) endpoint request validation — and tells you to verify the stored credential first. For HTTP 401 or 403, a confirmed-valid credential means the host is not rewriting placeholders and agent runtimes receive the same auth failure and skip the server; HTTP 400 remains inconclusive because the endpoint may reject the probe request itself. Every other outcome — differing rejections (an endpoint may reject two different literal bearers differently), endpoints that skip authentication, endpoint outages, policy denials, and unreachable sandboxes — reports as `unknown` rather than blaming the credential rewrite, and a source URL that fails the current authenticated-endpoint boundary is never probed. +Inspect MCP server state for one server or for all servers discovered from the agent-native configuration. Status joins that source with the live OpenShell policy, provider, attachment, and credential-key shape; no MCP registry row is consulted or created. Status also compares current DNS answers with recorded pins without changing the policy. Text output reports `public address pins:` or `private address pins:` with `match`, `drift`, or `unresolved`; public targets that resolve to private or special-use addresses report `rejected`. JSON output reports the state, recorded pins, and validated current pins when available in `publicTarget` or `trustedPrivateTarget`. Public drift directs you to `mcp update --refresh-public-pins`, which changes only the live endpoint address pins and refuses changes that conflict with sibling pins on the same hostname and port. Trusted-private drift still requires review and remove-and-add approval. When a single server is named, status requests a differential wire-level credential-resolution probe. It sends no probe traffic unless the policy binding is present, the expected provider attachment is confirmed, and the live provider has the `nemoclaw-mcp-v1` type, a valid resource version, and exactly one credential key matching the source placeholder; a readiness failure reports `unknown` with a `probe skipped` detail. When ready, the same MCP `initialize` is sent from inside the sandbox once with the recorded resolver placeholder header and once with a deliberately-unresolvable control bearer. Classification uses the two HTTP status codes plus curl exit codes for transport, timeout, and policy-denial outcomes; response bodies are never captured or printed. A `verified` verdict requires the placeholder request to be accepted (HTTP 2xx) while the control is rejected, the only outcome that proves a valid credential was on the wire. Identical HTTP 400, 401, or 403 rejections raise a warning that names the hypotheses, the placeholder forwarded verbatim, an expired or revoked credential that resolved correctly, or (for HTTP 400) endpoint request validation, and tells you to verify the stored credential first. For HTTP 401 or 403, a confirmed-valid credential means the host is not rewriting placeholders and agent runtimes receive the same auth failure and skip the server; HTTP 400 remains inconclusive because the endpoint may reject the probe request itself. Every other outcome, differing rejections (an endpoint may reject two different literal bearers differently), endpoints that skip authentication, endpoint outages, policy denials, and unreachable sandboxes, reports as `unknown` rather than blaming the credential rewrite, and a source URL that fails the current authenticated-endpoint boundary is never probed. `mcp status` exits with status `2` when the managed MCP projection is a symbolic link, FIFO, or diff --git a/docs/reference/troubleshoot-mcp-servers.mdx b/docs/reference/troubleshoot-mcp-servers.mdx index 1fc1e709520..fcb901a8528 100644 --- a/docs/reference/troubleshoot-mcp-servers.mdx +++ b/docs/reference/troubleshoot-mcp-servers.mdx @@ -432,6 +432,8 @@ $$nemoclaw mcp status --tools ``` The refresh preserves all other policy fields, including denied tools, and retains the existing agent configuration and credentials. +If another managed registration uses the same hostname and port, refresh refuses DNS answers that differ from its pins before changing policy. +Follow [Refresh Shared-Host Registrations](../manage-sandboxes/mcp-servers/manage-mcp-servers#refresh-shared-host-registrations) to coordinate that change. Successful tool discovery verifies recovery. Status, restart, rebuild, and restore preserve the live pins. If refresh cannot confirm a write, inspect status and the live OpenShell policy before retrying. @@ -444,17 +446,8 @@ Retry status after DNS recovers. If status reports `private address pins: drift`, review the endpoint address change before updating access. Status, restart, rebuild, and restore do not add new trusted-private addresses. -Remove and re-add the server with the same trusted host to perform a new preflight and record new pins: - -```bash -export LOCAL_MCP_TOKEN='replace-with-secret-manager-value' -$$nemoclaw mcp remove -$$nemoclaw mcp add \ - --url https://mcp-host.corp.example/mcp \ - --env LOCAL_MCP_TOKEN \ - --trusted-private-host mcp-host.corp.example -unset LOCAL_MCP_TOKEN -``` +Follow [Change Trusted-Private Pins](../manage-sandboxes/mcp-servers/manage-mcp-servers#change-trusted-private-pins) to re-export the credential, remove the registration, clean up its retained provider, and re-add with reviewed pins. +Confirm that no other sandbox uses the retained provider before deleting it. A `CONNECT 403` after an address change can mean that OpenShell rejected a current DNS answer outside `allowed_ips`. Do not add a provider's complete address range or broaden the policy to bypass the denial. diff --git a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts index 3bab3a3a902..ebefed8937c 100644 --- a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts +++ b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts @@ -58,7 +58,7 @@ import { waitForDetachedMcpCredential, } from "./mcp-bridge-provider"; import { createMcpProviderAdapterBoundary } from "./mcp-bridge-provider-inspection"; -import { alignMcpAddTargetWithSharedHostPins } from "./mcp-bridge/shared-host-pins"; +import { alignMcpTargetWithSharedHostPins } from "./mcp-bridge/shared-host-pins"; import { assertNoAmbiguousMcpCredentialTarget, assertNoAmbiguousMcpCredentialTargets, @@ -634,6 +634,15 @@ export async function refreshMcpBridgePublicPins( } const url = new URL(normalizeMcpServerUrl(entry.url)); const target = await preflightMcpServerUrlResolvedTarget(url); + const aligned = alignMcpTargetWithSharedHostPins({ + operation: "refresh", + sandboxName, + server, + url: url.toString(), + target, + bridges: observed.bridges, + }); + if (!aligned.ok) throw new McpBridgeError(aligned.message, 2); assertMcpCredentialBoundaryRuntimeVersion(); await ensureSandboxGatewaySelected(sandboxName, runtimeSelection); const provider = await assertMcpProviderRecoverable(entry, runtimeSelection); @@ -649,7 +658,7 @@ export async function refreshMcpBridgePublicPins( "The agent MCP registration changed during public-pin refresh. No policy was changed.", ); } - await refreshMcpPublicPolicyPins(sandboxName, entry, target, runtimeSelection); + await refreshMcpPublicPolicyPins(sandboxName, entry, aligned.target, runtimeSelection); console.log(` Refreshed public address pins for MCP server '${server}'.`); }); } @@ -782,7 +791,8 @@ async function addMcpBridgeUnlocked( // A host that publishes several addresses can answer each add differently, // and OpenShell rejects endpoints that share a host and port but list // different allowed IPs. Keep a new server's pins equal to its siblings'. - const aligned = alignMcpAddTargetWithSharedHostPins({ + const aligned = alignMcpTargetWithSharedHostPins({ + operation: "add", sandboxName, server: options.server, url: normalizedUrl, diff --git a/src/lib/actions/sandbox/mcp-bridge-update.test.ts b/src/lib/actions/sandbox/mcp-bridge-update.test.ts index 593a48b65cc..f73666a426c 100644 --- a/src/lib/actions/sandbox/mcp-bridge-update.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-update.test.ts @@ -102,6 +102,97 @@ describe("source-backed MCP denied-tool policy updates", () => { } }); + it.each([ + ["shared public pins", false, false], + ["trusted-private sibling", true, false], + ["conflicting sibling pins", false, true], + ])( + "refuses a public-pin refresh that would diverge from %s", + async (_label, trustedPrivate, conflicting) => { + const sibling: McpSourceEntry = { + ...entry, + server: "peer", + providerName: "alpha-mcp-peer", + providerId: "22222222-3333-4444-8555-666666666666", + policyName: "mcp-bridge-peer", + url: "https://mcp.example.test/peer", + env: ["PEER_TOKEN"], + ...(trustedPrivate + ? { trustedPrivateHost: "mcp.example.test", allowedIps: ["10.20.30.40"] } + : {}), + }; + const bridges = { + github: entry, + peer: sibling, + ...(conflicting + ? { + third: { + ...sibling, + server: "third", + providerName: "alpha-mcp-third", + providerId: "33333333-4444-4555-8666-777777777777", + policyName: "mcp-bridge-third", + url: "https://mcp.example.test/third", + env: ["THIRD_TOKEN"], + allowedIps: ["9.9.9.9"], + }, + } + : {}), + }; + mocks.inspectSourceBridgeState.mockReturnValueOnce({ + bridges, + sources: { native: bridges, legacy: {} }, + }); + const lookup = vi + .spyOn(dns, "lookup") + .mockResolvedValue([{ address: "1.1.1.1", family: 4 }] as never); + try { + await expect(refreshMcpBridgePublicPins("alpha", "github")).rejects.toThrow( + /not refreshed.*mcp\.example\.test:443/, + ); + expect(mocks.ensureSandboxGatewaySelected).not.toHaveBeenCalled(); + expect(mocks.assertMcpProviderRecoverable).not.toHaveBeenCalled(); + expect(mocks.refreshMcpPublicPolicyPins).not.toHaveBeenCalled(); + expect(mocks.removeGeneratedPolicy).not.toHaveBeenCalled(); + } finally { + lookup.mockRestore(); + } + }, + ); + + it.each([ + ["matching shared pins", "https://mcp.example.test/peer", "8.8.8.8"], + ["another hostname", "https://other.example.test/peer", "1.1.1.1"], + ["another port", "https://mcp.example.test:8443/peer", "1.1.1.1"], + ])("preserves public-pin refresh with %s", async (_label, url, address) => { + const sibling = { + ...entry, + server: "peer", + providerName: "alpha-mcp-peer", + providerId: "22222222-3333-4444-8555-666666666666", + policyName: "mcp-bridge-peer", + url, + env: ["PEER_TOKEN"], + }; + const bridges = { github: entry, peer: sibling }; + mocks.inspectSourceBridgeState.mockReturnValueOnce({ + bridges, + sources: { native: bridges, legacy: {} }, + }); + const lookup = vi.spyOn(dns, "lookup").mockResolvedValue([{ address, family: 4 }] as never); + try { + await refreshMcpBridgePublicPins("alpha", "github"); + expect(mocks.refreshMcpPublicPolicyPins).toHaveBeenCalledWith( + "alpha", + entry, + { addresses: [address] }, + { gatewayName: "nemoclaw-9090", workspace: "default" }, + ); + } finally { + lookup.mockRestore(); + } + }); + it("refuses public-pin refresh when the native registration changes during DNS resolution (#10464)", async () => { const lookup = vi .spyOn(dns, "lookup") diff --git a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts index 0629d12b95b..acf531191a7 100644 --- a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts @@ -11,7 +11,7 @@ import { describe, expect, it } from "vitest"; import { trailingJsonPayload } from "../../../../../test/helpers/host-process-harness"; import type { McpSourceEntry } from "../mcp-bridge-contracts"; -import { alignMcpAddTargetWithSharedHostPins } from "./shared-host-pins"; +import { alignMcpTargetWithSharedHostPins } from "./shared-host-pins"; function entry(server: string, overrides: Partial = {}): McpSourceEntry { return { @@ -31,7 +31,8 @@ function align( url = "https://mcp.example.test/two", target: Partial<{ trustedPrivateHost: string }> = {}, ) { - return alignMcpAddTargetWithSharedHostPins({ + return alignMcpTargetWithSharedHostPins({ + operation: "add", sandboxName: "alpha", server: "two", url, @@ -44,7 +45,8 @@ describe("MCP shared-host address pins", () => { it("leaves the target alone when no other server uses the host and port", () => { const target = { addresses: ["1.1.1.1"] }; expect( - alignMcpAddTargetWithSharedHostPins({ + alignMcpTargetWithSharedHostPins({ + operation: "add", sandboxName: "alpha", server: "two", url: "https://mcp.example.test/two", @@ -77,7 +79,8 @@ describe("MCP shared-host address pins", () => { it("keeps the target when its answer already equals the recorded pins", () => { const target = { addresses: ["1.1.1.1", "8.8.8.8"] }; - const aligned = alignMcpAddTargetWithSharedHostPins({ + const aligned = alignMcpTargetWithSharedHostPins({ + operation: "add", sandboxName: "alpha", server: "two", url: "https://mcp.example.test/two", @@ -171,7 +174,8 @@ describe("MCP shared-host address pins", () => { }); const target = { addresses: ["10.20.30.40"], trustedPrivateHost: "mcp.corp.example" }; expect( - alignMcpAddTargetWithSharedHostPins({ + alignMcpTargetWithSharedHostPins({ + operation: "add", sandboxName: "alpha", server: "two", url: "https://mcp.corp.example/two", diff --git a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts index 7735c657462..33a42cb0fcb 100644 --- a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts +++ b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts @@ -16,7 +16,7 @@ export type McpSharedHostPinAlignment = } | { ok: false; - /** Operator-facing reason the add cannot proceed; the caller reports it as a usage error. */ + /** Operator-facing reason the operation cannot proceed; the caller reports it as a usage error. */ message: string; }; @@ -47,28 +47,23 @@ function describeServers(servers: readonly string[]): string { return servers.map((server) => `'${server}'`).join(", "); } -/** - * OpenShell rejects a sandbox policy when two endpoints share a host and port - * but list different `allowed_ips`. A host that publishes several DNS addresses - * can answer each `mcp add` differently, so a second server on the same host - * and port would be pinned to an address set that disagrees with the first. - * - * Keep the new server's pins identical to the ones already recorded for that - * host and port. Fail before any mutation when the recorded pins already - * disagree with each other, or when they cannot be reused safely. +/** Keep endpoints on one host and port on a validated pin set before mutation. + * Adds may reuse public sibling pins; refreshes must not diverge from them. */ -export function alignMcpAddTargetWithSharedHostPins(options: { +export function alignMcpTargetWithSharedHostPins(options: { + operation: "add" | "refresh"; sandboxName: string; server: string; url: string; target: McpBridgeTargetValidation; bridges: Readonly>; }): McpSharedHostPinAlignment { - const { sandboxName, server, url, target, bridges } = options; + const { operation, sandboxName, server, url, target, bridges } = options; + const action = operation === "add" ? "added" : "refreshed"; const authority = endpointAuthority(url); if (!authority) return { ok: true, target, reusedFrom: [] }; - const recovery = `Before removing registrations with \`nemoclaw ${sandboxName} mcp remove \`, re-export the affected credential variables. Removal preserves providers. Before re-adding, perform explicit provider cleanup after confirming no other sandbox uses them. Follow https://docs.nvidia.com/nemoclaw/latest/user-guide/openclaw/manage-sandboxes/mcp-servers/manage-mcp-servers#rotate-a-credential before adding the servers again.`; + const recovery = `Before removing registrations with \`nemoclaw ${sandboxName} mcp remove \`, re-export the affected credential variables. Removal preserves providers. Perform explicit provider cleanup only after confirming no other sandbox uses them. Follow https://docs.nvidia.com/nemoclaw/latest/user-guide/openclaw/manage-sandboxes/mcp-servers/manage-mcp-servers#rotate-a-credential before adding the servers again.`; const groups = new Map(); for (const entry of Object.values(bridges)) { if ( @@ -95,7 +90,7 @@ export function alignMcpAddTargetWithSharedHostPins(options: { .join("; "); return { ok: false, - message: `MCP server '${server}' was not added: managed servers on ${authority} already record different address pins (${recorded}). OpenShell rejects endpoints that share a host and port but list different allowed IPs. ${recovery}`, + message: `MCP server '${server}' was not ${action}: managed servers on ${authority} already record different address pins (${recorded}). OpenShell rejects endpoints that share a host and port but list different allowed IPs. ${recovery}`, }; } @@ -106,7 +101,14 @@ export function alignMcpAddTargetWithSharedHostPins(options: { if (firstGroup.trustedPrivate || target.trustedPrivateHost) { return { ok: false, - message: `MCP server '${server}' was not added: it resolves to ${describePins(requested)} on ${authority}, but ${describeServers(firstGroup.servers)} record${firstGroup.servers.length === 1 ? "s" : ""} ${describePins(firstGroup.pins)}, and OpenShell rejects endpoints that share a host and port but list different allowed IPs. NemoClaw does not reuse or replace trusted-private pins on its own. ${recovery}`, + message: `MCP server '${server}' was not ${action}: it resolves to ${describePins(requested)} on ${authority}, but ${describeServers(firstGroup.servers)} record${firstGroup.servers.length === 1 ? "s" : ""} ${describePins(firstGroup.pins)}, and OpenShell rejects endpoints that share a host and port but list different allowed IPs. NemoClaw does not reuse or replace trusted-private pins on its own. ${recovery}`, + }; + } + + if (operation === "refresh") { + return { + ok: false, + message: `MCP server '${server}' was not refreshed: ${authority} is shared with ${describeServers(firstGroup.servers)}, which record ${describePins(firstGroup.pins)}. Refreshing only this server to ${describePins(requested)} would create conflicting address pins. ${recovery}`, }; } From 2361e8131febfd5c2f1e0c13284aec78fa502eda Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 17 Nov 2026 04:28:39 -0800 Subject: [PATCH 04/17] fix(mcp): preserve shared-host pins during policy updates Denied-tool updates could resolve new addresses, remove the existing route, and publish pins that conflict with another server on the same host. Check shared pins before route mutation. Reuse validated public pins and reject conflicting or trusted-private pin changes. Keep recorded public pins in existing-entry preflight so teardown rollback does not silently replace them with fresh DNS. Retain DNS admission checks, explicit pin refresh and the legacy unpinned path. Refs #13800 Signed-off-by: Deepak Jain --- docs/manage-sandboxes/manage-mcp-servers.mdx | 2 +- docs/reference/commands.mdx | 2 +- .../actions/sandbox/mcp-bridge-add-restart.ts | 14 ++- .../mcp-bridge-provider-inspection.test.ts | 46 ++++++++++ .../sandbox/mcp-bridge-provider-inspection.ts | 11 ++- .../mcp-bridge-restart-recovery.test.ts | 40 ++++++++- .../actions/sandbox/mcp-bridge-update.test.ts | 88 +++++++++++++++++++ .../sandbox/mcp-bridge/shared-host-pins.ts | 10 +-- 8 files changed, 200 insertions(+), 13 deletions(-) diff --git a/docs/manage-sandboxes/manage-mcp-servers.mdx b/docs/manage-sandboxes/manage-mcp-servers.mdx index 57ba6f6a0b1..12118bd7eb5 100644 --- a/docs/manage-sandboxes/manage-mcp-servers.mdx +++ b/docs/manage-sandboxes/manage-mcp-servers.mdx @@ -183,7 +183,7 @@ $$nemoclaw my-sandbox mcp update doordash \ The command changes only the live OpenShell policy. It does not change the agent-native endpoint, credential reference, provider, attachment, or agent adapter. Live policy is the enforcement source of truth; NemoClaw does not retain a second denied-tool intent record. -NemoClaw validates the current source entry and endpoint pins, removes the existing route, and then applies the replacement. This keeps an interrupted stricter update fail-closed. If replacement activation fails, the MCP route remains blocked and the error prints the exact `mcp update` command to retry. Rebuild captures and restores the complete live policy, including denied-tool rules, without regenerating it from registry state. +NemoClaw validates the current source entry and endpoint pins before replacing the route. For public endpoints, it validates DNS and retains revalidated recorded pins. Conflicting sibling pins stop the update before route removal. This keeps an interrupted stricter update fail-closed. If replacement activation fails, the MCP route remains blocked and the error prints the exact `mcp update` command to retry. Rebuild captures and restores the complete live policy, including denied-tool rules, without regenerating it from registry state. Clear every denied-tool rule explicitly: diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 89ec8733142..ecce3c6ca09 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3046,7 +3046,7 @@ Update the denied-tool list or refresh public address pins for one registered MC Both operations use the live OpenShell policy and preserve the agent-native endpoint, credential reference, provider, attachment, and agent adapter. Pass one or more `--deny-tool ` options, or pass `--clear-deny-tools` to remove every denied-tool rule. Use only one mode per command: `--deny-tool`, `--clear-deny-tools`, or `--refresh-public-pins`. -Live OpenShell policy is the enforcement source of truth; NemoClaw does not persist duplicate MCP intent. A denied-tool update validates the current source and address pins, removes the current route, and applies the replacement. If activation fails, the route remains blocked and the error prints the exact `mcp update` retry command. Rebuild captures and restores the complete live policy, including denied-tool rules. +Live OpenShell policy is the enforcement source of truth; NemoClaw does not persist duplicate MCP intent. A denied-tool update validates the current source and address pins, then checks sibling pin agreement before replacing the route. Public endpoints undergo DNS validation and retain revalidated recorded pins. If activation fails, the route remains blocked and the error prints the exact `mcp update` retry command. Rebuild captures and restores the complete live policy, including denied-tool rules. ```bash $$nemoclaw my-assistant mcp update github --deny-tool 'delete_*' --deny-tool 'admin_*' diff --git a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts index ebefed8937c..16fa8949a6c 100644 --- a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts +++ b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts @@ -686,12 +686,22 @@ async function updateMcpBridgeDenyToolsUnlocked( throw new McpBridgeError(`MCP server '${server}' not found on sandbox '${sandboxName}'.`); } assertAuthenticatedBridgeEntry(storedEntry); - const target = (await preflightMcpEntryTargets([storedEntry])).get(server); - if (!target || target.addresses.length === 0) { + const resolved = (await preflightMcpEntryTargets([storedEntry])).get(server); + if (!resolved || resolved.addresses.length === 0) { throw new McpBridgeError( `MCP server '${server}' has no validated address pins. No policy was changed.`, ); } + const aligned = alignMcpTargetWithSharedHostPins({ + operation: "update", + sandboxName, + server, + url: storedEntry.url, + target: resolved, + bridges: observed.bridges, + }); + if (!aligned.ok) throw new McpBridgeError(aligned.message, 2); + const target = aligned.target; const { denyTools: _previousDenyTools, ...entryWithoutDenyTools } = storedEntry; const updatedEntry: McpSourceEntry = { ...entryWithoutDenyTools, diff --git a/src/lib/actions/sandbox/mcp-bridge-provider-inspection.test.ts b/src/lib/actions/sandbox/mcp-bridge-provider-inspection.test.ts index 833039d7425..09c11d5c137 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider-inspection.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider-inspection.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import dns from "node:dns/promises"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -12,7 +13,9 @@ import { getMcpProviderInspectionRuntimeSelection, resolveSandboxConfigRuntimeSelection, inspectMcpProvider, + preflightMcpEntryTargets, } from "./mcp-bridge-provider-inspection"; +import type { McpSourceEntry } from "./mcp-bridge-contracts"; import * as gatewayTargets from "./gateway-target"; const temporaryDirectories: string[] = []; @@ -269,3 +272,46 @@ describe("MCP provider absence inspection", () => { }, ); }); + +describe("existing MCP target preflight", () => { + const entry: McpSourceEntry = { + server: "tools", + agent: "openclaw", + adapter: "openclaw-config", + url: "https://mcp.example.test/tools", + env: ["TOOLS_TOKEN"], + allowedIps: ["8.8.8.8"], + providerName: "alpha-mcp-tools", + providerId: "11111111-2222-4333-8444-555555555555", + policyName: "mcp-bridge-tools", + }; + + it("replays recorded public pins during update and rollback after fresh DNS validation", async () => { + const lookup = vi + .spyOn(dns, "lookup") + .mockResolvedValue([{ address: "1.1.1.1", family: 4 }] as never); + const targets = await preflightMcpEntryTargets([entry]); + expect(targets.get("tools")).toEqual({ addresses: ["8.8.8.8"] }); + expect(lookup).toHaveBeenCalled(); + }); + + it("rejects an invalid recorded public pin instead of replacing it with DNS", async () => { + vi.spyOn(dns, "lookup").mockResolvedValue([{ address: "1.1.1.1", family: 4 }] as never); + await expect( + preflightMcpEntryTargets([{ ...entry, allowedIps: ["127.0.0.1"] }]), + ).rejects.toThrow(/private, local, or special-use address pin/); + }); + + it("still rejects private DNS before replaying recorded public pins", async () => { + vi.spyOn(dns, "lookup").mockResolvedValue([{ address: "10.20.30.40", family: 4 }] as never); + await expect(preflightMcpEntryTargets([entry])).rejects.toThrow( + /private, local, or special-use/, + ); + }); + + it("keeps fresh public resolution for legacy entries without recorded pins", async () => { + vi.spyOn(dns, "lookup").mockResolvedValue([{ address: "1.1.1.1", family: 4 }] as never); + const targets = await preflightMcpEntryTargets([{ ...entry, allowedIps: undefined }]); + expect(targets.get("tools")).toEqual({ addresses: ["1.1.1.1"] }); + }); +}); diff --git a/src/lib/actions/sandbox/mcp-bridge-provider-inspection.ts b/src/lib/actions/sandbox/mcp-bridge-provider-inspection.ts index 1bc8c24de0d..ebec2d581b8 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider-inspection.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider-inspection.ts @@ -33,7 +33,10 @@ import type { SandboxEntry } from "../../state/registry/types"; import type { McpSourceEntry } from "./mcp-bridge-contracts"; import { getKnownSandboxTarget, getPersistedSandboxTargetGateway } from "./gateway-target"; import { McpBridgeError } from "./mcp-bridge-contracts"; -import type { McpBridgeTargetValidation } from "./mcp-bridge-url-validation"; +import { + parseMcpUrlWithValidatedTarget, + type McpBridgeTargetValidation, +} from "./mcp-bridge-url-validation"; import { assertAuthenticatedBridgeEntry, preflightMcpServerUrlResolvedTarget, @@ -516,7 +519,11 @@ export async function preflightMcpEntryTargets( }; return [entry.server, target] as const; } - const target = await preflightMcpServerUrlResolvedTarget(new URL(normalized)); + const resolved = await preflightMcpServerUrlResolvedTarget(new URL(normalized)); + // Existing registrations replay policy pins; changing them requires an + // explicit public-pin refresh, including during teardown rollback. + const target = entry.allowedIps?.length ? { addresses: [...entry.allowedIps] } : resolved; + parseMcpUrlWithValidatedTarget(normalized, target); return [entry.server, target] as const; }), ); diff --git a/src/lib/actions/sandbox/mcp-bridge-restart-recovery.test.ts b/src/lib/actions/sandbox/mcp-bridge-restart-recovery.test.ts index c6af0b20922..8c306a3b9cc 100644 --- a/src/lib/actions/sandbox/mcp-bridge-restart-recovery.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-restart-recovery.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import dns from "node:dns/promises"; import { beforeEach, describe, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ @@ -73,7 +74,8 @@ vi.mock("./mcp-bridge-status", async (importOriginal) => ({ ...(await importOriginal()), statusMcpBridge: mocks.status, })); -vi.mock("./mcp-bridge-validation", () => ({ +vi.mock("./mcp-bridge-validation", async (importOriginal) => ({ + ...(await importOriginal()), assertAuthenticatedBridgeEntry: vi.fn(), assertMcpCredentialBoundaryRuntimeVersion: vi.fn(), resolveCredentialEnv: vi.fn(() => ({})), @@ -81,6 +83,7 @@ vi.mock("./mcp-bridge-validation", () => ({ })); import { restartMcpBridge, restoreExistingMcpBridgeRuntime } from "./mcp-bridge-restart"; +import { applyGeneratedPolicy } from "./mcp-bridge-policy"; const entries = ["first", "second"].map((server) => ({ server, @@ -246,6 +249,41 @@ describe("OpenClaw MCP partial-mutation recovery", () => { ); }); + it("restores shared-host policy pins through real preflight despite differing DNS answers", async () => { + const shared = entries.map((entry) => ({ + ...entry, + url: `https://mcp.example.test/${entry.server}`, + allowedIps: ["8.8.8.8"], + })); + const { preflightMcpEntryTargets } = await vi.importActual< + typeof import("./mcp-bridge-provider-inspection") + >("./mcp-bridge-provider-inspection"); + mocks.preflightTargets.mockImplementationOnce(preflightMcpEntryTargets); + mocks.register.mockReset().mockResolvedValue(undefined); + const lookup = vi + .spyOn(dns, "lookup") + .mockResolvedValueOnce([{ address: "1.1.1.1", family: 4 }] as never) + .mockResolvedValue([{ address: "9.9.9.9", family: 4 }] as never); + try { + await restoreExistingMcpBridgeRuntime("alpha", shared, { + lifecyclePhase: "teardown-rollback", + }); + expect(lookup).toHaveBeenCalledTimes(2); + expect( + vi + .mocked(applyGeneratedPolicy) + .mock.calls.map((call) => [call[1].server, call[2].addresses]), + ).toEqual([ + ["first", ["8.8.8.8"]], + ["first", ["8.8.8.8"]], + ["second", ["8.8.8.8"]], + ["second", ["8.8.8.8"]], + ]); + } finally { + lookup.mockRestore(); + } + }); + it("reloads successful restoration using its recorded runtime", async () => { const runtimeSelection = { gatewayName: "recorded-gateway", diff --git a/src/lib/actions/sandbox/mcp-bridge-update.test.ts b/src/lib/actions/sandbox/mcp-bridge-update.test.ts index f73666a426c..142c138ced4 100644 --- a/src/lib/actions/sandbox/mcp-bridge-update.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-update.test.ts @@ -258,6 +258,94 @@ describe("source-backed MCP denied-tool policy updates", () => { } }); + it.each([ + ["replace", ["--deny-tool", "delete_*"]], + ["clear", ["--clear-deny-tools"]], + ])("keeps shared public pins when denied tools %s after DNS drift", async (_mode, flags) => { + const peer = { + ...entry, + server: "peer", + url: "https://mcp.example.test/peer", + env: ["PEER_TOKEN"], + providerName: "alpha-mcp-peer", + providerId: "22222222-3333-4444-8555-666666666666", + policyName: "mcp-bridge-peer", + }; + const bridges = { github: entry, peer }; + mocks.inspectSourceBridgeState.mockReturnValueOnce({ + bridges, + sources: { native: bridges, legacy: {} }, + }); + mocks.preflightMcpEntryTargets.mockResolvedValueOnce( + new Map([["github", { addresses: ["1.1.1.1"] }]]), + ); + + await dispatchMcpBridgeCommand("alpha", ["update", "github", ...flags]); + + expect(mocks.applyGeneratedPolicy).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ allowedIps: ["8.8.8.8"], env: ["GITHUB_TOKEN"] }), + { addresses: ["8.8.8.8"] }, + { runtimeSelection: { gatewayName: "nemoclaw-9090", workspace: "default" } }, + ); + expect(mocks.removeGeneratedPolicy.mock.invocationCallOrder[0]).toBeLessThan( + mocks.applyGeneratedPolicy.mock.invocationCallOrder[0], + ); + }); + + it.each([ + ["conflicting public pins on replace", ["delete_*"], ["9.9.9.9"], false, true], + ["conflicting public pins on clear", [], ["9.9.9.9"], false, true], + ["trusted-private sibling on replace", ["delete_*"], ["10.20.30.40"], true, false], + ["trusted-private sibling on clear", [], ["10.20.30.40"], true, false], + ["invalid public sibling pins on replace", ["delete_*"], ["127.0.0.1"], false, false], + ["invalid public sibling pins on clear", [], ["127.0.0.1"], false, false], + ])( + "rejects denied-tool changes before mutation with %s", + async (_label, denyTools, pins, privatePeer, conflict) => { + const peer = { + ...entry, + server: "peer", + url: "https://mcp.example.test/peer", + env: ["PEER_TOKEN"], + providerName: "alpha-mcp-peer", + providerId: "22222222-3333-4444-8555-666666666666", + policyName: "mcp-bridge-peer", + allowedIps: pins, + ...(privatePeer ? { trustedPrivateHost: "mcp.example.test" } : {}), + }; + const bridges = { + github: entry, + peer, + ...(conflict + ? { + third: { + ...peer, + server: "third", + url: "https://mcp.example.test/third", + env: ["THIRD_TOKEN"], + providerName: "alpha-mcp-third", + providerId: "33333333-4444-4555-8666-777777777777", + policyName: "mcp-bridge-third", + allowedIps: ["8.8.8.8"], + }, + } + : {}), + }; + mocks.inspectSourceBridgeState.mockReturnValue({ + bridges, + sources: { native: bridges, legacy: {} }, + }); + await expect(updateMcpBridgeDenyTools("alpha", "github", denyTools)).rejects.toThrow( + /not updated|private, local, or special-use address pin/, + ); + expect(mocks.ensureSandboxGatewaySelected).not.toHaveBeenCalled(); + expect(mocks.assertMcpProviderRecoverable).not.toHaveBeenCalled(); + expect(mocks.removeGeneratedPolicy).not.toHaveBeenCalled(); + expect(mocks.applyGeneratedPolicy).not.toHaveBeenCalled(); + }, + ); + it("removes the old route before applying and publishing the live replacement (#11115)", async () => { await updateMcpBridgeDenyTools("alpha", "github", ["submit_*", "delete_repo"]); diff --git a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts index 33a42cb0fcb..7e1dc68e8a5 100644 --- a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts +++ b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts @@ -11,7 +11,7 @@ export type McpSharedHostPinAlignment = | { ok: true; target: McpBridgeTargetValidation; - /** Servers whose recorded pins the new server reuses; empty when nothing changed. */ + /** Servers whose recorded public pins are reused. */ reusedFrom: string[]; } | { @@ -47,11 +47,9 @@ function describeServers(servers: readonly string[]): string { return servers.map((server) => `'${server}'`).join(", "); } -/** Keep endpoints on one host and port on a validated pin set before mutation. - * Adds may reuse public sibling pins; refreshes must not diverge from them. - */ +/** Align policy targets with recorded pins on the same host and port before mutation. */ export function alignMcpTargetWithSharedHostPins(options: { - operation: "add" | "refresh"; + operation: "add" | "update" | "refresh"; sandboxName: string; server: string; url: string; @@ -59,7 +57,7 @@ export function alignMcpTargetWithSharedHostPins(options: { bridges: Readonly>; }): McpSharedHostPinAlignment { const { operation, sandboxName, server, url, target, bridges } = options; - const action = operation === "add" ? "added" : "refreshed"; + const action = { add: "added", update: "updated", refresh: "refreshed" }[operation]; const authority = endpointAuthority(url); if (!authority) return { ok: true, target, reusedFrom: [] }; From 2ff29086708a123ad967d3c18e45c419eff3b22b Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 17 Nov 2026 06:34:32 -0800 Subject: [PATCH 05/17] docs(mcp): preserve live denied tools during recovery Record current denied-tool selectors before removing MCP registrations and pass them on re-add. Route recovery recipes to the owning procedure and direct CLI users there before removal. Signed-off-by: Deepak Jain --- docs/manage-sandboxes/manage-mcp-servers.mdx | 42 ++++++++----------- docs/reference/troubleshoot-mcp-servers.mdx | 36 ++++------------ .../mcp-bridge/shared-host-pins.test.ts | 5 ++- .../sandbox/mcp-bridge/shared-host-pins.ts | 2 +- 4 files changed, 32 insertions(+), 53 deletions(-) diff --git a/docs/manage-sandboxes/manage-mcp-servers.mdx b/docs/manage-sandboxes/manage-mcp-servers.mdx index 12118bd7eb5..9466f741e52 100644 --- a/docs/manage-sandboxes/manage-mcp-servers.mdx +++ b/docs/manage-sandboxes/manage-mcp-servers.mdx @@ -139,6 +139,11 @@ The bare `mcp list` and `mcp status` forms never probe, so they stay fast. Endpo ## Rotate a Credential +Before removal, inspect the live policy with `openshell policy get --full my-sandbox`. +Record the server's current denied-tool selectors from the `tool` fields of its `tools/call` deny rules. +These selectors can differ from the original add options after `mcp update`. +Keep the URL, credential variable name, and reviewed `--trusted-private-host` declaration. + Export the replacement under the same host environment name used by `mcp add`, then remove the native registration: ```bash @@ -148,8 +153,8 @@ $$nemoclaw my-sandbox mcp remove github `remove` deletes the agent-native registration and detaches the exact managed provider, but preserves the provider object. Confirm that no sandbox uses that provider before you delete it with `openshell provider delete `. -Keep the original URL, credential variable name, and any denied-tool or trusted-private options for the replacement. -Then add the server again to create a fresh provider binding: +Add the server again to create a fresh provider binding. +Append one `--deny-tool ''` option for each recorded selector to this command: ```bash $$nemoclaw my-sandbox mcp add github \ @@ -158,6 +163,9 @@ $$nemoclaw my-sandbox mcp add github \ unset GITHUB_MCP_TOKEN ``` +Inspect the live policy again and confirm that its denied-tool selectors match your record. +Tool discovery does not verify denied-tool enforcement. + For a trusted-private entry, pass the same reviewed `--trusted-private-host` value to `add`. For a public entry, `add` validates current DNS but reuses revalidated sibling pins when another managed server uses the same hostname and port. Remove-and-add therefore does not independently refresh shared public pins. @@ -220,10 +228,12 @@ A per-server refresh stops before mutation if its new DNS answers differ from a Adding or re-adding one public registration reuses the sibling pins instead of refreshing them. To change the shared pin set, plan an interruption for every affected registration. -Keep each server's original add options and re-export its credential from your secret manager before removal. +Before the first removal, record every server's endpoint options and current denied-tool selectors from live policy. +Re-export each credential from your secret manager. Remove every registration on that hostname and port, and complete the [retained-provider cleanup](#rotate-a-credential) for each one. -Add the servers again with their original options. +Add the servers again with their endpoint options and recorded selectors, passing one `--deny-tool` option per selector. The first public add records current validated DNS addresses; later adds reuse that set. +Confirm that each restored live denied-tool list matches your record. Run `mcp status --tools` for each server and confirm readiness and successful discovery. If DNS still differs from the recorded pins, coordinate the endpoint's DNS before repeating the procedure. @@ -231,26 +241,10 @@ If DNS still differs from the recorded pins, coordinate the endpoint's DNS befor For a trusted-private server, review every destination change before NemoClaw records new pins. Neither status, restart, rebuild, nor restore changes the recorded address set. -If the endpoint moves to another address, remove and re-add the server: - -```bash -export LOCAL_MCP_TOKEN='replace-with-secret-manager-value' -$$nemoclaw my-sandbox mcp remove local-tools -``` - -Complete the [retained-provider cleanup](#rotate-a-credential), then re-add the server: - -```bash -$$nemoclaw my-sandbox mcp add local-tools \ - --url https://mcp-host.corp.example/mcp \ - --env LOCAL_MCP_TOKEN \ - --trusted-private-host mcp-host.corp.example -unset LOCAL_MCP_TOKEN -``` - -Removing the server deletes the agent-native entry, removes its generated key from the current OpenShell policy, and detaches the provider. Complete the [retained-provider cleanup](#rotate-a-credential) before re-adding. -The re-add performs a new DNS preflight and records the reviewed exact address set. -For registrations sharing a hostname and port, coordinate removal and re-addition for all of them so their reviewed pins agree. +If the endpoint moves, follow [Rotate a Credential](#rotate-a-credential) to preserve current denied-tool selectors and replace the registration. +Pass the reviewed `--trusted-private-host` declaration and every recorded `--deny-tool` selector on re-add. +The re-add performs a new DNS preflight and records the reviewed address set. +For registrations sharing a hostname and port, follow [Refresh Shared-Host Registrations](#refresh-shared-host-registrations) so their reviewed pins agree. ## Remove a Server diff --git a/docs/reference/troubleshoot-mcp-servers.mdx b/docs/reference/troubleshoot-mcp-servers.mdx index fcb901a8528..2e87e777892 100644 --- a/docs/reference/troubleshoot-mcp-servers.mdx +++ b/docs/reference/troubleshoot-mcp-servers.mdx @@ -15,19 +15,8 @@ Use the reported status or lifecycle error to choose the matching remediation. If `mcp status ` reports identical placeholder and control rejections, first confirm the stored credential is valid. Restart validates and reloads the current provider-backed registration; it never consumes an exported replacement credential. -To replace the credential, follow the conservative remove and re-add procedure: - -```bash -export ='replacement-value' -$$nemoclaw mcp remove -# Confirm no sandbox uses the retained provider named by remove, then delete it. -openshell provider delete -$$nemoclaw mcp add --url --env -unset -``` - -Preserve the original denied-tool selectors and `--trusted-private-host` declaration on the re-add. -See [Rotate a Credential](../manage-sandboxes/mcp-servers/manage-mcp-servers#rotate-a-credential) for the complete provider-cleanup sequence. +To replace the credential, follow [Rotate a Credential](../manage-sandboxes/mcp-servers/manage-mcp-servers#rotate-a-credential). +That procedure preserves current denied-tool selectors before removal and verifies them after re-add. For identical HTTP 401 or 403 responses, a confirmed-valid credential means the OpenShell gateway on this host is not rewriting the recorded resolver placeholder on egress. Every agent request receives the same authentication failure even when provider, attachment, readiness, and adapter checks report healthy. @@ -51,11 +40,12 @@ Inspect the OpenShell gateway's ephemeral CA generation and CA-file initializati ## Provider Is Missing During Restart -If restart reports a missing provider, remove the native registration and re-add it with the same URL, credential environment name, denied-tool selectors, and trusted-private declaration. Restart does not recreate providers. +If restart reports a missing provider, follow [Rotate a Credential](../manage-sandboxes/mcp-servers/manage-mcp-servers#rotate-a-credential) to replace the registration and preserve current denied-tool selectors. +Restart does not recreate providers. ## Provider Uses the Legacy Generic Profile -If restart or rebuild reports that the provider uses the profile-less legacy `generic` type, remove that server and add it again with the recorded credential variable exported. +If restart or rebuild reports that the provider uses the profile-less legacy `generic` type, follow [Rotate a Credential](../manage-sandboxes/mcp-servers/manage-mcp-servers#rotate-a-credential). OpenShell cannot bind that provider to an MCP endpoint, and NemoClaw accepts it only for cleanup. ## Rebuild Cannot Prove a Credential Handle @@ -71,14 +61,7 @@ $$nemoclaw mcp status --json ``` If status cannot reach the sandbox, repair the reported gateway condition first. -Export the replacement under the same environment-variable name, then remove and re-add the server so a fresh provider binding and agent placeholder are created: - -```bash -export ='replacement-value' -$$nemoclaw mcp remove -$$nemoclaw mcp add --url --env -unset -``` +Follow [Rotate a Credential](../manage-sandboxes/mcp-servers/manage-mcp-servers#rotate-a-credential) to preserve current denied-tool selectors and create a fresh provider binding and agent placeholder. Run status again. OpenShell can retain the same `s…` stable handle after a provider update; verify endpoint authorization with the named `mcp status` probe. @@ -109,7 +92,7 @@ Keep the registration unchanged while status remains unavailable, conflicting, o For an interrupted `mcp add` that does not report an unknown outcome, inspect the native source and live status first. If no native registration exists, rerun the original command with the same URL, environment-variable name, and any `--deny-tool` options. -If the native registration exists, remove it and then re-add it after re-exporting the credential. +If the native registration exists, follow [Rotate a Credential](../manage-sandboxes/mcp-servers/manage-mcp-servers#rotate-a-credential) to preserve current denied-tool selectors during replacement. To abandon the transaction, run `mcp remove --force`. NemoClaw disables the native agent entry first and cleans only live resources whose ownership it can prove. It preserves the workspace provider and reports any residual policy or attachment cleanup. @@ -434,7 +417,7 @@ $$nemoclaw mcp status --tools The refresh preserves all other policy fields, including denied tools, and retains the existing agent configuration and credentials. If another managed registration uses the same hostname and port, refresh refuses DNS answers that differ from its pins before changing policy. Follow [Refresh Shared-Host Registrations](../manage-sandboxes/mcp-servers/manage-mcp-servers#refresh-shared-host-registrations) to coordinate that change. -Successful tool discovery verifies recovery. +Successful tool discovery verifies endpoint reachability. Status, restart, rebuild, and restore preserve the live pins. If refresh cannot confirm a write, inspect status and the live OpenShell policy before retrying. @@ -446,8 +429,7 @@ Retry status after DNS recovers. If status reports `private address pins: drift`, review the endpoint address change before updating access. Status, restart, rebuild, and restore do not add new trusted-private addresses. -Follow [Change Trusted-Private Pins](../manage-sandboxes/mcp-servers/manage-mcp-servers#change-trusted-private-pins) to re-export the credential, remove the registration, clean up its retained provider, and re-add with reviewed pins. -Confirm that no other sandbox uses the retained provider before deleting it. +Follow [Change Trusted-Private Pins](../manage-sandboxes/mcp-servers/manage-mcp-servers#change-trusted-private-pins) to replace the registration with reviewed pins and preserve its current denied-tool selectors. A `CONNECT 403` after an address change can mean that OpenShell rejected a current DNS answer outside `allowed_ips`. Do not add a provider's complete address range or broaden the policy to bypass the denial. diff --git a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts index acf531191a7..413b0cf244e 100644 --- a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts @@ -163,7 +163,10 @@ describe("MCP shared-host address pins", () => { expect(message).toContain("Removal preserves providers"); expect(message).toContain("explicit provider cleanup"); expect(message).toContain("no other sandbox uses them"); - expect(message).toContain("manage-mcp-servers#rotate-a-credential"); + expect(message).toMatch( + /Before removing.*follow .*manage-mcp-servers#rotate-a-credential to record current denied-tool selectors/, + ); + expect(message).toContain("Re-add with the recorded selectors"); }); it("accepts trusted-private siblings whose pins already match", () => { diff --git a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts index 7e1dc68e8a5..01eac28e83c 100644 --- a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts +++ b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts @@ -61,7 +61,7 @@ export function alignMcpTargetWithSharedHostPins(options: { const authority = endpointAuthority(url); if (!authority) return { ok: true, target, reusedFrom: [] }; - const recovery = `Before removing registrations with \`nemoclaw ${sandboxName} mcp remove \`, re-export the affected credential variables. Removal preserves providers. Perform explicit provider cleanup only after confirming no other sandbox uses them. Follow https://docs.nvidia.com/nemoclaw/latest/user-guide/openclaw/manage-sandboxes/mcp-servers/manage-mcp-servers#rotate-a-credential before adding the servers again.`; + const recovery = `Before removing registrations with \`nemoclaw ${sandboxName} mcp remove \`, follow https://docs.nvidia.com/nemoclaw/latest/user-guide/openclaw/manage-sandboxes/mcp-servers/manage-mcp-servers#rotate-a-credential to record current denied-tool selectors and re-export the affected credential variables. Removal preserves providers. Perform explicit provider cleanup only after confirming no other sandbox uses them. Re-add with the recorded selectors.`; const groups = new Map(); for (const entry of Object.values(bridges)) { if ( From 88494d1733e41e07a9f9d9e54a0184f1a4929a09 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 17 Nov 2026 07:24:56 -0800 Subject: [PATCH 06/17] fix(mcp): normalize recorded public pins before replay Sort copies of public policy pins before replay and compare public add intent by canonical pin order. Preserve the operator's recorded list and retain trusted-private ordering and validation checks. Extend preflight, process-isolated retry and real-preflight rollback coverage with reversed public pins. Refs #13800. Signed-off-by: Deepak Jain --- src/lib/actions/sandbox/mcp-bridge-add-restart.ts | 11 ++++++----- .../sandbox/mcp-bridge-input-targets.test.ts | 11 +++++++---- .../sandbox/mcp-bridge-provider-inspection.test.ts | 10 ++++++---- .../sandbox/mcp-bridge-provider-inspection.ts | 4 +++- .../sandbox/mcp-bridge-restart-recovery.test.ts | 14 +++++++++----- 5 files changed, 31 insertions(+), 19 deletions(-) diff --git a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts index 16fa8949a6c..816c72f5360 100644 --- a/src/lib/actions/sandbox/mcp-bridge-add-restart.ts +++ b/src/lib/actions/sandbox/mcp-bridge-add-restart.ts @@ -96,6 +96,9 @@ import { import { waitForMcpBridgeConditionAsync } from "./mcp-bridge/timing"; function sameMcpAddIntent(existing: McpSourceEntry, requested: McpSourceEntry): boolean { + const existingPins = existing.trustedPrivateHost + ? (existing.allowedIps ?? []) + : [...(existing.allowedIps ?? [])].sort(); return ( existing.server === requested.server && existing.agent === requested.agent && @@ -106,10 +109,8 @@ function sameMcpAddIntent(existing: McpSourceEntry, requested: McpSourceEntry): existing.trustedPrivateHost === requested.trustedPrivateHost && (existing.denyTools?.length ?? 0) === (requested.denyTools?.length ?? 0) && (existing.denyTools ?? []).every((tool, index) => tool === requested.denyTools?.[index]) && - (existing.allowedIps?.length ?? 0) === (requested.allowedIps?.length ?? 0) && - (existing.allowedIps ?? []).every( - (address, index) => address === requested.allowedIps?.[index], - ) && + existingPins.length === (requested.allowedIps?.length ?? 0) && + existingPins.every((address, index) => address === requested.allowedIps?.[index]) && existing.env.length === requested.env.length && existing.env.every((name, index) => name === requested.env[index]) ); @@ -149,7 +150,7 @@ function replayMcpAddTarget( ); } } - const target = { addresses: [...recordedPins] }; + const target = { addresses: [...recordedPins].sort() }; // Public policy pins are part of the committed transaction. Validate them // again, but do not replace them with a later DNS answer during an exact // retry; OpenShell must continue enforcing the originally admitted set. diff --git a/src/lib/actions/sandbox/mcp-bridge-input-targets.test.ts b/src/lib/actions/sandbox/mcp-bridge-input-targets.test.ts index 309f6e48ba9..e6cece792a8 100644 --- a/src/lib/actions/sandbox/mcp-bridge-input-targets.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-input-targets.test.ts @@ -398,6 +398,7 @@ const expectFailure = phase === "policy-url-mismatch" || stableUnauthorized || u let authorizationProbe; if (phase === "provider-hostless") delete process.env.GITHUB_TOKEN; const providerId = "11111111-2222-4333-8444-555555555555"; +const recordedPins = ["8.8.8.8", "1.1.1.1"]; const state = { policy: ["policy", "policy-url-mismatch", "provider", "provider-hostless", "attachment"].includes(seedPhase) ? "capability" : seedPhase === "bound-policy" || seedPhase === "adapter" ? "bound" : "absent", provider: ["provider", "provider-hostless", "attachment", "bound-policy", "adapter"].includes(seedPhase), @@ -419,7 +420,7 @@ const commandTransport = require("./src/lib/adapters/sandbox/command-transport.j const entry = () => ({ server: "github", agent: "openclaw", adapter: "openclaw-config", url: "https://8.8.8.8/mcp", env: ["GITHUB_TOKEN"], - allowedIps: ["8.8.8.8"], providerName: "alpha-mcp-github", + allowedIps: recordedPins, providerName: "alpha-mcp-github", ...(state.provider ? { providerId } : {}), policyName: "mcp-bridge-github", source: "native", }); @@ -462,7 +463,7 @@ replace(policies, "getPresetContentGatewayState", (_sandbox, content) => { if (state.policy === "absent") return "absent"; if (phase === "policy-url-mismatch") return "drift"; const expected = content.includes("credential_binding") ? "bound" : "capability"; - return state.policy === expected && content.includes("8.8.8.8") ? "match" : "drift"; + return state.policy === expected && content.includes("8.8.8.8") && content.includes("1.1.1.1") ? "match" : "drift"; }); replace(policies, "applyPresetContent", (_sandbox, _name, content) => { state.policy = content.includes("credential_binding") ? "bound" : "capability"; @@ -490,7 +491,7 @@ require("./src/lib/actions/sandbox/mcp-bridge.js").addMcpBridge("alpha", { server: "github", url: "https://8.8.8.8/mcp", env: [{ name: "GITHUB_TOKEN" }], }).then(() => { if (expectFailure) process.exit(2); - process.stdout.write(JSON.stringify({ state }), () => process.exit(0)); + process.stdout.write(JSON.stringify({ state, recordedPins }), () => process.exit(0)); }, async (error) => { if (!expectFailure) { process.stderr.write(String(error && error.stack || error), () => process.exit(1)); @@ -502,7 +503,7 @@ require("./src/lib/actions/sandbox/mcp-bridge.js").addMcpBridge("alpha", { } process.stdout.write(JSON.stringify({ message: String(error && error.message || error), - state, authorizationProbe, beforeOrdinaryRemoval, + state, authorizationProbe, beforeOrdinaryRemoval, recordedPins, }), () => process.exit(0)); }); `; @@ -524,7 +525,9 @@ require("./src/lib/actions/sandbox/mcp-bridge.js").addMcpBridge("alpha", { const outcome = trailingJsonPayload<{ message?: string; state: Record; + recordedPins: string[]; }>(result.stdout); + expect(outcome.recordedPins).toEqual(["8.8.8.8", "1.1.1.1"]); expect(outcome).toMatchObject( phase === "policy-url-mismatch" ? { diff --git a/src/lib/actions/sandbox/mcp-bridge-provider-inspection.test.ts b/src/lib/actions/sandbox/mcp-bridge-provider-inspection.test.ts index 09c11d5c137..9e11bc73e1d 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider-inspection.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider-inspection.test.ts @@ -286,12 +286,14 @@ describe("existing MCP target preflight", () => { policyName: "mcp-bridge-tools", }; - it("replays recorded public pins during update and rollback after fresh DNS validation", async () => { + it("replays sorted public pins without mutating recorded order after fresh DNS validation", async () => { + const pins = ["8.8.8.8", "1.1.1.1"]; const lookup = vi .spyOn(dns, "lookup") - .mockResolvedValue([{ address: "1.1.1.1", family: 4 }] as never); - const targets = await preflightMcpEntryTargets([entry]); - expect(targets.get("tools")).toEqual({ addresses: ["8.8.8.8"] }); + .mockResolvedValue([{ address: "9.9.9.9", family: 4 }] as never); + const targets = await preflightMcpEntryTargets([{ ...entry, allowedIps: pins }]); + expect(targets.get("tools")).toEqual({ addresses: ["1.1.1.1", "8.8.8.8"] }); + expect(pins).toEqual(["8.8.8.8", "1.1.1.1"]); expect(lookup).toHaveBeenCalled(); }); diff --git a/src/lib/actions/sandbox/mcp-bridge-provider-inspection.ts b/src/lib/actions/sandbox/mcp-bridge-provider-inspection.ts index ebec2d581b8..faf4e96c724 100644 --- a/src/lib/actions/sandbox/mcp-bridge-provider-inspection.ts +++ b/src/lib/actions/sandbox/mcp-bridge-provider-inspection.ts @@ -522,7 +522,9 @@ export async function preflightMcpEntryTargets( const resolved = await preflightMcpServerUrlResolvedTarget(new URL(normalized)); // Existing registrations replay policy pins; changing them requires an // explicit public-pin refresh, including during teardown rollback. - const target = entry.allowedIps?.length ? { addresses: [...entry.allowedIps] } : resolved; + const target = entry.allowedIps?.length + ? { addresses: [...entry.allowedIps].sort() } + : resolved; parseMcpUrlWithValidatedTarget(normalized, target); return [entry.server, target] as const; }), diff --git a/src/lib/actions/sandbox/mcp-bridge-restart-recovery.test.ts b/src/lib/actions/sandbox/mcp-bridge-restart-recovery.test.ts index 8c306a3b9cc..1ea2600a030 100644 --- a/src/lib/actions/sandbox/mcp-bridge-restart-recovery.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-restart-recovery.test.ts @@ -253,7 +253,7 @@ describe("OpenClaw MCP partial-mutation recovery", () => { const shared = entries.map((entry) => ({ ...entry, url: `https://mcp.example.test/${entry.server}`, - allowedIps: ["8.8.8.8"], + allowedIps: ["8.8.8.8", "1.1.1.1"], })); const { preflightMcpEntryTargets } = await vi.importActual< typeof import("./mcp-bridge-provider-inspection") @@ -274,10 +274,14 @@ describe("OpenClaw MCP partial-mutation recovery", () => { .mocked(applyGeneratedPolicy) .mock.calls.map((call) => [call[1].server, call[2].addresses]), ).toEqual([ - ["first", ["8.8.8.8"]], - ["first", ["8.8.8.8"]], - ["second", ["8.8.8.8"]], - ["second", ["8.8.8.8"]], + ["first", ["1.1.1.1", "8.8.8.8"]], + ["first", ["1.1.1.1", "8.8.8.8"]], + ["second", ["1.1.1.1", "8.8.8.8"]], + ["second", ["1.1.1.1", "8.8.8.8"]], + ]); + expect(shared.map((entry) => entry.allowedIps)).toEqual([ + ["8.8.8.8", "1.1.1.1"], + ["8.8.8.8", "1.1.1.1"], ]); } finally { lookup.mockRestore(); From 72cbc963daa70ce4c25e2bde8b106055c0c259c2 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Tue, 17 Nov 2026 09:18:53 -0800 Subject: [PATCH 07/17] test(mcp): cover shared-host composition for every agent Run the existing shared-host composition proof during common agent preparation, using each adapter for registration, cleanup and runtime attribution. Preserve the policy, credential, strict denial and absence assertions without growing the approved assertion budget. Cover adapter forwarding and probe runtime selection in the existing fast fixture tests. Refs #13800. Signed-off-by: Deepak Jain --- test/e2e/live/mcp-bridge-reliability.ts | 9 +- test/e2e/live/mcp-bridge-shared-host.ts | 20 ++++- test/e2e/live/mcp-bridge.test.ts | 39 ++++---- .../support/mcp-bridge-shared-host.test.ts | 90 ++++++++++++++++++- 4 files changed, 133 insertions(+), 25 deletions(-) diff --git a/test/e2e/live/mcp-bridge-reliability.ts b/test/e2e/live/mcp-bridge-reliability.ts index 6aac59ab4e4..1ec2468c92a 100644 --- a/test/e2e/live/mcp-bridge-reliability.ts +++ b/test/e2e/live/mcp-bridge-reliability.ts @@ -435,13 +435,20 @@ export async function runMcpProviderRewriteProbe( artifactName: string, credentialKey = "FAKE_MCP_SECRET", toolName?: string, + adapter: McpAdapter = "openclaw-config", ): Promise { + // Keep the admitted Python interpreter as an ancestor of the Node probe, + // matching the runtime attribution used by the existing rebinding probe. + const runtime = + adapter === "openclaw-config" + ? "node" + : `${adapter === "hermes-config" ? "/opt/hermes/.venv/bin/python" : "/opt/venv/bin/python3"} -c ${shellQuote("import subprocess, sys; raise SystemExit(subprocess.run(sys.argv[1:], check=False).returncode)")} node`; return sandbox.execShell( sandboxName, trustedSandboxShellScript( [ "set -eu", - `nemoclaw-start node - ${shellQuote(targetUrl)} ${shellQuote(method)} ${shellQuote(expectation)} ${shellQuote(credentialKey)}${toolName ? ` ${shellQuote(toolName)}` : ""} <<'NEMOCLAW_MCP_PROVIDER_REWRITE_PROBE'`, + `nemoclaw-start ${runtime} - ${shellQuote(targetUrl)} ${shellQuote(method)} ${shellQuote(expectation)} ${shellQuote(credentialKey)}${toolName ? ` ${shellQuote(toolName)}` : ""} <<'NEMOCLAW_MCP_PROVIDER_REWRITE_PROBE'`, MCP_PROVIDER_REWRITE_PROBE_SOURCE, "NEMOCLAW_MCP_PROVIDER_REWRITE_PROBE", ].join("\n"), diff --git a/test/e2e/live/mcp-bridge-shared-host.ts b/test/e2e/live/mcp-bridge-shared-host.ts index 07fb9f02c47..786fa91ad89 100644 --- a/test/e2e/live/mcp-bridge-shared-host.ts +++ b/test/e2e/live/mcp-bridge-shared-host.ts @@ -16,7 +16,8 @@ import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; import { MCP_BRIDGE_TEST_CREDENTIALS } from "../fixtures/mcp-bridge-credentials.ts"; import type { TestProgress } from "../fixtures/progress.ts"; import { buildMcpBridgePolicyKey } from "../../../src/lib/actions/sandbox/mcp-bridge-policy-render"; -import { cleanupMcpBridge } from "./mcp-bridge-cleanup.ts"; +import { cleanupMcpBridge, type McpAdapter } from "./mcp-bridge-cleanup.ts"; +import { approveOpenClawAdminScope } from "./openclaw-admin-scope.ts"; import { addBridgeAndReadStatus, runMcpProviderRewriteProbe } from "./mcp-bridge-reliability.ts"; import { captureManagedMcpPolicy, expectExitNonZero } from "./mcp-bridge-sandbox.ts"; import { startFakeMcpHttpsServer, startPublicMcpHttpsTunnel } from "./mcp-bridge-servers.ts"; @@ -63,6 +64,7 @@ dns.lookup = async (hostname, options) => { } export async function assertSharedHostMcpComposition(options: { + adapter: McpAdapter; host: HostCliClient; sandbox: SandboxClient; cleanup: CleanupRegistry; @@ -70,7 +72,13 @@ export async function assertSharedHostMcpComposition(options: { progress: TestProgress; sandboxName: string; }): Promise { - const { host, sandbox, cleanup, artifacts, progress, sandboxName } = options; + const { adapter, host, sandbox, cleanup, artifacts, progress, sandboxName } = options; + if (adapter === "openclaw-config") { + await approveOpenClawAdminScope(host, sandbox, sandboxName, buildAvailabilityProbeEnv(), [ + MCP_BRIDGE_TEST_CREDENTIALS.compatibleEndpoint, + MCP_BRIDGE_TEST_CREDENTIALS.host, + ]); + } const endpoint = await startFakeMcpHttpsServer({ secret: MCP_BRIDGE_TEST_CREDENTIALS.host, additionalPaths: { "/mcp-peer": MCP_BRIDGE_TEST_CREDENTIALS.rotatedHost }, @@ -120,7 +128,7 @@ export async function assertSharedHostMcpComposition(options: { const provider = `${sandboxName}-mcp-${entry.server}`; const run = async () => { if (complete) return; - await cleanupMcpBridge(host, sandboxName, entry.server, "openclaw-config"); + await cleanupMcpBridge(host, sandboxName, entry.server, adapter); const deleted = await host.command( host.openshellCommandPath, ["provider", "delete", provider], @@ -145,7 +153,7 @@ export async function assertSharedHostMcpComposition(options: { addBridgeAndReadStatus(host, sandbox, { sandboxName, mcpUrl: `${tunnel.origin}${entry.pathname}`, - expectedAdapter: "openclaw-config", + expectedAdapter: adapter, artifactPrefix: entry.server, serverName: entry.server, credentialEnvName: entry.key, @@ -173,6 +181,8 @@ export async function assertSharedHostMcpComposition(options: { "allow", `${entry.server}-authenticated`, entry.key, + undefined, + adapter, ); assertExitZero(accepted, `${entry.server} authenticated request after both adds`); const observed = endpoint.requests @@ -195,6 +205,8 @@ export async function assertSharedHostMcpComposition(options: { "deny-strict", `${entry.server}-outside-binding`, entry.key, + undefined, + adapter, ); assertExitZero(denied, `${entry.server} credential cannot reach an unconfigured path`); } diff --git a/test/e2e/live/mcp-bridge.test.ts b/test/e2e/live/mcp-bridge.test.ts index f5acae8e4d3..bf8ca2ff9f7 100644 --- a/test/e2e/live/mcp-bridge.test.ts +++ b/test/e2e/live/mcp-bridge.test.ts @@ -14,9 +14,10 @@ import { shellQuote } from "../../../src/lib/core/shell-quote"; import type { McpSourceEntry } from "../../../src/lib/actions/sandbox/mcp-bridge-contracts"; import { execTimeout, testTimeout } from "../../helpers/timeouts.ts"; import type { ArtifactSink } from "../fixtures/artifacts.ts"; -import { approveOpenClawAdminScope } from "./openclaw-admin-scope.ts"; +import { loadAgent } from "../../../src/lib/agent/defs"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; import type { CleanupRegistry } from "../fixtures/cleanup.ts"; +import type { TestProgress } from "../fixtures/progress.ts"; import { assertExitZero as expectExitZero, resultText } from "../fixtures/clients/command.ts"; import type { HostCliClient } from "../fixtures/clients/host.ts"; import { type SandboxClient, trustedSandboxShellScript } from "../fixtures/clients/sandbox.ts"; @@ -139,6 +140,8 @@ async function onboardAgent( agent: McpAgent; sandboxName: string; artifactName: string; + artifacts: ArtifactSink; + progress: TestProgress; envOverlay?: NodeJS.ProcessEnv; }, ): Promise { @@ -177,6 +180,15 @@ async function onboardAgent( }); expectExitZero(result, `onboard ${options.agent} sandbox for MCP bridge`); assertMcpBridgeManagedRegistryReceipt(options.sandboxName, options.agent, REGISTRY_FILE); + await assertSharedHostMcpComposition({ + host, + sandbox, + cleanup, + artifacts: options.artifacts, + progress: options.progress, + sandboxName: options.sandboxName, + adapter: loadAgent(options.agent).mcpCapability.adapter!, + }); } async function assertSecretAbsentFromSandbox( sandbox: SandboxClient, @@ -727,16 +739,11 @@ test( await onboardAgent(host, sandbox, cleanup, endpointUrl, { ...bridge, artifactName: "onboard-openclaw-mcp-bridge", + artifacts, + progress, }); - await approveOpenClawAdminScope( - host, - sandbox, - OPENCLAW_SANDBOX_NAME, - buildAvailabilityProbeEnv(), - [COMPATIBLE_KEY, HOST_SECRET], - ); - // Prove raw OpenShell allowed_ips with curl and a /** grant before MCP - // mutation. The helper restores the exact base policy before returning. + // Prove raw OpenShell allowed_ips with curl and a /** grant before ordinary + // lifecycle checks. The helper restores the exact base policy before returning. await runFullMcpBridgeE2eCoverage(mcpBridgeE2eScope, () => assertRawOpenShellAllowedIpsRebindingDenied({ artifacts, @@ -855,14 +862,6 @@ test( openClawToolSearch.toolNames = ["fake__fake_echo"]; } await cleanupMcpBridge(host, OPENCLAW_SANDBOX_NAME, "distinct", "openclaw-config"); - await assertSharedHostMcpComposition({ - host, - sandbox, - cleanup, - artifacts, - progress, - sandboxName: OPENCLAW_SANDBOX_NAME, - }); await assertBridgeInfrastructure(host, sandbox, { ...bridge, providerName, @@ -1118,6 +1117,8 @@ mcpBridgeShardTest("hermes")( await onboardAgent(host, sandbox, cleanup, endpointUrl, { ...bridge, artifactName: "onboard-hermes-mcp-bridge", + artifacts, + progress, }); cleanup.add("remove Hermes MCP bridge", () => cleanupMcpBridge(host, HERMES_SANDBOX_NAME, SERVER_NAME, "hermes-config"), @@ -1351,6 +1352,8 @@ mcpBridgeShardTest("deepagents")( await onboardAgent(host, sandbox, cleanup, endpointUrl, { ...bridge, artifactName: "onboard-deepagents-mcp-bridge", + artifacts, + progress, envOverlay: exactMainProof.envOverlay, }); await exactMainProof.afterOnboard(); diff --git a/test/e2e/support/mcp-bridge-shared-host.test.ts b/test/e2e/support/mcp-bridge-shared-host.test.ts index 2cf9aa6aced..208270fb190 100644 --- a/test/e2e/support/mcp-bridge-shared-host.test.ts +++ b/test/e2e/support/mcp-bridge-shared-host.test.ts @@ -2,16 +2,25 @@ // SPDX-License-Identifier: Apache-2.0 import { execFileSync } from "node:child_process"; +import dns from "node:dns/promises"; import fs from "node:fs"; import https from "node:https"; import path from "node:path"; -import { afterAll, expect, it } from "vitest"; +import { afterAll, afterEach, expect, it, vi } from "vitest"; import { createMcpFixtureTls } from "../fixtures/mcp-fixture-tls.ts"; -import { withMcpDnsAnswers } from "../live/mcp-bridge-shared-host.ts"; +import { + assertSharedHostMcpComposition, + withMcpDnsAnswers, +} from "../live/mcp-bridge-shared-host.ts"; +import * as bridgeCleanup from "../live/mcp-bridge-cleanup.ts"; +import * as reliability from "../live/mcp-bridge-reliability.ts"; +import * as servers from "../live/mcp-bridge-servers.ts"; +import * as adminScope from "../live/openclaw-admin-scope.ts"; import { startFakeMcpHttpsServer } from "../live/mcp-bridge-servers.ts"; const { tls, close } = createMcpFixtureTls(); afterAll(close); +afterEach(() => vi.restoreAllMocks()); it("controls only the selected host lookup and removes its DNS preload afterward", async () => { const answers = [ @@ -95,3 +104,80 @@ it("authenticates each MCP path with its own credential through real HTTPS", asy await server.close(); } }); + +it.each(["openclaw-config", "hermes-config", "deepagents-config"] as const)( + "passes %s through shared-host registration and partial-failure cleanup", + async (adapter) => { + type Options = Parameters[0]; + vi.spyOn(adminScope, "approveOpenClawAdminScope").mockResolvedValue(); + vi.spyOn(servers, "startFakeMcpHttpsServer").mockResolvedValue({ + close: vi.fn(), + } as unknown as Awaited>); + vi.spyOn(servers, "startPublicMcpHttpsTunnel").mockResolvedValue({ + origin: "https://shared.example.test", + } as Awaited>); + vi.spyOn(dns, "lookup").mockResolvedValue([ + { address: "8.8.8.8", family: 4 }, + { address: "8.8.4.4", family: 4 }, + ] as never); + const add = vi + .spyOn(reliability, "addBridgeAndReadStatus") + .mockRejectedValue(new Error("stop after registration handoff")); + const remove = vi.spyOn(bridgeCleanup, "cleanupMcpBridge").mockResolvedValue(); + const host = { + command: vi.fn().mockResolvedValue({ exitCode: 0, stdout: "", stderr: "" }), + openshellCommandPath: "openshell", + } as unknown as Options["host"]; + const cleanup = { add: vi.fn() }; + await expect( + assertSharedHostMcpComposition({ + adapter, + host, + sandbox: {} as Options["sandbox"], + cleanup: cleanup as unknown as Options["cleanup"], + artifacts: { writeJson: vi.fn() } as unknown as Options["artifacts"], + progress: {} as Options["progress"], + sandboxName: "alpha", + }), + ).rejects.toThrow("stop after registration handoff"); + expect(add).toHaveBeenCalledWith( + host, + expect.anything(), + expect.objectContaining({ + expectedAdapter: adapter, + serverName: "shared-one", + credentialEnvName: "SHARED_ONE_MCP_SECRET", + }), + ); + const cleanupEntry = cleanup.add.mock.calls.find( + ([name]) => name === "remove shared-host MCP registration and provider shared-one", + ); + await cleanupEntry![1](); + expect(remove).toHaveBeenCalledWith(host, "alpha", "shared-one", adapter); + }, +); + +it.each([ + ["openclaw-config", "nemoclaw-start node -"], + ["hermes-config", "nemoclaw-start /opt/hermes/.venv/bin/python -c"], + ["deepagents-config", "nemoclaw-start /opt/venv/bin/python3 -c"], +] as const)("uses the admitted %s runtime for credential probes", async (adapter, runtime) => { + const result = { exitCode: 0, stdout: "", stderr: "" }; + const execShell = vi.fn().mockResolvedValue(result); + type Sandbox = Parameters[0]; + expect( + await reliability.runMcpProviderRewriteProbe( + { execShell } as unknown as Sandbox, + "alpha", + "https://shared.example.test/mcp", + "tools/list", + "allow", + "shared-host-probe", + "SHARED_ONE_MCP_SECRET", + undefined, + adapter, + ), + ).toBe(result); + expect(execShell.mock.calls[0][1]).toContain(runtime); + expect(execShell.mock.calls[0][1]).toContain("SHARED_ONE_MCP_SECRET"); +}); From c8c8a45f95cbbbb93e9b8107f4615af04d564c2a Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 18 Nov 2026 20:07:15 -0800 Subject: [PATCH 08/17] fix(mcp): reconcile shared pins across policy conflicts Signed-off-by: Deepak Jain --- .../actions/sandbox/mcp-bridge-contracts.ts | 4 +- .../actions/sandbox/mcp-bridge-source.test.ts | 42 +++++ src/lib/actions/sandbox/mcp-bridge-source.ts | 1 + .../actions/sandbox/mcp-bridge-update.test.ts | 41 ++++- .../mcp-bridge/shared-host-pins.test.ts | 151 ++++++++++++++++-- .../sandbox/mcp-bridge/shared-host-pins.ts | 14 +- 6 files changed, 234 insertions(+), 19 deletions(-) diff --git a/src/lib/actions/sandbox/mcp-bridge-contracts.ts b/src/lib/actions/sandbox/mcp-bridge-contracts.ts index fadac7ca70e..08b282b9852 100644 --- a/src/lib/actions/sandbox/mcp-bridge-contracts.ts +++ b/src/lib/actions/sandbox/mcp-bridge-contracts.ts @@ -49,8 +49,10 @@ export interface McpSourceEntry { denyTools?: string[]; /** Where the current agent registration was observed. */ source?: "native" | "legacy" | "legacy-registry" | "policy"; - /** Live policy endpoint differs from the agent-native URL. */ + /** Live policy cannot be reconciled with the agent registration. */ policyConflict?: string; + /** Live policy endpoint differs from the agent-native URL. */ + policyEndpointConflict?: boolean; } export interface McpBridgeAddOptions extends ParsedMcpAddArgs {} diff --git a/src/lib/actions/sandbox/mcp-bridge-source.test.ts b/src/lib/actions/sandbox/mcp-bridge-source.test.ts index e5a96f60aa1..67999e4e979 100644 --- a/src/lib/actions/sandbox/mcp-bridge-source.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-source.test.ts @@ -57,6 +57,7 @@ import { inspectLegacyBridgeState, inspectPolicyOnlyMcpEntry, inspectSourceBridgeState, + joinMcpEntriesToOpenShell, } from "./mcp-bridge-source"; const sandbox = { @@ -439,6 +440,47 @@ network_policies: ).toContain("differs from live policy endpoint"); }); + it.each([ + ["matching endpoint", "api.githubcopilot.com", 443, "/mcp/", undefined], + ["different host", "other.example.com", 443, "/mcp/", true], + ["different path", "api.githubcopilot.com", 443, "/renamed", true], + ["different port", "api.githubcopilot.com", 8443, "/mcp/", true], + ])( + "retains endpoint identity with invalid denied tools and a %s", + async (_label, host, port, endpointPath, conflict) => { + mocks.capturePolicy.mockResolvedValue(`network_policies: + mcp_bridge_github: + endpoints: + - host: ${host} + port: ${port} + path: ${endpointPath} + protocol: mcp + allowed_ips: ["8.8.8.8"] + deny_rules: + - method: tools/call + tool: "invalid selector!" +`); + const bridges = await joinMcpEntriesToOpenShell( + sandbox, + { + github: { + server: "github", + agent: "openclaw", + url: "https://api.githubcopilot.com/mcp/", + env: ["GITHUB_TOKEN"], + policyName: "mcp-bridge-github", + }, + }, + runtimeSelection, + ); + expect(bridges.github.policyConflict).toBe( + "Live policy contains invalid denied-tool selectors.", + ); + expect(bridges.github.policyEndpointConflict).toBe(conflict); + expect(bridges.github.allowedIps).toEqual(["8.8.8.8"]); + }, + ); + it("redacts credentials and strips terminal controls from source-read failures", async () => { mocks.executeSandboxExecCommand.mockReturnValue({ status: 2, diff --git a/src/lib/actions/sandbox/mcp-bridge-source.ts b/src/lib/actions/sandbox/mcp-bridge-source.ts index 16da02ee02e..368577f6a3e 100644 --- a/src/lib/actions/sandbox/mcp-bridge-source.ts +++ b/src/lib/actions/sandbox/mcp-bridge-source.ts @@ -648,6 +648,7 @@ async function enrichFromPolicy( ...(provider.exists === true && provider.id ? { providerId: provider.id } : {}), ...(denyTools.length > 0 && entry.source !== "legacy-registry" ? { denyTools } : {}), ...(policyConflict ? { policyConflict } : {}), + ...(endpointConflict ? { policyEndpointConflict: true } : {}), }; } diff --git a/src/lib/actions/sandbox/mcp-bridge-update.test.ts b/src/lib/actions/sandbox/mcp-bridge-update.test.ts index 142c138ced4..bf876ff8219 100644 --- a/src/lib/actions/sandbox/mcp-bridge-update.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-update.test.ts @@ -106,9 +106,17 @@ describe("source-backed MCP denied-tool policy updates", () => { ["shared public pins", false, false], ["trusted-private sibling", true, false], ["conflicting sibling pins", false, true], + ["sibling with invalid denied tools", false, false, true], + ["sibling with endpoint path drift", false, false, false, true], ])( "refuses a public-pin refresh that would diverge from %s", - async (_label, trustedPrivate, conflicting) => { + async ( + _label, + trustedPrivate, + conflicting, + policyConflict = false, + endpointConflict = false, + ) => { const sibling: McpSourceEntry = { ...entry, server: "peer", @@ -117,6 +125,10 @@ describe("source-backed MCP denied-tool policy updates", () => { policyName: "mcp-bridge-peer", url: "https://mcp.example.test/peer", env: ["PEER_TOKEN"], + ...(policyConflict + ? { policyConflict: "Live policy contains invalid denied-tool selectors." } + : {}), + ...(endpointConflict ? { policyEndpointConflict: true } : {}), ...(trustedPrivate ? { trustedPrivateHost: "mcp.example.test", allowedIps: ["10.20.30.40"] } : {}), @@ -300,9 +312,29 @@ describe("source-backed MCP denied-tool policy updates", () => { ["trusted-private sibling on clear", [], ["10.20.30.40"], true, false], ["invalid public sibling pins on replace", ["delete_*"], ["127.0.0.1"], false, false], ["invalid public sibling pins on clear", [], ["127.0.0.1"], false, false], + ["sibling with invalid denied tools on replace", ["delete_*"], ["9.9.9.9"], false, true, true], + ["sibling with invalid denied tools on clear", [], ["9.9.9.9"], false, true, true], + [ + "sibling with endpoint path drift on replace", + ["delete_*"], + ["9.9.9.9"], + false, + false, + false, + true, + ], + ["sibling with endpoint path drift on clear", [], ["9.9.9.9"], false, false, false, true], ])( "rejects denied-tool changes before mutation with %s", - async (_label, denyTools, pins, privatePeer, conflict) => { + async ( + _label, + denyTools, + pins, + privatePeer, + conflict, + policyConflict = false, + endpointConflict = false, + ) => { const peer = { ...entry, server: "peer", @@ -312,6 +344,10 @@ describe("source-backed MCP denied-tool policy updates", () => { providerId: "22222222-3333-4444-8555-666666666666", policyName: "mcp-bridge-peer", allowedIps: pins, + ...(endpointConflict ? { policyEndpointConflict: true } : {}), + ...(policyConflict + ? { policyConflict: "Live policy contains invalid denied-tool selectors." } + : {}), ...(privatePeer ? { trustedPrivateHost: "mcp.example.test" } : {}), }; const bridges = { @@ -321,6 +357,7 @@ describe("source-backed MCP denied-tool policy updates", () => { ? { third: { ...peer, + policyConflict: undefined, server: "third", url: "https://mcp.example.test/third", env: ["THIRD_TOKEN"], diff --git a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts index 413b0cf244e..585e629aa11 100644 --- a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts @@ -98,11 +98,10 @@ describe("MCP shared-host address pins", () => { expect(aligned).toMatchObject({ ok: true, reusedFrom: ["one", "three"] }); }); - it("ignores the server being added and servers whose live policy points elsewhere", () => { + it("ignores the server being added and unpinned siblings without endpoint conflicts", () => { const aligned = align( { two: entry("two", { allowedIps: ["9.9.9.9"] }), - stale: entry("stale", { allowedIps: ["4.4.4.4"], policyConflict: "URL differs" }), unpinned: entry("unpinned", { allowedIps: undefined }), }, ["1.1.1.1"], @@ -110,6 +109,76 @@ describe("MCP shared-host address pins", () => { expect(aligned).toEqual({ ok: true, target: { addresses: ["1.1.1.1"] }, reusedFrom: [] }); }); + it.each(["add", "update", "refresh"] as const)( + "refuses %s when a sibling's live endpoint differs only by path", + (operation) => { + const refused = alignMcpTargetWithSharedHostPins({ + operation, + sandboxName: "alpha", + server: "two", + url: "https://mcp.example.test/two", + target: { addresses: ["1.1.1.1"] }, + bridges: { + one: entry("one", { + policyConflict: "Agent URL differs from live policy endpoint at /renamed.", + policyEndpointConflict: true, + }), + }, + }); + expect(refused.ok).toBe(false); + expect(refused.ok ? "" : refused.message).toMatch( + /live policy endpoint.*'one'.*Resolve.*conflict.*mcp\.example\.test:443/, + ); + }, + ); + + it.each([{ url: "https://other.example.test/one" }, { allowedIps: undefined }])( + "refuses unresolved live authority before filtering sibling $url / $allowedIps", + (overrides) => { + const refused = align({ one: entry("one", { ...overrides, policyEndpointConflict: true }) }, [ + "1.1.1.1", + ]); + expect(refused.ok).toBe(false); + }, + ); + + it.each(["add", "update", "refresh"] as const)( + "rejects %s when a sibling with invalid denied tools records conflicting pins", + (operation) => { + const refused = alignMcpTargetWithSharedHostPins({ + operation, + sandboxName: "alpha", + server: "two", + url: "https://mcp.example.test/two", + target: { addresses: ["1.1.1.1"] }, + bridges: { + one: entry("one"), + three: entry("three", { + allowedIps: ["9.9.9.9"], + policyConflict: "Live policy contains invalid denied-tool selectors.", + }), + }, + }); + expect(refused.ok).toBe(false); + expect(refused.ok ? "" : refused.message).toMatch( + /'one': 8\.8\.8\.8; 'three': 9\.9\.9\.9.*nemoclaw alpha mcp remove /, + ); + }, + ); + + it("reuses public pins despite a sibling's invalid denied tools", () => { + expect( + align( + { + one: entry("one", { + policyConflict: "Live policy contains invalid denied-tool selectors.", + }), + }, + ["1.1.1.1"], + ), + ).toEqual({ ok: true, target: { addresses: ["8.8.8.8"] }, reusedFrom: ["one"] }); + }); + it("names the servers and pins when existing servers already disagree", () => { const refused = align( { @@ -129,6 +198,7 @@ describe("MCP shared-host address pins", () => { url: "https://mcp.corp.example/one", allowedIps: ["10.20.30.40"], trustedPrivateHost: "mcp.corp.example", + policyConflict: "Live policy contains invalid denied-tool selectors.", }); const privateTarget = align( { one: privateSibling }, @@ -196,7 +266,11 @@ describe("MCP shared-host address pins", () => { }); describe("mcp add on a host that rotates DNS answers (#13800)", () => { - function runAdd(options: { siblings: Record; dnsAnswer: string }) { + function runAdd(options: { + siblings: Record; + dnsAnswer: string; + livePolicy?: Record; + }) { const home = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-mcp-shared-host-")); const sourceRequireHook = path.resolve("test/helpers/onboard-script-mocks.cjs"); const script = ` @@ -214,6 +288,8 @@ const provider = require("./src/lib/actions/sandbox/mcp-bridge-provider.js"); const processRecovery = require("./src/lib/actions/sandbox/process-recovery.js"); const state = require("./src/lib/actions/sandbox/mcp-bridge-state.js"); const sourceState = require("./src/lib/actions/sandbox/mcp-bridge-source.js"); +const providerInspection = require("./src/lib/actions/sandbox/mcp-bridge-provider-inspection.js"); +const livePolicy = ${JSON.stringify(options.livePolicy ?? null)}; const validation = require("./src/lib/actions/sandbox/mcp-bridge-validation.js"); let appliedTarget; let mutated = false; @@ -248,8 +324,17 @@ replace(provider, "waitForAttachedMcpCredential", () => "v1"); replace(processRecovery, "restartSandboxGateway", () => ({ ok: true, restarted: true, healthPassed: true, forwardRecovered: true, })); -replace(sourceState, "inspectSourceBridgeState", () => ({ - bridges: ${JSON.stringify(options.siblings)}, sources: { native: {}, legacy: {} }, +if (livePolicy) { + replace(policies, "captureRecordedSandboxBasePolicy", async () => JSON.stringify(livePolicy)); + replace(providerInspection, "inspectMcpProvider", async () => ({ + credentialKeys: null, exists: false, id: null, resourceVersion: null, type: null, + })); +} +replace(sourceState, "inspectSourceBridgeState", async (sandbox, runtimeSelection) => ({ + bridges: livePolicy + ? await sourceState.joinMcpEntriesToOpenShell(sandbox, ${JSON.stringify(options.siblings)}, runtimeSelection) + : ${JSON.stringify(options.siblings)}, + sources: { native: {}, legacy: {} }, })); registry.registerSandbox({ name: "alpha", agent: "openclaw", gatewayName: "nemoclaw-9090", gatewayPort: 9090, @@ -306,17 +391,65 @@ require("./src/lib/actions/sandbox/mcp-bridge.js").addMcpBridge("alpha", { const outcome = runAdd({ siblings: { one: sibling("one", ["8.8.8.8"]) }, dnsAnswer: "8.8.4.4", + livePolicy: { + network_policies: { + mcp_bridge_one: { + endpoints: [ + { + host: "mcp.example.test", + port: 443, + path: "/mcp/one", + protocol: "mcp", + allowed_ips: ["8.8.8.8"], + }, + ], + }, + }, + }, }); expect(outcome.message).toBeNull(); expect(outcome.appliedAddresses).toEqual(["8.8.8.8"]); }); - it( - "fails before changing anything when the existing servers disagree", + it.each([ + ["path", { host: "mcp.example.test", port: 443, path: "/renamed" }], + ["host", { host: "other.example.test", port: 443, path: "/mcp/one" }], + ["port", { host: "mcp.example.test", port: 8443, path: "/mcp/one" }], + ] as const)( + "refuses before mutation when the joined live sibling has %s drift", + { timeout: 40_000 }, + (_kind, endpoint) => { + const outcome = runAdd({ + siblings: { one: sibling("one", ["8.8.8.8"]) }, + dnsAnswer: "1.1.1.1", + livePolicy: { + network_policies: { + mcp_bridge_one: { + endpoints: [{ ...endpoint, protocol: "mcp", allowed_ips: ["8.8.8.8"] }], + }, + }, + }, + }); + expect(outcome, JSON.stringify(outcome)).toMatchObject({ + mutated: false, + appliedAddresses: null, + message: expect.stringMatching(/not added.*live policy endpoint.*'one'.*Resolve.*conflict/), + }); + }, + ); + + it.each([undefined, "Live policy contains invalid denied-tool selectors."])( + "fails before changing anything when existing servers disagree (policy conflict: %s)", { timeout: 40_000 }, - () => { + (policyConflict) => { const outcome = runAdd({ - siblings: { one: sibling("one", ["8.8.8.8"]), three: sibling("three", ["9.9.9.9"]) }, + siblings: { + one: sibling("one", ["8.8.8.8"]), + three: { + ...sibling("three", ["9.9.9.9"]), + ...(policyConflict ? { policyConflict } : {}), + }, + }, dnsAnswer: "8.8.4.4", }); expect(outcome.message).toMatch(/'one': 8\.8\.8\.8; 'three': 9\.9\.9\.9/); diff --git a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts index 01eac28e83c..5eb82ada565 100644 --- a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts +++ b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts @@ -64,14 +64,14 @@ export function alignMcpTargetWithSharedHostPins(options: { const recovery = `Before removing registrations with \`nemoclaw ${sandboxName} mcp remove \`, follow https://docs.nvidia.com/nemoclaw/latest/user-guide/openclaw/manage-sandboxes/mcp-servers/manage-mcp-servers#rotate-a-credential to record current denied-tool selectors and re-export the affected credential variables. Removal preserves providers. Perform explicit provider cleanup only after confirming no other sandbox uses them. Re-add with the recorded selectors.`; const groups = new Map(); for (const entry of Object.values(bridges)) { - if ( - entry.server === server || - entry.policyConflict || - !entry.allowedIps?.length || - endpointAuthority(entry.url) !== authority - ) { - continue; + if (entry.server === server) continue; + if (entry.policyEndpointConflict) { + return { + ok: false, + message: `MCP server '${server}' was not ${action}: the live policy endpoint for managed server '${entry.server}' differs from its registered URL. Resolve that conflict before reconciling address pins on ${authority}. ${recovery}`, + }; } + if (!entry.allowedIps?.length || endpointAuthority(entry.url) !== authority) continue; const pins = sortedPins(entry.allowedIps); const key = pins.join(","); const group = groups.get(key) ?? { pins, servers: [], trustedPrivate: false }; From ea02fe3ea6b7c71068c84ec641e6315b25991efd Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Wed, 18 Nov 2026 22:51:12 -0800 Subject: [PATCH 09/17] fix(mcp): limit endpoint conflicts to shared authorities Keep add, denied-tool changes, and pin refresh available when a conflicting registration uses another host or port. Compare the registered and live authorities before refusing an operation, and retain refusal when the live authority cannot be determined. Refs #13800. Signed-off-by: Deepak Jain --- .../actions/sandbox/mcp-bridge-contracts.ts | 4 +- .../actions/sandbox/mcp-bridge-source.test.ts | 7 +- src/lib/actions/sandbox/mcp-bridge-source.ts | 13 +- .../actions/sandbox/mcp-bridge-update.test.ts | 113 +++++++++++++----- .../mcp-bridge/shared-host-pins.test.ts | 104 +++++++++++++++- .../sandbox/mcp-bridge/shared-host-pins.ts | 11 +- 6 files changed, 208 insertions(+), 44 deletions(-) diff --git a/src/lib/actions/sandbox/mcp-bridge-contracts.ts b/src/lib/actions/sandbox/mcp-bridge-contracts.ts index 08b282b9852..662cb7ab806 100644 --- a/src/lib/actions/sandbox/mcp-bridge-contracts.ts +++ b/src/lib/actions/sandbox/mcp-bridge-contracts.ts @@ -51,8 +51,8 @@ export interface McpSourceEntry { source?: "native" | "legacy" | "legacy-registry" | "policy"; /** Live policy cannot be reconciled with the agent registration. */ policyConflict?: string; - /** Live policy endpoint differs from the agent-native URL. */ - policyEndpointConflict?: boolean; + /** Differing live policy authority, or null when it cannot be determined. */ + policyEndpointConflict?: string | null; } export interface McpBridgeAddOptions extends ParsedMcpAddArgs {} diff --git a/src/lib/actions/sandbox/mcp-bridge-source.test.ts b/src/lib/actions/sandbox/mcp-bridge-source.test.ts index 67999e4e979..6d54b30700d 100644 --- a/src/lib/actions/sandbox/mcp-bridge-source.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-source.test.ts @@ -442,9 +442,10 @@ network_policies: it.each([ ["matching endpoint", "api.githubcopilot.com", 443, "/mcp/", undefined], - ["different host", "other.example.com", 443, "/mcp/", true], - ["different path", "api.githubcopilot.com", 443, "/renamed", true], - ["different port", "api.githubcopilot.com", 8443, "/mcp/", true], + ["different host", "other.example.com", 443, "/mcp/", "other.example.com:443"], + ["different path", "api.githubcopilot.com", 443, "/renamed", "api.githubcopilot.com:443"], + ["different port", "api.githubcopilot.com", 8443, "/mcp/", "api.githubcopilot.com:8443"], + ["unknown port", "api.githubcopilot.com", null, "/mcp/", null], ])( "retains endpoint identity with invalid denied tools and a %s", async (_label, host, port, endpointPath, conflict) => { diff --git a/src/lib/actions/sandbox/mcp-bridge-source.ts b/src/lib/actions/sandbox/mcp-bridge-source.ts index 368577f6a3e..7fa10537360 100644 --- a/src/lib/actions/sandbox/mcp-bridge-source.ts +++ b/src/lib/actions/sandbox/mcp-bridge-source.ts @@ -648,7 +648,18 @@ async function enrichFromPolicy( ...(provider.exists === true && provider.id ? { providerId: provider.id } : {}), ...(denyTools.length > 0 && entry.source !== "legacy-registry" ? { denyTools } : {}), ...(policyConflict ? { policyConflict } : {}), - ...(endpointConflict ? { policyEndpointConflict: true } : {}), + ...(endpointConflict + ? { + policyEndpointConflict: + host && + typeof endpoint.port === "number" && + Number.isInteger(endpoint.port) && + endpoint.port > 0 && + endpoint.port <= 65535 + ? `${host}:${endpoint.port}` + : null, + } + : {}), }; } diff --git a/src/lib/actions/sandbox/mcp-bridge-update.test.ts b/src/lib/actions/sandbox/mcp-bridge-update.test.ts index bf876ff8219..d8e52179112 100644 --- a/src/lib/actions/sandbox/mcp-bridge-update.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-update.test.ts @@ -128,7 +128,7 @@ describe("source-backed MCP denied-tool policy updates", () => { ...(policyConflict ? { policyConflict: "Live policy contains invalid denied-tool selectors." } : {}), - ...(endpointConflict ? { policyEndpointConflict: true } : {}), + ...(endpointConflict ? { policyEndpointConflict: "mcp.example.test:443" } : {}), ...(trustedPrivate ? { trustedPrivateHost: "mcp.example.test", allowedIps: ["10.20.30.40"] } : {}), @@ -176,34 +176,50 @@ describe("source-backed MCP denied-tool policy updates", () => { ["matching shared pins", "https://mcp.example.test/peer", "8.8.8.8"], ["another hostname", "https://other.example.test/peer", "1.1.1.1"], ["another port", "https://mcp.example.test:8443/peer", "1.1.1.1"], - ])("preserves public-pin refresh with %s", async (_label, url, address) => { - const sibling = { - ...entry, - server: "peer", - providerName: "alpha-mcp-peer", - providerId: "22222222-3333-4444-8555-666666666666", - policyName: "mcp-bridge-peer", - url, - env: ["PEER_TOKEN"], - }; - const bridges = { github: entry, peer: sibling }; - mocks.inspectSourceBridgeState.mockReturnValueOnce({ - bridges, - sources: { native: bridges, legacy: {} }, - }); - const lookup = vi.spyOn(dns, "lookup").mockResolvedValue([{ address, family: 4 }] as never); - try { - await refreshMcpBridgePublicPins("alpha", "github"); - expect(mocks.refreshMcpPublicPolicyPins).toHaveBeenCalledWith( - "alpha", - entry, - { addresses: [address] }, - { gatewayName: "nemoclaw-9090", workspace: "default" }, - ); - } finally { - lookup.mockRestore(); - } - }); + [ + "an unrelated host conflict", + "https://other.example.test/peer", + "1.1.1.1", + "other.example.test:443", + ], + [ + "an unrelated port conflict", + "https://mcp.example.test:8443/peer", + "1.1.1.1", + "mcp.example.test:8443", + ], + ])( + "preserves public-pin refresh with %s", + async (_label, url, address, policyEndpointConflict?: string) => { + const sibling = { + ...entry, + server: "peer", + providerName: "alpha-mcp-peer", + providerId: "22222222-3333-4444-8555-666666666666", + policyName: "mcp-bridge-peer", + url, + policyEndpointConflict, + env: ["PEER_TOKEN"], + }; + const bridges = { github: entry, peer: sibling }; + mocks.inspectSourceBridgeState.mockReturnValueOnce({ + bridges, + sources: { native: bridges, legacy: {} }, + }); + const lookup = vi.spyOn(dns, "lookup").mockResolvedValue([{ address, family: 4 }] as never); + try { + await refreshMcpBridgePublicPins("alpha", "github"); + expect(mocks.refreshMcpPublicPolicyPins).toHaveBeenCalledWith( + "alpha", + entry, + { addresses: [address] }, + { gatewayName: "nemoclaw-9090", workspace: "default" }, + ); + } finally { + lookup.mockRestore(); + } + }, + ); it("refuses public-pin refresh when the native registration changes during DNS resolution (#10464)", async () => { const lookup = vi @@ -344,7 +360,7 @@ describe("source-backed MCP denied-tool policy updates", () => { providerId: "22222222-3333-4444-8555-666666666666", policyName: "mcp-bridge-peer", allowedIps: pins, - ...(endpointConflict ? { policyEndpointConflict: true } : {}), + ...(endpointConflict ? { policyEndpointConflict: "mcp.example.test:443" } : {}), ...(policyConflict ? { policyConflict: "Live policy contains invalid denied-tool selectors." } : {}), @@ -383,6 +399,43 @@ describe("source-backed MCP denied-tool policy updates", () => { }, ); + it.each([ + ["replace", ["delete_*"], "https://other.example.test/peer", "other.example.test:443"], + ["clear", [], "https://other.example.test/peer", "other.example.test:443"], + ["replace", ["delete_*"], "https://mcp.example.test:8443/peer", "mcp.example.test:8443"], + ["clear", [], "https://mcp.example.test:8443/peer", "mcp.example.test:8443"], + ])( + "permits denied-tool %s despite an unrelated endpoint conflict", + async (_mode, denyTools, url, policyEndpointConflict) => { + const peer = { + ...entry, + server: "peer", + url, + policyEndpointConflict, + allowedIps: ["9.9.9.9"], + }; + const before = structuredClone(peer); + const bridges = { github: entry, peer }; + mocks.inspectSourceBridgeState.mockReturnValueOnce({ + bridges, + sources: { native: bridges, legacy: {} }, + }); + await updateMcpBridgeDenyTools("alpha", "github", denyTools); + expect(mocks.removeGeneratedPolicy).toHaveBeenCalledExactlyOnceWith("alpha", entry, { + runtimeSelection: { gatewayName: "nemoclaw-9090", workspace: "default" }, + }); + expect(mocks.applyGeneratedPolicy).toHaveBeenCalledWith( + "alpha", + expect.objectContaining({ server: "github" }), + { addresses: ["8.8.8.8"] }, + { runtimeSelection: { gatewayName: "nemoclaw-9090", workspace: "default" } }, + ); + expect(mocks.applyGeneratedPolicy).toHaveBeenCalledTimes(1); + expect(mocks.applyGeneratedPolicy.mock.calls[0][1].denyTools ?? []).toEqual(denyTools); + expect(peer).toEqual(before); + }, + ); + it("removes the old route before applying and publishing the live replacement (#11115)", async () => { await updateMcpBridgeDenyTools("alpha", "github", ["submit_*", "delete_repo"]); diff --git a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts index 585e629aa11..4264124aea8 100644 --- a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts @@ -121,7 +121,7 @@ describe("MCP shared-host address pins", () => { bridges: { one: entry("one", { policyConflict: "Agent URL differs from live policy endpoint at /renamed.", - policyEndpointConflict: true, + policyEndpointConflict: "mcp.example.test:443", }), }, }); @@ -132,16 +132,44 @@ describe("MCP shared-host address pins", () => { }, ); - it.each([{ url: "https://other.example.test/one" }, { allowedIps: undefined }])( + it.each([ + { url: "https://other.example.test/one", policyEndpointConflict: "mcp.example.test:443" }, + { allowedIps: undefined, policyEndpointConflict: "mcp.example.test:443" }, + { url: "https://other.example.test/one", policyEndpointConflict: null }, + ])( "refuses unresolved live authority before filtering sibling $url / $allowedIps", (overrides) => { - const refused = align({ one: entry("one", { ...overrides, policyEndpointConflict: true }) }, [ - "1.1.1.1", - ]); + const refused = align({ one: entry("one", overrides) }, ["1.1.1.1"]); expect(refused.ok).toBe(false); }, ); + it.each([ + ["add", "https://other.example.test/one", "other.example.test:443"], + ["update", "https://other.example.test/one", "other.example.test:443"], + ["refresh", "https://other.example.test/one", "other.example.test:443"], + ["add", "https://mcp.example.test:8443/one", "mcp.example.test:8443"], + ["update", "https://mcp.example.test:8443/one", "mcp.example.test:8443"], + ["refresh", "https://mcp.example.test:8443/one", "mcp.example.test:8443"], + ] as const)("permits %s despite an unrelated endpoint conflict at %s", (operation, url, live) => { + const bridges = { + one: entry("one", { url, policyEndpointConflict: live, allowedIps: ["9.9.9.9"] }), + }; + const before = structuredClone(bridges); + const target = { addresses: ["1.1.1.1"] }; + expect( + alignMcpTargetWithSharedHostPins({ + operation, + sandboxName: "alpha", + server: "two", + url: "https://mcp.example.test/two", + target, + bridges, + }), + ).toEqual({ ok: true, target, reusedFrom: [] }); + expect(bridges).toEqual(before); + }); + it.each(["add", "update", "refresh"] as const)( "rejects %s when a sibling with invalid denied tools records conflicting pins", (operation) => { @@ -293,11 +321,12 @@ const livePolicy = ${JSON.stringify(options.livePolicy ?? null)}; const validation = require("./src/lib/actions/sandbox/mcp-bridge-validation.js"); let appliedTarget; let mutated = false; +const policyMutations = []; replace(policies, "getPresetContentGatewayState", () => "absent"); replace(adapters, "assertAgentMcpMutationRuntimeCapability", () => {}); replace(adapters, "inspectAgentAdapterRegistration", () => ({ state: "absent" })); replace(adapters, "registerAgentAdapterAtCurrentCredentialRevision", () => { mutated = true; return "v1"; }); -replace(policy, "applyGeneratedPolicy", (_sandbox, _entry, target) => { mutated = true; appliedTarget = target; }); +replace(policy, "applyGeneratedPolicy", (_sandbox, updatedEntry, target) => { mutated = true; policyMutations.push(updatedEntry.server); appliedTarget = target; }); replace(state, "ensureSandboxGatewaySelected", async () => {}); replace(validation, "assertMcpCredentialBoundaryRuntimeVersion", () => {}); replace(provider, "assertNoProviderCredentialCollisions", () => {}); @@ -343,6 +372,7 @@ const finish = (error) => process.stdout.write(JSON.stringify({ message: error ? String(error.message || error) : null, appliedAddresses: appliedTarget ? appliedTarget.addresses : null, mutated, + policyMutations, }), () => process.exit(0)); require("./src/lib/actions/sandbox/mcp-bridge.js").addMcpBridge("alpha", { server: "two", @@ -369,6 +399,7 @@ require("./src/lib/actions/sandbox/mcp-bridge.js").addMcpBridge("alpha", { message: string | null; appliedAddresses: string[] | null; mutated: boolean; + policyMutations: string[]; }>(result.stdout); } finally { fs.rmSync(home, { recursive: true, force: true }); @@ -411,6 +442,67 @@ require("./src/lib/actions/sandbox/mcp-bridge.js").addMcpBridge("alpha", { expect(outcome.appliedAddresses).toEqual(["8.8.8.8"]); }); + it.each([ + ["another host", "https://other.example.test/mcp/one", "other.example.test", 443], + ["another port", "https://mcp.example.test:8443/mcp/one", "mcp.example.test", 8443], + ] as const)( + "adds without changing a conflicting registration on %s", + { timeout: 40_000 }, + (_label, url, host, port) => { + const outcome = runAdd({ + siblings: { one: { ...sibling("one", ["8.8.8.8"]), url } }, + dnsAnswer: "1.1.1.1", + livePolicy: { + network_policies: { + mcp_bridge_one: { + endpoints: [ + { host, port, path: "/renamed", protocol: "mcp", allowed_ips: ["8.8.8.8"] }, + ], + }, + }, + }, + }); + expect(outcome).toMatchObject({ + message: null, + appliedAddresses: ["1.1.1.1"], + }); + expect(new Set(outcome.policyMutations)).toEqual(new Set(["two"])); + }, + ); + + it( + "refuses a live sibling authority even when its registered host differs", + { timeout: 40_000 }, + () => { + const outcome = runAdd({ + siblings: { + one: { ...sibling("one", ["8.8.8.8"]), url: "https://other.example.test/mcp/one" }, + }, + dnsAnswer: "1.1.1.1", + livePolicy: { + network_policies: { + mcp_bridge_one: { + endpoints: [ + { + host: "mcp.example.test", + port: 443, + path: "/mcp/one", + protocol: "mcp", + allowed_ips: ["8.8.8.8"], + }, + ], + }, + }, + }, + }); + expect(outcome).toMatchObject({ + mutated: false, + policyMutations: [], + message: expect.stringMatching(/live policy endpoint/), + }); + }, + ); + it.each([ ["path", { host: "mcp.example.test", port: 443, path: "/renamed" }], ["host", { host: "other.example.test", port: 443, path: "/mcp/one" }], diff --git a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts index 5eb82ada565..294a9567cd2 100644 --- a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts +++ b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts @@ -65,13 +65,20 @@ export function alignMcpTargetWithSharedHostPins(options: { const groups = new Map(); for (const entry of Object.values(bridges)) { if (entry.server === server) continue; - if (entry.policyEndpointConflict) { + if ( + endpointAuthority(entry.url) !== authority && + entry.policyEndpointConflict !== authority && + entry.policyEndpointConflict !== null + ) { + continue; + } + if (entry.policyEndpointConflict !== undefined) { return { ok: false, message: `MCP server '${server}' was not ${action}: the live policy endpoint for managed server '${entry.server}' differs from its registered URL. Resolve that conflict before reconciling address pins on ${authority}. ${recovery}`, }; } - if (!entry.allowedIps?.length || endpointAuthority(entry.url) !== authority) continue; + if (!entry.allowedIps?.length) continue; const pins = sortedPins(entry.allowedIps); const key = pins.join(","); const group = groups.get(key) ?? { pins, servers: [], trustedPrivate: false }; From 2a10ea1f5326e7973b10c7ebc79b690f7b857252 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 19 Nov 2026 00:24:01 -0800 Subject: [PATCH 10/17] fix(mcp): scope unknown endpoint conflicts to matching hosts Limit sibling reconciliation to registrations whose registered or known live authority matches the requested endpoint. Unknown policy endpoints on unrelated hosts no longer block add, denied-tool changes, or public-pin refresh. Clarify that DNS validation does not refresh reused public pins. Cover unknown authorities through the shared helper and public operations. Signed-off-by: Deepak Jain --- docs/manage-sandboxes/add-mcp-server.mdx | 5 +++-- docs/manage-sandboxes/manage-mcp-servers.mdx | 9 +++++++-- docs/reference/commands.mdx | 8 ++++++-- src/lib/actions/sandbox/mcp-bridge-update.test.ts | 5 ++++- .../sandbox/mcp-bridge/shared-host-pins.test.ts | 10 +++++++++- src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts | 6 +----- 6 files changed, 30 insertions(+), 13 deletions(-) diff --git a/docs/manage-sandboxes/add-mcp-server.mdx b/docs/manage-sandboxes/add-mcp-server.mdx index 46e38968a0e..de51ececd9d 100644 --- a/docs/manage-sandboxes/add-mcp-server.mdx +++ b/docs/manage-sandboxes/add-mcp-server.mdx @@ -208,9 +208,10 @@ Deep Agents Code supports at most 64 managed MCP servers in one sandbox. Endpoint paths cannot contain percent escapes, backslashes, semicolons, or OpenShell glob metacharacters. Endpoint URLs cannot use port `0`. -NemoClaw validates DNS before registration. -When another managed server in the sandbox uses the same hostname and port, a public add revalidates and reuses its recorded address pins, even if current DNS differs. +NemoClaw validates current DNS answers before registration. +If another managed server shares the hostname and port, a public add reuses its previously recorded public pins. Otherwise, the generated policy pins the validated DNS addresses. +Reused pins can differ from the current DNS answers. NemoClaw refuses the add before mutation if sibling pin sets conflict or trusted-private pins would need to change. Refer to [Refresh Shared-Host Registrations](manage-mcp-servers#refresh-shared-host-registrations) to change pins for every registration on that hostname and port. Public endpoints need no trusted-private declaration. diff --git a/docs/manage-sandboxes/manage-mcp-servers.mdx b/docs/manage-sandboxes/manage-mcp-servers.mdx index 9466f741e52..4169834f621 100644 --- a/docs/manage-sandboxes/manage-mcp-servers.mdx +++ b/docs/manage-sandboxes/manage-mcp-servers.mdx @@ -167,7 +167,7 @@ Inspect the live policy again and confirm that its denied-tool selectors match y Tool discovery does not verify denied-tool enforcement. For a trusted-private entry, pass the same reviewed `--trusted-private-host` value to `add`. -For a public entry, `add` validates current DNS but reuses revalidated sibling pins when another managed server uses the same hostname and port. +For a public entry, `add` validates current DNS answers, then reuses previously recorded public pins if another managed server shares the hostname and port. Remove-and-add therefore does not independently refresh shared public pins. Refer to [Change Endpoint Pins](#change-endpoint-pins) for pin changes. @@ -191,7 +191,12 @@ $$nemoclaw my-sandbox mcp update doordash \ The command changes only the live OpenShell policy. It does not change the agent-native endpoint, credential reference, provider, attachment, or agent adapter. Live policy is the enforcement source of truth; NemoClaw does not retain a second denied-tool intent record. -NemoClaw validates the current source entry and endpoint pins before replacing the route. For public endpoints, it validates DNS and retains revalidated recorded pins. Conflicting sibling pins stop the update before route removal. This keeps an interrupted stricter update fail-closed. If replacement activation fails, the MCP route remains blocked and the error prints the exact `mcp update` command to retry. Rebuild captures and restores the complete live policy, including denied-tool rules, without regenerating it from registry state. +NemoClaw validates the current source entry and endpoint pins before replacing the route. +For public endpoints, it validates current DNS answers and checks that the retained recorded pins are public IP addresses. +Conflicting sibling pins stop the update before route removal. +This keeps an interrupted stricter update fail-closed. +If replacement activation fails, the MCP route remains blocked and the error prints the exact `mcp update` command to retry. +Rebuild captures and restores the complete live policy, including denied-tool rules, without regenerating it from registry state. Clear every denied-tool rule explicitly: diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index 7f99acd5f2a..7db4ea5240b 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -3000,7 +3000,7 @@ $$nemoclaw my-assistant mcp list [--json] Add an MCP Streamable HTTP server to a sandbox. Pass `--url` for the MCP endpoint and the required single `--env KEY` bearer credential for the sandbox-side MCP client. Pass repeatable `--deny-tool ` options to block matching `tools/call` requests at the OpenShell proxy. The generated deny rules match tool names only and do not inspect arguments. Pass a repeatable `--trusted-private-host ` option to admit an exact RFC1918, CGNAT, or IPv6 unique local destination for the current command. The declaration must equal the normalized host from `--url`. For managed MCP, use a DNS hostname for an IPv6 unique local address because NemoClaw has not qualified direct IPv6-literal MCP URLs. You can supply exact hosts through `NEMOCLAW_TRUSTED_PRIVATE_HOSTS` instead, and NemoClaw combines the variable with command options. NemoClaw records the resulting exact trust intent and address pins, so restart, rebuild, and restore do not depend on the ambient environment. NemoClaw registers that credential in an OpenShell provider, installs a generated OpenShell `protocol: mcp` policy for the target endpoint, attaches the provider to the running sandbox, and writes only an OpenShell resolver placeholder for the recorded key into the agent configuration. Inline `--env KEY=VALUE` is rejected because it would expose the value in NemoClaw process arguments. Load the variable from a secret manager or masked prompt, export it without recording the value in shell history, and pass only `--env KEY`. All endpoints must use HTTPS. The full URL and path are persisted and displayed, so URLs cannot contain userinfo, query strings, fragments, known secret-shaped path material, percent-escaped or glob-style paths, or port zero. Server names must start with a letter and contain at most 64 letters, digits, hyphens, or underscores, and endpoint hostnames must use canonical lowercase DNS labels. NemoClaw rejects invalid names and endpoints before it writes lifecycle state or changes OpenShell resources. NemoClaw generates a narrow `protocol: mcp` policy for the destination, literal path, adapter binaries, pinned addresses, explicit MCP methods, and a 131,072-byte request-body limit. OpenShell `0.0.116` evaluates that policy before replacing the attached provider placeholder in the allowed request header. NemoClaw imports the endpointless `nemoclaw-mcp-v1` profile and binds the dedicated provider to that endpoint with `credential_binding.provider`. OpenShell withholds the credential before the binding is active and outside the bound host, port, and path. The sandbox client connects directly through OpenShell's existing egress path, and NemoClaw does not run a host-side MCP data-plane bridge, proxy, relay, or listener. After the add commits, NemoClaw freshly verifies the exact generated policy, expected provider attachment, recorded provider ID, `nemoclaw-mcp-v1` type, valid resource version, and exactly one credential key matching the recorded key. If those readiness checks pass, it sends a differential pair of wire-level MCP `initialize` requests from inside the sandbox — one with the placeholder header and one with an unresolvable control bearer — to verify that OpenShell resolves the credential on egress; otherwise it reports an inconclusive `probe skipped` result and sends no request. Neither outcome fails the committed add, and `--no-probe` skips this check. For full setup details, see [Add an MCP Server](../manage-sandboxes/mcp-servers/add-an-mcp-server). -Public registrations on the same hostname and port reuse revalidated sibling address pins when current DNS differs. +For public registrations, NemoClaw validates current DNS answers, then reuses previously recorded public pins if another managed server shares the hostname and port. Conflicting sibling pins or trusted-private pin changes stop the add before mutation. Refer to [Change Endpoint Pins](../manage-sandboxes/mcp-servers/manage-mcp-servers#change-endpoint-pins) for coordinated recovery. @@ -3068,7 +3068,11 @@ Update the denied-tool list or refresh public address pins for one registered MC Both operations use the live OpenShell policy and preserve the agent-native endpoint, credential reference, provider, attachment, and agent adapter. Pass one or more `--deny-tool ` options, or pass `--clear-deny-tools` to remove every denied-tool rule. Use only one mode per command: `--deny-tool`, `--clear-deny-tools`, or `--refresh-public-pins`. -Live OpenShell policy is the enforcement source of truth; NemoClaw does not persist duplicate MCP intent. A denied-tool update validates the current source and address pins, then checks sibling pin agreement before replacing the route. Public endpoints undergo DNS validation and retain revalidated recorded pins. If activation fails, the route remains blocked and the error prints the exact `mcp update` retry command. Rebuild captures and restores the complete live policy, including denied-tool rules. +Live OpenShell policy is the enforcement source of truth; NemoClaw does not persist duplicate MCP intent. +A denied-tool update validates the current source and address pins, then checks sibling pin agreement before replacing the route. +For public endpoints, NemoClaw validates current DNS answers and checks that the retained recorded pins are public IP addresses. +If activation fails, the route remains blocked and the error prints the exact `mcp update` retry command. +Rebuild captures and restores the complete live policy, including denied-tool rules. ```bash $$nemoclaw my-assistant mcp update github --deny-tool 'delete_*' --deny-tool 'admin_*' diff --git a/src/lib/actions/sandbox/mcp-bridge-update.test.ts b/src/lib/actions/sandbox/mcp-bridge-update.test.ts index d8e52179112..f7c571e1c6e 100644 --- a/src/lib/actions/sandbox/mcp-bridge-update.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge-update.test.ts @@ -176,6 +176,7 @@ describe("source-backed MCP denied-tool policy updates", () => { ["matching shared pins", "https://mcp.example.test/peer", "8.8.8.8"], ["another hostname", "https://other.example.test/peer", "1.1.1.1"], ["another port", "https://mcp.example.test:8443/peer", "1.1.1.1"], + ["an unknown unrelated authority", "https://other.example.test/peer", "1.1.1.1", null], [ "an unrelated host conflict", "https://other.example.test/peer", @@ -190,7 +191,7 @@ describe("source-backed MCP denied-tool policy updates", () => { ], ])( "preserves public-pin refresh with %s", - async (_label, url, address, policyEndpointConflict?: string) => { + async (_label, url, address, policyEndpointConflict?: string | null) => { const sibling = { ...entry, server: "peer", @@ -400,6 +401,8 @@ describe("source-backed MCP denied-tool policy updates", () => { ); it.each([ + ["replace", ["delete_*"], "https://other.example.test/peer", null], + ["clear", [], "https://other.example.test/peer", null], ["replace", ["delete_*"], "https://other.example.test/peer", "other.example.test:443"], ["clear", [], "https://other.example.test/peer", "other.example.test:443"], ["replace", ["delete_*"], "https://mcp.example.test:8443/peer", "mcp.example.test:8443"], diff --git a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts index 4264124aea8..a659fd9de7c 100644 --- a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts +++ b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.test.ts @@ -135,7 +135,7 @@ describe("MCP shared-host address pins", () => { it.each([ { url: "https://other.example.test/one", policyEndpointConflict: "mcp.example.test:443" }, { allowedIps: undefined, policyEndpointConflict: "mcp.example.test:443" }, - { url: "https://other.example.test/one", policyEndpointConflict: null }, + { policyEndpointConflict: null }, ])( "refuses unresolved live authority before filtering sibling $url / $allowedIps", (overrides) => { @@ -145,6 +145,12 @@ describe("MCP shared-host address pins", () => { ); it.each([ + ["add", "https://other.example.test/one", null], + ["update", "https://other.example.test/one", null], + ["refresh", "https://other.example.test/one", null], + ["add", "https://mcp.example.test:8443/one", null], + ["update", "https://mcp.example.test:8443/one", null], + ["refresh", "https://mcp.example.test:8443/one", null], ["add", "https://other.example.test/one", "other.example.test:443"], ["update", "https://other.example.test/one", "other.example.test:443"], ["refresh", "https://other.example.test/one", "other.example.test:443"], @@ -445,6 +451,8 @@ require("./src/lib/actions/sandbox/mcp-bridge.js").addMcpBridge("alpha", { it.each([ ["another host", "https://other.example.test/mcp/one", "other.example.test", 443], ["another port", "https://mcp.example.test:8443/mcp/one", "mcp.example.test", 8443], + ["an unknown live host", "https://other.example.test/mcp/one", "", 443], + ["an unknown live port", "https://mcp.example.test:8443/mcp/one", "mcp.example.test", 0], ] as const)( "adds without changing a conflicting registration on %s", { timeout: 40_000 }, diff --git a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts index 294a9567cd2..a5d9ef64a45 100644 --- a/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts +++ b/src/lib/actions/sandbox/mcp-bridge/shared-host-pins.ts @@ -65,11 +65,7 @@ export function alignMcpTargetWithSharedHostPins(options: { const groups = new Map(); for (const entry of Object.values(bridges)) { if (entry.server === server) continue; - if ( - endpointAuthority(entry.url) !== authority && - entry.policyEndpointConflict !== authority && - entry.policyEndpointConflict !== null - ) { + if (endpointAuthority(entry.url) !== authority && entry.policyEndpointConflict !== authority) { continue; } if (entry.policyEndpointConflict !== undefined) { From 267b682fd087c165044f818732b361bc10ce8592 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 19 Nov 2026 01:00:43 -0800 Subject: [PATCH 11/17] test(mcp): verify configured-peer credential withholding Send each managed MCP placeholder to the other configured path while both providers are attached. Require an explicit authentication rejection and reject server observations containing the foreign secret or a successful response. Keep unconfigured-route denials and cleanup. Cover both directions, global rewriting, and transport errors in support tests. Record the minimal two assertion points with their maintainer approval. Signed-off-by: Deepak Jain --- ci/e2e-assertion-budget.json | 10 +- ci/e2e-assertion-growth-exceptions.json | 4 +- test/e2e/README.md | 6 + test/e2e/live/mcp-bridge-reliability.ts | 2 +- test/e2e/live/mcp-bridge-shared-host.ts | 24 ++- test/e2e/live/mcp-provider-rewrite-probe.ts | 4 +- .../support/mcp-bridge-shared-host.test.ts | 151 ++++++++++++++++++ .../mcp-provider-rewrite-probe.test.ts | 64 ++++++++ 8 files changed, 254 insertions(+), 11 deletions(-) diff --git a/ci/e2e-assertion-budget.json b/ci/e2e-assertion-budget.json index f38f2a52801..b47eb8cea54 100644 --- a/ci/e2e-assertion-budget.json +++ b/ci/e2e-assertion-budget.json @@ -27,14 +27,14 @@ "generatedProbeConditions": 214 }, "unique": { - "expectCalls": 1761, - "matcherAssertions": 1741, + "expectCalls": 1762, + "matcherAssertions": 1742, "nodeAssertions": 132, - "namedAssertionHelpers": 686, + "namedAssertionHelpers": 687, "failCalls": 1, "throwGuards": 533, "objectFieldAssertions": 266, - "assertionPoints": 3359, + "assertionPoints": 3361, "generatedProbeBlocks": 221, "generatedProbeConditions": 729 }, @@ -84,7 +84,7 @@ "test/e2e/live/managed-image-activation-e2e.test.ts": [0,0,12,25,0], "test/e2e/live/managed-image-multiarch-startup.test.ts": [1,3,1,9,0], "test/e2e/live/managed-image-protected-runtime.test.ts": [0,0,39,81,16], - "test/e2e/live/mcp-bridge.test.ts": [39,139,198,531,47], + "test/e2e/live/mcp-bridge.test.ts": [39,139,199,533,47], "test/e2e/live/messaging-compatible-endpoint.test.ts": [13,19,13,28,2], "test/e2e/live/messaging-providers.test.ts": [0,11,6,51,11], "test/e2e/live/native-runtime-qualification-case.test.ts": [0,0,9,84,0], diff --git a/ci/e2e-assertion-growth-exceptions.json b/ci/e2e-assertion-growth-exceptions.json index 5a1d4a5d68d..6096bfb787b 100644 --- a/ci/e2e-assertion-growth-exceptions.json +++ b/ci/e2e-assertion-growth-exceptions.json @@ -1,5 +1,5 @@ { - "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12718 is the prerequisite for the PR #12382 budget transition recorded below. The exception matches only PR #12382 and both budget digests. A changed base or candidate budget invalidates it. The independent check reads trusted base policy, so this prerequisite must land on main before #12382 uses the exception. Remove after #12382 merges.\n\nMaintainer Prekshi Vyas (@prekshivyas) approved this exact refreshed PR #12382 transition on 2026-10-08: base budget SHA-256 53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441 to candidate budget SHA-256 8162408384d7a6b97ef0062042c73d4bc9486f54d2dfa6c0c5732e42d1060e2a. Acceptance record: https://github.com/NVIDIA/NemoClaw/pull/12840#issuecomment-6066319444. It includes one additional unique assertion point and one generated probe condition. This refresh preserves the #12608 concurrent-gateway-ports reduction and the previously reviewed runtime assertion changes. The independent check is not waived: the refreshed exception must land on main before enforcement can accept it. A different PR or budget digest remains rejected. Remove after #12382 merges.\n\nPR #12777 adds exactly two approved live assertions for native host-local inference success and sibling provider isolation. Deterministic behavior remains in unit/integration tests. Approval transcription: https://github.com/NVIDIA/NemoClaw/pull/12777#issuecomment-6048385152. The independent check reads trusted base policy; this entry does not disable it. Remove after #12777 merges.\n\nThe #12777 budget digests account for main #12608 removing seven assertions from concurrent-gateway-ports. The candidate preserves that reduction and adds only the same two approved inference-routing assertions. No other file budget increases.\n\nPR #12886 approved the provider-smoke transition extracted by #12955. Approval: https://github.com/NVIDIA/NemoClaw/pull/12886#issuecomment-6083839176. The unchanged change digest binds the same nine assertion points and companion inventory. This entry supports local preliminary validation and the Slice 2 consumer. Independent CI for the prerequisite requires its own maintainer approval record; this entry does not approve that PR.\n\nPR #12958 extracts the same approved provider-smoke budget transition for #12955. Its exact, unedited maintainer approval is https://github.com/NVIDIA/NemoClaw/pull/12958#issuecomment-6093851571. This candidate entry supports static hooks; the independent check continues to verify the PR-specific approval on GitHub. Remove after #12958 merges.\n\nPR #13203 adds the approved 19 assertion points for real authenticated and credentialless DCode native-local requests, credential isolation and sibling denial. Approval: https://github.com/NVIDIA/NemoClaw/pull/13203#issuecomment-6180239679. This exact change digest supports local hooks and candidate CI. Independent enforcement still verifies the PR-specific maintainer approval on GitHub. Remove after #13203 merges.\n\nPR #13201 adds one generated probe block and one counted probe condition in the existing full E2E owner to verify the selected sandbox agent endpoint, API, model and credential reference. Rebecca Sliter approved this exact delta: https://github.com/NVIDIA/NemoClaw/pull/13201#issuecomment-6180464605. This entry supports local validation; the independent check must verify the maintainer record. Remove after #13201 merges.\n\nPR #13293 consolidates OpenClaw native-local scenarios into the existing switching owner and removes duplicated deterministic metadata checks and the redundant mock curl probe. Suite totals fall by 16 expect calls and 10 assertion points without adding live files. Only the owning file transitive allocation grows because it now imports existing live helpers. Maintainer authorization: https://github.com/NVIDIA/NemoClaw/pull/13293#issuecomment-6211036786. This exact transition supports candidate CI; independent enforcement still verifies the maintainer record.\n\nPR #13007 retains the same ten Pi native-local live assertion points approved at https://github.com/NVIDIA/NemoClaw/pull/13007#issuecomment-6175787892. The exact change digest is unchanged against its replacement OpenClaw parent #13293. This entry supports local checks against that stacked base; independent enforcement still checks the authenticated PR approval.\n\nPR #13582 adds eight live assertion points for the WSL2 IPv6 native-local policy boundary. Only openclaw-inference-switch.test.ts increases, by seven direct expectations and the existing onboard-success helper. Deterministic CIDR and receipt coverage remain in source tests. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13582#issuecomment-6308860348. Independent enforcement verifies that PR-specific record. Remove this preliminary local exception after merge.\n\nPR #13645 adds three approved live assertion points for engine-down uninstall diagnostics inside rebuild-openclaw. Exact approval: https://github.com/NVIDIA/NemoClaw/pull/13645#issuecomment-6429899630. This entry enables candidate CI; independent enforcement still verifies the PR-specific maintainer record. Remove after merge.\n\nPR #13771 adds four Hermes OpenRouter rebuild assertions and a bounded diagnostic probe. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13771#issuecomment-6427647915. The independent PR check verifies that comment. Remove after #13771 merges.\n\nPR #13873 adds two live command assertions for the CLI build and native Hermes Discord qualification when consuming protected evidence from an older trusted producer. Approval: https://github.com/NVIDIA/NemoClaw/pull/13873#issuecomment-6488667052. The parser and identity cases stay in e2e-support tests. Remove after #13873 merges.\n\nPR #13651 moves the native NVIDIA Discord rebuild proof from hermes-discord to hermes-inference-switch, which receives the public endpoint credential. The native switch target also checks status through its installed credential verifier after rebuild. This adds four assertion points for the live status and restored-provider boundary; deterministic rejection and command-failure cases remain in fast tests. This entry permits the approved transition in local and candidate checks; independent enforcement verifies the maintainer record at https://github.com/NVIDIA/NemoClaw/pull/13651#issuecomment-6377201610. The typed helper extraction retains every live predicate and the same unique and transitive totals; the direct census decreases because the phase now lives in the existing helper.\n\nPR #13635 adds the approved protected-runtime deadline companion and five unique assertion points, one generated probe block, and one probe condition. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13635#issuecomment-6383152261. This entry supports local hooks and candidate CI; independent enforcement verifies the PR-specific GitHub approval. Remove after #13635 merges.\n\nPR #13596 adds four live assertion points to the existing double-onboard target for #13595: the managed OpenClaw state volume exists before `nemoclaw uninstall`, uninstall succeeds, the volume is gone afterwards, and same-name onboarding succeeds. Deterministic removal and failure cases remain in fast tests. This entry permits the approved transition in local and candidate checks; independent enforcement verifies the maintainer record at https://github.com/NVIDIA/NemoClaw/pull/13596#issuecomment-6365742624. Remove after #13596 merges.\n\nPR #13515 extends dashboard-remote-bind with Hermes host-listener coverage. The dashboard remains remotely reachable, API health works on loopback, and the non-loopback API port refuses TCP connections. Approval: https://github.com/NVIDIA/NemoClaw/pull/13515#issuecomment-6295553350. This entry supports local and candidate checks; independent enforcement verifies the authenticated maintainer record.\n\nPR #13515 also checks Hermes loopback API health and non-loopback refusal after stop/start, preserving the onboarding assertions. The combined delta is approved at https://github.com/NVIDIA/NemoClaw/pull/13515#issuecomment-6298021751.\n\nPR #13515 verifies the Hermes API forward identity before health probes after onboarding and restart. These two additional process-ownership assertions are approved at https://github.com/NVIDIA/NemoClaw/pull/13515#issuecomment-6322568985.\n\nPR #13927 reuses the verified public HTTPS fixture transport for two Podman inference targets. Direct and unique assertion counts are unchanged. Each target gains eleven transitive assertion points from existing package and tunnel prerequisites; the extracted Anthropic response helper adds one live companion file. This exact transition supports local validation. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13927#issuecomment-6524030655. Independent enforcement verifies this PR-specific record. Remove after merge.\n\nPR #14062 adds one live Ollama cleanup helper, three existing port-validation guards reached by gpu-double-onboard, and one shared shell probe. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14062#issuecomment-6582340290. This entry supports local hooks and candidate CI; independent enforcement verifies the PR-specific approval. Remove after merge.\n\nPR #13607 adds two live assertions and one read-only configuration probe to the existing balanced OpenClaw egress case for unavailable-search replies. The refreshed delta removes the unrelated public-fetch precondition guard while retaining both live assertions and the probe. Approved delta: https://github.com/NVIDIA/NemoClaw/pull/13607#issuecomment-6327887365. Remove after #13607 merges.\n\nPR #14000 replaces #12872 and retains one approved assertion point for owning-gateway connect sessions. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14000#issuecomment-6506269922. This entry enables candidate CI; independent enforcement verifies the PR-specific approval.\n\nPR #14122 retains the production bearerless provider-validation proof and private-publication proof in both Express targets. Spark and Station each request health on the two allowed addresses and require connection refusal on all discovered unintended addresses. Four added Spark assertions protect its separate physical-host path; deterministic URL construction remains in the support tests. The combined delta adds seven assertion points and one generated probe relative to main. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14122#issuecomment-6661407269. Independent enforcement verifies this PR-specific approval. Remove after merge.\n\nPR #14252 adds twelve live assertion points to the existing sandbox-survival owner for first-invocation cold public OpenClaw recovery, native and forwarded health, and retained sandbox/container identities on Docker and native Podman. Existing raw OpenShell survival evidence and target timeouts are unchanged. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14252#issuecomment-6676328443. This entry supports local and candidate checks; independent enforcement verifies the PR-specific approval record. Remove after merge.\n\nPR #14303 replaces #14201 and retains its two assertion points in hermes-root-entrypoint-smoke for qualification through the real entrypoint before gateway readiness. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14303#issuecomment-6713570086. This entry supports local hooks and candidate CI. Independent enforcement still verifies the PR-specific maintainer record. Remove after merge.\n\nPR #14512 adds24 net assertion points for native Switchyard cross-provider authorization, continuation policy enforcement, provider failure/recovery and a second credential scan. Three redundant proposed checks were omitted and two existing fixture-output checks remain covered by fast tests. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14512#issuecomment-6932725987. This branch entry supports local preliminary validation; independent CI verifies the PR-specific record. Remove after #14512 merges.\n\nPR #14512 retains its approved 24 assertion points and adds two generated conditions for bounded NULL diagnostics and PTY socket-state validation during sandbox retirement. Three unnecessary conditions were removed. Exact refreshed transition approved by Rebecca Sliter: https://github.com/NVIDIA/NemoClaw/pull/14512#issuecomment-6989339885. Independent enforcement still verifies this unedited maintainer record on GitHub.\n\nPR #14517 adds the required real shared-host MCP policy and credential composition proof: distinct paths and credentials, differing add-time DNS inputs, strict out-of-binding denial, and owned cleanup. The approved delta adds 13 unique assertion points and one companion file. Approval: https://github.com/NVIDIA/NemoClaw/pull/14517#issuecomment-6942719509. This branch entry supports preliminary local and candidate checks; independent enforcement verifies the recorded approval. Remove after merge.", + "$comment": "SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\nSPDX-License-Identifier: Apache-2.0\n\nMaintainer-approved exception for the exact PR #10341 budget transition. Adds only deferred-onboarding.test.ts with [12,14,12,14,0]; existing per-file budgets remain unchanged. Approval: https://github.com/NVIDIA/NemoClaw/pull/10341#issuecomment-5799263232. Local hooks and candidate CI may use this branch policy. The independent PR check reads only trusted base policy, so its expected growth failure is explicitly waived for #10341. A changed base or candidate budget invalidates this exception. Remove after #10341 merges.\n\nPR #12305 adds 19 live assertion points for the approved stopped-container recovery proof while retaining healthy-rebuild coverage. Exact budget-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5803852010. No other budget transition is accepted by this entry.\n\nThe same 19-assertion helper is also exercised by rebuild-openclaw, independently of the inherited private-MCP failure. Unique assertion counts are unchanged; one helper file is extracted. Revised exact-transition approval: https://github.com/NVIDIA/NemoClaw/pull/12305#issuecomment-5807159038.\n\nProposed exact budget transition for PR #12591: replace a restart progress-message check with a native gateway-owner observation before and after inference switching. Adds one generated probe and five probe conditions; direct and unique expectation counts do not exceed main. The imported helper also appears in the full-e2e transitive inventory. This entry requires maintainer review before landing on main. Remove it after #12591 merges.\n\nPR #12718 is the prerequisite for the PR #12382 budget transition recorded below. The exception matches only PR #12382 and both budget digests. A changed base or candidate budget invalidates it. The independent check reads trusted base policy, so this prerequisite must land on main before #12382 uses the exception. Remove after #12382 merges.\n\nMaintainer Prekshi Vyas (@prekshivyas) approved this exact refreshed PR #12382 transition on 2026-10-08: base budget SHA-256 53c51c4229d387633165771730f8f1a8373f84e9f3303b2144280027a56e3441 to candidate budget SHA-256 8162408384d7a6b97ef0062042c73d4bc9486f54d2dfa6c0c5732e42d1060e2a. Acceptance record: https://github.com/NVIDIA/NemoClaw/pull/12840#issuecomment-6066319444. It includes one additional unique assertion point and one generated probe condition. This refresh preserves the #12608 concurrent-gateway-ports reduction and the previously reviewed runtime assertion changes. The independent check is not waived: the refreshed exception must land on main before enforcement can accept it. A different PR or budget digest remains rejected. Remove after #12382 merges.\n\nPR #12777 adds exactly two approved live assertions for native host-local inference success and sibling provider isolation. Deterministic behavior remains in unit/integration tests. Approval transcription: https://github.com/NVIDIA/NemoClaw/pull/12777#issuecomment-6048385152. The independent check reads trusted base policy; this entry does not disable it. Remove after #12777 merges.\n\nThe #12777 budget digests account for main #12608 removing seven assertions from concurrent-gateway-ports. The candidate preserves that reduction and adds only the same two approved inference-routing assertions. No other file budget increases.\n\nPR #12886 approved the provider-smoke transition extracted by #12955. Approval: https://github.com/NVIDIA/NemoClaw/pull/12886#issuecomment-6083839176. The unchanged change digest binds the same nine assertion points and companion inventory. This entry supports local preliminary validation and the Slice 2 consumer. Independent CI for the prerequisite requires its own maintainer approval record; this entry does not approve that PR.\n\nPR #12958 extracts the same approved provider-smoke budget transition for #12955. Its exact, unedited maintainer approval is https://github.com/NVIDIA/NemoClaw/pull/12958#issuecomment-6093851571. This candidate entry supports static hooks; the independent check continues to verify the PR-specific approval on GitHub. Remove after #12958 merges.\n\nPR #13203 adds the approved 19 assertion points for real authenticated and credentialless DCode native-local requests, credential isolation and sibling denial. Approval: https://github.com/NVIDIA/NemoClaw/pull/13203#issuecomment-6180239679. This exact change digest supports local hooks and candidate CI. Independent enforcement still verifies the PR-specific maintainer approval on GitHub. Remove after #13203 merges.\n\nPR #13201 adds one generated probe block and one counted probe condition in the existing full E2E owner to verify the selected sandbox agent endpoint, API, model and credential reference. Rebecca Sliter approved this exact delta: https://github.com/NVIDIA/NemoClaw/pull/13201#issuecomment-6180464605. This entry supports local validation; the independent check must verify the maintainer record. Remove after #13201 merges.\n\nPR #13293 consolidates OpenClaw native-local scenarios into the existing switching owner and removes duplicated deterministic metadata checks and the redundant mock curl probe. Suite totals fall by 16 expect calls and 10 assertion points without adding live files. Only the owning file transitive allocation grows because it now imports existing live helpers. Maintainer authorization: https://github.com/NVIDIA/NemoClaw/pull/13293#issuecomment-6211036786. This exact transition supports candidate CI; independent enforcement still verifies the maintainer record.\n\nPR #13007 retains the same ten Pi native-local live assertion points approved at https://github.com/NVIDIA/NemoClaw/pull/13007#issuecomment-6175787892. The exact change digest is unchanged against its replacement OpenClaw parent #13293. This entry supports local checks against that stacked base; independent enforcement still checks the authenticated PR approval.\n\nPR #13582 adds eight live assertion points for the WSL2 IPv6 native-local policy boundary. Only openclaw-inference-switch.test.ts increases, by seven direct expectations and the existing onboard-success helper. Deterministic CIDR and receipt coverage remain in source tests. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13582#issuecomment-6308860348. Independent enforcement verifies that PR-specific record. Remove this preliminary local exception after merge.\n\nPR #13645 adds three approved live assertion points for engine-down uninstall diagnostics inside rebuild-openclaw. Exact approval: https://github.com/NVIDIA/NemoClaw/pull/13645#issuecomment-6429899630. This entry enables candidate CI; independent enforcement still verifies the PR-specific maintainer record. Remove after merge.\n\nPR #13771 adds four Hermes OpenRouter rebuild assertions and a bounded diagnostic probe. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13771#issuecomment-6427647915. The independent PR check verifies that comment. Remove after #13771 merges.\n\nPR #13873 adds two live command assertions for the CLI build and native Hermes Discord qualification when consuming protected evidence from an older trusted producer. Approval: https://github.com/NVIDIA/NemoClaw/pull/13873#issuecomment-6488667052. The parser and identity cases stay in e2e-support tests. Remove after #13873 merges.\n\nPR #13651 moves the native NVIDIA Discord rebuild proof from hermes-discord to hermes-inference-switch, which receives the public endpoint credential. The native switch target also checks status through its installed credential verifier after rebuild. This adds four assertion points for the live status and restored-provider boundary; deterministic rejection and command-failure cases remain in fast tests. This entry permits the approved transition in local and candidate checks; independent enforcement verifies the maintainer record at https://github.com/NVIDIA/NemoClaw/pull/13651#issuecomment-6377201610. The typed helper extraction retains every live predicate and the same unique and transitive totals; the direct census decreases because the phase now lives in the existing helper.\n\nPR #13635 adds the approved protected-runtime deadline companion and five unique assertion points, one generated probe block, and one probe condition. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13635#issuecomment-6383152261. This entry supports local hooks and candidate CI; independent enforcement verifies the PR-specific GitHub approval. Remove after #13635 merges.\n\nPR #13596 adds four live assertion points to the existing double-onboard target for #13595: the managed OpenClaw state volume exists before `nemoclaw uninstall`, uninstall succeeds, the volume is gone afterwards, and same-name onboarding succeeds. Deterministic removal and failure cases remain in fast tests. This entry permits the approved transition in local and candidate checks; independent enforcement verifies the maintainer record at https://github.com/NVIDIA/NemoClaw/pull/13596#issuecomment-6365742624. Remove after #13596 merges.\n\nPR #13515 extends dashboard-remote-bind with Hermes host-listener coverage. The dashboard remains remotely reachable, API health works on loopback, and the non-loopback API port refuses TCP connections. Approval: https://github.com/NVIDIA/NemoClaw/pull/13515#issuecomment-6295553350. This entry supports local and candidate checks; independent enforcement verifies the authenticated maintainer record.\n\nPR #13515 also checks Hermes loopback API health and non-loopback refusal after stop/start, preserving the onboarding assertions. The combined delta is approved at https://github.com/NVIDIA/NemoClaw/pull/13515#issuecomment-6298021751.\n\nPR #13515 verifies the Hermes API forward identity before health probes after onboarding and restart. These two additional process-ownership assertions are approved at https://github.com/NVIDIA/NemoClaw/pull/13515#issuecomment-6322568985.\n\nPR #13927 reuses the verified public HTTPS fixture transport for two Podman inference targets. Direct and unique assertion counts are unchanged. Each target gains eleven transitive assertion points from existing package and tunnel prerequisites; the extracted Anthropic response helper adds one live companion file. This exact transition supports local validation. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/13927#issuecomment-6524030655. Independent enforcement verifies this PR-specific record. Remove after merge.\n\nPR #14062 adds one live Ollama cleanup helper, three existing port-validation guards reached by gpu-double-onboard, and one shared shell probe. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14062#issuecomment-6582340290. This entry supports local hooks and candidate CI; independent enforcement verifies the PR-specific approval. Remove after merge.\n\nPR #13607 adds two live assertions and one read-only configuration probe to the existing balanced OpenClaw egress case for unavailable-search replies. The refreshed delta removes the unrelated public-fetch precondition guard while retaining both live assertions and the probe. Approved delta: https://github.com/NVIDIA/NemoClaw/pull/13607#issuecomment-6327887365. Remove after #13607 merges.\n\nPR #14000 replaces #12872 and retains one approved assertion point for owning-gateway connect sessions. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14000#issuecomment-6506269922. This entry enables candidate CI; independent enforcement verifies the PR-specific approval.\n\nPR #14122 retains the production bearerless provider-validation proof and private-publication proof in both Express targets. Spark and Station each request health on the two allowed addresses and require connection refusal on all discovered unintended addresses. Four added Spark assertions protect its separate physical-host path; deterministic URL construction remains in the support tests. The combined delta adds seven assertion points and one generated probe relative to main. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14122#issuecomment-6661407269. Independent enforcement verifies this PR-specific approval. Remove after merge.\n\nPR #14252 adds twelve live assertion points to the existing sandbox-survival owner for first-invocation cold public OpenClaw recovery, native and forwarded health, and retained sandbox/container identities on Docker and native Podman. Existing raw OpenShell survival evidence and target timeouts are unchanged. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14252#issuecomment-6676328443. This entry supports local and candidate checks; independent enforcement verifies the PR-specific approval record. Remove after merge.\n\nPR #14303 replaces #14201 and retains its two assertion points in hermes-root-entrypoint-smoke for qualification through the real entrypoint before gateway readiness. Maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14303#issuecomment-6713570086. This entry supports local hooks and candidate CI. Independent enforcement still verifies the PR-specific maintainer record. Remove after merge.\n\nPR #14512 adds24 net assertion points for native Switchyard cross-provider authorization, continuation policy enforcement, provider failure/recovery and a second credential scan. Three redundant proposed checks were omitted and two existing fixture-output checks remain covered by fast tests. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14512#issuecomment-6932725987. This branch entry supports local preliminary validation; independent CI verifies the PR-specific record. Remove after #14512 merges.\n\nPR #14512 retains its approved 24 assertion points and adds two generated conditions for bounded NULL diagnostics and PTY socket-state validation during sandbox retirement. Three unnecessary conditions were removed. Exact refreshed transition approved by Rebecca Sliter: https://github.com/NVIDIA/NemoClaw/pull/14512#issuecomment-6989339885. Independent enforcement still verifies this unedited maintainer record on GitHub.\n\nPR #14517 adds real shared-host MCP policy and credential composition proof with distinct paths and credentials, differing add-time DNS inputs, own-path success, configured-peer credential withholding, unconfigured-path denial, and owned cleanup. The delta adds 15 unique assertion points and one companion file. The two configured-peer assertion points require OpenShell enforcement; support tests cover status classification and rejection of simulated credential leaks or unintended peer authorization. Exact maintainer approval: https://github.com/NVIDIA/NemoClaw/pull/14517#issuecomment-7004275478. This branch entry supports preliminary local and candidate checks; independent enforcement verifies the recorded approval. Remove after merge.", "schemaVersion": 1, "exceptions": [ { @@ -161,7 +161,7 @@ }, { "pullRequest": 14517, - "changeSha256": "7f129199e585c9f9e65b7fd6dee1b9c5e504ca70377b859464ed17f9e5851686" + "changeSha256": "c12a7992f1a458b46416744bed676734e231812d4738f93d81a716ea282db426" } ] } diff --git a/test/e2e/README.md b/test/e2e/README.md index 92c9fef80f8..2541b610a9a 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -1125,6 +1125,12 @@ except `allowed_ips`. This live step proves that OpenShell enforces the refreshe depend on an external DNS rotation happening during the test. A failed step restores the captured policy before normal sandbox cleanup. +The shared-host MCP scenario sends each provider placeholder to both configured paths for OpenClaw, Hermes, and Deep Agents Code. +Its own path must authenticate; the peer must reject it without receiving the foreign raw credential. +The probe requires HTTP 401 or 403, and the server observation rejects a credential leak even when authentication fails. +Transport, TLS, timeout, and unrelated HTTP failures cannot establish credential withholding. +Support tests validate these oracles; candidate-bound MCP jobs must establish OpenShell enforcement. + The pin-recovery proof stays within the existing assertion budget by retiring fixture-detail checks: the probe's fixed HTTP method and JSON-RPC fields, and the removed proxy's `enc:v1:` and `proxy.pid` markers. `test/mcp/mcp-bridge-servers.test.ts` owns the fake server's protocol behavior, and diff --git a/test/e2e/live/mcp-bridge-reliability.ts b/test/e2e/live/mcp-bridge-reliability.ts index 1ec2468c92a..6daab2aabcd 100644 --- a/test/e2e/live/mcp-bridge-reliability.ts +++ b/test/e2e/live/mcp-bridge-reliability.ts @@ -431,7 +431,7 @@ export async function runMcpProviderRewriteProbe( sandboxName: string, targetUrl: string, method: string, - expectation: "allow" | "deny" | "deny-strict", + expectation: "allow" | "deny" | "deny-strict" | "withhold", artifactName: string, credentialKey = "FAKE_MCP_SECRET", toolName?: string, diff --git a/test/e2e/live/mcp-bridge-shared-host.ts b/test/e2e/live/mcp-bridge-shared-host.ts index 786fa91ad89..26ce043bc14 100644 --- a/test/e2e/live/mcp-bridge-shared-host.ts +++ b/test/e2e/live/mcp-bridge-shared-host.ts @@ -196,7 +196,29 @@ export async function assertSharedHostMcpComposition(options: { ).toBe(true); } const requestOffset = endpoint.requests.length; - for (const entry of entries) { + for (const [index, entry] of entries.entries()) { + const peer = entries[1 - index]; + const peerRequestOffset = endpoint.requests.length; + const withheld = await runMcpProviderRewriteProbe( + sandbox, + sandboxName, + `${tunnel.origin}${peer.pathname}`, + "tools/list", + "withhold", + `${entry.server}-credential-at-${peer.server}`, + entry.key, + undefined, + adapter, + ); + assertExitZero(withheld, `${entry.server} credential cannot authorize ${peer.server}`); + const peerRequests = endpoint.requests + .slice(peerRequestOffset) + .filter((request) => request.path === peer.pathname); + expect( + peerRequests.every( + (request) => !request.auth.includes(entry.secret) && request.responseStatus === 401, + ), + ).toBe(true); const denied = await runMcpProviderRewriteProbe( sandbox, sandboxName, diff --git a/test/e2e/live/mcp-provider-rewrite-probe.ts b/test/e2e/live/mcp-provider-rewrite-probe.ts index b6b4088bc34..44bb3db93b7 100644 --- a/test/e2e/live/mcp-provider-rewrite-probe.ts +++ b/test/e2e/live/mcp-provider-rewrite-probe.ts @@ -59,13 +59,13 @@ const req = https.request({ res.on("end", () => { console.log(JSON.stringify({ status: res.statusCode, body: data })); const allowed = res.statusCode === 200 && data.includes('"result"'); - const denied = res.statusCode === 403; + const denied = res.statusCode === 403 || (expectation === "withhold" && res.statusCode === 401); process.exit(expectation === "allow" ? (allowed ? 0 : 1) : (denied ? 0 : 1)); }); }); req.on("error", (error) => { console.error(error.message); - const strictDenied = expectation === "deny-strict" && /HTTP\\/1\\.[01] 403 Forbidden/.test(error.message); + const strictDenied = (expectation === "deny-strict" || expectation === "withhold") && /HTTP\\/1\\.[01] 403 Forbidden/.test(error.message); strictDenied && console.log(JSON.stringify({ status: 403, error: error.message })); process.exit(expectation === "deny" || strictDenied ? 0 : 1); }); diff --git a/test/e2e/support/mcp-bridge-shared-host.test.ts b/test/e2e/support/mcp-bridge-shared-host.test.ts index 208270fb190..7cc55d74d15 100644 --- a/test/e2e/support/mcp-bridge-shared-host.test.ts +++ b/test/e2e/support/mcp-bridge-shared-host.test.ts @@ -16,6 +16,9 @@ import * as bridgeCleanup from "../live/mcp-bridge-cleanup.ts"; import * as reliability from "../live/mcp-bridge-reliability.ts"; import * as servers from "../live/mcp-bridge-servers.ts"; import * as adminScope from "../live/openclaw-admin-scope.ts"; +import * as sandboxProbes from "../live/mcp-bridge-sandbox.ts"; +import { MCP_BRIDGE_TEST_CREDENTIALS } from "../fixtures/mcp-bridge-credentials.ts"; +import type { ShellProbeResult } from "../fixtures/shell-probe.ts"; import { startFakeMcpHttpsServer } from "../live/mcp-bridge-servers.ts"; const { tls, close } = createMcpFixtureTls(); @@ -181,3 +184,151 @@ it.each([ expect(execShell.mock.calls[0][1]).toContain(runtime); expect(execShell.mock.calls[0][1]).toContain("SHARED_ONE_MCP_SECRET"); }); + +it.each([ + ["withheld", "SHARED_ONE_MCP_SECRET", "success", 2], + ["gateway-rejection", "SHARED_ONE_MCP_SECRET", "success", 2], + ["foreign-credential", "SHARED_ONE_MCP_SECRET", "failure", 1], + ["foreign-credential", "SHARED_TWO_MCP_SECRET", "failure", 2], + ["peer-credential", "SHARED_ONE_MCP_SECRET", "failure", 1], + ["peer-credential", "SHARED_TWO_MCP_SECRET", "failure", 2], + ["transport-failure", "SHARED_ONE_MCP_SECRET", "failure", 1], +] as const)( + "requires configured-peer withholding for %s at %s", + async (behavior, affectedKey, expected, count) => { + type Options = Parameters[0]; + const requests: Array<{ path: string; auth: string; responseStatus: number }> = []; + const peerCalls: string[] = []; + vi.spyOn(adminScope, "approveOpenClawAdminScope").mockResolvedValue(); + vi.spyOn(servers, "startFakeMcpHttpsServer").mockResolvedValue({ + requests, + close: vi.fn(), + } as unknown as Awaited>); + vi.spyOn(servers, "startPublicMcpHttpsTunnel").mockResolvedValue({ + origin: "https://shared.example.test", + } as Awaited>); + vi.spyOn(dns, "lookup").mockResolvedValue([ + { address: "8.8.8.8", family: 4 }, + { address: "8.8.4.4", family: 4 }, + ] as never); + vi.spyOn(reliability, "addBridgeAndReadStatus").mockImplementation( + async (_host, _sandbox, options) => { + execFileSync( + process.execPath, + ["-e", 'require("node:dns/promises").lookup("shared.example.test", { all: true })'], + { + env: { ...process.env, NODE_OPTIONS: options.addNodeOptions }, + timeout: 10_000, + }, + ); + return ""; + }, + ); + vi.spyOn(sandboxProbes, "captureManagedMcpPolicy").mockResolvedValue({ + policy: { endpoints: [{ allowed_ips: ["8.8.4.4", "8.8.8.8"] }] }, + } as unknown as Awaited>); + const result = (exitCode = 0): ShellProbeResult => ({ + command: [], + exitCode, + stdout: "", + stderr: "", + signal: null, + timedOut: false, + artifacts: { stdout: "", stderr: "", result: "" }, + }); + const entries = [ + { + key: "SHARED_ONE_MCP_SECRET", + own: "/mcp", + peer: "/mcp-peer", + secret: MCP_BRIDGE_TEST_CREDENTIALS.host, + peerSecret: MCP_BRIDGE_TEST_CREDENTIALS.rotatedHost, + }, + { + key: "SHARED_TWO_MCP_SECRET", + own: "/mcp-peer", + peer: "/mcp", + secret: MCP_BRIDGE_TEST_CREDENTIALS.rotatedHost, + peerSecret: MCP_BRIDGE_TEST_CREDENTIALS.host, + }, + ]; + type Plan = { requests: typeof requests; peer: boolean; result: ShellProbeResult }; + const plans = new Map( + entries.flatMap<[string, Plan]>((entry) => { + const selected = entry.key === affectedKey ? behavior : "withheld"; + const peerAuth = { + withheld: `Bearer openshell:resolve:env:v1_${entry.key}`, + "gateway-rejection": "", + "foreign-credential": `Bearer ${entry.secret}`, + "peer-credential": `Bearer ${entry.peerSecret}`, + "transport-failure": "", + }[selected]; + return [ + [ + `${entry.key}:${entry.own}`, + { + requests: [{ path: entry.own, auth: `Bearer ${entry.secret}`, responseStatus: 200 }], + peer: false, + result: result(), + }, + ], + [ + `${entry.key}:${entry.peer}`, + { + requests: peerAuth + ? [ + { + path: entry.peer, + auth: peerAuth, + responseStatus: selected === "peer-credential" ? 200 : 401, + }, + ] + : [], + peer: true, + result: result(selected === "transport-failure" ? 1 : 0), + }, + ], + [`${entry.key}:/unconfigured`, { requests: [], peer: false, result: result() }], + ]; + }), + ); + vi.spyOn(reliability, "runMcpProviderRewriteProbe").mockImplementation( + async (_sandbox, _name, url, _method, expectation, _artifact, key) => { + const pathname = new URL(url).pathname; + const plan = plans.get(`${key}:${pathname}`)!; + requests.push(...plan.requests); + peerCalls.push(...(plan.peer ? [`${key}:${pathname}:${expectation}`] : [])); + return plan.result; + }, + ); + vi.spyOn(bridgeCleanup, "cleanupMcpBridge").mockResolvedValue(); + const host = { + command: vi.fn(async (_command: string, args: string[]) => + args[1] === "get" ? { ...result(1), stderr: "NOT_FOUND" } : result(), + ), + nemoclaw: vi.fn(async () => ({ ...result(), stdout: '{"bridges":[]}' })), + openshellCommandPath: "openshell", + } as unknown as Options["host"]; + const run = assertSharedHostMcpComposition({ + adapter: "openclaw-config", + host, + sandbox: {} as Options["sandbox"], + cleanup: { add: vi.fn() } as unknown as Options["cleanup"], + artifacts: { writeJson: vi.fn() } as unknown as Options["artifacts"], + progress: {} as Options["progress"], + sandboxName: "alpha", + }); + await expect( + run.then( + () => "success", + () => "failure", + ), + ).resolves.toBe(expected); + expect(peerCalls).toEqual( + ["SHARED_ONE_MCP_SECRET:/mcp-peer:withhold", "SHARED_TWO_MCP_SECRET:/mcp:withhold"].slice( + 0, + count, + ), + ); + }, +); diff --git a/test/e2e/support/mcp-provider-rewrite-probe.test.ts b/test/e2e/support/mcp-provider-rewrite-probe.test.ts index 7f093f3883e..3f79bb6fe7d 100644 --- a/test/e2e/support/mcp-provider-rewrite-probe.test.ts +++ b/test/e2e/support/mcp-provider-rewrite-probe.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import vm from "node:vm"; +import { EventEmitter } from "node:events"; import { describe, expect, it } from "vitest"; @@ -88,3 +89,66 @@ describe("managed MCP provider rewrite probe", () => { ); }); }); + +function runRewriteProbe(expectation: string, status: number, error?: string): number { + let exitCode = -1; + const request = Object.assign(new EventEmitter(), { end: () => {} }); + const response = Object.assign(new EventEmitter(), { + statusCode: status, + setEncoding: () => {}, + }); + new vm.Script(MCP_PROVIDER_REWRITE_PROBE_SOURCE).runInNewContext({ + require: () => ({ + request: (_options: unknown, respond: (response: unknown) => void) => { + request.end = error + ? () => { + request.emit("error", new Error(error)); + } + : () => { + respond(response); + response.emit("data", '{"result":{}}'); + response.emit("end"); + }; + return request; + }, + }), + process: { + argv: [ + "node", + "-", + "https://shared.example.test/mcp-peer", + "tools/list", + expectation, + "SOURCE_TOKEN", + ], + env: { SOURCE_TOKEN: "openshell:resolve:env:v1_SOURCE_TOKEN" }, + exit: (code: number) => { + exitCode = code; + }, + }, + Buffer, + URL, + console: { log: () => {}, error: () => {} }, + }); + return exitCode; +} + +it.each([ + [401, undefined, 0], + [403, undefined, 0], + [0, "HTTP/1.1 403 Forbidden", 0], + [200, undefined, 1], + [404, undefined, 1], + [500, undefined, 1], + [0, "ECONNRESET", 1], + [0, "ETIMEDOUT", 1], + [0, "certificate has expired", 1], +])("requires explicit credential rejection for peer status %s / %s", (status, error, expected) => { + expect(runRewriteProbe("withhold", status, error)).toBe(expected); +}); + +it("keeps strict route denial separate from credential withholding", () => { + expect(runRewriteProbe("deny-strict", 401)).toBe(1); + expect(runRewriteProbe("allow", 401)).toBe(1); + expect(runRewriteProbe("deny-strict", 0, "ECONNRESET")).toBe(1); +}); From d6f96fb667708f2bdc6bd970647d8f3623b2fe21 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 19 Nov 2026 04:27:58 -0800 Subject: [PATCH 12/17] test(mcp): keep credential probes out of Hermes startup Invoke the admitted Hermes interpreter directly for credential probes. Exercise quoted arguments and child exits through the generated command. Keep supervisor mutation guards, live assertions and deadlines unchanged. Signed-off-by: Deepak Jain --- test/e2e/live/mcp-bridge-reliability.ts | 6 +- .../support/mcp-bridge-shared-host.test.ts | 61 ++++++++++++++++++- 2 files changed, 62 insertions(+), 5 deletions(-) diff --git a/test/e2e/live/mcp-bridge-reliability.ts b/test/e2e/live/mcp-bridge-reliability.ts index 6daab2aabcd..d3713d177a4 100644 --- a/test/e2e/live/mcp-bridge-reliability.ts +++ b/test/e2e/live/mcp-bridge-reliability.ts @@ -442,13 +442,15 @@ export async function runMcpProviderRewriteProbe( const runtime = adapter === "openclaw-config" ? "node" - : `${adapter === "hermes-config" ? "/opt/hermes/.venv/bin/python" : "/opt/venv/bin/python3"} -c ${shellQuote("import subprocess, sys; raise SystemExit(subprocess.run(sys.argv[1:], check=False).returncode)")} node`; + : `${adapter === "hermes-config" ? "/opt/hermes/.venv/bin/python3" : "/opt/venv/bin/python3"} -c ${shellQuote("import subprocess, sys; raise SystemExit(subprocess.run(sys.argv[1:], check=False).returncode)")} node`; + // Hermes startup owns supervisor state and cannot be re-entered by an exec probe. + const launcher = adapter === "hermes-config" ? "" : "nemoclaw-start "; return sandbox.execShell( sandboxName, trustedSandboxShellScript( [ "set -eu", - `nemoclaw-start ${runtime} - ${shellQuote(targetUrl)} ${shellQuote(method)} ${shellQuote(expectation)} ${shellQuote(credentialKey)}${toolName ? ` ${shellQuote(toolName)}` : ""} <<'NEMOCLAW_MCP_PROVIDER_REWRITE_PROBE'`, + `${launcher}${runtime} - ${shellQuote(targetUrl)} ${shellQuote(method)} ${shellQuote(expectation)} ${shellQuote(credentialKey)}${toolName ? ` ${shellQuote(toolName)}` : ""} <<'NEMOCLAW_MCP_PROVIDER_REWRITE_PROBE'`, MCP_PROVIDER_REWRITE_PROBE_SOURCE, "NEMOCLAW_MCP_PROVIDER_REWRITE_PROBE", ].join("\n"), diff --git a/test/e2e/support/mcp-bridge-shared-host.test.ts b/test/e2e/support/mcp-bridge-shared-host.test.ts index 7cc55d74d15..76b94a94d44 100644 --- a/test/e2e/support/mcp-bridge-shared-host.test.ts +++ b/test/e2e/support/mcp-bridge-shared-host.test.ts @@ -1,11 +1,14 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { execFileSync } from "node:child_process"; +import { execFileSync, spawnSync } from "node:child_process"; import dns from "node:dns/promises"; import fs from "node:fs"; import https from "node:https"; import path from "node:path"; +import os from "node:os"; +import { shellQuote } from "../../../src/lib/core/shell-quote"; +import { MCP_PROVIDER_REWRITE_PROBE_SOURCE } from "../live/mcp-provider-rewrite-probe.ts"; import { afterAll, afterEach, expect, it, vi } from "vitest"; import { createMcpFixtureTls } from "../fixtures/mcp-fixture-tls.ts"; import { @@ -162,7 +165,7 @@ it.each(["openclaw-config", "hermes-config", "deepagents-config"] as const)( it.each([ ["openclaw-config", "nemoclaw-start node -"], - ["hermes-config", "nemoclaw-start /opt/hermes/.venv/bin/python -c"], + ["hermes-config", "/opt/hermes/.venv/bin/python3 -c"], ["deepagents-config", "nemoclaw-start /opt/venv/bin/python3 -c"], ] as const)("uses the admitted %s runtime for credential probes", async (adapter, runtime) => { const result = { exitCode: 0, stdout: "", stderr: "" }; @@ -181,10 +184,62 @@ it.each([ adapter, ), ).toBe(result); - expect(execShell.mock.calls[0][1]).toContain(runtime); + expect(execShell.mock.calls[0][1]).toContain(`\n${runtime}`); expect(execShell.mock.calls[0][1]).toContain("SHARED_ONE_MCP_SECRET"); }); +it.each([0, 23])( + "runs Hermes credential probes without restarting its supervisor (exit %s)", + async (exitCode) => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "hermes-mcp-probe-")); + try { + fs.writeFileSync( + path.join(directory, "nemoclaw-start"), + "#!/bin/sh\nprintf '%s\\n' '[SECURITY] Hermes runtime config guard refuses mutation under a foreign PID 1' >&2\nexit 23\n", + { mode: 0o700 }, + ); + const python = execFileSync("python3", ["-c", "import sys; print(sys.executable)"], { + encoding: "utf8", + }).trim(); + const target = "https://shared.example.test/mcp?label=some'quote"; + const execShell = vi.fn().mockResolvedValue({ exitCode: 0, stdout: "", stderr: "" }); + type Sandbox = Parameters[0]; + await reliability.runMcpProviderRewriteProbe( + { execShell } as unknown as Sandbox, + "alpha", + target, + "tools/list", + "allow", + "hermes-process-probe", + "SHARED_ONE_MCP_SECRET", + undefined, + "hermes-config", + ); + const script = (execShell.mock.calls[0][1] as string) + .replace(/\/opt\/hermes\/\.venv\/bin\/python3?(?= )/u, shellQuote(python)) + .replace( + MCP_PROVIDER_REWRITE_PROBE_SOURCE, + `process.stdout.write(JSON.stringify(process.argv.slice(2))); process.exit(${exitCode});`, + ); + const result = spawnSync("sh", ["-c", script], { + encoding: "utf8", + env: { ...process.env, PATH: `${directory}:${process.env.PATH}` }, + timeout: 10_000, + }); + expect(result.status).toBe(exitCode); + expect(result.stderr).toBe(""); + expect(JSON.parse(result.stdout)).toEqual([ + target, + "tools/list", + "allow", + "SHARED_ONE_MCP_SECRET", + ]); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }, +); + it.each([ ["withheld", "SHARED_ONE_MCP_SECRET", "success", 2], ["gateway-rejection", "SHARED_ONE_MCP_SECRET", "success", 2], From b31fd190aaf2de78a71b8a588ceec0e62d6c635d Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Thu, 19 Nov 2026 07:28:33 -0800 Subject: [PATCH 13/17] test(mcp): keep shared-host status DNS deterministic Use the first controlled answer set for both status calls while the second add receives a subset. Preserve DNS drift and credential checks. Cover the IPv6 answers observed in the failed shared-host run. Signed-off-by: Deepak Jain --- test/e2e/README.md | 1 + test/e2e/live/mcp-bridge-reliability.ts | 2 + test/e2e/live/mcp-bridge-shared-host.ts | 39 ++++--- .../support/mcp-bridge-shared-host.test.ts | 108 ++++++++++++++++-- 4 files changed, 124 insertions(+), 26 deletions(-) diff --git a/test/e2e/README.md b/test/e2e/README.md index b78c3e7bc72..96cef3de097 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -1126,6 +1126,7 @@ depend on an external DNS rotation happening during the test. A failed step rest policy before normal sandbox cleanup. The shared-host MCP scenario sends each provider placeholder to both configured paths for OpenClaw, Hermes, and Deep Agents Code. +The fixture gives status the first DNS answer set and gives the second add a subset, keeping status independent of later live DNS changes. Its own path must authenticate; the peer must reject it without receiving the foreign raw credential. The probe requires HTTP 401 or 403, and the server observation rejects a credential leak even when authentication fails. Transport, TLS, timeout, and unrelated HTTP failures cannot establish credential withholding. diff --git a/test/e2e/live/mcp-bridge-reliability.ts b/test/e2e/live/mcp-bridge-reliability.ts index d3713d177a4..cbfc976f094 100644 --- a/test/e2e/live/mcp-bridge-reliability.ts +++ b/test/e2e/live/mcp-bridge-reliability.ts @@ -57,6 +57,7 @@ export async function addBridgeAndReadStatus( credentialEnvName?: string; applyHostPolicyEdit?: boolean; addNodeOptions?: string; + statusNodeOptions?: string; }, ): Promise { await (options.applyHostPolicyEdit === false @@ -92,6 +93,7 @@ export async function addBridgeAndReadStatus( artifactName: `${options.artifactPrefix}-mcp-status-json`, env: { ...buildAvailabilityProbeEnv(), + ...(options.statusNodeOptions ? { NODE_OPTIONS: options.statusNodeOptions } : {}), [credentialEnvName]: credential, }, redactionValues: [credential], diff --git a/test/e2e/live/mcp-bridge-shared-host.ts b/test/e2e/live/mcp-bridge-shared-host.ts index 26ce043bc14..d89a8b06664 100644 --- a/test/e2e/live/mcp-bridge-shared-host.ts +++ b/test/e2e/live/mcp-bridge-shared-host.ts @@ -24,7 +24,7 @@ import { startFakeMcpHttpsServer, startPublicMcpHttpsTunnel } from "./mcp-bridge type Address = { address: string; family: number }; -/** Control the add process's DNS input without replacing policy or provider operations. */ +/** Control a CLI process's DNS input without replacing policy or provider operations. */ export async function withMcpDnsAnswers( hostname: string, addresses: readonly Address[], @@ -53,9 +53,9 @@ dns.lookup = async (hostname, options) => { { mode: 0o600 }, ); const result = await run(`--require=${JSON.stringify(preload)}`); - // An unused preload cannot establish that the real add saw the intended DNS input. + // An unused preload cannot establish that the CLI command saw the intended DNS input. if (fs.readFileSync(observed, "utf8") !== JSON.stringify(addresses)) { - throw new Error("MCP add did not consume the controlled DNS answers"); + throw new Error("MCP command did not consume the controlled DNS answers"); } return result; } finally { @@ -148,21 +148,24 @@ export async function assertSharedHostMcpComposition(options: { cleanup.add(`remove shared-host MCP registration and provider ${entry.server}`, run); return run; }); - for (const entry of entries) { - await withMcpDnsAnswers(hostname, entry.answers, (addNodeOptions) => - addBridgeAndReadStatus(host, sandbox, { - sandboxName, - mcpUrl: `${tunnel.origin}${entry.pathname}`, - expectedAdapter: adapter, - artifactPrefix: entry.server, - serverName: entry.server, - credentialEnvName: entry.key, - credential: entry.secret, - applyHostPolicyEdit: false, - addNodeOptions, - }), - ); - } + await withMcpDnsAnswers(hostname, answers, async (statusNodeOptions) => { + for (const entry of entries) { + await withMcpDnsAnswers(hostname, entry.answers, (addNodeOptions) => + addBridgeAndReadStatus(host, sandbox, { + sandboxName, + mcpUrl: `${tunnel.origin}${entry.pathname}`, + expectedAdapter: adapter, + artifactPrefix: entry.server, + serverName: entry.server, + credentialEnvName: entry.key, + credential: entry.secret, + applyHostPolicyEdit: false, + addNodeOptions, + statusNodeOptions, + }), + ); + } + }); for (const entry of entries) { const captured = await captureManagedMcpPolicy(sandbox, { sandboxName, diff --git a/test/e2e/support/mcp-bridge-shared-host.test.ts b/test/e2e/support/mcp-bridge-shared-host.test.ts index 76b94a94d44..4b8f0eb31d3 100644 --- a/test/e2e/support/mcp-bridge-shared-host.test.ts +++ b/test/e2e/support/mcp-bridge-shared-host.test.ts @@ -71,6 +71,104 @@ it("rejects an unused DNS preload and removes it when the add fails", async () = expect(fs.existsSync(directory)).toBe(false); }); +function lookupSharedHostAnswers(nodeOptions: string): Array<{ address: string; family: number }> { + return JSON.parse( + execFileSync( + process.execPath, + [ + "-e", + 'require("node:dns/promises").lookup("shared.example.test", { all: true }).then(answers => process.stdout.write(JSON.stringify(answers)))', + ], + { env: { ...process.env, NODE_OPTIONS: nodeOptions }, encoding: "utf8", timeout: 10_000 }, + ), + ); +} + +it.each(["shared-one", "shared-two"])( + "holds status DNS steady when live answers change for %s", + async (driftingServer) => { + type Options = Parameters[0]; + const firstAnswers = [ + { address: "104.16.230.132", family: 4 }, + { address: "104.16.231.132", family: 4 }, + ]; + const liveAnswers = [ + ...firstAnswers, + { address: "2606:4700::6810:e684", family: 6 }, + { address: "2606:4700::6810:e784", family: 6 }, + ]; + const observations: Array<{ server: string; command: string; answers: typeof firstAnswers }> = + []; + vi.spyOn(adminScope, "approveOpenClawAdminScope").mockResolvedValue(); + vi.spyOn(servers, "startFakeMcpHttpsServer").mockResolvedValue({ + close: vi.fn(), + } as unknown as Awaited>); + vi.spyOn(servers, "startPublicMcpHttpsTunnel").mockResolvedValue({ + origin: "https://shared.example.test", + } as Awaited>); + vi.spyOn(dns, "lookup").mockResolvedValue(firstAnswers as never); + const stop = new Error("stop after controlled DNS handoff"); + vi.spyOn(sandboxProbes, "captureManagedMcpPolicy").mockRejectedValue(stop); + const host = { + nemoclaw: vi.fn(async (args: string[], options: { env: NodeJS.ProcessEnv }) => { + const [, , command, server] = args; + const nodeOptions = options.env.NODE_OPTIONS; + const answers = nodeOptions + ? lookupSharedHostAnswers(nodeOptions) + : server === driftingServer + ? liveAnswers + : firstAnswers; + observations.push({ server, command, answers }); + const pins = answers.map((entry) => entry.address); + return { + exitCode: 0, + stderr: "", + stdout: JSON.stringify({ + server, + url: `https://shared.example.test${server === "shared-one" ? "/mcp" : "/mcp-peer"}`, + support: { adapter: "openclaw-config" }, + env: { + names: [server === "shared-one" ? "SHARED_ONE_MCP_SECRET" : "SHARED_TWO_MCP_SECRET"], + ready: true, + }, + provider: { + name: `alpha-mcp-${server}`, + present: true, + attached: true, + state: "configured", + }, + policy: { name: `mcp-bridge-${server}`, present: true, state: "configured" }, + adapter: { registered: true }, + warnings: + pins.join(",") === firstAnswers.map((entry) => entry.address).join(",") + ? [] + : [ + "Public DNS answers differ from the recorded pins. Run mcp update --refresh-public-pins to refresh the live policy.", + ], + }), + }; + }), + } as unknown as Options["host"]; + await expect( + assertSharedHostMcpComposition({ + adapter: "openclaw-config", + host, + sandbox: {} as Options["sandbox"], + cleanup: { add: vi.fn() } as unknown as Options["cleanup"], + artifacts: { writeJson: vi.fn() } as unknown as Options["artifacts"], + progress: {} as Options["progress"], + sandboxName: "alpha", + }), + ).rejects.toThrow(stop.message); + expect(observations).toEqual([ + { server: "shared-one", command: "add", answers: firstAnswers }, + { server: "shared-one", command: "status", answers: firstAnswers }, + { server: "shared-two", command: "add", answers: firstAnswers.slice(1) }, + { server: "shared-two", command: "status", answers: firstAnswers }, + ]); + }, +); + it("authenticates each MCP path with its own credential through real HTTPS", async () => { const server = await startFakeMcpHttpsServer({ secret: "first", @@ -268,14 +366,8 @@ it.each([ ] as never); vi.spyOn(reliability, "addBridgeAndReadStatus").mockImplementation( async (_host, _sandbox, options) => { - execFileSync( - process.execPath, - ["-e", 'require("node:dns/promises").lookup("shared.example.test", { all: true })'], - { - env: { ...process.env, NODE_OPTIONS: options.addNodeOptions }, - timeout: 10_000, - }, - ); + lookupSharedHostAnswers(options.addNodeOptions!); + lookupSharedHostAnswers(options.statusNodeOptions!); return ""; }, ); From ca23c78c41204a6ceaab97b1f75be88f406b6842 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Fri, 20 Nov 2026 08:33:14 -0800 Subject: [PATCH 14/17] test(mcp): control bounded status DNS in shared-host coverage The isolated status resolver clears inherited loader options, so the shared-host fixture never reached its callback lookup. Load only the fixture explicitly in that resolver child and preserve its environment clearing, timeout and unrelated DNS behavior. Exercise the real public-pin status consumer and bounded resolver. Keep all live policy, credential-isolation and cleanup assertions, and correct the fixture guidance. Refs #13800. Signed-off-by: Deepak Jain --- test/e2e/README.md | 5 +- test/e2e/live/mcp-bridge-shared-host.ts | 40 ++++++++-- test/e2e/mock-parity.json | 1 + .../support/mcp-bridge-shared-host.test.ts | 16 +++- .../e2e/support/mcp-bridge-status-dns.test.ts | 79 +++++++++++++++++++ 5 files changed, 130 insertions(+), 11 deletions(-) create mode 100644 test/e2e/support/mcp-bridge-status-dns.test.ts diff --git a/test/e2e/README.md b/test/e2e/README.md index 96cef3de097..9b21188d5ac 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -1126,7 +1126,10 @@ depend on an external DNS rotation happening during the test. A failed step rest policy before normal sandbox cleanup. The shared-host MCP scenario sends each provider placeholder to both configured paths for OpenClaw, Hermes, and Deep Agents Code. -The fixture gives status the first DNS answer set and gives the second add a subset, keeping status independent of later live DNS changes. +The fixture gives the second add a subset of the first DNS answer set. +For status, its preload explicitly loads the fixture in the isolated resolver child and supplies the first answer set. +The resolver keeps its cleared loader environment and existing deadline. +A process regression exercises the real bounded resolver and public-pin status inspection. Its own path must authenticate; the peer must reject it without receiving the foreign raw credential. The probe requires HTTP 401 or 403, and the server observation rejects a credential leak even when authentication fails. Transport, TLS, timeout, and unrelated HTTP failures cannot establish credential withholding. diff --git a/test/e2e/live/mcp-bridge-shared-host.ts b/test/e2e/live/mcp-bridge-shared-host.ts index d89a8b06664..f925dd5ed3e 100644 --- a/test/e2e/live/mcp-bridge-shared-host.ts +++ b/test/e2e/live/mcp-bridge-shared-host.ts @@ -35,19 +35,47 @@ export async function withMcpDnsAnswers( const directory = fs.mkdtempSync(path.join(scratch, "mcp-shared-host-dns-")); const preload = path.join(directory, "lookup.cjs"); const observed = path.join(directory, "observed.json"); + const callbackPreload = path.join(directory, "callback.cjs"); try { fs.writeFileSync( preload, ` -const dns = require("node:dns/promises"); -const original = dns.lookup; +const promises = require("node:dns/promises"); +const childProcess = require("node:child_process"); +const originalPromisesLookup = promises.lookup; +const originalExecFile = childProcess.execFile; +const target = ${JSON.stringify(hostname)}; const answers = ${JSON.stringify(addresses)}; -dns.lookup = async (hostname, options) => { - if (hostname !== ${JSON.stringify(hostname)} || options?.all !== true) { - return original.call(dns, hostname, options); - } +function selectedAnswers() { require("node:fs").writeFileSync(${JSON.stringify(observed)}, JSON.stringify(answers)); return answers.map(answer => ({ ...answer })); +} +promises.lookup = async (hostname, options) => { + if (hostname !== target || options?.all !== true) { + return originalPromisesLookup.call(promises, hostname, options); + } + return selectedAnswers(); +}; +// Status clears loader environment variables. Load only this fixture explicitly in its DNS child. +childProcess.execFile = function(file, args, ...rest) { + const options = rest[0]; + const boundedLookup = file === process.execPath && Array.isArray(args) && args.length === 4 && + args[0] === "-e" && args[1].includes('require("node:dns").lookup(') && + args[2] === "--" && args[3] === target && + options?.env?.NODE_OPTIONS === "" && options?.env?.NODE_PATH === ""; + return originalExecFile.call(this, file, + boundedLookup ? ["--require", ${JSON.stringify(callbackPreload)}, ...args] : args, ...rest); +}; +module.exports = selectedAnswers; +`, + { mode: 0o600 }, + ); + fs.writeFileSync( + callbackPreload, + // Only the recognized, host-bound resolver child loads this callback fixture. + `const answers = require(${JSON.stringify(preload)}); +require("node:dns").lookup = (_hostname, _options, callback) => { + queueMicrotask(() => callback(null, answers())); }; `, { mode: 0o600 }, diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index cf37375d667..11c902d7810 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -861,6 +861,7 @@ "test/e2e/support/mcp-bridge-onboard-env.test.ts", "test/e2e/support/mcp-bridge-reliability.test.ts", "test/e2e/support/mcp-bridge-shared-host.test.ts", + "test/e2e/support/mcp-bridge-status-dns.test.ts", "test/e2e/support/retry-policy.test.ts", "test/e2e/support/mcp-bridge-sandbox.test.ts", "test/e2e/support/mcp-bridge-tool-discovery.test.ts", diff --git a/test/e2e/support/mcp-bridge-shared-host.test.ts b/test/e2e/support/mcp-bridge-shared-host.test.ts index 4b8f0eb31d3..2682a33b42e 100644 --- a/test/e2e/support/mcp-bridge-shared-host.test.ts +++ b/test/e2e/support/mcp-bridge-shared-host.test.ts @@ -8,6 +8,7 @@ import https from "node:https"; import path from "node:path"; import os from "node:os"; import { shellQuote } from "../../../src/lib/core/shell-quote"; +import { SOURCE_REQUIRE_HOOK } from "../../helpers/source-loader-options"; import { MCP_PROVIDER_REWRITE_PROBE_SOURCE } from "../live/mcp-provider-rewrite-probe.ts"; import { afterAll, afterEach, expect, it, vi } from "vitest"; import { createMcpFixtureTls } from "../fixtures/mcp-fixture-tls.ts"; @@ -71,13 +72,20 @@ it("rejects an unused DNS preload and removes it when the add fails", async () = expect(fs.existsSync(directory)).toBe(false); }); -function lookupSharedHostAnswers(nodeOptions: string): Array<{ address: string; family: number }> { +function lookupSharedHostAnswers( + nodeOptions: string, + bounded = false, +): Array<{ address: string; family: number }> { return JSON.parse( execFileSync( process.execPath, [ + "--require", + SOURCE_REQUIRE_HOOK, "-e", - 'require("node:dns/promises").lookup("shared.example.test", { all: true }).then(answers => process.stdout.write(JSON.stringify(answers)))', + bounded + ? 'require("./src/lib/adapters/dns/resolve.js").resolveHostAddressesBounded("shared.example.test", 2_000).then(answers => process.stdout.write(JSON.stringify(answers)))' + : 'require("node:dns/promises").lookup("shared.example.test", { all: true }).then(answers => process.stdout.write(JSON.stringify(answers)))', ], { env: { ...process.env, NODE_OPTIONS: nodeOptions }, encoding: "utf8", timeout: 10_000 }, ), @@ -114,7 +122,7 @@ it.each(["shared-one", "shared-two"])( const [, , command, server] = args; const nodeOptions = options.env.NODE_OPTIONS; const answers = nodeOptions - ? lookupSharedHostAnswers(nodeOptions) + ? lookupSharedHostAnswers(nodeOptions, command === "status") : server === driftingServer ? liveAnswers : firstAnswers; @@ -367,7 +375,7 @@ it.each([ vi.spyOn(reliability, "addBridgeAndReadStatus").mockImplementation( async (_host, _sandbox, options) => { lookupSharedHostAnswers(options.addNodeOptions!); - lookupSharedHostAnswers(options.statusNodeOptions!); + lookupSharedHostAnswers(options.statusNodeOptions!, true); return ""; }, ); diff --git a/test/e2e/support/mcp-bridge-status-dns.test.ts b/test/e2e/support/mcp-bridge-status-dns.test.ts new file mode 100644 index 00000000000..97a327d34a8 --- /dev/null +++ b/test/e2e/support/mcp-bridge-status-dns.test.ts @@ -0,0 +1,79 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { expect, it } from "vitest"; +import { SOURCE_REQUIRE_HOOK } from "../../helpers/source-loader-options"; +import { withMcpDnsAnswers } from "../live/mcp-bridge-shared-host"; + +it("controls public-pin status through the isolated bounded DNS resolver", async () => { + const answers = [ + { address: "104.16.230.132", family: 4 }, + { address: "104.16.231.132", family: 4 }, + ]; + let observation: unknown; + await withMcpDnsAnswers("shared.example.test", answers, async (nodeOptions) => { + const result = spawnSync( + process.execPath, + [ + "--require", + SOURCE_REQUIRE_HOOK, + "-e", + ` +const childProcess = require("node:child_process"); +const execFile = childProcess.execFile; +const launches = []; +childProcess.execFile = function(file, args, options, callback) { + const child = execFile.call(this, file, args, options, callback); + launches.push({ + hostname: args.at(-1), + fixtureLoaded: child.spawnargs[1] === "--require", + loaderEnvironmentCleared: options.env.NODE_OPTIONS === "" && options.env.NODE_PATH === "", + timeout: options.timeout, + killSignal: options.killSignal, + }); + return child; +}; +const { resolveHostAddressesBounded } = require("./src/lib/adapters/dns/resolve.js"); +const { inspectMcpRecordedPublicTargetPins } = require("./src/lib/actions/sandbox/mcp-bridge-url-validation.js"); +(async () => { + const status = await inspectMcpRecordedPublicTargetPins( + new URL("https://shared.example.test/mcp"), + ["104.16.230.132", "104.16.231.132"], + hostname => resolveHostAddressesBounded(hostname, 2_000), + ); + const unrelated = await resolveHostAddressesBounded("127.0.0.1", 2_000); + process.stdout.write(JSON.stringify({ status, unrelated, launches })); +})().catch(error => { console.error(error); process.exitCode = 1; }); +`, + ], + { + env: { ...process.env, NODE_OPTIONS: nodeOptions }, + encoding: "utf8", + timeout: 20_000, + }, + ); + expect(result.status, result.stderr).toBe(0); + observation = JSON.parse(result.stdout); + }); + expect(observation).toEqual({ + status: { state: "match", currentAddresses: answers.map(({ address }) => address) }, + unrelated: [{ address: "127.0.0.1", family: 4 }], + launches: [ + { + hostname: "shared.example.test", + fixtureLoaded: true, + loaderEnvironmentCleared: true, + timeout: 2_000, + killSignal: "SIGKILL", + }, + { + hostname: "127.0.0.1", + fixtureLoaded: false, + loaderEnvironmentCleared: true, + timeout: 2_000, + killSignal: "SIGKILL", + }, + ], + }); +}, 30_000); From e9b593f7311a1af5326a308efd09aaa85db4da19 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Fri, 20 Nov 2026 11:22:41 -0800 Subject: [PATCH 15/17] test(rebuild): load shared source dependencies in lock checks Rebuild lock tests must run without plugin build output. Use the existing source preload for both children so shared CommonJS imports resolve to their typed source. Keep the real entry points, process deadlines and lock and registry assertions. Signed-off-by: Deepak Jain --- src/lib/actions/sandbox/rebuild-entry-lock.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild-entry-lock.test.ts b/src/lib/actions/sandbox/rebuild-entry-lock.test.ts index dd7543f882a..f269ad50ce9 100644 --- a/src/lib/actions/sandbox/rebuild-entry-lock.test.ts +++ b/src/lib/actions/sandbox/rebuild-entry-lock.test.ts @@ -8,6 +8,7 @@ import { fileURLToPath } from "node:url"; import path from "node:path"; import { expect, test } from "../../../../test/helpers/owned-test-resources"; +import { SOURCE_REQUIRE_HOOK } from "../../../../test/helpers/source-loader-options"; // Passing CI shards ran each case in 2.2-4.7 s, including lock-holder startup // (#14689). This deadline allows slower runners and still reports the child's @@ -55,7 +56,7 @@ test.for(["registered", "missing"] as const)( process.execPath, [ "--require", - "tsx/cjs", + SOURCE_REQUIRE_HOOK, "-e", ` const session = require(process.argv[1]); @@ -78,7 +79,7 @@ test.for(["registered", "missing"] as const)( process.execPath, [ "--require", - "tsx/cjs", + SOURCE_REQUIRE_HOOK, "-e", ` const entry = require(process.argv[1]); From fa7c5427669b9f56bb25d9d8f59ce08248ba5a21 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Fri, 20 Nov 2026 12:26:18 -0800 Subject: [PATCH 16/17] test(sandbox): prepare catalog for rebuild lock regression Rebuild lock tests exit during startup when an unbuilt checkout lacks the serving catalog. Generate it with the existing source loader before starting either child. Replace the catalog atomically so concurrent readers see complete output. Retain lock-holder stderr to report startup failures. Signed-off-by: Deepak Jain --- .../sandbox/rebuild-entry-lock.test.ts | 37 ++++++++++++++++++- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild-entry-lock.test.ts b/src/lib/actions/sandbox/rebuild-entry-lock.test.ts index f269ad50ce9..8692dcca8ec 100644 --- a/src/lib/actions/sandbox/rebuild-entry-lock.test.ts +++ b/src/lib/actions/sandbox/rebuild-entry-lock.test.ts @@ -1,11 +1,12 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawn, type ChildProcess } from "node:child_process"; +import { execFileSync, spawn, type ChildProcess } from "node:child_process"; import { once } from "node:events"; import fs from "node:fs"; import { fileURLToPath } from "node:url"; import path from "node:path"; +import { beforeAll } from "vitest"; import { expect, test } from "../../../../test/helpers/owned-test-resources"; import { SOURCE_REQUIRE_HOOK } from "../../../../test/helpers/source-loader-options"; @@ -15,6 +16,34 @@ import { SOURCE_REQUIRE_HOOK } from "../../../../test/helpers/source-loader-opti // stderr before the 30 s test timeout. const REBUILD_CHILD_TIMEOUT_MS = 20_000; +beforeAll(() => { + const rootDir = fileURLToPath(new URL("../../../../", import.meta.url)); + const catalogDir = path.join(rootDir, "dist/managed-inference"); + fs.mkdirSync(catalogDir, { recursive: true }); + const stagingDir = fs.mkdtempSync(path.join(catalogDir, "rebuild-entry-lock-")); + const stagedCatalog = path.join(stagingDir, "catalog.json"); + try { + // Source-loaded inference modules need the real catalog even without a CLI build. + execFileSync( + process.execPath, + [ + "--require", + SOURCE_REQUIRE_HOOK, + "-e", + "require(process.argv[1]).generateServingCatalog({ rootDir: process.argv[2], outputPath: process.argv[3] });", + fileURLToPath(new URL("../../inference/serving/generate-catalog.ts", import.meta.url)), + rootDir, + stagedCatalog, + ], + { cwd: rootDir, timeout: REBUILD_CHILD_TIMEOUT_MS, stdio: "pipe" }, + ); + // Other test workers must only see complete catalog bytes. + fs.renameSync(stagedCatalog, path.join(catalogDir, "catalog.json")); + } finally { + fs.rmSync(stagingDir, { recursive: true, force: true }); + } +}, REBUILD_CHILD_TIMEOUT_MS); + function firstOutput(child: ChildProcess, label: string, stderr: () => string): Promise { return Promise.race([ once(child.stdout!, "data"), @@ -73,6 +102,10 @@ test.for(["registered", "missing"] as const)( { env, stdio: ["ignore", "pipe", "pipe"] }, ), ); + let holderStderr = ""; + holder.stderr!.setEncoding("utf8").on("data", (chunk: string) => { + holderStderr += chunk; + }); // Load the rebuild entry while the holder starts, then run it once the locks are held. const rebuild = resources.ownChild( spawn( @@ -109,7 +142,7 @@ test.for(["registered", "missing"] as const)( }); const closed = once(rebuild, "close"); await Promise.all([ - firstOutput(holder, "lock holder", () => ""), + firstOutput(holder, "lock holder", () => holderStderr), firstOutput(rebuild, "rebuild entry", () => stderr), ]); const onboardLock = path.join(stateDir, "onboard.lock"); From a523938a80699abd8a4a0ed69c9c40c09f6a9583 Mon Sep 17 00:00:00 2001 From: Deepak Jain Date: Fri, 20 Nov 2026 13:58:46 -0800 Subject: [PATCH 17/17] test(mcp): keep distinct-endpoint setup in its scenario Keep the single-use distinct-host setup beside its OpenClaw lifecycle assertions and remove the exported wrapper. Preserve tunnel setup, credential options and cleanup registration. Reuse each caller's bridge values during credential rotation and resolve the adapter through the agent registry. This removes repeated argument lists and duplicate adapter classification. Signed-off-by: Deepak Jain --- test/e2e/live/mcp-bridge-shared-host.ts | 34 ---------- test/e2e/live/mcp-bridge.test.ts | 88 ++++++++++--------------- 2 files changed, 36 insertions(+), 86 deletions(-) diff --git a/test/e2e/live/mcp-bridge-shared-host.ts b/test/e2e/live/mcp-bridge-shared-host.ts index f925dd5ed3e..92014c73229 100644 --- a/test/e2e/live/mcp-bridge-shared-host.ts +++ b/test/e2e/live/mcp-bridge-shared-host.ts @@ -294,37 +294,3 @@ export async function assertSharedHostMcpComposition(options: { ); } } - -/** Keep the existing different-host credential case beside the same-host composition case. */ -export async function addDistinctCredentialMcpEndpoint(options: { - host: HostCliClient; - sandbox: SandboxClient; - cleanup: CleanupRegistry; - progress: TestProgress; - sandboxName: string; - serverOptions: Parameters[0]; -}) { - const { host, sandbox, cleanup, progress, sandboxName, serverOptions } = options; - const endpoint = await startFakeMcpHttpsServer(serverOptions); - cleanup.add("stop distinct MCP HTTPS server", () => endpoint.close()); - const tunnel = await startPublicMcpHttpsTunnel({ - cleanup, - label: "distinct credential MCP HTTPS server", - progress, - server: endpoint, - }); - cleanup.add("remove distinct credential bridge", () => - cleanupMcpBridge(host, sandboxName, "distinct", "openclaw-config"), - ); - await addBridgeAndReadStatus(host, sandbox, { - sandboxName, - mcpUrl: tunnel.url, - expectedAdapter: "openclaw-config", - serverName: "distinct", - credentialEnvName: "DISTINCT_MCP_SECRET", - credential: serverOptions.secret, - artifactPrefix: "openclaw-distinct", - applyHostPolicyEdit: false, - }); - return { endpoint, tunnel }; -} diff --git a/test/e2e/live/mcp-bridge.test.ts b/test/e2e/live/mcp-bridge.test.ts index bf8ca2ff9f7..4e8a7ef4d21 100644 --- a/test/e2e/live/mcp-bridge.test.ts +++ b/test/e2e/live/mcp-bridge.test.ts @@ -59,10 +59,7 @@ import { requireMcpBridgeTlsCaCert, } from "./mcp-bridge-onboard-env.ts"; import { MCP_BRIDGE_PHASES } from "./mcp-bridge-phases.ts"; -import { - addDistinctCredentialMcpEndpoint, - assertSharedHostMcpComposition, -} from "./mcp-bridge-shared-host.ts"; +import { assertSharedHostMcpComposition } from "./mcp-bridge-shared-host.ts"; import { DEEPAGENTS_MCP_DENIED_TOOL_PROBE, HERMES_MCP_ENV_LOAD_COMMANDS, @@ -627,22 +624,15 @@ async function replaceBridgeCredentialConservatively( host: HostCliClient, sandbox: SandboxClient, fakeMcp: Awaited>, - adapter: McpAdapter, - sandboxName: string, - mcpUrl: string, + options: { + agent: McpAgent; + artifactPrefix: string; + sandboxName: string; + mcpUrl: string; + }, ): Promise { - const artifactPrefix = - adapter === "openclaw-config" - ? "openclaw" - : adapter === "hermes-config" - ? "hermes" - : "deepagents"; - const agent: McpAgent = - adapter === "openclaw-config" - ? "openclaw" - : adapter === "hermes-config" - ? "hermes" - : "langchain-deepagents-code"; + const { agent, artifactPrefix, sandboxName, mcpUrl } = options; + const adapter = loadAgent(agent).mcpCapability.adapter!; const providerName = `${sandboxName}-mcp-${SERVER_NAME}`; const bridge = { sandboxName, mcpUrl, artifactPrefix }; const restart = await host.nemoclaw([sandboxName, "mcp", "restart", SERVER_NAME], { @@ -826,15 +816,30 @@ test( expect(aliasState.policyAbsent).toBe(true); expect(aliasState.adapterAbsent).toBe(true); // Exercise both native adapters with both credentials and policy entries present. - const { endpoint: distinctMcp, tunnel: distinctTunnel } = - await addDistinctCredentialMcpEndpoint({ - host, - sandbox, - cleanup, - progress, - sandboxName: OPENCLAW_SANDBOX_NAME, - serverOptions: { ...MCP_SERVER_OPTIONS, secret: ROTATED_HOST_SECRET }, - }); + const distinctMcp = await startFakeMcpHttpsServer({ + ...MCP_SERVER_OPTIONS, + secret: ROTATED_HOST_SECRET, + }); + cleanup.add("stop distinct MCP HTTPS server", () => distinctMcp.close()); + const distinctTunnel = await startPublicMcpHttpsTunnel({ + cleanup, + label: "distinct credential MCP HTTPS server", + progress, + server: distinctMcp, + }); + cleanup.add("remove distinct credential bridge", () => + cleanupMcpBridge(host, OPENCLAW_SANDBOX_NAME, "distinct", "openclaw-config"), + ); + await addBridgeAndReadStatus(host, sandbox, { + sandboxName: OPENCLAW_SANDBOX_NAME, + mcpUrl: distinctTunnel.url, + expectedAdapter: "openclaw-config", + serverName: "distinct", + credentialEnvName: "DISTINCT_MCP_SECRET", + credential: ROTATED_HOST_SECRET, + artifactPrefix: "openclaw-distinct", + applyHostPolicyEdit: false, + }); await assertRealAdapterToolCall(host, sandbox, fakeMcp, { ...bridge, resultToken: MCP_RESULT, @@ -1002,14 +1007,7 @@ test( expect(updateProof.lastCall).toMatchObject({ auth: `Bearer ${HOST_SECRET}`, }); - await replaceBridgeCredentialConservatively( - host, - sandbox, - fakeMcp, - "openclaw-config", - OPENCLAW_SANDBOX_NAME, - mcpUrl, - ); + await replaceBridgeCredentialConservatively(host, sandbox, fakeMcp, bridge); await assertRealAdapterToolCall(host, sandbox, fakeMcp, { ...bridge, resultToken: MCP_RESULT, @@ -1216,14 +1214,7 @@ mcpBridgeShardTest("hermes")( await restartBridgeWithoutHostSecret(host, HERMES_SANDBOX_NAME, "hermes"); await assertHermesToolCall("hermes-real-mcp-tool-call-after-rediscovery-restart"); await assertAuthenticatedMcpRediscovery(survivingMcp, survivingDiscoveryOffset); - await replaceBridgeCredentialConservatively( - host, - sandbox, - fakeMcp, - "hermes-config", - HERMES_SANDBOX_NAME, - mcpUrl, - ); + await replaceBridgeCredentialConservatively(host, sandbox, fakeMcp, bridge); await assertRealAdapterToolCall(host, sandbox, fakeMcp, { ...bridge, resultToken: MCP_RESULT, @@ -1419,14 +1410,7 @@ mcpBridgeShardTest("deepagents")( deniedTool: MCP_BRIDGE_DENIED_TOOL_NAME, }); await exactMainProof.assertSnapshotResidue("after-restart-tool-call"); - await replaceBridgeCredentialConservatively( - host, - sandbox, - fakeMcp, - "deepagents-config", - sandboxName, - mcpUrl, - ); + await replaceBridgeCredentialConservatively(host, sandbox, fakeMcp, bridge); await assertRealAdapterToolCall(host, sandbox, fakeMcp, { ...bridge, resultToken: MCP_RESULT,