# Encased Python enforcement 0.2.1 — review candidate This is real customer-side Python code, not a certification or bypass-proof sandbox. Production use requires an independent security review of the code, supported environment and external containment. It does not detect arbitrary semantic drift, revoke provider keys, or snapshot process memory. ## Install and run ```sh pip install https://encased.ai/sdk/encased-0.2.1.tgz export ENCASED_KEY='YOUR_WORKSPACE_AGENT_KEY' python examples/guarded_agent.py ``` For the source example, extract the archive or use `sdk/python/examples` in the repository. Do not paste production keys into source files. Default gateway: `https://encased.ai/api/public/v1`. Optional HTTPS `ENCASED_URL` must include `/api/public/v1`. Plain HTTP is only available with explicit `allow_local_test` for loopback integration tests. Never enable that option in deployment. ## Covered operations * `Encased.protect` sync/async functions: immutable JSON arguments, proposal validation, pending polling, same-action approval, monotonic review deadline. Invalid responses, denial, revocation or transport failure stop the call. No automatic re-proposals, execution retries or action replay. * `NetworkGuard([Destination('api.openai.com')])`: exact HTTPS host/443 policies; public DNS validation; TCP connect/connect_ex hooks; urllib redirects checked; requests/httpx/aiohttp redirects disabled; optional clients patched if installed before guard entry. Native extensions, pre-existing sockets, hostile Python, UDP/raw sockets, subprocess networking and arbitrary proxies are not contained. Numeric connections require prior DNS approval; DNS/IP caching and pooled connections are not a substitute for an external egress proxy/firewall. * `RunGuard(Limits(...)).action(tool, args)`: limits total/repeated protected actions, nested depth, concurrency and duration. Only instrumented actions are counted. No inference that call-stack inspection detects malicious intent. * `run_worker([...], duration_s=..., stop_event=...)`: Linux/POSIX dedicated process-group termination (TERM then KILL). Never kills the customer's entire application, captures memory or restarts after approval. Escaped process groups require independently configured cgroups/container supervision. * `Budget` and `ProviderGuard`: thread-safe reservations shared by all wrappers using the same Budget instance in one worker. OpenAI chat completions sync/ async non-streaming and sync streaming; Anthropic messages sync/async non- streaming. No Anthropic/async streaming, Responses API, Google adapter, shared multi-process/workspace ledger, or automatic tokenizer/pricing discovery. Provider clients require `max_retries=0`. Supply conservative input token bounds, explicit output caps and current prices per million tokens. Reserve full maximum before dispatch; missing usage, errors or partial streams retain reservation. Reported usage reconciles once; overshoot stops subsequent calls. Stop closes supported active streams on their next chunk, not instantly during a stalled read. Cancellation cannot undo remote work or guarantee billing cessation. * `telemetry`: one correctly shaped batch, explicit acknowledgement or `DeliveryError`. Bounded nested metadata, common secret/PII masking, no silent success. No durable local spool; customer must provide monitored bounded retries if needed. Lost/uncertain evidence is not approval or proof of cancellation. ## Network and provider example ```python from encased import Budget, Destination, NetworkGuard, ProviderGuard from openai import OpenAI budget = Budget(token_limit=5000, spend_limit_usd=0.10, tokens_per_minute=5000) provider = ProviderGuard(budget, input_usd_per_million=1.0, output_usd_per_million=4.0) # Prices above are illustrative, not a current model price quote. with NetworkGuard([Destination('api.openai.com')]): client = OpenAI(max_retries=0, timeout=10) result = provider.call(client, 'openai', input_token_bound=1000, max_output_tokens=200, model='YOUR_APPROVED_MODEL', messages=[{'role': 'user', 'content': 'Summarise this synthetic example.'}]) ``` Create HTTP clients inside the dedicated worker/guard. One guard per process; do not change monkeypatches concurrently. Encased uses a private control-plane exemption to avoid recursion; hostile code can bypass process-local hooks. ## Privacy and policy delivery Destination rules are explicit customer-side configuration, NOT a hosted dashboard whitelist. Current hosted policies have no destination-host policy API/version acknowledgements. Hosted `/propose` still applies workspace tool/content rules. The exact frozen proposal arguments are transmitted and stored by Encased so content checks work: use synthetic/minimised arguments, never raw secrets or personal data. Redacting proposals would change what is approved and could hide content-rule triggers, so this SDK only redacts telemetry. No complete secret detection guarantee. Do not send headers, prompts, memory dumps or provider errors as evidence. Establish retention/consent separately before customer data use. ## Approval and isolation boundaries An initial `allowed/allow` executes; `pending/quarantine` pauses; a subsequent `approved/quarantine` with decision timestamp for the same ID executes. Human approval does not restart a process. One wrapper invocation executes at most once locally. The hosted API has no single-use permit consumption, approval expiry, execution receipt or downstream idempotency guarantee. Supply downstream idempotency for financial/destructive operations; never replay uncertain effects. Revoked Encased keys stop subsequent gateway access, not an already running action or provider key. Emergency stop is local `stop_event`/`Budget.stop`; no claim of a remote dashboard-to-worker kill channel. Container example is a starting point, not complete isolation. Run reviewed images with non-root user, read-only filesystem, dropped capabilities, no Docker socket, CPU/memory/PID limits, and external deny-by-default egress that only permits the approved providers and Encased. `--network=none` can demonstrate offline denial but cannot reach the hosted gateway. Customer-specific egress proxy/firewall rules and TLS/DNS handling must be independently deployed and tested; this Dockerfile does not silently claim to install those rules. ## Validation and release Run `pip install '.[http,providers]'` then `python -m unittest discover -s tests -v`. Runtime tested here on Python 3.13.12, Linux with requests 2.34.2, urllib3 2.8.0, httpx 0.28.1, aiohttp 3.14.5, openai 2.54.0 and anthropic 0.125.0. Provider tests use synthetic HTTP responses without billable model calls. The preview workspace journey was exercised with the real REST gateway: allow once, block, human approval once, human denial, dashboard telemetry and disposable-key revocation. 29 Python tests and 10 existing workspace tests passed. This is functional evidence, not an independent penetration test. Metadata targets 3.11+, but other Python versions, provider SDK releases and customer OS/framework combinations need separate qualification. Existing LangChain/CrewAI adapters in 0.1.0 are NOT claimed as validated enforcement adapters in this release; explicitly decorate tool functions instead. Keep 0.1.0 downloads for existing integrations. Package with `python -m build --sdist`; registry publication needs the owner's PyPI account and a package-name availability check. No automatic PyPI release. Before production: independent bypass tests, external isolation, shared budgets if required, monitored delivery, approval lifecycle extensions, load tests, credential rotation, rollback/incident ownership and customer acceptance evidence.