Skip to main content

SelfHeal Runtime

AI-assisted repair for running Python applications, with verification and developer control.

Python 3.11+  ·  Rust core  ·  Beta  ·  Review by default

SelfHeal is a Python SDK for detecting failures, checking AI-proposed repairs, and updating selected functions inside a running application. Its Python agent handles health checks, provider requests and live dispatch; its Rust core handles workspace verification, source snapshots, patch transactions and audit records.

When a registered function raises an exception or fails a developer-defined health check, the agent can ask your AI provider for a scoped patch and produce a verified preview. Applying it requires explicit authorization. Authorized patches update live function bodies without re-running module initialization. If activation fails, SelfHeal attempts to restore the previous source and function code.

You choose what can change, what correctness means, and when a patch may apply. Successful live repairs keep the application's process running; an uninterruptible timeout can stop it for recovery.

Get started · Embed the agent · Async support · Terminal controls · Time budgets · Try the calculator · Security

What you get

Capability How it works
Detect exceptions and wrong results Routed calls report failures; your health checks define expected behavior.
Keep edits scoped Only registered function bodies may change. Imports, signatures and other definitions stay protected.
Verify before activation The Rust core checks syntax and optional pytest in a copied workspace; candidate health checks run in a separate process.
See every proposed change Terminal diffs, verification results, snapshots and audit records make repairs inspectable.
Update running functions Guarded activation updates function code while preserving module initialization and existing function objects.
Await async functions Coroutine calls and safe retries use the app's owning event loop; repair workers coordinate activation with in-flight calls.
Control time and API usage A shared repair deadline, direct-call limits and cooldown, background budgets, backoff and suspension bound repair activity.

This is a single-process Python SDK. Integrate it into your app, register editable functions, and route participating calls through its dispatch lock. It cannot attach to an arbitrary process or prove every AI patch correct. Synchronous and async def functions, directly defined methods and property accessors are supported. Async apps use async with agent and await agent.bind("target")(...); see the async integration guide for loop ownership and cancellation.

Install and configure your own API

Install into your application's Python environment:

python -m pip install "pyselfheal-rt[verification]"
python -m selfheal doctor

The distribution name is pyselfheal-rt; Python imports and the CLI use selfheal. Use standard CPython 3.11 or later. Compatible wheels include the native extension; building from source requires Rust and platform C/C++ build prerequisites.

Installation Includes
pyselfheal-rt Python SDK, Rust extension, background agent and CLI.
pyselfheal-rt[verification] Adds pytest for candidate regression checks, enabled by default.
pyselfheal-rt[verification,exploration] Also adds Hypothesis for bounded property checks.

For development from a repository checkout:

python -m pip install -e ".[dev]"
python -m selfheal doctor

doctor checks the installed distribution, Python SDK and native interface without contacting a provider. See Windows setup for source-build prerequisites.

Create .env in your app's working directory:

SELFHEAL_USE_GROQ=true
GROQ_API_KEY=your-groq-key
GROQ_MODEL=your-enabled-json-capable-model
OPENAI_API_KEY=
OPENAI_MODEL=

# Optional outbound telemetry push to your dashboard (non-blocking, fail-silent):
SELFHEAL_DASHBOARD_URL=
SELFHEAL_DASHBOARD_KEY=
SELFHEAL_APP_NAME=

Replace the placeholders with your own key and enabled model. Set SELFHEAL_USE_GROQ=false to use OPENAI_API_KEY and OPENAI_MODEL. Built-in providers require the selected vendor's key/model and raise ConfigurationError when configuration is missing, invalid or still a known placeholder. No account, API credit, key or model is bundled. Authentication and model access are checked by the provider on the first request; the API provider may charge for requests.

provider_from_env() loads the working directory's .env. Existing process variables take precedence. Restart after editing credentials or selection. Keep .env out of source control. Validate local configuration without an API request:

python -m selfheal check-config

Embed it in your running app

Suppose your app's myapp/pricing.py defines quote(price, discount). Its expected result for quote(100, 0.10) is 90. Put the health contract in trusted integration code, outside the functions the AI may edit:

from pathlib import Path
from selfheal import (
    AgentConfig, HealthCheckResult, HealthReport, LiveControlServer, LiveTarget,
    SelfHealAgent, SelfHealConfig, SelfHealRuntime, TerminalReporter,
)


def pricing_health(module):
    try:
        value = module.quote(100, 0.10)
        return HealthReport((HealthCheckResult("discount result", value == 90),))
    except Exception as exc:
        return HealthReport((HealthCheckResult("quote", False, type(exc).__name__),))


runtime = SelfHealRuntime(
    SelfHealConfig(project_root=Path(".")),  # project pytest verification enabled
    event_sink=TerminalReporter(),
)
target = LiveTarget(
    name="pricing", module_name="myapp.pricing", symbol_name="quote",
    health_check=pricing_health, editable_symbols=("quote",), retry_safe=True,
    instructions="Preserve the pricing API and discount contracts.",
)
agent = SelfHealAgent(runtime, (target,), config=AgentConfig(
    interval_seconds=60, auto_apply=False,
))
quote = agent.bind("pricing")

with agent, LiveControlServer(runtime, (target,), agent=agent):
    run_your_application(quote=quote)  # your existing blocking app entry point

Start the agent once in the owning app process. The context managers must stay alive for the application's lifetime. quote resolves the current function on each call; failures are preserved for the caller and queue a background inspection. The agent does not replay the failed application request. Future calls use a successfully committed repair. Healthy checks skip AI requests by default. Failing checks catch wrong-result bugs even when no exception is raised.

auto_apply=False produces verified previews. Explicitly set AgentConfig(auto_apply=True) to permit scheduled verified patches. Pure, nonempty developer health checks and retry_safe=True are required for live activation. For production-shaped apps, maintain regression tests as well as health checks. SelfHealConfig(run_tests=False) is an explicit choice to rely on syntax and registered health contracts rather than pytest.

Protect a whole module in one line

Instead of registering every function by hand, protect all eligible functions of a module at once:

import selfheal
from myapp import pricing

pricing = selfheal.protect(pricing, health_check=pricing_health, retry_safe=("quote",))
pricing.quote(100, 0.10)          # routed through the agent, like agent.bind("...")

protect() returns a read-only proxy: protected functions are routed through the agent, everything else (constants, classes, imports) is forwarded to the real module. Each function stays its own target, so an AI patch can only change that function's body. Eligible are public, module-level def/async def functions defined in the module; imports, aliases, lambdas, generators, closures and decorated wrappers are skipped and listed in pricing.__selfheal__.skipped. Methods are not covered; register them as dotted LiveTargets. Useful options: include, exclude (globs), include_private, ignore_exceptions=(ValueError,) for expected errors, control=True for the terminal commands, and protect(a, b) for several modules sharing one agent. Control lives on pricing.__selfheal__ (close(), status()).

Know the limits: the module namespace is not patched, so calls made inside the module, or through from myapp.pricing import quote, bypass protection; always call through the returned object. Without health_check only a weak "still callable" contract exists, so only exceptions (not wrong results) are noticed. Review-only is the default; auto_apply needs retry_safe for every protected function. A synchronous function called on an event-loop thread runs unprotected with a one-time warning.

Choose the integration API

API Use it for
agent.bind(name) / agent.call(name, ...) Coordinated application calls with background inspection after failures.
runtime.invoke(...) / await runtime.ainvoke(...) Coordinated calls without automatic repair.
runtime.call(...) / await runtime.acall(...) Exception-triggered repair with at most one authorized, explicitly safe retry.
runtime.inspect(...) / await runtime.ainspect(...) Explicit health-based inspection or improvement; apply=False previews.
runtime.check_health(...) / await runtime.acheck_health(...) Developer health checks without an AI request or source change.

Direct exception repair uses SelfHealConfig(auto_apply=...) or a runtime reviewer callback; background activation uses AgentConfig(auto_apply=...). These are separate controls. Declaring retry_safe=True means your application can safely repeat the relevant work; it does not make side effects reversible.

Configure the agent with TOML

Copy selfheal.example.toml to your app as selfheal.toml, then replace the target modules and trusted health callback references:

agent = SelfHealAgent.from_config(
    Path("selfheal.toml"), event_sink=TerminalReporter(),
)
quote = agent.bind("pricing")
with agent, LiveControlServer(
    agent.runtime, tuple(agent.targets.values()), agent=agent,
):
    run_your_application(quote=quote)

The imports and app entry point are the same as in the example above. project_root resolves relative to the TOML file. Credentials remain in .env or process environment variables.

By default, the agent checks every 300 seconds, skips AI requests for healthy scheduled checks, allows six AI attempts per hour and suspends a target after three consecutive failures. Failed attempts use exponential backoff. Explicit scans and failure notifications can inspect targets even when known checks pass. Use improvement_instructions to opt into recurring improvements; define health contracts for the behavior you expect.

Inspect and patch from the terminal

In another terminal, use the same working directory or pass --session:

python -m selfheal status
python -m selfheal telemetry
python -m selfheal heal --target pricing --preview
python -m selfheal heal --target pricing
python -m selfheal improve "Handle invalid discounts clearly" --target pricing
python -m selfheal agent pause
python -m selfheal agent resume
python -m selfheal agent status
python -m selfheal agent scan --target pricing
python -m selfheal agent reset --target pricing

heal and improve without --preview authorize a fresh verified live patch. Diffs, verification, health results, snapshots and rollback are visible in the app terminal and command client. The local control server is authenticated and loopback-only; protect its .selfheal/live.json credential.

agent scan queues an inspection under the agent's existing activation policy; agent reset clears suspension and backoff without clearing its hourly budget. Explicit heal and improve operations are outside the background agent's hourly budget. A preview performs native syntax/pytest verification; candidate health checks run on the activation path. Applying after a preview generates a fresh candidate rather than approving a saved preview.

registered health failure / exception / developer request
  -> your AI API proposes a complete candidate module
  -> allowed function bodies and unchanged signatures are checked
  -> Rust verifies syntax and optional pytest in a copied workspace
  -> developer authorization and candidate health checks
  -> source snapshot and guarded source replacement
  -> function code updated without re-running module initialization
  -> running health checks pass: commit; otherwise: restore and report

Module globals, existing function objects, defaults, decorators and connections are retained. Active routed calls finish before activation; subsequent routed calls use the new code. Calls continue during API generation and initial native verification, and wait during final verification and activation.

Deeper checks and method targets

For generated edge cases, workflow invariants, dotted method targets and optional read-only helper context, see deeper checks and method targets. The optional pyselfheal-rt[exploration] extra supplies Hypothesis for bounded property checks:

Building block Purpose
ScenarioCheck Run a trusted workflow against fresh disposable state and return a boolean contract result.
PropertyCheck Generate and shrink cases, then retain failing examples in memory for subsequent checks.
HealthSuite Combine synchronous checks into one nonempty health report.
LiveTarget.context_files Supply explicitly selected project Python files as read-only provider context.

Scenario/property predicates are synchronous; async health callbacks are supported separately. Generated tests do not establish that every bug has been found. Read-only context is limited to eight files and 16 KB combined, and does not expand the editable scope or enable multi-file transactions.

Method targets use dotted names such as Pricing.quote or Pricing.total.fget. For an instance method, pass the instance to the bound callable. Property access must also use coordinated dispatch; an ordinary instance.total read bypasses it.

Run python -m selfheal doctor to inspect SDK/native compatibility without an API request. A stale editable native extension is rejected before repair starts.

Provider selection

from selfheal.providers import provider_from_env, GroqProvider, OpenAIProvider

provider = provider_from_env()  # .env boolean selects Groq or OpenAI
provider = GroqProvider(api_key="your-real-key", model="your-enabled-model")

An explicit priority argument overrides the boolean. If the boolean is absent, SELFHEAL_PROVIDER_PRIORITY controls the default groq,openai order and missing keys are skipped. Cross-provider fallback is opt-in: provider_from_env(priority=("groq", "openai"), fallback=True). With the boolean alone, selection stays pinned to that vendor, even if fallback=True is passed.

Built-in providers use HTTPS, refuse redirects, bound response/context sizes and HTTP retries, and validate the JSON proposal. Model output cannot directly write files or issue shell commands. A custom AIProvider can be explicitly injected; the deterministic mock exists for offline tests and is never an automatic fallback.

Configure the repair time budget

Set the complete repair budget in your application's working-directory .env:

SELFHEAL_REPAIR_TIMEOUT_SECONDS=180
SELFHEAL_TIMEOUT_CLEANUP_SECONDS=5
SELFHEAL_HARD_TIMEOUT=true

One deadline covers provider retries, verification, review, activation and live retry. Each stage uses the time remaining; it does not start a fresh budget. Cleanup is reserved inside the total, capped at 10% of that total. With the defaults, work has 175 seconds and cleanup has the remaining 5 seconds.

Explicit SDK/TOML settings override process environment variables, which override .env. Recreate the runtime or restart your app after changing settings.

The enabled hard-timeout watchdog can terminate the owning application if native code cannot unwind. A supervisor or maintainer must restart it after recovery finishes. Disabling it removes that bound on native stalls. See timing behavior and recovery for details.

Operational boundaries

  • Targets can be synchronous/coroutine module functions, directly defined instance, static/class methods and property accessors in writable UTF-8 project source. Class layout, descriptors and signatures stay fixed. Regular/async generators, native callables, arbitrary wrapper closures, custom metaclasses, inherited target definitions and dependency changes are rejected.
  • Register one runtime/agent per owning process. Multi-worker coordination, automatic crash recovery after a forced kill and remote-process attachment are not implemented. All participating calls need the runtime's dispatch coordination; async targets share one owning event loop per runtime.
  • Health checks must be pure and safe to repeat. Candidate checks use a disposable process and a serializable snapshot of app state. Baseline and activation checks remain in-process to preserve live state/identity checks. Neither is a permission sandbox; external side effects remain possible.
  • Timeouts interrupt guarded Python loops and terminate candidate/verification process trees. The hard watchdog can stop the owning app on a native stall. Deadlines are not a real-time OS guarantee; recovery I/O can take additional time.
  • Rollback restores source and function code. It cannot undo external writes, arbitrary shared-state changes or side effects. If restoration fails, healing is disabled and the app must restart.
  • Source and sanitized failure/health context go to the selected provider. Known secrets are redacted or rejected; arbitrary personal data needs the developer's own policy. Direct exception repairs have an hourly budget and failure cooldown; the agent separately bounds background AI attempts with budgets, backoff and suspension.

Use only code, accounts and data you are authorized to modify or transmit. Review SECURITY.md and the AI provider's applicable terms before enabling automatic patches. Passing checks is evidence about the registered contracts, not a guarantee of correctness or legal compliance.

Try the isolated calculator

After installing the current checkout, run this from the repository root:

python scripts/run_timing_calculator.py --scenario all --timeout 10

The fixture starts with broken subtraction and zero division, then exercises repair, candidate timeout, live-retry rollback, a shared-budget timeout and a hard timeout. It uses a deterministic offline provider by default, with no API request. Disposable calculator files stay under ignored .selfheal/manual-timing/; the SDK never imports the fixture.

Expected final output: MANUAL CALCULATOR: PASS. The hard-timeout scenario intentionally terminates a child calculator process and checks source recovery. See the walkthrough and expected results.

Development and release

From an installed development checkout:

python -m selfheal doctor
python -m pytest tests
cargo test --locked

CI is configured to run Python tests, SDK/native compatibility checks and Rust tests on Windows and Linux with Python 3.11 through 3.14. The release workflow builds wheels for Linux x64, Windows x64, macOS Intel and macOS ARM64, plus a source archive. It checks archive contents and metadata and runs regressions against installed wheels, including a wheel built from the source archive.

Manual workflow dispatch builds validation artifacts. Pushing a v* tag also enables the PyPI publishing job after the build jobs succeed and the tag matches the package version, using the configured pypi environment and trusted publishing. Workflow configuration alone does not prove a release has published or passed on every platform.

Resource Purpose
Integration guide Register targets, define health contracts and embed the background agent.
Async guide Coroutine dispatch, live health, cancellation, concurrency and manual regression commands.
Deep healing guide Methods, property accessors, scenarios, generated cases and read-only context.
TOML template Configure runtime, scheduling and editable targets.
Manual testing Set up Windows tooling and walk through the live calculator.
Timing guide Configure deadlines and exercise the isolated timeout scenarios.
Release guide Build and validate distribution artifacts before publication.
Changelog Review version history.

examples/live_calculator.py is a deliberately broken manual fixture. Examples and test fixtures are separate from the application's SDK integration.

Original source is MIT licensed. Bundled dependency terms and retained copyright notices are in THIRD_PARTY_NOTICES.md.

Metadata

Release files for pyselfheal-rt 0.4.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 pyselfheal-rt 0.4.0
File Size Uploaded Provenance Actions
pyselfheal_rt-0.4.0.tar.gz 151.3 kB With provenance Details for pyselfheal_rt-0.4.0.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for pyselfheal-rt 0.4.0
File Actions
pyselfheal_rt-0.4.0-cp311-abi3-win_amd64.whl CPython 3.11 abi3 Windows x86-64 Details for pyselfheal_rt-0.4.0-cp311-abi3-win_amd64.whl
pyselfheal_rt-0.4.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl CPython 3.11 abi3 Linux glibc 2.17+ x86-64 Details for pyselfheal_rt-0.4.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
pyselfheal_rt-0.4.0-cp311-abi3-macosx_11_0_arm64.whl CPython 3.11 abi3 macOS 11.0+ ARM64 Details for pyselfheal_rt-0.4.0-cp311-abi3-macosx_11_0_arm64.whl
pyselfheal_rt-0.4.0-cp311-abi3-macosx_10_12_x86_64.whl CPython 3.11 abi3 macOS 10.12+ x86-64 Details for pyselfheal_rt-0.4.0-cp311-abi3-macosx_10_12_x86_64.whl

Total release size: 1.9 MB

Release files / pyselfheal_rt-0.4.0.tar.gz

Download URL pyselfheal_rt-0.4.0.tar.gz
Size 151.3 kB
Tags Source
SHA-256 checksum
How to use checksums
9b384807b09eb04a6efd136f08c9031c607283dd721899cb1219ad4bdb302c4e
BLAKE2b-256 checksum
How to use checksums
d5f4cd6db872da0e19da27a05e62a41acf1e7e42d52aff72e80da2606a7243ab
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.

Transparency log

Release files / pyselfheal_rt-0.4.0-cp311-abi3-win_amd64.whl

Download URL pyselfheal_rt-0.4.0-cp311-abi3-win_amd64.whl
Size 403.7 kB
Tags CPython 3.11 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
86e929cdc752032ac9a8e40efe3aad2aa7eb41cd77c38ff2b3ae77f9ff5718f2
BLAKE2b-256 checksum
How to use checksums
ecf8f8ec83956e0841d75c7ca59935b41da8e400ff9c77ee619f9dded720e2e2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.

Transparency log

Release files / pyselfheal_rt-0.4.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl

Download URL pyselfheal_rt-0.4.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Size 473.6 kB
Tags CPython 3.11 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
0463bbc25745fceb6b817b4b24841e3e56f827a3782eddb9e1c5f73e0850eb9c
BLAKE2b-256 checksum
How to use checksums
ce372d35c601ec7acd42ca2e4b00d17807c4b716dcecb943095770b1bf095b1d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.

Transparency log

Release files / pyselfheal_rt-0.4.0-cp311-abi3-macosx_11_0_arm64.whl

Download URL pyselfheal_rt-0.4.0-cp311-abi3-macosx_11_0_arm64.whl
Size 435.5 kB
Tags CPython 3.11 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
b71d5c83124cab179c30b9a390609f25c8622086d449d7616964cc326d06bc06
BLAKE2b-256 checksum
How to use checksums
4ee8a8a2636d117e73f52a876332b1bacee69f32d33d62f3d4f17e5a3801f799
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.

Transparency log

Release files / pyselfheal_rt-0.4.0-cp311-abi3-macosx_10_12_x86_64.whl

Download URL pyselfheal_rt-0.4.0-cp311-abi3-macosx_10_12_x86_64.whl
Size 441.3 kB
Tags CPython 3.11 abi3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
9b2c1eff22db44719b7faf9af4fa0042654e81757a177d40b40848a37fa39b62
BLAKE2b-256 checksum
How to use checksums
aff04d7c418c2db3bbb6a40bcb280bf3f3ec26221c631d7322e00a3267fb5d7a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.

Transparency log

Security for pyselfheal-rt 0.4.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.

Full provenance

All 5 files in this release have been uploaded with provenance metadata.

Select from 5 files

Attestation for pyselfheal_rt-0.4.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.

Transparency log

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.4.0 This release

5 release files Full 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