- Added an in-process `column` with util-linux 2.41 options (-t, -N, -C, -R, -H, -O, -T, -W, -E, -m, -e, -J, trees), so `column -t -N …` no longer falls through to macOS's BSD column, which rejected them. - Table fitting shrinks -T/-W/-E columns widest first to exactly the output width; util-linux's statistical ranking can trim a few cells more. - Added OpenFile::window_size and moved ls and the progress bar onto it instead of their own TIOCGWINSZ calls.
44 KiB
bash
Execute a shell command in the session workspace, with optional PTY, background-job handling, or supervised service mode.
Source
- Entry:
packages/coding-agent/src/tools/bash.ts - Model-facing prompt:
packages/coding-agent/src/prompts/tools/bash.md - Key collaborators:
packages/coding-agent/src/tools/bash-interactive.ts— PTY/TUI execution path.packages/coding-agent/src/tools/bash-interceptor.ts— blocks tool-better shell patterns.packages/coding-agent/src/internal-urls/url-filesystem.ts— router-backed shell filesystem forscheme://paths.packages/coding-agent/src/tools/bash-pty-selection.ts—canUseInteractiveBashPty()decides whether a call may use the local PTY overlay.packages/coding-agent/src/tools/gh-cache-invalidation.ts— dropsgithub-cacherows for mutatinggh issue/gh prsubcommands.packages/coding-agent/src/tools/bash-worktree-rewrite.ts— optionalgit worktree addclone rewrite.packages/coding-agent/src/launch/services.ts— named-service validation and launch-broker calls.packages/coding-agent/src/exec/bash-executor.ts— non-PTY shell execution.packages/tui/src/tools/streaming-output.ts— streaming buffer, truncation, artifact spill.packages/coding-agent/src/tools/tool-timeouts.ts— timeout clamp bounds.packages/coding-agent/src/exec/settings.ts— default interceptor rules.docs/bash-tool-runtime.md— deeper executor/runtime notes; use as the companion doc for shell-session internals.
Inputs
| Field | Type | Required | Description |
|---|---|---|---|
command |
string |
Yes | Shell command text to execute. A leading cd <path> && ... is rewritten into cwd only when cwd was omitted. |
timeout |
number |
No | Timeout in seconds. Default 300. 0 disables the deadline. Nonzero values (including the default) are capped by a positive tools.maxTimeout, then clamped to 1..3600. |
cwd |
string |
No | Working directory, resolved against session.cwd via resolveToCwd, or a registered internal URL directory for embedded-shell execution. Must exist and be a directory. |
pty |
boolean |
No | Request PTY mode. Default false for finite commands, true for named services. Foreground PTY requires a UI and PI_NO_PTY !== "1"; named services forward this setting to the broker. |
async |
boolean |
No | Background execution request. Present only when async.enabled is true for the session. Returns immediately with a job id instead of waiting; it does not change the effective deadline, including a disabled deadline from timeout: 0. |
notify |
string |
No | Rust-syntax regex (as grep). Each output line it matches reaches the session as an async-notify follow-up while the command runs. Without name it starts the command as a background job, as async: true does (needs async.enabled); with name the launch broker matches the service's output. Blank is unset. |
name |
string |
No | Project-unique supervised service name: 1–48 letters, numbers, dots, underscores, or hyphens, starting with a letter or number. Present only when launch.enabled and Bash is active. Blank names select finite-command mode. A live name restarts using the new spec. Incompatible with async: true or any supplied timeout. |
ready |
{ log?: string; port?: number; host?: string; timeout?: number } |
No | Service readiness requires a nonblank log regex and/or integer TCP port 1..65535; all supplied conditions must pass. Host defaults to 127.0.0.1, timeout to 30 seconds (clamped to 0.05..3600). Without name, a nonempty spec is ignored with a notice. |
There is no env input. Every command and named service also gets PI_SESSION_ID, PI_SESSION_FILE (the transcript's absolute path, empty when the session is not persisted), and PI_TOOL_CALL_ID (the id of the running bash call), read when the call starts; see environment variables. Named services otherwise inherit the configured shell environment; put command-specific assignments in command.
Without name, pty, or a client terminal, commands run in the embedded bash engine (bash 5.3 semantics), even when shellPath points to PowerShell or another external shell. shellPath selects the external shell for named services, supported terminal routes, and interactive ! commands; a bash path may still supply environment and rc snapshots to the embedded session. To use PowerShell syntax in a plain tool call, invoke pwsh -Command '...' explicitly, quoting so the embedded shell preserves PowerShell's $ variables.
Named service example:
{
"command": "python3 -m http.server 8765",
"name": "web",
"ready": { "port": 8765 }
}
Builtins
The embedded shell resolves a command name in order: the engine's own bash 5.3 builtins, then pi's shell tools, then pi's in-process utilities, then mounted tool commands, then PATH. A name containing a slash is never a builtin, and type/command -v report the in-process utilities as shell builtins.
- Engine builtins are bash 5.3's own:
alias,cd,command,coproc,declare/typeset,echo,eval,exec,export,fc,getopts,history,jobs,kill,let,local,mapfile/readarray,printf,pwd,read,readonly,set,shopt,source,test,times,trap,type,ulimit,umask,unset,wait, and the rest of the builtin table.suspendis withheld (suspend: not available in this shell, status1);execnever replaces pi's process, and its fd-only form (exec 3>&1,exec >log) changes only the shell's own descriptors.complete,compopt, andbindare accepted no-ops. - pi's shell tools run their operands in subshells:
timeout,nohup,git(whenPI_SMART_GIT/PI_GIT_GUARDlayers are on), and the utilities that run command lines (direnv exec,entr,env,flock,ifne,watchexec,xargs,find -exec). - pi's in-process utilities replace the matching external binaries:
ast-grep/sg,awk,b2sum,base32,base64,basename,cat,chmod,cksum,cmp,column,combine,comm,cp,cut,date,dd,df,diff,dirname,du,errno,fd,file,find,fold,fswatch,grep,head,hostname,id,ifne,isutf8,jq,ln,ls,md5,md5sum,mkdir,mktemp,mv,nl,nproc,od,open,paste,printenv,readlink,realpath,rg,rm,rmdir,rsync,say,sd,sed,seq,sha1sum,sha224sum,sha256sum,sha384sum,sha512sum,shasum,sort,sponge,stat,strings,tac,tail,tar,tee,touch,tr,truncate,ts,uname,uniq,uptime,wc,which,whoami,xargs,xdg-open,yes.chmod,errno, andidare Unix-only;tarneeds a Unix or Windows target;ast-grep,fd,find,grep,rgare awaited natively so cancellation stops the work. - pi's process builtins are
ps,top,sleep,pgrep,pkill,pidwait, andlsof(Linux, macOS, Windows); they buffer output and are never gated off.
For a checked literal edit, use sd -F --expect 3 -U 2 'oldName' 'newName' file.ts. --expect checks the number of matches per input, before any -n limit; a count mismatch exits nonzero without writing any file. -U 2 prints the applied unified diff with two lines of context. No change prints nothing; binary changes print a filename notice. -U requires file operands and cannot be combined with --preview.
Gates are read once, from the environment the session starts with; a set, nonempty value other than 0/false turns one on.
| Variable | Effect |
|---|---|
PI_DISABLE_UUTILS_BUILTINS |
No utility is a builtin; every utility name resolves to the PATH binary. |
PI_DISABLE_UUTILS_DESTRUCTIVE |
rm, mv, cp, ln, dd, rsync, and tar resolve to the system's. |
PI_DISABLE_RM_BUILTIN |
rm resolves to the system's. |
PI_DISABLE_MV_BUILTIN |
mv resolves to the system's. |
A path (/usr/bin/jq) always runs the system program for that one command, even with the utilities enabled. The bundled jq behaves like jq 1.8.2; its divergence list is in bash-tool-runtime.md.
Tool commands
A tool mounted as a session command (isMountableAsToolCommand) is a command of the embedded shell, resolved after the engine builtins, pi's shell tools, and the in-process utilities, and before PATH; a name the shell reserves is never mounted as a command. exec/tool-command-host.ts installs the session's command names for a run, and runToolCli() in exec/tool-cli.ts parses and runs each invocation from the tool's JSON schema:
- required top-level scalar/enum fields are positionals in schema order;
- every field also takes
--flag value(underscores become dashes; a nested field is--a.b); - a boolean field is
--flagor--no-flag; - an array field repeats its flag;
-j/--json <JSON>merges a raw object;@FILEand-merge a JSON object, or bind their text to the next positional (-reads stdin);--helpprints the schema-derived usage.
A usage error exits 2; the tool's own failure exits 1. Each invocation is recorded on the result as details.toolCommands (partial and final results), in invocation order. A line naming a tool command stays on the embedded engine even when a client terminal is available, and pty: true refuses it (<name> is a session tool command and cannot run in a PTY; run it without \pty`.). A line made only of tool commands — joined by ;, &&, ||, |, |&, or newlines, with no redirection, expansion, or substitution — passes the outer bash approval gate; each tool is approved on its own tier and tools.approval.policy when it runs. Image blocks a tool returns reach the shell as kitty graphics on stdout, and the output pipeline decodes terminal graphics from any command into attached images plusImage saved: ` link lines.
Outputs
The tool returns a text content block plus optional details and image blocks decoded from terminal graphics.
- Success, foreground:
content[0].text: command output, or(no output)when the command produced nothing.details.timeoutSeconds: effective positive timeout after global/per-tool clamping, ordetails.timeoutDisabled: truewhentimeout: 0.details.requestedTimeoutSeconds: present when the requested/default timeout differs from the effective timeout, including0when the deadline is disabled.details.wallTimeMs: elapsed wall-clock milliseconds for completed local/client-terminal runs.details.terminalId: present in streaming updates when execution is routed through a client terminal bridge; not retained in the completed result.details.exitCode: present when the command completed with a non-zero exit code.details.timedOut: true: present on local, PTY, and client-terminal timeout results.details.meta.truncation: present when output was truncated in memory; includesartifactIdwhen full output spilled to an artifact.details.meta.minimized: present when the shell minimizer's text replaced the output;{ filter, inputBytes, outputBytes, artifactId }names the native filter (chainfor a minimized&&/;chain), the raw and minimized byte counts, and thebash-originalartifact holding the raw capture.- non-zero exits and timeouts return a tool result marked
isError; definite non-zero output ends withCommand exited with code <n>.
- Success, background start (
async: trueor auto-background):content[0].text: optional preview tail and notices, followed byBackgrounded as job <id> (killed once it has run <n>s in total; …)— or(no deadline)undertimeout: 0— and the no-polling instruction (formatBackgroundNoticeinpackages/tui/src/tools/bash.ts), so the model sees the job's deadline before it waits on the result. The deadline counts from job start, so an auto-backgrounded command has already spent its foreground wait.details.async:{ state: "running", jobId, type: "bash" }.read proc://lists owned jobs and project services;read proc://<id>inspects status/output without consuming result delivery;write proc://<id>/killwith emptycontentcancels the job.
- Success, named service (
name): executescommandthrough the user's shell under the launch broker, returning readiness, exit, or readiness timeout with state and log tail. A live name is stopped and restarted with the new spec; exit notifications still auto-deliver.read proc://<name>inspects status/logs;write proc://<name>sends stdin (appends Enter unless content already ends with newline, including empty content);write proc://<name>/killstops it.write proc://<name>/modeacceptspersist,session, ordetached. - Background progress / completion:
- delivered through
onUpdate/ async job manager, not the initial return. - running updates contain tail text and
details.async.state: "running"only after the job is considered backgrounded. - completion/failure updates carry final text and
details.async.state: "completed" | "failed". A non-zero exit or timeout is recorded as a failed background job. - the
async-resultfollow-up names the job by its command on one line (line breaks as\n, the middle elided past 400 characters):Background job <id> (<command>) has completed., or── Job <id> (<command>) ──in a batch.
- delivered through
- Background output notices (
notify):- while a background job or a named service runs, each output line (stdout and stderr, as merged for the model) matching the
notifyregex is delivered as anasync-notifyfollow-up; lines that match within 200 ms of the first go out together. The notice names a job by its command and a service by its name, and says whether it is still running. - delivery is the result's: a new turn when the session is idle, an aside between requests otherwise, and the end of a blocked
wait(which returnsWait interrupted by message., the notice following it). - a job's matches belong to the transcript the job started in. A service's belong to the session that owns it, like its exit notification: the launch broker matches the output and reports only while that session's omp process is connected, and a resumed session receives them again. Output printed while the owner is away is not reported.
- when a service exits, its matches not sent yet, an unterminated last line included, go out at once, ahead of its exit notification, which carries no output. A job's are dropped, as its result carries the output; so are those of a stopped service or a cancelled job.
- the notice message's
details.reports[]:{ id, type: "bash" | "service", pattern, lines, omitted, running, stopped }; batches of one source queued between two injections merge into one entry.
- while a background job or a named service runs, each output line (stdout and stderr, as merged for the model) matching the
- Failure:
- cancellation, missing exit status, validation failures, and intercepted commands throw
ToolError/ToolAbortError; timeouts return an error result.
- cancellation, missing exit status, validation failures, and intercepted commands throw
Stdout and stderr are merged before the model sees them. Definite non-zero exit codes are appended to the returned error result text as Command exited with code <n>.
Command policy and dedicated-tool routing
Two independent settings can prevent a Bash subprocess from starting. They serve different purposes and run at different points in the tool-call lifecycle.
| Setting | Purpose | Rule syntax | Result when matched |
|---|---|---|---|
bash.patterns |
Command-specific execution policy | Literal text with * wildcards |
Allows the call, requests human approval, or denies it. |
bashInterceptor.patterns |
Prefer a dedicated tool over Bash | JavaScript regular expression, optional flags, tool name, and message | Returns a Bash tool error telling the model to call the named dedicated tool instead. |
bash.patterns: permission policy
bash.patterns is for commands that must be allowed, confirmed by a person, or refused regardless of whether another tool could perform the work. Rules are ordered; the first matching rule wins. Each rule has a match glob and an approval value of allow, prompt, or deny. Whitespace runs in both the glob and the command collapse to a single space before matching, so a newline in a glob matches any whitespace ("*\n*" behaves like "* *").
bash:
patterns:
- match: "git *"
approval: allow
- match: "curl *"
approval: prompt
- match: "rm -rf *"
approval: deny
denystops the call beforeBashTool.execute()runs, including inyolomode.promptdisplays an approval request. Only an accepted request proceeds toBashTool.execute().- By default,
allowcan lower the approval tier for a simple command, but cannot approve a compound command. For example,match: "git *"does not approvegit status && rm -rf build. - With
bash.allowCompoundCommands: true(defaultfalse) and a configured POSIX shell, literal&&chains are evaluated per command. Every segment needs anallowrule to allow the chain; an unmatched segment retains normal exec-tier approval. Segment rules remain first-match-wins, any segment or chain-wide deny wins, and prompts are retained. Expansions, other shell operators, and critical command patterns do not gain an allow bypass. denyandpromptcheck the complete command and each shell command segment (first matching restriction per segment, withdenytaking precedence overpromptacross segments). A rule such asmatch: "rm -rf *"therefore catchescd /tmp && rm -rf buildandcurl http://example.com; rm -rf buildeven whencurl *matches an earlierpromptrule. Operatordenyrules inSettings.grantAuthority()also outrank project-layer rules.- Both
bash.patternsandbashInterceptor.patternssupport path-scoped entries ({ path, patterns: [...] }), allowing repository-specific command rules to live directly in~/.omp/agent/config.yml. - Leading
KEY=VALUEassignments onallowrules are stripped only when the variable name exactly matches an entry inbash.allowedEnvVarsor the rule's optionalenv: [...]list (no wildcards).denyandpromptrules check segments with and without leading bareKEY=VALUEassignments, soFOO=1 rm -rf buildstill hitsmatch: "rm -rf *". Wrapper commands such asenv FOO=1 rm -rf buildare not unwrapped. - Project (
.omp/config.yml) and--configoverlaybash.patternslists are prepended ahead of the globalconfig.ymllist, so repository-local rules extend your global policy without replacing it.
Use this setting for safety and user control. It remains useful for commands with no appropriate replacement tool, such as destructive removal, network access, deployment scripts, or project-specific scripts.
bashInterceptor.patterns: dedicated-tool routing
bashInterceptor is an opt-in routing layer (bashInterceptor.enabled defaults to false). It is for commands that are technically valid Bash but are better expressed through an available dedicated tool. Each pattern is a regular expression and includes the name of that replacement tool and the explanation shown to the model.
bashInterceptor:
enabled: true
patterns:
- pattern: '^\s*(cat|head|tail)\s+'
tool: read
message: "Use the read tool instead; it handles binary files and provides better context."
- pattern: '^\s*(grep|rg)\s+'
tool: grep
message: "Use the grep tool instead; it respects .gitignore and returns structured results."
An interceptor rule only applies when its tool is available in the current session. If read is disabled, a cat rule targeting read does not block the Bash call. This makes the interceptor a best-effort capability preference rather than an execution-security boundary.
The built-in default rules route common operations such as cat to read, rg to grep, in-place sed to edit, shell redirection to write, and unmanaged services/watchers to named bash service mode. See DEFAULT_BASH_INTERCEPTOR_RULES in packages/coding-agent/src/exec/settings.ts for the complete list. Project and --config overlay bashInterceptor.patterns entries are prepended ahead of the global list (or DEFAULT_BASH_INTERCEPTOR_RULES when the global config leaves bashInterceptor.patterns unset). A global list of only path-scoped entries keeps the built-in rules after its own, so prepending onto it keeps them too.
For compatibility with existing custom regexes, the interceptor always checks the complete original command first. It then checks raw, flat command fragments separated by unquoted and unescaped &&, ||, ;, |, &, or newlines. It also checks fragments after leading environment assignments are removed:
git add file && git commit -m "message"
GIT_AUTHOR_NAME=Dev git commit -m "message"
An anchored rule such as ^\s*git\s+commit\b can therefore match the git commit command in both examples. A stage that consumes another command's stdout through an unquoted | or |& (for example grep x in printf 'x\n' | grep x) is not treated as an interception candidate: it reads piped stdin, which the path-based dedicated tools cannot supply, so only a standalone or first-stage command is matched. Blank and comment-only continuation lines after the pipe preserve that context. Quoted, escaped, and commented text is not treated as a command. Heredocs, parameter expansion, command substitution, backticks, grouping, and malformed quoting retain only the complete-command check; the interceptor deliberately does not attempt to become a full shell parser.
Interaction and selection guide
The approval policy is resolved before execution. A matching bash.patterns deny never reaches the interceptor. A matching prompt reaches the interceptor only after the user accepts the approval request. If an accepted call then matches an interceptor rule, the Bash call still does not run; the model receives the routing error and should invoke the dedicated tool.
Avoid configuring the same operation in both places unless that two-step behavior is intended. For example, a prompt rule for cat * plus an enabled cat-to-read interceptor first asks the user to approve Bash, then rejects Bash and asks the model to use read.
Choose the setting by the desired outcome:
- Use
bash.patternswhen the question is whether the command may execute. - Use
bashInterceptor.patternswhen the question is which tool should perform the operation.
Flow
BashTool.execute()inpackages/coding-agent/src/tools/bash.tsreadscommand. Anameselects supervised service mode (through the user's shell and launch broker); normal Bash execution defaultstimeoutto300.- If
cwdis absent, it rewrites a leadingcd <path> && ...into the structuredcwdfield and strips that prefix fromcommand. - Without
name, a nonblanknotifycounts asasync: true. If either is requested whileasync.enabledis off, it throwsToolErrorbefore any execution; so does anotifyregex that does not compile, with or withoutname. - If
bashInterceptor.enabledis on,checkBashInterception()runs against both the original command and thecd-stripped command. For each form, configured regexes still check the complete input first, then each flat command separated by unquoted/unescaped&&,||,;,|,|&,&, or newlines (excluding stages that consume piped stdin from|or|&, including across blank/comment continuations), followed by versions of those fragments without leadingNAME=valueassignments. A matching enabled rule throws before execution. - When
worktree.cloneis enabled, recognized literalgit worktree addcommands are rewritten to the clone-backed worktree helper. GitHub cache invalidation then runs. A per-runInternalUrlFilesystemis injected into the native shell soscheme://paths resolve at operation time. - A host
cwdresolves againstsession.cwdandfs.stat()verifies it is a directory; a URLcwdis checked through the URL filesystem and handed to the shell as-is (service and PTY modes refuse it). - Named services dispatch before finite-command timeout handling, default PTY to
true, and useready.timeoutonly for readiness. Anotifyregex travels in the service's launch spec: the broker feeds the service's output to the sameOutputNotifiera job uses and sends each batch to the owner's connection as adaemon-notifyevent (packages/coding-agent/src/launch/broker.ts), whichservices.tsqueues on the owning session. For finite commands,timeout: 0disables the deadline; otherwiseclampTimeout("bash", requestedTimeoutSec, tools.maxTimeout)applies a positive global ceiling, thenTOOL_TIMEOUTS.bash(min: 1,max: 3600). Clamping adds a notice line. - Execution path splits:
async: trueornotify->#startManagedBashJob()registers a session async job and returns immediately. Withnotify, the job feeds its output to anOutputNotifier(packages/coding-agent/src/async/notify.ts), which sends matching lines through the session'sopenAsyncNotifychannel.- Non-PTY with
bash.autoBackground.enabled, an async job manager below its running-job cap, and no client-terminal bridge available (the bridge wins when both apply) -> starts a managed job, waits up tomin(thresholdMs, max(0, timeoutMs - 1000))when a deadline exists, and either returns the completed result or converts the run into a background job. - Non-PTY client-terminal bridge, when the session advertises terminal capability and
ptyis false -> creates a remote terminal, streams/polls current output, and releases the terminal after completion. - Otherwise runs foreground execution.
- Foreground non-PTY without client terminal calls
executeBash()frompackages/coding-agent/src/exec/bash-executor.ts; that path performs direnv/devenv preflight itself. - Foreground PTY and client-terminal paths run the same direnv preflight in
BashToolbefore dispatch. Withbash.direnv: "auto"(the default), an allowed.envrcmay merge environment changes into the command;"off"disables this.bash.direnvLoadTimeoutMsdefaults to30_000, and a positive command timeout also bounds the preflight. - Local non-PTY and PTY paths allocate an output artifact first when
session.allocateOutputArtifactis available. The artifact path/id are passed into the sink so large output can spill to disk. executeBash()loads shell settings, optional shell snapshot, and shell minimizer settings, then runs via a persistent nativeShellsession or one-shotexecuteShell().docs/bash-tool-runtime.mdcovers that path in detail.runInteractiveBashPty()creates aPtySession, overlays an xterm-backed console UI, forwards user key input into the PTY, captures output throughOutputSink, and kills the PTY on dismiss/dispose.- Client-terminal bridge mode calls
session.getClientBridge().createTerminal(...), emitsterminalIdupdates, polls output until exit/timeout/abort, maps signal exits to137, and releases the handle infinally. - On completion,
#buildCompletedResult()formats(no output)when needed, attaches truncation metadata from the output summary, appends wall-time/timeout/exit notices, and re-checks unfinished status before returning. - Local, PTY, and client-terminal timeout outcomes become
isErrorresults withdetails.timedOut. Client-terminal allocation/polling races the deadline; on timeout, late allocations are cleaned up or the live terminal is killed before a bounded final output read. Cancellation and missing exit status still throw.
Modes / Variants
- Foreground non-PTY local
- Default path when no client terminal bridge is available.
- Uses
executeBash(). - Streams tail-only updates through
streamTailUpdates()andTailBuffer(DEFAULT_MAX_BYTES).
- Foreground non-PTY client terminal
- Used when
session.getClientBridge()?.capabilities.terminalis true,createTerminalexists, andptyis false. - Streams current terminal output via polling updates with
details.terminalId. - Enforces the same timeout and abort behavior, then releases the terminal handle.
- Used when
- Foreground PTY
- Requires
pty: true, UI context, andPI_NO_PTY !== "1". - Uses
runInteractiveBashPty()and aPtySessionoverlay. - Supports interactive input;
Esckills the session from the overlay. - While the program waits on keys, the run shows as blocked on the user (title
!, OSC 7501blocked), and each new wait sends aConsole waiting for inputterminal notification unlesspty.notifyisoffor keys were sent to the console in the last 10s.PtySession.awaitsInput()decides: terminal echo off (password prompts, full-screen programs) on every Unix; on Linux, also a foreground process blocked inreadon the terminal (/proc/<pid>/syscall). Where it cannot tell (macOS and Windows line prompts, an uninspectable setuid process on Linux), 2s of silent output with the cursor after text counts as a prompt.
- Requires
- Explicit background job
- Requires
async: trueornotify, andasync.enabled. - Registers a job with
session.asyncJobManagerand returns{ state: "running", jobId }immediately.timeout: 0leaves the job without a tool-imposed deadline.
- Requires
- Auto-backgrounded non-PTY job
- Requires
bash.autoBackground.enabled, no PTY/client-terminal bridge, and an async job manager below its running-job cap. - Starts like a foreground managed job, then backgrounds it when it outlives the wait window; at capacity, Bash falls back to direct foreground execution.
- Requires
- Named supervised service
- Requires
launch.enabledand an active Bash tool;async: trueand any suppliedtimeoutare incompatible and ignored with a notice. notifyreports the service's matching output while it runs, up to 30 notices per start; starting it again re-arms it. A broker left running by an older omp starts the service and ignores the regex; the result then saysIgnored notify: …instead of confirming it.- Runs through the launch broker with project-unique
name, the configured shell environment plus the session identity, PTY defaulting totrue, and optional readiness conditions. Reusing a live name restarts it with the new spec. - Readiness waits for all supplied log/port conditions, service exit, or timeout.
ready.logis a Unicode multiline regex over accumulated output:^and$match line boundaries, including after earlier startup output, and matches may span output chunks.$also matches at the end of the output received so far, so an anchored pattern can match a line the service has not finished writing (this lets prompts without a trailing newline match). Inspect withread proc://<name>.
- Requires
- Intercepted command
- No subprocess created.
- Returns a
ToolErrorpointing the model at the dedicated tool or named service mode.
Side Effects
- Filesystem
- Validates
cwdwithfs.stat(). - May allocate and write artifact files for full local output (
bash) and minimizer-preserved raw output (bash-original). scheme://paths are served per operation byInternalUrlFilesystem: file-backed schemes redirect to their backing files (writes only for mutable file-written schemes such aslocal://, within the approved tier); rendered resources are read-only;realpath/readlinkprint the physical backing path of file-backed URLs.- A redirect to a handler-written URL (
: > proc://<id>/kill,echo hi > agent://<id>,cfg://,ssh://, …) opens a write-only handle; on close its bytes (UTF-8 only) reach the scheme's handler as one write, as with thewritetool. The handler's answer (or refusal reason) is appended to the result as a notice; a refusal also fails the close, so the command exits non-zero. Appends (>>) are refused except for theproc://,out://, andagent://channels that hold no content, since a handler write replaces its target. - A redirect to
out://(printf '…' > out://) opens a write-only handle; on close its text becomes a reply shown to the user as assistant prose after the call. Replies ride every progress frame and the result asdetails.replies, so the transcript draws each once, live and on rebuild. They are accepted only while the call waits on the command (a backgrounded job's writes fail), and a reply past 64 KiB fails withEFBIGand is dropped whole.
- Validates
- Subprocesses / native bindings / client terminal
- Non-PTY local execution uses native shell execution via
@oh-my-pi/pi-natives(Shell.run()orexecuteShell()). - PTY uses native
PtySession.start(). - Client-terminal mode delegates process execution to the connected client terminal capability.
- Named services run in the project-scoped launch broker and retain logs/status for
proc://.
- Non-PTY local execution uses native shell execution via
- Session state
- Reads session settings for async, auto-background, interceptor, direnv, global timeout cap, tool availability, and shell configuration.
- Registers jobs with
session.asyncJobManagerfor explicit/auto background runs. - Uses
session.getSessionId()to isolate shell reuse and async session keys. - Uses
session.allocateOutputArtifact()for spill files. - Invalidates
github-cacherows before execution when the command contains a mutatinggh issue/gh prsubcommand, so laterissue:///pr://reads see post-mutation state (invalidateGithubCacheForBashCommand).
- User-visible prompts / interactive UI
- PTY mode opens a TUI overlay titled
Consoleand forwards input to the PTY. - Background start messages note that the result is delivered automatically; use
waitonly when there is no other work.
- PTY mode opens a TUI overlay titled
- Background work / cancellation
- Async and auto-background jobs continue after the initial tool return, until completion, cancellation, or their deadline (unless
timeout: 0disabled it). - Cancellation aborts the native run; PTY overlay dismissal also kills the PTY.
- Async and auto-background jobs continue after the initial tool return, until completion, cancellation, or their deadline (unless
Limits & Caps
- Default timeout:
300s(TOOL_TIMEOUTS.bash.defaultinpackages/coding-agent/src/tools/tool-timeouts.ts). timeout: 0disables the command deadline.- Positive timeout clamp:
tools.maxTimeoutis an optional global ceiling (0means no global ceiling), followed by the Bash1..3600srange. - Auto-background default threshold:
60_000ms(cfgBashAutoBackgroundThresholdMs,bash.autoBackground.thresholdMs, inpackages/coding-agent/src/exec/settings.ts), further capped tomax(0, timeoutMs - 1000)when a deadline exists; a disabled deadline leaves the threshold uncapped. - Non-PTY tool execution passes its positive timeout to the native run, which owns deadline enforcement. A host-side watchdog waits
max(1_000, timeoutMs) + 5_000msfor native cancellation/output draining; if it wins, the result warns that output may be incomplete and quarantines the persistent session.timeout: 0arms neither deadline nor watchdog (packages/coding-agent/src/exec/bash-executor.ts). - Streaming-update tail cap:
50 * 1024bytes (DEFAULT_MAX_BYTESinpackages/tui/src/tools/streaming-output.ts). The local executor's result sink defaults to the same byte budget and preserves an initial head window (tools.artifactHeadBytes, default 20 KiB) alongside the rolling tail; set that setting to0for tail-only retention. - Result postprocessing uses
tools.artifactSpillThreshold(default 50 KiB) and head/tail windows (both default 20 KiB). The final Bash boundary also applies the spill threshold plus 2 KiB of notice slack.tools.outputMaxColumnsdefaults to a 768-byte per-line cap for streaming output. - Streaming callback throttle in
executeBash():50msbetweenonChunkcalls when streaming is enabled. notify(packages/coding-agent/src/async/notify.ts): a 200 ms batching window;50lines per notice, each cut to 400 characters, further matches only counted; blank lines never match. A job may send30notices in quick succession and regains one every 20 s, as its deadline ends it; a service, which has no deadline, gets30per start and regains none. The notice that spends the last one is markedstoppedand no later match is reported, while the process keeps running. Starting a service again re-arms it.- TUI collapsed preview:
10visual lines (DEFAULT_TERMINAL_PREVIEW_LINES) when rendered inline in the agent UI; this is a renderer cap, not a tool output cap.
Errors
- Input validation:
- async requested while disabled ->
ToolError("Async bash execution is disabled..."). - missing async job manager ->
ToolError("Background job manager unavailable for this session."). - invalid
notifyregex ->ToolError("Invalid notify regex: ..."); a session that cannot take the notices (advisors, SDK tool sessions withoutopenAsyncNotifyfor jobs orqueueServiceNotifyfor services) ->ToolError("notify is unavailable in this session."). Neither starts the command. - missing/bad
cwd->ToolError("Working directory does not exist: ...")orToolError("Working directory is not a directory: ...").
- async requested while disabled ->
- Interceptor:
- matched command ->
ToolErrorwithBlocked: <rule.message>and the original command. - invalid interceptor regexes are silently skipped by
compileRules().
- matched command ->
- Internal URL filesystem:
- failures surface inside the command as errno results: missing entries
ENOENT, writes to immutable schemes, non-write mutations (rm,mkdir, …) of handler-owned schemes, andout://writes whenout.enabledis offEROFS, appends to replace-only handler URLs and non-UTF-8 handler payloadsEINVAL, oversizeout://repliesEFBIG, schemes above the approved tierEACCES, cross-scheme renames/linksEXDEV, containment escapesEACCES. External programs started in a URL working directory fail instead of running on the host.
- failures surface inside the command as errno results: missing entries
- Execution:
- non-zero exit -> returned tool result marked
isError, withdetails.exitCodeand text ending inCommand exited with code <n>. - missing exit code -> thrown
ToolErrorwithCommand failed: missing exit status. - timeout -> local, PTY, and client-terminal execution return an
isErrorresult withdetails.timedOut: trueand a timeout notice. Managed background execution records it as a failed job. - user abort ->
ToolAbortErrorwhen the caller signal is aborted.
- non-zero exit -> returned tool result marked
- Artifact allocation/save failures in
saveBashOriginalArtifact()do not fail the command. Sink artifact failures also permit execution to continue, but returnartifactErrormetadata and an incomplete-capture notice instead of advertising an incomplete artifact as full output.
Notes
strict = trueis set onBashTool;concurrencyis resolved per call:pty: trueis"exclusive"(it takes over the terminal UI), everything else is"shared", so multiple non-pty bash calls in one assistant message run in parallel. When parallel calls overlap on the same shell session key, the first owns the persistentShell; the rest run in one-shot forks of it, whose shell state carries back into the persistentShellwhen they end (seeshellSessionsInUseandShell.adopt()inbash-executor.ts).- A bare
skill://<name>is the skill directory for shell operations; its instructions areskill://<name>/SKILL.md. checkBashInterception()blocks only when the matching rule'stoolname is present inctx.toolNames; missing tools disable their corresponding rule.- Interceptor configuration syntax is unchanged. It handles common flat command lists, not full shell parsing: heredocs, parameter expansion, command substitution, backticks, grouping, and malformed quoting only receive the existing whole-input check. This is best-effort routing toward dedicated tools, not a security boundary.
bash.direnvdefaults to"auto"and honors direnv's allow list; an unallowed.envrcis not executed. Set it to"off"to bypass preflight.bash.direnvLoadTimeoutMscontrols the cold-load budget.- Default interceptor rules come from
DEFAULT_BASH_INTERCEPTOR_RULESinpackages/coding-agent/src/exec/settings.ts:cat|head|tail|less|more->read(notcatthat sends stdout to a file or reads a heredoc, such ascat > forcat 2>err > f)grep|rg|ripgrep|ag|ack->grepfind|fd|locatewith name/type/glob flags ->globsed -i,perl -i,awk -i inplace->editecho|printf|catwhose stdout goes to a file (echo x > f,cat > f,cat 2>err > f,cat <<EOF > f) ->write; redirects of other fds (2>err.log), fd duplication,/devsinks and redirects after;,&&,|or a newline do not count
- PTY mode is ignored in non-UI contexts and when
PI_NO_PTY=1(gated bycanUseInteractiveBashPty()); the tool falls back to non-PTY execution and appends apty requested but unavailable in this environment; ran without a terminalnotice. - Non-PTY runs layer
NON_INTERACTIVE_ENVviabuildNonInteractiveEnv(); PTY runs instead get the shell spawn environment (getShellConfig().env) minusGIT_EDITOR,GPG_TTY,CI, andNO_COLOR, thenTERM=xterm-256color, then any direnv-provided values, which win. - When the shell minimizer rewrites output inside
executeBash(), the visible output is replaced with minimized text and a[raw output: local://<id>.log]footer may be appended ifonMinimizedSavepersisted the original text. - For executor internals that are not tool-specific — shell session reuse keys, snapshots, prefix handling, and native timeout behavior — see
docs/bash-tool-runtime.md.