npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@taliesinb/mash

v0.1.1

Published

A bash virtual machine: span-preserving parser, static effect analysis, policy-checked streaming execution, behavior definitions for executables, and tracing hooks.

Readme

mash — a bash virtual machine for agent harnesses

mash sounds like bash; the m is for machine. Source: github.com/taliesinb/mash.

mash parses a bash snippet into a span-preserving AST and analyzes it statically. It then executes the snippet itself, a tree-walking interpreter over real processes and streams, and checks every step against a sandbox policy.

It is built for the DeepSea agent harness. There, the model's bash tool calls should be:

  • Rejected up front when they would definitely violate the sandbox policy (rm -rf /etc/foo, cd /usr/local && make install).
  • Checked step by step when a step's target is only known at runtime (d=$(...); rm -rf "$d"). Each step is denied individually, and the script carries on with exit status 126, as if the OS had refused.
  • Observable while they run. Trace events report which command is running, loop iterations, the subshell tree, and the bytes flowing through every pipe and redirection.

TypeScript, Node ≥ 24, no runtime dependencies.

$ mash analyze -c 'out=$(mktemp -d); for f in src/*.ts; do wc -l "$f" >> "$out/n"; done; cd /etc && rm -f x.bak'
verdict: reject
  ✗ line 1: `rm -f x.bak` would delete /etc/x.bak: delete: /etc/x.bak is outside the writable roots (…)

commands:
  ✓ L1 [must,$()] mktemp -d
      allow write ⟨$(mktemp):path⟩
  ✓ L1 [must,loop] wc -l src/⟨*.ts:filename⟩
      allow append ⟨$(mktemp):path⟩/n
  ✓ L1 [must] cd /etc
  ✗ L1 [happy] rm -f x.bak
      deny delete /etc/x.bak — …
variables:
  out: path = ⟨$(mktemp):path⟩
  f: filename = src/⟨*.ts:filename⟩

Install

npm install @taliesinb/mash        # library: import { Machine } from '@taliesinb/mash'
npx @taliesinb/mash analyze -c 'rm -rf /opt/x'     # CLI (the binary is called `mash`)

The DeepSea adapter is a subpath export: import { preflight, runForHarness } from '@taliesinb/mash/integrations/deepsea'. So is the pretty-printer alone, for browser bundles: import { formatHtml, summarize } from '@taliesinb/mash/printer' (it still reaches the static analysis, so a bundler needs stand-ins for node:fs, node:path and node:os).

Quick start (from a clone)

pnpm install
pnpm test                                  # ~1970 tests, incl. ~1780 differential tests against /bin/bash
node bin/mash.ts analyze -c 'rm -rf /opt/x'
node bin/mash.ts run --trace -c 'for f in a b; do echo $f | tr a-z A-Z; done'
node bin/mash.ts run --dry-run -c 'rm -rf build && mkdir build && cp src/*.ts build/'
import { Machine, ProgressTracker } from '@taliesinb/mash'

const m = new Machine({
  cwd: '/work/repo',
  policy: { mode: 'workspace-write', workspaceRoot: '/work/repo', network: 'deny' },
  hooks: {
    beforeCommand(ctx) {        // argv after expansion + predicted effects + policy findings
      if (ctx.argv[0] === 'git' && ctx.argv[1] === 'push') return { action: 'deny', reason: 'ask first' }
    },
  },
  stdout: (chunk) => process.stdout.write(chunk),
})

const script = m.parse(snippet)
const report = m.analyze(script)            // static: commands, effects, types, verdict
if (report.verdict === 'reject') throw new Error(report.reasons.join('\n'))

const progress = new ProgressTracker(report)  // static plan + live events
m.on((e) => progress.update(e))
m.tap((channel, bytes) => { /* every pipe / redirection / capture */ })
const { status, denials } = await m.run(script)

The four pieces

1. Parser → AST for analysis (src/parser)

parse(source) is a scannerless recursive-descent parser. Bash's lexing depends on context (command position, [[ ]], $(( )), ${ }, here-docs, case patterns), so the parser scans the source directly with context-specific word scanners instead of using a separate tokenizer.

  • Every node has an id and an exact span (offsets into the source). Trace events carry node ids, so a UI can highlight the running command, and analysis findings point at exact text.
  • Words keep their quoting structure. Parts are Lit, SglQuoted, DblQuoted, Escaped, ParamExp (with a typed op), CmdSubst, ArithExp and ProcSubst. Expansion, globbing and the analyzer can therefore tell quoted text from unquoted text.
  • Arithmetic and [[ ]] are parsed into expression trees. Redirections, here-docs (several per line, <<-, quoted delimiters) and assignments (arrays, +=, subscripts, arguments of declaration builtins) are structured too.
  • Trivial wrappers are collapsed. A Pipeline node exists only for two or more stages, and an AndOr only for two or more items.
  • ParseError has line and column, and an incomplete flag ("needs more input").

2. Execution against a sandbox policy (src/vm, src/policy)

The interpreter runs everything a shell normally does in-process: expansions in bash order (brace, tilde, parameter/command/arithmetic, splitting, globbing including extglob), all compound commands, functions with dynamic scoping, subshells (as copies of the state), about 50 builtins, set -euo pipefail, EXIT/ERR/RETURN traps, background jobs, wait and kill. External commands are real child processes.

I/O is modelled on POSIX open file descriptions. Each shell "process" has an fd table of reference-counted open files: pipes, host files, captures, here-docs. These give the semantics scripts rely on:

  • EOF arrives when the last writer closes.
  • SIGPIPE: yes | head -1 ends yes, and while true; do echo; done | head ends the subshell with status 141.
  • { read x; cat; } < f shares the read position between a builtin and a child process.
  • A command that never reads stdin doesn't swallow the input of a while read loop.

Every pipe stage runs concurrently. Child stdio is pumped through the VM's channels when something is tracing, and plain files are passed straight through otherwise.

Before any command runs, its fully expanded argv goes through these steps:

  1. Its behavior definition predicts effects: read, write, delete, network, exec of subcommands, chdir.
  2. The effects of its redirections are added.
  3. The policy checks every effect. Concrete paths are resolved through symlinks, so ln -s /etc x; touch x/y is caught.
  4. Hooks may allow, deny, abort or simulate.

Redirections are checked before files are opened, so a denied > /etc/hosts truncates nothing. A denied command prints mash: cmd: denied by policy: … and returns 126, or aborts the run if abortOnDeny is set.

Nested commands run inside the VM. Without this, these would disappear into an opaque child process:

  • bash -c '…', sh script.sh and executables with a bash/sh shebang (inlineScripts).
  • xargs, and find's -exec/-delete actions (emulate). mash runs find … -print0 itself, or reads xargs' input itself, then runs each resulting command through the VM.

Either way, every nested command is traced and checked individually with its concrete arguments.

Policy mirrors the harness vocabulary (read-only | workspace-write | danger-full-access, workspaceRoot, additionalWritableRoots, temp areas). It adds restrictions an OS sandbox can't express: network: 'deny' or a host allow-list (network: { allow: ['github.com', '*.githubusercontent.com'] }), deniedCommands, readDeniedRoots, read policy coverage for credential stores (readDenyCredentials: true denies reading ~/.ssh, ~/.aws, ~/.config/gh, keychains and other token files), missingDeletes: 'allow' (rm -f of a missing path is a no-op, not a violation), and unknownCommands / denyUnknown for commands whose effects cannot be shown safe. Static reasons for nested code name the inner command: would write /etc/x (via `touch /etc/x` (/w/deploy.sh:3)).

3. Behavior definitions (src/behaviors)

A behavior is a pure function from an invocation to the command's effects. The invocation is the argv (as abstract values), the cwd, the environment and the kind of stdin.

const touch: Behavior = {
  names: ['touch'],
  analyze(inv, h) {
    const p = h.parseArgs(inv.argv.slice(1), { short: 'acmfh', shortWithArg: 'rtd' })
    return { effects: p.operands.map((f) => ({ kind: 'write', path: h.resolve(f) })), readsStdin: false }
  },
}

The same definition serves runtime enforcement (concrete argv) and static analysis (argv with unknown parts). Unknown arguments flow through as typed holes. Definitions can also:

  • recurse into subcommands with h.subcommand (xargs, find -exec, env, timeout, sudo, command, …),
  • analyze nested scripts with h.script (bash -c, script files),
  • declare their stdout type (mktemp → a path under $TMPDIR, basename → a filename, pwd → the cwd), which feeds type inference for x=$(cmd),
  • declare whether they read stdin, which the VM uses for stdin plumbing.

There are about 440 bundled command names in defs/core.ts, defs/devtools.ts, defs/tools.ts and defs/macos.ts, chosen by measuring a corpus of real agent commands. They cover coreutils, grep/sed/awk/find/xargs, archives, curl/wget/ssh, git (with its subcommands), npm/pnpm/yarn, interpreters, build tools, system package managers, sqlite3, typst, ffmpeg, yt-dlp, PDF and image tools, openssl, linters, and macOS tools (defaults, plutil, launchctl, codesign, …). Most are declarative tables (define({ names, spec, operands: 'read*', flags: { o: 'write' } }), see docs/behaviors.md). A command without a definition yields an unknown effect: it is allowed by default (the OS sandbox still confines it), and denied with denyUnknown.

4. Tracing and hooks (src/trace)

machine.on(listener) receives these events in execution order:

| Event | When | |---|---| | run:start / run:end | Whole run | | step | Before every command node (simple or compound), with node id, span and line; like bash's DEBUG trap, but with exact spans | | command:start / command:spawn / command:end | Expanded argv, kind (builtin / function / external), resolved path, cwd, redirects, OS pid, status, duration | | command:denied | Policy or hook denial, with the findings | | subshell:start / subshell:end | Virtual pid tree; reason subshell, pipeline, cmdsubst, procsubst, background or script | | loop:iteration, branch | Loop iteration with the loop variable's value; which if/case arm was taken | | function:enter / function:exit, assign | Function calls and variable assignments | | channel:open, data | Each pipe, redirection, capture or here-doc, with a label such as `grep foo | wc -l` or > out.txt, and its bytes |

  • machine.tap(fn) intercepts the bytes on every channel: pipes, redirections, command-substitution captures and stdio.
  • hooks.beforeCommand(ctx) sees the expanded argv, predicted effects and policy findings. It returns allow, deny, abort or simulate (fake output without running the command; this is how --dry-run works).
  • ProgressTracker folds the static plan and live events into "3/7 command sites, loop #2, running npm test".

Pretty-printer (src/printer)

format(src, options) returns the snippet re-laid out as readable bash that parses to the same AST and runs the same. Words are printed exactly as written; only line breaks, \ continuations and indentation change.

  • Long && chains and pipelines go one item per line.
  • Two or more prefix assignments get their own lines.
  • Short loops stay on one line.
  • Here-docs, comments, and bash's line-by-line error and alias semantics are handled.

formatHtml(src, options) renders the same layout as syntax-highlighted HTML. It shortens over-long strings to fit the width, with a grey … that expands on click. Long here-docs and multi-line strings collapse to "⋯ N more lines".

summarize(src, { width }) gives a one-line summary that keeps the snippet's shape (commands, operators, redirections), e.g. cd …/harness-port && CI=true bash … -j 8 … > …th.log 2>&1 && echo done. Every … carries what it hides as a tooltip.

format also returns where every command ended up in the output. With ranges: true, formatHtml and summarize tag every piece of source text, and every … that hides some, with data-src="start-end" (offsets into the source), so a UI can map a command's span (from a command:start event) onto the pretty or summarized view and highlight the running command. The CLI is mash fmt; the design is in docs/pretty-printer.md.

$ mash fmt -c 'FOO=bam BAR=baz make -j8 all && cd packages/core && pnpm install --frozen-lockfile && pnpm build 2>&1 | tail -20'
FOO=bam \
BAR=baz \
make -j8 all &&
  cd packages/core &&
  pnpm install --frozen-lockfile &&
  pnpm build 2>&1 | tail -20

Static analysis (src/analysis)

machine.analyze(src) performs abstract interpretation over the AST. The abstract environment tracks variables, the cwd, positional parameters and function definitions. Words are expanded into abstract values: sets of alternatives made of literal text and typed holes.

| Hole type | Example source | Guarantee | |---|---|---| | int | $((…)), $?, ${#x} | Never contains / | | filename | Glob matches (*.txt), $(basename …) | A single path component, never . or .. | | path | $(mktemp -d), $(pwd), find results | Optionally known to be under a directory | | string | Anything else | None |

The types make definite verdicts possible despite unknowns:

  • rm /etc/*.conf is definitely inside /etc, because a glob match can't contain /...
  • rm -rf "$(mktemp -d)" is definitely in the temp area.
  • rm -rf "/etc/$x" is not definite: $x could be ../home/…, so the runtime check decides.

The analyzer inlines function bodies at their call sites. It follows bash -c, script files, eval of known strings, find -exec, xargs and env/timeout-style wrappers. Shell builtins such as cd, read, declare, set and shift update the abstract state.

Each command site gets a reach:

  • must: runs unless the script terminates earlier.
  • happy: runs if every earlier command succeeds (cd x && cmd).
  • may: runs only under a condition. This covers if/case arms, anything after || or after a predicate (test -f x && …, grep -q … && …), loop bodies that may not run, and uncalled functions.

Some effects are only possible (maybe): a build tool writing into its directory, find -delete on a tree that may contain no matches, xargs with empty input. A possible effect never produces a definite denial, statically or at runtime; it is reported as unknown.

The cd builtin only changes the abstract cwd if it can succeed: the directory exists, or the snippet itself created it. a && b continues in the state a left.

The verdict is:

  • reject when a definite violation sits on a must or happy path (configurable with rejectOn),
  • check-at-runtime when violations are only possible,
  • allow otherwise.

Fidelity

  • Differential tests (tests/differential.test.ts, and 1643 more in tests/differential-extra.test.ts) run each snippet under /bin/bash and under mash in identical fixture directories and compare stdout and exit status. Currently 1780+ cases match. 5 known differences are marked it.fails: function pretty-printing in declare -f/type, GLOBIGNORE, and tilde expansion after = in plain arguments. macOS ships bash 3.2, so bash 4/5 features (associative arrays, ${x^^}, mapfile, |&, &>>, {fd}>, ;&, ${x@Q}, negative indices, globstar) are covered by expectation tests in tests/runtime.test.ts.
  • Behavior targets bash 5. Non-interactive behavior only: no job control, no readline, no history.

Limitations (prototype)

  • Not implemented: coproc, GLOBIGNORE, function pretty-printing. Aliases are expanded only when expand_aliases is on, by substituting into the command's text.
  • Extglob is partial: @(…), *(…), +(…) and ?(…) work in globs and patterns, but !(…) is only exact at the end of a pattern.
  • Traps: EXIT, ERR and RETURN traps run. Signal traps are recorded but never fire.
  • Process substitution feeding an external command uses /dev/fd/N with an extra stdio pipe. That works on macOS. On Linux, Node's stdio pipes are sockets, and /dev/fd/N can't open a socket, so a FIFO fallback is still needed. cmd < <(…) into builtins and loops works everywhere.
  • Locale: pathname-expansion results are sorted in C-locale (code unit) order.
  • Children never get a TTY. Interactive programs see pipes.
  • Behaviors only cover what they model. The static and runtime checks are only as complete as the behavior definitions; arbitrary code (python script.py, make) is reported as unknown. mash is designed to run on top of OS confinement, not instead of it (see docs/deepsea-integration.md).
  • Performance: in-process loops cost about 0.1 ms per command and yield to the event loop every 64 steps, so a runaway while :; do :; done can't freeze the host.

Playground

playground/ is a browser page for trying the static analysis live: pick an example or type a snippet, change the policy, and see the verdict, each command's predicted effects, the inferred types and the AST update as you type. Nothing is executed. It runs the compiled dist/ in the browser against a small virtual filesystem (playground/shims/).

pnpm build && node playground/serve.mjs     # → http://localhost:8377/playground/

Documentation

Layout

src/parser/      ast.ts (node types), parser.ts (parse, ParseError, arithText)
src/vm/          interp.ts (interpreter), expand.ts (word expansion), io.ts (fds, pipes, channels),
                 builtins.ts, external.ts (child processes), arith.ts, pattern.ts (globs), test.ts ([[ ]], test)
src/analysis/    value.ts (abstract values, hole types), analyze.ts (abstract interpreter)
src/behaviors/   types.ts, registry.ts (parseArgs over abstract values), dsl.ts (define: table definitions), defs/
src/policy/      policy.ts (modes, roots, abstract path shapes), effects.ts
src/trace/       events.ts (events + hooks), progress.ts
src/printer/     doc.ts (layout IR + renderer), print.ts (format), highlight.ts, html.ts (formatHtml), summary.ts (summarize)
src/integrations/deepsea.ts   adapter for the DeepSea harness
bin/mash.ts      CLI
scripts/         compare.ts (bash vs mash), explain.ts (analysis dump), flip-fixed.mjs (it.fails upkeep)
playground/      browser playground for live static analysis (index.html, app.js, style.css, examples.js, shims/)
docs/            see Documentation above