- hx-core: Tool trait + registry (schema validation, parallel calls), event bus with Block/Mutate/Inject hooks, agent loop (abort, max turns, AgentEnd inject), JSONL session tree (fork, resume, torn-line tolerant), AGENTS.md/CLAUDE.md hierarchy, skills index (bodies on demand) - hx-tools: read (ranges, binary, images, caps), write/edit (exact match, ambiguity, CRLF, diff, read-guard), bash (merged output, timeout kills process group, tail truncation to temp file) - hx-cli: -p runs full agent loop, --session / --continue, Ctrl-C abort, HX_BASE_URL override - tests/e2e.sh: scripted fake Anthropic server drives write -> bash -> answer Closes #6, closes #7, closes #8, closes #9, closes #10, closes #11, closes #12, closes #13, closes #14
This commit is contained in:
1 parent
da9d5d1ae0
commit
21d4d2bb3d
15 files changed
+1752
-52
No files matched your search
+111
-33
@@ -1,9 +1,14 @@
|
||||
use anyhow::Result;
|
||||
use clap::{Parser, Subcommand};
|
||||
use futures::StreamExt;
|
||||
use hx_ai::auth::{self, Kind};
|
||||
use hx_ai::{Message, Provider, Request, StreamEvent, anthropic::Anthropic, codex::Codex};
|
||||
use hx_ai::{Provider, StreamEvent, anthropic::Anthropic, codex::Codex};
|
||||
use hx_core::agent::Agent;
|
||||
use hx_core::context;
|
||||
use hx_core::hook::{Event, Hook, HookAction};
|
||||
use hx_core::session::Session;
|
||||
use hx_core::tool::ToolCtx;
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "hx", version, about = "Minimal coding agent")]
|
||||
@@ -18,6 +23,12 @@ struct Cli {
|
||||
provider: Kind,
|
||||
#[arg(short, long, env = "HX_MODEL")]
|
||||
model: Option<String>,
|
||||
/// Session file to resume (JSONL). Default: new file under ~/.hx/sessions.
|
||||
#[arg(short, long)]
|
||||
session: Option<std::path::PathBuf>,
|
||||
/// Continue the most recent session in this directory.
|
||||
#[arg(short, long)]
|
||||
r#continue: bool,
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
@@ -35,13 +46,65 @@ fn default_model(k: Kind) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
fn provider(k: Kind) -> hx_ai::Result<Box<dyn Provider>> {
|
||||
fn provider(k: Kind) -> hx_ai::Result<Arc<dyn Provider>> {
|
||||
Ok(match k {
|
||||
Kind::Claude => Box::new(Anthropic::login_default()?),
|
||||
Kind::Codex => Box::new(Codex::login_default()?),
|
||||
Kind::Claude => {
|
||||
let a = Anthropic::login_default()?;
|
||||
Arc::new(match std::env::var("HX_BASE_URL") {
|
||||
Ok(u) => a.with_base_url(u),
|
||||
Err(_) => a,
|
||||
})
|
||||
}
|
||||
Kind::Codex => {
|
||||
let c = Codex::login_default()?;
|
||||
Arc::new(match std::env::var("HX_BASE_URL") {
|
||||
Ok(u) => c.with_base_url(u),
|
||||
Err(_) => c,
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Streams text to stdout and tool activity to stderr.
|
||||
struct Printer;
|
||||
#[async_trait::async_trait]
|
||||
impl Hook for Printer {
|
||||
async fn on(&self, ev: &Event) -> HookAction {
|
||||
match ev {
|
||||
Event::Stream(StreamEvent::TextDelta { text }) => {
|
||||
let mut o = std::io::stdout().lock();
|
||||
let _ = o.write_all(text.as_bytes());
|
||||
let _ = o.flush();
|
||||
}
|
||||
Event::Stream(StreamEvent::Done { .. }) => println!(),
|
||||
Event::ToolCall { name, args, .. } => {
|
||||
let a = args.to_string();
|
||||
eprintln!("> {name} {}", a.chars().take(160).collect::<String>());
|
||||
}
|
||||
Event::ToolResult {
|
||||
is_error: true,
|
||||
content,
|
||||
..
|
||||
} => {
|
||||
eprintln!(" ! {}", content.lines().next().unwrap_or_default());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
HookAction::Continue
|
||||
}
|
||||
}
|
||||
|
||||
fn session_dir(cwd: &std::path::Path) -> std::path::PathBuf {
|
||||
let slug: String = cwd
|
||||
.to_string_lossy()
|
||||
.chars()
|
||||
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
|
||||
.collect();
|
||||
context::hx_home()
|
||||
.join("sessions")
|
||||
.join(slug.trim_matches('-'))
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let cli = Cli::parse();
|
||||
@@ -57,34 +120,49 @@ async fn main() -> Result<()> {
|
||||
let Some(prompt) = cli.print else {
|
||||
anyhow::bail!("interactive mode not implemented yet; use -p \"prompt\"");
|
||||
};
|
||||
let p = provider(cli.provider)?;
|
||||
let req = Request {
|
||||
model: cli
|
||||
.model
|
||||
.unwrap_or_else(|| default_model(cli.provider).into()),
|
||||
system: String::new(),
|
||||
messages: vec![Message::user(prompt)],
|
||||
tools: vec![],
|
||||
max_tokens: 8192,
|
||||
};
|
||||
let mut s = p.stream(req).await?;
|
||||
let mut out = std::io::stdout().lock();
|
||||
while let Some(ev) = s.next().await {
|
||||
match ev? {
|
||||
StreamEvent::TextDelta { text } => {
|
||||
out.write_all(text.as_bytes())?;
|
||||
out.flush()?;
|
||||
}
|
||||
StreamEvent::Done { usage, .. } => {
|
||||
writeln!(out)?;
|
||||
eprintln!(
|
||||
"[{} in / {} out tokens]",
|
||||
usage.input_tokens + usage.cache_read_tokens,
|
||||
usage.output_tokens
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
let cwd = std::env::current_dir()?;
|
||||
let dir = session_dir(&cwd);
|
||||
let path = match (cli.session, cli.r#continue) {
|
||||
(Some(p), _) => p,
|
||||
(None, true) => std::fs::read_dir(&dir)
|
||||
.ok()
|
||||
.and_then(|rd| rd.flatten().map(|e| e.path()).max())
|
||||
.ok_or_else(|| anyhow::anyhow!("no previous session in {}", dir.display()))?,
|
||||
(None, false) => {
|
||||
let ts = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)?
|
||||
.as_millis();
|
||||
dir.join(format!("{ts}.jsonl"))
|
||||
}
|
||||
}
|
||||
};
|
||||
let cx = ToolCtx {
|
||||
cwd: cwd.clone(),
|
||||
state: Default::default(),
|
||||
};
|
||||
let (mut agent, abort) = Agent::new(
|
||||
provider(cli.provider)?,
|
||||
hx_tools::registry(),
|
||||
Session::open(&path)?,
|
||||
cx,
|
||||
);
|
||||
agent.model = cli
|
||||
.model
|
||||
.unwrap_or_else(|| default_model(cli.provider).into());
|
||||
agent.system = context::system_prompt(None, &context::hx_home(), &cwd);
|
||||
agent.bus.add(Printer);
|
||||
tokio::spawn(async move {
|
||||
if tokio::signal::ctrl_c().await.is_ok() {
|
||||
abort.abort();
|
||||
}
|
||||
});
|
||||
let r = agent.run(prompt).await;
|
||||
let u = &agent.usage;
|
||||
eprintln!(
|
||||
"[{} in / {} out tokens; session {}]",
|
||||
u.input_tokens + u.cache_read_tokens,
|
||||
u.output_tokens,
|
||||
path.display()
|
||||
);
|
||||
r?;
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user