Módulo de referência

O módulo que o site entrega, completo. A cada poucos segundos ele grava o estado do personagem em um arquivo; quando os comandos abrirem, vai lê-los de outro. O script envia os arquivos, então o cliente do jogo não faz requisições à internet.

Baixar o zip Licença MIT. Adapte para o seu servidor.

README.txt

Voidwatch module and upload scripts                                          MIT licence

1. Close the game client.
2. Copy the "voidwatch" folder into the modules folder of your client: the folder that holds the
   other modules (the ones named game_... and client_...).
   Orion client: it loads modules only from its own files, so Voidwatch runs from the bot folder.
   In the client's data folder, make a folder "_voidwatch" inside "bot", copy the "voidwatch" folder
   into it (bot/_voidwatch/voidwatch), and copy voidwatch/voidwatch_start.lua into the folder of the
   bot config you use, for example bot/vBot_4.8.
3. Set up the upload script once, by double-clicking:
     Windows:  setup-windows.cmd
     macOS:    setup-mac.command   (the first time: right-click it, pick Open, then Open again)
     Linux:    sh setup-linux.sh
   It runs in the background and starts at every login from then on. A client that runs through Wine or
   CrossOver uses the macOS or Linux setup.
4. Start the client and log in. A game message shows a code and a link. Open the link to add the
   character to your account, or to try the dashboard as a guest; in early access a new account waits
   until we let it in. You can also type the code on the Clients page on the website. The Voidwatch
   button in the top bar opens a window with the same code, and later with what the module sends.

Updates: when a new module is out, the Voidwatch window shows "Update to X.Y.Z". Click it. The upload
script downloads the release from GitHub, checks it, keeps the old module as a backup and the module
reloads. "Roll back" puts the backup back. From module 0.5.x, update once by hand: steps 1 and 2, then
run the setup again.

Reset: "Reset loot, supplies and time" in the same window starts the loot, the supplies and the time
from zero.

Verified on Orion-OTS. Most other servers lock their client against modules.

If the game message says the setup did not find the client, drop the folder it shows onto the setup file
(Windows) or drag it into the setup window (macOS), or run: sh setup-linux.sh "<folder>".

To remove the upload script: remove-windows.cmd, remove-mac.command or sh remove-linux.sh.

Adapting the module to a server: https://voidwatch.xyz/developers/new-server

voidwatch/voidwatch.otmod

Module
  name: voidwatch
  description: Writes the character state for the Voidwatch upload script and runs the commands it brings back
  author: Voidwatch
  website: https://voidwatch.xyz/developers
  version: 0.16.1
  sandboxed: true
  autoload: true
  autoload-priority: 1000
  scripts: [ voidwatch, orion, orion_autoloot, orion_tasks, voidwatch_ui ]
  @onLoad: Voidwatch.init()
  @onUnload: Voidwatch.terminate()

voidwatch/voidwatch.lua

-- Voidwatch reference module, feed schema vw.status/1. MIT licence.
--
-- The client makes no web requests. Clients on one computer often share a write directory, so every character has
-- its own folder, <write dir>/voidwatch/<character>/, or <write dir>/bot/_voidwatch/data/<character>/ when the module
-- runs from the bot folder (voidwatch_start.lua). The module writes files there and the upload script answers:
--   outbox/status.json          the character state: every 2 s while someone watches, every 30 s otherwise
--   outbox/capture.png          a screenshot of the game view, when the last reply asked for one
--   outbox/pair-request.json    who wants a pairing code, until the character is paired
--   outbox/results.json         how the commands went
--   inbox/reply.json            the last answer to status: statusEvery, captureEvery, commands, settings, radar
--   inbox/pair.json             the pairing code and link to show the player, or paired: true
--   inbox/commands.json         commands to run
--   plan.json                   the bot's running plan, so a bot reload keeps it; removed at logout
--   outbox/exiva.json           the player's own exiva cast and its answer, which starts a team exiva
--   addons-wanted.json          the addons this folder wants; the upload script puts them in addons/<id>/
--   addons-off.json             the addons turned off for this character, in its own folder
--   addon-settings.json         each addon's own settings for this character, and addon-data/<id>.json its saved table
--   addon-pictures/<id>/        the addon's screenshots; addon-pictures-wanted.txt asks the upload script for them
-- Everything the stock client knows, the module reads itself. The rest comes from adapters (/developers/new-server):
--   Voidwatch.register(adapter)    a server adapter in this module, for example orion.lua; it runs only on its server
--   Voidwatch.attachBot(adapter)   the bot adapter, a script in the bot's config folder; it attaches every 10 s
-- A file named "off" in the data folder stops the module in every client. In the console,
-- modules.voidwatch.Voidwatch.stop() stops this one and modules.voidwatch.Voidwatch.status() shows what it does;
-- modules.voidwatch.Voidwatch.installBot() and .removeBot() add or remove the bot adapter in the selected bot config,
-- and modules.voidwatch.Voidwatch.resetLoot() starts the loot, supply and time counters over. After an update that adds a file,
-- run g_modules.discoverModules() before the reload: a reload keeps the file list the client read at its start.

Voidwatch = { actions = {} }

local MODULE = 'voidwatch-feed/0.16.1'
-- the module's own folder, from this file's path: /modules/voidwatch/ in a client that allows modules, or
-- /bot/_voidwatch/voidwatch/ when voidwatch_start.lua runs it from the bot folder; its data then sits beside it
local HOME = (debug.getinfo(1, 'S').source or ''):match('^@(.*/)[^/]*$') or '/modules/voidwatch/'
local BOT_MODE = HOME:find('/_voidwatch/', 1, true) ~= nil
local ROOT = BOT_MODE and (HOME:gsub('[^/]+/$', '') .. 'data') or '/voidwatch'
local HOMES = BOT_MODE and { HOME } or { HOME, '/modules/voidwatch/', '/mods/voidwatch/' }
local START_FILE = 'voidwatch_start.lua'
Voidwatch.home, Voidwatch.botMode = HOME, BOT_MODE
local LOOP_MS = 1000                                    -- how often the module looks at the reply; writing a file is cheap
local SERVER = ''                                       -- set it, or let an adapter return the server field
local CAPTURES = true                                   -- the game view only: the whole window is larger than the API takes
local COMMANDS = true                                   -- a player can still turn them off per client on the website
local COMMAND_TTL = 60                                  -- seconds: a command older than this is not run
local BOT_FRESH_MS = 30000                              -- bot data older than this is dropped: the bot reloaded or stopped
local LOOT_FLUSH_MS = 10000                             -- the loot file is written at most this often, and at logout
local LOOT_ITEMS = 200                                  -- the most items one loot source keeps, as the API takes
local SUPPLY_ITEMS = 60                                 -- the most supply chips the API takes
local COINS = { ['gold coin'] = 1, ['platinum coin'] = 100, ['crystal coin'] = 10000 }
local GUARD_EVERY = 5                                   -- loops between two memory checks
local GUARD_WINDOW = 120                                -- checks kept for the heap floor: 10 minutes
local GUARD_LUA_MB = 200                                -- growth of the heap floor since load that stops the module
local GUARD_PROCESS_MB = 1400                           -- process memory that stops the module
local MAX_ERRORS = 10                                   -- errors in a row that stop the module
local SETUP_HINT_MS = 20000                             -- no answer from the upload script this long after login
local SETTINGS_RESEND_S = 2                             -- the status pace while a change from the window waits for the website

local SKULLS = { [SkullWhite or 3] = 'white', [SkullRed or 4] = 'red', [SkullBlack or 5] = 'black', [SkullYellow or 1] = 'yellow',
                 [SkullGreen or 2] = 'green', [SkullOrange or 6] = 'orange' }

-- the status fields an adapter may fill; anything else it returns is ignored
local FIELDS = { 'server', 'vocation', 'expPerHour', 'route', 'routeOn', 'label', 'phase', 'labelsMissing', 'plan', 'routes', 'targetOn', 'botConfig',
                 'targetProfile', 'botProfile', 'supplies', 'tasks', 'taskPoints', 'taskWeek', 'loot', 'lootHours',
                 'lootSource', 'blessed', 'redemption', 'redemptionLeft' }

local alive, halted, loopEvent = false, nil, nil
local loops, errors, lastError, baseKB, heap = 0, 0, nil, 0, {}
local me = {}
local adapters, order = {}, {}                          -- id -> { def, running, off, errors, lastError }
local bot = nil                                         -- { def, at, errors, blockedUntil }
-- the character's loot since the last reset, per source: 'corpse' from the loot messages, or an adapter's id
local ledger, ledgerDirty, ledgerFlushAt = nil, false, 0
local prices = nil                                      -- { sell = { name = best price }, buy = { name = lowest price } }
local lastLeft = {}                                     -- name -> the count the last "Using one of N" line showed
-- name -> { n = what is carried now, consumed = true once a use made the count drop }: every bag, closed ones too
local carried, carriedDirty = {}, false

local function log(text) g_logger.info('[Voidwatch] ' .. text) end

local function say(text)
  pcall(function() modules.game_textmessage.displayGameMessage('[Voidwatch] ' .. text) end)
  log(text)
end

local function write(path, text)
  local ok, res = pcall(g_resources.writeFileContents, path, text)
  return ok and res ~= false
end

local function read(path)
  if not g_resources.fileExists(path) then return nil end
  local ok, text = pcall(g_resources.readFileContents, path)
  return ok and text or nil
end

local function readJson(path)
  local text = read(path)
  if not text then return nil end
  local ok, value = pcall(json.decode, text)
  return ok and type(value) == 'table' and value or nil
end

local function keyOf(name) return (name:lower():gsub('[^%w]+', '_')) end

local function mb(bytes) return math.floor(bytes / 1048576) end

-- addons: our own optional parts of the module, from the same GitHub release and checked like the core. The upload
-- script puts them in the data folder, so every client of that folder has them. Each one runs in its own environment;
-- its errors are caught, and ADDON_ERRORS in a row stop it. A file named addons-off in the data folder stops them all.
local ADDON_DIR = ROOT .. '/addons'
local ADDON_ERRORS = 10
local ADDON_SCAN_MS = 5000
local ADDON_LOG = 20
local OFF_HERE = 'off for this character'
local ADDON_PICTURES = ROOT .. '/addon-pictures'
local addons, addonScanAt = {}, -math.huge              -- id -> { id, version, env, handlers, timers, errors, off, error, loaded, here, log }
local unloadAddon, priceOf

local function newAddon(id) return { id = id, errors = 0, timers = {}, handlers = {}, log = {}, connections = {}, widgets = {} } end

local function addonLog(rec, text)
  table.insert(rec.log, 1, { at = os.time(), text = text })
  rec.log[ADDON_LOG + 1] = nil
end

local function addonCall(rec, fn, ...)
  if rec.off then return false end
  local ok, err = pcall(fn, ...)
  if ok then rec.errors = 0; return true end
  rec.errors, rec.error = rec.errors + 1, tostring(err):sub(1, 200)
  addonLog(rec, rec.error)
  log(('addon %s: %s'):format(rec.id, rec.error))
  if rec.errors >= ADDON_ERRORS then
    unloadAddon(rec)
    rec.off = true
    say(('addon %s stopped after %d errors: %s'):format(rec.id, ADDON_ERRORS, rec.error))
  end
  return false
end

function unloadAddon(rec)
  if rec.env and type(rec.env.terminate) == 'function' then pcall(rec.env.terminate) end
  for _, ev in pairs(rec.timers) do removeEvent(ev) end
  for _, c in ipairs(rec.connections or {}) do pcall(disconnect, c[1], c[2]) end
  for _, w in ipairs(rec.widgets or {}) do pcall(function() if not w:isDestroyed() then w:destroy() end end) end
  if rec.button then pcall(function() rec.button:destroy() end) end
  rec.timers, rec.handlers, rec.env, rec.loaded = {}, {}, nil, false
  rec.connections, rec.widgets, rec.button, rec.openFn, rec.openLabel = {}, {}, nil, nil, nil
end

-- an addon's own settings: declared in its addon.json, saved per character, the default while a saved value does not fit
local SETTING_TYPES = { bool = true, number = true, choice = true, text = true }

local function declaredSettings(rec)
  local out = {}
  for _, s in ipairs(rec.info and type(rec.info.settings) == 'table' and rec.info.settings or {}) do
    if type(s) == 'table' and type(s.key) == 'string' and s.key:match('^[%w_]+$') and SETTING_TYPES[s.type] then out[#out + 1] = s end
  end
  return out
end

local function settingFits(s, v)
  if s.type == 'bool' then return type(v) == 'boolean' end
  if s.type == 'number' then
    return type(v) == 'number' and v == v and (not tonumber(s.min) or v >= tonumber(s.min)) and (not tonumber(s.max) or v <= tonumber(s.max))
  end
  if s.type == 'text' then return type(v) == 'string' and #v <= (tonumber(s.maxLength) or 40) and not v:find('[%c]') end
  for _, o in ipairs(type(s.options) == 'table' and s.options or {}) do
    if o == v then return true end
  end
  return false
end

local function addonSettings(rec)
  local all = me.dir and readJson(me.dir .. '/addon-settings.json') or {}
  local saved = type(all[rec.id]) == 'table' and all[rec.id] or {}
  local out = {}
  for _, s in ipairs(declaredSettings(rec)) do
    local v = saved[s.key]
    if v == nil or not settingFits(s, v) then v = s.default end
    out[s.key] = v
  end
  return out
end

local function addonApi(rec)
  local api = { id = rec.id, version = rec.version, dir = ADDON_DIR .. '/' .. rec.id .. '/' }
  function api.log(text) log(rec.id .. ': ' .. tostring(text)) end
  function api.say(text) say(tostring(text)) end
  function api.on(name, fn) if type(fn) == 'function' then rec.handlers[name] = fn end end
  function api.settings() return type(me.settings) == 'table' and me.settings or {} end
  function api.state() return me.last end
  function api.minimap() return modules.game_minimap and modules.game_minimap.minimapWidget or nil end
  function api.after(ms, fn)
    local key = {}
    rec.timers[key] = scheduleEvent(function() rec.timers[key] = nil; addonCall(rec, fn) end, ms)
    return key
  end
  function api.cancel(key)
    if rec.timers[key] then removeEvent(rec.timers[key]) end
    rec.timers[key] = nil
  end
  -- the next run is scheduled first, so one error does not end the timer
  function api.every(ms, fn)
    local key = {}
    local function run()
      rec.timers[key] = scheduleEvent(run, ms)
      addonCall(rec, fn)
    end
    rec.timers[key] = scheduleEvent(run, math.max(50, tonumber(ms) or 1000))
    return key
  end
  function api.style(file)
    if type(file) ~= 'string' or not file:match('^[%w_%-]+%.otui$') then return false end
    return (pcall(g_ui.importStyle, api.dir .. file))
  end
  function api.ui(style, parent)
    local ok, w = pcall(g_ui.createWidget, style, parent or rootWidget)
    if not ok or not w then return nil end
    rec.widgets[#rec.widgets + 1] = w
    return w
  end
  function api.connect(object, handlers)
    local wrapped = {}
    for name, fn in pairs(type(handlers) == 'table' and handlers or {}) do
      if type(fn) == 'function' then wrapped[name] = function(...) return addonCall(rec, fn, ...) end end
    end
    connect(object, wrapped)
    rec.connections[#rec.connections + 1] = { object, wrapped }
  end
  function api.button(tooltip, icon, fn)
    local tm = modules.client_topmenu
    if rec.button or type(fn) ~= 'function' or not (tm and tm.addRightGameToggleButton) then return rec.button end
    local image = type(icon) == 'string' and icon:match('^[%w_%-]+$') and (api.dir .. icon) or '/images/topbuttons/analyzers'
    rec.openFn, rec.openLabel = fn, type(tooltip) == 'string' and tooltip or nil
    rec.button = tm.addRightGameToggleButton('vwAddon' .. rec.id:gsub('%-', ''), tostring(tooltip or rec.id), image, function() addonCall(rec, fn) end, false, 950)
    return rec.button
  end
  function api.load()
    return me.dir and readJson(me.dir .. '/addon-data/' .. rec.id .. '.json') or {}
  end
  function api.save(t)
    if not me.dir or type(t) ~= 'table' then return false end
    local ok, text = pcall(json.encode, t)
    if not ok then return false end
    pcall(g_resources.makeDir, me.dir .. '/addon-data')
    return write(me.dir .. '/addon-data/' .. rec.id .. '.json', text)
  end
  function api.setting(key) return addonSettings(rec)[key] end
  function api.price(name) return type(name) == 'string' and priceOf(name:lower()) or nil end
  function api.online() return ledger and math.floor(tonumber(ledger.onlineS) or 0) or 0 end
  return api
end

local function loadAddon(id, version)
  local rec = addons[id] or newAddon(id)
  addons[id] = rec
  if rec.loaded then unloadAddon(rec) end
  rec.version, rec.off, rec.errors, rec.error, rec.here = version, false, 0, nil, true
  local src = read(ADDON_DIR .. '/' .. id .. '/main.lua')
  local chunk, err = nil, 'no main.lua'
  if src then chunk, err = loadstring(src, '@addons/' .. id .. '/main.lua') end
  if not chunk then
    rec.off, rec.error = true, tostring(err):sub(1, 200)
    addonLog(rec, rec.error)
    return
  end
  local env = setmetatable({ Addon = addonApi(rec) }, { __index = getfenv(1) })
  setfenv(chunk, env)
  rec.env, rec.loaded = env, true
  if addonCall(rec, chunk) and type(env.init) == 'function' then addonCall(rec, env.init) end
  if not rec.off then log(('addon %s %s loaded'):format(id, version)) end
end

local function stopAllAddons()
  for _, rec in pairs(addons) do
    if rec.loaded then unloadAddon(rec) end
  end
end

-- loads new and changed addons, unloads removed ones; the upload script writes .version beside each addon
local function wantedAddons()
  local w = readJson(ROOT .. '/addons-wanted.json')
  return w and type(w.ids) == 'table' and w.ids or {}
end

local function offHere()
  local w = me.dir and readJson(me.dir .. '/addons-off.json')
  local out = {}
  for _, id in ipairs(w and type(w.ids) == 'table' and w.ids or {}) do out[tostring(id)] = true end
  return out
end

local function scanAddons(force)
  if not me.dir then return end
  local now = g_clock.millis()
  if not force and now - addonScanAt < ADDON_SCAN_MS then return end
  addonScanAt = now
  if g_resources.fileExists(ROOT .. '/addons-off') then return stopAllAddons() end
  local wanted, seen, off = {}, {}, offHere()
  for _, id in ipairs(wantedAddons()) do wanted[tostring(id)] = true end
  local ok, names = pcall(g_resources.listDirectoryFiles, ADDON_DIR)
  for _, id in ipairs(ok and type(names) == 'table' and names or {}) do
    id = tostring(id)
    local manifest = wanted[id] and id:match('^[%w%-]+$') and readJson(ADDON_DIR .. '/' .. id .. '/addon.json')
    if manifest then
      seen[id] = true
      local version = (read(ADDON_DIR .. '/' .. id .. '/.version') or tostring(manifest.version or '?')):match('^%s*(.-)%s*$')
      local rec = addons[id]
      local info = { name = manifest.name, about = manifest.about, points = manifest.points, plan = manifest.plan, settings = manifest.settings }
      if off[id] then
        rec = rec or newAddon(id)
        addons[id] = rec
        if rec.loaded then unloadAddon(rec) end
        rec.version, rec.here = version, false
      elseif not rec or rec.version ~= version or rec.here == false or (not rec.off and not rec.loaded) then
        loadAddon(id, version)
      end
      addons[id].info = info
    end
  end
  for id, rec in pairs(addons) do
    if not seen[id] then
      if rec.loaded then unloadAddon(rec) end
      addons[id] = nil
    end
  end
end

local function emitAddons(name, ...)
  for _, rec in pairs(addons) do
    local fn = rec.loaded and rec.handlers[name]
    if fn then addonCall(rec, fn, ...) end
  end
end

local function setWanted(id, on)
  local out = {}
  for _, x in ipairs(wantedAddons()) do
    if x ~= id then out[#out + 1] = x end
  end
  if on then out[#out + 1] = id end
  table.sort(out)
  return write(ROOT .. '/addons-wanted.json', json.encode({ ids = out }))
end

local SETTING_KINDS = { captures = 'boolean', minimap = 'boolean', supplyList = 'boolean', commands = 'boolean', exiva = 'boolean',
                        exivaShowAll = 'boolean', chat = 'boolean', planWait = 'number', labels = 'table' }
local SETTING_DEFAULTS = { captures = true, minimap = true, supplyList = true, commands = true, exiva = false, exivaShowAll = false,
                           chat = true, planWait = 20, labels = {} }

-- a change saved in the window counts at once; a reply from before the website took it must not undo it
local function withChange(settings)
  if not me.change then return settings end
  local out = {}
  for k, v in pairs(settings) do out[k] = v end
  for k, v in pairs(me.change.values) do out[k] = v end
  return out
end

local function addonStates()
  local out = {}
  for id, rec in pairs(addons) do
    out[#out + 1] = { id = id, version = rec.version, on = rec.loaded == true, error = rec.here == false and OFF_HERE or rec.error }
  end
  for _, id in ipairs(wantedAddons()) do
    if not addons[id] then
      out[#out + 1] = { id = id, on = false, error = g_resources.fileExists(ADDON_DIR .. '/.failed-' .. id) and 'the download failed' or 'installing' }
    end
  end
  table.sort(out, function(a, b) return a.id < b.id end)
  return out
end

-- the addon's screenshots in this folder, by file name
local function pictureFiles(id)
  local out = {}
  if type(id) ~= 'string' or not id:match('^[%w%-]+$') then return out end
  local ok, names = pcall(g_resources.listDirectoryFiles, ADDON_PICTURES .. '/' .. id)
  for _, n in ipairs(ok and type(names) == 'table' and names or {}) do
    n = tostring(n)
    if n:match('^[%w_%-]+%.png$') then out[#out + 1] = n end
  end
  table.sort(out)
  return out
end
Voidwatch.pictureFiles = pictureFiles

local function addonView()
  local off, out = offHere(), addonStates()
  for _, st in ipairs(out) do
    local rec = addons[st.id]
    st.here = not off[st.id]
    st.log = rec and rec.log or {}
    st.canOpen = rec ~= nil and rec.loaded == true and (type(rec.handlers.open) == 'function' or rec.openFn ~= nil)
    st.openLabel = st.canOpen and type(rec.handlers.open) ~= 'function' and rec.openLabel or nil
    st.broken = rec ~= nil and rec.off == true
    st.errors = rec and rec.errors or 0
    st.info = rec and rec.info or nil
    st.settings = {}
    if rec then
      local values = addonSettings(rec)
      for _, d in ipairs(declaredSettings(rec)) do
        st.settings[#st.settings + 1] = { key = d.key, type = d.type, label = tostring(d.label or d.key), min = tonumber(d.min), max = tonumber(d.max),
                                          maxLength = tonumber(d.maxLength), options = type(d.options) == 'table' and d.options or nil, value = values[d.key] }
      end
    end
    st.pictures = pictureFiles(st.id)
  end
  return out
end

-- some clients return an empty OS name; the client's own build target is the fallback
local function platform()
  for _, get in ipairs({ function() return g_platform.getOSName() end, function() return g_app.getOs() end }) do
    local ok, os = pcall(get)
    if ok and type(os) == 'string' and os ~= '' then return (os:gsub('^%l', string.upper)) end
  end
  return nil
end

local function features()
  local list = { 'status' }
  if CAPTURES then list[#list + 1] = 'captures' end
  if COMMANDS and not (me.settings and me.settings.commands == false) then list[#list + 1] = 'commands' end
  return list
end

-- the website finds the server from these: the login address, the world and the protocol version
local function origin()
  local okHost, host = pcall(g_settings.get, 'host')
  local okWorld, world = pcall(g_game.getWorldName)
  local okVersion, version = pcall(g_game.getClientVersion)
  return okHost and type(host) == 'string' and host ~= '' and host:sub(1, 200) or nil,
         okWorld and type(world) == 'string' and world ~= '' and world:sub(1, 60) or nil,
         okVersion and tonumber(version) or nil
end

local function addLoot(source, name, count)
  count = tonumber(count) or 0
  if not ledger or type(name) ~= 'string' or name == '' or count <= 0 then return end
  local items = ledger.sources[source] or {}
  ledger.sources[source] = items
  if not items[name] then
    local n = 0
    for _ in pairs(items) do n = n + 1 end
    if n >= LOOT_ITEMS then return end
  end
  items[name] = (items[name] or 0) + count
  ledgerDirty = true
  emitAddons('loot', source, name, count)
end

local function dropLoot(source, name)
  local items = ledger and ledger.sources[source]
  if items and type(name) == 'string' and items[name] then
    items[name] = nil
    ledgerDirty = true
  end
end

local function newLedger() return { since = os.time(), onlineS = 0, sources = {}, used = {} } end

local function loadLedger()
  local t = readJson(me.dir .. '/loot.json')
  ledger = (t and type(t.sources) == 'table') and t or newLedger()
  ledger.onlineS = tonumber(ledger.onlineS) or 0
  if type(ledger.used) ~= 'table' then ledger.used = {} end
end

local function addUsed(name, n)
  if not ledger or name == '' or n <= 0 then return end
  local count = 0
  for _ in pairs(ledger.used) do count = count + 1 end
  if not ledger.used[name] and count >= LOOT_ITEMS then return end
  ledger.used[name] = (ledger.used[name] or 0) + n
  ledgerDirty = true
end

local function flushLedger(force)
  if not ledger or not me.dir or not (ledgerDirty or carriedDirty) then return end
  if not force and g_clock.millis() < ledgerFlushAt then return end
  ledgerFlushAt = g_clock.millis() + LOOT_FLUSH_MS
  if ledgerDirty then write(me.dir .. '/loot.json', json.encode(ledger)) end
  if carriedDirty and next(carried) then write(me.dir .. '/carried.json', json.encode(carried)) end
  ledgerDirty, carriedDirty = false, false
end

-- a count above one comes as a plural: "43 gold coins", "2 small rubies", "3 pieces of royal steel"
local function singular(word)
  if word:match('ies$') then return (word:gsub('ies$', 'y')) end
  if word:match('[sxz]es$') or word:match('[cs]hes$') then return (word:gsub('es$', '')) end
  if word:match('[^s]s$') then return (word:gsub('s$', '')) end
  return word
end

local function lootName(part)
  part = part:lower():gsub('^%s+', ''):gsub('%s+$', '')
  local n, rest = part:match('^(%d+)%s+(.+)$')
  if not n then return (part:gsub('^an?%s+', ''):gsub('^the%s+', '')), 1 end
  local head, tail = rest:match('^(.-)(%s+of%s+.+)$')
  if head then return (head:gsub('(%S+)$', singular)) .. tail, tonumber(n) end
  return (rest:gsub('(%S+)$', singular)), tonumber(n)
end

-- The game says how many you had before each use: "Using one of 100 great mana potions...", and for the last one
-- "Using the last great mana potion...". A count one lower than the line before means one was used; a rope or a
-- shovel never goes down, so tools never count. Like vBot's analyzer, the last use before a refill is not seen.
local function onUse(text)
  local n, plural = text:match('^Using one of (%d+) (.-)%.%.%.')
  local name, left
  if n then
    name, left = lootName(n .. ' ' .. plural)
  else
    name = text:match('^Using the last (.-)%.%.%.')
    if not name then return false end
    name, left = lootName(name), 1
  end
  local before = lastLeft[name]
  local c = carried[name] or {}
  if before and left < before and before - left <= 10 then addUsed(name, before - left); c.consumed = true end
  lastLeft[name] = (left > 1) and left or nil       -- the next line after the last one comes after a refill
  if left == 1 and before == 2 then addUsed(name, 1) end
  -- the line shows the count before the use: a supply has one less now, a rope or a probe the same
  c.n = c.consumed and math.max(0, left - 1) or left
  carried[name], carriedDirty = c, true
  return true
end

-- "Loot of a dragon: 2 dragon hams, 43 gold coins." is what the corpse held; every server sends it
-- exiva: the player's own cast starts a team exiva on the website, and a cast the website asks for answers it. The answer is
-- the game message that follows the cast, in the words of TFS (spells.cpp, SearchPlayer).
local EXIVA_GAP_MS = 5000
local EXIVA_TRIES = 5
local EXIVA_RETRY_MS = 400
local EXIVA_ANSWER_MS = 3000
local EXIVA_LATE_MS = 10000
local EXIVA_MANA = 20
local EXIVA_DIRS = { north = 'north', south = 'south', east = 'east', west = 'west', ['north-east'] = 'north-east',
  ['north-west'] = 'north-west', ['south-east'] = 'south-east', ['south-west'] = 'south-west', northeast = 'north-east',
  northwest = 'north-west', southeast = 'south-east', southwest = 'south-west' }
local EXIVA_PATTERNS = {
  { '^(.-) is standing next to you%.?$', 'beside', 'same' }, { '^(.-) is above you%.?$', 'beside', 'higher' },
  { '^(.-) is below you%.?$', 'beside', 'lower' }, { '^(.-) is on a higher level to the ([%a%-]+)%.?$', 'close', 'higher' },
  { '^(.-) is on a lower level to the ([%a%-]+)%.?$', 'close', 'lower' }, { '^(.-) is very far to the ([%a%-]+)%.?$', 'veryfar', 'unknown' },
  { '^(.-) is far to the ([%a%-]+)%.?$', 'far', 'unknown' }, { '^(.-) is to the ([%a%-]+)%.?$', 'close', 'same' },
}
-- the game's answers that end a cast without a direction; "exhausted" is tried again, the bot's own spells hold the timer
local EXIVA_REFUSALS = {
  { '^A player with this name is not online', 'not online' }, { '^A player with this name does not exist', 'no such player' },
  { '^Player name is ambiguous', 'name is ambiguous' }, { '^You do not have enough mana', 'not enough mana' },
  { '^You need to learn this spell first', 'the character does not know exiva' }, { '^Your level is too low', 'level too low' },
  { '^You are exhausted', 'exhausted' },
}
local exiva = { last = -math.huge }
local addResults   -- below, with the commands

local function exivaAnswer(text)
  for _, p in ipairs(EXIVA_PATTERNS) do
    local name, word = text:match(p[1])
    if name then
      local dir = word and EXIVA_DIRS[word:lower()]
      if word and not dir then return nil end
      return { name = name, band = p[2], level = p[3], dir = dir }
    end
  end
end

local function exivaCast(p)
  if exiva.pending ~= p then return end
  local pl = g_game.getLocalPlayer()
  if not pl or pl:getHealth() < pl:getMaxHealth() * 0.5 then
    exiva.pending = nil
    return addResults({ { id = p.id, ok = false, message = pl and 'HP below 50%' or 'not logged in' } })
  end
  p.tries, p.t, p.last = p.tries + 1, g_clock.millis(), nil
  g_game.talk('exiva "' .. p.name .. '"')
end

local function sameTarget(name, target)
  local n, want = name:lower(), target:lower():gsub('~$', '')
  return n:sub(1, #want) == want or want:sub(1, #n) == n
end

-- the game sends the answer before it echoes the spell words, so an answer with no team cast waiting is the player's own
-- cast, however it was typed; a late answer to a recent team cast is not. Addons see every own cast, also with Team exiva off.
local function ownExiva(text)
  local a = exivaAnswer(text)
  if not a then return end
  local now, pl = g_clock.millis(), g_game.getLocalPlayer()
  if exiva.team and now - exiva.team.t < EXIVA_LATE_MS and sameTarget(a.name, exiva.team.target) then return end
  local at = pl and pl:getPosition()
  if not at then return end
  emitAddons('exiva_cast', { target = a.name, x = at.x, y = at.y, z = at.z, band = a.band, dir = a.dir, level = a.level })
  if not (me.settings and me.settings.exiva) then return end
  exiva.last = now
  write(me.dir .. '/outbox/exiva.json', json.encode({ target = a.name, pos = { x = at.x, y = at.y, z = at.z }, band = a.band, dir = a.dir, level = a.level, text = text }))
  say(('your exiva on %s starts a team exiva.'):format(a.name))
end

local function exivaMessage(text)
  local p = exiva.pending
  if not me.dir then return end
  if not p or g_clock.millis() - p.t > EXIVA_ANSWER_MS then return ownExiva(text) end
  local refused
  for _, r in ipairs(EXIVA_REFUSALS) do
    if text:find(r[1]) then refused = r[2] break end
  end
  if refused == 'exhausted' and p.team and p.tries < EXIVA_TRIES then
    p.t = g_clock.millis()
    scheduleEvent(function() exivaCast(p) end, EXIVA_RETRY_MS)
    return
  end
  if refused then
    exiva.pending = nil
    if p.team then
      addResults({ { id = p.id, ok = false, message = refused == 'exhausted' and ('exhausted after ' .. p.tries .. ' tries') or refused } })
    end
    return
  end
  local a = exivaAnswer(text)
  if not a then
    if #text <= 100 and not text:find('^Loot of') and not text:find('^Using ') then p.last = text end
    return
  end
  if not sameTarget(a.name, p.target) then return ownExiva(text) end
  exiva.pending = nil
  addResults({ { id = p.id, ok = true, message = text, data = { x = p.pos.x, y = p.pos.y, z = p.pos.z, band = a.band, dir = a.dir, level = a.level } } })
end

local function onTextMessage(mode, text)
  if alive and not halted and type(text) == 'string' then
    exivaMessage(text)
    emitAddons('message', mode, text)
  end
  if not alive or halted or not ledger or type(text) ~= 'string' then return end
  if onUse(text) then return end
  local body = text:match('^Loot of [^:]+:%s*(.+)$')
  if not body or body:lower():match('^nothing') then return end
  for part in body:gsub('%.%s*$', ''):gmatch('[^,]+') do
    local name, n = lootName(part)
    addLoot('corpse', name, n)
  end
end

-- the stock client hands every trade window's list to this event: { item, name, weight, buy price, sell price }
local function readPrices()
  local t = readJson(ROOT .. '/prices.json') or {}
  if type(t.sell) ~= 'table' and type(t.buy) ~= 'table' then t = { sell = t, buy = {} } end   -- the first files held sell prices only
  t.sell, t.buy = type(t.sell) == 'table' and t.sell or {}, type(t.buy) == 'table' and t.buy or {}
  return t
end

-- the stock client hands every trade window's list to this event: { item, name, weight, buy price, sell price }.
-- The best price wins: the highest an NPC pays, the lowest an NPC asks.
local function onOpenNpcTrade(items)
  if not alive or type(items) ~= 'table' then return end
  local all = readPrices()                              -- another client may have learned prices meanwhile
  local changed = false
  for _, it in pairs(items) do
    local name = type(it) == 'table' and type(it[2]) == 'string' and it[2]:lower()
    local buy, sell = name and tonumber(it[4]), name and tonumber(it[5])
    if sell and sell > 0 and (not tonumber(all.sell[name]) or sell > tonumber(all.sell[name])) then all.sell[name], changed = sell, true end
    if buy and buy > 0 and (not tonumber(all.buy[name]) or buy < tonumber(all.buy[name])) then all.buy[name], changed = buy, true end
  end
  prices = all
  if changed then write(ROOT .. '/prices.json', json.encode(all)) end
end

function priceOf(name) return COINS[name] or (prices and tonumber(prices.sell[name])) or nil end
local function buyPriceOf(name) return prices and tonumber(prices.buy[name]) or nil end

local function provides(def, name)
  for _, v in ipairs(type(def.provides) == 'table' and def.provides or {}) do if v == name then return true end end
  return false
end

local function domainOf(host)
  return (tostring(host or ''):lower():gsub('^%a+://', ''):gsub('/.*$', ''):gsub(':%d+$', ''))
end

local function matches(def, host, world)
  local m = def.match
  if type(m) ~= 'table' then return true end
  local function any(list, test)
    if type(list) ~= 'table' then return true end
    for _, v in ipairs(list) do if test(tostring(v):lower()) then return true end end
    return false
  end
  local domain, w = domainOf(host), tostring(world or ''):lower()
  return any(m.hosts, function(h) return domain == h or domain:sub(-#h - 1) == '.' .. h end)
     and any(m.worlds, function(v) return v == w end)
end

-- one call into an adapter; MAX_ERRORS in a row turn that adapter off, and only that one
local function call(rec, name, fn, ...)
  local ok, res, extra = pcall(fn, ...)
  if ok then rec.errors = 0; return true, res, extra end
  rec.errors = rec.errors + 1
  if tostring(res) ~= rec.lastError then log(('adapter %s, %s: %s'):format(rec.def.id, name, tostring(res))) end
  rec.lastError = tostring(res)
  if rec.errors >= MAX_ERRORS and rec.def ~= (bot and bot.def) then
    rec.off = true
    if rec.running and rec.def.terminate then pcall(rec.def.terminate) end
    rec.running = false
    say(('adapter %s stopped after %d errors: %s'):format(rec.def.id, MAX_ERRORS, rec.lastError))
  end
  return false
end

local function stopAdapters()
  for _, id in ipairs(order) do
    local rec = adapters[id]
    if rec.running and rec.def.terminate then pcall(rec.def.terminate) end
    rec.running = false
  end
end

-- at every login: start the adapters for this server, stop the others
local function startAdapters()
  local host, world = origin()
  for _, id in ipairs(order) do
    local rec = adapters[id]
    local want = not rec.off and matches(rec.def, host, world)
    if want and not rec.running then
      rec.running = true
      local id = rec.def.id
      if rec.def.init then
        call(rec, 'init', rec.def.init, { log = log, say = say, addLoot = function(name, n) addLoot(id, name, n) end,
                                         dropLoot = function(name) dropLoot(id, name) end })
      end
    elseif not want and rec.running then
      if rec.def.terminate then pcall(rec.def.terminate) end
      rec.running = false
    end
  end
end

local function freshBot()
  if not bot or g_clock.millis() - bot.at > BOT_FRESH_MS then return nil end
  if bot.blockedUntil and g_clock.millis() < bot.blockedUntil then return nil end
  return bot
end

-- a running adapter that lists a field in `provides` owns it: an empty answer then means unknown, not "use the core's"
local function owned(name)
  for _, id in ipairs(order) do
    if adapters[id].running and provides(adapters[id].def, name) then return true end
  end
  return false
end

-- the first answer wins: the module's adapters first, then the bot
local function field(name)
  for _, id in ipairs(order) do
    local rec = adapters[id]
    local fn = rec.running and type(rec.def.fields) == 'table' and rec.def.fields[name]
    if fn then
      local ok, value = call(rec, name, fn)
      if ok and value ~= nil then return value end
    end
  end
  local b = freshBot()
  local fn = b and type(b.def.fields) == 'table' and b.def.fields[name]
  if fn then
    local ok, value = call(b, name, fn)
    if ok then
      if value ~= nil then return value end
    elseif b.errors >= MAX_ERRORS then
      b.blockedUntil, b.errors = g_clock.millis() + 60000, 0
      log('bot adapter paused for a minute after ' .. MAX_ERRORS .. ' errors: ' .. tostring(b.lastError))
    end
  end
  return nil
end

local function action(name)
  if Voidwatch.actions[name] then return Voidwatch.actions[name] end
  for _, id in ipairs(order) do
    local rec = adapters[id]
    if rec.running and type(rec.def.actions) == 'table' and rec.def.actions[name] then return rec.def.actions[name] end
  end
  local b = freshBot()
  return b and type(b.def.actions) == 'table' and b.def.actions[name] or nil
end

local shipped, bundledBot
local function shippedBot()
  if shipped == nil then
    local src = bundledBot()
    shipped = src and src:match("local VERSION = '(%d+)'") or false
  end
  return shipped or nil
end

local function adapterStates()
  local states = {}
  for _, id in ipairs(order) do
    local rec = adapters[id]
    if rec.running or rec.off then states[#states + 1] = { id = id, version = tostring(rec.def.version or ''), on = rec.running } end
  end
  if bot then
    states[#states + 1] = { id = tostring(bot.def.id or 'bot'), version = tostring(bot.def.version or ''), on = freshBot() ~= nil,
                            want = shippedBot() }
  end
  return states
end

-- an adapter that counts loot (an autoloot, the bot) wins over the loot messages, which only say what a corpse held
local function lootState()
  if not ledger then return nil end
  local source = 'corpse'
  for _, id in ipairs(order) do
    local rec = adapters[id]
    if rec.running and provides(rec.def, 'loot') then source = id break end
  end
  local items = {}
  for name, count in pairs(ledger.sources[source] or {}) do
    items[#items + 1] = { name = name:sub(1, 60), count = count, sell = priceOf(name) }
  end
  table.sort(items, function(a, b) return a.name < b.name end)
  return #items > 0 and items or nil, source, math.floor(ledger.onlineS / 36) / 100
end

-- case 1: the bot's own supply list, with "have" from the game's last count where it has one; case 3, when the bot
-- has no list or the player turned it off: every item the "Using one of" lines named
local function supplyState(botRows, useBotList)
  if useBotList and type(botRows) == 'table' and #botRows > 0 then
    for _, r in ipairs(botRows) do
      local c = type(r) == 'table' and carried[tostring(r.name):lower()]
      if c and c.n then r.have = c.n end
    end
    return botRows, 'bot'
  end
  local rows = {}
  for name, c in pairs(carried) do
    if c.n then rows[#rows + 1] = { name = name:sub(1, 60), have = c.n } end
  end
  table.sort(rows, function(a, b) return a.name < b.name end)
  while #rows > SUPPLY_ITEMS do table.remove(rows) end
  return (#rows > 0 and rows or nil), (#rows > 0 and 'used' or nil)
end

local function usedState()
  if not ledger then return nil end
  local items = {}
  for name, count in pairs(ledger.used) do
    items[#items + 1] = { name = name:sub(1, 60), count = count, buy = buyPriceOf(name) }
  end
  table.sort(items, function(a, b) return a.name < b.name end)
  return #items > 0 and items or nil
end

-- the stock skills module keeps the exp per second on the player, the number its level bar tooltip shows per hour
local function stockExpPerHour(p)
  local ok, speed = pcall(function() return p.expSpeed end)
  if ok and type(speed) == 'number' and speed >= 0 then return math.floor(speed * 3600) end
  return nil
end

-- an empty list is left out: the API fills in its own default
local function list(value)
  if type(value) ~= 'table' or next(value) == nil then return nil end
  return value
end

-- some clients have no isInProtectionZone; the protection zone is then a bit of the player's states
local function inPz(p)
  if type(p.isInProtectionZone) == 'function' then
    local ok, v = pcall(p.isInProtectionZone, p)
    if ok and type(v) == 'boolean' then return v end
  end
  local ok, v = pcall(function() return bit.band(p:getStates(), (PlayerStates and PlayerStates.Pz) or 16384) > 0 end)
  if ok then return v end
  return nil
end

local function stockBlessed(p)
  if type(p.getBlessings) ~= 'function' then return nil end
  local ok, v = pcall(p.getBlessings, p)
  if ok and type(v) == 'number' then return v > 0 end
  return nil
end

local function outfitOf(p)
  local ok, o = pcall(function() return p:getOutfit() end)
  if not ok or type(o) ~= 'table' or not tonumber(o.type) then return nil end
  local n = function(v) return math.max(0, math.floor(tonumber(v) or 0)) end
  return { type = n(o.type), head = n(o.head), body = n(o.body), legs = n(o.legs), feet = n(o.feet), addons = n(o.addons) }
end

local function pzLocked(p)
  local ok, v = pcall(function() return bit.band(p:getStates(), (PlayerStates and PlayerStates.PzBlock) or 8192) > 0 end)
  if ok then return v end
  return nil
end

local function changed()
  if Voidwatch.ui and Voidwatch.ui.changed then pcall(Voidwatch.ui.changed) end
end

local function halt(why)
  halted = why
  stopAdapters()
  stopAllAddons()
  say('stopped: ' .. why .. '. Start it again in the Voidwatch window, or reload the module.')
  changed()
end

local function guard()
  local kb = collectgarbage('count')
  heap[#heap + 1] = kb
  if #heap > GUARD_WINDOW then table.remove(heap, 1) end
  local floor = kb
  for _, v in ipairs(heap) do if v < floor then floor = v end end
  local grown = math.floor((floor - baseKB) / 1024)
  if grown > GUARD_LUA_MB then return halt(('the Lua heap grew %d MB'):format(grown)) end
  local ok, bytes = pcall(g_platform.getMemoryUsage)
  if ok and type(bytes) == 'number' and mb(bytes) > GUARD_PROCESS_MB then
    return halt(('the client uses %d MB'):format(mb(bytes)))
  end
end

local function actionNames()
  local names, seen = {}, {}
  local function add(t)
    for name in pairs(type(t) == 'table' and t or {}) do
      if not seen[name] then seen[name], names[#names + 1] = true, name end
    end
  end
  add(Voidwatch.actions)
  for _, id in ipairs(order) do
    if adapters[id].running then add(adapters[id].def.actions) end
  end
  local b = freshBot()
  if b then add(b.def.actions) end
  table.sort(names)
  return names
end

local function state(p)
  local level, exp = p:getLevel(), p:getExperience()
  if not level or level < 1 or not exp or exp < 0 then return nil end  -- right after a relog the server sends -1
  local pos = p:getPosition()
  if not pos then return nil end
  local skulls, players = {}, 0
  for _, c in ipairs(g_map.getSpectators(pos, false)) do
    if c:isPlayer() and c ~= p then
      players = players + 1
      if SKULLS[c:getSkull()] then
        local okQ, q = pcall(function() return c:getPosition() end)
        q = okQ and q or nil
        table.insert(skulls, { name = c:getName(), skull = SKULLS[c:getSkull()],
                               dist = q and math.min(100, math.max(math.abs(q.x - pos.x), math.abs(q.y - pos.y))) or nil })
      end
    end
  end

  local s = {
    schema = 'vw.status/1', module = MODULE, online = true,
    character = { name = p:getName(), level = level, exp = exp },
    pos = { x = pos.x, y = pos.y, z = pos.z },
    cap = math.max(0, math.floor(p:getFreeCapacity())),
    stamina = p.getStamina and math.max(0, math.min(2520, p:getStamina())) or nil,
    skulls = list(skulls), features = features(), playersInView = players, skull = SKULLS[p:getSkull()],
    pz = inPz(p), pzLock = pzLocked(p), outfit = outfitOf(p),
  }
  for _, name in ipairs(FIELDS) do
    if name ~= 'server' then
      local value = field(name)
      if type(value) == 'table' and name ~= 'tasks' then value = list(value) end
      if name == 'vocation' then s.character.vocation = value else s[name] = value end
    end
  end
  s.expPerHour = s.expPerHour or stockExpPerHour(p)
  if s.blessed == nil and not owned('blessed') then s.blessed = stockBlessed(p) end
  if s.loot == nil then
    local items, source, hours = lootState()
    s.loot, s.lootHours = items, s.lootHours or hours
    s.lootSource = items and source or nil
  end
  s.used = usedState()
  s.supplies, s.suppliesSource = supplyState(s.supplies, not (me.settings and me.settings.supplyList == false))
  s.adapters = list(adapterStates())
  s.addons = list(addonStates())
  emitAddons('status', s)
  if COMMANDS and not (me.settings and me.settings.commands == false) then s.actions = list(actionNames()) end
  return s
end

local function pairing(name)
  local pair = readJson(me.dir .. '/inbox/pair.json')
  me.answered = me.answered or pair ~= nil
  me.pair = pair
  if pair and pair.paired then
    if me.shownCode and not me.saidPaired then say(name .. ' is connected to your Voidwatch account.') end
    me.saidPaired = true
    return true
  end
  me.saidPaired = false
  if pair and pair.code and pair.code ~= me.shownCode then
    me.shownCode = pair.code
    say(('pairing code %s. Open %s to add %s to your account.'):format(pair.code, pair.url or 'voidwatch.xyz', name))
  elseif not me.answered and not me.hinted and g_clock.millis() - me.since > SETUP_HINT_MS then
    me.hinted = true
    say('the upload script did not answer. Run the Voidwatch setup once. If it does not find this client, give it '
        .. 'this folder: ' .. g_resources.getWriteDir() .. ROOT:sub(2))
  end
  return false
end

local function serverNow()
  if me.serverAt and me.serverLocal then return me.serverAt + (os.time() - me.serverLocal) end
  return os.time()
end

local function inboxFiles()
  local files = {}
  local ok, list = pcall(g_resources.listDirectoryFiles, me.dir .. '/inbox')
  for _, f in ipairs(ok and type(list) == 'table' and list or {}) do
    f = tostring(f)
    if f == 'commands.json' or f:match('^commands%-[%w%-]+%.json$') then files[#files + 1] = f end
  end
  table.sort(files)
  return files
end

function addResults(results)
  local path = me.dir .. '/outbox/results.json'
  local ok, old = pcall(json.decode, read(path) or '[]')
  local all = ok and type(old) == 'table' and old or {}
  for _, r in ipairs(results) do all[#all + 1] = r end
  write(path, json.encode(all))
end

local ran, ranOrder = {}, {}
local function runCommands()
  local results = {}
  for _, f in ipairs(inboxFiles()) do
    local path = me.dir .. '/inbox/' .. f
    local ok, cmds = pcall(json.decode, read(path) or '')
    pcall(g_resources.deleteFile, path)
    for _, c in ipairs(ok and type(cmds) == 'table' and cmds or {}) do
      local id = type(c) == 'table' and tonumber(c.id)
      if id and not ran[id] then
        ran[id], ranOrder[#ranOrder + 1] = true, id
        if #ranOrder > 200 then ran[table.remove(ranOrder, 1)] = nil end
        local done, message, later = false, 'not supported on this client', false
        if serverNow() - (tonumber(c.createdAt) or 0) > COMMAND_TTL then
          message = 'too old: sent more than a minute ago'
        elseif me.settings and me.settings.commands == false then
          message = 'commands are off for this client'
        else
          local fn = action(c.action)
          if fn then
            local okRun, res, msg = pcall(fn, type(c.args) == 'table' and c.args or {}, { id = id })
            done, message, later = okRun and res ~= false, okRun and msg or tostring(res), okRun and res == 'pending'
          end
        end
        if not later then results[#results + 1] = { id = id, ok = done, message = message and tostring(message):sub(1, 200) or nil } end
      end
    end
  end
  if #results > 0 then addResults(results) end
end


local function step()
  if g_resources.fileExists(ROOT .. '/off') or not g_game.isOnline() then return end
  local p = g_game.getLocalPlayer()
  local name = p and p:getName()
  if not name or name == '' then return end
  if me.key ~= keyOf(name) then
    flushLedger(true)
    me = { key = keyOf(name), lastStatus = -math.huge, lastShot = -math.huge, since = g_clock.millis() }
    me.dir = ROOT .. '/' .. me.key
    for _, d in ipairs({ ROOT, me.dir, me.dir .. '/outbox', me.dir .. '/inbox' }) do pcall(g_resources.makeDir, d) end
    loadLedger()
    if not prices then prices = readPrices() end
    lastLeft = {}
    local saved = readJson(me.dir .. '/carried.json')
    carried, carriedDirty = type(saved) == 'table' and saved or {}, false
    startAdapters()
    scanAddons(true)
    emitAddons('login', name)
  end
  local now0 = g_clock.millis()
  if me.lastTick then
    ledger.onlineS = ledger.onlineS + math.min(10000, now0 - me.lastTick) / 1000
    ledgerDirty = true
  end
  me.lastTick = now0
  if exiva.pending and now0 - exiva.pending.t > EXIVA_ANSWER_MS then
    local p = exiva.pending
    exiva.pending = nil
    if p.team then
      addResults({ { id = p.id, ok = false, message = p.last and ('no answer, the game said: ' .. p.last) or 'no answer from the game' } })
    end
  end
  flushLedger(false)
  local paired = pairing(name)
  -- the reply carries the server time, so a new text means the upload script got an answer just now
  local replyText = paired and read(me.dir .. '/inbox/reply.json') or nil
  local fresh = replyText and replyText ~= me.replyText
  if fresh then me.replyText, me.replyAt = replyText, g_clock.millis() end
  local okReply, reply = pcall(json.decode, replyText or '{}')
  reply = okReply and type(reply) == 'table' and reply or {}
  if fresh and tonumber(reply.at) then me.serverAt, me.serverLocal = tonumber(reply.at), os.time() end
  me.reply = reply
  local saved = type(reply.settingsSaved) == 'table' and reply.settingsSaved
  if saved and me.change and tonumber(saved.rev) == me.change.rev then
    me.saved = { ok = saved.ok ~= false, error = saved.error and tostring(saved.error):sub(1, 200) or nil, at = g_clock.millis() }
    me.change = nil
  end
  me.settings = withChange(type(reply.settings) == 'table' and reply.settings or {})
  if fresh then emitAddons('reply', reply) end
  local now = g_clock.millis()
  local every = me.change and SETTINGS_RESEND_S or tonumber(reply.statusEvery) or 30
  if now - me.lastStatus >= every * 1000 then
    local s = state(p)
    if s then
      if me.change then s.settingsChange = { rev = me.change.rev, values = me.change.values } end
      me.lastStatus, me.last = now, s
      if not paired then
        local host, world, version = origin()
        write(me.dir .. '/outbox/pair-request.json', json.encode({ character = name, server = field('server') or SERVER,
          platform = platform(), module = MODULE, host = host, world = world, clientVersion = version }))
      end
      write(me.dir .. '/outbox/status.json', json.encode(s))
    end
  end
  if CAPTURES and paired and me.settings.captures ~= false and now - me.lastShot >= (tonumber(reply.captureEvery) or 60) * 1000 then
    me.lastShot = now
    g_app.doMapScreenshot(me.dir .. '/outbox/capture.png')
  end
  if COMMANDS and paired then runCommands() end
end

local checkUpdates   -- below, with the window's actions
local ensureStartFile   -- below, with the bot adapter

local function tick()
  loopEvent = nil
  if not alive or halted then return end
  pcall(checkUpdates)
  loops = loops + 1
  if loops % GUARD_EVERY == 0 then
    guard()
    if halted then return end
  end
  pcall(ensureStartFile)
  pcall(scanAddons)
  local ok, err = pcall(step)
  if ok then
    errors = 0
  else
    errors = errors + 1
    if tostring(err) ~= lastError then log('error: ' .. tostring(err)) end
    lastError = tostring(err)
    if errors >= MAX_ERRORS then return halt(MAX_ERRORS .. ' errors in a row, the last one: ' .. lastError) end
  end
  changed()
  if alive then loopEvent = scheduleEvent(tick, LOOP_MS) end
end

-- actions every client can run without an adapter
Voidwatch.actions.capture = function() me.lastShot = -math.huge; return true end
Voidwatch.actions.reset_loot = function()
  if not ledger then return false, 'not logged in' end
  Voidwatch.resetLoot()
  return true, 'loot, supplies and time reset'
end
-- a team cast: at once, also in a fight, but not below half HP, since a spell can hold back a heal for a second
Voidwatch.actions.cast_exiva = function(args, ctx)
  local p = g_game.getLocalPlayer()
  local target = type(args.target) == 'string' and args.target or ''
  if not p then return false, 'not logged in' end
  if not (me.settings and me.settings.exiva) then return false, 'Team exiva is off for this client' end
  if target == '' or #target > 30 or target:find('["\r\n]') then return false, 'no valid target' end
  if p:getHealth() < p:getMaxHealth() * 0.5 then return false, 'HP below 50%' end
  if p:getMana() < EXIVA_MANA then return false, 'not enough mana' end
  local now = g_clock.millis()
  if exiva.pending then return false, 'another exiva waits for its answer' end
  if now - exiva.last < EXIVA_GAP_MS then return false, 'cast less than 5 s ago' end
  local at = p:getPosition()
  local cast = { id = ctx and ctx.id, team = true, name = target, target = target:lower(), pos = { x = at.x, y = at.y, z = at.z }, t = now, tries = 0 }
  exiva.pending, exiva.last, exiva.team = cast, now, { target = cast.target, t = now }
  say(('exiva on %s for %s.'):format(target, tostring(args.by or 'your team')))
  exivaCast(cast)
  return 'pending'
end
Voidwatch.actions.exiva_show = function(args)
  emitAddons('exiva', args)
  local target = tostring(args.target or '?')
  if args.partial then
    if args.first then say(('exiva %s: first area from %d answers, more coming.'):format(target, tonumber(args.answers) or 0)) end
    return true, 'updated'
  end
  local x, y = tonumber(args.x), tonumber(args.y)
  if not x or not y then
    say(('exiva %s: no answer came back%s.'):format(target, args.why and (', ' .. tostring(args.why)) or ''))
    return true, 'no area'
  end
  local zmin, zmax = tonumber(args.zmin), tonumber(args.zmax)
  local floor = not zmin and 'floor unknown' or zmin == zmax and ('floor ' .. zmin) or ('floor ' .. zmin .. ' to ' .. zmax)
  local n, agree, more = tonumber(args.answers) or 0, tonumber(args.agree), (tonumber(args.areas) or 1) - 1
  say(('exiva %s: around %d, %d, %s, within %d sqm, %s%s.'):format(target, x, y, floor, tonumber(args.radius) or 0,
    agree and agree < n and ('%d of %d answers agree'):format(agree, n) or ('answers: %d'):format(n), more == 1 and ', 1 more area' or more > 1 and (', %d more areas'):format(more) or ''))
  return true, 'shown'
end
Voidwatch.actions.addon_install = function(args)
  local id = type(args.addon) == 'string' and args.addon:match('^[%w%-]+$')
  if not id then return false, 'no valid addon' end
  return setWanted(id, true), 'the upload script installs it for every client in this folder'
end
Voidwatch.actions.addon_remove = function(args)
  local id = type(args.addon) == 'string' and args.addon:match('^[%w%-]+$')
  if not id then return false, 'no valid addon' end
  return setWanted(id, false), 'removed for every client in this folder'
end
Voidwatch.actions.logout_in_pz = function()
  local p = g_game.getLocalPlayer()
  if p and inPz(p) then g_game.safeLogout(); return true end
  return false, 'not in a protection zone'
end

-- a second register with the same id replaces the first, so a reloaded adapter file does not run twice
function Voidwatch.register(def)
  if type(def) ~= 'table' or type(def.id) ~= 'string' or def.id == '' then return false end
  local old = adapters[def.id]
  if old then
    if old.running and old.def.terminate then pcall(old.def.terminate) end
  else
    order[#order + 1] = def.id
  end
  adapters[def.id] = { def = def, running = false, off = false, errors = 0 }
  if alive and me.key then startAdapters() end
  return true
end

local function botConfig()
  local ok, name = pcall(function() return modules.game_bot.contentsPanel.config:getCurrentOption().text end)
  return ok and type(name) == 'string' and name ~= '' and name or nil
end

function bundledBot()
  for _, home in ipairs(HOMES) do
    local src = read(home .. 'bot/voidwatch_bot.lua')
    if src then return src end
  end
end

-- From the bot folder, the start file is what runs the module and the bot adapter, so every bot config the player
-- picks needs its own copy. It is copied once per config and session.
local startChecked = {}
function ensureStartFile()
  local config = botConfig()
  if not BOT_MODE or not config or startChecked[config] then return end
  startChecked[config] = true
  local target = '/bot/' .. config .. '/' .. START_FILE
  if g_resources.fileExists(target) then return end
  local src = read(HOME .. START_FILE)
  if not (src and write(target, src)) then return end
  addEvent(function()
    local ok = botConfig() == config and pcall(function() modules.game_bot.refresh() end)
    say(ok and ('start file copied to %s, bot reloaded: Voidwatch runs with this config now.'):format(config)
      or ('start file copied to %s. Reload the bot to use the bot commands.'):format(config))
  end)
end

local botRefreshed = false
local function refreshBot(def)
  if botRefreshed or BOT_MODE then return end
  local src = bundledBot()
  local want = src and tonumber(src:match("local VERSION = '(%d+)'"))
  local config = botConfig()
  if not want or not config or (tonumber(def.version) or 0) >= want then return end
  botRefreshed = true
  if write('/bot/' .. config .. '/voidwatch_bot.lua', src) then
    say(('bot adapter %d copied to %s. Reload the bot to use the bot commands.'):format(want, config))
  end
end

function Voidwatch.labelRoles()
  return type(me.settings) == 'table' and type(me.settings.labels) == 'table' and me.settings.labels or {}
end

function Voidwatch.planWait()
  local m = type(me.settings) == 'table' and tonumber(me.settings.planWait)
  return m and math.max(5, math.min(120, math.floor(m))) or 20
end

-- false: no character yet, so the bot asks again
function Voidwatch.loadPlan()
  if not me.dir then return false end
  return readJson(me.dir .. '/plan.json')
end

function Voidwatch.savePlan(plan)
  if not me.dir then return false end
  if plan == nil then return pcall(g_resources.deleteFile, me.dir .. '/plan.json') end
  return write(me.dir .. '/plan.json', json.encode(plan))
end

function Voidwatch.cancelPlan()
  local fn = action('cancel_plan')
  if fn then return fn({}) end
  return false
end

local function onGameEnd()
  if me.dir then pcall(g_resources.deleteFile, me.dir .. '/plan.json') end
  emitAddons('logout')
end

function Voidwatch.attachBot(def)
  if type(def) ~= 'table' then return false end
  if bot and bot.def == def then bot.at = g_clock.millis(); return true end
  bot = { def = def, at = g_clock.millis(), errors = 0 }
  refreshBot(def)
  return true
end

function Voidwatch.init()
  alive, halted, loops, errors, lastError, me, bot = true, nil, 0, 0, nil, {}, nil
  ledger, ledgerDirty, prices = nil, false, nil
  connect(g_game, { onTextMessage = onTextMessage, onOpenNpcTrade = onOpenNpcTrade, onGameEnd = onGameEnd })
  baseKB = collectgarbage('count')
  heap = { baseKB }
  loopEvent = scheduleEvent(tick, LOOP_MS)
  if Voidwatch.ui and Voidwatch.ui.init then pcall(Voidwatch.ui.init) end
  log(('%s loaded, Lua heap %d MB'):format(MODULE, math.floor(baseKB / 1024)))
end

function Voidwatch.terminate()
  alive = false
  if Voidwatch.ui and Voidwatch.ui.terminate then pcall(Voidwatch.ui.terminate) end
  stopAdapters()
  stopAllAddons()
  disconnect(g_game, { onTextMessage = onTextMessage, onOpenNpcTrade = onOpenNpcTrade, onGameEnd = onGameEnd })
  flushLedger(true)
  if loopEvent then removeEvent(loopEvent) end
  loopEvent = nil
end


-- console helpers, see the top of the file. The bot file goes in only when the player asks for it.
function Voidwatch.installBot()
  local config = botConfig()
  if not config then return say('no bot config is selected in the bot window.') end
  if BOT_MODE then
    startChecked[config] = nil
    ensureStartFile()
    return say('from the bot folder, the start file in ' .. config .. ' runs the bot adapter.')
  end
  local src = bundledBot()
  if not src then return say('the bot adapter is missing from the module folder.') end
  if write('/bot/' .. config .. '/voidwatch_bot.lua', src) then
    say('bot adapter added to ' .. config .. '. Reload the bot, or log in again, to start it.')
  end
end

function Voidwatch.removeBot()
  local config = botConfig()
  if not config then return say('no bot config is selected in the bot window.') end
  pcall(g_resources.deleteFile, '/bot/' .. config .. '/voidwatch_bot.lua')
  bot = nil
  say('bot adapter removed from ' .. config .. '. Reload the bot to stop it.')
end

function Voidwatch.resetLoot()
  if not ledger then return say('log in first.') end
  ledger, ledgerDirty, lastLeft = newLedger(), true, {}
  carried, carriedDirty = {}, false
  write(me.dir .. '/carried.json', '{}')
  flushLedger(true)
  say('loot, supply and time counters reset.')
end

function Voidwatch.stop()
  Voidwatch.terminate()
  say('stopped from the console. Reload the module to start it again.')
end

-- the window: what this client does now, read-only, and three actions
local GIVES = { { 'server', 'server' }, { 'blessed', 'blessings' }, { 'tasks', 'tasks' }, { 'taskPoints', 'task points' },
                { 'redemption', 'death redemption' }, { 'loot', 'the autoloot list' }, { 'route', 'route' }, { 'routeOn', 'cavebot' },
                { 'targetOn', 'targetbot' } }

local function gives(has)
  local out = {}
  for _, g in ipairs(GIVES) do if has(g[1]) then out[#out + 1] = g[2] end end
  return table.concat(out, ', ')
end

local function sources()
  local out = {}
  for _, id in ipairs(order) do
    local rec = adapters[id]
    if rec.running then
      out[#out + 1] = { name = tostring(rec.def.name or id), on = true, gives = gives(function(f) return provides(rec.def, f) end) }
    end
  end
  if bot then
    local f = type(bot.def.fields) == 'table' and bot.def.fields or {}
    local text = gives(function(name) return f[name] ~= nil and name ~= 'server' end)
    if me.last and me.last.suppliesSource == 'bot' then text = text .. (text ~= '' and ', ' or '') .. 'supply list' end
    out[#out + 1] = { name = 'Bot - ' .. tostring(me.last and me.last.botConfig or bot.def.id or 'bot'), on = freshBot() ~= nil, gives = text }
  end
  out[#out + 1] = { name = 'Client', on = true, gives = 'level, exp/h, loot and supplies from the game messages' }
  return out
end

local function stateOf()
  if g_resources.fileExists(ROOT .. '/off') then return 'off' end
  if halted then return 'stopped' end
  if not g_game.isOnline() then return 'offline' end
  if me.saidPaired then return 'connected' end
  return me.pair and me.pair.code and 'pairing' or 'waiting'
end
Voidwatch.state = stateOf

-- updates: the upload script fetches a release from GitHub and swaps the folder; the module only reads its notes and
-- writes requests, so the game client still makes no web request
local RUNNING = MODULE:match('/(.+)$') or MODULE
local upd = { at = -math.huge }
local function vnum(v)
  local a, b, c = tostring(v or ''):match('^(%d+)%.(%d+)%.(%d+)')
  return a and (tonumber(a) * 1000000 + tonumber(b) * 1000 + tonumber(c)) or 0
end
local function who() return g_game.isOnline() and g_game.getCharacterName() or '' end
local function filesVersion()
  for _, home in ipairs(HOMES) do
    local text = read(home .. 'voidwatch.otmod')
    if text then return text:match('version:%s*([%d%.]+)') end
  end
end
local function reloadSelf()
  if Voidwatch.ui and Voidwatch.ui.isOpen and Voidwatch.ui.isOpen() then pcall(g_settings.set, 'voidwatch-reopen', true) end
  -- on the next frame, outside the module's own call stack
  local boot = BOT_MODE and modules._G and modules._G.VoidwatchBoot
  if boot then return addEvent(function() pcall(boot.restart) end) end
  addEvent(function()
    pcall(g_modules.discoverModules)
    local m = g_modules.getModule('voidwatch')
    if m then pcall(function() m:reload() end) end
  end)
end
function checkUpdates(force)
  if not force and g_clock.millis() - upd.at < 10000 then return end
  upd.at = g_clock.millis()
  local l = readJson(ROOT .. '/latest.json') or {}
  upd.latest = l.latest ~= '' and l.latest or nil
  upd.updatable = l.updatable == true
  upd.backup = l.backup ~= '' and l.backup or nil
  upd.files = filesVersion()
  upd.asked = g_resources.fileExists(ROOT .. '/update-request.json') or g_resources.fileExists(ROOT .. '/rollback-request.json')
  upd.result = readJson(ROOT .. '/update-result.json')
  -- the client that asked reloads once the files hold another version; the others offer Reload
  local r = upd.result
  if r and r.ok and upd.files and upd.files ~= RUNNING and r.by == who() and not upd.reloading then
    upd.reloading = true
    say(('the files are version %s now, reloading.'):format(upd.files))
    reloadSelf()
  end
end

function Voidwatch.update()
  checkUpdates(true)
  if not upd.latest or not upd.updatable or vnum(upd.latest) <= vnum(RUNNING) then return false end
  pcall(g_resources.deleteFile, ROOT .. '/update-result.json')
  write(ROOT .. '/update-request.json', json.encode({ version = upd.latest, by = who() }))
  upd.asked = true
  changed()
  return true
end

function Voidwatch.rollback()
  checkUpdates(true)
  if not upd.backup or not upd.updatable then return false end
  pcall(g_resources.deleteFile, ROOT .. '/update-result.json')
  write(ROOT .. '/rollback-request.json', json.encode({ by = who() }))
  upd.asked = true
  changed()
  return true
end

function Voidwatch.reloadFiles() reloadSelf() end

function Voidwatch.view()
  checkUpdates()
  local now = g_clock.millis()
  local p = g_game.isOnline() and g_game.getLocalPlayer() or nil
  for _, id in ipairs(order) do
    if adapters[id].running and provides(adapters[id].def, 'server') and adapters[id].def.name then me.serverName = adapters[id].def.name break end
  end
  local okMem, bytes = pcall(g_platform.getMemoryUsage)
  local settings = me.settings or {}
  local full = {}
  for k, v in pairs(SETTING_DEFAULTS) do full[k] = v end
  for k, v in pairs(settings) do if SETTING_KINDS[k] then full[k] = v end end
  return {
    state = stateOf(), version = MODULE:match('/(.+)$') or MODULE, stopped = halted,
    character = p and p:getName() or nil, server = me.serverName or (g_game.getWorldName and g_game.getWorldName()) or nil,
    code = me.pair and me.pair.code or nil, url = me.pair and me.pair.url or nil, expiresAt = me.pair and tonumber(me.pair.expiresAt) or nil,
    answered = me.answered == true, replyS = me.replyAt and math.floor((now - me.replyAt) / 1000) or nil,
    statusEvery = tonumber(me.reply and me.reply.statusEvery), captureEvery = tonumber(me.reply and me.reply.captureEvery),
    captures = CAPTURES and settings.captures ~= false, supplyList = settings.supplyList ~= false,
    suppliesSource = me.last and me.last.suppliesSource or nil, commands = COMMANDS,
    routeName = me.last and me.last.route or nil, phase = me.last and me.last.phase or nil, labelsMissing = me.last and me.last.labelsMissing or nil,
    plan = p and field('plan') or nil,
    addons = addonView(), addonsOff = g_resources.fileExists(ROOT .. '/addons-off'),
    addonCatalog = me.reply and type(me.reply.addonCatalog) == 'table' and me.reply.addonCatalog or {},
    settings = full, settingsPending = me.change ~= nil,
    settingsSaved = me.saved and { ok = me.saved.ok, error = me.saved.error, ago = math.floor((now - me.saved.at) / 1000) } or nil,
    heapMB = math.floor(collectgarbage('count') / 1024), clientMB = okMem and type(bytes) == 'number' and mb(bytes) or nil,
    errors = errors, lastError = lastError, sources = sources(), dir = g_resources.getWriteDir() .. ROOT:sub(2),
    update = {
      running = RUNNING, latest = upd.latest, files = upd.files, backup = upd.backup, asked = upd.asked,
      canUpdate = upd.updatable and vnum(upd.latest) > vnum(RUNNING) and not upd.asked,
      byHand = not upd.updatable and vnum(upd.latest) > vnum(RUNNING),
      needsReload = vnum(upd.files) > 0 and upd.files ~= RUNNING and not upd.asked,
      canRollback = upd.updatable and upd.backup ~= nil and upd.backup ~= RUNNING and not upd.asked,
      error = upd.result and upd.result.ok == false and tostring(upd.result.error) or nil,
    },
  }
end

function Voidwatch.installAddon(id) return Voidwatch.actions.addon_install({ addon = id }) end
function Voidwatch.removeAddon(id) return Voidwatch.actions.addon_remove({ addon = id }) end

function Voidwatch.setAddonHere(id, on)
  id = type(id) == 'string' and id:match('^[%w%-]+$')
  if not id or not me.dir then return false end
  local off, ids = offHere(), {}
  off[id] = not on or nil
  for x in pairs(off) do ids[#ids + 1] = x end
  table.sort(ids)
  local ok = write(me.dir .. '/addons-off.json', json.encode({ ids = ids }))
  scanAddons(true)
  return ok
end

-- also starts an addon again after its errors stopped it
function Voidwatch.reloadAddon(id)
  local rec = addons[id]
  if not rec or rec.here == false or g_resources.fileExists(ROOT .. '/addons-off') then return false end
  loadAddon(id, rec.version)
  return rec.loaded == true and not rec.off
end

function Voidwatch.openAddon(id)
  local rec = addons[id]
  local fn = rec and rec.loaded and (rec.handlers.open or rec.openFn)
  return fn and addonCall(rec, fn) or false
end

function Voidwatch.setAddonSetting(id, key, value)
  local rec, file = addons[id], me.dir and (me.dir .. '/addon-settings.json')
  if not rec or not file then return false end
  local decl
  for _, s in ipairs(declaredSettings(rec)) do
    if s.key == key then decl = s end
  end
  if decl and decl.type == 'number' then value = tonumber(value) end
  if not decl or not settingFits(decl, value) then return false end
  local all = readJson(file) or {}
  all[id] = type(all[id]) == 'table' and all[id] or {}
  all[id][key] = value
  if not write(file, json.encode(all)) then return false end
  local fn = rec.loaded and rec.handlers.settings
  if fn then addonCall(rec, fn, addonSettings(rec)) end
  return true
end

function Voidwatch.picturePath(id, file) return ADDON_PICTURES .. '/' .. tostring(id) .. '/' .. tostring(file) end

-- asks the upload script for the pictures the website lists for an addon and this folder does not have, at most once a minute
local pictureAsk = {}
function Voidwatch.wantPictures(id, pictures)
  if type(id) ~= 'string' or not id:match('^[%w%-]+$') or type(pictures) ~= 'table' then return false end
  local now = g_clock.millis()
  if pictureAsk[id] and now - pictureAsk[id] < 60000 then return false end
  local have, lines = {}, {}
  for _, n in ipairs(pictureFiles(id)) do have[n] = true end
  local prefix = '/static/img/addons/' .. id .. '/'
  for _, pic in ipairs(pictures) do
    local src = type(pic) == 'table' and tostring(pic.src or '') or ''
    local file = src:sub(1, #prefix) == prefix and src:sub(#prefix + 1) or ''
    if file:match('^[%w_%-]+%.png$') and not have[file] then lines[#lines + 1] = id .. ' ' .. file .. ' ' .. src end
  end
  if #lines == 0 then return false end
  pictureAsk[id] = now
  return write(ROOT .. '/addon-pictures-wanted.txt', (read(ROOT .. '/addon-pictures-wanted.txt') or '') .. table.concat(lines, '\n') .. '\n')
end

-- the window's Settings tab; the website applies the values with the rules of its Clients page
function Voidwatch.saveSettings(values)
  if type(values) ~= 'table' or not me.dir or not me.saidPaired then return false end
  local merged = me.change and me.change.values or {}
  local any = false
  for k, v in pairs(values) do
    local kind = SETTING_KINDS[k]
    if kind == 'number' then v = tonumber(v) and math.floor(tonumber(v)) or nil end
    if kind == 'table' and type(v) == 'table' then
      local roles = {}
      for _, role in ipairs({ 'hunt', 'refill', 'city', 'resp' }) do roles[role] = type(v[role]) == 'string' and v[role] or '' end
      v = roles
    end
    if kind and type(v) == kind then merged[k], any = v, true end
  end
  if not any then return false end
  me.change = { rev = math.max(os.time(), (me.changeRev or 0) + 1), values = merged }
  me.changeRev, me.saved, me.lastStatus = me.change.rev, nil, -math.huge
  me.settings = withChange(me.settings or {})
  return true
end

-- the off file stops every addon in every client that shares this folder, until it starts them again
function Voidwatch.stopAddons()
  write(ROOT .. '/addons-off', 'stopped in the Voidwatch window\n')
  scanAddons(true)
end
function Voidwatch.startAddons()
  pcall(g_resources.deleteFile, ROOT .. '/addons-off')
  scanAddons(true)
end

function Voidwatch.stopHere()
  if not halted then halt('by you, in the Voidwatch window') end
end

-- the off file stops the module in every client that shares this folder
function Voidwatch.stopAll()
  write(ROOT .. '/off', 'stopped in the Voidwatch window\n')
  changed()
end

function Voidwatch.startAgain()
  if g_resources.fileExists(ROOT .. '/off') then pcall(g_resources.deleteFile, ROOT .. '/off') end
  if halted then
    halted, errors, lastError = nil, 0, nil
    baseKB = collectgarbage('count')
    heap = { baseKB }
    if me.key then startAdapters() end
    say('started again.')
  end
  if alive and not loopEvent then loopEvent = scheduleEvent(tick, LOOP_MS) end
  changed()
end

function Voidwatch.status()
  local ok, bytes = pcall(g_platform.getMemoryUsage)
  local line = ('%s alive=%s halted=%s off=%s character=%s paired=%s status %s s ago, heap %d MB (%+d), client %s MB, errors %d%s'):format(
    MODULE, tostring(alive), tostring(halted or 'no'), tostring(g_resources.fileExists(ROOT .. '/off')),
    tostring(me.key), tostring(me.saidPaired or false),
    me.lastStatus and me.lastStatus > -math.huge and math.floor((g_clock.millis() - me.lastStatus) / 1000) or '-',
    math.floor(collectgarbage('count') / 1024), math.floor((collectgarbage('count') - baseKB) / 1024),
    ok and type(bytes) == 'number' and mb(bytes) or '?', errors, lastError and (', last: ' .. lastError) or '')
  print(line)
  return line
end

voidwatch/orion.lua

-- Orion-OTS server adapter. It runs only in the Orion client, which the module knows by its login address.
-- Orion never sends the blessings to the client, so getBlessings() always reads 0. The server's text reply to
-- !bless is the one source: whoever says it, the player or a bot, the adapter reads the reply. It never says !bless
-- itself, because that buys. A death means a relog, so every login starts unknown.
local FAIL = { 'not enough', "don't have enough", 'do not have enough', 'cannot', "can't", 'you need' }
local blessed, owner

local function has(text, words)
  for _, w in ipairs(words) do if text:find(w, 1, true) then return true end end
  return false
end

local function onText(mode, text)
  if type(text) ~= 'string' then return end
  local low = text:lower()
  if not low:find('bless', 1, true) then return end
  owner, blessed = g_game.getCharacterName(), not has(low, FAIL)
end

local function onStart() owner, blessed = nil, nil end

Voidwatch.register({
  id = 'orion-ots', name = 'Orion-OTS', version = '3',
  match = { hosts = { 'orion-ots.pl' } },
  provides = { 'server', 'blessed' },
  fields = {
    server = function() return 'orion' end,
    blessed = function() if owner == g_game.getCharacterName() then return blessed end end,
  },
  init = function() connect(g_game, { onTextMessage = onText, onGameStart = onStart }) end,
  terminate = function() disconnect(g_game, { onTextMessage = onText, onGameStart = onStart }) end,
})

voidwatch/orion_autoloot.lua

-- Orion-OTS autoloot adapter. Orion's autoloot prints what went into the bags, "Autoloot: 5x platinum coin, 7x gold
-- coin.", and the gold it sends straight to the bank, "Auto-loot: 200 gp trafilo do banku (+100 gp z talentu
-- Bogactwo)." The banked sum already holds the talent's part. While it runs, its count wins over the loot messages.
local vw
-- Orion's own notices come the same way; they are no items. 0.5.2 took every part without a count for one of them
local NOTICES = { 'brak miejsca', 'czesc lupu' }
local function notice(s)
  for _, n in ipairs(NOTICES) do if s:sub(1, #n) == n then return true end end
  return false
end

local function onTextMessage(mode, text)
  if not vw or type(text) ~= 'string' then return end
  local body = text:match('^Autoloot:%s*(.+)$')
  if body then
    for part in body:gsub('%.%s*$', ''):gmatch('[^,]+') do
      local p = part:gsub('^%s+', ''):gsub('%s+$', '')
      -- "5x platinum coin", or one item without a count, "fire sword". A notice books nothing and takes back an entry
      -- that 0.5.1 booked; the list's fill ("9/13 slotow") holds digits, which no name has
      local n, name = p:match('^(%d+)x%s+(.+)$')
      name = (name or p):lower()
      if notice(name) then
        if vw.dropLoot then vw.dropLoot(name) end
      elseif name:match("^%a[%a%s'%-]*$") then
        vw.addLoot(name, tonumber(n) or 1)
      end
    end
    return
  end
  local gp = tonumber(text:match('^Auto%-loot:%s*(%d+)%s*gp'))
  if gp then vw.addLoot('gold coin', gp) end
end

Voidwatch.register({
  id = 'orion-ots-autoloot', name = 'Orion autoloot', version = '3',
  match = { hosts = { 'orion-ots.pl' } },
  provides = { 'loot' },
  init = function(api)
    vw = api
    connect(g_game, { onTextMessage = onTextMessage })
  end,
  terminate = function()
    disconnect(g_game, { onTextMessage = onTextMessage })
    vw = nil
  end,
})

voidwatch/orion_tasks.lua

-- Orion-OTS tasks adapter. Orion sends its task data as JSON on extended opcode 30: "refreshTrackerKills" and
-- "refreshTracker" while tasks run, "open" (every task, killed -1 when not taken) and "getMonsterInfo" (the
-- rewards per goal) when the tasks window opens, "refreshPoints" for the task points. The adapter wraps the client's
-- packet dispatcher, not the tasks module's own callback, so it cannot clash with a bot that taps that one. It
-- passes every packet on first and only reads.
-- Death redemption is an item of the task shop's "consum" page. The page arrives only when asked for, so the
-- adapter asks: every minute while redemption is off or unknown, every 10 minutes while it is on. The task points
-- come only with a claim or with the tasks window, so the adapter asks once per character, with the "open" request
-- that the window sends. Neither window opens.
local original, wrapper
local owner                                             -- the character the data below belongs to
local catalog, goals, active, fromTracker, known = {}, {}, {}, false, false
local points, week
local dr                                                -- { active = bool, left = buys left this week }
local log, lastError, poll = nil, nil, nil
local ASK_ON_MS, ASK_OFF_MS = 600000, 60000

local function me() return g_game.getCharacterName() end

local function onPacket(buffer)
  local ok, data = pcall(json.decode, buffer)
  if not ok or type(data) ~= 'table' or type(data.data) ~= 'table' then return end
  if owner ~= me() then
    owner, catalog, goals, active, fromTracker, known, points, week, dr = me(), {}, {}, {}, false, false, nil, nil, nil
  end
  local action, list = data.action, data.data
  if action == 'refreshTrackerKills' or action == 'refreshTracker' then
    local now = {}
    for _, e in pairs(list) do
      if type(e) == 'table' and e.name then
        now[tostring(e.name):lower()] = { name = tostring(e.name), have = tonumber(e.currentKills) or 0, want = tonumber(e.required) or 0 }
      end
    end
    active, fromTracker, known = now, true, true
  elseif action == 'open' then
    local now = {}
    for _, e in pairs(list) do
      if type(e) == 'table' and e.name then
        local key = tostring(e.name):lower()
        catalog[key] = { exp = tonumber(e.expReward), want = tonumber(e.required) }
        local killed = tonumber(e.killed)
        if killed and killed >= 0 then now[key] = { name = tostring(e.name), have = killed, want = tonumber(e.required) or 0 } end
      end
    end
    -- the tracker is the live count; the window list only stands in until the first tracker packet
    if not fromTracker then active, known = now, true end
  elseif action == 'getMonsterInfo' then
    for _, e in pairs(list) do
      if type(e) == 'table' and e.name and type(e.goals) == 'table' then
        local g = {}
        for kills, v in pairs(e.goals) do
          if tonumber(kills) and type(v) == 'table' then g[tonumber(kills)] = { exp = tonumber(v.exp), taskPoints = tonumber(v.taskPts) } end
        end
        goals[tostring(e.name):lower()] = g
      end
    end
  elseif action == 'shopCategoryData' and type(list.items) == 'table' then
    for _, it in pairs(list.items) do
      if type(it) == 'table' and it.key == 'redemption' then
        local desc = tostring(it.desc or '')
        -- "2/week left"; some labels come translated, then the weekly cap in the text minus this week's buys
        local left = tonumber(tostring(it.limitLabel or ''):match('(%d+)%s*/%s*week'))
        local cap = tonumber(desc:match('%((%d+)%s*/%s*week%)'))
        if not left and cap and tonumber(it.boughtThisWeek) then left = math.max(0, cap - tonumber(it.boughtThisWeek)) end
        dr = { active = it.owned == true or desc:upper():find('[ACTIVE', 1, true) ~= nil, left = left }
      end
    end
  elseif action == 'refreshPoints' then
    points = tonumber(list.taskPoints)
    local earned, cap = tonumber(list.weeklyEarned), tonumber(list.weeklyCap)
    week = (earned and cap) and { earned = earned, cap = cap } or nil
  end
end

local function send(action, data)
  local proto = g_game.isOnline() and g_game.getProtocolGame()
  if proto then proto:sendExtendedOpcode(30, json.encode({ action = action, data = data })) end
end

-- checked every minute, so a redemption that turns off is asked about again within a minute
local askedAt, openedFor
local function tick()
  if g_game.isOnline() and openedFor ~= me() then
    openedFor = me()
    pcall(send, 'open', {})
  end
  local wait = (owner == me() and dr and dr.active) and ASK_ON_MS or ASK_OFF_MS
  if g_game.isOnline() and (not askedAt or g_clock.millis() - askedAt >= wait) then
    askedAt = g_clock.millis()
    local ok, err = pcall(function()
      send('shopOpen', {})
      scheduleEvent(function() pcall(send, 'shopCategory', { page = 1, category = 'consum' }) end, 400)
    end)
    if not ok and log then log('orion-ots-tasks: ' .. tostring(err)) end
  end
  poll = scheduleEvent(tick, ASK_OFF_MS)
end

-- nil until Orion said which tasks run: an empty list then means none, which is how the website sees a task end
local function tasks()
  if owner ~= me() or not known then return nil end
  local out = {}
  for key, t in pairs(active) do
    local goal = goals[key] and goals[key][t.want]
    local whole = catalog[key] and catalog[key].want == t.want and catalog[key] or nil
    out[#out + 1] = { name = t.name, have = t.have, want = t.want,
                      exp = (goal and goal.exp) or (whole and whole.exp) or nil, taskPoints = goal and goal.taskPoints or nil }
  end
  table.sort(out, function(a, b) return a.name < b.name end)
  return out
end

local function tap()
  if wrapper or type(ProtocolGame) ~= 'table' or type(ProtocolGame.onExtendedOpcode) ~= 'function' then return end
  original = ProtocolGame.onExtendedOpcode
  local mine
  mine = function(self, opcode, buffer)
    local res = original(self, opcode, buffer)
    if opcode == 30 and wrapper == mine and type(buffer) == 'string' then
      local ok, err = pcall(onPacket, buffer)
      if not ok and tostring(err) ~= lastError and log then log('orion-ots-tasks: ' .. tostring(err)) end
      lastError = not ok and tostring(err) or lastError
    end
    return res
  end
  wrapper = mine
  ProtocolGame.onExtendedOpcode = mine
end

-- if someone wrapped the dispatcher after us, ours stays in their chain but only passes packets on from now
local function untap()
  if wrapper and type(ProtocolGame) == 'table' and ProtocolGame.onExtendedOpcode == wrapper then ProtocolGame.onExtendedOpcode = original end
  wrapper = nil
end

Voidwatch.register({
  id = 'orion-ots-tasks', name = 'Orion tasks', version = '3',
  match = { hosts = { 'orion-ots.pl' } },
  provides = { 'tasks', 'taskPoints', 'taskWeek', 'redemption', 'redemptionLeft' },
  fields = {
    tasks = tasks,
    taskPoints = function() return owner == me() and points or nil end,
    taskWeek = function() return owner == me() and week or nil end,
    redemption = function() if owner == me() and dr then return dr.active end end,
    redemptionLeft = function() if owner == me() and dr then return dr.left end end,
  },
  init = function(vw) log = vw.log; tap(); poll = scheduleEvent(tick, 10000) end,
  terminate = function()
    untap()
    if poll then removeEvent(poll) end
    poll = nil
  end,
})

voidwatch/voidwatch_ui.lua

-- The Voidwatch window: a button in the client's top bar and a window that shows what this client does. The window
-- is built when the button is clicked and destroyed when it closes; only while it is open does it refresh, once a
-- second. It reads Voidwatch.view() and changes nothing but through the actions of the core.
local SITE = 'https://voidwatch.xyz'
local COLOURS = { connected = '#4cd964', pairing = '#f5a623', waiting = '#f5a623', stopped = '#ff5b5b', off = '#ff5b5b', offline = '#777777' }
local GREEN, YELLOW, RED, GREY, FAINT = '#4cd964', '#f5a623', '#ff6b6b', '#777777', '#6f6f6f'
local TABS = { { 'main', 'Main' }, { 'addons', 'Addons' }, { 'settings', 'Settings' } }
local SEND = {
  { 'captures', 'Send screenshots', 'Off: the live view shows the numbers only.' },
  { 'minimap', 'Send my minimap automatically', 'The upload script sends the map files of your client when they change. The website adds them into your own map.' },
  { 'supplyList', "Use the bot's supply list", 'Off: the supply chips show every item from the game\'s "Using one of" lines.' },
  { 'commands', 'Allow commands', 'Off: the client ignores commands from the website.' },
}
local TEAM = {
  { 'exiva', 'Team exiva', 'This character casts exiva when you or your guild ask. Its own exiva in the game starts a team exiva.' },
  { 'exivaShowAll', 'Show every team exiva result', 'Off: only the character that cast first shows the result.' },
  { 'chat', 'Sync private messages', 'Off: private chats stay in the game client.' },
}
local ROLES = { 'hunt', 'refill', 'city', 'resp' }
local WIDTH, HEIGHT, MIN_HEIGHT, SCREEN_GAP, SPACING = 760, 370, 340, 60, 3
local button, dot, win, timer, styled, lastState, site
local pages, tabButtons, shapes, refs = {}, {}, {}, {}
local current = 'main'                                 -- the open tab, kept while the client runs
local detail = nil                                     -- the addon the Addons tab shows
local listScroll = nil                                 -- the addon list's scroll position, put back after a rebuild
local subtab = 'about'                                 -- the part of the addon details that shows
local picIndex = {}                                    -- addon id -> the picture its details show
local form = nil                                       -- the Settings tab while the player edits it
local syncing = false
local render

-- a click that rebuilds a page waits for the next frame: the clicked widget must not go away inside its own event
local function later() addEvent(function() pcall(render) end) end

-- the folder this module sits in: a click runs outside the script, so paths are given in full
local function home()
  for _, dir in ipairs({ Voidwatch.home, '/modules/voidwatch/', '/mods/voidwatch/' }) do
    if dir and g_resources.fileExists(dir .. 'voidwatch.otui') then return dir end
  end
  return Voidwatch.home or '/modules/voidwatch/'
end

local function ago(s)
  if s < 60 then return s .. ' s ago' end
  return math.floor(s / 60) .. ' min ago'
end

local function every(s)
  if not s then return '?' end
  if s < 60 then return s .. ' s' end
  return math.floor(s / 60) .. ' min'
end

local function short(text, n)
  text = tostring(text or '')
  return #text > n and (text:sub(1, n - 3) .. '...') or text
end

local function vnum(v)
  local a, b, c = tostring(v or ''):match('^(%d+)%.(%d+)%.(%d+)')
  return a and (tonumber(a) * 1000000 + tonumber(b) * 1000 + tonumber(c)) or 0
end

local function make(style, parent, text)
  local w = g_ui.createWidget(style, parent)
  if text then w:setText(text) end
  return w
end

local function click(w, fn)
  w.onClick = function() pcall(fn); later() end
end

local function line(parent, key, tooltip)
  local w = make('VwLine', parent)
  w.key:setText(key)
  if tooltip then w:setTooltip(tooltip) end
  return w
end

local function kv(parent, key, tooltip)
  local w = make('VwKV', parent)
  w.key:setText(key)
  if tooltip then w:setTooltip(tooltip) end
  return w
end

local function buttons(parent, a, onA, b, onB)
  local w = make('VwButtons', parent)
  w.a:setText(a)
  click(w.a, onA)
  if b then
    w.b:setText(b)
    click(w.b, onB)
  else
    w.b:hide()
    w.a:removeAnchor(AnchorRight)
    w.a:addAnchor(AnchorRight, 'parent', AnchorRight)
    w.a:setMarginRight(0)
  end
  return w
end

local function contentHeight(body)
  local h, n = body:getPaddingTop() + body:getPaddingBottom(), 0
  for _, w in ipairs(body:getChildren()) do
    if w:isExplicitlyVisible() then
      h, n = h + w:getHeight() + w:getMarginTop() + w:getMarginBottom(), n + 1
    end
  end
  return h + math.max(0, n - 1) * SPACING
end

-- a list shows its scroll bar only while its rows are taller than the list
local function scrollIfNeeded(body, scroll)
  if not (body and scroll) or body:isDestroyed() then return end
  local scrolls = contentHeight(body) > body:getHeight()
  if scroll:isVisible() ~= scrolls then
    scroll:setVisible(scrolls)
    body:setMarginRight(scrolls and (scroll:getWidth() + 4) or 0)
  end
end

local function fitWidths(panel)
  for _, w in ipairs(panel:getChildren()) do w:setWidth(panel:getWidth() - w:getMarginLeft() - w:getMarginRight()) end
end

-- header and update bar -------------------------------------------------------------------------------------------

local STATE_TEXT = { connected = 'Connected to your Voidwatch account', pairing = 'Waiting for pairing', waiting = 'Waiting for the upload script',
                     off = 'Stopped for all clients', offline = 'Not logged in' }

local function fillHeader(v)
  local head = win.top.head
  head.name:setText(v.character or 'Not logged in')
  head.server:setText(v.server or '')
  head.stateDot:setBackgroundColor(COLOURS[v.state] or GREY)
  head.stateText:setColor(COLOURS[v.state] or '#dfdfdf')
  head.stateText:setText(STATE_TEXT[v.state] or ('Stopped: ' .. short(v.stopped, 50)))
  head.stateText:setTooltip(v.state == 'stopped' and tostring(v.stopped) or '')
end

-- only when there is something to do: Update, Reload, an update by hand, one under way, or a failed one
local function barOf(u)
  if not u then return nil end
  if u.asked then return 'Updating Voidwatch. The upload script downloads the new version.' end
  if u.needsReload then return 'The files are version ' .. tostring(u.files) .. '.', 'Reload', Voidwatch.reloadFiles end
  if u.canUpdate then return 'Version ' .. tostring(u.latest) .. ' is out.', 'Update', Voidwatch.update end
  if u.byHand then return 'Version ' .. tostring(u.latest) .. ' is out. Update it by hand from voidwatch.xyz.' end
  if u.error then return 'The update failed: ' .. short(u.error, 80) end
end

-- in the footer beside the version, so the window never has to make room for it
local function fillBar(v)
  local link = win.update
  local text, label, action = barOf(v.update)
  link:setVisible(text ~= nil)
  if text then
    local u = v.update
    link:setText(label and (label .. ' to ' .. tostring(u.needsReload and u.files or u.latest)) or (u.asked and 'Updating...' or u.byHand and
      ('Version ' .. tostring(u.latest) .. ' is out') or 'The update failed'))
    link:setColor(u.error and not label and RED or '#ffdd55')
    link:setTooltip(text)
    link.line:setVisible(label ~= nil)
    link.onClick = label and function() pcall(action); later() end or nil
  end
  local u = v.update
  local back = u and u.canRollback and not u.asked
  win.rollback:setVisible(back and true or false)
  if back then win.rollback:setText('Roll back to ' .. tostring(u.backup)) end
end

-- the number of installed addons, in yellow beside the tab's name, over spaces that make room for it
local function setBadge(n)
  local tab = tabButtons.addons
  if not tab or tab.vwCount == n then return end
  tab.vwCount = n
  if not tab.vwBadge then
    local b = g_ui.createWidget('Label', tab)
    b:setColor('#ffdd55')
    b:setPhantom(true)
    b:setTextAutoResize(true)
    b:addAnchor(AnchorRight, 'parent', AnchorRight)
    b:addAnchor(AnchorVerticalCenter, 'parent', AnchorVerticalCenter)
    b:setMarginRight(tab:getPaddingRight() + 3)
    tab.vwBadge = b
  end
  tab.vwBadge:setText(n > 0 and tostring(n) or '')
  tab:setText(n > 0 and ('Addons' .. string.rep(' ', #tostring(n) + 4)) or 'Addons')
  tab:setWidth(tab:getTextSize().width + tab:getPaddingLeft() + tab:getPaddingRight())
end

-- Main tab --------------------------------------------------------------------------------------------------------

local PHASES = { hunting = 'hunting', to_city = 'to city', in_city = 'in city', to_resp = 'to resp', parked = 'parked',
                 stopped = 'stopped', unknown = 'no route labels', town = 'in town', at_check = 'at check', leaving = 'leaving' }

local PLAN_KINDS = { refill = 'Force refill', go_depot = 'Stop in depot', load_route = 'Switch route' }
local PLAN_ENDS = { done = 'done', stuck = 'stuck', cancelled = 'cancelled', taken_over = 'taken over', failed = 'failed' }

local function planText(pl)
  local what = (PLAN_KINDS[pl.kind] or tostring(pl.kind)) .. (pl.route and (' to ' .. short(pl.route, 14)) or '')
  if pl.state ~= 'running' then return (PLAN_ENDS[pl.state] or tostring(pl.state)) .. ': ' .. short(pl.message, 30) end
  local left = tonumber(pl['until']) and math.max(0, math.ceil((pl['until'] - os.time()) / 60))
  return what .. ' - ' .. tostring(pl.message or '') .. (left and (' (' .. left .. ' min left)') or '')
end

local function mainShape(v)
  return table.concat({ v.state, #v.sources, tostring(v.plan and v.plan.state == 'running') }, '|')
end

local function resetButton(b, r)
  local label = b:getText()
  b.onClick = function()
    -- a second click within 3 s confirms: the counters of this session are gone after it
    if r.resetAsked and g_clock.millis() - r.resetAsked < 3000 then
      r.resetAsked = nil
      b:setText(label)
      pcall(Voidwatch.resetLoot)
    else
      r.resetAsked = g_clock.millis()
      b:setText('Click again to reset')
      scheduleEvent(function()
        if not b:isDestroyed() and r.resetAsked then
          r.resetAsked = nil
          b:setText(label)
        end
      end, 3000)
    end
  end
end

local function buildConnected(page, v, r)
  local m = make('VwMainConnected', page)
  local rows = m.client.rows
  r.upload = kv(rows, 'Upload script')
  r.sending = kv(rows, 'Sending', 'The site sets the pace: faster while someone has the dashboard open.')
  r.route = kv(rows, 'Route', 'Where the character is in its route, from the route labels hunt, refill, city and resp.')
  r.route.info:setImageSource(home() .. 'voidwatch_info')
  r.plan = kv(rows, 'Plan', 'A command that waits for a label of the route: force refill, stop in depot or switch route.')
  if v.plan and v.plan.state == 'running' then buttons(rows, 'Cancel the plan', Voidwatch.cancelPlan) end
  r.memory = kv(rows, 'Memory')
  r.errors = kv(rows, 'Errors')
  r.sourceRows, r.sourceScroll = m.sources.rows, m.sources.scroll
  for i in ipairs(v.sources) do r.sources[i] = make('VwSourceLine', m.sources.rows) end
  resetButton(m.client.reset, r)
  m.client.stop.a:setText('Stop this client')
  m.client.stop.b:setText('Stop all clients')
  m.client.stop.b:setColor('#ff8a8a')
  click(m.client.stop.a, Voidwatch.stopHere)
  click(m.client.stop.b, Voidwatch.stopAll)
  r.lists = { rows, m.sources.rows }
end

local function buildOther(page, v, r)
  local o = make('VwMainOther', page)
  local body = o.card.body
  r.lists = { body }
  r.sourceRows, r.sourceScroll = body, o.card.scroll
  if v.state == 'pairing' then
    r.code = make('VwCode', body)
    r.expires = line(body, 'Code expires')
    local row
    local copied = function(what, text, key, label)
      g_window.setClipboardText(text or '')
      r.copied, r.copiedAt = what, g_clock.millis()
      local b = row and row[key]
      if b then
        local colour = b:getColor()
        b:setText('Copied')
        b:setColor(GREEN)
        scheduleEvent(function()
          if not b:isDestroyed() then
            b:setText(label)
            b:setColor(colour)
          end
        end, 2000)
      end
    end
    row = buttons(body, 'Copy code', function() copied('Code copied.', v.code, 'a', 'Copy code') end,
      'Copy link', function() copied('Link copied.', v.url, 'b', 'Copy link') end)
    buttons(body, 'Open the link', function() if v.url then g_platform.openUrl(v.url) end end)
    r.howto = make('VwText', body)
    make('VwSeparator', body)
    r.upload = line(body, 'Upload script')
    r.memory = line(body, 'Memory')
    buttons(body, 'Stop this client', Voidwatch.stopHere, 'Stop all clients', Voidwatch.stopAll)
  elseif v.state == 'waiting' then
    make('VwText', body, 'The upload script has not answered yet. Run the Voidwatch setup once. If it does not find this '
      .. 'client, give it this folder: ' .. tostring(v.dir))
    r.memory = line(body, 'Memory')
    buttons(body, 'Stop this client', Voidwatch.stopHere, 'Stop all clients', Voidwatch.stopAll)
  elseif v.state == 'stopped' or v.state == 'off' then
    make('VwText', body, v.state == 'off' and 'Every client that shares this folder sends nothing until it starts again.'
      or 'This client sends nothing until it starts again. The game itself is not affected.')
    buttons(body, v.state == 'off' and 'Start all clients again' or 'Start again', Voidwatch.startAgain)
    make('VwSeparator', body)
    r.memory = line(body, 'Memory')
    r.errors = line(body, 'Errors')
  else
    make('VwText', body, 'Log in to see this client.')
  end
end

local function buildMain(page, v)
  page:destroyChildren()
  local r = { sources = {} }
  refs.main = r
  if v.state == 'connected' then buildConnected(page, v, r) else buildOther(page, v, r) end
end

local function fillMain(v)
  local r = refs.main
  if not r then return end
  for _, list in ipairs(r.lists or {}) do fitWidths(list) end
  if r.upload then
    r.upload.value:setText(v.replyS and ('answered ' .. ago(v.replyS)) or (v.answered and 'answers' or 'no answer yet'))
  end
  if r.sending then
    r.sending.value:setText(('status %s, %s'):format(every(v.statusEvery),
      v.captures and ('screenshot ' .. every(v.captureEvery)) or 'no screenshots'))
  end
  if r.route then
    local missing = v.phase == 'unknown' and v.labelsMissing
    local phase = v.phase and not missing and PHASES[v.phase] or nil
    local name = v.routeName and short(v.routeName, 26) or nil
    r.route.value:setText(name and phase and (name .. ' - ' .. phase) or name or phase or 'no bot data')
    r.route.info:setVisible(missing and true or false)
    r.route.info:setTooltip(missing and ('Labels missing: ' .. table.concat(v.labelsMissing, ', ')) or '')
  end
  if r.plan then
    r.plan.value:setText(v.plan and short(planText(v.plan), 40) or 'none')
    r.plan:setTooltip(v.plan and planText(v.plan) or 'A command that waits for a label of the route: force refill, stop in depot or switch route.')
  end
  if r.memory then r.memory.value:setText(('Lua %d MB, client %s MB'):format(v.heapMB, tostring(v.clientMB or '?'))) end
  if r.errors then
    r.errors.value:setText(v.errors > 0 and (v.errors .. ', last: ' .. short(v.lastError, 30)) or 'none')
    r.errors:setTooltip(v.lastError and tostring(v.lastError) or '')
  end
  for i, src in ipairs(v.sources) do
    local w = r.sources[i]
    if w then
      w.dot:setBackgroundColor(src.on and GREEN or GREY)
      local gives = src.gives ~= '' and src.gives or '-'
      w.name:setText(short(src.name, 17))
      w.gives:setText(short(gives, math.max(8, math.floor((w:getWidth() - 117) / 6))))
      w:setTooltip(src.name .. ': ' .. gives)
    end
  end
  if r.code then
    r.code:setText(v.code or '')
    local left = v.expiresAt and (v.expiresAt - os.time()) or nil
    r.expires.value:setText(left and left > 0 and ('in %d:%02d'):format(math.floor(left / 60), left % 60) or 'now; a new code comes')
    r.howto:setText((r.copiedAt and g_clock.millis() - r.copiedAt < 3000) and r.copied
      or ('Open the link and sign in. ' .. tostring(v.character or 'This character') .. ' then joins your account.'))
  end
  scrollIfNeeded(r.sourceRows, r.sourceScroll)
end

-- Addons tab ------------------------------------------------------------------------------------------------------

-- the release's addons with their text, then any the folder has that the release no longer lists
local function addonList(v)
  local out, byId = {}, {}
  for _, a in ipairs(v.addonCatalog or {}) do
    if type(a) == 'table' and type(a.id) == 'string' and not byId[a.id] then
      local e = { id = a.id, name = tostring(a.name or a.id), about = tostring(a.about or ''), points = type(a.points) == 'table' and a.points or {},
                  plan = a.plan, size = tonumber(a.size), latest = a.version, pictures = type(a.pictures) == 'table' and a.pictures or {} }
      byId[a.id] = e
      out[#out + 1] = e
    end
  end
  for _, st in ipairs(v.addons or {}) do
    local e = byId[st.id]
    if not e then
      e = { id = st.id, name = st.id, about = '', points = {}, pictures = {} }
      byId[st.id] = e
      out[#out + 1] = e
    end
    e.st = st
    -- the addon's own addon.json fills what the website does not send
    local info = type(st.info) == 'table' and st.info or {}
    if e.name == e.id and type(info.name) == 'string' then e.name = info.name end
    if e.about == '' and type(info.about) == 'string' then e.about = info.about end
    if #e.points == 0 and type(info.points) == 'table' then e.points = info.points end
    if not e.plan and type(info.plan) == 'string' then e.plan = info.plan end
  end
  for _, e in ipairs(out) do
    e.newer = e.st and e.st.version and e.latest and vnum(e.latest) > vnum(e.st.version) or false
  end
  return out, byId
end

local function addonState(v, e)
  local st = e.st
  if not st then return 'not installed', GREY end
  if v.addonsOff then return 'stopped for all clients', RED end
  if st.here == false then return 'off for this character', FAINT end
  if st.on then return 'runs, ' .. tostring(st.version), GREEN end
  if st.broken then
    if (st.errors or 0) >= 10 then return 'stopped: ' .. st.errors .. ' errors', RED end
    return 'does not load', RED
  end
  if st.error == 'installing' then return 'installing', YELLOW end
  if st.error == 'the download failed' then return 'the download failed', RED end
  return 'stopped', RED
end

-- the addon the details show: the chosen one while it is listed, else the first installed, else the first offered
local function selected(list, byId)
  if detail and byId[detail] then return byId[detail] end
  for _, e in ipairs(list) do if e.st then return e end end
  return list[1]
end

local function addonsShape(v)
  local list, byId = addonList(v)
  local sel = selected(list, byId)
  local parts = { sel and sel.id or '-', tostring(v.addonsOff) }
  for _, e in ipairs(list) do
    local st = e.st or {}
    parts[#parts + 1] = table.concat({ e.id, tostring(e.st ~= nil), tostring(st.here), tostring(st.on), tostring(st.broken), tostring(st.canOpen),
      tostring(e.newer), tostring(#(st.log or {})), tostring(st.error), tostring(st.version), tostring(#e.about), tostring(#(st.settings or {})),
      tostring(#Voidwatch.pictureFiles(e.id)) }, ':')
  end
  return table.concat(parts, '|')
end

local function buildItems(a, v, list, sel)
  local items = a.list.items
  items:destroyChildren()
  local offered = 0
  for _, e in ipairs(list) do
    if e.st then
      local item = make('VwAddonItem', items)
      item.name:setText(e.name)
      item.summary:setText(short(e.about:match('^(.-)[:%.]') or e.about, 22))
      local text, colour = addonState(v, e)
      item.state:setText(text)
      item.state:setColor(colour)
      item.badge:setVisible(e.newer)
      if e.newer then
        item.badge:setText(tostring(e.latest))
        item.badge:setTooltip('A newer version. It comes with the module update.')
      end
      item.here:setChecked(e.st.here ~= false)
      item.here:setEnabled(not v.addonsOff)
      item.here:setTooltip('On for this character')
      item.here.onCheckChange = function(_, on) pcall(Voidwatch.setAddonHere, e.id, on); later() end
      if e == sel then
        item:setBackgroundColor('#ffffff17')
        item:setBorderWidth(1)
        item:setBorderColor('#ffffff21')
      end
      item.onClick = function() detail = e.id; later() end
    end
  end
  for _, e in ipairs(list) do
    if not e.st then
      if offered == 0 then make('VwSub', items, 'Available') end
      offered = offered + 1
      local row = make('VwAddonOffer', items)
      row.name:setText(e.name)
      if e == sel then row:setBackgroundColor('#ffffff17') end
      row.onClick = function() detail = e.id; later() end
      click(row.install, function() Voidwatch.installAddon(e.id) end)
    end
  end
  if #list == 0 then make('VwText', items, 'No addons yet.') end
  a.list.stopAll:setText(v.addonsOff and 'Start all addons' or 'Stop all addons')
  click(a.list.stopAll, v.addonsOff and Voidwatch.startAddons or Voidwatch.stopAddons)
  a.list.website.onClick = function() g_platform.openUrl((site or SITE) .. '/dashboard/addons') end
end

-- the website's caption for one picture file, matched by its name
local function captionOf(e, file)
  for _, p in ipairs(e.pictures or {}) do
    if type(p) == 'table' and tostring(p.src or ''):sub(-#file - 1) == '/' .. file then return tostring(p.caption or '') end
  end
  return ''
end

local function openPicture(e, files, i)
  if refs.picWin and not refs.picWin:isDestroyed() then refs.picWin:destroy() end
  local w = g_ui.createWidget('VwPictureWindow', rootWidget)
  refs.picWin = w
  w:setText(e.name)
  local function show(k)
    i = (k - 1) % #files + 1
    w.frame.img:setImageSource(Voidwatch.picturePath(e.id, files[i]))
    w.caption:setText(captionOf(e, files[i]))
    w.count:setText(i .. ' / ' .. #files)
  end
  for key, step in pairs({ prev = -1, next = 1 }) do
    w.frame[key]:setText(step < 0 and '<' or '>')
    w.frame[key]:setVisible(#files > 1)
    w.frame[key].onClick = function() show(i + step) end
  end
  w.closeButton.onClick = function() w:destroy() end
  w.onEscape = function() w:destroy() end
  show(i)
  w:show()
  w:raise()
  w:focus()
end

-- the picture beside the details, changed in place so the page does not draw again
local function showPicture(d, e, files)
  local has = #files > 0
  local i = math.min(math.max(1, picIndex[e.id] or 1), math.max(1, #files))
  d.pic.img:setVisible(has)
  d.pic.icon:setVisible(not has)
  d.pic.picText:setVisible(not has)
  d.pic.picCount:setText(has and (i .. ' / ' .. #files) or '0 / 0')
  if has then
    d.pic.img:setImageSource(Voidwatch.picturePath(e.id, files[i]))
    d.pic.img:setTooltip(captionOf(e, files[i]))
    d.pic.img.onClick = function() openPicture(e, files, i) end
  end
  for key, step in pairs({ prev = -1, next = 1 }) do
    d.pic[key]:setText(step < 0 and '<' or '>')
    d.pic[key]:setVisible(#files > 1)
    d.pic[key].onClick = function()
      picIndex[e.id] = (i - 1 + step) % #files + 1
      showPicture(d, e, files)
    end
  end
end

local function showSub(d)
  local keys = {}
  for _, tab in ipairs(d.subtabs.tabs or {}) do keys[tab.vwKey] = true end
  if not keys[subtab] then subtab = 'about' end
  d.sub.points:setVisible(subtab == 'about')
  d.sub.settings:setVisible(subtab == 'settings')
  d.sub.log:setVisible(subtab == 'errors' and d.sub.log:getChildCount() > 0)
  d.sub.none:setVisible(subtab == 'errors' and d.sub.log:getChildCount() == 0)
end

local function settingControls(panel, e, list)
  for _, s in ipairs(list) do
    if s.type == 'bool' then
      local box = make('VwCheck', panel, s.label)
      box:setChecked(s.value == true)
      box.onCheckChange = function(_, on) pcall(Voidwatch.setAddonSetting, e.id, s.key, on) end
    elseif s.type == 'number' then
      local row = make('VwNumber', panel)
      row.key:setText(s.label)
      row.unit:setText('')
      pcall(function()
        row.value:setMinimum(s.min or 0)
        row.value:setMaximum(s.max or 1000000)
        row.value:setValue(tonumber(s.value) or s.min or 0)
      end)
      row.value.onValueChange = function(_, n) pcall(Voidwatch.setAddonSetting, e.id, s.key, tonumber(n)) end
    elseif s.type == 'choice' then
      local row = make('VwChoice', panel)
      row.key:setText(s.label)
      pcall(function()
        for _, o in ipairs(s.options or {}) do row.value:addOption(tostring(o)) end
        row.value:setCurrentOption(tostring(s.value))
      end)
      row.value.onOptionChange = function(_, text) pcall(Voidwatch.setAddonSetting, e.id, s.key, text) end
    elseif s.type == 'text' then
      local row = make('VwTextSetting', panel)
      row.key:setText(s.label)
      row.value:setMaxLength(s.maxLength or 40)
      row.value:setText(tostring(s.value or ''))
      row.value.onTextChange = function(_, text) pcall(Voidwatch.setAddonSetting, e.id, s.key, text) end
    end
  end
end

local function buildDetail(a, v, e)
  local card = a.detail
  card:destroyChildren()
  if not e then
    make('VwText', card, 'No addons yet. They come with the module updates.')
    return
  end
  local d = make('VwAddonDetail', card)
  d.pic.icon:setImageSource(home() .. 'voidwatch_picture')
  local st = e.st
  d.name:setText(e.name)
  local text, colour = addonState(v, e)
  d.state:setText(text)
  d.state:setColor(colour)
  d.about:setText(e.about ~= '' and e.about or 'No description yet.')
  local meta = {}
  if e.plan then meta[#meta + 1] = (tostring(e.plan):gsub('^%l', string.upper)) .. ' plan' end
  if e.size then meta[#meta + 1] = math.max(1, math.floor(e.size / 1024 + 0.5)) .. ' KB' end
  if st then meta[#meta + 1] = st.here == false and 'off for this character' or 'on for this character' end
  if e.newer then meta[#meta + 1] = 'version ' .. tostring(e.latest) .. ' comes with the module update' end
  d.meta:setText(table.concat(meta, '  -  '))
  local actions = {}
  if not st then
    actions[#actions + 1] = { 'Install', function() Voidwatch.installAddon(e.id) end }
  elseif st.here ~= false then
    local function restart()
      local ok = Voidwatch.reloadAddon(e.id)
      pcall(function() modules.game_textmessage.displayGameMessage('[Voidwatch] ' .. e.name .. (ok and ' reloaded.' or ' did not start: see Errors.')) end)
    end
    if st.broken then
      actions[#actions + 1] = { 'Start again', restart }
    elseif st.on then
      actions[#actions + 1] = { 'Reload', restart }
    end
    if st.canOpen then
      local label = st.openLabel and #st.openLabel <= 14 and st.openLabel or 'Open window'
      actions[#actions + 1] = { label, function() Voidwatch.openAddon(e.id) end }
    end
  end
  for i, key in ipairs({ 'a', 'b' }) do
    local b, act = d.bar[key], actions[i]
    b:setVisible(act ~= nil)
    if act then
      b:setText(act[1])
      click(b, act[2])
    end
  end
  d.bar.remove:setVisible(st ~= nil)
  click(d.bar.remove, function() Voidwatch.removeAddon(e.id) end)
  -- the folder's picture files; the website lists the ones it has, and the upload script brings the missing ones
  if #e.pictures > 0 then pcall(Voidwatch.wantPictures, e.id, e.pictures) end
  showPicture(d, e, Voidwatch.pictureFiles(e.id))
  for i, p in ipairs(e.points) do
    local w = make('VwPoint', i % 2 == 1 and d.sub.points.colA or d.sub.points.colB)
    w.vwText = tostring(p)
    w:setTooltip(w.vwText)
  end
  local settings = st and st.settings or {}
  settingControls(d.sub.settings, e, settings)
  local log = st and st.log or {}
  for _, item in ipairs(log) do
    local l = make('VwLogLine', d.sub.log, os.date('%H:%M:%S', item.at) .. '   ' .. short(item.text, 90))
    l:setTooltip(tostring(item.text))
  end
  d.sub.none:setText('No errors since the addon started.')
  local tabs = { { 'about', 'About' } }
  if #settings > 0 then tabs[#tabs + 1] = { 'settings', 'Settings' } end
  if st then tabs[#tabs + 1] = { 'errors', 'Errors ' .. #log } end
  for _, t in ipairs(tabs) do
    local tab = d.subtabs:addTab(t[2], g_ui.createWidget('UIWidget'))
    tab.vwKey = t[1]
    if t[1] == subtab then d.subtabs:selectTab(tab) end
  end
  d.subtabs.onTabChange = function(_, tab)
    subtab = tab.vwKey or 'about'
    showSub(d)
  end
  showSub(d)
  refs.detail = d
end

local function buildAddons(page, v)
  local a = refs.addonsPage
  local list, byId = addonList(v)
  local sel = selected(list, byId)
  detail = sel and sel.id or nil
  local at = tonumber(a.list.itemsScroll:getValue()) or 0
  listScroll = at > 0 and { value = at, fills = 0 } or nil
  buildItems(a, v, list, sel)
  buildDetail(a, v, sel)
end

-- the two columns of points get their width from the card, and each point is cut to it
local function fillAddons()
  local a = refs.addonsPage
  if not a then return end
  fitWidths(a.list.items)
  scrollIfNeeded(a.list.items, a.list.itemsScroll)
  -- the rebuilt list is laid out only after the first fill, so its old position fits from the second one on
  if listScroll then
    local bar = a.list.itemsScroll
    listScroll.fills = listScroll.fills + 1
    if listScroll.fills >= 2 and bar:getMaximum() > 0 then
      bar:setValue(math.min(listScroll.value, bar:getMaximum()))
      listScroll = nil
    elseif listScroll.fills >= 4 then
      listScroll = nil
    end
  end
  local d = refs.detail
  if not d or d:isDestroyed() then return end
  local colW = math.floor((a.detail:getWidth() - a.detail:getPaddingLeft() - a.detail:getPaddingRight() - 14) / 2)
  if colW <= 0 then return end
  for _, col in ipairs({ d.sub.points.colA, d.sub.points.colB }) do
    for _, w in ipairs(col:getChildren()) do
      w:setWidth(colW)
      w.text:setWidth(colW - 10)
      w.text:setText(short(w.vwText, math.floor((colW - 10) / 6)))
    end
  end
  fitWidths(d.sub.settings)
end

-- Settings tab ----------------------------------------------------------------------------------------------------

local function formFrom(v)
  local f = { values = {}, changed = {} }
  for k, val in pairs(v.settings or {}) do f.values[k] = val end
  local labels = {}
  for _, role in ipairs(ROLES) do labels[role] = type(f.values.labels) == 'table' and f.values.labels[role] or '' end
  f.values.labels = labels
  return f
end

local function dirty() return form ~= nil and next(form.changed) ~= nil end

local function syncForm()
  local r = refs.settings
  if not (r and form) then return end
  syncing = true
  for key, box in pairs(r.checks) do box:setChecked(form.values[key] == true) end
  pcall(function() r.wait.value:setValue(tonumber(form.values.planWait) or 20) end)
  for role, edit in pairs(r.labels) do
    if edit:getText() ~= form.values.labels[role] then edit:setText(form.values.labels[role] or '') end
  end
  syncing = false
end

local function setValue(key, value)
  if syncing or not form then return end
  form.values[key] = value
  form.changed[key] = true
  render()
end

local function settingsShape(v)
  return v.state == 'connected' and 'form' or 'unpaired'
end

-- the form is built once with the window; only whether it shows changes with the state
local function makeSettings(page)
  local s = make('VwSettingsPage', page)
  local r = { root = s, checks = {}, labels = {} }
  for _, group in ipairs({ { SEND, s.send.rows }, { TEAM, s.team.rows } }) do
    for _, item in ipairs(group[1]) do
      local key = item[1]
      local box = make('VwCheck', group[2], item[2])
      box:setTooltip(item[3])
      box.onCheckChange = function(_, on) setValue(key, on) end
      r.checks[key] = box
    end
  end
  r.wait = make('VwNumber', s.team.rows)
  r.wait:setMarginTop(2)
  r.wait.key:setText('Plan wait limit')
  r.wait.unit:setText('minutes')
  r.wait:setTooltip('A plan step that waits longer stops as stuck. A big respawn with a long hunt loop may need more.')
  r.wait.value.onValueChange = function(_, n) setValue('planWait', tonumber(n)) end
  r.fields = {}
  local hint = 'The label names your routes use for each part, as a comma list. Empty: the standard name.'
  s.labels.title:setTooltip(hint)
  for _, role in ipairs(ROLES) do
    local f = make('VwLabelField', s.labels.row)
    f.key:setText(role)
    f:setTooltip(hint)
    f.edit.onTextChange = function(_, text)
      if syncing or not form then return end
      form.values.labels[role] = text
      setValue('labels', form.values.labels)
    end
    r.labels[role] = f.edit
    r.fields[#r.fields + 1] = f
  end
  s.bottom.save.onClick = function()
    if not form then return end
    local out = {}
    for k in pairs(form.changed) do out[k] = form.values[k] end
    if Voidwatch.saveSettings(out) then form.changed = {} end
    render()
  end
  s.bottom.undo.onClick = function()
    local ok, now = pcall(Voidwatch.view)
    if ok and type(now) == 'table' then form = formFrom(now) end
    syncForm()
    render()
  end
  refs.settings = r
end

local function buildSettings(page, v)
  local r = refs.settings
  local on = v.state == 'connected'
  for _, id in ipairs({ 'send', 'team', 'labels', 'bottom' }) do r.root[id]:setVisible(on) end
  r.root.unpaired:setVisible(not on)
  if on and not dirty() then form = formFrom(v) end
  if not on then form = nil end
  syncForm()
end

local function fillSettings(v)
  local r = refs.settings
  if not (r and form) then return end
  for _, rows in ipairs({ r.root.send.rows, r.root.team.rows }) do fitWidths(rows) end
  local fieldW = math.max(60, math.floor((r.root.labels.row:getWidth() - 3 * 12) / 4))
  for _, f in ipairs(r.fields) do f:setWidth(fieldW) end
  if not dirty() then
    form = formFrom(v)
    syncForm()
  end
  local status = r.root.bottom.status
  r.root.bottom.save:setEnabled(dirty())
  r.root.bottom.undo:setEnabled(dirty())
  local saved = v.settingsSaved
  local text, colour, tip = 'The same settings as the Clients page on voidwatch.xyz', FAINT, 'Save sends a change to the website.'
  if dirty() then
    text = 'Changes not saved yet'
  elseif v.settingsPending then
    text, colour, tip = 'Saving on voidwatch.xyz...', YELLOW, 'The upload script sends it with the next status, within 30 seconds. This client uses it already.'
  elseif saved and saved.ok then
    text, colour = 'Saved on voidwatch.xyz ' .. ago(saved.ago or 0), GREEN
  elseif saved then
    text, colour, tip = 'Not saved: ' .. short(saved.error, 60), RED, tostring(saved.error or '')
  end
  status.dot:setVisible(colour ~= FAINT)
  status.dot:setBackgroundColor(colour)
  status.text:setColor(colour)
  status.text:setText(text)
  status:setTooltip(tip)
end

-- pages -----------------------------------------------------------------------------------------------------------

local SHAPE = { main = mainShape, addons = addonsShape, settings = settingsShape }
local BUILD = { main = buildMain, addons = buildAddons, settings = buildSettings }
local FILL = { main = fillMain, addons = fillAddons, settings = fillSettings }

-- new rows get their width only after a frame, so a rebuilt page waits unseen until it is filled again at that width
local function settle(key)
  local page = pages[key]
  page:setOpacity(0)
  addEvent(function()
    if not win or page:isDestroyed() then return end
    local ok, v = pcall(Voidwatch.view)
    if ok and type(v) == 'table' then FILL[key](v) end
    page:setOpacity(1)
  end)
end

local function show()
  for key, page in pairs(pages) do page:setVisible(key == current) end
end

-- every tab stays built and filled, so a tab change only shows another page
function render()
  if not win then return end
  local ok, v = pcall(Voidwatch.view)
  if not ok or type(v) ~= 'table' then return end
  if v.url then site = v.url:match('^(https?://[^/]+)') or site end
  fillHeader(v)
  fillBar(v)
  setBadge(#(v.addons or {}))
  for _, t in ipairs(TABS) do
    local key = t[1]
    local shape = SHAPE[key](v)
    if shape ~= shapes[key] then
      shapes[key] = shape
      BUILD[key](pages[key], v)
      FILL[key](v)
      settle(key)
    else
      FILL[key](v)
    end
  end
end

local function refresh()
  if timer then removeEvent(timer) end
  timer = nil
  if not win then return end
  pcall(render)
  timer = scheduleEvent(refresh, 1000)
end

local function close()
  if timer then removeEvent(timer) end
  if refs.picWin and not refs.picWin:isDestroyed() then refs.picWin:destroy() end
  timer, refs, shapes, pages, tabButtons, form = nil, {}, {}, {}, {}, nil
  if win then win:destroy() end
  win = nil
  if button then button:setOn(false) end
end

local function open()
  if not styled then
    g_ui.importStyle(home() .. 'voidwatch.otui')
    styled = true
  end
  win = g_ui.createWidget('VoidwatchWindow', rootWidget)
  win:setOpacity(0)
  -- one size from the start, never changed while the window is open
  win:setSize({ width = WIDTH, height = math.max(MIN_HEIGHT, math.min(HEIGHT, rootWidget:getHeight() - SCREEN_GAP)) })
  win.onEscape = close
  win.closeButton.onClick = close
  win.dashboardButton.onClick = function() g_platform.openUrl((site or SITE) .. '/dashboard') end
  win.rollback.onClick = function() pcall(Voidwatch.rollback); later() end
  -- the pages stay in the content panel and only change visibility; the tab bar moves no panels
  for _, t in ipairs(TABS) do
    pages[t[1]] = g_ui.createWidget('VwPage', win.content)
    local tab = win.tabs:addTab(t[2], g_ui.createWidget('UIWidget'))
    tab.vwKey = t[1]
    tabButtons[t[1]] = tab
  end
  refs.addonsPage = make('VwAddonsPage', pages.addons)
  makeSettings(pages.settings)
  win.tabs:selectTab(tabButtons[current])
  win.tabs.onTabChange = function(_, tab)
    current = tab.vwKey or 'main'
    show()
  end
  local ok, v = pcall(Voidwatch.view)
  win.version:setText('v' .. tostring(ok and v.version or '?'))
  if button then button:setOn(true) end
  refresh()
  win:show()
  win:raise()
  win:focus()
  -- unseen for one frame, until every page is filled again at its width
  addEvent(function()
    if not win then return end
    pcall(render)
    show()
    win:setOpacity(1)
  end)
end

local function toggle()
  if win then close() else open() end
end

local function changed()
  if not dot then return end
  local state = Voidwatch.state()
  if state ~= lastState then
    lastState = state
    if win then pcall(render) end
    dot:setBackgroundColor(COLOURS[state] or GREY)
    button:setTooltip('Voidwatch: ' .. (({ connected = 'connected', pairing = 'waiting for pairing', waiting = 'waiting for the upload script',
      stopped = 'stopped', off = 'stopped for all clients', offline = 'not logged in' })[state] or state))
  end
end

Voidwatch.ui = {
  init = function()
    local tm = modules.client_topmenu
    if not tm or not tm.addRightGameToggleButton then return end
    button = tm.addRightGameToggleButton('voidwatchButton', 'Voidwatch', home() .. 'voidwatch_button', toggle, false, 900)
    button:setOn(false)
    dot = g_ui.createWidget('UIWidget', button)
    dot:setSize({ width = 6, height = 6 })
    dot:addAnchor(AnchorRight, 'parent', AnchorRight)
    dot:addAnchor(AnchorBottom, 'parent', AnchorBottom)
    dot:setMarginRight(2)
    dot:setMarginBottom(2)
    dot:setBorderWidth(1)
    dot:setBorderColor('#000000')
    dot:setPhantom(true)
    lastState = nil
    changed()
    local ok, again = pcall(g_settings.getBoolean, 'voidwatch-reopen')
    if ok and again then
      pcall(g_settings.remove, 'voidwatch-reopen')
      open()
    end
  end,
  terminate = function()
    close()
    if button then button:destroy() end
    button, dot, lastState = nil, nil, nil
  end,
  changed = changed,
  close = close,
  toggle = toggle,
  isOpen = function() return win ~= nil end,
}

voidwatch/voidwatch.otui

VwHead < Label
  color: #e8c547
  text-auto-resize: true

VwSub < Label
  color: #6f6f6f
  text-auto-resize: true
  margin-top: 9
  margin-left: 6

VwText < Label
  color: #9b9b9b
  text-wrap: true
  text-auto-resize: true

VwNote < VwText
  color: #ffdd55

VwDot < UIWidget
  size: 7 7
  border-width: 1
  border-color: #000000
  phantom: true

VwState < Panel
  height: 16

  VwDot
    id: dot
    anchors.left: parent.left
    anchors.verticalCenter: parent.verticalCenter

  Label
    id: text
    anchors.left: dot.right
    anchors.right: parent.right
    anchors.verticalCenter: parent.verticalCenter
    margin-left: 5
    text-auto-resize: true

VwLine < Panel
  height: 15

  Label
    id: key
    anchors.left: parent.left
    anchors.verticalCenter: parent.verticalCenter
    color: #9b9b9b
    text-auto-resize: true

  Label
    id: value
    anchors.right: parent.right
    anchors.verticalCenter: parent.verticalCenter
    color: #dfdfdf
    text-auto-resize: true

VwKV < Panel
  height: 15

  Label
    id: key
    anchors.left: parent.left
    anchors.top: parent.top
    size: 100 15
    text-align: left
    color: #9b9b9b

  Label
    id: value
    anchors.left: key.right
    anchors.top: parent.top
    height: 15
    text-align: left
    color: #dfdfdf
    text-auto-resize: true

  UIWidget
    id: info
    anchors.left: value.right
    anchors.verticalCenter: value.verticalCenter
    margin-left: 6
    size: 11 11
    visible: false

VwSourceLine < Panel
  height: 16

  VwDot
    id: dot
    anchors.left: parent.left
    anchors.verticalCenter: parent.verticalCenter

  Label
    id: name
    anchors.left: dot.right
    anchors.verticalCenter: parent.verticalCenter
    margin-left: 6
    size: 104 16
    text-align: left
    color: #ffffff

  Label
    id: gives
    anchors.left: name.right
    anchors.right: parent.right
    anchors.verticalCenter: parent.verticalCenter
    height: 16
    text-align: left
    color: #9b9b9b

VwButtons < Panel
  height: 21

  Button
    id: a
    anchors.left: parent.left
    anchors.right: parent.horizontalCenter
    anchors.verticalCenter: parent.verticalCenter
    margin-right: 3
    height: 21

  Button
    id: b
    anchors.left: parent.horizontalCenter
    anchors.right: parent.right
    anchors.verticalCenter: parent.verticalCenter
    margin-left: 2
    height: 21

VwCode < Label
  height: 34
  font: sans-bold-16px
  color: #ffffff
  text-align: center
  background-color: #1c1c1c
  border-width: 1
  border-color: #4a4a4a

VwSeparator < UIWidget
  height: 2
  margin-top: 4
  margin-bottom: 4
  border-width: 1
  border-color: #4a4a4a
  border-color-top: #1a1a1a
  border-color-left: #1a1a1a
  border-color-right: #1a1a1a
  phantom: true

VwUpdate < Panel
  height: 27
  background-color: #e8a31721
  border-width: 1
  border-color: #b8901f

  Label
    id: text
    anchors.left: parent.left
    anchors.right: action.left
    anchors.verticalCenter: parent.verticalCenter
    margin-left: 8
    margin-right: 8
    color: #ffdd55
    text-wrap: true
    text-auto-resize: true

  Button
    id: action
    anchors.right: parent.right
    anchors.verticalCenter: parent.verticalCenter
    margin-right: 3
    size: 76 21
    color: #ffffff
    font: verdana-11px-rounded

VwLink < UIButton
  color: #9b9b9b
  text-auto-resize: true
  $hover:
    color: #dfdfdf

  UIWidget
    id: line
    anchors.left: parent.left
    anchors.right: parent.right
    anchors.bottom: parent.bottom
    height: 1
    background-color: #9b9b9b
    phantom: true

VwFrame < UIWidget
  background-color: #0000002e
  border-width: 1
  border-color: #4b4b4b
  border-color-top: #161616
  border-color-left: #161616

VwCard < VwFrame
  background-color: #00000029
  padding: 8 10 8 10
  clipping: true

VwSunken < UIWidget
  background-color: #141414
  border-width: 1
  border-color: #444444
  border-color-top: #0c0c0c
  border-color-left: #0c0c0c

VwCheck < CheckBox
  height: 16
  text-auto-resize: false

VwBadge < Label
  height: 13
  color: #1c1c1c
  background-color: #e8a317
  text-auto-resize: true
  padding-left: 3
  padding-right: 3
  phantom: true

VwMainConnected < Panel
  anchors.fill: parent

  VwCard
    id: client
    anchors.top: parent.top
    anchors.left: parent.left
    anchors.right: parent.horizontalCenter
    anchors.bottom: parent.bottom
    margin-right: -14

    VwHead
      id: title
      anchors.top: parent.top
      anchors.left: parent.left
      !text: tr('This client')

    Panel
      id: rows
      anchors.top: title.bottom
      anchors.left: parent.left
      anchors.right: parent.right
      anchors.bottom: sep.top
      margin-top: 8
      layout:
        type: verticalBox
        spacing: 8

    VwButtons
      id: stop
      anchors.left: parent.left
      anchors.right: parent.right
      anchors.bottom: parent.bottom

    Button
      id: reset
      anchors.left: parent.left
      anchors.right: parent.right
      anchors.bottom: stop.top
      margin-bottom: 5
      height: 21
      !text: tr('Reset loot, supplies and time')

    VwSeparator
      id: sep
      anchors.left: parent.left
      anchors.right: parent.right
      anchors.bottom: reset.top
      margin-bottom: 8

  VwCard
    id: sources
    anchors.top: parent.top
    anchors.left: client.right
    anchors.right: parent.right
    anchors.bottom: parent.bottom
    margin-left: 9

    VwHead
      id: title
      anchors.top: parent.top
      anchors.left: parent.left
      !text: tr('Data sources')

    ScrollablePanel
      id: rows
      anchors.top: title.bottom
      anchors.left: parent.left
      anchors.right: parent.right
      anchors.bottom: parent.bottom
      margin-top: 8
      vertical-scrollbar: scroll
      layout:
        type: verticalBox
        spacing: 8

    VerticalScrollBar
      id: scroll
      anchors.top: rows.top
      anchors.right: parent.right
      anchors.bottom: rows.bottom
      step: 24
      pixels-scroll: true
      visible: false

VwMainOther < Panel
  anchors.fill: parent

  VwCard
    id: card
    anchors.fill: parent

    ScrollablePanel
      id: body
      anchors.fill: parent
      vertical-scrollbar: scroll
      layout:
        type: verticalBox
        spacing: 5

    VerticalScrollBar
      id: scroll
      anchors.top: parent.top
      anchors.right: parent.right
      anchors.bottom: parent.bottom
      step: 24
      pixels-scroll: true
      visible: false

VwAddonItem < UIWidget
  height: 54
  padding: 5

  CheckBox
    id: here
    anchors.left: parent.left
    anchors.top: parent.top
    size: 16 16

  Label
    id: name
    anchors.left: here.right
    anchors.top: parent.top
    margin-left: 6
    margin-top: 1
    color: #ffffff
    text-auto-resize: true
    phantom: true

  Label
    id: summary
    anchors.left: name.left
    anchors.right: parent.right
    anchors.top: name.bottom
    margin-top: 2
    height: 14
    text-align: left
    color: #8a8a8a
    phantom: true

  Label
    id: state
    anchors.left: name.left
    anchors.top: summary.bottom
    margin-top: 1
    text-auto-resize: true
    phantom: true

  VwBadge
    id: badge
    anchors.left: name.right
    anchors.verticalCenter: name.verticalCenter
    margin-left: 5

VwAddonOffer < UIWidget
  height: 27
  padding: 4 5 4 5

  Label
    id: name
    anchors.left: parent.left
    anchors.verticalCenter: parent.verticalCenter
    margin-left: 22
    color: #9b9b9b
    text-auto-resize: true
    phantom: true

  Button
    id: install
    anchors.right: parent.right
    anchors.verticalCenter: parent.verticalCenter
    size: 54 19
    !text: tr('Install')

VwAddonsPage < Panel
  anchors.fill: parent

  VwCard
    id: list
    anchors.top: parent.top
    anchors.left: parent.left
    anchors.bottom: parent.bottom
    width: 180
    padding: 4

    Label
      id: hint
      anchors.top: parent.top
      anchors.left: parent.left
      anchors.right: parent.right
      margin-top: 2
      margin-left: 5
      height: 14
      text-align: left
      color: #6f6f6f
      !text: tr('Ticked: on for this character')

    Button
      id: website
      anchors.left: parent.left
      anchors.right: parent.right
      anchors.bottom: parent.bottom
      height: 21
      !text: tr('Addons on the website')

    Button
      id: stopAll
      anchors.left: parent.left
      anchors.right: parent.right
      anchors.bottom: website.top
      margin-bottom: 4
      height: 21

    ScrollablePanel
      id: items
      anchors.top: hint.bottom
      anchors.left: parent.left
      anchors.right: parent.right
      anchors.bottom: stopAll.top
      margin-top: 4
      margin-bottom: 6
      vertical-scrollbar: itemsScroll
      layout:
        type: verticalBox

    VerticalScrollBar
      id: itemsScroll
      anchors.top: items.top
      anchors.right: parent.right
      anchors.bottom: items.bottom
      step: 24
      pixels-scroll: true
      visible: false

  VwCard
    id: detail
    anchors.top: parent.top
    anchors.left: list.right
    anchors.right: parent.right
    anchors.bottom: parent.bottom
    margin-left: 9

VwPoint < Panel
  height: 14

  UIWidget
    id: mark
    anchors.left: parent.left
    anchors.top: parent.top
    margin-top: 5
    margin-left: 1
    size: 4 4
    background-color: #e8c547
    phantom: true

  Label
    id: text
    anchors.left: mark.right
    anchors.right: parent.right
    anchors.top: parent.top
    margin-left: 5
    height: 14
    text-align: left
    color: #9b9b9b

VwAddonDetail < Panel
  anchors.fill: parent

  VwSunken
    id: pic
    anchors.top: parent.top
    anchors.left: parent.left
    size: 184 115

    UIWidget
      id: icon
      anchors.horizontalCenter: parent.horizontalCenter
      anchors.bottom: parent.verticalCenter
      margin-bottom: 1
      size: 34 24
      phantom: true

    Label
      id: picText
      anchors.horizontalCenter: parent.horizontalCenter
      anchors.top: parent.verticalCenter
      margin-top: 6
      color: #6f6f6f
      text-auto-resize: true
      !text: tr('Screenshots come soon')

    UIWidget
      id: img
      anchors.fill: parent
      margin: 1
      image-fixed-ratio: true
      visible: false

    Button
      id: prev
      anchors.left: parent.left
      anchors.verticalCenter: parent.verticalCenter
      margin-left: 2
      size: 16 26
      visible: false

    Button
      id: next
      anchors.right: parent.right
      anchors.verticalCenter: parent.verticalCenter
      margin-right: 2
      size: 16 26
      visible: false

    Label
      id: picCount
      anchors.right: parent.right
      anchors.bottom: parent.bottom
      margin-right: 4
      margin-bottom: 3
      color: #dddddd
      background-color: #00000099
      padding-left: 3
      padding-right: 3
      text-auto-resize: true
      phantom: true

  Label
    id: name
    anchors.top: parent.top
    anchors.left: pic.right
    margin-left: 12
    color: #ffffff
    font: verdana-11px-rounded
    text-auto-resize: true

  Label
    id: state
    anchors.top: parent.top
    anchors.right: parent.right
    text-auto-resize: true

  Label
    id: about
    anchors.top: name.bottom
    anchors.left: name.left
    anchors.right: parent.right
    margin-top: 5
    color: #dfdfdf
    text-wrap: true
    text-auto-resize: true

  Label
    id: meta
    anchors.top: about.bottom
    anchors.left: name.left
    anchors.right: parent.right
    margin-top: 4
    color: #6f6f6f
    text-wrap: true
    text-auto-resize: true

  Panel
    id: bar
    anchors.left: name.left
    anchors.right: parent.right
    anchors.bottom: pic.bottom
    height: 21

    Button
      id: a
      anchors.left: parent.left
      anchors.top: parent.top
      size: 76 21

    Button
      id: b
      anchors.left: a.right
      anchors.top: parent.top
      margin-left: 5
      size: 96 21

    Button
      id: remove
      anchors.right: parent.right
      anchors.top: parent.top
      size: 72 21
      color: #ff8a8a
      !text: tr('Remove')

  TabBar
    id: subtabs
    anchors.top: pic.bottom
    anchors.left: parent.left
    anchors.right: parent.right
    margin-top: 8

  Panel
    id: sub
    anchors.top: subtabs.bottom
    anchors.left: parent.left
    anchors.right: parent.right
    anchors.bottom: parent.bottom
    margin-top: 7

    Panel
      id: points
      anchors.fill: parent

      Panel
        id: colA
        anchors.top: parent.top
        anchors.left: parent.left
        anchors.right: parent.horizontalCenter
        margin-right: 7
        layout:
          type: verticalBox
          spacing: 3
          fit-children: true

      Panel
        id: colB
        anchors.top: parent.top
        anchors.left: parent.horizontalCenter
        anchors.right: parent.right
        margin-left: 7
        layout:
          type: verticalBox
          spacing: 3
          fit-children: true

    Panel
      id: settings
      anchors.fill: parent
      layout:
        type: verticalBox
        spacing: 7

    VwSunken
      id: log
      anchors.fill: parent
      background-color: #161616
      padding: 3 6 3 6
      layout:
        type: verticalBox
        spacing: 1

    Label
      id: none
      anchors.top: parent.top
      anchors.left: parent.left
      color: #6f6f6f
      text-auto-resize: true

VwChoice < Panel
  height: 20

  Label
    id: key
    anchors.left: parent.left
    anchors.verticalCenter: parent.verticalCenter
    color: #9b9b9b
    text-auto-resize: true

  ComboBox
    id: value
    anchors.left: key.right
    anchors.verticalCenter: parent.verticalCenter
    margin-left: 8
    size: 130 20

VwTextSetting < Panel
  height: 20

  Label
    id: key
    anchors.left: parent.left
    anchors.verticalCenter: parent.verticalCenter
    color: #9b9b9b
    text-auto-resize: true

  TextEdit
    id: value
    anchors.left: key.right
    anchors.verticalCenter: parent.verticalCenter
    margin-left: 8
    size: 130 20

VwPictureWindow < MainWindow
  size: 660 470

  VwSunken
    id: frame
    anchors.top: parent.top
    anchors.left: parent.left
    anchors.right: parent.right
    anchors.bottom: closeButton.top
    margin-bottom: 8

    UIWidget
      id: img
      anchors.fill: parent
      margin: 1
      image-fixed-ratio: true

    Button
      id: prev
      anchors.left: parent.left
      anchors.verticalCenter: parent.verticalCenter
      margin-left: 4
      size: 22 34

    Button
      id: next
      anchors.right: parent.right
      anchors.verticalCenter: parent.verticalCenter
      margin-right: 4
      size: 22 34

  Label
    id: caption
    anchors.left: parent.left
    anchors.right: count.left
    anchors.verticalCenter: closeButton.verticalCenter
    margin-right: 8
    height: 15
    text-align: left
    color: #dfdfdf

  Label
    id: count
    anchors.right: closeButton.left
    anchors.verticalCenter: closeButton.verticalCenter
    margin-right: 10
    color: #6f6f6f
    text-auto-resize: true

  Button
    id: closeButton
    !text: tr('Close')
    anchors.right: parent.right
    anchors.bottom: parent.bottom
    size: 84 21

VwLogLine < Label
  height: 14
  text-align: left
  color: #dfdfdf

VwNumber < Panel
  height: 20

  Label
    id: key
    anchors.left: parent.left
    anchors.verticalCenter: parent.verticalCenter
    color: #9b9b9b
    text-auto-resize: true

  SpinBox
    id: value
    anchors.left: key.right
    anchors.verticalCenter: parent.verticalCenter
    margin-left: 7
    size: 46 20
    minimum: 5
    maximum: 120
    step: 1

  Label
    id: unit
    anchors.left: value.right
    anchors.verticalCenter: parent.verticalCenter
    margin-left: 7
    color: #9b9b9b
    text-auto-resize: true

VwLabelField < Panel
  height: 20

  Label
    id: key
    anchors.left: parent.left
    anchors.verticalCenter: parent.verticalCenter
    size: 32 15
    text-align: right
    color: #9b9b9b

  TextEdit
    id: edit
    anchors.left: key.right
    anchors.right: parent.right
    anchors.verticalCenter: parent.verticalCenter
    margin-left: 6
    height: 20
    max-length: 80

VwSettingsPage < Panel
  anchors.fill: parent

  VwCard
    id: send
    anchors.top: parent.top
    anchors.left: parent.left
    anchors.right: parent.horizontalCenter
    margin-right: 5
    height: 132

    VwHead
      id: title
      anchors.top: parent.top
      anchors.left: parent.left
      !text: tr('What this client sends')

    Panel
      id: rows
      anchors.top: title.bottom
      anchors.left: parent.left
      anchors.right: parent.right
      anchors.bottom: parent.bottom
      margin-top: 8
      layout:
        type: verticalBox
        spacing: 8

  VwCard
    id: team
    anchors.top: parent.top
    anchors.left: parent.horizontalCenter
    anchors.right: parent.right
    margin-left: 4
    height: 132

    VwHead
      id: title
      anchors.top: parent.top
      anchors.left: parent.left
      !text: tr('Team and chat')

    Panel
      id: rows
      anchors.top: title.bottom
      anchors.left: parent.left
      anchors.right: parent.right
      anchors.bottom: parent.bottom
      margin-top: 8
      layout:
        type: verticalBox
        spacing: 8

  VwCard
    id: labels
    anchors.top: send.bottom
    anchors.left: parent.left
    anchors.right: parent.right
    margin-top: 9
    height: 58

    VwHead
      id: title
      anchors.top: parent.top
      anchors.left: parent.left
      !text: tr('Route labels')

    Panel
      id: row
      anchors.top: title.bottom
      anchors.left: parent.left
      anchors.right: parent.right
      margin-top: 8
      height: 20
      layout:
        type: horizontalBox
        spacing: 12


  Panel
    id: bottom
    anchors.left: parent.left
    anchors.right: parent.right
    anchors.bottom: parent.bottom
    height: 21

    VwState
      id: status
      anchors.left: parent.left
      anchors.right: undo.left
      anchors.verticalCenter: parent.verticalCenter
      margin-right: 8

    Button
      id: save
      anchors.right: parent.right
      anchors.top: parent.top
      size: 60 21
      font: verdana-11px-rounded
      !text: tr('Save')

    Button
      id: undo
      anchors.right: save.left
      anchors.top: parent.top
      margin-right: 5
      size: 104 21
      !text: tr('Undo changes')

  Label
    id: unpaired
    anchors.centerIn: parent
    color: #9b9b9b
    text-auto-resize: true
    visible: false
    !text: tr('Pair this client first. The settings live on voidwatch.xyz.')

VwPage < Panel
  anchors.fill: parent
  padding: 9

VoidwatchWindow < MainWindow
  id: voidwatchWindow
  !text: tr('Voidwatch')
  size: 760 370

  Panel
    id: top
    anchors.top: parent.top
    anchors.left: parent.left
    anchors.right: parent.right
    layout:
      type: verticalBox
      spacing: 7
      fit-children: true

    Panel
      id: head
      height: 18

      Label
        id: name
        anchors.left: parent.left
        anchors.verticalCenter: parent.verticalCenter
        color: #ffffff
        font: verdana-11px-rounded
        text-auto-resize: true

      Label
        id: server
        anchors.left: name.right
        anchors.verticalCenter: parent.verticalCenter
        margin-left: 8
        color: #9b9b9b
        text-auto-resize: true

      Label
        id: stateText
        anchors.right: parent.right
        anchors.verticalCenter: parent.verticalCenter
        text-auto-resize: true

      VwDot
        id: stateDot
        anchors.right: stateText.left
        anchors.verticalCenter: parent.verticalCenter
        margin-right: 5

  TabBar
    id: tabs
    anchors.top: top.bottom
    anchors.left: parent.left
    anchors.right: parent.right
    margin-top: 8

  VwFrame
    id: content
    anchors.top: tabs.bottom
    anchors.left: parent.left
    anchors.right: parent.right
    anchors.bottom: closeButton.top
    margin-bottom: 8

  Label
    id: version
    anchors.left: parent.left
    anchors.verticalCenter: closeButton.verticalCenter
    color: #6f6f6f
    text-auto-resize: true

  VwLink
    id: update
    anchors.left: version.right
    anchors.verticalCenter: closeButton.verticalCenter
    margin-left: 10
    color: #ffdd55
    visible: false

  VwLink
    id: rollback
    anchors.left: update.right
    anchors.verticalCenter: closeButton.verticalCenter
    margin-left: 12
    visible: false

  Button
    id: closeButton
    !text: tr('Close')
    anchors.right: parent.right
    anchors.bottom: parent.bottom
    size: 84 21

  Button
    id: dashboardButton
    !text: tr('Dashboard')
    anchors.right: closeButton.left
    anchors.bottom: parent.bottom
    margin-right: 5
    size: 84 21

voidwatch/bot/voidwatch_bot.lua

-- Voidwatch bot adapter, MIT licence. The Voidwatch module copies it into the bot's config folder when the player
-- turns it on; the bot loads every .lua file there. It hands the bot's state to the module every 10 s, and it changes
-- the bot only through the commands below. It works with the stock cavebot, vBot and presets built on them: each value
-- is read only where its function exists, and a missing one stays out of the status.
local VERSION = '5'

local config = (function()
  local ok, name = pcall(function() return modules.game_bot.contentsPanel.config:getCurrentOption().text end)
  return ok and name or nil
end)()

local function fn(t, k) return type(t) == 'table' and type(t[k]) == 'function' and t[k] or nil end

-- the cavebot and targetbot keep the loaded profile in the same place in every stock config
local function selected(kind)
  local c = type(storage) == 'table' and type(storage._configs) == 'table' and storage._configs[kind]
  return type(c) == 'table' and c.selected or nil
end

local routeList = { at = nil, names = nil }
local function routes()
  if not config then return nil end
  if routeList.at and now - routeList.at < 60000 then return routeList.names end
  local names = {}
  local ok, files = pcall(g_resources.listDirectoryFiles, '/bot/' .. config .. '/cavebot_configs')
  for _, f in ipairs(ok and type(files) == 'table' and files or {}) do
    local n = tostring(f):match('^(.+)%.cfg$')
    if n then names[#names + 1] = n end
  end
  table.sort(names)
  routeList.at, routeList.names = now, names
  return names
end

-- vBot remembers the last label; the stock cavebot only has its waypoint list, so the label above the current row
local function label()
  local last = fn(CaveBot, 'lastReachedLabel')
  if last then
    local v = last()
    if v and v ~= '' then return v end
  end
  local list = type(CaveBot) == 'table' and CaveBot.actionList
  local cur = list and list:getFocusedChild()
  if not cur then return nil end
  for i = list:getChildIndex(cur), 1, -1 do
    local row = list:getChildByIndex(i)
    if row and row.action == 'label' then return row.value end
  end
  return nil
end

local function itemName(id)
  local ok, name = pcall(function()
    local m = g_things.getThingType(id, ThingCategoryItem):getMarketData()
    return m and m.name ~= '' and m.name or nil
  end)
  return ok and name or ('item ' .. id)
end

-- vBot's supply list: the bot buys up to max, so max is what it keeps in stock
local function supplies()
  local data = type(Supplies) == 'table' and fn(Supplies, 'getItemsData')
  if not data then return nil end
  local rows = {}
  for id, v in pairs(data()) do
    local n = tonumber(id)
    if n and #rows < 30 then
      rows[#rows + 1] = { name = itemName(n), have = player:getItemsCount(n) or 0, want = tonumber(v.max) or 0 }
    end
  end
  table.sort(rows, function(a, b) return a.name < b.name end)
  return rows
end

local function botProfile()
  if type(vBot) ~= 'table' then return nil end
  local ok, n = pcall(g_settings.getNumber, 'profile')
  return ok and type(n) == 'number' and n >= 1 and n <= 20 and n or nil
end

local function onOff(t)
  local isOn = fn(t, 'isOn')
  if isOn then return isOn() and true or false end
  return nil
end

-- where the character is in its route, from the label of each route part: the player names the labels, and each
-- role takes a comma list of names (Clients → Module on the website)
local ROLES = { 'hunt', 'refill', 'city', 'resp' }
local LEG = { hunt = 'hunting', refill = 'to_city', city = 'in_city', resp = 'to_resp' }
local PARKED_SQM = 8

local function xyz(value)
  local x, y, z = tostring(value):match('^%s*(%d+)%s*,%s*(%d+)%s*,%s*(%d+)')
  return tonumber(x), tonumber(y), tonumber(z)
end

local function roleNames()
  local vw = modules.voidwatch and modules.voidwatch.Voidwatch
  local given = vw and vw.labelRoles and vw.labelRoles() or {}
  local out = {}
  for _, role in ipairs(ROLES) do
    out[role] = {}
    for name in tostring(type(given[role]) == 'string' and given[role] ~= '' and given[role] or role):gmatch('[^,]+') do
      out[role][name:match('^%s*(.-)%s*$'):lower()] = true
    end
  end
  return out
end

local spot = { at = -1 }
local function whereInRoute()
  if spot.at == now then return spot end
  spot = { at = now }
  local list = type(CaveBot) == 'table' and CaveBot.actionList
  if not list then return spot end
  local names, marks, roleAt, children = roleNames(), {}, {}, list:getChildren()
  for index, child in ipairs(children) do
    if child.action == 'label' then
      local v = tostring(child.value):lower()
      for _, role in ipairs(ROLES) do
        if names[role][v] then
          roleAt[index] = roleAt[index] or role
          marks[role] = marks[role] or index
        end
      end
    end
  end
  local missing = {}
  for _, role in ipairs(ROLES) do
    if not marks[role] then missing[#missing + 1] = role end
  end
  spot.missing = #missing > 0 and missing or nil
  if spot.missing then spot.phase = 'unknown'; return spot end
  if onOff(CaveBot) == false then
    local p = g_game.getLocalPlayer()
    local pos = p and p:getPosition()
    local okPz, pz = pcall(function() return p:hasState(PlayerStates.Pz) end)
    local near = false
    for i = marks.city + 1, #children do
      if children[i].action == 'goto' then
        local x, y, z = xyz(children[i].value)
        near = pos and x and pos.z == z and math.max(math.abs(pos.x - x), math.abs(pos.y - y)) <= PARKED_SQM or false
        break
      end
    end
    spot.phase = (near or (okPz and pz)) and 'parked' or 'stopped'
    return spot
  end
  local cur = list:getFocusedChild()
  local at = cur and list:getChildIndex(cur)
  if not at then spot.phase = 'unknown'; return spot end
  for step = 0, #children - 1 do
    local role = roleAt[(at - 1 - step) % #children + 1]
    if role then spot.phase = LEG[role]; return spot end
  end
  return spot
end

local function currentRoute()
  local get = fn(CaveBot, 'getCurrentProfile')
  return (get and get()) or selected('cavebot_configs')
end

local function switch(t, name, on)
  if type(on) ~= 'boolean' then return false, 'on must be true or false' end
  local set = fn(t, on and 'setOn' or 'setOff')
  if not set then return false, name .. ' is not loaded' end
  set()
  return true, name .. (on and ' on' or ' off')
end

local function nearestGoto(list, me)
  local best, bestDist, bestIndex
  for index, child in ipairs(list:getChildren()) do
    if child.action == 'goto' then
      local x, y, z = tostring(child.value):match('^%s*(%d+)%s*,%s*(%d+)%s*,%s*(%d+)')
      x, y, z = tonumber(x), tonumber(y), tonumber(z)
      if z == me.z then
        local d = math.max(math.abs(x - me.x), math.abs(y - me.y))
        if not bestDist or d < bestDist then best, bestDist, bestIndex = child, d, index end
      end
    end
  end
  return best, bestDist, bestIndex
end

local function resetHere()
  local list = type(CaveBot) == 'table' and CaveBot.actionList
  if not list then return false, 'the cavebot is not loaded' end
  local best, dist, index = nearestGoto(list, g_game.getLocalPlayer():getPosition())
  if not best then return false, 'no waypoint on this floor' end
  list:focusChild(best)
  return true, ('waypoint %d, %d sqm away'):format(index, dist)
end

-- plans: a command that acts when the bot reaches a label of its route. The hooks wrap the bot's own label and goto
-- steps and its gotoLabel, so a plan never edits the route; without a running plan they only pass the step on. The
-- module keeps the plan on disk, so a bot reload does not lose it.
local PLAN_KEEP_S = 120
local plan, planLoaded = nil, false
local onLabel, onGoto

local function vw() return modules.voidwatch and modules.voidwatch.Voidwatch end

local function savePlan()
  local m = vw()
  if m and m.savePlan then pcall(m.savePlan, plan) end
end

local function waitMin()
  local m = vw()
  local ok, n = pcall(function() return m.planWait() end)
  return ok and tonumber(n) or 20
end

local function roleOf(value, names)
  local v = tostring(value):lower()
  for _, role in ipairs(ROLES) do
    if names[role][v] then return role end
  end
end

local function firstLabel(role)
  local names = roleNames()
  for _, child in ipairs(CaveBot.actionList:getChildren()) do
    if child.action == 'label' and roleOf(child.value, names) == role then return child end
  end
end

local function jump(role)
  local row = firstLabel(role)
  if not row then return false end
  CaveBot.actionList:focusChild(row)
  if type(vBot) == 'table' then vBot.lastLabel = row.value end
  return true
end

local function setStep(step, message)
  plan.step, plan.message, plan.deadline = step, message, os.time() + waitMin() * 60
  savePlan()
  return true, message
end

local function finish(state, message)
  plan.state, plan.step, plan.message, plan.ended, plan.deadline = state, nil, message, os.time(), nil
  savePlan()
  return true, message
end

local function hook(name, after)
  local a = type(CaveBot) == 'table' and type(CaveBot.Actions) == 'table' and CaveBot.Actions[name]
  if type(a) ~= 'table' or type(a.callback) ~= 'function' then return false end
  if not a.voidwatch then
    local original = a.callback
    a.callback = function(value, ...)
      local list = CaveBot.actionList
      local row = list and list:getFocusedChild()
      local at = row and list:getChildIndex(row)
      local result = original(value, ...)
      if result == true and plan and plan.state == 'running' then pcall(after, value, at) end
      return result
    end
    a.voidwatch = true
  end
  return true
end

-- a jump with gotolabel or a supply check skips the label step itself, so the jump is a hook too
local function hookJump()
  local go = fn(CaveBot, 'gotoLabel')
  if not go then return false end
  if CaveBot.voidwatchJump ~= go then
    local wrapped = function(label, ...)
      local result = go(label, ...)
      if result and plan and plan.state == 'running' then pcall(onLabel, label) end
      return result
    end
    CaveBot.gotoLabel, CaveBot.voidwatchJump = wrapped, wrapped
  end
  return true
end

local function hooked()
  local a, b, c = hook('label', onLabel), hook('goto', onGoto), hookJump()
  return a and b and c
end

local function routeFile(name) return '/bot/' .. tostring(config) .. '/cavebot_configs/' .. name .. '.cfg' end

local function routeHasCity(name)
  local ok, src = pcall(g_resources.readFileContents, routeFile(name))
  if not ok or type(src) ~= 'string' then return false end
  local names = roleNames().city
  for line in src:gmatch('[^\r\n]+') do
    local v = line:match('^label:(.+)$')
    if v and names[v:match('^%s*(.-)%s*$'):lower()] then return true end
  end
  return false
end

local function stopAfter(row)
  local list = CaveBot.actionList
  local children = list:getChildren()
  for i = (list:getChildIndex(row) or #children) + 1, #children do
    if children[i].action == 'goto' then
      plan.stopAt = i
      return setStep('depot', 'walking into the depot')
    end
  end
  return finish('failed', 'no step after the city label')
end

local function loadRoute()
  if not (plan and plan.state == 'running' and plan.step == 'switch') then return end
  if not g_resources.fileExists(routeFile(plan.route)) then return finish('failed', plan.route .. ' is gone') end
  CaveBot.setOff()
  storage._configs.cavebot_configs.selected = plan.route
  CaveBot.setOn()
  plan.routeAt = currentRoute()
  if plan.routeAt ~= plan.route then CaveBot.setOff(); return finish('failed', plan.route .. ' did not load') end
  if not jump('city') then CaveBot.setOff(); return finish('failed', plan.route .. ' has no city label') end
  finish('done', plan.route .. ' runs from city')
end

-- the old route stops before the new one loads, and the new one starts at its own city: no step of the old one runs
local function switchRoute()
  CaveBot.setOff()
  setStep('switch', 'loading ' .. plan.route)
  if type(schedule) == 'function' then schedule(300, loadRoute) else loadRoute() end
end

function onLabel(value, at)
  local role = roleOf(value, roleNames())
  if plan.step == 'hunt' and role == 'refill' then
    if plan.kind == 'refill' then return finish('done', 'on the way to the city') end
    return setStep('city', 'waiting for city')
  elseif plan.step == 'hunt' and role == 'hunt' then
    if not jump('refill') then return finish('failed', 'the route has no refill label') end
    if plan.kind == 'refill' then return finish('done', 'on the way to the city') end
    return setStep('city', 'waiting for city')
  elseif plan.step == 'city' and role == 'city' then
    if plan.kind == 'load_route' then return switchRoute() end
    local list = CaveBot.actionList
    return stopAfter(at and list:getChildByIndex(at) or list:getFocusedChild())
  end
end

function onGoto(_, at)
  if plan.step ~= 'depot' or at ~= plan.stopAt then return end
  CaveBot.setOff()
  finish('done', 'parked in the depot')
end

local function startPlan(kind, args, ctx)
  if not hooked() then return false, 'plans need vBot or the stock cavebot' end
  local where = whereInRoute()
  if where.missing then return false, 'the route misses labels: ' .. table.concat(where.missing, ', ') end
  local phase = where.phase
  local route = type(args) == 'table' and type(args.route) == 'string' and args.route or nil
  if kind == 'load_route' then
    if not route or not g_resources.fileExists(routeFile(route)) then return false, 'no route ' .. tostring(route) end
    if route == currentRoute() then return false, route .. ' is loaded already' end
    if not routeHasCity(route) then return false, route .. ' has no city label' end
  end
  if kind == 'refill' and (phase == 'to_city' or phase == 'in_city') then return true, 'on the way to the city already' end
  if kind == 'go_depot' and phase == 'parked' then return true, 'parked already' end
  if phase == 'stopped' or (kind == 'refill' and phase == 'parked') then return false, 'the cavebot is off' end
  plan = { id = type(ctx) == 'table' and tonumber(ctx.id) or nil, kind = kind, route = route, state = 'running', since = os.time(),
           routeAt = currentRoute() }
  if kind == 'load_route' and (phase == 'parked' or phase == 'in_city') then
    switchRoute()
    return true, 'loading ' .. route
  end
  if kind == 'go_depot' and phase == 'in_city' then
    local row = firstLabel('city')
    CaveBot.actionList:focusChild(row)
    return stopAfter(row)
  end
  if phase == 'to_city' then return setStep('city', 'waiting for city') end
  return setStep('hunt', 'waiting for hunt')
end

local function resume()
  if not hooked() then return false, 'plans need vBot or the stock cavebot' end
  local where = whereInRoute()
  if where.missing then return false, 'the route misses labels: ' .. table.concat(where.missing, ', ') end
  if where.phase ~= 'parked' then return false, onOff(CaveBot) and 'the cavebot runs already' or 'the character is not parked' end
  CaveBot.setOn()
  jump('city')
  return true, 'resumed at city'
end

local function cancelPlan()
  if not (plan and plan.state == 'running') then return false, 'no plan runs' end
  return finish('cancelled', 'cancelled')
end

local function watchPlan()
  if type(CaveBot) == 'table' then hooked() end
  if not planLoaded then
    local m = vw()
    local ok, saved = pcall(function() return m.loadPlan() end)
    if ok and saved ~= false then
      planLoaded, plan = true, type(saved) == 'table' and saved or nil
      if plan and plan.state == 'running' and plan.step == 'switch' then loadRoute() end
    end
  end
  if not plan then return end
  if plan.state ~= 'running' then
    if os.time() - (tonumber(plan.ended) or 0) > PLAN_KEEP_S then plan = nil; savePlan() end
    return
  end
  if plan.step ~= 'switch' and currentRoute() ~= plan.routeAt then return finish('taken_over', 'another route was loaded') end
  if os.time() > (tonumber(plan.deadline) or 0) then return finish('stuck', ('no %s within %d min'):format(tostring(plan.step), waitMin())) end
end

local function planState()
  if not plan then return nil end
  return { id = plan.id, kind = plan.kind, route = plan.route, state = plan.state, step = plan.step, message = plan.message,
           since = plan.since, ['until'] = plan.deadline, ended = plan.ended }
end

local adapter = {
  id = 'bot', version = VERSION,
  actions = {
    toggle_cavebot = function(args) return switch(CaveBot, 'cavebot', args.on) end,
    toggle_targetbot = function(args) return switch(TargetBot, 'targeting', args.on) end,
    reset_here = resetHere,
    refill = function(args, ctx) return startPlan('refill', args, ctx) end,
    go_depot = function(args, ctx) return startPlan('go_depot', args, ctx) end,
    load_route = function(args, ctx) return startPlan('load_route', args, ctx) end,
    resume = resume,
    cancel_plan = cancelPlan,
  },
  fields = {
    botConfig = function() return config end,
    routeOn = function() return onOff(CaveBot) end,
    route = currentRoute,
    routes = routes,
    label = label,
    phase = function() return whereInRoute().phase end,
    labelsMissing = function() return whereInRoute().missing end,
    plan = planState,
    targetOn = function() return onOff(TargetBot) end,
    targetProfile = function() local get = fn(TargetBot, 'getCurrentProfile'); return (get and get()) or selected('targetbot_configs') end,
    botProfile = botProfile,
    supplies = supplies,
  },
}

local function attach()
  local vw = modules.voidwatch and modules.voidwatch.Voidwatch
  if vw and vw.attachBot then pcall(vw.attachBot, adapter) end
end
attach()
macro(1000, watchPlan)
macro(10000, attach)

setup-windows.cmd

@echo off
rem Voidwatch setup for Windows: copies the upload script, starts it now and at every login. No admin rights needed.
rem Drop the folder the game message showed onto this file to add a client that is not in the usual place.
setlocal
set "DEST=%LOCALAPPDATA%\Voidwatch"
mkdir "%DEST%" 2>nul
copy /Y "%~dp0upload\upload.ps1" "%DEST%\upload.ps1" >nul
if not "%~1"=="" echo %~1>>"%DEST%\folders.txt"
powershell -NoProfile -ExecutionPolicy Bypass -Command "$s = (New-Object -ComObject WScript.Shell).CreateShortcut([Environment]::GetFolderPath('Startup') + '\Voidwatch upload.lnk'); $s.TargetPath = 'powershell.exe'; $s.Arguments = '-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File \"' + $env:LOCALAPPDATA + '\Voidwatch\upload.ps1\"'; $s.WindowStyle = 7; $s.Save()"
start "" powershell -NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File "%DEST%\upload.ps1"
echo.
echo Voidwatch is set up. It runs in the background now and starts with Windows from now on.
echo Start the game and log in: a game message shows a code and a link.
echo.
pause

setup-mac.command

#!/bin/sh
# Voidwatch setup for macOS, also for clients in CrossOver or Wine: copies the upload script, starts it now and at
# every login. Double-click it. The first time, macOS may ask: right-click the file, pick Open, then Open again.
set -eu
DEST="$HOME/Library/Application Support/Voidwatch"
# macOS lists a login item under the name of the file it starts, so the script runs as "Voidwatch Upload"
APP="$DEST/Voidwatch Upload"
PLIST="$HOME/Library/LaunchAgents/xyz.voidwatch.upload.plist"
mkdir -p "$DEST" "$HOME/Library/LaunchAgents"
launchctl unload "$PLIST" 2>/dev/null || true
# an earlier setup started the script as "sh upload.sh"
pkill -f "Voidwatch/upload.sh" 2>/dev/null || true
rm -f "$DEST/upload.sh"
cp "$(dirname "$0")/upload/upload.sh" "$APP"
chmod 755 "$APP"
xattr -d com.apple.quarantine "$APP" 2>/dev/null || true
echo "Drag the folder the game message showed into this window and press Enter,"
printf "or just press Enter to look in the usual places: "
read -r folder || folder=""
folder=$(printf '%s' "$folder" | sed "s/^'//; s/'$//; s/\\\\ / /g")
[ -n "$folder" ] && printf '%s\n' "$folder" >> "$DEST/folders.txt"
cat > "$PLIST" <<PL
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>Label</key><string>xyz.voidwatch.upload</string>
  <key>ProgramArguments</key><array><string>$APP</string></array>
  <key>RunAtLoad</key><true/><key>KeepAlive</key><true/>
</dict></plist>
PL
launchctl load "$PLIST"
echo
echo "Voidwatch is set up. It runs in the background as \"Voidwatch Upload\" and starts with your Mac from now on."
echo "Start the game and log in: a game message shows a code and a link. You can close this window."

setup-linux.sh

#!/bin/sh
# Voidwatch setup for Linux, also for clients in Wine: copies the upload script and runs it as a user service, now and
# at every login. Run: sh setup-linux.sh [the folder the game message showed]
set -eu
DEST="${XDG_DATA_HOME:-$HOME/.local/share}/voidwatch"
UNIT="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/voidwatch.service"
mkdir -p "$DEST" "$(dirname "$UNIT")"
cp "$(dirname "$0")/upload/upload.sh" "$DEST/upload.sh"
[ $# -gt 0 ] && printf '%s\n' "$1" >> "$DEST/folders.txt"
cat > "$UNIT" <<U
[Unit]
Description=Voidwatch upload script
[Service]
ExecStart=/bin/sh $DEST/upload.sh
Restart=always
RestartSec=5
[Install]
WantedBy=default.target
U
systemctl --user daemon-reload
systemctl --user enable --now voidwatch.service
echo "Voidwatch is set up and starts at every login. Start the game and log in: a game message shows a code and a link."

upload/upload.ps1

# Voidwatch upload script for Windows. It sends what the module writes and brings back the replies. MIT licence.
#   powershell -ExecutionPolicy Bypass -File upload.ps1                        watch every client
#   powershell -ExecutionPolicy Bypass -File upload.ps1 "<voidwatch folder>"   watch one client
# The module shows the voidwatch folder in a game message. Every character has its own folder inside it, and its own
# hidden worker.
param([string]$Dir = '', [switch]$Worker)
$Home_ = Join-Path $env:LOCALAPPDATA 'Voidwatch'
# module updates come from the GitHub releases, not from the website: a broken-into website cannot ship code
$Releases = if ($env:VOIDWATCH_RELEASES) { $env:VOIDWATCH_RELEASES } else { 'https://github.com/voidwatch-xyz/module/releases' }
$LatestApi = if ($env:VOIDWATCH_LATEST) { $env:VOIDWATCH_LATEST } else { 'https://api.github.com/repos/voidwatch-xyz/module/releases/latest' }
$Site = $(if ($env:VOIDWATCH_API) { $env:VOIDWATCH_API } else { 'https://voidwatch.xyz/api/v1' }) -replace '/api/v1/?$', ''

if (-not $Worker) {
  $latest = ''; $latestAt = [datetime]::MinValue
  function Version-Of($otmod) {
    $m = Select-String -Path $otmod -Pattern '^\s*version:\s*([0-9.]+)' -ErrorAction SilentlyContinue | Select-Object -First 1
    if ($m) { $m.Matches[0].Groups[1].Value } else { '' }
  }
  function Write-Text($path, $text) { [IO.File]::WriteAllText("$path.tmp", $text); Move-Item -Force "$path.tmp" $path }
  # the module folder the client loads: beside the data folder in bot\_voidwatch, or the write folder's modules folder
  function Module-Of($d) {
    if ($d -match '[\\/]_voidwatch[\\/]data[\\/]?$') { return Join-Path (Split-Path $d) 'voidwatch' }
    Join-Path (Split-Path $d) 'modules\voidwatch'
  }
  function Can-Write($m) {
    if (-not (Test-Path (Join-Path $m 'voidwatch.otmod'))) { return $false }
    try { [IO.File]::WriteAllText((Join-Path $m '.w'), ''); Remove-Item -Force (Join-Path $m '.w'); return $true } catch { return $false }
  }
  function Update-Done($d, $result) {
    Write-Text (Join-Path $d 'update-result.json') ($result | ConvertTo-Json -Compress)
    Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $d 'update-request.json'), (Join-Path $d 'rollback-request.json')
    Remove-Item -Recurse -Force -ErrorAction SilentlyContinue (Join-Path $d '.update')
  }
  # an update the window asked for: the release zip, checked against its SHA256SUMS; the old folder stays as a backup
  function Update-Module($d) {
    $m = Module-Of $d; $t = Join-Path $d '.update'; $b = Join-Path $d 'backup'
    $req = Get-Content (Join-Path $d 'update-request.json') -Raw -ErrorAction SilentlyContinue | ConvertFrom-Json
    $v = [string]$req.version; $by = [string]$req.by
    if ($v -notmatch '^[0-9.]+$') { Update-Done $d @{ ok = $false; error = 'no version asked for' }; return }
    Remove-Item -Recurse -Force -ErrorAction SilentlyContinue $t
    New-Item -ItemType Directory -Force -Path $t | Out-Null
    try {
      Invoke-WebRequest -UseBasicParsing -TimeoutSec 120 -Uri "$Releases/download/v$v/voidwatch-module.zip" -OutFile (Join-Path $t 'm.zip')
      Invoke-WebRequest -UseBasicParsing -TimeoutSec 30 -Uri "$Releases/download/v$v/SHA256SUMS" -OutFile (Join-Path $t 'SHA256SUMS')
    } catch { Update-Done $d @{ ok = $false; error = 'the download failed' }; return }
    $line = Select-String -Path (Join-Path $t 'SHA256SUMS') -Pattern '^([0-9a-f]{64})\s+voidwatch-module\.zip' | Select-Object -First 1
    $want = if ($line) { $line.Matches[0].Groups[1].Value } else { '' }
    $got = (Get-FileHash -Algorithm SHA256 (Join-Path $t 'm.zip')).Hash.ToLower()
    if (-not $want -or $want -ne $got) { Update-Done $d @{ ok = $false; error = 'the checksum does not match' }; return }
    try { Expand-Archive -Path (Join-Path $t 'm.zip') -DestinationPath (Join-Path $t 'x') -Force } catch { }
    if ((Version-Of (Join-Path $t 'x\voidwatch\voidwatch.otmod')) -ne $v) { Update-Done $d @{ ok = $false; error = 'the zip holds another version' }; return }
    $old = Version-Of (Join-Path $m 'voidwatch.otmod')
    try {
      Remove-Item -Recurse -Force -ErrorAction SilentlyContinue $b
      New-Item -ItemType Directory -Force -Path $b | Out-Null
      Copy-Item -Recurse $m (Join-Path $b 'voidwatch')
      [IO.File]::WriteAllText((Join-Path $b 'version'), $old)
    } catch { Update-Done $d @{ ok = $false; error = 'no backup could be made' }; return }
    try {
      Remove-Item -Recurse -Force $m
      Move-Item (Join-Path $t 'x\voidwatch') $m
    } catch {
      Copy-Item -Recurse (Join-Path $b 'voidwatch') $m -ErrorAction SilentlyContinue
      Update-Done $d @{ ok = $false; error = 'the swap failed' }; return
    }
    # the installed copy of this script updates itself too, once the new one parses; the main loop then starts it again
    $new = Join-Path $t 'x\upload\upload.ps1'
    if ($PSCommandPath.StartsWith($Home_, [StringComparison]::OrdinalIgnoreCase) -and (Test-Path $new) -and
        (Get-FileHash $new).Hash -ne (Get-FileHash $PSCommandPath).Hash) {
      $errors = $null
      [void][System.Management.Automation.Language.Parser]::ParseFile($new, [ref]$null, [ref]$errors)
      if (-not $errors) {
        try {
          Copy-Item -Force $new "$PSCommandPath.new"
          Move-Item -Force "$PSCommandPath.new" $PSCommandPath
          $script:restartSelf = $true
        } catch { }
      }
    }
    Update-Done $d @{ ok = $true; version = $v; from = $old; by = $by; at = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds() }
  }
  # addons come from the release of the module version the folder runs, checked against the same SHA256SUMS. A failed
  # download waits 30 minutes or a new module version before it tries again.
  function Install-Addon($d, $id, $v) {
    $t = Join-Path $d '.addon'; $dir = Join-Path $d 'addons'
    Remove-Item -Recurse -Force -ErrorAction SilentlyContinue $t
    New-Item -ItemType Directory -Force -Path $t, $dir | Out-Null
    try {
      Invoke-WebRequest -UseBasicParsing -TimeoutSec 60 -Uri "$Releases/download/v$v/addon-$id.zip" -OutFile (Join-Path $t 'a.zip')
      Invoke-WebRequest -UseBasicParsing -TimeoutSec 30 -Uri "$Releases/download/v$v/SHA256SUMS" -OutFile (Join-Path $t 'SHA256SUMS')
      $line = Select-String -Path (Join-Path $t 'SHA256SUMS') -Pattern ('^([0-9a-f]{64})\s+addon-' + [regex]::Escape($id) + '\.zip$') | Select-Object -First 1
      $want = if ($line) { $line.Matches[0].Groups[1].Value } else { '' }
      $got = (Get-FileHash -Algorithm SHA256 (Join-Path $t 'a.zip')).Hash.ToLower()
      if ($want -and $want -eq $got) {
        Expand-Archive -Path (Join-Path $t 'a.zip') -DestinationPath (Join-Path $t 'x') -Force
        if (Test-Path (Join-Path $t "x\$id\main.lua")) {
          [IO.File]::WriteAllText((Join-Path $t "x\$id\.version"), $v)
          Remove-Item -Recurse -Force -ErrorAction SilentlyContinue (Join-Path $dir $id)
          Move-Item (Join-Path $t "x\$id") (Join-Path $dir $id)
          Remove-Item -Recurse -Force -ErrorAction SilentlyContinue $t, (Join-Path $dir ".failed-$id")
          return
        }
      }
    } catch { }
    Remove-Item -Recurse -Force -ErrorAction SilentlyContinue $t
    [IO.File]::WriteAllText((Join-Path $dir ".failed-$id"), $v)
  }
  function Sync-Addons($d) {
    $v = Version-Of (Join-Path (Module-Of $d) 'voidwatch.otmod')
    $w = Get-Content (Join-Path $d 'addons-wanted.json') -Raw -ErrorAction SilentlyContinue | ConvertFrom-Json -ErrorAction SilentlyContinue
    $wanted = @($w.ids | Where-Object { $_ -match '^[a-z0-9-]+$' })
    $dir = Join-Path $d 'addons'
    foreach ($id in $wanted) {
      $have = Get-Content (Join-Path $dir "$id\.version") -Raw -ErrorAction SilentlyContinue
      if ($have -and $have.Trim() -eq $v) { continue }
      $f = Get-Item (Join-Path $dir ".failed-$id") -ErrorAction SilentlyContinue
      if ($f -and (Get-Content $f.FullName -Raw).Trim() -eq $v -and ((Get-Date) - $f.LastWriteTime).TotalSeconds -lt 1800) { continue }
      Install-Addon $d $id $v
    }
    foreach ($p in (Get-ChildItem -Directory $dir -ErrorAction SilentlyContinue)) {
      if ($wanted -notcontains $p.Name) { Remove-Item -Recurse -Force -ErrorAction SilentlyContinue $p.FullName }
    }
  }
  # the pictures the Voidwatch window asks for: lines "id file path", only addon pictures from the website, PNG, 2 MB at most
  function Fetch-Pictures($d) {
    $w = Join-Path $d 'addon-pictures-wanted.txt'
    foreach ($line in @(Get-Content $w -ErrorAction SilentlyContinue)) {
      $parts = @("$line".Trim() -split '\s+')
      if ($parts.Count -ne 3) { continue }
      $id, $file, $src = $parts
      if ($id -notmatch '^[a-z0-9-]+$' -or $file -notmatch '^[A-Za-z0-9_-]+\.png$' -or $src -cne "/static/img/addons/$id/$file") { continue }
      $dir = Join-Path $d "addon-pictures\$id"; $out = Join-Path $dir $file
      if (Test-Path $out) { continue }
      try {
        New-Item -ItemType Directory -Force -Path $dir | Out-Null
        Invoke-WebRequest -UseBasicParsing -TimeoutSec 30 -Uri ($Site + $src) -OutFile "$out.part"
        $b = [IO.File]::ReadAllBytes("$out.part")
        if ($b.Length -ge 8 -and $b.Length -le 2097152 -and $b[0] -eq 0x89 -and $b[1] -eq 0x50 -and $b[2] -eq 0x4E -and $b[3] -eq 0x47) {
          Move-Item -Force "$out.part" $out
        } else { Remove-Item -Force -ErrorAction SilentlyContinue "$out.part" }
      } catch { Remove-Item -Force -ErrorAction SilentlyContinue "$out.part" }
    }
    Remove-Item -Force -ErrorAction SilentlyContinue $w
  }
  function Rollback-Module($d) {
    $m = Module-Of $d; $b = Join-Path $d 'backup'
    $req = Get-Content (Join-Path $d 'rollback-request.json') -Raw -ErrorAction SilentlyContinue | ConvertFrom-Json
    if (-not (Test-Path (Join-Path $b 'voidwatch\voidwatch.otmod'))) { Update-Done $d @{ ok = $false; error = 'there is no backup' }; return }
    $v = (Get-Content (Join-Path $b 'version') -Raw -ErrorAction SilentlyContinue).Trim()
    Remove-Item -Recurse -Force -ErrorAction SilentlyContinue $m
    Copy-Item -Recurse (Join-Path $b 'voidwatch') $m
    Remove-Item -Recurse -Force -ErrorAction SilentlyContinue $b
    Update-Done $d @{ ok = $true; version = $v; rollback = $true; by = [string]$req.by; at = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds() }
  }
  $restartSelf = $false
  while ($true) {
    # the newest release, asked at most every 6 hours: GitHub answers 60 questions an hour without an account
    if (((Get-Date) - $latestAt).TotalHours -ge 6) {
      $latestAt = Get-Date
      try { $r = Invoke-RestMethod -TimeoutSec 20 -Uri $LatestApi; if ([string]$r.tag_name -match '^v([0-9.]+)$') { $latest = $matches[1] } } catch { }
    }
    if ($Dir) {
      $found = @($Dir)
    } else {
      $found = @(Get-ChildItem (Join-Path $env:APPDATA 'OTClientV8') -Directory -ErrorAction SilentlyContinue |
        ForEach-Object { (Join-Path $_.FullName 'voidwatch'), (Join-Path $_.FullName 'bot\_voidwatch\data') } | Where-Object { Test-Path $_ })
      $list = Join-Path $Home_ 'folders.txt'
      if (Test-Path $list) { $found += Get-Content $list | Where-Object { $_ -and (Test-Path $_) } }
    }
    foreach ($d in ($found | Sort-Object -Unique)) {
      $chars = Get-ChildItem $d -Directory -ErrorAction SilentlyContinue | Where-Object { Test-Path (Join-Path $_.FullName 'outbox') }
      foreach ($c in $chars) {
        $pidFile = Join-Path $c.FullName '.pid'
        $alive = $false
        if (Test-Path $pidFile) { $alive = [bool](Get-Process -Id ([int](Get-Content $pidFile)) -ErrorAction SilentlyContinue) }
        if (-not $alive) {
          $p = Start-Process powershell -WindowStyle Hidden -PassThru -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass',
            '-File', "`"$PSCommandPath`"", '-Worker', '-Dir', "`"$($c.FullName)`"")
          Set-Content -Path $pidFile -Value $p.Id
        }
      }
      $m = Module-Of $d
      $writable = Can-Write $m
      $backup = (Get-Content (Join-Path $d 'backup\version') -Raw -ErrorAction SilentlyContinue)
      # the website passes on the newest release it saw on GitHub within 5 minutes; the higher of the two counts
      $told = @(Get-ChildItem $d -Directory -ErrorAction SilentlyContinue | ForEach-Object {
        $r = Get-Content (Join-Path $_.FullName 'inbox\reply.json') -Raw -ErrorAction SilentlyContinue
        if ($r -match '"latestModule"\s*:\s*"(\d+\.\d+\.\d+)"') { $matches[1] }
      })
      $best = @(@($latest) + $told | Where-Object { $_ -match '^\d+\.\d+\.\d+$' } | Sort-Object { [version]$_ } | Select-Object -Last 1)
      $best = if ($best.Count) { [string]$best[0] } else { '' }
      Write-Text (Join-Path $d 'latest.json') (@{ latest = $best; updatable = $writable; backup = if ($backup) { $backup.Trim() } else { '' } } | ConvertTo-Json -Compress)
      if ($writable -and (Test-Path (Join-Path $d 'update-request.json'))) { Update-Module $d }
      if ($writable -and (Test-Path (Join-Path $d 'rollback-request.json'))) { Rollback-Module $d }
      if (Test-Path (Join-Path $d 'addons-wanted.json')) { Sync-Addons $d }
      if (Test-Path (Join-Path $d 'addon-pictures-wanted.txt')) { Fetch-Pictures $d }
    }
    if ($restartSelf) {
      # the new script takes over: the workers stop, and a new hidden main script starts them again
      foreach ($d in ($found | Sort-Object -Unique)) {
        foreach ($c in @(Get-ChildItem $d -Directory -ErrorAction SilentlyContinue)) {
          $pf = Join-Path $c.FullName '.pid'
          $wp = if (Test-Path $pf) { Get-Process -Id ([int](Get-Content $pf)) -ErrorAction SilentlyContinue }
          if ($wp -and $wp.ProcessName -eq 'powershell') { Stop-Process -Id $wp.Id -Force -ErrorAction SilentlyContinue }
        }
      }
      $again = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', "`"$PSCommandPath`"")
      if ($Dir) { $again += "`"$Dir`"" }
      Start-Process powershell -WindowStyle Hidden -ArgumentList $again
      exit
    }
    Start-Sleep -Seconds 2
  }
}

$Api = if ($env:VOIDWATCH_API) { $env:VOIDWATCH_API } else { 'https://voidwatch.xyz/api/v1' }
$Dir = $Dir.TrimEnd('\', '/')
$Out = Join-Path $Dir 'outbox'; $In = Join-Path $Dir 'inbox'; $TokenFile = Join-Path $Dir '.token'
$Parent = Split-Path $Dir; $SentMaps = Join-Path $Parent '.minimap-sent.d'; $MapReset = Join-Path $Parent '.minimap-reset'
# the client's write folder: two levels up from a character folder, four from one in bot\_voidwatch\data
$WriteDir = if ($Parent -match '[\\/]_voidwatch[\\/]data$') { Split-Path (Split-Path (Split-Path $Parent)) } else { Split-Path $Parent }
New-Item -ItemType Directory -Force -Path $In | Out-Null
$lastSent = $null; $lastCapture = $null; $minimapCheck = [datetime]::MinValue
$statusEvery = 30; $minimapOn = $true; $needMap = $false; $refused = 0; $wake = $false; $said = ''; $wakeCheck = [datetime]::MinValue

# one line per change of state, never the token or the code
function Note($text) {
  if ($text -eq $script:said) { return }
  $script:said = $text
  $log = Join-Path $Dir 'upload.log'
  if ((Test-Path $log) -and (Get-Item $log).Length -gt 100000) { Move-Item -Force $log "$log.1" }
  Add-Content -Path $log -Value ((Get-Date -Format 'yyyy-MM-dd HH:mm:ss') + ' ' + $text)
}

# one call to the API: the HTTP status (0 without a connection) and the answer
function Call($method, $path, $file, $type, $timeout, $extra) {
  $a = @{ Method = $method; Uri = "$Api$path"; TimeoutSec = $timeout; UseBasicParsing = $true; Headers = @{} }
  if ($extra) { foreach ($k in $extra.Keys) { $a.Headers[$k] = $extra[$k] } }
  if (Test-Path $TokenFile) { $a.Headers.Authorization = 'Bearer ' + (Get-Content $TokenFile -Raw).Trim() }
  if ($file) { $a.InFile = $file; $a.ContentType = $type }
  try {
    $r = Invoke-WebRequest @a
    return @{ code = [int]$r.StatusCode; body = [string]$r.Content }
  } catch {
    $code = 0
    if ($_.Exception.Response) { $code = [int]$_.Exception.Response.StatusCode }
    return @{ code = $code; body = [string]$_.ErrorDetails.Message }
  }
}

# the module reads these files, so they are written whole, as UTF-8 without a byte order mark
function Put($path, $text) {
  [IO.File]::WriteAllText("$path.tmp", $text)
  Move-Item -Force "$path.tmp" $path
}

# the client writes a screenshot on the next frame: send it only once its first and last bytes are there
function Whole-Png($path) {
  $b = [IO.File]::ReadAllBytes($path)
  if ($b.Length -lt 20) { return $false }
  $head = [Text.Encoding]::ASCII.GetString($b, 1, 3)
  $tail = [Text.Encoding]::ASCII.GetString($b, $b.Length - 8, 4)
  return $b[0] -eq 0x89 -and $head -eq 'PNG' -and $tail -eq 'IEND'
}

function Field($text, $name) { if ("$text" -match ('"' + $name + '":\s*([0-9a-z]+)')) { $matches[1] } }

function Unpair($why) {
  Note "$why, asking for a new code"
  Remove-Item -Force -ErrorAction SilentlyContinue $TokenFile, "$In\pair.json", "$In\reply.json"
  $script:refused = 0
}

function Revoked($r) { return $r.code -eq 401 -and "$($r.body)" -match '"detail":"revoked client"' }

function On-Refused {
  $script:refused++
  $pair = Get-Content "$In\pair.json" -Raw -ErrorAction SilentlyContinue
  if ("$pair" -match '"paired":true') {
    if ($script:refused -ge 3) { Unpair 'the website refused this client' }
  } else {
    $expires = [long](Field $pair 'expiresAt')
    if (-not $expires -or [DateTimeOffset]::UtcNow.ToUnixTimeSeconds() -gt $expires) { Unpair 'the code expired' }
    else { Note 'waiting until the code is used' }
  }
}

while (Test-Path $Dir) {
  try {
    $now = Get-Date
    if (-not (Test-Path $TokenFile)) {
      if (Test-Path "$Out\pair-request.json") {
        $r = Call 'Post' '/pair' "$Out\pair-request.json" 'application/json' 10
        if ($r.code -eq 200 -and $r.body -match '"token":"([^"]+)"') {
          [IO.File]::WriteAllText($TokenFile, $matches[1])
          Put "$In\pair.json" ($r.body -replace '"token":"[^"]*",?', '')
          Note 'got a pairing code'
        } else {
          Note "pairing failed: HTTP $($r.code)"
          Start-Sleep -Seconds 30
        }
      }
      Start-Sleep -Seconds 1
      continue
    }

    $status = Get-Item "$Out\status.json" -ErrorAction SilentlyContinue
    $age = if ($status) { ($now - $status.LastWriteTime).TotalSeconds } else { [double]::MaxValue }
    # an old file is left from a closed client: sending it would show the character online
    if ($status -and $age -lt 90 -and ($status.LastWriteTime -ne $lastSent -or $wake)) {
      $wake = $false
      $r = Call 'Post' '/status' $status.FullName 'application/json' 10
      if ($r.code -eq 200) {
        $lastSent = $status.LastWriteTime; $refused = 0
        Put "$In\reply.json" $r.body
        if ("$(Get-Content "$In\pair.json" -Raw -ErrorAction SilentlyContinue)" -notmatch '"paired":true') {
          Put "$In\pair.json" '{"paired":true}'
          Note 'paired'
        }
        $statusEvery = [int](Field $r.body 'statusEvery'); if (-not $statusEvery) { $statusEvery = 30 }
        $minimapOn = $r.body -notmatch '"minimap":false'
        $needMap = $r.body -match '"needMap":true'
        if ((Field $r.body 'commands') -ne '0') {
          $c = Call 'Get' '/commands' $null $null 10
          if ($c.code -eq 200) { $fetched++; Put "$In\commands-$([DateTimeOffset]::UtcNow.ToUnixTimeSeconds())-$fetched.json" $c.body }
        }
        Note 'sending'
      } elseif (Revoked $r) {
        Unpair 'removed on the website'
        continue
      } elseif ($r.code -eq 401) {
        On-Refused
        Start-Sleep -Seconds 5
        continue
      } elseif ($r.code -eq 422) {
        $lastSent = $status.LastWriteTime
        Note 'the website refused a status (HTTP 422)'
      } else {
        Note "status failed: HTTP $($r.code)"
        Start-Sleep -Seconds 5
        continue
      }
    }

    $shot = Get-Item "$Out\capture.png" -ErrorAction SilentlyContinue
    if ($shot -and $shot.LastWriteTime -ne $lastCapture -and (Whole-Png $shot.FullName)) {
      if ((Call 'Post' '/capture' $shot.FullName 'image/png' 20).code -eq 200) { $lastCapture = $shot.LastWriteTime }
    }

    if ((Test-Path "$Out\results.json") -and -not (Test-Path "$Out\.results")) { Move-Item -Force "$Out\results.json" "$Out\.results" }
    if (Test-Path "$Out\.results") {
      foreach ($res in (Get-Content "$Out\.results" -Raw | ConvertFrom-Json)) {
        Put "$Out\.result" (@{ ok = $res.ok; message = $res.message; data = $res.data } | ConvertTo-Json -Compress -Depth 4)
        Call 'Post' "/commands/$($res.id)/result" "$Out\.result" 'application/json' 10 | Out-Null
      }
      Remove-Item -Force -ErrorAction SilentlyContinue "$Out\.results", "$Out\.result"
    }

    if (Test-Path "$Out\exiva.json") {
      Move-Item -Force "$Out\exiva.json" "$Out\.exiva"
      Call 'Post' '/exiva' "$Out\.exiva" 'application/json' 10 | Out-Null
      Remove-Item -Force -ErrorAction SilentlyContinue "$Out\.exiva"
    }

    # the client's own minimap files sit in the write folder. The clients there share them, so only the first paired
    # character sends them: each file after it changed, at most every 30 minutes, and all again when the site has no map.
    if ($minimapOn -and ($now - $minimapCheck).TotalSeconds -ge 60) {
      $minimapCheck = $now
      $first = Get-ChildItem $Parent -Directory -ErrorAction SilentlyContinue |
        Where-Object { "$(Get-Content (Join-Path $_.FullName 'inbox\pair.json') -Raw -ErrorAction SilentlyContinue)" -match '"paired":true' } |
        Sort-Object Name | Select-Object -First 1
      if ($first -and $first.FullName -eq (Get-Item $Dir).FullName) {
        New-Item -ItemType Directory -Force -Path $SentMaps | Out-Null
        $unix = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
        $resetAt = [long]0
        [void][long]::TryParse("$(Get-Content $MapReset -Raw -ErrorAction SilentlyContinue)".Trim(), [ref]$resetAt)
        if ($needMap -and $unix - $resetAt -ge 1800) {
          Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $SentMaps '*.otmm')
          [IO.File]::WriteAllText($MapReset, [string]$unix)
        }
        foreach ($map in @(Get-ChildItem $WriteDir -Filter 'minimap*.otmm' -File -ErrorAction SilentlyContinue)) {
          $mtime = ([DateTimeOffset]$map.LastWriteTimeUtc).ToUnixTimeSeconds()
          $mark = Join-Path $SentMaps $map.Name
          $was = "$(Get-Content $mark -Raw -ErrorAction SilentlyContinue)".Trim() -split '\s+'
          if ($was[0] -eq [string]$mtime) { continue }
          $sentAt = [long]0
          if ($was.Count -gt 1) { [void][long]::TryParse($was[1], [ref]$sentAt) }
          if ($unix - $sentAt -lt 1800) { continue }
          $code = (Call 'Post' '/minimap' $map.FullName 'application/octet-stream' 120 @{ 'X-File-Mtime' = [string]$mtime }).code
          if ($code -eq 200 -or $code -eq 409 -or $code -eq 422) { [IO.File]::WriteAllText($mark, "$mtime $unix") }
          elseif ($code -eq 429) { break }
        }
      }
    }

    if ($age -le 300 -and "$(Get-Content "$In\reply.json" -Raw -ErrorAction SilentlyContinue)" -match '"exiva":true') {
      # Team exiva: a long poll would hold the team's casts and answers, so ask briefly every 2 s instead
      Start-Sleep -Seconds 1
      if (($now - $wakeCheck).TotalSeconds -ge 2) {
        $wakeCheck = $now
        $w = Call 'Get' '/wake' $null $null 5
        if ($w.code -eq 200 -and $w.body -match '"wake":true') { $wake = $true }
      }
    } elseif ($statusEvery -le 5) {
      Start-Sleep -Milliseconds 500
    } elseif ($age -gt 300) {
      Start-Sleep -Seconds 10  # the client is closed or logged out: no request stays open
    } else {
      # someone opened the character, an alert fired or a command arrived: send the status again for a new pace
      $w = Call 'Get' '/wait?timeout=25' $null $null 30
      if ($w.code -eq 200) {
        if ($w.body -match '"wake":true') { $wake = $true }
      } elseif (Revoked $w) {
        Unpair 'removed on the website'
      } else {
        Start-Sleep -Seconds 5
      }
    }
  } catch {
    Note $_.Exception.Message
    Start-Sleep -Seconds 5
  }
}

upload/upload.sh

#!/bin/sh
# Voidwatch upload script for macOS and Linux (also for clients that run through Wine or CrossOver).
# It sends what the module writes and brings back the replies. MIT licence.
#   sh upload.sh                          watch every client in the usual places and in folders.txt
#   sh upload.sh "<voidwatch folder>"     watch one client: the folder the module shows in a game message
# Every character has its own folder inside the voidwatch folder, and its own worker.
set -u
API=${VOIDWATCH_API:-https://voidwatch.xyz/api/v1}
# module updates come from the GitHub releases, not from the website: a broken-into website cannot ship code
RELEASES=${VOIDWATCH_RELEASES:-https://github.com/voidwatch-xyz/module/releases}
LATEST_API=${VOIDWATCH_LATEST:-https://api.github.com/repos/voidwatch-xyz/module/releases/latest}

if [ "${1:-}" != --worker ]; then
  HOME_DIR="$HOME/Library/Application Support/Voidwatch"
  [ -d "$HOME_DIR" ] || HOME_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/voidwatch"
  latest="" latest_at=0
  write_file() { printf '%s' "$2" > "$1.tmp" && mv -f "$1.tmp" "$1"; }
  version_of() { sed -n 's/^ *version: *\([0-9.]*\).*/\1/p' "$1" 2>/dev/null | head -n 1; }
  # the newest release, asked at most every 6 hours: GitHub answers 60 questions an hour without an account
  check_latest() {
    now=$(date +%s)
    [ $((now - latest_at)) -lt 21600 ] && return
    latest_at=$now
    tag=$(curl -sS -m 20 "$LATEST_API" 2>/dev/null | sed -n 's/.*"tag_name": *"v\([0-9.]*\)".*/\1/p' | head -n 1)
    [ -n "$tag" ] && latest=$tag
  }
  # the module folder the client loads: beside the data folder in bot/_voidwatch, or the write folder's modules folder
  module_of() {
    case "${1%/}" in
      */_voidwatch/data) printf '%s' "${1%/}/../voidwatch" ;;
      *) printf '%s' "${1%/}/../modules/voidwatch" ;;
    esac
  }
  update_done() { write_file "$1/update-result.json" "$2"; rm -f "$1/update-request.json" "$1/rollback-request.json"; rm -rf "$1/.update"; }
  # an update the window asked for: the release zip, checked against its SHA256SUMS; the old folder stays as a backup
  update_module() {
    d=${1%/} m=$(module_of "$1") t="${1%/}/.update"
    v=$(sed -n 's/.*"version": *"\([0-9.]*\)".*/\1/p' "$d/update-request.json" | head -n 1)
    by=$(sed -n 's/.*"by": *"\([^"]*\)".*/\1/p' "$d/update-request.json" | head -n 1)
    rm -rf "$t" && mkdir -p "$t"
    [ -n "$v" ] || { update_done "$d" '{"ok":false,"error":"no version asked for"}'; return; }
    if ! curl -sSfL -m 120 -o "$t/m.zip" "$RELEASES/download/v$v/voidwatch-module.zip" 2>/dev/null \
      || ! curl -sSfL -m 30 -o "$t/SHA256SUMS" "$RELEASES/download/v$v/SHA256SUMS" 2>/dev/null; then
      update_done "$d" '{"ok":false,"error":"the download failed"}'
      return
    fi
    want=$(sed -n 's/^\([0-9a-f]\{64\}\)  *voidwatch-module.zip$/\1/p' "$t/SHA256SUMS" | head -n 1)
    got=$({ shasum -a 256 "$t/m.zip" 2>/dev/null || sha256sum "$t/m.zip"; } | cut -d ' ' -f 1)
    if [ -z "$want" ] || [ "$want" != "$got" ]; then
      update_done "$d" '{"ok":false,"error":"the checksum does not match"}'
      return
    fi
    if ! unzip -q "$t/m.zip" -d "$t/x" 2>/dev/null || [ "$(version_of "$t/x/voidwatch/voidwatch.otmod")" != "$v" ]; then
      update_done "$d" '{"ok":false,"error":"the zip holds another version"}'
      return
    fi
    old=$(version_of "$m/voidwatch.otmod")
    rm -rf "$d/backup"
    if ! mkdir -p "$d/backup" || ! cp -R "$m" "$d/backup/voidwatch" || ! printf '%s' "$old" > "$d/backup/version"; then
      update_done "$d" '{"ok":false,"error":"no backup could be made"}'
      return
    fi
    rm -rf "$m"
    if ! mv "$t/x/voidwatch" "$m"; then
      cp -R "$d/backup/voidwatch" "$m"
      update_done "$d" '{"ok":false,"error":"the swap failed"}'
      return
    fi
    # the installed copy of this script updates itself too; the login item or the service starts it again
    case "$0" in
      "$HOME_DIR"/*)
        if [ -f "$t/x/upload/upload.sh" ] && ! cmp -s "$t/x/upload/upload.sh" "$0" && sh -n "$t/x/upload/upload.sh"; then
          cp "$t/x/upload/upload.sh" "$0.new" && chmod 755 "$0.new" && mv -f "$0.new" "$0" && : > "$HOME_DIR/.restart"
        fi ;;
    esac
    update_done "$d" "{\"ok\":true,\"version\":\"$v\",\"from\":\"$old\",\"by\":\"$by\",\"at\":$(date +%s)}"
  }
  # addons come from the release of the module version the folder runs, checked against the same SHA256SUMS. A failed
  # download waits 30 minutes or a new module version before it tries again.
  install_addon() {
    d=${1%/} id=$2 v=$3 t="${1%/}/.addon"
    rm -rf "$t" && mkdir -p "$t" "$d/addons" || return 1
    if curl -sSfL -m 60 -o "$t/a.zip" "$RELEASES/download/v$v/addon-$id.zip" 2>/dev/null \
      && curl -sSfL -m 30 -o "$t/SHA256SUMS" "$RELEASES/download/v$v/SHA256SUMS" 2>/dev/null; then
      want=$(sed -n "s/^\([0-9a-f]\{64\}\)  *addon-$id\.zip\$/\1/p" "$t/SHA256SUMS" | head -n 1)
      got=$({ shasum -a 256 "$t/a.zip" 2>/dev/null || sha256sum "$t/a.zip"; } | cut -d ' ' -f 1)
      if [ -n "$want" ] && [ "$want" = "$got" ] && unzip -q "$t/a.zip" -d "$t/x" 2>/dev/null && [ -f "$t/x/$id/main.lua" ]; then
        printf '%s' "$v" > "$t/x/$id/.version"
        rm -rf "${d:?}/addons/$id" && mv "$t/x/$id" "$d/addons/$id" && rm -rf "$t" && rm -f "$d/addons/.failed-$id" && return 0
      fi
    fi
    rm -rf "$t"
    printf '%s' "$v" > "$d/addons/.failed-$id"
    return 1
  }
  sync_addons() {
    d=${1%/} v=$(version_of "$(module_of "$1")/voidwatch.otmod")
    wanted=$(sed -n 's/.*"ids": *\[\([^]]*\)\].*/\1/p' "$d/addons-wanted.json" 2>/dev/null | tr -d '" ' | tr ',' ' ')
    for id in $wanted; do
      case "$id" in "" | *[!a-z0-9-]*) continue ;; esac
      [ "$(cat "$d/addons/$id/.version" 2>/dev/null)" = "$v" ] && continue
      f="$d/addons/.failed-$id"
      if [ -f "$f" ] && [ "$(cat "$f")" = "$v" ] && [ $(($(date +%s) - $(stat -c %Y "$f" 2>/dev/null || stat -f %m "$f"))) -lt 1800 ]; then
        continue
      fi
      install_addon "$d" "$id" "$v"
    done
    for p in "$d"/addons/*/; do
      [ -d "$p" ] || continue
      id=$(basename "$p")
      case " $wanted " in *" $id "*) ;; *) rm -rf "${d:?}/addons/$id" ;; esac
    done
  }
  # the pictures the Voidwatch window asks for: lines "id file path", only addon pictures from the website, PNG, 2 MB at most
  fetch_pictures() {
    d=${1%/} w="${1%/}/addon-pictures-wanted.txt"
    while read -r id file src; do
      case "$id" in "" | *[!a-z0-9-]*) continue ;; esac
      case "$file" in "" | *[!A-Za-z0-9_.-]* | .*) continue ;; *.png) ;; *) continue ;; esac
      [ "$src" = "/static/img/addons/$id/$file" ] || continue
      out="$d/addon-pictures/$id/$file"
      [ -f "$out" ] && continue
      mkdir -p "$d/addon-pictures/$id" || continue
      if curl -sSfL -m 30 --max-filesize 2097152 -o "$out.part" "${API%/api/v1}$src" 2>/dev/null \
        && [ "$(wc -c < "$out.part")" -le 2097152 ] && [ "$(head -c 8 "$out.part" | od -An -tx1 | tr -d ' \n')" = "89504e470d0a1a0a" ]; then
        mv -f "$out.part" "$out"
      else
        rm -f "$out.part"
      fi
    done < "$w"
    rm -f "$w"
  }
  rollback_module() {
    d=${1%/} m=$(module_of "$1")
    by=$(sed -n 's/.*"by": *"\([^"]*\)".*/\1/p' "$d/rollback-request.json" | head -n 1)
    [ -f "$d/backup/voidwatch/voidwatch.otmod" ] || { update_done "$d" '{"ok":false,"error":"there is no backup"}'; return; }
    v=$(cat "$d/backup/version" 2>/dev/null)
    rm -rf "$m"
    cp -R "$d/backup/voidwatch" "$m" && rm -rf "$d/backup"
    update_done "$d" "{\"ok\":true,\"version\":\"$v\",\"rollback\":true,\"by\":\"$by\",\"at\":$(date +%s)}"
  }
  while :; do
    check_latest
    if [ $# -gt 0 ]; then
      found=$1
    else
      found=$(
        for d in "$HOME/Library/Application Support/OTClientV8"/*/voidwatch "$HOME/.otclientv8"/*/voidwatch \
                 "$HOME/.local/share/otclientv8"/*/voidwatch \
                 "$HOME/Library/Application Support/CrossOver/Bottles"/*/drive_c/users/*/AppData/Roaming/OTClientV8/*/voidwatch \
                 "$HOME/.wine/drive_c/users"/*/AppData/Roaming/OTClientV8/*/voidwatch \
                 "$HOME/Library/Application Support/OTClientV8"/*/bot/_voidwatch/data "$HOME/.otclientv8"/*/bot/_voidwatch/data \
                 "$HOME/.local/share/otclientv8"/*/bot/_voidwatch/data \
                 "$HOME/Library/Application Support/CrossOver/Bottles"/*/drive_c/users/*/AppData/Roaming/OTClientV8/*/bot/_voidwatch/data \
                 "$HOME/.wine/drive_c/users"/*/AppData/Roaming/OTClientV8/*/bot/_voidwatch/data; do
          [ -d "$d" ] && printf '%s\n' "$d"
        done
        [ -f "$HOME_DIR/folders.txt" ] && cat "$HOME_DIR/folders.txt"
      )
    fi
    printf '%s\n' "$found" | while IFS= read -r d; do
      [ -d "$d" ] || continue
      for c in "${d%/}"/*/outbox; do
        [ -d "$c" ] || continue
        c=${c%/outbox}
        pid=$(cat "$c/.pid" 2>/dev/null)
        [ "${pid:-0}" -gt 0 ] && kill -0 "$pid" 2>/dev/null && continue
        sh "$0" --worker "$c" >/dev/null 2>&1 &
        echo $! > "$c/.pid"
      done
      m=$(module_of "$d")
      writable=false
      [ -f "$m/voidwatch.otmod" ] && [ -w "$m" ] && [ -w "${m%/voidwatch}" ] && writable=true
      # the website passes on the newest release it saw on GitHub within 5 minutes; the higher of the two counts
      told=$(sed -n 's/.*"latestModule": *"\([0-9.]*\)".*/\1/p' "${d%/}"/*/inbox/reply.json 2>/dev/null | sort -t. -k1,1n -k2,2n -k3,3n | tail -n 1)
      best=$(printf '%s\n%s\n' "$latest" "$told" | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | sort -t. -k1,1n -k2,2n -k3,3n | tail -n 1)
      write_file "${d%/}/latest.json" "{\"latest\":\"$best\",\"updatable\":$writable,\"backup\":\"$(cat "${d%/}/backup/version" 2>/dev/null)\"}"
      [ "$writable" = true ] && [ -f "${d%/}/update-request.json" ] && update_module "$d"
      [ "$writable" = true ] && [ -f "${d%/}/rollback-request.json" ] && rollback_module "$d"
      [ -f "${d%/}/addons-wanted.json" ] && sync_addons "$d"
      [ -f "${d%/}/addon-pictures-wanted.txt" ] && fetch_pictures "$d"
    done
    if [ -f "$HOME_DIR/.restart" ]; then
      # the new script takes over: the workers stop, and the login item or the service starts the new one
      rm -f "$HOME_DIR/.restart"
      pkill -f "$0 --worker" 2>/dev/null
      exit 0
    fi
    sleep 2
  done
fi

DIR=${2%/}
OUT="$DIR/outbox" IN="$DIR/inbox" TOKEN_FILE="$DIR/.token" AUTH="$DIR/.auth" BODY="$DIR/.body"
SENT_MAPS="$DIR/../.minimap-sent.d" MAP_RESET="$DIR/../.minimap-reset"
# the client's write folder: two levels up from a character folder, four from one in bot/_voidwatch/data
case "$DIR" in
  */_voidwatch/data/*) WRITE_DIR="$DIR/../../../.." ;;
  *) WRITE_DIR="$DIR/../.." ;;
esac
mkdir -p "$IN"
last_sent=0 minimap_check=0 status_every=30 refused=0 minimap_on=1 need_map=0 wake=0 said="" fetched=0 wake_check=0
# a game client that runs through Wine reports Windows: the website takes the system from here
case $(uname -s 2>/dev/null) in
  Darwin) host_os=macOS ;;
  Linux) host_os=Linux ;;
  *) host_os="" ;;
esac
# the token travels in a header file, so it never shows in the process list
if [ -s "$TOKEN_FILE" ]; then
  chmod 600 "$TOKEN_FILE"
  (umask 077; printf 'Authorization: Bearer %s\n' "$(cat "$TOKEN_FILE")" > "$AUTH")
fi

# one line per change of state, never the token or the code
note() {
  [ "$1" = "$said" ] && return
  said=$1
  [ "$(wc -c < "$DIR/upload.log" 2>/dev/null || echo 0)" -gt 100000 ] && mv -f "$DIR/upload.log" "$DIR/upload.log.1"
  printf '%s %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$1" >> "$DIR/upload.log"
}

# request METHOD PATH [curl options]: the answer goes to $BODY, the HTTP status to stdout (000 without a connection)
request() {
  m=$1 p=$2
  shift 2
  if [ -s "$AUTH" ]; then set -- -H "@$AUTH" "$@"; fi
  curl -sS -m 30 -o "$BODY" -w '%{http_code}' -X "$m" "$@" "$API$p" 2>/dev/null
}

field() { sed -n "s/.*\"$2\": *\([0-9a-z]*\).*/\1/p" "$1" 2>/dev/null | head -n 1; }
mtime() { stat -c %Y "$1" 2>/dev/null || stat -f %m "$1"; }
# the client writes a screenshot on the next frame: send it only once its first and last bytes are there
whole_png() { [ "$(head -c 8 "$1" | od -An -tx1 | tr -d ' \n')" = 89504e470d0a1a0a ] && tail -c 12 "$1" | LC_ALL=C grep -q IEND; }
put() { printf '%s' "$2" > "$1.tmp" && mv -f "$1.tmp" "$1"; }

unpair() {
  note "$1, asking for a new code"
  rm -f "$TOKEN_FILE" "$AUTH" "$IN/pair.json" "$IN/reply.json"
  refused=0
}

revoked() { grep -q '"detail":"revoked client"' "$BODY" 2>/dev/null; }

on_refused() {
  refused=$((refused + 1))
  if grep -q '"paired":true' "$IN/pair.json" 2>/dev/null; then
    [ "$refused" -ge 3 ] && unpair "the website refused this client"
  else
    expires=$(field "$IN/pair.json" expiresAt)
    if [ -z "$expires" ] || [ "$now" -gt "$expires" ]; then unpair "the code expired"; else note "waiting until the code is used"; fi
  fi
}

while [ -d "$DIR" ]; do
  now=$(date +%s)
  if [ ! -s "$TOKEN_FILE" ]; then
    if [ -f "$OUT/pair-request.json" ]; then
      code=$(request POST /pair -m 10 -H "Content-Type: application/json" -H "X-Voidwatch-OS: $host_os" --data-binary "@$OUT/pair-request.json")
      token=$(sed -n 's/.*"token":"\([^"]*\)".*/\1/p' "$BODY" 2>/dev/null)
      if [ "$code" = 200 ] && [ -n "$token" ]; then
        (umask 077; printf '%s' "$token" > "$TOKEN_FILE"; printf 'Authorization: Bearer %s\n' "$token" > "$AUTH")
        put "$IN/pair.json" "$(sed 's/"token":"[^"]*",\{0,1\}//' "$BODY")"
        note "got a pairing code"
      else
        note "pairing failed: HTTP $code $(head -c 200 "$BODY" 2>/dev/null)"
        sleep 30
      fi
    fi
    sleep 1
    continue
  fi

  age=999999
  if [ -f "$OUT/status.json" ]; then
    m=$(mtime "$OUT/status.json")
    age=$((now - m))
    # an old file is left from a closed client: sending it would show the character online
    if [ "$age" -lt 90 ] && { [ "$m" != "$last_sent" ] || [ "$wake" = 1 ]; }; then
      wake=0
      code=$(request POST /status -m 10 -H "Content-Type: application/json" --data-binary "@$OUT/status.json")
      case $code in
        200)
          last_sent=$m refused=0
          mv -f "$BODY" "$IN/reply.json"
          grep -q '"paired":true' "$IN/pair.json" 2>/dev/null || { put "$IN/pair.json" '{"paired":true}'; note "paired"; }
          status_every=$(field "$IN/reply.json" statusEvery)
          status_every=${status_every:-30}
          case $(cat "$IN/reply.json") in *'"minimap":false'*) minimap_on=0 ;; *) minimap_on=1 ;; esac
          case $(cat "$IN/reply.json") in *'"needMap":true'*) need_map=1 ;; *) need_map=0 ;; esac
          if [ "$(field "$IN/reply.json" commands)" != 0 ] && [ "$(request GET /commands -m 10)" = 200 ]; then
            fetched=$((fetched + 1))
            mv -f "$BODY" "$IN/commands-$(date +%s)-$fetched.json"
          fi
          note "sending"
          ;;
        401)
          if revoked; then
            unpair "removed on the website"
            continue
          fi
          on_refused
          sleep 5
          continue
          ;;
        422)
          last_sent=$m
          note "the website refused a status: $(head -c 300 "$BODY")"
          ;;
        *)
          note "status failed: HTTP $code"
          sleep 5
          continue
          ;;
      esac
    fi
  fi

  if [ -f "$OUT/capture.png" ]; then
    m=$(mtime "$OUT/capture.png")
    if [ "$m" != "${last_capture:-}" ] && whole_png "$OUT/capture.png" && [ "$(request POST /capture -m 20 -H "Content-Type: image/png" --data-binary "@$OUT/capture.png")" = 200 ]; then
      last_capture=$m
    fi
  fi

  [ -f "$OUT/results.json" ] && [ ! -f "$OUT/.results" ] && mv -f "$OUT/results.json" "$OUT/.results"
  if [ -f "$OUT/.results" ]; then
    # one result per command: {"id":1,"ok":true,"message":"..."}
    sed 's/},{/}\
{/g; s/^\[//; s/\]$//' "$OUT/.results" | while IFS= read -r r || [ -n "$r" ]; do
      id=$(printf '%s' "$r" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
      [ -n "$id" ] && printf '%s' "$r" > "$OUT/.result" \
        && request POST "/commands/$id/result" -m 10 -H "Content-Type: application/json" --data-binary "@$OUT/.result" >/dev/null
    done
    rm -f "$OUT/.results" "$OUT/.result"
  fi

  if [ -f "$OUT/exiva.json" ]; then
    mv -f "$OUT/exiva.json" "$OUT/.exiva"
    request POST /exiva -m 10 -H "Content-Type: application/json" --data-binary "@$OUT/.exiva" >/dev/null
    rm -f "$OUT/.exiva"
  fi

  # the client's own minimap files sit in the write folder. The clients there share them, so only the first paired
  # character sends them: each file after it changed, at most every 30 minutes, and all again when the site has no map.
  if [ "$minimap_on" = 1 ] && [ $((now - minimap_check)) -ge 60 ]; then
    minimap_check=$now
    first=""
    for t in "$DIR"/../*/inbox/pair.json; do grep -q '"paired":true' "$t" 2>/dev/null && { first=$t; break; }; done
    if [ "$first" = "$DIR/../${DIR##*/}/inbox/pair.json" ]; then
      mkdir -p "$SENT_MAPS"
      if [ "$need_map" = 1 ] && [ $((now - $(cat "$MAP_RESET" 2>/dev/null || echo 0))) -ge 1800 ]; then
        rm -f "$SENT_MAPS"/*.otmm
        printf '%s' "$now" > "$MAP_RESET"
      fi
      for f in "$WRITE_DIR"/minimap*.otmm; do
        [ -f "$f" ] || continue
        mm=$(mtime "$f") mark="$SENT_MAPS/${f##*/}" was_mm="" was_at=0
        [ -f "$mark" ] && read -r was_mm was_at < "$mark"
        [ "$mm" = "$was_mm" ] && continue
        [ $((now - ${was_at:-0})) -ge 1800 ] || continue
        case $(request POST /minimap -m 120 -H "Content-Type: application/octet-stream" -H "X-File-Mtime: $mm" --data-binary "@$f") in
          200 | 409 | 422) printf '%s %s\n' "$mm" "$now" > "$mark" ;;
          429) break ;;
        esac
      done
    fi
  fi

  if [ "$age" -le 300 ] && grep -q '"exiva":true' "$IN/reply.json" 2>/dev/null; then
    # Team exiva: a long poll would hold the team's casts and answers, so ask briefly every 2 s instead
    sleep 1
    if [ $((now - wake_check)) -ge 2 ]; then
      wake_check=$now
      [ "$(request GET /wake -m 5)" = 200 ] && grep -q '"wake":true' "$BODY" && wake=1
    fi
  elif [ "$status_every" -le 5 ]; then
    sleep 0.5
  elif [ "$age" -gt 300 ]; then
    sleep 10 # the client is closed or logged out: no request stays open
  else
    code=$(request GET "/wait?timeout=25" -m 30)
    if [ "$code" = 200 ]; then
      # someone opened the character, an alert fired or a command arrived: send the status again for a new pace
      grep -q '"wake":true' "$BODY" && wake=1
    elif [ "$code" = 401 ] && revoked; then
      unpair "removed on the website"
    else
      sleep 5
    fi
  fi
done

remove-windows.cmd

@echo off
rem Removes the Voidwatch upload script from Windows: stops it, removes it from the startup items, deletes its files.
powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter \"Name='powershell.exe'\" | Where-Object { $_.CommandLine -like '*Voidwatch\upload.ps1*' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }"
del "%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\Voidwatch upload.lnk" 2>nul
rmdir /S /Q "%LOCALAPPDATA%\Voidwatch" 2>nul
echo Voidwatch upload script removed. The module in your game client stays until you delete its folder.
pause

remove-mac.command

#!/bin/sh
# Removes the Voidwatch upload script from macOS: stops it, removes the login item, deletes its files.
PLIST="$HOME/Library/LaunchAgents/xyz.voidwatch.upload.plist"
launchctl unload "$PLIST" 2>/dev/null
rm -f "$PLIST"
pkill -f "Voidwatch/Voidwatch Upload" 2>/dev/null
pkill -f "Voidwatch/upload.sh" 2>/dev/null
rm -rf "$HOME/Library/Application Support/Voidwatch"
echo "Voidwatch upload script removed. The module in your game client stays until you delete its folder."

remove-linux.sh

#!/bin/sh
# Removes the Voidwatch upload script from Linux: stops the user service and deletes its files.
systemctl --user disable --now voidwatch.service 2>/dev/null
rm -f "${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/voidwatch.service"
rm -rf "${XDG_DATA_HOME:-$HOME/.local/share}/voidwatch"
echo "Voidwatch upload script removed. The module in your game client stays until you delete its folder."