The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(accessibility): gate macOS-specific imports behind cfg attribute
Steven Enamakel7f9e2907f089
diff --git a/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rs b/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rsnew file mode 100644index 0000000000..02673ee526--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/turn_outcome.rs@@ -0,0 +1,136 @@+//! The outcome type a `tinyagents`-driven turn produces, plus the shared+//! sinks middleware write into to build it.++use crate::agent::messages::{ChatMessage, ConversationMessage};++/// The outcome of a turn driven on the `tinyagents` harness.+#[derive(Debug, Clone)]+pub(crate) struct TinyagentsTurnOutcome {+ /// Final assistant text.+ pub text: String,+ /// The full transcript, converted back to openhuman messages (flat — tool+ /// calls rendered as text).+ pub history: Vec<ChatMessage>,+ /// The **typed** messages this turn appended (after the user turn):+ /// `AssistantToolCalls` / `ToolResults` / final assistant `Chat`. The chat+ /// session persists these to keep structured tool-call history fidelity.+ pub conversation: Vec<ConversationMessage>,+ /// Number of model calls the loop made.+ pub model_calls: usize,+ /// Number of tool calls the loop made.+ pub tool_calls: usize,+ /// Accumulated input tokens.+ pub input_tokens: u64,+ /// Accumulated output tokens.+ pub output_tokens: u64,+ /// Accumulated cached (cache-read) input tokens. Carried so the turn persists+ /// real cached usage instead of zero (issue #4249, Phase 5).+ pub cached_input_tokens: u64,+ /// Estimated charged USD for the turn (from `cost::catalog::estimate_cost_usd`+ /// over the observed usage). Carried so the transcript / session meters record+ /// a real cost instead of `$0` on every non-cap turn.+ pub charged_amount_usd: f64,+ /// Set when an early-exit tool (e.g. `ask_user_clarification`) fired: the+ /// loop paused so the caller can checkpoint and surface the question. When+ /// present, `text` holds the question. Mirrors the legacy `early_exit_tool`.+ pub early_exit_tool: Option<String>,+ /// `true` when the run stopped because it reached the model-call cap with+ /// work still pending (the last response requested more tools). The caller+ /// should summarize a resumable checkpoint rather than treat `text` as a+ /// final answer — the tinyagents analogue of the legacy cap checkpoint seam.+ pub hit_cap: bool,+ /// `true` when [`FinalCallWrapUpMiddleware`](super::middleware::FinalCallWrapUpMiddleware)+ /// turned this turn's last permitted model call into its conclusion (issue+ /// #6014) — the tools were withdrawn and the wrap-up instruction appended in+ /// the loop, so `text` already **is** the capped turn's answer.+ ///+ /// Read alongside [`hit_cap`](Self::hit_cap) rather than folded into it,+ /// because the caller's action differs: with this set there is nothing left+ /// to ask the model for, while a cap reached without it (a run with the+ /// middleware uninstalled, or one whose final call still came back empty)+ /// keeps the out-of-band `summarize_turn_wrapup` path it always had. That+ /// makes the in-loop conclusion strictly additive — no path loses the+ /// behaviour it has today.+ pub wrap_up_injected: bool,+ /// Set (with the root-cause halt summary) when the repeated-tool-failure /+ /// repeat-progress circuit breaker halted the run before a natural finish.+ /// The sub-agent runner surfaces this as `SubagentRunStatus::Incomplete`+ /// (#4466) so a parent does NOT treat a halted child as a clean completion.+ /// `text` already carries this same summary; the flag lets the status mapper+ /// distinguish a breaker halt from a genuine final answer.+ pub breaker_halt: Option<String>,+ /// Per-tool-call execution outcomes (success + raw result content), keyed by+ /// provider call id, captured at the tool boundary. The harness folds a tool+ /// result into a `Message::tool` that drops its `error` flag, so this is the+ /// only place the caller can recover whether each call actually failed — used+ /// to build honest `ToolCallRecord`s for post-turn hooks + the cap checkpoint.+ pub tool_outcomes: Vec<ToolCallOutcome>,+}++/// One tool call's execution outcome, captured at the tool boundary before the+/// harness discards the failure flag. `success` mirrors the absence of a+/// `TaToolResult::error`; `content` is the (possibly summarized/capped) result+/// text used to derive a sanitized post-turn summary.+#[derive(Debug, Clone)]+pub(crate) struct ToolCallOutcome {+ pub call_id: String,+ pub name: String,+ pub success: bool,+ pub content: String,+}++/// Shared sink the [`ToolOutcomeCaptureMiddleware`](super::middleware::ToolOutcomeCaptureMiddleware)+/// appends each tool call's outcome to, drained into the turn outcome.+pub(crate) type ToolOutcomeSink = std::sync::Arc<std::sync::Mutex<Vec<ToolCallOutcome>>>;++/// Shared slot the repeated-failure breaker writes a root-cause halt summary into+/// when it trips. The turn overrides its final text with this summary so the+/// no-progress halt surfaces the cause instead of an empty/last-model reply+/// (legacy `RepeatFailureGuard` parity).+pub(crate) type HaltSummarySlot = std::sync::Arc<std::sync::Mutex<Option<String>>>;++/// Feed an **unobserved** turn's aggregate usage into the global cost tracker.+///+/// The per-call tracker feed lives in the event bridge+/// ([`OpenhumanEventBridge::record_usage`](super::observability::OpenhumanEventBridge)),+/// which only exists on observed runs (`on_progress` set). Without this+/// aggregate record a fire-and-forget turn's spend never reaches the cost+/// dashboard / wallet surfaces (issue #4249, Phase 5 rollup gap). The bridge+/// and this fallback are mutually exclusive, so spend is recorded exactly once+/// either way.+///+/// Returns `true` when a record was attempted (any tokens observed); all-zero+/// usage is skipped so providers that echo no usage don't inflate the request+/// count. Recording is best-effort — a missing/uninitialised tracker is a+/// silent no-op by contract.+pub(crate) fn record_unobserved_turn_usage(+ model: &str,+ input_tokens: u64,+ output_tokens: u64,+ cached_input_tokens: u64,+ charged_amount_usd: f64,+) -> bool {+ if input_tokens == 0 && output_tokens == 0 {+ return false;+ }+ tracing::debug!(+ model,+ input_tokens,+ output_tokens,+ charged_usd = charged_amount_usd,+ "[tinyagents] recording unobserved-turn usage into the global cost tracker"+ );+ crate::platform::cost::record_provider_usage(+ model,+ &crate::inference::provider::UsageInfo {+ input_tokens,+ output_tokens,+ context_window: 0,+ cached_input_tokens,+ cache_creation_tokens: 0,+ reasoning_tokens: 0,+ charged_amount_usd,+ },+ );+ true+}diff --git a/crates/openhuman-core/src/desktop/accessibility/helper.rs b/crates/openhuman-core/src/desktop/accessibility/helper.rsindex 76696db404..f0a6b07819 100644--- a/crates/openhuman-core/src/desktop/accessibility/helper.rs+++ b/crates/openhuman-core/src/desktop/accessibility/helper.rs@@ -30,8 +30,10 @@ mod swift_overlay;mod swift_paste;mod swift_source;+#[cfg(target_os = "macos")]#[allow(unused_imports)]pub(crate) use process::helper_send_receive;+#[cfg(target_os = "macos")]#[allow(unused_imports)]pub(in crate::desktop::accessibility) use process::{helper_quit, helper_send_fire_and_forget};pub use process::precompile_helper_background;diff --git a/crates/openhuman-core/src/integrations/client/requests.rs b/crates/openhuman-core/src/integrations/client/requests.rsnew file mode 100644index 0000000000..1937b1dde3--- /dev/null+++ b/crates/openhuman-core/src/integrations/client/requests.rs@@ -0,0 +1,153 @@+//! Outbound request plumbing for [`IntegrationClient`]: route guards, egress+//! disclosure/enforcement, budget gating, and the JSON verb methods+//! (`post`/`get`/`patch`/`delete`/`upload_multipart`).++use super::construct::IntegrationClient;++pub(super) fn managed_budget_applies_to_path(path: &str) -> bool {+ path != "/agent-integrations/pricing" && path.starts_with("/agent-integrations/")+}++fn reject_backend_webhook_path(method: &str, path: &str) -> anyhow::Result<()> {+ let route = path.split('?').next().unwrap_or(path);+ if route+ .split('/')+ .any(|segment| segment.eq_ignore_ascii_case("webhooks"))+ {+ anyhow::bail!(+ "route is intentionally not exposed by the SDK: {} {}",+ method,+ route+ );+ }+ Ok(())+}++/// Build the egress descriptor for a managed-backend round-trip. The query+/// string is stripped so only the endpoint (the "to where") is described, never+/// any data carried in the query.+pub(super) fn backend_egress_descriptor(path: &str) -> crate::security::egress::EgressDescriptor {+ let endpoint = path.split('?').next().unwrap_or(path);+ crate::security::egress::EgressDescriptor::integration(endpoint)+}++/// Egress spine (privacy epic S2, #4436): disclose an OpenHuman managed-backend+/// round-trip before it leaves the device. Fire-and-forget — never fails the+/// caller.+pub(super) fn emit_backend_egress(path: &str) {+ crate::security::egress::emit_external_transfer(backend_egress_descriptor(path));+}++/// Local-only enforcement (privacy epic S7, #4441): refuse a managed-backend+/// round-trip that ships user data when the live policy is `LocalOnly`. Returns+/// `Ok(())` for control-plane paths (session / team / billing / integration+/// connection-management + catalog) even under `LocalOnly` — blocking those+/// would break sign-in and the Connections UI for no privacy benefit. See+/// [`is_control_plane`](crate::security::egress). Call before+/// [`emit_backend_egress`] so a blocked call is neither disclosed nor sent.+pub(super) fn enforce_backend_egress(path: &str) -> anyhow::Result<()> {+ crate::security::egress::enforce_egress(&backend_egress_descriptor(path))+}++impl IntegrationClient {+ pub(super) async fn ensure_budget_available(&self, path: &str) -> anyhow::Result<()> {+ if !managed_budget_applies_to_path(path) {+ return Ok(());+ }+ if let Some(config) = &self.budget_config {+ if crate::hosted::team::managed_tool_budget_exhausted(config).await {+ anyhow::bail!(+ "Managed cloud tools are disabled because your OpenHuman AI credits are exhausted. Add credits or route the task to user-supplied providers."+ );+ }+ }+ Ok(())+ }++ /// POST JSON to a backend endpoint and parse the response `data` field.+ pub async fn post<T: serde::de::DeserializeOwned>(+ &self,+ path: &str,+ body: &serde_json::Value,+ ) -> anyhow::Result<T> {+ self.request_json(reqwest::Method::POST, path, Some(body))+ .await+ }++ /// GET from a backend endpoint and parse the response `data` field.+ pub async fn get<T: serde::de::DeserializeOwned>(&self, path: &str) -> anyhow::Result<T> {+ self.request_json(reqwest::Method::GET, path, None).await+ }++ pub(super) async fn request_json<T: serde::de::DeserializeOwned>(+ &self,+ method: reqwest::Method,+ path: &str,+ body: Option<&serde_json::Value>,+ ) -> anyhow::Result<T> {+ reject_backend_webhook_path(method.as_str(), path)?;+ enforce_backend_egress(path)?;+ emit_backend_egress(path);+ self.ensure_budget_available(path).await?;+ let url = crate::api::config::api_url(&self.backend_url, path);+ let method_name = method.as_str().to_ascii_lowercase();+ tracing::debug!("[integrations] {} {}", method.as_str(), url);+ let value = self+ .sdk+ .raw()+ .send(method, path, &[], body, false)+ .await+ .map_err(|error| Self::map_sdk_error(error, &method_name, path, &url))?;+ Self::parse_envelope(&method_name, path, &url, value)+ }++ /// PATCH JSON to a backend endpoint and parse the response `data` field.+ /// Mirrors [`Self::post`] (auth header, 401 → session-expiry, error+ /// classification).+ pub async fn patch<T: serde::de::DeserializeOwned>(+ &self,+ path: &str,+ body: &serde_json::Value,+ ) -> anyhow::Result<T> {+ self.request_json(reqwest::Method::PATCH, path, Some(body))+ .await+ }++ /// DELETE a backend resource and parse the response `data` field.+ /// Mirrors [`Self::post`] (auth header, 401 → session-expiry, error+ /// classification).+ pub async fn delete<T: serde::de::DeserializeOwned>(&self, path: &str) -> anyhow::Result<T> {+ self.request_json(reqwest::Method::DELETE, path, None).await+ }++ /// POST a `multipart/form-data` body to a backend endpoint and parse the+ /// response `data` field. Mirrors [`Self::post`] URL building, Bearer+ /// auth, 401 → session-expiry handling and error classification; the+ /// content type is set by reqwest from the form boundary.+ pub async fn upload_multipart<T: serde::de::DeserializeOwned>(+ &self,+ path: &str,+ form: reqwest::multipart::Form,+ ) -> anyhow::Result<T> {+ reject_backend_webhook_path("POST", path)?;+ enforce_backend_egress(path)?;+ emit_backend_egress(path);+ self.ensure_budget_available(path).await?;+ let url = crate::api::config::api_url(&self.backend_url, path);+ tracing::debug!("[integrations] POST(multipart) {}", url);++ let value = self+ .sdk+ .raw()+ .post_multipart(path, form)+ .await+ .map_err(|error| Self::map_sdk_error(error, "post_multipart", path, &url))?;+ // The SDK unwraps successful `{success,data}` responses. Preserve+ // compatibility with endpoints that return their payload directly,+ // while still recognizing a `success:false` envelope.+ if value.get("success") == Some(&serde_json::Value::Bool(false)) {+ return Self::parse_envelope("post_multipart", path, &url, value);+ }+ Ok(serde_json::from_value(value)?)+ }+}