ci / checks (pull_request) Successful in 51s
ci / test (pull_request) Successful in 54s
ci / chart (pull_request) Successful in 4s
ci / web (pull_request) Successful in 16s
ci / docker (pull_request) Successful in 1m42s
ci / publish-edge-image (pull_request) Skipped
ci / publish-edge-chart (pull_request) Skipped
A message posted without a mention while the agent worked waited for the
next turn, so the model read it only once the work the line was about was
finished. The spec's turn rules already promised the mid-turn half ("the
next step of the running turn"); the runner implemented the turn-boundary
half only.
The turn now hands the framework a steering source. The driver drains it
between two steps and appends one User-role message per drain, so the line
lands in the history without the step in flight dying. The drain stops at
the first line it cannot carry -- a mention, which the drop path owns, or a
message with images, which a line cannot -- and leaves the cursor there, so
the boundary pass appends them in the log's order. What it drains advances
`absorbed_seq`, so nothing is appended twice.
A mention still drops the turn: that is the only way to stop a running
command, and this change does not touch it.
450 lines
16 KiB
Rust
450 lines
16 KiB
Rust
//! 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::{Overlay, Session, ToolResolver};
|
|
use rhema_host_agent::{HostAgent, HostAgentConfig, Steering};
|
|
use rhema_sandbox::WorkspaceSeed;
|
|
use rhema_sandbox::{Sandbox, ShellSandbox};
|
|
|
|
use crate::error::{AppError, AppResult};
|
|
use crate::state::Shared;
|
|
|
|
use super::message_tool::MessageTool;
|
|
use super::preview_tool::PreviewTool;
|
|
|
|
/// 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,
|
|
/// The model's stored vision fact; `None` is unknown, not no.
|
|
pub supports_vision: Option<bool>,
|
|
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.
|
|
#[derive(Clone)]
|
|
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<_>, _>>()?;
|
|
let model = room_model
|
|
.filter(|model| !model.trim().is_empty())
|
|
.unwrap_or(provider_model);
|
|
if model.trim().is_empty() {
|
|
return Err(AppError::bad_request("room has no model selected"));
|
|
}
|
|
let supports_vision = crate::util::model_supports_vision(&conn, &kind, &model);
|
|
Ok(TurnConfig {
|
|
room_id: room_id.to_owned(),
|
|
room_name: name,
|
|
workspace,
|
|
repo_url,
|
|
model,
|
|
supports_vision,
|
|
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,
|
|
})
|
|
}
|
|
|
|
/// A sandbox handle for this room. The control plane never opens the
|
|
/// ssh connection itself: the handle belongs to the room's disposable
|
|
/// worker, and every call crosses a loopback HTTP route.
|
|
pub fn build_sandbox(
|
|
state: &Shared,
|
|
config: &TurnConfig,
|
|
) -> AppResult<crate::worker::WorkerSandbox> {
|
|
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<crate::worker::WorkerSandbox> {
|
|
Ok(crate::worker::WorkerSandbox::new(
|
|
state.clone(),
|
|
workspace,
|
|
target,
|
|
))
|
|
}
|
|
|
|
/// 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`, with `steering` as the turn
|
|
/// loop's step-boundary source (see `runner::RoomSteering`).
|
|
pub fn build_agent(
|
|
state: &Shared,
|
|
config: &TurnConfig,
|
|
session: Session,
|
|
steering: Option<Arc<dyn Steering>>,
|
|
) -> 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 preview_tool: Arc<dyn ToolResolver> =
|
|
Arc::new(PreviewTool::new(state.clone(), config.room_id.clone()));
|
|
let extra_tools: Arc<dyn ToolResolver> = Arc::new(Overlay::new(message_tool, preview_tool));
|
|
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(extra_tools),
|
|
shell_env: Default::default(),
|
|
transcript: Some(Default::default()),
|
|
summary_worker: None,
|
|
steering,
|
|
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: config.supports_vision,
|
|
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()),
|
|
}
|
|
}
|
|
|
|
/// The images a human message carries, read back as inline blocks.
|
|
/// An attachment that vanished or is not a wire format the providers
|
|
/// share is skipped: the text still reaches the model.
|
|
pub fn load_images(
|
|
state: &Shared,
|
|
room: &str,
|
|
attachments: &[crate::models::Attachment],
|
|
) -> Vec<rhema_core::Image> {
|
|
use base64::Engine as _;
|
|
let conn = state.db.conn();
|
|
let mut images = Vec::with_capacity(attachments.len());
|
|
for attachment in attachments {
|
|
let row = conn.query_row(
|
|
"SELECT mime, bytes FROM attachments WHERE id = ?1 AND room_id = ?2",
|
|
rusqlite::params![attachment.id, room],
|
|
|row| Ok((row.get::<_, String>(0)?, row.get::<_, Vec<u8>>(1)?)),
|
|
);
|
|
let Ok((mime, bytes)) = row else {
|
|
continue;
|
|
};
|
|
let Some(media) = rhema_core::ImageMediaType::parse(&mime) else {
|
|
continue;
|
|
};
|
|
images.push(rhema_core::Image::new(
|
|
media,
|
|
base64::engine::general_purpose::STANDARD.encode(bytes),
|
|
));
|
|
}
|
|
images
|
|
}
|
|
|
|
/// 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(())
|
|
}
|