Architecture

Process Startup & Dual-Proxy Launch

run_singleconfig watcher taskCcrStore backendproxy::build_statebind loopMultiConfigrun()tokio runtimemain()run_singleconfig watcher taskCcrStore backendproxy::build_statebind loopMultiConfigrun()tokio runtimemain()env > TOML(proxy>defaults) > defaultAPI-key chain, per-mode port override,timeout clamp ≤600s, max_output<max_contextalt[config file exists (multi-proxy)][no config (CLI fallback)]alt[mode == Token && !no_ccr_marker][mode == Cache][Token && no_ccr_marker]loop[each (name, cli) in proxies]on Modify(aphrodite.toml): debounce 500ms →MultiConfig::load → resolve_thresholds →store into every live AppState's 4 atomicsloop[each bound listener]OS / shellexec `aphrodite [args]`1--version / --help early-exit checks2`aphrodite setup` subcommand handled before the runtime3worker_threads = env APHRODITE_WORKER_THREADSor (cpus*4).max(32)4Builder::new_multi_thread().worker_threads(n).enable_all()5block_on(run())6resolve config_path:APHRODITE_CONFIG_PATH → ./aphrodite.toml → ~/.hermes/aphrodite/aphrodite.toml7MultiConfig::load(path)8proxies[], [compression], [defaults]9for each proxy: config.resolve(p) → Cli10Cli::parse() (requires --api-key)11init tracing subscriber12resolve relative ccr_db_path vs exe dir · mkdir -p parent13TcpListener::bind(cli.listen) - a bind failure aborts startup14build_state(&cli, compression)15resolve_thresholds(compression)16SqliteCcrStore::open(db_path, ccr_ttl_seconds)17InMemoryCcrStore::with_capacity_and_ttl(10_000, ttl)18None (no CCR backend)19Arc<AppState> (atomics seeded: ema=200, fill=9000, thresholds)20bound.push((name, cli, listener, state))21spawn notify watcher on aphrodite.toml dir22spawn run_single(name, cli, listener, state, shutdown_rx)23warn if APHRODITE_MGMT_TOKEN unset24build restricted Router (/stats,/retrieve,/ccr/*,/reload,...)+ catch_all /{*path} → proxy_handler+ /health (public)25axum::serve(...).with_graceful_shutdown(shutdown_rx.changed())26SIGINT / SIGTERM27shutdown_tx.send(true) → all listeners drain28select: drain done | 5s timeout | 2nd Ctrl+C → abort remaining29OS / shell
STARTUP SEQUENCE
Some sNonecachetokenotherOk portpresent, malformedabsentProxyConfig (from aphrodite.toml)MultiConfig::resolvecfg.listen set?s.parse::<SocketAddr> (fail→error)default 127.0.0.1:9797mode / nameapply_port_override(listen, APHRODITE_CACHE_PORT)apply_port_override(listen, APHRODITE_TOKEN_PORT)listen unchangedenv var parses as u16?addr.set_port(port) · info! logwarn! · keep listenCli.listen
PORT OVERRIDE (ENV PIERCES TOML PER MODE)
_start_proxyaphrodite_hermes_get_hooks / get_schemasaphrodite_hermes_materialize_directiveslayout_check.check_and_heal_probe_dylib (subprocess)_load_dylibregister()Hermes host (PluginManager)_start_proxyaphrodite_hermes_get_hooks / get_schemasaphrodite_hermes_materialize_directiveslayout_check.check_and_heal_probe_dylib (subprocess)_load_dylibregister()Hermes host (PluginManager)canonical layout per layout_schema.json v2 (report-only):detect + log deviations, quarantine stale plugin-source copiesnever moves in a git checkout, never touches plugins/aphrodite (Hermes-owned)embeds the built-in directives from the binary(include_str!) → writes ~/.hermes/aphrodite/directives/idempotent, never overwrites user-modified filesloop[each hook (per-hook try/except - one failure neveraborts)]loop[each tool (per-tool try/except)]skills are not shipped - they live dev-sidecontext engine is opt-in (APHRODITE_CONTEXT_ENGINE=1)alt[both healthy][launch needed]register(ctx)1_load_dylib()2_ensure_binaries(): presence check - NEVER downloadsmissing → log explicit setup command (download.sh / aphrodite setup)legacy APHRODITE_AUTO_DOWNLOAD=1 opt-in runs download.sh3subprocess smoke-test (once per unique path)4rc==0 → CDLL on the resolved canonical path (once per process, no hot-reload)5_configure_ffi: _bindings.py bind_to → manual fallback →_REQUIRED_VOID_P assertion6check_and_heal() (best-effort, never raises)7materialize_directives(home_dir=b"")8{"status":"ok","written":[...],"skipped":[...],"warnings":[...]}9hooks[] + schemas[]10ctx.register_hook(name, _hook_dispatch) (fresh dylib per call)11ctx.register_tool(name, "aphrodite", schema, _make_handler(name))12_start_proxy()13pre-launch probe: GET /health on :9797/:9798(direct-only opener, confirmed "healthy" body) → reuse running instance?14skip launch15Popen(aphrodite binary) · stderr → ~/.hermes/aphrodite/proxy-stderr.log16immediate-death check (stderr tail + API-key hint) ·poll both health endpoints ≤5s17
PLUGIN STARTUP (REGISTER() - THE HERMES-SIDE HALF)
IN THIS DOCUMENT

Crimson marks the heading currently in view; every entry is one of the document's own headings.

aphrodite startup splits into two halves.

The binary half resolves configuration (env > TOML > default), binds every listener before spawning any server, builds one AppState per listener with a CCR store backend, and arms a config-file reload watcher.

The Hermes plugin half runs once per Hermes home inside register(): it loads and smoke-tests the dylib, checks the runtime layout (report-only), materializes the built-in directives, registers hooks and tools, and launches the proxy when it is not already healthy.

Startup sequence

run_singleconfig watcher taskCcrStore backendproxy::build_statebind loopMultiConfigrun()tokio runtimemain()run_singleconfig watcher taskCcrStore backendproxy::build_statebind loopMultiConfigrun()tokio runtimemain()env > TOML(proxy>defaults) > defaultAPI-key chain, per-mode port override,timeout clamp ≤600s, max_output<max_contextalt[config file exists (multi-proxy)][no config (CLI fallback)]alt[mode == Token && !no_ccr_marker][mode == Cache][Token && no_ccr_marker]loop[each (name, cli) in proxies]on Modify(aphrodite.toml): debounce 500ms →MultiConfig::load → resolve_thresholds →store into every live AppState's 4 atomicsloop[each bound listener]OS / shellexec `aphrodite [args]`1--version / --help early-exit checks2`aphrodite setup` subcommand handled before the runtime3worker_threads = env APHRODITE_WORKER_THREADSor (cpus*4).max(32)4Builder::new_multi_thread().worker_threads(n).enable_all()5block_on(run())6resolve config_path:APHRODITE_CONFIG_PATH → ./aphrodite.toml → ~/.hermes/aphrodite/aphrodite.toml7MultiConfig::load(path)8proxies[], [compression], [defaults]9for each proxy: config.resolve(p) → Cli10Cli::parse() (requires --api-key)11init tracing subscriber12resolve relative ccr_db_path vs exe dir · mkdir -p parent13TcpListener::bind(cli.listen) - a bind failure aborts startup14build_state(&cli, compression)15resolve_thresholds(compression)16SqliteCcrStore::open(db_path, ccr_ttl_seconds)17InMemoryCcrStore::with_capacity_and_ttl(10_000, ttl)18None (no CCR backend)19Arc<AppState> (atomics seeded: ema=200, fill=9000, thresholds)20bound.push((name, cli, listener, state))21spawn notify watcher on aphrodite.toml dir22spawn run_single(name, cli, listener, state, shutdown_rx)23warn if APHRODITE_MGMT_TOKEN unset24build restricted Router (/stats,/retrieve,/ccr/*,/reload,...)+ catch_all /{*path} → proxy_handler+ /health (public)25axum::serve(...).with_graceful_shutdown(shutdown_rx.changed())26SIGINT / SIGTERM27shutdown_tx.send(true) → all listeners drain28select: drain done | 5s timeout | 2nd Ctrl+C → abort remaining29OS / shell
STARTUP SEQUENCE

Port override (env pierces TOML per mode)

Some sNonecachetokenotherOk portpresent, malformedabsentProxyConfig (from aphrodite.toml)MultiConfig::resolvecfg.listen set?s.parse::<SocketAddr> (fail→error)default 127.0.0.1:9797mode / nameapply_port_override(listen, APHRODITE_CACHE_PORT)apply_port_override(listen, APHRODITE_TOKEN_PORT)listen unchangedenv var parses as u16?addr.set_port(port) · info! logwarn! · keep listenCli.listen
PORT OVERRIDE (ENV PIERCES TOML PER MODE)

Plugin startup (register() - the Hermes-side half)

register() runs once per Hermes home (one PluginManager per home) and is a pure loader: all logic lives in the dylib.

Runtime artifacts (binary, dylib, aphrodite.toml, ccr.db, logs) live under the canonical runtime home $HERMES_HOME/aphrodite (else ~/.hermes/aphrodite), never inside the plugin tree.

_start_proxyaphrodite_hermes_get_hooks / get_schemasaphrodite_hermes_materialize_directiveslayout_check.check_and_heal_probe_dylib (subprocess)_load_dylibregister()Hermes host (PluginManager)_start_proxyaphrodite_hermes_get_hooks / get_schemasaphrodite_hermes_materialize_directiveslayout_check.check_and_heal_probe_dylib (subprocess)_load_dylibregister()Hermes host (PluginManager)canonical layout per layout_schema.json v2 (report-only):detect + log deviations, quarantine stale plugin-source copiesnever moves in a git checkout, never touches plugins/aphrodite (Hermes-owned)embeds the built-in directives from the binary(include_str!) → writes ~/.hermes/aphrodite/directives/idempotent, never overwrites user-modified filesloop[each hook (per-hook try/except - one failure neveraborts)]loop[each tool (per-tool try/except)]skills are not shipped - they live dev-sidecontext engine is opt-in (APHRODITE_CONTEXT_ENGINE=1)alt[both healthy][launch needed]register(ctx)1_load_dylib()2_ensure_binaries(): presence check - NEVER downloadsmissing → log explicit setup command (download.sh / aphrodite setup)legacy APHRODITE_AUTO_DOWNLOAD=1 opt-in runs download.sh3subprocess smoke-test (once per unique path)4rc==0 → CDLL on the resolved canonical path (once per process, no hot-reload)5_configure_ffi: _bindings.py bind_to → manual fallback →_REQUIRED_VOID_P assertion6check_and_heal() (best-effort, never raises)7materialize_directives(home_dir=b"")8{"status":"ok","written":[...],"skipped":[...],"warnings":[...]}9hooks[] + schemas[]10ctx.register_hook(name, _hook_dispatch) (fresh dylib per call)11ctx.register_tool(name, "aphrodite", schema, _make_handler(name))12_start_proxy()13pre-launch probe: GET /health on :9797/:9798(direct-only opener, confirmed "healthy" body) → reuse running instance?14skip launch15Popen(aphrodite binary) · stderr → ~/.hermes/aphrodite/proxy-stderr.log16immediate-death check (stderr tail + API-key hint) ·poll both health endpoints ≤5s17
PLUGIN STARTUP (REGISTER() - THE HERMES-SIDE HALF)

The layout check and the directives materialize are best-effort by design: either failing degrades to a warning and the plugin still registers (never a raise).

The dylib load itself is the one hard gate - if the smoke test or the FFI assertion fails, register() logs “plugin disabled” and returns.

Call sites

ConcernModule
Runtime + subcommand dispatchcrates/aphrodite/src/main.rs
Config path resolution + bind-before-spawncrates/aphrodite/src/main.rs
Config reload watchercrates/aphrodite/src/main.rs
Per-listener router + servecrates/aphrodite/src/main.rs
MultiConfig::resolve / apply_port_overridecrates/aphrodite/src/config/
proxy::build_state (CCR backend selection)crates/aphrodite/src/proxy.rs
resolve_thresholdscrates/aphrodite/src/proxy.rs
SqliteCcrStore / InMemoryCcrStorevendor/headroom/crates/headroom-core/src/ccr/backends/{sqlite,in_memory}.rs
Plugin register() / _load_dylib / _probe_dylib / _start_proxyplugins/aphrodite/__init__.py
Layout check (report-only)plugins/aphrodite/layout_check.py (+ layout_schema.json)
Directives materialize FFIcrates/aphrodite-hermes/src/lib.rs