--- a/net/minecraft/commands/Commands.java
+++ b/net/minecraft/commands/Commands.java
@@ -170,12 +_,18 @@
 
         @Override
         public boolean isRestricted(CommandNode<CommandSourceStack> node) {
+            if (node.getRequirement() instanceof PermissionSource.RestrictedMarker) return true; // Paper - restricted api
             return node.getRequirement() instanceof PermissionCheck<?> permissionCheck && permissionCheck.requiredLevel() > 0;
         }
     };
     private final CommandDispatcher<CommandSourceStack> dispatcher = new CommandDispatcher<>();
 
     public Commands(Commands.CommandSelection selection, CommandBuildContext context) {
+    // Paper start - Brigadier API - modern minecraft overloads that do not use redirects but are copies instead
+        this(selection, context, false);
+    }
+    public Commands(Commands.CommandSelection selection, CommandBuildContext context, final boolean modern) {
+    // Paper end - Brigadier API - modern minecraft overloads that do not use redirects but are copies instead
         AdvancementCommands.register(this.dispatcher);
         AttributeCommand.register(this.dispatcher, context);
         ExecuteCommand.register(this.dispatcher, context);
@@ -280,6 +_,42 @@
             PublishCommand.register(this.dispatcher);
         }
 
+        // Paper start - Vanilla command permission fixes
+        for (final CommandNode<CommandSourceStack> node : this.dispatcher.getRoot().getChildren()) {
+            if (node.getRequirement() == com.mojang.brigadier.builder.ArgumentBuilder.<CommandSourceStack>defaultRequirement()) {
+                node.requirement = stack -> stack.source == CommandSource.NULL || stack.getBukkitSender().hasPermission(org.bukkit.craftbukkit.command.VanillaCommandWrapper.getPermission(node));
+            } else if (node.getRequirement() instanceof net.minecraft.commands.PermissionSource.Check<CommandSourceStack> check) {
+                check.vanillaNode().set(node);
+            }
+        }
+        // Paper end - Vanilla command permission fixes
+        // Paper start - Brigadier Command API
+        // Create legacy minecraft namespace commands
+        for (final CommandNode<CommandSourceStack> node : new java.util.ArrayList<>(this.dispatcher.getRoot().getChildren())) {
+            if (modern) {
+                // Modern behaviour that simply creates a full copy of the commands node.
+                // Avoids plenty of issues around registering redirects *to* these nodes from the API
+                this.dispatcher.getRoot().addChild(
+                    io.papermc.paper.command.brigadier.PaperBrigadier.copyLiteral(
+                        "minecraft:" + node.getName(),
+                        (com.mojang.brigadier.tree.LiteralCommandNode<CommandSourceStack>) node
+                    )
+                );
+                continue;
+            }
+
+            // Legacy behaviour of creating a flattened redirecting node.
+            // Used by CommandArgumentUpgrader
+            CommandNode<CommandSourceStack> flattenedAliasTarget = node;
+            while (flattenedAliasTarget.getRedirect() != null) flattenedAliasTarget = flattenedAliasTarget.getRedirect();
+
+            this.dispatcher.register(
+                com.mojang.brigadier.builder.LiteralArgumentBuilder.<CommandSourceStack>literal("minecraft:" + node.getName())
+                    .executes(flattenedAliasTarget.getCommand())
+                    .requires(flattenedAliasTarget.getRequirement())
+                    .redirect(flattenedAliasTarget));
+        }
+        // Paper end - Brigadier Command API
         this.dispatcher.setConsumer(ExecutionCommandSource.resultConsumer());
     }
 
@@ -299,6 +_,13 @@
     }
 
     public void performCommand(ParseResults<CommandSourceStack> parseResults, String command) {
+        // Paper start
+        this.performCommand(parseResults, command, false);
+    }
+
+    public void performCommand(ParseResults<CommandSourceStack> parseResults, String command, boolean throwCommandError) {
+        org.spigotmc.AsyncCatcher.catchOp("Cannot perform command async");
+        // Paper end
         CommandSourceStack commandSourceStack = parseResults.getContext().getSource();
         Profiler.get().push(() -> "/" + command);
         ContextChain<CommandSourceStack> contextChain = finishParsing(parseResults, command, commandSourceStack);
@@ -312,10 +_,13 @@
                     )
                 );
             }
-        } catch (Exception var12) {
+            // Paper start
+        } catch (Throwable var12) { // always gracefully handle it, no matter how bad:tm:
+            if (throwCommandError) throw var12; // rethrow directly if requested
+            // Paper end
             MutableComponent mutableComponent = Component.literal(var12.getMessage() == null ? var12.getClass().getName() : var12.getMessage());
-            if (LOGGER.isDebugEnabled()) {
-                LOGGER.error("Command exception: /{}", command, var12);
+            LOGGER.error("Command exception: /{}", command, var12); // Paper - always show execution exception in console log
+            if (commandSourceStack.getServer().isDebugging() || LOGGER.isDebugEnabled()) { // Paper - Debugging
                 StackTraceElement[] stackTrace = var12.getStackTrace();
 
                 for (int i = 0; i < Math.min(stackTrace.length, 3); i++) {
@@ -341,13 +_,17 @@
     }
 
     @Nullable
-    private static ContextChain<CommandSourceStack> finishParsing(ParseResults<CommandSourceStack> parseResults, String command, CommandSourceStack source) {
+    private ContextChain<CommandSourceStack> finishParsing(ParseResults<CommandSourceStack> parseResults, String command, CommandSourceStack source) {
         try {
             validateParseResults(parseResults);
             return ContextChain.tryFlatten(parseResults.getContext().build(command))
                 .orElseThrow(() -> CommandSyntaxException.BUILT_IN_EXCEPTIONS.dispatcherUnknownCommand().createWithContext(parseResults.getReader()));
         } catch (CommandSyntaxException var7) {
-            source.sendFailure(ComponentUtils.fromMessage(var7.getRawMessage()));
+            // Paper start - Add UnknownCommandEvent
+            final net.kyori.adventure.text.TextComponent.Builder builder = net.kyori.adventure.text.Component.text();
+            // source.sendFailure(ComponentUtils.fromMessage(var7.getRawMessage()));
+            builder.color(net.kyori.adventure.text.format.NamedTextColor.RED).append(io.papermc.paper.command.brigadier.MessageComponentSerializer.message().deserialize(var7.getRawMessage()));
+            // Paper end - Add UnknownCommandEvent
             if (var7.getInput() != null && var7.getCursor() >= 0) {
                 int min = Math.min(var7.getInput().length(), var7.getCursor());
                 MutableComponent mutableComponent = Component.empty()
@@ -364,7 +_,17 @@
                 }
 
                 mutableComponent.append(Component.translatable("command.context.here").withStyle(ChatFormatting.RED, ChatFormatting.ITALIC));
-                source.sendFailure(mutableComponent);
+                // Paper start - Add UnknownCommandEvent
+                // source.sendFailure(mutableComponent);
+                builder
+                    .append(net.kyori.adventure.text.Component.newline())
+                    .append(io.papermc.paper.adventure.PaperAdventure.asAdventure(mutableComponent));
+            }
+            org.bukkit.event.command.UnknownCommandEvent event = new org.bukkit.event.command.UnknownCommandEvent(source.getBukkitSender(), command, org.spigotmc.SpigotConfig.unknownCommandMessage.isEmpty() ? null : builder.build());
+            org.bukkit.Bukkit.getServer().getPluginManager().callEvent(event);
+            if (event.message() != null) {
+                source.sendFailure(io.papermc.paper.adventure.PaperAdventure.asVanilla(event.message()), false);
+                // Paper end - Add UnknownCommandEvent
             }
 
             return null;
@@ -392,17 +_,110 @@
     }
 
     public void sendCommands(ServerPlayer player) {
+        // Paper start - Send empty commands if tab completion is disabled
+        if (org.spigotmc.SpigotConfig.tabComplete < 0) {
+            player.connection.send(new ClientboundCommandsPacket(new RootCommandNode<>(), COMMAND_NODE_INSPECTOR));
+            return;
+        }
+        // Paper end - Send empty commands if tab completion is disabled
+        // CraftBukkit start
+        // Register Vanilla commands into builtRoot as before
+        // Paper start - Perf: Async command map building
+        // Copy root children to avoid concurrent modification during building
+        final java.util.Collection<CommandNode<CommandSourceStack>> commandNodes = new java.util.ArrayList<>(this.dispatcher.getRoot().getChildren());
+        COMMAND_SENDING_POOL.execute(() -> this.sendAsync(player, commandNodes));
+    }
+
+    // Fixed pool, but with discard policy
+    public static final java.util.concurrent.ExecutorService COMMAND_SENDING_POOL = new java.util.concurrent.ThreadPoolExecutor(
+        2, 2, 0, java.util.concurrent.TimeUnit.MILLISECONDS,
+        new java.util.concurrent.LinkedBlockingQueue<>(),
+        new com.google.common.util.concurrent.ThreadFactoryBuilder()
+            .setNameFormat("Paper Async Command Builder Thread Pool - %1$d")
+            .setUncaughtExceptionHandler(new net.minecraft.DefaultUncaughtExceptionHandlerWithName(net.minecraft.server.MinecraftServer.LOGGER))
+            .build(),
+        new java.util.concurrent.ThreadPoolExecutor.DiscardPolicy()
+    );
+
+    private void sendAsync(ServerPlayer player, java.util.Collection<CommandNode<CommandSourceStack>> dispatcherRootChildren) {
+        // Paper end - Perf: Async command map building
         Map<CommandNode<CommandSourceStack>, CommandNode<CommandSourceStack>> map = new HashMap<>();
         RootCommandNode<CommandSourceStack> rootCommandNode = new RootCommandNode<>();
         map.put(this.dispatcher.getRoot(), rootCommandNode);
-        fillUsableCommands(this.dispatcher.getRoot(), rootCommandNode, player.createCommandSourceStack(), map);
+        fillUsableCommands(dispatcherRootChildren, rootCommandNode, player.createCommandSourceStack(), map); // Paper - Perf: Async command map building; pass copy of children
+
+        java.util.Collection<String> bukkit = new java.util.LinkedHashSet<>();
+        for (CommandNode node : rootCommandNode.getChildren()) {
+            bukkit.add(node.getName());
+        }
+        // Paper start - Perf: Async command map building
+        new com.destroystokyo.paper.event.brigadier.AsyncPlayerSendCommandsEvent<CommandSourceStack>(player.getBukkitEntity(), (RootCommandNode) rootCommandNode, false).callEvent(); // Paper - Brigadier API
+        net.minecraft.server.MinecraftServer.getServer().execute(() -> {
+            runSync(player, bukkit, rootCommandNode);
+        });
+    }
+
+    private void runSync(ServerPlayer player, java.util.Collection<String> bukkit, RootCommandNode<CommandSourceStack> rootCommandNode) {
+        // Paper end - Perf: Async command map building
+        new com.destroystokyo.paper.event.brigadier.AsyncPlayerSendCommandsEvent<CommandSourceStack>(player.getBukkitEntity(), (RootCommandNode) rootCommandNode, true).callEvent(); // Paper - Brigadier API
+        org.bukkit.event.player.PlayerCommandSendEvent event = new org.bukkit.event.player.PlayerCommandSendEvent(player.getBukkitEntity(), new java.util.LinkedHashSet<>(bukkit));
+        event.getPlayer().getServer().getPluginManager().callEvent(event);
+
+        // Remove labels that were removed during the event
+        for (String orig : bukkit) {
+            if (!event.getCommands().contains(orig)) {
+                rootCommandNode.removeCommand(orig);
+            }
+        }
+        // CraftBukkit end
         player.connection.send(new ClientboundCommandsPacket(rootCommandNode, COMMAND_NODE_INSPECTOR));
     }
 
-    private static <S> void fillUsableCommands(CommandNode<S> root, CommandNode<S> current, S source, Map<CommandNode<S>, CommandNode<S>> output) {
-        for (CommandNode<S> commandNode : root.getChildren()) {
+    private static <S> void fillUsableCommands(java.util.Collection<CommandNode<S>> children, CommandNode<S> current, S source, Map<CommandNode<S>, CommandNode<S>> output) { // Paper - Perf: Async command map building; pass copy of children
+        for (CommandNode<S> commandNode : children) {  // Paper - Perf: Async command map building; pass copy of children
+            // Paper start - Brigadier API
+            if (commandNode.clientNode != null) {
+                commandNode = commandNode.clientNode;
+            }
+            // Paper end - Brigadier API
+            if (!org.spigotmc.SpigotConfig.sendNamespaced && commandNode.getName().contains(":")) continue; // Spigot
             if (commandNode.canUse(source)) {
                 ArgumentBuilder<S, ?> argumentBuilder = commandNode.createBuilder();
+                // Paper start
+                /*
+                Because of how commands can be yeeted right left and center due to bad bukkit practices
+                we need to be able to ensure that ALL commands are registered (even redirects).
+
+                What this will do is IF the redirect seems to be "dead" it will create a builder and essentially populate (flatten)
+                all the children from the dead redirect to the node.
+
+                So, if minecraft:msg redirects to msg but the original msg node has been overriden minecraft:msg will now act as msg and will explicilty inherit its children.
+
+                The only way to fix this is to either:
+                - Send EVERYTHING flattened, don't use redirects
+                - Don't allow command nodes to be deleted
+                - Do this :)
+                 */
+                // Is there an invalid command redirect?
+                if (argumentBuilder.getRedirect() != null && output.get(argumentBuilder.getRedirect()) == null) {
+                    // Create the argument builder with the same values as the specified node, but with a different literal and populated children
+
+                    final CommandNode<S> redirect = argumentBuilder.getRedirect();
+                    // Diff copied from LiteralCommand#createBuilder
+                    final com.mojang.brigadier.builder.LiteralArgumentBuilder<S> builder = com.mojang.brigadier.builder.LiteralArgumentBuilder.literal(commandNode.getName());
+                    builder.requires(redirect.getRequirement());
+                    // builder.forward(redirect.getRedirect(), redirect.getRedirectModifier(), redirect.isFork()); We don't want to migrate the forward, since it's invalid.
+                    if (redirect.getCommand() != null) {
+                        builder.executes(redirect.getCommand());
+                    }
+                    // Diff copied from LiteralCommand#createBuilder
+                    for (final CommandNode<S> child : redirect.getChildren()) {
+                        builder.then(child);
+                    }
+
+                    argumentBuilder = builder;
+                }
+                // Paper end
                 if (argumentBuilder.getRedirect() != null) {
                     argumentBuilder.redirect(output.get(argumentBuilder.getRedirect()));
                 }
@@ -411,7 +_,7 @@
                 output.put(commandNode, commandNode1);
                 current.addChild(commandNode1);
                 if (!commandNode.getChildren().isEmpty()) {
-                    fillUsableCommands(commandNode, commandNode1, source, output);
+                    fillUsableCommands(commandNode.getChildren(), commandNode1, source, output); // Paper - Perf: Async command map building; pass copy of children
                 }
             }
         }
