chore: delete code comments, add ratchet lint and ADRs

Classify every comment as tautology, stale, excuse or decision record.
Tautology/stale/excuse comments are deleted (excuses filed as issues
#196-#236), decisions moved to docs/adr/0001-0034.

- scripts/lint-comments.sh + .comment-baseline: per-file comment count
  may only go down; wired into tests/all.sh
- .claude/skills/delete-comment: repeatable audit workflow
- cargo fmt applied to touched crates

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
johannesandClaude Sonnet 5.5 committed 2026-11-21 13:37:32 +01:00
1 parent 0545702fe0
commit a94632ea3d
131 files changed
+1051 -1746

No files matched your search

-45
View File
@@ -1,15 +1,3 @@
//! Headless Agent Client Protocol server: `hx serve --acp --cwd <dir> --session <id>`.
//!
//! JSON-RPC 2.0, one message per line on stdio; the orchestrator is the client.
//! Standard ACP: `initialize`, `session/new|load`, `session/prompt`, `session/cancel`,
//! `session/update` (notifications out), `session/request_permission` (request out).
//! Orchestrator extensions: in `hx/step`, `hx/message`, `hx/interrupt`, `hx/compact`;
//! out `hx/step_result`, `hx/intent`, `hx/edit`, `hx/usage`, `hx/decision`, `hx/plan`.
//!
//! The model reports step outcome, decisions and plan in a closing ```hx-step JSON block
//! (see [`PROMPT`]); that works the same for every provider, including the `claude` CLI whose
//! tools hx does not own.
use crate::rpc::emit;
use anyhow::Result;
use async_trait::async_trait;
@@ -45,14 +33,12 @@ End every step with exactly one fenced block, last in your reply:
`decisions` and `plan` are optional; give `plan` in planning steps. Put free text in `summary`,
never in `catch`."#;
/// Server options from the command line and the finished agent setup.
pub struct Opts {
pub session: String,
pub cwd: PathBuf,
pub pricing: Option<Pricing>,
}
/// Outgoing messages and requests waiting for the client's answer.
struct Link {
sid: String,
next: AtomicU64,
@@ -69,7 +55,6 @@ impl Link {
json!({"sessionId": self.sid, "update": u}),
);
}
/// The client's whole reply message; None when the connection closed first.
async fn request(&self, method: &str, params: Value) -> Option<Value> {
let id = self.next.fetch_add(1, SeqCst);
let (tx, rx) = oneshot::channel();
@@ -91,7 +76,6 @@ impl Link {
let _ = tx.send(msg);
}
}
/// Unanswered requests fail (permissions are denied).
fn close(&self) {
self.pending
.lock()
@@ -114,28 +98,21 @@ fn respond(id: &Value, r: Result<Value, String>) {
struct M {
step: Usage,
total: Usage,
/// context tokens of the last request
ctx: u64,
ctx_limit: Option<u64>,
cost_limit: Option<f64>,
/// why the run must end at the next turn boundary
stop: Option<String>,
/// hints from `hx/message`, injected at the next turn boundary
pending: Vec<String>,
/// a question the model tried to ask a human
question: Option<String>,
intent: String,
/// file contents before a write/edit call, by tool call id
before: HashMap<String, Option<String>>,
}
/// Turns bus events into ACP notifications and enforces the step limits.
struct Meter {
link: Arc<Link>,
abort: AbortHandle,
cwd: PathBuf,
pricing: Option<Pricing>,
/// context limit reported when the step sets none
window: u64,
st: StdMutex<M>,
}
@@ -170,7 +147,6 @@ fn intent_of(name: &str, args: &Value) -> String {
}
}
/// (added, removed) lines between two file contents.
fn line_diff(old: &str, new: &str) -> (usize, usize) {
use similar::{ChangeTag, TextDiff};
TextDiff::from_lines(old, new)
@@ -208,7 +184,6 @@ impl Meter {
m.stop = None;
m.question = None;
}
/// Ask the run to end after the current tool round; the first reason wins.
fn stop(&self, why: impl Into<String>) {
let mut m = self.m();
m.stop.get_or_insert(why.into());
@@ -330,7 +305,6 @@ impl Hook for Meter {
}
}
/// Options shown to the client for a permission request.
fn options(always: bool) -> Value {
let mut o = vec![json!({"optionId": "allow_once", "name": "Allow", "kind": "allow_once"})];
if always {
@@ -340,7 +314,6 @@ fn options(always: bool) -> Value {
json!(o)
}
/// `Some(option id)` when the client picked one; None = cancelled, error or connection gone.
async fn permission(
link: &Link,
mut abort: tokio::sync::watch::Receiver<bool>,
@@ -358,7 +331,6 @@ async fn permission(
.flatten()
}
/// Wire permission, yes/no and multiple-choice questions to the client.
fn install(agent: &Agent, link: &Arc<Link>, meter: &Arc<Meter>) {
let state = &agent.cx.state;
let abort = state.abort.get().cloned();
@@ -377,7 +349,6 @@ fn install(agent: &Agent, link: &Arc<Link>, meter: &Arc<Meter>) {
let call = json!({"toolCallId": format!("perm-{n}"),
"title": format!("{}: {}", r.tool, r.detail), "kind": kind(&r.tool),
"status": "pending", "rawInput": {"tool": r.tool, "detail": r.detail}});
// file tools have no rule; their "always" means all edits this session
let always = !r.rule.is_empty() || matches!(r.tool.as_str(), "write" | "edit");
match permission(&link, rx(), call, always).await.as_deref() {
Some("allow_once") => Decision::Once,
@@ -403,7 +374,6 @@ fn install(agent: &Agent, link: &Arc<Link>, meter: &Arc<Meter>) {
}));
}
{
// no human to answer: remember the question, the step ends as needs_input
let meter = meter.clone();
let _ = state.choose.set(Arc::new(move |q| {
meter.m().question.get_or_insert(q.text);
@@ -416,7 +386,6 @@ fn text_of(v: &Value) -> Option<String> {
match v {
Value::Null => None,
Value::String(s) => (!s.trim().is_empty()).then(|| s.clone()),
// ACP content blocks
Value::Array(a) if a.iter().all(|b| b["text"].is_string()) => {
let t: Vec<_> = a.iter().filter_map(|b| b["text"].as_str()).collect();
Some(t.join("\n"))
@@ -425,7 +394,6 @@ fn text_of(v: &Value) -> Option<String> {
}
}
/// instruction, context and prompt of an `hx/step` as one user message.
fn compose(p: &Value) -> String {
let mut parts = vec![];
parts.extend(text_of(&p["instruction"]));
@@ -438,7 +406,6 @@ fn num(v: &Value, keys: &[&str]) -> Option<f64> {
keys.iter().find_map(|k| v[k].as_f64()).filter(|n| *n > 0.0)
}
/// The closing ```hx-step block of a reply.
fn report(text: &str) -> Option<(Value, &str)> {
let i = text.rfind("```hx-step")?;
let rest = &text[i + "```hx-step".len()..];
@@ -455,7 +422,6 @@ fn now() -> u64 {
.map_or(0, |d| d.as_secs())
}
/// `hx/step_result` payload from the model's reply; sends `hx/decision` and `hx/plan` on the way.
fn outcome(link: &Link, reply: &str, question: Option<String>, catches: &[String]) -> Value {
let (rep, body) = report(reply).unwrap_or((Value::Null, reply.trim()));
for d in rep["decisions"].as_array().into_iter().flatten() {
@@ -494,7 +460,6 @@ fn outcome(link: &Link, reply: &str, question: Option<String>, catches: &[String
let mut summary: String = rep["summary"]
.as_str()
.map_or_else(|| body.chars().take(1500).collect(), String::from);
// `catch` is a name from the step's catch list, only on blocked; anything else is free text
let mut catch = Value::Null;
if let (true, Some(c)) = (status == "blocked", rep["catch"].as_str()) {
if catches.iter().any(|n| n == c) {
@@ -506,7 +471,6 @@ fn outcome(link: &Link, reply: &str, question: Option<String>, catches: &[String
json!({"status": status, "summary": summary, "catch": catch, "question": q})
}
/// Catch names the orchestrator offers in `hx/step` (`catches`, also inside `context`).
fn catch_names(p: &Value) -> Vec<String> {
[&p["catches"], &p["context"]["catches"]]
.iter()
@@ -523,9 +487,7 @@ struct Srv {
agent: Arc<Mutex<Agent>>,
}
/// One step; returns the `hx/step_result` payload.
async fn step(s: &Srv, p: &Value) -> Value {
// no catch: a stop that is not one of the state's catches names its reason instead
let blocked = |reason: &str, why: String| {
json!({"status": "blocked", "summary": why, "catch": null, "reason": reason,
"question": null})
@@ -561,7 +523,6 @@ async fn step(s: &Srv, p: &Value) -> Value {
r = &mut run => r,
_ = deadline => {
s.meter.stop(format!("wall time limit {}s reached", wall.unwrap_or_default()));
// soft stop at the next turn boundary; a stuck tool gets a grace period
tokio::select! {
r = &mut run => r,
_ = tokio::time::sleep(Duration::from_secs(30)) => {
@@ -599,7 +560,6 @@ pub async fn serve(mut agent: Agent, abort: AbortHandle, o: Opts) -> Result<()>
window: agent.compact_at() as u64,
st: Default::default(),
});
// nobody to answer exit_plan; the step reports its plan instead
agent.tools.retain(|n| n != "exit_plan");
agent.append_system(PROMPT);
install(&agent, &link, &meter);
@@ -620,7 +580,6 @@ pub async fn serve(mut agent: Agent, abort: AbortHandle, o: Opts) -> Result<()>
};
let (id, p) = (m["id"].clone(), m["params"].clone());
let Some(method) = m["method"].as_str() else {
// answer to one of our requests
link.resolve(&id, m);
continue;
};
@@ -631,7 +590,6 @@ pub async fn serve(mut agent: Agent, abort: AbortHandle, o: Opts) -> Result<()>
"agentCapabilities": {"loadSession": true, "promptCapabilities": {}},
"agentInfo": {"name": "hx", "version": env!("CARGO_PKG_VERSION")}})),
),
// the session id is fixed by --session
"session/new" | "session/load" => respond(&id, Ok(json!({"sessionId": link.sid}))),
"session/cancel" => abort.abort(),
"hx/interrupt" => {
@@ -705,7 +663,6 @@ pub async fn serve(mut agent: Agent, abort: AbortHandle, o: Opts) -> Result<()>
other => respond(&id, Err(format!("method not found: {other}"))),
}
}
// client gone: stop the running step, deny open permission requests
abort.abort();
link.close();
for t in tasks {
@@ -763,7 +720,6 @@ mod tests {
(o["status"].as_str(), o["question"].as_str()),
(Some("needs_input"), Some("which db?"))
);
// needs_input without a question cannot be answered
let r = "```hx-step\n{\"status\":\"needs_input\"}\n```";
assert_eq!(outcome(&l, r, None, &[])["status"], "blocked");
}
@@ -788,7 +744,6 @@ mod tests {
(o["catch"].is_null(), o["summary"].as_str()),
(true, Some("s (made up)"))
);
// caveats on a done step are not a catch
let r = "```hx-step\n{\"status\":\"done\",\"catch\":\"ToolDenied\"}\n```";
assert!(outcome(&l, r, None, &names)["catch"].is_null());
}
-75
View File
@@ -18,7 +18,6 @@ use std::sync::Arc;
#[derive(Parser)]
#[command(
name = "hx",
// CI sets HX_VERSION to the release version; local builds use Cargo's
version = option_env!("HX_VERSION").unwrap_or(env!("CARGO_PKG_VERSION")),
about = "Minimal coding agent"
)]
@@ -127,7 +126,6 @@ enum ConfigAction {
},
}
/// Every key commented out; `sample_config_parses` keeps it in sync with `Config`.
const SAMPLE_CONFIG: &str = include_str!("config.sample.toml");
#[derive(Subcommand)]
@@ -138,7 +136,6 @@ enum McpAction {
Logout { server: String },
}
/// `~/.hx/config.toml`, overridden by `.hx/config.toml` in the project.
#[derive(Clone, serde::Deserialize)]
#[serde(untagged)]
enum CliCfg {
@@ -152,41 +149,24 @@ struct Config {
provider: Option<Kind>,
model: Option<String>,
claude_model: Option<String>,
/// Run Claude through the official `claude` CLI (subscription billing). Default: on when `claude` is in PATH.
/// `false` = own OAuth calls (billed as extra usage); `true` / `[]` = on; a list = on with extra `claude` args.
claude_cli: Option<CliCfg>,
/// OpenAI-compatible endpoint (Ollama, vLLM, LM Studio, OpenRouter, ...), provider "custom".
openai_compat: Option<hx_ai::openai_compat::Config>,
codex_model: Option<String>,
/// Auto-compact threshold in estimated tokens.
compact_at: Option<usize>,
max_tokens: Option<u32>,
/// Model for read-only `task` subagents; default: the provider's cheapest tier (Haiku / Luna).
explore_model: Option<String>,
/// Register the `task` subagent tool (default true; each call still asks the user). `--no-subagents` = off.
subagents: Option<bool>,
/// Add the `codemode` tool: JS scripts that call the other tools (default false).
codemode: Option<bool>,
/// Capture the mouse for wheel scrolling (default true; false = terminal selection works without shift).
mouse: Option<bool>,
/// Where sessions live (default `~/.hx/sessions`); `~` expands. Point at a synced/mounted cloud folder. `HX_SESSIONS_DIR` wins.
sessions_dir: Option<String>,
/// Prefix session folders with the host name, so machines sharing `sessions_dir` stay apart (default false).
sessions_host: Option<bool>,
/// Reuse the last model chosen with /model or /provider (default true).
remember_model: Option<bool>,
/// `/model auto`: tier pins (`fast`, `balanced`, `deep` = model ids) and `down_after`.
auto: Option<hx_core::route::Cfg>,
/// "ask" (default), "auto" or "yolo": whether bash/write/edit prompt in the TUI.
permissions: Option<String>,
/// Replaces the built-in system prompt (AGENTS.md etc. are still appended).
system_prompt: Option<String>,
/// confine child processes: mode = "on", backend, network, rw, ro, env_allow
sandbox: Option<hx_core::sandbox::Cfg>,
lsp: Option<LspCfg>,
/// web_search backend: search = "brave" (default, key in $BRAVE_API_KEY) | "searxng", searxng_url
web: Option<WebCfg>,
/// subprocess extensions (JSON-RPC over stdio); global and project lists are concatenated
extensions: Vec<hx_core::ext::ExtCfg>,
}
@@ -209,17 +189,11 @@ fn web_search(cfg: &Config) -> Option<hx_tools::web::Search> {
#[derive(Default, Clone, serde::Deserialize)]
#[serde(default, deny_unknown_fields)]
struct LspCfg {
/// turn_end (default) | agent_end | off
mode: Option<hx_lens::Mode>,
/// extra or overriding servers (same `id` replaces a built-in)
servers: Vec<hx_lens::manager::ServerCfg>,
/// built-in server ids to disable
disable: Vec<String>,
/// runner ids to enable in addition to defaults (e.g. "clippy")
enable_runners: Vec<String>,
/// runner ids to disable (e.g. "rustfmt", "biome-format")
disable_runners: Vec<String>,
/// affected tests: turn_end (default) | agent_end | off
tests: Option<hx_lens::testrun::TestMode>,
}
@@ -264,12 +238,9 @@ impl Config {
}
}
/// Tool context of the agent, for the stored "run claude outside the sandbox" rule.
static CLAUDE_CX: std::sync::OnceLock<ToolCtx> = std::sync::OnceLock::new();
const OUTSIDE_RULE: &str = "claude:unsandboxed";
/// Leave the sandbox only on an explicit, stored rule (`claude:unsandboxed` in `.hx/allow.json`). Never
/// asked and never implied by yolo: yolo is only safe because claude's tools stay confined.
fn claude_outside() -> bool {
CLAUDE_CX.get().is_some_and(|cx| {
cx.state
@@ -280,7 +251,6 @@ fn claude_outside() -> bool {
})
}
/// `hx mcp-serve`: lens/LSP, hx's MCP servers and (with a permission socket) `approve` for claude.
async fn mcp_serve() -> Result<()> {
let cwd = std::env::current_dir()?;
let mgr = Arc::new(hx_lens::manager::Manager::new(
@@ -296,17 +266,14 @@ async fn mcp_serve() -> Result<()> {
let sock = std::env::var_os(hx_core::approve::ENV);
if let Some(p) = &sock {
reg.add(hx_core::approve::Approve(p.into()));
// tools run by codemode ask hx for permission like any other
let _ = cx
.state
.permit
.set(hx_core::approve::remote_permit(p.into()));
}
// claude keeps its own tools; hx's MCP servers are added directly, or only through `codemode`
let cfg = Config::load(&cwd)?;
let mut servers =
hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?;
// a server entry that is hx itself would spawn mcp-serve recursively
servers.retain(|_, s| !s.args.iter().any(|a| a == "mcp-serve"));
let hub = Arc::new(hx_mcp::Hub::start(servers).await);
if std::env::var_os("HX_CODEMODE").is_some() {
@@ -329,7 +296,6 @@ async fn mcp_serve() -> Result<()> {
Ok(())
}
/// Appends a line to `$TMPDIR/hx-mcp-serve.log` (writable inside the sandbox too); best effort.
fn mcp_serve_log(line: &str) {
use std::io::Write;
let p = std::env::temp_dir().join("hx-mcp-serve.log");
@@ -351,8 +317,6 @@ fn mcp_serve_log(line: &str) {
}
}
/// What `claude` (and its `hx mcp-serve` child) need inside the sandbox: its binary and config,
/// the network, hx itself and the permission socket.
fn claude_extra(bin: &str) -> hx_core::sandbox::Extra {
let home = std::path::PathBuf::from(std::env::var_os("HOME").unwrap_or_default());
let mut ro = vec![];
@@ -373,14 +337,12 @@ fn claude_extra(bin: &str) -> hx_core::sandbox::Extra {
{
ro.extend(f.parent().map(Into::into));
}
// claude's install dir (versions/..) sits next to the resolved symlink target
hx_core::sandbox::Extra {
ro,
rw: vec![
home.join(".claude"),
home.join(".claude.json"),
home.join(".config/claude"),
// macOS keeps claude's login in the login keychain; without it claude says "Not logged in"
home.join("Library/Keychains"),
hx_core::approve::sock_path(),
],
@@ -401,7 +363,6 @@ fn claude_extra(bin: &str) -> hx_core::sandbox::Extra {
}
}
/// The `claude` command: sandboxed when the sandbox is on, unless claude's sandbox is off or a rule lets it out.
async fn claude_command(bin: String) -> tokio::process::Command {
if hx_core::sandbox::active().is_none()
|| !hx_core::sandbox::claude_sandboxed()
@@ -412,8 +373,6 @@ async fn claude_command(bin: String) -> tokio::process::Command {
hx_core::sandbox::command_with(&bin, &claude_extra(&bin))
}
/// Builtins, MCP prompts (`/server:prompt`), then skills (builtins win name clashes).
/// `models` feeds `/model` completion (any other id still works); `kinds` = logged-in providers.
fn command_specs(
mcp: &hx_mcp::Hub,
cwd: &std::path::Path,
@@ -437,7 +396,6 @@ fn command_specs(
Source::Builtin,
ArgKind::None,
));
// servers still connecting have no prompts yet; `/mcp` shows them, typed `/server:prompt` still resolves
v.extend(mcp.prompts().iter().map(|(n, p)| {
CmdSpec::new(
&format!("{n}:{}", p["name"].as_str().unwrap_or_default()),
@@ -451,7 +409,6 @@ fn command_specs(
v
}
/// Providers with stored or importable credentials.
fn logged_in() -> Vec<Kind> {
[Kind::Claude, Kind::Codex, Kind::Custom]
.into_iter()
@@ -463,13 +420,11 @@ fn logged_in() -> Vec<Kind> {
.collect()
}
/// Model catalog of every logged-in provider (live list cached a day, else the built-in list).
async fn catalog(kinds: &[Kind]) -> Vec<ModelInfo> {
let one = |k: Kind| async move {
let Ok(p) = provider(k) else {
return hx_ai::models::fallback(k);
};
// stale-while-revalidate: any cached list starts us now; an expired one refreshes in the background
if k != Kind::Custom
&& let Some((m, fresh)) = hx_ai::models::cached(k)
{
@@ -498,7 +453,6 @@ async fn catalog(kinds: &[Kind]) -> Vec<ModelInfo> {
.collect()
}
/// `HX_TRACE_STARTUP=1`: print time since process start at each phase.
fn trace(phase: &str) {
static T0: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
let t0 = T0.get_or_init(std::time::Instant::now);
@@ -507,7 +461,6 @@ fn trace(phase: &str) {
}
}
/// `hx models`: what each provider's `/models` returns, and where the list came from.
async fn print_models(refresh: bool) {
for k in logged_in() {
let Ok(p) = provider(k) else { continue };
@@ -519,7 +472,6 @@ async fn print_models(refresh: bool) {
}
}
/// USD per million tokens. ponytail: subscription usage isn't billed per token; this is an API-equivalent estimate.
fn pricing(model: &str) -> Option<hx_ai::Pricing> {
let p = |input, output, cache_read, cache_write| hx_ai::Pricing {
input,
@@ -527,7 +479,6 @@ fn pricing(model: &str) -> Option<hx_ai::Pricing> {
cache_read,
cache_write,
};
// 5.x generation prices first; older ids keep their own
Some(match model {
m if m.contains("fable") => p(10.0, 50.0, 1.0, 12.5),
m if m.contains("opus-5") => p(4.0, 20.0, 0.4, 5.0),
@@ -544,11 +495,8 @@ fn pricing(model: &str) -> Option<hx_ai::Pricing> {
})
}
/// `[openai_compat]` from config, set once at startup.
static COMPAT: std::sync::OnceLock<hx_ai::openai_compat::Config> = std::sync::OnceLock::new();
/// `codemode` from config: also offer the codemode tool to claude.
static CODEMODE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
/// claude_cli sees only the `hx mcp-serve` tools: MCP is script-only with codemode, else `mcp__hx__*`.
fn via() -> hx_mcp::Via {
match (
CLAUDE_CLI.get().is_some(),
@@ -559,7 +507,6 @@ fn via() -> hx_mcp::Via {
_ => hx_mcp::Via::Direct,
}
}
/// `claude_cli` from config: extra args for the `claude` binary.
static CLAUDE_CLI: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
fn provider(k: Kind) -> hx_ai::Result<Arc<dyn Provider>> {
@@ -608,7 +555,6 @@ fn provider(k: Kind) -> hx_ai::Result<Arc<dyn Provider>> {
})
}
/// Streams text to stdout and tool activity to stderr.
struct Printer;
#[async_trait::async_trait]
impl Hook for Printer {
@@ -637,7 +583,6 @@ impl Hook for Printer {
}
}
/// Lets an `Arc`-shared hook sit on the bus while tools hold the same instance.
struct ArcHook<H>(Arc<H>);
#[async_trait::async_trait]
impl<H: Hook> Hook for ArcHook<H> {
@@ -669,7 +614,6 @@ fn session_dir(cwd: &std::path::Path, cfg: &Config) -> Result<std::path::PathBuf
.map_or("host".into(), |h| h.trim().to_string())
});
let dir = hx_core::session::dir(&root, cwd, host.as_deref());
// fail loud: a silent fallback would leave sessions off the cloud folder
std::fs::create_dir_all(&dir)
.map_err(|e| anyhow::anyhow!("sessions dir {}: {e}", dir.display()))?;
Ok(dir)
@@ -683,7 +627,6 @@ async fn main() -> Result<()> {
match cli.cmd {
Some(Cmd::Serve { acp, cwd, session }) => {
anyhow::ensure!(acp, "hx serve: --acp is required");
// file-name safe, so the id maps to one session file
let id: String = session
.chars()
.map(|c| {
@@ -864,8 +807,6 @@ async fn main() -> Result<()> {
return Ok(());
}
Some(Cmd::McpServe) => {
// claude starts this and hides its stderr: a failed start shows up only as
// "mcp__hx__approve not found", so the reason goes to a log file as well
let r = mcp_serve().await;
if let Err(e) = &r {
mcp_serve_log(&format!("mcp-serve failed: {e:#}"));
@@ -894,7 +835,6 @@ async fn main() -> Result<()> {
if let Some(oc) = cfg.openai_compat.clone() {
let _ = COMPAT.set(oc);
}
// auto-detect, except against a test server (HX_BASE_URL)
let cli_args = match cfg.claude_cli.clone() {
Some(CliCfg::Args(a)) => Some(a),
Some(CliCfg::Switch(on)) => on.then(Vec::new),
@@ -906,18 +846,15 @@ async fn main() -> Result<()> {
if let Some(a) = cli_args {
let _ = CLAUDE_CLI.set(a);
}
// MCP servers connect while the model catalog loads
let mcp_cfg = hx_mcp::config::load(&context::hx_home(), &cwd).map_err(anyhow::Error::msg)?;
let mcp = hx_mcp::Hub::spawn(mcp_cfg);
let kinds = logged_in();
let last_path = context::hx_home().join("last.json");
let remember = cfg.remember_model != Some(false);
// last /model choice, only while its provider is still logged in
let last = remember
.then(|| hx_core::switch::Last::load(&last_path))
.flatten()
.filter(|l| kinds.contains(&l.provider));
// default provider: flag, config, last choice, else the first one logged in
let kind = cli
.provider
.or(cfg.provider)
@@ -926,16 +863,13 @@ async fn main() -> Result<()> {
.unwrap_or(Kind::Claude);
let models = catalog(&kinds).await;
trace("catalog");
// an explicit model picks its provider unless --provider says otherwise
let kind = match (&cli.provider, cli.model.as_deref().or(cfg.model.as_deref())) {
(None, Some(m)) => hx_ai::models::kind_of(&models, m).unwrap_or(kind),
_ => kind,
};
// the remembered model applies only to the provider it was chosen on
let last_fable = last.as_ref().and_then(|l| l.fable);
let last = last.filter(|l| l.provider == kind);
let last_effort = last.as_ref().and_then(|l| l.effort);
// auto mode: `--model auto` / `model = "auto"`, else whatever was on last time
let want_auto = match cli.model.as_deref().or(cfg.model.as_deref()) {
Some(m) => m == "auto",
None => last.as_ref().is_some_and(|l| l.auto),
@@ -1014,7 +948,6 @@ async fn main() -> Result<()> {
.unwrap_or(context::DEFAULT_PROMPT)
));
trace("prompt");
// short grace so fast servers land in the (cache-stable) startup prompt; slow ones connect in the background
mcp.wait_all(std::time::Duration::from_secs(1)).await;
trace("mcp");
mcp.register(&mut agent.tools);
@@ -1079,7 +1012,6 @@ async fn main() -> Result<()> {
let _ = tl.state.set(agent.cx.state.clone());
agent.bus.add(tl);
}
// rust-analyzer & co are slow to index: start servers for languages present at the top level now
let probe: Vec<_> = std::fs::read_dir(&cwd)
.into_iter()
.flatten()
@@ -1103,7 +1035,6 @@ async fn main() -> Result<()> {
}
trace("lens");
if !cli.no_subagents && cfg.subagents != Some(false) {
// children get the parent's tools as of now (no `task`, so no recursion)
let mut general = agent.tools.clone();
general.retain(|n| n != "ask_user" && n != "exit_plan");
let mut explore = agent.tools.clone();
@@ -1140,7 +1071,6 @@ async fn main() -> Result<()> {
hx_ai::models::cheap_for(kind, &models).or_else(|| Some(agent.model().to_string())),
)
{
// auto permissions: a cheap model judges the commands the rules cannot classify
let _ = agent
.cx
.state
@@ -1148,7 +1078,6 @@ async fn main() -> Result<()> {
.set(hx_core::danger::Judge { provider: p, model });
}
if cfg.codemode.unwrap_or(false) {
// snapshot after every other tool (MCP, lens, task); codemode itself is not callable inside
let cm = hx_tools::codemode::Codemode::new(&agent.tools);
agent.tools.add(cm);
agent.append_system(
@@ -1183,19 +1112,15 @@ async fn main() -> Result<()> {
anyhow::bail!("--mode json needs -p <prompt>");
}
if CLAUDE_CLI.get().is_some() {
// claude asks here (via `hx mcp-serve`) before running its tools
let (p, cx) = (hx_core::approve::sock_path(), agent.cx.clone());
let _ = CLAUDE_CX.set(cx.clone());
let bus = agent.bus.clone();
// only -p has no prompt; `permissions = "deny" | "extensions-only"` closes it
let mode = hx_core::approve::Unanswered::from_config(cfg.permissions.as_deref());
tokio::spawn(async move {
let _ = hx_core::approve::serve(&p, cx, bus, mode).await;
});
}
if let Some(id) = acp_id {
// no TUI, no prompts: every permission question goes to the orchestrator, except what
// --yolo / --auto (or `permissions` in config.toml) settle here, the same as in the TUI
{
let yolo = cli.yolo || cfg.permissions.as_deref() == Some("yolo");
let auto = cli.auto || cfg.permissions.as_deref() == Some("auto");
-12
View File
@@ -1,5 +1,3 @@
//! Machine interfaces: NDJSON event stream (`--mode json`) and JSON-RPC over stdio (`--mode rpc`).
use anyhow::Result;
use hx_core::agent::{AbortHandle, Agent};
use hx_core::hook::{Event, Hook, HookAction};
@@ -9,14 +7,12 @@ use std::sync::Arc;
use tokio::io::AsyncBufReadExt;
use tokio::sync::Mutex;
/// One JSON line on stdout.
pub fn emit(v: &Value) {
let mut o = std::io::stdout().lock();
let _ = writeln!(o, "{v}");
let _ = o.flush();
}
/// `--mode json`: every bus event as one NDJSON line.
pub struct Ndjson;
#[async_trait::async_trait]
impl Hook for Ndjson {
@@ -26,7 +22,6 @@ impl Hook for Ndjson {
}
}
/// RPC mode forwards events as `event` notifications.
struct Notify;
#[async_trait::async_trait]
impl Hook for Notify {
@@ -43,10 +38,6 @@ fn reply(id: &Value, r: Result<Value, String>) {
});
}
/// Methods: `prompt {text}` (replies when the run ends; events stream meanwhile), `abort`,
/// `state`, `messages`, `fork {id}`, `clear`, `set_model {model}`, `compact`,
/// `complete {line, cursor?}` (cursor = byte offset, default end), `sessions {scope?: project|all}`,
/// `new`, `resume {path}`. One prompt at a time.
pub struct Ctx {
pub specs: Vec<hx_core::command::CmdSpec>,
pub files: Vec<String>,
@@ -77,7 +68,6 @@ pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()>
let id = m["id"].clone();
let p = &m["params"];
let method = m["method"].as_str().unwrap_or_default();
// abort and complete must work while a prompt holds the agent lock
if method == "complete" {
let Some(line) = p["line"].as_str() else {
reply(&id, Err("params.line required".into()));
@@ -141,7 +131,6 @@ pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()>
.map(|_| json!({"session": a.session().path()}))
.map_err(|e| e.to_string()),
"set_model" => match p["model"].as_str() {
// switches provider too when the model belongs to another one
Some(m) => switcher
.set_model(&mut a, m)
.map(|sw| {
@@ -185,7 +174,6 @@ pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()>
reply(&id, r);
}
}
// stdin closed: let a running prompt finish
for h in running {
let _ = h.await;
}