Skip to main content

offswitch

A tiny, dependency-free AI off switch for Python. The AI (or any automated agent) operates; a human can kill it; and only a human can turn it back on.

Inspired by a latching emergency stop on a machine: someone presses the big red button, everything stops, and it stays stopped until a person walks over and deliberately resets it. The machine can read the button. It can never press reset.

  • Zero dependencies, pure standard library, Python 3.9+
  • Latching: once killed, a process stays killed
  • Fail closed: if the switch can't be read or the remote can't be reached, that is a kill
  • Any one source kills: kill file, env var, signal, remote URL, or a stale human heartbeat
  • Append-only, hash-chained audit log of every kill and reset
  • Reset only works from a human at a terminal who types a confirmation phrase

Read the threat model before relying on this. A software switch is a seatbelt, not a vault.

Install

pip install offswitch            # once published; until then:
pip install git+https://github.com/fitzyracing1/offswitch   # (planned location)
# or from a checkout:
pip install .

2-minute drop-in guide

1. Add the switch to your agent.

from offswitch import OffSwitch, KilledError

switch = OffSwitch()  # watches .offswitch/KILLED and $OFFSWITCH_KILL


@switch.guard  # checked before every call
def run_tool(name, args): ...


def agent_loop():
    while True:
        switch.check()  # raises KilledError if the switch is ON
        step()


try:
    agent_loop()
except KilledError as stop:  # note: a BaseException, `except Exception` won't eat it
    cleanup()
    raise SystemExit(f"stopped: {stop.reason}")

Also works as a context manager and on async def functions:

with switch:  # checks on entry and again on exit
    do_something_risky()

Put switch.check() (or @switch.guard) in front of anything with side effects: tool calls, shell commands, network writes, spending money, commits, deploys.

2. Kill it (from any shell, script, cron job or monitoring alert; killing needs no confirmation):

offswitch kill -m "agent is looping on prod"

Every guarded call now raises KilledError, in every process that watches that file.

3. Look at it.

offswitch status       # exit code 0 = running, 3 = killed
offswitch log          # audit trail + chain verification

4. Resume (a human, at a terminal):

offswitch reset        # type the confirmation phrase when asked

Then restart the agent. A process that was killed stays killed even if the file disappears, by design. Restart is the "walk over and reset the machine" step.

Add .offswitch/ to .gitignore (the kill file is local state).

Kill sources

Any one of these kills. Once any fires, the switch latches (a kill file is written so other processes see it too) and the event is audited.

Source How Default
Kill file file exists (even empty) .offswitch/KILLED (path resolved to absolute at startup)
Env var set to anything except "", 0, false, no, off OFFSWITCH_KILL
Signal kill -USR1 <pid> or offswitch kill --pid <pid> off; pass signals=(signal.SIGUSR1,)
Remote URL poll an http(s) endpoint, fails closed off; pass remote_url=...
Heartbeat human heartbeat file is missing or stale (dead-man) off; pass both args
Code switch.kill("reason"), an agent can trip itself, never un-trip n/a
import signal

switch = OffSwitch(
    ".offswitch/KILLED",
    env_var="OFFSWITCH_KILL",
    signals=(signal.SIGUSR1,),  # main thread only
    remote_url="https://example.com/ai-status",
    remote_timeout=2.0,  # per request
    remote_interval=5.0,  # cache results this long
    remote_fail_closed=True,  # default: unreachable/garbled = killed
    remote_grace=0.0,  # seconds of failure tolerated before killing
    remote_headers={"Authorization": f"Bearer {os.environ['STATUS_TOKEN']}"},
    latch_on_remote_error=True,  # False: blocked while unreachable, auto-recovers
    heartbeat_file=".offswitch/HEARTBEAT",
    heartbeat_max_age=900,  # human must `offswitch beat` every 15 min
    audit_log=".offswitch/audit.log",
)

Remote URL protocol

GET the URL. 200 plus JSON {"killed": false} (or a plain body ok/alive/run/ go/0/false) means keep going. {"killed": true} or a plain body killed/stop/ off/1/true means stop. Anything else is an error: non-200, timeout, DNS failure, a captive portal's HTML. With remote_fail_closed=True (default) errors kill. Set remote_fail_closed=False only if a network blip must never stop you, and understand that then an attacker who can block the network can also block your kill signal. Only http/https URLs are accepted. Use a URL a human controls (a gist, an S3 object, a tiny worker, a status page). Do not put secrets in code; read tokens from the environment.

Dead-man heartbeat

switch = OffSwitch(heartbeat_file=".offswitch/HEARTBEAT", heartbeat_max_age=900)

A human runs offswitch beat --heartbeat-max-age 900 (or any script that touches the file, run from their session) at least every 15 minutes. If they stop (asleep, laptop closed, incident), the agent stops on its own. A missing file counts as stale.

CLI

offswitch kill   [-m REASON] [--pid PID ...]   turn ON (no confirmation; exit 3)
offswitch status                                exit 0 running, 3 killed
offswitch reset  [-m NOTE]                      human only (see below)
offswitch beat                                  refresh the dead-man heartbeat
offswitch log    [--no-verify]                  show audit log, verify hash chain

Common flags: --dir (default .offswitch), --kill-file, --audit-log, --heartbeat-file, --heartbeat-max-age, --env-var, --remote-url, --remote-timeout. python -m offswitch ... also works.

reset is deliberately awkward. It refuses unless stdin and stdout are a terminal (exit 4, nothing changes), and then requires you to type I AM A HUMAN, RESUME THE AI exactly. Wrong phrase: refused and audited. Right phrase: kill file removed, reset audited. The Python API has no reset method on OffSwitch at all. Reset lives in offswitch.admin and runs the same checks.

If $OFFSWITCH_KILL is still set, or the remote still says killed, or the heartbeat is still stale, the next process will be killed again immediately; offswitch status tells you which.

Audit log

.offswitch/audit.log is JSON lines, written with O_APPEND, one entry per kill, kill-observed, reset, reset-refused, with timestamp, user, host, pid, source and reason. Each entry stores the SHA-256 of the previous one, so edited or removed lines are detected by offswitch log (or AuditLog.verify()). That is tamper evidence. For tamper resistance on Linux, as root: chattr +a .offswitch/audit.log, or ship entries to a log host the agent can't write to.

GitHub Actions

  • examples/github-actions/agent-job-gate.yml: blocks agent jobs while a .offswitch/KILLED file exists on the default branch or the repo variable OFFSWITCH_KILL is truthy. Checking the default branch (not the PR checkout) matters: an agent can delete a file in its own branch, but not on main. Errors fail closed. Copy it to .github/workflows/ and put your agent steps after the gate. To kill: gh variable set OFFSWITCH_KILL --body 1 (or commit .offswitch/KILLED to main). To resume: gh variable delete OFFSWITCH_KILL, and revert the file. Give the agent's token no permission to edit repo variables or push to main.
  • .github/workflows/ci.yml: lint, tests and build for this package.

Threat model (be honest with yourself)

What this protects against: well-meaning-but-buggy agents, runaway loops, a tool-using model that is confused rather than adversarial, a human who needs to say "stop now" and have every guarded call obey, and accidents like an agent "helpfully" deleting the kill file (the in-memory latch holds).

What it does not protect against: a determined process with the same permissions as the switch. If the agent can run arbitrary code as the same OS user, it can delete or rewrite the audit log, unset the env var, remove the signal handler, monkeypatch OffSwitch.check, never call check() at all, spawn a subprocess that doesn't import this library, os.fork() past it, or allocate a pseudo-terminal and type the reset phrase. A Python library cannot stop code that is willing to ignore it. The checks only work if the guarded code chooses to run them.

What a real guarantee needs is separation the software can't provide:

  • Run the agent as an OS user (or container) that cannot write the kill file or heartbeat directory and cannot read the reset tooling. Make the state dir root-owned and read-only to the agent. Then it can read the switch and cannot reset it, which is the entire design.
  • Put the real control outside the machine: revoke the API key or cloud role, drop the network at a firewall, stop the container, or cut power. These work on a process that has ignored your library entirely.
  • Do the enforcement at a chokepoint the agent has no access to (a proxy, a broker, a deploy pipeline) and let offswitch be the cooperative fast path in front of it.
  • Use the dead-man heartbeat so that silence stops the agent, rather than depending on someone remembering to press kill.

The hardware version of this idea: the original design is a harbor whose passive radar reflectors keep marking the channel even if the AI that runs the active gear (radar beacon, AIS, lights) goes wrong. A physical, human-flipped latching cutoff on the active gear removes its power and the AI cannot override it, because it is wired on the far side of the AI's reach, and the passive safety layer needs no software at all. This library is the software analog of that cutoff; the physical one is stronger. If the stakes are physical, build the physical one: a latching e-stop that cuts power to actuators, wired so a controller fault leaves them off, with a manual reset.

Other caveats

  • Latching is per process. Restart is part of reset.
  • Fail-closed means a flaky remote will stop you (that is the point; tune remote_grace).
  • Signal handlers only install from the main thread (a warning is raised otherwise) and replace the default SIGUSR1 action; any previous Python handler is chained.
  • check() is cheap (a stat and an env read; remote polls are cached) but not free; don't call it in a tight inner loop of pure computation.
  • Not Windows-tested; signal support is POSIX-only.

Development

pip install -e '.[dev]'
ruff check .
pytest
python -m build

License

MIT, © 2026 Joshua Almeida (@fitzyracing1).

Metadata

Release files for offswitch 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for offswitch 0.1.0
File Size Uploaded Provenance Actions
offswitch-0.1.0.tar.gz 27.4 kB Without provenance Details for offswitch-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for offswitch 0.1.0
File Interpreter ABI Platform Actions
offswitch-0.1.0-py3-none-any.whl Python 3 none any Details for offswitch-0.1.0-py3-none-any.whl

Total release size: 46.3 kB

Release files / offswitch-0.1.0.tar.gz

Download URL offswitch-0.1.0.tar.gz
Size 27.4 kB
Tags Source
SHA-256 checksum
How to use checksums
f0451530c13ec16bc95d9b48f8c7a00df3b8d5f86e3b8683d26cfc89ed172df5
BLAKE2b-256 checksum
How to use checksums
8326f25fdcb16417484cdf9f18cbad0594cd7f732c24e7f863b30d66d3167ccb
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.5

Release files / offswitch-0.1.0-py3-none-any.whl

Download URL offswitch-0.1.0-py3-none-any.whl
Size 18.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
736b1c447bd5e5215ec2cc73c038464ca6e2e5152947f1d7cb23c21d9636b3c1
BLAKE2b-256 checksum
How to use checksums
0fe5ba90b2ebed4c30f692f5ca8f7ef3fe6553bd49675606fa1f7790aea280b7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.5

Security for offswitch 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page