aidaemon-nodes 0.28.0

Nodes for aidaemon agents: enrolled hardware companions with server-issued identity, their HTTP Gateway, store, OTA releases, speech, monitoring and the tools that read and command them; implementation crate of the aidaemon SDK, no stability promise (use it through aidaemon-sdk)
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
use aidaemon_tools::semantics::ToolSemantics;
use anyhow::Context;
use async_trait::async_trait;
use chrono::Utc;
use serde::Deserialize;
use serde_json::{Value, json};
use sqlx::SqlitePool;

use aidaemon_core::ChannelVisibility;
use aidaemon_tools::semantics::UserRole;

use aidaemon_tools::OutcomeTool as Tool;
use aidaemon_tools::semantics::{
    EvidenceAuthority, EvidencePurpose, EvidenceTemporalScope, ToolCallContext, ToolCallMetadata,
    ToolCallOutcome, ToolCallSemantics, ToolCapabilities, ToolEvidenceCapability,
    ToolMutationEffects, ToolOutcomeStatus, ToolRole, ToolSemanticScope, ToolVerificationMode,
};

const FRESH_READING_SECONDS: i64 = 90;
/// A Node seen within this many seconds counts as recently connected (a
/// restart is confirmed by the same test).
pub(crate) const FRESH_NODE_SECONDS: i64 = 90;

pub struct ReadNodeSensorsTool {
    pool: SqlitePool,
}

pub struct ReadNodeHealthTool {
    pool: SqlitePool,
}

pub struct SendNodeAudioTool {
    announcements: super::announcement::NodeAnnouncementService,
}

pub struct ManageNodeMonitorsTool {
    monitoring: super::monitoring::NodeMonitoringService,
}

impl ManageNodeMonitorsTool {
    pub fn new(monitoring: super::monitoring::NodeMonitoringService) -> Self {
        Self { monitoring }
    }
}

impl SendNodeAudioTool {
    pub fn new(announcements: super::announcement::NodeAnnouncementService) -> Self {
        Self { announcements }
    }

    async fn execute_delivery(
        &self,
        arguments: &str,
        facts: &ToolCallContext,
    ) -> anyhow::Result<(String, String)> {
        let args: SendNodeAudioArgs = serde_json::from_str(arguments)
            .context("send_node_audio arguments must be valid JSON")?;
        anyhow::ensure!(
            facts.user_role == Some(UserRole::Owner),
            "Only the AIDaemon owner may send Node audio"
        );
        let delivery = self
            .announcements
            .queue_and_wait(args.node.as_deref(), &args.text)
            .await?;
        let now = Utc::now();
        let last_seen_age_seconds = delivery
            .queued
            .last_seen_at
            .map(|seen| (now - seen).num_seconds().max(0));
        let (status, acknowledged_at, detail_code) = delivery
            .receipt
            .as_ref()
            .map(|receipt| {
                (
                    receipt.status.as_str(),
                    Some(receipt.acknowledged_at.to_rfc3339()),
                    receipt.detail_code.as_deref(),
                )
            })
            .unwrap_or(("queued", None, None));
        let output = serde_json::to_string_pretty(&json!({
            "node": delivery.queued.display_name,
            "delivery_id": delivery.queued.cursor,
            "delivery_status": status,
            "acknowledged_at": acknowledged_at,
            "detail_code": detail_code,
            "audio_bytes": delivery.queued.size_bytes,
            "expires_at": delivery.queued.expires_at.to_rfc3339(),
            "node_last_seen_age_seconds": last_seen_age_seconds,
            "interpretation": if status == "played" {
                "The Device acknowledged completed playback."
            } else if status == "queued" {
                "The announcement is queued but playback has not been acknowledged; do not claim that it played."
            } else {
                "The Device acknowledged the announcement without successful playback."
            }
        }))?;
        Ok((output, status.to_string()))
    }
}

fn node_evidence(purposes: &[EvidencePurpose]) -> Vec<ToolEvidenceCapability> {
    vec![ToolEvidenceCapability::new(
        ToolSemanticScope::ExternalRemote,
        purposes,
        EvidenceAuthority::Direct,
        EvidenceTemporalScope::Current,
    )]
}

fn node_observation_semantics(purposes: &[EvidencePurpose]) -> ToolCallSemantics {
    ToolCallSemantics::observation()
        .with_verification_mode(ToolVerificationMode::ResultContent)
        .with_evidence(node_evidence(purposes))
}

fn node_audio_receipt_semantics() -> ToolCallSemantics {
    ToolCallSemantics::observation_and_mutation_with(ToolMutationEffects::EXTERNAL_DELIVERY)
        .with_verification_mode(ToolVerificationMode::ResultContent)
        .with_evidence(node_evidence(&[EvidencePurpose::Outcome]))
}

fn node_audio_outcome_status(status: &str) -> ToolOutcomeStatus {
    match status {
        "played" => ToolOutcomeStatus::Succeeded,
        // Queuing changed outbox state, but it did not establish completed
        // playback and should remain an explicit incomplete domain result.
        "queued" => ToolOutcomeStatus::CompletedWithNegativeResult,
        // The Device explicitly rejected or failed playback. Retrying the same
        // non-idempotent delivery automatically would be unsafe.
        "failed" | "dismissed" => ToolOutcomeStatus::FailedPermanent,
        _ => ToolOutcomeStatus::FailedPermanent,
    }
}

impl ReadNodeSensorsTool {
    pub fn new(pool: SqlitePool) -> Self {
        Self { pool }
    }
}

impl ReadNodeHealthTool {
    pub fn new(pool: SqlitePool) -> Self {
        Self { pool }
    }
}

#[derive(Debug, Deserialize)]
struct ReadNodeSensorsArgs {
    #[serde(default)]
    node: Option<String>,
}

#[derive(Debug, Deserialize)]
struct ReadNodeHealthArgs {
    #[serde(default)]
    node: Option<String>,
}

#[derive(Debug, Deserialize)]
struct SendNodeAudioArgs {
    text: String,
    #[serde(default)]
    node: Option<String>,
}

#[derive(Debug, Deserialize)]
struct ManageNodeMonitorsArgs {
    action: String,
    #[serde(default)]
    monitor_id: Option<String>,
    #[serde(default)]
    name: Option<String>,
    #[serde(default)]
    node: Option<String>,
    #[serde(default)]
    capability_id: Option<String>,
    #[serde(default)]
    comparison: Option<String>,
    #[serde(default)]
    threshold: Option<f64>,
    #[serde(default)]
    clear_threshold: Option<f64>,
    #[serde(default)]
    duration_seconds: Option<u64>,
    #[serde(default)]
    stale_after_seconds: Option<u64>,
    #[serde(default)]
    offline_after_seconds: Option<u64>,
    #[serde(default)]
    repeat_seconds: Option<u64>,
    #[serde(default)]
    send_recovery: Option<bool>,
    #[serde(default)]
    duration_minutes: Option<u64>,
    #[serde(default)]
    mandate_id: Option<String>,
    #[serde(default)]
    since_hours: Option<u64>,
    #[serde(default)]
    limit: Option<u32>,
}

fn required_arg<'a>(value: Option<&'a str>, name: &str) -> anyhow::Result<&'a str> {
    value
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| anyhow::anyhow!("{name} is required"))
}

fn monitor_mandate_for_action(
    action: &str,
    mandate_id: Option<String>,
) -> anyhow::Result<Option<String>> {
    match action {
        // Standalone creation is intentionally robust against an LLM copying a
        // nearby goal, requirement, or mandate identifier into an optional
        // field. Lifecycle binding requires the distinct explicit action.
        "create" => Ok(None),
        "create_linked" => Ok(Some(
            required_arg(mandate_id.as_deref(), "mandate_id")?.to_string(),
        )),
        _ => Ok(mandate_id),
    }
}

#[async_trait]
impl Tool for ReadNodeSensorsTool {
    fn name(&self) -> &str {
        "read_node_sensors"
    }

    fn description(&self) -> &str {
        "Read the latest authenticated environmental sensor readings reported by an enrolled AIDaemon Node. Use when the owner asks for the K10 temperature or humidity."
    }

    fn schema(&self) -> Value {
        json!({
            "name": "read_node_sensors",
            "description": "Read the latest server-received temperature and humidity values from an enrolled AIDaemon Node, including reading age. This reads stored sensor state; it does not activate a microphone, camera, or actuator.",
            "parameters": {
                "type": "object",
                "properties": {
                    "node": {
                        "type": "string",
                        "description": "Optional Node display name. Omit when exactly one active Node is enrolled."
                    }
                },
                "additionalProperties": false
            }
        })
    }

    async fn execute(
        &self,
        arguments: &str,
        facts: &aidaemon_tools::semantics::ToolCallContext,
    ) -> anyhow::Result<aidaemon_tools::semantics::ToolCallOutcome> {
        let facts = facts.clone();

        Ok(ToolCallOutcome {
            output: self.run(arguments, &facts).await?,
            metadata: ToolCallMetadata {
                outcome_status: Some(ToolOutcomeStatus::Succeeded),
                semantics: self.call_semantics(arguments),
                ..ToolCallMetadata::default()
            },
            finish: None,
        })
    }
}

impl ReadNodeSensorsTool {
    /// Run one call with the dispatcher's `facts`.
    async fn run(&self, arguments: &str, facts: &ToolCallContext) -> anyhow::Result<String> {
        let args: ReadNodeSensorsArgs = serde_json::from_str(if arguments.trim().is_empty() {
            "{}"
        } else {
            arguments
        })
        .context("read_node_sensors arguments must be valid JSON")?;
        anyhow::ensure!(
            facts.user_role == Some(UserRole::Owner),
            "Only the AIDaemon owner may read Node sensor values"
        );
        let readings =
            super::store::latest_sensor_readings(&self.pool, args.node.as_deref()).await?;
        anyhow::ensure!(
            !readings.is_empty(),
            "The selected Node has not reported any sensor readings yet"
        );
        let now = Utc::now();
        let mut output_readings = Vec::with_capacity(readings.len());
        let mut all_fresh = true;
        for reading in &readings {
            let age_seconds = (now - reading.received_at).num_seconds().max(0);
            all_fresh &= age_seconds <= FRESH_READING_SECONDS;
            let mut rendered = json!({
                "capability_id": reading.capability_id,
                "capability_version": reading.capability_version,
                "value": reading.value,
                "unit": reading.unit,
                "reading_age_seconds": age_seconds,
                "server_received_at": reading.received_at.to_rfc3339(),
                "sample_uptime_ms": reading.sample_uptime_ms,
            });
            if reading.capability_id == "sensor.environment.temperature"
                && reading.unit == "celsius"
            {
                rendered["fahrenheit"] = json!(reading.value.mul_add(1.8, 32.0));
            }
            output_readings.push(rendered);
        }
        let last_seen_age_seconds = readings[0]
            .node_last_seen_at
            .map(|seen| (now - seen).num_seconds().max(0));
        Ok(serde_json::to_string_pretty(&json!({
            "node": readings[0].display_name,
            "freshness": if all_fresh { "fresh" } else { "stale" },
            "freshness_threshold_seconds": FRESH_READING_SECONDS,
            "node_last_seen_age_seconds": last_seen_age_seconds,
            "readings": output_readings,
            "interpretation": "These are the latest Device-reported ambient readings. A stale reading must be described as stale, not current."
        }))?)
    }
}

impl aidaemon_tools::semantics::ToolSemantics for ReadNodeSensorsTool {
    fn dispatch_facts(&self) -> aidaemon_tools::semantics::ToolDispatchFacts {
        aidaemon_tools::semantics::ToolDispatchFacts {
            evidence: aidaemon_tools::semantics::EvidenceSource::NodeReading,
            ..Default::default()
        }
    }

    fn capabilities(&self) -> ToolCapabilities {
        ToolCapabilities::READ_ONLY
    }

    /// The request travels to an enrolled Node over the network, whose
    /// address is not known from the arguments.
    fn call_effects(&self, _arguments: &str) -> aidaemon_core::CallEffects {
        aidaemon_core::CallEffects::unknown()
    }

    fn call_semantics(&self, _arguments: &str) -> ToolCallSemantics {
        node_observation_semantics(&[EvidencePurpose::CurrentState, EvidencePurpose::Content])
    }
}

#[async_trait]
impl Tool for ReadNodeHealthTool {
    fn name(&self) -> &str {
        "read_node_health"
    }

    fn description(&self) -> &str {
        "Read an enrolled AIDaemon Node's latest authenticated heartbeat, reported capabilities, current gateway authorizations, and bounded Runtime recovery evidence."
    }

    fn schema(&self) -> Value {
        json!({
            "name": "read_node_health",
            "description": "Inspect stored Node connection freshness, Runtime/firmware versions, reported protocol capabilities and limits, current gateway authorizations, bounded resource health, and the most recent Runtime recovery report. Use this before claiming that a Companion control is supported or unavailable. This is evidence reported during an authenticated Node Session; it cannot contact or restart an offline Device.",
            "parameters": {
                "type": "object",
                "properties": {
                    "node": {
                        "type": "string",
                        "description": "Optional Node display name. Omit when exactly one active Node is enrolled."
                    }
                },
                "additionalProperties": false
            }
        })
    }

    async fn execute(
        &self,
        arguments: &str,
        facts: &aidaemon_tools::semantics::ToolCallContext,
    ) -> anyhow::Result<aidaemon_tools::semantics::ToolCallOutcome> {
        let facts = facts.clone();

        Ok(ToolCallOutcome {
            output: self.run(arguments, &facts).await?,
            metadata: ToolCallMetadata {
                outcome_status: Some(ToolOutcomeStatus::Succeeded),
                semantics: self.call_semantics(arguments),
                ..ToolCallMetadata::default()
            },
            finish: None,
        })
    }
}

impl ReadNodeHealthTool {
    /// Run one call with the dispatcher's `facts`.
    async fn run(&self, arguments: &str, facts: &ToolCallContext) -> anyhow::Result<String> {
        let args: ReadNodeHealthArgs = serde_json::from_str(if arguments.trim().is_empty() {
            "{}"
        } else {
            arguments
        })
        .context("read_node_health arguments must be valid JSON")?;
        anyhow::ensure!(
            facts.user_role == Some(UserRole::Owner),
            "Only the AIDaemon owner may read Node health"
        );
        let health = super::store::node_health_snapshot(&self.pool, args.node.as_deref()).await?;
        let now = Utc::now();
        let last_seen_age_seconds = health
            .last_seen_at
            .map(|seen| (now - seen).num_seconds().max(0));
        let connection_state = match last_seen_age_seconds {
            Some(age) if age <= FRESH_NODE_SECONDS => "recently_connected",
            Some(_) => "stale",
            None => "never_connected",
        };
        Ok(serde_json::to_string_pretty(&json!({
            "node": health.display_name,
            "connection_state": connection_state,
            "freshness_threshold_seconds": FRESH_NODE_SECONDS,
            "last_seen_age_seconds": last_seen_age_seconds,
            "last_seen_at": health.last_seen_at.map(|value| value.to_rfc3339()),
            "runtime_version": health.runtime_version,
            "firmware_version": health.firmware_version,
            "uptime_ms": health.uptime_ms,
            "free_internal_heap": health.free_internal_heap,
            "largest_internal_allocation": health.largest_internal_allocation,
            "psram_free": health.psram_free,
            "recovery": health.recovery,
            "reported_capabilities": health.capabilities,
            "current_authorizations": health.authorizations,
            "interpretation": "This is the latest authenticated Runtime report stored by AIDaemon. Capability absence means the Node did not report that protocol control; it does not prove the physical hardware lacks it. Authorization absence means the gateway has not granted that action. A stale report does not prove the Device is currently reachable, and a recovery report does not prove physical hardware health."
        }))?)
    }
}

impl aidaemon_tools::semantics::ToolSemantics for ReadNodeHealthTool {
    fn dispatch_facts(&self) -> aidaemon_tools::semantics::ToolDispatchFacts {
        aidaemon_tools::semantics::ToolDispatchFacts {
            evidence: aidaemon_tools::semantics::EvidenceSource::NodeReading,
            ..Default::default()
        }
    }

    fn capabilities(&self) -> ToolCapabilities {
        ToolCapabilities::READ_ONLY
    }

    /// The request travels to an enrolled Node over the network, whose
    /// address is not known from the arguments.
    fn call_effects(&self, _arguments: &str) -> aidaemon_core::CallEffects {
        aidaemon_core::CallEffects::unknown()
    }

    fn call_semantics(&self, _arguments: &str) -> ToolCallSemantics {
        node_observation_semantics(&[EvidencePurpose::CurrentState, EvidencePurpose::Content])
    }
}

#[async_trait]
impl Tool for SendNodeAudioTool {
    fn name(&self) -> &str {
        "send_node_audio"
    }

    fn description(&self) -> &str {
        "Deliver a short owner-requested spoken announcement to an enrolled, explicitly authorized audio-capable Node. Use when the owner asks AIDaemon to tell or announce something on a Companion."
    }

    fn schema(&self) -> Value {
        json!({
            "name": "send_node_audio",
            "description": "Generate and deliver a short spoken announcement to an enrolled Node. This is owner-only external delivery; use only when the owner explicitly asks to play or say something on a Node.",
            "parameters": {
                "type": "object",
                "properties": {
                    "text": {
                        "type": "string",
                        "description": "Exact short message to speak. Do not add private context the owner did not request."
                    },
                    "node": {
                        "type": "string",
                        "description": "Exact Node display name. Omit only when one eligible Node exists."
                    }
                },
                "required": ["text"],
                "additionalProperties": false
            }
        })
    }

    async fn execute(
        &self,
        arguments: &str,
        facts: &aidaemon_tools::semantics::ToolCallContext,
    ) -> anyhow::Result<aidaemon_tools::semantics::ToolCallOutcome> {
        let facts = facts.clone();

        let (output, status) = self.execute_delivery(arguments, &facts).await?;
        Ok(ToolCallOutcome {
            output,
            metadata: ToolCallMetadata {
                outcome_status: Some(node_audio_outcome_status(&status)),
                semantics: node_audio_receipt_semantics(),
                ..ToolCallMetadata::default()
            },
            finish: None,
        })
    }
}

impl aidaemon_tools::semantics::ToolSemantics for SendNodeAudioTool {
    fn dispatch_facts(&self) -> aidaemon_tools::semantics::ToolDispatchFacts {
        aidaemon_tools::semantics::ToolDispatchFacts {
            evidence: aidaemon_tools::semantics::EvidenceSource::NodeAction,
            ..Default::default()
        }
    }

    fn capabilities(&self) -> ToolCapabilities {
        ToolCapabilities::EXTERNAL_WRITE
    }

    fn call_semantics(&self, _arguments: &str) -> ToolCallSemantics {
        node_audio_receipt_semantics()
    }
}

#[async_trait]
impl Tool for ManageNodeMonitorsTool {
    fn name(&self) -> &str {
        "manage_node_monitors"
    }

    fn description(&self) -> &str {
        "Create and govern explicit, time-bounded temperature or humidity monitors for the owner; a direct owner request needs no separate monitoring authorization or mandate."
    }

    fn schema(&self) -> Value {
        json!({
            "name": "manage_node_monitors",
            "description": "Create, list, inspect, pause, resume, or cancel deterministic environmental monitors. Create only after an explicit owner request in a private Channel. A direct owner request is sufficient: do not create a mandate or a separate monitoring authorization. The Node's existing report_sensor grant is the only Node authorization required. Every monitor expires. V1 supports temperature and humidity only; it never activates a camera, microphone, or actuator.",
            "parameters": {
                "type": "object",
                "properties": {
                    "action": {
                        "type": "string",
                        "enum": ["create", "create_linked", "list", "get", "history", "pause", "resume", "cancel"],
                        "description": "Use create for normal direct owner requests. Use create_linked only when the current owner message explicitly requests linkage to an exact existing mandate ID."
                    },
                    "monitor_id": {"type": "string", "description": "Required for get, history, pause, resume, and cancel."},
                    "name": {"type": "string", "description": "Create only: short owner-facing monitor name."},
                    "node": {"type": "string", "description": "Create only: exact Node display name. Omit only when one eligible Node exists."},
                    "capability_id": {
                        "type": "string",
                        "enum": ["sensor.environment.temperature", "sensor.environment.humidity"],
                        "description": "Create only."
                    },
                    "comparison": {"type": "string", "enum": ["above", "below"], "description": "Create only."},
                    "threshold": {"type": "number", "description": "Create only: Celsius or percent relative humidity alert point."},
                    "clear_threshold": {"type": "number", "description": "Create only: hysteresis recovery point; <= threshold for above, >= for below."},
                    "duration_seconds": {"type": "integer", "minimum": 0, "maximum": 86400, "description": "Create only: continuous crossing time before alerting."},
                    "stale_after_seconds": {"type": "integer", "minimum": 30, "maximum": 86400, "description": "Create only: optional missing-reading alert interval."},
                    "offline_after_seconds": {"type": "integer", "minimum": 30, "maximum": 86400, "description": "Create only: optional Node check-in alert interval. Values shorter than stale_after_seconds are safely normalized to stale_after_seconds."},
                    "repeat_seconds": {"type": "integer", "minimum": 0, "maximum": 604800, "description": "Create only: 0 sends one alert per incident; otherwise repeat interval."},
                    "send_recovery": {"type": "boolean", "description": "Create only: send an alert when the condition recovers."},
                    "duration_minutes": {"type": "integer", "minimum": 1, "description": "Create only: required monitor lifetime."},
                    "mandate_id": {"type": "string", "description": "Required only for create_linked and ignored by ordinary create. Use create_linked only when the current owner message explicitly names an exact existing, confirmed, active mandate ID. Never use a goal ID, requirement ID, inferred ID, or a mandate created merely to authorize monitoring; direct owner requests need no mandate."},
                    "since_hours": {"type": "integer", "minimum": 1, "maximum": 720, "description": "History only; defaults to 24."},
                    "limit": {"type": "integer", "minimum": 1, "maximum": 500, "description": "History only; defaults to 100."}
                },
                "required": ["action"],
                "additionalProperties": false
            }
        })
    }

    async fn execute(
        &self,
        arguments: &str,
        facts: &aidaemon_tools::semantics::ToolCallContext,
    ) -> anyhow::Result<aidaemon_tools::semantics::ToolCallOutcome> {
        let facts = facts.clone();

        self.run(arguments, &facts)
            .await
            .map(ToolCallOutcome::from_output)
    }
}

impl ManageNodeMonitorsTool {
    /// Run one call with the dispatcher's `facts`.
    async fn run(&self, arguments: &str, facts: &ToolCallContext) -> anyhow::Result<String> {
        let args: ManageNodeMonitorsArgs = serde_json::from_str(arguments)
            .context("manage_node_monitors arguments must be valid JSON")?;
        anyhow::ensure!(
            facts.user_role == Some(UserRole::Owner),
            "Only the AIDaemon owner may manage Node monitors"
        );
        anyhow::ensure!(
            facts.channel_visibility == Some(ChannelVisibility::Private),
            "Node monitors may only be managed from a private Channel"
        );
        let session_id = required_arg(facts.session(), "owner session")?;
        let output = match args.action.as_str() {
            "create" | "create_linked" => {
                let mandate_id = monitor_mandate_for_action(&args.action, args.mandate_id)?;
                let request = super::monitoring::CreateNodeMonitor {
                    name: required_arg(args.name.as_deref(), "name")?.to_string(),
                    owner_session_id: session_id.to_string(),
                    node: args.node,
                    capability_id: required_arg(args.capability_id.as_deref(), "capability_id")?
                        .to_string(),
                    comparison: super::monitoring::MonitorComparison::parse(required_arg(
                        args.comparison.as_deref(),
                        "comparison",
                    )?)?,
                    threshold: args.threshold.context("threshold is required")?,
                    clear_threshold: args
                        .clear_threshold
                        .context("clear_threshold is required")?,
                    duration_seconds: args.duration_seconds.unwrap_or(0),
                    stale_after_seconds: args.stale_after_seconds,
                    offline_after_seconds: args.offline_after_seconds,
                    repeat_seconds: args.repeat_seconds.unwrap_or(0),
                    send_recovery: args.send_recovery.unwrap_or(true),
                    duration_minutes: args
                        .duration_minutes
                        .context("duration_minutes is required")?,
                    mandate_id,
                };
                json!({"monitor": self.monitoring.create(request).await?})
            }
            "list" => json!({"monitors": self.monitoring.list(session_id).await?}),
            "get" => {
                let monitor_id = required_arg(args.monitor_id.as_deref(), "monitor_id")?;
                json!({"monitor": self.monitoring.get(monitor_id, session_id).await?})
            }
            "history" => {
                let monitor_id = required_arg(args.monitor_id.as_deref(), "monitor_id")?;
                let since_hours = args.since_hours.unwrap_or(24);
                let limit = args.limit.unwrap_or(100);
                json!({
                    "monitor": self.monitoring.get(monitor_id, session_id).await?,
                    "events": self.monitoring.history(
                        monitor_id,
                        session_id,
                        since_hours,
                        limit,
                    ).await?,
                    "sensor_readings": self.monitoring.sensor_history(
                        monitor_id,
                        session_id,
                        since_hours,
                        limit,
                    ).await?,
                })
            }
            "pause" | "resume" | "cancel" => {
                let monitor_id = required_arg(args.monitor_id.as_deref(), "monitor_id")?;
                json!({"monitor": self.monitoring.change_status(monitor_id, session_id, &args.action).await?})
            }
            other => anyhow::bail!("unknown manage_node_monitors action `{other}`"),
        };
        Ok(serde_json::to_string_pretty(&output)?)
    }
}

impl aidaemon_tools::semantics::ToolSemantics for ManageNodeMonitorsTool {
    fn capabilities(&self) -> ToolCapabilities {
        ToolCapabilities::EXTERNAL_WRITE
    }

    fn tool_role(&self) -> ToolRole {
        ToolRole::Management
    }

    fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
        let action = serde_json::from_str::<Value>(arguments)
            .ok()
            .and_then(|value| {
                value
                    .get("action")
                    .and_then(Value::as_str)
                    .map(str::to_string)
            });
        match action.as_deref() {
            Some("list" | "get" | "history") => ToolCallSemantics::observation(),
            _ => ToolCallSemantics::mutation_with(ToolMutationEffects::CONFIGURATION),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use aidaemon_tools::testing::CallWithFacts;

    #[test]
    fn played_audio_receipt_is_authoritative_delivery_and_outcome_evidence() {
        assert_eq!(
            node_audio_outcome_status("played"),
            ToolOutcomeStatus::Succeeded
        );
        let semantics = node_audio_receipt_semantics();
        assert!(semantics.observes_state());
        assert!(semantics.mutates_state());
        assert!(
            semantics
                .mutation_effects
                .contains(ToolMutationEffects::EXTERNAL_DELIVERY)
        );
        assert!(semantics.can_verify_with_result_content());
        assert!(semantics.evidence.iter().any(|capability| {
            capability.scope == ToolSemanticScope::ExternalRemote
                && capability.purposes.contains(&EvidencePurpose::Outcome)
                && capability.authority == EvidenceAuthority::Direct
        }));
    }

    #[test]
    fn incomplete_audio_receipts_do_not_satisfy_completed_playback() {
        assert_eq!(
            node_audio_outcome_status("queued"),
            ToolOutcomeStatus::CompletedWithNegativeResult
        );
        for status in ["failed", "dismissed"] {
            assert_eq!(
                node_audio_outcome_status(status),
                ToolOutcomeStatus::FailedPermanent
            );
        }
    }

    #[tokio::test]
    async fn rejects_non_owner_before_reading_node_state() {
        let pool = SqlitePool::connect("sqlite::memory:").await.unwrap();
        let tool = ReadNodeSensorsTool::new(pool.clone());
        let error = tool
            .call_with(
                r#"{}"#,
                aidaemon_tools::semantics::ToolCallContext {
                    user_role: Some(aidaemon_tools::semantics::UserRole::Public),
                    ..Default::default()
                },
            )
            .await
            .unwrap_err();
        assert!(error.to_string().contains("Only the AIDaemon owner"));
        let health_tool = ReadNodeHealthTool::new(pool);
        let error = health_tool
            .call_with(
                r#"{}"#,
                aidaemon_tools::semantics::ToolCallContext {
                    user_role: Some(aidaemon_tools::semantics::UserRole::Public),
                    ..Default::default()
                },
            )
            .await
            .unwrap_err();
        assert!(error.to_string().contains("Only the AIDaemon owner"));
    }

    #[tokio::test]
    async fn audio_delivery_is_owner_only_and_disabled_by_default() {
        let pool = SqlitePool::connect("sqlite::memory:").await.unwrap();
        let store = std::sync::Arc::new(super::super::store::NodeStore::new(pool, [9_u8; 32]));
        let announcements = super::super::announcement::NodeAnnouncementService::new(
            store,
            crate::config::NodesConfig::default(),
            std::sync::Arc::new(super::super::speech::DisabledSpeech),
        );
        let tool = SendNodeAudioTool::new(announcements);

        let non_owner = tool
            .call_with(
                r#"{"text":"hello"}"#,
                aidaemon_tools::semantics::ToolCallContext {
                    user_role: Some(aidaemon_tools::semantics::UserRole::Public),
                    ..Default::default()
                },
            )
            .await
            .unwrap_err();
        assert!(non_owner.to_string().contains("Only the AIDaemon owner"));

        let disabled = tool
            .call_with(
                r#"{"text":"hello"}"#,
                aidaemon_tools::semantics::ToolCallContext {
                    user_role: Some(aidaemon_tools::semantics::UserRole::Owner),
                    ..Default::default()
                },
            )
            .await
            .unwrap_err();
        assert!(
            disabled
                .to_string()
                .contains("Node audio announcements are disabled")
        );
    }

    #[tokio::test]
    async fn monitor_management_requires_owner_and_private_channel() {
        let pool = SqlitePool::connect("sqlite::memory:").await.unwrap();
        let service = super::super::monitoring::NodeMonitoringService::new(
            pool,
            crate::config::NodeMonitoringConfig::default(),
        );
        let tool = ManageNodeMonitorsTool::new(service);

        let non_owner = tool
            .call_with(
                r#"{"action":"list"}"#,
                aidaemon_tools::semantics::ToolCallContext {
                    user_role: Some(aidaemon_tools::semantics::UserRole::Public),
                    channel_visibility: Some(aidaemon_core::ChannelVisibility::Private),
                    session_id: "public-session".into(),
                    ..Default::default()
                },
            )
            .await
            .unwrap_err();
        assert!(non_owner.to_string().contains("Only the AIDaemon owner"));

        let public_channel = tool
            .call_with(
                r#"{"action":"list"}"#,
                aidaemon_tools::semantics::ToolCallContext {
                    user_role: Some(aidaemon_tools::semantics::UserRole::Owner),
                    channel_visibility: Some(aidaemon_core::ChannelVisibility::PublicExternal),
                    session_id: "owner-session".into(),
                    ..Default::default()
                },
            )
            .await
            .unwrap_err();
        assert!(public_channel.to_string().contains("private Channel"));

        let disabled = tool
            .call_with(
                r#"{"action":"list"}"#,
                aidaemon_tools::semantics::ToolCallContext {
                    user_role: Some(aidaemon_tools::semantics::UserRole::Owner),
                    channel_visibility: Some(aidaemon_core::ChannelVisibility::Private),
                    session_id: "owner-session".into(),
                    ..Default::default()
                },
            )
            .await
            .unwrap_err();
        assert!(disabled.to_string().contains("monitoring is disabled"));
    }

    #[tokio::test]
    async fn monitor_schema_tells_agents_not_to_invent_mandate_authorization() {
        let pool = SqlitePool::connect("sqlite::memory:").await.unwrap();
        let service = super::super::monitoring::NodeMonitoringService::new(
            pool,
            crate::config::NodeMonitoringConfig::default(),
        );
        let tool = ManageNodeMonitorsTool::new(service);
        let schema = tool.schema();

        let description = schema["description"].as_str().unwrap();
        assert!(description.contains("direct owner request is sufficient"));
        assert!(description.contains("do not create a mandate"));
        assert!(description.contains("report_sensor"));
        let mandate_description = schema["parameters"]["properties"]["mandate_id"]["description"]
            .as_str()
            .unwrap();
        assert!(mandate_description.contains("Never use a goal ID"));
        assert!(mandate_description.contains("direct owner requests need no mandate"));
    }

    #[test]
    fn standalone_monitor_creation_ignores_inferred_mandate_ids() {
        assert_eq!(
            monitor_mandate_for_action("create", Some("not-a-mandate".to_string())).unwrap(),
            None
        );

        let error = monitor_mandate_for_action("create_linked", None).unwrap_err();
        assert!(error.to_string().contains("mandate_id is required"));
        assert_eq!(
            monitor_mandate_for_action("create_linked", Some("explicit-mandate".to_string()))
                .unwrap(),
            Some("explicit-mandate".to_string())
        );
    }
}