1use std::ffi::OsStr;
19use std::net::SocketAddr;
20use std::path::{Path, PathBuf};
21use std::sync::Arc;
22
23use axum::Router;
24use axum::routing::post;
25use printobserver_core::store::Stores;
26use printobserver_core::{Clock as _, CoreConfig, Supervisor, SystemClock};
27use printobserver_obico::{ObicoVision, ObicoVisionConfig};
28use printobserver_octoprint::OctoPrintPrinter;
29use printobserver_oneharness::{
30 AgentCommand, AssessmentSchema, EnvAssignment, HarnessSignIn, OneharnessSupervisor,
31 SupervisorConfig,
32};
33use printobserver_printer_api::{PrinterError, PrinterPort};
34use printobserver_store_sqlite::SqliteStore;
35use printobserver_supervisor_api::SupervisorPort;
36use tokio::net::TcpListener;
37use tokio::sync::{oneshot, watch};
38use tokio::task::JoinHandle;
39
40use crate::api::{ApiState, router};
41use crate::config::{ApiCredential, ConfigError, ConfigField, CredentialVerifier, ServerConfig};
42use crate::events::Stored;
43use crate::ingress::{IngressState, receive};
44use crate::operations::{INGRESS_PATH, OPERATIONS, command_for};
45use crate::reconcile::{ReconcileStores, Reconciliation, overdue, reconcile};
46use crate::turns::TurnCredentials;
47
48pub const CONTEXT_PROGRAM: &str = "printobserver";
50
51pub const CLIENT_CONFIG_FILE: &str = "client.toml";
56
57pub const API_CREDENTIAL_FILE: &str = "api-credential";
62
63pub const API_CREDENTIAL_VERIFIER_FILE: &str = "api-credential.verifier";
66
67pub const CREDENTIAL_ISSUE: &str = "printobserver credential issue";
70
71pub const CREDENTIAL_VERIFIER: &str = "printobserver credential verifier";
74
75#[cfg(unix)]
81const PRIVATE: u32 = 0o600;
82
83#[must_use]
92pub fn context_command() -> String {
93 format!("{CONTEXT_PROGRAM} context --print-id {{print_id}}")
94}
95
96#[derive(Debug, Clone)]
98pub enum OperatorCredential {
99 Verifier(CredentialVerifier),
101 Plaintext(ApiCredential),
104 Unconfigured,
107}
108
109impl OperatorCredential {
110 #[must_use]
112 pub fn admits(&self, presented: &[u8]) -> bool {
113 match self {
114 Self::Verifier(verifier) => verifier.admits(presented),
115 Self::Plaintext(credential) => credential.admits(presented),
116 Self::Unconfigured => false,
117 }
118 }
119}
120
121#[must_use]
125pub fn plaintext_credential_warning() -> String {
126 format!(
127 "the server configuration carries `api.credential`, an operator credential in \
128 plaintext. A supervision turn runs as this service's user and can read that file, \
129 so it can read that credential until it is replaced. Replace it with \
130 `api.credential_verifier`: pipe the credential into `{CREDENTIAL_VERIFIER}` to print \
131 that line, put it in the configuration, delete `api.credential`, and restart the \
132 service"
133 )
134}
135
136fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
138 use std::io::Write as _;
139
140 let mut options = std::fs::OpenOptions::new();
141 options.write(true).create_new(true);
142 #[cfg(unix)]
143 std::os::unix::fs::OpenOptionsExt::mode(&mut options, PRIVATE);
144 let mut file = options.open(path)?;
145 let written = file.write_all(contents).and_then(|()| file.sync_all());
147 if written.is_err() {
148 let _ = std::fs::remove_file(path);
151 }
152 written
153}
154
155fn remove_if_there(path: &Path) -> std::io::Result<()> {
157 match std::fs::remove_file(path) {
158 Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error),
159 _ => Ok(()),
160 }
161}
162
163fn take_plaintext_out(state_dir: &Path) -> Result<(), StartError> {
179 let client_config = state_dir.join(CLIENT_CONFIG_FILE);
180 remove_if_there(&client_config).map_err(|error| StartError::State {
181 detail: format!(
182 "{} could not be removed, and it may carry the operator's credential where a \
183 supervision turn can read it: {error}",
184 client_config.display()
185 ),
186 })?;
187 let legacy = state_dir.join(API_CREDENTIAL_FILE);
188 let refusing = |detail: String| StartError::Credential {
189 path: legacy.clone(),
190 detail,
191 };
192 let held = match std::fs::read(&legacy) {
193 Ok(held) => held,
194 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
195 Err(error) => return Err(refusing(format!("it cannot be read: {error}"))),
196 };
197 let verifier_file = state_dir.join(API_CREDENTIAL_VERIFIER_FILE);
198 if !verifier_file.exists() {
199 let text = core::str::from_utf8(&held).ok().map(without_terminator);
200 let credential = text
201 .ok_or("it is not text")
202 .and_then(ApiCredential::new)
203 .map_err(|why| {
204 refusing(format!(
205 "{why}. This server converts the credential an earlier version generated \
206 there into its verifier: correct the file, or remove it and run \
207 `{CREDENTIAL_ISSUE} --replace`"
208 ))
209 })?;
210 write_private(
211 &verifier_file,
212 format!("{}\n", credential.verifier()).as_bytes(),
213 )
214 .map_err(|error| {
215 refusing(format!(
216 "its verifier could not be written to {}: {error}",
217 verifier_file.display()
218 ))
219 })?;
220 }
221 std::fs::remove_file(&legacy)
222 .map_err(|error| refusing(format!("it could not be removed: {error}")))
223}
224
225pub fn operator_credential(
240 config: &ServerConfig,
241) -> Result<(OperatorCredential, Vec<String>), StartError> {
242 take_plaintext_out(&config.state_dir)?;
243 let mut warnings = Vec::new();
244 if config.api_credential.is_some() {
245 warnings.push(plaintext_credential_warning());
246 }
247 if let Some(verifier) = &config.api_credential_verifier {
248 return Ok((OperatorCredential::Verifier(verifier.clone()), warnings));
249 }
250 if let Some(plaintext) = &config.api_credential {
251 return Ok((OperatorCredential::Plaintext(plaintext.clone()), warnings));
252 }
253 let path = config.state_dir.join(API_CREDENTIAL_VERIFIER_FILE);
254 let held = match std::fs::read_to_string(&path) {
255 Ok(held) => held,
256 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
257 return Ok((OperatorCredential::Unconfigured, warnings));
258 }
259 Err(error) => {
260 return Err(StartError::Credential {
261 path,
262 detail: format!("it cannot be read: {error}"),
263 });
264 }
265 };
266 let verifier =
267 CredentialVerifier::parse(held.trim()).map_err(|why| StartError::Credential {
268 path: path.clone(),
269 detail: format!(
270 "{why}. Correct the file, or remove it and set `api.credential_verifier`"
271 ),
272 })?;
273 Ok((OperatorCredential::Verifier(verifier), warnings))
274}
275
276fn without_terminator(text: &str) -> &str {
283 text.strip_suffix("\r\n")
284 .or_else(|| text.strip_suffix('\n'))
285 .unwrap_or(text)
286}
287
288pub const PROMPT_FILE: &str = "turn-prompt.md";
290
291pub const SCHEMA_FILE: &str = "assessment-schema.json";
293
294pub const TURN_PROMPT: &str = printobserver_oneharness::DEFAULT_TURN_PROMPT;
300
301pub struct Ports {
306 pub printer: Arc<dyn PrinterPort>,
308 pub stores: Stores,
310 pub vision: Arc<ObicoVision>,
312 pub agent: Arc<dyn SupervisorPort>,
314}
315
316impl core::fmt::Debug for Ports {
317 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
318 formatter.debug_struct("Ports").finish_non_exhaustive()
319 }
320}
321
322#[derive(Debug)]
324pub enum StartError {
325 Configuration(ConfigError),
327 State {
329 detail: String,
331 },
332 Credential {
334 path: PathBuf,
336 detail: String,
338 },
339 Listen {
341 address: SocketAddr,
343 detail: String,
345 },
346 Store {
348 detail: String,
350 },
351 Supervisor {
353 detail: String,
355 },
356 Reconciliation {
358 detail: String,
360 },
361}
362
363impl StartError {
364 #[must_use]
366 pub const fn field(&self) -> Option<ConfigField> {
367 match self {
368 Self::Configuration(error) => error.field(),
369 _ => None,
370 }
371 }
372}
373
374impl core::fmt::Display for StartError {
375 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
376 match self {
377 Self::Configuration(error) => write!(formatter, "{error}"),
378 Self::State { detail } => {
379 write!(
380 formatter,
381 "the state directory could not be prepared: {detail}"
382 )
383 }
384 Self::Credential { path, detail } => write!(
385 formatter,
386 "the credential file {} cannot be used: {detail}",
387 path.display()
388 ),
389 Self::Listen { address, detail } => {
390 write!(formatter, "{address} could not be listened on: {detail}")
391 }
392 Self::Store { detail } => write!(formatter, "the store could not be opened: {detail}"),
393 Self::Supervisor { detail } => write!(
394 formatter,
395 "the supervising agent's harness could not be reached: {detail}"
396 ),
397 Self::Reconciliation { detail } => write!(
398 formatter,
399 "what the store held could not be reconciled: {detail}"
400 ),
401 }
402 }
403}
404
405impl core::error::Error for StartError {}
406
407impl From<ConfigError> for StartError {
408 fn from(error: ConfigError) -> Self {
409 Self::Configuration(error)
410 }
411}
412
413#[derive(Debug)]
415pub struct Server;
416
417impl Server {
418 pub async fn start(config_path: impl AsRef<Path>) -> Result<Running, StartError> {
427 let config = ServerConfig::load(config_path)?;
428 let stores = Stores::of(Arc::new(SqliteStore::open(&config.state_dir).map_err(
429 |error| StartError::Store {
430 detail: error.to_string(),
431 },
432 )?));
433 let printer = Arc::new(OctoPrintPrinter::new(config.octoprint.clone()));
434 probe(printer.as_ref()).await?;
435 let vision = Arc::new(
436 ObicoVision::new(ObicoVisionConfig::default())
437 .map_err(|error| StartError::State {
438 detail: error.to_string(),
439 })?
440 .with_api(config.obico_api.clone()),
441 );
442 let agent = Arc::new(agent_for(&config)?);
443 Self::start_with(
444 config,
445 Ports {
446 printer,
447 stores,
448 vision,
449 agent,
450 },
451 )
452 .await
453 }
454
455 pub async fn start_with(config: ServerConfig, ports: Ports) -> Result<Running, StartError> {
462 let (operator, warnings) = operator_credential(&config)?;
467 let listener =
471 TcpListener::bind(config.listen)
472 .await
473 .map_err(|error| StartError::Listen {
474 address: config.listen,
475 detail: error.to_string(),
476 })?;
477 let address = listener.local_addr().map_err(|error| StartError::Listen {
478 address: config.listen,
479 detail: error.to_string(),
480 })?;
481 let clock = Arc::new(SystemClock);
482 let due = overdue(&ports.stores.actions, clock.now())
483 .await
484 .map_err(|error| StartError::Reconciliation {
485 detail: error.to_string(),
486 })?;
487 let mut core_config = CoreConfig::new(config.safety.clone(), context_command());
488 core_config
489 .camera_snapshot_url
490 .clone_from(&config.camera_snapshot_url);
491 core_config.observation_interval = config.observation_interval;
492 core_config.spools = config.spools;
493 let supervisor = Supervisor::new(
494 core_config,
495 Arc::clone(&ports.printer),
496 ports.stores.clone(),
497 Arc::clone(&ports.vision) as Arc<dyn printobserver_vision_api::VisionPort>,
498 Arc::clone(&ports.agent),
499 clock,
500 );
501 let turns = TurnCredentials::new(Some(address));
504 supervisor.install_turn_authority(Arc::new(turns.clone()));
505 let reconciliation = reconcile(
506 &supervisor,
507 &ReconcileStores {
508 prints: Arc::clone(&ports.stores.prints),
509 sessions: Arc::clone(&ports.stores.sessions),
510 events: Arc::clone(&ports.stores.events),
511 },
512 due,
513 )
514 .await
515 .map_err(|error| StartError::Reconciliation {
516 detail: error.to_string(),
517 })?;
518
519 let ingress = IngressState::start(
520 Arc::clone(&supervisor),
521 Arc::clone(&ports.stores.events),
522 Arc::clone(&ports.vision),
523 config.ingress_shared_secret.clone(),
524 config.ingress_answer_bound,
525 );
526 let completions = ingress.completions();
527 let observing = crate::observation::start(&supervisor);
528 let (stored, signal) = Stored::channel();
532 ports.stores.events.on_stored(signal);
533 let application = router(ApiState {
534 supervisor: Arc::clone(&supervisor),
535 prints: Arc::clone(&ports.stores.prints),
536 events: Arc::clone(&ports.stores.events),
537 images: Arc::clone(&ports.stores.images),
538 sessions: Arc::clone(&ports.stores.sessions),
539 operator: Arc::new(operator),
540 turns,
541 stored,
542 })
543 .merge(
544 Router::new()
545 .route(INGRESS_PATH, post(receive))
546 .with_state(ingress),
547 );
548
549 let (stop, stopped) = oneshot::channel::<()>();
550 let serving = tokio::spawn(async move {
551 let _ = axum::serve(listener, application)
552 .with_graceful_shutdown(async move {
553 let _ = stopped.await;
554 })
555 .await;
556 });
557 Ok(Running {
558 address,
559 config,
560 warnings,
561 supervisor,
562 stores: ports.stores,
563 reconciliation,
564 completions,
565 stop: Some(stop),
566 serving,
567 observing,
568 })
569 }
570}
571
572async fn probe(printer: &dyn PrinterPort) -> Result<(), StartError> {
580 match printer.snapshot().await {
581 Err(PrinterError::Unreachable { detail }) => {
582 Err(StartError::Configuration(ConfigError::about(
583 ConfigField::OctoprintUrl,
584 format!("nothing answers there: {detail}"),
585 )))
586 }
587 Err(PrinterError::Unauthorized { detail }) => {
588 Err(StartError::Configuration(ConfigError::about(
589 ConfigField::OctoprintApiKey,
590 format!("the OctoPrint instance refused it: {detail}"),
591 )))
592 }
593 _ => Ok(()),
594 }
595}
596
597fn materialize(
605 directory: &Path,
606 name: &str,
607 contents: &str,
608) -> Result<std::path::PathBuf, StartError> {
609 let path = directory.join(name);
610 std::fs::write(&path, contents).map_err(|error| StartError::State {
611 detail: format!("{} could not be written: {error}", path.display()),
612 })?;
613 Ok(path)
614}
615
616fn beside_the_skill(skill_path: &Path) -> std::path::PathBuf {
623 match skill_path.parent() {
624 Some(directory) if !directory.as_os_str().is_empty() => directory.to_path_buf(),
625 _ => std::path::PathBuf::from("."),
626 }
627}
628
629fn agent_for(config: &ServerConfig) -> Result<OneharnessSupervisor, StartError> {
632 OneharnessSupervisor::open(agent_config(config)?).map_err(|error| StartError::Supervisor {
633 detail: error.to_string(),
634 })
635}
636
637pub fn agent_config(config: &ServerConfig) -> Result<SupervisorConfig, StartError> {
653 let assets = config.assets_dir();
654 std::fs::create_dir_all(&assets).map_err(|error| StartError::State {
655 detail: format!("{} could not be created: {error}", assets.display()),
656 })?;
657 let prompt_template_path = match &config.prompt_template_path {
658 Some(path) => path.clone(),
659 None => materialize(&assets, PROMPT_FILE, TURN_PROMPT)?,
660 };
661 let schema_path =
662 materialize(
663 &assets,
664 SCHEMA_FILE,
665 &printobserver_types::serde_json::to_string_pretty(&without_dialect(
666 printobserver_types::contract::schema_of::<
667 printobserver_supervisor_api::AgentAssessment,
668 >(),
669 ))
670 .map_err(|error| StartError::State {
671 detail: error.to_string(),
672 })?,
673 )?;
674 let assessment_schema =
675 AssessmentSchema::at(&schema_path).map_err(|error| StartError::Supervisor {
676 detail: error.to_string(),
677 })?;
678 let mut harness_env = match HarnessSignIn::of(&config.harness) {
683 Some(sign_in) => {
684 let directory =
685 sign_in
686 .prepare(&config.state_dir)
687 .map_err(|error| StartError::State {
688 detail: format!(
689 "{} could not be created: {error}",
690 sign_in.directory(&config.state_dir).display()
691 ),
692 })?;
693 vec![
694 sign_in
695 .assignment(&directory)
696 .map_err(|error| StartError::Supervisor {
697 detail: error.to_string(),
698 })?,
699 ]
700 }
701 None => Vec::new(),
702 };
703 let search_path = std::env::var_os("PATH").unwrap_or_default();
704 harness_env.extend(path_led_by_this_program(&search_path)?);
705 Ok(SupervisorConfig {
706 state_dir: config.state_dir.clone(),
707 skill_path: config.skill_path.clone(),
708 prompt_template_path,
709 assessment_schema,
710 harness: config.harness.clone(),
711 model: config.model.clone(),
712 working_dir: beside_the_skill(&config.skill_path),
716 turn_timeout: printobserver_oneharness::TurnTimeout::DEFAULT,
717 harness_bin: HarnessSignIn::of(&config.harness)
721 .and_then(|harness| harness.program_behind_launcher(&search_path)),
722 harness_env,
723 agent_commands: agent_commands()?,
724 })
725}
726
727const DIALECT_KEY: &str = "$schema";
729
730fn without_dialect(
740 mut schema: printobserver_types::serde_json::Value,
741) -> printobserver_types::serde_json::Value {
742 if let Some(object) = schema.as_object_mut() {
743 object.remove(DIALECT_KEY);
744 }
745 schema
746}
747
748fn agent_commands() -> Result<Vec<AgentCommand>, StartError> {
757 OPERATIONS
758 .iter()
759 .map(|operation| {
760 AgentCommand::new(&format!(
761 "{CONTEXT_PROGRAM} {}",
762 command_for(operation.name)
763 ))
764 })
765 .collect::<Result<_, _>>()
766 .map_err(|error| StartError::Supervisor {
767 detail: error.to_string(),
768 })
769}
770
771fn path_led_by_this_program(inherited: &OsStr) -> Result<Option<EnvAssignment>, StartError> {
784 let Some(directory) = std::env::current_exe()
785 .ok()
786 .and_then(|program| program.parent().map(Path::to_path_buf))
787 else {
788 return Ok(None);
789 };
790 let refused = |detail: String| StartError::Supervisor {
791 detail: format!(
792 "a turn's PATH cannot lead with {}: {detail}",
793 directory.display()
794 ),
795 };
796 let joined = std::env::join_paths(
797 std::iter::once(directory.clone()).chain(std::env::split_paths(inherited)),
798 )
799 .map_err(|error| refused(error.to_string()))?;
800 let joined = joined
801 .to_str()
802 .ok_or_else(|| refused("it is not valid Unicode".to_owned()))?;
803 EnvAssignment::new(&format!("PATH={joined}"))
804 .map(Some)
805 .map_err(|error| refused(error.to_string()))
806}
807
808pub struct Running {
813 address: SocketAddr,
815 config: ServerConfig,
817 warnings: Vec<String>,
820 supervisor: Arc<Supervisor>,
822 stores: Stores,
824 reconciliation: Reconciliation,
826 completions: watch::Receiver<u64>,
828 stop: Option<oneshot::Sender<()>>,
830 serving: JoinHandle<()>,
832 observing: JoinHandle<()>,
834}
835
836impl core::fmt::Debug for Running {
837 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
838 formatter
839 .debug_struct("Running")
840 .field("address", &self.address)
841 .field("reconciliation", &self.reconciliation)
842 .finish_non_exhaustive()
843 }
844}
845
846impl Running {
847 #[must_use]
849 pub const fn address(&self) -> SocketAddr {
850 self.address
851 }
852
853 #[must_use]
855 pub fn base_url(&self) -> String {
856 format!(
857 "http://{}{}",
858 self.address,
859 crate::operations::VERSION_PREFIX
860 )
861 }
862
863 #[must_use]
865 pub fn ingress_url(&self) -> String {
866 format!("http://{}{INGRESS_PATH}", self.address)
867 }
868
869 #[must_use]
871 pub const fn config(&self) -> &ServerConfig {
872 &self.config
873 }
874
875 #[must_use]
879 pub fn warnings(&self) -> &[String] {
880 &self.warnings
881 }
882
883 #[must_use]
885 pub const fn reconciliation(&self) -> &Reconciliation {
886 &self.reconciliation
887 }
888
889 #[must_use]
891 pub const fn supervisor(&self) -> &Arc<Supervisor> {
892 &self.supervisor
893 }
894
895 #[must_use]
897 pub const fn stores(&self) -> &Stores {
898 &self.stores
899 }
900
901 #[must_use]
904 pub fn completions(&self) -> watch::Receiver<u64> {
905 self.completions.clone()
906 }
907
908 pub async fn stop(mut self) {
910 if let Some(stop) = self.stop.take() {
911 let _ = stop.send(());
912 }
913 self.observing.abort();
914 let _ = (&mut self.serving).await;
915 }
916
917 pub async fn serve_until_signalled(self) -> Result<(), StartError> {
928 stop_requested().await?;
929 self.stop().await;
930 Ok(())
931 }
932}
933
934fn unhandled(what: &str, error: &std::io::Error) -> StartError {
936 StartError::State {
937 detail: format!("{what} cannot be handled: {error}"),
938 }
939}
940
941#[cfg(unix)]
946async fn stop_requested() -> Result<(), StartError> {
947 use tokio::signal::unix::{SignalKind, signal};
948
949 let mut terminate = signal(SignalKind::terminate())
950 .map_err(|error| unhandled("the termination signal", &error))?;
951 let mut interrupt = signal(SignalKind::interrupt())
952 .map_err(|error| unhandled("the interrupt signal", &error))?;
953 tokio::select! {
954 _ = terminate.recv() => {}
955 _ = interrupt.recv() => {}
956 }
957 Ok(())
958}
959
960#[cfg(windows)]
968async fn stop_requested() -> Result<(), StartError> {
969 use tokio::signal::windows::{ctrl_break, ctrl_c, ctrl_close, ctrl_shutdown};
970
971 let mut interrupt = ctrl_c().map_err(|error| unhandled("the CTRL_C event", &error))?;
972 let mut breaking = ctrl_break().map_err(|error| unhandled("the CTRL_BREAK event", &error))?;
973 let mut closing = ctrl_close().map_err(|error| unhandled("the CTRL_CLOSE event", &error))?;
974 let mut shutting_down =
975 ctrl_shutdown().map_err(|error| unhandled("the CTRL_SHUTDOWN event", &error))?;
976 tokio::select! {
977 _ = interrupt.recv() => {}
978 _ = breaking.recv() => {}
979 _ = closing.recv() => {}
980 _ = shutting_down.recv() => {}
981 }
982 Ok(())
983}
984
985impl Drop for Running {
986 fn drop(&mut self) {
987 if let Some(stop) = self.stop.take() {
988 let _ = stop.send(());
989 }
990 self.serving.abort();
991 }
992}