Contract symbols
The host looks callbacks up by symbol name in the TCC build output (xsbase.h); every one is optional. The symbol names are the protocol — no registration functions, no base classes.
| Symbol | Protocol | Signature |
|---|---|---|
ServiceInit | all | void (XS_HostInfo*) |
ServiceUnit | all | void (XS_HostInfo*) |
ServiceSwap | all | bool (XS_HostInfo*, xvalue**) |
RequestProc | http | XS_RequestResult (XS_HttpReq*) |
WsOpen | ws | void (XS_HostInfo*, xwsstream*) |
WsText | ws | void (XS_HostInfo*, xwsstream*, xstrview) |
WsBinary | ws | void (XS_HostInfo*, xwsstream*, xbytesview) |
WsPing | ws | void (XS_HostInfo*, xwsstream*, xbytesview) |
WsPong | ws | void (XS_HostInfo*, xwsstream*, xbytesview) |
WsClose | ws | void (XS_HostInfo*, xwsstream*, uint16, xstrview) |
EventOpen | tcp | void (XS_HostInfo*, XS_StreamConn*) |
EventData | tcp | void (XS_HostInfo*, XS_StreamConn*, xnetbuf*) |
EventClose | tcp | void (XS_HostInfo*, XS_StreamConn*, xnetresult, const xerror*) |
EventDgram | udp | void (XS_HostInfo*, xnetudp*, const xnetudpmessage*) |
RequestProc returns a three-way result: XS_OK (responded, keep-alive continues) / XS_FALLBACK (drop to the static layer or 404) / XS_TAKEOVER (the application takes over the connection). Semantics in the guide · script contract. Full reference (signatures / timing / threading / examples) →
XServer layer APIs (23)
In-process direct linkage: implemented by the single-process host and resolved by address via tcc_add_symbol, no export decorations. Everything beyond these is an xrt or extension symbol. Full reference (signatures / ownership / examples) →
Topology queries
xsServerFind(name)
Find a server by its unique name. Returns a retained lease that must be paired with xsServerRelease
xsServerRetain / Release
Extend the life of a borrowed pointer (Retain before storing it inside a connection / enumeration callback)
xsHostFind(server, name)
Find a host by name within a server, protected jointly by that server's lease
xsEnumServers / xsEnumHosts
Enumeration callbacks; arguments are borrowed for the callback only — Retain to keep them
xsConfigRoot()
Returns the top-level Custom of xs.json (a retained xvalue*; call xrtValueRelease)
Hot reload
xsReloadHostSubmit(pHost)
Submit a host reload intent. Returns 0 = not accepted; a non-zero ID queries the final state
xsReloadServerSubmit(name)
Submit a server-level reload by name
xsReloadAllSubmit()
Batch transaction: all candidates pre-compile, failures roll back in reverse
xsReloadQuery(id, &result)
Query XS_ReloadResult{Id, State, Revision, Target, Message}
xsReloadHost / Server / All
bool compatibility wrappers: only tell whether Submit returned non-zero
Timers · deploy · handover
xsTimerAfter(owner, ms, proc, ud)
Life-cycle timer bound to the owner's generation — old-generation timers die with the swap
xsTimerCancel(id)
Cancel a timer
xsAppPath()
The application (executable) directory, UTF-8
xsExtensionEnabled()
Runtime probe: is an optional library compiled in (v1.0.0)
xsExtensionCount() / xsExtensionName()
Enumerate this variant's extension list (registry order, v1.0.0)
xsCreateTCC / xsDestroyTCC
A nested compiler preloaded with standard include / lib paths and symbol imports — the foundation of the application-level plugin system
xsSwapTake(pHost)
Valid only inside the new generation's ServiceInit: take the data exported by the old generation's ServiceSwap; ownership transfers to the application
xrt runtime (3,030 symbols indexed by domain)
Scripts see xrt in full: the public APIs of 91 modules are called by address through the symbol table, exactly like the host itself. Quick domain map (full prototypes in /xs/xrt_decl.h built into the VFS; cards link to the xrt API reference, or see our per-domain index page):
Networking core371+
xrtNet / Tcp / Udp / NetServer / NetStream — connections, listeners (SHARED / REUSE_PORT), datagrams, address resolution
TLS 1.2 / 1.3252+
xrtTls / Tls12 / Tls13 — handshakes, records, session resumption PSK / Ticket, mutual auth
Certificates / ASN.1123+
xrtX509 / Der / Pem — chain building and validation, name constraints, CRL, system trust stores
HTTP / 1.1149
xrtHttp / Http1 — parser (35 error codes), ResponseWrite, Chunk, BodyRead
WebSocket104
xrtWs — frames, streams, Upgrade, permessage-deflate, ref-counted reads and writes
Concurrency≈220
xrtCo / Channel / Task / Future / Executor / Thread — coroutines, Go-style channels, work-stealing thread pool
Dynamic values / JSON181
xrtValue 116 + Json / Xson 65 — objects / arrays / trees, serialization, queries
Strings / Unicode133
xrtStr / Utf8 / Utf16 / Utf32 — views, conversion, casing, validation
Regex / patterns91
xrtRegex / RegexSet / Pattern — NFA regex, batch pre-compiled routing patterns
Containers≈160
Array / List / Map / Set / AVL / Stack / Buffer / SlotMap
Files / paths118
xrtFile 45 / Path 38 / Dir 35 — sync and async IO, directory trees, path normalization
Memory≈90
xrtMem / Temp / Pool — allocation, temp allocators, pools, memory debug reports
Logging76
xrtLog — levels, formatting, multiple sinks
Templates32
xrtTemplate — compile / render, {$var} and {#foreach}
Process / system≈40
xrtProcess / Signal / Environment — child processes, signals, environment variables
Crypto / compression118+
SHA family, HMAC / HKDF / PBKDF2, AES, RSA / ECDSA / Ed25519; miniz compression
Domain counts aggregate prefix families (xrtTcp counts toward networking core); small domains not listed (Time / Atomic / Math / Random / Html / Codec …) make up the rest of the 3,030.
Extension · sqlite (272 symbols)
Compiled in by the build variant build.bat sqlite. The complete SQLite engine is linked statically into the host; scripts simply #include <sqlite3.h> (provided by the VFS), with FULLMUTEX mode for multiple workers. Full reference (connections / the five statement steps / transactions) →
/* Real usage from demo-single/modules/database.h */
iResult = sqlite3_open_v2(sDBFile, &G_DB,
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
(void)sqlite3_exec(G_DB, "CREATE TABLE IF NOT EXISTS ...", NULL, NULL, NULL);
sqlite3_prepare_v2(G_DB, sSQL, -1, & pStatement, NULL); /* prepared statement */
sqlite3_bind_text(pStatement, 1, sName, -1, SQLITE_TRANSIENT);
sqlite3_step(pStatement);
sqlite3_finalize(pStatement);
The exported surface is the full native SQLite API (open/exec/prepare/step/bind/finalize/backup/…, 272 symbols) — the five families and the five statement steps are detailed in the sqlite reference; the full walkthrough is chapter 32.
Extension · xtp2 (13 functions)
Compiled in by the build variant build.bat xtp. A binary application-layer protocol framing library over ordered byte streams: 32-byte header, REQUEST / RESPONSE / PUSH / EVENT message types, streaming incremental parsing, a complete limits system. libFuzzer-verified for round-trip consistency and the streaming state machine.
xtp2_config_init / create / destroy
Config (limits, allocator) → decoder creation and destruction
xtp2_feed / finish
Streaming incremental feed (consumed bytes and message via out-params); finish checks for half frames at EOF
xtp2_decode
Zero-allocation single-frame decode (complete buffer)
xtp2_measure / encode
Measure first, then write; the output buffer is untouched on error
xtp2_params / param_next / find
Parameter iteration and exact binary lookup
xtp2_error_string / reset
Error text; parse errors are sticky until reset
xtp2_processor* pRx;
if ( xtp2_create(NULL, &pRx) != XTP2_OK ) { ... }
/* Inside every TCP / TLS plaintext read loop: */
while ( iSize ) {
size_t iUsed;
xtp2_message tMsg;
xtp2_result r = xtp2_feed(pRx, pBytes, iSize, &iUsed, &tMsg);
pBytes += iUsed; iSize -= iUsed;
if ( r < 0 ) break; /* sticky error */
if ( r == XTP2_MESSAGE ) { ... } /* use/copy tMsg, then keep feeding */
if ( r == XTP2_MORE ) break; /* need more data, wait for the next round */
}
/* At EOF, xtp2_finish(pRx) checks for half frames, then xtp2_destroy */
Extension · xllm (68 functions)
Compiled in by the build variant build.bat xllm. The core library for calling LLM services (vendored from xrt extlibs, v3.0.0 core layer): one call, one API, three provider wire dialects (Chat Completions / OpenAI Responses / Anthropic Messages). Every runtime dependency — networking, TLS, JSON, cancellation — comes from the host's built-in full xrt; scripts just #include <xllm.h>.
xllmClientConfigInit / Create / Destroy
client configuration and lifecycle; borrow the host engine or let the library own one
xllmRequestInit / AddTextMessage / AddTool
request construction: text messages, multimodal parts, tool definitions and results
xllmCallFuture / Wait / Cancel
async calls: a borrowed future handle, blocking wait, cancellation through xrt
xllmClientComplete
the one-shot synchronous entry: retries, rate-limit respect and SSE streaming callbacks inside
xllmModelProfileBuiltin / Supports
built-in model profiles (the GLM family) with capability/limit checks
xllmEstimateTextTokens
offline token estimation for conversation budgeting
xllm_client_config tConf;
xllm_client* pClient;
xllm_request tReq;
xllm_response* pResp = NULL;
xllm_error tErr;
xllmClientConfigInit(&tConf);
tConf.sBaseUrl = "https://open.bigmodel.cn/api/paas/v4";
tConf.sApiKey = sKey; /* borrowed pointer, not copied */
tConf.sModel = "glm-5.2";
tConf.eProvider = XLLM_PROVIDER_GLM;
pClient = xllmClientCreate(&tConf, &tErr); /* owns its engine by default */
xllmRequestInit(&tReq);
xllmRequestAddTextMessage(&tReq, XLLM_ROLE_USER, "Describe XServer in one sentence");
if ( xllmClientComplete(pClient, &tReq, NULL, &pResp, &tErr) == XLLM_RESULT_OK ) {
/* read text blocks / finish reason / usage, then xllmResponseDestroy(pResp) */
}
xllmRequestUnit(&tReq);
xllmClientDestroy(pClient);
Extension · the mail family (283 functions)
Compiled in by build.bat xsmtp (or xpop3 / ximap — xmail comes along automatically). xmail is the MIME base: codecs (QP/Base64), charsets, address and date parsing, parameters and multipart, the message tree, builders and wire format; the three protocol clients share its transport and SASL. TLS comes from the host xrt. #include <xsmtp.h> resolves the whole family.
xrtMailTreeParse / Compose
MIME message-tree parsing and one-step composition
xrtSmtpClientMail / Data / Bdat
SMTP sessions: MAIL/RCPT/DATA and BDAT chunks, STARTTLS/SSL
xrtPop3ClientStat / RetrTree
POP3: STAT/LIST/UIDL, Retr straight to the message tree
xrtImapClientBeginFetch / Idle
IMAP: select/search/fetch/APPEND/IDLE push/COMPRESS
shared SASL
PLAIN / XOAUTH2 / OAUTHBEARER across all three protocols
the xrtMailBuilder family
streaming multipart construction, zero intermediate copies
Extension · md4c (2 functions)
Compiled in by build.bat md4c. CommonMark Markdown parsing and HTML rendering: md_parse is a callback event stream (blocks and spans entering/leaving, text chunks); md_html renders in one step on top; tables, strikethrough and task lists come via flags. Self-contained headers, no link dependencies. Note: callback pointers are unchecked — drive md_parse with a complete callback structure, or use md_html which carries its own.
void sink(const MD_CHAR* p, MD_SIZE n, void* u) { buf_append(u, p, n); }
md_html(sMarkdown, iLen, sink, &tBuf, MD_DIALECT_GFM, 0);
Extension · xacme (20 functions)
Compiled in by build.bat xacme. An ACME (RFC 8555) certificate client: account registration, order, dns-01 challenge and certificate fetch in one stop (xacmeClientIssue); xacmeClientIssueStored composes disk storage into "renew only when the remaining lifetime is short". The Aliyun DNS provider is built in; custom providers plug in as plain structs. Own synchronous HTTPS transport and TXT propagation probing — depends only on the host xrt.
xacmeClientInit / Issue / IssueStored
the issuance main path; Stored composes storage and renewal
xrtAcmeDnsAli / ProviderValidate
DNS provider construction and validation (Aliyun built in)
xrtAcmeStoreSaveCert / NeedRenew
certificate/account persistence and renewal checks
xrtAcmeAccountConfigInit
account config and CA presets (LE/ZeroSSL/Google/Buypass)
Extension · qrcodegen (10 functions)
Compiled in by build.bat qrcodegen. QR Code generator (Nayuki, MIT) plus a PNG output layer: 9 upstream functions (three encode entries Text/Binary/Segments, numeric/alphanumeric mode detection, buffer sizing, matrix reads getSize/getModule) plus qrcodegen_png for one-step 1-bit grayscale PNG (IDAT compressed via the xrt zlib stream, CRC32 local). Typical uses: 2FA provisioning (otpauth:// URI to QR), dynamic payment codes, a GET /qr?text=... endpoint, QR embedded in mail (with xsmtp).
qrcodegen_encodeText / Binary / Segments
three encode entries; caller provides module and temp buffers
qrcodegen_png
one-step PNG output (scale/border/quiet zone); free with xrtFree
qrcodegen_getSize / getModule
module-matrix reads (for custom renderers)
qrcodegen_isNumeric / isAlphanumeric
mode detection (optimal compression hints)
Extension · xjwt (24 functions)
Compiled in by build.bat xjwt. JWT (RFC 7519) / JWS (RFC 7515) signing and verification: HS256/384/512, RS256/384/512 (PKCS#8/PKCS#1 private keys), ES256 (DER encoding, two-way OpenSSL interop); JWKS (RFC 7517) kid-strict key selection; a public-key cache trio for high-frequency verification. Claims travel as xvalue* (zero bridging in the script layer), errors read in one line via xjwtLastError(), aud accepts strings and arrays. Four audit rounds incl. OpenSSL interop, fuzz and steady-state zero-leak measurement.
xjwtSign / one-shot trio
config-style iss/aud/sub/jti/kid injection; seven one-shot signers
xjwtVerify / xjwtVerifyKey
one-step verify (exp/nbf/iss/aud + signature); cached-key variant skips PEM parsing
xjwtJwksParse / xjwtVerifyJwks
third-party IdP key sets with kid selection (rotation-retry signal)
xjwtClaimString / xjwtLastError
safe string-claim extraction; one-line domain error codes
Extension · xoauth2 (25 functions)
Compiled in by build.bat xoauth2. OAuth 2.0 (RFC 6749) client: authorization-code flow + PKCE (RFC 7636) + token refresh + five provider presets (GitHub/Google/WeChat/Microsoft/Custom); OIDC helpers (one-shot nonce burn, HttpGet for JWKS, GetUserInfo). Transport is injected via xoauth2httpproc (mocks drive the whole flow offline); an xrt net/tls/http1 convenience implementation is included (stack and heap variants). Four-level error codes map straight to HTTP semantics. Data-couples with xjwt — zero linkage dependency: an OIDC login composes from eight lines of glue, no requires needed.
xoauth2BeginLogin / CompleteLogin
authorize URL (state+PKCE+nonce) → code exchange (constant-time state burn)
xoauth2Refresh / TokenExpiring
refresh and expiry checks (unknown lifetime ≠ expiring)
xoauth2HttpGet / NonceConsume / GetUserInfo
the OIDC data-coupling layer: fetch JWKS, consume nonce, userinfo
xoauth2HttpXrt quintet
xrt TLS convenience transport (stack + heap); or inject your own HTTP callback
Extension · xwork (42 functions)
Compiled in by build.bat xwork (auto-pulls xllm + xllm-session). The AI-stack capstone (v2.3.1): agent orchestration, tool registration & execution (built-in read/write set), workspace policy, subagent types, notification stream and compaction scheduling. release/agent-demo/ is the four-library production proof — approval gates and execution trails verified in-browser.
xworkAgentConfigInit / Create / Destroy
lifecycle: config (workspace/mode/budget) → handle → free
xworkAgentRunBegin / Run / RunEnd
three-phase turn: begin → drive (model+tool loop) → end
xworkAgentRegisterTool / RegisterBuiltinTools
tool registration (custom schema or built-ins; hot-update safe)
xworkAgentTakeTaskNotices
batch task notices — data source for approval UIs and trails
Extension · webview (2 functions) + app node
Compiled in by build.bat webview. Desktop window extension (WebView2 backend, zero runtime DLLs, ~296 KB binary delta): only 2 availability probes on the script side; window lifecycle belongs to the class: "app" service node — loading splash → auto-open on ready → graceful shutdown on close; headless fallback. Combined with single-file packing (xs pack) = a double-click desktop exe.
xsWebviewAvailable / Version
environment probe and backend version
class: "app" service node
local HTTP + desktop window; headless fallback
window descriptor · 9 fields
title / sizes / url / devtools / close / install_fallback — field-by-field constraints and defaults
XS_ServerInfo.PortBound
readback of the actual port for port: 0 auto-assign (uint16, tail-appended)
VFS built-in resources
Everything script compilation needs is inside the binary (LZMA-compressed, 350 resources in the all variant) — the target machine needs no headers or libraries:
| Path | Contents |
|---|---|
/xs/xsbase.h | The contract header (same version as the binary) |
/xs/xrt_decl.h | Full public xrt declarations (3,030 API prototypes) |
/xs/libtcc.h | Nested compilation API |
/tcc/include_win/** | Windows SDK headers (incl. winapi, curl) |
/tcc/include_linux/** | Linux-side standard headers |
/tcc/lib/*.def | kernel32 / msvcrt / user32 / gdi32 / shell32 / ole32 / oleaut32 / ws2_32 / imm32 |
/tcc/lib/libtcc1.a | TCC runtime helper library |
See the VFS reference for the resource inventory and variant differences. On Windows, msvcrt and kernel32 auto-mount in memory-compile mode; the 7 system libraries above are exported explicitly by the host — process, COM, socket and shell Win32 APIs work directly in scripts. sqlite3.h / xtp2.h ship only in their corresponding variants.