Using aitools from an agent¶
Use aitools as the CLI for file and text work. Its run command invokes
external programs. This page describes the loop an agent runs against it:
discover a command, call it, branch on the exit code, and follow the
next_commands and repairs the output hands back.
Discover commands with schema¶
Start with the command list, then ask for the detail of the commands you plan to use:
aitools schema # [{name, summary}] for every command
aitools schema edit read # arguments, output fields, error codes
aitools schema doc get # a group command, as typed
schema without arguments returns only command names and summaries. The detail
object lists each argument's type and default, each output
field, and the error codes the command declares. The
command reference and its context pages show the same data.
Use the same doc commands for JSON, YAML, and TOML files; the path extension selects the format,
and --format overrides it.
Branch on the exit code first¶
| Exit code | What to do |
|---|---|
| 0 | Use the result on standard output. |
| 3 | The result on standard output is incomplete (status:"partial"). Follow next_commands when present, or narrow the request. For run, check the child outcome before considering a retry; see Run an external program. |
| 2 | A precondition failed. Read the command's error details and follow its repair. Refresh any file selection, hash, count, or transaction state before retrying. |
| 1 | Read error.code; treat error.repairs as suggestions and review a command before running it. |
Standard output carries success; standard error carries the error envelope. Each is exactly one JSON object.
Paths¶
A relative path argument resolves against the current working directory,
as in a shell. --root selects the workspace (the write boundary, the state
directory, and the ignore rules) and does not change what a relative path
means. Write commands return paths relative to the workspace root. read,
info, check, and diff give a file inside the root relative to it and a
file outside the root as its absolute real path.
Built-in reads are not restricted to the workspace. Built-in writes outside it, through a
symlink that leaves it, or into the workspace's .git/ fail with
refusal.outside-workspace. archive extract entry paths and
copy --recursive children go through the same boundary, so an archive entry
or nested directory that resolves into .git/ is refused.
During planning, archive extract resolves each symlink target one component
at a time. It refuses a target that leaves the resolved extraction root or
passes through an archive symlink. For example, if the archive contains
D -> ., the target D/.. is refused because the planner checks D before
applying ...
The planner checks disk entries without following symlinks. For
archive extract --tx, it also checks entries already staged in that
transaction, including entries from earlier archive extract calls, against
the incoming archive. A target cannot cross an existing destination symlink,
including at its final component. An archive entry also cannot have a parent
that is an archive or destination symlink, even when that symlink resolves
inside the extraction root. Staged and archive symlink components use Unicode
NFD normalization and full case folding on every platform. Other archive-name
comparisons follow the spelling rules below.
Without --tx, archive extract writes after planning against the resolved
extraction root. With --tx, it stages the entries after the same planning
check. Before tx commit writes, the store checks every symlink in the final
staged view against the workspace root, including links that did not come from
an archive. The commit returns refusal.outside-workspace if a staged symlink
target resolves outside the workspace, including through an intermediate
symlink path component, and leaves the transaction open. Remove or replace
the offending staged link and retry tx commit, or run tx abort.
Archive member names containing .. are refused. Relative symlink targets may
contain .. when component-by-component resolution stays inside the resolved
extraction root. Entry selection with --entry, duplicate-name checks, and
hard-link target lookup preserve case and Unicode spelling after empty and .
path components are removed. Thus
README and readme are distinct entries on a case-sensitive filesystem. On
a case-insensitive filesystem, both may pass planning. Applying the extraction
returns refusal.exists if the destination aliases the paths; with --tx,
this occurs when tx commit applies the staged changes.
The --to path names the extraction root. A destination symlink is followed
when it resolves inside the workspace; a target outside the workspace is
refused. Archive member paths and link targets are checked within the resolved
extraction root.
Archive extraction caps entry paths at 4,095 UTF-8 bytes, path components at
255 UTF-8 bytes, path depth at 2,048 nonempty, non-. components, and link
targets at 4,095 UTF-8 bytes. The tar reader accepts at most 200,000 nonzero
header records; the all-zero end-of-archive records do not count. PAX and GNU
metadata headers count toward the limit. The ZIP reader accepts at most 65,534
central-directory entries. The readers also cap retained path metadata at
16 MiB per archive, summed across entry names and link targets. ZIP charges
raw name bytes and uncompressed symlink target sizes; tar charges emitted
UTF-8 name and link-target bytes. Archive input is capped at 64 MiB. The reader
checks the open file's size with fstat and refuses larger files before
reading. If a file grows during the read, it reads at most 64 MiB plus one
byte; that extra byte triggers refusal.too-large. Gzip streams may contain
at most 1,024 concatenated members, each with at most 256 MiB of decompressed
output. With no explicit output limit, gzip decoding allows at most 1 GiB of
total decompressed data. archive extract defaults --max-bytes to 1 GiB
when the option is omitted and supplies that cap to decoding and extraction
planning. The cap limits cumulative extracted file data.
Exceeding any archive limit returns refusal.too-large.
Extracted files get the entry's mode masked with 0755: never group- or
other-writable, and never setuid, setgid, or sticky. Aitools' state directory
lives outside the root, so writes there are refused too. The one
exception is the temporary area that aitools mktemp creates; writes below
the path it returns are allowed.
Read in bounded pieces¶
Every read has a limit, and a cut result says how to continue:
$ aitools read nums.txt --max-lines 3
{"schema_version":2,"status":"partial","command":"read","mode":"text","path":"nums.txt","start_line":1,"lines":["1","2","3"],"total_lines":100,"hash":"93d4e5c7...","truncated":true,"encoding_errors":0,"approx_tokens":2,"next_commands":["aitools read nums.txt --range 4:6"]}
approx_tokens estimates returned text size as ceil(characters / 4). It
counts characters in the returned string, not UTF-8 bytes, so a multi-byte
UTF-8 character counts once. The estimate is independent of any model's
tokenizer. Use it to decide whether to read more
or to narrow the range.
Write with guards¶
A write states what it expects the file to look like, and fails without writing when the file differs.
- Select by content where you can.
edit --oldfirst searches for an exact match. Only if none exists does it compare whole lines, ignoring leading and trailing whitespace on each line. The selected strategy must find exactly one place; zero or several matches fail with exit code 2 andcandidates. Check the returnedstrategy(exactorwhitespace); the whitespace strategy also adjusts the replacement's indentation. - When you select by position (
--range,--symbol), pass the file's current hash:aitools info <path>returns it ashash, and so doesaitools read. Without--expect-hash, the write fails withargument.invalidand a repair that runsaitools info <path>. - When a selection can match many lines (
--match,replace), pass--expect-count. Run the command with--dry-runfirst: a dry run needs no--expect-count, writes nothing, and reports the count asexpect_countnext to the diff. Then run it without--dry-runand with--expect-count <that count>. A write without--expect-countfails withargument.invalidand a repair that is that--dry-run. - Keep the
op_idfrom the output.aitools undo <op_id>reverts that operation, and refuses with exit code 2 if a later change touched the same paths.
$ aitools edit hello.lisp --old 'Hello' --new 'Hi'
{"schema_version":2,"status":"ok","command":"edit","changes":[{"path":"hello.lisp","action":"modified","hash_before":"de2187a5...","hash_after":"5f132d76...","diff":"@@ -1,2 +1,2 @@\n (defun greet (name)\n- (format t \"Hello, ~a\" name))\n+ (format t \"Hi, ~a\" name))\n"}],"op_id":"op-20260926T011541Z-4a125e73","strategy":"exact"}
Hashes above are shortened for the page; real output carries the full SHA-256 hex digest.
Never write text copied from output that contains [REDACTED_SECRET].
aitools masks known secret formats in JSON output, and a guarded write whose input
contains the mask text fails with refusal.redacted-input. To change nearby
nonsecret text, use edit --old and --new that exclude the secret, leaving
the existing secret untouched. If the requested change requires the secret
itself, stop and ask for an authorized way to supply it; rereading masked
output does not recover the value.
Remove a file or tree¶
Use rm for journaled removal of one explicit path. Without --recursive,
it removes only a file, symlink, or empty directory. A recursive removal
requires a preview and an expected entry count:
Inspect the selected paths and returned count. Repeat the command without
--dry-run, adding --expect-count with that count. The count includes the
root entry, all nested directories, files, and symlinks. Symlinks are removed
without following their targets. The default limits are 1,000 entries and
64 MiB of regular-file content; --max-entries and --max-bytes override
them. These limits bound the selected deletion, not process memory.
For rm, the workspace root, home directory, filesystem roots, .git/,
.jj/, and aitools' state directory are protected. Keep the returned op_id
to undo the deletion.
Stop external writers to the target tree before running the operation.
Neither a dry run nor the journal reserves the tree against other processes.
If a committed write needs recovery, inspect its diagnostics before retrying;
see Transactions for recovery behavior.
The journal and undo apply to workspace targets. The mktemp scratch area
is not journaled or undoable, and a failure there can leave partial changes.
Group related writes in a transaction¶
To group several writes as one journal operation, or check their combined result before it reaches the files, open a transaction:
aitools tx begin --name refactor # returns {"tx": "tx-..."}
aitools edit a.lisp --old ... --new ... --tx tx-...
aitools read b.lisp --tx tx-... # sees staged content; records the read
aitools tx diff tx-... # what commit would change
aitools tx commit tx-... # one op_id for everything
If another process changed a file after the transaction read it, tx commit
fails with exit code 2 and repairs that name tx rebase or a re-read. See
Transactions for the full model.
Read a resource snapshot¶
Use sys snapshot to collect host information, CPU and memory metrics,
interface counters, filesystem capacity, and listening TCP sockets together:
The disk section uses the filesystem containing an optional positional path, or the workspace root by default. The info section always uses the workspace.
Inspect status and reason for each section. The snapshot is not atomic. See
the system command reference for
partial results, limits, and acquisition bounds.
Partial sections retain the data collected so far; unavailable sections have
null data. A list cut off by a configured limit has truncated: true in its
data. A file read larger than 16 MiB makes its section unavailable.
The overall deadline defaults to ten minutes and covers all sections,
including socket-owner scans. Use --timeout to change it. When a deadline
check finds the budget exhausted, deadline_reached is true. Sections left
uncollected by that check are unavailable with a reason object whose code is
environment.timeout. A source failure recorded before the check keeps its own
reason. Each external command is limited to 60 seconds or the remaining overall
budget, whichever is less. A timed-out command is killed and reaped. Local
operations are checked at their boundaries, not interrupted while running. A
bounded call already in progress may finish after the budget; the post-call
check then stops collection.
Directory and ancestor walks check between entries.
Captured subprocess output has no memory bound.
Use sys metrics for a noninteractive, JSON alternative to top:
For field definitions and source limits, see the sys metrics reference.
Use sys network --limit 100 or sys disk PATH when you need one source. See
the sys network and
sys disk references for their
semantics.
See State inspection for workspace and execution state, which the host snapshot does not include.
Run an external program¶
Use a built-in command when you need structured selections, guarded edits,
or undo. Use run when you need an installed program's own behavior:
aitools run -- awk 'END { print NR }' README.md
aitools run -- sed -n '1,10p' README.md
aitools run -- grep -n 'aitools' README.md
Arguments after -- reach the child unchanged. Shell operators, wildcards,
and variable references are not expanded by aitools. To use shell syntax,
explicitly select a shell and quote the whole program:
Only do this with a shell program you trust; do not interpolate untrusted text into it. Prefer direct arguments for variable input.
run captures non-interactive output and does not allocate a terminal or PTY.
By default, run closes stdin and inherits the caller's directory and environment.
Choose one input source: --stdin forwards piped input, --stdin-data TEXT
sends UTF-8 text without adding a newline, and --stdin-file PATH sends regular-file
bytes. FIFOs, devices, and directories are rejected; use --stdin for piped input.
Inline input can appear in shell history; use a file or pipe for sensitive data.
--cwd PATH changes the child's directory only. Relative input-file paths still
resolve from the caller's directory. Repeat --env KEY=VALUE to overlay inherited
variables; the last value wins, and empty values are allowed.
aitools run --stdin-data 'hello' -- sed 's/hello/world/'
aitools run --stdin-file README.md -- wc -l
aitools run --cwd docs --env LC_ALL=C -- find . -name '*.md'
These input, directory, and environment options apply to run, not bg start.
Check the child's exit_code, signal, and timed_out separately: a child
failure or timeout does not make aitools fail. For example, grep returns 1
for no matches while aitools returns 0. If --grep results exceed
--grep-limit, aitools returns 3 with
status:"partial"; the child has already run, so do not blindly retry a
command that can have side effects.
The default output keeps the first 50 and last 150 lines of each stream.
Head/tail trimming and capture caps do not change the aitools exit code.
Inspect truncated and capture_capped before treating output as complete.
External programs are not sandboxed by --root. They retain filesystem and
network access, and their writes bypass aitools guards, transactions, and
undo. Captured JSON output masks known secret formats; --stdout-to writes
raw, unmasked stdout to a new file and is not journaled.
Shell commands and their aitools replacements¶
Choose by the operation, not just the executable name. For example,
sed -n or perl -ne used to print selected lines belongs with read or
search, not an editing command. Arbitrary sed, Perl, awk, and jq programs
can retain their exact behavior through run when no built-in operation
matches. For changes, use edit for one exact occurrence or replace for
every pattern match with a required count. transform changes a file in place;
it is not a drop-in replacement for a shell filter that only prints output.
An agent that calls a shell command name by habit gets argument.invalid
with repairs naming the aitools command to use instead:
| Shell command | aitools command | What it does |
|---|---|---|
cat, head, tail, nl |
aitools read |
Read a file with line numbers and range control. |
grep, rg, egrep, fgrep |
aitools search |
Search file contents by pattern. |
ls, fd, find, tree, du |
aitools find |
List or find files. |
diff, cmp, comm |
aitools diff |
Compare files. |
sed, perl |
aitools edit |
Replace a single occurrence by exact old/new text. |
sed, perl |
aitools replace |
Replace every occurrence of a pattern, with a required match count. |
awk, cut |
aitools table read |
Read delimited or whitespace-separated tabular text. |
sort, uniq, tac, shuf |
aitools transform |
Reorder, dedupe, reverse, or shuffle lines in place. |
tr, dos2unix, expand, unexpand, fold, fmt |
aitools transform |
Apply a line-level text transform. |
iconv, nkf |
aitools transcode |
Convert a file's text encoding. |
cp |
aitools copy |
Copy a file, or a directory with --recursive. |
mv |
aitools move |
Move or rename a file or directory. |
rm |
aitools rm |
Remove one target with journal and undo; trees need --recursive and --expect-count. |
rmdir |
aitools rm |
Remove an empty directory with the journaled rm command. |
delete |
aitools rm |
The former file-removal command was removed; use rm. |
mkdir |
aitools mkdir |
Create a directory and its parents. |
chmod |
aitools chmod |
Set executable bits or an octal mode. |
ln |
aitools link |
Create a symbolic link inside the workspace. |
touch |
aitools touch |
Create an empty file or set a file's modification time. |
mktemp |
aitools mktemp |
Create a temporary file or directory in the workspace's state tmp/ area. |
jq |
aitools doc get |
Read and query structured documents. |
tar, unzip, zcat, gzip, zip |
aitools archive list |
Use archive list, read, extract, or create for the matching operation. |
git |
aitools run -- git |
Run Git through aitools run. |
uname, whoami, hostname, nproc |
aitools sys info |
Read system information. |
uptime |
aitools sys info |
Read system uptime. |
uptime |
aitools sys metrics |
Read load averages. |
env |
aitools sys env |
Read environment variables, with secrets masked. |
which |
aitools sys tools |
Check whether an external tool is available. |
ps |
aitools sys procs |
List processes (read-only). |
top |
aitools sys metrics |
Read one noninteractive system metrics snapshot. |
lsof |
aitools sys ports |
List listening TCP sockets and their owning processes. |
df |
aitools sys disk |
Read capacity of the filesystem containing a path, not every mount. |
netstat |
aitools sys network |
Read cumulative interface counters, not rates or connectivity. |
netstat |
aitools sys ports |
List listening TCP sockets, not every connection or route. |
curl, WebFetch |
aitools net get |
Fetch an HTTP resource with GET and a bounded response body. |
curl, WebFetch |
aitools net head |
Fetch response headers with HEAD. |
dig, nslookup |
aitools net resolve |
Resolve A and AAAA address results through the operating system resolver. CNAME chains and DNS response codes require dig or nslookup. |
date |
aitools time now |
Read or convert the current or a given time. |
base64, xxd |
aitools util encode |
Encode bytes with util encode; use util decode to decode them. |
bc, expr |
aitools util calc |
Evaluate an arithmetic expression. |
uuidgen |
aitools util uuid |
Generate a UUID. |
uuid |
aitools util uuid |
uuid is a group subcommand name; the group prefix is required. |
openssl |
aitools util random |
openssl rand outputs bytes. aitools util random generates cryptographically random strings over hex, alnum, or base64url. |
A shell command with several rows (sed, perl) returns every row's repair,
in table order. A name the table does not list returns the repair
aitools schema. Names that are also aitools commands or groups (find,
diff, mkdir, chmod, mktemp, touch) run the aitools command
and never reach this lookup; their rows only document the mapping.
Retired structured-document command names¶
The former dotted json.*, yaml.*, and toml.* command names no longer
dispatch. Use the matching doc subcommand.
| Retired command names | Current command |
|---|---|
json.get, yaml.get, toml.get |
aitools doc get |
json.select, yaml.select, toml.select |
aitools doc select |
json.diff, yaml.diff, toml.diff |
aitools doc diff |
json.set, yaml.set, toml.set |
aitools doc set |
json.delete, yaml.delete, toml.delete |
aitools doc delete |
json.merge, yaml.merge, toml.merge |
aitools doc merge |
json.patch, yaml.patch, toml.patch |
aitools doc patch |
json.fmt, yaml.fmt, toml.fmt |
aitools doc fmt |