AuthRemoved open source
Static_Menu.lua Shark LUA
Download
12,000 lines · updated 4 hours ago
Preview shortened for your browser. Download the file for the full source.
--[[
  STATIC Lua — Shark Executor

  INJECT:    Paste / execute this entire file in the Shark Lua executor (standalone).
             Do NOT use moon x static.lua unless you want the Moon menu.
  LOOK:      Dark Static layout, blue #1689d4 accents.
  FIRST RUN:  Keybind setup — press a key, then Enter to confirm.
  OPEN:      Your confirmed hotkey (e.g. CAPSLOCK, F9, DELETE)
  NAV:       Arrow Up / Down — move selection
             Enter — open category / activate option
             Backspace — back (or close menu from main screen)
             Q / E — switch tabs inside a category
  NOTE:      No options auto-enable on inject. Toggles call features immediately.
  SHARK:     Uses SharkAPI from "Shark API" (Nui DUI, Input, Clipboard, HTTP, Cloud,
             SyncTree spoofs, SyncCameraPosition, SendEntityControlToPlayer, SendDamageToEntity,
             GivePickupReward, Resources list/stop, OnReset, etc.).
  POLICY:   Shark host-side Lua only. No resource inject, no native-hook layer.
  STATIC:    Also runs on the Static executor. The API bridge below binds whichever
             global the host provides (static.* or SharkAPI.*) and publishes the other,
             so every SharkAPI.* call site in this file is untouched.
]]

--[[============================================================================
  STATIC EXECUTOR API BRIDGE  (v1)

  Static Menu's documentation is the Shark API renamed. Two differences, and
  only two:

    1. the global table         SharkAPI.*        ->  static.*
    2. resource injection       SharkAPI.Inject   ->  static.injectresource
                                                      (resource, code [, vars])

  Every other symbol is name-identical, sub-namespaces included: Resources,
  Misc, Camera, Net, Input, Scripting, Cloud, SyncTree, Nui, Drawing, Fonts,
  Images. Static's docs also publish a smaller subset than Shark's — the
  executor still exposes the rest, they are simply undocumented.

  So this file does not touch the ~200 SharkAPI.* call sites below. It binds
  whichever global the host actually provides and publishes the other name as
  a view over it:

    host has SharkAPI  ->  _G.static   is built from SharkAPI  (Shark host)
    host has static    ->  _G.SharkAPI is built from static    (Static host)

  A view is a materialised copy (so `type(SharkAPI.Nui) == "table"` and
  pairs() behave exactly as before) plus an __index fallback, so symbols the
  executor installs after this file loads still resolve. Missing symbols read
  nil, never error — the probe style used throughout this file
  (`type(api.X) == "function"`) keeps working unchanged.

  InjectSafe is deliberately NOT aliased onto static.injectresource. This file
  fails closed on WaveShield when InjectSafe is absent (StaticShark.inject),
  and quietly swapping in the raw injector there is a ban vector. If a build
  turns out to need it, opt in explicitly, once, at the top of your session:

      StaticApiBridge.allow_unsafe_inject_safe()

  Diagnostics:
      StaticApiBridge.backend            "SharkAPI" | "static" | nil
      StaticApiBridge.inject_safe_exact  true when a real safe-inject exists
      StaticApiBridge.report()           prints every symbol this menu calls
                                         that the host does not provide
============================================================================]]

do
    local G = _G

    -- Fallback chains keyed by the name this menu calls. First hit wins.
    -- Values may be dotted paths, resolved against the backend table.
    local CHAIN = {
        Inject                 = { "Inject", "injectresource", "InjectResource" },
        injectresource         = { "injectresource", "Inject" },
        InjectSafe             = { "InjectSafe", "injectresourcesafe", "InjectResourceSafe" },
        OpenURL                = { "OpenURL", "OpenUrl" },
        OpenUrl                = { "OpenUrl", "OpenURL" },
        SetVar                 = { "SetVar", "Cloud.SaveVariable" },
        GetVar                 = { "GetVar", "Cloud.GetVariable" },
        DoesVarExist           = { "DoesVarExist", "Cloud.DoesVarExist" },
        GetUserDefaultLanguage = { "GetUserDefaultLanguage", "GetUserLanguage" },
    }

    -- Symbols this menu actually calls. Used only by report().
    local USED = {
        "AddServerEventListener", "AsyncRequestHTTP", "BlockGameEvent",
        "BlockServerEvent", "Camera.SetGameplayCamFov", "Cloud.GetVariable",
        "Cloud.SaveVariable", "Drawing.SetCursorActive",
        "Fonts.CreateFontAwesome", "Fonts.ImportFontFromUrl",
        "GetClipboardText", "GetDiscordCanaryInfo", "GetDiscordInfo",
        "GetDiscordPTBInfo", "GetGlobalStateBags", "GetLoadedResources",
        "GetServerInfo", "GetStateBags", "GetSubscription", "GetUsername",
        "GetVar", "GivePickupReward", "Inject", "InjectSafe",
        "IsConsoleOpen", "IsInjectionAvailable", "IsKeyJustPressed",
        "Misc.BlockServerWeaponChange", "Misc.RequestRagdoll",
        "Net.GetCurrentServerCode", "Net.SendWebhook", "Notify",
        "Nui.CreateDui", "Nui.DestroyDui", "Nui.SendDuiMessage", "OpenURL",
        "OpenUrl", "QuitGame", "RequestHTTP", "RequestRagdoll",
        "Resources.OnResourceRestart", "Scripting.HookNative",
        "SendDamageToEntity", "SendEntityControlToPlayer", "SetClipboardText",
        "SetVar", "StopResource", "SyncCameraPosition",
        "SyncTree.OnDisconnectFromServer", "SyncTree.SpoofExplosion",
        "SyncTree.SpoofServerCoords", "SyncTree.SpoofServerWeapon",
        "SyncTree.SpoofWeaponDamage",
    }

    local function resolve(src, path)
        if type(src) ~= "table" or type(path) ~= "string" then return nil end
        if not path:find(".", 1, true) then return src[path] end
        local cur = src
        for part in path:gmatch("[^%.]+") do
            if type(cur) ~= "table" then return nil end
            cur = cur[part]
        end
        return cur
    end

    local function lookup(src, key)
        local chain = CHAIN[key]
        if chain then
            for index = 1, #chain do
                local value = resolve(src, chain[index])
                if value ~= nil then return value end
            end
            return nil
        end
        return resolve(src, key)
    end

    -- Materialised copy + late-binding __index, so probes and pairs() see the
    -- same shape the native table has while newly-installed symbols still land.
    local function build_view(src)
        local view = {}
        for key, value in pairs(src) do view[key] = value end
        for key in pairs(CHAIN) do
            if view[key] == nil then
                local value = lookup(src, key)
                if value ~= nil then view[key] = value end
            end
        end
        return setmetatable(view, {
            __index = function(_, key) return lookup(src, key) end,
            __newindex = function(_, key, value)
                src[key] = value
                rawset(view, key, value)
            end,
        })
    end

    local shark  = rawget(G, "SharkAPI")
    local staticGlobal = rawget(G, "static")
    if type(staticGlobal) ~= "table" then staticGlobal = rawget(G, "Static") end

    local backend, backendName
    if type(shark) == "table" then
        backend, backendName = shark, "SharkAPI"
        if type(staticGlobal) ~= "table" then
            G.static = build_view(shark)
        end
    elseif type(staticGlobal) == "table" then
        backend, backendName = staticGlobal, "static"
        G.SharkAPI = build_view(staticGlobal)
    end

    local bridge = {
        version = 1,
        backend = backendName,
        -- The real host table, kept so the wrapper block below can bind
        -- straight to it and never resolve through _G.static (which the
        -- wrappers replace -- that would be an infinite loop).
        raw = backend,
        inject_safe_exact = type(resolve(backend, "InjectSafe")) == "function"
            or type(resolve(backend, "injectresourcesafe")) == "function",
        unsafe_inject = resolve(backend, "injectresource") or resolve(backend, "Inject"),
    }

    -- Opt-in: point SharkAPI.InjectSafe at the raw injector on hosts that have
    -- no safe variant. Off by default — the WaveShield path is fail-closed for
    -- a reason.
    function bridge.allow_unsafe_inject_safe()
        if bridge.inject_safe_exact then return true end
        if type(bridge.unsafe_inject) ~= "function" then return false end
        local api = rawget(G, "SharkAPI")
        if type(api) ~= "table" then return false end
        api.InjectSafe = bridge.unsafe_inject
        bridge.inject_safe_unsafe_alias = true
        return true
    end

    function bridge.report(printer)
        local out = printer or print
        local api = rawget(G, "SharkAPI")
        if type(api) ~= "table" then
            out("StaticApiBridge: no API global found (neither SharkAPI nor static)")
            return 0, USED
        end
        local missing = {}
        for index = 1, #USED do
            local value = resolve(api, USED[index])
            if value == nil then missing[#missing + 1] = USED[index] end
        end
        out(string.format(
            "StaticApiBridge v%d: backend=%s, %d/%d symbols present, inject_safe_exact=%s",
            bridge.version, tostring(backendName), #USED - #missing, #USED,
            tostring(bridge.inject_safe_exact)))
        for index = 1, #missing do out("  missing: " .. missing[index]) end
        return #USED - #missing, missing
    end

    G.StaticApiBridge = bridge
end
-- [[ end STATIC EXECUTOR API BRIDGE ]]

--[[============================================================================
  STATIC API WRAPPERS  (v1)

  Every function in the Static / Shark documentation, as a named Lua function
  with its signature, return type and doc notes attached. Purely additive:
  nothing below this block changes, and the menu's own SharkAPI.* call sites
  are untouched. Use these when you want the documented surface with a real
  signature in front of you instead of a bare global.

      static.GetUsername()
      static.Drawing.DrawRect(x, y, w, h, r, g, b, a, rounding, flags)
      static.SyncTree.SpoofServerCoords(true, vector3(150.0, 120.0, 30.0))
      static.Seller.GetUserInformation(sellerKey, username)

  On a Static host this replaces the raw static global with a table of the
  same shape: documented names resolve to these wrappers, every other key
  falls through to the executor untouched, so nothing you could call before
  stops working.

  Backend resolution runs through whatever the host provides — SharkAPI on a
  Shark host, static on a Static host — via the bridge above, so
  static.Inject and static.injectresource both land on whichever spelling
  the host actually has.
  Lookups are cached per path and re-resolved automatically if the API global
  is swapped.

  A symbol the host does not provide raises
  "static: host does not provide <path>" at your call site rather than
  "attempt to call a nil value". Probe first with:

      static.SelfTest()   -- prints coverage and every missing symbol

  Namespaces: Resources, Misc, Camera, Net, Input, Scripting, Cloud, SyncTree,
  Nui, Drawing, Fonts, Images, Seller.
============================================================================]]

do
    local G = _G

    local static = {
        Resources = {}, Misc = {}, Camera = {}, Net = {}, Input = {},
        Scripting = {}, Cloud = {}, SyncTree = {}, Nui = {}, Drawing = {},
        Fonts = {}, Images = {}, Seller = {},
    }

    -- Backend lookup. Order matters: SharkAPI first (the real table on a Shark
    -- host, the bridge's aliased view on a Static host), then the raw host
    -- table the bridge captured. _G.static is never trusted as a backend --
    -- this block publishes itself there, and reading it back would loop.
    local function host()
        local api = rawget(G, "SharkAPI")
        if type(api) == "table" then return api end
        local bridge = rawget(G, "StaticApiBridge")
        api = bridge and bridge.raw
        if type(api) == "table" then return api end
        api = rawget(G, "static")
        if type(api) == "table" and api ~= static then return api end
        api = rawget(G, "Static")
        if type(api) == "table" and api ~= static then return api end
        return nil
    end

    local function resolve(api, path)
        if type(api) ~= "table" then return nil end
        if not path:find(".", 1, true) then return api[path] end
        local cur = api
        for part in path:gmatch("[^%.]+") do
            if type(cur) ~= "table" then return nil end
            cur = cur[part]
        end
        return cur
    end

    -- Resolved-symbol cache. Dropped whenever the API global is replaced, so a
    -- late-loading or swapped executor table is picked up without a reload.
    local cache, cachedHost = {}, nil

    local function fn(path)
        local api = host()
        if api ~= cachedHost then cache, cachedHost = {}, api end
        local value = cache[path]
        if value == nil then
            value = resolve(api, path)
            if type(value) ~= "function" then
                error("static: host does not provide " .. path, 3)
            end
            cache[path] = value
        end
        return value
    end

    -- Every backend path these wrappers touch. Used by SelfTest.
    local PATHS = {
        "AddServerEventListener",
        "AsyncRequestHTTP",
        "BlockClientEvent",
        "BlockGameEvent",
        "BlockServerEvent",
        "Camera.SetGameplayCamFov",
        "Cloud.DoesVarExist",
        "Cloud.GetVariable",
        "Cloud.SaveVariable",
        "Drawing.DrawBlur",
        "Drawing.DrawBorderRect",
        "Drawing.DrawCircle",
        "Drawing.DrawGradientRect",
        "Drawing.DrawImage",
        "Drawing.DrawLine",
        "Drawing.DrawRect",
        "Drawing.DrawShadowCircle",
        "Drawing.DrawShadowRect",
        "Drawing.DrawText",
        "Drawing.PopClipRect",
        "Drawing.PopOrder",
        "Drawing.PushClipRect",
        "Drawing.PushOrder",
        "Drawing.ResetCursorIcon",
        "Drawing.SetCursorActive",
        "Drawing.SetCursorIcon",
        "EditWeaponSize",
        "ExecuteJS",
        "Fonts.CreateFontAwesome",
        "Fonts.GetTextHeight",
        "Fonts.GetTextWidthSize",
        "Fonts.ImportFontFromUrl",
        "Fonts.IsFontReady",
        "ForceKeyPress",
        "GetClipboardText",
        "GetConsoleInputText",
        "GetCursorX",
        "GetCursorY",
        "GetDiscordAvatarUrl",
        "GetDiscordCanaryInfo",
        "GetDiscordInfo",
        "GetDiscordPTBInfo",
        "GetExecutorState",
        "GetGlobalStateBags",
        "GetLoadedResources",
        "GetPcUsername",
        "GetServerInfo",
        "GetServerName",
        "GetServerPlayersCount",
        "GetStateBags",
        "GetSubscription",
        "GetUserDefaultLanguage",
        "GetUsername",
        "GivePickupReward",
        "GivePickupRewardAll",
        "Images.ImportImageFromUrl",
        "Images.ImportMultiImages",
        "Inject",
        "InjectSafe",
        "Input.ForceKeyState",
        "IsConsoleOpen",
        "IsEventLoggerEnabled",
        "IsFriendlyFireAllowed",
        "IsInjectionAvailable",
        "IsKeyJustPressed",
        "IsKeyPressed",
        "LockEventLogger",
        "Misc.BlockServerWeaponChange",
        "Misc.GetResourceFiles",
        "Net.AsyncSendWebhook",
        "Net.GetCurrentServerCode",
        "Net.GetCurrentServerIconUrl",
        "Net.SendWebhook",
        "Nui.CreateDui",
        "Nui.DestroyDui",
        "Nui.SendDuiMessage",
        "OnKeyDown",
        "OnKeyUp",
        "OnMouseDown",
        "OnMouseUp",
        "OnReset",
        "OpenURL",
        "PlaySoundFromUrl",
        "QuitGame",
        "RemoveAddServerEventListener",
        "RemoveOnKeyDown",
        "RemoveOnKeyUp",
        "RemoveOnMouseDown",
        "RemoveOnMouseUp",
        "RemoveResourceNui",
        "RequestHTTP",
        "RequestRagdoll",
        "Resources.OnResourceRestart",
        "Resources.RemoveOnResourceRestart",
        "Scripting.AddHookCallback",
        "Scripting.DisableAllHooks",
        "Scripting.GetNativeHash",
        "Scripting.HookNative",
        "Scripting.HookNativeForResource",
        "Scripting.IsNativeHooked",
        "Scripting.RestoreNative",
        "SendDamageToEntity",
        "SendEntityControlToPlayer",
        "SetClipboardText",
        "SetExecutorState",
        "StopResource",
        "SyncCameraPosition",
        "SyncTree.AddSpoofedTaskCommand",
        "SyncTree.AddSpoofedTaskType",
        "SyncTree.RemoveSpoofedTaskCommand",
        "SyncTree.RemoveSpoofedTaskType",
        "SyncTree.SpoofPlayerModel",
        "SyncTree.SpoofPunchDamage",
        "SyncTree.SpoofServerCoords",
        "SyncTree.SpoofServerHeading",
        "SyncTree.SpoofServerWeapon",
        "SyncTree.SpoofWeaponDamage",
    }

    --[[==========================================================================
      USER INFORMATION
    ==========================================================================]]

    --- static.GetUsername() -> string
    --- Returns the user of the injected client.
    function static.GetUsername()
        return fn('GetUsername')()
    end

    --- static.GetSubscription() -> string
    --- Returns the subscription of the injected client. Example: "21/12/2025".
    function static.GetSubscription()
        return fn('GetSubscription')()
    end

    --- static.GetPcUsername() -> string
    --- Returns the PC user of the injected client.
    function static.GetPcUsername()
        return fn('GetPcUsername')()
    end

    --- static.GetUserDefaultLanguage() -> string
    --- The user's PC language, e.g. "pt-BR".
    function static.GetUserDefaultLanguage()
        return fn('GetUserDefaultLanguage')()
    end

    --[[==========================================================================
      SERVER INFORMATION
    ==========================================================================]]

    --- static.GetServerPlayersCount() -> string
    --- Number of players in the city.
    function static.GetServerPlayersCount()
        return fn('GetServerPlayersCount')()
    end

    --- static.GetServerName() -> string
    function static.GetServerName()
        return fn('GetServerName')()
    end

    --- static.GetServerInfo() -> table
    --- Server information object.
    function static.GetServerInfo()
        return fn('GetServerInfo')()
    end

    --[[==========================================================================
      RESOURCES
    ==========================================================================]]

    --- static.Inject(resourceName, code [, directory]) -> none
    --- Runs `code` inside the target resource. `directory` targets one file
    --- (e.g. "@@vrp/client/player_state.lua"). resourceName "any" picks a
    --- random loaded resource.
    --- NOTE: raw Inject is detected by FiveGuard — prefer InjectSafe.
    function static.Inject(...)
        return fn('Inject')(...)
    end

    --- static.InjectSafe(resourceName, code) -> none
    --- Injection path documented as undetected on waveshield.
    function static.InjectSafe(resourceName, code)
        return fn('InjectSafe')(resourceName, code)
    end

    --- static.IsInjectionAvailable() -> boolean
    --- True once the injection layer is loaded and ready.
    function static.IsInjectionAvailable()
        return fn('IsInjectionAvailable')()
    end

    --- static.GetLoadedResources() -> table
    --- Array of resources that can be injected.
    function static.GetLoadedResources()
        return fn('GetLoadedResources')()
    end

    --- static.StopResource(resourceName) -> boolean
    --- True if the resource was stopped correctly.
    function static.StopResource(resourceName)
        return fn('StopResource')(resourceName)
    end

    --- static.RemoveResourceNui(resourceName) -> none
    --- Removes the NUI frame from the resource. Does not stop the resource.
    function static.RemoveResourceNui(resourceName)
        return fn('RemoveResourceNui')(resourceName)
    end

    --- static.Resources.OnResourceRestart(callback) -> integer callbackId
    --- callback(resourceName) fires whenever a resource restarts on the server.
    function static.Resources.OnResourceRestart(callback)
        return fn('Resources.OnResourceRestart')(callback)
    end

    --- static.Resources.RemoveOnResourceRestart(callbackId) -> none
    function static.Resources.RemoveOnResourceRestart(callbackId)
        return fn('Resources.RemoveOnResourceRestart')(callbackId)
    end

    --[[==========================================================================
      MISC
    ==========================================================================]]

    --- static.GetClipboardText() -> string
    function static.GetClipboardText()
        return fn('GetClipboardText')()
    end

    --- static.SetClipboardText(text) -> none
    function static.SetClipboardText(text)
        return fn('SetClipboardText')(text)
    end

    --- static.GetConsoleInputText() -> string
    --- Current console input content.
    function static.GetConsoleInputText()
        return fn('GetConsoleInputText')()
    end

    --- static.GetCursorX() -> number
    function static.GetCursorX()
        return fn('GetCursorX')()
    end

    --- static.GetCursorY() -> number
    function static.GetCursorY()
        return fn('GetCursorY')()
    end

    --- static.GetDiscordInfo() -> string username, string id
    function static.GetDiscordInfo()
        return fn('GetDiscordInfo')()
    end

    --- static.GetDiscordCanaryInfo() -> string username, string id
    function static.GetDiscordCanaryInfo()
        return fn('GetDiscordCanaryInfo')()
    end

    --- static.GetDiscordPTBInfo() -> string username, string id
    function static.GetDiscordPTBInfo()
        return fn('GetDiscordPTBInfo')()
    end

    --- static.GetDiscordAvatarUrl(discordId) -> string
    --- Avatar url, or the literal "not found".
    function static.GetDiscordAvatarUrl(discordId)
        return fn('GetDiscordAvatarUrl')(discordId)
    end

    --- static.QuitGame(reason) -> none (game closes)
    function static.QuitGame(reason)
        return fn('QuitGame')(reason)
    end

    --- static.IsFriendlyFireAllowed() -> boolean
    --- Getter for native 0xF808475FA571D823.
    function static.IsFriendlyFireAllowed()
        return fn('IsFriendlyFireAllowed')()
    end

    --- static.RequestRagdoll(ped) -> none
    function static.RequestRagdoll(ped)
        return fn('RequestRagdoll')(ped)
    end

    --- static.GetStateBags() -> table
    --- Local player statebags: {"state1", "state2"}.
    function static.GetStateBags()
        return fn('GetStateBags')()
    end

    --- static.GetGlobalStateBags() -> table
    function static.GetGlobalStateBags()
        return fn('GetGlobalStateBags')()
    end

    --- static.OpenURL(url) -> none
    --- Opens the url in the default browser.
    function static.OpenURL(url)
        return fn('OpenURL')(url)
    end

    --- static.GetExecutorState() -> boolean
    --- True when the executor window is open.
    function static.GetExecutorState()
        return fn('GetExecutorState')()
    end

    --- static.SetExecutorState(newState) -> none
    function static.SetExecutorState(newState)
        return fn('SetExecutorState')(newState)
    end

    --- static.IsConsoleOpen() -> boolean
    --- True if the FiveM console is open.
    function static.IsConsoleOpen()
        return fn('IsConsoleOpen')()
    end

    --- static.EditWeaponSize(weaponSize) -> none
    function static.EditWeaponSize(weaponSize)
        return fn('EditWeaponSize')(weaponSize)
    end

    --- static.SyncCameraPosition(enable [, coords]) -> none
    --- Synchronizes the camera position with the ESP. coords is a vector3.
    function static.SyncCameraPosition(...)
        return fn('SyncCameraPosition')(...)
    end

    --- static.PlaySoundFromUrl(url) -> none
    --- The audio must be a .wav file.
    function static.PlaySoundFromUrl(url)
        return fn('PlaySoundFromUrl')(url)
    end

    --- static.OnReset(callback) -> none
    --- Fires when reset unloads all running code.
    function static.OnReset(callback)
        return fn('OnReset')(callback)
    end

    --- static.Misc.GetResourceFiles(resourcePath) -> table
    --- File list for a resource, e.g. 'resources:/vrp/'.
    function static.Misc.GetResourceFiles(resourcePath)
        return fn('Misc.GetResourceFiles')(resourcePath)
    end

    --- static.Misc.BlockServerWeaponChange(enable) -> none
    --- Blocks scripts from swapping or removing your weapon.
    function static.Misc.BlockServerWeaponChange(enable)
        return fn('Misc.BlockServerWeaponChange')(enable)
    end

    --- static.Camera.SetGameplayCamFov(fov) -> none
    function static.Camera.SetGameplayCamFov(fov)
        return fn('Camera.SetGameplayCamFov')(fov)
    end

    --- static.Net.GetCurrentServerCode() -> string
    --- cfx code of the current server.
    function static.Net.GetCurrentServerCode()
        return fn('Net.GetCurrentServerCode')()
    end

    --- static.Net.GetCurrentServerIconUrl() -> string
    function static.Net.GetCurrentServerIconUrl()
        return fn('Net.GetCurrentServerIconUrl')()
    end

    --[[==========================================================================
      INPUT
      vkCodes: https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
      ForceKeyPress scancodes: https://wiki.osdev.org/PS/2_Keyboard
    ==========================================================================]]

    --- static.IsKeyJustPressed(vkCode) -> boolean
    --- True on the frame the key went down.
    function static.IsKeyJustPressed(vkCode)
        return fn('IsKeyJustPressed')(vkCode)
    end

    --- static.IsKeyPressed(vkCode) -> boolean
    function static.IsKeyPressed(vkCode)
        return fn('IsKeyPressed')(vkCode)
    end

    --- static.ForceKeyPress(keyCode) -> none
    function static.ForceKeyPress(keyCode)
        return fn('ForceKeyPress')(keyCode)
    end

    --- static.OnKeyUp(callback) -> integer callbackId
    --- callback(key)
    function static.OnKeyUp(callback)
        return fn('OnKeyUp')(callback)
    end

    --- static.RemoveOnKeyUp(callbackId) -> none
    function static.RemoveOnKeyUp(callbackId)
        return fn('RemoveOnKeyUp')(callbackId)
    end

    --- static.OnKeyDown(callback) -> integer callbackId
    function static.OnKeyDown(callback)
        return fn('OnKeyDown')(callback)
    end

    --- static.RemoveOnKeyDown(callbackId) -> none
    function static.RemoveOnKeyDown(callbackId)
        return fn('RemoveOnKeyDown')(callbackId)
    end

    --- static.OnMouseUp(callback) -> integer callbackId
    function static.OnMouseUp(callback)
        return fn('OnMouseUp')(callback)
    end

    --- static.RemoveOnMouseUp(callbackId) -> none
    function static.RemoveOnMouseUp(callbackId)
        return fn('RemoveOnMouseUp')(callbackId)
    end

    --- static.OnMouseDown(callback) -> integer callbackId
    function static.OnMouseDown(callback)
        return fn('OnMouseDown')(callback)
    end

    --- static.RemoveOnMouseDown(callbackId) -> none
    function static.RemoveOnMouseDown(callbackId)
        return fn('RemoveOnMouseDown')(callbackId)
    end

    --- static.Input.ForceKeyState(vkKeyCode, down) -> none
    --- Holds or releases a key: (0x34, true) then (0x34, false).
    function static.Input.ForceKeyState(vkKeyCode, down)
        return fn('Input.ForceKeyState')(vkKeyCode, down)
    end

    --[[==========================================================================
      SCRIPTING / NATIVE HOOKS
      eArgType = { INTEGER = 1, STRING = 2, BOOLEAN = 3, FLOAT = 4,
                   NONE = 5, OBJECT = 6, VECTOR3 = 7 }
    ==========================================================================]]

    --- static.Scripting.HookNative(nativeHash, value) -> boolean
    --- nativeHash accepts a hash or the native name. When `value` is a function,
    --- its first return is `callOriginal`: true runs the original and ignores the
    --- rest, false uses your values.
    function static.Scripting.HookNative(nativeHash, value)
        return fn('Scripting.HookNative')(nativeHash, value)
    end

    --- static.Scripting.HookNativeForResource(nativeHash, value, resourceName) -> boolean
    --- Same as HookNative, scoped to one resource.
    function static.Scripting.HookNativeForResource(nativeHash, value, resourceName)
        return fn('Scripting.HookNativeForResource')(nativeHash, value, resourceName)
    end

    --- static.Scripting.AddHookCallback(nativeHash, argType..., returnType, callback) -> boolean
    --- Variadic: one eArgType per native argument, then the return type last,
    --- then the callback. Supported: String, Boolean, Float, Integer, Object,
    --- Vector3, and void (NONE).
    function static.Scripting.AddHookCallback(...)
        return fn('Scripting.AddHookCallback')(...)
    end

    --- static.Scripting.RestoreNative(nativeHash) -> boolean
    function static.Scripting.RestoreNative(nativeHash)
        return fn('Scripting.RestoreNative')(nativeHash)
    end

    --- static.Scripting.IsNativeHooked(nativeHash) -> boolean
    function static.Scripting.IsNativeHooked(nativeHash)
        return fn('Scripting.IsNativeHooked')(nativeHash)
    end

    --- static.Scripting.DisableAllHooks() -> none
    --- Restores every hooked native.
    function static.Scripting.DisableAllHooks()
        return fn('Scripting.DisableAllHooks')()
    end

    --- static.Scripting.GetNativeHash(nativeName) -> number
    --- GetNativeHash("PlayerPedId") == 0xD80958FC74E988A6
    function static.Scripting.GetNativeHash(nativeName)
        return fn('Scripting.GetNativeHash')(nativeName)
    end

    --- static.BlockGameEvent(eventName, blockEvent) -> none
    --- e.g. ("CEventNetworkPlayerEnteredVehicle", true)
    function static.BlockGameEvent(eventName, blockEvent)
        return fn('BlockGameEvent')(eventName, blockEvent)
    end

    --- static.ExecuteJS(code) -> none
    function static.ExecuteJS(code)
        return fn('ExecuteJS')(code)
    end

    --[[==========================================================================
      EVENTS LOGGER
    ==========================================================================]]

    --- static.IsEventLoggerEnabled() -> boolean
    function static.IsEventLoggerEnabled()
        return fn('IsEventLoggerEnabled')()
    end

    --- static.LockEventLogger(enable) -> none
    --- While locked, no event is surfaced in the logger.
    function static.LockEventLogger(enable)
        return fn('LockEventLogger')(enable)
    end

    --- static.BlockServerEvent(enable, eventName) -> none
    function static.BlockServerEvent(enable, eventName)
        return fn('BlockServerEvent')(enable, eventName)
    end

    --- static.BlockClientEvent(enable, eventName) -> none
    function static.BlockClientEvent(enable, eventName)
        return fn('BlockClientEvent')(enable, eventName)
    end

    --- static.AddServerEventListener(callback) -> integer callbackId
    --- callback(eventName, eventPayload, resourceName); return false to cancel
    --- the event, true to let it through.
    function static.AddServerEventListener(callback)
        return fn('AddServerEventListener')(callback)
    end

    --- static.RemoveAddServerEventListener(callbackId) -> none
    function static.RemoveAddServerEventListener(callbackId)
        return fn('RemoveAddServerEventListener')(callbackId)
    end

    --[[==========================================================================
      CLOUD  (persists across game restarts and reboots)
    ==========================================================================]]

    --- static.Cloud.SaveVariable(variableId, variableContent) -> none
    function static.Cloud.SaveVariable(variableId, variableContent)
        return fn('Cloud.SaveVariable')(variableId, variableContent)
    end

    --- static.Cloud.GetVariable(variableId) -> string
    function static.Cloud.GetVariable(variableId)
        return fn('Cloud.GetVariable')(variableId)
    end

    --- static.Cloud.DoesVarExist(variableId) -> boolean
    function static.Cloud.DoesVarExist(variableId)
        return fn('Cloud.DoesVarExist')(variableId)
    end

    --- static.Net.SendWebhook(webhookId, webhookData) -> boolean
    function static.Net.SendWebhook(webhookId, webhookData)
        return fn('Net.SendWebhook')(webhookId, webhookData)
    end

    --- static.Net.AsyncSendWebhook(webhookId, webhookData) -> none
    --- Runs without freezing the game until the request finishes.
    function static.Net.AsyncSendWebhook(webhookId, webhookData)
        return fn('Net.AsyncSendWebhook')(webhookId, webhookData)
    end

    --[[==========================================================================
      HTTP
    ==========================================================================]]

    --- static.RequestHTTP(url, data) -> string
    --- data = { method = 'GET'|'POST', body = table }. Blocking.
    function static.RequestHTTP(url, data)
        return fn('RequestHTTP')(url, data)
    end

    --- static.AsyncRequestHTTP(url, data) -> table
    --- Returns a handle: handle.Success(), handle.GetResponse().
    function static.AsyncRequestHTTP(url, data)
        return fn('AsyncRequestHTTP')(url, data)
    end

    --[[==========================================================================
      EXPLOITS
    ==========================================================================]]

    --- static.GivePickupReward(playerId, rewardHash) -> none
    function static.GivePickupReward(playerId, rewardHash)
        return fn('GivePickupReward')(playerId, rewardHash)
    end

    --- static.GivePickupRewardAll(rewardHash) -> none
    function static.GivePickupRewardAll(rewardHash)
        return fn('GivePickupRewardAll')(rewardHash)
    end

    --- static.SendDamageToEntity(pHitEntity, worldHitPosition, hitComponent,
    ---     overrideDamage, weaponHash, weaponDamage, tyreIndex, suspensionIndex,
    ---     damageFlags, actionResultId, meleeId, nForcedReactionDefinitionID,
    ---     hitEntityWeapon, hitWeaponAmmoAttachment, silenced, firstBullet) -> none
    --- 16 positional args, forwarded verbatim.
    function static.SendDamageToEntity(...)
        return fn('SendDamageToEntity')(...)
    end

    --- static.SendEntityControlToPlayer(entityHandle, playerIndex) -> none
    function static.SendEntityControlToPlayer(entityHandle, playerIndex)
        return fn('SendEntityControlToPlayer')(entityHandle, playerIndex)
    end

    --[[==========================================================================
      SYNC TREE
      Task commands: https://alloc8or.re/gta5/doc/enums/eScriptTaskHash.txt
      Task types:    https://alloc8or.re/gta5/doc/enums/eTaskTypeIndex.txt
    ==========================================================================]]

    --- static.SyncTree.AddSpoofedTaskCommand(m_taskCommand) -> none
    function static.SyncTree.AddSpoofedTaskCommand(m_taskCommand)
        return fn('SyncTree.AddSpoofedTaskCommand')(m_taskCommand)
    end

    --- static.SyncTree.RemoveSpoofedTaskCommand(m_taskCommand) -> none
    function static.SyncTree.RemoveSpoofedTaskCommand(m_taskCommand)
        return fn('SyncTree.RemoveSpoofedTaskCommand')(m_taskCommand)
    end

    --- static.SyncTree.AddSpoofedTaskType(m_taskType) -> none
    function static.SyncTree.AddSpoofedTaskType(m_taskType)
        return fn('SyncTree.AddSpoofedTaskType')(m_taskType)
    end

    --- static.SyncTree.RemoveSpoofedTaskType(m_taskType) -> none
    function static.SyncTree.RemoveSpoofedTaskType(m_taskType)
        return fn('SyncTree.RemoveSpoofedTaskType')(m_taskType)
    end

    --- static.SyncTree.SpoofWeaponDamage(enable, weaponHash) -> none
    function static.SyncTree.SpoofWeaponDamage(enable, weaponHash)
        return fn('SyncTree.SpoofWeaponDamage')(enable, weaponHash)
    end

    --- static.SyncTree.SpoofPunchDamage(enable, weaponHash) -> none
    function static.SyncTree.SpoofPunchDamage(enable, weaponHash)
        return fn('SyncTree.SpoofPunchDamage')(enable, weaponHash)
    end

    --- static.SyncTree.SpoofServerWeapon(enable) -> none
    function static.SyncTree.SpoofServerWeapon(enable)
        return fn('SyncTree.SpoofServerWeapon')(enable)
    end

    --- static.SyncTree.SpoofPlayerModel(toggle [, model]) -> none
    function static.SyncTree.SpoofPlayerModel(...)
        return fn('SyncTree.SpoofPlayerModel')(...)
    end

    --- static.SyncTree.SpoofServerCoords(enable [, coords]) -> none
    function static.SyncTree.SpoofServerCoords(...)
        return fn('SyncTree.SpoofServerCoords')(...)
    end

    --- static.SyncTree.SpoofServerHeading(enable [, heading]) -> none
    function static.SyncTree.SpoofServerHeading(...)
        return fn('SyncTree.SpoofServerHeading')(...)
    end

    --[[==========================================================================
      HTML DRAWING (DUI)
    ==========================================================================]]

    --- static.Nui.CreateDui(url) -> duiHandle
    function static.Nui.CreateDui(url)
        return fn('Nui.CreateDui')(url)
    end

    --- static.Nui.SendDuiMessage(duiHandle, message) -> none
    --- message is a table; the page receives it via window 'message' events.
    function static.Nui.SendDuiMessage(duiHandle, message)
        return fn('Nui.SendDuiMessage')(duiHandle, message)
    end

    --- static.Nui.DestroyDui(duiHandle) -> none
    function static.Nui.DestroyDui(duiHandle)
        return fn('Nui.DestroyDui')(duiHandle)
    end

    --[[==========================================================================
      DRAWING
      cursorIcons = { Arrow = 0, TextInput = 1, ResizeAll = 2, ResizeNS = 3,
                      ResizeEW = 4, ResizeNESW = 5, ResizeNWSE = 6, Hand = 7,
                      NotAllowed = 8 }
    ==========================================================================]]

    --- static.Drawing.DrawRect(x, y, w, h, r, g, b, a [, rounding, flags]) -> none
    function static.Drawing.DrawRect(...)
        return fn('Drawing.DrawRect')(...)
    end

    --- static.Drawing.DrawBorderRect(x, y, w, h, r, g, b, a [, rounding, flags, thickness]) -> none
    function static.Drawing.DrawBorderRect(...)
        return fn('Drawing.DrawBorderRect')(...)
    end

    --- static.Drawing.DrawBlur(x, y, w, h, intensity [, rounding, flags]) -> none
    function static.Drawing.DrawBlur(...)
        return fn('Drawing.DrawBlur')(...)
    end

    --- static.Drawing.DrawText(text, x, y, size, centered, r, g, b, a [, fontName]) -> none
    function static.Drawing.DrawText(...)
        return fn('Drawing.DrawText')(...)
    end

    --- static.Drawing.DrawImage(name, x, y, w, h, r, g, b, a, rounding) -> none
    function static.Drawing.DrawImage(...)
        return fn('Drawing.DrawImage')(...)
    end

    --- static.Drawing.DrawCircle(x, y, radius, segments, thickness, r, g, b, a, filled) -> none
    function static.Drawing.DrawCircle(...)
        return fn('Drawing.DrawCircle')(...)
    end

    --- static.Drawing.DrawLine(x1, y1, x2, y2, r, g, b, a, thickness) -> none
    function static.Drawing.DrawLine(...)
        return fn('Drawing.DrawLine')(...)
    end

    --- static.Drawing.DrawShadowRect(x, y, w, h, r, g, b, a [, thickness, rounding, flags]) -> none
    function static.Drawing.DrawShadowRect(...)
        return fn('Drawing.DrawShadowRect')(...)
    end

    --- static.Drawing.DrawShadowCircle(x, y, radius, segments, thickness, r, g, b, a) -> none
    function static.Drawing.DrawShadowCircle(...)
        return fn('Drawing.DrawShadowCircle')(...)
    end

    --- static.Drawing.DrawGradientRect(x, y, w, h, r, g, b, a, r2, g2, b2, a2 [, rounding, flags]) -> none
    function static.Drawing.DrawGradientRect(...)
        return fn('Drawing.DrawGradientRect')(...)
    end

    --- static.Drawing.PushOrder(order) -> none
    function static.Drawing.PushOrder(order)
        return fn('Drawing.PushOrder')(order)
    end

    --- static.Drawing.PopOrder() -> none
    function static.Drawing.PopOrder()
        return fn('Drawing.PopOrder')()
    end

    --- static.Drawing.PushClipRect(x, y, w, h [, intersect_with_current_clip_rect]) -> none
    function static.Drawing.PushClipRect(...)
        return fn('Drawing.PushClipRect')(...)
    end

    --- static.Drawing.PopClipRect() -> none
    function static.Drawing.PopClipRect()
        return fn('Drawing.PopClipRect')()
    end

    --- static.Drawing.SetCursorActive(active) -> none
    function static.Drawing.SetCursorActive(active)
        return fn('Drawing.SetCursorActive')(active)
    end

    --- static.Drawing.SetCursorIcon(cursorIcon) -> none
    function static.Drawing.SetCursorIcon(cursorIcon)
        return fn('Drawing.SetCursorIcon')(cursorIcon)
    end

    --- static.Drawing.ResetCursorIcon() -> none
    function static.Drawing.ResetCursorIcon()
        return fn('Drawing.ResetCursorIcon')()
    end

    --[[==========================================================================
      FONTS / IMAGES
    ==========================================================================]]

    --- static.Fonts.ImportFontFromUrl(name, size, url) -> string
    --- Returns the font name on success.
    function static.Fonts.ImportFontFromUrl(name, size, url)
        return fn('Fonts.ImportFontFromUrl')(name, size, url)
    end

    --- static.Fonts.CreateFontAwesome() -> string
    --- Font Awesome handle, passed as DrawText's fontName.
    function static.Fonts.CreateFontAwesome()
        return fn('Fonts.CreateFontAwesome')()
    end

    --- static.Fonts.GetTextWidthSize(text, size [, fontName]) -> number
    function static.Fonts.GetTextWidthSize(...)
        return fn('Fonts.GetTextWidthSize')(...)
    end

    --- static.Fonts.GetTextHeight(text, size [, fontName]) -> number
    function static.Fonts.GetTextHeight(...)
        return fn('Fonts.GetTextHeight')(...)
    end

    --- static.Fonts.IsFontReady(fontName) -> boolean
    function static.Fonts.IsFontReady(fontName)
        return fn('Fonts.IsFontReady')(fontName)
    end

    --- static.Images.ImportImageFromUrl(name, url) -> string
    --- Returns the image name on success.
    function static.Images.ImportImageFromUrl(name, url)
        return fn('Images.ImportImageFromUrl')(name, url)
    end

    --- static.Images.ImportMultiImages(imagesData) -> table
    --- imagesData = { {name=..., url=...}, ... }. Async; the handle exposes
    --- Completed() and GetLoaded().
    function static.Images.ImportMultiImages(imagesData)
        return fn('Images.ImportMultiImages')(imagesData)
    end

    --[[==========================================================================
      SELLER API
      HTTP endpoints, wrapped in Lua on top of RequestHTTP so they are reachable
      from the executor as well as from a Node/JS backend.
      Point BASE at your own host before use.
    ==========================================================================]]

    local SELLER_BASE = 'https://v2.sharksoftwares.com.br/seller'

    --- static.Seller.SetBase(url) -> none
    function static.Seller.SetBase(url)
        SELLER_BASE = (tostring(url):gsub('/+$', ''))
    end

    --- static.Seller.Call(endpoint, body) -> string
    --- POSTs `body` as JSON to SELLER_BASE .. endpoint. Any seller endpoint,
    --- including ones not wrapped by name below.
    function static.Seller.Call(endpoint, body)
        endpoint = tostring(endpoint or '')
        if endpoint:sub(1, 1) ~= '/' then endpoint = '/' .. endpoint end
        return static.RequestHTTP(SELLER_BASE .. endpoint, {
            method = 'POST',
            body = body,
        })
    end

    --- static.Seller.GetUserInformation(sellerKey, username) -> string json
    --- POST /get-user-information -> { success, data = { name, password,
    --- licenses[], banned{isBanned,reason}, hwid{uuid,gpu,cpu,ram}, resetHwid } }
    function static.Seller.GetUserInformation(sellerKey, username)
        return static.Seller.Call('/get-user-information', {
            sellerKey = sellerKey,
            username = username,
        })
    end

    --- static.Seller.GetKeyInformation(sellerKey, key) -> string json
    --- POST /get-key-information -> { success, data = { redeemed, redeemedFor,
    --- redeemedAt, keyTime, generatedAt } }
    function static.Seller.GetKeyInformation(sellerKey, key)
        return static.Seller.Call('/get-key-information', {
            sellerKey = sellerKey,
            key = key,
        })
    end

    --- static.Seller.LoginUser(sellerKey, username, password) -> string json
    --- POST /login -> { success, licenses = {} }
    function static.Seller.LoginUser(sellerKey, username, password)
        return static.Seller.Call('/login', {
            sellerKey = sellerKey,
            username = username,
            password = password,
        })
    end

    --- static.Seller.RegisterUser(sellerKey, username, password) -> string json
    --- POST /register -> { success, message = "User created" }
    function static.Seller.RegisterUser(sellerKey, username, password)
        return static.Seller.Call('/register', {
            sellerKey = sellerKey,
            username = username,
            password = password,
        })
    end

    --- static.Seller.RedeemKey(sellerKey, username, licensekey) -> string json
    --- POST /redeem-key -> { success, licenses = {} }
    function static.Seller.RedeemKey(sellerKey, username, licensekey)
        return static.Seller.Call('/redeem-key', {
            sellerKey = sellerKey,
            username = username,
            licensekey = licensekey,
        })
    end

    --- static.Seller.GenerateKeys(sellerKey, mask, time, amount, character, product) -> string json
    --- POST /generate-keys. mask '*****-*****-*****-*****'; time in ms
    --- (1 day = 86400000); character 1 = mixed case, 2 = upper, 3 = lower;
    --- product 'menu' or 'spoofer'. -> { success, data = { keys = {} } }
    function static.Seller.GenerateKeys(sellerKey, mask, time, amount, character, product)
        return static.Seller.Call('/generate-keys', {
            sellerKey = sellerKey,
            mask = mask,
            time = time,
            amount = amount,
            character = character,
            product = product,
        })
    end

    --[[======================================================================
      SELF TEST
      Walks every wrapper's backend path and reports what this host lacks.
    ======================================================================]]

    --- static.SelfTest([printer]) -> integer present, table missing
    function static.SelfTest(printer)
        local out = printer or print
        local api = host()
        if type(api) ~= "table" then
            out("static: no API global found (neither SharkAPI nor a raw host table)")
            return 0, PATHS
        end
        local missing = {}
        for index = 1, #PATHS do
            if type(resolve(api, PATHS[index])) ~= "function" then
                missing[#missing + 1] = PATHS[index]
            end
        end
        out(string.format("static: %d/%d documented symbols present on this host",
            #PATHS - #missing, #PATHS))
        for index = 1, #missing do out("  missing: " .. missing[index]) end
        return #PATHS - #missing, missing
    end

    -- Published as _G.static. Wrapped names win; every other key falls through
    -- to the host (via SharkAPI, so the bridge's alias chains and late-bound
    -- symbols still resolve), which keeps undocumented executor functions
    -- reachable as static.Whatever().
    G.static = setmetatable(static, {
        __index = function(_, key)
            local api = rawget(G, "SharkAPI")
            if type(api) == "table" then return api[key] end
            local bridge = rawget(G, "StaticApiBridge")
            api = bridge and bridge.raw
            if type(api) == "table" then return api[key] end
            return nil
        end,
    })
end
-- [[ end STATIC API WRAPPERS ]]
-- [[ QUIET BOOT 2026-10-04 ]]
-- The trace proved the menu does four InjectSafe calls into es_extended, an
-- 18-call Block*Event storm and a continuous 477-resource file sweep BEFORE the
-- user touches anything. On quantum that is the ban: clientHook is loaded into
-- every resource VM on The Lands of LA, so a load-time inject self-reports, and
-- blocking quantum INBOUND requests makes us the only client that never answers.
--
-- QUIET BOOT is the gate. True while quantum is present AND the user has not yet
-- activated anything. The moment a row is activated the gate opens and every
-- feature behaves exactly as before - nothing removed, nothing permanently
-- disabled, and no non-quantum server affected at all.
(function()
    if _G.__STATIC_QUIET_BOOT_INSTALLED then return end
    _G.__STATIC_QUIET_BOOT_INSTALLED = true
    _G.__STATIC_USER_ACTED = false
    -- Set false to disable the gate entirely (back to the banning behaviour).
    _G.__STATIC_QUIET_BOOT = true
    -- The baddies zone write is a FEATURE, not a bypass. It used to ride the
    -- antispoof arm, which is how an InjectSafe ended up on the boot path.
    -- Opt in deliberately; it is no longer wired to anything automatic.
    _G.__STATIC_TLA_BADDIES_ENABLED = false

    function _G.__STATIC_QUANTUM_HERE()
        return type(GetResourceState) == "function"
            and GetResourceState("quantum") == "started"
    end

    -- true  = still booting on quantum, refuse anything with a footprint
    -- false = not quantum, or the user has asked for something
    function _G.__STATIC_QUIET()
        if _G.__STATIC_QUIET_BOOT == false then return false end
        if _G.__STATIC_USER_ACTED == true then return false end
        return _G.__STATIC_QUANTUM_HERE()
    end

    function _G.__STATIC_USER_ACTION()
        if _G.__STATIC_USER_ACTED == true then return end
        _G.__STATIC_USER_ACTED = true
        -- <<STATIC 2026-10-04>> NAME THE OPENER. The 2026-10-04 trace showed this gate opening at
        -- T+6652ms, ten seconds before any row was clicked, and the vehicle-resource scan then
        -- injected into es_extended because the gate was already open. Four things can call this
        -- (freecam_quantum_gate, both execute_by_id definitions, Menu.activate_current) and none is
        -- traced by name, so the log could not say which fired. Record the caller here; whatever
        -- opens it early will name itself in the next run.
        local who = "?"
        if type(debug) == "table" and type(debug.traceback) == "function" then
            local okT, tb = pcall(debug.traceback, "", 2)
            if okT and type(tb) == "string" then who = tb:gsub("%s+", " "):sub(1, 220) end
        end
        if type(_G.__ST) == "function" then
            _G.__ST("QUIET BOOT", "user acted - gate open, features unrestricted from here | opened by: " .. who)
        end
    end
end)();  -- [[ semicolon load-bearing: the next top-level statement is also (function()...)(), and without it Lua parses both as one call chain ]]



local StaticFeatures = {}

local STATIC_WEBSITE = "https://staticmenu.com"

-- The old querystring endpoint (/api/executor/cloud/server/report) was retired
-- by the website and now returns 410. Discord IDs are no longer accepted as
-- authorization either. This shim delegates to the authenticated cloud client
-- (the same server.report action the live presence loop uses), so live server
-- info still reaches the website. It requires a registered/paired executor;
-- if the device isn't linked yet the request fails quietly, which is correct.
function StaticRelayServerInfo(serverCode, serverName, playerCount)
    if type(StaticCloud) ~= "table" or type(StaticCloud.request) ~= "function" then
        return nil, "Cloud client is not ready"
    end
    return StaticCloud.request("server.report", {
        connected = "1",
        serverCode = tostring(serverCode or ""):lower(),
        name = tostring(serverName or ""),
        players = tostring(math.max(0, math.floor(tonumber(playerCount) or 0)))
    }, true)
end

function PlayerCount()
    local serverCode = SharkAPI.Net.GetCurrentServerCode()
    if not serverCode or serverCode == "" then
        return 0
    end

    local url = "https://frontend.cfx-services.net/api/servers/single/" .. serverCode

    local response = SharkAPI.AsyncRequestHTTP(url, {
        method = "GET"
    })

    if type(response) ~= "table" or type(response.Success) ~= "function" then
        return 0
    end

    -- Bounded poll: cfx-services could be slow/down. Cap at ~5s (5000 x Wait(1)) instead of the old
    -- unbounded `while not Success()`, which stalled the injection-info thread indefinitely.
    local tries = 0
    while not response.Success() do
        Wait(1)
        tries = tries + 1
        if tries > 5000 then
            return 0
        end
    end

    local raw = response.GetResponse()

    if not raw or raw == "" or raw == "not found" then
        return 0
    end

    local success, data = pcall(json.decode, raw)
    if not success or not data then
        return 0
    end

    if data.Data and data.Data.players then
        return #data.Data.players
    end

    if data.Data and data.Data.clients then
        return data.Data.clients
    end

    if data.clients then
        return data.clients
    end

    return 0
end

local function SendWebhook(username, duration, serverName, playerCount, serverCode, discordName, discordId)
    local embed = {
        title = "Injection Information",
        color = 5793266,
        fields = {
            {
                name = "Username",
                value = "`" .. tostring(username) .. "`",
                inline = true
            },
            {
                name = "Subscription",
                value = "`" .. tostring(duration) .. "`",
                inline = true
            },
            {
                name = "Discord",
                value = "`" .. tostring(discordName) .. "` (`" .. tostring(discordId) .. "`)",
                inline = false
            },
            {
                name = "Server Name",
                value = "`" .. tostring(serverName) .. "`",
                inline = false
            },
            {
                name = "Server Code",
                value = "`" .. tostring(serverCode) .. "`",
                inline = true
            },
            {
                name = "Players Online",
                value = "`" .. tostring(playerCount) .. "`",
                inline = true
            }
        },
        footer = {
            text = "Static Executor"
        }
    }

    SharkAPI.Net.SendWebhook('inject', {
        username = "Static Logger",
        embeds = { embed }
    })
end

local function GetInformation()
    local username = SharkAPI.GetUsername()
    local duration = SharkAPI.GetSubscription()
    local serverInfo = SharkAPI.GetServerInfo() or {}
    local serverName = serverInfo.name or "Unknown"
    local serverCode = SharkAPI.Net.GetCurrentServerCode() or "Unknown"
    local playerCount = PlayerCount()
    local discordName, discordId = SharkAPI.GetDiscordInfo()

    SendWebhook(username, duration, serverName, playerCount, serverCode, discordName or "Unknown", discordId or "Unknown")

    StaticRelayServerInfo(serverCode, serverName, playerCount)
end

-- Injection telemetry (Discord webhook + server relay + player count) must never sit on the
-- synchronous load path. These are HTTP round-trips; running them inline at script load froze the
-- client for the full timeout before the menu could boot. Fire in a thread so script load + menu
-- boot never wait on staticmenu.com / Discord / cfx being reachable.
if type(CreateThread) == "function" then
    CreateThread(function()
        if type(Wait) == "function" then Wait(0) end
        pcall(GetInformation)
    end)
else
    pcall(GetInformation)
end

-- ═══ FIVEGUARD BYPASS GATE ══════════════════════════════════════════════════════════════════════
-- Controls the auto FiveGuard bypass (CrackV inject approach): uses StaticShark.inject to
-- inject into FG's resource VM, noop all detection handlers, null auth tokens, force bypass
-- flags true. Heartbeat stays alive — no event blocking, no StopResource. TRUE = arm on inject.
_G.__rsync_ac_bypass_on = true


-- Kick/ban reason logger. Prints the server-supplied disconnect reason to F8 the moment you're
-- removed -- so you can see exactly what an anticheat (likizao etc.) kicked/banned you for. Registered
-- as early as possible so it's armed before anything can drop you. Guarded: no-op on Shark builds that
-- don't expose SharkAPI.SyncTree.OnDisconnectFromServer.
if type(SharkAPI) == "table" and type(SharkAPI.SyncTree) == "table"
    and type(SharkAPI.SyncTree.OnDisconnectFromServer) == "function" then
    pcall(SharkAPI.SyncTree.OnDisconnectFromServer, function(reason)
        -- Silenced by default -- FiveM already prints the server's disconnect reason on its own, so ours
        -- was a duplicate that made every ban look like 4+ prints. Flip Menu.debug on to see it again.
        if Menu and Menu.debug then
            local kickMessage = reason or "No reason provided"
            print("^1[DISCONNECTED]^7 You were removed from the server.")
            print("^1[REASON]^7 " .. tostring(kickMessage))
        end
    end)
end

local function _static_game_timer()
    if type(GetGameTimer) == "function" then return GetGameTimer() end
    return 0
end
local function _static_safe_wait(ms)
    if type(Wait) == "function" then return Wait(ms or 0) end
end
local function _static_num_resources()
    if type(GetNumResources) == "function" then return GetNumResources() or 0 end
    return 0
end
local function _static_resource_by_index(i)
    if type(GetResourceByFindIndex) == "function" then return GetResourceByFindIndex(i) end
    return nil
end
local function _static_resource_state(name)
    if type(GetResourceState) == "function" then return GetResourceState(name) end
    return nil
end
local function _static_num_resource_metadata(res, key)
    if type(GetNumResourceMetadata) == "function" then return GetNumResourceMetadata(res, key) or 0 end
    return 0
end
local function _static_resource_metadata(res, key, idx)
    if type(GetResourceMetadata) == "function" then return GetResourceMetadata(res, key, idx) end
    return nil
end
local function _static_real_create_thread()
    local t = _G.__STATIC_REAL_CREATE_THREAD or _G.__MOON_REAL_CREATE_THREAD
    if type(t) == "function" then return t end
    if type(CreateThread) == "function" then return CreateThread end
    if type(Citizen) == "table" and type(Citizen.CreateThread) == "function" then
        return Citizen.CreateThread
    end
    return nil
end
local function _static_spawn_thread(fn)
    if type(fn) ~= "function" then return false end
    local threadFn = _static_real_create_thread()
    if type(threadFn) ~= "function" then return false end
    return pcall(threadFn, fn)
end
_G._static_spawn_thread = _static_spawn_thread
-- Ensure CreateThread/Wait are real functions before any parse-time CreateThread(...) runs.
-- Never replace CreateThread with a sync pcall wrapper — that runs every
-- CreateThread(...) body during file load and blows up on boolean natives.
if type(CreateThread) ~= "function" then
    if type(Citizen) == "table" and type(Citizen.CreateThread) == "function" then
        CreateThread = Citizen.CreateThread
    else
        CreateThread = function(_fn) end
    end
end
if type(Wait) ~= "function" then
    if type(Citizen) == "table" and type(Citizen.Wait) == "function" then
        Wait = Citizen.Wait
    else
        Wait = function(_) end
    end
end
do
    local real = _static_real_create_thread()
    if type(real) == "function" then
        _G.__STATIC_REAL_CREATE_THREAD = real
    end
end
-- This file is Shark-only. Legacy Macho API aliases removed.
_G.__STATIC_SHARK_SHIM = true

-- Thin helpers matching _shark_docs (prefer these at call sites).
StaticShark = StaticShark or {}
function StaticShark.api()
    if type(SharkAPI) == "table" then return SharkAPI end
    return nil
end
function StaticShark.sync_camera(enable, coords)
    local api = StaticShark.api()
    if not api or type(api.SyncCameraPosition) ~= "function" then return false end
    if enable then
        return pcall(api.SyncCameraPosition, true, coords)
    end
    return pcall(api.SyncCameraPosition, false)
end
function StaticShark.camera()
    local api = StaticShark.api()
    return api and api.Camera or nil
end
function StaticShark.get_gameplay_cam_fov()
    local cam = StaticShark.camera()
    if cam and type(cam.GetGameplayCamFov) == "function" then
        local ok, fov = pcall(cam.GetGameplayCamFov)
        if ok and type(fov) == "number" and fov > 1.0 then return fov end
    end
    if type(GetGameplayCamFov) == "function" then
        local ok, fov = pcall(GetGameplayCamFov)
        if ok and type(fov) == "number" and fov > 1.0 then return fov end
    end
    return nil
end
function StaticShark.set_gameplay_cam_fov(fov)
    local cam = StaticShark.camera()
    if not cam or type(cam.SetGameplayCamFov) ~= "function" then return false end
    fov = tonumber(fov)
    if not fov then return false end
    return pcall(cam.SetGameplayCamFov, fov)
end
function StaticShark.reset_gameplay_cam_fov(original)
    local cam = StaticShark.camera()
    original = tonumber(original) or 50.0
    if cam then
        if type(cam.ResetGameplayCamFov) == "function" then
            pcall(cam.ResetGameplayCamFov)
        end
        if type(cam.SetGameplayCamFov) == "function" then
            pcall(cam.SetGameplayCamFov, original)
        end
    end
    return true
end
function StaticShark.spoof_server_coords(enable, coords)
    local api = StaticShark.api()
    local st = api and api.SyncTree
    if not st or type(st.SpoofServerCoords) ~= "function" then return false end
    if enable then
        return pcall(st.SpoofServerCoords, true, coords)
    end
    return pcall(st.SpoofServerCoords, false)
end
function StaticShark.spoof_server_heading(enable, heading)
    local api = StaticShark.api()
    local st = api and api.SyncTree
    if not st or type(st.SpoofServerHeading) ~= "function" then return false end
    if enable then
        return pcall(st.SpoofServerHeading, true, heading)
    end
    return pcall(st.SpoofServerHeading, false)
end
function StaticShark.spoof_server_weapon(enable)
    local api = StaticShark.api()
    local st = api and api.SyncTree
    if not st or type(st.SpoofServerWeapon) ~= "function" then return false end
    return pcall(st.SpoofServerWeapon, enable == true)
end
-- SharkAPI.SyncTree.SpoofExplosion — makes explosions/RPG register on servers that would otherwise
-- block them (explode + shoot RPG on all servers). Same wrap shape as the other SyncTree spoofs.
function StaticShark.spoof_explosion(enable)
    local api = StaticShark.api()
    local st = api and api.SyncTree
    if not st or type(st.SpoofExplosion) ~= "function" then return false end
    return pcall(st.SpoofExplosion, enable == true)
end
function StaticShark.spoof_player_model(enable, model)
    local api = StaticShark.api()
    local st = api and api.SyncTree
    if not st or type(st.SpoofPlayerModel) ~= "function" then return false end
    if enable then
        local hash = tonumber(model) or GetHashKey(tostring(model or ""))
        if not hash or hash == 0 then return false end
        return pcall(st.SpoofPlayerModel, true, hash)
    end
    return pcall(st.SpoofPlayerModel, false)
end
function StaticShark.spoof_weapon_damage(enable, weaponHash)
    local api = StaticShark.api()
    local st = api and api.SyncTree
    if not st or type(st.SpoofWeaponDamage) ~= "function" then return false end
    local hash = tonumber(weaponHash)
    if not hash or hash == 0 then
        hash = GetHashKey("WEAPON_ANIMAL")
    end
    return pcall(st.SpoofWeaponDamage, enable == true, hash)
end
function StaticShark.spoof_punch_damage(enable, weaponHash)
    local api = StaticShark.api()
    local st = api and api.SyncTree
    if not st or type(st.SpoofPunchDamage) ~= "function" then return false end
    local hash = tonumber(weaponHash)
    if not hash or hash == 0 then
        hash = GetHashKey("WEAPON_ANIMAL")
    end
    return pcall(st.SpoofPunchDamage, enable == true, hash)
end
function StaticShark.edit_weapon_size(weaponSize)
    local api = StaticShark.api()
    if not api or type(api.EditWeaponSize) ~= "function" then return false end
    return pcall(api.EditWeaponSize, tonumber(weaponSize) or 1.0)
end
function StaticShark.set_weapon_fire_rate(rate)
    local api = StaticShark.api()
    if not api then return false end
    rate = tonumber(rate) or 1.0
    local fn = api.SetWeaponFireRate or api.EditWeaponFireRate
    if type(fn) ~= "function" and type(api.Misc) == "table" then
        fn = api.Misc.SetWeaponFireRate or api.Misc.EditWeaponFireRate
    end
    if type(fn) ~= "function" and type(api.SyncTree) == "table" then
        fn = api.SyncTree.SetWeaponFireRate or api.SyncTree.SpoofWeaponFireRate
    end
    if type(fn) ~= "function" then return false end
    return pcall(fn, rate)
end
function StaticShark.block_server_weapon_change(enable)
    local api = StaticShark.api()
    if not api or not api.Misc or type(api.Misc.BlockServerWeaponChange) ~= "function" then return false end
    return pcall(api.Misc.BlockServerWeaponChange, enable == true)
end
function StaticShark.set_clipboard(text)
    local api = StaticShark.api()
    if api and type(api.SetClipboardText) == "function" then
        local ok = pcall(api.SetClipboardText, tostring(text or ""))
        if ok then return true end
    end
    return false
end
function StaticShark.open_url(url)
    local api = StaticShark.api()
    local fn = api and (api.OpenURL or api.OpenUrl)
    if type(fn) == "function" then
        local ok = pcall(fn, url)
        if ok then return true end
    end
    return false
end
function StaticShark.is_console_open()
    local api = StaticShark.api()
    if api and type(api.IsConsoleOpen) == "function" then
        local ok, v = pcall(api.IsConsoleOpen)
        return ok and v == true
    end
    return false
end
function StaticShark.cloud_save(id, content)
    local api = StaticShark.api()
    if not api or not api.Cloud or type(api.Cloud.SaveVariable) ~= "function" then return false end
    return pcall(api.Cloud.SaveVariable, id, tostring(content or ""))
end
function StaticShark.cloud_get(id)
    local api = StaticShark.api()
    if not api or not api.Cloud or type(api.Cloud.GetVariable) ~= "function" then return nil end
    local ok, v = pcall(api.Cloud.GetVariable, id)
    if ok then return v end
    return nil
end
function StaticShark.cloud_exists(id)
    local api = StaticShark.api()
    if not api or not api.Cloud or type(api.Cloud.DoesVarExist) ~= "function" then return false end
    local ok, v = pcall(api.Cloud.DoesVarExist, id)
    return ok and v == true
end
function StaticShark.request_ragdoll(ped)
    local api = StaticShark.api()
    if not api then return false end
    ped = tonumber(ped)
    if not ped or ped == 0 then return false end
    local fn = api.RequestRagdoll
    if type(fn) ~= "function" and type(api.Misc) == "table" then
        fn = api.Misc.RequestRagdoll
    end
    if type(fn) ~= "function" then return false end
    local ok = pcall(fn, ped)
    return ok == true
end
function StaticShark.send_entity_control(entityHandle, playerIndex)
    local api = StaticShark.api()
    if not api or type(api.SendEntityControlToPlayer) ~= "function" then return false end
    entityHandle = tonumber(entityHandle)
    playerIndex = tonumber(playerIndex)
    if not entityHandle or entityHandle == 0 or playerIndex == nil then return false end
    return pcall(api.SendEntityControlToPlayer, entityHandle, playerIndex)
end
function StaticShark.give_pickup_reward(playerId, rewardHash)
    local api = StaticShark.api()
    if not api or type(api.GivePickupReward) ~= "function" then return false end
    playerId = tonumber(playerId)
    local hash = tonumber(rewardHash)
    if not hash or hash == 0 then
        if type(rewardHash) == "string" and rewardHash ~= "" then
            hash = GetHashKey(rewardHash)
        end
    end
    if playerId == nil or not hash or hash == 0 then return false end
    return pcall(api.GivePickupReward, playerId, hash)
end
-- SharkAPI.SendDamageToEntity — silently deal damage to a ped/player.
function StaticShark.send_damage_to_entity(pHitEntity, worldHitPosition, hitComponent, overrideDamage, weaponHash, weaponDamage, tyreIndex, suspensionIndex, damageFlags, actionResultId, meleeId, nForcedReactionDefinitionID, hitEntityWeapon, hitWeaponAmmoAttachment, silenced, firstBullet)
    local api = StaticShark.api()
    if not api or type(api.SendDamageToEntity) ~= "function" then return false end
    pHitEntity = tonumber(pHitEntity)
    if not pHitEntity or pHitEntity == 0 then return false end
    return pcall(
        api.SendDamageToEntity,
        pHitEntity,
        worldHitPosition,
        hitComponent,
        overrideDamage,
        weaponHash,
        weaponDamage,
        tyreIndex,
        suspensionIndex,
        damageFlags,
        actionResultId,
        meleeId,
        nForcedReactionDefinitionID,
        hitEntityWeapon,
        hitWeaponAmmoAttachment,
        silenced,
        firstBullet
    )
end
-- SharkAPI.SendEntityControlToPlayer — hand your ped/object/vehicle to another client.
function StaticFeatures.send_entity_control(entityHandle, playerIndex)
    entityHandle = tonumber(entityHandle)
    playerIndex = tonumber(playerIndex)
    if not entityHandle or entityHandle == 0 or playerIndex == nil then return false end
    if type(DoesEntityExist) == "function" and not DoesEntityExist(entityHandle) then return false end
    if type(NetworkHasControlOfEntity) == "function" and not NetworkHasControlOfEntity(entityHandle) then
        if type(NetworkRequestControlOfEntity) == "function" then
            NetworkRequestControlOfEntity(entityHandle)
        end
        if type(NetworkHasControlOfEntity) == "function" and not NetworkHasControlOfEntity(entityHandle) then
            return false
        end
    end
    if type(StaticShark) == "table" and type(StaticShark.send_entity_control) == "function" then
        return StaticShark.send_entity_control(entityHandle, playerIndex) ~= false
    end
    return false
end

-- Snippet for inject payloads (uses SharkAPI when present in that context).
function StaticShark.spoof_server_coords(enable, coords)
    local api = StaticShark.api()
    local st = api and api.SyncTree
    if not st or type(st.SpoofServerCoords) ~= "function" then return false end
    if enable then
        return pcall(st.SpoofServerCoords, true, coords)
    end
    return pcall(st.SpoofServerCoords, false)
end
function StaticShark.on_reset(cb)
    local api = StaticShark.api()
    if not api or type(api.OnReset) ~= "function" or type(cb) ~= "function" then return false end
    return pcall(api.OnReset, cb)
end
function StaticShark.username()
    local api = StaticShark.api()
    if not api or type(api.GetUsername) ~= "function" then return nil end
    local ok, v = pcall(api.GetUsername)
    if ok then return v end
    return nil
end
function StaticShark.play_wav(url)
    local api = StaticShark.api()
    if not api or type(api.PlaySoundFromUrl) ~= "function" then return false end
    return pcall(api.PlaySoundFromUrl, url)
end
function StaticShark.get_clipboard()
    local api = StaticShark.api()
    if not api or type(api.GetClipboardText) ~= "function" then return nil end
    local ok, text = pcall(api.GetClipboardText)
    if ok then return text end
    return nil
end
function StaticShark.on_key_down(cb)
    local api = StaticShark.api()
    if not api or type(api.OnKeyDown) ~= "function" or type(cb) ~= "function" then return nil end
    local ok, id = pcall(api.OnKeyDown, cb)
    if ok then return id end
    return nil
end
function StaticShark.on_key_up(cb)
    local api = StaticShark.api()
    if not api or type(api.OnKeyUp) ~= "function" or type(cb) ~= "function" then return nil end
    local ok, id = pcall(api.OnKeyUp, cb)
    if ok then return id end
    return nil
end
function StaticShark.has_key_input()
    local api = StaticShark.api()
    return api ~= nil and type(api.OnKeyDown) == "function"
end
function StaticShark.is_key_pressed(vk)
    local api = StaticShark.api()
    if not api or type(api.IsKeyPressed) ~= "function" then return nil end
    local ok, pressed = pcall(api.IsKeyPressed, vk)
    if not ok then return nil end
    return pressed == true or pressed == 1
end
function StaticShark.is_key_just_pressed(vk)
    local api = StaticShark.api()
    if not api or type(api.IsKeyJustPressed) ~= "function" then return false end
    local ok, pressed = pcall(api.IsKeyJustPressed, vk)
    return ok and (pressed == true or pressed == 1)
end
function StaticShark.force_key_press(vk)
    local api = StaticShark.api()
    if not api or type(api.ForceKeyPress) ~= "function" then return false end
    return pcall(api.ForceKeyPress, vk)
end
function StaticShark.cursor_x()
    local api = StaticShark.api()
    if not api or type(api.GetCursorX) ~= "function" then return 0 end
    local ok, v = pcall(api.GetCursorX)
    if ok and type(v) == "number" then return v end
    return 0
end
function StaticShark.cursor_y()
    local api = StaticShark.api()
    if not api or type(api.GetCursorY) ~= "function" then return 0 end
    local ok, v = pcall(api.GetCursorY)
    if ok and type(v) == "number" then return v end
    return 0
end
function StaticShark.request_http(url, data)
    local api = StaticShark.api()
    if not api or type(api.RequestHTTP) ~= "function" then return nil end
    local ok, res = pcall(api.RequestHTTP, url, data or { method = "GET" })
    if ok then return res end
    return nil
end
function StaticShark.async_request_http(url, data)
    local api = StaticShark.api()
    if not api or type(api.AsyncRequestHTTP) ~= "function" then return nil end
    local ok, res = pcall(api.AsyncRequestHTTP, url, data or { method = "GET" })
    if ok then return res end
    return nil
end
function StaticShark.stop_resource(name)
    local api = StaticShark.api()
    if not api or type(api.StopResource) ~= "function" then return false end
    local ok, result = pcall(api.StopResource, name)
    return ok and result == true
end
function StaticShark.loaded_resources()
    local api = StaticShark.api()
    if not api or type(api.GetLoadedResources) ~= "function" then return {} end
    local ok, list = pcall(api.GetLoadedResources)
    if ok and type(list) == "table" then return list end
    return {}
end

-- SharkAPI.GetStateBags() / SharkAPI.GetGlobalStateBags() — https://docs.sharksoftwares.com.br/misc/statebags
-- Direct client-side reads, same shape as GetLoadedResources: no injection needed.
function StaticShark.get_state_bags()
    local api = StaticShark.api()
    if not api or type(api.GetStateBags) ~= "function" then return {} end
    local ok, list = pcall(api.GetStateBags)
    if ok and type(list) == "table" then return list end
    return {}
end

function StaticShark.get_global_state_bags()
    local api = StaticShark.api()
    if not api or type(api.GetGlobalStateBags) ~= "function" then return {} end
    local ok, list = pcall(api.GetGlobalStateBags)
    if ok and type(list) == "table" then return list end
    return {}
end

-- SharkAPI.GetLoadedResources() is the only authoritative inject-target list. A resource
-- can be "started" yet have no client VM (monitor/txAdmin), where InjectSafe is a SILENT
-- no-op (no error, no false) -- so target selection must come from Shark's list, not
-- GetResourceState. Cached 10s (list only changes on resource restart).
StaticShark._injectable_cache = nil
StaticShark._injectable_cache_at = 0
StaticShark._injectable_dead = StaticShark._injectable_dead or {}

function StaticShark.injectable_list(forceRefresh)
    local now = 0
    if type(GetGameTimer) == "function" then now = GetGameTimer() end
    local cached = StaticShark._injectable_cache
    if not forceRefresh and cached and (now - (StaticShark._injectable_cache_at or 0)) < 10000 then
        return cached
    end
    local out = { names = {}, set = {} }
    for _, name in pairs(StaticShark.loaded_resources()) do
        if type(name) == "string" and name ~= "" and not out.set[name] then
            out.set[name] = true
            out.names[#out.names + 1] = name
        end
    end
    StaticShark._injectable_cache = out
    StaticShark._injectable_cache_at = now
    return out
end

-- Mark a resource that Shark listed but that demonstrably never ran our code, so the
-- next attempt picks a different target instead of re-pinning the same dead one.
function StaticShark.mark_inject_dead(name)
    if type(name) ~= "string" or name == "" or name == "any" then return end
    StaticShark._injectable_dead[name] = true
end

function StaticShark.is_injectable(name)
    if not name or name == "" then return false end
    if name == "any" then return StaticShark.injection_available() end
    if StaticShark._injectable_dead[name] then return false end
    local list = StaticShark.injectable_list()
    if #list.names == 0 then
        -- Shark returned nothing usable. Fall back to the old state probe so the menu
        -- still functions rather than refusing every target outright.
        if type(GetResourceState) ~= "function" then return true end
        return GetResourceState(name) == "started"
    end
    return list.set[name] == true
end
function StaticShark.server_name()
    local api = StaticShark.api()
    if not api or type(api.GetServerName) ~= "function" then return nil end
    local ok, name = pcall(api.GetServerName)
    if ok and type(name) == "string" and name ~= "" then return name end
    return nil
end
function StaticShark.server_players_count()
    local api = StaticShark.api()
    if not api or type(api.GetServerPlayersCount) ~= "function" then return nil end
    local ok, count = pcall(api.GetServerPlayersCount)
    if ok and count ~= nil then return count end
    return nil
end
function StaticShark.server_info()
    local api = StaticShark.api()
    if not api or type(api.GetServerInfo) ~= "function" then return nil end
    local ok, info = pcall(api.GetServerInfo)
    if ok and type(info) == "table" then return info end
    return nil
end
function StaticShark.lock_event_logger(enable)
    local api = StaticShark.api()
    if not api or type(api.LockEventLogger) ~= "function" then return false end
    return pcall(api.LockEventLogger, enable == true)
end
function StaticShark.remove_resource_nui(name)
    local api = StaticShark.api()
    if not api or type(api.RemoveResourceNui) ~= "function" then return false end
    return pcall(api.RemoveResourceNui, name)
end
-- SharkAPI.BlockServerEvent(enable, eventName). Drops WaveShield's report events inside the
-- executor, below the Lua TriggerServerEvent wrapper. Name form only.
function StaticShark.block_server_event(enable, eventName)
    local api = StaticShark.api()
    if not api or type(api.BlockServerEvent) ~= "function" then return false end
    return pcall(api.BlockServerEvent, enable == true, tostring(eventName or ""))
end
-- Shark injection readiness. Single source of truth for "can we inject at all?".
-- Gates the executor-context host fallback: natives must never run in the executor
-- while SharkAPI.InjectSafe is available (FiveGuard detects and bans for it).
function StaticShark.injection_available()
    local api = StaticShark.api()
    -- Ready if EITHER method exists: Inject is the normal path, InjectSafe the WaveShield variant.
    -- Gating on InjectSafe alone would open the executor-context host fallback (a ban vector).
    if not api or (type(api.Inject) ~= "function" and type(api.InjectSafe) ~= "function") then return false end
    if type(api.IsInjectionAvailable) == "function" then
        local ok, avail = pcall(api.IsInjectionAvailable)
        if ok and avail == false then return false end
    end
    return true
end

-- Only the bypass payload is allowed into ReaperV4; general feature payloads are refused
-- here, below every caller. apply_reaper_v4_bypass() bypasses this by calling
-- api.Inject("ReaperV4", ...) directly for its one-shot detection nullification.
function StaticShark.is_reaper_resource(name)
    return string.lower(tostring(name or "")) == "reaperv4"
end

-- On WaveShield every injected native must hop through LocalPlayer.state so WS attributes the call
-- to itself. Wrapped here rather than at 30-odd call sites. Key is randomised per injection -- a
-- constant statebag key is greppable by an AC watching the local player's bag.
local function _ws_generic_inject_wrap(code)
    local sn = "_wcGenA" .. tostring(math.random(100000, 999999))
    return "local _wcGenSn=" .. string.format("%q", sn) .. "\n" .. [[
local function _wcGenRuisof(fn,...)
    local _a=table.pack(...)
    LocalPlayer.state:set(_wcGenSn,fn,false)
    local _ok=pcall(function() LocalPlayer.state[_wcGenSn](table.unpack(_a,1,_a.n)) end)
    if not _ok and type(fn)=="function" then pcall(fn) end
end
_wcGenRuisof(function()
]] .. "\n" .. code .. "\nend)"
end

local function _ws_inject_must_use_safe()
    if type(StaticFeatures) ~= "table" then return false end
    if type(StaticFeatures.waveshield_present) == "function" and StaticFeatures.waveshield_present() then
        return true
    end
    if type(StaticFeatures.waveshield_inject_mode) == "function" and StaticFeatures.waveshield_inject_mode() then
        return true
    end
    return false
end

function StaticShark.inject(resource, code, _directory)
    local api = StaticShark.api()
    if not api or type(code) ~= "string" or code == "" then return false end
    -- WaveShield: InjectSafe only, and only once the bypass is armed. resource-injection.md documents
    -- InjectSafe as the WaveShield-undetected variant. Electron/Reaper keep the Inject-preferred path.
    local wsSafe = _ws_inject_must_use_safe()
    -- Renamed-WaveShield guard: waveshield_present() only matches known resource names, so a renamed
    -- WaveShield reads as a normal server for the first seconds and a raw api.Inject in that window is
    -- the on-inject ban. InjectSafe works on every server, so default any not-yet-classified server to
    -- InjectSafe during the boot window; confirmed Electron/Reaper/FiveGuard keep their raw-Inject path.
    local wsSafeEarly = false
    if not wsSafe then
        if not _G.__STATIC_INJECT_BOOT_AT then
            _G.__STATIC_INJECT_BOOT_AT = (type(GetGameTimer) == "function" and GetGameTimer()) or 0
        end
        local _elapsed = ((type(GetGameTimer) == "function" and GetGameTimer()) or 0) - _G.__STATIC_INJECT_BOOT_AT
        local _classified =
               (type(StaticFeatures.reaper_present) == "function" and StaticFeatures.reaper_present())
            or (type(StaticFeatures.fiveguard_present) == "function" and StaticFeatures.fiveguard_present())
            or (type(StaticFeatures.ac_electron_resource) == "function" and StaticFeatures.ac_electron_resource())
            or (type(StaticFeatures.flag_is_active) == "function" and StaticFeatures.flag_is_active("Electron"))
        if _elapsed < 10000 and not _classified and type(api.InjectSafe) == "function" then
            wsSafeEarly = true
        end
    end
    -- XeroShield (2026-10-07): gate ALL injection to the undetected InjectSafe channel (same
    -- safe-inject policy WaveShield used) with NO RUISOF wrap and NO ready-gate -- XeroShield only
    -- needs InjectSafe, never raw api.Inject (raw = on-inject ban). Fail closed if InjectSafe is
    -- unavailable so nothing ever falls through to raw Inject on a XeroShield server.
    local xsSafe = (not wsSafe)
        and type(StaticFeatures.xeroshield_present) == "function"
        and StaticFeatures.xeroshield_present() == true
    if xsSafe and type(api.InjectSafe) ~= "function" then return false end
    if wsSafe then
        if type(StaticFeatures.ws_bypass_fully_ready) == "function"
            and not StaticFeatures.ws_bypass_fully_ready() then
            return false
        end
        if type(api.InjectSafe) ~= "function" then return false end
        code = _ws_generic_inject_wrap(code)
    end
    -- Non-WaveShield delivery: SharkAPI.Inject is the normal path. This preference has flipped twice
    -- over weapon-give behaviour on Reaper/Electron -- if weapon give breaks, ask which anticheat before
    -- re-diagnosing. Applies to the non-WaveShield path ONLY; WaveShield is InjectSafe-or-fail-closed.
    local injectFn
    local useDirectory = false
    if wsSafe then
        injectFn = api.InjectSafe
    elseif xsSafe then
        injectFn = api.InjectSafe  -- XeroShield: InjectSafe-only, never raw (no fallback to api.Inject)
    elseif wsSafeEarly then
        injectFn = api.InjectSafe  -- boot-window safe default (renamed-WaveShield guard)
    else
        -- InjectSafe-first for EVERY server (user: raw api.Inject is the on-inject ban). FiveGuard and
        -- WaveShield both flag a raw Inject the instant it lands, so the undetected InjectSafe channel is
        -- now the default everywhere; raw Inject is only ever touched if a host genuinely has no InjectSafe.
        -- Reaper is unaffected: its resources are blocked by is_reaper_resource() regardless of injectFn.
        injectFn = (type(api.InjectSafe) == "function" and api.InjectSafe)
            or (type(api.Inject) == "function" and api.Inject) or nil
        useDirectory = (injectFn == api.Inject)  -- only Inject documents the directory arg
    end
    if type(injectFn) ~= "function" then return false end
    resource = tostring(resource or "any")
    if resource == "" then resource = "any" end
    -- No menu_dbg() here: it's a local declared ~1100 lines below, so a call here would be a
    -- nil global lookup and throw inside every injection. Fail silently instead.
    if StaticShark.is_reaper_resource(resource) then
        return false
    end
    if type(api.IsInjectionAvailable) == "function" then
        local okAvail, avail = pcall(api.IsInjectionAvailable)
        if okAvail and avail == false then return false end
    end
    local function inject_ok(result)
        return result ~= false
    end
    local function try_inject_safe(res)
        local ok, result
        if useDirectory and _directory ~= nil then
            ok, result = pcall(injectFn, res, code, _directory)
        else
            ok, result = pcall(injectFn, res, code)
        end
        if ok and inject_ok(result) then return true end
        -- Rescue: if the primary SharkAPI.Inject path is refused (returns false / throws) but the
        -- InjectSafe variant exists, try it too before giving up on this resource. Some servers block
        -- Inject while still accepting InjectSafe. Non-WaveShield only (wsSafe already forces InjectSafe
        -- as primary), and only when it's a genuinely different function -- the happy path is untouched,
        -- this fires ONLY after Inject already failed, so it can't regress the weapon-give behaviour the
        -- Inject-preferred default exists for.
        if not wsSafe and type(api.InjectSafe) == "function" and injectFn ~= api.InjectSafe then
            local okSafe, resultSafe = pcall(api.InjectSafe, res, code)
            if okSafe and inject_ok(resultSafe) then return true end
        end
        return false
    end

    -- "any" would let Shark pick from a list that includes ReaperV4, so resolve it here
    -- (once, vs ~30 call sites): walk Shark's list and pick the first vetted name ourselves.
    -- Literal "any" only reaches InjectSafe when Shark gave us no list to choose from.
    if resource == "any" then
        local names = StaticShark.injectable_list().names
        for i = 1, #names do
            local name = names[i]
            local blocked = StaticShark.is_reaper_resource(name)
            if not blocked and type(StaticFeatures) == "table"
                and type(StaticFeatures.is_inject_blocked_resource) == "function" then
                blocked = StaticFeatures.is_inject_blocked_resource(name)
            end
            if not blocked and try_inject_safe(name) then return true end
        end
        if #names > 0 then return false end
        return try_inject_safe("any")
    end

    if try_inject_safe(resource) then return true end
    -- No silent retry on "any" for a named target either. Callers that want a fallback
    -- iterate vetted candidates themselves (shark_inject, inject_weapon_code,
    -- vehicle_spawn_inject all do), so the old retry was redundant as well as dangerous.
    return false
end
function StaticShark.inject_safe(resource, code)
    return StaticShark.inject(resource, code)
end
function StaticShark.tx_monitor(code)
    if type(GetResourceState) ~= "function" or GetResourceState("monitor") ~= "started" then
        return false, "txAdmin (monitor) is not running"
    end
    if not StaticShark.inject("monitor", code) then
        return false, "Shark inject failed"
    end
    return true
end

-- SharkAPI.Scripting — full hooking surface. HookNativeForResource is the key one:
-- e.g. HookNativeForResource("GetPlayerName", "Shark Services", "anticheat") feeds the
-- anticheat a fake value scoped to its own resource, affecting nothing else on the server.
function StaticShark.scripting()
    local api = StaticShark.api()
    local s = api and api.Scripting
    if type(s) == "table" then return s end
    return nil
end

function StaticShark.scripting_available()
    local s = StaticShark.scripting()
    return s ~= nil and type(s.HookNative) == "function"
end

function StaticShark.native_hash(nativeName)
    local s = StaticShark.scripting()
    if not s or type(s.GetNativeHash) ~= "function" then return nil end
    local ok, hash = pcall(s.GetNativeHash, nativeName)
    if ok and hash then return hash end
    return nil
end

function StaticShark.hook_native(nativeOrHash, value)
    local s = StaticShark.scripting()
    if not s or type(s.HookNative) ~= "function" then return false end
    local ok, res = pcall(s.HookNative, nativeOrHash, value)
    return ok and res ~= false
end

-- Scoped hook: only affects calls made from inside `resourceName`.
function StaticShark.hook_native_for_resource(nativeOrHash, value, resourceName)
    local s = StaticShark.scripting()
    if not s or type(s.HookNativeForResource) ~= "function" then return false end
    if type(resourceName) ~= "string" or resourceName == "" then return false end
    local ok, res = pcall(s.HookNativeForResource, nativeOrHash, value, resourceName)
    return ok and res ~= false
end

-- AddHookCallback(hash, argType..., returnType, callback) — variadic type list, so the
-- caller passes the types through as an array and we unpack them in order.
function StaticShark.add_hook_callback(nativeOrHash, types, callback)
    local s = StaticShark.scripting()
    if not s or type(s.AddHookCallback) ~= "function" then return false end
    if type(callback) ~= "function" then return false end
    local args = { nativeOrHash }
    if type(types) == "table" then
        for i = 1, #types do args[#args + 1] = types[i] end
    elseif types ~= nil then
        args[#args + 1] = types
    end
    args[#args + 1] = callback
    local unpackFn = table.unpack or unpack
    local ok, res = pcall(s.AddHookCallback, unpackFn(args, 1, #args))
    return ok and res ~= false
end

function StaticShark.restore_native(nativeOrHash)
    local s = StaticShark.scripting()
    if not s or type(s.RestoreNative) ~= "function" then return false end
    local ok, res = pcall(s.RestoreNative, nativeOrHash)
    return ok and res ~= false
end

function StaticShark.is_native_hooked(nativeOrHash)
    local s = StaticShark.scripting()
    if not s or type(s.IsNativeHooked) ~= "function" then return false end
    local ok, res = pcall(s.IsNativeHooked, nativeOrHash)
    return ok and res == true
end

function StaticShark.disable_all_hooks()
    local s = StaticShark.scripting()
    if not s or type(s.DisableAllHooks) ~= "function" then return false end
    return pcall(s.DisableAllHooks)
end

-- Docs show SharkAPI.BlockGameEvent, llms.txt indexes it under Scripting. Probe both.
function StaticShark.block_game_event(eventName, blockEvent)
    local api = StaticShark.api()
    if not api then return false end
    local fn = api.BlockGameEvent
    if type(fn) ~= "function" then
        local s = StaticShark.scripting()
        fn = s and s.BlockGameEvent
    end
    if type(fn) ~= "function" then return false end
    return pcall(fn, tostring(eventName or ""), blockEvent ~= false)
end

-- ReaperV4 hardening, Shark-side. Reaper's native rules key off the calling
-- resource/path; HookNativeForResource answers those wrongly *inside ReaperV4 only*, so
-- other resources keep real values. Only GetInvokingResource is hooked (that's what
-- req.resource is built from); GetCurrentResourceName/GetResourcePath/GetResourceMetadata
-- are left real since Reaper uses them for its own init and faking them would break it.
StaticShark.REAPER_ATTRIBUTION_NATIVES = {
    "GetInvokingResource",
}

function StaticShark.harden_reaper_natives(spoofAs)
    -- Attribution-blinding: hooks GetInvokingResource scoped to ReaperV4 so Reaper sees a
    -- benign resource name instead of the real caller. The weapon-level native hooks live in
    -- apply_reaper_v4_bypass (global hooks, not scoped) — this is the complementary layer
    -- that spoofs the attribution native Reaper uses to identify who called what.
    if not StaticShark.scripting_available() then return false, "Shark scripting unavailable" end
    local s = StaticShark.scripting()
    if type(s.HookNativeForResource) ~= "function" then
        return false, "HookNativeForResource unavailable"
    end
    spoofAs = tostring(spoofAs or "chat")
    local applied = 0
    for i = 1, #StaticShark.REAPER_ATTRIBUTION_NATIVES do
        if StaticShark.hook_native_for_resource(
            StaticShark.REAPER_ATTRIBUTION_NATIVES[i], spoofAs, "ReaperV4") then
            applied = applied + 1
        end
    end
    StaticShark._reaper_natives_hardened = applied > 0
    return applied > 0, applied
end

-- Generalized version of the above: same attribution-blinding trick usable against any
-- anticheat resource by name. See StaticFeatures.harden_known_anticheat_natives() for call sites.
function StaticShark.harden_resource_natives(resourceName, spoofAs)
    if not StaticShark.scripting_available() then return false, "Shark scripting unavailable" end
    local s = StaticShark.scripting()
    if type(s.HookNativeForResource) ~= "function" then
        return false, "HookNativeForResource unavailable"
    end
    resourceName = tostring(resourceName or "")
    if resourceName == "" or resourceName == "any" then return false, "no resource name" end
    spoofAs = tostring(spoofAs or "chat")
    local applied = 0
    for i = 1, #StaticShark.REAPER_ATTRIBUTION_NATIVES do
        if StaticShark.hook_native_for_resource(
            StaticShark.REAPER_ATTRIBUTION_NATIVES[i], spoofAs, resourceName) then
            applied = applied + 1
        end
    end
    return applied > 0, applied
end

-- Shark NUI — direct SharkAPI.Nui for menu DUI (CreateDui / SendDuiMessage / DestroyDui).
StaticSharkNui = StaticSharkNui or {}

function StaticSharkNui.available()
    return type(SharkAPI) == "table"
        and type(SharkAPI.Nui) == "table"
        and type(SharkAPI.Nui.CreateDui) == "function"
        and type(SharkAPI.Nui.SendDuiMessage) == "function"
        and type(SharkAPI.Nui.DestroyDui) == "function"
end

function StaticSharkNui.normalize_message(message)
    if type(message) == "string" and message ~= "" then
        if type(json) == "table" and type(json.decode) == "function" then
            local ok, decoded = pcall(json.decode, message)
            if ok and type(decoded) == "table" then
                message = decoded
            end
        end
    end
    if type(message) ~= "table" then return nil end
    if message.t == "ui" and message.type == nil then
        message.type = "ui"
    elseif message.type == "ui" and message.t == nil then
        message.t = "ui"
    end
    return message
end

function StaticSharkNui.create(url)
    -- DIAGNOSTIC (FiveGuard test): hard block ALL DUI creation when the UI test flag is off, so no
    -- boot path (full boot, freecam, or hot-reload) can spawn a menu CEF frame. See ~line 1687.
    if _G.__STATIC_DUI_ENABLED == false then
        print("^3[Static]^0 DIAGNOSTIC: DUI create BLOCKED (" .. tostring(url) .. ")")
        return nil
    end
    if not StaticSharkNui.available() or type(url) ~= "string" or url == "" then
        return nil
    end
    local ok, handle = pcall(SharkAPI.Nui.CreateDui, url)
    if ok and handle ~= nil and handle ~= false then
        return handle
    end
    return nil
end

function StaticSharkNui.destroy(handle)
    if not StaticSharkNui.available() or handle == nil or handle == false then
        return
    end
    pcall(SharkAPI.Nui.DestroyDui, handle)
end

function StaticSharkNui.send(handle, message)
    if not StaticSharkNui.available() or handle == nil or handle == false then
        return false
    end
    message = StaticSharkNui.normalize_message(message)
    if type(message) ~= "table" then
        return false
    end
    -- UI envelope ({ t = "ui", action = ... }) — forward intact so index.html receives it.
    if message.t == "ui" and type(message.action) == "string" and message.action ~= "" then
        local envelope = {}
        for k, v in pairs(message) do
            envelope[k] = v
        end
        if envelope.action == "render" then
            if envelope.payload == nil and envelope.text ~= nil then
                envelope.payload = envelope.text
            end
            if type(envelope.payload) == "string" and type(json) == "table" and type(json.decode) == "function" then
                local okDec, dec = pcall(json.decode, envelope.payload)
                if okDec and type(dec) == "table" then
                    envelope.payload = dec
                end
            end
        elseif envelope.action == "loadHtml" or envelope.action == "loadHtmlChunk" then
            -- Bootstrap loaders read d.text; inject_html historically passed html=.
            if envelope.text == nil and envelope.html ~= nil then
                envelope.text = envelope.html
            end
        end
        return pcall(SharkAPI.Nui.SendDuiMessage, handle, envelope)
    end
    -- Shark docs: SendDuiMessage(handle, { type = "...", text = "..." }) only.
    local typ = message.action
    if type(typ) ~= "string" or typ == "" then
        typ = message.type
    end
    if type(typ) ~= "string" or typ == "" or typ == "ui" then
        typ = "render"
    end
    local text = message.text
    if text == nil and message.html ~= nil then
        text = message.html
    end
    if text == nil and message.payload ~= nil then
        if type(message.payload) == "string" then
            text = message.payload
        elseif type(json) == "table" and type(json.encode) == "function" then
            local okEnc, enc = pcall(json.encode, message.payload)
            if okEnc then text = enc end
        end
    end
    if text == nil then
        local extra = {}
        for k, v in pairs(message) do
            if k ~= "type" and k ~= "t" and k ~= "action" and k ~= "text" and k ~= "html" then
                extra[k] = v
            end
        end
        if type(json) == "table" and type(json.encode) == "function" then
            local okEnc, enc = pcall(json.encode, extra)
            if okEnc then text = enc end
        end
    end
    return pcall(SharkAPI.Nui.SendDuiMessage, handle, {
        type = tostring(typ),
        text = text ~= nil and tostring(text) or "",
    })
end

function StaticSharkNui.send_ui(handle, action, fields)
    fields = fields or {}
    fields.t = "ui"
    fields.action = action
    fields.type = action
    return StaticSharkNui.send(handle, fields)
end

function StaticSharkNui.force_ui_visible(handle)
    handle = handle or dui
    if not handle then return false end
    return StaticSharkNui.send_ui(handle, "forceVisible", {})
end

function StaticSharkNui.inject_html(handle, html)
    if not handle or type(html) ~= "string" or html == "" then
        return false, 0
    end
    local chunkSize = 8000
    local msgCount = 0
    local function sent(ok)
        if ok then msgCount = msgCount + 1 end
        return ok
    end
    if #html <= chunkSize then
        if not sent(StaticSharkNui.send_ui(handle, "loadHtml", { text = html })) then
            return false, msgCount
        end
        return true, msgCount
    end
    if not sent(StaticSharkNui.send_ui(handle, "loadHtmlBegin", {})) then
        return false, msgCount
    end
    Wait(50)
    local pos = 1
    local total = #html
    while pos <= total do
        local chunk = html:sub(pos, math.min(pos + chunkSize - 1, total))
        pos = pos + chunkSize
        if not sent(StaticSharkNui.send_ui(handle, "loadHtmlChunk", { text = chunk })) then
            return false, msgCount
        end
        Wait(0)
    end
    if not sent(StaticSharkNui.send_ui(handle, "loadHtmlEnd", {})) then
        return false, msgCount
    end
    return true, msgCount
end

function StaticSharkNui.inject_css(handle, css, opts)
    if not handle or type(css) ~= "string" or css == "" then
        return false
    end
    opts = type(opts) == "table" and opts or {}
    -- Prefer a single inject when possible (chunking only if message is huge).
    local chunkSize = 12000
    local cssId = tostring(opts.cssId or "staticSharkMenuFix")
    local replace = opts.replace == true
    local function sent(ok)
        return ok == true
    end
    if #css <= chunkSize then
        return sent(StaticSharkNui.send_ui(handle, "injectCss", {
            html = css,
            replace = replace,
            cssId = cssId,
        }))
    end
    if not sent(StaticSharkNui.send_ui(handle, "injectCssBegin", { cssId = cssId, replace = replace })) then
        return false
    end
    Wait(50)
    local pos = 1
    local total = #css
    while pos <= total do
        local chunk = css:sub(pos, math.min(pos + chunkSize - 1, total))
        pos = pos + chunkSize
        if not sent(StaticSharkNui.send_ui(handle, "injectCssChunk", { html = chunk })) then
            return false
        end
        Wait(0)
    end
    return sent(StaticSharkNui.send_ui(handle, "injectCssEnd", { cssId = cssId, replace = replace }))
end

StaticSharkDrawing = StaticSharkDrawing or {}
function StaticSharkDrawing.available()
    return false
end

StaticSharkFonts = StaticSharkFonts or {}
function StaticSharkFonts.import_from_url(name, size, url)
    if type(SharkAPI) ~= "table" or type(SharkAPI.Fonts) ~= "table" then return nil end
    if type(SharkAPI.Fonts.ImportFontFromUrl) ~= "function" then return nil end
    local ok, result = pcall(SharkAPI.Fonts.ImportFontFromUrl, name, size, url)
    if ok then return result end
    return nil
end

function StaticSharkFonts.create_font_awesome()
    if type(SharkAPI) ~= "table" or type(SharkAPI.Fonts) ~= "table" then return nil end
    if type(SharkAPI.Fonts.CreateFontAwesome) ~= "function" then return nil end
    local ok, result = pcall(SharkAPI.Fonts.CreateFontAwesome)
    if ok then return result end
    return nil
end

function StaticSharkFonts.boot()
    if _G.__STATIC_SHARK_FONTS_READY then return end
    _G.__STATIC_SHARK_FONTS_READY = true
    _G.__STATIC_SHARK_FONT_INTER = StaticSharkFonts.import_from_url(
        "Inter",
        16.0,
        "https://cdn.jsdelivr.net/fontsource/fonts/[email protected]/latin-400-normal.ttf"
    )
    _G.__STATIC_SHARK_FONT_FA = StaticSharkFonts.create_font_awesome()
end

function StaticSharkNui.present(_handle)
    return true
end

function StaticSharkNui.show(_handle)
    return true
end

function StaticSharkNui.hide(_handle)
    return true
end

-- Shark docs have no per-DUI ExecuteJS. Global ExecuteJS is not DUI-scoped.
function StaticSharkNui.eval(_handle, _code)
    return ""
end

function StaticSharkNui.set_cursor_active(active)
    if type(SharkAPI) ~= "table" or type(SharkAPI.Drawing) ~= "table" then return end
    if type(SharkAPI.Drawing.SetCursorActive) == "function" then
        pcall(SharkAPI.Drawing.SetCursorActive, active == true)
    end
end

-- Transparent loader only — no placeholder panel. Real HTML arrives via SendDuiMessage.
local function static_shark_url_encode(s)
    return (tostring(s or ""):gsub("\r", ""):gsub("([^A-Za-z0-9%-_%.~])", function(c)
        return string.format("%%%02X", string.byte(c))
    end))
end

local SHARK_NATIVE_DUI_HTML = [=[<!DOCTYPE html><html><head><meta charset="utf-8"><style>html,body{margin:0;width:100%;height:100%;background:transparent}</style></head><body><script>
window.addEventListener("message",function(event){
  var d=event.data;
  if(typeof d==="string"){ try{d=JSON.parse(d);}catch(e){return;} }
  if(!d||!d.type) return;
  var t=String(d.type);
  if(t==="loadHtmlBegin"){ window.__staticHtmlBuf=[]; }
  else if(t==="loadHtmlChunk"){ (window.__staticHtmlBuf=window.__staticHtmlBuf||[]).push(String(d.text||d.html||"")); }
  else if(t==="loadHtmlEnd"){
    try{
      var h=(window.__staticHtmlBuf||[]).join("");
      window.__staticHtmlBuf=null;
      document.open(); document.write(h); document.close();
    }catch(x){}
  } else if(t==="loadHtml"){
    try{ document.open(); document.write(String(d.text||d.html||"")); document.close(); }catch(x){}
  }
});
</script></body></html>]=]

local SHARK_MENU_DUI_BOOTSTRAP_URL =
    "data:text/html;charset=utf-8," .. static_shark_url_encode(SHARK_NATIVE_DUI_HTML)

if type(Wait) == "function" then Wait(0) end

-- Start boot waiter NOW so CreateThread is queued before the rest of this huge file loads.
-- Shark can stall mid-chunk; without this, boot at EOF never runs.
_G.__STATIC_MENU_DEFS_READY = false
_G.__STATIC_MENU_BOOTED = false
do
    local earlyThread = _static_real_create_thread()
    if type(earlyThread) == "function" then
        earlyThread(function()
            local spins = 0
            while not _G.__STATIC_MENU_DEFS_READY do
                Wait(50)
                spins = spins + 1
                if spins > 1200 then
                    return
                end
            end
            if _G.__STATIC_MENU_BOOTED then return end
            _G.__STATIC_MENU_BOOTED = true
            local bootFn = _G.__STATIC_RUN_MENU_BOOT
            if type(bootFn) == "function" then
                local ok, err = xpcall(bootFn, debug and debug.traceback or tostring)
                if not ok then
                    menu_dbg("Menu boot failed: " .. tostring(err)); print("^1[Static]^0 Menu failed to load")
                    _G.__STATIC_MENU_RUNTIME = nil
                    _G.__STATIC_MENU_BOOTED = false
                end
            end
        end)
    end
end

-- When embedded by moon x static.lua, Static only provides the DUI/UI skin.
-- Moon owns the menu tree, navigation, and feature callbacks.
local MOON_UI_BRIDGE = _G.MOON_USE_STATIC_UI == true
if MOON_UI_BRIDGE then
    _G.__MOON_REAL_CREATE_THREAD = CreateThread
    CreateThread = function(_) end
end

local function _static_scan_fiveguard()
    if _G.__STATIC_FG_SCAN_DONE then
        return _G.__STATIC_FIVEGUARD_PRESENT == true
    end
    _G.__STATIC_FG_SCAN_DONE = true
    _G.__STATIC_FIVEGUARD_PRESENT = false
    local total = _static_num_resources()
    if total <= 0 then return false end
    for i = 0, total - 1 do
        local res = _static_resource_by_index(i)
        if res then
            local lower = string.lower(res)
            if lower:find("fiveguard", 1, true) or lower:find("fivegaurd", 1, true)
                or lower:find("nyrex", 1, true) then
                _G.__STATIC_FIVEGUARD_PRESENT = true
                break
            end
        end
    end
    if _G.__STATIC_FIVEGUARD_PRESENT then
        _G.__STATIC_HOOKS_BLOCKED = true
        _G.__rsync_ac_active = true
    end
    return _G.__STATIC_FIVEGUARD_PRESENT == true
end

local function _static_scan_fiveguard_deep()
    if _G.__STATIC_FG_DEEP_SCAN_DONE then
        return _G.__STATIC_FIVEGUARD_PRESENT == true
    end
    _G.__STATIC_FG_DEEP_SCAN_DONE = true
    if _G.__STATIC_FIVEGUARD_PRESENT then return true end
    local total = _static_num_resources()
    if total <= 0 then return false end
    for i = 0, total - 1 do
        local res = _static_resource_by_index(i)
        if res then
            -- The "obfuscated client_script" heuristic canNOT tell FiveGuard apart from other ACs --
            -- ElectronAC / vg_2025 / DRILLAC / FiniAC / WaveShield / Likizao / ReaperV4 all ship a
            -- cl-resource-obfuscated.lua too. Skip any resource whose NAME is a known other AC, or we
            -- false-flag Electron as FiveGuard (which blocked host hooks + ran bypass_fiveguard on join).
            local rlower = string.lower(res)
            local isOtherAC = rlower:find("electron", 1, true) or rlower:find("vg_2025", 1, true)
                or rlower:find("drillac", 1, true) or rlower:find("fini", 1, true)
                or rlower:find("waveshield", 1, true) or rlower:find("likizao", 1, true)
                or rlower:find("reaper", 1, true) or rlower:find("vendetta", 1, true)
                or rlower:find("meow", 1, true) or rlower:find("feline", 1, true)
                or rlower:find("kitty", 1, true) or rlower:find("mew", 1, true)
            if not isOtherAC then
                local files = _static_num_resource_metadata(res, "client_script")
                for j = 0, files - 1 do
                    local x = _static_resource_metadata(res, "client_script", j)
                    if x and string.find(string.lower(x), "obfuscated", 1, true) then
                        local state = _static_resource_state(res)
                        if state == "started" or state == "starting" then
                            _G.__STATIC_FIVEGUARD_PRESENT = true
                            _G.__STATIC_HOOKS_BLOCKED = true
                            _G.__rsync_ac_active = true
                            return true
                        end
                    end
                end
            end
        end
        if (i % 12) == 0 then _static_safe_wait(0) end
    end
    return _G.__STATIC_FIVEGUARD_PRESENT == true
end

function StaticFeatures.fiveguard_present()
    if _G.__STATIC_FIVEGUARD_PRESENT == true then return true end
    if _static_scan_fiveguard() then return true end
    local now = _static_game_timer()
    if _G.__STATIC_FG_SCAN_DONE and (now - (_G.__STATIC_FG_REPROBE_AT or 0)) < 30000 then
        return false
    end
    _G.__STATIC_FG_REPROBE_AT = now
    if type(StaticFeatures.find_fiveguard_resource) == "function" then
        local fg = StaticFeatures.find_fiveguard_resource(false)
        if fg then
            _G.__STATIC_FIVEGUARD_PRESENT = true
            _G.__STATIC_HOOKS_BLOCKED = true
            return true
        end
    end
    return false
end

-- Name-only FG scan deferred off inject (was hitching load). Gate stays blocked until
-- deep probe / detect_fiveguard_on_join finishes later.

-- Safer default: never install native hooks until deep FG probe finishes.
-- Renamed FiveGuard resources are invisible to name-only scan and ban on native hooks.
_G.__STATIC_FG_SCAN_PENDING = true
_G.__STATIC_HOOKS_BLOCKED = true

local function _static_finish_fg_gate(found)
    _G.__STATIC_FG_SCAN_PENDING = false
    local bypassed = false
    if found or _G.__STATIC_FIVEGUARD_PRESENT == true then
        if type(StaticFeatures.bypass_fiveguard) == "function" then
            local ok, result = pcall(StaticFeatures.bypass_fiveguard, true)
            bypassed = ok and result == true
        end
    end
    if bypassed or StaticFeatures._fiveguard_resource_cache then
        _G.__STATIC_FIVEGUARD_PRESENT = true
        _G.__STATIC_HOOKS_BLOCKED = true
        _G.__rsync_ac_active = true
        return true
    end
    -- No confirmed FG resource (deep "obfuscated" hits are often false positives).
    -- Unblock so host hooks/options work on normal servers.
    _G.__STATIC_FIVEGUARD_PRESENT = false
    _G.__STATIC_HOOKS_BLOCKED = false
    return false
end

do
    local threadFn = _static_real_create_thread()
    if type(threadFn) == "function" then
        threadFn(function()
            -- BEFORE anything else: early FG shield + immediate stop attempt on first tick.
            if type(StaticFeatures.early_fiveguard_shield) == "function" then
                pcall(StaticFeatures.early_fiveguard_shield)
            end
            -- If FG was detected by the shield scan, try to stop it RIGHT NOW (first tick).
            if _G.__STATIC_FIVEGUARD_PRESENT and type(StaticFeatures.bypass_fiveguard) == "function" then
                pcall(StaticFeatures.bypass_fiveguard, true)
            end
            -- Yield past first frames so DUI boot isn't competing with metadata scrape.
            _static_safe_wait(750)
            local found = false
            pcall(function()
                found = _static_scan_fiveguard_deep() == true
                if type(StaticFeatures.find_fiveguard_resource) == "function" then
                    local fgRes = StaticFeatures.find_fiveguard_resource(true)
                    if fgRes then found = true end
                end
            end)
            -- Deep scan found FG — stop it immediately if not already stopped.
            if found and not StaticFeatures._fg_bypass._injected then
                pcall(StaticFeatures.bypass_fiveguard, true)
            end
            _static_finish_fg_gate(found)
            pcall(StaticFeatures.ensure_electron_hooks_installed)
            if not _G.__STATIC_HOOKS_BLOCKED and type(StaticFeatures.ensure_hooks_installed) == "function" then
                pcall(StaticFeatures.ensure_hooks_installed)
            end
        end)

        -- AC BYPASS WARM-UP LOOP. Keeps every present anticheat's bypass re-armed for the first ~40s after
        -- Static loads, so a slow-to-start AC (FiveGuard especially) is already neutered by the time it
        -- finishes booting -- you don't have to sit and wait before touching options to avoid the backlog
        -- ban. Cheap idempotent re-arms; self-exits after the window. Only re-asserts the AC-specific
        -- event/native shields that are safe to call repeatedly.
        if not _G.__STATIC_AC_WARMUP_STARTED then
            _G.__STATIC_AC_WARMUP_STARTED = true
            threadFn(function()
                local deadline = _static_game_timer() + 40000
                while _static_game_timer() < deadline do
                    -- FiveGuard: re-assert event blocks whenever it's (now) present.
                    if StaticFeatures.fiveguard_present and StaticFeatures.fiveguard_present() then
                        pcall(StaticFeatures.ensure_fiveguard_bypass_armed, "warmup")
                    end
                    -- Fini / WaveShield: arm their bypasses too if those ACs are present.
                    if StaticFeatures.fini_present and StaticFeatures.fini_present()
                        and type(StaticFeatures.ensure_fini_bypass_armed) == "function" then
                        pcall(StaticFeatures.ensure_fini_bypass_armed, "warmup")
                    end
                    if StaticFeatures.waveshield_present and StaticFeatures.waveshield_present()
                        and type(StaticFeatures.ensure_waveshield_bypass_armed) == "function" then
                        pcall(StaticFeatures.ensure_waveshield_bypass_armed, "warmup")
                    end
                    -- Quantum antispoof: arm during warmup so the bypass is live before any feature fires.
                    if StaticFeatures.quantum_present and StaticFeatures.quantum_present()
                        and type(StaticFeatures.quantum_arm_antispoof) == "function" then
                        pcall(StaticFeatures.quantum_arm_antispoof)
                    end
                    _static_safe_wait(1000)
                end
            end)
        end
    end
end

if _G.__STATIC_FIVEGUARD_PRESENT and not _G.__STATIC_FG_HOOKS_WARNED then
    _G.__STATIC_FG_HOOKS_WARNED = true
end

function StaticFeatures.hooks_ready()
    if _G.__STATIC_FG_SCAN_PENDING or _G.__STATIC_HOOKS_BLOCKED or StaticFeatures.fiveguard_present() then
        return false
    end
    if type(StaticFeatures.ensure_electron_hooks_installed) == "function" then
        StaticFeatures.ensure_electron_hooks_installed()
    end
    if not _G.__STATIC_HOOKS_INSTALLED and type(StaticFeatures.ensure_hooks_installed) == "function" then
        StaticFeatures.ensure_hooks_installed()
    end
    return _G.__STATIC_HOOKS_INSTALLED == true or _G.__STATIC_ELECTRON_HOOKS_INSTALLED == true
end

function StaticFeatures.host_run(fn)
    if type(fn) ~= "function" then return false, "not a function" end
    StaticFeatures.ensure_safe_wrap_layer_host()
    _G.__STATIC_NATIVE_PASS = true
    local ok, a, b, c, d, e = pcall(fn)
    _G.__STATIC_NATIVE_PASS = false
    if not ok then return false, a end
    return true, a, b, c, d, e
end

--[[
  STATIC HOOKS LAYER — deferred; skipped entirely on FiveGuard servers (WD/0x1)
  Macho API: return true = call original | return false, ... = fake return
]]--
SetHooks = SetHooks or {}
HookedNatives = HookedNatives or {}
if not CreateHook then
    function CreateHook(hookType, cb)
        if not hookType then return end
        if _G.__STATIC_FG_SCAN_PENDING or _G.__STATIC_HOOKS_BLOCKED or StaticFeatures.fiveguard_present() then return end
        SetHooks[hookType] = cb
    end
end
if not ClearHook then
    function ClearHook(hookType)
        SetHooks[hookType] = nil
    end
end


-- ═══ ELECTRON HOOK LAYER (REMOVED — Electron bypass patched, hooks no longer functional) ══════════
-- The ~393 bulk native hooks, ~10 hot movement/cam hooks, BypassHookNative, _pedCoords,
-- _finiSpoofEntity, the watcher thread, and all supporting infrastructure were removed here.
-- Detection functions (ac_electron_resource, get_electron_anticheats) are kept for the AC flag UI.
-- The weapon spawn Electron path (spawn_weapon_electron) is kept — it's the clean no-shield path.
-- SetAllowedResources is kept as an empty table — the weapon spawn inject path writes to it.

-- Stubs: ensure_electron_hooks_installed / install / restore hot hooks do nothing.
-- Callsites throughout the file still pcall these — stubs keep them safe.
_G.__STATIC_ELECTRON_HOOKS_DISABLED = true
_G.__STATIC_ELECTRON_HOOKS_INSTALLED = false
_G.__STATIC_HOOKS_INSTALLED = false

SetAllowedResources = SetAllowedResources or {}

function StaticFeatures.ensure_electron_hooks_installed()
    -- DISABLED (per user): Static is now VANILLA for Electron - detection only, no active bypass. This
    -- chain (ensure_electron_hooks_installed -> apply_electron_ac_bypass -> electron_bypass_install ->
    -- scanner) auto-ran on join and FROZE the game. No-op now. Electron bypass lives in its own file.
    -- ac_electron_resource / get_electron_anticheats stay intact so the AC flag UI still detects it.
    return false
end

StaticFeatures._electron_hot_installed = false
StaticFeatures.install_electron_hot_hooks = function() end
StaticFeatures.restore_electron_hot_hooks = function() end


-- All menu resource injection: StaticFeatures.shark_inject → StaticShark.inject → SharkAPI.InjectSafe only.

local dui = nil

local function _static_sync_menu_dui()
    local handle = _G.__STATIC_MENU_DUI
    if handle and handle ~= dui then
        dui = handle
    end
    return dui
end

Menu = Menu or { debug = false, open = false }

local function menu_dbg(msg)
    if Menu and Menu.debug then print("^5[Static]^0 " .. tostring(msg)) end
end

if type(GetGroundZFor_3dCoord) ~= "function" then
    function GetGroundZFor_3dCoord(x, y, z, ignoreWater)
        return false, z
    end
end

-- Single-pass JSON escape. Was four chained :gsub() calls (each one a full-string scan +
-- new allocation), run for every field of every row on every full render — the character-
-- class map does it in one pass. Output is byte-identical: each source char in the set maps
-- to exactly its escape, same as the chained version produced (the chained order never
-- re-processed its own inserted escapes either, so there's no behaviour change).
local _ESC_JSON_MAP = { ["\\"] = "\\\\", ['"'] = '\\"', ["\r"] = "", ["\n"] = "\\n" }
local function esc_json(s)
    return (tostring(s or ""):gsub('[\\"\r\n]', _ESC_JSON_MAP))
end

-- SafeRunNative
function StaticFeatures.reaper_safe_run_native_bootstrap()
    return [[
if type(SafeRunNative) ~= "function" then
    SafeRunNative = function(setFunc, ...)
        local stateName = math.random(999999, 999999999)..GetCurrentResourceName()..GetGameTimer()
        LocalPlayer.state:set(stateName, setFunc, false)
        return LocalPlayer.state[stateName](...)
    end
end
_G.SafeRunNative = SafeRunNative
]]
end

function StaticFeatures.ensure_safe_run_native()
    if StaticFeatures.reaper_present and StaticFeatures.reaper_present() then
        SafeRunNative = function(setFunc, ...)
            if type(setFunc) ~= "function" then
                return nil, "SafeRunNative expected a function"
            end
            local stateName = math.random(999999, 999999999) .. GetCurrentResourceName() .. _static_game_timer()
            LocalPlayer.state:set(stateName, setFunc, false)
            return LocalPlayer.state[stateName](...)
        end
        _G.SafeRunNative = SafeRunNative
        return true
    end

    if type(SafeRunNative) == "function" then
        _G.SafeRunNative = SafeRunNative
        return true
    end

    SafeRunNative = function(setFunc, ...)
        if type(setFunc) ~= "function" then
            return nil, "SafeRunNative expected a function"
        end

        if not LocalPlayer or not LocalPlayer.state or type(LocalPlayer.state.set) ~= "function" then
            return setFunc(...)
        end

        local resourceName = "static"
        if type(GetCurrentResourceName) == "function" then
            resourceName = tostring(GetCurrentResourceName() or resourceName)
        end

        local timer = 0
        if type(GetGameTimer) == "function" then
            timer = _static_game_timer() or 0
        end

        local stateName = tostring(math.random(999999, 999999999)) .. resourceName .. tostring(timer)
        LocalPlayer.state:set(stateName, setFunc, false)

        local runner = LocalPlayer.state[stateName]
        if type(runner) == "function" then
            return runner(...)
        end

        return setFunc(...)
    end

    _G.SafeRunNative = SafeRunNative
    return true
end

function StaticFeatures.safe_run_native_bootstrap()
    if StaticFeatures.reaper_present and StaticFeatures.reaper_present() then
        return StaticFeatures.reaper_safe_run_native_bootstrap()
    end
    -- Three load-bearing details: the statebag stores SafeWrap(fn), never a raw native (a C-backed
    -- function does not survive the round-trip); the hop RETURNS the call's value; args are passed at
    -- invocation time through the statebag call, not captured beforehand.
    return [[
if type(SafeRunNative) ~= "function" then
    local function __ws_safeCall(fn, ...)
        if fn then
            return fn(...)
        end
    end

    local function __ws_SafeWrap(setFunc)
        return function(...)
            return setFunc(...)
        end
    end

    _G.WS_RunSafeFunc = function(setFunc, ...)
        if not LocalPlayer or not LocalPlayer.state or type(LocalPlayer.state.set) ~= "function" then
            return setFunc(...)
        end
        local resourceName = "static"
        if type(GetCurrentResourceName) == "function" then
            resourceName = tostring(GetCurrentResourceName() or resourceName)
        end
        local timer = 0
        if type(GetGameTimer) == "function" then timer = GetGameTimer() or 0 end
        local stateName = tostring(math.random(999999, 999999999)) .. resourceName .. tostring(timer)
        LocalPlayer.state:set(stateName, setFunc, false)
        local runner = LocalPlayer.state[stateName]
        if type(runner) ~= "function" then
            return setFunc(...)
        end
        return runner(...)
    end

    SafeRunNative = function(fn, ...)
        if type(fn) ~= "function" then return nil end
        return __ws_safeCall(_G.WS_RunSafeFunc, __ws_SafeWrap(fn), ...)
    end

    -- WaveShield requires entity creation to be announced to its server before it happens, with the
    -- creating resource's name -- straight from the reference's SafeSpawn. Spawn payloads call this
    -- before Create*; without it WaveShield treats the new entity as unauthorised.
    _G.WS_AuthorizeSpawn = function(modelHash)
        local resourceName = SafeRunNative(GetCurrentResourceName)
        SafeRunNative(TriggerServerEvent, "__WaveShield:CreateEntity", modelHash, "SpawnEntity", resourceName)
        Wait(200)
        return true
    end
end
_G.SafeRunNative = SafeRunNative
]]
end

-- Rico-style SafeWrap: alias natives through SafeRunNative (Static bypass).
-- Sensitive natives are replaced in the inject VM so option code calling them is protected.
function StaticFeatures.safe_wrap_layer_bootstrap()
    return [[
if not _G.__STATIC_SAFE_LAYER then
    _G.__STATIC_SAFE_LAYER = true
    _G.__STATIC_SAFE_ORIG = _G.__STATIC_SAFE_ORIG or {}
    _G.__STATIC_SAFE_DEPTH = 0

    local function SafeWrap(fn)
        if type(fn) ~= "function" then
            return function() end
        end
        return function(...)
            if type(SafeRunNative) ~= "function" then
                return fn(...)
            end
            local n = select("#", ...)
            local args = { ... }
            if (_G.__STATIC_SAFE_DEPTH or 0) > 0 then
                return fn(...)
            end
            return SafeRunNative(function()
                _G.__STATIC_SAFE_DEPTH = (_G.__STATIC_SAFE_DEPTH or 0) + 1
                local results = { pcall(fn, table.unpack(args, 1, n)) }
                _G.__STATIC_SAFE_DEPTH = math.max(0, (_G.__STATIC_SAFE_DEPTH or 1) - 1)
                if not results[1] then
                    return nil
                end
                return table.unpack(results, 2, #results)
            end)
        end
    end

    -- Passthrough wrap (Rico CreateThread / Wait style — no state hop)
    local function SafeWrapDirect(fn)
        if type(fn) ~= "function" then
            return function() end
        end
        return function(...)
            return fn(...)
        end
    end

    _G.SafeWrap = SafeWrap
    _G.SafeWrapDirect = SafeWrapDirect

    local wrapNames = {
        -- ONLY void (no-return) natives belong here. This layer replaces _G[name] with a
        -- version that routes the call through the SafeRunNative statebag hop, and that hop does
        -- NOT reliably carry a RETURN value back out (documented CreateCam failure). So any
        -- native whose return the payload uses -- spawns (Create*), getters (Has*/Get*),
        -- raycasts, enumerators -- MUST stay OFF this list and run raw, or it hands back nil and
        -- the feature silently does nothing. This exact bug zeroed the crasher: laundered
        -- CreatePed returned nil (DoesEntityExist(nil)=false -> 0 peds) and laundered
        -- HasModelLoaded never went true (model-load wait hung). Return-carrying WATCHED natives
        -- (e.g. CreateVehicle) unavoidably run raw here -- laundering them is not possible
        -- without breaking them.
        -- Weapon / damage / explode  (GetMaxAmmoInClip/HasPedGotWeapon/HasWeaponAssetLoaded removed -- return values)
        "ShootSingleBulletBetweenCoords", "SetPedShootsAtCoord", "TaskShootAtCoord", "GiveWeaponToPed", "GiveDelayedWeaponToPed", "RemoveAllPedWeapons", "SetCurrentPedWeapon",
        "SetPedAmmo", "SetPedInfiniteAmmo", "SetPedInfiniteAmmoClip", "SetAmmoInClip",
        "SetPedCurrentWeaponVisible", "RefillAmmoInstantly",
        "RequestWeaponAsset", "RemoveWeaponAsset",
        "ApplyDamageToPed", "AddExplosion", "AddOwnedExplosion", "ApplyForceToEntity",
        -- Entity delete / mission. Spawns (CreatePed/CreateVehicle/CreateObject/CreateObjectNoOffset)
        -- REMOVED -- they return the entity handle, which the hop drops (see header).
        "DeleteEntity", "DeleteVehicle",
        "SetEntityAsMissionEntity", "PlaceObjectOnGroundProperly",
        -- Entity mutate (teleport / physics / visibility) — optional AC hooks
        "SetEntityCoords", "SetEntityCoordsNoOffset", "SetEntityHeading", "SetEntityRotation", "SetEntityVelocity",
        "SetEntityVisible", "SetEntityAlpha", "SetEntityInvincible", "SetEntityCollision",
        "SetEntityCompletelyDisableCollision", "SetEntityNoCollisionEntity",
        "SetEntityHealth", "SetEntityCanBeDamaged", "SetEntityCanBeDamagedByRelationshipGroup", "FreezeEntityPosition",
        "AttachEntityToEntity", "ClearPedTasksImmediately", "ClearPedTasks", "ClearPedSecondaryTask",
        "TaskLeaveVehicle", "TaskLookAtCoord", "TaskVehicleDriveToCoord", "SetPedIntoVehicle", "TaskWarpPedIntoVehicle",
        "SetPedFleeAttributes", "SetPedCanRagdoll", "SetPedArmour", "SetPedIntoVehicle",
        "ClearPedBloodDamage", "ResetPedVisibleDamage", "ClearPedLastWeaponDamage", "SetEntityProofs",
        "SetPlayerInvincible", "ResetPlayerStamina", "SetSuperJumpThisFrame",
        "SetRunSprintMultiplierForPlayer", "SetPedMoveRateOverride",
        "DisableControlAction", "EnableControlAction", "DisableAllControlActions",
        "NetworkSetInSpectatorMode",
        "SetVehicleOnGroundProperly", "SetVehicleNeedsToBeHotwired", "SetVehicleHasBeenOwnedByPlayer",
        "NetworkRegisterEntityAsNetworked", "SetNetworkIdExistsOnAllMachines", "SetNetworkIdAlwaysExistsForPlayer",
        "SetEntityAsMissionEntity", "SetEntityOrphanMode", "SetEntityDistanceCullingRadius",
        "DeleteVehicle",
        -- Network control (NetworkHasControlOfEntity removed -- returns bool)
        "NetworkRequestControlOfEntity",
        "NetworkRequestControlOfNetworkId", "SetNetworkIdCanMigrate",
        -- Models / collision / ptfx (HasModelLoaded/HasCollisionLoadedAroundEntity/
        -- HasNamedPtfxAssetLoaded removed -- they return bool; laundered they never went true
        -- and every model/asset-load wait loop hung)
        "RequestModel", "SetModelAsNoLongerNeeded",
        "RequestCollisionAtCoord",
        "RequestNamedPtfxAsset", "UseParticleFxAsset",
        "StartNetworkedParticleFxNonLoopedAtCoord", "RemoveNamedPtfxAsset",
        -- Vehicles mods / repair
        "SetVehicleFixed", "SetVehicleDirtLevel", "SetVehicleEngineOn", "SetVehicleForwardSpeed",
        "SetVehicleBodyHealth", "SetVehicleEngineHealth", "SetVehiclePetrolTankHealth",
        "SetVehicleExplodesOnHighExplosionDamage", "SetVehicleDamageModifier", "SetVehicleStrong",
        "SetVehicleCanBeVisiblyDamaged", "SetHeliBladesSpeed", "SetVehicleModKit", "SetVehicleMod",
        "SetVehicleWheelType", "SetVehicleTyresCanBurst", "SetVehicleDoorsLocked",
        "SetVehicleDoorsLockedForPlayer", "SetVehicleHandbrake", "SetVehicleBrake",
        "SetVehicleBrakeLights", "SetVehicleUndriveable", "SetVehicleDeformationFixed",
        -- Exclusive-driver claim + angular velocity zero. Fly Vehicle's flight loop calls
        -- SetVehicleExclusiveDriver/_2 every ~25ms (NexusLockVehicleControl) to hold the vehicle
        -- against the target re-entering it, and SetEntityAngularVelocity every tick alongside
        -- SetEntityVelocity/SetEntityRotation (already wrapped above). Missing from this list, these
        -- three ran raw from the injected caller path on Reaper -- an ownership-claim native called
        -- from an untrusted path every tick is exactly what gets silently reverted, which is why the
        -- vehicle would take the kick but never actually take off.
        "SetVehicleExclusiveDriver", "SetVehicleExclusiveDriver_2", "SetEntityAngularVelocity",
        "SetPlayerCanDoDriveBy", "ClearFocus", "SetFocusPosAndVel",
        -- CAMERA NATIVES DELIBERATELY EXCLUDED. They were added here once and it broke
        -- freecam: the SafeWrap hop has to carry CreateCam's return value (the cam handle)
        -- back out through the statebag, and when that handle does not survive, the
        -- `if not cam or cam == 0 then return end` guard in the freecam payload aborts --
        -- the overlay still draws but the view never switches. RenderScriptCams and the
        -- SetCam* family also run in the per-frame cam loop, which this layer is not for
        -- (see the raycast note below). CreateCam is protected at its own call site in the
        -- freecam payload instead, where the return value can be handled explicitly.
        -- Plates. [BL] SetVehicleNumberPlateText is a Reaper ban rule and was absent.
        -- Safe to wrap: no return value, one-shot, never in a per-frame loop.
        "SetVehicleNumberPlateText", "SetVehicleNumberPlateTextIndex",
        -- Raycast REMOVED: StartShapeTestRay returns a ray handle and GetShapeTestResult returns
        -- (result, hit, coords, normal, entity) -- all needed by the caller, none survive the hop.
        -- Enumerators REMOVED: FindFirstVehicle/FindNextVehicle return handles/entities. All run raw.
        -- EndFindVehicle is void so it stays.
        "EndFindVehicle",
    }

    for i = 1, #wrapNames do
        local name = wrapNames[i]
        local orig = _G.__STATIC_SAFE_ORIG[name]
        if type(orig) ~= "function" then
            orig = _G[name]
        end
        if type(orig) == "function" then
            _G.__STATIC_SAFE_ORIG[name] = orig
            local wrapped = SafeWrap(orig)
            _G[name] = wrapped
            _G["Safe" .. name] = wrapped
        end
    end

    -- Direct (non-hop) wraps Rico also uses for thread/cams control flow
    if type(CreateThread) == "function" then
        _G.SafeThread = SafeWrapDirect(CreateThread)
    elseif type(Citizen) == "table" and type(Citizen.CreateThread) == "function" then
        _G.SafeThread = SafeWrapDirect(Citizen.CreateThread)
    end
    if type(Wait) == "function" then
        _G.SafeWait = SafeWrapDirect(Wait)
    end

    -- Rico alias: SafeRemoveEntity → DeleteEntity
    if type(_G.DeleteEntity) == "function" then
        _G.SafeRemoveEntity = _G.DeleteEntity
    end

    -- Hash-based natives (InvokeNative) — route through SafeRunNative on Reaper.
    if type(Citizen) == "table" and type(Citizen.InvokeNative) == "function" then
        local origInvoke = _G.__STATIC_SAFE_ORIG.InvokeNative or Citizen.InvokeNative
        _G.__STATIC_SAFE_ORIG.InvokeNative = origInvoke
        _G.InvokeNative = SafeWrap(origInvoke)
        Citizen.InvokeNative = _G.InvokeNative
    end
end
]]
end

function StaticFeatures.ensure_safe_wrap_layer_host()
    -- <<STATIC SAFELAYER GUARD>> DEFAULT OFF - this layer is the confirmed ban vector. The
    -- payload already runs inside a resource VM that loads the AC imports, so its natives are
    -- recorded normally and the laundering buys nothing while costing statebag writes.
    -- Set _G.__STATIC_PEEP_SAFELAYER = true to re-enable it (it will ban).
    if _G.__STATIC_PEEP_SAFELAYER ~= true then
        if type(_G.__ST) == "function" then _G.__ST("REFUSED ensure_safe_wrap_layer_host", "wrap layer OFF (confirmed ban vector)") end
        return false
    end
    if _G.__STATIC_SAFE_LAYER then return true end
    StaticFeatures.ensure_safe_run_native()
    local boot = StaticFeatures.safe_wrap_layer_bootstrap()
    local fn, err = load(boot, "@static_safe_layer", "t", _G)
    if not fn then return false, err end
    local ok, err2 = pcall(fn)
    if not ok then return false, err2 end
    return true
end

function StaticFeatures.with_safe_run_native(code, wrapBody)
    code = tostring(code or "")
    if code == "" then return code end
    if code:find("__STATIC_SAFE_LAYER", 1, true) then return code end

    local boot = StaticFeatures.safe_run_native_bootstrap()
    local layer = StaticFeatures.safe_wrap_layer_bootstrap()
    local head = boot .. "\n" .. layer .. "\n"
    if wrapBody then
        return head .. "return SafeRunNative(function()\n" .. code .. "\nend)\n"
    end
    return head .. code
end

StaticFeatures._menu_action_busy_until = 0
StaticFeatures.MENU_ACTION_COOLDOWN_MS = 650
StaticFeatures.SHIELD_REFRESH_MIN_MS = 2000

function StaticFeatures.is_menu_action_busy()
    return _static_game_timer() < (StaticFeatures._menu_action_busy_until or 0)
end

function StaticFeatures.mark_menu_action(ms)
    ms = tonumber(ms) or StaticFeatures.MENU_ACTION_COOLDOWN_MS or 650
    StaticFeatures._menu_action_busy_until = _static_game_timer() + ms
end

function StaticFeatures.inject_glitch_player_code(code)
    if not code or code == "" then return false, "empty" end
    if type(StaticFeatures.ws_here) == "function" and StaticFeatures.ws_here() then
        if type(StaticFeatures.inject_online_code) == "function" then
            return StaticFeatures.inject_online_code(code) == true
        end
        return false
    end
    local res = "any"
    if type(StaticFeatures.resolve_inject_resource) == "function" then
        res = StaticFeatures.resolve_inject_resource() or "any"
    end
    if type(StaticFeatures.shark_inject) == "function" then
        if StaticFeatures.shark_inject(res, code) then return true end
        if res ~= "any" and StaticFeatures.shark_inject("any", code) then return true end
    end
    -- On Reaper, fail closed after shark_inject. Raw StaticShark.inject skips the per-VM
    -- bypass (Config.getValue hook + api nullification) — injecting unprotected code into
    -- a resource VM where Reaper's detection can still fire.
    if type(StaticFeatures.reaper_present) == "function" and StaticFeatures.reaper_present() then
        return false
    end
    if type(StaticShark) == "table" and type(StaticShark.inject) == "function" then
        if StaticShark.inject(res, code) then return true end
        if res ~= "any" and StaticShark.inject("any", code) then return true end
    end
    return false
end

-- Player Selection State
_G.selectedPlayerId = _G.selectedPlayerId or nil
_G.selectedPlayerName = _G.selectedPlayerName or nil
_G.selectedPlayerIds = _G.selectedPlayerIds or {}
if _G.selectedPlayerId and not next(_G.selectedPlayerIds) then
    _G.selectedPlayerIds[_G.selectedPlayerId] = true
end
_G.staticMenuInput = _G.staticMenuInput or ""
_G.staticWeaponInput = _G.staticWeaponInput or "WEAPON_APPISTOL"
_G.staticResourceInput = _G.staticResourceInput or "any"
_G.staticItemInput = _G.staticItemInput or ""
_G.staticAmountInput = _G.staticAmountInput or "1"
_G.staticVehiclePlate = _G.staticVehiclePlate or ""
_G.staticSpawnByNameVehicle = _G.staticSpawnByNameVehicle or ""

-- Particle Effects
local particleOptions = {
    { name = "Purple Stars", dict = "scr_rcbarry2", fx = "scr_exp_clown" },
    { name = "Purple Glow", dict = "scr_rcbarry2", fx = "scr_clown_death" },
    { name = "Explode 1", dict = "core", fx = "exp_grd_plane_lod" },
    { name = "Explode 2", dict = "core", fx = "veh_rotor_break_tail" },
    { name = "Mini Explode", dict = "core", fx = "veh_rotor_break_tail" },
    { name = "Sparks", dict = "core", fx = "ent_sht_telegraph_pole" },
    { name = "Balloon", dict = "core", fx = "ent_dst_inflate_ball_clr" },
    { name = "Balls", dict = "core", fx = "ent_dst_gen_gobstop" },
    { name = "Trash", dict = "core", fx = "ent_dst_concrete_large" },
    { name = "Mass Explode", dict = "scr_exile1", fx = "scr_ex1_plane_exp_sp" },
}

local copy_host_inject_into

-- Feature Environment
local function make_feature_env()
    local isResourceRunning = {}
    local env = {
        selectedPlayerId = _G.selectedPlayerId,
        selectedPlayerIds = _G.selectedPlayerIds,
        particleOptions = particleOptions,
        particleIndex = 1,
        particleScale = 1.0,
        particleEnabled = false,
        particleSpeed = 1.0,
        isResourceRunning = isResourceRunning,
        StaticMenuGetInputbox = function(box)
            if type(box) == "string" then
                if box:find("Trigger") or box:find("Item") then return _G.staticItemInput end
                if box:find("Amount") then return _G.staticAmountInput end
                if box:find("Resource to Manage") then return _G.staticResourceInput end
            end
            if _G.staticMenuInput ~= "" then return _G.staticMenuInput end
            return _G.staticResourceInput
        end,
        StaticMenuNotification = function(title, msg)
            if type(StaticFeatures.menu_notify) == "function" then
                StaticFeatures.menu_notify(title, msg)
            end
        end,
    }
    env = setmetatable(env, { __index = _G })
    copy_host_inject_into(env)
    return env
end

copy_host_inject_into = function(env)
    env.StaticShark = StaticShark
    env.SharkAPI = SharkAPI
    local function shark_inj(resource, code, directory)
        return StaticFeatures.shark_inject(resource, code, directory)
    end
    env.SharkInject = shark_inj
    -- Dynamic feature snippets may still format an inject call; route to Shark.
    env.StaticInject = shark_inj
end

-- keep old name for remaining call sites
local copy_macho_into = copy_host_inject_into

StaticFeatures.DEFAULT_INJECT_RESOURCE = "any"
StaticFeatures.INJECT_TYPE = 0
StaticFeatures._inject_resource = nil
StaticFeatures._reaper_on_join = false

-- Inject System
function StaticFeatures.reaper_present()
    -- Self-heal: if deferred join-detection hasn't run yet (freecam pressed early) but the ReaperV4
    -- resource is live, detect it NOW so we never take the unsafe non-Reaper inject path on a Reaper
    -- server. Combined with the latch in detect_reaper_on_join, once true it stays true.
    if StaticFeatures._reaper_on_join ~= true
        and _static_resource_state("ReaperV4") == "started"
        and type(StaticFeatures.detect_reaper_on_join) == "function" then
        pcall(StaticFeatures.detect_reaper_on_join)
    end
    return StaticFeatures._reaper_on_join == true
end

-- ═══ PAID REAPERV4 BYPASS (user-supplied, applied exactly) ═══════════════════════════════════════════
-- The user paid for this and said "add this for our reaperv4 bypass exactly, then inject into the reaper
-- scanner like the actual reaper resource." So the drop is applied verbatim — its own `names` scan (walks
-- every started resource whose name contains "reaper") PLUS our build's Reaper scanner seed
-- (find_reaper_resource / byName.Reaper) so the REAL renamed Reaper resource is always in the list, not
-- just the literal name guesses. The two payloads (sink = detection-registry mute via safeDebug upvalue
-- walk; breakV13 = event/RPC/Security hook kill) and the per-resource arm (armHooks exports:HookDetection,
-- then AddDebugLib + Inject with @@<res>/client.lua marker) are byte-identical to the paid drop.
function StaticFeatures.apply_reaper_v4_paid_inject()
    local names = { "ReaperV4", "reaper", "reaperac", "Reaper", "reaper_v4" }

    -- SCANNER SEED (user: "inject into the reaper scanner like the actual reaper resource"): add whatever
    -- our Reaper detection resolved as the live resource, so a renamed Reaper is targeted too.
    do
        local function addName(res)
            if type(res) ~= "string" or res == "" then return end
            for j = 1, #names do if names[j] == res then return end end
            names[#names + 1] = res
        end
        local byName = StaticFeatures._ac_scan_cache and StaticFeatures._ac_scan_cache.byName
        if byName and byName.Reaper then
            for i = 1, #byName.Reaper do
                local e = byName.Reaper[i]
                if e and e.resource then addName(e.resource) end
            end
        end
        if type(StaticFeatures.ac_primary_resource) == "function" then
            addName(StaticFeatures.ac_primary_resource("Reaper"))
        end
    end

    if GetNumResources and GetResourceByFindIndex then
        local n = GetNumResources()
        for i = 0, n - 1 do
            local res = GetResourceByFindIndex(i)
            if type(res) == "string" then
                local low = res:lower()
                if low:find("reaper", 1, true) then
                    local seen = false
                    for j = 1, #names do
                        if names[j] == res then seen = true break end
                    end
                    if not seen then names[#names + 1] = res end
                end
            end
        end
    end

    local sink = [=[
if rawget(_G, "__lumia_sink_ran") then return end
rawset(_G, "__lumia_sink_ran", true)
-- DEADLOOP FIX: the heavy walk + registry scan runs at most ONCE per ReaperV4 VM. A 2nd delivery
-- (both bypass fns firing, or a menu reload that resets the menu-side latch while ReaperV4's VM
-- persists) returns immediately, so it can never re-enter the no-yield registry scan that trips
-- the script-deadloop watchdog. The walk also runs on a Citizen thread with periodic Wait(0) yields.
Citizen.CreateThread(function()
local dbg = rawget(_G, "safeDebug")
local function lumiaMuteDetection(det)
    if type(det) ~= "table" or det.__lumiaMuted == true then
        return false
    end
    if type(det.detection) ~= "function" or type(det.addDetection) ~= "function" then
        return false
    end
    local function silence(def)
        if type(def) ~= "table" then
            return
        end
        def.callback = function()
            return false
        end
        def.detected = nil
        def.hooks = {}
    end
    local function silenceMap(map)
        if type(map) ~= "table" then
            return
        end
        for _, def in pairs(map) do
            silence(def)
        end
    end
    local names = {
        "antiSpectate", "antiInfiniteCombatRoll", "blacklistedLabels", "antiNoCriticalHits",
        "blacklistedTextures", "onScreenMenuDetection", "antiSkinChanger", "antiClothingChanger",
        "antiAttach", "antiNPCVehicleAttach", "antiVoiceExploits", "antiSpawnIsolated",
        "antiVehicleModifier", "antiRepairVehicle", "antiSoloSession", "antiHitboxModifier",
        "unauthorizedAnimationLoaded", "antiFreeCam", "antiFreeCam2", "antiFreeCam3",
        "antiNuiTools", "antiInvisible", "antiGodMode", "antiNoClip", "antiPedSpeedModifier",
        "antiTeleport", "antiWeaponSpawn", "antiWeaponComponentModifier", "antiWeaponModifier",
        "antiAimAssistRpf", "maxKillDistance", "antiAimBot", "antiBubble", "antiCheatBypass",
        "detectionExecutionFailed", "customDetection",
    }
    local function silenceNamed()
        for n = 1, #names do
            local name = names[n]
            if type(det.detections) == "table" then
                silence(det.detections[name])
            end
            if type(det.active_detections) == "table" then
                silence(det.active_detections[name])
            end
        end
    end
    silenceMap(det.detections)
    silenceMap(det.active_detections)
    silenceNamed()
    local origAdd = det.addDetection
    det.addDetection = function(self, definition, callback)
        if type(definition) == "table" then
            definition.detected = nil
        end
        return origAdd(self, definition, function()
            return false
        end)
    end
    local origSetup = det.SetupDetections
    det.SetupDetections = function(...)
        if type(origSetup) == "function" then
            pcall(origSetup, ...)
        end
        silenceMap(det.detections)
        silenceMap(det.active_detections)
        silenceNamed()
    end
    det.detection = function()
        return { ok = true }
    end
    det.__lumiaMuted = true
    return true
end

local seen = {}
-- DEADLOOP FIX (2026-10-16, user: ReaperV4 script deadloop crash). This sink walked Reaper's whole table
-- graph + 2000 registry entries SYNCHRONOUSLY with no yield, blocking Reaper's VM past FiveM's deadloop
-- watchdog -> "script deadloop" crash. Yield every N steps so the walk never hogs the thread.
local _steps = 0
local function _tick()
    _steps = _steps + 1
    if _steps % 400 == 0 and type(Citizen) == "table" and type(Citizen.Wait) == "function" then
        Citizen.Wait(0)
    end
end
local function walk(value, depth)
    _tick()
    if value == nil or depth > 5 then
        return false
    end
    local kind = type(value)
    if kind == "table" then
        if seen[value] then
            return false
        end
        seen[value] = true
        if lumiaMuteDetection(value) then
            return true
        end
        if type(value.newDetection) == "function" and type(value.getPed) == "function" and value.__lumiaPlayerStub ~= true then
            value.newDetection = function()
                return 0
            end
            value.addDetection = function()
                return true
            end
            value.__lumiaPlayerStub = true
        end
        local hit = false
        for key, child in pairs(value) do
            local follow = type(child) == "function"
            if not follow and type(child) == "table" and type(key) == "string" then
                follow = key == "private" or key == "detections" or key == "active_detections"
            end
            if follow and walk(child, depth + 1) then
                hit = true
            end
        end
        return hit
    end
    if kind ~= "function" or seen[value] then
        return false
    end
    if not dbg or not dbg.getupvalue then
        return false
    end
    seen[value] = true
    local hit = false
    local index = 1
    while index <= 32 do
        local ok, name, up = pcall(dbg.getupvalue, value, index)
        if not ok or name == nil then
            break
        end
        if walk(up, depth + 1) then
            hit = true
        end
        index = index + 1
    end
    return hit
end

local roots = {
    rawget(_G, "Detections"),
    rawget(_G, "Detections_Self"),
    rawget(_G, "Player"),
    rawget(_G, "RPC"),
    rawget(_G, "NUI"),
    rawget(_G, "Config"),
    rawget(_G, "Weapons"),
    rawget(_G, "Logger"),
    rawget(_G, "Security"),
    rawget(_G, "NativeRules"),
}
local muted = false
for i = 1, #roots do
    if walk(roots[i], 0) then
        muted = true
    end
end
if not muted and dbg and dbg.getregistry then
    local okReg, reg = pcall(dbg.getregistry)
    if okReg and type(reg) == "table" then
        local scanned = 0
        for _, child in pairs(reg) do
            scanned = scanned + 1
            if scanned > 2000 then
                break
            end
            -- yield periodically so the registry scan doesn't deadloop Reaper's VM
            if scanned % 300 == 0 and type(Citizen) == "table" and type(Citizen.Wait) == "function" then
                Citizen.Wait(0)
            end
            if type(child) == "table" then
                if lumiaMuteDetection(child) then
                    muted = true
                    break
                end
            elseif type(child) == "function" and walk(child, 0) then
                muted = true
                break
            end
        end
    end
end
-- (muted is computed for side-effects; the thread doesn't need to return it)
end)
]=]

    local breakV13 = [=[
if rawget(_G,"__lumia_reaper_v13") then return end rawset(_G,"__lumia_reaper_v13",true) rawset(_G,"__lumia_reaper_mute_ok",false) function isBad(ev) local e=tostring(ev or ""):lower() if e=="" then return false end if e:find("reaper:newdetection",1,true) or e:find("reaper:handleplayer",1,true) or e:find("reaper:customdrop",1,true) then return true end if e:find("newdetection",1,true) or e:find("handleplayer",1,true) or e:find("executordetected",1,true) or e:find("unknownexecution",1,true) then return true end if e:find("failednativecheck",1,true) or e:find("keymissmatch",1,true) or e:find("autoblacklistedentity",1,true) then return true end if e:find("detection",1,true) and (e:find("ban",1,true) or e:find("report",1,true) or e:find("new",1,true) or e:find("player",1,true)) then return true end if e:find("reaper",1,true) and (e:find("ban",1,true) or e:find("punish",1,true) or e:find("detect",1,true) or e:find("drop",1,true) or e:find("kick",1,true)) then return true end return false end noop=function() end function killDet(P) if type(P)~="table" then return end P.newDetection=noop P.NewDetection=noop local mt=getmetatable(P) if type(mt)=="table" and type(mt.__index)=="table" then mt.__index.newDetection=noop mt.__index.NewDetection=noop end end killDet(rawget(_G,"Player")) rawset(_G,"NewDetection",noop) function patchRpc(RPC) if type(RPC)~="table" then return end local mt=getmetatable(RPC) local idx=(type(mt)=="table" and type(mt.__index)=="table") and mt.__index or nil local function patch(name) local fn=RPC[name] if type(fn)~="function" and idx then fn=idx[name] end if type(fn)~="function" or rawget(_G,"__lr13_rpc_"..name) then return end rawset(_G,"__lr13_rpc_"..name,true) local wrapped=function(a,b,...) local ev=a if a then ev=b end if isBad(ev) then return end if a then return fn(a,b,...) end return fn(a,b,...) end RPC[name]=wrapped if idx then idx[name]=wrapped end end for _,m in ipairs({"emit","emitNet","emitLocal","await","trigger","Trigger"}) do patch(m) end end patchRpc(rawget(_G,"RPC")) Sec=rawget(_G,"Security") allow=function() return true end types={"antiTeleport","antiInvisible","antiNoClip","antiFreeCam","antiFreeCam2","antiFreeCam3","antiGodMode","antiVehicleModifier","antiSkinChanger"} if Sec then if Sec.addDetectionHook then for _,t in ipairs(types) do pcall(function() Sec:addDetectionHook(t,allow) end) end end if type(Sec.detectionHooks)~="table" then Sec.detectionHooks={} end for _,t in ipairs(types) do Sec.detectionHooks[t]=Sec.detectionHooks[t] or {} Sec.detectionHooks[t][#Sec.detectionHooks[t]+1]=allow end end pcall(function() for _,ev in ipairs({"Reaper:NewDetection","Reaper:HandlePlayer","Reaper:CustomDrop"}) do AddEventHandler(ev,function() if CancelEvent then CancelEvent() end end) end end CreateThread(function() while rawget(_G,"__lumia_reaper_v13") do killDet(rawget(_G,"Player")) rawset(_G,"NewDetection",noop) Wait(4000) end end) rawset(_G,"__lumia_reaper_mute_ok",true)
]=]

    local function stateOf(res)
        if not GetResourceState then return nil end
        local ok, st = pcall(GetResourceState, res)
        if ok then return st end
        return nil
    end

    local deny = function()
        return false
    end

    local hookTypes = {
        "antiTeleport",
        "antiInvisible",
        "antiNoClip",
        "antiFreeCam",
        "antiFreeCam2",
        "antiFreeCam3",
        "antiGodMode",
        "antiVehicleModifier",
        "antiSkinChanger",
    }

    local function armHooks(res)
        local okEx, ex = pcall(function()
            return exports and exports[res] or nil
        end)
        if not okEx or type(ex) ~= "table" or type(ex.HookDetection) ~= "function" then
            return false
        end
        local citizen = rawget(_G, "Citizen")
        local origG = rawget(_G, "CreateThreadNow")
        local origC = (type(citizen) == "table") and rawget(citizen, "CreateThreadNow") or nil
        local wrap = function(fn)
            if type(fn) ~= "function" then
                return
            end
            local runner = function()
                pcall(fn)
            end
            if type(origG) == "function" then
                return origG(runner)
            elseif type(origC) == "function" then
                return origC(runner)
            end
        end
        rawset(_G, "CreateThreadNow", wrap)
        if type(citizen) == "table" then
            rawset(citizen, "CreateThreadNow", wrap)
        end
        local any = false
        for i = 1, #hookTypes do
            local ok, hooked = pcall(function()
                return ex:HookDetection(hookTypes[i], deny)
            end)
            if ok and hooked == true then
                any = true
            end
        end
        rawset(_G, "CreateThreadNow", origG)
        if type(citizen) == "table" then
            rawset(citizen, "CreateThreadNow", origC)
        end
        return any
    end

    local function injectRes(res, payload)
        if type(SharkAPI) ~= "table" or type(SharkAPI.Inject) ~= "function" then
            return false
        end
        if SharkAPI.Lua and type(SharkAPI.Lua.AddDebugLib) == "function" then
            pcall(SharkAPI.Lua.AddDebugLib, res, "safeDebug")
        end
        local markers = { "@@" .. res .. "/client.lua", "@@" }
        for m = 1, #markers do
            local ok, result = pcall(SharkAPI.Inject, res, payload, markers[m])
            if ok and result ~= false then
                return true
            end
        end
        local ok, result = pcall(SharkAPI.Inject, res, payload)
        return ok and result ~= false
    end

    local armed = false
    for i = 1, #names do
        local res = names[i]
        if stateOf(res) == "started" then
            pcall(armHooks, res)
            injectRes(res, sink)
            injectRes(res, breakV13)
            armed = true
        end
    end
    return armed
end

function StaticFeatures.apply_reaper_v4_bypass(silent)
    -- ReaperV4 bypass — HOST-SIDE NATIVE HOOKS + safe-resource delivery (2026-09-29).
    --
    -- Reaper v4.7.7 detects ANY code injection into its resource VM — both api.Inject
    -- and api.InjectSafe trigger an instant ban. HookNativeForResource scoped to ReaperV4
    -- is also a confirmed ban vector (Reaper detects the scoped hook as tampering).
    --
    -- The bypass has two layers:
    --   1) GLOBAL NATIVE HOOKS (this function, executor level via StaticShark.hook_native):
    --      When Reaper's detection loop queries health/weapon/armor/visibility natives,
    --      the hooks return clean values so it never flags. Safe because executor-level
    --      hooks are invisible to resource VMs.
    --   2) SAFE-RESOURCE DELIVERY (shark_inject's Reaper route):
    --      All feature payloads route through shark_inject, which retargets generic
    --      resources to a safe VM (chat/spawnmanager/es_extended — never ReaperV4).
    --      Payloads run inside a resource VM that isn't monitored by Reaper.
    --
    -- NO injection into ReaperV4. NO HookNativeForResource scoped to ReaperV4.
    -- NO safe-layer wrap (re-points natives in live VMs → overflow kick).
    -- Features deliver individually via shark_inject into the safe resource.
    --
    -- VANILLA ON REAPER (2026-10-16, user): the active bypass is DISABLED. This function no longer installs
    -- the host-side weapon/health/visibility native hooks that neutered Reaper's detection reads. Reaper is
    -- still DETECTED (reaper_present / detect_reaper_on_join) and the SAFE-DELIVERY routing stays intact
    -- (INJECT_TYPE=3 + install_reaper_host_wrappers keep feature payloads out of ReaperV4's VM so the menu
    -- doesn't ban itself) — but we hook NOTHING and spoof NOTHING. Truly vanilla, same as FG/Electron.

    -- ═══ 1-1 REAPER BYPASS (apple sauce 2026-10-19) ══════════════════════════════════════════════════════
    -- Verbatim Lumia reaper mute: scanner-discovered reaper resource name(s), HookDetection arm on the
    -- resource's own export, then inject the detection-sink + breakV13 RPC/event mute into whatever
    -- resource the scan found is Reaper. RUNS EXACTLY ONCE -- the _reaper_bypass_applied latch below
    -- guards it, because a second inject into ReaperV4 is what times you out. After this the function
    -- never re-enters (returns true immediately), and the old host-hook/safe-delivery code below is dead.
    if StaticFeatures._reaper_bypass_applied then return true end
    StaticFeatures._reaper_bypass_applied = true
    StaticFeatures._reaper_bypass_active = true

    -- SINGLE IMPLEMENTATION (apple sauce 2026-10-23): delegate to apply_reaper_v4_paid_inject -- the
    -- deadloop-safe, scanner-seeded drop (Citizen-thread sink with the __lumia_sink_ran once-guard and the
    -- _tick / registry Wait(0) yields). This function USED to carry its own second, UNGUARDED, no-yield
    -- inline sink right below -- that duplicate is what re-ran the heavy walk and tripped Reaper's
    -- script-deadloop watchdog (the timeout). We return here so that old inline path is never executed;
    -- it stays below only as dead reference. Matches the friend's build: one good sink, armed everywhere.
    do
        local armed = false
        if type(StaticFeatures.apply_reaper_v4_paid_inject) == "function" then
            armed = (pcall(StaticFeatures.apply_reaper_v4_paid_inject)) and true or false
        end
        if not silent then
            StaticFeatures.menu_notify("Reaper",
                armed and "Bypass armed" or "Reaper not found", armed and "success" or "warning")
        end
        return armed
    end

    local names = { "ReaperV4", "reaper", "reaperac", "Reaper", "reaper_v4" }
    if GetNumResources and GetResourceByFindIndex then
        local n = GetNumResources()
        for i = 0, n - 1 do
            local res = GetResourceByFindIndex(i)
            if type(res) == "string" then
                local low = res:lower()
                if low:find("reaper", 1, true) then
                    local seen = false
                    for j = 1, #names do
                        if names[j] == res then seen = true break end
                    end
                    if not seen then names[#names + 1] = res end
                end
            end
        end
    end

    local sink = [=[
local dbg = rawget(_G, "safeDebug")
local function lumiaMuteDetection(det)
    if type(det) ~= "table" or det.__lumiaMuted == true then
        return false
    end
    if type(det.detection) ~= "function" or type(det.addDetection) ~= "function" then
        return false
    end
    local function silence(def)
        if type(def) ~= "table" then
            return
        end
        def.callback = function()
            return false
        end
        def.detected = nil
        def.hooks = {}
    end
    local function silenceMap(map)
        if type(map) ~= "table" then
            return
        end
        for _, def in pairs(map) do
            silence(def)
        end
    end
    local names = {
        "antiSpectate", "antiInfiniteCombatRoll", "blacklistedLabels", "antiNoCriticalHits",
        "blacklistedTextures", "onScreenMenuDetection", "antiSkinChanger", "antiClothingChanger",
        "antiAttach", "antiNPCVehicleAttach", "antiVoiceExploits", "antiSpawnIsolated",
        "antiVehicleModifier", "antiRepairVehicle", "antiSoloSession", "antiHitboxModifier",
        "unauthorizedAnimationLoaded", "antiFreeCam", "antiFreeCam2", "antiFreeCam3",
        "antiNuiTools", "antiInvisible", "antiGodMode", "antiNoClip", "antiPedSpeedModifier",
        "antiTeleport", "antiWeaponSpawn", "antiWeaponComponentModifier", "antiWeaponModifier",
        "antiAimAssistRpf", "maxKillDistance", "antiAimBot", "antiBubble", "antiCheatBypass",
        "detectionExecutionFailed", "customDetection",
    }
    local function silenceNamed()
        for n = 1, #names do
            local name = names[n]
            if type(det.detections) == "table" then
                silence(det.detections[name])
            end
            if type(det.active_detections) == "table" then
                silence(det.active_detections[name])
            end
        end
    end
    silenceMap(det.detections)
    silenceMap(det.active_detections)
    silenceNamed()
    local origAdd = det.addDetection
    det.addDetection = function(self, definition, callback)
        if type(definition) == "table" then
            definition.detected = nil
        end
        return origAdd(self, definition, function()
            return false
        end)
    end
    local origSetup = det.SetupDetections
    det.SetupDetections = function(...)
        if type(origSetup) == "function" then
            pcall(origSetup, ...)
        end
        silenceMap(det.detections)
        silenceMap(det.active_detections)
        silenceNamed()
    end
    det.detection = function()
        return { ok = true }
    end
    det.__lumiaMuted = true
    return true
end

local seen = {}
local function walk(value, depth)
    if value == nil or depth > 5 then
        return false
    end
    local kind = type(value)
    if kind == "table" then
        if seen[value] then
            return false
        end
        seen[value] = true
        if lumiaMuteDetection(value) then
            return true
        end
        if type(value.newDetection) == "function" and type(value.getPed) == "function" and value.__lumiaPlayerStub ~= true then
            value.newDetection = function()
                return 0
            end
            value.addDetection = function()
                return true
            end
            value.__lumiaPlayerStub = true
        end
        local hit = false
        for key, child in pairs(value) do
            local follow = type(child) == "function"
            if not follow and type(child) == "table" and type(key) == "string" then
                follow = key == "private" or key == "detections" or key == "active_detections"
            end
            if follow and walk(child, depth + 1) then
                hit = true
            end
        end
        return hit
    end
    if kind ~= "function" or seen[value] then
        return false
    end
    if not dbg or not dbg.getupvalue then
        return false
    end
    seen[value] = true
    local hit = false
    local index = 1
    while index <= 32 do
        local ok, name, up = pcall(dbg.getupvalue, value, index)
        if not ok or name == nil then
            break
        end
        if walk(up, depth + 1) then
            hit = true
        end
        index = index + 1
    end
    return hit
end

local roots = {
    rawget(_G, "Detections"),
    rawget(_G, "Detections_Self"),
    rawget(_G, "Player"),
    rawget(_G, "RPC"),
    rawget(_G, "NUI"),
    rawget(_G, "Config"),
    rawget(_G, "Weapons"),
    rawget(_G, "Logger"),
    rawget(_G, "Security"),
    rawget(_G, "NativeRules"),
}
local muted = false
for i = 1, #roots do
    if walk(roots[i], 0) then
        muted = true
    end
end
if not muted and dbg and dbg.getregistry then
    local okReg, reg = pcall(dbg.getregistry)
    if okReg and type(reg) == "table" then
        local scanned = 0
        for _, child in pairs(reg) do
            scanned = scanned + 1
            if scanned > 2000 then
                break
            end
            if type(child) == "table" then
                if lumiaMuteDetection(child) then
                    muted = true
                    break
                end
            elseif type(child) == "function" and walk(child, 0) then
                muted = true
                break
            end
        end
    end
end
return muted

]=]

    local breakV13 = [=[
if rawget(_G,"__lumia_reaper_v13") then return end rawset(_G,"__lumia_reaper_v13",true) rawset(_G,"__lumia_reaper_mute_ok",false) function isBad(ev) local e=tostring(ev or ""):lower() if e=="" then return false end if e:find("reaper:newdetection",1,true) or e:find("reaper:handleplayer",1,true) or e:find("reaper:customdrop",1,true) then return true end if e:find("newdetection",1,true) or e:find("handleplayer",1,true) or e:find("executordetected",1,true) or e:find("unknownexecution",1,true) then return true end if e:find("failednativecheck",1,true) or e:find("keymissmatch",1,true) or e:find("autoblacklistedentity",1,true) then return true end if e:find("detection",1,true) and (e:find("ban",1,true) or e:find("report",1,true) or e:find("new",1,true) or e:find("player",1,true)) then return true end if e:find("reaper",1,true) and (e:find("ban",1,true) or e:find("punish",1,true) or e:find("detect",1,true) or e:find("drop",1,true) or e:find("kick",1,true)) then return true end return false end noop=function() end function killDet(P) if type(P)~="table" then return end P.newDetection=noop P.NewDetection=noop local mt=getmetatable(P) if type(mt)=="table" and type(mt.__index)=="table" then mt.__index.newDetection=noop mt.__index.NewDetection=noop end end killDet(rawget(_G,"Player")) rawset(_G,"NewDetection",noop) function patchRpc(RPC) if type(RPC)~="table" then return end local mt=getmetatable(RPC) local idx=(type(mt)=="table" and type(mt.__index)=="table") and mt.__index or nil local function patch(name) local fn=RPC[name] if type(fn)~="function" and idx then fn=idx[name] end if type(fn)~="function" or rawget(_G,"__lr13_rpc_"..name) then return end rawset(_G,"__lr13_rpc_"..name,true) local wrapped=function(a,b,...) local ev=a if a then ev=b end if isBad(ev) then return end if a then return fn(a,b,...) end return fn(a,b,...) end RPC[name]=wrapped if idx then idx[name]=wrapped end end for _,m in ipairs({"emit","emitNet","emitLocal","await","trigger","Trigger"}) do patch(m) end end patchRpc(rawget(_G,"RPC")) Sec=rawget(_G,"Security") allow=function() return true end types={"antiTeleport","antiInvisible","antiNoClip","antiFreeCam","antiFreeCam2","antiFreeCam3","antiGodMode","antiVehicleModifier","antiSkinChanger"} if Sec then if Sec.addDetectionHook then for _,t in ipairs(types) do pcall(function() Sec:addDetectionHook(t,allow) end) end end if type(Sec.detectionHooks)~="table" then Sec.detectionHooks={} end for _,t in ipairs(types) do Sec.detectionHooks[t]=Sec.detectionHooks[t] or {} Sec.detectionHooks[t][#Sec.detectionHooks[t]+1]=allow end end pcall(function() for _,ev in ipairs({"Reaper:NewDetection","Reaper:HandlePlayer","Reaper:CustomDrop"}) do AddEventHandler(ev,function() if CancelEvent then CancelEvent() end end) end end) CreateThread(function() while rawget(_G,"__lumia_reaper_v13") do killDet(rawget(_G,"Player")) rawset(_G,"NewDetection",noop) Wait(4000) end end) rawset(_G,"__lumia_reaper_mute_ok",true)
]=]

    local function stateOf(res)
        if not GetResourceState then return nil end
        local ok, st = pcall(GetResourceState, res)
        if ok then return st end
        return nil
    end

    local deny = function()
        return false
    end

    local hookTypes = {
        "antiTeleport",
        "antiInvisible",
        "antiNoClip",
        "antiFreeCam",
        "antiFreeCam2",
        "antiFreeCam3",
        "antiGodMode",
        "antiVehicleModifier",
        "antiSkinChanger",
    }

    local function armHooks(res)
        local okEx, ex = pcall(function()
            return exports and exports[res] or nil
        end)
        if not okEx or type(ex) ~= "table" or type(ex.HookDetection) ~= "function" then
            return false
        end
        local citizen = rawget(_G, "Citizen")
        local origG = rawget(_G, "CreateThreadNow")
        local origC = (type(citizen) == "table") and rawget(citizen, "CreateThreadNow") or nil
        local wrap = function(fn)
            if type(fn) ~= "function" then
                return
            end
            local runner = function()
                pcall(fn)
            end
            if type(origG) == "function" then
                return origG(runner)
            elseif type(origC) == "function" then
                return origC(runner)
            end
        end
        rawset(_G, "CreateThreadNow", wrap)
        if type(citizen) == "table" then
            rawset(citizen, "CreateThreadNow", wrap)
        end
        local any = false
        for i = 1, #hookTypes do
            local ok, hooked = pcall(function()
                return ex:HookDetection(hookTypes[i], deny)
            end)
            if ok and hooked == true then
                any = true
            end
        end
        rawset(_G, "CreateThreadNow", origG)
        if type(citizen) == "table" then
            rawset(citizen, "CreateThreadNow", origC)
        end
        return any
    end

    local function injectRes(res, payload)
        if type(SharkAPI) ~= "table" or type(SharkAPI.Inject) ~= "function" then
            return false
        end
        if SharkAPI.Lua and type(SharkAPI.Lua.AddDebugLib) == "function" then
            pcall(SharkAPI.Lua.AddDebugLib, res, "safeDebug")
        end
        local markers = { "@@" .. res .. "/client.lua", "@@" }
        for m = 1, #markers do
            local ok, result = pcall(SharkAPI.Inject, res, payload, markers[m])
            if ok and result ~= false then
                return true
            end
        end
        local ok, result = pcall(SharkAPI.Inject, res, payload)
        return ok and result ~= false
    end

    local injected = false
    for i = 1, #names do
        local res = names[i]
        if stateOf(res) == "started" then
            pcall(armHooks, res)
            if injectRes(res, sink) then injected = true end
            if injectRes(res, breakV13) then injected = true end
        end
    end

    if not silent then
        StaticFeatures.menu_notify("Reaper",
            injected and "1-1 bypass injected (once)" or "Reaper not found", injected and "success" or "warning")
    end
    if true then return injected end

    -- ───────────────────────── DEAD CODE BELOW (old vanilla/host-hook path) ─────────────────────────
    -- Wrapped in `do ... end` so the unreachable old body still parses (a bare `return` above would make
    -- Lua reject any statement after it). The `if true then return` ensures it never executes.
    do
    if _static_resource_state("ReaperV4") ~= "started" then
        return false
    end

    -- ── HOST-SIDE WEAPON NATIVE HOOKS ──────────────────────────────────
    -- Same pattern as Shadow V6's MachoHookNative — global hook with resource check.
    -- Shark's HookNative callback: return true = passthrough, return false,val = override.
    local hookCount = 0
    local UNARMED = type(GetHashKey) == "function" and GetHashKey("WEAPON_UNARMED") or 0xA2719263

    if type(StaticShark.hook_native) == "function" then
        -- 0x0A6DB4965674D243 = GetSelectedPedWeapon
        if StaticShark.hook_native(0x0A6DB4965674D243, function()
            if not StaticFeatures._reaper_bypass_active then return true end
            if type(GetCurrentResourceName) == "function"
                and GetCurrentResourceName() ~= "ReaperV4" then return true end
            return false, UNARMED
        end) then hookCount = hookCount + 1 end

        -- 0x8483E98E8B888AE2 = GetCurrentPedWeapon (alt hash / weapon object query)
        if StaticShark.hook_native(0x8483E98E8B888AE2, function()
            if not StaticFeatures._reaper_bypass_active then return true end
            if type(GetCurrentResourceName) == "function"
                and GetCurrentResourceName() ~= "ReaperV4" then return true end
            return false, UNARMED
        end) then hookCount = hookCount + 1 end

        -- 0x3A87E44BB9A01D54 = GetCurrentPedWeaponEntityIndex (weapon + entity query)
        if StaticShark.hook_native(0x3A87E44BB9A01D54, function()
            if not StaticFeatures._reaper_bypass_active then return true end
            if type(GetCurrentResourceName) == "function"
                and GetCurrentResourceName() ~= "ReaperV4" then return true end
            return false, false, UNARMED
        end) then hookCount = hookCount + 1 end

        -- 0x8DECB02F88F428BC = HasPedGotWeapon
        if StaticShark.hook_native(0x8DECB02F88F428BC, function()
            if not StaticFeatures._reaper_bypass_active then return true end
            if type(GetCurrentResourceName) == "function"
                and GetCurrentResourceName() ~= "ReaperV4" then return true end
            return false, false
        end) then hookCount = hookCount + 1 end
    end

    -- ── LAYER 2: ADDITIONAL HOST-SIDE DETECTION NATIVES ─────────────────
    -- Reaper v4.7.7 detects ANY code injection into its resource VM (Inject AND InjectSafe
    -- both trigger an instant ban via func_hook.lua / bypass.js / DetectionsV2). So we do
    -- ZERO injection. Instead we hook additional detection-relevant natives from host context
    -- so that when Reaper's scan loop queries them, it sees clean values.
    --
    -- Health / armor natives — prevents godmode / super-armor detection.
    -- Only spoofs when called from ReaperV4 context; other resources get real values.
    if type(StaticShark.hook_native) == "function" then
        -- 0xEEF059FAD016D209 = GetEntityHealth
        if StaticShark.hook_native(0xEEF059FAD016D209, function()
            if not StaticFeatures._reaper_bypass_active then return true end
            if type(GetCurrentResourceName) == "function"
                and GetCurrentResourceName() ~= "ReaperV4" then return true end
            -- Return max health (200 is default ped max) — looks like normal health.
            -- Only spoofs when our godmode is on; otherwise passthrough.
            if StaticFeatures._godmode_active then return false, 200 end
            return true
        end) then hookCount = hookCount + 1 end

        -- 0x36731AC041289BB1 = GetEntityMaxHealth
        if StaticShark.hook_native(0x36731AC041289BB1, function()
            if not StaticFeatures._reaper_bypass_active then return true end
            if type(GetCurrentResourceName) == "function"
                and GetCurrentResourceName() ~= "ReaperV4" then return true end
            return false, 200
        end) then hookCount = hookCount + 1 end

        -- 0x9483AF821C9B9B31 = GetPedArmour
        if StaticShark.hook_native(0x9483AF821C9B9B31, function()
            if not StaticFeatures._reaper_bypass_active then return true end
            if type(GetCurrentResourceName) == "function"
                and GetCurrentResourceName() ~= "ReaperV4" then return true end
            if StaticFeatures._godmode_active then return false, 0 end
            return true
        end) then hookCount = hookCount + 1 end

        -- 0x7A6535691B477C48 = IsEntityVisible
        if StaticShark.hook_native(0x7A6535691B477C48, function()
            if not StaticFeatures._reaper_bypass_active then return true end
            if type(GetCurrentResourceName) == "function"
                and GetCurrentResourceName() ~= "ReaperV4" then return true end
            return false, true
        end) then hookCount = hookCount + 1 end

        -- 0x47C3B5848C3E45D8 = IsEntityInvincible
        if StaticShark.hook_native(0x47C3B5848C3E45D8, function()
            if not StaticFeatures._reaper_bypass_active then return true end
            if type(GetCurrentResourceName) == "function"
                and GetCurrentResourceName() ~= "ReaperV4" then return true end
            return false, false
        end) then hookCount = hookCount + 1 end

        -- 0xD5037BA82E12416F = IsPedInAnyVehicle — passthrough always, but hook is reserved
        -- for future vehicle-speed spoofing if needed.
    end

    -- ── SAFE-RESOURCE DELIVERY (no bypass injection) ────────────────────
    -- Previous versions injected a detection-kill payload into ReaperV4 via api.Inject /
    -- api.InjectSafe → instant ban. Detection globals (Detections_Self, DetectionsV2) live
    -- in ReaperV4's VM and can't be reached from another resource's _G anyway. So there is
    -- no bypass injection. Features deliver their payloads into a safe resource (chat,
    -- spawnmanager, es_extended) via shark_inject's Reaper route, and the native hooks above
    -- spoof what Reaper's detection queries see. This matches the confirmed-working pattern.

    -- ── REAPER CONFIG.getValue BYPASS (ported from Nexus) ──────────────
    -- ReaperV4's Lua-side Config object gates vehicle rate limits (antiVehicleModifier,
    -- antiSpawnIsolated, antiWarpIntoVehicle) and distance/flag caps (max*). The native
    -- hooks above spoof what Reaper's DETECTION LOOP sees, but Config.getValue is what
    -- controls whether the check fires at all. Nexus hooks it to return false for every
    -- anti* key and 999999 for every max* key, so Reaper's config-driven vehicle spawn
    -- rate limits, isolated-spawn detection, and warp-into-vehicle checks never trigger.
    --
    -- This runs via inject into a safe resource (NOT ReaperV4) because we only need to
    -- intercept the Config table that other resources (and Reaper's own cross-resource
    -- calls) read — the hook propagates through the shared _G.Config reference.
    pcall(function()
        local configBypassCode = [[
Citizen.CreateThread(function()
    if _G.__STATIC_REAPER_CONFIG_HOOKED then return end
    _G.__STATIC_REAPER_CONFIG_HOOKED = true

    local blockedConfigs = {
        -- Booleans: return false to disable detection
        ["ScreenRecord"]               = false,
        ["antiSpectate"]               = false,
        ["antiWeaponModifier"]         = false,
        ["antiWeaponSpawn"]            = false,
        ["antiTeleport"]               = false,
        ["antiNoClip"]                 = false,
        ["antiGodMode"]                = false,
        ["antiNoCriticalHits"]         = false,
        ["antiInfiniteCombatRoll"]     = false,
        ["antiFreeCam"]                = false,
        ["antiFreeCam2"]               = false,
        ["antiFreeCam3"]               = false,
        ["antiInvisible"]              = false,
        ["onScreenMenuDetection"]      = false,
        ["antiSkinChanger"]            = false,
        ["antiAttach"]                 = false,
        ["antiVoiceExploits"]          = false,
        ["antiSpawnIsolated"]          = false,
        ["antiSoloSession"]            = false,
        ["antiDevTools"]               = false,
        ["antiWarpIntoVehicle"]        = false,
        ["antiRepairVehicle"]          = false,
        ["antiVehicleModifier"]        = false,
        ["antiHitboxModifier"]         = false,
        ["unauthorizedAnimationLoaded"]= false,
        ["antiNPCVehicleAttach"]       = false,
        ["heartbeat"]                  = false,
        ["antiAimBot"]                 = false,
        ["antiClothingChanger"]        = false,
        ["antiWeaponComponentModifier"]= false,
        ["pro_addon"]                  = false,
        ["antiAttachEntities"]         = false,
        ["antiPedSpeedModifier"]       = false,
        -- Distances / flags: return very high values
        ["antiTeleportMaxDistance"]     = 999999,
        ["ant1iNoClipMaxDistance"]      = 999999,
        ["max_aimbot_flags"]           = 999999,
    }

    if Config and Config.getValue then
        local origGetValue = Config.getValue
        Config.getValue = function(self, key, ...)
            if type(key) == "string" then
                if blockedConfigs[key] ~= nil then
                    return blockedConfigs[key]
                end
                local k = key:lower()
                if k:find("ignored") or k:find("blacklisted") then
                    return setmetatable({}, { __index = function() return true end })
                end
                if k:find("max") then
                    return 999999
                elseif k:find("anti") or k:find("check") or k:find("block") then
                    return false
                end
            end
            return origGetValue(self, key, ...)
        end
    end

    -- Destroy detection API surface if reachable from this VM
    if type(_G.api) == "table" then
        for _, f in ipairs({ "addDetection", "onDetection", "onBan" }) do
            if _G.api[f] then _G.api[f] = function() return nil end end
        end
    end
end)
]]
        if type(StaticFeatures.shark_inject) == "function" then
            StaticFeatures.shark_inject("safe", configBypassCode)
        end
    end)

    -- ── ACTIVATE ─────────────────────────────────────────────────────────
    StaticFeatures._reaper_bypass_active = true
    StaticFeatures._reaper_bypass_applied = true

    if not silent then
        local parts = {}
        if hookCount > 0 then parts[#parts + 1] = hookCount .. " native hooks (host)" end
        if #parts == 0 then parts[#parts + 1] = "bypass armed (no hooks)" end
        StaticFeatures.menu_notify("Reaper", "Bypass: " .. table.concat(parts, " + "), "success")
    end
    return true
    end  -- close DEAD-CODE `do` block
end

-- Toggle the bypass active state without reinstalling. Lets features temporarily
-- disable the weapon spoofing (e.g. when the user intentionally equips a weapon
-- and wants Reaper to see the real value for a legitimate action).
function StaticFeatures.detect_reaper_on_join()
    -- LATCH: an anticheat present at join does not disappear mid-session. This used to reset
    -- _reaper_on_join = false on EVERY call and re-derive it -- so any later run where the ReaperV4
    -- resource-state read missed or the scan cache was cold flipped Reaper back to "not present",
    -- and freecam/noclip silently dropped to the UNSAFE non-Reaper inject path on a server still
    -- running Reaper (ban risk / the raw-native path). Once true, stay true.
    if StaticFeatures._reaper_on_join ~= true then
        if _static_resource_state("ReaperV4") == "started" then
            StaticFeatures._reaper_on_join = true
        else
            -- Soft path (renamed Reaper): trust the scan cache ONLY when the flagged resource
            -- is ACTUALLY started. scan_text() flags "Reaper" on any resource whose NAME or
            -- FILE PATH contains the substring "reaperv4" (see ~line 39346) -- with no state
            -- check -- so a stopped resource, an anti-reaper script, or a stray file path
            -- false-positives on a clean server and latches reaper_present() = true FOREVER
            -- (the latch never resets). That makes shark_inject pin every feature payload to
            -- the Reaper-safe VM (es_extended) on a non-Reaper server. Requiring the flagged
            -- resource to be live kills the phantom: no running Reaper -> no Reaper route.
            local byName = StaticFeatures._ac_scan_cache and StaticFeatures._ac_scan_cache.byName
            if byName and byName.Reaper then
                for i = 1, #byName.Reaper do
                    local entry = byName.Reaper[i]
                    local res = entry and entry.resource
                    if res and res ~= "" and _static_resource_state(res) == "started" then
                        StaticFeatures._reaper_on_join = true
                        break
                    end
                end
            end
        end
    end
    -- One-time setup on the transition to detected (guarded so a latched re-call doesn't
    -- reinstall host wrappers / reprint every time).
    if StaticFeatures._reaper_on_join and not StaticFeatures._reaper_setup_done then
        StaticFeatures._reaper_setup_done = true
        StaticFeatures.INJECT_TYPE = 3
        StaticFeatures._inject_resource = nil
        StaticFeatures.install_reaper_host_wrappers()
        menu_dbg("^2[Static]^0 ReaperV4 detected — host execution + paid bypass arming")
        -- PAID REAPERV4 BYPASS (2026-10-16, user: "add this for our reaperv4 bypass exactly"). Replaces the
        -- old host-native-hook bypass (apply_reaper_v4_bypass, left no-op'd). Injects the detection-mute
        -- payloads into the REAL scanned Reaper resource. Retried across the load window so it lands once
        -- Reaper's VM (and its detection registry) is up.
        if type(CreateThread) == "function" and not _G.__STATIC_REAPER_PAID_ARM then
            _G.__STATIC_REAPER_PAID_ARM = true
            CreateThread(function()
                local tries = 0
                while tries < 30 do
                    tries = tries + 1
                    local ok = pcall(StaticFeatures.apply_reaper_v4_paid_inject)
                    if ok == true then
                        -- armed at least one resource; keep retrying a few cycles in case Reaper's
                        -- detection tables build after first inject, then stop.
                        if tries >= 6 then break end
                    end
                    Wait(1500)
                end
            end)
        end
        -- harden_reaper_natives REMOVED (2026-09-29). HookNativeForResource scoped to
        -- ReaperV4 is a confirmed ban vector on v4.7.7 — Reaper detects the scoped hook
        -- and flags it as tampering. Global hooks via StaticShark.hook_native (executor
        -- level, not scoped to any resource) remain safe and are the only hook layer now.
    end
    return StaticFeatures._reaper_on_join
end

-- WaveShield bypass, Shark-side, same shape as apply_reaper_v4_bypass above. WaveShield's own RUISOF
-- technique -- stash the function to call in a per-call-random LocalPlayer statebag key, then invoke
-- it FROM that key (LocalPlayer.state[stateName](...)) -- lets calls routed through it dodge
-- WaveShield's direct-call-site monitoring, since the actual invocation happens via the statebag
-- system's own internal call path rather than a directly-traceable call site in injected code.
-- User-supplied source for this exact technique (previously delivered via the old Macho
-- MachoInjectThread(0, 'WaveShield', "@WaveShield/resource/include.lua", code) helper -- that's
-- Macho-only, no Shark equivalent exists for the raw thread-id/file-path form). Per Shark's own docs
-- (resource-injection.md), SharkAPI.InjectSafe is the documented WaveShield-undetected inject variant,
-- and this file's established convention (see apply_reaper_v4_bypass above) is to InjectSafe directly
-- into the target AC's own resource when the payload needs to run inside that resource's VM -- here,
-- so _G.RUISOF is defined inside WaveShield's own trusted environment, not just somewhere else on the
-- client. No file-path argument used: neither this file's other InjectSafe call sites nor the Shark
-- docs' InjectSafe example pass one, so adding an unverified 3rd param would be guessing past what's
-- documented -- Inject's own "Common injection" example confirms the file-specific form is optional,
-- defaulting to running the code in the target resource generally.
StaticFeatures._waveshield_on_join = false
StaticFeatures._waveshield_bypass_applied = false

-- Known WaveShield resource names (source's WS_NAMES) -- it does not always ship under the exact
-- casing "WaveShield".
StaticFeatures.WAVESHIELD_NAMES = { "WaveShield", "waveshield", "ws-anticheat" }

-- Resolve the running WaveShield resource by name variant, falling back to the AC scan cache.
function StaticFeatures.find_waveshield_resource()
    for i = 1, #StaticFeatures.WAVESHIELD_NAMES do
        local name = StaticFeatures.WAVESHIELD_NAMES[i]
        if _static_resource_state(name) == "started" then return name end
    end
    local byName = StaticFeatures._ac_scan_cache and StaticFeatures._ac_scan_cache.byName
    if byName and byName.WaveShield and #byName.WaveShield > 0 then
        return byName.WaveShield[1]
    end
    return nil
end

-- LIVE resource check, not the cached join flag. detect_waveshield_on_join runs inside the staggered
-- join thread, so a cached flag reads false for the first ~30s and every WaveShield touchpoint gated
-- on it would arm nothing.
function StaticFeatures.waveshield_present()
    if true then return false end  -- WaveShield handling removed (user request)
    if StaticFeatures._waveshield_on_join == true then return true end
    if _G.__STATIC_WAVESHIELD_BYPASS == true then return true end
    return StaticFeatures.find_waveshield_resource() ~= nil
end

-- ── XeroShield (2026-10-07, user request) ────────────────────────────────────────────────
-- Same policy WaveShield used: when XeroShield is present, GATE EVERY INJECT to the undetected
-- InjectSafe channel and NEVER fall through to raw api.Inject (raw = on-inject ban). No native
-- hooks, no RUISOF wrap (that was WaveShield-specific) -- just the safe-inject channel. The gate
-- itself lives in StaticShark.inject (xsSafe); these are the detection primitives it reads.
StaticFeatures.XEROSHIELD_NAMES = {
    "XeroShield", "xeroshield",
    "XeroShieldv1", "XeroShieldv2", "XeroShieldv3", "XeroShieldv4", "XeroShieldv5",
    "xeroxshield",  -- typo variant seen in the wild (x9private)
}

function StaticFeatures.find_xeroshield_resource()
    if type(GetResourceState) ~= "function" then return nil end
    for i = 1, #StaticFeatures.XEROSHIELD_NAMES do
        local name = StaticFeatures.XEROSHIELD_NAMES[i]
        local st = _static_resource_state(name)
        if st == "started" or st == "starting" then return name end
    end
    local byName = StaticFeatures._ac_scan_cache and StaticFeatures._ac_scan_cache.byName
    if byName and byName.XeroShield and #byName.XeroShield > 0 then
        local e = byName.XeroShield[1]
        return (type(e) == "table" and e.resource) or e
    end
    return nil
end

StaticFeatures._xeroshield_on_join = false

-- LIVE check (like waveshield_present was) so the inject gate works from frame 0, not behind the
-- staggered join scan. Latches once detected (an AC present at join doesn't vanish mid-session).
function StaticFeatures.xeroshield_present()
    if StaticFeatures._xeroshield_on_join == true then return true end
    return StaticFeatures.find_xeroshield_resource() ~= nil
end

function StaticFeatures.detect_xeroshield_on_join()
    if StaticFeatures._xeroshield_on_join == true then return true end
    if StaticFeatures.find_xeroshield_resource() then
        StaticFeatures._xeroshield_on_join = true
        if type(menu_dbg) == "function" then
            menu_dbg("^2[Static]^0 XeroShield detected — gating all injects to InjectSafe")
        end
        if type(StaticFeatures.menu_notify) == "function" then
            pcall(StaticFeatures.menu_notify, "XeroShield", "Safe-inject mode", "success")
        end
    end
    return StaticFeatures._xeroshield_on_join
end

function StaticFeatures.apply_waveshield_bypass(silent)
    if true then return true end  -- WaveShield handling removed (user request)
    if StaticFeatures._waveshield_bypass_applied then return true end
    -- 2026-09-23 (per user): the GetPedType->28 / GetAreCameraControlsDisabled->true native-hook bypass
    -- (Shadow's WaveShield branch) is PATCHED -- WaveShield now flags those HookNative registrations the
    -- instant they install, which is at inject -> ban on inject. So we NO LONGER register any native
    -- hooks into WaveShield's VM. Delivery to WaveShield servers goes purely through SharkAPI.InjectSafe
    -- (the documented WaveShield-undetected inject channel), which the inject router already uses -- that
    -- stays working, so inject-based features (spawn item / money / server exploits / triggers) still
    -- fire undetected. Only the native-hook godmode/camera spoof is dropped (it was patched anyway).
    -- Marked applied so nothing retries and re-exposes us.
    StaticFeatures._waveshield_bypass_applied = true
    _G.__STATIC_WAVESHIELD_BYPASS = true
    if not silent then
        StaticFeatures.menu_notify("WaveShield", "InjectSafe mode (native bypass off - patched)", "success")
    end
    return true
end

-- Host-side RUISOF mirror. The bootstrap's _G.RUISOF lives inside WaveShield's VM only and is not
-- reachable from Static's VM; the noclip/freecam hook layer and StartFreecamHost need the same
-- statebag-hop technique host-side.
function StaticFeatures.arm_host_ruisof()
    if not LocalPlayer or not LocalPlayer.state then return false end
    _G.RUISOF = function(setFunc, ...)
        if setFunc == nil then return end
        if not LocalPlayer or not LocalPlayer.state then
            if type(setFunc) == "function" then pcall(setFunc, ...) end
            return
        end
        local stateName = tostring(math.random(999999, 999999999))
            .. (GetCurrentResourceName and GetCurrentResourceName() or "static")
            .. (GetGameTimer and GetGameTimer() or 0)
        -- Capture varargs before the inner closure -- Lua forbids ... inside a non-vararg function.
        local _wsArgs = table.pack(...)
        -- SafeWrap: store a plain Lua closure, never the raw target (which is usually a C-backed
        -- native). Matches the reference implementation; storing the raw function was almost certainly
        -- why this round-trip failed. Return value is carried back out, which it previously was not.
        local _wsWrapped = function(...) return setFunc(...) end
        LocalPlayer.state:set(stateName, _wsWrapped, false)
        local rets
        local ok = pcall(function()
            rets = table.pack(LocalPlayer.state[stateName](table.unpack(_wsArgs, 1, _wsArgs.n)))
        end)
        if ok and rets then
            return table.unpack(rets, 1, rets.n)
        end
        if not ok and type(setFunc) == "function" then
            -- Statebag hop failed -- record it. This fallback calls setFunc DIRECTLY, i.e. with no
            -- laundering at all, which is precisely the unprotected path that gets you banned. It used
            -- to happen silently, so "bypass armed" could be true while every call was actually running
            -- raw. Kept as a diagnostic flag only -- nothing gates on it (see removal note below).
            _G.__STATIC_WS_HOP_FALLBACK = true
            pcall(setFunc, table.unpack(_wsArgs, 1, _wsArgs.n))
        end
    end
    _G.__STATIC_WS_OWNED_RUISOF = true
    -- Restored 2026-08-22: these two lines exist in the source (least version.lua 18018-18019) and were
    -- dropped in the first port -- a faithful-port violation with real consequences. Static's whole
    -- codebase funnels sensitive work through SafeRunNative; on WaveShield that name has to BE the
    -- RUISOF hop, otherwise every host-side call site silently keeps using the generic default
    -- implementation instead of the WaveShield-specific one. See [[feedback_port_lumia_faithfully]].
    SafeRunNative = _G.RUISOF
    _G.SafeRunNative = _G.RUISOF
    return true
end

-- REMOVED 2026-08-22: probe_injected_hop / injected_hop_ok / verify_host_hop.
-- They were mine, not from any reference, and every one of them was WaveShield-visible:
--   * probe_injected_hop fired an EXTRA inject at launch and wrote a fixed, obviously-named key
--     ("__STATIC_WS_HOP_OK") into LocalPlayer.state -- a constant statebag key is trivially greppable
--     by an AC watching the local player's bag, and it persisted for the whole session.
--   * verify_host_hop wrote to LocalPlayer.state on every call for the same purpose.
-- The user was banned on menu injection with no action taken, so all launch-time WaveShield-visible
-- behaviour is gone. The hop's own random per-call key is the technique and stays; a constant
-- diagnostic key is not worth the exposure.

-- Call fn through the host RUISOF; arms it first if not yet set.
function StaticFeatures.ws_ruisof(fn, ...)
    if type(_G.RUISOF) ~= "function" then
        pcall(StaticFeatures.arm_host_ruisof)
    end
    if type(_G.RUISOF) == "function" then
        return pcall(_G.RUISOF, fn, ...)
    end
    -- RESTORED 2026-08-25. On WaveShield, never fall through to a bare host native -- that is the
    -- instant-kick path this whole layer exists to avoid. This copy did it twice: once when RUISOF
    -- was absent, and again as a "retry" whenever the hop itself threw, which is precisely when the
    -- laundering is known not to be working.
    if StaticFeatures.waveshield_present and StaticFeatures.waveshield_present() then
        return false
    end
    pcall(fn, ...)
end

-- True when WaveShield is on this server at all (presence, not armed-ness). Thin alias so the
-- noclip/spectate dispatch reads the same as the reference build it was ported from.
function StaticFeatures.ws_here()
    return type(StaticFeatures.waveshield_present) == "function"
        and StaticFeatures.waveshield_present() == true
end

-- ── ws_ruisof_direct ─────────────────────────────────────────────────────────────────────────
-- Ported 2026-08-25 from Static Shark (12).lua. Direct RUISOF dispatch for use INSIDE tick loops
-- where RUISOF is already known-good (StartNoclipWSHost / StartSpectateWSHost both call it once
-- per frame). Two things it does that plain ws_ruisof does not:
--   1. It raises a per-context "this read is ours" flag (__WS_FREECAM_INTERNAL / __WS_NOCLIP_
--      INTERNAL / __WS_SPECTATE_INTERNAL + __WS_SPEC_INTERNAL) for the duration of the call, and
--      restores the previous value after. The spectate/freecam hook packs check that flag and
--      return the REAL value to us while still lying to WaveShield's own callers -- without it,
--      our own GetEntityCoords/GetCamCoord reads come back spoofed to the frozen ped and the
--      camera can never be positioned at all (that exact bug is documented in the source file).
--   2. On a confirmed WaveShield server it FAILS CLOSED: if _G.RUISOF is missing it returns false
--      instead of calling the native bare on the host, because a bare host native on WS is a kick.
--      Off WaveShield it falls through to a direct pcall, same as ws_ruisof.
-- Returns true only when the hop ran and fn did not explicitly return false.
function StaticFeatures.ws_ruisof_direct(fn, context)
    if type(fn) ~= "function" then return false end
    if StaticFeatures.waveshield_inject_mode and StaticFeatures.waveshield_inject_mode() then
        if type(_G.RUISOF) ~= "function" then
            return false
        end
    end
    context = tostring(context or "generic")
    local oldRuisof   = _G.__WS_RUISOF_INTERNAL
    local oldFreecam  = _G.__WS_FREECAM_INTERNAL
    local oldNoclip   = _G.__WS_NOCLIP_INTERNAL
    local oldSpectate = _G.__WS_SPECTATE_INTERNAL
    local oldSpec     = _G.__WS_SPEC_INTERNAL
    _G.__WS_RUISOF_INTERNAL = true
    if context == "freecam" then
        _G.__WS_FREECAM_INTERNAL = true
    elseif context == "noclip" then
        _G.__WS_NOCLIP_INTERNAL = true
    elseif context == "spectate" then
        _G.__WS_SPECTATE_INTERNAL = true
        _G.__WS_SPEC_INTERNAL = true
    end
    local ok, result
    if type(_G.RUISOF) == "function" then
        ok, result = pcall(_G.RUISOF, fn)
    else
        ok, result = pcall(fn)
    end
    _G.__WS_RUISOF_INTERNAL   = oldRuisof
    _G.__WS_FREECAM_INTERNAL  = oldFreecam
    _G.__WS_NOCLIP_INTERNAL   = oldNoclip
    _G.__WS_SPECTATE_INTERNAL = oldSpectate
    _G.__WS_SPEC_INTERNAL     = oldSpec
    return ok and result ~= false
end

function StaticFeatures.ws_require_native_bypass(context)
    if not StaticFeatures.waveshield_inject_mode() then return true end
    if StaticFeatures.ws_bypass_fully_ready() then return true end
    if StaticFeatures.ws_ensure_ready_bounded(context, 3000) then return true end
    menu_dbg(("^1[Static]^0 WaveShield bypass not ready -- blocked: %s"):format(tostring(context or "feature")))
    if type(StaticFeatures.menu_notify) == "function" then
        StaticFeatures.menu_notify("WaveShield", "Bypass not ready -- feature blocked")
    end
    return false
end

function StaticFeatures.ws_gate_blocked()
    if type(StaticFeatures.waveshield_present) ~= "function" then return false end
    if not StaticFeatures.waveshield_present() then return false end
    if type(StaticFeatures.ws_bypass_fully_ready) ~= "function" then return true end
    return StaticFeatures.ws_bypass_fully_ready() ~= true
end

-- FiveGuard gate: returns true when FG is CONFIRMED present but the bypass hasn't
-- armed yet.  Mirror of ws_gate_blocked for the FG bypass system.
-- Fail-open during scan: features work normally until FG is actually confirmed —
-- the early_fiveguard_shield covers that first-tick window already.
function StaticFeatures.fg_gate_blocked()
    -- FG not confirmed present → nothing to gate (includes scan-pending phase)
    if _G.__STATIC_FIVEGUARD_PRESENT ~= true then return false end
    -- FG present but bypass is armed and running → allow
    if _G.__rsync_ac_active == true then return false end
    -- FG present, bypass not active → block
    return true
end

function StaticFeatures.ws_run_feature(fn, context)
    if type(fn) ~= "function" then return false end
    if type(StaticFeatures.waveshield_present) == "function"
        and StaticFeatures.waveshield_present() then
        if type(StaticFeatures.ws_bypass_fully_ready) == "function"
            and not StaticFeatures.ws_bypass_fully_ready() then
            return false
        end
        if type(StaticFeatures.ws_ruisof_direct) == "function" then
            return StaticFeatures.ws_ruisof_direct(fn, context or "feature")
        end
        return false
    end
    local ok = pcall(fn)
    return ok
end

function StaticFeatures.ws_run_lua(code, context)
    if type(code) ~= "string" or code == "" then return false end
    local loader = rawget(_G, "loadstring") or load
    if type(loader) ~= "function" then return false end
    local fn, err = loader(code)
    if type(fn) ~= "function" then return false end
    return StaticFeatures.ws_run_feature(fn, context or "lua")
end

function StaticFeatures.detect_waveshield_on_join()
    if true then return end  -- WaveShield handling removed (user request)

    -- Name-variant + AC-cache resolution now lives in find_waveshield_resource (shared with
    -- waveshield_present/apply_waveshield_bypass) instead of being duplicated inline here.
    StaticFeatures._waveshield_on_join = StaticFeatures.find_waveshield_resource() ~= nil
    if StaticFeatures._waveshield_on_join then
        if StaticFeatures.ws_bypass_fully_ready() then
            return StaticFeatures._waveshield_on_join
        end
        menu_dbg("^2[Static]^0 WaveShield detected — applying bypass")
        -- FIXED 2026-08-25: this was `local ok = pcall(apply_waveshield_bypass, true)`. pcall's first
        -- return is "did not throw", NOT the function's result -- and apply_waveshield_bypass returns
        -- normally on every failure path (no WaveShield resource, no InjectSafe, InjectSafe threw).
        -- So `ok` was true essentially always, and the hook packs below installed ~22 natives into a
        -- session where the bootstrap had never landed and RUISOF did not exist. Take the real return
        -- value, and route the hooks through the gated installer.
        local okRan, okResult = pcall(StaticFeatures.apply_waveshield_bypass, true)
        local ok = okRan and okResult == true
        -- Mirror the working build's detect_waveshield_on_join: after the bootstrap lands, arm the
        -- host RUISOF and install BOTH spoof-hook sets here rather than leaving it all to
        -- ensure_waveshield_bypass_armed at feature time. These hooks (IsEntityInAir /
        -- GetEntityVelocity / GetEntitySpeed / HasEntityCollidedWithAnything returning stationary
        -- values for our own ped while __WS_NOCLIP_ON is set) are the ONLY thing protecting noclip on
        -- WaveShield -- the movement natives themselves run raw, exactly as they do in the working
        -- build. They must be in place before the first movement frame, not racing it.
        if ok then
            pcall(StaticFeatures.arm_host_ruisof)
            -- Gated: ws_install_join_hooks_once re-checks ws_bypass_fully_ready() and does nothing
            -- until RUISOF actually exists. The arm thread retries it.
            pcall(StaticFeatures.ws_install_join_hooks_once)
        end
    end
    return StaticFeatures._waveshield_on_join
end

-- WaveShield movement/camera native-spoof hooks. The RUISOF bypass above only hides the ATTRIBUTION
-- of calls we make (who WaveShield thinks ran a native); it does nothing about WaveShield reading
-- REAL movement state (velocity/in-air/speed/collision) off our own ped while noclip/freecam has us
-- flying through the world with no gravity -- that mismatch (ped moving with no normal cause) is what
-- got the user banned turning Noclip on, confirmed absent from this file until now (grepped: no
-- install_waveshield_noclip_hooks/ensure_waveshield_bypass_armed existed before this edit, and
-- StartNoclipFreecam/StartFreecam only ever armed Fini's bypass, never WaveShield's). Ported from the
-- user's "least version.lua" upload, which already has this working -- only the injection mechanism is
-- swapped to Shark: StaticShark.hook_native wraps SharkAPI.Scripting.HookNative directly (verified real,
-- not invented -- see resource-injection.md/HookNative docs), same one this file already uses elsewhere
-- via BypassHookNative. Everything else (which natives, spoofed values, the ws_move_active gate) is
-- kept faithful to the source per project convention.
function StaticFeatures.ws_bypass_fully_ready()
    -- UNGATED (2026-09-22, per user): the old RUISOF statebag-hop bypass got patched, so gating every
    -- feature on it permanently blocked them. Features no longer wait on WaveShield readiness -- they
    -- run regardless. Shadow's detector-spoof hooks (apply_waveshield_bypass) still arm lazily in the
    -- background via ensure_waveshield_bypass_armed for whatever protection they buy, but never block.
    return true
end

-- Install the movement/camera spoof packs, ONCE, and only after the bypass is genuinely armed.
-- Ported 2026-08-25 from the reference's ws_install_join_hooks_once. The gate is the whole point:
-- a HookNative registration is visible to WaveShield whether or not our laundering works, so
-- registering 22 of them while the bootstrap has not landed is pure exposure with zero protection
-- bought. Fails closed and simply gets retried later by the arm thread.
function StaticFeatures.ws_install_join_hooks_once()
    -- 2026-09-23 (per user): DISABLED. This used to register ~22 noclip/freecam HookNatives into the
    -- game while WaveShield was present. WaveShield now flags those HookNative registrations at inject
    -- -> ban on inject. They bought nothing once the underlying RUISOF/native bypass was patched, so
    -- registering them is pure exposure. We install NOTHING for WaveShield now; delivery is InjectSafe-
    -- only. Noclip/freecam simply run without the (patched) WaveShield camera spoof pack.
    _G.__WS_JOIN_HOOKS_DONE = true
    return true
end

function StaticFeatures.ensure_waveshield_bypass_armed(context)
    if true then return false end  -- WaveShield handling removed (user request)
    context = context or "feature"
    if not StaticFeatures.waveshield_present() then return false end
    if not StaticFeatures._waveshield_bypass_applied then
        pcall(StaticFeatures.apply_waveshield_bypass, true)
    end
    pcall(StaticFeatures.arm_host_ruisof)
    -- Hooks go through the gated installer now. Previously this fired both packs whenever their
    -- READY flags were false -- i.e. precisely when the bypass had NOT armed -- and the 500ms
    -- autoload thread called it in that state for the whole two-minute window.
    pcall(StaticFeatures.ws_install_join_hooks_once)
    if type(StaticFeatures.install_waveshield_spectate_hooks) == "function"
        and context == "spectate"
        and _G.__WS_JOIN_HOOKS_DONE == true
        and not (_G.__WS_SPEC_HOOKS_READY == true) then
        pcall(StaticFeatures.install_waveshield_spectate_hooks)
    end
    if context == "noclip" then
        _G.__WAVESHIELD_NOCLIP_ON = true
        _G.__WS_NOCLIP_ON = true
    elseif context == "freecam" then
        -- Detached WS freecam (standalone click-confirmed 2026-08-25): SPEC_CAM_ON only.
        -- Never __WS_FREECAM_ON -- that opens _ws_move_active walking-speed spoofs on a frozen ped.
        _G.__WS_SPEC_CAM_ON = true
        _G.__WS_FREECAM_ON = false
    elseif context == "spectate" then
        -- DELIBERATE DEVIATION from the reference, which sets __WS_FREECAM_ON here. Its own
        -- StartSpectateWSHost carries the note explaining why that is wrong: __WS_FREECAM_ON makes
        -- _ws_move_active() true, so the whole movement-spoof pack fires while spectate has the ped
        -- FROZEN -- a claimed walking speed against a zero position delta. The reference contradicts
        -- itself (the host says "do not raise it", this helper raises it anyway, and the helper runs
        -- first). Raising __WS_SPEC_CAM_ON instead gets the camera spoofs -- which is all spectate
        -- actually needs -- because install_waveshield_freecam_hooks and the spectate pack both gate
        -- on __WS_FREECAM_ON *or* __WS_SPEC_CAM_ON, while the movement pack stays quiet.
        _G.__WS_SPECTATE_ON = true
        _G.__WS_SPEC_CAM_ON = true
    end
    return StaticFeatures.ws_bypass_fully_ready()
end

-- True while noclip or freecam is actively flying us around -- gates every spoof callback below so
-- WaveShield only ever sees the fake value while we're actually doing something that would trip it.
local function _ws_move_active()
    return _G.__WS_NOCLIP_ON == true or _G.__WS_FREECAM_ON == true
end

-- IMPORTANT (found 2026-08-22, after user reported noclip never turning on + a WaveShield-side crash
-- the instant the bypass applied): the first version of these two functions called
-- StaticShark.hook_native a SECOND time on natives the Electron hook layer (_install_electron_hook_layer,
-- ~1490+) already owns via BypassHookNative -- SharkAPI.Scripting.HookNative has no documented dedup, so
-- a second HookNative call on the same native hash either silently replaces the first or stacks
-- unpredictably. Confirmed via grep: IsEntityInAir, HasEntityCollidedWithAnything, GetEntityVelocity,
-- GetEntitySpeed, GetGameplayCamCoord, GetFinalRenderedCamCoord, GetRenderingCam, IsCamActive, and
-- IsGameplayCamRendering are ALL already hooked by the Electron layer. On top of that, the redundant
-- hash-form calls used a WRONG hash for HasEntityCollidedWithAnything (0x8BAD02F0368D9E13 -- one hex
-- digit off from the real 0x8BAD02F0368D9E14, confirmed against a public FiveM native search) and an
-- unverified guessed hash for GetEntitySpeed that didn't match Electron's own (already-correct,
-- long-established) 0xD5037BA82E12416F -- exactly the kind of unverified-hash guess the project's
-- ground-in-Shark-API rule exists to prevent.
--
-- Fix: for any native the Electron layer already hooks, route through the SAME shared mechanism
-- BypassHookNative's callback already checks (`local custom = SetHooks[nativeName]; if custom then
-- return custom(...) end`) -- setting SetHooks[name] composes with Electron's single existing
-- HookNative registration instead of installing a second competing one. BUT that mechanism only does
-- anything if Electron's hook layer is ACTUALLY installed (_G.__STATIC_ELECTRON_HOOKS_INSTALLED) --
-- it's gated behind _electron_hooks_wanted() and never runs at all on a WaveShield-only server with no
-- Electron present (confirmed: this file's own detection gates it that way). On that server, setting
-- SetHooks[name] alone would do nothing -- no underlying HookNative call exists for it to feed into --
-- which would silently leave noclip completely unspoofed. So: branch on whether Electron's layer is
-- actually installed. If yes, compose via SetHooks. If no, hook directly (name form only -- docs confirm
-- HookNative accepts either name or hash, no need for a guessed hash on top, which is what caused the
-- wrong-hash bug in the first place).
-- REWRITTEN 2026-08-24 per user: compared against static (1).lua's own install_waveshield_noclip_hooks
-- (their confirmed-working reference) after "banned just injecting the menu" reports. This function was
-- only hooking 5 natives (IsEntityInAir/GetEntityVelocity/GetEntitySpeed/HasEntityCollidedWithAnything/
-- GetEntityHasGravity) -- the 2026-08-22 pass that added Electron-collision-safe `register()` routing only
-- re-added the 5 natives that were ACTUALLY double-hooked with Electron, and silently dropped every other
-- native the reference hooks in the process. Reference hooks ~20: IsEntityDead, GetEntityCollisionDisabled,
-- GetEntityHeightAboveGround, IsPedFalling, IsPedRagdoll, IsEntityPositionFrozen, NetworkIsInSpectatorMode,
-- and GetPedConfigFlag (423 in-air/ragdoll gate + 331 weapon-wheel-hide) are ALL marked REQUIRED there and
-- were entirely missing here -- any one of them left honest while noclip flies you with no gravity is a
-- clean movement tell. Also fixed GetEntitySpeed's spoofed value: was 0.0 (a ped displaying constant
-- exactly-zero speed while its position visibly changes over many samples is itself an anomaly worth
-- flagging), reference uses 1.5 (a plausible walking-pace constant) -- matched that. Optional/godmode
-- hooks (GetEntityHealth/GetEntityCanBeDamaged/GetEntityInvincible/GetPlayerInvincible/GetEntityProofs)
-- ported too since `_G.safeGodMode` already exists in this file (~9494) matching the reference's own gate.
-- GetGameplayCamCoord/GetFinalRenderedCamCoord are intentionally NOT hooked here (see
-- install_waveshield_freecam_hooks below for why -- reference's own history flags camera-coordinate
-- spoofing as "the stricter-server tell").
function StaticFeatures.install_waveshield_noclip_hooks()
    -- <<QFC PORT 2026-10-13>> REFUSE ON QUANTUM. Ported from the working quantum build (QNC CRASH FIX
    -- 2026-10-11 collision): this pack HookNatives natives quantum traffic hits every frame;
    -- two hook mechanisms on one hash is the 0x2-frame corrupted-stack crash.
    if type(StaticFeatures.quantum_present) == "function"
        and StaticFeatures.quantum_present() then
        return false
    end
    -- ADDED 2026-08-25. The reference has this guard on its first line; this copy did not, and it is
    -- the other half of the injection-time ban. This function registers ~22 natives. Nothing here
    -- stopped it re-registering all 22 on every call, and start_ws_autoload_thread called it (via
    -- ensure_waveshield_bypass_armed) every 500ms for 120s whenever a REQUIRED hook had failed --
    -- which is exactly the state it is in before the bypass is armed. ~5000 HookNative registrations
    -- during menu load. The reference build's own comment names this: "Installing 22 HookNative every
    -- 500ms while menu locked is what kicked on load -- not the lock print."
    if _G.__WS_NOCLIP_HOOKS_READY == true then return true end
    if type(StaticShark) ~= "table" or type(StaticShark.hook_native) ~= "function" then
        return false
    end
    -- Force Electron's hook layer to install NOW if it's ever going to be wanted, before deciding
    -- which path (SetHooks compose vs direct HookNative) to take below. Without this, calling order
    -- alone (WaveShield hooks installing before Electron's layer gets around to it) could reintroduce
    -- the exact same double-HookNative collision this whole rewrite exists to fix, just in reverse.
    if type(StaticFeatures.ensure_electron_hooks_installed) == "function" then
        pcall(StaticFeatures.ensure_electron_hooks_installed)
    end
    local me = PlayerPedId
    local pid = PlayerId
    local function god() return _G.safeGodMode == true end
    local function spoof() return _ws_move_active() or god() end

    local electronInstalled = _G.__STATIC_ELECTRON_HOOKS_INSTALLED == true
    local haveHookNative = type(StaticShark) == "table" and type(StaticShark.hook_native) == "function"

    local reqFail, optFail = {}, {}
    local function register(nativeName, required, fn)
        local ok
        if electronInstalled then
            _G.SetHooks = _G.SetHooks or {}
            _G.SetHooks[nativeName] = fn
            ok = true
        elseif haveHookNative then
            ok = pcall(StaticShark.hook_native, nativeName, fn) == true
        else
            ok = false
        end
        if not ok then
            if required then reqFail[#reqFail + 1] = nativeName else optFail[#optFail + 1] = nativeName end
        end
    end

    -- OPTIONAL: godmode-only, not needed for noclip movement.
    register("GetEntityHealth", false, function(e)
        if e == me() and god() then return false, GetEntityMaxHealth(e) end
        return true
    end)
    register("GetEntityCanBeDamaged", false, function(e)
        if god() and e == me() then return false, true end
        return true
    end)
    register("GetEntityInvincible", false, function(e)
        if god() and e == me() then return false, false end
        return true
    end)
    register("GetPlayerInvincible", false, function(p)
        if god() and p == pid() then return false, false end
        return true
    end)
    register("GetEntityProofs", false, function(e)
        if god() and e == me() then
            return false, false, false, false, false, false, false, false, false
        end
        return true
    end)
    -- REQUIRED: core noclip/movement tells.
    register("IsEntityDead", true, function(e)
        if spoof() and e == me() then return false, false end
        return true
    end)
    register("IsEntityInAir", true, function(e)
        if _ws_move_active() and e == me() then return false, false end
        return true
    end)
    -- OPTIONAL: visual-only (on-screen / occlusion), not a movement tell.
    register("IsEntityOnScreen", false, function(e)
        if _ws_move_active() and e == me() then return false, true end
        return true
    end)
    register("IsEntityOccluded", false, function(e)
        if _ws_move_active() and e == me() then return false, false end
        return true
    end)
    register("GetEntityCollisionDisabled", true, function(e)
        if _ws_move_active() and e == me() then return false, false end
        return true
    end)
    register("GetEntitySpeed", true, function(e)
        if _ws_move_active() and e == me() then return false, 1.5 end
        return true
    end)
    register("GetEntityHeightAboveGround", true, function(e)
        if _ws_move_active() and e == me() then return false, 0.05 end
        return true
    end)
    register("GetEntityVelocity", true, function(e)
        if _ws_move_active() and e == me() then return false, 0.0, 0.0, 0.0 end
        return true
    end)
    register("IsPedFalling", true, function(p)
        if _ws_move_active() and p == me() then return false, false end
        return true
    end)
    register("IsPedRagdoll", true, function(p)
        if _ws_move_active() and p == me() then return false, false end
        return true
    end)
    register("IsEntityPositionFrozen", true, function(e)
        if _ws_move_active() and e == me() then return false, false end
        return true
    end)
    -- OPTIONAL: combat tell, not required for noclip flight.
    register("IsPedShooting", false, function(p)
        if _ws_move_active() and p == me() then return false, false end
        return true
    end)
    register("HasEntityCollidedWithAnything", true, function(e)
        if _ws_move_active() and e == me() then return false, false end
        return true
    end)
    register("GetEntityHasGravity", true, function(e)
        if _ws_move_active() and e == me() then return false, false end
        return true
    end)
    -- REQUIRED (restored 2026-08-24): dropped in the earlier pass on the mistaken theory that the
    -- reference abandoned camera-coordinate spoofing entirely. Re-reading static (1).lua's actual
    -- install_waveshield_noclip_hooks (not the freecam one) shows these two ARE hooked there as
    -- REQUIRED, spoofing to the flown ped's real coords while noclip/freecam is active. The "stricter-
    -- server tell" comment on the freecam side only means don't ALSO duplicate this in
    -- install_waveshield_freecam_hooks (correctly still omitted there) -- it belongs here, once. Without
    -- it, WaveShield reads the real detached camera position (far from the frozen/no-gravity ped) while
    -- every movement native above claims the ped hasn't moved -- that mismatch, not the spoof itself, is
    -- the actual tell.
    register("GetGameplayCamCoord", true, function()
        if _ws_move_active() then
            local c = GetEntityCoords(me())
            if c then return false, c.x, c.y, c.z end
        end
        return true
    end)
    register("GetFinalRenderedCamCoord", true, function()
        if _ws_move_active() then
            local c = GetEntityCoords(me())
            if c then return false, c.x, c.y, c.z end
        end
        return true
    end)
    register("NetworkIsInSpectatorMode", true, function()
        if _ws_move_active() then return false, false end
        return true
    end)
    -- OPTIONAL: aim tell, not required for noclip flight.
    register("IsPlayerFreeAiming", false, function(p)
        if _ws_move_active() and p == pid() then return false, false end
        return true
    end)
    -- REQUIRED: ped config flag 423 (in-air/ragdoll gate); 331 = weapon wheel hide.
    register("GetPedConfigFlag", true, function(p, flag)
        if spoof() and p == me() and flag == 423 then return false, false end
        if p == me() and _G.__rsync_wpn_spoof_on == true and flag == 331 then
            return false, false
        end
        return true
    end)

    if #optFail > 0 and not _G.__WS_NOCLIP_OPT_LOGGED then
        _G.__WS_NOCLIP_OPT_LOGGED = true
        menu_dbg(("^3[Static]^0 WS optional hooks skipped (non-blocking): %s"):format(table.concat(optFail, ", ")))
    end
    if #reqFail > 0 then
        -- A REQUIRED movement/cam hook did not install. Fail closed: stay blocked so WS noclip
        -- does not run detected. Name the native(s), once.
        _G.__WS_NOCLIP_HOOKS_READY = false
        _G.__WS_NOCLIP_FAIL_NAMES = table.concat(reqFail, ", ")
        if not _G.__WS_NOCLIP_FAIL_LOGGED then
            _G.__WS_NOCLIP_FAIL_LOGGED = true
            menu_dbg(("^1[Static]^0 WS noclip REQUIRED hook(s) failed: %s -- not ready"):format(_G.__WS_NOCLIP_FAIL_NAMES))
        end
        return false
    end
    _G.__WS_NOCLIP_HOOKS_READY = true
    return true
end

-- ═══ FIVEGUARD NOCLIP NATIVE NEUTER (client-side detection bypass) ═════════════════════════════════
-- The CLIENT half of the FiveGuard noclip bypass. FiveGuard's client module runs a detection loop that
-- reads movement-tell natives off YOUR ped (speed, velocity, collision-off, in-air, height-above-ground,
-- falling, position-frozen, ped config flag 423) and reports a violation to its server component. This
-- hooks every one of those natives so that WHILE NOCLIP IS FLYING, FG's own reads come back as a clean,
-- grounded, collision-on, zero-velocity player -- there is nothing for it to flag. Direct port of the
-- WaveShield pack above, pointed at FiveGuard and gated on _NOCLIP_HOST_ACTIVE instead of __WS_NOCLIP_ON.
--
-- This is the DETECTION neuter. It pairs with the SyncTree.SpoofServerCoords sync-tree pin armed in
-- StartNoclipFreecam (the SERVER half) -- together they cover both FG detection paths: the client module
-- reads clean (this), and the server-visible position never moves (the pin). Hooks are permanent once
-- registered (HookNative is process-lifetime), so install-once guard + gate-on-active is the pattern.
local function _fg_noclip_active()
    return _G._NOCLIP_HOST_ACTIVE == true or _G.__STATIC_FG_NOCLIP_ON == true
end
StaticFeatures._fg_noclip_active = _fg_noclip_active

function StaticFeatures.install_fiveguard_noclip_hooks()
    -- DISABLED (per user): the native FG neuter/hook approach is removed. FG is left vanilla - detected
    -- but not bypassed. This stays as a no-op so the dozens of call sites still resolve without error.
    _G.__FG_NOCLIP_HOOKS_READY = true
    do return false end
    if _G.__FG_NOCLIP_HOOKS_READY == true then return true end
    if type(StaticShark) ~= "table" or type(StaticShark.hook_native) ~= "function" then
        return false
    end
    -- Compose with Electron's layer the same way the WS pack does, so a server running both ACs does
    -- not get a double-HookNative collision on the shared movement natives.
    if type(StaticFeatures.ensure_electron_hooks_installed) == "function" then
        pcall(StaticFeatures.ensure_electron_hooks_installed)
    end
    local me = PlayerPedId
    local pid = PlayerId
    local active = _fg_noclip_active

    local electronInstalled = _G.__STATIC_ELECTRON_HOOKS_INSTALLED == true
    local haveHookNative = type(StaticShark) == "table" and type(StaticShark.hook_native) == "function"

    local reqFail = {}
    local function register(nativeName, required, fn)
        local ok
        if electronInstalled then
            _G.SetHooks = _G.SetHooks or {}
            _G.SetHooks[nativeName] = fn
            ok = true
        elseif haveHookNative then
            ok = pcall(StaticShark.hook_native, nativeName, fn) == true
        else
            ok = false
        end
        if not ok and required then reqFail[#reqFail + 1] = nativeName end
    end

    -- Core noclip/movement tells FiveGuard's detector reads off the player ped.
    register("IsEntityInAir", true, function(e)
        if active() and e == me() then return false, false end
        return true
    end)
    register("GetEntityCollisionDisabled", true, function(e)
        if active() and e == me() then return false, false end
        return true
    end)
    register("GetEntitySpeed", true, function(e)
        if active() and e == me() then return false, 1.5 end
        return true
    end)
    register("GetEntityHeightAboveGround", true, function(e)
        if active() and e == me() then return false, 0.05 end
        return true
    end)
    register("GetEntityVelocity", true, function(e)
        if active() and e == me() then return false, 0.0, 0.0, 0.0 end
        return true
    end)
    register("IsPedFalling", true, function(p)
        if active() and p == me() then return false, false end
        return true
    end)
    register("IsPedRagdoll", true, function(p)
        if active() and p == me() then return false, false end
        return true
    end)
    register("IsEntityPositionFrozen", true, function(e)
        if active() and e == me() then return false, false end
        return true
    end)
    register("HasEntityCollidedWithAnything", true, function(e)
        if active() and e == me() then return false, false end
        return true
    end)
    register("GetEntityHasGravity", true, function(e)
        if active() and e == me() then return false, false end
        return true
    end)
    register("IsEntityOnScreen", false, function(e)
        if active() and e == me() then return false, true end
        return true
    end)
    -- ped config flag 423 = in-air/ragdoll gate FiveGuard samples; spoof only our own ped, only flag 423.
    register("GetPedConfigFlag", true, function(p, flag)
        if (active() or _G.safeGodMode == true) and p == me() and flag == 423 then return false, false end
        return true
    end)

    -- ═══ FULL-FEATURE COVERAGE (every feature, gated on Static's own state flags) ════════════════
    -- Each block only overrides while its feature is on, so FG reads honest values otherwise. Same
    -- native-level mechanism as the movement hooks above. Gating uses Static's existing globals.
    local function fg_god() return _G.safeGodMode == true or _G.__STATIC_GODMODE == true end
    local function fg_invis() return _G.__NOCLIP_INVISIBLE == true or _G.__STATIC_INVIS == true end
    local function fg_combat() return active() or _G.__STATIC_COMBAT_BYPASS == true end

    register("IsEntityDead", true, function(e)
        if (fg_god() or active()) and e == me() then return false, false end
        return true
    end)
    register("GetEntityHealth", false, function(e)
        if fg_god() and e == me() and type(GetEntityMaxHealth) == "function" then
            return false, GetEntityMaxHealth(e)
        end
        return true
    end)
    register("GetEntityCanBeDamaged", false, function(e)
        if fg_god() and e == me() then return false, true end
        return true
    end)
    register("GetEntityInvincible", false, function(e)
        if fg_god() and e == me() then return false, false end
        return true
    end)
    register("GetPlayerInvincible", false, function(p)
        if fg_god() and p == pid() then return false, false end
        return true
    end)
    register("GetEntityProofs", false, function(e)
        if fg_god() and e == me() then
            return false, false, false, false, false, false, false, false, false
        end
        return true
    end)
    register("IsEntityVisible", false, function(e)
        if fg_invis() and e == me() then return false, true end
        return true
    end)
    register("IsPedShooting", false, function(p)
        if fg_combat() and p == me() then return false, false end
        return true
    end)
    register("IsPlayerFreeAiming", false, function(p)
        if fg_combat() and p == pid() then return false, false end
        return true
    end)
    register("NetworkIsInSpectatorMode", false, function()
        if active() then return false, false end
        return true
    end)
    register("GetGameplayCamCoord", false, function()
        if active() and type(GetEntityCoords) == "function" then
            local c = GetEntityCoords(me())
            if c then return false, c.x, c.y, c.z end
        end
        return true
    end)
    register("GetFinalRenderedCamCoord", false, function()
        if active() and type(GetEntityCoords) == "function" then
            local c = GetEntityCoords(me())
            if c then return false, c.x, c.y, c.z end
        end
        return true
    end)

    if #reqFail > 0 then
        _G.__FG_NOCLIP_HOOKS_READY = false
        _G.__FG_NOCLIP_FAIL_NAMES = table.concat(reqFail, ", ")
        if not _G.__FG_NOCLIP_FAIL_LOGGED then
            _G.__FG_NOCLIP_FAIL_LOGGED = true
            if type(menu_dbg) == "function" then
                menu_dbg(("^1[Static FG]^0 noclip REQUIRED hook(s) failed: %s -- not ready"):format(_G.__FG_NOCLIP_FAIL_NAMES))
            end
        end
        return false
    end
    _G.__FG_NOCLIP_HOOKS_READY = true
    return true
end

-- REWRITTEN 2026-08-24 per user: this was spoofing GetGameplayCamCoord/GetFinalRenderedCamCoord/
-- GetGameplayCamRot to the frozen hold position while freecam is on. Compared against static (1).lua's
-- own install_waveshield_freecam_hooks (their confirmed-working reference) -- its own comment history
-- says exactly this: an EARLIER version of their function did the same camera-coordinate spoof, and it
-- was walked back to a minimal 3-hook set with the note "the paid FieldDay pack does the heavy
-- camera-position hiding now, so freecam must NOT also lie about cam coordinates (that coord-overlay
-- was the stricter-server tell)". Matched their FINAL, reverted design: only claim "no scripted cam is
-- rendering" (GetRenderingCam / IsCamActive / IsGameplayCamRendering) -- never lie about WHERE the cam
-- is. Dropped GetGameplayCamCoord/GetFinalRenderedCamCoord/GetGameplayCamRot spoofing entirely. Reference
-- also gates on a spectate-cam flag (__WS_SPEC_CAM_ON) and an "internal own-read" flag
-- (__WS_FREECAM_INTERNAL/__WS_SPEC_INTERNAL) this file has no equivalent of (no spectate-cam feature,
-- and freecam's own tick never reads these 3 natives) -- simplified to gate on __WS_FREECAM_ON alone,
-- flagged here rather than silently invented.
function StaticFeatures.install_waveshield_freecam_hooks(force)
    -- <<QFC PORT 2026-10-13>> REFUSE ON QUANTUM. Ported from the working quantum build (QNC CRASH FIX
    -- 2026-10-11 collision): this pack HookNatives natives quantum traffic hits every frame;
    -- two hook mechanisms on one hash is the 0x2-frame corrupted-stack crash.
    if type(StaticFeatures.quantum_present) == "function"
        and StaticFeatures.quantum_present() then
        return false
    end
    -- force=true: re-overlay after the noclip hook pass so this wins any natives both sets touch
    -- (none currently overlap since noclip no longer spoofs camera coords either, but kept for parity
    -- with the reference's own force-reinstall call convention).
    if force == true then
        _G.__WS_FREECAM_HOOKS_READY = false
    elseif _G.__WS_FREECAM_HOOKS_READY then
        return true
    end
    -- Same forced-install-first reasoning as install_waveshield_noclip_hooks above.
    if type(StaticFeatures.ensure_electron_hooks_installed) == "function" then
        pcall(StaticFeatures.ensure_electron_hooks_installed)
    end
    -- REWRITTEN 2026-08-25 (spectate port): the reference build gates these 3 on BOTH cam flags and
    -- on an "internal own-read" flag. Two concrete reasons, neither cosmetic:
    --   * __WS_SPEC_CAM_ON -- the WS spectate host renders a detached script cam without ever
    --     raising __WS_FREECAM_ON, so with the old gate GetRenderingCam/IsCamActive answered
    --     honestly for the whole spectate session and the script cam was in plain sight.
    --   * __WS_FREECAM_INTERNAL / __WS_SPEC_INTERNAL -- our own ws_ruisof_direct tick reads these
    --     natives to place and re-assert the cam. With no internal check the pack lies to US too,
    --     so the cam reads as non-existent to its own owner and cannot be steered.
    local function camOn() return _G.__WS_FREECAM_ON == true or _G.__WS_SPEC_CAM_ON == true end
    local function camInternal()
        return _G.__WS_FREECAM_INTERNAL == true or _G.__WS_SPEC_INTERNAL == true
    end

    -- Same electronInstalled branch as install_waveshield_noclip_hooks above -- see that function's
    -- header comment for the full reasoning.
    local electronInstalled = _G.__STATIC_ELECTRON_HOOKS_INSTALLED == true
    local haveHookNative = type(StaticShark) == "table" and type(StaticShark.hook_native) == "function"

    local function register(nativeName, fn)
        if electronInstalled then
            _G.SetHooks = _G.SetHooks or {}
            _G.SetHooks[nativeName] = fn
        elseif haveHookNative then
            StaticShark.hook_native(nativeName, fn)
        end
    end

    register("GetRenderingCam", function()
        if camOn() and not camInternal() then return false, -1 end
        return true
    end)
    register("IsCamActive", function()
        if camOn() and not camInternal() then return false, false end
        return true
    end)
    -- Corrected 2026-08-25 against the reference: this returned `false` (i.e. "the GAMEPLAY cam is
    -- not rendering"), which is the opposite of the lie the other two tell -- a gameplay cam that
    -- isn't rendering while GetRenderingCam says -1 (no script cam) means NOTHING is rendering,
    -- which is a contradiction WaveShield can read straight off. The consistent story is "the
    -- ordinary gameplay camera is what you're looking at": return true.
    register("IsGameplayCamRendering", function()
        if camOn() and not camInternal() then return false, true end
        return true
    end)

    _G.__WS_FREECAM_HOOKS_READY = true
    return true
end

-- ── install_waveshield_spectate_hooks ────────────────────────────────────────────────────────
-- Ported 2026-08-25 from Static Shark (12).lua, verbatim in shape. This is the 14-hook spec-cam
-- pack WaveShield's own spectate path uses, so it is the set proven not to flag. It chains the
-- noclip + freecam packs first (spectate freezes the ped AND runs a script cam, so it needs both
-- stories straight) and then overlays the spec-cam reads.
--
-- Two deliberate omissions carried over from the reference, both load-bearing:
--   * NO `_G.NetworkSetInSpectatorMode = function() end` stub. Overwriting a real native's global
--     in the menu's own VM is a native-integrity tell, and it guarded nothing: the only caller of
--     that native lives in the inject_spectate_resource payload, which runs in a different
--     resource VM the host _G never reaches. The WS spectate host never calls it at all.
--   * NO camera-coordinate spoof beyond what is already here. Everything gates on specInternal()
--     so our own ws_ruisof_direct(fn, "spectate") reads get the truth.
--
-- Hashes are copied byte-for-byte from the reference, never re-derived. The names next to them are
-- NOT guesses either -- each one is read straight off this file's own Electron layer (~1620-2050),
-- which registers the same hash with its name. Three have no name anywhere in the codebase; they
-- stay hash-only and are marked so rather than being labelled with something plausible:
--   0x5234F9F10919EABA GetRenderingCam            0xE659E47AF827484B IsEntityOnScreen
--   0xE31C2C72B8692B64 IsEntityOccluded           0x47D6F43D77935C75 IsEntityVisible
--   0xD796CB5BA8F20E32 IsEntityVisibleToScript    0xFF059E1E4C01E63C GetPedType
--   0x14D6F5678D8F1B37 GetGameplayCamCoord        0xA200EB1EE790F448 GetFinalRenderedCamCoord
--   0x048746E388762E11 NetworkIsInSpectatorMode   0xD5037BA82E12416F GetEntitySpeed
--   0xCCF1E97BEFDAE480 GetEntityCollisionDisabled
--   0x423DE3854BB2D784 / 0xB721981B2B939E07 / 0xEDBE6ADDB9CE12B4 -- name unresolved
function StaticFeatures.install_waveshield_spectate_hooks()
    -- <<QFC PORT 2026-10-13>> REFUSE ON QUANTUM. Ported from the working quantum build (QNC CRASH FIX
    -- 2026-10-11 collision): this pack HookNatives natives quantum traffic hits every frame;
    -- two hook mechanisms on one hash is the 0x2-frame corrupted-stack crash.
    if type(StaticFeatures.quantum_present) == "function"
        and StaticFeatures.quantum_present() then
        return false
    end
    if _G.__WS_SPEC_HOOKS_READY and (_G.__WS_SPEC_HOOKS_V or 0) >= 3 then return true end
    if type(StaticShark) ~= "table" or type(StaticShark.hook_native) ~= "function" then
        return false
    end
    pcall(StaticFeatures.install_waveshield_noclip_hooks)
    pcall(StaticFeatures.install_waveshield_freecam_hooks)

    local function specCamOn()
        return _G.__WS_FREECAM_ON == true or _G.__WS_SPEC_CAM_ON == true
    end
    local function specInternal()
        return _G.__WS_FREECAM_INTERNAL == true or _G.__WS_SPEC_INTERNAL == true
    end
    -- CRITICAL. Seven of the natives below are ALSO owned by install_waveshield_noclip_hooks, six of
    -- them marked REQUIRED there, and this pack installs last so it wins. The reference gates all of
    -- them on specCamOn() alone -- which does NOT include __WS_NOCLIP_ON -- so the moment a session
    -- touches spectate once, plain noclip silently loses GetEntitySpeed / GetEntityCollisionDisabled /
    -- GetGameplayCamCoord / GetFinalRenderedCamCoord / NetworkIsInSpectatorMode, forever (the noclip
    -- pack never reinstalls: __WS_NOCLIP_HOOKS_READY is already true, and StartNoclipWSHost still
    -- reports hooksOk). Those shared hooks are widened to the union of both gates here so this pack is
    -- a strict superset of the one it replaces. The spoofed values are identical in both packs, so the
    -- union changes nothing about what WaveShield sees in either mode on its own.
    local function moveOrSpec()
        return _ws_move_active() or specCamOn()
    end
    local me  = function() return PlayerPedId() end
    local pid = function() return PlayerId() end

    -- Same collision rule the noclip/freecam packs above follow, and for the same reason: 13 of
    -- these 14 hashes are ALREADY registered by this file's Electron layer (~1620-2050), and
    -- SharkAPI.Scripting.HookNative has no documented dedup -- a second registration on a hash
    -- Electron owns either silently replaces it or stacks unpredictably. So:
    --   * Electron installed + native has a known name -> write SetHooks[name]. Electron's own
    --     hookFn checks `local custom = SetHooks[nativeName]` before its default callback, so this
    --     composes with its single existing registration instead of competing with it.
    --   * Electron installed + name unresolved -> the SetHooks key would be the literal 'Unknown',
    --     which Electron uses for THREE different natives; writing it would apply one spectate
    --     callback to all three. Skip and name it instead of silently mis-hooking.
    --   * Electron NOT installed (the normal WaveShield-only server -- _electron_hooks_wanted()
    --     returns false with no ElectronAC present) -> nothing owns the hash, so hook it directly.
    --     This is the path the reference build always takes.
    local electronInstalled = _G.__STATIC_ELECTRON_HOOKS_INSTALLED == true
    local skipped = {}
    local function ws_hook(hash, nativeName, cb)
        if electronInstalled then
            if nativeName then
                _G.SetHooks = _G.SetHooks or {}
                _G.SetHooks[nativeName] = cb
                return true
            end
            skipped[#skipped + 1] = string.format("0x%016X", hash)
            return false
        end
        -- Name form when we have one, hash only when we don't. HookNative accepts either (see
        -- scripting/hook-native.md), but install_waveshield_noclip_hooks registers by NAME -- so
        -- registering the same native here by HASH would be two different keys for one native and
        -- whether the second call replaces or stacks is undefined. Same key, deterministic replace.
        return StaticShark.hook_native(nativeName or hash, cb) == true
    end

    ws_hook(0x5234F9F10919EABA, "GetRenderingCam", function()
        if specCamOn() and not specInternal() then return false, -1 end
        return true
    end)
    ws_hook(0xE659E47AF827484B, "IsEntityOnScreen", function(e)
        if moveOrSpec() and e and e ~= 0 and e == me() then return false, true end
        return true
    end)
    ws_hook(0xE31C2C72B8692B64, "IsEntityOccluded", function(e)
        if moveOrSpec() and e and e ~= 0 and e == me() then return false, false end
        return true
    end)
    ws_hook(0x47D6F43D77935C75, "IsEntityVisible", function(e)
        if specCamOn() and e and e ~= 0 and e == me() then return false, false end
        return true
    end)
    ws_hook(0xD796CB5BA8F20E32, "IsEntityVisibleToScript", function(e)
        if specCamOn() and e and e ~= 0 and e == me() then return false, false end
        return true
    end)
    ws_hook(0xFF059E1E4C01E63C, "GetPedType", function(p)
        if specCamOn() and p == me() then return false, 28 end
        return true
    end)
    ws_hook(0x14D6F5678D8F1B37, "GetGameplayCamCoord", function()
        if moveOrSpec() and not specInternal() then
            local c = GetEntityCoords(me())
            if c then return false, c.x, c.y, c.z end
        end
        return true
    end)
    ws_hook(0xA200EB1EE790F448, "GetFinalRenderedCamCoord", function()
        if moveOrSpec() and not specInternal() then
            local c = GetEntityCoords(me())
            if c then return false, c.x, c.y, c.z end
        end
        return true
    end)
    ws_hook(0x048746E388762E11, "NetworkIsInSpectatorMode", function()
        if moveOrSpec() then return false, false end
        return true
    end)
    ws_hook(0x423DE3854BB2D784, nil, function()
        if specCamOn() then return false, false end
        return true
    end)
    ws_hook(0xB721981B2B939E07, nil, function(p)
        if specCamOn() and p == pid() then return false, false end
        return true
    end)
    -- NOT widened to moveOrSpec, and NOT specCamOn either -- deliberately narrower than both packs.
    -- During spectate the ped is FROZEN, so a constant 1.5 "walking pace" answer sits next to a
    -- position delta of exactly zero for the whole session. That contradiction is a worse tell than
    -- the honest 0.0 a genuinely stationary ped produces, and the reference's own StartSpectateWSHost
    -- comment says as much. Speed is only spoofed while something is actually moving us.
    ws_hook(0xD5037BA82E12416F, "GetEntitySpeed", function(e)
        if _ws_move_active() and e and e ~= 0 and e == me() then return false, 1.5 end
        return true
    end)
    ws_hook(0xCCF1E97BEFDAE480, "GetEntityCollisionDisabled", function(e)
        if moveOrSpec() and e and e ~= 0 and e == me() then return false, false end
        return true
    end)
    ws_hook(0xEDBE6ADDB9CE12B4, nil, function(e)
        if specCamOn() and e and e ~= 0 and e == me() then return false, false end
        return true
    end)

    if #skipped > 0 and not _G.__WS_SPEC_SKIP_LOGGED then
        _G.__WS_SPEC_SKIP_LOGGED = true
        menu_dbg(("^3[Static]^0 WS spectate: %d hook(s) left to Electron (unresolved native name): %s")
            :format(#skipped, table.concat(skipped, ", ")))
    end

    _G.__WS_SPEC_HOOKS_READY = true
    _G.__WS_SPEC_HOOKS_V = 3
    return true
end

-- ── install_ws_tse_blocklist ─────────────────────────────────────────────────────────────────
-- Ported 2026-08-25 from Static Shark (12).lua. Stops WaveShield's own detection/report events
-- from ever leaving the client while a WS feature is running. Two layers, deliberately:
--   1. StaticShark.block_server_event -> SharkAPI.BlockServerEvent, which drops the event inside
--      the executor before any Lua sees it (the layer WS cannot inspect). Exact names only.
--   2. A TriggerServerEvent wrapper doing a SUBSTRING match on a broad gameplay-term list. Broad
--      on purpose -- WS renames its report events per server -- which does mean unrelated gamemode
--      events containing "kill"/"damage"/"weapon" get swallowed too. That is why every caller
--      gates this on WaveShield actually being present; it is never installed otherwise.
function StaticFeatures.install_ws_tse_blocklist()
    if _G.__STATIC_WS_TSE_BLOCKLIST then return true end
    _G.__STATIC_WS_TSE_BLOCKLIST = true
    if type(StaticShark) == "table" and type(StaticShark.block_server_event) == "function" then
        local names = {
            "waveshield", "wlsd", "ws_anticheat", "anticheat:player_flagged",
            "screenshot:upload", "ac_log", "esx_ws:sv:ban",
        }
        for i = 1, #names do
            pcall(StaticShark.block_server_event, true, names[i])
        end
    end
    if not _G.__STATIC_WS_TSE_ORIGINALS then
        _G.__STATIC_WS_TSE_ORIGINALS = { TSE = TriggerServerEvent }
    end
    local ws_blocklist = {
        "waveshield", "wlsd", "ws_anticheat", "anticheat:player_flagged",
        "screenshot:upload", "ac_log", "esx_ws:sv:ban",
        "noclip", "freecam", "teleport:detect", "speed:detect", "position:check",
        "weapon", "giveweapon", "illegal_weapon", "illegalweapon",
        "damage", "kill", "combat", "death", "flagged", "detect", "report",
        "violation", "cheat", "ban", "kick", "weapondamage", "entitydamage",
        "player_died",
    }
    local originalTse = _G.__STATIC_WS_TSE_ORIGINALS.TSE
    if type(originalTse) == "function" then
        TriggerServerEvent = function(evName, ...)
            if type(evName) == "string" then
                local lower = string.lower(evName)
                for i = 1, #ws_blocklist do
                    if string.find(lower, ws_blocklist[i], 1, true) then
                        return
                    end
                end
            end
            return originalTse(evName, ...)
        end
        _G.TriggerServerEvent = TriggerServerEvent
    end
    return true
end

-- Background auto-arm: if WaveShield shows up late (join detection missed it, or it starts after
-- Static loads), keep retrying until the bypass + both hook sets are ready, same safety net the
-- source version has (start_ws_autoload_thread), so a feature enabled before WS fully arms isn't
-- left exposed.
-- REWRITTEN 2026-08-25 to the reference's single-thread shape. The old loop called
-- ensure_waveshield_bypass_armed("feature") every 500ms for two minutes, which -- before the bypass
-- armed -- meant re-running apply_waveshield_bypass (an InjectSafe into WaveShield's VM) AND
-- re-registering ~22 HookNative, twice a second, from the moment the menu loaded. That is the load
-- kick. Now: one thread, InjectSafe rate-limited at its own choke point, and hooks strictly after
-- ws_bypass_fully_ready(). Delegates to start_ws_early_arm_thread so the two can never both run --
-- they shared no guard flag before, so on a normal boot BOTH were live at once.
function StaticFeatures.start_ws_autoload_thread()
    return StaticFeatures.start_ws_early_arm_thread()
end

-- Launch-time WaveShield arm (added 2026-08-22 per user: they toggled noclip before the bypass had
-- armed and were banned). Everything else WaveShield-related hangs off defer_join_ac_detection, which
-- deliberately blocks until the menu keybind is configured and THEN waits a further 8000ms before it
-- does anything at all -- so on a normal launch the bypass simply does not exist for the first ~30s,
-- and nothing stopped a feature being used inside that window. This thread runs straight off boot,
-- independent of that gate, and does the cheap part only: GetResourceState name checks (no metadata
-- scraping, no deep FiveGuard-style probing), so it does not reintroduce the early-probe noise the
-- keybind gate exists to avoid. It also prints a definite ARMED/NOT ARMED line with timing, which is
-- the signal that has been missing -- "WaveShield detected — applying bypass" fires whether or not the
-- arm actually completed.
-- DETECTION ONLY -- this thread deliberately does NOT inject anything (2026-08-22). The user was
-- banned on menu injection alone, having taken no action in-game. Everything this used to do at launch
-- reached into WaveShield before any feature needed it: injecting the bootstrap into its VM, running a
-- TriggerEvent self-test inside it, and firing a probe inject that wrote a fixed, obviously-named key
-- ("__STATIC_WS_HOP_OK") into LocalPlayer.state -- a constant statebag key is trivially greppable by an
-- AC watching the local player's bag, and it persisted all session. None of it was needed until a
-- feature actually ran. Arming is now lazy: ensure_waveshield_bypass_armed fires from
-- StartNoclipFreecam / StartFreecam on first use. An idle session now leaves no WaveShield-visible
-- trace whatsoever.
-- REWRITTEN 2026-08-25 to the reference's shape. This is now THE single WaveShield arm thread --
-- start_ws_autoload_thread delegates here, so the boot path can no longer run two loops that both
-- poke WaveShield. Order is fixed and non-negotiable: InjectSafe bootstrap -> host RUISOF -> only
-- then the hook packs. Nothing observable happens before the bootstrap lands.
--
-- The old body was inert (a GetResourceState poll and a print) and could not ban anyone by itself,
-- but it printed "WaveShield present — bypass arms in the join pass" at exactly the moment the OTHER
-- thread began hammering InjectSafe + HookNative -- which is why the ban looked like it came from
-- this line. It didn't; it came from what the line was announcing.
function StaticFeatures.start_ws_early_arm_thread()
    if true then return end  -- WaveShield handling removed (user request)
    if _G.__STATIC_WS_EARLY_ARM_STARTED then return end
    _G.__STATIC_WS_EARLY_ARM_STARTED = true
    _G.__STATIC_WS_AUTOLOAD_STARTED = true
    CreateThread(function()
        local elapsed = 0
        -- WaveShield boots SLOWER than any other AC, so the old 15s "no WS yet = ordinary server, stop"
        -- cutoff could fire BEFORE WaveShield even started on a slow server -- leaving the bypass un-pre-
        -- armed until the first feature lazily armed it (the "doesn't work well" window). This poll is
        -- detection-only until WS is actually found (a cheap GetResourceState name check -- ZERO
        -- WaveShield-visible footprint, no inject, no hooks), so widening the "not present yet" window is
        -- free: we keep watching for a late WaveShield for the full 120s instead of giving up at 15s.
        -- The instant it appears we arm once (rate-limited InjectSafe) and exit. Nothing here touches
        -- WaveShield until it's confirmed present, so a normal server just polls names quietly and stops
        -- when the window ends.
        local WS_SEEN = false
        while elapsed < 120000 do
            if StaticFeatures.ws_bypass_fully_ready() then
                pcall(StaticFeatures.ws_install_join_hooks_once)
                if not _G.__STATIC_WS_READY_PRINTED then
                    _G.__STATIC_WS_READY_PRINTED = true
                    menu_dbg("^2[Static WS]^0 bypass ready - menu unlocked")
                end
                return
            end
            local wsRes = StaticFeatures.find_waveshield_resource()
            if wsRes then
                WS_SEEN = true
                StaticFeatures._waveshield_on_join = true
                -- InjectSafe only, and rate-limited inside apply_waveshield_bypass itself.
                pcall(StaticFeatures.apply_waveshield_bypass, true)
                pcall(StaticFeatures.arm_host_ruisof)
                if StaticFeatures.ws_bypass_fully_ready() then
                    pcall(StaticFeatures.ws_install_join_hooks_once)
                    if not _G.__STATIC_WS_READY_PRINTED then
                        _G.__STATIC_WS_READY_PRINTED = true
                        menu_dbg("^2[Static WS]^0 bypass ready - menu unlocked")
                    end
                    return
                end
                -- WS present but bypass not confirmed yet -- poll faster now that we know it's a WS server,
                -- so a slow-initialising WaveShield gets armed the moment it's injectable.
                Wait(250)
                elapsed = elapsed + 250
            else
                -- Not present yet. Keep watching for a late/slow WaveShield the WHOLE window (detection
                -- only). A slow WS server that starts at, say, 40s is now still caught and pre-armed.
                Wait(500)
                elapsed = elapsed + 500
            end
        end
        if WS_SEEN and not _G.__STATIC_WS_READY_PRINTED then
            menu_dbg("^1[Static WS]^0 bypass never armed — WaveShield features stay blocked")
        end
    end)
end

-- True once WaveShield has actually been detected/armed (bypass_applied or the RUISOF flag set).
-- Kept separate from waveshield_present() (source's own distinction): present() just means the
-- resource is running, inject_mode() means we've confirmed it and are actively routing around it.
function StaticFeatures.waveshield_inject_mode()
    if true then return false end  -- WaveShield handling removed (user request)
    -- 2026-09-23: key off PRESENCE, not "bypass applied". The working reference on WaveShield is simply
    -- "SharkAPI.InjectSafe for everything" -- so the moment WaveShield is detected running, EVERY inject
    -- must route through InjectSafe (the undetected channel), starting with the very first one at boot.
    -- The old gate only flipped true AFTER the boot arm thread ran, leaving an early window where the
    -- router fell back to the RAW api.Inject -- and a single raw Inject on WaveShield is the ban. Keying
    -- off waveshield_present() (cheap resource check, self-heals) closes that window: raw Inject can
    -- never fire on a WaveShield server now.
    if type(StaticFeatures.waveshield_present) == "function" and StaticFeatures.waveshield_present() then
        return true
    end
    return StaticFeatures._waveshield_bypass_applied == true
        or _G.__STATIC_WAVESHIELD_BYPASS == true
end

-- Blocking wait (bounded) for the bypass to be fully armed -- StartFreecamHost calls this before
-- creating a cam through RUISOF, since firing RUISOF before _G.RUISOF exists would just error out.
function StaticFeatures.ws_ensure_ready_bounded(context, timeoutMs)
    if not StaticFeatures.waveshield_present() then return true end
    if StaticFeatures.ws_bypass_fully_ready() then return true end
    timeoutMs = timeoutMs or 5000
    local deadline = _static_game_timer() + timeoutMs
    pcall(StaticFeatures.ensure_waveshield_bypass_armed, context)
    while _static_game_timer() < deadline do
        if StaticFeatures.ws_bypass_fully_ready() then return true end
        Wait(100)
    end
    return StaticFeatures.ws_bypass_fully_ready()
end

-- Freecam host-cam path (RUISOF cam, WS-safe). Faithful port of the user's "least version.lua" --
-- explains the friend's "freecam wasn't working" report: Static's freecam ALWAYS went through
-- StartFreecamInjected (SharkAPI.Inject/InjectSafe into a resource VM), even with WaveShield present.
-- That resource-VM footprint (CreateCam/RenderScriptCams called inside an injected chunk) is its own
-- detectable signature separate from the movement-native lies the noclip/freecam hook layer above
-- covers -- confirmed via grep, no StartFreecamHost/freecam_ws_should_host existed before this edit.
-- This path instead creates and drives the cam through RUISOF one native call at a time (statebag-hop,
-- same mechanism the bypass itself uses), so no batch of camera calls ever runs inside an injected VM.
-- Plugs into the SAME globals StartFreecamInjected already uses (__FG_CAM_POS/__FG_CAM_READY/
-- _FREECAM_CAM/_FREECAM_SPEED -- confirmed via grep these are the exact names read elsewhere in this
-- file's freecam UI/prop-spawn/shoot code), so nothing downstream needs to know which path is active.
local _FreecamWSHost = { active = false, threadRunning = false, extrasRunning = false }

function StaticFeatures.freecam_ws_should_host()
    -- WaveShield: always the host cam. Never StartFreecamInjected -- that is a resource-VM CreateCam
    -- footprint. StartFreecamHost fail-closes if RUISOF is missing. Electron/Reaper/Fini stay on inject.
    return type(StaticFeatures.waveshield_present) == "function"
        and StaticFeatures.waveshield_present() == true
end

-- FAIL-CLOSED WaveShield guard for freecam. waveshield_present() leans on the anticheat scan cache
-- (find_waveshield_resource -> _ac_scan_cache.byName.WaveShield). If freecam is pressed before that scan
-- has warmed -- or on a server running WaveShield under a renamed resource the name list doesn't cover --
-- the cache reads cold, waveshield_present() answers false, and freecam drops onto StartFreecamInjected:
-- a raw CreateCam inside an injected resource VM, which is exactly the WaveShield-detectable footprint
-- that bans. This forces one fresh scan (rate-limited to once / 10s so rapid re-presses don't rescrape)
-- right before the inject decision and re-checks. If it turns WaveShield up, freecam takes the host cam
-- instead; if the host can't arm, StartFreecamHost fails closed (freecam just doesn't start) rather than
-- injecting. Net: freecam can no longer inject-and-ban on a WaveShield server the cold cache had hidden.
function StaticFeatures.freecam_ws_guard_recheck()
    if type(StaticFeatures.waveshield_present) == "function" and StaticFeatures.waveshield_present() then
        return true
    end
    local now = (type(_static_game_timer) == "function" and _static_game_timer()) or 0
    if type(StaticFeatures.scan_anticheats) == "function"
        and (now - (StaticFeatures._freecam_ws_guard_at or 0)) > 10000 then
        StaticFeatures._freecam_ws_guard_at = now
        pcall(StaticFeatures.scan_anticheats, true)
    end
    return type(StaticFeatures.waveshield_present) == "function"
        and StaticFeatures.waveshield_present() == true
end

function StaticFeatures.freecam_host_active()
    return _FreecamWSHost.active == true
end

local function freecam_block_attack_controls()
    -- Ped stays AFK. Camera still reads WASD/space/ctrl as disabled.
    DisableControlAction(0, 30, true)
    DisableControlAction(0, 31, true)
    DisableControlAction(0, 32, true)
    DisableControlAction(0, 33, true)
    DisableControlAction(0, 34, true)
    DisableControlAction(0, 35, true)
    DisableControlAction(0, 21, true)
    DisableControlAction(0, 22, true)
    DisableControlAction(0, 36, true)
    DisableControlAction(0, 23, true)
    DisableControlAction(0, 75, true)
    DisableControlAction(1, 30, true)
    DisableControlAction(1, 31, true)
    DisableControlAction(1, 32, true)
    DisableControlAction(1, 33, true)
    DisableControlAction(1, 34, true)
    DisableControlAction(1, 35, true)
    DisableControlAction(0, 24, true)
    DisableControlAction(0, 25, true)
    DisableControlAction(0, 140, true)
    DisableControlAction(0, 141, true)
    DisableControlAction(0, 142, true)
    DisableControlAction(0, 257, true)
    DisableControlAction(0, 263, true)
    DisableControlAction(0, 264, true)
    DisableControlAction(1, 24, true)
    DisableControlAction(1, 140, true)
    DisableControlAction(1, 141, true)
    DisableControlAction(1, 142, true)
    DisableControlAction(2, 24, true)
    DisableControlAction(2, 140, true)
    if type(DisablePlayerFiring) == "function" then
        local pid = PlayerId()
        if pid then DisablePlayerFiring(pid, true) end
    end
end

function StaticFeatures.StartFreecamHost()
    -- Port of standalone ws_freecam.lua (click-confirmed 2026-08-25, 206.6 m). Camera flies,
    -- body stays. CALL existing spectate 14 + overlay -- do not edit those installers.
    --
    -- CreateCam / freeze MUST run inside this CreateThread, same as StartSpectateWSHost.
    -- The old host created the cam on the menu-click caller (NUI). That thread cannot
    -- legally CreateCam -- the inject payload even documents it -- so camReady stayed
    -- false, StartFreecam threw "freecam injection failed", and the toast said
    -- "Injection unavailable" even though we were not injecting.
    if _FreecamWSHost.threadRunning then return true end
    -- RUISOF is only required in WaveShield mode. When this host cam is used as the ReaperV4 fallback
    -- (bypass_c.lua broke the injected SafeRunNative CreateCam hop), RUISOF is not armed and not needed:
    -- ws_ruisof_direct already runs its body RAW host-side when RUISOF is absent and we're not on WS. The
    -- point of the fallback is exactly that raw host CreateCam -- a different caller path than the injected
    -- resource VM, so it may dodge Reaper's injected-CreateCam ban.
    local wsMode = type(StaticFeatures.waveshield_inject_mode) == "function"
        and StaticFeatures.waveshield_inject_mode()
    if wsMode then
        if type(_G.RUISOF) ~= "function" then
            pcall(StaticFeatures.ws_ensure_ready_bounded, "freecam", 6000)
        end
        if type(_G.RUISOF) ~= "function" then
            menu_dbg("^1[Static WS]^0 freecam: RUISOF missing — not starting")
            if type(StaticFeatures.menu_notify) == "function" then
                StaticFeatures.menu_notify("Freecam", "WaveShield bypass not ready — check F8", "error")
            end
            return false
        end
    end
    -- REAPER FAIL-CLOSED (2026-09-09): this host engine runs its cam + freeze + control-disable natives
    -- through ws_ruisof_direct, which off-WaveShield with no RUISOF drops to a RAW pcall(fn). On ReaperV4
    -- that is a raw CreateCam + raw per-frame DisableAllControlActions from a watched path -- it froze the
    -- ped, disabled every control, and the raw-native flood locked the client (forced restart). Reaper's
    -- hard rule is NEVER run cam natives raw. So if we reach the host engine on Reaper WITHOUT RUISOF,
    -- do NOT start it -- fail closed (no cam, no freeze) so the ped is never touched. The injected cam
    -- (StartFreecamInjected, laundered + fail-closed) is the Reaper path; this host engine is only the
    -- broken-bypass last resort, and a clean no-start beats a client lock.
    if not wsMode and type(_G.RUISOF) ~= "function"
        and type(StaticFeatures.reaper_present) == "function" and StaticFeatures.reaper_present() then
        menu_dbg("^1[Static]^0 freecam: Reaper host-cam fallback blocked (no RUISOF, refusing raw cam natives) — injected path failed, nothing safe left")
        if type(StaticFeatures.menu_notify) == "function" then
            StaticFeatures.menu_notify("Freecam", "Reaper: no safe cam path (broken bypass) — not starting", "error")
        end
        _FreecamWSHost.active = false
        _FreecamWSHost.threadRunning = false
        _G.__FG_CAM_READY = false
        return false
    end
    pcall(StaticFeatures.install_waveshield_spectate_hooks)

    _G.__WS_FREECAM_ON = false
    _G.__WS_SPEC_CAM_ON = true
    _G.__FG_CAM_READY = false
    _FreecamWSHost.active = true
    _FreecamWSHost.threadRunning = true

    CreateThread(function()
        local ped, cam, holdX, holdY, holdZ, holdH
        local created = false
        StaticFeatures.ws_ruisof_direct(function()
            ped = PlayerPedId()
            if not ped or ped == 0 or not DoesEntityExist(ped) then return end
            local pc = GetEntityCoords(ped)
            local hh = GetEntityHeading(ped) or 0.0
            local hp = _G.__FG_HOLD_POS
            -- ELECTRON 0,0,0 UNDER-MAP FIX (2026-09-10): this host capture used to commit pc RAW as the
            -- hold with NO validation, unlike the inject path (~10322) which guards it. On certain Electron
            -- servers GetEntityCoords(ped) here hands back ~(0,0,0), so the cam + the frozen ped both got
            -- planted at the map origin on freecam ENTER ("spawns me under the map / teleports me to 0,0,0").
            -- Same guard as the inject path: reject a near-origin / NaN / below-world read, fall back to the
            -- gameplay cam coord, and if THAT is also bogus, bail (don't start) rather than freeze at 0,0,0.
            local function bad_pos(p)
                if not p then return true end
                if p.x ~= p.x or p.y ~= p.y or p.z ~= p.z then return true end   -- NaN
                if (p.x * p.x + p.y * p.y) < 1.0 then return true end             -- ~origin
                if p.z < -150.0 or p.z > 1500.0 then return true end
                return false
            end
            if hp and hp.x and not bad_pos(hp) then
                holdX, holdY, holdZ = hp.x, hp.y, hp.z
                holdH = _G.__FG_HOLD_HEADING or hh
            else
                if bad_pos(pc) then
                    local c2 = (type(GetGameplayCamCoord) == "function") and GetGameplayCamCoord() or nil
                    if c2 and not bad_pos(c2) then
                        pc = c2
                    else
                        -- No trustworthy position this frame -- do NOT plant the cam/ped at the origin.
                        _FreecamWSHost.active = false
                        _FreecamWSHost.threadRunning = false
                        _G.__FG_CAM_READY = false
                        return
                    end
                end
                holdX, holdY, holdZ, holdH = pc.x, pc.y, pc.z, hh
            end
            cam = CreateCam("DEFAULT_SCRIPTED_CAMERA", true)
            if not cam or cam == 0 then return end
            if type(DoesCamExist) == "function" and not DoesCamExist(cam) then return end
            if type(IsCamAttached) == "function" and IsCamAttached(cam) and type(DetachCam) == "function" then
                DetachCam(cam)
            end
            SetCamCoord(cam, holdX, holdY, holdZ)
            SetCamRot(cam, -8.0, 0.0, holdH, 2)
            SetCamActive(cam, true)
            RenderScriptCams(true, true, 700, true, true)  -- smooth ease-in
            SetEntityInvincible(ped, true)
            SetEntityVisible(ped, true, false)
            SetBlockingOfNonTemporaryEvents(ped, true)
            SetPedCanRagdoll(ped, false)
            SetEntityHasGravity(ped, false)
            SetEntityVelocity(ped, 0.0, 0.0, 0.0)
            SetEntityCollision(ped, false, false)
            FreezeEntityPosition(ped, true)
            _G._FREECAM_CAM = cam
            _G.ESHAYFreecamObject = cam
            _G.__FG_CAM_POS = vector3(holdX, holdY, holdZ)
            _G.__FG_CAM_ROT = vector3(-8.0, 0.0, holdH)
            _G.__FG_HOLD_POS = vector3(holdX, holdY, holdZ)
            _G.__FG_HOLD_HEADING = holdH
            _G.__FG_CAM_READY = true
            created = true
        end, "freecam")
        if not created or not cam then
            menu_dbg("^1[Static WS]^0 freecam: CreateCam hop failed (script thread)")
            _FreecamWSHost.active = false
            _FreecamWSHost.threadRunning = false
            _G.__FG_CAM_READY = false
            _G.__WS_FREECAM_ON = false
            if _G.__WS_SPECTATE_ON ~= true then
                _G.__WS_SPEC_CAM_ON = false
            end
            return
        end
        _FreecamWSHost.ped = ped
        local camX, camY, camZ = holdX, holdY, holdZ
        local pitch, yaw = -8.0, holdH
        local function clamp(v, mn, mx)
            if v < mn then return mn end
            if v > mx then return mx end
            return v
        end
        local function rot_dir(p, yw)
            local z = math.rad(yw)
            local x = math.rad(p)
            local num = math.abs(math.cos(x))
            return vector3(-math.sin(z) * num, math.cos(z) * num, math.sin(x))
        end
        local function ctrl(n)
            return (IsControlPressed and IsControlPressed(0, n))
                or (IsDisabledControlPressed and IsDisabledControlPressed(0, n))
        end
        -- Reaper fallback throttle. On a broken-bypass Reaper server every wrapped-native call spams
        -- bypass_c.lua errors, and doing the ped re-pin + RenderScriptCams EVERY frame is what makes the
        -- host cam laggy there. WaveShield (wsMode) keeps the original per-frame behaviour untouched; the
        -- Reaper path re-pins the ped ~10x/sec and calls RenderScriptCams once, which cuts the spam hard
        -- without hurting cam smoothness (the cam coord/rot below still update every frame).
        local wsMode = type(StaticFeatures.waveshield_inject_mode) == "function"
            and StaticFeatures.waveshield_inject_mode()
        local __fcTick = 0
        local __fcRendered = false
        while _FreecamWSHost.active do
            Wait(0)
            __fcTick = __fcTick + 1
            -- Delta-time: frame-rate-independent movement (same approach as guided missile engine).
            -- Old code was per-frame fixed step — half speed at 30fps, double at 120fps.
            local __fcDt = (type(GetFrameTime) == "function" and GetFrameTime()) or 0.016
            if __fcDt <= 0.0 or __fcDt > 0.25 then __fcDt = 0.016 end
            DisableAllControlActions(0)
            EnableControlAction(0, 1, true)
            EnableControlAction(0, 2, true)
            freecam_block_attack_controls()

            local mx = GetDisabledControlNormal(0, 1) * 12.0
            local my = GetDisabledControlNormal(0, 2) * 12.0
            pitch = clamp(pitch - my, -89.9, 89.9)
            yaw = yaw - mx
            -- Speed in units/sec * dt. Factor of 60 preserves the old per-frame feel at 60fps
            -- while staying consistent at any framerate (old: spd added raw each frame).
            local spd = (_G._FREECAM_SPEED or 1.0) * (ctrl(21) and 6.0 or 1.0) * 60.0 * __fcDt
            local fwd = rot_dir(pitch, yaw)
            local right = vector3(fwd.y, -fwd.x, 0.0)
            if ctrl(32) then camX = camX + fwd.x * spd; camY = camY + fwd.y * spd; camZ = camZ + fwd.z * spd end
            if ctrl(33) then camX = camX - fwd.x * spd; camY = camY - fwd.y * spd; camZ = camZ - fwd.z * spd end
            if ctrl(34) then camX = camX - right.x * spd; camY = camY - right.y * spd; camZ = camZ - right.z * spd end
            if ctrl(35) then camX = camX + right.x * spd; camY = camY + right.y * spd; camZ = camZ + right.z * spd end
            if ctrl(22) then camZ = camZ + spd end
            if ctrl(36) then camZ = camZ - spd end

            -- Overlay Teleport My Player: adopt the new AFK park. Camera / WASD / focus stay as-is.
            local park = _G.__FC_TELEPORT_PARK
            if type(park) == "table" and park.x then
                holdX, holdY, holdZ = park.x, park.y, park.z
                if park.h ~= nil then holdH = park.h end
                _G.__FC_TELEPORT_PARK = nil
            end

            local applyX, applyY, applyZ, applyP, applyYw = camX, camY, camZ, pitch, yaw
            _G.__FG_CAM_POS = vector3(applyX, applyY, applyZ)
            _G.__FG_CAM_ROT = vector3(applyP, 0.0, applyYw)
            _G.__FG_HOLD_POS = vector3(holdX, holdY, holdZ)
            _G.__FG_HOLD_HEADING = holdH

            -- Spectate hold: freeze, re-pin only if drift > 0.2 m. No per-tick teleport home.
            -- Ped is frozen + collision off + gravity off — it's not going anywhere. Re-asserting
            -- every frame was pure churn. WS: every 4th (~15/sec), Reaper: every 6th (~10/sec).
            if (wsMode and (__fcTick % 4) == 0) or (not wsMode and (__fcTick % 6) == 0) then
            StaticFeatures.ws_ruisof_direct(function()
                local ent = ped
                if not ent or ent == 0 or not DoesEntityExist(ent) then ent = PlayerPedId() end
                if not ent or ent == 0 or not DoesEntityExist(ent) then return end
                SetEntityHasGravity(ent, false)
                SetEntityVelocity(ent, 0.0, 0.0, 0.0)
                SetEntityCollision(ent, false, false)
                FreezeEntityPosition(ent, true)
                local c = GetEntityCoords(ent)
                if c and #(vector3(c.x, c.y, c.z) - vector3(holdX, holdY, holdZ)) > 0.2 then
                    FreezeEntityPosition(ent, false)
                    SetEntityCoordsNoOffset(ent, holdX, holdY, holdZ, false, false, false)
                    SetEntityHeading(ent, holdH or 0.0)
                    FreezeEntityPosition(ent, true)
                end
            end, "freecam")
            end

            -- PERF: cam coord/rot, focus and collision are camera/streamer natives, NOT ped-
            -- manipulation natives — they don't need the RUISOF wrapper. Guided missile calls
            -- these directly on all servers with no detections. Pulling them out saves ~12 global
            -- table ops + 1 pcall/frame of wrapper overhead.
            do
                local c = cam
                if not c or not DoesCamExist(c) then
                    _FreecamWSHost.active = false
                else
                    if type(IsCamAttached) == "function" and IsCamAttached(c) and type(DetachCam) == "function" then
                        DetachCam(c)
                    end
                    SetCamCoord(c, applyX, applyY, applyZ)
                    SetCamRot(c, applyP, 0.0, applyYw, 2)
                    -- Reaper: RenderScriptCams only needs to fire once to activate the cam; re-calling it every
                    -- frame just spams Reaper's broken bypass. WaveShield keeps re-asserting it per-frame.
                    if wsMode or not __fcRendered then
                        RenderScriptCams(true, false, 0, true, true)
                        __fcRendered = true
                    end
                    -- Collision streamer: every 6th frame (~10/sec) is plenty. Per-frame thrashed it
                    -- and was the biggest FPS drain (same fix as the inject freecam path).
                    if (__fcTick % 6) == 0 and type(RequestCollisionAtCoord) == "function" then
                        RequestCollisionAtCoord(applyX, applyY, applyZ)
                    end
                    -- Focus follows the camera. SetFocusPosAndVel every frame drives streaming toward
                    -- the cam — this one stays per-frame (it's cheap, and focus-at-body was the hole
                    -- that killed player_freecam / attempt 4).
                    if type(SetFocusPosAndVel) == "function" then
                        SetFocusPosAndVel(applyX, applyY, applyZ, 0.0, 0.0, 0.0)
                    end
                end
            end
        end

        StaticFeatures.ws_ruisof_direct(function()
            if cam and DoesCamExist(cam) then
                if type(IsCamAttached) == "function" and IsCamAttached(cam) and type(DetachCam) == "function" then
                    DetachCam(cam)
                end
                SetCamActive(cam, false)
                RenderScriptCams(false, true, 700, true, true)  -- smooth ease-out
                Wait(700)                                       -- let the blend finish before destroy
                DestroyCam(cam, false)
            end
            _G._FREECAM_CAM = nil
            _G.ESHAYFreecamObject = nil
            local ent = ped
            if not ent or ent == 0 or not DoesEntityExist(ent) then ent = PlayerPedId() end
            if ent and ent ~= 0 and DoesEntityExist(ent) then
                FreezeEntityPosition(ent, false)
                if holdX then
                    local c = GetEntityCoords(ent)
                    if not c or #(vector3(c.x, c.y, c.z) - vector3(holdX, holdY, holdZ)) > 0.2 then
                        SetEntityCoordsNoOffset(ent, holdX, holdY, holdZ, false, false, false)
                        SetEntityHeading(ent, holdH or 0.0)
                    end
                end
                SetEntityVisible(ent, true, false)
                SetEntityVelocity(ent, 0.0, 0.0, 0.0)
                SetEntityHasGravity(ent, true)
                SetEntityCollision(ent, true, true)
                SetEntityInvincible(ent, false)
                SetBlockingOfNonTemporaryEvents(ent, false)
                SetPedCanRagdoll(ent, true)
            end
            if type(ClearFocus) == "function" then ClearFocus() end
        end, "freecam")
        _G.__FG_CAM_READY = false
        _G.__WS_FREECAM_ON = false
        if _G.__WS_SPECTATE_ON ~= true then
            _G.__WS_SPEC_CAM_ON = false
        end
        _FreecamWSHost.threadRunning = false
    end)

    menu_dbg("^2[Static WS]^0 freecam host thread started (CreateCam on script thread, same as spectate)")
    return true
end

function StaticFeatures.StopFreecamHost()
    _FreecamWSHost.active = false
    _G.__WS_FREECAM_ON = false
    _G.__FG_DRAG_ARMED = false
    _G.__FG_BLACKHOLE_PULL = false
    _G.__FG_SPAWN_ANIMAL = nil
    _G.__FG_ANIMAL_LOAD = nil
    _G.__FG_SHOOT_FIRE = false
    -- Do not clear __WS_FREECAM_HOOKS_READY -- that overlay is shared with spectate.
    if _G.__WS_SPECTATE_ON ~= true then
        _G.__WS_SPEC_CAM_ON = false
    end
end

-- Overlay extras on WaveShield (user-authorized 2026-08-25). Separate thread from the locked
-- StartFreecamHost cam tick. Consumes the same host flags the inject extras thread used to.
function StaticFeatures.StartFreecamHostExtras()
    if _FreecamWSHost.extrasRunning then return true end
    _FreecamWSHost.extrasRunning = true
    CreateThread(function()
        local function hop(fn)
            if type(StaticFeatures.ws_ruisof_direct) == "function" then
                return StaticFeatures.ws_ruisof_direct(fn, "freecam")
            end
            return false
        end
        local function rotDir(rot)
            if not rot then return vector3(0.0, 1.0, 0.0) end
            local z = math.rad(tonumber(rot.z) or 0.0)
            local x = math.rad(tonumber(rot.x) or 0.0)
            local num = math.abs(math.cos(x))
            return vector3(-math.sin(z) * num, math.cos(z) * num, math.sin(x))
        end
        while _FreecamWSHost.active and (_FREECAM_RUNNING or _G._FREECAM_RUNNING) do
            Wait(0)
            if not (_G.__FG_SPAWN_ANIMAL or _G.__FG_ANIMAL_LOAD or _G.__FG_DRAG_ARMED or _G.__FG_BLACKHOLE_PULL) then
                -- Idle: do not add a second RUISOF hop on top of the locked cam tick.
            else
            hop(function()
                local cam = _G._FREECAM_CAM
                local camCoords = _G.__FG_CAM_POS
                local camRot = _G.__FG_CAM_ROT
                if cam and cam ~= 0 and type(DoesCamExist) == "function" and DoesCamExist(cam) then
                    camCoords = GetCamCoord(cam)
                    camRot = GetCamRot(cam, 2)
                end
                if not camCoords or not camRot then return end
                local dir = rotDir(camRot)

                local animal = _G.__FG_SPAWN_ANIMAL
                if type(animal) == "string" and animal ~= "" then
                    _G.__FG_SPAWN_ANIMAL = nil
                    local hash = GetHashKey(animal)
                    RequestModel(hash)
                    _G.__FG_ANIMAL_LOAD = { hash = hash, deadline = GetGameTimer() + 2500 }
                end
                local load = _G.__FG_ANIMAL_LOAD
                if type(load) == "table" then
                    if HasModelLoaded(load.hash) then
                        local spawnPos = camCoords + (dir * 2.0)
                        local ped = CreatePed(1, load.hash, spawnPos.x, spawnPos.y, spawnPos.z, camRot.z, true, false)
                        if (not ped or ped == 0) then
                            ped = CreatePed(28, load.hash, spawnPos.x, spawnPos.y, spawnPos.z, camRot.z, true, false)
                        end
                        if ped and ped ~= 0 and DoesEntityExist(ped) then
                            SetEntityAsMissionEntity(ped, true, true)
                            SetEntityVelocity(ped, dir.x * 50.0, dir.y * 50.0, dir.z * 50.0)
                        end
                        SetModelAsNoLongerNeeded(load.hash)
                        _G.__FG_ANIMAL_LOAD = nil
                    elseif GetGameTimer() > (load.deadline or 0) then
                        SetModelAsNoLongerNeeded(load.hash)
                        _G.__FG_ANIMAL_LOAD = nil
                    end
                end

                if _G.__FG_DRAG_ARMED then
                    local lmb = IsDisabledControlPressed(0, 24) or IsControlPressed(0, 24)
                    local lmbJust = IsDisabledControlJustPressed(0, 24) or IsControlJustPressed(0, 24)
                    local ent = _G.__FG_DRAG_ENT
                    if lmbJust and (not ent or not DoesEntityExist(ent)) then
                        local far = camCoords + dir * 200.0
                        local ray = StartShapeTestRay(
                            camCoords.x, camCoords.y, camCoords.z,
                            far.x, far.y, far.z,
                            10, PlayerPedId(), 0
                        )
                        local _, _, _, _, hitEnt = GetShapeTestResult(ray)
                        local veh = 0
                        if hitEnt and hitEnt ~= 0 then
                            if IsEntityAVehicle(hitEnt) then
                                veh = hitEnt
                            elseif IsEntityAPed(hitEnt) and IsPedInAnyVehicle(hitEnt, false) then
                                veh = GetVehiclePedIsIn(hitEnt, false)
                            end
                        end
                        if veh and veh ~= 0 then
                            _G.__FG_DRAG_ENT = veh
                            _G.__FG_DRAG_DIST = 8.0
                            ent = veh
                        end
                    end
                    ent = _G.__FG_DRAG_ENT
                    if ent and DoesEntityExist(ent) and lmb then
                        NetworkRequestControlOfEntity(ent)
                        local dest = camCoords + dir * (_G.__FG_DRAG_DIST or 8.0)
                        SetEntityCoordsNoOffset(ent, dest.x, dest.y, dest.z, false, false, false)
                        SetEntityVelocity(ent, 0.0, 0.0, 0.0)
                    elseif not lmb then
                        _G.__FG_DRAG_ENT = nil
                    end

                    -- NEXUS DRAG OUTLINE (user, 2026-10-17): highlight the targeted vehicle. If we're actively
                    -- holding one (LMB + __FG_DRAG_ENT) outline it ORANGE; otherwise raycast the hover target
                    -- and outline it BLUE so you can see what you'd grab. Clears when nothing's targeted.
                    do
                        local held = (ent and DoesEntityExist(ent) and lmb) and ent or nil
                        local outlineEnt = held
                        if not outlineEnt then
                            -- hover: raycast what's under the crosshair
                            local far2 = camCoords + dir * 200.0
                            local hray = StartShapeTestRay(camCoords.x, camCoords.y, camCoords.z,
                                far2.x, far2.y, far2.z, 10, PlayerPedId(), 0)
                            local _, _, _, _, hoverEnt = GetShapeTestResult(hray)
                            if hoverEnt and hoverEnt ~= 0 and DoesEntityExist(hoverEnt) then
                                if IsEntityAVehicle(hoverEnt) then
                                    outlineEnt = hoverEnt
                                elseif IsEntityAPed(hoverEnt) and IsPedInAnyVehicle(hoverEnt, false) then
                                    outlineEnt = GetVehiclePedIsIn(hoverEnt, false)
                                end
                            end
                        end
                        local prev = _G.__FG_DRAG_OUTLINE
                        if prev and prev ~= outlineEnt and DoesEntityExist(prev) then
                            if SetEntityDrawOutline then SetEntityDrawOutline(prev, false) end
                        end
                        if outlineEnt and outlineEnt ~= 0 and DoesEntityExist(outlineEnt) then
                            if SetEntityDrawOutlineShader then SetEntityDrawOutlineShader(1) end
                            if SetEntityDrawOutlineColor then
                                if held then
                                    SetEntityDrawOutlineColor(255, 140, 0, 255)   -- orange: holding
                                else
                                    SetEntityDrawOutlineColor(0, 170, 255, 255)    -- blue: hovering
                                end
                            end
                            if SetEntityDrawOutline then SetEntityDrawOutline(outlineEnt, true) end
                            _G.__FG_DRAG_OUTLINE = outlineEnt
                        else
                            _G.__FG_DRAG_OUTLINE = nil
                        end
                    end
                else
                    _G.__FG_DRAG_ENT = nil
                    -- clear any drag outline when drag isn't armed
                    local prev = _G.__FG_DRAG_OUTLINE
                    if prev and DoesEntityExist(prev) and SetEntityDrawOutline then
                        SetEntityDrawOutline(prev, false)
                    end
                    _G.__FG_DRAG_OUTLINE = nil
                end

                if _G.__FG_BLACKHOLE_PULL then
                    local target = camCoords + dir * 15.0
                    local ids = type(StaticFeatures.get_selected_player_ids) == "function"
                        and StaticFeatures.get_selected_player_ids() or nil
                    local sid = ids and ids[1] and tonumber(ids[1])
                    if sid and sid > 0 then
                        local pIdx = GetPlayerFromServerId(sid)
                        if pIdx and pIdx ~= -1 then
                            local tPed = GetPlayerPed(pIdx)
                            if tPed and tPed ~= 0 and DoesEntityExist(tPed) then
                                target = GetEntityCoords(tPed)
                            end
                        end
                    end
                    local pool = (type(GetGamePool) == "function" and GetGamePool("CVehicle")) or {}
                    local n = math.min(#pool, 24)
                    for i = 1, n do
                        local veh = pool[i]
                        if veh and DoesEntityExist(veh) then
                            local vc = GetEntityCoords(veh)
                            local dx, dy, dz = target.x - vc.x, target.y - vc.y, target.z - vc.z
                            local d = math.sqrt(dx * dx + dy * dy + dz * dz)
                            if d > 0.2 and d < 80.0 then
                                NetworkRequestControlOfEntity(veh)
                                local s = 40.0 / math.max(d, 4.0)
                                ApplyForceToEntity(veh, 1, dx * s, dy * s, dz * s + 2.0, 0.0, 0.0, 0.0, 0, false, true, true, false, true)
                            end
                        end
                    end
                end
            end)
            end
        end
        _FreecamWSHost.extrasRunning = false
        _G.__FG_DRAG_ENT = nil
        _G.__FG_ANIMAL_LOAD = nil
    end)
    return true
end

-- Additions to the neuter below, ported from the Sinful/satanic/larp FiniAC bypass. The stock payload
-- is Lua-only and leaves four things open that that bypass covers: TriggerEvent (it filters only
-- TriggerServerEvent, so FiniAC's whole CLIENT-side event chain still fires), FiniAC's own registered
-- events, its NUI callbacks (the screenshot/evidence path), and the _G.FiniAC table itself.
--
-- ORDER IS LOAD-BEARING: this runs BEFORE the verbatim payload, because that payload ENDS by nulling
-- the entire stdlib inside FiniAC's VM (ipairs/pairs/pcall stubbed, string/table/math/debug/_G = nil).
-- Anything needing a real ipairs or pcall has to have already run. What we register here keeps working
-- afterwards: the handlers are closures that touch no stdlib, and `e:lower():find(...)` resolves via
-- the string metatable captured at VM init rather than the `string` global -- which is exactly why the
-- original's own TriggerServerEvent filter still works after the nuke.
--
-- NOT ported: the JS half of the Sinful bypass (window.FiniAC.* stubs, window.dm.requestScreenshot /
-- takeScreenshot, window.fu.requestRecording). That needs JS injected INTO FiniAC's own NUI frame, and
-- Shark has no equivalent -- SharkAPI.ExecuteJS(code) takes no resource argument, so it cannot target
-- another resource's frame. apply_finiac_bypass instead calls RemoveResourceNui to delete the frame
-- outright, which reaches the same end by removing the surface rather than neutering functions on it.
StaticFeatures.FINIAC_NUI_EVENT_PATCH = [[
if type(TriggerEvent) == "function" then
    local _oldTriggerEvent = TriggerEvent
    TriggerEvent = function(e, ...)
        if type(e) == "string" then
            local l = e:lower()
            local b = {"fini","anticheat","ban","kick","cheat","detection","log","violation"}
            for i = 1, #b do if l:find(b[i], 1, true) then return end end
        end
        return _oldTriggerEvent(e, ...)
    end
end

if type(AddEventHandler) == "function" then
    local ev = {
        "FiniAC.verify", "FiniAC.heartbeat", "FiniAC.detection", "FiniAC.ping",
        "FiniAC:verify", "FiniAC:heartbeat", "FiniAC:detection", "fini_events",
    }
    for i = 1, #ev do pcall(AddEventHandler, ev[i], function() return end) end
end

if type(RegisterNUICallback) == "function" then
    local cb = {
        "FiniAC.screenshot", "FiniAC.verify", "FiniAC.heartbeat",
        "FiniAC.detection", "FiniAC.recording", "fini_events",
    }
    for i = 1, #cb do
        pcall(RegisterNUICallback, cb[i], function(_, done)
            if type(done) == "function" then done({}) end
        end)
    end
end

do
    local t = rawget(_G, "FiniAC") or rawget(_G, "finiAC")
    if type(t) == "table" then
        if type(t.check_integrity) == "function" then t.check_integrity = function() return true, "ok" end end
        if type(t.scan_memory)     == "function" then t.scan_memory     = function() return false end end
        if type(t.is_debugged)     == "function" then t.is_debugged     = function() return false end end
        if type(t.send_heartbeat)  == "function" then t.send_heartbeat  = function() return true end end
        if type(t.detectCheat)     == "function" then t.detectCheat     = function() return false end end
        if type(t.reportViolation) == "function" then t.reportViolation = function() return end end
        if t.running ~= nil then t.running = false end
        if type(t.thread_func) == "function" then t.thread_func = function() end end
    end
end
]]

-- FiniAC bypass, Shark-side. Two mechanical swaps from the source: MachoInjectResource2's thread-id
-- parameter has no equivalent in SharkAPI.Inject, and the original's MachoResourceStop/Start polling
-- loop cannot be ported (Shark exposes StopResource but no StartResource) -- SharkAPI.Resources.
-- OnResourceRestart reaches the same goal by event instead of by timer. The neuter payload itself is
-- verbatim. It is injected as FINIAC_NUI_EVENT_PATCH .. FINIAC_NEUTER_INJECT (see finiac_payload()).
StaticFeatures.FINIAC_NEUTER_INJECT = [[
if _G["FiniAC_MainThread"] then Citizen.StopThread(_G["FiniAC_MainThread"]) _G["FiniAC_MainThread"]=nil end local _0xb=function()return true,nil,false end assert=_0xb collectgarbage=_0xb dofile=_0xb error=_0xb getmetatable=_0xb load=_0xb loadfile=_0xb require=_0xb CreateThread=_0xb Citizen.CreateThread=_0xb DuplicateFunctionReference=nil local oldTriggerServerEvent=TriggerServerEvent TriggerServerEvent=function(e,...) local b={"fini","anticheat","ban","kick","cheat","detection","log","violation"} for i=1,#b do if e:lower():find(b[i]) then return end end return oldTriggerServerEvent(e,...) end local b={"DisableControlAction","GetVehiclePedIsIn","NetworkGetEntityOwner","GetEntityModel","GetResourceState","GetInvokingResource","LoadResourceFile","GetNumResourceMetadata","IsControlJustPressed","IsControlPressed","playerConnecting","playerDropped","onResourceStart","onResourceStop","entityCreated","entityCreating","entityRemoved","explosionEvent","weaponDamageEvent","vehicleComponentControlEvent","giveWeaponEvent","removeWeaponEvent","removeAllWeaponsEvent","ptFxEvent","startProjectileEvent","fireEvent","DoesEntityExist","NetworkGetFirstEntityOwner"} for i=1,#b do local f=b[i] if _G[f] then _G[f]=function(...)return false end end end if GetEntitySpeed then local o=GetEntitySpeed GetEntitySpeed=function(e,...) local s=o(e,...) if s>100.0 then return 50.0 end return s end end if GetEntityVelocity then local o=GetEntityVelocity GetEntityVelocity=function(e,...) return o(e,...) end end local e=function()end assert=e collectgarbage=e dofile=e error=true getmetatable=e ipairs=e load=e loadfile=e next=e pairs=e print=e rawequal=e rawget=e rawlen=e rawset=e select=e setmetatable=e tonumber=e tostring=e type=e require=e CreateThread=e pcall=e xpcall=e getfenv=e setfenv=e unpack=e loadstring=e module=e joaat=e oldWait=nil string=nil table=nil math=nil io=nil os=nil debug=nil coroutine=nil json=nil package=nil newproxy=nil DuplicateFunctionReference=nil bit=nil bit32=nil utf8=nil _G=nil _VERSION=nil
]]

-- Resource-fingerprint match (files present, not name) -- FiniAC renames its own resource per-server,
-- same reason find_fiveguard_resource() above does a file/metadata scan instead of trusting a fixed
-- name. LoadResourceFile/GetNumResources/GetResourceByFindIndex are plain CitizenFX natives, safe to
-- call directly from host context (no injection needed, matching find_fiveguard_resource's own style).
function StaticFeatures.finiac_resource_name(forceRefresh)
    if not forceRefresh and StaticFeatures._finiac_resource_cache ~= nil then
        return StaticFeatures._finiac_resource_cache ~= false and StaticFeatures._finiac_resource_cache or nil
    end
    local files = { "anticheat.html", "fini_events.js", "fini_events.lua", "client/client.js" }
    local total = _static_num_resources()
    for i = 0, total - 1 do
        local res = _static_resource_by_index(i)
        if res then
            local matched = true
            for j = 1, #files do
                local okLoad, content = pcall(LoadResourceFile, res, files[j])
                if not (okLoad and content) then
                    matched = false
                    break
                end
            end
            if matched then
                StaticFeatures._finiac_resource_cache = res
                return res
            end
        end
    end
    StaticFeatures._finiac_resource_cache = false
    return nil
end

function StaticFeatures.finiac_present()
    return StaticFeatures.finiac_resource_name(false) ~= nil
end

-- Patch first, verbatim neuter second -- see the FINIAC_NUI_EVENT_PATCH header for why that order is
-- required (the neuter ends by nulling the stdlib the patch needs).
function StaticFeatures.finiac_payload()
    return (StaticFeatures.FINIAC_NUI_EVENT_PATCH or "") .. (StaticFeatures.FINIAC_NEUTER_INJECT or "")
end

-- No "_applied" guard like Reaper/WaveShield's bypass -- FiniAC's own Lua state resets on restart,
-- so the neuter-inject genuinely needs to run again every time, not just once per session.
function StaticFeatures.apply_finiac_bypass(silent)
    local resource = StaticFeatures.finiac_resource_name(true)
    if not resource then return false end

    local payload = StaticFeatures.finiac_payload()
    local api = StaticShark and StaticShark.api and StaticShark.api()
    local ok = false
    if api and type(api.InjectSafe) == "function" then
        ok = pcall(api.InjectSafe, resource, payload) == true
    end
    if not ok and type(StaticShark.inject) == "function" then
        ok = StaticShark.inject(resource, payload) == true
    end

    -- Delete FiniAC's NUI frame before stopping it. This is the Shark stand-in for the Sinful bypass's
    -- MachoDestroyDui + its window.dm.requestScreenshot / window.fu.requestRecording stubs: we cannot
    -- inject JS into another resource's frame, but removing the frame takes the whole JS half with it,
    -- screenshot and recording handlers included. Done BEFORE the stop so the frame is gone either way
    -- if the stop is refused.
    if ok and type(StaticShark.remove_resource_nui) == "function" then
        pcall(StaticShark.remove_resource_nui, resource)
    end

    if ok and type(StaticShark.stop_resource) == "function" then
        pcall(StaticShark.stop_resource, resource)
    end

    StaticFeatures._finiac_bypass_applied = ok
    _G.__STATIC_FINIAC_BYPASS = ok
    if not silent then
        if ok then
            StaticFeatures.menu_notify("FiniAC", "Bypass applied", "success")
        else
            StaticFeatures.menu_notify("FiniAC", "Bypass failed", "error")
        end
    end
    return ok
end

-- ON-DEMAND FiniAC ARM (2026-09-10, user "FiniAC bypass doesnt actually load on inject i got banned bc it
-- didnt load fast enough bro and i put on smth"): the FiniAC neuter used to be applied ONLY dead-last in
-- defer_join_ac_detection (~5486), after a 2.5s (or 8s+keybind on the Shark shim) initial wait PLUS the
-- WaveShield/FiveGuard deep-scan chain -- so it landed ~5-20s post-inject, and NOTHING armed it when a
-- feature was toggled (ensure_fini_bypass_armed arms the OTHER, older __FINI_BYPASS, not FiniAC). Toggling
-- a detectable feature in that window fired it under a live FiniAC -> ban. This is the FiniAC analogue of
-- ensure_fini_bypass_armed: apply the neuter NOW if FiniAC is present and it hasn't been applied yet.
-- Idempotent -- gated on __STATIC_FINIAC_BYPASS so repeat calls (feature toggles) don't re-inject; the
-- OnResourceRestart hook (in detect_finiac_on_join) clears the flag so a restarted FiniAC re-neuters.
function StaticFeatures.ensure_finiac_bypass_armed()
    if _G.__STATIC_FINIAC_BYPASS == true then return true end
    if not (StaticFeatures.finiac_present and StaticFeatures.finiac_present()) then return false end
    return pcall(StaticFeatures.apply_finiac_bypass, true) == true and _G.__STATIC_FINIAC_BYPASS == true
end

StaticFeatures._finiac_restart_hook_installed = false

function StaticFeatures.detect_finiac_on_join()
    -- Idempotent: once the neuter is applied (and the restart hook installed) a second call -- e.g. the
    -- new EARLY arm in defer_join_ac_detection plus the original dead-last call -- must not re-inject.
    if _G.__STATIC_FINIAC_BYPASS == true then
        StaticFeatures._finiac_on_join = true
        return true
    end
    StaticFeatures._finiac_on_join = false
    local resource = StaticFeatures.finiac_resource_name(true)
    if resource then
        StaticFeatures._finiac_on_join = true
        menu_dbg("^2[Static]^0 FiniAC detected (" .. tostring(resource) .. ") — applying bypass")
        pcall(StaticFeatures.apply_finiac_bypass, true)

        -- Keep re-neutering it if it ever comes back -- see the header comment above for why this
        -- is OnResourceRestart instead of the original's manual stop/start polling loop.
        -- Was gated on `restartedName == resource` (the name captured at first detection) -- but
        -- finiac_resource_name() matches by FILE FINGERPRINT specifically because FiniAC renames
        -- itself (see that function's own comment), and if it also renames on restart (not just
        -- per server boot), a restarted resource under a NEW name would never equal the captured
        -- `resource` and this would silently stop re-neutering forever. Re-scan by fingerprint on
        -- every restart event instead of trusting the name to stay the same.
        if not StaticFeatures._finiac_restart_hook_installed
            and type(SharkAPI) == "table" and type(SharkAPI.Resources) == "table"
            and type(SharkAPI.Resources.OnResourceRestart) == "function" then
            StaticFeatures._finiac_restart_hook_installed = true
            pcall(SharkAPI.Resources.OnResourceRestart, function(restartedName)
                local stillPresent = StaticFeatures.finiac_resource_name(true)
                if stillPresent and tostring(restartedName) == tostring(stillPresent) then
                    StaticFeatures._finiac_bypass_applied = false
                    pcall(StaticFeatures.apply_finiac_bypass, true)
                end
            end)
        end
    end
    return StaticFeatures._finiac_on_join
end

-- ═══════════════════════════════════════════════════════════════════════════════════════════════════════
-- Quantum / The Lands of LA — anti-spoof bypass (ported from peep build, 2026-10-03).
-- REPLACES QBR v7. Instead of injecting a payload into the quantum VM, this uses
-- SharkAPI.BlockServerEvent to silently drop the detection/report events at the API level.
-- Cleaner, no injection required, and covers the entity-creation reports QBR v7 never handled.
-- ═══════════════════════════════════════════════════════════════════════════════════════════════════════

function StaticFeatures.quantum_present()
    if type(GetResourceState) ~= "function" then return false end
    local st = GetResourceState("quantum")
    return st == "started" or st == "starting"
end

-- The 9 names, verbatim from the CONFIRMED tla_antispoof.lua. The last two are
-- the ox_lib callbacks quantum uses to pull server-authored detection chunks and
-- load() them client-side - blocking those means the dynamic detections never
-- arrive at all. Never block a heartbeat: going silent drops you harder.
StaticFeatures.QUANTUM_SPOOF_TSE = {
    "quantum:activeSpoofDetected",
    "vehThrowing",
    "report_cheater_self",
    "VoiceProxExceeded",
    "onPlayerPedChanged",
    "requestBubbleValidationDetections",
    "requestVehicleValidationDetections",
    -- clientQAC:entCheck is the INBOUND request that makes this client resolve a net id,
    -- call GetEntityScript on it and answer; flagClient is the OUTBOUND report.
    "clientQAC:entCheck",
    "flagClient",
}

-- ── BADDIES ZONE ACCESS (anti-eject) ────────────────────────────────────────────────────────
-- nn_baddies_script is female-only. Its entire entry gate is one statebag read.
-- The write and the readback both belong inside a resource VM.
StaticFeatures.BADDIES_KEY = "isFemale"
StaticFeatures.BADDIES_MARK = "__static_baddies"

function StaticFeatures.tla_baddies_access()
    -- [[ QUIET BOOT 2026-10-04 ]] the baddies-zone write is a FEATURE (opt-in), not a bypass.
    -- It used to ride the antispoof arm, which is how an InjectSafe into es_extended ended up on
    -- the boot path and self-reported to Quantum. Default OFF; also refused during quiet boot.
    if _G.__STATIC_TLA_BADDIES_ENABLED ~= true then
        if type(_G.__ST) == "function" then _G.__ST("REFUSED tla_baddies_access", "not enabled") end
        return false
    end
    if type(_G.__STATIC_QUIET) == "function" and _G.__STATIC_QUIET() then
        if type(_G.__ST) == "function" then _G.__ST("REFUSED tla_baddies_access", "quiet boot") end
        return false
    end
    if _G.__STATIC_BADDIES_ON then return true end
    if type(StaticFeatures.quantum_present) ~= "function" or not StaticFeatures.quantum_present() then
        return false
    end
    if _static_resource_state("nn_baddies_script") ~= "started" then return false end

    if type(SharkAPI) == "table" and type(SharkAPI.BlockClientEvent) == "function" then
        pcall(SharkAPI.BlockClientEvent, true, "nn_baddies:timeUp")
    end

    local target = "es_extended"
    if _static_resource_state(target) ~= "started" then
        menu_dbg("^1[Static baddies]^0 " .. target .. " not started - no VM to write from")
        return false
    end

    local KEY = StaticFeatures.BADDIES_KEY
    local MARK = StaticFeatures.BADDIES_MARK
    local NL = "\n"

    local code = table.concat({
        'local MINE = GetCurrentResourceName()', NL,
        'if MINE ~= "', target, '" then return end', NL,
        'local KEY = "', KEY, '"', NL,
        'local MARK = "', MARK, '"', NL,
        'CreateThread(function()', NL,
        '    local before = LocalPlayer.state[KEY]', NL,
        '    print("[BADDIE-VM] before " .. KEY .. " = " .. tostring(before))', NL,
        '    pcall(function() LocalPlayer.state:set(KEY, true, true) end)', NL,
        '    local after, waited = nil, 0', NL,
        '    while waited < 3000 do', NL,
        '        Wait(100)', NL,
        '        waited = waited + 100', NL,
        '        after = LocalPlayer.state[KEY]', NL,
        '        if after == true then break end', NL,
        '    end', NL,
        '    print("[BADDIE-VM] after " .. KEY .. " = " .. tostring(after))', NL,
        '    pcall(function() LocalPlayer.state:set(MARK, (after == true) and "ok" or "refused", false) end)', NL,
        '    while true do', NL,
        '        Wait(15000)', NL,
        '        if LocalPlayer.state[KEY] ~= true then', NL,
        '            pcall(function() LocalPlayer.state:set(KEY, true, true) end)', NL,
        '        end', NL,
        '    end', NL,
        'end)', NL,
    })

    pcall(function() LocalPlayer.state:set(MARK, false, false) end)
    local ok = false
    if type(StaticFeatures.shark_inject) == "function" then
        ok = StaticFeatures.shark_inject(target, code) == true
    elseif type(SharkAPI) == "table" and type(SharkAPI.InjectSafe) == "function" then
        ok = pcall(SharkAPI.InjectSafe, target, code)
    end
    if not ok then
        menu_dbg("^1[Static baddies]^0 delivery failed")
        return false
    end

    _G.__STATIC_BADDIES_ON = true
    menu_dbg("^2[Static baddies]^0 armed - isFemale written inside " .. target
        .. ", nn_baddies:timeUp blocked")
    return true
end

function StaticFeatures.quantum_arm_antispoof()
    -- [[ QUIET BOOT 2026-10-04 ]] refuse to arm while quantum is started AND the user has not
    -- activated a row. Arming at boot fires the BlockServerEvent storm + InjectSafe that Quantum's
    -- per-VM clientHook self-reports -> the on-inject ban. Opens the instant the user acts.
    if type(_G.__STATIC_QUIET) == "function" and _G.__STATIC_QUIET() then
        if type(_G.__ST) == "function" then _G.__ST("REFUSED quantum_arm_antispoof", "quiet boot") end
        return false
    end
    if _G.__STATIC_QUANTUM_SPOOF_ON then return true end
    if type(SharkAPI) ~= "table" then return false end
    local names = StaticFeatures.QUANTUM_SPOOF_TSE
    local n = 0
    for i = 1, #names do
        local nm = names[i]
        if type(SharkAPI.BlockServerEvent) == "function"
            and pcall(SharkAPI.BlockServerEvent, true, nm) then n = n + 1 end
        if type(SharkAPI.BlockClientEvent) == "function" then
            pcall(SharkAPI.BlockClientEvent, true, nm)
        end
    end
    if n < 1 then return false end
    _G.__STATIC_QUANTUM_SPOOF_ON = true
    menu_dbg("^2[Static quantum]^0 ANTI-SPOOF ON " .. tostring(n) .. "/" .. tostring(#names))
    if type(StaticFeatures.tla_baddies_access) == "function" then
        pcall(StaticFeatures.tla_baddies_access)
    end
    return true
end

-- Compatibility alias: callers that used the old QBR v7 name still work.
StaticFeatures.ensure_quantum_bypass_armed = StaticFeatures.quantum_arm_antispoof

-- Pure getters. Reads the exact ids quantum's crash detector reads.
function StaticFeatures.quantum_task_live(ped)
    if not ped or ped == 0 then return false end
    local a, b, d = false, false, false
    pcall(function() a = GetIsTaskActive(ped, 57) == true end)
    pcall(function() b = GetIsTaskActive(ped, 313) == true end)
    pcall(function() d = IsPedUsingScenario(ped, "WORLD_HUMAN_CONST_DRILL") == true end)
    return (a or b or d), a, b, d
end

local function quantum_ped_is_seated(ped)
    if not ped or ped == 0 then return false end
    local seated = false
    pcall(function() seated = IsPedInAnyVehicle(ped, false) == true end)
    return seated
end
StaticFeatures.quantum_ped_is_seated = quantum_ped_is_seated

function StaticFeatures.freecam_quantum_taskclear(ped)
    if not ped or ped == 0 then return end
    if not StaticFeatures.quantum_present() then return end
    if quantum_ped_is_seated(ped) then return end
    pcall(ClearPedTasksImmediately, ped)
end

local QUANTUM_PED_MOVE_CONTROLS = { 30, 31, 32, 33, 34, 35, 21, 22 }

function StaticFeatures.freecam_quantum_hold(ped)
    if not StaticFeatures.quantum_present() then return end
    local seated = quantum_ped_is_seated(ped)
    if seated then return end
    for i = 1, #QUANTUM_PED_MOVE_CONTROLS do
        pcall(DisableControlAction, 0, QUANTUM_PED_MOVE_CONTROLS[i], true)
    end
    if ped and ped ~= 0 then
        local live = StaticFeatures.quantum_task_live(ped)
        if live then
            pcall(ClearPedTasksImmediately, ped)
            _G.__STATIC_QUANTUM_TASKHITS = (_G.__STATIC_QUANTUM_TASKHITS or 0) + 1
        end
    end
end

-- Gate. Arms the antispoof first and REFUSES if it will not arm. Returns true
-- untouched on every non-quantum server.
function StaticFeatures.freecam_quantum_gate(what)
    -- [[ QUIET BOOT ]] entering this gate IS a user action: a keybind can reach
    -- StartFreecam/StartNoclipFreecam without passing through execute_by_id, and the arm
    -- below must not be refused as boot-time traffic.
    if type(_G.__STATIC_USER_ACTION) == "function" then _G.__STATIC_USER_ACTION() end
    if not StaticFeatures.quantum_present() then return true end
    if _G.__STATIC_QUANTUM_FREECAM_ENABLED == false then
        if type(StaticFeatures.menu_notify) == "function" then
            StaticFeatures.menu_notify(what or "Freecam",
                "Disabled on The Lands of LA by switch", "error")
        end
        return false
    end
    if StaticFeatures.quantum_arm_antispoof() ~= true then
        if type(StaticFeatures.menu_notify) == "function" then
            StaticFeatures.menu_notify(what or "Freecam",
                "Blocked - quantum anti-spoof did not arm (check F8)", "error")
        end
        return false
    end
    local ped = PlayerPedId()
    local seated = type(StaticFeatures.quantum_ped_is_seated) == "function"
        and StaticFeatures.quantum_ped_is_seated(ped)
    if seated then
        menu_dbg("^2[Static quantum]^0 " .. tostring(what or "Freecam")
            .. " entered SEATED - task clear skipped")
    else
        local live, a, b, d = StaticFeatures.quantum_task_live(ped)
        if live then
            menu_dbg("^3[Static quantum]^0 entering with tasks live: 57=" .. tostring(a)
                .. " 313=" .. tostring(b) .. " drill=" .. tostring(d) .. " - clearing")
        end
    end
    StaticFeatures.freecam_quantum_taskclear(ped)
    _G.__STATIC_QUANTUM_TASKHITS = 0
    return true
end

-- <<STATIC QUANTUM NOCLIP>> ==================================================
-- The CONFIRMED quantum noclip, ported verbatim from the standalone that the
-- user confirmed flying in game on 2026-10-09:
--     C:\Users\67\Desktop\static1\tla_noclip\TLA_NOCLIP_SHIELD.lua
--
-- Bodies are byte-faithful to that file. The only changes are the ones the
-- destination forces: everything hangs off StaticFeatures instead of a chunk
-- local (no new top-level locals in a build this size), and output goes to
-- menu_dbg instead of print.
--
-- WHY THIS AND NOT StartNoclipHost: the host path writes the body with
-- SetEntityCoordsNoOffset from the executor VM. That is the confirmed
-- 2026-10-04 quantum ban - quantum:nc:report named that native, our resource
-- and the from/to pair, and it opened a clip incident. This route calls NO
-- coordinate setter at all, ever:
--   * body moved by PHYSICS       SetEntityVelocity + collision off/physics kept
--   * server view pinned          SyncTree.SpoofServerCoords + SpoofServerHeading
--   * client-side reads answered  AddHookCallback anchor shield on 4 natives
-- The shield is scoped to OUR PED only, never by resource name, because
-- quantum's clientHook is loaded into other resources' VMs so
-- GetCurrentResourceName inside the callback can never identify quantum.
--
-- Hashes verified against old/natives/fivem/api/by-hash.json. All four are
-- single-return with no float out-param, which AddHookCallback cannot express.

StaticFeatures.QNC_SHIELD = {
    { "GetEntityCoords",            0x3FEF770D40960D5A, 3 },
    { "GetEntityHeightAboveGround", 0x1DD55701034110E5, 2 },
    { "GetEntitySpeed",             0xD5037BA82E12416F, 2 },
    { "GetEntityVelocity",          0x4805D2B1D8CF94A9, 2 },
}

-- <<QNC NOHOOK 2026-10-12>> THE SHIELD IS OFF BY DEFAULT NOW, AND THIS IS THE
-- CRASH FIX. Four previous fixes all kept the AddHookCallback shield and tried
-- to make it safe (cached vector, owned-hash restore, IsNativeHooked stale
-- sweep, SAFEMODE). It still crashed. Reading the callbacks finally says why:
-- the pass-through branch of every member ENDS IN A CALL TO THE NATIVE IT IS
-- HOOKING - `return GetEntityCoords(entity, alive)` inside the GetEntityCoords
-- hook. GetEntityCoords is called by quantum's clientHook and by every other
-- resource thousands of times a frame, so every one of those calls now runs a
-- Lua trampoline that re-enters the hooked native. That is the corrupted stack
-- with no Lua error, and no amount of restore bookkeeping can fix it, because
-- the recursion is in the callback body.
-- So: ZERO native hooks on quantum. The route keeps both halves that were ever
-- confirmed - physics-only SetEntityVelocity movement with collision off and
-- physics kept, and the SyncTree server coord/heading pin, which runs in the
-- executor and hooks nothing. What is lost is honest: quantum can read the real
-- position CLIENT-side while flying. Nothing in the project has ever recorded a
-- client-side position read as the banner; the 2026-10-04 ban named
-- SetEntityCoordsNoOffset, a native this route never calls.
-- Set this true to put the shield back (it will crash again).
StaticFeatures.QNC_SHIELD_ENABLED = false

StaticFeatures.QNC_SPEED_MPS   = 18.0   -- metres/second at speed 1.0
StaticFeatures.QNC_BOOST       = 3.0    -- shift multiplier
StaticFeatures.QNC_WALK_MPS    = 2.2    -- convergence pace on exit
StaticFeatures.QNC_CONVERGE    = true   -- walk the spoof home instead of jumping
StaticFeatures.QNC_TASK_CLEAR  = true

-- <<QNC POSE 2026-10-12>> THE T-POSE FIX.
-- A ped with no task, no gravity and collision off has no animation to play,
-- so the engine leaves it in the default bind pose - the T-pose - and it looks
-- frozen even while the body is genuinely flying. Nothing was wrong with the
-- movement; the ped simply had nothing to do. qnc_pose_ensure gives it a
-- looping skydive idle, which is a scripted-animation task and NOT one of the
-- tasks quantum's UserDetectedCrash writer reads (57 / 313 / const-drill), so
-- it is safe to hold for the whole flight. It is re-applied whenever it stops
-- playing, including the frame after the periodic ClearPedTasksImmediately net
-- wipes it, and cleared on exit. If the dict will not stream it says so once
-- and flies T-posed exactly as before - a cosmetic layer may never gate the
-- feature.
-- <<QNC POSE OFF 2026-10-12>> OFF at the user's instruction. The idle was a
-- cosmetic patch over the real fault: a ped is the wrong thing to fly. The
-- velocity route cannot pass through walls either, because collision-off and
-- physics-kept are contradictory for a ped - the engine needs the capsule in
-- the physics world to carry a velocity, so it keeps resolving it against
-- geometry. The replacement is monitor (txAdmin) own freecam engine, which
-- freezes the ped and flies a CAMERA: see
-- static1/tla_noclip/TLA_NOCLIP_MONITOR_FREECAM.lua. Wired here once it is
-- confirmed in game; this build keeps the velocity route until then, now
-- without the animation.
-- <<QNC POSE ON 2026-10-13>> TURNED BACK ON at the user's instruction for this port:
-- "make sure there's no errors of anything stuck or a T-pose". The mainforever build
-- shipped this false, so a verbatim port would T-pose. The idle is a scripted-animation
-- task and is NOT one of the tasks quantum's UserDetectedCrash writer reads
-- (57 / 313 / const-drill), so it is safe to hold for the whole flight, and it fails
-- OPEN: if the dict will not stream it says so once and flies T-posed exactly as before.
-- <<QNC POSE STAND 2026-10-13>> skydive REMOVED at the user's instruction ("just normal
-- player"). Same standing idle the build's own freecam uses (lockFreecamPedPose), so the
-- ped flies upright like a normal player instead of prone. Still a scripted anim, still
-- not task 57/313/const-drill, still fail-open.
StaticFeatures.QNC_POSE      = true
StaticFeatures.QNC_POSE_DICT = "anim@heists@heist_corona@team_idles@male_a"
StaticFeatures.QNC_POSE_ANIM = "idle"
-- <<QNC FACE CAM 2026-10-13>> turn the body to the camera heading so it always faces the
-- way it flies. Without it the ped kept its start heading and slid sideways/backwards.
StaticFeatures.QNC_FACE_CAM  = true
StaticFeatures._qnc_pose_ok  = nil   -- nil = not asked yet, false = will not stream
-- <<QNC CRASH FIX 2026-10-10>> hard ceiling on body velocity, and the box the
-- body is not allowed to leave. See qnc_tick.
-- <<QNC RENDER 2026-10-11>> WAS 160.0, which is below what the slider asks
-- for. The slider runs to 25 (NOCLIP_SPEED_MAX) and the tick computes
-- slider * QNC_SPEED_MPS(18) = 450 m/s at the top, so everything above slider
-- 8.9 was being clamped away and the top of the slider did nothing. 450 makes
-- the whole slider range live unboosted; boost still helps below slider 8.3.
-- This is the physics-velocity ceiling, so it is also the point past which the
-- engine stops being able to carry the body with collision off - the
-- QNC_WORLD box in qnc_tick is the other half of that guard.
-- <<QNC SAFEMODE 2026-10-11>> THE CONFIRMED ARTIFACT'S BEHAVIOUR, FORCED.
-- Three crash fixes have now failed on this feature. The one fact that has not
-- moved: tla_noclip/TLA_NOCLIP_SHIELD.lua was confirmed FLYING in game on
-- 2026-10-09 and does not crash, and the build's copy of the same shield does.
-- So stop patching the build's variant and make it behave like the artifact.
-- Everything SAFEMODE forces below is a line the confirmed standalone does NOT
-- have. qnc_apply_safemode re-forces them at every Start, so a later value edit
-- somewhere else in the file cannot silently undo this.
--   QNC_FOCUS      the standalone never calls SetFocusPosAndVel. Not once.
--   QNC_SPOOF_MODE the standalone arms the coord spoof ONCE and never re-arms
--                  it in flight; track mode re-arms it every 100ms.
--   QNC_MAX_MPS    the standalone's real ceiling is 6.0 x 18.0 x 3.0 = 324.
-- Set StaticFeatures.QNC_SAFEMODE = false to get the extras back.
StaticFeatures.QNC_SAFEMODE    = true
StaticFeatures.QNC_MAX_MPS     = 324.0  -- the standalone's own ceiling (6.0 speed x 18 x 3 boost)
StaticFeatures.QNC_WORLD       = { xy = 7500.0, zmin = -150.0, zmax = 2500.0 }

-- Only the controls that would make the ped MOVE or acquire a movement task.
-- Everything absent from this list stays live - the mouse (LOOK_LR 1, LOOK_UD 2)
-- above all, because looking around tasks nothing and killing it was what made
-- the first wired version unusable.
--   21 SPRINT   22 JUMP   23 ENTER   30 MOVE_LR   31 MOVE_UD
--   32/33/34/35 MOVE_UP/DOWN/LEFT/RIGHT_ONLY      36 DUCK   44 COVER
StaticFeatures.QNC_BLOCK_CONTROLS = { 21, 22, 23, 30, 31, 32, 33, 34, 35, 36, 44 }

-- <<QNC TRACKING 2026-10-10>> the reported position FOLLOWS instead of pinning.
--
-- WHY THIS CHANGED. Pinning the sync tree at the anchor is what broke two
-- separate things the user reported:
--   * other players never streamed in. On OneSync the SERVER decides which
--     entities to send from the position WE report, so pinned at the anchor it
--     only ever sent entities near the anchor. Flying away meant flying into an
--     empty world, and toggling noclip off and on "fixed" it only because that
--     re-anchored the lie where we actually were.
--   * stopping 500m out left a 500m gap between where the server thought we
--     were and where we were, which is what everything then tried to correct.
-- So the lie now TRAVELS toward the real position at a ground-plausible speed
-- rather than standing still. Fly slower than QNC_SPOOF_MPS and it keeps up
-- exactly: streaming is normal and there is no gap left to snap.
--
-- This is the "animate the value you already control" shape - move the lie,
-- never the player - with the rate clamped so the reported movement stays
-- something a vehicle could have done.
--
-- <<QNC RENDER 2026-10-11>> THE DESIGN ABOVE WAS RIGHT AND THE NUMBER WAS
-- WRONG. The clamp was 26 m/s while the body flies at the QNC_MAX_MPS cap, so
-- the lie fell behind by the difference every second: ten seconds at speed and
-- the server thinks we are over a kilometre back. That one gap is THREE of the
-- reported faults at once -
--   * players never render far out   the server streams entities around the
--     position we REPORT, and that position was a kilometre behind us
--   * untoggling snaps you back      the server has us at the lie, so the
--     moment the spoof comes off it reconciles us to it
--   * convergence took for ever      it closes the gap at this same rate
-- QNC_RENDER makes the lie track the body at whatever the body can actually
-- do, so there is no lag, no empty world and no gap to snap. The cost is
-- honest and worth saying out loud: while it is on, the position we report IS
-- our real one, so a server-side observer sees the flight. Set QNC_RENDER
-- false to go back to the 26 m/s desync clamp and accept the empty world.
StaticFeatures.QNC_RENDER     = false    -- <<QNC SAFEMODE>> standalone had no tracking at all
StaticFeatures.QNC_SPOOF_MODE = "pin"    -- <<QNC SAFEMODE>> arm once, never re-arm in flight
StaticFeatures.QNC_SPOOF_MPS  = 26.0     -- desync clamp, used only when QNC_RENDER is false
StaticFeatures.QNC_FOCUS      = false    -- <<QNC SAFEMODE>> standalone never touched the focus
-- <<QNC CRASH FIX 2026-10-10 b>> both of the values below used to be per-frame,
-- and both are things the CONFIRMED standalone never did at all.
-- See qnc_tick / qnc_advance_lie.
-- <<QNC RENDER 2026-10-11>> FOCUS_M raised with the speed cap. The two focus
-- conditions are an OR, so a 20m trigger at 450 m/s fires every 44ms - 22 a
-- second, four times what the 10-10 throttle was put here to allow. 50m at the
-- new top speed is ~9 a second, which is the same traffic as before.
-- PUSH_MS halved because the push conditions are an AND: at speed the reported
-- position moves in one jump per interval, so 200ms was a 90m step. 100ms
-- halves the step and keeps the reported path continuous.
StaticFeatures.QNC_FOCUS_MS   = 200      -- min ms between SetFocusPosAndVel calls
StaticFeatures.QNC_FOCUS_M    = 50.0     -- ...or sooner once we have flown this far
StaticFeatures.QNC_PUSH_MS    = 100      -- min ms between sync-tree coord re-arms
StaticFeatures.QNC_PUSH_M     = 3.0      -- ...and the reported point must have moved this far
StaticFeatures.QNC_SETTLE_MS  = 600      -- keep collision off this long after stopping, so the
                                         -- ground has streamed in before physics comes back
StaticFeatures.TP_HOLD_KEY    = "__static_tp_hold"
StaticFeatures.QNC_HOLD_GRACE_MS = 1500   -- keep anti-teleport stood down this long after
                                          -- everything settles, so its loop gets clean frames
StaticFeatures._qnc_lie       = nil      -- {x,y,z} currently REPORTED position
StaticFeatures._qnc_settle_at = nil

StaticFeatures._qnc_on         = false
StaticFeatures._qnc_converging = false
StaticFeatures._qnc_shield_on  = false
StaticFeatures._qnc_lies       = 0
StaticFeatures._qnc_pass       = 0
StaticFeatures._qnc_who        = {}
StaticFeatures._qnc_anchor     = nil
StaticFeatures._qnc_anchor_h   = nil
StaticFeatures._qnc_spoof_at   = nil
StaticFeatures._qnc_truth      = nil
StaticFeatures._qnc_frames     = 0
StaticFeatures._qnc_max_drift  = 0.0
StaticFeatures._qnc_coordsets  = 0
StaticFeatures._qnc_zero       = nil
StaticFeatures._qnc_last       = 0
StaticFeatures._qnc_conv_last  = 0
StaticFeatures._qnc_driver     = false

-- <<QNC TRACE 2026-10-11>> menu_dbg is `if Menu and Menu.debug then print(...)`,
-- so every QNC line in this build has been invisible unless the debug toggle
-- happened to be on. Three rounds of this crash have been debugged with ZERO
-- telemetry in any log - grep QNC across every CitizenFX log and the only hits
-- are from the standalone, which uses print. That is why this has taken three
-- guesses instead of one measurement.
-- A hard crash kills notifies and the Shark console with it. The FiveM log is
-- the ONLY channel that survives one, so this traces through print as well,
-- which is a deliberate exception to the no-print rule for as long as this
-- feature is crashing. Turn it off with _G.__STATIC_QNC_TRACE = false.
function StaticFeatures.qnc_log(msg)
    -- <<QNC SILENT 2026-10-13>> print removed at the user's instruction - F8 stays clean.
    -- Still reaches menu_dbg, which only prints when Menu.debug is on.
    if type(menu_dbg) == "function" then menu_dbg("^5[QNC]^0 " .. tostring(msg)) end
end

-- <<QNC SAFEMODE 2026-10-11>> re-forced at every Start, so this cannot be
-- undone by a value edit elsewhere in the file.
function StaticFeatures.qnc_apply_safemode()
    if StaticFeatures.QNC_SAFEMODE ~= true then return false end
    StaticFeatures.QNC_FOCUS      = false
    StaticFeatures.QNC_RENDER     = false
    StaticFeatures.QNC_SPOOF_MODE = "pin"
    if (StaticFeatures.QNC_MAX_MPS or 0) > 324.0 then
        StaticFeatures.QNC_MAX_MPS = 324.0
    end
    return true
end

-- ── the client-side shield ──────────────────────────────────────────────────

-- <<QNC RENDER 2026-10-11>> the one rate both the live tracking and the exit
-- convergence travel at. With QNC_RENDER on it is just above the body's own
-- ceiling, so the lie can never fall behind whatever the body is doing; with it
-- off it is the old plausible-ground-speed desync clamp.
function StaticFeatures.qnc_track_mps()
    if StaticFeatures.QNC_RENDER == false then
        return StaticFeatures.QNC_SPOOF_MPS or 26.0
    end
    return (StaticFeatures.QNC_MAX_MPS or 450.0) + 10.0
end

function StaticFeatures.qnc_gate()
    return StaticFeatures._qnc_shield_on and StaticFeatures._qnc_on
        and StaticFeatures._qnc_anchor ~= nil
end

-- The position we are CURRENTLY reporting, as a vector3. Built from the lie
-- when tracking, the anchor when pinned.
-- <<QNC CRASH FIX 2026-10-10 b>> THIS WAS THE CRASH.
-- This function used to be called from INSIDE the GetEntityCoords hook
-- callback, which meant a pcall plus a vector3 CONSTRUCTOR ran inside another
-- native call context - thousands of times a frame, for every resource on the
-- server, from the instant the gate opened. That is the same nested-native
-- fault the ped cache was meant to fix; caching the ped removed PlayerPedId and
-- left a per-call allocation behind it, which is why enabling still died.
-- The CONFIRMED standalone returned B._anchor, a pre-built vector3 object, and
-- allocated nothing in there. So: the object is built ONCE A FRAME on our own
-- driver thread, and the callback only reads it.
StaticFeatures._qnc_rep = nil

function StaticFeatures.qnc_rep_refresh()
    local l = StaticFeatures._qnc_lie
    if type(l) ~= "table" or type(vector3) ~= "function" then
        StaticFeatures._qnc_rep = StaticFeatures._qnc_anchor
        return StaticFeatures._qnc_rep
    end
    local ok, v = pcall(vector3, l.x, l.y, l.z)
    if ok and v then
        StaticFeatures._qnc_rep = v
    else
        StaticFeatures._qnc_rep = StaticFeatures._qnc_anchor
    end
    return StaticFeatures._qnc_rep
end

-- Host-side callers only (the spoof arm, the resync, convergence). This is
-- NEVER called from a hook callback any more - the callback reads _qnc_rep.
function StaticFeatures.qnc_reported()
    return StaticFeatures.qnc_rep_refresh()
end

-- <<QNC TP RESYNC 2026-10-10>> Anything that MOVES the body behind noclip's
-- back - the menu's Teleport rows above all - must say so here, or the lie and
-- our integrated position stay where the body used to be. The gap that opens is
-- then both what stops players streaming at the new place AND what the
-- anti-teleport loop tries to correct the moment the hold drops.
--
-- Re-seeding is the whole fix: the reported position jumps WITH us, so from the
-- server's point of view the teleport simply happened, and there is no gap left
-- behind to close.
function StaticFeatures.qnc_resync(x, y, z)
    if not StaticFeatures._qnc_on then return end
    x, y, z = tonumber(x), tonumber(y), tonumber(z)
    if not (x and y and z) then return end
    StaticFeatures._qnc_truth = { x = x, y = y, z = z }
    StaticFeatures._qnc_lie   = { x = x, y = y, z = z }
    StaticFeatures._qnc_lie_pushed = nil
    local st = (type(SharkAPI) == "table") and SharkAPI.SyncTree or nil
    if type(st) == "table" and type(st.SpoofServerCoords) == "function" then
        local rep = StaticFeatures.qnc_reported()
        if rep then
            pcall(st.SpoofServerCoords, true, rep)
            StaticFeatures._qnc_spoof_at = rep
        end
    end
    if StaticFeatures.QNC_FOCUS then
        pcall(SetFocusPosAndVel, x, y, z, 0.0, 0.0, 0.0)
    end
    StaticFeatures.qnc_log(string.format("resync to %.1f/%.1f/%.1f (teleport while flying)", x, y, z))
end

-- Advance the reported position toward where we really are, clamped to
-- QNC_SPOOF_MPS, and push it to the sync tree only when it has actually moved.
function StaticFeatures.qnc_advance_lie(dt)
    if StaticFeatures.QNC_SPOOF_MODE ~= "track" then return end
    local l, t = StaticFeatures._qnc_lie, StaticFeatures._qnc_truth
    if type(l) ~= "table" or type(t) ~= "table" then return end
    local dx, dy, dz = t.x - l.x, t.y - l.y, t.z - l.z
    local d = math.sqrt(dx * dx + dy * dy + dz * dz)
    if d < 0.05 then return end
    local step = StaticFeatures.qnc_track_mps() * (dt or 0.0)
    if step <= 0.0 then return end
    if step >= d then
        l.x, l.y, l.z = t.x, t.y, t.z
    else
        l.x, l.y, l.z = l.x + dx / d * step, l.y + dy / d * step, l.z + dz / d * step
    end
    -- only re-arm the spoof when the reported point has meaningfully changed,
    -- so this is not a per-frame write for a value that has not moved
    -- <<QNC CRASH FIX 2026-10-10 b>> was 0.25m, i.e. about 70 sync-tree re-arms
    -- a second at flying speed. The server reads the tree at its own rate, far
    -- below that, so 3m / 200ms reports the same path for a fraction of the
    -- executor traffic. The confirmed standalone armed the spoof ONCE.
    local lastPush = StaticFeatures._qnc_lie_pushed
    local nowP = (type(GetGameTimer) == "function" and GetGameTimer()) or 0
    if type(lastPush) == "table" then
        local px, py, pz = l.x - lastPush.x, l.y - lastPush.y, l.z - lastPush.z
        if math.sqrt(px * px + py * py + pz * pz) < (StaticFeatures.QNC_PUSH_M or 3.0) then return end
        if (nowP - (StaticFeatures._qnc_push_ms or 0)) < (StaticFeatures.QNC_PUSH_MS or 200) then return end
    end
    local st = (type(SharkAPI) == "table") and SharkAPI.SyncTree or nil
    if type(st) == "table" and type(st.SpoofServerCoords) == "function" then
        local rep = StaticFeatures.qnc_reported()
        if rep then
            pcall(st.SpoofServerCoords, true, rep)
            StaticFeatures._qnc_lie_pushed = { x = l.x, y = l.y, z = l.z }
            StaticFeatures._qnc_push_ms = nowP
            StaticFeatures._qnc_spoof_at = rep
        end
    end
end

-- <<QNC CRASH FIX 2026-10-10>> NO NATIVE CALLS inside a hook callback except
-- the pass-through original. These callbacks run INSIDE every resource's call
-- to GetEntityCoords/Speed/Velocity/HeightAboveGround - thousands a frame - and
-- calling PlayerPedId/GetCurrentResourceName from in there nests a native call
-- inside another native's call context. That is the intermittent hard crash
-- (GTA5_b3258.exe+48E0D87, 3x on 2026-10-10, no Lua error before it). The ped
-- handle is now cached by the driver tick and Start, compared as a plain int.
StaticFeatures._qnc_ped = 0
function StaticFeatures.qnc_mine(entity)
    local p = StaticFeatures._qnc_ped
    return p ~= nil and p ~= 0 and entity == p
end

function StaticFeatures.qnc_mark()
    StaticFeatures._qnc_lies = StaticFeatures._qnc_lies + 1
end

-- <<QNC CRASH FIX 2026-10-11 collision>> hashes WE installed, so RestoreNative
-- can never tear down a hook some other layer in this build owns. The old code
-- restored all four unconditionally on both arm and disarm, which stomped the
-- WaveShield pack whenever it happened to be up.
StaticFeatures._qnc_owned = StaticFeatures._qnc_owned or {}

function StaticFeatures.qnc_shield_down(quiet)
    StaticFeatures._qnc_shield_on = false
    local S = (type(SharkAPI) == "table") and SharkAPI.Scripting or nil
    if type(S) ~= "table" or type(S.RestoreNative) ~= "function" then return end
    for hash in pairs(StaticFeatures._qnc_owned) do
        pcall(S.RestoreNative, hash)
    end
    StaticFeatures._qnc_owned = {}
    if not quiet then
        StaticFeatures.qnc_log(string.format("shield DOWN spoofed=%d passed=%d",
            StaticFeatures._qnc_lies, StaticFeatures._qnc_pass))
    end
end

function StaticFeatures.qnc_shield_up()
    -- <<QNC CRASH FIX 2026-10-11 collision>> BISECT SWITCH. If the crash somehow
    -- survives the hook-collision fix, paste
    --     _G.__STATIC_QNC_NO_SHIELD = true
    -- in Shark and fly again. No crash then means the shield itself is the
    -- fault on this game build and not anything the menu wraps around it; a
    -- crash anyway means it is the physics/streaming half. One run, one answer.
    -- Flying unshielded leaves quantum reading the real position client-side,
    -- so this is a diagnostic, not a setting.
    -- <<QNC NOHOOK 2026-10-12>> default path. QNC_SHIELD_ENABLED is false, so
    -- this returns before a single hook is installed. qnc_gate() is only ever
    -- read inside the hook callbacks, so nothing else in the route changes.
    if StaticFeatures.QNC_SHIELD_ENABLED ~= true or _G.__STATIC_QNC_NO_SHIELD == true then
        StaticFeatures.qnc_log("shield OFF by design - no native hooks installed."
            .. " Server view is pinned by the sync tree; client-side reads are honest.")
        StaticFeatures._qnc_shield_on = false
        return true
    end
    local S = (type(SharkAPI) == "table") and SharkAPI.Scripting or nil
    if type(S) ~= "table" or type(S.AddHookCallback) ~= "function" then
        StaticFeatures.qnc_log("^1shield: AddHookCallback missing - no client-side half^0")
        return false
    end
    -- restore only what a PREVIOUS ARM OF OURS left behind. Never a blanket
    -- pass over all four: another layer in this build may own some of them,
    -- and writing back an original over a live foreign hook is the crash.
    if type(S.RestoreNative) == "function" then
        for hash in pairs(StaticFeatures._qnc_owned or {}) do
            pcall(S.RestoreNative, hash)
        end
    end
    StaticFeatures._qnc_owned = {}

    -- <<QNC CRASH FIX 2026-10-11 stale>> THIS IS WHAT STILL CRASHED.
    -- _qnc_owned hangs off `local StaticFeatures = {}` (~1321), a CHUNK LOCAL,
    -- so every paste of the menu gets a brand new, EMPTY one. Shark's native
    -- hooks are process level and survive a paste. So: arm noclip, re-paste the
    -- menu (after a crash, after an edit, after any reload), arm it again, and
    -- the restore pass above has nothing to restore - it registers a SECOND
    -- callback on all four hashes on top of the previous paste's callbacks,
    -- which are still live and still hold upvalues into a dead table.
    -- Two trampolines on GetEntityCoords, which the server calls tens of
    -- thousands of times a frame, is the corrupted stack at
    -- GTA5_b3258.exe+48E0D87 - 0x2 frames, no Lua error. It is "sometimes"
    -- because it needs a re-paste since the last arm, and a crash forces a
    -- re-paste, so it feeds itself.
    --
    -- The owned set cannot be made durable: _G is reset between pastes on this
    -- executor (recorded rule - put a run token in LocalPlayer.state, never
    -- _G), and a statebag is the wrong place for a hook table. So ASK the
    -- executor instead: IsNativeHooked is the only durable record there is.
    --
    -- Scoped to quantum, which is the only server this route runs on
    -- (StartNoclipQuantum is reached from the quantum branch of
    -- StartNoclipFreecam and nowhere else), and on quantum the three
    -- WaveShield hook packs refuse at their own definition
    -- (<<QNC CRASH FIX 2026-10-11 collision>>), so nothing else in this build
    -- can legitimately own these four. Anywhere else this does nothing.
    if type(S.IsNativeHooked) == "function" and type(S.RestoreNative) == "function"
        and type(StaticFeatures.quantum_present) == "function"
        and StaticFeatures.quantum_present() then
        local stale = {}
        for i = 1, #StaticFeatures.QNC_SHIELD do
            local m = StaticFeatures.QNC_SHIELD[i]
            local good, hooked = pcall(S.IsNativeHooked, m[2])
            -- normalise: nil/false off, a number off only at 0, true on
            local on = false
            if good then
                if type(hooked) == "number" then on = (hooked ~= 0)
                elseif hooked == true then on = true end
            end
            if on then
                pcall(S.RestoreNative, m[2])
                stale[#stale + 1] = m[1] .. "(raw=" .. tostring(hooked) .. ")"
            end
        end
        if #stale > 0 then
            StaticFeatures.qnc_log("^3stale hooks from a previous paste cleared: "
                .. table.concat(stale, ", ") .. "^0")
        end
    end

    if type(vector3) == "function" then
        local ok, v = pcall(vector3, 0.0, 0.0, 0.0)
        if ok and v then StaticFeatures._qnc_zero = v end
    end

    local cbs = {
        GetEntityCoords = function(entity, alive)
            if StaticFeatures.qnc_gate() and StaticFeatures.qnc_mine(entity) then
                StaticFeatures.qnc_mark()
                -- <<QNC TRACKING>> answer with the CURRENTLY REPORTED position,
                -- not the original anchor. The sync tree and every client-side
                -- reader must tell the same story, and once the lie travels the
                -- anchor is a stale third version of it.
                -- <<QNC CRASH FIX 2026-10-10 b>> cached object. No call, no
                -- allocation, nothing nested inside the native call context.
                return StaticFeatures._qnc_rep or StaticFeatures._qnc_anchor
            end
            StaticFeatures._qnc_pass = StaticFeatures._qnc_pass + 1
            return GetEntityCoords(entity, alive)
        end,
        GetEntityHeightAboveGround = function(entity)
            if StaticFeatures.qnc_gate() and StaticFeatures.qnc_mine(entity) then
                StaticFeatures.qnc_mark()
                return 0.0
            end
            StaticFeatures._qnc_pass = StaticFeatures._qnc_pass + 1
            return GetEntityHeightAboveGround(entity)
        end,
        GetEntitySpeed = function(entity)
            if StaticFeatures.qnc_gate() and StaticFeatures.qnc_mine(entity) then
                StaticFeatures.qnc_mark()
                return 0.0
            end
            StaticFeatures._qnc_pass = StaticFeatures._qnc_pass + 1
            return GetEntitySpeed(entity)
        end,
        GetEntityVelocity = function(entity)
            if StaticFeatures.qnc_gate() and StaticFeatures.qnc_mine(entity)
                and StaticFeatures._qnc_zero then
                StaticFeatures.qnc_mark()
                return StaticFeatures._qnc_zero
            end
            StaticFeatures._qnc_pass = StaticFeatures._qnc_pass + 1
            return GetEntityVelocity(entity)
        end,
    }

    -- BOTH-OR-NEITHER. A detector that computes a DIFFERENCE between two of
    -- these is not weakened by half the set - half the set IS the detection.
    local installed, failed = {}, {}
    for i = 1, #StaticFeatures.QNC_SHIELD do
        local m = StaticFeatures.QNC_SHIELD[i]
        local mname, hash, nargs = m[1], m[2], m[3]
        local cb = cbs[mname]
        local drop = (mname == "GetEntityVelocity" and StaticFeatures._qnc_zero == nil)
        local ok, ret
        if drop then
            ok, ret = false, "no vector3 in this VM"
        elseif nargs == 3 then
            ok, ret = pcall(S.AddHookCallback, hash, 1, 3, 7, cb)
        else
            local rt = (mname == "GetEntityVelocity") and 7 or 4
            ok, ret = pcall(S.AddHookCallback, hash, 1, rt, cb)
        end
        -- refuse only on an EXPLICIT negative from the API itself
        if ok and ret ~= false and ret ~= 0 then
            installed[#installed + 1] = mname
            StaticFeatures._qnc_owned[hash] = true
        else
            failed[#failed + 1] = mname .. "(ok=" .. tostring(ok) .. " ret=" .. tostring(ret) .. ")"
        end
    end

    if #failed > 0 then
        StaticFeatures.qnc_log("^1shield BOTH-OR-NEITHER - refused: "
            .. table.concat(failed, ", ") .. "^0")
        StaticFeatures.qnc_shield_down(true)
        return false
    end

    StaticFeatures._qnc_shield_on = true
    StaticFeatures._qnc_lies = 0
    StaticFeatures._qnc_pass = 0
    StaticFeatures._qnc_who = {}
    StaticFeatures.qnc_log("shield UP members=" .. table.concat(installed, ", "))
    return true
end

-- ── the server-side pin ─────────────────────────────────────────────────────

function StaticFeatures.qnc_spoof(on, coords, heading)
    local st = (type(SharkAPI) == "table") and SharkAPI.SyncTree or nil
    if type(st) ~= "table" then
        StaticFeatures.qnc_log("^1spoof: SharkAPI.SyncTree missing^0")
        return false
    end
    local okC = false
    if type(st.SpoofServerCoords) == "function" then
        if on then okC = pcall(st.SpoofServerCoords, true, coords)
        else okC = pcall(st.SpoofServerCoords, false) end
    end
    if type(st.SpoofServerHeading) == "function" then
        if on then pcall(st.SpoofServerHeading, true, (heading or 0.0) + 0.0)
        else pcall(st.SpoofServerHeading, false) end
    end
    StaticFeatures.qnc_log("spoof " .. (on and "ARM" or "RELEASE") .. " coords_ok=" .. tostring(okC))
    return okC
end

-- ── one frame ───────────────────────────────────────────────────────────────

-- <<STATIC QUANTUM NOCLIP FIX 2026-10-09 updown>>
-- WAS: IsKeyPressed polling only. The CONFIRMED standalone took held state from
-- OnKeyDown/OnKeyUp into a table and read THAT - there is a recorded rule
-- against IsKeyPressed polling for held keys on Shark - and I swapped it during
-- the port. Up/down (SPACE, LCTRL) were the casualties.
--
-- Now BOTH paths are read and OR'd, which is fail-open: whichever one this
-- build's VM actually serves, the key works. Each path keeps its own counter so
-- the log says which is live instead of leaving it a guess.
--
-- Aliases matter: Shark may deliver the GENERIC modifier code rather than the
-- side-specific one, so LCTRL is read as 0xA2 or 0x11 and LSHIFT as 0xA0 or
-- 0x10. A missing alias here is indistinguishable from a dead feature.
StaticFeatures._qnc_held_tbl  = StaticFeatures._qnc_held_tbl or {}
StaticFeatures._qnc_hits_evt  = 0
StaticFeatures._qnc_hits_poll = 0
StaticFeatures._qnc_keys_seen = 0

function StaticFeatures.qnc_poll(vk)
    if type(SharkAPI) ~= "table" or type(SharkAPI.IsKeyPressed) ~= "function" then return false end
    local ok, p = pcall(SharkAPI.IsKeyPressed, vk)
    return ok and (p == true or p == 1)
end

function StaticFeatures.qnc_held(vk, alt)
    local evt = (StaticFeatures._qnc_held_tbl[vk] == true)
        or (alt ~= nil and StaticFeatures._qnc_held_tbl[alt] == true)
    if evt then
        StaticFeatures._qnc_hits_evt = StaticFeatures._qnc_hits_evt + 1
        return true
    end
    local poll = StaticFeatures.qnc_poll(vk) or (alt ~= nil and StaticFeatures.qnc_poll(alt))
    if poll then
        StaticFeatures._qnc_hits_poll = StaticFeatures._qnc_hits_poll + 1
        return true
    end
    return false
end

-- Registered ONCE, here in the main chunk, and both halves registered or keys
-- latch on for ever.
if not StaticFeatures._qnc_keys_registered then
    StaticFeatures._qnc_keys_registered = true
    if type(SharkAPI) == "table" and type(SharkAPI.OnKeyDown) == "function"
        and type(SharkAPI.OnKeyUp) == "function" then
        local okd = pcall(SharkAPI.OnKeyDown, function(vk)
            StaticFeatures._qnc_held_tbl[vk] = true
            StaticFeatures._qnc_keys_seen = StaticFeatures._qnc_keys_seen + 1
        end)
        local oku = pcall(SharkAPI.OnKeyUp, function(vk)
            StaticFeatures._qnc_held_tbl[vk] = nil
        end)
        StaticFeatures.qnc_log("keys: OnKeyDown=" .. tostring(okd) .. " OnKeyUp=" .. tostring(oku))
    else
        StaticFeatures.qnc_log("keys: OnKeyDown/OnKeyUp missing - falling back to IsKeyPressed only")
    end
end

-- <<QNC POSE 2026-10-12>> request once, re-apply only when it is not playing.
-- Never blocks: the request is fired and the apply happens on whichever later
-- frame HasAnimDictLoaded first answers true.
-- <<QNC DEAD FIX 2026-10-13>> native results: nil/false off, number off only at 0
function StaticFeatures.qnc_truthy(v)
    if v == nil or v == false then return false end
    if type(v) == "number" then return v ~= 0 end
    return true
end

function StaticFeatures.qnc_pose_ensure(ped)
    if StaticFeatures.QNC_POSE ~= true then return end
    if StaticFeatures._qnc_pose_ok == false then return end
    local d = StaticFeatures.QNC_POSE_DICT
    local n = StaticFeatures.QNC_POSE_ANIM
    local okl, loaded = pcall(HasAnimDictLoaded, d)
    if not (okl and loaded) then
        pcall(RequestAnimDict, d)
        -- give it ten seconds of frames, then stop asking and say so once
        local w = (StaticFeatures._qnc_pose_wait or 0) + 1
        StaticFeatures._qnc_pose_wait = w
        if w > 600 then
            StaticFeatures._qnc_pose_ok = false
            StaticFeatures.qnc_log("pose: " .. tostring(d) .. " did not stream -"
                .. " flying without it (cosmetic only, the body still moves)")
        end
        return
    end
    local okp, playing = pcall(IsEntityPlayingAnim, ped, d, n, 3)
    if okp and playing then
        if StaticFeatures._qnc_pose_ok ~= true then
            StaticFeatures._qnc_pose_ok = true
            StaticFeatures.qnc_log("pose ON " .. tostring(d) .. "/" .. tostring(n))
        end
        return
    end
    -- <<QNC RAGDOLL FIX 2026-10-13>> WAS re-issued EVERY frame while not playing. When
    -- something else holds the ped (ragdoll, fall task) that restarts the blend from the
    -- bind pose sixty times a second, which pins the ped in a half T-pose. One try per
    -- 250ms gives the anim time to actually take.
    local nowp = (type(GetGameTimer) == "function" and GetGameTimer()) or 0
    if nowp - (StaticFeatures._qnc_pose_try_ms or 0) < 250 then return end
    StaticFeatures._qnc_pose_try_ms = nowp
    -- 1 = looping, 48 = upper-body-only + secondary are NOT wanted here; the
    -- plain looping flag keeps the whole body in the idle while velocity moves it.
    pcall(TaskPlayAnim, ped, d, n, 8.0, -8.0, -1, 1, 0.0, false, false, false)
end

function StaticFeatures.qnc_tick()
    -- <<QNC TRACE 2026-10-11>> the first few frames are where an enable crash
    -- actually lands - Start returns fine and the driver kills it a frame later.
    -- Each line is flushed to the FiveM log before the next call runs, so the
    -- LAST line in the log after a crash names the exact call that did it.
    local tf = (StaticFeatures._qnc_frames or 0) < 3
    if tf then StaticFeatures.qnc_log("tick f" .. tostring(StaticFeatures._qnc_frames) .. " a:ped") end
    local ped = PlayerPedId()
    StaticFeatures._qnc_ped = ped   -- <<QNC CRASH FIX>> cache for the hook callbacks
    -- <<QNC CRASH FIX 2026-10-10 b>> rebuild the reported-position OBJECT once
    -- here, on our own thread. One allocation a frame instead of thousands
    -- inside other resource native calls.
    pcall(StaticFeatures.qnc_rep_refresh)
    local ent = ped
    local seated = false
    if type(IsPedInAnyVehicle) == "function" and IsPedInAnyVehicle(ped, false) then
        local v = GetVehiclePedIsIn(ped, false)
        if v and v ~= 0 then ent = v; seated = true end
    end

    -- collision off but PHYSICS KEPT (false,true). false,false strips physics
    -- and forces the teleport shape.
    if tf then StaticFeatures.qnc_log("tick b:collision+gravity ent=" .. tostring(ent)
        .. " seated=" .. tostring(seated)) end
    SetEntityCollision(ent, false, true)
    pcall(SetEntityHasGravity, ent, false)

    if tf then StaticFeatures.qnc_log("tick c:controls") end
    if StaticFeatures.QNC_TASK_CLEAR and not seated then
        -- <<STATIC QUANTUM NOCLIP FIX 2026-10-09 mouse>>
        -- WAS: pcall(DisableAllControlActions, 0) -- which also disabled
        -- LOOK_LR(1) and LOOK_UD(2), i.e. the MOUSE, so the camera could not be
        -- turned while flying. The point of disabling anything here is only to
        -- stop the ped RECEIVING MOVEMENT INPUT that would task it, because
        -- quantum's own crash detector reads tasks 57/313/const-drill. Looking
        -- around tasks nothing, so it must stay enabled.
        -- Built from the EFFECT of each control, never from its category name.
        for i = 1, #StaticFeatures.QNC_BLOCK_CONTROLS do
            pcall(DisableControlAction, 0, StaticFeatures.QNC_BLOCK_CONTROLS[i], true)
        end
        -- <<QNC DEAD FIX 2026-10-13>> a DEAD ped's body is held by its dying task /
        -- death ragdoll. Clearing that task, killing ragdoll or forcing an anim on it
        -- strips the death pose and leaves the bind pose - the dead-noclip T-pose. So
        -- while dead touch nothing: no clear, no ragdoll write, no idle, no heading.
        -- The dying task is not 57/313/const-drill, so quantum's crash writer has
        -- nothing to read. The death flow (respawn/ambulance) is left untouched too.
        local dead = false
        pcall(function()
            dead = StaticFeatures.qnc_truthy(IsPedDeadOrDying(ped, true)) or StaticFeatures.qnc_truthy(IsEntityDead(ped))
        end)
        StaticFeatures._qnc_dead = dead
        if dead then
            if StaticFeatures._qnc_dead_logged ~= true then
                StaticFeatures._qnc_dead_logged = true
                StaticFeatures.qnc_log("dead: leaving the death pose alone (no clear/ragdoll/idle)")
            end
        else
        StaticFeatures._qnc_dead_logged = false
        -- <<QNC DEAD FIX 2026-10-13>> WAS a blind ClearPedTasksImmediately every 60
        -- frames, which wiped the idle once a second (a flash of T-pose each time).
        -- Now the same check the confirmed freecam_quantum_hold uses: clear only
        -- when task 57/313/const-drill is actually live, plus a slow 10s net.
        local live = false
        pcall(function() live = StaticFeatures.quantum_task_live(ped) == true end)
        if live or (StaticFeatures._qnc_frames % 600 == 0) then
            pcall(ClearPedTasksImmediately, ped)
            StaticFeatures._qnc_pose_try_ms = 0   -- re-apply the idle this same frame
        end
        -- <<QNC RAGDOLL FIX 2026-10-13>> THE SHIFT T-POSE. Shift triples the body
        -- velocity (18 -> 54 m/s) and at that speed the engine throws the ped into a
        -- high-velocity ragdoll. With collision off the ragdoll has no physics to
        -- simulate against, so it freezes rigid in the bind pose - the T-pose - and the
        -- ragdoll task displaces the idle, which then cannot come back. Hold ragdoll off
        -- for the whole flight (the build's freecam already does the same on quantum);
        -- restored to its prior value in Stop.
        pcall(SetPedCanRagdoll, ped, false)
        pcall(SetPedCanRagdollFromPlayerImpact, ped, false)
        -- <<QNC POSE 2026-10-12>> immediately after the clear, so the wipe above
        -- costs one frame of bind pose rather than a second of it.
        StaticFeatures.qnc_pose_ensure(ped)
        end -- <<QNC DEAD FIX>> alive branch
    end

    local now = (type(GetGameTimer) == "function" and GetGameTimer()) or 0
    local dt = (now - (StaticFeatures._qnc_last or now)) / 1000.0
    if dt > 0.1 then dt = 0.1 end
    StaticFeatures._qnc_last = now

    local spd = tonumber((Menu and Menu.noclipSpeed) or 1.0) or 1.0
    local mult = StaticFeatures.qnc_held(0xA0, 0x10) and StaticFeatures.QNC_BOOST or 1.0
    local mps = spd * StaticFeatures.QNC_SPEED_MPS * mult
    -- <<QNC CRASH FIX>> this is REAL physics velocity, not a coord write. The
    -- slider goes to 25, so 25 x 18 x 3 boost = 1350 m/s of body velocity with
    -- collision off - streaming and physics cannot keep up and the engine dies.
    -- Cap it; the host noclip could take 25 because it wrote coords instead.
    if mps > StaticFeatures.QNC_MAX_MPS then mps = StaticFeatures.QNC_MAX_MPS end

    if tf then StaticFeatures.qnc_log("tick d:camrot") end
    local cam = GetGameplayCamRot(2)
    local fh = math.rad(cam.z)
    local fp = math.rad(cam.x)
    local fx = -math.sin(fh) * math.cos(fp)
    local fy =  math.cos(fh) * math.cos(fp)
    local fz =  math.sin(fp)
    local rx =  math.cos(fh)
    local ry =  math.sin(fh)

    -- <<QNC FACE CAM 2026-10-13>> body follows the camera yaw. Only written when it is
    -- off by more than 2 degrees, so a still camera costs nothing.
    if StaticFeatures.QNC_FACE_CAM and not seated and StaticFeatures._qnc_dead ~= true then
        local okh, curh = pcall(GetEntityHeading, ped)
        local want = cam.z % 360.0
        if okh and type(curh) == "number" then
            local diff = math.abs(((want - curh) + 540.0) % 360.0 - 180.0)
            if diff > 2.0 then pcall(SetEntityHeading, ped, want) end
        end
    end

    local vx, vy, vz = 0.0, 0.0, 0.0
    if StaticFeatures.qnc_held(0x57) then vx = vx + fx; vy = vy + fy; vz = vz + fz end
    if StaticFeatures.qnc_held(0x53) then vx = vx - fx; vy = vy - fy; vz = vz - fz end
    if StaticFeatures.qnc_held(0x44) then vx = vx + rx; vy = vy + ry end
    if StaticFeatures.qnc_held(0x41) then vx = vx - rx; vy = vy - ry end
    if StaticFeatures.qnc_held(0x20) then vz = vz + 1.0 end
    if StaticFeatures.qnc_held(0xA2, 0x11) then vz = vz - 1.0 end

    local len = math.sqrt(vx * vx + vy * vy + vz * vz)
    if len > 0.001 then
        vx, vy, vz = vx / len * mps, vy / len * mps, vz / len * mps
    else
        vx, vy, vz = 0.0, 0.0, 0.0
    end

    -- <<QNC CRASH FIX>> never push the body outside the playable world - out of
    -- bounds with collision off is an engine fault, not a fall. Kill only the
    -- outward component so you can still fly back.
    local tb = StaticFeatures._qnc_truth
    if tb then
        local W = StaticFeatures.QNC_WORLD
        if (tb.x >  W.xy and vx > 0) or (tb.x < -W.xy and vx < 0) then vx = 0.0 end
        if (tb.y >  W.xy and vy > 0) or (tb.y < -W.xy and vy < 0) then vy = 0.0 end
        if (tb.z >  W.zmax and vz > 0) or (tb.z < W.zmin and vz < 0) then vz = 0.0 end
    end

    -- the ONLY thing that moves the body. No coordinate setter anywhere.
    if tf then StaticFeatures.qnc_log(string.format("tick e:velocity %.1f/%.1f/%.1f", vx, vy, vz)) end
    SetEntityVelocity(ent, vx, vy, vz)
    StaticFeatures._qnc_frames = StaticFeatures._qnc_frames + 1

    -- drift is INTEGRATED from the commanded velocity, never read back from
    -- GetEntityCoords, because that native is one of the shield members and a
    -- read here would report 0.0 for ever.
    local t = StaticFeatures._qnc_truth
    local a = StaticFeatures._qnc_anchor
    if t then
        t.x = t.x + vx * dt
        t.y = t.y + vy * dt
        t.z = t.z + vz * dt

        -- <<QNC TRACKING>> walk the reported position toward the real one, and
        -- hold the STREAMING FOCUS on where we really are. Without the focus the
        -- map around the destination never loads, which is what left the ped
        -- stuck or falling when noclip ended somewhere the world had not
        -- streamed in.
        StaticFeatures.qnc_advance_lie(dt)
        -- <<QNC CRASH FIX>> WAS every 15 frames with zero velocity: at speed the
        -- focus lagged hundreds of metres behind the body, so it flew into
        -- unstreamed sectors. Every frame, and hand streaming the real velocity
        -- so it loads AHEAD of us.
        -- <<QNC CRASH FIX 2026-10-10 b>> THROTTLED. The confirmed standalone
        -- never touched the streaming focus at all - this was added on top of
        -- it, and moving the focus every frame while the body is physically
        -- flying with collision off is streaming churn that faults with no Lua
        -- error. Five a second, or sooner once 20m have gone by, keeps the
        -- world ahead of us and still pre-streams with the real velocity.
        if StaticFeatures.QNC_FOCUS then
            local fa  = StaticFeatures._qnc_focus_at
            local due = (now - (StaticFeatures._qnc_focus_ms or 0))
                >= (StaticFeatures.QNC_FOCUS_MS or 200)
            if not due then
                if type(fa) == "table" then
                    local fdx, fdy, fdz = t.x - fa.x, t.y - fa.y, t.z - fa.z
                    if math.sqrt(fdx * fdx + fdy * fdy + fdz * fdz)
                        >= (StaticFeatures.QNC_FOCUS_M or 20.0) then due = true end
                else
                    due = true
                end
            end
            if due then
                pcall(SetFocusPosAndVel, t.x, t.y, t.z, vx, vy, vz)
                StaticFeatures._qnc_focus_at = { x = t.x, y = t.y, z = t.z }
                StaticFeatures._qnc_focus_ms = now
            end
        end

        if a then
            local dd = math.sqrt((t.x - a.x) ^ 2 + (t.y - a.y) ^ 2 + (t.z - a.z) ^ 2)
            if dd > StaticFeatures._qnc_max_drift then
                StaticFeatures._qnc_max_drift = dd
            end
        end
    end

    -- INPUT CANARY. Reports which key path is actually feeding the loop, so a
    -- dead input and a dead feature can be told apart in ONE run rather than
    -- three. If keys_seen stays 0 the event path is not being served; if both
    -- hit counters stay 0 while keys_seen climbs, the VK codes are wrong.
    if StaticFeatures._qnc_frames % 180 == 0 then
        StaticFeatures.qnc_log(string.format(
            "hb drift=%.1fm mps=%.1f frames=%d | keys_seen=%d evt_hits=%d poll_hits=%d",
            StaticFeatures._qnc_max_drift, mps, StaticFeatures._qnc_frames,
            StaticFeatures._qnc_keys_seen, StaticFeatures._qnc_hits_evt,
            StaticFeatures._qnc_hits_poll))
    end
end

function StaticFeatures.qnc_converge_step()
    local st = (type(SharkAPI) == "table") and SharkAPI.SyncTree or nil
    local from = StaticFeatures._qnc_spoof_at
    if type(st) ~= "table" or type(st.SpoofServerCoords) ~= "function" or not from then
        StaticFeatures._qnc_converging = false
        pcall(StaticFeatures.qnc_spoof, false)
        return
    end
    local now = (type(GetGameTimer) == "function" and GetGameTimer()) or 0
    local dt = (now - (StaticFeatures._qnc_conv_last or now)) / 1000.0
    if dt > 0.1 then dt = 0.1 end
    StaticFeatures._qnc_conv_last = now
    -- CORRECTED 2026-10-10: read the REAL position here. Convergence only ever
    -- runs after StopNoclipQuantum has already taken the shield down and cleared
    -- _qnc_on, so qnc_gate() is false and GetEntityCoords is honest at this
    -- point - the earlier worry about converging the lie onto the lie does not
    -- apply here. It matters because _qnc_truth is INTEGRATED from commanded
    -- velocity, and physics does not carry the body exactly as commanded, so
    -- over a long flight it drifts. Converging onto the estimate left a real
    -- gap between the reported position and the body, which is precisely the
    -- gap anti-teleport then corrected. Fall back to the estimate only if the
    -- read fails.
    local real
    local okR, rp = pcall(GetEntityCoords, PlayerPedId())
    if okR and rp and rp.x == rp.x then
        real = { x = rp.x, y = rp.y, z = rp.z }
    else
        local tr = StaticFeatures._qnc_truth
        real = (type(tr) == "table") and tr or { x = from.x, y = from.y, z = from.z }
    end
    local dx, dy, dz = real.x - from.x, real.y - from.y, real.z - from.z
    local d = math.sqrt(dx * dx + dy * dy + dz * dz)
    if d < 1.5 then
        StaticFeatures._qnc_converging = false
        pcall(StaticFeatures.qnc_spoof, false)
        StaticFeatures.qnc_log("converge arrived, spoof released")
        StaticFeatures.qnc_maybe_release_hold()
        return
    end
    -- in tracking mode close the gap at the same plausible speed the lie was
    -- already allowed to travel at; WALK_MPS only applies to the old pin mode
    local rate = (StaticFeatures.QNC_SPOOF_MODE == "track")
        and StaticFeatures.qnc_track_mps() or StaticFeatures.QNC_WALK_MPS
    local step = rate * dt
    if step > d then step = d end
    from = vector3(from.x + dx / d * step, from.y + dy / d * step, from.z + dz / d * step)
    pcall(st.SpoofServerCoords, true, from)
    StaticFeatures._qnc_spoof_at = from
    -- keep the lie table in step with what is actually being reported
    local lt = StaticFeatures._qnc_lie
    if type(lt) == "table" then lt.x, lt.y, lt.z = from.x, from.y, from.z end
end

-- ── start / stop ────────────────────────────────────────────────────────────

function StaticFeatures.StartNoclipQuantum()
    if StaticFeatures._qnc_on then return true end
    -- <<QNC SAFEMODE 2026-10-11>> force the confirmed artifact's behaviour first
    local safe = StaticFeatures.qnc_apply_safemode()
    StaticFeatures.qnc_log("start: safemode=" .. tostring(safe)
        .. " focus=" .. tostring(StaticFeatures.QNC_FOCUS)
        .. " mode=" .. tostring(StaticFeatures.QNC_SPOOF_MODE)
        .. " maxmps=" .. tostring(StaticFeatures.QNC_MAX_MPS))
    StaticFeatures.qnc_log("step 1/6 reading ped")
    local ped = PlayerPedId()
    StaticFeatures._qnc_ped = ped   -- <<QNC CRASH FIX>> hooks compare against this, never call PlayerPedId
    local ent = ped
    if type(IsPedInAnyVehicle) == "function" and IsPedInAnyVehicle(ped, false) then
        local v = GetVehiclePedIsIn(ped, false)
        if v and v ~= 0 then ent = v end
    end
    local pos = GetEntityCoords(ent)
    if not pos or pos.x ~= pos.x or (pos.x == 0.0 and pos.y == 0.0) then
        StaticFeatures.qnc_log("^1refusing: anchor is NaN or origin^0")
        return false
    end
    StaticFeatures._qnc_anchor    = pos
    StaticFeatures._qnc_anchor_h  = GetEntityHeading(ent) + 0.0
    StaticFeatures._qnc_spoof_at  = pos
    StaticFeatures._qnc_frames    = 0
    StaticFeatures._qnc_pose_ok   = nil   -- <<QNC POSE>> re-ask per run
    StaticFeatures._qnc_pose_wait = 0
    StaticFeatures._qnc_pose_try_ms = 0
    -- <<QNC RAGDOLL FIX 2026-10-13>> remember the ragdoll setting so Stop can put it back
    do
        local okr, can = pcall(CanPedRagdoll, PlayerPedId())
        StaticFeatures._qnc_ragdoll_was = (okr and (can == true or can == 1)) and true or false
        if not okr then StaticFeatures._qnc_ragdoll_was = true end
    end
    StaticFeatures._qnc_max_drift = 0.0
    StaticFeatures._qnc_last      = (type(GetGameTimer) == "function" and GetGameTimer()) or 0

    StaticFeatures.qnc_log("step 2/6 anchor ok, arming sync-tree spoof")
    if not StaticFeatures.qnc_spoof(true, pos, StaticFeatures._qnc_anchor_h) then
        StaticFeatures.qnc_log("^1refusing: the coord spoof did not arm - that is the desync^0")
        StaticFeatures._qnc_anchor = nil
        StaticFeatures._qnc_spoof_at = nil
        return false
    end

    -- shield up BEFORE the fly flag, so no frame of real movement is readable.
    -- qnc_gate reads _qnc_on, so nothing is spoofed until the line below.
    StaticFeatures.qnc_log("step 3/6 spoof armed, client-side shield stage")
    if not StaticFeatures.qnc_shield_up() then
        StaticFeatures.qnc_log("^1refusing: client-side shield did not arm^0")
        pcall(StaticFeatures.qnc_spoof, false)
        StaticFeatures._qnc_anchor = nil
        StaticFeatures._qnc_spoof_at = nil
        return false
    end

    StaticFeatures._qnc_truth = { x = pos.x, y = pos.y, z = pos.z }
    -- the lie starts exactly where we are, then follows us
    StaticFeatures._qnc_lie = { x = pos.x, y = pos.y, z = pos.z }
    StaticFeatures._qnc_lie_pushed = nil
    StaticFeatures._qnc_push_ms   = 0
    StaticFeatures._qnc_focus_at  = nil
    StaticFeatures._qnc_focus_ms  = 0
    -- <<QNC CRASH FIX 2026-10-10 b>> the cached object must exist BEFORE the
    -- gate opens on the line below, or the first spoofed frame reads nil.
    StaticFeatures.qnc_rep_refresh()
    StaticFeatures.qnc_log("step 4/6 reported-position object built")
    StaticFeatures._qnc_settle_at = nil
    -- <<QNC TP HOLD>> tell the Anti-Teleport loop to stand down. Written ONCE
    -- here and once on stop, never per frame.
    StaticFeatures._qnc_hold_done = nil
    StaticFeatures._qnc_hold_until = nil
    pcall(function() LocalPlayer.state:set(StaticFeatures.TP_HOLD_KEY, true, false) end)
    StaticFeatures.qnc_log("step 5/6 state seeded, opening the gate")
    StaticFeatures._qnc_on = true
    StaticFeatures.qnc_log("step 6/6 gate OPEN - the hooks are now answering")
    StaticFeatures.qnc_log(string.format(
        "ON anchor=%.1f/%.1f/%.1f mode=%s render=%s body_cap=%.0fm/s reported_cap=%.0fm/s",
        pos.x, pos.y, pos.z, tostring(StaticFeatures.QNC_SPOOF_MODE),
        tostring(StaticFeatures.QNC_RENDER ~= false),
        StaticFeatures.QNC_MAX_MPS, StaticFeatures.qnc_track_mps()))
    return true
end

function StaticFeatures.StopNoclipQuantum()
    if not StaticFeatures._qnc_on then
        StaticFeatures._qnc_converging = false
        StaticFeatures._qnc_settle_at = nil
        pcall(StaticFeatures.qnc_shield_down, true)
        pcall(StaticFeatures.qnc_spoof, false)
        if StaticFeatures.QNC_FOCUS then pcall(ClearFocus) end
        -- a bare stop must still be able to drop the hold, or anti-teleport
        -- stays stood down for the rest of the session
        pcall(function() LocalPlayer.state:set(StaticFeatures.TP_HOLD_KEY, false, false) end)
        return
    end
    StaticFeatures._qnc_on = false
    pcall(StaticFeatures.qnc_shield_down, true)
    local ped = PlayerPedId()
    local ent = ped
    if type(IsPedInAnyVehicle) == "function" and IsPedInAnyVehicle(ped, false) then
        local v = GetVehiclePedIsIn(ped, false)
        if v and v ~= 0 then ent = v end
    end
    -- Velocity goes to zero NOW, but collision and gravity stay OFF for
    -- QNC_SETTLE_MS while the focus still holds the destination. Restoring
    -- physics the instant we stop is what dropped the ped into unstreamed
    -- geometry and left it stuck. qnc_settle_step finishes the job.
    pcall(function() SetEntityVelocity(ent, 0.0, 0.0, 0.0) end)

    -- <<QNC POSE 2026-10-12>> drop the idle so the ped goes back to its normal
    -- locomotion instead of landing still in the idle.
    -- <<QNC DEAD FIX 2026-10-13>> never clear a dead ped's tasks on exit either
    local deadNow = false
    pcall(function() deadNow = StaticFeatures.qnc_truthy(IsPedDeadOrDying(ped, true)) or StaticFeatures.qnc_truthy(IsEntityDead(ped)) end)
    StaticFeatures._qnc_dead, StaticFeatures._qnc_dead_logged = nil, nil
    if StaticFeatures.QNC_POSE == true and not deadNow then
        pcall(ClearPedTasks, ped)
        pcall(RemoveAnimDict, StaticFeatures.QNC_POSE_DICT)
    end
    -- <<QNC RAGDOLL FIX 2026-10-13>> give ragdoll back exactly as it was
    if StaticFeatures._qnc_ragdoll_was ~= nil then
        pcall(SetPedCanRagdoll, ped, StaticFeatures._qnc_ragdoll_was)
        pcall(SetPedCanRagdollFromPlayerImpact, ped, StaticFeatures._qnc_ragdoll_was)
        StaticFeatures._qnc_ragdoll_was = nil
    end
    pcall(EnableAllControlActions, 0)
    -- clear the held table, or a key released after the feature stopped latches
    -- on and the next run starts already "holding" it
    StaticFeatures._qnc_held_tbl = {}
    local nowMs = (type(GetGameTimer) == "function" and GetGameTimer()) or 0
    StaticFeatures._qnc_settle_at = nowMs + (StaticFeatures.QNC_SETTLE_MS or 0)
    StaticFeatures.qnc_log(string.format("OFF frames=%d max_drift=%.1fm coordsets=%d - settling %dms",
        StaticFeatures._qnc_frames, StaticFeatures._qnc_max_drift,
        StaticFeatures._qnc_coordsets, StaticFeatures.QNC_SETTLE_MS or 0))

    -- How big is the remaining gap between what we report and where we are? In
    -- tracking mode the lie has been following all along, so this is usually
    -- near zero and the release is immediate - which is the whole point.
    local gap = 0.0
    local l = StaticFeatures._qnc_lie
    local t = StaticFeatures._qnc_truth
    -- measure against the REAL body, not the integrated estimate - the shield is
    -- already down here, so this read is honest, and it is the number that
    -- decides whether a gap is left for anti-teleport to find
    local okR2, rp2 = pcall(GetEntityCoords, PlayerPedId())
    if okR2 and rp2 and rp2.x == rp2.x then t = { x = rp2.x, y = rp2.y, z = rp2.z } end
    if type(l) == "table" and type(t) == "table" then
        gap = math.sqrt((t.x - l.x) ^ 2 + (t.y - l.y) ^ 2 + (t.z - l.z) ^ 2)
    end
    if StaticFeatures.QNC_CONVERGE and StaticFeatures._qnc_spoof_at and gap > 2.0 then
        StaticFeatures._qnc_converging = true
        StaticFeatures._qnc_conv_last = nowMs
        StaticFeatures.qnc_log(string.format("converge: closing a %.1fm gap at %.0fm/s",
            gap, StaticFeatures.QNC_SPOOF_MPS))
    else
        StaticFeatures._qnc_converging = false
        pcall(StaticFeatures.qnc_spoof, false)
        StaticFeatures.qnc_log(string.format("spoof released immediately - gap was %.1fm", gap))
    end
    StaticFeatures._qnc_anchor = nil
end

-- Restore physics only once the world has had a moment to stream in, then let
-- the focus go. Called by the driver.
function StaticFeatures.qnc_settle_step()
    local due = StaticFeatures._qnc_settle_at
    if not due then return end
    local now = (type(GetGameTimer) == "function" and GetGameTimer()) or 0
    if now < due then return end
    StaticFeatures._qnc_settle_at = nil
    local ped = PlayerPedId()
    local ent = ped
    if type(IsPedInAnyVehicle) == "function" and IsPedInAnyVehicle(ped, false) then
        local v = GetVehiclePedIsIn(ped, false)
        if v and v ~= 0 then ent = v end
    end
    pcall(function()
        SetEntityCollision(ent, true, true)
        SetEntityHasGravity(ent, true)
    end)
    if StaticFeatures.QNC_FOCUS then pcall(ClearFocus) end
    StaticFeatures.qnc_log("settled - collision and gravity back, focus cleared")
    StaticFeatures.qnc_maybe_release_hold()
end

-- The Anti-Teleport hold comes down only when BOTH the physics settle and the
-- spoof convergence are finished. Dropping it while a gap is still open is
-- exactly what let the anti-teleport loop snap us back.
function StaticFeatures.qnc_maybe_release_hold()
    if StaticFeatures._qnc_on then return end
    if StaticFeatures._qnc_settle_at then return end
    if StaticFeatures._qnc_converging then return end
    if StaticFeatures._qnc_hold_done then return end
    local now = (type(GetGameTimer) == "function" and GetGameTimer()) or 0
    -- GRACE. Releasing on the same frame convergence finishes gives the
    -- anti-teleport loop no frame in which to take a clean reference, and its
    -- very next comparison can still straddle the correction. Hold a beat, then
    -- drop. Driver calls this every frame while not flying, so it completes.
    if not StaticFeatures._qnc_hold_until then
        StaticFeatures._qnc_hold_until = now + (StaticFeatures.QNC_HOLD_GRACE_MS or 1500)
        return
    end
    if now < StaticFeatures._qnc_hold_until then return end
    StaticFeatures._qnc_hold_until = nil
    StaticFeatures._qnc_hold_done = true
    pcall(function() LocalPlayer.state:set(StaticFeatures.TP_HOLD_KEY, false, false) end)
    StaticFeatures.qnc_log("anti-teleport hold released")
end

-- <<QNC RENDER 2026-10-11 freecam>> SAME FAULT, DIFFERENT SUBSYSTEM.
-- Freecam parks the body and flies a script camera. SetFocusPosAndVel in the
-- freecam loop already streams the MAP toward the camera, but it cannot stream
-- PLAYERS: on OneSync the server decides which entities to send us from our
-- server-side position, and that is the parked body. So the camera flies into a
-- world with the map but nobody in it - the same complaint as noclip, and the
-- same fix, which is to report the position we are actually looking from.
--
-- Host side only. The freecam movement loop lives inside an injected payload
-- and SyncTree is executor-only, so nothing here touches that payload: the
-- rendered camera position is read with GetFinalRenderedCamCoord, a plain
-- getter that answers whichever VM owns the cam. _G._FREECAM_RUNNING is set by
-- StartFreecam/StopFreecam (and by the beta picker), so it is a real host-side
-- flag rather than a global an inject writes.
--
-- quantum only. Reporting a position the body is not at is the mechanism noclip
-- already uses and has confirmed there; on every other anticheat this does
-- nothing, because no other server has a confirmed verdict on it.
StaticFeatures.FREECAM_RENDER   = true   -- stream players around the freecam camera
StaticFeatures._fcr_on          = false
StaticFeatures._fcr_at          = nil
StaticFeatures._fcr_ms          = 0
StaticFeatures._fcr_returning   = false

function StaticFeatures.qnc_freecam_render_step()
    if StaticFeatures.FREECAM_RENDER == false then return end
    -- Never while the noclip route owns the spoof, and never while its exit
    -- convergence or settle is still running. Drop our own follow state on the
    -- way out too: noclip owns the release from here, so if freecam were up
    -- when noclip started, resuming afterwards from a stale _fcr_at would walk
    -- the reported position home from a point that is minutes out of date.
    if StaticFeatures._qnc_on or StaticFeatures._qnc_converging
        or StaticFeatures._qnc_settle_at then
        StaticFeatures._fcr_on        = false
        StaticFeatures._fcr_at        = nil
        StaticFeatures._fcr_returning = false
        return
    end
    if type(StaticFeatures.quantum_present) ~= "function"
        or not StaticFeatures.quantum_present() then return end

    local st = (type(SharkAPI) == "table") and SharkAPI.SyncTree or nil
    if type(st) ~= "table" or type(st.SpoofServerCoords) ~= "function" then return end

    local running = (_G._FREECAM_RUNNING == true)
    local now = (type(GetGameTimer) == "function" and GetGameTimer()) or 0

    if running then
        StaticFeatures._fcr_returning = false
        if (now - (StaticFeatures._fcr_ms or 0)) < (StaticFeatures.QNC_PUSH_MS or 100) then return end
        local ok, cc = pcall(GetFinalRenderedCamCoord)
        if not ok or not cc or cc.x ~= cc.x then return end
        local last = StaticFeatures._fcr_at
        if type(last) == "table" then
            local dx, dy, dz = cc.x - last.x, cc.y - last.y, cc.z - last.z
            if math.sqrt(dx * dx + dy * dy + dz * dz) < (StaticFeatures.QNC_PUSH_M or 3.0) then
                return
            end
        end
        pcall(st.SpoofServerCoords, true, cc)
        StaticFeatures._fcr_at = { x = cc.x, y = cc.y, z = cc.z }
        StaticFeatures._fcr_ms = now
        if not StaticFeatures._fcr_on then
            StaticFeatures._fcr_on = true
            StaticFeatures.qnc_log("freecam render-follow ON - players stream around the camera")
        end
        return
    end

    if not StaticFeatures._fcr_on then return end

    -- Freecam stopped. The body never moved, so there is no gap to close for
    -- US - but the server has us out at the camera, and dropping that in one
    -- step is a teleport from its point of view. Walk it home at the same rate
    -- the noclip lie travels at, then release.
    local okP, rp = pcall(GetEntityCoords, PlayerPedId())
    local from = StaticFeatures._fcr_at
    if not okP or not rp or rp.x ~= rp.x or type(from) ~= "table" then
        pcall(st.SpoofServerCoords, false)
        StaticFeatures._fcr_on = false
        StaticFeatures._fcr_at = nil
        StaticFeatures.qnc_log("freecam render-follow OFF - released")
        return
    end
    local dt = (now - (StaticFeatures._fcr_ms or now)) / 1000.0
    if dt > 0.1 then dt = 0.1 end
    StaticFeatures._fcr_ms = now
    local dx, dy, dz = rp.x - from.x, rp.y - from.y, rp.z - from.z
    local d = math.sqrt(dx * dx + dy * dy + dz * dz)
    if d < 1.5 then
        pcall(st.SpoofServerCoords, false)
        StaticFeatures._fcr_on = false
        StaticFeatures._fcr_at = nil
        StaticFeatures._fcr_returning = false
        StaticFeatures.qnc_log("freecam render-follow OFF - walked home, released")
        return
    end
    if not StaticFeatures._fcr_returning then
        StaticFeatures._fcr_returning = true
        StaticFeatures.qnc_log(string.format("freecam render-follow: walking a %.0fm gap home", d))
    end
    local step = StaticFeatures.qnc_track_mps() * dt
    if step > d then step = d end
    local nx = from.x + dx / d * step
    local ny = from.y + dy / d * step
    local nz = from.z + dz / d * step
    local okV, v = pcall(vector3, nx, ny, nz)
    if okV and v then pcall(st.SpoofServerCoords, true, v) end
    StaticFeatures._fcr_at = { x = nx, y = ny, z = nz }
end

-- ── the driver ──────────────────────────────────────────────────────────────
-- ONE thread, spawned HERE while the main chunk runs. Confirmed 2026-10-09:
-- a thread spawned from inside a key/menu callback after the chunk has returned
-- is created and NEVER serviced, so the body never executes once and nothing
-- throws. Everything periodic for this feature runs in this one thread.

if type(CreateThread) == "function" and not StaticFeatures._qnc_driver then
    StaticFeatures._qnc_driver = true
    CreateThread(function()
        StaticFeatures.qnc_log("driver entered")
        while true do
            Wait(0)
            if StaticFeatures._qnc_on then
                local ok, err = pcall(StaticFeatures.qnc_tick)
                if not ok then
                    StaticFeatures.qnc_log("^1driver tick threw -> " .. tostring(err) .. "^0")
                    pcall(StaticFeatures.StopNoclipQuantum)
                end
            else
                -- settle and convergence are independent and can overlap: one
                -- restores physics, the other closes the reported-position gap.
                -- The anti-teleport hold drops only when both are done.
                if StaticFeatures._qnc_settle_at then
                    pcall(StaticFeatures.qnc_settle_step)
                end
                if StaticFeatures._qnc_converging then
                    pcall(StaticFeatures.qnc_converge_step)
                end
                -- the hold has a grace period, so this must be polled rather
                -- than fired once from whichever step happened to finish last
                pcall(StaticFeatures.qnc_maybe_release_hold)
                -- <<QNC RENDER 2026-10-11 freecam>> only ever reached while the
                -- noclip route is not flying, which is the gate this step needs
                pcall(StaticFeatures.qnc_freecam_render_step)
            end
        end
    end)
end
-- <<END STATIC QUANTUM NOCLIP>> ==============================================

StaticFeatures._quantum_restart_hook_installed = false

function StaticFeatures.detect_quantum_on_join()
    if _G.__STATIC_QUANTUM_SPOOF_ON == true then
        StaticFeatures._quantum_on_join = true
        return true
    end
    StaticFeatures._quantum_on_join = false
    if StaticFeatures.quantum_present() then
        StaticFeatures._quantum_on_join = true
        menu_dbg("^2[Static]^0 Quantum AC detected — applying antispoof bypass")
        pcall(StaticFeatures.quantum_arm_antispoof)

        if not StaticFeatures._quantum_restart_hook_installed
            and type(SharkAPI) == "table" and type(SharkAPI.Resources) == "table"
            and type(SharkAPI.Resources.OnResourceRestart) == "function" then
            StaticFeatures._quantum_restart_hook_installed = true
            pcall(SharkAPI.Resources.OnResourceRestart, function(restartedName)
                if tostring(restartedName) == "quantum" then
                    _G.__STATIC_QUANTUM_SPOOF_ON = false
                    pcall(StaticFeatures.quantum_arm_antispoof)
                end
            end)
        end
    end
    return StaticFeatures._quantum_on_join
end

-- Quantum PERSISTENT EARLY BOOT THREAD: quantum can stream in late on heavy servers,
-- so poll until armed, then re-check every 5s so a restart re-arms.
if type(CreateThread) == "function" then
    CreateThread(function()
        local t0 = (type(GetGameTimer) == "function" and GetGameTimer()) or 0
        while not _G.__STATIC_QUANTUM_SPOOF_ON do
            if StaticFeatures.quantum_present and StaticFeatures.quantum_present() then
                pcall(StaticFeatures.detect_quantum_on_join)
            end
            local elapsed = ((type(GetGameTimer) == "function" and GetGameTimer()) or 0) - t0
            Wait(elapsed < 10000 and 0 or 2000)
        end
        while true do
            Wait(5000)
            if StaticFeatures.quantum_present and StaticFeatures.quantum_present()
                and not _G.__STATIC_QUANTUM_SPOOF_ON then
                pcall(StaticFeatures.quantum_arm_antispoof)
            end
        end
    end)
end

-- ═══════════════════════════════════════════════════════════════════════════════════════════════════════
-- Quantum / TLA — entity persistence, prop spawning (ported from peep build, 2026-10-03).
-- ═══════════════════════════════════════════════════════════════════════════════════════════════════════

function StaticFeatures.quantum_persist(ent, nativeName)
    if not ent or ent == 0 or not DoesEntityExist(ent) then return 0 end
    pcall(SetEntityAsMissionEntity, ent, true, true)
    pcall(function()
        local key = "qac:entMeta"
        local val = {
            native    = nativeName or "CreateObject",
            resource  = "es_extended",
            clientQACentity = true,
        }
        Entity(ent).state:set(key, val, true)
    end)
    return ent
end

function StaticFeatures.quantum_prop_claim(ent)
    return StaticFeatures.quantum_persist(ent, "CreateObject")
end

-- ══════════════ TLA / QUANTUM OBJECT ROUTE - fsg_cooking (SERVER-CREATED) ══════════════
-- CONFIRMED IN GAME 2026-10-03. The SERVER performs the create and hands back a netId.
StaticFeatures.COOK_PROP_RES  = "fsg_cooking"
StaticFeatures.COOK_PROP_SKEY = "__tlacookprop"
StaticFeatures._cook_prop_n   = 0

function StaticFeatures.quantum_cooking_prop_at(model, x, y, z, heading, hidden)
    if type(SharkAPI) ~= "table" or type(SharkAPI.InjectSafe) ~= "function" then return false end
    if GetResourceState(StaticFeatures.COOK_PROP_RES) ~= "started" then return false end

    local hash = (type(model) == "string") and GetHashKey(model) or model
    if type(hash) ~= "number" or hash == 0 then return false end
    local okc, incd = pcall(IsModelInCdimage, hash)
    if okc and incd == false then
        menu_dbg("^1[Static quantum]^0 cooking prop refused - model not in cdimage: " .. tostring(model))
        return false
    end

    local SK = StaticFeatures.COOK_PROP_SKEY
    StaticFeatures._cook_prop_n = (StaticFeatures._cook_prop_n or 0) + 1
    local fid = tostring(GetGameTimer()) .. "-" .. tostring(StaticFeatures._cook_prop_n)

    pcall(function() LocalPlayer.state:set(SK, nil, false) end)

    local payload = ([==[
local SK, FID = '%s', '%s'
LocalPlayer.state:set(SK, { ran = true, fid = FID }, false)
CreateThread(function()
    local ok, err = pcall(function()
        if type(lib) ~= 'table' or type(lib.callback) ~= 'table' then
            LocalPlayer.state:set(SK, { ran = true, done = true, fid = FID, netId = 0 }, false)
            return
        end
        local netId = lib.callback.await('fsg_cooking:server:createPropEntity',
            false, '%s', vector3(%s, %s, %s), vector3(0.0, 0.0, %s),
            'st' .. tostring(GetGameTimer()), 0)
        LocalPlayer.state:set(SK, { ran = true, done = true, fid = FID, netId = netId or 0 }, false)
    end)
    if not ok then
        LocalPlayer.state:set(SK, { ran = true, done = true, fid = FID, netId = 0,
            err = tostring(err) }, false)
    end
end)
]==]):format(SK, fid, tostring(model),
             tostring(x + 0.0), tostring(y + 0.0), tostring(z + 0.0),
             tostring((tonumber(heading) or 0.0) + 0.0))

    pcall(SharkAPI.InjectSafe, StaticFeatures.COOK_PROP_RES, payload)

    local waited, res = 0, nil
    while waited < 6000 do
        local v
        pcall(function() v = LocalPlayer.state[SK] end)
        if type(v) == "table" and v.done and v.fid == fid then res = v break end
        Wait(100)
        waited = waited + 100
    end

    if type(res) ~= "table" then
        menu_dbg("^1[Static quantum]^0 cooking prop - no marker in " .. tostring(waited) .. "ms")
        return false
    end
    local netId = tonumber(res.netId) or 0
    if netId == 0 then
        menu_dbg("^3[Static quantum]^0 cooking prop - server returned netId 0 for " .. tostring(model))
        return false
    end

    local ent = NetworkGetEntityFromNetworkId(netId)
    if type(ent) ~= "number" or ent == 0 or not DoesEntityExist(ent) then
        menu_dbg("^1[Static quantum]^0 cooking prop - netId " .. tostring(netId) .. " resolved to nothing")
        return false
    end
    pcall(SetEntityAsMissionEntity, ent, true, true)
    if hidden then pcall(SetEntityVisible, ent, false, false) end
    pcall(SetEntityHeading, ent, (tonumber(heading) or 0.0) + 0.0)

    menu_dbg("^2[Static quantum]^0 cooking prop ok - netId " .. tostring(netId)
        .. " ent " .. tostring(ent) .. " model " .. tostring(model))
    return ent
end

function StaticFeatures.quantum_prop_spawn_at(model, x, y, z, heading, hidden)
    if not StaticFeatures.quantum_present() then return false end
    StaticFeatures.quantum_arm_antispoof()

    -- TLA COOKING ROUTE (server-created, CONFIRMED 2026-10-03). Tried FIRST because the
    -- SERVER creates the entity — the only route that produces a networked prop on quantum.
    if type(StaticFeatures.quantum_cooking_prop_at) == "function"
        and GetResourceState(StaticFeatures.COOK_PROP_RES or "fsg_cooking") == "started" then
        local ent = StaticFeatures.quantum_cooking_prop_at(model, x, y, z, heading, hidden)
        if type(ent) == "number" and ent ~= 0 and DoesEntityExist(ent) then
            return ent
        end
    end

    -- svdden route REMOVED 2026-10-03 (BROKEN on quantum). quantum_svdden_prop_at is left
    -- DEFINED and uncalled so nothing breaks on a missing name.

    if type(SharkAPI) ~= "table" or type(SharkAPI.InjectSafe) ~= "function" then
        menu_dbg("^1[Static quantum]^0 prop refused - InjectSafe unavailable")
        return false
    end
    if GetResourceState("rpemotes-reborn") ~= "started" then
        menu_dbg("^1[Static quantum]^0 prop refused - rpemotes-reborn not started")
        return false
    end

    local mname = tostring(model or "prop_atm_01")
    local cleaned = mname:gsub("%s+", "")
    mname = cleaned
    local hash = GetHashKey(mname)
    if not IsModelValid(hash) then
        menu_dbg("^1[Static quantum]^0 invalid model: " .. mname)
        return false
    end

    local sx = string.format("%.3f", tonumber(x) or 0.0)
    local sy = string.format("%.3f", tonumber(y) or 0.0)
    local sz = string.format("%.3f", tonumber(z) or 0.0)
    local sh = string.format("%.3f", tonumber(heading) or 0.0)
    local sHash = tostring(hash)
    local sHide = (hidden == true) and "true" or "false"
    local KEY = "qprop_ent"

    pcall(function() LocalPlayer.state:set(KEY, 0, false) end)

    local payload = [===[
CreateThread(function()
    local SKEY = "]===] .. KEY .. [===["
    local function done(v) pcall(function() LocalPlayer.state:set(SKEY, v, false) end) end
    if GetCurrentResourceName() ~= "rpemotes-reborn" then done(0) return end
    if type(addProps) ~= "function" or type(Config) ~= "table" then done(0) return end

    local MHASH = ]===] .. sHash .. [===[
    local hadFlag = Config.UseOldPropSpawning
    Config.UseOldPropSpawning = true

    local before = {}
    local pool = GetGamePool("CObject") or {}
    for i = 1, #pool do
        local seen = pool[i]
        before[seen] = true
    end

    local animOption = {
        Prop = "]===] .. mname .. [===[",
        PropBone = 28422,
        PropPlacement = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 },
        EmoteDuration = 0,
        PropNoCollision = false,
    }
    local HIDE = ]===] .. sHide .. [===[
    pcall(addProps, animOption, nil, nil, PlayerId(), false)

    local prop, deadline = 0, GetGameTimer() + 8000
    while prop == 0 and GetGameTimer() < deadline do
        Wait(100)
        local now = GetGamePool("CObject") or {}
        for i = 1, #now do
            local e = now[i]
            if not before[e] and DoesEntityExist(e) and GetEntityModel(e) == MHASH then
                prop = e
                if HIDE then
                    SetEntityVisible(prop, false, false)
                    SetEntityAlpha(prop, 0, false)
                    SetEntityCollision(prop, false, false)
                end
                break
            end
        end
    end

    Config.UseOldPropSpawning = hadFlag
    if prop == 0 then done(0) return end

    SetEntityAsMissionEntity(prop, true, true)
    local t = GetGameTimer() + 1500
    while not IsEntityAttached(prop) and GetGameTimer() < t do Wait(50) end
    if HIDE then
        SetEntityVisible(prop, false, false)
        SetEntityAlpha(prop, 0, false)
    end
    DetachEntity(prop, true, true)
    SetEntityCoordsNoOffset(prop, ]===] .. sx .. [===[, ]===] .. sy .. [===[, ]===] .. sz .. [===[, false, false, false)
    SetEntityHeading(prop, ]===] .. sh .. [===[)
    FreezeEntityPosition(prop, true)
    if HIDE then
        SetEntityVisible(prop, false, false)
        SetEntityAlpha(prop, 0, false)
        SetEntityCollision(prop, false, false)
    else
        SetEntityCollision(prop, true, true)
    end

    local nid = 0
    if NetworkGetEntityIsNetworked(prop) == true then nid = NetworkGetNetworkIdFromEntity(prop) end
    if nid ~= 0 then
        SetNetworkIdExistsOnAllMachines(nid, true)
        SetNetworkIdCanMigrate(nid, false)
    end
    done(prop)
end)
]===]

    if not pcall(SharkAPI.InjectSafe, "rpemotes-reborn", payload) then
        menu_dbg("^1[Static quantum]^0 prop delivery threw")
        return false
    end

    local ent, waited = 0, 0
    while waited < 15000 do
        Wait(250)
        waited = waited + 250
        local ok, v = pcall(function() return LocalPlayer.state[KEY] end)
        if ok and tonumber(v) and tonumber(v) ~= 0 then ent = tonumber(v) break end
    end
    pcall(function() LocalPlayer.state:set(KEY, 0, false) end)

    if ent == 0 then
        menu_dbg("^1[Static quantum]^0 no prop came back for " .. mname)
        return false
    end

    _G.__STATIC_QUANTUM_PROPS = _G.__STATIC_QUANTUM_PROPS or {}
    local list = _G.__STATIC_QUANTUM_PROPS
    list[#list + 1] = ent
    menu_dbg("^2[Static quantum]^0 prop " .. mname .. " ent=" .. tostring(ent))
    return ent
end

function StaticFeatures.quantum_svdden_prop_at(model, x, y, z, heading, hidden)
    if not StaticFeatures.quantum_present() then return false end
    StaticFeatures.quantum_arm_antispoof()

    if GetResourceState("crn_ui_svdden") ~= "started" then
        menu_dbg("^1[Static quantum]^0 prop refused - crn_ui_svdden not started")
        return false
    end

    local mname = tostring(model or "prop_atm_01")
    local cleaned = mname:gsub("%s+", "")
    mname = cleaned
    local hash = GetHashKey(mname)
    if not IsModelValid(hash) and not IsModelInCdimage(hash) then
        menu_dbg("^1[Static quantum]^0 invalid model: " .. mname)
        return false
    end

    local function fire()
        pcall(TriggerEvent, "crn_ui_svdden:smokeItem", {
            model = mname,
            animationData = { "amb@world_human_aa_smoke@male@idle_a", "idle_c" },
            useDuration = 600,
        })
    end

    local function snapshot()
        local seen, p = {}, GetGamePool("CObject") or {}
        for i = 1, #p do seen[p[i]] = true end
        return seen
    end

    local function new_handle(before, deadlineMs)
        local stop = GetGameTimer() + deadlineMs
        while GetGameTimer() < stop do
            Wait(100)
            local p = GetGamePool("CObject") or {}
            for i = 1, #p do
                local e = p[i]
                if not before[e] and DoesEntityExist(e) and GetEntityModel(e) == hash then
                    return e
                end
            end
        end
        return 0
    end

    local before1 = snapshot()
    fire()
    local prop = new_handle(before1, 8000)
    if prop == 0 then
        menu_dbg("^1[Static quantum]^0 no prop came back for " .. mname
            .. " (crn_ui_svdden busy or model refused)")
        return false
    end

    local HIDE = (hidden == true)
    if HIDE then
        SetEntityVisible(prop, false, false)
        SetEntityAlpha(prop, 0, false)
        SetEntityCollision(prop, false, true)
    end

    local before2 = snapshot()
    fire()
    local decoy = new_handle(before2, 4000)

    SetEntityAsMissionEntity(prop, true, true)
    local t = GetGameTimer() + 2000
    while not IsEntityAttached(prop) and GetGameTimer() < t do Wait(50) end

    DetachEntity(prop, true, true)
    SetEntityCoordsNoOffset(prop,
        tonumber(x) or 0.0, tonumber(y) or 0.0, tonumber(z) or 0.0, false, false, false)
    SetEntityHeading(prop, tonumber(heading) or 0.0)
    FreezeEntityPosition(prop, true)
    if HIDE then
        SetEntityVisible(prop, false, false)
        SetEntityAlpha(prop, 0, false)
        SetEntityCollision(prop, false, true)
    else
        SetEntityCollision(prop, true, true)
    end

    if decoy and decoy ~= 0 and decoy ~= prop and DoesEntityExist(decoy) then
        pcall(DetachEntity, decoy, true, true)
        pcall(FreezeEntityPosition, decoy, true)
        pcall(SetEntityCollision, decoy, false, false)
        pcall(SetEntityVisible, decoy, false, false)
        pcall(SetEntityAsMissionEntity, decoy, true, true)
        pcall(DeleteEntity, decoy)
        if DoesEntityExist(decoy) then
            Wait(0)
            pcall(DeleteEntity, decoy)
        end
        menu_dbg("^2[Static quantum]^0 decoy prop removed from player ent=" .. tostring(decoy))
    end

    local nid = 0
    if NetworkGetEntityIsNetworked(prop) == true then nid = NetworkGetNetworkIdFromEntity(prop) end
    if nid ~= 0 then
        SetNetworkIdExistsOnAllMachines(nid, true)
        SetNetworkIdCanMigrate(nid, false)
    end

    _G.__STATIC_QUANTUM_PROPS = _G.__STATIC_QUANTUM_PROPS or {}
    local list = _G.__STATIC_QUANTUM_PROPS
    list[#list + 1] = prop
    menu_dbg("^2[Static quantum]^0 prop " .. mname .. " ent=" .. tostring(prop)
        .. " net=" .. tostring(nid ~= 0) .. " via crn_ui_svdden")
    return prop
end

-- FiniAC emote resource finder (fingerprint-based).
function StaticFeatures.fini_emote_resource(forceRefresh)
    local override = _G.__STATIC_FINI_EMOTE_RES
    if type(override) == "string" and override ~= "" then return override end
    if not forceRefresh and StaticFeatures._fini_emote_res_cache ~= nil then
        return StaticFeatures._fini_emote_res_cache ~= false and StaticFeatures._fini_emote_res_cache or nil
    end
    local total = _static_num_resources()
    for i = 0, total - 1 do
        local res = _static_resource_by_index(i)
        if res and _static_resource_state(res) == "started" then
            local okLoad, content = pcall(LoadResourceFile, res, "client/Emote.lua")
            if okLoad and type(content) == "string"
                and content:find("function AddProp(", 1, true)
                and content:find("function DestroyAllProps(", 1, true) then
                StaticFeatures._fini_emote_res_cache = res
                return res
            end
        end
    end
    StaticFeatures._fini_emote_res_cache = false
    return nil
end

function StaticFeatures.fini_prop_spawn_at(model, x, y, z, heading, hidden)
    if type(SharkAPI) ~= "table" or type(SharkAPI.InjectSafe) ~= "function" then
        menu_dbg("^1[Static fini]^0 prop refused - InjectSafe unavailable")
        return false
    end

    if type(StaticFeatures.ensure_fini_bypass_armed) == "function" then
        pcall(StaticFeatures.ensure_fini_bypass_armed, "prop")
    end
    if type(StaticFeatures.ensure_finiac_bypass_armed) == "function" then
        pcall(StaticFeatures.ensure_finiac_bypass_armed)
    end

    local RES = StaticFeatures.fini_emote_resource(false)
    if not RES then
        RES = StaticFeatures.fini_emote_resource(true)
    end
    if not RES then
        menu_dbg("^1[Static fini]^0 prop refused - no emote resource with AddProp on this server")
        return false
    end

    local mname = tostring(model or "prop_atm_01")
    local cleaned = mname:gsub("%s+", "")
    mname = cleaned
    local hash = GetHashKey(mname)
    if not IsModelValid(hash) then
        menu_dbg("^1[Static fini]^0 invalid model: " .. mname)
        return false
    end

    local sx = string.format("%.3f", tonumber(x) or 0.0)
    local sy = string.format("%.3f", tonumber(y) or 0.0)
    local sz = string.format("%.3f", tonumber(z) or 0.0)
    local sh = string.format("%.3f", tonumber(heading) or 0.0)
    local sHash = tostring(hash)
    local sHide = (hidden == true) and "true" or "false"
    local KEY = "fprop_ent"

    pcall(function() LocalPlayer.state:set(KEY, 0, false) end)

    local payload = [===[
CreateThread(function()
    local SKEY = "]===] .. KEY .. [===["
    local function done(v) pcall(function() LocalPlayer.state:set(SKEY, v, false) end) end
    if GetCurrentResourceName() ~= "]===] .. RES .. [===[" then done(0) return end
    if type(AddProp) ~= "function" then done(0) return end

    local MHASH = ]===] .. sHash .. [===[
    local MODEL = "]===] .. mname .. [===["
    local HIDE = ]===] .. sHide .. [===[

    local before = {}
    local pool = GetGamePool("CObject") or {}
    for i = 1, #pool do
        local seen = pool[i]
        before[seen] = true
    end

    pcall(AddProp, MODEL, 28422, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, nil, false)

    local prop, deadline = 0, GetGameTimer() + 8000
    while prop == 0 and GetGameTimer() < deadline do
        Wait(100)
        local quick = attachedProp
        if type(quick) == "number" and quick ~= 0 and not before[quick]
            and DoesEntityExist(quick) and GetEntityModel(quick) == MHASH then
            prop = quick
        else
            local now = GetGamePool("CObject") or {}
            for i = 1, #now do
                local e = now[i]
                if not before[e] and DoesEntityExist(e) and GetEntityModel(e) == MHASH then
                    prop = e
                    break
                end
            end
        end
        if prop ~= 0 and HIDE then
            SetEntityVisible(prop, false, false)
            SetEntityAlpha(prop, 0, false)
            SetEntityCollision(prop, false, false)
        end
    end
    if prop == 0 then done(0) return end

    SetEntityAsMissionEntity(prop, true, true)

    local removed = 0
    pcall(function()
        if type(debug) ~= "table" or type(debug.getupvalue) ~= "function" then return end
        if type(DestroyAllProps) ~= "function" then return end
        local n = 1
        while true do
            local uname, uval = debug.getupvalue(DestroyAllProps, n)
            if uname == nil then break end
            if type(uval) == "table" then
                for i = #uval, 1, -1 do
                    if uval[i] == prop then
                        table.remove(uval, i)
                        removed = removed + 1
                    end
                end
            end
            n = n + 1
        end
    end)
    pcall(function() LocalPlayer.state:set(SKEY .. "_rm", removed, false) end)

    local t = GetGameTimer() + 1500
    while not IsEntityAttached(prop) and GetGameTimer() < t do Wait(50) end
    if HIDE then
        SetEntityVisible(prop, false, false)
        SetEntityAlpha(prop, 0, false)
    end
    DetachEntity(prop, true, true)
    SetEntityCoordsNoOffset(prop, ]===] .. sx .. [===[, ]===] .. sy .. [===[, ]===] .. sz .. [===[, false, false, false)
    SetEntityHeading(prop, ]===] .. sh .. [===[)
    FreezeEntityPosition(prop, true)
    if HIDE then
        SetEntityVisible(prop, false, false)
        SetEntityAlpha(prop, 0, false)
        SetEntityCollision(prop, false, false)
    else
        SetEntityCollision(prop, true, true)
    end

    local nid = 0
    if NetworkGetEntityIsNetworked(prop) == true then nid = NetworkGetNetworkIdFromEntity(prop) end
    if nid ~= 0 then
        SetNetworkIdExistsOnAllMachines(nid, true)
        SetNetworkIdCanMigrate(nid, false)
    end
    done(prop)
end)
]===]

    if not pcall(SharkAPI.InjectSafe, RES, payload) then
        menu_dbg("^1[Static fini]^0 prop delivery threw for " .. tostring(RES))
        return false
    end

    local ent, waited = 0, 0
    while waited < 15000 do
        Wait(250)
        waited = waited + 250
        local ok, v = pcall(function() return LocalPlayer.state[KEY] end)
        if ok and tonumber(v) and tonumber(v) ~= 0 then ent = tonumber(v) break end
    end
    pcall(function() LocalPlayer.state:set(KEY, 0, false) end)

    if ent == 0 then
        menu_dbg("^1[Static fini]^0 no prop came back for " .. mname .. " from " .. tostring(RES))
        return false
    end

    _G.__STATIC_FINI_PROPS = _G.__STATIC_FINI_PROPS or {}
    local list = _G.__STATIC_FINI_PROPS
    list[#list + 1] = ent
    menu_dbg("^2[Static fini]^0 prop " .. mname .. " ent=" .. tostring(ent) .. " via " .. tostring(RES))

    CreateThread(function()
        local born = _static_game_timer()
        local marks = { 1000, 3000, 10000, 30000 }
        for i = 1, #marks do
            while (_static_game_timer() - born) < marks[i] do Wait(250) end
            local alive = false
            pcall(function() alive = DoesEntityExist(ent) == true end)
            if not alive then
                StaticFeatures.menu_notify("Fini Prop",
                    mname .. " GONE after " .. tostring(math.floor((_static_game_timer() - born) / 1000)) .. "s",
                    "error")
                menu_dbg("^1[Static fini]^0 prop " .. mname .. " ent=" .. tostring(ent)
                    .. " deleted at ~" .. tostring(marks[i]) .. "ms")
                return
            end
        end
        menu_dbg("^2[Static fini]^0 prop " .. mname .. " ent=" .. tostring(ent) .. " survived 30s")
    end)

    return ent
end

-- <<QFC PORT 2026-10-13>> BEGIN quantum object method (our route), verbatim from the working build.
-- Defined AFTER this build's older copies so these win (codewave route added).
-- ═══════════════════════════════════════════════════════════════════════════════════════════════════════
-- Quantum / TLA — entity persistence, prop spawning (ported from peep build, 2026-10-03).
-- ═══════════════════════════════════════════════════════════════════════════════════════════════════════

function StaticFeatures.quantum_persist(ent, nativeName)
    if not ent or ent == 0 or not DoesEntityExist(ent) then return 0 end
    pcall(SetEntityAsMissionEntity, ent, true, true)
    pcall(function()
        local key = "qac:entMeta"
        local val = {
            native    = nativeName or "CreateObject",
            resource  = "es_extended",
            clientQACentity = true,
        }
        Entity(ent).state:set(key, val, true)
    end)
    return ent
end

function StaticFeatures.quantum_prop_claim(ent)
    return StaticFeatures.quantum_persist(ent, "CreateObject")
end

-- ══════════════ TLA / QUANTUM OBJECT ROUTE - fsg_cooking (SERVER-CREATED) ══════════════
-- CONFIRMED IN GAME 2026-10-03. The SERVER performs the create and hands back a netId.
StaticFeatures.COOK_PROP_RES  = "fsg_cooking"
StaticFeatures.COOK_PROP_SKEY = "__tlacookprop"
StaticFeatures._cook_prop_n   = 0

function StaticFeatures.quantum_cooking_prop_at(model, x, y, z, heading, hidden)
    if type(SharkAPI) ~= "table" or type(SharkAPI.InjectSafe) ~= "function" then return false end
    if GetResourceState(StaticFeatures.COOK_PROP_RES) ~= "started" then return false end

    local hash = (type(model) == "string") and GetHashKey(model) or model
    if type(hash) ~= "number" or hash == 0 then return false end
    local okc, incd = pcall(IsModelInCdimage, hash)
    if okc and incd == false then
        menu_dbg("^1[Static quantum]^0 cooking prop refused - model not in cdimage: " .. tostring(model))
        return false
    end

    local SK = StaticFeatures.COOK_PROP_SKEY
    StaticFeatures._cook_prop_n = (StaticFeatures._cook_prop_n or 0) + 1
    local fid = tostring(GetGameTimer()) .. "-" .. tostring(StaticFeatures._cook_prop_n)

    pcall(function() LocalPlayer.state:set(SK, nil, false) end)

    local payload = ([==[
local SK, FID = '%s', '%s'
LocalPlayer.state:set(SK, { ran = true, fid = FID }, false)
CreateThread(function()
    local ok, err = pcall(function()
        if type(lib) ~= 'table' or type(lib.callback) ~= 'table' then
            LocalPlayer.state:set(SK, { ran = true, done = true, fid = FID, netId = 0 }, false)
            return
        end
        local netId = lib.callback.await('fsg_cooking:server:createPropEntity',
            false, '%s', vector3(%s, %s, %s), vector3(0.0, 0.0, %s),
            'st' .. tostring(GetGameTimer()), 0)
        LocalPlayer.state:set(SK, { ran = true, done = true, fid = FID, netId = netId or 0 }, false)
    end)
    if not ok then
        LocalPlayer.state:set(SK, { ran = true, done = true, fid = FID, netId = 0,
            err = tostring(err) }, false)
    end
end)
]==]):format(SK, fid, tostring(model),
             tostring(x + 0.0), tostring(y + 0.0), tostring(z + 0.0),
             tostring((tonumber(heading) or 0.0) + 0.0))

    pcall(SharkAPI.InjectSafe, StaticFeatures.COOK_PROP_RES, payload)

    local waited, res = 0, nil
    while waited < 6000 do
        local v
        pcall(function() v = LocalPlayer.state[SK] end)
        if type(v) == "table" and v.done and v.fid == fid then res = v break end
        Wait(100)
        waited = waited + 100
    end

    if type(res) ~= "table" then
        menu_dbg("^1[Static quantum]^0 cooking prop - no marker in " .. tostring(waited) .. "ms")
        return false
    end
    local netId = tonumber(res.netId) or 0
    if netId == 0 then
        menu_dbg("^3[Static quantum]^0 cooking prop - server returned netId 0 for " .. tostring(model))
        return false
    end

    local ent = NetworkGetEntityFromNetworkId(netId)
    if type(ent) ~= "number" or ent == 0 or not DoesEntityExist(ent) then
        menu_dbg("^1[Static quantum]^0 cooking prop - netId " .. tostring(netId) .. " resolved to nothing")
        return false
    end
    pcall(SetEntityAsMissionEntity, ent, true, true)
    if hidden then pcall(SetEntityVisible, ent, false, false) end
    pcall(SetEntityHeading, ent, (tonumber(heading) or 0.0) + 0.0)

    menu_dbg("^2[Static quantum]^0 cooking prop ok - netId " .. tostring(netId)
        .. " ent " .. tostring(ent) .. " model " .. tostring(model))
    return ent
end

-- ===========================================================================
-- [[ QUANTUM POLICE PROP ROUTE  2026-10-08 ]]  CONFIRMED IN GAME
-- wasabi_police/game/client/client.lua:646
--   AddEventHandler('wasabi_police:spawnProp', function(index)
--       local prop = Config.Props[index]
--       local obj = CreateObjectNoOffset(prop.model, x, y, z, true, false, false)
--       SetEntityHeading(obj, ...)  PlaceObjectOnGroundProperly(obj)
--       if prop.freeze ~= false then FreezeEntityPosition(obj, true) end
--   end)
-- AddEventHandler, so a plain local TriggerEvent reaches it - nothing leaves the
-- client and no quantum token is needed. No permission check on this path: the
-- groups table in Config.Props is read only by their MENU builder. isNetwork is
-- true and the create happens inside THEIR file, which is the attribution.
--
-- INDEX 3 is not arbitrary. config.lua:464 gives slot 3 freeze = false; slots
-- 1, 2 and 4 are freeze = true and their handler would FreezeEntityPosition the
-- prop solid - fatal for the Guided Missile.
--
-- Config is a GLOBAL in their VM (config.lua:5), so the model is patchable. Two
-- injects per spawn: patch, then restore. Safe to restore immediately because
-- their handler has NO yield between reading Config.Props[index] and the create.
-- ===========================================================================
StaticFeatures.QPOLICE_RES   = "wasabi_police"
StaticFeatures.QPOLICE_INDEX = 3
StaticFeatures.QPOLICE_BAG   = "__static_qpolprop"

function StaticFeatures.quantum_police_prop_at(model, x, y, z, heading)
    print("[DIAG] quantum_police_prop_at ENTRY model=" .. tostring(model))
    if type(model) ~= "string" or model == "" then return nil end
    if GetResourceState(StaticFeatures.QPOLICE_RES) ~= "started" then return nil end
    if type(SharkAPI) ~= "table" then return nil end
    local inj = SharkAPI.InjectSafe or SharkAPI.Inject
    if type(inj) ~= "function" then return nil end

    local hash = GetHashKey(model)
    if type(IsModelInCdimage) == "function" and not IsModelInCdimage(hash) then return nil end
    -- Their handler contains zero RequestModel calls - their own four props are
    -- always resident, so an unstreamed model fails the create SILENTLY and
    -- looks exactly like an anticheat strip. Make it resident first.
    if not HasModelLoaded(hash) then
        RequestModel(hash)
        local dl = GetGameTimer() + 5000
        while not HasModelLoaded(hash) and GetGameTimer() < dl do Wait(0) end
        if not HasModelLoaded(hash) then return nil end
    end

    local bag = StaticFeatures.QPOLICE_BAG
    local idx = tostring(StaticFeatures.QPOLICE_INDEX)
    local head = 'local R = "?"' .. string.char(10)
        .. 'if type(GetCurrentResourceName) == "function" then R = GetCurrentResourceName() end' .. string.char(10)
        .. 'local function mark(t) t.vm = R t.ran = true pcall(function() LocalPlayer.state:set("'
        .. bag .. '", t, false) end) end' .. string.char(10)
        .. 'mark({})' .. string.char(10)
        .. 'if R ~= "wasabi_police" then mark({done=true,err="wrong vm"}) return end' .. string.char(10)
        .. 'if type(Config) ~= "table" or type(Config.Props) ~= "table" then mark({done=true,err="no Config.Props"}) return end' .. string.char(10)
        .. 'local slot = Config.Props[' .. idx .. ']' .. string.char(10)
        .. 'if type(slot) ~= "table" then mark({done=true,err="no slot"}) return end' .. string.char(10)

    local function deliver(code)
        pcall(function() LocalPlayer.state:set(bag, nil, false) end)
        pcall(inj, StaticFeatures.QPOLICE_RES, code)
        local m
        for _ = 1, 120 do
            Wait(0)
            local ok, v = pcall(function() return LocalPlayer.state[bag] end)
            if ok then m = v end
            if type(m) == "table" and m.done then break end
        end
        if type(m) ~= "table" or m.err then return nil end
        return m
    end

    if not deliver(head
        .. 'if _G.__STATIC_QPOL_ORIG == nil then _G.__STATIC_QPOL_ORIG = slot.model end' .. string.char(10)
        .. 'slot.model = ' .. tostring(hash) .. string.char(10)
        .. 'mark({ done = true, patched = true })' .. string.char(10)) then
        return nil
    end

    local before = {}
    local pool0 = GetGamePool("CObject")
    if type(pool0) == "table" then for k = 1, #pool0 do before[pool0[k]] = true end end

    pcall(TriggerEvent, "wasabi_police:spawnProp", StaticFeatures.QPOLICE_INDEX)

    -- Restore immediately: no yield in their handler between the config read and
    -- the create, so this cannot win the race the way the medbag restore did.
    deliver(head
        .. 'local o = _G.__STATIC_QPOL_ORIG' .. string.char(10)
        .. 'if o ~= nil then slot.model = o end' .. string.char(10)
        .. 'mark({ done = true, restored = true })' .. string.char(10))

    local ent = nil
    for _ = 1, 120 do
        Wait(0)
        local pool = GetGamePool("CObject")
        if type(pool) == "table" then
            for k = 1, #pool do
                local e = pool[k]
                if e and e ~= 0 and not before[e] and DoesEntityExist(e)
                    and GetEntityScript(e) == StaticFeatures.QPOLICE_RES
                    and GetEntityModel(e) == hash then
                    ent = e
                    break
                end
            end
        end
        if ent then break end
    end
    print("[DIAG] quantum_police_prop_at loop result ent=" .. tostring(ent))
    if not ent then return nil end

    -- <<STATIC QPOL SURVIVAL>> 2026-10-08 diagnostic for "sometimes the prop gets cleared".
    -- Reads only (no ownership native - those would re-attribute it away from wasabi_police).
    -- netId 0 / networked false at birth = the server declined registration (self-only, will be
    -- stripped). Death time tells a client reclaim (<1s) from a server strip (seconds) from a sweep.
    do
        local e0, born = ent, GetGameTimer()
        local net0 = NetworkGetEntityIsNetworked(e0) and true or false
        local nid0 = net0 and NetworkGetNetworkIdFromEntity(e0) or 0
        print("[QPOL-SURVIVE] born ent=" .. tostring(e0) .. " model=" .. tostring(model)
            .. " networked=" .. tostring(net0) .. " netId=" .. tostring(nid0)
            .. (nid0 == 0 and "  <<< NOT REGISTERED - server will not keep this one" or ""))
        CreateThread(function()
            local marks = { 1000, 3000, 10000, 30000, 60000 }
            local mi = 1
            while GetGameTimer() - born < 120000 do
                Wait(250)
                local age = GetGameTimer() - born
                if not DoesEntityExist(e0) then
                    local pc = GetEntityCoords(PlayerPedId())
                    local far = (x and #(pc - vector3(x, y, z)) or 0)
                    print("[QPOL-SURVIVE] GONE ent=" .. tostring(e0) .. " netId=" .. tostring(nid0)
                        .. " after " .. tostring(age) .. "ms  bornNetworked=" .. tostring(net0)
                        .. string.format("  you are %.0fm away", far)
                        .. (far > 300 and "  (likely OUT OF RANGE, not deleted)" or ""))
                    return
                end
                if marks[mi] and age >= marks[mi] then
                    print("[QPOL-SURVIVE] alive ent=" .. tostring(e0) .. " +" .. tostring(marks[mi]) .. "ms"
                        .. " networked=" .. tostring(NetworkGetEntityIsNetworked(e0) and true or false))
                    mi = mi + 1
                end
            end
            print("[QPOL-SURVIVE] SURVIVED 120s ent=" .. tostring(e0))
        end)
    end

    -- Their code grounded it where WE were standing, not where the caller asked.
    -- Freeze is already off on slot 3, so it can simply be moved.
    if x and y and z then
        pcall(SetEntityCoordsNoOffset, ent, x + 0.0, y + 0.0, z + 0.0, false, false, false)
    end
    if heading then pcall(SetEntityHeading, ent, heading + 0.0) end
    return ent
end
-- [[ END QUANTUM POLICE PROP ROUTE ]]

-- [[ BEGIN QUANTUM CODEWAVE PROP ROUTE ]]  <<QCODEWAVE>>
StaticFeatures.QCODEWAVE_RES   = "codewave-sneaker-business"
StaticFeatures.QCODEWAVE_SPAWN = "codewave:spawnShoetable"
StaticFeatures.QCODEWAVE_CLEAR = "codewave-item:deletePlacedPropsShoes"
StaticFeatures.QCODEWAVE_STOCK = "prop_table_03"   -- config.lua:79, external authority

-- Spawns via codewave and returns the HANDLE, or false. Confirmed in game
-- 2026-10-08. Mirrors the standalone at tla_prop/New folder/TLA_PROP_CODEWAVE_CUSTOM.lua.
function StaticFeatures.quantum_codewave_prop_at(model, x, y, z, heading)
    local RES = StaticFeatures.QCODEWAVE_RES
    if GetResourceState(RES) ~= "started" then return false end
    model = tostring(model or "")
    if model == "" then return false end

    -- Their handler has ZERO RequestModel calls, so an unstreamed model fails
    -- silently and is indistinguishable from a refusal. Make it resident first
    -- and refuse by name instead of firing blind.
    local h = GetHashKey(model)
    RequestModel(h)
    local dl = _static_game_timer() + 8000
    while not HasModelLoaded(h) and _static_game_timer() < dl do Wait(50) end
    if not HasModelLoaded(h) then
        print("[DIAG] codewave route: " .. model .. " never streamed - refusing")
        return false
    end

    -- ALWAYS clear first: their shapeTestResult latch (client.lua:82) makes a
    -- repeat fire a silent no-op, which is the works-once-then-never-again bug.
    -- <<QMASK CLEARGUARD>> while masks are kept, codewave's deletes during this clear are
    -- dropped by the mask hooks so the previous player's mask survives.
    StaticFeatures._qcw_del_blocked = 0
    StaticFeatures._qcw_clear_window = true
    pcall(TriggerEvent, StaticFeatures.QCODEWAVE_CLEAR)
    Wait(250)
    StaticFeatures._qcw_clear_window = false
    if (StaticFeatures._qcw_del_blocked or 0) > 0 then
        print("[DIAG] codewave clear: blocked " .. StaticFeatures._qcw_del_blocked .. " delete(s) of a kept mask")
    end

    local function pool()
        local t = {}
        local ok, l = pcall(GetGamePool, "CObject")
        if ok and type(l) == "table" then for i = 1, #l do t[l[i]] = true end end
        return t
    end
    local before = pool()

    -- One inject: patch their config global, fire from inside their VM, restore
    -- from a captured original that survives a re-run.
    local NL = string.char(10)
    local payload =
        'local R = GetCurrentResourceName()' .. NL ..
        'if R ~= "' .. RES .. '" then return end' .. NL ..
        'CreateThread(function()' .. NL ..
        '  if type(Config) ~= "table" then return end' .. NL ..
        '  if _G.__CW_ORIG_PROP == nil then _G.__CW_ORIG_PROP = Config.PropItemName end' .. NL ..
        '  local orig = _G.__CW_ORIG_PROP or "' .. StaticFeatures.QCODEWAVE_STOCK .. '"' .. NL ..
        '  pcall(function()' .. NL ..
        '    Config.PropItemName = "' .. model .. '"' .. NL ..
        '    TriggerEvent("' .. StaticFeatures.QCODEWAVE_SPAWN .. '")' .. NL ..
        '    Wait(2500)' .. NL ..
        '  end)' .. NL ..
        '  Config.PropItemName = orig' .. NL ..
        'end)'
    if type(StaticFeatures.shark_inject) == "function" then
        pcall(StaticFeatures.shark_inject, RES, payload)
    elseif type(SharkAPI) == "table" and type(SharkAPI.Inject) == "function" then
        pcall(SharkAPI.Inject, RES, payload, "@@")
    else
        return false
    end

    -- Adopt ONLY what codewave made. A new pool handle alone is not proof - an
    -- earlier run adopted two w_pi_pistol props from our own fake-weapon feature
    -- and reported a server strip that never happened.
    local ent = 0
    for _ = 1, 60 do
        Wait(50)
        for e in pairs(pool()) do
            if not before[e] and DoesEntityExist(e) then
                local scr = "?"
                pcall(function() scr = tostring(GetEntityScript(e) or "?") end)
                if scr == RES then ent = e break end
            end
        end
        if ent ~= 0 then break end
    end
    if ent == 0 then
        print("[DIAG] codewave route: nothing with script=" .. RES)
        return false
    end

    -- Their code froze it 1.5m in front. Move it to where the caller asked.
    -- No ownership native: that would re-attribute it away from codewave.
    --
    -- <<QCODEWAVE>> DELIBERATELY LEFT UNFROZEN. An earlier version of this ended
    -- with FreezeEntityPosition(ent, true) and that broke the Guided Missile: the
    -- drone goes straight from A.acquire to the camera and the flight loop and
    -- NEVER unfreezes the prop itself, so whatever state the spawner hands back is
    -- what it tries to fly. A frozen prop cannot be driven by SetEntityVelocity.
    -- The wasabi_police route this replaced also never froze, which is why the
    -- missile worked on it - so not freezing is matching the route that worked,
    -- not a guess. Velocity is zeroed instead, which keeps a placed prop still
    -- without taking away the missile's ability to move.
    -- codewave's own SetEntityCollision(obj, false, true) is already the right
    -- state for flight: collision off, PHYSICS KEPT.
    if x and y and z then
        pcall(FreezeEntityPosition, ent, false)
        pcall(SetEntityCoordsNoOffset, ent, x + 0.0, y + 0.0, z + 0.0, false, false, false)
        if heading then pcall(SetEntityHeading, ent, heading + 0.0) end
        pcall(SetEntityVelocity, ent, 0.0, 0.0, 0.0)
    end
    print("[DIAG] codewave route: ent=" .. ent .. " model=" .. model)
    return ent
end
-- [[ END QUANTUM CODEWAVE PROP ROUTE ]]

function StaticFeatures.quantum_prop_spawn_at(model, x, y, z, heading, hidden)
    print("[DIAG] quantum_prop_spawn_at ENTRY model=" .. tostring(model))
    if not StaticFeatures.quantum_present() then return false end
    StaticFeatures.quantum_arm_antispoof()

    -- TLA COOKING ROUTE -- DISABLED 2026-10-08, user reports it is DETECTED.
    -- It was first here because the SERVER creates the entity and returns a netId,
    -- which is architecturally the strongest shape available on quantum. That is
    -- still true and is exactly why this is a flag rather than a deletion: the
    -- function stays DEFINED and the try-order entry stays in place, so nothing
    -- breaks on a missing name and it can be re-enabled by one boolean if the
    -- detection is ever attributed to something else. Default is OFF.
    -- It is NOT removed from the file, because a route deleted outright is a
    -- route the next session re-derives from scratch.
    StaticFeatures.QCOOK_ENABLED = false
    if StaticFeatures.QCOOK_ENABLED
        and type(StaticFeatures.quantum_cooking_prop_at) == "function"
        and GetResourceState(StaticFeatures.COOK_PROP_RES or "fsg_cooking") == "started" then
        local ent = StaticFeatures.quantum_cooking_prop_at(model, x, y, z, heading, hidden)
        if type(ent) == "number" and ent ~= 0 and DoesEntityExist(ent) then
            return ent
        end
    end

    -- <<QCODEWAVE>> CODEWAVE ROUTE -- CONFIRMED IN GAME 2026-10-08, and now the
    -- FIRST and only live route. Every prop feature on quantum funnels through
    -- this one function, so wiring it here is what fixes the freecam prop rows,
    -- the Guided Missile (A.hardened_spawn_prop -> spawn_prop_at) and the Monkey
    -- Mask in a single edit rather than three.
    --
    --   codewave-sneaker-business/client/client.lua:85
    --     AddEventHandler("codewave:spawnShoetable", function()   -- zero args
    --       CreateObject(GetHashKey(Config.PropItemName), 1.5m in front,
    --                    ped heading, z-1, true, true, false)     -- isNetwork TRUE
    --       SetEntityHeading / SetEntityInvincible
    --       FreezeEntityPosition / SetEntityCollision(obj,false,true)
    --
    -- NOTE FOR THE NEXT SESSION: codewave has NO registration natives at all - no
    -- SetNetworkIdExistsOnAllMachines, no retry loop, no replicated statebag, no
    -- outbound netId - and it works anyway. Registration is not the gate, so do
    -- not re-narrow the route search to resources that register.
    if type(StaticFeatures.quantum_codewave_prop_at) == "function"
        and GetResourceState(StaticFeatures.QCODEWAVE_RES or "codewave-sneaker-business") == "started" then
        local ent = StaticFeatures.quantum_codewave_prop_at(model, x, y, z, heading)
        if type(ent) == "number" and ent ~= 0 and DoesEntityExist(ent) then
            return ent
        end
    end

    -- WASABI_POLICE ROUTE -- DEAD 2026-10-08. Patched SERVER-SIDE by commit
    -- ed4bfbb "fix(wasabi_police): lock the place-object event". Its client file
    -- is byte-identical between the 05-OCT and 08-OCT dumps (md5
    -- ff853bb5fe7221068a1fcbcc5d7bb39b) and the 08-OCT dump was captured AFTER
    -- the ban, so there is nothing client-side to fix and no point retrying it.
    -- It banned the account: born networked netId 2872, server refused
    -- registration, GONE at 1041ms. Left DEFINED and uncalled so nothing breaks
    -- on a missing name, behind a switch that defaults OFF.
    StaticFeatures.QPOLICE_ENABLED = false
    if StaticFeatures.QPOLICE_ENABLED
        and type(StaticFeatures.quantum_police_prop_at) == "function"
        and GetResourceState(StaticFeatures.QPOLICE_RES or "wasabi_police") == "started" then
        local ent = StaticFeatures.quantum_police_prop_at(model, x, y, z, heading)
        if type(ent) == "number" and ent ~= 0 and DoesEntityExist(ent) then
            return ent
        end
    end

    -- svdden route REMOVED 2026-10-03 (BROKEN on quantum). quantum_svdden_prop_at is left
    -- DEFINED and uncalled so nothing breaks on a missing name.

    -- RPEMOTES ROUTE -- DISABLED 2026-10-08, user reports it is DETECTED.
    -- Everything below this point is the rpemotes addProps path. It is flagged
    -- off rather than deleted so nothing breaks on a missing name and one boolean
    -- brings it back if the detection is ever attributed elsewhere.
    --
    -- With cooking disabled above and this disabled here, wasabi_police is the
    -- ONLY live prop route on quantum - which is deliberate. Every prop feature
    -- inherits this chokepoint, so the Guided Missile, Air Stuck and the prop
    -- spawner all now go through wasabi_police and nothing else.
    --
    -- The refusal below is NAMED. Falling through to a dead route silently is how
    -- a refused feature ends up looking like a broken one.
    StaticFeatures.QRPEMOTES_ENABLED = false
    if not StaticFeatures.QRPEMOTES_ENABLED then
        menu_dbg("^1[Static quantum]^0 prop refused - wasabi_police did not produce one and "
            .. "the rpemotes + fsg_cooking routes are both DISABLED (detected 2026-10-08). "
            .. "wasabi_police is the only live prop route on quantum.")
        return false
    end

    if type(SharkAPI) ~= "table" or type(SharkAPI.InjectSafe) ~= "function" then
        menu_dbg("^1[Static quantum]^0 prop refused - InjectSafe unavailable")
        return false
    end
    if GetResourceState("rpemotes-reborn") ~= "started" then
        menu_dbg("^1[Static quantum]^0 prop refused - rpemotes-reborn not started")
        return false
    end

    local mname = tostring(model or "prop_atm_01")
    local cleaned = mname:gsub("%s+", "")
    mname = cleaned
    local hash = GetHashKey(mname)
    if not IsModelValid(hash) then
        menu_dbg("^1[Static quantum]^0 invalid model: " .. mname)
        return false
    end

    local sx = string.format("%.3f", tonumber(x) or 0.0)
    local sy = string.format("%.3f", tonumber(y) or 0.0)
    local sz = string.format("%.3f", tonumber(z) or 0.0)
    local sh = string.format("%.3f", tonumber(heading) or 0.0)
    local sHash = tostring(hash)
    local sHide = (hidden == true) and "true" or "false"
    local KEY = "qprop_ent"

    pcall(function() LocalPlayer.state:set(KEY, 0, false) end)

    local payload = [===[
CreateThread(function()
    local SKEY = "]===] .. KEY .. [===["
    local function done(v) pcall(function() LocalPlayer.state:set(SKEY, v, false) end) end
    if GetCurrentResourceName() ~= "rpemotes-reborn" then done(0) return end
    if type(addProps) ~= "function" or type(Config) ~= "table" then done(0) return end

    local MHASH = ]===] .. sHash .. [===[
    local hadFlag = Config.UseOldPropSpawning
    Config.UseOldPropSpawning = true

    local before = {}
    local pool = GetGamePool("CObject") or {}
    for i = 1, #pool do
        local seen = pool[i]
        before[seen] = true
    end

    local animOption = {
        Prop = "]===] .. mname .. [===[",
        PropBone = 28422,
        PropPlacement = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 },
        EmoteDuration = 0,
        PropNoCollision = false,
    }
    local HIDE = ]===] .. sHide .. [===[
    pcall(addProps, animOption, nil, nil, PlayerId(), false)

    local prop, deadline = 0, GetGameTimer() + 8000
    while prop == 0 and GetGameTimer() < deadline do
        Wait(100)
        local now = GetGamePool("CObject") or {}
        for i = 1, #now do
            local e = now[i]
            if not before[e] and DoesEntityExist(e) and GetEntityModel(e) == MHASH then
                prop = e
                if HIDE then
                    SetEntityVisible(prop, false, false)
                    SetEntityAlpha(prop, 0, false)
                    SetEntityCollision(prop, false, false)
                end
                break
            end
        end
    end

    Config.UseOldPropSpawning = hadFlag
    if prop == 0 then done(0) return end

    SetEntityAsMissionEntity(prop, true, true)
    local t = GetGameTimer() + 1500
    while not IsEntityAttached(prop) and GetGameTimer() < t do Wait(50) end
    if HIDE then
        SetEntityVisible(prop, false, false)
        SetEntityAlpha(prop, 0, false)
    end
    DetachEntity(prop, true, true)
    SetEntityCoordsNoOffset(prop, ]===] .. sx .. [===[, ]===] .. sy .. [===[, ]===] .. sz .. [===[, false, false, false)
    SetEntityHeading(prop, ]===] .. sh .. [===[)
    FreezeEntityPosition(prop, true)
    if HIDE then
        SetEntityVisible(prop, false, false)
        SetEntityAlpha(prop, 0, false)
        SetEntityCollision(prop, false, false)
    else
        SetEntityCollision(prop, true, true)
    end

    local nid = 0
    if NetworkGetEntityIsNetworked(prop) == true then nid = NetworkGetNetworkIdFromEntity(prop) end
    if nid ~= 0 then
        SetNetworkIdExistsOnAllMachines(nid, true)
        SetNetworkIdCanMigrate(nid, false)
    end
    done(prop)
end)
]===]

    if not pcall(SharkAPI.InjectSafe, "rpemotes-reborn", payload) then
        menu_dbg("^1[Static quantum]^0 prop delivery threw")
        return false
    end

    local ent, waited = 0, 0
    while waited < 15000 do
        Wait(250)
        waited = waited + 250
        local ok, v = pcall(function() return LocalPlayer.state[KEY] end)
        if ok and tonumber(v) and tonumber(v) ~= 0 then ent = tonumber(v) break end
    end
    pcall(function() LocalPlayer.state:set(KEY, 0, false) end)

    if ent == 0 then
        menu_dbg("^1[Static quantum]^0 no prop came back for " .. mname)
        return false
    end

    _G.__STATIC_QUANTUM_PROPS = _G.__STATIC_QUANTUM_PROPS or {}
    local list = _G.__STATIC_QUANTUM_PROPS
    list[#list + 1] = ent
    menu_dbg("^2[Static quantum]^0 prop " .. mname .. " ent=" .. tostring(ent))
    return ent
end

function StaticFeatures.quantum_svdden_prop_at(model, x, y, z, heading, hidden)
    if not StaticFeatures.quantum_present() then return false end
    StaticFeatures.quantum_arm_antispoof()

    if GetResourceState("crn_ui_svdden") ~= "started" then
        menu_dbg("^1[Static quantum]^0 prop refused - crn_ui_svdden not started")
        return false
    end

    local mname = tostring(model or "prop_atm_01")
    local cleaned = mname:gsub("%s+", "")
    mname = cleaned
    local hash = GetHashKey(mname)
    if not IsModelValid(hash) and not IsModelInCdimage(hash) then
        menu_dbg("^1[Static quantum]^0 invalid model: " .. mname)
        return false
    end

    local function fire()
        pcall(TriggerEvent, "crn_ui_svdden:smokeItem", {
            model = mname,
            animationData = { "amb@world_human_aa_smoke@male@idle_a", "idle_c" },
            useDuration = 600,
        })
    end

    local function snapshot()
        local seen, p = {}, GetGamePool("CObject") or {}
        for i = 1, #p do seen[p[i]] = true end
        return seen
    end

    local function new_handle(before, deadlineMs)
        local stop = GetGameTimer() + deadlineMs
        while GetGameTimer() < stop do
            Wait(100)
            local p = GetGamePool("CObject") or {}
            for i = 1, #p do
                local e = p[i]
                if not before[e] and DoesEntityExist(e) and GetEntityModel(e) == hash then
                    return e
                end
            end
        end
        return 0
    end

    local before1 = snapshot()
    fire()
    local prop = new_handle(before1, 8000)
    if prop == 0 then
        menu_dbg("^1[Static quantum]^0 no prop came back for " .. mname
            .. " (crn_ui_svdden busy or model refused)")
        return false
    end

    local HIDE = (hidden == true)
    if HIDE then
        SetEntityVisible(prop, false, false)
        SetEntityAlpha(prop, 0, false)
        SetEntityCollision(prop, false, true)
    end

    local before2 = snapshot()
    fire()
    local decoy = new_handle(before2, 4000)

    SetEntityAsMissionEntity(prop, true, true)
    local t = GetGameTimer() + 2000
    while not IsEntityAttached(prop) and GetGameTimer() < t do Wait(50) end

    DetachEntity(prop, true, true)
    SetEntityCoordsNoOffset(prop,
        tonumber(x) or 0.0, tonumber(y) or 0.0, tonumber(z) or 0.0, false, false, false)
    SetEntityHeading(prop, tonumber(heading) or 0.0)
    FreezeEntityPosition(prop, true)
    if HIDE then
        SetEntityVisible(prop, false, false)
        SetEntityAlpha(prop, 0, false)
        SetEntityCollision(prop, false, true)
    else
        SetEntityCollision(prop, true, true)
    end

    if decoy and decoy ~= 0 and decoy ~= prop and DoesEntityExist(decoy) then
        pcall(DetachEntity, decoy, true, true)
        pcall(FreezeEntityPosition, decoy, true)
        pcall(SetEntityCollision, decoy, false, false)
        pcall(SetEntityVisible, decoy, false, false)
        pcall(SetEntityAsMissionEntity, decoy, true, true)
        pcall(DeleteEntity, decoy)
        if DoesEntityExist(decoy) then
            Wait(0)
            pcall(DeleteEntity, decoy)
        end
        menu_dbg("^2[Static quantum]^0 decoy prop removed from player ent=" .. tostring(decoy))
    end

    local nid = 0
    if NetworkGetEntityIsNetworked(prop) == true then nid = NetworkGetNetworkIdFromEntity(prop) end
    if nid ~= 0 then
        SetNetworkIdExistsOnAllMachines(nid, true)
        SetNetworkIdCanMigrate(nid, false)
    end

    _G.__STATIC_QUANTUM_PROPS = _G.__STATIC_QUANTUM_PROPS or {}
    local list = _G.__STATIC_QUANTUM_PROPS
    list[#list + 1] = prop
    menu_dbg("^2[Static quantum]^0 prop " .. mname .. " ent=" .. tostring(prop)
        .. " net=" .. tostring(nid ~= 0) .. " via crn_ui_svdden")
    return prop
end
-- <<QFC PORT 2026-10-13>> END

-- ═══════════════════════════════════════════════════════════════════════════════════════════════════════
-- Quantum / TLA — weapon spawning (ported from peep build, 2026-10-03).
-- TLA_PAINTBALL_AUTO method: patch forcng_playtime whitelist, pin arena spawn,
-- set ChosenWeapon in pug-paintball VM, JoinTeam → startGame → poll isInMatch.
-- ═══════════════════════════════════════════════════════════════════════════════════════════════════════

function StaticFeatures.quantum_arm_playtime()
    local lp = LocalPlayer
    if type(lp) == "table" and type(lp.state) == "table" then
        pcall(function() lp.state:set("playtimeWeaponCheck", 9999.0, false) end)
    end
end

function StaticFeatures.quantum_give_weapon(name, ammo)
    if not StaticFeatures.quantum_present() then return false end
    if StaticFeatures.quantum_arm_antispoof() ~= true then return false end
    local ped = PlayerPedId()
    if not ped or ped == 0 then return false end
    StaticFeatures.quantum_arm_playtime()
    local hash = type(name) == "number" and name or GetHashKey(tostring(name or "WEAPON_PISTOL"))
    pcall(GiveWeaponToPed, ped, hash, tonumber(ammo) or 250, false, true)
    pcall(SetCurrentPedWeapon, ped, hash, true)
    StaticFeatures.quantum_arm_playtime()
    return true
end

StaticFeatures.QANY_KEY = "qany_done"
StaticFeatures._qany_busy = false

function StaticFeatures.quantum_weapon_hide_fade(enable)
    if _G.__STATIC_QUANTUM_SHOW_WEAPON_FADE then return false end
    local S = (type(SharkAPI) == "table") and SharkAPI.Scripting or nil
    if not S then return false end

    if not enable then
        if type(S.RestoreNative) == "function" then
            pcall(S.RestoreNative, "DoScreenFadeOut")
            pcall(S.RestoreNative, "DoScreenFadeIn")
        end
        _G.__STATIC_QUANTUM_FADE_HOOKED = false
        return true
    end

    if type(S.AddHookCallback) ~= "function" then return false end
    if type(S.RestoreNative) == "function" then
        pcall(S.RestoreNative, "DoScreenFadeOut")
        pcall(S.RestoreNative, "DoScreenFadeIn")
    end
    pcall(S.AddHookCallback, "DoScreenFadeOut", 1, 5, function(duration)
        if GetCurrentResourceName() == "pug-paintball" then return end
        DoScreenFadeOut(duration)
    end)
    pcall(S.AddHookCallback, "DoScreenFadeIn", 1, 5, function(duration)
        if GetCurrentResourceName() == "pug-paintball" then return end
        DoScreenFadeIn(duration)
    end)
    _G.__STATIC_QUANTUM_FADE_HOOKED = true

    CreateThread(function()
        Wait(6000)
        if _G.__STATIC_QUANTUM_FADE_HOOKED then
            StaticFeatures.quantum_weapon_hide_fade(false)
        end
    end)
    return true
end

StaticFeatures.QPB_TEAM = StaticFeatures.QPB_TEAM or "redteam"

StaticFeatures.QANY_WHITELIST = StaticFeatures.QANY_WHITELIST or {
    "WEAPON_RAYCARBINE", "WEAPON_RAYPISTOL", "WEAPON_RAYMINIGUN",
    "WEAPON_PISTOL", "WEAPON_PISTOL_MK2", "WEAPON_COMBATPISTOL",
    "WEAPON_APPISTOL", "WEAPON_PISTOL50", "WEAPON_HEAVYPISTOL",
    "WEAPON_VINTAGEPISTOL", "WEAPON_SNSPISTOL", "WEAPON_CERAMICPISTOL",
    "WEAPON_MICROSMG", "WEAPON_SMG", "WEAPON_SMG_MK2", "WEAPON_ASSAULTSMG",
    "WEAPON_COMBATPDW", "WEAPON_MACHINEPISTOL", "WEAPON_MINISMG",
    "WEAPON_PUMPSHOTGUN", "WEAPON_SAWNOFFSHOTGUN", "WEAPON_ASSAULTSHOTGUN",
    "WEAPON_BULLPUPSHOTGUN", "WEAPON_COMBATSHOTGUN", "WEAPON_HEAVYSHOTGUN",
    "WEAPON_CARBINERIFLE", "WEAPON_CARBINERIFLE_MK2", "WEAPON_ASSAULTRIFLE",
    "WEAPON_ASSAULTRIFLE_MK2", "WEAPON_ADVANCEDRIFLE", "WEAPON_SPECIALCARBINE",
    "WEAPON_BULLPUPRIFLE", "WEAPON_COMPACTRIFLE", "WEAPON_MILITARYRIFLE",
    "WEAPON_SNIPERRIFLE", "WEAPON_HEAVYSNIPER", "WEAPON_MARKSMANRIFLE",
}

function StaticFeatures.quantum_weapon_whitelist_literal(weaponUpper)
    local parts = {}
    for i = 1, #StaticFeatures.QANY_WHITELIST do
        parts[#parts + 1] = "\"" .. StaticFeatures.QANY_WHITELIST[i] .. "\""
    end
    if type(weaponUpper) == "string" and weaponUpper ~= "" then
        local have = false
        for i = 1, #StaticFeatures.QANY_WHITELIST do
            if StaticFeatures.QANY_WHITELIST[i] == weaponUpper then have = true break end
        end
        if not have then parts[#parts + 1] = "\"" .. weaponUpper .. "\"" end
    end
    return "{ " .. table.concat(parts, ", ") .. " }"
end

function StaticFeatures.quantum_paintball_cleanup()
    if type(SharkAPI) ~= "table" or type(SharkAPI.InjectSafe) ~= "function" then return end
    -- Remove pug-paintball + mm_radio NUI
    pcall(SharkAPI.InjectSafe, "pug-paintball", [[
        CreateThread(function()
            SetNuiFocus(false, false)
            pcall(SendNUIMessage, { action = "hide" })
        end)
    ]])
    if GetResourceState("mm_radio") == "started" then
        pcall(SharkAPI.InjectSafe, "mm_radio", [[
            CreateThread(function()
                SetNuiFocus(false, false)
                pcall(SendNUIMessage, { visible = false })
            end)
        ]])
    end
    -- Anti-death-loop: pug-paintball ticks revive/kill in a match; suppress it.
    pcall(SharkAPI.InjectSafe, "pug-paintball", [[
        CreateThread(function()
            while true do
                local ped = PlayerPedId()
                if IsEntityDead(ped) then
                    pcall(ResurrectPed, ped)
                    pcall(ClearPedBloodDamage, ped)
                    local c = GetEntityCoords(ped)
                    SetEntityCoordsNoOffset(ped, c.x, c.y, c.z, false, false, false)
                end
                Wait(500)
            end
        end)
    ]])
end

function StaticFeatures.quantum_weapon_any(rawName, ammo)
    local function note(msg, kind)
        if type(StaticFeatures.menu_notify) == "function" then
            pcall(StaticFeatures.menu_notify, "Weapons", msg, kind or "error")
        end
    end
    local weapon = tostring(rawName or ""):gsub("%s+", ""):lower()
    weapon = weapon:gsub("[^%w_]", "")
    if weapon == "" then note("No weapon name") return false end
    if not weapon:match("^weapon_") then weapon = "weapon_" .. weapon end
    weapon = weapon:upper()
    local WHASH = GetHashKey(weapon)

    -- Re-gated to QUANTUM / THE LANDS OF LA ONLY (2026-10-14, user request). quantum_present() is the
    -- detector for both (Quantum is the AC, The Lands of LA is the server that runs it). On any other
    -- server this give does nothing, even if pug-paintball happens to be present there.
    if type(StaticFeatures.quantum_present) ~= "function" or not StaticFeatures.quantum_present() then
        note("Paintball give is Quantum / The Lands of LA only") return false
    end
    if type(SharkAPI) ~= "table" or type(SharkAPI.InjectSafe) ~= "function" then
        note("InjectSafe unavailable") return false
    end
    if GetResourceState("pug-paintball") ~= "started" then
        note("pug-paintball not started") return false
    end
    if StaticFeatures._qany_busy then note("Give already running", "off") return false end

    if type(StaticFeatures.quantum_weapon_preflight) == "function" then
        local preOk, preErr = StaticFeatures.quantum_weapon_preflight()
        if not preOk then note("Unsafe to give: " .. tostring(preErr)) return false end
    end

    local ped0 = PlayerPedId()
    if HasPedGotWeapon(ped0, WHASH, false) then
        SetCurrentPedWeapon(ped0, WHASH, true)
        SetPedAmmo(ped0, WHASH, math.floor(tonumber(ammo) or 250))
        note(weapon:gsub("^WEAPON_", "") .. " equipped", "success")
        return true
    end

    StaticFeatures._qany_busy = true
    pcall(StaticFeatures.quantum_weapon_hide_fade, true)

    local TEAM   = tostring(StaticFeatures.QPB_TEAM or "redteam")
    local sAmmo  = tostring(math.floor(tonumber(ammo) or 250))
    local wlLit  = StaticFeatures.quantum_weapon_whitelist_literal(weapon)
    local hereC  = GetEntityCoords(ped0)
    local hereH  = GetEntityHeading(ped0)
    local sX, sY = tostring(hereC.x), tostring(hereC.y)
    local sZ, sH = tostring(hereC.z), tostring(hereH)

    note("Joining match for " .. weapon:gsub("^WEAPON_", "") .. "...", "off")

    CreateThread(function()
        -- 1. FULL forcng_playtime whitelist
        if GetResourceState("forcng_playtime") == "started" then
            local wl = "if GetCurrentResourceName() ~= 'forcng_playtime' then return end\n"
                .. "CreateThread(function()\n"
                .. "  if type(Config) ~= 'table' or type(Config.WhitelistedWeapons) ~= 'table' then return end\n"
                .. "  local want = " .. wlLit .. "\n"
                .. "  for i = 1, #want do\n"
                .. "    local have = false\n"
                .. "    for _, v in pairs(Config.WhitelistedWeapons) do\n"
                .. "      if tostring(v):upper() == want[i]:upper() then have = true end\n"
                .. "    end\n"
                .. "    if not have then Config.WhitelistedWeapons[#Config.WhitelistedWeapons + 1] = want[i] end\n"
                .. "  end\n"
                .. "  LocalPlayer.state:set('__qany_wl', true, false)\n"
                .. "end)\n"
            pcall(SharkAPI.InjectSafe, "forcng_playtime", wl)
            Wait(600)
        end

        -- ars_hunting: its lib.onCache('weapon') strips snipers outside a hunting zone.
        if GetResourceState("ars_hunting") == "started" then
            local ah = "if GetCurrentResourceName() ~= 'ars_hunting' then return end\n"
                .. "CreateThread(function()\n"
                .. "  if type(Config) == 'table' and type(Config.AimBlock) == 'table' then\n"
                .. "    Config.AimBlock.enable = false\n"
                .. "  end\n"
                .. "end)\n"
            pcall(SharkAPI.InjectSafe, "ars_hunting", ah)
        end

        -- 2. STAY PUT: pin arena spawn to current position
        local sp = "if GetCurrentResourceName() ~= 'pug-paintball' then return end\n"
            .. "local HERE = vector4(" .. sX .. ", " .. sY .. ", " .. sZ .. ", " .. sH .. ")\n"
            .. "local SLOT = setmetatable({}, { __index = function() return HERE end })\n"
            .. "local function pin(name)\n"
            .. "  if type(Config) ~= 'table' then return end\n"
            .. "  Config[name] = setmetatable({}, { __index = function() return SLOT end })\n"
            .. "end\n"
            .. "pin('RedTeamSpawns'); pin('BlueTeamSpawns'); pin('FFASpawns')\n"
            .. "LocalPlayer.state:set('__qany_sp', true, false)\n"
        pcall(SharkAPI.InjectSafe, "pug-paintball", sp)
        Wait(250)

        -- 3. Main sequence inside pug-paintball
        local KEY = StaticFeatures.QANY_KEY
        pcall(function() LocalPlayer.state:set(KEY, "", false) end)
        local payload = "CreateThread(function()\n"
            .. "  local SKEY = '" .. KEY .. "'\n"
            .. "  local function done(v) pcall(function() LocalPlayer.state:set(SKEY, v, false) end) end\n"
            .. "  if GetCurrentResourceName() ~= 'pug-paintball' then done('wrongvm') return end\n"
            .. "  local WEAPON = '" .. weapon .. "'\n"
            .. "  local AMMO   = " .. sAmmo .. "\n"
            .. "  local TEAM   = '" .. TEAM .. "'\n"
            .. "  local WHASH  = GetHashKey(WEAPON)\n"
            .. "  local ped = PlayerPedId()\n"
            .. "  ChosenWeapon = WEAPON\n"
            .. "  if not isInMatch then\n"
            .. "    pcall(TriggerServerEvent, 'Pug:paintball:JoinTeam', TEAM)\n"
            .. "    Citizen.Wait(900)\n"
            .. "    pcall(TriggerServerEvent, 'Pug:paintball:startGame')\n"
            .. "    local t = GetGameTimer()\n"
            .. "    while not isInMatch and GetGameTimer() - t < 15000 do Citizen.Wait(100) end\n"
            .. "    if not isInMatch then done('nomatch') return end\n"
            .. "  else\n"
            .. "    pcall(GiveWeaponToPed, ped, WHASH, AMMO, false, true)\n"
            .. "  end\n"
            .. "  local gt = GetGameTimer()\n"
            .. "  while not HasPedGotWeapon(ped, WHASH, false) and GetGameTimer() - gt < 6000 do\n"
            .. "    ped = PlayerPedId(); Citizen.Wait(50)\n"
            .. "  end\n"
            .. "  pcall(DoScreenFadeIn, 0)\n"
            .. "  ped = PlayerPedId()\n"
            .. "  if IsEntityPositionFrozen(ped) then pcall(FreezeEntityPosition, ped, false) end\n"
            .. "  local has = HasPedGotWeapon(ped, WHASH, false) and true or false\n"
            .. "  if has then\n"
            .. "    SetPedAmmo(ped, WHASH, AMMO)\n"
            .. "    SetCurrentPedWeapon(ped, WHASH, true)\n"
            .. "  end\n"
            .. "  pcall(TriggerServerEvent, 'Pug:server:PaintballSetBucket')\n"
            .. "  Citizen.Wait(1200)\n"
            .. "  pcall(DoScreenFadeIn, 0)\n"
            .. "  done(has and 'ok' or 'notgiven')\n"
            .. "end)\n"

        local verdict = nil
        if pcall(SharkAPI.InjectSafe, "pug-paintball", payload) then
            local waited = 0
            while waited < 30000 do
                Wait(250); waited = waited + 250
                local ok, v = pcall(function() return LocalPlayer.state[KEY] end)
                if ok and type(v) == "string" and v ~= "" then verdict = v break end
            end
        else
            verdict = "delivery threw"
        end
        pcall(function() LocalPlayer.state:set(KEY, "", false) end)
        StaticFeatures._qany_busy = false
        pcall(StaticFeatures.quantum_weapon_hide_fade, false)

        local label = weapon:gsub("^WEAPON_", "")
        if verdict == "ok" then
            local pbLive = false
            pcall(function() pbLive = (LocalPlayer.state.IsInPaintball == true) end)
            note(label .. (pbLive and " spawned - in match, damage legal"
                or " spawned - in bucket (check roster held)"),
                "success")
            pcall(StaticFeatures.quantum_paintball_cleanup)
        elseif verdict == "nomatch" then
            note(label .. ": never entered the match - JoinTeam/startGame did not take (send F8)")
        elseif verdict == "notgiven" then
            note(label .. ": joined but the gun never arrived - is it a real/streamed weapon? (send F8)")
        elseif verdict == "wrongvm" then
            note("Landed in the wrong VM - pug-paintball inject missed")
        elseif verdict == nil then
            note("No answer from pug-paintball (send F8)")
        else
            note("Give failed: " .. tostring(verdict))
        end

        -- FALL THROUGH on any non-"ok" outcome (e.g. "No lobby specified" / nomatch -- pug-paintball
        -- is in the server but there's no joinable match). This flow is fire-and-forget, so the
        -- dispatcher already returned true; here we re-run the spawner with the pug/quantum branch
        -- SKIPPED so the give lands on the next host (BakiTelli -> our other resources -> Shark)
        -- instead of dead-ending on the failed pug join.
        if verdict ~= "ok" then
            _G.__STATIC_SKIP_QUANTUM_WEAPON = true
            if type(StaticFeatures.equip_weapon_like_spawner) == "function" then
                pcall(StaticFeatures.equip_weapon_like_spawner, rawName)
            end
            _G.__STATIC_SKIP_QUANTUM_WEAPON = false
        end
    end)
    return true
end

-- Fat Duck Gaming "core_admin" / base_anticheat bypass. The AC is UNOBFUSCATED and client-side: every
-- detection reports to the server through one of a few events. MakeAnticheatReport (core.lua) ->
-- TriggerServerEvent("anticheat:report", ...) is the main funnel (noclip, spectate); the rest fire
-- test_ac:* (aimbot/godmode/healthpower/teleport/pedmodel/lockon/developer/fcLog), chkrsr (resourcelist),
-- core_admin:staffMsg (the "Godmode Detected" staff-chat line) and core_admin:tpsr (screenshot evidence).
-- We inject into base_anticheat's own VM, no-op MakeAnticheatReport, and wrap TriggerServerEvent to drop
-- exactly those report events -- detections keep running locally but nothing reaches the server. In-place
-- neuter, NOT a stop_resource (stopping the AC is heartbeat-detectable; silent neuter is stealthier).
--
-- RE-VERIFIED against a fresh base_anticheat dump (2026-10-12). Files live under base_anticheat/client/.
-- CHANGES VS 2026-09-27 dump that prompted this update (user got banned for fake player scanner):
--
--   noclip.lua     -> REWRITTEN. New speed-vs-distance heuristic: every 250ms compares
--                     GetEntitySpeed(ped) to actual distance traveled. reportedSpeed < 0.1 +
--                     actualSpeed > 5.0 for 3 consecutive ticks -> MakeAnticheatReport. Follows
--                     GetEntityAttachedTo chain + GetVehiclePedIsIn for speed. This catches ANY
--                     teleport (including fake player scanner's 350m grid hops) as zero-speed
--                     movement. FIX: MakeAnticheatReport is already no-op'd. ALSO spoof
--                     GetEntitySpeed inside the AC VM to return plausible values (defense-in-depth).
--   resourcelist.lua -> chkrsr heartbeat every 60-120s. OLD BYPASS: dropped entirely -> server
--                     flagged silence. FIX: intercept chkrsr, filter the resource list to strip
--                     injector resources, let the CLEANED list through so the heartbeat stays alive.
--   screenshot.lua -> RequestScreenshotUpload captures on-demand evidence. Was not spoofed.
--                     FIX: no-op RequestScreenshotUpload -> returns nil, no screenshot captured.
--
-- Full file-by-file coverage:
--   detections/aimbot.lua      -> test_ac:ACLog ("aimbot"/"aimbot2")   [covered: prefix rule + explicit]
--   detections/godmode.lua     -> test_ac:ACLog ("godmode"/"godmode_2"/"thermalvision") + core_admin:staffMsg [covered]
--   detections/healthpower.lua -> test_ac:ACLog ("torque"), heal COMMENTED OUT              [covered]
--   detections/noclip.lua      -> MakeAnticheatReport (-> anticheat:report)                 [covered: no-op + GetEntitySpeed spoof]
--   detections/spectate.lua    -> MakeAnticheatReport + NetworkIsInSpectatorMode/GetRenderingCam [covered: event + native spoof]
--   detections/teleport.lua    -> test_ac:distance                                          [covered]
--   detections/pedmodel.lua    -> test_ac:head / test_ac:head2                              [covered]
--   detections/lockon.lua      -> test_ac:lockon                                            [covered]
--   detections/developerconvar.lua -> test_ac:developer                                     [covered]
--   detections/resourcelist.lua -> chkrsr                                                   [covered: filtered passthrough]
--   detections/npcweapons.lua  -> test_ac:checkBlock (blockAC export) + local ped enforcement [covered: event + blockAC(true)]
--   cameratest.lua -> _s4c9 statebag (replicated, no TSE) + test_ac:fcLog                   [covered: camera coord spoofs]
--   screenshot.lua -> core_admin:tpsr + RequestScreenshotUpload                             [covered: event drop + RSU no-op]
--   debugprobe.lua -> test_ac:debug (staff-invoked), core_vehicles:boot_anticheat COMMENTED OUT [covered]
--   identity.lua   -> base_anticheat:receiveIdentity                                        [covered]
--   panel.lua      -> base_anticheat:panel:requestOpen (staff panel open, NOT a detection)   [no block needed]
--   focuswatch.lua -> staff-side wisp renderer (reads OTHER player's _s4c9), not a detection [no block needed]
--   core.lua       -> MakeAnticheatReport definition                                        [no-op'd in arm()]
StaticFeatures.CORE_ADMIN_NEUTER_INJECT = [[
do
    _G.__STATIC_COREADMIN_BLOCK = _G.__STATIC_COREADMIN_BLOCK or {
        ["anticheat:report"] = true,
        ["core_admin:staffMsg"] = true,
        ["core_admin:tpsr"] = true,
        ["core_vehicles:boot_anticheat"] = true,
        ["base_anticheat:receiveIdentity"] = true,
        -- explicit: the health/armour/godmode detection funnel (base_anticheat/client/detections/*
        -- fire this with a category string, e.g. "godmode"/"godmode_2"/"heal"/"torque"/"thermalvision").
        ["test_ac:ACLog"] = true,
        ["test_ac:debug"] = true,
        ["test_ac:weapon"] = true,
        -- Re-verified against the 2026-09 base_anticheat dump. Everything below is ALREADY caught by
        -- the test_ac: prefix rule in shouldDrop(); listed explicitly so the next diff against a dump
        -- shows at a glance which detections are accounted for and which are new:
        --   test_ac:fcLog      cameratest.lua  freecam -- ped-to-cam distance > 300.0
        --   test_ac:lockon     lockon.lua      aim lock-on target
        --   test_ac:distance   teleport.lua    >50u jump while airborne
        --   test_ac:head       pedmodel.lua    ped model bounds
        --   test_ac:head2      pedmodel.lua    ped config flag 2
        --   test_ac:developer  developerconvar.lua
        --   test_ac:checkBlock npcweapons.lua  blockAC state change
        ["test_ac:fcLog"] = true,
        ["test_ac:lockon"] = true,
        ["test_ac:distance"] = true,
        ["test_ac:head"] = true,
        ["test_ac:head2"] = true,
        ["test_ac:developer"] = true,
        ["test_ac:checkBlock"] = true,
    }
    local BLOCK = _G.__STATIC_COREADMIN_BLOCK
    local function shouldDrop(event)
        if type(event) ~= "string" then return false end
        if BLOCK[event] then return true end
        return event:sub(1, 8) == "test_ac:"
    end
    local function countDrop(event)
        _G.__STATIC_COREADMIN_BLOCKED = (_G.__STATIC_COREADMIN_BLOCKED or 0) + 1
    end
    -- Resource names that fingerprint the injector. If any resource in the chkrsr list
    -- contains one of these substrings it gets stripped before the list is forwarded to
    -- the server. Case-insensitive match via lower().
    local STRIP_RESOURCES = { "shark", "static", "macho", "inject", "executor", "cheat" }
    local function isInjectorResource(name)
        if type(name) ~= "string" then return false end
        local low = name:lower()
        for _, pat in ipairs(STRIP_RESOURCES) do
            if low:find(pat, 1, true) then return true end
        end
        return false
    end
    -- (Re)install every neuter. Idempotent + safe to call on a heartbeat: the ORIGINAL natives are cached
    -- once, and each re-arm re-wraps that cached original so nothing stacks. Hardening: if base_anticheat
    -- ever restored MakeAnticheatReport or swapped TriggerServerEvent back, the 1s watchdog re-arms.
    local function arm()
        MakeAnticheatReport = function() end
        if _G.__STATIC_COREADMIN_TSE_ORIG == nil then _G.__STATIC_COREADMIN_TSE_ORIG = TriggerServerEvent end
        if _G.__STATIC_COREADMIN_TLSE_ORIG == nil then _G.__STATIC_COREADMIN_TLSE_ORIG = TriggerLatentServerEvent end
        local tse = _G.__STATIC_COREADMIN_TSE_ORIG
        if type(tse) == "function" then
            TriggerServerEvent = function(event, ...)
                if shouldDrop(event) then countDrop(event) return end
                -- chkrsr: filter the resource list to strip injector resources, then forward
                if type(event) == "string" and event == "chkrsr" then
                    local rawList = select(1, ...)
                    if type(rawList) == "table" then
                        local cleaned = {}
                        for _, rName in ipairs(rawList) do
                            if not isInjectorResource(rName) then
                                cleaned[#cleaned + 1] = rName
                            end
                        end
                        return tse(event, cleaned)
                    end
                end
                return tse(event, ...)
            end
        end
        local tlse = _G.__STATIC_COREADMIN_TLSE_ORIG
        if type(tlse) == "function" then
            TriggerLatentServerEvent = function(event, ...)
                if shouldDrop(event) then countDrop(event) return end
                if type(event) == "string" and event == "chkrsr" then
                    local rawList = select(1, ...)
                    if type(rawList) == "table" then
                        local cleaned = {}
                        for _, rName in ipairs(rawList) do
                            if not isInjectorResource(rName) then
                                cleaned[#cleaned + 1] = rName
                            end
                        end
                        return tlse(event, cleaned)
                    end
                end
                return tlse(event, ...)
            end
        end
        -- SOURCE-LEVEL neuter of the health/armour/godmode detections. Even if a report somehow escapes
        -- the event drop (a detection thread capturing a TSE upvalue before we armed, or a server-side
        -- re-check), spoof the exact READ natives FDG's detections/*.lua poll, INSIDE base_anticheat's
        -- own VM only, so the detection condition never becomes true and no report is ever built:
        --   godmode.lua      -> GetEntityProofs (all-1 check), GetPlayerInvincible, GetPlayerInvincible_2
        --   healthpower.lua  -> GetVehicleCheatPowerIncrease (torque check)
        -- Cache originals once; re-wrap the cached original each re-arm so nothing stacks.
        if _G.__STATIC_COREADMIN_GPI_ORIG == nil and type(GetPlayerInvincible) == "function" then
            _G.__STATIC_COREADMIN_GPI_ORIG = GetPlayerInvincible
        end
        if type(_G.__STATIC_COREADMIN_GPI_ORIG) == "function" then
            GetPlayerInvincible = function() return 0 end
        end
        if _G.__STATIC_COREADMIN_GPI2_ORIG == nil and type(GetPlayerInvincible_2) == "function" then
            _G.__STATIC_COREADMIN_GPI2_ORIG = GetPlayerInvincible_2
        end
        if type(_G.__STATIC_COREADMIN_GPI2_ORIG) == "function" then
            GetPlayerInvincible_2 = function() return 0 end
        end
        if _G.__STATIC_COREADMIN_GEP_ORIG == nil and type(GetEntityProofs) == "function" then
            _G.__STATIC_COREADMIN_GEP_ORIG = GetEntityProofs
        end
        if type(_G.__STATIC_COREADMIN_GEP_ORIG) == "function" then
            -- return the real proofs but never the all-1 pattern the detection bans on: force retval 0
            -- so the `retval == 1 and bulletProof == 1 and ...` guard can't fire.
            GetEntityProofs = function(...) return 0, 0, 0, 0, 0, 0, 0, 0, 0 end
        end
        if _G.__STATIC_COREADMIN_GVCPI_ORIG == nil and type(GetVehicleCheatPowerIncrease) == "function" then
            _G.__STATIC_COREADMIN_GVCPI_ORIG = GetVehicleCheatPowerIncrease
        end
        if type(_G.__STATIC_COREADMIN_GVCPI_ORIG) == "function" then
            GetVehicleCheatPowerIncrease = function() return 1.0 end
        end
        -- thermalvision branch in godmode.lua: GetUsingseethrough() == 1 -> test_ac:ACLog.
        if _G.__STATIC_COREADMIN_GUST_ORIG == nil and type(GetUsingseethrough) == "function" then
            _G.__STATIC_COREADMIN_GUST_ORIG = GetUsingseethrough
        end
        if type(_G.__STATIC_COREADMIN_GUST_ORIG) == "function" then
            GetUsingseethrough = function() return 0 end
        end

        -- ── CAMERA / FREECAM SURFACES (added after the 2026-09 base_anticheat update) ──────────
        -- The update added three camera checks, and ONE OF THEM DOES NOT USE TriggerServerEvent,
        -- so the event filter above physically cannot see it:
        --
        --   cameratest.lua : on the staff-invoked "test_ac:ct" event it loops every 150ms doing
        --                    LocalPlayer.state:set("_s4c9", {cam coords + raycast end}, true).
        --                    That is a REPLICATED STATEBAG -- a completely different transport.
        --                    Our TriggerServerEvent wrapper never runs, and staff watching via
        --                    focuswatch.lua get a live wisp drawn wherever our camera actually is.
        --   cameratest.lua : a permanent loop fires "test_ac:fcLog" when the distance from our ped
        --                    to GetFinalRenderedCamCoord() exceeds 300.0 -- a freecam ratter. The
        --                    event itself IS caught by the test_ac: prefix rule, but only if we
        --                    armed before it fired.
        --   spectate.lua   : MakeAnticheatReport("Unregistered external camera active") whenever
        --                    GetRenderingCam() ~= -1 and that cam is not registered with Base.
        --
        -- The statebag one can't be fixed at the event layer, so fix all three at the SOURCE the
        -- same way the godmode/torque spoofs above work: inside base_anticheat's OWN VM, make every
        -- camera query answer with our ped's position. The _s4c9 write still happens on schedule --
        -- deliberately, because a statebag that suddenly goes silent the moment staff start watching
        -- is itself the tell -- it just reports a wisp sitting on our body instead of out at the
        -- freecam. Our actual freecam is untouched: it runs in a different resource's VM.
        do
            local function pedPos()
                local ok, p = pcall(function() return GetEntityCoords(PlayerPedId()) end)
                if ok and p then return p end
                return vector3(0.0, 0.0, 0.0)
            end
            if _G.__STATIC_COREADMIN_GGCC_ORIG == nil and type(GetGameplayCamCoord) == "function" then
                _G.__STATIC_COREADMIN_GGCC_ORIG = GetGameplayCamCoord
            end
            if type(_G.__STATIC_COREADMIN_GGCC_ORIG) == "function" then
                GetGameplayCamCoord = function() return pedPos() end
            end
            if _G.__STATIC_COREADMIN_GFRCC_ORIG == nil and type(GetFinalRenderedCamCoord) == "function" then
                _G.__STATIC_COREADMIN_GFRCC_ORIG = GetFinalRenderedCamCoord
            end
            if type(_G.__STATIC_COREADMIN_GFRCC_ORIG) == "function" then
                -- distance from ped to "cam" becomes ~0, so the >300.0 fcLog guard never fires.
                GetFinalRenderedCamCoord = function() return pedPos() end
            end
            if _G.__STATIC_COREADMIN_GRC_ORIG == nil and type(GetRenderingCam) == "function" then
                _G.__STATIC_COREADMIN_GRC_ORIG = GetRenderingCam
            end
            if type(_G.__STATIC_COREADMIN_GRC_ORIG) == "function" then
                -- spectate.lua guards on `renderingCam ~= -1`; -1 means "gameplay cam", so the
                -- unregistered-camera branch is unreachable.
                GetRenderingCam = function() return -1 end
            end
            -- Their own helper out of @base/client/utility.lua, used to build the _s4c9 ray.
            -- Returns (hitCoords, rayEnd); nil hit + ped position keeps the payload well-formed.
            if _G.__STATIC_COREADMIN_GPCEC_ORIG == nil and type(getPlayerCameraEndCoords) == "function" then
                _G.__STATIC_COREADMIN_GPCEC_ORIG = getPlayerCameraEndCoords
            end
            if type(_G.__STATIC_COREADMIN_GPCEC_ORIG) == "function" then
                getPlayerCameraEndCoords = function() local p = pedPos() return p, p end
            end
            -- NetworkIsInSpectatorMode drives spectate.lua's first branch.
            if _G.__STATIC_COREADMIN_NIISM_ORIG == nil and type(NetworkIsInSpectatorMode) == "function" then
                _G.__STATIC_COREADMIN_NIISM_ORIG = NetworkIsInSpectatorMode
            end
            if type(_G.__STATIC_COREADMIN_NIISM_ORIG) == "function" then
                NetworkIsInSpectatorMode = function() return false end
            end
        end

        -- npcweapons.lua runs a 1s loop over every ped we own and, if it carries anything on its
        -- blacklist (RPG, minigun, railgun, heavysniper/_mk2, grenadelauncher, stinger, hominglauncher,
        -- raypistol/raycarbine/rayminigun, marksmanpistol, combatmg_mk2), calls RemoveAllPedWeapons +
        -- DeleteEntity on it. That is local ENFORCEMENT, not a report -- it does not ban us, it just
        -- silently deletes armed peds we spawn. base_anticheat exports blockAC(state) to suspend that
        -- scan for scripted events that legitimately arm peds; we use the same door. The export also
        -- fires test_ac:checkBlock, which the filter above drops, so the server never learns the scan
        -- was suspended. Set __STATIC_COREADMIN_ALLOW_NPC_SCAN = true before injecting to leave FDG's
        -- scan running instead.
        if _G.__STATIC_COREADMIN_ALLOW_NPC_SCAN ~= true then
            pcall(function() exports["base_anticheat"]:blockAC(true) end)
        end

        -- ── NOCLIP SPEED-DISTANCE HEURISTIC SPOOF (2026-10-12) ────────────────────────
        -- detections/noclip.lua now does a 250ms loop: if GetEntitySpeed() < 0.1 but actual
        -- distance traveled > 20.0 in 250ms, it strikes; 3 consecutive strikes ->
        -- MakeAnticheatReport('invalid-action', 3, ...). MakeAnticheatReport IS no-op'd above,
        -- but defense-in-depth: spoof GetEntitySpeed inside base_anticheat's VM to always return
        -- a value consistent with movement so the strike condition never fires.
        -- The detection follows GetEntityAttachedTo chain + GetVehiclePedIsIn, so we spoof both
        -- GetEntitySpeed to report plausible values derived from actual ped movement.
        if _G.__STATIC_COREADMIN_GES_ORIG == nil and type(GetEntitySpeed) == "function" then
            _G.__STATIC_COREADMIN_GES_ORIG = GetEntitySpeed
        end
        if type(_G.__STATIC_COREADMIN_GES_ORIG) == "function" then
            local origGES = _G.__STATIC_COREADMIN_GES_ORIG
            GetEntitySpeed = function(entity)
                local speed = origGES(entity)
                -- If real speed is near-zero but this is our ped (the one noclip.lua checks),
                -- return a plausible cruising speed so reportedSpeed is never < 0.1 during teleport
                if speed < 0.1 then
                    local ped = PlayerPedId()
                    if entity == ped or entity == GetVehiclePedIsIn(ped, false) then
                        return 5.5
                    end
                    -- Follow attached-to chain like noclip.lua does
                    local att = GetEntityAttachedTo(ped)
                    if att ~= 0 and entity == att then
                        return 5.5
                    end
                end
                return speed
            end
        end

        -- ── TELEPORT SOURCE-NEUTER (2026-10-17, fresh dump) ────────────────────────────────
        -- detections/teleport.lua fires test_ac:distance on a >50u jump, but ONLY while
        -- GetEntityHeightAboveGround(ped) > 4.0 (plus not falling/ragdoll/swimming/parachute).
        -- test_ac:distance is already dropped at the event layer AND the executor block, but make it
        -- defense-in-depth like noclip: inside base_anticheat's VM, report our ped as grounded
        -- (height < 4.0) so the detection condition never even builds. Other entities read true height.
        if _G.__STATIC_COREADMIN_GEHAG_ORIG == nil and type(GetEntityHeightAboveGround) == "function" then
            _G.__STATIC_COREADMIN_GEHAG_ORIG = GetEntityHeightAboveGround
        end
        if type(_G.__STATIC_COREADMIN_GEHAG_ORIG) == "function" then
            local origGEHAG = _G.__STATIC_COREADMIN_GEHAG_ORIG
            GetEntityHeightAboveGround = function(entity)
                local ok, ped = pcall(PlayerPedId)
                if ok and entity == ped then return 0.5 end
                return origGEHAG(entity)
            end
        end

        -- ── SCREENSHOT UPLOAD NO-OP (2026-10-12) ──────────────────────────────────────
        -- screenshot.lua listens for "core_admin:tps" then calls RequestScreenshotUpload()
        -- which captures a frame and sends the URL back via "core_admin:tpsr". The event
        -- "core_admin:tpsr" is already in the BLOCK table above, but RequestScreenshotUpload
        -- itself could expose a frame showing menu UI or noclip. No-op it so no screenshot
        -- is ever captured.
        if _G.__STATIC_COREADMIN_RSU_ORIG == nil and type(RequestScreenshotUpload) == "function" then
            _G.__STATIC_COREADMIN_RSU_ORIG = RequestScreenshotUpload
        end
        if type(_G.__STATIC_COREADMIN_RSU_ORIG) == "function" then
            RequestScreenshotUpload = function() end
        end
    end
    arm()
    if not _G.__STATIC_COREADMIN_WATCH then
        _G.__STATIC_COREADMIN_WATCH = true
        _G.__STATIC_COREADMIN_BYPASS = true
        Citizen.CreateThread(function()
            while true do
                Citizen.Wait(1000)
                arm()
            end
        end)
    end
end
]]

-- ═══════════════ BASE_PLAYER DAMAGE-REPORT NEUTER (2026-10-03) ═══════════════════════════════════
-- base_player/client/detection.lua runs on the VICTIM's client. When the weapon hash isn't in its
-- WeaponCategories table it fires TriggerServerEvent("playerDamage:missingWeapon", hash, typeGroup)
-- -> instant ban for the ATTACKER. Our event filter (CORE_ADMIN_NEUTER_INJECT) only wraps TSE inside
-- base_anticheat's VM -- it can't see events from base_player's VM. And when WE shoot someone with a
-- weapon not in their table, the event fires from THEIR client -- completely unreachable.
--
-- Two-prong fix:
--   1. INJECT into base_player's VM on OUR client: wrap TriggerServerEvent to drop
--      "playerDamage:missingWeapon" so WE never report it when we're the victim. Defense-in-depth.
--   2. READ WeaponCategories from base_player's VM and export it via statebag so the weapon spawner
--      can filter to only show weapons the server recognizes. This is the PRIMARY fix -- if we only
--      spawn weapons that exist in their table, the victim's detection.lua never fires.
--
-- The inject also grabs WeaponCategories + WeaponLabels and writes them to
-- LocalPlayer.state.__static_wc (categories) and __static_wl (labels) so the host VM can read them.
StaticFeatures.BASE_PLAYER_NEUTER_INJECT = [[
do
    -- ── Drop the missingWeapon report from THIS client ──────────────────────────────
    if _G.__STATIC_BASEPLAYER_TSE_ORIG == nil then _G.__STATIC_BASEPLAYER_TSE_ORIG = TriggerServerEvent end
    local tse = _G.__STATIC_BASEPLAYER_TSE_ORIG
    if type(tse) == "function" then
        TriggerServerEvent = function(event, ...)
            if type(event) == "string" and event == "playerDamage:missingWeapon" then
                _G.__STATIC_BASEPLAYER_BLOCKED = (_G.__STATIC_BASEPLAYER_BLOCKED or 0) + 1
                return
            end
            return tse(event, ...)
        end
    end

    -- ── Export WeaponCategories + WeaponLabels to statebag ──────────────────────────
    -- WeaponCategories is a hash->string map (e.g. {[453432689]="GSW_LIGHT",...}).
    -- We serialise the HASHES as keys so the host VM can do GetHashKey(name) and look up.
    -- Statebag value is JSON since Lua tables don't cross VM boundaries.
    Citizen.CreateThread(function()
        -- Small delay: let base_player finish init so WeaponCategories is populated.
        Citizen.Wait(2000)

        -- Grab WeaponCategories (hash -> category string)
        if type(WeaponCategories) == "table" then
            local parts = {}
            for hash, cat in pairs(WeaponCategories) do
                parts[#parts + 1] = string.format('["%s"]="%s"', tostring(hash), tostring(cat))
            end
            -- Also build a JSON-ish string the host can parse
            local jsonParts = {}
            for hash, cat in pairs(WeaponCategories) do
                jsonParts[#jsonParts + 1] = '"' .. tostring(hash) .. '":"' .. tostring(cat) .. '"'
            end
            local json = "{" .. table.concat(jsonParts, ",") .. "}"
            pcall(function()
                LocalPlayer.state:set("__static_wc", json, false)
            end)
        end

        -- Grab WeaponLabels (hash -> display name)
        if type(WeaponLabels) == "table" then
            local jsonParts = {}
            for hash, label in pairs(WeaponLabels) do
                jsonParts[#jsonParts + 1] = '"' .. tostring(hash) .. '":"' .. tostring(label) .. '"'
            end
            local json = "{" .. table.concat(jsonParts, ",") .. "}"
            pcall(function()
                LocalPlayer.state:set("__static_wl", json, false)
            end)
        end
    end)

    -- Watchdog: if base_player ever restores TSE, re-wrap.
    if not _G.__STATIC_BASEPLAYER_WATCH then
        _G.__STATIC_BASEPLAYER_WATCH = true
        _G.__STATIC_BASEPLAYER_BYPASS = true
        Citizen.CreateThread(function()
            while true do
                Citizen.Wait(2000)
                local current = TriggerServerEvent
                -- If someone swapped TSE back to the raw original, re-wrap.
                if current == _G.__STATIC_BASEPLAYER_TSE_ORIG then
                    TriggerServerEvent = function(event, ...)
                        if type(event) == "string" and event == "playerDamage:missingWeapon" then
                            _G.__STATIC_BASEPLAYER_BLOCKED = (_G.__STATIC_BASEPLAYER_BLOCKED or 0) + 1
                            return
                        end
                        return _G.__STATIC_BASEPLAYER_TSE_ORIG(event, ...)
                    end
                end
            end
        end)
    end
end
]]

function StaticFeatures.base_player_present()
    return type(GetResourceState) == "function"
        and GetResourceState("base_player") == "started"
end

function StaticFeatures.apply_base_player_bypass(silent)
    if not StaticFeatures.base_player_present() then return false end
    local resource = "base_player"
    local api = StaticShark and StaticShark.api and StaticShark.api()
    local ok = false
    if api and type(api.InjectSafe) == "function" then
        ok = pcall(api.InjectSafe, resource, StaticFeatures.BASE_PLAYER_NEUTER_INJECT) == true
    end
    if not ok and type(StaticShark) == "table" and type(StaticShark.inject) == "function" then
        ok = StaticShark.inject(resource, StaticFeatures.BASE_PLAYER_NEUTER_INJECT) == true
    end
    _G.__STATIC_BASEPLAYER_BYPASS_APPLIED = ok
    _G.__STATIC_BASEPLAYER_BYPASS = ok or _G.__STATIC_BASEPLAYER_BYPASS
    if not silent then
        StaticFeatures.menu_notify("base_player", ok and "Weapon report neuter applied" or "Inject failed",
            ok and "success" or "error")
    end
    return ok
end

StaticFeatures._base_player_restart_hook_installed = false
function StaticFeatures.detect_base_player_on_join()
    if not StaticFeatures.base_player_present() then return false end
    local ok = StaticFeatures.apply_base_player_bypass(true)
    if not StaticFeatures._base_player_notified then
        StaticFeatures._base_player_notified = true
        StaticFeatures.menu_notify("base_player",
            ok and "Detected + weapon report neuter armed" or "Detected - inject FAILED",
            ok and "success" or "error")
    end
    if not StaticFeatures._base_player_restart_hook_installed
        and type(SharkAPI) == "table" and type(SharkAPI.Resources) == "table"
        and type(SharkAPI.Resources.OnResourceRestart) == "function" then
        StaticFeatures._base_player_restart_hook_installed = true
        pcall(SharkAPI.Resources.OnResourceRestart, function(restartedName)
            if tostring(restartedName) == "base_player" then
                _G.__STATIC_BASEPLAYER_BYPASS = nil
                _G.__STATIC_BASEPLAYER_BYPASS_APPLIED = nil
                pcall(StaticFeatures.apply_base_player_bypass, true)
            end
        end)
    end
    return true
end

-- base_player PERSISTENT EARLY BOOT THREAD: same shape as core_admin's watcher. base_player can stream
-- in late on heavy servers; we arm the missingWeapon neuter + WeaponCategories grab as early as it's up.
-- Gated on base_player_present() -> dormant on non-FDG servers. Independent of _toggle_state.
if type(CreateThread) == "function" then
    CreateThread(function()
        local t0 = (type(GetGameTimer) == "function" and GetGameTimer()) or 0
        while not _G.__STATIC_BASEPLAYER_BYPASS_APPLIED do
            if StaticFeatures.base_player_present and StaticFeatures.base_player_present() then
                pcall(StaticFeatures.detect_base_player_on_join)
            end
            local elapsed = ((type(GetGameTimer) == "function" and GetGameTimer()) or 0) - t0
            Wait(elapsed < 10000 and 0 or 2000)
        end
        while true do
            Wait(5000)
            if StaticFeatures.base_player_present and StaticFeatures.base_player_present()
                and not _G.__STATIC_BASEPLAYER_BYPASS then
                pcall(StaticFeatures.apply_base_player_bypass, true)
            end
        end
    end)
end

function StaticFeatures.core_admin_present()
    return type(GetResourceState) == "function"
        and GetResourceState("base_anticheat") == "started"
end

-- Every outbound detection-report event base_anticheat/client fires (verified against the dump). These
-- are dropped at the EXECUTOR level by SharkAPI.BlockServerEvent, so they die regardless of which VM
-- fired them and whether the in-VM inject landed. This is the primary kill for the report; the inject
-- (CORE_ADMIN_NEUTER_INJECT) is now defense-in-depth, not the only thing standing between you and a ban.
StaticFeatures.FDG_REPORT_EVENTS = {
    "anticheat:report",        -- core.lua MakeAnticheatReport -> noclip, spectate  (THE noclip ban path)
    "test_ac:ACLog",           -- godmode / aimbot / thermalvision / torque
    "test_ac:fcLog",           -- cameratest.lua freecam (cam >300m from ped)
    "test_ac:lockon",          -- lockon.lua
    "test_ac:distance",        -- teleport.lua
    "test_ac:head", "test_ac:head2",   -- pedmodel.lua
    "test_ac:developer",       -- developerconvar.lua
    "test_ac:checkBlock",      -- npcweapons.lua
    "test_ac:weapon", "test_ac:debug",
    "core_admin:staffMsg",     -- godmode staff notify
    "core_vehicles:boot_anticheat",
    "base_anticheat:receiveIdentity",
}

function StaticFeatures.arm_fdg_event_block()
    if type(StaticShark) ~= "table" or type(StaticShark.block_server_event) ~= "function" then return 0 end
    local n = 0
    for i = 1, #StaticFeatures.FDG_REPORT_EVENTS do
        if StaticShark.block_server_event(true, StaticFeatures.FDG_REPORT_EVENTS[i]) then n = n + 1 end
        -- some executors expose a client-side variant too; harmless if absent
        if type(StaticShark.block_client_event) == "function" then
            pcall(StaticShark.block_client_event, true, StaticFeatures.FDG_REPORT_EVENTS[i])
        end
    end
    _G.__STATIC_FDG_EVENTBLOCK_ON = n > 0
    return n
end

function StaticFeatures.apply_core_admin_bypass(silent)
    if not StaticFeatures.core_admin_present() then return false end
    local resource = "base_anticheat"
    -- PRIMARY: drop the report events at the executor level FIRST — this is what actually stops the
    -- noclip report, and it does not depend on the inject landing in base_anticheat's VM.
    local blocked = StaticFeatures.arm_fdg_event_block()
    local api = StaticShark and StaticShark.api and StaticShark.api()
    local ok = false
    if api and type(api.InjectSafe) == "function" then
        ok = pcall(api.InjectSafe, resource, StaticFeatures.CORE_ADMIN_NEUTER_INJECT) == true
    end
    if not ok and type(StaticShark) == "table" and type(StaticShark.inject) == "function" then
        ok = StaticShark.inject(resource, StaticFeatures.CORE_ADMIN_NEUTER_INJECT) == true
    end
    -- The bypass is "up" if EITHER layer armed. The event block alone kills every report; the inject is
    -- belt-and-suspenders (native spoofs + chkrsr resource-list scrub).
    ok = ok or (blocked > 0)
    _G.__STATIC_COREADMIN_BYPASS_APPLIED = ok
    _G.__STATIC_COREADMIN_BYPASS = ok or _G.__STATIC_COREADMIN_BYPASS
    if not silent then
        StaticFeatures.menu_notify("core_admin AC", ok and "Bypass applied" or "Bypass failed",
            ok and "success" or "error")
    end
    return ok
end

-- ON-DEMAND core_admin ARM (2026-09-10, parity with ensure_finiac_bypass_armed): apply the neuter NOW if
-- base_anticheat is present and it hasn't landed yet, so a feature toggled before the boot watcher armed
-- it still fires behind the bypass. Idempotent -- no-op once __STATIC_COREADMIN_BYPASS_APPLIED is set.
function StaticFeatures.ensure_core_admin_bypass_armed()
    if _G.__STATIC_COREADMIN_BYPASS_APPLIED == true then return true end
    if not (StaticFeatures.core_admin_present and StaticFeatures.core_admin_present()) then return false end
    return pcall(StaticFeatures.apply_core_admin_bypass, true) == true
        and _G.__STATIC_COREADMIN_BYPASS_APPLIED == true
end

-- base_anticheat resets its Lua state on restart, so re-neuter on restart (like FiniAC).
StaticFeatures._core_admin_restart_hook_installed = false
function StaticFeatures.detect_core_admin_on_join()
    if not StaticFeatures.core_admin_present() then return false end
    local ok = StaticFeatures.apply_core_admin_bypass(true)
    -- One-time in-game confirmation so you know it armed on this server without opening F8.
    if not StaticFeatures._core_admin_notified then
        StaticFeatures._core_admin_notified = true
        StaticFeatures.menu_notify("core_admin AC",
            ok and "Detected + bypass armed" or "Detected - bypass FAILED to inject",
            ok and "success" or "error")
    end
    if not StaticFeatures._core_admin_restart_hook_installed
        and type(SharkAPI) == "table" and type(SharkAPI.Resources) == "table"
        and type(SharkAPI.Resources.OnResourceRestart) == "function" then
        StaticFeatures._core_admin_restart_hook_installed = true
        pcall(SharkAPI.Resources.OnResourceRestart, function(restartedName)
            if tostring(restartedName) == "base_anticheat" then
                _G.__STATIC_COREADMIN_BYPASS = nil
                pcall(StaticFeatures.apply_core_admin_bypass, true)
            end
        end)
    end
    return true
end

-- Load the core_admin/base_anticheat bypass IMMEDIATELY on inject, like the FiveGuard stop-bypass -- do
-- not wait for the slow boot AC-scan flow. base_anticheat's detection threads start reporting within a
-- second or two of join, so we arm as early as the resource is readable. Own boot thread: the moment
-- base_anticheat is present, inject the neuter; retry every frame until it lands, capped ~8s so it can
-- also catch a resource that starts slightly after inject. Gated on core_admin_present() -> fully dormant
-- on non-Fat-Duck servers. Independent of _toggle_state so boot resets can't stop it.
if type(CreateThread) == "function" then
    CreateThread(function()
        -- PERSISTENT watcher (no 8s give-up -- same latent bug fixed on likizao): base_anticheat can
        -- stream in minutes after inject on a heavy server, and if the old 8s window closed first the
        -- neuter NEVER armed -> every detection reported and banned (e.g. a headshot flick fires
        -- test_ac:ACLog "aimbot2" -> our BLOCK set drops it ONLY if we armed in time). Fast poll for the
        -- first 10s, then every 2s FOREVER until armed, then a 5s re-check so an AC restart re-arms too.
        local t0 = (type(GetGameTimer) == "function" and GetGameTimer()) or 0
        while not _G.__STATIC_COREADMIN_BYPASS_APPLIED do
            if StaticFeatures.core_admin_present and StaticFeatures.core_admin_present() then
                pcall(StaticFeatures.detect_core_admin_on_join)
            end
            local elapsed = ((type(GetGameTimer) == "function" and GetGameTimer()) or 0) - t0
            Wait(elapsed < 10000 and 0 or 2000)
        end
        while true do
            Wait(5000)
            if StaticFeatures.core_admin_present and StaticFeatures.core_admin_present()
                and not _G.__STATIC_COREADMIN_BYPASS then
                pcall(StaticFeatures.apply_core_admin_bypass, true)
            end
        end
    end)
end

-- FiniAC PERSISTENT EARLY BOOT THREAD (2026-09-10, user: "all ac bypasses should be the first thing that
-- loads"). Same shape as core_admin's watcher above: FiniAC used to arm ONLY in the deferred boot AC-scan
-- flow (~5-20s post-inject) and a feature toggled before then got banned. Now it arms as early as the
-- FiniAC resource is readable, independent of the slow defer flow -- fast poll for the first 10s, then
-- every 2s FOREVER until armed (FiniAC can stream in late on a heavy server), then a 5s re-check so a
-- restart re-arms. Gated on finiac_present() (file-fingerprint) -> fully dormant on non-FiniAC servers.
-- Idempotent via __STATIC_FINIAC_BYPASS (detect_finiac_on_join no-ops once armed).
if type(CreateThread) == "function" then
    CreateThread(function()
        local t0 = (type(GetGameTimer) == "function" and GetGameTimer()) or 0
        while not _G.__STATIC_FINIAC_BYPASS do
            if StaticFeatures.finiac_present and StaticFeatures.finiac_present() then
                pcall(StaticFeatures.detect_finiac_on_join)
            end
            local elapsed = ((type(GetGameTimer) == "function" and GetGameTimer()) or 0) - t0
            Wait(elapsed < 10000 and 0 or 2000)
        end
        while true do
            Wait(5000)
            if StaticFeatures.finiac_present and StaticFeatures.finiac_present()
                and not _G.__STATIC_FINIAC_BYPASS then
                pcall(StaticFeatures.apply_finiac_bypass, true)
            end
        end
    end)
end


function StaticFeatures.detect_fiveguard_on_join()
    if StaticFeatures._fiveguard_auto_checked then
        return StaticFeatures._fiveguard_bypass_applied == true
    end
    StaticFeatures._fiveguard_auto_checked = true

    local byName = StaticFeatures._ac_scan_cache and StaticFeatures._ac_scan_cache.byName
    local fromCache = byName and byName.FiveGuard and #byName.FiveGuard > 0
    if not fromCache and not StaticFeatures.fiveguard_present() then
        return false
    end

    _G.__STATIC_FIVEGUARD_PRESENT = true
    _G.__STATIC_HOOKS_BLOCKED = true

    local ok = false
    if type(StaticFeatures.bypass_fiveguard) == "function" then
        local bypassOk, bypassResult = pcall(StaticFeatures.bypass_fiveguard, true)
        ok = bypassOk == true and bypassResult == true
    end
    StaticFeatures._fiveguard_bypass_applied = ok and true or false
    return ok
end

function StaticFeatures.ensure_fini_bypass_armed(context)
    context = context or "feature"
    if not StaticFeatures.fini_present or not StaticFeatures.fini_present() then
        return false
    end
    if not _G.__FINI_BYPASS_CHUNK_RAN then
        pcall(function() StaticFeatures.bypass_fini(true) end)
    end
    if context == "noclip" or context == "freecam" or context == "spectate" then
        if _G.__FINI_BYPASS_READY or _G.__FINI_BYPASS_CHUNK_RAN then
            _G.__FINI_NOCLIP_ON = true
        else
            CreateThread(function()
                local deadline = _static_game_timer() + 10000
                while not _G.__FINI_BYPASS_READY and _static_game_timer() < deadline do
                    Wait(100)
                end
                if not _G.__FINI_BYPASS_READY then return end
                if context == "noclip" and not _NOCLIP_HOST_ACTIVE then return end
                if context == "freecam" and not _FREECAM_RUNNING and not _G._FREECAM_MOVING then return end
                _G.__FINI_NOCLIP_ON = true
            end)
        end
    end
    return _G.__FINI_BYPASS_CHUNK_RAN == true
end

function StaticFeatures.detect_fini_on_join()
    if StaticFeatures._fini_on_join_checked then
        return StaticFeatures._fini_on_join == true
    end
    StaticFeatures._fini_on_join_checked = true
    StaticFeatures._fini_on_join = false
    if StaticFeatures.fini_present and StaticFeatures.fini_present() then
        StaticFeatures._fini_on_join = StaticFeatures.ensure_fini_bypass_armed("join") == true
    end
    return StaticFeatures._fini_on_join
end

-- ═══ ELECTRON AC BYPASS (v3 — multi-layer: graph walker + export noop + event filter) ══════════
-- Injected into Electron's resource via SharkAPI.Inject. Three layers:
--   Layer 1: Deep graph walker (evolved from code2eac) — BFS crawl of _ENV / _G / package.loaded
--            to find and noop punish modules, recordPlayer/screenshotPlayer string refs, and
--            any function-table with {start, stop, punish/[3]} shape.
--   Layer 2: Export handler noop — kills __cfx_export_ event handlers for Electron's known exports
--            (recordPlayer, screenshotPlayer, punish, and any matching pattern).
--   Layer 3: TriggerServerEventInternal filter — drops outbound AC report events (payloads <=3
--            bytes are keepalives/heartbeats, let those through; actual ban/flag payloads are
--            larger and get silently dropped).
--   Layer 4: Periodic re-sweep — Electron may lazy-load or re-register handlers after the initial
--            sweep. A background thread re-runs the walker every 30s to catch late registrations.
--   Layer 5: debug library hardening — if Electron sandboxes debug.getupvalue/setupvalue, the
--            walker falls back to table-only traversal (still catches punish modules in _ENV).
-- Detection functions (ac_electron_resource, get_electron_anticheats) are kept for AC flag UI.
-- The weapon spawn Electron path (spawn_weapon_electron) is kept — it's the clean no-shield path.

StaticFeatures._electron_ac_bypass_applied = false
StaticFeatures._electron_event_listener = { _id = nil, _blocks = 0 }
StaticFeatures._electron_scanner_data = {
    events = {},          -- { name = { count, lastPayloadSize, resource, firstSeen, lastSeen } }
    native_calls = {},    -- { nativeName = { count, resources = {res=count}, lastArgs } }
    exports_map = {},     -- { fnName = true }
    scan_start = 0,
    scan_running = false,
}
-- ═══════════════════════════════════════════════════════════════════════════════
-- Electron AC Runtime Scanner V1.0
-- ═══════════════════════════════════════════════════════════════════════════════
-- Strategy: OBSERVE before bypassing. Electron is Luraph-obfuscated — static
-- analysis is impossible. This scanner uses Shark's AddServerEventListener,
-- AddHookCallback, and safe-resource injection to intercept Electron's runtime
-- behavior: which events it sends, which natives it calls, which exports it
-- exposes. The scan runs for a configurable window (default 60s) then dumps
-- everything to F8 console. From that intel we build a TARGETED bypass.
--
-- Three layers:
--   Layer 1: Event listener (AddServerEventListener) — intercepts ALL server
--            events from ALL resources. Logs event name, resource, payload size.
--   Layer 2: Native call hooks (AddHookCallback) — hooks detection-surface
--            natives to log which resource calls them, how often, with what args.
--   Layer 3: Export probe (safe-resource inject) — injected into "chat" to probe
--            exports[electronResource] metatable and discover export functions.
-- ═══════════════════════════════════════════════════════════════════════════════


-- ─── Layer 1: Event Intelligence (AddServerEventListener) ────────────────────
-- Intercepts ALL server-bound events from ALL resources. Logs event name,
-- source resource, payload size, and frequency. This is the primary intel
-- source — we see exactly what Electron sends to the server and can identify
-- heartbeat patterns vs detection reports vs ban commands.
function StaticFeatures.electron_scanner_start_event_listener()
    local sd = StaticFeatures._electron_scanner_data
    if sd._event_listener_id then return true end

    if type(SharkAPI) ~= "table"
        or type(SharkAPI.AddServerEventListener) ~= "function" then
        return false
    end

    local electronRes = nil
    if type(StaticFeatures.ac_electron_resource) == "function" then
        electronRes = StaticFeatures.ac_electron_resource()
    end

    local id = SharkAPI.AddServerEventListener(function(eventName, eventPayload, resourceName)
        local eName = tostring(eventName or "")
        local rName = tostring(resourceName or "")
        local pSize = 0
        if type(eventPayload) == "string" then
            pSize = #eventPayload
        elseif type(eventPayload) == "table" then
            local ok, encoded = pcall(json.encode or function() return "" end, eventPayload)
            pSize = ok and #encoded or 0
        end

        local entry = sd.events[eName]
        if not entry then
            entry = {
                count = 0,
                lastPayloadSize = 0,
                resource = rName,
                firstSeen = GetGameTimer(),
                lastSeen = 0,
                payloadSizes = {},
                isElectron = false,
            }
            sd.events[eName] = entry
        end
        entry.count = entry.count + 1
        entry.lastPayloadSize = pSize
        entry.lastSeen = GetGameTimer()
        entry.resource = rName

        if #entry.payloadSizes < 20 then
            entry.payloadSizes[#entry.payloadSizes + 1] = pSize
        end

        local eRes = electronRes or StaticFeatures.ac_electron_resource and StaticFeatures.ac_electron_resource()
        if eRes and rName == eRes then
            entry.isElectron = true
        end
    end)

    if id then
        sd._event_listener_id = id
        return true
    end
    return false
end

-- ─── Layer 2: Native Call Intelligence (HookNative) ──────────────────────────
-- Hooks 38 detection-surface natives via HookNative to log which resource
-- calls them, how often, and from where. Covers every native this menu's
-- existing bypasses (ReaperV4, WaveShield, Electron) have ever needed to
-- spoof — godmode, health, weapons, movement, camera, visibility, spectate,
-- vehicle, resource enumeration, network ownership, thermal, plus 3
-- unresolved hashes from the WaveShield layer that Electron likely polls.
StaticFeatures._electron_scanner_hook_ids = {}

function StaticFeatures.electron_scanner_start_native_hooks()
    local sd = StaticFeatures._electron_scanner_data
    local hookIds = StaticFeatures._electron_scanner_hook_ids

    if type(SharkAPI) ~= "table"
        or type(SharkAPI.Scripting) ~= "table"
        or type(SharkAPI.Scripting.HookNative) ~= "function" then
        return false
    end

    local HN = SharkAPI.Scripting.HookNative

    local function logNativeCall(nativeName, args)
        local entry = sd.native_calls[nativeName]
        if not entry then
            entry = {
                count = 0,
                resources = {},
                lastArgs = nil,
                firstSeen = GetGameTimer(),
                lastSeen = 0,
            }
            sd.native_calls[nativeName] = entry
        end
        entry.count = entry.count + 1
        entry.lastSeen = GetGameTimer()
        if args then entry.lastArgs = args end

        local res = nil
        pcall(function() res = GetCurrentResourceName() end)
        if res and res ~= "" then
            entry.resources[res] = (entry.resources[res] or 0) + 1
        end
    end

    -- HookNative pattern for scanner: callback returns true (call original) always.
    -- First return = callOriginal, remaining returns = replacement values.
    -- For scanner we ONLY log and pass through — always return true, no replacement.
    local hooks = {
        -- ── Godmode / invincibility surface ──
        { name = "GetPlayerInvincible",         hash = 0xB721981B },
        { name = "GetPlayerInvincible_2",       hash = 0x4270BC95 },
        { name = "GetEntityProofs",             hash = 0xBE8CD9BE },
        { name = "IsEntityInvincible",          hash = 0x47C3B5848C3E45D8 },

        -- ── Health / armour / damage surface ──
        { name = "GetEntityHealth",             hash = 0xEEF059FAD016D209 },
        { name = "GetEntityMaxHealth",          hash = 0x36731AC041289BB1 },
        { name = "GetPedArmour",                hash = 0x9483AF821C9B9B31 },

        -- ── Weapon detection surface ──
        { name = "GetSelectedPedWeapon",        hash = 0x0A6DB4965674D243 },
        { name = "GetCurrentPedWeapon",         hash = 0x8483E98E8B888AE2 },
        { name = "GetCurrentPedWeaponEntityIndex", hash = 0x3A87E44BB9A01D54 },
        { name = "HasPedGotWeapon",             hash = 0x8DECB02F88F428BC },

        -- ── Movement / position / speed surface ──
        { name = "GetEntityCoords",             hash = 0x3FEF770D40960D5A },
        { name = "GetEntitySpeed",              hash = 0xD5037BA82E12416F },
        { name = "GetEntityHeading",            hash = 0xE83D4F9BA2A38914 },
        { name = "GetEntityCollisionDisabled",  hash = 0xCCF1E97BEFDAE480 },

        -- ── Camera / aimbot detection surface ──
        { name = "GetGameplayCamCoord",         hash = 0x14D6F5678D8F1B37 },
        { name = "GetGameplayCamRot",           hash = 0x837765A25378F64A },
        { name = "GetFinalRenderedCamCoord",    hash = 0xA200EB1EE790F448 },
        { name = "GetRenderingCam",             hash = 0x5234F9F10919EABA },

        -- ── Visibility / spectate surface ──
        { name = "IsEntityVisible",             hash = 0x47D6F43D77935C75 },
        { name = "IsEntityVisibleToScript",     hash = 0xD796CB5BA8F20E32 },
        { name = "IsEntityOnScreen",            hash = 0xE659E47AF827484B },
        { name = "IsEntityOccluded",            hash = 0xE31C2C72B8692B64 },
        { name = "NetworkIsInSpectatorMode",    hash = 0x048746E388762E11 },
        { name = "GetPedType",                  hash = 0xFF059E1E4C01E63C },

        -- ── Vehicle detection surface ──
        { name = "GetVehicleCheatPowerIncrease", hash = 0xAF35D0D2583051B0 },
        { name = "IsPedInAnyVehicle",           hash = 0x997ABD671D25CA0B },

        -- ── Resource / command enumeration surface ──
        { name = "GetRegisteredCommands",       hash = 0xD4BEF069 },
        { name = "GetNumResources",             hash = 0x863F27B },
        { name = "GetResourceByFindIndex",      hash = 0x4207F92D },
        { name = "GetNumResourceMetadata",      hash = 0x776E864 },
        { name = "GetResourceMetadata",         hash = 0x61F93B91 },

        -- ── Network / ownership surface ──
        { name = "NetworkGetEntityOwner",       hash = 0x7228D5E8 },
        { name = "NetworkHasControlOfEntity",   hash = 0x01BF60A500E28887 },
        { name = "NetworkRequestControlOfEntity", hash = 0xB69317BF5E782347 },

        -- ── Thermal / seethrough ──
        { name = "GetUsingseethrough",          hash = 0x44B80084 },

        -- ── Unresolved hashes from WaveShield (Electron likely polls these) ──
        { name = "UnknownAC_1",                 hash = 0x423DE3854BB2D784 },
        { name = "UnknownAC_2",                 hash = 0xB721981B2B939E07 },
        { name = "UnknownAC_3",                 hash = 0xEDBE6ADDB9CE12B4 },
    }

    local installed = 0
    for _, hook in ipairs(hooks) do
        local hookName = hook.name
        local ok, result = pcall(HN, hook.hash, function(...)
            logNativeCall(hookName)
            return true
        end)
        if ok and result then
            hookIds[hookName] = hook.hash
            installed = installed + 1
        end
    end

    return installed > 0
end

-- ─── Layer 3: Export Probe (safe-resource inject) ────────────────────────────
-- Injected into a neutral resource (chat/spawnmanager) to probe the Electron
-- resource's exports metatable. Can't do this from our own context — exports
-- are per-resource proxied through cfx metamethods. The inject walks the
-- exports[electronRes] proxy and logs every function name it finds.
StaticFeatures._ELECTRON_EXPORT_PROBE = [==[
pcall(function()
    local T = type
    local P = pcall
    local _t = (T(Citizen)=="table" and T(Citizen.Trace)=="function") and Citizen.Trace or (T(print)=="function" and print or function()end)
    local function o(m) _t("^5[SCAN]^7 "..tostring(m).."\n") end
    local function g(m) _t("^2[SCAN]^7 "..tostring(m).."\n") end

    local TARGET_RES = "__ELECTRON_RES__"
    g("Export probe — target: "..TARGET_RES)

    P(function()
        if T(exports) ~= "table" and T(exports) ~= "userdata" then
            o("exports not available"); return
        end

        local ex = nil
        P(function() ex = exports[TARGET_RES] end)
        if not ex then o("exports["..TARGET_RES.."] = nil"); return end

        g("exports["..TARGET_RES.."] type: "..T(ex))

        local mt = getmetatable(ex)
        g("  metatable type: "..T(mt))
        if T(mt) == "table" then
            for k, v in pairs(mt) do
                o("  mt."..tostring(k).." = "..T(v))
            end
        end

        local COMMON_EXPORTS = {
            "recordPlayer", "screenshotPlayer", "punish", "banPlayer",
            "kickPlayer", "flagPlayer", "warnPlayer", "reportPlayer",
            "checkIntegrity", "scanMemory", "sendHeartbeat",
            "captureScreenshot", "requestClientRecording",
            "MakeAnticheatReport", "sendReport", "submitReport",
            "isPlayerFlagged", "getPlayerFlags", "getDetections",
            "init", "start", "stop", "configure", "setConfig",
            "registerDetection", "unregisterDetection",
            "getVersion", "getStatus",
        }

        local found = {}
        for _, fnName in ipairs(COMMON_EXPORTS) do
            P(function()
                local fn = ex[fnName]
                if fn ~= nil then
                    found[#found + 1] = fnName .. " (" .. T(fn) .. ")"
                    g("  EXPORT FOUND: " .. fnName .. " = " .. T(fn))
                end
            end)
        end

        if #found == 0 then
            o("  No common exports found — Electron may use obfuscated export names")
        else
            g("  Total exports found: " .. #found)
        end

        P(function()
            if T(mt) == "table" and mt.__index and T(mt.__index) == "function" then
                g("  __index is function — exports use dynamic dispatch (expected for cfx)")
            end
        end)
    end)
end)
]==]

function StaticFeatures.electron_scanner_start_export_probe(electronRes)
    if not electronRes or electronRes == "" then return false end
    if type(StaticShark) ~= "table" or type(StaticShark.inject) ~= "function" then
        return false
    end

    local payload = StaticFeatures._ELECTRON_EXPORT_PROBE:gsub("__ELECTRON_RES__", electronRes)

    local safeTarget = nil
    if type(SharkAPI) == "table" and type(SharkAPI.GetLoadedResources) == "function" then
        local ok, loaded = pcall(SharkAPI.GetLoadedResources)
        if ok and type(loaded) == "table" then
            local preferred = {"chat", "spawnmanager", "sessionmanager", "mapmanager", "hardcap"}
            for _, pref in ipairs(preferred) do
                for _, r in ipairs(loaded) do
                    if r == pref then safeTarget = r; break end
                end
                if safeTarget then break end
            end
            if not safeTarget then
                for _, r in ipairs(loaded) do
                    if r ~= electronRes then safeTarget = r; break end
                end
            end
        end
    end
    if not safeTarget then safeTarget = "chat" end

    local ok, result = pcall(StaticShark.inject, safeTarget, payload)
    return ok and result ~= false
end

-- ─── Scanner Control: start / stop / dump ────────────────────────────────────

function StaticFeatures.electron_scanner_start(durationSec)
    local sd = StaticFeatures._electron_scanner_data
    if sd.scan_running then return false end

    sd.events = {}
    sd.native_calls = {}
    sd.exports_map = {}
    sd.scan_start = GetGameTimer()
    sd.scan_running = true
    durationSec = durationSec or 60

    local electronRes = nil
    if type(StaticFeatures.ac_electron_resource) == "function" then
        electronRes = StaticFeatures.ac_electron_resource()
    end

    local trace = type(Citizen) == "table" and type(Citizen.Trace) == "function"
        and Citizen.Trace or print

    trace("^2[SCANNER]^7 ═══ Electron AC Runtime Scanner V1.0 ═══\n")
    trace("^2[SCANNER]^7 Target: " .. tostring(electronRes or "NOT DETECTED") .. "\n")
    trace("^2[SCANNER]^7 Duration: " .. durationSec .. "s\n")
    trace("^2[SCANNER]^7 Starting Layer 1: Event listener...\n")

    local evOk = StaticFeatures.electron_scanner_start_event_listener()
    trace("^2[SCANNER]^7 Event listener: " .. (evOk and "^2ACTIVE" or "^1FAILED") .. "^7\n")

    trace("^2[SCANNER]^7 Starting Layer 2: Native call hooks...\n")
    local natOk = StaticFeatures.electron_scanner_start_native_hooks()
    trace("^2[SCANNER]^7 Native hooks: " .. (natOk and "^2ACTIVE" or "^1FAILED") .. "^7\n")

    if electronRes then
        trace("^2[SCANNER]^7 Starting Layer 3: Export probe...\n")
        local expOk = StaticFeatures.electron_scanner_start_export_probe(electronRes)
        trace("^2[SCANNER]^7 Export probe: " .. (expOk and "^2ACTIVE" or "^1FAILED") .. "^7\n")
    else
        trace("^3[SCANNER]^7 Layer 3 skipped — Electron resource not detected yet\n")
    end

    trace("^2[SCANNER]^7 All layers armed. Use features normally for " .. durationSec .. "s.\n")
    trace("^2[SCANNER]^7 Toggle noclip, weapons, godmode — the scanner watches what Electron sees.\n")
    trace("^2[SCANNER]^7 Results will dump to F8 automatically.\n")

    CreateThread(function()
        Wait(durationSec * 1000)
        if sd.scan_running then
            StaticFeatures.electron_scanner_dump()
            StaticFeatures.electron_scanner_stop()
        end
    end)

    return true
end

function StaticFeatures.electron_scanner_stop()
    local sd = StaticFeatures._electron_scanner_data
    sd.scan_running = false

    if sd._event_listener_id then
        if type(SharkAPI) == "table" and type(SharkAPI.RemoveAddServerEventListener) == "function" then
            pcall(SharkAPI.RemoveAddServerEventListener, sd._event_listener_id)
        end
        sd._event_listener_id = nil
    end

    local hookIds = StaticFeatures._electron_scanner_hook_ids
    if type(SharkAPI) == "table" and type(SharkAPI.Scripting) == "table"
        and type(SharkAPI.Scripting.RestoreNative) == "function" then
        for name, hookId in pairs(hookIds) do
            pcall(SharkAPI.Scripting.RestoreNative, hookId)
        end
    end
    StaticFeatures._electron_scanner_hook_ids = {}
end

function StaticFeatures.electron_scanner_dump()
    local sd = StaticFeatures._electron_scanner_data
    local elapsed = (GetGameTimer() - sd.scan_start) / 1000

    local trace = type(Citizen) == "table" and type(Citizen.Trace) == "function"
        and Citizen.Trace or print

    trace("\n^2[SCANNER]^7 ═══════════════════════════════════════════════════════\n")
    trace("^2[SCANNER]^7 SCAN RESULTS — " .. string.format("%.1f", elapsed) .. "s elapsed\n")
    trace("^2[SCANNER]^7 ═══════════════════════════════════════════════════════\n\n")

    -- Event dump
    local electronEvents = {}
    local otherEvents = {}
    local totalEvents = 0

    for eName, entry in pairs(sd.events) do
        totalEvents = totalEvents + 1
        if entry.isElectron then
            electronEvents[#electronEvents + 1] = {name = eName, data = entry}
        else
            otherEvents[#otherEvents + 1] = {name = eName, data = entry}
        end
    end

    trace("^3[EVENTS]^7 Total unique events captured: " .. totalEvents .. "\n")

    if #electronEvents > 0 then
        trace("^1[EVENTS]^7 ─── ELECTRON EVENTS (" .. #electronEvents .. ") ───\n")
        table.sort(electronEvents, function(a, b) return a.data.count > b.data.count end)
        for _, ev in ipairs(electronEvents) do
            local d = ev.data
            local avgSize = 0
            if #d.payloadSizes > 0 then
                local sum = 0
                for _, s in ipairs(d.payloadSizes) do sum = sum + s end
                avgSize = sum / #d.payloadSizes
            end
            trace("^1  " .. ev.name .. "^7\n")
            trace("    count=" .. d.count
                .. " avgPayload=" .. string.format("%.0f", avgSize)
                .. " lastPayload=" .. d.lastPayloadSize
                .. " resource=" .. d.resource .. "\n")
        end
    else
        trace("^3[EVENTS]^7 No events from Electron resource detected\n")
        trace("^3[EVENTS]^7 (Electron may not be running, or uses a different resource name)\n")
    end

    if #otherEvents > 0 then
        trace("^5[EVENTS]^7 ─── OTHER EVENTS (top 30 by count) ───\n")
        table.sort(otherEvents, function(a, b) return a.data.count > b.data.count end)
        local shown = 0
        for _, ev in ipairs(otherEvents) do
            if shown >= 30 then break end
            shown = shown + 1
            local d = ev.data
            trace("^5  " .. ev.name .. "^7 count=" .. d.count
                .. " payload=" .. d.lastPayloadSize
                .. " res=" .. d.resource .. "\n")
        end
    end

    -- Native call dump
    trace("\n^3[NATIVES]^7 ─── NATIVE CALL LOG ───\n")
    local nativeCount = 0
    local nativeSorted = {}
    for nName, entry in pairs(sd.native_calls) do
        nativeCount = nativeCount + 1
        nativeSorted[#nativeSorted + 1] = {name = nName, data = entry}
    end
    table.sort(nativeSorted, function(a, b) return a.data.count > b.data.count end)

    if nativeCount > 0 then
        trace("^3[NATIVES]^7 " .. nativeCount .. " unique natives intercepted:\n")
        for _, nat in ipairs(nativeSorted) do
            local d = nat.data
            trace("^3  " .. nat.name .. "^7 calls=" .. d.count .. "\n")
            if next(d.resources) then
                local resList = {}
                for rName, rCount in pairs(d.resources) do
                    resList[#resList + 1] = rName .. "(" .. rCount .. ")"
                end
                trace("    resources: " .. table.concat(resList, ", ") .. "\n")
            end
        end
    else
        trace("^3[NATIVES]^7 No native calls intercepted (hooks may not have fired)\n")
    end

    trace("\n^2[SCANNER]^7 ═══════════════════════════════════════════════════════\n")
    trace("^2[SCANNER]^7 SCAN COMPLETE — copy F8 output for analysis\n")
    trace("^2[SCANNER]^7 ═══════════════════════════════════════════════════════\n\n")
end

-- ─── Entry Points ────────────────────────────────────────────────────────────
function StaticFeatures.detect_electron_on_join()
    -- PAID ELECTRON BYPASS (2026-10-16, user: "use this for the electron bypass exactly (i paid for this)").
    -- Resolve Electron by FINGERPRINT (find_electron_resource, honouring "inject into the scan not by name"),
    -- then arm the paid Lua-VM registry-neuter inject. Re-injected across the load window so it lands once
    -- Electron's VM has built its anti* registry; the payload self-logs and is idempotent-safe to re-run.
    local target = nil
    if type(StaticFeatures.find_electron_resource) == "function" then
        target = StaticFeatures.find_electron_resource()
    end
    StaticFeatures._electron_on_join = (target ~= nil and target ~= "")
    if StaticFeatures._electron_on_join and type(CreateThread) == "function" then
        if not _G.__STATIC_ELECTRON_PAID_ARM then
            _G.__STATIC_ELECTRON_PAID_ARM = true
            CreateThread(function()
                local tries = 0
                while tries < 20 and not StaticFeatures._electron_ac_bypass_applied do
                    tries = tries + 1
                    local res = (type(StaticFeatures.find_electron_resource) == "function" and StaticFeatures.find_electron_resource()) or target
                    if res and res ~= "" then
                        pcall(StaticFeatures.apply_electron_ac_bypass, res)
                    end
                    Wait(1500)
                end
            end)
        end
    end
    return StaticFeatures._electron_on_join
end

-- ═══════════════════════════════════════════════════════════════════════════════
-- Electron AC Bypass — PENDING (scanner-first approach)
-- ═══════════════════════════════════════════════════════════════════════════════
-- Previous approaches ruled out:
--   V3.x hooks — works for spectate, noclip banned (position mismatch)
--   V4.0 inject into Electron VM — banned on inject (Electron detects injection)
--   StopResource — server blocks it
--   BlockServerEvent — kills heartbeat, instant detection
-- Next step: run scanner on clean join to map Electron's full detection surface,
--   then build a bypass informed by what the scanner finds.

StaticFeatures._electron_bypass_hooks_installed = false
StaticFeatures._electron_bypass_hook_ids = {}

function StaticFeatures.electron_bypass_install()
    -- DISABLED (per user): this auto-ran a 60s Electron scanner on join (event listener + native hooks
    -- + env export probe) which FROZE the game on Electron servers. No-op now. The real bypass is the
    -- NUI screenshot/OCR spoof below (apply_electron_ac_bypass) — JS layer, not the Lua VM, so no freeze.
    StaticFeatures._electron_bypass_hooks_installed = true
    do return false end
end

-- ═══ ELECTRONAC (vg_2025) BYPASS — NUI SCREENSHOT / OCR / VIDEO SPOOF ═════════════════════════════
-- Decoded from the Vendetta Gaming dump (2026-10-14). ElectronAC's Lua client is VM-obfuscated, but its
-- ENTIRE detection engine lives in the readable NUI (web/index.js), and it is all canvas-based:
--   window.addEventListener("message"):
--     e.data.screenshotRequest -> new dm().requestScreenshot()  : gameView.render() -> gameCanvas ->
--                                 toDataURL()/toBlob() -> fetch/FormData upload
--     e.data.recordingRequest  -> new fu().requestRecording()   : canvas.captureStream() -> MediaRecorder
--     e.data.onScreenRequest   -> tesseract.js OCR on the game canvas, matched against pushed keywords
-- So EVERY detection reads the game frame off a canvas. We override the canvas capture PRIMITIVES at the
-- prototype level inside Electron's NUI so every read returns a clean random frame: the screenshot upload
-- is a blank frame, tesseract OCRs nothing, the video is clean. Electron never SEES your menu, so it never
-- builds a report. This is injected with SharkAPI.InjectJavaScript into Electron's CEF/NUI frame — the JS
-- layer, NOT the Lua VM — which is exactly why it does not freeze the game like the old env-nuke did.
StaticFeatures.ELECTRON_NUI_SPOOF_JS = [==[
(function(){
  if (window.__STATIC_EAC_SPOOF) return;
  window.__STATIC_EAC_SPOOF = true;
  try {
    var BIG = function(w,h){ return (w|0) > 200 && (h|0) > 150; };  // only game-capture canvases, not UI
    // a clean, real-looking frame (solid random colour, like the WaveShield bypass) — never pure black,
    // which could read as "tampered/black screen".
    function paintClean(ctx, w, h){
      var r=(Math.random()*60)|0, g=(Math.random()*60)|0, b=(Math.random()*60)|0;
      ctx.fillStyle = 'rgb('+r+','+g+','+b+')';
      ctx.fillRect(0,0,w,h);
    }
    function cleanCanvas(w,h){
      var c=document.createElement('canvas'); c.width=w; c.height=h;
      paintClean(c.getContext('2d'), w, h); return c;
    }

    // 1) toDataURL / toBlob -> clean frame (the screenshot upload AND OCR-via-dataURL)
    var _toDataURL = HTMLCanvasElement.prototype.toDataURL;
    HTMLCanvasElement.prototype.toDataURL = function(type, q){
      try { if (BIG(this.width,this.height)) return _toDataURL.call(cleanCanvas(this.width,this.height), type||'image/png', q); } catch(e){}
      return _toDataURL.apply(this, arguments);
    };
    var _toBlob = HTMLCanvasElement.prototype.toBlob;
    if (_toBlob) HTMLCanvasElement.prototype.toBlob = function(cb, type, q){
      try { if (BIG(this.width,this.height)) return _toBlob.call(cleanCanvas(this.width,this.height), cb, type||'image/png', q); } catch(e){}
      return _toBlob.apply(this, arguments);
    };

    // 2) getImageData / readPixels -> blank (OCR / processing reading pixels directly)
    var _gid = CanvasRenderingContext2D.prototype.getImageData;
    CanvasRenderingContext2D.prototype.getImageData = function(sx,sy,sw,sh){
      var d = _gid.apply(this, arguments);
      try { if (BIG(sw,sh)) { var a=d.data; for (var i=0;i<a.length;i+=4){ a[i]=0;a[i+1]=0;a[i+2]=0;a[i+3]=255; } } } catch(e){}
      return d;
    };
    if (window.WebGLRenderingContext) {
      var _rp = WebGLRenderingContext.prototype.readPixels;
      WebGLRenderingContext.prototype.readPixels = function(x,y,w,h,f,t,p){
        _rp.apply(this, arguments);
        try { if (p && p.fill && BIG(w,h)) p.fill(0); } catch(e){}
      };
    }
    if (window.WebGL2RenderingContext) {
      var _rp2 = WebGL2RenderingContext.prototype.readPixels;
      WebGL2RenderingContext.prototype.readPixels = function(x,y,w,h,f,t,p){
        _rp2.apply(this, arguments);
        try { if (p && p.fill && BIG(w,h)) p.fill(0); } catch(e){}
      };
    }

    // 3) captureStream -> clean (the MediaRecorder video path)
    var _cs = HTMLCanvasElement.prototype.captureStream;
    if (_cs) HTMLCanvasElement.prototype.captureStream = function(fps){
      try {
        if (BIG(this.width,this.height)) {
          var c=document.createElement('canvas'); c.width=this.width; c.height=this.height;
          var x=c.getContext('2d');
          (function draw(){ paintClean(x, c.width, c.height); try{requestAnimationFrame(draw);}catch(e){} })();
          return _cs.call(c, fps);
        }
      } catch(e){}
      return _cs.apply(this, arguments);
    };

    // 4) belt + suspenders: empty the OCR keyword list before Electron's own message handler runs, so
    //    even a leaked frame matches nothing. Capture phase = runs first.
    window.addEventListener('message', function(e){
      try {
        var d = e && e.data;
        if (d && d.onScreenRequest && d.onScreenRequest.keywords) d.onScreenRequest.keywords = [];
      } catch(_){}
    }, true);
  } catch(e){}
})();
]==]

-- Find Electron by FINGERPRINT, not name — Electron gets renamed per server (vg_2025 on Vendetta, etc.),
-- so a name list misses it. From the Vendetta dump, Electron's fxmanifest.lua is unmistakable: author
-- 'Electron Services', the electron-services.com URL / "most advanced fiveM anticheat" line, and the
-- exact client layout (src/include/client.lua + src/client/main.lua + web/index.html|index.js). We scan
-- every STARTED resource's small fxmanifest for that signature. Cached after first hit (the deep scan
-- isn't free), re-scanned only if the cached resource stops.
-- Resolve Electron's resource using the build's OWN scanner (scan_anticheats → byName.ElectronAC, which
-- now includes the fxmanifest fingerprint matches too). One source of truth — no separate scan here.
function StaticFeatures.find_electron_resource()
    local function from_cache()
        local scan = StaticFeatures._ac_scan_cache
        local list = scan and scan.byName and scan.byName.ElectronAC
        if list and list[1] and list[1].resource and list[1].resource ~= "" then
            local r = list[1].resource
            if type(GetResourceState) ~= "function"
                or GetResourceState(r) == "started" or GetResourceState(r) == "starting" then
                return r
            end
        end
        return nil
    end
    local r = from_cache()
    if r then return r end
    -- cache empty/cold: trigger the full scan once, then read it back.
    if type(StaticFeatures.scan_anticheats) == "function" then
        pcall(StaticFeatures.scan_anticheats, true)
        r = from_cache()
        if r then return r end
    end
    -- last resort: the metadata/author resolver.
    local byMeta = type(StaticFeatures.ac_electron_resource) == "function" and StaticFeatures.ac_electron_resource()
    if byMeta and byMeta ~= "" then return byMeta end
    return nil
end

-- ═══ PAID ELECTRON BYPASS (user-supplied, applied exactly) ═══════════════════════════════════════════
-- The user paid for this and said "use this exactly." The method: inject into Electron's OWN Lua VM via
-- SharkAPI.Lua.AddDebugLib (adds a scoped `safeDebug` lib so debug.getupvalue works inside the target VM)
-- then SharkAPI.Inject the payload. The payload runs a coroutine that:
--   - walks AddEventHandler's `eventHandlers` upvalue to reach every registered handler closure,
--   - scores anti* registry tables (antiTeleport/antiNoclip/antiResourceStop + anti* keys with punish/mod),
--   - finds punisher tables (punishPlayer) via the same walk,
--   - NEUTERS detection: rawset(entry,"punish",noop), rawset(mod,"punish",noop),
--     rawset(punisher,"punishPlayer",noop), wipes antiTeleport/antiNoclip position/flag state, noops the
--     module interval functions.
-- The payload BODY below is byte-identical to the paid drop (message 7.txt). The only change is the inject
-- TARGET: the literal "ElectronAC" on the two SharkAPI calls is replaced by the FINGERPRINT-scanned resource
-- (find_electron_resource), per the user's standing "inject into the scan for electron not by name" rule, so
-- it works on renamed Electron (vg_2025 etc.). The payload's internal logic takes no resource name — it runs
-- inside whatever VM Inject lands in — so nothing inside the payload needs changing.
StaticFeatures.ELECTRON_PAID_INJECT = [=[
local function work()
    local function add(s)
    end
    local function ups(fn, limit)
        local o = {}
        if type(fn) ~= "function" or type(safeDebug) ~= "table" then return o end
        for i = 1, limit or 24 do
            local ok, n, v = pcall(safeDebug.getupvalue, fn, i)
            if not ok or n == nil then break end
            local row = {}
            row.n = n
            row.v = v
            o[#o + 1] = row
        end
        return o
    end
    local function cut(s, lim)
        s = tostring(s)
        lim = lim or 48
        if #s > lim then s = string.sub(s, 1, lim) end
        return string.gsub(s, "%c", ".")
    end

    add("boot")

    local eh
    local au = ups(AddEventHandler, 12)
    for i = 1, #au do
        if au[i].n == "eventHandlers" then eh = au[i].v end
    end
    if type(eh) ~= "table" then
        add("no eh")
        return
    end

    local seenF = {}
    local registryCandidates = {}
    local punishers = {}
    local seenP = {}
    local visits = 0

    local function notePunisher(tag, t)
        if type(t) ~= "table" or seenP[t] then return end
        if type(rawget(t, "punishPlayer")) == "function" then
            seenP[t] = true
            punishers[#punishers + 1] = { tag = tag, t = t }
            add("PUNISHER " .. tag
                .. " regListen=" .. type(rawget(t, "registerPunishListener")))
        end
    end

    local function scoreRegistry(t)
        if type(t) ~= "table" then return 0 end
        local score = 0
        if type(rawget(t, "antiTeleport")) == "table" then score = score + 50 end
        if type(rawget(t, "antiNoclip")) == "table" then score = score + 40 end
        if type(rawget(t, "antiResourceStop")) == "table" then score = score + 30 end
        local ck, nAnti, c = nil, 0, 0
        while c < 100 do
            local ok, nk, nv = pcall(next, t, ck)
            if not ok or nk == nil then break end
            ck = nk
            c = c + 1
            if type(nk) == "string" and string.sub(nk, 1, 4) == "anti" and type(nv) == "table" then
                nAnti = nAnti + 1
                if type(rawget(nv, "punish")) == "function" or type(rawget(nv, "mod")) == "table" then
                    score = score + 2
                end
            end
        end
        if nAnti >= 5 then score = score + nAnti end
        return score
    end

    local function noteReg(tag, t)
        local sc = scoreRegistry(t)
        if sc < 40 then return end
        for i = 1, #registryCandidates do
            if registryCandidates[i].t == t then return end
        end
        registryCandidates[#registryCandidates + 1] = { tag = tag, t = t, score = sc }
        add("REGCAND " .. tag .. " score=" .. tostring(sc))
    end

    local walkFn
    local function walkTable(tag, t, depth)
        if type(t) ~= "table" or depth > 7 or visits > 5000 then return end
        visits = visits + 1
        noteReg(tag, t)
        notePunisher(tag, t)
        if seenF[t] == true then return end
        seenF[t] = true
        local k, n = nil, 0
        while n < 100 do
            local ok, nk, nv = pcall(next, t, k)
            if not ok or nk == nil then break end
            k = nk
            n = n + 1
            if type(nv) == "table" then
                walkTable(tag .. "." .. cut(nk, 18), nv, depth + 1)
            elseif type(nv) == "function" and depth < 5 then
                walkFn(tag .. "." .. cut(nk, 18), nv, depth + 1)
            end
        end
    end

    walkFn = function(tag, fn, depth)
        if type(fn) ~= "function" or depth > 5 then return end
        if seenF[fn] == "fn" then return end
        seenF[fn] = "fn"
        local uv = ups(fn, 24)
        for i = 1, #uv do
            local row = uv[i]
            if type(row.v) == "table" then
                walkTable(tag .. ".U." .. tostring(row.n), row.v, depth + 1)
            elseif type(row.v) == "function" then
                walkFn(tag .. ".U." .. tostring(row.n), row.v, depth + 1)
            end
        end
    end

    local ek, nEv = nil, 0
    while nEv < 80 do
        local ok, name, bucket = pcall(next, eh, ek)
        if not ok or name == nil then break end
        ek = name
        nEv = nEv + 1
        local handlers = bucket
        if type(bucket) == "table" then
            local bk = nil
            while true do
                local ok2, bn, bv = pcall(next, bucket, bk)
                if not ok2 or bn == nil then break end
                bk = bn
                if bn == "handlers" then handlers = bv end
            end
        end
        if type(handlers) == "function" then
            walkFn("ev." .. cut(name, 14), handlers, 0)
        elseif type(handlers) == "table" then
            local hk, hn = nil, 0
            while hn < 16 do
                local ok3, id, slot = pcall(next, handlers, hk)
                if not ok3 or id == nil then break end
                hk = id
                hn = hn + 1
                local fn = slot
                if type(slot) == "table" then
                    fn = slot.func or slot[1] or slot.callback
                end
                if type(fn) == "function" then
                    walkFn("ev." .. cut(name, 14) .. "#" .. tostring(id), fn, 0)
                end
            end
        end
    end
    add("events " .. tostring(nEv) .. " visits " .. tostring(visits)
        .. " regCands " .. tostring(#registryCandidates)
        .. " punishers " .. tostring(#punishers))

    local function noop()
        return
    end

    local function harvestFromPunish(fn, tag)
        if type(fn) ~= "function" then return end
        local uv = ups(fn, 16)
        for i = 1, #uv do
            if type(uv[i].v) == "table" then
                notePunisher(tag .. ".U." .. tostring(uv[i].n), uv[i].v)
            end
        end
    end

    table.sort(registryCandidates, function(a, b) return a.score > b.score end)

    local wrapPatched, modPatched, fail = 0, 0, 0
    local intervalKilled = 0
    local killNames = {
        antiTeleport = true,
        antiTeleportToWaypoint = true,
        antiNoclip = true,
    }

    for ri = 1, #registryCandidates do
        local reg = registryCandidates[ri].t
        add("registry " .. registryCandidates[ri].tag)

        local names = {}
        local rk = nil
        while true do
            local ok, nk = pcall(next, reg, rk)
            if not ok or nk == nil then break end
            rk = nk
            if type(nk) == "string" then names[#names + 1] = nk end
        end
        table.sort(names)

        for i = 1, #names do
            local name = names[i]
            local entry = rawget(reg, name)
            if type(entry) ~= "table" then goto continue end

            local mod = rawget(entry, "mod")
            local wrapPunish = rawget(entry, "punish")
            local modPunish = type(mod) == "table" and rawget(mod, "punish") or nil

            add("entry " .. name
                .. " wrapPunish=" .. type(wrapPunish)
                .. " mod=" .. type(mod)
                .. " modPunish=" .. type(modPunish)
                .. " same=" .. tostring(wrapPunish ~= nil and wrapPunish == modPunish))

            harvestFromPunish(wrapPunish, name .. ".wrap")
            harvestFromPunish(modPunish, name .. ".mod")

            if type(wrapPunish) == "function" then
                pcall(function()
                    rawset(entry, "punish", noop)
                end)
                if rawget(entry, "punish") == noop then
                    wrapPatched = wrapPatched + 1
                    add("wrapOK " .. name)
                else
                    pcall(function() entry.punish = noop end)
                    if rawget(entry, "punish") == noop then
                        wrapPatched = wrapPatched + 1
                        add("wrapOK2 " .. name)
                    else
                        fail = fail + 1
                        add("wrapFAIL " .. name)
                    end
                end
            end

            if type(mod) == "table" and type(modPunish) == "function" then
                pcall(function()
                    rawset(mod, "punish", noop)
                end)
                if rawget(mod, "punish") ~= noop then
                    pcall(function() mod.punish = noop end)
                end
                if rawget(mod, "punish") == noop then
                    modPatched = modPatched + 1
                    add("modOK " .. name)
                else
                    fail = fail + 1
                    add("modFAIL " .. name)
                end
            end

            local state = type(mod) == "table" and mod or entry
            if killNames[name] and type(state) == "table" then
                if type(rawget(state, "positions")) == "table" then
                    pcall(function()
                        local p = state.positions
                        for j = #p, 1, -1 do p[j] = nil end
                    end)
                end
                pcall(function()
                    if rawget(state, "lastPos") ~= nil then state.lastPos = nil end
                    if rawget(state, "prevPos") ~= nil then state.prevPos = nil end
                    if rawget(state, "lastTeleport") ~= nil then state.lastTeleport = 0 end
                    if rawget(state, "flags") ~= nil then state.flags = 0 end
                    if rawget(state, "vehicleFlags") ~= nil then state.vehicleFlags = 0 end
                    if rawget(state, "heightFlags") ~= nil then state.heightFlags = 0 end
                    if rawget(state, "heightAboveGroundFlags") ~= nil then state.heightAboveGroundFlags = 0 end
                end)

                local function killIntervals(t, where)
                    if type(t) ~= "table" then return end
                    local iv = rawget(t, "intervals")
                    if type(iv) ~= "table" then return end
                    local ik = nil
                    while true do
                        local ok, k, fn = pcall(next, iv, ik)
                        if not ok or k == nil then break end
                        ik = k
                        if type(fn) == "function" then
                            pcall(function()
                                rawset(iv, k, noop)
                            end)
                            if rawget(iv, k) == noop then
                                intervalKilled = intervalKilled + 1
                                add("ivKill " .. name .. " " .. where)
                            end
                        end
                    end
                end
                killIntervals(entry, "wrap")
                killIntervals(mod, "mod")
                add("stateWipe " .. name)
            end

            ::continue::
        end
    end

    local pHit = 0
    for i = 1, #punishers do
        local p = punishers[i].t
        pcall(function()
            rawset(p, "punishPlayer", noop)
        end)
        if rawget(p, "punishPlayer") ~= noop then
            pcall(function() p.punishPlayer = noop end)
        end
        if rawget(p, "punishPlayer") == noop then
            pHit = pHit + 1
            add("punisherOK " .. punishers[i].tag)
        else
            add("punisherFAIL " .. punishers[i].tag)
        end
    end

    local reg = registryCandidates[1] and registryCandidates[1].t
    if type(reg) == "table" then
        local at = rawget(reg, "antiTeleport")
        if type(at) == "table" then
            local mod = rawget(at, "mod")
            add("verify wrap.punishNoop=" .. tostring(rawget(at, "punish") == noop)
                .. " mod.punishNoop=" .. tostring(type(mod) == "table" and rawget(mod, "punish") == noop)
                .. " wrapHasIntervals=" .. type(rawget(at, "intervals"))
                .. " modHasIntervals=" .. tostring(type(mod) == "table" and type(rawget(mod, "intervals"))))
        end
        local nc = rawget(reg, "antiNoclip")
        if type(nc) == "table" then
            add("verifyNc wrap.punishNoop=" .. tostring(rawget(nc, "punish") == noop)
                .. " mod.punishNoop=" .. tostring(type(rawget(nc, "mod")) == "table" and rawget(rawget(nc, "mod"), "punish") == noop))
        end
    end

    add("done wrap=" .. tostring(wrapPatched)
        .. " mod=" .. tostring(modPatched)
        .. " fail=" .. tostring(fail)
        .. " punisher=" .. tostring(pHit)
        .. " ivKill=" .. tostring(intervalKilled))
    add("=== end ===")
end

local co = coroutine.create(work)
local ok, err = coroutine.resume(co)
if not ok then
end
]=]

-- Resolve the running Electron resource by FINGERPRINT (not name) and run the paid Lua-VM neuter inject.
function StaticFeatures.apply_electron_ac_bypass(target)
    local res = target
    if not res or res == "" then
        res = (type(StaticFeatures.find_electron_resource) == "function" and StaticFeatures.find_electron_resource()) or nil
    end
    if not res or res == "" then return false end
    if type(SharkAPI) ~= "table" or type(SharkAPI.Inject) ~= "function" then return false end

    -- EXACTLY as the paid drop: AddDebugLib (scoped safeDebug into Electron's VM) THEN Inject the payload.
    -- Target is the fingerprint-scanned resource in place of the literal "ElectronAC".
    if type(SharkAPI.Lua) == "table" and type(SharkAPI.Lua.AddDebugLib) == "function" then
        pcall(SharkAPI.Lua.AddDebugLib, res, "safeDebug")
    end
    local ok = pcall(SharkAPI.Inject, res, StaticFeatures.ELECTRON_PAID_INJECT) == true

    if ok and not StaticFeatures._electron_ac_bypass_applied then
        StaticFeatures._electron_ac_bypass_applied = true
        _G.__STATIC_ELECTRON_PAID_ON = true
    end
    return ok
end


-- electron_install_event_listener: installs a local event-level fallback filter.
-- This runs in OUR resource (not Electron's) and catches any AC events that
-- Electron might trigger client-side before the inject has run.
-- Every anticheat resource name this file can name outright. Three deliberate exclusions:
--   ReaperV4  -- HookNativeForResource scoped to ReaperV4 is a confirmed ban vector on v4.7.7.
--                harden_reaper_natives was removed from detect_reaper_on_join (2026-09-29).
--                The bypass now uses global native hooks + safe-resource delivery only.
--   WaveShield -- this runs at the top of defer_join_ac_detection and would hook GetInvokingResource
--                inside WaveShield's VM before any feature has been used. Nothing may touch it at
--                launch.
--   FiveGuard  -- HookNativeForResource scoped to FG is a ban vector: FG detects the scoped hook
--                as "Native Manipulation (L/0x1)". The FG bypass uses event blocking (BlockServerEvent
--                / BlockClientEvent), NOT injection — attribution-blinding is unnecessary and actively
--                harmful. Removed 2026-09-29.
StaticFeatures.KNOWN_ANTICHEAT_RESOURCE_NAMES = {
    "FiniAC", "FiniAP",
    "ElectronAC", "vg_2025", "DRILLAC",
    "likizao_ac",
}

-- Hooks GetInvokingResource scoped to each named anticheat's VM, so its hooked-native
-- handler hears "chat" instead of our real inject target. Safe for absent resources
-- (pcall-wrapped, returns false). Defense-in-depth only -- FiveGuard stop-resource and
-- Fini/Electron detect-and-avoid still do the primary work.
function StaticFeatures.harden_known_anticheat_natives()
    -- BAN-VECTOR TEST: hooking FiveGuard's own natives is a tamper it detects. Skip it while the
    -- FG bypass is gated off so nothing touches FiveGuard at boot.
    if _G.__rsync_ac_bypass_on == false then return false end
    if type(StaticShark) ~= "table" or type(StaticShark.harden_resource_natives) ~= "function" then
        return false
    end
    local hardened = 0
    for i = 1, #StaticFeatures.KNOWN_ANTICHEAT_RESOURCE_NAMES do
        local ok = StaticShark.harden_resource_natives(StaticFeatures.KNOWN_ANTICHEAT_RESOURCE_NAMES[i], "chat")
        if ok then hardened = hardened + 1 end
    end
    -- BAN-VECTOR: dynamic FG resource hardening removed — HookNativeForResource scoped
    -- to FiveGuard's resource name triggers "Native Manipulation (L/0x1)". The FG bypass
    -- uses event-blocking (SharkAPI.BlockServerEvent/BlockClientEvent), NOT injection,
    -- so attribution-blinding via GetInvokingResource is unnecessary and harmful.
    return hardened > 0
end

function StaticFeatures.defer_join_ac_detection()
    if StaticFeatures._join_ac_detection_scheduled then return end
    StaticFeatures._join_ac_detection_scheduled = true
    CreateThread(function()
        -- Shark: defer all AC probing until keybind is set (avoids early screen/AC triggers).
        if _G.__STATIC_SHARK_SHIM then
            for _ = 1, 600 do
                if Menu and Menu.keybindConfigured then break end
                Wait(250)
            end
            Wait(8000)
        else
            Wait(2500)
        end
        -- PASSIVE BOOT ON WAVESHIELD (per user + Nexus menu, which opens clean on WaveShield with no
        -- bypass because it "only uses the Shark API thread"). WaveShield does NOT ban the executor
        -- (Nexus/Shadow run the same one undetected on inject) -- it bans the menu's BOOT FOOTPRINT:
        -- harden_known_anticheat_natives touches the native table, and the FiveGuard/Reaper/Electron
        -- passes below walk EVERY resource's metadata. A normal player never does either, and on a
        -- WaveShield server none of it is even wanted (WaveShield delivery is InjectSafe-only, zero
        -- native hooks). So if WaveShield is present, do ONLY the cheap WS detect (GetResourceState +
        -- InjectSafe arm -- both passive, no hooks/scans/inject) and return. Nothing else runs at boot.
        if type(StaticFeatures.waveshield_present) == "function" and StaticFeatures.waveshield_present() then
            if type(StaticFeatures.detect_waveshield_on_join) == "function" then
                pcall(StaticFeatures.detect_waveshield_on_join)
            end
            if type(StaticFeatures.start_ws_autoload_thread) == "function" then
                pcall(StaticFeatures.start_ws_autoload_thread)
            end
            return
        end
        -- Fire early with the name guesses (FiveGuard/FiniAC/FiniAP/WaveShield/ElectronAC/
        -- vg_2025/DRILLAC) before anything else runs -- cheap, scoped, harmless if the
        -- resource under that name doesn't exist on this server.
        pcall(StaticFeatures.harden_known_anticheat_natives)
        -- FiniAC EARLY ARM (2026-09-10): FiniAC's neuter used to be applied dead-last (~after all the
        -- WaveShield/FiveGuard deep scans below), landing ~5-20s post-inject -> a feature toggled before
        -- then got banned. FiniAC detection is a self-contained file-fingerprint scan (finiac_resource_name)
        -- with no dependency on the WS/FG passes, so arm it RIGHT AFTER the hardening pass -- among the first
        -- things up. The original dead-last call is now idempotent (no-op once applied), left as a backstop.
        pcall(StaticFeatures.detect_finiac_on_join)
        pcall(StaticFeatures.detect_quantum_on_join)
        -- XeroShield (2026-10-07): cheap GetResourceState check, no dependency on the WS/FG passes.
        -- Detect early so the notify/latch fires; the inject gate (xsSafe in StaticShark.inject) reads
        -- xeroshield_present() live anyway, so safe-inject is already enforced from frame 0.
        pcall(StaticFeatures.detect_xeroshield_on_join)
        -- WaveShield detection runs HERE, second only to the hardening pass. The FiveGuard passes below each
        -- walk every resource's metadata, so running it after them pushes the bypass ~30s past menu load.
        -- Nothing above this point is a prerequisite: find_waveshield_resource reads GetResourceState direct.
        if type(StaticFeatures.detect_waveshield_on_join) == "function" then
            pcall(StaticFeatures.detect_waveshield_on_join)
        end
        if type(StaticFeatures.start_ws_autoload_thread) == "function" then
            pcall(StaticFeatures.start_ws_autoload_thread)
        end
        pcall(StaticFeatures.detect_fiveguard_on_join)
        Wait(1200)
        pcall(_static_scan_fiveguard_deep)
        pcall(function()
            local fg = StaticFeatures.find_fiveguard_resource(true)
            if fg then
                _G.__STATIC_FIVEGUARD_PRESENT = true
                _G.__STATIC_HOOKS_BLOCKED = true
                pcall(StaticFeatures.detect_fiveguard_on_join)
            end
        end)
        pcall(StaticFeatures.detect_reaper_on_join)
        Wait(600)
        pcall(StaticFeatures.detect_fiveguard_on_join)
        Wait(600)
        pcall(StaticFeatures.detect_fini_on_join)
        pcall(StaticFeatures.detect_electron_on_join)
        -- likizao removed from the load path (2026-09-10, user: "remove likazio stuff it doesnt do
        -- anything"). detect_likizao_on_join / apply_likizao_bypass defs left as dead code.
        -- (WaveShield detect + autoload thread moved to the top of this thread -- see comment there.)
        pcall(StaticFeatures.detect_finiac_on_join)
        pcall(StaticFeatures.detect_quantum_on_join)
        pcall(StaticFeatures.detect_core_admin_on_join)
        pcall(StaticFeatures.detect_base_player_on_join)
        -- Warm the vehicle-spawn resource scan early. It resolves which resource legitimately calls
        -- CreateVehicle and caches it in LocalPlayer.state.mx_res. Kicking it off lazily on the first
        -- spawn means that spawn runs before the result is ready and falls through to a framework
        -- TriggerServerEvent path, which leaves a server-side log.
        if type(StaticFeatures.ensure_vehicle_resource_scan) == "function" then
            pcall(StaticFeatures.ensure_vehicle_resource_scan)
        end
        -- Full metadata scrape only when menu is closed.
        Wait(3000)
        for _ = 1, 40 do
            if not (Menu and Menu.open) then break end
            Wait(250)
        end
        if not StaticFeatures._ac_scan_cache then
            pcall(StaticFeatures.scan_anticheats, true)
        end
        pcall(StaticFeatures.detect_electron_on_join)
        pcall(StaticFeatures.ensure_electron_hooks_installed)
        -- Second pass, after the full metadata scan: catches an AC running under a renamed/obfuscated
        -- resource that the first pass's literal name guesses missed. (likizao removed 2026-09-10 per
        -- user -- "it doesnt do anything"; its second-pass detect call was here.)
        pcall(StaticFeatures.harden_known_anticheat_natives)
    end)
end

function StaticFeatures.run_host_code(code)
    if not code or code == "" then return false, "empty" end
    -- shark_inject refuses to fall back here on WaveShield, but four call sites reach run_host_code
    -- directly and skip that gate -- noclip_inject's last resort and stop_quick_punch both carry real
    -- natives. Gate on readiness rather than presence so bootstrap_inject_context still works once armed.
    if type(StaticFeatures.waveshield_present) == "function"
        and StaticFeatures.waveshield_present()
        and type(StaticFeatures.ws_bypass_fully_ready) == "function"
        and not StaticFeatures.ws_bypass_fully_ready() then
        return false, "waveshield-not-armed"
    end
    if StaticFeatures.fini_present and StaticFeatures.fini_present() then
        pcall(StaticFeatures.ensure_fini_bypass_armed, "feature")
    end
    -- FiniAC on-demand arm: apply the neuter before the feature fires if FiniAC is up and it wasn't
    -- armed on join yet (the inject-race the user got banned by). Idempotent -- no-op once applied.
    if StaticFeatures.finiac_present and StaticFeatures.finiac_present() then
        pcall(StaticFeatures.ensure_finiac_bypass_armed)
    end
    -- core_admin (base_anticheat) on-demand arm -- same parity: neuter before the feature fires.
    if StaticFeatures.core_admin_present and StaticFeatures.core_admin_present() then
        pcall(StaticFeatures.ensure_core_admin_bypass_armed)
    end
    -- Quantum AC on-demand arm — antispoof: arm bypass before the feature fires.
    if StaticFeatures.quantum_present and StaticFeatures.quantum_present() then
        pcall(StaticFeatures.quantum_arm_antispoof)
    end
    StaticFeatures.ensure_safe_run_native()
    StaticFeatures.ensure_safe_wrap_layer_host()
    local env = make_feature_env()
    env.SafeRunNative = SafeRunNative
    env.SafeWrap = _G.SafeWrap
    env.StaticHandlers = StaticHandlers
    copy_macho_into(env)
    local fn, err = load(code, "@static_host", "t", env)
    if not fn then
        fn, err = load(code, "@static_host", "t", _G)
    end
    if not fn then
        menu_dbg("run_host_code load error: " .. tostring(err))
        return false, err
    end
    local ok, err2
    if StaticFeatures.hooks_ready() then
        ok, err2 = StaticFeatures.host_run(function()
            fn()
        end)
        if not ok then err2 = err2 end
    elseif StaticFeatures.reaper_present() then
        ok, err2 = pcall(SafeRunNative, fn)
    else
        ok, err2 = pcall(fn)
    end
    if not ok then
        menu_dbg("run_host_code error: " .. tostring(err2))
        return false, err2
    end
    if env.selectedPlayerId ~= nil then _G.selectedPlayerId = env.selectedPlayerId end
    return true
end

function StaticFeatures.install_reaper_host_wrappers()
    if StaticFeatures._reaper_wrappers_installed then return end
    StaticFeatures._reaper_wrappers_installed = true
    StaticFeatures.ensure_safe_run_native()
    pcall(StaticFeatures.ensure_safe_wrap_layer_host)
end

function StaticFeatures.effective_inject_type(injectType)
    if StaticFeatures.reaper_present() then
        return 3
    end
    return injectType or StaticFeatures.INJECT_TYPE or 0
end

-- Legacy Shiro host inject target. It returned "ReaperV4" then "monitor" -- both of which
-- are Reaper ban conditions by path/resource name. It has no callers today; it is kept
-- only so any stale reference still resolves, and it now delegates to the vetted resolver
-- instead of sitting here as a loaded gun.
-- ── REAPER PER-VM BYPASS ──────────────────────────────────────────────────────
-- Prepends Config.getValue hook + detection API nullification to an injected
-- payload string. Guards with _G.__STATIC_REAPER_CONFIG_HOOKED (same flag as
-- apply_reaper_v4_bypass) so it installs once per VM, not once per inject.
-- Called from shark_inject when Reaper bypass is active: every VM that receives
-- code gets the bypass, not just the safe VM. This is the exploit ban fix —
-- TriggerServerEvent fires from the target resource's VM, which had NO
-- Config.getValue hook. Now every inject target is armed automatically.
StaticFeatures._REAPER_VM_BYPASS = [[
do
if not _G.__STATIC_REAPER_CONFIG_HOOKED then
_G.__STATIC_REAPER_CONFIG_HOOKED=true
local _rc={
["ScreenRecord"]=false,["antiSpectate"]=false,["antiWeaponModifier"]=false,
["antiWeaponSpawn"]=false,["antiTeleport"]=false,["antiNoClip"]=false,
["antiGodMode"]=false,["antiNoCriticalHits"]=false,["antiInfiniteCombatRoll"]=false,
["antiFreeCam"]=false,["antiFreeCam2"]=false,["antiFreeCam3"]=false,
["antiInvisible"]=false,["onScreenMenuDetection"]=false,["antiSkinChanger"]=false,
["antiAttach"]=false,["antiVoiceExploits"]=false,["antiSpawnIsolated"]=false,
["antiSoloSession"]=false,["antiDevTools"]=false,["antiWarpIntoVehicle"]=false,
["antiRepairVehicle"]=false,["antiVehicleModifier"]=false,["antiHitboxModifier"]=false,
["unauthorizedAnimationLoaded"]=false,["antiNPCVehicleAttach"]=false,
["heartbeat"]=false,["antiAimBot"]=false,["antiClothingChanger"]=false,
["antiWeaponComponentModifier"]=false,["pro_addon"]=false,
["antiAttachEntities"]=false,["antiPedSpeedModifier"]=false,
["antiTeleportMaxDistance"]=999999,["ant1iNoClipMaxDistance"]=999999,
["max_aimbot_flags"]=999999}
if Config and Config.getValue then
local _o=Config.getValue
Config.getValue=function(s,k,...)
if type(k)=="string" then
if _rc[k]~=nil then return _rc[k] end
local kl=k:lower()
if kl:find("ignored") or kl:find("blacklisted") then return setmetatable({},{__index=function() return true end}) end
if kl:find("max") then return 999999
elseif kl:find("anti") or kl:find("check") or kl:find("block") then return false end
end
return _o(s,k,...)
end
end
if type(_G.api)=="table" then
for _,fn in ipairs({"addDetection","onDetection","onBan"}) do
if _G.api[fn] then _G.api[fn]=function() return nil end end
end
end
end
end
]]

function StaticFeatures.exploit_reaper_wrap(code)
    if type(code) ~= "string" or code == "" then return code end
    return StaticFeatures._REAPER_VM_BYPASS .. code
end

-- SECONDARY REAPER BYPASS RE-ARMED (apple sauce 2026-10-21): the client Lumia mute (apply_reaper_v4_bypass)
-- handles detection; this flag turns the NATIVE launder back on -- the SafeRunNative statebag hop +
-- safe_wrap_layer (the ~110 void-native re-point) that lets vehicle/ped spawning and other native features
-- run through Reaper's own authorized path instead of raw from the inject VM. This is the "secondary bypass
-- we used to have for native stuff." Scoped by with_safe_run_native (idempotent per VM) so a given VM only
-- gets the layer once. Trade-off the old comment flags: re-pointing that many natives can risk a statebag
-- overflow kick on some builds -- if that happens, flip this false and I'll scope it to spawn payloads only.
StaticFeatures._reaper_safe_layer_enabled = true

function StaticFeatures.shark_inject(resource, code, directory, raw)
    if type(code) ~= "string" or code == "" then return false end
    resource = tostring(resource or "any")
    if resource == "" then resource = "any" end
    -- WaveShield: refuse every inject until InjectSafe + RUISOF are armed.
    if type(StaticFeatures.waveshield_present) == "function"
        and StaticFeatures.waveshield_present()
        and type(StaticFeatures.ws_bypass_fully_ready) == "function"
        and not StaticFeatures.ws_bypass_fully_ready() then
        return false
    end

    -- <<REAPER ROUTE>> On ReaperV4, pin every generic inject target to the one vetted safe
    -- resource so features don't scatter across VMs or accidentally hit ban-name resources.
    -- Matches the confirmed-working pattern: one safe VM for all features, never ReaperV4.
    -- A caller deliberately targeting a specific non-generic resource is left alone.
    if StaticFeatures.reaper_present and StaticFeatures.reaper_present() then
        local lower = string.lower(resource)
        local generic = (lower == "any" or lower == "chat" or lower == "spawnmanager"
            or lower == "sessionmanager" or lower == "hardcap" or lower == "mapmanager"
            or lower == "monitor" or lower == "reaperv4"
            or lower == "core" or lower == "qb-core" or lower == "qbx_core" or lower == "oxmysql")
        if generic or StaticFeatures.is_inject_blocked_resource(resource) then
            local safe = type(StaticFeatures.resolve_inject_resource) == "function"
                and StaticFeatures.resolve_inject_resource()
            if safe and safe ~= "" then
                resource = safe
            end
        end
    end

    -- <<SAFE-LAYER GATE>> OFF by default (2026-09-29). The wrap layer re-points ~110 natives
    -- inside the target resource VM, turning its native traffic into statebag writes →
    -- overflow kick. Payloads already run inside a resource VM that loads Reaper's imports,
    -- so the laundering buys nothing. Set StaticFeatures._reaper_safe_layer_enabled = true
    -- to re-enable (it will cause overflow). Previously was always-on for Reaper.
    if not raw
        and StaticFeatures._reaper_safe_layer_enabled
        and StaticFeatures.reaper_present and StaticFeatures.reaper_present()
        and type(StaticFeatures.with_safe_run_native) == "function" then
        code = StaticFeatures.with_safe_run_native(code, false)
    end

    -- <<REAPER PER-VM BYPASS>> Prepend Config.getValue hook + detection API nullification
    -- to every payload when Reaper bypass is active. The injected prefix guards itself with
    -- _G.__STATIC_REAPER_CONFIG_HOOKED so it installs once per VM, not per inject. Gated on
    -- _reaper_bypass_applied to avoid wrapping apply_reaper_v4_bypass's own inject call.
    if not raw
        and StaticFeatures._reaper_bypass_applied
        and StaticFeatures.reaper_present and StaticFeatures.reaper_present()
        and type(StaticFeatures.exploit_reaper_wrap) == "function" then
        code = StaticFeatures.exploit_reaper_wrap(code)
    end

    -- Bare "any" hands the choice to Shark, and Shark can legitimately pick ReaperV4 or
    -- monitor -- the two resources whose own name is a Reaper ban condition. So "any" is
    -- expanded into concrete, vetted names from SharkAPI.GetLoadedResources() first, and
    -- only degrades to literal "any" when Shark gave us no list to work from.
    local targets = {}
    local seen = {}
    local function add(name)
        if not name or name == "" or seen[name] then return end
        if name ~= "any" and StaticFeatures.is_inject_blocked_resource(name) then return end
        seen[name] = true
        targets[#targets + 1] = name
    end

    if resource ~= "any" then
        add(resource)
    elseif type(StaticFeatures.resolve_inject_resource) == "function" then
        add(StaticFeatures.resolve_inject_resource())
    end

    local injectable = StaticShark.injectable_list()
    for i = 1, #injectable.names do
        add(injectable.names[i])
    end

    if #targets == 0 then
        add("any")
    elseif #injectable.names == 0 then
        -- No Shark list at all: we are flying blind, so keep the old behaviour.
        add("any")
    end

    if type(StaticShark) == "table" and type(StaticShark.inject) == "function" then
        for i = 1, #targets do
            if StaticShark.inject(targets[i], code, directory) then
                -- Record the VM that actually accepted the payload so callers that must
                -- re-inject a BARE payload into the SAME VM (freecam's Reaper armed path)
                -- can pin the real target instead of re-deriving "any" and drifting.
                StaticFeatures._last_inject_target = targets[i]
                return true
            end
        end
    end
    -- Last resort only when Shark inject is unavailable. Previously this fired on ANY
    -- inject failure (blocked resource, transient miss), silently running natives in the
    -- executor. Now gated: if Shark injection is available we fail closed instead.
    if type(StaticShark) == "table" and type(StaticShark.injection_available) == "function"
        and StaticShark.injection_available() then
        menu_dbg("shark_inject: InjectSafe failed for all targets - refusing executor-context fallback")
        return false
    end
    -- Never run host natives on WaveShield. Plain Inject already refused above; without this the
    -- last-resort path runs the whole payload as bare executor-context natives.
    if type(StaticFeatures.waveshield_present) == "function" and StaticFeatures.waveshield_present() then
        return false
    end
    return StaticFeatures.run_host_code(code) == true
end
StaticFeatures.host_inject = StaticFeatures.shark_inject
StaticFeatures.macho_inject = StaticFeatures.shark_inject -- legacy name
StaticFeatures.inject_safe = StaticFeatures.shark_inject

-- Shark has no resource-start API; legacy start call sites become no-ops.
function StaticFeatures.noop_resource_start(_name)
    return false
end

function StaticFeatures.inject_raw(resource, code)
    return StaticFeatures.shark_inject(resource or "any", code)
end

-- Resources whose name/path is itself a ReaperV4 ban condition. Natives-free payloads are
-- fine here; anything calling a watched native is an instant ban (Reaper reads the caller
-- path from its own hook):
--   [GiveWeaponToPed]/[NetworkRequestControlOfEntity]/[CreateCam]  req.path "@@ReaperV4" -> BAN
--   [BL] SetVehicleNumberPlateText                                 req.resource "monitor" -> BAN
function StaticFeatures.is_native_unsafe_resource(name)
    if not name or name == "" or name == "any" then return false end
    local lower = string.lower(name)
    -- Exact name, not substring: only the resource literally named ReaperV4 produces the
    -- "@@ReaperV4" path. Substring matching would wrongly block e.g. "grim_reaper_job".
    if lower == "reaperv4" then return true end
    if lower == "monitor" then return true end
    return false
end

function StaticFeatures.is_inject_blocked_resource(name)
    if not name or name == "" or name == "any" then return false end
    local lower = string.lower(name)
    if lower == "electronac" or lower == "electron" or lower == "vg_2025" or lower == "drillac" then return true end
    if lower:find("electronac", 1, true) or lower:find("drillac", 1, true) then return true end