diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index 46f6f95..f3ca2ee 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -1,6 +1,11 @@ +{"_type":"issue","id":"killall-agent-e0a.3","title":"Do not validate unselected Pi provider entries","description":"Claude review identified and local binary reproduction confirmed a regression: Config providers BTreeMap\u003cString, ProviderConfig\u003e eagerly requires all fields on every provider. A valid strata entry next to anthropic:{baseUrl:...} fails Invalid Pi provider configuration / missing apiKey before selection. Installed Pi docs/models.md explicitly permits baseUrl-only overrides for built-in providers. Parse/validate only the selected provider, and add a regression test with an unrelated partial provider. Review output: /tmp/killall-agent-claude-review.txt.","status":"closed","priority":1,"issue_type":"bug","assignee":"archae0pteryx","owner":"github@pocketcereal.com","created_at":"2026-12-03T00:53:29Z","created_by":"archae0pteryx","updated_at":"2026-12-03T00:59:08Z","started_at":"2026-12-03T00:57:41Z","closed_at":"2026-12-03T00:59:08Z","close_reason":"Provider entries remain raw JSON until selected; only selected entry is deserialized with provider-specific context. Regression test failed for missing apiKey before fix and now passes; selected incomplete provider still reports concrete serde_json error. Full suite: 40 tests.","dependencies":[{"issue_id":"killall-agent-e0a.3","depends_on_id":"killall-agent-e0a","type":"parent-child","created_at":"2026-12-03T00:53:29Z","created_by":"archae0pteryx","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"killall-agent-e0a.4","title":"Trigger CI for sandbox YAML definition changes","description":"Claude review confirmed .github/workflows/ci.yml pull_request and push path filters omit sandbox/**, while src/definition.rs uses include_str! on sandbox/example-def.yaml and sandbox/default.yaml. YAML-only changes can break compilation/tests or the default agent without triggering CI. Add sandbox/** to both filters.","status":"in_progress","priority":2,"issue_type":"bug","assignee":"archae0pteryx","owner":"github@pocketcereal.com","created_at":"2026-12-03T00:53:30Z","created_by":"archae0pteryx","updated_at":"2026-12-03T00:57:42Z","started_at":"2026-12-03T00:57:42Z","lease_expires_at":"2026-12-03T01:02:42Z","heartbeat_at":"2026-12-03T00:57:42Z","dependencies":[{"issue_id":"killall-agent-e0a.4","depends_on_id":"killall-agent-e0a","type":"parent-child","created_at":"2026-12-03T00:53:30Z","created_by":"archae0pteryx","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"killall-agent-e0a.2","title":"Review YAML agent loader with Claude","description":"User requested claude -p review of the first YAML loader slice. Obtain read-only review, independently verify impactful findings, and report results without changing implementation.","status":"closed","priority":2,"issue_type":"task","assignee":"archae0pteryx","owner":"github@pocketcereal.com","created_at":"2026-12-03T00:52:16Z","created_by":"archae0pteryx","updated_at":"2026-12-03T00:53:31Z","started_at":"2026-12-03T00:52:27Z","closed_at":"2026-12-03T00:53:31Z","close_reason":"Ran claude -p read-only review and independently verified both findings: reproduced unrelated partial provider failure with isolated HOME and confirmed Pi docs support baseUrl-only overrides; inspected CI filters and fixture includes. Findings tracked as follow-up bugs; no implementation edits.","dependencies":[{"issue_id":"killall-agent-e0a.2","depends_on_id":"killall-agent-e0a","type":"parent-child","created_at":"2026-12-03T00:52:16Z","created_by":"archae0pteryx","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"killall-agent-e0a.1","title":"Parse YAML agent definitions and require --agent at startup","description":"First implementation slice: typed YAML definition loader, required --agent, optional --model override, generic provider/model selection from Pi providers JSON, sandbox/default.yaml. Parse tool and skill lists without resolving them; defer tool selection, instructions and skill loading. Relative agentfile paths are based on definition directory. Verify parser, CLI, model resolution and startup failure paths with offline tests.","status":"closed","priority":2,"issue_type":"task","assignee":"archae0pteryx","owner":"github@pocketcereal.com","created_at":"2026-12-03T00:37:10Z","created_by":"archae0pteryx","updated_at":"2026-12-03T00:40:33Z","started_at":"2026-12-03T00:37:22Z","closed_at":"2026-12-03T00:40:33Z","close_reason":"Implemented typed YAML parsing, required --agent, --model precedence, JSON-key provider/model resolution, default YAML and task run wiring. Tools/skills/instructions parsed only. Verified 37 tests, fmt, clippy -D warnings, diff check; no live provider calls.","dependencies":[{"issue_id":"killall-agent-e0a.1","depends_on_id":"killall-agent-e0a","type":"parent-child","created_at":"2026-12-03T00:37:10Z","created_by":"archae0pteryx","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"killall-agent-e0a","title":"Load agent definitions from YAML via --agent","description":"Design and implement agent definitions using sandbox/example-def.yaml. Proposed components: typed YAML definition parsing and validation; CLI --agent path and precedence; model resolution through existing model-loader work (killall-agent-y5r); selection of available tools; agentfile instruction loading; skill source resolution; final runtime assembly. Keep definition parsing separate from provider credentials and side-effectful resource resolution. Decisions needed before implementation: CLI override behavior, relative-path base, ALL and tool-name semantics, supported skill sources, and required/defaulted fields. Baseline inspected: src/cli.rs, src/config.rs, src/models.rs, src/tools.rs, src/main.rs. cargo test --locked passes 21 tests. No implementation started.","design":"Confirmed: --agent required; explicit CLI arguments override YAML; future YAML keys should have CLI counterparts; relative resources resolve from definition directory, workspace stays unchanged. ALL means all registered tools but tool resolution is deferred. Parse skills only, no fetching. Model provider is a key in Pi providers JSON; selection splits at the first slash.","notes":"First slice complete in killall-agent-e0a.1. src/definition.rs parses names, model selections, tool/skill lists and optional agentfile, with agentfile relative to definition directory. Required name/model; optional lists empty by default. --agent required; --model overrides YAML. sandbox/default.yaml selects strata/qwen3.8. Runtime tool selection, instruction loading, skills and additional CLI counterparts remain future slices. 37 tests passing, fmt/clippy/diff checks clean.","status":"open","priority":2,"issue_type":"feature","owner":"github@pocketcereal.com","created_at":"2026-12-03T00:33:17Z","created_by":"archae0pteryx","updated_at":"2026-12-03T00:40:34Z","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"killall-agent-0ds","title":"Merge config/models and hall-monitor work onto main","description":"Restore outstanding hall-monitor branch work into PR #4, include all current work, validate shell and Rust tests, wait for CI, merge, and fast-forward local main to origin/main.","status":"closed","priority":2,"issue_type":"task","assignee":"archae0pteryx","owner":"github@pocketcereal.com","created_at":"2026-12-03T00:24:34Z","created_by":"archae0pteryx","updated_at":"2026-12-03T00:28:50Z","started_at":"2026-12-03T00:24:40Z","closed_at":"2026-12-03T00:28:50Z","close_reason":"Merged PR #4 (config/models refactor, sandbox example, Beads export, and all hall-monitor script/tests) after all six hosted checks passed. Closed superseded PR #2 and fast-forwarded local main to origin/main. All 21 Rust tests and 11 hall-monitor checks, ShellCheck, actionlint, formatting, Clippy, and build passed locally.","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"killall-agent-9rk","title":"Open PR for config and models separation","description":"Create a feature branch containing all working-tree changes, including the Beads export and sandbox agent-definition example. Rerun checks, confirm latest remote main, push, and open a pull request.","status":"closed","priority":2,"issue_type":"task","assignee":"archae0pteryx","owner":"github@pocketcereal.com","created_at":"2026-12-03T00:22:39Z","created_by":"archae0pteryx","updated_at":"2026-12-03T00:23:25Z","started_at":"2026-12-03T00:22:47Z","closed_at":"2026-12-03T00:23:25Z","close_reason":"Created and pushed refactor/config-and-models with all working-tree changes, opened PR #4: https://github.com/killallgit/killall-agent/pull/4. All 21 tests, formatting, Clippy, build and CLI smoke checks pass; verified latest origin/main is an ancestor before push.","dependency_count":0,"dependent_count":0,"comment_count":0} -{"_type":"issue","id":"killall-agent-y5r","title":"Build out the model loader","description":"Follow up on the config/models separation: design and implement model loading beyond the existing Strata qwen3.8 path behind the common models interface. Confirm supported providers, selection behavior, and configuration requirements before expanding scope; keep this separate from the behavior-preserving module extraction.","status":"open","priority":2,"issue_type":"task","owner":"github@pocketcereal.com","created_at":"2026-12-03T00:17:41Z","created_by":"archae0pteryx","updated_at":"2026-12-03T00:17:41Z","dependencies":[{"issue_id":"killall-agent-y5r","depends_on_id":"killall-agent-985","type":"blocks","created_at":"2026-12-03T00:19:07Z","created_by":"archae0pteryx","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"killall-agent-y5r","title":"Build out the model loader","description":"Follow up on the config/models separation: design and implement model loading beyond the existing Strata qwen3.8 path behind the common models interface. Confirm supported providers, selection behavior, and configuration requirements before expanding scope; keep this separate from the behavior-preserving module extraction.","notes":"First slice implemented under killall-agent-e0a.1: model selection now splits provider/model at the first slash, provider comes from the Pi providers JSON key, and the model ID is checked against that provider. Construction still supports only openai-completions. Broader provider/API design remains open.","status":"open","priority":2,"issue_type":"task","owner":"github@pocketcereal.com","created_at":"2026-12-03T00:17:41Z","created_by":"archae0pteryx","updated_at":"2026-12-03T00:40:32Z","dependencies":[{"issue_id":"killall-agent-y5r","depends_on_id":"killall-agent-985","type":"blocks","created_at":"2026-12-03T00:19:07Z","created_by":"archae0pteryx","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"killall-agent-985","title":"Separate model construction from Pi configuration","description":"Extract config and models modules from strata.rs and main.rs while preserving the Pi models.json source and the single supported CLI model. Verify with focused tests, the full test suite, formatting and clippy.","status":"closed","priority":2,"issue_type":"task","assignee":"archae0pteryx","owner":"github@pocketcereal.com","created_at":"2026-12-03T00:17:16Z","created_by":"archae0pteryx","updated_at":"2026-12-03T00:19:09Z","started_at":"2026-12-03T00:17:21Z","closed_at":"2026-12-03T00:19:09Z","close_reason":"Extracted Pi config and credential handling into config, moved selection and model construction into models with a provider-neutral DynModel\u003cCompletion\u003e result, and simplified main. All 21 tests, formatting, clippy with warnings denied, build, and CLI help/version smoke checks pass. Model-loader expansion tracked separately in killall-agent-y5r.","dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"killall-agent-i14","title":"Open and merge read-only tool loading PR","description":"Review and validate tool loading and integration tests, push a feature branch, open a PR, wait for hosted checks, address blockers and merge once green.","status":"closed","priority":2,"issue_type":"task","assignee":"archae0pteryx","owner":"github@pocketcereal.com","created_at":"2026-12-02T23:54:47Z","created_by":"archae0pteryx","updated_at":"2026-12-03T00:04:27Z","started_at":"2026-12-02T23:55:04Z","closed_at":"2026-12-03T00:04:27Z","close_reason":"Merged PR #3 after all seven hosted checks passed and no review findings. Hall-monitor graded all seven selected files A; all 18 local tests, formatting, clippy, build, CLI smoke test, actionlint and diff checks passed. Added tests/** CI path filters.","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"killall-agent-1kq","title":"Add agent integration tests for read list and search","description":"Exercise each loaded tool through the Rig agent loop with a scripted model and real temporary workspace, keeping integration tests separate from unit tests and avoiding network calls.","status":"closed","priority":2,"issue_type":"task","assignee":"archae0pteryx","owner":"github@pocketcereal.com","created_at":"2026-12-02T23:23:35Z","created_by":"archae0pteryx","updated_at":"2026-12-02T23:25:55Z","started_at":"2026-12-02T23:24:19Z","closed_at":"2026-12-02T23:25:55Z","close_reason":"Added tests/tools.rs with one full agent-loop test each for read/list/search, asserting advertised tools, call identity, successful results and actual workspace content in the next model request. Exposed the existing tools module through src/lib.rs and replaced redundant direct-dispatch tests. All 18 tests, clippy, formatting and diff checks pass; no network or credentials required.","dependency_count":0,"dependent_count":0,"comment_count":0} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e33d343..3fc58df 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,6 +3,7 @@ name: CI on: pull_request: paths: + - 'sandbox/**' - 'src/**' - 'tests/**' - Cargo.toml @@ -11,6 +12,7 @@ on: push: branches: [main] paths: + - 'sandbox/**' - 'src/**' - 'tests/**' - Cargo.toml diff --git a/Cargo.lock b/Cargo.lock index d3aa8b7..7e8d316 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1076,6 +1076,7 @@ dependencies = [ "serde_json", "tempfile", "tokio", + "yaml_serde", ] [[package]] @@ -1110,6 +1111,12 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libyaml-rs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e126dda6f34391ab7b444f9922055facc83c07a910da3eb16f1e4d9c45dc777" + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -1839,6 +1846,12 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "same-file" version = "1.0.6" @@ -2834,6 +2847,19 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +[[package]] +name = "yaml_serde" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33b729a08a9a6be689bbad3e2bf8015926db54b6622cc89c3a5f7dc174b9e918" +dependencies = [ + "indexmap", + "itoa", + "libyaml-rs", + "ryu", + "serde", +] + [[package]] name = "yoke" version = "0.8.4" diff --git a/Cargo.toml b/Cargo.toml index 3b3fd5c..21606db 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ rig-tools = "0.47.2" serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" tokio = { version = "1.54.1", features = ["macros", "rt-multi-thread"] } +yaml_serde = "0.10.7" [dev-dependencies] rig-core = { version = "0.47.2", default-features = false, features = ["test-utils"] } diff --git a/Taskfile.yml b/Taskfile.yml index f995a0e..d9cb20b 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -9,8 +9,8 @@ tasks: - task --list-all silent: true run: - desc: Send a prompt to Strata - cmd: cargo run + desc: Run the default agent + cmd: cargo run -- --agent sandbox/default.yaml {{.CLI_ARGS}} pi: desc: Dumb pi agent cmd: ./scripts/pi.sh diff --git a/sandbox/default.yaml b/sandbox/default.yaml new file mode 100644 index 0000000..4735031 --- /dev/null +++ b/sandbox/default.yaml @@ -0,0 +1,2 @@ +name: default +model: strata/qwen3.8 diff --git a/src/cli.rs b/src/cli.rs index 42585d7..f4c0f6f 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -1,3 +1,5 @@ +use std::path::PathBuf; + use clap::Parser; use killall_agent::models::ModelSelection; @@ -7,100 +9,89 @@ use killall_agent::models::ModelSelection; about = "Run a read-only coding agent in the current directory" )] pub struct Args { + /// YAML agent definition to load + #[arg(long, value_name = "PATH")] + pub agent: PathBuf, + /// Prompt to send to the model #[arg(short, long, default_value = "Say hello in one short sentence.")] pub prompt: String, - /// Model to use, in / form - #[arg( - short, - long, - value_enum, - default_value = "strata/qwen3.8", - value_name = "PROVIDER/MODEL" - )] - pub model: ModelSelection, + /// Override the agent definition's model + #[arg(short, long, value_name = "PROVIDER/MODEL")] + pub model: Option, } #[cfg(test)] mod tests { use super::*; - use clap::{Parser, error::ErrorKind}; + use clap::error::ErrorKind; #[test] - fn defaults_to_sample_prompt_and_strata_qwen() { - let args = Args::try_parse_from(["killall-agent"]).unwrap(); - - assert_eq!(args.prompt, "Say hello in one short sentence."); - assert_eq!(args.model, ModelSelection::StrataQwen38); - assert_eq!(args.model.id(), "qwen3.8"); + fn requires_an_agent_definition() { + let error = Args::try_parse_from(["killall-agent"]).unwrap_err(); + assert_eq!(error.kind(), ErrorKind::MissingRequiredArgument); } #[test] - fn accepts_short_options() { - let args = Args::try_parse_from([ - "killall-agent", - "-p", - "Explain Rust", - "-m", - "strata/qwen3.8", - ]) - .unwrap(); - - assert_eq!(args.prompt, "Explain Rust"); - assert_eq!(args.model, ModelSelection::StrataQwen38); + fn leaves_model_selection_to_the_definition_by_default() { + let args = + Args::try_parse_from(["killall-agent", "--agent", "sandbox/default.yaml"]).unwrap(); + assert_eq!(args.agent, PathBuf::from("sandbox/default.yaml")); + assert_eq!(args.prompt, "Say hello in one short sentence."); + assert_eq!(args.model, None); } #[test] - fn accepts_long_options() { - let args = Args::try_parse_from([ - "killall-agent", - "--prompt", - "Explain Rust", - "--model", - "strata/qwen3.8", - ]) - .unwrap(); - - assert_eq!(args.prompt, "Explain Rust"); - assert_eq!(args.model, ModelSelection::StrataQwen38); + fn accepts_long_and_short_overrides() { + for (prompt, model) in [("--prompt", "--model"), ("-p", "-m")] { + let args = Args::try_parse_from([ + "killall-agent", + "--agent", + "agent.yaml", + prompt, + "Explain Rust", + model, + "custom/org/model", + ]) + .unwrap(); + assert_eq!(args.prompt, "Explain Rust"); + assert_eq!(args.model.unwrap(), "custom/org/model".parse().unwrap()); + } } #[test] - fn rejects_unsupported_model_selections() { - for model in [ - "qwen3.8", - "strata/", - "/qwen3.8", - "other/qwen3.8", - "strata/other", - "strata/qwen3.8/extra", - ] { - let error = Args::try_parse_from(["killall-agent", "--model", model]).unwrap_err(); - assert_eq!(error.kind(), ErrorKind::InvalidValue, "{model}"); + fn rejects_malformed_model_selections() { + for model in ["qwen3.8", "strata/", "/qwen3.8"] { + let error = + Args::try_parse_from(["killall-agent", "--agent", "agent.yaml", "--model", model]) + .unwrap_err(); + assert_eq!(error.kind(), ErrorKind::ValueValidation, "{model}"); } } #[test] fn requires_a_prompt_value_after_the_option() { - let error = Args::try_parse_from(["killall-agent", "--prompt"]).unwrap_err(); + let error = Args::try_parse_from(["killall-agent", "--agent", "agent.yaml", "--prompt"]) + .unwrap_err(); assert_eq!(error.kind(), ErrorKind::InvalidValue); } #[test] fn rejects_positional_prompts() { - let error = Args::try_parse_from(["killall-agent", "hello"]).unwrap_err(); + let error = + Args::try_parse_from(["killall-agent", "--agent", "agent.yaml", "hello"]).unwrap_err(); assert_eq!(error.kind(), ErrorKind::UnknownArgument); } #[test] - fn provides_help() { + fn provides_help_without_an_agent() { let error = Args::try_parse_from(["killall-agent", "--help"]).unwrap_err(); assert_eq!(error.kind(), ErrorKind::DisplayHelp); } #[test] - fn provides_version() { + fn provides_version_without_an_agent() { let error = Args::try_parse_from(["killall-agent", "--version"]).unwrap_err(); assert_eq!(error.kind(), ErrorKind::DisplayVersion); } diff --git a/src/config.rs b/src/config.rs index 9afd15d..25ce14e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,16 +1,11 @@ -use std::{env, fs, path::PathBuf, process::Command}; +use std::{collections::BTreeMap, env, fs, path::PathBuf, process::Command}; use anyhow::{Context, Result, ensure}; use serde::Deserialize; -#[derive(Deserialize)] -struct PiConfig { - providers: Config, -} - #[derive(Deserialize)] pub struct Config { - pub strata: ProviderConfig, + pub providers: BTreeMap, } #[derive(Deserialize)] @@ -19,7 +14,7 @@ pub struct ProviderConfig { pub base_url: String, pub api_key: String, pub models: Vec, - api: String, + pub api: String, } #[derive(Deserialize)] @@ -36,13 +31,7 @@ pub fn load() -> Result { } fn parse_config(contents: &str) -> Result { - let config: PiConfig = - serde_json::from_str(contents).context("Invalid Pi Strata configuration")?; - ensure!( - config.providers.strata.api == "openai-completions", - "Strata must use openai-completions" - ); - Ok(config.providers) + serde_json::from_str(contents).context("Invalid Pi provider configuration") } pub(crate) fn resolve_api_key(value: &str) -> Result { @@ -50,18 +39,18 @@ pub(crate) fn resolve_api_key(value: &str) -> Result { let output = Command::new("sh") .args(["-c", command]) .output() - .context("Could not run Strata API key command")?; + .context("Could not run API key command")?; ensure!( output.status.success(), - "Strata API key command failed ({})", + "API key command failed ({})", output.status ); - String::from_utf8(output.stdout).context("Strata API key is not UTF-8")? + String::from_utf8(output.stdout).context("API key is not UTF-8")? } else { value.to_owned() }; let key = key.trim().to_owned(); - ensure!(!key.is_empty(), "Strata API key is empty"); + ensure!(!key.is_empty(), "API key is empty"); Ok(key) } @@ -81,9 +70,11 @@ mod tests { ) .unwrap(); - assert_eq!(config.strata.base_url, "https://strata.example/v1"); - assert_eq!(config.strata.api_key, "!printf test-key"); - assert_eq!(config.strata.models[0].id, "test-model"); + let provider: ProviderConfig = + serde_json::from_value(config.providers["strata"].clone()).unwrap(); + assert_eq!(provider.base_url, "https://strata.example/v1"); + assert_eq!(provider.api_key, "!printf test-key"); + assert_eq!(provider.models[0].id, "test-model"); } #[test] @@ -97,9 +88,6 @@ mod tests { #[test] fn rejects_failed_credential_command() { let error = resolve_api_key("!exit 7").unwrap_err(); - assert_eq!( - error.to_string(), - "Strata API key command failed (exit status: 7)" - ); + assert_eq!(error.to_string(), "API key command failed (exit status: 7)"); } } diff --git a/src/definition.rs b/src/definition.rs new file mode 100644 index 0000000..1a3b735 --- /dev/null +++ b/src/definition.rs @@ -0,0 +1,132 @@ +use std::{ + fs, + path::{Path, PathBuf}, +}; + +use anyhow::{Context, Result, ensure}; +use serde::Deserialize; + +use crate::models::ModelSelection; + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Definition { + pub name: String, + pub model: ModelSelection, + #[serde(default)] + pub tools: Vec, + #[serde(default)] + pub skills: Vec, + pub agentfile: Option, +} + +pub fn load(path: &Path) -> Result { + let contents = fs::read_to_string(path) + .with_context(|| format!("Could not read agent definition {}", path.display()))?; + let mut definition = + parse(&contents).with_context(|| format!("Invalid agent definition {}", path.display()))?; + definition.agentfile = definition + .agentfile + .map(|file| path.parent().unwrap_or_else(|| Path::new(".")).join(file)); + Ok(definition) +} + +fn parse(contents: &str) -> Result { + let definition: Definition = yaml_serde::from_str(contents)?; + ensure!( + !definition.name.trim().is_empty(), + "Agent name must not be empty" + ); + Ok(definition) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_the_example_without_resolving_resources() { + let definition = parse(include_str!("../sandbox/example-def.yaml")).unwrap(); + + assert_eq!(definition.name, "lenny"); + assert_eq!(definition.model.provider(), "openai"); + assert_eq!(definition.model.id(), "sol"); + assert_eq!(definition.tools, ["ALL", "Read", "List", "Etc"]); + assert_eq!( + definition.skills, + ["github://owner/repo", "file://path/to/dir"] + ); + assert_eq!(definition.agentfile, Some("path/to/agents.md".into())); + } + + #[test] + fn defaults_optional_resources_to_empty() { + let definition = parse("name: minimal\nmodel: strata/qwen3.8\n").unwrap(); + + assert!(definition.tools.is_empty()); + assert!(definition.skills.is_empty()); + assert!(definition.agentfile.is_none()); + } + + #[test] + fn rejects_missing_required_fields() { + for contents in ["name: lenny", "model: strata/qwen3.8"] { + let error = parse(contents).unwrap_err(); + assert!(error.downcast_ref::().is_some()); + } + } + + #[test] + fn parses_the_default_definition() { + let definition = parse(include_str!("../sandbox/default.yaml")).unwrap(); + assert_eq!(definition.model.provider(), "strata"); + assert_eq!(definition.model.id(), "qwen3.8"); + } + + #[test] + fn rejects_malformed_models() { + let error = parse("name: test\nmodel: missing-separator").unwrap_err(); + assert!(error.downcast_ref::().is_some()); + } + + #[test] + fn rejects_an_empty_name() { + assert_eq!( + parse("name: ' '\nmodel: strata/qwen3.8") + .unwrap_err() + .to_string(), + "Agent name must not be empty" + ); + } + + #[test] + fn rejects_unknown_fields() { + let error = parse("name: lenny\nmodel: strata/qwen3.8\nmodle: typo").unwrap_err(); + assert!(error.downcast_ref::().is_some()); + } + + #[test] + fn resolves_agentfile_relative_to_the_definition() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("agent.yaml"); + std::fs::write(&path, include_str!("../sandbox/example-def.yaml")).unwrap(); + + let definition = load(&path).unwrap(); + + assert_eq!( + definition.agentfile, + Some(directory.path().join("path/to/agents.md")) + ); + } + + #[test] + fn reports_missing_definition_as_an_io_error() { + let directory = tempfile::tempdir().unwrap(); + let error = load(&directory.path().join("missing.yaml")).unwrap_err(); + + assert_eq!( + error.downcast_ref::().unwrap().kind(), + std::io::ErrorKind::NotFound + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index 83e2912..12b74f8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ pub mod config; +pub mod definition; pub mod models; pub mod tools; diff --git a/src/main.rs b/src/main.rs index 9e6ecc1..a524f0b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,16 +2,17 @@ mod cli; use anyhow::{Context, Result}; use clap::Parser; -use killall_agent::{config, models, tools}; +use killall_agent::{config, definition, models, tools}; use rig_agent::AgentBuilder; #[tokio::main] async fn main() -> Result<()> { let args = cli::Args::parse(); + let definition = definition::load(&args.agent)?; let workspace = std::env::current_dir().context("Cannot determine workspace directory")?; let tools = tools::load(&workspace)?; let config = config::load()?; - let model = models::load(&config, args.model)?; + let model = models::load(&config, args.model.unwrap_or(definition.model))?; let agent = AgentBuilder::new(model) .tool_server_handle(tools) .default_max_turns(10) @@ -20,7 +21,7 @@ async fn main() -> Result<()> { let response = agent .prompt(args.prompt) .await - .context("Strata agent run failed")?; + .context("Agent run failed")?; println!("{response}"); Ok(()) diff --git a/src/models.rs b/src/models.rs index 8e77053..ac6f9cd 100644 --- a/src/models.rs +++ b/src/models.rs @@ -1,81 +1,202 @@ -use anyhow::{Context, Result}; -use clap::ValueEnum; +use std::str::FromStr; + +use anyhow::{Context, Result, ensure}; use rig_core::{DynModel, operation::Completion, providers::openai::OpenAIConfig}; +use serde::Deserialize; -use crate::config::{self, Config}; +use crate::config::{self, Config, ProviderConfig}; -#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)] -pub enum ModelSelection { - #[value(name = "strata/qwen3.8")] - StrataQwen38, +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] +#[serde(try_from = "String")] +pub struct ModelSelection { + provider: String, + model: String, } impl ModelSelection { - pub fn id(self) -> &'static str { - match self { - Self::StrataQwen38 => "qwen3.8", - } + pub fn provider(&self) -> &str { + &self.provider + } + + pub fn id(&self) -> &str { + &self.model } } -pub fn load(config: &Config, selection: ModelSelection) -> Result> { - match selection { - ModelSelection::StrataQwen38 => { - let strata = &config.strata; - let model = strata - .models - .iter() - .find(|model| model.id == selection.id()) - .with_context(|| { - format!("Model {} is not configured for Strata", selection.id()) - })?; - let client = OpenAIConfig::new(config::resolve_api_key(&strata.api_key)?) - .with_base_url(&strata.base_url) - .client(); - Ok(client.chat(&model.id).into()) - } +impl FromStr for ModelSelection { + type Err = anyhow::Error; + + fn from_str(value: &str) -> Result { + let (provider, model) = value + .split_once('/') + .context("Model must be in / form")?; + ensure!( + !provider.trim().is_empty() && !model.trim().is_empty(), + "Model must include both provider and model" + ); + Ok(Self { + provider: provider.to_owned(), + model: model.to_owned(), + }) + } +} + +impl TryFrom for ModelSelection { + type Error = anyhow::Error; + + fn try_from(value: String) -> Result { + value.parse() } } +pub fn load(config: &Config, selection: ModelSelection) -> Result> { + let provider = config + .providers + .get(selection.provider()) + .with_context(|| format!("Provider {} is not configured", selection.provider()))?; + let provider: ProviderConfig = serde_json::from_value(provider.clone()).with_context(|| { + format!( + "Invalid configuration for provider {}", + selection.provider() + ) + })?; + ensure!( + provider.api == "openai-completions", + "Provider {} must use openai-completions", + selection.provider() + ); + let model = provider + .models + .iter() + .find(|model| model.id == selection.id()) + .with_context(|| { + format!( + "Model {} is not configured for provider {}", + selection.id(), + selection.provider() + ) + })?; + let client = OpenAIConfig::new(config::resolve_api_key(&provider.api_key)?) + .with_base_url(&provider.base_url) + .client(); + Ok(client.chat(&model.id).into()) +} + #[cfg(test)] mod tests { use super::*; - fn config(models: &str, api_key: &str) -> Config { + fn config() -> Config { serde_json::from_value(serde_json::json!({ - "strata": { - "baseUrl": "https://strata.example/v1", - "api": "openai-completions", - "apiKey": api_key, - "models": [{"id": models}] + "providers": { + "custom": { + "baseUrl": "https://strata.example/v1", + "api": "openai-completions", + "apiKey": "test-key", + "models": [{"id": "org/model"}] + } } })) .unwrap() } #[test] - fn builds_the_selected_model_without_contacting_the_provider() { - let config = config("qwen3.8", "test-key"); - assert!(load(&config, ModelSelection::StrataQwen38).is_ok()); + fn splits_selection_at_the_first_slash() { + let selection: ModelSelection = "custom/org/model".parse().unwrap(); + assert_eq!(selection.provider(), "custom"); + assert_eq!(selection.id(), "org/model"); } #[test] - fn rejects_a_model_missing_from_configuration() { - let config = config("other-model", "test-key"); - let error = load(&config, ModelSelection::StrataQwen38).err().unwrap(); + fn rejects_missing_provider_or_model() { + for value in ["qwen3.8", "strata/", "/qwen3.8", " / "] { + assert!(value.parse::().is_err(), "{value}"); + } + } + + #[test] + fn builds_a_model_from_the_provider_key_without_contacting_it() { + assert!(load(&config(), "custom/org/model".parse().unwrap()).is_ok()); + } + + #[test] + fn ignores_incomplete_unselected_providers() { + let config: Config = serde_json::from_value(serde_json::json!({ + "providers": { + "custom": { + "baseUrl": "https://strata.example/v1", + "api": "openai-completions", + "apiKey": "test-key", + "models": [{"id": "org/model"}] + }, + "anthropic": {"baseUrl": "https://proxy.example"} + } + })) + .unwrap(); + + assert!(load(&config, "custom/org/model".parse().unwrap()).is_ok()); + } + + #[test] + fn rejects_an_incomplete_selected_provider_with_context() { + let mut config = config(); + config.providers.insert( + "partial".into(), + serde_json::json!({ + "baseUrl": "https://proxy.example" + }), + ); + + let error = load(&config, "partial/model".parse().unwrap()) + .err() + .unwrap(); + assert_eq!( error.to_string(), - "Model qwen3.8 is not configured for Strata" + "Invalid configuration for provider partial" ); + assert!(error.downcast_ref::().is_some()); } #[test] - fn resolves_credentials_when_building_the_model() { - let config = config("qwen3.8", "!exit 7"); - let error = load(&config, ModelSelection::StrataQwen38).err().unwrap(); + fn rejects_a_missing_provider() { + let error = load(&config(), "missing/model".parse().unwrap()) + .err() + .unwrap(); + assert_eq!(error.to_string(), "Provider missing is not configured"); + } + + #[test] + fn rejects_a_missing_model() { + let error = load(&config(), "custom/missing".parse().unwrap()) + .err() + .unwrap(); assert_eq!( error.to_string(), - "Strata API key command failed (exit status: 7)" + "Model missing is not configured for provider custom" ); } + + #[test] + fn rejects_an_unsupported_provider_api() { + let mut config = config(); + config.providers.get_mut("custom").unwrap()["api"] = "other-api".into(); + let error = load(&config, "custom/org/model".parse().unwrap()) + .err() + .unwrap(); + assert_eq!( + error.to_string(), + "Provider custom must use openai-completions" + ); + } + + #[test] + fn resolves_credentials_when_building_the_model() { + let mut config = config(); + config.providers.get_mut("custom").unwrap()["apiKey"] = "!exit 7".into(); + let error = load(&config, "custom/org/model".parse().unwrap()) + .err() + .unwrap(); + assert_eq!(error.to_string(), "API key command failed (exit status: 7)"); + } } diff --git a/tests/agent_cli.rs b/tests/agent_cli.rs new file mode 100644 index 0000000..3b80116 --- /dev/null +++ b/tests/agent_cli.rs @@ -0,0 +1,62 @@ +use std::process::{Command, Output}; + +fn run_with_definition(model_override: Option<&str>) -> Output { + let home = tempfile::tempdir().unwrap(); + let config_dir = home.path().join(".pi/agent"); + std::fs::create_dir_all(&config_dir).unwrap(); + std::fs::write(config_dir.join("models.json"), r#"{"providers":{}}"#).unwrap(); + let definition = home.path().join("agent.yaml"); + std::fs::write(&definition, "name: test\nmodel: from-yaml/model\n").unwrap(); + + let mut command = Command::new(env!("CARGO_BIN_EXE_killall-agent")); + command + .env("HOME", home.path()) + .arg("--agent") + .arg(definition); + if let Some(model) = model_override { + command.args(["--model", model]); + } + command.output().unwrap() +} + +#[test] +fn resolves_the_model_from_the_yaml_definition() { + let output = run_with_definition(None); + + assert!(!output.status.success()); + assert!( + String::from_utf8(output.stderr) + .unwrap() + .contains("Provider from-yaml is not configured") + ); +} + +#[test] +fn explicit_model_overrides_the_yaml_model() { + let output = run_with_definition(Some("from-cli/model")); + + assert!(!output.status.success()); + assert!( + String::from_utf8(output.stderr) + .unwrap() + .contains("Provider from-cli is not configured") + ); +} + +#[test] +fn reports_a_missing_definition_before_loading_provider_configuration() { + let home = tempfile::tempdir().unwrap(); + let missing = home.path().join("missing.yaml"); + let output = Command::new(env!("CARGO_BIN_EXE_killall-agent")) + .env("HOME", home.path()) + .arg("--agent") + .arg(&missing) + .output() + .unwrap(); + + assert!(!output.status.success()); + assert!(String::from_utf8(output.stderr).unwrap().contains(&format!( + "Could not read agent definition {}", + missing.display() + ))); +} diff --git a/tests/workflow.rs b/tests/workflow.rs new file mode 100644 index 0000000..3064ec0 --- /dev/null +++ b/tests/workflow.rs @@ -0,0 +1,13 @@ +#[test] +fn sandbox_definition_changes_trigger_ci_for_pull_requests_and_pushes() { + let workflow: yaml_serde::Value = + yaml_serde::from_str(include_str!("../.github/workflows/ci.yml")).unwrap(); + + for event in ["pull_request", "push"] { + let paths = workflow["on"][event]["paths"].as_sequence().unwrap(); + assert!( + paths.iter().any(|path| path.as_str() == Some("sandbox/**")), + "{event} must run CI for sandbox definitions" + ); + } +}