diff --git a/MODULE.md b/MODULE.md index 5cc663bb4..918cba155 100644 --- a/MODULE.md +++ b/MODULE.md @@ -50,6 +50,9 @@ is optional: and requested task reports. Sink mode replaces local trace/session storage and does not fall back to `trace_path`; event errors follow `trace_strict`, and report write errors return a recoverable `TRACE_SINK_FAILED` response; +- `consequence_host`: an object containing only the unique destination prepared + for the confidential `ConsequenceHost` callback. When reviewing an approved + pending action, a missing object, interface, or failed callback declines it; - `jev`: the decision model and its API key, needed by the Jev-driven and task members. `provider` picks it: Jev through `type_safe` (the default), `open_router`, or `tiny_humans_open_router`; `open_jev` (OpenJEV's diff --git a/crates/tinycomputer-bus/README.md b/crates/tinycomputer-bus/README.md index 88bf0d96f..f97a3cc78 100644 --- a/crates/tinycomputer-bus/README.md +++ b/crates/tinycomputer-bus/README.md @@ -190,3 +190,9 @@ distinguish causal re-entry from unrelated concurrent work. Event and artifact acknowledgements are bounded by the engine's operation deadline; report calls have a ten-second transport timeout. A host that does not opt in keeps the existing desktop file/session trace behavior. + +Contract 2.27 adds an opaque host context to `ContinueTask` and relays it +unchanged to `ConsequenceHost.Review`. TinyComputer does not interpret the +context or grant it authority; hosts can use it to recover trusted caller +context while reviewing an approval. Hosts that depend on this relay must +reject modules older than 2.27. diff --git a/crates/tinycomputer-bus/src/agent/agent_tests.rs b/crates/tinycomputer-bus/src/agent/agent_tests.rs index fe2e40e21..1bbbf83e4 100644 --- a/crates/tinycomputer-bus/src/agent/agent_tests.rs +++ b/crates/tinycomputer-bus/src/agent/agent_tests.rs @@ -281,18 +281,40 @@ fn waiting_and_continuing_have_forgiving_defaults() { assert_eq!(resume.id.to_string(), "t-1"); assert_eq!(resume.inputs["date of birth"], "1990-04-02"); assert_eq!(resume.approve, None); + assert_eq!(resume.host_context, None); + assert!( + serde_json::to_value(&resume) + .unwrap() + .get("host_context") + .is_none() + ); let private: ContinueTaskRequest = serde_json::from_value(json!({ "id": "t-2", + "host_context": "opaque-context", "fact_handles": { "email": {"handle": "opaque-email", "mask": "‹email›", "kind": "asked_input"} } })) .unwrap(); assert_eq!(private.fact_handles["email"].handle, "opaque-email"); + assert_eq!( + private + .host_context + .as_ref() + .map(super::HostContext::as_str), + Some("opaque-context") + ); let wire = serde_json::to_value(private).unwrap(); assert_eq!(wire["fact_handles"]["email"]["mask"], "‹email›"); assert_eq!(wire["inputs"], json!({})); + assert_eq!(wire["host_context"], "opaque-context"); +} + +#[test] +fn host_context_debug_output_hides_the_opaque_value() { + let context = super::HostContext::new("secret-capability"); + assert!(!format!("{context:?}").contains("secret-capability")); } #[test] diff --git a/crates/tinycomputer-bus/src/agent/mod.rs b/crates/tinycomputer-bus/src/agent/mod.rs index 30329d65e..ab8c2e5e2 100644 --- a/crates/tinycomputer-bus/src/agent/mod.rs +++ b/crates/tinycomputer-bus/src/agent/mod.rs @@ -52,8 +52,8 @@ mod types; pub use types::{ AgentError, AgentResponse, AwaitTaskRequest, Capabilities, ContinueTaskRequest, Example, - InputField, InputKind, LanguageModelConfiguration, LanguageModelProvider, MemberDoc, - ModelUsage, PaymentMode, PlanTaskRequest, Rescue, RescueOutcome, SecretHandle, + HostContext, InputField, InputKind, LanguageModelConfiguration, LanguageModelProvider, + MemberDoc, ModelUsage, PaymentMode, PlanTaskRequest, Rescue, RescueOutcome, SecretHandle, StartTaskRequest, StepView, SurfaceAvailability, SurfaceKind, TaskBudget, TaskConstraints, TaskId, TaskOutput, TaskPlan, TaskRef, TaskReport, TaskReportRequest, TaskStatus, TaskUsage, TaskView, diff --git a/crates/tinycomputer-bus/src/agent/types/mod.rs b/crates/tinycomputer-bus/src/agent/types/mod.rs index a3c8f70e3..bcb920f2d 100644 --- a/crates/tinycomputer-bus/src/agent/types/mod.rs +++ b/crates/tinycomputer-bus/src/agent/types/mod.rs @@ -13,7 +13,7 @@ pub use models::{LanguageModelConfiguration, LanguageModelProvider}; pub use reply::{AgentError, AgentResponse}; pub use report::{Rescue, RescueOutcome, TaskReport}; pub use request::{ - AwaitTaskRequest, ContinueTaskRequest, PaymentMode, PlanTaskRequest, SecretHandle, + AwaitTaskRequest, ContinueTaskRequest, HostContext, PaymentMode, PlanTaskRequest, SecretHandle, StartTaskRequest, SurfaceKind, TaskBudget, TaskConstraints, TaskId, TaskOutput, TaskPlan, TaskRef, TaskReportRequest, }; diff --git a/crates/tinycomputer-bus/src/agent/types/request.rs b/crates/tinycomputer-bus/src/agent/types/request.rs index 83cd9d4a8..d6e5850e8 100644 --- a/crates/tinycomputer-bus/src/agent/types/request.rs +++ b/crates/tinycomputer-bus/src/agent/types/request.rs @@ -120,6 +120,33 @@ impl std::fmt::Debug for SecretHandle { } } +/// Opaque, host-issued context carried from a task continuation to a +/// `ConsequenceHost` review. The module must relay it unchanged and never +/// treat it as authorization. Debug output deliberately hides the value. +#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(transparent)] +pub struct HostContext(String); + +impl HostContext { + /// Wraps a host-issued opaque context value. + #[must_use] + pub fn new(value: impl Into) -> Self { + Self(value.into()) + } + + /// Returns the opaque value for host-side lookup. + #[must_use] + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl std::fmt::Debug for HostContext { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("HostContext([opaque])") + } +} + /// What a finished task returns, beyond its raw records. /// /// The result is always a JSON object. `schema` is a JSON Schema it must @@ -251,6 +278,10 @@ pub struct ContinueTaskRequest { /// The decision on a `needs_approval` pause, or `true` to go past a /// non-payment `checkpoint`. pub approve: Option, + /// Opaque host-issued context for reviewing this continuation. The module + /// carries it to `ConsequenceHost` without interpreting or authorizing it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub host_context: Option, /// A free-text answer, for a pause that asked a question — or, for /// `needs_human`, `"done"` once the person has finished. pub answer: Option, diff --git a/crates/tinycomputer-bus/src/consequence_host/consequence_host_tests.rs b/crates/tinycomputer-bus/src/consequence_host/consequence_host_tests.rs index 7a341a290..520cb819c 100644 --- a/crates/tinycomputer-bus/src/consequence_host/consequence_host_tests.rs +++ b/crates/tinycomputer-bus/src/consequence_host/consequence_host_tests.rs @@ -15,14 +15,29 @@ fn the_interface_is_its_own_not_the_desktop_or_site_memory_one() { #[test] fn a_review_request_keeps_its_wire_form() { let request: ReviewActionRequest = serde_json::from_value(serde_json::json!({ - "task": "t1", "action": "pay now", "target": "Pay", "kind": "payment" + "task": "t1", "action": "pay now", "target": "Pay", "kind": "payment", + "host_context": "opaque-context" })) .unwrap(); assert_eq!(request.kind, ConsequenceKind::Payment); + assert_eq!( + request + .host_context + .as_ref() + .map(crate::agent::HostContext::as_str), + Some("opaque-context") + ); let json = serde_json::to_value(&request).unwrap(); assert_eq!(json["kind"], "payment"); + assert_eq!(json["host_context"], "opaque-context"); let irreversible = serde_json::to_value(ConsequenceKind::Irreversible).unwrap(); assert_eq!(irreversible, "irreversible"); + + let legacy: ReviewActionRequest = serde_json::from_value(serde_json::json!({ + "task": "t2", "action": "send", "target": "Send", "kind": "irreversible" + })) + .unwrap(); + assert_eq!(legacy.host_context, None); } #[test] diff --git a/crates/tinycomputer-bus/src/consequence_host/mod.rs b/crates/tinycomputer-bus/src/consequence_host/mod.rs index ec2491e80..46aa9a6ef 100644 --- a/crates/tinycomputer-bus/src/consequence_host/mod.rs +++ b/crates/tinycomputer-bus/src/consequence_host/mod.rs @@ -21,6 +21,8 @@ use serde::{Deserialize, Serialize}; +use crate::agent::HostContext; + /// The interface the host serves consequence review on. pub const INTERFACE: &str = "ai.tinyhumans.tinycomputer.ConsequenceHost"; @@ -58,6 +60,10 @@ pub struct ReviewActionRequest { pub target: String, /// What the module classified the action as. pub kind: ConsequenceKind, + /// Opaque host-issued context from the `ContinueTask` request. The module + /// relays this value unchanged and grants it no authority. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub host_context: Option, } /// The reply to `Review`. diff --git a/crates/tinycomputer-bus/src/version/mod.rs b/crates/tinycomputer-bus/src/version/mod.rs index 841c92b62..bc21fef6a 100644 --- a/crates/tinycomputer-bus/src/version/mod.rs +++ b/crates/tinycomputer-bus/src/version/mod.rs @@ -8,7 +8,7 @@ //! release workflow bumps, which tracks the shipped artifact. /// The wire contract version this crate defines. -pub const CONTRACT_VERSION: (u32, u32) = (2, 26); +pub const CONTRACT_VERSION: (u32, u32) = (2, 27); /// Returns whether a host holding [`CONTRACT_VERSION`] can bind to a module /// reporting `module`. @@ -22,7 +22,7 @@ pub const CONTRACT_VERSION: (u32, u32) = (2, 26); /// ``` /// # use tinycomputer_bus::{is_compatible, CONTRACT_VERSION}; /// assert!(is_compatible(CONTRACT_VERSION)); -/// assert!(is_compatible((2, 26))); +/// assert!(is_compatible((2, 27))); /// assert!(!is_compatible((2, 11))); /// assert!(!is_compatible((1, 8))); /// ``` diff --git a/crates/tinycomputer-bus/src/version/version_tests.rs b/crates/tinycomputer-bus/src/version/version_tests.rs index e813ad574..529e2ab7e 100644 --- a/crates/tinycomputer-bus/src/version/version_tests.rs +++ b/crates/tinycomputer-bus/src/version/version_tests.rs @@ -6,7 +6,7 @@ use super::{CONTRACT_VERSION, binds, is_compatible}; #[test] fn the_shipped_contract_version_is_pinned() { - assert_eq!(CONTRACT_VERSION, (2, 26)); + assert_eq!(CONTRACT_VERSION, (2, 27)); } #[test] @@ -16,7 +16,7 @@ fn the_contract_binds_to_itself() { #[test] fn a_newer_minor_on_the_module_side_binds() { - assert!(is_compatible((2, 26))); + assert!(is_compatible((2, 27))); assert!(is_compatible((2, 97))); // 2.24 adds same-task flow-to-planner handoff to StartTask. // 2.22 adds optional host-held secret handles to StartTask and RunFlow. @@ -42,6 +42,9 @@ fn a_newer_minor_on_the_module_side_binds() { // 2.20 adds SessionOptions identity fields. // 2.25 adds BrowserEgressHost. // 2.26 adds TraceSinkHost, so a 2.25 module lacks that callback. + // 2.27 relays opaque host context to ConsequenceHost reviews. A 2.26 + // module would drop that context, so a host requiring it cannot bind. + assert!(!is_compatible((2, 26))); assert!(!is_compatible((2, 25))); assert!(!is_compatible((2, 24))); assert!(!is_compatible((2, 23))); diff --git a/crates/tinycomputer-engine/src/task/describe.rs b/crates/tinycomputer-engine/src/task/describe.rs index 21e97c635..ea2af843d 100644 --- a/crates/tinycomputer-engine/src/task/describe.rs +++ b/crates/tinycomputer-engine/src/task/describe.rs @@ -5,8 +5,8 @@ //! The schemas here are written by hand, so each field of a request type //! must be added here when it is added to the contract, save the host's //! own settings no model is offered (a task's browser binary and profile); -//! `task_tests/describe_tests.rs` checks the `StartTask` and `PlanTask` -//! schemas name every other field their types serialize. +//! `task_tests/describe_tests.rs` checks the request schemas name their +//! model-settable fields; host-only context is deliberately omitted. use serde_json::{Value, json}; use tinycomputer_bus::agent::names::{CONFIDENTIAL, methods}; diff --git a/crates/tinycomputer-engine/src/task/task_tests/describe_tests.rs b/crates/tinycomputer-engine/src/task/task_tests/describe_tests.rs index 6be80573c..69885b1a3 100644 --- a/crates/tinycomputer-engine/src/task/task_tests/describe_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests/describe_tests.rs @@ -15,6 +15,7 @@ fn continue_with_handle( id, approve: Some(true), answer: Some(String::new()), + host_context: Some(tinycomputer_bus::agent::HostContext::new("opaque-context")), fact_handles: std::collections::BTreeMap::from([( "email".to_owned(), tinycomputer_bus::agent::SecretHandle { @@ -256,7 +257,20 @@ async fn describe_schemas_name_every_request_field() { let plan = serde_json::to_value(tinycomputer_bus::agent::PlanTaskRequest::default()).unwrap(); assert_eq!(documented(&schema("PlanTask")), fields(&plan)); +} +#[tokio::test] +async fn describe_schemas_name_continuation_request_fields() { + let (tasks, _) = controller(Vec::new()); + let described = capabilities(Vec::new(), Some(&jev()), &tasks); + let schema = |name: &str| { + described + .members + .iter() + .find(|member| member.name == name) + .map(|member| member.input.clone()) + .expect("the member is documented") + }; let id = tinycomputer_bus::agent::TaskId::new("t-1"); let others = [ ( @@ -282,10 +296,23 @@ async fn describe_schemas_name_every_request_field() { for (member, request) in others { assert_eq!( documented(&schema(member)), - fields(&request.unwrap()), + if member == "ContinueTask" { + fields(&request.unwrap()) + .into_iter() + .filter(|field| field != "host_context") + .collect() + } else { + fields(&request.unwrap()) + }, "{member}" ); } + assert!( + schema("ContinueTask")["properties"] + .get("host_context") + .is_none(), + "host context is injected by the trusted host, not exposed to agents" + ); // Every member with a request object is compared above; the rest take // no argument. for member in &described.members { diff --git a/crates/tinycomputer/src/tinybus_module/README.md b/crates/tinycomputer/src/tinybus_module/README.md index a2af54e06..480af3ea0 100644 --- a/crates/tinycomputer/src/tinybus_module/README.md +++ b/crates/tinycomputer/src/tinybus_module/README.md @@ -75,6 +75,14 @@ TinyBus treats initial and replacement module configuration as sensitive host-control traffic. An unreadable configuration fails before replacing the served object rather than falling back to defaults. +Setting `consequence_host` to an object with the unique `destination` supplied +by `ModuleHost::prepare_host_callbacks` enables confidential consequence +reviews. When `ContinueTask` approves a pending action for host review, the +module declines it if the configured callback is absent or cannot answer. A +declined approval, an unanswered pause, or a continuation with no pending +action does not fail solely because this callback is absent. Without host +context, the legacy well-known host interface remains available. + ## The manifest `tinybus_module::module_export_optional_static!` emits (C exports by default; `linked_module()` under `static-link`) the descriptor, embedded manifest, and diff --git a/crates/tinycomputer/src/tinybus_module/config.rs b/crates/tinycomputer/src/tinybus_module/config.rs index 5521ae9f5..45560e8c1 100644 --- a/crates/tinycomputer/src/tinybus_module/config.rs +++ b/crates/tinycomputer/src/tinybus_module/config.rs @@ -225,6 +225,44 @@ pub(crate) fn trace_sink_destination( } } +/// Whether the host prepared a confidential consequence-review callback. +pub(crate) fn consequence_host_destination( + config: &serde_json::Value, +) -> Result> { + match config + .as_object() + .and_then(|object| object.get("consequence_host")) + { + None | Some(serde_json::Value::Bool(false)) => Ok(None), + Some(serde_json::Value::Object(options)) if options.len() == 1 => { + let destination = options + .get("destination") + .and_then(serde_json::Value::as_str) + .ok_or(crate::Error::ConfigFieldType { + field: "consequence_host.destination", + expected: "the unique name of the host callback prepared for this module", + })?; + tinybus::BusName::new(destination.to_owned()) + .map_err(|_| crate::Error::ConfigFieldType { + field: "consequence_host.destination", + expected: "the unique name of the host callback prepared for this module", + }) + .and_then(|name| { + name.is_unique() + .then_some(Some(name)) + .ok_or(crate::Error::ConfigFieldType { + field: "consequence_host.destination", + expected: "the unique name of the host callback prepared for this module", + }) + }) + } + Some(_) => Err(crate::Error::ConfigFieldType { + field: "consequence_host", + expected: "false or an object containing only the host callback `destination`", + }), + } +} + /// The `cursor` configuration: the agent's one on-screen cursor, shared by /// the desktop and every task's browser. Either a pace name, or an object /// with an optional `pace` and an optional `overlay` path to the diff --git a/crates/tinycomputer/src/tinybus_module/consequence_gate/consequence_gate_tests.rs b/crates/tinycomputer/src/tinybus_module/consequence_gate/consequence_gate_tests.rs index 32089e4b8..efb5806bd 100644 --- a/crates/tinycomputer/src/tinybus_module/consequence_gate/consequence_gate_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/consequence_gate/consequence_gate_tests.rs @@ -6,7 +6,7 @@ use std::sync::{Arc, Mutex}; use tinybus::Connection; -use tinycomputer_bus::agent::{ContinueTaskRequest, TaskId}; +use tinycomputer_bus::agent::{ContinueTaskRequest, HostContext, TaskId}; use super::*; @@ -61,6 +61,7 @@ fn approval(approve: Option) -> ContinueTaskRequest { fact_handles: std::collections::BTreeMap::new(), approve, answer: None, + host_context: Some(HostContext::new("opaque-context")), } } @@ -103,6 +104,10 @@ async fn an_allowed_approval_goes_through() { assert_eq!(seen[0].task, "t1"); assert_eq!(seen[0].target, "Send"); assert_eq!(seen[0].kind, ConsequenceKind::Irreversible); + assert_eq!( + seen[0].host_context.as_ref().map(HostContext::as_str), + Some("opaque-context") + ); } #[tokio::test] @@ -174,13 +179,43 @@ async fn the_bus_port_reaches_the_hosts_interface() -> tinybus::Result<()> { host_connection.request_name(INTERFACE).await?; let module = Connection::connect(bus.connect().await?).await?; - let link = ConsequenceLink::new(Box::new(BusPort::new(module))); - let verdict = link.review("t1", "pay now", "Pay").await; + let link = ConsequenceLink::new(Box::new(BusPort::new(module, None))); + let verdict = link.review("t1", "pay now", "Pay", None).await; assert_eq!(verdict, Verdict::Denied("no".to_owned())); assert_eq!(fake.seen.lock().unwrap()[0].kind, ConsequenceKind::Payment); Ok(()) } +#[tokio::test] +async fn the_bus_port_never_sends_host_context_to_an_unconfidential_host() -> tinybus::Result<()> { + use tinybus::broker::Broker; + use tinybus::transport::memory::MemoryBus; + + let bus = MemoryBus::new(); + Broker::new().spawn(bus.clone()); + let host_connection = Connection::connect(bus.connect().await?).await?; + let fake = FakeHost::new(Answer::Allow); + host_connection + .serve_at(OBJECT_PATH.try_into()?, BusHost(fake.clone())) + .await?; + host_connection.request_name(INTERFACE).await?; + let module = Connection::connect(bus.connect().await?).await?; + + let link = ConsequenceLink::new(Box::new(BusPort::new(module, None))); + let verdict = link + .review( + "t1", + "send", + "Send", + Some(HostContext::new("opaque-context")), + ) + .await; + + assert!(matches!(verdict, Verdict::Denied(ref reason) if reason.contains("confidential"))); + assert!(fake.seen.lock().unwrap().is_empty()); + Ok(()) +} + #[tokio::test] async fn the_bus_port_treats_a_host_that_serves_nothing_as_unreviewed() -> tinybus::Result<()> { use tinybus::broker::Broker; @@ -189,7 +224,55 @@ async fn the_bus_port_treats_a_host_that_serves_nothing_as_unreviewed() -> tinyb let bus = MemoryBus::new(); Broker::new().spawn(bus.clone()); let module = Connection::connect(bus.connect().await?).await?; - let link = ConsequenceLink::new(Box::new(BusPort::new(module))); - assert_eq!(link.review("t1", "send", "Send").await, Verdict::Unreviewed); + let link = ConsequenceLink::new(Box::new(BusPort::new(module, None))); + assert_eq!( + link.review("t1", "send", "Send", None).await, + Verdict::Unreviewed + ); + Ok(()) +} + +#[tokio::test] +async fn a_missing_configured_callback_is_a_failure_not_an_unreviewed_action() -> tinybus::Result<()> +{ + use tinybus::broker::Broker; + use tinybus::transport::memory::MemoryBus; + + let bus = MemoryBus::new(); + Broker::new().spawn(bus.clone()); + let host = Connection::connect(bus.connect().await?).await?; + let destination = host + .unique_name() + .expect("connected host has a unique name"); + host.serve_at(OBJECT_PATH.try_into()?, UnrelatedObject) + .await?; + let module = Connection::connect(bus.connect().await?).await?; + let link = ConsequenceLink::new(Box::new(BusPort::new(module, Some(destination)))); + + assert!(matches!( + link.review("t1", "send", "Send", None).await, + Verdict::Denied(_) + )); Ok(()) } + +struct UnrelatedObject; + +#[tinybus::interface(name = "org.example.Unrelated")] +impl UnrelatedObject { + async fn ping(&self) -> tinybus::Result<()> { + std::future::ready(Ok(())).await + } +} + +#[test] +fn a_configured_callback_that_is_not_served_is_a_failure() { + let error = tinybus::Error::UnknownInterface { + path: OBJECT_PATH.parse().unwrap(), + interface: INTERFACE.parse().unwrap(), + }; + assert!(matches!( + BusPort::classify_error(true, &error), + PortError::Failed(_) + )); +} diff --git a/crates/tinycomputer/src/tinybus_module/consequence_gate/mod.rs b/crates/tinycomputer/src/tinybus_module/consequence_gate/mod.rs index 93dd0e777..01ee55650 100644 --- a/crates/tinycomputer/src/tinybus_module/consequence_gate/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/consequence_gate/mod.rs @@ -17,7 +17,7 @@ use std::future::Future; use std::pin::Pin; use tinybus::Connection; -use tinycomputer_bus::agent::ContinueTaskRequest; +use tinycomputer_bus::agent::{ContinueTaskRequest, HostContext}; use tinycomputer_bus::consequence_host::{ ConsequenceKind, INTERFACE, OBJECT_PATH, ReviewActionRequest, ReviewActionResponse, methods, }; @@ -26,8 +26,9 @@ use tinycomputer_core::{Consequence, consequence}; /// The deadline for one call to the host. const CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); -/// The bus errors that mean the host does not serve the interface at all, -/// rather than serving it and failing. +/// The bus errors that identify a missing service on the legacy well-known +/// lookup. An explicitly configured destination is expected to be served and +/// every failure from it denies the action. const NOT_SERVED: [&str; 3] = [ "ai.tinyhumans.tinybus.Error.NameHasNoOwner", "ai.tinyhumans.tinybus.Error.UnknownObject", @@ -56,6 +57,7 @@ pub(crate) trait ConsequencePort: Send + Sync + std::fmt::Debug { #[derive(Clone)] pub(crate) struct BusPort { connection: Connection, + destination: Option, } impl std::fmt::Debug for BusPort { @@ -65,31 +67,49 @@ impl std::fmt::Debug for BusPort { } impl BusPort { - pub(crate) fn new(connection: Connection) -> Self { - Self { connection } + pub(crate) fn new(connection: Connection, destination: Option) -> Self { + Self { + connection, + destination, + } + } + + fn classify_error(configured_destination: bool, error: &tinybus::Error) -> PortError { + if !configured_destination && NOT_SERVED.contains(&error.wire_name()) { + PortError::NotServed + } else { + PortError::Failed(error.to_string()) + } } } impl ConsequencePort for BusPort { fn review(&self, request: ReviewActionRequest) -> PortFuture<'_, ReviewActionResponse> { + if request.host_context.is_some() && self.destination.is_none() { + return Box::pin(async { + Err(PortError::Failed( + "host context requires a confidential host callback".to_owned(), + )) + }); + } Box::pin(async move { let proxy = self .connection - .proxy(INTERFACE, OBJECT_PATH, INTERFACE) + .proxy( + self.destination + .as_ref() + .map_or(INTERFACE, tinybus::BusName::as_str), + OBJECT_PATH, + INTERFACE, + ) .map(|proxy| proxy.with_timeout(CALL_TIMEOUT)) .map_err(|error| PortError::Failed(error.to_string()))?; - proxy - .call(methods::REVIEW, (request,)) - .await - .map_err(|error| { - // Across the bus an error keeps its dotted name, not its - // variant, so the name is what says nobody serves this. - if NOT_SERVED.contains(&error.wire_name()) { - PortError::NotServed - } else { - PortError::Failed(error.to_string()) - } - }) + let reply = if self.destination.is_some() { + proxy.call_confidential(methods::REVIEW, (request,)).await + } else { + proxy.call(methods::REVIEW, (request,)).await + }; + reply.map_err(|error| Self::classify_error(self.destination.is_some(), &error)) }) } } @@ -129,13 +149,20 @@ impl ConsequenceLink { /// Asks the host whether task `task` may go ahead with `action` on /// `target`. - pub(crate) async fn review(&self, task: &str, action: &str, target: &str) -> Verdict { + pub(crate) async fn review( + &self, + task: &str, + action: &str, + target: &str, + host_context: Option, + ) -> Verdict { let kind = kind_of(action, target); let request = ReviewActionRequest { task: task.to_owned(), action: action.to_owned(), target: target.to_owned(), kind, + host_context, }; match self.port.review(request).await { Ok(reply) if reply.allow => Verdict::Allowed, @@ -169,7 +196,15 @@ impl ConsequenceLink { let Some((action, target)) = paused else { return; }; - if let Verdict::Denied(_) = self.review(&request.id.to_string(), &action, &target).await { + if let Verdict::Denied(_) = self + .review( + &request.id.to_string(), + &action, + &target, + request.host_context.clone(), + ) + .await + { request.approve = Some(false); } } diff --git a/crates/tinycomputer/src/tinybus_module/dispatch/service.rs b/crates/tinycomputer/src/tinybus_module/dispatch/service.rs index 4385e3081..3cfb9f04d 100644 --- a/crates/tinycomputer/src/tinybus_module/dispatch/service.rs +++ b/crates/tinycomputer/src/tinybus_module/dispatch/service.rs @@ -73,6 +73,12 @@ impl DesktopService { expected: "a module set up with its host callback connection", }); } + if super::super::config::consequence_host_destination(config)?.is_some() { + return Err(crate::Error::ConfigFieldType { + field: "consequence_host", + expected: "a module set up with its confidential host callback connection", + }); + } Self::with_browser_and_trace_sink(config, browser, None) } diff --git a/crates/tinycomputer/src/tinybus_module/mod.rs b/crates/tinycomputer/src/tinybus_module/mod.rs index 2fe7786a3..e7e3c93f6 100644 --- a/crates/tinycomputer/src/tinybus_module/mod.rs +++ b/crates/tinycomputer/src/tinybus_module/mod.rs @@ -40,6 +40,8 @@ pub(crate) use dispatch::DesktopService; /// silently ignoring the session it was told to join would allocate refs /// nothing else can spend. async fn setup(connection: Connection, config: Value) -> TinyBusResult<()> { + let consequence_host = config::consequence_host_destination(&config) + .map_err(|error| tinybus::Error::failed(error.to_string()))?; let service = DesktopService::from_config_with_connection(&config, connection.clone()) .map_err(|error| tinybus::Error::failed(error.to_string()))?; // The host's per-site memory; a host that does not serve it only costs @@ -47,8 +49,10 @@ async fn setup(connection: Connection, config: Value) -> TinyBusResult<()> { let service = service.with_site_memory(Box::new(site_memory::BusPort::new(connection.clone()))); // The host's consequence review; a host that does not serve it leaves a // task's own approval pause as the only gate. - let service = service - .with_consequence_review(Box::new(consequence_gate::BusPort::new(connection.clone()))); + let service = service.with_consequence_review(Box::new(consequence_gate::BusPort::new( + connection.clone(), + consequence_host, + ))); #[cfg(test)] let service = service.with_native_fixture(); service.sweep_outputs(); diff --git a/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs index c81d44495..22d6b0f78 100644 --- a/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/config_tests.rs @@ -308,6 +308,45 @@ fn trace_sink_requires_the_host_prepared_unique_destination() { ); } +#[test] +fn consequence_host_requires_the_host_prepared_unique_destination() { + use crate::tinybus_module::config::consequence_host_destination; + + assert!(consequence_host_destination(&json!({})).unwrap().is_none()); + assert!( + consequence_host_destination(&json!({"consequence_host": false})) + .unwrap() + .is_none() + ); + for invalid in [ + json!({"consequence_host": true}), + json!({"consequence_host": {}}), + json!({"consequence_host": {"destination": "ai.tinyhumans.host"}}), + json!({"consequence_host": {"destination": ":1.42", "scope": "model"}}), + ] { + assert!(consequence_host_destination(&invalid).is_err(), "{invalid}"); + } + assert_eq!( + consequence_host_destination(&json!({ + "consequence_host": {"destination": ":1.42"} + })) + .unwrap() + .unwrap() + .as_str(), + ":1.42" + ); +} + +#[test] +fn connectionless_service_construction_rejects_consequence_host_configuration() { + let error = DesktopService::from_config(&json!({ + "consequence_host": {"destination": ":1.42"} + })) + .expect_err("a host callback needs the module's bus connection"); + + assert!(error.to_string().contains("consequence_host")); +} + #[test] fn connectionless_service_construction_rejects_trace_sink_configuration() { let error = DesktopService::from_config(&json!({ diff --git a/crates/tinycomputer/tests/public_api_tests.rs b/crates/tinycomputer/tests/public_api_tests.rs index 9497a15c0..fa11ff982 100644 --- a/crates/tinycomputer/tests/public_api_tests.rs +++ b/crates/tinycomputer/tests/public_api_tests.rs @@ -34,7 +34,7 @@ fn the_crate_re_exports_the_contract_rather_than_redefining_it() { #[test] fn the_shipped_contract_binds_to_itself() { assert!(is_compatible(CONTRACT_VERSION)); - assert_eq!(CONTRACT_VERSION, (2, 26)); + assert_eq!(CONTRACT_VERSION, (2, 27)); assert!(!is_compatible((2, 25))); } diff --git a/docs/crates/tinycomputer-bus/versioning.md b/docs/crates/tinycomputer-bus/versioning.md index b4767f549..edf255cf1 100644 --- a/docs/crates/tinycomputer-bus/versioning.md +++ b/docs/crates/tinycomputer-bus/versioning.md @@ -9,7 +9,7 @@ code, so this page exists mostly to keep them apart. ## `CONTRACT_VERSION`: does this host understand this module ```rust,ignore -pub const CONTRACT_VERSION: (u32, u32) = (2, 26); +pub const CONTRACT_VERSION: (u32, u32) = (2, 27); ``` This describes the *vocabulary*: the member set and the payload shapes, @@ -45,17 +45,19 @@ Two conditions, both necessary: relies on changed shape or disappeared, so a mismatched major is refused outright, in either direction. 2. **The module must be at least as new, minor-wise, as the host.** A host - built against `(2, 26)` expects at least the members and fields that - existed at `(2, 26)`. A module reporting `(2, 25)` predates the + built against `(2, 27)` expects at least the members and fields that + existed at `(2, 27)`. A module reporting `(2, 26)` lacks host-context relay + for `ConsequenceHost`, so a 2.27 host rejects it. A module reporting + `(2, 25)` predates the `TraceSinkHost` callback added in 2.26, so a 2.26 host rejects it. It does include `BrowserEgressHost`, which was added in 2.25. A newer module with the same major is accepted. ```rust,ignore -assert!(is_compatible(CONTRACT_VERSION)); // (2, 26), the exact version this crate ships -assert!(is_compatible((2, 27))); // a newer, still-compatible module +assert!(is_compatible(CONTRACT_VERSION)); // (2, 27), the exact version this crate ships +assert!(is_compatible((2, 28))); // a newer, still-compatible module assert!(!is_compatible((2, 11))); // an older module, missing something -assert!(!is_compatible((2, 25))); // predates TraceSinkHost; includes BrowserEgressHost from 2.25 +assert!(!is_compatible((2, 26))); // predates ConsequenceHost host-context relay assert!(!is_compatible((1, 10))); // a different major, all bets off ``` diff --git a/docs/crates/tinycomputer/configuration.md b/docs/crates/tinycomputer/configuration.md index 51717dbf1..561cd88cf 100644 --- a/docs/crates/tinycomputer/configuration.md +++ b/docs/crates/tinycomputer/configuration.md @@ -66,6 +66,26 @@ can retry `TaskReport`. Without this key, or with `false`, the existing `trace_path` behavior remains in effect. `true`, malformed objects, and well-known bus names are rejected. +## `consequence_host` + +```json +{ + "consequence_host": { + "destination": ":1.42" + } +} +``` + +Set `consequence_host` to an object containing only the unique callback +destination prepared for this module by `ModuleHost::prepare_host_callbacks`. +The module sends consequence reviews to the host through that confidential +callback. When a `ContinueTask` approves a pending action for host review, +failure to reach the configured callback declines the action. A declined +approval, unanswered pause, or continuation without a pending action does not +fail solely because this callback is absent. Without this key, or with +`false`, calls without host context keep using the legacy well-known host +interface. `true`, malformed objects, and well-known bus names are rejected. + ## `jev` ```json diff --git a/docs/technical/architecture.md b/docs/technical/architecture.md index 1f0ef1317..5036b776a 100644 --- a/docs/technical/architecture.md +++ b/docs/technical/architecture.md @@ -222,6 +222,7 @@ configuration validates. | `trace_path` | string | where agent-desktop writes its trace | | `trace_strict` | bool | fail a call when its trace cannot be written | | `trace_sink` | object | optional host-owned persistence at the unique destination prepared by `ModuleHost::prepare_host_callbacks`; replaces local trace and session persistence | +| `consequence_host` | object | optional confidential consequence review callback at the unique destination prepared by `ModuleHost::prepare_host_callbacks`; a missing callback denies an approved pending action under host review | | `headed` | bool | use real input instead of accessibility actions | | `jev` | object | decision provider (`type_safe`, `open_router`, `tiny_humans_open_router`, `open_jev`, `sage`), API key, optional model, approved endpoint, timeout, retries, `sdk_name` for the TinyHumans proxy, and `fast` for Sage | | `planner` | object | `api_key`, `provider` (`open_router` or `tiny_humans`), approved `endpoint_url`, `sdk_name`, and optional `model` for the planner, optional `rescue_route` giving the rescuer its own route and key, optional `rescue_model` for rescuing failed steps (`docs/technical/specs/task-rescue.md`), and optional `output_model` for shaping a finished task's answer (`docs/technical/specs/task-output.md`); absent means no planner, no rescues, and no output shapes | diff --git a/docs/technical/specs/desktop-module-contract.md b/docs/technical/specs/desktop-module-contract.md index 79d556918..4b36ca80e 100644 --- a/docs/technical/specs/desktop-module-contract.md +++ b/docs/technical/specs/desktop-module-contract.md @@ -89,6 +89,15 @@ serves the interface and fails to answer, turns the approval into a decline, so the task never takes the action. A host that serves nothing leaves the pause as the only gate. A payment checkpoint is never continuable and needs no review. +Host context relay (2.27): `ContinueTaskRequest` takes an optional opaque +`host_context`. When the module requests consequence review, it copies that +value unchanged into `ReviewActionRequest.host_context`; the module does not +interpret it or grant it authority. The bus type redacts the value from its +`Debug` output. Hosts that use the relay must validate the context themselves +and bind it to the task and action under review. Omitting the field preserves +the earlier continuation and consequence-review behavior; hosts that depend on +the relay require a compatible 2.27 module. + Browser egress (2.25): a host may serve the optional `ai.tinyhumans.tinycomputer.BrowserEgressHost` interface (`tinycomputer_bus::browser_egress`) with `Authorize`, `Consume`, and