Skip to main content

printobserver_server/
server.rs

1//! The composition root: the one place an implementation crate is named.
2//!
3//! Everything below this file is written against the three ports and the
4//! supervision domain's store traits. This is where one implementation is
5//! chosen for each — `OctoPrint` behind the printer port, `Obico` behind the
6//! vision port, `OneHarness` behind the supervisor port, and `SQLite` behind
7//! the store traits — and `just check-repo` refuses any other crate that names
8//! one. The store is one implementation held once per aggregate: [`Stores::of`]
9//! coerces the one `SQLite` store to each of the seven trait objects, and every
10//! consumer below is handed the handle for the aggregate it names and no
11//! other.
12//!
13//! [`Server::start`] is that root. [`Server::start_with`] takes ports a caller
14//! composed, which is how the tiers that stand in for a machine drive the real
15//! surface without one; the two share every line after the ports exist, so what
16//! a tier drives is the server this file starts.
17
18use 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::ingress::{IngressState, receive};
43use crate::operations::{INGRESS_PATH, OPERATIONS, command_for};
44use crate::reconcile::{ReconcileStores, Reconciliation, overdue, reconcile};
45use crate::turns::TurnCredentials;
46
47/// The program a supervision turn runs to read its print's context.
48pub const CONTEXT_PROGRAM: &str = "printobserver";
49
50/// The file, under the state directory, a server before this one wrote the
51/// address it took and the credential in force into. A start deletes it: a
52/// supervision turn runs as the service's user and could read the operator's
53/// credential out of it.
54pub const CLIENT_CONFIG_FILE: &str = "client.toml";
55
56/// The file, under the state directory, a server before this one generated its
57/// API credential into, as plaintext. A start converts it into
58/// [`API_CREDENTIAL_VERIFIER_FILE`] and deletes it, so the credential it held
59/// keeps authenticating while nothing the service's user can read holds it.
60pub const API_CREDENTIAL_FILE: &str = "api-credential";
61
62/// The file, under the state directory, holding the verifier of the operator's
63/// credential — read when `api.credential_verifier` is not configured.
64pub const API_CREDENTIAL_VERIFIER_FILE: &str = "api-credential.verifier";
65
66/// The command that gives an operator a credential, as every refusal and
67/// warning about one names it.
68pub const CREDENTIAL_ISSUE: &str = "printobserver credential issue";
69
70/// The command that prints the verifier of a credential an operator already
71/// holds.
72pub const CREDENTIAL_VERIFIER: &str = "printobserver credential verifier";
73
74/// The mode the verifier file is created with.
75///
76/// Unix alone has one. A file Windows creates carries the access its directory
77/// grants rather than a mode, so there the state directory is what keeps it to
78/// the service's own account.
79#[cfg(unix)]
80const PRIVATE: u32 = 0o600;
81
82/// The command a supervision turn runs to read its print's context.
83///
84/// This program's own context read, against the print the turn is about, and
85/// nothing else: where the server is and the credential the turn answers to
86/// reach the turn through its environment alone — the address the server
87/// bound and a credential minted for that turn — so the command names no
88/// configuration file and the program reads none.
89/// `printobserver-oneharness` substitutes the print for the placeholder.
90#[must_use]
91pub fn context_command() -> String {
92    format!("{CONTEXT_PROGRAM} context --print-id {{print_id}}")
93}
94
95/// Who an operator's credential is checked against, as one start settled it.
96#[derive(Debug, Clone)]
97pub enum OperatorCredential {
98    /// Its verifier, from `api.credential_verifier` or the state directory.
99    Verifier(CredentialVerifier),
100    /// A plaintext `api.credential` the configuration still carries, admitted
101    /// until it is replaced.
102    Plaintext(ApiCredential),
103    /// Nothing at all: a fresh install whose operator has not run
104    /// `printobserver credential issue` yet. No operator request is admitted.
105    Unconfigured,
106}
107
108impl OperatorCredential {
109    /// Whether a presented credential is the operator's.
110    #[must_use]
111    pub fn admits(&self, presented: &[u8]) -> bool {
112        match self {
113            Self::Verifier(verifier) => verifier.admits(presented),
114            Self::Plaintext(credential) => credential.admits(presented),
115            Self::Unconfigured => false,
116        }
117    }
118}
119
120/// The warning every start under a plaintext `api.credential` gives, which
121/// names the key, its replacement and the command that computes one, and never
122/// what the key holds.
123#[must_use]
124pub fn plaintext_credential_warning() -> String {
125    format!(
126        "the server configuration carries `api.credential`, an operator credential in \
127         plaintext. A supervision turn runs as this service's user and can read that file, \
128         so it can read that credential until it is replaced. Replace it with \
129         `api.credential_verifier`: pipe the credential into `{CREDENTIAL_VERIFIER}` to print \
130         that line, put it in the configuration, delete `api.credential`, and restart the \
131         service"
132    )
133}
134
135/// Write one file this start creates, exclusively and private to the service.
136fn write_private(path: &Path, contents: &[u8]) -> std::io::Result<()> {
137    use std::io::Write as _;
138
139    let mut options = std::fs::OpenOptions::new();
140    options.write(true).create_new(true);
141    #[cfg(unix)]
142    std::os::unix::fs::OpenOptionsExt::mode(&mut options, PRIVATE);
143    let mut file = options.open(path)?;
144    // llmlint: ignore[changed_behavior_has_e2e] A write or sync failing into a file this start just created exclusively is a full or failing disk, which no journey can arrange on a runner without root; the conversion it serves, and the next start after it, are driven by `a_legacy_installation_keeps_its_operators_credential_through_every_route`.
145    let written = file.write_all(contents).and_then(|()| file.sync_all());
146    if written.is_err() {
147        // The file is this start's own and holds nothing usable, so it is
148        // taken back rather than left for the next start to refuse.
149        let _ = std::fs::remove_file(path);
150    }
151    written
152}
153
154/// Remove one file a server before this one left, when it is there.
155fn remove_if_there(path: &Path) -> std::io::Result<()> {
156    match std::fs::remove_file(path) {
157        Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error),
158        _ => Ok(()),
159    }
160}
161
162/// Take the plaintext a server before this one left in the state directory out
163/// of it.
164///
165/// `client.toml` is deleted. `api-credential` is converted into the verifier
166/// file — written first, exclusively, so a start that stops between the two
167/// leaves the credential still convertible — and then deleted; one left beside
168/// a verifier file that is already there is deleted outright, because that
169/// verifier is what is in force.
170///
171/// # Errors
172///
173/// Returns [`StartError::Credential`] naming the file, and never what it holds,
174/// when the legacy credential cannot be read, holds nothing a header could
175/// present, or cannot be converted or removed; and [`StartError::State`] when
176/// `client.toml` cannot be removed.
177fn take_plaintext_out(state_dir: &Path) -> Result<(), StartError> {
178    let client_config = state_dir.join(CLIENT_CONFIG_FILE);
179    remove_if_there(&client_config).map_err(|error| StartError::State {
180        detail: format!(
181            "{} could not be removed, and it may carry the operator's credential where a \
182             supervision turn can read it: {error}",
183            client_config.display()
184        ),
185    })?;
186    let legacy = state_dir.join(API_CREDENTIAL_FILE);
187    let refusing = |detail: String| StartError::Credential {
188        path: legacy.clone(),
189        detail,
190    };
191    let held = match std::fs::read(&legacy) {
192        Ok(held) => held,
193        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
194        Err(error) => return Err(refusing(format!("it cannot be read: {error}"))),
195    };
196    let verifier_file = state_dir.join(API_CREDENTIAL_VERIFIER_FILE);
197    if !verifier_file.exists() {
198        let text = core::str::from_utf8(&held).ok().map(without_terminator);
199        let credential = text
200            .ok_or("it is not text")
201            .and_then(ApiCredential::new)
202            .map_err(|why| {
203                refusing(format!(
204                    "{why}. This server converts the credential an earlier version generated \
205                     there into its verifier: correct the file, or remove it and run \
206                     `{CREDENTIAL_ISSUE} --replace`"
207                ))
208            })?;
209        write_private(
210            &verifier_file,
211            format!("{}\n", credential.verifier()).as_bytes(),
212        )
213        .map_err(|error| {
214            refusing(format!(
215                "its verifier could not be written to {}: {error}",
216                verifier_file.display()
217            ))
218        })?;
219    }
220    std::fs::remove_file(&legacy)
221        .map_err(|error| refusing(format!("it could not be removed: {error}")))
222}
223
224/// The operator credential this start serves under, and the warnings it owes.
225///
226/// The legacy plaintext is taken out of the state directory first. Then
227/// `api.credential_verifier` when it is configured, a plaintext
228/// `api.credential` when that is all the configuration carries, the verifier
229/// file in the state directory, and otherwise nothing — a fresh install, which
230/// supervises and admits no operator until one is issued. A plaintext
231/// `api.credential` warns whether or not a verifier wins over it.
232///
233/// # Errors
234///
235/// Returns [`StartError::Credential`] naming the file, and never what it
236/// holds, when the legacy plaintext cannot be taken out or the verifier file
237/// cannot be read as one.
238pub fn operator_credential(
239    config: &ServerConfig,
240) -> Result<(OperatorCredential, Vec<String>), StartError> {
241    take_plaintext_out(&config.state_dir)?;
242    let mut warnings = Vec::new();
243    if config.api_credential.is_some() {
244        warnings.push(plaintext_credential_warning());
245    }
246    if let Some(verifier) = &config.api_credential_verifier {
247        return Ok((OperatorCredential::Verifier(verifier.clone()), warnings));
248    }
249    if let Some(plaintext) = &config.api_credential {
250        return Ok((OperatorCredential::Plaintext(plaintext.clone()), warnings));
251    }
252    let path = config.state_dir.join(API_CREDENTIAL_VERIFIER_FILE);
253    let held = match std::fs::read_to_string(&path) {
254        Ok(held) => held,
255        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
256            return Ok((OperatorCredential::Unconfigured, warnings));
257        }
258        Err(error) => {
259            return Err(StartError::Credential {
260                path,
261                detail: format!("it cannot be read: {error}"),
262            });
263        }
264    };
265    let verifier =
266        CredentialVerifier::parse(held.trim()).map_err(|why| StartError::Credential {
267            path: path.clone(),
268            detail: format!(
269                "{why}. Correct the file, or remove it and set `api.credential_verifier`"
270            ),
271        })?;
272    Ok((OperatorCredential::Verifier(verifier), warnings))
273}
274
275/// A credential file's text with the one line terminator a person's editor or
276/// shell ends it with set aside.
277///
278/// Exactly one, `\n` or `\r\n`: that terminator is not part of the credential,
279/// and anything else in the text — a second one included — is left for the
280/// character rule to refuse.
281fn without_terminator(text: &str) -> &str {
282    text.strip_suffix("\r\n")
283        .or_else(|| text.strip_suffix('\n'))
284        .unwrap_or(text)
285}
286
287/// The file name the agent's prompt template is materialized under.
288pub const PROMPT_FILE: &str = "turn-prompt.md";
289
290/// The file name the assessment schema is materialized under.
291pub const SCHEMA_FILE: &str = "assessment-schema.json";
292
293/// The prompt template this program carries and materializes.
294///
295/// The adapter's own committed asset rather than a copy of it, so what an
296/// installed program fills a turn with and what `just check-repo` reads are one
297/// file.
298pub const TURN_PROMPT: &str = printobserver_oneharness::DEFAULT_TURN_PROMPT;
299
300/// The four implementations one running server was composed from.
301///
302/// A tier that stands in for a machine hands these in; [`Server::start`] builds
303/// them from the configuration.
304pub struct Ports {
305    /// The printer.
306    pub printer: Arc<dyn PrinterPort>,
307    /// Durable state, one handle per aggregate onto one store.
308    pub stores: Stores,
309    /// External observations, and the snapshot fetch.
310    pub vision: Arc<ObicoVision>,
311    /// The supervising agent's harness.
312    pub agent: Arc<dyn SupervisorPort>,
313}
314
315impl core::fmt::Debug for Ports {
316    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
317        formatter.debug_struct("Ports").finish_non_exhaustive()
318    }
319}
320
321/// Why this server did not start.
322#[derive(Debug)]
323pub enum StartError {
324    /// The configuration will not do, naming the field that will not.
325    Configuration(ConfigError),
326    /// The state directory could not be prepared.
327    State {
328        /// What went wrong.
329        detail: String,
330    },
331    /// A credential file in the state directory cannot be used.
332    Credential {
333        /// The file.
334        path: PathBuf,
335        /// Why it cannot be used, in words that never quote what it holds.
336        detail: String,
337    },
338    /// The address could not be listened on.
339    Listen {
340        /// The address that was asked for.
341        address: SocketAddr,
342        /// What went wrong.
343        detail: String,
344    },
345    /// The store could not be opened.
346    Store {
347        /// What the store said.
348        detail: String,
349    },
350    /// The supervising agent's harness could not be reached at all.
351    Supervisor {
352        /// What the harness said.
353        detail: String,
354    },
355    /// Reconciling what the store held failed.
356    Reconciliation {
357        /// What went wrong.
358        detail: String,
359    },
360}
361
362impl StartError {
363    /// The configuration field this refusal is about, when it is about one.
364    #[must_use]
365    pub const fn field(&self) -> Option<ConfigField> {
366        match self {
367            Self::Configuration(error) => error.field(),
368            _ => None,
369        }
370    }
371}
372
373impl core::fmt::Display for StartError {
374    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
375        match self {
376            Self::Configuration(error) => write!(formatter, "{error}"),
377            Self::State { detail } => {
378                write!(
379                    formatter,
380                    "the state directory could not be prepared: {detail}"
381                )
382            }
383            Self::Credential { path, detail } => write!(
384                formatter,
385                "the credential file {} cannot be used: {detail}",
386                path.display()
387            ),
388            Self::Listen { address, detail } => {
389                write!(formatter, "{address} could not be listened on: {detail}")
390            }
391            Self::Store { detail } => write!(formatter, "the store could not be opened: {detail}"),
392            Self::Supervisor { detail } => write!(
393                formatter,
394                "the supervising agent's harness could not be reached: {detail}"
395            ),
396            Self::Reconciliation { detail } => write!(
397                formatter,
398                "what the store held could not be reconciled: {detail}"
399            ),
400        }
401    }
402}
403
404impl core::error::Error for StartError {}
405
406impl From<ConfigError> for StartError {
407    fn from(error: ConfigError) -> Self {
408        Self::Configuration(error)
409    }
410}
411
412/// The composition root.
413#[derive(Debug)]
414pub struct Server;
415
416impl Server {
417    /// Read one configuration file, compose the four implementations, and serve.
418    ///
419    /// # Errors
420    ///
421    /// Returns [`StartError::Configuration`] naming the field that will not do
422    /// — including the two only the machine can rule on, an `OctoPrint` address
423    /// nothing answers at and a key that instance refuses — and the other
424    /// variants for a host that will not let this server come up.
425    pub async fn start(config_path: impl AsRef<Path>) -> Result<Running, StartError> {
426        let config = ServerConfig::load(config_path)?;
427        let stores = Stores::of(Arc::new(SqliteStore::open(&config.state_dir).map_err(
428            |error| StartError::Store {
429                detail: error.to_string(),
430            },
431        )?));
432        let printer = Arc::new(OctoPrintPrinter::new(config.octoprint.clone()));
433        probe(printer.as_ref()).await?;
434        let vision = Arc::new(
435            ObicoVision::new(ObicoVisionConfig::default())
436                .map_err(|error| StartError::State {
437                    detail: error.to_string(),
438                })?
439                .with_api(config.obico_api.clone()),
440        );
441        let agent = Arc::new(agent_for(&config)?);
442        Self::start_with(
443            config,
444            Ports {
445                printer,
446                stores,
447                vision,
448                agent,
449            },
450        )
451        .await
452    }
453
454    /// Serve over ports a caller composed.
455    ///
456    /// # Errors
457    ///
458    /// The same as [`Server::start`], less the refusals that belong to building
459    /// the implementations.
460    pub async fn start_with(config: ServerConfig, ports: Ports) -> Result<Running, StartError> {
461        // The operator's credential is settled before anything listens, so
462        // there is no moment at which this server answers a request it has
463        // nothing to check against — and the plaintext an earlier version left
464        // is out of the state directory before the first turn could read it.
465        let (operator, warnings) = operator_credential(&config)?;
466        // The listener is taken next, because the command a supervision turn
467        // runs to read its context names the address this server is answering
468        // on — and a configuration may ask for any free port.
469        let listener =
470            TcpListener::bind(config.listen)
471                .await
472                .map_err(|error| StartError::Listen {
473                    address: config.listen,
474                    detail: error.to_string(),
475                })?;
476        let address = listener.local_addr().map_err(|error| StartError::Listen {
477            address: config.listen,
478            detail: error.to_string(),
479        })?;
480        let clock = Arc::new(SystemClock);
481        let due = overdue(&ports.stores.actions, clock.now())
482            .await
483            .map_err(|error| StartError::Reconciliation {
484                detail: error.to_string(),
485            })?;
486        let mut core_config = CoreConfig::new(config.safety.clone(), context_command());
487        core_config
488            .camera_snapshot_url
489            .clone_from(&config.camera_snapshot_url);
490        core_config.observation_interval = config.observation_interval;
491        core_config.spools = config.spools;
492        let supervisor = Supervisor::new(
493            core_config,
494            Arc::clone(&ports.printer),
495            ports.stores.clone(),
496            Arc::clone(&ports.vision) as Arc<dyn printobserver_vision_api::VisionPort>,
497            Arc::clone(&ports.agent),
498            clock,
499        );
500        // Every turn's runs are told the address this server bound, beside the
501        // credential minted for them.
502        let turns = TurnCredentials::new(Some(address));
503        supervisor.install_turn_authority(Arc::new(turns.clone()));
504        let reconciliation = reconcile(
505            &supervisor,
506            &ReconcileStores {
507                prints: Arc::clone(&ports.stores.prints),
508                sessions: Arc::clone(&ports.stores.sessions),
509                events: Arc::clone(&ports.stores.events),
510            },
511            due,
512        )
513        .await
514        .map_err(|error| StartError::Reconciliation {
515            detail: error.to_string(),
516        })?;
517
518        let ingress = IngressState::start(
519            Arc::clone(&supervisor),
520            Arc::clone(&ports.stores.events),
521            Arc::clone(&ports.vision),
522            config.ingress_shared_secret.clone(),
523            config.ingress_answer_bound,
524        );
525        let completions = ingress.completions();
526        let observing = crate::observation::start(&supervisor);
527        let application = router(ApiState {
528            supervisor: Arc::clone(&supervisor),
529            prints: Arc::clone(&ports.stores.prints),
530            events: Arc::clone(&ports.stores.events),
531            images: Arc::clone(&ports.stores.images),
532            sessions: Arc::clone(&ports.stores.sessions),
533            operator: Arc::new(operator),
534            turns,
535        })
536        .merge(
537            Router::new()
538                .route(INGRESS_PATH, post(receive))
539                .with_state(ingress),
540        );
541
542        let (stop, stopped) = oneshot::channel::<()>();
543        let serving = tokio::spawn(async move {
544            let _ = axum::serve(listener, application)
545                .with_graceful_shutdown(async move {
546                    let _ = stopped.await;
547                })
548                .await;
549        });
550        Ok(Running {
551            address,
552            config,
553            warnings,
554            supervisor,
555            stores: ports.stores,
556            reconciliation,
557            completions,
558            stop: Some(stop),
559            serving,
560            observing,
561        })
562    }
563}
564
565/// Ask the machine whether the address and the key are the ones it answers to.
566///
567/// Only the two answers that are *about the configuration* refuse a start. A
568/// printer that is off, in an error state, or answering something this adapter
569/// cannot read is a machine having a bad day rather than a file with the wrong
570/// value in it, and a supervisor that would not come up for one of those could
571/// not be used to find out why.
572async fn probe(printer: &dyn PrinterPort) -> Result<(), StartError> {
573    match printer.snapshot().await {
574        Err(PrinterError::Unreachable { detail }) => {
575            Err(StartError::Configuration(ConfigError::about(
576                ConfigField::OctoprintUrl,
577                format!("nothing answers there: {detail}"),
578            )))
579        }
580        Err(PrinterError::Unauthorized { detail }) => {
581            Err(StartError::Configuration(ConfigError::about(
582                ConfigField::OctoprintApiKey,
583                format!("the OctoPrint instance refused it: {detail}"),
584            )))
585        }
586        _ => Ok(()),
587    }
588}
589
590/// Write one of the agent's committed assets into the state directory.
591///
592/// The port reads its template and its schema from paths, so that editing one
593/// on a running host is a restart rather than a rebuild. An installed program
594/// has no checkout to read them out of, so the bytes it carries are written
595/// here — and an operator who configured a template of their own is pointed at
596/// theirs instead.
597fn materialize(
598    directory: &Path,
599    name: &str,
600    contents: &str,
601) -> Result<std::path::PathBuf, StartError> {
602    let path = directory.join(name);
603    std::fs::write(&path, contents).map_err(|error| StartError::State {
604        detail: format!("{} could not be written: {error}", path.display()),
605    })?;
606    Ok(path)
607}
608
609/// The directory the harness runs in: the one holding the configured skill.
610///
611/// An installed skill is a directory — its `SKILL.md` and the `reference/`
612/// documents that file links to by relative paths — so the agent stands where
613/// those links resolve. A skill named by a bare file name sits in this
614/// process's own working directory.
615fn beside_the_skill(skill_path: &Path) -> std::path::PathBuf {
616    match skill_path.parent() {
617        Some(directory) if !directory.as_os_str().is_empty() => directory.to_path_buf(),
618        _ => std::path::PathBuf::from("."),
619    }
620}
621
622/// The supervising agent's harness, over the configured skill and the assets
623/// this program carries.
624fn agent_for(config: &ServerConfig) -> Result<OneharnessSupervisor, StartError> {
625    OneharnessSupervisor::open(agent_config(config)?).map_err(|error| StartError::Supervisor {
626        detail: error.to_string(),
627    })
628}
629
630/// The supervising agent's configuration, as [`Server::start`] composes it.
631///
632/// The template and the assessment schema are written into the assets
633/// directory; the skill is the installed one `supervisor.skill_path` names, and
634/// every turn runs in the directory holding it — where an installed skill's
635/// `reference/` documents sit, so the links the skill carries resolve from
636/// where the agent stands. The harness is the one `supervisor.harness` names,
637/// found by name, and a harness this program can sign in is pointed at the
638/// sign-in kept under the state directory.
639///
640/// # Errors
641///
642/// Returns [`StartError::State`] when the assets or the sign-in directory
643/// cannot be written, and [`StartError::Supervisor`] when the schema it wrote
644/// constrains nothing.
645pub fn agent_config(config: &ServerConfig) -> Result<SupervisorConfig, StartError> {
646    let assets = config.assets_dir();
647    std::fs::create_dir_all(&assets).map_err(|error| StartError::State {
648        detail: format!("{} could not be created: {error}", assets.display()),
649    })?;
650    let prompt_template_path = match &config.prompt_template_path {
651        Some(path) => path.clone(),
652        None => materialize(&assets, PROMPT_FILE, TURN_PROMPT)?,
653    };
654    let schema_path =
655        materialize(
656            &assets,
657            SCHEMA_FILE,
658            &printobserver_types::serde_json::to_string_pretty(&without_dialect(
659                printobserver_types::contract::schema_of::<
660                    printobserver_supervisor_api::AgentAssessment,
661                >(),
662            ))
663            .map_err(|error| StartError::State {
664                detail: error.to_string(),
665            })?,
666        )?;
667    let assessment_schema =
668        AssessmentSchema::at(&schema_path).map_err(|error| StartError::Supervisor {
669            detail: error.to_string(),
670        })?;
671    // A harness this program can sign in keeps that sign-in under the state
672    // directory — the one place the service's unit lets it write — and every
673    // turn is pointed at the directory `printobserver sign-in` wrote it to. A
674    // harness outside the table is handed nothing extra.
675    let mut harness_env = match HarnessSignIn::of(&config.harness) {
676        Some(sign_in) => {
677            let directory =
678                sign_in
679                    .prepare(&config.state_dir)
680                    .map_err(|error| StartError::State {
681                        detail: format!(
682                            "{} could not be created: {error}",
683                            sign_in.directory(&config.state_dir).display()
684                        ),
685                    })?;
686            vec![
687                sign_in
688                    .assignment(&directory)
689                    .map_err(|error| StartError::Supervisor {
690                        detail: error.to_string(),
691                    })?,
692            ]
693        }
694        None => Vec::new(),
695    };
696    let search_path = std::env::var_os("PATH").unwrap_or_default();
697    harness_env.extend(path_led_by_this_program(&search_path)?);
698    Ok(SupervisorConfig {
699        state_dir: config.state_dir.clone(),
700        skill_path: config.skill_path.clone(),
701        prompt_template_path,
702        assessment_schema,
703        harness: config.harness.clone(),
704        model: config.model.clone(),
705        // The skill's own directory rather than the state or assets directory,
706        // so that the skill's relative links to the reference documents beside
707        // it resolve from where the agent is standing as well as from the skill.
708        working_dir: beside_the_skill(&config.skill_path),
709        turn_timeout: printobserver_oneharness::TurnTimeout::DEFAULT,
710        // Found by name, unless npm's launcher is all a search finds: then the
711        // native program behind it, which `OneHarness` can start where the
712        // launcher cannot be.
713        harness_bin: HarnessSignIn::of(&config.harness)
714            .and_then(|harness| harness.program_behind_launcher(&search_path)),
715        harness_env,
716        agent_commands: agent_commands()?,
717    })
718}
719
720/// The key a JSON Schema declares its dialect under.
721const DIALECT_KEY: &str = "$schema";
722
723/// A schema with its dialect declaration taken off, and nothing else changed.
724///
725/// The generated assessment schema declares draft 2020-12, and Claude Code
726/// refuses a `--json-schema` naming a dialect its validator was not given ("no
727/// schema with key or ref `https://json-schema.org/draft/2020-12/schema`"), so
728/// every turn ended before the agent was asked anything. Left undeclared, the
729/// harness reads the schema in its own dialect and `OneHarness` in its default,
730/// and the keywords this schema uses mean the same in both. The checked-in
731/// schema keeps its declaration: only the copy a turn is handed drops it.
732fn without_dialect(
733    mut schema: printobserver_types::serde_json::Value,
734) -> printobserver_types::serde_json::Value {
735    if let Some(object) = schema.as_object_mut() {
736        object.remove(DIALECT_KEY);
737    }
738    schema
739}
740
741/// The commands the supervising agent may run: this program's own, one per
742/// operation the server serves, and no other.
743///
744/// Every one of them is a request to this server, so what the agent can change
745/// is still exactly what the policy grants its actor. Derived from
746/// [`OPERATIONS`] through the command-line program's own spelling, so an
747/// operation the server gains is a command the agent may run from the same
748/// change.
749fn agent_commands() -> Result<Vec<AgentCommand>, StartError> {
750    OPERATIONS
751        .iter()
752        .map(|operation| {
753            AgentCommand::new(&format!(
754                "{CONTEXT_PROGRAM} {}",
755                command_for(operation.name)
756            ))
757        })
758        .collect::<Result<_, _>>()
759        .map_err(|error| StartError::Supervisor {
760            detail: error.to_string(),
761        })
762}
763
764/// A turn's `PATH`: the directory this program is running from, then the
765/// search path this process was given.
766///
767/// The context command, and every command the agent may run, names this
768/// program by name rather than by path, and nothing makes that name resolve in
769/// a service's environment: neither installer puts the program's directory on
770/// a `PATH`, and Windows' service control manager hands a service the
771/// environment it had at boot. Leading the turn's `PATH` with this program's
772/// own directory makes the name the program that is serving.
773///
774/// Nothing is added when the running program's path cannot be read, which
775/// leaves the turn the `PATH` it inherits.
776fn path_led_by_this_program(inherited: &OsStr) -> Result<Option<EnvAssignment>, StartError> {
777    let Some(directory) = std::env::current_exe()
778        .ok()
779        .and_then(|program| program.parent().map(Path::to_path_buf))
780    else {
781        return Ok(None);
782    };
783    let refused = |detail: String| StartError::Supervisor {
784        detail: format!(
785            "a turn's PATH cannot lead with {}: {detail}",
786            directory.display()
787        ),
788    };
789    let joined = std::env::join_paths(
790        std::iter::once(directory.clone()).chain(std::env::split_paths(inherited)),
791    )
792    .map_err(|error| refused(error.to_string()))?;
793    let joined = joined
794        .to_str()
795        .ok_or_else(|| refused("it is not valid Unicode".to_owned()))?;
796    EnvAssignment::new(&format!("PATH={joined}"))
797        .map(Some)
798        .map_err(|error| refused(error.to_string()))
799}
800
801/// One server, serving.
802///
803/// Dropping this stops it, and so does [`Running::stop`]; nothing here outlives
804/// the handle a caller holds.
805pub struct Running {
806    /// Where it is answering.
807    address: SocketAddr,
808    /// What it was configured with.
809    config: ServerConfig,
810    /// What this start found that its operator should change, in words that
811    /// quote no credential.
812    warnings: Vec<String>,
813    /// The supervision core.
814    supervisor: Arc<Supervisor>,
815    /// Durable state, one handle per aggregate.
816    stores: Stores,
817    /// What this start adopted.
818    reconciliation: Reconciliation,
819    /// How many posts the ingress worker has finished handling.
820    completions: watch::Receiver<u64>,
821    /// The graceful-shutdown signal, taken when it is sent.
822    stop: Option<oneshot::Sender<()>>,
823    /// The task serving requests.
824    serving: JoinHandle<()>,
825    /// The task giving every active print its periodic observation.
826    observing: JoinHandle<()>,
827}
828
829impl core::fmt::Debug for Running {
830    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
831        formatter
832            .debug_struct("Running")
833            .field("address", &self.address)
834            .field("reconciliation", &self.reconciliation)
835            .finish_non_exhaustive()
836    }
837}
838
839impl Running {
840    /// Where this server is answering.
841    #[must_use]
842    pub const fn address(&self) -> SocketAddr {
843        self.address
844    }
845
846    /// The base URL of its versioned surface.
847    #[must_use]
848    pub fn base_url(&self) -> String {
849        format!(
850            "http://{}{}",
851            self.address,
852            crate::operations::VERSION_PREFIX
853        )
854    }
855
856    /// The URL its ingress endpoint answers on.
857    #[must_use]
858    pub fn ingress_url(&self) -> String {
859        format!("http://{}{INGRESS_PATH}", self.address)
860    }
861
862    /// What it was configured with.
863    #[must_use]
864    pub const fn config(&self) -> &ServerConfig {
865        &self.config
866    }
867
868    /// What this start found that its operator should change — a plaintext
869    /// `api.credential` among them — in words that quote no credential. The
870    /// program running the server writes each to its log on every start.
871    #[must_use]
872    pub fn warnings(&self) -> &[String] {
873        &self.warnings
874    }
875
876    /// What this start adopted from the store.
877    #[must_use]
878    pub const fn reconciliation(&self) -> &Reconciliation {
879        &self.reconciliation
880    }
881
882    /// The supervision core it is serving over.
883    #[must_use]
884    pub const fn supervisor(&self) -> &Arc<Supervisor> {
885        &self.supervisor
886    }
887
888    /// Durable state, as it is serving over it.
889    #[must_use]
890    pub const fn stores(&self) -> &Stores {
891        &self.stores
892    }
893
894    /// How many posts the ingress worker has finished handling, watchable while
895    /// it works.
896    #[must_use]
897    pub fn completions(&self) -> watch::Receiver<u64> {
898        self.completions.clone()
899    }
900
901    /// Stop serving, and wait for the last request to finish.
902    pub async fn stop(mut self) {
903        if let Some(stop) = self.stop.take() {
904            let _ = stop.send(());
905        }
906        self.observing.abort();
907        let _ = (&mut self.serving).await;
908    }
909
910    /// Serve until the operating system asks this process to stop.
911    ///
912    /// This is what the `server` subcommand runs. It answers however this
913    /// platform asks a process to stop — see [`stop_requested`] — and every one
914    /// of those ways enters the same shutdown: [`Running::stop`].
915    ///
916    /// # Errors
917    ///
918    /// Returns [`StartError::State`] when the stop handlers cannot be
919    /// installed, which is a process that could not be stopped cleanly.
920    pub async fn serve_until_signalled(self) -> Result<(), StartError> {
921        stop_requested().await?;
922        self.stop().await;
923        Ok(())
924    }
925}
926
927/// A stop handler that could not be installed, naming which.
928fn unhandled(what: &str, error: &std::io::Error) -> StartError {
929    StartError::State {
930        detail: format!("{what} cannot be handled: {error}"),
931    }
932}
933
934/// Wait until the operating system asks this process to stop.
935///
936/// On Unix that is the signal a service manager stops a unit with, or the
937/// interrupt from the terminal that started it.
938#[cfg(unix)]
939async fn stop_requested() -> Result<(), StartError> {
940    use tokio::signal::unix::{SignalKind, signal};
941
942    let mut terminate = signal(SignalKind::terminate())
943        .map_err(|error| unhandled("the termination signal", &error))?;
944    let mut interrupt = signal(SignalKind::interrupt())
945        .map_err(|error| unhandled("the interrupt signal", &error))?;
946    tokio::select! {
947        _ = terminate.recv() => {}
948        _ = interrupt.recv() => {}
949    }
950    Ok(())
951}
952
953/// Wait until the operating system asks this process to stop.
954///
955/// Windows has no signals: a console process is stopped by a console control
956/// event. `CTRL_C` and `CTRL_BREAK` are the terminal's interrupt — the second is
957/// the one another process can send a process group started apart from its own
958/// — and `CTRL_CLOSE` and `CTRL_SHUTDOWN` are the console closing and the
959/// machine shutting down.
960#[cfg(windows)]
961async fn stop_requested() -> Result<(), StartError> {
962    use tokio::signal::windows::{ctrl_break, ctrl_c, ctrl_close, ctrl_shutdown};
963
964    let mut interrupt = ctrl_c().map_err(|error| unhandled("the CTRL_C event", &error))?;
965    let mut breaking = ctrl_break().map_err(|error| unhandled("the CTRL_BREAK event", &error))?;
966    let mut closing = ctrl_close().map_err(|error| unhandled("the CTRL_CLOSE event", &error))?;
967    let mut shutting_down =
968        ctrl_shutdown().map_err(|error| unhandled("the CTRL_SHUTDOWN event", &error))?;
969    tokio::select! {
970        _ = interrupt.recv() => {}
971        _ = breaking.recv() => {}
972        _ = closing.recv() => {}
973        _ = shutting_down.recv() => {}
974    }
975    Ok(())
976}
977
978impl Drop for Running {
979    fn drop(&mut self) {
980        if let Some(stop) = self.stop.take() {
981            let _ = stop.send(());
982        }
983        self.serving.abort();
984    }
985}