Skip to content

Latest commit

 

History

History
646 lines (491 loc) · 102 KB

API.md

File metadata and controls

646 lines (491 loc) · 102 KB

CDAL API reference

Lua controlled-player state (API 3 / SnapshotProvider=0)

When [Lua] SnapshotProvider=0 is set explicitly (the read-only snapshot provider defaults to 1), game.player_state() takes no arguments and returns nil, reason. No mounted, combat, movement, death/revival or pause/menu fields are established as safe lock-free snapshots. Source inspection shows it needs no IDs and makes no game-memory reads or game calls. Do not treat the refusal as false or use it to authorize a change. See the Lua guide. With [Lua] SnapshotProvider=1 (the default) in Lua API 3-8, game.player_state() returns the verified snapshot fields (plus API 5+ enriched fields) documented in Lua API 4-8, BSX services & DevBridge v1.

BSX script diagnostics services

get_service("BSX.Status/1") retains its frozen bsx_status_service_v1 and bsx_status_row_v1 layouts (bsx/status.h). Its count/at now list native plugin rows followed by copied Lua script rows, including an instantiated console. Script file is scripts/<folder>; status contains errors=N and bounded last-error text; reason contains the state or exact approval lines. bsx_interface.plugin_count/at remain DLL-only. Count/at are thread-safe but are not one atomic snapshot; handle BSX_E_NOT_FOUND during changes.

BSX.Lua.Status/1 is an optional process-lifetime provider defined by bsx_script_status_service_v1: struct_size, api_version=1, context, count(context, uint32_t*), and at(context, index, bsx_status_row_v1*). Both copy outputs and return BSX_E_ARGS for null output; count returns BSX_E_UNAVAILABLE until the first FRAME snapshot, and at returns BSX_E_NOT_FOUND for absent indices. Check size/version/function pointers and reacquire via get_service; never hold loader locks while calling a provider. No pointer to a Lua state or mutable script storage crosses the service.

BSX.Lua.Console/1.submit(context, ":reload hello", length) uses the existing bounded input queue to reload exactly the hello folder on FRAME. It works with HotReload=0, skips old unload callbacks, cancels old work and rechecks static-file approvals. Approval INI changes still require restart. See the Lua guide.

Lua typed policies (API 3)

game.weather is a callable table: game.weather() retains the raw weather snapshot. Approved lua_api: 3, changes: true scripts additionally receive game.weather.scale_precipitation(rain_factor, snow_factor) and game.weather.reset_precipitation(). The setter requires exactly two finite numeric factors in 0..1, [Policies] precipitation=1 in the host INI, FRAME, an exact checked build and declared/resolved IDs Weather::GetRainIntensity, Weather::GetSnowIntensity, WorldSystem::sInstance, WorldSystem::RenderManager, RenderManager::WeatherState. Success is true; failure is nil, reason, including owned by <folder>. Reset takes no arguments and relinquishes only the caller's claim without game reads or hook installation. Raw reads retain their additional ID requirements. Console and native-only approval do not grant policy methods. Stop/reload/error/removal reset values; the process-lifetime host hooks forward once with no Lua on native threads. See framework and context rules.

Save IDs 365-379 have native contracts. SaveCatalogue::WriteSlot is u32* (catalogue, result, u32 slot, serverActor, optionsPointer) with a required fifth pointer at entry RSP+0x28. SaveSerializer::SerializeAndCommit takes four arguments (serializer/result/store/slotName); SaveDataStore::CommitRecord and handler WriteSlot/DeleteSlot take two; WriteFile/Encode take three. SaveCatalogue::DeleteSlot takes catalogue/result/slot/refresh. Follow the ID descriptions for native buffer ownership and return semantics. These are observation anchors, not new SDK or Lua callable functions.

Co-save service (API 3)

On Windows, get_service(BSX_COSAVE_SERVICE) returns bsx_cosave_service_v1* only when CoSave/WorldReady are enabled and the required hooks install. Check version == 1 and struct_size. register_data(self, name, callbacks, &handle) registers save(user, writer) and load(user, reader); names are 1..64 lowercase ASCII letters/digits/_/-, scoped by the owning DLL. writer->write(context, bytes, size) copies one blob, maximum 65536 bytes. ready(self, handle) is false until this registration's current load/reset arrives. unregister_data(self, handle) cancels queued work and drains callbacks before user data is freed. No bsx_interface field or existing enum changes.

Callbacks run on the observed FRAME thread, never the I/O worker. Save runs at publication, or, when the game saves on another thread, on the first FRAME after the save starts; PRESENT, MISSING or MISMATCH loads run at/after matching WORLD_READY. A PENDING reset can arrive earlier on FRAME during a slot switch. Do not retain borrowed buffers or call native save functions. A successful snapshot is not a disk commit. Lua API-3 scripts use bsx.save.set(key, string_or_number) and get(key); no additional permissions, paths or game calls are exposed. See the complete contract and backup procedure.

Native stat IDs 290–299 have build-specific call and data contracts, including all stack arguments and helper limitations. Check LookupByKey's build description for whether the key is passed by pointer in RCX or by value in EDX. These are game addresses, not new SDK or Lua functions. ID 77 requires a writable snapshot as its fifth argument.

The lookup, pack, hook and BSX APIs, in one page. The headers are the authority: cdal.hpp, hooks.hpp, cdal.h, hooks.h, bsx.h, hotkeys.h, status.h, world.h, ui.h. How to use them in a port: PORTING.md.

API use, SDK integration (including header-only builds) and adapted examples in mods are permitted by LICENSE, section 2. Your own work keeps its own licence. Preserve the applicable notices with copied or compiled SDK code; distributing modified or repackaged CDAL/BSX implementations requires written permission except for the licence's explicit contribution permissions.

Lua stat request follow-up

Lua stat request follow-up: by default ([Lua] ServerCommands=0 or lua_api: 3), game.stats.add keeps its exact unverified-semantics/FRAME refusal ([Lua] ServerCommands=1 in Lua API 4-8 enables server-queued mutations; see Lua API 4-8, BSX services & DevBridge v1). Stat request analysis identifies ID 415's movement caller and receiver 348's direct ordinary-mutator path, which bypasses ID 10's HP branch and STAT_CHANGE entry observation. Do not substitute that packet for a generic heal or use event 16 as application completion. heal_hotkey is an approval/refusal probe with no game reads/native calls and intentionally no ID requirements.

Which header

ID-specific arguments and dereferences are in ids.md. The corrected database withdraws IDs 135 and 164; their old constants remain reserved, and require() must fail for them. Engine::sInstance and Appearance::ApplyEquipmentBatch are distinct replacements with new contracts, not aliases. Follow the migration steps.

You write Include Define / link Gives you
C++ that reads addresses only cdal/cdal.hpp, cdal/ids.hpp nothing (header-only) cdal::init, address, ptr, value, require, Relocation, find_vtable, class_name
C++ that hooks (the usual case) the above + cdal/hooks.hpp CDAL_SHARED before cdal.hpp; link cdal.lib the above through cdal.dll, plus cdal::hooks::*
C, Rust, Zig, LuaJIT cdal/cdal.h, cdal/hooks.h, cdal/ids.h link cdal.lib, or GetProcAddress on cdal.dll the C functions below
A BSX plugin bsx/bsx.h, plus any of the above link cdal.lib if it hooks bsx_plugin_query, bsx_plugin_load, events
A mod with its own site pack cdal/cdal.hpp and the pack's generated <name>-ids.hpp as above; cdal.dll 0.4 in shared mode cdal::Pack

C++17 for cdal.hpp and hooks.hpp. All functions are thread-safe after init().

IDs and kinds

Helmet visibility IDs 600-608 are offline native mappings on all five builds. Only the part-visibility evaluator has a complete prototype; descriptor/priority sites do not authorize Lua calls. game.appearance.hide_helmet(enabled) is a future policy contract and remains unavailable until its native rebuild and restoration gates are proven.

Input IDs 400-414 map game functions, the dispatch-owner slot, the action-context vtable and two offset fields; see native input contracts. HandleMessage (402) takes five arguments, with lParam at entry RSP+0x28; PollXInput (404) takes RCX/XMM1/R8D/R9. The other mapped functions take one to four register arguments. These IDs add no CDAL/BSX C ABI function or Lua binding. AcceptEvents does not clear action caches, and MoveBlocked only zeros movement. Thread/lifetime and release handling remain live-test requirements.

For inventory work, use the item mapping contracts and catalog descriptions. New game-function IDs are Inventory::ApplyPlannedItem (four arguments), Inventory::RemoveAtSlot (five), Inventory::FreePlannedItems (one). The existing UsableItem::Destroy (122) supplies item cleanup. These mappings do not change the CDAL C ABI. Inventory::InsertIntoHolder takes nine arguments and produces an owned 0xE0-byte placement vector. Legacy CommitTransaction is an extraction operation, and legacy FreePlacements walks a different 0xD8 container. Game calls are not made thread-safe by CDAL's thread-safe address lookup.

An active function's catalog entry may contain prototype: ordered argument types, stack argument count, result register and checked_builds. It is metadata in docs/reference/ids.json and comments in ids.hpp, not a native API or function typedef. Require the current build to be listed, preserve every argument and consult the description for pointer ownership and thread requirements. Absence means unknown; it does not imply a zero-argument or void function.

IDs are std::uint32_t constants: cdal::ids::<Class>::<member> (C++, cdal/ids.hpp) and CDAL_ID_<Class>_<member> (C, cdal/ids.h). A name part that is a C++ keyword gets a trailing _. 0 is never an ID. The list with descriptions and per-build status is docs/reference/ids.md.

Kind What the ID's value is Read it with
function a function's first instruction cdal::Relocation<Fn>, cdal::ptr<Fn>, FunctionHook::install
code one instruction inside a function; the description names it and its registers MidHook::create, Patch::create, cdal::address
data the address of a global; usually holds a pointer ("dereference once") cdal::ptr<T**>
vtable a class's virtual function table cdal::address, compare with *(uintptr_t*)object
offset a number, usually a struct field offset cdal::value

C++ core: cdal/cdal.hpp

Call Returns On failure
bool cdal::init(const cdal::Options& = {}) true when a database is loaded for this process false; cdal::last_error() says why (no CDAL folder, no .cdal file, bad file)
std::uintptr_t cdal::address(std::uint32_t id) absolute address in the running game 0 (unknown ID, no value on this build, or not initialised)
std::uintptr_t cdal::address(std::string_view name) same, by name such as "WorldSystem::sInstance" 0
template <class T> T cdal::ptr(std::uint32_t id) reinterpret_cast<T>(address(id)) a null T
std::optional<std::uint64_t> cdal::value(std::uint32_t id) the value of an offset ID std::nullopt (also for a non-offset ID)
bool cdal::require({ids...}, std::string* missing = nullptr) true when every ID resolves (empty list returns true) false; *missing = "Name: reason; Name: reason"
std::string cdal::last_error() shared mode: the last error on this thread; header-only: the library initialization error. For lookup failures use require(..., &missing) or Library::lookup(id).error
std::string cdal::build() the build name of the database in use, e.g. "1.0.0.xxxx"; "" if none
std::uintptr_t cdal::find_vtable(std::string_view type) primary vtable of a class by RTTI name, "pa::Foo" or ".?AVFoo@pa@@" 0. The first call per name scans the game once (under a second); call it from a worker thread. Shared mode needs cdal.dll 0.3
const char* cdal::class_name(const void* object) decorated RTTI name of the object's class nullptr, also for a bad pointer. Shared mode needs cdal.dll 0.3
std::string cdal::demangle_rtti(std::string_view) ".?AVFoo@pa@@" becomes "pa::Foo" input unchanged
cdal::Relocation<T> r{id, offset = 0} lazy typed address: r.address(), r.get(), r(args...), bool(r) address() == 0; calling a null one crashes, so require() first
void cdal::set_crash_context(const char* context) / cdal::ScopedCrashContext sets or scopes a thread-local tag (up to 191 UTF-8 bytes; RAII guard clears on scope exit) emitted in crash notes (C API 8) no-op if cdal.dll lacks it

Typical reasons in missing: no value for this game build (the database has no value for this build and signature scanning is off), no value for this game build and no signature, pattern not found or pattern is not unique (a game patch moved the code and CDAL's data isn't updated yet), signatures disagree: 0x…, 0x… (two of the ID's signatures found different places on this build, so neither is trusted), the database's value 0x… is outside the game's image (a damaged or wrong database), unknown id 123 (the mod's ids.hpp is newer than the player's CDAL folder), CDAL not initialized. Log it as it is: players paste it into bug reports.

cdal::Options fields (all optional): directory (default: CDAL next to the exe), module_base / module_size (default: the game exe), allow_scan (default true: scan signatures when the database has no value for this build), embedded_data / embedded_size (a .cdal file compiled into the mod; used only when the CDAL folder has no database for this exact build), scan_cache (default false; cdal.dll sets it for the game itself: scan results are written to <directory>/cache/scan-<pe timestamp>-<size of image>-<database hash>.txt and reused on the next start with the same exe and database; Library::cache_file() and Library::cached() report the file and how many entries came from it), allow_hooked (default true: a byte pattern with no match is looked for once more behind another mod's hook jump; false skips that search, for a clean image such as the exe on disk, where such a match could only be the wrong place). In shared mode the first init() in the process wins, whoever calls it.

Library::prefetch() scans, before any lookup, the signatures of every entry without a stored value: all byte patterns in one pass over the code, and all rtti and str signatures in batch passes (three over the data sections for every class, one over the sections and one over the code for every string). Lookups after it get exactly what they would have found one by one; init() calls it for a pack and resolve_all() always does. Library::resolve_signatures(id) returns each signature's own cdal::Resolution (ok, value, is_value, matches, error), in the database's order, without using a stored value, checking the kind or comparing the signatures: cdal-resolve writes these for cdal resolve. The free function cdal::resolve(image, pattern, recipe, index, allow_hooked = true) takes the same switch.

Recipes (cdal::Recipe::parse) take the ops in FORMAT.md; func_start and find_in_func <pattern> (CDAL 0.8) find a place through the function around the cursor as .pdata lists it, and fail closed with the reason in Resolution::error. cdal::Image::pdata_rva() and pdata_count() give the exception directory they read. A cdal.dll before 0.8 rejects such a recipe, so keep a signature without them in a pack that must run on older ones.

Site packs: cdal::Pack (CDAL 0.4)

A pack is a mod's own list of addresses, compiled by tools/pack.ps1 into bin64/CDAL/packs/<name>/ (PACKS.md). Its IDs are constants in the pack's generated header, cdal::packs::<name>::Class::member, and mean nothing to cdal::address(); ask the pack.

Call Returns On failure
bool Pack::open(std::string_view name, cdal::Options = {}) true when CDAL/packs/<name>/ has a database; ready() says the same later false; last_error() says why
std::uintptr_t Pack::address(std::uint32_t id) / address(std::string_view name) absolute address 0
cdal::Status Pack::status(std::uint32_t id) Verified (safe to patch: on the reference build every signed site; on later builds only "verify": "body" sites whose function's code is unchanged, and sites read from a vtable or table slot whose function is unchanged; the rest come back Resolved), Resolved, Scanned (found by a runtime scan rather than a stored value: call and hook only), Missing
bool Pack::require({ids...}, std::string* missing) same as cdal::require, for the pack's IDs
std::string Pack::build(), bool exact_match(), std::string last_error(), bool write_report(path)

A Pack can't be copied: keep it as a global or static. The generated header's namespace is the pack name with - turned into _ (live-edit gives cdal::packs::live_edit), with a pack_ prefix when the name starts with a digit. Hook a pack address with install_at / create_at. C: cdal_pack_open(name, options, &pack), cdal_pack_address, cdal_pack_lookup (info.status), cdal_pack_require, cdal_pack_id_by_name, cdal_pack_entry_count, cdal_pack_entry_at, cdal_pack_build_name, cdal_pack_build_matched, cdal_pack_write_report, cdal_pack_close.

cdal::Library is the class behind these functions, for tools that need their own instance (lookup(id) returns a cdal::Record with status, matches and hooked; write_report(path)). Mods don't need it.

Feature states: cdal::Feature (C API 6)

cdal::Feature f{owner, name} is one feature of a mod: owner is the mod's name (the hook owner), name the feature's name as players and the mod's enrollment know it. Keep it as a global or static.

Call Does Reports to cdal.dll
bool f.require({ids...}, std::string* missing = nullptr) cdal::require() for the feature's IDs on, or off with missing on <build>: <missing>
void f.off(std::string_view reason) marks the feature off after its require(): a failed hook (rule 7), a check that didn't pass (also usable without IDs) off with reason
void f.on() marks it on again (also usable without IDs) on
bool f.is_on(), const std::string& f.reason(), owner(), name() the last state

It finds cdal_report_feature in the loaded cdal.dll with GetProcAddress and does nothing when that is missing, so it works in shared and header-only builds, on every cdal.dll, and never raises the CDAL version a mod needs. cdal.dll keeps one row per module, owner and feature (up to 256 rows), logs each change once (feature off: <owner> / <feature> (<module>): <reason>, feature on: ...), and lists the rows in session.json and crash notes. A failed cdal_require or cdal_pack_require is recorded even without cdal::Feature: once per calling module and ID set, as <module>: require failed on <build>: <missing>, and a named report for the same IDs from that module takes that row over. Attribution is the calling module; BSX plugins and BSX Lua scripts report with each plugin's or script's own owner and feature names (and set scoped cdal_set_crash_context tags during callbacks).

C++ hooks: cdal/hooks.hpp (needs cdal.dll)

cdal::hooks::Options{owner, priority}: owner is the mod's name (required, shown in CDAL/hooks.log), priority higher runs first, default 0.

Type Create Use Remove
FunctionHook<Fn> (must be a global or static; not copyable or movable) bool install(id, Fn detour, Options, std::string* err); install_at(std::uintptr_t, ...) for an address original() returns the next hook in the chain, then the game; valid at once and forever (cdal_hook_function enables the hook immediately after writing *original, so pass the live detour slot directly) reset() or destruction
MidHook (movable) static MidHook create(id, std::function<void(cdal_context&)>, Options, std::string* err); create_at(address, ...) the callback gets the registers and may change them reset() or destruction; a call another thread is already making finishes safely, later calls skip it, and a callback may reset() a hook that runs after it at the same address
Patch (movable) static Patch create(id, std::ptrdiff_t offset, std::vector<std::uint8_t> bytes, Options, std::string* err); create_at(address, bytes, ...) bytes are written at once reset() or destruction tries to restore the original bytes; later writes are left alone
std::vector<std::uint8_t> read_original(std::uintptr_t at, std::size_t n, bool* changed = nullptr, std::string* err = nullptr) (CDAL 0.6) the n bytes at at as the game had them: bytes under a CDAL hook's jump or patch come from CDAL's saved copy, the rest from memory; *changed says whether CDAL changes any of them now read instructions at a hooked function's start, or check bytes before you patch empty on failure (unreadable range, n 0)
std::vector<HookInfo> list() every active hook and patch registered through CDAL: handle, kind, target, owner, priority, id, name, foreign, chain_index for menus and logs

A FunctionHook and a MidHook on the same address both work (cdal.dll 0.5 or later; 0.4 and older refuse the second), whichever comes first: the mid hooks run first, then the function chain. A mid hook a few bytes into a function another mod function-hooks overlaps its jump and is refused.

Test success with bool(hook) (or install()'s return value). On failure *err says why: the ID has no value, a conflict (names the other mod), or the address can't be hooked. One reason for the last: the first 5 bytes hold a branch back into themselves (a tight loop) or a loop/jrcxz, which SafetyHook can't move into its trampoline correctly; hook a few instructions later, or a different place.

A raw-address function hook may also target a Windows function (GetProcAddress on kernelbase.dll, for example), as Crimson FastLoad does for Sleep. While it writes such a hook, CDAL keeps the page executable when it lies in ntdll.dll, kernelbase.dll, kernel32.dll or the C and C++ runtimes, because the thread placing the hook runs code there itself. In CDAL 0.7.3 and earlier, a hook on a function that shares a page with VirtualProtect's body hung that thread (kernelbase Sleep after Windows update KB5132061).

cdal_context fields: xmm0..xmm15 (unions with u8[16], u16[8], u32[4], u64[2], f32[4], f64[2]), rflags, r15, r14, r13, r12, r11, r10, r9, r8, rdi, rsi, rdx, rcx, rbx, rax, rbp, rsp (read-only), trampoline_rsp, rip. Same layout as SafetyHook's x64 context.

C ABI: cdal/cdal.h (API version 8) and cdal/hooks.h

Every struct has struct_size as its first field; set it to sizeof the struct. Results are cdal_result: CDAL_OK 0, CDAL_E_NOT_INITIALIZED 1, CDAL_E_NO_DATABASE 2, CDAL_E_UNKNOWN_ID 3, CDAL_E_UNRESOLVED 4, CDAL_E_WRONG_KIND 5, CDAL_E_ARGS 6, CDAL_E_IO 7, CDAL_E_CONFLICT 8, CDAL_E_HOOK_FAILED 9.

uint32_t    cdal_api_version(void);             /* 8 on CDAL 0.8 (5=0.7, 6=0.7.6, 7=build_flags, 8=crash_context) */
const char* cdal_library_version(void);         /* e.g. "0.8.1" */
cdal_result cdal_init(void);                    /* idempotent */
cdal_result cdal_init_ex(const cdal_init_options*);
cdal_result cdal_reinit(const cdal_init_options*); /* replaces the previous initialization */
uintptr_t   cdal_address(uint32_t id);          /* 0 if missing */
uintptr_t   cdal_address_by_name(const char* name);
cdal_result cdal_value(uint32_t id, uint64_t* out);
uint32_t    cdal_id_by_name(const char* name);  /* 0 if unknown */
cdal_result cdal_lookup(uint32_t id, cdal_entry_info* out);
cdal_result cdal_require(const uint32_t* ids, uint32_t count, char* msg, size_t msg_size);
const char* cdal_build_name(void);
int         cdal_build_matched(void);           /* nonzero if the database is for this exact exe */
const char* cdal_last_error(void);              /* per thread */
uint32_t    cdal_entry_count(void);             /* 0 if initialization fails */
cdal_result cdal_entry_at(uint32_t index, cdal_entry_info* out);
cdal_result cdal_write_report(const char* path_utf8);
uintptr_t   cdal_vtable_by_type(const char* type_name);   /* API 3 */
const char* cdal_class_name(const void* object);          /* API 3 */
size_t      cdal_demangle(const char* type_name, char* out, size_t out_size);  /* API 3 */
int         cdal_build_supports(uint32_t id, int require_checked);             /* API 5 */
cdal_result cdal_report_feature(const cdal_feature_report*);  /* API 6: {size, owner, feature, CDAL_FEATURE_ON or _OFF, reason, ids, id_count} */
uint32_t    cdal_feature_count(void);                          /* API 6 */
cdal_result cdal_feature_at(uint32_t index, cdal_feature_info* out);  /* API 6: owner, feature, module, state, reason */
uint32_t    cdal_build_flags(void);                            /* API 7: CDAL_BUILD_* flags for exact matched exe */
void        cdal_set_crash_context(const char* context);       /* API 8: per-thread tag included in crash notes */

/* hooks.h; options = {sizeof(cdal_hook_options), "Mod Name", priority} */
cdal_result cdal_hook_function_id(uint32_t id, void* detour, void** original, const cdal_hook_options*, cdal_hook_handle* out);
cdal_result cdal_hook_function(uintptr_t target, void* detour, void** original, const cdal_hook_options*, cdal_hook_handle* out);
cdal_result cdal_hook_mid_id(uint32_t id, cdal_mid_fn fn, void* user, const cdal_hook_options*, cdal_hook_handle* out);
cdal_result cdal_hook_mid(uintptr_t target, cdal_mid_fn fn, void* user, const cdal_hook_options*, cdal_hook_handle* out);
cdal_result cdal_patch_id(uint32_t id, const void* bytes, size_t size, const cdal_hook_options*, cdal_hook_handle* out);
cdal_result cdal_patch(uintptr_t target, const void* bytes, size_t size, const cdal_hook_options*, cdal_hook_handle* out);
cdal_result cdal_unhook(cdal_hook_handle);
uint32_t    cdal_hook_count(void);
cdal_result cdal_hook_at(uint32_t index, cdal_hook_info* out);
cdal_result cdal_read_original(uintptr_t target, void* out, size_t size, uint32_t* changed);  /* hooks API 2, CDAL 0.6 */

CDAL_HOOKS_API_VERSION is 2 from CDAL 0.6 (cdal_read_original). Bytes a hook placed outside CDAL had already changed come back as that mod left them; cdal_hook_info.foreign names it. A mod that loads cdal.dll with GetProcAddress checks that cdal_read_original exists before calling it.

cdal.dll 0.6 and later also scan through CDAL's own changes: a signature that covers a CDAL hook's jump or patch is matched against, and its recipe reads, the game's bytes there. Before, an ID with no stored value that another mod had hooked or patched across through CDAL could fail with "pattern not found", depending on which mod started first.

cdal_reinit() reloads the runtime and returns its initialization result; it is safe while other threads look IDs up (calls in progress finish first, and each call sees the old database or the new one). Text from cdal_build_name() stays valid; names from cdal_entry_at() for the previous database don't. cdal_entry_at() returns CDAL_OK for a valid index even when that entry is unresolved: check out.ok and out.status. An invalid index returns CDAL_E_ARGS. cdal_write_report() resolves every entry and writes its report; a null path returns CDAL_E_ARGS, and a write failure returns CDAL_E_IO.

cdal_mid_fn is void (*)(cdal_context* ctx, void* user). After cdal_unhook returns, later calls skip a mid hook's fn, but a thread already making that call finishes it: keep user valid for good (the C++ MidHook keeps its callback for that reason). A removed function hook's *original stays callable and leads to the hooks still placed below it. A mod that loads cdal.dll with GetProcAddress and hooks must check cdal_library_version() is 0.2.1 or later, cdal_api_version() >= 3 before calling the API 3 functions, >= 4 before cdal_pack_*, >= 5 before cdal_build_supports, >= 6 before the feature functions, >= 7 before cdal_build_flags, and >= 8 before cdal_set_crash_context. cdal_report_feature copies its strings (owner and feature up to 63 bytes, reason up to 239) and returns CDAL_E_ARGS without an owner, a feature name or a valid state; cdal_feature_at strings stay valid. cdal_set_crash_context(const char*) sets a thread-local context label (up to 191 bytes; NULL or "" clears it) emitted into crash notes alongside zero-heap CDAL ID symbolication (nearest CDAL ID: and Game addresses on the crashed stack), a single-line Signature: summary (build=, cdal=, bsx=, exc=, at=), and duplicate-module warnings (warning: duplicate module ... in hooks.log, session.json, and crash/hang notes); C++ callers can use cdal::ScopedCrashContext.

BSX: bsx/bsx.h (preview, API version 3)

Key events and hotkeys (API 3)

API 3 also appends BSX_EVENT_KEY = 25 and bsx_key_event, leaving all prior fields/numbers and bsx_interface unchanged. Require minimum API 3. Payload: struct_size, Windows virtual_key, scan_code, down, repeat, modifiers, repeat_count, flags (all u32). Modifiers are CTRL=1, ALT=2, SHIFT=4, WIN=8; flags are EXTENDED=1 and RESET=2. On focus loss/destruction/queue overflow, held keys receive synthetic ups with RESET, followed by a RESET marker with VK 0. Clear held state on that marker. These are copied OS observations, never text, game-action IDs or input-capture permission. Delivery precedes FRAME subscribers on the first FRAME thread; no callbacks execute in WndProc.

get_service("BSX.Hotkeys/1") returns bsx_hotkeys_service_v1 from bsx/hotkeys.h. Check struct_size, api_version == 1 and both function pointers. Call register_key(self, vk, modifiers, callback, user, label, &token); callbacks use bsx_event_fn and receive KEY/bsx_key_event. Exact modifiers and a non-repeat down fire once; conflicts log both owners but succeed. The optional label is copied, at most 128 bytes; 128 registrations per plugin. remove(self, token) cancels pending snapshots and drains other-thread callbacks like unsubscribe; failure/load failure cancels all of that plugin's registrations. Raw unsubscribe does not remove hotkey tokens. NULL/invalid arguments return ARGS, absent/foreign tokens NOT_FOUND, and disabled/unavailable keys UNAVAILABLE.

[BSX] Keys=1 defaults on because the observer forwards input unchanged. It attaches lazily, via a temporary thread-specific installation hook, only after a process window exists. A successful registration can precede window attachment; check bsx.log for the attachment line. Keys=0 also disables the overlay toggle. [BSX] Gamepad=1 (default 0) adds controller buttons read with XInput at FRAME: KEY events with BSX_KEY_GAMEPAD (4) in flags, a VK_GAMEPAD_* code (0xC3..0xDA) in virtual_key, the controller index in scan_code and zero modifiers; register a hotkey with that code and no modifiers. Lua: e.gamepad, bsx.hotkey('pad_a', fn). Both overlay renderers use the service; standalone UI handling is attached to the same window observer. Lua exposes bsx.on('key', fn) and bsx.hotkey('ctrl+f5', fn) in the safe tier with cleanup on reload/failure. See names and limits.

Existing event contracts

The header defines BSX_API_VERSION 3u, released with BSX 0.3.0 (CDAL v0.7.0); the v0.6.0 BSX has API 2; current BSX 0.4.0 (CDAL v0.8.0 and v0.8.1) keeps API 3. API 3 appends opt-in STAT_CHANGE (16) and after-call events 17-24 with separate payload structs and no changes to bsx_interface, bsx_plugin_info or events 1-15. Require min_api_version = 3 (or zero with api_version = 3): an API-2 loader disables that plugin before load and logs the version mismatch. An API-2 plugin loads unchanged on API 3. An API-3 plugin intentionally targeting minimum 2 must test the runtime version before using optional after events; API-2 subscribe returns BSX_E_UNKNOWN_EVENT for these new numbers.

After event (API 3) Payload Required IDs / observation
SAVE_LOAD_AFTER (17) bsx_save_load_after_event 41; request key/argument/zero flags, returned pointer and copied u32 result
EQUIP_AFTER (18) bsx_equip_after_event 34/61; before fields, returned pointer and copied i32 result
UNEQUIP_AFTER (19) bsx_unequip_after_event 35/61; before fields/sentinels, returned pointer and copied i32 result
LOAD_REQUEST_AFTER (20) bsx_load_request_after_event 39/199/200; requested, previous and post-call manager selectors
WEAPON_SWAP_AFTER (21) bsx_weapon_swap_after_event 101/61; before fields, returned pointer and copied i32 result
QUICK_SLOT_USE_AFTER (22) bsx_quick_slot_use_after_event 126; before fields, returned pointer and copied i32 result; auxiliary output untouched
MOVIE_AFTER (23) bsx_movie_after_event 58; path copied before the call, native bool result
BATTLE_STATE_AFTER (24) bsx_battle_state_after_event 80; requested bool after the void setter returns

Subscribe with subscribe(self, BSX_EVENT_*_AFTER, callback, user). Each typed hook is installed independently on first subscription and retained for the process lifetime, as with requests. The database must match the running build exactly, store every required ID, and list the event's typed IDs in that build's checked_ids (BSX gates); otherwise, and on site/vtable failures, the subscription returns BSX_E_UNAVAILABLE. Capture/result faults disable only that event; equipment receivers retain the skip/32-consecutive-mismatches rule. Callbacks run synchronously after the next chain call returns normally, including failure; native exceptions produce no event, while callback faults use existing plugin recovery. Results are copied from the actual returned pointer; never retain or modify that borrowed identity. A lower hook may skip native work or substitute its result. No replay, FRAME deferral, player filter or success-only filtering is added. Save readiness, applied equipment and playback completion are separate concepts; events 6-8 are unchanged. The after-event guide lists full signatures and stack arguments. Native events do not add Lua bindings.

API 2 also has the additional request events and player comparison. Use min_api_version = 2 when required. Event numbers 1-8 and all existing field offsets stay unchanged; the runtime interface is unchanged from the API-2 helpers.

Request event (API 2) Payload Contract / required IDs
BSX_EVENT_WORLD_READY (9, API 3) bsx_world_ready_event: generation, actor, requested_stage, follows_save on unless [BSX] WorldReady=0; FRAME after SAVE_LOADED for saves, witnessed terminal readiness for other requests
BSX_EVENT_TITLE_SCREEN (10) bsx_title_screen_event {struct_size, root} every title tick entry; 37
BSX_EVENT_LOAD_REQUEST (11) bsx_load_request_event {struct_size, manager, requested_stage, previous_stage} queue entry; 39/199/200; reads request and pre-call manager selectors separately
BSX_EVENT_WEAPON_SWAP (12) bsx_weapon_swap_event {struct_size, equipment, slot, slot2} paired-slot swap request; 101/61; not the player's weapon switch; read that from the equipment component's selection pair, offset IDs 3047/3048, or Lua weapon_draw
BSX_EVENT_QUICK_SLOT_USE (13) bsx_quick_slot_use_event {struct_size, holder, actor, storage, index, use_parameter, amount} item-use entry; 126; includes inventory use, opaque parameter, raw 64-bit amount
BSX_EVENT_MOVIE (14) bsx_movie_event {struct_size, movie, path_truncated, path[512]} movie-open entry; 58; copied raw narrow path with NUL
BSX_EVENT_BATTLE_STATE (15) bsx_battle_state_event {struct_size, hud, in_battle} HUD setter entry; 80; bool, no deduplication

Events 10-15 are synchronous before-call observations on the native caller's thread, not success/completion reports. Missing IDs/site failures return BSX_E_UNAVAILABLE independently and log a reason. An unreadable receiver or payload, or an invalid battle bool, switches off that event once; a swap receiver of another class is skipped and only 32 in a row switch WEAPON_SWAP off. The native function always runs.

bsx_equipment_applied_event appends uint32_t player_flags at offset 56 (x64 size 64; the API-2 prefix is 56 bytes). Check payload struct_size before reading it. BSX_PLAYER_KNOWN means a non-null actor was readable through IDs 1/193/194 at dispatch; BSX_PLAYER_CONTROLLED additionally means identity equality with the payload actor. Zero is unknown. Missing IDs or failed reads do not change the existing completion delivery rules. The player helper is internal, since services require a loaded plugin owner; pointers remain borrowed identities with no lifetime guarantee.

WORLD_READY requires min_api_version = 3 and offset ID 395 (LoadingManager::CompletionPropertyValue, resolved through cdal_value when reading the ID-246 property object); [BSX] WorldReady=0 makes it return UNAVAILABLE. The API-2 reserved payload prefix retains its offsets; API 3 appends uint32_t requested_stage, follows_save. Copy generation and the selectors; actor is borrowed identity only. Saves retry for the first eligible FRAME within 120 frames after SAVE_LOADED for that generation; expiry logs once and drops the pending event. Non-save requests require a prior post-Update terminal edge/property plus controlled-actor field entry, closed loading roots and fresh input/camera witnesses. Requests are deduplicated, replacement loads invalidate pending delivery, title requests are excluded, and nothing is replayed. Events 6-8 keep their predicates and timing. Do not infer readiness from selector 8. See WORLD_READY for readiness criteria and early-hook behavior.

API 3 appends BSX_EVENT_STAT_CHANGE = 16 and bsx_stat_change_event {uint32_t struct_size, source_kind; void* stat_container; uint16_t stat_id; int64_t delta; void* source_raw; void* source_actor;} (x64 size 48, delta offset 24). This is synchronous before-call observation of ID 10, preserving all eleven arguments and including zero-delta requests; it promises no result value or successful change. [BSX] StatChange defaults to 1 (on when a plugin subscribes); [BSX] StatChange=0 in BSX/bsx.ini disables it, returning BSX_E_UNAVAILABLE with a gate reason and installing no hook.

source_raw is the fifth native argument. Kind 0 (BSX_STAT_SOURCE_NULL) means null; 1 (BSX_STAT_SOURCE_ACTOR) means a guarded primary-vptr match to ID 6/62/83/203 and source_actor == source_raw; 2 (BSX_STAT_SOURCE_UNKNOWN) preserves the non-null raw pointer with a null decoded actor. Never unwrap source+0x68: checked actor paths use it as the components pointer. Missing vtable IDs leave the event unavailable. [BSX] StatChangePlayerOnly=1 additionally requires 1/193/194/195/197/198 and compares the target container with the guarded controlled-character chain; unknown chains suppress observations. StatChange defaults to 1, and StatChangePlayerOnly defaults to 0. Host dispatch takes no locks and allocates nothing; callbacks must remain short and thread-safe. See stat observations. There is no Lua binding for this event (bsx.on('stat_change', ...) copies scalars on Lua API 3).

The separate BSX Lua 0.4.0 host implements bsx.on(event, fn), bsx.log(text), bsx.after(ms, fn), and quota-limited bsx.fs.read(path)/write(path, text). Scripts start at first FRAME after manifest checks. Its additional modules and reload lifecycle are described in BSX Lua modules below. Its safe/changes tiers have no FFI or arbitrary native-call binding; separately approved native scripts use the native tier below.

A plugin is a DLL in bin64/BSX/plugins that exports:

BSX_EXPORT const bsx_plugin_info* bsx_plugin_query(void);  /* no game access here; return static data */
BSX_EXPORT int bsx_plugin_load(const bsx_interface* bsx);  /* nonzero = loaded */

bsx_plugin_info: struct_size, api_version (BSX_API_VERSION), name (unique), version, author, cdal_ids, cdal_id_count, requires_plugins (NULL-terminated), load_after (NULL-terminated), flags (BSX_PLUGIN_EARLY). BSX loads the plugin only when every listed CDAL ID resolves and every required plugin loaded, after it has called cdal_init.

bsx_interface: log(self, level, message), subscribe(self, event, fn, user), plugin_count(), plugin_at(i, out), is_loaded(name), plus self, bsx_version, plugin_dir_utf8. subscribe returns BSX_E_UNAVAILABLE when the event's game hook can't be placed on this build. Callbacks start once bsx_plugin_load returns nonzero; a plugin whose load failed gets none, and its subscribe returns BSX_E_ARGS. A C++ exception from bsx_plugin_query or bsx_plugin_load marks the plugin failed; one from a callback stops that plugin's events. Both are logged, and the game keeps running.

Event Data Fires
BSX_EVENT_PLUGINS_LOADED none once, after every plugin was tried
BSX_EVENT_FRAME bsx_frame_event {struct_size, frame} each Game::Update (id 33), game thread
BSX_EVENT_SAVE_LOAD bsx_save_load_event {struct_size, key, argument, flags} before SaveGame::LoadSlot (id 41); API 2 also replays an earlier load to a late subscriber, flagged
BSX_EVENT_EQUIP bsx_equip_event {struct_size, equipment, bucket, index, tag} before ClientEquipment::Equip (id 34)
BSX_EVENT_UNEQUIP same, bucket and index 0xFFFF before ClientEquipment::Unequip (id 35)
BSX_EVENT_SAVE_LOADED (6) bsx_save_loaded_event {struct_size, argument, generation, key, actor} next FRAME boundary after save-specific queue, successful field entry and composite readiness
BSX_EVENT_EQUIP_APPLIED (7) bsx_equipment_applied_event {struct_size, cause, generation, actor, equipment, tag, row, reserved, item_word0, count} next FRAME boundary after successful controlled-character insertion changes a valid slot
BSX_EVENT_UNEQUIP_APPLIED (8) same; copied removed item next FRAME boundary after successful controlled-character removal leaves the tag absent

Event data is valid only during the callback. Callbacks observe; to change arguments or skip the call, hook the function (PORTING.md recipe 1).

SAVE_LOAD replay (API 2): BSX hooks SaveGame::LoadSlot in the early phase when a plugin in BSX/plugins is built for API 2 or later (EarlySaveLoad=0 under [BSX] in bsx.ini turns that off) and remembers the latest load. SAVE_LOADED is not replayed. EarlySaveLoaded=1 in bsx.ini, the default, places its completion observers early so a save queued before plugins load still sends SAVE_LOADED; EarlySaveLoaded=0 is for Crimson FastLoad releases before its #18 fix, which switch auto-load off when those hooks are already there. See the known limit in the BSX guide. A plugin built for API 2 or later that subscribes to BSX_EVENT_SAVE_LOAD after a load gets that load once, on the game thread at a later FRAME after its bsx_plugin_load returned, with BSX_EVENT_FLAG_REPLAYED in flags. Live loads have flags == 0. A subscription gets no replay of a load it already received live, none after unsubscribing, and none without a FRAME hook (logged). Read flags only when bsx->api_version >= 2. A replay is a late observation, not a new load: the world may already be loaded. See a save load no plugin misses.

API 2 appends events and structs without changing API 1. Older plugins still load; a plugin requiring a newer API than the loader is disabled (see min_api_version below). New events dispatch before FRAME subscribers, in subscription order, and cancel queued data on a new loading generation. No completed load is replayed after subscription (only BSX_EVENT_SAVE_LOAD is, below). cause is BSX_EQUIPMENT_CAUSE_UNKNOWN, reserved is zero, and item_word0 is opaque, not a stable item ID. Actor/component pointers are borrowed identities. A single action can change several slots.

Completion observers use CDAL hooks owned by BSX at priority 1000. Each subscription reports BSX_E_UNAVAILABLE if its witnesses cannot be installed or its executable layout is unsupported; other events remain available. The database must match the running build exactly and store every required ID. See completion events for readiness and suppression details.

BSX API 2 helpers

EQUIP, UNEQUIP and WEAPON_SWAP check the receiver against the resolved equipment vtable. A call with another receiver is skipped (the native function still runs) and logged once; only 32 in a row switch that event off for the session, after which later subscriptions return BSX_E_UNAVAILABLE. SAVE_LOAD switches off on an unreadable key. Hook sites must be executable. These checks preserve the native call and leave other events enabled. See checked addresses and runtime limits.

API 2 was released with BSX 0.2.0 (CDAL v0.6.0). These function pointers append to bsx_interface; existing fields do not move. Use the plugin's own self wherever a handle is required. All helpers are safe to call from any thread.

Function Contract
bsx_result unsubscribe(self, uint32_t event, bsx_event_fn fn) Removes all matching registrations, regardless of user, and cancels dispatch snapshots. Waits for same-plugin callbacks on other threads; only callbacks already active on the calling thread may finish. Different threads are no longer serialized: protect shared data. Self-unsubscribe works, but callbacks must not form mutual unsubscribe waits or wait for a worker unsubscribing that plugin; defer that teardown instead. Returns OK, NOT_FOUND, ARGS or UNKNOWN_EVENT. A later subscribe is a new registration.
bsx_result defer(self, void (*fn)(void*), void* user) Calls once at the next FRAME, before FRAME subscribers, in accepted order. Enables FRAME; UNAVAILABLE if its hook fails, ARGS for invalid or switched-off callers. Calls queued during drain/FRAME callbacks wait for a later FRAME. Loading plugins hold their work and later entries until load completes. Failed loads/callback exceptions drop work with a log line. user is borrowed, never freed by BSX.
int32_t config_int(self, const char* section, const char* key, int32_t fallback) Reads signed decimal from the startup snapshot of <DLL filename>.ini beside the DLL; missing/malformed/out-of-range values use the default.
size_t config_string(self, const char* section, const char* key, const char* fallback, char* out, size_t capacity) Copies the value or default; returns required bytes including NUL even on truncation. Terminates any nonempty output buffer. NULL/0 queries size; NULL default means empty. No plugin-owned allocation.
void set_status(self, const char* text) Copies at most 255 bytes (BSX_STATUS_MAX_LENGTH), flattens CR/LF, logs and retains the status for a future window. NULL clears.
bsx_result register_service(self, const char* name, void* ptr) Registers a borrowed pointer under a case-sensitive name; provider may replace its own pointer. Invalid args, another owner or switched-off provider returns ARGS. Use versioned names and keep published pointers alive for the process lifetime.
void* get_service(const char* name) Returns NULL if missing, invalid or provider not successfully loaded/still active. Failure/shutdown removes registrations; previously borrowed pointers cannot be revoked.

INI sections/keys are case-sensitive, whitespace is trimmed, duplicate keys use the last value, and ;/# start comment lines. No quote removal, escapes or inline comments. NULL/empty section selects the root. Restart to reload settings. defer exceptions stop that plugin's callbacks and services.

BSX also guards recoverable hardware faults in event/deferred callbacks on Windows MSVC builds, before unwinding can reach the game thunk. It logs the plugin, exception code and address, cancels its work/services and immediately flushes the log. This does not guard plugin-owned threads/hooks or undo corruption. SafeMode=1 and the persistent interrupted-load marker prevent all plugin loading, including DLL queries; see player recovery. Dispatch uses immutable snapshots without a per-event allocation/mutex; plugin log messages are buffered and limited to 100 lines/s per plugin. API-1/2 layouts and event numbers are unchanged.

bsx_plugin_info appends uint32_t min_api_version: zero or absent means api_version. The loader reads it only when both api_version >= 2 and struct_size cover it, because API 1's trailing padding can occupy the same bytes. Newer headers with a supported minimum can load; check the running interface's version/size before using optional newer fields. API-1 loaders still reject a newer declared api_version. An unsupported minimum is logged and refused before load. See API helpers for examples and lifetime rules. Offline tooling: resolve reports list event ID requirements and missing IDs (MAINTAINING.md); event on does not override the runtime checks above. enroll --source <script folder> reads a Lua script.json into the existing status board, preserving the feature/status fields used by ASI mods (ENROLLMENT.md).

Offline actor native contracts

These are game function IDs, not additions to the CDAL/BSX C ABI. Check ownership, lock, and thread rules before calling them. Read the actor guide before calling them. All use Windows x64 calling convention.

ID Register and stack arguments Return and ownership
304 ClientActorManager::FindActorScope RCX manager, RDX writable 0x20-byte scope aligned to 8, R8D full key; no stack args RAX=out; +8 actor, +0x10 valid, +0x11 mode. Owns a reference when valid; does not lock actor fields. Pair with 305 even on failed lookup.
305 ClientActorScope::Release RCX constructed scope; no other args No usable return. Releases reference, can destroy actor, clears validity; stale +8 is not usable. Never release a copied scope.
310 CommonTransformSyncActorComponent::GetPackedPosition RCX component, RDX writable 16-byte output; no stack args RAX=out. Three floats then signed int16 cellX/cellZ. Caller holds actor read lock; world X/Z add 1000 times cell.
318 ServerTransformSyncActorComponent::TeleportWithDescriptor RCX server component, RDX int32 error output, R8 native descriptor, R9B notify flag; entry stack+0x28 flag5, +0x30 flag6 RAX=error output. Native mutation/validation/notifications; requires server/TLS context. Descriptor layout and auxiliary ownership differ or remain incomplete. Mapping anchor only, not a ready teleport API.
319 ReadLockScope::Acquire RCX writable eight-byte scope, RDX native lock pointer; no stack args RAX=out. Actor lock pointer is [actor+8]. Release once through lock vfunc+0x20 with RCX=lock, DL=1, on the same thread before actor-scope release. No script calls/yields while held.

ID 134 Transform::Get takes RCX source snapshot and RDX output, returns output, and writes 0x28 bytes. Native callers snapshot 0x78 bytes including relative-frame state; a 0x2C-byte source is insufficient. IDs 300-303 describe only the client registry. IDs 314-317 describe partial status fields, not general hostility or alive/dead functions.

Files on a player's PC

bin64/
  CrimsonDesert.exe
  cdal.dll                 installed once by the player, never shipped by a mod
  CDAL/
    *.cdal                 databases, one per game build
    hooks.log              one line per game start (session start: ...), then every hook placed through
                           CDAL, its owner and chain; refused hooks and why; one line per note written;
                           session end: ... when the game closes itself (also CDAL's own hooks on
                           TerminateProcess and NtTerminateProcess, owner CDAL, which record that)
    hooks.old.log          the previous hooks.log, moved aside at a game start when it was over 1 MB
    session.json           this game run as data: state, hooks, refusals, the modules behind them
                           (docs/reference/FORMAT.md, "Session record")
    session-prev.json      the run before
    crash-<time>-<pid>.txt crash notes, the 5 newest; create crash-notes.off here to switch them off
    hang-<time>-<pid>.txt  hang notes, when the game's window stopped answering for 60 s; the 5 newest;
                           create hang-notes.off here to switch them off
    exit-<time>-<pid>.txt  exit notes, when the game closed without a crash and a mod was the
                           nearest caller of ExitProcess or TerminateProcess; the 5 newest
    runs/<start>-<pid>/    past runs, kept at the next game start: the run's session.json, its notes,
                           its part of hooks.log, its bsx.log, the hashes of the code it ran (binaries.json)
                           and how it ended (run.json). The 5 newest, and the 3 newest that went wrong
                           (docs/reference/FORMAT.md, "Run history")
    backup/<version>/      the updater's copy of the release before; never loaded
  BSX.asi, BSX/plugins/    only with BSX
  YourMod.asi              loaded by Ultimate ASI Loader (winmm.dll or similar)

BSX Lua modules

Guarded reads cache up to 64 validated regions per protected Lua callback, with SEH on every copy and no retained game bytes. Errors, timeouts and normal returns discard the cache; writes still query protections afresh. Keep large diagnostic groups on separate bsx.after(0, ...) steps as in smoke; see guarded reads and the time limit. No Lua signature or permission changes.

Lua API 3 retains the typed HP change interface, gated by changes: true and player-approved per-folder SHA-256 in BSX.Lua.dll.ini. For every API-3+ script game.stats is a callable table with .read; approval additionally exposes .add(stat_id, delta). API-2 scripts keep the original function. By default ([Lua] ServerCommands=0, and for lua_api: 3), valid requests return nil, "stat request semantics and FRAME calling context are not verified" before reading game pointers or calling the clock/ID 10 ([Lua] ServerCommands=1 in Lua API 4-8 enables server-queued stat/inventory/world mutations; see Lua API 4-8, BSX services & DevBridge v1). Permission, unload, FRAME-thread and argument checks remain: numeric stat 0, nonzero integral delta in [-1000000, 1000000]. Without ServerCommands=1 in API 4-8, this is a refusal, not a successful mutation or a script fault; reads/events keep running. The internal diagnostic leaf records exception code, phase, module+RVA, access type/address and thread ID, then poisons the script and closes it after the protected Lua callback. No raw writes or FFI are exposed in the Changes tier; API 1/2 are unchanged.

The optional Lua host requires BSX API 2 including its appended helpers, checked by interface size and non-null pointers. A script's manifest lua_api is 1 through 8; 2 adds cdal.value and player/equipment/stats, 3 adds game.inventory, and 4 through 8 add the modules, composable hooks, tables, combat primitives, and events described in Lua API 4-8, BSX services & DevBridge v1 below. BSX Lua 0.4.0 supports up to lua_api: 8; hosts older than 0.3 refuse API-3+ scripts, and API-2 scripts keep the original three-member game table. Safe/changes scripts have no raw writes, arbitrary native calls or FFI. The typed HP helper requires the separate change approval described above.

Native Lua API 3: native: true requires independent [Native] <folder>=1 and [Native.SHA256] <folder>=<static-file digest> approval. Missing/stale approval yields off: native tier not approved in BSX.Lua.dll.ini; running status/logs say native: safety promises off. It uses the changes snapshot/hash format. File notifications stop the old state before queued work; native code never falls back to read-only. FFI is full process trust. Native scripts run interpreted so recoverable SEH faults reach the host boundary; per-state Lua memory and callback limits remain, but cannot cap external allocations or interrupt stalled native code. Finalizers are deferred out of GC under that deadline and skipped during teardown. Native scripts also get hook rules:

local r, why = cdal.rule(name, {          -- name must be in needs_ids
    expect = "C5 FA 11 83 ?? 01 00 00",     -- optional: original bytes at the ID, ?? = any
    enabled = false,                        -- optional: install paused until r:enable(true)
    when = { {operand, cmp, value}, ... },  -- 0..32 checks; cmp == ~= != < <= > >= contains excludes absent present
    set  = { {operand, op, value}, ... },   -- 1..32 changes; op set add sub mul div min max and or xor sqrt cas, or a comparison (check step)
    jump = 6,                               -- optional: then continue at the ID + 6 bytes
    after = true,                           -- optional, func IDs: run when the function returns
    before = { {operand, op, value}, ... }, -- optional with after: run at entry; set runs at return, sharing %0..%7
    context = true,                         -- optional with after: other rules see this call as %%0..%%7 and depth
    buffer = true,                          -- optional with context: a zeroed 0x800-byte buf[...] per call
    unwind = true,                          -- optional with an entry phase: the return phase also runs on an exception
    stop_on_failure = true,                 -- optional: a change that fails skips the later ones
    each = { list = operand, count = operand, -- optional: or ["end"] = operand; walk a list before set
             stride = bytes, max = n,         -- stride 1..65536, max 1..1024 elements
             set = { ... } },                 -- per element; @ = element address; false check step = next element
})                                          -- or { ret = {register, value} } on a func ID
-- r:set(i, v), r:when(i, v), r:enable(bool), r:hits(), r:active(), r:remove()
-- cdal.cell(i [, type]), cdal.set_cell(i, value [, type]): the script's cells $0..$15
-- cdal.table_keep(t, keep): keyed table #t refuses new keys when full instead of replacing rows
-- cdal.table_rows(t, n): table #t uses only n (1..64) rows; only before any rule has used it
-- cdal.tick(['ms'|'us']): the rules' tick (ms) or tick_us (us) clock now, real time
-- cdal.clock_rate([factor]): the game's own clock reads run factor (0.1..100) times as fast; no arg = current

Operands: rax..r15, eax..r15d, 16/8-bit parts (no ah..dh), :u suffix for unsigned, xmmN.f32/xmmN.f64 lane 0 or a chosen lane (xmmN.f32[0..3], xmmN.f64[0..1]), memory [reg+off].u8..f64 and chains up to three levels such as [[rcx+0x68]+0x40].f32 (guarded read; unreadable is false or skipped; writes only to committed, writable, non-executable pages under SEH), the script's 16 shared cells $0..$15 with an optional type ($3.f32, default i64; zero on each load), and read-only rsp, tick (GetTickCount64 milliseconds) and tick_us (QueryPerformanceCounter microseconds). A value that is text not starting with a digit or - names an operand read on each call ({"xmm0.f32","set","xmm1.f32"}); such entries refuse r:set/r:when. and/or/xor take integers only. Per-call temporaries %0..%7 (zeroed each call), address operands &[...] (read-only), and .str/.strN memory operands for contains/excludes (1-32 literal bytes; reads at most 256 or N (1-256) bytes; contains is true once found, excludes needs a NUL within that length). {op, "cas", new, expected} is an atomic compare-exchange on aligned writable u32/u64 memory; a mismatch writes nothing and is a failed change. div by zero leaves the target unchanged. after = true (func IDs; not with ret/jump) hooks the function with a generated CDAL function-hook thunk that forwards all register arguments and 16 stack slots, then applies the rule with entry rcx/rdx/r8/r9/xmm1-3/rsp and result rax/xmm0; only rax-family, xmm0, memory, cells and temporaries may be changed. before (with after) runs at entry after the when checks (no rax there) and may change rcx/rdx/r8/r9/xmm0-3, memory (including stack arguments), cells and temporaries; the thunk forwards the changed arguments, and set runs at return for each call that passed the entry checks, even if the rule was paused meanwhile; a failed before change or false before check step skips the rest of before and that call's set (earlier before changes stay). After rules may name only rcx/rdx/r8/r9/xmm0-3/rsp (plus rax/xmm0 results in set), including as memory bases and table keys; others are refused at creation. Stack slots are copied up to the thread's stack base before before runs, and [rsp+0x28]..[rsp+0xA0] name that private copy (the caller's stack is never changed; offsets outside [rsp+0]..[rsp+0xA0] are refused; functions with more than 20 arguments are unsupported); the thunk has registered unwind data, and a call left by an exception skips set. Overlapping calls on different threads are not synchronized; at most 32 operations in before and set together, numbered before first for r:set. stop_on_failure = true stops at the first change that fails (unreadable/unwritable address, division by zero, non-finite result, sqrt of a negative value), and then also skips jump/ret. Keyed tables #0..#3 (#T[key].F[.type], key a 64-bit register or cell/temp/thread cell, field 0-3): 64 rows each, absent key reads fail, two-entry {"#T[key].F", "absent"|"present"} checks row existence under the table lock (fixed at creation; r:when refuses them), set creates a row (others zero) replacing the least recently used, try-lock per table (busy fails, never waits), empty on load. Thread cells ^0..^7 (typed like $N) are per script and per game thread, zero until written on that thread, kept between calls; a thread holds blocks for 4 scripts and replaces the least recently used (zeroed) for a fifth; not readable from Lua. An operation entry whose middle is a comparison is a check step that stops the remaining operations, and the rule's jump/ret, unless it holds (shares the 32 condition slots with when; r:set refuses it). sqrt (float targets only) sets the square root of the value. each walks at most max elements of stride bytes from the whole-number operand list (count from count, or from the end address); its set runs per element with read-only @ as the element address ([@+off], &[@+off], a table key), a false check step skips to the next element, temporaries carry over between elements, and a failed change under stop_on_failure stops the walk, the rest of set and jump/ret; a null list walks nothing; @ is refused outside each; the walk runs before the rule's set (at return in after rules) and its operations count toward the 32. context = true (with after) links every call of the rule into a thread-local list through its AfterFrame (no capacity limit) from entry to return, also unlinked by the thunk's unwind handler on an exception, and marks it when when (and before) pass; the script's other rules on that thread read and write the innermost call's temporaries as %%0..%%7 and read depth (marked calls of the script); when the script's innermost linked call is unmarked (paused, when false, before failed) %%N, buf and depth fail instead of reaching an outer call, and depth also fails past 64 linked calls. Contexts are per OS thread, not per fiber. each = {..., entry = true} (with after) walks at entry after before; a stopped walk does not cancel the return phase. unwind = true (with after and before, context or an entry walk) runs the return phase when an exception unwinds through a matched call, with no result (rax/xmm0 refused in that phase); the handler ignores the thunk before it stores its frame (after_marker_ready). A when presence check whose table is written in the return phase is refused (claims must be checked and written in one phase). {"#T[key].F", "remove"} deletes a row (no float field type); cdal.table_keep(T, true) makes a full table refuse new keys (a failed change) instead of evicting; a present probe refreshes the row's age. {place, "copy16", place} copies 16 bytes between memory and buf[...] with one 16-byte store (source read separately); places are untyped, and in an after rule a direct stack place must fit 16 bytes ([rsp+0x98] is the last). A claim written in before with an argument-register key may be changed or removed at return. each over buf is clamped to the buffer and each [@+off] access must end inside it. Table keys and buffer indexes take no type suffix. buffer = true (with context) gives each call a zeroed 0x800-byte buffer: buf[OFF].type (OFF a constant, or a slot plus a constant; out of range fails) and read-only buf (its address), for the innermost marked call. Thunk pages and rule blocks live for the process lifetime. jump (nonzero, not with ret) sets RIP to the ID's address plus the offset after the changes; it must land on an instruction boundary. Integers saturate; mul truncates toward zero; NaN/inf floats are left unchanged. expect (1-32 hex pairs, first byte fixed) is compared with cdal_read_original at the ID's address before hooking; a mismatch returns nil and a reason that lists the expected and found bytes. Failures return nil, reason. At most 32 rules per script. No Lua callback hook API is supplied.

Native-only Lua function Contract
ffi, require("ffi"), require("bit") LuaJIT FFI and bit modules. require accepts only these two names. Safe/changes scripts still have no ffi/require.
cdal.address(name), pack:address(site) Native scripts receive lightuserdata usable with ffi.cast; manifest allowlists and nil, reason failures remain. Other tiers and read-only game helpers keep numeric addresses.
mem.cas_u32/cas_u64(address, expected, new) true, false, found (u64 as decimal text) or nil, reason; native permission, bound FRAME thread, aligned committed writable non-executable memory, then one interlocked compare-exchange under SEH.
mem.write_u8/u16/u32/u64/f32/ptr(address, value) true or nil, reason; native permission, bound FRAME thread, committed writable non-executable pages, then an SEH-wrapped copy. Numbers must be exact/in range; u64/ptr additionally accept unsigned decimal text, ptr accepts CDAL lightuserdata, f32 requires finite range. Address accepts exact numbers or CDAL lightuserdata.
cdal.patch(name, bytes) Declared ID name, binary string of 1–4096 bytes; at most 128 patches. Returns true or nil, reason from CDAL's shared Patch manager, owner=manifest name, priority=0. Host-owned handles restore on stop/fault/reload. Requires hooks in the CDAL runtime.
Lua function Contract
cdal.address(name) Exact numeric address (native tier: lightuserdata) or nil, reason. Name must be in this script's needs_ids; refusal happens before cdal_id_by_name/cdal_address. Offset IDs have no address.
cdal.status(name) Same allowlist; returns verified, resolved, scanned, or the unavailable-address reason. Undeclared names return nil, reason.
cdal.pack(path) Only an exact relative file listed in packs. Returns a query table with :address(site) and :status(site) or nil, reason. The native adapter consumes checked compiled .cdal bytes with cdal_pack_open, copies results and closes the handle. Source pack.json is not loadable. No pack writes or native handles.
config.int/float/bool/string(section, key, default) Also bsx.config. Reads the script's optional settings.ini snapshot, refreshed on reload. Missing/malformed values use typed defaults (0, 0, false, "" when omitted). INI spelling/limits are in the module reference.
cdal.value(name) (lua_api 2) An offset ID's value as a number, or nil, reason. Same needs_ids allowlist.
game.player(), game.equipment(actor), game.stats(actor) (lua_api 2) Read-only pointer walks: the controlled actor (IDs 1, 193, 194); its equipment component (195, 196, checked against vtable 61 pa::ClientEquipSlotActorComponent::vftable); its stat container (195, 197, 198). Every walked ID must be in needs_ids. Returns an address or nil, reason naming the ID or member that failed.
game.item_name(row), game.item_info(row) (lua_api 3) Cached internal name or {row,key,name,max_stack,max_durability,category_row,item_type}. Row ordinal 0..65534; name at most 256 bytes; max_stack is a decimal string. Require IDs 92/93/94, plus 267/268/269/272 for item_info. No localized display name or lazy loading.
game.stat_name(id) (lua_api 3) Cached internal StatusInfo name with key verification, key 0..65534 and 256-byte bound. Require StatusInfo::sTable (291).
game.time(), game.weather() (lua_api 3) Raw client {day,hour,minute,second,millisecond} (ID 225), or unattenuated {rain_base,snow_base} (IDs 1/331/332). Guarded observations with an exact database and stored requirements, not atomic snapshots or native getter results.
game.player_position() (lua_api 3) Safe copied {x,y,z, yaw_deg?} world observation from the controlled actor's transform, including inline relative scale/rotation/origin and signed sectors. Declare IDs 1/193/194/82/6/195/309/64/311/510/511 by their names in the read table. Exact-build gate, guarded double copies, owner/vtable/path checks, nil, reason on failure; no native scope/lock calls.
game.camera_position() (lua_api 3) Safe copied {x,y,z} from the renderer's active-camera world cache. Declare IDs 1/193/194/82/6/512/513/514 by name. Requires a controlled player, unchanged renderer/vptr/active reference and equal finite XYZ copies; exact-build gate. The cache may be stale across a camera switch. No origin addition or native calls. Both position helpers are observations, not atomic snapshots. See Player and camera positions.
game.actors(max), game.position(actor), game.stats.read(actor,stat_id), game.in_cutscene() (lua_api 3) Served by [Lua] SnapshotProvider=1 (default) on WORLD_READY, or return nil, reason when SnapshotProvider=0. First three require scope IDs 304/305/319; cutscene requires 334. Validate max 1..256 (default 64), exact positive actor addresses and stat keys 0..65534. See the module reference.
game.inventory.count(item_id) (lua_api 3) Exact row 0–65534 in the controlled actor's own holder; decimal-string sum of positive stacks, "0" if absent, or nil, reason. Requires IDs 1, 193, 194, 195, 91 and 205-209, 264, 265, declared by name. Guarded reads only, 256 buckets/4,096 total slots maximum; fails on bad reads, layouts, overflow or detected list changes. Does not reproduce native owner redirection, ItemInfo grouping, storage selection or exclusions. See the reference.
game.inventory.list(limit), game.equipment_snapshot() (lua_api 3) Read-only copied arrays or nil, reason, without Changes approval. Inventory records contain external bucket, zero-based index, row, decimal count, optional decimal instance_id; equipment substitutes actor-relative slot_tag for bucket and its index is an equipment-array ordinal. Array metadata: actor_key, opaque per-script generation, truncated. Limit defaults to 256 (1–4096); at most 256 buckets/4096 inventory slots or 256 equipment records. Declare all snapshot requirements, including offsets 540/541. Owned-player guards, two copied passes and lifecycle invalidation detect changes; they do not supply atomicity or persistent identity. Console refuses. The outfits demo revalidates before each existing request and waits for controlled APPLIED plus copied state; no uncertain-send retries or storage access.
bsx.api_version, bsx.lua_api Numeric running BSX interface version and this script's selected Lua API. Added in BSX Lua 0.3 for all supported Lua APIs; older hosts do not expose these fields.
mem.read_u8/u32/u64/f32/ptr(address) Also bsx.mem. Page-checked and SEH-guarded reads; failure returns nil, reason. Addresses/pointers are exact numbers in 0..2^53-1; native scripts may also pass CDAL lightuserdata. read_u64 returns a decimal string to preserve all 64 bits. Safe/changes scripts have no write functions.

Put options in BSX/plugins/BSX.Lua.dll.ini, section [Lua]: TimeBudgetMs=50 (1–2,000), MaxScriptMemoryMB=64 (1–64), HotReload=1 (0/1). The host reads these through BSX config_int; invalid values use defaults. BSX snapshots these once at plugin startup.

bsx.after(ms, fn) retains its millisecond contract. Due timers queue through BSX defer and run on a later FRAME after reload checks and events. Stop/reload cancels queued timers and copied events as well as native subscriptions. The host uses distinct per-script callbacks because unsubscribe(self, event, fn) ignores user. The host's own FRAME subscription remains active for discovery/reload. ReadDirectoryChangesW notifications are debounced for 300 ms, ignoring data/; optional on_unload() runs protected before teardown. Reload revalidates all requirements; a failed script stays off until another edit.

set_status publishes the first off script/reason and aggregate counts; detailed errors go to the log. Native get_service("BSX.Lua/1") returns the borrowed process-lifetime bsx_lua_service_v1: check struct_size and api_version == 1, then call status(char* out, size_t capacity) from any thread. It returns required bytes including NUL, permits NULL, 0, and terminates truncated output. This service cannot invoke Lua.

Generate editor-only bsx/lua/ids.lua from docs/reference/ids.json with python -B bsx/lua/generate_ids.py. It contains active names and completion annotations, no numeric IDs/addresses; the host never loads it. Use the module examples as starting patterns.

Lua API 4–8, BSX services & DevBridge v1

  • Manifest lua_api 4–8 and data_only: script.json accepts "lua_api": 1..8. Scripts with "data_only": true run from tweaks.json ("schema_version": 2, 3, 4, or 5) without main.lua, applying reversible items (max_stack, max_durability, v3 cooldown_ms), stores/buffs/craft_tools overrides (v3), recipes (craft_tool_row, required_knowledge_row, apply_enchant_level, material_count_scale in v4), gameplay scalars/toggles (including v3 item_cooldown_scale/loot_drop_scale, v4 wind_scale/trails_enabled/parry_range_scale/conquest_gauge_scale/ignore_wanted_surcharge/fishing & mount/minigame/boss-rush controls, and v5 attack_speed_scale/move_speed_stat_scale/action_speed_scale/knockback_scale/life_steal/groggy_scale/hp_regen_scale/stamina_regen_scale/mp_regen_scale/no_fall_damage/day_speed/fast_travel_anywhere/resolution_scale), and composable hooks entries (zero_code_balance_pack).
  • JSON, sandboxed FS, UI v5, Draw v4, Textures v1, Audio & Tween (lua_api: 4+): bsx.json.encode/decode and bsx.fs.{exists,list,delete,mkdir} stay pinned inside each script's data/ directory (BSX/scripts/<folder>/data). "BSX.Lua.UI/5" (extending UI/4 with set_theme, categorized listbox, set_next_width, push_color/pop_color) raises panel caps to 32 panels / 128 widgets; "BSX.Lua.Draw/4" (bsx_lua_draw_service_v4, falling back to Draw/3/Draw/2/Draw/1) raises foreground primitives to 4096 (2048 per script) and adds triangle, image (paired with "BSX.Lua.Textures/1" up to 512x512 RGBA8), measure_text, world_line, world_circle, world_sphere, font family (default, sans, bold, impact, serif, mono), and native shadow/outline/heavy styles. bsx.audio (play, stop_all, master_volume, set_master_volume), bsx.tween (to, cancel_all), Safe-tier lua_api: 7+ bsx.every repeating timers, bsx.system (info, copy_text), and bsx.memory (info, async trim with a process-wide 30 s cooldown), gamepad events, and :stop()/:cancel() handle aliases run bounded on the FRAME thread.
  • Composable hooks (game.hooks) & interop (bsx.export, bsx.mods, bsx.bus): game.hooks.add(channel, opts) and tweaks.json compose ordered chains (acc = acc * mult + add, priority -1000..1000, highest wins) across 19 gameplay channels (on_damage with target="dealt"|"taken", on_stamina_cost, on_mp_cost, on_shop_price, on_craft_cost, on_gather_mult, on_parry_window, on_move_speed, on_jump_scale, on_skill_xp, on_durability_wear, API 6 on_item_cooldown / on_loot_drop, and API 7 on_catch_quantity, on_trap_chance, on_parry_range, on_wind, on_conquest_gauge, on_boss_rush_limit), overridable persistently via BSX/lua_overrides.ini. script.json "requires" orders startup topologically; bsx.export / bsx.mods.get share plain-data functions across states and bsx.bus handles pub/sub + FRAME provide/call (INTEROP.md).
  • Lua API 5 helpers & events: plugins_loaded, equip_applied, unequip_applied, zone_changed, weather_changed, game.tweaks (set_item/revert_item/set_gameplay/revert_gameplay/revert_all/list/gameplay_list, auto-reverting on stop/reload), game.items.find, game.item_is_dyeable, game.input.block_flags / auto-reverting game.input.set_capture, game.actors.nearby / screen_bounds, game.camera.unproject_ray, game.appearance.export_preset / apply_preset, enriched game.player_state() flags (in_town, in_safe_zone, in_battle, in_cutscene, character_name, display_name), and config.set/config.save (bsx.lua).
  • Lua API 6–8 tables, live readers, combat primitives, reactive events & safety boundaries: API 6 adds paginated .find(query, limit, cursor) and .info(row) over game.characters, game.skills, game.buffs, game.quests, game.stores, and game.craft_tools, their game.tweaks setters, live readers game.buffs.active(actor_key?), game.quests.status(id)/active(include_completed?), game.factions.agreement(a, b), game.skills.sublevel(key)/sublevels(), game.appearance.equipped_dyes()/visual_items(), and game.gameplay.{item_cooldown_scale,set_item_cooldown_scale,loot_drop_scale,set_loot_drop_scale}. API 7 adds game.recipes.{find,info}, game.tweaks.{set_recipe,revert_recipe,recipe_list}, 11 passive events (fishing_result, loot_pickup, skill_learned, skill_reset, pet_summoned, quest_dialogue, journal_unlocked, minigame_record, boss_rush_event, combat_damage, and Safe-tier weapon_draw), game.pets.observed(), game.actors.has_aggro, game.skills.{max_level,set_max_level,learn,reset}, game.world.{wind_scale,set_wind_scale,trails_enabled,set_trails_enabled}, [Lua] SnapshotProvider=1-gated game.world.raycast_segment/raycast_dir, game.gameplay.{parry_range_scale,conquest_gauge_scale,ignore_wanted_surcharge}, game.appearance.{character_scale,dye_palettes,set_decoration,rebuild}, game.ui.close_panel, game.fishing.*, game.pets.*, game.mounts.*, game.minigames.*, game.interaction.auto_pickup, game.vfx v2 (client-side changes-approved + WORLD_READY without requiring ServerCommands=1, Safe-tier game.vfx.socket_transform(socket_name?, actor?), world/parent poses on vfx_handle:info(), plus spawn-time color, emissive, glow, opacity, spawn_count, particle_scale, lifetime via ID 695), and Safe-tier bsx.every, bsx.system, bsx.memory, bsx.ui.mouse(). API 8 adds game.combat overhaul controls (attack_speed_scale, move_speed_scale, action_speed_scale, hitstop, knockback_scale, life_steal, groggy_scale, set_stat_bonus, clear_stat_bonuses, stat_bonuses), game.stats.find_by_name, game.buffs.{has,apply,remove,clear} (plus uid), game.actors.{is_groggy,add_groggy,apply_impulse,stat}, game.gameplay.{hp_regen_scale,stamina_regen_scale,mp_regen_scale,no_fall_damage}, game.world.{day_speed,fast_travel_anywhere}, optional game.world.set_weather atmosphere overrides (fog, cloud_density, cloud_alpha, cloud_speed, cloud_thickness, sun_brightness, wetness, dust), game.render.resolution_scale, game.audio.* (Wwise SDK helpers), omitted/"" game.ui.close_panel(), and 6 reactive events (attack_hit, kill, just_action, groggy_changed, buff_applied, buff_removed). Clean omissions remaining unexposed: post-spawn vfx_handle:set_target (can_set_target = false), pure-GPU clock control (can_gpu_sync = false), native cheat spawner TrocTrSpawnCharacterCheatReq, and UI-thread AlertSystem::Slot146.
  • BSX C services (bsx/lua/service.h, bsx/world.h, bsx/ui.h): Standalone .asi mods can query public services from BSX.asi via bsx_get_service (bsx_get_service_fn in bsx/include/bsx/bsx.h); BSX plugins use api->get_service:
    • "BSX.World/1" (bsx/world.h): registered by BSX.Lua; FRAME and WORLD_READY-gated snapshot_player_state, snapshot_actors, snapshot_weather, and read_stat (requiring [Lua] SnapshotProvider=1) plus queue_stat_add, queue_inventory_add, queue_inventory_remove, queue_set_time, queue_set_weather, queue_reset_weather, and queue_teleport (requiring [Lua] ServerCommands=1 and an exact build match).
    • "BSX.Lua.Approval/2" (bsx_lua_approval_service_v2): lists pending scripts and missing capability flags (BSX_LUA_CAP_SERVER_COMMANDS, BSX_LUA_CAP_SNAPSHOT_PROVIDER, BSX_LUA_CAP_COSAVE, BSX_LUA_CAP_UNCHECKED_BUILD) and performs 1-click Changes + INI consent updates (approve_and_enable_caps; Native remains manual INI-only).
    • "BSX.Overlay.State/2" (bsx_overlay_state_service_v2), "BSX.Overlay.State/1", and "BSX.ExternalMenu.State/1" (bsx_overlay_state_service_v1): expose is_open() (plus is_ui_hovered() and mouse_state() on State/2) so game.input.set_capture releases automatically when menus open and bsx.ui.mouse() reports overlay-aware pointer state.
    • "BSX.Lua.Conflicts/1" (bsx_lua_conflicts_service_v1): exposes snapshot_json, set_hook_override, and clear_overrides for Overlay and DevBridge.
    • "BSX.Lua.Textures/1" (bsx_lua_textures_service_v1): copies decoded up to 512x512 RGBA8 image textures registered via bsx.draw.image(...) for overlay rendering.
    • "BSX.Lua.Toast/1" (bsx_lua_toast_service_v1): thread-safe bounded corner toast notifications; snapshot prunes expired entries and copies up to BSX_LUA_TOAST_MAX_ACTIVE (8) active toasts.
    • "BSX.Lua.Settings/1" (bsx_lua_settings_service_v1): thread-safe inspection and editing of a loaded script's optional settings.ini (list_entries up to 64 entries; set_entry updates or appends atomically while preserving comments).
  • DevBridge v1 (\\.\pipe\BSX.Lua.DevBridge.v1, [Lua] DevMode=1): JSON ops ping, eval, status, reload, inspect, item_search, table_search, event_spy, tweaks_preview, tweaks_revert, hooks_override, and approve_script all marshal onto the FRAME thread; CDAL Studio's MCP server exposes read-only inspect_game and search_items.

Native equipment contracts (IDs 280-285)

These are game-function ID contracts, not additions to the CDAL or BSX C ABI. Full ownership and completion limits are in the equipment guide and the catalog descriptions.

Windows x64 register order is RCX, RDX, R8, R9; the fifth and sixth arguments are at entry RSP+0x28 and RSP+0x30. The following signatures show argument order, not C++ declarations for complete game types:

ID Signature
34 int32_t* (Equipment*, int32_t* result, uint16_t bucket, uint16_t inventory_index, uint16_t tag)
35 int32_t* (Equipment*, int32_t* result, uint16_t tag)
101 int32_t* (Equipment*, int32_t* result, uint16_t tag_a, uint16_t tag_b)
106 int32_t* (Equipment*, int32_t* result, uint16_t tag_a, uint16_t row_a, uint16_t tag_b, uint16_t row_b)
280 int32_t* (Actor*, int32_t* result, const InventoryItemView*, uint16_t tag)
281 const void* (const SlotDefinitionGroup*, int16_t tag)
282 uint16_t (Equipment*, const uint32_t* name_key, int32_t occurrence)
283 int64_t* (StatContainer*, int64_t* out, uint16_t status_row, int64_t time)

IDs 280-283 have no stack arguments. ID 280 reads the view's row at +8 and inventory index at +0xCA; it does not accept a row value or a bare ItemRecord. ID 281 returns a shared default on an invalid tag. ID 282 takes a name-key pointer, not a string, and can return a fallback tag. ID 283 can write a fallback scalar without a separate failure flag; attack/defense keys and scaling remain unidentified. IDs 284/285 describe equipped-record stride/tag, separate from inventory stride and slot-definition layout.

For a helper, resolve a current owned inventory instance before requesting ID 34, reject stale/loading/non-controlled actors, and retain no borrowed record across mutation. Unequip can request fallback gear; swap requires two occupied tags and is not proven to be the combat weapon switch. IDs 187/188 observe later storage changes, including restoration; IDs 218/220 handle appearance. Do not assume thread affinity, reentrancy, or immediate gameplay completion from a native call return.

Overlay status and console services (optional preview)

The opted-in renderer preserves all native DXGI arguments/results even on cleanup failure, holds no chain/back-buffer references between Presents and retires same-HWND replacements. The private WindowInput/1 bridge appends an optional size-checked diagnostic snapshot; its filter prefix and the public BSX ABI are unchanged. Debug=1 includes HWND/focus, pre-filter keys, KEY/hotkey delivery and creation/resize lifetime results.

The overlay is an experimental preview that has crashed the game twice with Steam overlay present. It defaults off at runtime as well as at build time. Only [Overlay] Enabled=1 in BSX/plugins/BSX.Overlay.dll.ini opts in. The loader snapshot read occurs before scheduling; absent/0/invalid leaves one off log and no App, workers, subscriptions, hotkeys, WndProc, ReShade registration or hooks. This does not disable unrelated plugins or the independent status/console services.

These tables use existing BSX API-2 get_service; no bsx_interface field changes. Check a non-null pointer, struct_size >= sizeof(table) and api_version == 1 before calling. Reacquire before each operation; borrowed storage has process lifetime, but a disabled provider disappears from lookup.

  • BSX.Status/1, bsx/status.h: loader-owned, reserved name. count() returns the published plugin count; at(index, out) copies fixed UTF-8 file/name/version/state/reason/status fields and returns BSX_OK, BSX_E_ARGS for null output or BSX_E_NOT_FOUND for an absent index. Fields truncate with a NUL terminator. Calls are individually synchronized; count/rows are not an atomic snapshot during loading.
  • BSX.Lua.Console/1, service.h: scripts(context, out, capacity) and output(context, out, capacity) copy text, return required bytes including NUL, support null/zero queries and always terminate nonempty destinations. submit(context, text, length) returns 1 when queued, 0 for invalid/full input. Limit: eight pending chunks, 4096 bytes each, no embedded NUL. One chunk runs per FRAME in the isolated console. Output retains 32 KiB. Clients cannot grant changes permission. Only the Lua host's startup ini [Console] Changes=1 does so, preserving all native safety gates. The console never inherits native folder/hash approval and has no native-tier opt-in. FFI, raw writes and cdal.patch remain exclusive to approved scripts.
  • BSX.Overlay.UI/1, bsx/ui.h: registered by BSX.Overlay when [Overlay] Enabled=1. Thread-safe retained UI for native C/C++ plugins (create_panel, remove_panel, clear_panel, widget adders, set_text, set_value; up to 16 panels, 32 widgets/panel). Widget callbacks run on BSX_EVENT_FRAME via bsx->defer, never from Present/render threads.

The overlay implementation guide documents FRAME-side UI construction, the frozen internal widget vocabulary, ReShade's exact ImGui 19191 function table and GPU/input compatibility notes. After the opt-in snapshot read, overlay load only schedules work. DXGI export and object discovery runs outside the load caller, on a worker/on observed creation calls, with a 30-second independent deadline; timeout keeps the overlay off and partial hooks forwarding. It creates no dummy graphics objects and does not change these service contracts.

D3D12Core/ExecuteCommandLists hooks are omitted. Creation callbacks only retain successful outputs unchanged; worker inspection waits for a later FRAME, readiness requires a successful Present on the exact captured chain, and GPU setup waits for UI open. Debug capture includes the queue method's full module path without hooking it.

The overlay flicker/input follow-up adds [Overlay] Debug=1, submission-slot fences, queued raw-mouse/keyboard input and a software cursor. Loaded frame-generation providers do not disable rendering. Optional shared hooks on existing ID 76 and its configure target observe requests, separately from presents/FRAME evidence; FG on selects normal rendering with a warning. Descriptors and gameplay input gates remain untouched. These are private implementation details, with no service or public BSX ABI change. See diagnostics and limits.

World-state game contracts (IDs 320-334)

These are game addresses/offsets, not new CDAL exported functions or Lua APIs. The world-state guide contains the snapshot layout, full request arguments and ownership limits. DecodeProgressMilliseconds and EncodeProgressMilliseconds convert buffers using a nonuniform 75,600,000-unit day. RequestTimeChange has six ABI slots, including two stack arguments, and can queue native work. WeatherController::SetTriggerOverride has four arguments and copies a keyed five-float record; it uses a different owner from the intensity getters. ClientActor::GetCutsceneHandle takes an 8-byte output pointer and returns that pointer, not a bool.

Use the offset IDs for the frame-timer and render/weather layouts. Menu scale 1.0, timer mode and a cutscene handle are separate observations; none is a general world-ready or permission-to-mutate flag. Preserve TLS realm and native object/scoping behavior.

Native request contracts (IDs 335-349)

These game-function IDs do not change the CDAL/BSX C ABI. The request guide lists every register and stack argument, pointer depth, ownership and return contract. Sender 335 takes seven arguments and returns an output status pointer; dispatcher 340 takes six; receivers 342-345/347-348 take three; discard builder 346 takes six; simulation loop 349 takes five and must not be called by a plugin. Framework 336 is dereferenced once, manager root 338 twice. Lookup 339 returns a 0x20-byte native scope requiring ID 305 release and a separate read lock before actor-field access. Executor 341 consumes native-owned events, not callbacks.

Follow native client validation and distinguish queue acceptance, parsing/dispatch status and later mutation. The mode-1 allocation-failure path can execute immediately, while stat-input mode 0 uses dispatcher context. Keep Lua on its owning thread and validate context before invoking native request paths.

Combat native contracts (IDs 380-394)

Combat mapping lists the register/stack arguments, native results, writes, scopes, RVAs and event payloads for each ID. These are game-function addresses. HP ID 385 has eleven arguments and conditionally writes resulting HP, not damage; common death ID 386 has eight arguments and may repeat callbacks on already-dead input. Client death ID 387 has seven arguments. Check per-build callback-slot and layout offsets via CDAL IDs. The opt-in BSX adapter below uses a limited subset; these IDs alone never authorize a Lua mutation helper.

BSX combat observations (API 3)

BSX_EVENT_HIT=26, BSX_EVENT_DEATH=27, BSX_EVENT_REVIVE=28; KEY uses event 25. Require native plugin minimum API 3. [BSX] CombatEvents defaults on (installed only when a plugin subscribes); subscription returns unavailable with a log reason with CombatEvents=0, on an unsupported exact build, missing IDs or failed dependencies/hooks. HIT requires 381/306/319 and lifecycle IDs 33/41/39/37/199/200. Death and revive each require the same lifecycle/key/lock IDs plus both 387/391 and dead offset 317; both directions must be observed to rearm transition tracking.

Payloads are bsx_hit_event (attacker/target/skill keys), bsx_death_event (actor/raw source keys) and bsx_revive_event (actor key), each with size, shared uint64 sequence/generation and uint32 producer thread. They contain no pointers. Client detours queue after normal chain return; death/revive also require a zero native result and opposite sampled dead-byte states. All native and Lua subscribers run on FRAME, before ordinary FRAME subscribers. Queue capacity 256 and transition capacity 1024 are fixed; losses are logged. Loading/title boundaries cancel old epochs. Generation is local cancellation state, not WORLD_READY's identity.

Lua API 3 bsx.on('stat_change', fn) copies stat_id, decimal-string delta and source_kind; save_load_after, equip_after, unequip_after, load_request_after, weapon_swap_after, movie_after and battle_state_after copy their request fields plus result (opened for movies, current_stage for load requests). No pointer is copied; all are delivered on the next FRAME (table).

Lua bsx.on('hit'|'death'|'revive', fn) exposes uint32 *_key numbers, exact decimal-string sequence/generation and numeric producer_thread. Unknown attacker/source keys are omitted. Damage, combat flags and killer credit are omitted; no native BSX KILL/RESPAWN event (Lua API 8 separately exposes a reactive kill event; see above). Read the limitations and event notes before replacing a mod's existing callback.

Lua read-helper contract notes

Scope reads: when [Lua] SnapshotProvider=0 is set explicitly, game.actors/position/stats.read/in_cutscene refuse on exact checked builds after validating arguments and declared IDs ([Lua] SnapshotProvider=1, the default, serves them safely through the host snapshot provider on FRAME). Reasons distinguish missing bounded acquisition/lock phase, incomplete alive checks, lazy stat evaluation and cutscene dependency lifetime. See examples/where_am_i for a safe-tier diagnostic pattern. No new ID or C ABI field is added.

game.stat_name(id) accepts a compact StatusInfo cache ordinal, not its serialized u32 _key; the fields may differ. Definition reads require DefinitionTable::Capacity, DefinitionTable::CachedRows (or RowEntries/Row), and DefinitionRow::Key alongside their existing IDs. Weather also requires WeatherState::Resource, WeatherResource::Climate, Climate::RainBase and Climate::SnowBase. Declare these in needs_ids; do not infer offsets from an unresolved value. See the helper table. Smoke uses bounded game.item_info batches to find Money_Copper; no portable copper/silver/gold row numbers are established across builds.

game.item_name, game.item_info and game.stat_name additionally require DefinitionRow::InternalName (457) in needs_ids (even on builds where its valid resolved offset is 0; BSX Lua resolves DefinitionEntry::InternalName 6137 automatically when 457 is listed).

Lua client requests and native ID 415

Lua API 3 exposes game.request.equip(bucket, index, slot_tag) and game.request.unequip(slot_tag) only with manifest Changes and current folder/hash approval. Bucket is an external tag (0..65534), index and explicit slot tag are 0..32767. Both return true for exactly one expected accepted packet, or nil, reason; an uncertain result may follow an actual send, so do not blindly retry. Helpers require declared IDs, guarded controlled-player inputs and FRAME identity. Native approval alone and the console do not expose them. See required IDs, return semantics and example.

Native IDs 458 ActorEquipment::RequestUnequipItem and 459 Inventory::GetBucketForItemRow are documented in the request evidence. They add no C ABI fields.

ClientRequest::SendVaryStatByAccInput (415) has the native ABI void (Actor*, uint32_t reserved, const uint32_t* actor_key, const uint32_t* external_stat_key, const int64_t* accumulated_input). The fifth pointer is at entry RSP+0x28. It copies inputs but discards queue status and can skip sending; treat it as an observation anchor rather than a mutation API. See request pipeline notes.

Lua item-use request follow-up

Approved Lua API 3+ exposes game.request.use_item(external_bucket, index) -> true | nil, reason. It invokes the default-one path of ID 126 with amount 1, selector 0xFFFF and a four-byte auxiliary diagnostic. Preserve equip's approval, FRAME, declared-ID, controlled-player/inventory and sender-335 guards; true means exactly one expected accepted packet. Lua quick_slot_use_after copies event 22's scalars and signed result on FRAME; it confirms normal return, not consumption or attribution. No new ID or C ABI field. See the request pipeline notes and item-use requests.

Stored build contracts (C API 5)

int cdal_build_supports(uint32_t id, int require_checked) is appended to cdal.h. It returns 1 only for an initialized exact executable/database match and a stored resolved/verified ID (with an in-image RVA for address kinds). It never scans; a zero offset remains available. With nonzero require_checked, that ID must also be in the compiled database's checked-ID trailer. Old databases return false for this additional approval, not an error. cdal::Library::build_supports(id, require_checked) provides the same query. Existing APIs and bsx.h layouts retain their signatures.

BSX uses this query with cdal_build_matched() and ordinary require checks for layout consumers. After/combat adapters additionally require per-build prototype approval. The human build name is not a feature gate. See patch-day approval and format compatibility. This does not turn a resolved ID into permission to call it from Lua.

Build flags (C API 7)

uint32_t cdal_build_flags(void) returns the compiled database's header flags for the running game: CDAL_BUILD_HAS_VALUES (0x1), CDAL_BUILD_RUNTIME (0x2), CDAL_BUILD_CHECKED_IDS (0x4) and CDAL_BUILD_BSX_CHECKED (0x8). It returns 0 before a successful cdal_init() and when the database is not for this exact executable. CDAL_BUILD_BSX_CHECKED is set when the build file says bsx_checked (FORMAT.md); BSX turns its game events on only with it. cdal::Library::build_flags() gives the same in C++. A cdal.dll older than C API 7 has no such export, so find it with GetProcAddress and treat a missing export as 0.