<roblox version="4">
  <Item class="ModuleScript" referent="0">
    <Properties>
      <string name="Name">LyretoBridge</string>
      <string name="Source"><![CDATA[--!strict
--[[
	LyretoBridge  ·  Roblox <-> Lyreto chat bridge  ·  v1.1.1
	Docs: https://lyreto.com/developers/bridge
	Works in Roblox and in Guts&Bolts games (same module, same calls).

	SERVER ONLY. Keep this ModuleScript in ServerScriptService.

	Setup (in a server Script in ServerScriptService). Best: keep the key as a secret, not in a script.
		local HttpService = game:GetService("HttpService")
		local LyretoBridge = require(game:GetService("ServerScriptService").LyretoBridge)
		LyretoBridge.Start({ ApiKey = HttpService:GetSecret("LyretoKey") })
	  Roblox: Creator Hub -> your experience -> Secrets -> add "LyretoKey" (domain lyreto.com); in Studio,
	          Game Settings -> Security -> Secrets.
	  Guts&Bolts: the game's Configure page on the website -> turn on Web requests -> add the secret "LyretoKey"
	          for lyreto.com. Anyone can host a Guts&Bolts game and read its scripts, so never type the key into a
	          script there: a secret stays on the Guts&Bolts server and the host never sees it.
	A plain string still works (Roblox): LyretoBridge.Start({ ApiKey = "lyb_..." }), or a ModuleScript
	ServerScriptService.LyretoBridgeConfig that returns { ApiKey = ... }, or a string attribute "LyretoApiKey" on
	ServerScriptService. With no key at all, Start() tries HttpService:GetSecret("LyretoKey") by itself.
	Never put a key in ReplicatedStorage, Workspace, StarterGui or any LocalScript: those are downloaded by players.

	Roblox: Game Settings -> Security -> "Allow HTTP Requests" must be ON.

	What it does
	  * Player chat (Player.Chatted) is filtered with TextService (GetNonChatStringForBroadcastAsync) and sent to
	    your linked Lyreto channel in small batches.
	  * Messages from the Lyreto channel are polled, links are stripped, and EVERY message is filtered with
	    TextService:FilterStringAsync + GetChatForUserAsync for each player before it is shown, as a system message
	    "[Lyreto] name: message". In a live game unfiltered text is never shown: if filtering fails or Roblox's
	    filter returns nothing, the message is not shown. In Roblox Studio (a test session only) the filter often
	    returns nothing, so there the line is shown unfiltered so you can see the bridge working.
	  * Debug = true prints every step to the Output window (server and client). Without it, a request Lyreto
	    refuses for good (400) still prints its reason once (at most one such warning every 30 s).
	  * Stays well under HttpService's 500 requests/minute per server (default budget 120/min for this module),
	    backs off on errors, and stops on an invalid key.
	  * Guts&Bolts: chat arrives already filtered by Guts&Bolts, Lyreto lines are shown with
	    TextChatService:DisplaySystemMessage (Guts&Bolts filters those too), long polls stay under its 10 s request
	    limit and the budget under its 120 requests/minute per server. Lyreto knows the requests come from
	    Guts&Bolts (its servers add X-GutsAndBolts-* headers) and shows those players with a GUTS&BOLTS tag.
]]

local HttpService = game:GetService("HttpService")
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local ServerScriptService = game:GetService("ServerScriptService")
local StarterPlayer = game:GetService("StarterPlayer")
local TextService = game:GetService("TextService");

export type Options = {
	ApiKey: any, -- a string "lyb_..." or a Secret from HttpService:GetSecret("LyretoKey")
	BaseUrl: string?, -- default "https://lyreto.com"
	Prefix: string?, -- default "[Lyreto]"
	SendPlayerChat: boolean?, -- default true
	ShowLyretoChat: boolean?, -- default true
	IgnoreCommands: boolean?, -- skip messages that start with "/" (default true)
	ShouldSend: ((player: Player, message: string) -> boolean)?, -- your own rule (e.g. skip team chat)
	PollWait: number?, -- long-poll seconds, 0..20 (default 10)
	MinPollGap: number?, -- seconds between polls (default 2)
	FlushInterval: number?, -- seconds between sends (default 1)
	RequestBudgetPerMinute: number?, -- this module's own cap (default 120, max 300)
	Color: Color3?, -- system message color (Roblox)
	Platform: string?, -- "Roblox" or "GutsAndBolts" (default: found by itself)
	Debug: boolean?,
}

local LyretoBridge = {}
LyretoBridge.Version = "1.1.1"
LyretoBridge.Platform = "Roblox" -- "GutsAndBolts" once Start() runs in a Guts&Bolts game

local REMOTE_NAME = "LyretoBridgeMessage"
local CLIENT_NAME = "LyretoBridgeClient"
local MAX_QUEUE = 50
local BATCH_MAX = 10
local TEXT_MAX = 300

local started = false
local stopped = false
local opts: Options = {}
local apiKey: any = "" -- a string or a Secret; never printed
local baseUrl = "https://lyreto.com"
local queue: { any } = {}
local requestTimes: { number } = {}
local remote: RemoteEvent? = nil
local connections: { RBXScriptConnection } = {}
local warnedHttpOff = false
local warnedSetup: { [string]: boolean } = {}

local function log(...: any)
	if opts.Debug then
		print("[LyretoBridge]", ...)
	end
end

local function warnOnce(msg: string)
	warn("[LyretoBridge] " .. msg)
end

-- Lyreto refused a request for good (400 and the like): say why even without Debug, once per distinct reason and
-- at most one warning every 30 s, so a broken setup can't flood the output.
local warnedRejects: { [string]: boolean } = {}
local warnedRejectCount = 0
local lastRejectWarn = -math.huge
local function warnRejected(what: string, status: number, data: any)
	local reason = tostring((type(data) == "table" and data.error) or ("HTTP " .. tostring(status)))
	local k = what .. ":" .. tostring(status) .. ":" .. reason
	if warnedRejects[k] or warnedRejectCount >= 10 or os.clock() - lastRejectWarn < 30 then
		return
	end
	warnedRejects[k] = true
	warnedRejectCount += 1
	lastRejectWarn = os.clock()
	warn("[LyretoBridge] Lyreto refused " .. what .. " (" .. tostring(status) .. "): " .. reason)
end

-- ------------------------------------------------------------------ platform + key
-- Guts&Bolts runs Lua 5.4 (Roblox runs Luau) and its RunService has no IsStudio/IsServer.
local function detectGutsAndBolts(): boolean
	if type(_VERSION) == "string" and _VERSION:sub(1, 5) == "Lua 5" then
		return true
	end
	local ok = pcall(function()
		return RunService:IsStudio()
	end)
	return not ok
end
local IS_GNB = detectGutsAndBolts()

-- The game's id for Lyreto. Roblox: the universe id (a number). Guts&Bolts: game.GameId is a number in newer games
-- and a text id like "game-a243aeed03" in older ones; Lyreto takes either (it locks G&B bridges by the game number
-- G&B puts in its X-GutsAndBolts-Game header). Anything else is left out.
local function apiId(v: any): any
	if not IS_GNB then
		return v
	end
	if type(v) == "number" then
		return v
	end
	if type(v) ~= "string" then
		return nil
	end
	if v:match("^%d+$") and #v <= 15 then
		return tonumber(v)
	end
	if #v >= 1 and #v <= 64 and v:match("^[%w_%-]+$") then
		return v
	end
	return nil
end

-- A Secret (Roblox and Guts&Bolts) can't be read or joined to text; it can only go in a request header.
local function isSecret(v: any): boolean
	if typeof(v) == "Secret" then
		return true
	end
	-- Guts&Bolts: a Secret is a table whose hidden metatable is the text "Secret" (its typeof may say "table").
	return type(v) == "table" and getmetatable(v) == "Secret"
end

local function keyLooksOk(v: any): boolean
	if isSecret(v) then
		return true
	end
	return type(v) == "string" and v:match("^lyb_%d+_[%w_%-]+$") ~= nil
end

-- The Authorization header: secret:AddPrefix("Bearer ") for a Secret, "Bearer " .. key for a string.
local function authHeader(key: any): any
	if isSecret(key) then
		return key:AddPrefix("Bearer ")
	end
	return "Bearer " .. tostring(key)
end

local function studioNow(): boolean
	if IS_GNB then
		return false
	end
	local ok, yes = pcall(function()
		return RunService:IsStudio()
	end)
	return ok and yes == true
end

-- ------------------------------------------------------------------ text helpers
local TLDS = {
	com = true, net = true, org = true, gg = true, io = true, co = true, me = true, ly = true, xyz = true, app = true,
	dev = true, tv = true, us = true, uk = true, de = true, ru = true, info = true, biz = true, link = true, site = true,
	online = true, store = true, shop = true, fun = true, live = true, club = true, pro = true, top = true, cc = true,
	to = true, be = true, ws = true, gl = true, gd = true, sh = true, click = true, win = true, vip = true, lol = true,
	chat = true, games = true, game = true, tk = true, ml = true, ga = true, cf = true, gq = true,
}

-- Removes URLs and bare domains (defense in depth: the Lyreto API already strips them).
local function stripUrls(s: string): string
	s = s:gsub("[Hh][Tt][Tt][Pp][Ss]?://%S+", "")
	s = s:gsub("[Ww][Ww][Ww]%.%S+", "")
	local replaceDomain: any = function(name: string, tld: string, rest: string): string
		if TLDS[tld:lower()] then
			return ""
		end
		return name .. "." .. tld .. rest
	end
	s = s:gsub("([%w%-]+)%.(%a%a+)(/?%S*)", replaceDomain)
	s = s:gsub("%s+", " ")
	s = s:gsub("^%s+", ""):gsub("%s+$", "")
	return s
end

local function clip(s: string, n: number): string
	if utf8.len(s) == nil then
		s = s:gsub("[\128-\255]", "")
	end
	if #s <= n then
		return s
	end
	local cut = utf8.offset(s, n) or n
	return s:sub(1, cut - 1)
end

local function cleanName(s: any): string
	if type(s) ~= "string" then
		return "someone"
	end
	local out = s:gsub("[%c<>]", ""):gsub("%s+", " ")
	out = clip(out, 32)
	if out == "" then
		return "someone"
	end
	return out
end

local function onlyHashes(s: string): boolean
	return s:gsub("[#%s]", "") == ""
end

-- ------------------------------------------------------------------ HTTP (own budget + backoff)
local function budgetWait()
	-- Guts&Bolts allows 120 web requests a minute per server: stay under it.
	local cap = math.clamp(opts.RequestBudgetPerMinute or 120, 10, 300)
	if IS_GNB then
		cap = math.clamp(opts.RequestBudgetPerMinute or 100, 10, 110)
	end
	while true do
		local now = os.clock()
		local keep = {}
		for _, t in ipairs(requestTimes) do
			if now - t < 60 then
				table.insert(keep, t)
			end
		end
		requestTimes = keep
		if #requestTimes < cap then
			table.insert(requestTimes, now)
			return
		end
		task.wait(1)
	end
end

type Response = { ok: boolean, status: number, data: any, err: string? }

local function request(method: string, path: string, body: any?): Response
	budgetWait()
	local req: any = {
		Url = baseUrl .. path,
		Method = method,
		Headers = {
			["Authorization"] = authHeader(apiKey),
			["Content-Type"] = "application/json",
			["Accept"] = "application/json",
		},
	}
	if body ~= nil then
		req.Body = HttpService:JSONEncode(body)
	end
	local ok, res = pcall(function()
		return HttpService:RequestAsync(req)
	end)
	if not ok then
		local msg = tostring(res)
		local low = msg:lower()
		if low:find("http requests are not enabled") or low:find("httpenabled") then
			if not warnedHttpOff then
				warnedHttpOff = true
				warnOnce("HTTP requests are off. Turn on Game Settings -> Security -> Allow HTTP Requests.")
			end
			return { ok = false, status = -2, data = nil, err = msg }
		end
		-- Set-up problems the game's owner has to fix (web requests off, the secret missing or for another
		-- site, a secret kept for Guts&Bolts game servers only): say so once, retry slowly.
		if low:find("web requests are off") or low:find("secret") or low:find("only goes to") or low:find("only works on") then
			if not warnedSetup[msg] then
				warnedSetup[msg] = true
				warnOnce("Can't reach Lyreto: " .. msg)
			end
			return { ok = false, status = -2, data = nil, err = msg }
		end
		return { ok = false, status = -1, data = nil, err = msg }
	end
	local data = nil
	if res.Body and #res.Body > 0 then
		local okJson, decoded = pcall(function()
			return HttpService:JSONDecode(res.Body)
		end)
		if okJson then
			data = decoded
		end
	end
	return { ok = res.Success, status = res.StatusCode, data = data, err = nil }
end

-- Returns seconds to wait after a failed request, or nil to stop the bridge.
local function failureDelay(r: Response, attempt: number): number?
	if r.status == 401 then
		warnOnce("Lyreto rejected the API key (rotated or deleted?). The bridge stopped. Make a new key in Server Settings -> Game Bridge.")
		return nil
	elseif r.status == 409 then
		-- e.g. a Roblox bridge's key used in a Guts&Bolts game (or the other way round)
		warnOnce(tostring(r.data and r.data.error or "This key is for a bridge on another platform.") .. " The bridge stopped.")
		return nil
	elseif r.status == 403 or r.status == 410 then
		warnOnce("This bridge is turned off or its channel is gone (" .. tostring(r.data and r.data.error or r.status) .. "). Retrying in 60 s.")
		return 60
	elseif r.status == 429 then
		local after = (r.data and tonumber(r.data.retry_after)) or 5
		return math.clamp(after, 1, 60)
	elseif r.status == 503 then
		return 30
	elseif r.status == -2 then
		return 60
	end
	return math.min(60, 2 ^ math.min(attempt, 6))
end

-- ------------------------------------------------------------------ outgoing (game -> Lyreto)
local function enqueue(player: Player, message: string)
	if stopped or opts.SendPlayerChat == false then
		return
	end
	if opts.IgnoreCommands ~= false and message:sub(1, 1) == "/" then
		return
	end
	if opts.ShouldSend then
		local okRule, allowed = pcall(opts.ShouldSend, player, message)
		if not okRule or not allowed then
			return
		end
	end
	-- Lyreto needs a real account id (Studio test players and guests have none).
	local userId = tonumber(player.UserId)
	if userId == nil or userId <= 0 then
		log("not sent: player", player.Name, "has no account id (test player or guest)")
		return
	end
	local filtered: any = nil
	if IS_GNB then
		-- Guts&Bolts hands scripts chat that already went through its own chat filter.
		filtered = message
	else
		-- Roblox's own filter first (what everyone would see in a broadcast), then send.
		local okF, f = pcall(function()
			local result = TextService:FilterStringAsync(message, player.UserId, Enum.TextFilterContext.PublicChat)
			return result:GetNonChatStringForBroadcastAsync()
		end)
		if not okF then
			return
		end
		filtered = f
	end
	if type(filtered) ~= "string" or filtered == "" or onlyHashes(filtered) then
		return
	end
	local text = clip(stripUrls(filtered), TEXT_MAX)
	if text == "" then
		return
	end
	if #queue >= MAX_QUEUE then
		table.remove(queue, 1)
	end
	-- On Guts&Bolts these hold its game id and user number; Lyreto tells by the X-GutsAndBolts-* headers.
	local jobId: any = game.JobId
	if type(jobId) ~= "string" or jobId == "" then
		jobId = nil
	end
	table.insert(queue, {
		universeId = apiId(game.GameId),
		placeId = apiId(game.PlaceId),
		jobId = jobId,
		robloxUserId = userId,
		robloxDisplayName = player.DisplayName or player.Name,
		robloxUsername = player.Name,
		text = text,
	})
end

local function flushLoop()
	local attempt = 0
	while not stopped do
		task.wait(math.max(0.5, opts.FlushInterval or 1))
		if #queue > 0 then
			local batch = {}
			for _ = 1, math.min(BATCH_MAX, #queue) do
				table.insert(batch, table.remove(queue, 1))
			end
			local r = request("POST", "/api/bridge/v1/messages", { messages = batch })
			if r.ok then
				attempt = 0
				log("sent", #batch)
			else
				attempt += 1
				-- put the batch back in front (oldest first) unless the server refused it for good
				if r.status == 400 or r.status == 413 or r.status == 422 then
					warnRejected("a chat batch", r.status, r.data)
				else
					for i = #batch, 1, -1 do
						table.insert(queue, 1, batch[i])
					end
					while #queue > MAX_QUEUE do
						table.remove(queue, #queue)
					end
				end
				local delay = failureDelay(r, attempt)
				if delay == nil then
					stopped = true
					break
				end
				log("send failed", r.status, r.err, "retry in", delay)
				task.wait(delay)
			end
		end
	end
end

-- ------------------------------------------------------------------ incoming (Lyreto -> game)
local function anyPlayer(): Player?
	local list = Players:GetPlayers()
	return list[1]
end

local function showLine(authorName: string, text: string)
	local clean = stripUrls(text)
	if clean == "" then
		return
	end
	local line = cleanName(authorName) .. ": " .. clip(clean, TEXT_MAX)
	local from = anyPlayer()
	if not from then
		log("not shown: no players in server")
		return -- nobody to show it to
	end
	log("lyreto msg:", line)
	local prefix = opts.Prefix or "[Lyreto]"
	if IS_GNB then
		-- Guts&Bolts puts the line in everyone's chat and runs it through its own chat filter first.
		local okS, err = pcall(function()
			game:GetService("TextChatService"):DisplaySystemMessage(prefix .. " " .. line)
		end)
		if okS then
			log("shown in chat")
		else
			log("not shown:", tostring(err))
		end
		return
	end
	local rem = remote
	if not rem then
		log("not shown: no RemoteEvent")
		return
	end
	local isStudio = studioNow()
	-- REQUIRED by Roblox: filter before displaying. Per recipient, so each player's age settings apply.
	local okF, result = pcall(function()
		return TextService:FilterStringAsync(line, from.UserId, Enum.TextFilterContext.PublicChat)
	end)
	if not okF or not result then
		log("filter failed:", tostring(result))
		if isStudio then
			-- Studio test only: show it unfiltered so you can see the bridge works. Live games always filter.
			for _, player in ipairs(Players:GetPlayers()) do
				rem:FireClient(player, prefix .. " " .. line)
			end
			log("studio: shown unfiltered for testing")
		else
			log("not shown (Roblox filter failed)")
		end
		return
	end
	for _, player in ipairs(Players:GetPlayers()) do
		local okU, shown = pcall(function()
			return (result :: any):GetChatForUserAsync(player.UserId)
		end)
		-- GetChatForUserAsync can error, return a non-string, or return "" (seen in real games): try the broadcast string.
		if not okU or type(shown) ~= "string" or shown == "" then
			local okB, b = pcall(function()
				return (result :: any):GetNonChatStringForBroadcastAsync()
			end)
			if okB and type(b) == "string" and b ~= "" then
				okU, shown = true, b
			end
		end
		if okU and type(shown) == "string" and shown ~= "" and not onlyHashes(shown) then
			rem:FireClient(player, prefix .. " " .. shown)
			log("shown to", player.Name)
		elseif isStudio then
			-- Studio test only: Roblox's filter often returns nothing in Studio. Live games always filter.
			rem:FireClient(player, prefix .. " " .. line)
			log("studio: filter returned nothing, shown unfiltered to", player.Name)
		else
			log("not shown to", player.Name, "(Roblox filter blocked it)")
		end
	end
end

local function pollLoop()
	local cursor: string? = nil
	local attempt = 0
	local waitS = math.clamp(opts.PollWait or 10, 0, 20)
	if IS_GNB then
		-- Guts&Bolts gives up on a web request after 10 seconds: keep the long poll shorter.
		waitS = math.clamp(opts.PollWait or 7, 0, 7)
	end
	while not stopped do
		if opts.ShowLyretoChat == false then
			task.wait(5)
			continue
		end
		if #Players:GetPlayers() == 0 then
			cursor = nil -- empty server: start fresh when someone joins
			task.wait(2)
			continue
		end
		local job: any = game.JobId
		if type(job) ~= "string" or job == "" then
			job = "studio"
		end
		local gid = apiId(game.GameId)
		local q = gid ~= nil and ("?universeId=" .. tostring(gid)) or "?"
		if not IS_GNB then
			-- (Guts&Bolts has no JobId: Lyreto tells its servers apart by the X-GutsAndBolts-* headers.)
			q = "?jobId=" .. HttpService:UrlEncode(job) .. "&universeId=" .. tostring(game.GameId)
		end
		if cursor then
			q ..= "&cursor=" .. cursor .. "&wait=" .. tostring(waitS)
		end
		local r = request("GET", "/api/bridge/v1/messages" .. q)
		if r.ok and type(r.data) == "table" then
			attempt = 0
			if type(r.data.cursor) == "string" then
				cursor = r.data.cursor
			end
			if type(r.data.messages) == "table" and #r.data.messages > 0 then
				log("got", #r.data.messages, "msg(s) from lyreto")
			end
			if type(r.data.messages) == "table" then
				for _, m in ipairs(r.data.messages) do
					if type(m) == "table" and type(m.text) == "string" then
						task.spawn(showLine, tostring(m.authorName or "someone"), m.text)
					end
				end
			end
			task.wait(math.max(1, opts.MinPollGap or 2))
		else
			attempt += 1
			if r.status == 400 then
				warnRejected("a poll", r.status, r.data)
			end
			local delay = failureDelay(r, attempt)
			if delay == nil then
				stopped = true
				break
			end
			log("poll failed", r.status, r.err, "retry in", delay)
			task.wait(delay)
		end
	end
end

-- ------------------------------------------------------------------ setup
-- The key: a Secret (HttpService:GetSecret("LyretoKey"), best) or a string "lyb_...". Never printed.
local function findKey(o: Options): any
	if isSecret(o.ApiKey) or (type(o.ApiKey) == "string" and o.ApiKey ~= "") then
		return o.ApiKey
	end
	local cfg = ServerScriptService:FindFirstChild("LyretoBridgeConfig")
	if cfg and cfg:IsA("ModuleScript") then
		local ok, value = pcall(require, cfg)
		if ok and type(value) == "table" then
			local k = (value :: any).ApiKey
			if isSecret(k) or (type(k) == "string" and k ~= "") then
				return k
			end
		end
	end
	local okA, attr = pcall(function()
		return ServerScriptService:GetAttribute("LyretoApiKey")
	end)
	if okA and type(attr) == "string" and attr ~= "" then
		return attr
	end
	-- Nothing given: try the secret "LyretoKey" (Roblox errors when there is none; that's fine here).
	local okS, secret = pcall(function()
		return HttpService:GetSecret("LyretoKey")
	end)
	if okS and isSecret(secret) then
		log("using the secret LyretoKey")
		return secret
	end
	return nil
end

local function installClient()
	local template = script:FindFirstChild(CLIENT_NAME)
	if not template then
		warnOnce("LyretoBridgeClient (LocalScript) is missing next to the module, so Lyreto messages can't be shown in chat. Use the .rbxmx from lyreto.com/developers/bridge.")
		return
	end
	local sps = StarterPlayer:FindFirstChildOfClass("StarterPlayerScripts")
	if sps and not sps:FindFirstChild(CLIENT_NAME) then
		local c = template:Clone()
		c:SetAttribute("LyretoColor", opts.Color or Color3.fromRGB(167, 139, 250))
		c:SetAttribute("LyretoDebug", opts.Debug == true)
		c.Parent = sps
	end
	-- players who joined before Start() ran
	for _, player in ipairs(Players:GetPlayers()) do
		local gui = player:FindFirstChildOfClass("PlayerGui")
		if gui and not gui:FindFirstChild("LyretoBridgeGui") then
			local holder = Instance.new("ScreenGui")
			holder.Name = "LyretoBridgeGui"
			holder.ResetOnSpawn = false
			local c = template:Clone()
			c:SetAttribute("LyretoColor", opts.Color or Color3.fromRGB(167, 139, 250))
			c:SetAttribute("LyretoDebug", opts.Debug == true)
			c.Parent = holder
			holder.Parent = gui
		end
	end
end

local function hookPlayer(player: Player)
	table.insert(connections, player.Chatted:Connect(function(message: string, recipient: Player?)
		if recipient ~= nil then
			return -- legacy whisper
		end
		task.spawn(enqueue, player, message)
	end))
end

function LyretoBridge.Start(o: Options?)
	if started then
		return
	end
	opts = o or {}
	if opts.Platform == "GutsAndBolts" then
		IS_GNB = true
	elseif opts.Platform == "Roblox" then
		IS_GNB = false
	end
	if not IS_GNB then
		assert(RunService:IsServer(), "[LyretoBridge] Start() must run on the server (a Script in ServerScriptService)")
	end
	local okWhere, exposed = pcall(function()
		return script:IsDescendantOf(ReplicatedStorage) or script:IsDescendantOf(workspace)
	end)
	if okWhere and exposed then
		warnOnce("Move the LyretoBridge module to ServerScriptService. Anything in ReplicatedStorage or Workspace is visible to players. Not starting.")
		return
	end
	local key = findKey(opts)
	if not keyLooksOk(key) then
		warnOnce("No API key. Best: LyretoBridge.Start({ ApiKey = HttpService:GetSecret(\"LyretoKey\") }) with the key saved as a secret named LyretoKey (or pass { ApiKey = \"lyb_...\" }). Get a key in your Lyreto server: Server Settings -> Game Bridge.")
		return
	end
	apiKey = key
	if type(opts.BaseUrl) == "string" and opts.BaseUrl ~= "" then
		baseUrl = (opts.BaseUrl :: string):gsub("/+$", "")
	end
	started = true
	stopped = false
	LyretoBridge.Platform = "Roblox"
	if IS_GNB then
		LyretoBridge.Platform = "GutsAndBolts"
	end

	if not IS_GNB then
		-- Roblox: Lyreto lines reach players through a RemoteEvent + LocalScript (filtered per player first).
		-- Guts&Bolts shows them with TextChatService:DisplaySystemMessage instead (see showLine).
		local existing = ReplicatedStorage:FindFirstChild(REMOTE_NAME)
		if existing and existing:IsA("RemoteEvent") then
			remote = existing
		else
			local ev = Instance.new("RemoteEvent")
			ev.Name = REMOTE_NAME
			ev.Parent = ReplicatedStorage
			remote = ev
		end
		-- clients never send through this remote; ignore anything they try
		table.insert(connections, (remote :: RemoteEvent).OnServerEvent:Connect(function() end))

		installClient()
	end
	for _, player in ipairs(Players:GetPlayers()) do
		hookPlayer(player)
	end
	table.insert(connections, Players.PlayerAdded:Connect(hookPlayer))

	task.spawn(flushLoop)
	task.spawn(pollLoop)
	log("started", LyretoBridge.Version, LyretoBridge.Platform, isSecret(apiKey) and "(key from a Secret)" or "(key from a string)")
end

function LyretoBridge.Stop()
	stopped = true
	started = false
	for _, c in ipairs(connections) do
		c:Disconnect()
	end
	connections = {}
	queue = {}
end

-- For tests / custom chat systems: send one line as a player (still filtered first).
function LyretoBridge.SendAs(player: Player, message: string)
	task.spawn(enqueue, player, message)
end

-- exposed for unit tests
LyretoBridge._stripUrls = stripUrls
LyretoBridge._authHeader = authHeader
LyretoBridge._isSecret = isSecret
LyretoBridge._keyLooksOk = keyLooksOk

return LyretoBridge
]]></string>
    </Properties>
    <Item class="LocalScript" referent="1">
      <Properties>
        <string name="Name">LyretoBridgeClient</string>
        <string name="Source"><![CDATA[--[[
	LyretoBridgeClient  ·  shows Lyreto channel messages in the chat window as system messages.
	The server module (LyretoBridge) already filtered every line with TextService for this player before sending.
	Installed automatically by LyretoBridge.Start(); keep it as a child of the LyretoBridge ModuleScript.
]]
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local TextChatService = game:GetService("TextChatService")
local StarterGui = game:GetService("StarterGui")

local remote = ReplicatedStorage:WaitForChild("LyretoBridgeMessage", 60)
if not remote then
	return
end

local attr = script:GetAttribute("LyretoColor")
local debugOn = script:GetAttribute("LyretoDebug") == true -- set by the server module when Start({ Debug = true })
local color: Color3 = if typeof(attr) == "Color3" then attr else Color3.fromRGB(167, 139, 250)

local function escapeRich(s: string): string
	return (s:gsub("&", "&amp;"):gsub("<", "&lt;"):gsub(">", "&gt;"):gsub('"', "&quot;"):gsub("'", "&apos;"))
end

local function show(text: string)
	if debugOn then
		print("[LyretoBridge client] got:", text)
	end
	if type(text) ~= "string" or text == "" then
		return
	end
	if TextChatService.ChatVersion == Enum.ChatVersion.TextChatService then
		local channels = TextChatService:FindFirstChild("TextChannels")
		local general = channels and channels:FindFirstChild("RBXGeneral")
		if general and general:IsA("TextChannel") then
			local hex = color:ToHex()
			general:DisplaySystemMessage('<font color="#' .. hex .. '">' .. escapeRich(text) .. "</font>")
		end
	else
		for _ = 1, 5 do
			local ok = pcall(function()
				StarterGui:SetCore("ChatMakeSystemMessage", { Text = text, Color = color })
			end)
			if ok then
				break
			end
			task.wait(0.5)
		end
	end
end

(remote :: RemoteEvent).OnClientEvent:Connect(show)
]]></string>
      </Properties>
    </Item>
  </Item>
</roblox>