const MAX_FRAME_BYTES
pub const MAX_FRAME_BYTES = 1048576Purpose
Constant MAX_FRAME_BYTES, defining protocol or algorithm parameters.
#xacp#xacp is the transport-neutral safety core published with the Xu 0.13.1 SDK: frame limits, XUN checks, permissions, and session lifetime. Importing it does not open a control channel. Stdio and loopback TCP are runtime hooks inserted only by xu build --xacp or --xacp-port.
CLI: xu xacp · FAQ · Matching release source · Development protocol
The API declarations are source-reviewed against the selected release. The bounded ui.record sampling contract below follows §7 of the development protocol. Native stdio/TCP sessions, UI attachment, screenshots, and platform acceptance remain unverified.
open_session() returns a session in STATE_NEW (0) with PERM_NONE, generation 1, and the next request id 1. close_session moves it to STATE_CLOSED (2), bumps the generation, clears the active request, and drops permissions. STATE_OPEN is 1.
Only one request may be active. begin_request checks authorization and accepts only a positive id equal to next_id, reserves it, and advances the next id. An invalid id returns invalid_request_id; a second active request returns request_in_flight. A non-hello first request closes the session with hello_required. finish_request checks the active id and generation (stale_request on mismatch). A successfully negotiated hello opens the session; an unnegotiated hello cannot open it. Closed sessions return session_closed.
| Function | Role |
|---|---|
open_session() Session | New session, no permissions. |
close_session(s $&Session) | Close and clear permissions. |
cancel_request(s $&Session) | Drop the active request without opening the session. |
begin_request(s $&Session, r &Request) Outcome | Reserve the next monotonic id when authorized allows it. |
finish_request(s $&Session, id int) Outcome | Release the active id. Id 1 opens the session. |
authorized(s $&Session, r &Request) bool | xacp.hello only in STATE_NEW. Later ops need their permission bit. |
dispatch(s $&Session, d &xun.Doc, l &Limits) Outcome | Core lifecycle only. Completes xacp.hello. Does not grant development permissions. Every other known op returns not_implemented after a successful begin, or permission_denied when unauthorized. |
Permission changes are host policy. set_permissions succeeds only while the session is still STATE_NEW, and only for bits inside 0..15. Unknown bits are rejected. After a request has been finished, permissions stay as they are.
| Constant | Value | Operations |
|---|---|---|
PERM_NONE | 0 | xacp.hello, and only from STATE_NEW |
PERM_INFO | 1 | proc.status |
PERM_PROCESS | 2 | proc.output |
PERM_UI_READ | 4 | ui.tree, ui.screenshot, ui.record |
PERM_UI_MUTATE | 8 | ui.input, ui.act |
PERM_ALL | 15 | development_permissions() and enable_development() |
enable_development(s) is an explicit host helper equivalent to set_permissions(s, PERM_ALL). It does not bypass schema checks, session lifetime, native-resource disposal, or limits. Calling it after hello finishes returns false. Startup and attachment servers instead read XU_XACP_TOKEN and call negotiate_hello after a validated hello has begun and before finish_request.
Hello requires ver: !ver 1.0.0 and a non-empty string nonce, which the response echoes. With no host token configured, grants are capped at PERM_INFO, even if the client sends a token. With a host token, missing or mismatched args.token returns auth_failed and closes the session; a matching token allows up to PERM_ALL (15 in this SDK). Optional args.permissions is an !i mask of known bits: the grant is its intersection with the host allowance. Omitting it requests that allowance. Responses include numeric permissions and permission_label (none, info, development, or custom).
Both transports use XACP/1\n<N>\n followed by exactly N bytes of plain XUN. Header lines end in LF (0x0A); N is a positive ASCII decimal byte count excluding the header. Count UTF-8 bytes, including any newline in the body. There is no closing delimiter or extra separator between frames. The transport strips the prefix and reads exactly N bytes before calling parse_frame(body). That function accepts only the XUN body and rejects an empty body, invalid XUN, or a body above MAX_FRAME_BYTES. validate_request requires a root dictionary containing exactly id, op, and args; id is a positive !i.
default_limits() uses these hard caps. A custom Limits value may only be smaller.
| Constant | Value |
|---|---|
MAX_FRAME_BYTES | 1048576 (1 MiB) |
MAX_STRING_BYTES | 65536 |
MAX_FIELDS | 64 |
MAX_TABLE_ROWS | 10000 |
MAX_NODE_ID | 16777215 |
consume_input and consume_output reject negative counts, single counts above the frame cap, and totals above the session byte budget. The startup reader returns frame_too_large for an oversized body and truncated_frame for EOF inside a header or body. Clean EOF at a frame boundary closes the session. Frame errors use id 0; schema errors use a valid id hint when available, otherwise 0. Frame, schema, and authentication errors close the session.
This hello has a 69-byte body and a 10-byte header (79 bytes total). Every displayed line ends in LF, including the nonce line:
XACP/1
69
id: !i 1
op: xacp.hello
args:
ver: !ver 1.0.0
nonce: docs-client
With no host token configured, the matching response has a 109-byte body (120 bytes including its header). The last line again ends in LF. Responses use the same length prefix, with id, ok, and either data or error.code (plus optional error.msg). The next frame starts immediately after the body:
XACP/1
109
id: !i 1
ok: !b true
data:
state: OPEN
nonce: "docs-client"
permissions: !i 1
permission_label: info
The schema allows only these operations. Anything else is an unknown operation.
| Op | Permission | Startup control channel |
|---|---|---|
xacp.hello | PERM_NONE, STATE_NEW only | Token and permission negotiation before finish. Returns state: OPEN, echoed nonce, numeric permissions, and a permission label. |
proc.status | PERM_INFO | Empty args. Returns the real os.getpid() and state: OPEN. |
proc.output | PERM_PROCESS | Schema-checked (stream is stdout or stderr). Returns not_implemented with no output adapter. |
ui.tree | PERM_UI_READ | Schema-checked. Returns not_implemented with no Screen adapter. |
ui.screenshot | PERM_UI_READ | Same. No live pixels on this channel. |
ui.input | PERM_UI_MUTATE | Same, including after step checks. |
ui.act | PERM_UI_MUTATE | Same. Allowed action names in the schema are focus, click, set_text, and set_checked. |
ui.record | PERM_UI_READ | Same. Schema modes are events and frames. This is not the launcher's stdout record mode. |
On the startup channel, not_implemented is returned after begin_request, so that id is consumed and the next frame must use the following id. permission_denied is returned before the id advances.
UI control requires an explicit attach_stdio or attach_tcp handle, a live ui/widgets.Screen registered with register_screen, and poll calls from the Screen-owning coroutine between UI event iterations. Business main continues on this path. Unregister before leaving the poll loop. Typed helpers (ui_tree, ui_screenshot, ui_input, ui_act, and recorder helpers) still require the matching permission and check window/node ids, scale (0.1 through 4.0), text, and row/event budgets. A screenshot returns an owning draw.Surface; the caller disposes it. Startup --xacp-stdio and --xacp-tcp do not register a Screen. End-to-end UI behavior remains unverified.
With a matching registered Screen, ui.record performs bounded, pull-style XAR1 sampling within a single request. It requires PERM_UI_READ, a positive win: !i, and mode: events|frames. The Screen owner starts an in-memory bounded StreamWriter, samples synchronously, and finishes the recorder before responding. The optional arguments are:
| Argument | Default | Bound and meaning |
|---|---|---|
max_bytes: !i | 65536, reduced to fit the response | 1..limits.max_frame_bytes; cumulative XAR1 bytes, including headers and trailing LF. |
max_records: !i | 64 | At least 1; maximum complete records in this segment. |
duration_ms: !i | 0 | 0..limits.request_timeout_ms - 1; 0 takes one immediate sample, positive values bound the sampling window. |
Unknown fields, wrong types, or invalid bounds return schema_error. Between samples the recorder sleeps for up to 10 ms, stopping at the duration or record/byte budget; request queue time reduces the available window. Each success contains mode, records: !i, bytes: !i, truncated: !b, and payload, a quoted XAR1 string containing only complete records. truncated=true means the byte or record budget was exhausted; reaching the requested duration alone is normal completion. The effective byte budget is at most (limits.max_frame_bytes - 256) / 2 to reserve envelope and string-escape space, and the serialized response is also checked against the frame limit.
If the first record cannot fit, or a sink/snapshot fails, the recorder is aborted and the request returns adapter_error. A later record that cannot fit returns the completed prefix with truncated=true. The response uses the normal XU_XACP_WRITE_TIMEOUT_MS frame write deadline.
events emits current-state observations labelled state=true, with window, canvas, generation, and open. Screen has no public input event history/subscription, so these are not a real input event log. frames uses screen_screenshot then surface_record, exporting dimensions only with redacted=true and no pixels; each native Surface is disposed before continuing. Sampling neither injects input nor requires PERM_UI_MUTATE. It does not pump the application's UI event loop or reconstruct events between requests.
Clients pull successive segments by repeating ui.record. Each segment starts at sequence 1, with no persistent recorder or continuation cursor, and each request has exactly one XACP/1 response. Without a Screen, the result is not_implemented; a foreign or closed window returns stale_window. stream_required is reserved for adapters without a sink/sampling capability and is not returned by the supplied Screen sampling path. Platform support follows the registered Screen and its snapshot backend, including Windows.
Library start_recorder / write_record / finish_recorder also accept other StreamWriter sinks; callers must abort_recorder on failure. Library users with an input source can write input_record payloads. XAR1 segments are distinct from CLI xu xacp record, which captures stdout. The full recording contract is in PROTOCOL.md §7 on dev.
src/xacp/stdio.xu is part of the same package, and an --xacp build inserts stdio_preflight(port) at the start of main. That is the control entry. A normal import of #xacp does not emit it.
stdio_preflight(port) scans arguments until --. The first of --xacp-tcp or --xacp-stdio wins and exits without running the rest of main. Other launches return and business main runs. They do not listen and do not read control stdin.serve_stdio() reads and writes the process standard streams. Requests and responses use the same XACP/1 length prefix. The session is exclusive. EOF ends the process.serve_tcp(port) listens on 127.0.0.1:port only. The build port must be 1..65535; port 0 disables TCP and this function fails. Each accepted connection gets its own session. Connections are handled one at a time. A failed peer closes that session and the listener keeps accepting. There is no TLS and no other bind address.--xacp-help is a separate startup print, not a control session. Its capabilities line is stdio. When the build port is 0 it also prints tcp: disabled (port 0). A positive port prints tcp: enabled and bind: 127.0.0.1:PORT. See the CLI reference for launcher modes.
127.0.0.1.Screen adapter on the startup channel. proc.output and the UI ops validate, then return not_implemented.XU_XACP_REQUEST_TIMEOUT_MS accepts decimal 1..600000; invalid values retain the default. Work already executing is not interrupted. Callers still need process/I/O timeouts for a stalled target.--desktop.record is still unavailable on Windows. That mode captures stdout; it is not ui.record.Use the matching release source and smoke scripts for the released API, and development protocol §7 for bounded UI sampling. Older example README/design notes may describe obsolete framing, permissions, or timeout behavior.
These sources come from the official examples repository and can be copied or downloaded. Run them with a local Xu SDK in the complete project; network, database, and desktop examples require the corresponding services or assets.
16_ui_webview/xacp_screen/main.xu@main
#ui
#ui/widgets
#xacp
#errors
demo #"github.com/xulang-org/examples/ui_demo"
struct Model{
label_id int
count int
}
fn (m $&Model) layout(s $&widgets.Screen) int {
s.place(m.label_id, 32.0, 36.0, 540.0, 44.0) or >>
<< 0
}
fn inspect_screen(s $&widgets.Screen) int {
$session := xacp.open_session()
// The in-process adapter follows the current session lifecycle too.
// This token belongs only to this local demonstration; no listener is opened.
permissions := xacp.PERM_UI_READ | xacp.PERM_UI_MUTATE
limits := xacp.default_limits()
$nonces := xacp.new_nonce_registry(8, true)
hello := xacp.parse_frame("id: !i 1\nop: xacp.hello\nargs:\n ver: !ver 1.0.0\n nonce: local-screen-demo\n token: local-screen-demo\n permissions: !i " + str(permissions) + "\n") or(err) {
xacp.close_session($&session)
>> err
}
opened := xacp.dispatch_with_token($&session, &hello, &limits, "local-screen-demo", $&nonces)
if !opened.ok{
xacp.close_session($&session)
>> errors.new("xacp_screen: " + opened.err_msg)
}
tree := xacp.ui_tree(& * s, $&session, 2, false, 0, 32, &limits) or(err) {
xacp.close_session($&session)
>> err
}
println("XACP ui.tree: " + str(tree.nodes.len) + " visible nodes")
for node in tree.nodes{
println(" #" + str(node.id) + " kind=" + str(node.kind) + " " + node.text)
}
$snapshot := xacp.ui_screenshot(& * s, $&session, 3, 1.0, &limits) or(err) {
xacp.close_session($&session)
>> err
}
println("XACP ui.screenshot: " + str(snapshot.pixel_width) + "x" + str(snapshot.pixel_height) + " pixels")
snapshot.dispose() or(err) {
xacp.close_session($&session)
>> err
}
_ := xacp.ui_act(& * s, $&session, 2, 4, "focus", "", false, &limits) or(err) {
xacp.close_session($&session)
>> err
}
xacp.close_session($&session)
<< 0
}
fn scene(events chan ui.Event) int {
ready := demo.ready(events) or >>
if ready.kind == ui.EV_EXIT{ << 0}
$screen := widgets.screen(&ready) or >>
screen.resize(640.0, 180.0) or >>
label_id := screen.label("XACP Screen adapter", 22.0, false) or >>
button_id := screen.button("Activate locally or through ui.act") or >>
screen.place(label_id, 32.0, 36.0, 540.0, 44.0) or >>
screen.place(button_id, 32.0, 96.0, 360.0, 40.0) or >>
inspect_screen($&screen) or(err) {
screen.dispose()
>> err
}
$model := Model{label_id: label_id, count: 0}
$actions := widgets.action_dispatcher(&model, &screen)
actions.on(button_id, widgets.ACTION_ACTIVATE, activate) or >>
actions.set_fallback(global_key)
<< widgets.run_screen_actions($&screen, events, $&model, layout_action, &actions) or >>
}
fn worker(events chan ui.Event) {
scene(events) or(err) {demo.fail(err.msg())
<< }
}
fn launch() int {
$app := demo.app("Xu / XACP Screen adapter", 640, 180) or >>
xu worker(app.event_ch)
<< app.run() or >>
}
fn main() int {
<< launch() or(err) {eprintln(err.msg())
<< 1}
}const MAX_FRAME_BYTESpub const MAX_FRAME_BYTES = 1048576Constant MAX_FRAME_BYTES, defining protocol or algorithm parameters.
const MAX_STRING_BYTESpub const MAX_STRING_BYTES = 65536Constant MAX_STRING_BYTES, defining protocol or algorithm parameters.
const MAX_FIELDSpub const MAX_FIELDS = 64Constant MAX_FIELDS, defining protocol or algorithm parameters.
const MAX_TABLE_ROWSpub const MAX_TABLE_ROWS = 10000Constant MAX_TABLE_ROWS, defining protocol or algorithm parameters.
const MAX_NODE_IDpub const MAX_NODE_ID = 16777215Constant MAX_NODE_ID, defining protocol or algorithm parameters.
const DEFAULT_REQUEST_TIMEOUT_MSpub const DEFAULT_REQUEST_TIMEOUT_MS = 5000Constant DEFAULT_REQUEST_TIMEOUT_MS, defining protocol or algorithm parameters.
const MAX_REQUEST_TIMEOUT_MSpub const MAX_REQUEST_TIMEOUT_MS = 600000Constant MAX_REQUEST_TIMEOUT_MS, defining protocol or algorithm parameters.
const DEFAULT_WRITE_TIMEOUT_MSpub const DEFAULT_WRITE_TIMEOUT_MS = 10000Constant DEFAULT_WRITE_TIMEOUT_MS, defining protocol or algorithm parameters.
const MAX_WRITE_TIMEOUT_MSpub const MAX_WRITE_TIMEOUT_MS = 600000Constant MAX_WRITE_TIMEOUT_MS, defining protocol or algorithm parameters.
const DEFAULT_HELLO_TIMEOUT_MSpub const DEFAULT_HELLO_TIMEOUT_MS = 5000Constant DEFAULT_HELLO_TIMEOUT_MS, defining protocol or algorithm parameters.
const MAX_HELLO_TIMEOUT_MSpub const MAX_HELLO_TIMEOUT_MS = 600000Constant MAX_HELLO_TIMEOUT_MS, defining protocol or algorithm parameters.
const DEFAULT_IDLE_TIMEOUT_MSpub const DEFAULT_IDLE_TIMEOUT_MS = 60000Constant DEFAULT_IDLE_TIMEOUT_MS, defining protocol or algorithm parameters.
const MIN_IDLE_TIMEOUT_MSpub const MIN_IDLE_TIMEOUT_MS = 1000Constant MIN_IDLE_TIMEOUT_MS, defining protocol or algorithm parameters.
const MAX_IDLE_TIMEOUT_MSpub const MAX_IDLE_TIMEOUT_MS = 3600000Constant MAX_IDLE_TIMEOUT_MS, defining protocol or algorithm parameters.
const DEFAULT_NONCE_CACHEpub const DEFAULT_NONCE_CACHE = 1024Constant DEFAULT_NONCE_CACHE, defining protocol or algorithm parameters.
const MAX_NONCE_CACHEpub const MAX_NONCE_CACHE = 65536Constant MAX_NONCE_CACHE, defining protocol or algorithm parameters.
const STATE_NEWpub const STATE_NEW = 0Constant STATE_NEW, defining protocol or algorithm parameters.
const STATE_OPENpub const STATE_OPEN = 1Constant STATE_OPEN, defining protocol or algorithm parameters.
const STATE_CLOSEDpub const STATE_CLOSED = 2Constant STATE_CLOSED, defining protocol or algorithm parameters.
const PERM_NONEpub const PERM_NONE = 0Constant PERM_NONE, defining protocol or algorithm parameters.
const PERM_INFOpub const PERM_INFO = 1Constant PERM_INFO, defining protocol or algorithm parameters.
const PERM_PROCESSpub const PERM_PROCESS = 2Constant PERM_PROCESS, defining protocol or algorithm parameters.
const PERM_UI_READpub const PERM_UI_READ = 4Constant PERM_UI_READ, defining protocol or algorithm parameters.
const PERM_UI_MUTATEpub const PERM_UI_MUTATE = 8Constant PERM_UI_MUTATE, defining protocol or algorithm parameters.
const PERM_UI_RAWpub const PERM_UI_RAW = 16Constant PERM_UI_RAW, defining protocol or algorithm parameters.
const PERM_ALLpub const PERM_ALL = 31Constant PERM_ALL, defining protocol or algorithm parameters.
struct Limitspub struct Limits {
pub max_frame_bytes int
pub max_string_bytes int
pub max_fields int
pub max_table_rows int
pub max_node_id int
pub request_timeout_ms int
pub write_timeout_ms int
pub hello_timeout_ms int
pub idle_timeout_ms int
}Structure encapsulating max_frame_bytes, max_string_bytes, max_fields, max_table_rows, max_node_id.
max_frame_bytes intmax_string_bytes intmax_fields intmax_table_rows intmax_node_id intrequest_timeout_ms intwrite_timeout_ms inthello_timeout_ms intidle_timeout_ms intstruct Sessionpub struct Session {
pub state int
pub generation int
pub next_id int
pub active_id int
pub active_generation int
pub permissions int
pub nonce string
pub bytes_in int
pub bytes_out int
}Structure encapsulating state, generation, next_id, active_id, active_generation.
state intgeneration intnext_id intactive_id intactive_generation intpermissions intnonce stringbytes_in intbytes_out intstruct NonceRegistrypub struct NonceRegistry {
}The host owns this bounded FIFO across sessions. Sequential listeners borrow it exclusively while negotiating; concurrent hosts must serialize that borrow.
This type has no public fields.
new_nonce_registrypub fn new_nonce_registry(capacity int, enabled bool) NonceRegistryInvalid capacities use the default. Disabled registries retain no nonces.
capacity intenabled boolNonceRegistry — a value of this type
struct Requestpub struct Request {
pub id int
pub op string
pub args int
}Structure encapsulating id, op, args.
id intop stringargs intstruct Outcomepub struct Outcome {
pub ok bool
pub request_id int
pub err_code string
pub err_msg string
}Structure encapsulating ok, request_id, err_code, err_msg.
ok boolrequest_id interr_code stringerr_msg stringdefault_limitspub fn default_limits() LimitsDefault limits.
No arguments are required.
Limits — a value of this type
request_timeout_from_envpub fn request_timeout_from_env() intRead once when the control server initializes its limits. Only ASCII decimal 1..600000 is accepted; invalid values silently keep the default deadline.
No arguments are required.
int — a value of this type
write_timeout_from_envpub fn write_timeout_from_env() intwrite_timeout_from_env accepts ASCII decimal 1..600000, otherwise the default.
No arguments are required.
int — a value of this type
hello_timeout_from_envpub fn hello_timeout_from_env() inthello_timeout_from_env accepts ASCII decimal 1..600000, otherwise the default.
No arguments are required.
int — a value of this type
idle_timeout_from_envpub fn idle_timeout_from_env() intidle_timeout_from_env accepts 1000..3600000 or 0 to disable idle expiry. Empty, malformed, out-of-range and overflowing input keeps the default.
No arguments are required.
int — a value of this type
nonce_cache_from_envpub fn nonce_cache_from_env() intHosts read nonce policy once when starting a listener/control loop.
No arguments are required.
int — a value of this type
nonce_replay_from_envpub fn nonce_replay_from_env() boolNonce replay from env.
No arguments are required.
bool — true or false
open_sessionpub fn open_session() SessionOpen session.
No arguments are required.
Session — a value of this type
close_sessionpub fn close_session(s $&Session)Close session.
s $&SessionThis call does not return a value.
cancel_requestpub fn cancel_request(s $&Session)Cancel request.
s $&SessionThis call does not return a value.
set_permissionspub fn set_permissions(s $&Session, permissions int) boolPermission grants are explicit host policy. Unknown bits are rejected and permissions cannot be changed after a session has begun serving requests.
s $&Sessionpermissions intbool — true or false
development_permissionspub fn development_permissions() intDevelopment hosts may opt into the complete permission set explicitly. This is policy only; schema, byte, window, and lifecycle checks still apply.
No arguments are required.
int — a value of this type
enable_developmentpub fn enable_development(s $&Session) boolEnable development.
s $&Sessionbool — true or false
parse_framepub fn parse_frame(src string) xun.DocParse the plain XUN body of one XACP/1 frame. The transport has already stripped the XACP/1\n<N>\n length prefix and read exactly N bytes; pass only the body. Throws for an empty body, a body above MAX_FRAME_BYTES, or invalid XUN.
src stringparsed XUN document; validate_request checks the request schema separately
request_id_hintpub fn request_id_hint(d &xun.Doc) intrequest_id_hint returns a top-level id: !i N if one parses, otherwise 0, so schema errors can still echo the caller's id.
d &xun.Docint — a value of this type
validate_requestpub fn validate_request(d &xun.Doc, l &Limits) Requestvalidate_request enforces the fixed top-level schema and rejects every operation that has not been explicitly added to this package's schema. Throws on failure; handle the error or propagate it to the caller.
d &xun.Docl &LimitsRequest — a value of this type
authorizedpub fn authorized(s $&Session, r &Request) boolExecute authorized.
s $&Sessionr &Requestbool — true or false
begin_requestpub fn begin_request(s $&Session, r &Request) OutcomeBegin request.
s $&Sessionr &RequestOutcome — a value of this type
finish_requestpub fn finish_request(s $&Session, id int) OutcomeFinish request.
s $&Sessionid intOutcome — a value of this type
consume_inputpub fn consume_input(s $&Session, n int, l &Limits) boolConsume input.
s $&Sessionn intl &Limitsbool — true or false
consume_outputpub fn consume_output(s $&Session, n int, l &Limits) boolConsume output.
s $&Sessionn intl &Limitsbool — true or false
check_windowpub fn check_window(start int, count int, total int, l &Limits) boolCheck window.
start intcount inttotal intl &Limitsbool — true or false
check_nodepub fn check_node(node int, l &Limits) boolCheck node.
node intl &Limitsbool — true or false
negotiate_hellopub fn negotiate_hello(s $&Session, d &xun.Doc, r &Request, expected_token string, nonces $&NonceRegistry) Outcomenegotiate_hello consumes a schema-validated, reserved hello. The host supplies its expected token and shared registry; RAW additionally requires host opt-in. A client token alone never grants more than INFO when the host has no token.
s $&Sessiond &xun.Docr &Requestexpected_token stringnonces $&NonceRegistryOutcome — a value of this type
dispatchpub fn dispatch(s $&Session, d &xun.Doc, l &Limits, nonces $&NonceRegistry) Outcomedispatch performs only the safe core lifecycle with the default INFO policy. Data-bearing adapters implement operations after the same checks.
s $&Sessiond &xun.Docl &Limitsnonces $&NonceRegistryOutcome — a value of this type
dispatch_with_tokenpub fn dispatch_with_token(s $&Session, d &xun.Doc, l &Limits, expected_token string, nonces $&NonceRegistry) OutcomeHosts with an explicit authentication policy pass the expected token here.
s $&Sessiond &xun.Docl &Limitsexpected_token stringnonces $&NonceRegistryOutcome — a value of this type
struct ControlReplypub struct ControlReply {
pub outcome Outcome
pub data string
}Only owning strings, scalars and channel handles cross the control coroutine.
outcome Outcomedata stringstruct ControlJobpub struct ControlJob {
pub id int
pub op string
pub body string
pub permissions int
pub generation int
pub started int
pub timeout_ms int
pub reply chan ControlReply
}Structure encapsulating id, op, body, permissions, generation.
id intop stringbody stringpermissions intgeneration intstarted inttimeout_ms intreply chan ControlReplystruct ScreenControlpub struct ScreenControl {
pub done chan int
}One attachment per process, with one registered Screen. Keep this handle in the Screen-owning coroutine. The state token serializes registration/enqueue the one-slot mailbox bounds pending work. No Screen reference is retained.
done chan intattach_stdiopub fn attach_stdio() ScreenControlExplicit attachment: business main continues; stdin/stdout carry XACP. Prefer stderr for logs on this shared transport. Both streams are captured. done receives the server exit status at EOF.
No arguments are required.
ScreenControl — a value of this type
attach_tcppub fn attach_tcp(port int) ScreenControlLoopback TCP uses the same sequential-peer and authentication policy as exclusive TCP. The caller must use a valid port and keep polling until exit. Throws on failure; handle the error or propagate it to the caller.
port intScreenControl — a value of this type
register_screenpub fn register_screen(control $&ScreenControl,s &widgets.Screen) intRegistration borrows only during this call. Duplicate registration is rejected; unregister before registering another Screen. Close/dispose sends a channel notification so the control side also invalidates idle screens. Throws on failure; handle the error or propagate it to the caller.
control $&ScreenControls &widgets.Screenint — a value of this type
unregister_screenpub fn unregister_screen(control $&ScreenControl)The UI owner must unregister before abandoning the poll loop. A queued job receives stale_window. New requests see not_implemented without needing poll.
control $&ScreenControlThis call does not return a value.
pollpub fn poll(control $&ScreenControl,s $&widgets.Screen) boolNonblocking: service at most one request between UI event iterations. Never call a blocking UI wait while control work needs polling. A registered owner that stops polling gets request_timeout after the configured deadline. Work already executing is not interrupted; its late reply is buffered and discarded.
control $&ScreenControls $&widgets.Screenbool — true or false
struct RecordBufferpub struct RecordBuffer {
}StreamWriter with all-or-error appends. Neither a failed write nor a caller-supplied large max_records can grow the retained payload past limit.
This type has no public fields.
record_bufferpub fn record_buffer(max_bytes int) RecordBufferRecord buffer. Throws on failure; handle the error or propagate it to the caller.
max_bytes intRecordBuffer — a value of this type
($&RecordBuffer) write_strpub fn (b $&RecordBuffer) write_str(data string) intOperation on $&RecordBuffer: write a string. Throws on failure; handle the error or propagate it to the caller.
b $&RecordBufferRecordBuffer instance used by this call (exclusive borrow).data stringint — a value of this type
(&RecordBuffer) textpub fn (b &RecordBuffer) text() stringOperation on &RecordBuffer: return the current text.
b &RecordBufferRecordBuffer instance used by this call (borrow).string — result string
const MAX_SCREENSHOT_BYTESpub const MAX_SCREENSHOT_BYTES = 33554432Constant MAX_SCREENSHOT_BYTES, defining protocol or algorithm parameters.
screenshot_dirpub fn screenshot_dir() stringAbsolute directory for the host only; the wire always returns a basename. The POSIX native UI host creates/validates private directories on first write. Throws on failure; handle the error or propagate it to the caller.
No arguments are required.
string — result string
program_preflightpub fn program_preflight(port int)Discover the compiled capabilities before dispatching to an explicit control mode.
port intThis call does not return a value.
stdio_preflightpub fn stdio_preflight(port int)Explicit control modes skip business main; the first control flag wins. Ordinary invocations never listen or read control stdin. The -- boundary protects application arguments.
port intThis call does not return a value.
const MAX_ERROR_MSG_BYTESpub const MAX_ERROR_MSG_BYTES = 256Constant MAX_ERROR_MSG_BYTES, defining protocol or algorithm parameters.
serve_stdiopub fn serve_stdio() intChunked reads and an amortized builder bound memory and copying. EOF and fatal frame/schema/auth errors terminate the session; complete frames may share a read. Throws on failure; handle the error or propagate it to the caller.
No arguments are required.
int — a value of this type
serve_tcppub fn serve_tcp(port int) intExplicit exclusive control mode; loopback only, sequential connections. A malformed/disconnected peer ends its session, not the listener. Throws on failure; handle the error or propagate it to the caller.
port intint — a value of this type
const MAX_UI_EVENTSpub const MAX_UI_EVENTS = 512ScreenAdapter is the typed bridge between the transport-neutral XACP core and a live widgets.Screen. The Screen still owns all native resources; this package only borrows it for the duration of each checked operation.
struct Recorderpub struct Recorder {
pub mode string
pub max_bytes int
pub bytes int
pub sequence int
pub closed bool
pub request_id int
pub session_generation int
}Structure encapsulating mode, max_bytes, bytes, sequence, closed.
mode stringmax_bytes intbytes intsequence intclosed boolrequest_id intsession_generation intnew_recorderpub fn new_recorder(mode string,max_bytes int,l &Limits) RecorderConstruct recorder. Throws on failure; handle the error or propagate it to the caller.
mode stringmax_bytes intl &LimitsRecorder — a value of this type
($&Recorder) closepub fn (r $&Recorder) close()Operation on $&Recorder: close the resource.
r $&RecorderRecorder instance used by this call (exclusive borrow).This call does not return a value.
(&Recorder) is_openpub fn (r &Recorder) is_open() boolOperation on &Recorder: whether it is open.
r &RecorderRecorder instance used by this call (borrow).bool — true or false
write_recordpub fn write_record#W:StreamWriter(r $&Recorder,sink $&W,kind string,data string) intwrite_record is deliberately streaming: no record is retained after the sink accepts it. The length prefix lets a consumer reject truncation without parsing untrusted payload bytes. A failed sink write does not advance the recorder's accounting or sequence. Throws on failure; handle the error or propagate it to the caller.
r $&Recordersink $&Wkind stringdata stringint — a value of this type
input_recordpub fn input_record(event &ui.InputEvent) stringInput record.
event &ui.InputEventstring — result string
surface_recordpub fn surface_record(surface &draw.Surface) stringSurface record.
surface &draw.Surfacestring — result string
struct TreeWindowpub struct TreeWindow {
pub start int
pub total int
pub nodes []widgets.ScreenNodeInfo
}Structure encapsulating start, total, nodes.
start inttotal intnodes []widgets.ScreenNodeInfoscreen_treepub fn screen_tree(s $&widgets.Screen,include_hidden bool,start int,max_rows int,l &Limits) TreeWindowRead-only tree window. The returned nodes are copies and remain valid after the caller releases the Screen borrow. Throws on failure; handle the error or propagate it to the caller.
s $&widgets.Screeninclude_hidden boolstart intmax_rows intl &LimitsTreeWindow — a value of this type
screen_screenshotpub fn screen_screenshot(s $&widgets.Screen,scale f64) draw.SurfaceThe Surface is a native resource with explicit ownership. The caller must dispose it, including error and cancellation paths; no byte copy is staged in the adapter. Throws on failure; handle the error or propagate it to the caller.
s $&widgets.Screenscale f64draw.Surface — a value of this type
screen_screenshot_nodepub fn screen_screenshot_node(s $&widgets.Screen,node int,scale f64,l &Limits) draw.SurfaceScreen screenshot node. Throws on failure; handle the error or propagate it to the caller.
s $&widgets.Screennode intscale f64l &Limitsdraw.Surface — a value of this type
screen_inputpub fn screen_input(s $&widgets.Screen,events &[]ui.InputEvent,l &Limits) []widgets.ActionScreen input. Throws on failure; handle the error or propagate it to the caller.
s $&widgets.Screenevents &[]ui.InputEventl &Limits[]widgets.Action — slice result
screen_input_requestpub fn screen_input_request(s $&widgets.Screen,d &xun.Doc,args int,l &Limits) []widgets.ActionScreen input request. Throws on failure; handle the error or propagate it to the caller.
s $&widgets.Screend &xun.Docargs intl &Limits[]widgets.Action — slice result
screen_actpub fn screen_act(s $&widgets.Screen,id int,act string,text string,checked bool,l &Limits) []widgets.ActionScreen act. Throws on failure; handle the error or propagate it to the caller.
s $&widgets.Screenid intact stringtext stringchecked booll &Limits[]widgets.Action — slice result
start_recorderpub fn start_recorder(session $&Session,id int,mode string,max_bytes int,l &Limits) RecorderStart recorder. Throws on failure; handle the error or propagate it to the caller.
session $&Sessionid intmode stringmax_bytes intl &LimitsRecorder — a value of this type
finish_recorderpub fn finish_recorder(session $&Session,r $&Recorder) intFinish recorder. Throws on failure; handle the error or propagate it to the caller.
session $&Sessionr $&Recorderint — a value of this type
abort_recorderpub fn abort_recorder(session $&Session,r $&Recorder)Abort recorder.
session $&Sessionr $&RecorderThis call does not return a value.
ui_treepub fn ui_tree(s $&widgets.Screen,session $&Session,id int,include_hidden bool,start int,max_rows int,l &Limits) TreeWindowPermission-bearing entry points. Every operation reserves a monotonic request id and releases it on both success and adapter failure. Throws on failure; handle the error or propagate it to the caller.
s $&widgets.Screensession $&Sessionid intinclude_hidden boolstart intmax_rows intl &LimitsTreeWindow — a value of this type
ui_screenshotpub fn ui_screenshot(s $&widgets.Screen,session $&Session,id int,scale f64,l &Limits) draw.SurfaceUi screenshot. Throws on failure; handle the error or propagate it to the caller.
s $&widgets.Screensession $&Sessionid intscale f64l &Limitsdraw.Surface — a value of this type
ui_screenshot_nodepub fn ui_screenshot_node(s $&widgets.Screen,session $&Session,id int,node int,scale f64,l &Limits) draw.SurfaceUi screenshot node. Throws on failure; handle the error or propagate it to the caller.
s $&widgets.Screensession $&Sessionid intnode intscale f64l &Limitsdraw.Surface — a value of this type
ui_inputpub fn ui_input(s $&widgets.Screen,session $&Session,id int,events &[]ui.InputEvent,l &Limits) []widgets.ActionUi input. Throws on failure; handle the error or propagate it to the caller.
s $&widgets.Screensession $&Sessionid intevents &[]ui.InputEventl &Limits[]widgets.Action — slice result
ui_input_requestpub fn ui_input_request(s $&widgets.Screen,session $&Session,id int,d &xun.Doc,args int,l &Limits) []widgets.ActionUi input request. Throws on failure; handle the error or propagate it to the caller.
s $&widgets.Screensession $&Sessionid intd &xun.Docargs intl &Limits[]widgets.Action — slice result
ui_actpub fn ui_act(s $&widgets.Screen,session $&Session,id int,request_id int,act string,text string,checked bool,l &Limits) []widgets.ActionUi act. Throws on failure; handle the error or propagate it to the caller.
s $&widgets.Screensession $&Sessionid intrequest_id intact stringtext stringchecked booll &Limits[]widgets.Action — slice result
dispatch_screenpub fn dispatch_screen(s $&widgets.Screen,session $&Session,d &xun.Doc,l &Limits,nonces $&NonceRegistry) ControlReplydispatch_screen executes the schema-approved UI operations against the registered Screen and serializes every successful result before releasing the borrow. Native Surfaces are disposed before the owning PNG reply crosses the mailbox; only the authoritative session can export a screenshot file. Throws on failure; handle the error or propagate it to the caller.
s $&widgets.Screensession $&Sessiond &xun.Docl &Limitsnonces $&NonceRegistryControlReply — a value of this type