feat: add the multiplayer room server and client
A room is one conversation, one ssh sandbox, and one agent. Accounts create rooms; friends join through a single-use invite link and a display name; the agent speaks only through the message tool. The server is Axum and SQLite. It serves the built Nuxt client, streams room events over SSE, and runs one serialized turn loop per room with turn-level steering copied from rhema-code. The client has the chat, preview iframe, read-only file pane, xterm terminal, and presence. Preview URLs are signed wildcard hosts, and the proxy tunnels HTTP over ssh direct-tcpip. HostAgent::step remains deferred in the framework.
This commit is contained in:
1 parent
04dd63c4ca
commit
0035f4e031
69 files changed
+22501
-48
No files matched your search
@@ -0,0 +1,393 @@
|
||||
//! Building one turn: rows, the ssh sandbox, the provider, and the
|
||||
//! host agent over a stored session.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::num::NonZeroU32;
|
||||
use std::sync::Arc;
|
||||
|
||||
use base64::Engine;
|
||||
use rhema_bash::{AllowAll, ShellTools};
|
||||
use rhema_core::request::ThinkingEffort;
|
||||
use rhema_core::{Session, ToolResolver};
|
||||
use rhema_host_agent::{HostAgent, HostAgentConfig};
|
||||
use rhema_sandbox::WorkspaceSeed;
|
||||
use rhema_sandbox::{Sandbox, ShellSandbox};
|
||||
use rhema_sandbox_ssh::SshSandbox;
|
||||
|
||||
use crate::error::{AppError, AppResult};
|
||||
use crate::state::Shared;
|
||||
|
||||
use super::message_tool::MessageTool;
|
||||
|
||||
/// The room and its configuration, read fresh for every turn.
|
||||
pub struct TurnConfig {
|
||||
pub room_id: String,
|
||||
pub room_name: String,
|
||||
pub workspace: String,
|
||||
pub repo_url: Option<String>,
|
||||
pub model: String,
|
||||
pub max_turn_steps: u32,
|
||||
pub absorbed_seq: i64,
|
||||
pub seeded: bool,
|
||||
pub owner_name: String,
|
||||
pub members: Vec<String>,
|
||||
pub provider: ProviderRow,
|
||||
pub target: TargetRow,
|
||||
}
|
||||
|
||||
/// The provider row, ciphertext included.
|
||||
pub struct ProviderRow {
|
||||
pub kind: String,
|
||||
pub base_url: Option<String>,
|
||||
pub api_key_ciphertext: String,
|
||||
}
|
||||
|
||||
/// The sandbox row, ciphertext included.
|
||||
pub struct TargetRow {
|
||||
pub id: String,
|
||||
pub host: String,
|
||||
pub port: i64,
|
||||
pub user_name: String,
|
||||
pub private_key_ciphertext: String,
|
||||
pub host_fingerprint: Option<String>,
|
||||
}
|
||||
|
||||
/// Reads everything a turn needs.
|
||||
pub fn load_turn_config(state: &Shared, room_id: &str) -> AppResult<TurnConfig> {
|
||||
let conn = state.db.conn();
|
||||
let row = conn
|
||||
.query_row(
|
||||
"SELECT name, provider_config_id, sandbox_target_id, workspace, repo_url, model,
|
||||
max_turn_steps, absorbed_seq, seeded
|
||||
FROM rooms WHERE id = ?1 AND archived_at IS NULL",
|
||||
rusqlite::params![room_id],
|
||||
|row| {
|
||||
Ok((
|
||||
row.get::<_, String>(0)?,
|
||||
row.get::<_, Option<String>>(1)?,
|
||||
row.get::<_, Option<String>>(2)?,
|
||||
row.get::<_, String>(3)?,
|
||||
row.get::<_, Option<String>>(4)?,
|
||||
row.get::<_, Option<String>>(5)?,
|
||||
row.get::<_, i64>(6)?,
|
||||
row.get::<_, i64>(7)?,
|
||||
row.get::<_, i64>(8)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
.map_err(|_| AppError::not_found("room not found"))?;
|
||||
let (
|
||||
name,
|
||||
provider_id,
|
||||
target_id,
|
||||
workspace,
|
||||
repo_url,
|
||||
room_model,
|
||||
max_steps,
|
||||
absorbed,
|
||||
seeded,
|
||||
) = row;
|
||||
let provider_id =
|
||||
provider_id.ok_or_else(|| AppError::bad_request("room has no provider configured"))?;
|
||||
let target_id =
|
||||
target_id.ok_or_else(|| AppError::bad_request("room has no sandbox configured"))?;
|
||||
let (kind, provider_model, base_url, key) = conn.query_row(
|
||||
"SELECT kind, model, base_url, api_key_ciphertext FROM provider_configs WHERE id = ?1",
|
||||
rusqlite::params![provider_id],
|
||||
|row| {
|
||||
Ok((
|
||||
row.get::<_, String>(0)?,
|
||||
row.get::<_, String>(1)?,
|
||||
row.get::<_, Option<String>>(2)?,
|
||||
row.get::<_, String>(3)?,
|
||||
))
|
||||
},
|
||||
)?;
|
||||
let target = conn.query_row(
|
||||
"SELECT id, host, port, user_name, private_key_ciphertext, host_fingerprint
|
||||
FROM sandbox_targets WHERE id = ?1",
|
||||
rusqlite::params![target_id],
|
||||
|row| {
|
||||
Ok(TargetRow {
|
||||
id: row.get(0)?,
|
||||
host: row.get(1)?,
|
||||
port: row.get(2)?,
|
||||
user_name: row.get(3)?,
|
||||
private_key_ciphertext: row.get(4)?,
|
||||
host_fingerprint: row.get(5)?,
|
||||
})
|
||||
},
|
||||
)?;
|
||||
let owner_name: String = conn.query_row(
|
||||
"SELECT display_name FROM accounts WHERE id = (SELECT owner_id FROM rooms WHERE id = ?1)",
|
||||
rusqlite::params![room_id],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
let mut stmt =
|
||||
conn.prepare("SELECT display_name FROM members WHERE room_id = ?1 ORDER BY created_at")?;
|
||||
let members = stmt
|
||||
.query_map(rusqlite::params![room_id], |row| row.get::<_, String>(0))?
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(TurnConfig {
|
||||
room_id: room_id.to_owned(),
|
||||
room_name: name,
|
||||
workspace,
|
||||
repo_url,
|
||||
model: room_model.unwrap_or_else(|| provider_model.clone()),
|
||||
max_turn_steps: max_steps.max(1) as u32,
|
||||
absorbed_seq: absorbed,
|
||||
seeded: seeded != 0,
|
||||
owner_name,
|
||||
members,
|
||||
provider: ProviderRow {
|
||||
kind,
|
||||
base_url,
|
||||
api_key_ciphertext: key,
|
||||
},
|
||||
target,
|
||||
})
|
||||
}
|
||||
|
||||
/// The ssh destination in the form the backend resolves.
|
||||
fn destination(target: &TargetRow) -> String {
|
||||
format!("{}@{}:{}", target.user_name, target.host, target.port)
|
||||
}
|
||||
|
||||
/// A sandbox handle for this room.
|
||||
pub fn build_sandbox(state: &Shared, config: &TurnConfig) -> AppResult<SshSandbox> {
|
||||
sandbox_for(state, &config.workspace, &config.target)
|
||||
}
|
||||
|
||||
/// A sandbox handle from a workspace and a target row.
|
||||
pub fn sandbox_for(state: &Shared, workspace: &str, target: &TargetRow) -> AppResult<SshSandbox> {
|
||||
let key = state.secrets.open_str(&target.private_key_ciphertext)?;
|
||||
Ok(SshSandbox::new(destination(target))
|
||||
.with_workspace(workspace.to_owned())
|
||||
.with_private_key(key))
|
||||
}
|
||||
|
||||
/// The room's workspace and target, for routes that do not need the
|
||||
/// provider.
|
||||
pub fn load_room_target(state: &Shared, room: &str) -> AppResult<(String, TargetRow)> {
|
||||
let conn = state.db.conn();
|
||||
let (workspace, target_id): (String, Option<String>) = conn
|
||||
.query_row(
|
||||
"SELECT workspace, sandbox_target_id FROM rooms WHERE id = ?1 AND archived_at IS NULL",
|
||||
rusqlite::params![room],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)
|
||||
.map_err(|_| AppError::not_found("room not found"))?;
|
||||
let target_id =
|
||||
target_id.ok_or_else(|| AppError::bad_request("room has no sandbox configured"))?;
|
||||
let target = conn.query_row(
|
||||
"SELECT id, host, port, user_name, private_key_ciphertext, host_fingerprint
|
||||
FROM sandbox_targets WHERE id = ?1",
|
||||
rusqlite::params![target_id],
|
||||
|row| {
|
||||
Ok(TargetRow {
|
||||
id: row.get(0)?,
|
||||
host: row.get(1)?,
|
||||
port: row.get(2)?,
|
||||
user_name: row.get(3)?,
|
||||
private_key_ciphertext: row.get(4)?,
|
||||
host_fingerprint: row.get(5)?,
|
||||
})
|
||||
},
|
||||
)?;
|
||||
Ok((workspace, target))
|
||||
}
|
||||
|
||||
/// Creates the remote workspace on the first turn: a clone when the
|
||||
/// room names a repository, an empty directory otherwise.
|
||||
pub async fn ensure_workspace(state: &Shared, config: &TurnConfig) -> AppResult<()> {
|
||||
if config.seeded {
|
||||
return Ok(());
|
||||
}
|
||||
let sandbox = build_sandbox(state, config)?;
|
||||
let seed = match config.repo_url.as_deref().map(str::trim) {
|
||||
Some(url) if !url.is_empty() => WorkspaceSeed::GitClone(url.to_owned()),
|
||||
_ => WorkspaceSeed::Tarball {
|
||||
name: "room-seed".into(),
|
||||
tar_gz_base64: seed_tarball(config)?,
|
||||
},
|
||||
};
|
||||
sandbox
|
||||
.seed(&seed)
|
||||
.await
|
||||
.map_err(|err| AppError::internal(format!("could not prepare the workspace: {err}")))?;
|
||||
state.db.conn().execute(
|
||||
"UPDATE rooms SET seeded = 1 WHERE id = ?1",
|
||||
rusqlite::params![config.room_id],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn seed_tarball(config: &TurnConfig) -> AppResult<String> {
|
||||
let readme = format!(
|
||||
"# {}\n\nThis workspace belongs to the Rhema room \"{}\".\n\n\
|
||||
The agent works here with the same sandbox and key as the web terminal.\n\
|
||||
Open a terminal in the room to add a project, or create the room with a\n\
|
||||
repository URL to clone one.\n",
|
||||
config
|
||||
.workspace
|
||||
.trim_end_matches('/')
|
||||
.rsplit('/')
|
||||
.next()
|
||||
.unwrap_or("workspace"),
|
||||
config.room_name
|
||||
);
|
||||
let ignore = "node_modules/\ntarget/\n.env\n.DS_Store\n";
|
||||
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
|
||||
{
|
||||
let mut builder = tar::Builder::new(&mut gz);
|
||||
for (name, body) in [("README.md", readme.as_str()), (".gitignore", ignore)] {
|
||||
let mut header = tar::Header::new_gnu();
|
||||
header.set_path(name).map_err(|err| {
|
||||
AppError::internal(format!("could not build the room seed: {err}"))
|
||||
})?;
|
||||
header.set_mode(0o644);
|
||||
header.set_size(body.len() as u64);
|
||||
header.set_mtime(
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|value| value.as_secs())
|
||||
.unwrap_or(0),
|
||||
);
|
||||
header.set_cksum();
|
||||
builder.append(&header, body.as_bytes()).map_err(|err| {
|
||||
AppError::internal(format!("could not build the room seed: {err}"))
|
||||
})?;
|
||||
}
|
||||
builder
|
||||
.finish()
|
||||
.map_err(|err| AppError::internal(format!("could not build the room seed: {err}")))?;
|
||||
}
|
||||
let bytes = gz
|
||||
.finish()
|
||||
.map_err(|err| AppError::internal(format!("could not build the room seed: {err}")))?;
|
||||
Ok(base64::engine::general_purpose::STANDARD.encode(bytes))
|
||||
}
|
||||
|
||||
/// The turn's room section, rendered into the system prompt.
|
||||
fn room_section(config: &TurnConfig) -> String {
|
||||
let mut people = config.members.join(", ");
|
||||
if people.is_empty() {
|
||||
people = config.owner_name.clone();
|
||||
}
|
||||
format!(
|
||||
"Room \"{}\". Workspace {}. Sandbox {}@{}. Model {}.\n\
|
||||
People here: {}.",
|
||||
config.room_name,
|
||||
config.workspace,
|
||||
config.target.user_name,
|
||||
config.target.host,
|
||||
config.model,
|
||||
people
|
||||
)
|
||||
}
|
||||
|
||||
/// Assembles the host agent over `session`.
|
||||
pub fn build_agent(state: &Shared, config: &TurnConfig, session: Session) -> AppResult<HostAgent> {
|
||||
let sandbox = build_sandbox(state, config)?;
|
||||
let executor = Arc::new(ShellSandbox::new(Arc::new(sandbox)));
|
||||
let shell = Arc::new(ShellTools::with_executor(
|
||||
config.workspace.clone(),
|
||||
executor,
|
||||
));
|
||||
let api_key = state
|
||||
.secrets
|
||||
.open_str(&config.provider.api_key_ciphertext)?;
|
||||
let llama_url = (config.provider.kind == "llama-cpp")
|
||||
.then_some(config.provider.base_url.as_deref())
|
||||
.flatten();
|
||||
let built = rhema_provider_registry::build(
|
||||
&config.provider.kind,
|
||||
Some(&api_key),
|
||||
llama_url,
|
||||
config.provider.base_url.as_deref(),
|
||||
None,
|
||||
)
|
||||
.map_err(|err| AppError::bad_request(format!("provider: {err}")))?;
|
||||
let message_tool: Arc<dyn ToolResolver> =
|
||||
Arc::new(MessageTool::new(state.clone(), config.room_id.clone()));
|
||||
let max_turn_steps =
|
||||
NonZeroU32::new(config.max_turn_steps).unwrap_or(NonZeroU32::new(48).unwrap());
|
||||
let mut sections = BTreeMap::new();
|
||||
sections.insert("room".to_owned(), serde_json::json!(room_section(config)));
|
||||
let agent_config = HostAgentConfig {
|
||||
provider: built.provider,
|
||||
approval: Arc::new(AllowAll),
|
||||
model: config.model.clone(),
|
||||
system: None,
|
||||
base_system: Some(include_str!("prompt.md").to_owned()),
|
||||
workspace: config.workspace.clone().into(),
|
||||
skills: Some(Vec::new()),
|
||||
disabled_skills: Default::default(),
|
||||
mcp: None,
|
||||
disabled_subagents: Default::default(),
|
||||
subagent_providers: None,
|
||||
session_id: Some(config.room_id.clone()),
|
||||
max_turn_steps,
|
||||
thinking: ThinkingEffort::Default,
|
||||
tools: Some(shell),
|
||||
extra_resolver: Some(message_tool),
|
||||
shell_env: Default::default(),
|
||||
transcript: Some(Default::default()),
|
||||
summary_worker: None,
|
||||
steering: None,
|
||||
home: None,
|
||||
environment: Some(rhema_host_agent::remote_notice(
|
||||
"ssh",
|
||||
&config.workspace,
|
||||
&config.model,
|
||||
concat!("rhema-together ", env!("CARGO_PKG_VERSION")),
|
||||
)),
|
||||
user_preferences: None,
|
||||
supports_vision: None,
|
||||
vision: None,
|
||||
jobs: None,
|
||||
websearch: None,
|
||||
decision: None,
|
||||
sections,
|
||||
};
|
||||
let mut agent = HostAgent::from_session(agent_config, session)
|
||||
.map_err(|err| AppError::internal(format!("could not build the agent: {err}")))?;
|
||||
let db = state.db.clone();
|
||||
let room = config.room_id.clone();
|
||||
agent.set_commit_hook(Some(Box::new(move |session| {
|
||||
let json = serde_json::to_string(session)
|
||||
.map_err(|err| rhema_core::CommitError(err.to_string()))?;
|
||||
db.conn()
|
||||
.execute(
|
||||
"UPDATE rooms SET session_json = ?1 WHERE id = ?2",
|
||||
rusqlite::params![json, room],
|
||||
)
|
||||
.map_err(|err| rhema_core::CommitError(err.to_string()))?;
|
||||
Ok(())
|
||||
})));
|
||||
Ok(agent)
|
||||
}
|
||||
|
||||
/// Reads the saved session, or an empty one.
|
||||
pub fn load_session(state: &Shared, room: &str) -> AppResult<Session> {
|
||||
let json: Option<String> = state.db.conn().query_row(
|
||||
"SELECT session_json FROM rooms WHERE id = ?1",
|
||||
rusqlite::params![room],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
match json {
|
||||
Some(json) if !json.trim().is_empty() => serde_json::from_str(&json)
|
||||
.map_err(|err| AppError::internal(format!("saved session is corrupt: {err}"))),
|
||||
_ => Ok(Session::default()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Persists a session outside the commit hook (the end of a turn).
|
||||
pub fn save_session(state: &Shared, room: &str, session: &Session) -> AppResult<()> {
|
||||
let json = serde_json::to_string(session)?;
|
||||
state.db.conn().execute(
|
||||
"UPDATE rooms SET session_json = ?1 WHERE id = ?2",
|
||||
rusqlite::params![json, room],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//! The `message` tool: the agent's only way into the room.
|
||||
|
||||
use async_trait::async_trait;
|
||||
use rhema_core::request::ToolSpec;
|
||||
use rhema_core::tool::{ReplaySafety, ToolCall, ToolContext, ToolResolver, ToolResult};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::error::AppResult;
|
||||
use crate::models::Message;
|
||||
use crate::state::Shared;
|
||||
use crate::util::{mentions_agent, now_ms, random_id};
|
||||
|
||||
/// Posts an agent message into the room log.
|
||||
pub fn post_agent_message(state: &Shared, room: &str, text: &str) -> AppResult<Message> {
|
||||
let text = text.trim();
|
||||
let seq = state.hub.next_seq(&state.db, room);
|
||||
let message = Message {
|
||||
seq,
|
||||
id: random_id(16),
|
||||
author_id: None,
|
||||
author_name: "rhema".into(),
|
||||
author_kind: "agent".into(),
|
||||
text: text.to_owned(),
|
||||
mentions: mentions_agent(text),
|
||||
created_at: now_ms(),
|
||||
};
|
||||
let data = serde_json::to_value(&message)?;
|
||||
state.hub.insert(&state.db, room, seq, "message", &data)?;
|
||||
state.hub.broadcast(
|
||||
room,
|
||||
crate::models::Envelope {
|
||||
seq,
|
||||
kind: "message".into(),
|
||||
data,
|
||||
},
|
||||
);
|
||||
Ok(message)
|
||||
}
|
||||
|
||||
/// The resolver handed to the agent as an extra tool.
|
||||
pub struct MessageTool {
|
||||
state: Shared,
|
||||
room: String,
|
||||
}
|
||||
|
||||
impl MessageTool {
|
||||
/// A tool posting into `room`.
|
||||
pub fn new(state: Shared, room: String) -> Self {
|
||||
Self { state, room }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ToolResolver for MessageTool {
|
||||
fn specs(&self) -> Vec<ToolSpec> {
|
||||
vec![ToolSpec::new(
|
||||
"message",
|
||||
"Send a message to the people in the room. This is the only way you \
|
||||
speak: text outside this tool is not shown. One short message per \
|
||||
update. Always send one before the turn ends.",
|
||||
json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"text": {
|
||||
"type": "string",
|
||||
"description": "The message, in plain language. Address people by name."
|
||||
}
|
||||
},
|
||||
"required": ["text"]
|
||||
}),
|
||||
)]
|
||||
}
|
||||
|
||||
fn replay_safety(&self, _name: &str) -> ReplaySafety {
|
||||
// Posting twice would duplicate a line in the room. A resume
|
||||
// reports the call interrupted instead of re-running it.
|
||||
ReplaySafety::Unsafe
|
||||
}
|
||||
|
||||
async fn resolve(&self, call: ToolCall, _ctx: &ToolContext) -> ToolResult {
|
||||
let Some(text) = call.args.get("text").and_then(|value| value.as_str()) else {
|
||||
return ToolResult::failure(call.id, "`text` must be a string");
|
||||
};
|
||||
if text.trim().is_empty() {
|
||||
return ToolResult::failure(call.id, "the message is empty");
|
||||
}
|
||||
match post_agent_message(&self.state, &self.room, text) {
|
||||
Ok(_) => ToolResult::success(call.id, "sent"),
|
||||
Err(err) => ToolResult::failure(call.id, format!("could not post: {}", err.message)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
//! The room turn runner. Filled in below.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::state::Shared;
|
||||
|
||||
/// A wake signal for a room's turn task.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum Wake {
|
||||
/// A message was posted without mentioning the agent.
|
||||
Chat,
|
||||
/// A message mentioned the agent.
|
||||
Mention,
|
||||
}
|
||||
|
||||
struct Handle {
|
||||
tx: mpsc::UnboundedSender<Wake>,
|
||||
}
|
||||
|
||||
/// The live turn tasks, one per room.
|
||||
#[derive(Default)]
|
||||
pub struct RoomRunner {
|
||||
handles: Mutex<HashMap<String, Handle>>,
|
||||
current: Mutex<HashMap<String, Arc<AtomicBool>>>,
|
||||
}
|
||||
|
||||
impl RoomRunner {
|
||||
/// Notifies the room's task that new work may be pending, spawning
|
||||
/// the task on first use.
|
||||
pub fn wake(&self, state: &Shared, room: &str, wake: Wake) {
|
||||
let mut handles = self.handles.lock().unwrap_or_else(|err| err.into_inner());
|
||||
if let Some(handle) = handles.get(room) {
|
||||
let _ = handle.tx.send(wake);
|
||||
return;
|
||||
}
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
let _ = tx.send(wake);
|
||||
handles.insert(room.to_owned(), Handle { tx });
|
||||
let room = room.to_owned();
|
||||
let weak = std::sync::Arc::downgrade(state);
|
||||
tokio::spawn(async move {
|
||||
let Some(state) = weak.upgrade() else { return };
|
||||
crate::room::runner::run(state, room, rx).await;
|
||||
});
|
||||
}
|
||||
|
||||
/// Records the cancel flag of the turn now running in `room`.
|
||||
pub fn set_current(&self, room: &str, cancel: Arc<AtomicBool>) {
|
||||
self.current
|
||||
.lock()
|
||||
.unwrap_or_else(|err| err.into_inner())
|
||||
.insert(room.to_owned(), cancel);
|
||||
}
|
||||
|
||||
/// Forgets the running turn.
|
||||
pub fn clear_current(&self, room: &str) {
|
||||
self.current
|
||||
.lock()
|
||||
.unwrap_or_else(|err| err.into_inner())
|
||||
.remove(room);
|
||||
}
|
||||
|
||||
/// Flips the running turn's cancel flag. False when nothing runs.
|
||||
pub fn interrupt(&self, room: &str) -> bool {
|
||||
let current = self.current.lock().unwrap_or_else(|err| err.into_inner());
|
||||
match current.get(room) {
|
||||
Some(flag) => {
|
||||
flag.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub mod agent;
|
||||
pub mod message_tool;
|
||||
pub mod runner;
|
||||
@@ -0,0 +1,42 @@
|
||||
You are @rhema, the coding agent in a shared room.
|
||||
|
||||
{{ room }}
|
||||
|
||||
## Talking to the room
|
||||
|
||||
Every human line in the conversation starts with the speaker's name. People
|
||||
also talk to each other. Messages that mention @rhema ask you to act. The
|
||||
rest is context.
|
||||
|
||||
Your only way to speak is the `message` tool. Text you write outside that
|
||||
tool is not shown to anyone.
|
||||
|
||||
- Send one short message when you have something to say.
|
||||
- Always send one before the turn ends. A short "Ack." is enough for a small
|
||||
change.
|
||||
- Report a decision, a result, a blocker, or a question. Do not narrate every
|
||||
command.
|
||||
- When a decision belongs to the people in the room, ask in a message and
|
||||
stop.
|
||||
- Address people by name when you answer someone in particular.
|
||||
|
||||
## Work
|
||||
|
||||
The workspace is {{ workspace }}. Inspect before you edit. Use `bash` for
|
||||
reading, searching, editing, and running tests. Leave the tree in a state
|
||||
someone else can pick up. When you finish, say which files changed and which
|
||||
checks you ran.
|
||||
|
||||
{% if tools %}
|
||||
## Tools
|
||||
|
||||
You have the following tools: each entry is its name and arguments, then what
|
||||
it is for. The arguments are the JSON schema a call must satisfy.
|
||||
{% for tool in tools %}
|
||||
|
||||
|
||||
- {{ tool.name }} | {{ tool.parameters | json }}
|
||||
|
||||
{{ tool.description | indent(2, true) }}
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
@@ -0,0 +1,395 @@
|
||||
//! The per-room turn loop. One task per room, one turn at a time.
|
||||
//!
|
||||
//! Steering is turn level for now: a new mention drops the running turn
|
||||
//! future and starts a fresh turn over the committed session, the shape
|
||||
//! `rhema-code` uses. The step-level hook (`HostAgent::step`) is
|
||||
//! deferred; see the spec's framework section.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
use rhema_core::event::Event;
|
||||
use rhema_core::{EventSink, Message, Role, Session, Usage};
|
||||
use serde_json::json;
|
||||
use tokio::sync::mpsc::UnboundedReceiver;
|
||||
|
||||
use crate::error::AppResult;
|
||||
use crate::models::Message as RoomMessage;
|
||||
use crate::state::Shared;
|
||||
use crate::util::{now_ms, random_id};
|
||||
|
||||
use super::Wake;
|
||||
use super::agent::{self, TurnConfig};
|
||||
|
||||
/// Runs the room until the process stops.
|
||||
pub async fn run(state: Shared, room: String, mut rx: UnboundedReceiver<Wake>) {
|
||||
let mut pending_mention = false;
|
||||
loop {
|
||||
let Some(wake) = rx.recv().await else { break };
|
||||
if matches!(wake, Wake::Mention) {
|
||||
pending_mention = true;
|
||||
}
|
||||
if !pending_mention {
|
||||
continue;
|
||||
}
|
||||
loop {
|
||||
let config = match agent::load_turn_config(&state, &room) {
|
||||
Ok(config) => config,
|
||||
Err(err) => {
|
||||
notice(&state, &room, "error", err.message);
|
||||
pending_mention = false;
|
||||
break;
|
||||
}
|
||||
};
|
||||
let pending = match pending_messages(&state, &room, config.absorbed_seq) {
|
||||
Ok(pending) => pending,
|
||||
Err(err) => {
|
||||
notice(&state, &room, "error", err.message);
|
||||
pending_mention = false;
|
||||
break;
|
||||
}
|
||||
};
|
||||
if !pending.iter().any(|message| message.mentions) {
|
||||
pending_mention = false;
|
||||
break;
|
||||
}
|
||||
if let Err(err) = agent::ensure_workspace(&state, &config).await {
|
||||
notice(&state, &room, "error", err.message);
|
||||
pending_mention = false;
|
||||
break;
|
||||
}
|
||||
let mut session = match agent::load_session(&state, &room) {
|
||||
Ok(session) => session,
|
||||
Err(err) => {
|
||||
notice(&state, &room, "error", err.message);
|
||||
pending_mention = false;
|
||||
break;
|
||||
}
|
||||
};
|
||||
for message in &pending {
|
||||
session.history.push(Message::text(
|
||||
Role::User,
|
||||
format!("{}: {}", message.author_name, message.text),
|
||||
));
|
||||
}
|
||||
if let Err(err) = agent::save_session(&state, &room, &session) {
|
||||
notice(&state, &room, "error", err.message);
|
||||
pending_mention = false;
|
||||
break;
|
||||
}
|
||||
let last = pending.last().map(|message| message.seq).unwrap_or(0);
|
||||
let _ = state.db.conn().execute(
|
||||
"UPDATE rooms SET absorbed_seq = ?1 WHERE id = ?2",
|
||||
rusqlite::params![last as i64, room],
|
||||
);
|
||||
pending_mention = false;
|
||||
let trigger = pending
|
||||
.iter()
|
||||
.find(|message| message.mentions)
|
||||
.map(|message| message.author_name.clone())
|
||||
.unwrap_or_else(|| "someone".into());
|
||||
run_turn(
|
||||
&state,
|
||||
&room,
|
||||
&config,
|
||||
session,
|
||||
&trigger,
|
||||
&mut rx,
|
||||
&mut pending_mention,
|
||||
)
|
||||
.await;
|
||||
if !pending_mention {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_turn(
|
||||
state: &Shared,
|
||||
room: &str,
|
||||
config: &TurnConfig,
|
||||
session: Session,
|
||||
trigger: &str,
|
||||
rx: &mut UnboundedReceiver<Wake>,
|
||||
pending_mention: &mut bool,
|
||||
) {
|
||||
let mut agent = match agent::build_agent(state, config, session) {
|
||||
Ok(agent) => agent,
|
||||
Err(err) => {
|
||||
notice(state, room, "error", err.message);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let turn_id = random_id(12);
|
||||
let started = state.hub.durable(
|
||||
&state.db,
|
||||
room,
|
||||
"turn_start",
|
||||
json!({
|
||||
"turn_id": turn_id,
|
||||
"by": trigger,
|
||||
"model": config.model,
|
||||
"at": now_ms(),
|
||||
}),
|
||||
);
|
||||
if let Err(err) = started {
|
||||
notice(state, room, "error", err.message);
|
||||
return;
|
||||
}
|
||||
let mut sink = RoomSink::new(state.clone(), room.to_owned(), turn_id.clone());
|
||||
let cancelled = Arc::new(AtomicBool::new(false));
|
||||
state.rooms.set_current(room, cancelled.clone());
|
||||
let mut turn = Box::pin(agent.retry_turn_with_cancel(&mut sink, cancelled));
|
||||
let outcome = loop {
|
||||
tokio::select! {
|
||||
result = &mut turn => break Some(result),
|
||||
wake = rx.recv() => match wake {
|
||||
Some(Wake::Mention) => {
|
||||
*pending_mention = true;
|
||||
break None;
|
||||
}
|
||||
Some(Wake::Chat) => continue,
|
||||
None => break None,
|
||||
},
|
||||
}
|
||||
};
|
||||
drop(turn);
|
||||
state.rooms.clear_current(room);
|
||||
let session = agent.session().clone();
|
||||
if let Err(err) = agent::save_session(state, room, &session) {
|
||||
notice(state, room, "error", err.message);
|
||||
}
|
||||
let data = match outcome {
|
||||
Some(Ok(output)) => {
|
||||
let reason = match &output.stop_reason {
|
||||
rhema_core::StopReason::EndTurn => "done",
|
||||
rhema_core::StopReason::ToolUse => "step_limit",
|
||||
rhema_core::StopReason::MaxTokens => "max_tokens",
|
||||
_ => "done",
|
||||
};
|
||||
json!({
|
||||
"turn_id": turn_id,
|
||||
"status": reason,
|
||||
"usage": sink.usage_json(),
|
||||
"steps": sink.steps,
|
||||
})
|
||||
}
|
||||
Some(Err(err)) => json!({
|
||||
"turn_id": turn_id,
|
||||
"status": "error",
|
||||
"error": err.to_string(),
|
||||
"usage": sink.usage_json(),
|
||||
"steps": sink.steps,
|
||||
}),
|
||||
None => json!({
|
||||
"turn_id": turn_id,
|
||||
"status": "interrupted",
|
||||
"usage": sink.usage_json(),
|
||||
"steps": sink.steps,
|
||||
}),
|
||||
};
|
||||
if let Err(err) = state.hub.durable(&state.db, room, "turn_end", data) {
|
||||
notice(state, room, "error", err.message);
|
||||
}
|
||||
}
|
||||
|
||||
fn pending_messages(state: &Shared, room: &str, absorbed: i64) -> AppResult<Vec<RoomMessage>> {
|
||||
let conn = state.db.conn();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT data FROM events WHERE room_id = ?1 AND kind = 'message' AND seq > ?2
|
||||
ORDER BY seq ASC LIMIT 500",
|
||||
)?;
|
||||
let rows = stmt.query_map(rusqlite::params![room, absorbed], |row| {
|
||||
row.get::<_, String>(0)
|
||||
})?;
|
||||
let mut messages = Vec::new();
|
||||
for row in rows {
|
||||
let text = row?;
|
||||
if let Ok(message) = serde_json::from_str::<RoomMessage>(&text)
|
||||
&& message.author_kind == "human"
|
||||
{
|
||||
messages.push(message);
|
||||
}
|
||||
}
|
||||
Ok(messages)
|
||||
}
|
||||
|
||||
fn notice(state: &Shared, room: &str, level: &str, text: impl Into<String>) {
|
||||
let _ = state.hub.durable(
|
||||
&state.db,
|
||||
room,
|
||||
"notice",
|
||||
json!({ "level": level, "text": text.into(), "at": now_ms() }),
|
||||
);
|
||||
}
|
||||
|
||||
/// The sink that turns the engine's events into room events.
|
||||
struct RoomSink {
|
||||
state: Shared,
|
||||
room: String,
|
||||
turn_id: String,
|
||||
names: HashMap<String, String>,
|
||||
args: HashMap<String, String>,
|
||||
usage: Usage,
|
||||
steps: u32,
|
||||
}
|
||||
|
||||
impl RoomSink {
|
||||
fn new(state: Shared, room: String, turn_id: String) -> Self {
|
||||
Self {
|
||||
state,
|
||||
room,
|
||||
turn_id,
|
||||
names: HashMap::new(),
|
||||
args: HashMap::new(),
|
||||
usage: Usage::default(),
|
||||
steps: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn live(&self, kind: &str, data: serde_json::Value) {
|
||||
self.state.hub.live(&self.state.db, &self.room, kind, data);
|
||||
}
|
||||
|
||||
fn usage_json(&self) -> serde_json::Value {
|
||||
json!({
|
||||
"input_tokens": self.usage.input_tokens,
|
||||
"output_tokens": self.usage.output_tokens,
|
||||
"cached_input_tokens": self.usage.cached_input_tokens,
|
||||
"cost_usd": self.usage.cost_usd,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl EventSink for RoomSink {
|
||||
fn emit(&mut self, event: Event<'_>) {
|
||||
let turn = self.turn_id.clone();
|
||||
match event {
|
||||
Event::StepStart { iteration } => {
|
||||
self.live(
|
||||
"step_start",
|
||||
json!({ "turn_id": turn, "iteration": iteration }),
|
||||
);
|
||||
}
|
||||
Event::TextDelta(delta) => {
|
||||
self.live("text_delta", json!({ "turn_id": turn, "delta": delta }));
|
||||
}
|
||||
Event::ThinkingDelta(delta) => {
|
||||
self.live("thinking_delta", json!({ "turn_id": turn, "delta": delta }));
|
||||
}
|
||||
Event::ToolCallStart { id, name } => {
|
||||
self.names.insert(id.to_owned(), name.to_owned());
|
||||
self.live(
|
||||
"tool_start",
|
||||
json!({ "turn_id": turn, "call_id": id, "name": name }),
|
||||
);
|
||||
}
|
||||
Event::ToolCallArgsDelta { id, delta } => {
|
||||
self.args.entry(id.to_owned()).or_default().push_str(delta);
|
||||
self.live(
|
||||
"tool_args",
|
||||
json!({ "turn_id": turn, "call_id": id, "delta": delta }),
|
||||
);
|
||||
}
|
||||
Event::ToolOutputDelta { id, chunk } => {
|
||||
self.live(
|
||||
"tool_output",
|
||||
json!({ "turn_id": turn, "call_id": id, "chunk": chunk }),
|
||||
);
|
||||
}
|
||||
Event::ToolResult {
|
||||
id,
|
||||
content,
|
||||
is_error,
|
||||
code,
|
||||
} => {
|
||||
let name = self.names.remove(id).unwrap_or_default();
|
||||
let args = self.args.remove(id).unwrap_or_default();
|
||||
let data = json!({
|
||||
"turn_id": turn,
|
||||
"call_id": id,
|
||||
"name": name,
|
||||
"args": args,
|
||||
"content": truncate(content, 32_000),
|
||||
"is_error": is_error,
|
||||
"code": code,
|
||||
});
|
||||
let _ = self
|
||||
.state
|
||||
.hub
|
||||
.durable(&self.state.db, &self.room, "tool_result", data);
|
||||
}
|
||||
Event::Usage(usage) => {
|
||||
self.usage.input_tokens += usage.input_tokens;
|
||||
self.usage.output_tokens += usage.output_tokens;
|
||||
self.usage.cached_input_tokens += usage.cached_input_tokens;
|
||||
if let Some(cost) = usage.cost_usd {
|
||||
self.usage.cost_usd = Some(self.usage.cost_usd.unwrap_or(0.0) + cost);
|
||||
}
|
||||
self.live(
|
||||
"usage",
|
||||
json!({
|
||||
"turn_id": turn,
|
||||
"input_tokens": usage.input_tokens,
|
||||
"output_tokens": usage.output_tokens,
|
||||
"cached_input_tokens": usage.cached_input_tokens,
|
||||
"cost_usd": usage.cost_usd,
|
||||
}),
|
||||
);
|
||||
}
|
||||
Event::StepEnd { usage, stop_reason } => {
|
||||
self.steps += 1;
|
||||
self.live(
|
||||
"step_end",
|
||||
json!({
|
||||
"turn_id": turn,
|
||||
"usage": {
|
||||
"input_tokens": usage.input_tokens,
|
||||
"output_tokens": usage.output_tokens,
|
||||
"cached_input_tokens": usage.cached_input_tokens,
|
||||
"cost_usd": usage.cost_usd,
|
||||
},
|
||||
"stop_reason": format!("{stop_reason:?}"),
|
||||
}),
|
||||
);
|
||||
}
|
||||
Event::ToolStatus { id, status } => {
|
||||
self.live(
|
||||
"tool_status",
|
||||
json!({ "turn_id": turn, "call_id": id, "status": format!("{status:?}") }),
|
||||
);
|
||||
}
|
||||
Event::RetryWait {
|
||||
error,
|
||||
delay,
|
||||
attempt,
|
||||
total,
|
||||
} => {
|
||||
self.live(
|
||||
"retry_wait",
|
||||
json!({
|
||||
"turn_id": turn,
|
||||
"error": error,
|
||||
"delay_ms": delay.as_millis() as u64,
|
||||
"attempt": attempt,
|
||||
"total": total,
|
||||
}),
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn truncate(text: &str, max: usize) -> String {
|
||||
if text.len() <= max {
|
||||
return text.to_owned();
|
||||
}
|
||||
let mut end = max;
|
||||
while !text.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
format!("{}\n[truncated]", &text[..end])
|
||||
}
|
||||
Reference in new issue
Block a user