Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
6 changes: 5 additions & 1 deletion crates/tinyagents-harness/src/config/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
2 changes: 1 addition & 1 deletion crates/tinyagents-harness/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
33 changes: 24 additions & 9 deletions crates/tinyagents-harness/src/config/types.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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<String>,
}

Expand Down Expand Up @@ -337,3 +348,7 @@ impl SessionConfig {
depth < self.max_depth
}
}

#[cfg(test)]
#[path = "types_serde_tests.rs"]
mod serde_tests;
147 changes: 147 additions & 0 deletions crates/tinyagents-harness/src/config/types_serde_tests.rs
Original file line number Diff line number Diff line change
@@ -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<String>,
}

/// How a host embeds the contract: an optional field of its agent section.
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
struct HostAgent<T> {
#[serde(default)]
required_output: Option<T>,
}

/// 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<RequiredOutput> = 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<RequiredOutput> = 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<RequiredOutput> = toml::from_str(input).unwrap();
let theirs: HostAgent<RequiredOutputContract> = 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<RequiredOutput> =
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<T: schemars::JsonSchema>() -> 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::<RequiredOutput>();
assert_eq!(ours, wire_schema::<RequiredOutputContract>());
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")
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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`.
Expand Down
41 changes: 34 additions & 7 deletions crates/tinyagents-harness/src/providers/claude_agent_sdk/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<f64>,
}

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,
}
}
Expand Down Expand Up @@ -592,3 +615,7 @@ fn coalesce_system_prompt(messages: &[Message]) -> Option<String> {
#[cfg(test)]
#[path = "mod_tests.rs"]
mod tests;

#[cfg(test)]
#[path = "mod_serde_tests.rs"]
mod serde_tests;
Loading
Loading