diff --git a/CHANGELOG.md b/CHANGELOG.md index a41c351dd..69a4be507 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## Unreleased + +- `tinyagents-harness`: `providers::claude_agent_sdk::ClaudeAgentSdkConfig` + now derives `Serialize`, `Deserialize` and `schemars::JsonSchema`, with + per-field defaults matching `Default`, so a host can embed it as a config + section instead of mirroring it. `config::RequiredOutput` gains + `schemars::JsonSchema` and container-level `#[serde(default)]`. + **Behaviour change:** a `RequiredOutput` with no `block_key` now + deserializes to the inert blank key instead of failing to parse. + ## 3.1.4 - Releases are cut from `main`: the version bump merges through a pull request diff --git a/crates/tinyagents-harness/src/config/README.md b/crates/tinyagents-harness/src/config/README.md index 89d9e5214..4bb446636 100644 --- a/crates/tinyagents-harness/src/config/README.md +++ b/crates/tinyagents-harness/src/config/README.md @@ -40,13 +40,17 @@ question by existing. the boundary, not a silent fallthrough in the turn loop. - [`RequiredOutput`] — a structured-output contract asserting the model's reply carries a particular JSON block; a blank `block_key` makes the - contract inert by design, so it is a safe zero-value default. + contract inert by design, so it is a safe zero-value default. It derives + `Serialize`/`Deserialize`/`JsonSchema` with `#[serde(default)]` on the + container, so a host can read it straight from a config section (for example + `[agent.required_output]`) where both fields are optional. ## Files | File | Role | | ---------- | ---------------------------------------------------------------------- | | `mod.rs` | Module overview and re-exports. | +| `types_serde_tests.rs` | `RequiredOutput` TOML/JSON and JSON-schema parity with OpenHuman's former mirror type. | | `required_output.rs` | Pure primitives over `RequiredOutput`: `output_satisfies_contract`, `find_required_block`, `synthesize_block`, `repair_instruction`. | | `types.rs` | All types: `SessionConfig`, `TurnConfig`, `ToolConfig`, `MemoryLimits`, `ToolDispatcher`, `RequiredOutput`, and their serde defaults. | | `mod_tests.rs` | Unit tests: defaulting, fallback rules, inert-contract behaviour, serde round-tripping. | diff --git a/crates/tinyagents-harness/src/config/mod.rs b/crates/tinyagents-harness/src/config/mod.rs index f0861827c..034b7b805 100644 --- a/crates/tinyagents-harness/src/config/mod.rs +++ b/crates/tinyagents-harness/src/config/mod.rs @@ -23,7 +23,7 @@ //! and are separable so a caller can override one turn's limits without //! rebuilding the session. //! -//! The types are inert — `serde` + `std` only, see `types`; `required_output` +//! The types are inert — `serde` + `schemars` + `std` only, see `types`; `required_output` //! adds pure validate/repair functions over [`RequiredOutput`]. Capabilities //! (memory, security, budget, progress) are trait objects supplied separately; //! nothing in this module is a behaviour seam. diff --git a/crates/tinyagents-harness/src/config/types.rs b/crates/tinyagents-harness/src/config/types.rs index 9d87765a6..98ac460d4 100644 --- a/crates/tinyagents-harness/src/config/types.rs +++ b/crates/tinyagents-harness/src/config/types.rs @@ -1,9 +1,11 @@ //! Inert configuration value types for the harness. //! -//! **Dependency rule:** this module is `serde` + `std` only. No engine types, -//! no tokio, no host types. A host must be able to depend on these structs to -//! build a mapper without pulling in the rest of the crate's machinery — the -//! same carve-out that keeps a gated domain's type module always-compiled. +//! **Dependency rule:** this module is `serde` + `schemars` + `std` only (the +//! `schemars` derives let a host embed these types in its own config schema). +//! No engine types, no tokio, no host types. A host must be able to depend on +//! these structs to build a mapper without pulling in the rest of the crate's +//! machinery — the same carve-out that keeps a gated domain's type module +//! always-compiled. use serde::{Deserialize, Serialize}; use std::collections::HashMap; @@ -91,13 +93,22 @@ pub enum ToolDispatcher { /// Satisfied when the reply contains a JSON object carrying `block_key` — plus /// every entry in `required_keys` — with a non-null value. A blank `block_key` /// makes the contract **inert** (enforcement skipped), so it is a safe default. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +/// +/// Every field is optional on the wire (`#[serde(default)]` on the container): +/// a missing `block_key` deserializes to the inert blank key and a missing +/// `required_keys` to an empty list. Both fields are always serialized. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default, schemars::JsonSchema)] +#[serde(default)] pub struct RequiredOutput { - /// The JSON key identifying the required block, e.g. `"thoughts"`. + /// The JSON key that identifies the required block (e.g. `"thoughts"`). The + /// contract is satisfied when the reply contains a JSON object carrying this + /// key — plus every key in [`required_keys`](Self::required_keys) — with a + /// non-null value. A blank `block_key` makes the contract inert (enforcement + /// is skipped), so it is a safe no-op default. pub block_key: String, - /// Sibling keys that must also be present and non-null in the same block. - /// `block_key` is always required and need not be repeated here. - #[serde(default)] + /// Additional sibling keys that must also be present and non-null in the + /// same block (e.g. `["next_action"]`). The `block_key` is always required + /// and need not be repeated here. pub required_keys: Vec, } @@ -337,3 +348,7 @@ impl SessionConfig { depth < self.max_depth } } + +#[cfg(test)] +#[path = "types_serde_tests.rs"] +mod serde_tests; diff --git a/crates/tinyagents-harness/src/config/types_serde_tests.rs b/crates/tinyagents-harness/src/config/types_serde_tests.rs new file mode 100644 index 000000000..d45858312 --- /dev/null +++ b/crates/tinyagents-harness/src/config/types_serde_tests.rs @@ -0,0 +1,147 @@ +//! Serde and JSON-schema parity tests for [`RequiredOutput`]. +//! +//! OpenHuman reads this contract from `[agent.required_output]` in its TOML +//! config through its own mirror type, `RequiredOutputContract`. The mirror is +//! reproduced verbatim below so these tests pin that the upstream derives read +//! the same files, write the same bytes and describe the same JSON schema — +//! the guarantee a host needs to swap its mirror for this type. + +use super::*; +use serde_json::json; + +/// OpenHuman's `config::schema::agent::RequiredOutputContract`, verbatim +/// (derives, attributes and field docs), as the parity oracle. +#[derive( + Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize, schemars::JsonSchema, +)] +#[serde(default)] +struct RequiredOutputContract { + /// The JSON key that identifies the required block (e.g. `"thoughts"`). The + /// contract is satisfied when the reply contains a JSON object carrying this + /// key — plus every key in [`required_keys`](Self::required_keys) — with a + /// non-null value. A blank `block_key` makes the contract inert (enforcement + /// is skipped), so it is a safe no-op default. + pub block_key: String, + /// Additional sibling keys that must also be present and non-null in the + /// same block (e.g. `["next_action"]`). The `block_key` is always required + /// and need not be repeated here. + pub required_keys: Vec, +} + +/// How a host embeds the contract: an optional field of its agent section. +#[derive(Debug, Default, serde::Serialize, serde::Deserialize)] +struct HostAgent { + #[serde(default)] + required_output: Option, +} + +/// TOML inputs a host config may carry for the contract. +const TOML_CASES: &[&str] = &[ + "[required_output]\nblock_key = \"thoughts\"\nrequired_keys = [\"next_action\"]\n", + "[required_output]\nblock_key = \"thoughts\"\n", + "[required_output]\nrequired_keys = [\"next_action\"]\n", + "[required_output]\n", + "", +]; + +#[test] +fn reads_a_full_toml_contract() { + let agent: HostAgent = toml::from_str(TOML_CASES[0]).unwrap(); + let contract = agent.required_output.expect("section present"); + assert_eq!(contract.block_key, "thoughts"); + assert_eq!(contract.required_keys, vec!["next_action".to_string()]); + assert!(contract.is_active()); +} + +#[test] +fn omitted_fields_take_the_inert_defaults() { + let only_key: RequiredOutput = + serde_json::from_value(json!({"block_key": "thoughts"})).unwrap(); + assert_eq!(only_key, RequiredOutput::new("thoughts")); + + // A missing `block_key` is no longer a parse error: it is the inert blank + // key, exactly as OpenHuman's mirror reads it. + let no_key: RequiredOutput = + serde_json::from_value(json!({"required_keys": ["next_action"]})).unwrap(); + assert_eq!(no_key.block_key, ""); + assert_eq!(no_key.required_keys, vec!["next_action".to_string()]); + assert!(!no_key.is_active()); + + let empty: RequiredOutput = serde_json::from_value(json!({})).unwrap(); + assert_eq!(empty, RequiredOutput::default()); + + let absent: HostAgent = toml::from_str("").unwrap(); + assert!(absent.required_output.is_none()); +} + +#[test] +fn serializes_every_field() { + assert_eq!( + serde_json::to_value(RequiredOutput::default()).unwrap(), + json!({"block_key": "", "required_keys": []}) + ); + assert_eq!( + toml::to_string(&RequiredOutput { + block_key: "thoughts".into(), + required_keys: vec!["next_action".into()], + }) + .unwrap(), + "block_key = \"thoughts\"\nrequired_keys = [\"next_action\"]\n" + ); +} + +#[test] +fn toml_and_json_match_openhumans_mirror_byte_for_byte() { + for input in TOML_CASES { + let ours: HostAgent = toml::from_str(input).unwrap(); + let theirs: HostAgent = toml::from_str(input).unwrap(); + assert_eq!( + ours.required_output + .as_ref() + .map(|c| (&c.block_key, &c.required_keys)), + theirs + .required_output + .as_ref() + .map(|c| (&c.block_key, &c.required_keys)), + "parsed values differ for {input:?}" + ); + assert_eq!( + toml::to_string(&ours).unwrap(), + toml::to_string(&theirs).unwrap(), + "TOML output differs for {input:?}" + ); + assert_eq!( + serde_json::to_string(&ours).unwrap(), + serde_json::to_string(&theirs).unwrap(), + "JSON output differs for {input:?}" + ); + // The re-serialized TOML reads back to the same value. + let again: HostAgent = + toml::from_str(&toml::to_string(&ours).unwrap()).unwrap(); + assert_eq!(again.required_output, ours.required_output); + } +} + +/// The root schema of `T` without the type-level `title`/`description`, which +/// name the Rust type rather than describe the wire shape. +fn wire_schema() -> serde_json::Value { + let mut schema = serde_json::to_value(schemars::schema_for!(T)).unwrap(); + let object = schema.as_object_mut().unwrap(); + object.remove("title"); + object.remove("description"); + schema +} + +#[test] +fn json_schema_matches_openhumans_mirror() { + let ours = wire_schema::(); + assert_eq!(ours, wire_schema::()); + assert_eq!(ours["type"], json!("object")); + assert!(ours.get("required").is_none(), "no field is required"); + assert_eq!(ours["properties"]["block_key"]["default"], json!("")); + assert_eq!(ours["properties"]["required_keys"]["default"], json!([])); + assert_eq!( + schemars::schema_for!(RequiredOutput).as_value()["title"], + json!("RequiredOutput") + ); +} diff --git a/crates/tinyagents-harness/src/providers/claude_agent_sdk/README.md b/crates/tinyagents-harness/src/providers/claude_agent_sdk/README.md index fe5ee5782..95aa457d9 100644 --- a/crates/tinyagents-harness/src/providers/claude_agent_sdk/README.md +++ b/crates/tinyagents-harness/src/providers/claude_agent_sdk/README.md @@ -16,6 +16,7 @@ plain prompt-guided chat model, not an agent driver. | `mod.rs` | `ClaudeAgentSdkConfig`, `ClaudeAgentSdkProvider` (`ChatModel<()>` impl), CLI argument/stdin building, the subprocess spawn/read/timeout loop, and system-prompt/transcript rendering. | | `protocol.rs` | `SdkMessage`/`SdkError`: the `serde` shapes for the `--output-format stream-json` NDJSON lines the CLI writes to stdout. | | `mod_tests.rs` | Unit tests for construction, invocation building, transcript rendering, and response assembly. | +| `mod_serde_tests.rs` | `ClaudeAgentSdkConfig` TOML/JSON and JSON-schema parity with OpenHuman's former mirror type. | ## Request shaping @@ -59,6 +60,13 @@ model) and pass it to the harness like any other `ChatModel`. `ClaudeAgentSdkConfig::enabled` is a plain data field for the embedding application's own gating — this crate does not read it. +`ClaudeAgentSdkConfig` derives `Serialize`, `Deserialize` and +`schemars::JsonSchema`, so a host can embed it directly as a config section +(OpenHuman's `[claude_agent_sdk]`). Every field is optional on input and takes +the `Default` value (`enabled = false`, `binary = "claude"`, +`default_model = "claude-sonnet-4-6"`, no budget); all four fields are +serialized, with a `None` budget written as JSON `null` and left out of TOML. + Doctor may construct `ClaudeAgentSdkProvider::for_inspection` only with an explicit API key or bearer token captured by its host. A gateway bearer is passed through `ANTHROPIC_AUTH_TOKEN`; it does not require `ANTHROPIC_API_KEY`. diff --git a/crates/tinyagents-harness/src/providers/claude_agent_sdk/mod.rs b/crates/tinyagents-harness/src/providers/claude_agent_sdk/mod.rs index 398327b56..a063a203e 100644 --- a/crates/tinyagents-harness/src/providers/claude_agent_sdk/mod.rs +++ b/crates/tinyagents-harness/src/providers/claude_agent_sdk/mod.rs @@ -26,24 +26,47 @@ use tokio::time::{Duration, timeout}; use protocol::SdkMessage; /// Configuration for the Claude CLI subprocess adapter. -#[derive(Debug, Clone)] +/// +/// Deserializes from a host config section such as `[claude_agent_sdk]`: every +/// field is optional, and a missing field takes the same value as +/// [`ClaudeAgentSdkConfig::default`]. Serialization always writes all four +/// fields (`max_budget_usd = None` becomes JSON `null` and is omitted by +/// TOML), so a host can embed this type directly in its own config schema. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)] pub struct ClaudeAgentSdkConfig { - /// Whether the embedding host enables this provider. + /// Whether the Claude Agent SDK provider is enabled. + #[serde(default)] pub enabled: bool, - /// Claude CLI binary or path. + + /// Path to the `claude` CLI binary. Defaults to `"claude"` (PATH lookup). + #[serde(default = "default_claude_binary")] pub binary: String, - /// Model used when a request does not override it. + + /// Default model passed via `--model` when the provider string is just + /// `"claude_agent_sdk"` with no model suffix. + #[serde(default = "default_claude_model")] pub default_model: String, - /// Optional maximum request budget in US dollars. + + /// Maximum spend in USD before aborting a request (`--max-turns` controls + /// loop depth; `--budget` controls cost). `None` means no cap. + #[serde(default)] pub max_budget_usd: Option, } +fn default_claude_binary() -> String { + "claude".to_string() +} + +fn default_claude_model() -> String { + "claude-sonnet-4-6".to_string() +} + impl Default for ClaudeAgentSdkConfig { fn default() -> Self { Self { enabled: false, - binary: "claude".to_string(), - default_model: "claude-sonnet-4-6".to_string(), + binary: default_claude_binary(), + default_model: default_claude_model(), max_budget_usd: None, } } @@ -592,3 +615,7 @@ fn coalesce_system_prompt(messages: &[Message]) -> Option { #[cfg(test)] #[path = "mod_tests.rs"] mod tests; + +#[cfg(test)] +#[path = "mod_serde_tests.rs"] +mod serde_tests; diff --git a/crates/tinyagents-harness/src/providers/claude_agent_sdk/mod_serde_tests.rs b/crates/tinyagents-harness/src/providers/claude_agent_sdk/mod_serde_tests.rs new file mode 100644 index 000000000..21a46cae1 --- /dev/null +++ b/crates/tinyagents-harness/src/providers/claude_agent_sdk/mod_serde_tests.rs @@ -0,0 +1,182 @@ +//! Serde and JSON-schema parity tests for [`ClaudeAgentSdkConfig`]. +//! +//! OpenHuman reads this config from the `[claude_agent_sdk]` section of its +//! TOML config through its own mirror type. The mirror is reproduced verbatim +//! below so these tests pin that the upstream derives read the same files, +//! write the same bytes and describe the same JSON schema — the guarantee a +//! host needs to swap its mirror for this type. + +use super::*; +use serde_json::json; + +/// OpenHuman's `config::schema::claude_agent_sdk::ClaudeAgentSdkConfig`, +/// verbatim (derives, attributes, field docs and default functions), as the +/// parity oracle. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)] +struct OpenHumanClaudeAgentSdkConfig { + /// Whether the Claude Agent SDK provider is enabled. + #[serde(default)] + pub enabled: bool, + + /// Path to the `claude` CLI binary. Defaults to `"claude"` (PATH lookup). + #[serde(default = "default_claude_binary")] + pub binary: String, + + /// Default model passed via `--model` when the provider string is just + /// `"claude_agent_sdk"` with no model suffix. + #[serde(default = "default_claude_model")] + pub default_model: String, + + /// Maximum spend in USD before aborting a request (`--max-turns` controls + /// loop depth; `--budget` controls cost). `None` means no cap. + #[serde(default)] + pub max_budget_usd: Option, +} + +impl Default for OpenHumanClaudeAgentSdkConfig { + fn default() -> Self { + Self { + enabled: false, + binary: default_claude_binary(), + default_model: default_claude_model(), + max_budget_usd: None, + } + } +} + +/// How OpenHuman embeds the section: `#[serde(default)] claude_agent_sdk`. +#[derive(Debug, Default, serde::Serialize, serde::Deserialize)] +struct HostConfig { + #[serde(default)] + claude_agent_sdk: T, +} + +/// TOML inputs a host config may carry for the section. +const TOML_CASES: &[&str] = &[ + "[claude_agent_sdk]\nenabled = true\nbinary = \"/opt/bin/claude\"\n\ + default_model = \"claude-opus-4-1\"\nmax_budget_usd = 2.5\n", + "[claude_agent_sdk]\nenabled = true\n", + "[claude_agent_sdk]\nmax_budget_usd = 0.25\n", + "[claude_agent_sdk]\n", + "", +]; + +fn fields(c: &ClaudeAgentSdkConfig) -> (bool, &str, &str, Option) { + (c.enabled, &c.binary, &c.default_model, c.max_budget_usd) +} + +fn mirror_fields(c: &OpenHumanClaudeAgentSdkConfig) -> (bool, &str, &str, Option) { + (c.enabled, &c.binary, &c.default_model, c.max_budget_usd) +} + +#[test] +fn reads_a_full_toml_section() { + let host: HostConfig = toml::from_str(TOML_CASES[0]).unwrap(); + assert_eq!( + fields(&host.claude_agent_sdk), + (true, "/opt/bin/claude", "claude-opus-4-1", Some(2.5)) + ); +} + +#[test] +fn omitted_fields_take_the_default_values() { + let only_enabled: ClaudeAgentSdkConfig = + serde_json::from_value(json!({"enabled": true})).unwrap(); + assert_eq!( + fields(&only_enabled), + (true, "claude", "claude-sonnet-4-6", None) + ); + + let empty: ClaudeAgentSdkConfig = serde_json::from_value(json!({})).unwrap(); + assert_eq!(fields(&empty), fields(&ClaudeAgentSdkConfig::default())); + + let absent: HostConfig = toml::from_str("").unwrap(); + assert_eq!( + fields(&absent.claude_agent_sdk), + fields(&ClaudeAgentSdkConfig::default()) + ); +} + +#[test] +fn serializes_every_field_and_none_as_null_or_omitted() { + assert_eq!( + serde_json::to_value(ClaudeAgentSdkConfig::default()).unwrap(), + json!({ + "enabled": false, + "binary": "claude", + "default_model": "claude-sonnet-4-6", + "max_budget_usd": null + }) + ); + // TOML has no null: a `None` budget is left out, and reads back as `None`. + assert_eq!( + toml::to_string(&ClaudeAgentSdkConfig::default()).unwrap(), + "enabled = false\nbinary = \"claude\"\ndefault_model = \"claude-sonnet-4-6\"\n" + ); +} + +#[test] +fn toml_and_json_match_openhumans_mirror_byte_for_byte() { + for input in TOML_CASES { + let ours: HostConfig = toml::from_str(input).unwrap(); + let theirs: HostConfig = toml::from_str(input).unwrap(); + assert_eq!( + fields(&ours.claude_agent_sdk), + mirror_fields(&theirs.claude_agent_sdk), + "parsed values differ for {input:?}" + ); + let ours_toml = toml::to_string(&ours).unwrap(); + assert_eq!( + ours_toml, + toml::to_string(&theirs).unwrap(), + "TOML output differs for {input:?}" + ); + assert_eq!( + serde_json::to_string(&ours).unwrap(), + serde_json::to_string(&theirs).unwrap(), + "JSON output differs for {input:?}" + ); + // The re-serialized TOML reads back to the same values. + let again: HostConfig = toml::from_str(&ours_toml).unwrap(); + assert_eq!( + fields(&again.claude_agent_sdk), + fields(&ours.claude_agent_sdk) + ); + } +} + +#[test] +fn mistyped_fields_are_rejected_like_the_mirror() { + let bad = json!({"enabled": "yes"}); + assert!(serde_json::from_value::(bad.clone()).is_err()); + assert!(serde_json::from_value::(bad).is_err()); +} + +/// The root schema of `T` without the type-level `title`/`description`, which +/// name the Rust type rather than describe the wire shape. +fn wire_schema() -> serde_json::Value { + let mut schema = serde_json::to_value(schemars::schema_for!(T)).unwrap(); + let object = schema.as_object_mut().unwrap(); + object.remove("title"); + object.remove("description"); + schema +} + +#[test] +fn json_schema_matches_openhumans_mirror() { + let ours = wire_schema::(); + assert_eq!(ours, wire_schema::()); + assert!(ours.get("required").is_none(), "no field is required"); + let props = &ours["properties"]; + assert_eq!(props["enabled"]["default"], json!(false)); + assert_eq!(props["binary"]["default"], json!("claude")); + assert_eq!( + props["default_model"]["default"], + json!("claude-sonnet-4-6") + ); + assert_eq!(props["max_budget_usd"]["default"], json!(null)); + assert_eq!( + schemars::schema_for!(ClaudeAgentSdkConfig).as_value()["title"], + json!("ClaudeAgentSdkConfig") + ); +}