// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 import type { InitialSandboxPolicy } from "./initial-policy"; import { type CreateOpenShellSandboxRequest, withoutOpenShellSandboxCreateGpu, } from "../adapters/openshell/sandbox-lifecycle"; import { hasConfiguredMessagingCredential, type MessagingTokenDef } from "./messaging-prep"; import { hasNemoClawOwnedMessagingProviderProfile } from "../messaging/applier/provider-application"; import { filterMessagingProvidersForSandboxCreate } from "./sandbox-create-intent"; import type { MaterializeSandboxCreatePlanInput, SandboxCreateIntent, SandboxCreateMessagingProviderRequest, } from "./sandbox-create-intent-types"; import { containerPathsOverlap } from "./host-mount/path-overlap"; import { normalizeSandboxGpuDeviceForCdi } from "./sandbox-gpu-create"; import { prepareSandboxGpuRoutePolicies } from "./sandbox-gpu-route-policy"; type PrepareInitialSandboxCreatePolicy = typeof import("./initial-policy").prepareInitialSandboxCreatePolicy; export type PlannedOpenShellSandboxCreateRequest = Omit< CreateOpenShellSandboxRequest, "target" | "startupCommand" | "environment" | "workingDirectory" >; /** Bind runtime-only fields to the final typed ordinary create plan. */ export function finalizeOpenShellSandboxCreateRequest(input: { readonly plan: PlannedOpenShellSandboxCreateRequest; readonly gatewayName: string; readonly startupCommand: readonly string[]; readonly environment: NodeJS.ProcessEnv; readonly workingDirectory?: string; readonly compatibilityPolicyPath?: string | null; }): CreateOpenShellSandboxRequest { const request: CreateOpenShellSandboxRequest = Object.freeze({ ...input.plan, target: Object.freeze({ kind: "named" as const, gatewayName: input.gatewayName }), startupCommand: Object.freeze([...input.startupCommand]), environment: Object.freeze({ ...input.environment }), ...(input.workingDirectory ? { workingDirectory: input.workingDirectory } : {}), }); if (input.compatibilityPolicyPath === undefined) return request; if (!input.compatibilityPolicyPath) { throw new Error("Compatibility GPU route requires its route-specific sandbox policy."); } return withoutOpenShellSandboxCreateGpu(request, { policyPath: input.compatibilityPolicyPath, }); } function materializeCreateResources( args: readonly string[], ): CreateOpenShellSandboxRequest["resources"] { const resources: { cpu?: string; memory?: string } = {}; for (let index = 0; index < args.length; index += 2) { const option = args[index]; const value = args[index + 1]; if (!value || (option !== "--cpu" && option !== "--memory")) { throw new Error("Resource profile produced an unsupported sandbox create option."); } if (option === "--cpu") resources.cpu = value; else resources.memory = value; } return Object.keys(resources).length > 0 ? Object.freeze(resources) : undefined; } function materializeCreateGpu(args: readonly string[]): CreateOpenShellSandboxRequest["gpu"] { if (args.length === 0) return undefined; if (args.length === 1 && args[0] === "--gpu") return Object.freeze({}); throw new Error("GPU selection produced an unsupported sandbox create option."); } const DCODE_MCP_SNAPSHOT_TMPFS_MOUNT = { type: "tmpfs", target: "/run/nemoclaw-dcode-mcp", // Docker applies nosuid and nodev to tmpfs mounts by default and rejects // both when they are repeated in structured MountTmpfsOptions. options: ["noexec"], size_bytes: 1_048_576, mode: 0o1777, } as const; function buildSandboxDriverConfig( intent: SandboxCreateIntent, managedStateMounts: MaterializeSandboxCreatePlanInput["managedStateMounts"], managedStateMountDriverId: MaterializeSandboxCreatePlanInput["managedStateMountDriverId"], ): string | null { const cdiDevice = normalizeSandboxGpuDeviceForCdi(intent.sandboxGpuDevice); if (cdiDevice && (!intent.policy.options.directGpu || !intent.gpuCreateArgs.includes("--gpu"))) { throw new Error("Sandbox GPU device selection requires the OpenShell GPU request."); } const dockerMounts: Array> = (intent.hostMounts ?? []).map( ({ source, target }) => ({ type: "bind", source, target, read_only: true }), ); const podmanMounts: Array> = []; const mountsByDriver = new Map>>([ ["docker", dockerMounts], ["podman", podmanMounts], ]); if ((managedStateMounts?.length ?? 0) > 0) { if (!managedStateMountDriverId) { throw new Error("Managed state mounts are missing their provider-owned driver config."); } const providerMounts = mountsByDriver.get(managedStateMountDriverId) ?? []; for (const managedStateMount of managedStateMounts ?? []) { const conflictingHostMount = intent.hostMounts?.find(({ target }) => containerPathsOverlap(target, managedStateMount.target), ); if (conflictingHostMount) { throw new Error( `Host mount target '${conflictingHostMount.target}' conflicts with the managed state root '${managedStateMount.target}'.`, ); } if ( providerMounts.some( ({ target }) => typeof target === "string" && containerPathsOverlap(target, managedStateMount.target), ) ) { throw new Error(`Managed state root '${managedStateMount.target}' overlaps another root.`); } providerMounts.push({ ...managedStateMount }); } mountsByDriver.set(managedStateMountDriverId, providerMounts); } if (intent.policy.options.agentName === "langchain-deepagents-code") { dockerMounts.unshift(DCODE_MCP_SNAPSHOT_TMPFS_MOUNT); podmanMounts.push(DCODE_MCP_SNAPSHOT_TMPFS_MOUNT); } const driverConfig = Object.fromEntries( [...mountsByDriver].flatMap(([driverId, mounts]) => mounts.length > 0 || cdiDevice ? [ [ driverId, { ...(cdiDevice ? { cdi_devices: [cdiDevice] } : {}), ...(mounts.length > 0 ? { mounts } : {}), }, ], ] : [], ), ); return Object.keys(driverConfig).length > 0 ? JSON.stringify(driverConfig) : null; } export type SandboxCreatePlan = { activeMessagingChannels: string[]; initialSandboxPolicy: InitialSandboxPolicy; createRequest: PlannedOpenShellSandboxCreateRequest; messagingProviders: string[]; gpuRoutePlan: SandboxCreateIntent["gpuRoutePlan"]; compatibilityPolicyPath: string | null; sandboxGpuLogMessage: string | null; /** One-shot provider activation owned by the post-create verification boundary. */ activateDeferredProviderEffects: | ((revalidateSandboxIdentity: (operation: string) => void) => Promise) | null; }; function sameProviderNames(left: readonly string[], right: readonly string[]): boolean { return ( left.length === right.length && left.every((providerName, index) => providerName === right[index]) ); } export function selectHermesPortableExtraProviderPlan( hermesPortable: boolean, requested: readonly string[] | undefined, planOrdinary: () => { readonly extraProviders: readonly string[]; readonly staleExtraProviders: readonly string[]; }, ): { readonly extraProviders: readonly string[]; readonly staleExtraProviders: readonly string[] } { if (hermesPortable) { return { extraProviders: [...(requested ?? [])], staleExtraProviders: [] }; } return requested ? { extraProviders: [...requested], staleExtraProviders: [] } : planOrdinary(); } export async function selectHermesPortableMessagingCapabilities( hermesPortable: boolean, rebindOrdinary: () => Promise<{ readonly messagingTokenDefs: MessagingTokenDef[]; readonly hasMessagingTokens: boolean; }>, ): Promise<{ readonly messagingTokenDefs: MessagingTokenDef[]; readonly hasMessagingTokens: boolean; }> { return hermesPortable ? { messagingTokenDefs: [], hasMessagingTokens: false } : await rebindOrdinary(); } export function applyOrdinaryExtraProviderReconciliation( hermesPortable: boolean, reconcile: () => void, ): void { if (!hermesPortable) reconcile(); } function getInitialSandboxCreatePolicy( ...args: Parameters ): ReturnType { const { prepareInitialSandboxCreatePolicy } = require("./initial-policy") as typeof import("./initial-policy"); return prepareInitialSandboxCreatePolicy(...args); } function getHermesPortableInitialSandboxPolicy( ...args: Parameters ): ReturnType { const { planHermesPortableInitialSandboxPolicy } = require("./initial-policy") as typeof import("./initial-policy"); return planHermesPortableInitialSandboxPolicy(...args); } export function prepareSandboxCreatePolicy( intent: SandboxCreateIntent, prepareInitialSandboxCreatePolicy: PrepareInitialSandboxCreatePolicy = getInitialSandboxCreatePolicy, messagingConfig?: MaterializeSandboxCreatePlanInput["messagingConfig"], plannedMessagingProviders: readonly string[] = [], ): { readonly initialSandboxPolicy: InitialSandboxPolicy; readonly compatibilityPolicyPath: string | null; } { return prepareSandboxGpuRoutePolicies( intent.policy.basePolicyPath, [...intent.policy.activeMessagingChannels], { directGpu: intent.policy.options.directGpu, hostGpuAvailable: intent.policy.options.hostGpuAvailable, additionalPresets: intent.policy.options.hostLocalInferenceRouteOnly ? intent.policy.options.additionalPresets.filter((name) => name !== "local-inference") : [...intent.policy.options.additionalPresets], agentName: intent.policy.options.agentName, inferenceProvider: intent.inferenceProvider, ...(intent.nativeHostedProviderAttachment ? { nativeHostedProviderAttachment: intent.nativeHostedProviderAttachment } : {}), // Channel presets bind `{sandboxName}--bridge`; without the name, // composing them throws. sandboxName: intent.sandboxName, policyTier: intent.policy.options.policyTier, messagingConfig, plannedProviders: [ ...(intent.inferenceProvider ? [intent.inferenceProvider] : []), ...intent.extraProviders, ...plannedMessagingProviders, ], }, intent.gpuRoutePlan, prepareInitialSandboxCreatePolicy, ); } function messagingProviderRequestKey( request: Pick, ): string { // Tuple encoding stays collision-free even if either value contains a separator. return JSON.stringify([request.name, request.envKey]); } export function validateSandboxCreateIntentBindings( intent: SandboxCreateIntent, messagingTokenDefs: readonly MessagingTokenDef[], ): MessagingTokenDef[] { const disabledChannelNames = new Set(intent.disabledChannelNames); const activeChannelNames = new Set(intent.policy.activeMessagingChannels); const enabledRequests = intent.messagingProviderRequests.filter( ({ channel }) => !channel || (activeChannelNames.has(channel) && !disabledChannelNames.has(channel)), ); const intentRequestKeys = new Set( intent.messagingProviderRequests.map(messagingProviderRequestKey), ); const tokenDefsByRequest = new Map( messagingTokenDefs.map((tokenDef) => [messagingProviderRequestKey(tokenDef), tokenDef]), ); if (tokenDefsByRequest.size !== messagingTokenDefs.length) { throw new Error( "Cannot materialize sandbox create intent; duplicate credential bindings found.", ); } if ( messagingTokenDefs.some( (tokenDef) => !intentRequestKeys.has(messagingProviderRequestKey(tokenDef)), ) ) { throw new Error("Cannot materialize sandbox create intent; credential binding set changed."); } return enabledRequests.map((request) => { const tokenDef = tokenDefsByRequest.get(messagingProviderRequestKey(request)); if (!tokenDef) { throw new Error( `Cannot materialize sandbox create intent; missing credential binding '${request.envKey}' for provider '${request.name}'.`, ); } if (hasConfiguredMessagingCredential(tokenDef) !== request.credentialConfigured) { throw new Error( `Cannot materialize sandbox create intent; credential availability changed for provider '${request.name}'.`, ); } if (!request.providerType || !tokenDef.providerType) { throw new Error( `Cannot materialize sandbox create intent; provider '${request.name}' has no explicit owned profile type. Re-run channel setup with a supported profile.`, ); } if (tokenDef.providerType !== request.providerType) { throw new Error( `Cannot materialize sandbox create intent; provider type changed for '${request.name}'.`, ); } if ( !hasNemoClawOwnedMessagingProviderProfile( undefined, intent.policy.options.agentName, request.providerType, ) ) { throw new Error( `Cannot materialize sandbox create intent; provider '${request.name}' has no NemoClaw-owned profile for type '${request.providerType}'. Re-run channel setup with a supported profile.`, ); } return tokenDef; }); } function assertCredentialBindingProvidersAttached( policy: InitialSandboxPolicy, createProviders: ReadonlySet, ): void { for (const provider of policy.credentialBindingProviders ?? []) { if (createProviders.has(provider)) continue; policy.cleanup?.(); throw new Error( `Cannot create sandbox; create-time policy requires credential provider '${provider}', but the sandbox create plan does not attach it.`, ); } } function buildCreateProviderSet( intent: SandboxCreateIntent, messagingProviders: readonly string[], hermesToolGatewayProvider: string | null, ): Set { return new Set( [ intent.inferenceProvider, ...messagingProviders, hermesToolGatewayProvider, ...intent.extraProviders, ].filter((provider): provider is string => Boolean(provider)), ); } function assertDeferredProviderPlanSupported( intent: SandboxCreateIntent, messagingProviders: readonly string[], initialSandboxPolicy: InitialSandboxPolicy, ): void { const requiresProviderAttachment = Boolean(intent.inferenceProvider) || messagingProviders.length > 0 || intent.extraProviders.length > 0 || intent.hermesToolGateways.length > 0; if (!requiresProviderAttachment) return; initialSandboxPolicy.cleanup?.(); throw new Error( `Cannot create sandbox '${intent.sandboxName}' with deferred providers because OpenShell cannot bind provider attachment to a verified immutable sandbox identity. No sandbox was created; use an OpenShell release with identity-bound provider attachment before retrying.`, ); } /** Materialize policy, route metadata, resources, and providers from a secretless intent. */ export async function materializeSandboxCreatePlan({ intent, fromRef, managedStateMounts, managedStateMountDriverId, policylessCreate = false, deferSandboxEffectsUntilIdentityVerification = false, skipProviderEffects = false, messagingTokenDefs, messagingConfig, upsertMessagingProviders, getHermesToolGatewayProviderName, discloseInitialSandboxPolicy, prepareInitialSandboxCreatePolicy = getInitialSandboxCreatePolicy, }: MaterializeSandboxCreatePlanInput): Promise { const driverConfig = buildSandboxDriverConfig( intent, managedStateMounts, managedStateMountDriverId, ); const enabledMessagingTokenDefs = validateSandboxCreateIntentBindings(intent, messagingTokenDefs); const plannedMessagingProviders = filterMessagingProvidersForSandboxCreate( [ ...enabledMessagingTokenDefs.filter(hasConfiguredMessagingCredential).map(({ name }) => name), ...intent.reusableMessagingProviders, ], intent.messagingProviderRequests, intent.policy.activeMessagingChannels, intent.disabledChannelNames, ); const { initialSandboxPolicy, compatibilityPolicyPath } = prepareSandboxCreatePolicy( intent, prepareInitialSandboxCreatePolicy, messagingConfig, plannedMessagingProviders, ); const createProviders: string[] = []; let hermesToolGatewayProvider: string | null | undefined; const resolveHermesToolGatewayProvider = (): string | null => { if (hermesToolGatewayProvider !== undefined) return hermesToolGatewayProvider; hermesToolGatewayProvider = intent.hermesToolGateways.length > 0 ? getHermesToolGatewayProviderName(intent.sandboxName) : null; return hermesToolGatewayProvider; }; if (deferSandboxEffectsUntilIdentityVerification) { assertDeferredProviderPlanSupported(intent, plannedMessagingProviders, initialSandboxPolicy); } if (!policylessCreate) { assertCredentialBindingProvidersAttached( initialSandboxPolicy, buildCreateProviderSet(intent, plannedMessagingProviders, resolveHermesToolGatewayProvider()), ); try { discloseInitialSandboxPolicy?.(initialSandboxPolicy); } catch (error) { initialSandboxPolicy.cleanup?.(); throw error; } } const activateProviderEffects = async ( revalidateSandboxIdentity?: (operation: string) => void, ): Promise => { const activatedMessagingProviders = filterMessagingProvidersForSandboxCreate( [ ...(await upsertMessagingProviders(enabledMessagingTokenDefs, { replaceExisting: true, allowedSandboxes: [intent.sandboxName], ...(revalidateSandboxIdentity ? { revalidateSandboxIdentity } : {}), })), ...intent.reusableMessagingProviders, ], intent.messagingProviderRequests, intent.policy.activeMessagingChannels, intent.disabledChannelNames, ); const createProviders = buildCreateProviderSet( intent, activatedMessagingProviders, resolveHermesToolGatewayProvider(), ); if (!policylessCreate) { assertCredentialBindingProvidersAttached(initialSandboxPolicy, createProviders); } if (!sameProviderNames(activatedMessagingProviders, plannedMessagingProviders)) { throw new Error( `Provider activation for sandbox '${intent.sandboxName}' did not match its verified create plan.`, ); } return [...createProviders]; }; if (!deferSandboxEffectsUntilIdentityVerification && !skipProviderEffects) { try { createProviders.push(...(await activateProviderEffects())); } catch (error) { initialSandboxPolicy.cleanup?.(); throw error; } } const sharedPlan = { activeMessagingChannels: [...intent.policy.activeMessagingChannels], initialSandboxPolicy, messagingProviders: plannedMessagingProviders, gpuRoutePlan: intent.gpuRoutePlan, compatibilityPolicyPath, sandboxGpuLogMessage: intent.sandboxGpuLogMessage, activateDeferredProviderEffects: deferSandboxEffectsUntilIdentityVerification ? activateProviderEffects : null, }; const resources = materializeCreateResources(intent.resourceCreateArgs); const gpu = materializeCreateGpu(intent.gpuCreateArgs); return { ...sharedPlan, createRequest: Object.freeze({ sandboxName: intent.sandboxName, source: Object.freeze({ reference: fromRef }), ...(!policylessCreate ? { policyPath: initialSandboxPolicy.policyPath } : {}), ...(driverConfig ? { driverConfigJson: driverConfig } : {}), ...(gpu ? { gpu } : {}), ...(resources ? { resources } : {}), ...(createProviders.length > 0 ? { providers: Object.freeze(createProviders) } : {}), }), }; } /** Build the schema-5 create plan without provider, filesystem, Docker, or prebuild effects. */ export function materializeHermesPortableCreatePlan(input: { readonly intent: SandboxCreateIntent; readonly fromRef: string; }): SandboxCreatePlan { const { intent, fromRef } = input; if ( intent.policy.options.agentName !== "hermes" || !["none", "native-only"].includes(intent.gpuRoutePlan) || (intent.hostMounts?.length ?? 0) > 0 || intent.policy.activeMessagingChannels.length > 0 || intent.messagingProviderRequests.length > 0 || intent.reusableMessagingProviders.length > 0 || intent.extraProviders.length > 0 || intent.staleExtraProviders.length > 0 || intent.hermesToolGateways.length > 0 ) { throw new Error( "Hermes portable create intent includes an effect that is not owned by its schema-5 receipt.", ); } const initialSandboxPolicy = getHermesPortableInitialSandboxPolicy( intent.policy.basePolicyPath, [...intent.policy.activeMessagingChannels], { directGpu: intent.policy.options.directGpu, hostGpuAvailable: intent.policy.options.hostGpuAvailable, additionalPresets: intent.policy.options.hostLocalInferenceRouteOnly ? intent.policy.options.additionalPresets.filter((name) => name !== "local-inference") : [...intent.policy.options.additionalPresets], agentName: "hermes", policyTier: intent.policy.options.policyTier, }, ); const driverConfig = buildSandboxDriverConfig(intent, undefined, null); const resources = materializeCreateResources(intent.resourceCreateArgs); const gpu = materializeCreateGpu(intent.gpuCreateArgs); return { activeMessagingChannels: [], initialSandboxPolicy, createRequest: Object.freeze({ sandboxName: intent.sandboxName, source: Object.freeze({ reference: fromRef }), policyPath: initialSandboxPolicy.policyPath, ...(driverConfig ? { driverConfigJson: driverConfig } : {}), ...(gpu ? { gpu } : {}), ...(resources ? { resources } : {}), ...(intent.inferenceProvider ? { providers: Object.freeze([intent.inferenceProvider]) } : {}), }), messagingProviders: [], gpuRoutePlan: intent.gpuRoutePlan, compatibilityPolicyPath: null, sandboxGpuLogMessage: intent.sandboxGpuLogMessage, activateDeferredProviderEffects: null, }; }