# How bowel works The product logic is in [product-ia.md](product-ia.md); the approved interaction prototype is [prototype/index.html](../prototype/index.html). How to build and run is in the [README](../README.md#develop). ## Design - **Providers supply nodes.** A subscription URL, pasted node links (`vmess://`, `trojan://`, `hysteria2://`, …) or a YAML file each become a mihomo `type: file` proxy-provider. bowel downloads subscriptions itself, to read their usage and expiry. A hidden per-provider suffix keeps node names unique across providers. - **Routes come from bowel's template** (`internal/routes`): 默认, AI 服务, 流媒体, 开发 and 直连, and the rules that recognise each. Every node can serve every route. Each proxied route has two groups: a selector, and an automatic url-test group the selector can point at ("自动" = fastest + failover). - **Your own rules come first** (`internal/routes/user.go`, `ui_rules.go`). A rule sends a domain and its subdomains, one name, a keyword or an IP range to a route; they are kept in settings.json and written before the template's. The quickest way to make one is 让它走… on a connection in 日志, which offers the site (api.openai.com → openai.com) or the one name. 设置 > 规则 adds them by hand, says what a typed rule will do before it is added, moves and removes them, and tests an address. A change closes the open connections it would send elsewhere, so it shows at once. - **Rule sets** (`internal/ruleset`, `app_rulesets.go`, `ui_rulesets.go`). A list of rules kept by someone else, from a link or a local file (mihomo YAML, or `.list` text), is a service of a route group, so it moves, switches off and goes like any other. bowel fetches and checks it itself: 导入 shows the rule count before anything counts, lines the core can't use are left out and counted, and the core is given a clean `type: file` rule-provider. That also lets 测试一个地址 look inside a set, which the core has no call for. Links update daily; a failed update keeps the last good list and says so on its row. An update replaces the file and asks the core to read it again (`PUT /providers/rules/…`), so it closes nothing. The order of the three is fixed: your rules, then rule sets, then the template's. Among themselves the sets go as 路由组 lists them, by their group and then their place in it, with 其他流量's last; groups and the sets of a group are dragged to reorder them (`Plan.MoveGroup`, `Plan.MoveRuleSet`). Developer networks come before all of them, so a remote list can't take the LAN or the tailnet. With no rule set in use, your rules and the template's stay sorted together by how specific they are. Rule sets are always `no-resolve`, as your own IP rules are, so a set can't add a DNS lookup to every connection. `IP-ASN` rules need the core's ASN database, which it downloads itself on first use. Agents can only read them (`list_rules`, `explain`). The phones have rule sets too (`mobile/bridge/rulesets.go`, and 导入规则集 under a group's 添加服务 in `mobile/flutter/lib/pages/routing.dart`), on the same parser, store and order. Their files are in the core's own directory (`rulesets/`), so the core may read them without `SAFE_PATHS` (checked on Android 15; iOS has not been run). Three things differ there: a picked file is a copy the system lends for a moment, so the set keeps its name, never updates, and is imported again to change it; a download that failed is tried again after an hour, not at every look; and sets are not yet dragged into another order among themselves. - **A whole config given as a rule set** (`internal/ruleset/config.go`). A source with `rules`, `proxies` or groups and no `payload` is a config, not a list, and is never read as one: the desktop says so, and the phone lists the targets its rules send to. The rules of one target can then be imported into the group as a set of their own; the source remembers the target as `#rules=` after the link, which is cut off before anything is fetched. The shared fetcher also accepts this suffix on the desktop, though its UI has no target picker. `MATCH`, `RULE-SET`, `SUB-RULE` (including references nested inside logic rules) and kinds a list can't hold are left out and counted, and nothing else of the config (nodes, groups, rule-providers, DNS, TUN) is read at all. A set belongs to one group and all sets come after your own rules, so the order between rules of different targets is not kept; a config whose meaning depends on that order is better used whole, as below. - **A provider's own routing** (`internal/core/imported.go`, `app_imported.go`, `ui_imported.go`). A complete Clash config often brings its own `proxy-groups` and `rules`. These stay unused until the user picks 使用它们 on that provider's row, because most subscriptions bring groups and an update must not change anyone's routing by itself. One provider at a time; `settings.ImportedRouting` names it. While it is in use bowel gives the core that config's nodes, groups, rules, sub-rules and the rule and proxy providers they use, unchanged, and nothing else from it: ports, DNS, TUN, listeners, the controller and scripts are bowel's or ignored. Of these, the ones that act on traffic and are switched on in the config (`dns`, `hosts`, `sniffer`, `tun`, `listeners`, `tunnels` and the ports; `Imported.Unused`) are named on 路由组, below `bowel routes` and in `list_routes`, since someone who wrote them expects them to work. The nodes go at the top level under their own names. A group's `proxies:` can't name a proxy-provider's nodes, so the suffixed copies could not be referenced; unchanged names also mean no reference needs rewriting and a `filter` still means what it meant. The provider's `p-` copy stays for the node list, tests and the location probe, and `listedNode` maps one name to the other. `include-all*` is expanded to the source's own members, so a group doesn't take in bowel's providers or the developer networks' outbounds. Remote providers are the core's to download, with the source's `path` removed. The core answers a reload only after it has tried each one it has no file of, and gives one it can't reach 20 s, so `Manager.Apply` takes a reload that outlasts its wait for a config still loading and not for one refused, as long as `mihomo -t` passed and the controller answers (`Manager.Loading`); what has not arrived, rule sets without a rule and providers without a node, is the news line's to say (`importedWaiting`). A config with no `proxies` of its own is not given to the core as a node file (`Store.OwnNodes`), and one with nothing to give nodes at all is refused when it is added; a used `type: file` is refused, as a path means nothing on this machine. Groups that rules point at become routes, so 今日, the map, 活动 and the menu bar work unchanged and MATCH's target is the default route; 路由组 lists every group, and only `select` groups can be switched. The user's rules and rule sets pause and come back with bowel's routing; developer networks still come first. 测试一个地址 and MCP's `explain` don't work here, since the core has no call for it and bowel can't evaluate rules it didn't write. An update of the provider in use is checked first, by reference and with `mihomo -t`: if it fails, or no longer has groups, the last good file stays and the error shows. It never falls back to the template. Disabling the provider goes to bowel's routing until it is enabled again; deleting it ends the choice. The phone has the same choice (`mobile/bridge/imported.go`, issue 184): 使用它们 on the provider's row, the config's groups on 路由组 with only `select` groups switched, and the same refusals. It builds the runtime config with the same `Imported` and keeps the phone's own TUN, listeners and probe. With no `mihomo -t` on the phone, an update of the provider in use is checked by building that config: it must still parse and have groups. Rule sets of the config, `.mrs` among them, are the core's to download, as on the desktop; importing an `.mrs` as a rule set of bowel's own is still refused. - **The core runs as a sidecar process** (`internal/core`), controlled over a unix socket. bowel falls back to TCP with a secret when the socket path is too long. Config changes reload the core without restarting it. - **The interface is native.** The window and the menu bar panel are MyGo `ui` views over two values: a `Snapshot`, rebuilt whenever anything changes, and a `Tick`, every second. The 今日 board animates its cells' boxes: the expanded cell grows in place and the others are squeezed into summaries chosen to fit. Every view is laid out at its cell's final size, so nothing reflows on the way. Views open and fold like drawers, and shared pieces fly between views (`Match`, with text morphing). - **Status is measured, not assumed** (§2 of the IA). bowel checks every 2 s that the system proxy still points at it (`scutil --proxy` on macOS, WinINet's settings on Windows, GNOME's or KDE's on Linux). The core's state, failing nodes and automatic switches feed the one light: 正常 / 降级 / 异常 / 未接管. - **Exit locations** (`internal/locate`, `internal/geo`). A node's place is guessed from its name. When it matters (the node a route uses, or one you pick), bowel measures it instead: it requests Cloudflare's `/cdn-cgi/trace` through the node, via a mihomo listener bound to a probe group. The UI labels each place 实测 / 按名称 / 未知. - **Monitoring** (`internal/monitor`). bowel polls connections every second while the window or the menu bar panel is open (every 5 s otherwise) to get rates per route and per app, new connections, and closed ones. It parses failed dials from the core's log, and keeps today's and this month's totals. On macOS 27 the kernel gives a process the whole socket list, which the core needs to tell which app opened a connection and so to match a rule for an application, only when two things hold (measured on 27.2; Apple documents neither): the process's code-signing identifier has a dot in it, like a bundle identifier, and its parent is not an app or another program that is not Apple's. Otherwise the list holds the process's own sockets and nothing says so. For the second, bowel starts the core detached (`core.startCore`: a shell starts it and exits, leaving it to launchd; its output still comes on an inherited pipe, and its exit is noticed by polling the pid). For the first, the core's file among the resources is called `dev.moho.app.core.bin` on macOS (`core.BinName`): a release build signs it without naming an identifier, and `codesign` makes one of the file's name less its last extension, `dev.moho.app.core`; called `mihomo` it was signed as `mihomo`, and the 0.4.1 core named no process however it was started. `scripts/release.sh` stops a release where the identifier came out otherwise. The core as upstream ships it is signed `a.out` by the linker, which passes, and an ad hoc build leaves that signature alone. The kind of signature counts too (#131, same binary, started detached, on 27.2): ad hoc and Developer ID pass with a dot in the identifier (0.4.2's core does), while an Apple Development signature did not in any combination tried: with or without a dot or the hardened runtime, three teams, not under TUN. Until MyGo 0.9.1 `mygo dev` signed everything in the bundle with an Apple Development identity when the keychain had one, so such a development build's core named no process. Since 0.9.1 it signs the app that way but leaves code among the resources that is already signed as it is, so the core keeps the linker's signature and names them, as it does when mygo dev signs ad hoc. bowel also reads the list itself (`internal/procinfo`) to name the connections the core does not look up. Under `mygo dev` bowel is itself a child of a program that is not Apple's, so there only the core's own names show. Since the names in the Log can be bowel's while the core still knows none, the monitor watches the core itself: when it has named none of the connections from this computer since it started, and five went unnamed (`monitor.Snapshot.Unnamed`; those through a route group's own port don't count, since the core doesn't look them up), with process matching set to always, the Log, its 让它走… menu and 应用 in the rule editor say that a rule for an app won't match (`Tick.AppsUnknown`). The first one it names clears that until the core restarts. - **TUN.** The first time you turn it on, the system asks for an administrator's authorisation, and what that buys is each system's own (`internal/tun`). On macOS bowel copies the core to `~/Library/Application Support/bowel/bin/` and makes it setuid root, the approach early Clash Verge used; a launchd helper would be the cleaner long-term design. On Linux the copy (in bowel's data directory) is given to root and the file capabilities TUN needs (`cap_net_admin`, `cap_net_bind_service`, `cap_net_raw`) under one `pkexec`, so the core still runs as the user; without `setcap` it is setuid root, and a data directory mounted `nosuid` is refused. Where systemd-resolved is in use the same `pkexec` leaves a polkit rule for the user (`/etc/polkit-1/rules.d/49-bowel-tun-.rules`), since the core calls `resolvectl` for the TUN device at every start and polkit would ask each time; `docs/platform-parity.md` says what it allows. On Windows nothing lets a program be elevated without asking, so the one UAC prompt copies the core to `%ProgramData%\bowel\tun\\`, which only administrators can write, and registers a scheduled task of the user's that runs it at the highest run level (and a second one for accounts the first cannot start for, which runs it through a copy of bowel's own program kept in the same directory, so that ending the task ends the core). The user may start and end their own task unasked, so the core manager does that in place of starting a child (`Manager.Spawn`), waits on the process, and reads its log from the controller, since such a core prints to no one. The copy does not follow an update of the app: when its version differs from the bundled core's (or, on macOS, when it is signed as `mihomo`, as the copies made before the core's file was renamed are, and so cannot tell applications apart), bowel runs the bundled core if TUN is off, and otherwise keeps the old copy and offers to replace it, which takes one authorization. The new copy replaces the old one only after that authorization. - **Gateway mode** (`internal/gateway`, `app_gateway.go`, `ui_gateway.go`). One switch lets other devices on the LAN set their gateway and DNS to this computer and follow bowel's rules. On macOS and Linux bowel turns IPv4 forwarding on through a sudoers rule that allows exactly the two `sysctl` commands (checked with `visudo`, installed in the same prompt as TUN), keeps the computer awake (`caffeinate`; a `systemd-inhibit` lock that ends with bowel's process), and puts DNS on `0.0.0.0:53` with fake-ip. The original forwarding value is kept in `gateway-before.json`, so a crash is undone on the next start. Forwarding, port 53 and TUN are measured; a gateway that is wanted but doesn't work makes the state 降级. On is manual: devices are pointed at this computer by hand. Automatic is a second step (`app_gateway_auto.go`, `internal/dhcp`): bowel hands out the LAN's addresses itself, with this computer as every lease's router and DNS, and only after a probe (a DISCOVER from a made-up device) found no other DHCP server; it confirms the addresses devices already hold, so taking over cuts nobody off. The devices that use the gateway (`app_devices.go`) are known from their connections' source addresses, bowel's leases and the ARP table, and shown under 日志 › 设备 with when each came and went. How to set it up and what it survives is [gateway.md](gateway.md), which `scripts/gateway-e2e.sh` checks in containers. A core that quits by itself is started again (`app_revive.go`), at growing intervals up to a minute, since a gateway has no one watching it. Windows has no gateway yet, and the interface doesn't offer one there: forwarding is per adapter and needs elevation each time, and the firewall needs rules of its own (`docs/platform-parity.md`). - **Skins** (`skins.go`). Sixteen looks for the whole interface: 纸墨 Paper (the default), 报刊 Broadsheet, 荧光屏 Phosphor, 霓虹 Neon, 蓝图 Blueprint, 樱 Sakura, 山水 Shanshui, 青瓷 Celadon, 敦煌 Dunhuang, 暮色 Dusk, 极光 Aurora, 黑曜 Obsidian, 孔版 Riso, 黑客军团 Mr. Robot, The Machine and Samaritan. A skin is a palette, the faces of text and big type, corner roundness, a glow and a texture. It may also say how what is chosen shows (a fill, a box of corner brackets, a block under the exit's name), how small tags are drawn, whether short Latin labels are in capitals and in which face, how the map marks its exits, and whether it has a terminal's manners (a square switch, gray sidebar icons, failures as solid tags); all of these are off unless a skin sets them. What the interface does is the same in every skin. - **Developer networks** (`internal/devnet`, `app_devnet.go`, `ui_devnet.go`; cases and reasons in `docs/dev-network.md`). A catalog of what is local everywhere, plus what bowel reads of this machine every 20 seconds (Tailscale, VPN routes, split DNS: `netstat` and `scutil` on macOS, iproute2 and systemd-resolved on Linux, the IP helper API and the name resolution policy table on Windows), compile into an overlay on the core's config and the system proxy's bypass list. It is never saved, so no migration and nothing left behind. Tailscale and VPNs get a direct outbound bound to their interface, because under TUN the core's DIRECT uses the default interface. In global and direct mode the core runs in rule mode with the overlay and a single `MATCH`, so the LAN and the tailnet are not sent to a node. - **IPv6 modes** (`core.IPv6Mode`, `internal/devnet/ipv6.go`, `app_devnet.go`). The setting is Off, Auto or On, Auto by default. Auto keeps IPv6 only while the interface traffic leaves by has a public (`2000::/3`) address and a TCP connection bound to that interface reaches a public resolver. Being bound keeps bowel's own TUN from answering, and it also proves there is a route, so routes aren't read for it. The check runs with the developer-network poll, tries the network again each minute, and needs two readings in a row to change anything, except losing the address, which counts at once. The result is never saved: like the overlay it only goes into the runtime config, as `ipv6` and `dns.ipv6`. `ipv6: false` is enough for the TUN too: mihomo then gives it no IPv6 address, and sing-tun routes no IPv6 without one. A change reopens the TUN, because its address is part of what the core compares; without TUN the reload interrupts nothing. In `settings.json` Off stays `false`, which older versions read, and Auto and On are strings; a bare `true` is from before the modes and migrates to Auto once. The mobile bridge doesn't read the network, so Auto is On there. - **Updating itself** (`app_update.go`, `ui_update.go`). A native binary cannot swap its code while it runs, so an update is `mygo.Updater` (signed archive or delta) followed by a restart. bowel checks the latest release 20 s after launch and every 6 hours and shows the new version in the title bar. One click downloads with progress and restarts through the ordinary quit: the system proxy and gateway go back and the core ends, so if the new version fails to come up the Mac keeps its own network. The network drops for a few seconds. Installs the app cannot write to, such as a .deb in /opt, are left to their package manager. - **Download sources** (`internal/devtools/sources.go`, `ui_sources.go`). npm, PyPI, Go and Rust are already built-in services of 开发, so the route a download takes is the group its service is in. The one thing a rule cannot say is "use a mirror instead", which is the tool's own setting: one line of `~/.npmrc`, `pip.conf`, Go's `env` or `~/.cargo/config.toml`. bowel reads it, and on 用这个 changes that one line where it is, leaving the rest of the file; going back to the official source deletes it. Only the mirrors bowel lists can be written. Every few minutes, and while the section is shown, each way is measured: the mirrors directly, the official address through bowel's own port so that it takes the route its service has (not measured while the core is down). A source whose setting does not answer makes a line on the 模式 cell and offers 修复: the fastest mirror that answers, else the official source, or, when the official address is down because its service was sent to 直连, putting that service back in its default group. This lives in the expanded 模式 cell under 开发工具, not in 路由组, and what belongs to a row there is set in under it with a rule down its left side. - **Agents (MCP)** (`internal/mcp`, `app_mcp.go`, `ui_mcp.go`). bowel serves an MCP server on a unix socket in its data folder (`mcp.sock`, this user only). `bowel mcp` bridges an agent's stdio to it and opens the app when it isn't running, so an agent registers it as an ordinary stdio server: `claude mcp add --scope user bowel -- /Applications/bowel.app/Contents/MacOS/bowel mcp` (设置 > MCP has the command and a JSON snippet to copy). Agents can always read: status, settings (secrets hidden), routes and nodes, rules, where a host would go, connections, logs, and the three whitelists (direct sites, the system proxy's bypass list, LAN addresses). Changes (mode, takeover, a route's node, rules, whitelists, settings by key, providers, DNS) follow `mcpPolicy`: `ask` (the default: a dialog shows what would change, and can let the rest of that connection through), `allow` or `deny`. Only the user can change the policy. 设置 > MCP lists the changes agents asked for. - **Command line and daemon** (`internal/cli`, `cli.go`, `app_cli.go`, `app_daemon.go`). bowel runs in two shapes that serve the same thing. The app is one; `bowel daemon` is the other: `newApp` and the same loops, but MyGo's `Run` is never called, so there is no window, tray, Dock icon or self-update, and it ends on SIGINT, SIGTERM or `bowel stop` through the ordinary `shutdown`. Either shape serves a second unix socket beside `mcp.sock`, `cli.sock`, in the same protocol (`internal/mcp`) with the same tool handlers (`mcpServer`) plus a few the command line alone has (`cliTools`: providers add/remove/enable, nodes on a route, gateway, log tail, stop). The commands (`bowel status`, `bowel mode global`, …) are a thin client of it: `internal/cli` parses, calls a tool and prints, as a table for people or as the tool's JSON with `--json`; it holds no product logic. `bowel tui` (`tui.go`, `tui_view.go`, `term_*.go`) is the same client on a whole terminal: one goroutine owns the model and the connection and waits on keys, a one-second clock and the terminal's size; each page is a tool's answer and each key a tool's call, a change asking y/n first. The terminal is driven directly (raw mode through `golang.org/x/sys`, escape sequences for the rest), with no terminal library. `bowel bar` (`bar.go`) is the same client for a status bar: `get_status` once a second, printed as a waybar JSON line or plain text, dialing again after a failed ask so one start outlives bowel's restarts, and ending when its output is no longer read. `main.go` only decides between the app (no arguments, or what a launcher passes) and `runCLI`. What tells the user from an agent is the socket and what the session says of itself. A session on `cli.sock` is the user's (`isLocal`), so `approve` lets its changes through without asking and they are not listed among the agents'; it may also set `mcpPolicy`. A command that finds an agent's environment (`cli.Agent`: `CLAUDECODE`, `CODEX_SANDBOX`, `CURSOR_AGENT`, `AI_AGENT`, …) says so in `initialize`, and that session is treated exactly as one on `mcp.sock`; so is a session that never initializes. The daemon cannot show the dialog, so under `ask` it refuses. This is a guard rail and not a boundary: a program of the same user that sets out to get round it can clear its environment, or write `settings.json`. A data folder named by `BOWEL_DATA_DIR` or `--data-dir` is told apart by its own sockets; the default one also takes MyGo's single-instance lock, so the app and the daemon never run two cores on one folder. ## Layout ``` main.go, app.go wiring: lifecycle, actions, the snapshot and tick model.go the view model: Snapshot, Tick, Conn, … ui.go the window: palette, title bar, pages, shared parts ui_home.go, ui_map.go 代理: the morphing board and the exit map ui_activity.go 活动: connections and logs ui_providers.go Provider: add, list, nodes ui_rules.go the user's rules: 日志's 让它走…, 设置 > 规则 ui_rulesets.go, app_rulesets.go imported rule sets: the panel, the row, updates ui_imported.go, app_imported.go a provider's own routing: the row's offer, the page, what the app sees of it ui_sources.go download sources in the 模式 cell: the section, switching, the fix ui_settings.go 设置: the core's options, in a window of their own (sidebar + pane, searchable) ui_gateway.go, app_gateway.go gateway mode: the switch, the guide card, measured checks ui_providers_qr.go, app_qr.go QR codes: show a provider's, scan with the camera or the screen skins.go the skins ui_panel.go, tray.go the menu bar icon, its panel and its menu logo.go the logo's squiggle, which the menu bar icon is drawn from debug.go a script hook for development builds (MOHO_DEBUG_DIR) internal/core mihomo process, runtime config, the core's options (Options), a provider's own routing (Imported) internal/devnet what stays off the proxy: the scenarios, this machine's networks, the overlay on the config internal/mihomo controller client internal/provider providers: detect, download, store internal/routes the routing template, and the user's rules internal/ruleset rule lists from a link or a file: read, check, store, look inside internal/monitor connections, rates, events, logs, totals internal/procinfo which app owns a local socket (macOS, where the core can't tell) internal/netif what an interface is where its name doesn't say: tunnels, routes, adapters (Linux, Windows) internal/nowindow start a program without a console window (Windows); every exec goes through it, and a test checks internal/locate, geo exit locations internal/sysdns point macOS's DNS servers into TUN while it is on, and put them back internal/sysproxy set, check and restore the system proxy: macOS, Windows, GNOME and KDE internal/tun the one authorisation TUN takes: setuid (macOS), file capabilities (Linux), an elevated task (Windows) internal/gateway IPv4 forwarding, LAN detection, the gateway's checks internal/dhcp who hands out addresses on the LAN, and handing them out: the gateway's automatic step internal/qr QR decoding internal/i18n 简体中文, 繁體中文, English, 日本語 internal/settings settings.json internal/mcp a small MCP server (stdio framing over a unix socket) and the `bowel mcp` bridge app_mcp.go, ui_mcp.go the agents' tools and their policy; 设置 > MCP internal/cli the command line: parsing, the client of cli.sock, tables and JSON, completions cli.go, app_cli.go the command line's wiring, its socket and its own tools app_daemon.go `bowel daemon`: bowel without a window prototype/ the interaction prototype and its history site/ the website; site/shots/ is rendered by scripts/site-shots.sh assets/icon/ the app icon: AppIcon.icon (Icon Composer) and its 1024 px render; iOS compiles it too resources/icon.png the fallback icon, for macOS before 26 and `mygo dev` scripts/mobile-brand.sh writes the Android vectors and Flutter's logo path from the above entitlements.plist the camera, which a Developer ID build's hardened runtime needs ``` mihomo is GPL-3.0; bowel runs it as a separate program and does not link it.