--!strict local HttpService = game:GetService("HttpService") local ScriptEditorService = game:GetService("ScriptEditorService") local ChangeHistoryService = game:GetService("ChangeHistoryService") local Selection = game:GetService("Selection") local TweenService = game:GetService("TweenService") local MarketplaceService = game:GetService("MarketplaceService") local API = "https://deluxeaiapp.com" local BRAND_IMAGE_ID = "137002742748505" local TOOLBAR_IMAGE_ID = "" local TOKEN_KEY = "DeviceToken" local MAX_TREE_CHILDREN = 100 local MAX_FIND_VISITS = 2_000 local MAX_FIND_MATCHES = 30 local MAX_SEARCH_SESSIONS = 4 local MAX_SOURCE_BYTES = 20_000 local MAX_ACTION_BYTES = 12_000 local allowedScriptClasses: {[string]: boolean} = { Script = true, LocalScript = true, ModuleScript = true } local allowedCreateServices: {[string]: boolean} = { Workspace = true, ServerScriptService = true, ReplicatedStorage = true, StarterGui = true, StarterPlayerScripts = true, StarterCharacterScripts = true, } local serviceNames = { "Workspace", "ServerScriptService", "ServerStorage", "ReplicatedStorage", "StarterGui", "StarterPlayer", "StarterPack", "Lighting", "SoundService", "ReplicatedFirst", "Teams", "TextChatService", } local rootInstances: {Instance} = {} local rootByName: {[string]: Instance} = {} for _, serviceName in serviceNames do local ok, service = pcall(function() return game:GetService(serviceName) end) if ok and service then rootByName[serviceName] = service table.insert(rootInstances, service) end end local starterPlayer = rootByName.StarterPlayer if starterPlayer then for _, childName in { "StarterPlayerScripts", "StarterCharacterScripts" } do local child = starterPlayer:FindFirstChild(childName) if child then rootByName[childName] = child end end end local savedToken = plugin:GetSetting(TOKEN_KEY) local deviceToken: string? = if type(savedToken) == "string" then savedToken else nil local running = true local requestBusy = false local resolvedPlaceId = 0 local resolvedPlaceName: string? = nil task.spawn(function() local nextRefresh = 0 while running do local placeId = game.PlaceId if placeId ~= resolvedPlaceId then resolvedPlaceId = placeId resolvedPlaceName = nil nextRefresh = 0 end if deviceToken and placeId > 0 and os.clock() >= nextRefresh then nextRefresh = os.clock() + 60 local ok, info = pcall(function() return MarketplaceService:GetProductInfoAsync(placeId, Enum.InfoType.Asset) end) if running and game.PlaceId == placeId and ok and type(info) == "table" and type(info.Name) == "string" and info.Name:match("%S") then resolvedPlaceName = info.Name end end task.wait(1) end end) local statusLabel: TextLabel local apiKeyInput: TextBox local apiKeyCaption: TextLabel local apiKeyField: Frame local connectButton: TextButton local disconnectButton: TextButton local statusDot: Frame local loadingPanel: CanvasGroup local loadingSpinner: Frame local loadingGradient: UIGradient local spinnerTween: any = nil local glowTween: any = nil local connectedPanel: CanvasGroup local subtitleLabel: TextLabel local statePill: Frame local statePillDot: Frame local loadingText: TextLabel local connectedTitle: TextLabel local connectedSubtitle: TextLabel local connectionState = "" local statusKey = "" local savedLanguage = plugin:GetSetting("Language") local currentLanguage = if savedLanguage == "en" then "en" else "ru" local toolbar = plugin:CreateToolbar("Deluxe AI") local toolbarButton = toolbar:CreateButton("DeluxeAI_Open", "Open Deluxe AI", if TOOLBAR_IMAGE_ID ~= "" then "rbxassetid://" .. TOOLBAR_IMAGE_ID else "", "Deluxe AI") toolbarButton.ClickableWhenViewportHidden = true local widget = plugin:CreateDockWidgetPluginGuiAsync( "DeluxeAI_Studio", DockWidgetPluginGuiInfo.new(Enum.InitialDockState.Right, false, false, 370, 500, 320, 460) ) widget.Title = "Deluxe Studio" local colors = { background = Color3.fromRGB(0, 0, 0), text = Color3.fromRGB(255, 255, 255), muted = Color3.fromRGB(174, 174, 174), line = Color3.fromRGB(72, 72, 72), connected = Color3.fromRGB(75, 222, 160), connecting = Color3.fromRGB(247, 186, 94), disconnected = Color3.fromRGB(241, 113, 126), } local copy: {[string]: {[string]: string}} = { ru = { badgeDisconnected = "Не подключено", badgeConnecting = "Устанавливаем соединение", apiKeyCaption = "API-КЛЮЧ ПРОЕКТА", apiKeyPlaceholder = "Вставь ключ проекта", connect = "Подключиться", disconnect = "Отключиться", loading = "Подключаем Studio...", connectedTitle = "Studio подключена", connectedSubtitle = "Соединение активно", invalidKey = "Ключ выглядит неверно. Скопируй ключ проекта на сайте.", connecting = "Подключаюсь к сайту…", invalidApiKey = "Ключ недействителен или отозван. Создай новый на сайте.", networkError = "Не удалось подключиться. Проверь интернет и разрешение HTTP в Studio.", connectFailed = "Не удалось подключиться. Проверь ключ и попробуй ещё раз.", disconnected = "Studio отключена на этом компьютере.", linking = "Связываюсь с сайтом…", revoked = "Ключ отключён или отозван. Создай ключ на сайте и подключи плагин заново.", retrying = "Нет связи с сайтом. Повторяю подключение…", planApplied = "План применён в Studio.", planFailed = "Studio не применила план. Проверь выбранный скрипт и состояние проекта.", }, en = { badgeDisconnected = "Not connected", badgeConnecting = "Establishing connection", apiKeyCaption = "PROJECT API KEY", apiKeyPlaceholder = "Paste your project key", connect = "Connect", disconnect = "Disconnect", loading = "Connecting Studio...", connectedTitle = "Studio connected", connectedSubtitle = "Connection active", invalidKey = "This key does not look valid. Copy the project key from the website.", connecting = "Connecting to the website...", invalidApiKey = "Key is invalid or revoked. Create a new key on the website.", networkError = "Could not connect. Check your internet and Studio HTTP permission.", connectFailed = "Could not connect. Check the key and try again.", disconnected = "Studio disconnected on this computer.", linking = "Connecting to the website...", revoked = "Key disabled or revoked. Create a new key on the website and reconnect.", retrying = "Website connection lost. Retrying...", planApplied = "Plan applied in Studio.", planFailed = "Studio could not apply the plan. Check the selected script and project state.", }, } local function tr(key: string): string return (copy[currentLanguage] or copy.ru)[key] or "" end local function create(className: string, parent: Instance, properties: {[string]: any}): any local instance = Instance.new(className) for name, value in pairs(properties) do (instance :: any)[name] = value end instance.Parent = parent return instance end local root = create("Frame", widget, { Name = "Content", Size = UDim2.fromScale(1, 1), BackgroundColor3 = colors.background, BorderSizePixel = 0, }) :: Frame local languageSwitch = create("Frame", root, { Name = "LanguageSwitch", Position = UDim2.new(1, -112, 0, 20), Size = UDim2.fromOffset(94, 30), BackgroundColor3 = Color3.fromRGB(24, 24, 26), BorderSizePixel = 0, }) :: Frame create("UICorner", languageSwitch, { CornerRadius = UDim.new(1, 0) }) create("UIStroke", languageSwitch, { Color = colors.line, Thickness = 1, Transparency = 0.35 }) local languageThumb = create("Frame", languageSwitch, { Name = "ActiveLanguage", Position = UDim2.fromOffset(3, 3), Size = UDim2.fromOffset(43, 24), BackgroundColor3 = colors.text, BorderSizePixel = 0, }) :: Frame create("UICorner", languageThumb, { CornerRadius = UDim.new(1, 0) }) local ruButton = create("TextButton", languageSwitch, { Name = "Russian", Position = UDim2.fromOffset(3, 3), Size = UDim2.fromOffset(43, 24), BackgroundTransparency = 1, Text = "RU", Font = Enum.Font.BuilderSansBold, TextSize = 11, }) :: TextButton local enButton = create("TextButton", languageSwitch, { Name = "English", Position = UDim2.fromOffset(48, 3), Size = UDim2.fromOffset(43, 24), BackgroundTransparency = 1, Text = "EN", Font = Enum.Font.BuilderSansBold, TextSize = 11, }) :: TextButton create("ImageLabel", root, { Name = "BrandImage", AnchorPoint = Vector2.new(0.5, 0), Position = UDim2.new(0.5, 0, 0, 75), Size = UDim2.new(1, -20, 0, 110), BackgroundTransparency = 1, Image = if BRAND_IMAGE_ID ~= "" then "rbxassetid://" .. BRAND_IMAGE_ID else "", ScaleType = Enum.ScaleType.Fit, Visible = BRAND_IMAGE_ID ~= "", }) local logo = create("Frame", root, { Name = "Logo", AnchorPoint = Vector2.new(0.5, 0), Position = UDim2.new(0.5, -108, 0, 91), Size = UDim2.fromOffset(68, 68), BackgroundColor3 = colors.background, BorderSizePixel = 0, Visible = BRAND_IMAGE_ID == "", }) :: Frame create("UICorner", logo, { CornerRadius = UDim.new(0, 18) }) create("UIStroke", logo, { Color = colors.text, Thickness = 1.5, Transparency = 0.15 }) create("TextLabel", logo, { Size = UDim2.fromScale(1, 1), BackgroundTransparency = 1, Text = "DA", TextColor3 = colors.text, Font = Enum.Font.BuilderSansBold, TextSize = 27, }) create("TextLabel", root, { Name = "Title", AnchorPoint = Vector2.new(0.5, 0), Position = UDim2.new(0.5, -28, 0, 101), Size = UDim2.new(0, 180, 0, 48), BackgroundTransparency = 1, Text = "Deluxe Studio", TextColor3 = colors.text, Font = Enum.Font.BuilderSansBold, TextSize = 23, TextXAlignment = Enum.TextXAlignment.Left, Visible = BRAND_IMAGE_ID == "", }) statePill = create("Frame", root, { Name = "ConnectionBadge", AnchorPoint = Vector2.new(0.5, 0), Position = UDim2.new(0.5, 0, 0, 193), Size = UDim2.fromOffset(212, 30), BackgroundColor3 = Color3.fromRGB(18, 18, 18), BorderSizePixel = 0, }) :: Frame create("UICorner", statePill, { CornerRadius = UDim.new(1, 0) }) statePillDot = create("Frame", statePill, { Position = UDim2.fromOffset(11, 10), Size = UDim2.fromOffset(9, 9), BackgroundColor3 = colors.disconnected, BorderSizePixel = 0, }) :: Frame create("UICorner", statePillDot, { CornerRadius = UDim.new(1, 0) }) subtitleLabel = create("TextLabel", statePill, { Name = "ConnectionBadgeText", Position = UDim2.fromOffset(29, 0), Size = UDim2.new(1, -38, 1, 0), BackgroundTransparency = 1, Text = "Не подключено", TextColor3 = colors.text, Font = Enum.Font.BuilderSansMedium, TextSize = 12, TextXAlignment = Enum.TextXAlignment.Left, }) :: TextLabel apiKeyCaption = create("TextLabel", root, { Name = "ApiKeyCaption", AnchorPoint = Vector2.new(0.5, 0), Position = UDim2.new(0.5, 0, 0, 237), Size = UDim2.new(1, -44, 0, 18), BackgroundTransparency = 1, Text = "API-КЛЮЧ ПРОЕКТА", TextColor3 = colors.muted, Font = Enum.Font.BuilderSansMedium, TextSize = 11, TextXAlignment = Enum.TextXAlignment.Left, }) :: TextLabel apiKeyField = create("Frame", root, { Name = "ApiKeyField", AnchorPoint = Vector2.new(0.5, 0), Position = UDim2.new(0.5, 0, 0, 259), Size = UDim2.new(1, -40, 0, 51), BackgroundColor3 = Color3.fromRGB(16, 16, 18), BorderSizePixel = 0, }) :: Frame create("UICorner", apiKeyField, { CornerRadius = UDim.new(0, 12) }) create("UIStroke", apiKeyField, { Color = colors.text, Thickness = 1, Transparency = 0.68 }) local apiKeyPlaceholder = create("TextLabel", apiKeyField, { Name = "Placeholder", Position = UDim2.fromOffset(16, 0), Size = UDim2.new(1, -32, 1, 0), BackgroundTransparency = 1, Text = "Вставь ключ проекта", TextColor3 = colors.muted, Font = Enum.Font.BuilderSansMedium, TextSize = 15, TextXAlignment = Enum.TextXAlignment.Left, }) :: TextLabel apiKeyInput = create("TextBox", apiKeyField, { Name = "ApiKey", Position = UDim2.fromOffset(16, 0), Size = UDim2.new(1, -32, 1, 0), BackgroundTransparency = 1, ClearTextOnFocus = false, PlaceholderText = "", Text = "", TextColor3 = colors.text, Font = Enum.Font.BuilderSansMedium, TextSize = 15, TextXAlignment = Enum.TextXAlignment.Left, }) :: TextBox local inputFocused = false apiKeyInput.Focused:Connect(function() inputFocused = true TweenService:Create(apiKeyPlaceholder, TweenInfo.new(0.2), { TextTransparency = 1 }):Play() end) apiKeyInput.FocusLost:Connect(function() inputFocused = false if apiKeyInput.Text == "" then TweenService:Create(apiKeyPlaceholder, TweenInfo.new(0.2), { TextTransparency = 0 }):Play() end end) apiKeyInput:GetPropertyChangedSignal("Text"):Connect(function() if apiKeyInput.Text ~= "" then apiKeyPlaceholder.TextTransparency = 1 elseif not inputFocused then TweenService:Create(apiKeyPlaceholder, TweenInfo.new(0.2), { TextTransparency = 0 }):Play() end end) connectButton = create("TextButton", root, { Name = "Connect", AnchorPoint = Vector2.new(0.5, 0), Position = UDim2.new(0.5, 0, 0, 326), Size = UDim2.new(1, -40, 0, 50), BackgroundColor3 = colors.text, BorderSizePixel = 0, Text = "Подключиться", TextColor3 = colors.background, Font = Enum.Font.BuilderSansBold, TextSize = 15, }) :: TextButton create("UICorner", connectButton, { CornerRadius = UDim.new(0, 12) }) disconnectButton = create("TextButton", root, { Name = "Disconnect", AnchorPoint = Vector2.new(0.5, 0), Position = UDim2.new(0.5, 0, 0, 316), Size = UDim2.new(1, -40, 0, 50), BackgroundColor3 = colors.text, BorderSizePixel = 0, Text = "Отключиться", TextColor3 = colors.background, Font = Enum.Font.BuilderSansBold, TextSize = 15, }) :: TextButton create("UICorner", disconnectButton, { CornerRadius = UDim.new(0, 12) }) disconnectButton.MouseEnter:Connect(function() TweenService:Create(disconnectButton, TweenInfo.new(0.16), { BackgroundColor3 = Color3.fromRGB(224, 224, 224) }):Play() end) disconnectButton.MouseLeave:Connect(function() TweenService:Create(disconnectButton, TweenInfo.new(0.16), { BackgroundColor3 = colors.text }):Play() end) loadingPanel = create("CanvasGroup", root, { Name = "Loading", AnchorPoint = Vector2.new(0.5, 0), Position = UDim2.new(0.5, 0, 0, 255), Size = UDim2.new(1, -40, 0, 105), BackgroundTransparency = 1, GroupTransparency = 1, Visible = false, }) :: CanvasGroup loadingSpinner = create("Frame", loadingPanel, { AnchorPoint = Vector2.new(0.5, 0), Position = UDim2.new(0.5, 0, 0, 4), Size = UDim2.fromOffset(38, 38), BackgroundTransparency = 1, }) :: Frame create("UICorner", loadingSpinner, { CornerRadius = UDim.new(1, 0) }) local spinnerStroke = create("UIStroke", loadingSpinner, { Color = colors.connecting, Thickness = 2 }) loadingGradient = create("UIGradient", spinnerStroke, { Transparency = NumberSequence.new({ NumberSequenceKeypoint.new(0, 0), NumberSequenceKeypoint.new(1, 1) }), }) :: UIGradient loadingText = create("TextLabel", loadingPanel, { Position = UDim2.new(0, 0, 0, 55), Size = UDim2.new(1, 0, 0, 28), BackgroundTransparency = 1, Text = "Подключаем Studio...", TextColor3 = colors.text, Font = Enum.Font.BuilderSansMedium, TextSize = 14, }) :: TextLabel connectedPanel = create("CanvasGroup", root, { Name = "Connected", AnchorPoint = Vector2.new(0.5, 0), Position = UDim2.new(0.5, 0, 0, 224), Size = UDim2.new(1, -40, 0, 76), BackgroundColor3 = Color3.fromRGB(8, 24, 19), BorderSizePixel = 0, GroupTransparency = 1, Visible = false, }) :: CanvasGroup create("UICorner", connectedPanel, { CornerRadius = UDim.new(0, 14) }) create("UIStroke", connectedPanel, { Color = colors.connected, Thickness = 1, Transparency = 0.4 }) local statusGlow = create("Frame", connectedPanel, { Position = UDim2.fromOffset(13, 22), Size = UDim2.fromOffset(22, 22), BackgroundColor3 = colors.connected, BackgroundTransparency = 0.83, BorderSizePixel = 0, }) :: Frame create("UICorner", statusGlow, { CornerRadius = UDim.new(1, 0) }) statusDot = create("Frame", connectedPanel, { Position = UDim2.fromOffset(19, 28), Size = UDim2.fromOffset(10, 10), BackgroundColor3 = colors.connected, BorderSizePixel = 0, }) :: Frame create("UICorner", statusDot, { CornerRadius = UDim.new(1, 0) }) connectedTitle = create("TextLabel", connectedPanel, { Position = UDim2.fromOffset(44, 12), Size = UDim2.new(1, -58, 0, 27), BackgroundTransparency = 1, Text = "Studio подключена", TextColor3 = colors.text, Font = Enum.Font.BuilderSansBold, TextSize = 15, TextXAlignment = Enum.TextXAlignment.Left, }) :: TextLabel connectedSubtitle = create("TextLabel", connectedPanel, { Position = UDim2.fromOffset(44, 38), Size = UDim2.new(1, -58, 0, 20), BackgroundTransparency = 1, Text = "Соединение активно", TextColor3 = colors.connected, Font = Enum.Font.BuilderSansMedium, TextSize = 12, TextXAlignment = Enum.TextXAlignment.Left, }) :: TextLabel statusLabel = create("TextLabel", root, { Name = "Status", AnchorPoint = Vector2.new(0.5, 0), Position = UDim2.new(0.5, 0, 0, 390), Size = UDim2.new(1, -44, 0, 45), BackgroundTransparency = 1, Text = "", TextColor3 = colors.muted, Font = Enum.Font.BuilderSans, TextSize = 12, TextWrapped = true, TextXAlignment = Enum.TextXAlignment.Center, TextYAlignment = Enum.TextYAlignment.Top, }) :: TextLabel local function updateLanguageSwitch(animated: boolean) local activeRu = currentLanguage == "ru" local offset = if activeRu then 3 else 48 local position = UDim2.fromOffset(offset, 3) local ruColor = if activeRu then colors.background else colors.muted local enColor = if activeRu then colors.muted else colors.background if animated then local info = TweenInfo.new(0.24, Enum.EasingStyle.Quad, Enum.EasingDirection.Out) TweenService:Create(languageThumb, info, { Position = position }):Play() TweenService:Create(ruButton, info, { TextColor3 = ruColor }):Play() TweenService:Create(enButton, info, { TextColor3 = enColor }):Play() else languageThumb.Position = position ruButton.TextColor3 = ruColor enButton.TextColor3 = enColor end end local function applyLanguage(animated: boolean) apiKeyCaption.Text = tr("apiKeyCaption") apiKeyPlaceholder.Text = tr("apiKeyPlaceholder") connectButton.Text = tr("connect") disconnectButton.Text = tr("disconnect") loadingText.Text = tr("loading") connectedTitle.Text = tr("connectedTitle") connectedSubtitle.Text = tr("connectedSubtitle") local badgeKey = if connectionState == "connecting" then "badgeConnecting" else "badgeDisconnected" subtitleLabel.Text = tr(badgeKey) statusLabel.Text = if statusKey == "" then "" else tr(statusKey) updateLanguageSwitch(animated) end local function setStatus(key: string) statusKey = key statusLabel.Text = if key == "" then "" else tr(key) statusLabel.TextColor3 = if connectionState == "connecting" then colors.text elseif key ~= "" then colors.disconnected else colors.muted end applyLanguage(false) local function setLanguage(language: string) if currentLanguage == language then return end currentLanguage = language plugin:SetSetting("Language", language) applyLanguage(true) end ruButton.Activated:Connect(function() setLanguage("ru") end) enButton.Activated:Connect(function() setLanguage("en") end) for _, button in { ruButton, enButton } do button.MouseEnter:Connect(function() if (button == ruButton and currentLanguage ~= "ru") or (button == enButton and currentLanguage ~= "en") then TweenService:Create(button, TweenInfo.new(0.16), { TextColor3 = colors.text }):Play() end end) button.MouseLeave:Connect(function() updateLanguageSwitch(true) end) end languageSwitch.MouseEnter:Connect(function() TweenService:Create(languageSwitch, TweenInfo.new(0.16), { BackgroundColor3 = Color3.fromRGB(34, 34, 36) }):Play() end) languageSwitch.MouseLeave:Connect(function() TweenService:Create(languageSwitch, TweenInfo.new(0.16), { BackgroundColor3 = Color3.fromRGB(24, 24, 26) }):Play() end) local function showConnectionState(state: string) if connectionState == state then return end connectionState = state if spinnerTween then spinnerTween:Cancel(); spinnerTween = nil end if glowTween then glowTween:Cancel(); glowTween = nil end apiKeyField.Visible = state == "disconnected" apiKeyCaption.Visible = state == "disconnected" connectButton.Visible = state == "disconnected" loadingPanel.Visible = state == "connecting" connectedPanel.Visible = state == "connected" disconnectButton.Visible = state == "connected" statePill.Visible = state ~= "connected" statusLabel.Visible = state ~= "connected" local badgeKey = if state == "connecting" then "badgeConnecting" else "badgeDisconnected" subtitleLabel.Text = tr(badgeKey) statePillDot.BackgroundColor3 = if state == "connecting" then colors.connecting else colors.disconnected statusLabel.TextColor3 = if state == "connecting" then colors.text elseif statusKey ~= "" then colors.disconnected else colors.muted if state == "connecting" then loadingPanel.GroupTransparency = 1 TweenService:Create(loadingPanel, TweenInfo.new(0.28, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), { GroupTransparency = 0 }):Play() loadingGradient.Rotation = 0 spinnerTween = TweenService:Create(loadingGradient, TweenInfo.new(1.1, Enum.EasingStyle.Linear, Enum.EasingDirection.InOut, -1), { Rotation = 360 }) spinnerTween:Play() elseif state == "connected" then connectedPanel.GroupTransparency = 1 TweenService:Create(connectedPanel, TweenInfo.new(0.45, Enum.EasingStyle.Quad, Enum.EasingDirection.Out), { GroupTransparency = 0 }):Play() statusGlow.Position = UDim2.fromOffset(13, 22) statusGlow.Size = UDim2.fromOffset(22, 22) statusGlow.BackgroundTransparency = 0.83 glowTween = TweenService:Create(statusGlow, TweenInfo.new(1.5, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut, -1, true), { Position = UDim2.fromOffset(10, 19), Size = UDim2.fromOffset(28, 28), BackgroundTransparency = 0.94, }) glowTween:Play() statusDot.Size = UDim2.fromOffset(4, 4) TweenService:Create(statusDot, TweenInfo.new(0.35, Enum.EasingStyle.Back, Enum.EasingDirection.Out), { Size = UDim2.fromOffset(10, 10) }):Play() end end local function clearDeviceToken(status: string) deviceToken = nil plugin:SetSetting(TOKEN_KEY, nil) setStatus(status) showConnectionState("disconnected") end local function apiRequest(path: string, method: string, body: any, bearer: string?): (any?, string?) local headers: {[string]: string} = { ["Content-Type"] = "application/json", Accept = "application/json" } if bearer then headers.Authorization = "Bearer " .. bearer end local ok, response = pcall(function() return HttpService:RequestAsync({ Url = API .. path, Method = method, Headers = headers, Body = HttpService:JSONEncode(body or {}), }) end) if not ok then return nil, "network_error" end local decoded: any = nil if response.Body and response.Body ~= "" then local decodeOk, value = pcall(function() return HttpService:JSONDecode(response.Body) end) if decodeOk then decoded = value end end if response.StatusCode == 401 and bearer and bearer == deviceToken then clearDeviceToken("revoked") end if not response.Success then local reason = if type(decoded) == "table" and type(decoded.error) == "string" then decoded.error else "http_error" return nil, reason end return decoded, nil end local function hasHiddenUnicode(value: string): boolean local ok, found = pcall(function() for _, codepoint in utf8.codes(value) do if (codepoint >= 0x200B and codepoint <= 0x200F) or (codepoint >= 0x202A and codepoint <= 0x202E) or (codepoint >= 0x2060 and codepoint <= 0x206F) or codepoint == 0xFEFF then return true end end return false end) return not ok or found == true end local secretMarkers = { "webhook", "api_key", "api-key", "apikey", "client_secret", "access_token", "refresh_token", "secret", "password", "bearer", "private key", "-----begin", "sk-", "ghp_", "gho_", "ghu_", "ghs_", "akia" } local function looksLikeSecret(source: string): boolean local lowered = string.lower(source) for _, marker in secretMarkers do if string.find(lowered, marker, 1, true) then return true end end return false end local idByInstance: {[Instance]: string} = setmetatable({}, { __mode = "k" }) :: any local instanceById: {[string]: Instance} = {} local instanceIdOrder: {string} = {} local MAX_KNOWN_INSTANCES = 50_000 local searches: {[string]: any} = {} local searchOrder: {string} = {} local function nodeFor(instance: Instance): {[string]: any} local id = idByInstance[instance] if not id or instanceById[id] ~= instance then id = HttpService:GenerateGUID(false) idByInstance[instance] = id instanceById[id] = instance table.insert(instanceIdOrder, id) if #instanceIdOrder > MAX_KNOWN_INSTANCES then local expiredId = table.remove(instanceIdOrder, 1) local expiredInstance = instanceById[expiredId] if expiredInstance then idByInstance[expiredInstance] = nil end instanceById[expiredId] = nil end end local pathOk, fullName = pcall(function() return instance:GetFullName() end) local childrenOk, children = pcall(function() return instance:GetChildren() end) return { id = id, name = string.sub(instance.Name, 1, 100), className = instance.ClassName, path = string.sub(if pathOk then fullName else instance.Name, 1, 240), hasChildren = childrenOk and #children > 0, isScript = instance:IsA("LuaSourceContainer"), } end local function getKnownInstance(id: any): Instance? if type(id) ~= "string" or #id > 64 then return nil end local instance = instanceById[id] if instance and instance:IsDescendantOf(game) then return instance end instanceById[id] = nil return nil end local function listServices(): {[string]: any} local nodes = {} for _, instance in rootInstances do table.insert(nodes, nodeFor(instance)) end return { nodes = nodes } end local function listChildren(id: any, offset: any): {[string]: any} local parent = getKnownInstance(id) if not parent then return { nodes = {}, error = "object_not_found" } end local ok, children = pcall(function() return parent:GetChildren() end) if not ok then return { nodes = {}, error = "children_unavailable" } end local nodes = {} local start = if type(offset) == "number" and offset >= 0 and offset % 1 == 0 then math.min(offset, #children) else 0 local last = math.min(#children, start + MAX_TREE_CHILDREN) for index = start + 1, last do table.insert(nodes, nodeFor(children[index])) end return { nodes = nodes, truncated = last < #children, nextOffset = if last < #children then last else nil } end local function findInstances(query: any, className: any, cursor: any): {[string]: any} if type(query) ~= "string" then return { matches = {}, truncated = false } end local needle = string.lower(string.sub(string.gsub(query, "^%s*(.-)%s*$", "%1"), 1, 100)) if needle == "" then return { matches = {}, truncated = false } end local classFilter = if type(className) == "string" then string.sub(className, 1, 50) else "" local state = if type(cursor) == "string" then searches[cursor] else nil if cursor and (not state or state.needle ~= needle or state.classFilter ~= classFilter) then return { matches = {}, error = "search_expired" } end if not state then cursor = HttpService:GenerateGUID(false) state = { needle = needle, classFilter = classFilter, stack = table.clone(rootInstances) } searches[cursor] = state table.insert(searchOrder, cursor) if #searchOrder > MAX_SEARCH_SESSIONS then searches[table.remove(searchOrder, 1)] = nil end end local stack = state.stack local matches = {} local visited = 0 while #stack > 0 and visited < MAX_FIND_VISITS and #matches < MAX_FIND_MATCHES do local instance = table.remove(stack) visited += 1 if string.find(string.lower(instance.Name), needle, 1, true) and (classFilter == "" or instance.ClassName == classFilter) then table.insert(matches, nodeFor(instance)) end local ok, children = pcall(function() return instance:GetChildren() end) if ok then for index = #children, 1, -1 do table.insert(stack, children[index]) end end if visited % 150 == 0 then task.wait() end end if #stack == 0 then searches[cursor] = nil end return { matches = matches, visited = visited, truncated = #stack > 0, cursor = if #stack > 0 then cursor else nil } end local function deleteInstances(ids: any): {[string]: any} if type(ids) ~= "table" or #ids < 1 or #ids > 20 then error("invalid_delete_request") end local requested: {Instance} = {} for _, id in ids do local instance = getKnownInstance(id) if not instance or not instance:IsDescendantOf(game) then error("object_not_available") end for _, root in rootInstances do if instance == root then error("service_delete_blocked") end end for _, root in rootByName do if instance == root then error("service_delete_blocked") end end table.insert(requested, instance) end local targets: {Instance} = {} for _, instance in requested do local covered = false for _, candidate in requested do if candidate ~= instance and candidate:IsAncestorOf(instance) then covered = true; break end end if not covered then table.insert(targets, instance) end end local recording = ChangeHistoryService:TryBeginRecording("DeluxeAI_DeleteObjects") if not recording then error("change_history_busy") end local originals: {{instance: Instance, parent: Instance}} = {} local ok = pcall(function() for _, instance in targets do local parent = instance.Parent if not parent then error("object_not_available") end table.insert(originals, { instance = instance, parent = parent }) instance.Parent = nil end end) if not ok then for index = #originals, 1, -1 do pcall(function() originals[index].instance.Parent = originals[index].parent end) end pcall(function() ChangeHistoryService:FinishRecording(recording, Enum.FinishRecordingOperation.Cancel) end) error("delete_failed") end local committed = pcall(function() ChangeHistoryService:FinishRecording(recording, Enum.FinishRecordingOperation.Commit) end) if not committed then for index = #originals, 1, -1 do pcall(function() originals[index].instance.Parent = originals[index].parent end) end pcall(function() ChangeHistoryService:FinishRecording(recording, Enum.FinishRecordingOperation.Cancel) end) error("delete_failed") end return { deleted = #targets } end local function readSource(id: any): {[string]: any} local instance = getKnownInstance(id) if not instance or not instance:IsA("LuaSourceContainer") or not allowedScriptClasses[instance.ClassName] then return { error = "script_not_found" } end local sourceOk, source = pcall(function() return ScriptEditorService:GetEditorSource(instance :: LuaSourceContainer) end) if not sourceOk or type(source) ~= "string" then sourceOk, source = pcall(function() return (instance :: LuaSourceContainer).Source end) end if not sourceOk or type(source) ~= "string" then return { error = "source_unavailable" } end if #source > MAX_SOURCE_BYTES then return { error = "source_too_large" } end if looksLikeSecret(source) then return { error = "secret_like_source_blocked" } end if hasHiddenUnicode(source) then return { error = "hidden_unicode_source_blocked" } end local node = nodeFor(instance) return { id = node.id, name = node.name, className = node.className, path = node.path, source = source } end local function resolveCreateParent(serviceName: any): Instance? if type(serviceName) ~= "string" or not allowedCreateServices[serviceName] then return nil end return rootByName[serviceName] end local function applyPlan(actions: any): {[string]: any} if type(actions) ~= "table" or #actions < 1 or #actions > 6 then return { applied = false, error = "invalid_plan" } end local totalBytes = 0 local updateAction: any = nil local createActions = {} for _, action in actions do if type(action) ~= "table" or type(action.source) ~= "string" or #action.source < 1 or #action.source > MAX_ACTION_BYTES or hasHiddenUnicode(action.source) then return { applied = false, error = "invalid_source" } end totalBytes += #action.source if totalBytes > 22_000 then return { applied = false, error = "plan_too_large" } end if action.type == "create_script" and allowedScriptClasses[action.className] and resolveCreateParent(action.service) and type(action.name) == "string" and #action.name >= 1 and #action.name <= 48 and not string.find(action.name, "[%c]") and not hasHiddenUnicode(action.name) then table.insert(createActions, action) elseif action.type == "update_selected_script" and #actions == 1 and type(action.targetId) == "string" and type(action.expectedSource) == "string" and #action.expectedSource <= MAX_SOURCE_BYTES then updateAction = action else return { applied = false, error = "unsupported_action" } end end if updateAction and #createActions > 0 then return { applied = false, error = "mixed_plan_unsupported" } end local recording = ChangeHistoryService:TryBeginRecording("DeluxeAI_StudioPlan") if not recording then return { applied = false, error = "change_history_busy" } end local created: {Instance} = {} local updateTarget: LuaSourceContainer? = nil local rollbackSource = "" local updateStarted = false local updated = false local failure = "apply_failed" local ok = pcall(function() if updateAction then local target = getKnownInstance(updateAction.targetId) local selection = Selection:Get() if not target or not target:IsA("LuaSourceContainer") or not allowedScriptClasses[target.ClassName] or #selection ~= 1 or selection[1] ~= target then error("Select the target script in Studio before applying.") end updateTarget = target :: LuaSourceContainer rollbackSource = updateAction.expectedSource local sourceChanged = false ScriptEditorService:UpdateSourceAsync(updateTarget, function(oldSource) if oldSource ~= updateAction.expectedSource then sourceChanged = true return nil end updateStarted = true return updateAction.source end) if sourceChanged then error("The selected script changed after the website built this plan.") end updated = true else for _, action in createActions do local parent = resolveCreateParent(action.service) if not parent then error("The target Roblox service is unavailable.") end local object = Instance.new(action.className) :: LuaSourceContainer object.Name = action.name if object:IsA("BaseScript") then object.Disabled = true end table.insert(created, object) object.Parent = parent ScriptEditorService:UpdateSourceAsync(object, function() return action.source end) end end end) if ok then local committed = pcall(function() ChangeHistoryService:FinishRecording(recording, Enum.FinishRecordingOperation.Commit) end) if committed then return { applied = true, created = #created, updated = updated, disabled = #created } end end local rollbackFailed = false for index = #created, 1, -1 do if not pcall(function() created[index]:Destroy() end) then rollbackFailed = true end end if updateStarted and updateTarget and updateTarget.Parent then local restoreSkipped = false local restored = pcall(function() ScriptEditorService:UpdateSourceAsync(updateTarget :: LuaSourceContainer, function(currentSource) if currentSource ~= updateAction.source then restoreSkipped = true return nil end return rollbackSource end) end) if not restored or restoreSkipped then rollbackFailed = true end end if not pcall(function() ChangeHistoryService:FinishRecording(recording, Enum.FinishRecordingOperation.Cancel) end) then rollbackFailed = true end return { applied = false, error = failure, rollbackFailed = rollbackFailed } end local function runCommand(command: any): any if type(command) ~= "table" or type(command.id) ~= "string" or type(command.type) ~= "string" then error("invalid_command") end local payload = if type(command.payload) == "table" then command.payload else {} if command.type == "list_services" then return listServices() end if command.type == "list_children" then return listChildren(payload.id, payload.offset) end if command.type == "find_instances" then return findInstances(payload.query, payload.className, payload.cursor) end if command.type == "get_instances" then local nodes = {} if type(payload.ids) ~= "table" or #payload.ids > 20 then error("invalid_objects") end for _, id in payload.ids do local instance = getKnownInstance(id) if instance then table.insert(nodes, nodeFor(instance)) end end return { nodes = nodes } end if command.type == "delete_instances" then return deleteInstances(payload.ids) end if command.type == "get_instance" then local instance = getKnownInstance(payload.id) return { node = if instance then nodeFor(instance) else nil } end if command.type == "read_source" then return readSource(payload.id) end if command.type == "apply_plan" then return applyPlan(payload.actions) end error("unsupported_command") end local function sendCommandResult(id: string, result: any?, errorMessage: string?, token: string) local body = if errorMessage then { id = id, error = errorMessage } else { id = id, result = result } return apiRequest("/api/studio/plugin/result", "POST", body, token) end local function connectWithApiKey() if requestBusy then return end local apiKey = string.gsub(apiKeyInput.Text, "%s+", "") if #apiKey ~= 52 or not string.match(apiKey, "^dai_live_[%w_-]+$") then setStatus("invalidKey") return end requestBusy = true connectButton.Active = false setStatus("connecting") showConnectionState("connecting") task.spawn(function() local result, requestError = apiRequest("/api/studio/plugin/connect", "POST", {}, apiKey) if result and type(result.token) == "string" and #result.token == 64 then deviceToken = result.token plugin:SetSetting(TOKEN_KEY, deviceToken) apiKeyInput.Text = "" setStatus("") showConnectionState("connected") else local errors = { invalid_api_key = "invalidApiKey", network_error = "networkError" } setStatus(errors[requestError or ""] or "connectFailed") showConnectionState("disconnected") end requestBusy = false connectButton.Active = true end) end connectButton.Activated:Connect(connectWithApiKey) disconnectButton.Activated:Connect(function() if requestBusy then return end local token = deviceToken clearDeviceToken("disconnected") if token then task.spawn(function() apiRequest("/api/studio/disconnect", "POST", {}, token) end) end end) toolbarButton.Click:Connect(function() widget.Enabled = not widget.Enabled end) if deviceToken then setStatus("linking") showConnectionState("connecting") else showConnectionState("disconnected") end local pendingResults: {{id: string, result: any?, error: string?}} = {} local completed: {[string]: {result: any?, error: string?}} = {} local completedOrder: {string} = {} local queueToken: string? = deviceToken task.spawn(function() local pollDelay = 0 while running do local token = deviceToken if token ~= queueToken then pendingResults = {} completed = {} completedOrder = {} queueToken = token end if token then local studioName = if game.PlaceId == resolvedPlaceId then resolvedPlaceName else nil local poll, pollError = apiRequest("/api/studio/plugin/poll", "POST", { studioName = studioName }, token) if deviceToken ~= token then pollDelay = 0 task.wait(0.1) continue end if poll and type(poll.commands) == "table" then pollDelay = 0 if statusKey == "linking" or statusKey == "retrying" then setStatus("") end showConnectionState("connected") for _, command in poll.commands do if deviceToken ~= token then break end if type(command) == "table" and type(command.id) == "string" then local cached = completed[command.id] if cached then table.insert(pendingResults, { id = command.id, result = cached.result, error = cached.error }) else local ok, result = pcall(runCommand, command) local errorMessage = if ok then nil else "command_failed" completed[command.id] = { result = if ok then result else nil, error = errorMessage } table.insert(completedOrder, command.id) if #completedOrder > 100 then completed[table.remove(completedOrder, 1)] = nil end table.insert(pendingResults, { id = command.id, result = if ok then result else nil, error = errorMessage }) if #pendingResults > 40 then table.remove(pendingResults, 1) end if command.type == "apply_plan" then setStatus(if ok and result.applied then "planApplied" else "planFailed") end end end end elseif pollError == "unauthorized" then clearDeviceToken("revoked") elseif pollError == "network_error" then setStatus("retrying") showConnectionState("connecting") pollDelay = math.min(math.max(pollDelay, 1) * 2, 15) elseif pollError and pollError ~= "unauthorized" then pollDelay = math.min(math.max(pollDelay, 1) * 2, 15) end for index = #pendingResults, 1, -1 do if deviceToken ~= token then break end local item = pendingResults[index] local result, resultError = sendCommandResult(item.id, item.result, item.error, token) if result or resultError == "unknown_command" or resultError == "invalid_studio_result" then table.remove(pendingResults, index) end end end task.wait(if deviceToken then math.max(pollDelay, 0.1) else 0.25) end end) plugin.Unloading:Connect(function() running = false end)