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
refactor(flows): serve copilot tools from the compiled module
Steven Enamakel762428293d63
diff --git a/crates/openhuman-core/src/flows/builder_tools_support.rs b/crates/openhuman-core/src/flows/builder_tools_support.rsindex fd82cd8f24..fe62faf96f 100644--- a/crates/openhuman-core/src/flows/builder_tools_support.rs+++ b/crates/openhuman-core/src/flows/builder_tools_support.rs@@ -1,83 +1,70 @@-//! Test constructors for the copilot tool belt bound to this host.-//!-//! The tools are defined in `tinyflows_copilot::tools` and take ports; these-//! build them over [`FlowsHost`] for a given config, the way-//! [`registration`](super::super::registration) does, so the composition tests-//! exercise the real draft/flow stores and gate stack.+//! Test constructors for the Copilot tools served by the compiled module.use std::sync::Arc;-use tinyflows_copilot::tools::{- CancelFlowRunTool, CreateWorkflowTool, DryRunWorkflowTool, DuplicateFlowTool, EditWorkflowTool,- GetFlowRunTool, GetFlowTool, GetNodeKindContractTool, ListFlowRunsTool, ListFlowsTool,- ListNodeKindsTool, ResumeFlowRunTool, ReviseWorkflowTool, SaveWorkflowTool,- ValidateWorkflowTool,-};-use crate::config::Config;-use crate::flows::builder_host::{FlowsHost, OverlayNodeKinds};+use crate::flows::copilot_bus::BusCopilotTool;++fn tool(config: Arc<Config>, name: &str) -> BusCopilotTool {+ BusCopilotTool::from_name(config, name)+}-pub(crate) fn edit_workflow_tool(config: Arc<Config>) -> EditWorkflowTool {- let h = FlowsHost::new(config);- EditWorkflowTool::new(h.clone(), h.clone(), h)+pub(crate) fn edit_workflow_tool(config: Arc<Config>) -> BusCopilotTool {+ tool(config, "edit_workflow")}-pub(crate) fn save_workflow_tool(config: Arc<Config>) -> SaveWorkflowTool {- let h = FlowsHost::new(config);- SaveWorkflowTool::new(h.clone(), h.clone(), h)+pub(crate) fn save_workflow_tool(config: Arc<Config>) -> BusCopilotTool {+ tool(config, "save_workflow")}-pub(crate) fn dry_run_workflow_tool(config: Arc<Config>) -> DryRunWorkflowTool {- let h = FlowsHost::new(config);- DryRunWorkflowTool::new(h.clone(), h.clone(), h)+pub(crate) fn dry_run_workflow_tool(config: Arc<Config>) -> BusCopilotTool {+ tool(config, "dry_run_workflow")}-pub(crate) fn validate_workflow_tool(config: Arc<Config>) -> ValidateWorkflowTool {- let h = FlowsHost::new(config);- ValidateWorkflowTool::new(h.clone(), h.clone(), h)+pub(crate) fn validate_workflow_tool(config: Arc<Config>) -> BusCopilotTool {+ tool(config, "validate_workflow")}-pub(crate) fn revise_workflow_tool(config: Arc<Config>) -> ReviseWorkflowTool {- ReviseWorkflowTool::new(FlowsHost::new(config))+pub(crate) fn revise_workflow_tool(config: Arc<Config>) -> BusCopilotTool {+ tool(config, "revise_workflow")}-pub(crate) fn create_workflow_tool(config: Arc<Config>) -> CreateWorkflowTool {- let h = FlowsHost::new(config);- CreateWorkflowTool::new(h.clone(), h)+pub(crate) fn create_workflow_tool(config: Arc<Config>) -> BusCopilotTool {+ tool(config, "create_workflow")}-pub(crate) fn duplicate_flow_tool(config: Arc<Config>) -> DuplicateFlowTool {- DuplicateFlowTool::new(FlowsHost::new(config))+pub(crate) fn duplicate_flow_tool(config: Arc<Config>) -> BusCopilotTool {+ tool(config, "duplicate_flow")}-pub(crate) fn list_flow_runs_tool(config: Arc<Config>) -> ListFlowRunsTool {- ListFlowRunsTool::new(FlowsHost::new(config))+pub(crate) fn list_flow_runs_tool(config: Arc<Config>) -> BusCopilotTool {+ tool(config, "list_flow_runs")}-pub(crate) fn cancel_flow_run_tool(config: Arc<Config>) -> CancelFlowRunTool {- CancelFlowRunTool::new(FlowsHost::new(config))+pub(crate) fn cancel_flow_run_tool(config: Arc<Config>) -> BusCopilotTool {+ tool(config, "cancel_flow_run")}-pub(crate) fn resume_flow_run_tool(config: Arc<Config>) -> ResumeFlowRunTool {- ResumeFlowRunTool::new(FlowsHost::new(config))+pub(crate) fn resume_flow_run_tool(config: Arc<Config>) -> BusCopilotTool {+ tool(config, "resume_flow_run")}-pub(crate) fn get_flow_tool(config: Arc<Config>) -> GetFlowTool {- GetFlowTool::new(FlowsHost::new(config))+pub(crate) fn get_flow_tool(config: Arc<Config>) -> BusCopilotTool {+ tool(config, "get_flow")}-pub(crate) fn list_flows_tool(config: Arc<Config>) -> ListFlowsTool {- ListFlowsTool::new(FlowsHost::new(config))+pub(crate) fn list_flows_tool(config: Arc<Config>) -> BusCopilotTool {+ tool(config, "list_flows")}-pub(crate) fn get_flow_run_tool(config: Arc<Config>) -> GetFlowRunTool {- GetFlowRunTool::new(FlowsHost::new(config))+pub(crate) fn get_flow_run_tool(config: Arc<Config>) -> BusCopilotTool {+ tool(config, "get_flow_run")}-pub(crate) fn list_node_kinds_tool() -> ListNodeKindsTool {- ListNodeKindsTool::new(Arc::new(OverlayNodeKinds))+pub(crate) fn list_node_kinds_tool(config: Arc<Config>) -> BusCopilotTool {+ tool(config, "list_node_kinds")}-pub(crate) fn get_node_kind_contract_tool() -> GetNodeKindContractTool {- GetNodeKindContractTool::new(Arc::new(OverlayNodeKinds))+pub(crate) fn get_node_kind_contract_tool(config: Arc<Config>) -> BusCopilotTool {+ tool(config, "get_node_kind_contract")}diff --git a/crates/openhuman-core/src/flows/mod.rs b/crates/openhuman-core/src/flows/mod.rsindex b85051b6c3..6e69dbba76 100644--- a/crates/openhuman-core/src/flows/mod.rs+++ b/crates/openhuman-core/src/flows/mod.rs@@ -26,6 +26,7 @@mod agent_route;pub mod agents;pub mod builder_host;+mod copilot_bus;pub(crate) mod builder_tools;mod builder_tools_connection_reads;pub mod bus;@@ -43,7 +44,6 @@ pub mod skills;mod store;/// The tinyflows engine seam (formerly `crate::tinyflows`).pub mod tinyflows;-pub mod tools;// Portable catalog vocabulary is imported directly from `tinyflows-catalog`.diff --git a/crates/openhuman-core/src/flows/parameters/propose_workflow.json b/crates/openhuman-core/src/flows/parameters/propose_workflow.jsondeleted file mode 100644index 614b505374..0000000000--- a/crates/openhuman-core/src/flows/parameters/propose_workflow.json+++ /dev/null@@ -1,104 +0,0 @@-{- "type": "object",- "properties": {- "name": {- "type": "string",- "description": "Human-readable name for the proposed flow."- },- "graph": {- "type": "object",- "description": "A tinyflows WorkflowGraph: { name?, nodes: [...], edges: [...] }. See the tool description for node kinds and their config shapes.",- "properties": {- "nodes": {- "type": "array",- "items": {- "type": "object",- "properties": {- "id": {- "type": "string",- "description": "Unique id within the graph."- },- "kind": {- "type": "string",- "enum": [- "trigger",- "agent",- "tool_call",- "http_request",- "code",- "shell",- "condition",- "switch",- "merge",- "split_out",- "transform",- "output_parser",- "sub_workflow",- "memory",- "dedup",- "loop",- "spawn",- "gate",- "scatter",- "gather",- "approval",- "void"- ]- },- "name": {- "type": "string",- "description": "Human-readable node name."- },- "config": {- "description": "Kind-specific configuration; see tool description."- }- },- "required": [- "id",- "kind",- "name"- ]- }- },- "edges": {- "type": "array",- "items": {- "type": "object",- "properties": {- "from_node": {- "type": "string"- },- "to_node": {- "type": "string"- },- "from_port": {- "type": "string",- "description": "Defaults to \"main\". For a condition/switch branch, this is where the branch label (e.g. \"true\"/\"false\") goes."- },- "to_port": {- "type": "string",- "description": "Defaults to \"main\". Almost always stays \"main\" — branch labels go on from_port, not here."- }- },- "required": [- "from_node",- "to_node"- ]- }- }- },- "required": [- "nodes",- "edges"- ]- },- "require_approval": {- "type": "boolean",- "description": "Force a human-approval gate on every outbound tool/HTTP action this flow takes once saved. Defaults to true for agent-proposed flows."- }- },- "required": [- "name",- "graph"- ]-}diff --git a/crates/openhuman-core/src/flows/registration.rs b/crates/openhuman-core/src/flows/registration.rsindex 4f37df301b..db99797eda 100644--- a/crates/openhuman-core/src/flows/registration.rs+++ b/crates/openhuman-core/src/flows/registration.rs@@ -68,6 +68,16 @@ pub(crate) fn tools(config: Arc<Config>, security: &Arc<SecurityPolicy>) -> Vec<for name in ["list_agent_definitions",+ ] {+ push_copilot_tool(&mut tools, copilot.as_ref(), name);+ }+ tools.push(Box::new(+ crate::integrations::composio::builder_tools::ListConnectableToolkitsTool::new(+ config.clone(),+ Arc::new(FlowsConnectionProvider),+ ),+ ));+ for name in ["list_node_kinds","get_node_kind_contract","dry_run_workflow",diff --git a/crates/openhuman-core/src/flows/tools.rs b/crates/openhuman-core/src/flows/tools.rsdeleted file mode 100644index 287b1a0f3d..0000000000--- a/crates/openhuman-core/src/flows/tools.rs+++ /dev/null@@ -1,374 +0,0 @@-//! Agent-facing tool for the `flows::` domain (issue B4 — agent-first-//! Workflow authoring): [`ProposeWorkflowTool`] ("propose_workflow").-//!-//! The user asks the assistant in chat to build an automation; the agent-//! calls this tool with a candidate `tinyflows::model::WorkflowGraph`. The-//! tool runs the graph through the exact same-//! [`tinyflows::authoring::validate_and_migrate_graph`] path-//! `flows_create` uses, and returns a `workflow_proposal` summary for the-//! chat UI's `WorkflowProposalCard` — it never persists anything itself.-//!-//! **Human-in-the-loop invariant:** this tool must NEVER call-//! [`crate::flows::ops::flows_create`] (or any other persistence-//! path). Only the user's "Save & enable" click in `WorkflowProposalCard`-//! creates the flow, via the `openhuman.flows_create` RPC directly from the-//! client. `permission_level() == PermissionLevel::None` and-//! `external_effect() == false` reflect that this call has no side effect —-//! it is pure validation.--use crate::tools::schema_cache::static_schema;-use std::sync::Arc;--use async_trait::async_trait;-use serde_json::{json, Value};--use crate::config::Config;-use crate::flows::ops::build_builder_proposal;-use tinyflows::authoring::validate_and_migrate_graph;-use tinytools::{PermissionLevel, Tool, ToolResult};--pub struct ProposeWorkflowTool {- config: Arc<Config>,-}--impl ProposeWorkflowTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}--#[async_trait]-impl Tool for ProposeWorkflowTool {- fn name(&self) -> &str {- "propose_workflow"- }-- fn description(&self) -> &str {- // Generated once, not hand-written.- //- // This description used to carry a 5,841-byte copy of the node-kind- // reference: every kind, its required *and* optional config, and a- // paragraph of gotchas each. That is the third copy of the same- // material — `get_node_kind_contract` serves it authoritatively and- // `workflow_builder`'s prompt carries an index — and it shipped on- // every request of every agent holding this tool.- //- // `tinyflows::catalog::render_node_kinds_required` reduces it to the one thing a caller- // cannot recover from a failed call: which kinds exist and what config- // each cannot be built without (401 bytes). Everything else is one- // `get_node_kind_contract { kind }` away.- //- // Generating it also retires a drift class rather than testing for it.- // `propose_workflow_description_matches_typed_node_contracts` existed- // because a hand-written copy could fall behind `node_contracts.rs`;- // it now passes by construction, and stays as the regression guard for- // anyone tempted to hand-write this again.- static DESCRIPTION: std::sync::OnceLock<String> = std::sync::OnceLock::new();- DESCRIPTION- .get_or_init(|| {- format!(- "Propose a candidate automation workflow for the user to review and save. \- This tool ONLY VALIDATES the graph and returns a summary — it NEVER creates \- or enables the flow; the user must click \"Save & enable\" in the UI before \- anything is persisted or can run. If validation fails, fix the graph and call \- this tool again.\n\- \n\- Build a tinyflows WorkflowGraph: nodes[] ({{id, kind, name, config}}) + \- edges[] ({{from_node, to_node, from_port?, to_port?}}; ports default \- \"main\"). Exactly ONE trigger node is required.\n\- \n\- Branching (condition/switch): the branch label goes on from_port, NEVER on \- to_port (which stays \"main\"). Routing is keyed exclusively on from_port, so \- a label on to_port silently turns the branch into an unconditional fan-out \- and is a hard reject.\n\- \n\- A memory node may only target config.scope \"flow\" for remember/forget; \- \"user\" is READ-ONLY and a write to it is a hard reject.\n\- \n\- Node kinds and their required config: {kinds}.\n\- Call `get_node_kind_contract {{ kind }}` for a kind's optional fields, ports, \- a worked example, and its gotchas — it is generated from the catalog the \- validator enforces, so it is always current.",- kinds = tinyflows::catalog::render_node_kinds_required(- &crate::flows::all_node_kind_contracts()- )- )- })- .as_str()- }-- fn parameters_schema(&self) -> Value {- static_schema!(include_str!("parameters/propose_workflow.json"))- }-- fn permission_level(&self) -> PermissionLevel {- // Pure validation with no side effect — see module doc.- PermissionLevel::None- }-- fn external_effect(&self) -> bool {- // Never persists or executes anything; only `flows_create` (invoked- // from the client by the user's own "Save & enable" click) does.- false- }-- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {- self.execute_with_context(args, tinytools::ToolCallOptions::default(), None)- .await- }-- async fn execute_with_context(- &self,- args: Value,- _options: tinytools::ToolCallOptions,- tool_context: Option<&dyn tinytools::ToolRunContext>,- ) -> anyhow::Result<ToolResult> {- let ctx = crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(tool_context);- let name = match args.get("name").and_then(Value::as_str).map(str::trim) {- Some(name) if !name.is_empty() => name.to_string(),- _ => return Ok(ToolResult::error("Missing 'name' parameter".to_string())),- };-- let graph_json = match args.get("graph") {- Some(v) if !v.is_null() => v.clone(),- _ => return Ok(ToolResult::error("Missing 'graph' parameter".to_string())),- };-- let require_approval = args- .get("require_approval")- .and_then(Value::as_bool)- .unwrap_or(true);-- tracing::debug!(- target: "flows",- %name,- require_approval,- workspace = %self.config.workspace_dir.display(),- "[flows] propose_workflow: validating candidate graph"- );-- let graph = match validate_and_migrate_graph(graph_json) {- Ok(graph) => graph,- Err(e) => {- tracing::debug!(- target: "flows",- %name,- error = %e,- "[flows] propose_workflow: validation failed"- );- return Ok(ToolResult::error(format!(- "Workflow graph is invalid: {e}. Fix the graph and call propose_workflow \- again."- )));- }- };-- // Route every first proposal through the same canonical hard-gate and- // payload builder as revise/edit/save. In particular, this includes- // compatibility checks for literal workflow_id children, which cannot- // be detected by graph-only validation because they require the store.- match build_builder_proposal(- &ctx,- &self.config,- "propose_workflow",- &name,- &graph,- require_approval,- false,- None,- None,- None,- )- .await- {- Ok(payload) => Ok(ToolResult::success(serde_json::to_string_pretty(&payload)?)),- Err(error) => {- tracing::debug!(- target: "flows",- %name,- %error,- "[flows] propose_workflow: builder gate rejected the graph"- );- Ok(ToolResult::error(error))- }- }- }-}--/// Runs a **saved** workflow by id so the `workflow-builder` agent can *test*-/// it end-to-end. Unlike `tinyflows_copilot::tools::DryRunWorkflowTool`-/// (a MOCK sandbox), this is a **real** run — so it is `PermissionLevel::Write`-/// with `external_effect() == true`. Two safety layers remain: the flow's own-/// `require_approval` gate still pauses outbound-action nodes mid-run, and the-/// agent prompt requires it to ASK THE USER for confirmation before ever-/// calling this. It only runs an already-persisted flow (no `flow_id`, no run).-pub struct RunFlowTool {- config: Arc<Config>,-}--impl RunFlowTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}--#[async_trait]-impl Tool for RunFlowTool {- fn name(&self) -> &str {- // NOTE: deliberately `run_flow`, not `run_workflow` — the latter- // name is already taken by the unrelated legacy skills-workflow- // runner (`crate::agent::tools::run_workflow`,- // `RUN_WORKFLOW_TOOL_NAME`), which is registered in the same- // default tool registry (`tools::ops::all_tools_with_runtime`).- // Both tools were previously named identically, which- // `all_tools_default_registry_has_no_duplicate_tool_names` caught- // as a duplicate-tool-name registry bug.- "run_flow"- }-- fn description(&self) -> &str {- "Run a SAVED workflow by id to TEST it end-to-end. This is a REAL run, not a \- simulation — real effects can fire (use dry_run_workflow for a safe MOCK run \- instead). It only works on a flow the user has already saved; pass its `flow_id`. \- You MUST ask the user to confirm and wait for an explicit 'yes' before calling this \- — never run a workflow unprompted. The flow's own approval gate still pauses \- outbound-action nodes. If the flow declares workflow inputs (read `graph.inputs` \- via get_flow), pass their values in `inputs` — ask the user for any required one \- rather than inventing it; a missing or wrongly-typed value is rejected and nothing \- runs. Params: { flow_id (required), input?, inputs? }. Returns the run's status + \- any nodes paused for approval."- }-- fn parameters_schema(&self) -> Value {- json!({- "type": "object",- "properties": {- "flow_id": {- "type": "string",- "description": "Id of the SAVED flow to run (the user must have saved it first)."- },- "input": {- "description": "Optional trigger input passed to the run (defaults to {})."- },- "inputs": {- "type": "object",- "description": "Values for the flow's DECLARED workflow inputs, keyed by \- name. Read the declarations from the flow's graph.inputs \- first; ask the user for any required value instead of \- guessing. Distinct from 'input', the free-form trigger \- payload."- }- },- "required": ["flow_id"]- })- }-- fn permission_level(&self) -> PermissionLevel {- // A real run with real effects — gated like a Write-class action.- PermissionLevel::Write- }-- fn external_effect(&self) -> bool {- true- }-- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {- self.execute_with_context(args, tinytools::ToolCallOptions::default(), None)- .await- }-- async fn execute_with_context(- &self,- args: Value,- _options: tinytools::ToolCallOptions,- tool_context: Option<&dyn tinytools::ToolRunContext>,- ) -> anyhow::Result<ToolResult> {- let ctx = crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(tool_context);- let flow_id = match args.get("flow_id").and_then(Value::as_str).map(str::trim) {- Some(id) if !id.is_empty() => id.to_string(),- _ => {- return Ok(ToolResult::error(- "Missing 'flow_id' — run_flow only works on a SAVED flow. Ask the user \- to Save the workflow first, then run it by id."- .to_string(),- ))- }- };- let input = args.get("input").cloned().unwrap_or_else(|| json!({}));- // A non-object `inputs` is the model mis-shaping the call; say so- // plainly rather than silently running with none, which would produce a- // confusing "required input missing" for a value it thinks it sent.- let inputs = match args.get("inputs") {- None | Some(Value::Null) => serde_json::Map::new(),- Some(Value::Object(map)) => map.clone(),- Some(_) => {- return Ok(ToolResult::error(- "'inputs' must be an object keyed by the flow's declared input names, \- e.g. {\"repo\": \"acme/api\"}. Read the declarations from the flow's \- graph.inputs."- .to_string(),- ))- }- };-- tracing::info!(- target: "flows",- %flow_id,- "[flows] run_flow: agent-initiated test run starting (detached)"- );-- // Detach (bug B41): a flow whose first real node is a live-research- // agent node inherently runs longer than the tinyagents harness's 120s- // per-tool-call cap, so a blocking `run_flow` could never succeed —- // it died at 120s, orphaning the run row (bug B42). `flows_run_detached`- // validates + compile-checks synchronously (so a broken flow still- // returns an immediate, actionable error), fires the run on a background- // task, and returns `{ run_id, status: "running" }` in well under 120s.- // The copilot then polls `get_flow_run(run_id)` to observe completion.- match crate::flows::ops::flows_run_detached(- &ctx,- &self.config,- &flow_id,- input,- inputs,- tinyflows_catalog::types::FlowRunTrigger::Rpc,- )- .await- {- Ok(outcome) => {- let run_id = outcome- .value- .get("run_id")- .and_then(Value::as_str)- .unwrap_or_default()- .to_string();- Ok(ToolResult::success(serde_json::to_string_pretty(&json!({- "type": "workflow_run_started",- "flow_id": flow_id,- "run_id": run_id,- "status": "running",- "detached": true,- "note": "The run started in the background and is now 'running'. Poll \- get_flow_run with this run_id to see it settle to a terminal \- status (completed / failed / interrupted / pending_approval); \- do not assume success from this response alone.",- "result": outcome.value,- }))?))- }- Err(e) => {- tracing::debug!(target: "flows", %flow_id, error = %e, "[flows] run_flow: failed to start");- Ok(ToolResult::error(format!(- "Could not start flow '{flow_id}': {e}"- )))- }- }- }-}--#[cfg(test)]-#[path = "tools_tests.rs"]-mod tests;--#[cfg(test)]-#[path = "tools_schema_tests.rs"]-mod schema_tests;diff --git a/crates/openhuman-core/src/flows/tools_schema_tests.rs b/crates/openhuman-core/src/flows/tools_schema_tests.rsdeleted file mode 100644index a0fbde4ade..0000000000--- a/crates/openhuman-core/src/flows/tools_schema_tests.rs+++ /dev/null@@ -1,70 +0,0 @@-use super::*;-use serde_json::json;--fn expected_propose_workflow() -> serde_json::Value {- json!({- "type": "object",- "properties": {- "name": {- "type": "string",- "description": "Human-readable name for the proposed flow."- },- "graph": {- "type": "object",- "description": "A tinyflows WorkflowGraph: { name?, nodes: [...], edges: [...] }. See the tool description for node kinds and their config shapes.",- "properties": {- "nodes": {- "type": "array",- "items": {- "type": "object",- "properties": {- "id": { "type": "string", "description": "Unique id within the graph." },- "kind": {- "type": "string",- "enum": [- "trigger", "agent", "tool_call", "http_request",- "code", "shell", "condition", "switch", "merge", "split_out",- "transform", "output_parser", "sub_workflow", "memory",- "dedup", "loop", "spawn", "gate", "scatter", "gather",- "approval", "void"- ]- },- "name": { "type": "string", "description": "Human-readable node name." },- "config": { "description": "Kind-specific configuration; see tool description." }- },- "required": ["id", "kind", "name"]- }- },- "edges": {- "type": "array",- "items": {- "type": "object",- "properties": {- "from_node": { "type": "string" },- "to_node": { "type": "string" },- "from_port": { "type": "string", "description": "Defaults to \"main\". For a condition/switch branch, this is where the branch label (e.g. \"true\"/\"false\") goes." },- "to_port": { "type": "string", "description": "Defaults to \"main\". Almost always stays \"main\" — branch labels go on from_port, not here." }- },- "required": ["from_node", "to_node"]- }- }- },- "required": ["nodes", "edges"]- },- "require_approval": {- "type": "boolean",- "description": "Force a human-approval gate on every outbound tool/HTTP action this flow takes once saved. Defaults to true for agent-proposed flows."- }- },- "required": ["name", "graph"]- })-}--#[test]-fn propose_workflow_static_schema_matches_json_literal() {- let tool = ProposeWorkflowTool::new(std::sync::Arc::new(crate::config::Config::default()));- assert_eq!(- tinytools::Tool::parameters_schema(&tool),- expected_propose_workflow()- );-}diff --git a/crates/openhuman-core/src/flows/tools_tests.rs b/crates/openhuman-core/src/flows/tools_tests.rsdeleted file mode 100644index 22e6a8042c..0000000000--- a/crates/openhuman-core/src/flows/tools_tests.rs+++ /dev/null@@ -1,458 +0,0 @@-use super::*;-use crate::config::Config;-use serde_json::json;-use tempfile::TempDir;--fn test_config(tmp: &TempDir) -> Arc<Config> {- let config = Config {- workspace_dir: tmp.path().join("workspace"),- action_dir: tmp.path().join("workspace"),- config_path: tmp.path().join("config.toml"),- ..Config::default()- };- std::fs::create_dir_all(&config.workspace_dir).unwrap();- Arc::new(config)-}--fn valid_graph() -> Value {- json!({- "nodes": [- {- "id": "t",- "kind": "trigger",- "name": "Every morning",- "config": { "trigger_kind": "schedule", "schedule": { "kind": "cron", "expr": "0 9 * * *" } }- },- {- "id": "a",- "kind": "agent",- "name": "Summarize",- "config": { "prompt": "Summarize yesterday's messages" }- },- {- "id": "s",- "kind": "tool_call",- "name": "Post to Slack",- "config": { "slug": "slack.post_message", "args": { "channel": "#general" } }- }- ],- "edges": [- { "from_node": "t", "to_node": "a" },- { "from_node": "a", "to_node": "s" }- ]- })-}--#[tokio::test]-async fn valid_graph_returns_workflow_proposal_success() {- let tmp = TempDir::new().unwrap();- let tool = ProposeWorkflowTool::new(test_config(&tmp));-- let result = tool- .execute(json!({ "name": "Daily standup summary", "graph": valid_graph() }))- .await- .unwrap();-- assert!(!result.is_error, "{}", result.output());- let parsed: Value = serde_json::from_str(&result.output()).expect("valid JSON output");- assert_eq!(parsed["type"], "workflow_proposal");- assert_eq!(parsed["name"], "Daily standup summary");- assert_eq!(parsed["graph"]["nodes"].as_array().unwrap().len(), 3);- // A proposal is never a persisted flow — the payload must say so (WS2) so- // an agent can't misread it as a save confirmation.- assert_eq!(parsed["persisted"], false);-}--#[tokio::test]-async fn no_trigger_graph_is_an_error() {- let tmp = TempDir::new().unwrap();- let tool = ProposeWorkflowTool::new(test_config(&tmp));-- let graph_without_trigger = json!({- "nodes": [ { "id": "a", "kind": "output_parser", "name": "A" } ],- "edges": []- });-- let result = tool- .execute(json!({ "name": "bad", "graph": graph_without_trigger }))- .await- .unwrap();-- assert!(result.is_error);- assert!(- result.output().to_lowercase().contains("trigger"),- "expected a trigger-related validation error, got: {}",- result.output()- );-}--#[tokio::test]-async fn missing_name_is_an_error() {- let tmp = TempDir::new().unwrap();- let tool = ProposeWorkflowTool::new(test_config(&tmp));-- let result = tool- .execute(json!({ "graph": valid_graph() }))- .await- .unwrap();-- assert!(result.is_error);- assert!(result.output().contains("Missing 'name'"));-}--#[tokio::test]-async fn missing_graph_is_an_error() {- let tmp = TempDir::new().unwrap();- let tool = ProposeWorkflowTool::new(test_config(&tmp));-- let result = tool- .execute(json!({ "name": "no graph here" }))- .await- .unwrap();-- assert!(result.is_error);- assert!(result.output().contains("Missing 'graph'"));-}--#[tokio::test]-async fn omitted_require_approval_defaults_true_in_result() {- let tmp = TempDir::new().unwrap();- let tool = ProposeWorkflowTool::new(test_config(&tmp));-- let result = tool- .execute(json!({ "name": "demo", "graph": valid_graph() }))- .await- .unwrap();-- let parsed: Value = serde_json::from_str(&result.output()).unwrap();- assert_eq!(parsed["require_approval"], true);-}--#[tokio::test]-async fn explicit_require_approval_false_is_respected() {- let tmp = TempDir::new().unwrap();- let tool = ProposeWorkflowTool::new(test_config(&tmp));-- let result = tool- .execute(json!({ "name": "demo", "graph": valid_graph(), "require_approval": false }))- .await- .unwrap();-- let parsed: Value = serde_json::from_str(&result.output()).unwrap();- assert_eq!(parsed["require_approval"], false);-}--#[tokio::test]-async fn explicit_require_approval_true_is_respected() {- let tmp = TempDir::new().unwrap();- let tool = ProposeWorkflowTool::new(test_config(&tmp));-- let result = tool- .execute(json!({ "name": "demo", "graph": valid_graph(), "require_approval": true }))- .await- .unwrap();-- let parsed: Value = serde_json::from_str(&result.output()).unwrap();- assert_eq!(parsed["require_approval"], true);-}--#[tokio::test]-async fn summary_step_count_and_kinds_are_correct() {- let tmp = TempDir::new().unwrap();- let tool = ProposeWorkflowTool::new(test_config(&tmp));-- let result = tool- .execute(json!({ "name": "demo", "graph": valid_graph() }))- .await- .unwrap();-- let parsed: Value = serde_json::from_str(&result.output()).unwrap();- let steps = parsed["summary"]["steps"].as_array().unwrap();- // 3 nodes total, minus the 1 trigger = 2 steps.- assert_eq!(steps.len(), 2);- assert_eq!(steps[0]["kind"], "agent");- assert_eq!(steps[0]["name"], "Summarize");- assert_eq!(steps[0]["config_hint"], "Summarize yesterday's messages");- assert_eq!(steps[1]["kind"], "tool_call");- assert_eq!(steps[1]["name"], "Post to Slack");- assert_eq!(steps[1]["config_hint"], "slack.post_message");-}--#[tokio::test]-async fn summary_trigger_describes_schedule() {- let tmp = TempDir::new().unwrap();- let tool = ProposeWorkflowTool::new(test_config(&tmp));-- let result = tool- .execute(json!({ "name": "demo", "graph": valid_graph() }))- .await- .unwrap();-- let parsed: Value = serde_json::from_str(&result.output()).unwrap();- assert_eq!(parsed["summary"]["trigger"], "schedule: 0 9 * * *");-}--#[tokio::test]-async fn summary_trigger_describes_manual_default() {- let tmp = TempDir::new().unwrap();- let tool = ProposeWorkflowTool::new(test_config(&tmp));-- let graph = json!({- "nodes": [ { "id": "t", "kind": "trigger", "name": "Manual start" } ],- "edges": []- });-- let result = tool- .execute(json!({ "name": "demo", "graph": graph }))- .await- .unwrap();-- let parsed: Value = serde_json::from_str(&result.output()).unwrap();- assert_eq!(parsed["summary"]["trigger"], "manual");- assert!(parsed["summary"]["steps"].as_array().unwrap().is_empty());-}--#[tokio::test]-async fn summary_trigger_describes_app_event() {- let tmp = TempDir::new().unwrap();- let tool = ProposeWorkflowTool::new(test_config(&tmp));-- let graph = json!({- "nodes": [- {- "id": "t",- "kind": "trigger",- "name": "On new email",- "config": {- "trigger_kind": "app_event",- "toolkit": "gmail",- "trigger_slug": "GMAIL_NEW_GMAIL_MESSAGE"- }- }- ],- "edges": []- });-- let result = tool- .execute(json!({ "name": "demo", "graph": graph }))- .await- .unwrap();-- let parsed: Value = serde_json::from_str(&result.output()).unwrap();- assert_eq!(- parsed["summary"]["trigger"],- "app event: gmail/GMAIL_NEW_GMAIL_MESSAGE"- );-}--#[test]-fn propose_workflow_never_creates_a_flow() {- // The tool must have no way to persist a flow — the human-in-the-loop- // invariant (issue B4) rests entirely on `external_effect() == false` and- // `permission_level() == None` (no gate would even fire if this ever- // regressed to true, but a saved flow must still only ever be created by- // the user's own `flows_create` click).- let tmp = TempDir::new().unwrap();- let tool = ProposeWorkflowTool::new(test_config(&tmp));- assert_eq!(tool.permission_level(), PermissionLevel::None);- assert!(!tool.external_effect());-}--#[test]-fn tool_name_and_schema_are_stable() {- let tmp = TempDir::new().unwrap();- let tool = ProposeWorkflowTool::new(test_config(&tmp));- assert_eq!(tool.name(), "propose_workflow");-- let schema = tool.parameters_schema();- let required = schema["required"].as_array().unwrap();- assert!(required.iter().any(|v| v.as_str() == Some("name")));- assert!(required.iter().any(|v| v.as_str() == Some("graph")));-}--#[test]-fn display_label_humanizes_the_tool_name() {- let tmp = TempDir::new().unwrap();- let tool = ProposeWorkflowTool::new(test_config(&tmp));- assert_eq!(- tool.display_label(&Value::Null).as_deref(),- Some("Propose Workflow")- );-}--// ── enforcing binding-resolvability gate ────────────────────────────────────--#[tokio::test]-async fn propose_workflow_rejects_agent_binding_missing_declared_field() {- // A declared schema that omits `channel` proves `notify`'s binding resolves- // null at runtime. Unlike a schema-less agent (whose host-defined output is- // merely unverifiable), propose_workflow must- // REJECT this outright rather than warn (warning_count would have been 0- // here — nothing stopped this from reaching save_workflow before).- let tmp = TempDir::new().unwrap();- let tool = ProposeWorkflowTool::new(test_config(&tmp));-- let graph = json!({- "nodes": [- { "id": "t", "kind": "trigger", "name": "Manual" },- { "id": "summarize", "kind": "agent", "name": "Summarize",- "config": { "agent_ref": "planner", "prompt": "summarize",- "output_parser": { "schema": { "type": "object",- "properties": { "summary": { "type": "string" } } } } } },- { "id": "notify", "kind": "tool_call", "name": "Notify",- "config": { "slug": "SLACK_SEND_MESSAGE",- "args": { "channel": "=nodes.summarize.item.json.channel", "text": "A notification" } } }- ],- "edges": [- { "from_node": "t", "to_node": "summarize" },- { "from_node": "summarize", "to_node": "notify" }- ]- });-- let result = tool- .execute(json!({ "name": "Summarize and notify", "graph": graph }))- .await- .unwrap();-- assert!(result.is_error, "must be rejected: {}", result.output());- let output = result.output();- assert!(output.contains("notify"), "{output}");- assert!(output.contains("channel"), "{output}");- assert!(output.contains("summarize"), "{output}");- assert!(- output.contains("output_parser.schema"),- "must name the missing schema as the fix: {output}"- );-}--#[tokio::test]-async fn propose_workflow_rejects_an_incompatible_saved_child_reference() {- let tmp = TempDir::new().unwrap();- let config = test_config(&tmp);- let tool = ProposeWorkflowTool::new(Arc::clone(&config));-- // Simulate a legacy child saved before the current TinyFlows engine- // rejected nested conditional fan-in. The parent itself is structurally- // valid, so only the config-aware shared builder gate can catch this.- let legacy_child = json!({- "nodes": [- { "id": "start", "kind": "trigger", "name": "Trigger" },- { "id": "outer", "kind": "condition", "name": "Outer", "config": { "field": "outer" } },- { "id": "inner", "kind": "condition", "name": "Inner", "config": { "field": "inner" } },- { "id": "outer_else", "kind": "output_parser", "name": "Outer else" },- { "id": "inner_else", "kind": "output_parser", "name": "Inner else" },- { "id": "a", "kind": "output_parser", "name": "A" },- { "id": "c", "kind": "output_parser", "name": "C" },- { "id": "m", "kind": "merge", "name": "Merge" }- ],- "edges": [- { "from_node": "start", "to_node": "outer" },- { "from_node": "start", "to_node": "c" },- { "from_node": "outer", "from_port": "true", "to_node": "inner" },- { "from_node": "outer", "from_port": "false", "to_node": "outer_else" },- { "from_node": "inner", "from_port": "true", "to_node": "a" },- { "from_node": "inner", "from_port": "false", "to_node": "inner_else" },- { "from_node": "a", "to_node": "m" },- { "from_node": "c", "to_node": "m" }- ]- });- let child_graph = tinyflows::migrate::deserialize_graph(legacy_child)- .expect("legacy child should deserialize");- tinyflows::validate::validate(&child_graph)- .expect("legacy child should remain structurally valid");- let child = crate::flows::store::create_flow(- &config,- "Legacy unsafe child".to_string(),- child_graph,- false,- false,- )- .unwrap();- let parent = json!({- "nodes": [- { "id": "start", "kind": "trigger", "name": "Trigger" },- {- "id": "saved-child",- "kind": "sub_workflow",- "name": "Saved child",- "config": { "workflow_id": child.id }- }- ],- "edges": [{ "from_node": "start", "to_node": "saved-child" }]- });-- let result = tool- .execute(json!({ "name": "Parent", "graph": parent }))- .await- .unwrap();-- assert!(result.is_error, "must reject unsafe saved child");- let output = result.output();- assert!(- output.contains("unsupported_nested_conditional_fan_in"),- "{output}"- );- assert!(output.contains(&child.id), "{output}");- assert!(output.contains("saved-child"), "{output}");- assert!(output.contains("call propose_workflow again"), "{output}");-}--/// Docs-drift guard (F2): `propose_workflow`'s hand-written description and the-/// typed node-kind contracts are two views of the SAME DSL, and they must not-/// diverge. If a node kind is added/renamed or a required config field changes-/// in `node_contracts.rs`, this fails until the tool description is updated to-/// match — the "prose can never diverge from code" check the plan calls for.-#[test]-fn propose_workflow_description_matches_typed_node_contracts() {- let tmp = TempDir::new().unwrap();- let tool = ProposeWorkflowTool::new(test_config(&tmp));- let desc = tool.description();- for contract in crate::flows::all_node_kind_contracts() {- assert!(- desc.contains(&contract.kind),- "propose_workflow description is missing node kind `{}` — update it to match \- node_contracts.rs",- contract.kind- );- for field in contract.config_fields.iter().filter(|f| f.required) {- assert!(- desc.contains(&field.name),- "propose_workflow description is missing required field `config.{}` of node kind \- `{}` — update it to match node_contracts.rs",- field.name,- contract.kind- );- }- }-}--/// Same drift class as the description guard above, but for the JSON `enum`-/// in `parameters_schema()`: a strict schema-constrained caller (some tool-use-/// providers validate arguments against the advertised schema before-/// `execute` ever runs) can only submit a `kind` this enum lists, regardless-/// of what the prose teaches or what `validate_and_migrate_graph` accepts. A-/// node kind present in `node_contracts.rs` but missing here would silently-/// be unreachable through `propose_workflow` for such a caller — this is the-/// exact class of bug the `loop` kind hit when it was documented in prose-/// but left off this enum.-#[test]-fn propose_workflow_schema_enum_matches_typed_node_contracts() {- let tmp = TempDir::new().unwrap();- let tool = ProposeWorkflowTool::new(test_config(&tmp));- let schema = tool.parameters_schema();- let enum_kinds: Vec<&str> = schema["properties"]["graph"]["properties"]["nodes"]["items"]- ["properties"]["kind"]["enum"]- .as_array()- .expect("kind enum must be an array")- .iter()- .map(|v| v.as_str().expect("enum entries are strings"))- .collect();- for contract in crate::flows::all_node_kind_contracts() {- assert!(- enum_kinds.contains(&contract.kind.as_str()),- "propose_workflow's parameters_schema `kind` enum is missing node kind `{}` — \- update it to match node_contracts.rs",- contract.kind- );- }-}