From aa9a2eaabc26da1de74643e5c39c9de4318836bd Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 02:54:33 +0530 Subject: [PATCH 01/73] feat(engine): expose task-scoped usage recorder Co-authored-by: Medulla --- crates/tinycomputer-bus/src/agent/mod.rs | 4 +- .../tinycomputer-bus/src/agent/types/mod.rs | 2 + .../tinycomputer-bus/src/agent/types/usage.rs | 98 +++++++++++++++ .../src/agent/types/usage_tests.rs | 40 ++++++ .../src/agentic/agentic_tests.rs | 1 + .../src/agentic/flow/flow_tests.rs | 2 + .../agentic/flow/flow_tests/hedge_tests.rs | 1 + .../src/agentic/runtime.rs | 51 +++++++- crates/tinycomputer-engine/src/lib.rs | 2 + crates/tinycomputer-engine/src/usage.rs | 114 ++++++++++++++++++ crates/tinycomputer-engine/src/usage_tests.rs | 20 +++ 11 files changed, 332 insertions(+), 3 deletions(-) create mode 100644 crates/tinycomputer-bus/src/agent/types/usage.rs create mode 100644 crates/tinycomputer-bus/src/agent/types/usage_tests.rs create mode 100644 crates/tinycomputer-engine/src/usage.rs create mode 100644 crates/tinycomputer-engine/src/usage_tests.rs diff --git a/crates/tinycomputer-bus/src/agent/mod.rs b/crates/tinycomputer-bus/src/agent/mod.rs index f93f96a43..69b8dcf99 100644 --- a/crates/tinycomputer-bus/src/agent/mod.rs +++ b/crates/tinycomputer-bus/src/agent/mod.rs @@ -53,9 +53,9 @@ mod types; pub use types::{ AgentError, AgentResponse, AwaitTaskRequest, Capabilities, ContinueTaskRequest, Example, InputField, InputKind, LanguageModelConfiguration, LanguageModelProvider, MemberDoc, - PaymentMode, PlanTaskRequest, Rescue, RescueOutcome, StartTaskRequest, StepView, + ModelUsage, PaymentMode, PlanTaskRequest, Rescue, RescueOutcome, StartTaskRequest, StepView, SurfaceAvailability, SurfaceKind, TaskBudget, TaskConstraints, TaskId, TaskOutput, TaskPlan, - TaskRef, TaskReport, TaskReportRequest, TaskStatus, TaskView, + TaskRef, TaskReport, TaskReportRequest, TaskStatus, TaskUsage, TaskView, }; #[cfg(test)] diff --git a/crates/tinycomputer-bus/src/agent/types/mod.rs b/crates/tinycomputer-bus/src/agent/types/mod.rs index 3c3a10a8e..576713c1f 100644 --- a/crates/tinycomputer-bus/src/agent/types/mod.rs +++ b/crates/tinycomputer-bus/src/agent/types/mod.rs @@ -6,6 +6,7 @@ mod reply; mod report; mod request; mod status; +mod usage; pub use describe::{Capabilities, Example, MemberDoc, SurfaceAvailability}; pub use models::{LanguageModelConfiguration, LanguageModelProvider}; @@ -17,3 +18,4 @@ pub use request::{ TaskReportRequest, }; pub use status::{InputField, InputKind, StepView, TaskStatus, TaskView}; +pub use usage::{ModelUsage, TaskUsage}; diff --git a/crates/tinycomputer-bus/src/agent/types/usage.rs b/crates/tinycomputer-bus/src/agent/types/usage.rs new file mode 100644 index 000000000..cc7218969 --- /dev/null +++ b/crates/tinycomputer-bus/src/agent/types/usage.rs @@ -0,0 +1,98 @@ +//! Provider-reported model usage accumulated by task and model role. + +use serde::{Deserialize, Serialize}; + +/// Model calls and the usage their providers reported for one task role. +/// +/// Token and cost values stay absent when no provider supplied them. Costs are +/// integer micro-units in the provider's reported currency; this crate does +/// not infer prices from token counts. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ModelUsage { + /// Model requests made, including calls whose usage was not reported. + #[serde(default)] + pub calls: u64, + /// Provider-reported input tokens, when available. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub input_tokens: Option, + /// Provider-reported cached input tokens, when available. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cached_input_tokens: Option, + /// Provider-reported output tokens, when available. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output_tokens: Option, + /// Provider-reported USD charge in integer micro-dollars, when available. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cost_usd_micros: Option, +} + +/// Per-role model usage accumulated over a task's lifetime. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TaskUsage { + /// TypeSafe/Jev decision calls. + #[serde(default, skip_serializing_if = "ModelUsage::is_empty")] + pub jev: ModelUsage, + /// Calls that turn the task description into a flow. + #[serde(default, skip_serializing_if = "ModelUsage::is_empty")] + pub planner: ModelUsage, + /// Calls that recover a failed flow step. + #[serde(default, skip_serializing_if = "ModelUsage::is_empty")] + pub rescue: ModelUsage, + /// Calls that shape extracted records into the requested answer. + #[serde(default, skip_serializing_if = "ModelUsage::is_empty")] + pub output: ModelUsage, +} + +impl TaskUsage { + /// Whether no role has recorded calls or provider-reported measurements. + #[must_use] + pub const fn is_empty(&self) -> bool { + self.jev.is_empty() + && self.planner.is_empty() + && self.rescue.is_empty() + && self.output.is_empty() + } +} + +impl ModelUsage { + /// Whether no calls or provider-reported measurements have been recorded. + #[must_use] + pub const fn is_empty(&self) -> bool { + self.calls == 0 + && self.input_tokens.is_none() + && self.cached_input_tokens.is_none() + && self.output_tokens.is_none() + && self.cost_usd_micros.is_none() + } + + /// Adds one request and any measurements its provider returned. + pub fn record( + &mut self, + input_tokens: Option, + cached_input_tokens: Option, + output_tokens: Option, + cost_usd_micros: Option, + ) { + self.calls = self.calls.saturating_add(1); + add_unsigned(&mut self.input_tokens, input_tokens); + add_unsigned(&mut self.cached_input_tokens, cached_input_tokens); + add_unsigned(&mut self.output_tokens, output_tokens); + if let Some(cost) = cost_usd_micros { + self.cost_usd_micros = Some( + self.cost_usd_micros + .unwrap_or_default() + .saturating_add(cost), + ); + } + } +} + +fn add_unsigned(total: &mut Option, value: Option) { + if let Some(value) = value { + *total = Some(total.unwrap_or_default().saturating_add(value)); + } +} + +#[cfg(test)] +#[path = "usage_tests.rs"] +mod tests; diff --git a/crates/tinycomputer-bus/src/agent/types/usage_tests.rs b/crates/tinycomputer-bus/src/agent/types/usage_tests.rs new file mode 100644 index 000000000..42528aa7f --- /dev/null +++ b/crates/tinycomputer-bus/src/agent/types/usage_tests.rs @@ -0,0 +1,40 @@ +//! Serialization and accumulation tests for task model usage. + +use super::*; +use serde_json::json; + +#[test] +fn keeps_unreported_usage_unknown_and_accumulates_reported_values() { + let mut usage = ModelUsage::default(); + usage.record(Some(10), Some(4), Some(3), Some(12)); + usage.record(None, None, None, None); + usage.record(Some(8), Some(2), Some(5), Some(7)); + + assert_eq!(usage.calls, 3); + assert_eq!(usage.input_tokens, Some(18)); + assert_eq!(usage.cached_input_tokens, Some(6)); + assert_eq!(usage.output_tokens, Some(8)); + assert_eq!(usage.cost_usd_micros, Some(19)); +} + +#[test] +fn omits_unreported_measurements_from_the_wire() { + assert_eq!( + serde_json::to_value(TaskUsage { + jev: ModelUsage { + calls: 1, + ..ModelUsage::default() + }, + ..TaskUsage::default() + }) + .unwrap(), + json!({"jev": {"calls": 1}}) + ); + assert_eq!( + serde_json::from_value::(json!({"calls": 1})).unwrap(), + ModelUsage { + calls: 1, + ..ModelUsage::default() + } + ); +} diff --git a/crates/tinycomputer-engine/src/agentic/agentic_tests.rs b/crates/tinycomputer-engine/src/agentic/agentic_tests.rs index df4f071b6..c07477710 100644 --- a/crates/tinycomputer-engine/src/agentic/agentic_tests.rs +++ b/crates/tinycomputer-engine/src/agentic/agentic_tests.rs @@ -366,6 +366,7 @@ fn runtime_recording( pending: Arc::new(Mutex::new(std::collections::HashMap::new())), journal: super::journal::Journal::default(), copies: Arc::default(), + usage: None, }, requests, ) diff --git a/crates/tinycomputer-engine/src/agentic/flow/flow_tests.rs b/crates/tinycomputer-engine/src/agentic/flow/flow_tests.rs index b09e41315..66ef66121 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/flow_tests.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/flow_tests.rs @@ -95,6 +95,7 @@ fn runtime(client: impl Evaluator + 'static) -> JevRuntime { pending: Arc::default(), journal: crate::agentic::journal::Journal::default(), copies: Arc::default(), + usage: None, } } @@ -127,6 +128,7 @@ async fn run_with( pending: Arc::default(), journal: crate::agentic::journal::Journal::default(), copies: Arc::default(), + usage: None, }; // One framing per decision, so every test that counts requests counts // decisions; voting has its own tests. diff --git a/crates/tinycomputer-engine/src/agentic/flow/flow_tests/hedge_tests.rs b/crates/tinycomputer-engine/src/agentic/flow/flow_tests/hedge_tests.rs index 7cae6c42e..2ff682acb 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/flow_tests/hedge_tests.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/flow_tests/hedge_tests.rs @@ -72,6 +72,7 @@ fn paced_as( pending: Arc::default(), journal: crate::agentic::journal::Journal::default(), copies: Arc::default(), + usage: None, }; (runtime, paced) } diff --git a/crates/tinycomputer-engine/src/agentic/runtime.rs b/crates/tinycomputer-engine/src/agentic/runtime.rs index 41c7bb098..cca25ab32 100644 --- a/crates/tinycomputer-engine/src/agentic/runtime.rs +++ b/crates/tinycomputer-engine/src/agentic/runtime.rs @@ -19,6 +19,7 @@ use super::flow::MAX_VOTES; use super::journal::Journal; use super::pending::PendingRun; use super::sage; +use crate::{ModelRole, UsageRecorder}; /// How a Jev call retries a provider's server error or rate limit when the /// configuration does not say: four more attempts, waiting 1, 2, 4, then 8 @@ -54,6 +55,8 @@ pub struct JevRuntime { /// Hedged copies of framings in flight, shared by every flow run on /// this runtime. pub(super) copies: Arc, + /// Optional task-scoped collector, set by an embedding host's runner. + pub(super) usage: Option>, } impl std::fmt::Debug for JevRuntime { @@ -80,7 +83,30 @@ impl JevRuntime { /// Returns a `JEV_INVALID_CONFIG` [`DesktopError`] when the provider, /// endpoint, or credentials in `request` cannot form a trusted client. pub fn configure(request: &JevConfig) -> Result> { - if let Some(endpoint) = &request.endpoint_url + Self::configure_inner(request, false) + } + + /// Build a Jev runtime for an embedding host, allowing the host to route + /// its configured provider to a private endpoint. + /// + /// The TinyBus module uses [`JevRuntime::configure`], which retains the + /// module's provider allow-list. This constructor is for Rust hosts that + /// own and trust their configuration. + /// + /// # Errors + /// + /// Returns `JEV_INVALID_CONFIG` when the provider or credentials cannot + /// form a client. + pub fn configure_for_host(request: &JevConfig) -> Result> { + Self::configure_inner(request, true) + } + + fn configure_inner( + request: &JevConfig, + allow_custom_endpoint: bool, + ) -> Result> { + if !allow_custom_endpoint + && let Some(endpoint) = &request.endpoint_url && !trusted_endpoint(request.provider, endpoint) { return Err(Box::new(DesktopError::new( @@ -111,6 +137,7 @@ impl JevRuntime { pending: Arc::new(Mutex::new(HashMap::new())), journal: Journal::from_env(), copies: Arc::default(), + usage: None, }) } @@ -154,6 +181,7 @@ impl JevRuntime { pending: Arc::new(Mutex::new(HashMap::new())), journal: Journal::from_env(), copies: Arc::default(), + usage: None, }) } @@ -164,6 +192,13 @@ impl JevRuntime { &self.configuration } + /// This runtime recording Jev usage into a task-scoped collector. + #[must_use] + pub fn with_usage_recorder(mut self, usage: Arc) -> Self { + self.usage = Some(usage); + self + } + /// This runtime with the debug journal written under `dir`, whatever /// [`JOURNAL_ENV`](crate::JOURNAL_ENV) says. /// @@ -264,7 +299,21 @@ impl JevRuntime { step: Option<&str>, request: &EvaluationRequest, ) -> std::result::Result { + if let Some(usage) = &self.usage { + usage.record_started(ModelRole::Jev); + } let outcome = self.client.evaluate(request).await; + if let Some(usage) = &self.usage { + if let Ok(result) = &outcome { + usage.record_measurements( + ModelRole::Jev, + result.response.usage.input_tokens, + None, + result.response.usage.output_tokens, + None, + ); + } + } self.journal.exchange(step, request, outcome.as_ref()); outcome } diff --git a/crates/tinycomputer-engine/src/lib.rs b/crates/tinycomputer-engine/src/lib.rs index d4786a892..59f6a9447 100644 --- a/crates/tinycomputer-engine/src/lib.rs +++ b/crates/tinycomputer-engine/src/lib.rs @@ -35,6 +35,7 @@ mod planner; mod rescue; mod shape; mod task; +mod usage; mod workspace; pub use agentic::{ @@ -55,4 +56,5 @@ pub use task::{ }; pub use tinycomputer_bus::DesktopResponse; use tinycomputer_desktop::Desktop; +pub use usage::{ModelRole, UsageRecorder}; pub use workspace::{BROWSER, Workspace}; diff --git a/crates/tinycomputer-engine/src/usage.rs b/crates/tinycomputer-engine/src/usage.rs new file mode 100644 index 000000000..b3add1758 --- /dev/null +++ b/crates/tinycomputer-engine/src/usage.rs @@ -0,0 +1,114 @@ +//! Per-task model usage collection shared by model adapters. + +use std::sync::Mutex; + +use tinycomputer_bus::agent::{ModelUsage, TaskUsage}; + +/// The model role whose provider-reported usage is being recorded. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ModelRole { + /// TypeSafe/Jev decisions. + Jev, + /// Plain-language task planning. + Planner, + /// Recovery guidance after a failed step. + Rescue, + /// Shaping extracted data into a requested answer. + Output, +} + +/// Thread-safe, per-task accumulator for provider-reported model usage. +/// +/// A task owns one recorder and passes it to every model adapter it uses. +/// Missing provider measurements remain absent; this type never estimates +/// tokens or cost. +#[derive(Debug, Default)] +pub struct UsageRecorder { + usage: Mutex, +} + +impl UsageRecorder { + /// Records one model call for `role`, retaining only reported values. + pub fn record_call( + &self, + role: ModelRole, + input_tokens: Option, + cached_input_tokens: Option, + output_tokens: Option, + cost_usd_micros: Option, + ) { + self.record_started(role); + self.record_measurements( + role, + input_tokens, + cached_input_tokens, + output_tokens, + cost_usd_micros, + ); + } + + /// Records that a model request started, even if it is later cancelled. + pub fn record_started(&self, role: ModelRole) { + let mut usage = self + .usage + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let role = role_usage(&mut usage, role); + role.calls = role.calls.saturating_add(1); + } + + /// Adds provider measurements for a request already counted with + /// [`UsageRecorder::record_started`]. + pub fn record_measurements( + &self, + role: ModelRole, + input_tokens: Option, + cached_input_tokens: Option, + output_tokens: Option, + cost_usd_micros: Option, + ) { + let mut usage = self + .usage + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let role = role_usage(&mut usage, role); + add_unsigned(&mut role.input_tokens, input_tokens); + add_unsigned(&mut role.cached_input_tokens, cached_input_tokens); + add_unsigned(&mut role.output_tokens, output_tokens); + if let Some(cost) = cost_usd_micros { + role.cost_usd_micros = Some( + role.cost_usd_micros + .unwrap_or_default() + .saturating_add(cost), + ); + } + } + + /// Returns the usage accumulated so far. + #[must_use] + pub fn snapshot(&self) -> TaskUsage { + *self + .usage + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } +} + +fn role_usage(usage: &mut TaskUsage, role: ModelRole) -> &mut ModelUsage { + match role { + ModelRole::Jev => &mut usage.jev, + ModelRole::Planner => &mut usage.planner, + ModelRole::Rescue => &mut usage.rescue, + ModelRole::Output => &mut usage.output, + } +} + +fn add_unsigned(total: &mut Option, value: Option) { + if let Some(value) = value { + *total = Some(total.unwrap_or_default().saturating_add(value)); + } +} + +#[cfg(test)] +#[path = "usage_tests.rs"] +mod tests; diff --git a/crates/tinycomputer-engine/src/usage_tests.rs b/crates/tinycomputer-engine/src/usage_tests.rs new file mode 100644 index 000000000..07cd48144 --- /dev/null +++ b/crates/tinycomputer-engine/src/usage_tests.rs @@ -0,0 +1,20 @@ +//! Per-task usage recorder tests. + +use super::{ModelRole, UsageRecorder}; + +#[test] +fn snapshots_only_reported_measurements_and_counts_unknown_calls() { + let recorder = UsageRecorder::default(); + recorder.record_started(ModelRole::Jev); + recorder.record_measurements(ModelRole::Jev, Some(8), None, Some(3), None); + recorder.record_call(ModelRole::Planner, None, None, None, None); + + let usage = recorder.snapshot(); + assert_eq!(usage.jev.calls, 1); + assert_eq!(usage.jev.input_tokens, Some(8)); + assert_eq!(usage.jev.cached_input_tokens, None); + assert_eq!(usage.jev.output_tokens, Some(3)); + assert_eq!(usage.jev.cost_usd_micros, None); + assert_eq!(usage.planner.calls, 1); + assert_eq!(usage.planner.input_tokens, None); +} From 0611c2af50bbfe01a2d23811387fb2d2bd880d0c Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 02:55:00 +0530 Subject: [PATCH 02/73] feat(engine): export browser-only task runner Co-authored-by: Medulla --- crates/tinycomputer-engine/src/lib.rs | 33 ++++++++++++++------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/crates/tinycomputer-engine/src/lib.rs b/crates/tinycomputer-engine/src/lib.rs index d4786a892..e146886f7 100644 --- a/crates/tinycomputer-engine/src/lib.rs +++ b/crates/tinycomputer-engine/src/lib.rs @@ -1,7 +1,8 @@ //! The tinycomputer agent runtime. //! -//! This crate composes the surface adapters with Jev, `TypeSafe`'s decision -//! model, into the loops a caller drives through the module: +//! This crate composes the browser and optional desktop surface adapters with +//! Jev, `TypeSafe`'s decision model, into loops an embedding host can call +//! directly or serve through the module: //! //! - [`resolve_intent`] grounds one described element and optionally acts on //! it; @@ -12,9 +13,9 @@ //! - [`validate_flow`] and [`flow_guide`] check and document flows without //! touching the desktop. //! -//! Every entry point returns a [`DesktopResponse`] envelope, never a `Result`, -//! for the reasons `tinycomputer-desktop` documents. A [`JevRuntime`] is built -//! once from the module's private configuration and cloned per call. +//! Every decision-loop entry point returns a [`DesktopResponse`] envelope. +//! A [`JevRuntime`] is built once from the host's configuration and cloned per +//! call. //! //! [`Tasks`] is the controller behind the Agent interface: it runs a task's //! flow in the background and reports it as a status a model can act on, @@ -22,13 +23,13 @@ //! With a [`Rescuer`], a failed step is first handed to a reasoning model //! for guidance, up to five times a task (`docs/technical/specs/task-rescue.md`). //! -//! A [`Workspace`] joins the desktop and the browser into one surface, so a -//! flow's `browse` and `open` steps move it between a web page and an -//! application. +//! A [`Workspace`] joins desktop and browser when the default `desktop` +//! feature is enabled. A [`BrowserRunner`] runs the public [`Tasks`] manager +//! directly on browser sessions without TinyBus or a desktop adapter. //! -//! The crate holds no bus: `tinycomputer` serves these functions over `TinyBus`. -//! The browser surface and the task controller arrive here next -//! (`docs/technical/specs/unified-agent.md`). +//! The crate holds no bus: `tinycomputer` may serve these functions over +//! TinyBus, while embedding hosts can call the runner and task manager in +//! process. mod agentic; mod planner; @@ -38,9 +39,10 @@ mod task; mod workspace; pub use agentic::{ - JOURNAL_DEFAULT_DIR, JOURNAL_ENV, JOURNAL_FILE, JevRuntime, flow_guide, resolve_intent, - run_flow, run_goal, validate_flow, + JOURNAL_DEFAULT_DIR, JOURNAL_ENV, JOURNAL_FILE, JevRuntime, flow_guide, run_flow, validate_flow, }; +#[cfg(feature = "desktop")] +pub use agentic::{resolve_intent, run_goal}; pub use planner::{Completion, LanguageModel, ModelUse, Planner, REPAIRS, Role, Turn}; #[cfg(feature = "planner")] pub use planner::{ @@ -50,9 +52,8 @@ pub use planner::{ pub use rescue::{Briefing, Guidance, MAX_RESCUE_STEPS, MAX_RESCUES, Rescuer, SCREEN_CHARS}; pub use shape::{Harvest, RECORDS_CHARS, Shaper}; pub use task::{ - CaptureFuture, FlowFuture, FlowRunner, MAX_AWAIT_MS, MAX_TASKS, PrepareFuture, Tasks, - TextFuture, capabilities, + BrowserRunner, CaptureFuture, FlowFuture, FlowRunner, MAX_AWAIT_MS, MAX_TASKS, PrepareFuture, + Tasks, TextFuture, capabilities, }; pub use tinycomputer_bus::DesktopResponse; -use tinycomputer_desktop::Desktop; pub use workspace::{BROWSER, Workspace}; From 1f8df057bfdde3f9822e2a46bc28c22af79a5e14 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 03:05:17 +0530 Subject: [PATCH 03/73] feat(tinycomputer-browser): add host action gate Co-authored-by: Medulla --- .../tinycomputer-browser/src/action_gate.rs | 183 +++++++++++++++++ crates/tinycomputer-browser/src/error/mod.rs | 13 +- crates/tinycomputer-browser/src/lib.rs | 7 + .../tinycomputer-browser/src/sessions/mod.rs | 60 +++++- .../tinycomputer-browser/src/sessions/page.rs | 62 +++++- .../src/sessions/sessions_tests/page_tests.rs | 193 +++++++++++++++++- .../tinycomputer-browser/src/surface/mod.rs | 19 +- 7 files changed, 527 insertions(+), 10 deletions(-) create mode 100644 crates/tinycomputer-browser/src/action_gate.rs diff --git a/crates/tinycomputer-browser/src/action_gate.rs b/crates/tinycomputer-browser/src/action_gate.rs new file mode 100644 index 000000000..6c734ea32 --- /dev/null +++ b/crates/tinycomputer-browser/src/action_gate.rs @@ -0,0 +1,183 @@ +//! Host policy for actions sent to a browser page. + +use std::sync::Arc; + +use serde_json::Value; +use tinycomputer_bus::browser::{Action, ElementRef, Target}; + +/// Per-task facts supplied by the host when it creates a browser surface. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ActionContext { + /// The task that is driving the page, when there is one. + pub task_id: Option, + /// Whether payment handling is in play for the task. + pub payment_in_play: bool, +} + +/// A target resolved as far as the latest accessibility snapshot allows. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ActionTarget { + /// The element's accessibility role, when known. + pub role: Option, + /// The element's accessible name, when known. + pub name: Option, + /// The snapshot ref used to identify the element, when known. + pub reference: Option, +} + +/// Information a trusted host may inspect before the browser acts. +/// +/// `payload` contains the requested action and its value, including typed +/// text. It is intentionally omitted from `Debug`; implementations must treat +/// it as confidential and must not log or persist it. +pub struct ActionRequest { + /// The typed or raw browser action, including values sent to the page. + pub payload: Value, + /// The resolved semantic target, if the request names one. + pub target: Option, + /// The page's actual current URL immediately before the request. + pub current_url: String, + /// The requested destination for a navigation, when applicable. + pub destination_url: Option, + /// Host-supplied task context. + pub context: ActionContext, +} + +impl ActionRequest { + pub(crate) fn typed( + action: &Action, + current_url: String, + destination_url: Option, + context: &ActionContext, + refs: &[ElementRef], + ) -> Self { + let payload = serde_json::to_value(action).unwrap_or(Value::Null); + let target = action_target(action, refs); + Self { + payload, + target, + current_url, + destination_url, + context: context.clone(), + } + } + + pub(crate) fn raw( + payload: Value, + current_url: String, + destination_url: Option, + context: &ActionContext, + refs: &[ElementRef], + ) -> Self { + let target = payload + .get("selector") + .and_then(Value::as_str) + .and_then(|selector| resolve_target(selector, refs)); + Self { + payload, + target, + current_url, + destination_url, + context: context.clone(), + } + } +} + +impl std::fmt::Debug for ActionRequest { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("ActionRequest") + .field( + "action", + &self.payload.get("action").and_then(Value::as_str), + ) + .field("target", &self.target) + .field("current_url", &self.current_url) + .field("destination_url", &self.destination_url) + .field("context", &self.context) + .finish_non_exhaustive() + } +} + +/// The host's decision for one action. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ActionVerdict { + /// Let the browser perform the request. + Allow, + /// Refuse it before any page interaction occurs. + Refuse { + /// A short explanation safe to show in task reports. Do not include + /// the request value in this message. + reason: String, + }, +} + +/// A synchronous host policy consulted before every typed or raw action. +pub trait ActionGate: Send + Sync { + /// Decide whether this request may reach the page. + fn check(&self, request: &ActionRequest) -> ActionVerdict; +} + +/// A gate that leaves browser behavior unchanged. +#[derive(Debug, Default)] +pub struct AllowAllActions; + +impl ActionGate for AllowAllActions { + fn check(&self, _request: &ActionRequest) -> ActionVerdict { + ActionVerdict::Allow + } +} + +pub(crate) fn default_gate() -> Arc { + Arc::new(AllowAllActions) +} + +fn action_target(action: &Action, refs: &[ElementRef]) -> Option { + let target = match action { + Action::Click { target, .. } + | Action::DoubleClick { target } + | Action::Hover { target } + | Action::Focus { target } + | Action::Fill { target, .. } + | Action::Select { target, .. } + | Action::Check { target, .. } + | Action::GetText { target } + | Action::GetAttribute { target, .. } + | Action::IsVisible { target } => Some(target), + Action::Type { target, .. } + | Action::Press { target, .. } + | Action::Scroll { target, .. } + | Action::WaitFor { target, .. } => target.as_ref(), + Action::Back | Action::Forward | Action::Reload => None, + }?; + target_from_target(target, refs) +} + +fn target_from_target(target: &Target, refs: &[ElementRef]) -> Option { + match target { + Target::Ref { value } | Target::Selector { value } => resolve_target(value, refs), + Target::Locator { value } if value.by == tinycomputer_bus::browser::LocateBy::Role => { + Some(ActionTarget { + role: Some(value.value.clone()), + name: value.name.clone(), + reference: None, + }) + } + Target::Locator { value } => Some(ActionTarget { + role: None, + name: Some(value.value.clone()), + reference: None, + }), + } +} + +fn resolve_target(value: &str, refs: &[ElementRef]) -> Option { + let reference = value.strip_prefix('@').unwrap_or(value); + refs.iter() + .find(|item| item.id == reference) + .map(|item| ActionTarget { + role: Some(item.role.clone()), + name: Some(item.name.clone()), + reference: Some(item.id.clone()), + }) +} diff --git a/crates/tinycomputer-browser/src/error/mod.rs b/crates/tinycomputer-browser/src/error/mod.rs index 258409d3e..c0a8385fc 100644 --- a/crates/tinycomputer-browser/src/error/mod.rs +++ b/crates/tinycomputer-browser/src/error/mod.rs @@ -98,6 +98,13 @@ pub enum Error { url: String, }, + /// The trusted host's action policy refused a request before it reached the page. + #[error("action refused by host: {reason}")] + ActionRefused { + /// The host's refusal reason. + reason: String, + }, + /// No browser could be launched or reached. #[error("browser unavailable: {message}")] BrowserUnavailable { @@ -175,7 +182,7 @@ impl Error { Self::PageError { .. } => errors::PAGE_ERROR, Self::NoSuchOutput { .. } => errors::NO_SUCH_OUTPUT, Self::LimitExceeded { .. } => errors::LIMIT_EXCEEDED, - Self::ModuleFailed { .. } => errors::MODULE_FAILED, + Self::ActionRefused { .. } | Self::ModuleFailed { .. } => errors::MODULE_FAILED, } } @@ -243,6 +250,9 @@ impl Error { Self::LimitExceeded { .. } => { Some("close sessions or release outputs you no longer need") } + Self::ActionRefused { .. } => { + Some("follow the host policy before retrying this action") + } Self::InvalidInput { .. } | Self::Timeout { .. } | Self::BrowserUnavailable { .. } @@ -268,6 +278,7 @@ impl Error { | Self::NoSuchOutput { .. } | Self::StaleRef { .. } | Self::BlockedByPolicy { .. } + | Self::ActionRefused { .. } ) } diff --git a/crates/tinycomputer-browser/src/lib.rs b/crates/tinycomputer-browser/src/lib.rs index f42cc376b..a5e7ec3ae 100644 --- a/crates/tinycomputer-browser/src/lib.rs +++ b/crates/tinycomputer-browser/src/lib.rs @@ -20,6 +20,9 @@ //! engine's decision loops drive a web page as they drive a desktop app. //! When the session has a window on screen it glides the agent's //! [`ScreenCursor`] onto each target; the cursor is cosmetic. +//! - [`ActionGate`] — an optional synchronous host policy called before typed +//! actions, raw commands, evaluations, and navigations. Requests expose +//! values to the trusted host callback; their `Debug` output omits values. //! - `AgentBrowser` (feature `agent-browser`) — the [`Launcher`] for //! agent-browser linked in-process. //! - [`Error`] — what can go wrong, as a taxonomy of what a caller should do @@ -29,6 +32,7 @@ //! Every browser contract type is re-exported, so `tinycomputer_browser::Action` //! is the same type as `tinycomputer_bus::browser::Action`. +mod action_gate; mod convert; mod deep; mod engine; @@ -44,6 +48,9 @@ mod reply; mod sessions; mod surface; +pub use action_gate::{ + ActionContext, ActionGate, ActionRequest, ActionTarget, ActionVerdict, AllowAllActions, +}; pub use engine::{Engine, Launcher, Reply}; pub use error::{Error, Result}; #[cfg(feature = "agent-browser")] diff --git a/crates/tinycomputer-browser/src/sessions/mod.rs b/crates/tinycomputer-browser/src/sessions/mod.rs index cae18cadb..f032ce97a 100644 --- a/crates/tinycomputer-browser/src/sessions/mod.rs +++ b/crates/tinycomputer-browser/src/sessions/mod.rs @@ -10,8 +10,11 @@ use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use serde_json::{Value, json}; +use tinycomputer_bus::browser::ElementRef; use tinycomputer_bus::browser::{DownloadInfo, PageState, SessionId, SessionInfo, SessionOptions}; +use crate::action_gate::{ActionContext, ActionGate, default_gate}; +use crate::action_gate::{ActionRequest, ActionVerdict}; use crate::convert; use crate::engine::{Engine, Launcher}; use crate::error::{Error, Result}; @@ -47,7 +50,6 @@ fn navigating(error: &Error) -> bool { } /// Browser automation over agent-browser, one engine per session. -#[derive(Debug)] pub struct Browser { launcher: Arc, sessions: Mutex>>>, @@ -58,6 +60,20 @@ pub struct Browser { /// the moment the limit is checked, so two concurrent opens cannot both /// see room for the last slot. opening: AtomicUsize, + action_gate: Arc, +} + +impl std::fmt::Debug for Browser { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("Browser") + .field("scratch", &self.scratch) + .field( + "session_count", + &self.sessions.lock().map(|sessions| sessions.len()).ok(), + ) + .finish_non_exhaustive() + } } /// One reserved launch slot, given back when the launch ends — inserted, @@ -81,6 +97,8 @@ struct Session { deep: crate::deep::Minted, downloads: Vec, dir: PathBuf, + action_context: ActionContext, + refs: Vec, } impl std::fmt::Debug for Session { @@ -98,6 +116,15 @@ impl Session { reply::data(&self.engine.execute(command).await) } + /// The best current address for gate context, without making an action + /// fail solely because a page is briefly between documents. + async fn action_url(&mut self) -> String { + match self.run(json!({"action": "url"})).await { + Ok(data) => reply::text(&data, "url"), + Err(_) => self.info.url.clone(), + } + } + async fn page(&mut self) -> Result { let url = reply::text(&self.run(json!({"action": "url"})).await?, "url"); let title = reply::text(&self.run(json!({"action": "title"})).await?, "title"); @@ -232,6 +259,21 @@ impl Browser { scratch, counter: AtomicU64::new(0), opening: AtomicUsize::new(0), + action_gate: default_gate(), + } + } + + /// Sets the trusted host policy consulted before browser actions. + #[must_use] + pub fn with_action_gate(mut self, gate: Arc) -> Self { + self.action_gate = gate; + self + } + + pub(crate) fn check_action(&self, request: &ActionRequest) -> Result<()> { + match self.action_gate.check(request) { + ActionVerdict::Allow => Ok(()), + ActionVerdict::Refuse { reason } => Err(Error::ActionRefused { reason }), } } @@ -245,6 +287,20 @@ impl Browser { /// saying what to set when a browser to launch is not found or will not /// start, and whatever the engine reports when one cannot be reached. pub async fn open_session(&self, options: SessionOptions) -> Result { + self.open_session_with_context(options, ActionContext::default()) + .await + } + + /// Opens a session with host-supplied task context for its action gate. + /// + /// # Errors + /// + /// Returns the same errors as [`Browser::open_session`]. + pub async fn open_session_with_context( + &self, + options: SessionOptions, + action_context: ActionContext, + ) -> Result { // Checked and reserved under the table's lock, so the check and the // claim are one step for every concurrent caller. let reservation = { @@ -275,6 +331,8 @@ impl Browser { deep: crate::deep::Minted::default(), downloads: Vec::new(), dir: self.scratch.join(id.as_str()), + action_context, + refs: Vec::new(), }; // A browser this module launches says what to set when it cannot // start; one attached to keeps the engine's own words. diff --git a/crates/tinycomputer-browser/src/sessions/page.rs b/crates/tinycomputer-browser/src/sessions/page.rs index 4fa628cd4..14eece274 100644 --- a/crates/tinycomputer-browser/src/sessions/page.rs +++ b/crates/tinycomputer-browser/src/sessions/page.rs @@ -8,6 +8,7 @@ use tinycomputer_bus::browser::{ }; use super::{Browser, Session}; +use crate::action_gate::ActionRequest; use crate::convert; use crate::deep; use crate::error::{Error, Result}; @@ -44,12 +45,20 @@ const URL_IS_NO_PAGE: &[&str] = &[ /// text shows. So is a permission grant, which changes what pages may do. const NEITHER_ACTS_NOR_READS: &[&str] = &["url", "waitforloadstate"]; +fn raw_destination(command: &Value) -> Option { + URL_FIELDS + .iter() + .find_map(|field| command.get(*field).and_then(Value::as_str)) + .map(str::to_owned) +} + impl Browser { /// Navigates the session's active page. /// /// # Errors /// /// [`Error::NoSuchSession`], [`Error::InvalidInput`] for an empty URL, + /// [`Error::ActionRefused`] when the trusted host refuses it, /// [`Error::BlockedByPolicy`] outside the allowed origins (refused before /// the browser is asked, or after a redirect that leaves them), and /// whatever else the navigation reports. @@ -57,6 +66,14 @@ impl Browser { let session = self.session(id)?; let mut session = session.lock().await; let command = convert::navigate(&request)?; + let current_url = session.action_url().await; + self.check_action(&ActionRequest::raw( + command.clone(), + current_url, + Some(request.url.clone()), + &session.action_context, + &session.refs, + ))?; if !session.origins.admits(&request.url) { return Err(Error::BlockedByPolicy { url: request.url }); } @@ -113,6 +130,7 @@ impl Browser { &controls, request.max_chars, ); + session.refs.clone_from(&snapshot.refs); Ok(snapshot) } @@ -149,6 +167,14 @@ impl Browser { // The page may have moved on its own since the last call: an // action is never sent to a refused one. session.check_if_readable(false).await?; + let current_url = session.action_url().await; + self.check_action(&ActionRequest::typed( + &action, + current_url, + None, + &session.action_context, + &session.refs, + ))?; let value = session.act_deep(number, &action).await?; return session.outcome(value, None).await; } @@ -157,6 +183,14 @@ impl Browser { // The page may have moved on its own since the last call (a redirect, // a timer): an action is never sent to a refused one. session.check_if_readable(false).await?; + let current_url = session.action_url().await; + self.check_action(&ActionRequest::typed( + &action, + current_url, + None, + &session.action_context, + &session.refs, + ))?; match keys { Keys::Checked(selector) => session.focus_only(&selector).await?, Keys::Blurred => session.blur().await?, @@ -219,18 +253,19 @@ impl Browser { /// `{"action": "inputvalue", "selector": "@e3"}`, and returns its `data`. /// /// This is the escape hatch for engine capabilities the typed calls do - /// not cover. It carries no policy of its own beyond the allowed origins: + /// not cover. The trusted host's [`ActionGate`](crate::ActionGate) is + /// consulted before the raw command is sent: /// a command that would open or fetch an address outside them is never /// sent, nor any command that acts on the page or reads what it shows /// while the session shows a refused page (only a wait for the page to /// load and a read of its address go ahead), and the page a command /// leaves the session on is checked before its result is returned. A - /// caller exposing it to a model must still decide which actions to - /// allow. + /// A host that does not install a gate allows everything by default. /// /// # Errors /// - /// [`Error::NoSuchSession`], [`Error::InvalidInput`] when `command` names + /// [`Error::NoSuchSession`], [`Error::ActionRefused`] when the trusted + /// host refuses it, [`Error::InvalidInput`] when `command` names /// no `action`, [`Error::BlockedByPolicy`] for a page the allowed origins /// refuse, and whatever the engine reports. pub async fn command(&self, id: &SessionId, command: Value) -> Result { @@ -243,6 +278,14 @@ impl Browser { }; let session = self.session(id)?; let mut session = session.lock().await; + let current_url = session.action_url().await; + self.check_action(&ActionRequest::raw( + command.clone(), + current_url, + raw_destination(&command), + &session.action_context, + &session.refs, + ))?; if !URL_IS_NO_PAGE.contains(&action) { for field in URL_FIELDS { if let Some(url) = command.get(*field).and_then(Value::as_str) @@ -283,7 +326,8 @@ impl Browser { /// /// # Errors /// - /// [`Error::NoSuchSession`], [`Error::InvalidInput`] for an empty + /// [`Error::NoSuchSession`], [`Error::ActionRefused`] when the trusted + /// host refuses it, [`Error::InvalidInput`] for an empty /// expression, [`Error::BlockedByPolicy`] when the page it would run in, /// or the page it leads to, is outside the allowed origins, and /// [`Error::PageError`] when the script throws. @@ -292,6 +336,14 @@ impl Browser { let mut session = session.lock().await; let command = convert::evaluate(&request)?; session.check_if_readable(false).await?; + let current_url = session.action_url().await; + self.check_action(&ActionRequest::raw( + command.clone(), + current_url, + None, + &session.action_context, + &session.refs, + ))?; let data = session.run(command).await?; session.check_if_readable(true).await?; Ok(data.get("result").cloned().unwrap_or(Value::Null)) diff --git a/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs b/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs index fff34d359..3a86e4f0a 100644 --- a/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs +++ b/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs @@ -2,14 +2,16 @@ //! reading, evaluation, and raw commands. use serde_json::{Value, json}; +use std::sync::Arc; use tinycomputer_bus::browser::{ Action, EvaluateRequest, LocateBy, Locator, NavigateRequest, ReadFormat, ReadRequest, - SnapshotRequest, Target, + SessionOptions, SnapshotRequest, Target, }; use super::open; use crate::error::Error; use crate::fake::{Fake, failure, ok}; +use crate::{ActionContext, ActionGate, ActionRequest, ActionVerdict, Browser}; #[tokio::test] async fn navigation_reports_the_page_and_refusals_are_typed() { @@ -38,6 +40,195 @@ async fn navigation_reports_the_page_and_refusals_are_typed() { )); } +struct RefuseNamedAction(&'static str); + +impl ActionGate for RefuseNamedAction { + fn check(&self, request: &ActionRequest) -> ActionVerdict { + let action = request.payload["action"].as_str().unwrap_or_default(); + if action == self.0 { + ActionVerdict::Refuse { + reason: "host policy refused this action".to_owned(), + } + } else { + ActionVerdict::Allow + } + } +} + +#[derive(Default)] +struct CaptureActionRequest(std::sync::Mutex>); + +impl ActionGate for CaptureActionRequest { + fn check(&self, request: &ActionRequest) -> ActionVerdict { + self.0.lock().unwrap().push(format!("{request:?}")); + if request.payload["action"] == "fill" { + assert_eq!(request.payload["value"], "private@example.test"); + } + ActionVerdict::Allow + } +} + +#[tokio::test] +async fn gate_receives_task_page_destination_and_value_without_debugging_the_value() { + let page_url = Arc::new(std::sync::Mutex::new("about:blank".to_owned())); + let page_url_for_script = Arc::clone(&page_url); + let fake = Fake::scripted(move |command| match command["action"].as_str() { + Some("url") => Some(ok( + &json!({"url": page_url_for_script.lock().unwrap().clone()}), + )), + Some("navigate") => { + *page_url_for_script.lock().unwrap() = + command["url"].as_str().unwrap_or_default().to_owned(); + Some(ok( + &json!({"url": page_url_for_script.lock().unwrap().clone(), "title": "Checkout"}), + )) + } + _ => None, + }); + let gate = Arc::new(CaptureActionRequest::default()); + let browser = Browser::with_scratch(Arc::new(fake), super::scratch("gate-context")) + .with_action_gate(gate.clone()); + let id = browser + .open_session_with_context( + SessionOptions::default(), + ActionContext { + task_id: Some("task-17".to_owned()), + payment_in_play: true, + }, + ) + .await + .unwrap() + .id; + browser + .navigate(&id, NavigateRequest::new("https://shop.test/checkout")) + .await + .unwrap(); + browser + .perform( + &id, + Action::Fill { + target: Target::locator(Locator::new(LocateBy::Role, "textbox").with_name("Email")), + value: "private@example.test".to_owned(), + }, + ) + .await + .unwrap(); + let requests = gate.0.lock().unwrap(); + let navigation = requests + .iter() + .find(|request| request.contains("destination_url: Some(\"https://shop.test/checkout\")")) + .unwrap(); + assert!(navigation.contains("task_id: Some(\"task-17\")")); + assert!(navigation.contains("payment_in_play: true")); + let fill = requests + .iter() + .find(|request| request.contains("action: Some(\"fill\")")) + .unwrap(); + assert!(fill.contains("current_url: \"https://shop.test/checkout\"")); + assert!(fill.contains("role: Some(\"textbox\")")); + assert!(fill.contains("name: Some(\"Email\")")); + assert!(!fill.contains("private@example.test")); +} + +#[tokio::test] +async fn refused_order_click_never_reaches_the_page_and_reports_the_reason() { + let fake = Fake::new(); + let browser = Browser::with_scratch(Arc::new(fake.clone()), super::scratch("gate-click")) + .with_action_gate(Arc::new(RefuseNamedAction("click"))); + let id = browser + .open_session_with_context( + SessionOptions::default(), + ActionContext { + task_id: Some("task-17".to_owned()), + payment_in_play: true, + }, + ) + .await + .unwrap() + .id; + browser + .navigate(&id, NavigateRequest::new("https://shop.test/checkout")) + .await + .unwrap(); + let error = browser + .perform( + &id, + Action::Click { + target: Target::locator( + Locator::new(LocateBy::Role, "button").with_name("Place order"), + ), + new_tab: false, + }, + ) + .await + .unwrap_err(); + assert!( + matches!(error, Error::ActionRefused { ref reason } if reason == "host policy refused this action") + ); + assert!(!fake.actions().iter().any(|action| action == "click")); +} + +#[tokio::test] +async fn refused_fill_leaves_the_page_field_empty() { + let field = Arc::new(std::sync::Mutex::new(String::new())); + let field_for_script = Arc::clone(&field); + let fake = Fake::scripted(move |command| match command["action"].as_str() { + Some("fill") => { + *field_for_script.lock().unwrap() = + command["value"].as_str().unwrap_or_default().to_owned(); + Some(ok(&json!({}))) + } + Some("inputvalue") => Some(ok( + &json!({"value": field_for_script.lock().unwrap().clone()}), + )), + _ => None, + }); + let browser = Browser::with_scratch(Arc::new(fake.clone()), super::scratch("gate-fill")) + .with_action_gate(Arc::new(RefuseNamedAction("fill"))); + let id = browser + .open_session(SessionOptions::default()) + .await + .unwrap() + .id; + let error = browser + .perform( + &id, + Action::Fill { + target: Target::selector("#email"), + value: "private@example.test".to_owned(), + }, + ) + .await + .unwrap_err(); + assert!(matches!(error, Error::ActionRefused { .. })); + assert_eq!(*field.lock().unwrap(), ""); + assert!(!fake.actions().iter().any(|action| action == "fill")); +} + +#[tokio::test] +async fn raw_commands_and_evaluate_are_consulted_by_the_gate() { + let fake = Fake::new(); + let browser = Browser::with_scratch(Arc::new(fake.clone()), super::scratch("gate-raw")) + .with_action_gate(Arc::new(RefuseNamedAction("evaluate"))); + let id = browser + .open_session(SessionOptions::default()) + .await + .unwrap() + .id; + let command = browser + .command( + &id, + json!({"action": "evaluate", "script": "document.body.remove()"}), + ) + .await; + assert!(matches!(command, Err(Error::ActionRefused { .. }))); + let evaluate = browser + .evaluate(&id, EvaluateRequest::new("document.body.remove()")) + .await; + assert!(matches!(evaluate, Err(Error::ActionRefused { .. }))); + assert!(!fake.actions().iter().any(|action| action == "evaluate")); +} + #[tokio::test] async fn snapshots_count_up_and_carry_the_page() { let fake = Fake::new(); diff --git a/crates/tinycomputer-browser/src/surface/mod.rs b/crates/tinycomputer-browser/src/surface/mod.rs index 4151aa912..564ec55dd 100644 --- a/crates/tinycomputer-browser/src/surface/mod.rs +++ b/crates/tinycomputer-browser/src/surface/mod.rs @@ -27,8 +27,10 @@ mod watch; #[cfg(test)] pub(crate) use cover::{COVER_JS, SPOT_GRID}; +#[cfg(all(test, feature = "agent-browser"))] +pub(crate) use uncover::CENTRE_JS; #[cfg(test)] -pub(crate) use uncover::{CENTRE_JS, INTO_VIEW_JS}; +pub(crate) use uncover::INTO_VIEW_JS; pub use sight::Denoised; @@ -44,6 +46,7 @@ use tinycomputer_core::Platform; use tinycomputer_core::surface::Screen; use tinycomputer_cursor::ScreenCursor; +use crate::action_gate::ActionContext; use crate::error::{Error, Result}; use crate::sessions::Browser; use envelope::reply; @@ -127,6 +130,7 @@ const EARLY_LOAD_MS: u64 = 10_000; pub struct BrowserSurface { browser: Arc, options: SessionOptions, + action_context: ActionContext, session: Arc>>, handle: tokio::runtime::Handle, platform: Platform, @@ -170,6 +174,7 @@ impl BrowserSurface { Self { browser, options, + action_context: ActionContext::default(), session: Arc::new(Mutex::new(None)), handle, platform: Platform::current(), @@ -190,6 +195,13 @@ impl BrowserSurface { self } + /// Supplies the task facts included in each host action-gate request. + #[must_use] + pub fn with_action_context(mut self, context: ActionContext) -> Self { + self.action_context = context; + self + } + /// The same surface, reading pages with `perception` /// ([`Perception::Sight`] unless told otherwise). #[must_use] @@ -306,7 +318,10 @@ impl BrowserSurface { if early && self.closed.load(Ordering::Acquire) { return Err(Error::failed("the browser surface was let go")); } - let info = self.block(self.browser.open_session(self.options.clone()))?; + let info = self.block( + self.browser + .open_session_with_context(self.options.clone(), self.action_context.clone()), + )?; *slot = Some(info.id.clone()); Ok(info.id) } From c491537f83ca1651be5cd02f9422b1f9e2c2681c Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 03:08:23 +0530 Subject: [PATCH 04/73] feat(engine): add browser-only task runner Co-authored-by: Medulla --- Cargo.lock | 1 + crates/tinycomputer-engine/Cargo.toml | 12 +- .../src/agentic/flow/backend/mod.rs | 2 +- .../src/agentic/flow/flow_tests.rs | 2 + .../agentic/flow/flow_tests/hedge_tests.rs | 1 + crates/tinycomputer-engine/src/agentic/mod.rs | 13 +- .../tinycomputer-engine/src/agentic/reply.rs | 12 +- .../src/agentic/runtime.rs | 43 ++-- .../src/agentic/screen/mod.rs | 9 +- crates/tinycomputer-engine/src/lib.rs | 4 +- .../tinycomputer-engine/src/task/browser.rs | 239 ++++++++++++++++++ crates/tinycomputer-engine/src/task/mod.rs | 17 ++ .../tinycomputer/src/tinybus_module/runner.rs | 33 ++- 13 files changed, 357 insertions(+), 31 deletions(-) create mode 100644 crates/tinycomputer-engine/src/task/browser.rs diff --git a/Cargo.lock b/Cargo.lock index 96628891a..b7c521d87 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2722,6 +2722,7 @@ dependencies = [ "getrandom 0.4.3", "serde", "serde_json", + "tinycomputer-browser", "tinycomputer-bus", "tinycomputer-core", "tinycomputer-desktop", diff --git a/crates/tinycomputer-engine/Cargo.toml b/crates/tinycomputer-engine/Cargo.toml index d6863d0e0..1a81c06d7 100644 --- a/crates/tinycomputer-engine/Cargo.toml +++ b/crates/tinycomputer-engine/Cargo.toml @@ -5,7 +5,7 @@ edition.workspace = true rust-version.workspace = true license.workspace = true repository.workspace = true -description = "The tinycomputer agent runtime: Jev decision loops, goals, and intent flows over the desktop (and, next, the browser)." +description = "The tinycomputer agent runtime: Jev decision loops and embeddable browser task flows, with optional desktop support." documentation = "https://docs.rs/tinycomputer-engine" readme = "README.md" keywords = ["automation", "agent", "accessibility", "desktop"] @@ -17,8 +17,10 @@ publish = false tinycomputer-bus = { workspace = true } # The surface trait, screen model, and text delivery the loops run over. tinycomputer-core = { workspace = true } -# The desktop surface the runtime observes and acts on. -tinycomputer-desktop = { workspace = true } +# The browser surface used by in-process browser task hosts. +tinycomputer-browser = { workspace = true } +# The desktop surface, enabled by the default `desktop` feature. +tinycomputer-desktop = { workspace = true, optional = true } # The Jev decisions client every loop asks. tinyinference-decisions = { workspace = true } # Snapshots, replies, and Jev state are JSON values throughout. @@ -35,7 +37,9 @@ tokio = { workspace = true } tinyinference-llm = { workspace = true, optional = true } [features] -default = [] +default = ["desktop"] +# Desktop observation and action entry points. +desktop = ["dep:tinycomputer-desktop"] # An LLM planner that turns plain-language tasks into flows. planner = ["dep:tinyinference-llm"] diff --git a/crates/tinycomputer-engine/src/agentic/flow/backend/mod.rs b/crates/tinycomputer-engine/src/agentic/flow/backend/mod.rs index 246ddc935..5580eb26e 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/backend/mod.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/backend/mod.rs @@ -44,5 +44,5 @@ where }) } -#[cfg(test)] +#[cfg(all(test, feature = "desktop"))] mod backend_tests; diff --git a/crates/tinycomputer-engine/src/agentic/flow/flow_tests.rs b/crates/tinycomputer-engine/src/agentic/flow/flow_tests.rs index 66ef66121..b50b93d9c 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/flow_tests.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/flow_tests.rs @@ -92,6 +92,7 @@ fn runtime(client: impl Evaluator + 'static) -> JevRuntime { endpoint_url: None, fast: false, }, + #[cfg(feature = "desktop")] pending: Arc::default(), journal: crate::agentic::journal::Journal::default(), copies: Arc::default(), @@ -125,6 +126,7 @@ async fn run_with( endpoint_url: None, fast: false, }, + #[cfg(feature = "desktop")] pending: Arc::default(), journal: crate::agentic::journal::Journal::default(), copies: Arc::default(), diff --git a/crates/tinycomputer-engine/src/agentic/flow/flow_tests/hedge_tests.rs b/crates/tinycomputer-engine/src/agentic/flow/flow_tests/hedge_tests.rs index 2ff682acb..27253c31a 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/flow_tests/hedge_tests.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/flow_tests/hedge_tests.rs @@ -69,6 +69,7 @@ fn paced_as( endpoint_url: None, fast: false, }, + #[cfg(feature = "desktop")] pending: Arc::default(), journal: crate::agentic::journal::Journal::default(), copies: Arc::default(), diff --git a/crates/tinycomputer-engine/src/agentic/mod.rs b/crates/tinycomputer-engine/src/agentic/mod.rs index 798006a78..e7aaad375 100644 --- a/crates/tinycomputer-engine/src/agentic/mod.rs +++ b/crates/tinycomputer-engine/src/agentic/mod.rs @@ -14,29 +14,40 @@ //! - `reply` builds the envelopes and maps errors, and `backend` runs the //! desktop off the async runtime. +#[cfg(feature = "desktop")] mod backend; +#[cfg(feature = "desktop")] mod continuation; mod flow; +#[cfg(feature = "desktop")] mod goal; mod journal; +#[cfg(feature = "desktop")] mod pending; +#[cfg(feature = "desktop")] mod policy; mod reply; +#[cfg(feature = "desktop")] mod resolve; mod runtime; mod sage; +#[cfg(feature = "desktop")] mod screen; +#[cfg(feature = "desktop")] mod task; +#[cfg(feature = "desktop")] mod verify; -#[cfg(test)] +#[cfg(all(test, feature = "desktop"))] mod agentic_tests; pub(crate) use flow::{check_flow, missing_inputs}; pub use flow::{flow_guide, run_flow, validate_flow}; +#[cfg(feature = "desktop")] pub use goal::run_goal; pub use journal::{DEFAULT_DIR as JOURNAL_DEFAULT_DIR, JOURNAL_ENV, JOURNAL_FILE}; use reply::{internal_error, merge_metrics, provider_error, response}; +#[cfg(feature = "desktop")] pub use resolve::resolve_intent; use runtime::Evaluator; pub use runtime::JevRuntime; diff --git a/crates/tinycomputer-engine/src/agentic/reply.rs b/crates/tinycomputer-engine/src/agentic/reply.rs index 027d57cc3..8990934d4 100644 --- a/crates/tinycomputer-engine/src/agentic/reply.rs +++ b/crates/tinycomputer-engine/src/agentic/reply.rs @@ -1,14 +1,17 @@ //! The reply envelopes `RunGoal` and `ResolveIntent` return, the metrics //! they carry, and the errors Jev and the desktop map to. +#[cfg(feature = "desktop")] use tinycomputer_bus::{ - DeliveryDisposition, DesktopError, DesktopResponse, JevDecision, JevMetrics, JevObservation, - JevRunResult, JevStopReason, JevTurn, + DeliveryDisposition, JevDecision, JevObservation, JevRunResult, JevStopReason, JevTurn, }; +use tinycomputer_bus::{DesktopError, DesktopResponse, JevMetrics}; use tinyinference_decisions::{Error as JevError, EvaluationResult}; +#[cfg(feature = "desktop")] use super::verify::satisfied; +#[cfg(feature = "desktop")] pub(super) fn action_failed_response( mut turns: Vec, decision: JevDecision, @@ -27,6 +30,7 @@ pub(super) fn action_failed_response( run_response(stop, turns, Some(decision), metrics) } +#[cfg(feature = "desktop")] pub(super) fn failed_turn(turns: &[JevTurn], decision: &JevDecision) -> JevTurn { JevTurn { step: u32::try_from(turns.len()) @@ -40,6 +44,7 @@ pub(super) fn failed_turn(turns: &[JevTurn], decision: &JevDecision) -> JevTurn } } +#[cfg(feature = "desktop")] pub(super) fn run_response( stop: JevStopReason, turns: Vec, @@ -49,6 +54,7 @@ pub(super) fn run_response( run_response_with_id(stop, turns, pending, metrics, None) } +#[cfg(feature = "desktop")] pub(super) fn run_response_observed( stop: JevStopReason, turns: Vec, @@ -70,6 +76,7 @@ pub(super) fn run_response_observed( ) } +#[cfg(feature = "desktop")] pub(super) fn run_response_with_id( stop: JevStopReason, turns: Vec, @@ -133,6 +140,7 @@ pub(super) fn provider_error( )) } +#[cfg(feature = "desktop")] pub(super) fn invalid_response(message: &str) -> Box { Box::new(DesktopResponse::err( "jev-evaluate", diff --git a/crates/tinycomputer-engine/src/agentic/runtime.rs b/crates/tinycomputer-engine/src/agentic/runtime.rs index cca25ab32..a0c5bc0b8 100644 --- a/crates/tinycomputer-engine/src/agentic/runtime.rs +++ b/crates/tinycomputer-engine/src/agentic/runtime.rs @@ -1,11 +1,12 @@ //! The Jev runtime: its configured client, the journal it writes, and the //! one door every Jev evaluation goes through. +#[cfg(feature = "desktop")] +use std::{collections::HashMap, sync::Mutex}; use std::{ - collections::HashMap, future::Future, pin::Pin, - sync::{Arc, Mutex, atomic::AtomicUsize}, + sync::{Arc, atomic::AtomicUsize}, time::Duration, }; @@ -17,6 +18,7 @@ use tinyinference_decisions::{ use super::flow::MAX_VOTES; use super::journal::Journal; +#[cfg(feature = "desktop")] use super::pending::PendingRun; use super::sage; use crate::{ModelRole, UsageRecorder}; @@ -50,6 +52,7 @@ pub(super) const FIRST_TURN: u32 = 2; pub struct JevRuntime { pub(super) client: Arc, pub(super) configuration: JevConfiguration, + #[cfg(feature = "desktop")] pub(super) pending: Arc>>, pub(super) journal: Journal, /// Hedged copies of framings in flight, shared by every flow run on @@ -61,13 +64,16 @@ pub struct JevRuntime { impl std::fmt::Debug for JevRuntime { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - formatter - .debug_struct("JevRuntime") + let mut debug = formatter.debug_struct("JevRuntime"); + debug .field("client", &"[configured]") - .field("configuration", &self.configuration) - .field("pending", &"[redacted]") + .field("configuration", &self.configuration); + #[cfg(feature = "desktop")] + debug.field("pending", &"[redacted]"); + debug .field("journal", &self.journal) .field("copies", &self.copies) + .field("usage", &self.usage.as_ref().map(|_| "[tracked]")) .finish() } } @@ -89,7 +95,7 @@ impl JevRuntime { /// Build a Jev runtime for an embedding host, allowing the host to route /// its configured provider to a private endpoint. /// - /// The TinyBus module uses [`JevRuntime::configure`], which retains the + /// The `TinyBus` module uses [`JevRuntime::configure`], which retains the /// module's provider allow-list. This constructor is for Rust hosts that /// own and trust their configuration. /// @@ -134,6 +140,7 @@ impl JevRuntime { endpoint_url: request.endpoint_url.clone(), fast: false, }, + #[cfg(feature = "desktop")] pending: Arc::new(Mutex::new(HashMap::new())), journal: Journal::from_env(), copies: Arc::default(), @@ -178,6 +185,7 @@ impl JevRuntime { endpoint_url: endpoint.map(str::to_owned), fast, }, + #[cfg(feature = "desktop")] pending: Arc::new(Mutex::new(HashMap::new())), journal: Journal::from_env(), copies: Arc::default(), @@ -255,6 +263,7 @@ impl JevRuntime { } /// This runtime writing to `journal`. + #[cfg(feature = "desktop")] pub(super) fn within(self, journal: Journal) -> Self { Self { journal, ..self } } @@ -303,16 +312,16 @@ impl JevRuntime { usage.record_started(ModelRole::Jev); } let outcome = self.client.evaluate(request).await; - if let Some(usage) = &self.usage { - if let Ok(result) = &outcome { - usage.record_measurements( - ModelRole::Jev, - result.response.usage.input_tokens, - None, - result.response.usage.output_tokens, - None, - ); - } + if let Some(usage) = &self.usage + && let Ok(result) = &outcome + { + usage.record_measurements( + ModelRole::Jev, + result.response.usage.input_tokens, + None, + result.response.usage.output_tokens, + None, + ); } self.journal.exchange(step, request, outcome.as_ref()); outcome diff --git a/crates/tinycomputer-engine/src/agentic/screen/mod.rs b/crates/tinycomputer-engine/src/agentic/screen/mod.rs index 728272586..77a0b4115 100644 --- a/crates/tinycomputer-engine/src/agentic/screen/mod.rs +++ b/crates/tinycomputer-engine/src/agentic/screen/mod.rs @@ -3,8 +3,12 @@ use serde::Deserialize; use serde_json::{Value, json}; use std::hash::{Hash, Hasher}; -use tinycomputer_bus::{DesktopResponse, SnapshotRequest, Surface}; +#[cfg(feature = "desktop")] +use tinycomputer_bus::Surface; +#[cfg(feature = "desktop")] +use tinycomputer_bus::{DesktopResponse, SnapshotRequest}; +#[cfg(feature = "desktop")] use crate::Desktop; const MAX_TREE_DEPTH: usize = 64; @@ -70,6 +74,7 @@ pub(super) struct Screen { pub(super) observed: Vec, } +#[cfg(feature = "desktop")] pub(super) fn observe( desktop: &Desktop, app: &str, @@ -90,6 +95,7 @@ pub(super) fn observe( parse_reply(desktop, app, window_id, root, reply) } +#[cfg(feature = "desktop")] pub(super) fn snapshot_request( app: &str, window_id: Option<&str>, @@ -106,6 +112,7 @@ pub(super) fn snapshot_request( } } +#[cfg(feature = "desktop")] pub(super) fn parse_reply( desktop: &Desktop, app: &str, diff --git a/crates/tinycomputer-engine/src/lib.rs b/crates/tinycomputer-engine/src/lib.rs index 8c3057efa..b83f2fa57 100644 --- a/crates/tinycomputer-engine/src/lib.rs +++ b/crates/tinycomputer-engine/src/lib.rs @@ -25,10 +25,10 @@ //! //! A [`Workspace`] joins desktop and browser when the default `desktop` //! feature is enabled. A [`BrowserRunner`] runs the public [`Tasks`] manager -//! directly on browser sessions without TinyBus or a desktop adapter. +//! directly on browser sessions without `TinyBus` or a desktop adapter. //! //! The crate holds no bus: `tinycomputer` may serve these functions over -//! TinyBus, while embedding hosts can call the runner and task manager in +//! `TinyBus`, while embedding hosts can call the runner and task manager in //! process. mod agentic; diff --git a/crates/tinycomputer-engine/src/task/browser.rs b/crates/tinycomputer-engine/src/task/browser.rs new file mode 100644 index 000000000..a2cf450f1 --- /dev/null +++ b/crates/tinycomputer-engine/src/task/browser.rs @@ -0,0 +1,239 @@ +//! A browser-only [`super::FlowRunner`] for hosts embedding the engine. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +use tinycomputer_browser::{ActionContext, Browser, BrowserSurface, SessionOptions}; +use tinycomputer_bus::agent::{PaymentMode, TaskConstraints, TaskId}; +use tinycomputer_bus::browser::ScreenshotRequest; +use tinycomputer_bus::{DesktopResponse, RunFlowRequest}; +use tinycomputer_core::surface::{Depth, Surface}; + +use super::{CaptureFuture, FlowFuture, FlowRunner, PrepareFuture, TextFuture}; +use crate::{JevRuntime, UsageRecorder}; + +/// Runs task flows directly on one in-process browser surface per task. +/// +/// The host owns the browser launcher and the configured Jev runtime. This +/// runner adds no bus or desktop adapter. Each task keeps its browser session +/// across pauses and continuations, and [`FlowRunner::release`] closes it when +/// the task ends. +pub struct BrowserRunner { + browser: Arc, + runtime: JevRuntime, + options: SessionOptions, + surfaces: Mutex>, +} + +impl std::fmt::Debug for BrowserRunner { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("BrowserRunner") + .field("runtime", &self.runtime) + .field("options", &self.options) + .field("surfaces", &"[task surfaces]") + .finish_non_exhaustive() + } +} + +impl BrowserRunner { + /// Creates a runner using `browser` and the host's configured `runtime`. + #[must_use] + pub fn new(browser: Arc, runtime: JevRuntime) -> Self { + Self { + browser, + runtime, + options: SessionOptions::default(), + surfaces: Mutex::new(HashMap::new()), + } + } + + /// Uses `options` as the host defaults for sessions this runner opens. + #[must_use] + pub fn with_session_options(mut self, options: SessionOptions) -> Self { + self.options = options; + self + } + + fn surface(&self, task: &TaskId, constraints: &TaskConstraints) -> BrowserSurface { + let fresh = || { + let mut options = self.options.clone(); + if constraints.browser_endpoint.is_some() { + options.endpoint.clone_from(&constraints.browser_endpoint); + } + if constraints.browser_executable.is_some() { + options + .executable + .clone_from(&constraints.browser_executable); + } + if constraints.browser_profile.is_some() { + options + .user_data_dir + .clone_from(&constraints.browser_profile); + } + if !constraints.origins.is_empty() { + options.allowed_origins.clone_from(&constraints.origins); + } + options.headless = !constraints.headed; + BrowserSurface::new( + self.browser.clone(), + options, + tokio::runtime::Handle::current(), + ) + .with_action_context(ActionContext { + task_id: Some(task.0.clone()), + payment_in_play: constraints.payment == PaymentMode::FillThenApprove, + }) + }; + + self.surfaces.lock().map_or_else( + |_| fresh(), + |mut surfaces| surfaces.entry(task.clone()).or_insert_with(fresh).clone(), + ) + } +} + +impl FlowRunner for BrowserRunner { + fn run( + &self, + task: &TaskId, + constraints: &TaskConstraints, + request: RunFlowRequest, + ) -> FlowFuture { + self.run_with_runtime(task, constraints, request, &self.runtime) + } + + fn run_with_usage( + &self, + task: &TaskId, + constraints: &TaskConstraints, + request: RunFlowRequest, + usage: Arc, + ) -> FlowFuture { + let runtime = self.runtime.clone().with_usage_recorder(usage); + self.run_with_runtime(task, constraints, request, &runtime) + } + + fn visible_text(&self, task: &TaskId) -> TextFuture { + let surface = self.surface(task, &TaskConstraints::default()); + Box::pin(async move { + tokio::task::spawn_blocking(move || { + surface + .observe("browser", None, Depth::Full) + .map(|screen| { + screen + .context + .into_iter() + .chain(screen.candidates.iter().filter_map(|node| { + let held = node + .value + .as_ref() + .and_then(serde_json::Value::as_str) + .filter(|held| !held.trim().is_empty()); + match (&node.name, held) { + (Some(name), Some(held)) => Some(format!("{name} = {held:?}")), + (name, _) => name.clone(), + } + })) + .collect() + }) + .unwrap_or_default() + }) + .await + .unwrap_or_default() + }) + } + + fn capture(&self, task: &TaskId) -> CaptureFuture { + let surface = self + .surfaces + .lock() + .ok() + .and_then(|surfaces| surfaces.get(task).cloned()); + let Some(session) = surface.and_then(|surface| surface.session()) else { + return Box::pin(async { None }); + }; + let browser = self.browser.clone(); + Box::pin(async move { + browser + .screenshot(&session, ScreenshotRequest::default()) + .await + .ok() + }) + } + + fn prepare(&self, task: &TaskId, constraints: &TaskConstraints) -> PrepareFuture { + let surface = self.surface(task, constraints); + Box::pin(async move { + let _opened = tokio::task::spawn_blocking(move || surface.open()).await; + }) + } + + fn open_page(&self, task: &TaskId, url: &str) -> PrepareFuture { + let surface = self + .surfaces + .lock() + .ok() + .and_then(|surfaces| surfaces.get(task).cloned()); + let Some(surface) = surface else { + return Box::pin(async {}); + }; + let url = url.to_owned(); + Box::pin(async move { + let _loaded = tokio::task::spawn_blocking(move || surface.open_at(&url)).await; + }) + } + + fn warm(&self, task: &TaskId, votes: u32) -> PrepareFuture { + let runtime = self.runtime.journaled_as(&format!("task-{task}")); + Box::pin(async move { runtime.warm(votes).await }) + } + + fn journal(&self, task: Option<&TaskId>, event: &str, fields: &dyn Fn() -> serde_json::Value) { + if !self.runtime.journaling() { + return; + } + let runtime = task.map_or_else( + || self.runtime.clone(), + |task| self.runtime.journaled_as(&format!("task-{task}")), + ); + runtime.journal_event(event, fields); + } + + fn release(&self, task: &TaskId) { + if let Some(surface) = self + .surfaces + .lock() + .ok() + .and_then(|mut surfaces| surfaces.remove(task)) + { + surface.close(); + } + } +} + +impl BrowserRunner { + fn run_with_runtime( + &self, + task: &TaskId, + constraints: &TaskConstraints, + request: RunFlowRequest, + runtime: &JevRuntime, + ) -> FlowFuture { + let runtime = runtime.journaled_as(&format!("task-{task}")); + let surface = self.surface(task, constraints); + Box::pin(tinycomputer_engine_flow(surface, runtime, request)) + } +} + +async fn tinycomputer_engine_flow( + surface: BrowserSurface, + runtime: JevRuntime, + request: RunFlowRequest, +) -> DesktopResponse { + crate::run_flow(surface, runtime, request).await +} + +#[cfg(test)] +#[path = "browser_tests.rs"] +mod browser_tests; diff --git a/crates/tinycomputer-engine/src/task/mod.rs b/crates/tinycomputer-engine/src/task/mod.rs index 368f1b964..0622e1102 100644 --- a/crates/tinycomputer-engine/src/task/mod.rs +++ b/crates/tinycomputer-engine/src/task/mod.rs @@ -38,6 +38,7 @@ mod artifact; mod brief; +mod browser; mod budget; mod controller; mod describe; @@ -60,6 +61,7 @@ use tinycomputer_bus::agent::{TaskConstraints, TaskId}; use tinycomputer_bus::browser::OutputRef; use tinycomputer_bus::{DesktopResponse, RunFlowRequest}; +pub use browser::BrowserRunner; pub use controller::Tasks; pub use describe::capabilities; pub(crate) use names::input_kind; @@ -90,6 +92,21 @@ pub trait FlowRunner: Send + Sync + 'static { request: RunFlowRequest, ) -> FlowFuture; + /// Runs a task flow with its usage recorder attached to model calls. + /// + /// Runners that do not account for model usage may keep the default. A + /// runner backed by [`JevRuntime`](crate::JevRuntime) should override + /// this method and attach `usage` to the cloned runtime before running. + fn run_with_usage( + &self, + task: &TaskId, + constraints: &TaskConstraints, + request: RunFlowRequest, + _usage: std::sync::Arc, + ) -> FlowFuture { + self.run(task, constraints, request) + } + /// The visible text of the task's surface now, to spot a wall only a /// person can pass. Empty by default. fn visible_text(&self, _task: &TaskId) -> TextFuture { diff --git a/crates/tinycomputer/src/tinybus_module/runner.rs b/crates/tinycomputer/src/tinybus_module/runner.rs index 67a879ef2..5fa02a12a 100644 --- a/crates/tinycomputer/src/tinybus_module/runner.rs +++ b/crates/tinycomputer/src/tinybus_module/runner.rs @@ -5,12 +5,13 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex}; use tinycomputer_browser::{ - Browser, BrowserSurface, ScreenCursor, ScreenshotRequest, SessionOptions, + ActionContext, Browser, BrowserSurface, ScreenCursor, ScreenshotRequest, SessionOptions, }; use tinycomputer_bus::DesktopResponse; -use tinycomputer_bus::agent::{SurfaceKind, TaskConstraints, TaskId}; +use tinycomputer_bus::agent::{PaymentMode, SurfaceKind, TaskConstraints, TaskId}; use tinycomputer_engine::{ - CaptureFuture, FlowFuture, FlowRunner, JevRuntime, PrepareFuture, TextFuture, Workspace, + CaptureFuture, FlowFuture, FlowRunner, JevRuntime, PrepareFuture, TextFuture, UsageRecorder, + Workspace, }; use super::config::BrowserDefaults; @@ -72,6 +73,10 @@ impl WorkspaceRunner { tokio::runtime::Handle::current(), ) .with_cursor(self.cursor.clone()) + .with_action_context(ActionContext { + task_id: Some(task.0.clone()), + payment_in_play: constraints.payment == PaymentMode::FillThenApprove, + }) .with_perception(self.defaults.perception) .with_settle(self.defaults.settle) }); @@ -110,6 +115,28 @@ impl FlowRunner for WorkspaceRunner { )) } + fn run_with_usage( + &self, + task: &TaskId, + constraints: &TaskConstraints, + request: tinycomputer_bus::RunFlowRequest, + usage: Arc, + ) -> FlowFuture { + let Some(runtime) = self.jev.as_ref() else { + return Box::pin(async { jev_not_configured("run-flow") }); + }; + // Keep model measurements scoped to the task, across its continuations. + let runtime = runtime + .clone() + .with_usage_recorder(usage) + .journaled_as(&format!("task-{task}")); + Box::pin(tinycomputer_engine::run_flow( + self.workspace(task, constraints), + runtime, + request, + )) + } + fn visible_text(&self, task: &TaskId) -> TextFuture { let workspace = self.workspace(task, &TaskConstraints::default()); Box::pin(async move { From f3b8b534adc270af5b4f40d0293b0381d547b121 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 03:08:26 +0530 Subject: [PATCH 05/73] test(engine): verify browser-only task flow and refusal recovery Co-authored-by: Medulla --- .../src/task/browser_tests.rs | 162 ++++++++++++++++++ .../src/bin/task_in_process.rs | 86 ++++++++++ 2 files changed, 248 insertions(+) create mode 100644 crates/tinycomputer-engine/src/task/browser_tests.rs create mode 100644 crates/tinycomputer-examples/src/bin/task_in_process.rs diff --git a/crates/tinycomputer-engine/src/task/browser_tests.rs b/crates/tinycomputer-engine/src/task/browser_tests.rs new file mode 100644 index 000000000..ec8951a65 --- /dev/null +++ b/crates/tinycomputer-engine/src/task/browser_tests.rs @@ -0,0 +1,162 @@ +//! Public task-manager behavior on a scripted browser-only runner. + +use std::sync::Arc; + +use tinycomputer_bus::agent::{ + AwaitTaskRequest, StartTaskRequest, SurfaceKind, TaskConstraints, TaskStatus, +}; +use tinycomputer_bus::{ + DesktopResponse, FlowRunResult, FlowStopReason, JevMetrics, RunFlowRequest, StepOutcome, + StepReport, +}; +use tinycomputer_bus::{Flow, FlowAction, FlowStep}; + +use super::{FlowFuture, FlowRunner}; +use crate::{Completion, LanguageModel, Rescuer, Tasks, Turn}; + +struct ScriptedBrowserRunner { + failure: Option<&'static str>, +} + +impl FlowRunner for ScriptedBrowserRunner { + fn run( + &self, + _task: &tinycomputer_bus::agent::TaskId, + constraints: &TaskConstraints, + _request: RunFlowRequest, + ) -> FlowFuture { + assert_eq!(constraints.surfaces, [SurfaceKind::Browser]); + let failure = self.failure; + let result = FlowRunResult { + stop: if failure.is_some() { + FlowStopReason::StepFailed + } else { + FlowStopReason::Completed + }, + steps: vec![StepReport { + path: "1".to_owned(), + kind: "browse".to_owned(), + text: "open the local page".to_owned(), + outcome: if failure.is_some() { + StepOutcome::Failed + } else { + StepOutcome::Done + }, + turns: 0, + jev_calls: 0, + actions: Vec::new(), + loops: Vec::new(), + confidence: None, + note: failure.unwrap_or_default().to_owned(), + }], + vars: std::collections::BTreeMap::new(), + pending: None, + learned: Vec::new(), + actions: 0, + metrics: JevMetrics::default(), + trace: Vec::new(), + dialog_left_open: false, + }; + let reply = serde_json::to_value(result).map_or_else( + |error| { + DesktopResponse::err( + "run-flow", + tinycomputer_bus::DesktopError::new("INTERNAL", error.to_string()), + ) + }, + |value| DesktopResponse::ok("run-flow", value), + ); + Box::pin(async move { reply }) + } +} + +#[tokio::test] +async fn public_task_manager_runs_a_scripted_browser_flow_to_done_without_models() +-> Result<(), Box> { + let tasks = Tasks::new(Arc::new(ScriptedBrowserRunner { failure: None })); + let started = tasks.start(&request()); + assert!(started.ok, "{:?}", started.error); + let Some(started) = started.data else { + return Err("the task start reply had no view".into()); + }; + + let finished = settle(&tasks, &started.id).await?; + assert!(matches!(finished.status, TaskStatus::Done { .. })); + Ok(()) +} + +struct RefusalRecovery; + +impl LanguageModel for RefusalRecovery { + fn complete(&self, _turns: &[Turn]) -> Completion { + Box::pin(async { Err("scripted recovery is unavailable".to_owned()) }) + } +} + +#[tokio::test] +async fn a_browser_action_refusal_keeps_its_reason_in_rescue_and_task_report() +-> Result<(), Box> { + const REASON: &str = "the host refused this browser action"; + let tasks = Tasks::new(Arc::new(ScriptedBrowserRunner { + failure: Some(REASON), + })) + .with_rescuer(Rescuer::new(Arc::new(RefusalRecovery))); + let started = tasks.start(&request()); + assert!(started.ok, "{:?}", started.error); + let Some(started) = started.data else { + return Err("the task start reply had no view".into()); + }; + let finished = settle(&tasks, &started.id).await?; + assert!(matches!( + &finished.status, + TaskStatus::Failed { reason, .. } if reason == REASON + )); + + let report = tasks.report(&started.id); + assert!(report.ok, "{:?}", report.error); + let Some(report) = report.data else { + return Err("the task report reply had no report".into()); + }; + assert_eq!(report.view.status, finished.status); + assert_eq!(report.steps[0].note, REASON); + assert_eq!(report.rescues[0].failure, REASON); + Ok(()) +} + +fn request() -> StartTaskRequest { + StartTaskRequest { + flow: Some(Flow { + app: "browser".to_owned(), + vars: std::collections::BTreeMap::new(), + steps: vec![FlowStep::Action(FlowAction::Browse( + "http://127.0.0.1:8765/index.html".to_owned(), + ))], + }), + constraints: TaskConstraints { + surfaces: vec![SurfaceKind::Browser], + ..TaskConstraints::default() + }, + ..StartTaskRequest::default() + } +} + +async fn settle( + tasks: &Tasks, + id: &tinycomputer_bus::agent::TaskId, +) -> Result> { + loop { + let reply = tasks + .await_task(AwaitTaskRequest { + id: id.clone(), + timeout_ms: 1_000, + }) + .await; + assert!(reply.ok, "{:?}", reply.error); + let Some(view) = reply.data else { + return Err("the await reply had no task view".into()); + }; + if view.status.is_final() { + return Ok(view); + } + } +} diff --git a/crates/tinycomputer-examples/src/bin/task_in_process.rs b/crates/tinycomputer-examples/src/bin/task_in_process.rs new file mode 100644 index 000000000..205f0df3d --- /dev/null +++ b/crates/tinycomputer-examples/src/bin/task_in_process.rs @@ -0,0 +1,86 @@ +//! Runs a browser task directly through `tinycomputer-engine`, without loading +//! the module or using TinyBus. +//! +//! Start the local travel fixture, then run this binary from the workspace: +//! +//! ```sh +//! python3 -m http.server 8765 --directory crates/tinycomputer-examples/fixtures/travel +//! OPENROUTER_API_KEY=... cargo run -p tinycomputer-examples --bin task_in_process +//! ``` +//! +//! `TINYCOMPUTER_FIXTURE_URL` changes the fixture address, and +//! `TINYCOMPUTER_BROWSER_EXECUTABLE` selects a Chrome or Chromium binary. + +use std::sync::Arc; +use tinycomputer_browser::{AgentBrowser, Browser}; +use tinycomputer_bus::agent::{ + AwaitTaskRequest, StartTaskRequest, SurfaceKind, TaskConstraints, TaskStatus, +}; +use tinycomputer_bus::agentic::{JevConfig, JevProvider}; +use tinycomputer_engine::{BrowserRunner, JevRuntime, Tasks}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + let base = std::env::var("TINYCOMPUTER_FIXTURE_URL") + .unwrap_or_else(|_| "http://127.0.0.1:8765".to_owned()); + let mut jev = JevConfig::new(std::env::var("OPENROUTER_API_KEY")?); + jev.provider = JevProvider::OpenRouter; + let runtime = JevRuntime::configure(&jev) + .map_err(|error| std::io::Error::other(error.message.clone()))?; + let options = tinycomputer_browser::SessionOptions { + executable: std::env::var("TINYCOMPUTER_BROWSER_EXECUTABLE").ok(), + ..tinycomputer_browser::SessionOptions::default() + }; + let runner = Arc::new( + BrowserRunner::new(Arc::new(Browser::new(Arc::new(AgentBrowser))), runtime) + .with_session_options(options), + ); + let tasks = Tasks::new(runner); + let started = tasks.start(&StartTaskRequest { + task: Some("Read the heading on the local fixture page.".to_owned()), + flow: Some(serde_json::from_value(serde_json::json!({ + "app": "browser", + "steps": [ + {"browse": format!("{base}/index.html")}, + "read the page heading" + ] + }))?), + constraints: TaskConstraints { + surfaces: vec![SurfaceKind::Browser], + origins: vec![base], + ..TaskConstraints::default() + }, + ..StartTaskRequest::default() + }); + let mut view = started.data.ok_or_else(|| { + started + .error + .map_or_else(|| "task did not start".to_owned(), |error| error.message) + })?; + + while !view.status.is_final() { + let reply = tasks + .await_task(AwaitTaskRequest { + id: view.id.clone(), + timeout_ms: 1_000, + }) + .await; + view = reply.data.ok_or_else(|| { + reply + .error + .map_or_else(|| "task wait failed".to_owned(), |error| error.message) + })?; + } + if matches!(view.status, TaskStatus::Done { .. }) { + let report = tasks.report(&view.id); + let report = report.data.ok_or_else(|| { + report + .error + .map_or_else(|| "task report failed".to_owned(), |error| error.message) + })?; + println!("{}", serde_json::to_string_pretty(&report)?); + Ok(()) + } else { + Err(format!("task ended as {:?}", view.status).into()) + } +} From 786dea6aa33369dd313915b2ab38b044c44984c8 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 03:08:29 +0530 Subject: [PATCH 06/73] docs(engine): document in-process browser task runtime Co-authored-by: Medulla --- crates/tinycomputer-engine/README.md | 16 ++++++++++++---- docs/crates/tinycomputer-engine/README.md | 6 ++++-- docs/crates/tinycomputer-engine/jev-runtime.md | 5 +++-- docs/crates/tinycomputer-engine/tasks.md | 10 +++++++--- 4 files changed, 26 insertions(+), 11 deletions(-) diff --git a/crates/tinycomputer-engine/README.md b/crates/tinycomputer-engine/README.md index 3a4ccddcc..ee14dce62 100644 --- a/crates/tinycomputer-engine/README.md +++ b/crates/tinycomputer-engine/README.md @@ -13,13 +13,21 @@ adapters with Jev, TypeSafe's decision model: | `run_goal` | `RunGoal` | a bounded, scoped goal with visible success predicates | | `run_flow` | `RunFlow` | a UI-agnostic intent flow grounded by small Jev decision loops | | `validate_flow`, `flow_guide` | `ValidateFlow`, `FlowGuide` | check and document flows offline | -| `Tasks` | `StartTask`, `AwaitTask`, `ContinueTask`, … | the task controller: runs a flow in the background, pauses for missing values and irreversible actions, always stops at payment | +| `Tasks` | `StartTask`, `AwaitTask`, `ContinueTask`, … | the public task controller: runs a flow in the background, pauses for missing values and irreversible actions, always stops at payment | +| `BrowserRunner` | — | embeds the same task controller on one in-process browser session per task, without TinyBus or a desktop adapter | | `Planner` | `PlanTask`, plain-language `StartTask` | turns a task into a flow with an LLM (`planner` feature); sees fact names, never values | | `Workspace` | — | the desktop and the browser as one surface, so `browse` and `open` steps move a flow between them | -`JevRuntime::configure` builds the Jev client from the module's private -configuration. The crate holds no bus; `tinycomputer` serves these functions over -TinyBus. +`JevRuntime::configure` builds the Jev client from a host-provided +configuration. The default `desktop` feature keeps the desktop entry points +available to the module. Disable default features to embed the flow and task +runtime without `tinycomputer-desktop`; `tinycomputer-browser` supplies the +in-process browser surface. + +An embedding host can construct `Tasks::new(Arc::new(BrowserRunner::new(...)))` +and use `start`, `await_task`, `continue_task`, `cancel`, and `report` directly. +The `task_in_process` example runs this path against the local travel page, +without loading the module or calling TinyBus. - `docs/technical/jev-harness.md` maps every layer between a request and a Jev call, and `docs/technical/jev-journal.md` the debug journal (`TINYCOMPUTER_JEV_JOURNAL`) diff --git a/docs/crates/tinycomputer-engine/README.md b/docs/crates/tinycomputer-engine/README.md index 5b4d5065e..f103c3e6c 100644 --- a/docs/crates/tinycomputer-engine/README.md +++ b/docs/crates/tinycomputer-engine/README.md @@ -7,7 +7,9 @@ crate, `tinycomputer-engine`, is that harness. It reads the screen, asks Jev what to do, checks the answer, acts, verifies the action landed, and enforces safety, and it keeps a task moving until it is done, blocked, or needs a person. If `tinycomputer-desktop` is the hand that clicks and -types, this crate is the part that decides where the hand goes next. +types, this crate is the part that decides where the hand goes next. The +default `desktop` feature enables desktop entry points; embedding hosts can +disable it and use `BrowserRunner` with `tinycomputer-browser` alone. It has no bus of its own. The `tinycomputer` crate wraps these functions as TinyBus members; this crate only holds the logic. @@ -21,7 +23,7 @@ TinyBus members; this crate only holds the logic. | Run a bounded goal | `src/agentic/goal.rs` and `src/agentic/task/` (`run_goal`) | An observe-decide-act loop toward one visible end state, with a confirmation handle for anything hard to undo. | | The high-level flow runtime | `src/agentic/flow/` | Runs a whole flow (the plain-language step language), one step at a time. Documented separately: see [flow/README.md](flow/README.md). | | The debug journal | `src/agentic/journal/` | Every Jev exchange and how long each part of a run took, written to disk, opt-in and inert when off. | -| The task controller | `src/task/` | Runs a flow in the background as a long-lived task, and reports it as a status a calling model can act on: needs input, needs approval, checkpoint, needs a person, done, or failed. | +| The task controller | `src/task/` | `Tasks` runs a flow in the background and reports its status; `BrowserRunner` supplies one in-process browser session per task without TinyBus. | | The planner | `src/planner/` | Turns a plain-language task into a flow, using a language model that never touches the screen. | | The rescuer | `src/rescue/` | Consulted only when a task's step fails; suggests replacement steps or gives up. | | The shaper | `src/shape/` | Turns a finished task's saved records into the JSON its caller asked for, one reasoning-model pass. See [output.md](output.md). | diff --git a/docs/crates/tinycomputer-engine/jev-runtime.md b/docs/crates/tinycomputer-engine/jev-runtime.md index afaac145a..f6a1ef39a 100644 --- a/docs/crates/tinycomputer-engine/jev-runtime.md +++ b/docs/crates/tinycomputer-engine/jev-runtime.md @@ -18,8 +18,9 @@ sees every exchange, with nothing able to slip past it. ## Configuring a runtime -A `JevRuntime` is built once, from the module's private configuration, with -`JevRuntime::configure`: +A `JevRuntime` is built once from a host's `JevConfig` with +`JevRuntime::configure`. The TinyBus module receives this configuration from +its loader; an embedding host can construct the same value directly: ```rust let runtime = JevRuntime::configure(&JevConfig { diff --git a/docs/crates/tinycomputer-engine/tasks.md b/docs/crates/tinycomputer-engine/tasks.md index 81852b952..df73401ac 100644 --- a/docs/crates/tinycomputer-engine/tasks.md +++ b/docs/crates/tinycomputer-engine/tasks.md @@ -1,8 +1,12 @@ # Tasks -`Tasks`, in `crates/tinycomputer-engine/src/task/controller.rs`, is the controller -behind the Agent interface: the thing most callers should actually use -instead of `RunGoal` or `ResolveIntent` directly. Give it a flow (or a +`Tasks`, in `crates/tinycomputer-engine/src/task/controller.rs`, is the public +controller behind the Agent interface: the thing most callers should actually +use instead of `RunGoal` or `ResolveIntent` directly. An embedding host can +construct it with `Tasks::new(Arc::new(BrowserRunner::new(browser, runtime)))` +and call the same start, await, continue, cancel, and report methods the module +serves over TinyBus. `BrowserRunner` keeps one in-process browser session per +task and requires no desktop adapter. Give it a flow (or a plain-language task, with a planner configured) and it runs that flow in the background, reporting back a status a calling model can act on: still running, needs a value, needs approval, reached a checkpoint, needs a From 2e0afd5ae344312587b7d40d83d28d8f2aaeeda2 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 03:14:41 +0530 Subject: [PATCH 07/73] feat(engine): accept host model routes and tally usage Co-authored-by: Medulla --- .../tinycomputer-bus/src/agent/agent_tests.rs | 1 + .../src/agent/types/models.rs | 3 + .../src/agent/types/report.rs | 5 +- .../src/agent/types/status.rs | 6 +- .../tinycomputer-bus/src/agent/types/usage.rs | 17 +- .../src/agent/types/usage_tests.rs | 2 +- crates/tinycomputer-bus/src/version/mod.rs | 4 +- .../src/version/version_tests.rs | 4 +- .../src/agentic/journal/journal_tests.rs | 2 + .../src/agentic/runtime.rs | 24 +- .../src/agentic/runtime_tests.rs | 245 ++++++++++++++++++ .../src/agentic/sage/mod.rs | 2 + crates/tinycomputer-engine/src/lib.rs | 14 +- .../tinycomputer-engine/src/planner/config.rs | 49 +++- .../tinycomputer-engine/src/planner/hosted.rs | 102 +++++++- crates/tinycomputer-engine/src/planner/mod.rs | 72 ++++- .../src/planner/planner_tests.rs | 9 + crates/tinycomputer-engine/src/rescue/mod.rs | 28 +- crates/tinycomputer-engine/src/shape/mod.rs | 28 +- .../src/task/controller.rs | 10 +- crates/tinycomputer-engine/src/task/drive.rs | 11 + .../tinycomputer-engine/src/task/publish.rs | 58 +++-- .../tinycomputer-engine/src/task/recovery.rs | 6 + crates/tinycomputer-engine/src/task/resume.rs | 8 +- crates/tinycomputer-engine/src/task/store.rs | 22 +- .../src/task/task_tests/status_tests.rs | 26 ++ crates/tinycomputer-engine/src/usage.rs | 25 +- crates/tinycomputer-engine/src/usage_tests.rs | 2 +- 28 files changed, 698 insertions(+), 87 deletions(-) create mode 100644 crates/tinycomputer-engine/src/agentic/runtime_tests.rs diff --git a/crates/tinycomputer-bus/src/agent/agent_tests.rs b/crates/tinycomputer-bus/src/agent/agent_tests.rs index 2bea8074d..7d7d1a48f 100644 --- a/crates/tinycomputer-bus/src/agent/agent_tests.rs +++ b/crates/tinycomputer-bus/src/agent/agent_tests.rs @@ -223,6 +223,7 @@ fn replies_carry_data_or_an_actionable_error() { step: None, progress: 0.25, next: vec!["AwaitTask".to_owned()], + usage: Default::default(), }; let ok = serde_json::to_value(AgentResponse::ok(view)).unwrap(); assert_eq!(ok["ok"], true); diff --git a/crates/tinycomputer-bus/src/agent/types/models.rs b/crates/tinycomputer-bus/src/agent/types/models.rs index 46afa1db4..3dfe455b3 100644 --- a/crates/tinycomputer-bus/src/agent/types/models.rs +++ b/crates/tinycomputer-bus/src/agent/types/models.rs @@ -19,6 +19,9 @@ pub enum LanguageModelProvider { /// (`https://api.tinyhumans.ai/openai/v1`), with the host's `TinyHumans` /// bearer. It takes the same `vendor/model` ids as `OpenRouter`. TinyHumans, + /// A host-selected OpenAI-compatible endpoint, only for Rust embedding + /// hosts; `TinyBus` configuration does not allow custom endpoints. + OpenAiCompatible, } /// Non-secret summary of one configured language model: its route and model. diff --git a/crates/tinycomputer-bus/src/agent/types/report.rs b/crates/tinycomputer-bus/src/agent/types/report.rs index 0e441552e..e9448e1cf 100644 --- a/crates/tinycomputer-bus/src/agent/types/report.rs +++ b/crates/tinycomputer-bus/src/agent/types/report.rs @@ -4,7 +4,7 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; -use super::TaskView; +use super::{TaskUsage, TaskView}; use crate::browser::OutputRef; use crate::flow::{Flow, FlowStep, GroundingHint, JevExchange, StepReport}; @@ -13,6 +13,9 @@ use crate::flow::{Flow, FlowStep, GroundingHint, JevExchange, StepReport}; pub struct TaskReport { /// The task as it stands. pub view: TaskView, + /// Provider-reported model usage accumulated over the task's lifetime. + #[serde(default, skip_serializing_if = "TaskUsage::is_empty")] + pub usage: TaskUsage, /// The flow it ran. #[serde(default, skip_serializing_if = "Option::is_none")] pub flow: Option, diff --git a/crates/tinycomputer-bus/src/agent/types/status.rs b/crates/tinycomputer-bus/src/agent/types/status.rs index 40b790bf9..abb6d3376 100644 --- a/crates/tinycomputer-bus/src/agent/types/status.rs +++ b/crates/tinycomputer-bus/src/agent/types/status.rs @@ -5,7 +5,7 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use serde_json::Value; -use super::TaskId; +use super::{TaskId, TaskUsage}; use crate::browser::OutputRef; /// A task's current state, as every call reports it. @@ -25,6 +25,10 @@ pub struct TaskView { /// The member calls that make sense now, such as `AwaitTask` or /// `ContinueTask`. pub next: Vec, + /// Provider-reported model usage accumulated so far, including on a + /// cancelled or timed-out task. + #[serde(default, skip_serializing_if = "TaskUsage::is_empty")] + pub usage: TaskUsage, } /// The step a task is on. diff --git a/crates/tinycomputer-bus/src/agent/types/usage.rs b/crates/tinycomputer-bus/src/agent/types/usage.rs index cc7218969..641aab67c 100644 --- a/crates/tinycomputer-bus/src/agent/types/usage.rs +++ b/crates/tinycomputer-bus/src/agent/types/usage.rs @@ -21,9 +21,9 @@ pub struct ModelUsage { /// Provider-reported output tokens, when available. #[serde(default, skip_serializing_if = "Option::is_none")] pub output_tokens: Option, - /// Provider-reported USD charge in integer micro-dollars, when available. + /// Provider-reported USD charge in integer nanodollars, when available. #[serde(default, skip_serializing_if = "Option::is_none")] - pub cost_usd_micros: Option, + pub cost_usd_nanos: Option, } /// Per-role model usage accumulated over a task's lifetime. @@ -62,7 +62,7 @@ impl ModelUsage { && self.input_tokens.is_none() && self.cached_input_tokens.is_none() && self.output_tokens.is_none() - && self.cost_usd_micros.is_none() + && self.cost_usd_nanos.is_none() } /// Adds one request and any measurements its provider returned. @@ -71,18 +71,15 @@ impl ModelUsage { input_tokens: Option, cached_input_tokens: Option, output_tokens: Option, - cost_usd_micros: Option, + cost_usd_nanos: Option, ) { self.calls = self.calls.saturating_add(1); add_unsigned(&mut self.input_tokens, input_tokens); add_unsigned(&mut self.cached_input_tokens, cached_input_tokens); add_unsigned(&mut self.output_tokens, output_tokens); - if let Some(cost) = cost_usd_micros { - self.cost_usd_micros = Some( - self.cost_usd_micros - .unwrap_or_default() - .saturating_add(cost), - ); + if let Some(cost) = cost_usd_nanos { + self.cost_usd_nanos = + Some(self.cost_usd_nanos.unwrap_or_default().saturating_add(cost)); } } } diff --git a/crates/tinycomputer-bus/src/agent/types/usage_tests.rs b/crates/tinycomputer-bus/src/agent/types/usage_tests.rs index 42528aa7f..94252f626 100644 --- a/crates/tinycomputer-bus/src/agent/types/usage_tests.rs +++ b/crates/tinycomputer-bus/src/agent/types/usage_tests.rs @@ -14,7 +14,7 @@ fn keeps_unreported_usage_unknown_and_accumulates_reported_values() { assert_eq!(usage.input_tokens, Some(18)); assert_eq!(usage.cached_input_tokens, Some(6)); assert_eq!(usage.output_tokens, Some(8)); - assert_eq!(usage.cost_usd_micros, Some(19)); + assert_eq!(usage.cost_usd_nanos, Some(19)); } #[test] diff --git a/crates/tinycomputer-bus/src/version/mod.rs b/crates/tinycomputer-bus/src/version/mod.rs index df0cfe38d..c26022e07 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, 20); +pub const CONTRACT_VERSION: (u32, u32) = (2, 21); /// 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, 20); /// ``` /// # use tinycomputer_bus::{is_compatible, CONTRACT_VERSION}; /// assert!(is_compatible(CONTRACT_VERSION)); -/// assert!(is_compatible((2, 20))); +/// assert!(is_compatible((2, 21))); /// 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 f3d7b52be..3fb692a88 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, 20)); + assert_eq!(CONTRACT_VERSION, (2, 21)); } #[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, 20))); + assert!(is_compatible((2, 21))); assert!(is_compatible((2, 97))); // 2.12 adds replayable GlobeRead and joined terminal GlobeShutdown. // A 2.11 module does not implement those members. diff --git a/crates/tinycomputer-engine/src/agentic/journal/journal_tests.rs b/crates/tinycomputer-engine/src/agentic/journal/journal_tests.rs index 09b4b7e50..a7fe70d01 100644 --- a/crates/tinycomputer-engine/src/agentic/journal/journal_tests.rs +++ b/crates/tinycomputer-engine/src/agentic/journal/journal_tests.rs @@ -117,6 +117,8 @@ fn a_begun_run_writes_a_run_event_then_each_exchange() { usage: Usage { input_tokens: Some(120), output_tokens: Some(4), + cached_input_tokens: None, + cost_usd_nanos: None, }, }, request_id: Some("req-1".to_owned()), diff --git a/crates/tinycomputer-engine/src/agentic/runtime.rs b/crates/tinycomputer-engine/src/agentic/runtime.rs index cca25ab32..122881b6e 100644 --- a/crates/tinycomputer-engine/src/agentic/runtime.rs +++ b/crates/tinycomputer-engine/src/agentic/runtime.rs @@ -68,6 +68,7 @@ impl std::fmt::Debug for JevRuntime { .field("pending", &"[redacted]") .field("journal", &self.journal) .field("copies", &self.copies) + .field("usage", &self.usage.as_ref().map(|_| "[tracked]")) .finish() } } @@ -89,7 +90,7 @@ impl JevRuntime { /// Build a Jev runtime for an embedding host, allowing the host to route /// its configured provider to a private endpoint. /// - /// The TinyBus module uses [`JevRuntime::configure`], which retains the + /// The `TinyBus` module uses [`JevRuntime::configure`], which retains the /// module's provider allow-list. This constructor is for Rust hosts that /// own and trust their configuration. /// @@ -303,16 +304,25 @@ impl JevRuntime { usage.record_started(ModelRole::Jev); } let outcome = self.client.evaluate(request).await; - if let Some(usage) = &self.usage { - if let Ok(result) = &outcome { + match (&self.usage, &outcome) { + (Some(usage), Ok(result)) => { + usage.record_additional_calls( + ModelRole::Jev, + u64::from(result.attempts.saturating_sub(1)), + ); usage.record_measurements( ModelRole::Jev, result.response.usage.input_tokens, - None, + result.response.usage.cached_input_tokens, result.response.usage.output_tokens, - None, + result.response.usage.cost_usd_nanos, ); } + (Some(usage), Err(failure)) => usage.record_additional_calls( + ModelRole::Jev, + u64::from(failure.attempts.saturating_sub(1)), + ), + _ => {} } self.journal.exchange(step, request, outcome.as_ref()); outcome @@ -440,3 +450,7 @@ pub(super) fn client_config(request: &JevConfig) -> ClientConfig { pub(super) fn config_error(error: &JevError) -> Box { Box::new(DesktopError::new("JEV_INVALID_CONFIG", error.to_string())) } + +#[cfg(test)] +#[path = "runtime_tests.rs"] +mod tests; diff --git a/crates/tinycomputer-engine/src/agentic/runtime_tests.rs b/crates/tinycomputer-engine/src/agentic/runtime_tests.rs new file mode 100644 index 000000000..468354e0a --- /dev/null +++ b/crates/tinycomputer-engine/src/agentic/runtime_tests.rs @@ -0,0 +1,245 @@ +//! Host endpoint and Jev usage integration tests. + +use std::sync::Arc; + +#[cfg(feature = "planner")] +use std::io::{Read, Write}; +#[cfg(feature = "planner")] +use std::net::{TcpListener, TcpStream}; + +use serde_json::json; +use tinycomputer_bus::agentic::JevConfig; +#[cfg(feature = "planner")] +use tinycomputer_bus::agentic::JevProvider; +use tinyinference_decisions::{EvaluationRequest, Noul, Question}; + +use super::JevRuntime; +use crate::UsageRecorder; + +#[cfg(feature = "planner")] +type StubServer = ( + String, + Arc, + std::thread::JoinHandle>>, +); + +#[cfg(feature = "planner")] +#[tokio::test] +async fn host_planner_rescue_output_and_jev_calls_stay_on_the_supplied_stub() +-> Result<(), Box> { + let _network_test = crate::MODEL_NETWORK_TEST_MUTEX.lock().await; + use crate::{Briefing, Harvest, HostModels, openai_compatible_models}; + use tinycomputer_bus::agent::SurfaceKind; + + const PLAN: &str = r#"{"app":"browser","steps":[{"browse":"https://example.com"}]}"#; + const RESCUE: &str = r#"{"action":"give_up","reason":"no repair"}"#; + const OUTPUT: &str = r#"{"answer":"done"}"#; + + let (base, requests, server) = stub_server([PLAN, RESCUE, OUTPUT])?; + let models = HostModels { + planner: host_model(&base, "planner-secret", "planner-local"), + rescue: Some(host_model(&base, "rescue-secret", "rescue-local")), + output: Some(host_model(&base, "output-secret", "output-local")), + }; + let debug = format!("{models:?}"); + for secret in ["planner-secret", "rescue-secret", "output-secret"] { + assert!(!debug.contains(secret)); + } + + let usage = Arc::new(UsageRecorder::default()); + let (planner, rescuer, shaper) = + openai_compatible_models(&models).map_err(std::io::Error::other)?; + let planner = planner.with_usage_recorder(Arc::clone(&usage)); + let rescuer = rescuer.with_usage_recorder(Arc::clone(&usage)); + let shaper = shaper.with_usage_recorder(Arc::clone(&usage)); + + let (plan, _) = planner + .plan_measured("open the example page", &[], &[], &[SurfaceKind::Browser]) + .await; + assert!(plan.is_ok(), "{plan:?}"); + assert!(matches!( + rescuer + .guide(&Briefing::default()) + .await + .map_err(std::io::Error::other)?, + crate::Guidance::GiveUp { .. } + )); + let output = shaper + .shape(&Harvest::default()) + .await + .map_err(std::io::Error::other)?; + assert_eq!(output["answer"], "done"); + + let mut jev = JevConfig::new("jev-secret"); + jev.provider = JevProvider::OpenRouter; + jev.model = Some("jev-latest".to_owned()); + jev.endpoint_url = Some(base.trim_end_matches("/v1").to_owned() + "/jev"); + let runtime = JevRuntime::configure_for_host(&jev) + .map_err(|error| std::io::Error::other(error.message.clone()))? + .with_usage_recorder(Arc::clone(&usage)); + runtime.evaluate(None, &jev_request()).await?; + + let seen = server + .join() + .map_err(|_| std::io::Error::other("stub server thread panicked"))??; + assert_stub_routes(&seen); + assert_eq!(requests.load(std::sync::atomic::Ordering::Relaxed), 4); + assert_usage(&usage); + Ok(()) +} + +#[tokio::test] +async fn failed_jev_attempt_keeps_its_started_call_in_the_tally() +-> Result<(), Box> { + let usage = Arc::new(UsageRecorder::default()); + let mut config = JevConfig::new("k"); + config.endpoint_url = Some("http://127.0.0.1:1/jev".to_owned()); + config.max_retries = Some(0); + let runtime = JevRuntime::configure_for_host(&config) + .map_err(|error| std::io::Error::other(error.message.clone()))? + .with_usage_recorder(Arc::clone(&usage)); + let _ = runtime.evaluate(None, &jev_request()).await; + assert_eq!(usage.snapshot().jev.calls, 1); + Ok(()) +} + +#[cfg(feature = "planner")] +fn host_model(base_url: &str, api_key: &str, model: &str) -> crate::HostModelConfig { + crate::HostModelConfig { + api_key: api_key.to_owned(), + base_url: base_url.to_owned(), + model: model.to_owned(), + } +} + +fn jev_request() -> EvaluationRequest { + EvaluationRequest::new( + "jev-latest", + json!("The stub integration test."), + [( + "ready".to_owned(), + Question::Noul(Noul { + instructions: json!("Is the test request ready?"), + criteria: None, + }), + )] + .into(), + ) +} + +#[cfg(feature = "planner")] +fn assert_stub_routes(requests: &[String]) { + assert_eq!(requests.len(), 4, "all four model calls must hit this stub"); + assert_eq!( + requests + .iter() + .filter(|request| request.starts_with("POST /v1/chat/completions ")) + .count(), + 3 + ); + assert!( + requests + .iter() + .any(|request| request.starts_with("POST /jev ")) + ); + for model in ["planner-local", "rescue-local", "output-local"] { + assert!( + requests.iter().any(|request| request.contains(model)), + "no local request used {model}" + ); + } +} + +#[cfg(feature = "planner")] +fn assert_usage(recorder: &UsageRecorder) { + let tally = recorder.snapshot(); + for role in [tally.planner, tally.rescue, tally.output] { + assert_eq!(role.calls, 1); + assert_eq!(role.input_tokens, Some(10)); + assert_eq!(role.cached_input_tokens, Some(2)); + assert_eq!(role.output_tokens, Some(3)); + assert_eq!(role.cost_usd_nanos, Some(400)); + } + assert_eq!(tally.jev.calls, 1); + assert_eq!(tally.jev.input_tokens, Some(20)); + assert_eq!(tally.jev.cached_input_tokens, Some(7)); + assert_eq!(tally.jev.output_tokens, Some(5)); + assert_eq!(tally.jev.cost_usd_nanos, Some(400)); +} + +#[cfg(feature = "planner")] +fn stub_server(replies: [&'static str; 3]) -> std::io::Result { + let listener = TcpListener::bind("127.0.0.1:0")?; + let address = listener.local_addr()?; + let base = format!("http://{address}/v1"); + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let counted = Arc::clone(&calls); + let server = std::thread::spawn(move || { + let mut requests = Vec::new(); + for _ in 0..4 { + let (mut stream, _) = listener.accept()?; + let raw = read_request(&mut stream)?; + counted.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let path = raw.lines().next().unwrap_or_default(); + if path.starts_with("POST /jev ") { + let body = json!({ + "model": "typesafe/jev-v1", + "answers": {"ready": {"type": "noul", "noul": 0.99}}, + "usage": { + "input_tokens": 20, + "cached_input_tokens": 7, + "output_tokens": 5, + "cost": 0.000_000_4 + } + }) + .to_string(); + write_response(&mut stream, "application/json", &body)?; + } else { + let call = replies[requests.len()]; + let body = format!( + "data: {{\"id\":\"stub\",\"choices\":[{{\"index\":0,\"delta\":{{\"role\":\"assistant\",\"content\":{}}},\"finish_reason\":null}}]}}\n\n\ + data: {{\"id\":\"stub\",\"choices\":[{{\"index\":0,\"delta\":{{}},\"finish_reason\":\"stop\"}}],\"usage\":{{\"prompt_tokens\":10,\"completion_tokens\":3,\"total_tokens\":13,\"prompt_tokens_details\":{{\"cached_tokens\":2}},\"cost\":0.0000004}}}}\n\n\ + data: [DONE]\n\n", + serde_json::to_string(call).map_err(std::io::Error::other)? + ); + write_response(&mut stream, "text/event-stream", &body)?; + } + requests.push(raw); + } + Ok(requests) + }); + Ok((base, calls, server)) +} + +#[cfg(feature = "planner")] +fn read_request(stream: &mut TcpStream) -> std::io::Result { + let mut bytes = Vec::new(); + let mut byte = [0; 1]; + while !bytes.ends_with(b"\r\n\r\n") { + stream.read_exact(&mut byte)?; + bytes.push(byte[0]); + } + let headers = String::from_utf8_lossy(&bytes); + let length = headers + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse::().ok()) + .flatten() + }) + .unwrap_or_default(); + let offset = bytes.len(); + bytes.resize(offset + length, 0); + stream.read_exact(&mut bytes[offset..])?; + String::from_utf8(bytes).map_err(std::io::Error::other) +} + +#[cfg(feature = "planner")] +fn write_response(stream: &mut TcpStream, content_type: &str, body: &str) -> std::io::Result<()> { + write!( + stream, + "HTTP/1.1 200 OK\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", + body.len() + ) +} diff --git a/crates/tinycomputer-engine/src/agentic/sage/mod.rs b/crates/tinycomputer-engine/src/agentic/sage/mod.rs index 898d67e1c..5c62482b4 100644 --- a/crates/tinycomputer-engine/src/agentic/sage/mod.rs +++ b/crates/tinycomputer-engine/src/agentic/sage/mod.rs @@ -93,6 +93,8 @@ impl super::Evaluator for SageEvaluator { .as_ref() .map(|usage| usage.billed_input_tokens), output_tokens: None, + cached_input_tokens: None, + cost_usd_nanos: None, }, }, request_id: None, diff --git a/crates/tinycomputer-engine/src/lib.rs b/crates/tinycomputer-engine/src/lib.rs index 59f6a9447..9a6b9db59 100644 --- a/crates/tinycomputer-engine/src/lib.rs +++ b/crates/tinycomputer-engine/src/lib.rs @@ -38,15 +38,23 @@ mod task; mod usage; mod workspace; +#[cfg(test)] +pub(crate) static MODEL_NETWORK_TEST_MUTEX: tokio::sync::Mutex<()> = + tokio::sync::Mutex::const_new(()); + pub use agentic::{ JOURNAL_DEFAULT_DIR, JOURNAL_ENV, JOURNAL_FILE, JevRuntime, flow_guide, resolve_intent, run_flow, run_goal, validate_flow, }; -pub use planner::{Completion, LanguageModel, ModelUse, Planner, REPAIRS, Role, Turn}; +pub use planner::{ + Completion, LanguageModel, ModelReply, ModelUse, Planner, REPAIRS, ReportedCompletion, + ReportedUsage, Role, Turn, +}; #[cfg(feature = "planner")] pub use planner::{ - ModelRoute, OPEN_ROUTER_BASE_URL, OUTPUT_MODEL, PLANNER_MODEL, PlannerConfig, RESCUE_MODEL, - TINYHUMANS_BASE_URL, open_router, open_router_rescuer, open_router_shaper, + HostModelConfig, HostModels, ModelRoute, OPEN_ROUTER_BASE_URL, OUTPUT_MODEL, PLANNER_MODEL, + PlannerConfig, RESCUE_MODEL, TINYHUMANS_BASE_URL, open_router, open_router_rescuer, + open_router_shaper, openai_compatible_models, }; pub use rescue::{Briefing, Guidance, MAX_RESCUE_STEPS, MAX_RESCUES, Rescuer, SCREEN_CHARS}; pub use shape::{Harvest, RECORDS_CHARS, Shaper}; diff --git a/crates/tinycomputer-engine/src/planner/config.rs b/crates/tinycomputer-engine/src/planner/config.rs index a798aefde..40437ef20 100644 --- a/crates/tinycomputer-engine/src/planner/config.rs +++ b/crates/tinycomputer-engine/src/planner/config.rs @@ -98,6 +98,44 @@ pub struct ModelRoute { pub sdk_name: Option, } +/// A host-owned OpenAI-compatible model endpoint. +/// +/// Use one configuration per role when planner, rescue, or output models need +/// different routes. The key is neither serializable nor printed by `Debug`. +#[derive(Clone, Deserialize)] +pub struct HostModelConfig { + /// The host's provider credential. + pub api_key: String, + /// The provider's OpenAI-compatible base URL. + pub base_url: String, + /// Model id understood by that endpoint. + pub model: String, +} + +impl std::fmt::Debug for HostModelConfig { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("HostModelConfig") + .field("api_key", &"[REDACTED]") + .field("base_url", &self.base_url) + .field("model", &self.model) + .finish() + } +} + +/// Independent host-supplied model configurations for each task role. +#[derive(Debug, Clone, Deserialize)] +pub struct HostModels { + /// Model used to draft plain-language tasks. + pub planner: HostModelConfig, + /// Model used to recover failed steps. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub rescue: Option, + /// Model used to shape a completed task's output. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output: Option, +} + impl std::fmt::Debug for ModelRoute { /// Never prints the key. fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -125,6 +163,11 @@ impl ModelRoute { if self.api_key.trim().is_empty() { return Err("the planner configuration needs an api_key".to_owned()); } + if self.provider == LanguageModelProvider::OpenAiCompatible { + return Err( + "open_ai_compatible routes are available only to Rust embedding hosts".to_owned(), + ); + } let base_url = match &self.endpoint_url { Some(endpoint) if trusted_base_url(self.provider, endpoint) => { endpoint.trim_end_matches('/').to_owned() @@ -138,7 +181,7 @@ impl ModelRoute { LanguageModelProvider::TinyHumans => { self.sdk_name.as_deref().and_then(sanitized_sdk_name) } - LanguageModelProvider::OpenRouter => None, + LanguageModelProvider::OpenRouter | LanguageModelProvider::OpenAiCompatible => None, }; Ok(ResolvedRoute { provider: self.provider, @@ -163,12 +206,16 @@ pub(super) const fn approved_base_url(provider: LanguageModelProvider) -> &'stat match provider { LanguageModelProvider::OpenRouter => OPEN_ROUTER_BASE_URL, LanguageModelProvider::TinyHumans => TINYHUMANS_BASE_URL, + LanguageModelProvider::OpenAiCompatible => "", } } /// Whether `endpoint` is `provider`'s approved base URL, with or without a /// trailing slash. pub(super) fn trusted_base_url(provider: LanguageModelProvider, endpoint: &str) -> bool { + if matches!(provider, LanguageModelProvider::OpenAiCompatible) { + return false; + } if endpoint.trim_end_matches('/') == approved_base_url(provider) { return true; } diff --git a/crates/tinycomputer-engine/src/planner/hosted.rs b/crates/tinycomputer-engine/src/planner/hosted.rs index ecb817dda..54524557f 100644 --- a/crates/tinycomputer-engine/src/planner/hosted.rs +++ b/crates/tinycomputer-engine/src/planner/hosted.rs @@ -10,7 +10,7 @@ use std::future::Future; use std::sync::Arc; use std::time::Duration; -use tinycomputer_bus::agent::LanguageModelProvider; +use tinycomputer_bus::agent::{LanguageModelConfiguration, LanguageModelProvider}; use tinyinference_llm::model::{ ReasoningConfig, ReasoningEffort, ResponseFormat, collect_model_stream, }; @@ -20,8 +20,13 @@ use tinyinference_llm::{ classify_provider_failure, }; -use super::config::{ModelRoute, OUTPUT_MODEL, PLANNER_MODEL, PlannerConfig, RESCUE_MODEL}; -use super::{Completion, LanguageModel, Planner, Role, Turn}; +use super::config::{ + HostModelConfig, HostModels, ModelRoute, OUTPUT_MODEL, PLANNER_MODEL, PlannerConfig, + RESCUE_MODEL, +}; +use super::{ + Completion, LanguageModel, ModelReply, Planner, ReportedCompletion, ReportedUsage, Role, Turn, +}; use crate::rescue::Rescuer; use crate::shape::Shaper; @@ -88,6 +93,75 @@ pub fn open_router_shaper(config: &PlannerConfig) -> Result { .with_configuration(config.route.describe(&model))) } +/// Builds planner, rescue, and output adapters from host-owned compatible +/// endpoints. Missing rescue or output routes reuse the planner model. +/// +/// This constructor accepts any base URL because a Rust embedding host owns +/// the route. `TinyBus` configuration continues to use the fixed provider +/// allow-list. +/// +/// # Errors +/// +/// Returns why a supplied host route cannot build a model client. +pub fn openai_compatible_models(models: &HostModels) -> Result<(Planner, Rescuer, Shaper), String> { + let planner = host_role(&models.planner, Some(0.2), None, 4_000)?; + let rescue = host_role( + models.rescue.as_ref().unwrap_or(&models.planner), + None, + Some(ReasoningEffort::Low), + 8_000, + )?; + let output = host_role( + models.output.as_ref().unwrap_or(&models.planner), + None, + Some(ReasoningEffort::Low), + 16_000, + )?; + Ok(( + Planner::new(planner.0).with_configuration(planner.1), + Rescuer::new(rescue.0).with_configuration(rescue.1), + Shaper::new(output.0).with_configuration(output.1), + )) +} + +fn host_role( + config: &HostModelConfig, + temperature: Option, + reasoning: Option, + max_tokens: u32, +) -> Result<(Arc, LanguageModelConfiguration), String> { + if config.api_key.trim().is_empty() { + return Err("host model configuration needs an api_key".to_owned()); + } + if config.base_url.trim().is_empty() { + return Err("host model configuration needs a base_url".to_owned()); + } + if config.model.trim().is_empty() { + return Err("host model configuration needs a model".to_owned()); + } + let base_url = config.base_url.trim_end_matches('/').to_owned(); + let spec = ProviderSpec::for_kind(ProviderKind::Compatible) + .with_model(config.model.clone()) + .with_base_url(base_url.clone()); + let model = OpenAiModel::from_spec(spec, config.api_key.clone()) + .map_err(|error| error.to_string())? + .with_json_object_format(true); + let configuration = LanguageModelConfiguration { + provider: LanguageModelProvider::OpenAiCompatible, + model: config.model.clone(), + endpoint_url: Some(base_url), + }; + Ok(( + Arc::new(Hosted { + model: Arc::new(model), + temperature, + reasoning, + max_tokens, + }), + configuration, + )) +} + /// `configured`, unless absent or blank, else `default`. fn model_name(configured: Option<&String>, default: &str) -> String { configured @@ -102,6 +176,9 @@ pub(super) fn chat_model(route: &ModelRoute, model: &str) -> Result ProviderKind::OpenRouter, LanguageModelProvider::TinyHumans => ProviderKind::TinyHumans, + LanguageModelProvider::OpenAiCompatible => { + return Err("open_ai_compatible routes require the host constructor".to_owned()); + } }; let spec = ProviderSpec::for_kind(kind) .with_model(model) @@ -124,6 +201,11 @@ struct Hosted { impl LanguageModel for Hosted { fn complete(&self, turns: &[Turn]) -> Completion { + let completion = self.complete_reported(turns); + Box::pin(async move { completion.await.map(|reply| reply.text) }) + } + + fn complete_reported(&self, turns: &[Turn]) -> ReportedCompletion { let model = self.model.clone(); let messages = turns .iter() @@ -153,7 +235,19 @@ impl LanguageModel for Hosted { async move { let stream = model.stream(&(), request).await?; let response = collect_model_stream(stream).await?; - Ok(Message::Assistant(response.message).text()) + let usage = + response + .usage + .map_or_else(ReportedUsage::default, |usage| ReportedUsage { + input_tokens: Some(usage.input_tokens), + cached_input_tokens: Some(usage.cache_read_tokens), + output_tokens: Some(usage.output_tokens), + cost_usd_nanos: usage.charged_amount_nanos, + }); + Ok(ModelReply { + text: Message::Assistant(response.message).text(), + usage, + }) } }) .await diff --git a/crates/tinycomputer-engine/src/planner/mod.rs b/crates/tinycomputer-engine/src/planner/mod.rs index 3bddd6fef..dff5572fd 100644 --- a/crates/tinycomputer-engine/src/planner/mod.rs +++ b/crates/tinycomputer-engine/src/planner/mod.rs @@ -23,6 +23,7 @@ use std::future::Future; use std::pin::Pin; use std::sync::Arc; +use crate::{ModelRole, UsageRecorder}; use serde_json::Value; use tinycomputer_bus::agent::{InputField, LanguageModelConfiguration, SurfaceKind, TaskPlan}; use tinycomputer_bus::{FLOW_GUIDE, Flow}; @@ -30,11 +31,11 @@ use tinycomputer_core::is_sensitive_name; #[cfg(feature = "planner")] pub use config::{ - ModelRoute, OPEN_ROUTER_BASE_URL, OUTPUT_MODEL, PLANNER_MODEL, PlannerConfig, RESCUE_MODEL, - TINYHUMANS_BASE_URL, + HostModelConfig, HostModels, ModelRoute, OPEN_ROUTER_BASE_URL, OUTPUT_MODEL, PLANNER_MODEL, + PlannerConfig, RESCUE_MODEL, TINYHUMANS_BASE_URL, }; #[cfg(feature = "planner")] -pub use hosted::{open_router, open_router_rescuer, open_router_shaper}; +pub use hosted::{open_router, open_router_rescuer, open_router_shaper, openai_compatible_models}; /// Validation repairs a plan gets. pub const REPAIRS: usize = 2; @@ -63,6 +64,28 @@ pub struct ModelUse { pub sent_bytes: usize, } +/// Provider-reported measurements for one completed language-model call. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct ReportedUsage { + /// Input tokens, when the provider reported them. + pub input_tokens: Option, + /// Cached input tokens, when the provider reported them. + pub cached_input_tokens: Option, + /// Output tokens, when the provider reported them. + pub output_tokens: Option, + /// USD charge in nanodollars, when the provider reported it. + pub cost_usd_nanos: Option, +} + +/// A language-model reply and the measurements its provider supplied. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ModelReply { + /// The assistant's text. + pub text: String, + /// Usage reported for this request, absent when the provider omitted it. + pub usage: ReportedUsage, +} + impl ModelUse { /// The use of a conversation about to be sent for the first time. pub(crate) fn starting(turns: &[Turn]) -> Self { @@ -94,11 +117,27 @@ impl Turn { /// The future a [`LanguageModel`] returns: its reply text, or why it failed. pub type Completion = Pin> + Send>>; +/// Future returned by [`LanguageModel::complete_reported`]. +pub type ReportedCompletion = Pin> + Send>>; + /// A chat model that answers a conversation with text. pub trait LanguageModel: Send + Sync + 'static { /// The model's reply to `turns`, which it is asked to give as one JSON /// object. fn complete(&self, turns: &[Turn]) -> Completion; + + /// A reply with provider-reported usage. Existing scripted models may + /// implement only [`LanguageModel::complete`]; their measurements remain + /// unknown. + fn complete_reported(&self, turns: &[Turn]) -> ReportedCompletion { + let completion = self.complete(turns); + Box::pin(async move { + completion.await.map(|text| ModelReply { + text, + usage: ReportedUsage::default(), + }) + }) + } } const PROTOCOL: &str = "You plan tasks for a module that drives web pages and desktop \ @@ -130,6 +169,7 @@ sending, deleting, publishing, or submitting with a stop_before step."; pub struct Planner { model: Arc, configuration: Option, + usage: Option>, } impl std::fmt::Debug for Planner { @@ -145,6 +185,7 @@ impl Planner { Self { model, configuration: None, + usage: None, } } @@ -156,6 +197,13 @@ impl Planner { self } + /// This planner recording calls into a task-scoped collector. + #[must_use] + pub fn with_usage_recorder(mut self, usage: Arc) -> Self { + self.usage = Some(usage); + self + } + /// The route and model this planner was configured with, when known. #[must_use] pub fn configuration(&self) -> Option<&LanguageModelConfiguration> { @@ -241,8 +289,22 @@ impl Planner { let mut last = String::new(); for _ in 0..=REPAIRS { used.calls += 1; - let reply = match self.model.complete(&turns).await { - Ok(reply) => reply, + if let Some(usage) = &self.usage { + usage.record_started(ModelRole::Planner); + } + let reply = match self.model.complete_reported(&turns).await { + Ok(reply) => { + if let Some(usage) = &self.usage { + usage.record_measurements( + ModelRole::Planner, + reply.usage.input_tokens, + reply.usage.cached_input_tokens, + reply.usage.output_tokens, + reply.usage.cost_usd_nanos, + ); + } + reply.text + } Err(error) => return (Err(error), used), }; turns.push(Turn::new(Role::Assistant, reply.clone())); diff --git a/crates/tinycomputer-engine/src/planner/planner_tests.rs b/crates/tinycomputer-engine/src/planner/planner_tests.rs index 1e057c28c..5f0eaef8f 100644 --- a/crates/tinycomputer-engine/src/planner/planner_tests.rs +++ b/crates/tinycomputer-engine/src/planner/planner_tests.rs @@ -208,6 +208,8 @@ async fn a_measured_plan_counts_each_call_and_what_the_first_one_sent() { async fn the_open_router_planner_needs_a_key_and_never_prints_it() { use super::{PlannerConfig, open_router}; + let _network_test = crate::MODEL_NETWORK_TEST_MUTEX.lock().await; + let empty = PlannerConfig { route: super::ModelRoute { api_key: " ".to_owned(), @@ -238,6 +240,13 @@ async fn the_open_router_planner_needs_a_key_and_never_prints_it() { // No network in tests: the guard makes the model call fail fast, which // exercises the adapter without reaching OpenRouter. tinyinference_llm::deny_network_models(); + struct RestoreNetworkGuard; + impl Drop for RestoreNetworkGuard { + fn drop(&mut self) { + tinyinference_llm::allow_network_models(); + } + } + let _restore_network = RestoreNetworkGuard; let failed = planner.plan("x", &[], &[], &[]).await.unwrap_err(); assert!(!failed.contains("secret-key")); diff --git a/crates/tinycomputer-engine/src/rescue/mod.rs b/crates/tinycomputer-engine/src/rescue/mod.rs index 396bdd79f..83e4ff866 100644 --- a/crates/tinycomputer-engine/src/rescue/mod.rs +++ b/crates/tinycomputer-engine/src/rescue/mod.rs @@ -28,6 +28,7 @@ use tinycomputer_bus::agent::{LanguageModelConfiguration, Rescue}; use tinycomputer_bus::{FLOW_GUIDE, Flow, FlowStep, StepReport}; use crate::planner::{LanguageModel, ModelUse, REPAIRS, Role, Turn}; +use crate::{ModelRole, UsageRecorder}; use judge::judge; pub(crate) use judge::resumed; use render::render; @@ -146,6 +147,7 @@ pub enum Guidance { pub struct Rescuer { model: Arc, configuration: Option, + usage: Option>, } impl std::fmt::Debug for Rescuer { @@ -161,6 +163,7 @@ impl Rescuer { Self { model, configuration: None, + usage: None, } } @@ -172,6 +175,13 @@ impl Rescuer { self } + /// This rescuer recording calls into a task-scoped collector. + #[must_use] + pub fn with_usage_recorder(mut self, usage: Arc) -> Self { + self.usage = Some(usage); + self + } + /// The route and model this rescuer was configured with, when known. #[must_use] pub fn configuration(&self) -> Option<&LanguageModelConfiguration> { @@ -202,8 +212,22 @@ impl Rescuer { let mut last = String::new(); for _ in 0..=REPAIRS { used.calls += 1; - let reply = match self.model.complete(&turns).await { - Ok(reply) => reply, + if let Some(usage) = &self.usage { + usage.record_started(ModelRole::Rescue); + } + let reply = match self.model.complete_reported(&turns).await { + Ok(reply) => { + if let Some(usage) = &self.usage { + usage.record_measurements( + ModelRole::Rescue, + reply.usage.input_tokens, + reply.usage.cached_input_tokens, + reply.usage.output_tokens, + reply.usage.cost_usd_nanos, + ); + } + reply.text + } Err(error) => return (Err(error), used), }; turns.push(Turn::new(Role::Assistant, reply.clone())); diff --git a/crates/tinycomputer-engine/src/shape/mod.rs b/crates/tinycomputer-engine/src/shape/mod.rs index 4f2477554..b080dc87b 100644 --- a/crates/tinycomputer-engine/src/shape/mod.rs +++ b/crates/tinycomputer-engine/src/shape/mod.rs @@ -24,6 +24,7 @@ use serde_json::{Value, json}; use tinycomputer_bus::agent::{LanguageModelConfiguration, TaskOutput}; use crate::planner::{LanguageModel, REPAIRS, Role, Turn, json_object}; +use crate::{ModelRole, UsageRecorder}; /// The most characters of records one shaping pass carries. pub const RECORDS_CHARS: usize = 60_000; @@ -57,6 +58,7 @@ pub struct Harvest { pub struct Shaper { model: Arc, configuration: Option, + usage: Option>, } impl std::fmt::Debug for Shaper { @@ -72,6 +74,7 @@ impl Shaper { Self { model, configuration: None, + usage: None, } } @@ -83,6 +86,13 @@ impl Shaper { self } + /// This shaper recording calls into a task-scoped collector. + #[must_use] + pub fn with_usage_recorder(mut self, usage: Arc) -> Self { + self.usage = Some(usage); + self + } + /// The route and model this shaper was configured with, when known. #[must_use] pub fn configuration(&self) -> Option<&LanguageModelConfiguration> { @@ -102,9 +112,21 @@ impl Shaper { ]; let mut last = String::new(); for _ in 0..=REPAIRS { - let reply = self.model.complete(&turns).await?; - turns.push(Turn::new(Role::Assistant, reply.clone())); - let problem = match judge(&reply, harvest.output.schema.as_ref()) { + if let Some(usage) = &self.usage { + usage.record_started(ModelRole::Output); + } + let reply = self.model.complete_reported(&turns).await?; + if let Some(usage) = &self.usage { + usage.record_measurements( + ModelRole::Output, + reply.usage.input_tokens, + reply.usage.cached_input_tokens, + reply.usage.output_tokens, + reply.usage.cost_usd_nanos, + ); + } + turns.push(Turn::new(Role::Assistant, reply.text.clone())); + let problem = match judge(&reply.text, harvest.output.schema.as_ref()) { Ok(value) => return Ok(value), Err(problem) => problem, }; diff --git a/crates/tinycomputer-engine/src/task/controller.rs b/crates/tinycomputer-engine/src/task/controller.rs index b8f317cd0..dded61c71 100644 --- a/crates/tinycomputer-engine/src/task/controller.rs +++ b/crates/tinycomputer-engine/src/task/controller.rs @@ -232,7 +232,7 @@ impl Tasks { "The task needs values before it can start.", ); } - AgentResponse::ok(cell.view.borrow().clone()) + AgentResponse::ok(cell.current_view()) } /// Waits until the task is no longer running, or `timeout_ms` passes. @@ -316,7 +316,7 @@ impl Tasks { publish(&cell, TaskStatus::Cancelled, "The task was cancelled."); } self.runner.release(id); - AgentResponse::ok(cell.view.borrow().clone()) + AgentResponse::ok(cell.current_view()) } /// Everything the task did. @@ -325,12 +325,14 @@ impl Tasks { let Some(cell) = self.find(id) else { return no_such_task(id); }; - let view = cell.view.borrow().clone(); + let view = cell.current_view(); + let usage = view.usage; let Ok(state) = cell.state.lock() else { return poisoned(); }; AgentResponse::ok(TaskReport { view, + usage, flow: Some(state.flow.clone()), steps: state.steps.clone(), records: records(&state.reads), @@ -364,7 +366,7 @@ impl Tasks { tasks .values() .rev() - .map(|cell| cell.view.borrow().clone()) + .map(|cell| cell.current_view()) .collect(), ) } diff --git a/crates/tinycomputer-engine/src/task/drive.rs b/crates/tinycomputer-engine/src/task/drive.rs index b4f03708a..5534d2825 100644 --- a/crates/tinycomputer-engine/src/task/drive.rs +++ b/crates/tinycomputer-engine/src/task/drive.rs @@ -47,6 +47,8 @@ pub(super) async fn plan_then_drive( }, ); let id = cell.view.borrow().id.clone(); + let usage = task_usage(&cell); + let planner = planner.with_usage_recorder(Arc::clone(&usage)); // Jev's connections open while the plan is drafted, so the first // decision need not open them; nothing waits for this. A budget that // caps the task's Jev calls is not spent on calls it does not count. @@ -271,6 +273,8 @@ pub(super) async fn finish(cell: &Cell, runner: &dyn FlowRunner) { }; let result = match (harvest, cell.shaper.clone()) { (Some(harvest), Some(shaper)) => { + let usage = task_usage(cell); + let shaper = shaper.with_usage_recorder(usage); publish( cell, TaskStatus::Running, @@ -317,6 +321,13 @@ pub(super) async fn finish(cell: &Cell, runner: &dyn FlowRunner) { runner.release(&cell.view.borrow().id); } +fn task_usage(cell: &Cell) -> Arc { + cell.state + .lock() + .map(|state| Arc::clone(&state.usage)) + .unwrap_or_default() +} + /// Every variable a step of `steps` writes: a `read`'s, `extract`'s, or /// `pick`'s `into`, at any depth. fn written_names(steps: &[tinycomputer_bus::FlowStep]) -> std::collections::BTreeSet { diff --git a/crates/tinycomputer-engine/src/task/publish.rs b/crates/tinycomputer-engine/src/task/publish.rs index d0580dff0..0bc9a71f0 100644 --- a/crates/tinycomputer-engine/src/task/publish.rs +++ b/crates/tinycomputer-engine/src/task/publish.rs @@ -3,7 +3,7 @@ use std::collections::BTreeMap; -use tinycomputer_bus::agent::{InputField, StepView, TaskStatus}; +use tinycomputer_bus::agent::{InputField, StepView, TaskStatus, TaskUsage}; use super::interpret; use super::names::input_kind; @@ -31,37 +31,43 @@ pub(super) fn publish(cell: &Cell, status: TaskStatus, summary: &str) { | TaskStatus::NeedsApproval { .. } | TaskStatus::NeedsHuman { .. } ); - let (progress, step) = cell.state.lock().map_or((0.0, None), |mut state| { - // The wait starts when the task first asks; publishing the same - // pause again does not restart it. - state.waiting_since = if waits { - state - .waiting_since - .or_else(|| Some(std::time::Instant::now())) - } else { - None - }; - let total = state.flow.steps.len().max(1); - let fraction = |count: usize| f32::from(u16::try_from(count).unwrap_or(u16::MAX)); - let progress = fraction(state.finished.min(total)) / fraction(total); - let step = state.steps.last().map(|report| StepView { - index: interpret::top_index(report.path.split('.').next().unwrap_or("1")).unwrap_or(0), - total: state.flow.steps.len(), - kind: report.kind.clone(), - intent: state.facts.redact(&report.text), - surface: interpret::app_at( - &state.flow, - interpret::top_index(report.path.split('.').next().unwrap_or("1")).unwrap_or(0), - ), - }); - (progress, step) - }); + let (progress, step, usage) = + cell.state + .lock() + .map_or((0.0, None, TaskUsage::default()), |mut state| { + // The wait starts when the task first asks; publishing the same + // pause again does not restart it. + state.waiting_since = if waits { + state + .waiting_since + .or_else(|| Some(std::time::Instant::now())) + } else { + None + }; + let total = state.flow.steps.len().max(1); + let fraction = |count: usize| f32::from(u16::try_from(count).unwrap_or(u16::MAX)); + let progress = fraction(state.finished.min(total)) / fraction(total); + let step = state.steps.last().map(|report| StepView { + index: interpret::top_index(report.path.split('.').next().unwrap_or("1")) + .unwrap_or(0), + total: state.flow.steps.len(), + kind: report.kind.clone(), + intent: state.facts.redact(&report.text), + surface: interpret::app_at( + &state.flow, + interpret::top_index(report.path.split('.').next().unwrap_or("1")) + .unwrap_or(0), + ), + }); + (progress, step, state.usage.snapshot()) + }); cell.view.send_modify(|view| { view.next = next_calls(&status); view.status = status; summary.clone_into(&mut view.summary); view.progress = progress; view.step = step; + view.usage = usage; }); } diff --git a/crates/tinycomputer-engine/src/task/recovery.rs b/crates/tinycomputer-engine/src/task/recovery.rs index 8ed8a3a6e..01386e82e 100644 --- a/crates/tinycomputer-engine/src/task/recovery.rs +++ b/crates/tinycomputer-engine/src/task/recovery.rs @@ -100,6 +100,12 @@ pub(super) async fn rescue( let Some(rescuer) = cell.rescuer.clone() else { return Rescued::Skipped; }; + let usage = cell + .state + .lock() + .map(|state| std::sync::Arc::clone(&state.usage)) + .unwrap_or_default(); + let rescuer = rescuer.with_usage_recorder(usage); let (facts, goal, earlier, limit, time_left, brief_rules, reads) = { let Ok(state) = cell.state.lock() else { return Rescued::Skipped; diff --git a/crates/tinycomputer-engine/src/task/resume.rs b/crates/tinycomputer-engine/src/task/resume.rs index 0313fc5ff..7eef227ce 100644 --- a/crates/tinycomputer-engine/src/task/resume.rs +++ b/crates/tinycomputer-engine/src/task/resume.rs @@ -38,7 +38,7 @@ impl Tasks { needs_input(&missing), "The task still needs values before it can start.", ); - return AgentResponse::ok(cell.view.borrow().clone()); + return AgentResponse::ok(cell.current_view()); } // A newly supplied value can turn a reference that only looked // undefined at `StartTask` into a fact used somewhere Jev must never @@ -66,7 +66,7 @@ impl Tasks { }; drop(state); self.spawn(cell, vec![run]); - AgentResponse::ok(cell.view.borrow().clone()) + AgentResponse::ok(cell.current_view()) } pub(super) fn decide( @@ -119,7 +119,7 @@ impl Tasks { ); self.runner.release(&cell.view.borrow().id); } - AgentResponse::ok(cell.view.borrow().clone()) + AgentResponse::ok(cell.current_view()) } /// Runs the step a person has just got the task past, and the rest. @@ -141,6 +141,6 @@ impl Tasks { }], ); } - AgentResponse::ok(cell.view.borrow().clone()) + AgentResponse::ok(cell.current_view()) } } diff --git a/crates/tinycomputer-engine/src/task/store.rs b/crates/tinycomputer-engine/src/task/store.rs index 926bc49b4..ef900184b 100644 --- a/crates/tinycomputer-engine/src/task/store.rs +++ b/crates/tinycomputer-engine/src/task/store.rs @@ -7,7 +7,7 @@ use std::sync::{Arc, Mutex}; use tinycomputer_bus::agent::{ AgentResponse, Rescue, StartTaskRequest, TaskBudget, TaskConstraints, TaskId, TaskOutput, - TaskStatus, TaskView, + TaskStatus, TaskUsage, TaskView, }; use tinycomputer_bus::browser::OutputRef; use tinycomputer_bus::{FLOW_GUIDE, Flow, GroundingHint, JevExchange, StepReport}; @@ -19,6 +19,7 @@ use super::errors::too_many; use super::interpret::Resume; use super::publish::{next_calls, publish}; use super::{MAX_TASKS, Tasks}; +use crate::UsageRecorder; use crate::rescue::Rescuer; use crate::shape::Shaper; @@ -33,7 +34,19 @@ pub(super) struct Cell { pub(super) shaper: Option, } +impl Cell { + /// The latest published state with usage accumulated since that update. + pub(super) fn current_view(&self) -> TaskView { + let mut view = self.view.borrow().clone(); + if let Ok(state) = self.state.lock() { + view.usage = state.usage.snapshot(); + } + view + } +} + pub(super) struct State { + pub(super) usage: Arc, pub(super) flow: Flow, /// The task in the caller's words, for Jev's brief; empty when only a /// flow was given. @@ -95,6 +108,7 @@ impl Tasks { ) -> Option> { let number = self.counter.fetch_add(1, Ordering::Relaxed) + 1; let id = TaskId::new(format!("t-{number}")); + let usage = Arc::new(UsageRecorder::default()); let view = TaskView { id, status: TaskStatus::Running, @@ -102,10 +116,12 @@ impl Tasks { step: None, progress: 0.0, next: next_calls(&TaskStatus::Running), + usage: TaskUsage::default(), }; let cell = Arc::new(Cell { view: watch::Sender::new(view), state: Mutex::new(State { + usage, flow: flow.clone(), goal: request.task.clone().unwrap_or_default(), facts, @@ -158,7 +174,7 @@ impl Tasks { }, "No planner is configured: write a flow for this task with the guide and start it again.", ); - AgentResponse::ok(cell.view.borrow().clone()) + AgentResponse::ok(cell.current_view()) } pub(super) fn start_planned( @@ -187,7 +203,7 @@ impl Tasks { if let Ok(mut slot) = cell.worker.lock() { *slot = Some(worker.abort_handle()); } - AgentResponse::ok(cell.view.borrow().clone()) + AgentResponse::ok(cell.current_view()) } pub(super) fn spawn(&self, cell: &Arc, runs: Vec) { diff --git a/crates/tinycomputer-engine/src/task/task_tests/status_tests.rs b/crates/tinycomputer-engine/src/task/task_tests/status_tests.rs index b3f488148..c8d10c65c 100644 --- a/crates/tinycomputer-engine/src/task/task_tests/status_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests/status_tests.rs @@ -89,6 +89,32 @@ async fn a_running_task_can_be_awaited_briefly_and_cancelled() { assert_eq!(settle(&tasks, &view.id).await.status, TaskStatus::Cancelled); } +#[tokio::test] +async fn cancelling_a_task_preserves_its_provider_usage_in_view_and_report() { + let (tasks, _) = controller(Vec::new()); + let view = start(&tasks, json!({"app": "Mail", "steps": ["a"]}), &[]); + let cell = tasks.find(&view.id).unwrap(); + cell.state.lock().unwrap().usage.record_call( + crate::ModelRole::Jev, + Some(40), + Some(12), + Some(7), + Some(300), + ); + + let cancelled = tasks.cancel(&view.id).data.unwrap(); + assert!(matches!(cancelled.status, TaskStatus::Cancelled)); + assert_eq!(cancelled.usage.jev.calls, 1); + assert_eq!(cancelled.usage.jev.input_tokens, Some(40)); + assert_eq!(cancelled.usage.jev.cached_input_tokens, Some(12)); + assert_eq!(cancelled.usage.jev.output_tokens, Some(7)); + assert_eq!(cancelled.usage.jev.cost_usd_nanos, Some(300)); + + let report = tasks.report(&view.id).data.unwrap(); + assert_eq!(report.usage, cancelled.usage); + assert_eq!(report.view.usage, cancelled.usage); +} + #[tokio::test] async fn unknown_tasks_are_named_as_such() { let (tasks, _) = controller(Vec::new()); diff --git a/crates/tinycomputer-engine/src/usage.rs b/crates/tinycomputer-engine/src/usage.rs index b3add1758..f9de846b1 100644 --- a/crates/tinycomputer-engine/src/usage.rs +++ b/crates/tinycomputer-engine/src/usage.rs @@ -35,7 +35,7 @@ impl UsageRecorder { input_tokens: Option, cached_input_tokens: Option, output_tokens: Option, - cost_usd_micros: Option, + cost_usd_nanos: Option, ) { self.record_started(role); self.record_measurements( @@ -43,7 +43,7 @@ impl UsageRecorder { input_tokens, cached_input_tokens, output_tokens, - cost_usd_micros, + cost_usd_nanos, ); } @@ -57,6 +57,16 @@ impl UsageRecorder { role.calls = role.calls.saturating_add(1); } + /// Adds provider attempts beyond the first attempt already counted. + pub fn record_additional_calls(&self, role: ModelRole, calls: u64) { + let mut usage = self + .usage + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let role = role_usage(&mut usage, role); + role.calls = role.calls.saturating_add(calls); + } + /// Adds provider measurements for a request already counted with /// [`UsageRecorder::record_started`]. pub fn record_measurements( @@ -65,7 +75,7 @@ impl UsageRecorder { input_tokens: Option, cached_input_tokens: Option, output_tokens: Option, - cost_usd_micros: Option, + cost_usd_nanos: Option, ) { let mut usage = self .usage @@ -75,12 +85,9 @@ impl UsageRecorder { add_unsigned(&mut role.input_tokens, input_tokens); add_unsigned(&mut role.cached_input_tokens, cached_input_tokens); add_unsigned(&mut role.output_tokens, output_tokens); - if let Some(cost) = cost_usd_micros { - role.cost_usd_micros = Some( - role.cost_usd_micros - .unwrap_or_default() - .saturating_add(cost), - ); + if let Some(cost) = cost_usd_nanos { + role.cost_usd_nanos = + Some(role.cost_usd_nanos.unwrap_or_default().saturating_add(cost)); } } diff --git a/crates/tinycomputer-engine/src/usage_tests.rs b/crates/tinycomputer-engine/src/usage_tests.rs index 07cd48144..0758a4218 100644 --- a/crates/tinycomputer-engine/src/usage_tests.rs +++ b/crates/tinycomputer-engine/src/usage_tests.rs @@ -14,7 +14,7 @@ fn snapshots_only_reported_measurements_and_counts_unknown_calls() { assert_eq!(usage.jev.input_tokens, Some(8)); assert_eq!(usage.jev.cached_input_tokens, None); assert_eq!(usage.jev.output_tokens, Some(3)); - assert_eq!(usage.jev.cost_usd_micros, None); + assert_eq!(usage.jev.cost_usd_nanos, None); assert_eq!(usage.planner.calls, 1); assert_eq!(usage.planner.input_tokens, None); } From 07fdc99433bd6338739377db4f8d77cd5c940aa9 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 03:17:19 +0530 Subject: [PATCH 08/73] chore(tinycomputer): refresh audited dependencies Co-authored-by: Medulla --- Cargo.lock | 85 ++++++++++++++++++++------------------------------ vendor/tinybus | 2 +- 2 files changed, 35 insertions(+), 52 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 96628891a..513ec2ab2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -181,15 +181,6 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" -[[package]] -name = "arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" -dependencies = [ - "derive_arbitrary", -] - [[package]] name = "arboard" version = "3.6.1" @@ -395,7 +386,7 @@ version = "5.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a68fa787550392a9d58f44c21a3022cfb3ea3e2458b7f85d3b399d0ceeccf409" dependencies = [ - "nix", + "nix 0.27.1", "winapi", ] @@ -529,12 +520,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "crossbeam-utils" -version = "0.8.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" - [[package]] name = "crypto-common" version = "0.1.7" @@ -582,17 +567,6 @@ version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" -[[package]] -name = "derive_arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "digest" version = "0.10.7" @@ -1029,7 +1003,7 @@ dependencies = [ "tokio", "tokio-rustls", "tower-service", - "webpki-roots 1.0.9", + "webpki-roots 1.0.10", ] [[package]] @@ -1465,6 +1439,18 @@ dependencies = [ "libc", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "ntapi" version = "0.4.3" @@ -2094,7 +2080,7 @@ dependencies = [ "wasm-bindgen-futures", "wasm-streams", "web-sys", - "webpki-roots 1.0.9", + "webpki-roots 1.0.10", ] [[package]] @@ -2176,9 +2162,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.45" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "log", "once_cell", @@ -2201,9 +2187,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "ring", "rustls-pki-types", @@ -2572,7 +2558,7 @@ dependencies = [ [[package]] name = "tinybus" -version = "0.1.5" +version = "0.1.6" dependencies = [ "async-trait", "flate2", @@ -2588,12 +2574,12 @@ dependencies = [ "toml", "tracing", "ureq", - "zip 2.4.2", + "zip 9.0.5", ] [[package]] name = "tinybus-macros" -version = "0.1.5" +version = "0.1.6" dependencies = [ "proc-macro2", "quote", @@ -2602,7 +2588,7 @@ dependencies = [ [[package]] name = "tinybus-module" -version = "0.1.5" +version = "0.1.6" dependencies = [ "async-trait", "serde", @@ -3108,7 +3094,7 @@ dependencies = [ "rustls-pki-types", "ureq-proto", "utf8-zero", - "webpki-roots 1.0.9", + "webpki-roots 1.0.10", ] [[package]] @@ -3295,14 +3281,14 @@ version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" dependencies = [ - "webpki-roots 1.0.9", + "webpki-roots 1.0.10", ] [[package]] name = "webpki-roots" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" dependencies = [ "rustls-pki-types", ] @@ -3329,7 +3315,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.48.0", ] [[package]] @@ -3877,33 +3863,30 @@ dependencies = [ [[package]] name = "zip" -version = "2.4.2" +version = "8.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" +checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" dependencies = [ - "arbitrary", "crc32fast", - "crossbeam-utils", - "displaydoc", "flate2", "indexmap", "memchr", - "thiserror 2.0.20", + "typed-path", "zopfli", ] [[package]] name = "zip" -version = "8.6.0" +version = "9.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" +checksum = "6e04976da629d3b04204ba8105b396a193af8ad2583b2c79bfb3ab8af580a11e" dependencies = [ "crc32fast", "flate2", "indexmap", "memchr", + "nix 0.31.3", "typed-path", - "zopfli", ] [[package]] diff --git a/vendor/tinybus b/vendor/tinybus index eb5cf7270..aa36051e2 160000 --- a/vendor/tinybus +++ b/vendor/tinybus @@ -1 +1 @@ -Subproject commit eb5cf727071a6eb12f9efa3db8ec59e54039f336 +Subproject commit aa36051e2d384b09a1fb7871758fcf22c2a7e709 From 270da1386a1dd9e4814f89ac5e37e90ff0a02359 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 03:20:41 +0530 Subject: [PATCH 09/73] chore(deps): pin merged TinyInference usage support Co-authored-by: Medulla --- Cargo.lock | 376 +++++++++++++++++++++++++++++++++++++------ vendor/tinyinference | 2 +- 2 files changed, 331 insertions(+), 47 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b7c521d87..0f1c6fca5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -151,7 +151,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812947049edcd670a82cd5c73c3661d2e58468577ba8489de58e1a73c04cbd5d" dependencies = [ "alsa-sys", - "bitflags", + "bitflags 2.13.1", "cfg-if", "libc", ] @@ -224,6 +224,17 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "atomicwrites" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ef1bb8d1b645fe38d51dfc331d720fb5fc2c94b440c76cc79c80ff265ca33e3" +dependencies = [ + "rustix 0.38.44", + "tempfile", + "windows-sys 0.52.0", +] + [[package]] name = "autocfg" version = "1.5.1" @@ -242,6 +253,12 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.13.1" @@ -321,6 +338,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d262e149917187838d5b42777c8253bcb64500067342904e7d429499a6f277e" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -336,6 +355,17 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + [[package]] name = "chacha20" version = "0.10.2" @@ -347,6 +377,19 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20 0.9.1", + "cipher", + "poly1305", + "zeroize", +] + [[package]] name = "chrono" version = "0.4.45" @@ -368,6 +411,16 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ "crypto-common 0.1.7", "inout", + "zeroize", +] + +[[package]] +name = "clack-private-fs" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fcca21d8096fca7f1c3a22c3109e38927c9b587007c9c7a13b327e5a955baba" +dependencies = [ + "windows-sys 0.61.2", ] [[package]] @@ -427,7 +480,7 @@ version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1" dependencies = [ - "bitflags", + "bitflags 2.13.1", "core-foundation", "core-graphics-types", "foreign-types", @@ -440,7 +493,7 @@ version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" dependencies = [ - "bitflags", + "bitflags 2.13.1", "core-foundation", "core-graphics-types", "foreign-types", @@ -453,7 +506,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" dependencies = [ - "bitflags", + "bitflags 2.13.1", "core-foundation", "libc", ] @@ -464,7 +517,7 @@ version = "0.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d5d7dca3ebcf65a035582c9ad4385371a9d9ee6537474d2a278f4e1e475bb58" dependencies = [ - "bitflags", + "bitflags 2.13.1", "libc", "objc2-audio-toolbox", "objc2-core-audio", @@ -642,7 +695,7 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" dependencies = [ - "bitflags", + "bitflags 2.13.1", "objc2 0.6.4", ] @@ -776,6 +829,16 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs4" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e72ed92b67c146290f88e9c89d60ca163ea417a446f61ffd7b72df3e7f1dfd5" +dependencies = [ + "rustix 1.1.4", + "windows-sys 0.61.2", +] + [[package]] name = "futures" version = "0.3.34" @@ -880,7 +943,7 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ - "rustix", + "rustix 1.1.4", "windows-link", ] @@ -897,6 +960,18 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -906,7 +981,7 @@ dependencies = [ "cfg-if", "js-sys", "libc", - "r-efi", + "r-efi 6.0.0", "rand_core 0.10.1", "wasm-bindgen", ] @@ -933,6 +1008,15 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + [[package]] name = "hmac" version = "0.12.1" @@ -1029,7 +1113,7 @@ dependencies = [ "tokio", "tokio-rustls", "tower-service", - "webpki-roots 1.0.9", + "webpki-roots 1.0.10", ] [[package]] @@ -1298,6 +1382,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + [[package]] name = "js-sys" version = "0.3.105" @@ -1324,6 +1418,12 @@ dependencies = [ "libc", ] +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -1431,7 +1531,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" dependencies = [ - "bitflags", + "bitflags 2.13.1", "jni-sys 0.3.1", "log", "ndk-sys", @@ -1460,7 +1560,7 @@ version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2eb04e9c688eff1c89d72b407f168cf79bb9e867a9d3323ed6c01519eb9cc053" dependencies = [ - "bitflags", + "bitflags 2.13.1", "cfg-if", "libc", ] @@ -1553,7 +1653,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" dependencies = [ - "bitflags", + "bitflags 2.13.1", "block2 0.5.1", "libc", "objc2 0.5.2", @@ -1569,7 +1669,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" dependencies = [ - "bitflags", + "bitflags 2.13.1", "objc2 0.6.4", "objc2-core-foundation", "objc2-core-graphics", @@ -1582,7 +1682,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6948501a91121d6399b79abaa33a8aa4ea7857fe019f341b8c23ad6e81b79b08" dependencies = [ - "bitflags", + "bitflags 2.13.1", "libc", "objc2 0.6.4", "objc2-core-audio", @@ -1597,7 +1697,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be" dependencies = [ - "bitflags", + "bitflags 2.13.1", "objc2 0.6.4", "objc2-foundation 0.3.2", ] @@ -1621,7 +1721,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c" dependencies = [ - "bitflags", + "bitflags 2.13.1", "objc2 0.6.4", ] @@ -1631,7 +1731,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" dependencies = [ - "bitflags", + "bitflags 2.13.1", "block2 0.5.1", "objc2 0.5.2", "objc2-foundation 0.2.2", @@ -1643,7 +1743,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ - "bitflags", + "bitflags 2.13.1", "block2 0.6.2", "dispatch2", "libc", @@ -1656,7 +1756,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" dependencies = [ - "bitflags", + "bitflags 2.13.1", "dispatch2", "objc2 0.6.4", "objc2-core-foundation", @@ -1687,7 +1787,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" dependencies = [ - "bitflags", + "bitflags 2.13.1", "block2 0.5.1", "libc", "objc2 0.5.2", @@ -1699,7 +1799,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ - "bitflags", + "bitflags 2.13.1", "block2 0.6.2", "libc", "objc2 0.6.4", @@ -1712,7 +1812,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" dependencies = [ - "bitflags", + "bitflags 2.13.1", "objc2 0.6.4", "objc2-core-foundation", ] @@ -1723,7 +1823,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" dependencies = [ - "bitflags", + "bitflags 2.13.1", "block2 0.5.1", "objc2 0.5.2", "objc2-foundation 0.2.2", @@ -1735,7 +1835,7 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" dependencies = [ - "bitflags", + "bitflags 2.13.1", "block2 0.5.1", "objc2 0.5.2", "objc2-foundation 0.2.2", @@ -1807,13 +1907,24 @@ version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" dependencies = [ - "bitflags", + "bitflags 2.13.1", "crc32fast", "fdeflate", "flate2", "miniz_oxide", ] +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + [[package]] name = "polyval" version = "0.6.2" @@ -1945,6 +2056,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "r-efi" version = "6.0.0" @@ -1958,17 +2075,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ "libc", - "rand_chacha", + "rand_chacha 0.3.1", "rand_core 0.6.4", ] +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + [[package]] name = "rand" version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ - "chacha20", + "chacha20 0.10.2", "getrandom 0.4.3", "rand_core 0.10.1", ] @@ -1983,6 +2110,16 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + [[package]] name = "rand_core" version = "0.6.4" @@ -1992,6 +2129,15 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "rand_core" version = "0.10.1" @@ -2013,7 +2159,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags", + "bitflags 2.13.1", ] [[package]] @@ -2094,7 +2240,7 @@ dependencies = [ "wasm-bindgen-futures", "wasm-streams", "web-sys", - "webpki-roots 1.0.9", + "webpki-roots 1.0.10", ] [[package]] @@ -2161,16 +2307,29 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.1", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.52.0", +] + [[package]] name = "rustix" version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ - "bitflags", + "bitflags 2.13.1", "errno", "libc", - "linux-raw-sys", + "linux-raw-sys 0.12.1", "windows-sys 0.61.2", ] @@ -2201,9 +2360,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "ring", "rustls-pki-types", @@ -2494,9 +2653,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", - "rustix", + "rustix 1.1.4", "windows-sys 0.61.2", ] @@ -2759,7 +2918,7 @@ dependencies = [ [[package]] name = "tinyinference-core" -version = "0.3.0" +version = "0.4.1" dependencies = [ "anyhow", "httpdate", @@ -2769,7 +2928,7 @@ dependencies = [ [[package]] name = "tinyinference-decisions" -version = "0.3.0" +version = "0.4.1" dependencies = [ "async-trait", "httpdate", @@ -2782,10 +2941,10 @@ dependencies = [ [[package]] name = "tinyinference-llm" -version = "0.3.0" +version = "0.4.1" dependencies = [ "async-trait", - "base64 0.22.1", + "base64 0.23.1", "bytes", "futures", "reqwest", @@ -2793,11 +2952,67 @@ dependencies = [ "serde_json", "thiserror 2.0.20", "tinyinference-core", + "tinyinference-providers", "tinytools-agent", "tokio", "tracing", ] +[[package]] +name = "tinyinference-providers" +version = "0.4.1" +dependencies = [ + "base64 0.23.1", + "rand 0.10.3", + "reqwest", + "serde", + "serde_json", + "sha2 0.11.0", + "tinystoragedrivers-secrets", + "tracing", + "url", + "zeroize", +] + +[[package]] +name = "tinystoragedrivers-core" +version = "1.0.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?tag=v1.0.0#141fd9ed0ad5d14a8fb5a1b3e837a719e81ac08d" +dependencies = [ + "async-trait", + "data-encoding", + "serde", + "serde_json", + "sha2 0.10.9", + "thiserror 2.0.20", + "tokio", + "ulid", + "zstd", +] + +[[package]] +name = "tinystoragedrivers-secrets" +version = "1.0.0" +source = "git+https://github.com/tinyhumansai/tinystoragedrivers?tag=v1.0.0#141fd9ed0ad5d14a8fb5a1b3e837a719e81ac08d" +dependencies = [ + "async-trait", + "atomicwrites", + "chacha20poly1305", + "clack-private-fs", + "fs4", + "hkdf", + "rustix 1.1.4", + "serde", + "serde_json", + "sha2 0.10.9", + "tinystoragedrivers-core", + "tokio", + "winapi-util", + "windows-permissions", + "winsafe", + "zeroize", +] + [[package]] name = "tinystr" version = "0.8.4" @@ -2974,7 +3189,7 @@ version = "0.6.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ - "bitflags", + "bitflags 2.13.1", "bytes", "futures-util", "http", @@ -3067,6 +3282,16 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "ulid" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "470dbf6591da1b39d43c14523b2b469c86879a53e8b758c8e090a470fe7b1fbe" +dependencies = [ + "rand 0.9.5", + "web-time", +] + [[package]] name = "unicase" version = "2.9.0" @@ -3109,7 +3334,7 @@ dependencies = [ "rustls-pki-types", "ureq-proto", "utf8-zero", - "webpki-roots 1.0.9", + "webpki-roots 1.0.10", ] [[package]] @@ -3202,6 +3427,15 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + [[package]] name = "wasm-bindgen" version = "0.2.128" @@ -3296,14 +3530,14 @@ version = "0.26.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" dependencies = [ - "webpki-roots 1.0.9", + "webpki-roots 1.0.10", ] [[package]] name = "webpki-roots" -version = "1.0.9" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" dependencies = [ "rustls-pki-types", ] @@ -3511,6 +3745,16 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-permissions" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e2ccdc3c6bf4d4a094e031b63fadd08d8e42abd259940eb8aa5fdc09d4bf9be" +dependencies = [ + "bitflags 1.3.2", + "winapi", +] + [[package]] name = "windows-result" version = "0.1.2" @@ -3723,6 +3967,18 @@ dependencies = [ "memchr", ] +[[package]] +name = "winsafe" +version = "0.0.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ef0ffc427f045c0cc9ebffd6f4f91153dcd2a1547b5c3c29ee3f541e16e95c6" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + [[package]] name = "writeable" version = "0.6.4" @@ -3736,7 +3992,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" dependencies = [ "gethostname", - "rustix", + "rustix 1.1.4", "x11rb-protocol", ] @@ -3753,7 +4009,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" dependencies = [ "libc", - "rustix", + "rustix 1.1.4", ] [[package]] @@ -3931,6 +4187,34 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.2+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" +dependencies = [ + "cc", + "pkg-config", +] + [[package]] name = "zune-core" version = "0.5.3" diff --git a/vendor/tinyinference b/vendor/tinyinference index abf90568a..8f0f80f1c 160000 --- a/vendor/tinyinference +++ b/vendor/tinyinference @@ -1 +1 @@ -Subproject commit abf90568a24b826d49900150b20856ef166df3f8 +Subproject commit 8f0f80f1c7223608895e3e11de46fca8b642a558 From 9f979b4b0d9847afa60ca284c5c20638bc0d3e2e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 03:24:43 +0530 Subject: [PATCH 10/73] fix(tinycomputer-browser): tighten action gate context Co-authored-by: Medulla --- .../tinycomputer-browser/src/action_gate.rs | 77 +++++++++++++++++-- .../src/error/error_tests.rs | 23 ++++++ crates/tinycomputer-browser/src/error/mod.rs | 3 +- .../tinycomputer-browser/src/sessions/mod.rs | 11 +-- .../src/sessions/sessions_tests/page_tests.rs | 54 ++++++++++++- 5 files changed, 155 insertions(+), 13 deletions(-) diff --git a/crates/tinycomputer-browser/src/action_gate.rs b/crates/tinycomputer-browser/src/action_gate.rs index 6c734ea32..c050f7ead 100644 --- a/crates/tinycomputer-browser/src/action_gate.rs +++ b/crates/tinycomputer-browser/src/action_gate.rs @@ -36,7 +36,10 @@ pub struct ActionRequest { /// The resolved semantic target, if the request names one. pub target: Option, /// The page's actual current URL immediately before the request. - pub current_url: String, + /// The actual address the browser reported immediately before the request, + /// or `None` when the page is between documents and has no readable URL. + /// A host that makes page-specific decisions should refuse an unknown URL. + pub current_url: Option, /// The requested destination for a navigation, when applicable. pub destination_url: Option, /// Host-supplied task context. @@ -46,7 +49,7 @@ pub struct ActionRequest { impl ActionRequest { pub(crate) fn typed( action: &Action, - current_url: String, + current_url: Option, destination_url: Option, context: &ActionContext, refs: &[ElementRef], @@ -64,7 +67,7 @@ impl ActionRequest { pub(crate) fn raw( payload: Value, - current_url: String, + current_url: Option, destination_url: Option, context: &ActionContext, refs: &[ElementRef], @@ -72,7 +75,8 @@ impl ActionRequest { let target = payload .get("selector") .and_then(Value::as_str) - .and_then(|selector| resolve_target(selector, refs)); + .and_then(|selector| selector.strip_prefix('@')) + .and_then(|reference| resolve_reference(reference, refs)); Self { payload, target, @@ -155,7 +159,8 @@ fn action_target(action: &Action, refs: &[ElementRef]) -> Option { fn target_from_target(target: &Target, refs: &[ElementRef]) -> Option { match target { - Target::Ref { value } | Target::Selector { value } => resolve_target(value, refs), + Target::Ref { value } => resolve_reference(value, refs), + Target::Selector { .. } => None, Target::Locator { value } if value.by == tinycomputer_bus::browser::LocateBy::Role => { Some(ActionTarget { role: Some(value.value.clone()), @@ -171,7 +176,7 @@ fn target_from_target(target: &Target, refs: &[ElementRef]) -> Option Option { +fn resolve_reference(value: &str, refs: &[ElementRef]) -> Option { let reference = value.strip_prefix('@').unwrap_or(value); refs.iter() .find(|item| item.id == reference) @@ -181,3 +186,63 @@ fn resolve_target(value: &str, refs: &[ElementRef]) -> Option { reference: Some(item.id.clone()), }) } + +#[cfg(test)] +mod tests { + use serde_json::json; + use tinycomputer_bus::browser::{Action, ElementRef, Target}; + + use super::{ActionContext, ActionRequest, action_target, resolve_reference}; + + fn refs() -> Vec { + vec![ElementRef { + id: "e1".to_owned(), + role: "button".to_owned(), + name: "Place order".to_owned(), + }] + } + + #[test] + fn only_explicit_snapshot_refs_resolve_to_snapshot_metadata() { + let refs = refs(); + assert!(resolve_reference("@e1", &refs).is_some()); + assert!(resolve_reference("e1", &refs).is_some()); + assert!( + action_target( + &Action::Click { + target: Target::selector("e1"), + new_tab: false, + }, + &refs, + ) + .is_none() + ); + } + + #[test] + fn raw_css_selectors_do_not_alias_snapshot_refs() { + let refs = refs(); + let css = ActionRequest::raw( + json!({"action": "click", "selector": "e1"}), + Some("https://shop.test/".to_owned()), + None, + &ActionContext::default(), + &refs, + ); + let reference = ActionRequest::raw( + json!({"action": "click", "selector": "@e1"}), + Some("https://shop.test/".to_owned()), + None, + &ActionContext::default(), + &refs, + ); + assert!(css.target.is_none()); + assert_eq!( + reference + .target + .as_ref() + .and_then(|target| target.name.as_deref()), + Some("Place order") + ); + } +} diff --git a/crates/tinycomputer-browser/src/error/error_tests.rs b/crates/tinycomputer-browser/src/error/error_tests.rs index 899581155..2c10c7b70 100644 --- a/crates/tinycomputer-browser/src/error/error_tests.rs +++ b/crates/tinycomputer-browser/src/error/error_tests.rs @@ -62,6 +62,25 @@ fn a_lost_connection_tells_the_host_to_open_a_new_session() { ); } +#[test] +fn a_host_refusal_is_a_non_retryable_policy_denial() { + let error = Error::ActionRefused { + reason: "host did not allow the action".to_owned(), + }; + let envelope = error.envelope(); + + assert_eq!(error.wire_name(), errors::BLOCKED_BY_POLICY); + assert_eq!(envelope.code, "POLICY_DENIED"); + assert_eq!( + envelope.disposition.delivery, + DeliveryDisposition::NotDelivered + ); + assert_eq!( + envelope.message, + "action refused by host: host did not allow the action" + ); +} + #[test] fn stale_ref_tells_the_caller_to_snapshot_again() { let error = Error::StaleRef { @@ -110,6 +129,9 @@ fn every_variant() -> Vec { Error::BlockedByPolicy { url: "https://evil.test/".to_string(), }, + Error::ActionRefused { + reason: "blocked by the trusted host".to_owned(), + }, Error::LeftRefusedPage { url: "https://evil.test/".to_string(), }, @@ -218,6 +240,7 @@ fn only_failures_decided_before_the_page_claim_nothing_was_delivered() { | Error::NoSuchOutput { .. } | Error::StaleRef { .. } | Error::BlockedByPolicy { .. } + | Error::ActionRefused { .. } ) }; for error in every_variant() { diff --git a/crates/tinycomputer-browser/src/error/mod.rs b/crates/tinycomputer-browser/src/error/mod.rs index c0a8385fc..1d4ee7989 100644 --- a/crates/tinycomputer-browser/src/error/mod.rs +++ b/crates/tinycomputer-browser/src/error/mod.rs @@ -182,7 +182,8 @@ impl Error { Self::PageError { .. } => errors::PAGE_ERROR, Self::NoSuchOutput { .. } => errors::NO_SUCH_OUTPUT, Self::LimitExceeded { .. } => errors::LIMIT_EXCEEDED, - Self::ActionRefused { .. } | Self::ModuleFailed { .. } => errors::MODULE_FAILED, + Self::ActionRefused { .. } => errors::BLOCKED_BY_POLICY, + Self::ModuleFailed { .. } => errors::MODULE_FAILED, } } diff --git a/crates/tinycomputer-browser/src/sessions/mod.rs b/crates/tinycomputer-browser/src/sessions/mod.rs index f032ce97a..917340f75 100644 --- a/crates/tinycomputer-browser/src/sessions/mod.rs +++ b/crates/tinycomputer-browser/src/sessions/mod.rs @@ -116,12 +116,13 @@ impl Session { reply::data(&self.engine.execute(command).await) } - /// The best current address for gate context, without making an action - /// fail solely because a page is briefly between documents. - async fn action_url(&mut self) -> String { + /// The current address for gate context, or `None` while the page is + /// briefly between documents. Never substitute a cached, potentially + /// stale address for the location of the page about to be acted on. + async fn action_url(&mut self) -> Option { match self.run(json!({"action": "url"})).await { - Ok(data) => reply::text(&data, "url"), - Err(_) => self.info.url.clone(), + Ok(data) => Some(reply::text(&data, "url")), + Err(_) => None, } } diff --git a/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs b/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs index 3a86e4f0a..0e3e23730 100644 --- a/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs +++ b/crates/tinycomputer-browser/src/sessions/sessions_tests/page_tests.rs @@ -3,6 +3,7 @@ use serde_json::{Value, json}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use tinycomputer_bus::browser::{ Action, EvaluateRequest, LocateBy, Locator, NavigateRequest, ReadFormat, ReadRequest, SessionOptions, SnapshotRequest, Target, @@ -55,6 +56,20 @@ impl ActionGate for RefuseNamedAction { } } +struct RefuseUnknownCurrentUrl; + +impl ActionGate for RefuseUnknownCurrentUrl { + fn check(&self, request: &ActionRequest) -> ActionVerdict { + if request.current_url.is_none() && request.destination_url.is_none() { + ActionVerdict::Refuse { + reason: "current page URL is unavailable".to_owned(), + } + } else { + ActionVerdict::Allow + } + } +} + #[derive(Default)] struct CaptureActionRequest(std::sync::Mutex>); @@ -124,12 +139,49 @@ async fn gate_receives_task_page_destination_and_value_without_debugging_the_val .iter() .find(|request| request.contains("action: Some(\"fill\")")) .unwrap(); - assert!(fill.contains("current_url: \"https://shop.test/checkout\"")); + assert!(fill.contains("current_url: Some(\"https://shop.test/checkout\")")); assert!(fill.contains("role: Some(\"textbox\")")); assert!(fill.contains("name: Some(\"Email\")")); assert!(!fill.contains("private@example.test")); } +#[tokio::test] +async fn an_unknown_current_url_is_not_replaced_with_the_last_known_page() { + let url_unavailable = Arc::new(AtomicBool::new(false)); + let unavailable_for_script = Arc::clone(&url_unavailable); + let fake = Fake::scripted(move |command| { + (command["action"] == "url" && unavailable_for_script.load(Ordering::SeqCst)) + .then(|| failure("page URL is temporarily unavailable")) + }); + let browser = Browser::with_scratch(Arc::new(fake.clone()), super::scratch("gate-unknown-url")) + .with_action_gate(Arc::new(RefuseUnknownCurrentUrl)); + let id = browser + .open_session(SessionOptions::default()) + .await + .unwrap() + .id; + browser + .navigate(&id, NavigateRequest::new("https://shop.test/checkout")) + .await + .unwrap(); + + url_unavailable.store(true, Ordering::SeqCst); + let error = browser + .perform( + &id, + Action::Click { + target: Target::reference("e1"), + new_tab: false, + }, + ) + .await + .unwrap_err(); + assert!( + matches!(error, Error::ActionRefused { ref reason } if reason == "current page URL is unavailable") + ); + assert!(!fake.actions().iter().any(|action| action == "click")); +} + #[tokio::test] async fn refused_order_click_never_reaches_the_page_and_reports_the_reason() { let fake = Fake::new(); From 222e2c526ae736182b1f3912190f06608e4c5e5e Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 03:39:06 +0530 Subject: [PATCH 11/73] test(engine): cover BrowserRunner and usage wire contract Co-authored-by: Medulla --- .../src/agent/types/usage_tests.rs | 26 +- .../src/task/browser_tests.rs | 241 +++++++++++++++++- .../tinybus_module_tests/tasks_tests.rs | 43 +++- 3 files changed, 284 insertions(+), 26 deletions(-) diff --git a/crates/tinycomputer-bus/src/agent/types/usage_tests.rs b/crates/tinycomputer-bus/src/agent/types/usage_tests.rs index 42528aa7f..356c5139f 100644 --- a/crates/tinycomputer-bus/src/agent/types/usage_tests.rs +++ b/crates/tinycomputer-bus/src/agent/types/usage_tests.rs @@ -18,23 +18,23 @@ fn keeps_unreported_usage_unknown_and_accumulates_reported_values() { } #[test] -fn omits_unreported_measurements_from_the_wire() { - assert_eq!( - serde_json::to_value(TaskUsage { - jev: ModelUsage { - calls: 1, - ..ModelUsage::default() - }, - ..TaskUsage::default() - }) - .unwrap(), - json!({"jev": {"calls": 1}}) - ); +fn omits_unreported_measurements_from_the_wire() -> Result<(), serde_json::Error> { + let wire = serde_json::to_value(TaskUsage { + jev: ModelUsage { + calls: 1, + ..ModelUsage::default() + }, + ..TaskUsage::default() + })?; + assert_eq!(wire, json!({"jev": {"calls": 1}})); + + let usage = serde_json::from_value::(json!({"calls": 1}))?; assert_eq!( - serde_json::from_value::(json!({"calls": 1})).unwrap(), + usage, ModelUsage { calls: 1, ..ModelUsage::default() } ); + Ok(()) } diff --git a/crates/tinycomputer-engine/src/task/browser_tests.rs b/crates/tinycomputer-engine/src/task/browser_tests.rs index ec8951a65..20da4e00d 100644 --- a/crates/tinycomputer-engine/src/task/browser_tests.rs +++ b/crates/tinycomputer-engine/src/task/browser_tests.rs @@ -2,8 +2,13 @@ use std::sync::Arc; +use serde_json::{Value, json}; +use tinycomputer_browser::{ + ActionContext, ActionGate, ActionRequest, ActionVerdict, Browser, Engine, Launcher, Reply, + SessionOptions, +}; use tinycomputer_bus::agent::{ - AwaitTaskRequest, StartTaskRequest, SurfaceKind, TaskConstraints, TaskStatus, + AwaitTaskRequest, PaymentMode, StartTaskRequest, SurfaceKind, TaskConstraints, TaskStatus, }; use tinycomputer_bus::{ DesktopResponse, FlowRunResult, FlowStopReason, JevMetrics, RunFlowRequest, StepOutcome, @@ -12,7 +17,7 @@ use tinycomputer_bus::{ use tinycomputer_bus::{Flow, FlowAction, FlowStep}; use super::{FlowFuture, FlowRunner}; -use crate::{Completion, LanguageModel, Rescuer, Tasks, Turn}; +use crate::{BrowserRunner, Completion, JevRuntime, LanguageModel, Rescuer, Tasks, Turn}; struct ScriptedBrowserRunner { failure: Option<&'static str>, @@ -107,10 +112,11 @@ async fn a_browser_action_refusal_keeps_its_reason_in_rescue_and_task_report() return Err("the task start reply had no view".into()); }; let finished = settle(&tasks, &started.id).await?; - assert!(matches!( - &finished.status, - TaskStatus::Failed { reason, .. } if reason == REASON - )); + let TaskStatus::Failed { reason, .. } = &finished.status else { + return Err(format!("unexpected refusal status: {:?}", finished.status).into()); + }; + assert!(reason.contains(REASON), "{reason}"); + let reported_reason = reason.clone(); let report = tasks.report(&started.id); assert!(report.ok, "{:?}", report.error); @@ -118,8 +124,215 @@ async fn a_browser_action_refusal_keeps_its_reason_in_rescue_and_task_report() return Err("the task report reply had no report".into()); }; assert_eq!(report.view.status, finished.status); - assert_eq!(report.steps[0].note, REASON); - assert_eq!(report.rescues[0].failure, REASON); + assert_eq!(report.steps[0].note, reported_reason); + assert_eq!(report.rescues[0].failure, reported_reason); + Ok(()) +} + +#[derive(Debug, Clone, Default)] +struct BrowserScript { + commands: Arc>>, + current_url: Arc>, +} + +impl BrowserScript { + fn commands(&self) -> Vec { + self.commands + .lock() + .map(|commands| commands.clone()) + .unwrap_or_default() + } +} + +struct BrowserScriptEngine(BrowserScript); + +impl Engine for BrowserScriptEngine { + fn execute(&mut self, command: Value) -> Reply<'_> { + if let Ok(mut commands) = self.0.commands.lock() { + commands.push(command.clone()); + } + let action = command["action"].as_str().unwrap_or_default(); + let data = match action { + "navigate" => { + let url = command["url"].as_str().unwrap_or_default().to_owned(); + if let Ok(mut current_url) = self.0.current_url.lock() { + *current_url = url.clone(); + } + json!({"url": url, "title": "Local fixture"}) + } + "url" => json!({ + "url": self + .0 + .current_url + .lock() + .map(|url| url.clone()) + .unwrap_or_default() + }), + "title" => json!({"title": "Local fixture"}), + "snapshot" => json!({ + "snapshot": "- heading \"Browser runner fixture\" [ref=h1]", + "refs": {"h1": {"role": "heading", "name": "Browser runner fixture"}} + }), + "evaluate" => json!({"result": 42}), + "screenshot" => { + let Some(path) = command["path"].as_str() else { + return Box::pin(async { + json!({"id":"", "success":false, "error":"screenshot path missing"}) + }); + }; + if let Err(error) = std::fs::write(path, png_header(1280, 800)) { + return Box::pin(async move { + json!({"id":"", "success":false, "error":error.to_string()}) + }); + } + json!({"path": path}) + } + _ => json!({}), + }; + Box::pin(async move { json!({"id":"", "success":true, "data":data}) }) + } +} + +impl Launcher for BrowserScript { + fn open(&self, _session: &str) -> Box { + Box::new(BrowserScriptEngine(self.clone())) + } +} + +#[derive(Default)] +struct RecordingGate { + contexts: std::sync::Mutex>, + refusal: Option, +} + +impl ActionGate for RecordingGate { + fn check(&self, request: &ActionRequest) -> ActionVerdict { + if let Ok(mut contexts) = self.contexts.lock() { + contexts.push(request.context.clone()); + } + if let Some(reason) = &self.refusal + && request.destination_url.is_some() + { + return ActionVerdict::Refuse { + reason: reason.clone(), + }; + } + ActionVerdict::Allow + } +} + +#[tokio::test] +async fn public_task_manager_runs_the_real_browser_runner_without_a_model() +-> Result<(), Box> { + let script = BrowserScript::default(); + let gate = Arc::new(RecordingGate::default()); + let browser = Arc::new(Browser::new(Arc::new(script.clone())).with_action_gate(gate.clone())); + let runner = Arc::new( + BrowserRunner::new(browser, runtime()?).with_session_options(SessionOptions { + headless: true, + ..SessionOptions::default() + }), + ); + let tasks = Tasks::new(runner); + let started = tasks.start(&request()); + assert!(started.ok, "{:?}", started.error); + let Some(started) = started.data else { + return Err("the task start reply had no view".into()); + }; + + let finished = settle(&tasks, &started.id).await?; + assert!(matches!(finished.status, TaskStatus::Done { .. })); + assert!(script.commands().iter().any(|command| { + command["action"] == "navigate" && command["url"] == "http://127.0.0.1:8765/index.html" + })); + let contexts = gate + .contexts + .lock() + .map_err(|error| std::io::Error::other(error.to_string()))?; + assert!(contexts.iter().any(|context| { + context.task_id.as_deref() == Some(started.id.0.as_str()) && !context.payment_in_play + })); + Ok(()) +} + +#[tokio::test] +async fn browser_action_refusal_from_the_real_runner_survives_rescue_and_report() +-> Result<(), Box> { + const REASON: &str = "the host refused this browser action"; + let script = BrowserScript::default(); + let gate = Arc::new(RecordingGate { + contexts: std::sync::Mutex::default(), + refusal: Some(REASON.to_owned()), + }); + let browser = Arc::new(Browser::new(Arc::new(script.clone())).with_action_gate(gate.clone())); + let mut request = request(); + request.constraints.payment = PaymentMode::FillThenApprove; + request.constraints.origins = vec!["http://127.0.0.1:8765".to_owned()]; + let tasks = Tasks::new(Arc::new(BrowserRunner::new(browser, runtime()?))) + .with_rescuer(Rescuer::new(Arc::new(RefusalRecovery))); + let started = tasks.start(&request); + assert!(started.ok, "{:?}", started.error); + let Some(started) = started.data else { + return Err("the task start reply had no view".into()); + }; + + let finished = settle(&tasks, &started.id).await?; + let TaskStatus::Failed { reason, .. } = &finished.status else { + return Err(format!("unexpected refusal status: {:?}", finished.status).into()); + }; + assert!(reason.contains(REASON), "{reason}"); + let reported_reason = reason.clone(); + assert!(!script.commands().iter().any(|command| { + command["action"] == "navigate" && command["url"] == "http://127.0.0.1:8765/index.html" + })); + let contexts = gate + .contexts + .lock() + .map_err(|error| std::io::Error::other(error.to_string()))?; + assert!(contexts.iter().any(|context| { + context.task_id.as_deref() == Some(started.id.0.as_str()) && context.payment_in_play + })); + let report = tasks.report(&started.id); + assert!(report.ok, "{:?}", report.error); + let Some(report) = report.data else { + return Err("the task report reply had no report".into()); + }; + assert_eq!(report.view.status, finished.status); + assert_eq!(report.steps[0].note, reported_reason); + assert_eq!(report.rescues[0].failure, reported_reason); + Ok(()) +} + +#[tokio::test] +async fn runner_hooks_share_the_task_surface_and_release_its_session() +-> Result<(), Box> { + let script = BrowserScript::default(); + let runner = BrowserRunner::new(Arc::new(Browser::new(Arc::new(script.clone()))), runtime()?); + let task = tinycomputer_bus::agent::TaskId::new("t-hooks"); + let constraints = TaskConstraints::default(); + runner.prepare(&task, &constraints).await; + runner + .open_page(&task, "http://127.0.0.1:8765/index.html") + .await; + let visible = runner.visible_text(&task).await; + assert!( + visible + .iter() + .any(|line| line.contains("Browser runner fixture")) + ); + assert!(runner.capture(&task).await.is_some()); + runner.warm(&task, 1).await; + runner.journal(None, "test", &|| json!({"phase":"host"})); + runner.journal(Some(&task), "test", &|| json!({"phase":"task"})); + runner.release(&task); + assert!(runner.capture(&task).await.is_none()); + runner + .open_page( + &tinycomputer_bus::agent::TaskId::new("t-unknown"), + "https://unused.test", + ) + .await; + runner.release(&tinycomputer_bus::agent::TaskId::new("t-unknown")); Ok(()) } @@ -160,3 +373,15 @@ async fn settle( } } } + +fn runtime() -> Result { + JevRuntime::sage("local-test-key", false) + .map_err(|error| std::io::Error::other(error.message.clone())) +} + +fn png_header(width: u32, height: u32) -> Vec { + let mut png = b"\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR".to_vec(); + png.extend(width.to_be_bytes()); + png.extend(height.to_be_bytes()); + png +} diff --git a/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/tasks_tests.rs b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/tasks_tests.rs index cf7888ef8..19bf206a0 100644 --- a/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/tasks_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/tasks_tests.rs @@ -8,6 +8,21 @@ use tinybus::transport::memory::MemoryBus; use tinybus::{Connection, Interface}; use tinycomputer_bus::names; +#[derive(Default)] +struct CaptureActionContext(std::sync::Mutex>); + +impl tinycomputer_browser::ActionGate for CaptureActionContext { + fn check( + &self, + request: &tinycomputer_browser::ActionRequest, + ) -> tinycomputer_browser::ActionVerdict { + if let Ok(mut contexts) = self.0.lock() { + contexts.push(request.context.clone()); + } + tinycomputer_browser::ActionVerdict::Allow + } +} + #[tokio::test] async fn the_ordinary_task_members_answer_over_a_real_bus() -> tinybus::Result<()> { use tinycomputer_bus::agent::{AgentResponse, Capabilities, TaskView}; @@ -359,16 +374,20 @@ async fn the_runner_loads_the_page_a_browser_task_names_in_its_early_browser() { #[tokio::test(flavor = "multi_thread")] async fn a_task_browser_launches_with_its_own_binary_and_profile_and_checks_pages_itself() { - use tinycomputer_bus::agent::{SurfaceKind, TaskConstraints, TaskId}; + use tinycomputer_bus::agent::{PaymentMode, SurfaceKind, TaskConstraints, TaskId}; use tinycomputer_engine::FlowRunner; let scratch = std::env::temp_dir().join(format!("tinycomputer-runner-launch-{}", std::process::id())); let sent = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); - let browser = std::sync::Arc::new(tinycomputer_browser::Browser::with_scratch( - std::sync::Arc::new(super::browser_tests::ScriptedLauncher(sent.clone())), - scratch.clone(), - )); + let contexts = std::sync::Arc::new(CaptureActionContext::default()); + let browser = std::sync::Arc::new( + tinycomputer_browser::Browser::with_scratch( + std::sync::Arc::new(super::browser_tests::ScriptedLauncher(sent.clone())), + scratch.clone(), + ) + .with_action_gate(contexts.clone()), + ); let runner = crate::tinybus_module::runner::WorkspaceRunner::new(crate::Desktop::new(), None, browser); let task = TaskId::new("t-1"); @@ -378,6 +397,7 @@ async fn a_task_browser_launches_with_its_own_binary_and_profile_and_checks_page &TaskConstraints { surfaces: vec![SurfaceKind::Browser], origins: vec!["https://.example.com".to_owned()], + payment: PaymentMode::FillThenApprove, browser_executable: Some("/opt/chrome/chrome".to_owned()), browser_profile: Some("/Users/asha/.openhuman/chrome".to_owned()), ..TaskConstraints::default() @@ -407,6 +427,19 @@ async fn a_task_browser_launches_with_its_own_binary_and_profile_and_checks_page [json!("https://www.example.com/")], "a page outside the origins is refused before the browser is asked" ); + let supplied_context = contexts + .0 + .lock() + .map(|contexts| { + contexts.iter().any(|context| { + context.task_id.as_deref() == Some(task.0.as_str()) && context.payment_in_play + }) + }) + .unwrap_or(false); + assert!( + supplied_context, + "task id and payment mode reach the browser gate" + ); runner.release(&task); let _ = std::fs::remove_dir_all(&scratch); } From 38f63f14a0745f294b5eb3a3569f7bc4eae415dd Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 03:39:49 +0530 Subject: [PATCH 12/73] feat(engine): add SecretHost handle API Co-authored-by: Medulla --- Cargo.lock | 2 +- .../tinycomputer-browser/src/sessions/page.rs | 22 +++ .../src/surface/operations.rs | 10 ++ crates/tinycomputer-bus/src/agent/mod.rs | 7 +- .../tinycomputer-bus/src/agent/types/mod.rs | 6 +- .../src/agent/types/request.rs | 18 +++ .../src/flow/types/request.rs | 10 ++ crates/tinycomputer-core/src/error/mod.rs | 6 + .../src/facts/facts_tests.rs | 31 +++- crates/tinycomputer-core/src/facts/mod.rs | 59 +++++++- crates/tinycomputer-core/src/lib.rs | 2 +- crates/tinycomputer-core/src/surface/mod.rs | 14 ++ .../src/agentic/flow/brief.rs | 2 +- .../src/agentic/flow/decide.rs | 4 +- .../src/agentic/flow/enter/fill.rs | 13 ++ .../src/agentic/flow/look.rs | 6 +- .../src/agentic/flow/mod.rs | 18 ++- .../src/agentic/flow/run.rs | 14 +- .../src/agentic/flow/secret.rs | 136 ++++++++++++++++++ crates/tinycomputer-engine/src/agentic/mod.rs | 1 + crates/tinycomputer-engine/src/lib.rs | 4 +- .../tinycomputer-engine/src/task/browser.rs | 36 ++++- crates/tinycomputer-engine/src/task/budget.rs | 18 +++ .../src/task/controller.rs | 17 ++- crates/tinycomputer-engine/src/task/mod.rs | 2 + .../src/task/secret_host.rs | 33 +++++ 26 files changed, 464 insertions(+), 27 deletions(-) create mode 100644 crates/tinycomputer-engine/src/agentic/flow/secret.rs create mode 100644 crates/tinycomputer-engine/src/task/secret_host.rs diff --git a/Cargo.lock b/Cargo.lock index 305857c60..3c56d3429 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1545,7 +1545,7 @@ version = "0.31.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" dependencies = [ - "bitflags", + "bitflags 2.13.1", "cfg-if", "cfg_aliases", "libc", diff --git a/crates/tinycomputer-browser/src/sessions/page.rs b/crates/tinycomputer-browser/src/sessions/page.rs index 14eece274..5f72df51c 100644 --- a/crates/tinycomputer-browser/src/sessions/page.rs +++ b/crates/tinycomputer-browser/src/sessions/page.rs @@ -217,6 +217,28 @@ impl Browser { session.outcome(value, matched).await } + /// Checks the configured action gate for a host-owned secret fill without + /// sending any text to the page. + pub async fn authorize_secret_type(&self, id: &SessionId, reference: &str) -> Result<()> { + let session = self.session(id)?; + let mut session = session.lock().await; + session.check_if_readable(false).await?; + let action = Action::Fill { + target: Target::Ref { + value: reference.to_owned(), + }, + value: "[host secret]".to_owned(), + }; + let current_url = session.action_url().await; + self.check_action(&ActionRequest::typed( + &action, + current_url, + None, + &session.action_context, + &session.refs, + )) + } + /// Extracts the active page as text, markdown, or HTML. /// /// # Errors diff --git a/crates/tinycomputer-browser/src/surface/operations.rs b/crates/tinycomputer-browser/src/surface/operations.rs index 60f3d56ef..5bea33729 100644 --- a/crates/tinycomputer-browser/src/surface/operations.rs +++ b/crates/tinycomputer-browser/src/surface/operations.rs @@ -173,6 +173,16 @@ impl Surface for BrowserSurface { } } + fn authorize_secret_type(&self, target: &Candidate) -> Result<(), String> { + let id = self.ensure_session().map_err(|error| error.to_string())?; + self.block(self.browser.authorize_secret_type(&id, &target.ref_id)) + .map_err(|error| error.to_string()) + } + + fn current_url(&self) -> Option { + self.page_url() + } + fn read_value(&self, target: &Candidate) -> Option { if target.ref_id.is_empty() { return None; diff --git a/crates/tinycomputer-bus/src/agent/mod.rs b/crates/tinycomputer-bus/src/agent/mod.rs index 69b8dcf99..30329d65e 100644 --- a/crates/tinycomputer-bus/src/agent/mod.rs +++ b/crates/tinycomputer-bus/src/agent/mod.rs @@ -53,9 +53,10 @@ mod types; pub use types::{ AgentError, AgentResponse, AwaitTaskRequest, Capabilities, ContinueTaskRequest, Example, InputField, InputKind, LanguageModelConfiguration, LanguageModelProvider, MemberDoc, - ModelUsage, PaymentMode, PlanTaskRequest, Rescue, RescueOutcome, StartTaskRequest, StepView, - SurfaceAvailability, SurfaceKind, TaskBudget, TaskConstraints, TaskId, TaskOutput, TaskPlan, - TaskRef, TaskReport, TaskReportRequest, TaskStatus, TaskUsage, TaskView, + ModelUsage, PaymentMode, PlanTaskRequest, Rescue, RescueOutcome, SecretHandle, + StartTaskRequest, StepView, SurfaceAvailability, SurfaceKind, TaskBudget, TaskConstraints, + TaskId, TaskOutput, TaskPlan, TaskRef, TaskReport, TaskReportRequest, TaskStatus, TaskUsage, + TaskView, }; #[cfg(test)] diff --git a/crates/tinycomputer-bus/src/agent/types/mod.rs b/crates/tinycomputer-bus/src/agent/types/mod.rs index 576713c1f..a3c8f70e3 100644 --- a/crates/tinycomputer-bus/src/agent/types/mod.rs +++ b/crates/tinycomputer-bus/src/agent/types/mod.rs @@ -13,9 +13,9 @@ pub use models::{LanguageModelConfiguration, LanguageModelProvider}; pub use reply::{AgentError, AgentResponse}; pub use report::{Rescue, RescueOutcome, TaskReport}; pub use request::{ - AwaitTaskRequest, ContinueTaskRequest, PaymentMode, PlanTaskRequest, StartTaskRequest, - SurfaceKind, TaskBudget, TaskConstraints, TaskId, TaskOutput, TaskPlan, TaskRef, - TaskReportRequest, + AwaitTaskRequest, ContinueTaskRequest, PaymentMode, PlanTaskRequest, SecretHandle, + StartTaskRequest, SurfaceKind, TaskBudget, TaskConstraints, TaskId, TaskOutput, TaskPlan, + TaskRef, TaskReportRequest, }; pub use status::{InputField, InputKind, StepView, TaskStatus, TaskView}; pub use usage::{ModelUsage, TaskUsage}; diff --git a/crates/tinycomputer-bus/src/agent/types/request.rs b/crates/tinycomputer-bus/src/agent/types/request.rs index 18e0b79a0..88cdda667 100644 --- a/crates/tinycomputer-bus/src/agent/types/request.rs +++ b/crates/tinycomputer-bus/src/agent/types/request.rs @@ -59,6 +59,11 @@ pub struct StartTaskRequest { /// and any value that is a card number — are templates: Jev and the /// planner only ever see `${name}`, and the value is typed locally. pub facts: BTreeMap, + /// Opaque handles for secret facts whose values remain in the host. + /// The map key is the fact name used by the flow; the handle itself must + /// never be expanded into a model-facing string. + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub fact_handles: BTreeMap, /// Names among `facts` to keep secret on top of the ones recognised as /// sensitive. A name here that is not in `facts` is refused, so a typo /// cannot leave a value shared. @@ -86,6 +91,19 @@ pub struct StartTaskRequest { pub site: Option, } +/// Host-side reference to a secret fact. Only its opaque handle and safe +/// display metadata cross the engine boundary. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct SecretHandle { + /// Opaque identifier resolved by the host when the field is typed. + pub handle: String, + /// Safe mask shown in reports and model context. + pub mask: String, + /// Host-defined category, such as `payment_card`. + pub kind: String, +} + /// What a finished task returns, beyond its raw records. /// /// The result is always a JSON object. `schema` is a JSON Schema it must diff --git a/crates/tinycomputer-bus/src/flow/types/request.rs b/crates/tinycomputer-bus/src/flow/types/request.rs index 4856e2573..2e24025ea 100644 --- a/crates/tinycomputer-bus/src/flow/types/request.rs +++ b/crates/tinycomputer-bus/src/flow/types/request.rs @@ -9,6 +9,7 @@ use serde_json::Value; use super::Flow; #[cfg(doc)] use super::{FlowRunResult, StepReport}; +use crate::agent::SecretHandle; /// One Jev decision loop. /// @@ -175,6 +176,13 @@ pub struct RunFlowRequest { /// Every other variable is shared: its value may appear in step text and /// in [`RunFlowRequest::brief`]. pub facts: BTreeSet, + /// Host-only handles for named secret facts, resolved only when a field + /// is typed. + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub fact_handles: BTreeMap, + /// The task making this run, for host-side secret resolution. + #[serde(skip_serializing_if = "Option::is_none")] + pub task_id: Option, /// Whether `stop_before` steps may perform their irreversible action. pub allow_destructive: bool, /// Whether ordinary field values may leave the machine for Jev. @@ -226,6 +234,8 @@ impl Default for RunFlowRequest { flow: Flow::default(), vars: BTreeMap::new(), facts: BTreeSet::new(), + fact_handles: BTreeMap::new(), + task_id: None, allow_destructive: false, include_values: false, max_actions: 60, diff --git a/crates/tinycomputer-core/src/error/mod.rs b/crates/tinycomputer-core/src/error/mod.rs index 99f0de515..5fe2d3129 100644 --- a/crates/tinycomputer-core/src/error/mod.rs +++ b/crates/tinycomputer-core/src/error/mod.rs @@ -13,6 +13,12 @@ pub enum Error { /// The name marked secret. name: String, }, + /// A fact name was supplied both with a value and as a host handle. + #[error("`{name}` has both a value and a host secret handle")] + DuplicateFact { + /// The conflicting fact name. + name: String, + }, } /// The crate's standard result type. diff --git a/crates/tinycomputer-core/src/facts/facts_tests.rs b/crates/tinycomputer-core/src/facts/facts_tests.rs index 2f8bc3543..84863c4c9 100644 --- a/crates/tinycomputer-core/src/facts/facts_tests.rs +++ b/crates/tinycomputer-core/src/facts/facts_tests.rs @@ -3,7 +3,7 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] -use super::{Facts, is_sensitive_name}; +use super::{Facts, SecretFactHandle, is_sensitive_name}; use crate::error::Error; fn traveller() -> Facts { @@ -125,6 +125,35 @@ fn merged_facts_keep_every_secret() { assert!(merged.is_secret("code") && !merged.is_secret("email")); } +#[test] +fn host_handles_are_secret_names_without_values() { + let facts = Facts::with_handles( + [("email", "person@example.test")], + [( + "card number", + SecretFactHandle { + handle: "vault-card-1".to_owned(), + mask: "•••• 4242".to_owned(), + kind: "payment_card".to_owned(), + }, + )], + std::iter::empty::<&str>(), + ) + .unwrap(); + + assert_eq!(facts.get("card number"), None); + assert_eq!(facts.handle("card number").unwrap().handle, "vault-card-1"); + assert!(facts.is_secret("card number")); + assert_eq!( + facts.shared().collect::>(), + [("email", "person@example.test")] + ); + assert_eq!( + facts.mask("use vault-card-1 or 4242"), + "use vault-card-1 or 4242" + ); +} + #[test] fn sensitive_names_match_whole_words_only() { assert!(is_sensitive_name("One-Time Password")); diff --git a/crates/tinycomputer-core/src/facts/mod.rs b/crates/tinycomputer-core/src/facts/mod.rs index 528fa508c..08487147a 100644 --- a/crates/tinycomputer-core/src/facts/mod.rs +++ b/crates/tinycomputer-core/src/facts/mod.rs @@ -65,9 +65,21 @@ const MIN_MASKED_DIGITS: usize = 6; #[derive(Clone, Default, PartialEq, Eq)] pub struct Facts { values: BTreeMap, + handles: BTreeMap, secret: BTreeSet, } +/// A reference to a secret whose value stays with its host. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct SecretFactHandle { + /// Opaque host identifier. + pub handle: String, + /// Safe display mask. + pub mask: String, + /// Host-defined kind of secret. + pub kind: String, +} + impl std::fmt::Debug for Facts { /// Names only: a fact's value never reaches a log. fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -97,7 +109,37 @@ impl Facts { .filter(|(name, value)| is_sensitive_name(name) || is_card_number(value)) .map(|(name, _)| name.clone()) .collect(); - Self { values, secret } + Self { + values, + handles: BTreeMap::new(), + secret, + } + } + + /// Facts from values and host-side secret handles. A name cannot be + /// supplied in both maps, and every name in `secret` must exist in one. + pub fn with_handles, V: Into, S: Into>( + pairs: impl IntoIterator, + handles: impl IntoIterator, + secret: impl IntoIterator, + ) -> Result { + let mut facts = Self::new(pairs); + for (name, handle) in handles { + let name = name.into(); + if facts.values.contains_key(&name) { + return Err(Error::DuplicateFact { name }); + } + facts.secret.insert(name.clone()); + facts.handles.insert(name, handle); + } + for name in secret { + let name = name.into(); + if !facts.values.contains_key(&name) && !facts.handles.contains_key(&name) { + return Err(Error::UnknownSecret { name }); + } + facts.secret.insert(name); + } + Ok(facts) } /// [`Facts::new`], with every name in `secret` kept secret as well. @@ -127,6 +169,7 @@ impl Facts { pub fn merged(&self, other: &Self) -> Self { let mut merged = self.clone(); merged.values.extend(other.values.clone()); + merged.handles.extend(other.handles.clone()); merged.secret.extend(other.secret.iter().cloned()); merged } @@ -137,10 +180,20 @@ impl Facts { self.values.get(name).map(String::as_str) } + /// The host-side handle for a fact, if it has no engine-visible value. + #[must_use] + pub fn handle(&self, name: &str) -> Option<&SecretFactHandle> { + self.handles.get(name) + } + /// Every fact's name. #[must_use] pub fn names(&self) -> Vec<&str> { - self.values.keys().map(String::as_str).collect() + self.values + .keys() + .chain(self.handles.keys()) + .map(String::as_str) + .collect() } /// Whether the fact called `name` is secret. @@ -169,7 +222,7 @@ impl Facts { wanted .iter() .map(String::as_str) - .filter(|name| !self.values.contains_key(*name)) + .filter(|name| !self.values.contains_key(*name) && !self.handles.contains_key(*name)) .collect() } diff --git a/crates/tinycomputer-core/src/lib.rs b/crates/tinycomputer-core/src/lib.rs index e4b91dea1..f3d484832 100644 --- a/crates/tinycomputer-core/src/lib.rs +++ b/crates/tinycomputer-core/src/lib.rs @@ -50,7 +50,7 @@ pub mod surface; pub use dates::{Date, date_pattern, parse_date, reformat_date}; pub use error::{Error, Result}; -pub use facts::{Facts, is_sensitive_name}; +pub use facts::{Facts, SecretFactHandle, is_sensitive_name}; pub use keymap::{Key, Platform}; pub use records::{ Criterion, Price, Record, closest_to, parse_clock, parse_duration, parse_price, parse_stops, diff --git a/crates/tinycomputer-core/src/surface/mod.rs b/crates/tinycomputer-core/src/surface/mod.rs index 76e4af68b..5c1d44142 100644 --- a/crates/tinycomputer-core/src/surface/mod.rs +++ b/crates/tinycomputer-core/src/surface/mod.rs @@ -51,6 +51,20 @@ pub trait Surface: Clone + Send + 'static { text: Option, ) -> DesktopResponse; + /// Consults the surface's action policy before a host types a secret into + /// `target`. Browser surfaces consult their configured gate with metadata + /// and no secret value. Other surfaces + /// refuse unless they implement an equivalent policy check. + fn authorize_secret_type(&self, _target: &Candidate) -> Result<(), String> { + Err("this surface does not support host-side secret typing".to_owned()) + } + + /// Current page URL when the surface can report one. Hosts must refuse a + /// page-specific secret fill when this is unavailable. + fn current_url(&self) -> Option { + None + } + /// Reads an element's current value, when the platform exposes one. fn read_value(&self, target: &Candidate) -> Option; diff --git a/crates/tinycomputer-engine/src/agentic/flow/brief.rs b/crates/tinycomputer-engine/src/agentic/flow/brief.rs index 8c7d68a55..f00b136b7 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/brief.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/brief.rs @@ -103,7 +103,7 @@ impl FlowRun<'_, B> { /// Notes something the run chose or entered, for the brief's `so_far`. pub(in crate::agentic::flow) fn remember_choice(&mut self, note: &str) { - self.so_far.push(self.secrets.mask(note)); + self.so_far.push(self.redact_text(note)); if self.so_far.len() > MAX_SO_FAR { self.so_far.remove(0); } diff --git a/crates/tinycomputer-engine/src/agentic/flow/decide.rs b/crates/tinycomputer-engine/src/agentic/flow/decide.rs index ac40955d6..c9ffb8f31 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/decide.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/decide.rs @@ -236,17 +236,19 @@ impl FlowRun<'_, B> { /// Masks every secret out of a request, wherever it appears. fn mask(&self, request: &mut EvaluationRequest) { - if self.secrets.secret_names().is_empty() { + if self.secrets.secret_names().is_empty() && self.secret_host.is_none() { return; } mask_value(&mut request.state, &self.secrets); for question in request.questions.values_mut() { let mut value = serde_json::to_value(&*question).unwrap_or_default(); mask_value(&mut value, &self.secrets); + super::secret::redact_value(&mut value, &|text| self.redact_text(text)); if let Ok(masked) = serde_json::from_value(value) { *question = masked; } } + super::secret::redact_value(&mut request.state, &|text| self.redact_text(text)); } } diff --git a/crates/tinycomputer-engine/src/agentic/flow/enter/fill.rs b/crates/tinycomputer-engine/src/agentic/flow/enter/fill.rs index c7d88a2df..542093621 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/enter/fill.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/enter/fill.rs @@ -217,6 +217,19 @@ impl FlowRun<'_, B> { before: &Screen, private: bool, ) -> Result { + let handle_names = crate::agentic::flow::validate::references(&slot.text) + .into_iter() + .filter(|name| self.fact_handles.contains_key(name)) + .collect::>(); + if !handle_names.is_empty() { + if handle_names.len() != 1 || slot.text != format!("${{{}}}", handle_names[0]) { + return Err(Halt::Failed( + "a host secret must occupy the entire field value".to_owned(), + )); + } + self.type_handle(log, &handle_names[0], field).await?; + return Ok(true); + } let app = self.app.clone(); let target = field.clone(); let hints = [field.name.as_deref(), field.description.as_deref()] diff --git a/crates/tinycomputer-engine/src/agentic/flow/look.rs b/crates/tinycomputer-engine/src/agentic/flow/look.rs index 528e2d10d..89a2a3d77 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/look.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/look.rs @@ -35,7 +35,8 @@ impl FlowRun<'_, B> { }) }); match observed { - Ok(screen) => { + Ok(mut screen) => { + self.redact_screen(&mut screen); self.blind_looks = 0; if let Some(note) = self.front.look(&screen, self.location.as_deref()) { self.history.push(note.to_owned()); @@ -95,7 +96,8 @@ impl FlowRun<'_, B> { "candidates": part.as_ref().map_or(0, |part| part.candidates.len()), }) }); - if let Ok(part) = part { + if let Ok(mut part) = part { + self.redact_screen(&mut part); screen.candidates.extend(part.candidates); screen.context.extend(part.context); screen.text_nodes.extend(part.text_nodes); diff --git a/crates/tinycomputer-engine/src/agentic/flow/mod.rs b/crates/tinycomputer-engine/src/agentic/flow/mod.rs index a7f8575c6..22b114328 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/mod.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/mod.rs @@ -62,6 +62,7 @@ mod memory; mod quorum; mod reflect; mod run; +mod secret; mod steps; mod survey; mod validate; @@ -78,6 +79,7 @@ use std::{ }; use serde_json::json; +use tinycomputer_bus::agent::SecretHandle; use tinycomputer_bus::{ Deliberation, DesktopError, DesktopResponse, FLOW_GUIDE, FlowActionRecord, FlowBrief, FlowLoop, FlowStopReason, FlowStrategy, GroundingHint, JevExchange, JevMetrics, JevTarget, @@ -152,6 +154,15 @@ pub(super) async fn run_flow_with( backend: B, runtime: &JevRuntime, request: RunFlowRequest, +) -> DesktopResponse { + run_flow_with_host(backend, runtime, request, None).await +} + +pub(crate) async fn run_flow_with_host( + backend: B, + runtime: &JevRuntime, + request: RunFlowRequest, + secret_host: Option>, ) -> DesktopResponse { let known = request .vars @@ -167,7 +178,7 @@ pub(super) async fn run_flow_with( ); } let flow = request.flow.clone(); - let mut run = FlowRun::new(backend, runtime, &request); + let mut run = FlowRun::new(backend, runtime, &request, secret_host); let stop = match run.start(&flow).await { Ok(()) => FlowStopReason::Completed, Err(Halt::Stop(stop)) => stop, @@ -262,6 +273,11 @@ pub(super) struct FlowRun<'r, B> { votes: u32, /// The secret values, to mask every request with. secrets: Facts, + /// Opaque host handles, never substituted into flow text. + fact_handles: BTreeMap, + /// The host types handles and sanitizes its values from observations. + secret_host: Option>, + task_id: Option, /// Every `stop_before` phrase the flow declares, gathered once up front /// so an ordinary step's destructive gate can recognize a control the /// flow has already named as irreversible, in its own words. diff --git a/crates/tinycomputer-engine/src/agentic/flow/run.rs b/crates/tinycomputer-engine/src/agentic/flow/run.rs index 073b8dc75..8f7db8cf3 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/run.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/run.rs @@ -49,7 +49,12 @@ fn collect_stop_before(steps: &[FlowStep], phrases: &mut Vec) { } impl<'r, B: AgentBackend + Sync> FlowRun<'r, B> { - pub(super) fn new(backend: B, runtime: &'r JevRuntime, request: &RunFlowRequest) -> Self { + pub(super) fn new( + backend: B, + runtime: &'r JevRuntime, + request: &RunFlowRequest, + secret_host: Option>, + ) -> Self { // A flow's own definitions may name the caller's values // (`"first_name": "${first name}"`), so they are expanded once // against them. The caller's values are never rescanned: one that @@ -102,6 +107,9 @@ impl<'r, B: AgentBackend + Sync> FlowRun<'r, B> { page: None, votes: request.votes.clamp(1, vote::MAX_VOTES), secrets, + fact_handles: request.fact_handles.clone(), + secret_host, + task_id: request.task_id.clone(), allow_destructive: request.allow_destructive, include_values: request.include_values, max_actions: request.max_actions.min(MAX_ACTIONS), @@ -204,8 +212,8 @@ impl<'r, B: AgentBackend + Sync> FlowRun<'r, B> { } Err(error @ Halt::Error(_)) => return Err(error), }; - let text = self.secrets.mask(&text); - let ended = Ended::new(ended.outcome, self.secrets.mask(&ended.note)); + let text = self.redact_text(&text); + let ended = Ended::new(ended.outcome, self.redact_text(&ended.note)); self.step.clone_from(&path); self.runtime.journal.record("step", || { json!({ diff --git a/crates/tinycomputer-engine/src/agentic/flow/secret.rs b/crates/tinycomputer-engine/src/agentic/flow/secret.rs new file mode 100644 index 000000000..60ae18685 --- /dev/null +++ b/crates/tinycomputer-engine/src/agentic/flow/secret.rs @@ -0,0 +1,136 @@ +//! Host typing and redaction for opaque secret facts. + +use tinycomputer_core::surface::{Candidate, Screen}; + +use super::{FlowRun, Halt, StepLog, backend::AgentBackend, view::target_payload}; +use crate::SecretTypeRequest; + +impl FlowRun<'_, B> { + pub(super) fn redact_text(&self, text: &str) -> String { + let text = self.secrets.mask(text); + match (&self.secret_host, &self.task_id) { + (Some(host), Some(task_id)) => host.redact(task_id, &text), + _ => text, + } + } + + pub(super) fn redact_screen(&self, screen: &mut Screen) { + screen.app = self.redact_text(&screen.app); + screen.window = screen.window.as_deref().map(|text| self.redact_text(text)); + screen.surface = self.redact_text(&screen.surface); + screen + .context + .iter_mut() + .for_each(|text| *text = self.redact_text(text)); + for candidate in &mut screen.candidates { + self.redact_candidate(candidate); + } + for candidate in &mut screen.text_nodes { + self.redact_candidate(candidate); + } + } + + pub(super) async fn type_handle( + &mut self, + log: &mut StepLog, + name: &str, + field: &Candidate, + ) -> Result<(), Halt> { + if self.actions >= self.max_actions { + return Err(Halt::Stop(tinycomputer_bus::FlowStopReason::ActionBudget)); + } + let Some(handle) = self.fact_handles.get(name) else { + return Err(Halt::Failed(format!( + "secret fact `{name}` has no value or host handle" + ))); + }; + let (Some(host), Some(task_id)) = (&self.secret_host, &self.task_id) else { + return Err(Halt::Failed(format!( + "secret fact `{name}` cannot be typed without a configured host, task id, and known page URL" + ))); + }; + let backend = self.backend.clone(); + let current_url = tokio::task::spawn_blocking(move || backend.current_url()) + .await + .map_err(|_| Halt::Failed("the current page URL could not be read".to_owned()))? + .ok_or_else(|| { + Halt::Failed( + "secret typing is refused because the current page URL is unknown".to_owned(), + ) + })?; + let request = SecretTypeRequest { + handle: handle.handle.clone(), + mask: handle.mask.clone(), + kind: handle.kind.clone(), + field_role: field.role.clone(), + field_name: field.name.clone(), + field_ref: field.ref_id.clone(), + current_url, + task_id: task_id.clone(), + }; + let backend = self.backend.clone(); + let target = field.clone(); + tokio::task::spawn_blocking(move || backend.authorize_secret_type(&target)) + .await + .map_err(|_| Halt::Failed("the page policy check failed".to_owned()))? + .map_err(|reason| Halt::Failed(self.redact_text(&reason)))?; + self.actions = self.actions.saturating_add(1); + self.typed_last = Some(field.clone()); + let host = host.clone(); + let result = tokio::task::spawn_blocking(move || host.type_secret(&request)) + .await + .map_err(|_| Halt::Failed("the secret host task failed".to_owned()))?; + if let Err(reason) = result { + return Err(Halt::Failed(self.redact_text(&reason))); + } + log.actions.push(tinycomputer_bus::FlowActionRecord { + action: "host-type-secret".to_owned(), + target: Some(target_payload(field)), + ok: true, + note: "typed by host".to_owned(), + }); + Ok(()) + } + + fn redact_candidate(&self, candidate: &mut Candidate) { + candidate.ref_id = self.redact_text(&candidate.ref_id); + candidate.role = self.redact_text(&candidate.role); + candidate.name = candidate.name.as_deref().map(|text| self.redact_text(text)); + candidate.description = candidate + .description + .as_deref() + .map(|text| self.redact_text(text)); + candidate.value = candidate.value.take().map(|mut value| { + redact_value(&mut value, &|text| self.redact_text(text)); + value + }); + candidate + .states + .iter_mut() + .for_each(|text| *text = self.redact_text(text)); + candidate + .available_actions + .iter_mut() + .for_each(|text| *text = self.redact_text(text)); + candidate + .path + .iter_mut() + .for_each(|text| *text = self.redact_text(text)); + for child in &mut candidate.children { + self.redact_candidate(child); + } + } +} + +pub(super) fn redact_value(value: &mut serde_json::Value, redact: &impl Fn(&str) -> String) { + match value { + serde_json::Value::String(text) => *text = redact(text), + serde_json::Value::Array(items) => { + items.iter_mut().for_each(|item| redact_value(item, redact)) + } + serde_json::Value::Object(fields) => fields + .values_mut() + .for_each(|item| redact_value(item, redact)), + _ => {} + } +} diff --git a/crates/tinycomputer-engine/src/agentic/mod.rs b/crates/tinycomputer-engine/src/agentic/mod.rs index e7aaad375..a17b54164 100644 --- a/crates/tinycomputer-engine/src/agentic/mod.rs +++ b/crates/tinycomputer-engine/src/agentic/mod.rs @@ -41,6 +41,7 @@ mod verify; #[cfg(all(test, feature = "desktop"))] mod agentic_tests; +pub(crate) use flow::run_flow_with_host; pub(crate) use flow::{check_flow, missing_inputs}; pub use flow::{flow_guide, run_flow, validate_flow}; #[cfg(feature = "desktop")] diff --git a/crates/tinycomputer-engine/src/lib.rs b/crates/tinycomputer-engine/src/lib.rs index ff8ecb761..3c659730f 100644 --- a/crates/tinycomputer-engine/src/lib.rs +++ b/crates/tinycomputer-engine/src/lib.rs @@ -39,6 +39,8 @@ mod task; mod usage; mod workspace; +pub(crate) use agentic::run_flow_with_host; + #[cfg(test)] pub(crate) static MODEL_NETWORK_TEST_MUTEX: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); @@ -62,7 +64,7 @@ pub use rescue::{Briefing, Guidance, MAX_RESCUE_STEPS, MAX_RESCUES, Rescuer, SCR pub use shape::{Harvest, RECORDS_CHARS, Shaper}; pub use task::{ BrowserRunner, CaptureFuture, FlowFuture, FlowRunner, MAX_AWAIT_MS, MAX_TASKS, PrepareFuture, - Tasks, TextFuture, capabilities, + SecretHost, SecretTypeRequest, Tasks, TextFuture, capabilities, }; pub use tinycomputer_bus::DesktopResponse; #[cfg(feature = "desktop")] diff --git a/crates/tinycomputer-engine/src/task/browser.rs b/crates/tinycomputer-engine/src/task/browser.rs index a2cf450f1..f8d501954 100644 --- a/crates/tinycomputer-engine/src/task/browser.rs +++ b/crates/tinycomputer-engine/src/task/browser.rs @@ -10,6 +10,7 @@ use tinycomputer_bus::{DesktopResponse, RunFlowRequest}; use tinycomputer_core::surface::{Depth, Surface}; use super::{CaptureFuture, FlowFuture, FlowRunner, PrepareFuture, TextFuture}; +use crate::SecretHost; use crate::{JevRuntime, UsageRecorder}; /// Runs task flows directly on one in-process browser surface per task. @@ -23,6 +24,7 @@ pub struct BrowserRunner { runtime: JevRuntime, options: SessionOptions, surfaces: Mutex>, + secret_host: Option>, } impl std::fmt::Debug for BrowserRunner { @@ -45,9 +47,18 @@ impl BrowserRunner { runtime, options: SessionOptions::default(), surfaces: Mutex::new(HashMap::new()), + secret_host: None, } } + /// Uses `host` to resolve opaque secret handles and type them at the + /// moment a task fills a field. + #[must_use] + pub fn with_secret_host(mut self, host: Arc) -> Self { + self.secret_host = Some(host); + self + } + /// Uses `options` as the host defaults for sessions this runner opens. #[must_use] pub fn with_session_options(mut self, options: SessionOptions) -> Self { @@ -116,8 +127,10 @@ impl FlowRunner for BrowserRunner { fn visible_text(&self, task: &TaskId) -> TextFuture { let surface = self.surface(task, &TaskConstraints::default()); + let host = self.secret_host.clone(); + let task_id = task.0.clone(); Box::pin(async move { - tokio::task::spawn_blocking(move || { + let text: Vec = tokio::task::spawn_blocking(move || { surface .observe("browser", None, Depth::Full) .map(|screen| { @@ -140,7 +153,14 @@ impl FlowRunner for BrowserRunner { .unwrap_or_default() }) .await - .unwrap_or_default() + .unwrap_or_default(); + match host { + Some(host) => text + .into_iter() + .map(|line| host.redact(&task_id, &line)) + .collect(), + None => text, + } }) } @@ -222,7 +242,14 @@ impl BrowserRunner { ) -> FlowFuture { let runtime = runtime.journaled_as(&format!("task-{task}")); let surface = self.surface(task, constraints); - Box::pin(tinycomputer_engine_flow(surface, runtime, request)) + let mut request = request; + request.task_id = Some(task.0.clone()); + Box::pin(tinycomputer_engine_flow( + surface, + runtime, + request, + self.secret_host.clone(), + )) } } @@ -230,8 +257,9 @@ async fn tinycomputer_engine_flow( surface: BrowserSurface, runtime: JevRuntime, request: RunFlowRequest, + secret_host: Option>, ) -> DesktopResponse { - crate::run_flow(surface, runtime, request).await + crate::run_flow_with_host(surface, &runtime, request, secret_host).await } #[cfg(test)] diff --git a/crates/tinycomputer-engine/src/task/budget.rs b/crates/tinycomputer-engine/src/task/budget.rs index 3a821266f..22a73bf16 100644 --- a/crates/tinycomputer-engine/src/task/budget.rs +++ b/crates/tinycomputer-engine/src/task/budget.rs @@ -51,6 +51,24 @@ pub(super) fn run_request( flow: run.flow.clone(), vars, facts, + fact_handles: state + .facts + .secret_names() + .into_iter() + .filter_map(|name| { + state.facts.handle(name).map(|handle| { + ( + name.to_owned(), + tinycomputer_bus::agent::SecretHandle { + handle: handle.handle.clone(), + mask: handle.mask.clone(), + kind: handle.kind.clone(), + }, + ) + }) + }) + .collect(), + task_id: Some(cell.view.borrow().id.0.clone()), allow_destructive: run.allow_destructive, // Jev must read what the fields hold to check what was typed. // Secret values are masked in everything the runtime sends Jev. diff --git a/crates/tinycomputer-engine/src/task/controller.rs b/crates/tinycomputer-engine/src/task/controller.rs index dded61c71..6bce66245 100644 --- a/crates/tinycomputer-engine/src/task/controller.rs +++ b/crates/tinycomputer-engine/src/task/controller.rs @@ -11,7 +11,7 @@ use tinycomputer_bus::agent::{ PaymentMode, PlanTaskRequest, StartTaskRequest, TaskId, TaskPlan, TaskReport, TaskReportRequest, TaskStatus, TaskView, }; -use tinycomputer_core::Facts; +use tinycomputer_core::{Facts, SecretFactHandle}; use super::errors::{no_planner, no_such_task, poisoned, too_many}; use super::names::{fact_names, is_undefined, known_names}; @@ -148,7 +148,20 @@ impl Tasks { /// When called outside a Tokio runtime: the task runs on a spawned worker. #[must_use] pub fn start(&self, request: &StartTaskRequest) -> AgentResponse { - let facts = match Facts::with_secrets(request.facts.clone(), request.secret_facts.clone()) { + let facts = match Facts::with_handles( + request.facts.clone(), + request.fact_handles.iter().map(|(name, handle)| { + ( + name.clone(), + SecretFactHandle { + handle: handle.handle.clone(), + mask: handle.mask.clone(), + kind: handle.kind.clone(), + }, + ) + }), + request.secret_facts.clone(), + ) { Ok(facts) => facts, Err(error) => { return AgentResponse::err(AgentError::new( diff --git a/crates/tinycomputer-engine/src/task/mod.rs b/crates/tinycomputer-engine/src/task/mod.rs index 0622e1102..271e3c6f6 100644 --- a/crates/tinycomputer-engine/src/task/mod.rs +++ b/crates/tinycomputer-engine/src/task/mod.rs @@ -51,6 +51,7 @@ mod page; mod publish; mod recovery; mod resume; +mod secret_host; mod store; mod timing; @@ -65,6 +66,7 @@ pub use browser::BrowserRunner; pub use controller::Tasks; pub use describe::capabilities; pub(crate) use names::input_kind; +pub use secret_host::{SecretHost, SecretTypeRequest}; /// The future a [`FlowRunner`] returns: the flow runtime's reply envelope. pub type FlowFuture = Pin + Send>>; diff --git a/crates/tinycomputer-engine/src/task/secret_host.rs b/crates/tinycomputer-engine/src/task/secret_host.rs new file mode 100644 index 000000000..119b693d7 --- /dev/null +++ b/crates/tinycomputer-engine/src/task/secret_host.rs @@ -0,0 +1,33 @@ +//! Host-resolved secret facts. Secret material is typed by the embedding +//! host and can be redacted from observations without returning it to engine. + +/// Metadata needed to resolve and type one host-side secret. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SecretTypeRequest { + /// Opaque host identifier. Never pass this to a model or report. + pub handle: String, + /// Safe mask associated with the secret fact. + pub mask: String, + /// Host-defined secret category. + pub kind: String, + /// Accessibility role of the selected field. + pub field_role: String, + /// Accessibility name of the selected field, when present. + pub field_name: Option, + /// Snapshot reference identifying the selected field. + pub field_ref: String, + /// Current page URL. Secret typing is refused when this is unknown. + pub current_url: String, + /// Task whose browser session owns the field. + pub task_id: String, +} + +/// A host that resolves opaque handles and types secrets without returning +/// their values to the engine. +pub trait SecretHost: Send + Sync + 'static { + /// Resolve and type into the requested field. A refusal must type nothing. + fn type_secret(&self, request: &SecretTypeRequest) -> Result<(), String>; + + /// Replace any host-held secret values appearing in outbound text. + fn redact(&self, task_id: &str, text: &str) -> String; +} From 3b0aaf4d725b1d8677a436c71832e07d39c52fe9 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 03:48:37 +0530 Subject: [PATCH 13/73] fix(tests): use is_ok_and for runner gate context Co-authored-by: Medulla --- .../tinybus_module_tests/tasks_tests.rs | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/tasks_tests.rs b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/tasks_tests.rs index 19bf206a0..826990e43 100644 --- a/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/tasks_tests.rs +++ b/crates/tinycomputer/src/tinybus_module/tinybus_module_tests/tasks_tests.rs @@ -427,15 +427,11 @@ async fn a_task_browser_launches_with_its_own_binary_and_profile_and_checks_page [json!("https://www.example.com/")], "a page outside the origins is refused before the browser is asked" ); - let supplied_context = contexts - .0 - .lock() - .map(|contexts| { - contexts.iter().any(|context| { - context.task_id.as_deref() == Some(task.0.as_str()) && context.payment_in_play - }) + let supplied_context = contexts.0.lock().is_ok_and(|contexts| { + contexts.iter().any(|context| { + context.task_id.as_deref() == Some(task.0.as_str()) && context.payment_in_play }) - .unwrap_or(false); + }); assert!( supplied_context, "task id and payment mode reach the browser gate" From 1e68b8815f2c99115e3bc553dfcc5e91c8dc9ed2 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 03:49:31 +0530 Subject: [PATCH 14/73] test(engine): update flow run constructor Co-authored-by: Medulla --- .../src/agentic/flow/flow_tests/quorum_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tinycomputer-engine/src/agentic/flow/flow_tests/quorum_tests.rs b/crates/tinycomputer-engine/src/agentic/flow/flow_tests/quorum_tests.rs index 8485800c6..73bee2290 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/flow_tests/quorum_tests.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/flow_tests/quorum_tests.rs @@ -456,7 +456,7 @@ async fn a_decision_ended_on_a_quorum_widens_past_every_framing_it_asked() { votes: 7, ..RunFlowRequest::default() }; - let mut run = FlowRun::new(app, &runtime, &request); + let mut run = FlowRun::new(app, &runtime, &request, None); let mut log = StepLog::default(); let yes_no = |question: &str| { Question::Noul(tinyinference_decisions::Noul { From 91b4b6be05b9034801ac6d70288bc9d348f4d8bb Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 03:52:53 +0530 Subject: [PATCH 15/73] feat(engine): type host-held secret facts Co-authored-by: Medulla --- .../tinycomputer-browser/src/sessions/page.rs | 48 ++-- .../src/surface/operations.rs | 15 +- .../surface/surface_tests/operations_tests.rs | 84 +++++++ .../tinycomputer-bus/src/agent/agent_tests.rs | 5 +- .../src/agent/types/request.rs | 13 +- .../src/browser/session/session_tests.rs | 2 +- crates/tinycomputer-core/src/error/mod.rs | 6 + .../src/facts/facts_tests.rs | 53 +++++ crates/tinycomputer-core/src/facts/mod.rs | 35 ++- crates/tinycomputer-core/src/surface/mod.rs | 13 +- .../src/agentic/flow/decide.rs | 4 +- .../src/agentic/flow/escalate/belief.rs | 4 +- .../src/agentic/flow/flow_tests.rs | 17 +- .../agentic/flow/flow_tests/secret_tests.rs | 213 ++++++++++++++++++ .../src/agentic/flow/flow_tests/simulator.rs | 8 + .../src/agentic/flow/mod.rs | 1 + .../src/agentic/flow/secret.rs | 61 +++-- .../tinycomputer-engine/src/task/describe.rs | 13 ++ .../src/task/secret_host.rs | 26 ++- 19 files changed, 546 insertions(+), 75 deletions(-) create mode 100644 crates/tinycomputer-engine/src/agentic/flow/flow_tests/secret_tests.rs diff --git a/crates/tinycomputer-browser/src/sessions/page.rs b/crates/tinycomputer-browser/src/sessions/page.rs index 5f72df51c..f4ba2bfb1 100644 --- a/crates/tinycomputer-browser/src/sessions/page.rs +++ b/crates/tinycomputer-browser/src/sessions/page.rs @@ -219,24 +219,42 @@ impl Browser { /// Checks the configured action gate for a host-owned secret fill without /// sending any text to the page. - pub async fn authorize_secret_type(&self, id: &SessionId, reference: &str) -> Result<()> { + /// + /// # Errors + /// + /// Returns the browser/session error or the action gate's refusal. The + /// current URL must be readable before a host secret can be typed. + pub async fn authorize_secret_type( + &self, + id: &SessionId, + role: &str, + name: Option<&str>, + reference: &str, + ) -> Result { let session = self.session(id)?; let mut session = session.lock().await; session.check_if_readable(false).await?; - let action = Action::Fill { - target: Target::Ref { - value: reference.to_owned(), - }, - value: "[host secret]".to_owned(), - }; - let current_url = session.action_url().await; - self.check_action(&ActionRequest::typed( - &action, - current_url, - None, - &session.action_context, - &session.refs, - )) + let current_url = session + .action_url() + .await + .ok_or_else(|| Error::invalid_input("the current page URL is unknown"))?; + let reference = reference.strip_prefix('@').unwrap_or(reference); + self.check_action(&ActionRequest { + payload: serde_json::json!({ + "action": "fill", + "selector": format!("@{reference}"), + "value": "[host secret]", + }), + target: Some(crate::action_gate::ActionTarget { + role: Some(role.to_owned()), + name: name.map(str::to_owned), + reference: Some(reference.to_owned()), + }), + current_url: Some(current_url.clone()), + destination_url: None, + context: session.action_context.clone(), + })?; + Ok(current_url) } /// Extracts the active page as text, markdown, or HTML. diff --git a/crates/tinycomputer-browser/src/surface/operations.rs b/crates/tinycomputer-browser/src/surface/operations.rs index 5bea33729..fa6c346a1 100644 --- a/crates/tinycomputer-browser/src/surface/operations.rs +++ b/crates/tinycomputer-browser/src/surface/operations.rs @@ -173,14 +173,15 @@ impl Surface for BrowserSurface { } } - fn authorize_secret_type(&self, target: &Candidate) -> Result<(), String> { + fn authorize_secret_type(&self, target: &Candidate) -> Result { let id = self.ensure_session().map_err(|error| error.to_string())?; - self.block(self.browser.authorize_secret_type(&id, &target.ref_id)) - .map_err(|error| error.to_string()) - } - - fn current_url(&self) -> Option { - self.page_url() + self.block(self.browser.authorize_secret_type( + &id, + &target.role, + target.name.as_deref(), + &target.ref_id, + )) + .map_err(|error| error.to_string()) } fn read_value(&self, target: &Candidate) -> Option { diff --git a/crates/tinycomputer-browser/src/surface/surface_tests/operations_tests.rs b/crates/tinycomputer-browser/src/surface/surface_tests/operations_tests.rs index 68d8adec5..7c80beb8c 100644 --- a/crates/tinycomputer-browser/src/surface/surface_tests/operations_tests.rs +++ b/crates/tinycomputer-browser/src/surface/surface_tests/operations_tests.rs @@ -6,6 +6,7 @@ use tinycomputer_bus::JevOperation; use tinycomputer_core::Platform; use tinycomputer_core::surface::{Depth, Surface}; +use crate::action_gate::{ActionContext, ActionGate, ActionRequest, ActionVerdict}; use tinycomputer_bus::browser::SessionOptions; use tinycomputer_core::surface::Candidate; @@ -38,6 +39,89 @@ fn keys_are_spelled_the_way_agent_browser_reads_them() { assert_eq!(browser_key(" + ", Platform::MacOs), ""); } +#[test] +fn secret_type_preflight_uses_gate_metadata_without_sending_text_to_the_page() { + #[derive(Default)] + struct RefuseFill(std::sync::Mutex>); + + impl ActionGate for RefuseFill { + fn check(&self, request: &ActionRequest) -> ActionVerdict { + if request + .payload + .get("action") + .and_then(serde_json::Value::as_str) + == Some("fill") + { + let payload = serde_json::json!({"action": "fill", "value": "[host secret]"}); + self.0.lock().unwrap().push(ActionRequest { + payload, + target: request.target.clone(), + current_url: request.current_url.clone(), + destination_url: request.destination_url.clone(), + context: request.context.clone(), + }); + ActionVerdict::Refuse { + reason: "secret fill refused".to_owned(), + } + } else { + ActionVerdict::Allow + } + } + } + + let fake = Fake::scripted(|command| match command["action"].as_str().unwrap() { + "snapshot" => Some(ok(&json!({"snapshot": PAGE}))), + "url" => Some(ok(&json!({"url": "https://shop.test/pay"}))), + _ => None, + }); + let gate = std::sync::Arc::new(RefuseFill::default()); + let runtime = tokio::runtime::Runtime::new().unwrap(); + let browser = crate::Browser::with_scratch( + std::sync::Arc::new(fake.clone()), + std::env::temp_dir().join(format!("tinycomputer-secret-gate-{}", std::process::id())), + ) + .with_action_gate(gate.clone()); + let surface = crate::surface::BrowserSurface::new( + std::sync::Arc::new(browser), + SessionOptions::default(), + runtime.handle().clone(), + ) + .with_action_context(ActionContext { + task_id: Some("task-secret".to_owned()), + payment_in_play: true, + }); + let screen = surface.observe("browser", None, Depth::Full).unwrap(); + let field = screen + .candidates + .iter() + .find(|field| field.name.as_deref() == Some("From")) + .unwrap(); + + assert!( + surface + .authorize_secret_type(field) + .unwrap_err() + .contains("secret fill refused") + ); + let requests = gate.0.lock().unwrap(); + assert_eq!(requests.len(), 1); + let request = &requests[0]; + assert_eq!( + request + .target + .as_ref() + .and_then(|target| target.name.as_deref()), + Some("From") + ); + assert_eq!( + request.current_url.as_deref(), + Some("https://shop.test/pay") + ); + assert_eq!(request.context.task_id.as_deref(), Some("task-secret")); + assert_eq!(request.payload["value"], "[host secret]"); + assert!(!fake.actions().iter().any(|action| action == "fill")); +} + #[test] fn observing_opens_the_session_once_and_reads_the_page() { let Harness { fake, surface, .. } = harness("observe", page_fake()); diff --git a/crates/tinycomputer-bus/src/agent/agent_tests.rs b/crates/tinycomputer-bus/src/agent/agent_tests.rs index 7d7d1a48f..c24ee1970 100644 --- a/crates/tinycomputer-bus/src/agent/agent_tests.rs +++ b/crates/tinycomputer-bus/src/agent/agent_tests.rs @@ -11,7 +11,8 @@ use serde_json::json; use super::{ AgentError, AgentResponse, AwaitTaskRequest, ContinueTaskRequest, InputField, InputKind, - PaymentMode, StartTaskRequest, SurfaceKind, TaskId, TaskReportRequest, TaskStatus, TaskView, + PaymentMode, StartTaskRequest, SurfaceKind, TaskId, TaskReportRequest, TaskStatus, TaskUsage, + TaskView, }; #[test] @@ -223,7 +224,7 @@ fn replies_carry_data_or_an_actionable_error() { step: None, progress: 0.25, next: vec!["AwaitTask".to_owned()], - usage: Default::default(), + usage: TaskUsage::default(), }; let ok = serde_json::to_value(AgentResponse::ok(view)).unwrap(); assert_eq!(ok["ok"], true); diff --git a/crates/tinycomputer-bus/src/agent/types/request.rs b/crates/tinycomputer-bus/src/agent/types/request.rs index 88cdda667..43305f6f3 100644 --- a/crates/tinycomputer-bus/src/agent/types/request.rs +++ b/crates/tinycomputer-bus/src/agent/types/request.rs @@ -93,7 +93,7 @@ pub struct StartTaskRequest { /// Host-side reference to a secret fact. Only its opaque handle and safe /// display metadata cross the engine boundary. -#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(default)] pub struct SecretHandle { /// Opaque identifier resolved by the host when the field is typed. @@ -104,6 +104,17 @@ pub struct SecretHandle { pub kind: String, } +impl std::fmt::Debug for SecretHandle { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("SecretHandle") + .field("handle", &"[opaque]") + .field("mask", &self.mask) + .field("kind", &self.kind) + .finish() + } +} + /// What a finished task returns, beyond its raw records. /// /// The result is always a JSON object. `schema` is a JSON Schema it must diff --git a/crates/tinycomputer-bus/src/browser/session/session_tests.rs b/crates/tinycomputer-bus/src/browser/session/session_tests.rs index 85122f10c..267392f88 100644 --- a/crates/tinycomputer-bus/src/browser/session/session_tests.rs +++ b/crates/tinycomputer-bus/src/browser/session/session_tests.rs @@ -182,7 +182,7 @@ fn a_minimal_metadata_and_screen_fill_their_defaults() { assert_eq!(metadata.platform, "Windows"); assert_eq!(metadata.platform_version, ""); assert!(!metadata.mobile); - assert_eq!(options.screen.expect("screen").device_scale_factor, 1.0); + assert!((options.screen.expect("screen").device_scale_factor - 1.0).abs() < f64::EPSILON); } #[test] diff --git a/crates/tinycomputer-core/src/error/mod.rs b/crates/tinycomputer-core/src/error/mod.rs index 5fe2d3129..20d7cdfe1 100644 --- a/crates/tinycomputer-core/src/error/mod.rs +++ b/crates/tinycomputer-core/src/error/mod.rs @@ -19,6 +19,12 @@ pub enum Error { /// The conflicting fact name. name: String, }, + /// A host-side handle is empty and cannot resolve a secret. + #[error("`{name}` has an empty host secret handle")] + EmptyFactHandle { + /// The fact name. + name: String, + }, } /// The crate's standard result type. diff --git a/crates/tinycomputer-core/src/facts/facts_tests.rs b/crates/tinycomputer-core/src/facts/facts_tests.rs index 84863c4c9..c5eda8e9a 100644 --- a/crates/tinycomputer-core/src/facts/facts_tests.rs +++ b/crates/tinycomputer-core/src/facts/facts_tests.rs @@ -154,6 +154,59 @@ fn host_handles_are_secret_names_without_values() { ); } +#[test] +fn host_handle_conflicts_and_empty_ids_are_refused() { + let handle = SecretFactHandle { + handle: "handle-1".to_owned(), + mask: "••••".to_owned(), + kind: "payment_card".to_owned(), + }; + assert!(matches!( + Facts::with_handles( + [("card number", "4111")], + [("card number", handle.clone())], + std::iter::empty::<&str>(), + ), + Err(crate::Error::DuplicateFact { .. }) + )); + assert!(matches!( + Facts::with_handles( + std::iter::empty::<(&str, &str)>(), + [( + "card number", + SecretFactHandle { + handle: String::new(), + ..handle + } + )], + std::iter::empty::<&str>(), + ), + Err(crate::Error::EmptyFactHandle { .. }) + )); +} + +#[test] +fn merging_caller_input_cannot_replace_a_host_held_value() { + let held = Facts::with_handles( + std::iter::empty::<(&str, &str)>(), + [( + "card number", + SecretFactHandle { + handle: "vault-card-1".to_owned(), + mask: "•••• 1111".to_owned(), + kind: "payment_card".to_owned(), + }, + )], + std::iter::empty::<&str>(), + ) + .unwrap(); + let supplied = Facts::new([("card number", "4111 1111 1111 1111")]); + let merged = held.merged(&supplied); + + assert_eq!(merged.get("card number"), None); + assert_eq!(merged.handle("card number").unwrap().handle, "vault-card-1"); +} + #[test] fn sensitive_names_match_whole_words_only() { assert!(is_sensitive_name("One-Time Password")); diff --git a/crates/tinycomputer-core/src/facts/mod.rs b/crates/tinycomputer-core/src/facts/mod.rs index 08487147a..8ad4e3161 100644 --- a/crates/tinycomputer-core/src/facts/mod.rs +++ b/crates/tinycomputer-core/src/facts/mod.rs @@ -70,7 +70,7 @@ pub struct Facts { } /// A reference to a secret whose value stays with its host. -#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[derive(Clone, Default, PartialEq, Eq)] pub struct SecretFactHandle { /// Opaque host identifier. pub handle: String, @@ -80,10 +80,21 @@ pub struct SecretFactHandle { pub kind: String, } +impl std::fmt::Debug for SecretFactHandle { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("SecretFactHandle") + .field("handle", &"[opaque]") + .field("mask", &self.mask) + .field("kind", &self.kind) + .finish() + } +} + impl std::fmt::Debug for Facts { /// Names only: a fact's value never reaches a log. fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - formatter.debug_set().entries(self.values.keys()).finish() + formatter.debug_set().entries(self.names()).finish() } } @@ -118,6 +129,12 @@ impl Facts { /// Facts from values and host-side secret handles. A name cannot be /// supplied in both maps, and every name in `secret` must exist in one. + /// + /// # Errors + /// + /// Returns [`Error::DuplicateFact`] when one name has both a value and a + /// handle, [`Error::EmptyFactHandle`] for an empty handle, or + /// [`Error::UnknownSecret`] when a requested secret name is missing. pub fn with_handles, V: Into, S: Into>( pairs: impl IntoIterator, handles: impl IntoIterator, @@ -126,6 +143,9 @@ impl Facts { let mut facts = Self::new(pairs); for (name, handle) in handles { let name = name.into(); + if handle.handle.trim().is_empty() { + return Err(Error::EmptyFactHandle { name }); + } if facts.values.contains_key(&name) { return Err(Error::DuplicateFact { name }); } @@ -168,8 +188,15 @@ impl Facts { #[must_use] pub fn merged(&self, other: &Self) -> Self { let mut merged = self.clone(); - merged.values.extend(other.values.clone()); - merged.handles.extend(other.handles.clone()); + for (name, value) in &other.values { + if !merged.handles.contains_key(name) { + merged.values.insert(name.clone(), value.clone()); + } + } + for (name, handle) in &other.handles { + merged.values.remove(name); + merged.handles.insert(name.clone(), handle.clone()); + } merged.secret.extend(other.secret.iter().cloned()); merged } diff --git a/crates/tinycomputer-core/src/surface/mod.rs b/crates/tinycomputer-core/src/surface/mod.rs index 5c1d44142..72fdeef6f 100644 --- a/crates/tinycomputer-core/src/surface/mod.rs +++ b/crates/tinycomputer-core/src/surface/mod.rs @@ -55,16 +55,15 @@ pub trait Surface: Clone + Send + 'static { /// `target`. Browser surfaces consult their configured gate with metadata /// and no secret value. Other surfaces /// refuse unless they implement an equivalent policy check. - fn authorize_secret_type(&self, _target: &Candidate) -> Result<(), String> { + /// + /// # Errors + /// + /// Returns a safe refusal reason when the surface cannot authorize the + /// host-side type or does not know the current page URL. + fn authorize_secret_type(&self, _target: &Candidate) -> Result { Err("this surface does not support host-side secret typing".to_owned()) } - /// Current page URL when the surface can report one. Hosts must refuse a - /// page-specific secret fill when this is unavailable. - fn current_url(&self) -> Option { - None - } - /// Reads an element's current value, when the platform exposes one. fn read_value(&self, target: &Candidate) -> Option; diff --git a/crates/tinycomputer-engine/src/agentic/flow/decide.rs b/crates/tinycomputer-engine/src/agentic/flow/decide.rs index c9ffb8f31..89fcf0d26 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/decide.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/decide.rs @@ -130,11 +130,13 @@ impl FlowRun<'_, B> { }) }); if self.tracing { + let mut answers = serde_json::to_value(&answers).unwrap_or_default(); + super::secret::redact_value(&mut answers, &|text| self.redact_text(text)); self.trace.push(JevExchange { step: self.step.clone(), state: request.state.clone(), questions: serde_json::to_value(&request.questions).unwrap_or_default(), - answers: serde_json::to_value(&answers).unwrap_or_default(), + answers, }); } if let Some((kind, _)) = ask::chosen(&answers, PAGE_KIND) { diff --git a/crates/tinycomputer-engine/src/agentic/flow/escalate/belief.rs b/crates/tinycomputer-engine/src/agentic/flow/escalate/belief.rs index 26e9499b1..7ced1a155 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/escalate/belief.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/escalate/belief.rs @@ -85,11 +85,13 @@ impl FlowRun<'_, B> { }) }); if self.tracing { + let mut answers = serde_json::to_value(vote::tally(&fresh)).unwrap_or_default(); + super::super::secret::redact_value(&mut answers, &|text| self.redact_text(text)); self.trace.push(JevExchange { step: self.step.clone(), state: prepared.state, questions: serde_json::to_value(&prepared.questions).unwrap_or_default(), - answers: serde_json::to_value(vote::tally(&fresh)).unwrap_or_default(), + answers, }); } let ballots = request diff --git a/crates/tinycomputer-engine/src/agentic/flow/flow_tests.rs b/crates/tinycomputer-engine/src/agentic/flow/flow_tests.rs index b50b93d9c..50566e1d0 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/flow_tests.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/flow_tests.rs @@ -34,6 +34,7 @@ mod pick_tests; mod picker_tests; mod quorum_tests; mod reflection_tests; +mod secret_tests; mod split_tests; mod step_kinds_tests; mod suggestion_tests; @@ -82,6 +83,7 @@ use super::{ view::{self, Candidate, Depth, Screen}, vote, wide, }; +use crate::{SecretHost, run_flow_with_host}; fn runtime(client: impl Evaluator + 'static) -> JevRuntime { JevRuntime { @@ -111,6 +113,16 @@ async fn run_with( flow: Value, configure: impl FnOnce(&mut RunFlowRequest), hook: impl Fn(&str, &Question, &Sim) -> Option + Send + Sync + 'static, +) -> Run { + run_with_secret_host(app, flow, configure, None, hook).await +} + +async fn run_with_secret_host( + app: App, + flow: Value, + configure: impl FnOnce(&mut RunFlowRequest), + secret_host: Option>, + hook: impl Fn(&str, &Question, &Sim) -> Option + Send + Sync + 'static, ) -> Run { let oracle = Arc::new(Oracle { app: app.clone(), @@ -142,7 +154,10 @@ async fn run_with( ..RunFlowRequest::default() }; configure(&mut request); - let reply = run_flow_with(app.clone(), &runtime, request).await; + if secret_host.is_some() { + request.task_id = Some("t-secret".to_owned()); + } + let reply = run_flow_with_host(app.clone(), &runtime, request, secret_host).await; assert!(reply.ok, "flow run failed: {:?}", reply.error); let requests = oracle.requests.lock().unwrap().clone(); Run { diff --git a/crates/tinycomputer-engine/src/agentic/flow/flow_tests/secret_tests.rs b/crates/tinycomputer-engine/src/agentic/flow/flow_tests/secret_tests.rs new file mode 100644 index 000000000..cf58e5a9d --- /dev/null +++ b/crates/tinycomputer-engine/src/agentic/flow/flow_tests/secret_tests.rs @@ -0,0 +1,213 @@ +//! Opaque secret facts are typed by the host and redacted from every +//! observation the model and report can see. + +use super::*; +use tinycomputer_bus::agent::SecretHandle; + +const CARD: &str = "4111 1111 1111 1111"; + +#[derive(Clone)] +struct TestSecretHost { + app: App, + refuse: bool, + calls: Arc>>, +} + +impl SecretHost for TestSecretHost { + fn type_secret(&self, request: &crate::SecretTypeRequest) -> Result<(), String> { + self.calls.lock().unwrap().push(request.clone()); + if self.refuse { + return Err("host refused the card field".to_owned()); + } + self.app + .sim() + .fields + .insert("To".to_owned(), CARD.to_owned()); + Ok(()) + } + + fn redact(&self, _task_id: &str, text: &str) -> String { + text.replace(CARD, "•••• 1111") + } +} + +fn card_flow() -> Value { + json!({ + "app": "Mail", + "steps": [ + {"open": "Mail"}, + "start a new email message", + {"enter": {"To": "${card number}"}} + ] + }) +} + +fn with_card_handle(request: &mut RunFlowRequest) { + request.facts.insert("card number".to_owned()); + request.fact_handles.insert( + "card number".to_owned(), + SecretHandle { + handle: "vault-card-1".to_owned(), + mask: "•••• 1111".to_owned(), + kind: "payment_card".to_owned(), + }, + ); +} + +fn host( + app: &App, + refuse: bool, +) -> ( + Arc, + Arc>>, +) { + let calls = Arc::new(Mutex::new(Vec::new())); + ( + Arc::new(TestSecretHost { + app: app.clone(), + refuse, + calls: calls.clone(), + }), + calls, + ) +} + +#[tokio::test] +async fn host_types_card_handle_and_echoes_are_redacted_from_model_and_report() { + let app = App::default(); + let (host, calls) = host(&app, false); + let run = run_with_secret_host( + app, + card_flow(), + with_card_handle, + Some(host), + |id, question, _| (id == "slot_0").then(|| pick(question, "To", 0.99)), + ) + .await; + assert_eq!( + run.result.stop, + tinycomputer_bus::FlowStopReason::Completed, + "{}", + serde_json::to_string(&run.result).unwrap() + ); + + assert_eq!( + run.app.sim().fields.get("To").map(String::as_str), + Some(CARD) + ); + let calls = calls.lock().unwrap(); + assert_eq!(calls.len(), 1); + assert_eq!(calls[0].handle, "vault-card-1"); + assert_eq!(calls[0].field_role, "textfield"); + assert_eq!(calls[0].field_name.as_deref(), Some("To")); + assert_eq!(calls[0].task_id, "t-secret"); + assert_eq!(calls[0].current_url, "https://shop.test/pay"); + assert!(calls[0].actions_remaining > 0); + + let model = serde_json::to_string(&run.requests).unwrap(); + assert!(!model.contains(CARD)); + assert!(model.contains("•••• 1111")); + let trace = serde_json::to_string(&run.result.trace).unwrap(); + let learned = serde_json::to_string(&run.result.learned).unwrap(); + let report = serde_json::to_string(&run.result).unwrap(); + assert!(!trace.contains(CARD)); + assert!(!learned.contains(CARD)); + assert!(!report.contains(CARD)); +} + +#[tokio::test] +async fn host_refusal_preserves_its_reason_and_types_nothing() { + let app = App::default(); + let (host, calls) = host(&app, true); + let run = run_with_secret_host( + app, + card_flow(), + with_card_handle, + Some(host), + |id, question, _| (id == "slot_0").then(|| pick(question, "To", 0.99)), + ) + .await; + + assert!(!run.app.sim().fields.contains_key("To")); + assert_eq!(calls.lock().unwrap().len(), 1); + assert!( + run.result + .steps + .iter() + .any(|step| step.note.contains("host refused the card field")) + ); +} + +#[tokio::test] +async fn opaque_handle_without_a_host_never_types_the_handle_or_mask() { + let run = run_with( + App::default(), + card_flow(), + with_card_handle, + |id, question, _| (id == "slot_0").then(|| pick(question, "To", 0.99)), + ) + .await; + assert!(!run.app.sim().fields.contains_key("To")); + let report = serde_json::to_string(&run.result).unwrap(); + assert!(report.contains("configured host")); + assert!(!report.contains("vault-card-1")); + assert!(!report.contains("•••• 1111")); +} + +#[tokio::test] +async fn secret_type_fails_closed_when_the_action_budget_is_spent() { + let app = App::default(); + let (host, calls) = host(&app, false); + let run = run_with_secret_host( + app, + card_flow(), + |request| { + with_card_handle(request); + request.max_actions = 2; + }, + Some(host), + |id, question, _| (id == "slot_0").then(|| pick(question, "To", 0.99)), + ) + .await; + + assert!(!run.app.sim().fields.contains_key("To")); + assert!(calls.lock().unwrap().is_empty()); + assert!( + run.result + .steps + .iter() + .any(|step| step.note.contains("action budget ran out")) + ); +} + +#[tokio::test] +async fn secret_type_fails_closed_when_the_live_url_is_unavailable() { + let app = App::quirky(Quirk::NoURL); + let (host, calls) = host(&app, false); + let run = run_with_secret_host( + app, + card_flow(), + with_card_handle, + Some(host), + |id, question, _| (id == "slot_0").then(|| pick(question, "To", 0.99)), + ) + .await; + + assert!(!run.app.sim().fields.contains_key("To")); + assert!(calls.lock().unwrap().is_empty()); + assert!( + run.result + .steps + .iter() + .any(|step| step.note.contains("current page URL is unknown")) + ); +} + +#[test] +fn structured_outbound_values_are_redacted_recursively() { + let mut value = json!({"page": [CARD, {"field": CARD}], "count": 1}); + super::super::secret::redact_value(&mut value, &|text| text.replace(CARD, "[masked]")); + assert_eq!(value["page"][0], "[masked]"); + assert_eq!(value["page"][1]["field"], "[masked]"); + assert_eq!(value["count"], 1); +} diff --git a/crates/tinycomputer-engine/src/agentic/flow/flow_tests/simulator.rs b/crates/tinycomputer-engine/src/agentic/flow/flow_tests/simulator.rs index 77228bb4e..c2b833fc1 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/flow_tests/simulator.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/flow_tests/simulator.rs @@ -14,6 +14,8 @@ pub(super) enum Quirk { Frozen, /// Observation fails. FailObserve, + /// The surface cannot report a trustworthy current URL. + NoURL, /// Launching fails. FailLaunch, /// The surface has no addresses, as a desktop application has none. @@ -631,6 +633,12 @@ impl AgentBackend for App { } DesktopResponse::ok("navigate", json!({"url": url, "title": "Flights"})) } + + fn authorize_secret_type(&self, _target: &Candidate) -> Result { + (!self.sim().has(Quirk::NoURL)) + .then(|| "https://shop.test/pay".to_owned()) + .ok_or_else(|| "the current page URL is unknown".to_owned()) + } } pub(super) fn is_city_row(target: Option<&Candidate>) -> bool { diff --git a/crates/tinycomputer-engine/src/agentic/flow/mod.rs b/crates/tinycomputer-engine/src/agentic/flow/mod.rs index 22b114328..96e4635d1 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/mod.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/mod.rs @@ -168,6 +168,7 @@ pub(crate) async fn run_flow_with_host( .vars .keys() .chain(request.collected.keys()) + .chain(request.fact_handles.keys()) .cloned() .collect::>(); let validation = validate::check(&request.flow, &known, &request.facts); diff --git a/crates/tinycomputer-engine/src/agentic/flow/secret.rs b/crates/tinycomputer-engine/src/agentic/flow/secret.rs index 60ae18685..7316ea714 100644 --- a/crates/tinycomputer-engine/src/agentic/flow/secret.rs +++ b/crates/tinycomputer-engine/src/agentic/flow/secret.rs @@ -18,10 +18,9 @@ impl FlowRun<'_, B> { screen.app = self.redact_text(&screen.app); screen.window = screen.window.as_deref().map(|text| self.redact_text(text)); screen.surface = self.redact_text(&screen.surface); - screen - .context - .iter_mut() - .for_each(|text| *text = self.redact_text(text)); + for text in &mut screen.context { + *text = self.redact_text(text); + } for candidate in &mut screen.candidates { self.redact_candidate(candidate); } @@ -50,14 +49,12 @@ impl FlowRun<'_, B> { ))); }; let backend = self.backend.clone(); - let current_url = tokio::task::spawn_blocking(move || backend.current_url()) - .await - .map_err(|_| Halt::Failed("the current page URL could not be read".to_owned()))? - .ok_or_else(|| { - Halt::Failed( - "secret typing is refused because the current page URL is unknown".to_owned(), - ) - })?; + let target = field.clone(); + let current_url = + tokio::task::spawn_blocking(move || backend.authorize_secret_type(&target)) + .await + .map_err(|_| Halt::Failed("the page policy check failed".to_owned()))? + .map_err(|reason| Halt::Failed(self.redact_text(&reason)))?; let request = SecretTypeRequest { handle: handle.handle.clone(), mask: handle.mask.clone(), @@ -67,13 +64,8 @@ impl FlowRun<'_, B> { field_ref: field.ref_id.clone(), current_url, task_id: task_id.clone(), + actions_remaining: self.max_actions.saturating_sub(self.actions), }; - let backend = self.backend.clone(); - let target = field.clone(); - tokio::task::spawn_blocking(move || backend.authorize_secret_type(&target)) - .await - .map_err(|_| Halt::Failed("the page policy check failed".to_owned()))? - .map_err(|reason| Halt::Failed(self.redact_text(&reason)))?; self.actions = self.actions.saturating_add(1); self.typed_last = Some(field.clone()); let host = host.clone(); @@ -104,18 +96,15 @@ impl FlowRun<'_, B> { redact_value(&mut value, &|text| self.redact_text(text)); value }); - candidate - .states - .iter_mut() - .for_each(|text| *text = self.redact_text(text)); - candidate - .available_actions - .iter_mut() - .for_each(|text| *text = self.redact_text(text)); - candidate - .path - .iter_mut() - .for_each(|text| *text = self.redact_text(text)); + for text in &mut candidate.states { + *text = self.redact_text(text); + } + for text in &mut candidate.available_actions { + *text = self.redact_text(text); + } + for text in &mut candidate.path { + *text = self.redact_text(text); + } for child in &mut candidate.children { self.redact_candidate(child); } @@ -126,11 +115,15 @@ pub(super) fn redact_value(value: &mut serde_json::Value, redact: &impl Fn(&str) match value { serde_json::Value::String(text) => *text = redact(text), serde_json::Value::Array(items) => { - items.iter_mut().for_each(|item| redact_value(item, redact)) + for item in items { + redact_value(item, redact); + } + } + serde_json::Value::Object(fields) => { + for item in fields.values_mut() { + redact_value(item, redact); + } } - serde_json::Value::Object(fields) => fields - .values_mut() - .for_each(|item| redact_value(item, redact)), _ => {} } } diff --git a/crates/tinycomputer-engine/src/task/describe.rs b/crates/tinycomputer-engine/src/task/describe.rs index 7a1c8fdbb..b6c32bf64 100644 --- a/crates/tinycomputer-engine/src/task/describe.rs +++ b/crates/tinycomputer-engine/src/task/describe.rs @@ -76,6 +76,19 @@ fn start_task_input() -> Value { "additionalProperties": {"type": "string"}, "description": "values the flow may type, by name; secret ones never reach a model" }, + "fact_handles": { + "type": "object", + "additionalProperties": { + "type": "object", + "required": ["handle", "mask", "kind"], + "properties": { + "handle": {"type": "string"}, + "mask": {"type": "string"}, + "kind": {"type": "string"} + } + }, + "description": "host-owned secret facts by name; the host resolves each opaque handle only when the flow types it" + }, "secret_facts": { "type": "array", "items": {"type": "string"}, diff --git a/crates/tinycomputer-engine/src/task/secret_host.rs b/crates/tinycomputer-engine/src/task/secret_host.rs index 119b693d7..9ad4db12e 100644 --- a/crates/tinycomputer-engine/src/task/secret_host.rs +++ b/crates/tinycomputer-engine/src/task/secret_host.rs @@ -2,7 +2,7 @@ //! host and can be redacted from observations without returning it to engine. /// Metadata needed to resolve and type one host-side secret. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] pub struct SecretTypeRequest { /// Opaque host identifier. Never pass this to a model or report. pub handle: String, @@ -20,12 +20,36 @@ pub struct SecretTypeRequest { pub current_url: String, /// Task whose browser session owns the field. pub task_id: String, + /// Task actions available before this host typing operation is charged. + pub actions_remaining: u32, +} + +impl std::fmt::Debug for SecretTypeRequest { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("SecretTypeRequest") + .field("handle", &"[opaque]") + .field("mask", &self.mask) + .field("kind", &self.kind) + .field("field_role", &self.field_role) + .field("field_name", &self.field_name) + .field("field_ref", &self.field_ref) + .field("current_url", &self.current_url) + .field("task_id", &self.task_id) + .field("actions_remaining", &self.actions_remaining) + .finish() + } } /// A host that resolves opaque handles and types secrets without returning /// their values to the engine. pub trait SecretHost: Send + Sync + 'static { /// Resolve and type into the requested field. A refusal must type nothing. + /// + /// # Errors + /// + /// Returns a safe reason when the handle, task, page, field, site, or + /// host policy refuses the type. fn type_secret(&self, request: &SecretTypeRequest) -> Result<(), String>; /// Replace any host-held secret values appearing in outbound text. From d93e258ae793fa4e92d8089478b99b0bfec35bda Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 04:02:54 +0530 Subject: [PATCH 16/73] feat(engine): add host secret redaction hook Co-authored-by: Medulla --- crates/tinycomputer-engine/src/task/browser.rs | 6 ++++++ crates/tinycomputer-engine/src/task/mod.rs | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/crates/tinycomputer-engine/src/task/browser.rs b/crates/tinycomputer-engine/src/task/browser.rs index f8d501954..25e1bb601 100644 --- a/crates/tinycomputer-engine/src/task/browser.rs +++ b/crates/tinycomputer-engine/src/task/browser.rs @@ -230,6 +230,12 @@ impl FlowRunner for BrowserRunner { surface.close(); } } + + fn redact(&self, task: &TaskId, text: &str) -> String { + self.secret_host + .as_ref() + .map_or_else(|| text.to_owned(), |host| host.redact(&task.0, text)) + } } impl BrowserRunner { diff --git a/crates/tinycomputer-engine/src/task/mod.rs b/crates/tinycomputer-engine/src/task/mod.rs index 271e3c6f6..5a4148c8e 100644 --- a/crates/tinycomputer-engine/src/task/mod.rs +++ b/crates/tinycomputer-engine/src/task/mod.rs @@ -171,6 +171,12 @@ pub trait FlowRunner: Send + Sync + 'static { _fields: &dyn Fn() -> serde_json::Value, ) { } + + /// Replaces host-held secret values in text before a task snapshot is + /// emitted. Runners without host-side secrets may keep the default. + fn redact(&self, _task: &TaskId, text: &str) -> String { + text.to_owned() + } } /// How many tasks the controller holds; finished ones are dropped first. From 41357617c094f38dbda0c32af750e0ef6549c941 Mon Sep 17 00:00:00 2001 From: Steven Enamakel Date: Wed, 21 Oct 2026 04:03:00 +0530 Subject: [PATCH 17/73] fix(engine): include warmups and retries in usage Co-authored-by: Medulla --- Cargo.lock | 2 +- .../tinycomputer-bus/src/agent/agent_tests.rs | 5 +- .../tinycomputer-bus/src/agent/types/usage.rs | 4 +- .../src/agentic/runtime_tests.rs | 60 ++++++--- crates/tinycomputer-engine/src/lib.rs | 4 +- .../tinycomputer-engine/src/planner/hosted.rs | 125 ++++++++++++++---- crates/tinycomputer-engine/src/planner/mod.rs | 95 ++++++++++--- .../src/planner/planner_tests/retry_tests.rs | 47 ++++++- crates/tinycomputer-engine/src/rescue/mod.rs | 24 +--- crates/tinycomputer-engine/src/shape/mod.rs | 18 +-- .../tinycomputer-engine/src/task/browser.rs | 13 ++ .../src/task/controller.rs | 2 +- crates/tinycomputer-engine/src/task/drive.rs | 2 +- crates/tinycomputer-engine/src/task/mod.rs | 11 ++ .../src/task/task_tests/plan_tests.rs | 67 ++++++++++ .../src/task/task_tests/status_tests.rs | 39 ++---- .../tinycomputer/src/tinybus_module/runner.rs | 15 +++ .../specs/desktop-module-contract.md | 11 ++ 18 files changed, 417 insertions(+), 127 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 305857c60..3c56d3429 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1545,7 +1545,7 @@ version = "0.31.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" dependencies = [ - "bitflags", + "bitflags 2.13.1", "cfg-if", "cfg_aliases", "libc", diff --git a/crates/tinycomputer-bus/src/agent/agent_tests.rs b/crates/tinycomputer-bus/src/agent/agent_tests.rs index 7d7d1a48f..c24ee1970 100644 --- a/crates/tinycomputer-bus/src/agent/agent_tests.rs +++ b/crates/tinycomputer-bus/src/agent/agent_tests.rs @@ -11,7 +11,8 @@ use serde_json::json; use super::{ AgentError, AgentResponse, AwaitTaskRequest, ContinueTaskRequest, InputField, InputKind, - PaymentMode, StartTaskRequest, SurfaceKind, TaskId, TaskReportRequest, TaskStatus, TaskView, + PaymentMode, StartTaskRequest, SurfaceKind, TaskId, TaskReportRequest, TaskStatus, TaskUsage, + TaskView, }; #[test] @@ -223,7 +224,7 @@ fn replies_carry_data_or_an_actionable_error() { step: None, progress: 0.25, next: vec!["AwaitTask".to_owned()], - usage: Default::default(), + usage: TaskUsage::default(), }; let ok = serde_json::to_value(AgentResponse::ok(view)).unwrap(); assert_eq!(ok["ok"], true); diff --git a/crates/tinycomputer-bus/src/agent/types/usage.rs b/crates/tinycomputer-bus/src/agent/types/usage.rs index 641aab67c..8588c8dd4 100644 --- a/crates/tinycomputer-bus/src/agent/types/usage.rs +++ b/crates/tinycomputer-bus/src/agent/types/usage.rs @@ -5,8 +5,8 @@ use serde::{Deserialize, Serialize}; /// Model calls and the usage their providers reported for one task role. /// /// Token and cost values stay absent when no provider supplied them. Costs are -/// integer micro-units in the provider's reported currency; this crate does -/// not infer prices from token counts. +/// integer nanodollars, and are included only when a provider reports them; +/// this crate does not infer prices from token counts. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct ModelUsage { /// Model requests made, including calls whose usage was not reported. diff --git a/crates/tinycomputer-engine/src/agentic/runtime_tests.rs b/crates/tinycomputer-engine/src/agentic/runtime_tests.rs index 7d01e6a5b..ec42a56ed 100644 --- a/crates/tinycomputer-engine/src/agentic/runtime_tests.rs +++ b/crates/tinycomputer-engine/src/agentic/runtime_tests.rs @@ -77,13 +77,14 @@ async fn host_planner_rescue_output_and_jev_calls_stay_on_the_supplied_stub() let runtime = JevRuntime::configure_for_host(&jev) .map_err(|error| std::io::Error::other(error.message.clone()))? .with_usage_recorder(Arc::clone(&usage)); + runtime.warm(1).await; runtime.evaluate(None, &jev_request()).await?; let seen = server .join() .map_err(|_| std::io::Error::other("stub server thread panicked"))??; assert_stub_routes(&seen); - assert_eq!(requests.load(std::sync::atomic::Ordering::Relaxed), 4); + assert_eq!(requests.load(std::sync::atomic::Ordering::Relaxed), 7); assert_usage(&usage); Ok(()) } @@ -129,18 +130,20 @@ fn jev_request() -> EvaluationRequest { #[cfg(feature = "planner")] fn assert_stub_routes(requests: &[String]) { - assert_eq!(requests.len(), 4, "all four model calls must hit this stub"); + assert_eq!(requests.len(), 7, "all model calls must hit this stub"); assert_eq!( requests .iter() .filter(|request| request.starts_with("POST /v1/chat/completions ")) .count(), - 3 + 4 ); - assert!( + assert_eq!( requests .iter() - .any(|request| request.starts_with("POST /jev ")) + .filter(|request| request.starts_with("POST /jev ")) + .count(), + 3 ); for model in ["planner-local", "rescue-local", "output-local"] { assert!( @@ -153,18 +156,18 @@ fn assert_stub_routes(requests: &[String]) { #[cfg(feature = "planner")] fn assert_usage(recorder: &UsageRecorder) { let tally = recorder.snapshot(); - for role in [tally.planner, tally.rescue, tally.output] { - assert_eq!(role.calls, 1); + for (role, calls) in [(tally.planner, 2), (tally.rescue, 1), (tally.output, 1)] { + assert_eq!(role.calls, calls); assert_eq!(role.input_tokens, Some(10)); assert_eq!(role.cached_input_tokens, Some(2)); assert_eq!(role.output_tokens, Some(3)); assert_eq!(role.cost_usd_nanos, Some(400)); } - assert_eq!(tally.jev.calls, 1); - assert_eq!(tally.jev.input_tokens, Some(20)); - assert_eq!(tally.jev.cached_input_tokens, Some(7)); - assert_eq!(tally.jev.output_tokens, Some(5)); - assert_eq!(tally.jev.cost_usd_nanos, Some(400)); + assert_eq!(tally.jev.calls, 3); + assert_eq!(tally.jev.input_tokens, Some(60)); + assert_eq!(tally.jev.cached_input_tokens, Some(21)); + assert_eq!(tally.jev.output_tokens, Some(15)); + assert_eq!(tally.jev.cost_usd_nanos, Some(1_200)); } #[cfg(feature = "planner")] @@ -176,7 +179,9 @@ fn stub_server(replies: [&'static str; 3]) -> std::io::Result { let counted = Arc::clone(&calls); let server = std::thread::spawn(move || { let mut requests = Vec::new(); - for _ in 0..4 { + let mut planner_attempts = 0; + let mut chat_replies = 0; + for _ in 0..7 { let (mut stream, _) = listener.accept()?; let raw = read_request(&mut stream)?; counted.fetch_add(1, std::sync::atomic::Ordering::Relaxed); @@ -195,7 +200,22 @@ fn stub_server(replies: [&'static str; 3]) -> std::io::Result { .to_string(); write_response(&mut stream, "application/json", &body)?; } else { - let call = replies[requests.len()]; + if raw.contains("planner-local") && planner_attempts == 0 { + planner_attempts += 1; + write_response_with_status( + &mut stream, + 503, + "application/json", + r#"{"error":"temporary outage"}"#, + )?; + requests.push(raw); + continue; + } + if raw.contains("planner-local") { + planner_attempts += 1; + } + let call = replies[chat_replies]; + chat_replies += 1; let body = format!( "data: {{\"id\":\"stub\",\"choices\":[{{\"index\":0,\"delta\":{{\"role\":\"assistant\",\"content\":{}}},\"finish_reason\":null}}]}}\n\n\ data: {{\"id\":\"stub\",\"choices\":[{{\"index\":0,\"delta\":{{}},\"finish_reason\":\"stop\"}}],\"usage\":{{\"prompt_tokens\":10,\"completion_tokens\":3,\"total_tokens\":13,\"prompt_tokens_details\":{{\"cached_tokens\":2}},\"cost\":0.0000004}}}}\n\n\ @@ -237,9 +257,19 @@ fn read_request(stream: &mut TcpStream) -> std::io::Result { #[cfg(feature = "planner")] fn write_response(stream: &mut TcpStream, content_type: &str, body: &str) -> std::io::Result<()> { + write_response_with_status(stream, 200, content_type, body) +} + +#[cfg(feature = "planner")] +fn write_response_with_status( + stream: &mut TcpStream, + status: u16, + content_type: &str, + body: &str, +) -> std::io::Result<()> { write!( stream, - "HTTP/1.1 200 OK\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", + "HTTP/1.1 {status} Stub\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len() ) } diff --git a/crates/tinycomputer-engine/src/lib.rs b/crates/tinycomputer-engine/src/lib.rs index ff8ecb761..232b827af 100644 --- a/crates/tinycomputer-engine/src/lib.rs +++ b/crates/tinycomputer-engine/src/lib.rs @@ -49,8 +49,8 @@ pub use agentic::{ #[cfg(feature = "desktop")] pub use agentic::{resolve_intent, run_goal}; pub use planner::{ - Completion, LanguageModel, ModelReply, ModelUse, Planner, REPAIRS, ReportedCompletion, - ReportedUsage, Role, Turn, + Completion, LanguageModel, ModelFailure, ModelReply, ModelUse, Planner, REPAIRS, + ReportedCompletion, ReportedUsage, Role, Turn, }; #[cfg(feature = "planner")] pub use planner::{ diff --git a/crates/tinycomputer-engine/src/planner/hosted.rs b/crates/tinycomputer-engine/src/planner/hosted.rs index 54524557f..e2b7c9c86 100644 --- a/crates/tinycomputer-engine/src/planner/hosted.rs +++ b/crates/tinycomputer-engine/src/planner/hosted.rs @@ -15,6 +15,7 @@ use tinyinference_llm::model::{ ReasoningConfig, ReasoningEffort, ResponseFormat, collect_model_stream, }; use tinyinference_llm::providers::openai::OpenAiModel; +use tinyinference_llm::usage::Usage; use tinyinference_llm::{ ChatModel, Error, Message, ModelRequest, ProviderKind, ProviderSpec, classify_provider_error, classify_provider_failure, @@ -25,10 +26,12 @@ use super::config::{ RESCUE_MODEL, }; use super::{ - Completion, LanguageModel, ModelReply, Planner, ReportedCompletion, ReportedUsage, Role, Turn, + Completion, LanguageModel, ModelFailure, ModelReply, Planner, ReportedCompletion, + ReportedUsage, Role, Turn, }; use crate::rescue::Rescuer; use crate::shape::Shaper; +use crate::{ModelRole, UsageRecorder}; /// A [`Planner`] configured by `config`, on its route: `OpenRouter` unless /// `provider` says `tiny_humans`. @@ -202,10 +205,35 @@ struct Hosted { impl LanguageModel for Hosted { fn complete(&self, turns: &[Turn]) -> Completion { let completion = self.complete_reported(turns); - Box::pin(async move { completion.await.map(|reply| reply.text) }) + Box::pin(async move { + completion + .await + .map(|reply| reply.text) + .map_err(|error| error.message) + }) } fn complete_reported(&self, turns: &[Turn]) -> ReportedCompletion { + self.complete_reported_for_task(turns, None, ModelRole::Planner) + } + + fn complete_for_task( + &self, + turns: &[Turn], + usage: Option>, + role: ModelRole, + ) -> ReportedCompletion { + self.complete_reported_for_task(turns, usage, role) + } +} + +impl Hosted { + fn complete_reported_for_task( + &self, + turns: &[Turn], + usage: Option>, + role: ModelRole, + ) -> ReportedCompletion { let model = self.model.clone(); let messages = turns .iter() @@ -229,33 +257,68 @@ impl LanguageModel for Hosted { // for 60 seconds, and a reasoning model's whole reply can take // longer. A route that ignores streaming still answers in one // piece. - with_retries(|| { - let model = model.clone(); - let request = request.clone(); - async move { - let stream = model.stream(&(), request).await?; - let response = collect_model_stream(stream).await?; - let usage = - response - .usage - .map_or_else(ReportedUsage::default, |usage| ReportedUsage { - input_tokens: Some(usage.input_tokens), - cached_input_tokens: Some(usage.cache_read_tokens), - output_tokens: Some(usage.output_tokens), - cost_usd_nanos: usage.charged_amount_nanos, - }); + let usage_recorder = usage; + let recorder = usage_recorder.clone(); + let (result, attempts) = with_retries_observed( + || { + let model = model.clone(); + let request = request.clone(); + async move { + let stream = model.stream(&(), request).await?; + let response = collect_model_stream(stream).await?; + let usage = reported_usage(response.usage.as_ref()); + Ok((Message::Assistant(response.message).text(), usage)) + } + }, + || { + if let Some(recorder) = &recorder { + recorder.record_started(role); + } + }, + ) + .await; + match result { + Ok((text, usage)) => { + if let Some(recorder) = &usage_recorder { + recorder.record_measurements( + role, + usage.input_tokens, + usage.cached_input_tokens, + usage.output_tokens, + usage.cost_usd_nanos, + ); + } Ok(ModelReply { - text: Message::Assistant(response.message).text(), + text, usage, + attempts, }) } - }) - .await - .map_err(|error| error.to_string()) + Err(error) => Err(ModelFailure { + message: error.to_string(), + attempts, + }), + } }) } } +pub(super) fn reported_usage(usage: Option<&Usage>) -> ReportedUsage { + let Some(usage) = usage else { + return ReportedUsage::default(); + }; + ReportedUsage { + input_tokens: reported_count(usage.input_tokens), + cached_input_tokens: reported_count(usage.cache_read_tokens), + output_tokens: reported_count(usage.output_tokens), + cost_usd_nanos: usage.charged_amount_nanos, + } +} + +fn reported_count(value: u64) -> Option { + (value > 0).then_some(value) +} + /// How many times one model call is tried when it fails in passing — a /// gateway's 502, a rate limit, a dropped connection — waiting 1, 2, then 4 /// seconds between tries. Live, one 502 from Tiny Humans' gateway ended a @@ -264,19 +327,33 @@ const MODEL_TRIES: u32 = 4; /// Runs `call` until it answers, fails in a way another try cannot mend, or /// has failed [`MODEL_TRIES`] times. +#[cfg(test)] pub(super) async fn with_retries(mut call: C) -> Result where C: FnMut() -> F, F: Future>, { - let mut tries = 1; + with_retries_observed(&mut call, || {}).await.0 +} + +pub(super) async fn with_retries_observed( + mut call: C, + mut on_attempt: O, +) -> (Result, u32) +where + C: FnMut() -> F, + F: Future>, + O: FnMut(), +{ + let mut tries = 0_u32; loop { + tries = tries.saturating_add(1); + on_attempt(); match call().await { Err(error) if tries < MODEL_TRIES && passing(&error) => { tokio::time::sleep(Duration::from_secs(1 << (tries - 1))).await; - tries += 1; } - outcome => return outcome, + outcome => return (outcome, tries), } } } diff --git a/crates/tinycomputer-engine/src/planner/mod.rs b/crates/tinycomputer-engine/src/planner/mod.rs index dff5572fd..0c0a051e6 100644 --- a/crates/tinycomputer-engine/src/planner/mod.rs +++ b/crates/tinycomputer-engine/src/planner/mod.rs @@ -84,6 +84,17 @@ pub struct ModelReply { pub text: String, /// Usage reported for this request, absent when the provider omitted it. pub usage: ReportedUsage, + /// Provider requests used to obtain this reply, including retries. + pub attempts: u32, +} + +/// A language-model failure with the number of provider requests attempted. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ModelFailure { + /// Human-readable failure details. + pub message: String, + /// Provider requests made before the failure was returned. + pub attempts: u32, } impl ModelUse { @@ -118,7 +129,8 @@ impl Turn { pub type Completion = Pin> + Send>>; /// Future returned by [`LanguageModel::complete_reported`]. -pub type ReportedCompletion = Pin> + Send>>; +pub type ReportedCompletion = + Pin> + Send>>; /// A chat model that answers a conversation with text. pub trait LanguageModel: Send + Sync + 'static { @@ -132,10 +144,59 @@ pub trait LanguageModel: Send + Sync + 'static { fn complete_reported(&self, turns: &[Turn]) -> ReportedCompletion { let completion = self.complete(turns); Box::pin(async move { - completion.await.map(|text| ModelReply { - text, - usage: ReportedUsage::default(), - }) + completion.await.map_or_else( + |message| { + Err(ModelFailure { + message, + attempts: 1, + }) + }, + |text| { + Ok(ModelReply { + text, + usage: ReportedUsage::default(), + attempts: 1, + }) + }, + ) + }) + } + + /// Completes a task-role call while recording attempts and provider data. + fn complete_for_task( + &self, + turns: &[Turn], + usage: Option>, + role: ModelRole, + ) -> ReportedCompletion { + let completion = self.complete_reported(turns); + Box::pin(async move { + if let Some(usage) = &usage { + usage.record_started(role); + } + let result = completion.await; + if let Some(usage) = &usage { + match &result { + Ok(reply) => { + usage.record_additional_calls( + role, + u64::from(reply.attempts.saturating_sub(1)), + ); + usage.record_measurements( + role, + reply.usage.input_tokens, + reply.usage.cached_input_tokens, + reply.usage.output_tokens, + reply.usage.cost_usd_nanos, + ); + } + Err(failure) => usage.record_additional_calls( + role, + u64::from(failure.attempts.saturating_sub(1)), + ), + } + } + result }) } } @@ -289,23 +350,13 @@ impl Planner { let mut last = String::new(); for _ in 0..=REPAIRS { used.calls += 1; - if let Some(usage) = &self.usage { - usage.record_started(ModelRole::Planner); - } - let reply = match self.model.complete_reported(&turns).await { - Ok(reply) => { - if let Some(usage) = &self.usage { - usage.record_measurements( - ModelRole::Planner, - reply.usage.input_tokens, - reply.usage.cached_input_tokens, - reply.usage.output_tokens, - reply.usage.cost_usd_nanos, - ); - } - reply.text - } - Err(error) => return (Err(error), used), + let reply = match self + .model + .complete_for_task(&turns, self.usage.clone(), ModelRole::Planner) + .await + { + Ok(reply) => reply.text, + Err(error) => return (Err(error.message), used), }; turns.push(Turn::new(Role::Assistant, reply.clone())); let problem = match parse(&reply) { diff --git a/crates/tinycomputer-engine/src/planner/planner_tests/retry_tests.rs b/crates/tinycomputer-engine/src/planner/planner_tests/retry_tests.rs index a9cdd7eee..e9aaa7c56 100644 --- a/crates/tinycomputer-engine/src/planner/planner_tests/retry_tests.rs +++ b/crates/tinycomputer-engine/src/planner/planner_tests/retry_tests.rs @@ -6,12 +6,33 @@ use std::cell::Cell; use tinyinference_llm::Error; use tinyinference_llm::model::ProviderError; -use super::super::hosted::{passing, with_retries}; +use super::super::ReportedUsage; +use super::super::hosted::{passing, reported_usage, with_retries, with_retries_observed}; +use tinyinference_llm::usage::Usage; fn bad_gateway() -> Error { Error::Model("tinyhumans returned HTTP 502: error code: 502".to_owned()) } +#[test] +fn absent_provider_counts_stay_unknown_instead_of_becoming_zero() { + assert_eq!(reported_usage(None), ReportedUsage::default()); + assert_eq!( + reported_usage(Some(&Usage { + input_tokens: 10, + output_tokens: 2, + charged_amount_nanos: Some(0), + ..Usage::default() + })), + ReportedUsage { + input_tokens: Some(10), + cached_input_tokens: None, + output_tokens: Some(2), + cost_usd_nanos: Some(0), + } + ); +} + #[tokio::test(start_paused = true)] async fn a_model_call_is_tried_again_after_a_gateway_error() { // Live, one 502 from Tiny Humans' gateway ended a task at its plan. @@ -38,6 +59,30 @@ async fn a_model_call_is_tried_again_after_a_gateway_error() { ); } +#[tokio::test(start_paused = true)] +async fn retry_observer_counts_each_provider_request() { + let tries = Cell::new(0); + let recorded = Cell::new(0); + let (answer, attempts) = with_retries_observed( + || { + tries.set(tries.get() + 1); + let failing = tries.get() < 3; + async move { + if failing { + Err(bad_gateway()) + } else { + Ok("the answer") + } + } + }, + || recorded.set(recorded.get() + 1), + ) + .await; + assert_eq!(answer.unwrap(), "the answer"); + assert_eq!(attempts, 3); + assert_eq!(recorded.get(), 3); +} + #[tokio::test(start_paused = true)] async fn a_model_call_that_keeps_failing_gives_up_after_its_tries() { let tries = Cell::new(0); diff --git a/crates/tinycomputer-engine/src/rescue/mod.rs b/crates/tinycomputer-engine/src/rescue/mod.rs index 83e4ff866..820e273c9 100644 --- a/crates/tinycomputer-engine/src/rescue/mod.rs +++ b/crates/tinycomputer-engine/src/rescue/mod.rs @@ -212,23 +212,13 @@ impl Rescuer { let mut last = String::new(); for _ in 0..=REPAIRS { used.calls += 1; - if let Some(usage) = &self.usage { - usage.record_started(ModelRole::Rescue); - } - let reply = match self.model.complete_reported(&turns).await { - Ok(reply) => { - if let Some(usage) = &self.usage { - usage.record_measurements( - ModelRole::Rescue, - reply.usage.input_tokens, - reply.usage.cached_input_tokens, - reply.usage.output_tokens, - reply.usage.cost_usd_nanos, - ); - } - reply.text - } - Err(error) => return (Err(error), used), + let reply = match self + .model + .complete_for_task(&turns, self.usage.clone(), ModelRole::Rescue) + .await + { + Ok(reply) => reply.text, + Err(error) => return (Err(error.message), used), }; turns.push(Turn::new(Role::Assistant, reply.clone())); let problem = match judge(&reply, briefing) { diff --git a/crates/tinycomputer-engine/src/shape/mod.rs b/crates/tinycomputer-engine/src/shape/mod.rs index b080dc87b..53d0ad279 100644 --- a/crates/tinycomputer-engine/src/shape/mod.rs +++ b/crates/tinycomputer-engine/src/shape/mod.rs @@ -112,19 +112,11 @@ impl Shaper { ]; let mut last = String::new(); for _ in 0..=REPAIRS { - if let Some(usage) = &self.usage { - usage.record_started(ModelRole::Output); - } - let reply = self.model.complete_reported(&turns).await?; - if let Some(usage) = &self.usage { - usage.record_measurements( - ModelRole::Output, - reply.usage.input_tokens, - reply.usage.cached_input_tokens, - reply.usage.output_tokens, - reply.usage.cost_usd_nanos, - ); - } + let reply = self + .model + .complete_for_task(&turns, self.usage.clone(), ModelRole::Output) + .await + .map_err(|error| error.message)?; turns.push(Turn::new(Role::Assistant, reply.text.clone())); let problem = match judge(&reply.text, harvest.output.schema.as_ref()) { Ok(value) => return Ok(value), diff --git a/crates/tinycomputer-engine/src/task/browser.rs b/crates/tinycomputer-engine/src/task/browser.rs index a2cf450f1..363fce71b 100644 --- a/crates/tinycomputer-engine/src/task/browser.rs +++ b/crates/tinycomputer-engine/src/task/browser.rs @@ -189,6 +189,19 @@ impl FlowRunner for BrowserRunner { Box::pin(async move { runtime.warm(votes).await }) } + fn warm_with_usage( + &self, + task: &TaskId, + votes: u32, + usage: Arc, + ) -> PrepareFuture { + let runtime = self + .runtime + .journaled_as(&format!("task-{task}")) + .with_usage_recorder(usage); + Box::pin(async move { runtime.warm(votes).await }) + } + fn journal(&self, task: Option<&TaskId>, event: &str, fields: &dyn Fn() -> serde_json::Value) { if !self.runtime.journaling() { return; diff --git a/crates/tinycomputer-engine/src/task/controller.rs b/crates/tinycomputer-engine/src/task/controller.rs index dded61c71..ec197e8a4 100644 --- a/crates/tinycomputer-engine/src/task/controller.rs +++ b/crates/tinycomputer-engine/src/task/controller.rs @@ -250,7 +250,7 @@ impl Tasks { } }) .await; - AgentResponse::ok(changes.borrow().clone()) + AgentResponse::ok(cell.current_view()) } /// Answers what a paused task asked for, and resumes it. diff --git a/crates/tinycomputer-engine/src/task/drive.rs b/crates/tinycomputer-engine/src/task/drive.rs index 4585aee83..82bbc712a 100644 --- a/crates/tinycomputer-engine/src/task/drive.rs +++ b/crates/tinycomputer-engine/src/task/drive.rs @@ -53,7 +53,7 @@ pub(super) async fn plan_then_drive( // decision need not open them; nothing waits for this. A budget that // caps the task's Jev calls is not spent on calls it does not count. if !capped { - tokio::spawn(runner.warm(&id, votes)); + tokio::spawn(runner.warm_with_usage(&id, votes, Arc::clone(&usage))); } let started = Instant::now(); // Timed on its own: a browser slower to open than the plan is to draft diff --git a/crates/tinycomputer-engine/src/task/mod.rs b/crates/tinycomputer-engine/src/task/mod.rs index 0622e1102..86565573b 100644 --- a/crates/tinycomputer-engine/src/task/mod.rs +++ b/crates/tinycomputer-engine/src/task/mod.rs @@ -157,6 +157,17 @@ pub trait FlowRunner: Send + Sync + 'static { Box::pin(async {}) } + /// Warms Jev while the task is planned, recording those calls in the + /// same task tally. Runners that warm the model override this method. + fn warm_with_usage( + &self, + task: &TaskId, + votes: u32, + _usage: std::sync::Arc, + ) -> PrepareFuture { + self.warm(task, votes) + } + /// Writes an `event` of the time a task spends outside its flows /// (`plan`, `rescue`, `resume`) to the debug journal: the task's own, /// or for `PlanTask`, which plans before any task exists (`task` is diff --git a/crates/tinycomputer-engine/src/task/task_tests/plan_tests.rs b/crates/tinycomputer-engine/src/task/task_tests/plan_tests.rs index 63f39a4a2..59f3f303c 100644 --- a/crates/tinycomputer-engine/src/task/task_tests/plan_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests/plan_tests.rs @@ -2,6 +2,40 @@ use super::*; +struct WarmUsageRunner(Arc