printobserver-server 0.15.3

The printobserver server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! The server this tier drives, composed from the real four.
//!
//! Everything here is the implementation the composition root chooses, with two
//! differences a tier is entitled to: the `OctoPrint` instance is the scripted
//! one rather than a printer in a room, and `OneHarness` is pointed at the
//! deterministic responder it itself publishes rather than at a paid provider.
//! Nothing else is replaced — the engine, the session store, the schema
//! validation and the re-prompt loop are the real ones.

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;

/// The shared secret this tier's ingress requires.
pub const SECRET: &str = "a-shared-secret-this-tier-configures";

/// The session the responder reports, which is what a continued session is
/// continued under.
pub const SESSION: &str = "watch-integration";

/// How long one request to the instance may take.
///
/// Longer than the adapter's own default, because a virtual printer part-way
/// through a ten-second dwell answers when the dwell does.
const TIMEOUT: Duration = Duration::from_secs(30);

/// The bound the manifest this tier writes narrows the feedrate to.
///
/// Named here because both the walk's accepted values and the responder's own
/// action have to sit inside it, and the rejection has to sit outside it.
pub const NARROWED: (f64, f64) = (0.8, 1.2);

/// The file this tier's responder appends what it did to.
pub const RESPONDER_LOG: &str = "responder-actions.log";

/// The feedrate the agent asks for, inside every bound in force.
pub const AGENT_FACTOR: f64 = 1.15;

/// How long the agent asks that change to stand for.
pub const AGENT_DURATION_S: i64 = 600;

/// The feedrate the agent also asks for, outside the operator's envelope.
pub const AGENT_REFUSED_FACTOR: f64 = 2.5;

/// The operator credential this tier presents, carrying both characters a
/// TOML string escapes. The configuration names its verifier alone, as an
/// operator who issued one configures it; the supervision turns this tier
/// drives present the credentials minted for them instead.
pub const CONFIGURED_CREDENTIAL: &str = r#"a-configured-"credential"-with-a-\-in-it"#;

/// The server this tier drives, and everything it was composed from.
pub struct Composed {
    /// The state directory, removed when this is dropped.
    pub root: TempDir,
    /// The server, serving.
    pub server: Running,
    /// Durable state, as the server holds it.
    pub stores: Stores,
    /// The client this tier drives the real surface with.
    pub client: reqwest::Client,
    /// The configuration it is running under.
    config: ServerConfig,
}

impl Composed {
    /// A server over a fresh state directory, reaching the instance at one URL.
    ///
    /// The URL is the recording proxy's rather than the instance's own, so that
    /// what the machine received is readable for the three actions it reports
    /// nothing about.
    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;
        // The configuration names the credential's verifier, so this tier
        // presents the credential on every request — and the supervision turns
        // it drives present the credentials minted for them, handed to them in
        // their environment.
        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,
        }
    }

    /// Every action this tier's responder has issued since the log was last
    /// forgotten, as the JSON object it wrote for each.
    ///
    /// # Panics
    ///
    /// Panics when a line the responder wrote is not the JSON object it writes,
    /// which is a responder that has stopped saying what it did.
    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()
    }

    /// Forget every action the responder has issued so far.
    ///
    /// The boundary one turn's actions are read against: the log is appended to
    /// by every turn, and a journey asserting on "an accepted action" would
    /// otherwise be satisfied by one an earlier turn issued.
    pub fn forget_responder_log(&self) {
        std::fs::write(responder_log_path(&self.config), "")
            .expect("the responder's own log is writable");
    }

    /// Stop this server and start another over the same state directory.
    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,
        }
    }

    /// One operation's URL, with the print substituted into it.
    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())
                // A spool command names a spool rather than a print, and this
                // walk asks one of nothing a spool is held under.
                .replace(
                    "{spool_id}",
                    &printobserver_core::SpoolId::new().to_string()
                )
        )
    }

    /// Read one JSON answer, and the status it came under.
    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
    }

    /// Replace one record with a JSON body, and read the JSON answer.
    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
    }

    /// Ask for one action, and read the JSON answer.
    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
    }
}

/// The status and body of one answer, which must be JSON.
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)
}

/// The configuration this tier runs under, written into its own root.
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", "close_print"]
# 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"]
"#,
        // A TOML string rather than the path spliced between quotes: a Windows
        // path's separators are escapes inside a basic string.
        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")
}

/// The file the scripted environment uploads and this tier keeps running.
const HOLD_FILE: &str = "hold.gcode";

/// How long a real machine is given to get where it is going.
const REACHED: Duration = Duration::from_secs(120);

/// A printer speaking to the scripted instance directly.
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),
    )
}

/// The hold print is running, whatever state the environment was left in.
///
/// This is a *precondition* rather than a step of the walk, so it goes through
/// the printer port directly rather than through the API: the API acts on a
/// print this system is watching, and what this establishes is the state the
/// machine has to be in before there is one. It runs before the first alert —
/// an alert delivered to an idle machine ends the print it opens, because a
/// terminal state is what ends a print — before the second, and at the end, so
/// that the other tier on this one machine finds the print it asserts is there.
///
/// # Panics
///
/// Panics when the machine cannot be got printing inside [`REACHED`].
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;
}

/// Wait until the machine reports one job state.
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:?}");
}

/// Write one of the agent's committed assets into the state directory.
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
}

/// The real supervising agent, with only the provider process replaced.
fn agent(config: &ServerConfig) -> OneharnessSupervisor {
    let assets = config.assets_dir();
    let template = materialize(
        &assets,
        "turn-prompt.md",
        printobserver_oneharness::DEFAULT_TURN_PROMPT,
    );
    // The generated assessment schema, as this program materializes it: read
    // from the contracts' own type rather than from a copy of the artifact, so
    // this tier constrains an answer by exactly what the server does.
    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,
        "disposition": "continue",
    })
    .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(),
        // Long enough for the two actions this tier's responder issues against a
        // real machine, and short enough that a turn which hangs is a defect to
        // be read rather than five minutes to be waited out.
        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"),
        ],
        // This tier's responder issues its actions itself rather than through a
        // shell, so the turn keeps the read-only mode.
        agent_commands: Vec::new(),
        withheld_beside_an_image: Vec::new(),
        command_usage: Vec::new(),
        auto_compact_tokens: None,
        idle_compact_tokens: None,
    })
    .expect("the supervising agent is built")
}

/// Where this tier's responder appends what it did.
///
/// Beside the state directory rather than inside it, so that a restart over the
/// same state directory goes on appending to the one file a journey reads.
fn responder_log_path(config: &ServerConfig) -> PathBuf {
    config
        .state_dir
        .parent()
        .unwrap_or(&config.state_dir)
        .join(RESPONDER_LOG)
}

/// The actions this tier's responder issues through the API on every turn.
///
/// One the policy admits and one it does not, both as the agent: an adjustment
/// inside the bounds the feedrate runs under, carrying a duration so that the
/// intervention it opens is readable, and one outside the operator's envelope
/// altogether — outside it whether or not a manifest has narrowed anything, so
/// that the turn the first alert prompts is bounded exactly as every later one
/// is.
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()
}

/// Start one server over the real four.
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)
}