PrivAiTe
AGENTS.md47 starsChanged 5 months agoBSD-3-ClauseView on GitHub
PrivAiTe is a self-hosted, OpenAI-compatible proxy that detects PII, replaces it with reversible placeholders before forwarding to the LLM provider, and restores the real values in the response. It is a privacy tool: a single leak defeats its purpose. The rules below each exist because breaking them caused a real bug. Treat them as invariants, not suggestions. 1. Fail closed. If detection/anonymization raises, the request is blocked, never forwarded. pii.on_error defaults to "block"; detector exceptions re-raise (engine._detect_all). Do not add…
- Commits and pushes
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository3 other files it gives its agents.
- docs/llms.txtllms.txt
- llms-full.txtllms.txt
- llms.txtllms.txt
The file
We split this AGENTS.md into the rules it gives an agent
4 rules. About 0 are common, 0 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 11
Fail closed: If detection/anonymization raises, the request is blocked, never forwarded.
- Very specific: line 15
One choke point: Every piece of user text reaches the provider only through PIIEngine._anonymize_text.
- Very specific: line 61
NOT scanned (documented limitation, keep it documented if you change it): messages[].name, top-level user/metadata, tools/functions …
- Very specific: line 134
Run in the repo venv (.venv): pytest, ruff check, ruff format --check, and mypy privaite/ integrations/openwebui/privaite_filter.py …
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
PrivAiTe, guide for AI agents (read this before changing code)
PrivAiTe is a self-hosted, OpenAI-compatible proxy that detects PII, replaces it with reversible placeholders before forwarding to the LLM provider, and restores the real values in the response. It is a privacy tool: a single leak defeats its purpose. The rules below each exist because breaking them caused a real bug. Treat them as invariants, not suggestions.
Non-negotiable invariants
- Fail closed. If detection/anonymization raises, the request is blocked,
never forwarded.
pii.on_errordefaults to"block"; detector exceptions re-raise (engine._detect_all). Do not add a fallback that forwards raw text on error. Startup refuses unsafe configs (see #6). - One choke point. Every piece of user text reaches the provider only through
PIIEngine._anonymize_text. Theblock_entitiesgate lives there. If you add a new field/path that carries user text, route it through the engine, never forward it directly. - Restore parity. Whatever is anonymized must be restored on the way back, in
both streaming and non-streaming:
content,tool_calls[].function.arguments, legacyfunction_call.arguments,reasoning_content/reasoning,refusal, and the audiotranscript. maskandredactare irreversible. They must NOT enter the reversible mapping (mapping.note(), notmapping.add()). Two values that mask to the same string must never cross-restore. Onlyplaceholderandfake_replacementare reversible.- Never log or echo PII. Errors name entity types, never values
(
PIIBlockedError,UnsupportedContentError). No logger call may emit message content or entity values. The reversible map is per-request, in-memory only. The opt-in detection cache (privaite/pii/cache.py) may hold only salted hashes and span metadata (offsets, types, scores, sources): never text, values, anonymized output, or mapping state. Its privacy delta is documented in the README threat model; keep that section in sync if you touch it. - Startup fails fast on unsafe config, it never degrades silently:
pii.enabledwith 0 detectors,merge_strategy: intersectionwith <2 detectors, a Presidio language with no spaCy model, duplicate providermodel_namealiases, and ablock_entitiestype no enabled detector can emit (conservative check: skipped when a detector's producible set is unknown) all raise at boot. - Config defaults are the safety posture, do not flip them casually.
preset: onnx(~85.2% recall),on_error: block,deanonymization.fuzzy_matching: false(fuzzy can mis-substitute), detectortrust_remote_code: false,block_entities: []. - An issued placeholder never equals a string already in the request. The
restore replaces every occurrence, so a pre-existing
<PERSON_1>(a fixture, a template, a planted?to=<EMAIL_ADDRESS_1>) would receive a real value.PIIMapping.reserveruns over the whole request before the first placeholder is issued (_process_requestwithother_fields, both gateway scrubs), the anonymizer swaps a literal that shows up too late (_shield_literals), and the restore is single-pass. A new path that shares one mapping across several calls must reserve the whole body first.
What is and isn't scanned (know the surface)
Scanned: messages[].content (string, multimodal text parts, or bare strings in a
list); tool_calls/function_call arguments parsed as JSON and scrubbed value by
value including numeric leaves with >=7 digits (a card number sent as a bare
number is caught); /v1/completions prompt and suffix; /v1/embeddings
input; chat prediction.content and web_search_options.user_location
(auxiliary request fields, scrubbed input-side via process_request_value, no
restore path needed).
NOT scanned (documented limitation, keep it documented if you change it):
messages[].name, top-level user/metadata, tools/functions definitions,
JSON object keys, and tokenized (integer-array) inputs.
POST /v1/pii/inspect (off by default, pii.inspect.enabled) is a dry run: it
returns the caller's own detections + anonymized preview and forwards NOTHING.
It is the one deliberate exception to "never echo values" (the caller sent the
text; invariant #5 still fully applies to logs, errors and /stats, and the
endpoint module deliberately has no logger). Keep it excluded from /stats.
Gateway: the SECOND scrub surface (privaite/gateway/)
Opt-in agent CLI routes (gateway.enabled, off by default): /v1/messages,
/v1/messages/count_tokens (Anthropic Messages, Claude Code) and /v1/responses
(OpenAI Responses, Codex, beta). They are a parallel request path to
privaite/api/: a core-side fix (a new scanned field, a new restored field, a
gate) is NOT automatically true here. Check both.
- Scrub (
gateway/scrub.py) still goes through the one choke point: every scanned string reachesPIIEngine.scrub_document(hence_anonymize_text), soblock_entitiesand fail-closed apply unchanged. Rules that exist because breaking them leaked: scrub coverage must match restore coverage (restore rewrites every string leaf, so the client holds REAL values insideserver_tool_use/mcp_tool_useblocks and echoes them back next turn: scrub them); tool OUTPUT carriers are where a file the agent read arrives (custom_tool_call_outputand friends, a list of{type,text}parts, not just a string); an Anthropic block type this build does not know is scanned through an allowlist of plaintext field names, never relayed raw. Relayed byte-for-byte:thinking/redacted_thinking, binary and opaque payloads, and the Responses opaque item types. The agent's own prompt (system,instructions) is the one field read but not rewritten: it goes throughPIIEngine.gate_document, soblock_entitiesstill rejects the request while the prompt reaches the provider verbatim. The exact frozensets are documented indocs/gateway.mdand pinned bytests/test_gateway/test_gateway_docs.py: change one, change the other. - Restore (
gateway/restore.py) is NOT the core restore.restore_treerewrites every string leaf of the response except blocks whose type is in the protocol'sskip_restore_types(thinking, encrypted reasoning/compaction), and anargumentsstring is restored on its PARSED tree and re-encoded, never by plain substitution (splicing a raw quote/backslash/newline back into a JSON string literal breaks the client'sjson.loads). - A separate SSE restorer lives here too (
_SSERestorer), driven by the declarative event plans ingateway/protocols.py: oneStreamingDeAnonymizerper text channel so a placeholder split across two events still restores, a flush at channel end and at[DONE]so held-back text is never dropped, andjson_escaped_mappingon JSON-fragment channels (streamed tool arguments) so the spliced original stays a valid piece of the JSON string literal it lands in. Upstream framing (event names, comments,[DONE]) is preserved verbatim. - Relay (
gateway/relay.py):accept-encodingis never forwarded (the proxy must be able to decode what comes back), duplicate header names are relayed verbatim as a list of pairs, an upstream timeout maps to 504 and a transport failure to 502. - Auth: gateway paths are deliberately skipped by
AuthMiddlewarewhen gateway mode is on (the only credential in the request is the client's own upstream token). With the defaultserver.host: 0.0.0.0and no rate limit, an exposed port plus gateway mode is an open endpoint. Documented indocs/gateway.md; do not "fix" it silently in either direction.GET /v1/modelsis shared with the core proxy: in gateway mode the middleware only flags whether the caller holds a valid PrivAiTe key, and the route serves PrivAiTe's list to that caller and relays everyone else to the Responses upstream (Codex needs its upstream catalog). A valid PrivAiTe key never leaves; with auth disabled the route always relays.
Streaming handler (privaite/streaming/handler.py)
Forward the provider's own chunks (preserve id, usage, logprobs, and the real
finish chunk: do not synthesize a duplicate finish). One restore buffer per
choice index (n>1 must not share). Flush held-back text onto the finish chunk and
again after the stream ends without a finish_reason. Never suppress a chunk that
carries any payload other than fully-held-back content.
Before you push or release
- Run in the repo venv (
.venv):pytest,ruff check,ruff format --check, andmypy privaite/ integrations/openwebui/privaite_filter.py integrations/litellm/privaite_guardrail.py. Both the push CI and the publish workflow type-check the integrations: skipping them locally once broke a release. - Version: bump both
pyproject.tomlandprivaite/__init__.py; date theCHANGELOG.mdsection; bump the integration pins (privaite>=X). - Install instructions: every docker tag, pip floor and sentence describing a
behaviour as not yet shipped moves with the release, or the quick start
installs the previous version.
tests/test_docs.pyfails on both. - Docs:
python scripts/gen_llms_full.pyafter ANY documentation change (--checkfails when stale).llms-full.txtis a concatenation and went stale for three releases once;llms.txtanddocs/llms.txtare the same file and must stay identical. - Benchmark: if you touched detection, re-run
privaite-bench(python -m solutions.comparefrom that repo root) and updateCOMPARISON.md+ the README numbers. The published numbers must match the shipped code. - Release:
gh release create vX.Y.Ztriggerspublish.yml→ PyPI (trusted publisher; its Environment field must stay empty). A PyPI version can never be reused, so verify green CI first.
Recognizer vocabulary follows the language
The recognizers PrivAiTe registers itself (privaite/pii/recognizer_*.py) are
registered on every configured language, so any human-language word inside
their regexes reaches text written in another language. A cue made of words
belongs to the language those words come from: declare it in a
LanguagePatterns map (privaite/pii/recognizer_vocab.py), never as a union of
every language's vocabulary. Only patterns with no vocabulary at all (digits,
punctuation, code identifiers) go in the neutral bucket that applies
everywhere. Unioning them is how issue #31 happened, and the same shape then
reported "configured via Terraform" as a location, via being an Italian
street. Stop-word lists are the deliberate exception: they only ever shorten a
match, so a union of languages there stays on the safe side.
A cue that merely means "I am" ("je suis", "I'm", "ik ben") introduces an adjective as often as a name, so it requires a capitalised name; a cue that announces a name ("my name is") accepts any casing.
These recognizers are also exempt from the entities allowlist by design,
so removing a type from that list does not disable them: the knob is
pii.detectors.presidio.disabled_recognizers, whose names are validated at
config load. Anything reasoning about what Presidio can emit must call
builtin_recognizer_entity_types() rather than restate the list.
Integrations must stay in sync with the core
integrations/litellm/privaite_guardrail.py and
integrations/openwebui/privaite_filter.py run the same engine in-process. Any
core behavior change (fuzzy, block gate, a new restored/scanned field) must be
mirrored in both.
Each integration ships as ONE self-contained file (the filter is pasted verbatim
onto the Open WebUI hub), so helpers they share exist as copies, not imports:
_restore_json_tree and _restore_arguments today. The copies are the accepted
price of that constraint, and the failure mode is real: a fix landing in one copy
and not the other (it happened to the filter's declared privaite floor, which
stayed behind while the file's content moved on). When you touch a shared helper
or a mirrored behavior, apply it to BOTH files in the same change, then run
tests/test_integrations/test_parity.py: it compares the copies' ASTs and fails
on drift, and its SHARED_HELPERS list must grow when a new copied helper
appears. If the change is deliberately one-sided, say why in the commit message.
- OpenWebUI filter:
outletmust pop the reversible map (Open WebUI may persist message metadata); do not stash it whendeanonymizeis off; clear any client-supplied incoming map ininlet. - LiteLLM guardrail: scan every Responses
inputitem (role message, tool output, tool-call arguments,input_textpart, bare string), not just a homogeneous list. - The guardrail also lives upstream in the fork
crp4222/litellm, branchfeat/privaite-guardrail(PR #31530 to BerriAI/litellm). Sync fixes there too. Fork PRs targetlitellm_oss_staging, notmain. The fork must pass litellm's gates: ruff-strict (UP006lowercaselist,C901complexity <=10, no net-newAny), type-discipline (LIT007: noTypeGuard/TypeIs), line length 120. Its tests fake theprivaitepackage because it is absent in litellm CI.
Verify, don't assume
Reproduce a suspected bug before fixing it, and re-run the exact command the CI/gate
runs (not a subset). For provider/streaming behavior, test against a real model
through the local proxy (python -m privaite --config <yaml> then curl with
stream: true); running with deanonymization.enabled: false proves the provider
only ever received placeholders.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

