This guide: sash guide · Language reference
What it is
sash is a Unix scripting shell with two explicit execution modes. --local runs
programs from PATH with your OS-user permissions on Linux and macOS. --session
provides the SAH fleet login and emergency shell, with an explicit command table
and host operations authorized by a signed grant. Both share in-process data
filters and the scripting language used for init service files. Agent mode never
falls back to local execution or another shell.
sash --local runs Unix programs, pipelines, background jobs and PTY-backed
expect conversations; sash --session runs filters and agent verbs under a
signed grant.
Current scope. Fleet use needs a launcher (the SystemAPI agent or adssh) that passes a signed grant on file descriptors; adding --session on a workstation does not obtain one. The SystemAPI agent is built to start sash for terminal sessions; rollout to hosts is in progress. journal has no agent reader, so no grant can carry it. Agent-managed interactive jobs and expect are planned, not implemented: job control and expect run only under --local. The release binary has no WebAssembly support. sash catalog --json has full argument contracts for three pilot forms only. XDG startup files, persistent local history and a module search path are not implemented.
The guide
Using sash
Build and install, the command-line modes, sessions and grants, connecting to a fleet host, writing, planning and reviewing scripts, changing files, secrets and recordings, interactive use, service and boot scripts, diagnostics, local execution and job control, expect, the environment, installer scripts, encodings, Jinja2 templates and module development.
ReferenceThe sash language
Every value, statement and option, the full command catalog with entitlement keys and mutation flags (host, compute, file, row, data, service, boot and session words), every exit status and every error string.
Command line
sash [-l] [--session | --local] [--plan] [-c script | file] [-- --name value ...]
run a script; a terminal with no script is the live prompt
sash --needs [--policy] [-c script | file] the grant a script asks for; runs nothing
sash --lint [-c script | file] advisory findings; runs nothing
sash --record out.jsonl --fixture fixture.json [--expires D] [-c script | file]
sash --replay rec.jsonl --fixture fixture.json [-c script | file]
sash --skill [features | language | verbs] print the embedded Claude skill
sash --skill --list list the embedded skill files
sash catalog --json versioned command metadata and pilot module contracts
sash compgen --json SOURCE [BYTE_CURSOR] structured completion edits; runs nothing
sash version --json what this build is, one JSON line
sash codes --json the catalog of what sash prints when it refuses or fails
sash connect [--root] <host> a terminal on a fleet host, for a person at a workstation
Without --session or --local the grant is empty: verbs are denied and filters still run. --session reads the grant and the verb socket from fds 3 to 6, as the systemapi agent or adssh sets them up.
Build and install
The module requires Go 1.26.0 or later. From the checkout, run these commands in your workstation's shell:
./build.sh
./bin/sash version --json
The default build writes bin/sash with -trimpath. ./build.sh install uses
go install and respects GOBIN and GOPATH. ./build.sh clean removes the local
binary. The examples below assume sash is on your workstation's PATH; otherwise
use ./bin/sash.
The release build excludes WebAssembly support. For a local build with it:
SASH_TAGS=sashwasm ./build.sh
This enables hash-pinned, bounded computation through wasm; it does not enable
arbitrary host execution. See the language reference for its restrictions.
First run
For a general-purpose local shell, run sash --local. To run a local script:
sash --local -c 'printf hello | tr a-z A-Z'
sash --local script.sash
No session or local execution mode is necessary for in-process filters and expressions:
sash -c 'echo hello'
sash -c 'echo [ 6 * 7 ]'
sash -c 'echo "alice 1001" | rows name uid |> select name |> to json'
These print hello, 42, and a JSON array containing {"name":"alice"}, respectively. A script can
also be read from a local file or standard input:
sash report.sash
sash < report.sash
With no script and terminal stdin, sash opens the interactive prompt. Without --local or a
session, it prints sash: no session grant: verbs are denied, filters run once.
In the default mode, host commands such as ps, ls, and unit status still need a grant. Reading the
local script file does not authorize reads of paths named inside that script.
Command-line modes
| Invocation | Purpose |
|---|---|
sash [-l] [--session | --local] [--plan] [-c script | file] [-- --name value ...] |
Execute source; without a source, use the prompt or read stdin. |
sash --needs [--policy] [-c script | file] |
List requested capabilities without executing; optionally print policy flags. |
sash --lint [-c script | file] |
Report static advisory findings without executing. |
sash --record out.jsonl --fixture fixture.json [--expires D] [-c script | file] |
Run against canned responses and create a recording. |
sash --replay rec.jsonl --fixture fixture.json [-c script | file] |
Replay responses under the fixture's grant. |
sash --describe [--grant-request] file |
Inspect a service definition or emit an unsigned grant request. |
sash [--session] [--plan] --entry start|stop|reload|check|run file |
Run a service lifecycle entry. |
sash --skill [features | language | verbs] |
Print the embedded agent skill or a reference. |
sash --skill --list |
List embedded skill files. |
sash catalog --json |
Print versioned command metadata; contracts are partial. |
sash compgen --json SOURCE [BYTE_CURSOR] |
Return completion edits without executing source. |
sash version --json |
Print build metadata. |
sash codes --json |
Print the diagnostic catalog. |
sash connect [--root] host |
Open a fleet terminal from a workstation. |
Flags are mode-specific, not freely interchangeable. In normal execution,
--session precedes --plan, which precedes --entry and the source. --needs
and --lint cannot be combined with each other or with execution flags. connect
must be the first argument. -l or --login is accepted first for login-shell use.
Sessions and authorization
Without --local, a hand-started shell has an empty grant, including when run as root. A trusted
launcher such as the systemapi agent or adssh supplies a session with
--session and inherited descriptors:
| Descriptor | Input |
|---|---|
| 3 | Signed grant |
| 4 | Fleet verification key input |
| 5 | Emergency verification key input |
| 6 | Verb transport |
sash validates the grant, checks each operation and target, and sends permitted
verbs to its parent. The agent or init checks them again. File reads and writes
inside the language go through that parent under the grant's roots; cd changes
a session prefix, not the operating system working directory.
Checks happen as statements are reached. Earlier mutations may have completed
before a later statement is denied. Explicit pipeline stages and redirects are
checked before that pipeline starts; called function bodies are checked as they
execute. Neither --needs, plan mode, nor a recording grants authority.
The default grant-controlled login shell reads no profile, rc, or ENV file and imports no environment
variables as script bindings. Programs such as scp, sftp, rsync, and git
are not commands in its table; SSH workflows that expect them fail with exit 127.
An administrator installs the binary, lists it in /etc/shells, and selects it
with chsh when appropriate; sash does not modify those files itself.
As a login shell
sash can be an account's shell. It then behaves exactly as a hand start: an empty grant, where verbs are denied and filters run, and one notice on stderr at the prompt (sash: no session grant: verbs are denied, filters run). -l and --login are accepted as the first argument and ignored, and an argv[0] of -sash changes nothing. sshd running $SHELL -c "<command>" is the ordinary -c path.
It reads no /etc/profile, ~/.profile, rc file, or ENV file, takes no environment variable as a name, and executes nothing: scp, sftp, rsync, and git over ssh into such an account are exit 127 unknown, by design. No error falls through to another shell. It opens no connection and asks no agent for a grant or a lease, and it is the same as root. A person with root adds the binary's path to /etc/shells and runs chsh; sash never edits either file.
Connecting to a fleet host
On your workstation, configure the control-plane address and the token file created by the systemapi CLI's login:
export SYSTEMAPI_URL=https://control.example.com
export SYSTEMAPI_TOKEN_FILE=/absolute/path/to/token
sash connect web1
The URL must be HTTPS without a user, query, or path. The token file must be a regular file owned by the current user, not a symlink, with no group or other permissions, at most 4096 bytes, and contain one token. stdin, stdout, and stderr must all be terminals.
The client resolves the host, obtains a single-use terminal ticket, and connects
using the control plane's sah/3 terminal protocol. --root requests
terminal:root; a refusal is final. The client holds no grant or signing key.
Scripts use the control plane's jobs path rather than sash connect.
The connection requires TLS 1.3 or later and platform trust roots, follows no
redirects, and ignores proxy and certificate-override environment variables.
Terminal output is filtered. After Enter, ~. disconnects locally and ~~ sends
one tilde. The client restores terminal modes when it exits.
What the client checks
sash connect <host> runs on a person's workstation. It is the client half of the control plane's existing terminal protocol, which it calls "sah/3" and names in its User-Agent; nothing is negotiated, and a server that does not answer as that protocol does is refused (connect: the server does not speak sah/3). It resolves the host (GET /api/v1/hosts/resolve), asks for a ticket for terminal:open, or terminal:root with --root (POST /api/v1/ws-ticket), and opens the terminal WebSocket with that ticket, which is used once. The host's agent still checks the signed grant and starts the host's sash. The client holds no grant and no key, records nothing, and never speaks to an agent.
It is an argument of the process and nothing else: no script, -c line, function, or session can reach it, and behind any flag it is the usage line. It takes no script, and stdin, stdout, and stderr must all be terminals. Scripts go through the control plane's jobs path, which has its own gate.
It reads two environment variables and no other. SYSTEMAPI_URL is the control plane's https address, with no user, query, or path. SYSTEMAPI_TOKEN_FILE is the absolute path of the file the systemapi CLI's login writes; sash does not log in. The file is opened without following a symlink and must be a regular file owned by this user, with no group or other permission bit, at most 4096 bytes, holding one token. The token is sent only as the bearer of the two HTTPS calls: never on the WebSocket upgrade, in a URL or argv, or in anything printed. TLS is 1.3 or later with the platform's own roots (on Linux, the platform's bundle files, read by sash itself; on macOS, the platform verifier), which SSL_CERT_FILE and SSL_CERT_DIR do not change, no redirect is followed, and no proxy is read from the environment; sash has no option that changes any of these.
A refusal is printed and the client stops. With --root it asks for terminal:root and nothing else, and a refusal of it is final: it never asks again for another purpose. Everything the client prints is its own fixed text, and the host's name only when it matches the control plane's own hostname rule (otherwise the host id alone). A code the control plane or the host sends is shown only when it is a plain token, with this build's meaning for it (area connect of sash codes --json), and the server's own words are never shown. The host's terminal output is filtered, always: text and the cursor, colour, and erase sequences pass, and a sequence with a numeric parameter of more than four digits is dropped; window titles, clipboard writes (OSC 52), hyperlinks, DCS, APC, PM, and SOS strings, and every sequence that makes the terminal answer are dropped. After Enter, ~. closes the session here and ~~ sends one ~. The terminal mode is put back on every way out, SIGTERM, SIGHUP, SIGQUIT and a panic included; SIGTSTP puts it back while the client is stopped, and raw mode is entered again when it continues. On every way out the client resets the terminal modes a host may set: the character set, the keypad and cursor-key modes, autowrap, cursor blink and visibility, the scroll region, colour and style, the alternate screen, and bracketed paste.
The exit status is the host shell's own; 2 for usage, the environment, the token file, or no terminal; 1 for a failed request, a server that does not speak sah/3, or a lost connection; 126 for a refusal; 130 for Ctrl-C before the session starts, or a SIGINT sent to the client during it (in the session Ctrl-C is the host's input); 131 for SIGQUIT.
Writing and reviewing scripts
Save this as inspect.sash on the workstation:
args {
service string required help "Service to inspect"
}
unit status $service |> to json
Inspect its interface and static requirements without a host session:
sash inspect.sash -- --help
sash --needs inspect.sash
sash --lint inspect.sash
The service target is dynamic, so the needs report may be incomplete. A literal
unit status nginx produces a more specific request. --needs --policy emits
policy flags for expressible literal needs; comments identify unresolved or
non-grantable needs. It does not follow files loaded by use.
For execution in a launcher-provided session, the form is:
sash --session --plan inspect.sash -- --service nginx
Do not expect adding --session to a workstation command to obtain a grant: it
requires the inherited descriptors above.
Use --plan to review changes. It locks plan mode on for the run: mutations are
reported rather than sent, but reads still execute and all grant checks still
apply. Reads after a planned write see the old state, so plan and live runs can
take different branches. set -o plan within a script is not locked on.
--lint reports issues such as unused bindings, incomplete needs, secrets reaching
sinks, retries around mutations, and untrusted prompt or compute results reaching
mutations. Exit 0 means no warning/error findings, 1 means findings, and 2 means a
usage or parse error. A clean report is not proof of correctness.
Changing files
Use fs write-atomic when a failed upstream stage must not overwrite a file:
cat /etc/nginx/nginx.conf | egrep listen | fs write-atomic /var/tmp/ops/listeners.conf
Ordinary > writes the rendered output even when an earlier stage fails or
matches nothing, potentially truncating the target. This remains true with
set -e. fs write-atomic sends no write when an earlier stage failed.
For multiple file changes, atomic { ... } asks the agent to journal writes and
restore them on failure. Writes are visible immediately; there is no isolation.
Concurrent changes can prevent restoration, and a lost connection can leave
writes visible until the transaction deadline. Irreversible operations such as
service restarts are rejected inside the block. See
atomic semantics before relying on rollback.
template_file spec.yaml template.tpl output.conf --check validates and previews
a render without writing. Without --check, it writes through file.write;
plan mode shows a diff. Templates support expressions and bounded control flow,
not command execution or includes. See
templates.
Secrets and recordings
Bind a secret when first reading it:
declare -s token = (cat /srv/app/token)
echo $token
The echo prints ***. Secrecy follows bindings and derived values; it does not
make every later read of the same file secret. A separate plain cat can disclose
the contents. Secret values cannot decide branches or reach ordinary verb
arguments and redirects. Controlled exceptions exist for secret template renders
and service spawn environment values. See
secret handling.
set -o record /allowed/write/root/run.jsonl records subsequent work and writes
through the agent at mode 0600 when recording ends. It is refused in plan mode.
Recordings can contain host data in clear; only bound secrets and recognized
occurrences are redacted. The hash chain checks consistency, not authenticity.
Offline modes use local fixtures and never reach a host:
sash --record run.jsonl --fixture fixture.json script.sash
sash --replay run.jsonl --fixture fixture.json script.sash
The fixture supplies a grant and canned responses. The output recording must not already exist; its default expiration is seven days. Replay checks script, expiry, chain, and event agreement. See offline record and replay and the tape implementation for the fixture contract.
Interactive use
Bindings, functions, options, and directory state persist between prompt lines; each script invocation starts fresh. Useful editor commands include:
| Command | Purpose |
|---|---|
why <line> |
Explain authorization without running the line. |
abbr name 'words' |
Define a visible command abbreviation for this session. |
bind vi / bind emacs |
Select editing bindings. |
z part / z -l part |
Visit or list matching previously visited directories. |
jump save name / jump name |
Save or visit a directory bookmark. |
set -o confirm |
Ask before each mutation. |
confirm off |
Ask to turn confirmation off from the editor. |
logout |
End the session; Ctrl-D also exits. |
Editor commands are not generally available in scripts. For a script to ask a
person, use term prompt or term confirm; stdin and stderr must be terminals,
and the script cannot itself be arriving on stdin. is_tty() tests availability.
Secret input has the exact form declare -s name = (term prompt -s "question").
See asking the person.
Service and boot scripts
A service file begins with a literal service { } declaration and may define
start, stop, reload, and check functions. A declarative run replaces a
scripted start. The init performs process creation, signaling, and mounting;
sash checks and delegates those operations.
sash --describe app.sash
sash --describe --grant-request app.sash
These commands run nothing. The grant request is unsigned and requires the fleet
signer to supply its session fields. Lifecycle execution uses --entry under a
matching service grant. check is read-only. Boot preparation uses a sash/3
boot grant with named modules, devices, mounts, network profiles, and services;
boot verbs run only in the start entry.
See service files and the boot command catalog for syntax and constraints.
Diagnostics
sash version --json reports the build, platform, protocol versions, optional
WebAssembly support, and command/code inventory. sash codes --json lists stable
diagnostics with exit statuses, meanings, and suggested fixes.
| Symptom | What to check |
|---|---|
denied <key> (126) |
Session grant, entitlement, target, and file roots; use interactive why or static --needs. |
unknown <name> (127) |
The closed command catalog; there is no fallback to an installed host program. |
type |> (2) |
Row pipes need rows; lift text with rows, lines, parse, or a suitable from format. |
prefix_unset (2) |
Use an absolute path or establish a permitted prefix. Script globs expand before execution. |
type path (2) |
Convert host-derived text to a validated path value before using it as a script file path. |
term needs a terminal (2) |
Terminal availability and whether source arrived on stdin. |
loop max / verb max (2) |
Work exceeded the configured bounded execution limits. |
wasm_unsupported (2) |
The binary was built without sashwasm. |
An ordinary status 1 does not usually stop a script; status 2, 126, and 127 do.
set -e stops on any failed stage. Failed parallel blocks stop the script even
at status 1. See the language reference for try, capture, $last, and special
uncatchable failures. Service lifecycle exits and connection exits have their own
interpretations; do not treat every nonzero result as a retryable host failure.
Version and codes
sash version --json prints one object: the module version, commit and whether the tree was modified (from the binary's own build information), OS and architecture, the grant and mux versions, whether wasm is built in, the number of forms in the closed table, and the number and SHA-256 of the catalog's codes. It is a claim the binary makes about itself: for display, never to gate anything. sash codes --json prints the catalog (internal/codes): each code with its exit status, area, meaning, and fix. A code is a token; where sash prints a sentence, the meaning quotes it. Both take exactly those two arguments, read no grant, and open no file. Every fix that names a change has a person, the operator, or an admin as its subject; a test scans the fixed messages of the language, grant, session, wire, line editor, connect, and command packages against the catalog, and another pins every sentence in internal/codes/testdata/codes.golden.json.
Development and documentation
Run the repository's full validation with:
./build.sh test
It checks formatting, runs vet and tests with and without sashwasm, runs race
checks for the language and editor packages, and runs govulncheck if installed.
For a focused check of the embedded reference examples and inventories:
go test ./internal/lang -run TestSkill
Source locations:
| Location | Responsibility |
|---|---|
cmd/sash/ |
CLI modes, connection entry point, offline recordings, build metadata. |
internal/lang/ |
Language, command table, data formats, evaluation, static analysis. |
internal/grant/ |
Grant validation and authorization. |
internal/session/, internal/proto/, internal/parent/ |
Session setup and parent transport contracts. |
internal/line/ |
Interactive editor and terminal handling. |
internal/connect/, internal/wsclient/ |
Workstation connection support. |
internal/codes/ |
Diagnostic catalog. |
skills/sash/ |
Embedded agent skill and executable documentation examples. |
docs/plans/ |
Design history; verify implementation before treating a plan as current behavior. |
Print the embedded references with sash --skill language, sash --skill verbs,
and sash --skill features. Install the agent skill from a checkout with
skills/install.sh [skills-dir]; its default destination is
$HOME/.claude/skills/sash. The skill teaches source authoring and grants no
execution authority.
When changing behavior, update this guide, the root language reference, and the corresponding embedded reference. The implementation and its tests are the final authority when design documents disagree.
The Claude skill
skills/sash/ teaches an agent the language and tells it to insert sash source onto the visible line and stop; it contains no runner and grants nothing. The same files are embedded in the binary. sash --skill takes no other flag, no script, and no file, reads no grant and nothing from disk, and writes only to stdout. Reference names are the bare words features, language, and verbs; any other spelling (verbs.md, reference/verbs, a path) is exit 2.
Install from a binary:
mkdir -p ~/.claude/skills/sash/reference
sash --skill > ~/.claude/skills/sash/SKILL.md
sash --skill language > ~/.claude/skills/sash/reference/language.md
sash --skill verbs > ~/.claude/skills/sash/reference/verbs.md
sash --skill features > ~/.claude/skills/sash/reference/features.md
Install from a checkout (copies skills/sash to ${1:-$HOME/.claude/skills}/sash, refuses a symlinked target, prints what it wrote):
skills/install.sh [skills-dir]
Editor actions, themes, and tooling
The kill ring holds up to 16 entries in the current session. Ctrl-K kills to the
end, Ctrl-U to the beginning, Ctrl-W the preceding word, and Alt-D the following
word. Consecutive kills join in text order. Ctrl-Y inserts the newest entry and
Alt-Y cycles older entries immediately after a yank. A different key ends that
rotation. A yank that would exceed the 8192-byte line limit inserts nothing.
Word movement uses spaces and tabs as boundaries; character movement uses UTF-8
runes, not grapheme clusters. The separate secret prompt never uses this ring;
editing a secret declaration also excludes that line from the ring until it is
submitted or cancelled. Vi command mode additionally supports D, p, b, w.
Inspect and customize session-local bindings:
bind actions
bind keys
bind list emacs
bind set emacs Ctrl-B backward-word
bind unset emacs Alt-D
bind reset emacs
Maps are emacs, vi-insert, and vi-command. The latter also accepts single
printable ASCII keys. bind vi and bind emacs still select the mode. A binding
selects a named editor action; it cannot execute source. Enter, Ctrl-C, Ctrl-D,
Ctrl-G and Escape retain their control behavior. Search and menu navigation keep
their own controls. Settings last for the current session only.
Choose a theme or customize individual colors:
theme list
theme dark
theme light
theme mono
theme show
theme set suggestion 244
theme set filter '#a6e3a1'
theme set prompt cyan
theme reset
default preserves the original palette; dark and light use RGB foreground
colors for their respective terminal backgrounds; mono uses terminal defaults
and emphasis. Colors accept default, the 16 ANSI color names (including
bright-black through bright-white), a palette index from 0 to 255, or a quoted
'#RRGGBB'. Quote hex colors because # starts a source comment. In local mode, startup environment settings select truecolor, 256-color, 16-color
or no-color output; RGB overrides are mapped to the selected palette. Sash does
not probe or change the terminal background. See Environment.
Roles are text, filter, verb, unknown, danger, type-error, dynamic,
string, denied, suggestion, prompt, status, error, right-prompt,
menu, and selection. A preset clears overrides; theme reset restores the
original palette. Themes are local to the session. Authorization dim/underline
marks and escaping of control characters remain active across themes and with
syntax coloring disabled. Quoted words receive string colors when ordinary
preview succeeds; refusal markings take priority.
History suggestions already appear at the end of a matching prefix. Right Arrow
or Ctrl-F accepts the visible suggestion without running it. Up/Down browse
matching history and Ctrl-R searches it. These are history-based suggestions, not
AI-generated commands; the theme's suggestion role controls their color.
For external editor integrations:
sash catalog --json
sash compgen --json 'unit re'
sash compgen --json 'theme set sug'
These commands return versioned JSON, read no session or history, and execute nothing. Completion offsets are UTF-8 byte offsets. The catalog currently has full argument contracts for three pilot forms; other contracts are explicitly null. See the module contract for development requirements and the completion API's limits.
Reusable functions and namespaced libraries
Define, inspect and save a session function:
fn twice(x) { return [ $x * 2 ] }
functions
functions show twice
functions refs twice
funcsave twice /srv/sash/lib/twice.sash
Saving needs file.write for the target and uses mode 0600. It participates in
plan and confirmation. The artifact contains the function definition only:
session variables and dependencies are not captured, and it does not autoload.
Functions loaded as part of a namespace must be shared with their library source.
Source containing secret declarations cannot be shown or saved by these commands.
A library file can define constants, helpers and public functions:
declare -r factor = [ 2 ]
fn helper(x) { return [ $x * $factor ] }
fn twice(x) { helper $x }
export twice factor
Load it and call it:
use /srv/sash/lib/math.sash as math
math::twice 21
echo $math.factor
The helper remains private. The namespace is readonly; calls have fresh local
bindings and cannot see caller variables. All ordinary grant checks still apply.
Dependencies use explicit use relative.sash as name declarations, resolved
relative to the importing library. Add sha256 HASH to pin exact source bytes.
Imports reject cycles and collisions and cap depth and total source size. See
Developing sash modules for the full contract.
Double-quoted shell words and expression strings now share escape decoding:
\n, \r, \t, \b, \f, \v, \a, \e, \\, \", \$,
\xHH, \uHHHH, and \UHHHHHHHH. Unknown escapes retain their backslash;
malformed numeric escapes fail. Single quotes remain literal. Compatibility:
"\n" now produces a newline in a shell word; use '\n' or "\\n" for its
literal spelling. Expression strings now preserve unknown escapes instead of
rejecting them. Decoded characters are data and never become shell syntax.
Local Unix execution and interactive jobs
Start sash --local for a local interactive shell, or use
sash --local -c 'sleep 1 & wait'. This explicitly runs programs with your OS
user's permissions. Agent sessions still use their signed grants and never fall
back to local execution.
Local mode supports external byte pipelines, </> redirection, PATH lookup,
command PROGRAM, cd, pwd, &, jobs, fg [%job], bg [%job], and
wait [%job]. Ctrl-Z stops the foreground process group; Ctrl-C interrupts it.
The shell restores terminal ownership and modes after foreground jobs, and
cleans up owned jobs on exit or hangup. Existing sash variables, functions,
libraries and funcsave remain available.
Private PTY conversations use expect open, expect match, expect send,
expect resize and expect close. These are local-mode operations. They do not
implement the pending agent stream protocol or secret-redacted transport.
See Job control and Expect for examples, limits, verification and remaining work.
The environment commands, the variables sash manages and the interactive color settings are in Environment.
Local Unix execution, PTYs and job control
Implemented for Linux and macOS (2026-12-01). Start the local
shell with sash --local, or run a script with sash --local -c '...' or
sash --local file.sash. This is explicit OS-user execution, separate from
--session and its signed grants. Agent operations never fall back to local exec.
The default hand-start behavior remains unchanged until --local is selected.
Using jobs
sleep 30 &
jobs
fg %1
# Ctrl-Z stops the foreground job and returns the prompt.
bg %1
fg %1
# Ctrl-C interrupts the foreground job.
fg and bg without an ID select the newest active job. wait %1 waits for one
job; wait waits for the jobs in the current table. jobs reports IDs, process
groups, running/stopped/done state and status. IDs are monotonic per shell.
Foreground jobs are also retained in the table; completed entries are pruned
when it reaches 256 entries. There can be at most 64 active jobs, each with at
most 64 pipeline members.
Local external pipelines use real OS pipes and run all members concurrently:
let message = hello
/bin/echo $message | tr a-z A-Z
sleep 1 &
wait
let result = (/bin/echo captured)
echo $result
Sash's existing capture semantics preserve the captured newline. Names and
functions stay in the interpreter. Unknown command names resolve through PATH.
Common Unix file/process commands (cat, ls, ps, rm, mkdir, touch,
chmod, chown, ln, mount, umount) use local programs in this mode.
command PROGRAM ... explicitly selects a program when a sash builtin has the
same name. cd [directory] changes local cwd; pwd prints it. Children inherit
the local environment, with PWD updated. Environment variables are not
implicitly imported into sash's typed variable namespace.
< and > on external pipelines use local files. Globs, source libraries and
funcsave use local OS file access through an explicit local parent. This parent
has no agent socket and cannot fulfill fleet operations. --local --plan and
set -o plan suppress process launches and file writes; confirm mode asks before
local process operations. As with ordinary shells, a local process runs with the
invoking user's OS authority: local mode is not a sandbox.
Terminal and process ownership
Each job owns a process group and a small supervisor process that reserves its PGID until cleanup. Workers wait behind a launch gate until every pipeline member has started and foreground terminal ownership is assigned. A failed launch kills and reaps the pending group before releasing the gate.
The local editor reads synchronously; it does not leave a goroutine reading the terminal while a child owns it. Foreground jobs receive the controlling terminal in cooked mode. Ctrl-C/Ctrl-Z reach the entire foreground group; background terminal readers stop through SIGTTIN. Sash saves stopped-job terminal modes and restores shell modes when it regains the terminal. Window changes on the shared terminal reach the foreground process group through the OS.
On exit or hangup, sash sends HUP/CONT to owned jobs, then escalates to KILL and
reaps its children. The supervisor's private pipe also detects a crashed parent.
Process groups are not containment against programs deliberately creating new
sessions; there is no disown, daemon supervisor or cgroup sandbox in this mode.
Captures are bounded to 8 MiB and terminate their group on overflow. Foreground output streams directly, allowing terminal applications and their escape codes. Background output also goes directly to the terminal and may interrupt prompt painting; asynchronous prompt-aware output redraw is not implemented.
PTY-backed expect
expect open allocates a private controlling PTY for a local program. See
Expect for match, send, resize, close, timeout and cleanup behavior.
Private conversations are separate from foreground jobs; they do not compete
with the editor for keyboard input.
Verification and remaining work
Tests exercise real controlling PTYs on Linux and macOS: foreground process-group ownership, canonical terminal modes, multi-process pipelines, Ctrl-Z/bg/fg, background readers, Ctrl-C, resize, hangup cleanup, launch rollback, capture limits, local libraries, plan mode and expect prompt/reply conversations.
Remaining scope is explicit:
- Agent-managed interactive jobs/expect still require the agent protocol,
authorization, lease, recording and disconnect integration. They are not
enabled by
--local. - External process pipelines cannot contain sash functions or typed
|>stages. Use a capture to bring external bytes back into sash's typed language. &applies to one pipeline, not a compound&&/||chain or block.- Local execution is refused in readiness checks, atomic file transactions, recordings and parallel-language branches. It does not silently evade those modes. Secret-valued process arguments and replies are refused.
- Full POSIX shell syntax, descriptor redirects, disown, PATH-aware completion and persistent local history are not implemented by this change. Sash keeps its own scripting syntax.
Environment access and child-process settings are documented in Environment.
Expect: local PTY conversations
The bounded stream matcher in internal/expect is connected to private local
PTYs through internal/job on Linux and macOS. These commands require --local.
They do not add interactive process execution to agent sessions.
expect open demo /bin/sh -c 'printf "Name? "; read name; printf "Hi %s!" "$name"'
expect match demo literal 'Name? ' timeout 2s
expect send demo "Ada\n"
expect match demo literal 'Hi Ada!' timeout 2s
expect close demo
expect open NAME PROGRAM [args...]resolves PROGRAM through PATH and starts it with a private controlling PTY, initially 24 rows by 80 columns.expect match NAME literal|regex PATTERN timeout Dconsumes bytes through the match and returns the matched text. Regex uses Go's regexp syntax. An outer sash timeout may shorten D; D must be positive and at most five minutes. Timeout returns status 124 and retains buffered bytes. EOF before a match returns status 1. Matches do not require a newline.expect send NAME TEXTsends exactly the supplied bytes; include\nwhen needed. Sending has a ten-second maximum deadline. Cancellation closes the conversation because a partially sent reply must not be retried automatically.expect resize NAME ROWS COLSchanges the terminal size (1–1000 each).expect close NAMEcloses the PTY, kills the owned process group and reaps the program. Shell cleanup closes any remaining conversations.
There can be at most 16 named conversations. Names start with an ASCII letter and contain letters, digits, underscores or hyphens, up to 64 characters. A process that exits remains unreaped until the conversation closes, reserving its PGID through cleanup; explicitly close finished conversations in long scripts.
The engine bounds unmatched output to 64 KiB and patterns to 4096 bytes. It matches across read boundaries, preserves trailing bytes for the next operation, and distinguishes EOF from timeouts. It uses available bytes immediately, so a greedy regex does not wait for future output. Its internal API supports multiple patterns and capture groups; the initial language command returns one match's text rather than exposing that full result structure.
Nothing automatically logs PTY input/output. Local program output is not redacted. Secret-valued sash arguments, including secret replies, are refused; end-to-end secret-marked transport/redaction is still agent-integration work. Plan mode suppresses these operations. Readiness checks, atomic transactions, recordings and parallel-language branches refuse local process execution.
Agent integration (planned)
Expect runs only under --local. Done: the bounded literal/regex stream matcher,
its connection to real local PTYs and language operations, and prompt/reply tests
on Linux and macOS. Planned, not implemented:
- Specify and implement agent stdin, incremental byte streams, EOF, acknowledgements and capability/version negotiation.
- Bind handles to the owning session/process and re-check executable policy, grants and lease expiry on the agent.
- Connect the agent adapter to the conversation commands without local fallback when an agent denies or lacks support.
- Preserve plan/confirm, cancellation, unknown write outcomes and cleanup across agent disconnects.
- Carry secret markings through replies and echoed output so credentials cannot reach transcripts, history, traces or recordings.
- Verify these paths against a real agent, including unsupported versions, denial, expiry, timeout, disconnect and secret echo.
Agent-managed expect is not complete. Local PTY tests do not close that checklist.
Local environment and terminal settings
These settings apply to sash --local. Agent sessions continue to use their
signed grants; local environment access does not change agent permissions.
Environment commands
export APP_MODE = production
export EDITOR = vim
let home = (getenv HOME)
let mode = (getenv APP_MODE development)
echo $mode
unset APP_MODE
export NAME = VALUE sets an environment string for subsequent local programs
and expect open processes. The = distinguishes it from a library export. Values undergo
normal sash expansion, never evaluation as source. Use quotes for spaces or an
empty value. let still creates a sash variable; it does not export it.
export function_name retains its existing library-export meaning.
getenv NAME [DEFAULT] returns the exact value, without adding a newline. A
missing name returns status 1, or the supplied default with status 0. An empty
value counts as set. Use let value = (getenv NAME); echo $value to print a line. Environment values are ordinary strings, not automatically
secret-marked. Request names explicitly; there is no bulk environment dump.
unset NAME ... removes exported names, not sash variables. All names are
validated before anything is removed. Names use ASCII letters, digits and
underscores and cannot start with a digit. Exported values cannot contain NUL
and are limited to 128 KiB each; the OS may impose smaller aggregate launch
limits. Sash refuses secret-marked exports.
Each session snapshots its inherited environment. Export/unset changes only that
session's later children, never the parent shell or an already-running child.
These commands must stand alone, without redirects, backgrounding or external
pipeline stages. getenv can be captured; export/unset cannot. Plan mode skips
all three commands, including reads. Confirmation and the existing restrictions
on recordings, readiness checks, atomic transactions and parallel branches apply.
Standard variables
| Variable | Behavior |
|---|---|
SASH_JINJA_PYTHON |
Optional Jinja2 renderer interpreter; one executable path/name, default python3. See Jinja2 templates. |
PATH |
Program search path for commands and expect open; exports take effect immediately. An unset/empty PATH does not fall back to a system default. Use explicit ./program for current-directory execution. |
HOME |
Destination of bare cd; changing it with export takes effect immediately. |
PWD |
Initialized from the actual working directory and updated by cd. Managed by sash. |
OLDPWD |
Updated to the previous directory after successful cd. Managed by sash. |
SHELL |
Initialized to the running sash executable; inherited by child programs. |
SHLVL |
Inherited level plus one; invalid, negative or >=1000 levels reset to 1. Managed by sash. |
EDITOR, VISUAL, PAGER, LANG, LC_*, TMPDIR |
Inherited by child programs; sash does not currently implement editor/pager commands or locale-dependent language syntax. |
PWD, OLDPWD and SHLVL cannot be changed with export/unset. Other names,
including PATH and HOME, can be changed. Environment names are not implicitly
sash variables: use (getenv HOME), not $HOME, unless you defined a sash variable
named HOME yourself.
Interactive colors
Configure these in the launching shell, before starting sash:
SASH_THEME=dark SASH_COLOR=auto sash --local
NO_COLOR=1 sash --local
| Variable | Values and behavior |
|---|---|
SASH_THEME |
default (default), dark, light, mono. |
SASH_COLOR |
auto (default), always (force truecolor), never (disable foreground colors). |
NO_COLOR |
Any nonempty value disables colors in auto mode. |
TERM |
dumb disables colors in auto mode; a value containing 256color enables a 256-color palette. Other values use 16 colors. |
COLORTERM |
truecolor or 24bit enables RGB in auto mode, unless NO_COLOR or TERM=dumb disables it. |
RGB themes and custom colors are mapped to the nearest supported palette color. Invalid SASH_THEME/SASH_COLOR values refuse interactive startup with a fixed error message. Explicit SASH_COLOR=always overrides NO_COLOR and TERM=dumb.
Settings are read at interactive startup. theme commands change the palette
within that session while preserving the startup color policy. No-color mode
still uses cursor controls, reset and emphasis sequences for editing; it is not
a plain terminal mode. Child programs control their own output colors.
Connection and build settings
sash connect still reads SYSTEMAPI_URL and SYSTEMAPI_TOKEN_FILE only for
connection configuration. It does not consume proxy or TLS override environment
variables. SASH_TAGS=sashwasm ./build.sh is a build option, not runtime configuration.
XDG startup/config files, persistent local history and a module search path are not implemented by this change; no environment knobs pretend to enable them.
Local installer scripts
Use sash --local script.sash for machine-local installer hooks. This mode uses
the invoking user's OS permissions and does not require or modify fleet grants.
Native fs operations require no coreutils, shell, or Python interpreter:
| Command | Behavior |
|---|---|
fs exists PATH |
Status 0 if an entry exists (including a symlink), 1 if missing |
fs read PATH |
Return exact file bytes as text, with no added newline |
fs mkdir PATH [MODE] |
Create directories recursively; default mode 0755, subject to umask |
fs write PATH CONTENT [MODE] |
Atomically replace a file; default mode 0644 |
fs copy SOURCE DEST [MODE] |
Atomic copy of a regular file; default source permission bits |
fs symlink TARGET LINK |
Create a symlink; target text is preserved verbatim |
fs chmod PATH MODE |
Change permission bits; refuse a symlink |
fs chown PATH UID GID |
Set numeric nonnegative owner/group IDs without following the final symlink |
fs remove PATH |
Remove one file, symlink, or empty directory; missing is success |
Modes are octal permission bits 0000 through 0777. Relative paths resolve from
the local session's working directory. Writes and copies require an existing
parent directory, sync the new file, then rename and sync the parent. A
replacement does not follow the destination symlink. Replacement files have the
invoking user's ownership; use fs chown explicitly if needed. Removal is not
recursive. Operations use local filesystem permissions; parent symlinks are not
a confinement boundary, and reads follow symlinks. Metadata preservation beyond
permission bits (ACLs, xattrs, ownership, timestamps) is not implied.
These commands must stand alone, without redirection, background execution, or
external process pipelines. fs read and fs exists may be used in captures or
conditions. Fleet/session fs write-atomic remains its existing granted verb;
the native commands do not become available in session/default mode.
Local process pipelines now return the rightmost nonzero stage status, matching
pipefail. A successful consumer no longer hides a failed producer. Use set -e
when a failed statement should stop the installer. Filesystem operations are
atomic individually; arbitrary script effects are not a multi-file transaction.
ADPM passes explicit context through the environment. Environment values are
not automatically variables; retrieve them with getenv:
set -e
let root = (getenv ADPM_ROOT)
fs exists $root
fs mkdir "$root/etc/base-system" 0755
if fs exists "$root/etc/base-system/settings.conf" {
echo "Keeping existing settings"
} else {
fs write "$root/etc/base-system/settings.conf" "enabled=true\n" 0644
}
When ADPM uses chroot, ADPM_ROOT is /; otherwise it is the host-side target
path. Use the supplied root for target files. Running a privileged local hook
without chroot gives it host privileges; sash does not turn that into a sandbox.
Binary encoding and decoding
Sash provides pure byte filters in every mode:
encode base64|base64url|hex|base91|base122
decode base64|base64url|hex|base91|base122
No external codec executable or extra dependency is needed. These are encodings, not encryption, compression or checksums. Both the input and output are limited to 8 MiB; filters buffer one complete input rather than stream unlimited files. Malformed input returns status 2 and emits no decoded bytes. Error messages do not echo the input. Encoders add neither a newline nor line wrapping.
File and pipeline examples
In sash --local:
encode base91 < payload.bin > payload.b91
decode base91 < payload.b91 > restored.bin
encode base122 < payload.bin > payload.b122
decode base122 < payload.b122 > restored122.bin
cat payload.bin | encode base91 | decode base91 > roundtrip.bin
The local pipeline manager runs native sash codec workers inside the job's process
group, alongside external programs. Their PATH cannot replace encode/decode;
command encode ... explicitly requests an external program instead. Local
pipelines preserve producer failures through pipefail.
As with other local OS redirects, > opens/truncates its destination before the
codec runs. Invalid input emits no partial decoded bytes but may leave that output
file empty. Use a new staging path when preserving an existing file matters.
In agent mode, codecs remain in-process filters; file reads and writes need the usual grant. Agent refusal never selects local execution. Pure in-process codecs can be used in plan mode; local process pipelines are suppressed by local plan mode. Neither codec is a readiness predicate: direct await-condition use is refused.
An echo producer adds a newline to its input, which is encoded too:
echo hello | encode base64
This produces aGVsbG8K, the encoding of hello plus newline. For exact strings,
use expression functions instead.
Encoding expressions
echo [ base64("hello") ]
echo [ unbase64("aGVsbG8=") ]
echo [ base64url("hello") ]
echo [ unbase64url("aGVsbG8") ]
echo [ unbase91(base91("hello")) ]
echo [ unbase122(base122("hello")) ]
echo [ hex(base122("hello")) ]
Functions operate on the string's bytes, including NUL and invalid UTF-8 in binary
strings. New functions are base64url, unbase64url, base91, unbase91,
base122, and unbase122; existing base64, unbase64, hex and unhex remain.
Expression allocation budgets may impose smaller limits than pipeline filters.
Results retain the language's secret taint; encoding does not declassify a value.
Formats and strictness
| Name | Encoder | Decoder |
|---|---|---|
base64 |
Standard RFC 4648 alphabet with = padding. |
Requires canonical padded representation and zero unused bits. |
base64url |
URL-safe -/_ alphabet, no padding. |
Requires canonical unpadded representation; rejects =. |
hex |
Lowercase hexadecimal, two digits per byte. | Accepts upper/lowercase digits; requires an even count. |
base91 |
Joachim Henke's basE91 alphabet and 13/14-bit packing. No padding. | Canonical reference format; rejects non-alphabet bytes and invalid tails. |
base122 |
Experimental Kevin Albertson Base122 format, producing UTF-8 bytes. | Validates UTF-8, escape tags, final groups and canonical encoding. |
All pipeline decoders and the new expression decoders reject whitespace rather than silently discarding it. Base122 is different: some whitespace/control bytes are valid encoded data and are preserved; never trim or normalize them. Canonical validation rejects redundant groups or nonzero unused tail bits. Hex is case-insensitive by definition. Empty input succeeds with empty output.
Compatibility: existing unbase64 retains its older Go standard-decoder behavior
(including ignored CR/LF and permissive unused bits). decode base64 is deliberately
stricter. No codec can detect every corruption that happens to form another valid
encoding; use a separate hash/checksum when integrity matters.
Playing with Base122
Base122 is explicitly experimental and follows the reference implementation
identified by hash in internal/codec/testdata/reference.json. It is opt-in;
no existing transport, configuration format or recording changes encoding.
Its output is valid UTF-8 but can contain control characters, including ESC, and
is not guaranteed to survive terminal display, copy/paste, whitespace cleanup or
Unicode normalization. Prefer file redirects. For inspection, render its bytes
as hex with hex(base122(...)) or an additional encode hex pipeline stage.
It is not automatically safe as an unquoted shell argument, JSON string or URL.
basE91 is printable ASCII, but includes punctuation with shell/JSON significance; quote or serialize it for its destination. Base64 remains the broadest interoperability choice; Base64URL is useful when URLs are the destination.
Verification and provenance
Tests compare basE91 with Joachim Henke's C reference and Base122 with Kevin Albertson's JavaScript implementation. Fixtures include all byte values, tail boundaries, zero/FF runs and deterministic larger inputs. Tests additionally cover all 65,536 two-byte inputs, malformed input, secret taint, allocation limits, local binary-file round trips and fuzzing. Reference notices are retained in THIRD_PARTY_NOTICES.md.
Sources: basE91 reference mirror, Base122 reference.
Optional Jinja2 configuration templates
Native sash templates remain the default and need no Python. On Linux and macOS,
--local can select the genuine Jinja2 3.1.6 engine using --engine jinja2.
This is not an Ansible runtime: Ansible-specific filters, lookups and extensions
are not included. Agent sessions cannot select this backend.
Install the optional backend
From your existing workstation shell, create a dedicated Python environment:
python3 -m venv "$HOME/.local/share/sash/jinja"
"$HOME/.local/share/sash/jinja/bin/python" -m pip install -r requirements-jinja2.txt
export SASH_JINJA_PYTHON="$HOME/.local/share/sash/jinja/bin/python"
./bin/sash --local
The requirements file pins Jinja2 and MarkupSafe. Without SASH_JINJA_PYTHON, sash
looks for python3 in the local session's PATH. The setting names one executable,
not a command line. Inside sash, use export SASH_JINJA_PYTHON = /absolute/path/to/python.
Missing Python or a Jinja2 version other than 3.1.6 produces an explicit error;
nothing is automatically installed and no renderer fallback occurs. Python runs
with -I, ignoring PYTHONPATH and user-site packages; a virtual environment works.
Render and preview
settings.yaml:
vars:
port: 8080
hostname: example.test
schema:
port:
type: number
required: true
hostname:
type: string
required: true
nginx.conf.j2:
server {
listen {{ port }};
server_name {{ hostname }};
}
In sash local mode:
template_file settings.yaml nginx.conf.j2 nginx.conf --engine jinja2 --check
template_file settings.yaml nginx.conf.j2 nginx.conf --engine jinja2
The spec can be YAML, JSON or TOML, either a plain variable map or the existing
vars/schema format. Schema validation precedes rendering. --check prints a
diff and exits 1 when different, 0 when identical; it never writes. Plan mode also
renders and previews without writing. A missing output is compared to empty text,
as with native templates. Render/schema errors return status 2 and leave the
output untouched. Successful writes use the existing template_file file-write
path; they are not a new atomic installation or application-validation facility.
Pipeline rendering takes a map and writes rendered bytes:
echo '{"port":8080,"hostname":"example.test"}' | from json | template nginx.conf.j2 --engine jinja2
Flags follow positional arguments:
template_file SPEC TEMPLATE OUTPUT [--check] [--engine native|jinja2] [--template-root DIR]
template TEMPLATE [--engine native|jinja2] [--template-root DIR]
--template-root is accepted only with Jinja2. Duplicate, unknown or incomplete
options are rejected. An extension such as .j2 never changes the engine implicitly.
Includes, macros and inheritance
Without --template-root, only the main template is available. To load supporting
templates, explicitly select a directory:
template_file settings.yaml nginx.conf.j2 nginx.conf --engine jinja2 --template-root templates
For example, a template can use {% extends "base.j2" %}, import macros with
{% import "macros.j2" as helpers %}, or include {% include "parts/routes.j2" %}.
Names are relative to the selected root, including inside nested templates;
they are not relative to the including file. Dynamic include names can select
only templates already present in the bundle.
Sash snapshots regular .j2, .jinja and .jinja2 files from that root into a
bounded in-memory loader. Other extensions are ignored. The entire selected root
is traversed, not just referenced files. Symlinks anywhere in that tree are
refused. Root-relative opening prevents path escape during traversal; absolute
include names, .., backslashes and empty path components are refused. Templates
have no filesystem loader. Select a small template-only directory.
Semantics and limits
- Missing variables are errors (Jinja StrictUndefined). Standard explicit Jinja
defaults such as
{{ optional | default("value") }}still work. - Jinja filters, loops, conditionals, macros and inheritance are available through
an immutable sandbox. The only global helper is bounded
range; arbitrary Python objects, environment access, plugins and shell calls are not exposed. - HTML autoescaping is off for config generation. Use format-appropriate quoting
or serialization (for example
tojson); Jinja does not validate nginx, YAML or shell syntax for you. Trailing newlines are preserved. - Source, bundle and rendered output are bounded to 8 MiB; at most 64 supporting templates, 1024 tree entries and 16 nested directory levels are scanned.
- Rendering has a five-second wall deadline (shortened by an outer sash timeout) and four CPU seconds. Linux additionally limits address space to 512 MiB. macOS has time/output bounds but no equivalent hard address-space cap here.
- Shell close/hangup cancels and waits for active renderer processes. Failed renders discard partial output. Python exception text is not printed because it may contain data; errors report fixed categories.
- Jinja2 rendering is refused in recordings, readiness checks, atomic blocks and parallel-language branches. Plan rendering is allowed because it must compute the diff; confirm still applies at the existing output-write boundary.
- Secret-marked inputs and sessions with tracked secret text are refused. Use native templates for the existing secret-aware 0600 rendering workflow. Plain unmarked sensitive data is not detected automatically. The Jinja sandbox is not OS containment against a compromised Python installation.
--needs marks Jinja2 forms not_grantable/incomplete rather than describing them
as agent-authorized operations. The builtin catalog lists engine flags, but static
inspection does not open the template root or enumerate dependencies.
Deployment workflow
Render to a staging file, validate it with the application's own checker, then
install it and reload the service only after validation succeeds. Sash does not
infer the right validation command, destination permissions, or reload operation.
For example, test an nginx configuration with nginx -t -c /absolute/staged.conf
before replacing the live file. This backend renders; it does not auto-deploy.
Jinja2 tests
With the optional dependencies installed:
SASH_JINJA_PYTHON=/absolute/venv/bin/python go test -race ./internal/job ./cmd/sash ./internal/lang -run 'TestJinja|TestLocalJinja|TestTemplate|TestNeeds'
Without that setting, optional live-Python tests explicitly skip; option parsing, agent refusal and bundle boundary tests still run. Native-template tests remain independent of Python.
Developing sash modules
Sash has three distinct extension mechanisms: compiled-in commands, sash source
libraries loaded with use, and optional pure WASM functions. This contract
covers compiled-in development. There is no dynamic native plugin loader.
Registration and metadata
Register each command form exactly once in internal/lang/builtin.go, using its
existing kind, entitlement key, description, completion visibility and flags.
The evaluator remains the execution authority. Completion, builtin, the novice
menu, and sash catalog --json use this registry; do not add another dispatcher.
The versioned sash-catalog/1 output includes all forms, build availability and
mutation classification. contract: null means the detailed schema has not been
specified. Consumers must preserve that unknown state. Keywords and builtins
with no entitlement are not necessarily pure: they can execute other statements,
change session state, prompt a person, or inspect state.
The first detailed contracts cover echo (pure bytes), cat (conditional file
reads, or input bytes with no path), and unit restart (a mutation delegated to
the agent). They are in internal/lang/catalog.go. Argument types describe the
command interface after expansion, not the syntax of every expression that can
produce an argument. Agent-defined results do not claim a fixed row schema.
Required implementation work
For a new form:
- Add its literal form and metadata. Reject collisions in catalog tests.
- Extend classification, argument validation and dispatch in
internal/lang. Preserve literal command/subcommand restrictions and secret provenance. - Extract targets through the ordinary authorization path. Document conditional
effects, such as
catwith and without paths, rather than hiding exceptions. - Extend needs analysis, lint and preview where necessary. Dynamic targets must remain explicitly unresolved; inspecting source must not execute it.
- For a mutation, register the entitlement in the shared mutation classification. Confirm must ask and plan must suppress the operation. Explain any exception such as boot-device observation being suppressed during a boot plan.
- Establish behavior under
await/check,atomic,par, retry, timeout and cancellation. An external effect is not automatically reversible or safe to retry. Preserve reports of mutations whose outcome is unknown. - Use existing parent transport and execution budgets. Bound argument sizes, output, waits and in-flight work; do not create a hidden direct I/O path.
- Define secret handling and recording/replay behavior. Display hostile data through the existing escaping paths. Never use a recorded response as a grant.
- Add stable errors to the error catalog when introducing new failures, and update the embedded verb reference and public documentation.
- Test success, invalid input, missing entitlement, target refusal, plan, confirmation and partial failure where relevant. Tests must observe effects, not merely repeat metadata declarations.
A descriptive schema does not authorize an operation. The host agent continues to verify the signed grant and target even when preview permits the source.
Source library contract
The flat use PATH form retains its original behavior. Namespaced imports use:
use /srv/sash/lib/services.sash as services sha256 HASH
services::restart_if_failed nginx
The optional HASH is 64 lowercase SHA-256 hex digits for the exact source bytes.
Namespaces expose functions with :: and readonly constants through map fields.
A library can explicitly export names:
declare -r attempts = [ 3 ]
fn helper(name) { unit status $name }
fn status(name) { helper $name }
export status attempts
Here helper stays private. Without export, all of the library's own functions
and constants are public. Dependencies use use other.sash as other and optional
hash pins; their namespaces stay private. Relative imports resolve against the
importing file's directory. There is no implicit search path or downloader.
Initialization permits only definitions, non-secret readonly constants, explicit namespaced imports and export declarations. Caller bindings are absent during loading and function calls. Each call copies module binding maps, so function locals do not leak or persist between calls. The caller's grant, execution budgets, cancellation, plan and confirm state continue to apply. Module helpers are followed by atomic preflight; runtime authorization still checks every verb.
The loader validates exports and duplicates before publishing anything, refuses
namespace collisions and cycles, limits nesting to 16 imports, and limits total
source bytes for one top-level import to 8 MiB. Files are read through the normal
authorized parent operation. Hash mismatch fails before parsing. --needs does
not follow imports: its explicit incomplete result remains significant.
functions, functions show NAME, and functions refs NAME provide inspection.
Refs are syntactic references, including locals/parameters, not a claim that every
listed name is an external dependency. funcsave NAME PATH persists one session
function through file.write at mode 0600. It never serializes session values,
bundles dependencies, or installs an autoload hook. Imported module functions
cannot be saved in isolation. Source containing secret declarations is refused.
Version resolution, dependency manifests and automatic loading remain future work; content pinning and explicit paths are implemented now.
WASM modules
WASM remains build-tagged (sashwasm) and absent from the release build. Its
existing interface is pure computation with JSON input/output, no host imports,
a checked content hash, bounded execution, and secret-argument refusal. The
catalog reports build availability. Enabling effects or host imports would need
a separate authorization and resource design.
Completion tooling contract
sash compgen --json SOURCE [BYTE_CURSOR] emits sash-completion/1. Each candidate
contains insertion/display text, kind, description, optional entitlement key,
denied, and UTF-8 byte offsets start and end. The end is exclusive. Input is
limited to 8192 bytes; the cursor must be a valid UTF-8 boundary. Invalid input is
exit 2; a valid request with no candidates is exit 0 with an empty array.
The API uses the same candidate engine and lexical insertion checks as Tab. Candidates describe edits, never execution. Open quotes and unsafe insertion contexts intentionally yield no edits. It completes command forms, flags and editor enums from existing registries. It does not contact a host, load history, read session descriptors, or enumerate the filesystem. Its empty grant marks entitlement-bearing commands denied; that says nothing about a separate session.
The editor's in-process Candidates method additionally sees its existing names,
functions and authorized remembered paths. No values are included. A caller must
preview and authorize submitted source normally after accepting any edit.
sash catalog --json and sash compgen --json are process modes, not sash-language
commands, and cannot be combined with session or execution flags.
Built from the sash repository's README.md, DOCUMENTATION.md and docs/ at commit e5bf852 on branch main. The implementation is authoritative: where this page and the code disagree, the code and its tests win. The repository has no license file yet.