# Dark Knight Agent Framework

DKAF packages a single-owner assistant you talk to from your own Telegram DM, together with
its restricted routing services and one-machine deployment template. The John's Harness Light
gateway, control UI and connection-aware context profile are embedded; there is no separately
installed Harness or proxy add-on. `dkaf` on a laptop is an offline packaging/configuration CLI.
Installing it **does not** change the laptop's routes or start a less-private local agent.

**Telegram is the control channel, not a tool.** A fresh install only needs a bot token and your
numeric Telegram user ID: the Machine boots, answers your DM, and reports what is still
unconfigured — with no model, no VPN and no public web origin. Model replies come from a local,
deterministic setup guide until you connect a model endpoint.

**Not a verified Fly deployment.** This is for ordinary browser, search and connected email
tasks. No shell, node/device tools, arbitrary URL fetch API, external browser relay or spawned
agents are enabled in the assistant tool allowlist. Graph CLI is x64-only upstream; Outlook is
not available in the ARM64 image.

## What goes where

| Request | Network path |
|---|---|
| Owner DMs, commands and replies | Direct TCP 443 to `api.telegram.org` through a local relay pinned to Telegram's published Bot API addresses. One destination, one port, one tunnel type; TLS is verified by the Telegram client, so a stale pin fails closed. No DNS is used. |
| Browser navigation and `ddg_search` | Local headless Chromium → owner's Proton WireGuard tunnel. Search uses the DuckDuckGo Lite page; if unavailable/challenged, it reports failure. No search API or Brave/Exa fallback. |
| Connected Gmail / Outlook, including token refresh | Light's email extension launches `gog` / `mgc` inside the same network and filesystem sandbox. |
| Tool DNS | Only the configured tunnel resolver is listed. Port 53 to other resolvers is blocked on the tunnel. No host resolver fallback; Chromium's secure DNS is disabled. |
| Selected model | Only `POST /chat/completions` against the owner's HTTPS base URL. Supports OpenAI Chat Completions-compatible streaming/tool calling, not arbitrary provider protocols. |
| Optional MemoryRouter | Only the fixed prepare/ingest/search/date-search/inspect/warmup/consolidation POST routes at the owner's HTTPS service. No imports, URL proxy, redirects or fetch-by-URL API. |
| Incoming UI / WebSocket (optional) | Raw TCP port 443 to app port 8443; the app presents the owner's cert. No Fly HTTP or TLS handler. Gateway token and normal device pairing still apply. |

The Linux bootstrap creates a WireGuard interface in the outer network namespace and **moves** it
into an initially empty one. Only the encrypted UDP socket remains outside. The assistant has
loopback plus that tunnel interface: no veth, default gateway to the host, or general-purpose
forward proxy. Default-drop workload nftables rules block IPv6 independently of sysctls. An outer
Machine firewall also limits new IPv4 flows to the numeric VPN peer and three separate connector
UIDs' pinned HTTPS addresses — the model/memory connector, the certificate ingress and the
Telegram relay each reach only their own destinations. Replies to incoming management/TLS
connections and IPv6 neighbor discovery are infrastructure traffic, not tool egress. A private
PID/mount/IPC sandbox hides host `/proc`, `/run`, secrets and devices; the workload runs as UID
31001, no capabilities, no new privileges, with a socket-family filter. Chromium's renderer
sandbox stays on. Browsers, OAuth helpers and descendants inherit the boundary. Failure to create
the boundary stops startup.

The direct services use fixed Unix sockets, separate local capability tokens, owner-configured
or fixed public IPv4 addresses, TLS SNI and certificate verification for the configured DNS name.
They relay only specific methods/paths (or, for Telegram, a single CONNECT destination), replace
caller headers and inject upstream credentials. No DNS lookups are needed for these links or the
numeric WireGuard peer. If a service IP rotates, update its pin and restart; there is no alternate
destination. Losing Proton stops tools, not the control channel — that is deliberate, so you can
fix the tunnel from the same DM. A failed internet link for the whole Machine can of course stop
everything.

This does not anonymize accounts or prompts. Telegram sees DM contents and the bot token; the
model sees prompts, MemoryRouter sees submitted memories, and email providers know the
authenticated account. The endpoints of direct connections see the Machine's egress IP. Proton is
the tool-traffic intermediary; a website can still recognize a signed-in user or browser. Fly
hosts the computation and can access process memory. One trusted owner per Machine; no defense
against a malicious host/kernel, compromised provider, stolen operator token or secrets that a
user deliberately pastes into a tool. Browser login on a separate personal device is outside this
boundary.

## Local package / deployment preparation

```sh
npm install -g dark-knight-agent-framework
dkaf verify
dkaf init ./dkaf-machine
```

`init` requires a **new** directory; it will not overwrite anything. It exports the embedded
runtime, image recipe, fixed services and `fly.toml`. `docker build -t dkaf ./dkaf-machine` builds
the same one-container image. Build-time downloads include public registry dependencies, Chromium
and the architecture-specific pinned email CLIs. Build traffic is not runtime traffic. Nothing
here provisions, deploys, publishes, reads your existing assistant's state or edits system
networking on the laptop.

### Owner inputs — configure once

Create a private JSON file **outside** the repo/build context (`chmod 600`). `telegram` is what
makes the instance administrable from your DM; `model`, `proton`, `memory` and `ingress` are all
optional and can be added later.

```json
{
  "telegram": {"botToken":"<bot id>:<secret>","ownerId":"<your numeric Telegram user id>"},
  "model": {"baseUrl":"https://model.example/v1","address":"<current public IPv4>","id":"<model ID>","apiKey":"<your key>"},
  "memory": {"baseUrl":"https://memory.example","address":"<current public IPv4>","apiKey":"<your memory key>"},
  "ingress": {"origin":"https://agent.example","token":"<at least 32 random non-space characters>","certPem":"<PEM full certificate chain>","keyPem":"<matching PEM private key>"}
}
```

`ownerId` is the numeric ID Telegram assigns to you (`@userinfobot` or a bot `getUpdates`
response). It is the only sender allowed to use commands; everyone else is refused and never sees
state. The bot token is the channel credential: keep it in owner configuration, never in chat.
`dkaf check-config /private/path/owner.json` validates the file without connecting or printing
secrets. Supply it as a read-only file at `/run/secrets/dkaf-owner.json` or as base64 in the
Machine secret `DKAF_OWNER_B64` (base64 is **not** encryption). Use stdin when importing secrets;
never commit them, pass them as image build args or paste them into chat. Rotate owner inputs and
restart for pin/key/cert changes.

## First run, from the DM

1. Create the bot with @BotFather, copy the token, and write the owner JSON above with your own
   numeric ID. `docker build`/deploy the Machine and mount `/data`.
2. Send the bot any message. It replies with the setup guide and refuses anyone who is not the
   configured owner.
3. `/setup` reports the state of the control channel, model, Proton tunnel, MemoryRouter vault and
   the tunnel-only tools, plus the next command. It is a native command: it works with no model
   and no VPN.
4. Add what you want:

   - `/login proton` — create a Linux WireGuard configuration in your own Proton account
     (Downloads → WireGuard configuration), then paste the `.conf` on the single-use owner page the
     bot links to, restart the same Machine with its volume, and send `/login proton` again.
     *Configured* means a file was accepted; *connected* requires a fresh DNS answer through the
     encrypted peer. Without a public origin the same import runs on your private Machine console
     (`docker exec -i CONTAINER /opt/dkaf/deploy/admin.sh proton import < proton.conf`, or
     `fly ssh console -a APP --pty=false -C '/opt/dkaf/deploy/admin.sh proton import'`).
   - `/login MemoryRouter` — the bot links to an owner-only page that runs MemoryRouter's hosted
     consent for `auth.memoryrouter.ai`; sign in, pick the vault, approve read/write/reflect. DKAF
     verifies the vault over MCP and stores the grant outside the harness filesystem. If the
     hosted client registration from this origin is refused, the same consent runs with
     `dkaf login memoryrouter --docker CONTAINER` (or `--fly APP`) on your own computer.
   - `/login model` — an owner-only page for an OpenAI Chat-Completions-compatible HTTPS base URL,
     model ID and key, plus the public IPv4 to pin (or a hostname resolved once at that moment).
     Until this exists, replies come from the local setup guide and no model traffic exists.
   - `/login gmail`, `/login outlook` — email authorization; the Proton tunnel must exist first
     because the mail CLIs inherit the tool boundary.

   None of these accept credentials in chat, and the agent never receives them as prompt text.
   Setup pages are `https://<your origin>/dkaf/setup/<single-use id>`: one kind of secret per page,
   ten-minute lifetime, five submission attempts, no-store/no-referrer/CSP `default-src 'none'`,
   and the submitted secret goes straight to a root broker — the gateway only ever sees the link.
   Ingress (a public HTTPS origin) is what makes those pages reachable; without it the commands
   print console steps instead.
5. The control UI is optional. With `ingress` configured, the gateway is reachable at the
   configured origin with the gateway token and normal device pairing
   (`/opt/dkaf/deploy/admin.sh devices list`, then `… devices approve <requestId>`).

### Fly template (owner-operated; staging gates first)

Set a new app name and region, an appropriately sized persistent volume `dkaf_data` and exactly
**one** Machine (`--ha=false` for initial deploy; confirm final Machine count). Use a public IP
suitable for raw TCP passthrough only if you want the optional control UI: point the custom
hostname at it and provide the matching certificate in-app. Shared IPv4/HTTP edge certificates are
**not** a substitute for raw TCP with app TLS. Fly compute, storage and dedicated IPv4 may cost
money. `fly.toml` has no target app or account identifiers.

**Platform gate:** needs kernel WireGuard, network/mount/PID namespaces, nftables, working
unprivileged Chromium sandbox, working cgroup limits, and sufficient bootstrap privileges. A
generic unprivileged Docker container is not a compatible runtime. Do not remove the sandbox,
enable host networking, expose CDP, or switch to a direct fallback to make a platform start. The
bootstrap, not the agent, needs namespace privileges. Validate Fly's exact kernel, TCP forwarding,
certificate, device pairing, volume and restart semantics before any production claim. The
bootstrap refuses to store credentials on an unmounted `/data`.

### Email connections

Only authenticated tools appear in Light's tool schema. All owner setup commands run via the
private Machine console inside the workload namespace, not via public HTTP. For Google, provide an
owner-managed desktop OAuth client JSON in the agent's private volume (owner UID 31001, mode 0600;
e.g. `/data/agent/google-client.json` is `/home/agent/google-client.json` inside). Use
`/opt/dkaf/deploy/admin.sh gmail credentials /home/agent/google-client.json`, then
`… gmail add <address> --services gmail --manual` and follow Google's prompts. `… gmail list` checks
stored account metadata. For Outlook on x64, `… admin.sh outlook --help` shows the installed
Microsoft Graph CLI's login flags; authorize with the intended account and only the required Graph
scopes. Check keyring/cache persistence on the target; a persistent token and a successful account
read after restart are acceptance gates. Real account OAuth and delivery are not asserted by
fixture tests. Do not put OAuth refresh tokens in the npm package or Docker layers.

### Release checks

1. Inspect the **packed** tree including the nested Light tarball, scan for secrets/private URLs,
   install the tarball in an empty prefix, and run `dkaf verify`, `init` and offline validation.
   Recheck the public registry name immediately before any authorized publication; a 404 is not a
   reservation.
2. `npm test` covers owner/Telegram validation, the CONNECT-only relay, command authorization and
   the model-less setup turn. `node tests/setup-guide.mjs <prepared-light-dir>` proves an owner DM
   is answered with no model at all; `node tests/light-smoke.mjs <prepared-light-dir>` runs a fake
   completion against the real runtime. For an isolated disposable Linux VM,
   `tests/linux/accept.sh` exercises a WireGuard fixture peer, both direct TLS services and outside
   capture (script documents requirements). It never uses Proton credentials.
3. In a separately authorized Fly staging run: observe the outer interface from outside the
   workload (IPv4 **and** IPv6), load the real model and MemoryRouter, use a browser/DDG search,
   Gmail/Graph read and OAuth refresh. Cut WireGuard during an in-flight request. Assert there is
   **no** direct retry or DNS leak, that Telegram still answers, model/MR still work, and recovery
   works after the tunnel returns. Verify public port 443 actually serves your app certificate, no
   alternate listener is reachable and an unpaired/unauthenticated client cannot operate the
   gateway. Never treat a passing local fixture as a Fly/Proton/account test.
4. Confirm the Telegram relay is the only new direct exception: one destination, one port, one
   CONNECT tunnel per call, pinned addresses, and no plain-HTTP or other-host path.

Embedded MIT upstream: `johns-harness-light` commit `7c72f99ed5efafecb6566422aca75a76ac973525`
(see `upstream/LICENSE` and SHA-256 manifest). `scripts/vendor-light.sh` exports only tracked
runtime paths from that revision — including `extensions/telegram` — never the working tree or user
settings. Only the email, optional MemoryRouter, Telegram channel and DKAF search extensions are
loaded. The upstream archive includes compiled generic providers; they are not search fallbacks or
configured direct exceptions. DKAF is not affiliated with Telegram, Proton, Fly.io or DuckDuckGo.
