Plugin host: core design
The first step of the plugin suite (docs/plugins_plan.md, phase 1). It fixes how plugins are found, run, isolated and called, and the shape of the API every later phase extends.
1. Where things live
| path | what |
|---|---|
native/third_party/luau/ | Luau 0.743 (MIT): Common, Ast, Bytecode, Compiler, VM. Built as cs_luau. |
native/game/src/plugins/ | The host, inside the game (it has the players, the rules and the entities, and calls the engine directly). |
native/game/src/plugins/api.toml | The API schema: functions, classes, events, option tables. |
tools/gen_plugin_api.py | Generates from the schema the C++ bindings (plugins/generated/bindings.inc), the Luau type definitions (data/plugin_sdk/cs.d.luau) and the reference (docs/plugins_reference.md). The generated files are committed; --check fails when they are stale. |
<user>/plugins/<name>/, data/plugins/<name>/ | Installed plugins (the user's folder wins by name). |
<user>/plugin_data/<name>/ | The only place a plugin may write (kept apart, so a plugin folder can be replaced whole). |
2. A plugin
plugins/hello/
plugin.toml
main.luau
lib/greetings.luau (require("./lib/greetings"))
name = "hello" # folder name; [a-z0-9_]
version = "1.0.0"
author = "someone"
description = "Says hello."
api = 1 # the API version it was written for
main = "main.luau" # default
enabled = true # false: installed, not loaded
depends = [] # plugins that must load first (S4c)
permissions = [] # "raw_properties", "raw_sockets", "raw_messages", "server_console"
hosts = [] # what its network may reach (section 5m)
cs.on("player_join", function(ev)
cs.chat(ev.player, "{green}Hello{default}, " .. ev.player.name)
end)
cs.command("hello", function(player, args)
cs.reply(player, "hello " .. (args[1] or "world"))
end, { help = "says hello" })
3. Running plugins
-
One Luau VM per plugin. The standard libraries Luau ships (no
io, noos.execute;oskeeps time and date), thecslibrary, thenluaL_sandbox: globals and libraries read-only, the plugin's code in its own sandboxed thread. A plugin cannot reach another's state. -
require loads
.luaufiles of the plugin's own folder only, relative to the requiring file, each once. -
Errors in any callback are caught (
lua_pcall), printed with the plugin, file, line and stack, and never reach the game. A plugin whose callbacks fail 20 times in a minute is paused (plugin resumebrings it back). On a dedicated server errors, a plugin that cannot load and a tick slowed by plugins also go tologs/errors.log, and a crash or hang report names the plugin and handler that ran (docs/dedicated.md). -
Budget: Luau's interrupt checks the time of each call into a plugin; past 100 ms (
sv_plugin_budget_ms) the call is stopped with an error. A memory cap per plugin (sv_plugin_memory_mb, 256) refuses allocations past it. -
Errors never jump through the game. The VM is built with
LUA_USE_LONGJMP; the generated bindings read and check every argument, call the plain C++ implementation, then push the results: only the binding layer raises Luau errors, so no game code is between a raise and its catch. - Everything on the tick thread. Callbacks run inside the server frame. Slow work (HTTP, SQL, files; phase 4) runs on worker jobs and comes back as a callback on the tick.
-
Load order: alphabetical, then by
depends(phase 4). Loading runs the main file; it registers handlers, commands, cvars and timers. -
Unloading removes everything the plugin registered (handlers, commands, cvars become unowned and keep their value, timers) and closes its VM.
plugin reload <name>= unload + load, so a reload never keeps stale handlers. State to keep across a reload is saved in acs.on("plugin_end")handler (to acs.store) and read back at load.
4. Events
-
Every hook point is a named event with typed fields. A handler receives one event object:
ev.player,ev.damage... Fields marked writable may be changed bybeforehandlers;ev:block()(inbeforehandlers of blockable events) stops the game's own handling, and every later handler seesev.blocked. -
cs.on(name, fn)runs after the game handled it;cs.on(name, fn, { before = true })runs before.priority(default 0, higher first) orders handlers across plugins; same priority keeps load order. The call returns aHookwith:remove(). - The event object is valid only during the call (keeping it raises an error when used later); it is reused, so firing an event allocates nothing.
- Free when unused. Each event has a counter of handlers; the game checks it inline before building anything. A server with no plugin installed does not start the host at all (no cvar, no command): every oracle stays exactly as it was.
Phase 1 events: plugin_start, plugin_end (the plugin's own), map_start, map_end, frame, player_connect (before: ev:reject(reason)), player_join, player_leave (ev.map_change: a map change makes every player leave and connect again), chat (before: block hides the line; ev.text, ev.team, read only in this phase), cvar_change. Bots join like players (player_connect after, player_join).
5. Phase 1 API
-
Players:
Playerobjects (one per slot, valid while connected; using one after the player left raises an error):slot,name,id(theCSID:player ID,BOTfor bots),bot,connected,in_game,team,alive,ping,address.cs.players()lists them,cs.player(slot)finds one. -
Commands:
cs.command(name, fn, opts): the same command from a player's console, from the server console (player nil) and from the chat as/nameor!name(unlesschat = false; the chat line is hidden unlessshow = true).admin = truerequires an admin whoseadmins.tomlentry allows the command name.fn(player, args):args[i]the words,args.linethe rest of the line.cs.reply(player, text)answers where the command came from (the server console for nil). A name another plugin has already stays that plugin's:cs.commandreturns false, the server console says so, and the plugin goes on loading (a mod and the game's chat commands may both haverespawn). -
Settings:
cs.cvar(name, default, opts)registers a server cvar the plugin owns (help,min,max,public) and returns aCvar:.value(string),:number(),:int(),:bool(),.value = x. A value out ofmin/maxis clamped, andcvar_changereports the change from the old value to the clamped one. Registering it again returns the same setting, with only the options given changed.cs.find_cvar(name)wraps an existing one (.protectedfor a password such assv_password). Changes firecvar_change. A plugin sets its own settings; setting the server's or another plugin's needs theserver_consolepermission, andplugin_devis set only from the server console. A value given before the plugin registers the setting (+name valueon the command line, a line of server.cfg) becomes its value on registering. -
Timers:
cs.after(seconds, fn),cs.every(seconds, fn); with{ player = p }the timer ends when that player leaves. They return aTimerwith:cancel(). Time is the game clock (cs.time()), checked every server frame. -
Talking:
cs.chat(to, text)(to = aPlayer, a list of them, or nil for everyone) with colour tags{default}{team}{green}{red}{blue}{grey}{white}{#rrggbb};cs.center(to, text);cs.console(to, text);cs.print(text)(server console, with the plugin's name). -
Server:
cs.map()the map name,cs.server_command(line)(theserver_consolepermission: the line has all the console's powers),cs.log(text). -
Admin command
plugin list | info <name> | load <name> | unload <name> | reload <name|all> | resume <name>(server console, orrcon).-nopluginson the command line keeps the host off.
5b. Phase 2 API: the world, game events, rules, menus, notices
The full list, with every field and option, is docs/plugins_reference.md (generated); this is the shape of it.
-
Vectors are Luau's native
vector(vector.create(x, y, z),+,*,vector.magnitude...): no allocation per value. -
Entities:
Entityobjects for anything in the map, the world included (cs.entity(0)): class, names, origin, angles, velocities, size, flags, solid, movetype, health, render, theiuser/fuserslots;:remove(),:set_size(),:set_model(),:use(activator),:spawn(),:key_value().cs.find_entities({ class, targetname, target, model, near, radius }),cs.create_entity(class, { origin, angles, spawn })(withspawn = false, set keys with:key_valueand then:spawn()). A removed entity's object raises an error when used (validtells). -
Players gain their body: origin, velocity, angles, view offset, flags, buttons, duck state, stamina, movetype, solid, health, armor, takedamage, gravity, maxspeed, ground, hidden HUD parts, fov, flashlight battery, the weapon in hand, money, score;
:respawn(),:join_team(),:strip(),:give(item, { clip, ammo }),:items(),:select(),:reset_maxspeed(),:teleport(),:send_command(). -
Traces:
cs.trace_line,cs.trace_hull(point,human,large,head),cs.trace_texture,cs.point_contents; a trace returns a table (fraction,end_pos,normal,entity,start_solid,all_solid...). -
Sounds and light:
cs.emit_sound(entity, sample, opts),cs.dynamic_light(to, origin, opts). -
Constants: read-only tables
cs.button,cs.flag,cs.damage,cs.hide_hud,cs.effect. -
Game events:
entity_spawn,use,touch(before: block replaces the entity's own use or touch),player_spawn,player_damage(before:ev.damagewritable, block),player_trace_attack,player_killed(before: block keeps the player alive),player_command(before: the buttons, impulse and moves of the usercmd are writable),player_pre_think,player_post_think,sound(before: block). Events about an entity take{ class = "func_button" }or{ entity = e }incs.on's options and only run for it. -
Rules:
cs.game.rounds,buying,pickups,item_drops,death_notices,corpses,gibs,team_menu,pvp_damage,team_balance. A rule is off while any plugin turned it off, and comes back when that plugin unloads. -
Menus:
cs.menu(player, title, items, fn(player, key), { exit, timeout }), numbered keys 1 to 9 (an empty item is a blank line), 0 exits; the handler runs once, after the menu closed (it may show another). The game's own menus replace a plugin's.cs.close_menu. -
Notices (
cs.notify(to, text, opts),cs.close_notice(to, id)): the HUD's messages for plugins, any number at once. Options:title;kind(info,success,warning,error,plain: the accent colour, icon and sound);icon(info,check,warning,error,timer,flag,star,bolt,pin,none);color(the accent),text_color,background(#rrggbb, the background#rrggbbaa);position(top,top_left,top_right,left,center,right,bottom_left,bottom,bottom_right: shortcuts) orx,yandalign, placed ascs.hud_textplaces a text (parts of the screen, 0 to 1; -1 centred; below 0 from the far edge;yis the top;alignleft,centerorrightsays which sidexis);size(small,normal,large);duration(seconds, 0: until closed; default 4);progress(0 to 1, a bar);sound(default: the kind's,none, or another kind's);id. Text and title take the chat's colour tags. Notices at the same place stack, slide in and fade out; a notice sent with theidof one on screen changes it in place (no sound, no slide), which makes live counters cheap. They show with the HUD hidden too. A plugin's notices close when it unloads.
Two rules of the host matter here: a hook added while its own event runs starts after that event (a hook for another event starts at once; add hooks at load time, and switch them with a flag); and the cs table's chains (cs.game.rounds) are looked up on every use, never cached when the chunk loads.
5b2. Content: models, sprites and sounds
A plugin may bring its own files in a content/ folder beside main.luau (content/models/..., content/sprites/..., content/sound/...). The folder joins the game's search path at the lowest priority, so it never replaces a game file. cs.precache(path) readies one (a model or sprite, a sound under sound/, or any other file players should download) and works only inside a map_start handler; it returns false when the file is missing. Players without the file download it like a map's own resources, and check it: the resource list carries the SHA-256 of each file found in a plugin's content/ (reserved byte 0 0xC5, then 31 bytes of the hash; files the consistency list checks keep its marks), and a client keeps a download only when its hash matches (a wrong copy from the web mirror, sv_downloadurl, is refused and asked of the server itself). The files' licence goes in plugin.toml (content_license = "CC-BY-4.0") or a content/LICENSE; the host warns when there is none, and plugin info shows it.
5c. Data: files and JSON
Each plugin has a data folder, <user folder>/plugin_data/<plugin>/, made when first used; it never sees anything outside it. Paths are relative, /-separated, made of letters, digits, _, - and . (no part starting or ending with ., none named as a Windows device: con, nul, aux, prn, com1...), at most 8 levels and 200 characters; anything else is an error.
-
cs.read_file(path)(nil when missing),cs.write_file(path, text),cs.append_file(path, text),cs.remove_file(path),cs.file_exists(path),cs.list_files(folder?)(sorted, folders end in/). Files are at most 16 MB. -
write_filereplaces a file whole: it writes a hidden file beside it and renames it over the old one, so a crash mid-write leaves the old file, never half of the new one. -
cs.json_encode(value, {pretty})andcs.json_decode(text);cs.read_json(path)(nil when missing) andcs.write_json(path, value, {pretty})(pretty by default). Tables with keys 1 to n are lists, the rest objects with string keys, written sorted so a file's text is stable (and diffs well); a vector is written as a list of 3 numbers; an empty table is[];nullreads as nil. Functions, other key types, NaN and infinities, invalid UTF-8 and nesting past 128 levels (or a table in itself) are errors; a decoding error names its line and column. -
These run on the tick, read or written whole: keep files small (a map's records, settings, zones) and write them when they change, not every frame. Larger files go through
cs.read_file_asyncandcs.write_file_async(section 5m).
5d. Movement
-
player_move: after each of a player's commands has moved them, the state before (start_origin,start_velocity,start_on_ground,start_ducking) and after (origin,velocity,on_ground,ducking,in_duck,on_ladder,water_level,ground), the command (buttons,old_buttons,forward_move,side_move,view_angles,msec), whether itjumped, and themax_speedandair_accelerateit used. It runs once per command, so jump stats, frames on ground and recordings see every tick, also at high frame rates. Without handlers the movement pays one branch. -
player.air_accelerate: the player's own air acceleration, used by the movement in place ofsv_airacceleratefor that player only (0 goes back to the server's). It is a key of the player's physics info, which reaches their client in its clientdata, so its prediction moves the same way (all of S3's movement settings travel so). - Messages a plugin sends a player still joining (notices, menus) wait for the player's first think instead of being lost.
5e. What one player sees, effects
-
player:hide(entity, hidden): an entity (a player too) hidden from this player only.player:pass_through(entity, through): this player moves through it (the others still collide); the entity reaches that player's client as not solid, so the prediction agrees.player:render(entity, {mode, amount, color, fx}): how this player alone sees it (nil: as everyone). Entries go with the entity (its slot reused) and with the player. Without entries the snapshots and the movement pay one branch. -
player.view_model/player.weapon_model(empty view model: the weapon hidden in first person),player.observer_mode,player:kick(reason),player:fade({color, alpha, duration, hold, direction}),player:light_style(style, pattern)(for that player only; "" back to the map's). -
entity.liquid: water, slime or lava (afunc_water, a brush marked as liquid, or one with!textures). -
cs.beam(to, from, target, {color, alpha, width, life, noise, speed})between points or entities (an entity end follows it),cs.beam_follow(to, entity, options)a trail,cs.beam_clear(to, entity). The sprite is precached only with plugins installed. -
Notices of kind
hudare bare outlined text without box, sound or animation, for readouts a plugin refreshes often (a timer, keys, a list);alignplacesxat the left edge, centre or right edge (a hud notice'syis its top) andfont = "mono"lines up columns.
5f. HTTP
cs.http(url, {method, body, headers, timeout}, callback) sends an http:// or https:// request (a web API) to a host the manifest lists (section 5m). The callback gets {status, ok, body, headers, error} on a later frame, never inside the call. Each request is one connection on the network thread, closed after the answer (8 MB at most, 64 connections at once per plugin, 10 s by default). An unloaded plugin's requests are dropped.
5g. Bots a plugin moves
cs.add_bot(name, {team, model}) adds a bot no AI drives (a replay): not solid, not hurt, never moved by the game, nothing in the world reacts to it, and it stays where bot:pose({origin, angles, velocity, buttons, ducking, on_ground, teleport}) puts it. The game animates it from the pose (running, crouching, a jump when it leaves the ground); spectators can watch it. player.puppet tells such a bot; bot:kick() removes it, and a plugin's bots go when it unloads.
5h. Sounds, voices, the scoreboard, maps
player.hear_players = false keeps the other players' sounds from that player (steps, weapons, shots and their events; a weapon's sounds count as its owner's); they still hear their own, and as spectators the player they watch. player:mute_voice(speaker, true) silences one voice for one listener, on top of the game's voice rules. Setting frags or deaths updates everyone's scoreboard at once. cs.maps() lists the loadable maps; cs.game.description (at most 63 characters) is the server list's Mode while no mode runs (a running mode's title goes first), until the plugin that set it unloads.
5i. Key binds, a player's own sounds, the takeoff
A command named +name / -name is a key's press and release (bind mouse3 +hook), from the console only. player:play_sound(sample, {pitch}) plays a sound only that player hears, not placed in the world. player_move gives with jumped the takeoff: jump_origin and jump_velocity, the velocity right after the jump, before the rest of the move (jump stats, FOG).
5j. The event model (S1)
Every event can have both sides: before handlers (by priority) may change the writable fields and, where the event is blockable, ev:block(); then the game acts; then the after handlers see the result. A blocked event has no after side. Events with an entity filter take { class = "...", entity = e } in the hook options, so a handler on think for func_door costs nothing for the other entities.
-
Entities:
think,blocked,entity_damage(damage and type writable, blockable),entity_killed(not players).Entity.next_think,Entity:damage(amount, {attacker, inflictor, type}). Every damage in the game goes through one function (DamageEntity), so plugins see all of it. -
Rounds:
round_start,freeze_end,round_end(reason and delay writable, blockable),game_restart.Game.round,freeze_period,round_over,round_time_left,bomb_planted,score_ct/score_t(writable),Game:end_round(reason, delay),Game:restart(seconds). -
Players:
client_command(every command the client sends, blockable),player_choose_team,player_team,player_name,player_money,player_buy,player_pickup,player_drop,player_flashed,player_spawn_point,player_equip,player_radio,player_hint. -
Weapons:
weapon_deploy,weapon_holster(every holster goes throughHolsterItem),weapon_attack(primary and secondary),weapon_reload,fire_bullets(spread, reach, penetration and damage writable, per bullet). Blocking an attack or a shot on the server does not stop the shooter's own prediction from showing it; weapons whose client follows the server's rules come with S5/S9. -
Grenades and objectives:
grenade_thrown,grenade_detonate(blockable: it vanishes; the bomb included),bomb_planted,bomb_defuse(time writable, blockable),bomb_defuse_end,hostage_rescued. -
Messages, spectators, the rest:
client_message(every game message to clients, its values read withev:arg(i)and changed withev:set_arg(i, v), or blocked;{ message = "TextMsg" }hooks one),team_win_check(blockable: a mode with its own victories),player_spectate,player_userinfo(Player:info(key)),player_footstep(volume writable, blockable),weapon_idle. -
Covered by the others: the bomb picked up or dropped is
player_pickup/player_dropofweapon_c4; it explodes ingrenade_detonate(kind = "bomb"); a defuse that endsdefusedisbomb_defuse_end; a hostage used or killed isuseorentity_killedwith{ class = "hostage_entity" }; the VIP escaping isround_endwithreason = "vip_escaped". Replacing what the game does is blocking it in a before handler and doing something else.
tools/plugin_events_test.sh runs the events test plugin on cs_office with four bots: blocking, changing and the after side of each group. plugin prof [reset] shows each plugin's handler calls and time per event and per server frame; tools/plugin_bench.sh runs 20 bots with and without twenty handlers on the busiest events (2026-10-22: about 30 us a frame, tick 0.14 to 0.18 ms average).
5k. Properties, raw access and the game objects (S2)
Every entity variable is an Entity property under our name (next_think, view_offset, iuser1...); the ones without a hand-written property are generated from the [[entvar]] table in api.toml.
Raw access reads and writes any field by name: the entity variables and every public member of the game's classes (players, weapons, grenades, hostages, doors, trains... and the game rules), found by the generator in the game's headers. It needs permissions = ["raw_properties"] in plugin.toml, since a member may hold what the game expects to stay consistent.
ent:get("m_iTeam") -- a member of the entity's class
ent:set("health", 50) -- our name, `pev_health` or `EV_FL_health`
ent:get("controller", 2) -- an element (1-based)
ent:get("EV_BYTE_controller2") -- the same element by its classic name
cs.game:set("m_iRoundTime", 120) -- a member of the game rules
for _, f in cs.fields(ent) do ... end -- name, class, type, count, writable, classic
Each name resolves to the member of the entity's actual class (checked at run time); a name of another class, an index out of range, a value of the wrong type and a read-only field are errors that name the call and the field. The kinds are integer, number, boolean, vector, string (string_t and char arrays) and Entity (pointers and handles; setting one checks the entity's class). The generator's kind of each member is checked against its C++ type at compile time. docs/plugins_fields.md lists every field with its classic names; S7's get_member/get_entvar and S8's translator use the same table.
The game objects stay valid while their entity exists: Player.active_weapon, Player:weapons() and Entity.weapon give a Weapon (clip, ammo, timers, recoil state, silencer and burst modes, top speed); cs.grenades() and Entity.grenade a Grenade (kind, thrower, fuse, damage, detonate()); cs.game.bomb the planted Bomb (planter, site, explode time, defuser), cs.game.bomb_carrier who carries the C4; cs.hostages() and Entity.hostage a Hostage (leader, settable, alive, rescued); cs.team("t"|"ct") a Team (score, count, alive, players).
tools/plugin_bots_test.sh fields runs the fields test plugin on cs_office with four bots: every entity variable, player, weapon and rules member read, written back and read again (about 1,850 values), the properties against raw, the classic names, the refusals and each object.
5l. Movement and visibility (S3)
player:set_movement({...}) gives one player their own movement: accelerate, air_accelerate, friction, stop_speed, jump_height, bhop_cap (0: no bunny hop cap), auto_bhop, stamina (the slowdown after landing and jumping), max_velocity, ladder_speed, duck_speed, swim_speed, can_jump, can_duck. Given fields replace the server's for that player, the others stay; player:movement() reads what is in effect, player:reset_movement() goes back to the server's. Gravity and top speed stay player.gravity and player.maxspeed.
ramp_fix (off by default) is for surf and slide servers. A badly built slide ramp can have seams where a fast slide hits the next brush's edge and stops dead in the middle of the ramp; with ramp_fix the player slides on instead. It only acts when a move along a slide ramp (steeper than a floor, not a wall) makes no progress at all from at least 200 u/s, so walls (wall bugs), floors, pixel surf and every move that goes anywhere stay exactly as they are. Like the other settings it is predicted, so the player sees no correction.
They are short keys in the player's physics info (\mv\1\jh\60...), which the client receives in its clientdata; the shared movement code reads them once at the start of each move (movement::load_tuning) on the server and in the prediction, so a player with their own settings is predicted exactly. A player without any pays one string search per move and moves exactly as before (the oracles stay at zero). Everything has to fit the 256 bytes of the physics info: a call that would not fit changes nothing and fails.
The move tells what it did, from each command (any frame rate): player_jump (takeoff origin and velocity), player_land (fall speed), player_ladder (on or off), player_water (level and old level) and player_duck (ducked or stood up). They are told after the move, not before: what a server handler changed inside a move would not be in the client's prediction. Changing how a player moves goes through the settings above (predicted), and S9's shared movement scripts.
entity_visible is AddToFullPack's place: before each entity goes into what one player is sent, its handlers may change how that player sees it (origin, model, skin, body, effects, render mode, amount, fx and color) or block it (that player is not sent it). It runs once per viewer and entity, only while some plugin listens; { class = } and { entity = } filter it. Player:hide and Player:render stay the cheap way for fixed choices.
cs.game.semiclip is off, team (teammates pass through each other) or all. Living players under the rule leave each other out of their movement and reach each other's clients as not solid, so the prediction agrees; bullets still hit. Player:pass_through adds single pairs.
tools/plugin_move_test.sh runs the movement test plugin with a predicting network client (port 27018). On cs_office the client moves with its own settings (auto bunny hop, jump height 60, air acceleration 150, no stamina...) through a frozen bot kept in its way with semiclip on, while two other bots reach it changed and hidden; the prediction must stay as exact as without plugins (2026-10-22: 2 of 3131 off, the same as the base; with semiclip off 10, with the client not reading its settings 13), and the client must see the bots as the plugin chose. On as_oilrig the client is put in deep water and on a ladder.
5m. Services: I/O threads, data, network (S4)
The game and every callback run on one thread. Work that waits on the disk or the network runs on the host's I/O threads (three, started at the first job): a job carries copies of what it needs, never touches the game, a VM or the engine, and its result comes back as a callback on a later frame. A plugin that unloads meanwhile is never called back.
-
Stores (
cs.store(name), the file<name>.storein the data folder): JSON values by string key, with an optional expiry (store:set(key, value, {ttl = seconds}),:touch,:expires). The store is read whole when it opens and answers:get,:hasand:keys(prefix)from memory; each change is written to the file on an I/O thread, in order. Expired keys read as missing and are dropped from the file the next time it opens. Values are at most 1 MB as JSON. -
Databases (
cs.database(name), SQLite in<name>.db, WAL journal):db:query(sql, params, callback)runs on an I/O thread; a database's queries run one at a time, in the order sent. Parameters are?with a list or:namewith a table; results are tables (ok,rowsby column name,changes,last_id,error). Without parameters the text may hold several statements.db:query_nowwaits for its result (after the queries before it): forplugin_startandmap_start, not for every frame. A database reaches its own file only:ATTACH,DETACHandVACUUMare refused. Databases and stores close with their plugin, after their pending writes. -
TOML:
cs.toml_encode(table),cs.toml_decode(text),cs.read_toml(path),cs.write_toml(path, table)(keys sorted). -
Binary files: Luau's
bufferlibrary reads and writes integers, floats and strings at any offset;cs.read_buffer(path)andcs.write_buffer(path, buffer)move a whole file (replays, compact records). -
Async files:
cs.read_file_async(path, {binary}, callback)(up to 256 MB) andcs.write_file_async(path, data, {append}, callback?); the callback gets(value, nil)or(nil, error).
tools/plugin_bots_test.sh services checks all of it, and that a query of several seconds leaves every frame on time.
Network. One network thread owns every socket and TLS session (Mbed TLS); the tick only queues and reads.
-
Hosts: a plugin reaches only the hosts its
plugin.tomllists:hosts = ["api.example.com", "*.example.org", "127.0.0.1"](a name in any case, a domain and its subdomains, an address) or["*"]for any host (a plugin whose address the admin sets,stats_api_url). Nohosts: no network. -
TLS:
https://,wss://andcs.tcp(..., {tls = true})check the certificate and its name against the system's store (the CA bundle on Linux, the ROOT store on Windows) and the file named by theCS_PLUGIN_CA_FILEenvironment variable (a private CA, tests). -
WebSocket:
cs.websocket(url, {headers, timeout})gives an object with:on("open" | "message" | "close", fn),:send(data, binary?)(a buffer is sent binary),:close(code?, reason?),.open,.url.messagegets(data, binary);closegets(code, reason, error). Pings are answered, fragments joined (16 MB per message), and messages sent before it opened go once it does. A close by the plugin runs no close handler. -
Raw sockets (the
raw_socketspermission):cs.tcp(host, port, {tls, timeout})andcs.udp(host, port), objects with:on("open" | "data" | "close", fn),:send(data),:close(),.protocol,.host,.port,.open. UDP sends and receives whole datagrams to and from one host.
tools/plugin_net_test.sh checks HTTPS (a trusted certificate, a rogue one, a name mismatch, a timeout), WebSocket and WSS (echo, binary, ping, fragments, both closes, a refused upgrade), TCP with and without TLS, UDP and the hosts list against local servers (tools/plugin_net_server.py) with a CA made for the run.
5n. Between plugins (S4)
-
Exports:
cs.export("name", fn)offers a function;cs.import("plugin", "name")gives a function that calls it (the export is looked up at each call, so it follows a reload);cs.exports("plugin")lists the names. Each plugin has its own VM, so arguments and results are copied: nil, booleans, numbers, strings, vectors, buffers, the API's objects (a copied player is the same player) and tables of those, at most 32 levels deep; functions and event objects never cross. An error inside an export raises in the caller. -
Plugin events:
cs.emit("record", ...)runs every plugin's handlers of"<emitter>:record"(cs.on("stats:record", fn, {priority})) now, by priority, with copies of the values; a handler that returns false stops the later ones, andcs.emitreturns whether none did. A plugin emits only its own events. -
Shared files:
require("@other/lib/util")loads a file of another plugin into this plugin's VM (its code, not its state);othermust be independs. Relative requires inside that file stay in its folder. -
Dependencies:
depends = ["stats", "core >= 1.2", "ui ^2.0"](>=,>,=,<,<=,^the same major version,~the same major and minor). Plugins load after what they depend on; one whose dependency is missing, did not load, has the wrong version or forms a cycle is not loaded, and the server says why.plugin unloadrefuses a plugin others need (plugin reloadkeeps them working: their imports follow).
tools/plugin_share_test.sh checks all of it with the plugins in native/game/src/plugins/tests/share.
5o. Languages and admins (S4)
-
Languages: a plugin's texts live in
lang/<language>.toml(hello = "Hello, {1}!"; tables give dotted keys,menu.title).player:t(key, args?)picks the player's language (the game sends the system's,es_ar, as the userinfo keylang;player.language), then its base (es), then the plugin's own (language = "en"in plugin.toml, the default), then English, then the key itself.{1},{2}... come from a list,{name}from a table;{{is a brace.cs.t(language, key, args?)does the same for the console or a log;cs.languages()lists the plugin's. -
Admins:
admins.toml(section "Admin commands" ofdocs/protocol.md) has[[group]]tables (name,allow,deny,inherits,immunity) and[[admin]]entries (id,groups,allow,deny,immunity).player:allowed(name)is true when an allow pattern of the entry or its groups matches and no deny pattern does; the names are commands, cvars or any permission a plugin checks (zones_edit).player.admin,player.immunity(the highest of the entry's and its groups'),player:groups()(inherited ones too) andplayer:can_target(other)(itself, or an immunity not above its own).
tools/plugin_people_test.sh checks both with two clients.
5p. Mods (S5)
-
Entity classes:
cs.register_entity("zp_supply", { spawn, think, touch, use, blocked, model, precache, mins, maxs, solid, movetype, usable })defines a class on one native class of the host, which calls the plugin back with the entity first. Maps may place it (its keys reachspawn(entity, keys)as strings) andcs.create_entitymakes it (:key_valuebefore:spawn()feeds the same table). The name may not be a game class or another plugin's; the model and theprecachelist are precached at every map. Unloading the plugin leaves its entities inert. -
Map patches: before a map's entities spawn, each plugin's
maps/all.tomlthenmaps/<map>.tomlapply:[[remove]](key patterns,*wildcards, never the world),[[change]](match,set,unset) and[[add]](a classname and keys; arrays become"x y z"). Thencs.patch_map(fn)handlers get(map, entities)and edit the list of key tables in place.cs.map_entities()shows the patched list. Without plugins the BSP's text loads untouched. -
Buying:
cs.buy_items()lists the buy menu (the game's items by their buy commands,ak47,vesthelm,primammo, and the plugins').cs.set_buy_item(id, { price, enabled, team, name, reset })changes one;cs.register_buy_item(id, { name, price, group, team, icon, buy })adds one, bought from the menu or by typing its id under the game's checks, itsbuy(player)callback giving it (false: not bought, not paid).player_buyhandlers may changecostfor one purchase.player.buy_zone(map,anywhere,nowhere) andplayer.can_buy. Once a plugin changed buying, the server sends the clients its catalog (theBuyMenumessage: lines of group, key, id, name, price, team and picture) and their buy menus show it; until then nothing is sent and the game asks nothing of the plugins. -
Gun variants:
cs.register_weapon("weapon_ak47_gold", { base, name, damage, cycle, clip, spread, recoil, max_speed, penetration, range_mod, view_model, player_model, world_model, fire_sound, price })makes a variant of one of the game's guns (base = "ak47"). The entity keeps the base's class name, so slots, duplicates anddropwork as for the base;weapon.varianttells it apart. Rates scale every fire mode in proportion (the alternate, zoomed and burst cycles), spread and recoil scale the base's tables, and with apricethe variant is sold in the buy menu next to its base (its id is the class withoutweapon_). Maps andgivemay name it. The server sends the clients the definitions (WeaponDef) and who holds which variant (WeaponHeld), so their weapon prediction, view model and fire sound follow it.weapon.max_speedreads the speed the carrier runs at; setting it overrides the gun's. -
Grenade variants:
cs.register_grenade("weapon_firegrenade", { base, name, fuse, damage, radius, gravity, friction, view_model, player_model, world_model, price, detonate })makes a variant of the HE, flash or smoke grenade the same way (the clients get it in the same messages). A thrown one takes the variant's fuse, flight, damage and radius, andgrenade.variantnames it.detonate(grenade, thrower)runs when it goes off, after thegrenade_detonatehandlers; returning true means the plugin made the blast, and the game's is skipped. A player carries the base's count; buying one more while holding the base's grenades turns them all into the new one. -
Modes:
cs.register_mode("deathmatch", { title, off, respawn, objectives, start, stop }); one runs at a time (cs.set_mode(name),cs.set_mode()for none;cs.game.modenames it). While it runs, thecs.gamerules inoffstay off, a dead player on a team spawns againrespawnseconds after dying, and withobjectives = falsethe maps' bomb sites, hostages, rescue, VIP and escape zones (and the bomb) are taken out at once and at each map. The server list's info gets amodeline with its title (the browser's Mode column; with no mode and nocs.game.description, game.toml'smode, else "Classic Strike"). When it stops, its rules come back and the teams' settings reset. The info never lists a server's plugins. -
Teams:
Team.titleandTeam.color(#rrggbb) rename and recolour a team on the players' scoreboard and team menu (theTeamLookmessage, sent only once a plugin changed them).Team.limitcaps the players the team menu and auto-join put there, andTeam.joinable = falsecloses it (both act through the game's "team full" check, so bots and auto-join choose the other team);Player:join_teampasses both. They reset when the plugin that last changed them unloads. -
Votes:
cs.vote(title, options, done, voters?, seconds?)shows the voters (default everyone; bots never vote) a numbered menu; it ends when all chose or afterseconds(15), anddonegets the counts, votes, voters and the winner (none on a tie). A title or option that is a key of the plugin's texts shows in each voter's language (the winner'soptionis the key). One vote runs at a time (cs.vote_running();cs.cancel_vote()ends one's own).cs.change_map(map, delay?)changes the map (false: no such map).
tools/plugin_mods_test.sh checks them (a client buys by its script and prints the catalog it got, cs_netclient -buymenu; it buys the golden AK, fires and reloads it, and its predicted weapon, clip and next attack are compared with the server's, -predict -weapons; then it throws an HE and a fire grenade with a blast of the plugin's own). tools/plugin_modes_test.sh runs a deathmatch mode: a client asks for the closed team, auto-joins, dies and respawns; the server's info and the client's team look (cs_netclient -teamlook) are checked; the client answers a vote and downloads the plugin's content file, refusing a wrong copy from a web mirror (cs_netclient -download).
5q. Demos the server records
-
Recording:
player:record(name?)starts a demo of the player in the server's folder (server_demos/<name>.csdem), the same file the player's client would record plus every command it ran;player:stop_recording({discard, save_as})ends it (kept, renamed, or deleted: a run that was not a record);player.recordingis the name being recorded andplayer.recording_timewhere it is (seconds on the clock its commands are read back with: a plugin notes its own moments of a run, such as a pause, to find them in it). The console'ssv_record,sv_stoprecordandsv_autorecordmake the same recordings (docs/dedicated.md). -
Reading:
cs.open_recording(name, function(rec, err) ... end)reads one on an I/O thread once it is written;rec.map,rec.count,rec.length,rec:command(i)(aRecordedCommand: time, view angles, moves, buttons, msec, impulse, weapon, origin, velocity, on the ground, ducking) andrec:at(time)(the command then) let a plugin study how a player moved and aimed.rec:close()frees it.cs.recording_part(name, offset, length, fn)reads its bytes in pieces on an I/O thread (to send it withcs.http), andcs.remove_recording(name)deletes one. -
Replays: a bot from
cs.add_botplays one withbot:play(rec, {from, to, speed, loop}), posed each frame between the commands around it, with the animation the others were shown and the legs and aim worked out again from each command as the player's were;bot:stop_playing()ends it,bot.playingtells,bot.play_timeis where it is, andreplay_endfires when it reaches the end withoutloop.
tools/server_demo_test.sh runs the test plugin tests/demos (recordings from the console, the plugin and automatic ones; the recording time against the commands read back; reading, in pieces too; removing; a bot playing one to the end, looping and stopped).
5r. A player's sky, voices, sprays and the ban list
-
Fog and weather for one player:
player:set_fog({color, density})(#rrggbb, 0 to 0.1; no options: the map's ownenv_fog, or none) andplayer:set_weather("rain" | "snow" | "none")(nil: the map's own). They last until the map changes or another call. -
Who is talking:
player.speaking(a voice packet in the last 0.3 seconds) andplayer_voicewhen a player starts or stops;player:mute_voice(speaker, true)silences a speaker for a listener. -
Sprays:
player_spray(the player, where on the wall) before the picture is drawn;ev:block()stops it (the wait until the next spray still counts). -
Bans:
cs.bans()lists the player ID and computer bans in force (id,minutesleft, 0 for good), next tocs.banandcs.unban.
tools/plugin_extras_test.sh runs the test plugin tests/extras (a client that sprays twice and talks for two seconds; the fog and weather messages it got are counted).
5s. HUD texts
-
HUD messages:
cs.hud_message(to, text, {x, y, color, color2, effect, fx_time, fade_in, hold, fade_out, channel})is the game's own HUD message: the four channels (channel1 to 4; without it the next in turn for that player), the effectsfade,flicker(betweencolorandcolor2) andtypewriter, x and y from 0 to 1 (-1 centres). It returns the channel used. A message on a channel replaces the one there. -
Director messages:
cs.dhud_message(to, text, {x, y, color, effect, fx_time, fade_in, hold, fade_out})draws the larger letters, eight at once for each player (the oldest goes first). -
The game's own texts:
cs.hud_text(to, text, {id, x, y, color, color2, effect, fx_time, fade_in, hold, fade_out, size})is one kind of message for everything both do, with no channels:sizesets the letters (8 to 120 points, 22 by default),hold = -1keeps the text until it is taken off, andidnames it (a new id is made when there is none; it is returned). The same id replaces its text;cs.hud_text_remove(to, id)takes one off andcs.hud_text_remove(to)all of the plugin's. Each plugin's ids are its own. A player sees up to 256 at once beside the HUD and director messages.align(left,center,rightof x) andfont = "mono"(columns line up) make HUD panels.
Every HUD text is drawn as light added to the picture, as in CS 1.6 games. The AMXX layer (set_hudmessage, show_hudmessage, ShowSyncHudMsg, ClearSyncHud, set_dhudmessage, show_dhudmessage) now sends these messages, with their effects.
tools/hud_text_test.sh runs the test plugin tests/hudtext (channels in turn, refused options, replacing and taking off by id, twenty texts at once) and checks what a client's HUD shows.
6. The schema
api.toml declares, for the generator:
[[function]]
name = "chat"
doc = "Writes in the chat of one player, some, or everyone (nil)."
args = [ { name = "to", type = "Players?" }, { name = "text", type = "string" } ]
[[class]]
name = "Player"
[[class.property]]
name = "name"
type = "string"
doc = "The player's name."
[[event]]
name = "player_connect"
before = true
doc = "A player connects; before handlers may refuse it."
fields = [ { name = "player", type = "Player" } ]
methods = [ { name = "reject", args = [ { name = "reason", type = "string" } ] } ]
Types: number, integer, boolean, string, vector, function, Player, Players (a player or a list), option tables ([[options]]), classes, T? for optional. The generator writes a checked wrapper per function, an __index/__newindex per class and per event object, the event structs with their handler counters, the Luau declarations (declare cs: { ... }, for luau-lsp) and the reference.
7. Verification
-
With no plugin: every oracle zero (
cs_tests,verify_ns.sh, demoshots). -
tools/plugin_test.sh: a dedicated server (port 27019) with the test plugins ofnative/game/src/plugins/tests/, a client that connects, runs commands, talks and leaves, and one that is refused. Theselftestplugin checks itself (require, sandbox, argument errors, settings and their ranges, priorities, stop, removal, event objects, timers, players, chat, commands); the script checks the host's own reports (a file that does not compile, the time budget, the memory cap, errors with file and line, pausing and resuming, unloading). -
tools/gen_plugin_api.py --check: the generated files match the schema.