Personal AI, On Personal Devices
Python
Add Rust cross-device execution handoff example (#994)
Elliot Slusky8344e5118725
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex ee653804..01ebfc44 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -179,3 +179,10 @@ jobs:- name: Testrun: cargo test --workspace++ # Standalone handoff example: intentionally not a runtime workspace member.+ - name: Cross-device travel example+ run: |+ cargo fmt --manifest-path ../examples/cross_device_travel/Cargo.toml --check+ cargo clippy --locked --manifest-path ../examples/cross_device_travel/Cargo.toml --all-targets -- -D warnings+ cargo test --locked --manifest-path ../examples/cross_device_travel/Cargo.tomldiff --git a/examples/cross_device_travel/Cargo.lock b/examples/cross_device_travel/Cargo.locknew file mode 100644index 00000000..5ee7798e--- /dev/null+++ b/examples/cross_device_travel/Cargo.lock@@ -0,0 +1,107 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "itoa"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "openjarvis-cross-device-travel"+version = "0.1.0"+dependencies = [+ "serde",+ "serde_json",+]++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "serde"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde_core"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "serde_json"+version = "1.0.151"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]++[[package]]+name = "syn"+version = "3.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "unicode-ident"+version = "1.0.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"++[[package]]+name = "zmij"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"diff --git a/examples/cross_device_travel/Cargo.toml b/examples/cross_device_travel/Cargo.tomlnew file mode 100644index 00000000..5e11a1ce--- /dev/null+++ b/examples/cross_device_travel/Cargo.toml@@ -0,0 +1,13 @@+[package]+name = "openjarvis-cross-device-travel"+version = "0.1.0"+edition = "2021"+rust-version = "1.88"+publish = false++# An isolated handoff example: no changes to the OpenJarvis runtime or workspace.+[workspace]++[dependencies]+serde = { version = "1", features = ["derive"] }+serde_json = "1"diff --git a/examples/cross_device_travel/README.md b/examples/cross_device_travel/README.mdnew file mode 100644index 00000000..be3c9157--- /dev/null+++ b/examples/cross_device_travel/README.md@@ -0,0 +1,213 @@+# Cross-device travel planning handoff++A standalone Rust template for a laptop coordinating work with a phone for+**“Make travel plans for me.”** It demonstrates device ownership, task messages,+routing, and failure behavior before building real infrastructure.++Everything is deterministic and synthetic. Both devices run in one process;+requests and responses cross an in-memory JSON serialization boundary. There is+no network connection, mobile integration, real model inference, live travel research,+calendar write, or booking. Saving a draft only changes synthetic in-memory state.++## Run it++Requires Rust 1.88 or later. Run these commands from the repository root:++```sh+cargo run --manifest-path examples/cross_device_travel/Cargo.toml -- happy+cargo test --manifest-path examples/cross_device_travel/Cargo.toml+```++CI also runs this crate's formatting, Clippy, and tests independently.++The executable prints JSON. `report.events` contains the full task request and+response messages; `final_output` contains the assembled result. The checked-in+[happy-path trace](traces/happy.json) is generated by the same executable:++```sh+cargo run --quiet --manifest-path examples/cross_device_travel/Cargo.toml -- happy > examples/cross_device_travel/traces/happy.json+```++Pass one scenario name after `--` (default: `happy`; `--help` lists options).+An aborted workflow still prints its report and exits with status 1.++| Scenario | Demonstrates |+| --- | --- |+| `happy` | Phone context, laptop research and planning, then a phone draft. |+| `phone-offline` | Optional phone work is unavailable; laptop planning proceeds with explicit gaps. |+| `photos-denied` | Photo access fails; other context still contributes to the plan. |+| `research-retry` | A transient research failure is retried within a fixed limit. |+| `save-timeout` | A phone draft times out; the action is not retried automatically. |+| `laptop-offline` | Required laptop work cannot run; the workflow aborts. |++This crate builds independently of the main Rust workspace.++## Walkthrough++The laptop creates a fixed, topologically ordered task list for this exact request+and synthetic trip assumptions. A future general natural-language planner can+produce the same task structures. The happy path plans three days in Montreal+from Boston, using phone-provided dates and interests.++The happy trace executes these six steps sequentially, one successful attempt each:++| Task / executor | Input and dependency outputs | Synthetic output |+| --- | --- | --- |+| `mobile_context` / phone | Fixed travel request. | Origin: Boston; timezone: `America/New_York`. |+| `photo_interests` / phone | Fixed travel request. | Interest summary: architecture and parks. |+| `calendar` / phone | Fixed travel request. | Available dates: October 16–18, 2026. |+| `research` / laptop | Destination: Montreal; `mobile_context` + `photo_interests`. | Air/rail candidates and a central-area stay, all synthetic and unverified. |+| `plan` / laptop | Model profile: `large_local`; `mobile_context` + `calendar` + `research`. | Oct 16 arrival, Oct 17 architecture, Oct 18 parks/return; selects the air/stay fixtures; execution backend: `mock`. |+| `save_draft` / phone | Completed `plan`. | Draft `travel-demo-001:save_draft` in demo memory; no bookings. |++Dependency flow: `mobile_context + photo_interests → research`;+`mobile_context + calendar + research → plan`; `plan → save_draft`.+Research and planning are required; their failure aborts the remaining workflow.+Phone tasks are optional; failures produce explicit gaps or an unsuccessful draft.+The assembled `final_output` has `status: "completed"`, the plan, no warnings,+and `draft_status: "saved_in_demo_memory"` on this happy path.++The phone returns summaries and availability rather than its raw photo library.+The laptop owns research and larger planning steps. Routing requires the requested+capability, device kind, and online status, with a stable device-ID tie break. An+unavailable phone capability does not silently migrate to the laptop. Discovery+assumes one user's single paired phone; it does not authenticate device ownership.++Only successful outputs from explicitly declared dependencies enter a task's+`context`. Failed optional dependencies are omitted; their failures remain visible+in the trace. The final report preserves missing inputs and unsuccessful actions+so a partial plan cannot be mistaken for a confirmed booking or calendar update.+Missing calendar context produces unconfirmed dates. Supplied `available_dates` must+contain exactly three nonempty strings; invalid payload shapes are rejected.++## Code and interfaces++| File | Responsibility and replacement point |+| --- | --- |+| [`src/protocol.rs`](src/protocol.rs) | Serde request/response types and independent protocol version 1. |+| [`src/runtime.rs`](src/runtime.rs) | `DeviceTransport`, discovery, routing, dependency context, retries, and failure handling. |+| [`src/travel.rs`](src/travel.rs) | Laptop decomposition, phone fixtures, mock device dispatch, and final output assembly. |+| [`src/laptop.rs`](src/laptop.rs) | `research_travel` option records and the `LaptopPlanner` inference boundary; validates scheduling context and consumes research options. |+| [`src/main.rs`](src/main.rs) | Scenario selection and JSON report output. |++The same workflow can be invoked from Rust:++```rust+use openjarvis_cross_device_travel::runtime::Orchestrator;+use openjarvis_cross_device_travel::travel::{decompose, DemoTransport, Scenario};++fn main() -> Result<(), Box<dyn std::error::Error>> {+ let tasks = decompose("Make travel plans for me.")?;+ let transport = DemoTransport::new(Scenario::Happy);+ let report = Orchestrator::new("laptop", transport).run("travel-demo-001", &tasks)?;+ assert!(!report.aborted);+ Ok(())+}+```++The laptop handlers expose concrete research and heavier-model replacement points:++```rust+use std::collections::BTreeMap;+use serde_json::Value;+use openjarvis_cross_device_travel::protocol::TaskError;+use openjarvis_cross_device_travel::laptop::{+ research_travel, LaptopPlanner, MockLaptopPlanner, PlannerRequest,+};++fn run_laptop_steps(+ research_context: &BTreeMap<String, Value>,+ planning_context: &mut BTreeMap<String, Value>,+) -> Result<Value, TaskError> {+ let findings = research_travel("Montreal", research_context)?;+ planning_context.insert("research".into(), findings);+ MockLaptopPlanner.plan(PlannerRequest {+ model_profile: "large_local", context: planning_context,+ })+}+```++Here research context contains successful `mobile_context` and `photo_interests`+outputs; planning context starts with successful `mobile_context` and `calendar`+outputs. `large_local` describes intended laptop placement; `MockLaptopPlanner`+returns deterministic fixtures without loading a model. Replace its `LaptopPlanner`+implementation with local inference, retaining the request/result boundary.++`DeviceTransport::discover` supplies device advertisements to the laptop.+The runtime selects a device by capability and device kind, then calls+`DeviceTransport::execute` with an addressed task request. The mock adapter+decodes that request, calls the corresponding phone or laptop fixture handler,+and returns a typed response. Replace the transport to cross a real process or+device boundary; replace fixture handlers to call mobile APIs or laptop tools.++The protocol is a demo contract, not an implementation of the A2A specification.+The trace is an executable example of the following envelopes:++| Request field | Meaning |+| --- | --- |+| `version` | Demo protocol version. |+| `workflow_id`, `task_id` | Correlate the workflow and stable logical task. |+| `attempt` | Distinguish attempts of that same task. |+| `from_device`, `to_device` | Identify sender and selected executor. |+| `capability` | Name the requested device function. |+| `input` | Task-specific arguments. |+| `context` | Successful outputs from declared dependencies. |+| `timeout_ms` | Execution timeout budget for the transport to enforce. |++Responses carry `version`, `workflow_id`, `task_id`, `attempt`, and `device_id`,+plus an `outcome` tagged with `status: "succeeded"` or `status: "failed"`. The runtime+validates every response correlation field before accepting an output. It also+rejects empty or duplicate task IDs and invalid dependency order before dispatch.++Read capabilities get at most two attempts, and actions get one. Retries require+a retryable timeout, unavailable-device error, or execution failure. Routing+failures do not dispatch or retry; rediscovery requires another workflow run.+A write timeout can mean the action happened but its reply was lost; `save_draft`+is therefore never automatically retried. Any failed dispatched draft is+conservatively reported as uncertain, including a disconnect or invalid reply;+`not_saved` is reserved for routing failures that prevented dispatch.+Stable task IDs support future+idempotency work but do not provide durable deduplication or exactly-once delivery.++Timeout enforcement belongs to the transport. The mock explicitly simulates+timeouts; it does not start a real timer or interrupt running work.++## OpenJarvis integration map++These future integration points are outside the demo's runtime and dependencies.++| Existing interface | Proposed adapter |+| --- | --- |+| `rust/crates/openjarvis-agents/src/traits.rs`: `OjAgent::run` | Wrap the laptop workflow as an agent; map `AgentContext` and `AgentResult` metadata to workflow context and results. |+| `rust/crates/openjarvis-tools/src/traits.rs`: `BaseTool` | Expose device dispatch with a `ToolSpec` argument schema and a `ToolResult` response. |+| `src/openjarvis/a2a/client.py`: `A2AClient` | Adapt discovery to agent cards and dispatch to the existing `tasks/send` endpoint. |+| `src/openjarvis/a2a/tool.py`: `A2AAgentTool` | Follow the existing remote-agent-as-tool pattern for Python orchestration. |+| `rust/crates/openjarvis-core/src/hardware.rs`: `detect_hardware` | Populate laptop compute advertisements; peer discovery still needs its own adapter. |+| `rust/crates/openjarvis-core/src/types.rs`: `Trace`, `TraceStep` | Record routing, tool calls, and responses in OpenJarvis tracing. |++Integration needs explicit adaptation. Rust A2A currently uses+`pending/active/cancelled`, whereas Python uses `submitted/working/canceled`;+their agent-card and task fields also differ. Do not forward these demo messages+directly into either implementation and assume compatibility. A production+adapter should check JSON-RPC errors and task completion explicitly.++The Rust `OrchestratorAgent` currently performs a single model chat and leaves+multi-turn tool dispatch for future work. Its `ToolExecutor` registers a closed+`BuiltinTool` enum, so adding an arbitrary remote `BaseTool` also requires an+integration change. Those changes are outside this example's scope.++## Productionization decisions++- Replace static advertisements with authenticated discovery, capability versions,+ permission state, and reachability/expiry handling. Bind private data to its+ specific owning device and user, beyond the demo's device-kind constraint.+- Add an actual transport with enforced deadlines, device identity, reconnect+ behavior, and payload limits; retain the runtime's response correlation checks.+- Add persistent task state, action idempotency, timeout reconciliation, and+ cancellation semantics before retrying actions across device disconnects.+- Replace fixtures with phone permission-aware data adapters, real research tools,+ and a laptop planner that asks for missing trip constraints.+- Define consent and data-minimization rules for real phone context; keep raw+ private data on its owning device where possible.+- Extend static dependency validation to generated plans, and add concurrent+ scheduling and durable trace storage when the execution model needs them.diff --git a/examples/cross_device_travel/src/laptop.rs b/examples/cross_device_travel/src/laptop.rsnew file mode 100644index 00000000..041df93c--- /dev/null+++ b/examples/cross_device_travel/src/laptop.rs@@ -0,0 +1,237 @@+//! Laptop research and heavy-model replacement points. Everything here is a fixture;+//! no model, search provider, transport timetable, or booking service is invoked.+use crate::protocol::{ErrorCode, TaskError};+use serde_json::{json, Value};+use std::collections::BTreeMap;++fn invalid(message: impl Into<String>) -> TaskError {+ TaskError::new(ErrorCode::ProtocolError, message, false)+}++fn text<'a>(value: &'a Value, field: &str) -> Result<&'a str, TaskError> {+ value+ .get(field)+ .and_then(Value::as_str)+ .filter(|s| !s.trim().is_empty())+ .ok_or_else(|| invalid(format!("{field} must be a nonempty string")))+}++fn strings(value: &Value, field: &str) -> Result<Vec<String>, TaskError> {+ let values: Vec<String> = serde_json::from_value(value[field].clone())+ .map_err(|_| invalid(format!("{field} must be an array of strings")))?;+ if values.is_empty() || values.iter().any(|s| s.trim().is_empty()) {+ return Err(invalid(format!("{field} must contain nonempty strings")));+ }+ Ok(values)+}++fn origin(context: &BTreeMap<String, Value>) -> Result<&str, TaskError> {+ match context.get("mobile_context") {+ Some(value) => text(value, "origin"),+ None => Ok("unconfirmed"),+ }+}++/// Replace the fixture records with search-provider results behind this interface.+/// The records illustrate candidates, not verified routes or available inventory.+pub fn research_travel(+ destination: &str,+ context: &BTreeMap<String, Value>,+) -> Result<Value, TaskError> {+ if destination.trim().is_empty() {+ return Err(invalid("destination must be a nonempty string"));+ }+ let origin = origin(context)?;+ let (interests, source) = match context.get("photo_interests") {+ Some(value) => (strings(value, "interests")?, "synthetic_phone_summary"),+ None => (+ vec!["city walks".into(), "neighborhood food".into()],+ "assumed_generic_preferences",+ ),+ };+ let transport_options: Vec<_> = ["air", "rail"]+ .into_iter()+ .map(|mode| {+ json!({+ "id": format!("fixture-{mode}"), "mode": mode,+ "origin": origin, "destination": destination,+ "verification": "unverified", "synthetic": true+ })+ })+ .collect();+ Ok(json!({+ "destination": destination, "departure_origin": origin,+ "interests": interests, "interest_source": source,+ "transport_research": format!("Compare transport from {origin} to {destination}; schedules and fares unverified"),+ "lodging_research": "Compare central accommodation; availability and prices unverified",+ "transport_options": transport_options,+ "lodging_options": [{"id": "fixture-central-stay", "area": "Central area",+ "destination": destination, "verification": "unverified", "synthetic": true}],+ "evidence": "Hypothetical fixture; no live research or cited sources"+ }))+}++pub struct PlannerRequest<'a> {+ pub model_profile: &'a str,+ pub context: &'a BTreeMap<String, Value>,+}++/// A production adapter can invoke a larger local model here, retaining schema+/// validation and caller-provided context. Device routing stays in the orchestrator.+pub trait LaptopPlanner {+ fn plan(&self, request: PlannerRequest<'_>) -> Result<Value, TaskError>;+}++pub struct MockLaptopPlanner;++fn options<'a>(+ research: &'a Value,+ field: &str,+ required: &[&str],+) -> Result<&'a [Value], TaskError> {+ let records = research[field]+ .as_array()+ .filter(|v| !v.is_empty())+ .ok_or_else(|| invalid(format!("{field} must contain candidate records")))?;+ for record in records {+ for key in required {+ text(record, key)?;+ }+ if text(record, "destination")? != text(research, "destination")?+ || text(record, "verification")? != "unverified"+ || record["synthetic"] != true+ {+ return Err(invalid(format!(+ "{field} must contain matching unverified fixtures"+ )));+ }+ }+ Ok(records)+}++impl LaptopPlanner for MockLaptopPlanner {+ fn plan(&self, request: PlannerRequest<'_>) -> Result<Value, TaskError> {+ if request.model_profile != "large_local" {+ return Err(invalid(+ "The mock laptop planner supports model_profile=large_local only",+ ));+ }+ let context = request.context;+ let research = context+ .get("research")+ .ok_or_else(|| invalid("Research output required"))?;+ let destination = text(research, "destination")?;+ let origin = origin(context)?;+ if text(research, "departure_origin")? != origin {+ return Err(invalid(+ "Research departure_origin must match mobile context or its fallback",+ ));+ }+ let interests = strings(research, "interests")?;+ for field in [+ "interest_source",+ "transport_research",+ "lodging_research",+ "evidence",+ ] {+ text(research, field)?;+ }+ let transport = options(research, "transport_options", &["id", "mode", "origin"])?;+ if transport.iter().any(|record| record["origin"] != origin) {+ return Err(invalid("Transport candidates must match departure_origin"));+ }+ let lodging = options(research, "lodging_options", &["id", "area"])?;+ // Missing optional context permits a labeled fallback. Supplied malformed+ // context is a protocol failure, never evidence of calendar availability.+ let dates: [String; 3] = match context.get("calendar") {+ None => std::array::from_fn(|_| "unconfirmed".into()),+ Some(calendar) => {+ serde_json::from_value(calendar["available_dates"].clone()).map_err(|_| {+ invalid("Calendar available_dates must contain exactly three strings")+ })?+ }+ };+ if dates.iter().any(|date| date.trim().is_empty()) {+ return Err(invalid("Calendar dates must be nonempty strings"));+ }+ let itinerary: Vec<_> = dates.iter().enumerate().map(|(day, date)| json!({+ "day": day + 1, "date": date,+ "activity": match day {+ 0 => "Arrival and orientation".to_string(),+ 1 => format!("Explore {} in {destination}", interests[0]),+ _ => format!("Explore {}; return travel", interests.get(1).map(String::as_str).unwrap_or("local neighborhoods"))+ }+ })).collect();+ Ok(json!({+ "title": format!("Hypothetical three-day {destination} trip"),+ "origin": origin, "research": research, "itinerary": itinerary,+ "selected_options": {"transport": transport[0], "lodging": lodging[0]},+ "execution": {"model_profile": request.model_profile, "backend": "mock"},+ "scheduling": {+ "dates": dates,+ "dates_status": if context.contains_key("calendar") {+ "supported_by_synthetic_phone_availability"+ } else { "unconfirmed" },+ "requires_user_confirmation": true,+ "next_steps": ["Confirm origin, dates, and interests", "Verify transport, lodging, and opening hours"]+ },+ "assumptions": [format!("{destination} is an illustrative destination"), "No budget provided"],+ "synthetic": true+ }))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn planner_consumes_research_candidates_and_destination() {+ let mut context = BTreeMap::from([+ ("mobile_context".into(), json!({"origin": "Boston"})),+ (+ "photo_interests".into(),+ json!({"interests": ["museums", "gardens"]}),+ ),+ ]);+ let mut research = research_travel("Quebec City", &context).unwrap();+ research["lodging_options"][0]["area"] = json!("Museum quarter");+ context.insert("research".into(), research);+ let plan = MockLaptopPlanner+ .plan(PlannerRequest {+ model_profile: "large_local",+ context: &context,+ })+ .unwrap();+ assert_eq!(plan["title"], "Hypothetical three-day Quebec City trip");+ assert_eq!(+ plan["itinerary"][1]["activity"],+ "Explore museums in Quebec City"+ );+ assert_eq!(+ plan["selected_options"]["lodging"]["area"],+ "Museum quarter"+ );+ assert_eq!(plan["selected_options"]["transport"]["origin"], "Boston");+ assert_eq!(+ plan["selected_options"]["transport"]["destination"],+ "Quebec City"+ );+ assert_eq!(+ plan["execution"],+ json!({"model_profile": "large_local", "backend": "mock"})+ );+ }++ #[test]+ fn unsupported_model_profile_is_a_nonretryable_protocol_error() {+ let error = MockLaptopPlanner+ .plan(PlannerRequest {+ model_profile: "cloud",+ context: &BTreeMap::new(),+ })+ .unwrap_err();+ assert_eq!(error.code, ErrorCode::ProtocolError);+ assert!(!error.retryable);+ }+}diff --git a/examples/cross_device_travel/src/lib.rs b/examples/cross_device_travel/src/lib.rsnew file mode 100644index 00000000..13608ea0--- /dev/null+++ b/examples/cross_device_travel/src/lib.rs@@ -0,0 +1,7 @@+//! Illustrative cross-device execution; all demo data and device actions are synthetic.+#![doc = include_str!("../README.md")]++pub mod laptop;+pub mod protocol;+pub mod runtime;+pub mod travel;diff --git a/examples/cross_device_travel/src/main.rs b/examples/cross_device_travel/src/main.rsnew file mode 100644index 00000000..8084f4a2--- /dev/null+++ b/examples/cross_device_travel/src/main.rs@@ -0,0 +1,41 @@+use openjarvis_cross_device_travel::travel::{run_demo, Scenario};+use std::process::ExitCode;++fn main() -> ExitCode {+ let args: Vec<_> = std::env::args().skip(1).collect();+ if args.len() == 1 && matches!(args[0].as_str(), "--help" | "-h") {+ println!(+ "Usage: cargo run -- [scenario]\nScenarios: {}\nDefault: happy",+ Scenario::NAMES+ );+ return ExitCode::SUCCESS;+ }+ if args.len() > 1 {+ eprintln!("Expected at most one scenario. Use --help for usage.");+ return ExitCode::from(2);+ }+ let scenario = match Scenario::parse(args.first().map(String::as_str).unwrap_or("happy")) {+ Ok(scenario) => scenario,+ Err(error) => {+ eprintln!("{error}");+ return ExitCode::from(2);+ }+ };+ match run_demo(scenario) {+ Ok(value) => {+ println!(+ "{}",+ serde_json::to_string_pretty(&value).expect("JSON Value serializes")+ );+ if value["report"]["aborted"] == true {+ ExitCode::FAILURE+ } else {+ ExitCode::SUCCESS+ }+ }+ Err(error) => {+ eprintln!("{error}");+ ExitCode::FAILURE+ }+ }+}diff --git a/examples/cross_device_travel/src/protocol.rs b/examples/cross_device_travel/src/protocol.rsnew file mode 100644index 00000000..85b63437--- /dev/null+++ b/examples/cross_device_travel/src/protocol.rs@@ -0,0 +1,160 @@+//! Demo protocol v1. These JSON types are intentionally independent of A2A.+use serde::{Deserialize, Serialize};+use serde_json::Value;+use std::collections::BTreeMap;++pub const PROTOCOL_VERSION: u16 = 1;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum DeviceKind {+ Laptop,+ Phone,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum Capability {+ MobileContext,+ PhotoInterests,+ CalendarAvailability,+ TravelResearch,+ ItineraryPlanning,+ SaveDraft,+}++impl Capability {+ /// An uncertain write must be reconciled with its owner, never blindly retried.+ pub fn is_read_only(self) -> bool {+ // Exhaustive classification makes adding a capability require an explicit+ // retry decision, instead of silently treating new actions as safe reads.+ match self {+ Self::MobileContext+ | Self::PhotoInterests+ | Self::CalendarAvailability+ | Self::TravelResearch+ | Self::ItineraryPlanning => true,+ Self::SaveDraft => false,+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Device {+ pub id: String,+ pub kind: DeviceKind,+ pub online: bool,+ pub capabilities: Vec<Capability>,+}++/// A small, sequential plan in dependency order. Device kind is a placement+/// constraint, so a laptop advertising photos cannot impersonate the phone.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TaskSpec {+ pub id: String,+ pub capability: Capability,+ pub device_kind: DeviceKind,+ pub depends_on: Vec<String>,+ pub optional: bool,+ pub input: Value,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct TaskRequest {+ pub version: u16,+ pub workflow_id: String,+ pub task_id: String,+ pub attempt: u32,+ pub from_device: String,+ pub to_device: String,+ pub capability: Capability,+ pub input: Value,+ /// Only successful, explicitly declared dependency outputs cross the boundary.+ pub context: BTreeMap<String, Value>,+ /// The transport must bound execution/waiting by this budget. A timeout is+ /// not proof that execution stopped or that a side effect did not occur.+ pub timeout_ms: u64,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ErrorCode {+ NoCapability,+ DeviceUnavailable,+ Timeout,+ PermissionDenied,+ ExecutionFailed,+ ProtocolError,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct TaskError {+ pub code: ErrorCode,+ pub message: String,+ pub retryable: bool,+}++impl TaskError {+ pub fn new(code: ErrorCode, message: impl Into<String>, retryable: bool) -> Self {+ Self {+ code,+ message: message.into(),+ retryable,+ }+ }+}++impl std::fmt::Display for TaskError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{:?}: {}", self.code, self.message)+ }+}++impl std::error::Error for TaskError {}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(tag = "status", rename_all = "snake_case")]+pub enum Outcome {+ Succeeded { output: Value },+ Failed { error: TaskError },+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct TaskResponse {+ pub version: u16,+ pub workflow_id: String,+ pub task_id: String,+ pub attempt: u32,+ pub device_id: String,+ pub outcome: Outcome,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(tag = "event", rename_all = "snake_case")]+pub enum TraceEvent {+ Dispatch {+ request: TaskRequest,+ },+ Response {+ response: TaskResponse,+ },+ Failure {+ task_id: String,+ attempt: u32,+ error: TaskError,+ },+ Skipped {+ task_id: String,+ reason: String,+ },+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct RunReport {+ pub workflow_id: String,+ pub devices: Vec<Device>,+ pub tasks: Vec<TaskSpec>,+ pub events: Vec<TraceEvent>,+ pub results: BTreeMap<String, Outcome>,+ pub aborted: bool,+}diff --git a/examples/cross_device_travel/src/runtime.rs b/examples/cross_device_travel/src/runtime.rsnew file mode 100644index 00000000..9fdf0436--- /dev/null+++ b/examples/cross_device_travel/src/runtime.rs@@ -0,0 +1,232 @@+//! Sequential laptop scheduler. Discovery, transport and placement policy are+//! deliberately small replacement points, not a durable distributed scheduler.+use crate::protocol::*;+use std::collections::{BTreeMap, BTreeSet};++pub trait DeviceTransport {+ /// A snapshot of paired devices and advertised capabilities. A real adapter+ /// needs authenticated discovery and liveness expiry; online is only a hint.+ fn discover(&self) -> Vec<Device>;++ /// Return a terminal device response, or a transport error. Implementations+ /// must enforce request.timeout_ms (including connection and response wait).+ fn execute(&mut self, request: &TaskRequest) -> Result<TaskResponse, TaskError>;+}++/// Match capability AND placement before considering availability. For this+/// one-phone demo discovery represents a single user's already-paired devices.+/// Production routing must also constrain data to the specific owning device.+pub fn route<'a>(devices: &'a [Device], task: &TaskSpec) -> Result<&'a Device, TaskError> {+ let candidates: Vec<_> = devices+ .iter()+ .filter(|device| {+ device.kind == task.device_kind && device.capabilities.contains(&task.capability)+ })+ .collect();+ // Stable tie break makes traces reproducible regardless of discovery order.+ candidates+ .iter()+ .filter(|device| device.online)+ .min_by_key(|device| &device.id)+ .copied()+ .ok_or_else(|| {+ if candidates.is_empty() {+ TaskError::new(+ ErrorCode::NoCapability,+ format!("No {:?} advertises {:?}", task.device_kind, task.capability),+ false,+ )+ } else {+ TaskError::new(+ ErrorCode::DeviceUnavailable,+ format!("Devices for {:?} are offline", task.capability),+ true,+ )+ }+ })+}++pub struct Orchestrator<T> {+ laptop_id: String,+ transport: T,+}++impl<T: DeviceTransport> Orchestrator<T> {+ pub fn new(laptop_id: &str, transport: T) -> Self {+ Self {+ laptop_id: laptop_id.into(),+ transport,+ }+ }++ pub fn run(&mut self, workflow_id: &str, tasks: &[TaskSpec]) -> Result<RunReport, TaskError> {+ validate_plan(workflow_id, tasks)?;+ let devices = self.transport.discover();+ let mut ids = BTreeSet::new();+ if devices+ .iter()+ .any(|device| device.id.is_empty() || !ids.insert(&device.id))+ {+ return Err(TaskError::new(+ ErrorCode::ProtocolError,+ "Discovery returned empty or duplicate device IDs",+ false,+ ));+ }+ let mut report = RunReport {+ workflow_id: workflow_id.into(),+ devices,+ tasks: tasks.to_vec(),+ events: Vec::new(),+ results: BTreeMap::new(),+ aborted: false,+ };+ for task in tasks {+ if report.aborted {+ report.events.push(TraceEvent::Skipped {+ task_id: task.id.clone(),+ reason: "Required task failed".into(),+ });+ continue;+ }+ let outcome = match route(&report.devices, task) {+ Ok(device) => {+ let target = device.id.clone();+ let context = task+ .depends_on+ .iter()+ .filter_map(|id| {+ match report.results.get(id) {+ Some(Outcome::Succeeded { output }) => {+ Some((id.clone(), output.clone()))+ }+ // Optional failures are omitted: the receiving handler+ // must explicitly choose and label its fallback.+ _ => None,+ }+ })+ .collect();+ self.dispatch(workflow_id, task, target, context, &mut report.events)+ }+ Err(error) => {+ // A discovery failure is not a dispatched attempt. No spinning+ // on an unavailable device; the next user run can rediscover.+ report.events.push(TraceEvent::Failure {+ task_id: task.id.clone(),+ attempt: 0,+ error: error.clone(),+ });+ Outcome::Failed { error }+ }+ };+ report.aborted = !task.optional && matches!(outcome, Outcome::Failed { .. });+ report.results.insert(task.id.clone(), outcome);+ }+ Ok(report)+ }++ fn dispatch(+ &mut self,+ workflow_id: &str,+ task: &TaskSpec,+ target: String,+ context: BTreeMap<String, serde_json::Value>,+ events: &mut Vec<TraceEvent>,+ ) -> Outcome {+ // Policy constants keep this handoff small. Replace with per-capability+ // budgets/backoff later. Action requests get exactly one send attempt.+ let attempts = if task.capability.is_read_only() { 2 } else { 1 };+ for attempt in 1..=attempts {+ let request = TaskRequest {+ version: PROTOCOL_VERSION,+ workflow_id: workflow_id.into(),+ task_id: task.id.clone(),+ attempt,+ from_device: self.laptop_id.clone(),+ to_device: target.clone(),+ capability: task.capability,+ input: task.input.clone(),+ context: context.clone(),+ timeout_ms: 5_000,+ };+ events.push(TraceEvent::Dispatch {+ request: request.clone(),+ });+ let result = self.transport.execute(&request).and_then(|response| {+ validate_response(&request, &response)?;+ events.push(TraceEvent::Response {+ response: response.clone(),+ });+ match response.outcome {+ Outcome::Succeeded { output } => Ok(output),+ Outcome::Failed { error } => Err(error),+ }+ });+ match result {+ Ok(output) => return Outcome::Succeeded { output },+ Err(error) => {+ events.push(TraceEvent::Failure {+ task_id: task.id.clone(),+ attempt,+ error: error.clone(),+ });+ // Treat only transient transport/execution failures as retry+ // candidates, even if a peer labels a protocol error retryable.+ let transient = matches!(+ error.code,+ ErrorCode::Timeout+ | ErrorCode::DeviceUnavailable+ | ErrorCode::ExecutionFailed+ );+ if !error.retryable || !transient || attempt == attempts {+ return Outcome::Failed { error };+ }+ }+ }+ }+ unreachable!("Every request has at least one attempt")+ }+}++fn validate_response(request: &TaskRequest, response: &TaskResponse) -> Result<(), TaskError> {+ if response.version != PROTOCOL_VERSION+ || response.workflow_id != request.workflow_id+ || response.task_id != request.task_id+ || response.attempt != request.attempt+ || response.device_id != request.to_device+ {+ return Err(TaskError::new(+ ErrorCode::ProtocolError,+ "Response version or correlation fields do not match request",+ false,+ ));+ }+ Ok(())+}++fn validate_plan(workflow_id: &str, tasks: &[TaskSpec]) -> Result<(), TaskError> {+ if workflow_id.is_empty() || tasks.is_empty() {+ return Err(TaskError::new(+ ErrorCode::ProtocolError,+ "Workflow ID and plan must be nonempty",+ false,+ ));+ }+ let mut completed_ids = BTreeSet::new();+ for task in tasks {+ // Requiring prior dependencies rejects cycles, self references and+ // misspelled IDs before any action is dispatched.+ if task.id.is_empty()+ || completed_ids.contains(&task.id)+ || task.depends_on.iter().any(|id| !completed_ids.contains(id))+ {+ return Err(TaskError::new(+ ErrorCode::ProtocolError,+ "Task IDs must be unique and dependencies must precede their task",+ false,+ ));+ }+ completed_ids.insert(task.id.clone());+ }+ Ok(())+}diff --git a/examples/cross_device_travel/src/travel.rs b/examples/cross_device_travel/src/travel.rsnew file mode 100644index 00000000..5c3211d1--- /dev/null+++ b/examples/cross_device_travel/src/travel.rs@@ -0,0 +1,488 @@+//! Fixed travel example: replace decomposition, discovery, and handlers independently.+//! Every place, date, research result, and action below is a synthetic fixture.+use crate::laptop::{research_travel, LaptopPlanner, MockLaptopPlanner, PlannerRequest};+use crate::protocol::*;+use crate::runtime::{DeviceTransport, Orchestrator};+use serde_json::{json, Value};+use std::collections::BTreeMap;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Scenario {+ Happy,+ PhoneOffline,+ PhotosDenied,+ ResearchRetry,+ SaveTimeout,+ LaptopOffline,+}++impl Scenario {+ pub const NAMES: &'static str =+ "happy | phone-offline | photos-denied | research-retry | save-timeout | laptop-offline";++ pub fn parse(name: &str) -> Result<Self, TaskError> {+ match name {+ "happy" => Ok(Self::Happy),+ "phone-offline" => Ok(Self::PhoneOffline),+ "photos-denied" => Ok(Self::PhotosDenied),+ "research-retry" => Ok(Self::ResearchRetry),+ "save-timeout" => Ok(Self::SaveTimeout),+ "laptop-offline" => Ok(Self::LaptopOffline),+ _ => Err(TaskError::new(+ ErrorCode::ExecutionFailed,+ format!("Unknown scenario {name:?}; expected {}", Self::NAMES),+ false,+ )),+ }+ }+}++/// A deterministic substitute for a model planner, deliberately limited to one prompt.+pub fn decompose(request: &str) -> Result<Vec<TaskSpec>, TaskError> {+ if request != "Make travel plans for me." {+ return Err(TaskError::new(+ ErrorCode::ExecutionFailed,+ "This fixed demo only supports: Make travel plans for me.",+ false,+ ));+ }+ use Capability::*;+ use DeviceKind::*;+ Ok([+ ("mobile_context", MobileContext, Phone, vec![], true),+ ("photo_interests", PhotoInterests, Phone, vec![], true),+ ("calendar", CalendarAvailability, Phone, vec![], true),+ (+ "research",+ TravelResearch,+ Laptop,+ vec!["mobile_context", "photo_interests"],+ false,+ ),+ (+ "plan",+ ItineraryPlanning,+ Laptop,+ vec!["mobile_context", "calendar", "research"],+ false,+ ),+ ("save_draft", SaveDraft, Phone, vec!["plan"], true),+ ]+ .into_iter()+ .map(+ |(id, capability, device_kind, dependencies, optional)| TaskSpec {+ id: id.into(),+ capability,+ device_kind,+ depends_on: dependencies.into_iter().map(String::from).collect(),+ optional,+ input: match capability {+ TravelResearch => json!({"destination": "Montreal", "synthetic": true}),+ ItineraryPlanning => json!({"model_profile": "large_local", "synthetic": true}),+ _ => json!({"request": request, "synthetic": true}),+ },+ },+ )+ .collect())+}++/// An in-memory stand-in for paired-device discovery plus an RPC transport.+/// Replace JSON round trips with authenticated, deadline-bound network I/O.+pub struct DemoTransport {+ scenario: Scenario,+ research_calls: usize,+ save_calls: usize,+ drafts: BTreeMap<String, Value>,+}++impl DemoTransport {+ pub fn new(scenario: Scenario) -> Self {+ Self {+ scenario,+ research_calls: 0,+ save_calls: 0,+ drafts: BTreeMap::new(),+ }+ }++ fn receive(&mut self, request: &TaskRequest) -> Result<Value, TaskError> {+ // Recheck at receipt: discovery is a snapshot, not authorization or liveness.+ if request.version != PROTOCOL_VERSION || request.from_device != "laptop" {+ return Err(TaskError::new(+ ErrorCode::ProtocolError,+ "Unsupported version or source address",+ false,+ ));+ }+ let device = self+ .discover()+ .into_iter()+ .find(|d| d.id == request.to_device)+ .ok_or_else(|| {+ TaskError::new(ErrorCode::ProtocolError, "Unknown target address", false)+ })?;+ if !device.online {+ return Err(TaskError::new(+ ErrorCode::DeviceUnavailable,+ "Device went offline",+ true,+ ));+ }+ if !device.capabilities.contains(&request.capability) {+ return Err(TaskError::new(+ ErrorCode::NoCapability,+ "Endpoint does not own capability",+ false,+ ));+ }+ if request.timeout_ms == 0 {+ return Err(TaskError::new(+ ErrorCode::Timeout,+ "Execution budget exhausted",+ true,+ ));+ }+ // No actual photos, location sensor access, calendar events, or network calls.+ match request.capability {+ Capability::MobileContext => Ok(json!({+ "origin": "Boston", "timezone": "America/New_York", "synthetic": true+ })),+ Capability::PhotoInterests => {+ if self.scenario == Scenario::PhotosDenied {+ return Err(TaskError::new(+ ErrorCode::PermissionDenied,+ "Photo summary permission denied; do not request raw photos elsewhere",+ false,+ ));+ }+ Ok(json!({"interests": ["architecture", "parks"], "synthetic": true}))+ }+ Capability::CalendarAvailability => Ok(json!({+ "available_dates": ["2026-10-16", "2026-10-17", "2026-10-18"], "synthetic": true+ })),+ Capability::TravelResearch => {+ self.research_calls += 1;+ if self.scenario == Scenario::ResearchRetry && self.research_calls == 1 {+ return Err(TaskError::new(+ ErrorCode::Timeout,+ "Synthetic research timeout",+ true,+ ));+ }+ let destination = input_string(request, "destination")?;+ research_travel(destination, &request.context)+ }+ Capability::ItineraryPlanning => {+ // The same task can call a real laptop model through this trait.+ // The mock records the selected profile; it performs no inference.+ MockLaptopPlanner.plan(PlannerRequest {+ model_profile: input_string(request, "model_profile")?,+ context: &request.context,+ })+ }+ Capability::SaveDraft => {+ self.save_calls += 1;+ let plan = request.context.get("plan").ok_or_else(|| {+ TaskError::new(ErrorCode::ExecutionFailed, "Plan output required", false)+ })?;+ let draft_id = format!("{}:{}", request.workflow_id, request.task_id);+ self.drafts.insert(draft_id.clone(), plan.clone());+ if self.scenario == Scenario::SaveTimeout {+ // The write happened, but its reply was lost. The orchestrator+ // must report an uncertain outcome and never retry this action.+ return Err(TaskError::new(ErrorCode::Timeout,+ "Draft response lost; outcome uncertain; reconcile with phone before retrying", true));+ }+ Ok(+ json!({"draft_id": draft_id, "storage": "synthetic_in_memory", "bookings_made": false}),+ )+ }+ }+ }+}++impl DeviceTransport for DemoTransport {+ fn discover(&self) -> Vec<Device> {+ vec![+ Device {+ id: "laptop".into(),+ kind: DeviceKind::Laptop,+ online: self.scenario != Scenario::LaptopOffline,+ capabilities: vec![Capability::TravelResearch, Capability::ItineraryPlanning],+ },+ Device {+ id: "phone".into(),+ kind: DeviceKind::Phone,+ online: self.scenario != Scenario::PhoneOffline,+ capabilities: vec![+ Capability::MobileContext,+ Capability::PhotoInterests,+ Capability::CalendarAvailability,+ Capability::SaveDraft,+ ],+ },+ ]+ }++ fn execute(&mut self, request: &TaskRequest) -> Result<TaskResponse, TaskError> {+ // Exercise the actual wire representation on both sides, including errors.+ fn round_trip<T: serde::Serialize + serde::de::DeserializeOwned>(+ value: &T,+ ) -> Result<T, TaskError> {+ serde_json::to_vec(value)+ .and_then(|bytes| serde_json::from_slice(&bytes))+ .map_err(|e| TaskError::new(ErrorCode::ProtocolError, e.to_string(), false))+ }+ let received: TaskRequest = round_trip(request)?;+ let outcome = match self.receive(&received) {+ Ok(output) => Outcome::Succeeded { output },+ Err(error) => Outcome::Failed { error },+ };+ round_trip(&TaskResponse {+ version: PROTOCOL_VERSION,+ workflow_id: received.workflow_id,+ task_id: received.task_id,+ attempt: received.attempt,+ device_id: received.to_device,+ outcome,+ })+ }+}++pub fn run_demo(scenario: Scenario) -> Result<Value, TaskError> {+ let tasks = decompose("Make travel plans for me.")?;+ let report =+ Orchestrator::new("laptop", DemoTransport::new(scenario)).run("travel-demo-001", &tasks)?;+ let final_output = assemble_output(&report);+ Ok(json!({"report": report, "final_output": final_output}))+}++fn input_string<'a>(request: &'a TaskRequest, name: &str) -> Result<&'a str, TaskError> {+ request+ .input+ .get(name)+ .and_then(Value::as_str)+ .filter(|s| !s.is_empty())+ .ok_or_else(|| {+ TaskError::new(+ ErrorCode::ProtocolError,+ format!("Missing or invalid input: {name}"),+ false,+ )+ })+}++/// Summarize only verified outcomes: losing any action acknowledgement leaves+/// its result unknown, even if the transport error was not called a timeout.+fn assemble_output(report: &RunReport) -> Value {+ let warnings: Vec<_> = report+ .tasks+ .iter()+ .filter(|task| task.optional)+ .filter_map(|task| match report.results.get(&task.id) {+ Some(Outcome::Failed { error }) => Some(json!({"task_id": task.id, "error": error})),+ _ => None,+ })+ .collect();+ let plan = match report.results.get("plan") {+ Some(Outcome::Succeeded { output }) if !report.aborted => output.clone(),+ _ => Value::Null,+ };+ let draft_status = match report.results.get("save_draft") {+ Some(Outcome::Succeeded { .. }) => "saved_in_demo_memory",+ Some(Outcome::Failed { .. }) if report.events.iter().any(|event| {+ matches!(event, TraceEvent::Dispatch { request } if request.task_id == "save_draft")+ }) => "uncertain_reconcile_with_phone",+ Some(Outcome::Failed { .. }) => "not_saved",+ None => "not_attempted",+ };+ json!({+ "status": if report.aborted { "aborted" } else { "completed" },+ "plan": plan, "warnings": warnings, "draft_status": draft_status,+ "notice": "Synthetic demo only: no live research, real device access, bookings, or persistent writes."+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn attempts(value: &Value, task: &str) -> usize {+ value["report"]["events"]+ .as_array()+ .unwrap()+ .iter()+ .filter(|event| event["event"] == "dispatch" && event["request"]["task_id"] == task)+ .count()+ }++ #[test]+ fn happy_flow_uses_phone_context_and_saves_plan() {+ let value = run_demo(Scenario::Happy).unwrap();+ let plan = &value["final_output"]["plan"];+ assert_eq!(plan["origin"], "Boston");+ assert_eq!(plan["research"]["departure_origin"], "Boston");+ assert_eq!(+ plan["itinerary"][1]["activity"],+ "Explore architecture in Montreal"+ );+ assert_eq!(plan["itinerary"][0]["date"], "2026-10-16");+ assert_eq!(+ value["final_output"]["draft_status"],+ "saved_in_demo_memory"+ );+ assert_eq!(value["final_output"]["warnings"], json!([]));+ assert_eq!(value["report"]["results"].as_object().unwrap().len(), 6);+ }++ #[test]+ fn missing_phone_context_is_explicit_and_changes_plan() {+ let value = run_demo(Scenario::PhoneOffline).unwrap();+ let plan = &value["final_output"]["plan"];+ assert_eq!(plan["origin"], "unconfirmed");+ assert_eq!(plan["scheduling"]["dates_status"], "unconfirmed");+ assert_eq!(+ plan["research"]["interest_source"],+ "assumed_generic_preferences"+ );+ assert_eq!(+ plan["itinerary"][1]["activity"],+ "Explore city walks in Montreal"+ );+ assert_eq!(+ value["final_output"]["warnings"].as_array().unwrap().len(),+ 4+ );+ assert_eq!(attempts(&value, "mobile_context"), 0);+ }++ #[test]+ fn photo_denial_is_optional_without_losing_calendar() {+ let value = run_demo(Scenario::PhotosDenied).unwrap();+ assert_eq!(attempts(&value, "photo_interests"), 1);+ assert_eq!(+ value["final_output"]["plan"]["research"]["interest_source"],+ "assumed_generic_preferences"+ );+ assert_eq!(+ value["final_output"]["plan"]["itinerary"][0]["date"],+ "2026-10-16"+ );+ assert_eq!(+ value["final_output"]["warnings"].as_array().unwrap().len(),+ 1+ );+ }++ #[test]+ fn retries_read_but_never_uncertain_write() {+ let read = run_demo(Scenario::ResearchRetry).unwrap();+ assert_eq!(attempts(&read, "research"), 2);+ assert_eq!(read["final_output"]["status"], "completed");+ let write = run_demo(Scenario::SaveTimeout).unwrap();+ assert_eq!(attempts(&write, "save_draft"), 1);+ assert_eq!(+ write["final_output"]["draft_status"],+ "uncertain_reconcile_with_phone"+ );+ assert!(!write["final_output"]["plan"].is_null());+ }++ #[test]+ fn lost_or_invalid_save_reply_leaves_the_action_outcome_unknown() {+ struct LostSaveReply {+ inner: DemoTransport,+ corrupt_reply: bool,+ }+ impl DeviceTransport for LostSaveReply {+ fn discover(&self) -> Vec<Device> {+ self.inner.discover()+ }+ fn execute(&mut self, request: &TaskRequest) -> Result<TaskResponse, TaskError> {+ let mut response = self.inner.execute(request)?;+ if request.capability == Capability::SaveDraft {+ // Prove the write took place before the acknowledgement failed.+ assert_eq!(self.inner.drafts.len(), 1);+ if self.corrupt_reply {+ response.task_id = "wrong-task".into();+ } else {+ return Err(TaskError::new(+ ErrorCode::DeviceUnavailable,+ "Connection lost after saving",+ true,+ ));+ }+ }+ Ok(response)+ }+ }+ for corrupt_reply in [false, true] {+ let transport = LostSaveReply {+ inner: DemoTransport::new(Scenario::Happy),+ corrupt_reply,+ };+ let report = Orchestrator::new("laptop", transport)+ .run(+ "test-save",+ &decompose("Make travel plans for me.").unwrap(),+ )+ .unwrap();+ assert!(!report.aborted);+ assert_eq!(+ assemble_output(&report)["draft_status"],+ "uncertain_reconcile_with_phone"+ );+ assert_eq!(report.events.iter().filter(|event| {+ matches!(event, TraceEvent::Dispatch { request } if request.task_id == "save_draft")+ }).count(), 1);+ }+ }++ #[test]+ fn missing_laptop_aborts_without_final_plan() {+ let value = run_demo(Scenario::LaptopOffline).unwrap();+ assert_eq!(value["final_output"]["status"], "aborted");+ assert!(value["final_output"]["plan"].is_null());+ assert_eq!(attempts(&value, "plan"), 0);+ assert_eq!(attempts(&value, "save_draft"), 0);+ }++ #[test]+ fn changed_dependency_values_reach_research_and_scheduling() {+ let mut transport = DemoTransport::new(Scenario::Happy);+ let mut request = TaskRequest {+ version: PROTOCOL_VERSION,+ workflow_id: "test".into(),+ task_id: "research".into(),+ attempt: 1,+ from_device: "laptop".into(),+ to_device: "laptop".into(),+ capability: Capability::TravelResearch,+ input: json!({"destination": "Montreal"}),+ context: BTreeMap::from([+ ("mobile_context".into(), json!({"origin": "Chicago"})),+ (+ "photo_interests".into(),+ json!({"interests": ["museums", "gardens"]}),+ ),+ ]),+ timeout_ms: 1000,+ };+ let research = transport.receive(&request).unwrap();+ assert_eq!(research["departure_origin"], "Chicago");+ request.capability = Capability::ItineraryPlanning;+ request.input = json!({"model_profile": "large_local"});+ request.context.insert("research".into(), research);+ request.context.insert(+ "calendar".into(),+ json!({"available_dates": ["2027-01-01", "2027-01-02", "2027-01-03"]}),+ );+ let plan = transport.receive(&request).unwrap();+ assert_eq!(plan["origin"], "Chicago");+ assert_eq!(+ plan["itinerary"][1]["activity"],+ "Explore museums in Montreal"+ );+ assert_eq!(plan["itinerary"][0]["date"], "2027-01-01");+ }+}diff --git a/examples/cross_device_travel/tests/demo_trace.rs b/examples/cross_device_travel/tests/demo_trace.rsnew file mode 100644index 00000000..e196d7f0--- /dev/null+++ b/examples/cross_device_travel/tests/demo_trace.rs@@ -0,0 +1,16 @@+//! Keep the handoff trace executable: reviewers can trust it matches the CLI.+#[test]+fn documented_trace_matches_the_executable() {+ let output = std::process::Command::new(env!("CARGO_BIN_EXE_openjarvis-cross-device-travel"))+ .arg("happy")+ .output()+ .expect("run demo binary");+ assert!(output.status.success());+ let actual: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ let documented: serde_json::Value =+ serde_json::from_str(include_str!("../traces/happy.json")).unwrap();+ assert_eq!(+ actual, documented,+ "Regenerate traces/happy.json after intentional demo changes"+ );+}diff --git a/examples/cross_device_travel/tests/review_regressions.rs b/examples/cross_device_travel/tests/review_regressions.rsnew file mode 100644index 00000000..7ba728bd--- /dev/null+++ b/examples/cross_device_travel/tests/review_regressions.rs@@ -0,0 +1,97 @@+use openjarvis_cross_device_travel::{+ protocol::*,+ runtime::{DeviceTransport, Orchestrator},+ travel::{decompose, DemoTransport, Scenario},+};+use serde_json::{json, Value};++struct MalformedCalendar {+ inner: DemoTransport,+ output: Value,+}++impl DeviceTransport for MalformedCalendar {+ fn discover(&self) -> Vec<Device> {+ self.inner.discover()+ }++ fn execute(&mut self, request: &TaskRequest) -> Result<TaskResponse, TaskError> {+ let mut response = self.inner.execute(request)?;+ if request.capability == Capability::CalendarAvailability {+ assert!(matches!(response.outcome, Outcome::Succeeded { .. }));+ response.outcome = Outcome::Succeeded {+ output: self.output.clone(),+ };+ }+ Ok(response)+ }+}++#[test]+fn malformed_successful_calendar_output_aborts_before_saving_a_plan() {+ let tasks = decompose("Make travel plans for me.").unwrap();+ for output in [+ json!({}),+ Value::Null,+ json!({"available_dates": []}),+ json!({"available_dates": ["2026-10-16", "2026-10-17"]}),+ json!({"available_dates": ["2026-10-16", null, "2026-10-18"]}),+ json!({"available_dates": ["2026-10-16", "", "2026-10-18"]}),+ ] {+ let transport = MalformedCalendar {+ inner: DemoTransport::new(Scenario::Happy),+ output: output.clone(),+ };+ let report = Orchestrator::new("laptop", transport)+ .run("calendar-validation", &tasks)+ .unwrap();+ assert!(+ matches!(&report.results["plan"], Outcome::Failed { error }+ if error.code == ErrorCode::ProtocolError),+ "calendar {output} unexpectedly produced {:?}",+ report.results["plan"]+ );+ assert!(report.aborted);+ assert!(!report.events.iter().any(|event| matches!(event,+ TraceEvent::Dispatch { request } if request.capability == Capability::SaveDraft)));+ }+}++#[test]+fn receiver_rejects_invalid_envelopes_before_acknowledging_an_action() {+ let valid = TaskRequest {+ version: PROTOCOL_VERSION,+ workflow_id: "receiver-validation".into(),+ task_id: "save_draft".into(),+ attempt: 1,+ from_device: "laptop".into(),+ to_device: "phone".into(),+ capability: Capability::SaveDraft,+ input: json!({}),+ context: [("plan".into(), json!({"synthetic": true}))].into(),+ timeout_ms: 5000,+ };+ type RejectionCase = (fn(&mut TaskRequest), ErrorCode);+ let cases: [RejectionCase; 5] = [+ (|r| r.version += 1, ErrorCode::ProtocolError),+ (|r| r.from_device = "phone".into(), ErrorCode::ProtocolError),+ (|r| r.to_device = "unknown".into(), ErrorCode::ProtocolError),+ (+ |r| r.capability = Capability::ItineraryPlanning,+ ErrorCode::NoCapability,+ ),+ (|r| r.timeout_ms = 0, ErrorCode::Timeout),+ ];+ for (invalidate, expected) in cases {+ let mut request = valid.clone();+ invalidate(&mut request);+ let response = DemoTransport::new(Scenario::Happy)+ .execute(&request)+ .unwrap();+ assert!(matches!(response.outcome, Outcome::Failed { error } if error.code == expected));+ }+ // The baseline includes the plan needed for a real synthetic save; rejection+ // above cannot pass merely because the fixture forgot that prerequisite.+ let response = DemoTransport::new(Scenario::Happy).execute(&valid).unwrap();+ assert!(matches!(response.outcome, Outcome::Succeeded { .. }));+}diff --git a/examples/cross_device_travel/tests/runtime.rs b/examples/cross_device_travel/tests/runtime.rsnew file mode 100644index 00000000..0c17e40a--- /dev/null+++ b/examples/cross_device_travel/tests/runtime.rs@@ -0,0 +1,342 @@+use openjarvis_cross_device_travel::{protocol::*, runtime::*};+use serde_json::{json, Value};+use std::{cell::RefCell, collections::VecDeque, rc::Rc};++enum Reply {+ Output(Value),+ TransportError(TaskError),+ DeviceError(TaskError),+ Corrupt(fn(&mut TaskResponse)),+}++struct MockTransport {+ devices: Vec<Device>,+ calls: Rc<RefCell<Vec<TaskRequest>>>,+ replies: VecDeque<Reply>,+}++impl DeviceTransport for MockTransport {+ fn discover(&self) -> Vec<Device> {+ self.devices.clone()+ }++ fn execute(&mut self, request: &TaskRequest) -> Result<TaskResponse, TaskError> {+ self.calls.borrow_mut().push(request.clone());+ let mut response = TaskResponse {+ version: request.version,+ workflow_id: request.workflow_id.clone(),+ task_id: request.task_id.clone(),+ attempt: request.attempt,+ device_id: request.to_device.clone(),+ outcome: Outcome::Succeeded {+ output: json!({"source": request.task_id}),+ },+ };+ match self.replies.pop_front() {+ Some(Reply::Output(output)) => response.outcome = Outcome::Succeeded { output },+ Some(Reply::TransportError(error)) => return Err(error),+ Some(Reply::DeviceError(error)) => response.outcome = Outcome::Failed { error },+ Some(Reply::Corrupt(corrupt)) => corrupt(&mut response),+ None => {}+ }+ Ok(response)+ }+}++fn device(id: &str, kind: DeviceKind, online: bool, capabilities: Vec<Capability>) -> Device {+ Device {+ id: id.into(),+ kind,+ online,+ capabilities,+ }+}++fn mock(replies: Vec<Reply>) -> MockTransport {+ MockTransport {+ devices: vec![device(+ "phone",+ DeviceKind::Phone,+ true,+ vec![Capability::MobileContext, Capability::SaveDraft],+ )],+ calls: Rc::new(RefCell::new(Vec::new())),+ replies: replies.into(),+ }+}++fn task(id: &str, depends_on: &[&str], optional: bool) -> TaskSpec {+ TaskSpec {+ id: id.into(),+ capability: Capability::MobileContext,+ device_kind: DeviceKind::Phone,+ depends_on: depends_on.iter().map(|id| (*id).into()).collect(),+ optional,+ input: json!({"requested": id}),+ }+}++fn error(code: ErrorCode, retryable: bool) -> TaskError {+ TaskError::new(code, "simulated failure", retryable)+}++fn failed(report: &RunReport, id: &str) -> ErrorCode {+ match &report.results[id] {+ Outcome::Failed { error } => error.code,+ other => panic!("expected failure for {id}, got {other:?}"),+ }+}++#[test]+fn routing_requires_placement_and_capability_and_distinguishes_offline() {+ let requested = task("context", &[], false);+ let wrong_kind = device(+ "laptop",+ DeviceKind::Laptop,+ true,+ vec![Capability::MobileContext],+ );+ let wrong_capability = device(+ "phone",+ DeviceKind::Phone,+ true,+ vec![Capability::SaveDraft],+ );+ let offline = device(+ "offline",+ DeviceKind::Phone,+ false,+ vec![Capability::MobileContext],+ );+ assert_eq!(+ route(&[wrong_kind.clone(), wrong_capability.clone()], &requested)+ .unwrap_err()+ .code,+ ErrorCode::NoCapability+ );+ assert_eq!(+ route(&[wrong_kind, wrong_capability, offline.clone()], &requested)+ .unwrap_err()+ .code,+ ErrorCode::DeviceUnavailable+ );+ let a = device(+ "a",+ DeviceKind::Phone,+ true,+ vec![Capability::MobileContext],+ );+ let z = device(+ "z",+ DeviceKind::Phone,+ true,+ vec![Capability::MobileContext],+ );+ for devices in [+ vec![z.clone(), offline.clone(), a.clone()],+ vec![a, offline, z],+ ] {+ assert_eq!(route(&devices, &requested).unwrap().id, "a");+ }+}++#[test]+fn invalid_plans_and_device_identities_fail_before_any_dispatch() {+ let cases = vec![+ ("", vec![task("a", &[], false)]),+ ("run", vec![]),+ ("run", vec![task("", &[], false)]),+ ("run", vec![task("a", &[], false), task("a", &[], false)]),+ ("run", vec![task("a", &["missing"], false)]),+ ("run", vec![task("a", &["a"], false)]),+ ("run", vec![task("a", &["b"], false), task("b", &[], false)]),+ (+ "run",+ vec![task("a", &["b"], false), task("b", &["a"], false)],+ ),+ ];+ for (workflow, plan) in cases {+ let transport = mock(vec![]);+ let calls = transport.calls.clone();+ let result = Orchestrator::new("laptop", transport).run(workflow, &plan);+ assert_eq!(result.unwrap_err().code, ErrorCode::ProtocolError);+ assert!(calls.borrow().is_empty());+ }+ for duplicate in [false, true] {+ let mut transport = mock(vec![]);+ if duplicate {+ transport.devices.push(transport.devices[0].clone());+ } else {+ transport.devices[0].id.clear();+ }+ let calls = transport.calls.clone();+ let result = Orchestrator::new("laptop", transport).run("run", &[task("a", &[], false)]);+ assert_eq!(result.unwrap_err().code, ErrorCode::ProtocolError);+ assert!(calls.borrow().is_empty());+ }+}++#[test]+fn context_contains_only_declared_successes_and_omits_optional_failure() {+ let transport = mock(vec![+ Reply::Output(json!({"private": "unrelated"})),+ Reply::Output(json!({"city": "Paris"})),+ Reply::DeviceError(error(ErrorCode::PermissionDenied, false)),+ ]);+ let calls = transport.calls.clone();+ let plan = [+ task("unrelated", &[], false),+ task("location", &[], false),+ task("photos", &[], true),+ task("plan", &["location", "photos"], false),+ ];+ let report = Orchestrator::new("laptop", transport)+ .run("run", &plan)+ .unwrap();+ assert!(!report.aborted);+ assert_eq!(failed(&report, "photos"), ErrorCode::PermissionDenied);+ let calls = calls.borrow();+ assert!(calls[..3].iter().all(|request| request.context.is_empty()));+ assert_eq!(+ calls[3].context,+ [("location".into(), json!({"city": "Paris"}))].into()+ );+ assert_eq!(calls[3].input, plan[3].input);+}++#[test]+fn correlation_rejects_every_mismatched_field_including_a_late_retry_response() {+ let corruptions: [fn(&mut TaskResponse); 5] = [+ |r| r.version += 1,+ |r| r.workflow_id.push('x'),+ |r| r.task_id.push('x'),+ |r| r.attempt += 1,+ |r| r.device_id.push('x'),+ ];+ for corrupt in corruptions {+ let transport = mock(vec![Reply::Corrupt(corrupt)]);+ let calls = transport.calls.clone();+ let report = Orchestrator::new("laptop", transport)+ .run("run", &[task("a", &[], false)])+ .unwrap();+ assert_eq!(failed(&report, "a"), ErrorCode::ProtocolError);+ assert_eq!(calls.borrow().len(), 1);+ assert!(!report+ .events+ .iter()+ .any(|event| matches!(event, TraceEvent::Response { .. })));+ }+ let transport = mock(vec![+ Reply::TransportError(error(ErrorCode::Timeout, true)),+ Reply::Corrupt(|r| r.attempt = 1),+ ]);+ let calls = transport.calls.clone();+ let report = Orchestrator::new("laptop", transport)+ .run("run", &[task("a", &[], false)])+ .unwrap();+ assert_eq!(failed(&report, "a"), ErrorCode::ProtocolError);+ assert_eq!(calls.borrow().len(), 2);+}++#[test]+fn read_retry_preserves_identity_payload_context_and_target() {+ for first in [+ Reply::TransportError(error(ErrorCode::Timeout, true)),+ Reply::DeviceError(error(ErrorCode::ExecutionFailed, true)),+ ] {+ let transport = mock(vec![Reply::Output(json!({"city": "Paris"})), first]);+ let calls = transport.calls.clone();+ let plan = [+ task("context", &[], false),+ task("read", &["context"], false),+ ];+ let report = Orchestrator::new("laptop", transport)+ .run("run", &plan)+ .unwrap();+ assert!(!report.aborted);+ assert!(matches!(report.results["read"], Outcome::Succeeded { .. }));+ let calls = calls.borrow();+ assert_eq!(calls.len(), 3);+ assert_eq!((calls[1].attempt, calls[2].attempt), (1, 2));+ let mut retried = calls[2].clone();+ retried.attempt = 1;+ assert_eq!(calls[1], retried);+ assert!(retried.timeout_ms > 0);+ assert_eq!(retried.context["context"], json!({"city": "Paris"}));+ }+}++#[test]+fn retries_are_bounded_and_require_both_transient_code_and_retryable_flag() {+ for (code, retryable, attempts) in [+ (ErrorCode::Timeout, true, 2),+ (ErrorCode::DeviceUnavailable, true, 2),+ (ErrorCode::ExecutionFailed, true, 2),+ (ErrorCode::Timeout, false, 1),+ (ErrorCode::PermissionDenied, true, 1),+ (ErrorCode::ProtocolError, true, 1),+ ] {+ let transport = mock(vec![+ Reply::DeviceError(error(code, retryable)),+ Reply::DeviceError(error(code, retryable)),+ ]);+ let calls = transport.calls.clone();+ let report = Orchestrator::new("laptop", transport)+ .run("run", &[task("a", &[], false)])+ .unwrap();+ assert_eq!(failed(&report, "a"), code);+ assert!(report.aborted);+ assert_eq!(+ calls.borrow().len(),+ attempts,+ "{code:?}, retryable={retryable}"+ );+ }+}++#[test]+fn uncertain_writes_are_never_replayed() {+ for reply in [+ Reply::TransportError(error(ErrorCode::Timeout, true)),+ Reply::DeviceError(error(ErrorCode::ExecutionFailed, true)),+ ] {+ let transport = mock(vec![reply]);+ let calls = transport.calls.clone();+ let mut action = task("save", &[], true);+ action.capability = Capability::SaveDraft;+ let report = Orchestrator::new("laptop", transport)+ .run("run", &[action])+ .unwrap();+ assert!(matches!(report.results["save"], Outcome::Failed { .. }));+ assert_eq!(calls.borrow().len(), 1);+ }+}++#[test]+fn required_failure_skips_dependent_actions_instead_of_using_partial_context() {+ for offline in [false, true] {+ let mut transport = mock(vec![Reply::DeviceError(error(+ ErrorCode::PermissionDenied,+ false,+ ))]);+ transport.devices[0].online = !offline;+ let calls = transport.calls.clone();+ let mut action = task("save", &["required"], true);+ action.capability = Capability::SaveDraft;+ let report = Orchestrator::new("laptop", transport)+ .run("run", &[task("required", &[], false), action])+ .unwrap();+ assert!(report.aborted);+ assert!(!report.results.contains_key("save"));+ assert!(report.events.iter().any(|event| matches!(event,+ TraceEvent::Skipped { task_id, .. } if task_id == "save")));+ assert_eq!(calls.borrow().len(), usize::from(!offline));+ if offline {+ assert_eq!(failed(&report, "required"), ErrorCode::DeviceUnavailable);+ assert!(matches!(+ report.events.first(),+ Some(TraceEvent::Failure { attempt: 0, .. })+ ));+ }+ }+}diff --git a/examples/cross_device_travel/traces/happy.json b/examples/cross_device_travel/traces/happy.jsonnew file mode 100644index 00000000..83e8a268--- /dev/null+++ b/examples/cross_device_travel/traces/happy.json@@ -0,0 +1,910 @@+{+ "final_output": {+ "draft_status": "saved_in_demo_memory",+ "notice": "Synthetic demo only: no live research, real device access, bookings, or persistent writes.",+ "plan": {+ "assumptions": [+ "Montreal is an illustrative destination",+ "No budget provided"+ ],+ "execution": {+ "backend": "mock",+ "model_profile": "large_local"+ },+ "itinerary": [+ {+ "activity": "Arrival and orientation",+ "date": "2026-10-16",+ "day": 1+ },+ {+ "activity": "Explore architecture in Montreal",+ "date": "2026-10-17",+ "day": 2+ },+ {+ "activity": "Explore parks; return travel",+ "date": "2026-10-18",+ "day": 3+ }+ ],+ "origin": "Boston",+ "research": {+ "departure_origin": "Boston",+ "destination": "Montreal",+ "evidence": "Hypothetical fixture; no live research or cited sources",+ "interest_source": "synthetic_phone_summary",+ "interests": [+ "architecture",+ "parks"+ ],+ "lodging_options": [+ {+ "area": "Central area",+ "destination": "Montreal",+ "id": "fixture-central-stay",+ "synthetic": true,+ "verification": "unverified"+ }+ ],+ "lodging_research": "Compare central accommodation; availability and prices unverified",+ "transport_options": [+ {+ "destination": "Montreal",+ "id": "fixture-air",+ "mode": "air",+ "origin": "Boston",+ "synthetic": true,+ "verification": "unverified"+ },+ {+ "destination": "Montreal",+ "id": "fixture-rail",+ "mode": "rail",+ "origin": "Boston",+ "synthetic": true,+ "verification": "unverified"+ }+ ],+ "transport_research": "Compare transport from Boston to Montreal; schedules and fares unverified"+ },+ "scheduling": {+ "dates": [+ "2026-10-16",+ "2026-10-17",+ "2026-10-18"+ ],+ "dates_status": "supported_by_synthetic_phone_availability",+ "next_steps": [+ "Confirm origin, dates, and interests",+ "Verify transport, lodging, and opening hours"+ ],+ "requires_user_confirmation": true+ },+ "selected_options": {+ "lodging": {+ "area": "Central area",+ "destination": "Montreal",+ "id": "fixture-central-stay",+ "synthetic": true,+ "verification": "unverified"+ },+ "transport": {+ "destination": "Montreal",+ "id": "fixture-air",+ "mode": "air",+ "origin": "Boston",+ "synthetic": true,+ "verification": "unverified"+ }+ },+ "synthetic": true,+ "title": "Hypothetical three-day Montreal trip"+ },+ "status": "completed",+ "warnings": []+ },+ "report": {+ "aborted": false,+ "devices": [+ {+ "capabilities": [+ "travel_research",+ "itinerary_planning"+ ],+ "id": "laptop",+ "kind": "laptop",+ "online": true+ },+ {+ "capabilities": [+ "mobile_context",+ "photo_interests",+ "calendar_availability",+ "save_draft"+ ],+ "id": "phone",+ "kind": "phone",+ "online": true+ }+ ],+ "events": [+ {+ "event": "dispatch",+ "request": {+ "attempt": 1,+ "capability": "mobile_context",+ "context": {},+ "from_device": "laptop",+ "input": {+ "request": "Make travel plans for me.",+ "synthetic": true+ },+ "task_id": "mobile_context",+ "timeout_ms": 5000,+ "to_device": "phone",+ "version": 1,+ "workflow_id": "travel-demo-001"+ }+ },+ {+ "event": "response",+ "response": {+ "attempt": 1,+ "device_id": "phone",+ "outcome": {+ "output": {+ "origin": "Boston",+ "synthetic": true,+ "timezone": "America/New_York"+ },+ "status": "succeeded"+ },+ "task_id": "mobile_context",+ "version": 1,+ "workflow_id": "travel-demo-001"+ }+ },+ {+ "event": "dispatch",+ "request": {+ "attempt": 1,+ "capability": "photo_interests",+ "context": {},+ "from_device": "laptop",+ "input": {+ "request": "Make travel plans for me.",+ "synthetic": true+ },+ "task_id": "photo_interests",+ "timeout_ms": 5000,+ "to_device": "phone",+ "version": 1,+ "workflow_id": "travel-demo-001"+ }+ },+ {+ "event": "response",+ "response": {+ "attempt": 1,+ "device_id": "phone",+ "outcome": {+ "output": {+ "interests": [+ "architecture",+ "parks"+ ],+ "synthetic": true+ },+ "status": "succeeded"+ },+ "task_id": "photo_interests",+ "version": 1,+ "workflow_id": "travel-demo-001"+ }+ },+ {+ "event": "dispatch",+ "request": {+ "attempt": 1,+ "capability": "calendar_availability",+ "context": {},+ "from_device": "laptop",+ "input": {+ "request": "Make travel plans for me.",+ "synthetic": true+ },+ "task_id": "calendar",+ "timeout_ms": 5000,+ "to_device": "phone",+ "version": 1,+ "workflow_id": "travel-demo-001"+ }+ },+ {+ "event": "response",+ "response": {+ "attempt": 1,+ "device_id": "phone",+ "outcome": {+ "output": {+ "available_dates": [+ "2026-10-16",+ "2026-10-17",+ "2026-10-18"+ ],+ "synthetic": true+ },+ "status": "succeeded"+ },+ "task_id": "calendar",+ "version": 1,+ "workflow_id": "travel-demo-001"+ }+ },+ {+ "event": "dispatch",+ "request": {+ "attempt": 1,+ "capability": "travel_research",+ "context": {+ "mobile_context": {+ "origin": "Boston",+ "synthetic": true,+ "timezone": "America/New_York"+ },+ "photo_interests": {+ "interests": [+ "architecture",+ "parks"+ ],+ "synthetic": true+ }+ },+ "from_device": "laptop",+ "input": {+ "destination": "Montreal",+ "synthetic": true+ },+ "task_id": "research",+ "timeout_ms": 5000,+ "to_device": "laptop",+ "version": 1,+ "workflow_id": "travel-demo-001"+ }+ },+ {+ "event": "response",+ "response": {+ "attempt": 1,+ "device_id": "laptop",+ "outcome": {+ "output": {+ "departure_origin": "Boston",+ "destination": "Montreal",+ "evidence": "Hypothetical fixture; no live research or cited sources",+ "interest_source": "synthetic_phone_summary",+ "interests": [+ "architecture",+ "parks"+ ],+ "lodging_options": [+ {+ "area": "Central area",+ "destination": "Montreal",+ "id": "fixture-central-stay",+ "synthetic": true,+ "verification": "unverified"+ }+ ],+ "lodging_research": "Compare central accommodation; availability and prices unverified",+ "transport_options": [+ {+ "destination": "Montreal",+ "id": "fixture-air",+ "mode": "air",+ "origin": "Boston",+ "synthetic": true,+ "verification": "unverified"+ },+ {+ "destination": "Montreal",+ "id": "fixture-rail",+ "mode": "rail",+ "origin": "Boston",+ "synthetic": true,+ "verification": "unverified"+ }+ ],+ "transport_research": "Compare transport from Boston to Montreal; schedules and fares unverified"+ },+ "status": "succeeded"+ },+ "task_id": "research",+ "version": 1,+ "workflow_id": "travel-demo-001"+ }+ },+ {+ "event": "dispatch",+ "request": {+ "attempt": 1,+ "capability": "itinerary_planning",+ "context": {+ "calendar": {+ "available_dates": [+ "2026-10-16",+ "2026-10-17",+ "2026-10-18"+ ],+ "synthetic": true+ },+ "mobile_context": {+ "origin": "Boston",+ "synthetic": true,+ "timezone": "America/New_York"+ },+ "research": {+ "departure_origin": "Boston",+ "destination": "Montreal",+ "evidence": "Hypothetical fixture; no live research or cited sources",+ "interest_source": "synthetic_phone_summary",+ "interests": [+ "architecture",+ "parks"+ ],+ "lodging_options": [+ {+ "area": "Central area",+ "destination": "Montreal",+ "id": "fixture-central-stay",+ "synthetic": true,+ "verification": "unverified"+ }+ ],+ "lodging_research": "Compare central accommodation; availability and prices unverified",+ "transport_options": [+ {+ "destination": "Montreal",+ "id": "fixture-air",+ "mode": "air",+ "origin": "Boston",+ "synthetic": true,+ "verification": "unverified"+ },+ {+ "destination": "Montreal",+ "id": "fixture-rail",+ "mode": "rail",+ "origin": "Boston",+ "synthetic": true,+ "verification": "unverified"+ }+ ],+ "transport_research": "Compare transport from Boston to Montreal; schedules and fares unverified"+ }+ },+ "from_device": "laptop",+ "input": {+ "model_profile": "large_local",+ "synthetic": true+ },+ "task_id": "plan",+ "timeout_ms": 5000,+ "to_device": "laptop",+ "version": 1,+ "workflow_id": "travel-demo-001"+ }+ },+ {+ "event": "response",+ "response": {+ "attempt": 1,+ "device_id": "laptop",+ "outcome": {+ "output": {+ "assumptions": [+ "Montreal is an illustrative destination",+ "No budget provided"+ ],+ "execution": {+ "backend": "mock",+ "model_profile": "large_local"+ },+ "itinerary": [+ {+ "activity": "Arrival and orientation",+ "date": "2026-10-16",+ "day": 1+ },+ {+ "activity": "Explore architecture in Montreal",+ "date": "2026-10-17",+ "day": 2+ },+ {+ "activity": "Explore parks; return travel",+ "date": "2026-10-18",+ "day": 3+ }+ ],+ "origin": "Boston",+ "research": {+ "departure_origin": "Boston",+ "destination": "Montreal",+ "evidence": "Hypothetical fixture; no live research or cited sources",+ "interest_source": "synthetic_phone_summary",+ "interests": [+ "architecture",+ "parks"+ ],+ "lodging_options": [+ {+ "area": "Central area",+ "destination": "Montreal",+ "id": "fixture-central-stay",+ "synthetic": true,+ "verification": "unverified"+ }+ ],+ "lodging_research": "Compare central accommodation; availability and prices unverified",+ "transport_options": [+ {+ "destination": "Montreal",+ "id": "fixture-air",+ "mode": "air",+ "origin": "Boston",+ "synthetic": true,+ "verification": "unverified"+ },+ {+ "destination": "Montreal",+ "id": "fixture-rail",+ "mode": "rail",+ "origin": "Boston",+ "synthetic": true,+ "verification": "unverified"+ }+ ],+ "transport_research": "Compare transport from Boston to Montreal; schedules and fares unverified"+ },+ "scheduling": {+ "dates": [+ "2026-10-16",+ "2026-10-17",+ "2026-10-18"+ ],+ "dates_status": "supported_by_synthetic_phone_availability",+ "next_steps": [+ "Confirm origin, dates, and interests",+ "Verify transport, lodging, and opening hours"+ ],+ "requires_user_confirmation": true+ },+ "selected_options": {+ "lodging": {+ "area": "Central area",+ "destination": "Montreal",+ "id": "fixture-central-stay",+ "synthetic": true,+ "verification": "unverified"+ },+ "transport": {+ "destination": "Montreal",+ "id": "fixture-air",+ "mode": "air",+ "origin": "Boston",+ "synthetic": true,+ "verification": "unverified"+ }+ },+ "synthetic": true,+ "title": "Hypothetical three-day Montreal trip"+ },+ "status": "succeeded"+ },+ "task_id": "plan",+ "version": 1,+ "workflow_id": "travel-demo-001"+ }+ },+ {+ "event": "dispatch",+ "request": {+ "attempt": 1,+ "capability": "save_draft",+ "context": {+ "plan": {+ "assumptions": [+ "Montreal is an illustrative destination",+ "No budget provided"+ ],+ "execution": {+ "backend": "mock",+ "model_profile": "large_local"+ },+ "itinerary": [+ {+ "activity": "Arrival and orientation",+ "date": "2026-10-16",+ "day": 1+ },+ {+ "activity": "Explore architecture in Montreal",+ "date": "2026-10-17",+ "day": 2+ },+ {+ "activity": "Explore parks; return travel",+ "date": "2026-10-18",+ "day": 3+ }+ ],+ "origin": "Boston",+ "research": {+ "departure_origin": "Boston",+ "destination": "Montreal",+ "evidence": "Hypothetical fixture; no live research or cited sources",+ "interest_source": "synthetic_phone_summary",+ "interests": [+ "architecture",+ "parks"+ ],+ "lodging_options": [+ {+ "area": "Central area",+ "destination": "Montreal",+ "id": "fixture-central-stay",+ "synthetic": true,+ "verification": "unverified"+ }+ ],+ "lodging_research": "Compare central accommodation; availability and prices unverified",+ "transport_options": [+ {+ "destination": "Montreal",+ "id": "fixture-air",+ "mode": "air",+ "origin": "Boston",+ "synthetic": true,+ "verification": "unverified"+ },+ {+ "destination": "Montreal",+ "id": "fixture-rail",+ "mode": "rail",+ "origin": "Boston",+ "synthetic": true,+ "verification": "unverified"+ }+ ],+ "transport_research": "Compare transport from Boston to Montreal; schedules and fares unverified"+ },+ "scheduling": {+ "dates": [+ "2026-10-16",+ "2026-10-17",+ "2026-10-18"+ ],+ "dates_status": "supported_by_synthetic_phone_availability",+ "next_steps": [+ "Confirm origin, dates, and interests",+ "Verify transport, lodging, and opening hours"+ ],+ "requires_user_confirmation": true+ },+ "selected_options": {+ "lodging": {+ "area": "Central area",+ "destination": "Montreal",+ "id": "fixture-central-stay",+ "synthetic": true,+ "verification": "unverified"+ },+ "transport": {+ "destination": "Montreal",+ "id": "fixture-air",+ "mode": "air",+ "origin": "Boston",+ "synthetic": true,+ "verification": "unverified"+ }+ },+ "synthetic": true,+ "title": "Hypothetical three-day Montreal trip"+ }+ },+ "from_device": "laptop",+ "input": {+ "request": "Make travel plans for me.",+ "synthetic": true+ },+ "task_id": "save_draft",+ "timeout_ms": 5000,+ "to_device": "phone",+ "version": 1,+ "workflow_id": "travel-demo-001"+ }+ },+ {+ "event": "response",+ "response": {+ "attempt": 1,+ "device_id": "phone",+ "outcome": {+ "output": {+ "bookings_made": false,+ "draft_id": "travel-demo-001:save_draft",+ "storage": "synthetic_in_memory"+ },+ "status": "succeeded"+ },+ "task_id": "save_draft",+ "version": 1,+ "workflow_id": "travel-demo-001"+ }+ }+ ],+ "results": {+ "calendar": {+ "output": {+ "available_dates": [+ "2026-10-16",+ "2026-10-17",+ "2026-10-18"+ ],+ "synthetic": true+ },+ "status": "succeeded"+ },+ "mobile_context": {+ "output": {+ "origin": "Boston",+ "synthetic": true,+ "timezone": "America/New_York"+ },+ "status": "succeeded"+ },+ "photo_interests": {+ "output": {+ "interests": [+ "architecture",+ "parks"+ ],+ "synthetic": true+ },+ "status": "succeeded"+ },+ "plan": {+ "output": {+ "assumptions": [+ "Montreal is an illustrative destination",+ "No budget provided"+ ],+ "execution": {+ "backend": "mock",+ "model_profile": "large_local"+ },+ "itinerary": [+ {+ "activity": "Arrival and orientation",+ "date": "2026-10-16",+ "day": 1+ },+ {+ "activity": "Explore architecture in Montreal",+ "date": "2026-10-17",+ "day": 2+ },+ {+ "activity": "Explore parks; return travel",+ "date": "2026-10-18",+ "day": 3+ }+ ],+ "origin": "Boston",+ "research": {+ "departure_origin": "Boston",+ "destination": "Montreal",+ "evidence": "Hypothetical fixture; no live research or cited sources",+ "interest_source": "synthetic_phone_summary",+ "interests": [+ "architecture",+ "parks"+ ],+ "lodging_options": [+ {+ "area": "Central area",+ "destination": "Montreal",+ "id": "fixture-central-stay",+ "synthetic": true,+ "verification": "unverified"+ }+ ],+ "lodging_research": "Compare central accommodation; availability and prices unverified",+ "transport_options": [+ {+ "destination": "Montreal",+ "id": "fixture-air",+ "mode": "air",+ "origin": "Boston",+ "synthetic": true,+ "verification": "unverified"+ },+ {+ "destination": "Montreal",+ "id": "fixture-rail",+ "mode": "rail",+ "origin": "Boston",+ "synthetic": true,+ "verification": "unverified"+ }+ ],+ "transport_research": "Compare transport from Boston to Montreal; schedules and fares unverified"+ },+ "scheduling": {+ "dates": [+ "2026-10-16",+ "2026-10-17",+ "2026-10-18"+ ],+ "dates_status": "supported_by_synthetic_phone_availability",+ "next_steps": [+ "Confirm origin, dates, and interests",+ "Verify transport, lodging, and opening hours"+ ],+ "requires_user_confirmation": true+ },+ "selected_options": {+ "lodging": {+ "area": "Central area",+ "destination": "Montreal",+ "id": "fixture-central-stay",+ "synthetic": true,+ "verification": "unverified"+ },+ "transport": {+ "destination": "Montreal",+ "id": "fixture-air",+ "mode": "air",+ "origin": "Boston",+ "synthetic": true,+ "verification": "unverified"+ }+ },+ "synthetic": true,+ "title": "Hypothetical three-day Montreal trip"+ },+ "status": "succeeded"+ },+ "research": {+ "output": {+ "departure_origin": "Boston",+ "destination": "Montreal",+ "evidence": "Hypothetical fixture; no live research or cited sources",+ "interest_source": "synthetic_phone_summary",+ "interests": [+ "architecture",+ "parks"+ ],+ "lodging_options": [+ {+ "area": "Central area",+ "destination": "Montreal",+ "id": "fixture-central-stay",+ "synthetic": true,+ "verification": "unverified"+ }+ ],+ "lodging_research": "Compare central accommodation; availability and prices unverified",+ "transport_options": [+ {+ "destination": "Montreal",+ "id": "fixture-air",+ "mode": "air",+ "origin": "Boston",+ "synthetic": true,+ "verification": "unverified"+ },+ {+ "destination": "Montreal",+ "id": "fixture-rail",+ "mode": "rail",+ "origin": "Boston",+ "synthetic": true,+ "verification": "unverified"+ }+ ],+ "transport_research": "Compare transport from Boston to Montreal; schedules and fares unverified"+ },+ "status": "succeeded"+ },+ "save_draft": {+ "output": {+ "bookings_made": false,+ "draft_id": "travel-demo-001:save_draft",+ "storage": "synthetic_in_memory"+ },+ "status": "succeeded"+ }+ },+ "tasks": [+ {+ "capability": "mobile_context",+ "depends_on": [],+ "device_kind": "phone",+ "id": "mobile_context",+ "input": {+ "request": "Make travel plans for me.",+ "synthetic": true+ },+ "optional": true+ },+ {+ "capability": "photo_interests",+ "depends_on": [],+ "device_kind": "phone",+ "id": "photo_interests",+ "input": {+ "request": "Make travel plans for me.",+ "synthetic": true+ },+ "optional": true+ },+ {+ "capability": "calendar_availability",+ "depends_on": [],+ "device_kind": "phone",+ "id": "calendar",+ "input": {+ "request": "Make travel plans for me.",+ "synthetic": true+ },+ "optional": true+ },+ {+ "capability": "travel_research",+ "depends_on": [+ "mobile_context",+ "photo_interests"+ ],+ "device_kind": "laptop",+ "id": "research",+ "input": {+ "destination": "Montreal",+ "synthetic": true+ },+ "optional": false+ },+ {+ "capability": "itinerary_planning",+ "depends_on": [+ "mobile_context",+ "calendar",+ "research"+ ],+ "device_kind": "laptop",+ "id": "plan",+ "input": {+ "model_profile": "large_local",+ "synthetic": true+ },+ "optional": false+ },+ {+ "capability": "save_draft",+ "depends_on": [+ "plan"+ ],+ "device_kind": "phone",+ "id": "save_draft",+ "input": {+ "request": "Make travel plans for me.",+ "synthetic": true+ },+ "optional": true+ }+ ],+ "workflow_id": "travel-demo-001"+ }+}