diff --git a/ci/source-shape-test-budget.json b/ci/source-shape-test-budget.json index 08dbb6efa65..3dd45f3afe5 100644 --- a/ci/source-shape-test-budget.json +++ b/ci/source-shape-test-budget.json @@ -16,6 +16,16 @@ "test": "accepts only the tracked published Hermes base digest", "category": "security" }, + { + "file": "src/lib/onboard/managed-startup-profile.test.ts", + "test": "classifies every stock Docker ARG as startup-affordance or deliberate exclusion", + "category": "compatibility" + }, + { + "file": "src/lib/onboard/managed-startup-profile.test.ts", + "test": "classifies every centralized runtime input as profile intent or an explicit deferral", + "category": "compatibility" + }, { "file": "src/lib/readiness/host.test.ts", "test": "bounds and redacts successful probe text before schema validation", diff --git a/src/lib/onboard/managed-startup-profile.test.ts b/src/lib/onboard/managed-startup-profile.test.ts new file mode 100644 index 00000000000..256c77bb0b2 --- /dev/null +++ b/src/lib/onboard/managed-startup-profile.test.ts @@ -0,0 +1,1286 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { Buffer } from "node:buffer"; +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { + decodeManagedStartupProfile, + encodeManagedStartupProfile, + fingerprintManagedStartupProfile, + MANAGED_STARTUP_AGENTS, + MANAGED_STARTUP_PROFILE_AFFORDANCE_INVENTORY, + MANAGED_STARTUP_PROFILE_CAPABILITIES, + MANAGED_STARTUP_PROFILE_DEFERRED_RUNTIME_INPUTS, + MANAGED_STARTUP_PROFILE_EXCLUDED_DOCKER_INPUTS, + MANAGED_STARTUP_PROFILE_MAX_BYTES, + MANAGED_STARTUP_PROFILE_SCHEMA_VERSION, + MANAGED_STARTUP_RUNTIME_CLEANUP_OBLIGATIONS, + type ManagedStartupAgent, + type ManagedStartupProfile, + serializeManagedStartupProfile, + validateManagedStartupProfile, +} from "./managed-startup/profile"; + +const CA_SHA256 = "a".repeat(64); + +const MESSAGING_PLAN = { + schemaVersion: 1, + sandboxName: "demo", + agent: "portable", + workflow: "onboard", + channels: [], + disabledChannels: [], + credentialBindings: [ + { + credentialId: "slackBotToken", + providerEnvKey: "SLACK_BOT_TOKEN", + placeholder: "openshell:resolve:env:SLACK_BOT_TOKEN", + credentialAvailable: true, + }, + ], + networkPolicy: { presets: [], entries: [] }, + agentRender: [ + { + channelId: "discord", + agent: "openclaw", + target: "openclaw.json", + kind: "json-fragment", + path: "channels.discord", + value: { token: "openshell:resolve:env:DISCORD_BOT_TOKEN" }, + templateRefs: ["credential.discordBotToken.placeholder"], + }, + { + channelId: "slack", + agent: "openclaw", + target: "openclaw.json", + kind: "json-fragment", + path: "channels.slack", + value: { token: "xoxb-OPENSHELL-RESOLVE-ENV-SLACK_BOT_TOKEN" }, + templateRefs: ["credential.slackBotToken.placeholder"], + }, + ], + buildSteps: [], + stateUpdates: [], + healthChecks: [], +} as const; + +const OPENCLAW_PROFILE = { + schemaVersion: MANAGED_STARTUP_PROFILE_SCHEMA_VERSION, + agent: "openclaw", + agentConfig: { + agent: "openclaw", + webSearch: { enabled: true, provider: "brave" }, + otel: { + enabled: true, + endpointUrl: "http://host.openshell.internal:4318", + serviceName: "openclaw-gateway", + sampleRate: 0.75, + }, + agentTimeoutSeconds: 900, + heartbeatEvery: "30m", + extraAgents: { + agents: [ + { + id: "reviewer", + workspace: "/sandbox/reviewer", + model: "inference/nvidia/nemotron-3-ultra-550b-a55b", + }, + ], + defaults: { subagents: { maxSpawnDepth: 3 } }, + main: { tools: { profile: "coding" } }, + }, + deviceAuth: { disabled: true, optOutSource: "managed-onboard" }, + minimalBootstrap: true, + }, + inference: { + routeProvider: "inference", + upstreamProvider: "nvidia-prod", + model: "nvidia/nemotron-3-ultra-550b-a55b", + routedBaseUrl: "https://inference.local/v1", + upstreamEndpointUrl: null, + api: "openai-responses", + primaryModelRef: "inference/nvidia/nemotron-3-ultra-550b-a55b", + compatibility: { supportsDeveloperRole: true, maxRetries: 2 }, + inputModalities: ["text", "image"], + }, + proxy: { + managedHost: "10.200.0.1", + managedPort: 3128, + hostHttpUrl: "http://proxy.example.test:8080", + hostHttpsUrl: "http://connect-proxy.example.test:3128", + hostNoProxy: ["inference.local", "127.0.0.1", "localhost"], + }, + dashboard: { + agent: "openclaw", + mode: "remote", + url: "https://dashboard.example.test:18789", + port: 18_789, + bindAddress: "0.0.0.0", + wslExposure: true, + }, + tools: { + disclosure: "progressive", + enabledGateways: [], + }, + messaging: { plan: { ...MESSAGING_PLAN, agent: "openclaw" } }, + tuning: { + contextWindow: 131_072, + maxTokens: 8192, + reasoning: true, + reasoningEffort: "high", + }, + corporateCa: { bundleSha256: CA_SHA256 }, +} as const satisfies ManagedStartupProfile; + +const HERMES_PROFILE = { + schemaVersion: MANAGED_STARTUP_PROFILE_SCHEMA_VERSION, + agent: "hermes", + agentConfig: { + agent: "hermes", + webSearch: { enabled: true, provider: "tavily" }, + }, + inference: { + routeProvider: "custom", + upstreamProvider: "anthropic-prod", + model: "claude-sonnet-4-5", + routedBaseUrl: "https://inference.local/v1", + upstreamEndpointUrl: null, + api: "anthropic-messages", + primaryModelRef: null, + compatibility: null, + inputModalities: null, + }, + proxy: { + managedHost: "10.200.0.1", + managedPort: 3128, + hostHttpUrl: "http://proxy.example.test:8080", + hostHttpsUrl: "https://proxy.example.test:8443", + hostNoProxy: ["localhost", "127.0.0.1"], + }, + dashboard: { + agent: "hermes", + mode: "loopback-forwarded", + url: "http://127.0.0.1:19189", + publicPort: 19_189, + internalPort: 29_189, + tuiEnabled: true, + }, + tools: { + disclosure: "direct", + enabledGateways: ["nous-web", "nous-image", "nous-audio", "nous-browser", "nous-code"], + }, + messaging: { plan: { ...MESSAGING_PLAN, agent: "hermes" } }, + tuning: { + contextWindow: 65_536, + maxTokens: null, + reasoning: null, + reasoningEffort: null, + }, + corporateCa: { bundleSha256: CA_SHA256 }, +} as const satisfies ManagedStartupProfile; + +const DCODE_PROFILE = { + schemaVersion: MANAGED_STARTUP_PROFILE_SCHEMA_VERSION, + agent: "langchain-deepagents-code", + agentConfig: { + agent: "langchain-deepagents-code", + autoApprovalMode: "thread-opt-in", + observabilityEnabled: true, + }, + inference: { + routeProvider: "inference", + upstreamProvider: "openrouter", + model: "openai/gpt-5.4", + routedBaseUrl: "https://inference.local/v1", + upstreamEndpointUrl: "https://openrouter.ai/api/v1", + api: "openai-completions", + primaryModelRef: null, + compatibility: null, + inputModalities: null, + }, + proxy: { + managedHost: "10.200.0.1", + managedPort: 3128, + hostHttpUrl: null, + hostHttpsUrl: null, + hostNoProxy: [], + }, + dashboard: { + agent: "langchain-deepagents-code", + mode: "disabled", + }, + tools: { + disclosure: "progressive", + enabledGateways: [], + }, + messaging: { plan: null }, + tuning: { + contextWindow: null, + maxTokens: null, + reasoning: null, + reasoningEffort: null, + }, + corporateCa: { bundleSha256: CA_SHA256 }, +} as const satisfies ManagedStartupProfile; + +const VALID_PROFILES = [OPENCLAW_PROFILE, HERMES_PROFILE, DCODE_PROFILE] as const; + +function encodeUnknown(value: unknown): string { + return Buffer.from(JSON.stringify(value), "utf8").toString("base64url"); +} + +function dockerArgs(relativePath: string): Set { + const source = readFileSync(relativePath, "utf8"); + return new Set( + [...source.matchAll(/^ARG\s+([A-Z][A-Z0-9_]*)/gmu)].map((match) => match[1] as string), + ); +} + +const STOCK_DOCKER_ARGS = { + openclaw: dockerArgs(path.join(process.cwd(), "Dockerfile")), + hermes: dockerArgs(path.join(process.cwd(), "agents/hermes/Dockerfile")), + "langchain-deepagents-code": dockerArgs( + path.join(process.cwd(), "agents/langchain-deepagents-code/Dockerfile"), + ), +} satisfies Record>; + +const RUNTIME_INPUT_SOURCE_FILES = [ + "src/lib/onboard/sandbox-create-launch.ts", + "src/lib/onboard/openclaw-runtime-env.ts", + "src/lib/onboard/extra-placeholder-keys.ts", + "src/lib/onboard/host-proxy-env.ts", + "src/lib/onboard/hermes-dashboard.ts", + "src/lib/hermes-dashboard.ts", +] as const; +const QUOTED_RUNTIME_INPUT_RE = + /["']((?:(?:NEMOCLAW|OPENCLAW)_[A-Z0-9_]+)|CHAT_UI_URL|HTTP_PROXY|HTTPS_PROXY|NO_PROXY|http_proxy|https_proxy|no_proxy)["']/gu; +const STOCK_RUNTIME_INPUTS = new Set( + RUNTIME_INPUT_SOURCE_FILES.flatMap((relativePath) => [ + ...readFileSync(path.join(process.cwd(), relativePath), "utf8").matchAll( + QUOTED_RUNTIME_INPUT_RE, + ), + ]).map((match) => match[1] as string), +); +const OPENCLAW_AUTO_PAIR_CONSUMER_INPUTS = new Set( + readFileSync(path.join(process.cwd(), "scripts/nemoclaw-start.sh"), "utf8").match( + /\bNEMOCLAW_AUTO_PAIR_[A-Z0-9_]+\b/gu, + ) ?? [], +); +const STOCK_RUNTIME_INPUT_AGENTS = { + CHAT_UI_URL: ["openclaw", "hermes"], + HTTPS_PROXY: MANAGED_STARTUP_AGENTS, + HTTP_PROXY: MANAGED_STARTUP_AGENTS, + NEMOCLAW_AUTO_PAIR_DEADLINE_SECS: ["openclaw"], + NEMOCLAW_AUTO_PAIR_FAST_DEADLINE_SECS: ["openclaw"], + NEMOCLAW_AUTO_PAIR_RUN_TIMEOUT_SECS: ["openclaw"], + NEMOCLAW_AUTO_PAIR_SLOW_INTERVAL_SECS: ["openclaw"], + NEMOCLAW_DASHBOARD_BIND: ["openclaw"], + NEMOCLAW_DASHBOARD_PORT: ["openclaw", "hermes"], + NEMOCLAW_EXTRA_PLACEHOLDER_KEYS: MANAGED_STARTUP_AGENTS, + NEMOCLAW_HERMES_DASHBOARD: ["hermes"], + NEMOCLAW_HERMES_DASHBOARD_INTERNAL_PORT: ["hermes"], + NEMOCLAW_HERMES_DASHBOARD_PORT: ["hermes"], + NEMOCLAW_HERMES_DASHBOARD_TUI: ["hermes"], + NEMOCLAW_MINIMAL_BOOTSTRAP: ["openclaw"], + NEMOCLAW_OBSERVABILITY: ["langchain-deepagents-code"], + NEMOCLAW_PROXY_HOST: MANAGED_STARTUP_AGENTS, + NEMOCLAW_PROXY_PORT: MANAGED_STARTUP_AGENTS, + NEMOCLAW_SANDBOX_NAME: ["langchain-deepagents-code"], + NO_PROXY: MANAGED_STARTUP_AGENTS, + OPENCLAW_HOME: ["openclaw"], + OPENCLAW_STATE_DIR: ["openclaw"], + OPENCLAW_WORKSPACE_DIR: ["openclaw"], + http_proxy: MANAGED_STARTUP_AGENTS, + https_proxy: MANAGED_STARTUP_AGENTS, + no_proxy: MANAGED_STARTUP_AGENTS, +} as const satisfies Record; + +describe("managed startup profile", () => { + it.each( + VALID_PROFILES, + )("round-trips each $agent profile through canonical encoding", (profile) => { + const validated = validateManagedStartupProfile(profile); + const encoded = encodeManagedStartupProfile(profile); + + expect(decodeManagedStartupProfile(encoded)).toEqual(validated); + expect(encoded).not.toContain(profile.inference.model); + expect(fingerprintManagedStartupProfile(profile)).toMatch(/^[a-f0-9]{64}$/); + }); + + it("round-trips all OpenClaw-only startup settings", () => { + const profile = decodeManagedStartupProfile(encodeManagedStartupProfile(OPENCLAW_PROFILE)); + expect(profile).toMatchObject({ + agentConfig: { + webSearch: { enabled: true, provider: "brave" }, + otel: { + enabled: true, + endpointUrl: "http://host.openshell.internal:4318", + serviceName: "openclaw-gateway", + sampleRate: 0.75, + }, + agentTimeoutSeconds: 900, + heartbeatEvery: "30m", + minimalBootstrap: true, + deviceAuth: { disabled: true, optOutSource: "managed-onboard" }, + }, + inference: { + api: "openai-responses", + primaryModelRef: "inference/nvidia/nemotron-3-ultra-550b-a55b", + compatibility: { supportsDeveloperRole: true, maxRetries: 2 }, + inputModalities: ["image", "text"], + }, + dashboard: { + mode: "remote", + bindAddress: "0.0.0.0", + wslExposure: true, + }, + tuning: { + contextWindow: 131_072, + maxTokens: 8192, + reasoning: true, + reasoningEffort: "high", + }, + }); + expect(profile.agentConfig.agent === "openclaw" && profile.agentConfig.extraAgents).toEqual( + OPENCLAW_PROFILE.agentConfig.extraAgents, + ); + }); + + it("round-trips Hermes forwarding, declared gateways, messaging, and context tuning", () => { + const profile = decodeManagedStartupProfile(encodeManagedStartupProfile(HERMES_PROFILE)); + expect(profile).toMatchObject({ + dashboard: { + mode: "loopback-forwarded", + publicPort: 19_189, + internalPort: 29_189, + tuiEnabled: true, + }, + agentConfig: { webSearch: { enabled: true, provider: "tavily" } }, + tuning: { + contextWindow: 65_536, + maxTokens: null, + reasoning: null, + reasoningEffort: null, + }, + }); + expect(profile.tools.enabledGateways).toEqual([ + "nous-audio", + "nous-browser", + "nous-code", + "nous-image", + "nous-web", + ]); + expect(profile.messaging.plan).not.toBeNull(); + }); + + it("round-trips langchain-deepagents-code upstream metadata, managed proxy, approval, and observability", () => { + const profile = decodeManagedStartupProfile(encodeManagedStartupProfile(DCODE_PROFILE)); + expect(profile).toMatchObject({ + inference: { + routeProvider: "inference", + upstreamProvider: "openrouter", + upstreamEndpointUrl: "https://openrouter.ai/api/v1", + routedBaseUrl: "https://inference.local/v1", + api: "openai-completions", + }, + proxy: { + managedHost: "10.200.0.1", + managedPort: 3128, + hostHttpUrl: null, + hostHttpsUrl: null, + hostNoProxy: [], + }, + agentConfig: { + autoApprovalMode: "thread-opt-in", + observabilityEnabled: true, + }, + dashboard: { mode: "disabled" }, + }); + }); + + it("canonicalizes object keys and set-like lists before fingerprinting", () => { + const reordered = { + ...HERMES_PROFILE, + proxy: { + ...HERMES_PROFILE.proxy, + hostNoProxy: [...HERMES_PROFILE.proxy.hostNoProxy].reverse(), + }, + tools: { + ...HERMES_PROFILE.tools, + enabledGateways: [...HERMES_PROFILE.tools.enabledGateways].reverse(), + }, + }; + const serialized = serializeManagedStartupProfile(HERMES_PROFILE); + + expect(serializeManagedStartupProfile(reordered)).toBe(serialized); + expect(fingerprintManagedStartupProfile(reordered)).toBe( + createHash("sha256").update(serialized, "utf8").digest("hex"), + ); + }); + + it("exports complete, fail-closed capabilities for every supported agent", () => { + expect(Object.keys(MANAGED_STARTUP_PROFILE_CAPABILITIES).sort()).toEqual( + [...MANAGED_STARTUP_AGENTS].sort(), + ); + expect(MANAGED_STARTUP_PROFILE_CAPABILITIES.openclaw.dashboardModes).toEqual([ + "loopback", + "remote", + ]); + expect(MANAGED_STARTUP_PROFILE_CAPABILITIES.hermes.dashboardModes).toEqual([ + "disabled", + "loopback-forwarded", + ]); + expect(MANAGED_STARTUP_PROFILE_CAPABILITIES.hermes.inputModalities).toEqual([]); + expect(MANAGED_STARTUP_PROFILE_CAPABILITIES["langchain-deepagents-code"].inferenceApis).toEqual( + ["openai-completions"], + ); + expect( + MANAGED_STARTUP_PROFILE_CAPABILITIES["langchain-deepagents-code"].inputModalities, + ).toEqual([]); + }); + + it("keeps exported capabilities deeply frozen and validation authority private", () => { + const capabilities = MANAGED_STARTUP_PROFILE_CAPABILITIES["langchain-deepagents-code"]; + expect(Object.isFrozen(MANAGED_STARTUP_PROFILE_CAPABILITIES)).toBe(true); + expect(Object.isFrozen(capabilities)).toBe(true); + expect(Object.isFrozen(capabilities.inferenceApis)).toBe(true); + expect(() => + (capabilities.inferenceApis as unknown as string[]).push("openai-responses"), + ).toThrow(TypeError); + expect(() => + validateManagedStartupProfile({ + ...DCODE_PROFILE, + inference: { ...DCODE_PROFILE.inference, api: "openai-responses" }, + }), + ).toThrow(/not supported/); + }); + + // source-shape-contract: compatibility -- Every shipped Docker build input must map to versioned startup intent or a declared build-only exclusion + it("classifies every stock Docker ARG as startup-affordance or deliberate exclusion", () => { + for (const agent of MANAGED_STARTUP_AGENTS) { + const classified = new Set([ + ...MANAGED_STARTUP_PROFILE_AFFORDANCE_INVENTORY[agent].map(({ input }) => input), + ...MANAGED_STARTUP_PROFILE_EXCLUDED_DOCKER_INPUTS[agent].map(({ input }) => input), + ]); + expect([...STOCK_DOCKER_ARGS[agent]].filter((input) => !classified.has(input))).toEqual([]); + } + }); + + // source-shape-contract: compatibility -- Every centralized agent runtime input must map to versioned startup intent or a typed downstream owner + it("classifies every centralized runtime input as profile intent or an explicit deferral", () => { + expect([...STOCK_RUNTIME_INPUTS].sort()).toEqual( + Object.keys(STOCK_RUNTIME_INPUT_AGENTS).sort(), + ); + const missing = Object.entries(STOCK_RUNTIME_INPUT_AGENTS).flatMap(([input, agents]) => + agents + .filter( + (agent) => + !new Set([ + ...MANAGED_STARTUP_PROFILE_AFFORDANCE_INVENTORY[agent].map( + ({ input: profileInput }) => profileInput, + ), + ...MANAGED_STARTUP_PROFILE_DEFERRED_RUNTIME_INPUTS[agent].map( + ({ input: deferredInput }) => deferredInput, + ), + ]).has(input), + ) + .map((agent) => `${agent}:${input}`), + ); + expect(missing).toEqual([]); + + const openClawAutoPairInputs = MANAGED_STARTUP_PROFILE_DEFERRED_RUNTIME_INPUTS.openclaw.filter( + ({ input }) => input.startsWith("NEMOCLAW_AUTO_PAIR_"), + ); + expect([...OPENCLAW_AUTO_PAIR_CONSUMER_INPUTS].sort()).toEqual( + openClawAutoPairInputs.map(({ input }) => input).sort(), + ); + expect( + Object.fromEntries(openClawAutoPairInputs.map(({ admission, input }) => [input, admission])), + ).toEqual({ + NEMOCLAW_AUTO_PAIR_DEADLINE_SECS: "managed-launch-forwarded", + NEMOCLAW_AUTO_PAIR_FAST_DEADLINE_SECS: "managed-launch-forwarded", + NEMOCLAW_AUTO_PAIR_FAST_REENTRY_INTERVAL_SECS: "image-consumed-not-forwarded", + NEMOCLAW_AUTO_PAIR_FAST_REENTRY_POLLS: "image-consumed-not-forwarded", + NEMOCLAW_AUTO_PAIR_RUN_TIMEOUT_SECS: "managed-launch-forwarded", + NEMOCLAW_AUTO_PAIR_SLOW_INTERVAL_SECS: "managed-launch-forwarded", + }); + }); + + it("records generic cross-agent emissions as cleanup obligations, not supported semantics", () => { + expect(MANAGED_STARTUP_RUNTIME_CLEANUP_OBLIGATIONS).toHaveLength(2); + for (const obligation of MANAGED_STARTUP_RUNTIME_CLEANUP_OBLIGATIONS) { + const supportedAgents = + STOCK_RUNTIME_INPUT_AGENTS[obligation.input as keyof typeof STOCK_RUNTIME_INPUT_AGENTS]; + expect(obligation.owner).toBe("application-environment"); + for (const agent of obligation.emittedFor) { + expect(supportedAgents).not.toContain(agent); + expect( + MANAGED_STARTUP_PROFILE_AFFORDANCE_INVENTORY[agent].map(({ input }) => input), + ).not.toContain(obligation.input); + } + for (const agent of obligation.supportedFor) { + expect(supportedAgents).toContain(agent); + } + } + }); + + it.each( + MANAGED_STARTUP_AGENTS, + )("keeps deferred %s runtime inputs separate from typed profile intent", (agent) => { + const profileInputs = new Set( + MANAGED_STARTUP_PROFILE_AFFORDANCE_INVENTORY[agent].map(({ input }) => input), + ); + expect( + MANAGED_STARTUP_PROFILE_DEFERRED_RUNTIME_INPUTS[agent].filter(({ input }) => + profileInputs.has(input), + ), + ).toEqual([]); + }); + + it.each(MANAGED_STARTUP_AGENTS)("keeps the %s affordance inventory unambiguous", (agent) => { + const inventory = MANAGED_STARTUP_PROFILE_AFFORDANCE_INVENTORY[agent]; + expect(new Set(inventory.map(({ input }) => input)).size).toBe(inventory.length); + expect(inventory.every(({ profilePath }) => !profilePath.startsWith("env."))).toBe(true); + }); + + it("classifies the shared Hermes dashboard port as runtime startup intent", () => { + expect(MANAGED_STARTUP_PROFILE_AFFORDANCE_INVENTORY.hermes).toContainEqual({ + input: "NEMOCLAW_DASHBOARD_PORT", + profilePath: "dashboard.publicPort", + source: "runtime-env", + representation: "value", + }); + }); + + it.each( + VALID_PROFILES, + )("maps every $agent inventory entry to an explicit profile field", (profile) => { + for (const { profilePath } of MANAGED_STARTUP_PROFILE_AFFORDANCE_INVENTORY[profile.agent]) { + let current: unknown = profile; + for (const segment of profilePath.split(".")) { + expect(current).not.toBeNull(); + expect(typeof current).toBe("object"); + expect(Object.hasOwn(current as object, segment)).toBe(true); + current = (current as Record)[segment]; + } + } + }); + + it("rejects non-canonical transports instead of accepting ambiguous fingerprints", () => { + const raw = JSON.stringify(OPENCLAW_PROFILE); + expect(() => decodeManagedStartupProfile(Buffer.from(raw).toString("base64url"))).toThrow( + /canonical form/, + ); + }); + + it.each([ + { + label: "top level", + mutate: (profile: ManagedStartupProfile) => ({ ...profile, extension: true }), + }, + { + label: "inference", + mutate: (profile: ManagedStartupProfile) => ({ + ...profile, + inference: { ...profile.inference, extension: true }, + }), + }, + { + label: "proxy", + mutate: (profile: ManagedStartupProfile) => ({ + ...profile, + proxy: { ...profile.proxy, extension: true }, + }), + }, + { + label: "dashboard", + mutate: (profile: ManagedStartupProfile) => ({ + ...profile, + dashboard: { ...profile.dashboard, extension: true }, + }), + }, + { + label: "messaging wrapper", + mutate: (profile: ManagedStartupProfile) => ({ + ...profile, + messaging: { ...profile.messaging, extension: true }, + }), + }, + { + label: "agent config", + mutate: (profile: ManagedStartupProfile) => ({ + ...profile, + agentConfig: { ...profile.agentConfig, extension: true }, + }), + }, + { + label: "CA digest", + mutate: (profile: ManagedStartupProfile) => ({ + ...profile, + corporateCa: { ...profile.corporateCa, extension: true }, + }), + }, + ])("rejects recursively unknown keys at $label", ({ mutate }) => { + expect(() => validateManagedStartupProfile(mutate(OPENCLAW_PROFILE))).toThrow( + /unsupported fields/, + ); + }); + + it.each([ + ["agentConfig", { ...OPENCLAW_PROFILE, agentConfig: HERMES_PROFILE.agentConfig }], + ["dashboard", { ...OPENCLAW_PROFILE, dashboard: HERMES_PROFILE.dashboard }], + ])("rejects a mismatched %s agent discriminator", (_label, profile) => { + expect(() => validateManagedStartupProfile(profile)).toThrow(/must match agent/); + }); + + it.each([ + ["schema version", { ...OPENCLAW_PROFILE.messaging.plan, schemaVersion: 2 }], + ["agent", { ...OPENCLAW_PROFILE.messaging.plan, agent: "hermes" }], + ])("rejects a messaging plan with a mismatched %s", (_label, plan) => { + expect(() => + validateManagedStartupProfile({ + ...OPENCLAW_PROFILE, + messaging: { plan }, + }), + ).toThrow(/version 1 plan for the selected agent/); + }); + + it.each([ + ["credential-named compatibility field", { accessToken: "not-even-a-real-token" }], + ["token-shaped compatibility field name", { [`nvapi-${"a".repeat(32)}`]: true }], + ["credential-prefixed public key field", { secret_public_key: "opaque-secret" }], + ["provider-prefixed token field", { slackBotToken: "opaque-secret" }], + ["provider-prefixed API key field", { customApiKey: "opaque-secret" }], + ["camel-case secret public key field", { secretPublicKey: "opaque-secret" }], + ["generic provider token field", { githubToken: "opaque-secret" }], + ["generic provider key field", { openaiKey: "opaque-secret" }], + ["generic provider secret field", { matrixSecret: "opaque-secret" }], + ["generic provider PAT field", { githubPat: "opaque-secret" }], + [ + "credential-named field hidden under a non-messaging plan", + { plan: { accessToken: "not-even-a-real-token" } }, + ], + ["provider token", { note: `nvapi-${"a".repeat(32)}` }], + ["bearer value", { note: `Bearer ${"a".repeat(32)}` }], + [ + "private key", + { + note: `-----BEGIN ${"PRIVATE"} KEY-----\nabc\n-----END ${"PRIVATE"} KEY-----`, + }, + ], + ])("rejects %s anywhere in the profile", (_label, compatibility) => { + expect(() => + validateManagedStartupProfile({ + ...OPENCLAW_PROFILE, + inference: { ...OPENCLAW_PROFILE.inference, compatibility }, + }), + ).toThrow(/credential-shaped/); + }); + + it.each([ + "publicKey", + "public_key", + "public-key", + ])("does not classify exact %s metadata as credential material", (field) => { + expect( + validateManagedStartupProfile({ + ...OPENCLAW_PROFILE, + inference: { + ...OPENCLAW_PROFILE.inference, + compatibility: { [field]: "non-secret metadata" }, + }, + }).inference.compatibility, + ).toEqual({ [field]: "non-secret metadata" }); + }); + + it("rejects raw credentials nested inside an otherwise opaque messaging plan", () => { + expect(() => + validateManagedStartupProfile({ + ...OPENCLAW_PROFILE, + messaging: { + plan: { + ...OPENCLAW_PROFILE.messaging.plan, + credentialBindings: [ + { + providerEnvKey: "SLACK_BOT_TOKEN", + value: `xoxb-${"a".repeat(32)}`, + }, + ], + }, + }, + }), + ).toThrow(/credential-shaped string data/); + }); + + it("rejects credential fields in a messaging plan unless they contain provider placeholders", () => { + expect(() => + validateManagedStartupProfile({ + ...OPENCLAW_PROFILE, + messaging: { + plan: { + ...OPENCLAW_PROFILE.messaging.plan, + password: "hunter2", + }, + }, + }), + ).toThrow(/credential-shaped field name/); + }); + + it.each([ + ["routed inference", "inference", "routedBaseUrl"], + ["upstream inference", "inference", "upstreamEndpointUrl"], + ["OTEL", "otel", "endpointUrl"], + ["dashboard", "dashboard", "url"], + ] as const)("rejects credentials embedded in the %s URL", (_label, scope, field) => { + const profile = + scope === "inference" + ? { + ...DCODE_PROFILE, + inference: { + ...DCODE_PROFILE.inference, + [field]: "https://user:password@example.test/v1", + }, + } + : scope === "otel" + ? { + ...OPENCLAW_PROFILE, + agentConfig: { + ...OPENCLAW_PROFILE.agentConfig, + otel: { + ...OPENCLAW_PROFILE.agentConfig.otel, + [field]: "https://user:password@example.test/v1", + }, + }, + } + : { + ...OPENCLAW_PROFILE, + dashboard: { + ...OPENCLAW_PROFILE.dashboard, + [field]: "https://user:password@example.test/v1", + }, + }; + expect(() => validateManagedStartupProfile(profile)).toThrow( + /embedded credentials|credential-free/, + ); + }); + + it.each([ + "token", + "api_key", + ])("rejects credential-shaped query parameter %s in an opaque URL", (credentialField) => { + expect(() => + validateManagedStartupProfile({ + ...OPENCLAW_PROFILE, + inference: { + ...OPENCLAW_PROFILE.inference, + compatibility: { + note: `https://example.test/hook?${credentialField}=opaque-secret`, + }, + }, + }), + ).toThrow(/URL with embedded credentials/); + }); + + it.each([ + "#access_token=opaque-secret", + "#token=opaque-secret", + "#/route?api_key=opaque-secret", + ])("rejects credential-shaped parameters in an opaque URL fragment", (fragment) => { + expect(() => + validateManagedStartupProfile({ + ...OPENCLAW_PROFILE, + inference: { + ...OPENCLAW_PROFILE.inference, + compatibility: { + note: `https://example.test/callback${fragment}`, + }, + }, + }), + ).toThrow(/URL with embedded credentials/); + }); + + it("accepts an HTTP CONNECT origin for host HTTPS proxy intent", () => { + expect(validateManagedStartupProfile(OPENCLAW_PROFILE).proxy.hostHttpsUrl).toBe( + "http://connect-proxy.example.test:3128", + ); + }); + + it("keeps langchain-deepagents-code messaging, dashboards, and tuning fail-closed while retaining host proxy intent", () => { + expect(() => + validateManagedStartupProfile({ + ...DCODE_PROFILE, + messaging: { plan: { schemaVersion: 1 } }, + }), + ).toThrow(/messaging\.plan must be null/); + expect( + validateManagedStartupProfile({ + ...DCODE_PROFILE, + proxy: { ...DCODE_PROFILE.proxy, hostHttpUrl: "http://proxy.example.test:8080" }, + }).proxy.hostHttpUrl, + ).toBe("http://proxy.example.test:8080"); + expect(() => + validateManagedStartupProfile({ + ...DCODE_PROFILE, + tuning: { ...DCODE_PROFILE.tuning, contextWindow: 65_536 }, + }), + ).toThrow(/does not support startup tuning/); + expect(() => + validateManagedStartupProfile({ + ...DCODE_PROFILE, + dashboard: { agent: "langchain-deepagents-code", mode: "remote" }, + }), + ).toThrow(/dashboard\.mode must be disabled/); + }); + + it("rejects unsupported langchain-deepagents-code inference APIs and OpenClaw-only inference fields", () => { + expect(() => + validateManagedStartupProfile({ + ...DCODE_PROFILE, + inference: { ...DCODE_PROFILE.inference, api: "openai-responses" }, + }), + ).toThrow(/not supported/); + expect(() => + validateManagedStartupProfile({ + ...HERMES_PROFILE, + inference: { + ...HERMES_PROFILE.inference, + compatibility: { supportsDeveloperRole: true }, + }, + }), + ).toThrow(/does not support/); + }); + + it("rejects an OpenClaw primary model reference that disagrees with its provider and model", () => { + expect(() => + validateManagedStartupProfile({ + ...OPENCLAW_PROFILE, + inference: { + ...OPENCLAW_PROFILE.inference, + primaryModelRef: "different-provider/different-model", + }, + }), + ).toThrow(/primaryModelRef must match routeProvider and model/); + }); + + it("accepts only declared Hermes gateway IDs and rejects gateways for other agents", () => { + expect(validateManagedStartupProfile(HERMES_PROFILE).tools.enabledGateways).toHaveLength(5); + expect(() => + validateManagedStartupProfile({ + ...HERMES_PROFILE, + tools: { ...HERMES_PROFILE.tools, enabledGateways: ["filesystem"] }, + }), + ).toThrow(/unsupported value/); + expect(() => + validateManagedStartupProfile({ + ...OPENCLAW_PROFILE, + tools: { ...OPENCLAW_PROFILE.tools, enabledGateways: ["nous-web"] }, + }), + ).toThrow(/supported only by hermes/); + }); + + it("enforces adapter-specific web-search providers", () => { + expect(() => + validateManagedStartupProfile({ + ...HERMES_PROFILE, + agentConfig: { + ...HERMES_PROFILE.agentConfig, + webSearch: { enabled: true, provider: "brave" }, + }, + }), + ).toThrow(/not supported/); + }); + + it("enforces resolved OpenClaw dashboard exposure and device-auth semantics", () => { + expect(() => + validateManagedStartupProfile({ + ...OPENCLAW_PROFILE, + dashboard: { ...OPENCLAW_PROFILE.dashboard, mode: "loopback" }, + }), + ).toThrow(/must reflect/); + expect(() => + validateManagedStartupProfile({ + ...OPENCLAW_PROFILE, + agentConfig: { + ...OPENCLAW_PROFILE.agentConfig, + deviceAuth: { disabled: false, optOutSource: "operator" }, + }, + }), + ).toThrow(/requires device auth to be disabled/); + expect(() => + validateManagedStartupProfile({ + ...OPENCLAW_PROFILE, + dashboard: { ...OPENCLAW_PROFILE.dashboard, port: 18_790 }, + }), + ).toThrow(/must match dashboard\.url/); + }); + + it("supports disabled or loopback-forwarded Hermes dashboards only", () => { + const disabled = validateManagedStartupProfile({ + ...HERMES_PROFILE, + dashboard: { + agent: "hermes", + mode: "disabled", + url: "http://127.0.0.1:18789", + publicPort: null, + internalPort: null, + tuiEnabled: false, + }, + }); + expect(disabled.dashboard.mode).toBe("disabled"); + expect(() => + validateManagedStartupProfile({ + ...HERMES_PROFILE, + dashboard: { ...HERMES_PROFILE.dashboard, url: "https://dashboard.example.test" }, + }), + ).toThrow(/must remain loopback/); + expect(() => + validateManagedStartupProfile({ + ...HERMES_PROFILE, + dashboard: { ...HERMES_PROFILE.dashboard, publicPort: 19_190 }, + }), + ).toThrow(/must match dashboard\.url/); + }); + + it("rejects an explicit Hermes context window below the image contract minimum", () => { + expect(() => + validateManagedStartupProfile({ + ...HERMES_PROFILE, + tuning: { ...HERMES_PROFILE.tuning, contextWindow: 63_999 }, + }), + ).toThrow(/contextWindow must be at least 64000 tokens/); + }); + + it.each([ + ["publicPort", 8642], + ["publicPort", 18_642], + ["internalPort", 8642], + ["internalPort", 18_642], + ] as const)("rejects Hermes dashboard %s collisions with reserved API port %i", (field, port) => { + expect(() => + validateManagedStartupProfile({ + ...HERMES_PROFILE, + dashboard: { ...HERMES_PROFILE.dashboard, [field]: port }, + }), + ).toThrow(/reserved API ports 8642 or 18642/); + }); + + it.each([ + "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----", + Buffer.from( + `-----BEGIN CERTIFICATE-----\n${"A".repeat(300)}\n-----END CERTIFICATE-----`, + "utf8", + ).toString("base64"), + `MII${"A".repeat(300)}`, + `data:application/x-x509-ca-cert;base64,MII${"A".repeat(300)}`, + ])("rejects raw CA material while accepting only its digest", (rawCa) => { + expect(() => + validateManagedStartupProfile({ + ...OPENCLAW_PROFILE, + inference: { ...OPENCLAW_PROFILE.inference, model: rawCa }, + }), + ).toThrow(/raw certificate data/); + }); + + it.each([ + ["bad schema", { ...OPENCLAW_PROFILE, schemaVersion: 2 }], + [ + "invalid langchain-deepagents-code approval mode", + { + ...DCODE_PROFILE, + agentConfig: { + ...DCODE_PROFILE.agentConfig, + autoApprovalMode: "always", + }, + }, + ], + [ + "bad heartbeat", + { + ...OPENCLAW_PROFILE, + agentConfig: { ...OPENCLAW_PROFILE.agentConfig, heartbeatEvery: "every hour" }, + }, + ], + [ + "invalid CA digest", + { + ...OPENCLAW_PROFILE, + corporateCa: { bundleSha256: "not-a-digest" }, + }, + ], + ])("rejects malformed profile: %s", (_label, profile) => { + expect(() => validateManagedStartupProfile(profile)).toThrow(/Invalid managed startup profile/); + }); + + it.each([ + ["empty", ""], + ["not base64url", "%%%"], + ["invalid base64url quantum", "a"], + ["invalid JSON", Buffer.from("{", "utf8").toString("base64url")], + ["invalid UTF-8", Buffer.from([0xc3, 0x28]).toString("base64url")], + ])("rejects malformed encoded payload: %s", (_label, encoded) => { + expect(() => decodeManagedStartupProfile(encoded)).toThrow(/Invalid managed startup profile/); + }); + + it("rejects decoded payloads over the bounded profile size", () => { + const encoded = Buffer.alloc(MANAGED_STARTUP_PROFILE_MAX_BYTES + 1, 0x61).toString("base64url"); + expect(() => decodeManagedStartupProfile(encoded)).toThrow(/size limit/); + }); + + it("rejects structurally deep payloads within the byte cap", () => { + const deep = JSON.parse(`${'{"nested":'.repeat(40)}null${"}".repeat(40)}`) as Record< + string, + unknown + >; + expect(() => validateManagedStartupProfile(deep)).toThrow(/complexity limit/); + }); + + it("checks direct payload complexity before reading excess properties", () => { + const wide = Object.fromEntries( + Array.from({ length: 5000 }, (_, index) => [`field-${String(index)}`, null]), + ); + let excessPropertyRead = false; + Object.defineProperty(wide, "excess", { + enumerable: true, + get() { + excessPropertyRead = true; + throw new Error("excess property was read"); + }, + }); + + expect(() => validateManagedStartupProfile(wide)).toThrow(/complexity limit/); + expect(excessPropertyRead).toBe(false); + }); + + it("rejects a custom JSON serializer before invoking it", () => { + const inputModalities = [...OPENCLAW_PROFILE.inference.inputModalities]; + let serializerInvoked = false; + Object.defineProperty(inputModalities, "toJSON", { + value() { + serializerInvoked = true; + return ["text"]; + }, + }); + + expect(() => + validateManagedStartupProfile({ + ...OPENCLAW_PROFILE, + inference: { ...OPENCLAW_PROFILE.inference, inputModalities }, + }), + ).toThrow(/custom JSON serializer/); + expect(serializerInvoked).toBe(false); + }); + + it("rejects an inherited array serializer before invoking it", () => { + const enabledGateways: string[] = []; + let serializerInvoked = false; + const prototype = Object.create(Array.prototype) as Record; + Object.defineProperty(prototype, "toJSON", { + value() { + serializerInvoked = true; + return [`nvapi-${"a".repeat(32)}`]; + }, + }); + Object.setPrototypeOf(enabledGateways, prototype); + + expect(() => + validateManagedStartupProfile({ + ...DCODE_PROFILE, + tools: { ...DCODE_PROFILE.tools, enabledGateways }, + }), + ).toThrow(/standard JSON prototype/); + expect(serializerInvoked).toBe(false); + }); + + it("rejects an array map override before invoking it", () => { + const enabledGateways: string[] = []; + let mapInvoked = false; + Object.defineProperty(enabledGateways, "map", { + value() { + mapInvoked = true; + return [`nvapi-${"a".repeat(32)}`]; + }, + }); + + expect(() => + validateManagedStartupProfile({ + ...DCODE_PROFILE, + tools: { ...DCODE_PROFILE.tools, enabledGateways }, + }), + ).toThrow(/only indexed JSON values/); + expect(mapInvoked).toBe(false); + }); + + it("rejects a polluted Object prototype serializer before invoking it", () => { + let serializerInvoked = false; + let caught: unknown; + Object.defineProperty(Object.prototype, "toJSON", { + configurable: true, + value() { + serializerInvoked = true; + return { note: `nvapi-${"a".repeat(32)}` }; + }, + }); + try { + validateManagedStartupProfile(OPENCLAW_PROFILE); + } catch (error) { + caught = error; + } finally { + Reflect.deleteProperty(Object.prototype, "toJSON"); + } + + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).toMatch(/custom JSON serializer/); + expect(serializerInvoked).toBe(false); + }); + + it("does not invoke an inherited getter to supply a missing schema field", () => { + const corporateCa: Record = {}; + let getterInvoked = false; + Object.defineProperty(Object.prototype, "bundleSha256", { + configurable: true, + get() { + getterInvoked = true; + return null; + }, + }); + + let caught: unknown; + try { + validateManagedStartupProfile({ ...DCODE_PROFILE, corporateCa }); + } catch (error) { + caught = error; + } finally { + Reflect.deleteProperty(Object.prototype, "bundleSha256"); + } + + expect(caught).toBeInstanceOf(Error); + expect((caught as Error).message).toMatch(/bundleSha256/); + expect(getterInvoked).toBe(false); + }); + + it("requires own messaging discriminators without invoking inherited getters", () => { + let getterInvoked = false; + Object.defineProperties(Object.prototype, { + schemaVersion: { + configurable: true, + get() { + getterInvoked = true; + return 1; + }, + }, + agent: { + configurable: true, + get() { + getterInvoked = true; + return "openclaw"; + }, + }, + }); + + try { + expect(() => + validateManagedStartupProfile({ + ...OPENCLAW_PROFILE, + messaging: { plan: {} }, + }), + ).toThrow(/version 1 plan for the selected agent/); + } finally { + Reflect.deleteProperty(Object.prototype, "schemaVersion"); + Reflect.deleteProperty(Object.prototype, "agent"); + } + + expect(getterInvoked).toBe(false); + }); + + it("returns opaque JSON objects without inherited prototype data", () => { + const profile = validateManagedStartupProfile(OPENCLAW_PROFILE); + expect(Object.getPrototypeOf(profile.inference.compatibility as object)).toBeNull(); + expect(Object.getPrototypeOf(profile.messaging.plan as object)).toBeNull(); + expect( + Object.getPrototypeOf( + (profile.messaging.plan as Record>).networkPolicy, + ), + ).toBeNull(); + }); + + it("rejects non-enumerable unknown fields instead of silently stripping them", () => { + const inference = { ...OPENCLAW_PROFILE.inference }; + Object.defineProperty(inference, "hiddenExtension", { + value: "safe", + enumerable: false, + }); + + expect(() => + validateManagedStartupProfile({ + ...OPENCLAW_PROFILE, + inference, + }), + ).toThrow(/unsupported fields/); + }); + + it("does not invoke polluted Array prototype mapping or sorting methods", () => { + const mapDescriptor = Object.getOwnPropertyDescriptor(Array.prototype, "map"); + const sortDescriptor = Object.getOwnPropertyDescriptor(Array.prototype, "sort"); + let prototypeMethodInvoked = false; + let serialized: string | undefined; + const poison = { + configurable: true, + value() { + prototypeMethodInvoked = true; + return [`nvapi-${"a".repeat(32)}`]; + }, + writable: true, + }; + Object.defineProperty(Array.prototype, "map", poison); + Object.defineProperty(Array.prototype, "sort", poison); + try { + serialized = serializeManagedStartupProfile({ + ...OPENCLAW_PROFILE, + messaging: { + plan: { + ...OPENCLAW_PROFILE.messaging.plan, + payload: ["safe"], + }, + }, + }); + } finally { + Object.defineProperty(Array.prototype, "map", mapDescriptor as PropertyDescriptor); + Object.defineProperty(Array.prototype, "sort", sortDescriptor as PropertyDescriptor); + } + + expect(prototypeMethodInvoked).toBe(false); + expect(serialized).toContain('"payload":["safe"]'); + expect(serialized).not.toContain("nvapi-"); + }); + + it("screens non-enumerable profile fields before rebuilding them", () => { + const inference = { ...OPENCLAW_PROFILE.inference }; + Object.defineProperty(inference, "model", { + value: `nvapi-${"a".repeat(32)}`, + enumerable: false, + }); + + expect(() => + validateManagedStartupProfile({ + ...OPENCLAW_PROFILE, + inference, + }), + ).toThrow(/credential-shaped string data/); + }); + + it("rejects a noncanonical payload even when its profile values are otherwise valid", () => { + const encoded = encodeUnknown({ + ...HERMES_PROFILE, + tools: { + ...HERMES_PROFILE.tools, + enabledGateways: [...HERMES_PROFILE.tools.enabledGateways].reverse(), + }, + }); + expect(() => decodeManagedStartupProfile(encoded)).toThrow(/canonical form/); + }); +}); diff --git a/src/lib/onboard/managed-startup/profile.ts b/src/lib/onboard/managed-startup/profile.ts new file mode 100644 index 00000000000..bacf4be6f3a --- /dev/null +++ b/src/lib/onboard/managed-startup/profile.ts @@ -0,0 +1,1889 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { Buffer } from "node:buffer"; +import { createHash } from "node:crypto"; +import { TextDecoder } from "node:util"; + +/** + * Versioned, bounded schema for managed-image startup intent. + * Runtime-specific construction and activation stay outside this module. + */ +export const MANAGED_STARTUP_PROFILE_SCHEMA_VERSION = 1 as const; + +/** Profiles are configuration, not a general-purpose transport. */ +export const MANAGED_STARTUP_PROFILE_MAX_BYTES = 64 * 1024; + +/** Maximum canonical base64url size for a profile at the decoded byte cap. */ +export const MANAGED_STARTUP_PROFILE_MAX_ENCODED_BYTES = + Math.ceil(MANAGED_STARTUP_PROFILE_MAX_BYTES / 3) * 4; + +const MAX_IDENTIFIER_BYTES = 256; +const MAX_MODEL_BYTES = 1024; +const MAX_URL_BYTES = 2048; +const MAX_LIST_ITEMS = 128; +const MAX_JSON_NODES = 4096; +const MAX_JSON_DEPTH = 32; +const MAX_TUNING_INTEGER = 1_000_000_000; +const MIN_HERMES_CONTEXT_WINDOW = 64_000; +const SHA256_RE = /^[a-f0-9]{64}$/; +const CONTROL_CHARACTER_RE = /[\u0000-\u001f\u007f-\u009f]/u; +const BASE64URL_RE = /^[A-Za-z0-9_-]+$/; +const RAW_CA_PEM_RE = /-----BEGIN (?:TRUSTED )?CERTIFICATE-----/iu; +const RAW_CA_PEM_BASE64_RE = + /^LS0tLS1CRUdJTi(?:BDRVJUSUZJQ0FURS0tLS0t|BUlVTVEVEIENFUlRJRklDQVRFLS0tLS0)/u; +const RAW_CA_DER_BASE64_RE = /^MII[A-Za-z0-9+/=\r\n]{253,}$/u; +const RAW_CA_DATA_URI_RE = + /data:application\/(?:pkix-cert|x-x509-ca-cert);base64,MII[A-Za-z0-9+/=]{253,}/iu; +const URL_CANDIDATE_RE = /[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'<>]+/gu; +const UTF8_DECODER = new TextDecoder("utf-8", { fatal: true }); +const 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; +const CREDENTIAL_COMPOUND_NAME_PATTERN = + /^(?:access|refresh|client|bearer|auth|api|private|signing|session|bot|app|resolved)(?:token|key|secret|password)$/iu; +const 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; +const CREDENTIAL_CAMEL_BOUNDARY_PATTERN = /[a-z0-9](?:Token|Key|Secret|Password|Passphrase|Pat)$/u; +const CREDENTIAL_ENV_NAME_PATTERN = + /^(?:[A-Z0-9]+_)*(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD|PASS|PASSPHRASE|CREDENTIAL)S?$/u; +const CREDENTIAL_HEADER_NAME_PATTERN = + /^(?:authorization|proxy-authorization|cookie|set-cookie|.+-(?:key|token|secret|password|passphrase|credential|auth)s?)$/iu; +const PUBLIC_KEY_NAME_PATTERN = /^public[-_]?keys?$/iu; +const PASS_CREDENTIAL_NAME_PATTERN = /(?:^|[-_])pass(?:wd)?$/iu; +const NON_SECRET_KEY_METADATA_NAMES = new Set([ + "envKey", + "installCacheEnvKey", + "providerEnvKey", + "stateKey", +]); +const MESSAGING_CREDENTIAL_PLACEHOLDER_RE = + /^(?:openshell:resolve:env:|[A-Za-z0-9]+-OPENSHELL-RESOLVE-ENV-)(?:v[0-9]+_)?[A-Z][A-Z0-9_]*$/u; +const SECRET_VALUE_PATTERNS: readonly RegExp[] = [ + /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, +]; + +export const MANAGED_STARTUP_INFERENCE_APIS = [ + "openai-completions", + "openai-responses", + "anthropic-messages", +] as const; +export type ManagedStartupInferenceApi = (typeof MANAGED_STARTUP_INFERENCE_APIS)[number]; +export type ManagedStartupToolDisclosure = "progressive" | "direct"; +export const MANAGED_STARTUP_REASONING_EFFORTS = ["default", "low", "medium", "high"] as const; +export type ManagedStartupReasoningEffort = (typeof MANAGED_STARTUP_REASONING_EFFORTS)[number]; +export const MANAGED_STARTUP_DCODE_AUTO_APPROVAL_MODES = ["disabled", "thread-opt-in"] as const; +export type ManagedStartupDcodeAutoApprovalMode = + (typeof MANAGED_STARTUP_DCODE_AUTO_APPROVAL_MODES)[number]; +export const MANAGED_STARTUP_HERMES_TOOL_GATEWAYS = [ + "nous-web", + "nous-image", + "nous-audio", + "nous-browser", + "nous-code", +] as const; +export type ManagedStartupHermesToolGateway = (typeof MANAGED_STARTUP_HERMES_TOOL_GATEWAYS)[number]; +export type ManagedStartupInputModality = "text" | "image"; +export type ManagedStartupWebSearchProvider = "brave" | "tavily"; +export type ManagedStartupDeviceAuthOptOutSource = "operator" | "managed-onboard"; + +export const MANAGED_STARTUP_AGENTS = ["openclaw", "hermes", "langchain-deepagents-code"] as const; + +export type ManagedStartupAgent = (typeof MANAGED_STARTUP_AGENTS)[number]; + +export type ManagedStartupJsonScalar = string | number | boolean | null; +export type ManagedStartupJsonValue = + | ManagedStartupJsonScalar + | ManagedStartupJsonObject + | readonly ManagedStartupJsonValue[]; +export interface ManagedStartupJsonObject { + readonly [key: string]: ManagedStartupJsonValue; +} + +export interface ManagedStartupInference { + /** Stable route name installed in the sandbox-facing inference config. */ + readonly routeProvider: string; + /** User-selected provider upstream of the managed inference route. */ + readonly upstreamProvider: string; + readonly model: string; + /** Sandbox-facing managed inference route (normally inference.local). */ + readonly routedBaseUrl: string; + /** Direct upstream metadata for langchain-deepagents-code; never the sandbox route. */ + readonly upstreamEndpointUrl: string | null; + readonly api: ManagedStartupInferenceApi; + /** OpenClaw's provider/model reference. Other adapters require null. */ + readonly primaryModelRef: string | null; + /** OpenClaw provider compatibility options. Other adapters require null. */ + readonly compatibility: ManagedStartupJsonObject | null; + /** OpenClaw model inputs. Other adapters require null. */ + readonly inputModalities: readonly ManagedStartupInputModality[] | null; +} + +export interface ManagedStartupProxy { + /** Managed OpenShell policy-proxy route declared for every adapter. */ + readonly managedHost: string; + readonly managedPort: number; + /** + * Optional host-proxy intent is separate from the root-owned managed route. + * The langchain-deepagents-code contract preserves this intent for its create + * boundary only. + */ + readonly hostHttpUrl: string | null; + readonly hostHttpsUrl: string | null; + readonly hostNoProxy: readonly string[]; +} + +export interface ManagedStartupOpenClawDashboard { + readonly agent: "openclaw"; + readonly mode: "loopback" | "remote"; + readonly url: string; + readonly port: number; + readonly bindAddress: "127.0.0.1" | "0.0.0.0"; + readonly wslExposure: boolean; +} + +export interface ManagedStartupHermesDashboardDisabled { + readonly agent: "hermes"; + readonly mode: "disabled"; + /** CHAT_UI_URL remains a stock image input even when host forwarding is off. */ + readonly url: string; + readonly publicPort: null; + readonly internalPort: null; + readonly tuiEnabled: false; +} + +export interface ManagedStartupHermesDashboardForwarded { + readonly agent: "hermes"; + readonly mode: "loopback-forwarded"; + readonly url: string; + readonly publicPort: number; + readonly internalPort: number; + readonly tuiEnabled: boolean; +} + +export type ManagedStartupHermesDashboard = + | ManagedStartupHermesDashboardDisabled + | ManagedStartupHermesDashboardForwarded; + +export interface ManagedStartupDcodeDashboard { + readonly agent: "langchain-deepagents-code"; + readonly mode: "disabled"; +} + +export type ManagedStartupDashboard = + | ManagedStartupOpenClawDashboard + | ManagedStartupHermesDashboard + | ManagedStartupDcodeDashboard; + +export interface ManagedStartupWebSearch { + readonly enabled: boolean; + /** + * The selected provider is retained even when disabled because the stock + * Dockerfiles currently materialize both build inputs independently. + */ + readonly provider: ManagedStartupWebSearchProvider; +} + +export interface ManagedStartupTools { + readonly disclosure: ManagedStartupToolDisclosure; + /** Declared Hermes gateway preset IDs; required empty for other adapters. */ + readonly enabledGateways: readonly ManagedStartupHermesToolGateway[]; +} + +export interface ManagedStartupMessaging { + /** + * A host-prevalidated SandboxMessagingPlan. The existing messaging + * validator owns its nested schema. This boundary rechecks its version and + * agent discriminator, validates JSON shape and size, and rejects defined + * credential shapes. + */ + readonly plan: ManagedStartupJsonObject | null; +} + +export interface ManagedStartupTuning { + readonly contextWindow: number | null; + readonly maxTokens: number | null; + readonly reasoning: boolean | null; + readonly reasoningEffort: ManagedStartupReasoningEffort | null; +} + +/** + * Only the digest crosses the startup-profile boundary. The host-side CA + * applicator owns the actual certificate bytes and verifies this digest before + * making them available to the sandbox. + */ +export interface ManagedStartupCorporateCa { + readonly bundleSha256: string | null; +} + +export interface ManagedStartupExtraAgents { + /** + * Canonical form of NEMOCLAW_EXTRA_AGENTS_JSON. The existing OpenClaw + * validator owns the nested agent schema; this boundary preserves all + * prevalidated values without accepting the legacy array/object ambiguity. + */ + readonly agents: readonly ManagedStartupJsonObject[]; + readonly defaults: ManagedStartupJsonObject; + readonly main: ManagedStartupJsonObject; +} + +export interface ManagedStartupOpenClawOtel { + readonly enabled: boolean; + readonly endpointUrl: string; + readonly serviceName: string; + readonly sampleRate: number; +} + +export interface ManagedStartupDeviceAuth { + readonly disabled: boolean; + readonly optOutSource: ManagedStartupDeviceAuthOptOutSource; +} + +export interface ManagedStartupOpenClawConfig { + readonly agent: "openclaw"; + readonly webSearch: ManagedStartupWebSearch; + readonly otel: ManagedStartupOpenClawOtel; + readonly agentTimeoutSeconds: number; + readonly heartbeatEvery: string | null; + readonly extraAgents: ManagedStartupExtraAgents; + readonly deviceAuth: ManagedStartupDeviceAuth; + readonly minimalBootstrap: boolean; +} + +export interface ManagedStartupHermesConfig { + readonly agent: "hermes"; + readonly webSearch: ManagedStartupWebSearch; +} + +export interface ManagedStartupDcodeConfig { + readonly agent: "langchain-deepagents-code"; + readonly autoApprovalMode: ManagedStartupDcodeAutoApprovalMode; + readonly observabilityEnabled: boolean; +} + +export type ManagedStartupAgentConfig = + | ManagedStartupOpenClawConfig + | ManagedStartupHermesConfig + | ManagedStartupDcodeConfig; + +export interface ManagedStartupProfile { + readonly schemaVersion: typeof MANAGED_STARTUP_PROFILE_SCHEMA_VERSION; + readonly agent: ManagedStartupAgent; + readonly agentConfig: ManagedStartupAgentConfig; + readonly inference: ManagedStartupInference; + readonly proxy: ManagedStartupProxy; + readonly dashboard: ManagedStartupDashboard; + readonly tools: ManagedStartupTools; + readonly messaging: ManagedStartupMessaging; + readonly tuning: ManagedStartupTuning; + readonly corporateCa: ManagedStartupCorporateCa; +} + +export type ManagedStartupDashboardMode = "disabled" | "loopback" | "remote" | "loopback-forwarded"; + +export interface ManagedStartupAgentCapabilities { + readonly inferenceApis: readonly ManagedStartupInferenceApi[]; + readonly dashboardModes: readonly ManagedStartupDashboardMode[]; + readonly inputModalities: readonly ManagedStartupInputModality[]; + readonly webSearchProviders: readonly ManagedStartupWebSearchProvider[]; + readonly toolGateways: readonly ManagedStartupHermesToolGateway[]; + readonly tuningFields: readonly ( + | "contextWindow" + | "maxTokens" + | "reasoning" + | "reasoningEffort" + )[]; + readonly supportsMessaging: boolean; + readonly supportsInferenceCompatibility: boolean; + readonly supportsUpstreamEndpoint: boolean; + readonly supportsHostProxyIntent: boolean; + readonly supportsPrimaryModelRef: boolean; + readonly supportsAgentTimeout: boolean; + readonly supportsHeartbeat: boolean; + readonly supportsExtraAgents: boolean; + readonly supportsDeviceAuth: boolean; + readonly observability: "openclaw-otel" | "dcode-marker" | "none"; + readonly supportsMinimalBootstrap: boolean; +} + +/** + * Host-side negotiation must use this table before dispatch. A runtime that + * does not advertise the requested semantic capability is rejected instead of + * silently dropping a field. + */ +const VALIDATED_INFERENCE_APIS_BY_AGENT = Object.freeze({ + openclaw: Object.freeze([...MANAGED_STARTUP_INFERENCE_APIS]), + hermes: Object.freeze([...MANAGED_STARTUP_INFERENCE_APIS]), + "langchain-deepagents-code": Object.freeze(["openai-completions"] as const), +}) satisfies Readonly>; + +function freezeAgentCapabilities( + capabilities: ManagedStartupAgentCapabilities, +): Readonly { + 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]), + }); +} + +const PROFILE_CAPABILITIES = { + openclaw: { + inferenceApis: [...VALIDATED_INFERENCE_APIS_BY_AGENT.openclaw], + 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: true, + observability: "openclaw-otel", + supportsMinimalBootstrap: true, + }, + hermes: { + inferenceApis: [...VALIDATED_INFERENCE_APIS_BY_AGENT.hermes], + 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: [], + supportsMessaging: false, + supportsInferenceCompatibility: false, + supportsUpstreamEndpoint: true, + supportsHostProxyIntent: true, + supportsPrimaryModelRef: false, + supportsAgentTimeout: false, + supportsHeartbeat: false, + supportsExtraAgents: false, + supportsDeviceAuth: false, + observability: "dcode-marker", + supportsMinimalBootstrap: false, + }, +} satisfies Record; + +for (const agent of MANAGED_STARTUP_AGENTS) { + Object.defineProperty(PROFILE_CAPABILITIES, agent, { + configurable: false, + enumerable: true, + value: freezeAgentCapabilities(PROFILE_CAPABILITIES[agent]), + writable: false, + }); +} + +export const MANAGED_STARTUP_PROFILE_CAPABILITIES = Object.freeze(PROFILE_CAPABILITIES); + +export type ManagedStartupAffordanceSource = "docker-arg" | "runtime-env" | "host-material"; +export type ManagedStartupAffordanceRepresentation = "value" | "derived" | "digest-handoff"; + +export interface ManagedStartupAffordance { + readonly input: string; + readonly profilePath: string; + readonly source: ManagedStartupAffordanceSource; + readonly representation: ManagedStartupAffordanceRepresentation; +} + +function affordance( + input: string, + profilePath: string, + source: ManagedStartupAffordanceSource = "docker-arg", + representation: ManagedStartupAffordanceRepresentation = "value", +): ManagedStartupAffordance { + return { input, profilePath, source, representation }; +} + +const 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"), +] as const; + +/** + * Complete v1 mapping from Docker/start inputs to typed profile fields. + * Data form lets the Dockerfile drift test reject an unclassified input. + */ +export const 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_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_DISABLE_DEVICE_AUTH", "agentConfig.deviceAuth.disabled"), + affordance("NEMOCLAW_DEVICE_AUTH_OPT_OUT_SOURCE", "agentConfig.deviceAuth.optOutSource"), + 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_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.url"), + 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_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, + ], +} as const satisfies Record; + +export type ManagedStartupDeferredRuntimeOwner = + | "application-environment" + | "credential-plumbing" + | "engine-identity" + | "fixed-image-contract"; + +export type ManagedStartupDeferredRuntimeAdmission = + | "managed-launch-forwarded" + | "image-consumed-not-forwarded"; + +export interface ManagedStartupDeferredRuntimeInput { + readonly input: string; + readonly owner: ManagedStartupDeferredRuntimeOwner; + readonly admission: ManagedStartupDeferredRuntimeAdmission; + readonly reason: string; +} + +function deferredRuntimeInput( + input: string, + owner: ManagedStartupDeferredRuntimeOwner, + reason: string, + admission: ManagedStartupDeferredRuntimeAdmission = "managed-launch-forwarded", +): ManagedStartupDeferredRuntimeInput { + return Object.freeze({ input, owner, admission, reason }); +} + +/** + * Runtime inputs intentionally deferred from the secret-free v1 profile. + * Every other input emitted by the sandbox-create environment must resolve to + * an affordance above. These remain owned by the application-environment, + * credential-plumbing, engine-identity, or fixed-image-contract surfaces + * instead of becoming implicit runtime-specific profile fields. + */ +export const 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", + "the image consumes this documented scheduler control but managed launch must admit it in the application environment transaction", + "image-consumed-not-forwarded", + ), + deferredRuntimeInput( + "NEMOCLAW_AUTO_PAIR_FAST_REENTRY_POLLS", + "application-environment", + "the image consumes this documented scheduler control but managed launch must admit it in the application environment transaction", + "image-consumed-not-forwarded", + ), + 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( + "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", + ), + ]), +}) satisfies Readonly>; + +export interface ManagedStartupRuntimeCleanupObligation { + readonly input: string; + readonly emittedFor: readonly ManagedStartupAgent[]; + readonly supportedFor: readonly ManagedStartupAgent[]; + readonly owner: "application-environment"; + readonly reason: string; +} + +function runtimeCleanupObligation( + input: string, + emittedFor: readonly ManagedStartupAgent[], + supportedFor: readonly ManagedStartupAgent[], + reason: string, +): ManagedStartupRuntimeCleanupObligation { + return Object.freeze({ + input, + emittedFor: Object.freeze([...emittedFor]), + supportedFor: Object.freeze([...supportedFor]), + owner: "application-environment" as const, + reason, + }); +} + +/** + * Known generic launch emissions that are not supported cross-agent semantics. + * The application environment transaction must remove these leaks before + * buildless activation; listing them here prevents profile construction from + * accidentally blessing the current implementation detail. + */ +export const 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", + ), +]) satisfies readonly ManagedStartupRuntimeCleanupObligation[]; + +export interface ManagedStartupExcludedDockerInput { + readonly input: string; + readonly reason: + | "release-composition" + | "integrity-pin" + | "build-provenance" + | "platform-build" + | "fixed-image-contract"; +} + +/** + * Docker inputs intentionally outside a startup profile. None are resolved + * deployment behavior: they select/pin release artifacts, invalidate build + * caches, or perform a platform-specific image ownership rewrite. + */ +export const MANAGED_STARTUP_PROFILE_EXCLUDED_DOCKER_INPUTS = { + openclaw: [ + { input: "BASE_IMAGE", reason: "release-composition" }, + { input: "OPENCLAW_VERSION", reason: "release-composition" }, + { input: "OPENCLAW_2026_7_1_INTEGRITY", reason: "integrity-pin" }, + { input: "OPENCLAW_2026_7_1_TARBALL", reason: "release-composition" }, + { input: "OPENCLAW_DIAGNOSTICS_OTEL_2026_7_1_INTEGRITY", reason: "integrity-pin" }, + { input: "OPENCLAW_BRAVE_PLUGIN_2026_7_1_INTEGRITY", reason: "integrity-pin" }, + { input: "NEMOCLAW_E2E_FIXTURE_LEGACY_OPENCLAW", reason: "release-composition" }, + { input: "NEMOCLAW_MANAGED_IMAGE_CAPABILITY_UNION", reason: "release-composition" }, + { input: "OPENCLAW_2026_3_11_INTEGRITY", reason: "integrity-pin" }, + { input: "OPENCLAW_2026_3_11_TARBALL", reason: "release-composition" }, + { input: "OPENCLAW_2026_4_24_INTEGRITY", reason: "integrity-pin" }, + { input: "OPENCLAW_2026_4_24_TARBALL", reason: "release-composition" }, + { input: "CODEX_ACP_0_11_1_INTEGRITY", reason: "integrity-pin" }, + { input: "MCPORTER_VERSION", reason: "release-composition" }, + { input: "MCPORTER_0_7_3_INTEGRITY", reason: "integrity-pin" }, + { input: "MCPORTER_0_7_3_TARBALL", reason: "release-composition" }, + { input: "NEMOCLAW_BUILD_ID", reason: "build-provenance" }, + { input: "NEMOCLAW_DARWIN_VM_COMPAT", reason: "platform-build" }, + { input: "NEMOCLAW_MANAGED_IMAGE_RUNTIME_USER", reason: "fixed-image-contract" }, + ], + hermes: [ + { input: "BASE_IMAGE", reason: "release-composition" }, + { input: "SSL_CERT_FILE", reason: "fixed-image-contract" }, + { input: "NEMOCLAW_MANAGED_IMAGE_CAPABILITY_UNION", reason: "release-composition" }, + { input: "NEMOCLAW_HERMES_PROFILE_POLICY_PATCHER_SHA256", reason: "integrity-pin" }, + { input: "NEMOCLAW_HERMES_GATEWAY_RUNTIME_METADATA_PATCHER_SHA256", reason: "integrity-pin" }, + { input: "NEMOCLAW_HERMES_CRON_RUNTIME_PATCHER_SHA256", reason: "integrity-pin" }, + { input: "NEMOCLAW_HERMES_CRON_EXECUTIONS_SOURCE_SHA256", reason: "integrity-pin" }, + { input: "NEMOCLAW_HERMES_BACKUP_SOURCE_SHA256", reason: "integrity-pin" }, + { input: "NEMOCLAW_HERMES_DISCORD_RECOVERY_PATCHER_SHA256", reason: "integrity-pin" }, + { input: "NEMOCLAW_HERMES_LANGFUSE_PATCHER_SHA256", reason: "integrity-pin" }, + { input: "NEMOCLAW_HERMES_WRAPPER_SHA256", reason: "integrity-pin" }, + { input: "NEMOCLAW_HERMES_VALIDATOR_SHA256", reason: "integrity-pin" }, + { input: "NEMOCLAW_HERMES_TIRITH_FINALIZER_SHA256", reason: "integrity-pin" }, + { input: "NEMOCLAW_BUILD_ID", reason: "build-provenance" }, + { input: "NEMOCLAW_DARWIN_VM_COMPAT", reason: "platform-build" }, + { input: "NEMOCLAW_MANAGED_IMAGE_RUNTIME_USER", reason: "fixed-image-contract" }, + ], + "langchain-deepagents-code": [ + { input: "BASE_IMAGE", reason: "release-composition" }, + { input: "NEMOCLAW_MANAGED_IMAGE_CAPABILITY_UNION", reason: "release-composition" }, + { input: "NEMOCLAW_BUILD_ID", reason: "build-provenance" }, + { input: "NEMOCLAW_DARWIN_VM_COMPAT", reason: "platform-build" }, + { input: "NEMOCLAW_MANAGED_IMAGE_RUNTIME_USER", reason: "fixed-image-contract" }, + ], +} as const satisfies Record; + +export class ManagedStartupProfileError extends Error { + constructor(message: string) { + super(`Invalid managed startup profile: ${message}`); + this.name = "ManagedStartupProfileError"; + } +} + +const PROFILE_KEYS = new Set([ + "schemaVersion", + "agent", + "agentConfig", + "inference", + "proxy", + "dashboard", + "tools", + "messaging", + "tuning", + "corporateCa", +]); +const INFERENCE_KEYS = new Set([ + "routeProvider", + "upstreamProvider", + "model", + "routedBaseUrl", + "upstreamEndpointUrl", + "api", + "primaryModelRef", + "compatibility", + "inputModalities", +]); +const PROXY_KEYS = new Set([ + "managedHost", + "managedPort", + "hostHttpUrl", + "hostHttpsUrl", + "hostNoProxy", +]); +const OPENCLAW_DASHBOARD_KEYS = new Set([ + "agent", + "mode", + "url", + "port", + "bindAddress", + "wslExposure", +]); +const HERMES_DASHBOARD_KEYS = new Set([ + "agent", + "mode", + "url", + "publicPort", + "internalPort", + "tuiEnabled", +]); +const DCODE_DASHBOARD_KEYS = new Set(["agent", "mode"]); +const TOOLS_KEYS = new Set(["disclosure", "enabledGateways"]); +const MESSAGING_KEYS = new Set(["plan"]); +const TUNING_KEYS = new Set(["contextWindow", "maxTokens", "reasoning", "reasoningEffort"]); +const CORPORATE_CA_KEYS = new Set(["bundleSha256"]); +const OPENCLAW_CONFIG_KEYS = new Set([ + "agent", + "webSearch", + "otel", + "agentTimeoutSeconds", + "heartbeatEvery", + "extraAgents", + "deviceAuth", + "minimalBootstrap", +]); +const HERMES_CONFIG_KEYS = new Set(["agent", "webSearch"]); +const DCODE_CONFIG_KEYS = new Set(["agent", "autoApprovalMode", "observabilityEnabled"]); +const WEB_SEARCH_KEYS = new Set(["enabled", "provider"]); +const OTEL_KEYS = new Set(["enabled", "endpointUrl", "serviceName", "sampleRate"]); +const DEVICE_AUTH_KEYS = new Set(["disabled", "optOutSource"]); +const EXTRA_AGENTS_KEYS = new Set(["agents", "defaults", "main"]); +const MANAGED_STARTUP_AGENT_SET = new Set(MANAGED_STARTUP_AGENTS); +const DCODE_AUTO_APPROVAL_MODE_SET = new Set(MANAGED_STARTUP_DCODE_AUTO_APPROVAL_MODES); +const INFERENCE_API_SET = new Set(MANAGED_STARTUP_INFERENCE_APIS); +const REASONING_EFFORT_SET = new Set(MANAGED_STARTUP_REASONING_EFFORTS); +const HERMES_GATEWAY_SET = new Set(MANAGED_STARTUP_HERMES_TOOL_GATEWAYS); +const HERMES_RESERVED_API_PORTS = new Set([8642, 18_642]); + +function isPlainObject(value: unknown): value is Record { + 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: string): boolean { + 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: string): boolean { + for (let index = 0; index < SECRET_VALUE_PATTERNS.length; index += 1) { + const descriptor = Object.getOwnPropertyDescriptor(SECRET_VALUE_PATTERNS, String(index)); + if (descriptor && "value" in descriptor && descriptor.value.test(value)) return true; + } + return false; +} + +function isMessagingCredentialPlaceholder(path: readonly string[], value: unknown): boolean { + return ( + path.length >= 2 && + path[0] === "messaging" && + path[1] === "plan" && + typeof value === "string" && + MESSAGING_CREDENTIAL_PLACEHOLDER_RE.test(value) + ); +} + +function containsUrlWithCredentialMaterial(value: string): boolean { + const candidates = value.match(URL_CANDIDATE_RE) ?? []; + for (let index = 0; index < candidates.length; index += 1) { + const descriptor = Object.getOwnPropertyDescriptor(candidates, String(index)); + if (!descriptor || !("value" in descriptor)) continue; + try { + const url = new URL(descriptor.value); + let credentialQuery = false; + url.searchParams.forEach((_queryValue, key) => { + 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 { + // A field-level URL validator owns malformed strings where a URL is expected. + } + } + return false; +} + +function invalid(reason: string): never { + throw new ManagedStartupProfileError(reason); +} + +function mapArrayByIndex(values: readonly T[], mapper: (value: T, index: number) => U): U[] { + const mapped: U[] = []; + for (let index = 0; index < values.length; index += 1) { + const descriptor = Object.getOwnPropertyDescriptor(values, String(index)); + if (!descriptor || !("value" in descriptor)) { + invalid("payload arrays must contain only indexed JSON values"); + } + Object.defineProperty(mapped, String(index), { + configurable: true, + enumerable: true, + value: mapper(descriptor.value as T, index), + writable: true, + }); + } + return mapped; +} + +function sortStrings(values: string[]): string[] { + for (let index = 1; index < values.length; index += 1) { + const selected = values[index] as string; + let insertion = index; + while (insertion > 0 && (values[insertion - 1] as string) > 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: unknown, where: string): Record { + if (!isPlainObject(value)) invalid(`${where} must be an object`); + return value; +} + +function rejectUnknownKeys( + value: Record, + allowed: ReadonlySet, + where: string, +): void { + const keys = Object.keys(value); + for (let index = 0; index < keys.length; index += 1) { + if (!allowed.has(keys[index] as string)) { + invalid(`${where} contains unsupported fields`); + } + } +} + +function requireBoolean(value: unknown, where: string): boolean { + if (typeof value !== "boolean") invalid(`${where} must be a boolean`); + return value; +} + +function requireNullableBoolean(value: unknown, where: string): boolean | null { + if (value === null) return null; + return requireBoolean(value, where); +} + +function requireBoundedString( + value: unknown, + where: string, + maxBytes = MAX_IDENTIFIER_BYTES, +): string { + if ( + typeof value !== "string" || + value.length === 0 || + value !== value.trim() || + Buffer.byteLength(value, "utf8") > maxBytes || + CONTROL_CHARACTER_RE.test(value) + ) { + invalid(`${where} must be a bounded, non-empty string without control characters`); + } + return value; +} + +function requireStringEnum( + value: unknown, + allowed: ReadonlySet, + where: string, +): T { + const normalized = requireBoundedString(value, where); + if (!allowed.has(normalized)) invalid(`${where} is not supported`); + return normalized as T; +} + +function requireNullablePositiveInteger(value: unknown, where: string): number | null { + 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: unknown, + where: string, + maximum = MAX_TUNING_INTEGER, +): number { + if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1 || value > maximum) { + invalid(`${where} must be a bounded positive integer`); + } + return value; +} + +function requirePort(value: unknown, where: string, minimum = 1): number { + if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 65_535) { + invalid(`${where} must be a valid TCP port`); + } + if (value < minimum) invalid(`${where} must be at least ${String(minimum)}`); + return value; +} + +function requireStringList(value: unknown, where: string): readonly string[] { + if (!Array.isArray(value) || value.length > MAX_LIST_ITEMS) { + invalid(`${where} must be a bounded string list`); + } + const items = mapArrayByIndex(value, (item) => requireBoundedString(item, `${where} item`)); + const unique = new Set(); + for (let index = 0; index < items.length; index += 1) { + unique.add(items[index] as string); + } + if (unique.size !== items.length) invalid(`${where} must not contain duplicates`); + return sortStrings(items); +} + +function requireEnumList( + value: unknown, + allowed: ReadonlySet, + where: string, + options: { readonly allowEmpty: boolean }, +): readonly T[] { + const items = requireStringList(value, where); + if (!options.allowEmpty && items.length === 0) invalid(`${where} must not be empty`); + for (let index = 0; index < items.length; index += 1) { + const item = items[index] as string; + if (!allowed.has(item)) invalid(`${where} contains an unsupported value`); + } + return items as readonly T[]; +} + +function cloneJsonValue( + value: unknown, + where: string, + options: { readonly nullPrototypeObjects?: boolean } = {}, +): ManagedStartupJsonValue { + const clone = (current: unknown, depth: number): ManagedStartupJsonValue => { + 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: ManagedStartupJsonObject = options.nullPrototypeObjects + ? (Object.create(null) as ManagedStartupJsonObject) + : {}; + const keys = Object.getOwnPropertyNames(current); + for (let index = 0; index < keys.length; index += 1) { + const key = keys[index] as string; + if ( + key.length === 0 || + Buffer.byteLength(key, "utf8") > MAX_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: unknown, where: string): ManagedStartupJsonObject | null { + if (value === null) return null; + if (!isPlainObject(value)) invalid(`${where} must be null or a plain JSON object`); + return cloneJsonValue(value, where, { nullPrototypeObjects: true }) as ManagedStartupJsonObject; +} + +function requireJsonObject(value: unknown, where: string): ManagedStartupJsonObject { + const object = requireJsonObjectOrNull(value, where); + if (object === null) invalid(`${where} must be a plain JSON object`); + return object; +} + +function requireHttpUrl(value: unknown, where: string): string { + const raw = requireBoundedString(value, where, MAX_URL_BYTES); + let parsed: URL; + 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: unknown, + allowedSchemes: ReadonlySet, + where: string, +): string | null { + if (value === null) return null; + const raw = requireBoundedString(value, where, MAX_URL_BYTES); + let parsed: URL; + 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: unknown, where: string): string { + 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 isLoopbackUrl(value: string): boolean { + const hostname = new URL(value).hostname.toLowerCase(); + return ( + hostname === "localhost" || + hostname === "127.0.0.1" || + hostname === "::1" || + hostname === "[::1]" + ); +} + +function configuredDashboardPort(value: string): number { + const explicit = new URL(value).port; + return explicit === "" ? 18_789 : Number(explicit); +} + +function requireSampleRate(value: unknown, where: string): number { + 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: unknown): void { + const pending: Array<{ + value: unknown; + depth: number; + path: readonly string[]; + }> = [{ value: root, depth: 0, path: [] }]; + let discoveredNodes = 1; + let observedBytes = 0; + + const observeText = (value: string): void => { + observedBytes += Buffer.byteLength(value, "utf8"); + if (observedBytes > MANAGED_STARTUP_PROFILE_MAX_BYTES) { + invalid(`payload exceeds ${String(MANAGED_STARTUP_PROFILE_MAX_BYTES)} bytes`); + } + }; + const reserveNode = (depth: number): void => { + 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 ( + !isMessagingCredentialPlaceholder(current.path, current.value) && + valueLooksLikeSecret(current.value) + ) { + invalid("payload 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 contains raw certificate data; provide only the CA SHA-256 digest"); + } + if (containsUrlWithCredentialMaterial(current.value)) { + invalid("payload 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; index < current.value.length; index += 1) { + const depth = current.depth + 1; + reserveNode(depth); + const descriptor = Object.getOwnPropertyDescriptor(current.value, String(index)); + if (descriptor && !("value" in descriptor)) { + invalid("payload must contain only JSON data properties"); + } + pending.push({ + value: descriptor?.value, + depth, + path: current.path, + }); + } + continue; + } + if (current.value !== null && typeof current.value === "object") { + if (!isPlainObject(current.value)) invalid("payload must contain only plain JSON objects"); + if ("toJSON" in current.value) { + invalid("payload must not define a custom JSON serializer"); + } + const keys = Object.getOwnPropertyNames(current.value); + if ( + Object.getOwnPropertySymbols(current.value).length > 0 || + discoveredNodes + keys.length > MAX_JSON_NODES + ) { + invalid("payload structure exceeds the complexity limit"); + } + for (let index = 0; index < keys.length; index += 1) { + const key = keys[index] as string; + const depth = current.depth + 1; + reserveNode(depth); + observeText(key); + if ( + valueLooksLikeSecret(key) || + RAW_CA_PEM_RE.test(key) || + RAW_CA_PEM_BASE64_RE.test(key) || + RAW_CA_DER_BASE64_RE.test(key) || + RAW_CA_DATA_URI_RE.test(key) || + containsUrlWithCredentialMaterial(key) + ) { + invalid("payload contains credential-shaped data in a field name"); + } + const descriptor = Object.getOwnPropertyDescriptor(current.value, key); + if (!descriptor || !("value" in descriptor)) { + invalid("payload must contain only JSON data properties"); + } + const child = descriptor.value; + if (isCredentialShapedName(key) && !isMessagingCredentialPlaceholder(current.path, child)) { + invalid("payload contains a credential-shaped field name"); + } + pending.push({ + value: child, + depth, + path: [...current.path, key], + }); + } + continue; + } + if ( + current.value !== null && + typeof current.value !== "number" && + typeof current.value !== "boolean" + ) { + invalid("payload must contain only JSON values"); + } + } +} + +function assertPayloadWithinByteLimit(value: unknown): void { + let serialized: string | undefined; + try { + serialized = JSON.stringify(value); + } catch { + invalid("payload is not serializable JSON"); + } + if ( + serialized === undefined || + Buffer.byteLength(serialized, "utf8") > MANAGED_STARTUP_PROFILE_MAX_BYTES + ) { + invalid(`payload exceeds ${String(MANAGED_STARTUP_PROFILE_MAX_BYTES)} bytes`); + } +} + +function validateWebSearch(value: unknown, agent: "openclaw" | "hermes"): ManagedStartupWebSearch { + const webSearch = requireRecord(value, "agentConfig.webSearch"); + rejectUnknownKeys(webSearch, WEB_SEARCH_KEYS, "agentConfig.webSearch"); + const provider = requireStringEnum( + webSearch.provider, + new Set(agent === "openclaw" ? ["brave", "tavily"] : ["tavily"]), + "agentConfig.webSearch.provider", + ); + return { + enabled: requireBoolean(webSearch.enabled, "agentConfig.webSearch.enabled"), + provider, + }; +} + +function validateOpenClawOtel(value: unknown): ManagedStartupOpenClawOtel { + const otel = requireRecord(value, "agentConfig.otel"); + rejectUnknownKeys(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: unknown): ManagedStartupExtraAgents { + const extraAgents = requireRecord(value, "agentConfig.extraAgents"); + rejectUnknownKeys(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 validateDeviceAuth(value: unknown): ManagedStartupDeviceAuth { + const deviceAuth = requireRecord(value, "agentConfig.deviceAuth"); + rejectUnknownKeys(deviceAuth, DEVICE_AUTH_KEYS, "agentConfig.deviceAuth"); + return { + disabled: requireBoolean(deviceAuth.disabled, "agentConfig.deviceAuth.disabled"), + optOutSource: requireStringEnum( + deviceAuth.optOutSource, + new Set(["operator", "managed-onboard"]), + "agentConfig.deviceAuth.optOutSource", + ), + }; +} + +function validateAgentConfig( + value: unknown, + expectedAgent: ManagedStartupAgent, +): ManagedStartupAgentConfig { + 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") { + rejectUnknownKeys(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), + deviceAuth: validateDeviceAuth(config.deviceAuth), + minimalBootstrap: requireBoolean(config.minimalBootstrap, "agentConfig.minimalBootstrap"), + }; + } + if (agent === "hermes") { + rejectUnknownKeys(config, HERMES_CONFIG_KEYS, "agentConfig"); + return { agent, webSearch: validateWebSearch(config.webSearch, agent) }; + } + + rejectUnknownKeys(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: unknown, + expectedAgent: ManagedStartupAgent, +): ManagedStartupDashboard { + 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") { + rejectUnknownKeys(dashboard, OPENCLAW_DASHBOARD_KEYS, "dashboard"); + const mode = requireStringEnum<"loopback" | "remote">( + dashboard.mode, + new Set(["loopback", "remote"]), + "dashboard.mode", + ); + const url = requireHttpUrl(dashboard.url, "dashboard.url"); + const bindAddress = requireStringEnum<"127.0.0.1" | "0.0.0.0">( + dashboard.bindAddress, + new Set(["127.0.0.1", "0.0.0.0"]), + "dashboard.bindAddress", + ); + const wslExposure = requireBoolean(dashboard.wslExposure, "dashboard.wslExposure"); + const hasRemoteExposure = !isLoopbackUrl(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 (port === 8642) + invalid("OpenClaw dashboard.port must not use reserved Hermes API port 8642"); + if (configuredDashboardPort(url) !== port) { + invalid("OpenClaw dashboard.port must match dashboard.url"); + } + return { + agent, + mode, + url, + port, + bindAddress, + wslExposure, + }; + } + if (agent === "hermes") { + rejectUnknownKeys(dashboard, HERMES_DASHBOARD_KEYS, "dashboard"); + const mode = requireStringEnum<"disabled" | "loopback-forwarded">( + dashboard.mode, + new Set(["disabled", "loopback-forwarded"]), + "dashboard.mode", + ); + const url = requireHttpUrl(dashboard.url, "dashboard.url"); + if (!isLoopbackUrl(url)) { + invalid("Hermes dashboard.url must remain loopback; OpenShell owns the host forward"); + } + 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, + 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 (HERMES_RESERVED_API_PORTS.has(publicPort) || HERMES_RESERVED_API_PORTS.has(internalPort)) { + invalid("Hermes dashboard ports must not use reserved API ports 8642 or 18642"); + } + if (configuredDashboardPort(url) !== publicPort) { + invalid("Hermes dashboard.publicPort must match dashboard.url"); + } + return { + agent, + mode, + url, + publicPort, + internalPort, + tuiEnabled: requireBoolean(dashboard.tuiEnabled, "dashboard.tuiEnabled"), + }; + } + + rejectUnknownKeys(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: unknown, agent: ManagedStartupAgent): ManagedStartupInference { + const inference = requireRecord(value, "inference"); + rejectUnknownKeys(inference, INFERENCE_KEYS, "inference"); + const routeProvider = requireBoundedString(inference.routeProvider, "inference.routeProvider"); + const model = requireBoundedString(inference.model, "inference.model", MAX_MODEL_BYTES); + const api = requireStringEnum( + inference.api, + INFERENCE_API_SET, + "inference.api", + ); + const supportedInferenceApis = VALIDATED_INFERENCE_APIS_BY_AGENT[agent]; + let apiSupported = false; + for (let index = 0; index < supportedInferenceApis.length; index += 1) { + if (supportedInferenceApis[index] === api) apiSupported = true; + } + if (!apiSupported) { + invalid(`inference.api is not supported by ${agent}`); + } + const upstreamEndpointUrl = + inference.upstreamEndpointUrl === null + ? null + : requireHttpUrl(inference.upstreamEndpointUrl, "inference.upstreamEndpointUrl"); + const primaryModelRef = + inference.primaryModelRef === null + ? null + : requireBoundedString( + inference.primaryModelRef, + "inference.primaryModelRef", + MAX_MODEL_BYTES, + ); + const compatibility = requireJsonObjectOrNull(inference.compatibility, "inference.compatibility"); + const inputModalities = + inference.inputModalities === null + ? null + : requireEnumList( + inference.inputModalities, + new Set(["text", "image"]), + "inference.inputModalities", + { allowEmpty: false }, + ); + + if (agent === "openclaw") { + if (upstreamEndpointUrl !== null) { + invalid("inference.upstreamEndpointUrl must be null for openclaw"); + } + if (primaryModelRef === null || inputModalities === null) { + invalid("openclaw requires primaryModelRef and inputModalities"); + } + if (primaryModelRef !== `${routeProvider}/${model}`) { + 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 === "hermes" && upstreamEndpointUrl !== null) { + invalid("inference.upstreamEndpointUrl must be null for hermes"); + } + } + + return { + routeProvider, + upstreamProvider: requireBoundedString( + inference.upstreamProvider, + "inference.upstreamProvider", + ), + model, + routedBaseUrl: requireHttpUrl(inference.routedBaseUrl, "inference.routedBaseUrl"), + upstreamEndpointUrl, + api, + primaryModelRef, + compatibility, + inputModalities, + }; +} + +function validateProxy(value: unknown, agent: ManagedStartupAgent): ManagedStartupProxy { + const proxy = requireRecord(value, "proxy"); + rejectUnknownKeys(proxy, PROXY_KEYS, "proxy"); + const hostHttpUrl = requireProxyUrl(proxy.hostHttpUrl, new Set(["http:"]), "proxy.hostHttpUrl"); + // HTTPS_PROXY conventionally names an HTTP CONNECT proxy, so either scheme + // is valid while credentials and non-origin paths remain forbidden. + 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: unknown, agent: ManagedStartupAgent): ManagedStartupTools { + const tools = requireRecord(value, "tools"); + rejectUnknownKeys(tools, TOOLS_KEYS, "tools"); + const enabledGateways = requireEnumList( + tools.enabledGateways, + HERMES_GATEWAY_SET, + "tools.enabledGateways", + { allowEmpty: true }, + ); + if (agent !== "hermes" && enabledGateways.length > 0) { + invalid("tools.enabledGateways is supported only by hermes"); + } + return { + disclosure: requireStringEnum( + tools.disclosure, + new Set(["progressive", "direct"]), + "tools.disclosure", + ), + enabledGateways, + }; +} + +function validateTuning(value: unknown, agent: ManagedStartupAgent): ManagedStartupTuning { + const tuning = requireRecord(value, "tuning"); + rejectUnknownKeys(tuning, TUNING_KEYS, "tuning"); + const result: ManagedStartupTuning = { + 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", + ), + }; + if (agent === "openclaw") { + if ( + result.contextWindow === null || + result.maxTokens === null || + result.reasoning === null || + result.reasoningEffort === null + ) { + invalid("openclaw requires contextWindow, maxTokens, reasoning, and reasoningEffort tuning"); + } + } else if (agent === "hermes") { + if (result.contextWindow !== null && result.contextWindow < MIN_HERMES_CONTEXT_WINDOW) { + invalid(`hermes contextWindow must be at least ${String(MIN_HERMES_CONTEXT_WINDOW)} tokens`); + } + if (result.maxTokens !== null || result.reasoning !== null || result.reasoningEffort !== null) { + invalid("hermes supports only contextWindow tuning"); + } + } else if ( + result.contextWindow !== null || + result.maxTokens !== null || + result.reasoning !== null || + result.reasoningEffort !== null + ) { + invalid("langchain-deepagents-code does not support startup tuning fields"); + } + return result; +} + +/** + * Validate unknown input and return a canonical, deeply rebuilt profile. + * Unknown keys are rejected at every object boundary, and unordered set-like + * lists are sorted so all producers fingerprint the same resolved intent. + */ +export function validateManagedStartupProfile(value: unknown): ManagedStartupProfile { + assertPayloadStructureAndCredentialShapes(value); + const ownedValue = cloneJsonValue(value, "profile", { nullPrototypeObjects: true }); + assertPayloadWithinByteLimit(ownedValue); + const profile = requireRecord(ownedValue, "profile"); + rejectUnknownKeys(profile, PROFILE_KEYS, "profile"); + if (profile.schemaVersion !== MANAGED_STARTUP_PROFILE_SCHEMA_VERSION) { + invalid(`schemaVersion must be ${String(MANAGED_STARTUP_PROFILE_SCHEMA_VERSION)}`); + } + const agent = requireStringEnum( + profile.agent, + MANAGED_STARTUP_AGENT_SET, + "agent", + ); + + const messaging = requireRecord(profile.messaging, "messaging"); + rejectUnknownKeys(messaging, MESSAGING_KEYS, "messaging"); + const messagingPlan = requireJsonObjectOrNull(messaging.plan, "messaging.plan"); + if (agent === "langchain-deepagents-code" && messagingPlan !== null) { + invalid("messaging.plan must be null for langchain-deepagents-code"); + } + if ( + messagingPlan !== null && + (!Object.hasOwn(messagingPlan, "schemaVersion") || + !Object.hasOwn(messagingPlan, "agent") || + messagingPlan.schemaVersion !== 1 || + messagingPlan.agent !== agent) + ) { + invalid("messaging.plan must be a version 1 plan for the selected agent"); + } + + const corporateCa = requireRecord(profile.corporateCa, "corporateCa"); + rejectUnknownKeys(corporateCa, CORPORATE_CA_KEYS, "corporateCa"); + const bundleSha256 = corporateCa.bundleSha256; + if ( + bundleSha256 !== null && + (typeof bundleSha256 !== "string" || !SHA256_RE.test(bundleSha256)) + ) { + invalid("corporateCa.bundleSha256 must be null or a lowercase SHA-256 digest"); + } + + const agentConfig = validateAgentConfig(profile.agentConfig, agent); + const dashboard = validateDashboard(profile.dashboard, agent); + if ( + agentConfig.agent === "openclaw" && + dashboard.agent === "openclaw" && + dashboard.mode === "remote" && + !agentConfig.deviceAuth.disabled + ) { + invalid("remote OpenClaw dashboard exposure requires device auth to be disabled"); + } + + return { + schemaVersion: MANAGED_STARTUP_PROFILE_SCHEMA_VERSION, + agent, + agentConfig, + inference: validateInference(profile.inference, agent), + proxy: validateProxy(profile.proxy, agent), + dashboard, + tools: validateTools(profile.tools, agent), + messaging: { + plan: messagingPlan, + }, + tuning: validateTuning(profile.tuning, agent), + corporateCa: { bundleSha256 }, + }; +} + +function canonicalizeJson(value: unknown): unknown { + if (Array.isArray(value)) return mapArrayByIndex(value, (item) => canonicalizeJson(item)); + if (!isPlainObject(value)) return value; + const result: Record = {}; + const keys = sortStrings(Object.keys(value)); + for (let index = 0; index < keys.length; index += 1) { + const key = keys[index] as string; + Object.defineProperty(result, key, { + configurable: true, + enumerable: true, + value: canonicalizeJson(value[key]), + writable: true, + }); + } + return result; +} + +/** Canonical JSON used by both the transport and fingerprint. */ +export function serializeManagedStartupProfile(profile: ManagedStartupProfile): string { + const validated = validateManagedStartupProfile(profile); + const serialized = JSON.stringify(canonicalizeJson(validated)); + if (Buffer.byteLength(serialized, "utf8") > MANAGED_STARTUP_PROFILE_MAX_BYTES) { + invalid(`canonical payload exceeds ${String(MANAGED_STARTUP_PROFILE_MAX_BYTES)} bytes`); + } + return serialized; +} + +/** Encode canonical JSON as unpadded base64url for transport through argv or an environment variable. */ +export function encodeManagedStartupProfile(profile: ManagedStartupProfile): string { + return Buffer.from(serializeManagedStartupProfile(profile), "utf8").toString("base64url"); +} + +/** Decode only the canonical representation produced by encodeManagedStartupProfile. */ +export function decodeManagedStartupProfile(encoded: string): ManagedStartupProfile { + if ( + typeof encoded !== "string" || + encoded.length === 0 || + 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 = 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: string; + try { + raw = UTF8_DECODER.decode(bytes); + } catch { + invalid("payload is not valid UTF-8"); + } + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + invalid("payload is not valid JSON"); + } + const profile = validateManagedStartupProfile(parsed); + if (serializeManagedStartupProfile(profile) !== raw) { + invalid("payload is not in canonical form"); + } + return profile; +} + +/** SHA-256 over canonical decoded JSON, independent of object key insertion order. */ +export function fingerprintManagedStartupProfile(profile: ManagedStartupProfile): string { + return createHash("sha256").update(serializeManagedStartupProfile(profile), "utf8").digest("hex"); +} diff --git a/src/lib/onboard/managed-startup/transport.ts b/src/lib/onboard/managed-startup/transport.ts new file mode 100644 index 00000000000..41d489ac47e --- /dev/null +++ b/src/lib/onboard/managed-startup/transport.ts @@ -0,0 +1,6 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +/** Environment variable names for the startup profile and CA bundle transports. */ +export const MANAGED_STARTUP_PROFILE_ENV = "NEMOCLAW_STARTUP_PROFILE_B64"; +export const MANAGED_STARTUP_CA_ENV = "NEMOCLAW_CORPORATE_CA_B64"; diff --git a/test/helpers/vitest-watch-triggers.ts b/test/helpers/vitest-watch-triggers.ts index fae85644d77..86390a961a1 100644 --- a/test/helpers/vitest-watch-triggers.ts +++ b/test/helpers/vitest-watch-triggers.ts @@ -46,6 +46,10 @@ function runTests(...tests: string[]): () => string[] { } export const vitestWatchTriggerPatterns: VitestWatchTriggerPattern[] = [ + { + pattern: /(?:^|\/)(?:Dockerfile|agents\/(?:hermes|langchain-deepagents-code)\/Dockerfile)$/, + testsToRun: runTests("src/lib/onboard/managed-startup-profile.test.ts"), + }, { pattern: /(?:^|\/)agents\/hermes\/policy-additions\.yaml$/, testsToRun: runTests( diff --git a/test/vitest-watch-triggers.test.ts b/test/vitest-watch-triggers.test.ts index 5d9234cbb2c..599426fe744 100644 --- a/test/vitest-watch-triggers.test.ts +++ b/test/vitest-watch-triggers.test.ts @@ -48,6 +48,9 @@ const E2E_WORKFLOW_CONTRACTS = [ ] as const; const OPAQUE_INPUTS = [ + "Dockerfile", + "agents/hermes/Dockerfile", + "agents/langchain-deepagents-code/Dockerfile", "agents/hermes/policy-additions.yaml", "src/lib/messaging/channels/telegram/policy/openclaw.yaml", "nemoclaw-blueprint/policies/presets/local-inference.yaml", @@ -83,6 +86,13 @@ describe("Vitest opaque-input watch triggers", () => { }); it("maps current opaque inputs to their direct contract tests (#6692)", () => { + expect(triggeredBy("Dockerfile")).toEqual(["src/lib/onboard/managed-startup-profile.test.ts"]); + expect(triggeredBy("agents/hermes/Dockerfile")).toEqual([ + "src/lib/onboard/managed-startup-profile.test.ts", + ]); + expect(triggeredBy("agents/langchain-deepagents-code/Dockerfile")).toEqual([ + "src/lib/onboard/managed-startup-profile.test.ts", + ]); expect(triggeredBy("agents/hermes/policy-additions.yaml")).toEqual([ "src/lib/onboard/initial-policy-real-policy.test.ts", "src/lib/onboard/initial-policy.test.ts",