Install
Install with PiG
pig install npm:pig-bg-tasksPackages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.
Pi manifest JSON
The pi field of package.json.
{
"extensions": [
"extensions/*"
]
}README
Written by the package's publisher, shown as published in version 0.3.6 (README.md). PiG does not review it.
pig-bg-tasks (Rust)
pi-bg-tasks, but in Rust + sandbox.
pi-bg-tasks (npm) is the lightweight background-bash
extension for PiG — run_in_background, timeout auto-background, Ctrl+Shift+B, completion
notifications (source). This repo
is that extension rewritten in Rust against the PiG Rust SDK, plus a permission sandbox: every
bash spawn can be confined in a Microsoft eXecution Container (mxc,
via mxc-sdk 1.0.1 on crates.io) instead of running bare.
What the sandbox adds over pi-bg-tasks:
- One composed
bashtool — sandbox params (sandbox_permissions,justification) and bg params (run_in_background,timeout,description) in a single tool with one execute path. Every spawn — foreground, quick-window, background — goes through the same spec builder; the only unconfined path is an explicitdanger-full-access. - Permission modes with fail-closed confinement, denial-first escalation and denial classification (below).
/sandbox [mode]— inspect or switch the mode process-wide.
Scope: bash only. write/edit belong to a separate permission-system extension and are never intercepted. Network is always allowed (no isolation). Threat model: fat-finger protection for a non-malicious model — not adversarial isolation.
Platform status: Windows, Linux and macOS. The sandbox is mxc everywhere — the same
Containment::Process request resolves per host to ProcessContainer (Windows), Bubblewrap (Linux)
or Seatbelt (macOS) — and the bare path is platform-native (job-object tree kill on Windows,
process-group kill on Unix; Git Bash on Windows, bash on PATH elsewhere). Windows is the
runtime-tested platform (gates E1–E10 + R11 in RUST-DECISION.md, smoke matrix 14/14,
acceptance runs in TESTING.md); Linux/macOS are verified by inspection — the cross-target
gate cargo check --target x86_64-unknown-linux-gnu --all-targets is clean, and the smoke matrix
self-skips where the host lacks a shell or the mxc backend (Linux: bwrap on PATH) instead of
failing.
Install / develop
# users — install the Package from npm (first use builds a runtime cell,
# which needs a Cargo/Rust toolchain on the machine):
pig install npm:pig-bg-tasks
# from the repository root (the npm Package):
pig install . --validate-only --json # cell build + registration check
PIG_HOME=<scratch-home> pig -ne -e "$(pwd)/extensions/pig-bg-tasks" -p # piped-prompt run
# plain cargo — run inside the crate:
cd extensions/pig-bg-tasks
cargo test # 115 tests: 101 unit + 14 smoke — single crate
cargo check --target x86_64-unknown-linux-gnu --all-targets # Unix compile gate (rustup target add first)
Rules that are easy to get wrong (full recipe: TESTING.md):
- The extension root is
extensions/pig-bg-tasks/, and its directory name is the extension identity — a-e <dir>selection registers under the directory's name, and the factory registerspig-bg-tasks; a mismatch fails withregister:name_mismatch. The crate'sCargo.toml,src/andtests/live there. This repository root is the npm Package (package.jsonwithpi.extensions: ["extensions/*"]), and its npm name ispig-bg-taskstoo, so the Package-selected identity matches as well. -nealways (skip ambient extensions — npmpi-bg-tasksregisters the same tool names) with an explicit-e.pig-sdkis never inCargo.toml(no[patch]either): pig resolves it at cell-build time into its own state dir..cargo/config.tomlcarries a path patch for plaincargoruns only — machine-local, never shipped.- Freeze the tree during pig builds (content-hash check) and warm the cell with
--validate-onlybefore timed piped runs (cold cell ≈ 9 min, warm ≈ 60 s).
Tools
| tool | notes |
|---|---|
bash | composed: sandbox params (sandbox_permissions, justification) + bg params (run_in_background, timeout, description). Denial-first escalation. 2 s quick-completion window (then live streaming); timeout auto-background (default 45 s) is interactive-only — in print/RPC the command runs out. |
bg_list | running first, then recent terminal (lazy eviction of notified jobs). |
bg_output | meta + last 32 KiB + log path; latches the completion notification. |
bg_stop | Job-object terminate (whole tree) + bounded wait; latches silently first, returns real outcome. |
Commands: /sandbox [mode] (process-wide, with completions), /bg, /bg-tasks.
Shortcut: Ctrl+Shift+B. Message renderers: <task-notification> and
<task-hung-notification> (one ● summary line each).
Steering (Enter mid-stream) auto-backgrounds running foreground commands.
Notifications are exactly-once via a check-and-set latch before send: any path that already
surfaced the outcome (bg_output/bg_stop, deliberate kill) suppresses it; a failed send is lost,
never retried. User-initiated stops emit zero notifications by design. Delivery is
deliverAs=steer, triggerTurn=true through a retained SDK context.
Hung-task check: a command that was not launched with run_in_background but was backgrounded
(timeout auto-background, Ctrl+Shift+B, steering) and is still running 10 minutes later gets one
extra steered notification — <task-hung-notification> (<backgrounded_for>, <running_for>,
<tail_preview>, and the instruction "Call bg_list to see all tasks, then call bg_stop for any hung
tasks.") — telling the model to bg_list and then bg_stop any hung tasks. Exactly-once per task
(its own hung_notified latch, independent of the completion latch — it can neither steal nor be
stolen by a completion); a task that finished or was stopped during the 10-minute window sends
nothing, and tasks launched with run_in_background=true are exempt by design: they are intentional,
not backgrounded-against-the-model's-plan.
Logs: %TEMP%\pi-bg-tasks\<taskId>.log (the temp root is inside the workspace-write grant — a
confined child writes its own log). Bare spawns are fd-direct (kernel moves the bytes); confined
mxc spawns pump piped stdout/stderr into the same log. Cap 64 MiB with auto-kill; session_start
sweeps logs older than 24 h; session_shutdown silently kills everything (Job objects guarantee no
orphans, even on hard extension death).
How the sandbox works
Permission modes
| mode | file effects (mxc per-spawn policy) |
|---|---|
read-only | zero writable roots: writes denied everywhere (workspace, temp dir included); the system root (C:\ / /) readable |
workspace-write (default) | workspace + host temp dir (%TEMP% / $TMPDIR) + default home dirs (~/go, ~/.cargo, ~/.rustup, plus ~/AppData/Local/Packages on Windows) + extraWritableDirs writable; system root read-only; everything else denied on write |
danger-full-access | bare spawn (explicit escape hatch) — runner: bypassed, OS permissions only |
Mode switching is /sandbox [mode]: with no args it shows the mode, the writable set, resolved
env, epoch and runner status; switching installs the process-wide override and bumps an epoch — the
next bash call binds it synchronously.
Per-spawn confinement through mxc
Each confined spawn builds its own ContainerRequest (runner::request::build_request →
mxc_sdk::v1::spawn) and starts a fresh mxc container — ProcessContainer on Windows,
Bubblewrap on Linux, Seatbelt on macOS; there is no long-lived sandbox:
- Filesystem:
readwrite_paths= the converged write roots,readonly_paths= the system root (C:\on Windows,/on Unix),deniedempty,clear_policy_on_exit. - Network: egress + ingress + host loopback allowed (posture: no network isolation).
- UI:
disable=false— no UI restriction (Windows console init needs win32k; a no-op elsewhere). - Environment: inherits the default env, plus
LC_ALLemptied /LC_MESSAGES=C(stable denial classification) and the resolved PATH;GH_TOKENis injected inworkspace-writeonly (see Known limits). - Engine: the shell resolved from pig's
shellPathsetting — configured path first on every host, then per platform: Windows$SHELL→ Git for Windows →bashon PATH; Unixbashon PATH →/bin/bash→$SHELL(see Git Bash);timeout_ms=0, so the extension's own timers govern. - Tree kill: bare spawns join a Windows Job object (
KILL_ON_JOB_CLOSE) or a Unix process group (kill(-pgid)) —bg_stop, session shutdown, and hard extension death take the whole tree; confined spawns die through the mxc process handle (Windows terminate is immediate; no SIGTERM).
No standing grants (per-call convergence)
Each bash call binds the newest mode epoch inside its own duration (resolve → validate →
record); policy is rebuilt per spawn (~37 ms baseline) and cleared on exit — no background thread,
no persistent container. Failures are causal and fail-closed (SANDBOX_UNAVAILABLE … with the real
cause): never bare, never half-applied. Full invariant list: CONVERGENCE.md.
Escalation (denial-first, bash only)
sandbox_permissions (workspace-write | danger-full-access) + justification:
- a strictly wider request is honored only after a real, unconsumed sandbox denial of the same
subject this session — otherwise the fields are ignored (the result carries
[sandbox: escalation fields were ignored …]); - one denial buys exactly one escalation retry;
- the approval prompt is Deny / Allow once (Deny first); no UI (headless/print/subagent) ⇒
fail-closed refusal, nothing executed — unless the session is a delegated child
(
PIG_PARENT_SESSIONset), in which case the ask rides the parent link and the parent session asks its user through its own dialog (see below); - placeholder
"null"/blank values are stripped before schema validation; approval covers one call.
Delegated children (the parent link)
A delegated child — any process whose environment carries PIG_PARENT_SESSION, the session id of
the session that spawned it (pi-subagents' one provenance marker) — orients to its parent over one
AF_UNIX socket per session: <osTempDir>/pig-sandbox-<sessionId>.sock — the OS temp dir
(%TEMP% / $TMPDIR), which both ends already agree on, so no config root has to be shared — on
every platform (Windows binds a real winsock AF_UNIX socket through the uds_windows crate). That single socket transports
everything that crosses the link: the policy fetch, the ask relay, the parent's pushed policy
updates, and the child's subscription to the parent's task busy state. Both ends are this extension — and no new model tools: the child's approval is asked of
the parent session's user through the parent session's own dialog.
- parent: listens from
session_startunder its own SDK session id — a session may be a child and a parent at once (nested delegation), so the listener always starts and the client only when the marker is set; - policy mirroring: the child fetches the parent's policy at session start and adopts it — the
parent's mode is the baseline (the child's own
sandbox.jsondefault does not apply) and a local/sandboxchoice may only narrow it, so nothing runs a child wider than its parent; the parent's extra writable roots replace the child's. The mirror stays live: whenever the parent's level widens or narrows, the parent pushes the new snapshot down the same socket (op:"policy-update") to every child that fetched one, and the child re-baselines in both directions — a frame from any other session is refused, so only the session that spawned the child can move it. An unreachable parent leaves the local policy untouched: a child never widens by being unreachable; - task busy-state watch:
op:"watch-tasks"subscribes on that same socket — the ack snapshots the parent's current state (busywhile any of its tasks runs, background or foreground) and every flip afterwards arrives as a{"event":"task-busy","busy":true|false}frame on the open connection until the subscriber closes it or the link goes down. A non-Rust consumer is verified too (tests/go_watch.rsruns a generated Go client against it — the Go source is written to the gitignoredpig-tmp/linkwatch/at run time, never committed); - ask relay: a headless escalation kicks the ask up instead of failing — the child blocks
(≤ 300 s) while the parent session's user answers the standard Deny-first dialog, worded
exactly like a local escalation (same title builder), so it reads as if it originated there. A
dismissed dialog cancels (nothing approved); a headless parent, a dialog error, no listener or a
timeout is fail-closed (nothing executes), and a deny's reason reaches the child in the ladder's
usual wording (
. The user's reason: …).
The endpoint name — the parent's session id — is the capability, under the user's own temp directory: that is the fat-finger bar of the threat model.
Denial classification (English-only)
Non-zero exit + a signature in the merged log tail ⇒ real denial →
[sandbox: file access denied under <mode> mode] + escalation hint + ledger record. Signatures:
access is denied, access to the path, permission denied, operation not permitted,
write-protected, read-only file system.
A runner failure (the command never ran) ⇒ SANDBOX_UNAVAILABLE … refusal instead — shell
unresolvable, or the container spawn itself failed. A missing marker on a localized Windows is a
classification gap, not a confinement failure.
Config — <configRoot>/agent/sandbox.json
Global only (~/.pig/agent/sandbox.json); project-level files are ignored silently (the project
is model-writable). Fields: mode, probeTimeoutMs (default 5000), extraWritableDirs (~
expanded, must exist, warned+dropped if invalid). Corrupt/missing ⇒ defaults. Read once per process
(restart to pick up changes). The shell comes from pig settings.json (shellPath), not from
sandbox.json.
Default writable dirs in workspace-write: four home-derived extras beyond workspace and
the host temp dir — ~/go (default GOPATH), ~/AppData/Local/Packages (per-app package data,
including mxc's own confinement dirs; Windows-only candidate, absent elsewhere and skipped),
~/.cargo (CARGO_HOME: registry caches, extracted crates, bin —
so sandboxed cargo build works) and ~/.rustup (toolchain store). The user folder is resolved at
runtime (never hardcoded); a missing candidate is skipped silently, and extraWritableDirs adds
to these defaults rather than replacing them.
Known limits (partial enforcement)
- Reads are unconfined by design (broad system-root read rule; the threat model is fat-finger writes).
- The Windows Credential Manager is blocked inside the container:
CredReadW/CredEnumerateWreturnERROR_ACCESS_DENIEDfor every target, sogh(whose token lives only in the keyring) sends noAuthorizationheader → 401, andgit credential fillfails too. Mitigation:workspace-writespawns getGH_TOKENin their env (hostGH_TOKEN/GITHUB_TOKENfirst, else a host-side keyring read — the pig host process is outside the container, where the vault is readable; on Unix gh's plaintexthosts.ymltoken is honored the same way). Read-only spawns stay tokenless; nothing is fabricated when no token exists. ping(ICMP) fails in the Windows container (Unable to contact IP driver— the driver is not exposed to the AppContainer); native tools otherwise run. Usepowershell -NoProfile -Command "Start-Sleep N"for long confined tasks there.- No persistent containers: policy is rebuilt per spawn instead of held for a session.
- Confinement needs the host's mxc backend present: Windows ships it, macOS has Seatbelt
built in, Linux needs
bwrapon PATH (Bubblewrap). A missing/broken backend fails closed with the backend's own cause (SANDBOX_UNAVAILABLE …), never bare; the smoke matrix self-skips on such a host. Denial classification is English-only.
Why Git Bash needs a patch
Windows-only story: on Linux/macOS the shell is native bash and the Bubblewrap/Seatbelt
backends do not share the MSYS runtime — no patch, nothing to install.
Git Bash (Git for Windows, https://gitforwindows.org/) is the usual shell for this extension —
but it is a Cygwin/MSYS runtime: bash and every child it forks share msys-2.0.dll's
in-memory world (cygheap, named objects, pipes). The sandbox runs that shell inside an mxc
ProcessContainer — an AppContainer whose security model differs from a normal logon session —
and the stock runtime assumes the latter. Inside the container the stock msys-2.0.dll fails in
three ways (root-caused in the fork's STATUS.md
and FORK_FAILURES.md):
- World-only object ACEs —
_everyone_sdgrants access to World (S-1-1-0) only, but AppContainer processes are not covered by "Everyone": opens need an ALL APPLICATION PACKAGES (S-1-15-2-1) ACE. Without itcygwin_pid()fails,fork()returns 0, and both halves of a pipeline run the same command. - Named objects and pipes — absolute NT pipe names and session-namespace objects are denied or
invisible in-container (named pipes die with
0xC00000B1,echo: write error). - Same-address fork vs. the container — the runtime reserves its cygheap at a fixed address
(
0x800000000), which fails intermittently under the container, and mxc force-relocates images that have not opted into ASLR — breaking Cygwin's same-address fork: children die0xC0000142withfork: retry: Resource temporarily unavailable.
All three are fixed in the winsup layer of https://github.com/xoviat/cygwin (the Cygwin fork
carrying the mxc patches) and shipped as a drop-in msys-2.0.dll — you do not build anything.
Install the patched Git Bash
Install Git for Windows (https://gitforwindows.org/) — default root
C:\Program Files\Git.Download
msys-2.0.dll,install.ps1anduninstall.ps1from the latest release (https://github.com/xoviat/cygwin/releases, currentlyv0.4.0, 2026-11-03; thecygwin1.dll/new-cygwin1.dllassets are for a Cygwin tree, not needed for Git Bash) into one directory.From an elevated PowerShell in that directory:
powershell -ExecutionPolicy Bypass -File install.ps1 # default Git root powershell -ExecutionPolicy Bypass -File install.ps1 -GitRoot 'D:\Git' # non-default rootPoint pig's
shellPath(insettings.json, NOTsandbox.json) at that install'sbash.exe.
Notes:
- The script swaps
{usr\bin,bin}\msys-2.0.dll(originals kept asmsys-2.0.dll.stock) and opts every PE image in the install into ASLR — mandatory under mxc, whose force-relocation of non-ASLR images breaks Cygwin's same-address fork (0xC0000142).-SkipPeFlagsskips the sweep (fine outside the sandbox, not inside it). - Safe to re-run as an update;
uninstall.ps1reverts the DLL and the PE flags from the manifest. - Gate in the fork:
tools/final-verify.sh→RESULT: 14 passed, 0 failed("git bash works inside the mxc sandbox").
License
MIT — see LICENSE (ported sources MIT; see upstream packages).