Skip to main content

phoxal_api/
lib.rs

1//! The single API layer (D60/D61/D1).
2//!
3//! This crate is the versioned API contract tree. It depends only on the
4//! [`phoxal-bus`](phoxal_bus) ABI floor (the contract primitive traits and the
5//! typed-topic builders) and the [`phoxal-macros`](phoxal_macros) proc-macros; it
6//! does **not** depend on the `phoxal` engine. A participant depends on both crates
7//! and imports the API tree directly with `use phoxal_api::v1 as api;`, so
8//! `phoxal_api::v1`, `phoxal_api::ApiVersion`, and `phoxal_api::ContractBody`
9//! are the canonical paths.
10//!
11//! # Stable and preview API versions
12//!
13//! An API version is a conventional `vN` module generated by
14//! [`phoxal_api_tree!`]. Each version module carries:
15//!
16//! - a zero-variant marker `enum Api {}` implementing [`ApiVersion`], whose
17//!   [`ApiVersion::ID`] is the module name (`"v1"` or `"v2"`);
18//! - the version-local wire bodies, one `pub mod` per contract node holding plain
19//!   serde structs/enums and their [`ContractBody`] impls;
20//! - an api-local `topic` builder rooted at `topic::new()`.
21//!
22//! `v1` is the current production surface and may change in place while the
23//! pre-stability topology is simplified. `v2` is the single preview surface for
24//! contracts that have not entered production. Preview work does not mint a new
25//! public version for each change.
26//! `v2` is authored as `preview version v2 { … }` and is available when the
27//! `preview-v2` Cargo feature is enabled. [`ApiVersion::IS_PREVIEW`] records the
28//! lifecycle without changing topics or wire bytes.
29//!
30//! [`Api`]: v1::Api
31//!
32//! # Per-field versions and per-contract identity
33//!
34//! A participant declares its bus surface with a companion
35//! `#[derive(phoxal::Api)]` handle struct.
36//! Each handle field names its own version-qualified contract type, so one
37//! participant may freely mix fields from modules such as `v1` and
38//! `v2`.
39//! The derive records each field's resolved [`ContractBody::VERSION`] and
40//! [`ContractBody::CONTRACT`] in the participant's embedded metadata and does
41//! not declare a participant-wide API version.
42//! Across the graph, compatibility is **name identity** (D1) - two participants
43//! interoperate on a contract iff they use the exact same version-qualified name
44//! (`v1::drive::Target`), which is real on the wire because the version
45//! is folded into the key ([`ContractBody::TOPIC`]). There is no `schema_id`: a
46//! stable contract type is immutable, so the name alone is the whole identity.
47//!
48//! # Plain serde wire bodies, provenance in metadata
49//!
50//! A wire body is just its serde encoding - there is no `{"v":…}` envelope or any
51//! other version tag inside the payload (D62). Identity lives entirely in the
52//! Zenoh key (the version-qualified [`ContractBody::TOPIC`]); the bus metadata
53//! alongside the encoded body carries only provenance (source + logical time) and
54//! the codec that produced the bytes - never schema/family/version. Keeping
55//! identity out of both the payload and the metadata means the body bytes for an
56//! unchanged contract are identical across codecs, and a receiver's per-key
57//! subscription is the whole fast-reject.
58//!
59//! # Topic
60//!
61//! [`ContractBody::TOPIC`] is derived from the contract node's path in the tree,
62//! never written by hand: the version, then the `/`-joined node path plus the
63//! topic leaf, with each dynamic node contributing a `{var}` placeholder, e.g.
64//! `v1/component/{instance}/motor/{capability}/command`. A fully static path
65//! has a literal key (`v1/drive/state`). Folding the version into the key
66//! (D1) is what makes two differently-versioned contracts physically distinct
67//! Zenoh keys - they cannot collide, so there is no `SCHEMA_ID`/`FAMILY` needed to
68//! disambiguate them.
69//!
70//! # The api-local topic builder
71//!
72//! Each version module exposes a `topic` builder that mirrors the node tree:
73//! `api::topic::new()` returns a root, one method per top-level node walks down the
74//! tree, a dynamic node's method takes its variable as `impl Display`, and a leaf
75//! method binds the topic's side-branded kind to its version-local body. For
76//! example `api::topic::new().drive().state()` yields a
77//! `Topic<Subscribe<drive::State>>` (the CLIENT observes the owner's `state`) over
78//! the version-qualified key `v1/drive/state`, and
79//! `api::topic::new().component("base").motor("left").command()` fills the dynamic
80//! segments to produce `v1/component/base/motor/left/command`. Because the
81//! builder is generated from the same tree as `TOPIC`, the built key and the
82//! documented key stay in lockstep.
83//!
84//! ## Owner side: `topic::internal`
85//!
86//! The PUBLIC `topic::new()...` chain above is the **client** side. The matching
87//! **owner** side lives at `api::topic::internal::new(cap)...` (L1 + L2, plan #00):
88//! the same node tree and keys, but the leaf brands flip so the owner gets the side
89//! it must take - `api::topic::internal::new(cap).drive().state()` is
90//! `Topic<Publish<drive::State>>` (the owner publishes its telemetry), and
91//! `api::topic::internal::new(cap).drive().target()` is `Topic<Subscribe<drive::Target>>`
92//! (the owner reads its command input). A query owner reaches its `ServeQuery`
93//! brand the same way. The `internal` chain is the deliberate, greppable owner
94//! opt-in; a participant acquires the topics of its OWN node through it and everything
95//! it consumes through the public chain.
96//!
97//! The `internal::new` entry requires the runner-minted owner capability
98//! ([`OwnerCap`](phoxal_bus::OwnerCap), Layer 2): a participant obtains it from
99//! `phoxal::SetupContext::owner_capability()` and passes it in. On the documented
100//! surface, owning a topic therefore cannot happen by accident - only with a
101//! capability the runner mints.
102
103use phoxal_macros::phoxal_api_tree;
104
105/// The contract primitive traits, re-exported from the `phoxal-bus` crate (the
106/// ABI floor) so they stay addressable at `phoxal_api::ApiVersion` /
107/// `phoxal_api::ContractBody`.
108///
109/// - [`ApiVersion`] is the marker trait identifying one API version (D60),
110///   implemented only by the zero-variant `enum Api {}` that [`phoxal_api_tree!`]
111///   generates inside each version module; its `ID` is the module name (`"v1"`).
112///   Its `IS_PREVIEW` const is lifecycle metadata only.
113/// - [`ContractBody`] is a version-local wire body (D61): a plain serde type
114///   bound to exactly one [`ApiVersion`] and one contract topic. Every body
115///   declared inside a [`phoxal_api_tree!`] node gets a generated impl; handles,
116///   `SetupContext` builders, and the `Service`/`Driver` derive assertions key
117///   off its `Api`/`TOPIC`. `TOPIC` is version-qualified (D1) and *is* the
118///   compatibility key - there is no `SCHEMA_ID`/`FAMILY`; its serde encoding
119///   *is* the wire payload, with no version envelope (D62).
120pub use phoxal_bus::{ApiVersion, ContractBody};
121
122phoxal_api_tree! {
123    version v1 {
124        drive {
125            /// Why actuation authority is in its current state.
126            enum StopReason {
127                NoTarget,
128                TargetStale,
129                TargetFromFuture,
130                TargetNotFinite,
131                ActuatorCommandNotFinite,
132                Inactive,
133                EmergencyStop,
134                Fault,
135            }
136
137            /// Whether the drive is actively commanding the actuators.
138            enum ActuatorAuthority {
139                Active,
140                Stopped,
141            }
142
143            /// A requested or limited planar velocity.
144            struct Target {
145                linear_x_mps: f32,
146                angular_z_radps: f32,
147                curvature_limit_radpm: Option<f32>,
148            }
149
150            /// The drive participant's published control state.
151            struct State {
152                target: Target,
153                limited_target: Target,
154                actuator_authority: ActuatorAuthority,
155                stop_reason: Option<StopReason>,
156                target_age_ns: Option<u64>,
157            }
158
159            topic target: command Target;
160            topic state: state State;
161        }
162
163        joint(joint) {
164            /// Per-joint position/velocity (and optional effort) on a dynamic
165            /// per-joint key.
166            struct JointState {
167                position_rad: f64,
168                velocity_radps: f64,
169                effort_nm: Option<f64>,
170            }
171
172            topic state: state JointState;
173        }
174
175        frame {
176            /// A parent → child rigid transform (translation + xyzw quaternion).
177            struct FrameTransform {
178                parent_frame_id: String,
179                child_frame_id: String,
180                translation_m: [f64; 3],
181                rotation_quat_xyzw: [f64; 4],
182                stamp_ns: Option<u64>,
183            }
184
185            /// Transforms that do not change over time.
186            struct StaticTransforms {
187                transforms: Vec<FrameTransform>,
188            }
189
190            /// The current transform tree.
191            struct Tree {
192                transforms: Vec<FrameTransform>,
193            }
194
195            /// Ask for the transform between two frames, optionally at a time.
196            struct LookupRequest {
197                target_frame_id: String,
198                source_frame_id: String,
199                at_ns: Option<u64>,
200            }
201
202            /// The resolved transform, or `None` if it is not available.
203            struct LookupResponse {
204                transform: Option<FrameTransform>,
205            }
206
207            topic tree: state Tree;
208            topic static_transforms: state StaticTransforms;
209            topic lookup: query LookupRequest => LookupResponse;
210        }
211
212        power {
213            /// A platform power command.
214            #[derive(Copy, Eq)]
215            enum Command {
216                Reboot,
217                Shutdown,
218            }
219
220            /// Where the power participant is in handling a command.
221            #[derive(Copy, Eq)]
222            enum Status {
223                Idle,
224                Rebooting,
225                ShuttingDown,
226                Failed,
227            }
228
229            /// Why a power command was rejected outright.
230            #[derive(Copy, Eq)]
231            #[serde(rename_all = "snake_case")]
232            enum RejectedReason {
233                HostIntegrationUnavailable,
234                CommandRejected,
235            }
236
237            /// Why an accepted power command later failed.
238            #[derive(Copy, Eq)]
239            #[serde(rename_all = "snake_case")]
240            enum FailedReason {
241                HostCommandFailed,
242            }
243
244            /// The power participant's published state.
245            struct State {
246                status: Status,
247                detail: Option<String>,
248            }
249
250            topic command: command Command;
251            topic state: state State;
252        }
253
254        motion {
255            struct Target {
256                linear_x_mps: f32,
257                angular_z_radps: f32,
258                curvature_limit_radpm: Option<f32>,
259            }
260
261            #[derive(Copy, Eq)]
262            #[serde(rename_all = "snake_case")]
263            enum Source {
264                Manual,
265                Navigation,
266                EmergencyStop,
267            }
268
269            #[derive(Copy, Eq)]
270            #[serde(rename_all = "snake_case")]
271            enum ZeroReason {
272                NoCandidate,
273                ManualCandidateStale,
274                NavigationCandidateStale,
275                ManualCandidateFromFuture,
276                NavigationCandidateFromFuture,
277                ManualCandidateNotFinite,
278                NavigationCandidateNotFinite,
279                EmergencyStopEngaged,
280                SafetyConstraintsUnavailable,
281                SafetyProtectiveStop,
282            }
283
284            #[derive(Copy, Eq)]
285            #[serde(rename_all = "snake_case")]
286            enum SafetyRuntime {
287                Absent,
288                Present,
289            }
290
291            struct ManualCommand {
292                linear_x_mps: f64,
293                angular_z_radps: f64,
294            }
295
296            #[derive(Eq)]
297            struct EmergencyStopRequest {
298                engaged: bool,
299            }
300
301            struct State {
302                manual_candidate_age_ns: Option<u64>,
303                autonomous_candidate_age_ns: Option<u64>,
304                safety_constraints_age_ns: Option<u64>,
305                selected_source: Option<Source>,
306                final_target: Target,
307                zero_reason: Option<ZeroReason>,
308                safety_runtime: SafetyRuntime,
309                software_estop_engaged: bool,
310                component_estop_blocked: bool,
311                active_safety_constraints: Vec<super::safety::Constraint>,
312            }
313
314            topic manual: command ManualCommand;
315            topic estop: command EmergencyStopRequest;
316            topic state: state State;
317        }
318
319        safety {
320            /// Why safety is stopping or limiting body motion.
321            #[derive(Copy, Eq)]
322            #[serde(rename_all = "snake_case")]
323            enum ConstraintReason {
324                WorldUnavailable,
325                MapUnavailable,
326                DrivableSpaceUnavailable,
327                LocalizationUnavailable,
328                LocalizationUncertain,
329                ObstacleProximity,
330                RangeSensorFault,
331                DriveFault,
332                BatteryLow,
333                BatteryCritical,
334                SpeedZone,
335                OperatorPolicy,
336            }
337
338            /// Typed origin of one constraint, suitable for operator diagnosis.
339            #[derive(Copy, Eq)]
340            #[serde(rename_all = "snake_case")]
341            enum ConstraintSourceKind {
342                WorldModel,
343                Map,
344                Localization,
345                Range,
346                Drive,
347                Battery,
348                Operator,
349            }
350
351            struct ConstraintSource {
352                kind: ConstraintSourceKind,
353                participant_id: String,
354                component_id: Option<String>,
355                capability_id: Option<String>,
356            }
357
358            struct Constraint {
359                reason: ConstraintReason,
360                source: ConstraintSource,
361                stop: bool,
362                max_linear_speed_mps: Option<f32>,
363                max_angular_speed_radps: Option<f32>,
364                observed_value: Option<f32>,
365                valid_from_ns: u64,
366                expires_at_ns: u64,
367            }
368
369            /// The sole safety-to-motion control product. Motion accepts it only
370            /// in the same epoch and before `expires_at_ns`.
371            struct MotionConstraints {
372                sequence: u64,
373                stop: bool,
374                max_linear_speed_mps: Option<f32>,
375                max_angular_speed_radps: Option<f32>,
376                constraints: Vec<Constraint>,
377                expires_at_ns: u64,
378            }
379
380            /// Operator-facing state mirrors the exact product consumed by motion.
381            struct State {
382                clear: bool,
383                motion: MotionConstraints,
384            }
385
386            topic constraints: state MotionConstraints;
387            topic state: state State;
388        }
389
390        navigation {
391            #[derive(Eq)]
392            struct RequestId {
393                value: String,
394            }
395
396            struct Pose {
397                x_m: f64,
398                y_m: f64,
399                yaw_rad: Option<f64>,
400            }
401
402            struct Path {
403                poses: Vec<Pose>,
404                map_revision: Option<u64>,
405            }
406
407            enum RequestKind {
408                GotoPose(Pose),
409                FollowPath(Path),
410                Cancel(RequestId),
411            }
412
413            struct Request {
414                request_id: RequestId,
415                kind: RequestKind,
416            }
417
418            enum State {
419                Idle,
420                Accepted(RequestId),
421                Running(RequestId),
422            }
423
424            #[derive(Copy, Eq)]
425            #[serde(rename_all = "snake_case")]
426            enum FailureReason {
427                LocalizationUnavailable,
428                MapUnavailable,
429                MapChanged,
430                NoPath,
431                Blocked,
432                Internal,
433            }
434
435            #[derive(Copy, Eq)]
436            #[serde(rename_all = "snake_case")]
437            enum RefusalReason {
438                Busy,
439                InvalidRequest,
440                Unsupported,
441            }
442
443            enum Outcome {
444                Succeeded,
445                Failed(FailureReason),
446                Refused(RefusalReason),
447                Cancelled,
448                TimedOut,
449            }
450
451            struct Progress {
452                request_id: RequestId,
453                distance_remaining_m: f64,
454                path_index: u32,
455            }
456
457            struct Result {
458                request_id: RequestId,
459                outcome: Outcome,
460            }
461
462            struct Candidate {
463                request_id: RequestId,
464                linear_x_mps: f32,
465                angular_z_radps: f32,
466            }
467
468            struct FrontierRequest {
469                map_revision: Option<u64>,
470            }
471
472            struct Frontier {
473                x_m: f64,
474                y_m: f64,
475                score: f32,
476                size: u32,
477            }
478
479            struct FrontierResponse {
480                frontier: Option<Frontier>,
481                map_revision: Option<u64>,
482            }
483
484            topic request: command Request;
485            topic state: state State;
486            topic progress: state Progress;
487            topic result: state Result;
488            topic candidate: state Candidate;
489            topic next_frontier: query FrontierRequest => FrontierResponse;
490        }
491
492        behavior {
493            #[derive(Eq)]
494            struct RequestId {
495                value: String,
496            }
497
498            #[derive(Copy, Eq)]
499            #[serde(rename_all = "snake_case")]
500            enum ConflictPolicy {
501                Reject,
502                Queue,
503                Interrupt,
504            }
505
506            enum Value {
507                Bool(bool),
508                Integer(i64),
509                Number(f64),
510                String(String),
511                Pose(super::navigation::Pose),
512            }
513
514            struct Request {
515                request_id: RequestId,
516                behavior_id: String,
517                args: ::std::collections::BTreeMap<String, Value>,
518                priority: u8,
519                conflict_policy: ConflictPolicy,
520            }
521
522            enum Command {
523                Pause,
524                Resume,
525                Cancel,
526            }
527
528            #[derive(Copy, Eq)]
529            #[serde(rename_all = "snake_case")]
530            enum ExecutionStatus {
531                Idle,
532                Running,
533                Paused,
534                Succeeded,
535                Failed,
536                Cancelled,
537                Abandoned,
538            }
539
540            #[derive(Copy, Eq)]
541            #[serde(rename_all = "snake_case")]
542            enum NodeStatus {
543                Idle,
544                Running,
545                Succeeded,
546                Failed,
547                Skipped,
548                Waiting,
549                Cancelling,
550            }
551
552            #[derive(Copy, Eq)]
553            #[serde(rename_all = "snake_case")]
554            enum FailureReason {
555                MissingCapability,
556                ActionRefused,
557                ActionFailed,
558                ActionTimedOut,
559                ActionCancelled,
560                ConditionFailed,
561                SafetyStopped,
562                EmergencyStopped,
563                ResourceConflict,
564                InvalidArgument,
565                InvalidBlackboardValue,
566                SubtreeFailed,
567                ExecutionAbandoned,
568                InternalError,
569            }
570
571            struct Failure {
572                reason: FailureReason,
573                detail: Option<String>,
574                node_path: Option<String>,
575                action_id: Option<String>,
576            }
577
578            struct DefinitionRef {
579                id: String,
580                version: String,
581                content_hash: String,
582            }
583
584            struct State {
585                execution_id: Option<String>,
586                root_behavior_id: Option<String>,
587                active_request_id: Option<RequestId>,
588                active_behavior_id: Option<String>,
589                status: ExecutionStatus,
590                active_node_path: Option<String>,
591                failure: Option<Failure>,
592            }
593
594            struct Snapshot {
595                execution_id: Option<String>,
596                root: Option<DefinitionRef>,
597                definition_stack: Vec<DefinitionRef>,
598                active_request_id: Option<RequestId>,
599                active_behavior_id: Option<String>,
600                status: ExecutionStatus,
601                node_statuses: ::std::collections::BTreeMap<String, NodeStatus>,
602                active_node_path: Option<String>,
603                blackboard: ::std::collections::BTreeMap<String, Value>,
604                args: ::std::collections::BTreeMap<String, Value>,
605                started_at_ns: Option<u64>,
606                updated_at_ns: u64,
607                failure: Option<Failure>,
608            }
609
610            enum EventKind {
611                ExecutionStarted,
612                ExecutionPaused,
613                ExecutionResumed,
614                ExecutionCompleted,
615                ExecutionCancelled,
616                ExecutionAbandoned,
617                NodeTransition(NodeStatus),
618                RequestAccepted,
619                RequestCompleted(ExecutionStatus),
620                RequestRejected(FailureReason),
621            }
622
623            struct Event {
624                sequence: u64,
625                execution_id: Option<String>,
626                request_id: Option<RequestId>,
627                behavior_id: Option<String>,
628                content_hash: Option<String>,
629                node_path: Option<String>,
630                kind: EventKind,
631                failure: Option<Failure>,
632                participant_id: String,
633                logical_time_ns: u64,
634            }
635
636            topic command: command Command;
637            topic request: command Request;
638            topic state: state State;
639            topic snapshot: state Snapshot;
640            topic event: state Event;
641        }
642
643        logs(participant_id) {
644            /// Wall-clock timestamp carried by a structured bus log event.
645            struct Timestamp {
646                unix_seconds: i64,
647                nanos: u32,
648            }
649
650            /// The severity level of a structured bus log event.
651            #[derive(Copy, Eq)]
652            #[serde(rename_all = "snake_case")]
653            enum Level {
654                Error,
655                Warn,
656                Info,
657                Debug,
658                Trace,
659            }
660
661            /// A scalar tracing field value captured from a log event.
662            #[serde(untagged)]
663            enum LogValue {
664                Bool(bool),
665                I64(i64),
666                U64(u64),
667                F64(f64),
668                String(String),
669            }
670
671            /// One structured runner log event published out-of-band.
672            struct Event {
673                seq: u64,
674                time: Timestamp,
675                level: Level,
676                target: String,
677                message: String,
678                fields: ::std::collections::BTreeMap<String, LogValue>,
679                dropped: u32,
680            }
681
682            topic self: state Event;
683        }
684
685        bus {
686            uplink {
687                /// Observable state of the router's optional upstream connection.
688                #[derive(Copy, Eq)]
689                #[serde(rename_all = "snake_case")]
690                enum UplinkPhase {
691                    Disabled,
692                    Connecting,
693                    Connected,
694                    Retrying,
695                }
696
697                /// Router-owned out-of-band state for the optional site uplink.
698                struct State {
699                    phase: UplinkPhase,
700                    connect: Option<String>,
701                    retry_attempt: u32,
702                    detail: Option<String>,
703                }
704
705                topic state: state State;
706            }
707        }
708
709
710
711
712        perception {
713            /// A single detected object: class, confidence, and pose in a frame.
714            struct Detection {
715                class_id: String,
716                confidence: f32,
717                position_m: [f64; 3],
718                frame_id: String,
719                track_id: Option<u64>,
720            }
721
722            /// A batch of detections from one perception cycle.
723            struct Detections {
724                detections: Vec<Detection>,
725                stamp_ns: Option<u64>,
726            }
727
728            /// The perception participant's published health.
729            struct State {
730                healthy: bool,
731                detector: String,
732            }
733
734            topic detections: state Detections;
735            topic state: state State;
736        }
737
738        video {
739            /// Ask to open a video stream for a capability at an optional size.
740            struct OpenRequest {
741                capability: String,
742                width_px: Option<u32>,
743                height_px: Option<u32>,
744            }
745
746            /// The id of the stream that was opened.
747            struct OpenResponse {
748                stream_id: String,
749            }
750
751            topic open: query OpenRequest => OpenResponse;
752
753            stream(stream) {
754                /// Where one open video stream is in its lifecycle.
755                #[derive(Copy, Eq)]
756                #[serde(rename_all = "snake_case")]
757                enum StreamPhase {
758                    Starting,
759                    Active,
760                    Stopped,
761                }
762
763                /// The published state of one video stream: its lifecycle phase
764                /// and the number of source frames seen so far. The video participant
765                /// publishes it per stream; clients subscribe, hence `state`.
766                struct StreamState {
767                    phase: StreamPhase,
768                    frames_seen: u64,
769                }
770
771                topic state: state StreamState;
772            }
773        }
774
775        simulation {
776            /// The simulator clock: current time and whether it is advancing.
777            struct Clock {
778                now_ns: u64,
779                running: bool,
780            }
781
782            /// A command to the simulator's run loop.
783            #[derive(Copy, Eq)]
784            enum Control {
785                Pause,
786                Resume,
787                Reset,
788            }
789
790            /// The simulated robot's ground-truth planar pose.
791            struct RobotPose {
792                x_m: f64,
793                y_m: f64,
794                yaw_rad: f64,
795            }
796
797            /// Whether the simulated robot is in contact, with optional detail.
798            struct Contact {
799                in_contact: bool,
800                detail: Option<String>,
801            }
802
803            topic clock: state Clock;
804            topic control: command Control;
805            topic robot_pose: state RobotPose;
806            topic contact: state Contact;
807        }
808
809        // Per-instance component capabilities (D17/D38: framework participant / driver
810        // territory). `component(instance)` selects a manifest-declared component;
811        // each child `kind(capability)` is a self-contained node whose key is
812        // `component/{instance}/<kind>/{capability}/<leaf>`. Nodes duplicate any
813        // types they share by design - the node path disambiguates, so the names
814        // are path-local.
815        component(instance) {
816            motor(capability) {
817                /// A per-actuator command.
818                enum Command {
819                    Velocity(f32),
820                    Torque(f32),
821                    Stop,
822                }
823
824                topic command: command Command;
825            }
826
827            encoder(capability) {
828                /// Per-encoder sample on a dynamic per-instance key.
829                struct Sample {
830                    position_rad: f64,
831                    velocity_radps: f32,
832                }
833
834                topic sample: state Sample;
835            }
836
837            accelerometer(capability) {
838                /// Raw accelerometer sample in the sensor-local frame in m/s^2.
839                struct Sample {
840                    linear_acceleration: [f32; 3],
841                }
842
843                topic sample: state Sample;
844            }
845
846            gyroscope(capability) {
847                /// Raw angular velocity sample in the sensor-local frame in rad/s.
848                struct Sample {
849                    angular_velocity: [f32; 3],
850                }
851
852                topic sample: state Sample;
853            }
854
855            magnetometer(capability) {
856                /// Raw magnetic-field sample in the sensor-local frame.
857                struct Sample {
858                    magnetic_field: [f32; 3],
859                }
860
861                topic sample: state Sample;
862            }
863
864            imu(capability) {
865                #[derive(Copy, Eq)]
866                #[serde(rename_all = "snake_case")]
867                enum SensorHealth {
868                    Nominal,
869                    Degraded,
870                    Fault,
871                }
872
873                #[derive(Copy)]
874                struct Bias {
875                    angular_velocity_radps: [f32; 3],
876                    linear_acceleration_mps2: [f32; 3],
877                }
878
879                struct Sample {
880                    orientation: Option<[f32; 4]>,
881                    angular_velocity_radps: [f32; 3],
882                    linear_acceleration_mps2: [f32; 3],
883                    covariance: Option<[f32; 9]>,
884                    noise_density: Option<[f32; 3]>,
885                    sensor_frame_id: Option<String>,
886                    measured_at_ns: Option<u64>,
887                    health: SensorHealth,
888                    bias: Option<Bias>,
889                }
890
891                topic sample: state Sample;
892            }
893
894            range(capability) {
895                #[derive(Copy, Eq)]
896                #[serde(rename_all = "snake_case")]
897                enum SensorHealth {
898                    Nominal,
899                    Degraded,
900                    Fault,
901                }
902
903                #[derive(Copy)]
904                struct Limits {
905                    min_m: f32,
906                    max_m: f32,
907                }
908
909                #[derive(Copy)]
910                struct SampleQuality {
911                    valid: bool,
912                    confidence: Option<f32>,
913                }
914
915                struct Sample {
916                    distance_m: f32,
917                    limits: Option<Limits>,
918                    measured_at_ns: Option<u64>,
919                    quality: Option<SampleQuality>,
920                    health: SensorHealth,
921                }
922
923                topic sample: state Sample;
924            }
925
926            gnss(capability) {
927                /// A GNSS fix: geodetic position plus a 3x3 position covariance.
928                struct Sample {
929                    latitude: f64,
930                    longitude: f64,
931                    altitude: f64,
932                    position_covariance: [f64; 9],
933                }
934
935                topic sample: state Sample;
936            }
937
938            camera(capability) {
939                #[derive(Copy, Eq)]
940                #[serde(rename_all = "snake_case")]
941                enum Encoding {
942                    Jpeg,
943                    Png,
944                    L8,
945                    Rgb8,
946                    Rgba8,
947                }
948
949                #[derive(Copy)]
950                struct Intrinsics {
951                    fx: f32,
952                    fy: f32,
953                    cx: f32,
954                    cy: f32,
955                }
956
957                struct Distortion {
958                    model: String,
959                    coefficients: Vec<f32>,
960                }
961
962                #[derive(Copy)]
963                struct ExposureTiming {
964                    exposure_start_ns: Option<u64>,
965                    exposure_duration_ns: Option<u64>,
966                }
967
968                struct CalibrationIdentity {
969                    id: String,
970                    version: String,
971                }
972
973                /// One camera frame: encoded pixel bytes plus optional calibration
974                /// and timing metadata.
975                struct Frame {
976                    width: u32,
977                    height: u32,
978                    encoding: Encoding,
979                    intrinsics: Option<Intrinsics>,
980                    distortion: Option<Distortion>,
981                    exposure: Option<ExposureTiming>,
982                    measured_at_ns: Option<u64>,
983                    calibration: Option<CalibrationIdentity>,
984                    #[serde(with = "serde_bytes")]
985                    data: Vec<u8>,
986                }
987
988                topic frame: state Frame;
989            }
990
991            depth(capability) {
992                #[derive(Copy, Eq)]
993                #[serde(rename_all = "snake_case")]
994                enum Encoding {
995                    U16Millimeters,
996                }
997
998                #[derive(Copy, Eq)]
999                #[serde(rename_all = "snake_case")]
1000                enum InvalidSamplePolicy {
1001                    ZeroIsInvalid,
1002                    NonFiniteIsInvalid,
1003                }
1004
1005                #[derive(Copy)]
1006                struct Intrinsics {
1007                    fx: f32,
1008                    fy: f32,
1009                    cx: f32,
1010                    cy: f32,
1011                }
1012
1013                struct Distortion {
1014                    model: String,
1015                    coefficients: Vec<f32>,
1016                }
1017
1018                #[derive(Copy)]
1019                struct ExposureTiming {
1020                    exposure_start_ns: Option<u64>,
1021                    exposure_duration_ns: Option<u64>,
1022                }
1023
1024                struct CalibrationIdentity {
1025                    id: String,
1026                    version: String,
1027                }
1028
1029                /// One depth frame: per-pixel millimetre samples plus optional
1030                /// calibration and timing metadata.
1031                struct Frame {
1032                    samples_mm: Vec<u16>,
1033                    encoding: Encoding,
1034                    invalid_sample_policy: InvalidSamplePolicy,
1035                    width: Option<u32>,
1036                    height: Option<u32>,
1037                    intrinsics: Option<Intrinsics>,
1038                    distortion: Option<Distortion>,
1039                    exposure: Option<ExposureTiming>,
1040                    measured_at_ns: Option<u64>,
1041                    calibration: Option<CalibrationIdentity>,
1042                }
1043
1044                topic frame: state Frame;
1045            }
1046
1047            lidar(capability) {
1048                #[derive(Copy, Eq)]
1049                #[serde(rename_all = "snake_case")]
1050                enum SensorHealth {
1051                    Nominal,
1052                    Degraded,
1053                    Fault,
1054                }
1055
1056                #[derive(Copy)]
1057                struct ScanGeometry {
1058                    angle_min_rad: f32,
1059                    angle_increment_rad: f32,
1060                }
1061
1062                #[derive(Copy)]
1063                struct RangeLimits {
1064                    min_m: f32,
1065                    max_m: f32,
1066                }
1067
1068                #[derive(Copy)]
1069                struct ScanQuality {
1070                    valid_points: u32,
1071                }
1072
1073                struct Ranges {
1074                    ranges: Vec<f32>,
1075                    geometry: Option<ScanGeometry>,
1076                    limits: Option<RangeLimits>,
1077                    measured_at_ns: Option<u64>,
1078                    quality: Option<ScanQuality>,
1079                    health: SensorHealth,
1080                }
1081
1082                struct Points {
1083                    points: Vec<[f32; 3]>,
1084                    limits: Option<RangeLimits>,
1085                    measured_at_ns: Option<u64>,
1086                    quality: Option<ScanQuality>,
1087                    health: SensorHealth,
1088                }
1089
1090                /// One lidar scan, either as polar ranges or as cartesian points.
1091                #[serde(tag = "kind", rename_all = "snake_case")]
1092                enum Scan {
1093                    Ranges(Ranges),
1094                    Points(Points),
1095                }
1096
1097                topic scan: state Scan;
1098            }
1099
1100            mmwave(capability) {
1101                /// One mmWave radar detection: position, velocity, and SNR.
1102                #[derive(Copy)]
1103                struct Detection {
1104                    position: [f32; 3],
1105                    velocity: [f32; 3],
1106                    snr: f32,
1107                }
1108
1109                /// One mmWave radar scan as a set of detections.
1110                struct Scan {
1111                    detections: Vec<Detection>,
1112                }
1113
1114                topic scan: state Scan;
1115            }
1116
1117            microphone(capability) {
1118                /// One audio frame as raw encoded bytes.
1119                struct Frame {
1120                    data: Vec<u8>,
1121                }
1122
1123                topic frame: state Frame;
1124            }
1125
1126            led(capability) {
1127                /// A per-LED on/off command.
1128                #[derive(Copy, Eq)]
1129                enum Command {
1130                    On,
1131                    Off,
1132                }
1133
1134                topic command: command Command;
1135            }
1136
1137            emergency_stop(capability) {
1138                /// Per-instance emergency-stop state.
1139                #[derive(Eq)]
1140                struct State {
1141                    engaged: bool,
1142                }
1143
1144                topic state: state State;
1145            }
1146        }
1147
1148        odometry {
1149            /// A planar pose + twist estimate in the odometry frame.
1150            struct State {
1151                x_m: f64,
1152                y_m: f64,
1153                yaw_rad: f64,
1154                linear_x_mps: f32,
1155                angular_z_radps: f32,
1156            }
1157
1158            topic state: state State;
1159        }
1160
1161        localize {
1162            /// A planar localization estimate in the map frame.
1163            struct LocalizationState {
1164                x_m: f64,
1165                y_m: f64,
1166                yaw_rad: f64,
1167                confidence: f32,
1168            }
1169
1170            topic state: state LocalizationState;
1171        }
1172
1173        presence {
1174            /// Per-participant liveness + readiness beacon.
1175            enum Readiness {
1176                NotStarted,
1177                Initializing,
1178                Ready,
1179                Degraded,
1180                Failed,
1181            }
1182
1183            /// A single participant's liveness beacon. Participants publish their
1184            /// own heartbeat; the presence participant subscribes them as its control
1185            /// input, hence the `command` role.
1186            struct Heartbeat {
1187                participant: String,
1188                readiness: Readiness,
1189            }
1190
1191            /// The presence participant's aggregate readiness across all participants.
1192            /// Presence publishes it; clients subscribe, hence the `state` role.
1193            struct State {
1194                readiness: Readiness,
1195            }
1196
1197            topic heartbeat: command Heartbeat;
1198            topic state: state State;
1199        }
1200
1201        map {
1202            /// A published map revision marker.
1203            struct Revision {
1204                revision: u64,
1205                resolution_m: f32,
1206            }
1207
1208            /// Request a rectangular submap window (map-frame metres).
1209            struct SubmapRequest {
1210                min_x_m: f64,
1211                min_y_m: f64,
1212                max_x_m: f64,
1213                max_y_m: f64,
1214            }
1215
1216            /// An occupancy-grid window: row-major cells, 0..=100 + 255 = unknown.
1217            struct SubmapResponse {
1218                width: u32,
1219                height: u32,
1220                resolution_m: f32,
1221                cells: Vec<u8>,
1222            }
1223
1224            topic revision: state Revision;
1225            topic submap: query SubmapRequest => SubmapResponse;
1226        }
1227
1228        asset {
1229            /// Fetch a stored asset by path.
1230            struct GetRequest {
1231                path: String,
1232            }
1233
1234            /// The asset bytes, a not-found marker, or a rejected path.
1235            enum GetResponse {
1236                Found { bytes: Vec<u8> },
1237                Missing,
1238                InvalidPath,
1239            }
1240
1241            topic get: query GetRequest => GetResponse;
1242        }
1243    }
1244
1245    // v2 is the one evolving preview surface. New and changed contracts are
1246    // edited here until the complete version is ready to freeze; preview work
1247    // does not mint another public API namespace for each implementation batch.
1248    preview version v2 {
1249        battery {
1250            /// Battery state remains preview while hardware ownership evolves.
1251            struct State {
1252                voltage_v: f32,
1253                current_a: f32,
1254                charge_ratio: f32,
1255            }
1256
1257            topic state: state State;
1258        }
1259
1260        simulation {
1261            /// One robot node that the simulator spawn authority should import.
1262            struct RobotSpawn {
1263                robot_id: String,
1264                node_string: String,
1265            }
1266
1267            /// Requests the current complete robot spawn set.
1268            ///
1269            /// `known_revision` lets a future responder distinguish initial
1270            /// bootstrap from refreshes after a runtime join. Responders may
1271            /// still return the current set when the revision is unchanged.
1272            struct SpawnRequest {
1273                known_revision: Option<u64>,
1274            }
1275
1276            /// The complete robot spawn set for one simulation world.
1277            struct SpawnSet {
1278                revision: u64,
1279                robots: Vec<RobotSpawn>,
1280            }
1281
1282            /// The authoritative advancing simulation clock. Publication means
1283            /// the world advanced; silence means it did not.
1284            struct Clock {
1285                now_ns: u64,
1286                step: u64,
1287            }
1288
1289            topic spawn: query SpawnRequest => SpawnSet;
1290            topic clock: state Clock;
1291        }
1292
1293        router {
1294            /// One topic's measured ingress over the sample window.
1295            struct TopicMetric {
1296                topic: String,
1297                from_participant: String,
1298                ingress_rate_hz: f32,
1299                count: u64,
1300            }
1301
1302            /// The router's measured message-flow snapshot. `window_ns` is the
1303            /// measurement interval LENGTH (not a timestamp; production time is
1304            /// the envelope `publish_at`, per the guide's logical-time
1305            /// discipline).
1306            struct Metrics {
1307                topics: Vec<TopicMetric>,
1308                throughput_msg_s: f32,
1309                window_ns: u64,
1310            }
1311
1312            topic metrics: state Metrics;
1313        }
1314
1315        telemetry {
1316            /// Host OS resource sample (published by the new tool-telemetry).
1317            struct Host {
1318                cpu_pct: f32,
1319                ram_used_bytes: u64,
1320                ram_total_bytes: u64,
1321                load_1m: f32,
1322                window_ns: u64,
1323            }
1324
1325            /// One participant's OWN process resource sample (published by the
1326            /// runner off the heartbeat loop). Subscriber demuxes by envelope
1327            /// source, like `presence::Heartbeat`.
1328            struct Process {
1329                cpu_pct: f32,
1330                rss_bytes: u64,
1331                window_ns: u64,
1332            }
1333
1334            topic host: state Host;
1335            topic process: state Process;
1336        }
1337
1338        joypad {
1339            /// One gamepad the tool can see. `id` is a STABLE wire id the tool
1340            /// assigns (name/guid-derived) - NOT a process-local gilrs id.
1341            struct Device {
1342                id: String,
1343                name: String,
1344                connected: bool,
1345            }
1346
1347            /// The joypad tool's published device state.
1348            struct Devices {
1349                available: Vec<Device>,
1350                selected: Option<String>,
1351                last_error: Option<String>,
1352            }
1353
1354            /// Client asks the tool to select/connect a device by its stable id.
1355            struct Connect {
1356                id: String,
1357            }
1358
1359            /// Client asks the tool to re-enumerate devices.
1360            struct Rescan {}
1361
1362            topic devices: state Devices;
1363            topic connect: command Connect;
1364            topic rescan: command Rescan;
1365        }
1366    }
1367}
1368
1369#[cfg(test)]
1370mod tests;