Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(flows): add builder and discovery tool schemas

Steven Enamakel20a2ccf4b886
diff --git a/crates/openhuman-core/src/flows/builder_tools.rs b/crates/openhuman-core/src/flows/builder_tools.rs
index 69c74017e6..21a8dcf621 100644
--- a/crates/openhuman-core/src/flows/builder_tools.rs
+++ b/crates/openhuman-core/src/flows/builder_tools.rs
@@ -1,58 +1,29 @@
-//! Agent tool belt for the `workflow-builder` specialist (Phase 5b).
+//! The Composio-bound half of the `workflow-builder` tool belt.
//!
-//! These tools give the `workflow-builder` agent (see
-//! `agent_registry/agents/workflow_builder/`) its full authoring surface for
-//! tinyflows [`WorkflowGraph`]s in chat — 22 tools spanning propose-only
-//! validation, in-place draft mutation, live reads, one bounded real Composio
-//! call, run control, and persistence:
+//! The authoring tools (`revise_workflow`, `edit_workflow`, `validate_workflow`,
+//! `dry_run_workflow`, `create_workflow`, `duplicate_flow`, `save_workflow`, the
+//! run controls, the flow reads, `list_agent_definitions`, the node-kind reads
+//! and `suggest_workflows`) live in `tinyflows_copilot::tools` and run over the
+//! ports [`super::builder_host::FlowsHost`] implements; their registration is in
+//! [`super::registration`]. This module keeps the tools that are bound to the
+//! live Composio catalog and the connected accounts, which only this host owns:
//!
//! | Tool | Permission | Effect |
//! | --------------------------------- | ---------- | ---------------------------------------------------------------- |
-//! | [`ReviseWorkflowTool`] | `None` | validate a revised draft → proposal (never persists) |
-//! | [`EditWorkflowTool`] | `None` | mutate a draft in place (`add_node`/`remove_edge`/…) — never saves |
-//! | [`ValidateWorkflowTool`] | `None` | read: run the full gate stack without emitting a proposal card |
-//! | [`GetFlowHistoryTool`] | `None` | read: a saved flow's prior graph snapshots |
-//! | [`ListFlowRunsTool`] | `None` | read: a flow's run history |
-//! | [`ResumeFlowRunTool`] | `Execute` | advance a run parked on approval — approved nodes fire for real |
-//! | [`CancelFlowRunTool`] | `Write` | stop an in-flight/parked run; fires no new outbound effect |
-//! | [`CreateWorkflowTool`] | `Write` | persist a NEW flow — always born **DISABLED** |
-//! | [`DuplicateFlowTool`] | `Write` | clone a saved flow — the copy is always born **DISABLED** |
//! | [`ListConnectableToolkitsTool`] | `None` | read: which toolkits are already connected |
-//! | [`ListFlowsTool`] | `None` | read: list saved flows |
-//! | [`GetFlowTool`] | `None` | read: fetch a saved flow's graph |
-//! | [`GetFlowRunTool`] | `None` | read: fetch a run's steps |
//! | [`ListFlowConnectionsTool`] | `None` | read: connection refs (ids/names only) |
//! | [`SearchToolCatalogTool`] | `None` | read: real Composio tool slugs (live catalog) |
//! | [`GetToolContractTool`] | `None` | read: one action's FULL live contract |
//! | [`GetToolOutputSampleTool`] | `ReadOnly` | ONE bounded real Composio call (Read-scope only, connected toolkit only) |
-//! | [`ListAgentDefinitionsTool`] | `None` | read: selectable agent definitions (`agent_ref`) |
-//! | [`ListNodeKindsTool`] | `None` | read: the DSL's node kinds |
-//! | [`GetNodeKindContractTool`] | `None` | read: one node kind's config/port/example/gotcha contract |
-//! | [`DryRunWorkflowTool`] | `None` | run a *draft* against MOCK capabilities — not tier-gated (F7) |
-//! | [`SaveWorkflowTool`] | `Write` | persist a graph onto an EXISTING flow |
-//!
-//! **Human-in-the-loop invariant.** Enabling a flow is not a tool this agent
-//! has, by design, no matter which tool above it reaches for:
-//! [`CreateWorkflowTool`] and [`DuplicateFlowTool`] always produce a
-//! **DISABLED** flow, and [`SaveWorkflowTool`] never sets
-//! `enabled`/`require_approval` (it CAN auto-disable an already-enabled flow
-//! when the graph's trigger transitions from manual to automatic — see its
-//! own doc). `revise_workflow` / `edit_workflow` / `validate_workflow` only
-//! validate or mutate a draft and never persist. `dry_run_workflow` executes
-//! only against `tinyflows`' deterministic **mock** capabilities, so no real
-//! LLM / tool / HTTP / code side effect can fire from it regardless of tier
-//! (F7 — it is deliberately NOT tier-gated; see its own doc).
-//! [`ResumeFlowRunTool`] is the one place a non-persistence tool can cause a
-//! real effect: resuming a parked run lets its already-approved nodes fire,
-//! which is why it is `Execute`-gated rather than `None`/`Write`.
//!
//! The agent's full tool scope (see `agent_registry/agents/workflow_builder/
//! agent.toml`) also grants the Composio **discovery/connect** tools —
//! `composio_list_toolkits`, `composio_list_connections`, `composio_connect`
//! (defined in `composio/tools.rs`) — so the builder can link an app the
-//! workflow needs before proposing. Those stay within the invariant: connect
-//! is an approval-gated OAuth hand-off, and `composio_execute` (running an
-//! arbitrary real action, any scope) remains deliberately OUT of scope.
+//! workflow needs before proposing. Those stay within the copilot's
+//! human-in-the-loop invariant: connect is an approval-gated OAuth hand-off, and
+//! `composio_execute` (running an arbitrary real action, any scope) remains
+//! deliberately OUT of scope.
//!
//! **One narrow, deliberate carve-out (B12):** [`GetToolOutputSampleTool`]
//! (`get_tool_output_sample`) DOES perform a real Composio call — but only
@@ -66,37 +37,15 @@
mod catalog_search;
mod connection_reads;
-mod draft_edit;
-mod draft_revise;
-mod draft_validate;
-mod dry_run;
-mod flow_reads;
-mod kind_reads;
-mod persistence;
-mod run_control;
mod tool_contract;
pub(crate) use catalog_search::search_live_catalog;
pub use catalog_search::SearchToolCatalogTool;
pub use connection_reads::{ListConnectableToolkitsTool, ListFlowConnectionsTool};
-pub use draft_edit::EditWorkflowTool;
-pub use draft_revise::ReviseWorkflowTool;
-pub use draft_validate::ValidateWorkflowTool;
-pub use dry_run::DryRunWorkflowTool;
-pub use flow_reads::{
- GetFlowHistoryTool, GetFlowRunTool, GetFlowTool, ListFlowRunsTool, ListFlowsTool,
-};
-pub use kind_reads::{GetNodeKindContractTool, ListAgentDefinitionsTool, ListNodeKindsTool};
-pub use persistence::{CreateWorkflowTool, DuplicateFlowTool, SaveWorkflowTool};
-pub use run_control::{CancelFlowRunTool, ResumeFlowRunTool};
pub use tool_contract::{GetToolContractTool, GetToolOutputSampleTool};
#[cfg(test)]
use connection_reads::flow_connection_to_json;
-#[cfg(test)]
-use draft_validate::validate_workflow_report_is_ok;
-#[cfg(test)]
-use persistence::create_workflow_report;
#[cfg(test)]
#[path = "builder_tools_tests.rs"]
diff --git a/crates/openhuman-core/src/flows/builder_tools/draft_edit.rs b/crates/openhuman-core/src/flows/builder_tools/draft_edit.rs
deleted file mode 100644
index d1c988da43..0000000000
--- a/crates/openhuman-core/src/flows/builder_tools/draft_edit.rs
+++ /dev/null
@@ -1,461 +0,0 @@
-//! `edit_workflow`: structured incremental edits on a draft (proposal only, F1).
-
-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;
-use tinytools::{PermissionLevel, Tool, ToolResult};
-
-/// Comma list of the valid `op` tag values, for the missing-/unknown-`op`
-/// parse errors surfaced by [`EditWorkflowTool`].
-const VALID_OP_TYPES: &str = "add_node, update_node_config, set_node_name, rename_node, \
- remove_node, add_edge, remove_edge, set_node_position";
-
-/// The expected field shape for a given `op` tag, used in `edit_workflow`'s
-/// per-op parse diagnostics so a failing op tells the agent exactly what that
-/// op type wants. Returns `None` for an unrecognized tag.
-fn edit_op_shape(op: &str) -> Option<&'static str> {
- Some(match op {
- "add_node" => "{ op, node: { id, kind, name, config? } }",
- "update_node_config" => {
- "{ op, id, config } (id also accepts alias `node_id`; config is a JSON merge-patch)"
- }
- "set_node_name" => "{ op, id, name } (id also accepts alias `node_id`)",
- "rename_node" => "{ op, id, new_id } (also accept aliases `node_id` / `new_node_id`)",
- "remove_node" => "{ op, id } (id also accepts alias `node_id`)",
- "add_edge" => "{ op, edge: { from_node, to_node, from_port?, to_port? } }",
- "remove_edge" => "{ op, from_node, to_node, from_port?, to_port? }",
- "set_node_position" => "{ op, id, position: { x, y } } (id also accepts alias `node_id`)",
- _ => return None,
- })
-}
-
-// ─────────────────────────────────────────────────────────────────────────────
-// edit_workflow — structured incremental edits (proposal only) — F1
-// ─────────────────────────────────────────────────────────────────────────────
-
-/// `edit_workflow`: apply a small list of structured graph ops to a base graph
-/// (a saved flow by `flow_id`, or an inline `graph`) instead of re-emitting the
-/// whole graph. Applies the ops, runs the full validate + hard-gate stack, and
-/// returns the same `workflow_proposal` payload as `revise_workflow`.
-///
-/// This is the cheap, low-regression iteration path (audit F1): a one-field
-/// tweak on a 20-node flow is one `update_node_config` op, not a full re-emit.
-/// Still proposal-only — never persists or enables.
-pub struct EditWorkflowTool {
- config: Arc<Config>,
-}
-
-impl EditWorkflowTool {
- pub fn new(config: Arc<Config>) -> Self {
- Self { config }
- }
-}
-
-#[async_trait]
-impl Tool for EditWorkflowTool {
- fn name(&self) -> &str {
- "edit_workflow"
- }
-
- fn description(&self) -> &str {
- "Iterate on a workflow with STRUCTURED EDITS instead of re-emitting the whole graph — the \
- cheap, low-regression path for changing a draft, saved, or inline flow. Provide the base \
- (draft_id for a working draft — the applied edit is written back to it; flow_id for a \
- saved flow; or an inline graph) plus ops[]: a list of edits applied in \
- order. Op shapes (each is { \"op\": <type>, ... }): add_node {node}, update_node_config \
- {id, config} (JSON merge-patch — a null value deletes that config key), set_node_name \
- {id, name}, rename_node {id, new_id} (rewires EDGES onto the new id, but does NOT rewrite \
- `=nodes.<old_id>...` binding expressions inside OTHER nodes' config — re-point those \
- yourself, or validate_workflow will catch the dangling reference), remove_node {id} \
- (drops its edges), \
- add_edge {edge}, remove_edge {from_node, to_node, from_port?, to_port?}, set_node_position \
- {id, position}. PERSISTENCE: the applied edit is written to a DRAFT, never onto the saved \
- flow — this tool NEVER saves. Editing a flow_id SEEDS A NEW DRAFT from that flow's graph \
- and returns its `draft_id`; editing a draft_id writes back to that same draft. The result \
- carries `draft_id`, `flow_id` (if any), `persisted: false`, and a `next` hint. To keep \
- iterating pass that `draft_id` (to edit_workflow / dry_run_workflow); to persist, call \
- save_workflow { flow_id, draft_id } when the user asks. If an op fails or the resulting \
- graph is invalid, the error names the failing op / node; fix it and call edit_workflow \
- again."
- }
-
- fn parameters_schema(&self) -> Value {
- static_schema!(include_str!("parameters/edit_workflow.json"))
- }
-
- fn permission_level(&self) -> PermissionLevel {
- // Pure validation, no side effect — mirrors propose/revise_workflow.
- PermissionLevel::None
- }
-
- fn external_effect(&self) -> bool {
- false
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- // Resolve the base graph + a default name from exactly one of: a draft
- // (the shared working copy — edits are written back to it), a saved
- // flow, or an inline graph.
- let draft_id = args
- .get("draft_id")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty());
- let flow_id = args
- .get("flow_id")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty());
- let inline_graph = args.get("graph").filter(|v| !v.is_null());
-
- // The applied edit is always written back to a durable DRAFT (the shared
- // working copy across turns/reloads). `write_back_draft` is the draft id
- // it lands on; `edited_from_flow` is the saved flow this edit derives
- // from / would persist onto, if any. The core WS2 fix: editing a bare
- // `flow_id` used to persist NOTHING and return NO handle — the edit was
- // unreachable and read as "written onto the flow". Now a `flow_id` base
- // seeds a NEW draft, so the edit is durable, addressable, and clearly
- // NOT the saved flow.
- let mut write_back_draft: Option<String> = None;
- let mut edited_from_flow: Option<String> = None;
-
- let (base_graph, default_name) = match (draft_id, flow_id, inline_graph) {
- (Some(id), _, _) => match ops::flows_draft_get(&self.config, id) {
- Ok(outcome) => {
- let draft = outcome.value;
- match tinyflows::migrate::deserialize_graph(draft.graph.clone()) {
- Ok(graph) => {
- write_back_draft = Some(draft.id.clone());
- // A draft may already be linked to a saved flow —
- // carry that through so the proposal echoes it.
- edited_from_flow = draft.flow_id.clone();
- (graph, draft.name)
- }
- Err(e) => {
- return Ok(ToolResult::error(format!(
- "Draft '{id}' holds a graph that could not be parsed: {e}."
- )));
- }
- }
- }
- Err(e) => {
- return Ok(ToolResult::error(format!(
- "Could not load draft '{id}' to edit: {e}"
- )));
- }
- },
- (None, Some(id), _) => match ops::flows_get(&self.config, id).await {
- Ok(outcome) => {
- let flow = outcome.value;
- // Seed a NEW draft from the saved flow's graph so the edit is
- // durable and reachable (the RPC/canvas path uses the same
- // `flows_draft_create` op). Linking the draft to `flow.id`
- // means a later save_workflow { flow_id, draft_id } knows its
- // target.
- let graph_json = match serde_json::to_value(&flow.graph) {
- Ok(v) => v,
- Err(e) => {
- return Ok(ToolResult::error(format!(
- "Could not serialize flow '{id}' to seed a draft: {e}"
- )));
- }
- };
- match ops::flows_draft_create(
- &self.config,
- Some(flow.id.clone()),
- flow.name.clone(),
- graph_json,
- tinyflows_catalog::DraftOrigin::Chat,
- ) {
- Ok(created) => {
- let new_draft_id = created.value.id.clone();
- tracing::debug!(
- target: "flows",
- draft_id = %new_draft_id,
- flow_id = %flow.id,
- "[flows] edit_workflow: seeded a new draft from saved flow (edits live on the draft, NOT the flow)"
- );
- write_back_draft = Some(new_draft_id);
- edited_from_flow = Some(flow.id.clone());
- (flow.graph, flow.name)
- }
- Err(e) => {
- return Ok(ToolResult::error(format!(
- "Could not create a draft to edit flow '{id}': {e}"
- )));
- }
- }
- }
- Err(e) => {
- return Ok(ToolResult::error(format!(
- "Could not load flow '{id}' to edit: {e}"
- )));
- }
- },
- (None, None, Some(graph_json)) => {
- match tinyflows::migrate::deserialize_graph(graph_json.clone()) {
- Ok(graph) => {
- let name = graph.name.clone();
- (graph, name)
- }
- Err(e) => {
- return Ok(ToolResult::error(format!(
- "The inline base `graph` could not be parsed: {e}."
- )));
- }
- }
- }
- (None, None, None) => {
- return Ok(ToolResult::error(
- "Provide one of `draft_id` (a working draft), `flow_id` (a saved flow), or \
- `graph` (an inline base graph) to edit."
- .to_string(),
- ));
- }
- };
-
- // Parse the ops list element-by-element so a bad op reports its index,
- // its `op` tag, the serde error, AND the expected field shape for THAT
- // op type — instead of a bare aggregate "missing field `id`" that names
- // neither the failing op nor what it wanted (audit WS4).
- let ops_array = match args.get("ops") {
- Some(Value::Array(items)) => items.clone(),
- _ => {
- return Ok(ToolResult::error(
- "Missing 'ops' parameter (a non-empty array of structured edits).".to_string(),
- ));
- }
- };
- if ops_array.is_empty() {
- return Ok(ToolResult::error(
- "`ops` is empty — provide at least one edit.".to_string(),
- ));
- }
- let mut graph_ops: Vec<tinyflows::graph_ops::GraphOp> = Vec::with_capacity(ops_array.len());
- for (index, item) in ops_array.into_iter().enumerate() {
- let op_tag = item.get("op").and_then(Value::as_str).map(str::to_string);
- match serde_json::from_value::<tinyflows::graph_ops::GraphOp>(item) {
- Ok(op) => graph_ops.push(op),
- Err(e) => {
- let shape = match op_tag.as_deref() {
- Some(tag) => match edit_op_shape(tag) {
- Some(shape) => format!("op `{tag}` expects {shape}"),
- None => {
- format!("unknown op type `{tag}` — valid types: {VALID_OP_TYPES}")
- }
- },
- None => format!("missing `op` field — valid types: {VALID_OP_TYPES}"),
- };
- tracing::debug!(target: "flows", index, ?op_tag, error = %e, "[flows] edit_workflow: op failed to parse");
- return Ok(ToolResult::error(format!(
- "Could not parse op {index}: {e}. Expected {shape}. Each op is \
- {{ \"op\": <type>, ... }}. Fix the ops and call edit_workflow again."
- )));
- }
- }
- }
-
- let name = args
- .get("name")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string)
- .unwrap_or(default_name);
- let name = if name.is_empty() {
- "Untitled workflow".to_string()
- } else {
- name
- };
- let instruction = args
- .get("instruction")
- .and_then(Value::as_str)
- .map(str::to_string);
- let require_approval = args
- .get("require_approval")
- .and_then(Value::as_bool)
- .unwrap_or(true);
-
- tracing::debug!(
- target: "flows",
- %name,
- op_count = graph_ops.len(),
- from_flow = flow_id.is_some(),
- "[flows] edit_workflow: applying structured ops to base graph"
- );
-
- // Apply the ops (structural mutation, precise per-op errors).
- let edited = match tinyflows::graph_ops::apply_ops(&base_graph, &graph_ops) {
- Ok(graph) => graph,
- Err(e) => {
- tracing::debug!(target: "flows", %name, error = %e, "[flows] edit_workflow: an op failed to apply");
- // Ops apply strictly in array order, so an add_node for an id
- // that already exists is almost always an ordering mistake
- // (adding before removing the old node). Point at the fix — this
- // is the exact 2nd wasted call the WS4 audit caught.
- let hint = match (e.op, &e.kind) {
- ("add_node", tinyflows::graph_ops::GraphOpErrorKind::NodeIdExists(id)) => {
- format!(
- "\n\nOps apply strictly in array order. To replace node `{id}`, put a \
- remove_node op for it BEFORE the add_node, or use update_node_config \
- to patch it in place."
- )
- }
- _ => String::new(),
- };
- return Ok(ToolResult::error(format!(
- "{e}{hint}\n\nFix the ops and call edit_workflow again."
- )));
- }
- };
-
- // T-m6: returns `Err` (rather than only `warn!`-logging) when the
- // draft write-back itself fails, so callers can surface the failure
- // instead of telling the agent "Edits live on draft {id}" when the
- // draft still holds the PREVIOUS graph.
- let write_edit_to_draft = || -> Result<(), String> {
- if let Some(ref draft_id) = write_back_draft {
- let edited_json = serde_json::to_value(&edited).map_err(|e| e.to_string())?;
- if let Err(e) = ops::flows_draft_update(
- &self.config,
- draft_id,
- Some(name.clone()),
- Some(edited_json),
- None,
- ) {
- tracing::warn!(target: "flows", %draft_id, error = %e, "[flows] edit_workflow: could not write edit back to draft");
- return Err(e);
- }
- }
- Ok(())
- };
-
- // Structural validation of the RESULT — surface every problem at once.
- let structural = tinyflows::validate::validate_all(&edited);
- if !structural.is_empty() {
- // Preserve the longstanding working-copy contract: an applied edit
- // survives for the next repair turn even when structurally invalid.
- // T-m6: surface (not just log) a write-back failure here too, so the
- // agent knows the draft may still hold the PREVIOUS graph rather than
- // this attempted (invalid) edit.
- let write_back_note = match write_edit_to_draft() {
- Ok(()) => String::new(),
- Err(e) => format!(
- "\n\nNote: the edit could also NOT be written back to the draft ({e}) — the \
- draft still holds the PREVIOUS graph, not this attempted edit."
- ),
- };
- let messages: Vec<String> = structural.iter().map(ToString::to_string).collect();
- tracing::debug!(
- target: "flows",
- %name,
- error_count = messages.len(),
- "[flows] edit_workflow: the edited graph is structurally invalid"
- );
- return Ok(ToolResult::error(format!(
- "The edited graph is invalid:\n\n{}\n\nFix the ops and call edit_workflow again.{write_back_note}",
- messages.join("\n")
- )));
- }
-
- // Engine-incompatible topologies are different from ordinary builder
- // follow-up errors: persisting one would leave a draft that no current
- // save/run path can accept. Reject it before advancing the durable
- // working copy, while preserving the established write-back behavior
- // for later binding/connection/contract gates.
- let compatibility = ops::config_aware_engine_compatibility_errors(&self.config, &edited);
- if !compatibility.is_empty() {
- tracing::debug!(
- target: "flows",
- %name,
- error_count = compatibility.len(),
- "[flows] edit_workflow: the edited graph is engine-incompatible"
- );
- return Ok(ToolResult::error(format!(
- "The edited graph is incompatible with the current engine:\n\n{}\n\nFix the ops and call edit_workflow again.",
- compatibility.join("\n\n")
- )));
- }
-
- // Write the accepted structural edit back to the draft (the durable
- // working copy), so it survives across turns/reloads even if a later
- // binding/connection/contract gate flags something to fix next.
- //
- // T-m6: a failure here MUST short-circuit rather than fall through to
- // the proposal payload below — that payload's `next` text tells the
- // agent "Edits live on draft {id}", which would be false if the write
- // never landed, leaving the next turn silently iterating on a stale
- // draft.
- if let Some(draft_id) = write_back_draft.as_deref() {
- if let Err(e) = write_edit_to_draft() {
- tracing::warn!(
- target: "flows",
- %name,
- %draft_id,
- error = %e,
- "[flows] edit_workflow: draft write-back failed after validation passed"
- );
- return Ok(ToolResult::error(format!(
- "The edit passed validation, but could NOT be written back to draft \
- {draft_id}: {e}\n\nThe draft still holds the PREVIOUS graph, not this edit. \
- Retry edit_workflow."
- )));
- }
- }
-
- // Full builder hard-gate stack + proposal payload (shared with revise).
- // Thread the persistence-state handles so the payload carries draft_id /
- // flow_id / persisted:false and can't be misread as a save.
- match ops::build_builder_proposal(
- &self.config,
- "edit_workflow",
- &name,
- &edited,
- require_approval,
- true,
- instruction,
- write_back_draft.clone(),
- edited_from_flow.clone(),
- )
- .await
- {
- Ok(mut payload) => {
- // A prominent, one-line pointer at where the edit actually lives
- // (the draft) vs. where it does NOT (the saved flow) — the exact
- // confusion the WS2 audit caught. Only meaningful when the edit
- // landed on a draft (inline-graph edits have no durable handle).
- if let Some(draft_id) = write_back_draft.as_deref() {
- let next = match edited_from_flow.as_deref() {
- Some(flow_id) => format!(
- "Edits live on draft {draft_id}, NOT on flow {flow_id}. Iterate with \
- edit_workflow/dry_run_workflow {{ draft_id: \"{draft_id}\" }}, then \
- persist with save_workflow {{ flow_id: \"{flow_id}\", draft_id: \
- \"{draft_id}\" }} when the user asks."
- ),
- None => format!(
- "Edits live on draft {draft_id} (not yet linked to a saved flow). \
- Iterate with edit_workflow/dry_run_workflow {{ draft_id: \
- \"{draft_id}\" }}, then persist with create_workflow, or save_workflow \
- {{ flow_id, draft_id: \"{draft_id}\" }} once a flow exists."
- ),
- };
- payload["next"] = json!(next);
- }
- Ok(ToolResult::success(serde_json::to_string_pretty(&payload)?))
- }
- Err(message) => {
- tracing::debug!(target: "flows", %name, "[flows] edit_workflow: a hard gate rejected the edited graph");
- Ok(ToolResult::error(message))
- }
- }
- }
-}
-
-#[cfg(test)]
-#[path = "draft_edit_schema_tests.rs"]
-mod schema_tests;
diff --git a/crates/openhuman-core/src/flows/builder_tools/draft_edit_schema_tests.rs b/crates/openhuman-core/src/flows/builder_tools/draft_edit_schema_tests.rs
deleted file mode 100644
index 78107c94c3..0000000000
--- a/crates/openhuman-core/src/flows/builder_tools/draft_edit_schema_tests.rs
+++ /dev/null
@@ -1,54 +0,0 @@
-use super::*;
-use serde_json::json;
-
-fn expected_edit_workflow() -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "draft_id": {
- "type": "string",
- "description": "A working draft to edit as the base; the applied edit is written back to it. Provide one of draft_id / flow_id / graph."
- },
- "flow_id": {
- "type": "string",
- "description": "The saved flow to edit as the base graph. Provide one of draft_id / flow_id / graph."
- },
- "graph": {
- "type": "object",
- "description": "An inline base tinyflows WorkflowGraph to edit. Provide one of draft_id / flow_id / graph.",
- "properties": {
- "nodes": { "type": "array" },
- "edges": { "type": "array" }
- }
- },
- "ops": {
- "type": "array",
- "description": "The structured edits, applied in order. Each item is { op, ... } — see the tool description for op shapes.",
- "items": { "type": "object", "properties": { "op": { "type": "string" } }, "required": ["op"] },
- "minItems": 1
- },
- "name": {
- "type": "string",
- "description": "Name for the resulting proposed flow. Defaults to the base flow's name."
- },
- "instruction": {
- "type": "string",
- "description": "The change that motivated these ops (echoed back on the review card)."
- },
- "require_approval": {
- "type": "boolean",
- "description": "Force a human-approval gate on every outbound action once saved. Defaults to true."
- }
- },
- "required": ["ops"]
- })
-}
-
-#[test]
-fn edit_workflow_static_schema_matches_json_literal() {
- let tool = EditWorkflowTool::new(std::sync::Arc::new(crate::config::Config::default()));
- assert_eq!(
- tinytools::Tool::parameters_schema(&tool),
- expected_edit_workflow()
- );
-}
diff --git a/crates/openhuman-core/src/flows/builder_tools/draft_revise.rs b/crates/openhuman-core/src/flows/builder_tools/draft_revise.rs
deleted file mode 100644
index ce98ab6269..0000000000
--- a/crates/openhuman-core/src/flows/builder_tools/draft_revise.rs
+++ /dev/null
@@ -1,133 +0,0 @@
-//! `revise_workflow`: validate a revised draft and emit a proposal (never persists).
-
-use crate::tools::schema_cache::static_schema;
-use std::sync::Arc;
-
-use async_trait::async_trait;
-use serde_json::Value;
-
-use crate::config::Config;
-use crate::flows::ops;
-use tinyflows::authoring::validate_and_migrate_graph;
-use tinytools::{PermissionLevel, Tool, ToolResult};
-
-// ─────────────────────────────────────────────────────────────────────────────
-// revise_workflow — iterative refine of an existing draft (proposal only)
-// ─────────────────────────────────────────────────────────────────────────────
-
-/// `revise_workflow`: validate a **revised** draft graph and return the same
-/// `workflow_proposal` payload as `propose_workflow`.
-///
-/// Framed for iterative refinement: the agent supplies the updated `graph` (its
-/// revision of a prior draft) plus the `instruction` that motivated the change;
-/// the tool validates via the exact same [`validate_and_migrate_graph`] path
-/// `flows_create` uses and echoes an optional `revision` note. It NEVER
-/// persists — identical human-in-the-loop invariant to
-/// [`crate::flows::tools::ProposeWorkflowTool`].
-pub struct ReviseWorkflowTool {
- config: Arc<Config>,
-}
-
-impl ReviseWorkflowTool {
- pub fn new(config: Arc<Config>) -> Self {
- Self { config }
- }
-}
-
-#[async_trait]
-impl Tool for ReviseWorkflowTool {
- fn name(&self) -> &str {
- "revise_workflow"
- }
-
- fn description(&self) -> &str {
- "Refine an EXISTING workflow draft: supply the full updated tinyflows \
- WorkflowGraph (your revision applied to the prior draft — NOT a \
- regeneration from scratch) plus the `instruction` that motivated the \
- change. Like propose_workflow, this ONLY VALIDATES the revised graph \
- and returns a proposal summary for the user to review — it NEVER \
- creates, updates, or enables the flow. Same graph shape and node kinds \
- as propose_workflow. If validation fails, fix the graph and call again."
- }
-
- fn parameters_schema(&self) -> Value {
- static_schema!(include_str!("parameters/revise_workflow.json"))
- }
-
- fn permission_level(&self) -> PermissionLevel {
- // Pure validation, no side effect — mirrors propose_workflow.
- PermissionLevel::None
- }
-
- fn external_effect(&self) -> bool {
- false
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- 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 instruction = args
- .get("instruction")
- .and_then(Value::as_str)
- .map(str::to_string);
- let require_approval = args
- .get("require_approval")
- .and_then(Value::as_bool)
- .unwrap_or(true);
-
- tracing::debug!(
- target: "flows",
- %name,
- require_approval,
- has_instruction = instruction.is_some(),
- workspace = %self.config.workspace_dir.display(),
- "[flows] revise_workflow: validating revised candidate graph"
- );
-
- let graph = match validate_and_migrate_graph(graph_json) {
- Ok(graph) => graph,
- Err(e) => {
- tracing::debug!(target: "flows", %name, error = %e, "[flows] revise_workflow: validation failed");
- return Ok(ToolResult::error(format!(
- "Revised workflow graph is invalid: {e}. Fix the graph and call \
- revise_workflow again."
- )));
- }
- };
-
- // Full builder hard-gate stack (binding-resolvability → tool-contract →
- // required-arg resolvability) + summary/warning assembly, shared with
- // edit_workflow so the two proposal paths can't drift.
- match ops::build_builder_proposal(
- &self.config,
- "revise_workflow",
- &name,
- &graph,
- require_approval,
- true,
- instruction,
- // revise_workflow takes only an inline graph — no draft/flow handle
- // to echo. The payload still carries persisted:false unconditionally.
- None,
- None,
- )
- .await
- {
- Ok(payload) => Ok(ToolResult::success(serde_json::to_string_pretty(&payload)?)),
- Err(message) => {
- tracing::debug!(target: "flows", %name, "[flows] revise_workflow: a hard gate rejected the revised graph");
- Ok(ToolResult::error(message))
- }
- }
- }
-}
-
-#[cfg(test)]
-#[path = "draft_revise_schema_tests.rs"]
-mod schema_tests;
diff --git a/crates/openhuman-core/src/flows/builder_tools/draft_revise_schema_tests.rs b/crates/openhuman-core/src/flows/builder_tools/draft_revise_schema_tests.rs
deleted file mode 100644
index 398949f3e4..0000000000
--- a/crates/openhuman-core/src/flows/builder_tools/draft_revise_schema_tests.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-use super::*;
-use serde_json::json;
-
-fn expected_revise_workflow() -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "name": {
- "type": "string",
- "description": "Human-readable name for the (revised) proposed flow."
- },
- "graph": {
- "type": "object",
- "description": "The full REVISED tinyflows WorkflowGraph: { name?, nodes: [...], edges: [...] }. Apply your changes to the prior draft and pass the whole graph — see propose_workflow for node kinds and config shapes.",
- "properties": {
- "nodes": { "type": "array" },
- "edges": { "type": "array" }
- },
- "required": ["nodes", "edges"]
- },
- "instruction": {
- "type": "string",
- "description": "The revision instruction that motivated this change (e.g. 'add a Slack step after the summary'). Echoed back for the review card; does not affect validation."
- },
- "require_approval": {
- "type": "boolean",
- "description": "Force a human-approval gate on every outbound action once saved. Defaults to true for agent-proposed flows."
- }
- },
- "required": ["name", "graph"]
- })
-}
-
-#[test]
-fn revise_workflow_static_schema_matches_json_literal() {
- let tool = ReviseWorkflowTool::new(std::sync::Arc::new(crate::config::Config::default()));
- assert_eq!(
- tinytools::Tool::parameters_schema(&tool),
- expected_revise_workflow()
- );
-}
diff --git a/crates/openhuman-core/src/flows/builder_tools/draft_validate.rs b/crates/openhuman-core/src/flows/builder_tools/draft_validate.rs
deleted file mode 100644
index ac2a4e43d2..0000000000
--- a/crates/openhuman-core/src/flows/builder_tools/draft_validate.rs
+++ /dev/null
@@ -1,195 +0,0 @@
-//! `validate_workflow`: run the full gate stack on a draft without proposing (F3).
-
-use std::sync::Arc;
-
-use async_trait::async_trait;
-use serde_json::{json, Value};
-
-use crate::config::Config;
-use crate::flows::ops;
-use tinytools::{PermissionLevel, Tool, ToolResult};
-
-// ─────────────────────────────────────────────────────────────────────────────
-// validate_workflow — standalone check without proposing (F3)
-// ─────────────────────────────────────────────────────────────────────────────
-
-/// `validate_workflow`: run the SAME structural validation + hard-gate stack
-/// the propose/revise/edit/save tools use, but WITHOUT emitting a proposal —
-/// a pure check so the agent can verify a draft (or a saved flow) mid-build.
-///
-/// Returns a structured report `{ ok, structurally_valid, errors[],
-/// error_details[], gate_errors[], warnings[] }`, so a failing check is
-/// fix-and-retry rather than a proposal the user has to reject.
-pub struct ValidateWorkflowTool {
- config: Arc<Config>,
-}
-
-impl ValidateWorkflowTool {
- pub fn new(config: Arc<Config>) -> Self {
- Self { config }
- }
-}
-
-#[async_trait]
-impl Tool for ValidateWorkflowTool {
- fn name(&self) -> &str {
- "validate_workflow"
- }
-
- fn description(&self) -> &str {
- "Check a workflow graph WITHOUT proposing or saving it — the same validation the \
- propose/revise/edit/save tools run, surfaced on its own so you can verify a draft mid-\
- build. Provide the graph to check as exactly one of `draft_id` (a working draft), \
- `flow_id` (a saved flow), or inline `graph` (if several are given, draft_id wins, then \
- flow_id). Returns { ok, structurally_valid, errors, error_details:[{code, message, \
- node_id}], gate_errors, warnings }: `errors` lists EVERY structural problem at once; \
- `gate_errors` lists the hard author-gate failures (unresolvable bindings, unreal tool \
- slugs, unwired required args) checked only once the graph is structurally valid; \
- `warnings` are non-fatal. `ok` is true only when there are no errors and no gate_errors. \
- Read-only."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "draft_id": {
- "type": "string",
- "description": "A working draft to validate. Provide one of draft_id / flow_id / graph (draft_id wins)."
- },
- "flow_id": {
- "type": "string",
- "description": "A saved flow to validate. Provide one of draft_id / flow_id / graph."
- },
- "graph": {
- "type": "object",
- "description": "An inline tinyflows WorkflowGraph to validate. Provide one of draft_id / flow_id / graph.",
- "properties": {
- "nodes": { "type": "array" },
- "edges": { "type": "array" }
- }
- }
- }
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::None
- }
-
- fn external_effect(&self) -> bool {
- false
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- // Resolve the graph to check from exactly one of a working draft, a
- // saved flow, or an inline graph — same precedence (draft_id > flow_id >
- // graph) as edit_workflow, so the sibling tools accept the same handles.
- let draft_id = args
- .get("draft_id")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty());
- let flow_id = args
- .get("flow_id")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty());
- let inline_graph = args.get("graph").filter(|v| !v.is_null());
-
- let graph_json = match (draft_id, flow_id, inline_graph) {
- (Some(id), _, _) => match ops::flows_draft_get(&self.config, id) {
- Ok(outcome) => outcome.value.graph,
- Err(e) => {
- return Ok(ToolResult::error(format!(
- "Could not load draft '{id}' to validate: {e}"
- )));
- }
- },
- (None, Some(id), _) => match ops::load_flow_graph(&self.config, id) {
- Ok(Some(graph)) => serde_json::to_value(&graph)?,
- Ok(None) => {
- return Ok(ToolResult::error(format!("flow '{id}' not found")));
- }
- Err(e) => {
- return Ok(ToolResult::error(format!(
- "Could not load flow '{id}' to validate: {e}"
- )));
- }
- },
- (None, None, Some(graph)) => graph.clone(),
- (None, None, None) => {
- return Ok(ToolResult::error(
- "Provide one of `draft_id` (a working draft), `flow_id` (a saved flow), or \
- `graph` (an inline graph) to validate."
- .to_string(),
- ));
- }
- };
-
- tracing::debug!(
- target: "flows",
- from_draft = draft_id.is_some(),
- from_flow = flow_id.is_some(),
- "[flows] validate_workflow: checking graph (read-only)"
- );
-
- // Structural validation first (every error at once).
- let validation = ops::flows_validate(graph_json.clone()).value;
-
- // Only run the (expensive) hard gates on a structurally-valid graph.
- // A migrate/deserialize error here must fail CLOSED: `validation.valid`
- // only proves the graph passed structural checks, not that the hard
- // gates (unresolvable bindings, unreal tool slugs, unwired required
- // args) ran. Treating the empty `gate_errors` from a caught `Err` as
- // "gates passed" previously reported `ok: true` while silently
- // skipping every hard gate.
- let (gate_errors, gate_check_failed) = if validation.valid {
- match tinyflows::migrate::deserialize_graph(graph_json) {
- Ok(graph) => (ops::run_builder_gates(&self.config, &graph).await, false),
- Err(e) => {
- tracing::warn!(
- target: "flows",
- error = %e,
- "[flows] validate_workflow: graph passed structural validation but \
- failed to migrate/deserialize for gate checks; failing closed"
- );
- (
- vec![format!(
- "hard gates could not run: graph failed to migrate/deserialize ({e})"
- )],
- true,
- )
- }
- }
- } else {
- (Vec::new(), false)
- };
-
- let ok = validate_workflow_report_is_ok(validation.valid, &gate_errors, gate_check_failed);
- let report = json!({
- "ok": ok,
- "structurally_valid": validation.valid,
- "errors": validation.errors,
- "error_details": validation.error_details,
- "gate_errors": gate_errors,
- "warnings": validation.warnings,
- });
- Ok(ToolResult::success(serde_json::to_string_pretty(&report)?))
- }
-}
-
-/// `validate_workflow`'s aggregate verdict (T-m4): `ok` must be true only when
-/// the graph is structurally valid, every hard gate ran, AND every hard gate
-/// passed. Pulled out as a pure function so the fail-closed invariant — a
-/// gate-check failure (e.g. a migrate/deserialize error) must never be
-/// reported as `ok: true` — is unit-testable independent of the async gate
-/// execution and the (currently unreachable, pending future per-node schema
-/// migrations) path that produces `gate_check_failed`.
-pub(super) fn validate_workflow_report_is_ok(
- structurally_valid: bool,
- gate_errors: &[String],
- gate_check_failed: bool,
-) -> bool {
- structurally_valid && gate_errors.is_empty() && !gate_check_failed
-}
diff --git a/crates/openhuman-core/src/flows/builder_tools/dry_run.rs b/crates/openhuman-core/src/flows/builder_tools/dry_run.rs
deleted file mode 100644
index e50c0251e8..0000000000
--- a/crates/openhuman-core/src/flows/builder_tools/dry_run.rs
+++ /dev/null
@@ -1,403 +0,0 @@
-//! `dry_run_workflow`: execute a DRAFT against tinyflows MOCK capabilities (ungated, F7).
-
-use crate::tools::schema_cache::static_schema;
-use std::sync::Arc;
-
-use async_trait::async_trait;
-use serde_json::{json, Value};
-use tinyflows::model::WorkflowGraph;
-
-use crate::config::Config;
-use crate::flows::ops;
-use tinyflows::authoring::validate_and_migrate_graph;
-use tinytools::{PermissionLevel, Tool, ToolResult};
-
-use tinyflows::authoring_report::{self, AuthoringReport};
-use tinyflows::observability::CapturingObserver;
-
-/// Wall-clock bound on a single `dry_run_workflow` mock execution. A malformed
-/// or pathological draft graph must never hang the agent tool-loop; the mock
-/// capabilities are non-blocking echoes, so this is a generous safety net.
-const DRY_RUN_TIMEOUT_SECS: u64 = 30;
-
-// ─────────────────────────────────────────────────────────────────────────────
-// dry_run_workflow — execute a DRAFT against MOCK capabilities (ungated, F7)
-// ─────────────────────────────────────────────────────────────────────────────
-
-/// `dry_run_workflow`: compile a **draft** graph and run it against tinyflows'
-/// deterministic **mock** capabilities, returning the merged node-state output
-/// so the builder can self-verify a proposal before presenting it.
-///
-/// **No real side effects:** the run is wired to
-/// [`tinyflows::caps::mock::mock_capabilities`] — the LLM / tool / HTTP / code
-/// capabilities are echo stubs, so nothing external ever fires regardless of
-/// the graph. The output is explicitly labeled `sandbox: true`.
-///
-/// **Not autonomy-tier gated (F7):** `permission_level()` returns
-/// [`PermissionLevel::None`], so this tool runs on EVERY tier, read-only
-/// included — a read-only agent must be able to self-verify its own proposal.
-/// This is intentional, not an oversight: the mock capabilities never touch a
-/// real integration, so there is nothing for a tier gate to protect. See
-/// `dry_run_allowed_under_readonly_tier` in `builder_tools_tests.rs` for the
-/// pinned regression (an earlier draft of this tool *was* tier-gated via an
-/// unused `SecurityPolicy` field; the field was dead code by the time it
-/// shipped and was removed rather than wired up, since side-effect-free
-/// simulation has no tier to gate against).
-///
-/// **Wiring preflight:** the mock tool invoker is wrapped in the host's
-/// [`PreflightToolInvoker`](crate::flows::tinyflows::caps::PreflightToolInvoker),
-/// so a Composio `tool_call` whose required arg is missing or `=`-resolved to
-/// null fails the dry run with the same actionable, field-naming error a real
-/// run would produce — the echo mocks alone would happily accept a null `to`.
-///
-/// **Null-resolution check (the "produces functionally-broken workflows" fix):**
-/// a required arg can be present *and non-Composio* (a native `oh:` tool, or a
-/// Composio arg the catalog has no cached schema for) and still be wired to a
-/// `=`-expression that silently resolves to `null` — the preflight above only
-/// catches a *missing/null Composio-required* arg, so a graph like that used to
-/// dry-run green and then do nothing at runtime. The run is driven through
-/// [`tinyflows::engine::run_with_observer`] with a [`CapturingObserver`] that
-/// records every node's [`ExecutionStep::diagnostics`](tinyflows::observability::ExecutionStep)
-/// — the `=`-expressions the vendored engine itself traced as null-resolved
-/// (see `tinyflows::expr::resolve_traced`). After the run settles, every
-/// diagnostic on a **`tool_call` node's `args.*` location** is collected; any
-/// hit fails the dry run with `ok: false` and the offending
-/// `{ node_id, location, expression }` list, rather than reporting `ok: true`
-/// for a graph that would silently no-op. Diagnostics on any OTHER
-/// `agent`-node config subfield are NOT fatal here — a null there degrades
-/// output quality but doesn't break execution the way a null tool arg does.
-///
-/// **Agent-prompt null check:** the ONE `agent`-node diagnostic that IS fatal
-/// is a null-resolved **`prompt` itself** (`location == "prompt"`) — `prompt`
-/// is the node's only input channel to the completion, so a `null` there
-/// means the agent runs with a completely EMPTY prompt (the root-cause bug
-/// `config.input_context` and `ops::validate_binding_resolvability`'s static
-/// gate both exist to prevent). Collected separately into
-/// `agent_prompt_nulls` (`{ node_id, location, expression, suggestion }`) and
-/// added to the same `ok: false` condition as `null_resolutions`.
-///
-/// **Agent-`input_context` null check:** the SAME treatment applies to a
-/// null-resolved **`input_context`** (`location == "input_context"`) — since
-/// #4590 this is the agent's primary upstream-data channel (the very field
-/// `prompt`-embedded jq expressions were supposed to stop needing), so a
-/// `null` here is just as execution-breaking as a null `prompt`: the agent
-/// runs with no upstream data at all. Collected separately into
-/// `agent_input_context_nulls` (`{ node_id, location, expression, suggestion }`,
-/// mirroring `agent_prompt_nulls` exactly) and added to the same `ok: false`
-/// condition as `null_resolutions`/`agent_prompt_nulls`.
-///
-/// **`on_error: continue`/`route` does not mask a `tool_call` failure either.**
-/// Those policies convert an executor error (e.g. the required-arg preflight
-/// rejecting a null arg) into a routed error ITEM so the *run* still completes
-/// (`Ok(outcome)`) — the failing node's `ExecutionStep` carries an EMPTY
-/// `diagnostics` (the null check above would miss it) but its `status` is
-/// [`StepStatus::Error`](tinyflows::observability::StepStatus::Error). Every
-/// such `tool_call` step is collected into `node_errors`
-/// (`{ node_id, error }`, the error text read back out of the run's `output`
-/// state — see `authoring_report::AuthoringReport`) and fails the dry run the same as
-/// a null resolution.
-///
-/// **Routing-divergence warning (B15's dry-run blind spot):** none of the
-/// checks above see a node that never ran at all. An `agent`/`tool_call` node
-/// downstream of a `condition` can be silently unexercised because the
-/// sandbox's mock trigger payload has a different *shape* than a real
-/// trigger's (e.g. a webhook's real JSON body vs. the dry run's `{}`
-/// default), so the condition takes a different branch under mock data than
-/// it would at runtime — a graph can dry-run `ok: true` while its most
-/// data-dependent node was never actually checked. After the run settles,
-/// every `agent`/`tool_call` node with no [`ExecutionStep`] in the
-/// [`CapturingObserver`] is collected into `routing_divergence_warnings`
-/// (`{ node_id, condition_node_id, message }`, `condition_node_id` naming the
-/// nearest upstream `condition` node found by walking predecessors — see
-/// `tinyflows::diagnostics::nearest_upstream_condition` — or `null` if none is found). This is a
-/// **warning, not a hard reject**: it never flips `ok` to `false` by itself
-/// (an unexercised branch can be entirely intentional), and is surfaced on
-/// both the `ok: true` and `ok: false` result shapes so the caller can
-/// double-check that node's wiring by hand.
-pub struct DryRunWorkflowTool {
- config: Arc<Config>,
-}
-
-impl DryRunWorkflowTool {
- pub fn new(config: Arc<Config>) -> Self {
- Self { config }
- }
-}
-
-#[async_trait]
-impl Tool for DryRunWorkflowTool {
- fn name(&self) -> &str {
- "dry_run_workflow"
- }
-
- fn description(&self) -> &str {
- "Dry-run a workflow graph in a SANDBOX to self-verify it before \
- proposing. Compiles the graph and executes it against MOCK capabilities \
- — every LLM / tool_call / http_request / code node returns a deterministic \
- echo, so NOTHING real happens (no messages sent, no code run). Returns the \
- simulated per-node output labeled as sandbox output. Use it to catch \
- wiring/routing mistakes; it does NOT prove real integrations work. Provide \
- the graph as exactly one of `draft_id` (a working draft), `flow_id` (a saved \
- flow), or inline `graph` (draft_id wins, then flow_id), plus an optional \
- `input`."
- }
-
- fn parameters_schema(&self) -> Value {
- static_schema!(include_str!("parameters/dry_run_workflow.json"))
- }
-
- fn permission_level(&self) -> PermissionLevel {
- // Mock-only and side-effect-free: nothing external ever fires (all
- // capabilities are echo stubs). So it needs no elevated permission and
- // is available on EVERY tier, read-only included (audit F7) — a
- // read-only agent must be able to self-verify its own proposal.
- PermissionLevel::None
- }
-
- fn external_effect(&self) -> bool {
- // Mock capabilities only — no real outbound effect.
- false
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- // Graph source: exactly one of a working draft, a saved flow, or an
- // inline graph — same precedence (draft_id > flow_id > graph) as the
- // sibling validate/edit tools, so they all accept the same handles.
- let draft_id = args
- .get("draft_id")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty());
- let flow_id = args
- .get("flow_id")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty());
- let inline_graph = args.get("graph").filter(|v| !v.is_null());
-
- let graph_json = match (draft_id, flow_id, inline_graph) {
- (Some(id), _, _) => match ops::flows_draft_get(&self.config, id) {
- Ok(outcome) => outcome.value.graph,
- Err(e) => {
- return Ok(ToolResult::error(format!(
- "Could not load draft '{id}' to dry-run: {e}"
- )));
- }
- },
- (None, Some(id), _) => match ops::load_flow_graph(&self.config, id) {
- Ok(Some(graph)) => serde_json::to_value(&graph)?,
- Ok(None) => {
- return Ok(ToolResult::error(format!("flow '{id}' not found")));
- }
- Err(e) => {
- return Ok(ToolResult::error(format!(
- "Could not load flow '{id}' to dry-run: {e}"
- )));
- }
- },
- (None, None, Some(v)) => v.clone(),
- (None, None, None) => {
- return Ok(ToolResult::error(
- "Provide one of `draft_id` (a working draft), `flow_id` (a saved flow), or \
- `graph` (an inline graph) to dry-run."
- .to_string(),
- ));
- }
- };
- let input = args.get("input").cloned().unwrap_or_else(|| json!({}));
-
- let graph: WorkflowGraph = match validate_and_migrate_graph(graph_json) {
- Ok(graph) => graph,
- Err(e) => {
- return Ok(ToolResult::error(format!(
- "Cannot dry-run an invalid graph: {e}. Fix the graph first."
- )))
- }
- };
-
- tracing::debug!(
- target: "flows",
- node_count = graph.nodes.len(),
- "[flows] dry_run_workflow: compiling + running draft against MOCK capabilities"
- );
-
- let compiled = match tinyflows::compiler::compile(&graph) {
- Ok(c) => c,
- Err(e) => {
- return Ok(ToolResult::error(format!(
- "Draft graph failed to compile: {e}"
- )))
- }
- };
-
- // Wire the schema-aware mock `AgentRunner` so a draft with `agent`
- // nodes exercises the agent-node path during the dry run instead of
- // erroring on a missing capability — the plain `mock_capabilities()`
- // leaves `agent: None`. No real agent turn fires; the mock runner is a
- // deterministic echo, same contract as the other sandbox mocks, except
- // it additionally honors `config.output_parser.schema` (see its doc)
- // so the null-resolution check below doesn't false-positive on an
- // agent node that correctly declared a schema.
- let mut caps = tinyflows::caps::mock::mock_capabilities_with_agent(
- crate::flows::tinyflows::caps::SchemaAwareMockAgentRunner,
- );
- // Plain agent nodes (no `agent_ref`) never reach the runner above —
- // the vendored `agent` node routes them to the `llm` slot instead (see
- // `SchemaAwareMockLlm`'s doc). Swap the vendored `MockLlm` echo for the
- // schema-aware mock so their `output_parser.schema` is honored too,
- // instead of the echo shape failing the sub-port's validation.
- caps.llm = std::sync::Arc::new(crate::flows::tinyflows::caps::SchemaAwareMockLlm);
- // Wiring preflight over the echo mocks (see the struct doc): required
- // Composio args must be present and non-null even in the sandbox.
- caps.tools = std::sync::Arc::new(crate::flows::tinyflows::caps::PreflightToolInvoker {
- config: self.config.clone(),
- inner: caps.tools.clone(),
- });
-
- let observer = Arc::new(CapturingObserver::default());
- let observer_dyn: Arc<dyn tinyflows::observability::RunObserver> = observer.clone();
- let run = tinyflows::engine::run_with_observer(&compiled, input, &caps, &observer_dyn);
- let outcome = match tokio::time::timeout(
- std::time::Duration::from_secs(DRY_RUN_TIMEOUT_SECS),
- run,
- )
- .await
- {
- Ok(Ok(outcome)) => outcome,
- Ok(Err(e)) => {
- // A `stop`-policy `tool_call` whose required arg resolved null
- // aborts the WHOLE run here (via `PreflightToolInvoker`), so
- // the honest per-field diagnostic never reaches the settled-run
- // `null_resolutions` path below. Recover it from the observer:
- // if the abort was caused by a required arg bound to an upstream
- // Composio `tool_call`'s output, the echo mock simply CAN'T
- // produce that field — so surface it as `unverifiable` rather
- // than letting the generic "required arg missing/null" text
- // (which sent the transcript agent re-wiring a correct binding
- // three times) stand alone. WS6.
- let unverifiable_bindings =
- authoring_report::unverifiable_bindings(&graph, &observer.steps());
- if !unverifiable_bindings.is_empty() {
- tracing::debug!(
- target: "flows",
- error = %e,
- unverifiable_count = unverifiable_bindings.len(),
- "[flows] dry_run_workflow: sandbox run aborted on a Composio-upstream \
- binding the echo mock cannot verify — surfacing it honestly"
- );
- return Ok(ToolResult::success(serde_json::to_string_pretty(&json!({
- "sandbox": true,
- "ok": false,
- "error": e.to_string(),
- "unverifiable_bindings": unverifiable_bindings,
- "note": "SANDBOX (mock) output — a tool_call node aborted because a \
- required arg binds to the output of an upstream Composio tool_call, \
- which the sandbox can only ECHO (it never produces real tool output \
- fields). See unverifiable_bindings: each MAY already be wired \
- correctly — confirm the path with get_tool_contract {{ slug }} \
- (output_fields / primary_array_path; Composio results nest under \
- .item.json.data.) or get_tool_output_sample {{ slug, args }} instead \
- of re-wiring blindly. No real side effects occurred.",
- }))?));
- }
- tracing::debug!(target: "flows", error = %e, "[flows] dry_run_workflow: sandbox run errored");
- return Ok(ToolResult::success(serde_json::to_string_pretty(&json!({
- "sandbox": true,
- "ok": false,
- "error": e.to_string(),
- "note": "SANDBOX (mock) output — a node errored during simulation. No real side effects occurred.",
- }))?));
- }
- Err(_elapsed) => {
- return Ok(ToolResult::error(format!(
- "Sandbox dry-run timed out after {DRY_RUN_TIMEOUT_SECS}s"
- )))
- }
- };
-
- // The bucketing and advice wording live upstream (`tinyflows::authoring_report`);
- // this tool keeps the mock capabilities, the timeout and the JSON envelope.
- let AuthoringReport {
- null_resolutions,
- agent_prompt_nulls,
- agent_input_context_nulls,
- node_errors,
- routing_divergence_warnings,
- } = AuthoringReport::build(&graph, &observer.steps(), &outcome.output);
-
- let permissions_manifest =
- crate::flows::ops::compute_approval_manifest(&self.config, &graph).await;
-
- tracing::info!(
- target: "flows",
- node_count = graph.nodes.len(),
- pending_approvals = outcome.pending_approvals.len(),
- null_resolution_count = null_resolutions.len(),
- agent_prompt_null_count = agent_prompt_nulls.len(),
- agent_input_context_null_count = agent_input_context_nulls.len(),
- node_error_count = node_errors.len(),
- routing_divergence_warning_count = routing_divergence_warnings.len(),
- permissions_manifest_count = permissions_manifest.len(),
- "[flows] dry_run_workflow: sandbox run finished"
- );
-
- if !null_resolutions.is_empty()
- || !agent_prompt_nulls.is_empty()
- || !agent_input_context_nulls.is_empty()
- || !node_errors.is_empty()
- {
- tracing::debug!(
- target: "flows",
- ?null_resolutions,
- ?agent_prompt_nulls,
- ?agent_input_context_nulls,
- ?node_errors,
- "[flows] dry_run_workflow: tool_call/agent-prompt/agent-input_context issue(s) \
- found — failing the dry run"
- );
- return Ok(ToolResult::success(serde_json::to_string_pretty(&json!({
- "sandbox": true,
- "ok": false,
- "null_resolutions": null_resolutions,
- "agent_prompt_nulls": agent_prompt_nulls,
- "agent_input_context_nulls": agent_input_context_nulls,
- "node_errors": node_errors,
- "routing_divergence_warnings": routing_divergence_warnings,
- "permissions_manifest": permissions_manifest,
- "message": "These tool_call args resolved to null, an agent node's prompt or \
- input_context resolved to null (an EMPTY prompt — see agent_prompt_nulls — \
- or no upstream data at all — see agent_input_context_nulls), or a tool_call \
- node failed during the sandbox run (even one recovered via on_error: \
- continue/route) — wire null-resolved args from an upstream node's real \
- output (give any agent node an output_parser.schema so its fields are \
- addressable), feed upstream data into a null-resolved agent prompt/ \
- input_context from a real upstream field instead of a jq expression inside \
- the prompt text, and fix or rewire whatever tool_call node_errors names. Also \
- check routing_divergence_warnings: any agent/tool_call node listed there \
- never ran in this sandbox at all because an upstream condition routed the \
- mock data past it — verify that wiring by hand too.",
- }))?));
- }
-
- Ok(ToolResult::success(serde_json::to_string_pretty(&json!({
- "sandbox": true,
- "ok": true,
- "output": outcome.output,
- "pending_approvals": outcome.pending_approvals,
- "null_resolutions": null_resolutions,
- "agent_prompt_nulls": agent_prompt_nulls,
- "agent_input_context_nulls": agent_input_context_nulls,
- "node_errors": node_errors,
- "routing_divergence_warnings": routing_divergence_warnings,
- "permissions_manifest": permissions_manifest,
- "note": "SANDBOX (mock) output — LLM/tool/HTTP/code nodes returned deterministic echoes; NO real side effects occurred. This checks wiring/routing only, not whether real integrations work. \
- If routing_divergence_warnings is non-empty, an agent/tool_call node never ran in \
- this sandbox because an upstream condition routed the mock data past it — that \
- node's wiring is unverified; check it by hand.",
- }))?))
- }
-}
-
-#[cfg(test)]
-#[path = "dry_run_schema_tests.rs"]
-mod schema_tests;
diff --git a/crates/openhuman-core/src/flows/builder_tools/dry_run_schema_tests.rs b/crates/openhuman-core/src/flows/builder_tools/dry_run_schema_tests.rs
deleted file mode 100644
index 488092d152..0000000000
--- a/crates/openhuman-core/src/flows/builder_tools/dry_run_schema_tests.rs
+++ /dev/null
@@ -1,39 +0,0 @@
-use super::*;
-use serde_json::json;
-
-fn expected_dry_run_workflow() -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "draft_id": {
- "type": "string",
- "description": "A working draft to simulate. Provide one of draft_id / flow_id / graph (draft_id wins)."
- },
- "flow_id": {
- "type": "string",
- "description": "A saved flow to simulate. Provide one of draft_id / flow_id / graph."
- },
- "graph": {
- "type": "object",
- "description": "An inline tinyflows WorkflowGraph to simulate: { nodes: [...], edges: [...] }. Provide one of draft_id / flow_id / graph.",
- "properties": {
- "nodes": { "type": "array" },
- "edges": { "type": "array" }
- },
- "required": ["nodes", "edges"]
- },
- "input": {
- "description": "Optional trigger input passed to the run (defaults to {})."
- }
- }
- })
-}
-
-#[test]
-fn dry_run_workflow_static_schema_matches_json_literal() {
- let tool = DryRunWorkflowTool::new(std::sync::Arc::new(crate::config::Config::default()));
- assert_eq!(
- tinytools::Tool::parameters_schema(&tool),
- expected_dry_run_workflow()
- );
-}
diff --git a/crates/openhuman-core/src/flows/builder_tools/flow_reads.rs b/crates/openhuman-core/src/flows/builder_tools/flow_reads.rs
deleted file mode 100644
index 229532e8a8..0000000000
--- a/crates/openhuman-core/src/flows/builder_tools/flow_reads.rs
+++ /dev/null
@@ -1,355 +0,0 @@
-//! Read-only saved-flow tools: history, run listing, flow listing, one flow, one run.
-
-use std::sync::Arc;
-
-use async_trait::async_trait;
-use serde_json::{json, Value};
-
-use crate::config::Config;
-use crate::flows::ops;
-use tinytools::{PermissionLevel, Tool, ToolResult};
-
-// ─────────────────────────────────────────────────────────────────────────────
-// get_flow_history — read-only: prior graph snapshots (F6)
-// ─────────────────────────────────────────────────────────────────────────────
-
-/// `get_flow_history`: read a saved flow's revision history — the prior graph
-/// snapshots captured on each update. Lets the agent see what changed and pick
-/// a revision to roll back to (the user drives the actual rollback RPC).
-pub struct GetFlowHistoryTool {
- config: Arc<Config>,
-}
-
-impl GetFlowHistoryTool {
- pub fn new(config: Arc<Config>) -> Self {
- Self { config }
- }
-}
-
-#[async_trait]
-impl Tool for GetFlowHistoryTool {
- fn name(&self) -> &str {
- "get_flow_history"
- }
-
- fn description(&self) -> &str {
- "List a saved flow's revision history — the prior graph snapshots captured automatically \
- on each update (newest first, capped). Read-only. Returns a JSON array of { id, flow_id, \
- graph, name, require_approval, created_at }. Use it to see what a flow looked like before \
- a change, or to find the revision id the user can roll back to."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "flow_id": { "type": "string", "description": "The saved flow whose history to list." },
- "limit": { "type": "integer", "description": "Max revisions to return (default 20)." }
- },
- "required": ["flow_id"],
- "additionalProperties": false
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::None
- }
-
- fn external_effect(&self) -> bool {
- false
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- 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' parameter".to_string())),
- };
- let limit = args
- .get("limit")
- .and_then(Value::as_u64)
- .map(|n| n as usize)
- .unwrap_or(20);
- tracing::debug!(target: "flows", %flow_id, limit, "[flows] get_flow_history: listing revisions (read-only)");
- match ops::flows_get_history(&self.config, &flow_id, limit) {
- Ok(outcome) => Ok(ToolResult::success(serde_json::to_string_pretty(
- &json!({ "revisions": outcome.value }),
- )?)),
- Err(e) => Ok(ToolResult::error(format!(
- "Could not load history for flow '{flow_id}': {e}"
- ))),
- }
- }
-}
-
-/// `list_flow_runs`: read-only listing of a saved flow's recent runs (id /
-/// status / timestamps), so the agent can FIND a failing run to diagnose
-/// instead of needing a run_id handed to it externally — the missing first step
-/// of the self-debug loop (audit F4).
-pub struct ListFlowRunsTool {
- config: Arc<Config>,
-}
-
-impl ListFlowRunsTool {
- pub fn new(config: Arc<Config>) -> Self {
- Self { config }
- }
-}
-
-#[async_trait]
-impl Tool for ListFlowRunsTool {
- fn name(&self) -> &str {
- "list_flow_runs"
- }
-
- fn description(&self) -> &str {
- "List a saved flow's recent runs (newest first) so you can find one to diagnose with \
- get_flow_run. Read-only. Returns a JSON array of runs { id, flow_id, thread_id, status, \
- started_at, finished_at?, error? }. `id`/`thread_id` is the run id you pass to \
- get_flow_run / resume_flow_run / cancel_flow_run."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "flow_id": { "type": "string", "description": "The saved flow whose runs to list." },
- "limit": { "type": "integer", "description": "Max runs to return (default 20)." }
- },
- "required": ["flow_id"],
- "additionalProperties": false
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::None
- }
-
- fn external_effect(&self) -> bool {
- false
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- 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' parameter".to_string())),
- };
- let limit = args
- .get("limit")
- .and_then(Value::as_u64)
- .map(|n| n as usize)
- .unwrap_or(20);
- tracing::debug!(target: "flows", %flow_id, limit, "[flows] list_flow_runs: listing runs (read-only)");
- match ops::flows_list_runs(&self.config, &flow_id, limit).await {
- Ok(outcome) => Ok(ToolResult::success(serde_json::to_string_pretty(
- &json!({ "runs": outcome.value }),
- )?)),
- Err(e) => Ok(ToolResult::error(format!(
- "Could not list runs for flow '{flow_id}': {e}"
- ))),
- }
- }
-}
-
-// ─────────────────────────────────────────────────────────────────────────────
-// list_flows — read-only: saved flow summaries
-// ─────────────────────────────────────────────────────────────────────────────
-
-/// `list_flows`: read-only listing of saved flows (id / name / enabled /
-/// last_status) so the builder can reference, clone, or avoid duplicating an
-/// existing automation.
-pub struct ListFlowsTool {
- config: Arc<Config>,
-}
-
-impl ListFlowsTool {
- pub fn new(config: Arc<Config>) -> Self {
- Self { config }
- }
-}
-
-#[async_trait]
-impl Tool for ListFlowsTool {
- fn name(&self) -> &str {
- "list_flows"
- }
-
- fn description(&self) -> &str {
- "List the user's saved automation flows (tinyflows workflows). Read-only. \
- Returns a JSON array of { id, name, enabled, last_status, last_run_at } so \
- you can reference an existing flow, clone its structure (fetch the full \
- graph with get_flow), or avoid proposing a duplicate."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({ "type": "object", "properties": {}, "additionalProperties": false })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::None
- }
-
- fn external_effect(&self) -> bool {
- false
- }
-
- async fn execute(&self, _args: Value) -> anyhow::Result<ToolResult> {
- tracing::debug!(target: "flows", "[flows] list_flows: listing saved flows (read-only)");
- match ops::flows_list(&self.config).await {
- Ok(outcome) => {
- let flows: Vec<Value> = outcome
- .value
- .iter()
- .map(|f| {
- json!({
- "id": f.id,
- "name": f.name,
- "enabled": f.enabled,
- "last_status": f.last_status,
- "last_run_at": f.last_run_at,
- })
- })
- .collect();
- Ok(ToolResult::success(serde_json::to_string_pretty(
- &json!({ "flows": flows }),
- )?))
- }
- Err(e) => Ok(ToolResult::error(format!("Failed to list flows: {e}"))),
- }
- }
-}
-
-// ─────────────────────────────────────────────────────────────────────────────
-// get_flow — read-only: a saved flow's graph
-// ─────────────────────────────────────────────────────────────────────────────
-
-/// `get_flow`: read-only fetch of a saved flow's full [`WorkflowGraph`] by id,
-/// so the builder can clone or extend an existing automation.
-pub struct GetFlowTool {
- config: Arc<Config>,
-}
-
-impl GetFlowTool {
- pub fn new(config: Arc<Config>) -> Self {
- Self { config }
- }
-}
-
-#[async_trait]
-impl Tool for GetFlowTool {
- fn name(&self) -> &str {
- "get_flow"
- }
-
- fn description(&self) -> &str {
- "Fetch a saved flow's full tinyflows WorkflowGraph (nodes + edges) plus \
- its metadata by id. Read-only. Use it to clone or extend an existing \
- automation — pass the returned graph (possibly modified) to \
- revise_workflow or dry_run_workflow."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "id": { "type": "string", "description": "The saved flow's id (from list_flows)." }
- },
- "required": ["id"],
- "additionalProperties": false
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::None
- }
-
- fn external_effect(&self) -> bool {
- false
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let id = match args.get("id").and_then(Value::as_str).map(str::trim) {
- Some(id) if !id.is_empty() => id.to_string(),
- _ => return Ok(ToolResult::error("Missing 'id' parameter".to_string())),
- };
- tracing::debug!(target: "flows", flow_id = %id, "[flows] get_flow: fetching saved flow (read-only)");
- match ops::flows_get(&self.config, &id).await {
- Ok(outcome) => {
- let f = outcome.value;
- let graph = serde_json::to_value(&f.graph)?;
- Ok(ToolResult::success(serde_json::to_string_pretty(&json!({
- "id": f.id,
- "name": f.name,
- "enabled": f.enabled,
- "require_approval": f.require_approval,
- "last_status": f.last_status,
- "graph": graph,
- }))?))
- }
- Err(e) => Ok(ToolResult::error(format!("Failed to get flow '{id}': {e}"))),
- }
- }
-}
-
-// ─────────────────────────────────────────────────────────────────────────────
-// get_flow_run — read-only: a run's steps (for repair/debugging)
-// ─────────────────────────────────────────────────────────────────────────────
-
-/// `get_flow_run`: read-only fetch of a single flow run's step records, so the
-/// builder can diagnose a failure and propose a repair.
-pub struct GetFlowRunTool {
- config: Arc<Config>,
-}
-
-impl GetFlowRunTool {
- pub fn new(config: Arc<Config>) -> Self {
- Self { config }
- }
-}
-
-#[async_trait]
-impl Tool for GetFlowRunTool {
- fn name(&self) -> &str {
- "get_flow_run"
- }
-
- fn description(&self) -> &str {
- "Fetch a single flow run's record by run id: status, per-node step \
- results, any pending approvals, and the error (if it failed). Read-only. \
- Use it to debug a failing flow from an error report and propose a repair."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "run_id": { "type": "string", "description": "The run id (also the run's thread_id)." }
- },
- "required": ["run_id"],
- "additionalProperties": false
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::None
- }
-
- fn external_effect(&self) -> bool {
- false
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let run_id = match args.get("run_id").and_then(Value::as_str).map(str::trim) {
- Some(id) if !id.is_empty() => id.to_string(),
- _ => return Ok(ToolResult::error("Missing 'run_id' parameter".to_string())),
- };
- tracing::debug!(target: "flows", %run_id, "[flows] get_flow_run: fetching run record (read-only)");
- match ops::flows_get_run(&self.config, &run_id).await {
- Ok(outcome) => Ok(ToolResult::success(serde_json::to_string_pretty(
- &outcome.value,
- )?)),
- Err(e) => Ok(ToolResult::error(format!(
- "Failed to get flow run '{run_id}': {e}"
- ))),
- }
- }
-}
diff --git a/crates/openhuman-core/src/flows/builder_tools/kind_reads.rs b/crates/openhuman-core/src/flows/builder_tools/kind_reads.rs
deleted file mode 100644
index f85bb6f633..0000000000
--- a/crates/openhuman-core/src/flows/builder_tools/kind_reads.rs
+++ /dev/null
@@ -1,252 +0,0 @@
-//! Read-only DSL/registry tools: agent definitions, node kinds, and node-kind contracts (F2).
-
-use async_trait::async_trait;
-use serde_json::{json, Value};
-
-use tinytools::{PermissionLevel, Tool, ToolResult};
-
-// ─────────────────────────────────────────────────────────────────────────────
-// list_agent_definitions — read-only: selectable definitions for an `agent` node
-// ─────────────────────────────────────────────────────────────────────────────
-
-/// `list_agent_definitions`: read-only listing of the agent **definitions** an `agent`
-/// node can select via `agent_ref` (agent_memory, vision_agent, planner, …).
-///
-/// Grounds the builder's `agent_ref` choice in real registry ids — the agent
-/// analogue of `search_tool_catalog` for `tool_call` slugs — so it never
-/// hallucinates an agent kind. Returns `{ id, name, description, model, tools,
-/// tags }` for every enabled registered agent.
-pub struct ListAgentDefinitionsTool;
-
-impl ListAgentDefinitionsTool {
- /// Builds the tool (no configuration — reads the process-global registry).
- #[must_use]
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for ListAgentDefinitionsTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl Tool for ListAgentDefinitionsTool {
- fn name(&self) -> &str {
- "list_agent_definitions"
- }
-
- fn description(&self) -> &str {
- "List the agent KINDS an `agent` node can run via its `agent_ref` config \
- field (e.g. agent_memory, vision_agent, presentation_agent). Read-only. Returns \
- a JSON array of { id, name, description, model, tools, tags }. Use this to \
- pick a real agent_ref — a memory-lookup step should reference agent_memory, \
- an image-reading step vision_agent — instead of guessing an id. Note: setting \
- agent_ref runs the step as a REAL agent turn (its own `run_single`), with \
- the selected specialist's full persona, model, tool loop, and iteration \
- cap — not just a persona-flavored completion. A plain `agent` node with \
- no agent_ref only gets the default LLM plus its own inline `tools` list; \
- it cannot run code, search the web, or use any specialist's tools."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({ "type": "object", "properties": {}, "additionalProperties": false })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::None
- }
-
- fn external_effect(&self) -> bool {
- false
- }
-
- async fn execute(&self, _args: Value) -> anyhow::Result<ToolResult> {
- tracing::debug!(target: "flows", "[flows] list_agent_definitions: listing registered definitions (read-only)");
- match crate::agent::registry::list_agents(false).await {
- Ok(agents) => {
- let definitions: Vec<Value> = agents
- .iter()
- .map(|a| {
- json!({
- "id": a.id,
- "name": a.name,
- "description": a.description,
- "model": a.model,
- "tools": a.tool_allowlist,
- "tags": a.tags,
- })
- })
- .collect();
- Ok(ToolResult::success(serde_json::to_string_pretty(
- &json!({ "agent_definitions": definitions }),
- )?))
- }
- Err(e) => Ok(ToolResult::error(format!(
- "Failed to list agent definitions: {e}"
- ))),
- }
- }
-}
-
-// ─────────────────────────────────────────────────────────────────────────────
-// list_node_kinds / get_node_kind_contract — queryable DSL schema (F2)
-// ─────────────────────────────────────────────────────────────────────────────
-
-/// `list_node_kinds`: enumerate the 14 tinyflows node kinds with a one-line
-/// summary each. The DSL counterpart of `search_tool_catalog` for Composio
-/// actions — a cheap first call to orient before fetching a full contract.
-pub struct ListNodeKindsTool;
-
-impl ListNodeKindsTool {
- /// Builds the tool (no configuration — the contracts are static).
- #[must_use]
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for ListNodeKindsTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl Tool for ListNodeKindsTool {
- fn name(&self) -> &str {
- "list_node_kinds"
- }
-
- fn description(&self) -> &str {
- "List the 14 tinyflows node kinds you can put in a WorkflowGraph, each with a one-line \
- summary and its config field names. Read-only, no args. Returns a JSON array of { kind, \
- summary, required_config, optional_config }. Call get_node_kind_contract { kind } for the \
- full config-field shapes, ports, an example node, and authoring gotchas of any one kind — \
- this is the machine-readable DSL schema, so you don't have to rely on prose or memory."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({ "type": "object", "properties": {}, "additionalProperties": false })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::None
- }
-
- fn external_effect(&self) -> bool {
- false
- }
-
- async fn execute(&self, _args: Value) -> anyhow::Result<ToolResult> {
- tracing::debug!(target: "flows", "[flows] list_node_kinds: enumerating node kinds (read-only)");
- let kinds: Vec<Value> = crate::flows::all_node_kind_contracts()
- .iter()
- .map(|c| {
- let required: Vec<&str> = c
- .config_fields
- .iter()
- .filter(|f| f.required)
- .map(|f| f.name.as_str())
- .collect();
- let optional: Vec<&str> = c
- .config_fields
- .iter()
- .filter(|f| !f.required)
- .map(|f| f.name.as_str())
- .collect();
- json!({
- "kind": c.kind,
- "summary": c.summary,
- "required_config": required,
- "optional_config": optional,
- })
- })
- .collect();
- Ok(ToolResult::success(serde_json::to_string_pretty(
- &json!({ "node_kinds": kinds }),
- )?))
- }
-}
-
-/// `get_node_kind_contract`: the FULL machine-readable contract for one node
-/// kind — config fields (name/required/type/description/enum), ports, a valid
-/// example node, and the authoring gotchas. Mirrors `get_tool_contract` for
-/// Composio actions but for the DSL itself.
-pub struct GetNodeKindContractTool;
-
-impl GetNodeKindContractTool {
- /// Builds the tool (no configuration — the contracts are static).
- #[must_use]
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for GetNodeKindContractTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl Tool for GetNodeKindContractTool {
- fn name(&self) -> &str {
- "get_node_kind_contract"
- }
-
- fn description(&self) -> &str {
- "Fetch the FULL contract for ONE tinyflows node kind before you author a node of that \
- kind. Read-only. Returns { kind, summary, description, config_fields:[{name, required, \
- value_type, description, enum_values?}], ports:{inputs, outputs}, example, notes }. Use \
- config_fields for exactly what to put in config, ports for how to wire branch edges (the \
- branch label goes on the edge's from_port), and notes for the envelope/gotcha rules that \
- otherwise silently resolve to null. Find the kind names via list_node_kinds."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "kind": {
- "type": "string",
- "description": format!(
- "One of the {} node kinds, e.g. 'tool_call' (from list_node_kinds).",
- tinyflows::catalog::NODE_KINDS.len()
- ),
- "enum": tinyflows::catalog::NODE_KINDS,
- }
- },
- "required": ["kind"],
- "additionalProperties": false
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::None
- }
-
- fn external_effect(&self) -> bool {
- false
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let kind = match args.get("kind").and_then(Value::as_str).map(str::trim) {
- Some(k) if !k.is_empty() => k.to_string(),
- _ => return Ok(ToolResult::error("Missing 'kind' parameter".to_string())),
- };
- tracing::debug!(target: "flows", %kind, "[flows] get_node_kind_contract: fetching contract (read-only)");
- match crate::flows::node_kind_contract(&kind) {
- Some(contract) => Ok(ToolResult::success(serde_json::to_string_pretty(
- &contract,
- )?)),
- None => Ok(ToolResult::error(format!(
- "'{kind}' is not a tinyflows node kind — call list_node_kinds for the {} valid \
- kinds.",
- tinyflows::catalog::NODE_KINDS.len()
- ))),
- }
- }
-}
diff --git a/crates/openhuman-core/src/flows/builder_tools/parameters/dry_run_workflow.json b/crates/openhuman-core/src/flows/builder_tools/parameters/dry_run_workflow.json
deleted file mode 100644
index d38de1736c..0000000000
--- a/crates/openhuman-core/src/flows/builder_tools/parameters/dry_run_workflow.json
+++ /dev/null
@@ -1,32 +0,0 @@
-{
- "type": "object",
- "properties": {
- "draft_id": {
- "type": "string",
- "description": "A working draft to simulate. Provide one of draft_id / flow_id / graph (draft_id wins)."
- },
- "flow_id": {
- "type": "string",
- "description": "A saved flow to simulate. Provide one of draft_id / flow_id / graph."
- },
- "graph": {
- "type": "object",
- "description": "An inline tinyflows WorkflowGraph to simulate: { nodes: [...], edges: [...] }. Provide one of draft_id / flow_id / graph.",
- "properties": {
- "nodes": {
- "type": "array"
- },
- "edges": {
- "type": "array"
- }
- },
- "required": [
- "nodes",
- "edges"
- ]
- },
- "input": {
- "description": "Optional trigger input passed to the run (defaults to {})."
- }
- }
-}
diff --git a/crates/openhuman-core/src/flows/builder_tools/parameters/edit_workflow.json b/crates/openhuman-core/src/flows/builder_tools/parameters/edit_workflow.json
deleted file mode 100644
index c4dea706c5..0000000000
--- a/crates/openhuman-core/src/flows/builder_tools/parameters/edit_workflow.json
+++ /dev/null
@@ -1,56 +0,0 @@
-{
- "type": "object",
- "properties": {
- "draft_id": {
- "type": "string",
- "description": "A working draft to edit as the base; the applied edit is written back to it. Provide one of draft_id / flow_id / graph."
- },
- "flow_id": {
- "type": "string",
- "description": "The saved flow to edit as the base graph. Provide one of draft_id / flow_id / graph."
- },
- "graph": {
- "type": "object",
- "description": "An inline base tinyflows WorkflowGraph to edit. Provide one of draft_id / flow_id / graph.",
- "properties": {
- "nodes": {
- "type": "array"
- },
- "edges": {
- "type": "array"
- }
- }
- },
- "ops": {
- "type": "array",
- "description": "The structured edits, applied in order. Each item is { op, ... } — see the tool description for op shapes.",
- "items": {
- "type": "object",
- "properties": {
- "op": {
- "type": "string"
- }
- },
- "required": [
- "op"
- ]
- },
- "minItems": 1
- },
- "name": {
- "type": "string",
- "description": "Name for the resulting proposed flow. Defaults to the base flow's name."
- },
- "instruction": {
- "type": "string",
- "description": "The change that motivated these ops (echoed back on the review card)."
- },
- "require_approval": {
- "type": "boolean",
- "description": "Force a human-approval gate on every outbound action once saved. Defaults to true."
- }
- },
- "required": [
- "ops"
- ]
-}
diff --git a/crates/openhuman-core/src/flows/builder_tools/parameters/revise_workflow.json b/crates/openhuman-core/src/flows/builder_tools/parameters/revise_workflow.json
deleted file mode 100644
index 90ab0584cf..0000000000
--- a/crates/openhuman-core/src/flows/builder_tools/parameters/revise_workflow.json
+++ /dev/null
@@ -1,37 +0,0 @@
-{
- "type": "object",
- "properties": {
- "name": {
- "type": "string",
- "description": "Human-readable name for the (revised) proposed flow."
- },
- "graph": {
- "type": "object",
- "description": "The full REVISED tinyflows WorkflowGraph: { name?, nodes: [...], edges: [...] }. Apply your changes to the prior draft and pass the whole graph — see propose_workflow for node kinds and config shapes.",
- "properties": {
- "nodes": {
- "type": "array"
- },
- "edges": {
- "type": "array"
- }
- },
- "required": [
- "nodes",
- "edges"
- ]
- },
- "instruction": {
- "type": "string",
- "description": "The revision instruction that motivated this change (e.g. 'add a Slack step after the summary'). Echoed back for the review card; does not affect validation."
- },
- "require_approval": {
- "type": "boolean",
- "description": "Force a human-approval gate on every outbound action once saved. Defaults to true for agent-proposed flows."
- }
- },
- "required": [
- "name",
- "graph"
- ]
-}
diff --git a/crates/openhuman-core/src/flows/builder_tools/parameters/save_workflow.json b/crates/openhuman-core/src/flows/builder_tools/parameters/save_workflow.json
deleted file mode 100644
index 33277187aa..0000000000
--- a/crates/openhuman-core/src/flows/builder_tools/parameters/save_workflow.json
+++ /dev/null
@@ -1,37 +0,0 @@
-{
- "type": "object",
- "properties": {
- "flow_id": {
- "type": "string",
- "description": "Id of the EXISTING saved flow to write the graph to (the persistence target — always required)."
- },
- "draft_id": {
- "type": "string",
- "description": "A working draft whose graph to persist onto the flow. Provide this OR inline `graph`; if both are given, draft_id wins."
- },
- "graph": {
- "type": "object",
- "description": "The full tinyflows WorkflowGraph to persist: { name?, nodes: [...], edges: [...] }. Provide this OR `draft_id`. Same shape as propose_workflow.",
- "properties": {
- "nodes": {
- "type": "array"
- },
- "edges": {
- "type": "array"
- }
- },
- "required": [
- "nodes",
- "edges"
- ]
- },
- "name": {
- "type": "string",
- "description": "Optional new human-readable name for the flow."
- }
- },
- "required": [
- "flow_id"
- ],
- "additionalProperties": false
-}
diff --git a/crates/openhuman-core/src/flows/builder_tools/persistence.rs b/crates/openhuman-core/src/flows/builder_tools/persistence.rs
deleted file mode 100644
index 6179416f25..0000000000
--- a/crates/openhuman-core/src/flows/builder_tools/persistence.rs
+++ /dev/null
@@ -1,480 +0,0 @@
-//! Persistence tools: `create_workflow`, `duplicate_flow`, and `save_workflow`.
-//! Created/duplicated flows are always born DISABLED; save never touches enablement.
-
-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;
-use tinyflows::authoring::validate_and_migrate_graph;
-use tinytools::{PermissionLevel, Tool, ToolResult};
-
-/// `create_workflow`: the gated create tool (audit F4/F12). Persists a NEW
-/// flow, always **born disabled** (enable stays human-only) and behind the
-/// forced `require_approval` floor for side-effect graphs. Write + approval
-/// gated. This is the deliberate widening the Phase 3 rails (versioning,
-/// events, history) make safe.
-pub struct CreateWorkflowTool {
- config: Arc<Config>,
-}
-
-impl CreateWorkflowTool {
- pub fn new(config: Arc<Config>) -> Self {
- Self { config }
- }
-}
-
-#[async_trait]
-impl Tool for CreateWorkflowTool {
- fn name(&self) -> &str {
- "create_workflow"
- }
-
- fn description(&self) -> &str {
- "Create a NEW saved flow from a graph. Approval-gated. The flow is ALWAYS created DISABLED \
- (only the user can enable it via the UI) and inherits the forced approval gate for any \
- outbound action — so a created flow can never fire on its own without an explicit human \
- enable. Runs the same author hard-gates as save. Params: { name, graph, require_approval? }. \
- Prefer propose_workflow when the user just wants to review a design; use this when they've \
- explicitly asked you to create the flow."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "name": { "type": "string", "description": "Human-readable flow name." },
- "graph": {
- "type": "object",
- "description": "The tinyflows WorkflowGraph: { nodes: [...], edges: [...] }.",
- "properties": { "nodes": { "type": "array" }, "edges": { "type": "array" } },
- "required": ["nodes", "edges"]
- },
- "require_approval": { "type": "boolean", "description": "Force the approval gate (defaults true)." }
- },
- "required": ["name", "graph"],
- "additionalProperties": false
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::Write
- }
-
- fn external_effect(&self) -> bool {
- // Persists a new flow definition.
- true
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let name = match args.get("name").and_then(Value::as_str).map(str::trim) {
- Some(n) if !n.is_empty() => n.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);
-
- // Same structural + hard-gate stack an agent save must pass.
- if let Err(msg) = ops::strict_gate(&self.config, &graph_json).await {
- return Ok(ToolResult::error(format!(
- "{msg}\n\nFix the graph and call create_workflow again."
- )));
- }
-
- tracing::info!(target: "flows", %name, "[flows] create_workflow: agent-initiated create (born disabled)");
- let flow = match ops::flows_create(&self.config, name, graph_json, require_approval).await {
- Ok(outcome) => outcome.value,
- Err(e) => return Ok(ToolResult::error(format!("Could not create flow: {e}"))),
- };
-
- // Force born-disabled: enable stays human-only, even for a manual-trigger
- // graph that flows_create would otherwise create enabled. `flows_create`
- // and this force-disable are two separate writes — not one transaction —
- // so there is necessarily a brief window between them where the row is
- // persisted `enabled: true` before this call disables it. This fix does
- // not close that window; it only stops MISREPORTING the outcome when the
- // disable itself fails.
- //
- // T-m3: `flows_set_enabled(.., false)` can fail (store error, flow
- // deleted concurrently, …). That used to be only `warn!`-logged while
- // the response unconditionally claimed `"enabled": false` — so a
- // manual-trigger flow that flows_create left enabled would stay
- // enabled while the agent told the user it was disabled. Track the
- // real post-attempt state and report THAT.
- let mut disable_succeeded = true;
- if flow.enabled {
- match ops::flows_set_enabled(&self.config, &flow.id, false).await {
- Ok(_) => {}
- Err(e) => {
- disable_succeeded = false;
- tracing::warn!(
- target: "flows",
- flow_id = %flow.id,
- error = %e,
- "[flows] create_workflow: could not force-disable the new flow — it \
- remains ENABLED; reporting the true state, not the intended one"
- );
- }
- }
- }
- let (enabled, note) = create_workflow_report(flow.enabled, disable_succeeded);
-
- Ok(ToolResult::success(serde_json::to_string_pretty(&json!({
- "type": "workflow_created",
- "flow_id": flow.id,
- "name": flow.name,
- "enabled": enabled,
- "require_approval": flow.require_approval,
- "note": note,
- }))?))
- }
-}
-
-/// `create_workflow`'s reported `enabled` state + note (T-m3): derived from
-/// whether the flow was born enabled (`born_enabled`, from `flows_create`'s
-/// Rule 1) and whether the subsequent force-disable attempt succeeded
-/// (`disable_succeeded`, ignored when no attempt was made). Pulled out as a
-/// pure function so the fail-HONEST invariant — the response must reflect
-/// the flow's real post-attempt state, not the intended one — is
-/// unit-testable without forcing a genuine concurrent store failure between
-/// `flows_create` and `flows_set_enabled`.
-pub(super) fn create_workflow_report(
- born_enabled: bool,
- disable_succeeded: bool,
-) -> (bool, &'static str) {
- let enabled = born_enabled && !disable_succeeded;
- let note = if enabled {
- "Flow created, but it could NOT be force-disabled (see the tool result for the \
- underlying error) — it is currently ENABLED. Tell the user and ask them to disable it \
- manually if that was not intended."
- } else {
- "Flow created DISABLED. The user must enable it explicitly before it can run."
- };
- (enabled, note)
-}
-
-/// `duplicate_flow`: create an independent, DISABLED copy of a saved flow — the
-/// clone-then-edit pattern. Write-class.
-pub struct DuplicateFlowTool {
- config: Arc<Config>,
-}
-
-impl DuplicateFlowTool {
- pub fn new(config: Arc<Config>) -> Self {
- Self { config }
- }
-}
-
-#[async_trait]
-impl Tool for DuplicateFlowTool {
- fn name(&self) -> &str {
- "duplicate_flow"
- }
-
- fn description(&self) -> &str {
- "Duplicate a saved flow: create an independent, DISABLED copy of its graph under a new id \
- (name suffixed \" (copy)\"). The copy never fires until the user enables it. Use this for \
- the clone-then-edit pattern (edit_workflow the copy). Params: { flow_id }."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": { "flow_id": { "type": "string", "description": "The saved flow to duplicate." } },
- "required": ["flow_id"],
- "additionalProperties": false
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::Write
- }
-
- fn external_effect(&self) -> bool {
- true
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- 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' parameter".to_string())),
- };
- tracing::info!(target: "flows", %flow_id, "[flows] duplicate_flow: agent-initiated duplicate");
- match ops::flows_duplicate(&self.config, &flow_id).await {
- Ok(outcome) => {
- let flow = outcome.value;
- Ok(ToolResult::success(serde_json::to_string_pretty(&json!({
- "type": "workflow_duplicated",
- "flow_id": flow.id,
- "name": flow.name,
- "enabled": flow.enabled,
- }))?))
- }
- Err(e) => Ok(ToolResult::error(format!("Could not duplicate flow: {e}"))),
- }
- }
-}
-
-// ─────────────────────────────────────────────────────────────────────────────
-// save_workflow — persist a built graph onto an EXISTING saved flow
-// ─────────────────────────────────────────────────────────────────────────────
-
-/// `save_workflow`: persist a validated graph (and optionally a new name) onto
-/// an **existing, already-saved** flow via [`ops::flows_update`] — the same
-/// validate-and-migrate path the UI's Save uses.
-///
-/// It was originally added as a narrow, deliberate exception to the belt's
-/// "propose, never persist" invariant (for the Flows prompt bar's
-/// instant-create path, where the host creates the flow *before* delegating
-/// and hands the agent its `flow_id`) — before [`CreateWorkflowTool`] and
-/// [`DuplicateFlowTool`] existed, this was the belt's only write. Both now
-/// exist, so `save_workflow` is one of three persistence tools, not the sole
-/// one. Its own remaining boundaries:
-///
-/// - **Update-only.** It requires an existing `flow_id`; it never fabricates
-/// one. Creating a flow is [`CreateWorkflowTool`]/[`DuplicateFlowTool`]'s
-/// job — `save_workflow` can only write onto a flow that already exists
-/// (whether the host, the user, or an earlier `create_workflow`/
-/// `duplicate_flow` call made it).
-/// - **Never touches enablement or the approval gate.** `enabled` and
-/// `require_approval` are not parameters; whatever the user set stays —
-/// except that saving a graph whose trigger just transitioned from manual
-/// to automatic on an already-enabled flow auto-disables it (see
-/// [`ops::flows_update`]'s own doc for that guard).
-/// - **Real persistence, real consequences.** Saving a `schedule`/`app_event`
-/// trigger onto an ENABLED flow arms it (the trigger binds and will fire on
-/// its own) — hence `PermissionLevel::Write`. The description tells the agent
-/// to dry-run first and to say what it saved.
-pub struct SaveWorkflowTool {
- config: Arc<Config>,
-}
-
-impl SaveWorkflowTool {
- pub fn new(config: Arc<Config>) -> Self {
- Self { config }
- }
-}
-
-#[async_trait]
-impl Tool for SaveWorkflowTool {
- fn name(&self) -> &str {
- "save_workflow"
- }
-
- fn description(&self) -> &str {
- "Save a workflow graph onto an EXISTING saved flow (by `flow_id`), persisting it. \
- This is the ONLY builder tool that writes onto a saved flow — edit/validate/dry_run \
- never do. Use it after the user asked you to build/update a workflow and you have \
- dry-run-verified the graph. The graph source is either `draft_id` (a working draft — \
- the usual case after editing with edit_workflow; draft_id wins if both are given) or \
- an inline `graph`; `flow_id` is always required as the persistence TARGET. It \
- validates and writes the graph (and optional new `name`) to that flow. It can NOT \
- create a new flow, and it never touches the approval gate — but it CAN \
- auto-disable the flow when the trigger transitions from manual to automatic \
- (schedule/webhook/app_event), so a save never silently arms a trigger that wasn't \
- already live; the returned `warnings` will explain it when that happens. NOTE: if \
- the flow was ALREADY enabled with an automatic trigger and stays automatic, saving \
- re-arms it live — it will start firing on its own. Always tell the user what you \
- saved (including any auto-disable). Params: { flow_id, draft_id? | graph?, name? }."
- }
-
- fn parameters_schema(&self) -> Value {
- static_schema!(include_str!("parameters/save_workflow.json"))
- }
-
- fn permission_level(&self) -> PermissionLevel {
- // Persists a flow definition; on an enabled flow this can arm a
- // self-firing trigger — gate like a Write-class action.
- PermissionLevel::Write
- }
-
- fn external_effect(&self) -> bool {
- // Persistence is local (no message/HTTP/code fires at save time); the
- // flow's own runs — and their approval gate — govern real effects.
- false
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- 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' — save_workflow only updates an EXISTING saved flow. \
- If there is no flow yet, return the proposal and let the user save it."
- .to_string(),
- ))
- }
- };
- // Graph source: a working draft (the usual post-edit_workflow handle) or
- // an inline graph. `flow_id` above is the persistence TARGET, always
- // required; the draft only supplies the graph to write. If both a
- // draft_id and an inline graph are given, the draft wins (it is the
- // durable working copy the agent just iterated on).
- let draft_id = args
- .get("draft_id")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty());
- let graph_json =
- if let Some(id) = draft_id {
- match ops::flows_draft_get(&self.config, id) {
- Ok(outcome) => outcome.value.graph,
- Err(e) => {
- return Ok(ToolResult::error(format!(
- "Could not load draft '{id}' to save: {e}"
- )));
- }
- }
- } else {
- match args.get("graph") {
- Some(v) if !v.is_null() => v.clone(),
- _ => return Ok(ToolResult::error(
- "Provide `draft_id` (a working draft) or inline `graph` to save onto the \
- flow."
- .to_string(),
- )),
- }
- };
- let name = args
- .get("name")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string);
-
- // Same migrate/validate + enforcing binding-resolvability gate as
- // propose_workflow/revise_workflow, run HERE at the tool level (not
- // inside `ops::flows_update`, which the UI/RPC also call for a
- // human's own edits and which must stay permissive) — so an agent
- // can never persist a graph with an unresolvable `tool_call` binding
- // either. See `tinyflows::gates::failures`.
- let graph = match validate_and_migrate_graph(graph_json.clone()) {
- Ok(graph) => graph,
- Err(e) => {
- tracing::debug!(target: "flows", %flow_id, error = %e, "[flows] save_workflow: validation failed");
- return Ok(ToolResult::error(format!(
- "Workflow graph is invalid: {e}. Fix the graph and call save_workflow again."
- )));
- }
- };
- // The full builder hard-gate stack, run through the single canonical
- // runner shared with propose/revise/edit and the strict create/update
- // RPC path (F3) — so an agent can never persist a graph that would fail
- // gates the other planes enforce.
- let gate_errors = ops::run_builder_gates(&self.config, &graph).await;
- if !gate_errors.is_empty() {
- tracing::debug!(
- target: "flows",
- %flow_id,
- error_count = gate_errors.len(),
- "[flows] save_workflow: a hard gate rejected the graph"
- );
- return Ok(ToolResult::error(format!(
- "{}\n\nFix these and call save_workflow again.",
- gate_errors.join("\n\n")
- )));
- }
- // Author-time warnings (unfired trigger kinds + unwired REQUIRED
- // Composio args) were previously computed by propose/revise but never
- // surfaced again at save time — add them here so the agent sees any
- // non-fatal wiring gaps that remain in the final persisted graph.
- let mut warnings = tinyflows::triggers::graph_trigger_warnings(&graph);
- warnings.extend(ops::graph_wiring_warnings(&self.config, &graph).await);
-
- tracing::info!(
- target: "flows",
- %flow_id,
- renaming = name.is_some(),
- "[flows] save_workflow: agent-initiated save to existing flow"
- );
-
- match ops::flows_update(&self.config, &flow_id, name, Some(graph_json), None, None).await {
- Ok(outcome) => {
- let flow = outcome.value;
- tracing::info!(
- target: "flows",
- %flow_id,
- node_count = flow.graph.nodes.len(),
- enabled = flow.enabled,
- "[flows] save_workflow: persisted"
- );
- // Surface any explanatory logs `flows_update` produced — most
- // notably the manual→automatic auto-disarm message (#4889) —
- // to the agent. Skip the boilerplate "flow updated: <id>" line,
- // which just duplicates the `persisted`/`flow_id` fields this
- // response already carries.
- let flow_updated_boilerplate = format!("flow updated: {flow_id}");
- warnings.extend(
- outcome
- .logs
- .into_iter()
- .filter(|log| *log != flow_updated_boilerplate),
- );
- // Issue B29 (save/enable safety), Rule 3: `flows_create` only
- // gates the FIRST creation of a flow — an agent `save_workflow`
- // targets an EXISTING flow via `flows_update`, which (since
- // #4889) force-disables the flow whenever the trigger
- // transitions from manual to automatic (schedule/webhook/
- // app_event) — so a save can never silently arm a trigger that
- // wasn't already live (see the `warnings.extend` above for the
- // explanatory log). Short of that transition, `flows_update`
- // preserves whatever `enabled` state the flow already had: if
- // it was ALREADY enabled with an automatic trigger and stays
- // automatic, saving a new graph onto it re-arms it live with no
- // further confirmation. Surface that loudly so the copilot
- // relays it to the user instead of staying silent.
- if flow.enabled && ops::trigger_is_automatic(&flow.graph) {
- let trigger_desc = flow
- .graph
- .trigger()
- .map(tinyflows::summary::describe_trigger)
- .unwrap_or_else(|| "automatic".to_string());
- let warning = format!(
- "WARNING: this flow is ENABLED with an automatic trigger \
- ({trigger_desc}). It is now LIVE and will fire on its own — tell the \
- user, and offer to disable it (flows_set_enabled) if that's not what \
- they intended."
- );
- tracing::warn!(
- target: "flows",
- %flow_id,
- trigger = %trigger_desc,
- "[flows] save_workflow: saved onto an enabled auto-trigger flow — now LIVE"
- );
- warnings.push(warning);
- }
- Ok(ToolResult::success(serde_json::to_string_pretty(&json!({
- "type": "workflow_saved",
- // Explicit counterpart to a proposal's persisted:false — this
- // graph IS now written onto the saved flow.
- "persisted": true,
- "flow_id": flow.id,
- "name": flow.name,
- "enabled": flow.enabled,
- "require_approval": flow.require_approval,
- "node_count": flow.graph.nodes.len(),
- "warnings": warnings,
- }))?))
- }
- Err(e) => {
- tracing::debug!(target: "flows", %flow_id, error = %e, "[flows] save_workflow: failed");
- Ok(ToolResult::error(format!(
- "Could not save workflow to flow '{flow_id}': {e}"
- )))
- }
- }
- }
-}
-
-#[cfg(test)]
-#[path = "persistence_schema_tests.rs"]
-mod schema_tests;
diff --git a/crates/openhuman-core/src/flows/builder_tools/persistence_schema_tests.rs b/crates/openhuman-core/src/flows/builder_tools/persistence_schema_tests.rs
deleted file mode 100644
index 1001a3ba14..0000000000
--- a/crates/openhuman-core/src/flows/builder_tools/persistence_schema_tests.rs
+++ /dev/null
@@ -1,42 +0,0 @@
-use super::*;
-use serde_json::json;
-
-fn expected_save_workflow() -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "flow_id": {
- "type": "string",
- "description": "Id of the EXISTING saved flow to write the graph to (the persistence target — always required)."
- },
- "draft_id": {
- "type": "string",
- "description": "A working draft whose graph to persist onto the flow. Provide this OR inline `graph`; if both are given, draft_id wins."
- },
- "graph": {
- "type": "object",
- "description": "The full tinyflows WorkflowGraph to persist: { name?, nodes: [...], edges: [...] }. Provide this OR `draft_id`. Same shape as propose_workflow.",
- "properties": {
- "nodes": { "type": "array" },
- "edges": { "type": "array" }
- },
- "required": ["nodes", "edges"]
- },
- "name": {
- "type": "string",
- "description": "Optional new human-readable name for the flow."
- }
- },
- "required": ["flow_id"],
- "additionalProperties": false
- })
-}
-
-#[test]
-fn save_workflow_static_schema_matches_json_literal() {
- let tool = SaveWorkflowTool::new(std::sync::Arc::new(crate::config::Config::default()));
- assert_eq!(
- tinytools::Tool::parameters_schema(&tool),
- expected_save_workflow()
- );
-}
diff --git a/crates/openhuman-core/src/flows/builder_tools/run_control.rs b/crates/openhuman-core/src/flows/builder_tools/run_control.rs
deleted file mode 100644
index 0f0a7698aa..0000000000
--- a/crates/openhuman-core/src/flows/builder_tools/run_control.rs
+++ /dev/null
@@ -1,203 +0,0 @@
-//! Run control: resume a run parked on approval, cancel an in-flight run.
-
-use std::sync::Arc;
-
-use async_trait::async_trait;
-use serde_json::{json, Value};
-
-use crate::config::Config;
-use crate::flows::ops;
-use tinytools::{PermissionLevel, Tool, ToolResult};
-
-// ─────────────────────────────────────────────────────────────────────────────
-// Phase 4 — the self-debug loop + gated create (F4, F7)
-// ─────────────────────────────────────────────────────────────────────────────
-
-/// `resume_flow_run`: progress a run parked on a human approval by
-/// approving/rejecting its pending node(s). Execute + approval-gated — it
-/// advances a REAL run that can fire real outbound effects.
-pub struct ResumeFlowRunTool {
- config: Arc<Config>,
-}
-
-impl ResumeFlowRunTool {
- pub fn new(config: Arc<Config>) -> Self {
- Self { config }
- }
-}
-
-#[async_trait]
-impl Tool for ResumeFlowRunTool {
- fn name(&self) -> &str {
- "resume_flow_run"
- }
-
- fn description(&self) -> &str {
- "Resume a flow run that is paused on a human approval, approving and/or rejecting its \
- pending node(s). This ADVANCES A REAL RUN — approved outbound nodes will fire — so it is \
- approval-gated. Params: { flow_id, run_id, approve?: [node_id...], reject?: [node_id...] }. \
- Use list_flow_runs / get_flow_run to find a run with status pending_approval and its \
- pending node ids first."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "flow_id": { "type": "string", "description": "The run's flow id." },
- "run_id": { "type": "string", "description": "The run (thread) id to resume (from list_flow_runs)." },
- "approve": { "type": "array", "items": { "type": "string" }, "description": "Node ids to approve." },
- "reject": { "type": "array", "items": { "type": "string" }, "description": "Node ids to reject." }
- },
- "required": ["flow_id", "run_id"],
- "additionalProperties": false
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- // Advances a real run (approved nodes fire) — gate like an execute-class,
- // approval-parked action.
- PermissionLevel::Execute
- }
-
- fn external_effect(&self) -> bool {
- true
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- 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' parameter".to_string())),
- };
- let run_id = match args.get("run_id").and_then(Value::as_str).map(str::trim) {
- Some(id) if !id.is_empty() => id.to_string(),
- _ => return Ok(ToolResult::error("Missing 'run_id' parameter".to_string())),
- };
- let approve = string_array(&args, "approve");
- let reject = string_array(&args, "reject");
- tracing::debug!(target: "flows", %flow_id, %run_id, approve = approve.len(), reject = reject.len(), "[flows] resume_flow_run: resuming parked run");
- match ops::flows_resume(&self.config, &flow_id, &run_id, approve, reject).await {
- Ok(outcome) => Ok(ToolResult::success(serde_json::to_string_pretty(
- &outcome.value,
- )?)),
- Err(e) => Ok(ToolResult::error(format!("Could not resume run: {e}"))),
- }
- }
-}
-
-/// `cancel_flow_run`: stop an in-flight or parked run. Write-class — it changes
-/// run state but fires no new outbound effect.
-///
-/// **T-M3 fix.** This tool used to cancel an arbitrary `run_id` with no
-/// ownership check at all — combined with `external_effect() == false` (so
-/// the approval gate never parked it) and hiding that only covered the two
-/// `flows_build` copilot/headless paths (`FLOWS_BUILD_COPILOT_HIDDEN_TOOLS`,
-/// not the orchestrator-delegation or main-chat paths that also carry this
-/// tool), a prompt-injected turn could cancel ANY user's in-flight or
-/// approval-parked automation, unapproved. Two independent closes now apply:
-/// 1. **Ownership check** — the caller must name the `flow_id` it believes
-/// owns the run (mirrors [`ResumeFlowRunTool`]'s existing `{ flow_id,
-/// run_id }` shape); the run row's *actual* `flow_id` is resolved and
-/// compared, and a mismatch is refused rather than silently cancelling a
-/// run scoped to a different flow.
-/// 2. **`external_effect() == true`** — parks for approval on any surface
-/// that has a gate, same as `resume_flow_run`.
-pub struct CancelFlowRunTool {
- config: Arc<Config>,
-}
-
-impl CancelFlowRunTool {
- pub fn new(config: Arc<Config>) -> Self {
- Self { config }
- }
-}
-
-#[async_trait]
-impl Tool for CancelFlowRunTool {
- fn name(&self) -> &str {
- "cancel_flow_run"
- }
-
- fn description(&self) -> &str {
- "Cancel an in-flight or approval-parked flow run by its run_id (from list_flow_runs). \
- Stops a runaway or stuck run; fires no new outbound effect. The run_id must belong to \
- the given flow_id — cancelling a run that belongs to a different flow is refused. \
- Approval-gated. Params: { flow_id, run_id }."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "flow_id": { "type": "string", "description": "The flow that owns the run being cancelled (from list_flow_runs)." },
- "run_id": { "type": "string", "description": "The run (thread) id to cancel." }
- },
- "required": ["flow_id", "run_id"],
- "additionalProperties": false
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::Write
- }
-
- fn external_effect(&self) -> bool {
- true
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- 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' parameter".to_string())),
- };
- let run_id = match args.get("run_id").and_then(Value::as_str).map(str::trim) {
- Some(id) if !id.is_empty() => id.to_string(),
- _ => return Ok(ToolResult::error("Missing 'run_id' parameter".to_string())),
- };
-
- // SECURITY (T-M3 fix): verify the run actually belongs to the
- // caller-named flow before cancelling anything — mirrors
- // `resume_flow_run` (`ops::flows_resume`)'s existing `run_record.flow_id
- // != flow_id` guard. Without this, any run_id (guessed, enumerated, or
- // named by a prompt-injected turn that never called list_flow_runs)
- // could cancel a run scoped to a completely different flow.
- let run = match ops::flows_get_run(&self.config, &run_id).await {
- Ok(outcome) => outcome.value,
- Err(e) => return Ok(ToolResult::error(format!("Could not cancel run: {e}"))),
- };
- if run.flow_id != flow_id {
- tracing::warn!(
- target: "flows",
- %flow_id,
- %run_id,
- actual_flow_id = %run.flow_id,
- "[flows] cancel_flow_run: refused — run belongs to a different flow than the one named"
- );
- return Ok(ToolResult::error(format!(
- "run '{run_id}' belongs to flow '{}', not '{flow_id}' — refusing to cancel",
- run.flow_id
- )));
- }
-
- tracing::debug!(target: "flows", %flow_id, %run_id, "[flows] cancel_flow_run: cancelling run");
- match ops::flows_cancel_run(&self.config, &run_id).await {
- Ok(outcome) => Ok(ToolResult::success(serde_json::to_string_pretty(
- &outcome.value,
- )?)),
- Err(e) => Ok(ToolResult::error(format!("Could not cancel run: {e}"))),
- }
- }
-}
-
-/// Extracts a string array from `args[key]`, ignoring non-strings; empty when
-/// absent. Shared by the resume tool's approve/reject lists.
-fn string_array(args: &Value, key: &str) -> Vec<String> {
- args.get(key)
- .and_then(Value::as_array)
- .map(|a| {
- a.iter()
- .filter_map(|v| v.as_str().map(str::to_string))
- .collect()
- })
- .unwrap_or_default()
-}
diff --git a/crates/openhuman-core/src/flows/discovery_tools.rs b/crates/openhuman-core/src/flows/discovery_tools.rs
deleted file mode 100644
index b755ad9ffd..0000000000
--- a/crates/openhuman-core/src/flows/discovery_tools.rs
+++ /dev/null
@@ -1,239 +0,0 @@
-//! The discovery agent's terminal output tool: [`SuggestWorkflowsTool`]
-//! (`suggest_workflows`).
-//!
-//! The `flow_discovery` agent (the "Flow Scout", see
-//! `agent_registry/agents/flow_discovery/`) reasons read-only over the user's
-//! memory, threads, people, connected integrations, existing flows, and the
-//! web, then ends its run by calling this tool **once** with a batch of concrete
-//! workflow suggestions. The tool validates each pitch, stamps a stable
-//! content-hash id (so a re-run dedupes identical ideas instead of piling
-//! duplicates — see [`super::store::upsert_suggestions`]), persists them to the
-//! `flow_suggestions` table, and returns a `workflow_suggestions` payload the
-//! Flows page "Suggested for you" section renders.
-//!
-//! **Not authoring.** A suggestion is a *pitch* carrying a natural-language
-//! `build_prompt`, not a validated graph. When the user clicks "Build this",
-//! the frontend hands that prompt to the existing `workflow_builder` agent,
-//! which turns it into a real graph proposal to review and save. This keeps the
-//! discovery agent strictly read-only and reuses the whole authoring pipeline
-//! unchanged.
-//!
-//! **Permission contract:** `permission_level() == PermissionLevel::None` and
-//! `external_effect() == false`. The only write is to the agent's own
-//! suggestions sink (internal bookkeeping, no user data mutated, no external
-//! effect), so the tool passes a `read_only` sandbox — it is the agent's
-//! designated way to emit its result, analogous to
-//! [`super::tools::ProposeWorkflowTool`] returning a proposal.
-
-use crate::tools::schema_cache::static_schema;
-use std::sync::Arc;
-
-use async_trait::async_trait;
-use serde_json::{json, Value};
-use sha2::{Digest, Sha256};
-
-use crate::config::Config;
-use crate::flows::store;
-use tinyflows_catalog::types::{FlowSuggestion, SuggestionStatus};
-use tinytools::{PermissionLevel, Tool, ToolResult};
-
-/// Hard cap on suggestions accepted in one `suggest_workflows` call. Keeps the
-/// UI section digestible and bounds the write; the agent is told to return the
-/// few highest-value ideas, not an exhaustive list.
-const MAX_SUGGESTIONS_PER_CALL: usize = 8;
-
-/// Max characters kept for any single free-text field before truncation, so a
-/// pathological over-long pitch can't bloat the stored row or the card.
-const MAX_FIELD_CHARS: usize = 2000;
-
-pub struct SuggestWorkflowsTool {
- config: Arc<Config>,
-}
-
-impl SuggestWorkflowsTool {
- pub fn new(config: Arc<Config>) -> Self {
- Self { config }
- }
-}
-
-/// Derives a stable id for a suggestion from the normalized (lowercased,
-/// whitespace-collapsed) title, so the same idea proposed across two discovery
-/// runs collides on `ON CONFLICT(id)` and refreshes rather than duplicates.
-fn suggestion_id(title: &str) -> String {
- let normalized = title
- .split_whitespace()
- .collect::<Vec<_>>()
- .join(" ")
- .to_lowercase();
- let digest = Sha256::digest(normalized.as_bytes());
- // 16 hex chars (64 bits) is plenty to avoid collisions across a user's
- // handful of suggestions while keeping the id short and log-friendly.
- format!("sug_{}", hex::encode(&digest[..8]))
-}
-
-/// Reads an optional string array field into a `Vec<String>`, trimming empties.
-fn read_string_array(v: &Value, key: &str) -> Vec<String> {
- v.get(key)
- .and_then(Value::as_array)
- .map(|arr| {
- arr.iter()
- .filter_map(|e| e.as_str())
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(truncate)
- .collect()
- })
- .unwrap_or_default()
-}
-
-/// Trims and truncates a free-text field to [`MAX_FIELD_CHARS`] (char-safe).
-fn truncate(s: &str) -> String {
- let s = s.trim();
- if s.chars().count() <= MAX_FIELD_CHARS {
- return s.to_string();
- }
- s.chars().take(MAX_FIELD_CHARS).collect()
-}
-
-#[async_trait]
-impl Tool for SuggestWorkflowsTool {
- fn name(&self) -> &str {
- "suggest_workflows"
- }
-
- fn description(&self) -> &str {
- "Emit your discovered workflow suggestions for the user. Call this ONCE at the end of \
- your run with the few highest-value automations you found. Each suggestion is a PITCH \
- (not a graph): give a short `title`, a one-sentence `one_liner` of what it does, a \
- `rationale` grounded in what you actually observed about THIS user (a recurring thread, \
- a stated goal in memory, a connected app — never generic advice), and a self-contained \
- `build_prompt` that the workflow-builder agent can turn into a real graph. Ground \
- `suggested_connections` in real connection_ref values you saw via list_flow_connections \
- and `suggested_slugs` in real slugs from search_tool_catalog — NEVER invent either. \
- This tool only records the suggestions for the user to review on the Flows page; it does \
- NOT create, enable, or run any flow. Return 1-8 suggestions, best first."
- }
-
- fn parameters_schema(&self) -> Value {
- static_schema!(include_str!("parameters/suggest_workflows.json"))
- }
-
- fn permission_level(&self) -> PermissionLevel {
- // Terminal emit sink — see module doc. Only writes to the agent's own
- // suggestions store; no user data mutated, no external effect.
- PermissionLevel::None
- }
-
- fn external_effect(&self) -> bool {
- false
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let items = match args.get("suggestions").and_then(Value::as_array) {
- Some(arr) if !arr.is_empty() => arr,
- _ => {
- return Ok(ToolResult::error(
- "Missing or empty 'suggestions' array. Return 1-8 suggestions, best first."
- .to_string(),
- ))
- }
- };
-
- let run_id = args
- .get("run_id")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string);
-
- let now = chrono::Utc::now().to_rfc3339();
- let mut suggestions: Vec<FlowSuggestion> = Vec::new();
-
- for (idx, item) in items.iter().take(MAX_SUGGESTIONS_PER_CALL).enumerate() {
- let required = |key: &str| -> Result<String, String> {
- match item.get(key).and_then(Value::as_str).map(str::trim) {
- Some(s) if !s.is_empty() => Ok(truncate(s)),
- _ => Err(format!("suggestion #{}: missing '{key}'", idx + 1)),
- }
- };
-
- let title = match required("title") {
- Ok(v) => v,
- Err(e) => return Ok(ToolResult::error(e)),
- };
- let one_liner = match required("one_liner") {
- Ok(v) => v,
- Err(e) => return Ok(ToolResult::error(e)),
- };
- let rationale = match required("rationale") {
- Ok(v) => v,
- Err(e) => return Ok(ToolResult::error(e)),
- };
- let build_prompt = match required("build_prompt") {
- Ok(v) => v,
- Err(e) => return Ok(ToolResult::error(e)),
- };
-
- let trigger_hint = item
- .get("trigger_hint")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string);
- let confidence = item
- .get("confidence")
- .and_then(Value::as_f64)
- .unwrap_or(0.0)
- .clamp(0.0, 1.0);
-
- suggestions.push(FlowSuggestion {
- id: suggestion_id(&title),
- title,
- one_liner,
- rationale,
- trigger_hint,
- steps_outline: read_string_array(item, "steps_outline"),
- suggested_connections: read_string_array(item, "suggested_connections"),
- suggested_slugs: read_string_array(item, "suggested_slugs"),
- build_prompt,
- confidence,
- status: SuggestionStatus::New,
- created_at: now.clone(),
- source_run_id: run_id.clone(),
- });
- }
-
- // Dedupe within this single batch on id, keeping the first (highest
- // ranked) occurrence, so two near-identical titles in one call don't
- // fight over the same row.
- suggestions.dedup_by(|a, b| a.id == b.id);
- let mut seen = std::collections::HashSet::new();
- suggestions.retain(|s| seen.insert(s.id.clone()));
-
- tracing::info!(
- target: "flows",
- count = suggestions.len(),
- run_id = run_id.as_deref().unwrap_or("-"),
- "[flows] suggest_workflows: recording discovered suggestions"
- );
-
- let written = store::upsert_suggestions(&self.config, &suggestions)
- .map_err(|e| anyhow::anyhow!("failed to persist suggestions: {e}"))?;
-
- let payload = json!({
- "type": "workflow_suggestions",
- "count": written,
- "suggestions": suggestions,
- });
-
- Ok(ToolResult::success(serde_json::to_string_pretty(&payload)?))
- }
-}
-
-#[cfg(test)]
-#[path = "discovery_tools_tests.rs"]
-mod tests;
-
-#[cfg(test)]
-#[path = "discovery_tools_schema_tests.rs"]
-mod schema_tests;
diff --git a/crates/openhuman-core/src/flows/discovery_tools_schema_tests.rs b/crates/openhuman-core/src/flows/discovery_tools_schema_tests.rs
deleted file mode 100644
index 127765a1ce..0000000000
--- a/crates/openhuman-core/src/flows/discovery_tools_schema_tests.rs
+++ /dev/null
@@ -1,74 +0,0 @@
-use super::*;
-use serde_json::json;
-
-fn expected_suggest_workflows() -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "suggestions": {
- "type": "array",
- "description": "1-8 workflow suggestions, highest-value first.",
- "items": {
- "type": "object",
- "properties": {
- "title": {
- "type": "string",
- "description": "Short, human-friendly title, e.g. \"Auto-file email receipts\"."
- },
- "one_liner": {
- "type": "string",
- "description": "One sentence describing what the workflow does."
- },
- "rationale": {
- "type": "string",
- "description": "Why this is suggested to THIS user, grounded in what you observed."
- },
- "trigger_hint": {
- "type": "string",
- "description": "Likely trigger: \"schedule\" | \"app_event\" | \"manual\" (only these self-fire).",
- "enum": ["schedule", "app_event", "manual"]
- },
- "steps_outline": {
- "type": "array",
- "items": { "type": "string" },
- "description": "Plain-language step outline, one per element."
- },
- "suggested_connections": {
- "type": "array",
- "items": { "type": "string" },
- "description": "Real connection_ref values from list_flow_connections. Never invented."
- },
- "suggested_slugs": {
- "type": "array",
- "items": { "type": "string" },
- "description": "Real Composio action slugs from search_tool_catalog. Never hallucinated."
- },
- "build_prompt": {
- "type": "string",
- "description": "Self-contained natural-language brief handed to the workflow-builder on \"Build this\"."
- },
- "confidence": {
- "type": "number",
- "description": "Your confidence in [0,1] that this is a genuinely useful, buildable automation."
- }
- },
- "required": ["title", "one_liner", "rationale", "build_prompt"]
- }
- },
- "run_id": {
- "type": "string",
- "description": "Optional correlation id for the discovery run that produced these."
- }
- },
- "required": ["suggestions"]
- })
-}
-
-#[test]
-fn suggest_workflows_static_schema_matches_json_literal() {
- let tool = SuggestWorkflowsTool::new(std::sync::Arc::new(crate::config::Config::default()));
- assert_eq!(
- tinytools::Tool::parameters_schema(&tool),
- expected_suggest_workflows()
- );
-}
diff --git a/crates/openhuman-core/src/flows/parameters/suggest_workflows.json b/crates/openhuman-core/src/flows/parameters/suggest_workflows.json
deleted file mode 100644
index 4d605b8a03..0000000000
--- a/crates/openhuman-core/src/flows/parameters/suggest_workflows.json
+++ /dev/null
@@ -1,77 +0,0 @@
-{
- "type": "object",
- "properties": {
- "suggestions": {
- "type": "array",
- "description": "1-8 workflow suggestions, highest-value first.",
- "items": {
- "type": "object",
- "properties": {
- "title": {
- "type": "string",
- "description": "Short, human-friendly title, e.g. \"Auto-file email receipts\"."
- },
- "one_liner": {
- "type": "string",
- "description": "One sentence describing what the workflow does."
- },
- "rationale": {
- "type": "string",
- "description": "Why this is suggested to THIS user, grounded in what you observed."
- },
- "trigger_hint": {
- "type": "string",
- "description": "Likely trigger: \"schedule\" | \"app_event\" | \"manual\" (only these self-fire).",
- "enum": [
- "schedule",
- "app_event",
- "manual"
- ]
- },
- "steps_outline": {
- "type": "array",
- "items": {
- "type": "string"
- },
- "description": "Plain-language step outline, one per element."
- },
- "suggested_connections": {
- "type": "array",
- "items": {
- "type": "string"
- },
- "description": "Real connection_ref values from list_flow_connections. Never invented."
- },
- "suggested_slugs": {
- "type": "array",
- "items": {
- "type": "string"
- },
- "description": "Real Composio action slugs from search_tool_catalog. Never hallucinated."
- },
- "build_prompt": {
- "type": "string",
- "description": "Self-contained natural-language brief handed to the workflow-builder on \"Build this\"."
- },
- "confidence": {
- "type": "number",
- "description": "Your confidence in [0,1] that this is a genuinely useful, buildable automation."
- }
- },
- "required": [
- "title",
- "one_liner",
- "rationale",
- "build_prompt"
- ]
- }
- },
- "run_id": {
- "type": "string",
- "description": "Optional correlation id for the discovery run that produced these."
- }
- },
- "required": [
- "suggestions"
- ]
-}