esp-agent
esp-agent is an early-stage Rust no_std library for running a small agent
entirely on an ESP32-S3 or ESP32-S31. Your firmware embeds the model and keeps
its inputs and results on the chip.
What it does today
Embedderturns text into vectors on the chip.Knowledgestores each vector with its original text and an application payload.Agent::promptfinds the stored texts closest to a query.Agent::turnuses a handler you provide to run a command and can keep context for a follow-up.
Quick start
Add the library to your firmware as a Git dependency.
[dependencies]
esp-agent = { git = "https://github.com/veeso/esp-agent" }
Download a model into model/ in your firmware
crate. Embed it with model! and create an Embedder to turn text into a vector.
use esp_agent::{Embedder, Model, model};
static POTION: Model = model!("model");
let mut embedder = Embedder::new(POTION);
embedder.config_mut().max_length = 128;
let vector = embedder.embed("Qdrant is a vector search engine written in Rust.");
To search text, insert it with a payload into a Knowledge store and query
that store through an agent. See Search for ranking and buffer reuse.
use esp_agent::{Agent, Embedder, Knowledge, Model, model};
static POTION: Model = model!("model");
let mut knowledge = Knowledge::new(Embedder::new(POTION));
knowledge.insert("Paris is the capital of France.", 1);
knowledge.insert("Water boils at 100 degrees Celsius.", 2);
let agent = Agent::new(POTION, &knowledge).expect("the store is embedded with POTION");
let best = agent.prompt("Which city is France's capital?", 1);
To handle commands, enable conversation memory and pass your TurnHandler
implementation as home. The Turns guide shows a complete handler,
and the turn macros declare devices and commands
instead of writing one.
let mut agent = Agent::builder(POTION, &knowledge)
.context(2)
.build()
.expect("the store is embedded with POTION");
let outcome = agent.turn("Turn on the lamp", &mut home);
Firmware requirements
- Supply a global allocator, for example with
esp-alloc. - Size the application partition for the model and the rest of the firmware. In practice, Potion 2M needs a board with 16 MiB of flash. See Choose a model for model sizes.
The library leaves HAL selection, chip setup, and linker configuration to your firmware.
Build and test on a computer
With rustup and just installed, run these commands from the repository root.
The host recipes use standard Rust and just test downloads Potion 2M on first use.
rustup toolchain install 1.97 --profile minimal
just build_host
just test
To measure test coverage, install
cargo-llvm-cov and run
just coverage, which writes an LCOV report to lcov.info:
rustup component add llvm-tools-preview --toolchain 1.97
just coverage
Credits
esp-agent started as a fork of
static-models-bm by
qdrant-labs, created by
AstraBert. The tokenizer, the embedder, and the
idea of running static embedding models on bare metal all come from that work.
Huge thanks and the utmost respect to AstraBert for it.
AstraBert is also the author of
statembed, the reference that the
tokenizer and pooling are validated against.
License
esp-agent is licensed under the Apache License 2.0.
Available Models
esp-agent ships no model. Your firmware chooses which static embedding models
it needs and embeds them with model!.
Choose a model
These models use BERT WordPiece and a single F32 embedding table. The sizes cover the weights and compiled vocabulary. Budget separately for the rest of your firmware.
| Model | Model data in flash | Parameters | Hugging Face |
|---|---|---|---|
potion-base-2M | 7.64 MiB | 1,889,792 | Minish Lab |
pubmedbert-base-embeddings-2M | 7.90 MiB | 1,953,408 | NeuML |
potion-base-4M | 14.85 MiB | 3,779,584 | Minish Lab |
Start with potion-base-2M for general English search on a 16 MiB board. If
your application partition has room, potion-base-4M scores higher on
Minish Lab’s retrieval benchmarks. For biomedical English text,
try pubmedbert-base-embeddings-2M, which NeuML evaluated on
PubMed datasets.
Download a model
Download tokenizer.json and model.safetensors from the same revision.
Run this from your firmware crate to fetch the Potion 2M revision used by the
examples and tests.
base=https://huggingface.co/minishlab/potion-base-2M/resolve/389b9f64be5aa4ae7a6bc6fe95ef20ce485ae5da
mkdir -p model &&
curl --fail --location "$base/tokenizer.json" -o model/tokenizer.json &&
curl --fail --location "$base/model.safetensors" -o model/model.safetensors
Embed it
With Model and model imported from esp_agent, embed the directory and
rebuild your firmware. The path is relative to your firmware crate.
static POTION: Model = model!("model");
Use Embedder::new(POTION) to embed text. You can call model! multiple times
with different directories and create an Embedder for each model.
What the build checks
model! compiles tokenizer.json into a sorted binary vocabulary and reads the
embedding table in model.safetensors. The build fails if the table uses a data
type other than F32, contains non-finite weights, or its size disagrees with
its shape.
Switching models
Check that the rebuilt firmware fits the application partition before flashing.
Potion 4M alone occupies 14.85 MiB, so check the partition size even on a board
with 16 MiB of flash. Rebuild the embeddings in your store when you switch
models. Agent::new returns AgentError::ModelMismatch when the store was
embedded with another model.
Search
Semantic search finds the stored texts closest in meaning to a query. The firmware embeds the texts, embeds the query, and ranks the results on the chip.
What it is good for
- Look up an answer in an offline FAQ or manual.
- Match free text to a fixed set of intents or commands.
- Route a request to a handler based on the best match.
- Find near-duplicate log or sensor messages.
Each search scans the whole index, so search cost grows with the number of entries. Start with a corpus on the order of hundreds of entries and measure latency and heap use on your board. The static models mean-pool token vectors, so word order is lost. The models in this guide are for English text.
Two levels
Index::search(&query_vector, k) ranks vectors you supply. Each Hit gives
its score, insertion index, and payload. When you already have a
Knowledge store, you can access its index and look up the original text by
index.
let query = knowledge.embedder().embed("Which city is France's capital?");
for hit in knowledge.index().search(&query, 3) {
let text = knowledge.text(hit.index);
// hit.score, hit.payload, text
}
Agent::prompt(text, k) does that lookup for you. It embeds the query using the
store’s embedder and returns TextHit values with the score, index, text,
and payload. See the quick start for an example.
Ranking rules
The index ranks entries by descending cosine similarity and keeps insertion
order when scores tie. A k larger than the store returns every entry. A k
of zero returns no hits. A prompt with no known words scores every entry 0.0,
so the first entries inserted appear first.
Search without allocating
Keep a Scratch for the embedding buffers and a Vec::with_capacity(k) for
the hits. Agent::prompt_with fills both, and Index::search_into fills the
hits vector when you already have a query vector. Calls reuse the buffers and
allocate only if they need to grow. Use agent.knowledge().text(hit.index) to
borrow the original text for a hit from prompt_with.
extern crate alloc;
use alloc::vec::Vec;
use esp_agent::Scratch;
let mut scratch = Scratch::new();
let mut hits = Vec::with_capacity(3);
agent.prompt_with("Which city is France's capital?", 3, &mut scratch, &mut hits);
Example with the semantic search console
The example embeds Potion 2M and searches this corpus.
/// Number of closest sentences printed for each query.
pub(crate) const TOP_K: usize = 3;
/// Sentences the console searches. Each one is embedded once at startup.
pub(crate) const CORPUS: [&str; 8] = [
"The quick brown fox jumps over the lazy dog.",
"A fast auburn fox leaps above a sleepy hound.",
"Quarterly revenue grew 12% year over year.",
"Qdrant is a vector search engine written in Rust.",
"The ESP32-S3 is a dual-core microcontroller with Wi-Fi and Bluetooth.",
"Paris is the capital of France and sits on the river Seine.",
"Water boils at 100 degrees Celsius at sea level.",
"Rust guarantees memory safety without a garbage collector.",
];
At startup it embeds each sentence once and builds the agent.
let mut knowledge = Knowledge::with_capacity(embedder, CORPUS.len());
knowledge.extend(CORPUS.map(|text| (text, ())));
let agent = Agent::new(POTION, &knowledge).expect("the corpus is embedded with POTION");
For each query, it reuses its buffers, measures the search time, and prints the ranked sentences.
/// Prompts `agent` with `query` and prints the [`TOP_K`] closest indexed sentences.
fn answer<'a>(
agent: &Agent<'a, ()>,
query: &str,
scratch: &mut Scratch,
hits: &mut Vec<Hit<'a, ()>>,
) {
let start = Instant::now();
agent.prompt_with(query, TOP_K, scratch, hits);
let total_us = start.elapsed().as_micros();
println!("{total_us} us");
results::render_hits(hits, &CORPUS, |line| println!("{line}"));
println!();
}
From the repository root, run the command for your board.
just run_s3
# ESP32-S31
just run_s31
potion ready: 29528 tokens x 64 dims, table 7382 KiB in flash
indexed 8 sentences
Indexed sentences:
- The quick brown fox jumps over the lazy dog.
- A fast auburn fox leaps above a sleepy hound.
- ...
> The quick brown fox jumps over the lazy dog.
<timing> us
1. [<score>] The quick brown fox jumps over the lazy dog.
2. [<score>] A fast auburn fox leaps above a sleepy hound.
3. [<score>] ...
>
Turns
A turn handles one line of conversation and can run a command. Call
Agent::turn with the line and a TurnHandler supplied by your firmware.
What it is good for
Use turns to control devices from serial text or from text produced by a speech recognizer. The agent can ask which device the user means and let them say “it” in a follow-up. The command and its context are handled on the chip.
Who decides what
The agent handles the order of events in a turn and keeps conversation memory.
Your handler decides what the input means and how to act on it. When the
closest stored example has positive similarity, the agent passes its payload
as suggested. A search hit provides a hint only. parse validates the
original input, including every argument, before returning a command.
The handler
parseextracts aCommandwith an action and aTargetSelector.Explicitcarries a device name, alias, or group.Previousrefers to the target of the last successful command, as in “dim it”.resolve_targetslooks up an explicit selector in your device catalog. Each device has a stableTargetId.TargetMatch::Resolvednames the devices that act together,Ambiguousoffers alternatives for the user to choose from, andMissingindicates that the selector matched no device.matches_targetchecks whether a clarification reply identifies a device in the choices offered. Exactly one match is needed to continue.dispatchruns the action once on the resolved targets. It checks that every target ID still belongs to the catalog and returns a result or error.
Outcomes
Agent::turn returns a TurnOutcome that your firmware can use to respond.
| Outcome | Meaning |
|---|---|
Executed | The handler ran the action successfully and returned its result. |
Failed | The handler returned an error while running the action. |
Clarify | Ask the user to choose one of the returned targets. |
NeedTarget | Ask for a complete command with a more specific target. |
Unrecognized | The input did not parse as a command, and no question is pending. |
Conversation memory
Call Agent::builder(model, &knowledge).context(n).build() to keep up to n
choices for a pending question and up to n targets from the last successful
command. The default is zero, including when you use Agent::new. With memory
set to zero, explicit commands still work.
A successful dispatch replaces the remembered targets or clears them if the
whole list exceeds n. A failed dispatch preserves the previous targets.
“It” resolves directly when one target is remembered. If a group is remembered,
the agent asks the user to choose. With no remembered targets, it requests a
more specific command.
Each agent owns its conversation state. It can be cloned when its payload is
Clone, and each clone keeps an independent conversation. Agent never
implements Copy.
Declare the vocabulary instead
You do not need to write the handler by hand. targets! declares the devices
and the phrases that name them, and #[derive(TurnCommands)] declares the
commands on your action enum. The turn macros reference
covers every rule. The home assistant firmware declares both.
Example with the home assistant
The home-assistant firmware controls two simulated lamps. Its knowledge
store holds examples for turning a lamp on and setting its brightness. For
“Dim the lamp”, the firmware constructs BeginDim directly.
/// Knowledge store examples for turning a lamp on and setting its brightness.
pub const EXAMPLES: [(&str, Action); 2] = [
("Turn on the lamp", Action::TurnOn),
(
"Dim the lamp to 30 percent",
Action::SetBrightness {
level: Percent::new(30),
},
),
];
/// What the user can ask a lamp to do, with the arguments read from the original input.
#[derive(Debug, Clone, Copy, PartialEq, Eq, TurnCommands)]
#[commands(previous = "it")]
pub enum Action {
/// Switch the lamp on.
#[command("turn on {target}", "turn {target} on")]
TurnOn,
/// Set the brightness.
#[command("dim {target} to {level} percent", "dim {target} to {level}%")]
SetBrightness {
/// The new brightness.
level: Percent,
},
/// Ask which brightness the user wants. The firmware builds it from a shorter command.
BeginDim,
}
/// A brightness in percent, from 0 to 100.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Percent(u8);
impl Percent {
/// Creates a brightness at compile time.
///
/// # Panics
///
/// Panics if `value` is above 100.
pub const fn new(value: u8) -> Self {
assert!(value <= 100, "a percentage is at most 100");
Self(value)
}
}
impl FromStr for Percent {
type Err = ();
/// Accepts decimal digits only, from 0 through 100.
fn from_str(text: &str) -> Result<Self, ()> {
if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(());
}
text.parse::<u8>()
.ok()
.filter(|value| *value <= 100)
.map(Self)
.ok_or(())
}
}
The firmware embeds the examples and gives the agent room for two targets.
let mut knowledge = Knowledge::with_capacity(Embedder::new(POTION), EXAMPLES.len());
knowledge.extend(EXAMPLES);
let mut agent = Agent::builder(POTION, &knowledge)
.context(CONTEXT_TARGETS)
.build()
.expect("the examples are embedded with POTION");
The catalog lists the lamps. “Lamp” is ambiguous and “living room lights” is a group containing both lamps.
/// The lamps, the phrases that name them, and the replies that pick one out of a question.
static LAMPS: TargetCatalog = targets! {
device Desk = 1, "desk lamp" {
replies ["desk", "desk one"];
}
device Floor = 2, "floor lamp" {
replies ["floor", "floor one"];
}
choose "lamp" from [Desk, Floor];
group ["living room", "living room lights"] = [Desk, Floor];
};
The handler forwards parsing and lookups to the declarations. It also keeps one firmware-owned question, described below.
impl TurnHandler<Action> for Home {
type Success = Done;
type Error = HomeError;
fn parse<'a>(
&self,
input: &'a str,
_suggested: Option<&Action>,
) -> Option<Command<'a, Action>> {
parse_command(input).or_else(|| {
let lamp = self.awaiting_brightness?;
Some(Command {
action: Action::SetBrightness {
level: parse_level(input)?,
},
target: TargetSelector::Explicit(LAMPS.name(lamp)?),
})
})
}
fn resolve_targets(&self, selector: &str) -> TargetMatch {
LAMPS.resolve_targets(selector)
}
fn matches_target(&self, target: TargetId, reply: &str) -> bool {
LAMPS.matches_target(target, reply)
}
fn dispatch(&mut self, action: Action, targets: &[TargetId]) -> Result<Done, HomeError> {
if targets.is_empty() {
return Err(HomeError::NoTarget);
}
if let Some(unknown) = targets.iter().find(|id| self.lamp(**id).is_none()) {
return Err(HomeError::UnknownTarget(*unknown));
}
if action == Action::BeginDim {
let &[lamp] = targets else {
return Err(HomeError::NameOneLamp);
};
self.awaiting_brightness = Some(lamp);
} else {
for lamp in self
.lamps
.iter_mut()
.filter(|lamp| targets.contains(&lamp.id))
{
match action {
Action::SetBrightness { level } => lamp.brightness = level.0,
Action::TurnOn | Action::BeginDim => lamp.on = true,
}
}
self.awaiting_brightness = None;
}
Ok(Done {
action,
targets: targets.to_vec(),
})
}
}
From the repository root, flash the example with the command for your board.
just run_s3 home-assistant
# ESP32-S31
just run_s31 home-assistant
Try these commands in the serial monitor. The agent asks which lamp, and “it” refers to the last lamp that a command acted on.
> Dim the lamp to 37%
Which lamp, the desk lamp or the floor lamp?
> The desk one
The desk lamp is at 37 percent.
> Turn it on
The desk lamp is on.
> Turn on the living room lights
The living room lights are on.
> Dim it to 12%
Which lamp, the desk lamp or the floor lamp?
> Floor
The floor lamp is at 12 percent.
A question that the firmware owns
The agent asks which target a command means. It cannot know that a command is
missing a value, so your firmware asks for that. “Dim the lamp” is a short
command that the firmware turns into the unannotated BeginDim action. After
the agent resolves the lamp, dispatching BeginDim records the lamp and returns
a prompt. It changes no hardware.
/// Reads a complete command, or the short "dim <lamp>" that starts the brightness question.
fn parse_command(input: &str) -> Option<Command<'_, Action>> {
Action::parse_command(input).or_else(|| begin_dim(input))
}
/// Recognizes "dim <lamp>" when the lamp is a known selector or the word "it".
fn begin_dim(input: &str) -> Option<Command<'_, Action>> {
let rest = strip_prefix_ignore_case(trim_sentence(input), "dim ")?.trim();
let target = if rest.eq_ignore_ascii_case("it") {
TargetSelector::Previous
} else if LAMPS.contains_selector(rest) {
TargetSelector::Explicit(rest)
} else {
return None;
};
Some(Command {
action: Action::BeginDim,
target,
})
}
/// Tells whether the line opens with a command verb, whether or not it is a valid command.
fn starts_like_command(input: &str) -> bool {
["dim ", "turn "]
.iter()
.any(|verb| strip_prefix_ignore_case(input, verb).is_some())
}
/// Reads a bare brightness such as "37 percent" or "37%".
fn parse_level(input: &str) -> Option<Percent> {
let input = trim_sentence(input);
strip_suffix_ignore_case(input, " percent")
.or_else(|| strip_suffix_ignore_case(input, "%"))?
.trim()
.parse()
.ok()
}
The conversation looks like this. An invalid value repeats the question.
> Dim the lamp
Which lamp, the desk lamp or the floor lamp?
> The desk one
To what brightness?
> 150 percent
To what brightness?
> 37 percent
The desk lamp is at 37 percent.
The firmware keeps this state next to its devices, one value for each
conversation, and the question is independent of the agent’s memory limit. A
new command abandons it, even a command that needs a clarification, names an
unknown lamp, or is malformed such as “Dim the floor lamp to 150%”, so a later “37 percent” cannot revive the old question.
If the serial line is too long, the firmware asks for a shorter command. A
command verb in the retained prefix still cancels the brightness question.
Classifying a new command and clearing the question happens in the firmware’s
respond before it calls Agent::turn, because parse borrows the handler
immutably.
> Dim the lamp to 37%
Which lamp, the desk lamp or the floor lamp?
> Dim desk lamp
To what brightness?
> Turn on the floor lamp
The floor lamp is on.
> 37 percent
Sorry, I did not understand. Try "Turn on the lamp".
A group has no single brightness question, so “Dim the living room lights” replies that you must name one lamp. A complete command still works on a group.
The same walkthrough runs on your computer with just test in the
home assistant integration test.
Turn macros
Two independent macros declare the vocabulary of a conversation. targets!
builds a catalog of devices, and #[derive(TurnCommands)] builds a typed parser
for an action enum. Use either one alone or both together. The
Turns guide shows how a turn uses them.
targets!
targets! evaluates to a TargetCatalog that can initialize a static.
/// The lamps, the phrases that name them, and the replies that pick one out of a question.
static LAMPS: TargetCatalog = targets! {
device Desk = 1, "desk lamp" {
replies ["desk", "desk one"];
}
device Floor = 2, "floor lamp" {
replies ["floor", "floor one"];
}
choose "lamp" from [Desk, Floor];
group ["living room", "living room lights"] = [Desk, Floor];
};
| Declaration | Meaning |
|---|---|
device Name = id, "display name" { .. } | A device with a stable TargetId, a display name, and optional reply aliases. |
replies ["alias", ..]; | Phrases that pick this device out of a clarification only. |
choose "phrase" from [Name, ..]; | A phrase that names several devices, so the agent asks the user to choose one. |
group ["phrase", ..] = [Name, ..]; | Phrases that select every member at once, in one dispatch. |
Three kinds of phrase
- The display name of a device selects that device in a command and in a
reply.
resolve_targetsreturnsResolvedwith its ID. - A
choosephrase makesresolve_targetsreturnAmbiguouswith the members. Agroupphrase returnsResolvedwith every member. These are the two meanings of a selector with several IDs: choose one, or act on all. - A reply alias is only compared inside
matches_target, among the devices a clarification offered. “Desk one” answers the question but is not a command target, soresolve_targets("desk one")isMissing.
Use contains_selector(text) in a handwritten parser to check whether a device
name, choice, or group matches without allocating a target list.
Two devices can share a reply alias. If a reply matches both, the question
stays open. Use name(id) to turn a TargetId back into its display name.
How a conversation uses the catalog
The diagram follows the catalog above through the conversation from the Turns guide. The agent asks the catalog about each selector in a command, and about each reply to a question it asked. Desk is ID 1 and Floor is ID 2.
sequenceDiagram
actor User
participant Agent
participant Catalog as LAMPS catalog
participant Callback as dispatch callback
User->>Agent: Dim the lamp to 37%
Agent->>Catalog: resolve_targets("the lamp")
Note right of Catalog: a choose phrase
Catalog-->>Agent: Ambiguous([1, 2])
Agent-->>User: Which lamp, the desk lamp or the floor lamp?
User->>Agent: The desk one
Note over Agent: Not a command, so it answers the question
Agent->>Catalog: matches_target(1, "The desk one")
Catalog-->>Agent: true, the reply alias "desk one"
Agent->>Catalog: matches_target(2, "The desk one")
Catalog-->>Agent: false
Agent->>Callback: dispatch(SetBrightness 37, [1])
Callback-->>User: The desk lamp is at 37 percent.
User->>Agent: Turn on the living room lights
Agent->>Catalog: resolve_targets("the living room lights")
Note right of Catalog: a group phrase
Catalog-->>Agent: Resolved([1, 2])
Agent->>Callback: dispatch(TurnOn, [1, 2]) once
Callback-->>User: The living room lights are on.
User->>Agent: Turn on desk one
Agent->>Catalog: resolve_targets("desk one")
Note right of Catalog: a reply alias is not a command target
Catalog-->>Agent: Missing
Agent-->>User: Please give the full command and name a lamp.
A choose phrase sends the user back a question, a group phrase runs one
dispatch on every member, and a reply alias only works as an answer.
Normalization
Every lookup compares ASCII case-insensitively after trimming outer whitespace
and trailing sentence punctuation (., !, ?), and ignores one leading
“the”. “THE DESK LAMP?!” therefore selects the desk lamp. The macro applies the
same normalization when it checks your declarations.
Build-time checks
The macro fails the build, pointing at the declaration, for a duplicate ID or
device name, a selector that collides with another after normalization, an
empty selector, a member that is not a declared device or is listed twice, and
a choose or group with no members. Each group needs at least one phrase.
Each reply alias must contain text after normalization. Devices may share an alias.
#[derive(TurnCommands)]
The derive implements TurnCommands::parse_command for an enum. Each variant
with #[command("pattern", ..)] attributes can be spelled by the user.
Variants without the attribute are skipped so handwritten code can build them.
/// Knowledge store examples for turning a lamp on and setting its brightness.
pub const EXAMPLES: [(&str, Action); 2] = [
("Turn on the lamp", Action::TurnOn),
(
"Dim the lamp to 30 percent",
Action::SetBrightness {
level: Percent::new(30),
},
),
];
/// What the user can ask a lamp to do, with the arguments read from the original input.
#[derive(Debug, Clone, Copy, PartialEq, Eq, TurnCommands)]
#[commands(previous = "it")]
pub enum Action {
/// Switch the lamp on.
#[command("turn on {target}", "turn {target} on")]
TurnOn,
/// Set the brightness.
#[command("dim {target} to {level} percent", "dim {target} to {level}%")]
SetBrightness {
/// The new brightness.
level: Percent,
},
/// Ask which brightness the user wants. The firmware builds it from a shorter command.
BeginDim,
}
/// A brightness in percent, from 0 to 100.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Percent(u8);
impl Percent {
/// Creates a brightness at compile time.
///
/// # Panics
///
/// Panics if `value` is above 100.
pub const fn new(value: u8) -> Self {
assert!(value <= 100, "a percentage is at most 100");
Self(value)
}
}
impl FromStr for Percent {
type Err = ();
/// Accepts decimal digits only, from 0 through 100.
fn from_str(text: &str) -> Result<Self, ()> {
if text.is_empty() || !text.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(());
}
text.parse::<u8>()
.ok()
.filter(|value| *value <= 100)
.map(Self)
.ok_or(())
}
}
#[commands(previous = "it")] on the enum names the word that means the
previous target. Without it, every target is explicit.
Patterns
A pattern is literals and captures in braces. Literals match ignoring ASCII
case, and {{ and }} write a literal brace.
{target}captures a non-empty slice of the input and becomesTargetSelector::Explicit, orPreviouswhen it equals the configured word.{field}captures the text of a named field and converts it with the field type’score::str::FromStr. A value it rejects means the input is not that command. Any firmware type works, and its parser owns its cost.
A pattern matches the whole input, after trimming outer whitespace and
trailing sentence punctuation. The pattern itself is trimmed the same way, so
"is {target} on?" matches “Is the lamp on” and “Is the lamp on?”. Text around a capture is trimmed too. “Dim it to
2% later” is not a command, and neither is “Dim it to 101%” for a Percent
that stops at 100.
When a literal such as “ to ” also occurs inside the target, the matcher tries each possible delimiter and validates typed fields as it goes. A rejected field skips the remaining captures for that split. “Dim entrée to hall to 100 percent” captures the target “entrée to hall”. Input that two patterns or two splits both accept is declined as ambiguous rather than guessed.
Build-time checks
The derive rejects, with a message pointing at the attribute or field, an
unknown capture name, a field that no capture fills, a pattern with no
{target}, a repeated capture, two adjacent captures with no literal between
them, a duplicate pattern in the enum after ignoring case, more than eight
captures, a field named target, and a tuple variant. Each #[command(..)]
attribute must include at least one pattern.
The adapter
Action::handler(&CATALOG, callback) returns a TurnHandler that parses with
the derived parser, looks targets up in the catalog, and forwards dispatch to
callback, which keeps your success and error types. The adapter ignores the
agent’s suggestion and always checks the input. For a handler of your own, call
Action::parse_command from parse, as the
firmware example does.
Allocation
Both macros compile their syntax on the build host. On the device, the catalog
is read-only data and the parser borrows its input, so matching allocates
nothing. resolve_targets returns an owned list, and so does the agent’s
turn.