Skip to content

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

feat(core): add BoundedU64 schema type with range validation

obchain0b5b15da75ee
diff --git a/crates/openhuman-core/src/core/all.rs b/crates/openhuman-core/src/core/all.rs
index af8c5ff059..34ed3a87be 100644
--- a/crates/openhuman-core/src/core/all.rs
+++ b/crates/openhuman-core/src/core/all.rs
@@ -1511,14 +1511,30 @@ pub fn validate_params(
// already handled by the required-presence check above.
for input in &schema.inputs {
if let Some(value) = params.get(input.name) {
- check_type(value, &input.ty).map_err(|expected| {
+ check_type(value, &input.ty).map_err(|mismatch| {
+ let (expected, got) = match mismatch {
+ TypeMismatch::Kind(expected) => {
+ (expected.to_string(), json_type_name(value).to_string())
+ }
+ TypeMismatch::OutOfRange { min, max, got } => {
+ log::debug!(
+ "[rpc][validate] param '{}' in {}.{} out of range: {got} not in {min}..={max}",
+ input.name,
+ schema.namespace,
+ schema.function,
+ );
+ // Name the limit that was actually crossed.
+ let bound = if got > max {
+ format!("unsigned integer <= {max}")
+ } else {
+ format!("unsigned integer >= {min}")
+ };
+ (bound, got.to_string())
+ }
+ };
format!(
"invalid type for param '{}' in {}.{}: expected {}, got {}",
- input.name,
- schema.namespace,
- schema.function,
- expected,
- json_type_name(value),
+ input.name, schema.namespace, schema.function, expected, got,
)
})?;
}
@@ -1527,6 +1543,16 @@ pub fn validate_params(
Ok(())
}
+/// Why a value failed [`check_type`].
+enum TypeMismatch {
+ /// The JSON kind is wrong; carries a short description of the required type.
+ Kind(&'static str),
+ /// An unsigned integer outside a [`TypeSchema::BoundedU64`] range.
+ ///
+ /// [`TypeSchema::BoundedU64`]: crate::core::TypeSchema::BoundedU64
+ OutOfRange { min: u64, max: u64, got: u64 },
+}
+
/// A short, human-readable name for the JSON kind of `value`, used in
/// `validate_params` type-mismatch errors.
fn json_type_name(value: &Value) -> &'static str {
@@ -1542,11 +1568,10 @@ fn json_type_name(value: &Value) -> &'static str {
/// Validate a JSON `value` against a declared [`TypeSchema`].
///
-/// Returns `Ok(())` on a match, or `Err(expected)` where `expected` is a short
-/// description of the type that was required. Unknown/opaque shapes
-/// (`Json`, `Bytes`, `Ref`) accept any value — they are validated by the
-/// handler's typed deserialization.
-fn check_type(value: &Value, ty: &crate::core::TypeSchema) -> Result<(), &'static str> {
+/// Returns `Ok(())` on a match, or a [`TypeMismatch`] describing what was
+/// required. Unknown/opaque shapes (`Json`, `Bytes`, `Ref`) accept any value —
+/// they are validated by the handler's typed deserialization.
+fn check_type(value: &Value, ty: &crate::core::TypeSchema) -> Result<(), TypeMismatch> {
use crate::core::TypeSchema;
// JSON-RPC semantics (preserved from the prior presence-only check):
@@ -1576,13 +1601,22 @@ fn check_type(value: &Value, ty: &crate::core::TypeSchema) -> Result<(), &'stati
| TypeSchema::Object { .. }
| TypeSchema::Map(_) => Ok(()),
- TypeSchema::Bool => value.is_boolean().then_some(()).ok_or("bool"),
- TypeSchema::String => value.is_string().then_some(()).ok_or("string"),
- TypeSchema::I64 => value.is_i64().then_some(()).ok_or("integer"),
- TypeSchema::U64 => value.is_u64().then_some(()).ok_or("unsigned integer"),
+ TypeSchema::Bool => kind(value.is_boolean(), "bool"),
+ TypeSchema::String => kind(value.is_string(), "string"),
+ TypeSchema::I64 => kind(value.is_i64(), "integer"),
+ TypeSchema::U64 => kind(value.is_u64(), "unsigned integer"),
+ TypeSchema::BoundedU64 { min, max } => match value.as_u64() {
+ Some(got) if (*min..=*max).contains(&got) => Ok(()),
+ Some(got) => Err(TypeMismatch::OutOfRange {
+ min: *min,
+ max: *max,
+ got,
+ }),
+ None => Err(TypeMismatch::Kind("unsigned integer")),
+ },
TypeSchema::F64 => {
// Accept any JSON number (ints are valid floats).
- value.is_number().then_some(()).ok_or("number")
+ kind(value.is_number(), "number")
}
// `Option<T>` accepts null or a value matching the inner type.
@@ -1601,17 +1635,22 @@ fn check_type(value: &Value, ty: &crate::core::TypeSchema) -> Result<(), &'stati
}
Ok(())
}
- None => Err("array"),
+ None => Err(TypeMismatch::Kind("array")),
},
TypeSchema::Enum { variants } => match value.as_str() {
Some(s) if variants.contains(&s) => Ok(()),
- Some(_) => Err("one of the allowed enum variants"),
- None => Err("string"),
+ Some(_) => Err(TypeMismatch::Kind("one of the allowed enum variants")),
+ None => Err(TypeMismatch::Kind("string")),
},
}
}
+/// `Ok(())` when `matches`, else a [`TypeMismatch::Kind`] naming `expected`.
+fn kind(matches: bool, expected: &'static str) -> Result<(), TypeMismatch> {
+ matches.then_some(()).ok_or(TypeMismatch::Kind(expected))
+}
+
/// Attempts to invoke a registered RPC method by name.
///
/// Checks both the agent-facing controller registry and the internal-only registry,
diff --git a/crates/openhuman-core/src/core/all_tests.rs b/crates/openhuman-core/src/core/all_tests.rs
index 7bdebfa682..891109f3cc 100644
--- a/crates/openhuman-core/src/core/all_tests.rs
+++ b/crates/openhuman-core/src/core/all_tests.rs
@@ -641,6 +641,103 @@ fn validate_params_option_accepts_null_and_inner_type() {
assert!(validate_params(&s, &bad_p).is_err());
}
+// --- validate_params bounded integers (#6137) ----------------------------
+
+fn bounded_schema(ty: TypeSchema) -> ControllerSchema {
+ schema(
+ "test",
+ "fn",
+ vec![FieldSchema {
+ name: "order",
+ ty,
+ comment: "",
+ required: false,
+ }],
+ )
+}
+
+fn order_params(value: Value) -> Map<String, Value> {
+ let mut p = Map::new();
+ p.insert("order".into(), value);
+ p
+}
+
+const U32_RANGE: TypeSchema = TypeSchema::BoundedU64 {
+ min: 0,
+ max: u32::MAX as u64,
+};
+
+#[test]
+fn validate_params_bounded_accepts_both_inclusive_ends() {
+ let s = bounded_schema(TypeSchema::BoundedU64 { min: 1, max: 10 });
+ assert!(validate_params(&s, &order_params(Value::from(1u64))).is_ok());
+ assert!(validate_params(&s, &order_params(Value::from(10u64))).is_ok());
+ assert!(validate_params(&s, &order_params(Value::Null)).is_ok());
+}
+
+#[test]
+fn validate_params_bounded_rejects_above_max_naming_the_bound() {
+ // The value `is_u64()`, so a plain `U64` declaration would have let it
+ // through to the handler's `u32` deserialization.
+ let s = bounded_schema(U32_RANGE);
+ let err = validate_params(&s, &order_params(Value::from(4_294_967_296u64))).unwrap_err();
+ assert_eq!(
+ err,
+ "invalid type for param 'order' in test.fn: expected unsigned integer <= 4294967295, got 4294967296"
+ );
+}
+
+#[test]
+fn validate_params_bounded_rejects_below_min_naming_the_bound() {
+ let s = bounded_schema(TypeSchema::BoundedU64 {
+ min: 1,
+ max: u32::MAX as u64,
+ });
+ let err = validate_params(&s, &order_params(Value::from(0u64))).unwrap_err();
+ assert_eq!(
+ err,
+ "invalid type for param 'order' in test.fn: expected unsigned integer >= 1, got 0"
+ );
+}
+
+#[test]
+fn validate_params_bounded_rejects_non_unsigned_values_by_kind() {
+ let s = bounded_schema(U32_RANGE);
+ for (value, got) in [
+ (Value::from(-1i64), "number"),
+ (Value::from(1.5f64), "number"),
+ (Value::from("7"), "string"),
+ ] {
+ let err = validate_params(&s, &order_params(value)).unwrap_err();
+ assert_eq!(
+ err,
+ format!(
+ "invalid type for param 'order' in test.fn: expected unsigned integer, got {got}"
+ )
+ );
+ }
+}
+
+#[test]
+fn validate_params_bounded_applies_inside_option_and_array() {
+ let opt = bounded_schema(TypeSchema::Option(Box::new(U32_RANGE)));
+ assert!(validate_params(&opt, &order_params(Value::from(5u64))).is_ok());
+ let err = validate_params(&opt, &order_params(Value::from(u64::MAX))).unwrap_err();
+ assert!(err.ends_with(&format!("got {}", u64::MAX)), "got: {err}");
+
+ let arr = bounded_schema(TypeSchema::Array(Box::new(TypeSchema::BoundedU64 {
+ min: 0,
+ max: u8::MAX as u64,
+ })));
+ assert!(validate_params(&arr, &order_params(serde_json::json!([0, 255]))).is_ok());
+ // The offending element is named, not the whole array.
+ let err = validate_params(&arr, &order_params(serde_json::json!([1, 256]))).unwrap_err();
+ assert!(
+ err.ends_with("expected unsigned integer <= 255, got 256"),
+ "got: {err}"
+ );
+}
+
#[test]
fn validate_params_json_type_accepts_anything() {
let s = schema(
diff --git a/crates/openhuman-core/src/core/cli.rs b/crates/openhuman-core/src/core/cli.rs
index d97b989ced..3e30de3888 100644
--- a/crates/openhuman-core/src/core/cli.rs
+++ b/crates/openhuman-core/src/core/cli.rs
@@ -677,6 +677,18 @@ fn parse_input_value(ty: &TypeSchema, raw: &str) -> Result<Value, String> {
.parse::<u64>()
.map(|n| Value::Number(n.into()))
.map_err(|e| format!("expected u64, got '{raw}': {e}")),
+ TypeSchema::BoundedU64 { min, max } => {
+ let n = raw
+ .parse::<u64>()
+ .map_err(|e| format!("expected unsigned integer, got '{raw}': {e}"))?;
+ if (*min..=*max).contains(&n) {
+ Ok(Value::Number(n.into()))
+ } else {
+ Err(format!(
+ "expected unsigned integer in {min}..={max}, got '{raw}'"
+ ))
+ }
+ }
TypeSchema::F64 => {
let n = raw
.parse::<f64>()
diff --git a/crates/openhuman-core/src/core/cli_tests.rs b/crates/openhuman-core/src/core/cli_tests.rs
index 9f7482235e..e4ecef74a5 100644
--- a/crates/openhuman-core/src/core/cli_tests.rs
+++ b/crates/openhuman-core/src/core/cli_tests.rs
@@ -135,6 +135,25 @@ fn parse_input_value_rejects_invalid_bool() {
assert!(err.contains("expected bool"));
}
+#[test]
+fn parse_input_value_enforces_bounded_u64_range() {
+ let ty = TypeSchema::BoundedU64 { min: 1, max: 10 };
+
+ assert_eq!(parse_input_value(&ty, "10").unwrap(), serde_json::json!(10));
+
+ let err = parse_input_value(&ty, "11").expect_err("above max should fail");
+ assert_eq!(err, "expected unsigned integer in 1..=10, got '11'");
+
+ let err = parse_input_value(&ty, "0").expect_err("below min should fail");
+ assert_eq!(err, "expected unsigned integer in 1..=10, got '0'");
+
+ let err = parse_input_value(&ty, "-3").expect_err("negative should fail");
+ assert!(
+ err.starts_with("expected unsigned integer, got '-3'"),
+ "got: {err}"
+ );
+}
+
#[test]
fn load_dotenv_for_cli_reads_cwd_dotenv_without_overwriting_existing_env() {
let _guard = env_lock();
diff --git a/crates/openhuman-core/src/core/core_mod_tests.rs b/crates/openhuman-core/src/core/core_mod_tests.rs
index a0429ef702..b912c77684 100644
--- a/crates/openhuman-core/src/core/core_mod_tests.rs
+++ b/crates/openhuman-core/src/core/core_mod_tests.rs
@@ -113,3 +113,21 @@ fn controller_schema_serializes_to_json() {
assert_eq!(json["inputs"][0]["name"], "limit");
assert_eq!(json["outputs"][0]["required"], true);
}
+
+#[test]
+fn bounded_u64_serializes_additively() {
+ // `/schema` is a public contract: the bound rides in a new variant, so
+ // existing `"U64"` fields keep their exact wire shape (#6137).
+ let bounded = TypeSchema::BoundedU64 {
+ min: 1,
+ max: u32::MAX as u64,
+ };
+ assert_eq!(
+ serde_json::to_value(&bounded).unwrap(),
+ serde_json::json!({ "BoundedU64": { "min": 1, "max": 4_294_967_295u64 } })
+ );
+ assert_eq!(
+ serde_json::to_value(TypeSchema::U64).unwrap(),
+ serde_json::json!("U64")
+ );
+}
diff --git a/crates/openhuman-core/src/core/mod.rs b/crates/openhuman-core/src/core/mod.rs
index 012408af7f..3a8c03c555 100644
--- a/crates/openhuman-core/src/core/mod.rs
+++ b/crates/openhuman-core/src/core/mod.rs
@@ -97,6 +97,19 @@ pub enum TypeSchema {
I64,
/// A 64-bit unsigned integer.
U64,
+ /// An unsigned integer confined to `min..=max` (both inclusive).
+ ///
+ /// Declares the real range of a field backed by a type narrower than
+ /// `u64` (`u32`, `u16`, `u8`, `NonZero*`), so `validate_params` refuses an
+ /// out-of-range value before dispatch instead of the handler's typed
+ /// deserialization failing after it (#6137). A plain `u32` field is
+ /// `BoundedU64 { min: 0, max: u32::MAX as u64 }`.
+ BoundedU64 {
+ /// Smallest accepted value.
+ min: u64,
+ /// Largest accepted value.
+ max: u64,
+ },
/// A 64-bit floating point number.
F64,
/// A UTF-8 encoded string.
diff --git a/crates/openhuman-core/src/tools/registry/ops.rs b/crates/openhuman-core/src/tools/registry/ops.rs
index c0fd4d13d1..74b9e6e7fe 100644
--- a/crates/openhuman-core/src/tools/registry/ops.rs
+++ b/crates/openhuman-core/src/tools/registry/ops.rs
@@ -421,6 +421,11 @@ fn type_schema_to_json(ty: &TypeSchema) -> Value {
match ty {
TypeSchema::Bool => json!({ "type": "boolean" }),
TypeSchema::I64 | TypeSchema::U64 => json!({ "type": "integer" }),
+ TypeSchema::BoundedU64 { min, max } => json!({
+ "type": "integer",
+ "minimum": min,
+ "maximum": max,
+ }),
TypeSchema::F64 => json!({ "type": "number" }),
TypeSchema::String => json!({ "type": "string" }),
TypeSchema::Json => json!({}),
diff --git a/crates/openhuman-core/src/tools/registry/ops_tests.rs b/crates/openhuman-core/src/tools/registry/ops_tests.rs
index 36354fd662..a70ace3df5 100644
--- a/crates/openhuman-core/src/tools/registry/ops_tests.rs
+++ b/crates/openhuman-core/src/tools/registry/ops_tests.rs
@@ -304,6 +304,31 @@ fn controller_json_schema_marks_required_and_optional_fields() {
);
}
+#[test]
+fn controller_json_schema_carries_bounded_integer_range() {
+ // A model reads the declared range as a promise, so it must see the bound
+ // the dispatch gate enforces (#6137).
+ let schema = schema_fields_to_json_schema(&[FieldSchema {
+ name: "order",
+ ty: TypeSchema::BoundedU64 {
+ min: 1,
+ max: u32::MAX as u64,
+ },
+ comment: "Sort position.",
+ required: true,
+ }]);
+
+ assert_eq!(
+ schema["properties"]["order"],
+ json!({
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 4_294_967_295u64,
+ "description": "Sort position.",
+ })
+ );
+}
+
fn capability_provider(
id: &str,
trust_state: CapabilityProviderTrustState,