Merge pull request 'Add /btw side question' (#137) from feat/btw-wt into main

This commit was merged in pull request #137.
This commit is contained in:
hermes committed 2026-10-06 15:20:17 +00:00
commit 21ff700426
4 files changed
+233 -1

No files matched your search

+123
View File
@@ -10,6 +10,58 @@ use hx_ai::{ContentBlock, Message, Provider, Request, Role, StopReason, StreamEv
use std::sync::Arc;
use tokio::sync::watch;
/// What `/btw` needs, readable while a run holds the agent lock.
pub struct Snap {
provider: Arc<dyn Provider>,
model: String,
system: String,
messages: Vec<Message>,
}
impl Snap {
/// One tool-less request on the conversation so far plus `question`; nothing is saved.
/// Returns the answer and the request's usage.
pub async fn btw(&self, question: &str) -> Result<(String, Usage), Error> {
let mut messages = self.messages.clone();
// a run in flight may end on tool calls whose results are not in yet
if messages.last().is_some_and(|m| {
m.role == Role::Assistant
&& m.content
.iter()
.any(|b| matches!(b, ContentBlock::ToolUse { .. }))
}) {
messages.pop();
}
let q = ContentBlock::Text {
text: format!(
"Side question; answer briefly from the conversation so far, without tools:\n{question}"
),
};
match messages.last_mut() {
Some(m) if m.role == Role::User => m.content.push(q),
_ => messages.push(Message {
role: Role::User,
content: vec![q],
}),
}
let req = Request {
model: self.model.clone(),
system: self.system.clone(),
messages,
tools: vec![],
max_tokens: 2048,
effort: hx_ai::Effort::Off,
};
let mut s = self.provider.stream(req).await?;
while let Some(ev) = s.next().await {
if let StreamEvent::Done { message, usage, .. } = ev? {
return Ok((message.text(), usage));
}
}
Err(Error::Truncated)
}
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(transparent)]
@@ -39,6 +91,7 @@ pub struct Agent {
window: ContextWindow,
abort: watch::Receiver<bool>,
abort_tx: Arc<watch::Sender<bool>>,
snap: watch::Sender<Arc<Snap>>,
}
/// Cheap handle to cancel a running `Agent::run`.
@@ -64,6 +117,13 @@ impl Agent {
let (tx, rx) = watch::channel(false);
let tx = Arc::new(tx);
let _ = cx.state.abort.set(rx.clone());
let snap = watch::channel(Arc::new(Snap {
provider: provider.clone(),
model: String::new(),
system: String::new(),
messages: session.messages(),
}))
.0;
let a = Self {
provider,
tools,
@@ -79,10 +139,25 @@ impl Agent {
window: ContextWindow::new(150_000),
abort: rx,
abort_tx: tx.clone(),
snap,
};
(a, AbortHandle(tx))
}
/// Live view for `/btw`; stays readable while `run` holds the agent.
pub fn snap(&self) -> watch::Receiver<Arc<Snap>> {
self.snap.subscribe()
}
fn publish(&self) {
self.snap.send_replace(Arc::new(Snap {
provider: self.provider.clone(),
model: self.model.clone(),
system: self.system.clone(),
messages: self.session.messages(),
}));
}
pub fn set_max_turns(&mut self, n: u32) {
self.max_turns = n;
}
@@ -107,6 +182,7 @@ impl Agent {
/// Use another model of the current provider. For a different provider use [`set_provider`](Self::set_provider).
pub fn set_model(&mut self, model: impl Into<String>) {
self.model = model.into();
self.publish();
}
pub fn effort(&self) -> hx_ai::Effort {
@@ -120,12 +196,14 @@ impl Agent {
pub fn set_system(&mut self, system: impl Into<String>) {
self.system = system.into();
self.publish();
}
/// Append a section to the system prompt.
pub fn append_system(&mut self, section: &str) {
self.system.push_str("\n\n");
self.system.push_str(section);
self.publish();
}
/// Cap on tokens per reply. Set it before [`fit_window`](Self::fit_window), which reserves room for it.
@@ -164,6 +242,7 @@ impl Agent {
pub fn replace_session(&mut self, session: Session) {
self.session = session;
self.window.reset();
self.publish();
}
/// Move the session head to entry `id`. False (and no change) if there is no such entry.
@@ -171,6 +250,7 @@ impl Agent {
let ok = self.session.fork(id);
if ok {
self.window.reset();
self.publish();
}
ok
}
@@ -179,6 +259,7 @@ impl Agent {
pub fn clear(&mut self) -> Result<(), Error> {
self.session.rebase(vec![])?;
self.window.reset();
self.publish();
Ok(())
}
@@ -201,11 +282,13 @@ impl Agent {
let summary = summary.ok_or(Error::Truncated)?;
self.session.rebase(plan.apply(&summary))?;
self.window.reset();
self.publish();
Ok(true)
}
fn push(&mut self, m: Message) -> Result<(), Error> {
self.session.append(m)?;
self.publish();
Ok(())
}
@@ -213,6 +296,7 @@ impl Agent {
fn push_reply(&mut self, m: Message, usage: Usage, mask: usize) -> Result<(), Error> {
let by = Some(self.model.clone());
self.session.append_masked(m, by, Some(usage), Some(mask))?;
self.publish();
Ok(())
}
@@ -476,6 +560,45 @@ mod tests {
}
}
#[tokio::test]
async fn btw_reads_snapshot_without_touching_session() {
let script = Arc::new(Script(
Mutex::new(vec![
asst(vec![ContentBlock::Text {
text: "done".into(),
}]),
asst(vec![ContentBlock::Text {
text: "side".into(),
}]),
]),
Mutex::new(vec![]),
));
let dir = tempfile::tempdir().unwrap();
let cx = ToolCtx {
cwd: dir.path().into(),
state: Default::default(),
};
let (mut a, _h) = Agent::new(
script.clone(),
Registry::default(),
Session::open(dir.path().join("s.jsonl")).unwrap(),
cx,
);
let snap = a.snap();
a.run("go").await.unwrap();
let before = a.session().messages().len();
// taken from the receiver, no agent access: works while `run` holds the lock
let s = snap.borrow().clone();
let (text, _) = s.btw("why?").await.unwrap();
assert_eq!(text, "side");
assert_eq!(a.session().messages().len(), before);
let reqs = script.1.lock().unwrap();
let r = &reqs[1];
assert!(r.tools.is_empty());
assert_eq!(r.messages.len(), 3);
assert!(r.messages[2].text().contains("why?"));
}
#[tokio::test]
async fn multi_turn_with_hooks() {
let script = Arc::new(Script(
+1
View File
@@ -84,6 +84,7 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
"diff of this session's edits; reject reverts a file",
None,
),
b("btw", "side question; no tools, not saved", Free),
b("skills", "list skills and where they load from", None),
b(
"resume",