Expand description
§axi-sdk-rs
An independent, unofficial Rust SDK for authoring bounded, non-interactive Agent eXperience Interface (AXI) executables.
This crate independently models the AXI principles and the public behavior of
the TypeScript SDK. It is not maintained by or endorsed by the upstream AXI
project. Version 0.1.0 is the initial crates.io release and remains a pre-1.0
API.
Reference baseline:
- AXI repository commit
5dfe221d44d564bc47fbabfd20cf5c8369677838 - TypeScript SDK tag
axi-sdk-js-v0.1.10 - TOON format/package behavior
2.1.0 - Rust MSRV
1.85.0; edition 2021
See the conformance matrix, architecture, dependency review, release history, and security model for the exact supported surface and limitations.
§What the SDK owns
- command-first dispatch and strict typed options, switches, and arguments;
- a live, directory-scoped no-argument home view;
- generated top-level help, concise command help, examples, and bare version;
- deterministic TOON by default and compact JSON on explicit request;
- one structured stdout document, bounded to at most 48 KiB including LF;
- truthful Unicode previews, pages with totals, warnings, and artifact refs;
- structured errors and stable process statuses;
- lazy, explicit invocation context with declared environment capture only;
- reusable sync execution and executor-neutral async execution;
- cooperative deadlines/cancellation, LIFO cleanup, panic containment, and broken-pipe-safe process writes;
- explicit, idempotent ambient setup for Claude Code, Codex, and
OpenCode; - deterministic
SKILL.mdgeneration plus drift checks.
The SDK does not perform network access, update checks, interactive prompts, telemetry, implicit artifact writes, or ambient installation during normal execution.
§Add the crate
Use the registry package name axi-sdk-rs; Rust code imports its library as
axi_sdk. An exact dependency on the initial release is:
[dependencies]
axi-sdk-rs = "=0.1.0"§Start without a global install
Run the included examples directly from this checkout:
cargo run --quiet --example query_axi --
cargo run --quiet --example query_axi -- search rust
cargo run --quiet --example query_axi -- search 文档 --limit 1 --json
cargo run --quiet --example tasks_axi --
cargo run --quiet --example tasks_axi -- list --status open
cargo run --quiet --example tasks_axi -- view 1
cargo run --quiet --example tasks_axi -- close 1The second -- belongs to Cargo and forwards the remaining arguments. AXI is
command-first: SDK flags follow the command. For example, use
tasks-axi list --json, not tasks-axi --json list.
§Define an AXI once
The same typed keys define parsing, validation, generated help, skill export, and handler access:
use std::process::ExitCode;
use axi_sdk::{
process, ArgumentKey, Axi, AxiResult, Command, CommandKind, Identity,
OptionKey, Output, Page,
};
use serde::Serialize;
#[derive(Clone, Serialize)]
struct Row { id: u64, title: &'static str }
fn build() -> AxiResult<Axi> {
let query = ArgumentKey::<String>::new("query", "Text to match");
let limit = OptionKey::<usize>::new("limit", "Maximum rows")
.default(10)
.validate(|value| (1..=100).contains(value)
.then_some(())
.ok_or_else(|| "expected 1..=100".to_owned()));
let handler_query = query.clone();
let handler_limit = limit.clone();
let search = Command::<()>::builder(
"search",
"Search the offline fixture",
CommandKind::ReadOnly,
)
.argument(&query)
.option(&limit)
.example("rows-axi search rust")
.handler(move |input, _context| {
let query = input.argument(&handler_query)?;
let limit = input.get(&handler_limit)?;
let rows: Vec<Row> = vec![Row { id: 1, title: "Rust" }]
.into_iter()
.filter(|row| row.title.to_lowercase().contains(&query.to_lowercase()))
.take(limit)
.collect();
let total = rows.len();
if total == 0 {
return Ok(Output::definitive_empty("rows", "0 rows matched")?
.suggestion("Try a broader query"));
}
Ok(Output::empty().page("rows", Page::new(rows, 0, total)?)?)
});
Axi::builder(Identity::new("rows-axi", "1.0.0", "Search fixture rows"))
.home(|_| Ok(Output::definitive_empty("rows", "0 recent rows")?
.suggestion("Run `rows-axi search <query>`")))
.command(search)
.build()
}
fn main() -> ExitCode {
match build() {
Ok(app) => process::run(&app),
Err(error) => {
eprintln!("invalid AXI definition: {error}");
axi_sdk::ExitStatus::Software.process()
}
}
}Axi is immutable after build() and can be invoked repeatedly. Invalid
input is rejected before context resolution or handler execution. Mutating
commands must declare at least one concrete side effect; read-only commands
cannot claim mutation side effects.
§Generated CLI contract
tool live home view (TOON)
tool --help generated top-level help
tool -v | -V | --version bare version
tool <command> --help generated command reference
tool <command> ... TOON result
tool <command> ... --json compact JSON result
tool <command> ... --format json
tool <command> ... --timeout-ms 5000
tool <command> ... --full only when enabled by that command--full may remove a field-level preview but never bypasses the 48 KiB final
ceiling. Oversized output is replaced—not partially emitted—with a structured
OUTPUT_LIMIT error. Use Page, TextPreview, and ArtifactRef to keep output
truthful and useful.
§Streams and statuses
Domain data and structured errors go to stdout. Stderr is reserved for SDK containment/write diagnostics, never progress or a second domain document. Every SDK-rendered document has exactly one trailing LF.
| Status | Meaning |
|---|---|
0 | success, definitive empty result, or idempotent no-op |
1 | domain, dependency, cleanup, configuration, or output-limit failure |
2 | unknown command/flag, missing input, or invalid typed value |
70 | contained handler/home panic |
124 | deadline elapsed |
130 | cancellation or interrupt |
143 | termination request |
A downstream closed pipe is a quiet success. The process boundary reads only
arguments, cwd, executable, home-for-display, and environment variables that
the app explicitly declares with EnvironmentVariable.
§Async, cancellation, and containment
Default builds have no executor dependency. Enable async to define boxed,
borrowing futures and invoke them from the executable’s chosen runtime:
axi-sdk-rs = { version = "=0.1.0", features = ["async"] }let outcome = runtime.block_on(app.run_async(invocation));A pending future is woken when its cancellation token fires. Sync handlers
must call context.checkpoint() at safe interruption points; the SDK cannot
preempt arbitrary blocking work. Both sync and async handlers may register
LIFO callbacks with context.defer(...); callbacks run once after every
result path. Handler panics are caught and converted to INTERNAL_PANIC.
The host’s installed Rust panic hook still runs, so embedders that put secrets
in panic payloads must provide their own sanitized hook.
Enable signals to let process::run bridge SIGINT/SIGTERM to the invocation’s
cooperative token:
axi-sdk-rs = { version = "=0.1.0", features = ["signals"] }§Explicit ambient setup
Normal dispatch never modifies agent settings. A user-invoked setup command
may call AmbientSetup::install with an explicit home directory and explicit
PATH value. The installer:
- merges managed
SessionStarthooks into Claude Code and Codex settings; - optionally adds
SessionEndcapture for those two agents; - enables Codex’s
[features].hooksflag without replacing unrelated TOML; - generates a directory-scoped, per-session cached
OpenCodeplugin; - bounds plugin capture and executes the selected binary with
shell: false; - uses a PATH name only when it canonicalizes to the exact executable;
- otherwise records the full absolute executable path;
- repairs relocations, removes duplicate managed hooks, and is idempotent;
- preflights malformed JSON, unsafe targeted Codex hook values, and unmanaged plugins, then writes replacements atomically per file.
use axi_sdk::ambient::AmbientSetup;
use std::ffi::OsStr;
use std::path::Path;
let executable = context.invocation().executable();
let home = context.invocation().environment("HOME").expect("declared HOME");
let path = context.invocation().environment("PATH").map(OsStr::new);
let report = AmbientSetup::new("tasks-axi", "tasks-axi", executable)
.session_end_args(["session-end"])
.install(Path::new(home), path)?;Declare HOME and PATH on the app so process::capture includes them. Ask
for consent before running setup and disclose every file in InstallReport.
OpenCode currently has no stable equivalent of SessionEnd; the SDK does not
guess an event name.
§Generate and check an Agent Skill
Axi::generate_skill uses the frozen command definition, never live home data:
let skill = app.generate_skill("cargo run --example tasks_axi --")?;
skill.write(std::path::Path::new("skills/tasks-axi/SKILL.md"))?;
// CI/drift gate:
skill.check(std::path::Path::new("skills/tasks-axi/SKILL.md"))?;The generated frontmatter, argument/flag reference, examples, side-effect and network metadata, and declared environment contract remain aligned with the executable. The invocation prefix supports binaries that are not globally installed.
§Features and dependencies
| Feature | Default | Adds |
|---|---|---|
async | no | executor-neutral handler/future APIs; no dependency |
signals | no | signal-hook bridge for process::run |
Core dependencies are Serde, serde_json, and exact-pinned toon-rs 2.1.0.
The lockfile is committed. All production dependency licenses were reviewed as
permissive, and cargo audit reported no known vulnerabilities on the review
date. Details and caveats are in the dependency review.
§Validate this checkout
./scripts/generate-agents.sh --check
cargo fmt --all -- --check
cargo check --all-targets --all-features
cargo clippy --all-targets --all-features -- -D warnings
cargo test
cargo test --all-features
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features
cargo auditThe compatibility goldens under tests/fixtures/typescript-sdk-v0.1.10/ record
their source revision, package integrity, and independent tarball digest. Tests
cover exact TOON/JSON bytes, strict decoding, Unicode, empty values, parsing,
help/home/version, output limits, lazy context, cleanup, panic containment,
sync/async cancellation, signals, ambient repair, and skill drift.
§License
MIT. Upstream AXI is also MIT; no upstream source code is copied into this
crate. See the repository’s LICENSE file.
Modules§
- ambient
- Explicit, idempotent ambient session integration.
- process
- Explicit real-process boundary and broken-pipe-safe writes.
- skill
- Static Agent Skill generation from the same typed AXI definition.
Structs§
- Argument
Key - Typed key for a positional argument.
- Artifact
Ref - Reference to content deliberately written outside stdout by application code.
- Axi
- Reusable, immutable AXI definition.
- AxiBuilder
- Builder for an
Axi. - AxiError
- An error intended for structured AXI output.
- Cancellation
Token - Cloneable, thread-safe cooperative cancellation token.
- Command
- A complete typed command definition.
- Command
Builder - Builder for a
Command. - Environment
Variable - One explicitly declared environment dependency.
- Execution
Context - Context passed to home and command handlers.
- Identity
- Static executable identity used by home/help/version generation.
- Invocation
- Fully explicit request to execute an
Axi. - Invocation
Info - Process and environment facts captured explicitly for one invocation.
- Option
Key - Typed key for a named option such as
--limit 10. - Output
- Structured command output.
- Output
Bounds - Output policy applied at the one SDK-owned stdout boundary.
- Page
- A bounded page that retains the total aggregate.
- Page
Metadata - Truthful pagination metadata for a bounded collection.
- Parsed
Input - Validated values passed to a command handler.
- Resolve
Context - Lazy context resolver input.
- RunOutcome
- Captured SDK output for tests and embedding applications.
- Switch
- Typed key for a boolean switch such as
--verify. - Text
Preview - Stable, truthful representation of a bounded long-form text field.
- Warning
- A structured warning kept on stdout with the command data.
Enums§
- Cancellation
Reason - Why an invocation’s cancellation token was set.
- Command
Kind - Declared side-effect class for a command.
- Exit
Status - Stable process statuses emitted by the SDK.
- Network
Policy - Declared network behavior for a command.
- Output
Format - Structured stdout representation.
Constants§
- DEFAULT_
MAX_ OUTPUT_ BYTES - Default final structured stdout ceiling (48 KiB, including the newline).
- MIN_
OUTPUT_ BYTES - Smallest accepted final-output ceiling.
Functions§
- decode_
toon - Decode strict TOON into a typed value.
Type Aliases§
- AxiResult
- SDK result alias.
- BoxCommand
Future - Boxed async command result that borrows its invocation inputs.