Egress Proxy: Routing Outbound Traffic Through mihomo
简体中文 · Status: 2026-11-20, designed with the owner's decisions and built: pkg/outbound, the Host routing, the mihomo plugin and its tools, verified against mihomo 1.19.34 on macOS.
简体中文 · Status: 2026-11-20, designed with the owner's decisions and built: pkg/outbound, the Host routing, the mihomo plugin and its tools, verified against mihomo 1.19.34 on macOS. Not verified: Linux and Windows natively, Codex and Claude Code (no Runtime adapters yet), a live e2e case through a real channel. Kernel decision: ADR 0011.
1. Scenarios and Decisions
An admin tells the Agent in plain language which outbound traffic goes through which proxy, and pastes the proxy:
- ◆"Put Codex behind this proxy:
vless://…": every connection of the Codex Runtime instance uses that node. - ◆"Send
*.openai.comthrough Japan, then the US": a two-hop chain for one domain, whoever makes the request. - ◆"Proxy web search": the
websearchinstance uses the proxy; the other instances are unchanged.
Owner's decisions of 2026-11-20:
| Question | Decision |
|---|---|
| What "Codex / Claude Code" means | Runtime adapter instances (not built yet; they get their proxy like any child process, section 4) |
| System-wide capture (TUN) | Not done. Only traffic Orquelo makes or starts is routed |
| URL patterns | Domain only (exact or a domain and its subdomains); no path matching |
| Who may change routes | Admins only; every change needs an admin's approval |
2. Outbound Traffic Today
All of it uses one process-wide proxy, the environment: block of the configuration (deployment section 11):
| Traffic | Where | Proxy today |
|---|---|---|
| Model calls | plugins/openai | http.ProxyFromEnvironment |
| Web search, web fetch | plugins/websearch, plugins/webfetch | ProxyFromEnvironment; webfetch exempts the proxy address from its private-address check |
| Remote MCP servers | internal/mcp/http.go | default transport (environment) |
| MCP stdio servers, process plugins | internal/childenv | inherited variables |
| Shell commands | plugins/localenv/env.go | allowed proxy variables |
| OAuth, install, catalogs | internal/oauth, internal/install, internal/manage | default client (environment) |
| Feishu long connection | lark SDK | unverified |
ProxyFromEnvironment reads the environment once per process, so nothing can change at run time, and one value cannot differ per instance.
3. Structure
admin ─▶ Agent ─▶ egress tools (mihomo plugin) ── approval ──▶ apply
│ PUT /configs │ snapshot
▼ ▼
builtin plugin ─ Env.Proxy(req) ─▶ Host egress evaluator ─▶ mihomo (127.0.0.1) ─▶ chain ─▶ target
child process ─ HTTPS_PROXY=http://<instance>:<token>@127.0.0.1:<port> ─┘| Part | Responsibility | State owner |
|---|---|---|
Host egress evaluator (internal/host/egress) | Holds the current routing snapshot, answers which proxy (if any) a request of an instance uses, gives child processes their variables | the snapshot in memory (rebuilt from the provider at start) |
pkg/plugin contract | The egress role, Env.Proxy, the snapshot type | definitions only |
mihomo plugin (plugins/mihomo, builtin) | The mihomo process, nodes, chains and routes, the mihomo configuration, the tools | DataDir/egress.json; node credentials in the secret store |
| Consumers | Use Env.Proxy instead of ProxyFromEnvironment | — |
The Host knows instances, domains and proxy URLs, never mihomo or a proxy protocol. Another provider (a plain HTTP proxy, a corporate gateway) is another plugin with the egress role.
4. Contract
Role egress, needs the operator's grants: [egress]; at most one instance per Host (a second is unavailable with egress_conflict), and in v1 only a builtin plugin (execution_unsupported otherwise). The registry loads it before every other instance.
type Egress interface {
// SetTargets gives the provider every instance with its credentials,
// before the other instances load and after each reload.
SetTargets(ctx context.Context, targets []EgressTarget) error
// Snapshot is the current routing.
Snapshot(ctx context.Context) (EgressSnapshot, error)
}
type EgressTarget struct {
Instance, Plugin, Description string
Support string // in_process, env or ""
Token string // proxy password; the user is the instance id
}
type EgressSnapshot struct {
Revision int64
Proxy string // 127.0.0.1:7890, no credentials
Routes []EgressRoute // evaluated by specificity, section 6
}
type EgressRoute struct {
Instance string // "" for any instance
Domain string // "" for any domain; "api.x.com" or "*.x.com"
Direct bool // true: bypass the proxy for this match
}The Host makes each instance's token (random, per Host start) and gives the provider the targets, then takes its snapshot. The provider tells the Host about a change through Env.Egress.Changed; Env.Egress also keeps instance-scope secrets, which the per-principal GetSecret cannot provide. The Host keeps the last snapshot in <state_dir>/egress/snapshot.json, so after a restart whose provider cannot load (a missing mihomo binary: prerequisite_missing) routed traffic still goes to the unreachable proxy and fails closed.
*`Env.Proxy func(http.Request) (url.URL, error)`* for builtin plugins: the most specific matching route decides. A route through the proxy returns http://<instance>:<token>@<proxy>; a Direct route returns nil; unrouted traffic uses the process environment's proxy (environment:), as without egress routing. It reads the current snapshot on every request, so changes apply at once without restarts. Env.ProxyAddr is the proxy's address so webfetch can keep exempting it.
One outbound HTTP client. Today eight call sites build their own client: openai, websearch and webfetch each make a Transport, the remote MCP and OAuth clients make bare http.Clients, and install and the two catalog/fetch paths of internal/manage use http.DefaultClient, which has no client timeout. A focused public package, pkg/outbound, replaces them all: outbound.Client(outbound.Options{Proxy, Timeout, ResponseHeaderTimeout, Dial, Log}) returns an *http.Client whose transport takes the proxy from Env.Proxy (the Host's own clients for OAuth, install and catalogs keep the environment's proxy in v1), has default dial, TLS and response-header timeouts, lets webfetch keep its address check as a Dial control, logs each call (method, host, status, duration, whether it was routed; never the URL's query or headers) through pkg/logging, and turns a failed connection to the egress proxy into egress.unavailable. Feishu passes the same client to the lark SDK (lark.WithHttpClient); its WebSocket dialer is checked separately (section 12). No call site may build an http.Transport or use http.DefaultClient afterwards; a test in pkg/outbound greps the tree for them.
Child processes (MCP stdio servers, process plugins, shell commands, Runtime adapters): when an egress instance is configured, each gets HTTP_PROXY, HTTPS_PROXY, ALL_PROXY with its own instance's credentials, NO_PROXY=localhost,127.0.0.1,::1, and NODE_USE_ENV_PROXY=1 (Node ≥ 24 ignores proxy variables otherwise). The URL never changes for an instance, so route changes apply inside mihomo without restarting the process. Unrouted traffic of a child goes DIRECT from mihomo, as it does today.
Egress support is declared by the consumer's manifest, egress: in_process | env:
- ◆
in_process: the plugin usesEnv.Proxy; routing is enforced. - ◆
env: the program is expected to honour proxy variables. Routing is best effort; the tools show this to the admin. Manifest plugins and Runtime adapters default toenv. - ◆absent: a route for this instance is refused with
egress.target_unsupported(Feishu until its SDK is checked).
Failure is closed. A routed request never falls back to direct. When mihomo is down, routed in-process requests fail with error code egress.unavailable; unrouted in-process requests are unaffected; child processes fail to connect until mihomo is back.
Errors (stable codes, message keys and parameters): egress.unavailable, egress.target_unknown (lists the instances), egress.target_unsupported, egress.link_invalid, egress.node_unreachable, egress.apply_failed, egress.revision_conflict, egress.in_use.
5. The mihomo Plugin
- ◆Binary. mihomo is GPL-3.0, so Orquelo never links it; the plugin runs it as a child process. It is a
plugin-scopedownloadprerequisite (ADR 0001, item 7): mihomo v1.19.34 pinned by URL and SHA-256 for darwin, linux and windows on amd64 and arm64, fetched into${PLUGIN_DEPS}when a mihomo instance is added or enabled, or when one loads without it (ADR 0001, item 8); the plugin uses that binary, else one onPATH. When the download fails, the instance is unavailable withprerequisite_missingand the failed step, the next load tries again,serve --preflightstill passes, and routed traffic fails closed on the cached snapshot (section 4). Verified with mihomo 1.19.34; on 2026-11-21 a load from an empty state downloaded it in about three minutes. - ◆Process. A supervisor per data directory, shared by the configuration generations of the instance (a reload makes a new instance while the old one finishes its runs; both must use the one mihomo bound to the ports): it writes a base configuration on first start, starts mihomo with
mixed-portandexternal-controlleron 127.0.0.1 ports chosen at random once and kept inegress.json(controller with a random secret), waits up to 10 s for/version, restarts it with backoff (2 s doubling to 30 s) while a generation uses it, and stops it when the last generation closes. A mihomo left running by a Host that crashed answers with the same secret and is adopted throughmihomo.pid. Its status (state, revision, routes, restarts, last exit) is reported throughStatusReportertoorquelo status. - ◆Persistent state
DataDir/egress.json, revisioned: nodes (id, name, protocol, server, no credentials), chains, routes, per-instance tokens, the two ports. A node's full definition is in the secret store asnode:<id>. - ◆Applying a change (one at a time, under a lock): check
expected_revision→ build the new state → generate the configuration →PUT /configs?force=true(10 s timeout) → writeegress.json→Changed(revision). If mihomo refuses, nothing is written and the tool returnsegress.apply_failedwith mihomo's message. Removing a node or chain still used by a route returnsegress.in_use. - ◆At start, the state file is the truth: the configuration is regenerated from it, so a crash between the PUT and the write leaves the previous revision, which mihomo is given again.
6. Routing Model
- ◆Node: one proxy server, parsed from a share link (
ss://,vmess://,vless://,trojan://,hysteria2:///hy2://,tuic://,socks5://,http(s)://), a Clash/mihomo YAML snippet, or a subscription URL (its nodes are imported once; no automatic refresh). - ◆Chain: an ordered list of nodes,
[A, B]meaning Orquelo → A → B → target. Generated as copies of the nodes namedchain/<id>/<n>, the copy of B havingdialer-proxyset to the copy of A, so a node used directly is not changed. A one-node chain is the node itself. - ◆Route:
match {instance?, domain?}→viaa chain,directorreject. - ◆Specificity, never a manual order: instance and domain > domain > instance; within a class, an exact domain beats a wildcard. Setting a route with the same match replaces it.
Example, generated for mihomo:
rules:
- AND,((IN-USER,codex),(DOMAIN-SUFFIX,openai.com)),chain/us-direct/1
- DOMAIN-SUFFIX,openai.com,chain/jp-us/2
- IN-USER,websearch,chain/hk/1
- IN-USER,codex,chain/jp/1
- MATCH,DIRECT7. Tools, Skill and Natural Language
Tools of the mihomo instance, offered only when the caller is an admin (Principal.Role; a call by anyone else is refused with permission.denied). The read tools need no approval; every change needs an admin's approval (approval: true, approver: admin), which binds the arguments. Every change takes the optional revision that proxy_status showed (egress.revision_conflict when the routing changed since); a change that alters nothing keeps the revision, and node ids come from the call's idempotency key, so a retried call adds nothing twice:
| Tool | Purpose |
|---|---|
proxy_status | process state, revision, nodes, chains, routes, targets with their egress support |
proxy_node_add | parse a link, YAML or subscription; test reachability; store it (returns node ids, never credentials) |
proxy_node_remove, proxy_chain_set, proxy_chain_remove | maintain nodes and chains |
proxy_route_set, proxy_route_remove | {instance?, domain?, via} |
proxy_test | latency of a node or chain to a URL, through mihomo's delay API |
The tool descriptions (model-facing, English) tell the Agent how to map words to targets; no separate skill is shipped: call proxy_status for the targets, choose the instance whose id, plugin or description matches ("web search" → the websearch instance), and ask the user when there are several or none. A domain the user names becomes a domain match. One request may need several calls (add node, set chain, set route), each approved on its own card.
Example, "put Codex behind this proxy: vless://…": proxy_status → proxy_node_add {link} (approved) → proxy_route_set {instance: "codex", via: "<node>"} (approved) → the reply states what changed and that Codex follows proxy variables (env support).
Pasted credentials. The tools store the node in the secret store and return only its id; replies and logs never repeat a link. The user's own message still holds the link in the conversation history, like any pasted text; removing it needs a Host mechanism for redacting stored messages, which this design does not add.
8. Security
- ◆Who: tools offered only to instances whose
usesincludemihomo; calls by non-admins are refused (permission.denied), and approvals bind the arguments' digest, so a prompt injection cannot reroute traffic without an admin seeing exactly which. - ◆mihomo listens only on 127.0.0.1; each instance has its own random token, so a process cannot use another instance's routes by accident. The controller secret never leaves the plugin.
- ◆No TLS interception: mihomo sees only the domain of HTTPS traffic, which is why routes stop at domains.
- ◆webfetch refuses local and private addresses on every path: a direct connection is checked when dialing, after DNS; a proxied one (the environment's proxy or an egress route) dials only the proxy, so its host is resolved and checked before the request is sent. Before this check, a private target through the environment's proxy reached the proxy (found by veruqelo as HTTP 502).
- ◆Logs: process events, applies (revision, counts), refusals; never links, credentials, tokens or the controller secret.
9. Traces
Success. Admin: "proxy web search with trojan://…". proxy_status → proxy_node_add (card approved) → node n1 stored, latency 180 ms → proxy_route_set {instance: websearch, via: n1} (approved) → revision 3 accepted by mihomo → Changed(3) → the next search's Env.Proxy returns http://websearch:…@127.0.0.1:41873 → mihomo IN-USER,websearch → n1.
Failure. The node is down: proxy_node_add returns egress.node_unreachable with the latency test's error; nothing is stored. mihomo crashes: routed searches fail with egress.unavailable (never direct), orquelo status shows the restart count, unrouted traffic works.
Recovery. After a Host restart the plugin regenerates the configuration from egress.json, starts mihomo, and the Host takes the snapshot before any Run starts; until then routed requests fail closed.
10. Platforms
Proxy variables, the evaluator and mihomo's loopback listener behave the same on macOS, Linux and Windows. TUN, process rules and system proxies are not used. Native runs on Linux and Windows are required before claiming support there.
11. Acceptance
- ◆
pkg/outbound: every consumer migrated, nohttp.Transportorhttp.DefaultClientleft outside it, timeouts and call logging covered. - ◆Unit: snapshot evaluation (specificity, exact versus wildcard, direct, no egress instance), link parsing per protocol with invalid inputs, configuration generation (golden files), apply with revision conflicts and mihomo refusal.
- ◆Integration with a real mihomo and two local HTTP proxies: a two-hop chain reaches a local server through both; a route change applies without restarting a child process; killing mihomo makes routed requests fail with
egress.unavailableand leaves unrouted ones working; restart recovers. - ◆Authorization: a non-admin's change is refused; a change runs only after approval.
- ◆e2e (console + real model): "proxy web search through
<local test proxy link>" sets the route and the next search passes through the test proxy. - ◆Codex and Claude Code: verified when their Runtime adapters exist; until then
envsupport is checked with a child process honouring the variables.
12. Not Covered
Routing in orquelo exec and the other one-shot CLI commands (only serve routes); Feishu's long connection (route refused until the SDK's HTTP and WebSocket clients are checked), automatic subscription refresh, failover groups, per-person routes, path matching, TUN. Estimated size: about 1.6k production lines (Host and pkg/outbound 400, plugin 1.2k); the owner raised the budget to 62k for it on 2026-11-20 (architecture section 8).