219 lines
7.6 KiB
Rust
219 lines
7.6 KiB
Rust
//! Wake-signal writer: notifies the hyperhive harness when an incoming
|
|
//! matrix event arrives so claude drives a new turn.
|
|
//!
|
|
//! Same wire shape as `hive-agent::forge_notify`'s wake: a single JSON
|
|
//! line written to the hyperhive control socket (`/run/hive/mcp.sock`
|
|
//! by default) carrying an `Request::Wake { from, body }`.
|
|
//! The agent harness's `agent_server` parses it and treats it as a
|
|
//! `Wake` from the matrix subsystem.
|
|
//!
|
|
//! Per the operator's call (phase 3): the body is a SHORT TEASER, not
|
|
//! the full message — the agent then reads the unmarked event via
|
|
//! the `read_room` MCP tool. Truncation to ~100 chars keeps the wake
|
|
//! prompt focused (`forge_notify` embeds longer excerpts because the
|
|
//! agent doesn't have a follow-up read-the-original tool for forge).
|
|
|
|
use std::path::Path;
|
|
|
|
use anyhow::{Context, Result};
|
|
use tokio::io::AsyncWriteExt;
|
|
use tokio::net::UnixStream;
|
|
|
|
/// Send an `Request::Wake { from: "matrix", body }` to the hyperhive
|
|
/// control socket at `socket`. Best-effort: returns Err on any plumbing
|
|
/// failure; callers log + ignore so a wake delivery hiccup doesn't tear
|
|
/// down the matrix sync loop.
|
|
///
|
|
/// Wire format matches `hive_agent_sock::Request` tagged with `"cmd"` per
|
|
/// `#[serde(tag = "cmd", rename_all = "snake_case")]`. Must be `"cmd"`,
|
|
/// not `"kind"` — the harness deserialises against the hive-sh4re type
|
|
/// and silently discards requests that don't match.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// Returns an error on socket connect failure, serialisation failure,
|
|
/// or I/O error writing to or reading from the socket.
|
|
pub async fn send_wake(socket: &Path, body: impl AsRef<str>) -> Result<()> {
|
|
let payload = serde_json::json!({
|
|
"cmd": "wake",
|
|
"from": "matrix",
|
|
"body": body.as_ref(),
|
|
"transient": true,
|
|
});
|
|
send_line(socket, &payload).await
|
|
}
|
|
|
|
/// Upsert a matrix-subsystem *todo* (loose-ends v2) on the
|
|
/// hyperhive control socket — the replacement for a direct wake. `key` is
|
|
/// the room id (the dedup key); hive-c0re coalesces a wake iff the todo is
|
|
/// new or its `summary` changed. Best-effort like [`send_wake`].
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// Returns an error on socket connect failure, serialisation failure,
|
|
/// or I/O error writing to or reading from the socket.
|
|
pub async fn send_todo_upsert(socket: &Path, key: &str, summary: impl AsRef<str>) -> Result<()> {
|
|
let payload = serde_json::json!({
|
|
"cmd": "upsert_todo",
|
|
"subsystem": "matrix",
|
|
"key": key,
|
|
"summary": summary.as_ref(),
|
|
});
|
|
send_line(socket, &payload).await
|
|
}
|
|
|
|
/// Clear matrix-subsystem todos. `key = Some(room)` clears one room's
|
|
/// todo (it was read); `all = true` wipes the whole matrix set
|
|
/// (cancel-and-recreate on daemon restart). Best-effort.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// Returns an error on socket connect failure, serialisation failure,
|
|
/// or I/O error writing to or reading from the socket.
|
|
pub async fn send_todo_clear(socket: &Path, key: Option<&str>, all: bool) -> Result<()> {
|
|
let payload = serde_json::json!({
|
|
"cmd": "clear_todo",
|
|
"subsystem": "matrix",
|
|
"key": key,
|
|
"all": all,
|
|
});
|
|
send_line(socket, &payload).await
|
|
}
|
|
|
|
/// Write one JSON request line to the hyperhive control socket and drain
|
|
/// the response line (best-effort — the reply is not acted on, we just
|
|
/// read it so the server doesn't get ECONNRESET on its write-back).
|
|
/// Shared by [`send_wake`] and the todo senders.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// Returns an error on socket connect failure, serialisation failure,
|
|
/// or I/O error writing to or reading from the socket.
|
|
async fn send_line(socket: &Path, payload: &serde_json::Value) -> Result<()> {
|
|
use tokio::io::AsyncBufReadExt;
|
|
|
|
let line = format!("{}\n", serde_json::to_string(payload)?);
|
|
let stream = UnixStream::connect(socket)
|
|
.await
|
|
.with_context(|| format!("connect hyperhive socket {}", socket.display()))?;
|
|
let (read, mut write) = stream.into_split();
|
|
write
|
|
.write_all(line.as_bytes())
|
|
.await
|
|
.with_context(|| format!("write to {}", socket.display()))?;
|
|
write
|
|
.shutdown()
|
|
.await
|
|
.with_context(|| format!("shutdown write to {}", socket.display()))?;
|
|
let mut reader = tokio::io::BufReader::new(read);
|
|
let mut resp = String::new();
|
|
let _ = reader.read_line(&mut resp).await;
|
|
Ok(())
|
|
}
|
|
|
|
/// Format a wake-message body from a list of per-room unread summaries.
|
|
/// Single-room / single-message case collapses to the terse one-liner
|
|
/// format; multiple rooms expand to a bulleted list. Always appends a
|
|
/// read-hint line so the agent knows which tools to reach for.
|
|
#[must_use]
|
|
pub fn format_unread_summary(rooms: &[crate::protocol::RoomUnread]) -> String {
|
|
use std::fmt::Write as _;
|
|
if rooms.is_empty() {
|
|
return String::new();
|
|
}
|
|
// Terse path: exactly one room, exactly one unread with body.
|
|
if rooms.len() == 1 {
|
|
let r = &rooms[0];
|
|
if r.count == 1
|
|
&& let (Some(body), Some(sender)) = (&r.last_body, &r.last_sender)
|
|
{
|
|
return format!(
|
|
"[matrix] {sender} in {label}: {body} — use read_room to view, mark_read to clear",
|
|
label = r.label
|
|
);
|
|
}
|
|
return format!(
|
|
"[matrix] {} unread in {} — use read_room to view, mark_read to clear",
|
|
r.count, r.label
|
|
);
|
|
}
|
|
// Multi-room path.
|
|
let mut out = String::from("[matrix] unread messages:");
|
|
for r in rooms {
|
|
if r.count == 1
|
|
&& let (Some(body), Some(sender)) = (&r.last_body, &r.last_sender)
|
|
{
|
|
let _ = write!(out, "\n- {}: {sender}: {body}", r.label);
|
|
continue;
|
|
}
|
|
let _ = write!(out, "\n- {}: {} unread", r.label, r.count);
|
|
}
|
|
out.push_str("\nUse list_rooms + read_room to view, mark_read to clear.");
|
|
out
|
|
}
|
|
|
|
/// Prepend an account marker to a wake `body` when the daemon serves
|
|
/// more than one matrix account. `tag` is `Some(name)` only in
|
|
/// multi-account mode; `None` returns `body` unchanged so single-account
|
|
/// wakes keep their exact format. Shape: `[acct:<name>] <body>`.
|
|
#[must_use]
|
|
pub fn tag_account(tag: Option<&str>, body: String) -> String {
|
|
match tag {
|
|
Some(name) => format!("[acct:{name}] {body}"),
|
|
None => body,
|
|
}
|
|
}
|
|
|
|
/// Truncate `s` to `max` Unicode chars, appending `…` when cut.
|
|
/// Char-based not byte-based so multi-byte content (most chat) doesn't
|
|
/// get cut mid-codepoint.
|
|
#[must_use]
|
|
pub fn truncate_chars(s: &str, max: usize) -> String {
|
|
let mut end = s.len();
|
|
for (count, (i, _)) in s.char_indices().enumerate() {
|
|
if count == max {
|
|
end = i;
|
|
break;
|
|
}
|
|
}
|
|
if end == s.len() {
|
|
s.to_owned()
|
|
} else {
|
|
format!("{}…", &s[..end])
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn truncate_chars_handles_multibyte() {
|
|
// `ü` is 2 bytes / 1 char. truncating to 3 chars on "üüüüüü"
|
|
// should yield "üüü…" not "üü\xc3…" (mid-codepoint).
|
|
let s = "üüüüüü";
|
|
let t = truncate_chars(s, 3);
|
|
assert_eq!(t, "üüü…");
|
|
}
|
|
|
|
#[test]
|
|
fn truncate_chars_no_op_below_limit() {
|
|
let s = "hi";
|
|
assert_eq!(truncate_chars(s, 100), "hi");
|
|
}
|
|
|
|
#[test]
|
|
fn tag_account_none_is_passthrough() {
|
|
let body = "[matrix] @a:s in #x: hi".to_owned();
|
|
assert_eq!(tag_account(None, body.clone()), body);
|
|
}
|
|
|
|
#[test]
|
|
fn tag_account_some_prepends_marker() {
|
|
let body = "[matrix] @a:s in #x: hi".to_owned();
|
|
assert_eq!(
|
|
tag_account(Some("ccc"), body),
|
|
"[acct:ccc] [matrix] @a:s in #x: hi"
|
|
);
|
|
}
|
|
}
|