diff --git a/pkgs/id/crates/id-core/src/world_caps.rs b/pkgs/id/crates/id-core/src/world_caps.rs index 05112b4f55..dcaeb9daf1 100644 --- a/pkgs/id/crates/id-core/src/world_caps.rs +++ b/pkgs/id/crates/id-core/src/world_caps.rs @@ -15,6 +15,22 @@ //! {"id":"r2","cap":"chat.say","args":{"text":"hello"}}]} //! ``` //! +//! Asking what device the program is rendering on is the same shape — +//! `device.info` (#2338) is a one-shot request whose result is the +//! device capability manifest (taxonomy doc 2026-10-29, §3.1): +//! +//! ```json +//! {"v":1, +//! "requests":[{"id":"d1","cap":"device.info"}]} +//! ``` +//! +//! The server answers with the manifest as the result value: +//! `{"manifest":{"v":1},"display":{...},"input":{...},"sensors":{...},"audio":{...},"network":{...}}`. +//! A program may name the manifest version it understands +//! (`{"id":"d1","cap":"device.info","args":{"v":1}}`); an unsupported +//! version is refused with `bad_args`, never silently interpreted. A +//! host that cannot describe its device refuses with `unknown_cap`. +//! //! The server answers each new request with //! `{"cap":"result","id":"r1","ok":true,"value":...}` (or `"ok":false` with an //! `"error"`), and each subscription with its own events @@ -336,6 +352,14 @@ const LOC_POSITION_ARGUMENTS: &[ProviderArgument] = &[ProviderArgument { value_type: ArgumentType::UnsignedInteger, required: false, }]; +/// Argument schema for `device.info`: an optional manifest version +/// the program understands. An unsupported version is refused rather +/// than silently interpreted (#2338). +const DEVICE_INFO_ARGUMENTS: &[ProviderArgument] = &[ProviderArgument { + name: "v", + value_type: ArgumentType::UnsignedInteger, + required: false, +}]; /// Bounds for `loc.position`: the argument byte cap. const LOC_POSITION_BOUNDS: &[ProviderBound] = &[ProviderBound::ArgsBytes(MAX_ARGS_BYTES)]; /// Bounds for `loc.watch`: the concurrent-watch cap. The interval @@ -432,6 +456,14 @@ define_provider_registry! { required_scope: RequiredScope::Join, default_ceiling: DefaultCeiling::Included, }, + "device.info" => { + version: 1, + kind: ProviderKind::Request, + argument_schema: ArgumentSchema::JsonObject(DEVICE_INFO_ARGUMENTS), + bounds: COMMON_REQUEST_BOUNDS, + required_scope: RequiredScope::Join, + default_ceiling: DefaultCeiling::Included, + }, // Sensor caps (#2341): excluded from default ceilings, so a world // reaches them only through an explicit ceiling entry and an // explicit grant, and each use passes the consent seam. @@ -1153,6 +1185,126 @@ impl LocationReading { } } +/// The manifest version this host speaks for `device.info` (#2338). +/// A manifest — or a request — naming any other version is refused, +/// never silently interpreted. +pub const DEVICE_MANIFEST_VERSION: u64 = 1; + +/// One device's capability manifest (#2338): the typed shape every +/// `device.info` result carries, in the v1 form the capability +/// taxonomy (2026-10-29, §3.1) specifies. The five sections are opaque +/// JSON objects on purpose: display kinds, sensor sets and transports +/// vary per device family, and the wire contract is the section +/// presence plus the version, not an enumeration of affordances. +/// +/// The manifest is per-device, not per-program: the adapter boundary +/// enumerates the device once and caches the manifest, and the world +/// actor serves that cached copy to whoever asks (taxonomy §8 open +/// question 4). Enumeration never happens per request. +#[derive(Clone, Debug, PartialEq)] +pub struct DeviceManifest { + /// Display affordances object (e.g. `{"kind":"pixel","width":128}`). + pub display: serde_json::Value, + /// Input affordances object (e.g. `{"keys":8,"encoder":true}`). + pub input: serde_json::Value, + /// Sensor affordances object (e.g. `{"gnss":{"accuracy_m":5}}`). + pub sensors: serde_json::Value, + /// Audio affordances object (e.g. `{"out":"pcm","in":null}`). + pub audio: serde_json::Value, + /// Network affordances object (e.g. `{"transport":"mqtt"}`). + pub network: serde_json::Value, +} + +impl DeviceManifest { + /// The wire object: exactly + /// `{"manifest":{"v":1},"display":...,"input":...,"sensors":...,"audio":...,"network":...}`. + #[must_use] + pub fn to_json(&self) -> serde_json::Value { + serde_json::json!({ + "manifest": {"v": DEVICE_MANIFEST_VERSION}, + "display": self.display, + "input": self.input, + "sensors": self.sensors, + "audio": self.audio, + "network": self.network, + }) + } + + /// Parse and validate a manifest in wire form. The oracle is the + /// declared v1 manifest contract: `manifest.v` must equal + /// [`DEVICE_MANIFEST_VERSION`] and every section must be present + /// as a JSON object. + /// + /// # Errors + /// + /// [`CapError::bad_args`] naming the defect: an unsupported + /// manifest version, a missing section, or a section that is not + /// an object. + pub fn from_json(value: &serde_json::Value) -> Result { + let version = value + .get("manifest") + .and_then(|manifest| manifest.get("v")) + .and_then(serde_json::Value::as_u64); + match version { + Some(DEVICE_MANIFEST_VERSION) => {} + Some(_) => { + return Err(CapError::bad_args_with( + "unsupported device manifest version", + )); + } + None => { + return Err(CapError::bad_args_with( + "device manifest carries no version", + )); + } + } + let section = |name: &str| -> Result { + match value.get(name) { + Some(section) if section.is_object() => Ok(section.clone()), + Some(_) => Err(CapError::bad_args_with(format!( + "device manifest section {name} is not an object" + ))), + None => Err(CapError::bad_args_with(format!( + "device manifest is missing section {name}" + ))), + } + }; + Ok(Self { + display: section("display")?, + input: section("input")?, + sensors: section("sensors")?, + audio: section("audio")?, + network: section("network")?, + }) + } + + /// The manifest version a `device.info` request asks for: the + /// optional `v` argument, defaulting to + /// [`DEVICE_MANIFEST_VERSION`]. A program asking for a version + /// this host does not speak is refused, never silently served a + /// manifest it may misinterpret. + /// + /// # Errors + /// + /// [`CapError::bad_args`] for a non-integer or unsupported `v`. + pub fn requested_version(args: &serde_json::Value) -> Result { + let Some(version) = args.get("v") else { + return Ok(DEVICE_MANIFEST_VERSION); + }; + let Some(version) = version.as_u64() else { + return Err(CapError::bad_args_with( + "device.info v is not an unsigned integer", + )); + }; + if version != DEVICE_MANIFEST_VERSION { + return Err(CapError::bad_args_with( + "unsupported device manifest version", + )); + } + Ok(version) + } +} + /// Per-use consent for a sensor capability (#2341). Consent is a seam /// the host fills in (browser permission prompt, phone OS permission, /// device policy); the pure core only maps the state to the refusal @@ -1784,6 +1936,7 @@ mod tests { "schedule.at", "schedule.cancel", "world.info", + "device.info", "loc.position", "loc.watch", "Key", @@ -1793,9 +1946,9 @@ mod tests { "RocCap", "RocText", ], - "registry retains the catalog names and order (17 pre-#2341 names plus loc.position/loc.watch)" + "registry retains the catalog names and order (17 pre-#2341 names plus loc.position/loc.watch and device.info)" ); - assert_eq!(PROVIDER_REGISTRY.entries().len(), 19); + assert_eq!(PROVIDER_REGISTRY.entries().len(), 20); assert!( PROVIDER_REGISTRY .entries() @@ -1856,6 +2009,72 @@ mod tests { ); } + #[test] + fn device_manifest_round_trips_through_its_wire_form() { + // Oracle: the declared v1 manifest contract (taxonomy §3.1) — + // the wire object carries manifest.v plus the five sections, + // and parsing it returns the same manifest. + let manifest = DeviceManifest { + display: serde_json::json!({"kind": "pixel", "width": 128, "height": 64, "colors": 1}), + input: serde_json::json!({"keys": 8, "encoder": true, "pointer": false, "text_entry": "none"}), + sensors: serde_json::json!({"gnss": {"accuracy_m": 5}, "microphone": false, "camera": false}), + audio: serde_json::json!({"out": "pcm", "in": null}), + network: serde_json::json!({"transport": "mqtt", "rtt_class": "slow"}), + }; + let wire = manifest.to_json(); + assert_eq!(wire["manifest"]["v"], DEVICE_MANIFEST_VERSION); + for section in ["display", "input", "sensors", "audio", "network"] { + assert!(wire[section].is_object(), "section {section} present"); + } + assert_eq!(DeviceManifest::from_json(&wire).unwrap(), manifest); + } + + #[test] + fn device_manifest_refuses_unsupported_versions_and_missing_sections() { + // Oracle: the declared v1 manifest contract — an unsupported + // version is refused, never silently interpreted. + let mut wire = DeviceManifest { + display: serde_json::json!({}), + input: serde_json::json!({}), + sensors: serde_json::json!({}), + audio: serde_json::json!({}), + network: serde_json::json!({}), + } + .to_json(); + wire["manifest"]["v"] = serde_json::json!(2); + let error = DeviceManifest::from_json(&wire).unwrap_err(); + assert_eq!(error.code(), CapError::bad_args().code()); + assert!( + error + .reason() + .is_some_and(|reason| reason.contains("unsupported")), + "{error:?}" + ); + let mut missing = DeviceManifest { + display: serde_json::json!({}), + input: serde_json::json!({}), + sensors: serde_json::json!({}), + audio: serde_json::json!({}), + network: serde_json::json!({}), + } + .to_json(); + missing.as_object_mut().unwrap().remove("audio"); + assert!(DeviceManifest::from_json(&missing).is_err()); + // The request side negotiates by the same rule. + assert_eq!( + DeviceManifest::requested_version(&serde_json::json!({})).unwrap(), + DEVICE_MANIFEST_VERSION + ); + assert_eq!( + DeviceManifest::requested_version(&serde_json::json!({"v": 1})).unwrap(), + DEVICE_MANIFEST_VERSION + ); + assert!( + DeviceManifest::requested_version(&serde_json::json!({"v": 2})).is_err(), + "a request for an unsupported version is refused" + ); + } + #[test] fn test_a_newly_registered_excluded_provider_does_not_join_existing_ceilings() { // An existing world's ceiling, snapshotted before the upgrade. diff --git a/pkgs/id/src/world/actor.rs b/pkgs/id/src/world/actor.rs index 20993a46f9..c0c2782f3b 100644 --- a/pkgs/id/src/world/actor.rs +++ b/pkgs/id/src/world/actor.rs @@ -352,6 +352,12 @@ pub(crate) struct WorldActor { /// Restored schedules already overdue when the world opened. Their first /// fire is marked `late`; a cancel or fire removes the id. pub(crate) overdue_at_open: BTreeSet, + /// The hosting device's capability manifest (#2338), enumerated + /// once by the adapter boundary and cached here: `device.info` + /// serves this copy, so repeated program requests never trigger + /// device re-enumeration. `None` when the host cannot describe + /// its device — `device.info` then refuses with `unknown_cap`. + pub(crate) device_manifest: Option, /// The participant whose input is being processed. Requests the program /// makes in response are checked against that participant's scopes. pub(crate) acting: Option, @@ -876,6 +882,7 @@ impl WorldActor { "world": self.core.world_id, "sequence": self.core.sequence, })), + "device.info" => self.execute_device_info(&request.args), "chat.say" => self.execute_chat(&request.args), "chat.history" => Ok(serde_json::json!({ "lines": chat_history( @@ -895,6 +902,21 @@ impl WorldActor { } } + /// `device.info` (#2338): the hosting device's capability + /// manifest, in the v1 shape the taxonomy specifies. The manifest + /// comes from the adapter boundary's cached copy — this provider + /// never enumerates the device itself. A host that cannot + /// describe its device refuses with `unknown_cap`, and a request + /// naming a manifest version this host does not speak is refused + /// rather than silently interpreted. + fn execute_device_info(&self, args: &serde_json::Value) -> Result { + crate::world_caps::DeviceManifest::requested_version(args)?; + let Some(manifest) = &self.device_manifest else { + return Err(CapError::unknown()); + }; + Ok(manifest.to_json()) + } + fn players_list(&self) -> Vec { self.core .participants() @@ -2324,6 +2346,81 @@ mod replication_feed_tests { } } +#[cfg(test)] +mod device_info_tests { + use super::*; + use crate::world_caps::{CapError, DeviceManifest}; + + struct DeviceInfoProgram; + + impl WorldProgram for DeviceInfoProgram { + fn snapshot(&mut self) -> Result> { + Ok(Some("{}".to_owned())) + } + } + + fn granted_actor() -> WorldActor { + let mut core = WorldCore::new("lobby", WorldLimits::default()).unwrap(); + core.ledger + .set_granted(BTreeSet::from(["device.info".to_owned()])); + WorldActor::for_test(core, Box::new(DeviceInfoProgram), None) + } + + fn sample_manifest() -> DeviceManifest { + DeviceManifest { + display: serde_json::json!({"kind": "pixel", "width": 128, "height": 64, "colors": 1}), + input: serde_json::json!({"keys": 8, "encoder": true, "pointer": false, "text_entry": "none"}), + sensors: serde_json::json!({"gnss": {"accuracy_m": 5}, "microphone": false, "camera": false}), + audio: serde_json::json!({"out": "pcm", "in": null}), + network: serde_json::json!({"transport": "mqtt", "rtt_class": "slow"}), + } + } + + fn request(args: serde_json::Value) -> Request { + Request { + id: "d1".to_owned(), + cap: "device.info".to_owned(), + args, + } + } + + #[test] + fn device_info_result_round_trips_through_the_result_event() { + // Oracle: the declared v1 manifest contract (taxonomy §3.1) — + // the value delivered in the normal result event is the + // manifest the adapter boundary supplied. + let mut actor = granted_actor(); + actor.device_manifest = Some(sample_manifest()); + let outcome = actor.execute(&request(serde_json::json!({}))); + let event = crate::world_caps::result_event("d1", outcome); + let event: serde_json::Value = serde_json::from_str(&event).unwrap(); + assert_eq!(event["cap"], "result"); + assert_eq!(event["id"], "d1"); + assert_eq!(event["ok"], true); + assert_eq!(event["value"], sample_manifest().to_json()); + assert_eq!(event["value"]["manifest"]["v"], 1); + } + + #[test] + fn device_info_refuses_an_unsupported_manifest_version() { + // Oracle: the declared v1 manifest contract — a request for + // any other version is refused, never silently interpreted. + let mut actor = granted_actor(); + actor.device_manifest = Some(sample_manifest()); + let error = actor + .execute(&request(serde_json::json!({"v": 2}))) + .unwrap_err(); + assert_eq!(error.code(), CapError::bad_args().code()); + } + + #[test] + fn device_info_is_unknown_cap_when_the_host_cannot_describe_itself() { + let mut actor = granted_actor(); + let error = actor.execute(&request(serde_json::json!({}))).unwrap_err(); + assert_eq!(error.code(), CapError::unknown().code()); + } +} + #[cfg(test)] impl WorldActor { /// Assemble an actor without spawning its run loop, for tests that drive @@ -2377,6 +2474,7 @@ impl WorldActor { overdue_at_open, acting: None, acting_session: None, + device_manifest: None, auth: crate::directory_auth::DirectoryAuth::default(), metrics: WorldMetrics::default(), } diff --git a/pkgs/id/src/world/handle.rs b/pkgs/id/src/world/handle.rs index b6a145a921..9cbb21a73e 100644 --- a/pkgs/id/src/world/handle.rs +++ b/pkgs/id/src/world/handle.rs @@ -128,6 +128,7 @@ impl WorldHandle { overdue_at_open, acting: None, acting_session: None, + device_manifest: None, auth: crate::directory_auth::DirectoryAuth::default(), }; tokio::spawn(actor.run(receiver));