use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use printobserver_supervisor_api::{
AgentAssessment, BoxFuture, CREDENTIAL_ENV, Confidence, SERVER_ENV, SupervisorError,
SupervisorPort, TurnAccess, TurnOutcome, TurnRequest,
};
use printobserver_supervisor_api::{SessionPhase, SupervisionSession};
use printobserver_types::{PrintId, Timestamp};
pub const IDENTITY: &str = "claude-code";
const HELD_AT_MOST: core::time::Duration = core::time::Duration::from_secs(60);
#[derive(Debug, Default)]
pub struct StandInAgent {
sessions: Mutex<BTreeMap<PrintId, SupervisionSession>>,
turns: Mutex<Vec<TurnRequest>>,
dwell: Mutex<core::time::Duration>,
passes: Mutex<Vec<Pass>>,
holding: Mutex<bool>,
failing: Mutex<Option<SupervisorError>>,
moving: Mutex<bool>,
released: tokio::sync::Notify,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pass {
pub session_name: String,
pub server: Option<String>,
pub credential: String,
}
#[must_use]
pub fn session_of(print_id: PrintId) -> String {
format!("print-{print_id}")
}
impl StandInAgent {
#[must_use]
pub fn new() -> Arc<Self> {
Arc::new(Self::default())
}
pub fn taking(&self, dwell: core::time::Duration) {
*self.dwell.lock().expect("the agent is not poisoned") = dwell;
}
#[must_use]
pub fn passes(&self) -> Vec<Pass> {
self.passes
.lock()
.expect("the agent is not poisoned")
.clone()
}
pub fn fail_turns_with(&self, error: SupervisorError) {
*self.failing.lock().expect("the agent is not poisoned") = Some(error);
}
pub fn move_turns_to_a_second_session(&self) {
*self.moving.lock().expect("the agent is not poisoned") = true;
}
pub fn hold_turns(&self) {
*self.holding.lock().expect("the agent is not poisoned") = true;
}
pub fn release_turns(&self) {
*self.holding.lock().expect("the agent is not poisoned") = false;
self.released.notify_waiters();
}
pub async fn issued(&self, count: usize) -> Vec<Pass> {
let deadline = tokio::time::Instant::now() + core::time::Duration::from_secs(30);
loop {
let passes = self.passes();
if passes.len() >= count {
return passes;
}
assert!(
tokio::time::Instant::now() < deadline,
"only {} of {count} turns were issued a pass",
passes.len()
);
tokio::time::sleep(core::time::Duration::from_millis(20)).await;
}
}
#[must_use]
pub fn turns(&self) -> Vec<TurnRequest> {
self.turns
.lock()
.expect("the agent is not poisoned")
.clone()
}
}
fn assessment() -> AgentAssessment {
AgentAssessment {
summary: "the first layer is down and the walls are clean".to_owned(),
confidence: Confidence::High,
should_continue: true,
did: "read the event, the picture and the print's context".to_owned(),
why: "nothing in the picture is coming away from the bed".to_owned(),
escalating: false,
disposition: printobserver_supervisor_api::Disposition::Continue,
}
}
impl SupervisorPort for StandInAgent {
fn run_turn(
&self,
request: TurnRequest,
access: std::sync::Arc<dyn TurnAccess>,
) -> BoxFuture<'_, Result<TurnOutcome, SupervisorError>> {
let dwell = *self.dwell.lock().expect("the agent is not poisoned");
let print_id = request.print_id;
let mut sessions_run = vec![session_of(print_id)];
if *self.moving.lock().expect("the agent is not poisoned") {
sessions_run.push(format!("{}-2", session_of(print_id)));
}
for session_name in sessions_run {
let issued = match printobserver_supervisor_api::TurnSession::new(session_name.as_str())
.and_then(|session| access.issue(&session))
{
Ok(issued) => issued,
Err(error) => return Box::pin(async move { Err(error) }),
};
let environment = issued.environment();
let value = |name: &str| {
environment
.iter()
.find(|(named, _)| *named == name)
.map(|(_, value)| value.clone())
};
self.passes
.lock()
.expect("the agent is not poisoned")
.push(Pass {
session_name,
server: value(SERVER_ENV),
credential: value(CREDENTIAL_ENV).unwrap_or_default(),
});
}
let failing = self
.failing
.lock()
.expect("the agent is not poisoned")
.clone();
let holding = *self.holding.lock().expect("the agent is not poisoned");
self.turns
.lock()
.expect("the agent is not poisoned")
.push(request);
let mut sessions = self.sessions.lock().expect("the agent is not poisoned");
let now = Timestamp::now();
let (phase, session) = match sessions.get(&print_id).cloned() {
Some(mut held) => {
held.last_turn_at = now;
(SessionPhase::Continued, held)
}
None => (
SessionPhase::Created,
SupervisionSession {
print_id,
session_name: session_of(print_id),
harness_identity: IDENTITY.to_owned(),
created_at: now,
last_turn_at: now,
closed_at: None,
close_reason: None,
},
),
};
sessions.insert(print_id, session.clone());
drop(sessions);
Box::pin(async move {
if holding {
let released = self.released.notified();
tokio::pin!(released);
released.as_mut().enable();
if *self.holding.lock().expect("the agent is not poisoned") {
let _ = tokio::time::timeout(HELD_AT_MOST, released).await;
}
}
if !dwell.is_zero() {
tokio::time::sleep(dwell).await;
}
if let Some(error) = failing {
return Err(error);
}
Ok(TurnOutcome {
session,
phase,
assessment: assessment(),
})
})
}
fn close_session(
&self,
print_id: PrintId,
close_reason: String,
) -> BoxFuture<'_, Result<(), SupervisorError>> {
let mut sessions = self.sessions.lock().expect("the agent is not poisoned");
if let Some(session) = sessions.get_mut(&print_id) {
session.closed_at = Some(Timestamp::now());
session.close_reason = Some(close_reason);
}
drop(sessions);
Box::pin(async move { Ok(()) })
}
}