use super::{fake_error, record_request, send_mcp, Record, Signal};
use agent_client_protocol::{
schema::ProtocolVersion,
v2::{schema as v2, ConnectionTo, Responder},
Agent, Client, ConnectTo, Error,
};
use rho_tools::cancellation::RunCancellation;
use serde::{Deserialize, Serialize};
use std::{
collections::VecDeque,
sync::{Arc, Mutex},
};
use tokio::sync::mpsc;
pub(crate) const SESSION: &str = "scripted-session";
#[derive(Clone, Default, Serialize, Deserialize)]
pub(crate) struct V2Script {
#[serde(default)]
pub(crate) config_options: Vec<v2::SessionConfigOption>,
#[serde(default)]
pub(crate) sticky_config: Vec<String>,
#[serde(default)]
pub(crate) mode_after_set: Option<String>,
#[serde(default)]
pub(crate) mcp_over_acp: bool,
#[serde(default)]
pub(crate) image_prompts: bool,
pub(crate) turns: Vec<Vec<V2Step>>,
#[serde(default)]
pub(crate) refuse_steers: bool,
#[serde(default)]
pub(crate) hold_steers: bool,
}
#[derive(Default)]
struct Steering {
playing: std::sync::atomic::AtomicBool,
steered: tokio::sync::Notify,
refuse: bool,
hold: bool,
held: Mutex<Option<Responder<v2::PromptResponse>>>,
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(tag = "step", rename_all = "snake_case")]
pub(crate) enum V2Step {
Update {
#[serde(default)]
session: Option<String>,
#[serde(deserialize_with = "update_from_value")]
update: Box<v2::SessionUpdate>,
},
Running,
Idle {
#[serde(default)]
stop_reason: Option<v2::StopReason>,
},
Hang,
Wait { millis: u64 },
Rest,
Done,
Permission {
title: String,
#[serde(default)]
call: Option<Box<v2::ToolCallUpdate>>,
},
AwaitSteer,
Form {
request: Box<v2::CreateElicitationRequest>,
},
Mcp { envelope: serde_json::Value },
}
fn update_from_value<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> Result<Box<v2::SessionUpdate>, D::Error> {
let value = serde_json::Value::deserialize(deserializer)?;
serde_json::from_value(value).map_err(serde::de::Error::custom)
}
pub(super) async fn run(
script: V2Script,
record: Arc<Mutex<Record>>,
signals: mpsc::UnboundedSender<Signal>,
transport: impl ConnectTo<Agent> + 'static,
) -> Result<(), Error> {
let options = Arc::new(Mutex::new(script.config_options));
let turns = Arc::new(Mutex::new(VecDeque::from(script.turns)));
let cancelled = RunCancellation::new();
let sticky = script.sticky_config;
let mode_after_set = script.mode_after_set;
let mcp_over_acp = script.mcp_over_acp;
let image_prompts = script.image_prompts;
let steering = Arc::new(Steering {
refuse: script.refuse_steers,
hold: script.hold_steers,
..Steering::default()
});
let (initialize_record, new_record, resume_record, config_record, prompt_record) = (
Arc::clone(&record),
Arc::clone(&record),
Arc::clone(&record),
Arc::clone(&record),
Arc::clone(&record),
);
let (new_options, resume_options, config_options) = (
Arc::clone(&options),
Arc::clone(&options),
Arc::clone(&options),
);
let (prompt_signals, prompt_cancelled) = (signals.clone(), cancelled.clone());
Agent
.v2()
.name("rho-scripted-agent")
.on_receive_request(
async move |request: v2::InitializeRequest, responder, _cx| {
record_request(&initialize_record, "initialize", &request);
let session = v2::SessionCapabilities::new()
.mcp(
mcp_over_acp
.then(|| v2::McpCapabilities::new().acp(v2::McpAcpCapabilities::new())),
)
.prompt(image_prompts.then(|| {
v2::PromptCapabilities::new().image(v2::PromptImageCapabilities::new())
}));
responder.respond(
v2::InitializeResponse::new(
ProtocolVersion::V2,
v2::Implementation::new("rho-scripted-agent", "0"),
)
.capabilities(v2::AgentCapabilities::new().session(session)),
)
},
agent_client_protocol::on_receive_request!(),
)
.on_receive_request(
async move |request: v2::NewSessionRequest, responder, cx| {
record_request(&new_record, "session/new", &request);
let options = new_options.lock().expect("script options").clone();
cx.send_notification(options_changed(&options))?;
responder.respond(v2::NewSessionResponse::new(SESSION).config_options(options))
},
agent_client_protocol::on_receive_request!(),
)
.on_receive_request(
async move |request: v2::ResumeSessionRequest, responder, cx| {
record_request(&resume_record, "session/resume", &request);
cx.send_notification(idle(None))?;
let options = resume_options.lock().expect("script options").clone();
responder.respond(v2::ResumeSessionResponse::new().config_options(options))
},
agent_client_protocol::on_receive_request!(),
)
.on_receive_request(
async move |request: v2::SetSessionConfigOptionRequest, responder, cx| {
record_request(&config_record, "session/set_config_option", &request);
let mut options = config_options.lock().expect("script options");
if !sticky.contains(&request.config_id.to_string()) {
set_option(&mut options, &request)?;
cx.send_notification(options_changed(&options))?;
}
responder.respond(v2::SetSessionConfigOptionResponse::new(options.clone()))?;
if let Some(mode) = &mode_after_set {
let moved = v2::SetSessionConfigOptionRequest::new(
SESSION.to_owned(),
"mode",
v2::SessionConfigOptionValue::Id {
value: mode.clone().into(),
},
);
set_option(&mut options, &moved)?;
cx.send_notification(options_changed(&options))?;
}
Ok(())
},
agent_client_protocol::on_receive_request!(),
)
.on_receive_request(
async move |request: v2::PromptRequest, responder, cx| {
record_request(&prompt_record, "session/prompt", &request);
if steering.playing.load(std::sync::atomic::Ordering::SeqCst) {
steering.steered.notify_one();
if steering.refuse {
return responder.respond_with_error(fake_error("no steering here"));
}
if steering.hold {
*steering.held.lock().expect("held steer") = Some(responder);
return Ok(());
}
return responder.respond(v2::PromptResponse::new("steered-message"));
}
let _ = prompt_signals.send(Signal::Prompt);
let steps = next_turn(&turns)?;
let controls = (
Arc::clone(&prompt_record),
prompt_signals.clone(),
prompt_cancelled.clone(),
Arc::clone(&steering),
Arc::clone(&turns),
);
cx.clone()
.spawn(async move { play_turn(cx, responder, steps, controls).await })
},
agent_client_protocol::on_receive_request!(),
)
.on_receive_notification(
async move |notification: v2::CancelSessionNotification, _cx| {
record_request(&record, "session/cancel", ¬ification);
let _ = signals.send(Signal::Cancel);
cancelled.cancel();
Ok(())
},
agent_client_protocol::on_receive_notification!(),
)
.connect_with(transport, async move |cx: ConnectionTo<Client>| {
cx.incoming_closed().await;
Ok(())
})
.await
}
fn set_option(
options: &mut [v2::SessionConfigOption],
request: &v2::SetSessionConfigOptionRequest,
) -> Result<(), Error> {
let v2::SessionConfigOptionValue::Id { value } = &request.value else {
return Err(fake_error("the script sets select options only"));
};
let select = options
.iter_mut()
.find(|option| option.config_id == request.config_id)
.and_then(|option| match &mut option.kind {
v2::SessionConfigKind::Select(select) => Some(select),
_ => None,
})
.ok_or_else(|| fake_error("no such select option"))?;
select.current_value = value.clone();
Ok(())
}
fn options_changed(options: &[v2::SessionConfigOption]) -> v2::UpdateSessionNotification {
update(
SESSION,
v2::SessionUpdate::ConfigOptionUpdate(v2::ConfigOptionUpdate::new(options.to_vec())),
)
}
fn update(session: &str, update: v2::SessionUpdate) -> v2::UpdateSessionNotification {
v2::UpdateSessionNotification::new(session.to_owned(), update)
}
fn idle(stop_reason: Option<v2::StopReason>) -> v2::UpdateSessionNotification {
update(
SESSION,
v2::SessionUpdate::StateUpdate(v2::StateUpdate::Idle(
v2::IdleStateUpdate::new().stop_reason(stop_reason),
)),
)
}
type Turns = Arc<Mutex<VecDeque<Vec<V2Step>>>>;
fn next_turn(turns: &Turns) -> Result<Vec<V2Step>, Error> {
turns
.lock()
.expect("script turns")
.pop_front()
.ok_or_else(|| fake_error("unexpected prompt"))
}
fn running() -> v2::UpdateSessionNotification {
update(
SESSION,
v2::SessionUpdate::StateUpdate(v2::StateUpdate::Running(v2::RunningStateUpdate::new())),
)
}
async fn play_turn(
cx: ConnectionTo<Client>,
responder: Responder<v2::PromptResponse>,
steps: Vec<V2Step>,
(record, signals, cancelled, steering, turns): (
Arc<Mutex<Record>>,
mpsc::UnboundedSender<Signal>,
RunCancellation,
Arc<Steering>,
Turns,
),
) -> Result<(), Error> {
responder.respond(v2::PromptResponse::new("scripted-message"))?;
steering
.playing
.store(true, std::sync::atomic::Ordering::SeqCst);
let mut steps = VecDeque::from(steps);
while let Some(step) = steps.pop_front() {
match step {
V2Step::Update {
session,
update: body,
} => cx.send_notification(update(session.as_deref().unwrap_or(SESSION), *body))?,
V2Step::Running => cx.send_notification(running())?,
V2Step::Idle { stop_reason } => {
steering
.playing
.store(false, std::sync::atomic::Ordering::SeqCst);
cx.send_notification(idle(stop_reason))?;
let held = steering.held.lock().expect("held steer").take();
let Some(held) = held else {
return Ok(());
};
cx.send_notification(running())?;
held.respond(v2::PromptResponse::new("held-message"))?;
steering
.playing
.store(true, std::sync::atomic::Ordering::SeqCst);
steps = VecDeque::from(next_turn(&turns)?);
}
V2Step::AwaitSteer => {
let _ = signals.send(Signal::Waiting);
steering.steered.notified().await;
}
V2Step::Wait { millis } => {
tokio::time::sleep(std::time::Duration::from_millis(millis)).await;
}
V2Step::Done => {
steering
.playing
.store(false, std::sync::atomic::Ordering::SeqCst);
let _ = signals.send(Signal::Waiting);
return Ok(());
}
V2Step::Rest => {
let _ = signals.send(Signal::Waiting);
std::future::pending::<()>().await;
}
V2Step::Hang => {
let _ = signals.send(Signal::Waiting);
cancelled.cancelled().await;
return cx.send_notification(idle(Some(v2::StopReason::Cancelled)));
}
V2Step::Permission { title, call } => {
let subject = call.map(|call| {
v2::RequestPermissionSubject::ToolCall(Box::new(
v2::ToolCallPermissionSubject::new(*call),
))
});
let answer = cx
.send_request(
v2::RequestPermissionRequest::new(
SESSION.to_owned(),
title,
vec![
v2::PermissionOption::new(
"allow",
"Allow",
v2::PermissionOptionKind::AllowOnce,
),
v2::PermissionOption::new(
"reject",
"Reject",
v2::PermissionOptionKind::RejectOnce,
),
],
)
.subject(subject),
)
.block_task()
.await?;
record.lock().expect("script record").push_reply(
serde_json::json!({"method": "session/request_permission", "result": answer}),
);
}
V2Step::Form { request } => {
let answer = cx.send_request(*request).block_task().await?;
record.lock().expect("script record").push_reply(
serde_json::json!({"method": "elicitation/create", "result": answer}),
);
}
V2Step::Mcp { envelope } => {
send_mcp(&cx.clone().into_raw(), &record, vec![envelope], SESSION).await?;
}
}
}
Err(fake_error("script turn has no idle step"))
}