use core::time::Duration;
use std::path::PathBuf;
use std::sync::Arc;
use printobserver_core::store::Stores;
use printobserver_obico::{ObicoVision, ObicoVisionConfig};
use printobserver_octoprint::{OctoPrintConfig, OctoPrintPrinter};
use printobserver_oneharness::{
AssessmentSchema, EnvAssignment, HarnessIdentity, OneharnessSupervisor, SupervisorConfig,
TurnTimeout,
};
use printobserver_printer_api::PrinterPort as _;
use printobserver_server::{Ports, Running, Server, ServerConfig};
use printobserver_store_sqlite::SqliteStore;
use printobserver_types::serde_json::json;
use tempfile::TempDir;
use crate::scripted::Scripted;
pub const SECRET: &str = "a-shared-secret-this-tier-configures";
pub const SESSION: &str = "watch-integration";
const TIMEOUT: Duration = Duration::from_secs(30);
pub const NARROWED: (f64, f64) = (0.8, 1.2);
pub const RESPONDER_LOG: &str = "responder-actions.log";
pub const AGENT_FACTOR: f64 = 1.15;
pub const AGENT_DURATION_S: i64 = 600;
pub const AGENT_REFUSED_FACTOR: f64 = 2.5;
pub const CONFIGURED_CREDENTIAL: &str = r#"a-configured-"credential"-with-a-\-in-it"#;
pub struct Composed {
pub root: TempDir,
pub server: Running,
pub stores: Stores,
pub client: reqwest::Client,
config: ServerConfig,
}
impl Composed {
pub async fn open(instance: &Scripted, octoprint: &str) -> Self {
let root = TempDir::new().expect("this tier's own root");
let config = configuration(root.path(), instance, octoprint);
let (server, stores) = start(&config).await;
let mut headers = reqwest::header::HeaderMap::new();
headers.insert(
reqwest::header::AUTHORIZATION,
reqwest::header::HeaderValue::from_str(&format!("Bearer {CONFIGURED_CREDENTIAL}"))
.expect("a credential is a header value"),
);
Self {
root,
server,
stores,
client: reqwest::Client::builder()
.default_headers(headers)
.build()
.expect("a client is built"),
config,
}
}
pub fn responder_log(&self) -> Vec<printobserver_types::serde_json::Value> {
std::fs::read_to_string(responder_log_path(&self.config))
.unwrap_or_default()
.lines()
.filter(|line| !line.trim().is_empty())
.map(|line| {
printobserver_types::serde_json::from_str(line)
.unwrap_or_else(|error| panic!("the responder wrote {line:?}: {error}"))
})
.collect()
}
pub fn forget_responder_log(&self) {
std::fs::write(responder_log_path(&self.config), "")
.expect("the responder's own log is writable");
}
pub async fn restart(self) -> Self {
let Self {
root,
server,
client,
config,
..
} = self;
server.stop().await;
let (server, stores) = start(&config).await;
Self {
root,
server,
stores,
client,
config,
}
}
pub fn operation_url(&self, name: &str, print_id: printobserver_types::PrintId) -> String {
let operation =
printobserver_server::operation(name).unwrap_or_else(|| panic!("`{name}` is served"));
format!(
"http://{}{}",
self.server.address(),
operation
.full_path()
.replace("{print_id}", &print_id.to_string())
.replace(
"{spool_id}",
&printobserver_core::SpoolId::new().to_string()
)
)
}
pub async fn get(
&self,
url: &str,
) -> (reqwest::StatusCode, printobserver_types::serde_json::Value) {
let response = self
.client
.get(url)
.send()
.await
.expect("the server answers");
read(response).await
}
pub async fn put(
&self,
url: &str,
body: &printobserver_types::serde_json::Value,
) -> (reqwest::StatusCode, printobserver_types::serde_json::Value) {
let response = self
.client
.put(url)
.json(body)
.send()
.await
.expect("the server answers");
read(response).await
}
pub async fn post(
&self,
url: &str,
body: &printobserver_types::serde_json::Value,
) -> (reqwest::StatusCode, printobserver_types::serde_json::Value) {
let response = self
.client
.post(url)
.json(body)
.send()
.await
.expect("the server answers");
read(response).await
}
}
async fn read(
response: reqwest::Response,
) -> (reqwest::StatusCode, printobserver_types::serde_json::Value) {
let status = response.status();
let text = response.text().await.expect("an answer has a body");
let value = printobserver_types::serde_json::from_str(&text)
.unwrap_or_else(|error| panic!("the answer is not JSON ({error}): {text}"));
(status, value)
}
fn configuration(root: &std::path::Path, instance: &Scripted, octoprint: &str) -> ServerConfig {
let document = format!(
r#"
state_dir = {state}
listen = "127.0.0.1:0"
[octoprint]
url = "{url}"
api_key = "{key}"
fan = "commandable"
[supervisor]
harness = "claude-code"
skill_path = {skill}
[ingress]
shared_secret = "{SECRET}"
answer_bound_ms = 1000
[api]
credential_verifier = "{verifier}"
[safety]
agent_min_interval_s = 0
[safety.allowed]
feedrate = {{ min = 0.5, max = 1.5 }}
flowrate = {{ min = 0.9, max = 1.1 }}
fan = {{ min = 0.0, max = 100.0 }}
bed_target = {{ min = 0.0, max = 110.0 }}
"tool_target:0" = {{ min = 0.0, max = 260.0 }}
[safety.actions]
operator = ["pause", "resume", "cancel", "start_print", "set_feedrate_factor",
"set_flowrate_factor", "set_tool_target_c", "set_bed_target_c",
"set_fan_percent", "acknowledge_failure"]
# The agent is granted one adjustment and nothing else, so an agent asking for
# anything else is a rejection of that operation's own kind — and the one it is
# granted is the one this tier's responder issues through the API.
agent = ["set_feedrate_factor"]
system = ["set_feedrate_factor", "set_flowrate_factor", "set_tool_target_c",
"set_bed_target_c", "set_fan_percent"]
"#,
state = toml::Value::String(root.join("state").display().to_string()),
skill = toml::Value::String(
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../skills/printobserver/SKILL.md")
.display()
.to_string()
),
url = octoprint,
key = instance.api_key,
verifier = printobserver_server::CredentialVerifier::of(CONFIGURED_CREDENTIAL),
);
let path = root.join("config.toml");
std::fs::write(&path, document).expect("the configuration is writable");
ServerConfig::load(&path).expect("this tier's configuration is accepted")
}
const HOLD_FILE: &str = "hold.gcode";
const REACHED: Duration = Duration::from_secs(120);
fn printer(instance: &Scripted) -> OctoPrintPrinter {
OctoPrintPrinter::new(
OctoPrintConfig::new(&instance.url, instance.api_key.clone())
.expect("the scripted instance is a configuration")
.with_timeout(TIMEOUT),
)
}
pub async fn hold_the_print_running(instance: &Scripted) {
let printer = printer(instance);
let state = printer.job().await.expect("a job snapshot").state;
if state != printobserver_printer_api::PrinterState::Printing {
if state == printobserver_printer_api::PrinterState::Paused {
printer
.cancel()
.await
.expect("the paused print is cancelled");
until_job(
&printer,
&printobserver_printer_api::PrinterState::Operational,
)
.await;
}
if printer.job().await.expect("a job snapshot").state
!= printobserver_printer_api::PrinterState::Printing
{
printer
.start(printobserver_types::FileName::new(HOLD_FILE).expect("a file name"))
.await
.expect("the hold print starts");
}
}
until_job(&printer, &printobserver_printer_api::PrinterState::Printing).await;
}
async fn until_job(printer: &OctoPrintPrinter, wanted: &printobserver_printer_api::PrinterState) {
let deadline = std::time::Instant::now() + REACHED;
let mut last = None;
while std::time::Instant::now() < deadline {
let seen = printer.job().await.expect("a job snapshot").state;
if seen == *wanted {
return;
}
last = Some(seen);
tokio::time::sleep(Duration::from_millis(500)).await;
}
panic!("waited {REACHED:?} for the machine to report {wanted:?}; it reported {last:?}");
}
fn materialize(directory: &std::path::Path, name: &str, contents: &str) -> PathBuf {
std::fs::create_dir_all(directory).expect("an assets directory");
let path = directory.join(name);
std::fs::write(&path, contents).expect("an asset is writable");
path
}
fn agent(config: &ServerConfig) -> OneharnessSupervisor {
let assets = config.assets_dir();
let template = materialize(
&assets,
"turn-prompt.md",
printobserver_oneharness::DEFAULT_TURN_PROMPT,
);
let schema = materialize(
&assets,
"assessment-schema.json",
&printobserver_types::serde_json::to_string_pretty(
&printobserver_types::contract::schema_of::<
printobserver_supervisor_api::AgentAssessment,
>(),
)
.expect("the schema renders"),
);
let answer = json!({
"summary": "the first layer is down and the walls are clean",
"confidence": "high",
"should_continue": true,
"did": "slowed the feedrate for ten minutes and was refused a second change",
"why": "the extrusion width was widening on the long edges",
"escalating": false,
})
.to_string();
let document = json!({
"result": answer,
"session_id": SESSION,
"thread_id": SESSION,
})
.to_string();
OneharnessSupervisor::open(SupervisorConfig {
state_dir: config.state_dir.clone(),
skill_path: config.skill_path.clone(),
prompt_template_path: template,
assessment_schema: AssessmentSchema::at(&schema).expect("the schema constrains an answer"),
harness: HarnessIdentity::new("claude-code").expect("a harness identity"),
model: None,
working_dir: config.state_dir.clone(),
turn_timeout: TurnTimeout::new(240).expect("a bound"),
harness_bin: Some(PathBuf::from(env!(
"CARGO_BIN_EXE_printobserver-server-responder"
))),
harness_env: vec![
EnvAssignment::new(&format!("MOCK_STDOUT={document}")).expect("an assignment"),
EnvAssignment::new(&format!(
"PRINTOBSERVER_RESPONDER_LOG={}",
responder_log_path(config).display()
))
.expect("an assignment"),
EnvAssignment::new(&format!(
"PRINTOBSERVER_RESPONDER_ACTIONS={}",
responder_actions()
))
.expect("an assignment"),
],
agent_commands: Vec::new(),
})
.expect("the supervising agent is built")
}
fn responder_log_path(config: &ServerConfig) -> PathBuf {
config
.state_dir
.parent()
.unwrap_or(&config.state_dir)
.join(RESPONDER_LOG)
}
fn responder_actions() -> String {
json!([
{
"operation": "set_feedrate_factor",
"body": {
"reason": "the extrusion width is widening on the long edges",
"factor": AGENT_FACTOR,
"duration_s": AGENT_DURATION_S,
},
},
{
"operation": "set_feedrate_factor",
"body": {
"reason": "asking for more than the operator's envelope allows",
"factor": AGENT_REFUSED_FACTOR,
},
},
])
.to_string()
}
async fn start(config: &ServerConfig) -> (Running, Stores) {
let stores = Stores::of(Arc::new(
SqliteStore::open(&config.state_dir).expect("the store opens"),
));
let printer = Arc::new(OctoPrintPrinter::new(
config.octoprint.clone().with_timeout(TIMEOUT),
));
let server = Server::start_with(
config.clone(),
Ports {
printer: printer as Arc<dyn printobserver_printer_api::PrinterPort>,
stores: stores.clone(),
vision: Arc::new(
ObicoVision::new(ObicoVisionConfig::default()).expect("the adapter is built"),
),
agent: Arc::new(agent(config)) as Arc<dyn printobserver_supervisor_api::SupervisorPort>,
},
)
.await
.expect("the server starts against the scripted instance");
(server, stores)
}