//! Declared builtin signatures, enforced at dispatch and read by the ontology.
//!
//! # Why this exists
//!
//! Six defects surfaced in one week of benchmarking, and they were one design
//! property observed six times:
//!
//! | Call | Answered |
//! | --- | --- |
//! | `round(4.966, 2)` | `5` — the digits argument was accepted and discarded |
//! | `mean \| round(2)` | `2` — the digit count was taken as the subject |
//! | `env(name, default)` | the default was accepted and discarded |
//! | `echo $HOME` (compat) | `null`, exit 0 |
//! | `1 / 0`, `1 % 0` | `inf` at exit 0; a panic |
//! | `db_json_to_sqlite("x")` | `false`, exit 0 |
//!
//! Every one is a call the builtin could not honour, answered with a value
//! instead of a refusal. The cause is the calling convention: a builtin is
//! `fn(Vec<Value>, Option<Value>) -> Result<Value>`, which carries no schema,
//! so nothing can check arity or types before the body runs and the body is
//! free to ignore what it was handed.
//!
//! # And why the ontology could not catch it
//!
//! The discovery surface was a *second*, independent description. Nineteen
//! builtins have hand-written definitions in `agent_api`; the rest are
//! generated from the builtin's **name** — `describe_builtin_name` splits on
//! `_`, treats the first word as a module and title-cases the rest. So
//! `db_json_to_sqlite` is documented as "Database: json to sqlite" with an
//! empty parameter list, and `max` was documented as "Get maximum value,
//! `max() -> Number`" while refusing the array that description implies.
//!
//! An agent asking the shell what a function does was being told what its name
//! looks like. That is name-based reasoning, and it produced exactly the class
//! of bug it always produces.
//!
//! # The fix
//!
//! One declaration per builtin, used for both jobs. [`validate`] runs at
//! dispatch, so a call that does not match is refused before the body sees it;
//! the same declaration supplies the ontology, so the catalogue cannot describe
//! a function that does not exist.
//!
//! This is an incremental, source-reviewed migration. Builtins without a
//! declaration retain their legacy dispatch behavior. The coverage inventory
//! in `examples/signature_inventory.rs` lists the remaining implementations.
//! `tests/declared_signatures.rs` asserts that every declared
//! builtin is real, that its ontology entry comes from the declaration rather
//! than from its name, and that violating a declaration is refused.
use crate::value::Value;
/// The shape a parameter or a pipeline subject accepts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Ty {
Any,
Int,
Numeric,
Str,
Bool,
Array,
Record,
Lambda,
/// An array, or a string treated as its lines.
///
/// `Numeric` is the precedent: a union in the lattice because the
/// builtins genuinely accept either. `sort`, `unique` and `uniq` all
/// split a piped string on newlines on purpose -- `cat f | sort` is
/// the oldest idiom in the shell -- and their own error text already
/// said "input must be an array or string". Declaring them `Array`
/// deleted the text form, and it took a harness comparing every
/// declaration against its own body to notice.
Sequence,
}
impl Ty {
/// The name used in a signature string and in a refusal.
pub fn as_str(self) -> &'static str {
match self {
Ty::Any => "Any",
Ty::Int => "Int",
Ty::Numeric => "Number",
Ty::Str => "String",
Ty::Bool => "Bool",
Ty::Array => "Array",
Ty::Record => "Record",
Ty::Lambda => "Lambda",
Ty::Sequence => "Array | String",
}
}
/// Whether `name` is a type a signature shows as one word: `String`,
/// `Number`, and so on. Secret redaction asks this, so that `token: String`
/// in a signature is not taken for a token whose value is `String`.
pub fn is_type_name(name: &str) -> bool {
const ALL: [Ty; 9] = [
Ty::Any,
Ty::Int,
Ty::Numeric,
Ty::Str,
Ty::Bool,
Ty::Array,
Ty::Record,
Ty::Lambda,
Ty::Sequence,
];
ALL.iter().any(|t| t.as_str() == name)
}
fn accepts(self, v: &Value) -> bool {
match self {
Ty::Any => true,
Ty::Int => matches!(v, Value::Int(_)),
Ty::Numeric => matches!(v, Value::Int(_) | Value::Float(_)),
Ty::Str => matches!(v, Value::Str(_) | Value::Uri(_)),
Ty::Bool => matches!(v, Value::Bool(_)),
Ty::Array => matches!(v, Value::Array(_)),
Ty::Record => matches!(v, Value::Record(_) | Value::Table(_)),
Ty::Lambda => matches!(v, Value::Lambda(_) | Value::AsyncLambda(_)),
Ty::Sequence => matches!(v, Value::Array(_) | Value::Str(_) | Value::Uri(_)),
}
}
}
/// One declared parameter.
#[derive(Debug, Clone, Copy)]
pub struct Param {
pub name: &'static str,
pub ty: Ty,
pub required: bool,
/// Inclusive bounds for an `Int`, when the builtin has them. `round`'s
/// digits argument is the reason this exists: it silently accepted 99.
pub range: Option<(i64, i64)>,
/// This parameter absorbs all remaining arguments. Only meaningful on the
/// last one. `pick("name", "size", "modified")` is why: a fixed parameter
/// list cannot describe it, and declaring a fixed arity would have removed
/// the form E2's corpus uses.
pub variadic: bool,
pub doc: &'static str,
}
/// A builtin's declared interface.
#[derive(Debug, Clone, Copy)]
pub struct Signature {
pub name: &'static str,
/// The catalogue category, when the name-derived one is wrong.
///
/// `categorize_builtin` works from the name, so the array `zip` was filed
/// under **Archive** and `uniq`/`sort` under **FileSystem**. Categories are
/// how an agent browses (`ontology_describe("Array")` lists a category), so
/// a wrong one does not just mislabel a builtin, it hides it from the list
/// it belongs in. `None` keeps the derived category.
pub category: Option<&'static str>,
/// This builtin only works with a piped subject; the direct-call form is
/// not supported.
///
/// `uniq([1, 1, 2])` failed with `E_UNKNOWN` and "uniq: no input provided"
/// -- the one code an agent is told not to reason about, for a condition
/// that is entirely knowable before the body runs.
pub subject_required: bool,
/// Other spellings that dispatch to the same implementation.
///
/// Needed because a builtin is reachable under several names and an agent
/// may write any of them: `from_json`/`from-json`, `group_by`/`group`,
/// `mean`/`avg`, `to_string`/`str`. A declaration keyed on one spelling
/// would enforce nothing for the others and would leave the catalogue
/// describing them by name-splitting.
pub aliases: &'static [&'static str],
/// What the pipeline supplies, for a builtin that takes a subject.
pub subject: Option<Ty>,
pub params: &'static [Param],
pub returns: &'static str,
pub doc: &'static str,
/// Worked examples: the code, and what it evaluates to. These are asserted
/// to be non-empty for every declaration, because an example is the part an
/// agent copies.
pub examples: &'static [(&'static str, &'static str)],
}
impl Signature {
/// The signature as an agent reads it: `round(digits: Int) -> Number`.
pub fn render(&self) -> String {
let params = self
.params
.iter()
.map(|p| match (p.required, p.variadic) {
(_, true) => format!("{}...: {}", p.name, p.ty.as_str()),
(true, false) => format!("{}: {}", p.name, p.ty.as_str()),
(false, false) => format!("{}?: {}", p.name, p.ty.as_str()),
})
.collect::<Vec<_>>()
.join(", ");
match self.subject {
Some(s) => format!(
"{} | {}({}) -> {}",
s.as_str(),
self.name,
params,
self.returns
),
None => format!("{}({}) -> {}", self.name, params, self.returns),
}
}
}
const fn req(name: &'static str, ty: Ty, doc: &'static str) -> Param {
Param {
name,
ty,
required: true,
range: None,
variadic: false,
doc,
}
}
const fn opt(name: &'static str, ty: Ty, doc: &'static str) -> Param {
Param {
name,
ty,
required: false,
range: None,
variadic: false,
doc,
}
}
const fn opt_range(name: &'static str, ty: Ty, lo: i64, hi: i64, doc: &'static str) -> Param {
Param {
name,
ty,
required: false,
range: Some((lo, hi)),
variadic: false,
doc,
}
}
/// Like [`rest`], but zero values are allowed: `wc()` and `wc("-l")` are both
/// calls of one builtin.
const fn opt_rest(name: &'static str, ty: Ty, doc: &'static str) -> Param {
Param {
name,
ty,
required: false,
range: None,
variadic: true,
doc,
}
}
/// A parameter that absorbs every remaining argument.
const fn rest(name: &'static str, ty: Ty, doc: &'static str) -> Param {
Param {
name,
ty,
required: true,
range: None,
variadic: true,
doc,
}
}
/// The declared set.
///
/// Deliberately small. Every entry here is either a builtin that answered a
/// call it could not honour, or one of the everyday verbs the benchmark corpus
/// actually reaches for. Growing this list is the migration; the mechanism does
/// not depend on its size.
pub static SIGNATURES: &[Signature] = &[
Signature {
name: "file_backup", category: None, subject_required: false, aliases: &["backup_file"], subject: Some(Ty::Str),
params: &[opt("suffix", Ty::Str, "default .bak; nonempty filename suffix without separators, colon, controls or trailing dot/space")], returns: "Record",
doc: "Direct file_backup(path,suffix?) or path | file_backup(suffix?). Copy a regular file, including binary content, to path plus suffix and return resolved path, backup, bytes and success. Validate suffixes before effects; refuse non-file destinations and a destination resolving to the source. Resolve both paths against the workspace and guard both targets. Bound source bytes to 64 MiB, including growth during copying. Stream through an exclusively created sibling file, preserve source permissions and atomically replace the destination. Snapshot the destination for active transactions; clean the owned sibling on failure. Filesystem errors are coded.",
examples: &[(r#"let d = fs_tempdir("ae_backup"); let f = d + "/x"; file_write(f, "abc"); let result = file_backup(f); rmdir(d, true); result.bytes"#, "3"), (r#"let d = fs_tempdir("ae_backup"); let f = d + "/x"; file_write(f, "abc"); let result = f | backup_file(".save"); rmdir(d, true); result.success"#, "true")],
},
Signature {
name: "bat", category: None, subject_required: false, aliases: &["bat_view"], subject: None,
params: &[req("path", Ty::Str, "literal regular UTF-8 file path")], returns: "String",
doc: "Read plain file text natively and preserve all line endings. Resolve relative paths against the workspace and guard the actual read target. Bound regular UTF-8 reads to 64 MiB. Reject pipeline input, extra arguments and invalid paths; filesystem failures are coded. Plain output no longer depends on an external bat executable, its configuration or lossy UTF-8 decoding. File paths are literal, including names beginning with a dash.",
examples: &[(r#"let d = fs_tempdir("ae_bat"); let f = d + "/x"; file_write(f, "plain"); let result = bat(f); rmdir(d, true); result"#, r#""plain""#)],
},
Signature {
name: "file_diff", category: None, subject_required: false, aliases: &["diff_files"], subject: None,
params: &[req("path1", Ty::Str, "first regular UTF-8 file"), req("path2", Ty::Str, "second regular UTF-8 file")], returns: "Record",
doc: "Compare two direct file paths line by line at equal positions, returning original paths, line counts, differences, diff_count and identical. Each difference has a one-based line and type changed/added/deleted with old/new fields as applicable. This is positional comparison, not an edit-distance diff. CRLF and final line terminators do not affect line equality; identical describes line contents rather than byte identity. Resolve relative paths against the workspace and guard both actual read targets. Bound each file read to 64 MiB and differences to 10000 entries. Reject pipeline input and invalid paths; filesystem failures are coded. Iterate line references without collecting full line lists and move the difference array into the result without cloning it.",
examples: &[(r#"let d = fs_tempdir("ae_diff"); let a = d + "/a"; let b = d + "/b"; file_write(a, "same"); file_write(b, "same\n"); let result = file_diff(a, b); rmdir(d, true); result.identical"#, "true"), (r#"let d = fs_tempdir("ae_diff"); let a = d + "/a"; let b = d + "/b"; file_write(a, "a\nb"); file_write(b, "a\nc\nd"); let result = diff_files(a, b); rmdir(d, true); result.diff_count"#, "2")],
},
Signature {
name: "k8s_get",
category: None,
subject_required: false,
aliases: &["kubectl_get"],
subject: None,
params: &[req("resource", Ty::Str, "resource type, or type/name, e.g. pods or deployment/web"), opt("namespace", Ty::Str, "namespace; omitted uses kubectl's default")],
returns: "Record",
doc: "kubectl get <resource> -o json as a Record (a List for a collection). Arguments are validated before kubectl runs and are never read as flags: a leading '-' is refused. Runs with a 30 s deadline; output over 16 MiB is refused. A failure is E_TOOL_FAILED carrying the stderr tail; a missing kubectl is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_get(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_get("pods", "-A") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_apply",
category: None,
subject_required: false,
aliases: &["kubectl_apply"],
subject: None,
params: &[req("file", Ty::Str, "local manifest file inside the workspace; URLs are refused"), opt("namespace", Ty::Str, "namespace for the apply")],
returns: "String",
doc: "kubectl apply -f <file>, returning kubectl's report. The manifest is read through the workspace guard before kubectl is given its resolved path; a URL is refused because kubectl would fetch it outside that guard. This changes the cluster, and the network effect is not approval-gated in agent mode. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_apply(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_apply("https://example.invalid/app.yaml") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_delete",
category: None,
subject_required: false,
aliases: &["kubectl_delete"],
subject: None,
params: &[req("resource", Ty::Str, "resource type, e.g. pod or deployment"), req("name", Ty::Str, "object name"), opt("namespace", Ty::Str, "namespace for the object")],
returns: "String",
doc: "kubectl delete <resource> <name>, gated as destructive: in agent mode it needs approval before kubectl runs. Names are validated and never read as flags. Irreversible. Runs with a 30 s deadline; a failure is E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_delete("pods", "-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_delete("pods", "web", 5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_describe",
category: None,
subject_required: false,
aliases: &["kubectl_describe"],
subject: None,
params: &[req("resource", Ty::Str, "resource type, e.g. pod"), req("name", Ty::Str, "object name"), opt("namespace", Ty::Str, "namespace for the object")],
returns: "String",
doc: "kubectl describe <resource> <name> as text. Output over 4 MiB is refused, so a noisy object cannot exhaust memory. Names are validated and never read as flags. Runs with a 30 s deadline; a failure is E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_describe("pod", "-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_describe("pod", "web", 5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_logs",
category: None,
subject_required: false,
aliases: &["kubectl_logs"],
subject: None,
params: &[req("pod", Ty::Str, "pod name"), opt("namespace", Ty::Str, "namespace of the pod"), opt_range("tail", Ty::Int, 1, 10000, "lines from the end, 1 to 10000")],
returns: "String",
doc: "The last lines of a pod's logs. Always bounded: tail defaults to 200 lines and cannot exceed 10000, and output over 4 MiB is refused. The pod name is validated and never read as a flag. Runs with a 30 s deadline; a failure is E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_logs("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_logs("web", "default", 0) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_exec",
category: None,
subject_required: false,
aliases: &["kubectl_exec"],
subject: None,
params: &[req("pod", Ty::Str, "pod name"), req("command", Ty::Array, "argv: an Array of Strings run in the container; a shell string is refused"), opt("namespace", Ty::Str, "namespace of the pod")],
returns: "String",
doc: "Run argv in a pod with kubectl exec. The command is an Array of Strings, executed directly and never through a shell; a String is refused rather than split on spaces. Gated as exec: in agent mode it needs approval before kubectl runs. Output over 4 MiB is refused. Runs with a 30 s deadline; a failure is E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_exec("web", "id") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_exec("web", []) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_pods",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("namespace", Ty::Str, "namespace; omitted lists the default namespace")],
returns: "Record",
doc: "Pods as kubectl get pods -o json returns them (a List Record). Takes an optional namespace; failures are E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_pods("-A") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_pods(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_services",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("namespace", Ty::Str, "namespace; omitted lists the default namespace")],
returns: "Record",
doc: "Services as kubectl get services -o json returns them (a List Record). Takes an optional namespace; failures are E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_services("-A") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_services(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_deployments",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("namespace", Ty::Str, "namespace; omitted lists the default namespace")],
returns: "Record",
doc: "Deployments as kubectl get deployments -o json returns them (a List Record). Takes an optional namespace; failures are E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_deployments("-A") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_deployments(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_namespaces",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Namespaces as kubectl get namespaces -o json returns them (a List Record). Takes no arguments; failures are E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_namespaces("default") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_namespaces(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_nodes",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Nodes as kubectl get nodes -o json returns them (a List Record). Takes no arguments; failures are E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_nodes("default") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_nodes(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_events",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("namespace", Ty::Str, "namespace; omitted lists the default namespace")],
returns: "Record",
doc: "Events as kubectl get events -o json returns them (a List Record). Output over 16 MiB is refused, so narrow the namespace on a busy cluster. Failures are E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_events("-A") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_events(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_configmaps",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("namespace", Ty::Str, "namespace; omitted lists the default namespace")],
returns: "Record",
doc: "ConfigMaps as kubectl get configmaps -o json returns them (a List Record). Takes an optional namespace; failures are E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_configmaps("-A") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_configmaps(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_secrets",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("namespace", Ty::Str, "namespace; omitted lists the default namespace")],
returns: "Array",
doc: "Secret names only, as an Array of Strings. The kubectl query selects metadata.name and nothing else, so no secret value (.data) is read into the shell. Failures are E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_secrets("-A") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_secrets(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_ingresses",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("namespace", Ty::Str, "namespace; omitted lists the default namespace")],
returns: "Record",
doc: "Ingresses as kubectl get ingresses -o json returns them (a List Record). Takes an optional namespace; failures are E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_ingresses("-A") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_ingresses(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_rollout_status",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("deployment", Ty::Str, "deployment name"), opt("namespace", Ty::Str, "namespace of the deployment")],
returns: "String",
doc: "kubectl rollout status deployment/<name>, waiting at most 25 s for the rollout to finish. A rollout that does not complete is E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_rollout_status("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_rollout_status("web", 5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_rollout_restart",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("deployment", Ty::Str, "deployment name"), opt("namespace", Ty::Str, "namespace of the deployment")],
returns: "String",
doc: "kubectl rollout restart deployment/<name>, which replaces its pods. Gated as a process effect: in agent mode it needs approval before kubectl runs. Failures are E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_rollout_restart("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_rollout_restart("web", 5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_scale",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("deployment", Ty::Str, "deployment name"), req("replicas", Ty::Int, "desired replica count, 0 to 1000"), opt("namespace", Ty::Str, "namespace of the deployment")],
returns: "String",
doc: "Set a deployment's replica count with kubectl scale. The count must be 0 to 1000; a larger request is refused before kubectl runs. This changes the cluster, and the network effect is not approval-gated in agent mode. Failures are E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_scale("web", -1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_scale("web", "3") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_top_pods",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("namespace", Ty::Str, "namespace; omitted lists the default namespace")],
returns: "Array",
doc: "Pod CPU and memory from kubectl top pods, as an Array of Records with the table's columns. Needs metrics-server on the cluster; without it kubectl fails and the failure is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_top_pods("-A") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_top_pods(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_top_nodes",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Node CPU and memory from kubectl top nodes, as an Array of Records with the table's columns. Needs metrics-server on the cluster; without it kubectl fails and the failure is E_TOOL_FAILED. Takes no arguments and no pipeline input.",
examples: &[
(r#"(try { k8s_top_nodes("-A") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_top_nodes(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_context",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("context", Ty::Str, "context to switch to; omitted reads the current context")],
returns: "String",
doc: "With no argument, the current kubeconfig context name, read locally. With a name, switches the kubeconfig's current context with kubectl config use-context, which rewrites the kubeconfig file. Failures are E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { k8s_context(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_context("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_contexts",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "The context names in the kubeconfig, as an Array of Strings, read locally without contacting a cluster. Takes no arguments and no pipeline input.",
examples: &[
(r#"(try { k8s_contexts("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_contexts(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "k8s_cluster_info",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "kubectl cluster-info as text, which contacts the cluster's API server. Output over 4 MiB is refused. Failures are E_TOOL_FAILED with the stderr tail. Takes no arguments and no pipeline input.",
examples: &[
(r#"(try { k8s_cluster_info("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { k8s_cluster_info(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "tokei_count",
category: None,
subject_required: false,
aliases: &["tokei"],
subject: None,
params: &[opt("path", Ty::Str, "a directory inside the workspace; defaults to the working directory")],
returns: "Record",
doc: "Runs tokei --output json on a path and returns its JSON report as a Record. The path must lie inside the workspace and must not begin with '-'. A nonzero exit or output that is not JSON is E_TOOL_FAILED; output over 16 MiB is refused. Deadline 2 minutes. A missing tokei is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { tokei_count(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { tokei_count("--sort") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "hyperfine_bench",
category: None,
subject_required: false,
aliases: &["hyperfine"],
subject: None,
params: &[rest("command", Ty::Str, "a command to benchmark; each is split into words and run without a shell")],
returns: "Record",
doc: "Benchmarks each command with hyperfine --shell=none and returns hyperfine's JSON export as a Record. --shell=none is used because hyperfine otherwise runs every command through a shell: here shell syntax (pipes, redirections, expansions) is not interpreted, and each command is split into words and run directly. Commands must not begin with '-'. The export goes through a temporary file, which is removed afterwards. A nonzero exit is E_TOOL_FAILED. Deadline 10 minutes; a killed hyperfine does not kill the commands it started. The benchmarked commands are project code, so the call is classified Exec. A missing hyperfine is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { hyperfine_bench(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { hyperfine_bench("-N", "true") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { hyperfine_bench() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "sd", category: None, subject_required: false, aliases: &["sd_replace"], subject: None,
params: &[req("pattern", Ty::Str, "Rust regex pattern"), req("replacement", Ty::Str, "regex replacement with capture expansion"), opt("text", Ty::Str, "required direct input; omitted with piped String")], returns: "String",
doc: "Replace all regex matches across a whole String using native Rust regex, consistently across hosts. Direct sd(pattern,replacement,text) or text | sd(pattern,replacement). Support numbered/named capture expansion, braces and $$ for a literal dollar. Preserve line endings; reuse owned text if there is no match. Reject invalid regex, missing or wrong input types, extra arguments and conflicting direct/piped input. This is pure text processing with no file editing or external process. The previous host-dependent literal fallback and ignored external failure status are removed.",
examples: &[(r#"sd("[a-z]+", "x", "abc 123 def")"#, r#""x 123 x""#), (r#""abc-12" | sd("(?P<word>[a-z]+)-([0-9]+)", "$word:$2:$$")"#, r#""abc:12:$""#)],
},
Signature {
name: "helm_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("namespace", Ty::Str, "namespace; omitted lists the kubeconfig's default namespace")],
returns: "Array",
doc: "helm list -o json as an Array of release Records. The namespace is a Kubernetes name and is passed as --namespace=, so it is never read as a flag. Contacts the cluster named by the kubeconfig. Output over 16 MiB is refused. Failures are E_TOOL_FAILED with the stderr tail; a missing helm is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | helm_list() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { helm_list("-A") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "helm_install",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("release", Ty::Str, "release name: letters, digits, '-' and '.'"),
req("chart", Ty::Str, "chart: a repository chart name, an OCI or URL reference, or a local path inside the workspace"),
opt("namespace", Ty::Str, "namespace for the release"),
opt("values", Ty::Record, "values to set: dotted keys mapped to String, Int, Float or Bool scalars"),
],
returns: "String",
doc: "helm install <release> <chart> with --namespace= and one --set=key=value per value, returning helm's report. Option-like names are refused, values are scalars only, and a string's commas are escaped. A local chart path that exists must lie inside the workspace. This creates resources in the cluster and is approval-gated in agent mode. Runs with a 15 minute deadline; a killed install can leave the release half done. Takes no pipeline input.",
examples: &[
(r#"(try { helm_install("-x", "nginx") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { helm_install("web") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { helm_install("web", "nginx", "-A") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { helm_install("web", "nginx", "default", {a: [1]}) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | helm_install("web", "nginx") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "helm_upgrade",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("release", Ty::Str, "release name: letters, digits, '-' and '.'"),
req("chart", Ty::Str, "chart: a repository chart name, an OCI or URL reference, or a local path inside the workspace"),
opt("namespace", Ty::Str, "namespace of the release"),
opt("values", Ty::Record, "values to set: dotted keys mapped to String, Int, Float or Bool scalars"),
],
returns: "String",
doc: "helm upgrade <release> <chart> with --namespace= and one --set=key=value per value, returning helm's report. The same argument rules as helm_install. This changes a running release in the cluster and runs chart hooks; its effect is Exec, so agent mode asks for approval. Runs with a 15 minute deadline. Takes no pipeline input.",
examples: &[
(r#"(try { helm_upgrade("-x", "nginx") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { helm_upgrade("web") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { helm_upgrade("web", "nginx", "-A") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { helm_upgrade("web", "nginx", "default", {a: [1]}) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | helm_upgrade("web", "nginx") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "helm_uninstall",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("release", Ty::Str, "release name: letters, digits, '-' and '.'"),
opt("namespace", Ty::Str, "namespace of the release"),
],
returns: "String",
doc: "helm uninstall <release> with --namespace=, returning helm's report. Removes the release and its resources from the cluster; approval-gated in agent mode. Runs with a 15 minute deadline. Takes no pipeline input.",
examples: &[
(r#"(try { helm_uninstall("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { helm_uninstall("web", "-A") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | helm_uninstall("web") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "helm_repos",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "helm repo list -o json as an Array of repository Records, read from helm's local configuration without contacting any repository. With no repositories added the answer is an empty Array. Takes no arguments and no pipeline input.",
examples: &[
(r#"(try { helm_repos("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | helm_repos() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "helm_search",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("keyword", Ty::Str, "text to find in the added repositories' charts")],
returns: "Array",
doc: "helm search repo <keyword> -o json: the matching charts in the repositories already added, as an Array of Records. It searches only those local indexes and never the Artifact Hub, so it does not reach the network. The keyword is never read as a flag. Takes no pipeline input.",
examples: &[
(r#"(try { helm_search("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { helm_search() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "helm_status",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("release", Ty::Str, "release name: letters, digits, '-' and '.'"),
opt("namespace", Ty::Str, "namespace of the release"),
],
returns: "Record",
doc: "helm status <release> --namespace= -o json as a Record: the release's status, revision, and notes. Contacts the cluster named by the kubeconfig. Failures are E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { helm_status("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { helm_status("web", "-A") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | helm_status("web") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "sed", category: None, subject_required: false, aliases: &["sed_replace"], subject: None,
params: &[req("pattern", Ty::Str, "Rust regex pattern"), req("replacement", Ty::Str, "regex replacement with $name, ${name}, $N and $$ capture expansion"), opt("text_or_options", Ty::Any, "required String text or file path in direct calls; optional options in pipeline calls"), opt("options", Ty::Record, "direct-call {global: Bool, file: Bool}; defaults true and false")], returns: "String|Record",
doc: "Regex substitution over a whole String, not separately per line. Direct sed(pattern,replacement,text,options?) or text | sed(pattern,replacement,options?). global defaults true; false replaces only the first match in the entire input. file defaults false; true treats the input String as a path and atomically edits a guarded regular UTF-8 file, bounded to 64 MiB on read, with an active transaction snapshot. File mode returns {file: original_path, status: modified}, including when no match exists. Text mode returns the substituted String, preserving line endings; reuse owned input when there is no match. Reject invalid regex, unknown options, non-Bool flags and conflicting direct/piped input before modifying files. Filesystem failures are coded. Regex replacement output is not capped by the file read limit.",
examples: &[(r#"sed("a", "x", "aba")"#, r#""xbx""#), (r#""aba" | sed("a", "x", {global: false, file: false})"#, r#""xba""#), (r#"sed("a", "x", "aba", {global: false})"#, r#""xba""#), (r#""aba" | sed("a", "x")"#, r#""xbx""#), (r#"let d = fs_tempdir("ae_sed"); let f = d + "/x"; file_write(f, "aba"); sed("a", "x", f, {file: true}); let result = cat(f); rmdir(d, true); result"#, r#""xbx""#)],
},
Signature {
name: "awk", category: None, subject_required: false, aliases: &["awk_process"], subject: None,
params: &[req("program", Ty::Str, "awk program: BEGIN/END blocks, pattern-action rules (/re/, comparisons, && || !), if/else, print and printf, assignments, fields, NR/NF/FS/OFS, and length/substr/index/tolower/toupper"), opt("text_or_options", Ty::Any, "required String text in direct calls; optional {fs: String} in pipeline calls"), opt("options", Ty::Record, "direct-call {fs: String}; default one space")], returns: "Array<String>",
doc: "Run a bounded awk subset over text lines, in process and without a shell. Direct awk(program,text,options?) or text | awk(program,options?). Supports BEGIN and END, pattern-action rules with POSIX ERE /re/ patterns (no backreferences), comparison and logical patterns, if/else, print (OFS between arguments, newline ORS) and printf with %s %d %i %x %c %f (optional .N on %f) and %%, assignments and ++/--, $0 through $NF, NF, NR, FS and OFS, concatenation, + - * / %, and length, substr, index, tolower and toupper. Strings from input compare numerically when they look like numbers. FS is one space (blanks split), one character, or a regex of several characters; an empty FS is refused. Output lines are the Array<String>. Anything outside the subset (getline, system, redirection, pipes, user functions, arrays, split/sub/gsub/match, ?:, loops, exit, next) is refused with E_BAD_ARG naming the construct. Bounds: program 64 KiB, input 64 MiB or 10,000,000 lines, output 64 MiB, and a step budget; exceeding one returns E_BUDGET_EXCEEDED. Input lines end at LF with a trailing CR removed.",
examples: &[(r#"awk("{print $2, $1}", "a b\nc d")"#, "[\"b a\", \"d c\"]"), (r#""keep a\nskip b" | awk("/keep/{print $2}")"#, r#"["a"]"#), (r#"awk("{print $2}", "a::b", {fs: "::"})"#, r#"["b"]"#), (r#""a,b" | awk("{print $2}", {fs: ","})"#, r#"["b"]"#)],
},
Signature {
name: "cut", category: None, subject_required: false, aliases: &["cut_columns"], subject: None,
params: &[req("delimiter", Ty::Str, "literal delimiter, including empty or multi-character strings"), req("fields", Ty::Any, "positive Int or comma-separated positive indices and ascending inclusive ranges"), opt("text", Ty::Str, "required direct text; omitted with piped String")], returns: "Array<String>",
doc: "Extract fields from each text line. Direct cut(delimiter,fields,text), or text | cut(delimiter,fields). Fields are one-based; preserve specification order and duplicates, and omit missing fields. Trim whitespace around comma-separated specifications; reject zero, negative, malformed, descending or unrepresentable fields. Bound expanded selections to 10000 entries before allocation. Split on a literal delimiter and join selected fields with it. Normalize line endings and omit a trailing empty line. Refuse conflicting direct text and pipeline input.",
examples: &[(r#"cut(",", "3,1,3", "a,b,c")"#, r#"["c,a,c"]"#), (r#""a::b::c\nx::y" | cut("::", "2-3")"#, r#"["b::c", "y"]"#), (r#""a,b" | cut(",", 1)"#, r#"["a"]"#)],
},
Signature {
name: "tail", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Any),
params: &[opt("count_or_path", Ty::Any, "nonnegative representable Int count (default 10), or a file String in the count-first direct form")], returns: "Any",
doc: "Return the last lines of a piped String, or read a UTF-8 file with tail(path,count?) or tail(count,path). Preserve both direct argument orders. Reject non-String input/path and invalid counts; zero yields empty output. Strip line terminators, normalize CRLF to LF and join without a trailing newline. Bound file reads to 64 MiB and validate read paths. Scan backwards and retain only the selected line references. A piped Array gives its last count elements, as last(count) does (default 10).",
examples: &[(r#""a\nb\nc" | tail"#, r#""a\nb\nc""#), (r#""a\nb\nc" | tail(2)"#, r#""b\nc""#), (r#"[1, 2, 3, 4] | tail(2)"#, "[3, 4]"),(r#"let d = fs_tempdir("ae_tail"); let f = d + "/x"; file_write(f, "a\nb\nc"); let result = tail(1, f); rmdir(d, true); result"#, r#""c""#)],
},
Signature {
name: "journalctl", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt_range("count", Ty::Int, 1, 1000, "entries to return, default 50"), opt("unit", Ty::Str, "systemd unit name such as sshd.service on Linux, or an event provider name such as Service Control Manager on Windows; a leading '-' is refused")], returns: "Array",
doc: "The most recent entries of the systemd journal on Linux, as an Array of Records of the journal's JSON fields, optionally of one unit. On macOS the rows are the newest count entries of the unified log from the last hour, read with log show --style ndjson, as Records of its fields, oldest first; unit is then a process name, matched exactly, and the call reads the last 16 MiB of output at most. On Windows the rows are the newest System event log entries, read with Get-WinEvent, as Records {time, provider, level, id, message}: count is the event limit and unit an event provider name; no matching events give []. Elsewhere the call is E_UNIMPLEMENTED after its arguments are checked. A line that is not JSON is E_TOOL_FAILED, never skipped. Output past 16 MiB is E_BUDGET_EXCEEDED. Takes no pipeline input.",
examples: &[
(r#"(try { journalctl(0) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { journalctl(5, "-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "lnav_open", category: None, subject_required: false, aliases: &["lnav"], subject: None,
params: &[req("path", Ty::Str, "an existing log file; a leading '-' is refused")], returns: "Record",
doc: "Open one log file in the lnav viewer. lnav is interactive: without a terminal on stdin and stdout, or in agent mode, the call is E_NO_UI and nothing is started. With a terminal the viewer runs until the person quits, and the result is {path}.",
examples: &[
(r#"(try { lnav_open("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { lnav_open(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "multitail_open", category: None, subject_required: false, aliases: &["multitail"], subject: None,
params: &[rest("files", Ty::Str, "existing log files, one to 16; a leading '-' is refused")], returns: "Record",
doc: "Tail several log files at once in the multitail viewer. multitail is interactive: without a terminal on stdin and stdout, or in agent mode, the call is E_NO_UI and nothing is started. With a terminal the viewer runs until the person quits, and the result is {files}.",
examples: &[
(r#"(try { multitail_open("-y", "x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { multitail_open("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "logrotate_run", category: None, subject_required: false, aliases: &["logrotate"], subject: None,
params: &[req("config", Ty::Str, "configuration file inside the workspace; a leading '-' is refused"), opt("force", Ty::Bool, "rotate even when not due, default false")], returns: "Record",
doc: "Run logrotate with a configuration file inside the workspace, returning {config, state, forced, stdout, stderr}. The configuration may not name a path that is absolute or contains '..', and may not use prerotate, postrotate, firstaction, lastaction, preremove, mail, mailfirst or maillast, which run programs or send mail. The state file is <config>.state beside it. A nonzero exit is E_TOOL_FAILED.",
examples: &[
(r#"(try { logrotate_run("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { logrotate_run("x", 1) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "tee", category: None, subject_required: false, aliases: &["tee_output"], subject: None,
params: &[req("path", Ty::Str, "destination"), opt("data_or_options", Ty::Any, "required data for direct calls; optional {append: Bool} for piped calls"), opt("options", Ty::Record, "direct-call {append: Bool}; default false")], returns: "String",
doc: "Write data to a file and return its text. Direct: tee(path,data,options?); piped: data | tee(path,options?). Strings are unchanged; other values use their display representation. Refuse missing data, wrong options, unknown keys, non-Bool append and conflicting direct data in piped calls. Guard the actual destination, including newly created files, and snapshot for active transactions. Overwrite atomically by default; append with an append-only file handle when append is true. Filesystem failures are coded.",
examples: &[(r#"let d = fs_tempdir("ae_tee"); let f = d + "/x"; let result = tee(f, "hi"); rmdir(d, true); result"#, r#""hi""#), (r#"let d = fs_tempdir("ae_tee"); let f = d + "/x"; tee(f, "a"); tee(f, "b", {append: true}); let result = cat(f); rmdir(d, true); result"#, r#""ab""#), (r#"let d = fs_tempdir("ae_tee"); let f = d + "/x"; let result = "hi" | tee(f, {append: false}); rmdir(d, true); result"#, r#""hi""#), (r#"let d = fs_tempdir("ae_tee"); let f = d + "/x"; let result = "hi" | tee(f); rmdir(d, true); result"#, r#""hi""#)],
},
Signature {
name: "call", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "builtin name or alias"), opt_rest("args", Ty::Any, "arguments forwarded unchanged to the target")], returns: "Any",
doc: "Dynamically dispatch a builtin name (String or Uri) with zero or more arguments and forward any pipeline input unchanged. Use normal target signature validation and effect gating; target errors propagate. This calls builtins, not user-defined lambdas.",
examples: &[(r#"call("rl_gridworld").width"#, "5"), (r#"call("lower", "ABC")"#, r#""abc""#), (r#"[1,2] | call("map", fn(x) => x + 1)"#, "[2, 3]")],
},
Signature {
name: "budget", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Any),
params: &[req("max_tokens", Ty::Int, "positive representable token budget"), opt("cursor", Ty::Int, "nonnegative representable row offset; default zero")], returns: "Record",
doc: "Render a value using AECON and estimated tokens (or cl100k BPE with real-tokens). Arrays and tables produce a row page with from/shown/total/elided/next_cursor metadata; clamp the cursor to the row count and always include at least one remaining row even if oversized. Estimate rows conservatively and report actual page_tokens, which may exceed max_tokens due to an oversized row or framing. Other values produce a prefix with an explicit elision marker when over budget; nonzero cursors are refused for these values. Prefix length uses four Unicode characters per budget token, so the envelope is an approximate budget, not a hard cap. Clone only selected array/table rows.",
examples: &[(r#"budget([1,2,3], 100).shown"#, "3"), (r#"let result = [1,2,3] | budget(100, 1); result.from"#, "1"), (r#"budget("abc", 100).truncated"#, "false")],
},
Signature {
name: "file_append", category: None, subject_required: false, aliases: &["append_file"],
subject: None, params: &[req("path", Ty::Str, "file to append or create"), opt("content", Ty::Any, "content; omitted uses pipeline input")], returns: "Record",
doc: "Append content exactly as given, and return path, bytes appended and success. A file that does not exist is created, as >> does; its folder must already exist. No newline is added before or after the content, so a line that should end needs its own newline. An Array of Strings is joined with newlines, with none after its last item. Any other content (a Record, a number, a Bool) is refused with E_BAD_ARG and nothing is written; convert it first, e.g. to_json(value) or str(value).",
examples: &[
(r#"let d = fs_tempdir("ae_append"); let f = d + "/x"; let result = file_append(f, "hello"); rmdir(d, true); result.bytes_appended"#, "5"),
(r#"let d = fs_tempdir("ae_append"); let f = d + "/x"; let result = "hi" | file_append(f); rmdir(d, true); result.bytes_appended"#, "2"),
(r#"let d = fs_tempdir("ae_append"); let f = d + "/x"; file_write(f, "one"); file_append(f, "\ntwo\n"); let n = cat(f) | lines | len; rmdir(d, true); n"#, "2"),
(r#"let d = fs_tempdir("ae_append"); let f = d + "/x"; file_write(f, "one"); file_append(f, "two"); let n = cat(f) | lines | len; rmdir(d, true); n"#, "1"),
],
},
Signature {
name: "config_get", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("path", Ty::Str, "supported dotted configuration key")], returns: "Any",
doc: "Read a supported configuration key; unknown keys are refused with E_NOT_FOUND.",
examples: &[(r#"config_get("shell.show_banner") | type_of"#, "Bool")],
},
Signature {
name: "file_write", category: None, subject_required: false, aliases: &["write_file", "text_write"],
subject: None, params: &[req("path", Ty::Str, "destination path"), opt("content", Ty::Any, "content; omitted uses pipeline input")], returns: "Record",
doc: "Atomically write content, returning path, bytes, lines and success. Content must be a String, or an Array of Strings: the elements are joined with \\n, one per line, and no line break is added after the last one; an Array with a non-String element is refused with E_BAD_ARG naming its index. Any other value (a Record, a number, a Bool) is refused with E_BAD_ARG and nothing is written, so convert it first, e.g. to_json(value) or str(value).",
examples: &[
(r#"let d = fs_tempdir("ae_write"); let f = d + "/x"; let result = file_write(f, "hello"); rmdir(d, true); result.bytes"#, "5"),
(r#"let d = fs_tempdir("ae_write"); let f = d + "/x"; let result = "hi" | file_write(f); rmdir(d, true); result.bytes"#, "2"),
(r#"let d = fs_tempdir("ae_write"); let f = d + "/x"; let result = try { file_write(f, {a: 1}) } catch e { e.code }; rmdir(d, true); result"#, r#""E_BAD_ARG""#),
],
},
Signature {
name: "file_patch", category: None, subject_required: false, aliases: &["patch_file"],
subject: None, params: &[req("path", Ty::Str, "file to patch"), opt("patches", Ty::Any, "patch record or array; omitted uses pipeline input")], returns: "Record",
doc: "Apply find/replace patches in order, all or nothing. A patch whose find text is not in the file is an E_NOT_FOUND error and nothing is written; a success reports the applied patches. In a file whose line breaks are all CRLF, the LF in a find or replace text counts as CRLF: a multi-line find matches, and the replacement is written with CRLF line breaks; any other file is matched and written exactly as given.",
examples: &[
(r#"let d = fs_tempdir("ae_patch"); let f = d + "/x"; file_write(f, "hello"); let result = file_patch(f, {find: "hello", replace: "hi"}); rmdir(d, true); result.patches_applied"#, "1"),
(r#"let d = fs_tempdir("ae_patch"); let f = d + "/x"; file_write(f, "hello"); let result = [{find: "hello", replace: "hi"}] | file_patch(f); rmdir(d, true); result.success"#, "true"),
(r#"let d = fs_tempdir("ae_patch_crlf"); let f = d + "/x"; file_write(f, "one\r\ntwo\r\n"); file_patch(f, {find: "one\ntwo", replace: "X"}); let t = read_text(f); rmdir(d, true); t == "X\r\n""#, "true"),
],
},
Signature {
name: "file_replace", category: None, subject_required: false, aliases: &["str_replace_in_file", "text_replace"],
subject: None, params: &[req("path", Ty::Str, "file to edit"), req("old_text", Ty::Str, "text to replace"), req("new_text", Ty::Str, "replacement text")], returns: "Record",
doc: "Replace all occurrences of text in a file and return the patch result. Text that is not in the file is an E_NOT_FOUND error and nothing is written. A file that does not exist is also E_NOT_FOUND, reported as a missing file before any text is looked for. In a file whose line breaks are all CRLF, the LF in old_text counts as CRLF, so a multi-line old_text matches, and new_text is written with CRLF line breaks; any other file is matched and written exactly as given.",
examples: &[
(r#"let d = fs_tempdir("ae_replace"); let f = d + "/x"; file_write(f, "hello"); let result = file_replace(f, "hello", "hi"); rmdir(d, true); result.success"#, "true"),
(r#"let d = fs_tempdir("ae_replace_crlf"); let f = d + "/x"; file_write(f, "one\r\ntwo\r\n"); file_replace(f, "two", "x\ny"); let t = read_text(f); rmdir(d, true); t == "one\r\nx\r\ny\r\n""#, "true"),
],
},
Signature {
name: "file_insert", category: None, subject_required: false, aliases: &["insert_lines"],
subject: None, params: &[req("path", Ty::Str, "file to edit"), req("position", Ty::Any, "1-based line, named position, text pattern, or after/before/line record"), opt("content", Ty::Any, "lines to insert; omitted uses pipeline input")], returns: "Record",
doc: "Insert lines at a position or pattern, returning the insertion location. A line number is 1-based, and line count + 1 appends; a later line is E_BAD_ARG and nothing is written. A text anchor inserts AFTER the first line that contains it; the record {after: text} is the same anchor written out, and the record {before: text} inserts before that line instead. An anchor that no line contains is an E_NOT_FOUND error and nothing is written. The inserted lines take the file's line break: CRLF in a file whose line breaks are all CRLF, LF otherwise. The rest of the file is kept byte for byte; a file whose last line has no line break keeps that unless the insert goes after that line, and then the new text ends with a line break.",
examples: &[
(r#"let d = fs_tempdir("ae_insert"); let f = d + "/x"; file_write(f, "a"); let result = file_insert(f, 1, "b"); rmdir(d, true); result.at_line"#, "1"),
(r#"let d = fs_tempdir("ae_insert_crlf"); let f = d + "/x"; file_write(f, "a\r\nb\r\n"); file_insert(f, {after: "a"}, "c"); let t = read_text(f); rmdir(d, true); t == "a\r\nc\r\nb\r\n""#, "true"),
(r#"let d = fs_tempdir("ae_insert"); let f = d + "/x"; file_write(f, "a"); let result = "b" | file_insert(f, "end"); rmdir(d, true); result.at_line"#, "2"),
(r#"let d = fs_tempdir("ae_insert_after"); let f = d + "/x"; file_write(f, "a\nb"); let result = file_insert(f, {after: "a"}, "c"); rmdir(d, true); result.at_line"#, "2"),
],
},
Signature {
name: "file_edit", category: None, subject_required: false, aliases: &["edit_file", "text_edit"],
subject: None, params: &[req("path", Ty::Str, "regular UTF-8 file bounded to 64 MiB"), opt("edits", Ty::Any, "operation Record or Array; omitted uses pipeline input")], returns: "Record",
doc: "Validate replace/insert/delete operations and apply them in descending start-line order, preserving input order for ties, then publish atomically with transaction snapshot. Positive one-based ranges clip their end to EOF; out-of-range replacement/deletion refuses the whole batch, while insertion clips to EOF. Require operation-specific fields and String content for insert/replace. Surviving lines keep their text; every line is written with the file's line break, CRLF when all of the file's line breaks are CRLF and LF otherwise, and the file ends with a line break. A leading UTF-8 byte-order mark is kept as the first bytes. Refuse malformed or conflicting input; bound edits to 10000, aggregate payload and output to 64 MiB each, potential lines to one million and conservative line-edit work to ten million. Successful results contain applied metadata and an empty failed array.",
examples: &[(r#"let d = fs_tempdir("ae_edit"); let f = d + "/x"; file_write(f, "a\nb"); let result = file_edit(f, {op: "replace", line: 2, content: "x"}); rmdir(d, true); result.edits_applied"#, "1"), (r#"let d = fs_tempdir("ae_edit_pipe"); let f = d + "/x"; file_write(f, "a"); let result = [{operation: "insert_at", line: 2, text: "b"}] | edit_file(f); rmdir(d, true); result.final_lines"#, "2")],
},
Signature {
name: "fs_chown", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("path", Ty::Str, "filesystem path; symlinks affect their target"), req("owner", Ty::Any, "numeric Unix owner ID from 0 through 4294967294; on Windows an account name String"), opt("group", Ty::Int, "numeric Unix group ID in the same range; omitted preserves the existing group")], returns: "Bool",
doc: "Set ownership through the native Unix API and return true or a coded filesystem refusal, without launching a process. Guard the resolved path. On Windows, set the owner to a named account (a numeric ID is E_BAD_ARG, an unknown account E_NOT_FOUND, a refusal E_OS_DENIED) and take no group; a call inside a transaction is E_UNIMPLEMENTED because the Windows owner cannot be rolled back. Other platforms refuse with E_UNIMPLEMENTED. Inside a filesystem transaction on Unix, journal the prior owner and group so rollback restores them; reject reserved IDs, malformed or ignored arguments and pipeline input. Native ownership changes may clear special mode bits and capabilities.",
examples: &[
(r#"let d = fs_tempdir("ae_chown"); let f = d + "/x"; file_write(f, "hi"); let m = fs_stat(f); let result = if sys_os() == "windows" { fs_chown(f, whoami()) } else { fs_chown(f, m.uid) }; rmdir(d, true); result"#, "true"),
(r#"let d = fs_tempdir("ae_chown_group"); let f = d + "/x"; file_write(f, "hi"); let m = fs_stat(f); let result = if sys_os() == "windows" { fs_chown(f, whoami()) } else { fs_chown(f, m.uid, m.gid) }; rmdir(d, true); result"#, "true"),
],
},
Signature {
name: "fs_chmod", category: None, subject_required: false, aliases: &["chmod"],
subject: None, params: &[req("path", Ty::Str, "existing filesystem path"), req("mode", Ty::Any, "Int in 0..=07777 or octal String, optionally prefixed 0o")], returns: "Bool",
doc: "Set Unix mode bits; on Windows set the read-only attribute from the owner-write bit only. Return true or a coded failure. Resolve and guard the path before changing permissions. Refuse pipeline input. Inside a filesystem transaction, journal the prior permissions (and owner on Unix) of the resolved path so rollback restores them.",
examples: &[(r#"let d = fs_tempdir("ae_chmod"); let f = d + "/x"; file_write(f, "hi"); let result = fs_chmod(f, "0644"); rmdir(d, true); result"#, "true"), (r#"let d = fs_tempdir("ae_chmod_int"); let f = d + "/x"; file_write(f, "hi"); let result = chmod(f, 420); rmdir(d, true); result"#, "true")],
},
Signature {
name: "fs_watch", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("path", Ty::Str, "existing file or directory to watch"), opt("options", Ty::Record, "Record with optional recursive Bool (default false) and max_events Int in 1..=10000 (default 1000)")], returns: "String",
doc: "Start a native filesystem watch on path and return its handle, a String such as \"watch-1\". Watches are process-local and end with the process, so `ish -c` run once per call cannot keep a watch across calls: keep the handle inside one script or session and read it with fs_unwatch before the process exits. Events are OS notifications from the notify crate. They arrive asynchronously, may be coalesced or duplicated, and changes made before the watch is established may not appear; wait for the changes to settle, then call fs_unwatch to collect them. Bounds: at most 64 watches may be live (the 65th is E_BUDGET_EXCEEDED); each handle buffers at most max_events events and counts later ones in dropped. Unknown option keys, wrong types, out-of-range values, pipeline input and wrong argument counts are E_BAD_ARG; a missing path is E_NOT_FOUND. The effect is ReadLocal: the watch observes the filesystem and holds OS watch resources, and changes nothing.",
examples: &[(r#"typeof(fs_unwatch(fs_watch(".")))"#, "Record"), (r#"fs_unwatch(fs_watch(".", {recursive: false, max_events: 10})).dropped"#, "0")],
},
Signature {
name: "fs_unwatch", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("handle", Ty::Str, "handle returned by fs_watch")], returns: "Record",
doc: "Stop the watch named by handle, drop its OS watcher so no further events are recorded, remove the handle, and return {path, events, dropped}. events is an Array of records {kind, paths} in arrival order; kind is one of create, modify, remove, rename, access, other or error, and paths is an Array of String. An error event has no paths and carries a message String instead. dropped counts the events that arrived after the buffer reached max_events and were not stored. Events are asynchronous and may be coalesced or duplicated, so wait for the changes to settle before unwatching. An unknown or already unwatched handle is E_BAD_ARG, and the message names how many handles are live. The effect is ReadLocal.",
examples: &[(r#"typeof(fs_unwatch(fs_watch(".")).events)"#, "Array")],
},
Signature {
name: "fs_mount", category: None, subject_required: false, aliases: &[],
subject: None,
params: &[req("source", Ty::Str, "absolute path to a block device, a regular file (mounted through a loop device), or with bind: true a directory"), req("target", Ty::Str, "absolute path to an existing, empty directory"), opt("options", Ty::Record, "Record with optional fstype String of lowercase letters and digits, readonly Bool, options Array of String (each matching [a-z0-9_=.,-]+), and bind Bool")],
returns: "Record",
doc: "Mount a filesystem on Linux with /usr/bin/mount, run with an argv vector and no shell. Source and target must be absolute paths, and both are canonicalized first. A block device mounts directly, and a regular file mounts with -o loop. With bind: true a directory is bind-mounted with --bind, and readonly cannot be combined with it. The target must be an empty directory and must not be a protected system path: /, /proc, /sys, /dev, /run, /boot, /usr, /etc, /var or /home, matched by exact path. The options Array may not contain remount, and may contain bind or rbind only with bind: true. Returns {source, target, fstype, readonly}, where fstype and readonly are read back from /proc/self/mounts rather than echoed from the request. Relative paths, unknown keys, malformed values and a non-empty target are E_BAD_ARG; remount, a protected target and an unpermitted bind option are E_POLICY_DENY; a missing path is E_NOT_FOUND; a non-zero mount exit is E_TOOL_FAILED. On macOS a disk-image file is attached at the target with hdiutil attach -mountpoint (bind, fstype and options other than readonly are E_BAD_ARG) and read back with statfs; on Windows a .vhd or .vhdx file is attached and given the target, an empty NTFS folder, as its access path (bind, fstype and options other than readonly are E_BAD_ARG; drive roots and system folders are E_POLICY_DENY). Elsewhere the call is E_UNIMPLEMENTED and NOTHING WAS MOUNTED. A call inside a filesystem transaction is refused with E_POLICY_DENY. The effect is Privileged: it needs root or CAP_SYS_ADMIN and is refused in agent mode. Not done: /etc/fstab entries, mounts that need credentials, and unmount on exit.",
examples: &[
(r#"(try { fs_mount("relative", "relative") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { fs_mount("relative", "relative", {readonly: 1}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "fs_unmount", category: None, subject_required: false, aliases: &[],
subject: None,
params: &[req("target", Ty::Str, "absolute path of a mount point listed in /proc/self/mounts"), opt("options", Ty::Record, "Record with optional lazy Bool: umount -l, which detaches now and cleans up once the mount is no longer busy")],
returns: "Record",
doc: "Unmount the filesystem at target on Linux with /usr/bin/umount, run with an argv vector and no shell. target is canonicalized, and must be listed as a mount point in /proc/self/mounts. The paths /, /proc, /sys, /dev, /run, /boot, /usr, /etc, /var and /home are refused by exact path with E_POLICY_DENY, and so is any path that is not a mount point (E_NOT_FOUND). Returns {target, unmounted: true}. Relative paths, unknown keys and malformed values are E_BAD_ARG; a non-zero umount exit, such as a busy mount without lazy, is E_TOOL_FAILED. On macOS a disk image is detached with hdiutil detach (other mounts with umount); on Windows the access path is removed and the image detached, and lazy is E_BAD_ARG. Elsewhere the call is E_UNIMPLEMENTED and NOTHING WAS UNMOUNTED. A call inside a filesystem transaction is refused with E_POLICY_DENY. The effect is Privileged: it needs root or CAP_SYS_ADMIN and is refused in agent mode. Not done: unmounting by device, recursive unmount of nested mounts, and /etc/fstab changes.",
examples: &[
(r#"(try { fs_unmount("relative") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { fs_unmount("relative", {lazy: 1}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "fs_symlink", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("target", Ty::Str, "nonempty target; relative to the destination parent"), req("destination", Ty::Str, "nonempty new symbolic-link path")], returns: "Bool",
doc: "Create a symbolic link and return true or a coded refusal. Guard both the destination and referred target, including existing canonical audit aliases. Preserve relative target spelling. Refuse existing destinations and pipeline input. Inside a filesystem transaction, rollback removes the created link itself, never its target. Windows requires an existing target to select file/directory kind and refuses drive-relative or root-relative targets; creation may require symbolic-link privilege. Unix permits dangling targets.",
examples: &[
(r#"let d = fs_tempdir("ae_symlink"); file_write(d + "/target", "hi"); let result = try { fs_symlink("target", d + "/link") } catch e { e }; rmdir(d, true); if typeof(result) == "Bool" { result } else { throw json_stringify(result) }"#, "true"),
(r#"let d = fs_tempdir("ae_symlink_dir"); file_mkdir(d + "/target"); let result = try { fs_symlink(d + "/target", d + "/link") } catch e { e }; rmdir(d, true); if typeof(result) == "Bool" { result } else { throw json_stringify(result) }"#, "true"),
],
},
Signature {
name: "fs_link", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("source", Ty::Str, "existing regular file without a symlink"), req("destination", Ty::Str, "new hard-link path on the same filesystem")], returns: "Bool",
doc: "Create a hard link and return true, or a coded refusal. Both resolved paths pass the workspace write gate because the link shares the source file. Existing destinations and pipeline input are refused; transactions snapshot the new destination for rollback.",
examples: &[(r#"let d = fs_tempdir("ae_hard_link"); let f = d + "/x"; file_write(f, "hi"); let result = fs_link(f, d + "/y"); rmdir(d, true); result"#, "true")],
},
Signature {
name: "file_delete_lines", category: None, subject_required: false, aliases: &["delete_lines", "remove_lines"],
subject: None, params: &[req("path", Ty::Str, "regular UTF-8 file, bounded to 64 MiB"), req("selection", Ty::Any, "positive one-based line; or a String, which deletes every line containing that literal text (the same as {contains: text}); or a pattern Record {matching|contains|pattern|exact: text} matching literal text; or {regex: pattern} matching a regular expression (Rust regex syntax)"), opt("end", Ty::Int, "inclusive positive end for numeric selection only")], returns: "Record",
doc: "Delete a line, an ascending inclusive range, or lines selected by text. A String selector is the same as the pattern record {contains: text}, so an empty String deletes every line, as that record does. The matching, contains, pattern and exact selectors match literal text, so a regex metacharacter in them is only a character; {regex: pattern} deletes the lines that match a regular expression, and an invalid one is refused. A literal selector that holds regex syntax and deletes nothing still succeeds, with a note field that says so. Surviving lines are normalized to LF with a final newline; empty output stays empty. Out-of-range selection deletes nothing. Pipeline input is refused; the resolved path passes the destructive gate and transaction snapshot before atomic replacement.",
examples: &[
(r#"let d = fs_tempdir("ae_delete_line"); let f = d + "/x"; file_write(f, "a\nb\nc"); let result = file_delete_lines(f, 2); rmdir(d, true); result.lines_deleted"#, "1"),
(r#"let d = fs_tempdir("ae_delete_range"); let f = d + "/x"; file_write(f, "a\nb\nc"); let result = delete_lines(f, 1, 2); rmdir(d, true); result.lines_remaining"#, "1"),
(r#"let d = fs_tempdir("ae_delete_pattern"); let f = d + "/x"; file_write(f, "keep\ndrop\n"); let result = remove_lines(f, {exact: "drop"}); rmdir(d, true); result.success"#, "true"),
(r##"let d = fs_tempdir("ae_delete_string"); let f = d + "/x"; file_write(f, "keep\n# DEPRECATED\nalso keep\n"); let result = delete_lines(f, "# DEPRECATED"); rmdir(d, true); result.lines_deleted"##, "1"),
(r#"let d = fs_tempdir("ae_delete_regex"); let f = d + "/x"; file_write(f, "keep\ntmp1\ntmp22\n"); let result = delete_lines(f, {regex: "^tmp[0-9]+$"}); rmdir(d, true); result.lines_deleted"#, "2"),
(r#"let d = fs_tempdir("ae_delete_literal"); let f = d + "/x"; file_write(f, "t.x\ntt\n"); let result = delete_lines(f, {pattern: "t.*"}); rmdir(d, true); result.note == "matched literally; use {regex: ...} for a regular expression""#, "true"),
],
},
Signature {
name: "file_copy", category: None, subject_required: false, aliases: &["copy_file", "cp"],
subject: None, params: &[req("source", Ty::Str, "regular file or directory tree without symlink entries"), req("destination", Ty::Str, "non-overlapping destination with an existing parent, or an existing directory that takes a file copied into it")], returns: "Record",
doc: "Copy binary files or merge directory trees, bounded to 10000 entries and 64 MiB total. A file copied onto an existing directory goes inside it under its own name, as cp does; the result's dest names the file written. Preflight destination types and guard all writes; replace files atomically and snapshot modifications for transactions. Pipeline input is refused. In agent mode the source is judged by the read jail, as `cat` is: an outside source is E_OUTSIDE_WORKSPACE.",
examples: &[
(r#"let d = fs_tempdir("ae_copy"); file_write(d + "/x", "hi"); let result = file_copy(d + "/x", d + "/y"); rmdir(d, true); result.bytes"#, "2"),
(r#"let d = fs_tempdir("ae_copy_tree"); file_mkdir(d + "/a"); file_write(d + "/a/x", "hi"); let result = cp(d + "/a", d + "/b"); rmdir(d, true); result.success"#, "true"),
(r#"let d = fs_tempdir("ae_copy_into"); file_write(d + "/x", "hi"); file_mkdir(d + "/sub"); let result = cp(d + "/x", d + "/sub"); rmdir(d, true); result.bytes"#, "2"),
],
},
Signature {
name: "file_move", category: None, subject_required: false, aliases: &["file_rename", "move_file", "mv"],
subject: None, params: &[req("source", Ty::Str, "existing source path"), req("destination", Ty::Str, "destination path on the same filesystem")], returns: "Record",
doc: "Rename a path and return source, destination, bytes and success; both paths pass the move gate.",
examples: &[(r#"let d = fs_tempdir("ae_move"); let f = d + "/x"; file_write(f, "hi"); let result = file_move(f, d + "/y"); rmdir(d, true); result.success"#, "true")],
},
Signature {
name: "file_mkdir", category: None, subject_required: false, aliases: &["mkdir", "mkdirp"],
subject: None, params: &[opt("path", Ty::Str, "the directory to create; its missing parents are created too. Piped, the path is the input")], returns: "Record",
doc: "Create a directory and missing parents, returning path, created and success. Direct mkdir(path) or path | mkdir. An empty path is refused. undo removes the directories this call created, while they are still empty.",
examples: &[(r#"let d = fs_tempdir("ae_mkdir"); let result = mkdir(d + "/a/b"); rmdir(d, true); result.created"#, "true"), (r#"let d = fs_tempdir("ae_mkdir_pipe"); let result = (d + "/p") | mkdir; rmdir(d, true); result.created"#, "true")],
},
Signature {
name: "syntax_get", category: None, subject_required: false, aliases: &[],
subject: Some(Ty::Str), params: &[], returns: "Record",
doc: "Look up a registered syntax ID and return its specification, examples and encoding metadata.",
examples: &[(r#"syntax_get("ab").id"#, "ab"), (r#"("ironshell" | syntax_get).id"#, "ironshell")],
},
Signature {
name: "terraform_init",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("dir", Ty::Str, "configuration directory inside the workspace; omitted uses the workspace root")],
returns: "String",
doc: "terraform init -input=false -no-color in the directory, returning the tail of its report. Downloads the providers the configuration names. The directory must lie inside the workspace and must exist. Runs with a 15 minute deadline. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | terraform_init() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { terraform_init("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "terraform_plan",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("var_file", Ty::Str, "variable file inside the workspace; omitted uses the configuration's defaults")],
returns: "String",
doc: "terraform plan -input=false -no-color in the workspace root, returning the plan. Terraform may refresh state through providers, so this reaches the remote services the configuration names. The variable file must lie inside the workspace. Runs with a 15 minute deadline. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | terraform_plan() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { terraform_plan("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "terraform_apply",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("var_file", Ty::Str, "variable file inside the workspace; omitted uses the configuration's defaults")],
returns: "String",
doc: "terraform apply -input=false -no-color -auto-approve in the workspace root, returning the tail of its report. Changes the infrastructure the configuration describes, with no confirmation prompt; approval-gated in agent mode. The variable file must lie inside the workspace. Runs with a 15 minute deadline; a killed apply can leave state locked or half applied. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | terraform_apply() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { terraform_apply("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "terraform_destroy",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("dir", Ty::Str, "configuration directory inside the workspace; omitted uses the workspace root")],
returns: "String",
doc: "terraform destroy -input=false -no-color -auto-approve in the directory, returning the tail of its report. Destroys every resource the configuration manages. -auto-approve means Terraform never asks, so the call is approval-gated here, and the approval names the resolved directory. The directory must lie inside the workspace and must exist. Runs with a 15 minute deadline. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | terraform_destroy() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { terraform_destroy("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "terraform_state",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("dir", Ty::Str, "configuration directory inside the workspace; omitted uses the workspace root")],
returns: "Array",
doc: "terraform state list in the directory, as an Array of resource addresses. A missing state file is E_TOOL_FAILED with the stderr tail. The directory must lie inside the workspace and must exist. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | terraform_state() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { terraform_state("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "terraform_output",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("dir", Ty::Str, "configuration directory inside the workspace; omitted uses the workspace root")],
returns: "Record",
doc: "terraform output -json in the directory, as a Record of output name to value. Sensitive outputs are included with their values, as terraform output -json prints them, so their values reach the caller. The directory must lie inside the workspace and must exist. Failures are E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | terraform_output() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { terraform_output("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "terraform_workspace",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("name", Ty::Str, "workspace to select: letters, digits, '-' and '_'; omitted shows the current one")],
returns: "String",
doc: "With no name, terraform workspace show in the workspace root. With a name, terraform workspace select <name>, which changes the selected workspace of this configuration. The name is checked before terraform runs, so it is never read as a flag. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | terraform_workspace() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { terraform_workspace("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "terraform_validate",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("dir", Ty::Str, "configuration directory inside the workspace; omitted uses the workspace root")],
returns: "Record",
doc: "terraform validate -json in the directory, as a Record with valid and the diagnostics. An invalid configuration is an answer (valid is false), not a failure. The directory must lie inside the workspace and must exist. Failures that print no JSON are E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | terraform_validate() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { terraform_validate("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "tools",
category: None,
subject_required: false,
aliases: &["tool_list", "os_tools"],
subject: None,
params: &[opt("filter", Ty::Str, "an OS name, a category, or a search string")],
returns: "Array",
doc: "The catalogue of OS tools as Records {name, description, command, category, safety}, sorted by name. A filter that names an OS or a category selects that set; any other string is searched. A filter that is not a string is refused.",
examples: &[
(r#"(try { tools(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { tools("linux", "windows") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "tool_exec",
category: None,
subject_required: false,
aliases: &["tool_execute"],
subject: None,
params: &[
req("tool", Ty::Str, "a tool name from the tools catalogue"),
opt("args", Ty::Any, "a String or an Array of Strings passed to the tool as its argv"),
opt("allow_dangerous", Ty::Bool, "must be true to run a tool rated Dangerous or Critical"),
],
returns: "Record",
doc: "Run a catalogue tool directly (never through a shell) with the given argv, and return {success, stdout, stdout_truncated, stderr, stderr_truncated, exit_code, tool_name, command_executed, execution_time_ms}. The run is gated as an exec. Stdout keeps its first 1 MiB and stderr its last 64 KiB; a stream that was cut says so in its truncated flag. A run still going after 120 s is killed and refused with E_BUDGET_EXCEEDED. A nonzero exit is reported in the record (success false, exit_code), not raised. A tool that does not exist is E_NOT_FOUND; a Dangerous or Critical tool without allow_dangerous is E_POLICY_DENY; a program that cannot be started is E_TOOL_MISSING.",
examples: &[
(r#"(try { tool_exec() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { tool_exec("no_such_tool_xyz") } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "tool_info", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("name", Ty::Str, "registered OS tool name")], returns: "Record",
doc: "Describe an OS tool's command, safety level, parameters and worked examples.",
examples: &[(r#"tool_info("curl").name"#, "curl")],
},
Signature {
name: "tool_schema", category: None, subject_required: false, aliases: &["tool_schemas"],
subject: None, params: &[opt("filter", Ty::Str, "tool name, category or search query; omitted includes all tools")], returns: "Array",
doc: "Export OpenAI-compatible function schemas from the OS tool catalogue without executing tools.",
examples: &[("tool_schema() | type_of", "Array"), (r#"tool_schema("curl") | len"#, "1")],
},
Signature {
name: "tool_search", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("query", Ty::Str, "keyword or description")], returns: "Array",
doc: "Find recommended OS tools, falling back to catalogue text search.",
examples: &[(r#"tool_search("file copy") | type_of"#, "Array")],
},
Signature {
name: "ai_usage", category: Some("AI"), subject_required: false, aliases: &["ai-usage"],
subject: None, params: &[], returns: "Record",
doc: "Read session call counts, token totals, estimated costs and usage records.",
examples: &[("ai_usage() | type_of", "Record")],
},
Signature {
name: "ai_cost", category: Some("AI"), subject_required: false, aliases: &["ai-cost"],
subject: None, params: &[], returns: "Float",
doc: "Read the session's total estimated AI cost in USD.",
examples: &[("ai_cost() | type_of", "Float")],
},
Signature {
name: "ai_providers", category: Some("AI"), subject_required: false, aliases: &["ai-providers"],
subject: None, params: &[], returns: "Array",
doc: "List registered providers, readiness and credential presence, ordered by provider name.",
examples: &[("ai_providers() | type_of", "Array")],
},
Signature {
name: "ai_routes", category: Some("AI"), subject_required: false, aliases: &["ai-routes"],
subject: None, params: &[], returns: "Record",
doc: "Read the routing rules the provider registry checks, highest priority first, as {name, priority, condition, target, allow_fallback} records, with rule_count, registry totals, registered provider count, default provider and router enabled flag. A rule with no target is listed with target null and is skipped by routing. With no rule registered, rules is empty and note says so. No provider is contacted.",
examples: &[("ai_routes() | type_of", "Record")],
},
Signature {
name: "ai_registry_stats", category: Some("AI"), subject_required: false, aliases: &["ai-registry-stats"],
subject: None, params: &[], returns: "Record",
doc: "Read request, token, cost and latency statistics by provider, and the load-balancing strategy.",
examples: &[("ai_registry_stats() | type_of", "Record")],
},
Signature {
name: "ai_load_balancing", category: Some("AI"), subject_required: false, aliases: &["ai-load-balancing"],
subject: None, params: &[], returns: "String",
doc: "Read the current provider load-balancing strategy.",
examples: &[("ai_load_balancing() | type_of", "String")],
},
Signature {
name: "ai_local_backends", category: Some("AI"), subject_required: false, aliases: &["ai-local-backends"],
subject: None, params: &[], returns: "Array",
doc: "List compiled local inference backends, loaded models and supported formats.",
examples: &[("ai_local_backends() | type_of", "Array")],
},
Signature {
name: "ai_backends",
category: Some("AI"),
subject_required: false,
aliases: &["ai-backends"],
subject: None,
params: &[],
returns: "Array",
doc: "Probe the local and configured model endpoints (IronGate, Ollama, vLLM, llama.cpp, TGI, OpenAI, LM Studio) and list each reachable one as {name, provider, endpoint, available, models}. Only reachable backends are listed. This is a network operation: the call is gated as Network, and each endpoint probe that connects is charged to IRONSHELL_MAX_NET as its own request before it opens a socket (OpenAI is checked for a key only and makes no request). A probe the budget or policy refuses stops the sweep with that coded refusal rather than an empty list. Takes no arguments.",
examples: &[
(r#"(try { ai_backends(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | ai_backends() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ai_add_route", category: Some("AI"), subject_required: false, aliases: &["ai-add-route"],
subject: None, params: &[req("config", Ty::Record, "routing rule: {name, condition, priority?, target?, allow_fallback?}")], returns: "String",
doc: "Add a routing rule to the provider registry. The record takes name and condition (always, has_tools, has_vision, model:<pattern>, or tokens_over:<N>), with optional priority (an integer, default 50), target (a provider name; a rule with no target is listed and skipped by routing) and allow_fallback (a boolean, default true). Keys outside those, values of the wrong type and unknown conditions are refused before the registry changes. No provider is contacted.",
examples: &[
(r#"(try { ai_add_route("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ai_add_route({name: "r", condition: "bogus"}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ai_convert_model", category: Some("AI"), subject_required: false, aliases: &["ai-convert-model"],
subject: None, params: &[req("config", Ty::Record, "model conversion: {name, to_format, quantization?, output?, validate?}")], returns: "Record",
doc: "Convert a model stored in IronVault to another format, by delegating to vault_convert. The legacy source/target path form is refused, because IronVault addresses models by vault name: add a loose file to the vault first. Takes no pipeline input.",
examples: &[
(r#"(try { ai_convert_model("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ai_convert_model({source: "a.gguf", target: "b.safetensors"}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ai_detect", category: Some("AI"), subject_required: false, aliases: &["ai-detect"],
subject: None, params: &[], returns: "String",
doc: "Probe the local and configured backends and return the first available model URI (for example ollama:llama3), or an empty string when none is reachable. A probe the budget or policy refuses is an error, not an empty answer. This is a network operation: each probe that connects is charged to IRONSHELL_MAX_NET. Takes no arguments and no pipeline input.",
examples: &[
(r#"(try { ai_detect(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | ai_detect() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ai_gateway", category: Some("AI"), subject_required: false, aliases: &["ai-gateway", "irongate"],
subject: None, params: &[], returns: "Record",
doc: "Report IronGate, the routing gateway: its url, default model, whether it is reachable, its providers and models, and per-target circuit state. An unreachable gateway is an answer, reported as reachable false with the reason in error. Takes no arguments and no pipeline input.",
examples: &[
(r#"(try { ai_gateway(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | ai_gateway() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ai_gpu_memory", category: Some("AI"), subject_required: false, aliases: &["ai-gpu-memory"],
subject: None, params: &[], returns: "Record",
doc: "Report each NVIDIA GPU's total, used and free memory from nvidia-smi. A missing nvidia-smi is E_TOOL_MISSING and a failed or unreadable query is E_TOOL_FAILED; neither is reported as an empty GPU list. Takes no arguments and no pipeline input.",
examples: &[
(r#"(try { ai_gpu_memory(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | ai_gpu_memory() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ai_local_embed", category: Some("AI"), subject_required: false, aliases: &["ai-local-embed"],
subject: None, params: &[req("handle", Ty::Str, "local model handle such as candle:embed-model"), req("inputs", Ty::Sequence, "one string, or an array of strings")], returns: "Record",
doc: "Embed one or more strings with a loaded local model, returning embeddings and total_tokens. Each input must be a string and an empty array is refused. Only handles served by a compiled-in backend are answered; a handle no backend serves is E_NOT_FOUND. Takes no pipeline input.",
examples: &[
(r#"(try { ai_local_embed(1, "x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ai_local_embed("candle:x", [1]) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ai_local_generate", category: Some("AI"), subject_required: false, aliases: &["ai-local-generate"],
subject: None, params: &[req("handle", Ty::Str, "model handle, such as candle:llama or a model name for IronGate"), req("prompt", Ty::Any, "String prompt text, or a nonempty Array of {role, content} messages with role system, user, assistant or tool"), opt("params", Ty::Record, "optional {max_tokens?, temperature?, top_p?, repetition_penalty?, seed?}")], returns: "Record",
doc: "Generate text with a loaded local model, or through IronGate when no in-process backend serves the handle. A String prompt is sent as is. A messages Array is formatted by the model's own chat template, which the model's GGUF or tokenizer_config.json must carry; a model without one refuses messages, and IronGate takes only a String. params may set max_tokens (1 or more), temperature (0 or more), top_p (0 to 1), repetition_penalty (above 0) and seed (0 or more); other keys and wrong types are refused. The reply names the backend that answered. Takes no pipeline input.",
examples: &[
(r#"(try { ai_local_generate(1, "x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ai_local_generate("candle:x", "hi", {max_tokens: 0}) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ai_local_generate("candle:x", [{role: "bot", content: "hi"}]) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ai_local_load", category: Some("AI"), subject_required: false, aliases: &["ai-local-load"],
subject: None, params: &[req("path", Ty::Str, "model file path; its extension selects a compiled-in backend")], returns: "Record",
doc: "Load a model file into a compiled-in inference backend, returning its handle, backend name and estimated memory in MB. When the backend cannot estimate the memory, estimated_memory_mb is null and estimate_error says why. A format no compiled-in backend supports is E_UNIMPLEMENTED. Takes no pipeline input.",
examples: &[
(r#"(try { ai_local_load(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ai_local_load() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ai_local_unload", category: Some("AI"), subject_required: false, aliases: &["ai-local-unload"],
subject: None, params: &[req("handle", Ty::Str, "a handle returned by ai_local_load")], returns: "String",
doc: "Unload a model loaded with ai_local_load. A handle no backend serves is E_NOT_FOUND. Takes no pipeline input.",
examples: &[
(r#"(try { ai_local_unload(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ai_local_unload() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ai_model_fits", category: Some("AI"), subject_required: false, aliases: &["ai-model-fits"],
subject: None, params: &[req("config", Ty::Record, "{params_b (billions, above 0) or file_size_mb (1 or more), quantization?}")], returns: "Record",
doc: "Estimate a model's GPU memory need and compare it with each NVIDIA GPU's free memory from nvidia-smi. Give exactly one of params_b or file_size_mb: a record with neither, with both, or with an unknown key is refused, because a fit with no size is not an answer. A missing nvidia-smi is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { ai_model_fits(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ai_model_fits({}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ai_reset_usage", category: Some("AI"), subject_required: false, aliases: &["ai-reset-usage"],
subject: None, params: &[], returns: "String",
doc: "Reset the session's AI usage and cost counters. Takes no arguments and no pipeline input.",
examples: &[
(r#"(try { ai_reset_usage(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | ai_reset_usage() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ai_set_default", category: Some("AI"), subject_required: false, aliases: &["ai-set-default"],
subject: None, params: &[req("provider", Ty::Str, "provider name such as openai, anthropic or ollama")], returns: "String",
doc: "Make a provider the registry's default, registering it from the environment first if needed. An unknown provider name is E_BAD_ARG and changes nothing. Takes no pipeline input.",
examples: &[
(r#"(try { ai_set_default(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ai_set_default("no-such-provider") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ai_set_load_balancing", category: Some("AI"), subject_required: false, aliases: &["ai-set-load-balancing"],
subject: None, params: &[req("strategy", Ty::Any, "a strategy name, or {type: \"weighted\", weights: {provider: weight}}")], returns: "String",
doc: "Set the provider load-balancing strategy: none, round_robin, least_latency, least_requests or adaptive, or a weighted record whose weights are non-negative integers keyed by provider name. Unknown strategies, record keys, providers and weights are refused, and nothing changes. Takes no pipeline input.",
examples: &[
(r#"(try { ai_set_load_balancing("bogus") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ai_set_load_balancing({type: "weighted"}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ai_supported_conversions", category: Some("AI"), subject_required: false, aliases: &["ai-supported-conversions"],
subject: None, params: &[], returns: "Array | String",
doc: "List the model format conversions IronVault supports, as the vault reports them. Takes no arguments and no pipeline input.",
examples: &[
(r#"(try { ai_supported_conversions(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | ai_supported_conversions() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "vault_conversions", category: None, subject_required: false, aliases: &["vault-conversions"],
subject: None, params: &[], returns: "Array | String",
doc: "List the format conversions IronVault supports (iv list-conversions). Takes no arguments and no pipeline input.",
examples: &[
(r#"(try { vault_conversions(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | vault_conversions() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "vault_convert", category: None, subject_required: false, aliases: &["vault-convert"],
subject: None, params: &[req("config", Ty::Record, "{name, to_format, quantization?, output?, validate?}")], returns: "Record",
doc: "Convert a model stored in IronVault with iv convert. name and to_format are required; quantization and output are strings and validate is a boolean. Unknown keys, wrong types and values beginning with '-' are refused before iv runs. A failed iv run is E_TOOL_FAILED carrying its stderr. Takes no pipeline input.",
examples: &[
(r#"(try { vault_convert("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { vault_convert({name: "m"}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "vault_models", category: None, subject_required: false, aliases: &["vault-models"],
subject: None, params: &[], returns: "Array",
doc: "List the models IronVault stores (iv list --format json). The encrypted inventory needs IRONVAULT_PASSPHRASE, and the vault reports its own failure. Takes no arguments and no pipeline input.",
examples: &[
(r#"(try { vault_models(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | vault_models() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ai_detect_format", category: Some("AI"), subject_required: false, aliases: &["ai-detect-format"],
subject: None, params: &[req("path", Ty::Str, "model path; classified by extension without opening the file")], returns: "String",
doc: "Identify a model format by case-insensitive extension; unrecognized extensions return Unknown.",
examples: &[(r#"ai_detect_format("model.GGUF")"#, "GGUF"), (r#"ai_detect_format("model.xyz")"#, "Unknown")],
},
Signature {
name: "sys_env_all", category: None, subject_required: false, aliases: &[],
subject: None, params: &[], returns: "Record",
doc: "Read environment variables into a record, applying the secret access gate to each value.",
examples: &[("sys_env_all() | type_of", "Record")],
},
Signature {
name: "telemetry_report", category: None, subject_required: false, aliases: &[],
subject: None, params: &[opt("options", Ty::Record, "optional category string filter")], returns: "Record",
doc: "Count telemetry events by category and type, returning groups in sorted order.",
examples: &[("telemetry_report() | type_of", "Record"), (r#"telemetry_report({category: "example"}) | type_of"#, "Record")],
},
Signature {
name: "crypto_encrypt", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("data", Ty::Str, "UTF-8 plaintext"), req("password", Ty::Str, "nonempty password")], returns: "String",
doc: "Encrypt UTF-8 text with AES-256-GCM and fresh salt and nonce. Return a versioned authenticated envelope using Argon2id, or PBKDF2 in FIPS mode.",
examples: &[(r#"crypto_decrypt(crypto_encrypt("hello", "example-password"), "example-password")"#, "hello")],
},
Signature {
name: "crypto_decrypt", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("data", Ty::Str, "versioned authenticated ciphertext"), req("password", Ty::Str, "encryption password")], returns: "String",
doc: "Authenticate and decrypt a versioned envelope to UTF-8 text. The envelope selects its KDF. Legacy unauthenticated CBC requires explicit environment opt-in (IRONSHELL_CRYPTO_LEGACY_DECRYPT); it is decrypted in-process, with no openssl CLI.",
examples: &[(r#"crypto_decrypt(crypto_encrypt("hello", "example-password"), "example-password")"#, "hello")],
},
Signature {
name: "crypto_hmac", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("data", Ty::Str, "UTF-8 message"), req("key", Ty::Str, "UTF-8 secret key"), opt("algorithm", Ty::Str, "md5, sha1, sha256, sha384 or sha512; default sha256")], returns: "String",
doc: "Authenticate a message in process and return its lowercase hexadecimal HMAC. Weak algorithms are refused in FIPS mode.",
examples: &[(r#"crypto_hmac("The quick brown fox jumps over the lazy dog", "key")"#, "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8"), (r#"crypto_hmac("The quick brown fox jumps over the lazy dog", "key", "sha256")"#, "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8")],
},
Signature {
name: "crypto_uuid", category: None, subject_required: false, aliases: &["uuid"],
subject: None, params: &[], returns: "String",
doc: "Generate a random version-four UUID in process.",
examples: &[("crypto_uuid() | len", "36")],
},
Signature {
name: "crypto_random_bytes", category: None, subject_required: false, aliases: &[],
subject: None, params: &[opt_range("count", Ty::Int, 0, 1_048_576, "byte count; default 32")], returns: "String",
doc: "Generate random bytes in process and return lowercase hexadecimal text.",
examples: &[("crypto_random_bytes() | len", "64"), ("crypto_random_bytes(3) | len", "6")],
},
Signature {
name: "crypto_random_string", category: None, subject_required: false, aliases: &[],
subject: None, params: &[opt_range("length", Ty::Int, 0, 1_048_576, "character count; default 32"), opt("charset", Ty::Str, "nonempty character set; default ASCII alphanumeric")], returns: "String",
doc: "Generate the requested number of random characters using unbiased index sampling.",
examples: &[("crypto_random_string() | len", "32"), (r#"crypto_random_string(3, "x")"#, "xxx")],
},
Signature {
name: "ab_encode", category: None, subject_required: false, aliases: &[],
subject: None,
params: &[req("msg_type", Ty::Any, "String name or integer code 0..3"), req("opcode", Ty::Any, "String name or integer code 0..15"), req("payload", Ty::Str, "UTF-8 payload")],
returns: "Array",
doc: "Encode a version-zero AgenticBinary message as byte integers.",
examples: &[(r#"ab_encode("Query", "DATA", "hi") | len"#, "4"), (r#"(ab_encode(1, 4, "hi") | ab_decode).payload"#, "hi")],
},
Signature {
name: "ab_decode", category: None, subject_required: false, aliases: &[],
subject: Some(Ty::Array), params: &[], returns: "Record",
doc: "Decode an AgenticBinary byte array into header fields, payload text and bytes.",
examples: &[(r#"ab_decode([20, 2, 104, 105]).payload"#, "hi")],
},
Signature {
name: "web_parse_url", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("url", Ty::Str, "URL text")], returns: "Record",
doc: "Split URL text into protocol, host, port, path, query and hash fields.",
examples: &[(r#"web_parse_url("https://example.com:8080/a?q=1#x").host"#, "example.com")],
},
Signature {
name: "web_encode_url", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("text", Ty::Str, "UTF-8 text")], returns: "String",
doc: "Percent-encode UTF-8 text, preserving unreserved URL characters.",
examples: &[(r#"web_encode_url("a b")"#, "a%20b")],
},
Signature {
name: "web_decode_url", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("text", Ty::Str, "percent-encoded UTF-8; plus means space")], returns: "String",
doc: "Decode percent-encoded UTF-8; refuse invalid escapes and invalid UTF-8.",
examples: &[(r#"web_decode_url("%C3%A9+a")"#, "é a")],
},
Signature {
name: "web_parse_query", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("query", Ty::Str, "ampersand-separated key=value pairs")], returns: "Record",
doc: "Split query text into a record without percent-decoding; the last repeated key wins.",
examples: &[(r#"web_parse_query("?a=1&b=two").b"#, "two")],
},
Signature {
name: "web_build_query", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("values", Ty::Record, "query keys and values")], returns: "String",
doc: "Join record fields as key=value pairs without percent-encoding, in sorted key order.",
examples: &[(r#"web_build_query({a: "1", b: "two"})"#, "a=1&b=two")],
},
Signature {
name: "web_extract_emails", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("text", Ty::Str, "text to scan")], returns: "Array",
doc: "Find distinct email-like tokens in text.",
examples: &[(r#"web_extract_emails("a@example.com") | len"#, "1")],
},
Signature {
name: "web_extract_phones", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("text", Ty::Str, "text to scan")], returns: "Array",
doc: "Find phone-like runs containing 7 to 15 digits.",
examples: &[(r#"web_extract_phones("+1 555 123 4567") | len"#, "1")],
},
Signature {
name: "web_html_to_text", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("html", Ty::Str, "HTML text")], returns: "String",
doc: "Strip HTML tags using the shell's simple text converter.",
examples: &[(r#"web_html_to_text("<p>Hello</p>")"#, "Hello")],
},
Signature {
name: "web_html_to_markdown", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("html", Ty::Str, "HTML text")], returns: "String",
doc: "Convert basic headings, paragraphs and inline tags to Markdown.",
examples: &[(r#"web_html_to_markdown("<strong>Hello</strong>")"#, "**Hello**")],
},
Signature {
name: "web_json_path", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("value", Ty::Any, "value to traverse"), opt("path", Ty::Str, "dot fields and array indexes; omitted returns the value")], returns: "Any",
doc: "Traverse dot-separated fields and array indexes; missing values return null.",
examples: &[(r#"web_json_path({a: [7]}, "$.a[0]")"#, "7"), ("web_json_path(7)", "7")],
},
Signature {
name: "web_open_url", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("url", Ty::Str, "absolute http or https URL")], returns: "Bool",
doc: "Open an http or https URL in the desktop's web handler and return true once the launcher started. Only http and https are accepted; file:, javascript:, data: and every other scheme, option-like text, control characters and piped input are refused before anything launches. A launcher that cannot start or exits with an error is a coded failure, not false. Opens a browser: never call it from a test.",
examples: &[(r#"(try { web_open_url("file:///C:/Windows/win.ini") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { web_open_url("javascript:alert(1)") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "web_browser_open", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("url", Ty::Str, "absolute http or https URL")], returns: "Bool",
doc: "Open an http or https URL in the desktop's web handler; the same checks and results as web_open_url. Opens a browser: never call it from a test.",
examples: &[(r#"(try { web_browser_open("data:text/html,x") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { web_browser_open("-a") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "web_fetch", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("url", Ty::Str, "absolute http or https URL")], returns: "String",
doc: "GET an http or https URL and return the response body as text. Refuses other schemes (including through redirects), piped input and control characters before any request. A transport failure or an HTTP error status is E_TOOL_FAILED; a body over 8 MiB is E_BUDGET_EXCEEDED; requests stop after 10 redirects or 30 s.",
examples: &[(r#"(try { web_fetch("file:///etc/hosts") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { web_fetch(5) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "web_get", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("url", Ty::Str, "absolute http or https URL")], returns: "String",
doc: "GET an http or https URL and return the response body as text; the same checks, limits and result as web_fetch.",
examples: &[(r#"(try { web_get("ftp://example.invalid/x") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { web_get(5) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "http_get", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Str),
params: &[], returns: "Record",
doc: "Fetch one http or https URL, given directly or piped in, and return {url, status, headers, body}. The URL passes the network guard and the SSRF rules, and every redirect target passes the same rules before it is followed, at most 5. A non-2xx status is an answer, not a failure. The body is read up to 16 MiB, and more is E_BUDGET_EXCEEDED. A request that gets no answer is E_IO. Refused inside a transaction.",
examples: &[
(r#"(try { http_get("file:///etc/hosts") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { http_get(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "web_post", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("url", Ty::Str, "absolute http or https URL"), opt("data", Ty::Any, "a String sent as is, or any other value sent as JSON; default empty")], returns: "String",
doc: "POST data to an http or https URL and return the response body as text. The data is sent literally: a value starting with @ is never read as a file. Same refusals and limits as web_fetch.",
examples: &[(r#"(try { web_post("file:///x") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { web_post("file:///x", "a=1") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "web_json_get", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("url", Ty::Str, "absolute http or https URL")], returns: "Any",
doc: "GET an http or https URL with Accept: application/json and return the parsed JSON. A body that is not JSON is E_TOOL_FAILED. An HTTP error status is returned as its JSON body, so check the response for an error field; a transport failure is E_TOOL_FAILED.",
examples: &[(r#"(try { web_json_get("ftp://example.invalid/x") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { web_json_get(5) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "web_json_post", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("url", Ty::Str, "absolute http or https URL"), opt("body", Ty::Any, "value sent as JSON; default {}")], returns: "Any",
doc: "POST a value as JSON to an http or https URL and return the parsed JSON response. A response that is not JSON is E_TOOL_FAILED. Same limits as web_json_get.",
examples: &[(r#"(try { web_json_post("file:///x") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { web_json_post("file:///x", {a: 1}) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "web_scrape", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("url", Ty::Str, "absolute http or https URL"), opt("selector", Ty::Str, "a bare tag name such as h1; class and id selectors are refused")], returns: "String | Array",
doc: "GET an http or https URL. Without a selector, return the page's HTML as text. With a tag name, return each element with that name as a string, from its opening tag to its matching closing tag; more than 1000 matches is E_BUDGET_EXCEEDED. An HTTP error status is E_TOOL_FAILED.",
examples: &[(r#"(try { web_scrape("file:///x") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { web_scrape("https://example.invalid/", ".title") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "web_download", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("url", Ty::Str, "absolute http or https URL"), opt("path", Ty::Str, "local file to write; default is the URL's last path segment")], returns: "Bool",
doc: "Download an http or https URL to a local file and return true. The file path goes through the workspace write jail that file_write uses. An HTTP error status writes nothing and is E_TOOL_FAILED; a file over 512 MiB is E_BUDGET_EXCEEDED. Writes a local file and makes a request: use a temporary directory in tests.",
examples: &[(r#"(try { web_download("file:///etc/hosts") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { web_download("file:///etc/hosts", "hosts.txt") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "wget_download", category: None, subject_required: false, aliases: &["wget"], subject: None,
params: &[req("url", Ty::Str, "http or https URL"), opt("output", Ty::Str, "output path inside the workspace; default is the URL's last path segment")], returns: "Record",
doc: "Download one http or https URL to a file in the workspace, through curl with protocols limited to http and https for the request and every redirect. At most 5 redirects, a 1 GiB size limit, a 15 s connect limit and a 900 s deadline. An existing output is refused, and a failed transfer removes its partial file. Returns {url, output, size, status, tool}. Refused inside a transaction.",
examples: &[
(r#"(try { wget_download("file:///etc/hosts") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { wget_download("ftp://example.invalid/f", "f.txt") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "web_headers", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("url", Ty::Str, "absolute http or https URL")], returns: "Record",
doc: "Send a HEAD request, following redirects, and return the final response's headers as a record keyed by lowercase name. A repeated header keeps its last value; use web_cookies for Set-Cookie.",
examples: &[(r#"(try { web_headers("file:///etc/hosts") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { web_headers(5) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "web_cookies", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("url", Ty::Str, "absolute http or https URL")], returns: "Array",
doc: "Send a HEAD request, following redirects, and return every Set-Cookie header value sent along the way, in order.",
examples: &[(r#"(try { web_cookies("file:///etc/hosts") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { web_cookies(5) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "web_form_submit", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("url", Ty::Str, "absolute http or https URL"), opt("fields", Ty::Any, "a Record of String, Int, Float or Bool fields, percent-encoded; or an already-encoded String sent as is")], returns: "String",
doc: "POST a form to an http or https URL and return the response body as text. Record keys and values are percent-encoded in sorted key order. Same refusals and limits as web_fetch.",
examples: &[(r#"(try { web_form_submit("file:///x") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { web_form_submit("file:///x", {a: "1&b=2"}) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "web_upload_file", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("url", Ty::Str, "absolute http or https URL"), req("path", Ty::Str, "local file to send; no ';' or '\"' characters"), opt("field", Ty::Str, "multipart field name; default file")], returns: "Bool",
doc: "POST a local file as multipart form data to an http or https URL and return true on success. The file is read through the same read guard file_read uses. An HTTP error status is E_TOOL_FAILED. Reads a local file and sends it over the network.",
examples: &[(r#"(try { web_upload_file("file:///x", "a.txt") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { web_upload_file("file:///x", "a.txt", "upload") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "web_rest_api", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("method", Ty::Str, "GET, POST, PUT, PATCH, DELETE, HEAD or OPTIONS"), req("url", Ty::Str, "absolute http or https URL"), opt("body", Ty::Any, "value sent as JSON"), opt("headers", Ty::Record, "String header values; names are tokens; no control characters in values")], returns: "Any",
doc: "Send a request with the given method, optional JSON body and string headers to an http or https URL. A JSON response is returned parsed, anything else as text. Header values containing CR, LF or other control characters are refused, not sent. Same limits as web_fetch.",
examples: &[(r#"(try { web_rest_api("TRACE", "https://example.invalid/") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { web_rest_api("GET", "file:///x") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { web_rest_api("GET", "https://example.invalid/", "x", {"X-A": 1}) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "web_websocket", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("url", Ty::Str, "ws or wss URL"), opt("send", Ty::Any, "a String or Array of Strings sent as text frames after connecting; null sends nothing"), opt("opts", Ty::Record, "max_messages (Int 1..=1000, default 100), timeout_secs (Int 1..=120, default 10)")], returns: "Record",
doc: "One bounded WebSocket exchange: connect to a ws or wss URL, send each `send` string as a text frame, collect messages until the server closes, max_messages arrive or timeout_secs pass, then close. Returns {messages, closed_by_server, timed_out}; a text frame is a String, a binary frame {binary: base64}. timeout_secs covers the whole exchange; running out while collecting is timed_out true, not an error, but a connect or handshake that runs out is E_BUDGET_EXCEEDED. More than 8 MiB received is E_BUDGET_EXCEEDED. A connection or handshake that fails is E_TOOL_FAILED. A URL that is not ws or wss, a bad send value, an unknown option, an out-of-range option or a surplus argument is E_BAD_ARG before anything is opened. wss verifies the server against the webpki root certificates.",
examples: &[
(r#"(try { web_websocket("http://example.invalid/socket") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { web_websocket("ws://example.invalid/socket", 5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { web_websocket("ws://example.invalid/socket", null, {max_messages: 0}) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { web_websocket("ws://example.invalid/socket", ["a"], {colour: 1}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "web_graphql", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("url", Ty::Str, "absolute http or https URL"), req("query", Ty::Str, "GraphQL document"), opt("variables", Ty::Any, "value sent as the variables object")], returns: "Any",
doc: "POST a GraphQL document and optional variables as JSON to an http or https URL and return the parsed JSON response. GraphQL errors arrive in the response's errors field; a transport failure or a non-JSON response is E_TOOL_FAILED.",
examples: &[(r#"(try { web_graphql("file:///x", "{ a }") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { web_graphql("file:///x", "{ a }", {id: 1}) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "web_check_url", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("url", Ty::Str, "absolute http or https URL")], returns: "Bool",
doc: "Request an http or https URL, following redirects, and return true when the final status is 2xx or 3xx. A transport failure (DNS, refused connection, timeout) is E_TOOL_FAILED rather than false, so false always means the server answered with an error status.",
examples: &[(r#"(try { web_check_url("file:///etc/hosts") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { web_check_url(5) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "web_robots_txt", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("url", Ty::Str, "absolute http or https URL; its origin is fetched")], returns: "String",
doc: "Fetch /robots.txt from the origin of an absolute http or https URL and return it as text. A site without one is E_TOOL_FAILED (HTTP 404). A bare host name is refused, not given a guessed scheme.",
examples: &[(r#"(try { web_robots_txt("ftp://example.invalid/") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { web_robots_txt("example.invalid") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "web_sitemap", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("url", Ty::Str, "absolute http or https URL; its origin is fetched")], returns: "String",
doc: "Fetch /sitemap.xml from the origin of an absolute http or https URL and return it as text. A site without one is E_TOOL_FAILED (HTTP 404). A bare host name is refused, not given a guessed scheme.",
examples: &[(r#"(try { web_sitemap("ftp://example.invalid/") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { web_sitemap("example.invalid") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "web_xpath", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("html", Ty::Str, "HTML or simple XML text"), req("expression", Ty::Str, "XPath expression")], returns: "Array",
doc: "Evaluate an XPath expression against markup, with a lenient in-tree parser and no network or file access. Returns the matches in document order, without duplicates: an element as its outer HTML, an attribute as its decoded value, a text node as its decoded text. Supported: absolute and relative paths, //, ., .., the axes child, descendant, descendant-or-self, self, parent and attribute (abbreviated or spelled out), the tests name, *, text(), node(), @name and @*, predicates with position, last(), =, !=, <, <=, >, >=, existence, and, or, not(), contains(), starts-with() and normalize-space(), and a top-level union with |. Not supported, and refused with E_BAD_ARG: functions other than those listed (count(), string-length(), ...), other axes (following-sibling::, ...), variables, parenthesised path expressions such as (//li)[1], and comparisons between two node sets. Documents over 16 MiB, more than 1000 matches, or element nesting over 512 are E_BUDGET_EXCEEDED. Use web_scrape for a plain tag selector.",
examples: &[
(r#"web_xpath("<ul><li>a</li><li>b</li></ul>", "//li")"#, r#"["<li>a</li>", "<li>b</li>"]"#),
(r#"web_xpath("<a href='/x'>y</a>", "//a/@href")"#, r#"["/x"]"#),
(r#"web_xpath("<p>a<b>b</b>c</p>", "//p/text()")"#, r#"["a", "c"]"#),
(r#"web_xpath("<ul><li>a</li><li>b</li></ul>", "//li[2]")"#, r#"["<li>b</li>"]"#),
(r#"(try { web_xpath("<p>x</p>", "count(//p)") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "type_fields", category: None, subject_required: false, aliases: &[],
subject: Some(Ty::Record), params: &[], returns: "Array",
doc: "Inspect record fields or table columns as name, type and preview records.",
examples: &[(r#"type_fields({a: 1, b: "x"}) | len"#, "2")],
},
Signature {
name: "ontology_manifest", category: None, subject_required: false, aliases: &[],
subject: None, params: &[], returns: "Record",
doc: "List ontology categories, counts and schema metadata without expanding every builtin.",
examples: &[("ontology_manifest() | type_of", "Record")],
},
Signature {
name: "product", category: Some("Array"), subject_required: false, aliases: &[],
subject: Some(Ty::Array), params: &[], returns: "Number",
doc: "Multiply an array of numbers; the empty product is 1.",
examples: &[("[2,3,4] | product", "24"), ("product([])", "1")],
},
Signature {
name: "is_type", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("value", Ty::Any, "value to inspect"), req("type_name", Ty::Str, "type name or supported synonym")],
returns: "Bool", doc: "Check a value against a case-insensitive type name or synonym.",
examples: &[(r#"is_type([], "list")"#, "true"), (r#"is_type(1, "String")"#, "false")],
},
Signature {
name: "ontology_json", category: None, subject_required: false, aliases: &[],
subject: None, params: &[], returns: "Record", doc: "Export the OS ontology as JSON Schema.",
examples: &[("ontology_json() | type_of", "Record")],
},
Signature {
name: "ontology_jsonld", category: None, subject_required: false, aliases: &[],
subject: None, params: &[], returns: "Record", doc: "Export the OS ontology as JSON-LD.",
examples: &[("ontology_jsonld() | type_of", "Record")],
},
Signature {
name: "ontology_owl", category: None, subject_required: false, aliases: &[],
subject: None, params: &[], returns: "String", doc: "Export the OS ontology as OWL/RDF Turtle.",
examples: &[("ontology_owl() | type_of", "String")],
},
Signature {
name: "ontology_shacl", category: None, subject_required: false, aliases: &[],
subject: None, params: &[], returns: "Record", doc: "Export the OS ontology as SHACL shapes.",
examples: &[("ontology_shacl() | type_of", "Record")],
},
Signature {
name: "Some", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("value", Ty::Any, "the contained value")],
returns: "Record", doc: "Wrap a value in the Some option constructor.",
examples: &[("Some(7)._value", "7")],
},
Signature {
name: "aggregate_results",
category: None,
subject_required: false,
aliases: &["aggregate"],
subject: Some(Ty::Array),
params: &[opt("strategy", Ty::Str, "one of concat (the default), sum, count, first, last")],
returns: "Any",
doc: "Combine an Array of results: concat returns it unchanged, sum adds finite numbers (any other element is refused, not skipped), count gives its length, first and last give an element and refuse an empty Array. Piped, the strategy is the only argument: [1, 2] | aggregate_results(\"sum\"). Unpiped: aggregate_results(results, strategy?). An unknown strategy is E_BAD_ARG.",
examples: &[
(r#"aggregate_results([1, 2, 3], "count")"#, "3"),
(r#"[1, 2, 3] | aggregate_results("first")"#, "1"),
(r#"(try { aggregate_results([1, "x"], "sum") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "reduce", category: Some("Array"), subject_required: false, aliases: &[],
subject: Some(Ty::Array), params: &[req("action", Ty::Lambda, "fn(acc, item) or fn(acc, item, index)"), req("initial", Ty::Any, "the initial accumulator")],
returns: "Any", doc: "Fold an array from left to right, optionally passing each item's index.",
examples: &[("[1, 2, 3] | reduce(fn(a, x) => a + x, 0)", "6"), ("reduce([1, 2], fn(a, x, i) => a + x + i, 0)", "4")],
},
Signature {
name: "push", category: Some("Array"), subject_required: false, aliases: &[],
subject: Some(Ty::Array), params: &[req("item", Ty::Any, "the item to append")],
returns: "Array", doc: "Append one value to an array.",
examples: &[("[1, 2] | push(3) | len", "3"), ("push([1], 2) | len", "2")],
},
Signature {
name: "concat", category: Some("Array"), subject_required: false, aliases: &[],
subject: Some(Ty::Array), params: &[req("other", Ty::Array, "the array to append")],
returns: "Array", doc: "Concatenate two arrays in order.",
examples: &[("[1, 2] | concat([3]) | sum", "6"), ("concat([1], [2]) | len", "2")],
},
Signature {
name: "json_parse", category: None, subject_required: false, aliases: &[],
subject: Some(Ty::Str), params: &[], returns: "Any",
doc: "Parse a JSON string into a typed value. Text that is not JSON is E_BAD_VALUE, not retryable, and its hint gives the line and column.",
examples: &[(r#"json_parse("{\"n\":7}").n"#, "7"), (r#""[1,2]" | json_parse | len"#, "2"), (r#"(try { json_parse("{") } catch e { e.error.code })"#, "E_BAD_VALUE")],
},
Signature {
name: "from_csv", category: None, subject_required: false, aliases: &["from-csv"],
subject: Some(Ty::Str), params: &[], returns: "Array",
doc: "Parse a CSV string with headers. Each column is typed as a whole: it is numeric only when every non-empty cell is a number, with no leading \"+\" and no leading zero before another digit (\"007\" is text, \"0.5\" is a number). A numeric column holds Ints when every non-empty cell is an integer, else Floats, and its empty cells are null. A column whose non-empty cells are all true or false, in any case (TRUE, False), holds Bools, its empty cells null. Any other column holds only Strings, and its empty cells are \"\". A cell that spells NaN or an infinity (inf, -Infinity), or an integer past the 64-bit Int range, is text, so such a column is a String column: in CSV these are labels, JSON cannot hold a non-finite float, and a Float would lose the digits of a large integer. A header that names a column twice is E_BAD_ARG, since the second column would replace the first. A row whose field count differs from the header is E_BAD_ARG, and its message gives the CSV line, counting CRLF lines correctly. The text is piped in or passed as the argument: from_csv(text).",
examples: &[
(r#"("n\n7\n" | from_csv | first).n"#, "7"),
(r#"from_csv("n\n7\n") | len"#, "1"),
(r#"from_csv("n,m\n7,\n8,2\n") | first | fn(r) => r.m"#, "null"),
(r#"from_csv("n,s\n7,\n8,x\n") | first | fn(r) => r.s"#, r#""""#),
(r#"from_csv("n\n007\nNA\n12\n") | first | fn(r) => r.n"#, r#""007""#),
(r#"from_csv("v\nNaN\n1\n") | first | fn(r) => r.v"#, r#""NaN""#),
(r#"(try { from_csv("a,a\n1,2\n") } catch e { e.error.code })"#, r#""E_BAD_ARG""#),
],
},
Signature {
name: "to_csv", category: None, subject_required: false, aliases: &["to-csv"],
subject: Some(Ty::Array), params: &[opt("columns", Ty::Array, "column names, in the order to write them; a record without one writes an empty field")], returns: "String",
doc: "Serialize an array of records to CSV. The columns are the keys of every record in sorted order, so a key that only a later row has is kept, or the columns Array when one is given, in that order; a key a record lacks writes an empty field, and a null writes an empty field. The rows are piped in or passed as the argument: to_csv(rows), or rows | to_csv(columns).",
examples: &[
(r#"[{n: 7}] | to_csv | from_csv | len"#, "1"),
(r#"to_csv([{n: 7}]) | from_csv | len"#, "1"),
(r#"to_csv([{b: 2, a: 1}], ["b", "a"]) | lines | first"#, r#""b,a""#),
(r#"[{id: 1}, {id: 2, customer: "Ada"}] | to_csv(["id", "customer"]) | lines | last"#, r#""2,Ada""#),
(r#"[{id: 1}, {id: 2, customer: "Ada"}] | to_csv | lines | first"#, r#""customer,id""#),
],
},
Signature {
// The header of a file, without reading its rows. An agent that opens a
// CSV and then writes it back needs the order the file had: records are
// sorted maps, so `open` alone cannot say it.
name: "csv_columns", category: None, subject_required: false, aliases: &[],
subject: Some(Ty::Str), params: &[], returns: "Array",
doc: "The header row of a CSV file or of CSV text, as an Array of Strings in file order, with quoting read as from_csv reads it. A String that names an existing file is read as that file; a single line that ends in .csv, .tsv or .txt and names no file is E_NOT_FOUND; any other String is CSV text. The path or text is piped in or passed as the argument: csv_columns(path_or_text).",
examples: &[
(r#"csv_columns("id,customer\n1,Ada\n") | len"#, "2"),
(r#"(try { csv_columns("nofile.csv") } catch e { e.error.code })"#, "E_NOT_FOUND"),
(r#""id,customer\n1,Ada\n" | csv_columns | last"#, r#""customer""#),
(r#"let d = fs_tempdir("ae_csvcols"); let f = d + "/rows.csv"; file_write(f, "id,customer\n1,Ada\n"); let cols = csv_columns(f); rmdir(d, true); cols | first"#, r#""id""#),
],
},
Signature {
name: "from_yaml", category: None, subject_required: false, aliases: &["from-yaml"],
subject: Some(Ty::Str), params: &[], returns: "Any",
doc: "Parse the supported YAML subset into a typed value. Double-quoted escapes decode per YAML 1.2.",
examples: &[(r#"from_yaml("n: 7").n"#, "7"), (r#"("n: 7" | from_yaml).n"#, "7"), (r#"(try { from_yaml("n: 9223372036854775808") } catch e { e.error.code })"#, "E_BAD_VALUE")],
},
Signature {
name: "to_yaml", category: None, subject_required: false, aliases: &["to-yaml"],
subject: Some(Ty::Any), params: &[], returns: "String",
doc: "Serialize a typed value as YAML with round-trip-safe quoting.",
examples: &[("({n: 7} | to_yaml | from_yaml).n", "7"), ("from_yaml(to_yaml({n: 7})).n", "7")],
},
Signature {
name: "columns", category: None, subject_required: true, aliases: &[],
subject: Some(Ty::Any), params: &[], returns: "Array",
doc: "Keys of a piped record or its first array row; empty for other values.",
examples: &[("{a: 1, b: 2} | columns | len", "2"), ("42 | columns | len", "0")],
},
Signature {
name: "describe", category: None, subject_required: true, aliases: &[],
subject: Some(Ty::Any), params: &[], returns: "Record",
doc: "Describe a piped value's type and collection structure.",
examples: &[(r#"([1,2,3] | describe).length"#, "3")],
},
Signature {
name: "trace",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
opt("label_or_value", Ty::Any, "the label (a String) when two arguments are given, otherwise the value"),
opt("value", Ty::Any, "the value, when a label is given"),
],
returns: "Any",
doc: "Write one line to stderr, [TRACE label] Type: value, and return the value unchanged so it can sit in a pipeline. A value over 4096 characters is cut with an explicit marker. A label must be a string of at most 256 bytes. Piped, the only argument is the label.",
examples: &[
(r#"trace("step", 2 + 3)"#, "5"),
(r#"(try { trace("a", 1, 2) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "type_assert", category: None, subject_required: false, aliases: &["assert_type"],
subject: Some(Ty::Any), params: &[req("expected", Ty::Str, "case-insensitive value type name")],
returns: "Any", doc: "Return the value if its type matches, otherwise produce an error value.",
examples: &[(r#"type_assert(7, "Int")"#, "7"), (r#"7 | type_assert("int")"#, "7")],
},
Signature {
name: "round",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Numeric),
params: &[opt_range(
"digits",
Ty::Int,
0,
17,
"decimal places; 0 returns an Int",
)],
returns: "Number",
doc: "Round a number, optionally to a number of decimal places. The tie rule is half away from zero, applied to the exact binary value of a Float, as format_number does: 2.675 is stored as 2.67499999..., so round(2.675, 2) is 2.67, while an exact tie such as 0.125 or 2.5 goes up (round(0.125, 2) is 0.13, round(2.5) is 3, round(-2.5) is -3).",
examples: &[
("round(4.966, 2)", "4.97"),
("4.966 | round(2)", "4.97"),
("round(4.5)", "5"),
("round(2.675, 2)", "2.67"),
("round(0.125, 2)", "0.13"),
],
},
Signature {
name: "rsync_sync",
category: None,
subject_required: false,
aliases: &["rsync"],
subject: None,
params: &[req("source", Ty::Str, "a path inside the workspace or a [user@]host:path spec"), req("destination", Ty::Str, "a path inside the workspace or a [user@]host:path spec"), opt("options", Ty::Record, "archive, compress, delete, verbose, progress (Bool) and exclude (String); no Record means -az")],
returns: "Record",
doc: "rsync from source to destination, returning {source, destination, exit_code, success, stdout, stderr}. Operands are plain: a leading '-' is refused, so no rsync option can be passed, and a URL is refused. A local operand must lie inside the workspace. delete removes files on the destination. A nonzero exit is E_TOOL_FAILED. Runs with a 15 minute deadline. Takes no pipeline input.",
examples: &[
(r#"(try { rsync_sync("-x", "y") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { rsync_sync("a", "b", {bogus: true}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ruff_check",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("path", Ty::Str, "a file or directory inside the workspace; defaults to the working directory")],
returns: "Array",
doc: "Runs `ruff check --output-format=json <path>` and returns its violations as an Array of records. Violations are the answer, not a failure: ruff's exit status 1 is not an error. Any other nonzero exit is E_TOOL_FAILED. Output over 16 MiB is refused. Deadline 2 minutes; a missing ruff is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | ruff_check() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ruff_check("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ruff_format",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("path", Ty::Str, "a file or directory inside the workspace; defaults to the working directory")],
returns: "Record",
doc: "Runs `ruff format <path>`, which rewrites Python files in place. The path must lie inside the workspace. Returns {path, exit_code: 0, success: true, stdout, stderr}; a nonzero exit is E_TOOL_FAILED. Deadline 10 minutes; a missing ruff is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | ruff_format() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ruff_format("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "max",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[opt_rest("values", Ty::Any, "an array to aggregate, or numbers")],
returns: "Number",
doc: "Largest element of an array of numbers or of Strings (Strings by code point, as sort orders them), or the largest of two or more numbers. An array mixing numbers and Strings, or an empty array, is refused.",
examples: &[("max(1, 7, 3.5)", "7"), ("[1, 5, 3] | max", "5"), ("max(2, 9)", "9"), ("max(3, 2.5)", "3"), ("[2.5, 3, 1] | max", "3"), (r#"["pear", "apple", "fig"] | max"#, r#""pear""#)],
},
Signature {
name: "ninja_build",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("options", Ty::Any, "a Record {dir?: String, target?: String, jobs?: Int 1..=1024}, or a directory String")],
returns: "Record",
doc: "Runs ninja in a directory inside the workspace, with an optional target and job count, and returns {exit_code: 0, success: true, stdout, stderr}. Option keys other than dir, target and jobs are refused. A target and a directory must not begin with '-'. A nonzero exit is E_TOOL_FAILED with the stderr tail; output keeps its last 256 KiB. Deadline 15 minutes. Build steps run project code, so the call is classified Exec. A missing ninja is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { ninja_build(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ninja_build({target: "-t"}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "mage_run",
category: None,
subject_required: false,
aliases: &["mage"],
subject: None,
params: &[req("target", Ty::Str, "a mage target name; one word that does not begin with '-'")],
returns: "Record",
doc: "Runs mage <target> in the working directory and returns {target, exit_code: 0, success: true, stdout, stderr}. A nonzero exit is E_TOOL_FAILED with the stderr tail. Deadline 10 minutes. mage compiles and runs the project's magefile, so the call is classified Exec. A missing mage is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { mage_run(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { mage_run("-l") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "node_run",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("script", Ty::Str, "a .js, .mjs or .ts file inside the workspace, or a JavaScript expression")],
returns: "Record",
doc: "Runs node on a script file inside the workspace, or on an expression (node -e). Returns {exit_code: 0, success: true, stdout, stderr}. A file must not begin with '-' and must lie inside the workspace; an expression is passed after -e and is not a path. A nonzero exit is E_TOOL_FAILED with the stderr tail. Deadline 10 minutes. The call runs arbitrary JavaScript, so it is classified Exec. A missing node is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { node_run(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { node_run(" ") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "make_run",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
opt("target", Ty::Str, "make target or VAR=value override; one word, not starting with '-'"),
opt("options", Ty::Record, "optional {dir?: String, file?: String, jobs?: Int 1..1024}; dir and file must lie inside the workspace"),
],
returns: "Record",
doc: "make [-f file] [-jN] <target> run in dir (default: the process's directory), with no shell: the target is one argv element. Answers {exit_code, success, stdout, stderr, target?}; stdout keeps its last 256 KiB and sets output_truncated when it was cut. A nonzero exit is E_TOOL_FAILED with the stderr tail, and a deadline of 15 minutes is E_BUDGET_EXCEEDED. Option names other than dir, file and jobs are refused by name. Effect exec: a Makefile runs its recipes, so the central gate asks for approval in agent mode. Takes no pipeline input.",
examples: &[
(r#"(try { make_run("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { make_run({jobs: 1}) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { make_run("all", {jobs: 0}) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { make_run("all", {bogus: 1}) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | make_run() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "make_targets",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("makefile", Ty::Str, "path to the Makefile; defaults to Makefile in the process's directory")],
returns: "Array",
doc: "The target names a Makefile declares (lines of the form name: ...), read natively without running make. A missing file is E_NOT_FOUND; a file over 4 MiB is E_BUDGET_EXCEEDED rather than read in part. Takes no pipeline input.",
examples: &[
(r#"(try { make_targets("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { make_targets(["Makefile"]) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | make_targets() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "min",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[opt_rest("values", Ty::Any, "an array to aggregate, or numbers")],
returns: "Number",
doc: "Smallest element of an array of numbers or of Strings (Strings by code point, as sort orders them), or the smallest of two or more numbers. An array mixing numbers and Strings, or an empty array, is refused.",
examples: &[("min(4, 1.5, 3)", "1.5"), ("[1, 5, 3] | min", "1"), ("min(2, 9)", "2"), ("min(1, 2.5)", "1"), ("[2.5, 3, 4] | min", "2.5"), (r#"["pear", "apple", "fig"] | min"#, r#""apple""#)],
},
Signature {
name: "mise_use",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("tool", Ty::Str, "a tool and optional version, one word such as node@20; not starting with '-'")],
returns: "Record",
doc: "mise use <tool@version> in the process's directory: pins the version in that directory's .mise.toml, answering {tool, exit_code, success, stdout, stderr}. mise installs the version and writes the config. The effect is Exec, so agent mode asks for approval. The directory must lie inside the workspace; the option that would write the global config is refused as an option. A nonzero exit is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { mise_use("-g") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { mise_use("node 20") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { mise_use() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | mise_use("node@20") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "mise_list",
category: None,
subject_required: false,
aliases: &["mise"],
subject: None,
params: &[],
returns: "Array",
doc: "mise list: the tool versions mise knows, as an Array of Strings, one per line of its report. A failure is E_TOOL_FAILED. Takes no arguments and no pipeline input.",
examples: &[
(r#"(try { mise_list("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | mise_list() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "env",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("name", Ty::Str, "environment variable to read"),
opt("default", Ty::Any, "returned when the variable is unset"),
],
returns: "String | Null",
doc: "Read an environment variable, with an optional default when unset. Null when it is unset and no default is given.",
examples: &[
(r#"env("HOME")"#, "/home/me"),
(r#"env("NOPE", "fallback")"#, "fallback"),
],
},
Signature {
name: "db_json_to_sqlite",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req(
"db",
Ty::Str,
"database to write — NOTE: the database comes first",
),
req("json", Ty::Str, "JSON file to import"),
opt("table", Ty::Str, "table name; defaults to \"imported\" (sql() names a file's table after the file stem instead)"),
],
returns: "Bool",
doc: "Import a JSON array of objects into a SQLite table named by the table argument (default \"imported\"; unlike sql(), which names a file's table after the file stem). The columns are the union of the rows' keys in first-seen order, and a row without a key stores NULL. Each column is typed as sql() reads the same file: INTEGER for integers and Booleans (1 and 0), REAL when a number has a fraction, TEXT otherwise, so ORDER BY id sorts numbers as numbers. An empty array imports nothing and returns false. Refused before anything is written: invalid JSON, and anything but an array of objects. A nested array or object is stored as JSON text. Any non-empty key is accepted and quoted for you; a control character in a name is refused. Rows go in one at a time, so a failure partway keeps the earlier rows.",
examples: &[(
r#"db_json_to_sqlite("issues.db", "issues.json", "issues")"#,
"true",
)],
},
Signature {
name: "where",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[req(
"predicate",
Ty::Lambda,
"fn(element) -> Bool, or fn(element, index)",
)],
returns: "Array",
doc: "Keep the elements for which the predicate returns true. A predicate with two parameters also receives the element's index, as fn(element, index): [10, 20] | where(fn(x, i) => i > 0) is [20].",
examples: &[
("[1, 2, 3] | where(fn(x) => x > 1)", "[2, 3]"),
// The subject may also be passed directly, which is the form the
// hand-written catalogue entry used to advertise.
("where([1, 2, 3], fn(x) => x > 1)", "[2, 3]"),
("[10, 20] | where(fn(x, i) => i > 0)", "[20]"),
],
},
Signature {
name: "foreach",
category: None,
subject_required: false,
aliases: &["ForEach-Object", "foreach-object"],
subject: Some(Ty::Array),
params: &[req(
"transform",
Ty::Lambda,
"fn(element) -> Any, or fn(element, index)",
)],
returns: "Array",
doc: "PowerShell's ForEach-Object: apply a transform to every piped element. The same implementation as map.",
examples: &[
(r#"[1, 2, 3] | foreach(fn(x) => x * 2)"#, "[2, 4, 6]"),
(r#"foreach([1, 2, 3], fn(x) => x * 2)"#, "[2, 4, 6]"),
],
},
Signature {
name: "select",
category: None,
subject_required: true,
aliases: &["Select-Object", "select-object"],
subject: None,
params: &[opt_rest(
"property",
Ty::Str,
"a property name to keep on each piped record; none returns the input unchanged",
)],
returns: "Any",
doc: "PowerShell's Select-Object: keep the named properties of each piped record. A piped item that is not a record is refused.",
examples: &[
(r#"[{a: 1, b: 2}] | select("a") | map(fn(r) => r.a)"#, "[1]"),
(r#"(try { [1, 2] | select("a") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "measure",
category: None,
subject_required: true,
aliases: &["Measure-Object", "measure-object"],
subject: None,
params: &[opt(
"property",
Ty::Str,
"a property whose numeric values are summarised; omitted, only Count",
)],
returns: "Record",
doc: "PowerShell's Measure-Object: the number of piped elements and, for one property, its sum, average, minimum and maximum. A piped value that is not an array counts as one element.",
examples: &[
(r#"([1, 2, 3] | measure).Count"#, "3"),
(r#"([{n: 2}, {n: 5}] | measure("n")).Maximum"#, "5.0"),
(r#"(try { [1] | measure(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { [1] | measure("n", "m") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "map",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[req(
"transform",
Ty::Lambda,
"fn(element) -> Any, or fn(element, index)",
)],
returns: "Array",
doc: "Apply a transform to every element. A lambda with two parameters also receives the element's index, as fn(element, index): [10, 20] | map(fn(x, i) => i) is [0, 1].",
examples: &[
("[1, 2, 3] | map(fn(x) => x * 2)", "[2, 4, 6]"),
("map([1, 2, 3], fn(x) => x * 2)", "[2, 4, 6]"),
("[10, 20] | map(fn(x, i) => i)", "[0, 1]"),
],
},
Signature {
name: "sum",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[],
returns: "Number",
doc: "Total of a numeric array.",
examples: &[("[1, 2, 3] | sum", "6")],
},
Signature {
name: "len",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[],
returns: "Int",
doc: "Number of elements in an array, characters in a string, or fields in a record.",
examples: &[("[1, 2, 3] | len", "3"), (r#""abc" | len"#, "3")],
},
// ── the E1 corpus's working set ─────────────────────────────────────
//
// Everything below is a builtin the benchmark corpus actually calls. They
// were all described by name-splitting -- `from-json` as "From-json" with
// no parameters, `sort_by` as "Sort by" with none, `str` as "Str" -- and
// four of them (`from_json`, `group_by`, `mean`, `to_string`) could not be
// looked up at all, because they live in the dispatcher's fallback half
// which the catalogue never walked.
//
// `benches/agentic/PREREGISTERED_E7.md` names this as the thing that would
// make the IronShell arm lose for a fixable reason rather than a
// fundamental one, so it lands before that experiment runs.
Signature {
name: "from_json",
category: None,
subject_required: false,
aliases: &["from-json"],
subject: Some(Ty::Str),
params: &[],
returns: "Any",
doc: "Parse a JSON string into typed values. Text that is not JSON is E_BAD_ARG and not retryable: the same text fails again, and its hint gives the line and column. An integer past the 64-bit Int range is E_BAD_VALUE and the refusal names its path; quote it as a string to keep the digits.",
examples: &[
(r#"cat("issues.json") | from_json | len"#, "500"),
(r#""[1, 2]" | from_json"#, "[1, 2]"),
(r#"typeof("null" | from_json)"#, "Null"),
(r#"(try { from_json("9223372036854775808") } catch e { e.error.code })"#, "E_BAD_VALUE"),
],
},
Signature {
name: "group",
category: None,
subject_required: false,
aliases: &["group_by", "group-object", "Group-Object"],
subject: Some(Ty::Array),
params: &[req("key", Ty::Any, "field name String to group on, or a lambda (or .field) called per row whose result is the key")],
returns: "Array",
// The doc is what an agent reads (E7 builds its reference from this
// line). Asked "which author opened the most PRs, and how many?",
// a Haiku run returned the whole `{Count, Group, Name}` record: the
// right fact in a form nobody asked for. The idiom that answers it is
// named here rather than left to be discovered.
doc: r#"Group records by a field name or by a lambda key (`group_by(.region)`, `group_by(fn(r) => r.region)`), returning {Name, Count, Group} records. The subject is piped or the first argument: `rows | group_by("a")` and `group_by(rows, "a")` are the same. Name is always a String, the key's text (the Int key 1 is Name "1", and Int 1 and String "1" stay separate groups with the same Name), and the groups are sorted by Name as text, not by first appearance or by number: "10" comes before "9". A row without the field groups under Name "". For "which, and how many": | sort_by("Count", "desc") | first | fn(g) => "${g.Name} ${g.Count}"."#,
examples: &[
(
r#"[{user: "a"}, {user: "a"}, {user: "b"}] | group_by("user") | len"#,
"2",
),
(
r#"[{user: "a"}, {user: "a"}, {user: "b"}] | group_by("user") | sort_by("Count", "desc") | first | fn(g) => "${g.Name} ${g.Count}""#,
r#""a 2""#,
),
(
r#"[{user: "a"}, {user: "a"}, {user: "b"}] | group_by(fn(r) => r.user) | len"#,
"2",
),
(
r#"group_by([{a: 1}, {a: 2}, {a: 1}], "a") | map(fn(g) => g.Count)"#,
"[2, 1]",
),
(
r#"[{n: 10}, {n: 9}] | group_by("n") | map(fn(g) => g.Name)"#,
r#"["10", "9"]"#,
),
],
},
Signature {
name: "avg",
category: None,
subject_required: false,
aliases: &["mean"],
subject: Some(Ty::Array),
params: &[],
returns: "Float",
doc: "Arithmetic mean of a numeric array. An empty array is refused with E_BAD_ARG, as min and max refuse one: its mean is undefined.",
examples: &[
("[1, 2, 3, 4] | mean", "2.5"),
("[1, 2] | avg | round(2)", "1.5"),
(r#"(try { [] | avg } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "median",
category: Some("Math"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[],
returns: "Float",
doc: "Median of an array of numbers: the middle value, or the mean of the two middle values of an even-length array. Always a Float. An empty array is refused with E_BAD_ARG.",
examples: &[
("[1, 2, 3] | median", "2.0"),
("median([1, 2, 3, 4])", "2.5"),
(r#"(try { [] | median } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "variance",
category: Some("Math"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[],
returns: "Float",
doc: "Sample variance (divisor n - 1) of an array of numbers, as Python's statistics.variance. Fewer than 2 values is refused with E_BAD_ARG.",
examples: &[
("[1, 2, 3, 4, 5] | variance", "2.5"),
("[100000000.1, 100000000.2, 100000000.3] | variance", "0.010000000298023245"),
(r#"(try { [1] | variance } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "stddev",
category: Some("Math"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[],
returns: "Float",
doc: "Sample standard deviation (divisor n - 1) of an array of numbers, as Python's statistics.stdev. Fewer than 2 values is refused with E_BAD_ARG.",
examples: &[
("[1, 2, 3] | stddev", "1.0"),
(r#"(try { [1] | stddev } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "percentile",
category: Some("Math"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[req("p", Ty::Numeric, "the percentage, 0 to 100")],
returns: "Float",
doc: "The p-th percentile of an array of numbers, p from 0 to 100, by linear interpolation between the closest ranks (numpy's default). A p outside 0..=100 or an empty array is refused with E_BAD_ARG.",
examples: &[
("[1, 2, 3, 4, 5] | percentile(50)", "3.0"),
("percentile([1, 2, 3, 4], 25)", "1.75"),
(r#"(try { percentile([1, 2], 101) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "str",
category: None,
subject_required: false,
aliases: &["to_string"],
subject: Some(Ty::Any),
params: &[],
returns: "String",
doc: "Render any value as a string.",
examples: &[(r#"to_string(42) + "!""#, r#""42!""#)],
},
Signature {
name: "sort_by",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
// `key` is deliberately `Any` and optional. It takes a field name or a
// lambda, `"desc"` may follow it, and calling it with no key at all
// must reach the builtin's own error, which names both accepted forms
// -- a better message than a declaration can give, and one
// `tests/sort_by_key.rs` asserts. Declaring `key: String, required`
// rejected the lambda form and replaced that message with a worse one.
params: &[
opt(
"key",
Ty::Any,
"field name (String), or fn(record) -> Any",
),
opt("order", Ty::Str, r#""asc" or "desc", in any letter case; default ascending"#),
],
returns: "Array",
doc: "Sort an array of records by a field name or a lambda. Every key must be a number or every key a String; a row whose key is null, a Bool, or of another kind is refused with E_BAD_ARG naming the row, so filter with where first or give a default in the lambda. A row missing the named field is E_UNKNOWN_FIELD, and an order other than asc or desc is E_BAD_ARG. Key-evaluation errors propagate.",
examples: &[
(r#"[{n: 2}, {n: 1}] | sort_by("n") | first | fn(r) => r.n"#, "1"),
(r#"[{n: 1}, {n: 2}] | sort_by("n", "DESC") | first | fn(r) => r.n"#, "2"),
("[{n: 2}, {n: 1}] | sort_by(fn(r) => r.n)", "[{n: 1}, {n: 2}]"),
(r#"(try { [{n: 1}, {m: 2}] | sort_by("n") } catch e { e.error.code })"#, "E_UNKNOWN_FIELD"),
(r#"(try { [{n: 1}, {n: 2}] | sort_by("n", "sideways") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ai",
category: Some("AI"),
subject_required: false,
aliases: &[],
subject: None,
params: &[
opt(
"prompt",
Ty::Str,
"the prompt; with piped input the piped string is the prompt and this argument is ignored",
),
opt(
"config",
Ty::Record,
"optional: images, audio or video, each an Array of readable file paths sent with the prompt; a model field is accepted and not used",
),
],
returns: "String",
doc: "Send one prompt to the configured AI provider and return its text. Prompts are checked for injection before they are sent, and a refused prompt is an error. With piped input the piped string is the prompt, and the config is then the second argument. Each image, audio or video path is validated and read before the request is made. At most 30 calls are made per minute per process; a call past that is refused with the message AI rate limit exceeded until the window resets. This is a network operation.",
examples: &[
(r#"(try { ai(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ai("p", 1) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "sort",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Sequence),
params: &[],
returns: "Array",
doc: "Sort an array ascending by natural ordering.",
examples: &[("[3, 1, 2] | sort", "[1, 2, 3]")],
},
Signature {
name: "first",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
// `first(n)` returns the first n as an array; bare `first` returns the
// element. Declaring it parameterless refused `ls(…) | first(5)`, which
// is the form E2's corpus uses -- and the Rust suite did not notice,
// because nothing in it calls `first` with a count.
params: &[opt(
"count",
Ty::Int,
"how many to return, as an array; omit for the single element",
)],
returns: "Any",
doc: "First element of an array, or the first `count` elements. A negative count is refused with E_BAD_ARG, as take refuses one.",
examples: &[("[1, 2, 3] | first", "1"), ("[1, 2, 3] | first(1)", "[1]"), ("[1, 2, 3] | first(2)", "[1, 2]")],
},
Signature {
name: "last",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[opt(
"count",
Ty::Int,
"how many to return, as an array; omit for the single element",
)],
returns: "Any",
doc: "Last element of an array, or the last `count` elements. A negative count is refused with E_BAD_ARG, as take refuses one.",
examples: &[("[1, 2, 3] | last", "3"), ("[1, 2, 3] | last(1)", "[3]"), ("[1, 2, 3] | last(2)", "[2, 3]")],
},
Signature {
name: "flatten",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[],
returns: "Array",
doc: "Flatten one level of nesting.",
examples: &[("[[1, 2], [3]] | flatten", "[1, 2, 3]")],
},
Signature {
name: "unique",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[],
returns: "Array",
doc: "Remove every duplicate element, keeping the first of each in order. The subject is an Array, piped or as the argument; a String is refused: pipe it through lines for lines, or through split(\"\") for characters, first.",
examples: &[
("[1, 2, 1, 3] | unique", "[1, 2, 3]"),
(r#"unique(["b", "a", "b"])"#, r#"["b", "a"]"#),
],
},
Signature {
name: "any",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
// The subject is NOT listed as a parameter: `validate` already shifts
// past it for the direct-call form `any(array, predicate)`. Listing it
// too counted it twice and refused the corpus's own `any(r.labels,
// fn(l) => ...)` -- caught by running E1, not by the type checker.
// Optional: `any([false, true])` over an array of booleans is a
// documented form with its own tests. Declaring the predicate required
// refused it -- caught by `tests/builtin_consistent_syntax.rs`, which
// is what a suite is for.
params: &[opt(
"predicate",
Ty::Lambda,
"fn(element) -> Bool; omit to test the elements themselves",
)],
returns: "Bool",
doc: "True when the predicate holds for at least one element, or when any element is itself true.",
examples: &[
(r#"any(["a", "b"], fn(l) => l == "b")"#, "true"),
("[1, 2] | any(fn(x) => x > 1)", "true"),
("any([false, true, false])", "true"),
],
},
Signature {
name: "all",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[opt(
"predicate",
Ty::Lambda,
"fn(element) -> Bool; omit to test the elements themselves",
)],
returns: "Bool",
doc: "True when the predicate holds for every element, or when every element is itself true.",
examples: &[
("[2, 3] | all(fn(x) => x > 1)", "true"),
("all([true, false, true])", "false"),
],
},
Signature {
name: "ansible_playbook",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("playbook", Ty::Str, "playbook file inside the workspace"), opt("inventory", Ty::Str, "inventory file or directory inside the workspace; an inline host list is refused"), opt("extra_vars", Ty::Record, "scalar variables passed as --extra-vars; keys are identifiers")],
returns: "String",
doc: "ansible-playbook on a playbook inside the workspace, returning the tail of its output. The playbook and the inventory must exist inside the workspace. extra_vars travel on the command line, where other local users can read them in a process listing, so keep secrets in a vault file. A nonzero exit is E_TOOL_FAILED. Runs with a 15 minute deadline. Takes no pipeline input.",
examples: &[
(r#"(try { ansible_playbook() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ansible_playbook("-x", "-i") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ansible_inventory",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("inventory", Ty::Str, "inventory file or directory inside the workspace")],
returns: "Record",
doc: "ansible-inventory --list for an inventory inside the workspace, as the JSON Record it prints. Takes no pipeline input.",
examples: &[
(r#"(try { ansible_inventory() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ansible_inventory("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ansible_galaxy",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("role", Ty::Str, "a Galaxy role name, a registry spec, or a path inside the workspace")],
returns: "String",
doc: "ansible-galaxy install <role>, returning the tail of its output. A registry or URL spec is downloaded from the network. A file: or link: spec is refused. Runs with a 15 minute deadline. Takes no pipeline input.",
examples: &[
(r#"(try { ansible_galaxy("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ansible_galaxy("file:./role") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ansible_vault",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("action", Ty::Str, "view, encrypt or decrypt"), req("file", Ty::Str, "vault file inside the workspace")],
returns: "String",
doc: "ansible-vault view, encrypt or decrypt on a file inside the workspace. view returns the decrypted text, so the secret reaches the caller; decrypt leaves the file in plain text. No vault password is accepted or placed on the command line. Where no password source is configured, ansible-vault prompts on the terminal, and the deadline bounds that wait. Takes no pipeline input.",
examples: &[
(r#"(try { ansible_vault("-x", "f.yml") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ansible_vault("view") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "in",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[req("collection", Ty::Any, "an Array (membership by value), a String (substring), or a Record (key membership)")],
returns: "Bool",
doc: "Membership: whether a needle is in a collection. Direct in(needle, collection), or needle | in(collection). Arrays compare by value (numbers compare exactly, an Int equals an equal Float, Records and Arrays compare structurally). A String collection needs a String needle; a Record needs a String key. A collection of another type, or a needle of the wrong type for a String or Record, is E_BAD_ARG, because a false there would read as a true negative.",
examples: &[
(r#"2 | in([1, 2, 3])"#, "true"),
(r#"in(2, [1, 2, 3])"#, "true"),
(r#"(try { in(1, 5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "contains",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[req("needle", Ty::Any, "substring or element to look for")],
returns: "Bool",
// Strings only. This said "or an array an element" until
// `contains([1, 2, 3], 2)` was actually run: it answers
// `E_BAD_ARG: expected a string, got Array`. Exactly the kind of
// plausible-but-wrong sentence that name-derived documentation
// produces, written here by hand instead.
doc: "Whether a string contains a substring. Strings only.",
examples: &[(r#"contains("security fix", "security")"#, "true")],
},
Signature {
name: "lower",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "String",
doc: "Convert a string to lowercase.",
examples: &[(r#"lower("ABC")"#, r#""abc""#)],
},
Signature {
name: "ends_with",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[req("suffix", Ty::Str, "text the string must end with")],
returns: "Bool",
doc: "Whether a string ends with the given suffix.",
examples: &[(r#"ends_with("main.rs", ".rs")"#, "true"), (r#""main.rs" | ends_with(".rs")"#, "true")],
},
Signature {
name: "starts_with",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[req("prefix", Ty::Str, "text the string must begin with")],
returns: "Bool",
doc: "Whether a string starts with the given prefix.",
examples: &[(r#"starts_with("version = 1", "version")"#, "true")],
},
Signature {
name: "split",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[req("delimiter", Ty::Str, "separator to split on; required"), opt("limit", Ty::Int, "the most pieces to answer, 1 or more (Rust's splitn, not Python's maxsplit: limit 2 gives at most 2 pieces); the last piece keeps the rest of the text; default: no limit")],
returns: "Array",
doc: "Split a string on a delimiter, into at most limit pieces when a limit is given. A limit under 1 is E_BAD_ARG. For a pattern rather than a fixed delimiter, use regex_split.",
examples: &[(r#"split("a,b,c", ",")"#, r#"["a", "b", "c"]"#), (r#""a,b,c" | split(",") | len"#, "3"), (r#"split("abc", "")"#, r#"["a", "b", "c"]"#), (r#"split("a,b,c", ",", 2)"#, r#"["a", "b,c"]"#), (r#""a,b,c" | split(",", 1)"#, r#"["a,b,c"]"#)],
},
Signature {
name: "upper",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "String",
doc: "Convert a string to uppercase.",
examples: &[(r#"upper("ab")"#, r#""AB""#)],
},
Signature {
name: "trim",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[opt("chars", Ty::Str, "characters to strip from both ends, each one of them; default: whitespace")],
returns: "String",
doc: "Remove leading and trailing whitespace, or with a second String, every character in it from both ends (as Python's strip(chars) does). An empty second String strips nothing. A second argument that is not a String is E_BAD_ARG.",
examples: &[
(r#"trim(" x ")"#, r#""x""#),
(r#"trim("xxhixx", "x")"#, r#""hi""#),
(r#""xxhixx" | trim("x")"#, r#""hi""#),
(r#"trim(" x ", "")"#, r#"" x ""#),
(r#"(try { trim("a", 1) } catch e { e.error.code })"#, r#""E_BAD_ARG""#),
],
},
Signature {
name: "title",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "String",
doc: "Title-case a String: in each word the first letter is upper case and the other letters are lower case. A word is a run of letters, digits and apostrophes; any other character ends it and is kept. Digits and apostrophes are kept as they are, so 3rd becomes 3Rd. Letters are mapped one character at a time, so accented letters work.",
examples: &[
(r#"title("hello WORLD")"#, r#""Hello World""#),
(r#""well-known fact" | title"#, r#""Well-Known Fact""#),
(r#""élan vital" | title"#, r#""Élan Vital""#),
],
},
Signature {
name: "capitalize",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "String",
doc: "Capitalize a String: its first character in upper case and every other character in lower case. Unlike title, a space or a hyphen does not start a new word.",
examples: &[
(r#"capitalize("hELLO wORLD")"#, r#""Hello world""#),
(r#""élan" | capitalize"#, r#""Élan""#),
],
},
Signature {
name: "repeat",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[req("count", Ty::Int, "how many copies, 0 or more")],
returns: "String",
doc: "The String repeated count times in a row. A negative count is E_BAD_ARG. A result over 100 MB (100000000 bytes) is E_BAD_VALUE, refused before it is built. An empty String repeats to an empty String whatever the count.",
examples: &[
(r#"repeat("ab", 3)"#, r#""ababab""#),
(r#""-" | repeat(5)"#, r#""-----""#),
(r#"(try { repeat("a", -1) } catch e { e.error.code })"#, r#""E_BAD_ARG""#),
(r#"(try { repeat("ab", 100000000) } catch e { e.error.code })"#, r#""E_BAD_VALUE""#),
],
},
Signature {
name: "words",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "Array",
doc: "The words of a String: it is split on any run of whitespace (spaces, tabs, newlines, CRs), and the empty pieces are dropped.",
examples: &[
(r#"words(" the quick fox ")"#, r#"["the", "quick", "fox"]"#),
(r#""a b" | words | len"#, "2"),
],
},
Signature {
name: "log",
category: Some("Math"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Numeric),
params: &[opt("base", Ty::Numeric, "the base of the logarithm: above 0 and not 1; e (natural) by default")],
returns: "Number",
doc: "The logarithm of a number above 0: natural by default, or in the base given. A number of 0 or less is E_BAD_VALUE, and so is a base of 0 or less or of 1. Ints are read as Floats; the result is a Float.",
examples: &[
(r#"log(1)"#, "0.0"),
(r#"log(1, 2)"#, "0.0"),
(r#"(try { log(0) } catch e { e.error.code })"#, r#""E_BAD_VALUE""#),
(r#"(try { log(1, 1) } catch e { e.error.code })"#, r#""E_BAD_VALUE""#),
],
},
Signature {
name: "ln",
category: Some("Math"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Numeric),
params: &[],
returns: "Number",
doc: "The natural logarithm of a number above 0. A number of 0 or less is E_BAD_VALUE.",
examples: &[
(r#"ln(1)"#, "0.0"),
(r#"(try { ln(0) } catch e { e.error.code })"#, r#""E_BAD_VALUE""#),
],
},
Signature {
name: "log10",
category: Some("Math"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Numeric),
params: &[],
returns: "Number",
doc: "The base-10 logarithm of a number above 0. A number of 0 or less is E_BAD_VALUE.",
examples: &[
(r#"log10(1)"#, "0.0"),
(r#"(try { log10(-5) } catch e { e.error.code })"#, r#""E_BAD_VALUE""#),
],
},
Signature {
name: "log2",
category: Some("Math"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Numeric),
params: &[],
returns: "Number",
doc: "The base-2 logarithm of a number above 0. A number of 0 or less is E_BAD_VALUE.",
examples: &[
(r#"log2(1)"#, "0.0"),
(r#"(try { log2(0) } catch e { e.error.code })"#, r#""E_BAD_VALUE""#),
],
},
Signature {
name: "exp",
category: Some("Math"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Numeric),
params: &[],
returns: "Number",
doc: "e raised to the power of a number. A result too large for a Float is E_BAD_VALUE, never an inf.",
examples: &[
(r#"exp(0)"#, "1.0"),
(r#"(try { exp(1000) } catch e { e.error.code })"#, r#""E_BAD_VALUE""#),
],
},
Signature {
name: "from_epoch",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Numeric),
params: &[],
returns: "String",
doc: "An instant given as seconds since 1970-01-01T00:00:00Z, as UTC ISO 8601 to the second, ending in Z. A Float's fraction is dropped. Years 0001 to 9999 only: outside them is E_BAD_VALUE.",
examples: &[
(r#"from_epoch(0)"#, r#""1970-01-01T00:00:00Z""#),
(r#"86400 | from_epoch"#, r#""1970-01-02T00:00:00Z""#),
(r#"(try { from_epoch(253402300800) } catch e { e.error.code })"#, r#""E_BAD_VALUE""#),
],
},
Signature {
name: "to_epoch",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "Int",
doc: "The whole seconds since 1970-01-01T00:00:00Z of an ISO 8601 UTC date or datetime: a datetime with Z or an offset (its offset is applied), or a date as midnight UTC. Years 0001 to 9999 only; text that is not such a date is E_BAD_VALUE.",
examples: &[
(r#"to_epoch("1970-01-02T00:00:00Z")"#, "86400"),
(r#""1970-01-02" | to_epoch"#, "86400"),
(r#"(try { to_epoch("0000-01-01") } catch e { e.error.code })"#, r#""E_BAD_VALUE""#),
],
},
Signature {
name: "trivy_scan",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("path", Ty::Str, "file or directory inside the workspace; default the workspace directory")],
returns: "Record",
doc: "trivy fs --format json <path>, as the JSON Record it prints. Trivy may download its vulnerability database. The path must exist inside the workspace. A nonzero exit is E_TOOL_FAILED, and output that is not JSON is E_TOOL_FAILED. Runs with a 15 minute deadline. Takes no pipeline input.",
examples: &[
(r#"(try { trivy_scan("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { trivy_scan("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "trivy_image",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("image", Ty::Str, "container image reference")],
returns: "Record",
doc: "trivy image --format json <image>, as the JSON Record it prints. Trivy pulls the image from its registry. A nonzero exit is E_TOOL_FAILED, and output that is not JSON is E_TOOL_FAILED. Runs with a 15 minute deadline. Takes no pipeline input.",
examples: &[
(r#"(try { trivy_image("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { trivy_image("alpine:3", "x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "replace",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[req("from", Ty::Str, "text to find"), req("to", Ty::Str, "replacement")],
returns: "String",
doc: "Replace every occurrence of one substring with another.",
examples: &[(r#"replace("aXa", "X", "Y")"#, r#""aYa""#)],
},
Signature {
name: "join",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[req("separator", Ty::Str, "text placed between elements")],
returns: "String",
doc: "Join an array into a string with a separator.",
examples: &[(r#"join(["a", "b"], "-")"#, r#""a-b""#), (r#"["a", "b"] | join("-")"#, r#""a-b""#)],
},
Signature {
name: "keys",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Record),
params: &[],
returns: "Array",
doc: "The field names of a record.",
examples: &[(r#"keys({a: 1, b: 2}) | len"#, "2")],
},
Signature {
name: "values",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Record),
params: &[],
returns: "Array",
doc: "The field values of a record.",
examples: &[(r#"values({a: 1, b: 2}) | sum"#, "3")],
},
Signature {
name: "valgrind_run",
category: None,
subject_required: false,
aliases: &["valgrind"],
subject: None,
params: &[req("program", Ty::Str, "the program to run under memcheck; one word, not starting with '-'")],
returns: "Record",
doc: "valgrind --tool=memcheck <program>: answers {command, exit_code, stdout, report, output_truncated?} where report is valgrind's report on stderr. It runs the program, so its effect is exec and the central gate asks for approval in agent mode. A nonzero exit is E_TOOL_FAILED with the report's tail. The program runs with no arguments of its own. Takes no pipeline input.",
examples: &[
(r#"(try { valgrind_run("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { valgrind_run() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { valgrind_run("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | valgrind_run("a") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "valgrind_memcheck",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("program", Ty::Str, "the program to run under memcheck with full leak checking; one word, not starting with '-'")],
returns: "Record",
doc: "valgrind --tool=memcheck --leak-check=full --show-leak-kinds=all <program>, answering the same fields as valgrind_run. Its effect is exec and the central gate asks for approval in agent mode. A nonzero exit is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { valgrind_memcheck("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { valgrind_memcheck() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { valgrind_memcheck("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | valgrind_memcheck("a") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
// `Any`, not `Array`: it reverses strings too, and declaring it
// `Array` refused `"abc" | reverse`. That shipped in 5a54fc3 and
// survived because the only string test used the function-call
// form, which was not type-checked at the time.
name: "reverse",
category: Some("Array"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[],
returns: "Any",
doc: "Reverse an array or a string.",
examples: &[
("[1, 2, 3] | reverse", r#"[3, 2, 1]"#),
(r#""abc" | reverse"#, r#""cba""#),
(r#"reverse("abc")"#, r#""cba""#),
],
},
Signature {
name: "take",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[req("n", Ty::Int, "how many elements to keep")],
returns: "Array",
doc: "The first n elements of an array.",
examples: &[("[1, 2, 3, 4] | take(2) | len", "2")],
},
Signature {
// Conditional file/count argument roles are checked by the body.
name: "head",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[opt("count_or_path", Ty::Any, "nonnegative representable Int count (default 10), or file String in count-first direct calls")],
returns: "Any",
doc: "Return the first lines of a piped String, or a regular UTF-8 file with head(path,count?) or head(count,path). Preserve both direct argument orders. Counts must be nonnegative representable Int values; zero returns empty text. Normalize CRLF to LF and join without a trailing newline. Validate file read paths and bound reads to 64 MiB. A piped Array gives its first count elements, as take(count) does (default 10).",
examples: &[
(r#""abc" | head"#, r#""abc""#),
(r#""a\nb\nc" | head(2) | split("\n") | len"#, "2"),
(r#"[1, 2, 3, 4] | head(3)"#, "[1, 2, 3]"),
(r#"let d = fs_tempdir("ae_head"); let f = d + "/x"; file_write(f, "a\nb"); let result = head(1, f); rmdir(d, true); result"#, r#""a""#),
],
},
Signature {
name: "save_json",
category: None,
subject_required: false,
aliases: &["write_json"],
subject: None,
params: &[
req("path", Ty::Str, "the file to write, resolved in the workspace"),
opt("value", Ty::Any, "the value to save; piped, the input is the value instead"),
],
returns: "Record",
doc: "Save a value as pretty-printed JSON to a file and return {path, bytes, overwrote, success}. In agent mode or when a workspace is set (`--workspace` or IRONSHELL_WORKSPACE) the path is jailed to the workspace like every local write, so an absolute path outside it is refused. An existing file is replaced, and overwrote says so. Takes the value as an argument or piped, not both.",
examples: &[
(r#"(try { save_json() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { save_json("out.json", 1, 2) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "to_json",
category: None,
subject_required: false,
aliases: &["to-json"],
subject: Some(Ty::Any),
params: &[opt_range("indent", Ty::Int, 0, 8, "spaces per nesting level, 0 to 8; 0 is compact")],
returns: "String",
doc: "Render a value as JSON text, compact, or indented by 1 to 8 spaces per level with an indent argument (0 is compact). The value is piped in or passed as the argument: to_json(v) or to_json(v, indent). A NaN or an infinity has no JSON form, so it is E_BAD_VALUE and the refusal names its path, such as value[0].v; it is not written as 0 or null.",
examples: &[(r#"[1, 2] | to_json"#, r#""[1,2]""#), (r#"to_json([1, 2])"#, r#""[1,2]""#), (r#"to_json([1, 2], 2) | lines | len"#, "4"), (r#"to_json([1, 2], 0)"#, r#""[1,2]""#), (r#"(try { to_json(from_toml("a = nan")) } catch e { e.error.code })"#, "E_BAD_VALUE")],
},
Signature {
name: "ls",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("path", Ty::Str, "directory to list; defaults to the working directory")],
returns: "Array",
doc: "List a directory as records with name, path, size and modified. A file lists as itself, as one record; a glob lists its matches.",
examples: &[
(r#"(ls("src") | len) > 0"#, "true"),
(r#"(ls() | len) > 0"#, "true"),
],
},
Signature {
name: "fs_walk",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "directory to walk recursively")],
returns: "Array",
doc: "The files and the directories beneath a directory, recursively, as paths: a directory is listed as well as what is in it. At most 1,000,000 entries; more is E_BUDGET_EXCEEDED.",
examples: &[(r#"(fs_walk("tests") | len) > 0"#, "true")],
},
Signature {
// Variadic: `pick("name", "size", "modified")` is the form E2's
// corpus uses, and a fixed arity would have removed it.
name: "pick",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[rest("fields", Ty::Str, "field names to keep")],
returns: "Array | Record",
doc: "Keep only the named fields of each record. The subject is an Array of Records (each record becomes one with only those fields) or a single Record (it becomes one Record); any other value is refused with E_BAD_ARG. A field a record does not have is left out of its result, without an error. Piped, the arguments are the field names; called directly, the first argument is the subject.",
examples: &[
(r#"[{a: 1, b: 2}] | pick("a") | first | keys | len"#, "1"),
(r#"pick({a: 1, b: 2}, "a") | keys | len"#, "1"),
(r#"pick({a: 1, b: 2}, "a", "zz") | keys | len"#, "1"),
],
},
Signature {
name: "chunk",
category: Some("Array"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[req("size", Ty::Int, "elements per piece, an Int of at least 1")],
returns: "Array",
doc: "Split an Array into consecutive pieces of size elements, each an Array. The last piece is shorter when the length is not a multiple of size; an empty Array gives no pieces. A size below 1 is refused with E_BAD_ARG. Piped, the size is the argument; called directly, the array comes first.",
examples: &[
("[1, 2, 3] | chunk(2) | len", "2"),
("[1, 2, 3] | chunk(2)", "[[1, 2], [3]]"),
("chunk([1, 2, 3, 4], 2)", "[[1, 2], [3, 4]]"),
],
},
Signature {
name: "get",
category: Some("Core"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[
req("path", Ty::Any, "a field name, a dotted path such as \"u.n\", or an Array of keys and indices"),
opt("default", Ty::Any, "returned when a step is missing or Null; Null when omitted"),
],
returns: "Any",
doc: r#"Read an optional field without an error. Returns the value at path, or default (Null when omitted) when any step of the path is missing or Null, or when the value found is Null. The path is a field name, a dotted path ("u.n" reads r.u.n), or an Array of keys and indices (negative indices count from the end). A field whose own name holds a dot is matched by its whole name first. Plain r.field stays strict: a missing field is E_UNKNOWN_FIELD. Piped, the arguments are the path and the default; called directly, the first argument is the subject."#,
examples: &[
(r#"{u: {n: 5}} | get("u.n", 0)"#, "5"),
(r#"get({u: {n: 5}}, "u.n")"#, "5"),
(r#"{a: 1} | get("b", 0)"#, "0"),
(r#"typeof(get({a: 1}, "b"))"#, "Null"),
(r#"get({u: null}, "u.n", "none")"#, r#""none""#),
(r#"get({xs: [10, 20]}, ["xs", 1])"#, "20"),
],
},
Signature {
name: "has",
category: Some("Core"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[req("key", Ty::Any, "a String field name for a Record, an Int index for an Array")],
returns: "Bool",
doc: "Whether a Record has the field key (an Array has the Int index). A field that holds Null is present: has tells absent from Null, which get does not. Piped, the argument is the key; called directly, the first argument is the subject.",
examples: &[
(r#"{a: 1} | has("a")"#, "true"),
(r#"has({a: 1}, "b")"#, "false"),
(r#"{a: null} | has("a")"#, "true"),
],
},
Signature {
name: "to_entries",
category: Some("Core"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Record),
params: &[],
returns: "Array",
doc: "A Record as an Array of {key, value} records, in the order a Record iterates (sorted by key). The inverse of from_entries.",
examples: &[
("{a: 1} | to_entries", r#"[{key: "a", value: 1}]"#),
("to_entries({a: 1, b: 2}) | len", "2"),
],
},
Signature {
name: "from_entries",
category: Some("Core"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[],
returns: "Record",
doc: "Build a Record from an Array of {key, value} records or [key, value] pairs. A later entry with the same key wins. A key that is not a String is refused with E_BAD_ARG naming the entry's index. The inverse of to_entries.",
examples: &[
(r#"[["a", 1], ["b", 2]] | from_entries"#, "{a: 1, b: 2}"),
(r#"from_entries([{key: "a", value: 1}, {key: "a", value: 2}])"#, "{a: 2}"),
(r#"{a: 1} | to_entries | from_entries"#, "{a: 1}"),
],
},
Signature {
// Categorised by hand: `categorize_builtin` read the name and filed
// this under Archive, next to the compression builtins.
name: "zip",
category: Some("Array"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[req("other", Ty::Array, "array to pair with, element by element")],
returns: "Array",
doc: "Pair two arrays element by element, stopping at the shorter one.",
examples: &[
("zip([1, 2], [3, 4]) | len", "2"),
("[1, 2] | zip([3, 4]) | first | len", "2"),
("zip([1, 2, 3], [4]) | len", "1"),
],
},
Signature {
// The direct form takes the same subject as the piped one: `uniq([1, 1, 2])`
// and `[1, 1, 2] | uniq` are the same call.
name: "uniq",
category: Some("Array"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Sequence),
params: &[],
returns: "Array",
doc: "Remove ADJACENT duplicate elements, like Unix uniq: [1, 1, 2, 1] keeps the second 1. The subject is an Array, piped or as the argument. A String is split into lines first (one element per line, as lines does), then its adjacent duplicates are dropped: \"a\\na\\nb\" gives [\"a\", \"b\"]. Only adjacent duplicates go, as in Unix uniq; for every duplicate, not only neighbours, use unique or arr.unique. The -c flag is accepted and ignored.",
examples: &[
("[1, 1, 2] | uniq | len", "2"),
("uniq([1, 1, 2, 1])", "[1, 2, 1]"),
(r#""a\na\na\nb" | uniq"#, r#"["a", "b"]"#),
],
},
Signature {
name: "abs",
category: Some("Math"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Numeric),
params: &[],
returns: "Number",
doc: "Absolute value of a number.",
examples: &[("abs(-2)", "2")],
},
Signature {
name: "sqrt",
category: Some("Math"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Numeric),
params: &[],
returns: "Number",
doc: "Square root of a number.",
examples: &[("sqrt(16)", "4.0")],
},
Signature {
name: "pow",
category: Some("Math"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Numeric),
params: &[req("exponent", Ty::Numeric, "the power to raise to")],
returns: "Number",
doc: "Raise a number to a power.",
examples: &[("pow(2, 3)", "8")],
},
Signature {
name: "pre_commit_run",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("hook", Ty::Str, "a hook id, or \"--all-files\" to run every file; omitted runs the hooks on the staged files")],
returns: "Record",
doc: "Runs `pre-commit run [hook | --all-files]` with no shell. Hooks may create environments or rewrite files; the deadline is 15 minutes. Returns {exit_code: 0, success: true, stdout, stderr}; a failing hook is E_TOOL_FAILED with the end of the output. A missing pre-commit is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | pre_commit_run() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { pre_commit_run("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "pre_commit_install",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Runs `pre-commit install`, which writes the git hook into the repository's .git directory. The working directory must lie inside the workspace. Returns {exit_code: 0, success: true, stdout, stderr}; a nonzero exit is E_TOOL_FAILED. Takes no arguments and no pipeline input.",
examples: &[
(r#"(try { "x" | pre_commit_install() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { pre_commit_install("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "floor",
category: Some("Math"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Numeric),
params: &[],
returns: "Int",
doc: "Largest integer not greater than a number.",
examples: &[("floor(2.7)", "2")],
},
Signature {
name: "ceil",
category: Some("Math"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Numeric),
params: &[],
returns: "Int",
doc: "Smallest integer not less than a number.",
examples: &[("ceil(2.1)", "3")],
},
Signature {
name: "range",
category: Some("Array"),
subject_required: false,
aliases: &[],
subject: None,
params: &[req("start_or_count", Ty::Int, "count when alone, start when an end follows"), opt("end", Ty::Int, "exclusive upper bound")],
returns: "Array",
doc: "A range of integers: range(n) is 0..n, range(a, b) is a..b. At most 10,000,000 elements; a longer range is refused with BudgetExceeded before anything is built.",
examples: &[("range(3) | len", "3"), ("range(1, 4) | first", "1")],
},
Signature {
name: "typeof",
category: Some("Core"),
subject_required: false,
aliases: &["type_of"],
subject: Some(Ty::Any),
params: &[],
returns: "String",
doc: "The type name of a value.",
examples: &[(r#"type_of(42)"#, r#""Int""#), (r#"typeof("x")"#, r#""String""#)],
},
Signature {
name: "grep",
category: Some("Text"),
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pattern", Ty::Str, "a basic regular expression: ^ and $ anchor, . is any character; + ? | ( ) { } are literal unless backslashed (\\+ \\? \\| \\( \\) \\{ \\}); there is no grep -E, so use regex_match for extended syntax"), opt("path", Ty::Str, "file to search; omit to search the piped text"), opt("options", Ty::Record, "{line_numbers: true} returns {file, line, text} records instead of lines; line counts from 1 in each file, and file is null for piped text")],
returns: "Array",
doc: "Lines matching a basic regular expression; a back-reference such as \\1 is refused, and a pattern that does not compile says why. With {line_numbers: true} each match is a record {file, line, text} instead, the line numbered from 1 within its file (null for piped text).",
examples: &[(r#"grep("fn main", "src/main.rs") | len"#, "1"), (r#"(grep("fn", "src/main.rs") | len) > 0"#, "true"), (r#"grep("^version", "Cargo.toml") | len"#, "1"), (r#"grep("^version", "Cargo.toml", {line_numbers: true}) | first | fn(r) => r.file"#, r#""Cargo.toml""#), (r#""a\nb\na" | grep("a", {line_numbers: true}) | last | fn(r) => r.line"#, "3")],
},
Signature {
name: "find",
category: Some("FileSystem"),
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "directory to search"), opt("pattern", Ty::Str, "glob such as *.rs; omit for every file")],
returns: "Array",
doc: "Files under a directory, optionally matching a glob. At most 1,000,000 entries; more is E_BUDGET_EXCEEDED.",
examples: &[(r#"(find("src", "*.rs") | len) > 0"#, "true"), (r#"(find("src") | len) > 0"#, "true")],
},
Signature {
// The design document names this a core verb, and the hybrid arm of E1
// is built on it. It was described as `sql() -> Value`, "Sql", with no
// parameters -- and it answered three calls it could not honour:
//
// sqlite_query(":memory:") exit 0, no output
// sqlite_query() exit 0, no output
// sqlite_query(db, "SELECT ? AS n", [7]) exit 0, n = null
//
// The first two are the worst kind: an agent asks for data, and gets
// silence and success. The third accepts bind parameters and discards
// them, which is `round(4.966, 2)` returning 5 in a different costume.
// Declaring two required parameters and no more refuses all three.
//
// Bind parameters are genuinely unsupported; that is now visible in the
// signature instead of being discovered when a query returns nulls.
//
// Since src/sql.rs it runs in-process and read-only, and takes rows as
// well as databases: `rows | sql(query)` is the borrowed front-end
// docs/LANGUAGE_FIRST_PRINCIPLES.md §3 asks for. One argument is the
// query over the piped rows; two are a source and a query.
name: "sql",
category: Some("Database"),
subject_required: false,
aliases: &["sqlite_query", "db_sqlite_query"],
subject: Some(Ty::Any),
// A trailing `params` Array is matched by its own type: the validator
// lets the last argument skip `query` when it is not a String.
params: &[
req(
"source_or_query",
Ty::Str,
"with rows piped in, the query (they are table `t`); alone, the query over an empty database; otherwise a source: a .json/.jsonl/.csv/.tsv file (a table named after the file, also `t`; an empty CSV or TSV cell is NULL), a SQLite file, or \":memory:\"",
),
opt(
"query",
Ty::Str,
"the read-only SQL to run against the source; each ? in it takes the next value of params",
),
opt(
"params",
Ty::Array,
"bind values for the placeholders, in order: Int, Float, String, Bool or null; SQLite's ?, ?N, :name, @name and $name forms all bind by position from this Array, and a String binds as text, so pass 1, not \"1\", to compare with a number",
),
],
returns: "Array",
doc: "Run a read-only SQL query over piped rows, rows given as the first argument, a JSON/CSV file or a SQLite database, returning rows as records. A query with no rows and no source runs over an empty database: sql(\"select 1 as x\") answers [{x: 1}]. A trailing params Array binds its values to the query's ? placeholders in order, so a value is never spliced into the query text. With params and no rows the query runs over the same empty database: sql(\"select ? + 1 as y\", [41]) answers [{y: 42}]. A table in the query needs rows or a source first: sql(source, query, params).",
examples: &[
(
r#"sql("select 1 as x") | first | fn(r) => r.x"#,
"1",
),
(
r#"[{n: 1}, {n: 2}, {n: 3}] | sql("select sum(n) as total from t") | first | fn(r) => r.total"#,
"6",
),
(
r#"sql([{n: 1}, {n: 2}, {n: 3}], "select sum(n) as total from t") | first | fn(r) => r.total"#,
"6",
),
(
r#"sqlite_query(":memory:", "SELECT 1 AS n") | first | fn(r) => r.n"#,
"1",
),
(r#"sql(":memory:", "SELECT 2 AS n") | len"#, "1"),
(
r#"[{n: 1}, {n: 2}, {n: 3}] | sql("select n from t where n > ?", [1]) | len"#,
"2",
),
(
r#"sql(":memory:", "SELECT ? AS n", [7]) | first | fn(r) => r.n"#,
"7",
),
(
r#"sql("select ? + 1 as y", [41]) | first | fn(r) => r.y"#,
"42",
),
],
},
Signature {
// docs/LANGUAGE_FIRST_PRINCIPLES.md §6: containment an agent can ask
// about before running, instead of discovering by being refused.
name: "explain_effects",
category: Some("Safety"),
subject_required: false,
aliases: &[],
subject: None,
params: &[req("code", Ty::Str, "IronShell source to analyse; it is parsed, never run")],
returns: "Record",
doc: "Every call in a program with its effect class and agent-mode decision, and the strictest decision overall, without running it.",
examples: &[
(r#"explain_effects("[1, 2] | map(fn(x) => x + 1)") | fn(r) => r.decision"#, "allow"),
(r#"explain_effects("rm(1)") | fn(r) => r.effects"#, r#"["destructive"]"#),
],
},
Signature {
// E2's t2 was 38 tokens against bash's 11 largely for want of this:
// `len(split(cat(f.path), "\n"))` per file, where bash says `wc -l`.
name: "lines",
category: Some("String"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[opt("text", Ty::Str, "the text, when it is not piped in")],
returns: "Array",
doc: "Split text into lines without their terminators; a final newline adds no empty line.",
examples: &[
(r#""a\nb" | lines"#, r#"["a", "b"]"#),
(r#"lines("a\nb\n") | len"#, "2"),
(r#""x\r\ny" | lines | last"#, r#""y""#),
],
},
Signature {
// Borrowed from nushell, which answered E2's t6 in 14 tokens with
// `open Cargo.toml | get package.version` while IronShell split the
// file into lines and searched them.
name: "open",
category: Some("FileSystem"),
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a file; .json, .jsonl, .toml, .yaml/.yml, .csv and .tsv are parsed")],
returns: "Any",
doc: "Read a file and parse it by extension (JSON, JSON lines, TOML, YAML, CSV, TSV), or return its text. A .tsv file is read like a .csv one with a tab delimiter: a header row, columns typed by the same inference, and no quoting (a quote character is data). A file that does not parse is E_BAD_VALUE, not retryable, and its hint gives the line and column.",
examples: &[
(r#"open("Cargo.toml").package.name"#, r#""iron-shell""#),
(r#"typeof(open("README.md"))"#, "String"),
],
},
Signature {
// The scalar half of `sql`. E1's hybrid arm paid `|first|values|first`
// on every answer to get one number out of a one-row result; this is
// that, with a refusal when the result is not one cell instead of a
// silently different type.
name: "sql_value",
category: Some("Database"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
// A trailing params Array skips `query` by its type, as in `sql`.
params: &[
req(
"source_or_query",
Ty::Str,
"with rows piped in, the query (they are table `t`); otherwise a source, as for sql",
),
opt("query", Ty::Str, "the read-only SQL to run against the source; each ? in it takes the next value of params"),
opt(
"params",
Ty::Array,
"bind values for the placeholders, in order: Int, Float, String, Bool or null; SQLite's ?, ?N, :name, @name and $name forms all bind by position from this Array, and a String binds as text, so pass 1, not \"1\", to compare with a number",
),
],
returns: "Any",
doc: "Run a read-only SQL query that yields exactly one row of one column, returning that value. Rows may be piped in or given as the first argument, as for sql; a query alone runs over an empty database, so sql_value(\"select 1 + 1\") is 2. A trailing params Array binds its values to the query's ? placeholders in order, as for sql.",
examples: &[
(r#"[{n: 1}, {n: 2}, {n: 3}] | sql_value("select max(n) from t")"#, "3"),
(r#"sql_value([{n: 1}, {n: 2}, {n: 3}], "select count(*) from t where n > ?", [1])"#, "2"),
(r#"sql_value(":memory:", "select 6 * 7")"#, "42"),
(r#"sql_value(":memory:", "select ? * 6", [7])"#, "42"),
(r#"[{n: 1}, {n: 2}, {n: 3}] | sql_value("select count(*) from t where n > ?", [1])"#, "2"),
(r#"sql_value("select 1 + 1")"#, "2"),
(r#"sql_value("select ? * 2", [21])"#, "42"),
],
},
Signature {
// Works on arrays and on strings, so the subject is `Any` -- narrowing
// it to Array would have deleted `"abcdef" | slice(1, 3)`.
name: "slice",
category: Some("Array"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[
req("start", Ty::Int, "first index to keep, counting from zero; a negative index counts from the end"),
opt("end", Ty::Int, "index to stop before, counting from zero or, when negative, from the end; omit to run to the end"),
],
returns: "Any",
doc: "A sub-range of an array or a string, with Python's indices: slice(-3) is the last three, slice(0, -1) drops the last, and each index is clamped to the length. Strings are sliced by character. A start at or past the end gives an empty result.",
examples: &[
("[1, 2, 3, 4, 5] | slice(1, 3) | len", "2"),
("[1, 2, 3, 4, 5] | slice(2) | len", "3"),
("[1, 2, 3, 4, 5] | slice(-2) | len", "2"),
(r#""abcdef" | slice(1, 3)"#, r#""bc""#),
(r#""hello" | slice(-3)"#, r#""llo""#),
],
},
Signature {
// `subject: None` on purpose. With a piped subject `cat` is a
// passthrough -- `"Cargo.toml" | cat` returns the string, it does not
// read the file -- so the path is a parameter, not a subject. Declaring
// a subject would have made `cat("Cargo.toml")` treat the path as the
// subject and then complain the path was missing.
//
// `path` is optional for the same reason: required would refuse the
// passthrough form. That leaves `cat()` still answering E_UNKNOWN ("no
// file specified"), which a declaration cannot reach -- the contract is
// "a piped subject OR a path" and this model cannot say that. Two of
// the three defects go, and the third is written down rather than
// implied:
//
// cat({unexpected: true}) was E_UNKNOWN, now E_BAD_ARG
// cat("Cargo.toml", "README.md") silently ignored the second file
// cat() still E_UNKNOWN; needs a body change
name: "cat",
category: Some("FileSystem"),
subject_required: false,
aliases: &[],
subject: None,
params: &[opt(
"path",
Ty::Str,
"file to read; omit when the content arrives through the pipe",
)],
returns: "String",
doc: "Read a file as text, or pass piped text through unchanged.",
examples: &[
(r#"(cat("Cargo.toml") | len) > 0"#, "true"),
(r#""passthrough" | cat"#, r#""passthrough""#),
],
},
Signature {
name: "consensus_net", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "network name"), req("agent_count", Ty::Int, "positive; at most 1024"), req("input_size", Ty::Int, "positive state dimension"), req("hidden_size", Ty::Int, "positive message dimension"), req("output_size", Ty::Int, "positive decision dimension")], returns: "Record",
doc: "Create a randomly initialized consensus network with three message-passing rounds and Softmax decisions. Refuse invalid sizes and more than one million total weights and biases before allocation, including retained per-agent networks.",
examples: &[(r#"consensus_net("example", 2, 2, 2, 2).agent_count"#, "2")],
},
Signature {
name: "consensus_vote", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record),
params: &[req("agent_inputs", Ty::Array, "exactly one row of finite numbers per agent, each of state_dim length")], returns: "Record",
doc: "Run shared encoder/message/decision networks and return decisions, their mean consensus, and confidence 1/(1+mean squared disagreement). Retained per-agent networks are validated but not evaluated. Encoded networks are limited to 64 MiB, one million total parameters, 1024 agents and 16 rounds; malformed shapes and non-finite results are refused.",
examples: &[(r#"consensus_vote(consensus_net("example", 2, 2, 2, 2), [[0, 0], [0, 0]]).decisions | len"#, "2"), (r#"let result = consensus_net("example", 2, 2, 2, 2) | consensus_vote([[0, 0], [0, 0]]); result.consensus | len"#, "2")],
},
Signature {
name: "population", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("size", Ty::Int, "positive; at most 10000"), req("genome_type", Ty::Str, "nn, vec or vector"), opt("config", Ty::Record, "mutation_rate, mutation_strength, crossover_rate, generations, elitism; optional population_size must equal size")], returns: "Record",
doc: "Create an unevaluated random population. nn genomes have layers [4,8,4] with relu/tanh; vec/vector genomes have ten equal random Float values per individual. Size is bounded before allocation. Configurations accept only the documented numeric fields and the evolution_config type marker; rates are finite probabilities, strength is finite and non-negative, generations is an Int in 0..=10000, and elitism is an Int in 0..=size (default min(2,size)). Returned initial stats use negative/positive infinity for unevaluated best/worst fitness. Selection and crossover use engine defaults; strategy descriptors and seed options are unsupported.",
examples: &[(r#"population(3, "nn").size"#, "3"), (r#"population(3, "vector", {mutation_rate: 0, mutation_strength: 0, crossover_rate: 1, generations: 0, elitism: 1}).genome_type"#, "vec"), (r#"population(3, "vec", evolution_config({population_size: 3})).generation"#, "0")],
},
Signature {
name: "fitness", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record),
params: &[req("fitness_fn", Ty::Lambda, "one genome parameter; return a finite Int or Float")], returns: "Record",
doc: "Evaluate only individuals without cached fitness, update statistics once and return a population copy. Propagate the first callback failure or invalid score immediately. Validate encoded populations before callbacks: nonempty compatible genomes, finite parameters and fitness, matching configured size, unique IDs, valid counters and numeric configuration. Limits: 64 MiB encoding, 10000 individuals/history entries and one million total genome parameters. Preserve history and next_id; legacy states without next_id derive it from the largest existing ID. Numeric overflow produces a coded refusal.",
examples: &[(r#"fitness(population(3, "vec"), fn(g) => 7).stats.best_fitness"#, "7.0"), (r#"let result = population(3, "nn") | fitness(fn(g) => g.param_count); result.stats.avg_fitness"#, "76.0")],
},
Signature {
name: "evolve", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record),
params: &[req("fitness_fn", Ty::Lambda, "one genome parameter; return a finite Int or Float"), opt("generations", Ty::Int, "0..=10000; default 10, independently of stored config.generations")], returns: "Record",
doc: "Run the requested generations on a validated population copy. Each generation evaluates uncached parents before selection, crossover and mutation; propagate callback failures and invalid scores immediately. Return new offspring with unevaluated fitness and retained elite caches; statistics describe evaluated parents, so call fitness before ranking the final population. Preserve history and ID allocation. Encoded population limits match fitness. Before callbacks, cap requested work at 100000 individual-generation pairs, ten million parameter-generation pairs and 10000 total history entries; refuse counter overflow and non-finite computed results. Zero generations only validates and returns the state.",
examples: &[(r#"evolve(population(3, "vec"), fn(g) => 1).generation"#, "10"), (r#"evolve(population(3, "nn"), fn(g) => 1, 0).generation"#, "0"), (r#"let result = population(3, "vec") | evolve(fn(g) => 1, 2); result.generation"#, "2")],
},
Signature {
name: "evolve_step", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record),
params: &[req("fitness_fn", Ty::Lambda, "one genome parameter; return a finite Int or Float")], returns: "Record",
doc: "Run one generation with the same validated-state, callback, work-budget and numeric-overflow checks as evolve. Return a population copy with preserved history and IDs. Statistics describe evaluated parents; offspring fitness remains uncached until fitness or the next generation evaluates it.",
examples: &[(r#"evolve_step(population(3, "vec"), fn(g) => 1).generation"#, "1"), (r#"let result = population(3, "nn") | evolve_step(fn(g) => 1); result.generation"#, "1")],
},
Signature {
name: "best_individual", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record), params: &[], returns: "Record",
doc: "Return genome, finite fitness, generation and id for the highest-scoring individual in a validated, fully evaluated population. Refuse missing fitness with E_BAD_STATE; call fitness to evaluate fresh populations and offspring. Equal scores select the last matching individual. Encoded population limits match fitness.",
examples: &[(r#"best_individual(fitness(population(3, "vec"), fn(g) => 7)).fitness"#, "7.0"), (r#"let result = population(3, "nn") | fitness(fn(g) => 1) | best_individual; result.fitness"#, "1.0")],
},
Signature {
name: "black_format",
category: None,
subject_required: false,
aliases: &["black"],
subject: None,
params: &[opt("path", Ty::Str, "a file or directory inside the workspace; defaults to the working directory")],
returns: "Record",
doc: "Runs `black <path>`, which rewrites Python files in place. The path must lie inside the workspace. Returns {path, exit_code: 0, success: true, stdout, stderr}; a nonzero exit is E_TOOL_FAILED. Deadline 10 minutes; a missing black is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | black_format() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { black_format("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "coevolve", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Array),
params: &[req("fitness_fn", Ty::Lambda, "one genome parameter; finite numeric result"), opt("generations", Ty::Int, "0..=10000; default 10 independently of stored configurations")], returns: "Array",
doc: "Evolve each population independently with the same callback, in input order; no cross-population fitness or mating is performed. Allow an empty batch. Validate every population and counter before callbacks, propagate callback failures immediately, and preserve caches, histories and IDs. Use evolve semantics for parent statistics and unevaluated offspring. Combined batch limits: 64 MiB encoding, 10000 populations/individuals, one million genome parameters, 10000 existing plus requested history entries, 100000 individual-generation pairs and ten million parameter-generation pairs. Refuse non-finite scores and computed results.",
examples: &[(r#"coevolve([population(3, "vec"), population(3, "nn")], fn(g) => 1) | map(fn(p) => p.generation)"#, "[10, 10]"), (r#"[population(3, "vec")] | coevolve(fn(g) => 1, 2) | map(fn(p) => p.generation)"#, "[2]"), (r#"coevolve([], fn(g) => 1, 0)"#, "[]")],
},
Signature {
name: "gui_find_image", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("haystack", Ty::Str, "path to a PNG, JPEG, GIF or WebP image to search"), req("needle", Ty::Str, "path to the image to find; must fit inside the haystack in both dimensions"), opt("options", Ty::Record, "tolerance: Int 0..=255, default 0, the largest absolute per-channel RGBA8 difference that still matches; all: Bool, default false; limit: Int 1..=1000, default 100, the cap on matches when all is true")], returns: "Record | Null | Array",
doc: "Find the needle image inside the haystack image by exact template matching over decoded RGBA8 pixels, with no screen capture and no effects beyond reading the two files. A pixel matches when each of its four channels differs from the haystack pixel under it by at most tolerance. Positions are the needle's top-left corner in haystack coordinates, scanned row by row, left to right. With all false (the default), return the first match as Record {x, y, width, height} with Int fields, or Null when nothing matches. With all true, return an Array of such Records in row-major order, including overlapping matches, capped at limit; an empty Array means no match. Both paths go through the usual read guards and must be regular files; a missing file is E_NOT_FOUND, an unreadable one E_IO or E_POLICY_DENY, and a file that does not decode as an image is E_BAD_ARG. Refused before any pixel is decoded: an image above 40000000 pixels (E_BUDGET_EXCEEDED, from the header), a needle larger than the haystack in either dimension (E_BAD_ARG), and a search whose worst case exceeds 40000000000 pixel comparisons (E_BUDGET_EXCEEDED). Unknown option keys, wrong option types and out-of-range values are E_BAD_ARG, as are pipeline input and surplus arguments.",
examples: &[(r#"(try { gui_find_image("a.png") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_find_image("a.png", "b.png", {bogus: 1}) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "rl_agent", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "agent name"), req("state_size", Ty::Int, "positive state count"), req("action_size", Ty::Int, "positive action count; at most 10000"), opt("config", Ty::Record, "learning_rate, discount, epsilon: finite numbers in 0..=1")], returns: "Record",
doc: "Create an empty tabular Q-learning agent. Refuse invalid dimensions or more than one million possible state-action cells. Defaults: learning_rate 0.1, discount 0.99, epsilon 0.1. Unknown or wrong-typed options are refused. Encoded Q-table rows are sorted [state,action,value] triples; legacy empty-object tables remain readable.",
examples: &[(r#"rl_agent("example", 2, 3).action_size"#, "3"), (r#"rl_agent("example", 2, 3, {learning_rate: 1, discount: 0, epsilon: 0}).epsilon"#, "0.0")],
},
Signature {
name: "rl_action", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record),
params: &[req("state", Ty::Int, "in 0..state_size")], returns: "Int",
doc: "Select an action using epsilon-greedy Q-learning policy without updating the agent. With epsilon zero, return the highest Q-value action, choosing the last action on ties. Validate encoded rates, dimensions, counters and table rows; cap encoding at 64 MiB, actions at 10000 and state-action cells at one million.",
examples: &[(r#"rl_action(rl_agent("example", 2, 3, {epsilon: 0}), 0)"#, "2"), (r#"rl_agent("example", 2, 1) | rl_action(1)"#, "0")],
},
Signature {
name: "rl_update", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record),
params: &[req("state", Ty::Int, "in 0..state_size"), req("action", Ty::Int, "in 0..action_size"), req("reward", Ty::Numeric, "finite reward"), req("next_state", Ty::Int, "in 0..state_size, including terminal transitions"), req("done", Ty::Bool, "terminal transition")], returns: "Record",
doc: "Return an updated agent copy using Q += learning_rate*(reward + discount*max_next_Q - Q), with max_next_Q zero for terminal transitions. Increment steps once and multiply epsilon by epsilon_decay while it exceeds epsilon_min (defaults 0.995 and 0.01). Preserve sorted Q-table rows. Validate encoded state as in rl_action, refuse invalid indices/counter overflow and return a coded error for non-finite computed values.",
examples: &[(r#"rl_update(rl_agent("example", 2, 2), 0, 1, 5, 1, true).steps"#, "1"), (r#"let result = rl_agent("example", 2, 2) | rl_update(0, 1, 5, 1, false); result.steps"#, "1")],
},
Signature {
name: "rl_sarsa_agent", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "agent name"), req("state_size", Ty::Int, "positive state count"), req("action_size", Ty::Int, "positive action count; at most 10000")], returns: "Record",
doc: "Create an empty tabular SARSA agent with fixed learning_rate 0.1, discount 0.99 and epsilon 0.1. Limit the state-action space to one million cells. No configuration argument is supported. Encode Q-values as sorted [state,action,value] rows; legacy empty-object tables remain readable.",
examples: &[(r#"rl_sarsa_agent("example", 2, 3).action_size"#, "3")],
},
Signature {
name: "rl_sarsa_update", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record),
params: &[req("state", Ty::Int, "in 0..state_size"), req("action", Ty::Int, "in 0..action_size"), req("reward", Ty::Numeric, "finite reward"), req("next_state", Ty::Int, "in 0..state_size, including terminal transitions"), req("next_action", Ty::Int, "in 0..action_size, including terminal transitions"), req("done", Ty::Bool, "terminal transition")], returns: "Record",
doc: "Return an updated agent copy using Q += learning_rate*(reward + discount*Q(next_state,next_action) - Q), with the next Q-value zero for terminal transitions. Increment steps once and preserve epsilon. Validate dimensions, finite probability rates, counters and unique finite table rows before updating; cap encoding at 64 MiB, actions at 10000 and possible state-action cells at one million. Refuse counter overflow and non-finite computed results.",
examples: &[(r#"rl_sarsa_update(rl_sarsa_agent("example", 2, 2), 0, 1, 5, 1, 0, true).steps"#, "1"), (r#"let result = rl_sarsa_agent("example", 2, 2) | rl_sarsa_update(0, 1, 5, 1, 0, false); result.steps"#, "1")],
},
Signature {
name: "rl_pg_agent", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "agent name"), req("state_dim", Ty::Int, "positive state width"), req("action_size", Ty::Int, "positive action count; at most 10000")], returns: "Record",
doc: "Create a linear softmax policy with random weights in [-0.1,0.1), fixed learning_rate 0.01 and discount 0.99. Refuse more than one million weights before allocation. No configuration argument is supported. Start with empty episode history and zero completed episodes.",
examples: &[(r#"rl_pg_agent("example", 2, 3).action_size"#, "3")],
},
Signature {
name: "rl_pg_step", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record),
params: &[req("state", Ty::Array, "exactly state_dim finite numbers"), req("action", Ty::Int, "in 0..action_size"), req("reward", Ty::Numeric, "finite reward")], returns: "Record",
doc: "Return an agent copy with one recorded step; do not update weights or completed-episode count. Validate encoded dimensions, weight shapes, rates, counters and aligned episode arrays. Limit encoding to 64 MiB, episode length to 10000 and stored state values to one million. Refuse wrong-width/non-finite states and invalid actions/rewards.",
examples: &[(r#"rl_pg_step(rl_pg_agent("example", 2, 2), [1, 0], 1, 5).episodes"#, "0"), (r#"let result = rl_pg_agent("example", 2, 2) | rl_pg_step([1, 0], 1, 5); result.episodes"#, "0")],
},
Signature {
name: "rl_pg_episode_end", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record),
params: &[], returns: "Record",
doc: "Return an agent copy updated by REINFORCE: compute discounted returns, subtract their mean, then update linear softmax weights sequentially in recorded step order. A nonempty episode clears all history arrays and increments episodes once; an empty episode remains unchanged. Validate encoded state as in rl_pg_step; refuse counter overflow, more than ten million weight-step pairs or non-finite computed weights.",
examples: &[(r#"rl_pg_episode_end(rl_pg_agent("example", 2, 2)).episodes"#, "0"), (r#"let result = rl_pg_agent("example", 2, 2) | rl_pg_step([1, 0], 1, 5) | rl_pg_episode_end; result.episodes"#, "1")],
},
Signature {
name: "rl_ac_agent", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "agent name"), req("state_dim", Ty::Int, "positive state width"), req("action_size", Ty::Int, "positive action count; at most 10000")], returns: "Record",
doc: "Create linear softmax actor and linear value critic with random weights in [-0.1,0.1), actor_lr and critic_lr 0.01, discount 0.99 and zero steps. Check dimensions and combined actor/critic weight count at most one million before allocation. No configuration argument is supported.",
examples: &[(r#"rl_ac_agent("example", 2, 3).action_size"#, "3")],
},
Signature {
name: "rl_ac_update", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record),
params: &[req("state", Ty::Array, "exactly state_dim finite numbers"), req("action", Ty::Int, "in 0..action_size"), req("reward", Ty::Numeric, "finite reward"), req("next_state", Ty::Array, "exactly state_dim finite numbers, including terminal transitions"), req("done", Ty::Bool, "terminal transition")], returns: "Record",
doc: "Return an agent copy updated using TD error reward + discount*V(next_state) - V(state), with next value zero when terminal. Compute both values before changing critic weights, then update critic and softmax actor from that same TD error and increment steps once. Validate encoded shapes, finite probability rates and weights; cap encoding at 64 MiB, actions at 10000 and combined weights at one million. Refuse counter overflow and non-finite computed weights.",
examples: &[(r#"rl_ac_update(rl_ac_agent("example", 2, 2), [1, 0], 1, 5, [0, 1], true).steps"#, "1"), (r#"let result = rl_ac_agent("example", 2, 2) | rl_ac_update([1, 0], 1, 5, [0, 1], false); result.steps"#, "1")],
},
Signature {
name: "rl_dqn_agent", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "agent name"), req("state_dim", Ty::Int, "positive state width"), req("action_size", Ty::Int, "positive action count; at most 10000"), opt("hidden_sizes", Ty::Array, "at most 126 positive Int widths; default [64,64]; empty means no hidden layers")], returns: "Record",
doc: "Create matching policy/target networks with ReLU hidden layers and linear Q outputs, checking combined parameters at most one million before allocation. Defaults: learning_rate 0.001, discount 0.99, epsilon 1, epsilon_decay 0.995, epsilon_min 0.01, replay capacity 10000, batch size 32, target update frequency 100, steps zero. Batch training uses selected-action mean squared TD loss and SGD backpropagation, with a detached target network.",
examples: &[(r#"rl_dqn_agent("example", 2, 3).action_size"#, "3"), (r#"rl_dqn_agent("example", 2, 3, []).buffer_size"#, "0")],
},
Signature {
name: "rl_dqn_step", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record),
params: &[req("state", Ty::Array, "exactly state_dim finite numbers"), req("action", Ty::Int, "in 0..action_size"), req("reward", Ty::Numeric, "finite reward"), req("next_state", Ty::Array, "exactly state_dim finite numbers, including terminal transitions"), req("done", Ty::Bool, "terminal transition")], returns: "Record",
doc: "Return an agent copy with its experience stored in circular replay. At batch_size, sample replay with replacement and update policy weights/biases by batch-mean SGD for half squared TD loss, differentiating only the selected action and holding target values fixed; terminal transitions do not bootstrap. Increment steps, copy the trained policy to the target at its update frequency, and decay epsilon while above epsilon_min. Reject non-finite training arithmetic without returning changed state; cap estimated training work at twenty million dense operations. Validate both networks, matching architectures, rates, positive batch/frequency, replay entries/position and counters; cap encoding at 64 MiB, combined network parameters and stored state values separately at one million, and replay capacity/actions at 10000.",
examples: &[(r#"rl_dqn_step(rl_dqn_agent("example", 2, 2, []), [1, 0], 1, 5, [0, 1], true).steps"#, "1"), (r#"let result = rl_dqn_agent("example", 2, 2) | rl_dqn_step([1, 0], 1, 5, [0, 1], false); result.buffer_size"#, "1")],
},
// Source-reviewed neural operations; serialized networks are validated.
Signature {
name: "nn_create", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "network name"), req("layer_sizes", Ty::Array, "at least two positive Int sizes; at most one million weights and biases"), opt("hidden_activation", Ty::Str, "default relu"), opt("output_activation", Ty::Str, "default tanh")], returns: "Record",
doc: "Create a randomly initialized feedforward network. Activation names are case-insensitive: relu, sigmoid, tanh, softmax, linear, swish and leaky_relu. Unknown names, invalid sizes and excessive parameter counts are refused before allocation.",
examples: &[(r#"nn_create("example", [2, 3, 1]).param_count"#, "13"), (r#"nn_create("example", [2, 3, 1], "sigmoid").param_count"#, "13"), (r#"nn_create("example", [2, 3, 1], "relu", "linear").param_count"#, "13")],
},
Signature {
name: "nn_forward", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record),
params: &[req("input", Ty::Array, "finite numbers; length must equal network input size")], returns: "Array",
doc: "Evaluate a validated network and return finite Float outputs. Never pad short input or discard extra input. Encoded networks must have consistent nonempty layers, at most one million parameters, and at most 64 MiB of encoded data.",
examples: &[(r#"nn_forward(nn_create("example", [2, 1]), [0, 0]) | len"#, "1"), (r#"nn_create("example", [2, 1]) | nn_forward([0, 0]) | len"#, "1")],
},
Signature {
name: "nn_mutate", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record),
params: &[opt("rate", Ty::Numeric, "finite probability in 0..=1; default 0.1"), opt("strength", Ty::Numeric, "finite non-negative magnitude; default 0.3")], returns: "Record",
doc: "Return a mutated copy of a validated network. Refuse invalid numeric options or non-finite resulting parameters. Encoded networks are limited to one million parameters and 64 MiB of data.",
examples: &[(r#"nn_mutate(nn_create("example", [2, 1])).param_count"#, "3"), (r#"nn_mutate(nn_create("example", [2, 1]), 0).param_count"#, "3"), (r#"let result = nn_create("example", [2, 1]) | nn_mutate(0, 0) | nn_info; result.param_count"#, "3")],
},
Signature {
name: "nn_crossover", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("parent1", Ty::Record, "validated neural network"), req("parent2", Ty::Record, "same layer dimensions as parent1")], returns: "Record",
doc: "Combine parent weights and biases at random. Retain the first parent's name and activations. Refuse mismatched architectures. Each encoded network is limited to one million parameters and 64 MiB.",
examples: &[(r#"let a = nn_create("a", [2, 1]); nn_crossover(a, a).param_count"#, "3")],
},
Signature {
name: "nn_params", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record), params: &[], returns: "Array",
doc: "Flatten a validated network into Float weights and biases, layer by layer: row-major weights followed by biases. Encoded networks are limited to one million parameters and 64 MiB.",
examples: &[(r#"nn_params(nn_create("example", [2, 1])) | len"#, "3"), (r#"nn_create("example", [2, 1]) | nn_params | len"#, "3")],
},
Signature {
name: "nn_set_params", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record),
params: &[req("params", Ty::Array, "finite numbers; exactly the network parameter count")], returns: "Record",
doc: "Return a copy with all weights and biases replaced in nn_params order. Never accept partial or surplus parameters. Encoded networks are limited to one million parameters and 64 MiB.",
examples: &[(r#"nn_set_params(nn_create("example", [2, 1], "relu", "linear"), [2, 3, 4]) | nn_forward([1, 2]) | first"#, "12.0"), (r#"nn_create("example", [2, 1], "relu", "linear") | nn_set_params([2, 3, 4]) | nn_forward([1, 2]) | first"#, "12.0")],
},
Signature {
name: "nn_layers", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record), params: &[], returns: "Array",
doc: "Inspect a validated network as layer records: input_size, output_size, activation and param_count. Encoded networks are limited to one million parameters and 64 MiB.",
examples: &[(r#"nn_layers(nn_create("example", [2, 3, 1])) | len"#, "2"), (r#"nn_create("example", [2, 1]) | nn_layers | len"#, "1")],
},
Signature {
name: "nn_info", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record), params: &[], returns: "Record",
doc: "Inspect a validated network's name, layer_count, param_count, input_size and output_size. Use the encoded network rather than trusting outer metadata. Limit: one million parameters and 64 MiB of encoded data.",
examples: &[(r#"nn_info(nn_create("example", [2, 3, 1])).input_size"#, "2"), (r#"let result = nn_create("example", [2, 1]) | nn_info; result.output_size"#, "1")],
},
Signature {
name: "activation", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "relu, sigmoid, tanh, softmax, linear, swish or leaky_relu; case-insensitive")], returns: "Record",
doc: "Describe an activation as name and description fields. Leaky ReLU uses slope 0.01; this call takes no slope option.",
examples: &[(r#"activation("relu").name"#, "ReLU"), (r#"activation("LINEAR").name"#, "Linear")],
},
Signature {
name: "selection_strategy", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "tournament, roulette, rank, truncation or elite; case-insensitive"), opt("param", Ty::Any, "tournament: positive Int (default 3); elite: positive Int (default 5); truncation: finite probability (default 0.5); other strategies take no parameter")], returns: "Record",
doc: "Return a selection descriptor with type and debug-formatted name; does not run selection or configure a population. Refuse unused parameters and invalid ranges.",
examples: &[(r#"selection_strategy("tournament").name"#, "Tournament(3)"), (r#"selection_strategy("tournament", 4).name"#, "Tournament(4)"), (r#"selection_strategy("truncation", 0.25).name"#, "Truncation(0.25)"), (r#"selection_strategy("elite").name"#, "Elite(5)"), (r#"selection_strategy("rank").name"#, "Rank")],
},
Signature {
name: "crossover_strategy", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "single_point/singlepoint, two_point/twopoint, uniform, blend or sbx; case-insensitive"), opt("param", Ty::Numeric, "uniform: probability (default 0.5); blend: non-negative alpha (default 0.5); sbx: positive eta (default 20); finite; point crossover takes no parameter")], returns: "Record",
doc: "Return a crossover descriptor with type and debug-formatted name; does not run crossover or configure a population. Refuse unused parameters and invalid ranges.",
examples: &[(r#"crossover_strategy("uniform").name"#, "Uniform(0.5)"), (r#"crossover_strategy("uniform", 0.25).name"#, "Uniform(0.25)"), (r#"crossover_strategy("blend").name"#, "Blend(0.5)"), (r#"crossover_strategy("sbx").name"#, "SBX(20.0)"), (r#"crossover_strategy("singlepoint").name"#, "SinglePoint")],
},
Signature {
name: "evolution_stats", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record), params: &[], returns: "Record",
doc: "Return the nested stats record from a population record. Does not deserialize or run evolution; refuse missing or wrongly typed stats.",
examples: &[(r#"evolution_stats({stats: {generation: 3}}).generation"#, "3"), (r#"let result = {stats: {generation: 3}} | evolution_stats; result.generation"#, "3")],
},
// Source-reviewed line scanners; these do not perform AST analysis.
Signature {
name: "code_parse", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("file", Ty::Str, "UTF-8 source file path")], returns: "Record",
doc: "Read a file and return path, lines and size in bytes. Counts Rust string lines; does not parse syntax or produce an AST.",
examples: &[(r#"code_parse("tests/fixtures/signature-code.txt").lines"#, "8")],
},
Signature {
name: "code_symbols", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("file", Ty::Str, "UTF-8 source file path")], returns: "Array",
doc: "Scan declaration-like lines starting with fn, pub fn, struct, pub struct, enum, pub enum, impl, trait, def, class, function or const. Return records with one-based line and trimmed text. This is a prefix heuristic, not symbol resolution.",
examples: &[(r#"code_symbols("tests/fixtures/signature-code.txt") | len"#, "3")],
},
Signature {
name: "code_outline", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("file", Ty::Str, "UTF-8 source file path")], returns: "Array",
doc: "The same declaration-line scan as code_symbols; returns line and text records, not a syntax tree.",
examples: &[(r#"code_outline("tests/fixtures/signature-code.txt") | len"#, "3")],
},
Signature {
name: "code_imports", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("file", Ty::Str, "UTF-8 source file path")], returns: "Array",
doc: "Return trimmed lines beginning with use, import, from or #include. Text scan only; does not resolve modules.",
examples: &[(r#"code_imports("tests/fixtures/signature-code.txt") | first"#, "use std::fmt;")],
},
Signature {
name: "code_dependencies", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("file", Ty::Str, "UTF-8 source file path")], returns: "Array",
doc: "The same import-line scan as code_imports; returns source text, not resolved package dependencies.",
examples: &[(r#"code_dependencies("tests/fixtures/signature-code.txt") | first"#, "use std::fmt;")],
},
Signature {
name: "code_exports", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("file", Ty::Str, "UTF-8 source file path")], returns: "Array",
doc: "Return trimmed lines starting with pub or export. Text scan only; does not determine visibility through syntax analysis.",
examples: &[(r#"code_exports("tests/fixtures/signature-code.txt") | len"#, "3")],
},
Signature {
name: "code_comments", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("file", Ty::Str, "UTF-8 source file path")], returns: "Array",
doc: "Return one-based line and trimmed text records for lines starting with //, #, /* or *. Heuristic scan; excludes inline comments and may include non-comment lines.",
examples: &[(r#"code_comments("tests/fixtures/signature-code.txt") | len"#, "3")],
},
Signature {
name: "code_todos", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("file", Ty::Str, "UTF-8 source file path")], returns: "Array",
doc: "Return one-based line and trimmed text records for any line containing TODO or FIXME, case-insensitively. Includes matches outside comments.",
examples: &[(r#"code_todos("tests/fixtures/signature-code.txt") | len"#, "2")],
},
Signature {
name: "sleep", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("seconds", Ty::Numeric, "finite, non-negative representable duration in seconds")], returns: "Null",
doc: "Block the current thread for a numeric duration in seconds and return Null. Refuse NaN, infinity, negative and unrepresentable durations before sleeping. Under an evaluation deadline the sleep never outlasts it: it sleeps only the time left and then fails with E_BUDGET_EXCEEDED, and when the deadline has already expired it fails without sleeping.",
examples: &[("sleep(0)", "null"), ("sleep(0.001)", "null")],
},
// ---- System information -------------------------------------------
//
// Fourteen builtins that take no arguments at all -- their bodies bind
// `_args`, so the compiler proves it -- and which therefore accepted and
// discarded anything they were handed. `sys_os("a", 1, false)` answered
// "linux" as happily as `sys_os()`. That is the `round(4.966, 2) -> 5`
// defect, and `benches/agentic/discarded-args.mjs` measured it across
// 369 of 393 comparable builtins.
//
// Declaring a parameterless builtin carries none of the risk that sank
// `last(5)` and `"abc" | reverse`: there is no type to get too narrow,
// because there is no argument. The declaration says only "none", which
// the body already enforces by ignoring them.
//
// Each `returns` and `doc` is read off what the builtin actually
// returned, never off its name -- `sys_cpu_count` says 24 where
// `sys_cpu_info` reports 12 cores, so one counts hyperthreads and the
// other does not, and only running them says which is which.
//
// The examples are `typeof(x())` rather than a pinned value, because a
// hostname is not the same on two machines. That keeps every example
// executable by `tests/declared_signatures.rs` instead of joining the
// two-name `NEEDS_THE_WORLD` exemption, and it checks the `returns`
// field rather than merely decorating it.
Signature {
name: "sys_arch",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The CPU architecture this shell is running on.",
examples: &[("typeof(sys_arch())", "String")],
},
Signature {
name: "sys_boot_time",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "When the machine last booted, as UTC ISO 8601 to the second, for example 2026-10-30T12:34:56Z. The same form on every OS.",
examples: &[("typeof(sys_boot_time())", "String")],
},
Signature {
name: "sys_cpu_count",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Int",
doc: "The number of logical CPUs, hyperthreads included.",
examples: &[("typeof(sys_cpu_count())", "Int")],
},
Signature {
name: "sys_cpu_info",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "The CPU's model name, physical core count and clock speed in MHz.",
examples: &[("typeof(sys_cpu_info())", "Record")],
},
Signature {
name: "sys_disk_info",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Every mounted filesystem: device, mount point and free space.",
examples: &[("typeof(sys_disk_info())", "Array")],
},
Signature {
name: "sys_groups",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Every group on this system, with its gid and members.",
examples: &[("typeof(sys_groups())", "Array")],
},
Signature {
name: "sys_info",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "A summary of the host: os, arch, family and os_name (the distribution name). Every key is present on every OS; a value this host cannot read is null, and the names of the null fields are listed in missing.",
examples: &[("typeof(sys_info())", "Record")],
},
Signature {
name: "sys_kernel",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The running kernel's release string.",
examples: &[("typeof(sys_kernel())", "String")],
},
Signature {
name: "sys_load_avg",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "The 1, 5 and 15 minute load averages: from /proc/loadavg on Linux and sysctl vm.loadavg on macOS. Windows has no load average and is refused with E_UNIMPLEMENTED; use sys_cpu_info or proc_list there. Other systems are refused.",
examples: &[("sys_load_avg()", "{load_1: 0.5, load_5: 0.4, load_15: 0.3}")],
},
Signature {
name: "sys_locale",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The active locale.",
examples: &[("typeof(sys_locale())", "String")],
},
Signature {
name: "sys_os",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The operating system name.",
examples: &[("typeof(sys_os())", "String")],
},
Signature {
name: "sys_mem_info", category: None, subject_required: false, aliases: &[],
subject: None, params: &[], returns: "Record",
doc: "Read memory in process: total, free and available bytes as Int fields. Free means unallocated memory; available includes reusable memory where the OS reports it. Unsupported systems or unavailable measurements produce coded errors.",
examples: &[("sys_mem_info()", "{available: 4294967296, free: 2147483648, total: 8589934592}")],
},
Signature {
name: "sys_swap_info",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Read system swap in process: total, used and free bytes as Int fields. A system with no swap returns zero totals. Unsupported systems or unavailable memory queries produce coded errors.",
examples: &[("sys_swap_info()", "{free: 1073741824, total: 2147483648, used: 1073741824}")],
},
Signature {
name: "sys_timezone",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The system's time zone: the IANA name on Unix (`Europe/Berlin`), the Windows zone ID on Windows (`W. Europe Standard Time`). UTC when none is configured (no TZ and no /etc/localtime); a zone it cannot read or name is refused, never reported as UTC.",
examples: &[("typeof(sys_timezone())", "String")],
},
Signature {
name: "sys_user_info",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "The current user's name, home directory, login shell and domain.",
examples: &[("typeof(sys_user_info())", "Record")],
},
// ---- Project introspection ------------------------------------------
//
// The second tranche of parameterless declarations, on the same footing
// as the system group above: every body binds `_args`, so the compiler
// proves there is no argument to declare too narrowly.
//
// Every `returns` and `doc` was read off what the builtin produced when
// run against this repository, never off its name. `project_size`
// reports 24,297,412 -- bytes, not lines, which the name does not say
// and `describe_builtin_name` would have guessed wrong. `project_loc`
// is the line count, and it reported 0 for every project on every
// platform until this commit.
Signature {
name: "project_config_files",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "The build and package manifests found at the project root.",
examples: &[("typeof(project_config_files())", "Array")],
},
Signature {
name: "project_dependencies",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "The project's declared runtime dependencies.",
examples: &[("typeof(project_dependencies())", "Array")],
},
Signature {
name: "project_dev_dependencies",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "The project's declared development dependencies.",
examples: &[("typeof(project_dev_dependencies())", "Array")],
},
Signature {
name: "project_entry_points",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "The source files the build treats as entry points.",
examples: &[("typeof(project_entry_points())", "Array")],
},
Signature {
name: "project_gitignore",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The contents of the .gitignore file, verbatim (non-UTF-8 bytes replaced), or null if there is none.",
examples: &[("typeof(project_gitignore())", "String")],
},
Signature {
name: "project_languages",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Every programming language detected among the project files.",
examples: &[("typeof(project_languages())", "Array")],
},
Signature {
name: "project_license",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The contents of the LICENSE file, verbatim (non-UTF-8 bytes replaced), or null if there is none.",
examples: &[("typeof(project_license())", "String")],
},
Signature {
name: "project_loc",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Int",
doc: "Total source lines, skipping build output and vendored trees.",
examples: &[("typeof(project_loc())", "Int")],
},
Signature {
name: "project_name",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The project name from its manifest.",
examples: &[("typeof(project_name())", "String")],
},
Signature {
name: "project_readme",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The contents of the README, verbatim (non-UTF-8 bytes replaced), or null if there is none.",
examples: &[("typeof(project_readme())", "String")],
},
Signature {
name: "project_root",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The absolute path of the project root.",
examples: &[("typeof(project_root())", "String")],
},
Signature {
name: "project_size",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Int",
doc: "Total size of the project tree in bytes.",
examples: &[("typeof(project_size())", "Int")],
},
Signature {
name: "project_structure",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Every path in the project tree.",
examples: &[("typeof(project_structure())", "Array")],
},
Signature {
name: "project_test_files",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Every test file in the project.",
examples: &[("typeof(project_test_files())", "Array")],
},
Signature {
name: "project_type",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The build system in use, such as \"rust\", \"node\" or \"python\".",
examples: &[("typeof(project_type())", "String")],
},
Signature {
name: "project_version",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The project version from its manifest.",
examples: &[("typeof(project_version())", "String")],
},
// ---- Read-only status and inspection ---------------------------------
//
// Third tranche of parameterless declarations. Only read-only builtins
// are here: gathering the evidence means RUNNING each one, and
// `telemetry_enable`, `governor_reset`, `session_start`, `fs_mount`,
// `diag_fix` and `refactor_remove_unused` change the machine, so they
// are left for a setting where that is safe to do.
//
// `now` and `time` are declared identically because they measurably
// are the same thing: both return Unix seconds, one second apart on
// consecutive calls. The ontology should say so rather than imply two
// different clocks.
//
// `capabilities` stays undeclared: it is a Linux concept, and an
// executable example has to run on every platform CI has. The
// parameterless `search_*` builtins were held back for the same reason
// until they stopped shelling out to `grep`/`find` (which Windows may
// lack, or resolve to System32\find.exe); they walk in-process now and
// are declared below.
//
// `env_venv` returned "" when no virtualenv was active. That was first
// documented rather than changed; it now returns null, because null is
// what every other unset-variable lookup in the shell returns. It is a
// breaking change, and belongs in the release notes as one.
Signature {
name: "git_branches",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Every branch in the repository.",
examples: &[("typeof(git_branches())", "Array")],
},
Signature {
name: "git_remote",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The configured remotes, as `git remote -v` prints them.",
examples: &[("typeof(git_remote())", "String")],
},
Signature {
name: "git_root",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The absolute path of the repository root.",
examples: &[("typeof(git_root())", "String")],
},
Signature {
name: "git_stash_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Every stash entry, newest first.",
examples: &[("typeof(git_stash_list())", "Array")],
},
Signature {
name: "git_tags",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Every tag in the repository.",
examples: &[("typeof(git_tags())", "Array")],
},
Signature {
name: "glab_mr",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("subcommand", Ty::Str, "close, create, diff, list, note, reopen, update or view; default list"), opt_rest("flags", Ty::Str, "flags and values for glab mr, passed through; --editor, --web and --browser are refused")],
returns: "Record",
doc: "glab mr <subcommand>. Read subcommands return {subcmd, exit_code, success, stdout, stderr}; create, note, update, close and reopen change a remote and are approval-gated in agent mode. merge and approve are not offered. A nonzero exit is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { glab_mr("merge") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { glab_mr("list", "--web") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "glab_issue",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("subcommand", Ty::Str, "close, create, list, note, reopen, update or view; default list"), opt_rest("flags", Ty::Str, "flags and values for glab issue, passed through; --editor, --web and --browser are refused")],
returns: "Record",
doc: "glab issue <subcommand>. Read subcommands return {subcmd, exit_code, success, stdout, stderr}; create, note, update, close and reopen change a remote and are approval-gated in agent mode. delete is not offered. A nonzero exit is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { glab_issue("delete") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { glab_issue("list", "--browser") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "go_run",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("target", Ty::Str, "a package directory or import pattern; a directory must lie inside the workspace; defaults to .")],
returns: "Record",
doc: "Runs `go run <target>` with no shell. Compiles, then runs the package; the deadline is 15 minutes. Returns {exit_code: 0, success: true, stdout, stderr}; a nonzero exit is E_TOOL_FAILED with the tail of the output. A missing go is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | go_run() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { go_run("-exec=x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "go_build",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt_rest("packages", Ty::Str, "package directories or import patterns; each directory must lie inside the workspace; none builds the package in the working directory")],
returns: "Record",
doc: "Runs `go build <packages...>` with no shell. Build flags are refused, so no -toolexec, -exec or -o can reach the tool. The deadline is 15 minutes. Returns {exit_code: 0, success: true, stdout, stderr}; a nonzero exit is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | go_build() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { go_build("-toolexec=x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "go_test",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("target", Ty::Str, "a package directory or import pattern; a directory must lie inside the workspace; defaults to ./...")],
returns: "Record",
doc: "Runs `go test -v <target>` with no shell. The deadline is 15 minutes. Returns {exit_code: 0, success: true, stdout, stderr}; failing tests are E_TOOL_FAILED carrying the end of the test output. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | go_test() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { go_test("-exec=x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "env_container",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Bool",
doc: "Whether this shell is running inside a container.",
examples: &[("typeof(env_container())", "Bool")],
},
Signature {
name: "env_detect",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "The host OS, OS family and architecture.",
examples: &[("typeof(env_detect())", "Record")],
},
Signature {
name: "env_java",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The installed Java version string.",
examples: &[("typeof(env_java())", "String")],
},
Signature {
name: "env_node",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The installed Node.js version string.",
examples: &[("typeof(env_node())", "String")],
},
Signature {
name: "env_rust",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The installed Rust compiler version string.",
examples: &[("typeof(env_rust())", "String")],
},
Signature {
name: "env_shell",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The path of the user's login shell.",
examples: &[("typeof(env_shell())", "String")],
},
Signature {
name: "env_venv",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String | Null",
doc: "The active Python virtualenv path, or null when there is none.",
examples: &[(
r#"env_venv() == null || typeof(env_venv()) == "String""#,
"true",
)],
},
Signature {
name: "a2a_agents",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Every agent registered with a2a.register.",
examples: &[("typeof(a2a_agents())", "Array")],
},
Signature {
name: "a2a_discover",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Agents discovered on the local network.",
examples: &[("typeof(a2a_discover())", "Array")],
},
Signature {
name: "a2a_status",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Whether the agent channel is active, and its agent and pending-message counts.",
examples: &[("typeof(a2a_status())", "Record")],
},
Signature {
name: "telemetry_status",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Whether telemetry is enabled, how many events are held, and where they are stored.",
examples: &[("typeof(telemetry_status())", "Record")],
},
Signature {
name: "governor_status",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "The active resource limits and how much of each has been used.",
examples: &[("typeof(governor_status())", "Record")],
},
Signature {
name: "safety_status",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "The current mode, policy, workspace, governor state and audit log path.",
examples: &[("typeof(safety_status())", "Record")],
},
Signature {
name: "plan",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("ops", Ty::Array, "an Array of Records {op, path, content?, dest?}; op is write, append, rm, mkdir, copy or move")],
returns: "Record",
doc: "Describe a batch of filesystem operations without running any: {operations, summary (counts by op), token, hint, plan}. The token is derived from the exact ops, content and destinations included, so a changed op changes it. Nothing is written. In agent mode a human approves the token out of band (IRONSHELL_APPROVE), and an agent cannot approve it itself. Refused with E_BAD_ARG for a malformed op, an unknown op, or a write or append without content or a copy or move without dest.",
examples: &[
(r#"(try { plan() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { plan("write") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "plan_diff",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("ops", Ty::Array, "the same Array of ops that plan takes")],
returns: "Record",
doc: "Show what a plan would change, line by line: {operations, added, removed, diff: [{op, path, exists, added, removed, lines, elided?}], token}. Each file's lines are read as they are now, from any path (reads are not jailed), and at most 40 changed lines per op are shown with the rest counted in elided. Nothing is written. The token is the same one plan and apply use.",
examples: &[
(r#"(try { plan_diff() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { plan_diff("write") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "apply",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("ops", Ty::Array, "the Array of ops a plan described")],
returns: "Record",
doc: "Run a plan atomically: every op applies or none does, and a failure rolls the batch back. In agent mode the batch runs only when its plan token has been approved out of band (IRONSHELL_APPROVE or IRONSHELL_APPROVE_ALL); otherwise it answers {status: needs_approval, token}. An approval is spent by the apply it authorises, and an agent cannot approve its own token. Paths are confined to the workspace in agent mode or when IRONSHELL_WORKSPACE is set; a path outside it fails the batch. Returns {status: applied, applied} or {status: failed, error, rolled_back, restored}. When IRONSHELL_AUDIT_REQUIRED is set and the audit record of a batch that was applied cannot be written, the call is E_IO: the changes stay in place, the error says so, and the batch is not reported as applied.",
examples: &[
(r#"(try { apply() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { apply("write") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "approve",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("token", Ty::Str, "an approval token, such as one plan returned")],
returns: "Record",
doc: "Grant the approval for a token in this process. Human mode only: in agent mode it is refused with E_POLICY_DENY, because the token was issued to the caller being approved. The out-of-band channel an operator uses is the IRONSHELL_APPROVE environment variable, which an agent cannot set (set_env, env_set and env_unset refuse IRONSHELL_* names in agent mode).",
examples: &[
(
r#"approve("apv_0000000000000000")"#,
r#"{approved: true, token: "apv_0000000000000000"}"#,
),
(r#"(try { approve(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "record_summary",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "This session's opt-in evaluation records, summarised: attempts, failures, refusals, by_code, retries, recoveries and first_try_ok. Recording is off unless IRONSHELL_RECORD is 1 (hashes only) or full (with source text); off, every count is 0 and enabled is false. Records stay in record.jsonl in the session directory.",
examples: &[
("typeof(record_summary())", "Record"),
(r#"(try { record_summary(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "tx_status",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Whether a filesystem transaction is active, and its nesting depth.",
examples: &[("typeof(tx_status())", "Record")],
},
Signature {
name: "tx_begin",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Start a filesystem transaction, or nest a child one inside the active transaction. From then on, file writes and deletes record what they replaced so tx_rollback() or tx_rollback_to() can undo them. Returns transaction (the frame id), active and depth. The journal lives under .ironshell/tx in the workspace and is removed when the outermost transaction ends. The transaction is held by this process only. Refuses arguments and pipeline input.",
examples: &[
(r#"(try { tx_begin(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | tx_begin() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "tx_commit",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Commit the innermost transaction. An outermost commit makes its changes durable and discards the journal; a nested commit folds its record into the parent, so a later parent rollback still undoes it. Returns committed and operations (how many recorded operations the frame held). Without an active transaction it is E_BAD_STATE. Refuses arguments and pipeline input.",
examples: &[
(r#"(try { tx_commit(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | tx_commit() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "tx_rollback",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Roll back the innermost transaction, restoring every path it recorded to its state at the point it was begun, newest change first. An outermost rollback also discards the journal; a nested one leaves the parent open. Returns rolled_back and restored (how many paths were put back). A change that cannot be put back is E_IO naming each path; the transaction still ends, and an outermost rollback then keeps its journal for recovery. Without an active transaction it is E_BAD_STATE. Refuses arguments and pipeline input.",
examples: &[
(r#"(try { tx_rollback(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | tx_rollback() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "tx_savepoint",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("name", Ty::Str, "the savepoint's name; a later tx_rollback_to() with it reverts to this point")],
returns: "Record",
doc: "Mark a named savepoint inside the active transaction. Returns savepoint. Without an active transaction it is E_BAD_STATE. Refuses pipeline input.",
examples: &[
(r#"(try { tx_savepoint() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { tx_savepoint(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "tx_rollback_to",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("name", Ty::Str, "a savepoint named by tx_savepoint() in the active transaction")],
returns: "Record",
doc: "Undo the operations recorded after the named savepoint, newest first, leaving the transaction open and the savepoint in place. Returns rolled_back_to and restored; a change that cannot be put back is E_IO naming each path. An unknown savepoint is E_BAD_STATE, and so is having no active transaction. Refuses pipeline input.",
examples: &[
(r#"(try { tx_rollback_to() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { tx_rollback_to(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "session_checkpoint",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("name", Ty::Str, "label stored with the checkpoint; default \"checkpoint\"")],
returns: "Bool",
doc: "Save the uncommitted changes in the git stash list under name, leaving the working tree as it is. Returns true when saved and false when there were no changes to save. Outside a repository E_BAD_STATE. Refuses pipeline input.",
examples: &[
(r#"(try { session_checkpoint(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { session_checkpoint("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | session_checkpoint() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "session_restore",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt_range("index", Ty::Int, 0, 10000, "checkpoint position in session_checkpoints(), 0 the newest; default 0")],
returns: "Bool",
doc: "Re-apply the checkpoint at position index (see session_checkpoints()) to the working tree, keeping it in the stash list. Returns true on success. A conflict or a missing checkpoint is E_TOOL_FAILED with git's output. Refuses pipeline input.",
examples: &[
(r#"(try { session_restore(-1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { session_restore("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | session_restore() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "session_checkpoints",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "The checkpoints in the git stash list, newest first, one String line each. Read-only. Refuses arguments and pipeline input.",
examples: &[
(r#"(try { session_checkpoints(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | session_checkpoints() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "session_diff_since",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("commit", Ty::Str, "the commit or ref to diff the working tree against; default HEAD~1")],
returns: "String",
doc: "The diff of the working tree against commit (default HEAD~1), as text. Read-only. Refuses pipeline input.",
examples: &[
(r#"(try { session_diff_since(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { session_diff_since("--output=x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | session_diff_since() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "session_changes",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "The uncommitted changes in the repository, as git status --porcelain lines, the first being the branch line. Read-only. Refuses arguments and pipeline input.",
examples: &[
(r#"(try { session_changes(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | session_changes() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "session_rollback",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("commit", Ty::Str, "the commit to reset the working tree to; default HEAD")],
returns: "Bool",
doc: "Discard every uncommitted change and reset the repository to commit (default HEAD), with git reset --hard. Destructive: the changes are gone. Returns true on success; a failure is E_TOOL_FAILED with git's output. Refuses pipeline input.",
examples: &[
(r#"(try { session_rollback(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { session_rollback("--hard") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | session_rollback() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "session_export",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("file", Ty::Str, "where to write the patch; default session.patch")],
returns: "String",
doc: "Write the working tree's diff (git diff) to file and return the path written. An existing file is replaced atomically, as file_write replaces it, and a transaction rollback restores it. Refuses pipeline input.",
examples: &[
(r#"(try { session_export(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | session_export() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "config",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "The effective configuration, after files and environment are merged.",
examples: &[("typeof(config())", "Record")],
},
Signature {
name: "now",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Int",
doc: "The current Unix time in seconds. For an ISO 8601 string of the time, use now_iso().",
examples: &[("typeof(now())", "Int")],
},
Signature {
name: "npm_run",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("script", Ty::Str, "a script name from package.json; a leading '-' is refused")],
returns: "Record",
doc: "Runs `npm run <script>` with no shell. Returns {script, exit_code: 0, success: true, stdout, stderr}; a nonzero exit is E_TOOL_FAILED with the tail of the output. Deadline 10 minutes; a missing npm is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | npm_run("build") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { npm_run("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "npm_install",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt_rest("packages", Ty::Str, "package specs; with none, installs the project's dependencies; a leading '-' is refused, so no flag such as -g can reach npm")],
returns: "Record",
doc: "Runs `npm install <packages...>` with no shell, in the working directory. The deadline is 15 minutes. Package install scripts run as part of the install. Returns {exit_code: 0, success: true, stdout, stderr}; a nonzero exit is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | npm_install("left-pad") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { npm_install("-g") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "time",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Int",
doc: "The current Unix time in seconds. For an ISO 8601 string of the time, use now_iso().",
examples: &[("typeof(time())", "Int")],
},
Signature {
name: "audit_stats",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Counts for the active chained audit log: total and by_decision (a Record of decision name to count, such as allow or deny) count the entries audit_verify checks. info, warning and critical count the audit_log assertions made in this process by severity. With no active log, total counts those assertions.",
examples: &[("typeof(audit_stats())", "Record")],
},
Signature {
name: "diag_suppress", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("report", Ty::Str, "Supplied rustc/Cargo JSON-lines diagnostic report"), req("codes", Ty::Array, "Nonempty array of unique exact warning codes")], returns: "String",
doc: "Filter supplied rustc JSON diagnostic objects ($message_type diagnostic) or Cargo JSON events (reason compiler-message with message diagnostic). Remove only top-level warning diagnostics whose code object's code exactly matches a selector; retain errors, notes, null-code summaries and other Cargo events byte-for-byte including CRLF/missing final newline. Nested child diagnostics stay with their parent. Each diagnostic requires String level/message and null/object code; unknown levels, malformed JSON/objects and duplicate keys at any depth reject the entire report. Other Cargo reason Strings pass through. No Cargo execution, files/configuration changes or implicit report cache. This filters display data, not compiler policy. Selectors are ASCII identifier segments separated by double colon; each begins letter/underscore, with letters/digits/underscore thereafter. Limits: 1 MiB report, 25000 nonblank JSON lines, 64 KiB per line, 128 unique nonempty codes of at most 128 bytes; serde JSON recursion bound applies. Empty report allowed. Pure/direct-only; invalid types/selectors or pipeline input reject with coded errors.",
examples: &[(r#"diag_suppress("{\"$message_type\":\"diagnostic\",\"level\":\"warning\",\"message\":\"unused x\",\"code\":{\"code\":\"unused_variables\"}}\n", ["unused_variables"]) | len"#, "0")],
},
Signature {
name: "refactor_rename", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "One whole Rust source file, parsed by syn"), req("old", Ty::Str, "Existing identifier to rename, optionally raw"), req("new", Ty::Str, "Fresh identifier to rename it to, optionally raw")], returns: "String",
doc: "Rename every identifier token in a whole Rust source file whose normalized text equals old (raw prefixes ignored) to new, returning token-formatted Rust source. Items, fields, methods, locals, paths and visibility restrictions are renamed alike; lifetimes, string literals and comments are not identifiers and are unchanged. Refuse when new already occurs as an identifier anywhere (capture risk), when old does not occur, when old equals new, or when either is self, Self, super, crate or _. Refuse when old occurs in any macro invocation's tokens (new too, to keep format-string captures safe), in any non-doc attribute, or in verbatim syntax; doc comments are left alone. LIMITS: the rename is whole-file and purely syntactic. It does not resolve symbols, so different items that share the name are all renamed consistently and only within this file. It does not update other files, external crates, trait methods implemented for std or dependency traits (renaming fmt in an impl of Display breaks it), string contents, or consumers of pub API; callers must compile and review the result. Source <=256 KiB/4096 raw ASCII punctuation; each name <=256 bytes/32 punctuation; output <=2 MiB. Pure, direct-only; pipeline input and malformed arguments reject with coded errors.",
examples: &[(r#"typeof(refactor_rename("fn a()->i32 { 1 } fn b()->i32 { a() }", "a", "first"))"#, "String")],
},
Signature {
name: "refactor_extract_variable", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "Exactly one Rust free function with top-level tail expression"), req("name", Ty::Str, "Fresh Rust binding identifier, optionally raw")], returns: "String",
doc: "Extract the top-level final expression without semicolon into let NAME = EXPR; NAME, preserving preceding statements and function tokens. Return token-formatted Rust source; ordinary comments/layout are discarded and doc comments become attributes. The new identifier must not occur anywhere in the parsed function, conservatively including field names/shadowing; raw identifiers normalize. Reject receivers, variadics, macros, nonliteral-doc attributes, nested items and verbatim syntax. No symbol/type/borrow resolution, selection of arbitrary subexpressions, cfg/macro expansion, files, execution or call-site edits. Binding introduces a new local and can change temporary lifetimes or borrowing; callers compile and review semantics. Source <=64 KiB/256 raw ASCII punctuation; name <=256 bytes/32 punctuation; output <=1 MiB. Pure/direct-only; invalid shapes/syntax and pipeline input reject with coded errors.",
examples: &[(r#"typeof(refactor_extract_variable("fn sum(a:i32,b:i32)->i32 { a+b }", "result"))"#, "String")],
},
Signature {
name: "refactor_extract_constant", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "Exactly one Rust free function with top-level tail expression"), req("name", Ty::Str, "Fresh Rust constant identifier, optionally raw"), req("type", Ty::Str, "Explicit Rust type for local constant")], returns: "String",
doc: "Extract the top-level final expression without semicolon into const NAME: TYPE = EXPR; NAME, returning token-formatted Rust source and preserving preceding statements/function tokens. This is a syntax transformation: caller compiler checks must establish const-evaluability and type correctness; locals/generic parameters/runtime expressions may be invalid in a const initializer. No inference, constant evaluation, symbol resolution, arbitrary selection, files or execution. Identifier collisions, raw normalization, opaque syntax refusals, formatting changes and source/name/output bounds are the same as refactor_extract_variable. Explicit type <=16 KiB/128 raw ASCII punctuation; type syntax is also scanned conservatively. Pure/direct-only; wrong argument types/shapes/syntax and pipeline input reject.",
examples: &[(r#"typeof(refactor_extract_constant("fn answer()->i32 { 6*7 }", "ANSWER", "i32"))"#, "String")],
},
Signature {
name: "refactor_extract_function", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "Exactly one Rust free function with body"), req("name", Ty::Str, "Fresh Rust identifier for the new private function, optionally raw"), req("start", Ty::Int, "Zero-based inclusive index of the first top-level statement to extract"), req("end", Ty::Int, "Zero-based exclusive index one past the last top-level statement to extract")], returns: "String",
doc: "Move the top-level statements [start, end) of one Rust function into a new private function NAME, returning token-formatted source: the original function, then the new function. The range becomes one call statement NAME(args); or, when end is the function length and the last statement is a tail expression without semicolon, the tail call NAME(args) with the original return type. Captured variables are the outer names the range uses, passed by value in first-use order with their declared types: plain by-value parameters, or top-level lets before start that carry a type annotation. Refused: receivers, variadics, generics or where clauses, const/async/unsafe/extern, macros, nested items, non-doc attributes and verbatim syntax anywhere; NAME occurring anywhere in the function; any identifier bound more than once (no shadowing support); a captured name without a plain typed declaration; return, ?, .await, break or continue outside a loop inside the range; assignments or compound assignments whose target mentions a captured variable; &mut of a captured variable; method calls whose receiver mentions a captured variable; and a name bound inside the range that is used after end. Conservative limits: no type inference, borrow analysis or symbol resolution. By-value captures move non-Copy values, so a later use of one fails to compile, while a captured value the range only borrowed and that is not used later is now dropped when the new function returns, possibly earlier than before (e.g. a lock guard), without a compile error; values created in the range drop at the end of the new function rather than the original block. Caller compiler checks establish all of this, lifetime elision in a copied return type included. Source <=64 KiB/256 raw ASCII punctuation; name <=256 bytes/32 punctuation; output <=1 MiB. Start and end must be Int with 0 <= start < end <= statement count. Pure, direct-only; no files or execution; pipeline input and malformed arguments reject with coded errors.",
examples: &[(r#"typeof(refactor_extract_function("fn f(a:i32)->i32 { let b: i32 = a+1; b*2 }", "double", 1, 2))"#, "String")],
},
Signature {
name: "refactor_inline", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "Exactly one Rust free function with body"), req("name", Ty::Str, "Identifier of a top-level immutable let binding, optionally raw")], returns: "String",
doc: "Inline one top-level let NAME = EXPR; (plain identifier pattern; no mut/ref/subpattern/type/attributes/else) into its single use and remove the binding, returning token-formatted Rust source with EXPR parenthesized. The identifier must occur exactly twice in the parsed function, conservatively counting field names, struct shorthand and shadowing. The use must be in the immediately following top-level statement (let initializer, expression statement or tail), evaluated first, once, unconditionally and consumed by value: reached only through operands of arithmetic/bitwise operators, call/method arguments, tuple/array/struct elements, index expressions, casts, unary -/!, ?, return/break values, if conditions and the left side of &&/||. Method receivers, borrows, comparisons, derefs, field/index bases, match/if-let scrutinees, closures, loops, blocks and conditional branches reject, so evaluation order and drop timing are preserved. Literals and place reads may precede the use only when EXPR has no calls, assignments, blocks, mutable borrows or derefs; operator trait impls are assumed not to mutate unrelated locals. Ordinary comments/layout are discarded and doc comments become attributes. No symbol/type/borrow resolution, macro/cfg expansion, files or execution; callers compile and review. Macros, nonliteral-doc attributes, nested items and verbatim syntax reject. Source <=64 KiB/256 raw ASCII punctuation; name <=256 bytes/32 punctuation; output <=1 MiB. Pure/direct-only; invalid shapes/syntax and pipeline input reject with coded errors.",
examples: &[(r#"typeof(refactor_inline("fn area(w:i32,h:i32)->i32 { let a = w*h; a+1 }", "a"))"#, "String")],
},
Signature {
name: "refactor_move_to_file", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "Rust source text containing exactly one top-level item named ITEM"), req("item", Ty::Str, "Identifier of a top-level fn, struct, enum, union, const, static, type alias, trait or inline mod, optionally raw"), req("destination", Ty::Str, "Rust source text to append the item to; may be empty")], returns: "Record",
doc: "Move one top-level Rust item from SOURCE into the end of DESTINATION, returning a Record {source: String, destination: String} of token-formatted Rust source. Both texts are reformatted entirely: ordinary comments are discarded and doc comments become doc attributes. The item keeps its visibility and attributes; the only attributes accepted are doc, derive, allow, warn, deny, inline, must_use, cfg and repr, and macro_rules definitions anywhere inside the item, macro_export, no_mangle and other attributes are refused. Refused: a SOURCE that does not define the name exactly once at top level; an impl block in SOURCE whose self type is that single-segment name (moving the type would orphan its impls); an out-of-line mod; a DESTINATION that already defines the name or imports it by use (last segment or rename); a shebang. Nothing is added or changed beyond the move: no use statements, no pub, no path rewriting. References in SOURCE to the moved item stop resolving until the caller adds a use or visibility change, and the sources are not compiled, so callers must compile the results. Name matching is exact after raw-identifier normalization; macro-generated items are not seen. Source/destination <=256 KiB and <=4096 raw ASCII punctuation each; item name <=256 bytes/32 punctuation; each output <=2 MiB. Pure and direct-only: no files are read or written. Pipeline input, wrong argument count or types, and unparseable sources or names reject with coded errors.",
examples: &[(r#"typeof(refactor_move_to_file("fn a()->i32 { 1 } fn b()->i32 { 2 }", "b", ""))"#, "Record")],
},
Signature {
name: "refactor_change_signature", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "Exactly one Rust free-function definition with a body"), req("signature", Ty::Str, "Replacement Rust fn signature without visibility or body")], returns: "String",
doc: "Replace one supplied Rust function's signature while retaining its name, visibility, attributes and body tokens. Return token-formatted Rust source, not a filename; non-doc comments/formatting are discarded and doc comments become doc attributes. Reject token-identical replacement signatures, receivers, variadics, destructuring/ref/subpatterns and duplicate parameter bindings (raw identifiers normalize). At most 64 parameters. Dropping bindings requires a conservative scope-insensitive body identifier scan: identifier mentions (including fields/shadowing), macros, nonliteral-doc attributes, nested items and verbatim syntax reject; implicit format captures are therefore not missed. No symbol/type resolution, macro/cfg evaluation or call-site rewriting. Changed types/qualifiers/generics can require caller body/call-site edits and compiler checks. Source <=64 KiB/256 raw ASCII punctuation characters; replacement <=16 KiB/128 punctuation, including comments/strings; output <=1 MiB. Pure, direct-only; no files or execution. Reject pipeline input and malformed shapes/syntax with coded errors.",
examples: &[(r#"typeof(refactor_change_signature("pub fn sub(a:i32,b:i32)->i32 {a-b}", "fn sub(b:i32,a:i32)->i32"))"#, "String")],
},
Signature {
name: "refactor_add_parameter", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "Exactly one Rust free-function definition with a body"), req("parameter", Ty::Str, "One typed plain identifier parameter, such as _extra: i32"), opt_range("position", Ty::Int, 0, 64, "Zero-based insertion index through current parameter count; default append")], returns: "String",
doc: "Insert a supplied typed Rust parameter into one function, returning token-formatted source. Preserve function/body tokens except the parameter list; visibility, qualifiers, generics and attributes remain. Parameter names must be unique after raw-identifier normalization, with at most 64 parameters; plain identifiers with optional mut are supported, receivers/destructuring/ref/subpatterns/variadics are not. Explicit position must be at most the current parameter count. No defaults, argument generation, call-site edits, type checking or files/execution; callers apply the source and check its semantics. Source <=64 KiB/256 raw ASCII punctuation; parameter <=16 KiB/128 punctuation, including comments/strings; output <=1 MiB. Non-doc comments/formatting are discarded, docs become attributes. Pure, direct-only; pipeline input rejects.",
examples: &[(r#"typeof(refactor_add_parameter("fn f(a:i32)->i32 {a}", "_extra:i32"))"#, "String"), (r#"typeof(refactor_add_parameter("fn f(a:i32)->i32 {a}", "_extra:i32", 0))"#, "String")],
},
Signature {
name: "refactor_remove_parameter", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "Exactly one Rust free-function definition with a body"), req("parameter", Ty::Str, "Existing Rust parameter identifier, optionally raw")], returns: "String",
doc: "Remove an existing parameter from one supplied Rust function, retaining other declarations and body tokens and returning token-formatted source. Missing bindings reject. Require plain identifier patterns and no receivers/variadics; at most 64 parameters. The conservative scope-insensitive removal check rejects matching body identifiers (including fields/local shadowing), macros, attributes except literal docs, nested items and verbatim syntax. It does not infer references or rewrite calls, resolve imports/types, expand macros/cfg, run code or open files. Caller compiler/call-site checks remain necessary. Source <=64 KiB/256 raw ASCII punctuation; identifier <=256 bytes/32 punctuation, including comments/strings; output <=1 MiB. Non-doc comments/formatting are discarded and docs become attributes. Pure, direct-only; pipeline input rejects.",
examples: &[(r#"typeof(refactor_remove_parameter("fn f(a:i32,_extra:i32)->i32 {a}", "_extra"))"#, "String")],
},
Signature {
name: "test_bench", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("dir", Ty::Str, "project directory inside the workspace; must hold Cargo.toml")],
returns: "String",
doc: "Run cargo bench in the project directory dir and return its output, the last 256 KiB kept. dir is required: there is no default directory. dir must be an existing directory inside the workspace that holds Cargo.toml, and is refused with E_OUTSIDE_WORKSPACE or E_NOT_FOUND before any process starts. The run has a 900 s deadline and is killed past it (E_BUDGET_EXCEEDED). A failing benchmark run is E_TOOL_FAILED, carrying the stderr tail and the end of stdout. Only the cargo process is killed at the deadline, not rustc or benchmark children it started. Takes no pipeline input.",
examples: &[
(r#"(try { test_bench() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { test_bench("") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "test_list", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("dir", Ty::Str, "project directory inside the workspace; must hold Cargo.toml")],
returns: "Array",
doc: "List the test names of the project in directory dir, from cargo test -- --list, as an Array of String. dir is required and checked as for test_bench. The listing is read whole: output over 4 MiB is E_BUDGET_EXCEEDED rather than a partial list. Only the names of tests are kept; the counts and benchmark lines cargo prints are not. A failing build is E_TOOL_FAILED. The run has a 900 s deadline. Takes no pipeline input.",
examples: &[
(r#"(try { test_list() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { test_list("") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "test_run", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("dir", Ty::Str, "project directory inside the workspace; must hold Cargo.toml")],
returns: "String",
doc: "Run cargo test in the project directory dir and return its output, the last 256 KiB kept. This executes the project's test code, its build scripts and its procedural macros, so it is classified Exec and gated. dir is required and checked as for test_bench. A test failure is E_TOOL_FAILED, carrying the stderr tail and the end of stdout where the failing test output is printed. The run has a 900 s deadline and only the cargo process is killed at it. Takes no pipeline input.",
examples: &[
(r#"(try { test_run() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { test_run("") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "test_run_file", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("dir", Ty::Str, "project directory inside the workspace; must hold Cargo.toml"), req("file", Ty::Str, "name of an integration test target, without .rs; letters, digits, '_' or '-'")],
returns: "String",
doc: "Run cargo test --test <file> in the project directory dir and return its output, the last 256 KiB kept. file names an integration test target and is not a path: a path, a leading '-', or anything outside letters, digits, '_' and '-' is E_BAD_ARG before any process starts. dir is checked as for test_bench. A test failure is E_TOOL_FAILED, carrying the stderr tail and the end of stdout. The run has a 900 s deadline. Takes no pipeline input.",
examples: &[
(r#"(try { test_run_file("", "x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { test_run_file("", "-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "test_run_function", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("dir", Ty::Str, "project directory inside the workspace; must hold Cargo.toml"), req("name", Ty::Str, "test name or path filter, e.g. parser::tests::empty; letters, digits, '_' and ':'")],
returns: "String",
doc: "Run the tests of the project in directory dir whose names match the filter name, through cargo test <name>, and return the output, the last 256 KiB kept. The filter is a substring match on test names, as cargo's own is. A name with characters outside letters, digits, '_' and ':', or one starting with '-', is E_BAD_ARG before any process starts. dir is checked as for test_bench. A test failure is E_TOOL_FAILED, carrying the stderr tail and the end of stdout. The run has a 900 s deadline. Takes no pipeline input.",
examples: &[
(r#"(try { test_run_function("", "x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { test_run_function("", "-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "test_watch", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("command", Ty::Array, "Nonempty argv Array of String: program then arguments, run directly without a shell"), req("paths", Ty::Array, "Nonempty Array of String paths, each of which must exist; directories are scanned recursively"), opt("options", Ty::Record, "Optional Record whose Int fields are max_runs, poll_ms, idle_ms, timeout_ms and total_ms; unknown keys reject")], returns: "Record",
doc: "Run the program named by command once in the current directory, then run it again whenever the watched paths change, and return Record {runs, stopped, passed}. The command is an argv array run directly with no shell, stdin null and stdout and stderr captured, and it is executed on every run, so the builtin is classified Exec and is gated like other process-running builtins. Each run is {trigger: initial or change, changed: sorted Array<String> of the paths added, removed or modified since the previous snapshot (at most 32 listed), changed_count: Int, exit_code: Int, or Null when the run timed out or the process ended by signal, timed_out: Bool, duration_ms: Int, stdout: String, stderr: String}; stdout and stderr each keep only the last 65536 bytes, decoded lossily as UTF-8. A nonzero exit is reported in the run, not raised as an error. Change detection polls rather than using OS notifications: every poll_ms the paths are rescanned, directories recursively, skipping entries named target, .git and node_modules, following no symlinks, and each file is compared by relative path, length and modified time, so a change that keeps both length and modified time can be missed. stopped is max_runs when the run count is reached, idle when no change has been seen for idle_ms after the last run finished, or deadline when total_ms elapses; a run still going at the deadline is killed. passed is true only when the last run exited 0 and did not time out. Options: max_runs 1..=20 (default 2), poll_ms 50..=5000 (default 200), idle_ms 100..=600000 (default 30000), timeout_ms 100..=1800000 per run (default 300000), total_ms 100..=3600000 overall (default 900000). A run that exceeds timeout_ms, or is still going at the deadline, has its whole process tree killed (on Unix the process group the run was started in; on Windows taskkill /T) and is then reaped, so no child or grandchild is left running. Output is read on separate threads; after the child exits, at most 2 seconds are waited for those readers to reach end of output, so output held open by a process that survives returns only what arrived by then. Limits: command at most 64 elements of 4096 bytes each, no NUL; paths at most 64 entries; at most 10000 files scanned across all paths. Refused with E_BAD_ARG: pipeline input, a malformed or empty command or paths, a nonexistent path, unknown or out-of-range options; a program that cannot be started is an error (E_TOOL_MISSING). Direct-only.",
examples: &[(r#"test_watch(["rustc", "--version"], ["Cargo.toml"], {max_runs: 1}).passed"#, "true"), (r#"test_watch(["rustc", "--version"], ["Cargo.toml"]).passed"#, "true")],
},
Signature {
name: "pkg_install", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("names", Ty::Array, "a nonempty Array of at most 64 Strings: on Debian-family Linux, apt package names, each optionally name=version; on Windows, winget identifiers such as Publisher.Package, without versions"), opt("options", Ty::Record, "optional Record; on Linux its only key is no_recommends, a Bool that defaults to true; Windows takes no options")],
returns: "Record",
doc: "Install packages. On Debian-family Linux it runs apt-get install, non-interactively and keeping the existing configuration file on conflict, with --no-install-recommends unless no_recommends is false, then reads each installed version back with dpkg-query, and returns Record {installed: Array of Record {name, version}}; a name=version entry installs that exact version. Requires root. On Windows it runs `winget install --id <id> --exact --source winget` for each identifier, with the agreements accepted and no prompts, and returns Record {installed: Array of Record {name}}; winget's installed version is not read back. Each Windows identifier is first checked with `winget show --id <id> --exact`, so an identifier winget cannot find is E_NOT_FOUND before anything is installed. An install winget reports as already current (exit 0x8A15002B) counts as installed. A failure after the first install is E_TOOL_FAILED and does not say which earlier identifiers were installed. Refused with E_BAD_ARG, before any effect: a bad list (empty, over 64, or named twice, case-insensitively on Windows); on Linux a name not matching ^[a-z0-9][a-z0-9+.-]{1,127}$ or beginning with '-', or a version not matching ^[A-Za-z0-9.+~:-]{1,64}$; on Windows an identifier that is not letters, digits, '.', '-', '_' or '+', longer than 128 characters, or beginning with '-'; an unknown or non-Bool option; or pipeline input. Refused with E_UNIMPLEMENTED, NOTHING WAS CHANGED, on other platforms and package managers, and inside a transaction. A held apt or dpkg lock is E_BAD_STATE. A nonzero exit is E_TOOL_FAILED: apt's with the last 64 KiB of stderr, winget's with its exit code in hex. A run over 1800 s is killed and reported as E_BUDGET_EXCEEDED, with its effect UNKNOWN. Not done: repository key import, pinning, held-package handling, sources changes, winget sources other than winget, or winget versions.",
examples: &[
(r#"(try { pkg_install([]) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { pkg_install(["-y"], {no_recommends: false}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "pkg_remove", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("names", Ty::Array, "a nonempty Array of at most 64 installed package names, bare (no version): on Debian-family Linux apt names; on Windows winget identifiers"), opt("options", Ty::Record, "optional Record; on Linux its only key is purge, a Bool that defaults to false; Windows takes no options")],
returns: "Record",
doc: "Remove packages. On Debian-family Linux it runs apt-get remove, or apt-get purge when purge is true, and requires root. Before anything is removed, each name is checked with dpkg-query: it must be installed (E_NOT_FOUND otherwise), and it must not be Essential: yes or Priority: required (E_POLICY_DENY otherwise, NOTHING WAS REMOVED). On Windows it runs `winget uninstall --id <id> --exact` for each identifier, non-interactively. Before anything is removed, each identifier must be listed by `winget list --id <id> --exact` (E_NOT_FOUND otherwise). A later uninstall that winget cannot find is E_NOT_FOUND, and a failure after the first removal is E_TOOL_FAILED without saying which names were already removed. Returns Record {removed: Array of String} listing the names requested; packages apt removes as side effects are not listed. Refused with E_BAD_ARG: a bad list; on Linux a name not matching ^[a-z0-9][a-z0-9+.-]{1,127}$ or beginning with '-', or a name with =version; on Windows an identifier that is not letters, digits, '.', '-', '_' or '+', longer than 128 characters, or beginning with '-'; an unknown or non-Bool option; or pipeline input. Refused with E_UNIMPLEMENTED, NOTHING WAS CHANGED, on other platforms and package managers, and inside a transaction. A held apt or dpkg lock is E_BAD_STATE; a nonzero exit is E_TOOL_FAILED (apt's with the last 64 KiB of stderr, winget's with its exit code in hex); a run over 1800 s is killed and reported as E_BUDGET_EXCEEDED with its effect UNKNOWN.",
examples: &[
(r#"(try { pkg_remove([]) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { pkg_remove(["-y"], {purge: true}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "pkg_update", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "Record",
doc: "Refresh the package index. On Debian-family Linux it runs apt-get update --error-on=any, so a source that cannot be fetched is E_TOOL_FAILED rather than a silent success (plain apt-get update exits 0 then); it requires root. On Windows it runs `winget source update`. Returns Record {updated: true}. Accepts no arguments or pipeline input (E_BAD_ARG). Refused with E_UNIMPLEMENTED, NOTHING WAS CHANGED, on other platforms and package managers, and inside a transaction. A held apt or dpkg lock is E_BAD_STATE; a nonzero exit is E_TOOL_FAILED; a run over 1800 s is killed and reported as E_BUDGET_EXCEEDED.",
examples: &[(r#"(try { pkg_update("x") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "pkg_upgrade", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt("options", Ty::Record, "optional Record; on Linux its only key is dist, a Bool that defaults to false; on Windows its only key is id, a String winget identifier that upgrades just that package")],
returns: "Record",
doc: "Upgrade installed packages. On Debian-family Linux it runs apt-get upgrade, or apt-get dist-upgrade when dist is true, and requires root. It returns Record {upgraded: Int}, the N from apt's summary line `N upgraded, ...`, read from the output rather than from a before and after comparison; if the summary line is missing the call is E_TOOL_FAILED rather than reporting zero. On Windows it runs `winget upgrade --id <id> --exact` when id is given, and `winget upgrade --all` when it is not. It returns Record {changed: Bool}: false when winget reports nothing to upgrade (exit 0x8A15002B), true when it exits 0. The --all form reports only that winget exited 0, because winget does not say how many packages it changed here. An id winget cannot find is E_NOT_FOUND. Refused with E_BAD_ARG: an unknown or non-Bool option on Linux, an unknown option or an id that is not a winget identifier on Windows, a non-Record argument, or pipeline input. Refused with E_UNIMPLEMENTED, NOTHING WAS CHANGED, on other platforms and package managers, and inside a transaction. A held apt or dpkg lock is E_BAD_STATE; a nonzero exit is E_TOOL_FAILED; a run over 1800 s is killed and reported as E_BUDGET_EXCEEDED with its effect UNKNOWN.",
examples: &[
(r#"(try { pkg_upgrade("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { pkg_upgrade({dist: 1}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "pkg_clean", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "Record",
doc: "Delete downloaded package files from apt's cache with apt-get clean on Debian-family Linux; winget has no equivalent, so Windows, other platforms and package managers are E_UNIMPLEMENTED with NOTHING WAS CHANGED. Requires root. Returns Record {cleaned: true}. Accepts no arguments or pipeline input (E_BAD_ARG). Refused with E_UNIMPLEMENTED inside a transaction. A held lock is E_BAD_STATE; a nonzero apt exit is E_TOOL_FAILED with the last 64 KiB of stderr.",
examples: &[(r#"(try { pkg_clean("x") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "pkg_autoremove", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "Record",
doc: "Remove packages that were installed as dependencies and are no longer needed, with apt-get autoremove -y, on Debian-family Linux only; winget has no equivalent, so Windows, other platforms and package managers are E_UNIMPLEMENTED with NOTHING WAS CHANGED. Requires root. The removal set is whatever apt computes; nothing is filtered here. Returns Record {removed: Array of String}, parsed from the `Removing <name> ...` lines of apt's output, with any :arch suffix dropped. Accepts no arguments or pipeline input (E_BAD_ARG). Refused with E_UNIMPLEMENTED inside a transaction. A held lock is E_BAD_STATE; a nonzero apt exit is E_TOOL_FAILED with the last 64 KiB of stderr; a run over 1800 s is killed and reported as E_BUDGET_EXCEEDED with its effect UNKNOWN.",
examples: &[(r#"(try { pkg_autoremove("x") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "pkg_add_source", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "a source name matching ^[a-z0-9][a-z0-9_-]{0,63}$; the file is ironshell-<name>.list"), req("line", Ty::Str, "one deb or deb-src line whose URI is https://, e.g. `deb https://deb.debian.org/debian trixie main`"), opt("options", Ty::Record, "optional Record; its only key is update, a Bool that defaults to false")],
returns: "Record",
doc: "Add an apt source on Debian-family Linux only: writes /etc/apt/sources.list.d/ironshell-<name>.list containing a first line `# Created by IronShell pkg_add_source` and then the line, mode 0644, written under a hidden temporary name and hard-linked into place so an existing file is never replaced. Other platforms and package managers are E_UNIMPLEMENTED with NOTHING WAS CHANGED. Requires root. The line must match ^deb(-src)? (\\[[a-z0-9=_ /.:-]+\\] )?https://[^\\s]+ [a-z0-9._/-]+( [a-z0-9._-]+)+$; plain http and file sources are refused, and the line may carry a bracketed option such as signed-by. When update is true, apt-get update runs afterwards; if it fails the new file is removed and its error returned. Returns Record {path: String, updated: Bool}. Not done: repository key import or verification, which apt still enforces on signed repositories. Refused with E_BAD_ARG, before any effect: a bad name, a bad or non-https line, an unknown or non-Bool option, an existing ironshell-<name>.list, or pipeline input. Refused with E_UNIMPLEMENTED inside a transaction. A held lock is E_BAD_STATE; a nonzero apt exit is E_TOOL_FAILED.",
examples: &[
(r#"(try { pkg_add_source("Bad Name", "deb https://deb.debian.org/debian trixie main") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { pkg_add_source("x", "deb http://example.com/debian trixie main", {update: true}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "pkg_hold", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("names", Ty::Array, "a nonempty Array of at most 64 names of installed packages, bare (no version)")],
returns: "Record",
doc: "Hold installed packages at their current version with apt-mark hold on Debian-family Linux only; other platforms and package managers are E_UNIMPLEMENTED with NOTHING WAS CHANGED. Requires root. Each name must be installed (E_BAD_STATE otherwise, refused before any change). The hold is verified with apt-mark showhold; a name missing from that list is E_TOOL_FAILED. Returns Record {held: Array of String}. Refused with E_BAD_ARG: a bad list, a name not matching ^[a-z0-9][a-z0-9+.-]{1,127}$ or beginning with '-', a name with =version, or pipeline input. Refused with E_UNIMPLEMENTED inside a transaction. A held lock is E_BAD_STATE.",
examples: &[(r#"(try { pkg_hold([]) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "pkg_unhold", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("names", Ty::Array, "a nonempty Array of at most 64 package names, bare (no version)")],
returns: "Record",
doc: "Release holds with apt-mark unhold on Debian-family Linux only; other platforms and package managers are E_UNIMPLEMENTED with NOTHING WAS CHANGED. Requires root. The release is verified with apt-mark showhold: if any name is still held the call is E_TOOL_FAILED. Returns Record {unheld: Array of String}. Refused with E_BAD_ARG: a bad list, a name not matching ^[a-z0-9][a-z0-9+.-]{1,127}$ or beginning with '-', a name with =version, or pipeline input. Refused with E_UNIMPLEMENTED inside a transaction. A held lock is E_BAD_STATE.",
examples: &[(r#"(try { pkg_unhold([]) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "test_coverage", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("report", Ty::Str, "Supplied LCOV 1.x report text, not a filename")], returns: "Record",
doc: "Summarize supplied LCOV 1.x line/function/branch coverage, without collecting or executing tests. Return {files, lines, functions, branches}; each metric is {found: Int, hit: Int, percent: Float or null when found is zero}; files are sorted by literal SF path with the same metrics. Support TN, SF, FN, FNDA, DA with optional checksum, BRDA (dash means not hit), LF/LH/FNF/FNH/BRF/BRH and end_of_record. Require complete source records, matching FN/FNDA names and consistent optional summary counts. Duplicate data/summary fields within a record reject. Repeated source records merge by union of covered locations, with conflicting function locations or supplied line checksums rejected. No source-file reads, implicit last-run state, subprocess or instrumentation. Limits: 1 MiB, 25000 lines, 64 KiB per line, 1024 source records, 10000 data entries, 4096-byte names. Decimal counts fit nonnegative Int; line numbers are positive. Unknown formats/records, malformed data and pipeline input reject with coded errors. Direct-only and Pure.",
examples: &[(r#"test_coverage("SF:example.rs\nDA:1,1\nend_of_record\n").lines.hit"#, "1")],
},
Signature {
name: "test_passing", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("report", Ty::Str, "Completed Rust libtest JSON execution-event report text")], returns: "Array",
doc: "List passed test results from supplied completed libtest JSON execution reports. Return records {suite: Int (1-based report order), name: String, status: passed, stdout, message, reason, exec_time}; absent optional text/timing is null. Sort by suite then name. Require suite started and terminal ok/failed events, test starts for ok/failed results, exact summary counts and all declared tests completed. Ignored results may omit a start. Timeouts are nonterminal notifications; optional post-suite merged-doctest timing reports are validated. Fail-fast/incomplete reports, discovery or benchmark events, Cargo compiler JSON, unknown fields/events, duplicate JSON fields/test events and invalid types/durations reject. JSON is libtest's unstable execution format; no test execution or implicit last-run cache occurs here. Limits: 1 MiB, 25000 lines, 64 KiB per line, 128 suites, 10000 completed tests and 4096-byte test names. Direct-only and Pure; reject pipeline input.",
examples: &[(r#"test_passing("{\"type\":\"suite\",\"event\":\"started\",\"test_count\":1}\n{\"type\":\"test\",\"event\":\"started\",\"name\":\"works\"}\n{\"type\":\"test\",\"event\":\"ok\",\"name\":\"works\"}\n{\"type\":\"suite\",\"event\":\"ok\",\"passed\":1,\"failed\":0,\"ignored\":0,\"measured\":0,\"filtered_out\":0}") | len"#, "1")],
},
Signature {
name: "test_failing", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("report", Ty::Str, "Completed Rust libtest JSON execution-event report text")], returns: "Array",
doc: "List failed test results from supplied libtest JSON using the same validation, limits and record fields as test_passing, with status failed. Captured stdout, failure message/reason and optional duration are retained as data. Well-formed suites with no failed tests return an empty Array; incomplete, contradictory or malformed reports reject before any result is returned. No tests are run, no filename is opened and no last-run cache is assumed. Direct-only and Pure; reject pipeline input.",
examples: &[(r#"test_failing("{\"type\":\"suite\",\"event\":\"started\",\"test_count\":0}\n{\"type\":\"suite\",\"event\":\"ok\",\"passed\":0,\"failed\":0,\"ignored\":0,\"measured\":0,\"filtered_out\":0}") | len"#, "0")],
},
Signature {
name: "test_skipped", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("report", Ty::Str, "Completed Rust libtest JSON execution-event report text")], returns: "Array",
doc: "List explicitly ignored test results from supplied libtest JSON using the same validation, limits and record fields as test_passing, with status skipped. Preserve an optional ignore message. Filtered-out tests are not inferred or listed: their identities are not present in an execution report. No tests are run, no filename is opened and no last-run cache is assumed. Direct-only and Pure; reject pipeline input.",
examples: &[(r#"test_skipped("{\"type\":\"suite\",\"event\":\"started\",\"test_count\":1}\n{\"type\":\"test\",\"event\":\"ignored\",\"name\":\"later\",\"message\":\"needs hardware\"}\n{\"type\":\"suite\",\"event\":\"ok\",\"passed\":0,\"failed\":0,\"ignored\":1,\"measured\":0,\"filtered_out\":0}") | first | fn(r) => r.message"#, "needs hardware")],
},
Signature {
name: "test_snapshot", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("actual", Ty::Any, "Actual snapshot data"), req("baseline", Ty::Any, "Reference snapshot data; may be loaded with open()")], returns: "Record",
doc: "Compare typed snapshot data and return matched Bool, mismatches Int, truncated Bool and up to 128 structured differences. Paths use JSON Pointer escaping; root path is empty. Difference kinds are added, removed or changed relative to the baseline; absent values are Null with kind distinguishing absence. Traverse record keys in sorted order and arrays by index. Int and Float remain distinct; finite signed-zero Floats compare equal. Supported data: Null, Bool, Int, finite Float, String, Array and Record. Reject opaque values, nonfinite floats and invalid calls. Combined budgets: depth 32 (root depth zero), 10000 nodes, 1 MiB scalar/key bytes (numeric/Null/Bool count eight bytes); record keys <=256 bytes. Validate both snapshots before reporting differences, count all differences even if output is capped. Pure comparison only; baseline persistence is composed with ordinary file builtins. Direct-only.",
examples: &[("test_snapshot([1, 2], [1, 2]).matched", "true")],
},
Signature {
name: "test_generate", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("function", Ty::Str, "Rust function path"), req("cases", Ty::Array, "1..128 records of exactly arguments: Array<String>, expected: String; Strings are Rust expressions")], returns: "String",
doc: "Generate Rust assert_eq! unit-test source in a cfg(test) module named __ae_generated_tests, with stable case_000 onward names and super::* imports. Function paths are interpreted from that generated module; use crate:: paths for explicit placement. Parse each supplied argument/expected expression as Rust syntax before emitting code; expression code is supplied by the caller, not inferred. Generation does not execute code, typecheck expressions, infer test oracles, read files or use a model. Limits: path <=256 bytes and 32 raw ASCII punctuation characters; <=64 arguments per case; expressions <=16 KiB each, 64 KiB total and 128 raw ASCII punctuation characters each including strings/comments; output <=1 MiB. Reject malformed syntax, surplus fields and pipeline input. Pure, direct-only. Embed the returned module beside the code under test and run ordinary Rust tests separately.",
examples: &[(r#"typeof(test_generate("add", [{arguments: ["1", "2"], expected: "3"}]))"#, "String")],
},
Signature {
name: "docs_api", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "Rust source text, at most 64 KiB")], returns: "Array",
doc: "Extract top-level explicitly public Rust function, struct, enum, union, trait, type-alias, const and static declarations into name/kind/declaration/documentation records, sorted by name and kind. Function declarations are signatures without bodies; other declarations retain full syntactic definitions, including nested fields and trait defaults. Documentation is literal doc attributes with leading whitespace trimmed. Exclude private and restricted pub(crate)/pub(super) declarations. No effective visibility/type resolution, module/impl traversal, imports, macro expansion, cfg evaluation, HTML generation, file reads or execution. Limit 256 raw ASCII punctuation characters including comments/strings. Reject malformed source and pipeline input.",
examples: &[(r#"len(docs_api("pub fn example() {}"))"#, "1")],
},
Signature {
name: "yq_query",
category: None,
subject_required: false,
aliases: &["yq"],
subject: None,
params: &[req("expression", Ty::Str, "a yq expression; must not begin with '-'"), req("document", Ty::Str, "YAML, JSON or TOML text to query")],
returns: "String",
doc: "Runs yq with the expression and a document written to a temporary file (the runner gives a child no stdin), and returns yq's output, trimmed. The document is at most 4 MiB. The temporary directory is removed afterwards. A nonzero exit is E_TOOL_FAILED with the stderr tail; output over 4 MiB is refused. Deadline 2 minutes. yq itself reads the file and runs no project code, but it is classified Exec. A missing yq is E_TOOL_MISSING; nothing is parsed natively. Takes no pipeline input.",
examples: &[
(r#"(try { yq_query(5, "a: 1") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { yq_query("--version", "a: 1") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "fd_find",
category: None,
subject_required: false,
aliases: &["fd"],
subject: None,
params: &[req("pattern", Ty::Str, "a regular expression for file names; a leading '-' is data"), opt("path", Ty::Str, "a directory inside the workspace; defaults to the working directory"), opt("options", Ty::Record, "{type?: f|d|l|x|e|s|p, extension?: String}")],
returns: "Array",
doc: "Runs fd with the pattern after -- and returns the matching paths as an Array of Strings. Options other than type and extension are refused. More than 1000 matches is E_BUDGET_EXCEEDED, never a cut list. The path must lie inside the workspace and must not begin with '-'. A nonzero exit is E_TOOL_FAILED. Output is bounded at 4 MiB. Deadline 2 minutes. A missing fd is E_TOOL_MISSING; there is no native fallback. Takes no pipeline input.",
examples: &[
(r#"(try { fd_find(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { fd_find("x", "a", {type: "q"}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "rg_search",
category: None,
subject_required: false,
aliases: &["rg", "ripgrep"],
subject: None,
params: &[req("pattern", Ty::Str, "a regular expression (ripgrep syntax); a leading '-' is data"), opt("path", Ty::Str, "a file or directory inside the workspace; defaults to the working directory"), opt("options", Ty::Record, "{ignore_case?: Bool}")],
returns: "Array",
doc: "Runs rg --json --regexp=PATTERN PATH and returns one Record per match: {file, line, text}. Exit 1 is no matches; any other nonzero exit is E_TOOL_FAILED. More than 1000 matches is E_BUDGET_EXCEEDED. The pattern is passed as --regexp=, so a leading '-' is data. The path must lie inside the workspace and must not begin with '-'. Output is bounded at 16 MiB. Deadline 2 minutes. A missing rg is E_TOOL_MISSING; there is no native fallback. Takes no pipeline input.",
examples: &[
(r#"(try { rg_search(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { rg_search("x", "a", {ignore_case: 1}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "rga_search",
category: None,
subject_required: false,
aliases: &["rga"],
subject: None,
params: &[req("pattern", Ty::Str, "a regular expression; a leading '-' is data"), opt("path", Ty::Str, "a file or directory inside the workspace; defaults to the working directory")],
returns: "Array",
doc: "Runs rga --json --regexp=PATTERN PATH (ripgrep over PDFs, archives and other documents) and returns one value per JSON line of its report. Exit 1 is no matches; any other nonzero exit is E_TOOL_FAILED, and a line that is not JSON is too. More than 1000 matches is E_BUDGET_EXCEEDED. The path must lie inside the workspace. Output is bounded at 16 MiB. rga runs its document adapters as programs, so the call is Exec and agent mode asks for approval. Deadline 2 minutes. A missing rga is E_TOOL_MISSING; there is no fallback to rg. Takes no pipeline input.",
examples: &[
(r#"(try { rga_search(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { rga_search("x", "-y") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "eza_list",
category: None,
subject_required: false,
aliases: &["eza"],
subject: None,
params: &[opt("path", Ty::Str, "a directory inside the workspace; defaults to the working directory")],
returns: "Array",
doc: "Runs eza -la --git --no-user --time-style=long-iso on a directory and returns one String per listed line. The path must lie inside the workspace and must not begin with '-'. A nonzero exit is E_TOOL_FAILED with the stderr tail; output over 4 MiB is refused. Deadline 2 minutes. A missing eza is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { eza_list(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { eza_list("-la") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "fzf_select",
category: None,
subject_required: true,
aliases: &["fzf"],
subject: Some(Ty::Sequence),
params: &[opt("query", Ty::Str, "a case-insensitive substring; absent keeps every item")],
returns: "Array",
doc: "Filters piped items (an Array, or the lines of a String) to those containing the query as a case-insensitive substring, and returns them as an Array of Strings. No process is started: this is not fuzzy matching and offers no interactive picker, so it never needs a terminal and never blocks. Items must be piped in; a direct call is E_BAD_ARG. Takes at most one argument.",
examples: &[
(r#"["apple", "banana"] | fzf_select("AN")"#, r#"["banana"]"#),
(r#"(try { fzf_select("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "delta_diff",
category: None,
subject_required: false,
aliases: &["delta"],
subject: None,
params: &[req("file_a", Ty::Str, "first regular file inside the workspace"), req("file_b", Ty::Str, "second regular file inside the workspace")],
returns: "Record",
doc: "Runs delta on two files inside the workspace and returns {file_a, file_b, diff, success: true}, where diff is delta's rendering of the pair. Each path must be a regular file and must not begin with '-'; a missing one is E_NOT_FOUND. A nonzero exit is E_TOOL_FAILED with the stderr tail; output over 4 MiB is refused. Deadline 2 minutes. A missing delta is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { delta_diff(5, "b") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { delta_diff("a") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "search_by_size",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("size", Ty::Str, "a find-style size: [+|-]N[c|k|M|G|b], default +1M")],
returns: "Array",
doc: "Lists the regular files under the working directory whose size matches a find-style spec (+1M is larger than one MiB, -10k smaller than ten KiB, 100c exactly 100 bytes). The spec is validated before the walk, so a malformed one is E_BAD_ARG even in an empty tree. The walk skips symlinks, the directories node_modules, .git, target, dist, build, vendor, .venv and __pycache__, and stops with E_BUDGET_EXCEEDED after 200000 entries or 30 seconds. More than 1000 matches is E_BUDGET_EXCEEDED. Takes no pipeline input.",
examples: &[
(r#"(try { search_by_size("bogus") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { search_by_size(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "search_code",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pattern", Ty::Str, "a regular expression (Rust regex syntax)")],
returns: "Array",
doc: "Searches the text files under the working directory for lines matching the regular expression and returns \"path:line:text\" Strings. Binary files (a NUL in their first 8000 bytes) are skipped, as grep -I skips them; a text file over 64 MiB is E_BUDGET_EXCEEDED. The walk skips symlinks and the directories listed by search_by_size, and stops with E_BUDGET_EXCEEDED after 200000 entries or 30 seconds. More than 1000 matches is E_BUDGET_EXCEEDED, never a cut list. A pattern that does not compile is E_BAD_ARG with the regex error. Takes no pipeline input.",
examples: &[
(r#"(try { search_code("(") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { search_code(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "search_grep",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pattern", Ty::Str, "a regular expression (Rust regex syntax)")],
returns: "Array",
doc: "The same search as search_code, under its grep name. Returns \"path:line:text\" Strings; binary files are skipped; a pattern that does not compile is E_BAD_ARG; more than 1000 matches or a walk past its limits is E_BUDGET_EXCEEDED. Takes no pipeline input.",
examples: &[
(r#"(try { search_grep("(") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { search_grep(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "search_regex",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pattern", Ty::Str, "a regular expression (Rust regex syntax)")],
returns: "Array",
doc: "The same search as search_code, under its regex name. Returns \"path:line:text\" Strings; binary files are skipped; a pattern that does not compile is E_BAD_ARG; more than 1000 matches or a walk past its limits is E_BUDGET_EXCEEDED. Takes no pipeline input.",
examples: &[
(r#"(try { search_regex("(") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { search_regex(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "search_duplicates", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("corpus", Ty::Array, "Array of exactly {name: String, source: String} Rust source records")], returns: "Array",
doc: "Find exact token-normalized Rust free-function clones across supplied documents and inline modules. Ignore function names, outer attributes/docs, visibility, comments and source formatting. Preserve parameter names, types, qualifiers, generics, literal values and bodies. Return groups with count and sorted occurrences {document,function}; omit singletons. Not alpha-renaming, semantic equivalence, impl methods or macro expansion. Corpus maximum 128 unique document names (nonempty, <=256 bytes), 1 MiB aggregate source, 256 functions; each source <=64 KiB and 256 raw ASCII punctuation characters including strings/comments. Ambiguous duplicate function paths reject; cfg is not evaluated. Pure, direct-only; source is never executed or read from files.",
examples: &[("search_duplicates([])", "[]")],
},
Signature {
name: "search_similar", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("query", Ty::Str, "Rust source containing exactly one free function"), req("corpus", Ty::Array, "Array of exactly {name: String, source: String} records"), opt_range("limit", Ty::Int, 1, 100, "Maximum matches, default 10")], returns: "Array",
doc: "Rank parsed Rust free functions by Jaccard similarity of unique five-Unicode-scalar shingles of token-normalized signature/body syntax, ignoring function names and outer attributes/visibility. Preserve literal contents and parameter names. Return {document,function,score}, descending score then document/function. Structural text similarity, without semantic or alpha-renaming claims. The query contains exactly one free function; unrelated nonfunction items are ignored. Inline modules are traversed, impl methods/macros are not. Same source/corpus bounds and ambiguity rules as search_duplicates. Pure, direct-only; no files, execution or models.",
examples: &[(r#"search_similar("fn query() {}", [])"#, "[]"), (r#"search_similar("fn query() {}", [], 1)"#, "[]")],
},
Signature {
name: "search_semantic", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("query_embedding", Ty::Array, "Nonzero finite numeric embedding"), req("corpus", Ty::Array, "Array of exactly {name: String, embedding: Array} records"), opt_range("limit", Ty::Int, 1, 100, "Maximum matches, default 10")], returns: "Array",
doc: "Exact cosine nearest-neighbor ranking for caller-supplied semantic embeddings in a common model/space. Does not generate embeddings or infer meaning from source text. Return {name,score}, descending score then name, including negative scores. Scale-normalize to avoid overflow/underflow with finite extreme components. Each vector has equal dimension 1..4096, finite Int/Float elements and nonzero norm. At most 1024 unique nonempty document names (<=256 bytes), and 1048576 compared components. Validate the entire corpus before returning matches; malformed or incompatible vectors reject. Pure, direct-only, deterministic and no model/network/filesystem calls.",
examples: &[("search_semantic([1, 0], [])", "[]"), ("search_semantic([1, 0], [], 1)", "[]")],
},
Signature {
name: "docs_types", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "Rust source text, at most 1 MiB")], returns: "Array",
doc: "Parse Rust source and return top-level struct, enum, union, trait and type-alias declarations as name/kind/definition String records, sorted by name. Token-normalized definitions retain syntactic generics and fields. No file reads, execution, macro expansion, module traversal or type resolution. Conservative limit of 128 raw ASCII punctuation characters includes comments/strings. Reject invalid syntax, surplus arguments and pipeline input.",
examples: &[(r#"len(docs_types("struct Example;"))"#, "1")],
},
Signature {
name: "docs_signatures", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "Rust source text, at most 1 MiB")], returns: "Array",
doc: "Parse Rust source and return top-level free-function name/signature Strings and async Bool, sorted by name. Signatures preserve syntactic parameters, generics, return types and where clauses with normalized token spacing. No file reads, execution, macro expansion, module/impl traversal or type resolution. Source limit 1 MiB; conservative limit of 128 raw ASCII punctuation characters includes comments/strings. Reject invalid syntax, surplus arguments and pipeline input.",
examples: &[(r#"len(docs_signatures("fn example(x: i64) -> i64 { x }"))"#, "1")],
},
Signature {
name: "net_connect", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("ip", Ty::Str, "Literal IPv4 or IPv6 address"), Param { range: Some((1, 65535)), ..req("port", Ty::Int, "Port 1..65535") }, opt_range("timeout_ms", Ty::Int, 1, 10000, "Timeout in milliseconds, default 1000; also used for later I/O")], returns: "String",
doc: "Connect to a TCP endpoint. Return an opaque process-local connection handle. Literal IPs avoid unbounded DNS lookup. At most 128 retained handles; close explicitly. Timeout 1..10000 ms, default 1000. Network policy applies before effects. Transactions and pipeline input are refused.",
examples: &[(r#"(try { net_connect("invalid", 1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { net_connect("invalid", 1, 50) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "net_listen", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("ip", Ty::Str, "Literal IPv4 or IPv6 address"), Param { range: Some((1, 65535)), ..req("port", Ty::Int, "Port 1..65535") }, opt_range("timeout_ms", Ty::Int, 1, 10000, "Timeout in milliseconds, default 1000; also used for later I/O")], returns: "String",
doc: "Bind a TCP endpoint and accept one connection before timeout, then drop the listener. Guard both the bind address and accepted peer. Port zero is not accepted. Return an opaque process-local connection handle. Literal IPs avoid unbounded DNS lookup. At most 128 retained handles; close explicitly. Timeout 1..10000 ms, default 1000. Network policy applies before effects. Transactions and pipeline input are refused.",
examples: &[(r#"(try { net_listen("invalid", 1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { net_listen("invalid", 1, 50) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "net_send", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("handle", Ty::Str, "Live process-local TCP handle"), req("data", Ty::Any, "String UTF-8 or Array of byte Ints 0..255, at most 1 MiB")], returns: "Int",
doc: "Write all UTF-8 String or byte Array data and return byte count. At most 1 MiB per call. Total send deadline uses the connection timeout. Errors may occur after a prefix was transmitted; do not blindly retry. Guard the stored actual peer on every call. Transactions and pipeline input are refused; concurrent I/O on the same handle is refused as busy.",
examples: &[(r#"(try { net_send("missing", [256]) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "net_recv", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("handle", Ty::Str, "Live process-local TCP handle"), opt_range("max_bytes", Ty::Int, 1, 1048576, "Maximum bytes for one read, default 4096")], returns: "Record",
doc: "Perform one TCP read and return {bytes: Array<Int>, eof: Bool}. Binary bytes are preserved. A read may return fewer than max_bytes; TCP has no message framing. EOF means a zero-byte read; timeout is E_IO. Connection timeout bounds blocking. Guard the stored peer, refuse transactions and pipeline input, and reject concurrent I/O as busy.",
examples: &[(r#"(try { net_recv("missing") } catch e { e.error.code })"#, "E_BAD_STATE"), (r#"(try { net_recv("missing", 1) } catch e { e.error.code })"#, "E_BAD_STATE")],
},
Signature {
name: "net_close", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("handle", Ty::Str, "Live process-local TCP handle")], returns: "Bool",
doc: "Shutdown both directions and invalidate a TCP handle, returning true on successful closure including an already disconnected peer. Pending I/O observes a closed flag between waits bounded to 50 milliseconds; close never waits for the stream mutex. Guard the stored peer before cleanup; current network policy must permit it. Unknown or closed handles return E_BAD_STATE. Transactions and pipeline input are refused. Handles are released automatically on process exit.",
examples: &[(r#"(try { net_close("missing") } catch e { e.error.code })"#, "E_BAD_STATE")],
},
Signature {
name: "net_interfaces", category: None, subject_required: false, aliases: &["ifconfig"], subject: None,
params: &[],
returns: "Array",
doc: "Return one Record per network interface with name, plus mac and status where the tool reports them, description and speed on Windows, and mtu and addresses on Linux. A field the tool does not report is absent from the Record, not empty. Read from Get-NetAdapter, ip -j addr show or ifconfig. Machine-dependent. Tool failure and unreadable output are coded, never an empty array. At most 4096 records. Reject arguments and pipeline input.",
examples: &[("net_interfaces()", "[{name: lo, mac: 00:00:00:00:00:00, status: UNKNOWN}]")],
},
Signature {
name: "net_ip", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "String | Array",
doc: "Return this host's primary IPv4 address as a String, from hostname -I, ipconfig getifaddr en0 or Get-NetIPAddress. On Windows several addresses are returned as an Array of {ip, interface} Records. No IPv4 address is E_NOT_FOUND; tool failure is coded. Machine-dependent. Reject arguments and pipeline input.",
examples: &[("net_ip()", "192.168.1.10")],
},
Signature {
name: "net_dns_lookup", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("host", Ty::Str, "Hostname to resolve; option-like text and characters outside hostname syntax are refused")],
returns: "Array",
doc: "Resolve a hostname to its address answers as an Array of Strings, using Resolve-DnsName on Windows and dig +short elsewhere. The name is one argument to the resolver, never shell text. This makes a DNS query, so network policy applies. A name with no answer is an empty Array where the resolver reports success; a resolver that reports failure is E_TOOL_FAILED. Transactions and pipeline input are refused.",
examples: &[(r#"(try { net_dns_lookup("-f") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "host_lookup", category: None, subject_required: false, aliases: &["host"], subject: None,
params: &[req("hostname", Ty::Str, "a host name or IP literal; a leading '-' and characters outside host syntax are refused")], returns: "Record",
doc: "DNS lookup through the platform resolver: host on Unix, nslookup on Windows. Returns {hostname, result}, where result is the resolver's text. Takes no pipeline input. Output past 4 MiB is E_BUDGET_EXCEEDED. A lookup the resolver reports as failed is E_TOOL_FAILED and a missing resolver is E_TOOL_MISSING. Refused inside a transaction, because traffic cannot be rolled back.",
examples: &[
(r#"(try { host_lookup("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { host_lookup(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "net_dns_reverse", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("ip", Ty::Str, "IPv4 or IPv6 address literal; names are refused")],
returns: "String",
doc: "Return the first PTR name for an address as a String, using Resolve-DnsName on Windows and dig -x elsewhere. Only an address literal is accepted. This makes a DNS query, so network policy applies. No PTR record is E_NOT_FOUND; a resolver that reports failure is E_TOOL_FAILED. Transactions and pipeline input are refused.",
examples: &[(r#"(try { net_dns_reverse("example.com") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "net_ping", category: None, subject_required: false, aliases: &["ping"], subject: None,
params: &[req("host", Ty::Str, "Hostname or IP literal; option-like text is refused"), opt_range("count", Ty::Int, 1, 100, "Echo requests, default 4")],
returns: "Record",
doc: "Send ICMP echo requests with ping and return Record host, packets_sent, packets_received, packet_loss_pct, min_rtt, avg_rtt and max_rtt (milliseconds), with raw output kept. A host that does not answer is reported as loss, not an error. A run that prints no statistics is E_TOOL_FAILED. The host is passed as an argument and never read as an option. Count 1..100, default 4. Network policy applies. Transactions and pipeline input are refused.",
examples: &[(r#"(try { net_ping("-f") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { net_ping("-f", 0) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "net_latency", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("host", Ty::Str, "Hostname or IP literal; option-like text is refused")],
returns: "Float",
doc: "Return the round-trip time of one ICMP echo to the host, in milliseconds, as reported by ping. The value is the probe's own measurement, not the time to start the ping process. No reply is E_TOOL_FAILED. Network policy applies. Transactions and pipeline input are refused.",
examples: &[(r#"(try { net_latency("-f") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "net_traceroute", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("host", Ty::Str, "Hostname or IP literal; option-like text is refused"), opt_range("max_hops", Ty::Int, 1, 30, "Hop ceiling, default 30")],
returns: "Array",
doc: "Trace the route to a host with tracert or traceroute, without name resolution, and return Array of Records hop, ip and rtt_ms. ip is * for a hop that did not answer. At most max_hops hops (1..30, default 30). The run is bounded at 120 s. Network policy applies. Transactions and pipeline input are refused.",
examples: &[(r#"(try { net_traceroute("-f") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { net_traceroute("-f", 0) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "mtr_trace", category: None, subject_required: false, aliases: &["mtr"], subject: None,
params: &[req("host", Ty::Str, "a host name or IP literal; a leading '-' is refused"), opt_range("cycles", Ty::Int, 1, 100, "probe cycles, default 5")], returns: "Record",
doc: "mtr --report for one host, returning {host, report}. The run has a 120 s deadline and its report is bounded to 4 MiB. A nonzero exit is E_TOOL_FAILED and a missing mtr is E_TOOL_MISSING. Refused inside a transaction.",
examples: &[
(r#"(try { mtr_trace("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { mtr_trace("x", 0) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "net_connections", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "Array",
doc: "Return one Record per socket with protocol, state (upper case, such as LISTEN or ESTABLISHED), local and peer. Read from Get-NetTCPConnection, ss -tuan or netstat -an; the macOS table is TCP only. Machine-dependent. At most 4096 records. Reject arguments and pipeline input.",
examples: &[("net_connections()", "[{protocol: tcp, state: LISTEN, local: 0.0.0.0:22, peer: 0.0.0.0:0}]")],
},
Signature {
name: "net_ports", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "Array",
doc: "Return the listening sockets as net_connections Records: TCP in LISTEN and UDP in UNCONN. Machine-dependent. At most 4096 records. Reject arguments and pipeline input.",
examples: &[("net_ports()", "[{protocol: tcp, state: LISTEN, local: 0.0.0.0:22, peer: 0.0.0.0:0}]")],
},
Signature {
name: "net_arp", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "Array",
doc: "Return the ARP neighbour table as Records of ip, mac and interface (Unix) or ip, mac and type (Windows), read from arp -a. A failed run is E_TOOL_FAILED. Machine-dependent. At most 4096 records. Reject arguments and pipeline input.",
examples: &[("net_arp()", "[{ip: 192.168.1.1, mac: aa-bb-cc-dd-ee-ff, type: dynamic}]")],
},
Signature {
name: "net_route", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "Array",
doc: "Return the routing table as Records of destination, gateway, interface and metric (Linux and Windows) or destination, gateway, flags and interface (macOS), read from Get-NetRoute, ip -j route or netstat -rn. Machine-dependent. At most 4096 records. Reject arguments and pipeline input.",
examples: &[("net_route()", "[{destination: default, gateway: 192.168.1.1, interface: eth0, metric: 100}]")],
},
Signature {
name: "net_stats", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "Array",
doc: "Return the protocol counters from netstat -s as Records of section (the heading, or null), counter (its name) and value (an Int, or null where the line has no number). A line that cannot be read keeps its text as the counter. A failed run is E_TOOL_FAILED; output over 1 MiB is E_BUDGET_EXCEEDED. Machine-dependent. Reject arguments and pipeline input.",
examples: &[("net_stats()", "[{section: Tcp, counter: active connections openings, value: 12}]")],
},
Signature {
name: "net_bandwidth", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "Array",
doc: "Return per-interface totals since boot as Records of interface, rx_bytes, rx_packets, tx_bytes and tx_packets, read from /proc/net/dev, netstat -ib or Get-NetAdapterStatistics. Reads only; nothing is downloaded or sent. At most 4096 records. Reject arguments and pipeline input.",
examples: &[(r#"(try { net_bandwidth(1) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "net_scan", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("host", Ty::Str, "localhost, 127.0.0.1 or ::1; any other host is refused by policy"), Param { range: Some((1, 65535)), ..req("first_port", Ty::Int, "First TCP port, 1..65535") }, Param { range: Some((1, 65535)), ..req("last_port", Ty::Int, "Last TCP port, inclusive, 1..65535") }, opt_range("timeout_ms", Ty::Int, 1, 10000, "Per-port wait for an answer in milliseconds, default 3000")],
returns: "Array",
doc: "Probe a TCP port range on this machine and return Array of Records port and state, where state is open (accepted), closed (refused) or filtered (no answer within timeout_ms, 1..10000, default 3000). Ports are probed 128 at a time, each batch sharing one wait. Only localhost, 127.0.0.1 and ::1 are probed; another host is E_POLICY_DENY whatever IRONSHELL_NET_ALLOW says. At most 1024 ports per call; a larger range is E_BAD_ARG. The whole call is bounded at 30 s. Connect failures other than refusal are coded I/O errors. Network policy applies. Transactions and pipeline input are refused.",
examples: &[(r#"(try { net_scan("example.com", 1, 2) } catch e { e.error.code })"#, "E_POLICY_DENY"), (r#"(try { net_scan("127.0.0.1", 1, 2000, 50) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "nmap_scan", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("host", Ty::Str, "host name or IP literal; a leading '-' is refused"), opt("options", Ty::Record, "{ports?: port list such as 22,80,1000-1100; flags?: whitespace-separated scan flags from -sT -sS -sU -sV -Pn -n -T0..-T5}")], returns: "Record",
doc: "Scan one host with nmap, returning {host, ports}: one Record per port with its protocol, state, reason and service. Ports must be 1..65535 and given as a list or ranges. Flags come only from the allowlist; every other nmap option is refused by policy, because --script runs scripts and -oN, -oG and --log-file write files. Unknown option keys are refused. A nonzero exit is E_TOOL_FAILED and a missing nmap is E_TOOL_MISSING. The run has a 900 s deadline. Refused inside a transaction.",
examples: &[
(r#"(try { nmap_scan("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { nmap_scan("x", {ports: "0"}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "nmap_quick", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("host", Ty::Str, "host name or IP literal; a leading '-' is refused")], returns: "Record",
doc: "Quick nmap scan of the common ports, open ones only, returning {host, ports, scan_type}. A nonzero exit is E_TOOL_FAILED and a missing nmap is E_TOOL_MISSING. Refused inside a transaction.",
examples: &[
(r#"(try { nmap_quick("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { nmap_quick(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "net_whois", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("domain", Ty::Str, "Domain or IP literal; option-like text is refused")],
returns: "Record",
doc: "Query whois and return Record domain, with registrar, creation_date, expiration_date, updated_date, status, name_servers and other parsed fields when present, plus raw text cut at 64 KiB and raw_truncated. A failed whois is E_TOOL_FAILED. Makes a network query, so network policy applies. Transactions and pipeline input are refused.",
examples: &[(r#"(try { net_whois("-f") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "code_references", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "IronShell source text"), req("symbol", Ty::Str, "Identifier or dotted identifier, at most 256 bytes")], returns: "Array",
doc: "Pure IronShell source-unit analysis; never execute code, read imports or resolve other languages/files. Source limits: 64 KiB, 8192 lexer tokens and 256 raw ASCII punctuation characters including comments/strings. No runtime or semantic scope resolution. Invalid source syntax is E_BAD_ARG; budgets are coded. Reject pipeline input. Return lexical identifier occurrences, including declarations, parameters and field labels; exclude comments and string tokens including dynamic interpolation. One-based Unicode scalar line/column; exclusive end_column. Dotted queries match the terminal identifier of a lexical member chain.",
examples: &[(r#"len(code_references("x = 1; y = x", "x"))"#, "2")],
},
Signature {
name: "code_definition", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "IronShell source text"), req("symbol", Ty::Str, "Top-level binding name")], returns: "Array",
doc: "Pure IronShell source-unit analysis; never execute code, read imports or resolve other languages/files. Source limits: 64 KiB, 8192 lexer tokens and 256 raw ASCII punctuation characters including comments/strings. No runtime or semantic scope resolution. Invalid source syntax is E_BAD_ARG; budgets are coded. Reject pipeline input. Return all matching top-level bindings with name, kind, mutable, public, params and typed value_ast. Include cfg-wrapped declarations syntactically without evaluating conditions. No import/member definition lookup. Absent declarations return an empty Array.",
examples: &[(r#"len(code_definition("double = fn(x) => x * 2", "double"))"#, "1")],
},
Signature {
name: "code_callers", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "IronShell source text"), req("symbol", Ty::Str, "Static callee name, including dotted module names")], returns: "Array",
doc: "Pure IronShell source-unit analysis; never execute code, read imports or resolve other languages/files. Source limits: 64 KiB, 8192 lexer tokens and 256 raw ASCII punctuation characters including comments/strings. No runtime or semantic scope resolution. Invalid source syntax is E_BAD_ARG; budgets are coded. Reject pipeline input. Return sorted unique function-binding names containing a syntactic call to symbol; other calls use <top-level>. Include nested lambda bodies as lexical containment, named pipeline stages and registered module pipeline stages. Exclude dynamic calls and evaluated string interpolation. This is not a runtime trace.",
examples: &[(r#"len(code_callers("double = fn(x) => x * 2; use = fn(x) => double(x)", "double"))"#, "1")],
},
Signature {
name: "code_callees", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "IronShell source text"), req("symbol", Ty::Str, "Source function-binding name")], returns: "Record",
doc: "Pure IronShell source-unit analysis; never execute code, read imports or resolve other languages/files. Source limits: 64 KiB, 8192 lexer tokens and 256 raw ASCII punctuation characters including comments/strings. No runtime or semantic scope resolution. Invalid source syntax is E_BAD_ARG; budgets are coded. Reject pipeline input. Return {name, found, callees, dynamic_calls}: sorted union of static call names across matching lambdas plus a count of dynamic callee expressions. found=false means no source lambda body exists, including native builtin bodies. Include nested lambdas lexically and named pipeline stages; no evaluated-string call analysis.",
examples: &[(r#"code_callees("double = fn(x) => abs(x)", "double").found"#, "true")],
},
Signature {
name: "code_hover", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "IronShell source text"), req("line", Ty::Int, "One-based line"), req("column", Ty::Int, "One-based Unicode scalar column")], returns: "Record",
doc: "Pure IronShell source-unit analysis; never execute code, read imports or resolve other languages/files. Source limits: 64 KiB, 8192 lexer tokens and 256 raw ASCII punctuation characters including comments/strings. No runtime or semantic scope resolution. Invalid source syntax is E_BAD_ARG; budgets are coded. Reject pipeline input. Return found Bool and, for an identifier at the cursor, name, qualified, line, column, top-level definitions and declared signature information. Cursor must be within source or at line end. Comments/strings and keywords outside field/member positions have found=false. Binding metadata is syntactic; shadowing is not resolved.",
examples: &[(r#"code_hover("answer = 42", 1, 2).name"#, "answer")],
},
Signature {
name: "code_signature", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "IronShell source text, or empty String for builtin lookup"), req("symbol", Ty::Str, "Source binding or declared builtin name")], returns: "Record",
doc: "Pure IronShell source-unit analysis; never execute code, read imports or resolve other languages/files. Source limits: 64 KiB, 8192 lexer tokens and 256 raw ASCII punctuation characters including comments/strings. No runtime or semantic scope resolution. Invalid source syntax is E_BAD_ARG; budgets are coded. Reject pipeline input. Return {name, found, origin, signatures, documentation}. Source bindings take precedence; lambdas preserve parameter names and use Any for unknown return types. Return all matching lambda signatures; non-lambda bindings prevent builtin fallback. Otherwise read actual declared builtin signatures, using the actual module mapping for dotted spelling. Unknown/undeclared builtin signatures have found=false.",
examples: &[(r#"code_signature("double = fn(x) => x * 2", "double").found"#, "true")],
},
Signature {
name: "code_completions", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "IronShell source text"), opt("prefix", Ty::Str, "Literal prefix, default empty; at most 256 bytes")], returns: "Array",
doc: "Pure IronShell source-unit analysis; never execute code, read imports or resolve other languages/files. Source limits: 64 KiB, 8192 lexer tokens and 256 raw ASCII punctuation characters including comments/strings. No runtime or semantic scope resolution. Invalid source syntax is E_BAD_ARG; budgets are coded. Reject pipeline input. Return sorted unique registered builtin/top-level source binding completion records matching a literal prefix. Source bindings replace same-name builtins. Undeclared builtins have declared=false and null signature; no invented contracts. No import/member/local-scope/runtime completion. Refuse results beyond 16 MiB instead of returning partial output.",
examples: &[(r#"len(code_completions("answer = 42", "answer"))"#, "1"), (r#"len(code_completions("answer = 42")) > 0"#, "true")],
},
Signature {
name: "project_scripts", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("manifest", Ty::Str, "Path to a JSON, JSONC or TOML manifest/config file")], returns: "Array",
doc: "Read one regular UTF-8 manifest, at most 1 MiB, and return sorted {name, command, kind, manifest, definition} records. Extract literal JSON scripts (npm), tasks (Deno Strings or objects with command and/or String Array dependencies; dependency-only tasks have null command), TOML project.scripts/project.gui-scripts (Python) and alias (Cargo Strings or String Arrays). Support JSONC comments/trailing commas. Preserve the complete literal definition, including task metadata. Other manifest fields are not inferred scripts or execution plans. Return commands as data; never execute them. Invalid syntax/shapes refuse, as do more than 10000 entries; no partial results. Guard the resolved read target and use existing safe-path validation, including configured workspace/base-directory containment. Reject pipeline input and surplus arguments.",
examples: &[(r#"(try { project_scripts("") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "cron_add", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("schedule", Ty::Str, "Unix five-field/@ schedule; Windows @hourly, @daily or @weekly"), req("command", Ty::Str, "One command line; Unix at most 64 KiB, Windows at most 4096 UTF-16 code units")], returns: "String",
doc: "Create a recurring job under the current user and return its lifecycle target. Unix appends one unique crontab entry, preserving unrelated text; external writers can race. Windows creates a uniquely named limited interactive-user task running cmd.exe /d /s /c: @hourly starts next whole hour, @daily at midnight, @weekly Sunday midnight. Windows tasks require the user to be logged in. Reject transactions, invalid shape and pipeline input; requires Exec approval.",
examples: &[(r#"(try { cron_add("", "") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "cron_remove", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("target", Ty::Str, "Windows task name including task path, or exact active Unix crontab entry")], returns: "Bool",
doc: "Remove an existing scheduled job. Windows uses schtasks; Unix modifies one exact, unique user-crontab entry, preserving unrelated text. Disabled Unix entries use the IronShell comment prefix. Returns true after a successful native operation. Rejects transactions, pipeline input and invalid targets. In-process updates are serialized; external crontab writers can race. Requires effect approval.",
examples: &[(r#"(try { cron_remove("") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "cron_enable", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("target", Ty::Str, "Windows task name including task path, or exact active Unix crontab entry")], returns: "Bool",
doc: "Enable an existing scheduled job. Windows uses schtasks; Unix modifies one exact, unique user-crontab entry, preserving unrelated text. Disabled Unix entries use the IronShell comment prefix. Returns true after a successful native operation. Rejects transactions, pipeline input and invalid targets. In-process updates are serialized; external crontab writers can race. Requires effect approval.",
examples: &[(r#"(try { cron_enable("") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "cron_disable", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("target", Ty::Str, "Windows task name including task path, or exact active Unix crontab entry")], returns: "Bool",
doc: "Disable an existing scheduled job. Windows uses schtasks; Unix modifies one exact, unique user-crontab entry, preserving unrelated text. Disabled Unix entries use the IronShell comment prefix. Returns true after a successful native operation. Rejects transactions, pipeline input and invalid targets. In-process updates are serialized; external crontab writers can race. Requires effect approval.",
examples: &[(r#"(try { cron_disable("") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "at_schedule", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("time", Ty::Str, "Future local YYYY-MM-DDTHH:MM timestamp"), req("command", Ty::Str, "One command line; Unix at most 64 KiB, Windows at most 4096 UTF-16 code units")], returns: "String",
doc: "Schedule a one-time command and return its job ID. Reject past, ambiguous or nonexistent local times, invalid shape, transactions and pipeline input. Unix uses at -t with the command on stdin; Windows registers a unique IronShell-at task under the current limited interactive user running cmd.exe /d /s /c, requiring that user to be logged in. Requires Exec approval. Unrecognized successful registration output reports that a job may exist: inspect the queue before retrying.",
examples: &[(r#"(try { at_schedule("", "") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "at_remove", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("job_id", Ty::Str, "Unix positive decimal atq ID or Windows IronShell-at UUID task name")], returns: "Bool",
doc: "Remove one scheduled one-time job and return true after successful native removal. Unix uses atrm; Windows deletes the exact IronShell-at task by name. Reject invalid IDs, wildcard targets, transactions and pipeline input; requires Destructive approval.",
examples: &[(r#"(try { at_remove("") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "at_list", category: None, subject_required: false, aliases: &[], subject: None, params: &[], returns: "Array",
doc: "Unix atq job listing in a supported tab-separated layout. Records contain job_id, queue, user and schedule Strings; schedule preserves the entire raw tail including queue/user, without date or locale normalization. Successful empty output means no jobs. Failed tools, non-UTF-8 or unfamiliar layouts carry coded errors. Windows lists root-folder IronShell-at tasks as job_id/queue/user/schedule/state Strings; other Windows tasks are excluded, and schedule is the native trigger StartBoundary. Reject arguments and pipeline input.",
examples: &[("at_list()", "[]")],
},
Signature {
name: "cron_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Read-only scheduler query. Windows returns name/state/path Strings from complete task JSON; Unix returns schedule/command Strings from user-crontab jobs, excluding comments and environment definitions. Standard five-field and known @ schedules are supported; command text is preserved. No schedule evaluation or environment interpretation is performed. Reject arguments and pipeline input; failures and malformed output carry coded errors.",
examples: &[("cron_list()", "[]")],
},
Signature {
name: "group_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Every group on this system, with its gid and members.",
examples: &[("typeof(group_list())", "Array")],
},
Signature {
name: "user_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Every user account, with uid, gid, home and shell.",
examples: &[("typeof(user_list())", "Array")],
},
Signature {
name: "workspace_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Every configured workspace.",
examples: &[("typeof(workspace_list())", "Array")],
},
Signature {
name: "workspace_create",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("name", Ty::Str, "workspace name"), opt("options", Ty::Record, "{description?: String}")],
returns: "Record",
doc: "Create a workspace owned by the caller. Membership is local to this process.",
examples: &[
(r#"typeof(workspace_create("demo-team"))"#, "Record"),
(r#"typeof(workspace_create("demo-team", {description: "shared"}))"#, "Record"),
(r#"(try { workspace_create("") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "workspace_join",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("workspace_id", Ty::Str, "a workspace id")],
returns: "Record",
doc: "Add the caller to a workspace. An existing member refuses.",
examples: &[
(r#"(try { workspace_join("no-such-workspace") } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "workspace_leave",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("workspace_id", Ty::Str, "a workspace id")],
returns: "Record",
doc: "Remove the caller from a workspace. The owner cannot leave.",
examples: &[
(r#"(try { workspace_leave("no-such-workspace") } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "workspace_members",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("workspace_id", Ty::Str, "a workspace id")],
returns: "Array",
doc: "The members of a workspace, with their roles.",
examples: &[
(r#"(try { workspace_members("no-such-workspace") } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "workspace_share_agent",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("workspace_id", Ty::Str, "a workspace the caller belongs to"), req("agent", Ty::Str, "a registered agent (a2a_register)")],
returns: "Record",
doc: "Share a registered agent into a workspace the caller belongs to.",
examples: &[
(r#"(try { workspace_share_agent("no-such-workspace", "agent") } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "workspace_agents",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("workspace_id", Ty::Str, "a workspace id")],
returns: "Array",
doc: "The agent names shared in a workspace.",
examples: &[
(r#"(try { workspace_agents("no-such-workspace") } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "workspace_sync",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("workspace_id", Ty::Str, "a workspace id")],
returns: "Record",
doc: "Refused: there are no remote peers, so nothing can be synced.",
examples: &[
(r#"(try { workspace_sync("no-such-workspace") } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "repl_sessions",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Every open REPL session.",
examples: &[("typeof(repl_sessions())", "Array")],
},
Signature {
name: "repl_serve",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("options", Ty::Record, "host, port and stop; none is used")],
returns: "Record",
doc: "Serve this process's evaluation on 127.0.0.1 (or ::1). Returns {address, port, token, status}; every request must present the token, and remote code runs under the same guard as local code. Needs agent mode. `{stop: true}` stops the listener.",
examples: &[
(r#"(try { repl_serve({stop: true}) } catch e { e.error.code })"#, "E_BAD_STATE"),
(r#"(try { repl_serve({host: "10.0.0.1"}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "repl_connect",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("target", Ty::Any, "a tcp://ip:port String or {host, port} Record"),
req("options", Ty::Record, "{token, code}: the token repl_serve returned and the code to run"),
],
returns: "Record",
doc: "Send one request to a repl_serve listener and return {ok, value, type}, or {ok: false, error} if the remote evaluation failed. A refused token raises E_POLICY_DENY.",
examples: &[
(r#"(try { repl_connect(5, {token: "t"}) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { repl_connect("tcp://127.0.0.1:1", {token: "t"}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "repl_broadcast",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("expression", Ty::Str, "code to send to every session")],
returns: "Record",
doc: "Refused: repl_connect holds no session open, so there is no peer set to send to.",
examples: &[
(r#"(try { repl_broadcast("1 + 1") } catch e { e.error.code })"#, "E_UNIMPLEMENTED"),
],
},
Signature {
name: "repl_disconnect",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("session_id", Ty::Str, "a session from repl_sessions")],
returns: "Record",
doc: "Remove a session from the session table.",
examples: &[
(r#"(try { repl_disconnect("no-such-session") } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "marketplace_publish",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("package", Ty::Record, "{name, version, description?, category?, keywords?, path?}")],
returns: "Record",
doc: "Publish a package. With path, upload that file to the registry (network-guarded, inside the workspace, needs IRONSHELL_REGISTRY_TOKEN) and report status published with target registry. Without path, record it in the local catalogue and report status recorded_locally. A registry refusal is E_POLICY_DENY and leaves the local catalogue unchanged. Unknown fields and fields of the wrong type are E_BAD_ARG.",
examples: &[
(r#"try { marketplace_publish({name: "example-tool"}) } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
],
},
Signature {
name: "marketplace_search",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("query", Ty::Any, "a query string, or a record {q?, category?}")],
returns: "Array",
doc: "Search the registry at packages.nervosys.ai, falling back to the local catalogue. Each record's source is registry or local_cache. A registry that cannot be reached, with no local match, is E_POLICY_DENY rather than an empty list. Network-guarded; a query of the wrong shape is E_BAD_ARG before any request.",
examples: &[
(r#"try { marketplace_search(42) } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
(r#"try { marketplace_search({bogus: "x"}) } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
],
},
Signature {
name: "marketplace_info",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("name", Ty::Str, "the package name")],
returns: "Record",
doc: "A package's details from the registry, with source registry, or from the local catalogue, with source local_cache. A package neither holds is E_NOT_FOUND. Network-guarded; a name that is not a valid package name is E_BAD_ARG before any request.",
examples: &[
(r#"try { marketplace_info("") } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
(r#"try { marketplace_info("bad/name") } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
],
},
Signature {
name: "marketplace_install",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("name", Ty::Str, "the package name"),
opt("version", Ty::Str, "the version; the registry's latest when absent"),
],
returns: "Record",
doc: "Download a package's archive from the registry into the package cache and unpack it. Nothing is run. Links inside the archive are refused. A package the registry does not hold is E_NOT_FOUND; there is no fallback to the local catalogue, which holds records and no archives. Network-guarded.",
examples: &[
(r#"try { marketplace_install("") } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
(r#"try { marketplace_install("example-tool", "../escape") } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
],
},
Signature {
name: "marketplace_uninstall",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("name", Ty::Str, "the package name")],
returns: "Record",
doc: "Remove an installed package's cached files and clear its installed flag, reporting files_removed. A package that is not installed is E_BAD_STATE, and one the catalogue does not hold is E_NOT_FOUND. Nothing is removed from the registry.",
examples: &[
(r#"try { marketplace_uninstall("no-such-package-here") } catch e { e.error.code }"#, r#"E_NOT_FOUND"#),
],
},
Signature {
name: "marketplace_rate",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("name", Ty::Str, "the package name"),
req("score", Ty::Numeric, "a score from 1 to 5"),
],
returns: "Record",
doc: "Add a rating to a package in the local catalogue, reporting the new average, with scope local_cache. The registry is not told. A score outside 1 to 5 is E_BAD_ARG; a package not in the catalogue is E_NOT_FOUND.",
examples: &[
(r#"try { marketplace_rate("no-such-package-here", 3) } catch e { e.error.code }"#, r#"E_NOT_FOUND"#),
(r#"try { marketplace_rate("no-such-package-here", 9) } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
],
},
Signature {
name: "marketplace_update",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("name", Ty::Str, "one installed package; every installed package when absent")],
returns: "Array | Record",
doc: "Check installed packages against the registry for a newer version, reporting update_available with latest, up_to_date, or not_in_registry. It does not install anything. With a name, a package that is not installed is E_BAD_STATE and a registry failure is E_POLICY_DENY; with none, a package that could not be checked reports unreachable with the reason. Network-guarded per request, and makes none when nothing is installed.",
examples: &[
(r#"typeof(marketplace_update())"#, r#"Array"#),
(r#"try { marketplace_update("no-such-package-here") } catch e { e.error.code }"#, r#"E_NOT_FOUND"#),
],
},
Signature {
name: "marketplace_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Every plugin available in the configured marketplaces.",
examples: &[("typeof(marketplace_list())", "Array")],
},
Signature {
name: "startup_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Every startup service, with its enabled state.",
examples: &[("typeof(startup_list())", "Array")],
},
Signature {
name: "search_fixmes",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Every FIXME comment under the working directory, as path:line:text. Skips dependency and build trees.",
examples: &[("search_fixmes()", "[\"src/eval.rs:120: // FIXME ...\", ...]")],
},
Signature {
name: "search_todos",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Every TODO comment under the working directory, as path:line:text. Skips dependency and build trees.",
examples: &[("search_todos()", "[\"src/parser.rs:88: // TODO ...\", ...]")],
},
Signature {
name: "search_recent",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Files under the working directory modified in the last day. Skips dependency and build trees.",
examples: &[("search_recent()", "[\"src/builtins.rs\", ...]")],
},
// Fourth tranche of parameterless declarations. Chosen from the
// discarded-args list by reading bodies: every one binds `_args` or never
// reads `args`, is classified Pure or ReadLocal, and changes nothing.
// Each type below was measured with `typeof(x())` on Linux and on
// Windows and was the same on both; builtins whose type differed
// (platform_cpu_freq, platform_libcpp, platform_ssl_version) or whose
// answer depends on the working directory (docs_*, diag_config) are left
// out until that is fixed.
Signature {
name: "None",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "The Option variant for no value: the record {_tag: \"None\"}.",
examples: &[("typeof(None())", "Record")],
},
Signature {
name: "cloud_instances",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Not implemented: no cloud provider is wired in, so no instance list is read. A valid call answers E_UNIMPLEMENTED; it takes no arguments and no pipeline input.",
examples: &[
(r#"(try { cloud_instances() } catch e { e.error.code })"#, "E_UNIMPLEMENTED"),
(r#"(try { cloud_instances("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "cloud_regions",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Not implemented: no cloud provider is wired in, so no region list is read; the old fixed list was not a provider's answer. A valid call answers E_UNIMPLEMENTED; it takes no arguments and no pipeline input.",
examples: &[
(r#"(try { cloud_regions() } catch e { e.error.code })"#, "E_UNIMPLEMENTED"),
(r#"(try { cloud_regions("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "config_path",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Where the shell keeps its files: config file and directory, cache, data, history, init script and plugins.",
examples: &[("typeof(config_path())", "Record")],
},
Signature {
name: "df",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Mounted filesystems with size, used and available space.",
examples: &[("typeof(df())", "Array")],
},
Signature {
name: "features",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "The runtime feature flags currently enabled, by name.",
examples: &[("typeof(features())", "Array")],
},
Signature {
name: "finetune_start",
category: None,
subject_required: false,
aliases: &["start_finetune"],
subject: None,
params: &[
req("model", Ty::Str, "the base model name"),
req("dataset", Ty::Str, "the dataset name or path"),
opt("config", Ty::Record, "optional Record of String settings"),
],
returns: "Record",
doc: "Start a fine-tuning job. No training backend is wired into this build, so no job is created and nothing is trained: the call is E_UNIMPLEMENTED with nothing changed. It used to record a job as pending and report it started; nothing ever advanced it. Use the provider's own fine-tuning interface or an external trainer.",
examples: &[
(r#"(try { finetune_start("base-model") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { finetune_start("base-model", "train.jsonl") } catch e { e.error.code })"#, "E_UNIMPLEMENTED"),
(r#"(try { finetune_start("base-model", "train.jsonl", {epochs: "3"}) } catch e { e.error.code })"#, "E_UNIMPLEMENTED"),
],
},
Signature {
name: "finetune_status",
category: None,
subject_required: false,
aliases: &["finetune_progress"],
subject: Some(Ty::Str),
params: &[],
returns: "Record",
doc: "Report a fine-tuning job {job_id, model, dataset, status} from the process registry. The registry is empty in this build because finetune_start creates no job, so every id is E_NOT_FOUND. Takes the job id as an argument or piped.",
examples: &[
(r#"(try { finetune_status("ft_no_such_job") } catch e { e.error.code })"#, "E_NOT_FOUND"),
(r#"(try { finetune_status() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "finetune_cancel",
category: None,
subject_required: false,
aliases: &["cancel_finetune"],
subject: Some(Ty::Str),
params: &[],
returns: "Record",
doc: "Cancel a pending or training fine-tuning job in the process registry and return {status: cancelled, job_id}. Because finetune_start creates no job in this build, every id is E_NOT_FOUND. A job in any other state is E_BAD_STATE. Takes the job id as an argument or piped.",
examples: &[
(r#"(try { finetune_cancel("ft_no_such_job") } catch e { e.error.code })"#, "E_NOT_FOUND"),
(r#"(try { finetune_cancel() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "finetune_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Fine-tuning jobs started in this session, as records.",
examples: &[("typeof(finetune_list())", "Array")],
},
Signature {
name: "handle",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("id", Ty::Str, "a live handle id, as listed by handles()")],
returns: "Any",
doc: "The full value behind a result handle, exactly as computed. A missing or unknown id is refused, and the refusal names the live handles.",
examples: &[
(r#"(try { handle("no-such-handle") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { handle(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "handles",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Every live result handle with its shape and size, without the data.",
examples: &[("typeof(handles())", "Array")],
},
Signature {
name: "hostname",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "This machine's hostname.",
examples: &[("typeof(hostname())", "String")],
},
Signature {
name: "hw_disk",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Disks and their usage; the same answer as df().",
examples: &[("typeof(hw_disk())", "Array")],
},
Signature {
name: "hw_network",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Network interfaces; the same answer as net_interfaces().",
examples: &[("typeof(hw_network())", "Array")],
},
Signature {
name: "is_bsd",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Bool",
doc: "Whether the shell is running on a BSD.",
examples: &[("typeof(is_bsd())", "Bool")],
},
Signature {
name: "is_linux",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Bool",
doc: "Whether the shell is running on Linux (Android excluded).",
examples: &[("typeof(is_linux())", "Bool")],
},
Signature {
name: "is_macos",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Bool",
doc: "Whether the shell is running on macOS.",
examples: &[("typeof(is_macos())", "Bool")],
},
Signature {
name: "is_unix",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Bool",
doc: "Whether the shell is running on a Unix-like system.",
examples: &[("typeof(is_unix())", "Bool")],
},
Signature {
name: "is_windows",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Bool",
doc: "Whether the shell is running on Windows.",
examples: &[("typeof(is_windows())", "Bool")],
},
Signature {
name: "list_roles",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Every RBAC role defined in this session, as records.",
examples: &[("typeof(list_roles())", "Array")],
},
Signature {
name: "lscpu",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "CPU information; the same answer as sys_cpu_info().",
examples: &[("typeof(lscpu())", "Record")],
},
Signature {
name: "pkg_sources",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "The system package manager's configured sources (apt sources on Debian-family Linux); empty where there are none to read.",
examples: &[("typeof(pkg_sources())", "Array")],
},
Signature {
name: "platform",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The platform name: windows, linux, macos, bsd, ios or android.",
examples: &[("typeof(platform())", "String")],
},
Signature {
name: "platform_arch",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The CPU architecture the shell was built for, such as x86_64 or aarch64.",
examples: &[("typeof(platform_arch())", "String")],
},
Signature {
name: "platform_build",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The operating system's build identifier.",
examples: &[("typeof(platform_build())", "String")],
},
Signature {
name: "platform_build_systems",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Installed build tools (make, cmake, bazel, ...) with their versions.",
examples: &[("typeof(platform_build_systems())", "Record")],
},
Signature {
name: "platform_capabilities",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "What this host allows: administrator rights, sudo, a GUI, the network, and similar flags.",
examples: &[("typeof(platform_capabilities())", "Record")],
},
Signature {
name: "platform_cloud_clis",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Installed cloud CLIs with their versions.",
examples: &[("typeof(platform_cloud_clis())", "Record")],
},
Signature {
name: "platform_compilers",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Installed compilers with their versions.",
examples: &[("typeof(platform_compilers())", "Record")],
},
Signature {
name: "platform_snapshot",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "A point-in-time record of this host: OS, arch, family, hostname, kernel or Windows version, tool versions, selected environment variables, a timestamp and a fingerprint.",
examples: &[("platform_snapshot()", "a Record: {os, arch, family, timestamp, tools, env, fingerprint, ...}")],
},
Signature {
name: "platform_require",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("requirements", Ty::Record, "{os: \"linux|macos\", arch: \"x86_64\", python: \">=3.10\", docker: true}; no requirements is vacuously satisfied")],
returns: "Record",
doc: "Check requirements against this host. Returns {satisfied: Bool, missing: [String]}, one entry per unmet requirement. A version requirement that cannot be measured is unmet, not satisfied. A non-record argument is E_BAD_ARG.",
examples: &[
("platform_require().satisfied", "true"),
(r#"platform_require({os: "nonexistent-os"}).satisfied"#, "false"),
],
},
Signature {
name: "platform_check_reqs",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("requirements", Ty::Record, "the same requirements as platform_require")],
returns: "Record",
doc: "Check requirements against this host, as platform_require does: {satisfied, missing}.",
examples: &[
("platform_check_reqs().satisfied", "true"),
(r#"platform_check_reqs({os: "nonexistent-os"}).satisfied"#, "false"),
],
},
Signature {
name: "platform_satisfies",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("requirements", Ty::Record, "the same requirements as platform_require")],
returns: "Bool",
doc: "Whether this host meets the requirements: true or false, never a guess. An error means the answer could not be given.",
examples: &[
("platform_satisfies()", "true"),
(r#"platform_satisfies({os: "nonexistent-os"})"#, "false"),
],
},
Signature {
name: "platform_diff",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("before", Ty::Record, "an earlier snapshot"),
req("after", Ty::Record, "a later snapshot"),
],
returns: "Record",
doc: "Compare two snapshots. Returns {added: [key], removed: [key], changed: [{key, old, new}]}.",
examples: &[
("platform_diff({a: 1}, {a: 1}).changed", "[]"),
("platform_diff({a: 1, b: 2}, {a: 3, c: 4}).added", r#"["c"]"#),
],
},
Signature {
name: "platform_compatible",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("a", Ty::Record, "a snapshot from platform_snapshot()"),
req("b", Ty::Record, "a snapshot from platform_snapshot()"),
],
returns: "Bool",
doc: "Whether two snapshots describe the same OS, arch and family. A record without os, arch or family is E_BAD_ARG.",
examples: &[
(r#"platform_compatible({os: "linux", arch: "x86_64", family: "unix"}, {os: "linux", arch: "x86_64", family: "unix"})"#, "true"),
(r#"platform_compatible({os: "linux", arch: "x86_64", family: "unix"}, {os: "windows", arch: "x86_64", family: "windows"})"#, "false"),
],
},
Signature {
name: "platform_db_init",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "Create the platform store if it is absent and return its path: $HOME/.ironshell/platform_db.json, or under %USERPROFILE% where HOME is unset. Writes that file.",
examples: &[(r#"(try { platform_db_init(1) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "platform_db_store",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
opt("key", Ty::Str, "the name to store under; default \"default\""),
opt("snapshot", Ty::Any, "the value to store; a fresh platform_snapshot() when absent"),
],
returns: "Bool",
doc: "Store a value (by default a fresh snapshot) under a key in the platform store. Writes the platform store; an unreadable or corrupt store is E_BAD_STATE and nothing is written.",
examples: &[
(r#"(try { platform_db_store(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { platform_db_store("k", {a: 1}, 2) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "platform_db_delete",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("key", Ty::Str, "the key to remove")],
returns: "Bool",
doc: "Remove a key from the platform store: true when it was there, false when it was not. Destructive, so refused in agent mode without approval. A corrupt store is E_BAD_STATE and is left as it was.",
examples: &[
(r#"(try { platform_db_delete() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { platform_db_delete(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "platform_db_compare",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("key1", Ty::Str, "the first stored snapshot"),
req("key2", Ty::Str, "the second stored snapshot"),
],
returns: "Record",
doc: "Diff two snapshots stored in the platform store, as platform_diff does. A key that is not stored is E_NOT_FOUND.",
examples: &[
(r#"(try { platform_db_compare("a") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { platform_db_compare(1, "b") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "platform_db_import",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("source", Ty::Str, "a JSON object as text, or the path of a file holding one")],
returns: "Int",
doc: "Merge a JSON object into the platform store and return how many keys the store holds afterwards. Writes the platform store; a corrupt store is E_BAD_STATE and is left as it was.",
examples: &[
(r#"(try { platform_db_import(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { platform_db_import("not json") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "platform_fingerprint",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "A 64-bit hash of this host's identity from its platform snapshot: OS, arch, family, hostname, kernel or Windows version, and build. Stable on one machine; tool versions, environment and the timestamp are not part of it. Not cryptographic.",
examples: &[("platform_fingerprint()", "a String: a 16-digit hexadecimal hash")],
},
Signature {
name: "platform_memory",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "This host's memory: total, free and available figures in KiB and GiB. A probe that fails is E_TOOL_FAILED; no memory total is an error, not an empty record.",
examples: &[("platform_memory()", "a Record: {total_kb, total_gb, free_kb, ...}")],
},
Signature {
name: "platform_hardware_summary",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "This host's hardware in one record: cpu, memory, disks, gpus, network, arch and os. A section that cannot be read is listed under unavailable with its reason.",
examples: &[("platform_hardware_summary()", "a Record: {cpu, memory, disks, arch, os, ...}")],
},
Signature {
name: "platform_containers",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Installed container and virtual-machine tools with their versions.",
examples: &[("typeof(platform_containers())", "Record")],
},
Signature {
name: "platform_cpu",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "CPU model and core counts.",
examples: &[("typeof(platform_cpu())", "Record")],
},
Signature {
name: "platform_cpu_count",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Int",
doc: "Logical CPUs available to this process.",
examples: &[("typeof(platform_cpu_count())", "Int")],
},
Signature {
name: "platform_cuda_version",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record | Null",
doc: "The CUDA toolkit version reported by nvcc; null where nvcc is absent.",
examples: &[(
r#"platform_cuda_version() == null || typeof(platform_cuda_version()) == "Record""#,
"true",
)],
},
Signature {
name: "platform_databases",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Installed database clients and servers with their versions.",
examples: &[("typeof(platform_databases())", "Record")],
},
Signature {
name: "platform_db_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "The names of the platform snapshots saved with platform_db_store().",
examples: &[("typeof(platform_db_list())", "Array")],
},
Signature {
name: "platform_detect_tools",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Which of a fixed set of common developer tools are on PATH.",
examples: &[("typeof(platform_detect_tools())", "Array")],
},
Signature {
name: "platform_disks",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Disks with size, free space and filesystem.",
examples: &[("typeof(platform_disks())", "Array")],
},
Signature {
name: "platform_gpu_memory",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record | Null",
doc: "GPU memory totals from nvidia-smi, summed across every NVIDIA GPU: total_mb, used_mb, free_mb, and devices (how many GPUs were summed); null without an NVIDIA GPU. A row nvidia-smi reports that is not three numbers is an error.",
examples: &[(
r#"platform_gpu_memory() == null || typeof(platform_gpu_memory()) == "Record""#,
"true",
)],
},
Signature {
name: "platform_gpus",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "GPUs from nvidia-smi with memory, driver and utilisation; empty without an NVIDIA GPU. Without nvidia-smi, Windows reports {name, memory_bytes, memory_mb, driver} from Win32_VideoController with the driver's 64-bit memory size from the registry; Linux falls back to rocm-smi, one record per AMD GPU with vendor, index, name, memory_mb, memory_free_mb, driver, temperature_c and utilization_percent, a field rocm-smi does not print being null.",
examples: &[("typeof(platform_gpus())", "Array")],
},
Signature {
name: "platform_has_admin",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Bool",
doc: "Whether the shell runs with administrator (root) rights.",
examples: &[("typeof(platform_has_admin())", "Bool")],
},
Signature {
name: "platform_has_container",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Bool",
doc: "Whether docker or podman is on PATH.",
examples: &[("typeof(platform_has_container())", "Bool")],
},
Signature {
name: "platform_has_gui",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Bool",
doc: "Whether a graphical display is available.",
examples: &[("typeof(platform_has_gui())", "Bool")],
},
Signature {
name: "platform_has_network",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Bool",
doc: "Whether a loopback socket can be bound. It does not test internet access.",
examples: &[("typeof(platform_has_network())", "Bool")],
},
Signature {
name: "platform_has_sudo",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Bool",
doc: "Whether sudo is on PATH.",
examples: &[("typeof(platform_has_sudo())", "Bool")],
},
Signature {
name: "platform_hostname",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "This machine's hostname, from the hostname command.",
examples: &[("typeof(platform_hostname())", "String")],
},
Signature {
name: "platform_iac_tools",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Installed infrastructure-as-code and orchestration tools with their versions.",
examples: &[("typeof(platform_iac_tools())", "Record")],
},
Signature {
name: "platform_kernel",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The kernel version.",
examples: &[("typeof(platform_kernel())", "String")],
},
Signature {
name: "platform_libc",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The C library in use and its version.",
examples: &[("typeof(platform_libc())", "String")],
},
Signature {
name: "platform_libs",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Common development libraries (openssl, zlib, ...) that pkg-config can find, with versions.",
examples: &[("typeof(platform_libs())", "Record")],
},
Signature {
name: "platform_line_ending",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "This platform's line ending: CRLF on Windows, LF elsewhere.",
examples: &[("typeof(platform_line_ending())", "String")],
},
Signature {
name: "platform_linters",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Installed linters and formatters with their versions.",
examples: &[("typeof(platform_linters())", "Record")],
},
Signature {
name: "platform_machine_id",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "A stable per-machine identifier from the operating system.",
examples: &[("typeof(platform_machine_id())", "String")],
},
Signature {
name: "platform_memory_total",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Int",
doc: "Total physical memory, in bytes.",
examples: &[("typeof(platform_memory_total())", "Int")],
},
Signature {
name: "platform_network_interfaces",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Network interfaces with name, MAC address and IP addresses where known.",
examples: &[("typeof(platform_network_interfaces())", "Array")],
},
Signature {
name: "platform_os_version",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The operating system's version string.",
examples: &[("typeof(platform_os_version())", "String")],
},
Signature {
name: "platform_path_sep",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "This platform's path separator: a backslash on Windows, / elsewhere.",
examples: &[("typeof(platform_path_sep())", "String")],
},
Signature {
name: "platform_pkg_lang",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Installed language package managers (pip, npm, cargo, ...) with their versions.",
examples: &[("typeof(platform_pkg_lang())", "Record")],
},
Signature {
name: "platform_pkg_managers",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Installed system package managers.",
examples: &[("typeof(platform_pkg_managers())", "Array")],
},
Signature {
name: "platform_runtimes",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Installed language runtimes with their versions.",
examples: &[("typeof(platform_runtimes())", "Record")],
},
Signature {
name: "platform_shell_type",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The shell this process was started from: bash, zsh, powershell, cmd, ...",
examples: &[("typeof(platform_shell_type())", "String")],
},
Signature {
name: "platform_system_libs",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "System library versions, such as the C library.",
examples: &[("platform_system_libs()", "a Record of the C library and toolchain versions this host has, such as {glibc, libstdc++} on Linux")],
},
Signature {
name: "platform_tool_versions",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Versions of every tool the platform_* builtins know, keyed group.tool. Probing never reaches the network.",
examples: &[("typeof(platform_tool_versions())", "Record")],
},
Signature {
name: "platform_vcs",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Installed version-control tools with their versions.",
examples: &[("typeof(platform_vcs())", "Record")],
},
Signature {
name: "plugin_categories",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "The plugin categories the plugin registry knows.",
examples: &[("typeof(plugin_categories())", "Array")],
},
Signature {
name: "pwd",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The current working directory.",
examples: &[("typeof(pwd())", "String")],
},
Signature {
name: "session_undo",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt(
"n_or_options",
Ty::Any,
"steps to undo, from 1 to 10000, default 1; or {force: Bool}",
), opt("options", Ty::Record, "{force: Bool}: put a file back even though it changed after its step (default false)")],
returns: "Record",
doc: "Put back the last n recorded file writes, most recent first; the same record as undo(n), with restored, removed, skipped, failed, steps and complete. Covers local file contents only: a network call, a process or a directory tree is reported as skipped, never restored. Journalling is on in agent mode or with IRONSHELL_JOURNAL=on. Each undone step is kept so session_redo() can re-apply it, until a new recorded write discards that redo stack (a write that is recorded and then refused still discards it). Redo is itself journaled, so session_undo() reverses it. The journal persists per session directory and is bounded to 8 MiB per file and 64 MiB in total, shared with the redo stack.",
examples: &[
(r#"let d = fs_tempdir("ae_session_undo1"); file_write(d + "/u", "a"); let r = session_undo(); rmdir(d, true); typeof(r)"#, r#"Record"#),
(r#"let d = fs_tempdir("ae_session_undo2"); file_write(d + "/u", "a"); file_write(d + "/u", "b"); let r = session_undo(2); rmdir(d, true); typeof(r)"#, r#"Record"#),
(r#"(try { session_undo(0, {force: true}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "session_redo",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt(
"n",
Ty::Int,
"undone steps to re-apply, from 1 to 10000; default 1",
)],
returns: "Record",
doc: "Re-apply the last n steps that session_undo() put back, most recently undone first. Returns reapplied, removed, skipped, failed, steps and complete, where complete is false if any step could not be re-applied. Each re-applied step is first recorded in the journal, so session_undo() reverses it. A step whose re-apply fails stays on the redo stack and stops the redo, so it can be retried. Covers local file contents only. Any new recorded write discards the redo stack (a write that is recorded and then refused still discards it), which is kept per session directory and bounded with the journal to 8 MiB per file and 64 MiB in total.",
examples: &[
(r#"typeof(session_redo())"#, r#"Record"#),
(r#"typeof(session_redo(2))"#, r#"Record"#),
],
},
Signature {
name: "session_history",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "The session's reversible history, read-only: enabled, done (the steps undo can reverse, as journal() lists them) and undone (the steps session_redo() can re-apply, most recently undone last). Journalling is on in agent mode or with IRONSHELL_JOURNAL=on, and enabled says whether it is. Covers local file contents only.",
examples: &[
(r#"typeof(session_history())"#, r#"Record"#),
(r#"typeof(session_history().done)"#, r#"Array"#),
],
},
Signature {
name: "session_end",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "End the reversible session: keep every recorded change and forget the journal and the redo stack. No files outside the journal are touched, and a journal directory that cannot be removed is E_IO. Returns kept (steps forgotten), irreversible (how many of those could not be reversed in the first place) and discarded_redo (undone steps that can no longer be re-applied). Afterwards session_undo() and session_redo() have nothing to do. Journalling is on in agent mode or with IRONSHELL_JOURNAL=on.",
examples: &[(r#"typeof(session_end())"#, r#"Record"#)],
},
Signature {
name: "session_id",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Int",
doc: "The current session counter; 0 before session_start().",
examples: &[("typeof(session_id())", "Int")],
},
Signature {
name: "sso_info",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "SSO configuration status and the number of active sessions.",
examples: &[("typeof(sso_info())", "Record")],
},
Signature {
name: "svc_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "System services with their state.",
examples: &[("typeof(svc_list())", "Array")],
},
Signature {
name: "themes",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "The available colour themes, by name.",
examples: &[("typeof(themes())", "Array")],
},
Signature {
name: "uptime",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Int",
doc: "Seconds since the machine booted.",
examples: &[("typeof(uptime())", "Int")],
},
Signature {
name: "whoami",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The name of the user this shell runs as.",
examples: &[("typeof(whoami())", "String")],
},
// Held back from the fourth tranche because their type differed by
// operating system; declared once that was fixed. `platform_ssl_version`
// was already consistent: null means no OpenSSL, as elsewhere.
Signature {
name: "platform_cpu_freq",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Float | Null",
doc: "CPU clock speed in MHz, or null where the OS reports none (Apple Silicon, many ARM and virtual CPUs).",
examples: &[(r#"platform_cpu_freq() == null || typeof(platform_cpu_freq()) == "Float""#, "true")],
},
Signature {
name: "platform_libcpp",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "The C++ standard library as {name, version, abi}, with version and abi null where the platform does not report them. Windows: name MSVC STL, version a.b.c.d from the version resource of %SystemRoot%\\System32\\msvcp140.dll (abi msvcp140); a missing runtime or unreadable version resource is a coded error. Linux: libstdc++ with its highest GLIBCXX_ version and CXXABI_ version as abi, or libc++ with both null; an existing candidate library that cannot be read is a coded error, and a library larger than 64 MiB is refused. On macOS the library lives in the dyld shared cache and is reported without a version. Reject surplus arguments and pipeline input.",
examples: &[(r#"platform_libcpp()"#, "Record")],
},
Signature {
name: "platform_ssl_version",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String | Null",
doc: "The OpenSSL version, from openssl or pkg-config; null where OpenSSL is not installed.",
examples: &[(r#"platform_ssl_version() == null || typeof(platform_ssl_version()) == "String""#, "true")],
},
// The rest of the benchmark working set (plan item 1b starts here):
// every builtin the E1/E2 corpora or the E7 prompts use is now declared.
// `each` and `echo` are in the E7 cheatsheet; `git_branch` is E2's t4.
Signature {
name: "each",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[req(
"action",
Ty::Lambda,
"fn(element) -> Any; run for its effect, result discarded",
)],
returns: "Array",
doc: "Run an action on every element for its effect and return the array unchanged. An error in the action stops the loop and is reported.",
examples: &[
("[1, 2, 3] | each(fn(x) => x * 2)", "[1, 2, 3]"),
("each([1, 2, 3], fn(x) => x)", "[1, 2, 3]"),
],
},
Signature {
name: "echo",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[Param {
name: "values",
ty: Ty::Any,
required: false,
range: None,
variadic: true,
doc: "values to print, space-separated; with none, the piped value",
}],
returns: "String",
doc: "Render values on one line, separated by spaces. With no arguments, renders the piped value.",
examples: &[
(r#"echo("a", 1, true)"#, "a 1 true"),
(r#""hello" | echo()"#, "hello"),
],
},
Signature {
name: "git_branch",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The current branch name; an empty string on a detached HEAD. Outside a repository, E_BAD_STATE.",
examples: &[("typeof(git_branch())", "String")],
},
// git_* -- the git builtins. Their examples are refusals, each raised by
// validation or by the argument checks before git is started: what a
// read-only builtin answers depends on the checkout the examples run in,
// and a mutating one must never run from a declared example.
Signature {
name: "git_status",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("path", Ty::Str, "directory inside the repository; default the working directory")],
returns: "Array",
doc: "Porcelain status of the repository containing path, as an Array of String lines; the first is the `## branch` line. Read-only. Outside a repository E_BAD_STATE; a path that is not a directory E_NOT_FOUND; a failed git E_TOOL_FAILED with the tail of its output. Refuses pipeline input.",
examples: &[
(r#"(try { git_status(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { git_status("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_diff",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("path", Ty::Str, "directory inside the repository; default the working directory")],
returns: "String",
doc: "The unstaged changes of the repository containing path, as git's patch text (empty when nothing changed). Read-only. Outside a repository E_BAD_STATE; a path that is not a directory E_NOT_FOUND; a failed git E_TOOL_FAILED. Refuses pipeline input.",
examples: &[
(r#"(try { git_diff(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { git_diff("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_diff_staged",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("path", Ty::Str, "directory inside the repository; default the working directory")],
returns: "String",
doc: "The staged changes (the index against HEAD) of the repository containing path, as git's patch text. Read-only. Outside a repository E_BAD_STATE; a path that is not a directory E_NOT_FOUND; a failed git E_TOOL_FAILED. Refuses pipeline input.",
examples: &[
(r#"(try { git_diff_staged(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { git_diff_staged("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_log",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt_range("count", Ty::Int, 1, 10000, "how many commits, newest first; default 10")],
returns: "Array",
doc: "The most recent count commits of the current repository as an Array of `<short hash> <subject>` lines, newest first. Read-only. Outside a repository E_BAD_STATE; a repository with no commits, or a failed git, E_TOOL_FAILED. Refuses pipeline input.",
examples: &[
(r#"(try { git_log(0) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { git_log("3") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_blame",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("file", Ty::Str, "path of a file in the current repository")],
returns: "String",
doc: "git blame for one file of the current repository: git's annotated text, one line per source line. Read-only. A leading '-' in the path is refused. Outside a repository E_BAD_STATE; an unknown path E_TOOL_FAILED. Refuses pipeline input.",
examples: &[
(r#"(try { git_blame() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { git_blame("--follow") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_show",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("commit", Ty::Str, "a revision; default HEAD")],
returns: "String",
doc: "git show for one commit of the current repository: the header and patch text as one String. Read-only. A leading '-' is refused. Outside a repository E_BAD_STATE; an unknown revision E_TOOL_FAILED. Refuses pipeline input.",
examples: &[
(r#"(try { git_show(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { git_show("--output=x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_rev_parse",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("rev", Ty::Str, "a revision; default HEAD")],
returns: "String",
doc: "The full object name a revision resolves to in the current repository, as a String without a trailing newline. Read-only. A leading '-' is refused. Outside a repository E_BAD_STATE; a revision that does not resolve E_TOOL_FAILED. Refuses pipeline input.",
examples: &[
(r#"(try { git_rev_parse(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { git_rev_parse("--git-dir") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_clean",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("dry_run", Ty::Bool, "true (default) lists what would be removed; false removes untracked files and directories")],
returns: "Array",
doc: "Untracked files and directories of the current repository, as the lines git printed. With dry_run true (the default) nothing is removed. With false, git clean -d -f removes them: destructive, and ignored files are kept. Outside a repository E_BAD_STATE; a failed git E_TOOL_FAILED. Refuses pipeline input.",
examples: &[
(r#"(try { git_clean("yes") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { git_clean(true, true) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_ignore",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pattern", Ty::Str, "one .gitignore pattern, without line breaks")],
returns: "Bool",
doc: "Append one pattern to the .gitignore of the working directory, creating the file if it is absent. Returns true when a line was added and false when the pattern was already there. Writes a local file. Outside a repository E_BAD_STATE; an existing .gitignore that cannot be read is a coded filesystem error and is never overwritten. Refuses pipeline input.",
examples: &[
(r#"(try { git_ignore() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { git_ignore("") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_add",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[rest("paths", Ty::Str, "one or more paths to stage; none may begin with '-'")],
returns: "Bool",
doc: "Stage the given paths in the current repository (git add -- paths) and return true. Writes the index. Each argument must be a String and none may begin with '-'. A path git does not match, or a failed git, is E_TOOL_FAILED with the tail of its output. Refuses pipeline input.",
examples: &[
(r#"(try { git_add() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { git_add("--all") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_checkout",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("branch", Ty::Str, "a branch, tag or commit name; a path is refused")],
returns: "Bool",
doc: "Switch the working tree to a branch, tag or commit (git checkout name --). The trailing -- makes the name a revision only, so a file name is an invalid reference and no file is restored over its uncommitted edits. Changes that conflict with the switch fail with E_TOOL_FAILED and git's message, and nothing is discarded. Writes the working tree. A leading '-' is refused. Refuses pipeline input.",
examples: &[
(r#"(try { git_checkout() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { git_checkout("--force") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_commit",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("message", Ty::Str, "the commit message")],
returns: "Bool",
doc: "Commit the staged changes of the current repository with message (git commit -m), running the repository's hooks, and return true. Writes the repository. Nothing staged, a missing identity or a rejecting hook fails with E_TOOL_FAILED and git's text. Refuses pipeline input.",
examples: &[
(r#"(try { git_commit() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { git_commit(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_reset",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("mode", Ty::Str, "--mixed (default), --soft, --hard or --keep, or a revision to reset to")],
returns: "Bool",
doc: "Reset HEAD of the current repository and return true. A mode is one of --soft, --mixed (the default), --hard and --keep; a revision is reset to with --mixed semantics. Any other option is refused with E_BAD_ARG. --hard discards uncommitted changes and is destructive. A failed git is E_TOOL_FAILED. Refuses pipeline input.",
examples: &[
(r#"(try { git_reset("--bogus") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { git_reset("--soft", "--hard") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_stash",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Bool",
doc: "Stash the uncommitted changes of the current repository (git stash) and return true. Removes them from the working tree until git_stash_pop. With nothing to stash, git succeeds and nothing changes. Writes the repository. Takes no arguments and refuses pipeline input; a failure is E_TOOL_FAILED with git's text.",
examples: &[
(r#"(try { git_stash("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | git_stash() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_stash_pop",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Bool",
doc: "Apply the most recent stash of the current repository and drop it (git stash pop), returning true. A conflict, or no stash entries, is E_TOOL_FAILED with git's text, and the stash is kept. Writes the working tree. Takes no arguments and refuses pipeline input.",
examples: &[
(r#"(try { git_stash_pop("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | git_stash_pop() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_fetch",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Bool",
doc: "Download objects and refs from the default remote of the current repository (git fetch) and return true. Network. No remote, or an unreachable one, is E_TOOL_FAILED with git's text. Takes no arguments and refuses pipeline input.",
examples: &[
(r#"(try { git_fetch("--upload-pack=x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | git_fetch() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_pull",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Bool",
doc: "Fetch and integrate the upstream branch of the current repository (git pull) and return true. Network, and it may merge or rebase what it fetched. Divergent history without a reconciliation setting, or a conflict, is E_TOOL_FAILED with git's text. Takes no arguments and refuses pipeline input.",
examples: &[
(r#"(try { git_pull("--rebase") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | git_pull() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_push",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Bool",
doc: "Push the current branch of the current repository to its upstream (git push) and return true. Network. A rejected push, or no upstream, is E_TOOL_FAILED with git's text. Takes no arguments and refuses pipeline input.",
examples: &[
(r#"(try { git_push("--force") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | git_push() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_merge",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("branch", Ty::Str, "the branch to merge into the current one")],
returns: "Bool",
doc: "Merge the named branch into the current one (git merge --no-edit) and return true. Writes the repository and runs its hooks. A conflict or refusal is E_TOOL_FAILED with git's text, and the merge is left for the user to resolve or abort. A leading '-' is refused. Refuses pipeline input.",
examples: &[
(r#"(try { git_merge() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { git_merge("--abort") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_rebase",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("branch", Ty::Str, "the branch to rebase the current one onto")],
returns: "Bool",
doc: "Rebase the current branch onto the named one (git rebase) and return true. Writes the repository and runs its hooks. A conflict is E_TOOL_FAILED with git's text and leaves the rebase in progress. A leading '-' is refused. Refuses pipeline input.",
examples: &[
(r#"(try { git_rebase() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { git_rebase("--root") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "git_cherry_pick",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("commit", Ty::Str, "the commit to apply to the current branch")],
returns: "Bool",
doc: "Apply the named commit onto the current branch (git cherry-pick) and return true. Writes the repository and runs its hooks. A conflict is E_TOOL_FAILED with git's text and leaves the pick in progress. A leading '-' is refused. Refuses pipeline input.",
examples: &[
(r#"(try { git_cherry_pick() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { git_cherry_pick("--continue") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
// Plan item 1b, first tranche of parameter-taking builtins: pure data
// functions from the discarded-args list, each body read for its
// parameters, each example measured before it was written.
Signature {
name: "crypto_hex_encode",
category: None,
subject_required: false,
aliases: &["hex_encode"],
subject: Some(Ty::Str),
params: &[],
returns: "String",
doc: "The bytes of a string as lowercase hex.",
examples: &[
(r#"crypto_hex_encode("hi")"#, r#"6869"#),
(r#""hi" | crypto_hex_encode()"#, r#"6869"#),
],
},
Signature {
name: "crypto_hex_decode",
category: None,
subject_required: false,
aliases: &["hex_decode"],
subject: Some(Ty::Str),
params: &[],
returns: "String",
doc: "Decode hex digit pairs to a string. Odd length or a non-hex digit is refused, and so are bytes that are not UTF-8 text (E_BAD_ARG: these bytes are binary).",
examples: &[
(r#"crypto_hex_decode("6869")"#, r#"hi"#),
(r#"(try { crypto_hex_decode("ff00fe") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "digest",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[],
returns: "Record",
doc: "A constant-size summary of a value: kind, size, element shape, a two-element sample and its token cost.",
examples: &[
(r#"digest([1, 2, 3]).len"#, r#"3"#),
],
},
Signature {
name: "direnv_allow",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("path", Ty::Str, "a directory holding an .envrc, or an .envrc file; inside the workspace; defaults to the process's directory")],
returns: "Record",
doc: "direnv allow <path>: authorises the .envrc so direnv loads it, answering {path, exit_code, success, stdout, stderr}. Allowing an .envrc lets its code run on every cd into that directory. The effect is Exec, so agent mode asks for approval. The path must exist and lie inside the workspace; a missing path is E_NOT_FOUND. Takes no pipeline input.",
examples: &[
(r#"(try { direnv_allow("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { direnv_allow(["x"]) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { direnv_allow("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | direnv_allow() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "direnv_status",
category: None,
subject_required: false,
aliases: &["direnv"],
subject: None,
params: &[],
returns: "Record",
doc: "direnv status: direnv's report on the process's directory, answered as {status, success}. A failure is E_TOOL_FAILED. Takes no arguments and no pipeline input.",
examples: &[
(r#"(try { direnv_status("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | direnv_status() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "json_stringify",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[opt_range("indent", Ty::Int, 0, 8, "spaces per nesting level, 0 to 8; 0 is compact")],
returns: "String",
doc: "A value as JSON: compact, or indented by 1 to 8 spaces per level with an indent argument (0 is compact). The value is piped in or passed as the argument: json_stringify(v, indent).",
examples: &[
(r#"json_stringify({a: 1})"#, r#"{"a":1}"#),
(r#"json_stringify({a: 1}, 2) | lines | len"#, "3"),
(r#"json_stringify({a: 1}, 0)"#, r#"{"a":1}"#),
],
},
Signature {
// Edits one key of a JSON file in place. Its effect is file_write's: the
// path is guarded and the write is atomic, and the key order and
// indentation of the file are kept.
name: "json_set",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("path", Ty::Str, "the JSON file to edit; it must exist"),
req("key_path", Ty::Str, "dot-separated keys, such as version or a.b.c or items.0.name; a missing object key is created, an array index must exist"),
req("value", Ty::Any, "the value to set at key_path, as JSON"),
],
returns: "Record",
doc: "Set one key of a JSON file and write it back in place. The file keeps its key order and its indentation (a tab, two or four spaces, or compact). A path that would create a key inside a value that is not an object is E_BAD_ARG, naming the path.",
examples: &[
(r#"let d = fs_tempdir("ae_jsonset"); let f = d + "/c.json"; file_write(f, "{\n \"version\": \"1\"\n}\n"); json_set(f, "version", "2"); let v = open(f).version; rmdir(d, true); v"#, r#""2""#),
(r#"let d = fs_tempdir("ae_jsonset"); let f = d + "/c.json"; file_write(f, "{\"a\": {}}"); json_set(f, "a.b", 2); let v = open(f).a.b; rmdir(d, true); v"#, "2"),
],
},
Signature {
// The position of each element, for the loops that IronShell does not have.
name: "enumerate",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Array),
params: &[],
returns: "Array",
doc: "Each element of an Array with its position: an Array of {index, value} records, counted from 0. The Array is piped in or passed as the argument: enumerate(items).",
examples: &[
(r#"["a", "b"] | enumerate | last | fn(r) => r.index"#, "1"),
(r#"enumerate(["a", "b"]) | last | fn(r) => r.value"#, r#""b""#),
],
},
Signature {
name: "just_run",
category: None,
subject_required: false,
aliases: &["just"],
subject: None,
params: &[
req("recipe", Ty::Str, "a recipe in the justfile of the process's directory; one word, not starting with '-'"),
opt_rest("args", Ty::Str, "recipe arguments, each one word not starting with '-'"),
],
returns: "Record",
doc: "just <recipe> <args...> in the process's directory, answering {recipe, exit_code, stdout, stderr}. A recipe runs project code, so its effect is exec and the central gate asks for approval in agent mode. Output keeps its last 256 KiB. At most 256 arguments are passed. A nonzero exit is E_TOOL_FAILED with the stderr tail, and the deadline is 15 minutes. Takes no pipeline input.",
examples: &[
(r#"(try { just_run("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { just_run("build", "-v") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { just_run() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | just_run("build") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "just_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "just --list in the process's directory: an Array of {name, description?} Records, one per recipe. A missing justfile or any other failure is E_TOOL_FAILED, never a string. Takes no arguments and no pipeline input.",
examples: &[
(r#"(try { just_list("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | just_list() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "type_name",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[],
returns: "String",
doc: "A detailed type description, with element and field types.",
examples: &[
(r#"type_name([1, 2])"#, r#"Array<Int>"#),
],
},
Signature {
name: "type_schema",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[],
returns: "Record",
doc: "A JSON Schema describing a value's structure.",
examples: &[
(r#"type_schema({a: 1}).type"#, r#"object"#),
],
},
Signature {
name: "is_error",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[],
returns: "Bool",
doc: "Whether a value is an Error.",
examples: &[
(r#"is_error(42)"#, r#"false"#),
],
},
Signature {
name: "canonical",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[],
returns: "String",
doc: "Canonical JSON: sorted keys and shortest round-trip floats, byte-identical for equal values on every OS.",
examples: &[
(r#"canonical({b: 1, a: 2})"#, r#"{"a":2,"b":1}"#),
],
},
Signature {
name: "aecon",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[],
returns: "String",
doc: "A value as compact AECON text, which states the keys of a homogeneous record array once.",
examples: &[
(r#"typeof(aecon([{a: 1}, {a: 2}]))"#, r#"String"#),
],
},
Signature {
name: "aecon_decode",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "Array",
doc: "Parse tabular AECON text back into an array of records; the inverse of aecon.",
examples: &[
(r#"aecon_decode(aecon([{a: 1}, {a: 2}])) | len"#, r#"2"#),
],
},
Signature {
name: "tokens",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[],
returns: "Int",
doc: "An estimate of the tokens in a value's rendered form.",
examples: &[
(r#"tokens("hello world")"#, r#"4"#),
],
},
Signature {
name: "platform_hash",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("value", Ty::Any, "value to fingerprint")],
returns: "String",
doc: "A short hex fingerprint of a value's structure.",
examples: &[
(r#"typeof(platform_hash("x"))"#, r#"String"#),
],
},
Signature {
name: "platform_normalize_output",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("text", Ty::Str, "text with any line endings")],
returns: "String",
doc: "Convert CRLF and CR line endings to LF.",
examples: &[
(r#"platform_normalize_output("a\r\nb") | len"#, r#"3"#),
],
},
Signature {
name: "platform_normalize_path",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a path with either separator")],
returns: "String",
doc: "Convert backslash separators to forward slashes.",
examples: &[
(r#"platform_normalize_path("src/main.rs")"#, r#"src/main.rs"#),
],
},
Signature {
name: "code_language",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a file path; only its extension is read")],
returns: "String",
doc: "The programming language a file's extension indicates.",
examples: &[
(r#"code_language("main.rs")"#, r#"rust"#),
],
},
Signature {
name: "inspect",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[],
returns: "Record",
doc: "A value's type, size and contents, as a record.",
examples: &[
(r#"inspect([1, 2]).type"#, r#"Array"#),
],
},
Signature {
name: "debug",
category: None,
subject_required: false,
aliases: &["dbg"],
subject: Some(Ty::Any),
params: &[],
returns: "Any",
doc: "Print a value and its type to stderr and return it unchanged, for use mid-pipeline.",
examples: &[
(r#"debug(42)"#, r#"42"#),
],
},
Signature {
name: "deno_run",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("script", Ty::Str, "a script path inside the workspace; remote modules are refused")],
returns: "Record",
doc: "Runs `deno run --no-prompt <script>` with no shell. No permission is granted: a script that needs file, network or environment access fails with E_TOOL_FAILED instead of being given it. Returns {exit_code: 0, success: true, stdout, stderr}. Deadline 10 minutes; a missing deno is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | deno_run("a.ts") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { deno_run("https://example.com/a.ts") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "deno_task",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("task", Ty::Str, "a task name from deno.json; a leading '-' is refused")],
returns: "Record",
doc: "Runs `deno task <task>` with no shell. Returns {task, exit_code: 0, success: true, stdout, stderr}; a nonzero exit is E_TOOL_FAILED with the tail of the output. Deadline 10 minutes; a missing deno is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | deno_task("build") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { deno_task("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ontology_describe",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("name", Ty::Str, "a category or builtin name")],
returns: "Record",
doc: "A category's builtins, or one builtin's full definition. A name that is neither is E_UNKNOWN_BUILTIN, with the nearest names as did_you_mean.",
examples: &[
(r#"typeof(ontology_describe("Array"))"#, r#"Record"#),
],
},
Signature {
name: "feature_enabled",
category: None,
subject_required: false,
aliases: &["has_feature"],
subject: Some(Ty::Str),
params: &[],
returns: "Bool",
doc: "Whether a runtime feature flag is enabled.",
examples: &[
(r#"feature_enabled("definitely_not_a_feature")"#, r#"false"#),
(r#""definitely_not_a_feature" | has_feature()"#, r#"false"#),
],
},
Signature {
name: "error",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
opt("message", Ty::Str, "the message the caught error carries, as given; omitted, it is the pipeline input"),
opt("extra", Ty::Record, "fields added to the caught error record, such as {field: \"age\"}; code, message, retryable, builtin, error, did_you_mean and approval cannot be set; hint replaces the default hint, and expected and got are shown"),
],
returns: "Null",
doc: "Raise an error the script chose. It is E_USER with the message as given, and it does not return. A Record extra adds its fields to the caught error, so a script can name the bad field without parsing the message. Catch it with try/catch; uncaught, the script stops with a non-zero status. With no argument it takes the message from pipeline input.",
examples: &[
(r#"try { error("boom") } catch e { e.message }"#, "boom"),
(r#"try { error("bad", {field: "age"}) } catch e { e.field }"#, "age"),
(r#"try { error("bad") } catch e { e.code }"#, "E_USER"),
],
},
Signature {
name: "args",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "The arguments the running script was given: `ish script.ish a b` gives [\"a\", \"b\"]. Empty when there are none, and always under -c, stdin and the REPL.",
examples: &[("len(args())", "0")],
},
Signature {
name: "int",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[],
returns: "Int",
doc: "Convert a value to an Int. An Int is returned as it is, a Bool is 1 or 0, and a Float is truncated toward zero; NaN, infinity and a Float outside the Int range are refused. A String is parsed as a whole number, with surrounding whitespace and an optional sign allowed. \"1.5\", \"abc\" and \"\" are refused, and the refusal names the text.",
examples: &[
(r#"int("42") + 1"#, "43"),
(r#"int(3.9)"#, "3"),
(r#"int(true)"#, "1"),
],
},
Signature {
name: "float",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[],
returns: "Float",
doc: "Convert a value to a Float. An Int is widened, and a String is parsed as a decimal, with exponents such as \"1e3\" allowed. Text that is not a finite number, such as \"abc\", \"\" or \"inf\", is refused and the refusal names the text.",
examples: &[
(r#"float("1e3") == 1000.0"#, "true"),
(r#"float(2) == 2.0"#, "true"),
],
},
Signature {
name: "now_iso",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("zone", Ty::Str, "\"utc\" (the default) or \"local\", the local time with its UTC offset")],
returns: "String",
doc: "The current time as an ISO 8601 / RFC 3339 String, to the second. In UTC it ends in Z, such as 2026-11-08T14:03:05Z; with \"local\" it is the local time with its offset, such as 2026-11-08T06:03:05-08:00.",
examples: &[
("len(now_iso()) > 18", "true"),
(r#"len(now_iso("local")) > 18"#, "true"),
],
},
Signature {
name: "regex_match",
category: Some("String"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[req("pattern", Ty::Str, "a Rust regex pattern")],
returns: "Bool",
doc: "Whether a Rust regex matches anywhere in a String, direct as regex_match(text, pattern) or piped as text | regex_match(pattern). An invalid pattern, or one over the size cap, is E_BAD_ARG and the refusal names the pattern and the regex error.",
examples: &[
(r#""abc" | regex_match("b")"#, "true"),
(r#"regex_match("abc", "^b")"#, "false"),
(r#"(try { regex_match("abc", "(") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "regex_find",
category: Some("String"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[req("pattern", Ty::Str, "a Rust regex pattern")],
returns: "Record|Null",
doc: "The first match of a Rust regex in a String, as a Record {match, groups, named, start, end}, or null when nothing matches. groups is an Array of the capture groups as Strings, null for a group that did not take part. named is a Record of the named groups (?P<name>...) as Strings, null for a group that did not take part, and an empty Record when the pattern names no group. start and end are character offsets, end exclusive. An invalid pattern, or one over the size cap (compiled patterns are limited to 1 MiB), is E_BAD_ARG. Direct regex_find(text, pattern) or text | regex_find(pattern).",
examples: &[
(r#"regex_find("a1b22", "[0-9]+").start"#, "1"),
(r#"regex_find("ab", "b").end"#, "2"),
(r#"regex_find("2024-02", "(?P<y>[0-9]+)-(?P<m>[0-9]+)").named.m"#, r#""02""#),
(r#"regex_find("abc", "z")"#, "null"),
],
},
Signature {
name: "regex_find_all",
category: Some("String"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[req("pattern", Ty::Str, "a Rust regex pattern")],
returns: "Array",
doc: "Every match of a Rust regex in a String, left to right, as an Array of the records regex_find returns, each with match, groups, named, start and end. An empty Array when nothing matches. An invalid pattern, or one over the size cap (compiled patterns are limited to 1 MiB), is E_BAD_ARG. Direct regex_find_all(text, pattern) or text | regex_find_all(pattern).",
examples: &[
(r#"regex_find_all("a1b22", "[0-9]+") | len"#, "2"),
(r#"regex_find_all("abc", "z") | len"#, "0"),
],
},
Signature {
name: "regex_split",
category: Some("String"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[req("pattern", Ty::Str, "a Rust regex pattern")],
returns: "Array",
doc: "Split a String at every match of a Rust regex, as an Array of String (Rust regex split semantics: a match at the start or end gives an empty piece there, and text with no match is one piece). An invalid pattern is E_BAD_ARG. Direct regex_split(text, pattern) or text | regex_split(pattern).",
examples: &[
(r#"regex_split("a1b22c", "[0-9]+")"#, r#"["a", "b", "c"]"#),
(r#""a, b;c" | regex_split("[,;] *")"#, r#"["a", "b", "c"]"#),
(r#"regex_split("abc", "z")"#, r#"["abc"]"#),
],
},
Signature {
name: "index_of",
category: Some("String"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[req("sub", Ty::Str, "the text to look for")],
returns: "Int",
doc: "The character offset (not the byte offset, as regex_find's start) of the first occurrence of sub in a String, or -1 when absent. An empty sub is found at 0. Direct index_of(text, sub) or text | index_of(sub).",
examples: &[
(r#"index_of("hello", "l")"#, "2"),
(r#"index_of("héllo", "l")"#, "2"),
(r#""hello" | index_of("z")"#, "-1"),
],
},
Signature {
name: "last_index_of",
category: Some("String"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[req("sub", Ty::Str, "the text to look for")],
returns: "Int",
doc: "The character offset (not the byte offset) of the last occurrence of sub in a String, or -1 when absent. Direct last_index_of(text, sub) or text | last_index_of(sub).",
examples: &[
(r#"last_index_of("hello", "l")"#, "3"),
(r#"last_index_of("héllo", "o")"#, "4"),
(r#""hello" | last_index_of("z")"#, "-1"),
],
},
Signature {
name: "regex_replace",
category: Some("String"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[req("pattern", Ty::Str, "a Rust regex pattern"), req("replacement", Ty::Str, "replacement text; $1, $name and $$ expand as the regex crate expands them; write a named group as \\${name}, since ${name} interpolates")],
returns: "String",
doc: "Replace every match of a Rust regex in a String. The replacement expands $1, $name, ${name} and $$ as the regex crate does. In a double-quoted string ${name} is interpolation, so write \\${name} to pass ${name} to the regex: regex_replace(\"2024-02\", \"(?P<y>[0-9]+)-(?P<m>[0-9]+)\", \"\\${m}/\\${y}\") is \"02/2024\". An invalid pattern, or one over the size cap (compiled patterns are limited to 1 MiB), is E_BAD_ARG. A replacement that refers to a group the pattern does not have, such as $5 or $1x, is E_BAD_ARG too, and its hint says how to write it: ${1}x is group 1 followed by x. Direct regex_replace(text, pattern, replacement) or text | regex_replace(pattern, replacement).",
examples: &[
(r#"regex_replace("a1b2", "([0-9])", "<$1>")"#, r#""a<1>b<2>""#),
(r##""a1" | regex_replace("[0-9]", "#")"##, r#""a#""#),
(r#"regex_replace("2024-02", "(?P<y>[0-9]+)-(?P<m>[0-9]+)", "\${m}/\${y}")"#, r#""02/2024""#),
(r#"(try { regex_replace("a1", "([0-9])", "<$5>") } catch e { e.error.code })"#, r#""E_BAD_ARG""#),
],
},
Signature {
name: "pad_left",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[req("width", Ty::Int, "the width in characters, 0 or more"), opt("fill", Ty::Str, "one character to pad with; \" \" by default")],
returns: "String",
doc: "Pad a String on the left to a width in characters, with one fill character (a space by default). A text already at or over the width is returned unchanged. A fill that is not exactly one character, or a width over 1000000, is E_BAD_ARG.",
examples: &[
(r#"pad_left("7", 3, "0")"#, r#""007""#),
(r#""7" | pad_left(3)"#, r#"" 7""#),
(r#"pad_left("abcd", 2)"#, r#""abcd""#),
],
},
Signature {
name: "pad_right",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[req("width", Ty::Int, "the width in characters, 0 or more"), opt("fill", Ty::Str, "one character to pad with; \" \" by default")],
returns: "String",
doc: "Pad a String on the right to a width in characters, with one fill character (a space by default). A text already at or over the width is returned unchanged. A fill that is not exactly one character, or a width over 1000000, is E_BAD_ARG.",
examples: &[
(r#"pad_right("ab", 4, ".")"#, r#""ab..""#),
(r#""ab" | pad_right(4)"#, r#""ab ""#),
],
},
Signature {
name: "date_parse",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[opt("format", Ty::Str, "a chrono strftime layout; RFC 3339 and YYYY-MM-DD are read without one")],
returns: "String",
doc: "Read a date or datetime and answer it as ISO 8601 in UTC: a date as YYYY-MM-DD, a datetime as 2024-02-29T10:00:00Z, with any offset in the text converted. Seconds may be left out (13:05 is 13:05:00), the date and time may be in the basic form (20240229T130509Z), the separator may be T, t or a space, and an offset may be Z, +05:30, +0530 or -08. Text that is not a date is E_BAD_VALUE, and the refusal names it; a field that is short (2024-2-9) is E_BAD_ARG. date_add, date_diff and date_format read the same forms.",
examples: &[
(r#"date_parse("2024-02-29T13:05")"#, r#""2024-02-29T13:05:00Z""#),
(r#"date_parse("20240229T130509+0530")"#, r#""2024-02-29T07:35:09Z""#),
(r#"date_parse("20240229")"#, r#""2024-02-29""#),
(r#"date_parse("2024-02-29")"#, r#""2024-02-29""#),
(r#"date_parse("2024-02-29T10:00:00+02:00")"#, r#""2024-02-29T08:00:00Z""#),
(r#"date_parse("29/02/2024", "%d/%m/%Y")"#, r#""2024-02-29""#),
(r#"(try { date_parse("someday") } catch e { e.error.code })"#, "E_BAD_VALUE"),
],
},
Signature {
name: "date_diff",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[req("b", Ty::Str, "the second ISO date or datetime; the answer is b minus a, so an earlier b is negative"), opt("unit", Ty::Str, "days (the default: whole 24-hour periods), weeks, months, years, hours, minutes or seconds; any case, and the singular, is accepted")],
returns: "Int",
doc: "The time from the first date a to the second date b: the answer is b minus a, as a count of whole units truncated toward zero, so the sign is kept. date_diff(a, b) with a before b is positive, and with b before a it is negative: date_diff(\"2026-11-09\", \"2024-02-29\") is -984. The default unit, days, counts whole 24-hour periods of elapsed time: a partial day is dropped, so 23:00 to 01:00 the next day is 0 days. Weeks, hours, minutes and seconds count whole elapsed units. Months and years are calendar units, the inverse of date_add: the most whole months n for which date_add(a, n, \"months\") does not pass b, so 2024-01-31 to 2024-02-29 is 1 month and 2024-02-29 to 2025-02-28 is 1 year. Dates are ISO strings as date_parse answers them; a date alone is midnight UTC, so two dates count calendar days. A unit is read in any case and in the singular (\"DAY\", \"week\"); a bad unit is E_BAD_ARG. Direct date_diff(a, b, unit?) or text | date_diff(b, unit?).",
examples: &[
(r#"date_diff("2024-02-29", "2026-11-09")"#, "984"),
(r#"date_diff("2024-02-29", "2024-03-02", "DAY")"#, "2"),
(r#"date_diff("2026-11-09", "2024-02-29")"#, "-984"),
(r#"date_diff("2024-02-29", "2026-11-09", "hours")"#, "23616"),
(r#"date_diff("2024-01-31", "2024-02-29", "months")"#, "1"),
(r#"date_diff("2024-02-29", "2025-02-28", "years")"#, "1"),
(r#"date_diff("2024-03-15", "2024-01-20", "months")"#, "-1"),
(r#""2024-02-29" | date_diff("2024-03-01")"#, "1"),
(r#"date_diff("2026-11-01T23:00:00Z", "2026-11-02T01:00:00Z")"#, "0"),
(r#"date_diff("2026-11-01T23:00:00Z", "2026-11-02T01:00:00Z", "hours")"#, "2"),
],
},
Signature {
name: "date_format",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[req("format", Ty::Str, "a chrono strftime layout, such as %d %B %Y")],
returns: "String",
doc: "Format an ISO date or datetime with a chrono strftime layout. A date alone is midnight UTC. A layout chrono cannot read is E_BAD_ARG, and the refusal names the first specifier it cannot read (%^a, %#b, %10Y and %L are not supported). %f is the nanoseconds (nine digits); %6f or %.6f gives the microseconds, %3f or %.3f the milliseconds.",
examples: &[
(r#"date_format("2024-02-29T10:00:00Z", "%d %B %Y")"#, r#""29 February 2024""#),
(r#"date_format("2024-02-29T10:00:00.123456789Z", "%f")"#, r#""123456789""#),
(r#"date_format("2024-02-29T10:00:00.123456789Z", "%6f")"#, r#""123456""#),
(r#"date_format("2024-02-29T10:00:00Z", "%H:%M")"#, r#""10:00""#),
(r#""2024-02-29" | date_format("%A")"#, r#""Thursday""#),
],
},
Signature {
name: "date_add",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[req("amount", Ty::Int, "whole units; may be negative"), req("unit", Ty::Str, "weeks, days, months, years, hours, minutes or seconds; any case, and the singular, is accepted")],
returns: "String",
doc: "Move an ISO date or datetime by a whole amount of weeks, days, months, years, hours, minutes or seconds. Months and years are calendar units: the day of the month is kept, or clamped to the last day of the month it lands in, so 2024-01-31 plus one month is 2024-02-29 and 2024-02-29 plus one year is 2025-02-28. The time of day is kept. A date with the unit weeks, days, months or years is answered as a date; otherwise the answer is a UTC datetime ending in Z. A unit is read in any case and in the singular, so \"Day\" and \"week\" are accepted; a bad unit is E_BAD_ARG.",
examples: &[
(r#"date_add("2024-02-28", 1, "days")"#, r#""2024-02-29""#),
(r#"date_add("2024-01-01", 1, "DAY")"#, r#""2024-01-02""#),
(r#"date_add("2024-02-28", 1, "weeks")"#, r#""2024-03-06""#),
(r#"date_add("2024-01-31", 1, "months")"#, r#""2024-02-29""#),
(r#"date_add("2024-03-31", -1, "months")"#, r#""2024-02-29""#),
(r#"date_add("2024-02-29", 1, "years")"#, r#""2025-02-28""#),
(r#"date_add("2024-02-28T23:00:00Z", 2, "hours")"#, r#""2024-02-29T01:00:00Z""#),
],
},
Signature {
name: "to_toml",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[],
returns: "String",
doc: "Write a Record as a TOML document. The top level must be a Record. A null, or a value TOML has no form for, is E_BAD_ARG and the refusal names its path, such as app.servers[1].note.",
examples: &[
(r#"from_toml(to_toml({a: 1, b: "x"})).b"#, r#""x""#),
(r#"(try { to_toml([1]) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { to_toml({a: from_json("null")}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "from_toml",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "Record",
doc: "Read a TOML document as a Record. Datetimes come back as their text. Text that is not TOML is E_BAD_VALUE, and the refusal says why.",
examples: &[
(r#"from_toml("a = 1").a"#, "1"),
(r#"(try { from_toml("a = ") } catch e { e.error.code })"#, "E_BAD_VALUE"),
(r#"(try { from_toml("n = 9223372036854775808") } catch e { e.error.code })"#, "E_BAD_VALUE"),
],
},
Signature {
name: "merge",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Record),
params: &[req("b", Ty::Record, "the Record whose fields win")],
returns: "Record",
doc: "Shallow-merge two Records; a field both have takes b's value whole, and a nested Record is replaced, not merged. A non-Record argument is E_BAD_ARG.",
examples: &[
(r#"merge({a: 1, b: 2}, {b: 3}).b"#, "3"),
(r#"(try { merge({a: 1}, 2) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "format_number",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Numeric),
params: &[
req("decimals", Ty::Int, "digits after the point, 0 to 15; 0 writes no point"),
opt("separator", Ty::Str, "groups the integer part, such as \",\""),
],
returns: "String",
doc: "Format an Int or Float with exactly decimals digits after the point, rounded half away from zero. With a separator the integer part is grouped in threes. A negative number keeps its sign unless it rounds to zero.",
examples: &[
(r#"format_number(1234567.891, 2, ",")"#, r#""1,234,567.89""#),
(r#"format_number(1000, 2)"#, r#""1000.00""#),
(r#"format_number(-0.5, 0)"#, r#""-1""#),
],
},
Signature {
name: "path_join",
category: Some("FileSystem"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Sequence),
params: &[opt_rest("part", Ty::Sequence, "a path, or an Array of paths; a part with a root replaces the parts before it")],
returns: "String",
doc: "Join path parts with / as os.path.join does, on every platform. Text only: the disk is not read. Backslashes in the parts become /.",
examples: &[
(r#"path_join("a", "b")"#, r#""a/b""#),
(r#"path_join("a", "/etc", "b")"#, r#""/etc/b""#),
(r#"path_join(["data", "c.txt"])"#, r#""data/c.txt""#),
],
},
Signature {
name: "path_basename",
category: Some("FileSystem"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "String",
doc: "The last component of a path, with / separators on every platform. A trailing separator is ignored, so a/b/ is b; a path with no component (/, \"\") is \"\". Text only.",
examples: &[
(r#"path_basename("a/b/c.txt")"#, r#""c.txt""#),
(r#"path_basename("C:\\a\\b.txt")"#, r#""b.txt""#),
(r#"path_basename("a/b/")"#, r#""b""#),
],
},
Signature {
name: "path_dirname",
category: Some("FileSystem"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "String",
doc: "Everything above the last component of a path. A relative path with one component has the directory \".\"; the parent of a root is the root. Text only.",
examples: &[
(r#"path_dirname("a/b/c.txt")"#, r#""a/b""#),
(r#"path_dirname("c.txt")"#, r#"".""#),
(r#"path_dirname("/a")"#, r#""/""#),
],
},
Signature {
name: "path_extension",
category: Some("FileSystem"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "String",
doc: "The suffix of the last component, with its dot; \"\" when there is none. Only the last dot counts, and a dot at the start or end of the name is not a suffix. Text only.",
examples: &[
(r#"path_extension("archive.tar.gz")"#, r#"".gz""#),
(r#"path_extension(".bashrc")"#, r#""""#),
],
},
Signature {
name: "path_stem",
category: Some("FileSystem"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "String",
doc: "The last component of a path without its suffix. Text only.",
examples: &[
(r#"path_stem("c.txt")"#, r#""c""#),
(r#"path_stem("archive.tar.gz")"#, r#""archive.tar""#),
],
},
Signature {
name: "path_normalize",
category: Some("FileSystem"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "String",
doc: "Remove . parts, repeated separators and name/.. pairs, with / separators on every platform. Lexical: the disk is never read. A relative path keeps the .. it cannot resolve; an empty result is \".\".",
examples: &[
(r#"path_normalize("a/./b/../c//d/")"#, r#""a/c/d""#),
(r#"path_normalize("../x/../../y")"#, r#""../../y""#),
(r#"path_normalize("/../a")"#, r#""/a""#),
],
},
Signature {
name: "path_is_absolute",
category: Some("FileSystem"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "Bool",
doc: "Whether a path has a root: a leading separator, or a drive and a separator such as C:\\. Nothing is checked on the disk.",
examples: &[
(r#"path_is_absolute("/etc")"#, r#"true"#),
(r#"path_is_absolute("C:\\x")"#, r#"true"#),
(r#"path_is_absolute("a/b")"#, r#"false"#),
],
},
Signature {
name: "path_split",
category: Some("FileSystem"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "Array",
doc: "The components of a path as an Array of Strings, root first when there is one (/ or C:/). Empty and . parts are dropped; .. is kept. Text only.",
examples: &[
(r#"path_split("a/b/c.txt")"#, r#"["a", "b", "c.txt"]"#),
(r#"path_split("/a/b")"#, r#"["/", "a", "b"]"#),
],
},
Signature {
name: "url_encode",
category: Some("String"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "String",
doc: "Percent-encode text as RFC 3986 does: the UTF-8 bytes of every character except A-Z a-z 0-9 - . _ ~ become %XX (upper-case hex), so a space is %20 and / is %2F. Pure; the subject may be piped in.",
examples: &[
(r#"url_encode("a b/c")"#, r#"a%20b%2Fc"#),
(r#"("a&b=c" | url_encode)"#, r#"a%26b%3Dc"#),
],
},
Signature {
name: "url_decode",
category: Some("String"),
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "String",
doc: "Undo url_encode: each %XX becomes its byte, and the bytes are read as UTF-8. A % without two hex digits after it, or a result that is not UTF-8, is E_BAD_ARG. A + stays a + (it is not turned into a space; that is form encoding, not RFC 3986). Pure; the subject may be piped in.",
examples: &[
(r#"url_decode("a%20b%2Fc")"#, r#"a b/c"#),
(r#"("100%25" | url_decode)"#, r#"100%"#),
(r#"(try { url_decode("%zz") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "assert",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[
opt("condition", Ty::Any, "the condition, when it is not piped in: a falsy value (false, 0, null, \"\", [], {}) fails"),
opt("message", Ty::Str, "the reason, shown as \"assertion failed: message\"; default \"assertion failed\""),
],
returns: "Bool",
doc: "Return true when the condition is truthy. When it is falsy, raise E_ASSERT with the message as \"assertion failed: message\" (or \"assertion failed\" alone), so try { } catch e { e.code } and e.message work. Piped, the condition is the piped value and the only argument is the message.",
examples: &[
(r#"assert(1 == 1)"#, r#"true"#),
(r#"assert(true, "never shown")"#, r#"true"#),
(r#"true | assert("never shown")"#, r#"true"#),
(r#"(try { assert(false, "x must be positive") } catch e { e.code })"#, "E_ASSERT"),
(r#"(try { assert(false, "x must be positive") } catch e { e.message })"#, "assertion failed: x must be positive"),
],
},
Signature {
name: "asdf_list",
category: None,
subject_required: false,
aliases: &["asdf"],
subject: None,
params: &[opt("plugin", Ty::Str, "a plugin's name; omitted lists every plugin's installed versions")],
returns: "Array",
doc: "asdf list [plugin]: installed versions as an Array of Strings. An unknown plugin or any other failure is E_TOOL_FAILED, never a string. Takes no pipeline input.",
examples: &[
(r#"(try { asdf_list("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { asdf_list("nodejs", "x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | asdf_list() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "asdf_install",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("plugin", Ty::Str, "the plugin to install from; one word, not starting with '-'"),
opt("version", Ty::Str, "the version to install; defaults to latest; one word, not starting with '-'"),
],
returns: "Record",
doc: "asdf install <plugin> <version>, answering {plugin, version, exit_code, success, stdout, stderr}. The install goes into asdf's own directory, outside the workspace, and fetches and runs the plugin's code over the network. Its effect is exec, so the central gate asks for approval in agent mode. A nonzero exit is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { asdf_install("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { asdf_install() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { asdf_install("nodejs", "-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | asdf_install("nodejs") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "handle_drop",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("id", Ty::Str, "a handle id from handles()")],
returns: "Bool",
doc: "Release a result handle, reporting whether it existed.",
examples: &[
(r#"handle_drop("no-such-handle")"#, r#"false"#),
],
},
// 1b: builtins over in-process registries. Keys are declared Any because
// the bodies take a String or an integer id through key_arg, which
// refuses anything else; Ty has no union for that.
Signature {
name: "user_roles",
category: None,
subject_required: false,
aliases: &["get_roles"],
subject: Some(Ty::Any),
params: &[],
returns: "Array",
doc: "The roles assigned to a user; empty for a user with none.",
examples: &[
(r#"user_roles("nobody-with-this-name")"#, r#"[]"#),
],
},
Signature {
name: "role_create",
category: None,
subject_required: false,
aliases: &["create_role"],
subject: Some(Ty::Any),
params: &[opt("permissions", Ty::Array, "{resource, actions} records"), opt("description", Ty::Str, "what the role is for")],
returns: "Record",
doc: "Create an RBAC role. A malformed permission entry is refused, never dropped.",
examples: &[
(r#"role_create("example-reader", [{resource: "docs", actions: ["read"]}]).status"#, r#"created"#),
(r#"("example-reader" | role_create([{resource: "docs", actions: ["read"]}])).role"#, r#"example-reader"#),
],
},
Signature {
name: "kg_add",
category: None,
subject_required: false,
aliases: &["add_entity"],
subject: None,
params: &[
opt("type", Ty::Str, "the entity type, e.g. person"),
opt("name", Ty::Str, "the entity name"),
opt("properties", Ty::Record, "optional Record of String properties"),
],
returns: "Record",
doc: "Add an entity to the process-local knowledge graph and return {entity_id, type, name}. Takes type and name as arguments, or a piped Record {type, name, properties?}; any other piped value is refused. The graph is not persisted and has no removal; it refuses past 100000 entities with E_BUDGET_EXCEEDED. Refused with E_BAD_ARG for a missing or non-string type or name, a properties value that is not a Record, or more than three arguments.",
examples: &[
(r#"(try { kg_add() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { kg_add("person", "Ada", "x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "kg_relate",
category: None,
subject_required: false,
aliases: &["add_relation"],
subject: None,
params: &[
opt("source", Ty::Str, "the id of an existing entity"),
opt("target", Ty::Str, "the id of an existing entity"),
opt("relation", Ty::Str, "the relation type"),
opt("properties", Ty::Record, "optional Record of String properties"),
],
returns: "Record",
doc: "Add a relation between two existing entities of the process-local knowledge graph and return {relation_id, source, target, relation_type}. Takes source, target and relation as arguments, or a piped Record {source, target, relation, properties?}. An entity id that does not exist is E_NOT_FOUND and nothing is added.",
examples: &[
(r#"(try { kg_relate("no-such-a", "no-such-b", "knows") } catch e { e.error.code })"#, "E_NOT_FOUND"),
(r#"(try { kg_relate("a", "b", "knows", {}, 1) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "kg_query",
category: None,
subject_required: false,
aliases: &["query_kg"],
subject: Some(Ty::Any),
params: &[],
returns: "Array",
doc: "Knowledge-graph entities and relations matching a pattern.",
examples: &[
(r#"kg_query("nothing-matches-this")"#, r#"[]"#),
],
},
Signature {
name: "kg_entities",
category: None,
subject_required: false,
aliases: &["entities"],
subject: None,
params: &[],
returns: "Array",
doc: "Every entity in the knowledge graph.",
examples: &[
(r#"typeof(kg_entities())"#, r#"Array"#),
],
},
Signature {
name: "kg_relations",
category: None,
subject_required: false,
aliases: &["relations"],
subject: None,
params: &[],
returns: "Array",
doc: "Every relation in the knowledge graph.",
examples: &[
(r#"typeof(kg_relations())"#, r#"Array"#),
],
},
Signature {
name: "rag_index",
category: None,
subject_required: false,
aliases: &["index_docs"],
subject: None,
params: &[
opt("content", Ty::Any, "the document text (a string); piped, it is the subject instead"),
opt("source", Ty::Any, "a string naming the source; defaults to unknown"),
opt("metadata", Ty::Any, "optional Record of metadata"),
],
returns: "Record",
doc: "Index one document in the process-local RAG index and return {doc_id, source, chunk_count: 1, total_docs}. A document is at most 1 MiB and the index holds at most 10000 documents; it has no removal, so past the limit the call is E_BUDGET_EXCEEDED. Piped, the content is the input and the arguments are source and metadata. Refused with E_BAD_ARG for content that is not a string, a source that is not a string, metadata that is not a Record, or more than three arguments.",
examples: &[
(r#"(try { rag_index() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { rag_index(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { rag_index("a", "b", "c", "d") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "rag_search",
category: None,
subject_required: false,
aliases: &["search_docs"],
subject: Some(Ty::Any),
params: &[opt("top_k", Ty::Int, "how many chunks to use")],
returns: "Array",
doc: "The indexed chunks most similar to a query, with scores (top_k defaults to 5). top_k is an integer from 1 to 100: 0 or a negative count is E_BAD_ARG, and more than 100 is E_BUDGET_EXCEEDED. Piped, the query is the input and top_k is the only argument (`\"q\" | rag_search(3)`); called directly it is rag_search(query, top_k).",
examples: &[
(r#"typeof(rag_search("anything"))"#, r#"Array"#),
(r#"typeof(rag_search("anything", 2))"#, r#"Array"#),
(r#"(try { rag_search("anything", -1) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "rag_query",
category: None,
subject_required: false,
aliases: &["rag"],
subject: Some(Ty::Any),
params: &[opt("top_k", Ty::Int, "how many chunks to use")],
returns: "Record",
doc: "Retrieve context for a query and build an answer from it (top_k defaults to 3). top_k is an integer from 1 to 20: 0 or a negative count is E_BAD_ARG, and more than 20 is E_BUDGET_EXCEEDED. Piped, the query is the input and top_k is the only argument; called directly it is rag_query(query, top_k). The answer is built from the retrieved chunks only; no model is called.",
examples: &[
(r#"typeof(rag_query("anything"))"#, r#"Record"#),
(r#"typeof(rag_query("anything", 1))"#, r#"Record"#),
(r#"(try { rag_query("anything", 0) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "rag_clear",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Int",
doc: "Empty the RAG index, returning how many chunks it held.",
examples: &[
(r#"typeof(rag_clear())"#, r#"Int"#),
],
},
Signature {
name: "job_submit",
category: None,
subject_required: false,
aliases: &["submit"],
subject: None,
params: &[req("name", Ty::Str, "job name"), req("task", Ty::Str, "what the job should do"), opt("priority", Ty::Int, "scheduling priority")],
returns: "Record",
doc: "Submit a job to the distributed job table. Refused: there is no executor, so no job is queued and nothing runs.",
examples: &[
(r#"(try { job_submit("build", "cargo test") } catch e { e.error.code })"#, "E_UNIMPLEMENTED"),
(r#"(try { job_submit("build", "cargo test", 5) } catch e { e.error.code })"#, "E_UNIMPLEMENTED"),
(r#"(try { job_submit(5, "cargo test") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "job_status",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "Record",
doc: "The status of a job in the distributed job table, by its id.",
examples: &[
(r#"(try { job_status("job_none") } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "job_cancel",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "Bool",
doc: "Cancel a pending or running job. A job that has already finished refuses.",
examples: &[
(r#"(try { job_cancel("job_none") } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "job_results",
category: None,
subject_required: false,
aliases: &["results"],
subject: Some(Ty::Any),
params: &[],
returns: "Array",
doc: "A distributed job's results; empty for an unknown job.",
examples: &[
(r#"job_results("no-such-job")"#, r#"[]"#),
],
},
Signature {
name: "job_list",
category: None,
subject_required: false,
aliases: &["jobs"],
subject: None,
params: &[],
returns: "Array",
doc: "Every distributed job, with its status.",
examples: &[
(r#"typeof(job_list())"#, r#"Array"#),
],
},
Signature {
name: "cluster_create",
category: None,
subject_required: false,
aliases: &["cluster"],
subject: None,
params: &[opt("name", Ty::Str, "a non-empty cluster name of at most 128 bytes; defaults to default")],
returns: "Record",
doc: "Store a cluster in this process and answer its record {name, status: created, created_at}. In-process; nothing is started or contacted. cluster_status counts the stored clusters. Nodes added with cluster_add_node are kept in a separate registry that does not record their cluster. Refused with E_BAD_ARG for a name that is not a non-empty string of at most 128 bytes, a name already stored, or more than one argument; E_BUDGET_EXCEEDED above 64 stored clusters, since this process has no removal.",
examples: &[
(r#"(try { cluster_create("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { cluster_create(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "cluster_add_node",
category: None,
subject_required: false,
aliases: &["add_node"],
subject: None,
params: &[
opt("id", Ty::Str, "the node identifier"),
opt("address", Ty::Str, "host:port, with no whitespace"),
opt("capabilities", Ty::Array, "an Array of String capabilities; defaults to compute and storage"),
],
returns: "Record",
doc: "Register a node in this process's cluster registry and return {id, address, capabilities, status: registered}. Nothing contacts the node, so it is registered, not online; no heartbeat or liveness is checked, and cluster_status counts it under registered_nodes, never online_nodes. Takes id and address as arguments, or a piped Record {id, address}. Refused with E_BAD_ARG for an empty id, an address that is empty or has whitespace, a capabilities value that is not an Array of strings, or more than three arguments.",
examples: &[
(r#"(try { cluster_add_node() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { cluster_add_node("node-1", "bad address") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "cluster_nodes",
category: None,
subject_required: false,
aliases: &["nodes"],
subject: None,
params: &[],
returns: "Array",
doc: "Every node registered in the cluster.",
examples: &[
(r#"typeof(cluster_nodes())"#, r#"Array"#),
],
},
Signature {
name: "cluster_status",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Node, job and stored-cluster counts for this process: clusters and cluster_names come from cluster_create; registered_nodes counts nodes from cluster_add_node, which nothing has checked, and online_nodes counts only nodes whose status is online (none is set by cluster_add_node); the job counts come from the job table. In-process; nothing is contacted.",
examples: &[
(r#"typeof(cluster_status())"#, r#"Record"#),
],
},
Signature {
name: "cmake_configure",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
opt("source_dir", Ty::Str, "project source directory inside the workspace; defaults to the process's directory"),
opt("build_dir", Ty::Str, "build directory inside the workspace, created when missing; defaults to build"),
opt("options", Ty::Record, "optional {generator?: String, defines?: Record of String, Int or Bool values}"),
],
returns: "Record",
doc: "cmake -S <source> -B <build> [-G generator] [-Dname=value...] with no shell, answering {source_dir, build_dir, exit_code, success, stdout, stderr}. Option names other than generator and defines are refused by name; a define name is letters, digits and _.- and a Bool define is ON or OFF. Configure runs the project's CMakeLists code, but the effect is Exec, so agent mode asks for approval. A nonzero exit is E_TOOL_FAILED with the stderr tail. Takes no pipeline input.",
examples: &[
(r#"(try { cmake_configure("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { cmake_configure(".", "-B") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { cmake_configure({bogus: 1}) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { cmake_configure(".", "build", {defines: {"a b": 1}}) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | cmake_configure() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "cmake_build",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
opt("build_dir", Ty::Str, "configured build directory inside the workspace; defaults to build"),
opt("options", Ty::Record, "optional {target?: String, config?: String, jobs?: Int 1..1024}"),
],
returns: "Record",
doc: "cmake --build <build_dir> [--target t] [--config c] [-j n] with no shell, answering {build_dir, exit_code, success, stdout, stderr}. The directory must exist. Option names other than target, config and jobs are refused by name, and each value is one argument that may not start with '-'. The build runs project code, so its effect is exec and the central gate asks for approval in agent mode. A nonzero exit is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { cmake_build("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { cmake_build("build", {jobs: 0}) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { cmake_build({jobs: 1}) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | cmake_build() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "cluster_remove_node",
category: None,
subject_required: false,
aliases: &["remove_node"],
subject: Some(Ty::Any),
params: &[],
returns: "Bool",
doc: "Remove a node, reporting whether it existed.",
examples: &[
(r#"cluster_remove_node("no-such-node")"#, r#"false"#),
],
},
Signature {
name: "semantic_cache",
category: None,
subject_required: false,
aliases: &["cache_ai"],
subject: None,
params: &[
opt("query", Ty::Str, "the prompt to cache, 1 to 4096 bytes"),
opt("response", Ty::Str, "the response to store, at most 256 KiB"),
],
returns: "Record",
doc: "Store a response under a query in the process-local semantic cache, which holds at most 1000 entries (the oldest is evicted) and answers a later query by lexical similarity above a threshold, for at most an hour. Returns {cached: true, total_entries, total_hits}. Takes query and response as arguments, or a piped Record {query, response}. Refused with E_BAD_ARG for a missing or empty query, or more than two arguments, and with E_BUDGET_EXCEEDED for a response over 256 KiB.",
examples: &[
(r#"(try { semantic_cache("q") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { semantic_cache("", "answer") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "semantic_cache_clear",
category: None,
subject_required: false,
aliases: &["cache_clear_ai"],
subject: None,
params: &[],
returns: "Int",
doc: "Empty the semantic cache, returning how many entries it held.",
examples: &[
(r#"typeof(semantic_cache_clear())"#, r#"Int"#),
],
},
Signature {
name: "sso_init",
category: None,
subject_required: false,
aliases: &["init_sso"],
subject: None,
params: &[
req("provider", Ty::Str, "oauth2, saml or oidc"),
req("client_id", Ty::Str, "the client id registered with the provider"),
req("issuer_url", Ty::Str, "the identity provider, https:// (http:// only for localhost)"),
],
returns: "Record",
doc: "Record the SSO provider configuration for this process, and forget any tokens issued under the previous one. Returns {status: initialized, provider}. An unknown provider or a non-https issuer is E_BAD_ARG. Nothing contacts the provider; use sso_status to read the configuration back.",
examples: &[
(r#"try { sso_init("saml2", "example-app", "https://idp.example.com") } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
(r#"try { sso_init("oidc", "example-app", "http://idp.example.com") } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
],
},
Signature {
name: "sso_auth",
category: None,
subject_required: false,
aliases: &["sso_authenticate"],
subject: Some(Ty::Str),
params: &[],
returns: "Record",
doc: "Not implemented. The callback is not exchanged with the identity provider and its signature is not checked, so this cannot say who authenticated, and it issues no token. It answers E_UNIMPLEMENTED every time. Use rbac_login for a local, password-proven principal.",
examples: &[
(r#"try { sso_auth("example-callback") } catch e { e.error.code }"#, r#"E_UNIMPLEMENTED"#),
],
},
Signature {
name: "sso_validate",
category: None,
subject_required: false,
aliases: &["validate_sso"],
subject: Some(Ty::Any),
params: &[],
returns: "Record",
doc: "Whether an SSO token is live, and whose it is.",
examples: &[
(r#"sso_validate("no-such-token").valid"#, r#"false"#),
],
},
Signature {
name: "sso_logout",
category: None,
subject_required: false,
aliases: &["logout_sso"],
subject: Some(Ty::Any),
params: &[],
returns: "Record",
doc: "End an SSO session: status logged_out, or not_found for an unknown token.",
examples: &[
(r#"sso_logout("no-such-token").status"#, r#"not_found"#),
],
},
// Compliance: the shell's own controls, checked honestly. Encryption at
// rest is not observable here, so no standard can read as compliant.
Signature {
name: "compliance_check",
category: None,
subject_required: false,
aliases: &["check_compliance"],
subject: Some(Ty::Str),
params: &[opt("scope", Ty::Str, "\"all\", the only scope implemented")],
returns: "Record",
doc: "Check the shell's own controls against GDPR, HIPAA, SOC2 or PCI. Returns {standard, scope, passed, failed, unverified, compliant}. A control the shell cannot observe (encryption at rest) is unverified, and compliant is true only when nothing failed and nothing is unverified, so no standard is reported compliant on an assertion. A standard the shell does not know, or any scope but all, is E_BAD_ARG.",
examples: &[
(r#"compliance_check("GDPR").standard"#, r#"GDPR"#),
(r#"compliance_check("GDPR", "all").scope"#, r#"all"#),
(r#"try { compliance_check("NOT-A-STANDARD") } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
(r#"try { compliance_check("GDPR", "one-subset") } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
],
},
Signature {
name: "compliance_report",
category: None,
subject_required: false,
aliases: &["generate_compliance"],
subject: Some(Ty::Str),
params: &[],
returns: "Record",
doc: "The compliance_check verdict for a standard, with generated_at, the audit entry count, the role count and whether SSO is configured. Like compliance_check, it is never compliant while a control is unverified.",
examples: &[
(r#"compliance_report("HIPAA").standard"#, r#"HIPAA"#),
(r#"try { compliance_report("NOT-A-STANDARD") } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
],
},
// 1b: audit, feature flags, environment, plugins, telemetry, sessions.
Signature {
name: "audit_log",
category: None,
subject_required: false,
aliases: &["log_audit"],
subject: None,
params: &[
req("action", Ty::Str, "what was done"),
req("resource", Ty::Str, "what it was done to"),
opt("details", Ty::Str, "free text about the action"),
opt("severity", Ty::Str, "info, warning or critical; info when absent"),
],
returns: "Record",
doc: "Record an entry the agent asserts about its own work. It is kept in the in-process audit list (at most 10000 entries, then E_BUDGET_EXCEEDED) and, when a chained audit log is active, in that log labelled decision asserted, so an assertion is attributable and cannot be quietly edited. Returns {status: logged, id}. Text fields must be strings of at most 4096 bytes with no control characters; an unknown severity is E_BAD_ARG. When IRONSHELL_AUDIT_REQUIRED is set and the chained log cannot be written, the call is E_IO and the entry is neither kept nor reported as logged.",
examples: &[
(r#"audit_log("example-action", "example-resource").status"#, r#"logged"#),
(r#"audit_log("example-action", "example-resource", "with details").status"#, r#"logged"#),
(r#"try { audit_log("example-action", "example-resource", "d", "bogus") } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
],
},
Signature {
name: "audit_tail",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt_range("count", Ty::Int, 0, 10000, "how many of the newest entries; 20 when absent")],
returns: "Array",
doc: "The newest entries of the active chained audit log, oldest first, as records. A log that does not exist yet is an empty array; a log that exists and cannot be read is E_IO. With no active log (human mode without IRONSHELL_AUDIT_LOG) it is E_BAD_STATE. A count outside 0 to 10000 is E_BAD_ARG.",
examples: &[
(r#"try { audit_tail() } catch e { e.error.code }"#, r#"E_BAD_STATE"#),
(r#"try { audit_tail(-1) } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
],
},
Signature {
name: "audit_verify",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("path", Ty::Str, "the log to verify; the active log when absent")],
returns: "Record",
doc: "Verify a hash-chained audit log. Returns {valid, entries, path, keyed}: valid is true only for a log whose every entry chains to the one before. A missing, unreadable, empty or broken log is valid: false with the reason in error. keyed says whether the chain was keyed (IRONSHELL_AUDIT_KEY); an unkeyed chain shows corruption, not tampering, and the record then also carries a note on how to key it. A path that is not a string is E_BAD_ARG.",
examples: &[
(r#"try { audit_verify() } catch e { e.error.code }"#, r#"E_BAD_STATE"#),
(r#"(try { audit_verify("no-such-audit-log-here.log") } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "audit_export",
category: None,
subject_required: false,
aliases: &["export_audit"],
subject: None,
params: &[opt("format", Ty::Str, "\"json\", the only format implemented")],
returns: "Record",
doc: "The in-memory audit log as {format, count, entries}. Any format but json is refused rather than mislabelled.",
examples: &[
(r#"audit_export().format"#, r#"json"#),
(r#"audit_export("json").format"#, r#"json"#),
],
},
Signature {
name: "audit_query",
category: None,
subject_required: false,
aliases: &["query_audit"],
subject: None,
params: &[opt("filter", Ty::Record, "field values an entry must match")],
returns: "Array",
doc: "Audit log entries, optionally only those whose builtin (action is an alias) or resource contains the filter's value. With an audit log active these are the chained entries audit_verify checks, as records with builtin, decision, resource and detail fields. Any other field of the filter, or a filter that is not a record, is E_BAD_ARG.",
examples: &[
(r#"typeof(audit_query())"#, r#"Array"#),
(r#"typeof(audit_query({action: "nobody"}))"#, r#"Array"#),
],
},
Signature {
name: "feature_set", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Str),
params: &[req("enabled", Ty::Bool, "true to enable the flag, false to disable it")],
returns: "Bool",
doc: "Set a runtime feature flag on or off and return true. Called as feature_set(name, enabled), or piped as name | feature_set(enabled). A name that is empty, longer than 128 bytes, or contains anything but letters, digits, '_', '-', '.' or ':' is E_BAD_ARG; surplus arguments are refused rather than dropped. The flag is process-wide state read by feature_enabled and the features that check it, and is not transactional.",
examples: &[
(r#"(try { feature_set("", true) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { feature_set("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "feature_enable",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "Bool",
doc: "Turn a runtime feature flag on.",
examples: &[
(r#"feature_enable("example_flag")"#, r#"true"#),
(r#""example_flag" | feature_enable()"#, r#"true"#),
],
},
Signature {
name: "feature_disable",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "Bool",
doc: "Turn a runtime feature flag off, reporting whether it was on.",
examples: &[
(r#"feature_disable("never_enabled_flag")"#, r#"false"#),
],
},
Signature {
name: "set_env", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("key", Ty::Str, "variable name: 1 to 1024 bytes, no '=' and no NUL"), req("value", Ty::Str, "value: at most 32767 bytes, no NUL")],
returns: "Null",
doc: "Set an environment variable of this shell process and return null. It has the same checks as env_set, with the same E_BAD_ARG refusals, made before the environment changes. Takes no pipeline input.",
examples: &[
(r#"(try { set_env("", "x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { set_env("A=B", "x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "env_set", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "variable name: 1 to 1024 bytes, no '=' and no NUL"), req("value", Ty::Str, "value: at most 32767 bytes, no NUL")],
returns: "Bool",
doc: "Set an environment variable of this shell process to value and return true. A name that is empty or contains '=' or NUL, or a value containing NUL or longer than 32767 bytes, is E_BAD_ARG before the environment changes; the underlying call would panic on them. The change is process-local and is not transactional. Takes no pipeline input.",
examples: &[
(r#"(try { env_set("A=B", "x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { env_set("", "x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "env_unset",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("name", Ty::Str, "environment variable to remove")],
returns: "Bool",
doc: "Remove a variable from this shell's environment.",
examples: &[
(r#"env_unset("AE_EXAMPLE_UNSET_VARIABLE")"#, r#"true"#),
],
},
Signature {
name: "env_activate",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a Python virtualenv directory")],
returns: "String",
doc: "The shell command that activates a virtualenv. It returns the command; it does not run it.",
examples: &[
(r#"typeof(env_activate(".venv"))"#, r#"String"#),
],
},
Signature {
name: "help",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("name", Ty::Str, "a builtin or category name; omitted, it gives the short reference")],
returns: "String | Record",
doc: "A short reference of the core builtins. help(\"name\") describes one builtin, with its signature, effect and examples, as ontology_describe(\"name\") does; a category name lists its builtins.",
examples: &[
(r#"typeof(help())"#, r#"String"#),
(r#"typeof(help("ls"))"#, r#"Record"#),
],
},
Signature {
name: "platform_module",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "String",
doc: "The platform-specific script for a module: utils becomes utils_linux.ish on Linux, utils_windows.ish on Windows.",
examples: &[
(r#"typeof(platform_module("mymodule"))"#, r#"String"#),
],
},
Signature {
name: "plugin_enable",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "Bool",
doc: "Set a registered plugin's enabled flag to true, reporting true. The flag is what plugin_info reports as enabled. Nothing dispatches on it yet, so enabling a plugin does not make its builtins callable. An unknown plugin is E_NOT_FOUND.",
examples: &[
(r#"try { plugin_enable("no-such-plugin-id") } catch e { e.error.code }"#, r#"E_NOT_FOUND"#),
],
},
Signature {
name: "plugin_disable",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "Bool",
doc: "Set a registered plugin's enabled flag to false, reporting true. This records the flag as plugin_info.enabled. Nothing dispatches on that flag yet, so a disabled plugin's builtins are not stopped by it. An unknown plugin is E_NOT_FOUND.",
examples: &[
(r#"try { plugin_disable("no-such-plugin-id") } catch e { e.error.code }"#, r#"E_NOT_FOUND"#),
],
},
Signature {
name: "plugin_load",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "Record",
doc: "Register a plugin from a TOML manifest with a [plugin] table, reporting {id, name, version, status: registered}. Each [builtins] entry is one lambda literal (name = 'fn(...) => ...'); its name becomes callable after the load, and the body runs through the evaluator, so every builtin it calls keeps its own guard and a plugin builtin is classed as exec. A name must be an identifier that no core builtin serves and that no other loaded plugin provides (E_BAD_ARG, or E_BAD_STATE for a provider clash). A manifest with [builtins] is code: IRONSHELL_PLUGINS=off refuses it, and agent mode needs IRONSHELL_PLUGIN_ALLOW (E_POLICY_DENY). The id must be 1 to 128 letters, digits, '.', '_' or '-'. The manifest is at most 1 MiB. A duplicate id is E_BAD_STATE. Native and script plugins are not loaded by this builtin.",
examples: &[
(r#"try { plugin_load("no-such-manifest-here.plugin.toml") } catch e { e.error.code }"#, r#"E_NOT_FOUND"#),
],
},
Signature {
name: "plugin_unload",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "Record",
doc: "Remove a registered plugin and what it registered, reporting {id, status: unloaded}. A built-in plugin is E_POLICY_DENY, and an unknown one is E_NOT_FOUND.",
examples: &[
(r#"try { plugin_unload("builtin.json") } catch e { e.error.code }"#, r#"E_POLICY_DENY"#),
(r#"try { plugin_unload("no-such-plugin-id") } catch e { e.error.code }"#, r#"E_NOT_FOUND"#),
],
},
Signature {
name: "plugin_info",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "Record",
doc: "A plugin's metadata. An unknown id is E_NOT_FOUND.",
examples: &[
(r#"plugin_info("builtin.json").id"#, r#"builtin.json"#),
],
},
Signature {
name: "telemetry_events",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("limit", Ty::Int, "most recent events to return; default 100")],
returns: "Array",
doc: "Recorded telemetry events, most recent first.",
examples: &[
(r#"typeof(telemetry_events())"#, r#"Array"#),
(r#"typeof(telemetry_events(5))"#, r#"Array"#),
],
},
Signature {
name: "sess_open",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Open a stateful session: a persistent environment whose let-bindings survive across sess_eval calls. At most 64 are open.",
examples: &[
(r#"typeof(sess_open())"#, "Record"),
],
},
Signature {
name: "sess_eval",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("id", Ty::Str, "a session id from sess_open"), req("code", Ty::Str, "code to evaluate in the session")],
returns: "Any",
doc: "Evaluate code in a session's persistent environment and return its value. Builtins the code calls pass the same guard as at the REPL.",
examples: &[
(r#"(try { sess_eval("no-such-session", "1") } catch e { e.error.code })"#, "E_NOT_FOUND"),
(r#"(try { sess_eval(5, "1") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "sess_usage",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("id", Ty::Str, "a session id")],
returns: "Record",
doc: "Running token estimates for a session (tokens_in, tokens_out, tokens_total) and its eval count. The tokens are estimates, not model usage.",
examples: &[
(r#"(try { sess_usage("no-such-session") } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "sess_close",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("id", Ty::Str, "a session id")],
returns: "Record",
doc: "Discard a session and its environment, reporting whether it existed.",
examples: &[
(r#"sess_close("no-such-session").closed"#, r#"false"#),
],
},
// 1b: agent protocols (a2a, a2ui) and RL/RLM/evolution configuration.
// `rlm_stats` waits: with no argument it returns constants presented as
// statistics, and an example script depends on that; it needs a real
// source of run statistics first.
Signature {
name: "a2a_broadcast",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("message", Ty::Any, "the message every registered agent receives")],
returns: "Record",
doc: "Queue a message for every registered agent, in process. The message is at most 64 KiB as display text (E_BUDGET_EXCEEDED above that). A broadcast reaches at most 64 agents, and it is all or nothing: if one recipient's queue already holds 1024 undelivered messages, or there are too many recipients, the call is refused and no queue changes. Takes one message; piped input is refused.",
examples: &[
(r#"typeof(a2a_broadcast("hello"))"#, r#"Record"#),
(r#"(try { a2a_broadcast() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "a2a_send",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("target", Ty::Str, "the registered agent to queue the message for"), req("message", Ty::Any, "the message; at most 64 KiB as display text")],
returns: "Record",
doc: "Queue a message for a registered agent, in process. Nothing leaves the process; a2a_receive drains the queue.",
examples: &[
(r#"(try { a2a_send("agent-nobody-registered", "hi") } catch e { e.error.code })"#, "E_NOT_FOUND"),
(r#"(try { a2a_send(5, "hi") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "a2a_register",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("name", Ty::Str, "agent name"), opt("info", Ty::Record, "capabilities and other metadata")],
returns: "Record",
doc: "Register an agent so it can receive messages, in process. The name is a non-empty String of at most 128 bytes. At most 256 agents are registered: a new name past that is E_BUDGET_EXCEEDED, while re-registering a name replaces its info. Info must be a Record (anything else is E_BAD_ARG) of at most 64 KiB as display text.",
examples: &[
(r#"typeof(a2a_register("example-agent"))"#, r#"Record"#),
(r#"typeof(a2a_register("example-agent", {role: "demo"}))"#, r#"Record"#),
(r#"(try { a2a_register("example-agent", "not a record") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "a2a_receive",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("agent", Ty::Str, "whose messages; default \"default\"")],
returns: "Array",
doc: "Take an agent's pending messages, emptying its queue.",
examples: &[
(r#"a2a_receive("agent-nobody-registered")"#, r#"[]"#),
(r#"typeof(a2a_receive())"#, r#"Array"#),
],
},
Signature {
name: "a2a_unregister",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("name", Ty::Str, "agent name")],
returns: "Record",
doc: "Remove an agent and its queue, reporting whether it was registered.",
examples: &[
(r#"a2a_unregister("no-such-agent").unregistered"#, r#"false"#),
],
},
Signature {
name: "nanda_propose",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("name", Ty::Str, "proposal name"), req("data", Ty::Record, "kept on the record; threshold (Float in (0, 1], default 0.5) and electorate (Int 1..=1024, default 1) are read")],
returns: "Record",
doc: "Open a pending proposal in the local consensus tally. Nothing identifies voters, so the electorate is the caller's assertion.",
examples: &[
(r#"typeof(nanda_propose("ship-it", {threshold: 0.5}))"#, "Record"),
(r#"(try { nanda_propose(5, {}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "nanda_vote",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("proposal_id", Ty::Str, "a pending proposal"), req("approve", Ty::Bool, "true to approve")],
returns: "Record",
doc: "Cast one ballot on a pending proposal. A decided proposal, or one whose electorate has all balloted, refuses.",
examples: &[
(r#"(try { nanda_vote("prop_none", true) } catch e { e.error.code })"#, "E_NOT_FOUND"),
(r#"(try { nanda_vote("prop_none", "yes") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "nanda_commit",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("proposal_id", Ty::Str, "a pending proposal")],
returns: "Record",
doc: "Commit a pending proposal that has quorum (half its electorate balloted) and an approval ratio at or above its threshold. Below the threshold it is rejected.",
examples: &[
(r#"(try { nanda_commit("prop_none") } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "nanda_abort",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("proposal_id", Ty::Str, "a pending proposal")],
returns: "Record",
doc: "Abort a pending proposal. A decided proposal refuses.",
examples: &[
(r#"(try { nanda_abort("prop_none") } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "nanda_status",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("proposal_id", Ty::Str, "a proposal; omit for every proposal")],
returns: "Record | Array",
doc: "One proposal's record, or every held proposal as an array.",
examples: &[
(r#"typeof(nanda_status())"#, "Array"),
(r#"(try { nanda_status("prop_none") } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "nanda_consensus",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("proposal_id", Ty::Str, "a proposal")],
returns: "Record",
doc: "Whether a proposal's tally reaches consensus now: a quorum of ballots and an approval ratio at or above the threshold.",
examples: &[
(r#"(try { nanda_consensus("prop_none") } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "nanda_quorum",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("proposal_id", Ty::Str, "a proposal")],
returns: "Record",
doc: "How much of a proposal's electorate has balloted, and whether half of it has.",
examples: &[
(r#"(try { nanda_quorum("prop_none") } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "a2ui_notify",
category: None,
subject_required: false,
aliases: &["notify_user"],
subject: Some(Ty::Any),
params: &[opt("level", Ty::Any, "info, success, warning or error; a string or {level: ...}")],
returns: "Record",
doc: "Queue a notification for the user. sent means queued, not displayed; ui_attached says whether a UI has ever read the queue. An unknown level is refused, not shown as info.",
examples: &[
(r#"a2ui_notify("done").sent"#, r#"true"#),
(r#"a2ui_notify("done", "success").sent"#, r#"true"#),
],
},
Signature {
name: "a2ui_render",
category: None,
subject_required: false,
aliases: &["render_content"],
subject: Some(Ty::Any),
params: &[],
returns: "Bool",
doc: "Queue text, {markdown: ...}, {json: ...} or any value for rendering in the UI. Invalid JSON is refused. true means queued, not displayed: with no UI attached the event waits for one, and the oldest is dropped when the queue is full.",
examples: &[
(r#"a2ui_render("text")"#, r#"true"#),
],
},
Signature {
name: "a2ui_agent_started",
category: None,
subject_required: false,
aliases: &["agent_started"],
subject: Some(Ty::Any),
params: &[opt("task", Ty::Any, "what the agent is doing")],
returns: "Bool",
doc: "Queue an event telling the UI an agent has started. true means queued, not displayed: with no UI attached the event waits for one, and the oldest is dropped when the queue is full.",
examples: &[
(r#"a2ui_agent_started("a1")"#, r#"true"#),
(r#"a2ui_agent_started("a1", "indexing")"#, r#"true"#),
],
},
Signature {
name: "a2ui_agent_completed",
category: None,
subject_required: false,
aliases: &["agent_completed"],
subject: Some(Ty::Any),
params: &[opt("success", Ty::Bool, "whether it succeeded; default true"), opt("result", Ty::Any, "what it produced")],
returns: "Bool",
doc: "Queue an event telling the UI an agent has finished; true means queued, not displayed. The success flag, when given, must be a Bool; any other type (such as \"false\" or 0) is E_BAD_ARG rather than success.",
examples: &[
(r#"a2ui_agent_completed("a1")"#, r#"true"#),
(r#"a2ui_agent_completed("a1", false, "timed out")"#, r#"true"#),
(r#"(try { a2ui_agent_completed("a1", "false") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "a2ui_status",
category: None,
subject_required: false,
aliases: &["status_bar"],
subject: Some(Ty::Any),
params: &[],
returns: "Bool",
doc: "Queue new status-bar text. true means queued, not displayed: with no UI attached the event waits for one, and the oldest is dropped when the queue is full.",
examples: &[
(r#"a2ui_status("working")"#, r#"true"#),
],
},
Signature {
name: "a2ui_toast",
category: None,
subject_required: false,
aliases: &["toast"],
subject: Some(Ty::Any),
params: &[opt("level", Ty::Str, "info, success, warning or error"), opt("duration_ms", Ty::Numeric, "default 3000")],
returns: "Bool",
doc: "Queue a transient notification. An unknown level is refused. true means queued, not displayed: with no UI attached the event waits for one, and the oldest is dropped when the queue is full.",
examples: &[
(r#"a2ui_toast("saved")"#, r#"true"#),
(r#"a2ui_toast("saved", "success", 1000)"#, r#"true"#),
],
},
// The prompts wait for a UI. With none attached they refuse E_NO_UI at
// once, and they never answer for a user who is not there.
Signature {
name: "a2ui_prompt",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[],
returns: "Str | Null",
doc: "Ask the user for text and wait for the answer. Refused with E_NO_UI when no UI is attached; null when the user cancels.",
examples: &[
(r#"(try { a2ui_prompt() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { a2ui_prompt("Name?") } catch e { e.error.code })"#, "E_NO_UI"),
],
},
Signature {
name: "a2ui_confirm",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[],
returns: "Bool",
doc: "Ask the user yes or no and wait for the answer. Refused with E_NO_UI when no UI is attached, so nobody is answered for; a user who cancels is a decline.",
examples: &[
(r#"(try { a2ui_confirm() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { a2ui_confirm("Delete?") } catch e { e.error.code })"#, "E_NO_UI"),
],
},
Signature {
name: "a2ui_select",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[req("options", Ty::Array, "a non-empty array of choices")],
returns: "Str | Null",
doc: "Ask the user to choose one option and wait for the answer. Refused with E_NO_UI when no UI is attached; null when the user cancels.",
examples: &[
(r#"(try { a2ui_select("Pick") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { a2ui_select("Pick", ["a", "b"]) } catch e { e.error.code })"#, "E_NO_UI"),
],
},
// The display calls queue an event for a UI and do not wait for one.
Signature {
name: "a2ui_progress",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("label", Ty::Str, "what is in progress"),
req("current", Ty::Int, "whole count done so far"),
req("total", Ty::Int, "whole count in all, at least current"),
opt("progress_id", Ty::Str, "a UUID from an earlier call, to update that indicator"),
],
returns: "Record",
doc: "Show or update a progress indicator and return its progress_id. The event is queued for a UI; with none attached it is not an error.",
examples: &[
(r#"(try { a2ui_progress("x", -1, 3) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"a2ui_progress("build", 1, 3).current"#, "1"),
(r#"a2ui_progress("build", 2, 3, a2ui_progress("build", 1, 3).progress_id).current"#, "2"),
],
},
Signature {
name: "a2ui_progress_complete",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "Bool",
doc: "Queue the completion of a progress indicator. The id is the progress_id a2ui_progress returned. true means queued, not displayed: with no UI attached the event waits for one, and the oldest is dropped when the queue is full.",
examples: &[
(r#"(try { a2ui_progress_complete("not-a-uuid") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"a2ui_progress_complete("9b2e6f0a-6b1c-4f7e-8a7e-2c4d1e5f6a7b")"#, "true"),
],
},
Signature {
name: "a2ui_render_table",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("headers", Ty::Array, "column names"),
opt("rows", Ty::Array, "rows as arrays or as records keyed by header; or piped"),
],
returns: "Bool",
doc: "Queue a table for the UI. A row that is neither an array nor a record is refused. true means queued, not displayed: with no UI attached the event waits for one, and the oldest is dropped when the queue is full.",
examples: &[
(r#"(try { a2ui_render_table("h") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"a2ui_render_table(["a"], [["1"]])"#, "true"),
],
},
Signature {
name: "a2ui_render_code",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("language", Ty::Str, "the language name, such as rust"),
opt("code", Ty::Any, "the source text; or piped"),
],
returns: "Bool",
doc: "Queue code, with its language, for the UI. true means queued, not displayed: with no UI attached the event waits for one, and the oldest is dropped when the queue is full.",
examples: &[
(r#"(try { a2ui_render_code() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"a2ui_render_code("rust", "fn main() {}")"#, "true"),
],
},
Signature {
name: "a2ui_agent_thinking",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("agent_id", Ty::Str, "the agent that is reasoning"),
opt("thought", Ty::Any, "what it is considering; or piped"),
opt_range("step", Ty::Int, 0, i64::MAX, "the step number, 0 or more"),
],
returns: "Bool",
doc: "Queue an agent's reasoning for the UI. true means queued, not displayed: with no UI attached the event waits for one, and the oldest is dropped when the queue is full.",
examples: &[
(r#"(try { a2ui_agent_thinking() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"a2ui_agent_thinking("a1", "planning", 2)"#, "true"),
],
},
Signature {
name: "rl_gridworld",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("width", Ty::Int, "positive width; default 5"), opt("height", Ty::Int, "positive height; default: the width")],
returns: "Record",
doc: "Create a gridworld with positive dimensions and at most one million cells. Start at [0,0], set the goal to [width-1,height-1], use four cardinal actions and no obstacles. Return dimensions, positions, state/action counts and obstacles as [x,y] pairs.",
examples: &[
(r#"rl_gridworld().state_size"#, "25"),
(r#"rl_gridworld(3).height"#, "3"),
(r#"rl_gridworld(3, 4).state_size"#, "12"),
],
},
Signature {
name: "rl_replay_buffer",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("capacity", Ty::Int, "positive capacity in 1..=10000; default 10000")],
returns: "Record",
doc: "Create an empty experience replay buffer with a checked positive Int capacity at most 10000 before allocation. Return capacity, size zero and serialized circular buffer state with position zero.",
examples: &[
(r#"rl_replay_buffer().capacity"#, "10000"),
(r#"rl_replay_buffer(100).size"#, "0"),
],
},
Signature {
name: "rl_env_step", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record),
params: &[req("action", Ty::Int, "0=up, 1=down, 2=left, 3=right")], returns: "Record",
doc: "Return {state,reward,done,env} after moving a gridworld copy one clamped cardinal step. State is y*width+x. Reward is 1 at the goal, otherwise -0.5 on an obstacle, otherwise -0.01; done means the current position equals the goal and does not prevent subsequent movement. Preserve goals and obstacles. Require positive dimensions with at most one million cells, in-range positions and at most 10000 obstacle pairs. Missing agent coordinates default to zero, missing goal coordinates to the bottom-right corner, and missing obstacles to empty. Refuse wrong types, invalid actions and inconsistent type/state_size/action_size metadata when present.",
examples: &[(r#"rl_env_step(rl_gridworld(2, 1), 3).reward"#, "1.0"), (r#"let result = rl_gridworld(2, 2) | rl_env_step(1); result.state"#, "2")],
},
Signature {
name: "rlm_agent",
category: None,
subject_required: false,
aliases: &["recursive_agent"],
subject: None,
params: &[
req("goal", Ty::Str, "the task for the root agent"),
opt("tools", Ty::Array, "builtin names the agents may call; defaults to ls, cat, grep, find"),
opt("config", Ty::Record, "budgets: max_depth 0-8, max_agents 1-200, max_concurrent_children 1-32, timeout or agent_timeout_secs 1-3600, trace_enabled, model_uri"),
opt("model_uri", Ty::Str, "a model URI for the subagents"),
],
returns: "Record",
doc: "Run a recursive agent: a root model call may spawn subagents, which may spawn further ones within the depth and agent budgets. Each model call is a network request charged to IRONSHELL_MAX_NET and audited, and each agent makes at most 10 steps. Returns {output, total_agents, active_agents, messages_sent, elapsed_ms}. A run that stops at its step limit returns its partial output as an answer beginning (incomplete), not as an error. A budget above its ceiling is E_BUDGET_EXCEEDED; an unknown config key, a non-builtin tool name or a wrong type is E_BAD_ARG or E_NOT_FOUND.",
examples: &[
(r#"(try { rlm_agent() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { rlm_agent("summarise", ["no_such_builtin_xyz"]) } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "rlm_spawn",
category: None,
subject_required: false,
aliases: &["spawn_agent"],
subject: None,
params: &[
req("name", Ty::Str, "a label for the subagent"),
req("goal", Ty::Str, "the subtask"),
opt("tools", Ty::Array, "builtin names the subagent may call; defaults to ls and cat"),
],
returns: "Record",
doc: "Spawn one subagent of depth one (at most 5 agents, 30 seconds) to pursue goal, and return {name, goal, output, complete, success, agents_used, elapsed_ms}. The spawn is an exec decision and is gated as one; its model calls are each charged to IRONSHELL_MAX_NET. complete is false, and success false, when the subagent stopped at its step limit.",
examples: &[
(r#"(try { rlm_spawn("worker") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { rlm_spawn("worker", "count the files", ["no_such_builtin_xyz"]) } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "rlm_config",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("options", Ty::Record, "max_depth, max_agents, timeout, ...")],
returns: "Record",
doc: "A recursive-agent configuration, with defaults for anything not given.",
examples: &[
(r#"rlm_config().max_depth"#, r#"5"#),
(r#"rlm_config({max_depth: 3}).max_depth"#, r#"3"#),
],
},
Signature {
name: "evolution_config",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("options", Ty::Record, "population_size, generations, mutation_rate, mutation_strength, crossover_rate, elitism")],
returns: "Record",
doc: "Return validated numeric evolution settings; this call runs no evolution. Population size is an Int in 1..=10000; generations is an Int in 0..=10000. Mutation and crossover rates are finite numbers in 0..=1; mutation strength is finite and non-negative. Elitism is an Int in 0..=population_size, default min(2,population_size). Unknown keys and wrong-typed values are refused; selection, crossover descriptors and seed are unsupported. A returned evolution_config type marker is accepted when revalidating the record.",
examples: &[
(r#"typeof(evolution_config())"#, r#"Record"#),
(r#"evolution_config({population_size: 10}).population_size"#, r#"10"#),
(r#"evolution_config({generations: 0, mutation_rate: 0, mutation_strength: 1, crossover_rate: 1, elitism: 0}).generations"#, "0"),
],
},
// 1b: hashing, base64 and read-only file inspection. Examples read files
// in this repository, because that is where the declaration tests run.
Signature {
name: "crypto_hash",
category: None,
subject_required: false,
aliases: &["hash"],
subject: Some(Ty::Str),
params: &[opt("data", Ty::Str, "text to hash; omit when piping it in"), opt("algorithm", Ty::Str, "md5, sha1, sha256 (default), sha384 or sha512")],
returns: "String",
doc: "Hex digest of a string. An unknown algorithm is refused, never substituted. Called with two arguments, `crypto.hash(\"sha256\", data)` names the algorithm first. A lone algorithm name with nothing piped in (`crypto.hash(\"sha256\")`) is E_BAD_ARG, not the hash of that word.",
examples: &[
(r#"(try { crypto_hash("sha256") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"("hello" | crypto_hash("md5"))"#, r#"5d41402abc4b2a76b9719d911017c592"#),
(r#"crypto_hash("hello")"#, r#"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"#),
(r#"crypto_hash("hello", "md5")"#, r#"5d41402abc4b2a76b9719d911017c592"#),
(r#"crypto_hash("sha256", "hello")"#, r#"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"#),
],
},
Signature {
name: "md5",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "String",
doc: "MD5 hex digest of a string. Refused under IRONSHELL_FIPS.",
examples: &[
(r#"md5("hello")"#, r#"5d41402abc4b2a76b9719d911017c592"#),
],
},
Signature {
name: "sha256",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "String",
doc: "SHA-256 hex digest of a string.",
examples: &[
(r#"sha256("hello")"#, r#"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"#),
],
},
Signature {
name: "crypto_hash_file",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a file path"), opt("algorithm", Ty::Str, "md5, sha1, sha256 (default), sha384 or sha512")],
returns: "String",
doc: "Hex digest of a file's contents.",
examples: &[
(r#"crypto_hash_file("Cargo.toml") | len"#, r#"64"#),
(r#"crypto_hash_file("Cargo.toml", "md5") | len"#, r#"32"#),
],
},
Signature {
name: "crypto_checksum",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a file path"), opt("algorithm", Ty::Str, "md5, sha1, sha256 (default), sha384 or sha512")],
returns: "String",
doc: "Hex digest of a file's contents; the same as crypto_hash_file.",
examples: &[
(r#"crypto_checksum("Cargo.toml") | len"#, r#"64"#),
(r#"crypto_checksum("Cargo.toml", "sha512") | len"#, r#"128"#),
],
},
Signature {
name: "crypto_base64_encode",
category: None,
subject_required: false,
aliases: &["base64_encode"],
subject: Some(Ty::Str),
params: &[],
returns: "String",
doc: "Standard base64 of a string, unwrapped.",
examples: &[
(r#"base64_encode("hello")"#, r#"aGVsbG8="#),
(r#""hello" | base64_encode()"#, r#"aGVsbG8="#),
],
},
Signature {
name: "crypto_base64_decode",
category: None,
subject_required: false,
aliases: &["base64_decode"],
subject: Some(Ty::Str),
params: &[],
returns: "String",
doc: "Decode base64 to text. Whitespace is ignored, padding is optional, and the URL-safe alphabet (- and _ for + and /) is accepted. Invalid base64 or binary output is refused.",
examples: &[
(r#"base64_decode("aGVsbG8=")"#, r#"hello"#),
(r#"base64_decode("aGVsbG8")"#, r#"hello"#),
(r#"base64_decode("Pz8_")"#, r#"???"#),
],
},
Signature {
name: "file_exists",
category: None,
subject_required: false,
aliases: &["path_exists", "exists"],
subject: Some(Ty::Str),
params: &[],
returns: "Record",
doc: "Whether a path exists, and whether it is a file or a directory. A path that cannot be checked is an error, not absent.",
examples: &[
(r#"file_exists("Cargo.toml").exists"#, r#"true"#),
(r#"(file_exists("Cargo.toml")).is_file"#, r#"true"#),
],
},
Signature {
name: "file_type",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a file path")],
returns: "String",
doc: "The MIME type a path's extension indicates.",
examples: &[
(r#"file_type("data.json")"#, r#"application/json"#),
],
},
Signature {
name: "fs_lstat",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a file path")],
returns: "Record",
doc: "Size and kind of a path, without following a symlink. Null if the path does not exist; any other failure is an error.",
examples: &[
(r#"typeof(fs_lstat("Cargo.toml"))"#, r#"Record"#),
],
},
Signature {
name: "fs_realpath",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a file path")],
returns: "String",
doc: "The canonical absolute path, with symlinks resolved. Null if the path does not exist; any other failure is an error.",
examples: &[
(r#"ends_with(fs_realpath("Cargo.toml"), "Cargo.toml")"#, r#"true"#),
],
},
Signature {
name: "fs_glob",
category: None,
subject_required: false,
aliases: &["glob"],
subject: None,
params: &[req("pattern", Ty::Str, "a glob such as src/*.rs or src/**/*.rs")],
returns: "Array",
doc: "Paths matching a glob, sorted; ** matches any depth of directories, and a directory in the pattern that does not exist is E_NOT_FOUND. At most 1,000,000 entries; more is E_BUDGET_EXCEEDED.",
examples: &[
(r#"(glob("src/*.rs") | len) > 10"#, r#"true"#),
(r#"(glob("src/**/*.rs") | len) > (glob("src/*.rs") | len)"#, r#"true"#),
(r#"glob("Cargo.tom?")"#, r#"["Cargo.toml"]"#),
],
},
Signature {
name: "fs_stat",
category: None,
subject_required: false,
aliases: &["stat"],
subject: None,
params: &[req("path", Ty::Str, "a file path")],
returns: "Record | Null",
doc: "File metadata: size, times, and on Unix mode, inode and ownership. Null if the path does not exist; any other failure is an error.",
examples: &[
(r#"typeof(fs_stat("Cargo.toml"))"#, r#"Record"#),
],
},
Signature {
name: "read_text",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a file path")],
returns: "String",
doc: "A text file's contents, subject to the read denylist and size limit.",
examples: &[
(r#"(read_text("Cargo.toml") | len) > 0"#, r#"true"#),
],
},
Signature {
name: "fs_du",
category: None,
subject_required: false,
aliases: &["du"],
subject: None,
params: &[opt("path", Ty::Str, "directory; default the current one")],
returns: "Record",
doc: "Total size of a directory tree, in bytes and larger units.",
examples: &[
(r#"typeof(du())"#, r#"Record"#),
(r#"typeof(du("src"))"#, r#"Record"#),
],
},
// 1b: environment and process lookups, the search family, tree, CSV.
// proc_kill's examples are refusals, which send nothing; proc_info is
// declared below, its examples read a pid that exists everywhere.
// search_symbols is declared further down, in the machine-dependent tier.
Signature {
name: "env_vars", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "Record",
doc: "Every environment variable of this process as a Record from name to value. In agent mode a value whose name looks like a secret (containing SECRET, TOKEN, PASSWORD, _KEY, CREDENTIAL and similar) is replaced with a [REDACTED:<name>] marker unless IRONSHELL_SECRETS=allow; human mode shows values. The redaction is by name only: a secret held under an ordinary name, or inside a URL such as postgres://user:pass@host, is shown. Names and values that are not UTF-8 are shown with replacement characters. Takes no arguments and no pipeline input.",
examples: &[
(r#"typeof(env_vars())"#, "Record"),
(r#"(try { env_vars("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "env_var",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("name", Ty::Str, "environment variable")],
returns: "String | Null",
doc: "An environment variable, null when unset. Secret-looking names are redacted in agent mode.",
examples: &[
(r#"env_var("AE_SURELY_UNSET_VARIABLE") == null"#, r#"true"#),
(r#"env_var("PATH") != null"#, r#"true"#),
],
},
Signature {
name: "proc_exists",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pid", Ty::Any, "a positive process id, Int or numeric String")],
returns: "Bool",
doc: "Whether a process id is live. A name, zero or a negative number is refused.",
examples: &[
(r#"proc_exists(999999999)"#, r#"false"#),
],
},
Signature {
name: "search_files",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pattern", Ty::Str, "file-name glob such as *.rs")],
returns: "Array",
doc: "Files beneath the current directory whose name matches a glob; build and dependency directories are skipped.",
examples: &[
(r#"search_files("Cargo.toml")"#, r#"["./Cargo.toml"]"#),
],
},
Signature {
name: "search_by_type",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("extension", Ty::Str, "extension without the dot")],
returns: "Array",
doc: "Files beneath the current directory with an extension.",
examples: &[
(r#"search_by_type("toml")"#, r#"["./Cargo.toml", ...]"#),
],
},
Signature {
name: "search_modified",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("days", Ty::Int, "within this many days; default 7")],
returns: "Array",
doc: "Up to 100 files modified recently, beneath the current directory.",
examples: &[
(r#"search_modified()"#, r#"["./src/builtins.rs", ...]"#),
(r#"search_modified(30)"#, r#"["./src/builtins.rs", ...]"#),
],
},
Signature {
name: "fs_tree",
category: None,
subject_required: false,
aliases: &["tree"],
subject: None,
params: &[opt("path", Ty::Str, "directory; default the current one"), opt("depth", Ty::Int, "levels; default 3")],
returns: "String",
doc: "A directory tree as indented text. At most 1,000,000 entries; more is E_BUDGET_EXCEEDED.",
examples: &[
(r#"typeof(tree())"#, r#"String"#),
(r#"typeof(tree("src", 1))"#, r#"String"#),
],
},
Signature {
name: "db_json_to_csv",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("rows", Ty::Any, "an array of records, or its JSON text")],
returns: "String",
doc: "CSV text with a column for every field that appears in any record; nested values become JSON.",
examples: &[
(r#"db_json_to_csv([{a: 1, b: 2}]) == "a,b\n1,2\n""#, r#"true"#),
],
},
// 1b: tool lookup, sysinfo-backed disk and uptime queries, the semantic
// cache and diagnose.
Signature {
name: "platform_has_tool",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("name", Ty::Str, "a program name")],
returns: "Bool",
doc: "Whether a program is on PATH.",
examples: &[
(r#"platform_has_tool("definitely-not-a-real-tool")"#, r#"false"#),
],
},
Signature {
name: "monitor_uptime",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Uptime in seconds and as text, with the load average (load_1, load_5, load_15; null on Windows, which has no load average).",
examples: &[
(r#"typeof(monitor_uptime())"#, r#"Record"#),
],
},
Signature {
name: "mount_info",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Mounted filesystems: device, mount point, type, sizes.",
examples: &[
(r#"typeof(mount_info())"#, r#"Array"#),
],
},
Signature {
name: "lsblk",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Disks and their sizes.",
examples: &[
(r#"typeof(lsblk())"#, r#"Array"#),
],
},
Signature {
name: "semantic_cache_get",
category: None,
subject_required: false,
aliases: &["cache_get"],
subject: Some(Ty::Any),
params: &[],
returns: "Record",
doc: "A cached response for a query: {hit, response}.",
examples: &[
(r#"semantic_cache_get("never-cached-query").hit"#, r#"false"#),
],
},
Signature {
name: "diagnose",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[],
returns: "Record",
doc: "The minimal repair context for an error a catch block bound; a plain string is reported as uncoded.",
examples: &[
(r#"diagnose("plain text failure").code"#, r#"E_UNKNOWN"#),
(r#"typeof(try { 1 / 0 } catch e { diagnose(e) })"#, r#"Record"#),
],
},
// 1b: temp paths and touch. Examples write only under the system temp
// directory, never into the repository the tests run in.
Signature {
name: "fs_tempdir",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("prefix", Ty::Str, "name prefix; default ironshell_")],
returns: "String",
doc: "Create a new directory under the system temp directory and return its path. In agent mode it is created under <workspace>/.ironshell/tmp/ instead.",
examples: &[
(r#"typeof(fs_tempdir())"#, r#"String"#),
(r#"typeof(fs_tempdir("ae_example"))"#, r#"String"#),
],
},
Signature {
name: "fs_tempfile",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("prefix", Ty::Str, "name prefix; default ironshell_")],
returns: "String",
doc: "Create a new empty file under the system temp directory and return its path. In agent mode it is created under <workspace>/.ironshell/tmp/ instead.",
examples: &[
(r#"typeof(fs_tempfile())"#, r#"String"#),
(r#"typeof(fs_tempfile("ae_example"))"#, r#"String"#),
],
},
Signature {
name: "touch",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "file to create or refresh")],
returns: "String",
doc: "Create a file if missing and set its modification time to now; returns the path.",
examples: &[
(r#"typeof(touch(fs_tempfile("ae_touch")))"#, r#"String"#),
],
},
// 1b: JWT, RBAC queries, permissions and RLM statistics, each made to
// report failures instead of answering null.
Signature {
name: "crypto_jwt_decode",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("token", Ty::Str, "a JWT: header.payload.signature")],
returns: "Any",
doc: "A JWT's payload, decoded WITHOUT verifying the signature. A malformed token is refused.",
examples: &[
(r#"crypto_jwt_decode("eyJhbGciOiJub25lIn0.eyJzdWIiOiJhZSJ9.x").sub"#, r#"ae"#),
],
},
Signature {
name: "rbac_grant",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("user", Ty::Str, "the user id to grant the permission to"),
req("permission", Ty::Str, "resource:capability, such as effect:destructive"),
],
returns: "Record",
doc: "Grant a permission to a user, so that user's guarded calls skip the approval gate. Privileged: refused in agent mode, and in a human session it is the operator's call. Returns {user, granted, changed}; changed is false when the user already held the permission. A malformed user id or permission is E_BAD_ARG. A user this creates has no password, so rbac_principal can name it.",
examples: &[
(r#"try { rbac_grant("", "effect:destructive") } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
(r#"try { rbac_grant("example-user", "no-colon-here") } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
],
},
Signature {
name: "rbac_login",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("username", Ty::Str, "a registered username"),
opt("password", Ty::Str, "the account password; prompted for on a terminal when absent"),
],
returns: "Record",
doc: "Prove an identity with its password and become that principal for this session. The password is checked against an Argon2id hash and is never stored in the clear. Returns {user, user_id, session, expires_at}. Wrong credentials are E_POLICY_DENY, deliberately unspecific. Privileged: refused in agent mode. Without a password argument it reads one from a terminal, and with no terminal it is E_BAD_ARG.",
examples: &[
(r#"try { rbac_login("") } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
(r#"try { rbac_login("example-user-not-registered", "not-a-password") } catch e { e.error.code }"#, r#"E_POLICY_DENY"#),
],
},
Signature {
name: "rbac_principal",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("user", Ty::Str, "the user id to act as; absent reads the current principal")],
returns: "String | Null",
doc: "With an id, act as that user for guard decisions; without one, return the current principal or null. Setting the principal is Privileged. A user with a password cannot be assumed by name: that is E_POLICY_DENY, and the way in is rbac_login. The id must be a non-empty string of at most 256 bytes with no control characters.",
examples: &[
(r#"rbac_principal() == null"#, r#"true"#),
(r#"try { rbac_principal("") } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
],
},
Signature {
name: "rbac_register",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("username", Ty::Str, "the new username, unique in this process"),
opt("password", Ty::Str, "the password; prompted twice on a terminal when absent"),
],
returns: "Record",
doc: "Create a credentialed user whose password is stored as an Argon2id hash. Returns {user, user_id}. The store is in memory: an account lasts for this process only. A username already registered is E_BAD_ARG. An empty password is E_BAD_ARG.",
examples: &[
(r#"try { rbac_register("") } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
(r#"try { rbac_register("", "not-a-password") } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
],
},
Signature {
name: "check_permission",
category: None,
subject_required: false,
aliases: &["has_permission"],
subject: None,
params: &[
req("user", Ty::Str, "the user name"),
req("resource", Ty::Str, "the resource named by a role"),
req("action", Ty::Str, "the action named by a role"),
],
returns: "Bool",
doc: "Whether a user holds, through a role, an action on a resource. False for a user with no roles or a role that is not defined. This is the role store that role_grant writes; the guard does not consult it, so true here does not lift an approval gate. Each argument must be a non-empty string.",
examples: &[
(r#"check_permission("example-user", "example-resource", "read")"#, r#"false"#),
(r#"try { check_permission("", "example-resource", "read") } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
],
},
Signature {
name: "role_grant",
category: None,
subject_required: false,
aliases: &["grant_permission"],
subject: None,
params: &[
req("user", Ty::Str, "the user name"),
req("role", Ty::Str, "a role that role_create defined"),
],
returns: "Record",
doc: "Give a user a defined role. Returns {status, user, role}: status granted when the user did not hold it, or unchanged when it did. An undefined role is E_NOT_FOUND. Only check_permission reads this store, and this builtin is not classified as privileged, so it is not a gate.",
examples: &[
(r#"try { role_grant("example-user", "no-such-role-here") } catch e { e.error.code }"#, r#"E_NOT_FOUND"#),
(r#"try { role_grant("example-user") } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
],
},
Signature {
name: "role_revoke",
category: None,
subject_required: false,
aliases: &["revoke_permission"],
subject: None,
params: &[
req("user", Ty::Str, "the user name"),
req("role", Ty::Str, "the role to take away"),
],
returns: "Record",
doc: "Take a role away from a user, returning {status: revoked, user, role}. A user who does not hold the role is E_NOT_FOUND: nothing was revoked, so nothing is reported as if it were.",
examples: &[
(r#"try { role_revoke("example-user", "no-such-role-here") } catch e { e.error.code }"#, r#"E_NOT_FOUND"#),
(r#"try { role_revoke("example-user") } catch e { e.error.code }"#, r#"E_BAD_ARG"#),
],
},
Signature {
name: "role_delete",
category: None,
subject_required: false,
aliases: &["delete_role"],
subject: None,
params: &[req("name", Ty::Str, "the role to delete")],
returns: "Record",
doc: "Delete a role and take it from every user who held it, so a role created again later does not give its old holders their access back. Returns {status: deleted, role, users_unassigned}. An undefined role is E_NOT_FOUND.",
examples: &[
(r#"try { role_delete("no-such-role-here") } catch e { e.error.code }"#, r#"E_NOT_FOUND"#),
],
},
Signature {
name: "rbac_can",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("permission", Ty::Str, "a permission such as files:read")],
returns: "Bool",
doc: "Whether the current principal holds a permission; false when no principal is set.",
examples: &[
(r#"rbac_can("files:read")"#, r#"false"#),
],
},
Signature {
name: "rbac_session",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record | Null",
doc: "The current login session, or null when anonymous or expired.",
examples: &[
(r#"rbac_session() == null"#, r#"true"#),
],
},
Signature {
name: "perm_set", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("path", Ty::Str, "existing filesystem path"), req("mode", Ty::Any, "Int in 0..=07777 or octal String, optionally prefixed 0o")], returns: "Bool",
doc: "Set Unix mode bits; on Windows set the read-only attribute from the owner-write bit only. Share fs_chmod's strict validation and guarded native implementation while recording perm_set as the mutation name. Return true or a coded refusal. Reject pipeline input. Inside a filesystem transaction, journal the prior permissions so rollback restores them.",
examples: &[(r#"let d = fs_tempdir("ae_perm_set"); let f = d + "/x"; file_write(f, "hi"); let result = perm_set(f, "0644"); rmdir(d, true); result"#, "true"), (r#"let d = fs_tempdir("ae_perm_set_int"); let f = d + "/x"; file_write(f, "hi"); let result = perm_set(f, 384); rmdir(d, true); result"#, "true")],
},
Signature {
name: "perm_check", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("path", Ty::Str, "existing filesystem path, following symlinks"), opt("mode", Ty::Str, "r/read (default), w/write or x/execute")], returns: "Bool",
doc: "Query permission metadata, not effective caller authorization or ACL access. Read returns true when metadata is available; write reports the inverse read-only attribute; execute on Unix reports whether any execute bit is set. On Windows execute is a naming rule, not an ACL check: it is true only for a regular file whose extension (case-insensitive) is listed in PATHEXT, defaulting to .COM;.EXE;.BAT;.CMD when PATHEXT is unset or empty, and it does not consult ACLs. Execute is E_UNIMPLEMENTED on other platforms. Resolve workspace-relative paths and return coded filesystem errors. Refuse unknown modes, ignored arguments and pipeline input.",
examples: &[(r#"let d = fs_tempdir("ae_perm_check"); let f = d + "/x"; file_write(f, "hi"); let result = perm_check(f); rmdir(d, true); result"#, "true"), (r#"let d = fs_tempdir("ae_perm_check_write"); let f = d + "/x"; file_write(f, "hi"); perm_set(f, 384); let result = perm_check(f, "write"); rmdir(d, true); result"#, "true")],
},
Signature {
name: "user_add", category: None, subject_required: false, aliases: &["useradd"],
subject: None, params: &[req("name", Ty::Str, "new user name matching ^[a-z_][a-z0-9_-]{0,31}$"), opt("options", Ty::Record, "{home: Bool, create the home directory, default true; shell: String, absolute path to an existing file; groups: Array<String>, existing groups with gid >= 1000; system: Bool, create a system account, default false; comment: String, no ':' or control characters}")], returns: "Record",
doc: "Create a local account with useradd. Linux and Windows in 14.0.0; other platforms refuse with E_UNIMPLEMENTED and change nothing. Returns {name, uid, gid, home, shell, created_home}. Every input is validated before any effect: the name, the options record, pipeline input (refused) and an active filesystem transaction (refused, because its journal cannot undo account changes). Refusals: an existing user is E_BAD_STATE; a missing group is E_NOT_FOUND; a supplementary group below gid 1000 is E_POLICY_DENY, since such groups (sudo, wheel, docker, root) grant privileges and this builtin never adds a user to one; a shell that is not an existing file is E_BAD_ARG. The tool runs with argv only, never through a shell. It does not set a password (use user_passwd), and it does not configure sudo, SSH keys or account expiry. On Windows the account is created disabled with no password, so it cannot log on until user_passwd sets a password and user_unlock enables it; it returns {name, sid, comment, locked} instead. home, shell, system and groups are E_BAD_ARG there, since Windows creates no profile with the account, has no login shell or system-account class, and assigns identifiers itself.",
examples: &[(r#"(try { user_add("Bad Name") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { user_add("Bad Name", {home: false}) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { useradd("Bad Name") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "user_del", category: None, subject_required: false, aliases: &["userdel"],
subject: None, params: &[req("name", Ty::Str, "existing user name with uid >= 1000"), opt("options", Ty::Record, "{remove_home: Bool, remove the home directory with userdel -r, default false}")], returns: "Record",
doc: "Delete a local account with userdel. Linux and Windows in 14.0.0; other platforms refuse with E_UNIMPLEMENTED and change nothing. Returns {name, removed_home}. Refusals: an account with uid below 1000 and the account running this process are E_POLICY_DENY; a missing user is E_NOT_FOUND; remove_home for a home with fewer than two path components (such as / or /home) is E_POLICY_DENY; an active filesystem transaction is E_POLICY_DENY. A user who is logged in or running processes makes userdel fail with E_TOOL_FAILED. The tool runs with argv only. It does not remove groups the user owned. On Windows it returns {name, removed_home: false}, and remove_home is E_BAD_ARG because Windows leaves the profile folder in place.",
examples: &[(r#"(try { user_del("Bad Name") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { user_del("Bad Name", {remove_home: true}) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { userdel("Bad Name") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "user_mod", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("name", Ty::Str, "existing user name with uid >= 1000"), req("options", Ty::Record, "at least one of {shell: String, absolute path to an existing file; comment: String, no ':' or control characters; home: String, absolute path; move_home: Bool, with home, moves the contents; groups: Array<String>, replaces the supplementary groups; add_groups: Array<String>, appends to them}; groups and add_groups together are refused")], returns: "Record",
doc: "Modify a local account with usermod, in one call. Linux and Windows in 14.0.0; other platforms refuse with E_UNIMPLEMENTED and change nothing. Returns {name, changed}, where changed lists the options applied, in the order shell, comment, home, groups, add_groups. Refusals: uid below 1000 and the running account are E_POLICY_DENY; a missing user or group is E_NOT_FOUND; any supplementary group below gid 1000 is E_POLICY_DENY, both as a replacement (groups) and as an addition (add_groups), because such groups grant privileges and are never joined here; malformed options are E_BAD_ARG. Setting groups to an empty array clears the supplementary groups. The tool runs with argv only. It does not rename the account, change its uid or primary group, or touch its password. On Windows only comment and add_groups apply; add_groups adds the account by SID and an existing membership is not an error. shell, home, move_home and groups are E_BAD_ARG there, and replacing groups is refused because it would have to remove built-in memberships.",
examples: &[(r#"(try { user_mod("Bad Name", {shell: "/bin/sh"}) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { user_mod("ok", {shell: "relative"}) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "user_passwd", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("name", Ty::Str, "existing user name with uid >= 1000"), req("password", Ty::Str, "1 to 1024 bytes, no ':' or control characters")], returns: "Record",
doc: "Set an account's password with chpasswd, which receives the line name:password on standard input only. Linux and Windows in 14.0.0; other platforms refuse with E_UNIMPLEMENTED and change nothing. Returns {name, changed: true}. The password never appears in argv, the environment, or any error: stderr from the tool is redacted before it is reported. Refusals: uid below 1000 and the running account are E_POLICY_DENY; a missing user is E_NOT_FOUND; a malformed password is E_BAD_ARG, with a message that does not repeat it. It does not expire the password or change the account's lock state. On Windows the password is set from one in-memory buffer that is overwritten after the call; a password the machine's policy refuses is E_BAD_ARG, with no password in the message.",
examples: &[(r#"(try { user_passwd("Bad Name", "secret") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { user_passwd("ok", "bad:pw") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "user_lock", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("name", Ty::Str, "existing user name with uid >= 1000")], returns: "Record",
doc: "Lock an account's password with usermod -L. Linux and Windows in 14.0.0; other platforms refuse with E_UNIMPLEMENTED and change nothing. Returns {name, locked: true}. Refusals: uid below 1000 and the running account are E_POLICY_DENY; a missing user is E_NOT_FOUND. Locking does not stop key-based SSH logins. On Windows locking disables the account (UF_ACCOUNTDISABLE), which stops every logon method, and the password is untouched.",
examples: &[(r#"(try { user_lock("Bad Name") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "user_unlock", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("name", Ty::Str, "existing user name with uid >= 1000")], returns: "Record",
doc: "Unlock an account's password with usermod -U. Linux and Windows in 14.0.0; other platforms refuse with E_UNIMPLEMENTED and change nothing. Returns {name, locked: false}. Refusals are the same as user_lock. usermod refuses (E_TOOL_FAILED) when unlocking would leave a password-less account, which is the account's own state and is not overridden here. On Windows unlocking enables the account and leaves the password untouched.",
examples: &[(r#"(try { user_unlock("Bad Name") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "uv_run",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("script", Ty::Str, "a script path or command name; a path must lie inside the workspace and a leading '-' is refused"), opt_rest("args", Ty::Str, "arguments passed to the script after its name; each must be a String")],
returns: "Record",
doc: "Runs `uv run <script> <args...>` in the working directory, with no shell. Returns {exit_code: 0, success: true, stdout, stderr}; a nonzero exit is E_TOOL_FAILED carrying the tail of the output. Deadline 10 minutes; a missing uv is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | uv_run("a.py") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { uv_run("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "uv_pip",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("subcommand", Ty::Str, "one of install, uninstall, list, freeze, show, check, tree; defaults to install"), opt_rest("packages", Ty::Str, "package specs for the subcommand: names, versions or remote URLs; file: and link: specs are refused and a spec that names a path must lie inside the workspace")],
returns: "Record",
doc: "Runs `uv pip <subcommand> <packages...>` with no shell. install and uninstall have a 15 minute deadline and the other subcommands 2 minutes. Returns {subcmd, exit_code: 0, success: true, stdout, stderr}; a nonzero exit is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | uv_pip() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { uv_pip("compile") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "uv_venv",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("path", Ty::Str, "where to create the environment; inside the workspace; defaults to .venv")],
returns: "Record",
doc: "Runs `uv venv <path>`, creating a virtual environment. The path must lie inside the workspace and is refused when option-like. Returns {path, exit_code: 0, success: true, stdout, stderr}. Deadline 2 minutes. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | uv_venv() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { uv_venv("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "group_add", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("name", Ty::Str, "new group name matching ^[a-z_][a-z0-9_-]{0,31}$"), opt("options", Ty::Record, "{gid: Int, 1000 to 60000; system: Bool, take a system gid below 1000 with groupadd -r; gid and system together are refused}")], returns: "Record",
doc: "Create a local group with groupadd. Linux and Windows in 14.0.0; other platforms refuse with E_UNIMPLEMENTED and change nothing. Returns {name, gid}. Refusals: an existing group is E_BAD_STATE; a gid outside 1000 to 60000, or gid with system, is E_BAD_ARG; an active filesystem transaction is E_POLICY_DENY. The tool runs with argv only. A system group created with system is below 1000 and is therefore never changed by group_mod or group_del. On Windows it returns {name, sid}; gid and system are E_BAD_ARG, since Windows assigns the identifier.",
examples: &[(r#"(try { group_add("Bad Name") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { group_add("Bad Name", {gid: 5000}) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "group_del", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("name", Ty::Str, "existing group name with gid >= 1000")], returns: "Record",
doc: "Delete a local group with groupdel. Linux and Windows in 14.0.0; other platforms refuse with E_UNIMPLEMENTED and change nothing. Returns {name}. Refusals: a group with gid below 1000 is E_POLICY_DENY; a missing group is E_NOT_FOUND. groupdel fails (E_TOOL_FAILED) when the group is some account's primary group. On Windows a BUILTIN group is E_POLICY_DENY, as is any group whose RID is below 1000.",
examples: &[(r#"(try { group_del("Bad Name") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "group_mod", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("name", Ty::Str, "existing group name with gid >= 1000"), req("options", Ty::Record, "at least one of {new_name: String, matching the name rule; gid: Int, 1000 to 60000}")], returns: "Record",
doc: "Rename a local group and/or change its gid with groupmod. Linux and Windows in 14.0.0; other platforms refuse with E_UNIMPLEMENTED and change nothing. Returns {name, changed}; name is the group's name after the change, and changed lists new_name and/or gid. Refusals: a group below gid 1000 is E_POLICY_DENY; a missing group is E_NOT_FOUND; a new_name already in use is E_BAD_STATE; a gid outside 1000 to 60000 or a new_name equal to the current one is E_BAD_ARG. groupmod fails (E_TOOL_FAILED) when the new gid is already in use. On Windows only new_name applies, returning changed [new_name]; gid is E_BAD_ARG.",
examples: &[(r#"(try { group_mod("Bad Name", {gid: 5000}) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { group_mod("ok", {gid: 5}) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "crypto_cert_info", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("path", Ty::Str, "regular certificate file, at most 64 MiB: PEM with one or more CERTIFICATE blocks, or one DER certificate")], returns: "Array",
doc: "Certificate details from IronSocketLayer's X.509 (IronPKI, pure Rust over IronCrypto); no openssl or other process, on every OS. Returns an Array of Records, one per certificate in file order. A file that contains -----BEGIN CERTIFICATE----- is read as PEM: each CERTIFICATE block must decode strictly and any other PEM label is skipped; otherwise the whole file is one DER certificate. Fields: subject and issuer (RFC 4514 strings: CN, O, OU, C, ST, L, emailAddress, serialNumber and DC by short name, other attributes as dotted-OID=#hex; last RDN first), subject_cn and issuer_cn (String or Null), serial (lowercase hex of the INTEGER contents), not_before and not_after (RFC 3339 UTC), not_before_unix and not_after_unix (Int), dns_names, uri_names and ip_addresses (Arrays of String), is_ca and self_issued (Bool; self_issued is issuer DER equal to subject DER), public_key (Record {algorithm, bits}: algorithm is rsa, ecdsa-p256, ecdsa-p384, ecdsa-p521, ed25519, ml-dsa-44, ml-dsa-65, ml-dsa-87 or unknown; bits is the RSA modulus or curve size, 256 for Ed25519, Null for ML-DSA and unknown), signature_algorithm (the outer signature's IronPKI scheme id, or unsupported), sha256_fingerprint (lowercase hex of SHA-256 over the DER) and extension_count (Int). NOT reported, because IronPKI does not expose them: key usage, extended key usage, subject and authority key identifiers, path length, and email subject alternative names. A non-certificate file, or a CERTIFICATE block that fails to decode or parse, is E_BAD_ARG naming its 1-based index; more than 1000 certificates is E_BUDGET_EXCEEDED. Resolve relative paths against the configured workspace; reject option-like paths, surplus arguments and pipeline input. Missing files are E_NOT_FOUND; a path that is not a regular file is E_BAD_ARG.",
examples: &[(r#"crypto_cert_info("/etc/ssl/certs/ca-certificates.crt")"#, "[{subject_cn: ..., not_after: ..., is_ca: true, ...}]")],
},
Signature {
name: "crypto_sign", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("private_key", Ty::Str, "one unencrypted PEM envelope, at most 16384 bytes: PRIVATE KEY (PKCS#8: Ed25519 v2, ECDSA P-256 or P-384, or RSA), RSA PRIVATE KEY (PKCS#1 RSA) or EC PRIVATE KEY (SEC1 P-256 or P-384 with its public key)"), req("message", Ty::Any, "UTF-8 String or Array of byte Ints 0..255, at most 1 MiB")], returns: "Record",
doc: "Native signing of exact message bytes with IronCrypto (pure Rust, no dependencies); no OpenSSL or subprocess. Return {algorithm, public_key: String, signature: String}. algorithm is ed25519 (Ed25519 signature, 64 bytes), ecdsa-p256-sha256 or ecdsa-p384-sha384 (ECDSA with an ASN.1 DER signature, deterministic per RFC 6979: the same key and message always give the same signature), or rsa-pkcs1-sha256 (RSASSA-PKCS1-v1_5 with SHA-256, the output of openssl dgst -sha256 -sign; deterministic). public_key is the canonical padded standard Base64 of the raw key: 32 bytes for Ed25519, an uncompressed point 0x04||X||Y of 65 or 97 bytes for P-256 or P-384, or the DER RSAPublicKey. signature is canonical padded standard Base64. RSA private keys must have a 2048 to 4096-bit modulus with public exponent at least 65537 (IronCrypto's limits); larger RSA keys and other curves are E_BAD_ARG. Ed25519 PKCS#8 must be v2 with a public key that agrees with its seed. Do not interpret key Strings as paths. No file I/O, subprocess, model or key registry. Decoded PEM/DER temporary buffers are zeroized; caller key Strings and library-internal key storage have no promised wiping. IRONSHELL_FIPS refuses this native backend with E_POLICY_DENY because it is not FIPS validated, before any key is parsed. Shape, malformed key/message and size errors are coded; pipeline input rejects. Empty messages are valid. Pure effect classification retained.",
examples: &[(r#"typeof(crypto_sign(crypto_generate_key("ed25519"), "example"))"#, "Record"), (r#"crypto_sign(crypto_generate_key("ec"), "example").algorithm"#, "ecdsa-p256-sha256")],
},
Signature {
name: "crypto_verify_signature", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("public_key", Ty::Str, "canonical padded standard Base64 of raw key bytes as crypto_sign returns them (32 Ed25519 bytes; 65 or 97 uncompressed P-256 or P-384 point bytes starting 0x04; DER RSAPublicKey starting 0x30), or a BEGIN PUBLIC KEY SPKI PEM (Ed25519, ECDSA P-256 or P-384, rsaEncryption); at most 4096 bytes"), req("message", Ty::Any, "UTF-8 String or Array of byte Ints 0..255, at most 1 MiB"), req("signature", Ty::Str, "canonical padded standard Base64 signature: 64 bytes for Ed25519, 1 to 72 bytes of DER for P-256, 1 to 104 bytes of DER for P-384, 1 to 512 bytes for RSA; text at most 1400 bytes")], returns: "Bool",
doc: "Native verification of exact message bytes with IronCrypto; no OpenSSL or subprocess. Return true only for a valid signature. A well-formed signature that does not verify (wrong message, wrong key, tampered bytes, or an RSA signature of the wrong length) returns false, and so does an EC point that is not on its curve. Malformed input is a coded E_BAD_ARG: bad Base64, a public key that is neither a supported raw encoding nor a supported SPKI PEM (unsupported OIDs and curves such as secp256k1 are named in the message), an RSA public key outside 2048 to 4096 bits, a signature whose length does not fit the key's algorithm, or invalid call shapes. Algorithms: Ed25519 (no prehash), ECDSA P-256 with SHA-256 and P-384 with SHA-384 (ASN.1 DER signatures), RSASSA-PKCS1-v1_5 with SHA-256 (2048 to 4096-bit modulus, public exponent 65537 to 2^33 - 1). The key's algorithm, not a label, selects the verifier. Empty messages are valid. Only these algorithms are supported, without certificate or trust identity resolution, PSS, prehash variants or implicit key loading. IRONSHELL_FIPS refuses this native backend with E_POLICY_DENY, before any input is parsed. No files, processes or key registry; direct-only and Pure.",
examples: &[(r#"key = crypto_generate_key("ed25519"); signed = crypto_sign(key, "example"); crypto_verify_signature(signed.public_key, "example", signed.signature)"#, "true")],
},
Signature {
name: "crypto_generate_key", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt("type", Ty::Str, "rsa (default), ec, ecdsa or ed25519; case insensitive"), opt("bits", Ty::Int, "RSA-only size: 2048, 3072 or 4096; default 2048")], returns: "String",
doc: "Private-key PEM text: an unencrypted PKCS#8 PRIVATE KEY document (-----BEGIN PRIVATE KEY----- with 64-column Base64 lines), generated natively by IronCrypto on every platform with no openssl or other subprocess. rsa generates a 2048, 3072 or 4096-bit key (default 2048); ec and ecdsa generate a P-256 key; ed25519 generates an Ed25519 key. Randomness comes from the operating system through IronCrypto's Rng::from_os. The output is accepted by crypto_sign. Any other RSA size, including sizes the previous openssl path allowed, is E_BAD_ARG, as is a bit size given for a non-RSA type. Unsupported types, wrong types, surplus arguments and pipeline input are E_BAD_ARG. Generation is refused with E_POLICY_DENY under IRONSHELL_FIPS, because the native backend is not FIPS validated; this now covers RSA and EC as well as Ed25519. No file is written. Existing conservative WriteLocal classification is retained.",
examples: &[("crypto_generate_key()", "PEM private key"), (r#"crypto_generate_key("rsa")"#, "PEM private key"), (r#"crypto_generate_key("rsa", 2048)"#, "PEM private key"), (r#"crypto_generate_key("ec")"#, "PEM private key"), (r#"typeof(crypto_generate_key("ed25519"))"#, "String")],
},
Signature {
name: "crypto_password_hash", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("password", Ty::Str, "password, at most 65536 bytes")], returns: "String",
doc: "Native salted Argon2id PHC hash; IRONSHELL_FIPS algorithm policy uses PBKDF2-HMAC-SHA256 with 600000 iterations. Fresh 16-byte salt. No subprocess or unsalted fallback. Reject pipeline input and surplus arguments.",
examples: &[(r#"typeof(crypto_password_hash("example"))"#, "String")],
},
Signature {
name: "crypto_password_verify", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("password", Ty::Str, "password"), req("hash", Ty::Str, "stored PHC hash, at most 1024 bytes")], returns: "Bool",
doc: "Verify stored salt and bounded Argon2id or PBKDF2-SHA256 parameters, or a SHA-crypt $5$/$6$ hash per Drepper's specification (verify only; rounds above 1000000 are refused with E_BUDGET_EXCEEDED; refused under IRONSHELL_FIPS, where only PBKDF2 is accepted). False means mismatch; malformed, unsupported or excessive parameters produce coded errors. Legacy SHA256 hex is verify-only outside algorithm-policy mode and should be rehashed. Reject pipeline input and surplus arguments.",
examples: &[(r#"crypto_password_verify("example", crypto_password_hash("example"))"#, "true")],
},
Signature {
name: "sudo_check", category: None, subject_required: false, aliases: &[],
subject: None, params: &[], returns: "Bool",
doc: "Inspect current effective privileges: Unix effective UID zero, or the Windows current-token Administrator role through a noninteractive PowerShell query without profiles. This does not test sudo configuration or acquire privileges. Reject arguments and pipeline input. Report failed subprocesses and malformed output with codes rather than false; unsupported platforms refuse explicitly.",
examples: &[("sudo_check()", "false")],
},
Signature {
name: "sudo_exec", category: None, subject_required: false, aliases: &[],
subject: None,
params: &[req("command", Ty::Array, "argv: non-empty Array of String; argv[0] must not start with '-'; no NUL; at most 256 elements of at most 4096 bytes"), opt("options", Ty::Record, "optional {timeout_ms: Int 100..600000, default 60000}")],
returns: "Record",
doc: "Linux and macOS: runs `sudo -n -- argv...` with stdin closed, so sudo never prompts: a password requirement is refused with E_POLICY_DENY and nothing runs. Windows has no sudo, and IronShell never shows a UAC prompt, so argv runs directly (no shell) only when this process is already elevated: argv[0] must then be an absolute path, such as C:\\Windows\\System32\\whoami.exe, and a relative argv[0] is E_BAD_ARG. A process that is not elevated is refused with E_POLICY_DENY and nothing runs. Returns {exit_code: Int or Null (Null on timeout or signal), stdout: String, stderr: String (each the last 64 KiB), timed_out: Bool}. A nonzero exit of the command is reported in exit_code, not as an error. On timeout the sudo process group (on Windows, the command's job object and its tree) is killed and timed_out is true. Refused inside a transaction, which cannot roll back a command. Other platforms refuse with E_UNIMPLEMENTED and run nothing.",
examples: &[
(r#"(try { sudo_exec([]) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { sudo_exec([], {timeout_ms: 5}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "acl_get", category: None, subject_required: false, aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "existing file or directory whose ACL is read")],
returns: "Record",
doc: "Read the POSIX access and default ACL of path on Linux with getfacl --absolute-names, using names rather than numeric IDs. Returns {path, owner, group, entries}, where owner and group are Strings and entries is an Array of records {tag, qualifier, perms, default}. tag is user, group, mask or other; qualifier is the user or group name, or null for the unnamed owner, group, mask and other entries; perms is a three-character rwx- String; default is true for entries of the default ACL. Setuid, setgid and sticky bits are not reported. A missing path is E_NOT_FOUND, and an output line the parser does not recognise is E_TOOL_FAILED. On Windows it runs icacls and returns {path, entries} with no owner or group, where each entry is {principal, perms, inherited, flags, deny} and an unrecognised icacls line is E_TOOL_FAILED. On other platforms the call is E_UNIMPLEMENTED and NOTHING WAS READ. A call inside a filesystem transaction is refused with E_POLICY_DENY. The effect is ReadLocal: nothing is changed.",
examples: &[(r#"(try { acl_get(1) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "acl_set", category: None, subject_required: false, aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "existing file or directory"), req("entry", Ty::Str, "one ACL entry: tag:qualifier:perms such as u:nobody:r-- or u::rw-; with remove, tag:qualifier such as u:nobody"), opt("options", Ty::Record, "Record with optional default Bool (set the default ACL; path must be a directory) and remove Bool (delete the named user or group entry)")],
returns: "Record",
doc: "Change the POSIX ACL of path on Linux with setfacl -m, or -x with remove, and -d with default, placing -- before the path. The entry is validated strictly before anything runs. The tag is u, g, m or o, or user, group, mask or other. The qualifier is empty or a lowercase name matching [a-z_][a-z0-9_-]*, and must be empty for m and o. The perms are exactly three characters from rwx-. Numeric IDs are refused. With remove, the entry is u:name or g:name with no perms, and the base entries cannot be removed. Returns {path, entry, applied: true}, where entry is the normalized form passed to setfacl. A bad entry or option, a default ACL on a non-directory, and a missing path are E_BAD_ARG or E_NOT_FOUND, and change nothing; a non-zero setfacl exit is E_TOOL_FAILED. On Windows it runs icacls /grant with an entry such as Users:F, or icacls /remove with a bare principal when remove is set, refuses default and the Linux tag:qualifier:perms form with E_BAD_ARG, and is not undoable. On macOS it runs ls -led to read the ACL, and chmod +a, or chmod -a when remove is set, with an entry such as user:nobody allow read,write or group:staff deny delete (user or group, allow or deny, then comma-separated perms from read, write, execute, delete, append, list, search and the other names ls -le prints); a removal of an entry that is not there is E_NOT_FOUND, and default is refused with E_BAD_ARG. On other platforms the call is E_UNIMPLEMENTED and NOTHING WAS CHANGED. A call inside a filesystem transaction is refused with E_POLICY_DENY. ACL changes are not recorded by the undo journal, so undo does not reverse them; reverse a named entry with acl_set and remove. The effect is Privileged. Not done: numeric IDs, recursive changes, the setfacl -n mask-recalculation switch, and removal of base entries.",
examples: &[
(r#"(try { acl_set("/", "bogus") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { acl_set("/", "u::rw-", {default: 1}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "act_run",
category: None,
subject_required: false,
aliases: &["act"],
subject: None,
params: &[opt("event", Ty::Str, "the event whose workflows run, such as push; default push")],
returns: "Record",
doc: "act: runs GitHub Actions workflows locally, in Docker containers, for an event. Returns {event, exit_code, success, stdout, stderr} when an event is named, else the same without event. A nonzero exit is E_TOOL_FAILED. Runs with a 15 minute deadline. Takes no pipeline input.",
examples: &[
(r#"(try { act_run("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { act_run("push", "x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "perm_get",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a file path")],
returns: "String",
doc: "A path's permissions: octal mode bits on Unix, readonly or readwrite on Windows.",
examples: &[
(r#"typeof(perm_get("Cargo.toml"))"#, r#"String"#),
],
},
Signature {
name: "rlm_stats",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("run", Ty::Record, "the record an rlm run returned")],
returns: "Record",
doc: "Statistics of this session's last recursive-agent run as {runs, last_run}; last_run is null before any run. Given a run's record, returns it.",
examples: &[
(r#"typeof(rlm_stats())"#, r#"Record"#),
(r#"rlm_stats({total_spawned: 2}).total_spawned"#, r#"2"#),
],
},
Signature {
name: "pkg_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Installed packages as {name, version} Records, sorted by name. On apt systems it runs dpkg-query and on Arch it runs pacman -Q, each as an argv with no shell; on Windows it lists the Add/Remove Programs entries (64-bit and 32-bit machine keys and the current user's, without system components or updates), whose version is Null when a program records none. Each runs under a 60 s limit and a 64 MiB output cap. Takes no arguments and no pipeline input. Other package managers (dnf, yum, brew) are E_UNIMPLEMENTED and NOTHING WAS LISTED. A missing tool is E_TOOL_MISSING, a nonzero exit E_TOOL_FAILED, and a run over its limit or cap E_BUDGET_EXCEEDED.",
examples: &[
(r#"(try { pkg_list("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { pkg_list(1, 2) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
// 1b: package-manager queries. Machine-dependent: see MACHINE_DEPENDENT in
// tests/declared_signatures.rs; the results shown are Debian's.
Signature {
name: "pkg_info",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("package", Ty::Str, "a package name")],
returns: "Record",
doc: "A package's metadata, as the package manager reports it. Unsupported package managers are E_UNIMPLEMENTED; a package the manager does not know is E_TOOL_FAILED.",
examples: &[
(r#"pkg_info("coreutils")"#, r#"{package: coreutils, version: 9.4-3.1, ...}"#),
],
},
Signature {
name: "pkg_files",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("package", Ty::Str, "a package name")],
returns: "Array",
doc: "Files an installed package owns (apt, pacman). Unsupported package managers are E_UNIMPLEMENTED; a package the manager does not know is E_TOOL_FAILED.",
examples: &[
(r#"pkg_files("coreutils")"#, r#"[/usr, /usr/bin, /usr/bin/ls, ...]"#),
],
},
Signature {
name: "pkg_deps",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("package", Ty::Str, "a package name")],
returns: "Array",
doc: "A package's dependencies as {kind, package, alternative} (apt, pacman). Unsupported package managers are E_UNIMPLEMENTED; a package the manager does not know is E_TOOL_FAILED.",
examples: &[
(r#"pkg_deps("coreutils")"#, r#"[{alternative: false, kind: PreDepends, package: libacl1}, ...]"#),
],
},
Signature {
name: "pkg_rdeps",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("package", Ty::Str, "a package name")],
returns: "Array",
doc: "Packages that depend on a package (apt, pacman). Unsupported package managers are E_UNIMPLEMENTED; a package the manager does not know is E_TOOL_FAILED.",
examples: &[
(r#"pkg_rdeps("coreutils")"#, r#"[chkrootkit, dgit, ...]"#),
],
},
Signature {
name: "pkg_verify",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("package", Ty::Str, "a package name")],
returns: "Bool",
doc: "Whether an installed package's files match what was installed (apt: dpkg -V). Unsupported package managers are E_UNIMPLEMENTED; a package the manager does not know is E_TOOL_FAILED.",
examples: &[
(r#"pkg_verify("coreutils")"#, r#"true"#),
],
},
Signature {
name: "pkg_owner",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "an absolute file path")],
returns: "Record",
doc: "The installed package that owns a file (apt, pacman). Unsupported package managers are E_UNIMPLEMENTED; a package the manager does not know is E_TOOL_FAILED.",
examples: &[
(r#"pkg_owner("/usr/bin/ls")"#, r#"{file: /usr/bin/ls, package: coreutils}"#),
],
},
Signature {
name: "pkg_search",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("query", Ty::Str, "text to search package names and descriptions for")],
returns: "Array",
doc: "Available packages matching a query, as {name, description}. Unsupported package managers are E_UNIMPLEMENTED; a package the manager does not know is E_TOOL_FAILED.",
examples: &[
(r#"pkg_search("coreutils")"#, r#"[{description: GNU core utilities, name: coreutils}, ...]"#),
],
},
// 1b: binary inspection, toolchain and SDK versions, groups, GPG keys.
// Machine-dependent (MACHINE_DEPENDENT in tests/declared_signatures.rs);
// results shown are Debian's.
Signature {
name: "objdump_disasm",
category: None,
subject_required: false,
aliases: &["objdump"],
subject: None,
params: &[req("path", Ty::Str, "a binary file")],
returns: "Record",
doc: "Disassembly of a binary as {path, disassembly}. A missing tool is E_TOOL_MISSING; a file it cannot read is E_TOOL_FAILED.",
examples: &[
(r#"objdump("/bin/true")"#, r#"{disassembly: "/bin/true: file format elf64-x86-64 ...", path: /bin/true}"#),
],
},
Signature {
name: "objdump_headers",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a binary file")],
returns: "Record",
doc: "A binary's section headers as {path, headers}. A missing tool is E_TOOL_MISSING; a file it cannot read is E_TOOL_FAILED.",
examples: &[
(r#"objdump_headers("/bin/ls")"#, r#"{headers: "Sections: ...", path: /bin/ls}"#),
],
},
Signature {
name: "readelf_headers",
category: None,
subject_required: false,
aliases: &["readelf"],
subject: None,
params: &[req("path", Ty::Str, "a binary file")],
returns: "Record",
doc: "An ELF file's header as {path, headers}. A missing tool is E_TOOL_MISSING; a file it cannot read is E_TOOL_FAILED.",
examples: &[
(r#"readelf("/bin/ls")"#, r#"{headers: "ELF Header: ...", path: /bin/ls}"#),
],
},
Signature {
name: "readelf_sections",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a binary file")],
returns: "Record",
doc: "An ELF file's section table as {path, sections}. A missing tool is E_TOOL_MISSING; a file it cannot read is E_TOOL_FAILED.",
examples: &[
(r#"readelf_sections("/bin/ls")"#, r#"{path: /bin/ls, sections: "There are 31 section headers ..."}"#),
],
},
Signature {
name: "strace_cmd", category: None, subject_required: false, aliases: &["strace"], subject: None,
params: &[req("command", Ty::Str, "program and arguments separated by spaces; no shell and no quoting")], returns: "Record",
doc: "Trace the system calls of one program with strace -c, and summarise them as {command, exit_code, stdout, raw, syscalls, unparsed_rows}. The command is split on whitespace and run directly; its program may not begin with '-'. The exit code is the traced program's and is data. macOS uses dtruss. A missing tracer is E_TOOL_MISSING. The run has a 120 s deadline.",
examples: &[
(r#"(try { strace_cmd("-p 1") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { strace_cmd("") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ltrace_cmd", category: None, subject_required: false, aliases: &["ltrace"], subject: None,
params: &[req("command", Ty::Str, "program and arguments separated by spaces; no shell and no quoting")], returns: "Record",
doc: "Trace the library calls of one program with ltrace -c, returning {command, exit_code, stdout, trace, stdout_truncated}. The command is split on whitespace and run directly; its program may not begin with '-'. The exit code is the traced program's and is data. A missing ltrace is E_TOOL_MISSING. The run has a 120 s deadline.",
examples: &[
(r#"(try { ltrace_cmd("-p 1") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ltrace_cmd("") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "lldb_run", category: None, subject_required: false, aliases: &["lldb"], subject: None,
params: &[req("program", Ty::Str, "path of an existing program; a leading '-' is refused")], returns: "Record",
doc: "Run one program under LLDB in batch mode, and return {program, output} with the backtrace if it stops. The program runs with stdin closed and a 120 s deadline. Running a program is an execution effect. A nonzero exit is E_TOOL_FAILED and a missing lldb is E_TOOL_MISSING.",
examples: &[
(r#"(try { lldb_run("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { lldb_run("") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "nm_symbols", category: None, subject_required: false, aliases: &["nm"], subject: None,
params: &[req("path", Ty::Str, "an existing object file or executable; a leading '-' is refused")], returns: "Array",
doc: "List the symbols of an object file with nm --demangle, as an Array of {address, type, name}. An undefined symbol has no address, so its address is null. Output past 4 MiB is E_BUDGET_EXCEEDED, and a missing nm is E_TOOL_MISSING.",
examples: &[
(r#"(try { nm_symbols("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { nm_symbols("") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "rustup_show",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The installed Rust toolchains, as rustup show reports them. A missing tool is E_TOOL_MISSING; a file it cannot read is E_TOOL_FAILED.",
examples: &[
(r#"rustup_show()"#, r#"Default host: x86_64-unknown-linux-gnu ..."#),
],
},
Signature {
name: "rustup_update",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "rustup update, which fetches and installs the Rust toolchains and components. Returns {exit_code, success, stdout, stderr}; a nonzero exit is E_TOOL_FAILED. Takes no arguments and no pipeline input.",
examples: &[
(r#"(try { rustup_update("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "platform_tool_version",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("tool", Ty::Str, "a program name such as git")],
returns: "String | Null",
doc: "A program's version line, or null when it is not on PATH.",
examples: &[
(r#"platform_tool_version("git")"#, r#"git version 2.47.2"#),
],
},
Signature {
name: "platform_lib_version",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("library", Ty::Str, "a pkg-config module such as zlib")],
returns: "String | Null",
doc: "A library's version from pkg-config, or null when pkg-config does not know it. No pkg-config is E_TOOL_MISSING.",
examples: &[
(r#"platform_lib_version("zlib")"#, r#"1.3.1"#),
],
},
Signature {
name: "platform_sdk_version",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("sdk", Ty::Str, "android, ios, macos, xcode, windows, dotnet, java or jdk")],
returns: "String | Array | Null",
doc: "The installed version(s) of an SDK, or null when it is not installed. An unknown SDK name is refused.",
examples: &[
(r#"platform_sdk_version("java")"#, r#"null"#),
],
},
Signature {
name: "group_members",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("group", Ty::Str, "a group name")],
returns: "Array",
doc: "A group's members. An unknown group is E_NOT_FOUND (E_TOOL_FAILED on Windows).",
examples: &[
(r#"group_members("root")"#, r#"[]"#),
],
},
Signature {
name: "gpg_list_keys",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "The public keys in the gpg keyring as records.",
examples: &[
(r#"gpg_list_keys()"#, r#"[]"#),
],
},
// 1c: encryption and certificate tools. Each refuses an option-like path,
// refuses to overwrite, and runs its tool under a deadline with bounded
// output. A nonzero exit is E_TOOL_FAILED with the stderr tail. The
// examples are refusals that happen before any tool starts.
Signature {
name: "gpg_encrypt",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("file", Ty::Str, "the file to encrypt"),
req("recipient", Ty::Str, "a key id, fingerprint or user id in the keyring"),
],
returns: "Record",
doc: "Encrypt a file to one recipient into file.gpg with gpg --batch --no-tty. The output is refused if it exists, and a failed run removes its partial output. Returns {action, input_file, output_file, recipient, raw}. The keyring is the caller's own; no passphrase is taken on the command line.",
examples: &[
(r#"(try { gpg_encrypt("-x", "alice") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { gpg_encrypt("notes.txt", "-oX") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "gpg_decrypt",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("file", Ty::Str, "a .gpg or .asc file")],
returns: "Record",
doc: "Decrypt a .gpg or .asc file to the same name without that suffix, or to name.decrypted. The plaintext is written to that file and is never returned. An existing output is refused. gpg runs with --batch and --no-tty, and a passphrase prompt is cut off by the deadline. Returns {action, input_file, output_file}.",
examples: &[
(r#"(try { gpg_decrypt("-x.gpg") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "age_encrypt",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("input_file", Ty::Str, "the file to encrypt"),
req("output_file", Ty::Str, "the encrypted file to create; must not exist"),
req("recipient", Ty::Str, "an age1... or ssh- public key"),
],
returns: "Record",
doc: "Encrypt a file to one recipient with age. The output is refused if it exists, and a failed run removes its partial output. Returns {input, output, recipient, status}.",
examples: &[
(r#"(try { age_encrypt("notes.txt", "out.age", "not-a-key") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { age_encrypt("-x", "out.age", "age1example") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "age_decrypt",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("input_file", Ty::Str, "a file encrypted to the identity"),
opt("output_file", Ty::Str, "the plaintext file; default input_file without .age"),
opt("identity_file", Ty::Str, "the age identity file; default ~/.age/key.txt"),
],
returns: "Record",
doc: "Decrypt a file with an age identity. Without an output_file the input must end in .age. The output must differ from the input and must not exist. Returns {input, output, status}. The plaintext is written to the file and is not returned.",
examples: &[
(r#"(try { age_decrypt("plain.bin") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { age_decrypt("-i", "key.txt") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { age_decrypt("x.age", "y.txt", "-i") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "age_keygen",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("output_file", Ty::Str, "the new identity file; the private key is written there and never returned")],
returns: "Record",
doc: "Generate an age identity into a new file and return {public_key, identity_file, status}. The private key is never returned, so no form of this builtin prints it. An existing file is refused, and a failed run removes the file.",
examples: &[
(r#"(try { age_keygen() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { age_keygen("-o") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "openssl_cert_info",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("file", Ty::Str, "a PEM or DER certificate")],
returns: "Record",
doc: "Read a certificate's subject, issuer, validity, serial number and key and signature algorithms with openssl x509 -text -noout, with the raw text. Read-only, under a deadline. A private key given here is an openssl error.",
examples: &[
(r#"(try { openssl_cert_info("-noout") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "openssl_genrsa",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("file", Ty::Str, "the new private key file; must not exist"),
opt_range("bits", Ty::Int, 2048, 16384, "the modulus size; default 4096"),
],
returns: "Record",
doc: "Generate an RSA private key into a new file with openssl genrsa. The key is NOT encrypted. The file is refused if it exists and removed if the run fails. The key is never returned. Returns {action, file, bits, raw}.",
examples: &[
(r#"(try { openssl_genrsa("key.pem", 1024) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { openssl_genrsa("-engine") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
// 1b: disk usage, process info, diagnostics, docs search, pager, the
// platform key-value store. proc_info, diag_explain and docs_search are
// machine-dependent; the rest must give the result shown everywhere.
Signature {
name: "platform_disk_usage",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("path", Ty::Str, "any path on the disk; default the current directory")],
returns: "Record",
doc: "Size, free and used space of the disk holding a path, with its mount point.",
examples: &[
(r#"platform_disk_usage().total_bytes > 0"#, r#"true"#),
(r#"platform_disk_usage("src").total_bytes > 0"#, r#"true"#),
],
},
Signature {
name: "proc_info",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pid", Ty::Any, "a positive process id, Int or numeric String")],
returns: "Record",
doc: "A process as {pid, name, state, ppid, memory_bytes, start_time, exe}. An unknown pid is E_NOT_FOUND.",
examples: &[
(r#"proc_info(1)"#, r#"{name: systemd, pid: 1, ppid: null, state: Sleeping, ...}"#),
],
},
Signature {
name: "proc_kill",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("pid", Ty::Any, "a positive process id, Int or numeric String"),
opt("signal", Ty::Any, "TERM (default), KILL, HUP, INT, QUIT, STOP or CONT, by name or number"),
opt("options", Ty::Record, "Record {tree: Bool}, tree false by default; any other key, or a non-Bool tree, is E_BAD_ARG"),
],
returns: "Record",
doc: "Sends a signal to a process: {pid, signal, sent: true} on success. Unix uses kill(2) directly; Windows sends TERM (graceful, which a console process refuses) or KILL (forced, taskkill /F), and other signals are E_UNIMPLEMENTED there. A pid of 0 or less, a pid that does not fit the OS, this shell's own pid, and pipeline input are E_BAD_ARG; a process that does not exist is E_NOT_FOUND; a process owned by another user is E_OS_DENIED. With options {tree: true} the target and all its descendants are signalled: the descendants are read before any signal, by parent pid, and each is checked as the target is (a tree that contains this shell is E_BAD_ARG); more than 4096 descendants is E_BUDGET_EXCEEDED before anything is sent. A descendant that has already exited is skipped. The signal goes to each process in turn, deepest first and the target last, so a parent cannot respawn a child; an EPERM on a descendant stops the walk and the earlier ones are not undone. On Windows taskkill /PID /T runs once (with /F for KILL). The tree result also has killed: [pids] in the order signalled. Default tree false signals the target alone, as before.",
examples: &[
(r#"(try { proc_kill(0) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
(r#"(try { proc_kill(0, "TERM", {tree: "yes"}) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
(r#"(try { proc_kill(1, "BOGUS") } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
],
},
// proc_* (process management). The readers answer for a live pid and say
// E_NOT_FOUND for one that is not; their examples are refusals, which need
// no live process. proc_list, proc_children and proc_parent answer for pid
// 1, which is live on Unix and absent on Windows, so they are machine-
// dependent. The mutators' examples are refusals only.
Signature {
name: "proc_list",
category: None,
subject_required: false,
aliases: &["ps"],
subject: None,
params: &[],
returns: "Array",
doc: "Every process as {pid, name, cpu, mem, command}. mem is resident bytes. cpu is percent of one CPU from ps on Unix, and total CPU seconds on Windows, so the unit differs by OS. A failed listing is E_TOOL_FAILED; arguments and pipeline input are E_BAD_ARG.",
examples: &[
(r#"proc_list()"#, r#"[{command: systemd, cpu: 0.0, mem: 13000000, name: systemd, pid: 1}, ...]"#),
],
},
Signature {
name: "top_snapshot", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt_range("count", Ty::Int, 1, 10000, "processes to return, largest resident memory first, default 30")], returns: "Array",
doc: "A process snapshot as an Array of {pid, name, cpu_percent, memory_bytes, memory_mb}, largest resident memory first. CPU use is measured across one sampling interval. Takes no pipeline input.",
examples: &[
(r#"(try { top_snapshot(0) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { top_snapshot(1, 2) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "proc_children",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pid", Ty::Any, "a positive process id, Int or numeric String")],
returns: "Array",
doc: "The child process ids of a live process, as Ints; an empty array when it has none. A pid that is not live is E_NOT_FOUND; a pid that is not positive is E_BAD_ARG.",
examples: &[
(r#"proc_children(1)"#, r#"[]"#),
],
},
Signature {
name: "proc_parent",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pid", Ty::Any, "a positive process id, Int or numeric String")],
returns: "Int | Null",
doc: "The parent process id of a live process; null when the OS reports none. A pid that is not live is E_NOT_FOUND; a pid that is not positive is E_BAD_ARG.",
examples: &[
(r#"proc_parent(1)"#, r#"0"#),
],
},
Signature {
name: "proc_priority",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pid", Ty::Any, "a positive process id, Int or numeric String")],
returns: "Record",
doc: "A process's scheduling priority as {nice, class}: nice from -20 (highest) to 19 (lowest), and class one of Idle, BelowNormal, Normal, AboveNormal, High or RealTime, which Windows reports and Unix derives from nice. A pid that is not live is E_NOT_FOUND.",
examples: &[
(r#"(try { proc_priority(0) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
(r#"(try { proc_priority(2000000000) } catch e { e.error.code })"#, r#"E_NOT_FOUND"#),
],
},
Signature {
name: "proc_set_priority",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("pid", Ty::Any, "a positive process id, Int or numeric String"),
Param {
name: "priority",
ty: Ty::Int,
required: true,
range: Some((-20, 19)),
variadic: false,
doc: "nice value from -20 (highest) to 19 (lowest)",
},
],
returns: "Bool",
doc: "Sets a process's scheduling priority (nice on Unix, the nearest priority class on Windows) and answers true. Raising a priority needs privilege, and a refusal is E_OS_DENIED. A pid that is not live is E_NOT_FOUND; a pid that is not positive is E_BAD_ARG.",
examples: &[
(r#"(try { proc_set_priority(0, 5) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
(r#"(try { proc_set_priority(2000000000, 5) } catch e { e.error.code })"#, r#"E_NOT_FOUND"#),
(r#"(try { proc_set_priority(1, 20) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
],
},
Signature {
name: "proc_cpu_usage",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pid", Ty::Any, "a positive process id, Int or numeric String")],
returns: "Float",
doc: "The CPU use of a live process: percent of one CPU from ps on Unix, total CPU seconds on Windows, so the unit differs by OS. A pid that is not live is E_NOT_FOUND.",
examples: &[
(r#"(try { proc_cpu_usage(0) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
(r#"(try { proc_cpu_usage(2000000000) } catch e { e.error.code })"#, r#"E_NOT_FOUND"#),
],
},
Signature {
name: "proc_mem_usage",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pid", Ty::Any, "a positive process id, Int or numeric String")],
returns: "Int",
doc: "The resident memory of a live process, in bytes. A pid that is not live is E_NOT_FOUND.",
examples: &[
(r#"(try { proc_mem_usage(0) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
(r#"(try { proc_mem_usage(2000000000) } catch e { e.error.code })"#, r#"E_NOT_FOUND"#),
],
},
Signature {
name: "proc_threads",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pid", Ty::Any, "a positive process id, Int or numeric String")],
returns: "Int",
doc: "The number of threads in a live process. A pid that is not live is E_NOT_FOUND.",
examples: &[
(r#"(try { proc_threads(0) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
(r#"(try { proc_threads(2000000000) } catch e { e.error.code })"#, r#"E_NOT_FOUND"#),
],
},
Signature {
name: "proc_env",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pid", Ty::Any, "a positive process id, Int or numeric String")],
returns: "Record",
doc: "The environment of a process as a record of name to value. This shell's own pid is answered on every OS; another process's environment is read on Linux and Windows and is E_UNIMPLEMENTED on macOS. A pid that is not live is E_NOT_FOUND; a process the user does not own, or one Windows will not open, is E_OS_DENIED.",
examples: &[
(r#"(try { proc_env(0) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
(r#"(try { proc_env(2000000000) } catch e { e.error.code })"#, r#"E_NOT_FOUND"#),
],
},
Signature {
name: "proc_cwd",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pid", Ty::Any, "a positive process id, Int or numeric String")],
returns: "String",
doc: "The working directory of a process. This shell's own pid is answered on every OS; another process's directory is read on Linux, macOS and Windows. A process whose directory Windows will not give is E_OS_DENIED. A pid that is not live is E_NOT_FOUND.",
examples: &[
(r#"(try { proc_cwd(0) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
(r#"(try { proc_cwd(2000000000) } catch e { e.error.code })"#, r#"E_NOT_FOUND"#),
],
},
Signature {
name: "proc_exe",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pid", Ty::Any, "a positive process id, Int or numeric String")],
returns: "String",
doc: "The executable path of a live process. A pid that is not live is E_NOT_FOUND; a path the OS will not show is E_OS_DENIED.",
examples: &[
(r#"(try { proc_exe(0) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
(r#"(try { proc_exe(2000000000) } catch e { e.error.code })"#, r#"E_NOT_FOUND"#),
],
},
Signature {
name: "proc_cmdline",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pid", Ty::Any, "a positive process id, Int or numeric String")],
returns: "Array",
doc: "The command-line arguments of a live process, as Strings. A quoted argument with spaces stays one argument on Linux and Windows; on macOS ps does not quote, so it is split on whitespace. A pid that is not live is E_NOT_FOUND.",
examples: &[
(r#"(try { proc_cmdline(0) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
(r#"(try { proc_cmdline(2000000000) } catch e { e.error.code })"#, r#"E_NOT_FOUND"#),
],
},
Signature {
name: "proc_start_time",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pid", Ty::Any, "a positive process id, Int or numeric String")],
returns: "String",
doc: "When a live process started, as UTC ISO 8601 to the second (for example 2026-10-19T09:30:00Z), on every OS. A pid that is not live is E_NOT_FOUND.",
examples: &[
(r#"(try { proc_start_time(0) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
(r#"(try { proc_start_time(2000000000) } catch e { e.error.code })"#, r#"E_NOT_FOUND"#),
],
},
Signature {
name: "proc_spawn",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("program", Ty::Str, "the program to run, found on PATH or given by path"),
opt_rest("args", Ty::Str, "arguments, each a String, passed without a shell"),
opt("options", Ty::Record, "Record {timeout_ms: Int}, given as the last argument; no options by default; any other key, or a timeout_ms that is not an Int in 1..=86400000, is E_BAD_ARG"),
],
returns: "Int",
doc: "Starts a program directly, never through a shell, and answers the child's process id. The child is not waited for by this call; proc_wait waits for it. Pipeline input, a non-string argument, or a NUL byte is E_BAD_ARG; a program that does not exist is E_TOOL_MISSING. Agent mode gates it as Exec. With options {timeout_ms: N} (a positive Int, at most 86400000) the process is stopped if it is still running N ms after the spawn: on Unix the child is made the leader of its own process group, and SIGTERM goes to the group, then SIGKILL after up to 2 s, so its descendants that stayed in the group stop with it; a descendant that left the group (setsid, setpgid) is not reached. On Windows taskkill /T /F stops the process and its tree. The watcher checks the process's start time as well as its pid, so a pid that has since been reused by another process is never signalled, and a process that has ended, or been reaped by proc_wait, is left alone. The stop is logged to stderr. proc_wait still reports the exit: a process stopped on Unix reports as killed by a signal. Without the options record the spawn is unchanged. The answer is the same Int pid either way.",
examples: &[
(r#"(try { proc_spawn(5) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
(r#"(try { "x" | proc_spawn("hostname") } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
(r#"(try { proc_spawn("x", {timeout_ms: 0}) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
(r#"(try { proc_spawn("x", {timeout_ms: "1"}) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
(r#"(try { proc_spawn("x", {nope: 1}) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
],
},
Signature {
name: "timeout_cmd", category: None, subject_required: false, aliases: &["timeout"], subject: None,
params: &[Param { range: Some((1, 3600)), ..req("seconds", Ty::Int, "time limit in seconds, 1..3600") }, req("command", Ty::Str, "program and arguments separated by spaces; no shell and no quoting")], returns: "Record",
doc: "Run one program with a time limit, returning {command, exit_code, stdout, stderr, stdout_truncated}. The command is split on whitespace and run directly; its program may not begin with '-'. The exit code is the program's and is data. A program still running at the limit is killed and the call is E_BUDGET_EXCEEDED.",
examples: &[
(r#"(try { timeout_cmd(0, "x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { timeout_cmd(1, "-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "xargs_exec", category: None, subject_required: false, aliases: &["xargs"], subject: None,
params: &[req("command", Ty::Str, "program and fixed arguments separated by spaces; no shell"), opt("items", Ty::Sequence, "Array of scalars or a String of lines; piped input is also accepted")], returns: "Array",
doc: "Run one program once per item, with the item as its last argument, and return one Record per item: {item, exit_code, stdout, stderr}. The command is split on whitespace and run directly. Its program and each item may not begin with '-'. At most 256 items, each run has a 120 s deadline, and the call has 600 s in all. A nonzero exit is that item's exit code, which is data.",
examples: &[
(r#"(try { xargs_exec("-x", ["a"]) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { xargs_exec("x", 5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "proc_wait",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("pid", Ty::Any, "a positive process id, Int or numeric String"),
opt("timeout", Ty::Int, "milliseconds to wait; default 30000; zero checks once"),
],
returns: "Bool",
doc: "Waits for a process to end: true when it has ended, false when the timeout passes first. A child this shell spawned is reaped, so it does not linger as a zombie. The exit status is not reported. A pid that is not live when the call starts is E_NOT_FOUND, unless this shell spawned it and it has already ended: that is true.",
examples: &[
(r#"(try { proc_wait(0) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
(r#"(try { proc_wait(2000000000, 0) } catch e { e.error.code })"#, r#"E_NOT_FOUND"#),
],
},
Signature {
name: "proc_suspend",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pid", Ty::Any, "a positive process id, Int or numeric String")],
returns: "Bool",
doc: "Stops a process and answers true. Unix sends SIGSTOP; Windows opens the process with PROCESS_SUSPEND_RESUME and calls ntdll NtSuspendProcess, so every thread stops. This shell's own pid, zero and negative pids are E_BAD_ARG; a pid that is not live is E_NOT_FOUND; a process the user does not own (or a protected one, such as System on Windows) is E_OS_DENIED; any other OS or ntdll failure is E_TOOL_FAILED.",
examples: &[
(r#"(try { proc_suspend(0) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
(r#"(try { proc_suspend(2000000000) } catch e { e.error.code })"#, r#"E_NOT_FOUND"#),
],
},
Signature {
name: "proc_resume",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("pid", Ty::Any, "a positive process id, Int or numeric String")],
returns: "Bool",
doc: "Continues a stopped process and answers true. Unix sends SIGCONT; Windows calls ntdll NtResumeProcess on a PROCESS_SUSPEND_RESUME handle. The refusals are those of proc_suspend.",
examples: &[
(r#"(try { proc_resume(0) } catch e { e.error.code })"#, r#"E_BAD_ARG"#),
(r#"(try { proc_resume(2000000000) } catch e { e.error.code })"#, r#"E_NOT_FOUND"#),
],
},
Signature {
name: "diag_all", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("dir", Ty::Str, "project directory inside the workspace; must hold Cargo.toml")],
returns: "Array",
doc: "cargo check --all-targets over the project in directory dir: its library, binaries, tests, examples and benches. Returns an Array of Records {level, code, file, line, message}, one per error or warning; notes and help are left out. Errors and warnings are the answer, so a build with errors returns them rather than failing. A build that never finished, such as a broken manifest or a missing toolchain, is E_TOOL_FAILED. dir is required and checked as for test_bench. The run has a 900 s deadline; the cargo process is killed at it. Takes no pipeline input.",
examples: &[
(r#"(try { diag_all() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { diag_all("") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "diag_check", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("dir", Ty::Str, "project directory inside the workspace; must hold Cargo.toml")],
returns: "Array",
doc: "cargo check over the default targets of the project in directory dir. Returns an Array of Records {level, code, file, line, message} for each error and warning, as diag_all does, over the default targets only. dir is required and checked as for test_bench. A build that never finished is E_TOOL_FAILED; the run has a 900 s deadline. Takes no pipeline input.",
examples: &[
(r#"(try { diag_check() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { diag_check("") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "diag_errors", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("dir", Ty::Str, "project directory inside the workspace; must hold Cargo.toml")],
returns: "Array",
doc: "The error-level diagnostics of cargo check over the project in directory dir, as an Array of Records {level, code, file, line, message}. Warnings are left out. An empty Array means the check ran and found no errors; a build that never finished is E_TOOL_FAILED and is not an empty Array. dir is required and checked as for test_bench. The run has a 900 s deadline. Takes no pipeline input.",
examples: &[
(r#"(try { diag_errors() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { diag_errors("") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "diag_fix", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("dir", Ty::Str, "project directory inside the workspace; must hold Cargo.toml")],
returns: "Bool",
doc: "Run cargo fix over the project in directory dir, which rewrites the project's source files with the compiler's machine-applicable suggestions. It writes only inside dir, which must lie in the workspace. It does not pass --allow-dirty: cargo refuses a version-controlled tree with uncommitted changes, and that refusal is E_TOOL_FAILED with cargo's reason, so commit or stash first. Without version control, cargo also refuses unless told otherwise. Returns true when cargo finished. Because cargo compiles the project, it runs build scripts and procedural macros, so the builtin is Exec and agent mode asks for approval. The run has a 900 s deadline. Takes no pipeline input.",
examples: &[
(r#"(try { diag_fix() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { diag_fix("") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "diag_lint", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("dir", Ty::Str, "project directory inside the workspace; must hold Cargo.toml")],
returns: "Array",
doc: "cargo clippy over the project in directory dir. Returns an Array of Records {level, code, file, line, message} for each clippy error and warning. A build that never finished, including clippy not being installed, is E_TOOL_FAILED. dir is required and checked as for test_bench. The run has a 900 s deadline. Takes no pipeline input.",
examples: &[
(r#"(try { diag_lint() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { diag_lint("") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "diag_warnings", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("dir", Ty::Str, "project directory inside the workspace; must hold Cargo.toml")],
returns: "Array",
doc: "The warning-level diagnostics of cargo check over the project in directory dir, as an Array of Records {level, code, file, line, message}. Errors are left out. A build that never finished is E_TOOL_FAILED and is not an empty Array. dir is required and checked as for test_bench. The run has a 900 s deadline. Takes no pipeline input.",
examples: &[
(r#"(try { diag_warnings() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { diag_warnings("") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "diag_explain",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("code", Ty::Str, "a Rust error code such as E0308")],
returns: "String",
doc: "rustc's explanation of an error code. A code rustc does not know is E_TOOL_FAILED.",
examples: &[
(r#"diag_explain("E0308")"#, r#"Expected type did not match the received type. ..."#),
],
},
Signature {
name: "docs_generate", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("dir", Ty::Str, "project directory inside the workspace; must hold Cargo.toml")],
returns: "Bool",
doc: "Run cargo doc --no-deps over the project in directory dir and return true when it finished. Documentation is written to the project's target directory. dir is required and checked as for test_bench. A failing build is E_TOOL_FAILED with cargo's stderr tail. Because cargo runs the project's build scripts and procedural macros, the builtin is Exec and agent mode asks for approval. The run has a 900 s deadline. Takes no pipeline input.",
examples: &[
(r#"(try { docs_generate() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { docs_generate("") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "docs_search",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("query", Ty::Str, "text to find")],
returns: "Array",
doc: "Up to 20 lines of target/doc containing a query, as file:line: text. No target/doc is E_NOT_FOUND; an unreadable directory or file is an error, not skipped.",
examples: &[
(r#"docs_search("Value")"#, r#"["target/doc/ironshell/value/enum.Value.html:1: ...", ...]"#),
],
},
Signature {
name: "less",
category: None,
subject_required: false,
aliases: &["pager"],
subject: Some(Ty::Str),
params: &[opt("options", Ty::Record, "{file: Bool}, default false; true reads the subject as a path")],
returns: "String | Record",
doc: "Direct less(text,options?) or text | less(options?); pager is an alias. Return text of at most 40 lines unchanged, including its line endings, or a record with the first 40 lines joined with LF, total_lines, page_size 40, pages and a head/tail hint for longer input. File mode resolves paths against the workspace, guards the actual target and bounds regular UTF-8 reads to 64 MiB. Reject invalid or unknown options, non-Bool file and conflicting direct/piped input. Consume owned text, retain only first-page line references and count remaining lines without collecting them.",
examples: &[
(r#"less("a")"#, r#"a"#),
(r#"typeof(less("Cargo.toml", {file: true}))"#, r#"Record"#),
(r#""a" | pager({file: false})"#, r#""a""#),
],
},
Signature {
name: "platform_db_load",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("key", Ty::Str, "default \"default\"")],
returns: "Any",
doc: "A value from the platform key-value store, or null when absent. A corrupt store is E_BAD_STATE.",
examples: &[
(r#"platform_db_load("no-such-key-ae") == null"#, r#"true"#),
(r#"platform_db_load()"#, r#"null"#),
],
},
// 1b: archives (in-process: the same answer everywhere) and the SQLite
// inspectors (the sqlite3 CLI: machine-dependent). Fixtures live in
// tests/fixtures.
Signature {
name: "zip_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a .zip file")],
returns: "Array",
doc: "Entries of a zip archive as {name, size, compressed_size, dir}. A file that is not a zip is refused.",
examples: &[
(r#"zip_list("tests/fixtures/archives/sample.zip") | map(fn(e) => e.name)"#, r#"["README.txt", "src/files.rs"]"#),
],
},
Signature {
name: "zoxide_add",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("path", Ty::Str, "an existing directory; defaults to the process's directory")],
returns: "Record",
doc: "zoxide add <path>: records the directory in the user's zoxide database, answering {path, exit_code, success, stdout, stderr}. The path must exist as a directory and is one word not starting with '-'. The database lies outside the workspace; the directory itself is not changed. A missing directory is E_NOT_FOUND. Takes no pipeline input.",
examples: &[
(r#"(try { zoxide_add("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { zoxide_add({a: 1}) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { zoxide_add("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | zoxide_add() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "zoxide_query",
category: None,
subject_required: false,
aliases: &["zoxide"],
subject: None,
params: &[req("term", Ty::Str, "search keywords; one word, not starting with '-'")],
returns: "String",
doc: "zoxide query <term>: the highest-ranked directory in the user's zoxide database matching the term, as a path String. No match is E_NOT_FOUND, and any other failure is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { zoxide_query("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { zoxide_query() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | zoxide_query("a") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "tar_create",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("archive", Ty::Str, "the new archive file to write; an existing file is refused"),
Param {
name: "members",
ty: Ty::Str,
required: true,
range: None,
variadic: true,
doc: "one or more paths to archive; they are not followed as links, and under an enforced workspace each must lie inside it",
},
],
returns: "Bool",
doc: "Create a tar archive at a new path from the given members, and return true. The archive is streamed to a new file, so an existing one is refused rather than truncated; in agent mode or when a workspace is set (`--workspace` or IRONSHELL_WORKSPACE) it is jailed to the workspace, and it is capped in size and deadlined; a partial archive is removed on failure. Names that could be read as options are refused. Piped input is refused. A member inside the current directory is stored by its relative path as written (normalised, never with `..`); one outside it, or the current directory itself, under its last path component, with its tree below that for a folder, so no absolute path is stored (zip_create stores every member under its last component). The journal step for the call is the archive it creates.",
examples: &[
(r#"(try { tar_create("a.tar") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { tar_create("-x.tar", "f") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "task_run",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("task", Ty::Str, "a Taskfile task name, with no whitespace")],
returns: "Record",
doc: "Run one task of the Taskfile in the current directory with the task tool and return {task, stdout, stderr}. The task's commands run under the task tool's own interpreter, so this executes the task definition and is gated as an exec. Output is capped and the run has a deadline; stdin is closed. A nonzero exit is E_TOOL_FAILED with the stderr tail.",
examples: &[
(r#"(try { task_run() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { task_run("a b") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "task_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "List the tasks of the Taskfile in the current directory, as the task tool prints them. Output is capped and the run has a deadline. A missing Taskfile or a failing task tool is E_TOOL_FAILED or E_TOOL_MISSING.",
examples: &[
(r#"(try { task_list(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "tar_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a .tar, .tar.gz or .tgz file")],
returns: "Array",
doc: "Entries of a tar archive as {path, size, kind}.",
examples: &[
(r#"tar_list("tests/fixtures/archives/sample.tar.gz") | map(fn(e) => e.path)"#, r#"["README.txt", "src/files.rs"]"#),
],
},
Signature {
name: "archive_info",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "an archive file")],
returns: "Record",
doc: "An archive's {path, type, size}; type is null for an extension it does not recognise.",
examples: &[
(r#"archive_info("tests/fixtures/archives/sample.zip").type"#, r#"zip"#),
],
},
Signature {
name: "archive_test",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a .zip, .tar, .tar.gz/.tgz, .gz, .bz2, .xz, .zst, .tar.bz2, .tar.xz or .tar.zst file")],
returns: "Bool",
doc: "Whether every entry decompresses (and, for zip, matches its CRC). bzip2, xz and zstd files, and the tar archives inside them, are tested with bzip2 -t, xz -t and zstd -t (tar: decompressed and read to the end); the file's magic bytes must match its extension or the call is refused. Corrupt data answers false; a missing tool is E_TOOL_MISSING.",
examples: &[
(r#"archive_test("tests/fixtures/archives/sample.zip")"#, r#"true"#),
(r#"archive_test("tests/fixtures/archives/damaged.zip")"#, r#"false"#),
(r#"let d = fs_tempdir("ae_archive"); let f = d + "/notes.xz"; file_write(f, "not an archive\n"); let r = (try { archive_test(f) } catch e { e.error.code }); rmdir(d, true); r"#, "E_BAD_ARG"),
],
},
Signature {
name: "db_csv_query", category: None, subject_required: false, aliases: &["db_csv_to_json"],
subject: None, params: &[req("path", Ty::Str, "CSV file with a header row")], returns: "Array",
doc: "Load CSV into records with string cells, trimming headers and fields. Handle quoted commas and multiline fields; refuse unequal row lengths. This loader does not accept a SQL query.",
examples: &[(r#"let d = fs_tempdir("ae_csv"); let f = d + "/rows.csv"; file_write(f, "name,age\nAda,42\n"); let rows = db_csv_query(f); rmdir(d, true); rows | map(fn(r) => r.name) | first"#, "Ada"), (r#"let d = fs_tempdir("ae_csv"); let f = d + "/rows.csv"; file_write(f, "name,age\nAda,42\n"); let rows = db_csv_to_json(f); rmdir(d, true); rows | map(fn(r) => r.age) | first"#, "42")],
},
Signature {
name: "db_sqlite_exec", category: None, subject_required: false, aliases: &["sqlite_exec"],
subject: None, params: &[req("db", Ty::Str, "SQLite database path"), req("sql", Ty::Str, "SQL statements; no SQLite dot commands")], returns: "Bool",
doc: "Execute SQL through the sqlite3 CLI, snapshotting the database for an active transaction. Return true on success or a coded tool error. SQL query output is discarded; use sql for results.",
examples: &[(r#"db_sqlite_dump("tests/fixtures/sample.db"); let d = fs_tempdir("ae_exec"); let result = db_sqlite_exec(d + "/example.db", "CREATE TABLE example(value INTEGER)"); rmdir(d, true); result"#, "true")],
},
Signature {
name: "db_kv_set", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("store", Ty::Str, "SQLite key-value store path"), req("key", Ty::Str, "literal key"), req("value", Ty::Any, "strings are stored verbatim; other values use Rust debug text")], returns: "Bool",
doc: "Create the kv table if needed and insert or replace a key. Validate SQL literals before writing; propagate table-creation errors. Requires the sqlite3 CLI.",
examples: &[(r#"db_sqlite_dump("tests/fixtures/sample.db"); let d = fs_tempdir("ae_kv"); let result = db_kv_set(d + "/store.db", "greeting", "hello"); rmdir(d, true); result"#, "true")],
},
Signature {
name: "db_kv_delete", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("store", Ty::Str, "SQLite key-value store path"), req("key", Ty::Str, "literal key")], returns: "Bool",
doc: "Delete a key through the effect gate using the sqlite3 CLI. Return true when SQL succeeds, including when no matching key exists; tool failures are coded errors.",
examples: &[(r#"db_sqlite_dump("tests/fixtures/sample.db"); let d = fs_tempdir("ae_kv"); let f = d + "/store.db"; db_kv_set(f, "greeting", "hello"); let result = db_kv_delete(f, "greeting"); rmdir(d, true); result"#, "true")],
},
Signature {
name: "db_sqlite_insert", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("db", Ty::Str, "SQLite database path"), req("table", Ty::Str, "table name (any non-empty name; quoted for you)"), req("values", Ty::Record, "nonempty column-to-value record; String, Int, finite Float, Bool or Null cells")], returns: "Bool",
doc: "Insert one row using the sqlite3 CLI. Validate identifiers and scalar cells before execution; return true when SQL succeeds or a coded error.",
examples: &[(r#"db_sqlite_dump("tests/fixtures/sample.db"); let d = fs_tempdir("ae_insert"); let f = d + "/db"; file_copy("tests/fixtures/sample.db", f); let result = db_sqlite_insert(f, "people", {name: "O'Brien", age: 37}); rmdir(d, true); result"#, "true")],
},
Signature {
name: "db_sqlite_update", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("db", Ty::Str, "SQLite database path"), req("table", Ty::Str, "table name (any non-empty name; quoted for you)"), req("values", Ty::Record, "nonempty column-to-scalar record"), req("where", Ty::Str, "nonempty caller-owned SQL condition")], returns: "Bool",
doc: "Update matching rows using the sqlite3 CLI. Cells accept String, Int, finite Float, Bool and Null; other types are refused. Return true on successful SQL, even with no matching rows.",
examples: &[(r#"db_sqlite_dump("tests/fixtures/sample.db"); let d = fs_tempdir("ae_update"); let f = d + "/db"; file_copy("tests/fixtures/sample.db", f); let result = db_sqlite_update(f, "people", {age: 41}, "age > 40"); rmdir(d, true); result"#, "true")],
},
Signature {
name: "db_sqlite_delete", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("db", Ty::Str, "SQLite database path"), req("table", Ty::Str, "table name (any non-empty name; quoted for you)"), opt("where", Ty::Str, "required, nonempty caller-owned SQL condition; to delete every row pass \"1=1\"")], returns: "Bool",
doc: "Delete matching rows through the destructive effect gate using sqlite3. A missing or blank where is refused with E_BAD_ARG (to delete every row pass \"1=1\"), so nothing is deleted by omission; malformed conditions are refused. Return true when SQL succeeds, even with no match.",
examples: &[(r#"db_sqlite_dump("tests/fixtures/sample.db"); let d = fs_tempdir("ae_delete"); let f = d + "/db"; file_copy("tests/fixtures/sample.db", f); let result = db_sqlite_delete(f, "people", "1=1"); rmdir(d, true); result"#, "true"), (r#"db_sqlite_dump("tests/fixtures/sample.db"); let d = fs_tempdir("ae_delete"); let f = d + "/db"; file_copy("tests/fixtures/sample.db", f); let result = db_sqlite_delete(f, "people", "age > 40"); rmdir(d, true); result"#, "true")],
},
Signature {
name: "db_sqlite_create_table", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("db", Ty::Str, "SQLite database path"), req("table", Ty::Str, "table name (any non-empty name; quoted for you)"), req("columns", Ty::Any, "nonempty Record of validated SQL type strings, or nonempty raw SQL column-definition String")], returns: "Bool",
doc: "Create a table if absent using sqlite3. Validate record-form names and types before execution; the string form accepts caller-owned SQL grammar. Return true when SQL succeeds.",
examples: &[(r#"db_sqlite_dump("tests/fixtures/sample.db"); let d = fs_tempdir("ae_create"); let result = db_sqlite_create_table(d + "/db", "example", {name: "TEXT", age: "INTEGER"}); rmdir(d, true); result"#, "true"), (r#"db_sqlite_dump("tests/fixtures/sample.db"); let d = fs_tempdir("ae_create"); let result = db_sqlite_create_table(d + "/db", "example", "name TEXT, age INTEGER"); rmdir(d, true); result"#, "true")],
},
Signature {
name: "db_sqlite_drop_table", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("db", Ty::Str, "SQLite database path"), req("table", Ty::Str, "table name (any non-empty name; quoted for you)")], returns: "Bool",
doc: "Drop a table if present through the destructive effect gate using sqlite3. An active transaction snapshots the database for rollback. Return true when SQL succeeds.",
examples: &[(r#"db_sqlite_dump("tests/fixtures/sample.db"); let d = fs_tempdir("ae_drop"); let f = d + "/db"; file_copy("tests/fixtures/sample.db", f); let result = db_sqlite_drop_table(f, "people"); rmdir(d, true); result"#, "true")],
},
Signature {
name: "db_csv_to_sqlite", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("db", Ty::Str, "SQLite destination path"), req("csv", Ty::Str, "UTF-8 CSV with a header of unique column names (compared without regard to case)"), opt("table", Ty::Str, "table name; default imported")], returns: "Bool",
doc: "Import CSV in process in one transaction. Always consume the header; create absent columns typed as sql() reads the same file (INTEGER, REAL, or TEXT; a column of true and false is INTEGER 1 and 0) and bind each cell with that type, so ORDER BY id sorts numbers as numbers. An empty cell is NULL. Any non-empty column or table name is accepted and quoted for you (spaces, quotes and reserved words included); a control character is refused. Existing column affinities apply. Parse failures create no database; row failures roll back all imported rows. Limited to one million rows and the configured file-size budget.",
examples: &[(r#"let d = fs_tempdir("ae_csv_import"); let f = d + "/rows.csv"; file_write(f, "name,age\nAda,42\n"); let result = db_csv_to_sqlite(d + "/db", f); rmdir(d, true); result"#, "true"), (r#"let d = fs_tempdir("ae_csv_import"); let f = d + "/rows.csv"; file_write(f, "name,age\nAda,42\n"); let result = db_csv_to_sqlite(d + "/db", f, "people"); rmdir(d, true); result"#, "true")],
},
Signature {
name: "db_sqlite_import", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("db", Ty::Str, "SQLite database path"), req("sql_file", Ty::Str, "UTF-8 file of SQL statements")], returns: "Bool",
doc: "Read SQL from a file and execute it using sqlite3, snapshotting an active transaction. SQLite dot commands are refused; missing files and tool failures are coded errors.",
examples: &[(r#"db_sqlite_dump("tests/fixtures/sample.db"); let d = fs_tempdir("ae_import"); let f = d + "/schema.sql"; file_write(f, "CREATE TABLE example(value INTEGER); INSERT INTO example VALUES(42);"); let result = db_sqlite_import(d + "/db", f); rmdir(d, true); result"#, "true")],
},
Signature {
name: "db_sqlite_to_csv", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("db", Ty::Str, "SQLite database path"), req("table_or_query", Ty::Str, "table name (any non-empty name; quoted for you) or caller-owned SQL starting with SELECT"), opt("destination", Ty::Str, "write CSV to this file and return its path; omitted returns CSV text")], returns: "String",
doc: "Export CSV with a header using sqlite3. Every row ends with CRLF (RFC 4180) on every platform, in the returned text and in the destination file; a newline inside a quoted cell is kept as it is. Return text or the destination path; malformed destinations, tool failures and file-write failures are coded errors.",
examples: &[(r#"db_sqlite_to_csv("tests/fixtures/sample.db", "people")"#, "name,age\r\nada,36\r\nalan,41\r\n"), (r#"db_sqlite_dump("tests/fixtures/sample.db"); let d = fs_tempdir("ae_csv_out"); let result = db_sqlite_to_csv("tests/fixtures/sample.db", "people", d + "/people.csv"); let name = result | split("/") | last; rmdir(d, true); name"#, "people.csv")],
},
Signature {
name: "db_sqlite_to_json", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("db", Ty::Str, "existing SQLite database path"), req("table", Ty::Str, "table name (any non-empty name; quoted for you)")], returns: "Array",
doc: "Read a table in process as typed records, without creating a missing database. The result is an array, not serialized JSON text; use to_json for text.",
examples: &[(r#"db_sqlite_to_json("tests/fixtures/sample.db", "people") | len"#, "2")],
},
Signature {
name: "db_sqlite_schema", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("db", Ty::Str, "existing SQLite database"), opt("table", Ty::Str, "literal table name")], returns: "Array",
doc: "Read table definitions in name order, or column metadata for a literal table name. A missing table returns an empty array; a missing database is not created.",
examples: &[(r#"db_sqlite_schema("tests/fixtures/sample.db") | len"#, "2"), (r#"db_sqlite_schema("tests/fixtures/sample.db", "people") | len"#, "2")],
},
Signature {
name: "db_sqlite_backup", category: None, subject_required: false, aliases: &[],
subject: None, params: &[req("db", Ty::Str, "source SQLite database"), opt("destination", Ty::Str, "default source path plus .backup; no quotes or newlines")], returns: "Bool",
doc: "Back up an existing database using the sqlite3 CLI. An absent source is E_NOT_FOUND, not an empty backup, and :memory: is E_BAD_ARG. Return true on success or a coded tool error on failure.",
examples: &[(r#"db_sqlite_dump("tests/fixtures/sample.db"); let d = fs_tempdir("ae_backup"); let f = d + "/source.db"; file_copy("tests/fixtures/sample.db", f); let result = db_sqlite_backup(f); rmdir(d, true); result"#, "true"), (r#"db_sqlite_dump("tests/fixtures/sample.db"); let d = fs_tempdir("ae_backup"); let result = db_sqlite_backup("tests/fixtures/sample.db", d + "/copy.db"); rmdir(d, true); result"#, "true")],
},
Signature {
name: "db_sqlite_tables",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("db", Ty::Str, "an existing SQLite file")],
returns: "Array",
doc: "A database's tables as {name}. A missing database is E_NOT_FOUND and is not created.",
examples: &[
(r#"db_sqlite_tables("tests/fixtures/sample.db") | map(fn(t) => t.name)"#, r#"[kv, people]"#),
],
},
Signature {
name: "db_sqlite_dump",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("db", Ty::Str, "an existing SQLite file")],
returns: "String",
doc: "A database as SQL text (sqlite3 .dump).",
examples: &[
(r#"db_sqlite_dump("tests/fixtures/sample.db")"#, r#"PRAGMA foreign_keys=OFF; BEGIN TRANSACTION; CREATE TABLE people ..."#),
],
},
Signature {
name: "db_kv_keys",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("store", Ty::Str, "a key-value store; default .ironshell_kv.db")],
returns: "Array",
doc: "A key-value store's keys; [] for a store that does not exist yet, which is not created.",
examples: &[
(r#"db_kv_keys("tests/fixtures/sample.db")"#, r#"[greeting]"#),
(r#"db_kv_keys()"#, r#"[]"#),
],
},
Signature {
name: "db_kv_get",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("store", Ty::Str, "a key-value store"), req("key", Ty::Str, "the key")],
returns: "Any",
doc: "A key's value, or null when the key or the store is absent.",
examples: &[
(r#"db_kv_get("tests/fixtures/sample.db", "greeting")"#, r#"hello"#),
],
},
Signature {
name: "db_sqlite_count",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("db", Ty::Str, "an existing SQLite file"), req("table", Ty::Str, "a table name"), opt("where", Ty::Str, "a WHERE condition")],
returns: "Int",
doc: "The number of rows in a table, optionally matching a condition.",
examples: &[
(r#"db_sqlite_count("tests/fixtures/sample.db", "people")"#, r#"2"#),
(r#"db_sqlite_count("tests/fixtures/sample.db", "people", "age > 40")"#, r#"1"#),
],
},
// 1b: services, open connections, block devices, certificates, SSH
// config. All machine-dependent; results shown are Debian's.
Signature {
name: "svc_status",
category: None,
subject_required: false,
aliases: &["service", "systemctl"],
subject: None,
params: &[req("name", Ty::Str, "a service name")],
returns: "Record",
doc: "A service's {name, status} (and sub_state under systemd). A service that does not exist is E_NOT_FOUND, not \"inactive\".",
examples: &[
(r#"service("cron")"#, r#"{name: cron, status: active, sub_state: running}"#),
],
},
Signature {
name: "svc_info",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("name", Ty::Str, "a service name")],
returns: "Record",
doc: "The same as svc_status.",
examples: &[
(r#"svc_info("cron")"#, r#"{name: cron, status: active, sub_state: running}"#),
],
},
Signature {
name: "svc_logs",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("name", Ty::Str, "a service or process name"), opt("lines", Ty::Int, "newest entries to return; default 100")],
returns: "Array",
doc: "A service's newest log entries as {timestamp, level, message}.",
examples: &[
(r#"svc_logs("cron")"#, r#"[{level: 6, message: "...", timestamp: "..."}, ...]"#),
(r#"svc_logs("cron", 5)"#, r#"[{level: 6, message: "...", timestamp: "..."}, ...]"#),
],
},
Signature {
name: "lsof",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("path", Ty::Str, "an existing file; lists the processes that hold it open")],
returns: "Array",
doc: "Without a path: this machine's network connections as lsof -i reports them. With a path: the processes holding that file open (an empty array when none). One record per line. Linux and macOS read both forms. On Windows the no-path form lists TCP sockets; the path form asks the Restart Manager (RmGetList) for the processes holding the file, one record per process with command (the image name without .exe, as in the socket form), pid (String), and name (the file's canonical path); user, fd, type, device, size/off and node are Null, as the Restart Manager does not report them. A path that does not exist is E_NOT_FOUND. A directory is E_BAD_ARG, because the Restart Manager lists files only. A UNC or device path, or a drive that resolves to a network share, is E_BAD_ARG and is never probed. More than 1024 holders is E_BUDGET_EXCEEDED.",
examples: &[
(r#"lsof()"#, r#"[{command: sshd, pid: "812", ...}, ...]"#),
(r#"lsof("/etc/hosts")"#, r#"[] (no process holds it open)"#),
],
},
Signature {
name: "blkid",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("device", Ty::Str, "a block device such as /dev/sda1, or a Windows drive such as C:")],
returns: "Record",
doc: "Linux, macOS and Windows. On Linux, a block device's attributes (devname, uuid, partuuid, type, label), read with blkid -o export; a device under /dev/ that blkid cannot identify, or that does not exist, is E_NOT_FOUND. On macOS, a device under /dev/ such as /dev/disk1s1 is read with diskutil info -plist, which changes nothing: devname is DeviceNode, uuid is VolumeUUID (DiskUUID for a device with no volume), type is FilesystemType lower-cased and label is VolumeName; partuuid is left out, since macOS has no field for the GPT partition GUID. A device diskutil refuses is E_TOOL_FAILED. On Windows, a drive such as C: is read with Get-Volume and Get-Partition: uuid is the volume UniqueId, partuuid the partition Guid, type the file system lower-cased, label its label and devname the drive; a field the drive does not report is left out, and a drive with no volume is E_NOT_FOUND. Fields the platform does not report are left out on every OS, never null. Other platforms refuse with E_UNIMPLEMENTED and change nothing.",
examples: &[
(r#"blkid("/dev/sda1")"#, r#"{type: ext4, uuid: "...", ...}"#),
],
},
Signature {
name: "crypto_cert_verify",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a certificate file, at most 64 MiB: PEM or one DER certificate; the first certificate is the end entity and any others are intermediates")],
returns: "Bool",
doc: "Whether the first certificate in the file chains to a trust anchor, using IronSocketLayer's X.509 (IronPKI, pure Rust over IronCrypto); no openssl or other process, on every OS. The rest of the file are intermediates. Trust anchors come from the system store: SSL_CERT_FILE if it holds a usable PEM bundle, else the usual Linux, BSD and macOS bundle paths, else Git for Windows' bundle; a store of more than 4096 anchors is E_BUDGET_EXCEEDED. Policy is TLS server (id-kp-serverAuth), every IronPKI signature algorithm is allowed, RSA keys below 2048 bits are refused, the time is now, and no CRL or OCSP is consulted. Only the chain is checked: no host name is matched, so a true answer does not say the certificate is for any particular name. Returns true when the chain validates. Returns false for the outcomes that mean it does not: expired, revoked, wrong usage, unknown CA, bad signature, policy violation, name mismatch, bad certificate status, key algorithm mismatch, or a malformed certificate. Coded errors where no answer can be given: E_NOT_FOUND when no usable trust store is found (set SSL_CERT_FILE), E_UNIMPLEMENTED for a key or extension IronPKI does not implement (such as an RSA key over 4096 bits), E_BUDGET_EXCEEDED for capacity limits, and E_CRYPTO_FAILED for other IronPKI refusals. A missing file is E_NOT_FOUND, a non-regular or oversized file is E_BAD_ARG or E_BUDGET_EXCEEDED, and an unreadable file is a coded I/O error, never false. A non-certificate file is E_BAD_ARG.",
examples: &[
(r#"crypto_cert_verify("/etc/ssl/certs/ca-certificates.crt")"#, r#"true"#),
],
},
Signature {
name: "ssh_config",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("path", Ty::Str, "an ssh config file; default ~/.ssh/config")],
returns: "Array",
doc: "Host entries of an ssh config file as records. A missing file is E_NOT_FOUND.",
examples: &[
(r#"ssh_config()"#, r#"[{host: github.com, user: git, ...}]"#),
(r#"ssh_config("/etc/ssh/ssh_config")"#, r#"[{host: "*", ...}]"#),
],
},
// 1c: ssh and scp. Every host, remote path and local path is checked for
// option-like or shell-active text before a tool starts. Each run has a
// deadline and bounded output, and BatchMode is set so no password prompt can
// wait. These run code or move files on other hosts: see each doc.
Signature {
name: "ssh_exec",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("host", Ty::Str, "[user@]host"),
req("command", Ty::Str, "one command string; the remote login shell runs it"),
opt_range("port", Ty::Int, 1, 65535, "the ssh port; default 22"),
],
returns: "Record",
doc: "Run one command on a remote host over ssh. The command is one string that the remote login shell expands, so it runs there with that shell's rules; the host never reaches a local shell. Exit 0 returns {stdout, stderr, exit_code, success}. Any other exit is E_TOOL_FAILED with the status and the stderr tail. Output over 16 MiB is refused, and a run past 120 s is stopped. Runs code on another host.",
examples: &[
(r#"(try { ssh_exec("-oProxyCommand=id", "true") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ssh_exec("user@host", "") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ssh_exec("user@host", "true", 0) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ssh_tunnel",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("local_port", Ty::Int, "the local port to listen on, 1..65535"),
req("remote_host", Ty::Str, "the host the tunnel forwards to, as the ssh host sees it"),
req("remote_port", Ty::Int, "the port on remote_host, 1..65535"),
req("ssh_host", Ty::Str, "[user@]host to tunnel through"),
],
returns: "Record",
doc: "Start a local forward (ssh -N -L) through ssh_host and return {success, pid, local_port, remote_host, remote_port, ssh_host}. pid is the ssh process itself, so proc_kill(pid) stops the tunnel. The local port must be free on this machine: the call refuses one already in use. The call waits until the forward is listening, or fails when ssh exits or the deadline passes. ExitOnForwardFailure makes a port that cannot be bound an error. Opens a listening port on this machine.",
examples: &[
(r#"(try { ssh_tunnel(0, "db.internal", 5432, "bastion") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ssh_tunnel(15432, "db.internal", 5432, "-oProxyCommand=id") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ssh_keygen",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
opt("type", Ty::Str, "ed25519, rsa or ecdsa; default ed25519"),
opt("file", Ty::Str, "the private key file to create; default ~/.ssh/id_<type>"),
],
returns: "Record",
doc: "Generate an SSH key pair: the private key at file and the public key at file.pub. The private key has NO passphrase, so anyone who can read the file can use it. Existing key files are refused, not replaced, and the path passes the workspace write jail. Returns {passphrase: false, type, private_key, public_key, output}. Writes private key material to disk.",
examples: &[
(r#"(try { ssh_keygen("dsa") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ssh_keygen("ed25519", "-oX") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "ssh_copy_id",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("host", Ty::Str, "[user@]host"),
opt("key_file", Ty::Str, "an OpenSSH public key file; default ~/.ssh/id_ed25519.pub"),
],
returns: "Record",
doc: "Install a public key in the remote account's authorized_keys, with ssh-copy-id (or a manual, de-duplicated append on Windows). The key file must hold one OpenSSH public-key line; anything else is refused without its content being shown. Writes to the remote host. Returns {success, method, host}.",
examples: &[
(r#"(try { ssh_copy_id("-oProxyCommand=id") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { ssh_copy_id("user@host", "-oX") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "scp_upload",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("local_path", Ty::Str, "a local file; no ':' except a drive letter"),
req("remote", Ty::Str, "[user@]host:path, one file"),
opt_range("port", Ty::Int, 1, 65535, "the ssh port; default 22"),
],
returns: "Record",
doc: "Copy one local file to a remote host with scp (BatchMode, 600 s deadline). The remote path may not hold shell or glob characters. Returns {success, local_path, remote}. A failed transfer is E_TOOL_FAILED with the stderr tail. Sends a local file off this machine.",
examples: &[
(r#"(try { scp_upload("notes.txt", "-oProxyCommand=id:/tmp/x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { scp_upload("notes.txt", "host:/tmp/a;rm -rf x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { scp_upload("notes.txt", "host:/tmp/a", 0) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "scp_download",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("remote", Ty::Str, "[user@]host:path, one file"),
req("local_path", Ty::Str, "the new local file; must not exist"),
opt_range("port", Ty::Int, 1, 65535, "the ssh port; default 22"),
],
returns: "Record",
doc: "Copy one remote file to a new local file with scp (BatchMode, 600 s deadline). The local destination passes the workspace write jail and must not exist; a failed transfer removes it. The remote path may not hold shell or glob characters. Returns {success, remote, local_path}.",
examples: &[
(r#"(try { scp_download("host:/tmp/*.txt", "x.txt") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { scp_download("-oProxyCommand=id:/x", "x.txt") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { scp_download("host:/x", "x.txt", 0) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
// 1b: the monitor_* network and session readers. Machine-dependent: each
// reads the host through a tool (ip, ss, netstat, who, last, journalctl,
// nethogs, ethtool, or PowerShell on Windows). Each is bounded: a tool that
// is missing is E_TOOL_MISSING, one that fails is E_TOOL_FAILED with its
// stderr, and output past the cap is E_BUDGET_EXCEEDED.
Signature {
name: "monitor_iftop",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Network traffic counters: ss -s on Linux, netstat -s on macOS and Windows. A counter that cannot be read is E_TOOL_FAILED, never 0. Takes no arguments.",
examples: &[
(r#"monitor_iftop()"#, r#"{summary: "Total: 212 ...", ...}"#),
],
},
Signature {
name: "monitor_ip_route",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "The routing table as records: ip on Linux, Get-NetRoute on Windows, netstat -rn on macOS. Takes no arguments.",
examples: &[
(r#"monitor_ip_route()"#, r#"[{dst: default, gateway: 172.20.0.1, dev: eth0, ...}]"#),
],
},
Signature {
name: "monitor_nethogs",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Unix: bandwidth per program from nethogs -t (needs nethogs and root). There is no fallback: a missing nethogs is E_TOOL_MISSING and a failing one E_TOOL_FAILED. Windows: up to 30 established TCP connections with their process. The two platforms return different records. Takes no arguments.",
examples: &[
(r#"monitor_nethogs()"#, r#"[{program: "sshd/1234/0", sent_kbps: 1.5, received_kbps: 2.25}]"#),
],
},
Signature {
name: "monitor_sockets",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("filter", Ty::Str, "all (default), tcp, udp, or listening (LISTEN, or UNCONN for UDP)")],
returns: "Array",
doc: "Open TCP and UDP sockets. One query reads every socket and the filter is applied to its output, so tcp and udp include established connections. An unknown filter, or a filter that is not a String, is E_BAD_ARG. Linux: ss; macOS and Windows: netstat -an.",
examples: &[
(r#"monitor_sockets()"#, r#"[{protocol: tcp, local_address: "0.0.0.0:22", state: LISTEN, ...}]"#),
(r#"monitor_sockets("udp")"#, r#"[{protocol: udp, local_address: "0.0.0.0:53", ...}]"#),
],
},
Signature {
name: "monitor_users",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Users logged in to this machine: who on Unix, query user on Windows. [] when nobody is logged on. Takes no arguments.",
examples: &[
(r#"monitor_users()"#, r#"[{username: ada, terminal: pts/0, login_time: "..."}]"#),
],
},
Signature {
name: "monitor_ip_addr",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("interface", Ty::Str, "only this interface; it must exist")],
returns: "Array",
doc: "Interface addresses: ip on Linux, Get-NetIPAddress on Windows, ifconfig on macOS. An interface that does not exist is an error (E_NOT_FOUND on Windows, E_TOOL_FAILED elsewhere), not [].",
examples: &[
(r#"monitor_ip_addr()"#, r#"[{ifname: lo, addr_info: [...], ...}]"#),
(r#"monitor_ip_addr("lo")"#, r#"[{ifname: lo, addr_info: [...], ...}]"#),
],
},
Signature {
name: "monitor_ip_link",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("interface", Ty::Str, "only this interface; it must exist")],
returns: "Array",
doc: "Network interfaces and their link state: ip on Linux, Get-NetAdapter on Windows, ifconfig on macOS. An interface that does not exist is an error, not [].",
examples: &[
(r#"monitor_ip_link()"#, r#"[{ifname: lo, operstate: UNKNOWN, ...}]"#),
(r#"monitor_ip_link("lo")"#, r#"[{ifname: lo, operstate: UNKNOWN, ...}]"#),
],
},
Signature {
name: "monitor_logins",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("count", Ty::Int, "most recent logins, from 1 to 1000; default 20")],
returns: "Array",
doc: "Recent logins: last on Unix, the Security log on Windows (which needs an elevated shell; a refusal is E_TOOL_FAILED). A count outside 1 to 1000 is E_BAD_ARG.",
examples: &[
(r#"monitor_logins()"#, r#"[{user: ada, terminal: pts/0, login_time: "..."}]"#),
(r#"monitor_logins(5)"#, r#"[{user: ada, terminal: pts/0, login_time: "..."}]"#),
],
},
Signature {
name: "monitor_ethtool",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("device", Ty::Str, "an interface such as eth0, or a Windows adapter such as Ethernet")],
returns: "Record",
doc: "Linux, macOS and Windows. On Linux, an interface's driver-level settings, read with ethtool; a missing ethtool is E_TOOL_MISSING and a failing one is E_TOOL_FAILED with its stderr. On macOS, the interface is read with ifconfig name, which changes nothing: device, mtu, mac_address, and link_detected (yes or no from its status line, left out when the interface prints none, as loopback does). The speed and duplex fields are null on macOS, since ifconfig does not report them. An interface ifconfig says does not exist is E_NOT_FOUND. On Windows, the adapter named by Get-NetAdapter -Name: speed, duplex, link_detected, driver_description, driver_version and mac_address, with a field the adapter does not report left out; an unknown adapter is E_NOT_FOUND. Other platforms refuse with E_UNIMPLEMENTED and inspect nothing.",
examples: &[
(r#"monitor_ethtool("eth0")"#, r#"{device: eth0, speed: 10000Mb/s, link_detected: yes, ...}"#),
],
},
Signature {
name: "monitor_syslog",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("keyword", Ty::Str, "text to find: 1 to 256 characters, not starting with -"), opt("count", Ty::Int, "newest matches, from 1 to 1000; default 50")],
returns: "Array",
doc: "The newest system log entries containing a keyword. Linux: journalctl; the syslog file is read only when journalctl is not installed, and its records then carry MESSAGE and source. macOS: log show over the last hour. Windows: the newest 500 System events, matched on Message.",
examples: &[
(r#"monitor_syslog("error")"#, r#"[{MESSAGE: "...", ...}]"#),
(r#"monitor_syslog("error", 5)"#, r#"[{MESSAGE: "...", ...}]"#),
],
},
// 1b: compression and extraction. gzip is in-process (strict); the rest
// run a tool. Every example writes only under the system temp directory.
Signature {
name: "gzip_compress",
category: None,
subject_required: false,
aliases: &["compress"],
subject: None,
params: &[req("path", Ty::Str, "the file")],
returns: "Bool",
doc: "Write path.gz beside a file, keeping the file. An existing path.gz is not overwritten (E_BAD_STATE).",
examples: &[
(r#"compress(fs_tempfile("ae_gz"))"#, r#"true"#),
],
},
Signature {
name: "gzip_decompress",
category: None,
subject_required: false,
aliases: &["decompress"],
subject: None,
params: &[req("path", Ty::Str, "a .gz file")],
returns: "Bool",
doc: "Write a .gz file's contents beside it without the suffix, keeping the .gz. Invalid gzip data is refused.",
examples: &[
(r#"let d = fs_tempdir("ae_gz"); let f = d + "/a.txt"; file_write(f, "hello"); compress(f); file_move(f + ".gz", d + "/b.txt.gz"); decompress(d + "/b.txt.gz"); read_text(d + "/b.txt")"#, r#"hello"#),
],
},
Signature {
name: "gdb_run",
category: None,
subject_required: false,
aliases: &["gdb"],
subject: None,
params: &[
req("program", Ty::Str, "the program to run under gdb; one word, not starting with '-'"),
opt("commands", Ty::Str, "gdb commands, one per line (default: run, bt, quit); each line is one -ex argument"),
],
returns: "Record",
doc: "gdb --batch -ex <command>... <program>, answering {program, exit_code, output, stderr}. The commands can run shell commands inside gdb, and the program runs under it, so the call is an exec and the central gate asks for approval in agent mode. A script may hold at most 256 lines of at most 512 bytes. A nonzero exit is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { gdb_run("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { gdb_run("prog", "") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { gdb_run() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | gdb_run("prog") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "gh_pr",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("subcommand", Ty::Str, "checks, close, comment, create, diff, edit, list, ready, reopen, status or view; default list"), opt_rest("flags", Ty::Str, "flags and values for gh pr, passed through; --editor, --web and --browser are refused")],
returns: "Record",
doc: "gh pr <subcommand>. Read subcommands return {subcmd, exit_code, success, stdout, stderr}; create, comment, edit, close, reopen and ready change a remote and are approval-gated in agent mode. merge, review and checkout are not offered. A nonzero exit is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { gh_pr("merge") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { gh_pr("list", "--web") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "gh_issue",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("subcommand", Ty::Str, "close, comment, create, edit, list, reopen, status or view; default list"), opt_rest("flags", Ty::Str, "flags and values for gh issue, passed through; --editor and --web are refused")],
returns: "Record",
doc: "gh issue <subcommand>. Read subcommands return {subcmd, exit_code, success, stdout, stderr}; create, comment, edit, close and reopen change a remote and are approval-gated in agent mode. delete, transfer, pin and lock are not offered. A nonzero exit is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { gh_issue("delete") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { gh_issue("list", "--editor") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "gh_repo_cmd",
category: None,
subject_required: false,
aliases: &["gh_repo"],
subject: None,
params: &[opt("subcommand", Ty::Str, "list or view; default list"), opt_rest("flags", Ty::Str, "flags and values for gh repo, passed through; --web and --browser are refused")],
returns: "Record",
doc: "gh repo list or gh repo view, returning {subcmd, exit_code, success, stdout, stderr}. Every subcommand that changes a repository is refused. A nonzero exit is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { gh_repo_cmd("create") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { gh_repo("list", "--web") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "gdb_bt",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("program", Ty::Str, "the program the core came from; one word, not starting with '-'"),
req("core_file", Ty::Str, "an existing core file; one word, not starting with '-'"),
],
returns: "Record",
doc: "gdb --batch -ex 'bt full' <program> <core_file>, answering {program, core, backtrace, exit_code, stderr}. The backtrace keeps its last 4 MiB and sets output_truncated when cut. A missing core file is E_NOT_FOUND; a nonzero exit is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { gdb_bt("-x", "core") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { gdb_bt("prog") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | gdb_bt("prog", "core") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "bzip2_decompress",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a .bz2 file that exists")],
returns: "Bool",
doc: "Decompress a .bz2 file to a new file beside it, without the suffix, and return true. In agent mode or when a workspace is set (`--workspace` or IRONSHELL_WORKSPACE) the output is jailed to the workspace; it must not already exist, is capped at 1 GiB (a small archive can inflate without bound; a run past the cap is E_BUDGET_EXCEEDED and its partial output is removed), and has a deadline. Piped input is refused.",
examples: &[
(r#"(try { bzip2_decompress() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { bzip2_decompress("archive.gz") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "bzip2_compress",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "the file")],
returns: "Bool",
doc: "Write path.bz2 beside a file, keeping the file. A failure is E_TOOL_FAILED with the reason.",
examples: &[
(r#"bzip2_compress(fs_tempfile("ae_bz"))"#, r#"true"#),
],
},
Signature {
name: "xz_compress",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("file", Ty::Str, "the file to compress")],
returns: "Bool",
doc: "Write file.xz beside a file, keeping the file. An existing file.xz is refused (E_BAD_STATE) and never overwritten. A failure is E_TOOL_FAILED with the reason, and the partial output is removed.",
examples: &[
(r#"(try { xz_compress("-k") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "xz_decompress",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("file", Ty::Str, "a .xz file")],
returns: "Bool",
doc: "Write a .xz file's contents beside it without the suffix, keeping the .xz. Output past 1 GiB is refused and the partial file removed. An existing output is refused (E_BAD_STATE). Invalid xz data is E_TOOL_FAILED.",
examples: &[
(r#"(try { xz_decompress("notes.txt") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "zstd_compress",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("file", Ty::Str, "the file to compress")],
returns: "Bool",
doc: "Write file.zst beside a file, keeping the file. An existing file.zst is refused (E_BAD_STATE) and never overwritten. A failure is E_TOOL_FAILED with the reason, and the partial output is removed.",
examples: &[
(r#"(try { zstd_compress("-k") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "zstd_decompress",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("file", Ty::Str, "a .zst file")],
returns: "Bool",
doc: "Write a .zst file's contents beside it without the suffix, keeping the .zst. Output past 1 GiB is refused and the partial file removed. An existing output is refused (E_BAD_STATE). Invalid zstd data is E_TOOL_FAILED.",
examples: &[
(r#"(try { zstd_decompress("notes.txt") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "tar_extract",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("archive", Ty::Str, "a tar archive"), opt("dest", Ty::Str, "directory to extract into; default the current one")],
returns: "Bool",
doc: "Extract a tar archive. Entries that would land outside the destination (absolute names, `..` components, and symlinks or hard links with such targets) are refused with E_POLICY_DENY before anything is written. A bzip2, xz or zstd archive has its member names checked through tar -tf; its link targets are left to tar's own protection. A failure is E_TOOL_FAILED with the reason.",
examples: &[
(r#"tar_extract("tests/fixtures/archives/sample.tar.gz", fs_tempdir("ae_tar"))"#, r#"true"#),
(r#"tar_extract("no-such.tar")"#, r#"error: E_TOOL_FAILED"#),
],
},
Signature {
name: "zip_create",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("archive", Ty::Str, "the .zip file to create; must not exist"),
rest("files", Ty::Str, "one or more files to add"),
],
returns: "Bool",
doc: "Create a zip archive from files and folders, in-process on every platform. A folder is stored with everything in it, empty folders included; each member is stored under its last path component (tar_create keeps a relative path inside the current directory as written, and uses the last component only for a member outside it). An existing archive is refused (use zip_add); a missing member is E_NOT_FOUND; two members with one stored name are E_BAD_ARG. A failed run removes the archive it started.",
examples: &[
(r#"(try { zip_create("out.zip", "no-such-file.txt") } catch e { e.error.code })"#, "E_NOT_FOUND"),
(r#"(try { zip_create("out.zip") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { zip_create("out.zip", "-TT") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "zip_add",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("archive", Ty::Str, "an existing .zip file"),
rest("files", Ty::Str, "one or more files to add or refresh"),
],
returns: "Bool",
doc: "Add or refresh files and folders in an existing zip archive, in-process: a member whose stored name the archive already holds replaces that entry, and the rest are kept. A missing archive is E_NOT_FOUND; it is not created. A missing member is E_NOT_FOUND. A file that is not a zip is E_BAD_ARG.",
examples: &[
(r#"(try { zip_add("-TT", "a.txt") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { zip_add("out.zip") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "zip_extract",
category: None,
subject_required: false,
aliases: &["unzip"],
subject: None,
params: &[req("archive", Ty::Str, "a .zip file"), opt("dest", Ty::Str, "directory to extract into; default the current one")],
returns: "Bool",
doc: "Extract a zip archive. Entries that would land outside the destination (absolute names, drive or UNC paths, `..` components) are refused with E_POLICY_DENY before anything is written. Extracted in-process: files and empty folders are written under the destination (created if missing), symbolic-link entries are not created, and true is returned only after the entries were written. A file that is not a zip is E_BAD_ARG; a missing one is E_NOT_FOUND.",
examples: &[
(r#"unzip("tests/fixtures/archives/sample.zip", fs_tempdir("ae_zip"))"#, r#"true"#),
(r#"unzip("no-such.zip")"#, r#"error: E_TOOL_FAILED"#),
],
},
// 1b: the catalogue helpers. They read the declared signatures and the
// dispatcher; no model is consulted, so the answers are the same everywhere.
Signature {
name: "suggest",
category: None,
subject_required: false,
aliases: &["ai-suggest"],
subject: Some(Ty::Str),
params: &[],
returns: "Array",
doc: "Declared builtins whose name or description contains every word of a query, as {name, signature, doc}; at most 10.",
examples: &[
(r#"suggest("sha256 digest") | map(fn(s) => s.name)"#, r#"["sha256", "crypto_hash"]"#),
],
},
Signature {
name: "explain",
category: None,
subject_required: false,
aliases: &["ai-explain"],
subject: Some(Ty::Str),
params: &[],
returns: "Record",
doc: "A builtin's declared signature and description, or what an error code in the text means. Anything else is E_NOT_FOUND.",
examples: &[
(r#"explain("crypto_hash").name"#, r#"crypto_hash"#),
],
},
Signature {
name: "complete",
category: None,
subject_required: false,
aliases: &["ai-complete"],
subject: Some(Ty::Str),
params: &[],
returns: "Array",
doc: "Builtin names starting with a prefix, sorted; at most 20.",
examples: &[
(r#"complete("git_stat")"#, r#"["git_status"]"#),
],
},
Signature {
name: "fix",
category: None,
subject_required: false,
aliases: &["ai-fix"],
subject: Some(Ty::Any),
params: &[],
returns: "Record",
doc: "The minimal repair context for an error (as diagnose gives), from a caught error record or its text.",
examples: &[
(r#"fix("something broke").code"#, r#"E_UNKNOWN"#),
(r#"(try { crypto_hash("x", "blake3") } catch e { fix(e) }).code"#, r#"E_BAD_ARG"#),
],
},
// 1b: print, wc, cloud_config, syntax_list, imports, the SQLite/kv
// creators (temp files only), code_format, fs_readlink, db_json_query.
Signature {
name: "print",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Any),
params: &[],
returns: "String",
doc: "Show a value on stdout and return its plain text.",
examples: &[
(r#"print("hi")"#, r#"hi"#),
(r#"[1, 2] | print()"#, r#"[1, 2]"#),
],
},
Signature {
name: "wc",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[opt_rest("flags", Ty::Str, "-l, -w or -c to count only lines, words or characters")],
returns: "Record",
doc: "Line, word and character counts of piped text, or of a file named as the subject. An unknown flag is refused.",
examples: &[
(r#""a b\nc" | wc()"#, r#"{chars: 5, lines: 2, words: 3}"#),
(r#""a b\nc" | wc("-l")"#, r#"{lines: 2}"#),
],
},
Signature {
name: "cloud_config",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("options", Ty::Record, "provider, region, endpoint, instance_type")],
returns: "Record | Null",
doc: "Set the cloud configuration from a record, or read it back; null when nothing has been configured.",
examples: &[
(r#"cloud_config({region: "eu-west-1"}).region"#, r#"eu-west-1"#),
(r#"let c = cloud_config({region: "eu-west-1"}); cloud_config().region"#, r#"eu-west-1"#),
],
},
Signature {
name: "cloud_deploy",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("name", Ty::Str, "deployment name"), opt("options", Ty::Record, "region, instance_id or script, each a String")],
returns: "Record",
doc: "Not implemented: no cloud provider client is wired in, so no deployment is created. The name and options are checked first, and a valid call answers E_UNIMPLEMENTED. Takes no pipeline input.",
examples: &[
(r#"(try { cloud_deploy("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { cloud_deploy("app", {bogus: "x"}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "cloud_instance_create",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("name", Ty::Str, "instance name"), opt("options", Ty::Record, "region, type or workspace, each a String")],
returns: "Record",
doc: "Not implemented: no cloud provider client is wired in, so no instance is created. The name and options are checked first, and a valid call answers E_UNIMPLEMENTED. Takes no pipeline input.",
examples: &[
(r#"(try { cloud_instance_create("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { cloud_instance_create("web", {bogus: "x"}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "cloud_instance_destroy",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("id", Ty::Str, "instance ID")],
returns: "Record",
doc: "Destroys a cloud instance. Approval-gated in agent mode, and the gate runs before anything else. Then not implemented: no provider client is wired in, so the call answers E_UNIMPLEMENTED and destroys nothing. Takes no pipeline input.",
examples: &[
(r#"(try { cloud_instance_destroy("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "cloud_instance_status",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("id", Ty::Str, "instance ID")],
returns: "Record",
doc: "Not implemented: no provider is queried, so a valid call answers E_UNIMPLEMENTED. The ID is checked first. Takes no pipeline input.",
examples: &[
(r#"(try { cloud_instance_status("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "cloud_instance_connect",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("id", Ty::Str, "instance ID")],
returns: "Record",
doc: "Not implemented: no session is opened, so a valid call answers E_UNIMPLEMENTED. The ID is checked first. Takes no pipeline input.",
examples: &[
(r#"(try { cloud_instance_connect("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "syntax_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("category", Ty::Str, "protocol, language, encoding, command, query or a custom one")],
returns: "Array",
doc: "Ids in the syntax knowledge base, optionally of one category.",
examples: &[
(r#"typeof(syntax_list())"#, r#"Array"#),
(r#"typeof(syntax_list("protocol"))"#, r#"Array"#),
],
},
Signature {
name: "refactor_remove_unused", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("dir", Ty::Str, "project directory inside the workspace; must hold Cargo.toml")],
returns: "Bool",
doc: "Run cargo fix over the project in directory dir. This is not a targeted removal of unused code: cargo fix applies every machine-applicable suggestion the compiler makes, and removing unused imports is one kind of them. It does not pass --allow-dirty, so a version-controlled tree with uncommitted changes is refused with E_TOOL_FAILED. Returns true when cargo finished. The builtin rewrites files and compiles the project, so it is Exec and agent mode asks for approval. dir is required and checked as for test_bench. The run has a 900 s deadline. Takes no pipeline input.",
examples: &[
(r#"(try { refactor_remove_unused() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { refactor_remove_unused("") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "refactor_rename_file", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("from", Ty::Str, "existing file or directory inside the workspace"), req("to", Ty::Str, "new path inside the workspace; must not exist yet")],
returns: "Bool",
doc: "Rename the file or directory from to to, both inside the workspace, and return true. Refused before anything changes: E_BAD_ARG for a bad or identical path or an existing destination, E_OUTSIDE_WORKSPACE for a path outside the workspace, E_NOT_FOUND for a missing source. The destination must not exist, because the rename would silently replace it. Filesystem failures are E_IO. The write is recorded for an active transaction, so rollback restores the source and removes the destination. The existence check and the rename are not atomic; another process creating the destination in between is not detected. Takes no pipeline input.",
examples: &[
(r#"(try { refactor_rename_file("", "x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { refactor_rename_file("a", "a") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "remote_exec",
category: None,
subject_required: false,
aliases: &["exec_remote"],
subject: None,
params: &[req("node_id", Ty::Str, "a registered cluster node"), req("command", Ty::Str, "the command, of at most 8 KiB")],
returns: "Record",
doc: "Not implemented: no SSH or cluster transport is wired, so the command is not sent to the node, and a valid call answers E_UNIMPLEMENTED. When it is implemented, the remote node runs the command through its login shell, so the command is shell input. The node and command are checked first; a node that is not registered is E_NOT_FOUND. Also accepts node_id and command as a piped Record.",
examples: &[
(r#"(try { remote_exec("-x", "ls") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { remote_exec("n1", "") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "refactor_organize_imports",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("file", Ty::Str, "a Rust source file")],
returns: "Array",
doc: "A Rust file's `use` lines, sorted. It reads the file and does not change it.",
examples: &[
(r#"(refactor_organize_imports("src/lib.rs") | len) >= 0"#, r#"true"#),
],
},
Signature {
name: "db_kv_store",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("store", Ty::Str, "store file; default .ironshell_kv.db")],
returns: "String",
doc: "Create a key-value store (a SQLite file with a kv table) and return its path.",
examples: &[
(r#"db_kv_store(fs_tempdir("ae_kv") + "/s.db")"#, r#"/tmp/ae_kv_.../s.db"#),
],
},
Signature {
name: "db_sqlite_open",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("db", Ty::Str, "a SQLite file, created if missing")],
returns: "Bool",
doc: "Create or open a SQLite database file.",
examples: &[
(r#"let d = fs_tempdir("ae_db"); db_sqlite_open(d + "/x.db")"#, r#"true"#),
],
},
Signature {
name: "db_sqlite_vacuum",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("db", Ty::Str, "a SQLite file")],
returns: "Bool",
doc: "Rebuild a SQLite database to reclaim space: runs a fixed VACUUM in process, inside the workspace jail and journaled; no SQL from the caller reaches it.",
examples: &[
(r#"let d = fs_tempdir("ae_db"); db_sqlite_open(d + "/x.db"); db_sqlite_vacuum(d + "/x.db")"#, r#"true"#),
],
},
Signature {
name: "code_format",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("file", Ty::Str, "a .rs, .py, .js or .ts file, formatted in place")],
returns: "Bool",
doc: "Format a source file in place with its language formatter. An unsupported extension is refused.",
examples: &[
(r#"let f = fs_tempdir("ae_fmt") + "/a.rs"; file_write(f, "fn main(){}"); code_format(f)"#, r#"true"#),
],
},
Signature {
name: "fs_readlink",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a symbolic link")],
returns: "String",
doc: "A symlink's target. A missing path or one that is not a link is an error, not null.",
examples: &[
(r#"fs_readlink("/proc/self/exe")"#, r#"/usr/local/bin/ae"#),
],
},
Signature {
name: "jq",
category: None,
subject_required: false,
aliases: &["jq_query"],
subject: None,
params: &[
req("expression", Ty::Str, ". .key .key.sub .[n] .[] keys length, joined by |"),
opt("json", Ty::Str, "JSON text; default the piped input"),
],
returns: "Any",
doc: "Evaluate a jq expression over JSON in-process, without the jq binary. Supports ., .key, .key.sub, .[n], .[] (returns the elements as an array), keys, length, and | between them; .key[n] indexes too. length follows jq: the absolute value of a number, code points of a string, and an error for a boolean. A missing key is E_NOT_FOUND. Any other expression is refused, not guessed. JSON over 64 MiB is refused. Use jq_filter for a full jq filter.",
examples: &[
(r#"jq(".a.b", "{\"a\": {\"b\": 7}}")"#, "7"),
(r#""[1,2,3]" | jq("length")"#, "3"),
(r#"(try { jq(".a[x]", "{\"a\": [1]}") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "jq_filter",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("filter", Ty::Str, "a jq filter; a leading '-' is refused"),
opt("json", Ty::Str, "JSON text; default the piped input"),
],
returns: "Any",
doc: "Run a full jq filter over JSON with the jq binary, fed on stdin, with a 16 MiB output cap and a 600 s deadline. Output that parses as JSON is returned as a value, otherwise as text. A filter jq rejects is E_TOOL_FAILED with its stderr. Without jq on PATH this is E_TOOL_MISSING; it does not fall back to the native subset of jq.",
examples: &[
(r#"(try { jq_filter("-n") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { jq_filter("--slurp", "{}") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "db_json_query",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("path", Ty::Str, "a JSON file"), opt("filter", Ty::Str, "a jq filter; default .")],
returns: "Any",
doc: "Run a jq filter over a JSON file. A filter jq rejects is E_TOOL_FAILED, not the whole document.",
examples: &[
(r#"db_json_query(".well-known/ai-plugin.json", ".name_for_model")"#, r#"ironshell"#),
(r#"typeof(db_json_query(".well-known/ai-plugin.json"))"#, r#"Record"#),
],
},
// 1b: builtins whose answers made the discarded-args probe jitter
// between CI runs. Declared, they refuse extra arguments outright.
Signature {
name: "plugins",
category: None,
subject_required: false,
aliases: &["plugin_list"],
subject: None,
params: &[],
returns: "Array",
doc: "Registered plugins as records, sorted by id.",
examples: &[
(r#"plugins() | map(fn(p) => p.id)"#, r#"["builtin.csv", "builtin.json", "builtin.toml"]"#),
],
},
Signature {
name: "pnpm_run",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("script", Ty::Str, "a script name from package.json; a leading '-' is refused")],
returns: "Record",
doc: "Runs `pnpm run <script>` with no shell. Returns {script, exit_code: 0, success: true, stdout, stderr}; a nonzero exit is E_TOOL_FAILED with the tail of the output. Deadline 10 minutes; a missing pnpm is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | pnpm_run("build") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { pnpm_run("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "pnpm_install",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt_rest("packages", Ty::Str, "package specs; with none, installs the project's dependencies; a leading '-' is refused")],
returns: "Record",
doc: "Runs `pnpm install <packages...>` with no shell, in the working directory. The deadline is 15 minutes. Returns {exit_code: 0, success: true, stdout, stderr}; a nonzero exit is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | pnpm_install("left-pad") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { pnpm_install("-g") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "syntax_add", category: None, subject_required: false, aliases: &[], subject: Some(Ty::Record),
params: &[],
returns: "Bool",
doc: "Add one entry to the syntax knowledge base, which is saved to ~/.ironshell/syntax_kb.json, and return true. The entry is a Record with fields id (required; letters, digits, '_', '-' or '.', at most 128), name (required, non-blank), specification (required String), category (protocol, language, encoding, command or query; any other non-empty value makes a custom category; default custom) and examples (Array of String, optional). Piped or as the argument, never both. A misspelt field, a field of the wrong type, or an id already in the knowledge base is E_BAD_ARG, and nothing is saved in those cases. The file is under the home directory and not IRONSHELL_DATA_HOME; a failure to save is E_IO. If the file exists but does not load (corrupt or unreadable), syntax_add is E_BAD_STATE and saves nothing: the file is left untouched and never overwritten, while queries still answer from the knowledge base in memory.",
examples: &[
(r#"(try { syntax_add({id: "x"}) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { syntax_add({id: "x", name: "X", specification: "s", exmples: []}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "syntax_categories",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Categories in the syntax knowledge base, sorted.",
examples: &[
(r#"typeof(syntax_categories())"#, r#"Array"#),
],
},
Signature {
name: "syntax_search",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("query", Ty::Str, "text to find in names, ids and specifications")],
returns: "Array",
doc: "Ids of syntax knowledge-base entries matching a query, sorted.",
examples: &[
(r#"syntax_search("jsonrpc") | where(fn(x) => x == "jsonrpc") | len"#, r#"1"#),
],
},
Signature {
name: "hw_memory",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Total, used and free memory.",
examples: &[
(r#"hw_memory()"#, r#"{available: 12884901888, total: 17179869184, used: ...}"#),
],
},
Signature {
name: "sys_cpu_freq",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Int | Null",
doc: "CPU frequency in MHz: the clock Windows measured at boot, the current on Linux, the nominal on macOS. Null when the OS does not say (Apple Silicon, many VMs); a source that exists and cannot be read is a coded error, never null.",
examples: &[
(r#"sys_cpu_freq()"#, r#"3200"#),
],
},
// 1a: parameterless builtins -- terminal, docs, governor, sessions,
// telemetry, accounts and memory. Declared, they refuse arguments.
Signature {
name: "clear",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "The ANSI sequence that clears the screen, returned rather than printed.",
examples: &[
(r#"clear() | len"#, r#"7"#),
],
},
Signature {
name: "docs_examples",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Paths in the working directory's examples/ folder, sorted.",
examples: &[
(r#"(docs_examples() | len) > 0"#, r#"true"#),
],
},
Signature {
name: "governor_reset",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Bool",
doc: "Reset the resource-governor counters and clock, starting a fresh envelope.",
examples: &[
(r#"governor_reset()"#, r#"true"#),
],
},
Signature {
name: "nc_listen", category: None, subject_required: false, aliases: &[], subject: None,
params: &[Param { range: Some((1, 65535)), ..req("port", Ty::Int, "Port 1..65535") }, opt("options", Ty::Record, "optional {host: String literal IP default 127.0.0.1, timeout_ms: Int 1..10000 default 1000, max_bytes: Int 1..1048576 default 65536}")], returns: "Record",
doc: "Listen on 127.0.0.1 (or options.host) for one TCP connection, accept it before the timeout, read until EOF or max_bytes, then close the connection and listener. Returns {peer: String, data: String (lossy UTF-8), bytes: Int (bytes kept in data), truncated: Bool (true only when more data followed the limit)}. timeout_ms bounds the whole call; a timeout before EOF is E_IO and discards partial data. Network policy guards the bind address and the accepted peer, as net_listen does. Port zero, unknown options and pipeline input are refused.",
examples: &[(r#"(try { nc_listen("invalid") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { nc_listen(0) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { nc_listen(8080, {bogus: 1}) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "nc_connect", category: None, subject_required: false, aliases: &["nc", "netcat"], subject: None,
params: &[req("host", Ty::Str, "a host name or IP literal; a leading '-' is refused"), Param { range: Some((1, 65535)), ..req("port", Ty::Int, "TCP port 1..65535") }], returns: "Record",
doc: "Test whether a TCP port accepts a connection with netcat (nc -z). Returns {host, port, open, output}. A refused or unanswered connection is open false, which is the answer; any other netcat failure is E_TOOL_FAILED and a missing netcat is E_TOOL_MISSING. The run is bounded by netcat's own 5 s wait and a 120 s deadline. Refused inside a transaction.",
examples: &[
(r#"(try { nc_connect("-e", 1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { nc_connect("x", 0) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "socat_relay", category: None, subject_required: false, aliases: &["socat"], subject: None,
params: &[req("address1", Ty::Str, "outbound TCP, TCP4, UDP or UDP4 address: TCP:host:port"), req("address2", Ty::Str, "outbound TCP, TCP4, UDP or UDP4 address: TCP:host:port")], returns: "Record",
doc: "Relay data between two outbound connections with socat. Only TCP, TCP4, UDP and UDP4 to a host name or IPv4 literal and a port are accepted, with no options. EXEC, SYSTEM and SHELL run programs, OPEN and CREATE write files, and every LISTEN form opens a listener; each is refused by policy. The relay is killed at its 120 s deadline, so it cannot outlive the call. Returns {addr1, addr2, stdout, stdout_truncated}. Refused inside a transaction.",
examples: &[
(r#"(try { socat_relay("EXEC:/bin/sh", "TCP:127.0.0.1:1") } catch e { e.error.code })"#, "E_POLICY_DENY"),
(r#"(try { socat_relay("TCP-LISTEN:1", "STDIO") } catch e { e.error.code })"#, "E_POLICY_DENY"),
],
},
Signature {
name: "svc_create", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "unit name matching ^[a-z0-9][a-z0-9_-]{0,63}$; the unit is ironshell-<name>.service"), req("command", Ty::Array, "argv: absolute existing executable first, then String arguments without newline, carriage return or '%'"), opt("options", Ty::Record, "optional {description: String single line, user: existing account name, restart: \"no\"|\"on-failure\"|\"always\" default \"no\", enable: Bool default false, start: Bool default false}")],
returns: "Record",
doc: "Linux and Windows. On Linux, writes /etc/systemd/system/ironshell-<name>.service (0644, never overwriting an existing unit) whose first line is an IronShell marker, then runs systemctl daemon-reload and, when asked, enable and start. Returns {name: \"ironshell-<name>\", unit_path: String, enabled: Bool, started: Bool}. ExecStart quotes each argument in systemd syntax, so arguments with spaces or quotes are passed intact. If any later step fails, the unit is stopped and disabled as needed, the file is removed and the manager reloaded, so no half-created service remains. Needs root (or write access to /etc/systemd/system). On Windows it creates the service ironshell-<name> in the Service Control Manager with argv[0] as its program: an absolute existing .exe, given alone, since a service takes no arguments in this release, so any further argv element is E_BAD_ARG. enable selects start type auto (otherwise demand); the description is stored after an IronShell marker; restart \"on-failure\" sets three restarts 60 s apart, and \"always\" sets three restarts 1 s apart (Linux sets no RestartSec, so systemd\'s default applies there; the same 1 s is used here). Both set the failure actions with the non-crash flag, so a non-zero exit restarts too, and the failure count resets after 86400 s. On Windows \"always\" means restart on any failure, not after a clean exit: the Service Control Manager never restarts a service that stops with exit code 0, so this is as close to Linux\'s Restart=always as the manager allows. If the failure actions cannot be set, the new service is stopped and deleted and the error is returned; user must be an account the machine knows. start runs StartServiceW, and if any step fails the new service is stopped and deleted. On Windows unit_path is the service's registry key, HKLM\\SYSTEM\\CurrentControlSet\\Services\\ironshell-<name>. Needs an administrator. Refused inside a transaction. macOS refuses with E_UNIMPLEMENTED and changes nothing.",
examples: &[
(r#"(try { svc_create("Bad Name", ["/usr/bin/true"]) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { svc_create("Bad Name", ["/usr/bin/true"], {start: true}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "svc_delete", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "unit name matching ^[a-z0-9][a-z0-9_-]{0,63}$; removes ironshell-<name>.service")],
returns: "Record",
doc: "Linux and Windows. On Linux, removes /etc/systemd/system/ironshell-<name>.service only when the file carries the IronShell marker line; on Windows, removes the service ironshell-<name> only when its description carries the marker svc_create writes; a unit without it is refused with E_POLICY_DENY and left alone, and a missing unit is E_NOT_FOUND. Stops the unit if running, disables it if enabled, removes the file and runs systemctl daemon-reload. Returns {name: \"ironshell-<name>\", stopped: Bool (was running), disabled: Bool (was enabled), removed: true}. On Windows it waits up to 30 s for a running service to stop, and disabled means the service was not demand-start or disabled. Refused inside a transaction. macOS refuses with E_UNIMPLEMENTED and changes nothing.",
examples: &[(r#"(try { svc_delete("Bad Name") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "iperf3_server", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt("options", Ty::Record, "optional {bind: String literal IP default 127.0.0.1, port: Int 1024..65535 default 5201, timeout_ms: Int 1000..600000 default 60000}")],
returns: "Record",
doc: "Runs `iperf3 -s -1 -J` for one test, then exits, bound to options.bind and options.port, in its own process group. Returns {received_bytes: Int, seconds: Float, bits_per_second: Float (from end.sum_received), timed_out: false, exit_code: Int, duration_ms: Int, stdout: String, stderr: String}. If no client completes a test before timeout_ms, the server and its process tree are killed and the result is timed_out true with received_bytes, seconds and bits_per_second null; that is a result, not an error. A nonzero exit is E_TOOL_FAILED. A bind address other than loopback passes the network policy, as nc_listen does. A missing iperf3 is E_TOOL_MISSING. Pipeline input and unknown options are refused.",
examples: &[
(r#"(try { [1] | iperf3_server() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { iperf3_server({port: 80}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "iperf3_client", category: None, subject_required: false, aliases: &["iperf3"], subject: None,
params: &[req("host", Ty::Str, "iperf3 server host; a leading '-' is refused"), opt_range("port", Ty::Int, 1, 65535, "server port, default 5201")], returns: "Record",
doc: "Run one iperf3 bandwidth test as a client, with JSON output, and return iperf3's report as a Record. A failed test is E_TOOL_FAILED, a missing iperf3 is E_TOOL_MISSING, and the run has a 120 s deadline. Refused inside a transaction.",
examples: &[
(r#"(try { iperf3_client("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { iperf3_client("x", 0) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "entr_watch", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("paths", Ty::Array, "existing files or directories to watch, as Strings with no line break"), req("command", Ty::Array, "argv: absolute existing executable or plain name without '/' or a leading '-', then String arguments"), opt("options", Ty::Record, "optional {timeout_ms: Int 100..600000 default 30000}")],
returns: "Record",
doc: "Runs `entr -n -- <command>` with the paths written to entr's stdin, so the command runs once at start and again on every change to a listed path. entr is not postponed (-p), so the first run is immediate. The run is bounded by timeout_ms: at the deadline entr and the command's process tree are killed, so entr re-runs on change until then and nothing is left watching. Returns {exit_code: Int or null, timed_out: Bool, duration_ms: Int, stdout: String, stderr: String}; a deadline kill is timed_out true with exit_code null. No shell is used. A nonzero exit of entr itself is E_TOOL_FAILED; a missing entr is E_TOOL_MISSING.",
examples: &[
(r#"(try { entr_watch(["/nonexistent-ae-path"], ["true"]) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { entr_watch(["/nonexistent-ae-path"], ["true"], {timeout_ms: 1}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "watchexec_run", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("paths", Ty::Array, "existing files or directories to watch, as Strings; a leading '-' is refused"), req("command", Ty::Array, "argv: absolute existing executable or plain name without '/' or a leading '-', then String arguments"), opt("options", Ty::Record, "optional {timeout_ms: Int 100..600000 default 30000}")],
returns: "Record",
doc: "Runs `watchexec --shell=none -w <path>... -- <command>`: the command runs once at start and again on each change under the given paths, with no shell. The run is bounded by timeout_ms; at the deadline watchexec and the command's process tree are killed, so the command re-runs on change until then and nothing is left watching. Returns {exit_code: Int or null, timed_out: Bool, duration_ms: Int, stdout: String, stderr: String}; a deadline kill is timed_out true with exit_code null. A nonzero exit of watchexec itself is E_TOOL_FAILED; a missing watchexec is E_TOOL_MISSING.",
examples: &[
(r#"(try { watchexec_run(["/nonexistent-ae-path"], ["true"]) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { watchexec_run(["/nonexistent-ae-path"], ["true"], {timeout_ms: 1}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "nodemon_run", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("script", Ty::Str, "path to an existing .js file; it is the watched directory's entry point"), opt("options", Ty::Record, "optional {timeout_ms: Int 100..600000 default 30000}")],
returns: "Record",
doc: "Runs `nodemon --exitcrash --watch <script's directory> <script>` without stdin: the script runs at start and again on each change in its directory. A crash ends nodemon early. The run is bounded by timeout_ms; at the deadline nodemon and the script's process tree are killed, so nothing is left watching. Returns {exit_code: Int or null, timed_out: Bool, duration_ms: Int, stdout: String, stderr: String}; a deadline kill is timed_out true with exit_code null. A nonzero exit of nodemon itself is E_TOOL_FAILED; a missing nodemon is E_TOOL_MISSING.",
examples: &[
(r#"(try { nodemon_run("/nonexistent-ae-path/app.js") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { nodemon_run("/nonexistent-ae-path/app.js", {timeout_ms: 1}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "monitor_tcpdump",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
opt("interface", Ty::Str, "a capture interface such as lo or eth0; defaults to any"),
opt_range("count", Ty::Int, 1, 1000, "packets to capture before stopping; defaults to 10"),
opt_range("seconds", Ty::Int, 1, 60, "the duration cap; the capture is killed after this many seconds; defaults to 10"),
],
returns: "Record",
doc: "Linux only (macOS also runs it). Captures up to count packets on interface with tcpdump -nn -q, for at most seconds, then kills tcpdump and its process group. Returns {interface, count, captured, timed_out: Bool, packets: [{line}]}; timed_out is true when the duration cap stopped it first. Needs root for most interfaces. Other platforms refuse with E_UNIMPLEMENTED and capture nothing.",
examples: &[
(r#"(try { monitor_tcpdump("-i") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { monitor_tcpdump("lo", 0) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "monitor_perf_stat",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("argv", Ty::Array, "the program and its arguments as an Array of Strings, e.g. [\"/usr/bin/true\"]"),
opt("events", Ty::Str, "comma-separated perf events; defaults to cycles,instructions,cache-misses"),
],
returns: "Record",
doc: "Linux and Windows. Runs argv under perf stat -e events (no shell) on Linux and returns {command, events, counters: [{value, name}], raw_output}; on Windows it runs argv itself (no shell, no events argument) and returns {command, counters: [{name, value}], raw_output}, with task_clock_ms, user_ms, system_ms, elapsed_ms, peak_rss_bytes and page_faults from GetProcessTimes and GetProcessMemoryInfo, and hardware counters are not read there. A command string is E_BAD_ARG. A run past 120s is killed with its group and is E_BUDGET_EXCEEDED; a failing perf or command is E_TOOL_FAILED with its stderr. Other platforms refuse with E_UNIMPLEMENTED and run nothing.",
examples: &[
(r#"(try { monitor_perf_stat("sleep 1") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { monitor_perf_stat(["/usr/bin/true"], "-e") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "monitor_perf_record",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("argv", Ty::Array, "the program and its arguments as an Array of Strings, e.g. [\"/usr/bin/true\"]"),
opt("output", Ty::Str, "the file perf writes its profile to; defaults to perf.data in the working directory"),
],
returns: "Record",
doc: "Linux only. Runs argv under perf record -o output (no shell) and returns {command, output_file, bytes, success: true, details, hint}. The output's directory must exist and the path must not begin with '-'. A run past 120s is killed with its group and is E_BUDGET_EXCEEDED; a failing perf or command is E_TOOL_FAILED. Other platforms refuse with E_UNIMPLEMENTED and run nothing.",
examples: &[
(r#"(try { monitor_perf_record("sleep 1") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { monitor_perf_record(["/usr/bin/true"], "-o") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "monitor_htop",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
opt_range("count", Ty::Int, 1, 500, "how many processes to return, largest by memory first; defaults to 20"),
],
returns: "Array",
doc: "A snapshot of the process table read through sysinfo: no external program and no full-screen terminal UI. Returns the count largest processes by memory, each {pid, name, cpu_percent, memory_bytes, memory_mb}. Read-only; the CPU figures take about 200 ms to sample. Pipeline input and surplus arguments are E_BAD_ARG.",
examples: &[
(r#"monitor_htop()"#, r#"Array"#),
(r#"monitor_htop(3)"#, r#"Array"#),
],
},
Signature {
name: "monitor_iotop",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
opt_range("count", Ty::Int, 1, 500, "how many processes to return, largest I/O first; defaults to 20"),
],
returns: "Array",
doc: "A snapshot of per-process disk I/O read through sysinfo, not the iotop program and not a full-screen UI. Returns the count processes with the most I/O, each {pid, name, read_bytes, written_bytes, total_read_bytes, total_written_bytes}. The byte counts are cumulative since each process started, not rates. Read-only.",
examples: &[
(r#"monitor_iotop()"#, r#"Array"#),
(r#"monitor_iotop(3)"#, r#"Array"#),
],
},
Signature {
name: "monitor_nmon",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "A one-shot system snapshot read through sysinfo, not the nmon program and not a full-screen UI: CPU count and use, load averages (load_1, load_5, load_15; null on Windows, which has no load average), memory and disk totals, and a timestamp. Takes about 200 ms to sample CPU. Takes no arguments; pipeline input is E_BAD_ARG.",
examples: &[
(r#"monitor_nmon()"#, r#"Record"#),
],
},
Signature {
name: "monitor_glances",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "A one-shot system summary read through sysinfo, not the glances program and not a full-screen UI: host, uptime, per-CPU use, memory and swap, disks, network counters and load averages (load_1, load_5, load_15; null on Windows, which has no load average). Takes about 200 ms to sample CPU. Takes no arguments; pipeline input is E_BAD_ARG.",
examples: &[
(r#"monitor_glances()"#, r#"Record"#),
],
},
Signature {
name: "monitor_memory",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Physical and swap memory as {total, used, free, available, use_percent, swap_total, swap_used, swap_free}, in bytes, read through sysinfo. Takes no arguments; pipeline input is E_BAD_ARG.",
examples: &[
(r#"monitor_memory()"#, r#"Record"#),
],
},
Signature {
name: "monitor_dstat",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "A one-shot resource summary read through sysinfo, not the dstat program: per-CPU and total CPU use, memory, disks and network counters, with a timestamp. Takes about 200 ms to sample CPU. Takes no arguments; pipeline input is E_BAD_ARG.",
examples: &[
(r#"monitor_dstat()"#, r#"Record"#),
],
},
Signature {
name: "monitor_health_check",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Reads CPU, memory and disk use and returns {status: healthy, warning or critical, cpu_percent, memory_percent, disk_percent, load_1, load_5, load_15, process_count, alerts: [{type, severity, message, value, threshold}], timestamp}. The load fields are null on Windows, which has no load average. No network is contacted. Takes about 200 ms to sample CPU. Takes no arguments; pipeline input is E_BAD_ARG.",
examples: &[
(r#"monitor_health_check()"#, r#"Record"#),
],
},
Signature {
name: "monitor_alert_create",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("name", Ty::Str, "a name for the rule, 1 to 100 characters"),
req("metric", Ty::Str, "cpu, memory or disk"),
opt("condition", Ty::Str, "one of >, >=, <, <=; defaults to >"),
opt_range("threshold", Ty::Numeric, 0, 100, "a percentage from 0 to 100; defaults to 80"),
opt("severity", Ty::Str, "info, warning or critical; defaults to warning"),
],
returns: "Record",
doc: "Adds a rule to the alert store, a JSON file named alerts.json in the monitor directory of the data directory (IRONSHELL_DATA_HOME moves it), and records a created event in its history. Returns the stored rule {id, name, metric, condition, threshold, severity, status: active, created_at}. Nothing is evaluated or notified here: rules are checked when monitor_alert_list is called. The store holds at most 1000 rules (a full store is E_BUDGET_EXCEEDED). A store file that does not parse is E_IO and is left unchanged.",
examples: &[
(r#"(try { monitor_alert_create("", "cpu") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { monitor_alert_create("x", "gpu", "~", 150) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "monitor_alert_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Lists the rules in the alert store, each with its metric's current_value and triggered: whether that live reading breaches the rule now. An empty store returns []. Samples CPU for about 200 ms. Read-only.",
examples: &[
(r#"monitor_alert_list()"#, r#"Array"#),
],
},
Signature {
name: "monitor_alert_history",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
opt_range("limit", Ty::Int, 1, 1000, "how many events to return, newest first; defaults to 50"),
],
returns: "Array",
doc: "The rule-change history of the alert store: created and removed events, each {event, rule_id, name, at}, newest first. The store does not record when rules fire, so this is not a log of alerts that triggered. Read-only.",
examples: &[
(r#"monitor_alert_history()"#, r#"Array"#),
(r#"monitor_alert_history(5)"#, r#"Array"#),
],
},
Signature {
name: "monitor_alert_remove",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("id", Ty::Str, "the id of a rule, as monitor_alert_create returned it"),
],
returns: "Record",
doc: "Removes the rule with this id from the alert store and records a removed event. Returns {id, removed: true, timestamp}. An id with no rule is E_NOT_FOUND and nothing is changed.",
examples: &[
(r#"(try { monitor_alert_remove("") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { monitor_alert_remove(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "monitor_watch_cpu",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
opt_range("threshold", Ty::Numeric, 0, 100, "a CPU percentage from 0 to 100; defaults to 80"),
opt_range("samples", Ty::Int, 1, 10, "how many readings to take, 500 ms apart; defaults to 5"),
],
returns: "Record",
doc: "Takes samples readings of total CPU use, 500 ms apart, and returns {threshold, samples, average_cpu, breaches, alert, readings: [{sample, cpu_percent, above_threshold, timestamp}]}. alert is true when more than half the readings are above threshold. At the largest sample count a watch takes about 5 seconds. Read-only.",
examples: &[
(r#"monitor_watch_cpu()"#, r#"Record"#),
(r#"monitor_watch_cpu(95, 2)"#, r#"Record"#),
],
},
Signature {
name: "monitor_watch_memory",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
opt_range("threshold", Ty::Numeric, 0, 100, "a memory percentage from 0 to 100; defaults to 80"),
],
returns: "Record",
doc: "One reading of physical and swap memory: {status: healthy, warning or critical (above 95%), threshold, total_bytes, used_bytes, free_bytes, available_bytes, use_percent, above_threshold, swap_total, swap_used, swap_percent, timestamp}. Read-only.",
examples: &[
(r#"monitor_watch_memory()"#, r#"Record"#),
(r#"monitor_watch_memory(90)"#, r#"Record"#),
],
},
Signature {
name: "monitor_watch_disk",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
opt_range("threshold", Ty::Numeric, 0, 100, "a disk percentage from 0 to 100; defaults to 85"),
],
returns: "Record",
doc: "One reading of every mounted disk: {threshold, alert, disk_count, disks: [{mount, filesystem, total_bytes, used_bytes, available_bytes, use_percent, above_threshold, status}], timestamp}. alert is true when any disk is above threshold. Read-only.",
examples: &[
(r#"monitor_watch_disk()"#, r#"Record"#),
(r#"monitor_watch_disk(90)"#, r#"Record"#),
],
},
Signature {
name: "session_start",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Int",
doc: "A new session number for this process.",
examples: &[
(r#"typeof(session_start())"#, r#"Int"#),
],
},
Signature {
name: "telemetry_reset",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Clear the in-process telemetry event buffer and return {cleared: count, status, timestamp}. Nothing on disk is read or removed. Takes no arguments.",
examples: &[(r#"(try { telemetry_reset(1) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "telemetry_enable",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Turn on opt-in local telemetry recording.",
examples: &[
(r#"typeof(telemetry_enable())"#, r#"Record"#),
],
},
Signature {
name: "telemetry_disable",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Turn off local telemetry recording.",
examples: &[
(r#"typeof(telemetry_disable())"#, r#"Record"#),
],
},
Signature {
name: "a2ui_clear",
category: None,
subject_required: false,
aliases: &["ui_clear"],
subject: None,
params: &[],
returns: "Bool",
doc: "Clear the agent-to-UI event channel.",
examples: &[
(r#"a2ui_clear()"#, r#"true"#),
],
},
Signature {
name: "capabilities",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "On Linux, this process's capability sets as {effective, permitted, inheritable, bounding, ambient, uid, euid, gid, egid}, read from /proc/self/status. On Windows, {privileges: [{name, description, state}]} from whoami /priv, read-only and run without a shell. Elsewhere it is E_UNIMPLEMENTED.",
examples: &[
(r#"capabilities()"#, r#"a Record of capability sets on Linux, or of privileges on Windows"#),
],
},
Signature {
name: "cargo_run",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt_rest("args", Ty::Str, "arguments passed to the program after `--`; a leading \"--release\" selects the release profile; any other option-like argument is refused, so none can reach cargo as an option")],
returns: "Record",
doc: "Runs `cargo run [--release] [-- <args...>]` in the working directory, with no shell. Compiles, then runs the package's binary; the deadline is 15 minutes. Returns {exit_code: 0, success: true, stdout, stderr}; a nonzero exit is E_TOOL_FAILED with the tail of the output. A missing cargo is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | cargo_run() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { cargo_run("--config") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "cargo_build_cmd",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("profile", Ty::Str, "\"--release\" for the release profile; omitted builds the debug profile")],
returns: "Record",
doc: "Runs `cargo build [--release]` in the working directory. Build scripts run as part of the build. The deadline is 15 minutes. Returns {success: true, exit_code: 0, stdout, stderr}; a nonzero exit is E_TOOL_FAILED. Any other argument is refused. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | cargo_build_cmd() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { cargo_build_cmd("--verbose") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "cargo_test_cmd",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt_rest("args", Ty::Str, "optionally \"--release\" first, then at most one test-name filter; any other option-like argument is refused")],
returns: "Record",
doc: "Runs `cargo test [--release] [filter]` in the working directory, with no shell. The deadline is 15 minutes. Returns {exit_code: 0, success: true, stdout, stderr}; a failing test run is E_TOOL_FAILED carrying the end of its output. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | cargo_test_cmd() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { cargo_test_cmd("--nocapture") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "config_init", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "String",
doc: "Create the config directories and, when config.toml does not yet exist, write the default config file. Returns the text 'Created config file: <path>' or 'Config file already exists: <path>'. The directory comes from IRONSHELL_CONFIG_HOME when set. Takes no arguments and no pipeline input. Writes are not transactional: the file is created outside any rollback.",
examples: &[
(r#"(try { config_init("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "config_reload",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Bool",
doc: "Reload the shell configuration from disk and make it the one in use, so the prompt, colors and every other setting read by the running shell change at once. A config file that cannot be read or does not parse is E_BAD_STATE, and the settings in use stay as they were.",
examples: &[
(r#"config_reload()"#, r#"true"#),
],
},
Signature {
name: "config_set", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("path", Ty::Str, "a settable config path, such as ai.max_tokens or colors.theme"), req("value", Ty::Any, "a value of the path's type: Bool, String or Int as the path requires")],
returns: "String",
doc: "Set one config value and save the config file, returning 'Config saved: <path> = <value>'. For a key the shell stores but nothing acts on yet, the reply adds '(not applied: ...)' and names it: ai.default_model, ai.default_provider, ai.max_tokens, ai.streaming, colors.force, history.max_size, shell.show_tips, shell.vi_mode and shell.auto_cd. Settable paths: colors.enabled, colors.force, colors.true_color (Bool); colors.theme (String of 1 to 64 letters, digits, '_' or '-'); shell.show_banner, shell.show_tips, shell.vi_mode, shell.auto_cd (Bool); ai.default_model, ai.default_provider (non-blank String of at most 256 bytes, no control characters); ai.max_tokens (Int 1 to 4294967295); ai.streaming (Bool); history.enabled (Bool); history.max_size (Int 1 to 1000000). An unknown path, a value of the wrong type, or one out of range is E_BAD_ARG, and the file is neither read nor written. The file written is the one the shell reads: IRONSHELL_CONFIG when set; else config.toml in the config directory when it exists; else ~/.ironshellrc when it exists; else config.toml in the config directory (IRONSHELL_CONFIG_HOME when set). config_path() reports it as config_file. After the save the running shell reloads the configuration, so the new value is in effect when the call returns, as config_reload would make it. A failure to read, write or reload it is E_BAD_STATE. Takes no pipeline input.",
examples: &[
(r#"(try { config_set("ai.max_tokens", -1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { config_set("no.such.path", true) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "diag_config",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String | Null",
doc: "The clippy.toml (or .clippy.toml) in the working directory, or null.",
examples: &[
(r#"diag_config()"#, r#"null"#),
],
},
Signature {
name: "docs_changelog",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String | Null",
doc: "The CHANGELOG in the working directory (non-UTF-8 bytes replaced), or null if there is none.",
examples: &[
(r#"docs_changelog()"#, r#"# Changelog ..."#),
],
},
Signature {
name: "docs_readme",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String | Null",
doc: "The README in the working directory.",
examples: &[
(r#"docs_readme()"#, r#"# IronShell ..."#),
],
},
Signature {
name: "sys_users",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Accounts as {name, uid, gid, home, shell} (Windows: {name, enabled, last_logon}).",
examples: &[
(r#"sys_users()"#, r#"[{gid: 0, home: /root, name: root, shell: /bin/bash, uid: 0}, ...]"#),
],
},
Signature {
name: "platform_memory_free",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Int",
doc: "Available memory in bytes, measured the same way on every OS.",
examples: &[
(r#"platform_memory_free()"#, r#"8589934592"#),
],
},
// 1c: read-only listings the discarded-args probe still found ignoring
// arguments. Machine-dependent: each reads a tool or the host.
Signature {
name: "docker_images",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Local images as records (docker images --format json).",
examples: &[
(r#"docker_images()"#, r#"[{Repository: alpine, Tag: latest, ...}]"#),
],
},
Signature {
name: "docker_networks",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Docker networks as records.",
examples: &[
(r#"docker_networks()"#, r#"[{Name: bridge, Driver: bridge, ...}]"#),
],
},
Signature {
name: "docker_stats",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "One snapshot of per-container resource use.",
examples: &[
(r#"docker_stats()"#, r#"[{Name: web, CPUPerc: "0.10%", ...}]"#),
],
},
Signature {
name: "docker_volumes",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Docker volumes as records.",
examples: &[
(r#"docker_volumes()"#, r#"[{Name: data, Driver: local, ...}]"#),
],
},
Signature {
name: "docker_build",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("tag", Ty::Str, "image name and tag, not starting with '-'"), opt("path", Ty::Str, "build context directory; default the workspace; resolved and read-guarded")],
returns: "String",
doc: "Build an image from a local context with docker build, as an argv (no shell). Refuses option-like tags and paths, resolves the context against the workspace and guards it as a read. Output includes stderr, where build progress is written. A nonzero exit is E_TOOL_FAILED with the stderr tail; more than 4 MiB of output is E_BUDGET_EXCEEDED. Rejects pipeline input.",
examples: &[
(r#"(try { docker_build("-t") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { docker_build("app:1", "-ctx") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "docker_compose_down",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("file", Ty::Str, "compose file; validated, read-guarded and resolved against the workspace; default the compose project in the working directory")],
returns: "String",
doc: "Stop and remove a compose project with docker compose down. Destructive: approval is required in agent mode. Refuses option-like files and piped input before any effect. Nonzero exit is E_TOOL_FAILED with the stderr tail.",
examples: &[
(r#"(try { "x" | docker_compose_down() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { docker_compose_down("-f") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "docker_compose_ps",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("file", Ty::Str, "compose file; validated, read-guarded and resolved against the workspace; default the compose project in the working directory")],
returns: "Array",
doc: "List a compose project's containers as records (docker compose ps --format json). Refuses option-like files and piped input. Nonzero exit is E_TOOL_FAILED; output that is not JSON is E_TOOL_FAILED, never dropped rows.",
examples: &[
(r#"(try { "x" | docker_compose_ps() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { docker_compose_ps("-f") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "docker_compose_up",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("detach", Ty::Bool, "must be true or absent: a foreground compose up cannot be bounded"), opt("file", Ty::Str, "compose file; validated, read-guarded and resolved against the workspace; default the compose project in the working directory")],
returns: "String",
doc: "Start a compose project detached (docker compose up -d). Starts containers, so approval is required in agent mode. Refuses detach: false, option-like files and piped input before any effect. Progress is returned from stderr as well as stdout.",
examples: &[
(r#"(try { "x" | docker_compose_up() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { docker_compose_up(false) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "docker_cp",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("source", Ty::Str, "a local path, or container:path"), req("destination", Ty::Str, "a local path, or container:path")],
returns: "String",
doc: "Copy files between the host and a container with docker cp. Exactly one operand must be container:path. A host path copied out is guarded as a write (jailed in agent mode); one copied in is guarded as a read. Option-like operands are refused. Nonzero exit is E_TOOL_FAILED.",
examples: &[
(r#"(try { docker_cp("-x", "web:/tmp") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { docker_cp("a.txt", "b.txt") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "docker_exec",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("container", Ty::Str, "container name or ID, not starting with '-'"), req("command", Ty::Array, "argv: one String per argument, at least one; a shell string is refused")],
returns: "String",
doc: "Run an argv inside a running container with docker exec, never through a shell. Arguments after the container are passed to the command, including ones that begin with '-'. Output is trimmed stdout; a nonzero exit is E_TOOL_FAILED with the stderr tail. Executes code in the container, so it is Exec under the policy.",
examples: &[
(r#"(try { docker_exec("-x", ["id"]) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { docker_exec("web", "id -u") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "docker_inspect",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("name", Ty::Str, "container or image name or ID, not starting with '-'")],
returns: "Array",
doc: "The docker inspect JSON for a container or image, as an array of records. A nonzero exit is E_TOOL_FAILED; output that is not JSON is E_TOOL_FAILED.",
examples: &[
(r#"(try { docker_inspect("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { docker_inspect(["web"]) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "docker_logs",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("container", Ty::Str, "container name or ID, not starting with '-'"), opt_range("tail", Ty::Int, 1, 10000, "lines from the end, 1 to 10000; default 1000")],
returns: "String",
doc: "The last lines of a container's logs: its stdout, then its stderr. The tail is bounded so a long-running container cannot fill the answer; more than 4 MiB is E_BUDGET_EXCEEDED. Refuses piped input. A nonzero exit is E_TOOL_FAILED.",
examples: &[
(r#"(try { "x" | docker_logs("web") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { docker_logs("web", 0) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "docker_pull",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("image", Ty::Str, "image reference, not starting with '-'")],
returns: "String",
doc: "Pull an image from a registry with docker pull. Network access. Progress from stderr is included. A nonzero exit is E_TOOL_FAILED with the stderr tail.",
examples: &[
(r#"(try { docker_pull("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { docker_pull(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "docker_push",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("image", Ty::Str, "image reference, not starting with '-'")],
returns: "String",
doc: "Push an image to a registry with docker push. Network access. Progress from stderr is included. A nonzero exit is E_TOOL_FAILED with the stderr tail.",
examples: &[
(r#"(try { docker_push("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { docker_push(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "docker_rm",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("container", Ty::Str, "container name or ID, not starting with '-'"), opt("force", Ty::Bool, "remove a running container; default false")],
returns: "String",
doc: "Remove a container with docker rm. Destructive and irreversible: approval is required in agent mode. Refuses option-like names and piped input before the approval check. A nonzero exit is E_TOOL_FAILED.",
examples: &[
(r#"(try { "x" | docker_rm("web") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { docker_rm("-x", true) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "docker_run",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("image", Ty::Str, "image reference, not starting with '-'"), opt("command", Ty::Array, "argv for the container: one String per argument; a shell string is refused"), opt("flags", Ty::Record, "{detach, rm, name, port, env, volume} or any long flag name: value; Bool true sets it, false omits it")],
returns: "String",
doc: "Run a container with docker run, as an argv (no shell). Flags come from a Record; an unknown value type is refused, not ignored. Returns the container's stdout, trimmed (the container ID when detached). Starts a container, so it is Exec under the policy. A nonzero exit is E_TOOL_FAILED with the stderr tail.",
examples: &[
(r#"(try { docker_run("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { docker_run("alpine", "echo hi") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "docker_stop",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("container", Ty::Str, "container name or ID, not starting with '-'")],
returns: "String",
doc: "Stop a running container with docker stop. Returns a confirmation line. Refuses option-like names and piped input. A nonzero exit is E_TOOL_FAILED with the stderr tail.",
examples: &[
(r#"(try { docker_stop("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "docker_tag",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("source", Ty::Str, "existing image reference, not starting with '-'"), req("target", Ty::Str, "new image reference, not starting with '-'")],
returns: "String",
doc: "Give an existing image another name with docker tag. Returns a confirmation line. Refuses option-like references and piped input. A nonzero exit is E_TOOL_FAILED with the stderr tail.",
examples: &[
(r#"(try { docker_tag("-x", "y") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "docker_top",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("container", Ty::Str, "container name or ID, not starting with '-'")],
returns: "Array",
doc: "The processes in a container as records keyed by the lowercased column headers (docker top). A nonzero exit is E_TOOL_FAILED with the stderr tail. Refuses piped input.",
examples: &[
(r#"(try { docker_top("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "podman_build",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("tag", Ty::Str, "image name and tag, not starting with '-'"), opt("path", Ty::Str, "build context directory; default the workspace; resolved and read-guarded")],
returns: "String",
doc: "Build an image from a local context with podman build, as an argv (no shell). Refuses option-like tags and paths, resolves the context against the workspace and guards it as a read. Output includes stderr, where build progress is written. A nonzero exit is E_TOOL_FAILED with the stderr tail; more than 4 MiB of output is E_BUDGET_EXCEEDED. Rejects pipeline input.",
examples: &[
(r#"(try { podman_build("-t") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { podman_build("app:1", "-ctx") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "podman_exec",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("container", Ty::Str, "container name or ID, not starting with '-'"), req("command", Ty::Array, "argv: one String per argument, at least one; a shell string is refused")],
returns: "String",
doc: "Run an argv inside a running container with podman exec, never through a shell. Arguments after the container are passed to the command, including ones that begin with '-'. Output is trimmed stdout; a nonzero exit is E_TOOL_FAILED with the stderr tail. Executes code in the container, so it is Exec under the policy.",
examples: &[
(r#"(try { podman_exec("-x", ["id"]) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { podman_exec("web", "id -u") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "podman_images",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Local images as records (podman images --format json). A nonzero exit is E_TOOL_FAILED; output that is not JSON is E_TOOL_FAILED, never dropped rows. Takes no arguments and refuses piped input.",
examples: &[
(r#"(try { podman_images(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "podman_logs",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("container", Ty::Str, "container name or ID, not starting with '-'"), opt_range("tail", Ty::Int, 1, 10000, "lines from the end, 1 to 10000; default 1000")],
returns: "String",
doc: "The last lines of a container's logs: its stdout, then its stderr. The tail is bounded so a long-running container cannot fill the answer; more than 4 MiB is E_BUDGET_EXCEEDED. Refuses piped input. A nonzero exit is E_TOOL_FAILED.",
examples: &[
(r#"(try { "x" | podman_logs("web") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { podman_logs("web", 0) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "podman_ps",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("all", Ty::Bool, "include stopped containers; default false")],
returns: "Array",
doc: "Containers as records (podman ps --format json). A nonzero exit is E_TOOL_FAILED; output that is not JSON is E_TOOL_FAILED, never dropped rows. Refuses piped input.",
examples: &[
(r#"(try { "x" | podman_ps() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { podman_ps("yes") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "podman_pull",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("image", Ty::Str, "image reference, not starting with '-'")],
returns: "String",
doc: "Pull an image from a registry with podman pull. Network access. Progress from stderr is included. A nonzero exit is E_TOOL_FAILED with the stderr tail.",
examples: &[
(r#"(try { podman_pull("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { podman_pull(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "podman_rm",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("container", Ty::Str, "container name or ID, not starting with '-'"), opt("force", Ty::Bool, "remove a running container; default false")],
returns: "String",
doc: "Remove a container with podman rm. Destructive and irreversible: approval is required in agent mode. Refuses option-like names and piped input before the approval check. A nonzero exit is E_TOOL_FAILED.",
examples: &[
(r#"(try { "x" | podman_rm("web") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { podman_rm("-x", true) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "podman_run",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("image", Ty::Str, "image reference, not starting with '-'"), opt("command", Ty::Array, "argv for the container: one String per argument; a shell string is refused"), opt("flags", Ty::Record, "{detach, rm, name, port, env, volume} or any long flag name: value; Bool true sets it, false omits it")],
returns: "String",
doc: "Run a container with podman run, as an argv (no shell). Flags come from a Record; an unknown value type is refused, not ignored. Returns the container's stdout, trimmed (the container ID when detached). Starts a container, so it is Exec under the policy. A nonzero exit is E_TOOL_FAILED with the stderr tail.",
examples: &[
(r#"(try { podman_run("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { podman_run("alpine", "echo hi") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "podman_stop",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("container", Ty::Str, "container name or ID, not starting with '-'")],
returns: "String",
doc: "Stop a running container with podman stop. Returns a confirmation line. Refuses option-like names and piped input. A nonzero exit is E_TOOL_FAILED with the stderr tail.",
examples: &[
(r#"(try { podman_stop("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "poetry_run",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("command", Ty::Str, "the command to run in the Poetry environment; a path must lie inside the workspace and a leading '-' is refused"), opt_rest("args", Ty::Str, "arguments passed to the command; each must be a String")],
returns: "Record",
doc: "Runs `poetry run <command> <args...>` with no shell. Returns {exit_code: 0, success: true, stdout, stderr}; a nonzero exit is E_TOOL_FAILED with the tail of the output. Deadline 10 minutes; a missing poetry is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | poetry_run("pytest") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { poetry_run("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "poetry_install",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Runs `poetry install` in the working directory, installing the project's dependencies. The deadline is 15 minutes. Returns {exit_code: 0, success: true, stdout, stderr}; a nonzero exit is E_TOOL_FAILED. Takes no arguments and no pipeline input.",
examples: &[
(r#"(try { "x" | poetry_install() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { poetry_install("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "env_docker",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "docker's version line.",
examples: &[
(r#"env_docker()"#, r#"Docker version 27.3.1, build ..."#),
],
},
Signature {
name: "env_dotnet",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "dotnet's version.",
examples: &[
(r#"env_dotnet()"#, r#"9.0.100"#),
],
},
Signature {
name: "env_go",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "go's version line.",
examples: &[
(r#"env_go()"#, r#"go version go1.23.2 linux/amd64"#),
],
},
Signature {
name: "env_path",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "The PATH entries, in order, empty entries dropped.",
examples: &[
(r#"env_path()"#, r#"[/usr/local/bin, /usr/bin, /bin]"#),
],
},
Signature {
name: "env_python",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "python's version line.",
examples: &[
(r#"env_python()"#, r#"Python 3.12.7"#),
],
},
Signature {
name: "env_ruby",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "String",
doc: "ruby's version line.",
examples: &[
(r#"env_ruby()"#, r#"ruby 3.3.5 ..."#),
],
},
Signature {
name: "fs_mounts",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "Mounted filesystems as {device, mountpoint, fstype, options}.",
examples: &[
(r#"fs_mounts()"#, r#"[{device: /dev/sda1, fstype: ext4, mountpoint: /, ...}]"#),
],
},
Signature {
name: "hw_audio",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "List the host's sound devices as Records: {name, status} on Windows (PowerShell CIM), {name} on Linux (aplay -l) and {name, default_output} on macOS (system_profiler). Read-only: no device is opened. A query that fails or prints nothing usable is E_TOOL_FAILED, not an empty list; an OS without a listing is E_UNIMPLEMENTED.",
examples: &[(r#"hw_audio()"#, "Array")],
},
Signature {
name: "hw_pci",
category: None,
subject_required: false,
aliases: &["lspci"],
subject: None,
params: &[],
returns: "Array",
doc: "PCI devices as records.",
examples: &[
(r#"lspci()"#, r#"[{slot: "00:00.0", class: Host bridge, ...}]"#),
],
},
Signature {
name: "hw_usb",
category: None,
subject_required: false,
aliases: &["lsusb"],
subject: None,
params: &[],
returns: "Array",
doc: "USB devices as records.",
examples: &[
(r#"lsusb()"#, r#"[{bus: "001", device: "001", id: "1d6b:0002", ...}]"#),
],
},
Signature {
name: "pipx_list",
category: None,
subject_required: false,
aliases: &["pipx"],
subject: None,
params: &[],
returns: "String",
doc: "pipx list, as pipx prints it.",
examples: &[
(r#"pipx()"#, r#"venvs are in ... package black 24.8.0 ..."#),
],
},
Signature {
name: "pipx_install",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("package", Ty::Str, "a package spec: a name, a version, or a URL; file: and link: specs are refused")],
returns: "Record",
doc: "pipx install of one package, returning {package, exit_code, success, stdout, stderr}. It installs a Python application, so it fetches and runs package code. A nonzero exit is E_TOOL_FAILED. Runs with a 15 minute deadline. Takes no pipeline input.",
examples: &[
(r#"(try { pipx_install("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { pipx_install("file:./pkg") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "pkg_history",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt_range("limit", Ty::Int, 1, 1000, "how many of the newest transactions to return; default 50")],
returns: "Array",
doc: "Transactions, newest first, at most limit (1 to 1000, default 50). On Linux they come from the apt history log (/var/log/apt/history.log), each a Record {start, end, command, installed, upgraded, removed}: end and command are null when the log does not record them, and each package is named without its version. The last 64 MiB of an uncompressed log is read; a block cut at the front is dropped. A missing log is E_NOT_FOUND. On macOS they come from the installs in /var/log/install.log, one row per installer line that reports an install, in the same Record shape: start is the line's timestamp, end and command are null, installed holds the package name (the quoted name, without its version) and upgraded and removed are empty, since that log records no removals. The log is read whole up to the file-size limit; a larger log is E_BUDGET_EXCEEDED. On Windows they are the successful MsiInstaller installs (event 1033) and removals (event 1034) in the Application log, each a Record {time, action, package, version} with action install or remove. Elsewhere the call is E_UNIMPLEMENTED and NOTHING WAS READ.",
examples: &[
(r#"pkg_history()"#, r#"[{start: "2026-09-01 10:02:11", end: "2026-09-01 10:02:14", command: "apt install curl", installed: [curl:amd64, libcurl4:amd64], upgraded: [], removed: []}, ...]"#),
(r#"pkg_history(1)"#, r#"[{start: "2026-09-01 10:02:11", end: "2026-09-01 10:02:14", command: "apt install curl", installed: [curl:amd64, libcurl4:amd64], upgraded: [], removed: []}]"#),
],
},
Signature {
name: "pkg_changelog",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("package", Ty::Str, "package name")],
returns: "String",
doc: "The package's changelog, as apt-get changelog prints it. Only apt is supported; another package manager is E_UNIMPLEMENTED. The changelog is fetched from the network. The output is bounded, and a nonzero exit is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { pkg_changelog("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { pkg_changelog("bash", "x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
// 1c: container, session and lint listings from the discarded-args
// worklist. Machine-dependent: each runs a tool.
Signature {
name: "buildah_images",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Any",
doc: "Buildah images, as buildah images --json reports them.",
examples: &[
(r#"buildah_images()"#, r#"[{id: "...", names: ["localhost/app:latest"], ...}]"#),
],
},
Signature {
name: "buildah_build",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("tag", Ty::Str, "image reference to tag the built image with"), opt("context", Ty::Str, "build context directory inside the workspace; default the workspace directory")],
returns: "Record",
doc: "buildah bud -t <tag> <context>, returning {tag, exit_code, success, stdout, stderr}. A URL or git context is refused, and the context must exist inside the workspace. A nonzero exit is E_TOOL_FAILED. Runs with a 15 minute deadline. Takes no pipeline input.",
examples: &[
(r#"(try { buildah_build("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { buildah_build("app:1", "https://example.invalid/x.git") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "bun_run",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("script", Ty::Str, "a package.json script name or a file path inside the workspace; a leading '-' is refused")],
returns: "Record",
doc: "Runs `bun run <script>` with no shell. Returns {script, exit_code: 0, success: true, stdout, stderr}; a nonzero exit is E_TOOL_FAILED with the tail of the output. Deadline 10 minutes; a missing bun is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | bun_run("dev") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { bun_run("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "bun_install",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt_rest("packages", Ty::Str, "package specs; with none runs `bun install`, with some runs `bun add`; a leading '-' is refused")],
returns: "Record",
doc: "Runs `bun install`, or `bun add <packages...>` when packages are given, with no shell, in the working directory. The deadline is 15 minutes. Returns {exit_code: 0, success: true, stdout, stderr}; a nonzero exit is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | bun_install("left-pad") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { bun_install("-g") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "docker_ps",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("all", Ty::Bool, "include stopped containers")],
returns: "Array",
doc: "Containers as records; running only unless all is true.",
examples: &[
(r#"docker_ps()"#, r#"[{Names: web, State: running, ...}]"#),
(r#"docker_ps(true)"#, r#"[{Names: web, ...}, {Names: old, State: exited, ...}]"#),
],
},
Signature {
name: "netstat",
category: None,
subject_required: false,
aliases: &["netstat_info"],
subject: None,
params: &[opt("filter", Ty::Record, "{proto?, state?, port?}")],
returns: "Array",
doc: "Network connections as {proto, local_address, foreign_address, state}, optionally filtered.",
examples: &[
(r#"netstat()"#, r#"[{proto: tcp, local_address: "0.0.0.0:22", state: LISTEN, ...}]"#),
(r#"netstat({proto: "tcp"})"#, r#"[{proto: tcp, ...}]"#),
],
},
Signature {
name: "screen_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "screen sessions as {id, line}.",
examples: &[
(r#"screen_list()"#, r#"[{id: 1234.work, line: "1234.work (Detached)"}]"#),
],
},
Signature {
name: "screen_new",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("session_name", Ty::Str, "1-64 letters, digits, '-' or '_'; not starting with '-'")],
returns: "Record",
doc: "screen -dmS <name>: a detached GNU screen session running the default shell, answered as {session, exit_code, success, stdout, stderr}. It takes no command. A failure is E_TOOL_FAILED. Its effect is process. Takes no pipeline input.",
examples: &[
(r#"(try { screen_new("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { screen_new("a.b") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { screen_new("work", "ls") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | screen_new("work") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "screen_attach",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("session_name", Ty::Str, "an existing session's name; 1-64 letters, digits, '-' or '_'")],
returns: "Record",
doc: "screen -r <name>: attaches this terminal until the user detaches, then answers {session, success}. It needs a terminal on both stdin and stdout; without one, or in agent mode, it is refused as E_NO_UI before anything runs, so it cannot hang. Its effect is process. Takes no pipeline input.",
examples: &[
(r#"(try { screen_attach("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { screen_attach() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | screen_attach("work") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "tmux_list",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "tmux sessions as {name, windows, attached}; [] when no server runs.",
examples: &[
(r#"tmux_list()"#, r#"[{attached: false, name: work, windows: 2}]"#),
],
},
Signature {
name: "tmux_new",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("session_name", Ty::Str, "1-64 letters, digits, '-' or '_'; not starting with '-'")],
returns: "Record",
doc: "tmux new-session -d -s <name>: a detached session running the default shell, answered as {session, exit_code, success, stdout, stderr}. It takes no command: tmux runs a command string through a shell, so start a program with tmux_send instead, which is approval-gated. A name already in use is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { tmux_new("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { tmux_new("a:b") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { tmux_new("work", "ls") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | tmux_new("work") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "tmux_attach",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("session_name", Ty::Str, "an existing session's name; 1-64 letters, digits, '-' or '_'")],
returns: "Record",
doc: "tmux attach-session -t <name>: attaches this terminal until the user detaches, then answers {session, success}. It needs a terminal on both stdin and stdout; without one, or in agent mode, it is refused as E_NO_UI before anything runs, so it cannot hang. Its effect is process. Takes no pipeline input.",
examples: &[
(r#"(try { tmux_attach("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { tmux_attach() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | tmux_attach("work") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "tmux_send",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("target", Ty::Str, "the session the caller names: a session, or session:window.pane, one word"),
req("keys", Ty::Str, "one line of text typed into the session, with no control characters and not starting with '-'"),
],
returns: "Record",
doc: "tmux send-keys -t <target> <keys> Enter: types one line into a session and presses Enter, answering {target, keys, exit_code, success, stdout, stderr}. This is execution in another process's shell, so the central gate asks for approval in agent mode. A session that does not exist is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { tmux_send("-x", "ls") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { tmux_send("work", "-la") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { tmux_send("work", "ls\nrm x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { tmux_send("work") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "tmux_kill",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("session_name", Ty::Str, "an existing session's name; 1-64 letters, digits, '-' or '_'; not starting with '-'")],
returns: "Record",
doc: "tmux kill-session -t <name>: ends a session that tmux_new started, and everything running in it, answered as {session, exit_code, success, stdout, stderr}. It runs no command, so it is process control: the central gate asks for approval in agent mode. A session that does not exist is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { tmux_kill("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { tmux_kill("a:b") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { tmux_kill("work", "ls") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { tmux_kill() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { "x" | tmux_kill("work") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "eslint_check",
category: None,
subject_required: false,
aliases: &["eslint"],
subject: None,
params: &[opt("path", Ty::Str, "a file or directory inside the workspace; defaults to the working directory")],
returns: "Array",
doc: "Runs eslint --format=json on a path (eslint.cmd on Windows), directly and never through a shell, and returns its JSON report: one entry per linted file. Exit 0 (clean) and exit 1 (problems found) are both answers; any other exit is E_TOOL_FAILED with the stderr tail, and output that is not JSON is too. The path must lie inside the workspace and must not begin with '-'. Output is bounded at 16 MiB and refused beyond that. Deadline 15 minutes. eslint loads the project's configuration and plugins, which run project code, so the call is classified Exec. A missing eslint is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { eslint_check(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { eslint_check("--fix") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "hadolint_check",
category: None,
subject_required: false,
aliases: &["hadolint"],
subject: None,
params: &[opt("path", Ty::Str, "a Dockerfile inside the workspace; defaults to ./Dockerfile")],
returns: "Array",
doc: "Runs hadolint --format json on a Dockerfile and returns its findings as an Array (empty when clean). Exit 0 and exit 1 (findings) are both answers; any other exit is E_TOOL_FAILED with the stderr tail, and so is output that is not JSON. A file that does not exist is E_NOT_FOUND. The path must lie inside the workspace and must not begin with '-'. Output is bounded at 16 MiB. Deadline 2 minutes. A missing hadolint is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { hadolint_check(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { hadolint_check("-v") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "mypy_check",
category: None,
subject_required: false,
aliases: &["mypy"],
subject: None,
params: &[opt("path", Ty::Str, "a file or directory inside the workspace; defaults to the working directory")],
returns: "Record",
doc: "Runs mypy on a path and returns {success, issues}: success is true only for exit 0, and issues lists mypy's report lines without its summary lines. Exit 1 (type errors) is an answer; any other exit is E_TOOL_FAILED with the stderr tail. The path must lie inside the workspace and must not begin with '-'. Output is bounded at 4 MiB. mypy writes its cache under the workspace, so the call is classified WriteLocal. Deadline 15 minutes. A missing mypy is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { mypy_check(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { mypy_check("--strict") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "prettier_format",
category: None,
subject_required: false,
aliases: &["prettier"],
subject: None,
params: &[req("path", Ty::Str, "a file inside the workspace"), opt("mode", Ty::Str, "\"--write\" to rewrite the file in place; absent prints the formatted text and changes nothing")],
returns: "Record",
doc: "Runs prettier (prettier.cmd on Windows) on one file, directly and never through a shell, and returns {path, exit_code: 0, success: true, stdout, stderr}. Without \"--write\" the formatted text is stdout and no file changes; with it the file is rewritten in place. The only accepted mode is \"--write\". A nonzero exit is E_TOOL_FAILED with the stderr tail; output over 4 MiB is refused. Deadline 10 minutes. Prettier loads project configuration and plugins, so the call runs project code. A missing prettier is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { prettier_format(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { prettier_format("x.js", "--check") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "pytest_run",
category: None,
subject_required: false,
aliases: &["pytest"],
subject: None,
params: &[opt_rest("args", Ty::Str, "options and test selectors, passed after -v in the order given")],
returns: "Record",
doc: "Runs pytest -v with the given arguments, directly and never through a shell, and returns {exit_code: 0, success: true, stdout, stderr}. Each argument must be a String. A path-shaped argument that is not an option must lie inside the workspace; options are passed through as given, so an option that names a path outside it is not checked. A failing test run is a nonzero exit and so E_TOOL_FAILED, with the end of its output in the message. Deadline 10 minutes. pytest imports the project's test code, so the call is classified Exec. A missing pytest is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { pytest_run(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { pytest_run("-k", 5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "shfmt_format",
category: None,
subject_required: false,
aliases: &["shfmt"],
subject: None,
params: &[req("path", Ty::Str, "a shell script inside the workspace")],
returns: "String",
doc: "Runs shfmt on one script without -w and returns the formatted text. No file is changed, although the call is classified WriteLocal. The path must lie inside the workspace and must not begin with '-' (shfmt reads '-' as standard input). A nonzero exit is E_TOOL_FAILED with the stderr tail; output over 4 MiB is refused. Deadline 2 minutes. A missing shfmt is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { shfmt_format(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { shfmt_format("-") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "skopeo_copy",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("src", Ty::Str, "source transport reference, such as docker://image:tag or dir:path"), req("dst", Ty::Str, "destination transport reference")],
returns: "Record",
doc: "skopeo copy <src> <dst>, returning {src, dst, exit_code, success, stdout, stderr}. Each reference names a transport: docker://, docker-daemon:, containers-storage:, docker-archive:, oci-archive:, oci: or dir:. A local transport's path must lie inside the workspace. A nonzero exit is E_TOOL_FAILED. Runs with a 15 minute deadline. Takes no pipeline input.",
examples: &[
(r#"(try { skopeo_copy("-x", "docker://a") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { skopeo_copy("alpine", "docker://a") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "skopeo_inspect",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("image", Ty::Str, "transport reference, such as docker://image:tag or dir:path")],
returns: "Record",
doc: "skopeo inspect of a transport reference, as the JSON Record it prints. Transports and local paths are checked as skopeo_copy checks them. A nonzero exit is E_TOOL_FAILED, and output that is not JSON is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { skopeo_inspect("alpine") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { skopeo_inspect("docker://-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "shellcheck_check",
category: None,
subject_required: false,
aliases: &["shellcheck"],
subject: None,
params: &[req("path", Ty::Str, "a shell script")],
returns: "Array",
doc: "shellcheck's findings for a script ([] when clean). A file it cannot read is E_TOOL_FAILED, not a clean result.",
examples: &[
(r#"shellcheck("scripts/run_tests.sh")"#, r#"[{code: 2086, level: info, line: 12, message: "Double quote ..."}, ...]"#),
],
},
Signature {
name: "yamllint_check",
category: None,
subject_required: false,
aliases: &["yamllint"],
subject: None,
params: &[req("path", Ty::Str, "a YAML file")],
returns: "Record",
doc: "yamllint's result as {success, issues}. A file it cannot read is E_TOOL_FAILED.",
examples: &[
(r#"yamllint(".github/workflows/ci.yml")"#, r#"{issues: [], success: true}"#),
],
},
Signature {
name: "yarn_run",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("script", Ty::Str, "a script name from package.json; a leading '-' is refused")],
returns: "Record",
doc: "Runs `yarn run <script>` with no shell. Returns {script, exit_code: 0, success: true, stdout, stderr}; a nonzero exit is E_TOOL_FAILED with the tail of the output. Deadline 10 minutes; a missing yarn is E_TOOL_MISSING. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | yarn_run("build") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { yarn_run("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "yarn_install",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt_rest("packages", Ty::Str, "package specs; with none runs `yarn install`, with some runs `yarn add`; a leading '-' is refused")],
returns: "Record",
doc: "Runs `yarn install`, or `yarn add <packages...>` when packages are given, with no shell, in the working directory. The deadline is 15 minutes. Returns {exit_code: 0, success: true, stdout, stderr}; a nonzero exit is E_TOOL_FAILED. Takes no pipeline input.",
examples: &[
(r#"(try { "x" | yarn_install("left-pad") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { yarn_install("-g") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
// 1c: the in-process MCP server's listings. They read only the
// built-in tool catalogue, so they answer the same everywhere.
Signature {
name: "agent_with_mcp",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("goal", Ty::Str, "the task"), req("tools", Ty::Array, "builtin tool names (an mcp: prefix is stripped); with an endpoint, mcp:<name> must be a tool that server lists"), opt("endpoint", Ty::Any, "a loopback MCP server URL that detect_mcp_servers finds; its tools are the mcp: names")],
returns: "Record",
doc: "Run a model-driven agent over named builtin tools and, with an endpoint, the tools of the MCP server at it. The endpoint is connected as mcp_connect connects: only a loopback server that detect_mcp_servers finds is contacted, and any other address is refused. Its tools are named mcp:<tool> and only names in its tools/list are served; each call is guarded as a network effect. The model call is guarded as a network effect and each builtin call passes the dispatch guard; a run without a final answer is refused.",
examples: &[
(r#"(try { agent_with_mcp(5, []) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { agent_with_mcp("x", ["no_such_tool_xyz"]) } catch e { e.error.code })"#, "E_NOT_FOUND"),
(r#"(try { agent_with_mcp("x", [], "http://127.0.0.1:9") } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "mcp_prompts",
category: None,
subject_required: false,
aliases: &["mcp_list_prompts"],
subject: None,
params: &[opt("name", Ty::Str, "one prompt by name")],
returns: "Array | Record",
doc: "The MCP prompts, or one by name. An unknown name is E_NOT_FOUND.",
examples: &[
(r#"mcp_prompts() | map(fn(p) => p.name)"#, r#"["find-tool", "explain-tool"]"#),
(r#"mcp_prompts("find-tool").name"#, r#"find-tool"#),
],
},
Signature {
name: "mcp_resources",
category: None,
subject_required: false,
aliases: &["mcp_list_resources"],
subject: None,
params: &[opt("type", Ty::Str, "only resources whose MIME type contains this")],
returns: "Array",
doc: "The MCP resources, optionally filtered by MIME type.",
examples: &[
(r#"mcp_resources() | len"#, r#"3"#),
(r#"mcp_resources("json") | len"#, r#"3"#),
],
},
Signature {
name: "mcp_server",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("config", Ty::Record, "{max_safety_level?, allow_admin?, blocked_tools?, allowed_categories?}")],
returns: "Record",
doc: "Describe the in-process MCP server a config would create. An unknown safety level is refused.",
examples: &[
(r#"mcp_server().server_name"#, r#"ironshell-mcp"#),
(r#"mcp_server({max_safety_level: "safe"}).server_name"#, r#"ironshell-mcp"#),
],
},
// The MCP builtins beside mcp_server: detection, the tool catalogue, the
// calls that run a catalogue tool, and the server declaration.
Signature {
name: "mcp_servers",
category: None,
subject_required: false,
aliases: &["mcp-servers"],
subject: None,
params: &[],
returns: "Array",
doc: "The MCP servers answering on the loopback ports IronShell probes, each with name, endpoint, availability and tool names. An empty array when none answers.",
examples: &[
(r#"(try { mcp_servers(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"typeof(mcp_servers())"#, "Array"),
],
},
Signature {
name: "mcp_detect",
category: None,
subject_required: false,
aliases: &["mcp-detect"],
subject: None,
params: &[opt("endpoint", Ty::Str, "one of the detected endpoints, such as http://localhost:3001")],
returns: "Record | Null",
doc: "The first detected MCP server, or the one at the given endpoint. Null when no detected server matches. A piped value is refused.",
examples: &[
(r#"(try { mcp_detect(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"mcp_detect("http://127.0.0.1:9")"#, "null"),
],
},
Signature {
name: "mcp_cache_clear",
category: None,
subject_required: false,
aliases: &["mcp-cache-clear"],
subject: None,
params: &[],
returns: "Bool",
doc: "Empty the in-process MCP detection cache. Only memory is touched; nothing on disk is read or written. true once cleared.",
examples: &[
(r#"(try { mcp_cache_clear(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"mcp_cache_clear()"#, "true"),
],
},
Signature {
name: "mcp_cache_status",
category: None,
subject_required: false,
aliases: &["mcp-cache-status"],
subject: None,
params: &[],
returns: "Record",
doc: "The MCP detection cache: whether it is enabled, its time to live in seconds, and whether it holds a result.",
examples: &[
(r#"(try { mcp_cache_status(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"mcp_cache_status().ttl_seconds"#, "30"),
],
},
Signature {
name: "mcp_tools",
category: None,
subject_required: false,
aliases: &["mcp_list_tools"],
subject: None,
params: &[opt("config", Ty::Record, "{category?, search?, safety_level?}")],
returns: "Array",
doc: "The MCP tool catalogue for this host, filtered by category, search text or safety level. An unknown key, category or safety level is refused.",
examples: &[
(r#"(try { mcp_tools("git") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"typeof(mcp_tools())"#, "Array"),
(r#"typeof(mcp_tools({search: "zz-no-such-tool"}))"#, "Array"),
],
},
Signature {
name: "mcp_call",
category: None,
subject_required: false,
aliases: &["mcp_call_tool"],
subject: None,
params: &[
req("name", Ty::Str, "a catalogue tool name"),
opt("args", Ty::Record, "the tool's arguments, by name"),
],
returns: "Record",
doc: "Run a catalogue tool with named arguments and return its content. An unknown tool is E_NOT_FOUND and a tool that fails is E_TOOL_FAILED. The run is gated as an exec.",
examples: &[
(r#"(try { mcp_call(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { mcp_call("no-such-tool-xyz") } catch e { e.error.code })"#, "E_NOT_FOUND"),
(r#"(try { mcp_call("ls", 5) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "mcp_connect",
category: None,
subject_required: false,
aliases: &["mcp_client"],
subject: None,
params: &[req("endpoint", Ty::Str, "an endpoint URL, such as http://localhost:3001")],
returns: "Record",
doc: "The detected MCP server at an endpoint, as a record. When nothing answers there the record says available false, with an error field. It opens no connection to any address the caller names.",
examples: &[
(r#"(try { mcp_connect(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"mcp_connect("http://127.0.0.1:9").available"#, "false"),
],
},
Signature {
name: "mcp_server_start",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("config", Ty::Record, "{name?, type?, endpoint?, config?}")],
returns: "Record",
doc: "Declare an MCP server from a config record. It starts nothing: the status says so, and the hint names `ish mcp serve`, the server that does run.",
examples: &[
(r#"(try { mcp_server_start("fs") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"mcp_server_start({name: "fs"}).status"#, "declared (not started)"),
],
},
// 1c: try_repair and rbac_logout, the last pure entries on the
// discarded-args worklist that can be run safely in a test.
Signature {
name: "try_repair",
category: None,
subject_required: false,
aliases: &[],
subject: Some(Ty::Str),
params: &[],
returns: "Record",
doc: "Run code in a savepoint: {ok: true, value} on success; on failure {ok: false, error, restored, retryable}, with its changes rolled back. If they cannot all be rolled back, restore_error says why and retryable is false.",
examples: &[
(r#"try_repair("1 + 1").value"#, r#"2"#),
(r#"try_repair("null - null").error.code"#, r#"E_BAD_ARG"#),
],
},
Signature {
name: "rbac_logout",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Bool",
doc: "End the login session, reporting whether there was one. The local login is cleared first; if the auth store cannot end the session, the call is E_IO and says so, rather than reporting a clean logout.",
examples: &[
(r#"rbac_logout()"#, r#"false"#),
],
},
// 1c: six of the last eleven on the discarded-args worklist.
Signature {
name: "journal",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "The recorded steps of this session and how many can be reversed. Each row's id is the value undo({id: N}) takes to undo that one step; seq is the same number.",
examples: &[
(r#"typeof(journal())"#, r#"Record"#),
],
},
// Fallback journal, undo and agent builtins. Each refusal below is made by
// the declaration before the body runs; the examples never reach a model
// or touch the journal, because a refusal stops the call first.
Signature {
name: "journal_clear",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record",
doc: "Forget every recorded step of this session, so none of them can be undone. Touches no files outside the journal; takes no arguments. A journal directory that cannot be removed is E_IO, since a later process would load it.",
examples: &[
(r#"(try { journal_clear("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "undo",
category: None,
subject_required: false,
aliases: &["rewind"],
subject: None,
params: &[opt("steps_or_options", Ty::Any, "a bare Int n undoes the last n steps (default 1, not the step with id n); or a Record {id: Int} or {force: Bool}"), opt("options", Ty::Record, "{id: Int} undoes the one journal step with that id (a journal row's id) and leaves the others in place; {force: Bool}: put a file back even though it changed after its step (default false)")],
returns: "Record",
doc: "undo(n) undoes the last n steps; to undo the step with id n, write undo({id: n}). Put back what the last steps overwrote, reporting each step (with its id, seq) and whether all of them were restored. Steps that cannot be reversed are listed, not hidden. A step whose restore fails stays in the journal and stops the undo, so it can be retried. A file changed after its step (by a hand edit, say) is not overwritten: the undo is E_BAD_STATE and names the file, unless force is set, which restores it and discards those changes. undo({id: N}) undoes the one step with journal id N and leaves the later steps in place. It is E_BAD_STATE, naming the later step, when a later step changed the same file, unless force is set; undo the later step first. Writes are recorded only in agent mode (--agent, or IRONSHELL_MODE=agent) or with IRONSHELL_JOURNAL=on; in a human session undo is refused with E_BAD_STATE, because nothing was recorded to put back.",
examples: &[
(r#"(try { undo("x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { undo(-1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { undo({id: 0}) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"typeof(undo(0))"#, "Record"),
(r#"typeof(undo(0, {force: true}))"#, "Record"),
],
},
Signature {
name: "agent",
category: Some("AI"),
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("goal", Ty::Any, "a goal String, or a config Record {goal, tools?, max_steps?, dry_run?}"),
opt_rest("rest", Ty::Any, "tool names as Strings, or one Array of them; then max_steps Int in 1..=1000 and dry_run Bool; or, after a goal, a JSON object String as the whole config"),
],
returns: "String",
doc: "Run a model-driven agent over the named builtin tools and return its final answer. A dry run plans without acting. A malformed argument, an unknown key or an unknown tool is refused before any model is called.",
examples: &[
(r#"(try { agent(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { agent() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { agent("x", "print", 3, true, "extra") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { agent("x", ["no_such_tool_xyz"]) } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "swarm",
category: Some("AI"),
subject_required: false,
aliases: &[],
subject: None,
params: &[
req("goal", Ty::Any, "a goal String, or a config Record {goal, tools?, max_steps?, dry_run?}"),
opt_rest("rest", Ty::Any, "tool names as Strings, or one Array of them; then max_steps Int in 1..=1000 and dry_run Bool; or, after a goal, a JSON object String as the whole config"),
],
returns: "String",
doc: "Run a swarm of model-driven agents over the named builtin tools and return the combined answer. A dry run plans without acting. A malformed argument, an unknown key or an unknown tool is refused before any model is called.",
examples: &[
(r#"(try { swarm(5) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { swarm() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { swarm("x", "print", 3, true, "extra") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { swarm("x", ["no_such_tool_xyz"]) } catch e { e.error.code })"#, "E_NOT_FOUND"),
],
},
Signature {
name: "hw_battery",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Record | Null",
doc: "Battery charge and status, or null when there is no battery. Record {capacity: Int (percent), status: String, name: String (Windows only: Win32_Battery Name, so a UPS shows its own name)}. Windows status: discharging, ac (on AC power and not charging), charging, full, low, critical, partially_charged, unknown. Linux (BAT0 sysfs, lowercased) reports the raw value: charging, discharging, full, not charging, unknown.",
examples: &[
(r#"hw_battery()"#, r#"{capacity: 87, status: discharging}"#),
],
},
Signature {
name: "hw_gpu",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array | Null",
doc: "GPUs as {name, vram, driver}, or null when none is found. vram is bytes. On Windows it is the driver's 64-bit memory size from the display class registry key when present, else Win32_VideoController AdapterRAM, a 32-bit field that cannot show more than 4 GiB. Linux reports name only.",
examples: &[
(r#"hw_gpu()"#, r#"[{driver: "32.0.15", name: "NVIDIA ...", vram: 8589934592}]"#),
],
},
Signature {
name: "hw_sensors",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array | Null",
doc: "Temperature sensors as records, or null when none is readable.",
examples: &[
(r#"hw_sensors()"#, r#"[{name: acpitz, temperature_c: 41.0}]"#),
],
},
Signature {
name: "clipboard_types",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[],
returns: "Array",
doc: "The formats on the clipboard: text, image, files, audio, in that order, each once; an empty clipboard answers []. Windows asks the clipboard itself. Linux asks xclip under X11 (xsel can only say whether there is text) and wl-paste under Wayland, and with neither display set it is refused as E_NO_UI. macOS asks the pasteboard with osascript `clipboard info` and maps the classes: text (utf8, ut16, TEXT; text/html alone is not text), image (PNGf, TIFF, JPEG, GIFf, BMPf), files (furl, alis), audio (mp3, M4A, WAVE, AIFF); other classes are ignored.",
examples: &[
(r#"(try { clipboard_types(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { 1 | clipboard_types() } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "platform_db_export",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[opt("path", Ty::Str, "write the store to this file")],
returns: "String",
doc: "The platform store as JSON text, or, given a path, write it there and return the path. An existing file is replaced atomically, as file_write replaces it, and a transaction rollback restores it.",
examples: &[
(r#"platform_db_export()"#, r#"{"default": {...}}"#),
(r#"platform_db_export(fs_tempfile("ae_pdb"))"#, r#"/tmp/ae_pdb_..."#),
],
},
// 1c: search_symbols, withdrawn in 1934b80 because its walk could run
// out of its 30 s budget. That is now a coded absent-here answer.
Signature {
name: "search_symbols",
category: None,
subject_required: false,
aliases: &[],
subject: None,
params: &[req("name", Ty::Str, "a function, struct or class name")],
returns: "Array",
doc: "Definitions (fn, struct, class, def) of a name beneath the working directory, as path:line:text.",
examples: &[
(r#"search_symbols("bi_echo")"#, r#"["./src/builtins.rs:4210: fn bi_echo(args: Vec<Value>, ...)"]"#),
],
},
// 1c: strings, in-process since this commit, so the same everywhere.
Signature {
name: "strings",
category: None,
subject_required: false,
aliases: &["strings_extract"],
subject: None,
params: &[req("path", Ty::Str, "a file"), opt("min", Ty::Int, "shortest run to report, 1 to 4096; default 4")],
returns: "Array",
doc: "Runs of printable ASCII (and tab) in a file, as GNU strings finds them.",
examples: &[
(r#"strings("tests/fixtures/sample.db") | take(1)"#, r#"["SQLite format 3"]"#),
(r#"(strings("tests/fixtures/sample.db", 8) | len) > 0"#, r#"true"#),
],
},
Signature {
name: "input_timeout", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("prompt", Ty::Str, "text printed to stderr before reading; may be empty"), req("timeout_ms", Ty::Int, "milliseconds from 1 through 3600000 to wait for one line")],
returns: "String | Null",
doc: "Print prompt to stderr and read one line from stdin, waiting at most timeout_ms. Answers the line with CR and LF stripped, or null when the time passes first. A line typed after a timeout is not discarded: it answers the next prompt or input read. Lines are capped at 64 KiB; a longer one is discarded to its newline and refused with E_BUDGET_EXCEEDED. Closed stdin is E_NO_UI. Refuses pipeline input, surplus or missing arguments, non-String prompts and timeouts outside the range with E_BAD_ARG, all before anything is printed or read.",
examples: &[(r#"(try { input_timeout("x", 0) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { input_timeout("x", 3600001) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "input_progress", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("current", Ty::Numeric, "finished amount; finite and from 0 through total"), req("total", Ty::Numeric, "whole amount; finite and greater than 0"), opt("label", Ty::Str, "text drawn before the bar")],
returns: "Record",
doc: "Draw one progress line on stderr: a carriage return, the optional label, a 30-cell bar of # and -, and the percentage. The line is rewritten in place on each call, and a newline follows when current equals total. Answers {current, total, percent} with percent floored to an Int. Nothing is kept between calls. Refuses pipeline input, wrong argument counts, and non-finite, non-numeric, non-positive-total or out-of-range values with E_BAD_ARG before anything is drawn. Output goes to stderr only; the answer is unaffected.",
examples: &[(r#"input_progress(1, 2).percent"#, "50"), (r#"input_progress(1, 4, "copy").percent"#, "25"), (r#"(try { input_progress(3, 2) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "input_read_line", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt("prompt", Ty::Str, "text printed to stderr before the read; default none")],
returns: "String",
doc: "Read one line from stdin and answer it as a String, without its line terminator. Lines are capped at 64 KiB; a longer one is discarded to its newline and refused with E_BUDGET_EXCEEDED. Closed stdin is E_NO_UI. Refuses pipeline input, surplus arguments and a non-String prompt with E_BAD_ARG, before anything is printed or read.",
examples: &[
(r#"(try { input_read_line(0) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { input_read_line("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "input_read_password", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt("prompt", Ty::Str, "text printed to stderr before the read; default \"Password: \"")],
returns: "String",
doc: "Read one line from stdin as a password, without echo when stdin is a terminal: stty on Unix, PowerShell Read-Host -AsSecureString on Windows. Piped stdin is read as any other line. Only the line terminator is removed, so every other character is kept. Closed stdin is E_NO_UI. Refuses pipeline input, surplus arguments and a non-String prompt with E_BAD_ARG before anything is printed or read.",
examples: &[
(r#"(try { input_read_password(0) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { input_read_password("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "input_confirm", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt("prompt", Ty::Str, "question printed to stderr; default \"Confirm? [y/N]: \"")],
returns: "Bool",
doc: "Ask a yes-or-no question on stderr and read one answer from stdin. y or yes (any case) answers true; n, no or an empty answer answers false. Any other answer is asked again, and after 3 such answers the call refuses with E_BAD_ARG. Closed stdin is E_NO_UI. Refuses pipeline input, surplus arguments and a non-String prompt with E_BAD_ARG before anything is printed or read.",
examples: &[
(r#"(try { input_confirm(0) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { input_confirm("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "input_select", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("prompt", Ty::Str, "question printed above the numbered options"), req("options", Ty::Array, "1 to 1000 choices: Strings of 1 to 1024 bytes, or Int, Float or Bool values")],
returns: "Any",
doc: "List the options numbered on stderr, then read the number of the one chosen and answer that option, as it was given. An answer that is not a number in 1..=N is asked again; after 3 such answers the call refuses with E_BAD_ARG. Closed stdin is E_NO_UI. Options that are not choices (Records, Arrays, Lambdas, Null, empty or over-long Strings, more than 1000 options) refuse with E_BAD_ARG before anything is printed. Refuses pipeline input and wrong argument shapes with E_BAD_ARG.",
examples: &[
(r#"(try { input_select("Pick", []) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { input_select(0, ["a"]) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "input_multiselect", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("prompt", Ty::Str, "question printed above the numbered options"), req("options", Ty::Array, "1 to 1000 choices: Strings of 1 to 1024 bytes, or Int, Float or Bool values")],
returns: "Array",
doc: "List the options numbered on stderr, then read the numbers of the ones chosen, separated by commas, and answer them as an Array in the order given. A repeated number is answered once. An empty answer answers [], the deliberate choice of nothing. Any other answer, including a number outside 1..=N, is asked again; after 3 such answers the call refuses with E_BAD_ARG. Closed stdin is E_NO_UI. Option validation is the same as input_select's. Refuses pipeline input and wrong argument shapes with E_BAD_ARG.",
examples: &[
(r#"(try { input_multiselect("Pick", []) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { input_multiselect(0, ["a"]) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "input_number", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt("prompt", Ty::Str, "question printed to stderr; default \"Enter number: \"")],
returns: "Int | Float",
doc: "Read one line from stdin as a number: an Int when it is a whole number that fits, otherwise a finite Float. NaN and infinities are not answers. Any other answer is asked again; after 3 such answers the call refuses with E_BAD_ARG. Closed stdin is E_NO_UI. Refuses pipeline input, surplus arguments and a non-String prompt with E_BAD_ARG before anything is printed or read.",
examples: &[
(r#"(try { input_number(0) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { input_number("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "input_date", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt("prompt", Ty::Str, "question printed to stderr; default \"Enter date (YYYY-MM-DD): \"")],
returns: "String",
doc: "Read one line from stdin as a date written YYYY-MM-DD that the calendar accepts (2028-02-29 is accepted, 2026-02-30 is not), and answer its text. Any other answer is asked again; after 3 such answers the call refuses with E_BAD_ARG. Closed stdin is E_NO_UI. Refuses pipeline input, surplus arguments and a non-String prompt with E_BAD_ARG before anything is printed or read.",
examples: &[
(r#"(try { input_date(0) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { input_date("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "input_editor", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt("initial", Ty::Str, "text the temporary file starts with, at most 1 MiB; default empty")],
returns: "String",
doc: "Open the editor named by the EDITOR variable (notepad on Windows, vi elsewhere) on a new temporary file that starts with initial, wait for it to exit, and answer the text saved. EDITOR names one program, run without a shell, so arguments in it are not split; a value that starts with - or holds a control character refuses with E_BAD_ARG. Needs stdin and stdout to be terminals: otherwise the call refuses with E_NO_UI and runs nothing. An editor that exits unsuccessfully is E_TOOL_FAILED and answers nothing; a missing editor is E_TOOL_MISSING. A saved text over 1 MiB is E_BUDGET_EXCEEDED. Refuses pipeline input, surplus arguments and a non-String initial with E_BAD_ARG before anything is written or run.",
examples: &[
(r#"(try { input_editor(0) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { input_editor("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "input_read_char", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt_range("timeout_ms", Ty::Int, 1, 3_600_000, "milliseconds to wait for a key; absent waits without limit")],
returns: "String | Null",
doc: "Read one keypress from the terminal and answer it as a String: the character for a printable key, or a name such as Enter, Esc, Tab, BackTab, Backspace, Delete, Insert, Home, End, PageUp, PageDown, Up, Down, Left, Right and F1 to F12. Raw mode is entered for the read and restored on every path. With timeout_ms, answers null when the time passes first. Keys with no name are skipped. Needs stdin and stderr to be terminals: otherwise the call refuses with E_NO_UI without reading anything, so piped stdin is left for the next read. Ctrl+C is refused with E_POLICY_DENY and never answered as a character. Refuses pipeline input, surplus arguments and timeouts outside 1 through 3600000 with E_BAD_ARG, before anything is read.",
examples: &[
(r#"(try { "x" | input_read_char() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { input_read_char(0) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "input_spinner", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("label", Ty::Str, "text drawn after the spinner frame; at most 1 KiB; control characters are drawn as ?"), Param { name: "duration_ms", ty: Ty::Int, required: true, range: Some((1, 600_000)), variadic: false, doc: "how long to spin, from 1 through 600000 milliseconds" }],
returns: "Record",
doc: "Animate a spinner on stderr (| / - \\ every 100 ms, drawn as a carriage return and the label) for duration_ms, then clear its line and answer {label, duration_ms} once the duration has passed. Only a terminal stderr is drawn: otherwise nothing is written and the call still waits the full duration, so logs get no escape or carriage-return bytes. Refuses pipeline input, wrong argument counts, a non-String label, a label over 1 KiB, and durations outside 1 through 600000 with E_BAD_ARG before anything is drawn or waited.",
examples: &[
(r#"(try { input_spinner("working", 0) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { input_spinner("working", 600001) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "lazygit_open", category: None, subject_required: false, aliases: &["lazygit"], subject: None,
params: &[opt("path", Ty::Str, "the repository directory to open; default \".\"; must be an existing directory and not start with -")],
returns: "Record",
doc: "Run `lazygit -p <path>` with the terminal inherited and wait for it to exit, answering {path, exit_code: 0}. Needs stdin and stdout to be terminals: otherwise the call refuses with E_NO_UI and runs nothing. The path is checked first: an option-like path is refused with E_BAD_ARG, a missing path with E_NOT_FOUND and a non-directory with E_BAD_ARG. A missing lazygit is E_TOOL_MISSING; a nonzero exit is E_TOOL_FAILED. Refuses pipeline input and surplus arguments with E_BAD_ARG.",
examples: &[
(r#"(try { "x" | lazygit_open() } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { lazygit_open("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "input_form", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("fields", Ty::Array, "1 to 50 field Records: name (required; matches ^[A-Za-z_][A-Za-z0-9_]{0,63}$, unique), label?, default? and required? (Bool, default false); label and default are Strings of at most 1 KiB, and no other keys are allowed")],
returns: "Record",
doc: "Ask a form one line per field on the terminal and answer a Record mapping each field name to its answer, a String. Every field is validated before the first prompt, so a malformed form asks nothing. Each field prompts \"label: \", or \"label (default): \" when it has a default; label defaults to the name. An empty answer takes the default when there is one; an empty answer to a required field with no default prompts again, and after 3 empty answers the call refuses with E_BAD_ARG naming the field. An optional field with no default and an empty answer answers \"\". Reads stdin one line per prompt: with no UI attached (stdin closed) the call refuses with E_NO_UI. Direct-only: piped input and wrong argument shapes refuse with E_BAD_ARG before anything is printed.",
examples: &[(r#"(try { input_form([]) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "input_table", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("rows", Ty::Array, "1 to 1000 Records; the columns are the union of their keys, sorted"), opt("prompt", Ty::Str, "the question asked; default \"Select a row (1-N): \"")],
returns: "Record",
doc: "Print the rows to stderr as a numbered table, then ask for a row number and answer that row, unchanged, as a Record. Each cell is the value's display text, cut to 40 characters with ...; at most 16 columns are shown, and the chosen row still carries every key. A reply that is not an integer in 1..=N asks again, and after 3 replies the call refuses with E_BAD_ARG. Reads one line per reply from stdin: with no UI attached (stdin closed) the call refuses with E_NO_UI. Direct-only: piped input, a non-Record row or wrong argument shapes refuse with E_BAD_ARG before anything is printed.",
examples: &[
(r#"(try { input_table([]) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { input_table([], "Pick: ") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "gui_list_windows", category: None, subject_required: false, aliases: &["windows"], subject: None,
params: &[],
returns: "Array",
doc: "List the visible top-level windows that have a title, as Records. On Windows each is {hwnd: Int, title: String, pid: Int}; on Linux (wmctrl -l) each is {hwnd: String, title: String}. Reads the window list only: no window is focused, moved or changed. A missing wmctrl is E_TOOL_MISSING and a failing query E_TOOL_FAILED. Pipeline input and any argument are refused with E_BAD_ARG.",
examples: &[(r#"(try { gui_list_windows(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { windows(1) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_focus_window", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("target", Ty::Any, "the window's exact title (String), or its handle (an Int above 0)")],
returns: "Bool",
doc: "Bring a window to the front. Returns true when the window was focused. A title that matches no window is E_NOT_FOUND; a tool that fails is E_TOOL_FAILED, never false. Titles match exactly on Windows and by wmctrl's rules on Linux. Pipeline input and surplus arguments are refused with E_BAD_ARG, as is a target that is neither a String nor a positive Int.",
examples: &[(r#"(try { gui_focus_window(1.5) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_focus_window(0) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_minimize_window", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("title", Ty::Str, "the window's exact title")],
returns: "Bool",
doc: "Minimise the window with this title. Returns true when it was minimised. A title that matches no window is E_NOT_FOUND; a failing tool is E_TOOL_FAILED, never false. Pipeline input and surplus arguments are refused with E_BAD_ARG.",
examples: &[(r#"(try { gui_minimize_window(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_minimize_window("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_maximize_window", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("title", Ty::Str, "the window's exact title")],
returns: "Bool",
doc: "Maximise the window with this title. Returns true when it was maximised. A title that matches no window is E_NOT_FOUND; a failing tool is E_TOOL_FAILED, never false. Pipeline input and surplus arguments are refused with E_BAD_ARG.",
examples: &[(r#"(try { gui_maximize_window(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_maximize_window("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_close_window", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("title", Ty::Str, "the window's exact title")],
returns: "Bool",
doc: "Ask the window with this title to close, as its close button does: the application may prompt to save, or refuse. Returns true when the request was sent. It does not kill the process. A title that matches no window is E_NOT_FOUND; a failing tool is E_TOOL_FAILED. Pipeline input and surplus arguments are refused with E_BAD_ARG.",
examples: &[(r#"(try { gui_close_window(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_close_window("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_move_window", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("title", Ty::Str, "the window's exact title"), req("x", Ty::Int, "the new left edge, in pixels"), req("y", Ty::Int, "the new top edge, in pixels")],
returns: "Bool",
doc: "Move the window with this title so its top-left corner is at x, y on the screen. Returns true when it was moved. Coordinates are Ints between -100000 and 100000. A title that matches no window is E_NOT_FOUND; a failing tool is E_TOOL_FAILED. Pipeline input and surplus arguments are refused with E_BAD_ARG.",
examples: &[(r#"(try { gui_move_window("a", "x", 1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_move_window("a", 1) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_resize_window", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("title", Ty::Str, "the window's exact title"), req("width", Ty::Int, "the new width in pixels, 1 to 100000"), req("height", Ty::Int, "the new height in pixels, 1 to 100000")],
returns: "Bool",
doc: "Resize the window with this title to width by height pixels. Returns true when it was resized. A size outside 1 to 100000 is E_BAD_ARG. A title that matches no window is E_NOT_FOUND; a failing tool is E_TOOL_FAILED. Pipeline input and surplus arguments are refused with E_BAD_ARG.",
examples: &[(r#"(try { gui_resize_window("a", 0, 10) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_resize_window("a", 1) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_screenshot", category: None, subject_required: false, aliases: &["screenshot"], subject: None,
params: &[opt("path", Ty::Str, "the PNG file to write; default screenshot_<unix seconds>.png in the working directory")],
returns: "String",
doc: "Capture the whole primary screen to a PNG file and return its path. The path is checked as a write before anything is captured, and must not begin with a dash. Captures the screen's contents, which may include anything shown on it. A failing capture tool is E_TOOL_FAILED and nothing is returned in its place. Pipeline input and surplus arguments are refused with E_BAD_ARG.",
examples: &[(r#"(try { screenshot(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_screenshot("a.png", "b.png") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_screenshot_window", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("title", Ty::Str, "the window's exact title"), opt("path", Ty::Str, "where the PNG is written; default window_<seconds>.png")],
returns: "String",
doc: "Capture the window whose title is exactly `title` as a PNG and answer the path it was written to. The path is checked like any other write. Platforms: Linux X11, Windows, and macOS. Linux: xwininfo finds the window and ImageMagick's import captures it; this shell writes the file; no DISPLAY is E_NO_UI, and Wayland is E_UNIMPLEMENTED. Windows: the exact title is matched through user32 and drawn with PrintWindow; a minimized window is E_TOOL_FAILED. macOS: the title is resolved to a window id through CoreGraphics (osascript) and captured with screencapture -l; without Screen Recording permission it is E_OS_DENIED, never a blank PNG. No window with that title is E_NOT_FOUND on every platform; a missing tool is E_TOOL_MISSING. Elsewhere it is E_UNIMPLEMENTED. Use gui_screenshot for the whole screen.",
examples: &[(r#"(try { gui_screenshot_window(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_screenshot_window("a", 2) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_screenshot_window("a", "b.png", "c") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_mouse_move", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("x", Ty::Int, "the screen x in pixels"), req("y", Ty::Int, "the screen y in pixels")],
returns: "Bool",
doc: "Move the mouse pointer to x, y on the screen. Returns true when it was moved; a failing tool is E_TOOL_FAILED. Coordinates are Ints between -100000 and 100000. Pipeline input and surplus arguments are refused with E_BAD_ARG. On macOS the input is posted as CoreGraphics events through osascript and needs Accessibility: without it the call is E_OS_DENIED and nothing is sent.",
examples: &[(r#"(try { gui_mouse_move("a", 1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_mouse_move(1, 2, 3) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_mouse_click", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt("button", Ty::Any, "\"left\" (default), \"right\" or \"middle\", or 1, 2 or 3 for left, middle, right")],
returns: "Bool",
doc: "Click a mouse button where the pointer is. Returns true when the click was sent; a failing tool is E_TOOL_FAILED. An unknown button is E_BAD_ARG. Pipeline input and surplus arguments are refused with E_BAD_ARG. On macOS the input is posted as CoreGraphics events through osascript and needs Accessibility: without it the call is E_OS_DENIED and nothing is sent.",
examples: &[(r#"(try { gui_mouse_click("up") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_mouse_click("left", 1) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_mouse_double_click", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt("button", Ty::Any, "\"left\" (default), \"right\" or \"middle\", or 1, 2 or 3 for left, middle, right")],
returns: "Bool",
doc: "Double-click a mouse button where the pointer is: two clicks 50 ms apart. Returns true when both were sent; a failing tool is E_TOOL_FAILED. An unknown button is E_BAD_ARG. Pipeline input and surplus arguments are refused with E_BAD_ARG.",
examples: &[(r#"(try { gui_mouse_double_click("up") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_mouse_double_click("left", 1) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_mouse_drag", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("x1", Ty::Int, "where the press starts, x"), req("y1", Ty::Int, "where the press starts, y"), req("x2", Ty::Int, "where the release happens, x"), req("y2", Ty::Int, "where the release happens, y")],
returns: "Bool",
doc: "Press the left button at x1, y1, move to x2, y2, and release. Returns true when the drag was sent; a failing tool is E_TOOL_FAILED. Coordinates are Ints between -100000 and 100000. Pipeline input and surplus arguments are refused with E_BAD_ARG. On macOS the input is posted as CoreGraphics events through osascript and needs Accessibility: without it the call is E_OS_DENIED and nothing is sent.",
examples: &[(r#"(try { gui_mouse_drag(1, 2, 3) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_mouse_drag(1, 2, 3, "4") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_mouse_scroll", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt_range("amount", Ty::Int, -100, 100, "notches of the wheel: positive scrolls up, negative down (default 3)")],
returns: "Bool",
doc: "Turn the mouse wheel by the given number of notches. Returns true when the scroll was sent; a failing tool is E_TOOL_FAILED. Pipeline input and surplus arguments are refused with E_BAD_ARG. On macOS the input is posted as CoreGraphics events through osascript and needs Accessibility: without it the call is E_OS_DENIED and nothing is sent.",
examples: &[(r#"(try { gui_mouse_scroll(101) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_mouse_scroll("up") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_mouse_position", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "Record",
doc: "The pointer's position on the screen as Record {x: Int, y: Int}. A failing tool or an answer it does not give in that shape is E_TOOL_FAILED. Pipeline input and any argument are refused with E_BAD_ARG. On macOS the pointer is read with CoreGraphics, which needs no permission.",
examples: &[(r#"(try { gui_mouse_position(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { 1 | gui_mouse_position() } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_key_press", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("key", Ty::Str, "one key: a letter or digit, enter, tab, esc, space, backspace, delete, home, end, pageup, pagedown, up, down, left, right, or f1 to f12; modifiers before it with +, as in ctrl+shift+t")],
returns: "Bool",
doc: "Press one key, with any modifiers named before it. Returns true when the key was sent; a failing tool is E_TOOL_FAILED. Any other key name, an empty one, or a spec longer than 64 bytes is E_BAD_ARG, and nothing is sent. Pipeline input and surplus arguments are refused with E_BAD_ARG. On macOS the input is posted as CoreGraphics events through osascript and needs Accessibility: without it the call is E_OS_DENIED and nothing is sent.",
examples: &[(r#"(try { gui_key_press("") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_key_press("nope") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_key_combo", category: None, subject_required: false, aliases: &[], subject: None,
params: &[rest("key", Ty::Str, "the parts of one key combination, in order: modifiers (ctrl, alt, shift), then one key as gui_key_press names it")],
returns: "Bool",
doc: "Press a key combination such as gui_key_combo(\"ctrl\", \"shift\", \"t\"). The parts join into one key spec, which is checked as gui_key_press checks it: modifiers first, then exactly one key. Returns true when the combination was sent; a failing tool is E_TOOL_FAILED. Pipeline input, non-String parts and an invalid combination are refused with E_BAD_ARG, and nothing is sent. On macOS the input is posted as CoreGraphics events through osascript and needs Accessibility: without it the call is E_OS_DENIED and nothing is sent.",
examples: &[(r#"(try { gui_key_combo() } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_key_combo("ctrl", "nope") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_type_text", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("text", Ty::Str, "the text to type, up to 10000 bytes; newline and tab are typed as Enter and Tab")],
returns: "Bool",
doc: "Type text into whichever window has keyboard focus. Returns true when it was sent; a failing tool is E_TOOL_FAILED. Empty text, text over 10000 bytes, and control characters other than newline and tab are E_BAD_ARG, and nothing is typed. Pipeline input and surplus arguments are refused with E_BAD_ARG. On macOS the input is posted as CoreGraphics events through osascript and needs Accessibility: without it the call is E_OS_DENIED and nothing is sent.",
examples: &[(r#"(try { gui_type_text("") } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_type_text(1) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_get_active_window", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "Record",
doc: "The window that has keyboard focus, as Record {hwnd: Int, title: String} on Windows and Record {title: String} on Linux. A failing tool is E_TOOL_FAILED. Pipeline input and any argument are refused with E_BAD_ARG. On macOS it is {app: String, pid: Int, title: String or Null}: the frontmost application from NSWorkspace, and its first window title from System Events when Accessibility is granted, otherwise null (not an error).",
examples: &[(r#"(try { gui_get_active_window(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { 1 | gui_get_active_window() } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_screen_size", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "Record",
doc: "The primary screen's size in pixels as Record {width: Int, height: Int}. A failing tool or an answer without a size is E_TOOL_FAILED. Pipeline input and any argument are refused with E_BAD_ARG. On macOS it is the main screen frame in points, not pixels.",
examples: &[(r#"(try { gui_screen_size(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { 1 | gui_screen_size() } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_ocr", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("image", Ty::Str, "the path of an image file to read, inside the workspace in agent mode")],
returns: "String",
doc: "Read the text in an image file with the tesseract program and return it. The image is read through the usual read guard. A missing tesseract is E_TOOL_MISSING and a failing one E_TOOL_FAILED. An empty path, or one beginning with a dash, is E_BAD_ARG. Pipeline input and surplus arguments are refused with E_BAD_ARG.",
examples: &[(r#"(try { gui_ocr(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_ocr("") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_notify", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt("title", Ty::Str, "the notification's title (default Notification)"), opt("message", Ty::Str, "the notification's body (default empty)")],
returns: "Bool",
doc: "Show a desktop notification. Returns true when it was shown; a failing tool is E_TOOL_FAILED. A title or message that is not a String is E_BAD_ARG, as is an empty title. Pipeline input and surplus arguments are refused with E_BAD_ARG.",
examples: &[(r#"(try { gui_notify(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_notify("t", 2) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_dialog_message", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("message", Ty::Str, "the text to show"), opt("title", Ty::Str, "the dialog's title (default Message)")],
returns: "Bool",
doc: "Show a message dialog and wait until the user closes it. Returns true when it was acknowledged and false when the user dismissed it with Escape or the close button. A failing tool is E_TOOL_FAILED. Refused with E_NO_UI in agent mode. Arguments are checked before that, and pipeline input and surplus arguments are refused with E_BAD_ARG.",
examples: &[(r#"(try { gui_dialog_message(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_dialog_message("m", 2) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_dialog_input", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt("prompt", Ty::Str, "the question shown (default Enter value:)"), opt("title", Ty::Str, "the dialog's title (default Input)")],
returns: "String | Null",
doc: "Ask the user for text in a dialog and return the answer. Null when the user cancels, and on Windows also when the answer is empty. A failing tool is E_TOOL_FAILED. Refused with E_NO_UI in agent mode. Arguments are checked before that, and pipeline input and surplus arguments are refused with E_BAD_ARG.",
examples: &[(r#"(try { gui_dialog_input(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_dialog_input("p", 2) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_dialog_file_open", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt("title", Ty::Str, "the dialog's title (default Open File)")],
returns: "String | Null",
doc: "Show an open-file dialog and return the chosen path, or Null when the user cancels. A failing tool is E_TOOL_FAILED. Refused with E_NO_UI in agent mode. Arguments are checked before that, and pipeline input and surplus arguments are refused with E_BAD_ARG.",
examples: &[(r#"(try { gui_dialog_file_open(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_dialog_file_open("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_dialog_file_save", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt("title", Ty::Str, "the dialog's title (default Save File)")],
returns: "String | Null",
doc: "Show a save-file dialog and return the chosen path, or Null when the user cancels. Choosing a path does not write to it. A failing tool is E_TOOL_FAILED. Refused with E_NO_UI in agent mode. Arguments are checked before that, and pipeline input and surplus arguments are refused with E_BAD_ARG.",
examples: &[(r#"(try { gui_dialog_file_save(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_dialog_file_save("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_dialog_folder", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt("title", Ty::Str, "the dialog's title (default Select Folder)")],
returns: "String | Null",
doc: "Show a folder picker and return the chosen folder, or Null when the user cancels. A failing tool is E_TOOL_FAILED. Refused with E_NO_UI in agent mode. Arguments are checked before that, and pipeline input and surplus arguments are refused with E_BAD_ARG.",
examples: &[(r#"(try { gui_dialog_folder(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_dialog_folder("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_wait", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt("milliseconds", Ty::Numeric, "how long to wait, from 0 to 3600000 (default 1000)")],
returns: "Bool",
doc: "Pause for the given number of milliseconds, then answer true. Outside 0 to 3600000 is E_BAD_ARG. Pipeline input and surplus arguments are refused with E_BAD_ARG.",
examples: &[(r#"(try { gui_wait(-1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { gui_wait("x") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "gui_color_picker", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "Record | Null",
doc: "Show a colour picker and return the chosen colour as Record {r: Int, g: Int, b: Int, hex: String}, or Null when the user cancels. A failing tool is E_TOOL_FAILED. Refused with E_NO_UI in agent mode. Pipeline input and any argument are refused with E_BAD_ARG.",
examples: &[(r#"(try { gui_color_picker(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { 1 | gui_color_picker() } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "clipboard_get", category: None, subject_required: false, aliases: &["clipboard"], subject: None,
params: &[],
returns: "String",
doc: "The clipboard's text. Empty when it holds no text. Text over 8 MiB is E_BUDGET_EXCEEDED rather than cut short. The clipboard can hold passwords and other secrets, and this returns them to the caller. In agent mode it is E_POLICY_DENY, with nothing read, unless IRONSHELL_SECRETS=allow or IRONSHELL_POLICY=permissive is set. A failing tool is E_TOOL_FAILED; a missing one on Linux is E_TOOL_MISSING. Pipeline input and any argument are refused with E_BAD_ARG.",
examples: &[(r#"(try { clipboard_get(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { clipboard(1) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "clipboard_set", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt("text", Ty::Str, "the text to copy; with no argument, the piped String is copied")],
returns: "Bool",
doc: "Replace the clipboard's text. Returns true when it was set; a failing tool is E_TOOL_FAILED. Text over 8 MiB is E_BUDGET_EXCEEDED. Empty text clears it. The text is given once, either as the argument or piped in: a call with neither, both, or a piped value that is not a String is E_BAD_ARG, and nothing is copied.",
examples: &[(r#"(try { clipboard_set(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { clipboard_set("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "clipboard_clear", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "Bool",
doc: "Empty the clipboard by setting its text to the empty String. Returns true when it was cleared; a failing tool is E_TOOL_FAILED. Pipeline input and any argument are refused with E_BAD_ARG.",
examples: &[(r#"(try { clipboard_clear(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { 1 | clipboard_clear() } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "clipboard_has_text", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "Bool",
doc: "True when the clipboard holds text that is not empty. Reads the clipboard's text to decide, so it has the same access as clipboard_get. Pipeline input and any argument are refused with E_BAD_ARG.",
examples: &[(r#"(try { clipboard_has_text(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { 1 | clipboard_has_text() } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "clipboard_get_image", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "Record",
doc: "Read the image on the clipboard as {mime, bytes, base64}. Windows reads the clipboard through PowerShell and answers PNG. macOS reads the PNG class through osascript and answers PNG. Linux uses X11 through xclip or Wayland through wl-paste, preferring PNG, then JPEG, GIF, BMP and WEBP. No image on the clipboard (including an empty clipboard) is E_NOT_FOUND, never Null. Over 32 MiB is E_BUDGET_EXCEEDED. No DISPLAY and no WAYLAND_DISPLAY is E_NO_UI; xclip or wl-paste absent is E_TOOL_MISSING (xsel cannot carry images). In agent mode it is E_POLICY_DENY, with nothing read, unless IRONSHELL_SECRETS=allow or IRONSHELL_POLICY=permissive is set. Pipeline input and any argument are refused with E_BAD_ARG first.",
examples: &[(r#"(try { clipboard_get_image(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { 1 | clipboard_get_image() } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "clipboard_set_image", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("path", Ty::Str, "the image file to copy")],
returns: "Bool",
doc: "Copy an image file to the clipboard and answer true. The path is read through the same read guard as cat; a missing file is E_NOT_FOUND, a file over 32 MiB E_BUDGET_EXCEEDED, and a file that is not PNG, JPEG, GIF, BMP or WEBP (by its first bytes) E_BAD_ARG, all before the clipboard is touched. Linux: X11 through xclip, Wayland through wl-copy; the tool's holder process keeps the image on the clipboard after the call returns. No display is E_NO_UI. Windows copies the image through PowerShell as a bitmap and as PNG, flushed so it outlives the call. macOS copies it through osascript as PNG, JPEG, GIF or BMP; WEBP has no macOS clipboard class, so it is E_UNIMPLEMENTED with nothing copied. Pipeline input and surplus arguments are E_BAD_ARG.",
examples: &[(r#"(try { clipboard_set_image(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { clipboard_set_image("a", "b") } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "clipboard_history", category: None, subject_required: false, aliases: &[], subject: None,
params: &[],
returns: "Array",
doc: "The text entries in the Windows clipboard history, newest first, up to ten. An empty Array when the history is empty or switched off. A failing query is E_TOOL_FAILED. Implemented on Windows only: elsewhere it is E_UNIMPLEMENTED. The history can hold secrets, and this returns them to the caller. In agent mode it is E_POLICY_DENY, with nothing read, unless IRONSHELL_SECRETS=allow or IRONSHELL_POLICY=permissive is set. Pipeline input and any argument are refused with E_BAD_ARG.",
examples: &[(r#"(try { clipboard_history(1) } catch e { e.error.code })"#, "E_BAD_ARG"), (r#"(try { 1 | clipboard_history() } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "input_autocomplete", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("prompt", Ty::Str, "the question asked"), req("choices", Ty::Array, "1 to 10000 unique, non-empty Strings of at most 1 KiB")],
returns: "String",
doc: "Ask a question on the terminal and answer one of the choices. An answer that equals a choice exactly wins; otherwise a case-insensitive prefix that matches exactly one choice wins. An ambiguous prefix lists up to 20 matches on stderr and asks again; no match says so and asks again. After 5 answers that win nothing the call refuses with E_BAD_ARG. Reads one line per answer from stdin: with no UI attached (stdin closed) the call refuses with E_NO_UI. Direct-only: piped input and wrong argument shapes refuse with E_BAD_ARG before anything is printed.",
examples: &[(r#"(try { input_autocomplete("Pick: ", []) } catch e { e.error.code })"#, "E_BAD_ARG")],
},
Signature {
name: "cd", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("path", Ty::Str, "the new working directory; relative paths resolve against the workspace")],
returns: "String",
doc: "Change the process working directory, which decides what every later relative path means. The path passes the workspace jail first, so in agent mode cd cannot leave the workspace. Returns the new working directory as an absolute path. A missing directory or a file is a coded file-system error. Pipeline input, an empty path and surplus arguments are refused with E_BAD_ARG.",
examples: &[
(r#"(try { cd("") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { cd(".", ".") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "rm", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("path", Ty::Str, "the file to delete; relative paths resolve against the workspace"), opt("force", Ty::Bool, "true: a file that is already absent is not an error (default false)")],
returns: "String",
doc: "Delete one file. The path passes the workspace jail and the Destructive gate first, and inside a transaction the file is snapshotted before it goes. Returns \"removed: <path>\", or with force, \"already absent: <path>\" when there was nothing to delete. force excuses only absence: a directory, a locked file or a permission refusal is a coded file-system error either way. A force that is not a Bool, pipeline input and surplus arguments are refused with E_BAD_ARG.",
examples: &[
(r#"(try { rm(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { rm("x", "yes") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "rmdir", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("path", Ty::Str, "the directory to delete; relative paths resolve against the workspace"), opt("recursive", Ty::Bool, "true: delete its contents too (default false: it must be empty)")],
returns: "String",
doc: "Delete one directory: an empty one, or with recursive, the whole tree. The path passes the workspace jail and the Destructive gate first, and inside a transaction the tree is snapshotted before it goes. A symbolic link inside the tree is removed, never followed. Returns \"removed directory: <path>\". A missing directory, a non-empty one without recursive, or a refusal is a coded file-system error. A recursive that is not a Bool, pipeline input and surplus arguments are refused with E_BAD_ARG.",
examples: &[
(r#"(try { rmdir(1) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { rmdir("x", "yes") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "sh", category: None, subject_required: false, aliases: &["shell"], subject: None,
params: &[req("command", Ty::Any, "a command String split into words as a POSIX shell would (quotes and backslashes honoured; nothing expanded), or an argv Array whose first element is the program and whose other elements are Strings or numbers")],
returns: "Record",
doc: "Run one program directly, never through a shell: no globbing, variables, pipes or redirection. Disabled unless IRONSHELL_ALLOW_SH is true, 1 or yes (E_POLICY_DENY otherwise), and gated as Exec. stdin is closed and the run is killed at a 900 s deadline. Returns {stdout, stderr, success, exit_code, stdout_truncated}; only the tail of each stream is kept. A nonzero exit is in the record, as a shell's $? is, not an error. A missing program is E_TOOL_MISSING. An empty command, unbalanced quotes, a wrong argument type, pipeline input and surplus arguments are refused with E_BAD_ARG before the opt-in is checked.",
examples: &[
(r#"(try { sh([]) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { sh("echo 'open") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "exit", category: None, subject_required: false, aliases: &[], subject: None,
params: &[opt("code", Ty::Int, "the exit status, 0..=255 (default 0)")],
returns: "Null",
doc: "End the shell process with an exit status. It does not return. A code outside 0..=255 (which the OS would truncate), a code that is not an Int, pipeline input and surplus arguments are refused with E_BAD_ARG, and the process keeps running.",
examples: &[
(r#"(try { exit(256) } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { exit("1") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "dd_copy", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("source", Ty::Str, "the input file or device, passed as if=<source>"), req("destination", Ty::Str, "the output file or device, passed as of=<destination>"), opt("options", Ty::Record, "optional {bs: positive Int or a size such as 4M, count: positive Int}")],
returns: "Record",
doc: "Copy with dd if=<source> of=<destination> [bs=] [count=], each operand one argument, so a path cannot add another operand. On Unix dd runs directly with a 900 s deadline and returns {success: true, output: dd's own report from stderr}; a nonzero exit is E_TOOL_FAILED. On Windows the same copy runs in-process with the same bs and count and the same 900 s limit, and output is the three report lines dd prints. An empty path, an option other than bs and count, a bad value for either, pipeline input and surplus arguments are refused with E_BAD_ARG; on Windows a copy onto its own source is E_BAD_ARG.",
examples: &[
(r#"(try { dd_copy("", "b") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { dd_copy("a", "b", {skip: 1}) } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "pkill", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("prefix", Ty::Str, "a literal process-name prefix; no wildcard (* ? [ ]) or control character")],
returns: "Record",
doc: "Kill every process whose name begins with prefix (case-insensitively on Windows), forcibly: SIGKILL, or TerminateProcess on Windows. This shell and pids 0 and 1 are never killed. Gated as Process. Returns {pattern, killed: [pid]}; no match is an empty list, not an error. A match that could not be killed is E_TOOL_FAILED, which names the pids killed before it. An empty prefix, a wildcard, pipeline input and surplus arguments are refused with E_BAD_ARG.",
examples: &[
(r#"(try { pkill("*") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { pkill("") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "pgrep", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("prefix", Ty::Str, "a literal process-name prefix; no wildcard (* ? [ ]) or control character")],
returns: "Array",
doc: "List the processes whose name begins with prefix (case-insensitively on Windows), read from the process table with no external tool. Returns [{pid: Int, name: String, command: String}] sorted by pid; command is the argument vector joined with spaces and may be empty where the OS withholds it. No match is an empty list. An empty prefix, a wildcard, pipeline input and surplus arguments are refused with E_BAD_ARG.",
examples: &[
(r#"pgrep("ae-no-such-process-zq")"#, "[]"),
(r#"(try { pgrep("a?") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "chgrp", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("group", Ty::Str, "a group name or numeric id, not beginning with '-'"), req("path", Ty::Str, "an existing file, passed after --")],
returns: "Record",
doc: "Change the group of one file with chgrp -- <group> <path>, with a 120 s deadline. Returns {group, path}. A missing file is E_NOT_FOUND; a refusal by chgrp (unknown group, not permitted) is E_TOOL_FAILED. An empty or option-like group, an empty path, pipeline input and surplus arguments are refused with E_BAD_ARG. On Windows the group is an account name set as the file's primary group through the native security API: a numeric id is E_BAD_ARG, an unknown account E_NOT_FOUND, a refusal E_OS_DENIED, and a call inside a transaction E_UNIMPLEMENTED.",
examples: &[
(r#"(try { chgrp("staff", "") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { chgrp("-R", "f") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "svc_start", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "a service name of letters, digits and -_.@: not beginning with -")],
returns: "Record",
doc: "Start one service: systemctl start on Linux, launchctl start on macOS, Start-Service on Windows. Gated as Process. Returns {name, action: \"start\"}. A refusal by the service manager (no such service, not permitted) is E_TOOL_FAILED; another OS is E_UNIMPLEMENTED. A malformed name, pipeline input and surplus arguments are refused with E_BAD_ARG. 120 s deadline.",
examples: &[
(r#"(try { svc_start("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { svc_start("a b") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "svc_stop", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "a service name of letters, digits and -_.@: not beginning with -")],
returns: "Record",
doc: "Stop one service: systemctl stop on Linux, launchctl stop on macOS, Stop-Service on Windows. Gated as Process. Returns {name, action: \"stop\"}. A refusal by the service manager (no such service, not permitted) is E_TOOL_FAILED; another OS is E_UNIMPLEMENTED. A malformed name, pipeline input and surplus arguments are refused with E_BAD_ARG. 120 s deadline.",
examples: &[
(r#"(try { svc_stop("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { svc_stop("a;b") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "svc_restart", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "a service name of letters, digits and -_.@: not beginning with -")],
returns: "Record",
doc: "Restart one service: systemctl restart on Linux, launchctl kickstart -k system/<name> on macOS, Restart-Service on Windows. Gated as Process. Returns {name, action: \"restart\"}. A refusal by the service manager (no such service, not permitted) is E_TOOL_FAILED; another OS is E_UNIMPLEMENTED. A malformed name, pipeline input and surplus arguments are refused with E_BAD_ARG. 120 s deadline.",
examples: &[
(r#"(try { svc_restart("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { svc_restart("") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "svc_enable", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "a service name of letters, digits and -_.@: not beginning with -")],
returns: "Record",
doc: "Make one service start at boot: systemctl enable on Linux, launchctl enable system/<name> on macOS, Set-Service -StartupType Automatic on Windows. Gated as Process. Returns {name, action: \"enable\"}. A refusal by the service manager (no such service, not permitted) is E_TOOL_FAILED; another OS is E_UNIMPLEMENTED. A malformed name, pipeline input and surplus arguments are refused with E_BAD_ARG. 120 s deadline.",
examples: &[
(r#"(try { svc_enable("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { svc_enable("a/b") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
Signature {
name: "svc_disable", category: None, subject_required: false, aliases: &[], subject: None,
params: &[req("name", Ty::Str, "a service name of letters, digits and -_.@: not beginning with -")],
returns: "Record",
doc: "Stop one service from starting at boot: systemctl disable on Linux, launchctl disable system/<name> on macOS, Set-Service -StartupType Disabled on Windows. It does not stop a running service. Gated as Process. Returns {name, action: \"disable\"}. A refusal by the service manager (no such service, not permitted) is E_TOOL_FAILED; another OS is E_UNIMPLEMENTED. A malformed name, pipeline input and surplus arguments are refused with E_BAD_ARG. 120 s deadline.",
examples: &[
(r#"(try { svc_disable("-x") } catch e { e.error.code })"#, "E_BAD_ARG"),
(r#"(try { svc_disable("a b") } catch e { e.error.code })"#, "E_BAD_ARG"),
],
},
];
/// The declaration for `name`, if it has one.
pub fn signature_of(name: &str) -> Option<&'static Signature> {
// Asked on every builtin call. It was two linear scans -- names, then every
// alias list -- which for an undeclared builtin, most of them, meant ~800
// string comparisons to find nothing. Names win over aliases, first
// declaration first, as the scans did.
static INDEX: std::sync::LazyLock<rustc_hash::FxHashMap<&'static str, &'static Signature>> =
std::sync::LazyLock::new(|| {
let mut m = rustc_hash::FxHashMap::default();
for s in SIGNATURES {
m.entry(s.name).or_insert(s);
}
for s in SIGNATURES {
for a in s.aliases {
m.entry(*a).or_insert(s);
}
}
// Dispatcher aliases execute the same body. Let a reviewed
// declaration cover every spelling of that implementation, rather
// than leaving aliases able to bypass argument validation. Keep
// explicitly declared names and aliases authoritative.
for names in crate::builtins::alias_groups() {
if let Some(signature) = names.iter().find_map(|name| m.get(name).copied()) {
for name in names {
m.entry(name).or_insert(signature);
}
}
}
m
});
INDEX.get(name).copied()
}
/// Check a call against its declaration, if it has one.
///
/// Returns `Ok(())` for every undeclared builtin, so migration is incremental
/// and nothing that works today changes behaviour.
///
/// The subject is checked only when the call came through a pipeline: a
/// builtin with a declared subject may also be called with the subject as its
/// first argument, and both forms are in use.
/// Declared builtins whose bodies never read pipeline input. Each takes no
/// subject, and its dispatch row or function drops `input` unread, so
/// `"x" | platform_arch()` answered as if nothing had been piped: a call the
/// builtin could not honour, answered with a value. [`validate`] refuses piped
/// input to these before the body runs. `tests/pipe_input_refused.rs` derives
/// the set from the source and fails when this list falls out of step with it.
///
/// A builtin that reads its input without declaring a subject (`echo`,
/// `file_write`, `jq`) is not here: its direct-call form does not put the
/// subject first, so declaring one would shift its arguments.
pub const TAKES_NO_INPUT: &[&str] = &[
"None",
"Some",
"a2a_agents",
"a2a_discover",
"a2a_receive",
"a2a_status",
"a2a_unregister",
"a2ui_clear",
"ab_encode",
"activation",
"apply",
"approve",
"archive_info",
"audit_export",
"audit_log",
"audit_query",
"audit_stats",
"audit_tail",
"audit_verify",
"buildah_images",
"bzip2_compress",
"capabilities",
"cd",
"check_permission",
"clear",
"clipboard_types",
"cloud_config",
"cluster_nodes",
"cluster_status",
"code_comments",
"code_dependencies",
"code_exports",
"code_format",
"code_imports",
"code_language",
"code_parse",
"code_symbols",
"code_todos",
"config",
"config_get",
"config_path",
"config_reload",
"consensus_net",
"crossover_strategy",
"crypto_cert_verify",
"crypto_checksum",
"crypto_decrypt",
"crypto_encrypt",
"crypto_hash_file",
"crypto_hmac",
"crypto_jwt_decode",
"crypto_random_bytes",
"crypto_uuid",
"db_csv_query",
"db_csv_to_sqlite",
"db_json_query",
"db_json_to_sqlite",
"db_kv_delete",
"db_kv_get",
"db_kv_keys",
"db_kv_set",
"db_kv_store",
"db_sqlite_backup",
"db_sqlite_count",
"db_sqlite_create_table",
"db_sqlite_delete",
"db_sqlite_drop_table",
"db_sqlite_dump",
"db_sqlite_exec",
"db_sqlite_import",
"db_sqlite_insert",
"db_sqlite_open",
"db_sqlite_schema",
"db_sqlite_tables",
"db_sqlite_to_csv",
"db_sqlite_to_json",
"db_sqlite_update",
"db_sqlite_vacuum",
"df",
"diag_config",
"diag_explain",
"docker_images",
"docker_networks",
"docker_ps",
"docker_stats",
"docker_volumes",
"docs_changelog",
"docs_examples",
"docs_readme",
"docs_search",
"env",
"env_activate",
"env_container",
"env_detect",
"env_docker",
"env_dotnet",
"env_go",
"env_java",
"env_node",
"env_path",
"env_python",
"env_ruby",
"env_rust",
"env_shell",
"env_unset",
"env_var",
"env_venv",
"evolution_config",
"features",
"file_move",
"file_replace",
"file_type",
"find",
"finetune_list",
"finetune_start",
"fs_du",
"fs_glob",
"fs_lstat",
"fs_mounts",
"fs_readlink",
"fs_realpath",
"fs_stat",
"fs_tempdir",
"fs_tempfile",
"fs_tree",
"fs_walk",
"git_branch",
"git_branches",
"git_remote",
"git_root",
"git_stash_list",
"git_tags",
"governor_reset",
"governor_status",
"group_list",
"group_members",
"gzip_compress",
"gzip_decompress",
"help",
"hostname",
"hw_audio",
"hw_battery",
"hw_disk",
"hw_gpu",
"hw_memory",
"hw_network",
"hw_pci",
"hw_sensors",
"hw_usb",
"input_timeout",
"is_bsd",
"is_linux",
"is_macos",
"is_unix",
"is_windows",
"job_list",
"kg_entities",
"kg_relations",
"list_roles",
"ls",
"lsblk",
"lscpu",
"marketplace_info",
"marketplace_install",
"marketplace_list",
"marketplace_publish",
"marketplace_rate",
"marketplace_search",
"marketplace_uninstall",
"marketplace_update",
"mcp_prompts",
"mcp_resources",
"mcp_server",
"monitor_uptime",
"mount_info",
"netstat",
"nn_create",
"nn_crossover",
"now",
"objdump_disasm",
"objdump_headers",
"ontology_describe",
"ontology_manifest",
"perm_get",
"pipx_list",
"pkg_deps",
"pkg_files",
"pkg_info",
"pkg_owner",
"pkg_rdeps",
"pkg_search",
"pkg_sources",
"pkg_verify",
"plan",
"platform",
"platform_arch",
"platform_build",
"platform_build_systems",
"platform_capabilities",
"platform_cloud_clis",
"platform_compilers",
"platform_containers",
"platform_cpu",
"platform_cpu_count",
"platform_cpu_freq",
"platform_cuda_version",
"platform_databases",
"platform_db_export",
"platform_db_list",
"platform_db_load",
"platform_detect_tools",
"platform_disk_usage",
"platform_disks",
"platform_gpu_memory",
"platform_gpus",
"platform_has_admin",
"platform_has_container",
"platform_has_gui",
"platform_has_network",
"platform_has_sudo",
"platform_has_tool",
"platform_hash",
"platform_iac_tools",
"platform_kernel",
"platform_lib_version",
"platform_libc",
"platform_libs",
"platform_line_ending",
"platform_linters",
"platform_machine_id",
"platform_memory_free",
"platform_memory_total",
"platform_network_interfaces",
"platform_normalize_output",
"platform_normalize_path",
"platform_os_version",
"platform_path_sep",
"platform_pkg_lang",
"platform_pkg_managers",
"platform_runtimes",
"platform_sdk_version",
"platform_shell_type",
"platform_ssl_version",
"platform_system_libs",
"platform_tool_version",
"platform_tool_versions",
"platform_vcs",
"plugin_categories",
"plugins",
"population",
"proc_exists",
"proc_info",
"project_config_files",
"project_dependencies",
"project_dev_dependencies",
"project_entry_points",
"project_gitignore",
"project_languages",
"project_license",
"project_loc",
"project_name",
"project_readme",
"project_root",
"project_size",
"project_structure",
"project_test_files",
"project_type",
"project_version",
"pwd",
"rag_clear",
"range",
"rbac_can",
"rbac_grant",
"rbac_login",
"rbac_logout",
"rbac_principal",
"rbac_register",
"rbac_session",
"read_text",
"readelf_headers",
"readelf_sections",
"refactor_organize_imports",
"repl_sessions",
"rl_ac_agent",
"rl_agent",
"rl_dqn_agent",
"rl_gridworld",
"rl_pg_agent",
"rl_replay_buffer",
"rl_sarsa_agent",
"rlm_agent",
"rlm_config",
"rlm_spawn",
"rmdir",
"role_grant",
"role_revoke",
"rustup_show",
"safety_status",
"screen_list",
"search_by_type",
"search_files",
"search_fixmes",
"search_modified",
"search_recent",
"search_symbols",
"search_todos",
"selection_strategy",
"semantic_cache_clear",
"sess_close",
"session_id",
"session_start",
"shellcheck_check",
"sleep",
"ssh_config",
"sso_info",
"sso_init",
"startup_list",
"strings",
"svc_info",
"svc_list",
"svc_logs",
"svc_status",
"syntax_categories",
"sys_arch",
"sys_boot_time",
"sys_cpu_count",
"sys_cpu_freq",
"sys_cpu_info",
"sys_disk_info",
"sys_env_all",
"sys_groups",
"sys_info",
"sys_kernel",
"sys_load_avg",
"sys_locale",
"sys_mem_info",
"sys_os",
"sys_swap_info",
"sys_timezone",
"sys_user_info",
"sys_users",
"tar_extract",
"tar_list",
"telemetry_disable",
"telemetry_enable",
"telemetry_events",
"telemetry_report",
"telemetry_reset",
"telemetry_status",
"themes",
"tmux_list",
"tool_exec",
"tool_info",
"tool_schema",
"tool_search",
"tools",
"tx_status",
"uptime",
"user_list",
"web_build_query",
"web_decode_url",
"web_encode_url",
"web_extract_emails",
"web_extract_phones",
"web_html_to_markdown",
"web_html_to_text",
"web_json_path",
"web_parse_query",
"web_parse_url",
"workspace_list",
"yamllint_check",
"zip_extract",
"zip_list",
];
/// The refusal for a subject of the wrong type. A String where an Array is
/// declared gets a hint toward the text builtins, since that is the usual slip.
fn subject_refusal(
name: &str,
want: Ty,
got: &Value,
sig: &Signature,
position: &str,
) -> anyhow::Error {
let expected = format!("{} as the {position}: {}", want.as_str(), sig.render());
if want == Ty::Array && matches!(got, Value::Str(_)) {
return crate::safety::bad_arg_in(
name,
format!("{name}: expected {expected}, got {}", got.type_name()),
"a String is text, not an Array: pipe it through lines for lines, or through split(\"\") for characters, then pipe the Array on",
);
}
crate::safety::bad_arg(name, &expected, got.type_name())
}
pub fn validate(name: &str, args: &[Value], input: Option<&Value>) -> anyhow::Result<()> {
let Some(sig) = signature_of(name) else {
return Ok(());
};
// Piped input to a builtin whose body would drop it unread.
if input.is_some() && TAKES_NO_INPUT.binary_search(&sig.name).is_ok() {
return Err(crate::safety::bad_arg(
name,
&format!("no pipeline input: {}", sig.render()),
"a piped value",
));
}
// A pipeline-only builtin says so before the body has to.
if sig.subject_required && input.is_none() {
return Err(crate::safety::bad_arg(
name,
&format!("a piped subject: {}", sig.render()),
"a direct call",
));
}
// A declared subject must match when one was piped in.
if let (Some(want), Some(got)) = (sig.subject, input) {
if !want.accepts(got) {
return Err(subject_refusal(name, want, got, sig, "piped subject"));
}
}
// In a pipeline the subject is the input, so the arguments are the
// parameters. Called directly, a subject-taking builtin may receive the
// subject as its first argument instead, and the parameters shift by one.
// `sql("select 1")` and `sql_value("select 1")` have no source: the one
// String is the query, not a subject.
// A lone query, with or without a trailing params Array, runs over the
// empty database: `sql("select 1")` and `sql("select ? + 1", [41])`.
let lone_query = matches!(sig.name, "sql" | "sql_value")
&& input.is_none()
&& matches!(args, [Value::Str(_)] | [Value::Str(_), Value::Array(_)]);
let params_start =
usize::from(input.is_none() && sig.subject.is_some() && !args.is_empty() && !lone_query);
let supplied = args.len().saturating_sub(params_start);
// When the subject arrives as the first argument rather than through the
// pipe, it still has a declared type and still has to match. Checking it
// only in pipeline position left `unique({unexpected: true})` to fail in
// the body with an uncoded `E_UNKNOWN`, which
// `tests/uncoded_failure_census.rs` found by sweeping rather than by
// someone happening to try it.
//
// Restricted to builtins that declare no parameters, where the first
// argument can only be the subject. With parameters present it is
// genuinely ambiguous: `max(2, 9)` takes two numbers and `[1, 5] | max`
// takes an array, so `2` is a parameter there, not a malformed subject.
// Checking it unconditionally refused `max(2, 9)` -- caught immediately by
// the declaration tests, which is the argument for having written them.
// Resolving that ambiguity properly is overload resolution, and this is
// not the place for it.
if params_start == 1 && sig.params.is_empty() {
if let (Some(want), Some(got)) = (sig.subject, args.first()) {
if !want.accepts(got) {
return Err(subject_refusal(name, want, got, sig, "subject"));
}
}
}
// `sql("people.csv", ["Ann"])` with no rows piped in: a String with no
// whitespace is not a query but a source, and the query is missing. A lone
// query with params runs over the empty database; this one would only be
// a SQLite syntax error, so say what sql needs.
if input.is_none()
&& matches!(sig.name, "sql" | "sql_value")
&& matches!(args, [Value::Str(s), Value::Array(_)] if !s.trim().contains(char::is_whitespace))
{
return Err(crate::safety::bad_arg_in(
name,
format!(
"{name}: with no piped rows, {name} needs a query after its source: {name}(source, query, params) or rows | {name}(query, params)"
),
&format!("name the query, e.g. {name}(\"people.csv\", \"select * from t where name = ?\", [\"Ann\"])"),
));
}
// `sql(rows, "select ... ?", 5)`: the query is the String before the last
// argument, so the last argument is the params and must be an Array. Named
// as the mistake, rather than as a bad `query`.
if matches!(sig.name, "sql" | "sql_value") {
if let [.., Value::Str(_), last] = &args[params_start..] {
if !matches!(last, Value::Array(_)) {
let example = if matches!(last, Value::Str(_)) {
"[\"Ann\"]"
} else {
"[5]"
};
return Err(crate::safety::bad_arg_in(
name,
format!(
"{name}: params must be an Array, e.g. {example}, got {}",
last.type_name()
),
&format!("pass the bind values as an Array: {name}(..., query, [value, ...])"),
));
}
}
}
let required = sig.params.iter().filter(|p| p.required).count();
if supplied < required {
// `in` is a pipe stage far more often than a call with two arguments,
// so the missing collection is the one thing worth saying in words.
if name == "in" {
return Err(crate::safety::bad_arg_with_hint(
name,
&sig.render(),
&format!("{supplied} of {required} required"),
"to test membership, pipe the value to in: `\"bug\" | in([\"bug\", \"x\"])`",
));
}
// `sql("select 1")` reads as complete; what it lacks is rows.
if name == "sql" {
return Err(crate::safety::bad_arg_with_hint(
name,
&sig.render(),
&format!("{supplied} of {required} required"),
"sql runs over piped rows ([{a: 1}] | sql(\"select * from t\")) or a file (sql_value(\"data.csv\", \"select ...\"))",
));
}
// The first argument was taken as the subject, so the count of
// parameters given reads as "0 of 1" for `pow(2)`. Name the parameter
// that is missing, and say where the subject came from.
if params_start == 1 {
if let Some(missing) = sig.params.iter().skip(supplied).find(|p| p.required) {
return Err(crate::safety::bad_arg_in(
name,
format!("{name}: missing required argument '{}'", missing.name),
&format!(
"pass '{}' as the argument after the subject: {}",
missing.name,
sig.render()
),
));
}
}
// `expected` is the signature alone, with no "— missing x" tail. The
// tail read well and cost twice: `diagnose` carries the signature in
// its own field, generated from this same declaration, so a restated
// copy inside `expected` is the duplication `bi_diagnose` already
// refuses for `return_type` and `parameters`. The count says what the
// tail said, in four tokens.
return Err(crate::safety::bad_arg(
name,
&sig.render(),
&format!("{supplied} of {required} required"),
));
}
// A variadic parameter absorbs everything after it, so there is no upper
// bound to check.
let variadic = sig.params.iter().position(|p| p.variadic);
if variadic.is_none() && supplied > sig.params.len() {
// The bound counts what the caller wrote. A subject passed as the first
// argument is one of those arguments, so `sqrt(1, 2, 3)` may take one
// argument, not zero: the parameter list is empty and the subject is the
// one argument it takes.
return Err(crate::safety::bad_arg(
name,
&format!(
"at most {} argument(s): {}",
sig.params.len() + params_start,
sig.render()
),
&format!("{}", args.len()),
));
}
// Each supplied argument is checked against its own parameter, and every
// argument from the variadic one on against it. One optional parameter may
// follow the variadic (proc_spawn's options Record): the last argument is
// that parameter when its type accepts it, and a variadic one otherwise.
// Without a variadic, the last argument may likewise skip one optional
// parameter whose type it does not match for the optional one after it:
// `sql("select ?", [7])` gives the Array to `params`, past `query`.
let supplied_args = &args[params_start..];
let last = supplied_args.len().saturating_sub(1);
let rest = supplied_args.iter().enumerate().map(|(i, a)| {
let p = match variadic {
None => match (sig.params.get(i), sig.params.get(i + 1)) {
(Some(here), Some(next))
if i == last
&& !here.required
&& !next.required
&& !here.ty.accepts(a)
&& next.ty.accepts(a) =>
{
Some(next)
}
(here, _) => here,
},
Some(v) if i < v => sig.params.get(i),
Some(v) => match sig.params.get(v + 1) {
Some(tail) if i == last && tail.ty.accepts(a) => Some(tail),
_ => sig.params.get(v),
},
};
(p, a)
});
for (param, arg) in rest.filter_map(|(p, a)| p.map(|p| (p, a))) {
if !param.ty.accepts(arg) {
return Err(crate::safety::bad_arg(
name,
&format!("{}: {} ({})", param.name, param.ty.as_str(), param.doc),
arg.type_name(),
));
}
if let (Some((lo, hi)), Value::Int(n)) = (param.range, arg) {
if *n < lo || *n > hi {
return Err(crate::safety::bad_arg(
name,
&format!(
"{}: {} in {lo}..={hi} ({})",
param.name,
param.ty.as_str(),
param.doc
),
&format!("{n}"),
));
}
}
}
Ok(())
}