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
chore: update import paths across multiple modules
Steven Enamakel950cd0a8ae33
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rsindex c0785b633d..ae9b6b7908 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_tests.rs@@ -1,5 +1,34 @@use super::*;+use super::approval::approval_tool_name;+use super::artifact_index_toc::{FOOTER_ALLOWANCE, NO_WINDOW_ALLOWANCE};+use super::message_trim::{estimate_message_tokens, estimate_text_tokens, IMAGE_MARKER_TOKEN_COST};+use super::repeated_failure::{is_body_level_failure, user_actionable_escalation};+use super::tool_output::{+ is_compaction_exempt, is_truncation_exempt, COMPACTION_EXEMPT_TOOLS, SAMPLING_TOOLS,+};+use super::turn_context::DEFAULT_TOOL_RESULT_BUDGET_BYTES;use serde_json::json;+use std::collections::HashMap;+use std::sync::Arc;++use async_trait::async_trait;++use tinyagents_harness::middleware::{+ AgentRun, BudgetTracker, Middleware, MiddlewareToolOutcome, ToolHandler, ToolMiddleware,+};+use tinyagents_harness::steering::{SteeringCommand, SteeringHandle};+use tinyagents_harness::tool::{ToolPolicy as TaToolPolicy, ToolResult as TaToolResult};+use tinyinference::message::{ContentBlock, Message as TaMessage};+use tinyinference::model::{ModelResponse, SegmentRole};+use tinyinference::tool::{ToolCall as TaToolCall, ToolSchema};++use crate::agent::context::CLEARED_PLACEHOLDER;+use crate::agent::harness::tool_result_artifacts::TINYAGENTS_TOOL_RESULT_ARTIFACT_STORE;+use crate::agent::tinyagents::payload_summarizer::{+ PayloadSummarizer, SummarizeOutcome, UnavailableReason,+};+use crate::inference::tokenjuice::AgentTokenjuiceCompression;+use crate::tools::Tool;use tinyagents_harness::context::{RunConfig, RunContext};use tinyagents_harness::no_progress::{DEFAULT_REPEAT_CALL_THRESHOLD, DEFAULT_REPEAT_OUTPUT_THRESHOLD,@@ -382,11 +411,11 @@ fn embedder_hook_mw(})])}-#[path = "middleware_tests_part_01_tests.rs"]-mod part_01_tests;-#[path = "middleware_tests_part_02_tests.rs"]-mod part_02_tests;-#[path = "middleware_tests_part_03_tests.rs"]-mod part_03_tests;-#[path = "middleware_tests_part_04_tests.rs"]-mod part_04_tests;+#[path = "middleware_tool_output_tests.rs"]+mod tool_output_tests;+#[path = "middleware_loop_guard_tests.rs"]+mod loop_guard_tests;+#[path = "middleware_wrap_up_toc_tests.rs"]+mod wrap_up_toc_tests;+#[path = "middleware_tool_policy_tests.rs"]+mod tool_policy_tests;diff --git a/crates/openhuman-core/src/flows/ops/approval_manifest.rs b/crates/openhuman-core/src/flows/ops/approval_manifest.rsindex 4904d3f890..8305850094 100644--- a/crates/openhuman-core/src/flows/ops/approval_manifest.rs+++ b/crates/openhuman-core/src/flows/ops/approval_manifest.rs@@ -195,7 +195,7 @@ pub async fn compute_approval_manifest(config: &Config, graph: &WorkflowGraph) -/// permissions are authorized on a host that holds no grant for them./// `gate_installed: false` is the caller's single signal, which is exactly what/// the sibling `approval_preauthorize_flow` reports for the same condition.-fn split_manifest_trust(+pub(super) fn split_manifest_trust(entries: &[Value],gate_installed: bool,trusted: &HashSet<String>,diff --git a/crates/openhuman-core/src/flows/ops/builder.rs b/crates/openhuman-core/src/flows/ops/builder.rsindex c96ba6e054..f9ccfe24d2 100644--- a/crates/openhuman-core/src/flows/ops/builder.rs+++ b/crates/openhuman-core/src/flows/ops/builder.rs@@ -440,7 +440,7 @@ pub async fn flows_build_cancel(/// return a self-describing `{ "type": "workflow_proposal", … }` JSON string as/// their tool result, so we match on that (the same gate the frontend uses) and/// return the LAST one — the most recent proposal in the turn.-fn extract_workflow_proposal(+pub(super) fn extract_workflow_proposal(history: &[crate::agent::messages::ConversationMessage],) -> Option<Value> {use crate::agent::messages::ConversationMessage;diff --git a/crates/openhuman-core/src/flows/ops/builder_toolset.rs b/crates/openhuman-core/src/flows/ops/builder_toolset.rsindex 9e38ae0a44..e499c55f55 100644--- a/crates/openhuman-core/src/flows/ops/builder_toolset.rs+++ b/crates/openhuman-core/src/flows/ops/builder_toolset.rs@@ -10,7 +10,7 @@ use super::*;/// ~10s/iteration can take up to ~500s — the old 300s bound would have/// clipped a legitimate long build before the iteration cap ever got a/// chance to.-const FLOW_BUILD_TIMEOUT_SECS: u64 = 600;+pub(super) const FLOW_BUILD_TIMEOUT_SECS: u64 = 600;/// Tools stripped from the `workflow_builder` belt on the direct `flows_build`/// RPC path (issue #4593; widened for `resume_flow_run`/`cancel_flow_run`@@ -58,7 +58,7 @@ const FLOW_BUILD_TIMEOUT_SECS: u64 = 600;/// both are hard-forced **born disabled** (see [`builder_tools::CreateWorkflowTool`]/// / [`builder_tools::DuplicateFlowTool`]), so even an unattended call can't/// leave anything live — lower risk than the run/resume/cancel trio above.-const FLOWS_BUILD_HIDDEN_TOOLS: &[&str] = &[+pub(super) const FLOWS_BUILD_HIDDEN_TOOLS: &[&str] = &["run_workflow","run_flow","resume_flow_run",@@ -74,7 +74,7 @@ const FLOWS_BUILD_HIDDEN_TOOLS: &[&str] = &[/// boundary — a hard execution guarantee even if the model requests the tool./// The authoring tools (`propose`/`revise`/`save`/`dry_run`/reads/`create_workflow`//// `duplicate_flow`) stay visible and untouched, so the turn never fail-closes.-fn restrict_builder_toolset(agent: &mut crate::agent::Agent) {+pub(super) fn restrict_builder_toolset(agent: &mut crate::agent::Agent) {tracing::debug!(target: "flows",hidden = ?FLOWS_BUILD_HIDDEN_TOOLS,@@ -126,12 +126,12 @@ fn restrict_builder_toolset(agent: &mut crate::agent::Agent) {/// belt) stays hidden — belt-and-braces against a re-rename or the name ever/// leaking back onto the `workflow_builder` toolset; `hide_tools` no-ops on a/// name that isn't present.-const FLOWS_BUILD_COPILOT_HIDDEN_TOOLS: &[&str] = &["run_workflow", "cancel_flow_run"];+pub(super) const FLOWS_BUILD_COPILOT_HIDDEN_TOOLS: &[&str] = &["run_workflow", "cancel_flow_run"];/// Strip only [`FLOWS_BUILD_COPILOT_HIDDEN_TOOLS`] from `agent`'s callable set/// on the streaming `flows_build` path (copilot pane with a real approval/// surface) — see that constant's doc for the full safety rationale.-fn restrict_builder_toolset_for_copilot(agent: &mut crate::agent::Agent) {+pub(super) fn restrict_builder_toolset_for_copilot(agent: &mut crate::agent::Agent) {tracing::info!(target: "flows",hidden = ?FLOWS_BUILD_COPILOT_HIDDEN_TOOLS,diff --git a/crates/openhuman-core/src/flows/ops/connection_ref_gate.rs b/crates/openhuman-core/src/flows/ops/connection_ref_gate.rsindex 5038d7ebb0..802e2fa3c5 100644--- a/crates/openhuman-core/src/flows/ops/connection_ref_gate.rs+++ b/crates/openhuman-core/src/flows/ops/connection_ref_gate.rs@@ -88,7 +88,7 @@ pub(crate) async fn validate_connection_refs(/// when the live connection list was fetched (possibly empty — a genuine "no/// connections" state), or `None` when it was unavailable (fail-open: the/// id-existence check is skipped, only the toolkit-mismatch check runs).-fn validate_connection_refs_against(+pub(super) fn validate_connection_refs_against(graph: &WorkflowGraph,connections: Option<&[FlowConnection]>,) -> Vec<String> {diff --git a/crates/openhuman-core/src/flows/ops/connections.rs b/crates/openhuman-core/src/flows/ops/connections.rsindex 7e9edc66d1..bce031a626 100644--- a/crates/openhuman-core/src/flows/ops/connections.rs+++ b/crates/openhuman-core/src/flows/ops/connections.rs@@ -119,7 +119,7 @@ pub async fn flows_list_connections(/// (e.g. Slack `U123ABC`). This is what lets the workflow builder wire a/// self-targeted action ("DM me") to the user's own account instead of/// guessing a public channel.-fn build_flow_connections(+pub(super) fn build_flow_connections(composio: Vec<crate::integrations::composio::ComposioConnection>,http: Vec<crate::security::credentials::HttpCredentialSummary>,identities: &[crate::integrations::composio::providers::ConnectedIdentity],@@ -221,7 +221,7 @@ fn http_credential_display(/// Title-case a toolkit slug for display: `"gmail"` → `"Gmail"`,/// `"google_calendar"` → `"Google Calendar"`. Best-effort cosmetic only.-fn title_case_toolkit(toolkit: &str) -> String {+pub(super) fn title_case_toolkit(toolkit: &str) -> String {let trimmed = toolkit.trim();if trimmed.is_empty() {return String::new();diff --git a/crates/openhuman-core/src/flows/ops/definitions.rs b/crates/openhuman-core/src/flows/ops/definitions.rsindex 27896c2aab..38d51a2687 100644--- a/crates/openhuman-core/src/flows/ops/definitions.rs+++ b/crates/openhuman-core/src/flows/ops/definitions.rs@@ -4,7 +4,7 @@ use super::*;/// so an open Workflows list/canvas refetches (bridged to a `flow:changed`/// socket event) — the observability half of audit F6. Best-effort broadcast;/// `actor` is a coarse hint (`"system"` for RPC-driven changes today).-fn publish_flow_changed(flow_id: &str, kind: &str, actor: &str) {+pub(super) fn publish_flow_changed(flow_id: &str, kind: &str, actor: &str) {tracing::debug!(target: "flows", %flow_id, kind, actor, "[flows] publishing FlowChanged");crate::core::bus::BUS.publish(crate::core::events::DomainEvent::FlowChanged {flow_id: flow_id.to_string(),@@ -263,7 +263,7 @@ pub async fn flows_delete(config: &Config, id: &str) -> Result<RpcOutcome<Value>/// and the resolved path are the same type running the same policy steps; the/// override can no longer be a second, unguarded door into memory. Production/// still passes `None`.-async fn flows_delete_impl(+pub(super) async fn flows_delete_impl(config: &Config,id: &str,memory_override: Option<Arc<crate::memory::guard::MemoryGuard>>,diff --git a/crates/openhuman-core/src/flows/ops/execution.rs b/crates/openhuman-core/src/flows/ops/execution.rsindex d1bf4efe01..1a197689da 100644--- a/crates/openhuman-core/src/flows/ops/execution.rs+++ b/crates/openhuman-core/src/flows/ops/execution.rs@@ -3,7 +3,7 @@ use super::*;/// Builds the `TrustedAutomation { Workflow }` origin scoped around every/// `flows_run` / `flows_resume` invocation. See `flows_run`'s doc for why/// this applies uniformly regardless of caller.-fn workflow_origin(flow_id: &str, require_approval: bool) -> AgentTurnOrigin {+pub(super) fn workflow_origin(flow_id: &str, require_approval: bool) -> AgentTurnOrigin {AgentTurnOrigin::TrustedAutomation {job_id: flow_id.to_string(),source: TrustedAutomationSource::Workflow { require_approval },@@ -16,7 +16,7 @@ fn workflow_origin(flow_id: &str, require_approval: bool) -> AgentTurnOrigin {/// construction: any journal read failure is logged and swallowed, and the/// exporter itself never fails the run. Skips the journal read entirely when/// `observability.share_usage_data` is off.-async fn export_run_to_langfuse(+pub(super) async fn export_run_to_langfuse(config: &Config,flow_name: &str,flow_id: &str,@@ -90,7 +90,7 @@ async fn export_run_to_langfuse(/// status. Registering before the `run_id` is observable makes the cancel/// always take the signalled branch instead. `_run_guard` is held for the whole/// body and deregisters on any exit, including the early returns below.-async fn run_flow_body(+pub(super) async fn run_flow_body(config_arc: Arc<Config>,flow: Flow,flow_id: String,@@ -422,7 +422,7 @@ fn now_ms() -> u64 {/// generic `DomainEvent -> event_to_notification` bridge — this is a/// flows-specific card with flow-specific action data, not a translation of/// an existing broadcast event). No-op when nothing is pending.-fn notify_pending_approval(flow: &Flow, thread_id: &str, pending_approvals: &[String]) {+pub(super) fn notify_pending_approval(flow: &Flow, thread_id: &str, pending_approvals: &[String]) {if pending_approvals.is_empty() {return;}diff --git a/crates/openhuman-core/src/flows/ops/inference_readiness.rs b/crates/openhuman-core/src/flows/ops/inference_readiness.rsindex 8cc45f00c0..f5e911a7bd 100644--- a/crates/openhuman-core/src/flows/ops/inference_readiness.rs+++ b/crates/openhuman-core/src/flows/ops/inference_readiness.rs@@ -92,7 +92,7 @@ type InferenceProbeCacheMap =/// above on fail-open) — a fixed provider becomes visible again at most/// `INFERENCE_PROBE_CACHE_TTL` later, or immediately on sign-out/back-in via/// [`invalidate_inference_probe_cache_if_signed_out`].-static INFERENCE_PROBE_CACHE: LazyLock<std::sync::Mutex<InferenceProbeCacheMap>> =+pub(super) static INFERENCE_PROBE_CACHE: LazyLock<std::sync::Mutex<InferenceProbeCacheMap>> =LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));/// Invalidate every cached Layer-2 probe result. Checked defensively on every@@ -110,7 +110,7 @@ fn invalidate_inference_probe_cache_if_signed_out() {}}-async fn cached_probe_inference_readiness(role: &str, config: &Config) -> Result<(), String> {+pub(super) async fn cached_probe_inference_readiness(role: &str, config: &Config) -> Result<(), String> {invalidate_inference_probe_cache_if_signed_out();let key: InferenceProbeCacheKey = (role.to_string(), config.config_path.clone());@@ -169,7 +169,7 @@ async fn cached_probe_inference_readiness(role: &str, config: &Config) -> Result/// this case falls back to the default role rather than guess./// TODO(B45): resolve agent_ref-pinned model for harness `AgentDefinition`s/// once a parent-model-free resolution path exists.-fn agent_node_role(config: &Config, node: &tinyflows::model::Node) -> &'static str {+pub(super) fn agent_node_role(config: &Config, node: &tinyflows::model::Node) -> &'static str {let pinned_model = node.config.get("model")@@ -226,14 +226,14 @@ fn classify_inference_error_message(message: &str) -> &'static str {/// Outcome of [`evaluate_inference_readiness`] for a graph that has at least/// one applicable `agent` node.-struct InferenceReadinessEvaluation {+pub(super) struct InferenceReadinessEvaluation {/// One of `"ready"`, `"signed_out"`, `"provider_not_configured"`, `"error"`/// — the fixed vocabulary shared with the proposal payload.- status: &'static str,+ pub(super) status: &'static str,/// User-actionable prose; `None` only when `status == "ready"`.- message: Option<String>,+ pub(super) message: Option<String>,/// The offending node id, when applicable (absent for `"ready"`).- node_id: Option<String>,+ pub(super) node_id: Option<String>,}/// Evaluate the B45 provider-connectivity gate for `graph`.@@ -254,7 +254,7 @@ struct InferenceReadinessEvaluation {/// role already probed elsewhere in this process within the TTL is served/// from cache). `status`/`message` report `provider_not_configured`/`error`/// if ANY role's probe fails, naming every offending node and role.-async fn evaluate_inference_readiness(+pub(super) async fn evaluate_inference_readiness(config: &Config,graph: &WorkflowGraph,) -> Option<InferenceReadinessEvaluation> {diff --git a/crates/openhuman-core/src/flows/ops/resume.rs b/crates/openhuman-core/src/flows/ops/resume.rsindex 03c5f5972b..e458470dea 100644--- a/crates/openhuman-core/src/flows/ops/resume.rs+++ b/crates/openhuman-core/src/flows/ops/resume.rs@@ -502,7 +502,7 @@ pub async fn flows_resume(/// cannot be hashed is a run whose approval cannot be verified — but it is the/// opposite of fail-open, so do not read this as a guarantee that a serialize/// failure leaves a resumable run resumable.-fn compute_graph_hash(graph: &WorkflowGraph, require_approval: bool) -> Option<String> {+pub(super) fn compute_graph_hash(graph: &WorkflowGraph, require_approval: bool) -> Option<String> {let raw = match serde_json::to_value(graph) {Ok(v) => v,Err(e) => {diff --git a/crates/openhuman-core/src/flows/ops/run.rs b/crates/openhuman-core/src/flows/ops/run.rsindex b5d609349d..ce26099d86 100644--- a/crates/openhuman-core/src/flows/ops/run.rs+++ b/crates/openhuman-core/src/flows/ops/run.rs@@ -157,13 +157,13 @@ pub async fn flows_run_detached(/// minted `thread_id` (== run id / checkpointer key), and whether the graph has/// no actionable nodes. Produced by [`prepare_flow_run`] and consumed by both/// `flows_run` entry points.-struct PreparedFlowRun {- flow: Flow,- thread_id: String,- no_actionable_nodes: bool,+pub(super) struct PreparedFlowRun {+ pub(super) flow: Flow,+ pub(super) thread_id: String,+ pub(super) no_actionable_nodes: bool,/// The flow's declared inputs resolved against the caller's values —/// defaults applied, one entry per declaration.- inputs: serde_json::Map<String, Value>,+ pub(super) inputs: serde_json::Map<String, Value>,}/// Synchronous prep shared by [`flows_run`] and [`flows_run_detached`]: loads@@ -178,7 +178,7 @@ struct PreparedFlowRun {/// The engine re-resolves the same values (it is the authority on its own/// contract); doing it twice is cheap and keeps this host from having to trust/// its own copy of the rules.-fn prepare_flow_run(+pub(super) fn prepare_flow_run(config: &Config,flow_id: &str,inputs: &serde_json::Map<String, Value>,diff --git a/crates/openhuman-core/src/flows/ops/run_management.rs b/crates/openhuman-core/src/flows/ops/run_management.rsindex 2ec6cb59d6..f43f8af1d2 100644--- a/crates/openhuman-core/src/flows/ops/run_management.rs+++ b/crates/openhuman-core/src/flows/ops/run_management.rs@@ -108,7 +108,7 @@ pub async fn flows_cancel_run(config: &Config, run_id: &str) -> Result<RpcOutcom/// authoritative "not resumable" signal (the `flows_resume` guard already/// rejects any non-`pending_approval` status); dropping the checkpoint is/// belt-and-suspenders that also reclaims the storage.-async fn drop_checkpoint(config: &Config, thread_id: &str) {+pub(super) async fn drop_checkpoint(config: &Config, thread_id: &str) {match crate::flows::tinyflows::open_flow_checkpointer(config) {Ok(checkpointer) => match checkpointer.delete_thread(thread_id).await {Ok(()) => {diff --git a/crates/openhuman-core/src/flows/ops/run_rows.rs b/crates/openhuman-core/src/flows/ops/run_rows.rsindex ebacd1ec46..8e1ad48fd4 100644--- a/crates/openhuman-core/src/flows/ops/run_rows.rs+++ b/crates/openhuman-core/src/flows/ops/run_rows.rs@@ -5,7 +5,7 @@ use super::*;/// tool abort, chat turn end, runtime shutdown, panic) before any terminal/// write landed. Surfaced verbatim in the run-details sidebar (bug B42c) so a/// cancelled/timed-out run reads as interrupted rather than a blank spinner.-const INTERRUPTED_DROP_REASON: &str =+pub(super) const INTERRUPTED_DROP_REASON: &str ="Run interrupted before completion — it was cancelled, timed out, or the app shut down mid-run.";/// Cancellation-safe finalizer for a live `flow_runs` row (bug B42).@@ -19,7 +19,7 @@ const INTERRUPTED_DROP_REASON: &str =/// explicitly [`disarm`](Self::disarm)ed after a real terminal write. The/// `armed` flag is a single-task `Cell` (the guard never crosses tasks by/// reference), so the type stays `Send` for `tokio::spawn`.-struct RunRowFinalizer {+pub(super) struct RunRowFinalizer {config: Arc<Config>,thread_id: String,flow_id: String,@@ -27,7 +27,7 @@ struct RunRowFinalizer {}impl RunRowFinalizer {- fn new(config: Arc<Config>, thread_id: &str, flow_id: &str) -> Self {+ pub(super) fn new(config: Arc<Config>, thread_id: &str, flow_id: &str) -> Self {Self {config,thread_id: thread_id.to_string(),@@ -38,7 +38,7 @@ impl RunRowFinalizer {/// Disarm the guard after a real terminal write (success/failure/cancel//// pause) has already finalized the row, so `Drop` becomes a no-op.- fn disarm(&self) {+ pub(super) fn disarm(&self) {self.armed.set(false);}}@@ -103,12 +103,12 @@ impl Drop for RunRowFinalizer {/// has since moved ahead of the insert, closing that window at the source too;/// the floor stays because it holds regardless of what future callers do with/// that ordering.-static PROCESS_RUN_FLOOR: LazyLock<String> = LazyLock::new(|| Utc::now().to_rfc3339());+pub(super) static PROCESS_RUN_FLOOR: LazyLock<String> = LazyLock::new(|| Utc::now().to_rfc3339());/// Best-effort insert of the initial `"running"` `flow_runs` row. Logged,/// never fails the run — run-history persistence is an observability aid,/// not a correctness requirement of the run itself.-fn start_flow_run_row(config: &Config, thread_id: &str, flow_id: &str) {+pub(super) fn start_flow_run_row(config: &Config, thread_id: &str, flow_id: &str) {// Anchor the boot-sweep floor BEFORE stamping this row, so this row's// `started_at` can never precede it. See [`PROCESS_RUN_FLOOR`].LazyLock::force(&PROCESS_RUN_FLOOR);@@ -125,7 +125,7 @@ fn start_flow_run_row(config: &Config, thread_id: &str, flow_id: &str) {/// row (`status == "pending_approval"`) — every other caller passes `None`,/// which clears any stale pin now that the row is leaving (or never entered)/// `pending_approval`. See [`compute_graph_hash`] and `store::finish_flow_run`.-fn finish_flow_run_row(+pub(super) fn finish_flow_run_row(config: &Config,thread_id: &str,flow_id: &str,@@ -239,7 +239,7 @@ fn reconstruct_steps(output: &Value) -> Vec<FlowRunStep> {/// run's settle path.////// [`FlowRunObserver`]: crate::flows::tinyflows::observability::FlowRunObserver-fn current_persisted_steps(config: &Config, run_id: &str) -> Vec<FlowRunStep> {+pub(super) fn current_persisted_steps(config: &Config, run_id: &str) -> Vec<FlowRunStep> {store::get_flow_run(config, run_id).ok().flatten()@@ -254,7 +254,7 @@ fn current_persisted_steps(config: &Config, run_id: &str) -> Vec<FlowRunStep> {/// observer that missed a step. If the observer recorded nothing at all/// (e.g. a run that paused immediately at a gate before any node finished),/// falls back wholesale to the reconstruction.-fn settle_steps(config: &Config, run_id: &str, output: &Value) -> Vec<FlowRunStep> {+pub(super) fn settle_steps(config: &Config, run_id: &str, output: &Value) -> Vec<FlowRunStep> {let reconstructed = reconstruct_steps(output);let persisted = current_persisted_steps(config, run_id);if persisted.is_empty() {@@ -291,7 +291,7 @@ fn settle_steps(config: &Config, run_id: &str, output: &Value) -> Vec<FlowRunSte/// Called only once the run has no `pending_approvals` left — precedence/// against that case is handled by the caller (`pending_approval` always/// wins over any of these).-fn degrade_completed_status(steps: &[FlowRunStep]) -> &'static str {+pub(super) fn degrade_completed_status(steps: &[FlowRunStep]) -> &'static str {if steps.iter().any(|s| s.status.as_deref() == Some("error")) {return "failed";}@@ -309,7 +309,7 @@ fn degrade_completed_status(steps: &[FlowRunStep]) -> &'static str {/// policy is `"stop"`), so this is the best available detail for/// [`FlowRun::error`] when [`degrade_completed_status`] degrades to/// `"failed"` without an outer run-future `Err`.-fn failed_step_error_summary(steps: &[FlowRunStep]) -> Option<String> {+pub(super) fn failed_step_error_summary(steps: &[FlowRunStep]) -> Option<String> {let failed_nodes: Vec<&str> = steps.iter().filter(|s| s.status.as_deref() == Some("error"))@@ -332,7 +332,7 @@ fn failed_step_error_summary(steps: &[FlowRunStep]) -> Option<String> {/// populate [`FlowRun::error`] (its doc contract: "Error message when/// `status == \"failed\"`") for a run that degraded via a settled step error/// rather than an outer run-future `Err`.-fn finalize_terminal_status(+pub(super) fn finalize_terminal_status(settled: &[FlowRunStep],pending_approvals: &[String],) -> (&'static str, Option<String>) {diff --git a/crates/openhuman-core/src/flows/ops/streaming.rs b/crates/openhuman-core/src/flows/ops/streaming.rsindex 7394c6d9b4..5238832f2e 100644--- a/crates/openhuman-core/src/flows/ops/streaming.rs+++ b/crates/openhuman-core/src/flows/ops/streaming.rs@@ -54,7 +54,7 @@ impl FlowStreamTarget {/// on reopen). The bridge task lives until the agent drops its progress sender/// (turn end). `source` is a short trace-attribution label (e.g./// `"flows_build"`).-fn attach_flow_progress_bridge(+pub(super) fn attach_flow_progress_bridge(agent: &mut crate::agent::Agent,target: &FlowStreamTarget,source: &str,@@ -90,7 +90,7 @@ fn attach_flow_progress_bridge(/// path, so segmentation/reaction match a normal turn), a failure publishes a/// `chat_error`. Broadcast as `"system"` so any viewer of the thread receives/// it (frontend keys by `thread_id`).-async fn finalize_flow_stream(+pub(super) async fn finalize_flow_stream(target: &FlowStreamTarget,result: &Result<String, String>,prompt: &str,diff --git a/crates/openhuman-core/src/flows/ops/trail_off.rs b/crates/openhuman-core/src/flows/ops/trail_off.rsindex 0dd02cdda9..4aee9f7d08 100644--- a/crates/openhuman-core/src/flows/ops/trail_off.rs+++ b/crates/openhuman-core/src/flows/ops/trail_off.rs@@ -21,7 +21,7 @@ use super::*;/// delimiter of a code span whose last character is `?` (e.g. `` `id = ?` ``/// at the very end of the text), exposing that `?` as if it were a bare/// trailing question mark and defeating the code guard entirely.-fn text_looks_like_question(text: &str) -> bool {+pub(super) fn text_looks_like_question(text: &str) -> bool {let trimmed = text.trim().trim_end_matches(['"', '\'', ')', ']', '*', '_', '.'])@@ -112,7 +112,7 @@ fn last_paragraph(text: &str) -> Option<String> {/// unanswerable status note — exactly the failure mode this backstop exists/// to prevent. So each candidate `?` is additionally required to be/// sentence-terminal via [`is_sentence_terminal_question_mark`].-fn question_mark_outside_code(text: &str) -> bool {+pub(super) fn question_mark_outside_code(text: &str) -> bool {let chars: Vec<char> = text.chars().collect();// `Some(n)` while scanning is inside a code span opened by a run of `n`// backticks; that span closes only on the next run of exactly `n`.@@ -185,7 +185,7 @@ const TRAIL_OFF_BLOCKER_TOOLS: &[&str] = &[/// falls back to a generic "what should I focus on" question when no such/// blocker is found (the model may have simply stopped with nothing to point/// to).-fn build_trail_off_fallback(+pub(super) fn build_trail_off_fallback(history: &[crate::agent::messages::ConversationMessage],) -> String {match last_builder_tool_blocker(history) {@@ -208,7 +208,7 @@ fn build_trail_off_fallback(/// context. When `original` is empty/whitespace-only (a genuine silent/// turn — there's nothing to preserve), returns the fallback alone rather/// than prepending an empty divider.-fn combine_trail_off_fallback(fallback: &str, original: &str) -> String {+pub(super) fn combine_trail_off_fallback(fallback: &str, original: &str) -> String {let trimmed_original = original.trim();if trimmed_original.is_empty() {fallback.to_string()diff --git a/crates/openhuman-core/src/flows/ops/triggers.rs b/crates/openhuman-core/src/flows/ops/triggers.rsindex 91e190a223..496ced2a77 100644--- a/crates/openhuman-core/src/flows/ops/triggers.rs+++ b/crates/openhuman-core/src/flows/ops/triggers.rs@@ -127,7 +127,7 @@ pub async fn flows_set_enabled(/// `flows_set_enabled` call — the flow is still saved as enabled, it just/// won't fire automatically until the underlying issue (invalid schedule,/// cron store error, …) is fixed.-fn bind_trigger(config: &Config, flow: &Flow) {+pub(super) fn bind_trigger(config: &Config, flow: &Flow) {match bus::extract_trigger_kind(flow) {Some(TriggerKind::Schedule) => bind_schedule_trigger(config, flow),Some(TriggerKind::Webhook) => log_webhook_trigger_deferred(flow, true),@@ -141,7 +141,7 @@ fn bind_trigger(config: &Config, flow: &Flow) {/// Tears down the automatic-dispatch side effect for `flow`'s trigger kind,/// mirroring [`bind_trigger`]. Best-effort, same rationale.-fn unbind_trigger(config: &Config, flow: &Flow) {+pub(super) fn unbind_trigger(config: &Config, flow: &Flow) {match bus::extract_trigger_kind(flow) {Some(TriggerKind::Schedule) => unbind_schedule_trigger(config, &flow.id),Some(TriggerKind::Webhook) => log_webhook_trigger_deferred(flow, false),@@ -155,7 +155,7 @@ fn unbind_trigger(config: &Config, flow: &Flow) {/// `cron::find_flow_schedule_job` rather than creating a duplicate, so this/// is safe to call both from `flows_set_enabled` and from boot/// reconciliation ([`reconcile_schedule_triggers_on_boot`]).-fn bind_schedule_trigger(config: &Config, flow: &Flow) {+pub(super) fn bind_schedule_trigger(config: &Config, flow: &Flow) {let Some(trigger_config) = bus::extract_trigger_config(flow) else {tracing::warn!(target: "flows", flow_id = %flow.id, "[flows] schedule trigger: flow has no single trigger node — cannot bind cron job");return;diff --git a/crates/openhuman-core/src/flows/ops/validation.rs b/crates/openhuman-core/src/flows/ops/validation.rsindex ef04afc4b7..501b9fb7b1 100644--- a/crates/openhuman-core/src/flows/ops/validation.rs+++ b/crates/openhuman-core/src/flows/ops/validation.rs@@ -80,7 +80,7 @@ fn to_compat_validation_error(/// validation cannot inspect. Authoring boundaries use it before persistence;/// execution boundaries use it before compiling a root run/resume or returning/// a resolver graph, so an unsafe descendant cannot run after earlier effects.-fn ensure_config_aware_engine_compatible(+pub(super) fn ensure_config_aware_engine_compatible(config: &Config,graph: &WorkflowGraph,) -> Result<(), String> {@@ -128,7 +128,7 @@ pub(crate) fn to_flow_validation_error(/// parent that is already known to fail at execution. Dynamic `=` expressions,/// missing ids, and store failures retain their existing runtime diagnostics;/// this gate only rejects a saved graph whose topology is demonstrably unsafe.-fn referenced_workflow_compatibility_errors(config: &Config, graph: &WorkflowGraph) -> Vec<String> {+pub(super) fn referenced_workflow_compatibility_errors(config: &Config, graph: &WorkflowGraph) -> Vec<String> {// Descend as deep as the root graph declared it may nest, for the same// reason as the inline walk above.let max_depth = max_sub_workflow_depth(graph);diff --git a/crates/openhuman-core/src/flows/ops/wiring_warnings.rs b/crates/openhuman-core/src/flows/ops/wiring_warnings.rsindex 1f78292971..5feb498013 100644--- a/crates/openhuman-core/src/flows/ops/wiring_warnings.rs+++ b/crates/openhuman-core/src/flows/ops/wiring_warnings.rs@@ -88,7 +88,7 @@ pub(crate) async fn graph_wiring_warnings(config: &Config, graph: &WorkflowGraph/// `.item.json.<x>` fields with no `data.` prefix; flagging them as/// "missing the `data.` segment" would rewire an already-correct binding to/// a nonsense path (e.g. suggesting `.item.json.data.successful`).-async fn graph_output_field_warnings(config: &Config, graph: &WorkflowGraph) -> Vec<String> {+pub(super) async fn graph_output_field_warnings(config: &Config, graph: &WorkflowGraph) -> Vec<String> {use crate::flows::tinyflows::caps::fetch_live_toolkit_catalog;// Reading a graph's `=`-bindings is the engine's grammar, not this host's:// both helpers were a private copy here until the gates moved upstream.diff --git a/crates/openhuman-core/src/inference/local/ops.rs b/crates/openhuman-core/src/inference/local/ops.rsindex b76ac8fb97..dd784915df 100644--- a/crates/openhuman-core/src/inference/local/ops.rs+++ b/crates/openhuman-core/src/inference/local/ops.rs@@ -7,5 +7,25 @@#[cfg(test)]#[path = "ops_tests.rs"]mod tests;-include!("ops_part_01.rs");-include!("ops_part_02.rs");++mod agent_chat;+mod chat;+mod reactions;+mod runtime_ops;+mod turn_guards;++pub use agent_chat::{agent_chat, agent_chat_simple};+pub use chat::{local_ai_chat, LocalAiChatMessage};+pub use reactions::{local_ai_should_react, ReactionDecision};+pub use runtime_ops::{+ local_ai_assets_status, local_ai_download_asset, local_ai_downloads_progress, local_ai_embed,+ local_ai_prompt, local_ai_status, local_ai_summarize, local_ai_transcribe,+ local_ai_transcribe_bytes, local_ai_tts, local_ai_vision_prompt,+};++#[cfg(test)]+use reactions::{extract_first_emoji, is_emoji_start};+#[cfg(test)]+use turn_guards::{+ effective_agent_chat_origin, grant_turn_cwd, normalize_model_override, resolve_turn_cwd,+};diff --git a/crates/openhuman-core/src/inference/local/ops/agent_chat.rs b/crates/openhuman-core/src/inference/local/ops/agent_chat.rsnew file mode 100644index 0000000000..45f47a3b45--- /dev/null+++ b/crates/openhuman-core/src/inference/local/ops/agent_chat.rs@@ -0,0 +1,203 @@+//! Agent chat turns: the full tool-using turn and the simple no-tools variant.++use crate::agent::Agent;+use crate::config::Config;+use crate::inference::local as local_ai;+use crate::inference::provider as providers;+use crate::rpc::RpcOutcome;++use super::turn_guards::{+ effective_agent_chat_origin, enforce_user_prompt_or_reject, grant_turn_cwd,+ normalize_model_override, resolve_turn_cwd,+};++/// Executes a single chat turn with an AI agent.+///+/// This function initializes an agent from the provided configuration and+/// processes the input message.+///+/// # Arguments+///+/// * `config` - The configuration used to build the agent. May be updated with model/temp overrides.+/// * `message` - The user message to process.+/// * `model_override` - Optional model name to use for this call.+/// * `temperature` - Optional sampling temperature override.+/// * `cwd` - Optional per-turn working directory. When present and non-empty the+/// agent's filesystem / shell tools are rooted there for this turn only: a+/// relative path resolves inside it and an absolute path under it is+/// permitted. Absent or empty behaves exactly as before (the configured+/// `action_dir`). The override is applied to a *clone* of the config, so it+/// never leaks into concurrent turns the way a process-global would.+///+/// # Errors+///+/// Returns an error when the prompt is rejected by the injection guard, when+/// `cwd` names something that is not an accessible directory, or when building+/// or running the agent fails.+///+/// # Progress+///+/// If the caller scoped a+/// [`ProgressSink`](crate::agent::progress_sink::ProgressSink) around+/// the awaited future (see [`crate::agent_progress`]), it is attached to the+/// agent built here, so an in-process embedder observes the turn's tool calls+/// and deltas live instead of only its final string.+///+/// # Per-call inference route+///+/// `route` names an endpoint and bearer for this call alone. It is applied to+/// `config` in memory before the agent is built — including before the `cwd`+/// clone below, so a turn that is both rooted and routed gets both — and is+/// never persisted. See+/// [`ephemeral_route`](crate::config::schema::ephemeral_route).+pub async fn agent_chat(+ config: &mut Config,+ message: &str,+ model_override: Option<String>,+ temperature: Option<f64>,+ thread_id: Option<String>,+ cwd: Option<String>,+ route: Option<crate::config::schema::EphemeralRoute>,+) -> Result<RpcOutcome<String>, String> {+ enforce_user_prompt_or_reject(message, "local_ai.ops.agent_chat")?;++ // TAURI-RUST-RS: an upstream caller (frontend, JSON-RPC client) can pass+ // `model_override: Some("")`. See `normalize_model_override` for the+ // rationale — an empty / whitespace-only override collapses to `None`.+ if let Some(model) = normalize_model_override(model_override) {+ config.default_model = Some(model);+ }+ if let Some(temp) = temperature {+ config.default_temperature = temp;+ }+ // After the model override, because the route pins its roles to+ // `"<slug>:<model>"` and the model it uses is the one this call resolved.+ // Before the `cwd` clone below, so a rooted turn is routed too.+ if let Some(route) = route {+ crate::config::schema::ephemeral_route::apply(config, route);+ }+ let turn_cwd = resolve_turn_cwd(cwd)?;+ let mut agent = match turn_cwd.as_ref() {+ // Per-turn root. Building from a config clone whose `action_dir` is the+ // requested directory is what makes this a *turn-scoped* override: the+ // session's `SecurityPolicy`, its tool registry and the builder's+ // `action_dir` are all derived from that one field, so they agree, and+ // nothing process-global is mutated (unlike `live_policy::set_action_dir`,+ // which would race concurrent turns).+ Some(root) => {+ let mut scoped = config.clone();+ scoped.action_dir = root.clone();+ // `action_dir` alone is inert for access control — grant the same+ // root so the turn's tools may actually read and write in it.+ grant_turn_cwd(&mut scoped, root);+ log::debug!(+ "[inference] agent_chat rooting turn tools at cwd={}",+ root.display()+ );+ let mut agent = Agent::from_config(&scoped).map_err(|e| e.to_string())?;+ // Also thread it as the turn's workspace descriptor so acting tools+ // that read `ToolExecutionContext::workspace` (shell) resolve their+ // default cwd here, and so spawned sub-agents inherit the same root.+ agent.set_workspace_descriptor(Some(+ tinyagents_harness::workspace::WorkspaceDescriptor::new(root.clone()),+ ));+ agent+ }+ None => Agent::from_config(config).map_err(|e| e.to_string())?,+ };+ // Live progress for in-process embedders. `Agent::from_config` never+ // attaches a sink itself, so there is nothing to clobber here; callers that+ // set one explicitly (web chat, platform socket, flows, skills) hold their+ // own `Agent` and never reach this path — where both could apply, the+ // explicitly-set sink wins because it is applied to the agent it owns.+ if let Some(tx) = crate::agent::progress_sink::current_progress_sink() {+ agent.set_on_progress(Some(tx));+ }+ // Direct `agent_chat` RPC — invoked by trusted clients (desktop UI,+ // operator CLI). Label as CLI so the approval gate doesn't fail+ // closed on an unlabelled call site — *unless* the caller already scoped a+ // more specific origin around this dispatch, which an in-process embedder+ // can do (a workflow node labels its turn `TrustedAutomation::Workflow`).+ // Overwriting that with `Cli` would silently discard the caller's own+ // trust statement and hand every such turn the blanket CLI allowance+ // instead of the narrower one it asked for.+ let run = crate::agent::turn_origin::with_origin(+ effective_agent_chat_origin(),+ agent.run_single(message),+ );+ let response = match thread_id.as_deref() {+ Some(id) if !id.trim().is_empty() => {+ log::debug!("[inference] agent_chat routing with thread_id={id}");+ crate::agent::tinyagents::thread_context::with_thread_id(id, run).await+ }+ _ => {+ log::debug!("[inference] agent_chat routing without thread_id");+ run.await+ }+ }+ .map_err(|e| e.to_string())?;+ Ok(RpcOutcome::single_log(response, "agent chat completed"))+}++/// A simplified chat interface that does not update the base configuration.+pub async fn agent_chat_simple(+ config: &Config,+ message: &str,+ model_override: Option<String>,+ temperature: Option<f64>,+ thread_id: Option<String>,+) -> Result<RpcOutcome<String>, String> {+ enforce_user_prompt_or_reject(message, "local_ai.ops.agent_chat_simple")?;++ let mut effective = config.clone();+ // TAURI-RUST-RS: see `normalize_model_override` for the rationale.+ if let Some(model) = normalize_model_override(model_override) {+ effective.default_model = Some(model);+ }+ if let Some(temp) = temperature {+ effective.default_temperature = temp;+ }++ let default_model = effective+ .default_model+ .clone()+ .unwrap_or_else(|| crate::config::DEFAULT_MODEL.to_string());++ let (model, resolved_model) = providers::create_chat_model_with_model_id(+ "chat",+ &effective,+ effective.default_temperature,+ )+ .map_err(|e| e.to_string())?;+ tracing::debug!(+ requested_model = %default_model,+ resolved_model = %resolved_model,+ temperature = effective.default_temperature,+ "[inference] agent_chat_simple invoking crate-native chat model"+ );+ let run = model.invoke(+ &(),+ tinyinference::model::ModelRequest::new(vec![tinyinference::message::Message::user(+ message.to_string(),+ )])+ .with_model(default_model.clone())+ .with_temperature(effective.default_temperature),+ );+ let response = match thread_id.as_deref() {+ Some(id) if !id.trim().is_empty() => {+ log::debug!("[inference] agent_chat_simple routing with thread_id={id}");+ crate::agent::tinyagents::thread_context::with_thread_id(id, run).await+ }+ _ => {+ log::debug!("[inference] agent_chat_simple routing without thread_id");+ run.await+ }+ }+ .map_err(|e| e.to_string())?+ .text();++ Ok(RpcOutcome::single_log(+ response,+ "agent simple chat completed",+ ))+}diff --git a/crates/openhuman-core/src/inference/local/ops/chat.rs b/crates/openhuman-core/src/inference/local/ops/chat.rsnew file mode 100644index 0000000000..7e31c65088--- /dev/null+++ b/crates/openhuman-core/src/inference/local/ops/chat.rs@@ -0,0 +1,67 @@+//! Multi-turn chat through the local model.++use crate::config::Config;+use crate::inference::local as local_ai;+use crate::rpc::RpcOutcome;++use super::turn_guards::enforce_user_prompt_or_reject;++/// A single message in a local AI chat conversation.+#[derive(Debug, serde::Deserialize)]+pub struct LocalAiChatMessage {+ /// The role of the message sender (e.g., "user", "assistant").+ pub role: String,+ /// The text content of the message.+ pub content: String,+}++/// Executes a multi-turn chat conversation using the local model.+pub async fn local_ai_chat(+ config: &Config,+ messages: Vec<LocalAiChatMessage>,+ max_tokens: Option<u32>,+) -> Result<RpcOutcome<String>, String> {+ tracing::debug!(+ message_count = messages.len(),+ "[local_ai:chat] local_ai_chat op: validating"+ );++ if messages.is_empty() {+ return Err("messages must not be empty".to_string());+ }++ let mut ollama_messages: Vec<crate::inference::local::ollama::OllamaChatMessage> =+ Vec::with_capacity(messages.len());++ for msg in messages.into_iter() {+ let normalized_role = msg.role.trim().to_ascii_lowercase();+ match normalized_role.as_str() {+ "user" => {+ enforce_user_prompt_or_reject(msg.content.as_str(), "local_ai.ops.local_ai_chat")?;+ }+ "system" | "assistant" => {}+ _ => {+ return Err(format!(+ "unsupported message role: '{}'; expected one of: user, system, assistant",+ msg.role.trim()+ ));+ }+ }++ ollama_messages.push(crate::inference::local::ollama::OllamaChatMessage {+ role: normalized_role,+ content: msg.content,+ });+ }++ let service = local_ai::global(config);+ let reply = service+ .chat_with_history_interactive(config, ollama_messages, max_tokens)+ .await?;++ tracing::debug!(+ reply_len = reply.len(),+ "[local_ai:chat] local_ai_chat op: done"+ );+ Ok(RpcOutcome::single_log(reply, "local ai chat completed"))+}diff --git a/crates/openhuman-core/src/inference/local/ops_part_02.rs b/crates/openhuman-core/src/inference/local/ops/reactions.rssimilarity index 89%rename from crates/openhuman-core/src/inference/local/ops_part_02.rsrename to crates/openhuman-core/src/inference/local/ops/reactions.rsindex 952fddaa54..e2d964e54f 100644--- a/crates/openhuman-core/src/inference/local/ops_part_02.rs+++ b/crates/openhuman-core/src/inference/local/ops/reactions.rs@@ -1,3 +1,18 @@+//! The emoji reaction decision: asking the local model whether to react and+//! extracting the emoji it picked.++use crate::config::Config;+use crate::inference::local as local_ai;+use crate::rpc::RpcOutcome;++/// Result of the reaction-decision prompt.+#[derive(Debug, serde::Serialize)]+pub struct ReactionDecision {+ /// Whether the model thinks a reaction is appropriate.+ pub should_react: bool,+ /// The emoji to use (only meaningful when `should_react` is true).+ pub emoji: Option<String>,+}/// Evaluates whether the assistant should add an emoji reaction to a user message.///@@ -97,7 +112,7 @@ pub async fn local_ai_should_react(/// Extract the first emoji from a string. Handles common emoji codepoints/// including flag sequences (pairs of regional indicator symbols).-fn extract_first_emoji(text: &str) -> Option<String> {+pub(super) fn extract_first_emoji(text: &str) -> Option<String> {let mut chars = text.chars();while let Some(ch) = chars.next() {// Regional indicator pair → flag emoji (e.g. 🇺🇸 = U+1F1FA U+1F1F8)@@ -136,11 +151,11 @@ fn extract_first_emoji(text: &str) -> Option<String> {None}-fn is_regional_indicator(ch: char) -> bool {+pub(super) fn is_regional_indicator(ch: char) -> bool {('\u{1F1E6}'..='\u{1F1FF}').contains(&ch)}-fn is_emoji_start(ch: char) -> bool {+pub(super) fn is_emoji_start(ch: char) -> bool {matches!(ch,'\u{203C}' | '\u{2049}' // exclamation marks| '\u{2139}' // informationdiff --git a/crates/openhuman-core/src/inference/local/ops/runtime_ops.rs b/crates/openhuman-core/src/inference/local/ops/runtime_ops.rsnew file mode 100644index 0000000000..0b0f90149b--- /dev/null+++ b/crates/openhuman-core/src/inference/local/ops/runtime_ops.rs@@ -0,0 +1,239 @@+//! Operations over the local runtime: status, summarize, prompt, vision,+//! embeddings, transcription, speech, and model asset management.++use chrono::Utc;++use crate::config::Config;+use crate::inference::local as local_ai;+use crate::inference::provider as providers;+use crate::inference::{+ LocalAiAssetsStatus, LocalAiDownloadsProgress, LocalAiEmbeddingResult, LocalAiSpeechResult,+ LocalAiStatus, LocalAiTtsResult,+};+use crate::rpc::RpcOutcome;++use super::turn_guards::enforce_user_prompt_or_reject;++/// Returns the current operational status of the local AI stack.+pub async fn local_ai_status(config: &Config) -> Result<RpcOutcome<LocalAiStatus>, String> {+ let service = local_ai::global(config);+ let status = service.status();+ if matches!(status.state.as_str(), "idle" | "degraded") {+ let service_clone = service.clone();+ let config_clone = config.clone();+ tokio::spawn(async move {+ service_clone.bootstrap(&config_clone).await;+ });+ }+ // `LocalAiService` is a process-wide singleton whose cached `provider`+ // field was set at first init from whichever config it saw. After an+ // `inference_update_local_settings` call that swaps providers+ // (e.g. ollama → lm_studio) the cached value is stale, so we overlay+ // the current config's provider on the status snapshot before returning.+ let mut snapshot = service.status();+ snapshot.provider = local_ai::provider::provider_from_config(config)+ .as_str()+ .to_string();+ Ok(RpcOutcome::single_log(snapshot, "local ai status fetched"))+}++/// Generates a summary of the provided text using local AI models.+pub async fn local_ai_summarize(+ config: &Config,+ text: &str,+ max_tokens: Option<u32>,+) -> Result<RpcOutcome<String>, String> {+ enforce_user_prompt_or_reject(text.trim(), "local_ai.ops.local_ai_summarize")?;++ let service = local_ai::global(config);+ let status = service.status();+ if !matches!(status.state.as_str(), "ready") {+ service.bootstrap(config).await;+ }+ let summary = service+ .summarize_interactive(config, text, max_tokens)+ .await+ .map_err(|e| e.to_string())?;+ Ok(RpcOutcome::single_log(+ summary,+ "local ai summarize completed",+ ))+}++/// Executes a raw prompt directly against the local AI model.+pub async fn local_ai_prompt(+ config: &Config,+ prompt: &str,+ max_tokens: Option<u32>,+ no_think: Option<bool>,+) -> Result<RpcOutcome<String>, String> {+ enforce_user_prompt_or_reject(prompt.trim(), "local_ai.ops.local_ai_prompt")?;++ let service = local_ai::global(config);+ let status = service.status();+ if !matches!(status.state.as_str(), "ready") {+ service.bootstrap(config).await;+ }+ let output = service+ .prompt_interactive(config, prompt.trim(), max_tokens, no_think.unwrap_or(true))+ .await+ .map_err(|e| e.to_string())?;+ Ok(RpcOutcome::single_log(output, "local ai prompt completed"))+}++/// Executes a multimodal (vision) prompt with associated images.+pub async fn local_ai_vision_prompt(+ config: &Config,+ prompt: &str,+ image_refs: &[String],+ max_tokens: Option<u32>,+) -> Result<RpcOutcome<String>, String> {+ enforce_user_prompt_or_reject(prompt.trim(), "local_ai.ops.local_ai_vision_prompt")?;++ let service = local_ai::global(config);+ let output = service+ .vision_prompt(config, prompt.trim(), image_refs, max_tokens)+ .await+ .map_err(|e| e.to_string())?;+ Ok(RpcOutcome::single_log(+ output,+ "local ai vision prompt completed",+ ))+}++/// Generates semantic embeddings for the provided input strings.+pub async fn local_ai_embed(+ config: &Config,+ inputs: &[String],+) -> Result<RpcOutcome<LocalAiEmbeddingResult>, String> {+ let service = local_ai::global(config);+ let output = service+ .embed(config, inputs)+ .await+ .map_err(|e| e.to_string())?;+ Ok(RpcOutcome::single_log(+ output,+ "local ai embedding completed",+ ))+}++/// Transcribes the audio file at the specified path.+pub async fn local_ai_transcribe(+ config: &Config,+ audio_path: &str,+) -> Result<RpcOutcome<LocalAiSpeechResult>, String> {+ let service = local_ai::global(config);+ let output = service+ .transcribe(config, audio_path.trim())+ .await+ .map_err(|e| e.to_string())?;+ Ok(RpcOutcome::single_log(+ output,+ "local ai transcription completed",+ ))+}++/// Transcribes raw audio bytes by first saving them to a temporary file.+pub async fn local_ai_transcribe_bytes(+ config: &Config,+ audio_bytes: &[u8],+ extension: Option<String>,+) -> Result<RpcOutcome<LocalAiSpeechResult>, String> {+ let service = local_ai::global(config);++ let ext = extension+ .unwrap_or_else(|| "webm".to_string())+ .trim()+ .trim_start_matches('.')+ .to_ascii_lowercase();+ if ext.is_empty() || !ext.chars().all(|c| c.is_ascii_alphanumeric()) {+ return Err("Invalid audio extension".to_string());+ }++ let voice_dir = std::env::temp_dir().join("openhuman_voice_input");+ tokio::fs::create_dir_all(&voice_dir)+ .await+ .map_err(|e| format!("Failed to create voice input directory: {e}"))?;++ let filename = format!(+ "voice-{}-{}.{}",+ Utc::now().timestamp_millis(),+ uuid::Uuid::new_v4(),+ ext+ );+ let file_path = voice_dir.join(filename);+ tokio::fs::write(&file_path, audio_bytes)+ .await+ .map_err(|e| format!("Failed to write audio file: {e}"))?;++ let output = service+ .transcribe(config, file_path.to_string_lossy().as_ref())+ .await;+ let _ = tokio::fs::remove_file(&file_path).await;++ let output = output.map_err(|e| e.to_string())?;+ Ok(RpcOutcome::single_log(+ output,+ "local ai transcription completed",+ ))+}++/// Performs text-to-speech synthesis and optionally saves the result to a file.+pub async fn local_ai_tts(+ config: &Config,+ text: &str,+ output_path: Option<&str>,+) -> Result<RpcOutcome<LocalAiTtsResult>, String> {+ let service = local_ai::global(config);+ let output = service+ .tts(config, text.trim(), output_path)+ .await+ .map_err(|e| e.to_string())?;+ Ok(RpcOutcome::single_log(output, "local ai tts completed"))+}++/// Returns the status of all local AI assets (models and support files).+pub async fn local_ai_assets_status(+ config: &Config,+) -> Result<RpcOutcome<LocalAiAssetsStatus>, String> {+ let service = local_ai::global(config);+ let output = service+ .assets_status(config)+ .await+ .map_err(|e| e.to_string())?;+ Ok(RpcOutcome::single_log(+ output,+ "local ai assets status fetched",+ ))+}++/// Returns progress for any ongoing asset downloads.+pub async fn local_ai_downloads_progress(+ config: &Config,+) -> Result<RpcOutcome<LocalAiDownloadsProgress>, String> {+ let service = local_ai::global(config);+ let output = service+ .downloads_progress(config)+ .await+ .map_err(|e| e.to_string())?;+ Ok(RpcOutcome::single_log(+ output,+ "local ai downloads progress fetched",+ ))+}++/// Triggers the download of a specific AI asset based on capability name.+pub async fn local_ai_download_asset(+ config: &Config,+ capability: &str,+) -> Result<RpcOutcome<LocalAiAssetsStatus>, String> {+ let service = local_ai::global(config);+ let output = service+ .download_asset(config, capability.trim())+ .await+ .map_err(|e| e.to_string())?;+ Ok(RpcOutcome::single_log(+ output,+ "local ai asset download triggered",+ ))+}diff --git a/crates/openhuman-core/src/inference/local/ops/turn_guards.rs b/crates/openhuman-core/src/inference/local/ops/turn_guards.rsnew file mode 100644index 0000000000..3755cbfdbb--- /dev/null+++ b/crates/openhuman-core/src/inference/local/ops/turn_guards.rs@@ -0,0 +1,137 @@+//! Shared guards applied before a turn runs: prompt-injection enforcement,+//! model-override normalisation, working-directory resolution and grant, and+//! the origin label an agent chat runs under.++use crate::config::Config;+use crate::inference::local as local_ai;+use crate::security::prompt_injection::{+ enforce_prompt_input, PromptEnforcementAction, PromptEnforcementContext,+};++pub(super) fn prompt_guard_user_message(action: PromptEnforcementAction) -> &'static str {+ match action {+ PromptEnforcementAction::Allow => "Message accepted.",+ PromptEnforcementAction::Blocked => {+ "Prompt blocked by security policy. Please rephrase without instruction overrides or exfiltration requests."+ }+ PromptEnforcementAction::ReviewBlocked => {+ "Prompt flagged for security review and was not processed. Please rephrase clearly."+ }+ }+}++/// Normalize a `model_override` string into the `Option<String>` form the+/// downstream config-resolution path expects.+///+/// `None` → `None`. `Some(non-empty-after-trim)` → `Some(trimmed)`. Anything+/// else (`Some("")`, `Some(" ")`, `Some("\t\n")`) collapses to `None` so+/// the existing default-model fallback applies instead of overwriting+/// `config.default_model` with a blank string that the OpenHuman backend+/// would reject with `400 model is required` (Sentry TAURI-RUST-RS).+///+/// Extracted to keep `agent_chat` and `agent_chat_simple` in lockstep —+/// future tweaks (additional log lines, tightening the trim rules) live in+/// exactly one place.+pub(super) fn normalize_model_override(opt: Option<String>) -> Option<String> {+ opt.and_then(|m| {+ let t = m.trim();+ if t.is_empty() {+ None+ } else {+ Some(t.to_string())+ }+ })+}++pub(super) fn enforce_user_prompt_or_reject(+ prompt: &str,+ source: &'static str,+) -> Result<(), String> {+ let decision = enforce_prompt_input(+ prompt,+ PromptEnforcementContext {+ source,+ request_id: None,+ user_id: None,+ session_id: Some("local_ai"),+ },+ );+ match decision.action {+ PromptEnforcementAction::Allow => Ok(()),+ PromptEnforcementAction::Blocked | PromptEnforcementAction::ReviewBlocked => {+ Err(prompt_guard_user_message(decision.action).to_string())+ }+ }+}++/// Resolve the per-turn `cwd` parameter into the directory the turn's tools+/// should be rooted at.+///+/// `None` / empty / whitespace-only collapses to `None`, which keeps the turn on+/// the configured `action_dir` exactly as before. A present value must name an+/// existing directory: rooting an agent at a path that does not exist would give+/// it a cwd every shell and file call fails against, so this rejects loudly+/// instead. The path is canonicalized so symlinked and `..`-containing inputs+/// compare equal to the paths the security policy derives from it.+pub(super) fn resolve_turn_cwd(cwd: Option<String>) -> Result<Option<std::path::PathBuf>, String> {+ let Some(raw) = cwd else { return Ok(None) };+ let trimmed = raw.trim();+ if trimmed.is_empty() {+ return Ok(None);+ }+ let path = std::path::Path::new(trimmed);+ let canonical = std::fs::canonicalize(path)+ .map_err(|e| format!("cwd '{trimmed}' is not accessible: {e}"))?;+ if !canonical.is_dir() {+ return Err(format!("cwd '{trimmed}' is not a directory"));+ }+ Ok(Some(canonical))+}++/// Grant `root` as a `ReadWrite` trusted root on a per-turn config clone.+///+/// Setting `action_dir` alone only moves where a *relative* path resolves; the+/// allow/deny decision reads `workspace_dir` + `trusted_roots`, so without this+/// grant an absolute path in `root` is refused by `workspace_only` and a+/// relative one is refused as "escapes workspace". Idempotent: an entry the+/// user already configured for the same path is left untouched so a `Read`-only+/// grant is not silently widened by the presence of a `cwd`.+///+/// Only ever called on a *clone* of the config, on the `cwd`-present branch —+/// the no-`cwd` path is untouched, and nothing process-global is mutated.+pub(super) fn grant_turn_cwd(config: &mut Config, root: &std::path::Path) {+ let path = root.to_string_lossy().to_string();+ if config.autonomy.trusted_roots.iter().any(|r| r.path == path) {+ return;+ }+ config+ .autonomy+ .trusted_roots+ .push(crate::security::TrustedRoot {+ path,+ access: crate::security::TrustedAccess::ReadWrite,+ });+}++/// The origin label [`agent_chat`] scopes around its turn.+///+/// An ambient origin — scoped by an in-process embedder around its+/// `invoke("openhuman.inference_agent_chat", …)` — is the caller's own,+/// deliberate trust statement about the turn and is kept. Absent one,+/// [`AgentTurnOrigin::DirectChat`] applies: this RPC is reached by trusted+/// clients (the desktop Settings agent-chat panel, an operator running the RPC+/// by hand), and leaving it unlabelled would fail the approval gate closed on+/// every external-effect tool.+///+/// `DirectChat` rather than the historical `Cli`, and the difference is not+/// cosmetic. The approval gate treats the two identically, so trust is+/// unchanged — but `message` here is something a *person* typed, and `Cli`+/// answers "who wrote this" with a trust answer. Its own documentation covers+/// sub-agent and internal invocations, so+/// [`is_user_authored`](crate::agent::turn_origin::AgentTurnOrigin::is_user_authored)+/// reads `false` for it and the conversation autosave would silently drop a+/// real user message.+pub(super) fn effective_agent_chat_origin() -> crate::agent::turn_origin::AgentTurnOrigin {+ crate::agent::turn_origin::current()+ .unwrap_or(crate::agent::turn_origin::AgentTurnOrigin::DirectChat)+}diff --git a/crates/openhuman-core/src/inference/local/ops_part_01.rs b/crates/openhuman-core/src/inference/local/ops_part_01.rsdeleted file mode 100644index 56da1128f8..0000000000--- a/crates/openhuman-core/src/inference/local/ops_part_01.rs+++ /dev/null@@ -1,624 +0,0 @@-use chrono::Utc;--use crate::agent::Agent;-use crate::config::Config;-use crate::inference::local as local_ai;-use crate::inference::provider as providers;-use crate::inference::{- LocalAiAssetsStatus, LocalAiDownloadsProgress, LocalAiEmbeddingResult, LocalAiSpeechResult,- LocalAiStatus, LocalAiTtsResult,-};-use crate::security::prompt_injection::{- enforce_prompt_input, PromptEnforcementAction, PromptEnforcementContext,-};-use crate::rpc::RpcOutcome;--fn prompt_guard_user_message(action: PromptEnforcementAction) -> &'static str {- match action {- PromptEnforcementAction::Allow => "Message accepted.",- PromptEnforcementAction::Blocked => {- "Prompt blocked by security policy. Please rephrase without instruction overrides or exfiltration requests."- }- PromptEnforcementAction::ReviewBlocked => {- "Prompt flagged for security review and was not processed. Please rephrase clearly."- }- }-}--/// Normalize a `model_override` string into the `Option<String>` form the-/// downstream config-resolution path expects.-///-/// `None` → `None`. `Some(non-empty-after-trim)` → `Some(trimmed)`. Anything-/// else (`Some("")`, `Some(" ")`, `Some("\t\n")`) collapses to `None` so-/// the existing default-model fallback applies instead of overwriting-/// `config.default_model` with a blank string that the OpenHuman backend-/// would reject with `400 model is required` (Sentry TAURI-RUST-RS).-///-/// Extracted to keep `agent_chat` and `agent_chat_simple` in lockstep —-/// future tweaks (additional log lines, tightening the trim rules) live in-/// exactly one place.-fn normalize_model_override(opt: Option<String>) -> Option<String> {- opt.and_then(|m| {- let t = m.trim();- if t.is_empty() {- None- } else {- Some(t.to_string())- }- })-}--fn enforce_user_prompt_or_reject(prompt: &str, source: &'static str) -> Result<(), String> {- let decision = enforce_prompt_input(- prompt,- PromptEnforcementContext {- source,- request_id: None,- user_id: None,- session_id: Some("local_ai"),- },- );- match decision.action {- PromptEnforcementAction::Allow => Ok(()),- PromptEnforcementAction::Blocked | PromptEnforcementAction::ReviewBlocked => {- Err(prompt_guard_user_message(decision.action).to_string())- }- }-}--/// Resolve the per-turn `cwd` parameter into the directory the turn's tools-/// should be rooted at.-///-/// `None` / empty / whitespace-only collapses to `None`, which keeps the turn on-/// the configured `action_dir` exactly as before. A present value must name an-/// existing directory: rooting an agent at a path that does not exist would give-/// it a cwd every shell and file call fails against, so this rejects loudly-/// instead. The path is canonicalized so symlinked and `..`-containing inputs-/// compare equal to the paths the security policy derives from it.-fn resolve_turn_cwd(cwd: Option<String>) -> Result<Option<std::path::PathBuf>, String> {- let Some(raw) = cwd else { return Ok(None) };- let trimmed = raw.trim();- if trimmed.is_empty() {- return Ok(None);- }- let path = std::path::Path::new(trimmed);- let canonical = std::fs::canonicalize(path)- .map_err(|e| format!("cwd '{trimmed}' is not accessible: {e}"))?;- if !canonical.is_dir() {- return Err(format!("cwd '{trimmed}' is not a directory"));- }- Ok(Some(canonical))-}--/// Grant `root` as a `ReadWrite` trusted root on a per-turn config clone.-///-/// Setting `action_dir` alone only moves where a *relative* path resolves; the-/// allow/deny decision reads `workspace_dir` + `trusted_roots`, so without this-/// grant an absolute path in `root` is refused by `workspace_only` and a-/// relative one is refused as "escapes workspace". Idempotent: an entry the-/// user already configured for the same path is left untouched so a `Read`-only-/// grant is not silently widened by the presence of a `cwd`.-///-/// Only ever called on a *clone* of the config, on the `cwd`-present branch —-/// the no-`cwd` path is untouched, and nothing process-global is mutated.-fn grant_turn_cwd(config: &mut Config, root: &std::path::Path) {- let path = root.to_string_lossy().to_string();- if config.autonomy.trusted_roots.iter().any(|r| r.path == path) {- return;- }- config- .autonomy- .trusted_roots- .push(crate::security::TrustedRoot {- path,- access: crate::security::TrustedAccess::ReadWrite,- });-}--/// The origin label [`agent_chat`] scopes around its turn.-///-/// An ambient origin — scoped by an in-process embedder around its-/// `invoke("openhuman.inference_agent_chat", …)` — is the caller's own,-/// deliberate trust statement about the turn and is kept. Absent one,-/// [`AgentTurnOrigin::DirectChat`] applies: this RPC is reached by trusted-/// clients (the desktop Settings agent-chat panel, an operator running the RPC-/// by hand), and leaving it unlabelled would fail the approval gate closed on-/// every external-effect tool.-///-/// `DirectChat` rather than the historical `Cli`, and the difference is not-/// cosmetic. The approval gate treats the two identically, so trust is-/// unchanged — but `message` here is something a *person* typed, and `Cli`-/// answers "who wrote this" with a trust answer. Its own documentation covers-/// sub-agent and internal invocations, so-/// [`is_user_authored`](crate::agent::turn_origin::AgentTurnOrigin::is_user_authored)-/// reads `false` for it and the conversation autosave would silently drop a-/// real user message.-fn effective_agent_chat_origin() -> crate::agent::turn_origin::AgentTurnOrigin {- crate::agent::turn_origin::current()- .unwrap_or(crate::agent::turn_origin::AgentTurnOrigin::DirectChat)-}--/// Executes a single chat turn with an AI agent.-///-/// This function initializes an agent from the provided configuration and-/// processes the input message.-///-/// # Arguments-///-/// * `config` - The configuration used to build the agent. May be updated with model/temp overrides.-/// * `message` - The user message to process.-/// * `model_override` - Optional model name to use for this call.-/// * `temperature` - Optional sampling temperature override.-/// * `cwd` - Optional per-turn working directory. When present and non-empty the-/// agent's filesystem / shell tools are rooted there for this turn only: a-/// relative path resolves inside it and an absolute path under it is-/// permitted. Absent or empty behaves exactly as before (the configured-/// `action_dir`). The override is applied to a *clone* of the config, so it-/// never leaks into concurrent turns the way a process-global would.-///-/// # Errors-///-/// Returns an error when the prompt is rejected by the injection guard, when-/// `cwd` names something that is not an accessible directory, or when building-/// or running the agent fails.-///-/// # Progress-///-/// If the caller scoped a-/// [`ProgressSink`](crate::agent::progress_sink::ProgressSink) around-/// the awaited future (see [`crate::agent_progress`]), it is attached to the-/// agent built here, so an in-process embedder observes the turn's tool calls-/// and deltas live instead of only its final string.-///-/// # Per-call inference route-///-/// `route` names an endpoint and bearer for this call alone. It is applied to-/// `config` in memory before the agent is built — including before the `cwd`-/// clone below, so a turn that is both rooted and routed gets both — and is-/// never persisted. See-/// [`ephemeral_route`](crate::config::schema::ephemeral_route).-pub async fn agent_chat(- config: &mut Config,- message: &str,- model_override: Option<String>,- temperature: Option<f64>,- thread_id: Option<String>,- cwd: Option<String>,- route: Option<crate::config::schema::EphemeralRoute>,-) -> Result<RpcOutcome<String>, String> {- enforce_user_prompt_or_reject(message, "local_ai.ops.agent_chat")?;-- // TAURI-RUST-RS: an upstream caller (frontend, JSON-RPC client) can pass- // `model_override: Some("")`. See `normalize_model_override` for the- // rationale — an empty / whitespace-only override collapses to `None`.- if let Some(model) = normalize_model_override(model_override) {- config.default_model = Some(model);- }- if let Some(temp) = temperature {- config.default_temperature = temp;- }- // After the model override, because the route pins its roles to- // `"<slug>:<model>"` and the model it uses is the one this call resolved.- // Before the `cwd` clone below, so a rooted turn is routed too.- if let Some(route) = route {- crate::config::schema::ephemeral_route::apply(config, route);- }- let turn_cwd = resolve_turn_cwd(cwd)?;- let mut agent = match turn_cwd.as_ref() {- // Per-turn root. Building from a config clone whose `action_dir` is the- // requested directory is what makes this a *turn-scoped* override: the- // session's `SecurityPolicy`, its tool registry and the builder's- // `action_dir` are all derived from that one field, so they agree, and- // nothing process-global is mutated (unlike `live_policy::set_action_dir`,- // which would race concurrent turns).- Some(root) => {- let mut scoped = config.clone();- scoped.action_dir = root.clone();- // `action_dir` alone is inert for access control — grant the same- // root so the turn's tools may actually read and write in it.- grant_turn_cwd(&mut scoped, root);- log::debug!(- "[inference] agent_chat rooting turn tools at cwd={}",- root.display()- );- let mut agent = Agent::from_config(&scoped).map_err(|e| e.to_string())?;- // Also thread it as the turn's workspace descriptor so acting tools- // that read `ToolExecutionContext::workspace` (shell) resolve their- // default cwd here, and so spawned sub-agents inherit the same root.- agent.set_workspace_descriptor(Some(- tinyagents_harness::workspace::WorkspaceDescriptor::new(root.clone()),- ));- agent- }- None => Agent::from_config(config).map_err(|e| e.to_string())?,- };- // Live progress for in-process embedders. `Agent::from_config` never- // attaches a sink itself, so there is nothing to clobber here; callers that- // set one explicitly (web chat, platform socket, flows, skills) hold their- // own `Agent` and never reach this path — where both could apply, the- // explicitly-set sink wins because it is applied to the agent it owns.- if let Some(tx) = crate::agent::progress_sink::current_progress_sink() {- agent.set_on_progress(Some(tx));- }- // Direct `agent_chat` RPC — invoked by trusted clients (desktop UI,- // operator CLI). Label as CLI so the approval gate doesn't fail- // closed on an unlabelled call site — *unless* the caller already scoped a- // more specific origin around this dispatch, which an in-process embedder- // can do (a workflow node labels its turn `TrustedAutomation::Workflow`).- // Overwriting that with `Cli` would silently discard the caller's own- // trust statement and hand every such turn the blanket CLI allowance- // instead of the narrower one it asked for.- let run = crate::agent::turn_origin::with_origin(- effective_agent_chat_origin(),- agent.run_single(message),- );- let response = match thread_id.as_deref() {- Some(id) if !id.trim().is_empty() => {- log::debug!("[inference] agent_chat routing with thread_id={id}");- crate::agent::tinyagents::thread_context::with_thread_id(id, run).await- }- _ => {- log::debug!("[inference] agent_chat routing without thread_id");- run.await- }- }- .map_err(|e| e.to_string())?;- Ok(RpcOutcome::single_log(response, "agent chat completed"))-}--/// A simplified chat interface that does not update the base configuration.-pub async fn agent_chat_simple(- config: &Config,- message: &str,- model_override: Option<String>,- temperature: Option<f64>,- thread_id: Option<String>,-) -> Result<RpcOutcome<String>, String> {- enforce_user_prompt_or_reject(message, "local_ai.ops.agent_chat_simple")?;-- let mut effective = config.clone();- // TAURI-RUST-RS: see `normalize_model_override` for the rationale.- if let Some(model) = normalize_model_override(model_override) {- effective.default_model = Some(model);- }- if let Some(temp) = temperature {- effective.default_temperature = temp;- }-- let default_model = effective- .default_model- .clone()- .unwrap_or_else(|| crate::config::DEFAULT_MODEL.to_string());-- let (model, resolved_model) = providers::create_chat_model_with_model_id(- "chat",- &effective,- effective.default_temperature,- )- .map_err(|e| e.to_string())?;- tracing::debug!(- requested_model = %default_model,- resolved_model = %resolved_model,- temperature = effective.default_temperature,- "[inference] agent_chat_simple invoking crate-native chat model"- );- let run = model.invoke(- &(),- tinyinference::model::ModelRequest::new(vec![- tinyinference::message::Message::user(message.to_string()),- ])- .with_model(default_model.clone())- .with_temperature(effective.default_temperature),- );- let response = match thread_id.as_deref() {- Some(id) if !id.trim().is_empty() => {- log::debug!("[inference] agent_chat_simple routing with thread_id={id}");- crate::agent::tinyagents::thread_context::with_thread_id(id, run).await- }- _ => {- log::debug!("[inference] agent_chat_simple routing without thread_id");- run.await- }- }- .map_err(|e| e.to_string())?- .text();-- Ok(RpcOutcome::single_log(- response,- "agent simple chat completed",- ))-}--/// Returns the current operational status of the local AI stack.-pub async fn local_ai_status(config: &Config) -> Result<RpcOutcome<LocalAiStatus>, String> {- let service = local_ai::global(config);- let status = service.status();- if matches!(status.state.as_str(), "idle" | "degraded") {- let service_clone = service.clone();- let config_clone = config.clone();- tokio::spawn(async move {- service_clone.bootstrap(&config_clone).await;- });- }- // `LocalAiService` is a process-wide singleton whose cached `provider`- // field was set at first init from whichever config it saw. After an- // `inference_update_local_settings` call that swaps providers- // (e.g. ollama → lm_studio) the cached value is stale, so we overlay- // the current config's provider on the status snapshot before returning.- let mut snapshot = service.status();- snapshot.provider = local_ai::provider::provider_from_config(config)- .as_str()- .to_string();- Ok(RpcOutcome::single_log(snapshot, "local ai status fetched"))-}--/// Generates a summary of the provided text using local AI models.-pub async fn local_ai_summarize(- config: &Config,- text: &str,- max_tokens: Option<u32>,-) -> Result<RpcOutcome<String>, String> {- enforce_user_prompt_or_reject(text.trim(), "local_ai.ops.local_ai_summarize")?;-- let service = local_ai::global(config);- let status = service.status();- if !matches!(status.state.as_str(), "ready") {- service.bootstrap(config).await;- }- let summary = service- .summarize_interactive(config, text, max_tokens)- .await- .map_err(|e| e.to_string())?;- Ok(RpcOutcome::single_log(- summary,- "local ai summarize completed",- ))-}--/// Executes a raw prompt directly against the local AI model.-pub async fn local_ai_prompt(- config: &Config,- prompt: &str,- max_tokens: Option<u32>,- no_think: Option<bool>,-) -> Result<RpcOutcome<String>, String> {- enforce_user_prompt_or_reject(prompt.trim(), "local_ai.ops.local_ai_prompt")?;-- let service = local_ai::global(config);- let status = service.status();- if !matches!(status.state.as_str(), "ready") {- service.bootstrap(config).await;- }- let output = service- .prompt_interactive(config, prompt.trim(), max_tokens, no_think.unwrap_or(true))- .await- .map_err(|e| e.to_string())?;- Ok(RpcOutcome::single_log(output, "local ai prompt completed"))-}--/// Executes a multimodal (vision) prompt with associated images.-pub async fn local_ai_vision_prompt(- config: &Config,- prompt: &str,- image_refs: &[String],- max_tokens: Option<u32>,-) -> Result<RpcOutcome<String>, String> {- enforce_user_prompt_or_reject(prompt.trim(), "local_ai.ops.local_ai_vision_prompt")?;-- let service = local_ai::global(config);- let output = service- .vision_prompt(config, prompt.trim(), image_refs, max_tokens)- .await- .map_err(|e| e.to_string())?;- Ok(RpcOutcome::single_log(- output,- "local ai vision prompt completed",- ))-}--/// Generates semantic embeddings for the provided input strings.-pub async fn local_ai_embed(- config: &Config,- inputs: &[String],-) -> Result<RpcOutcome<LocalAiEmbeddingResult>, String> {- let service = local_ai::global(config);- let output = service- .embed(config, inputs)- .await- .map_err(|e| e.to_string())?;- Ok(RpcOutcome::single_log(- output,- "local ai embedding completed",- ))-}--/// Transcribes the audio file at the specified path.-pub async fn local_ai_transcribe(- config: &Config,- audio_path: &str,-) -> Result<RpcOutcome<LocalAiSpeechResult>, String> {- let service = local_ai::global(config);- let output = service- .transcribe(config, audio_path.trim())- .await- .map_err(|e| e.to_string())?;- Ok(RpcOutcome::single_log(- output,- "local ai transcription completed",- ))-}--/// Transcribes raw audio bytes by first saving them to a temporary file.-pub async fn local_ai_transcribe_bytes(- config: &Config,- audio_bytes: &[u8],- extension: Option<String>,-) -> Result<RpcOutcome<LocalAiSpeechResult>, String> {- let service = local_ai::global(config);-- let ext = extension- .unwrap_or_else(|| "webm".to_string())- .trim()- .trim_start_matches('.')- .to_ascii_lowercase();- if ext.is_empty() || !ext.chars().all(|c| c.is_ascii_alphanumeric()) {- return Err("Invalid audio extension".to_string());- }-- let voice_dir = std::env::temp_dir().join("openhuman_voice_input");- tokio::fs::create_dir_all(&voice_dir)- .await- .map_err(|e| format!("Failed to create voice input directory: {e}"))?;-- let filename = format!(- "voice-{}-{}.{}",- Utc::now().timestamp_millis(),- uuid::Uuid::new_v4(),- ext- );- let file_path = voice_dir.join(filename);- tokio::fs::write(&file_path, audio_bytes)- .await- .map_err(|e| format!("Failed to write audio file: {e}"))?;-- let output = service- .transcribe(config, file_path.to_string_lossy().as_ref())- .await;- let _ = tokio::fs::remove_file(&file_path).await;-- let output = output.map_err(|e| e.to_string())?;- Ok(RpcOutcome::single_log(- output,- "local ai transcription completed",- ))-}--/// Performs text-to-speech synthesis and optionally saves the result to a file.-pub async fn local_ai_tts(- config: &Config,- text: &str,- output_path: Option<&str>,-) -> Result<RpcOutcome<LocalAiTtsResult>, String> {- let service = local_ai::global(config);- let output = service- .tts(config, text.trim(), output_path)- .await- .map_err(|e| e.to_string())?;- Ok(RpcOutcome::single_log(output, "local ai tts completed"))-}--/// Returns the status of all local AI assets (models and support files).-pub async fn local_ai_assets_status(- config: &Config,-) -> Result<RpcOutcome<LocalAiAssetsStatus>, String> {- let service = local_ai::global(config);- let output = service- .assets_status(config)- .await- .map_err(|e| e.to_string())?;- Ok(RpcOutcome::single_log(- output,- "local ai assets status fetched",- ))-}--/// Returns progress for any ongoing asset downloads.-pub async fn local_ai_downloads_progress(- config: &Config,-) -> Result<RpcOutcome<LocalAiDownloadsProgress>, String> {- let service = local_ai::global(config);- let output = service- .downloads_progress(config)- .await- .map_err(|e| e.to_string())?;- Ok(RpcOutcome::single_log(- output,- "local ai downloads progress fetched",- ))-}--/// Triggers the download of a specific AI asset based on capability name.-pub async fn local_ai_download_asset(- config: &Config,- capability: &str,-) -> Result<RpcOutcome<LocalAiAssetsStatus>, String> {- let service = local_ai::global(config);- let output = service- .download_asset(config, capability.trim())- .await- .map_err(|e| e.to_string())?;- Ok(RpcOutcome::single_log(- output,- "local ai asset download triggered",- ))-}--/// A single message in a local AI chat conversation.-#[derive(Debug, serde::Deserialize)]-pub struct LocalAiChatMessage {- /// The role of the message sender (e.g., "user", "assistant").- pub role: String,- /// The text content of the message.- pub content: String,-}--/// Executes a multi-turn chat conversation using the local model.-pub async fn local_ai_chat(- config: &Config,- messages: Vec<LocalAiChatMessage>,- max_tokens: Option<u32>,-) -> Result<RpcOutcome<String>, String> {- tracing::debug!(- message_count = messages.len(),- "[local_ai:chat] local_ai_chat op: validating"- );-- if messages.is_empty() {- return Err("messages must not be empty".to_string());- }-- let mut ollama_messages: Vec<crate::inference::local::ollama::OllamaChatMessage> =- Vec::with_capacity(messages.len());-- for msg in messages.into_iter() {- let normalized_role = msg.role.trim().to_ascii_lowercase();- match normalized_role.as_str() {- "user" => {- enforce_user_prompt_or_reject(msg.content.as_str(), "local_ai.ops.local_ai_chat")?;- }- "system" | "assistant" => {}- _ => {- return Err(format!(- "unsupported message role: '{}'; expected one of: user, system, assistant",- msg.role.trim()- ));- }- }-- ollama_messages.push(- crate::inference::local::ollama::OllamaChatMessage {- role: normalized_role,- content: msg.content,- },- );- }-- let service = local_ai::global(config);- let reply = service- .chat_with_history_interactive(config, ollama_messages, max_tokens)- .await?;-- tracing::debug!(- reply_len = reply.len(),- "[local_ai:chat] local_ai_chat op: done"- );- Ok(RpcOutcome::single_log(reply, "local ai chat completed"))-}-/// Result of the reaction-decision prompt.-#[derive(Debug, serde::Serialize)]-pub struct ReactionDecision {- /// Whether the model thinks a reaction is appropriate.- pub should_react: bool,- /// The emoji to use (only meaningful when `should_react` is true).- pub emoji: Option<String>,-}