Skip to content

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

refactor(json_schema): replace inline schema-walk logic with re-exports from tinyagents-harness

Steven Enamakelaa754fa60825
diff --git a/crates/openhuman-core/src/json_schema/ops.rs b/crates/openhuman-core/src/json_schema/ops.rs
index 00f1f20af5..5fe5526504 100644
--- a/crates/openhuman-core/src/json_schema/ops.rs
+++ b/crates/openhuman-core/src/json_schema/ops.rs
@@ -1,193 +1,8 @@
-//! Business logic for [`super`] — see that module's docs for why this domain
-//! is neutral (owned by neither the adapter seam nor the integration
-//! catalog) and for the vendor-name ban that applies to this file too.
-
-use serde_json::Value;
-
-/// Dotted path to the shallowest array-typed property declared by `schema`.
-///
-/// Breadth-first, so the shallowest match wins: every property at one level is
-/// checked for `type: "array"` before descending, which matters when a schema
-/// declares both a top-level list and a deeper one and a binding should prefer
-/// the outer.
-///
-/// `None` when `schema` is absent, declares no `properties`, or names no array
-/// anywhere.
-pub(crate) fn compute_primary_array_path(schema: Option<&Value>) -> Option<String> {
- let root = schema?;
- let mut queue: std::collections::VecDeque<(String, &Value)> = std::collections::VecDeque::new();
- queue.push_back((String::new(), root));
-
- while let Some((path, node)) = queue.pop_front() {
- let Some(props) = node.get("properties").and_then(Value::as_object) else {
- continue;
- };
- // Check every property at THIS level for an array before descending
- // to the next level — guarantees the shallowest match wins.
- for (key, prop_schema) in props {
- if prop_schema.get("type").and_then(Value::as_str) == Some("array") {
- let prop_path = if path.is_empty() {
- key.clone()
- } else {
- format!("{path}.{key}")
- };
- return Some(prop_path);
- }
- }
- for (key, prop_schema) in props {
- let prop_path = if path.is_empty() {
- key.clone()
- } else {
- format!("{path}.{key}")
- };
- queue.push_back((prop_path, prop_schema));
- }
- }
- None
-}
-
-/// [`compute_primary_array_path`]'s counterpart for a REAL runtime value rather
-/// than a schema — walks the value breadth-first for the first array-typed
-/// property.
-///
-/// `skip_root_keys` names properties to ignore **at the root only**. A caller
-/// whose values arrive wrapped in a response envelope passes the envelope's own
-/// metadata keys here, so an envelope field can never masquerade as (or shadow,
-/// via the shallowest-wins tie) the tool's real array. Pass `&[]` when the value
-/// has no envelope.
-///
-/// Because the scan starts at whatever root it is given, a hit beneath a wrapper
-/// property comes back already prefixed (e.g. `"data.issues"`) with no separate
-/// stitching step needed.
-///
-/// `None` when no array is found anywhere in the value — note a genuinely empty
-/// list still serializes as `[]`, which *is* an array, so `None` means the shape
-/// truly has no list at any depth.
-pub(crate) fn compute_primary_array_path_from_value(
- value: &Value,
- skip_root_keys: &[&str],
-) -> Option<String> {
- let mut queue: std::collections::VecDeque<(String, &Value)> = std::collections::VecDeque::new();
- queue.push_back((String::new(), value));
-
- while let Some((path, node)) = queue.pop_front() {
- let Some(obj) = node.as_object() else {
- continue;
- };
- for (key, v) in obj {
- if path.is_empty() && skip_root_keys.contains(&key.as_str()) {
- continue;
- }
- if v.is_array() {
- let prop_path = if path.is_empty() {
- key.clone()
- } else {
- format!("{path}.{key}")
- };
- return Some(prop_path);
- }
- }
- for (key, v) in obj {
- if path.is_empty() && skip_root_keys.contains(&key.as_str()) {
- continue;
- }
- let prop_path = if path.is_empty() {
- key.clone()
- } else {
- format!("{path}.{key}")
- };
- queue.push_back((prop_path, v));
- }
- }
- None
-}
-
-/// Extracts top-level field names from an output-schema value.
-///
-/// Reads `.properties`' keys for a standard object schema
-/// (`{"type": "object", "properties": {…}}`), and falls back to the schema's own
-/// top-level keys minus common JSON-Schema keywords for a looser or legacy
-/// shape. Empty when the schema is absent or unrecognized — never fails.
-pub(crate) fn response_fields_from_schema(schema: Option<&Value>) -> Vec<String> {
- const SCHEMA_KEYWORDS: &[&str] = &[
- "type",
- "required",
- "additionalProperties",
- "$schema",
- "description",
- "title",
- "examples",
- ];
-
- let Some(obj) = schema.and_then(Value::as_object) else {
- return Vec::new();
- };
- let mut fields: Vec<String> =
- if let Some(props) = obj.get("properties").and_then(Value::as_object) {
- props.keys().cloned().collect()
- } else {
- obj.keys()
- .filter(|k| !SCHEMA_KEYWORDS.contains(&k.as_str()))
- .cloned()
- .collect()
- };
- fields.sort();
- fields
-}
-
-/// Returns the names in `required` that are absent or `null` in `args`.
-pub(crate) fn missing_required_args(required: &[String], args: &Value) -> Vec<String> {
- required
- .iter()
- .filter(|name| match args.get(name.as_str()) {
- None => true,
- Some(v) => v.is_null(),
- })
- .cloned()
- .collect()
-}
-
-/// [B13] Returns argument names in `args` that are NOT declared `properties`
-/// of `schema` — the NAME-VALIDITY counterpart to [`missing_required_args`]'s
-/// PRESENCE check. Catches the class of bug [`missing_required_args`] alone
-/// cannot: a builder wires a real, well-typed value under an arg name the
-/// action's schema doesn't recognize at all (e.g. a chat action's `text` when
-/// the live action actually wants `markdown_text`) — the required arg still
-/// LOOKS satisfied from [`missing_required_args`]' perspective (a value is
-/// present under *some* key), so the mistake sails through authoring/save and
-/// only 400s from the real provider at runtime.
-///
-/// `None` means "cannot validate this schema — skip, never reject", so a
-/// caller must never turn a `None` into a rejection:
-/// - `schema` is `None` (the input schema is unknown for this slug), or
-/// - `schema` is not a JSON object, or names no object `properties` map (an
-/// unrecognized/legacy shape — nothing to check names against), or
-/// - `schema` declares `additionalProperties: true` (the provider explicitly
-/// telling us to accept arbitrary keys beyond the declared ones).
-///
-/// `Some(vec![])` means the schema WAS usable and every arg name in `args`
-/// is a real declared property. `args` must be a JSON object to check
-/// against; any other shape (including `Value::Null` — no args wired at
-/// all) yields `Some(vec![])`, mirroring [`missing_required_args`]' treatment
-/// of an absent/non-object `args`.
-pub(crate) fn unsupported_arg_names(schema: Option<&Value>, args: &Value) -> Option<Vec<String>> {
- let schema_obj = schema?.as_object()?;
- if schema_obj
- .get("additionalProperties")
- .and_then(Value::as_bool)
- == Some(true)
- {
- return None;
- }
- let properties = schema_obj.get("properties")?.as_object()?;
- let Some(args_obj) = args.as_object() else {
- return Some(Vec::new());
- };
- let mut unsupported: Vec<String> = args_obj
- .keys()
- .filter(|k| !properties.contains_key(k.as_str()))
- .cloned()
- .collect();
- unsupported.sort();
- Some(unsupported)
-}
+//! Business logic for [`super`] lives in `tinyagents-harness`
+//! (`tool::schema_walk`); this module only re-exports it under the names the
+//! host's callers already use. See [`super`] for why this domain is neutral.
+
+pub(crate) use tinyagents_harness::tool::{
+ compute_primary_array_path, compute_primary_array_path_from_value, missing_required_args,
+ response_fields_from_schema, unsupported_arg_names,
+};
diff --git a/crates/openhuman-core/src/json_schema/ops_tests.rs b/crates/openhuman-core/src/json_schema/ops_tests.rs
index 3454031797..49b8db8e6f 100644
--- a/crates/openhuman-core/src/json_schema/ops_tests.rs
+++ b/crates/openhuman-core/src/json_schema/ops_tests.rs
@@ -1,56 +1,6 @@
use super::*;
use serde_json::{json, Value};
-#[test]
-fn schema_array_path_prefers_the_shallowest_array() {
- let schema = json!({"properties": {
- "nested": {"properties": {"items": {"type": "array"}}},
- "top": {"type": "array"}
- }});
- assert_eq!(
- compute_primary_array_path(Some(&schema)).as_deref(),
- Some("top")
- );
-}
-
-#[test]
-fn value_array_path_skips_only_named_root_keys() {
- let value = json!({"metadata": [], "data": {"metadata": []}});
- assert_eq!(
- compute_primary_array_path_from_value(&value, &["metadata"]).as_deref(),
- Some("data.metadata")
- );
-}
-
-#[test]
-fn response_fields_are_sorted_and_ignore_schema_keywords() {
- let schema = json!({"type": "object", "z": {}, "a": {}});
- assert_eq!(response_fields_from_schema(Some(&schema)), ["a", "z"]);
-}
-
-#[test]
-fn required_arguments_treat_missing_and_null_as_absent() {
- let required = vec!["missing".to_string(), "null".to_string(), "set".to_string()];
- assert_eq!(
- missing_required_args(&required, &json!({"null": null, "set": 1})),
- ["missing", "null"]
- );
-}
-
-#[test]
-fn unsupported_arguments_follow_schema_openness() {
- let strict = json!({"properties": {"known": {}}});
- assert_eq!(
- unsupported_arg_names(Some(&strict), &json!({"known": 1, "extra": 2})),
- Some(vec!["extra".to_string()])
- );
- let open = json!({"properties": {"known": {}}, "additionalProperties": true});
- assert_eq!(
- unsupported_arg_names(Some(&open), &json!({"extra": 2})),
- None
- );
-}
-
#[test]
fn unsupported_arg_names_empty_when_every_name_is_a_real_property() {
let schema = json!({