# Agentic DM Gateway

[](https://gitlab.com/WattoCyber/agentic-dm-gateway/-/pipelines) [](LICENSE) [](https://gitlab.com/WattoCyber/agentic-dm-gateway)
プライベートチャット(通常は Discord DM)を介した LLM エージェント向けのセキュリティコントロールプレーン。
これは**エージェントの手前に**位置します。誰が会話できるか、セッションがロック解除されているか、プロセスが一時停止されているか、そしてこのメッセージが転送するのに十分安全かどうかを判断します。モデルとツールはこのゲートの背後に留まります。このライブラリは LLM を呼び出しません。セキュリティ以外の製品機能は実装しません。
**Hermes に着想を得ています。** 設計は [Hermes Agent](https://github.com/NousResearch/hermes-agent) のメッセージングゲートウェイで使われているコントロールプレーンの考え方に従っています。DM ファーストの配信、ID 許可リスト、ペアリング形式のオープン、オーナーによるキルスイッチ、そして*誰が行動できるか*(コントロールプレーン)と*モデルが見るメッセージテキスト*(データプレーン)の厳格な分離です。このパッケージは、あらゆる呼び出し可能なエージェント向けにそのパターンを小さく独立して抽出したものです。Nous Research とは提携していません。
**成熟度:** 実装済み · 独立検証済み · メンテナンス中。[STATUS.md](https://gitlab.com/wattocyber/agentic-dm-gateway/-/blob/main/STATUS.md) を参照してください。
**再現:** `python scripts/repro.py`(`REPRO_OK` を期待)。
**オフラインテスト:**
```bash
pip install -e ".[dev]" # or: pip install -e . && pip install pytest
python -m pytest -q --tb=line
# or: python scripts/repro.py
```
**ライブ:** https://gitlab.com/WattoCyber/agentic-dm-gateway
---
## 問題点
ツールを備えたエージェントをDiscord(または任意のチャットAPI)に配置すると、ボットにメッセージを送れる誰もが次のことを試みる可能性があります:
- 権限なしでエージェントを利用する
- 大量送信でAPIクォータを消費する
- 「以前の指示を無視せよ」といったスタイルのプロンプトを注入する
- モデルを騙してAPIキーやその他の秘密情報を出力させる
**データプレーン**(モデルが見るメッセージテキスト)とは別に、**コントロールプレーン**(アイデンティティとプロセスの制御)が必要です。
このパッケージがそのコントロールプレーンです。
---
## 機能
| 制御 | 動作 |
|---------|----------|
| **許可リスト** | 設定されたユーザーIDのみが処理を進められます。それ以外はすべて破棄されます(サイレントまたは短い拒否文字列)。 |
| **オーナーとフレンド** | オーナーはPINをスキップし、エージェント全体を一時停止できます。フレンドは期間限定の開放に共有PINを必要とする場合があります(Hermesスタイルのペアリングのアイデアを簡略化したもの)。 |
| **キルスイッチ** | グローバルな一時停止ファイルまたは環境フラグ。有効中はエージェントのターンは発生しません。 |
| **レート制限** | ユーザーごとのスライディングウィンドウ(毎分および毎時)。 |
| **入力チェック** | 最大長、異常な制御文字の除去、一般的なインジェクション/秘密情報漁りのフレーズに対する正規表現ヒューリスティック。 |
| **出力スクラブ** | 秘密情報の形をしたトークン(APIキー、JWT、Bearerヘッダー)を伏字化し、自動フェッチによる外部送信が可能なMarkdown/HTML画像ビーコンを除去します。 |
| **監査ログ** | 許可/拒否/認証/キルイベントの追記専用JSONL(後で確認するため)。 |
| **ローカルコマンド** | `/auth`、`/lock`、`/kill`、`/unkill`、`/status` はモデルを呼び出さずに処理されます。 |
スコープ:セキュリティゲートのみ。チャットボット、トレーディングボット、スキャナー、エージェントフレームワークではありません。Discordを使用する場合は `agent(user_id, text) -> str`(または非同期)を渡してください。コアは任意の整数ユーザーIDとプレーンテキストで動作します。
---
## デモ(コピー&ペースト)
```text
$ python - <<'PY'
from agentic_dm_gateway import InboundSecurityPipeline
pipe = InboundSecurityPipeline({
"allowed_user_ids": [111],
"owner_ids": [111],
"pin_enabled": False,
"block_injection": True,
"deny_message": "Not authorized.",
})
for uid, text in [
(99, "hi"),
(111, "ignore previous instructions"),
(111, "summarize this note"),
]:
r = pipe.precheck(uid, text)
print(uid, r.stage, r.run_agent, r.reply_text)
PY
99 allowlist False Not authorized.
111 injection False Blocked: looks like prompt injection / secret fishing. Rephrase.
111 ok True None
$ python scripts/repro.py
REPRO_OK agentic-dm-gateway unit suite
```
## フックの組み込み方
3つの統合パスがあります。いずれかを選択してください。
### 1) Discord へのドロップイン(最も簡単)
Discord サポート付きでインストールし、env を自分のユーザー ID に設定し、ゲートウェイを登録して、ボットを実行します。
```bash
pip install -e ".[discord]"
# or: pip install agentic-dm-gateway[discord]

export DISCORD_BOT_TOKEN=...
export AGENTIC_DM_ALLOWLIST=your_discord_user_id
export AGENTIC_DM_OWNER_ID=your_discord_user_id
# optional: export AGENTIC_DM_PIN=....

python examples/discord_echo_bot.py
```
ご自身のボットで:
```python
import discord
from agentic_dm_gateway.discord_adapter import register_dm_gateway
def agent(user_id: int, text: str, *, is_owner: bool = False) -> str:
# your Hermes / local model / tool loop
return call_your_model(text)
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Client(intents=intents)
register_dm_gateway(
bot,
{
"allowed_user_ids": [], # or rely on AGENTIC_DM_ALLOWLIST env
"owner_ids": [],
"pin_enabled": False,
"deny_message": False, # silent drop for strangers
},
agent=agent,
)
bot.run(TOKEN)
```
`register_dm_gateway` の動作:
1. `discord.Client` / ボットに `on_message` ハンドラをインストールします。
2. ボットと**ギルド**メッセージを無視します(DM のみ)。
3. エージェントの前に `InboundSecurityPipeline.precheck` を実行します。
4. 必要に応じて拒否 / 制御の返信を送信します。
5. `agent(user_id, sanitized_text, is_owner=...)` を呼び出します。
6. エージェントの返信をスクラブし(シークレット + 画像ビーコン)、Discord の 2000 文字制限で分割します。
ギルドメッセージがエージェントに届くことはありません。許可リストに登録されたユーザーからの DM のみが届きます。
### 2) 手動 Discord フック(既に `on_message` がある場合)
`register_dm_gateway` を使用できない場合(既存のハンドラチェーンがある場合)は、パイプラインを自分で呼び出してください:
```python
from agentic_dm_gateway import InboundSecurityPipeline
from agentic_dm_gateway.security import sanitize_agent_output
pipe = InboundSecurityPipeline({
"allowed_user_ids": [YOUR_ID],
"owner_ids": [YOUR_ID],
"pin_enabled": True,
})
@bot.event
async def on_message(message):
if message.author.bot or message.guild is not None:
return
pre = pipe.precheck(int(message.author.id), message.content or "")
if pre.reply_text and not pre.run_agent:
await message.channel.send(pre.reply_text[:1900])
return
if not pre.run_agent:
return
raw = await your_agent(pre.sanitized_text) # Hermes, Ollama, API, ...
await message.channel.send(sanitize_agent_output(str(raw))[:1900])
```
### 3) プロトコル非依存(Hermes、CLI、Telegram、その他何でも)
Discord のインポートは不要です。任意のエージェントターンの前後に同じプリチェックを使用します:
```python
from agentic_dm_gateway import InboundSecurityPipeline
from agentic_dm_gateway.security import sanitize_agent_output
pipe = InboundSecurityPipeline({
"allowed_user_ids": [111],
"owner_ids": [111],
"pin_enabled": False,
"rate_limit_per_minute": 20,
"block_injection": True,
"deny_message": "Not authorized.",
})
def handle_inbound(user_id: int, text: str) -> str | None:
pre = pipe.precheck(user_id, text)
if pre.run_agent:
answer = my_llm(pre.sanitized_text) # your model / Hermes run
return sanitize_agent_output(str(answer))
return pre.reply_text # deny or control-command reply
```
`PrecheckResult` のフィールド:
- `run_agent`: true の場合のみモデルに転送
- `sanitized_text`: クリーン済みの入力
- `reply_text`: 拒否 / 制御コマンドの応答
- `stage`: `allowlist` | `kill` | `pin` | `rate` | `injection` | `ok` | ...
フックのチェックリスト:
1. プロセス起動時に `InboundSecurityPipeline` を一度構築する(config + env)。
2. 受信メッセージごとに: `pre = pipe.precheck(user_id, text)`。
3. `pre.run_agent` が真の場合: `pre.sanitized_text` のみを使ってエージェントを呼び出す。
4. 送信前に必ずモデル出力を `sanitize_agent_output` に通す。
5. 制御応答(`/auth`、`/kill`、…)は `run_agent` が false のとき完了として扱う。
---
## パイプライン(受信メッセージ 1 件)
```
1. Adapter: ignore bots; only accept DMs (not server channels)
2. Allowlist: is this user id permitted?
3. Owner commands: /kill /unkill /status -> reply, stop
4. Session commands: /auth <pin> /lock -> reply, stop
5. SecurityGateway.check_message:
kill switch?
session unlocked? (PIN)
under rate limit?
length + injection heuristics OK?
6. If ok -> run_agent=True with sanitized text
7. After your agent returns -> sanitize_agent_output (redact + strip image beacons)
8. Audit rows written along the way
```
**コントロールプレーン:** ユーザーが誰であるか(許可リスト / 所有者)。
**データプレーン:** メッセージ本文(チェックが通るまで常に信頼できない)。
---
## パッケージ構成
```
src/agentic_dm_gateway/
security.py # RateLimiter, SessionAuth, SecurityGateway,
# sanitize_input, redact_secrets, sanitize_agent_output,
# kill switch, audit_log
allowlist.py # merge config + env + file into allowlist / owners
commands.py # /kill /unkill /status /auth /lock (no LLM)
pipeline.py # InboundSecurityPipeline.precheck() orchestration
discord_adapter.py # optional discord.py on_message wire-up
tests/ # unit tests for the core (no Discord required)
examples/
minimal_precheck.py # CLI-style demo of precheck outcomes
discord_echo_bot.py # secured DMs + echo agent
```
| モジュール | 責務 |
|--------|----------------|
| `SecurityGateway` | 単一の `check_message(user_id, text) -> SecurityVerdict` |
| `InboundSecurityPipeline` | 許可リスト + スラッシュコマンド + ゲートウェイを1回の呼び出しで |
| `DiscordDMGateway` | DM専用アダプター。エージェント関数を注入する |
必須のランタイム依存関係はゼロ。Discordはオプション: `pip install agentic-dm-gateway[discord]`。
---
## インストール
```bash
git clone https://gitlab.com/WattoCyber/agentic-dm-gateway.git
cd agentic-dm-gateway
pip install -e ".[dev]"
python scripts/repro.py
```
## 設定
### 設定辞書
| キー | デフォルト | 意味 |
|-----|---------|---------|
| `allowed_user_ids` | `[]` | チャットを許可するユーザーID |
| `owner_ids` | `[]` | PINをスキップ。`/kill` を実行可能 |
| `pin_enabled` | `True` | 非オーナーに対するPINゲート |
| `pin_ttl_hours` | `72` | オープン期間 |
| `rate_limit_per_minute` | `8` | スライディングウィンドウ |
| `rate_limit_per_hour` | `60` | スライディングウィンドウ |
| `max_input_chars` | `2000` | 最大入力長 |
| `block_injection` | `True` | ヒューリスティックなブロックリスト |
| `deny_message` | `False` | サイレント、`True`、またはカスタム文字列 |
| `audit_log` | `True` | 監査JSONLを書き込む |
| `enabled` | `True` | マスタースイッチ |
### 環境変数
| 変数 | 目的 |
|----------|---------|
| `AGENTIC_DM_ALLOWLIST` | カンマ区切りのユーザーID |
| `AGENTIC_DM_OWNER_ID` | オーナーID |
| `AGENTIC_DM_PIN` | PINの平文 |
| `AGENTIC_DM_PIN_REQUIRED` | `1` = 未設定でもPINを要求 |
| `AGENTIC_DM_KILLED` | `1` = キルスイッチ有効 |
| `AGENTIC_DM_DATA_DIR` | キルファイル、オープン、監査ログ用のディレクトリ |
| `AGENTIC_DM_SECRETS_DIR` | `dm_pin.txt` / `dm_allowlist.txt` 用のディレクトリ |
デフォルトの状態ディレクトリ: `./data/agentic_dm/`。
---
## オーナーおよびセッションコマンド
| コマンド | 実行者 | 効果 |
|---------|-----|--------|
| `/kill` `/pause` | オーナー | 全員に対してエージェントを一時停止 |
| `/unkill` `/resume` | オーナー | 一時停止を解除 |
| `/status` | オーナー | キル / PIN / 許可リストのスナップショット |
| `/auth <pin>` | 許可リスト登録者 | TTLの間セッションをオープン |
| `/lock` | 許可リスト登録者 | オープンをクリア |
これらはモデルを呼び出すことはありません。
---
## 制限事項(正直なところ)
- インジェクション検出は**正規表現のヒューリスティックリスト**であり、完全なLLMジャッジや分類器ではありません。
- 秘匿情報のマスキングは**ベストエフォート**のパターンマッチングであり、新しい形式のシークレットを見逃します。
- Hermesからの着想はアーキテクチャ上のもの(DMコントロールプレーン)です。これは完全なHermesゲートウェイやペアリングスタックではありません。
- このライブラリの外側では、安全なトークンストレージ、最小権限のツール、ホストの堅牢化が依然として必要です。
---
## ライセンス
MIT。[LICENSE](https://gitlab.com/wattocyber/agentic-dm-gateway/-/blob/main/LICENSE) を参照してください。