HUB
Sign inSign up
agentcloak-pre-router logo

agentcloak/agentcloak-pre-router

By agentcloak

•Updated about 3 hours ago

AgentCloak Pre-Router is an OpenAI-compatible proxy that replaces sensitive data with tokens

Image
Machine learning & AI
Data science
Web servers
0

117

agentcloak/agentcloak-pre-router repository overview

⁠AgentCloak Pre-Router

AgentCloak Pre-Router is an Open AI- compatible privacy proxy that replaces sensitive data in every outgoing request with context-preserving synthetic substitutes, and then puts the real values back into the response before it reaches your application. Your AI application sends and receives real values like names and the provider only sees placeholders.

Integration is one change: point your OpenAI SDK’s base URL at the Pre-Router. Your provider API key and your code stay the same. Compatible with OpenAI-compatible APIs including OpenAI, Azure OpenAI, OpenRouter, vLLM, Ollama, LiteLLM, and others.

Full documentation: configuration reference, detection tuning, placeholders, custom rules, supported endpoints, and errors are described at docs.incountry.com/agentcloak/agentcloak-pre-router⁠.

⁠What is in the image

Container pathContents
/app/agentcloak-server.yamlThe default configuration
/app/models/gliner2-pii-multi/The multilingual GLiNER2-PII detection model (Fastino, Apache-2.0)
/app/models/lexicons/Word lists of the detection safety nets: English, German, French, Spanish, Italian, Dutch
/app/data/A volume for the conversation database (SQLite)
/app/licenses/NOTICELicenses of the included model and word lists

The server has one OpenAI-compatible route, /to/v1/openai, and protects chat completions, responses, embeddings, and file attachments (text, Markdown, Office, OpenDocument, RTF, EPUB, CSV, and PDF), in chat and responses requests and through the Files API. It listens on port 5050 and runs as a non-root user. Platforms: linux/amd64, linux/arm64.

This is a preview release. It works through 31 January 2027 (UTC), and logs that date at startup. After that date the server no longer starts, and a running one refuses every request. The next version will offer several license options, which you will be able to obtain from the InCountry portal⁠.

⁠Quick start

openssl rand -hex 32 > conversation-secret

docker run -d --name agentcloak-pre-router \
  -p 5050:5050 \
  -e AGENTCLOAK_CONVERSATION_SECRET="$(cat conversation-secret)" \
  -e OPENAI_BASE_URL="https://api.openai.com/v1" \
  -v agentcloak-data:/app/data \
  --memory 4g --cpus 2 \
  --read-only --tmpfs /tmp \
  --cap-drop ALL --security-opt no-new-privileges:true \
  --restart unless-stopped \
  agentcloak/agentcloak-pre-router:1.0.0

Keep the conversation secret stable: changing it starts new conversations for every caller. agentcloak-data keeps conversations across restarts and image updates. To keep the database in a host folder instead, make the folder writable by user id 65532 and mount it:

mkdir -p data && sudo chown 65532:65532 data
# then: -v "$PWD/data:/app/data"

Loading the model takes a few seconds. A configuration problem, such as a missing AGENTCLOAK_CONVERSATION_SECRET, stops the server at startup with an error naming the setting (docker logs agentcloak-pre-router). GET / is the health check and answers "status": "healthy" once the server is ready:

curl http://localhost:5050/

Send a request through it with your provider key:

curl http://localhost:5050/to/v1/openai/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "Say hello to Ada Lovelace."}]}'

The answer mentions Ada Lovelace by name, while the provider received a stand-in name. Then use http://<host>:5050/to/v1/openai as the base URL of your OpenAI client:

import os

from openai import OpenAI

client = OpenAI(
    base_url="http://localhost:5050/to/v1/openai",
    api_key=os.environ["OPENAI_API_KEY"],  # your provider key, unchanged
)

reply = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Write a thank-you note to Ada Lovelace."}],
)
print(reply.choices[0].message.content)  # mentions "Ada Lovelace"

⁠Environment variables

VariableDefaultMeaning
AGENTCLOAK_CONVERSATION_SECRETnone, requiredProtects the link between an API key and its conversations. Generate it once with openssl rand -hex 32 and keep it stable.
OPENAI_BASE_URLhttps://api.openai.com/v1The provider, version prefix included, for example https://openrouter.ai/api/v1.
AGENTCLOAK_DB_PATH/app/data/agentcloak.dbThe conversation database file.
RUST_LOGinfo,ort=warnLog level.

⁠Docker Compose

Create .env:

OPENAI_BASE_URL=https://api.openai.com/v1
AGENTCLOAK_CONVERSATION_SECRET=<output of: openssl rand -hex 32>

and docker-compose.yml:

services:
  agentcloak-pre-router:
    image: agentcloak/agentcloak-pre-router:1.0.0
    ports:
      - "5050:5050"
    environment:
      OPENAI_BASE_URL: ${OPENAI_BASE_URL:-https://api.openai.com/v1}
      AGENTCLOAK_CONVERSATION_SECRET: ${AGENTCLOAK_CONVERSATION_SECRET:?set AGENTCLOAK_CONVERSATION_SECRET in .env}
    volumes:
      - agentcloak-data:/app/data
    mem_limit: 4g
    cpus: 2
    read_only: true
    tmpfs:
      - /tmp
    cap_drop:
      - ALL
    security_opt:
      - no-new-privileges:true
    stop_grace_period: 30s
    restart: unless-stopped

volumes:
  agentcloak-data:

⁠Detection

The default configuration detects people, companies, locations, and email addresses with the model, and email addresses again with a pattern. Three safety nets look for hints of a name the model scored too low and replace it:

  • Cue words: a capitalized word after a title, greeting, or naming word (Mr, Herr, Mme, Sra, Dhr, Dear, Liebe, Hola, named, von, and others).
  • Boundary: a capitalized word right next to a detected name that the detection stopped short of, such as the last part of a double surname.
  • Unknown words: a capitalized word that none of the common-word lists holds.

Measured on 3,000 texts in the six languages, with 4,340 names, cities, streets, and email addresses:

Without safety netsWith safety nets
Values fully replaced98.2%99.0%
Over-replaced spans per text0.440.46
Time per text35.5 ms35.4 ms

⁠Safety Check

Important: test the Pre-Router on your own data before using it in production. Personal data detection is statistical. AgentCloak Pre-Router’s three pass architecture achieved 99% of values detected in English leaving only fragments. Results on your traffic depend on language, format, and types of personal data. Run a representative sample of your own requests through it and confirm that every value you must protect is replaced. Repeat the check after every configuration change or image update.

⁠Placeholders

People and companies get realistic stand-in names (Jane Doe), so the provider's model reads natural text. Locations and email addresses get tags such as LOCATION_a497a9. The same value gets the same placeholder everywhere in a request and for the whole conversation, and different requests and conversations get different placeholders, so they cannot be linked through them.

Other placeholder types can be configured: keyed tags that stay the same for a value across all conversations (keyed_pseudonym with salt_scope: tenant, which makes the output pseudonymised rather than anonymised) and numbered tags (counter, PERSON_1).

⁠Conversations and multiple users

The Pre-Router serves many users at once and keeps each one's data apart. With the default configuration, a conversation belongs to one provider API key: the conversation database holds a keyed hash of the key, never the key itself, and a caller with another key cannot reach a conversation, even with the same conversation id. Callers sharing one API key share conversations.

To tell turns apart, send a conversation id in the X-Conversation-Id header (not forwarded to the provider). Without one, a conversation is recognised from the Responses API conversation or previous_response_id, or from the opening messages when your client resends the full history.

When all users share one provider key, put your own sign-in in front of the provider: define an identity provider policy under auth:, reference it on the route, and set conversation.scope: principal. Each signed-in user's conversations are then private to them.

⁠Changing the configuration

Copy the default configuration out of the image, edit it, and mount it back:

id=$(docker create agentcloak/agentcloak-pre-router:1.0.0)
docker cp "$id:/app/agentcloak-server.yaml" ./agentcloak-server.yaml
docker rm "$id"
# then add: -v "$PWD/agentcloak-server.yaml:/app/agentcloak-server.yaml:ro"

Keep server.bind at 0.0.0.0:5050 and the /app/models/... paths. The configuration is read at startup; restart the container after editing it.

You can add your own detection rules to the stages: list of the chat pipeline, after the ner_detector. Mount word list files next to the configuration, for example with -v "$PWD/custom:/app/custom:ro"; relative paths resolve against /app.

      # Customer numbers such as CUST-004211, always tagged as customer_id.
      - type: static_processor
        pattern: '\bCUST-\d{6}\b'
        label: customer_id

      # Project code names from a word list, one per line.
      - type: static_processor
        label: project
        matcher:
          type: dictionary
          entries: [{ path: custom/projects.txt }]
          case: insensitive

      # The name after "Patient:" must be replaced, or the request is refused
      # with 422 cloak_failed and nothing is sent to the provider.
      - type: guard
        pattern: '\b[Pp]atient:\s*(\p{Lu}[\p{L}''-]+)'
        on_failure: { type: retry_with_confidence, min_confidence: 0.05 }

A static_processor finds values the model does not know and gives them a category, also relabeling a detection that contains a match. A guard checks that every match of its pattern lies inside a detection and, if not, goes on, detects again with other settings, or refuses the request. Test a guard on your own data: one that refuses requests also refuses text where the hint is a false alarm.

⁠Telemetry

Logs go to stdout, one JSON line per event, so any log shipper (Promtail, Grafana Alloy, Fluent Bit, Vector, the Docker logging drivers) can collect them. server ready marks readiness. Each request logs one line with its route, status, duration, and request_id, which the response echoes in x-request-id. RUST_LOG sets the level.

Traces, metrics, and logs over OpenTelemetry (OTLP over HTTP/protobuf) go to any OTLP receiver: an OpenTelemetry Collector, Grafana Alloy or the LGTM stack, Grafana Cloud, Datadog, Honeycomb, New Relic, and others. Export is off until the configuration has a telemetry: section. Add one to your copy of the configuration (see Changing the configuration⁠):

telemetry:
  service:
    attributes:
      deployment.environment.name: production
  exporter:
    # Base URL: /v1/traces, /v1/metrics, and /v1/logs are appended.
    endpoint: http://otel-collector:4318
    headers:
      authorization: "Bearer ${OTEL_TOKEN}"   # for a hosted backend; omit otherwise

A key the section does not write falls back to its standard variable, so telemetry: { exporter: {} } with -e OTEL_EXPORTER_OTLP_ENDPOINT=... works too. OTEL_SERVICE_NAME (default agentcloak-server), OTEL_RESOURCE_ATTRIBUTES, OTEL_TRACES_SAMPLER and OTEL_TRACES_SAMPLER_ARG, and OTEL_METRIC_EXPORT_INTERVAL are read the same way; OTEL_SDK_DISABLED=true turns export off.

Defaults: every trace is sampled, down to one span per detection pipeline run; metrics are pushed every 60 seconds; log records at warn and above are exported. An incoming traceparent is linked rather than joined, so a client cannot force sampling; set traces.incoming_context: follow behind a trusted gateway. Export never blocks a request: if the collector is down, signals are dropped and counted.

Main metrics, as named in Prometheus:

MetricWhat it shows
http_server_request_duration_secondsRequest latency by route, status, and error_type
agentcloak_cloak_duration_secondsTime to detect and replace, by pipeline and outcome
agentcloak_cloak_permit_wait_secondsTime waiting for a free model copy: raise sessions when it grows
agentcloak_cloak_values_totalValues replaced, by pipeline
http_client_request_duration_secondsProvider latency by status
db_client_operation_duration_secondsConversation database latency
agentcloak_license_valid_until_secondsPreview license expiry

Telemetry carries shape, never content: no request or response text, placeholders, API keys, or conversation ids appear in logs, spans, metrics, or their attributes.

⁠Example: Grafana LGTM

grafana/otel-lgtm⁠ runs a Collector, Tempo, Prometheus, Loki, and Grafana in one container, suited to trying telemetry out. Add it to the Docker Compose file above, mount your configuration with the telemetry: section, and point the exporter at it:

services:
  agentcloak-pre-router:
    # ...as above, plus:
    environment:
      OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-lgtm:4318
    volumes:
      - ./agentcloak-server.yaml:/app/agentcloak-server.yaml:ro

  otel-lgtm:
    image: grafana/otel-lgtm:latest
    ports:
      - "3000:3000"   # Grafana, admin / admin

with telemetry: { exporter: {} } in agentcloak-server.yaml. In Grafana, Explore shows traces in Tempo (service.name = agentcloak-server), metrics in Prometheus, and logs in Loki ({service_name="agentcloak-server"}), each log record linked to its trace. For production, send to your own Collector or hosted backend the same way.

⁠Production notes

  • Test first on a representative sample of your own requests, and again after every configuration change or image update.
  • HTTPS. Put the Pre-Router behind a reverse proxy that terminates TLS. Your users' provider keys travel in request headers.
  • Resources. Detection runs on the CPU. Each loaded copy of the model takes about 1.2 GiB of memory; the default configuration loads two. Allow at least 2 CPUs and 4 GiB of memory.
  • Conversation data. The database on /app/data holds the original values of each conversation so answers can be restored. Restrict access to the volume and include it in your retention policy. A conversation with no activity for a day expires and is deleted; clients that resend the full chat history keep working after it expires.
  • One container per database. Keep the database on a local disk, not a network file system, and do not share one file between containers.
  • Fails closed. If personal data cannot be detected and replaced, or detection takes too long, the request is rejected and nothing is sent to the provider.

⁠Documentation

The full documentation is at docs.incountry.com/agentcloak/agentcloak-pre-router⁠.

Contact [email protected]⁠ with questions or feedback

⁠Licenses

Third-party licenses of the included model and word lists are in /app/licenses/NOTICE inside the image.

Tag summary

Content type

Image

Digest

sha256:7fc194df4…

Size

1.1 GB

Last updated

about 3 hours ago

docker pull agentcloak/agentcloak-pre-router