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(())
|
||||
}
|
||||
Reference in new issue
Block a user