The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(flows): stop claiming ungranted trust and reject malformed contract slugs\n\nTwo defects in the flows RPCs that report what a run will ask the user for.\n\n`flows_approval_manifest` pushed every approvable `tool_name` onto\n`already_trusted` when no `ApprovalGate` was installed. Nothing parks without a\ngate, so `missing` is empty by definition — but nothing was ever *granted*\neither, so those keys do not belong in `already_trusted`. A graph with an\n`http_request` and a `code` node came back as\n`already_trusted: ["flows_http_request", "flows_code"]` on a host holding no\ngrant, which is what the save+enable card renders as "already authorized".\nThe classification moves into `split_manifest_trust`, which returns both lists\nempty with no gate — the same answer the sibling `approval_preauthorize_flow`\nalready gives for the identical condition, and the one the RPC schema already\ndocumented for the field. Extracting it also makes both branches testable\nwithout the process-global `OnceLock` gate.\n\n`flows_get_tool_contract`'s `<TOOLKIT>_<ACTION>` guard was unreachable for any\nnon-empty slug: `toolkit_from_slug` falls back to the whole string when there is\nno `_`, so `nodashhere` resolved to a toolkit and failed later with an unrelated\n"could not fetch the live Composio catalog" message, after taking a per-toolkit\nfetch lock and attempting a round trip. `toolkit_for_contract_slug` checks the\nshape first — non-empty segments either side of the first `_` — and the error\nnames the caller's own slug rather than the trimmed one. The vendored\n`toolkit_from_slug` is left permissive on purpose: `compute_required_connections`\nmaps toolkit-ish tokens and wants the whole string back, so the stricter rule\nbelongs to these controllers.\n\nThe agent's `get_tool_contract` tool carried a verbatim copy of the same guard,\nwhere it was fully dead — the tool rejects an empty slug before reaching it — and\nwhere the fall-through was more damaging, since the catalog error tells the model\nto retry a fetch that can never succeed. It now calls the same helper, which is\nwhat its RPC twin's docstring already claimed ("the same core as the agent's\nget_tool_contract tool").\n\nCloses #6071\nCloses #6072\n
Shanub9cfafcfebf9
diff --git a/app/src/services/api/flowsApi.ts b/app/src/services/api/flowsApi.tsindex efcb63a3b1..24b8b10390 100644--- a/app/src/services/api/flowsApi.ts+++ b/app/src/services/api/flowsApi.ts@@ -834,6 +834,11 @@ export interface ApprovalManifest {entries: ApprovalManifestEntry[];/** Approvable trust keys the flow does not yet hold — what the card asks for. */missing: string[];+ /**+ * Approvable trust keys this flow already holds a grant for. Empty whenever+ * `gate_installed` is false: with no gate no grant was ever made, so nothing+ * can be reported as authorized.+ */already_trusted: string[];/** False when the approval gate is disabled — nothing ever prompts. */gate_installed: boolean;diff --git a/src/openhuman/flows/builder_tools_part_04.rs b/src/openhuman/flows/builder_tools_part_04.rsindex 3021dd2af3..4b4b86e94c 100644--- a/src/openhuman/flows/builder_tools_part_04.rs+++ b/src/openhuman/flows/builder_tools_part_04.rs@@ -349,10 +349,13 @@ impl Tool for GetToolContractTool {Some(s) if !s.is_empty() => s.to_string(),_ => return Ok(ToolResult::error("Missing 'slug' parameter".to_string())),};- // Contract crate — `toolkit_from_slug` is defined in- // `tinymemory_api::composio::scopes` and only re-exported by the engine's- // providers module, so this names the same function (#5560).- let Some(toolkit) = tinymemory_api::composio::toolkit_from_slug(&slug) else {+ // Shape-check before any I/O, through the same guard the+ // `flows_get_tool_contract` RPC uses — `toolkit_from_slug` falls back to+ // the whole string when there is no `_`, so a bare action name would+ // otherwise resolve to a bogus toolkit and come back as the catalog+ // error below, which tells the model to retry a fetch that can never+ // succeed.+ let Some(toolkit) = crate::openhuman::flows::ops::toolkit_for_contract_slug(&slug) else {return Ok(ToolResult::error(format!("Could not extract a toolkit from slug '{slug}' — it must look like \'<TOOLKIT>_<ACTION>' (e.g. 'GMAIL_SEND_EMAIL')."diff --git a/src/openhuman/flows/builder_tools_tests_part_01_tests.rs b/src/openhuman/flows/builder_tools_tests_part_01_tests.rsindex f667befa12..2526f09736 100644--- a/src/openhuman/flows/builder_tools_tests_part_01_tests.rs+++ b/src/openhuman/flows/builder_tools_tests_part_01_tests.rs@@ -352,6 +352,26 @@ async fn get_tool_contract_missing_slug_is_error() {assert!(result.output().contains("Missing 'slug'"));}+#[tokio::test]+async fn get_tool_contract_rejects_a_slug_with_no_action_segment() {+ let tmp = TempDir::new().unwrap();+ let tool = GetToolContractTool::new(test_config(&tmp));++ // A bare toolkit-ish token names no action, so this endpoint cannot return+ // anything for it. Before the shape guard, `toolkit_from_slug` fell back to+ // the whole string and the model got the catalog error instead — which tells+ // it to retry a fetch that can never succeed.+ for slug in ["nodashhere", "_LEADING_UNDERSCORE", "GMAIL_"] {+ let result = tool.execute(json!({ "slug": slug })).await.unwrap();+ assert!(result.is_error, "slug {slug:?} must be rejected");+ assert!(+ result.output().contains("'<TOOLKIT>_<ACTION>'"),+ "slug {slug:?} must get the malformed-slug message, got: {}",+ result.output()+ );+ }+}+#[tokio::test]async fn get_tool_contract_rejects_a_hallucinated_slug() {seed_live_catalog_cache("gmail", vec![seeded_gmail_send_contract()]);diff --git a/src/openhuman/flows/flows_schema_part_02.rs b/src/openhuman/flows/flows_schema_part_02.rsindex 19e9951358..d726277c9d 100644--- a/src/openhuman/flows/flows_schema_part_02.rs+++ b/src/openhuman/flows/flows_schema_part_02.rs@@ -55,7 +55,8 @@ pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {FieldSchema {name: "already_trusted",ty: TypeSchema::Array(Box::new(TypeSchema::String)),- comment: "Approvable trust keys already granted to this flow.",+ comment: "Approvable trust keys already granted to this flow. Empty when \+ gate_installed is false — no gate means no grant was ever made.",required: true,},FieldSchema {diff --git a/src/openhuman/flows/ops_part_12.rs b/src/openhuman/flows/ops_part_12.rsindex a49a6321c0..d69bc55963 100644--- a/src/openhuman/flows/ops_part_12.rs+++ b/src/openhuman/flows/ops_part_12.rs@@ -367,12 +367,49 @@ pub async fn compute_approval_manifest(config: &Config, graph: &WorkflowGraph) -entries}+/// Splits a manifest's approvable entries into the trust keys a run will have to+/// ask for and the ones the flow already holds a grant for.+///+/// With no gate installed both lists are empty: nothing ever parks, so nothing+/// is `missing` — and nothing was ever granted, so nothing is `already_trusted`+/// either. Naming the approvable keys there would tell the save+enable card that+/// permissions are authorized on a host that holds no grant for them.+/// `gate_installed: false` is the caller's single signal, which is exactly what+/// the sibling `approval_preauthorize_flow` reports for the same condition.+fn split_manifest_trust(+ entries: &[Value],+ gate_installed: bool,+ trusted: &HashSet<String>,+) -> (Vec<String>, Vec<String>) {+ let mut missing: Vec<String> = Vec::new();+ let mut already_trusted: Vec<String> = Vec::new();+ if !gate_installed {+ return (missing, already_trusted);+ }+ for entry in entries {+ if entry.get("kind").and_then(Value::as_str) != Some("approvable") {+ continue;+ }+ let Some(tool_name) = entry.get("tool_name").and_then(Value::as_str) else {+ continue;+ };+ if trusted.contains(tool_name) {+ already_trusted.push(tool_name.to_string());+ } else {+ missing.push(tool_name.to_string());+ }+ }+ (missing, already_trusted)+}+/// RPC: the approval manifest for a saved flow (by `id`) or a candidate/// `graph`, joined against the flow's existing `flow_tool_trust` grants so/// the save+enable card can ask only for what's missing.////// With the approval gate uninstalled (`OPENHUMAN_APPROVAL_GATE=0`) nothing-/// ever parks, so `missing` is empty by definition and the card never shows.+/// ever parks and nothing was ever granted, so `missing` and `already_trusted`+/// are both empty by definition and the card never shows — `gate_installed:+/// false` is the only signal in that case.pub async fn flows_approval_manifest(config: &Config,id: Option<&str>,@@ -404,24 +441,7 @@ pub async fn flows_approval_manifest(_ => HashSet::new(),};- let mut missing: Vec<String> = Vec::new();- let mut already_trusted: Vec<String> = Vec::new();- for entry in &entries {- if entry.get("kind").and_then(Value::as_str) != Some("approvable") {- continue;- }- let Some(tool_name) = entry.get("tool_name").and_then(Value::as_str) else {- continue;- };- if !gate_installed {- // Nothing parks without a gate; report nothing as missing.- already_trusted.push(tool_name.to_string());- } else if trusted.contains(tool_name) {- already_trusted.push(tool_name.to_string());- } else {- missing.push(tool_name.to_string());- }- }+ let (missing, already_trusted) = split_manifest_trust(&entries, gate_installed, &trusted);let log = format!("[flows] approval manifest: {} entr{}, {} missing grant(s)",@@ -464,6 +484,33 @@ pub async fn flows_search_tool_catalog())}+/// Resolves the toolkit for a *single action* slug, rejecting anything that is+/// not shaped `<TOOLKIT>_<ACTION>`.+///+/// [`tinymemory_api::composio::toolkit_from_slug`] falls back to the whole+/// string when there is no `_`, so it answers `Some` for every non-empty input+/// — `toolkit_from_slug("nodashhere") == Some("nodashhere")`. That permissive+/// fall-back is load-bearing for `compute_required_connections`, which maps+/// toolkit-ish tokens and legitimately wants the whole string back, so the+/// stricter rule belongs to this caller rather than to the shared helper.+///+/// A contract fetch returns *one action*, so a slug with no action segment+/// cannot name anything it could return; rejecting it here also spares the+/// caller a pointless catalog round trip (which takes a per-toolkit fetch lock)+/// before failing with an unrelated "could not fetch the catalog" message.+///+/// The multi-segment toolkit prefixes (`MICROSOFT_TEAMS_`, `ONE_DRIVE_`,+/// `ZOHO_MAIL_`) all end in `_`, so a real action under one of them always has+/// non-empty segments either side of its first `_` and passes unchanged.+pub(super) fn toolkit_for_contract_slug(slug: &str) -> Option<String> {+ let trimmed = slug.trim();+ let (toolkit_segment, action_segment) = trimmed.split_once('_')?;+ if toolkit_segment.is_empty() || action_segment.is_empty() {+ return None;+ }+ tinymemory_api::composio::toolkit_from_slug(trimmed)+}+/// Fetches one Composio action's full contract (secret-free) — the RPC the/// canvas tool browser calls to fill in an action's arg schema, reusing the same/// core as the agent's `get_tool_contract` tool.@@ -471,14 +518,19 @@ pub async fn flows_get_tool_contract(config: &Config,slug: &str,) -> Result<RpcOutcome<Value>, String> {- let slug = slug.trim();- let Some(toolkit) = tinymemory_api::composio::toolkit_from_slug(slug) else {+ let trimmed = slug.trim();+ // Shape-check before `toolkit_from_slug`, and before any I/O: the shared+ // helper is deliberately permissive, so an unshaped slug would otherwise+ // fall through to a catalog round trip and fail with an unrelated message.+ // The message quotes the caller's own slug, not `trimmed` — reporting the+ // trimmed form named an empty string back at whoever sent whitespace.+ let Some(toolkit) = toolkit_for_contract_slug(trimmed) else {return Err(format!("Could not extract a toolkit from slug '{slug}' — it must look like \'<TOOLKIT>_<ACTION>' (e.g. 'GMAIL_SEND_EMAIL')."));};- tracing::debug!(target: "flows", %slug, %toolkit, "[flows] flows_get_tool_contract: fetching contract");+ tracing::debug!(target: "flows", slug = %trimmed, %toolkit, "[flows] flows_get_tool_contract: fetching contract");let Some(catalog) =crate::openhuman::flows::tinyflows::caps::fetch_live_toolkit_catalog(config, &toolkit).await@@ -487,7 +539,10 @@ pub async fn flows_get_tool_contract("Could not fetch the live Composio catalog for toolkit '{toolkit}'."));};- match catalog.iter().find(|c| c.slug.eq_ignore_ascii_case(slug)) {+ match catalog+ .iter()+ .find(|c| c.slug.eq_ignore_ascii_case(trimmed))+ {Some(contract) => {let contract =crate::openhuman::flows::tinyflows::caps::apply_probe_override(contract.clone());@@ -498,7 +553,7 @@ pub async fn flows_get_tool_contract())}None => Err(format!(- "'{slug}' is not a real action in the '{toolkit}' toolkit's live catalog."+ "'{trimmed}' is not a real action in the '{toolkit}' toolkit's live catalog.")),}}diff --git a/src/openhuman/flows/ops_support_tests.rs b/src/openhuman/flows/ops_support_tests.rsindex 7ff5d79fa8..9a173b37b9 100644--- a/src/openhuman/flows/ops_support_tests.rs+++ b/src/openhuman/flows/ops_support_tests.rs@@ -2,7 +2,13 @@ use super::*;// compute_approval_manifest (save-time pre-authorization card)pub(super) fn manifest_graph() -> WorkflowGraph {- structurally_valid_graph(json!({+ structurally_valid_graph(manifest_graph_json())+}++/// The same fixture in its wire form, for the RPCs that take a candidate+/// `graph` payload rather than a deserialized [`WorkflowGraph`].+pub(super) fn manifest_graph_json() -> Value {+ json!({"name": "manifest-fixture","nodes": [{ "id": "t", "kind": "trigger", "name": "Trigger" },@@ -21,7 +27,7 @@ pub(super) fn manifest_graph() -> WorkflowGraph {{ "from_node": "c", "from_port": "main", "to_node": "w" },{ "from_node": "w", "from_port": "main", "to_node": "r" }]- }))+ })}pub(super) fn entry_kinds_by_tool(entries: &[Value]) -> Vec<(String, String)> {diff --git a/src/openhuman/flows/ops_tests_part_13_tests.rs b/src/openhuman/flows/ops_tests_part_13_tests.rsindex abfc769624..79185a51db 100644--- a/src/openhuman/flows/ops_tests_part_13_tests.rs+++ b/src/openhuman/flows/ops_tests_part_13_tests.rs@@ -506,3 +506,140 @@ async fn stale_approval_refusal_does_not_settle_a_run_another_resume_claimed() {refusal path keys its record_run + drop_checkpoint off this exact value");}++#[tokio::test]+async fn approval_manifest_never_claims_trust_that_was_never_granted() {+ let tmp = TempDir::new().unwrap();+ let config = test_config(&tmp);++ // A candidate graph carries no flow id, so there is no `flow_tool_trust`+ // row to join against and nothing can legitimately be "already trusted" —+ // whether or not this process happens to have an `ApprovalGate` installed.+ let outcome = flows_approval_manifest(&config, None, Some(manifest_graph_json()))+ .await+ .expect("manifest must compute for a candidate graph");++ let already_trusted = outcome.value["already_trusted"]+ .as_array()+ .expect("already_trusted must be an array");+ assert!(+ already_trusted.is_empty(),+ "already_trusted must never name a permission no grant was ever made for; \+ the save+enable card renders these as authorized: {outcome:?}"+ );++ let gate_installed = outcome.value["gate_installed"]+ .as_bool()+ .expect("gate_installed must be a bool");+ let missing: Vec<&str> = outcome.value["missing"]+ .as_array()+ .expect("missing must be an array")+ .iter()+ .filter_map(Value::as_str)+ .collect();+ if gate_installed {+ // Gate installed, no grants held: every approvable key is asked for.+ assert!(+ missing.contains(&"flows_http_request") && missing.contains(&"flows_code"),+ "{missing:?}"+ );+ } else {+ // No gate: nothing ever parks, so nothing is missing either — the two+ // lists are empty together and `gate_installed` is the only signal.+ assert!(missing.is_empty(), "{missing:?}");+ }+}++#[test]+fn split_manifest_trust_claims_nothing_without_a_gate() {+ let entries = vec![+ json!({ "kind": "approvable", "tool_name": "flows_http_request" }),+ json!({ "kind": "approvable", "tool_name": "flows_code" }),+ json!({ "kind": "blocked", "tool_name": "SHOPIFY_CREATE_ORDER" }),+ ];++ // No gate: nothing ever parks, so nothing is missing — and no grant was ever+ // made, so nothing is already trusted either. Both lists must be empty; a+ // populated `already_trusted` here is what the save+enable card renders as+ // "already authorized" for a permission the flow does not hold.+ let (missing, already_trusted) = split_manifest_trust(&entries, false, &HashSet::new());+ assert!(missing.is_empty(), "{missing:?}");+ assert!(already_trusted.is_empty(), "{already_trusted:?}");++ // Gate installed, nothing granted: every approvable key is asked for, and+ // the non-approvable entry is still skipped.+ let (missing, already_trusted) = split_manifest_trust(&entries, true, &HashSet::new());+ assert_eq!(missing, vec!["flows_http_request", "flows_code"]);+ assert!(already_trusted.is_empty(), "{already_trusted:?}");++ // Gate installed with one grant held: that key moves across, and only it.+ let trusted: HashSet<String> = ["flows_code".to_string()].into_iter().collect();+ let (missing, already_trusted) = split_manifest_trust(&entries, true, &trusted);+ assert_eq!(missing, vec!["flows_http_request"]);+ assert_eq!(already_trusted, vec!["flows_code"]);+}++#[tokio::test]+async fn get_tool_contract_rejects_a_malformed_slug_before_any_catalog_fetch() {+ let tmp = TempDir::new().unwrap();+ let config = test_config(&tmp);++ // Each of these fails the `<TOOLKIT>_<ACTION>` shape, so the guard must+ // fire and no live catalog round trip may be attempted (these tests run+ // without Composio credentials or network).+ for slug in ["nodashhere", " ", "_LEADING_UNDERSCORE", "GMAIL_"] {+ let err = flows_get_tool_contract(&config, slug)+ .await+ .expect_err("a malformed slug must be rejected");+ assert!(+ err.contains("'<TOOLKIT>_<ACTION>'"),+ "slug {slug:?} must get the malformed-slug message, got: {err}"+ );+ }++ // The message names what the caller sent, not the trimmed form — a blank+ // slug used to be reported as `slug ''`, naming nothing the caller typed.+ let err = flows_get_tool_contract(&config, " nodashhere ")+ .await+ .expect_err("a malformed slug must be rejected");+ assert!(+ err.contains("slug ' nodashhere '"),+ "the error must quote the caller's own slug, got: {err}"+ );+}++#[test]+fn toolkit_for_contract_slug_accepts_real_action_slugs() {+ // Ordinary single-segment toolkit.+ assert_eq!(+ toolkit_for_contract_slug("GMAIL_SEND_EMAIL").as_deref(),+ Some("gmail")+ );+ // Surrounding whitespace is tolerated, as it was before the guard.+ assert_eq!(+ toolkit_for_contract_slug(" GMAIL_SEND_EMAIL ").as_deref(),+ Some("gmail")+ );+ // Every multi-segment toolkit prefix ends in `_`, so a real action under+ // one of them always has non-empty segments either side of its first `_`.+ assert_eq!(+ toolkit_for_contract_slug("ZOHO_MAIL_SEND_EMAIL").as_deref(),+ Some("zoho_mail")+ );+ assert_eq!(+ toolkit_for_contract_slug("ONE_DRIVE_UPLOAD_FILE").as_deref(),+ Some("one_drive")+ );+ assert_eq!(+ toolkit_for_contract_slug("MICROSOFT_TEAMS_SEND_MESSAGE").as_deref(),+ Some("microsoft_teams")+ );++ // The shared helper stays permissive for its other callers — this stricter+ // rule is this controller's, not `toolkit_from_slug`'s.+ assert_eq!(+ tinymemory_api::composio::toolkit_from_slug("nodashhere").as_deref(),+ Some("nodashhere")+ );+ assert_eq!(toolkit_for_contract_slug("nodashhere"), None);+}