1use std::net::SocketAddr;
19use std::path::{Path, PathBuf};
20use std::sync::Arc;
21
22use axum::Router;
23use axum::routing::post;
24use printobserver_core::store::Stores;
25use printobserver_core::{Clock as _, CoreConfig, Supervisor, SystemClock};
26use printobserver_obico::{ObicoVision, ObicoVisionConfig};
27use printobserver_octoprint::OctoPrintPrinter;
28use printobserver_oneharness::{
29 AssessmentSchema, HarnessSignIn, OneharnessSupervisor, SupervisorConfig,
30};
31use printobserver_printer_api::{PrinterError, PrinterPort};
32use printobserver_store_sqlite::SqliteStore;
33use printobserver_supervisor_api::SupervisorPort;
34use tokio::net::TcpListener;
35use tokio::sync::{oneshot, watch};
36use tokio::task::JoinHandle;
37
38use crate::api::{ApiState, router};
39use crate::config::{ApiCredential, ConfigError, ConfigField, ServerConfig};
40use crate::ingress::{IngressState, receive};
41use crate::operations::INGRESS_PATH;
42use crate::reconcile::{ReconcileStores, Reconciliation, overdue, reconcile};
43
44pub const CONTEXT_PROGRAM: &str = "printobserver";
46
47pub const CLIENT_CONFIG_FILE: &str = "client.toml";
50
51pub const API_CREDENTIAL_FILE: &str = "api-credential";
55
56#[cfg(unix)]
62const PRIVATE: u32 = 0o600;
63
64#[must_use]
79pub fn context_command(client_config: &Path) -> String {
80 format!(
81 "{CONTEXT_PROGRAM} context --config {} --print-id {{print_id}}",
82 client_config.display()
83 )
84}
85
86fn write_client_config(
96 directory: &Path,
97 address: SocketAddr,
98 credential: &ApiCredential,
99) -> Result<PathBuf, StartError> {
100 use std::io::Write as _;
101
102 let path = directory.join(CLIENT_CONFIG_FILE);
103 let failing = |error: std::io::Error| StartError::State {
104 detail: format!("{} could not be written: {error}", path.display()),
105 };
106 let mut options = std::fs::OpenOptions::new();
107 options.write(true).create(true).truncate(true);
108 #[cfg(unix)]
109 std::os::unix::fs::OpenOptionsExt::mode(&mut options, PRIVATE);
110 let mut file = options.open(&path).map_err(failing)?;
111 #[cfg(unix)]
112 file.set_permissions(std::os::unix::fs::PermissionsExt::from_mode(PRIVATE))
113 .map_err(failing)?;
114 file.write_all(
115 format!(
116 "[client]\nserver = \"http://{address}\"\ncredential = \"{}\"\n",
117 toml_basic_string(credential.written())
118 )
119 .as_bytes(),
120 )
121 .map_err(failing)?;
122 Ok(path)
123}
124
125fn toml_basic_string(text: &str) -> String {
130 text.replace('\\', "\\\\").replace('"', "\\\"")
131}
132
133fn credential_in_force(config: &ServerConfig) -> Result<ApiCredential, StartError> {
145 use std::io::Write as _;
146
147 if let Some(configured) = &config.api_credential {
148 return Ok(configured.clone());
149 }
150 let path = config.state_dir.join(API_CREDENTIAL_FILE);
151 let refusing = |detail: String| StartError::Credential {
152 path: path.clone(),
153 detail,
154 };
155 let mut options = std::fs::OpenOptions::new();
156 options.write(true).create_new(true);
157 #[cfg(unix)]
158 std::os::unix::fs::OpenOptionsExt::mode(&mut options, PRIVATE);
159 match options.open(&path) {
160 Ok(mut file) => {
161 let generated = ApiCredential::generate().map_err(|error| {
162 refusing(format!(
163 "no credential could be generated for it, because the operating system's \
164 random source refused: {error}"
165 ))
166 });
167 let written = generated.and_then(|credential| {
168 file.write_all(credential.written().as_bytes())
169 .and_then(|()| file.sync_all())
170 .map(|()| credential)
171 .map_err(|error| refusing(format!("it could not be written: {error}")))
172 });
173 if written.is_err() {
174 let _ = std::fs::remove_file(&path);
177 }
178 written
179 }
180 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
181 let held = std::fs::read(&path)
183 .map_err(|error| refusing(format!("it cannot be read: {error}")))?;
184 let text = core::str::from_utf8(&held).ok().map(without_terminator);
185 text.ok_or("it is not text")
186 .and_then(ApiCredential::new)
187 .map_err(|why| {
188 refusing(format!(
189 "{why}. This server does not replace a credential it did not write \
190 just now: correct the file, or remove it to have a new one generated"
191 ))
192 })
193 }
194 Err(error) => Err(refusing(format!("it cannot be created: {error}"))),
195 }
196}
197
198fn without_terminator(text: &str) -> &str {
205 text.strip_suffix("\r\n")
206 .or_else(|| text.strip_suffix('\n'))
207 .unwrap_or(text)
208}
209
210pub const PROMPT_FILE: &str = "turn-prompt.md";
212
213pub const SCHEMA_FILE: &str = "assessment-schema.json";
215
216pub const TURN_PROMPT: &str = printobserver_oneharness::DEFAULT_TURN_PROMPT;
222
223pub struct Ports {
228 pub printer: Arc<dyn PrinterPort>,
230 pub stores: Stores,
232 pub vision: Arc<ObicoVision>,
234 pub agent: Arc<dyn SupervisorPort>,
236}
237
238impl core::fmt::Debug for Ports {
239 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
240 formatter.debug_struct("Ports").finish_non_exhaustive()
241 }
242}
243
244#[derive(Debug)]
246pub enum StartError {
247 Configuration(ConfigError),
249 State {
251 detail: String,
253 },
254 Credential {
256 path: PathBuf,
258 detail: String,
260 },
261 Listen {
263 address: SocketAddr,
265 detail: String,
267 },
268 Store {
270 detail: String,
272 },
273 Supervisor {
275 detail: String,
277 },
278 Reconciliation {
280 detail: String,
282 },
283}
284
285impl StartError {
286 #[must_use]
288 pub const fn field(&self) -> Option<ConfigField> {
289 match self {
290 Self::Configuration(error) => error.field(),
291 _ => None,
292 }
293 }
294}
295
296impl core::fmt::Display for StartError {
297 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
298 match self {
299 Self::Configuration(error) => write!(formatter, "{error}"),
300 Self::State { detail } => {
301 write!(
302 formatter,
303 "the state directory could not be prepared: {detail}"
304 )
305 }
306 Self::Credential { path, detail } => write!(
307 formatter,
308 "the API credential file {} cannot be used: {detail}",
309 path.display()
310 ),
311 Self::Listen { address, detail } => {
312 write!(formatter, "{address} could not be listened on: {detail}")
313 }
314 Self::Store { detail } => write!(formatter, "the store could not be opened: {detail}"),
315 Self::Supervisor { detail } => write!(
316 formatter,
317 "the supervising agent's harness could not be reached: {detail}"
318 ),
319 Self::Reconciliation { detail } => write!(
320 formatter,
321 "what the store held could not be reconciled: {detail}"
322 ),
323 }
324 }
325}
326
327impl core::error::Error for StartError {}
328
329impl From<ConfigError> for StartError {
330 fn from(error: ConfigError) -> Self {
331 Self::Configuration(error)
332 }
333}
334
335#[derive(Debug)]
337pub struct Server;
338
339impl Server {
340 pub async fn start(config_path: impl AsRef<Path>) -> Result<Running, StartError> {
349 let config = ServerConfig::load(config_path)?;
350 let stores = Stores::of(Arc::new(SqliteStore::open(&config.state_dir).map_err(
351 |error| StartError::Store {
352 detail: error.to_string(),
353 },
354 )?));
355 let printer = Arc::new(OctoPrintPrinter::new(config.octoprint.clone()));
356 probe(printer.as_ref()).await?;
357 let vision = Arc::new(
358 ObicoVision::new(ObicoVisionConfig::default()).map_err(|error| StartError::State {
359 detail: error.to_string(),
360 })?,
361 );
362 let agent = Arc::new(agent_for(&config)?);
363 Self::start_with(
364 config,
365 Ports {
366 printer,
367 stores,
368 vision,
369 agent,
370 },
371 )
372 .await
373 }
374
375 pub async fn start_with(config: ServerConfig, ports: Ports) -> Result<Running, StartError> {
382 let credential = credential_in_force(&config)?;
386 let listener =
390 TcpListener::bind(config.listen)
391 .await
392 .map_err(|error| StartError::Listen {
393 address: config.listen,
394 detail: error.to_string(),
395 })?;
396 let address = listener.local_addr().map_err(|error| StartError::Listen {
397 address: config.listen,
398 detail: error.to_string(),
399 })?;
400 let client_config = write_client_config(&config.state_dir, address, &credential)?;
401 let clock = Arc::new(SystemClock);
402 let due = overdue(&ports.stores.actions, clock.now())
403 .await
404 .map_err(|error| StartError::Reconciliation {
405 detail: error.to_string(),
406 })?;
407 let supervisor = Supervisor::new(
408 CoreConfig::new(config.safety.clone(), context_command(&client_config)),
409 Arc::clone(&ports.printer),
410 ports.stores.clone(),
411 Arc::clone(&ports.vision) as Arc<dyn printobserver_vision_api::VisionPort>,
412 Arc::clone(&ports.agent),
413 clock,
414 );
415 let reconciliation = reconcile(
416 &supervisor,
417 &ReconcileStores {
418 prints: Arc::clone(&ports.stores.prints),
419 sessions: Arc::clone(&ports.stores.sessions),
420 events: Arc::clone(&ports.stores.events),
421 },
422 due,
423 )
424 .await
425 .map_err(|error| StartError::Reconciliation {
426 detail: error.to_string(),
427 })?;
428
429 let ingress = IngressState::start(
430 Arc::clone(&supervisor),
431 Arc::clone(&ports.stores.events),
432 Arc::clone(&ports.vision),
433 config.ingress_shared_secret.clone(),
434 config.ingress_answer_bound,
435 );
436 let completions = ingress.completions();
437 let application = router(ApiState {
438 supervisor: Arc::clone(&supervisor),
439 prints: Arc::clone(&ports.stores.prints),
440 events: Arc::clone(&ports.stores.events),
441 images: Arc::clone(&ports.stores.images),
442 sessions: Arc::clone(&ports.stores.sessions),
443 credential: Arc::new(credential),
444 })
445 .merge(
446 Router::new()
447 .route(INGRESS_PATH, post(receive))
448 .with_state(ingress),
449 );
450
451 let (stop, stopped) = oneshot::channel::<()>();
452 let serving = tokio::spawn(async move {
453 let _ = axum::serve(listener, application)
454 .with_graceful_shutdown(async move {
455 let _ = stopped.await;
456 })
457 .await;
458 });
459 Ok(Running {
460 address,
461 config,
462 supervisor,
463 stores: ports.stores,
464 reconciliation,
465 completions,
466 stop: Some(stop),
467 serving,
468 })
469 }
470}
471
472async fn probe(printer: &dyn PrinterPort) -> Result<(), StartError> {
480 match printer.snapshot().await {
481 Err(PrinterError::Unreachable { detail }) => {
482 Err(StartError::Configuration(ConfigError::about(
483 ConfigField::OctoprintUrl,
484 format!("nothing answers there: {detail}"),
485 )))
486 }
487 Err(PrinterError::Unauthorized { detail }) => {
488 Err(StartError::Configuration(ConfigError::about(
489 ConfigField::OctoprintApiKey,
490 format!("the OctoPrint instance refused it: {detail}"),
491 )))
492 }
493 _ => Ok(()),
494 }
495}
496
497fn materialize(
505 directory: &Path,
506 name: &str,
507 contents: &str,
508) -> Result<std::path::PathBuf, StartError> {
509 let path = directory.join(name);
510 std::fs::write(&path, contents).map_err(|error| StartError::State {
511 detail: format!("{} could not be written: {error}", path.display()),
512 })?;
513 Ok(path)
514}
515
516fn beside_the_skill(skill_path: &Path) -> std::path::PathBuf {
523 match skill_path.parent() {
524 Some(directory) if !directory.as_os_str().is_empty() => directory.to_path_buf(),
525 _ => std::path::PathBuf::from("."),
526 }
527}
528
529fn agent_for(config: &ServerConfig) -> Result<OneharnessSupervisor, StartError> {
532 OneharnessSupervisor::open(agent_config(config)?).map_err(|error| StartError::Supervisor {
533 detail: error.to_string(),
534 })
535}
536
537pub fn agent_config(config: &ServerConfig) -> Result<SupervisorConfig, StartError> {
553 let assets = config.assets_dir();
554 std::fs::create_dir_all(&assets).map_err(|error| StartError::State {
555 detail: format!("{} could not be created: {error}", assets.display()),
556 })?;
557 let prompt_template_path = match &config.prompt_template_path {
558 Some(path) => path.clone(),
559 None => materialize(&assets, PROMPT_FILE, TURN_PROMPT)?,
560 };
561 let schema_path = materialize(
562 &assets,
563 SCHEMA_FILE,
564 &printobserver_types::serde_json::to_string_pretty(
565 &printobserver_types::contract::schema_of::<
566 printobserver_supervisor_api::AgentAssessment,
567 >(),
568 )
569 .map_err(|error| StartError::State {
570 detail: error.to_string(),
571 })?,
572 )?;
573 let assessment_schema =
574 AssessmentSchema::at(&schema_path).map_err(|error| StartError::Supervisor {
575 detail: error.to_string(),
576 })?;
577 let harness_env = match HarnessSignIn::of(&config.harness) {
582 Some(sign_in) => {
583 let directory =
584 sign_in
585 .prepare(&config.state_dir)
586 .map_err(|error| StartError::State {
587 detail: format!(
588 "{} could not be created: {error}",
589 sign_in.directory(&config.state_dir).display()
590 ),
591 })?;
592 vec![
593 sign_in
594 .assignment(&directory)
595 .map_err(|error| StartError::Supervisor {
596 detail: error.to_string(),
597 })?,
598 ]
599 }
600 None => Vec::new(),
601 };
602 Ok(SupervisorConfig {
603 state_dir: config.state_dir.clone(),
604 skill_path: config.skill_path.clone(),
605 prompt_template_path,
606 assessment_schema,
607 harness: config.harness.clone(),
608 model: config.model.clone(),
609 working_dir: beside_the_skill(&config.skill_path),
613 turn_timeout: printobserver_oneharness::TurnTimeout::DEFAULT,
614 harness_bin: None,
615 harness_env,
616 })
617}
618
619pub struct Running {
624 address: SocketAddr,
626 config: ServerConfig,
628 supervisor: Arc<Supervisor>,
630 stores: Stores,
632 reconciliation: Reconciliation,
634 completions: watch::Receiver<u64>,
636 stop: Option<oneshot::Sender<()>>,
638 serving: JoinHandle<()>,
640}
641
642impl core::fmt::Debug for Running {
643 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
644 formatter
645 .debug_struct("Running")
646 .field("address", &self.address)
647 .field("reconciliation", &self.reconciliation)
648 .finish_non_exhaustive()
649 }
650}
651
652impl Running {
653 #[must_use]
655 pub const fn address(&self) -> SocketAddr {
656 self.address
657 }
658
659 #[must_use]
661 pub fn base_url(&self) -> String {
662 format!(
663 "http://{}{}",
664 self.address,
665 crate::operations::VERSION_PREFIX
666 )
667 }
668
669 #[must_use]
671 pub fn ingress_url(&self) -> String {
672 format!("http://{}{INGRESS_PATH}", self.address)
673 }
674
675 #[must_use]
677 pub const fn config(&self) -> &ServerConfig {
678 &self.config
679 }
680
681 #[must_use]
683 pub const fn reconciliation(&self) -> &Reconciliation {
684 &self.reconciliation
685 }
686
687 #[must_use]
689 pub const fn supervisor(&self) -> &Arc<Supervisor> {
690 &self.supervisor
691 }
692
693 #[must_use]
695 pub const fn stores(&self) -> &Stores {
696 &self.stores
697 }
698
699 #[must_use]
702 pub fn completions(&self) -> watch::Receiver<u64> {
703 self.completions.clone()
704 }
705
706 pub async fn stop(mut self) {
708 if let Some(stop) = self.stop.take() {
709 let _ = stop.send(());
710 }
711 let _ = (&mut self.serving).await;
712 }
713
714 pub async fn serve_until_signalled(self) -> Result<(), StartError> {
725 stop_requested().await?;
726 self.stop().await;
727 Ok(())
728 }
729}
730
731fn unhandled(what: &str, error: &std::io::Error) -> StartError {
733 StartError::State {
734 detail: format!("{what} cannot be handled: {error}"),
735 }
736}
737
738#[cfg(unix)]
743async fn stop_requested() -> Result<(), StartError> {
744 use tokio::signal::unix::{SignalKind, signal};
745
746 let mut terminate = signal(SignalKind::terminate())
747 .map_err(|error| unhandled("the termination signal", &error))?;
748 let mut interrupt = signal(SignalKind::interrupt())
749 .map_err(|error| unhandled("the interrupt signal", &error))?;
750 tokio::select! {
751 _ = terminate.recv() => {}
752 _ = interrupt.recv() => {}
753 }
754 Ok(())
755}
756
757#[cfg(windows)]
765async fn stop_requested() -> Result<(), StartError> {
766 use tokio::signal::windows::{ctrl_break, ctrl_c, ctrl_close, ctrl_shutdown};
767
768 let mut interrupt = ctrl_c().map_err(|error| unhandled("the CTRL_C event", &error))?;
769 let mut breaking = ctrl_break().map_err(|error| unhandled("the CTRL_BREAK event", &error))?;
770 let mut closing = ctrl_close().map_err(|error| unhandled("the CTRL_CLOSE event", &error))?;
771 let mut shutting_down =
772 ctrl_shutdown().map_err(|error| unhandled("the CTRL_SHUTDOWN event", &error))?;
773 tokio::select! {
774 _ = interrupt.recv() => {}
775 _ = breaking.recv() => {}
776 _ = closing.recv() => {}
777 _ = shutting_down.recv() => {}
778 }
779 Ok(())
780}
781
782impl Drop for Running {
783 fn drop(&mut self) {
784 if let Some(stop) = self.stop.take() {
785 let _ = stop.send(());
786 }
787 self.serving.abort();
788 }
789}