Compare commits
7
Commits
feature/m4
...
feature/m6
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ba2f7af74 | ||
|
|
08b3cd8fb7 | ||
|
|
5fd1698d47 | ||
|
|
dbc676332a | ||
|
|
d6af65f494 | ||
|
|
fe6d00ce6d | ||
|
|
f71a347061 |
Generated
+175
-2
@@ -35,6 +35,15 @@ version = "0.2.21"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
|
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "android_system_properties"
|
||||||
|
version = "0.1.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "anyhow"
|
name = "anyhow"
|
||||||
version = "1.0.103"
|
version = "1.0.103"
|
||||||
@@ -92,6 +101,18 @@ version = "1.1.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "autocfg"
|
||||||
|
version = "1.5.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "base64"
|
||||||
|
version = "0.21.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "base64"
|
name = "base64"
|
||||||
version = "0.22.1"
|
version = "0.22.1"
|
||||||
@@ -175,6 +196,20 @@ dependencies = [
|
|||||||
"rand_core 0.10.1",
|
"rand_core 0.10.1",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "chrono"
|
||||||
|
version = "0.4.45"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
|
||||||
|
dependencies = [
|
||||||
|
"iana-time-zone",
|
||||||
|
"js-sys",
|
||||||
|
"num-traits",
|
||||||
|
"serde",
|
||||||
|
"wasm-bindgen",
|
||||||
|
"windows-link",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "compact_str"
|
name = "compact_str"
|
||||||
version = "0.8.2"
|
version = "0.8.2"
|
||||||
@@ -217,6 +252,12 @@ dependencies = [
|
|||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "core-foundation-sys"
|
||||||
|
version = "0.8.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cpufeatures"
|
name = "cpufeatures"
|
||||||
version = "0.3.0"
|
version = "0.3.0"
|
||||||
@@ -711,14 +752,28 @@ dependencies = [
|
|||||||
name = "harness-lsp"
|
name = "harness-lsp"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"async-trait",
|
||||||
"harness-core",
|
"harness-core",
|
||||||
|
"serde_json",
|
||||||
|
"tempfile",
|
||||||
|
"tokio",
|
||||||
|
"tracing",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "harness-mcp"
|
name = "harness-mcp"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"async-trait",
|
||||||
"harness-core",
|
"harness-core",
|
||||||
|
"rmcp",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"tempfile",
|
||||||
|
"thiserror 2.0.18",
|
||||||
|
"tokio",
|
||||||
|
"tokio-util",
|
||||||
|
"tracing",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -909,7 +964,7 @@ version = "0.1.20"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
|
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64",
|
"base64 0.22.1",
|
||||||
"bytes",
|
"bytes",
|
||||||
"futures-channel",
|
"futures-channel",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
@@ -926,6 +981,30 @@ dependencies = [
|
|||||||
"tracing",
|
"tracing",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "iana-time-zone"
|
||||||
|
version = "0.1.65"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
|
||||||
|
dependencies = [
|
||||||
|
"android_system_properties",
|
||||||
|
"core-foundation-sys",
|
||||||
|
"iana-time-zone-haiku",
|
||||||
|
"js-sys",
|
||||||
|
"log",
|
||||||
|
"wasm-bindgen",
|
||||||
|
"windows-core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "iana-time-zone-haiku"
|
||||||
|
version = "0.1.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "icu_collections"
|
name = "icu_collections"
|
||||||
version = "2.2.0"
|
version = "2.2.0"
|
||||||
@@ -1293,6 +1372,15 @@ version = "0.2.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
|
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "num-traits"
|
||||||
|
version = "0.2.19"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||||
|
dependencies = [
|
||||||
|
"autocfg",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "once_cell"
|
name = "once_cell"
|
||||||
version = "1.21.4"
|
version = "1.21.4"
|
||||||
@@ -1600,7 +1688,7 @@ version = "0.12.28"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
|
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64",
|
"base64 0.22.1",
|
||||||
"bytes",
|
"bytes",
|
||||||
"futures-core",
|
"futures-core",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
@@ -1649,6 +1737,38 @@ dependencies = [
|
|||||||
"windows-sys 0.52.0",
|
"windows-sys 0.52.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rmcp"
|
||||||
|
version = "0.1.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "33a0110d28bd076f39e14bfd5b0340216dd18effeb5d02b43215944cc3e5c751"
|
||||||
|
dependencies = [
|
||||||
|
"base64 0.21.7",
|
||||||
|
"chrono",
|
||||||
|
"futures",
|
||||||
|
"paste",
|
||||||
|
"pin-project-lite",
|
||||||
|
"rmcp-macros",
|
||||||
|
"schemars",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"thiserror 2.0.18",
|
||||||
|
"tokio",
|
||||||
|
"tokio-util",
|
||||||
|
"tracing",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rmcp-macros"
|
||||||
|
version = "0.1.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a6e2b2fd7497540489fa2db285edd43b7ed14c49157157438664278da6e42a7a"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rusqlite"
|
name = "rusqlite"
|
||||||
version = "0.32.1"
|
version = "0.32.1"
|
||||||
@@ -2600,12 +2720,65 @@ version = "0.4.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-core"
|
||||||
|
version = "0.62.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
|
||||||
|
dependencies = [
|
||||||
|
"windows-implement",
|
||||||
|
"windows-interface",
|
||||||
|
"windows-link",
|
||||||
|
"windows-result",
|
||||||
|
"windows-strings",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-implement"
|
||||||
|
version = "0.60.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-interface"
|
||||||
|
version = "0.59.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows-link"
|
name = "windows-link"
|
||||||
version = "0.2.1"
|
version = "0.2.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-result"
|
||||||
|
version = "0.4.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
|
||||||
|
dependencies = [
|
||||||
|
"windows-link",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-strings"
|
||||||
|
version = "0.5.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
|
||||||
|
dependencies = [
|
||||||
|
"windows-link",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows-sys"
|
name = "windows-sys"
|
||||||
version = "0.48.0"
|
version = "0.48.0"
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ harness-mcp = { workspace = true }
|
|||||||
harness-lsp = { workspace = true }
|
harness-lsp = { workspace = true }
|
||||||
tokio = { workspace = true }
|
tokio = { workspace = true }
|
||||||
tokio-util = { workspace = true }
|
tokio-util = { workspace = true }
|
||||||
|
futures = { workspace = true }
|
||||||
|
serde_json = { workspace = true }
|
||||||
async-trait = { workspace = true }
|
async-trait = { workspace = true }
|
||||||
dirs = { workspace = true }
|
dirs = { workspace = true }
|
||||||
thiserror = { workspace = true }
|
thiserror = { workspace = true }
|
||||||
|
|||||||
+608
-61
@@ -14,12 +14,17 @@ use async_trait::async_trait;
|
|||||||
use harness_core::agent::{AgentDef, AgentRegistry};
|
use harness_core::agent::{AgentDef, AgentRegistry};
|
||||||
use harness_core::config::{self, Config, ConfigError};
|
use harness_core::config::{self, Config, ConfigError};
|
||||||
use harness_core::engine::jobs::{JobBoard, JobState, LaunchSpec};
|
use harness_core::engine::jobs::{JobBoard, JobState, LaunchSpec};
|
||||||
use harness_core::engine::{run_session, RunConfig, StepContext};
|
use harness_core::engine::{run_session, Compactor, RunConfig, StepContext};
|
||||||
use harness_core::event::{AppEvent, EventBus, RunOutcome};
|
use harness_core::event::{AppEvent, EventBus, RunOutcome};
|
||||||
|
use harness_core::llm::{
|
||||||
|
Initiator, LlmEvent, LlmRequest, Provider, ProviderError, Role as WireRole, WireContent,
|
||||||
|
WireMessage,
|
||||||
|
};
|
||||||
|
use harness_core::lsp::DiagnosticsSource;
|
||||||
use harness_core::permission::{PermissionReply, PermissionService, Rule, Ruleset};
|
use harness_core::permission::{PermissionReply, PermissionService, Rule, Ruleset};
|
||||||
use harness_core::store::{Store, StoreError};
|
use harness_core::store::{Store, StoreError};
|
||||||
use harness_core::tool::{
|
use harness_core::tool::{
|
||||||
ContextReporter, SpawnError, SpawnOutcome, SpawnRequest, SubagentSpawner, ToolRegistry,
|
ContextReporter, SpawnError, SpawnOutcome, SpawnRequest, SubagentSpawner, Tool, ToolRegistry,
|
||||||
};
|
};
|
||||||
use harness_core::types::{
|
use harness_core::types::{
|
||||||
Message, MessageId, ModelRef, Part, PartBody, PartId, Session, SessionId,
|
Message, MessageId, ModelRef, Part, PartBody, PartId, Session, SessionId,
|
||||||
@@ -75,55 +80,8 @@ fn db_path(cwd: &Path) -> PathBuf {
|
|||||||
base.join(format!("{}.sqlite", slug))
|
base.join(format!("{}.sqlite", slug))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Non-blocking, multi-turn engine API used by the TUI.
|
/// Builds the provider registry from config: every provider with an API key is registered.
|
||||||
#[derive(Clone)]
|
fn providers_from_config(config: &Config) -> ProviderRegistry {
|
||||||
pub struct EngineHandle {
|
|
||||||
inner: Arc<EngineInner>,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct EngineInner {
|
|
||||||
config: Config,
|
|
||||||
store: Store,
|
|
||||||
bus: EventBus,
|
|
||||||
permissions: Arc<PermissionService>,
|
|
||||||
tools: ToolRegistry,
|
|
||||||
providers: ProviderRegistry,
|
|
||||||
catalog: ModelCatalog,
|
|
||||||
agents: AgentRegistry,
|
|
||||||
cwd: PathBuf,
|
|
||||||
data_dir: PathBuf,
|
|
||||||
runs: Mutex<HashMap<SessionId, RunHandle>>,
|
|
||||||
/// One job board per session (scoped to that session as a parent). Lazily created and
|
|
||||||
/// shared between a session's run loop (board injection) and the spawner (registration).
|
|
||||||
boards: Mutex<HashMap<SessionId, Arc<JobBoard>>>,
|
|
||||||
/// Self-reference so the spawner can hand an `Arc<EngineInner>` to child contexts (for
|
|
||||||
/// nested delegation) and to detached background tasks. Set once in `new`.
|
|
||||||
me: OnceLock<Weak<EngineInner>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct RunHandle {
|
|
||||||
cancel: CancellationToken,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EngineHandle {
|
|
||||||
/// Persistent SQLite-backed store. Used by the TUI and the default headless `App`.
|
|
||||||
pub fn init(cwd: PathBuf) -> Result<Self, AppError> {
|
|
||||||
let path = db_path(&cwd);
|
|
||||||
let store = Store::open(&path)?;
|
|
||||||
let handle = Self::new(cwd, store)?;
|
|
||||||
handle.spawn_catalog_refresh();
|
|
||||||
Ok(handle)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// In-memory store — useful for tests and ephemeral sessions.
|
|
||||||
pub fn init_in_memory(cwd: PathBuf) -> Result<Self, AppError> {
|
|
||||||
let store = Store::open_in_memory()?;
|
|
||||||
Self::new(cwd, store)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn new(cwd: PathBuf, store: Store) -> Result<Self, AppError> {
|
|
||||||
let config = config::load(&cwd)?;
|
|
||||||
|
|
||||||
let mut providers = ProviderRegistry::new();
|
let mut providers = ProviderRegistry::new();
|
||||||
if let Some(key) = config
|
if let Some(key) = config
|
||||||
.providers
|
.providers
|
||||||
@@ -147,8 +105,8 @@ impl EngineHandle {
|
|||||||
};
|
};
|
||||||
providers.register(Arc::new(provider));
|
providers.register(Arc::new(provider));
|
||||||
}
|
}
|
||||||
// OpenCode Zen: OpenAI-compatible chat gateway under its own `opencode` provider id,
|
// OpenCode Zen: OpenAI-compatible chat gateway under its own `opencode` provider id, so it
|
||||||
// so it coexists with a real `openai` provider. `base_url` defaults to Zen's endpoint.
|
// coexists with a real `openai` provider. `base_url` defaults to Zen's endpoint.
|
||||||
if let Some(key) = config
|
if let Some(key) = config
|
||||||
.providers
|
.providers
|
||||||
.get("opencode")
|
.get("opencode")
|
||||||
@@ -160,16 +118,109 @@ impl EngineHandle {
|
|||||||
.and_then(|p| p.base_url.clone());
|
.and_then(|p| p.base_url.clone());
|
||||||
providers.register(Arc::new(OpenAiProvider::opencode(key, base_url)));
|
providers.register(Arc::new(OpenAiProvider::opencode(key, base_url)));
|
||||||
}
|
}
|
||||||
|
providers
|
||||||
Self::build(cwd, store, config, providers)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Shared construction over an explicit provider set — the seam tests use to inject a mock.
|
/// Connects every enabled MCP server declared in config and returns their tool adapters. A
|
||||||
|
/// server that fails to start is logged and skipped inside `harness_mcp` — never fatal.
|
||||||
|
async fn connect_mcp_tools(config: &Config) -> Vec<Arc<dyn Tool>> {
|
||||||
|
let servers: HashMap<String, harness_mcp::ServerConfig> = config
|
||||||
|
.mcp
|
||||||
|
.iter()
|
||||||
|
.filter(|(_, c)| c.enabled.unwrap_or(true) && !c.command.is_empty())
|
||||||
|
.map(|(name, c)| {
|
||||||
|
(
|
||||||
|
name.clone(),
|
||||||
|
harness_mcp::ServerConfig {
|
||||||
|
command: c.command.clone(),
|
||||||
|
args: c.args.clone(),
|
||||||
|
env: c.env.clone(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if servers.is_empty() {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
harness_mcp::connect_all(servers).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Non-blocking, multi-turn engine API used by the TUI.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct EngineHandle {
|
||||||
|
inner: Arc<EngineInner>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct EngineInner {
|
||||||
|
config: Config,
|
||||||
|
store: Store,
|
||||||
|
bus: EventBus,
|
||||||
|
permissions: Arc<PermissionService>,
|
||||||
|
tools: ToolRegistry,
|
||||||
|
providers: ProviderRegistry,
|
||||||
|
catalog: ModelCatalog,
|
||||||
|
agents: AgentRegistry,
|
||||||
|
/// LSP diagnostics pool (edit/write surface errors). Shared across sessions; servers spawn
|
||||||
|
/// lazily on first touch.
|
||||||
|
diagnostics: Option<Arc<dyn DiagnosticsSource>>,
|
||||||
|
/// Pre-rendered "## Skills" system block (name + description), injected into every run.
|
||||||
|
/// `None` when no skills are configured.
|
||||||
|
skills_prompt: Option<String>,
|
||||||
|
/// Slash commands by name, expanded into the user message by the TUI input layer.
|
||||||
|
commands: HashMap<String, config::CommandDef>,
|
||||||
|
/// Auto-compaction backend (small model). `None` when no `small_model` is configured or
|
||||||
|
/// its provider isn't registered — compaction is then disabled.
|
||||||
|
compactor: Option<Arc<dyn Compactor>>,
|
||||||
|
/// Resolved `small_model` (provider + model id) for session-title generation. `None`
|
||||||
|
/// disables titling (the session keeps its empty title / prompt fallback).
|
||||||
|
small_model: Option<(Arc<dyn Provider>, String)>,
|
||||||
|
cwd: PathBuf,
|
||||||
|
data_dir: PathBuf,
|
||||||
|
runs: Mutex<HashMap<SessionId, RunHandle>>,
|
||||||
|
/// One job board per session (scoped to that session as a parent). Lazily created and
|
||||||
|
/// shared between a session's run loop (board injection) and the spawner (registration).
|
||||||
|
boards: Mutex<HashMap<SessionId, Arc<JobBoard>>>,
|
||||||
|
/// Self-reference so the spawner can hand an `Arc<EngineInner>` to child contexts (for
|
||||||
|
/// nested delegation) and to detached background tasks. Set once in `new`.
|
||||||
|
me: OnceLock<Weak<EngineInner>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct RunHandle {
|
||||||
|
cancel: CancellationToken,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EngineHandle {
|
||||||
|
/// Persistent SQLite-backed store. Used by the TUI and the default headless `App`.
|
||||||
|
/// Async because it connects any configured MCP servers (spawn + initialize + list tools)
|
||||||
|
/// before the first turn so their tools are advertised to the model.
|
||||||
|
pub async fn init(cwd: PathBuf) -> Result<Self, AppError> {
|
||||||
|
let path = db_path(&cwd);
|
||||||
|
let store = Store::open(&path)?;
|
||||||
|
let config = config::load(&cwd)?;
|
||||||
|
let providers = providers_from_config(&config);
|
||||||
|
let mcp_tools = connect_mcp_tools(&config).await;
|
||||||
|
let handle = Self::build(cwd, store, config, providers, mcp_tools)?;
|
||||||
|
handle.spawn_catalog_refresh();
|
||||||
|
Ok(handle)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// In-memory store — useful for tests and ephemeral sessions. Skips MCP (no external
|
||||||
|
/// servers in tests) and stays synchronous.
|
||||||
|
pub fn init_in_memory(cwd: PathBuf) -> Result<Self, AppError> {
|
||||||
|
let store = Store::open_in_memory()?;
|
||||||
|
let config = config::load(&cwd)?;
|
||||||
|
let providers = providers_from_config(&config);
|
||||||
|
Self::build(cwd, store, config, providers, Vec::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shared construction over an explicit provider set and pre-connected extra tools (MCP) —
|
||||||
|
/// the seam the tests use to inject a mock provider.
|
||||||
fn build(
|
fn build(
|
||||||
cwd: PathBuf,
|
cwd: PathBuf,
|
||||||
store: Store,
|
store: Store,
|
||||||
config: Config,
|
config: Config,
|
||||||
providers: ProviderRegistry,
|
providers: ProviderRegistry,
|
||||||
|
extra_tools: Vec<Arc<dyn Tool>>,
|
||||||
) -> Result<Self, AppError> {
|
) -> Result<Self, AppError> {
|
||||||
let bus = EventBus::new();
|
let bus = EventBus::new();
|
||||||
let permissions = Arc::new(PermissionService::new(bus.clone()));
|
let permissions = Arc::new(PermissionService::new(bus.clone()));
|
||||||
@@ -177,6 +228,24 @@ impl EngineHandle {
|
|||||||
let mut tools = ToolRegistry::new();
|
let mut tools = ToolRegistry::new();
|
||||||
harness_tools::register_builtins(&mut tools);
|
harness_tools::register_builtins(&mut tools);
|
||||||
harness_tools::register_task_tool(&mut tools);
|
harness_tools::register_task_tool(&mut tools);
|
||||||
|
for tool in extra_tools {
|
||||||
|
tools.register(tool);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skills: layered global + project markdown, advertised in the system prompt and pulled
|
||||||
|
// on demand by the `skill` tool (only registered when at least one skill exists).
|
||||||
|
let global_skill_dir = dirs::config_dir().map(|d| d.join("ai-harness").join("skill"));
|
||||||
|
let project_skill_dir = cwd.join(".harness").join("skill");
|
||||||
|
let skills = config::load_skills(global_skill_dir.as_deref(), Some(&project_skill_dir));
|
||||||
|
harness_tools::register_skill_tool(&mut tools, &skills);
|
||||||
|
let skills_prompt = config::skills_prompt(&skills);
|
||||||
|
|
||||||
|
// Slash commands: layered global + project markdown, expanded into the user message by
|
||||||
|
// the TUI input layer (project wins by name).
|
||||||
|
let global_command_dir = dirs::config_dir().map(|d| d.join("ai-harness").join("command"));
|
||||||
|
let project_command_dir = cwd.join(".harness").join("command");
|
||||||
|
let commands =
|
||||||
|
config::load_commands(global_command_dir.as_deref(), Some(&project_command_dir));
|
||||||
|
|
||||||
// Layered agent registry: bundled markdown → global dir → project dir → config patches.
|
// Layered agent registry: bundled markdown → global dir → project dir → config patches.
|
||||||
let global_agent_dir = dirs::config_dir().map(|d| d.join("ai-harness").join("agent"));
|
let global_agent_dir = dirs::config_dir().map(|d| d.join("ai-harness").join("agent"));
|
||||||
@@ -196,6 +265,37 @@ impl EngineHandle {
|
|||||||
// `init` warms the cache in the background for the next launch.
|
// `init` warms the cache in the background for the next launch.
|
||||||
let catalog = ModelCatalog::load_cached_or_baked(&ModelCatalog::default_cache_path());
|
let catalog = ModelCatalog::load_cached_or_baked(&ModelCatalog::default_cache_path());
|
||||||
|
|
||||||
|
// The configured `small_model` (provider/model), resolved to a provider if registered.
|
||||||
|
// Powers both auto-compaction and session-title generation; `None` disables both.
|
||||||
|
let small_model: Option<(Arc<dyn Provider>, String)> = config
|
||||||
|
.small_model
|
||||||
|
.as_deref()
|
||||||
|
.and_then(|m| m.split_once('/'))
|
||||||
|
.and_then(|(provider_id, model_id)| {
|
||||||
|
providers
|
||||||
|
.get(provider_id)
|
||||||
|
.map(|provider| (provider, model_id.to_string()))
|
||||||
|
});
|
||||||
|
let compactor: Option<Arc<dyn Compactor>> =
|
||||||
|
small_model.clone().map(|(provider, model_id)| {
|
||||||
|
Arc::new(SmallModelCompactor::new(provider, model_id)) as Arc<dyn Compactor>
|
||||||
|
});
|
||||||
|
|
||||||
|
// LSP pool: built-ins present on PATH, plus any config-declared servers.
|
||||||
|
let lsp_servers: Vec<harness_lsp::ServerConfig> = config
|
||||||
|
.lsp
|
||||||
|
.iter()
|
||||||
|
.map(|(name, c)| harness_lsp::ServerConfig {
|
||||||
|
name: name.clone(),
|
||||||
|
command: c.command.clone(),
|
||||||
|
args: c.args.clone(),
|
||||||
|
extensions: c.extensions.clone(),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let diagnostics: Option<Arc<dyn DiagnosticsSource>> = Some(Arc::new(
|
||||||
|
harness_lsp::LspPool::new(cwd.clone(), lsp_servers),
|
||||||
|
));
|
||||||
|
|
||||||
let inner = Arc::new(EngineInner {
|
let inner = Arc::new(EngineInner {
|
||||||
config,
|
config,
|
||||||
store,
|
store,
|
||||||
@@ -205,6 +305,11 @@ impl EngineHandle {
|
|||||||
providers,
|
providers,
|
||||||
catalog,
|
catalog,
|
||||||
agents,
|
agents,
|
||||||
|
diagnostics,
|
||||||
|
skills_prompt,
|
||||||
|
commands,
|
||||||
|
compactor,
|
||||||
|
small_model,
|
||||||
cwd,
|
cwd,
|
||||||
data_dir,
|
data_dir,
|
||||||
runs: Mutex::new(HashMap::new()),
|
runs: Mutex::new(HashMap::new()),
|
||||||
@@ -236,6 +341,11 @@ impl EngineHandle {
|
|||||||
self.inner.config.clone()
|
self.inner.config.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A loaded slash command by name (without the leading `/`), if defined.
|
||||||
|
pub fn command(&self, name: &str) -> Option<config::CommandDef> {
|
||||||
|
self.inner.commands.get(name).cloned()
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn new_session(&self, agent: &str, model_ref: &str) -> Result<SessionId, AppError> {
|
pub async fn new_session(&self, agent: &str, model_ref: &str) -> Result<SessionId, AppError> {
|
||||||
let (provider_id, model_id) = model_ref
|
let (provider_id, model_id) = model_ref
|
||||||
.split_once('/')
|
.split_once('/')
|
||||||
@@ -254,6 +364,18 @@ impl EngineHandle {
|
|||||||
session_id: SessionId,
|
session_id: SessionId,
|
||||||
text: String,
|
text: String,
|
||||||
model_ref: &str,
|
model_ref: &str,
|
||||||
|
) -> Result<(), AppError> {
|
||||||
|
self.prompt_with(session_id, text, model_ref, None).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like [`prompt`](Self::prompt) but lets a slash command override the agent for this one
|
||||||
|
/// run (`agent_override`) without mutating the stored session agent.
|
||||||
|
pub async fn prompt_with(
|
||||||
|
&self,
|
||||||
|
session_id: SessionId,
|
||||||
|
text: String,
|
||||||
|
model_ref: &str,
|
||||||
|
agent_override: Option<&str>,
|
||||||
) -> Result<(), AppError> {
|
) -> Result<(), AppError> {
|
||||||
let (provider_id, model_id) = model_ref
|
let (provider_id, model_id) = model_ref
|
||||||
.split_once('/')
|
.split_once('/')
|
||||||
@@ -272,6 +394,12 @@ impl EngineHandle {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Crash-resume: a previous run may have died mid-turn (process killed) leaving an
|
||||||
|
// assistant message with no finish/error and tool parts stuck Running/Pending. Repair
|
||||||
|
// that before appending the new turn so history is well-formed and the model isn't
|
||||||
|
// shown a dangling tool call.
|
||||||
|
self.inner.repair_unfinished(&session_id).await?;
|
||||||
|
|
||||||
let now = now_ms();
|
let now = now_ms();
|
||||||
let user_message = Message::new_user(session_id.clone(), now);
|
let user_message = Message::new_user(session_id.clone(), now);
|
||||||
self.inner
|
self.inner
|
||||||
@@ -285,6 +413,9 @@ impl EngineHandle {
|
|||||||
message: user_message.clone(),
|
message: user_message.clone(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Fire-and-forget session-title generation from the first user turn's text.
|
||||||
|
self.inner.spawn_title_generation(&session_id, &text);
|
||||||
|
|
||||||
let user_part = Part {
|
let user_part = Part {
|
||||||
id: PartId::new(),
|
id: PartId::new(),
|
||||||
message_id: user_message.id.clone(),
|
message_id: user_message.id.clone(),
|
||||||
@@ -300,14 +431,18 @@ impl EngineHandle {
|
|||||||
.bus
|
.bus
|
||||||
.publish(AppEvent::PartUpdated { part: user_part });
|
.publish(AppEvent::PartUpdated { part: user_part });
|
||||||
|
|
||||||
// Resolve the session's agent from the registry (falls back to a generic assistant).
|
// Resolve the agent: a command's `agent:` override for this run, else the session's
|
||||||
let session_agent = self
|
// stored agent (falling back to a generic assistant).
|
||||||
|
let session_agent = match agent_override {
|
||||||
|
Some(name) => name.to_string(),
|
||||||
|
None => self
|
||||||
.inner
|
.inner
|
||||||
.store
|
.store
|
||||||
.session(session_id.clone())
|
.session(session_id.clone())
|
||||||
.await?
|
.await?
|
||||||
.map(|s| s.agent)
|
.map(|s| s.agent)
|
||||||
.unwrap_or_else(|| "orchestrator".to_string());
|
.unwrap_or_else(|| "orchestrator".to_string()),
|
||||||
|
};
|
||||||
let agent = self.inner.agent_def(&session_agent);
|
let agent = self.inner.agent_def(&session_agent);
|
||||||
let inject_job_board = self.inner.config.orchestration.job_board && agent.mode.is_primary();
|
let inject_job_board = self.inner.config.orchestration.job_board && agent.mode.is_primary();
|
||||||
let board = self.inner.board_for(&session_id).await?;
|
let board = self.inner.board_for(&session_id).await?;
|
||||||
@@ -328,6 +463,8 @@ impl EngineHandle {
|
|||||||
spawner: Some(self.inner.clone()),
|
spawner: Some(self.inner.clone()),
|
||||||
job_board: Some(board),
|
job_board: Some(board),
|
||||||
context_reporter: None, // root session has no parent board to report to
|
context_reporter: None, // root session has no parent board to report to
|
||||||
|
diagnostics: self.inner.diagnostics.clone(),
|
||||||
|
compactor: self.inner.compactor.clone(),
|
||||||
};
|
};
|
||||||
let run_config = RunConfig {
|
let run_config = RunConfig {
|
||||||
agent_name: agent.name.clone(),
|
agent_name: agent.name.clone(),
|
||||||
@@ -340,6 +477,13 @@ impl EngineHandle {
|
|||||||
inject_job_board,
|
inject_job_board,
|
||||||
reminder_turn_start: self.inner.reminder("turn_start"),
|
reminder_turn_start: self.inner.reminder("turn_start"),
|
||||||
reminder_after_file_tool: self.inner.reminder("after_file_tool"),
|
reminder_after_file_tool: self.inner.reminder("after_file_tool"),
|
||||||
|
skills_prompt: self.inner.skills_prompt.clone(),
|
||||||
|
context_limit: self
|
||||||
|
.inner
|
||||||
|
.catalog
|
||||||
|
.get(provider_id, model_id)
|
||||||
|
.map(|i| i.context_limit)
|
||||||
|
.unwrap_or(0),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Reserve the run slot *before* spawning. If we inserted after spawning, a run that
|
// Reserve the run slot *before* spawning. If we inserted after spawning, a run that
|
||||||
@@ -405,6 +549,13 @@ impl EngineHandle {
|
|||||||
Ok(self.inner.store.session(session_id).await?)
|
Ok(self.inner.store.session(session_id).await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Repairs a crashed-mid-run session (unfinished assistant → aborted, in-flight tool parts
|
||||||
|
/// → interrupted). Idempotent; safe to call whenever a session is loaded/resumed.
|
||||||
|
pub async fn repair_session(&self, session_id: &SessionId) -> Result<(), AppError> {
|
||||||
|
self.inner.repair_unfinished(session_id).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Background jobs spawned by `session_id` (the parent), for the TUI jobs pane / drill-in.
|
/// Background jobs spawned by `session_id` (the parent), for the TUI jobs pane / drill-in.
|
||||||
pub async fn jobs(
|
pub async fn jobs(
|
||||||
&self,
|
&self,
|
||||||
@@ -457,6 +608,116 @@ impl EngineInner {
|
|||||||
.expect("EngineInner self-reference set in new()")
|
.expect("EngineInner self-reference set in new()")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Repairs a session that crashed mid-run: any assistant message with neither a finish
|
||||||
|
/// reason nor an error is marked `Aborted`, and its in-flight tool parts (Running/Pending)
|
||||||
|
/// become `Error { "interrupted" }`. Idempotent — a clean session is left untouched.
|
||||||
|
async fn repair_unfinished(&self, session_id: &SessionId) -> Result<(), StoreError> {
|
||||||
|
let messages = self.store.messages(session_id.clone()).await?;
|
||||||
|
for message in messages {
|
||||||
|
let crashed = message.role == harness_core::types::Role::Assistant
|
||||||
|
&& message.finished.is_none()
|
||||||
|
&& message.error.is_none();
|
||||||
|
if !crashed {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
for mut part in self.store.parts(message.id.clone()).await? {
|
||||||
|
let interrupted = match &part.body {
|
||||||
|
PartBody::Tool { state, .. } => matches!(
|
||||||
|
state,
|
||||||
|
harness_core::types::ToolState::Running { .. }
|
||||||
|
| harness_core::types::ToolState::Pending { .. }
|
||||||
|
),
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
if !interrupted {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let PartBody::Tool {
|
||||||
|
call_id,
|
||||||
|
name,
|
||||||
|
state,
|
||||||
|
} = part.body
|
||||||
|
{
|
||||||
|
let input = match &state {
|
||||||
|
harness_core::types::ToolState::Running { input, .. } => input.clone(),
|
||||||
|
_ => serde_json::Value::Null,
|
||||||
|
};
|
||||||
|
part.body = PartBody::Tool {
|
||||||
|
call_id,
|
||||||
|
name,
|
||||||
|
state: harness_core::types::ToolState::Error {
|
||||||
|
input,
|
||||||
|
error: "interrupted".to_string(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
self.store.upsert_part(part.clone()).await?;
|
||||||
|
self.bus.publish(AppEvent::PartUpdated { part });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut repaired = message;
|
||||||
|
repaired.error = Some(harness_core::types::MessageError::Aborted);
|
||||||
|
self.store.upsert_message(repaired.clone()).await?;
|
||||||
|
self.bus
|
||||||
|
.publish(AppEvent::MessageUpdated { message: repaired });
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fires a background task that generates a short session title from the first user turn.
|
||||||
|
/// No-op when no `small_model` is available; the title is only generated once (the task
|
||||||
|
/// re-checks that the session is still untitled before writing).
|
||||||
|
fn spawn_title_generation(&self, session_id: &SessionId, user_text: &str) {
|
||||||
|
let Some((provider, model_id)) = self.small_model.clone() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let inner = self.arc();
|
||||||
|
let session_id = session_id.clone();
|
||||||
|
let user_text = user_text.to_string();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
inner
|
||||||
|
.generate_title(provider, model_id, session_id, user_text)
|
||||||
|
.await;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Generates and stores a session title for a still-untitled root session.
|
||||||
|
async fn generate_title(
|
||||||
|
&self,
|
||||||
|
provider: Arc<dyn Provider>,
|
||||||
|
model_id: String,
|
||||||
|
session_id: SessionId,
|
||||||
|
user_text: String,
|
||||||
|
) {
|
||||||
|
// Only title a root session that hasn't been titled yet.
|
||||||
|
match self.store.session(session_id.clone()).await {
|
||||||
|
Ok(Some(s)) if s.depth == 0 && s.title.is_empty() => {}
|
||||||
|
_ => return,
|
||||||
|
}
|
||||||
|
let raw = match oneshot_text(&provider, &model_id, TITLE_SYSTEM_PROMPT, &user_text).await {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::debug!(error = %e, "session-title generation failed");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let title = sanitize_title(&raw);
|
||||||
|
if title.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if let Ok(Some(mut session)) = self.store.session(session_id.clone()).await {
|
||||||
|
if !session.title.is_empty() {
|
||||||
|
return; // titled concurrently; don't clobber
|
||||||
|
}
|
||||||
|
session.title = title;
|
||||||
|
session.updated_at = now_ms();
|
||||||
|
if self.store.upsert_session(session.clone()).await.is_ok() {
|
||||||
|
self.bus.publish(AppEvent::SessionUpdated { session });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Resolves an agent definition by name, falling back to a generic assistant so an
|
/// Resolves an agent definition by name, falling back to a generic assistant so an
|
||||||
/// unknown/misconfigured agent still runs rather than failing the session.
|
/// unknown/misconfigured agent still runs rather than failing the session.
|
||||||
fn agent_def(&self, name: &str) -> AgentDef {
|
fn agent_def(&self, name: &str) -> AgentDef {
|
||||||
@@ -633,6 +894,8 @@ impl EngineInner {
|
|||||||
spawner: Some(self.arc()),
|
spawner: Some(self.arc()),
|
||||||
job_board: Some(board),
|
job_board: Some(board),
|
||||||
context_reporter: reporter,
|
context_reporter: reporter,
|
||||||
|
diagnostics: self.diagnostics.clone(),
|
||||||
|
compactor: self.compactor.clone(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -653,6 +916,101 @@ impl ContextReporter for BoardReporter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// System prompt for session-title generation.
|
||||||
|
const TITLE_SYSTEM_PROMPT: &str = "Generate a concise title (3 to 6 words) for a coding \
|
||||||
|
session, summarizing what the user is asking for. No quotes, no trailing punctuation, no \
|
||||||
|
preamble. Output only the title.";
|
||||||
|
|
||||||
|
/// Cap on a generated title's length, in characters.
|
||||||
|
const MAX_TITLE_LEN: usize = 60;
|
||||||
|
|
||||||
|
/// Cleans a model-generated title: first non-empty line, stripped of surrounding quotes, and
|
||||||
|
/// truncated to [`MAX_TITLE_LEN`] characters (on a char boundary).
|
||||||
|
fn sanitize_title(raw: &str) -> String {
|
||||||
|
let line = raw
|
||||||
|
.lines()
|
||||||
|
.map(str::trim)
|
||||||
|
.find(|l| !l.is_empty())
|
||||||
|
.unwrap_or("");
|
||||||
|
let line = line
|
||||||
|
.trim_matches(|c| c == '"' || c == '\'' || c == '`')
|
||||||
|
.trim();
|
||||||
|
line.chars().take(MAX_TITLE_LEN).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One-shot text completion: sends `user_text` under `system` to the model and concatenates the
|
||||||
|
/// streamed text. Used for session titles (compaction uses the message-array form directly).
|
||||||
|
async fn oneshot_text(
|
||||||
|
provider: &Arc<dyn Provider>,
|
||||||
|
model_id: &str,
|
||||||
|
system: &str,
|
||||||
|
user_text: &str,
|
||||||
|
) -> Result<String, ProviderError> {
|
||||||
|
use futures::StreamExt;
|
||||||
|
|
||||||
|
let req = LlmRequest {
|
||||||
|
model: model_id.to_string(),
|
||||||
|
system: vec![system.to_string()],
|
||||||
|
messages: vec![WireMessage {
|
||||||
|
role: WireRole::User,
|
||||||
|
content: vec![WireContent::Text {
|
||||||
|
text: user_text.to_string(),
|
||||||
|
}],
|
||||||
|
}],
|
||||||
|
tools: Vec::new(),
|
||||||
|
temperature: None,
|
||||||
|
max_tokens: None,
|
||||||
|
reasoning: None,
|
||||||
|
initiator: Initiator::Agent,
|
||||||
|
};
|
||||||
|
let mut stream = provider.stream(req, CancellationToken::new()).await?;
|
||||||
|
let mut out = String::new();
|
||||||
|
while let Some(event) = stream.next().await {
|
||||||
|
if let LlmEvent::TextDelta { text, .. } = event? {
|
||||||
|
out.push_str(&text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Auto-compaction backend: summarizes a conversation with the configured `small_model`.
|
||||||
|
struct SmallModelCompactor {
|
||||||
|
provider: Arc<dyn Provider>,
|
||||||
|
model_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SmallModelCompactor {
|
||||||
|
fn new(provider: Arc<dyn Provider>, model_id: String) -> Self {
|
||||||
|
Self { provider, model_id }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Compactor for SmallModelCompactor {
|
||||||
|
async fn summarize(&self, messages: &[WireMessage]) -> Result<String, ProviderError> {
|
||||||
|
use futures::StreamExt;
|
||||||
|
|
||||||
|
let req = LlmRequest {
|
||||||
|
model: self.model_id.clone(),
|
||||||
|
system: vec![harness_core::engine::compact::SUMMARY_SYSTEM_PROMPT.to_string()],
|
||||||
|
messages: messages.to_vec(),
|
||||||
|
tools: Vec::new(),
|
||||||
|
temperature: None,
|
||||||
|
max_tokens: None,
|
||||||
|
reasoning: None,
|
||||||
|
initiator: Initiator::Agent,
|
||||||
|
};
|
||||||
|
let mut stream = self.provider.stream(req, CancellationToken::new()).await?;
|
||||||
|
let mut summary = String::new();
|
||||||
|
while let Some(event) = stream.next().await {
|
||||||
|
if let LlmEvent::TextDelta { text, .. } = event? {
|
||||||
|
summary.push_str(&text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(summary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl SubagentSpawner for EngineInner {
|
impl SubagentSpawner for EngineInner {
|
||||||
async fn spawn(&self, req: SpawnRequest) -> Result<SpawnOutcome, SpawnError> {
|
async fn spawn(&self, req: SpawnRequest) -> Result<SpawnOutcome, SpawnError> {
|
||||||
@@ -751,6 +1109,15 @@ impl SubagentSpawner for EngineInner {
|
|||||||
inject_job_board: agent.mode.is_primary(),
|
inject_job_board: agent.mode.is_primary(),
|
||||||
reminder_turn_start: self.reminder("turn_start"),
|
reminder_turn_start: self.reminder("turn_start"),
|
||||||
reminder_after_file_tool: self.reminder("after_file_tool"),
|
reminder_after_file_tool: self.reminder("after_file_tool"),
|
||||||
|
skills_prompt: self.skills_prompt.clone(),
|
||||||
|
context_limit: self
|
||||||
|
.catalog
|
||||||
|
.get(
|
||||||
|
&child_session.model.provider_id,
|
||||||
|
&child_session.model.model_id,
|
||||||
|
)
|
||||||
|
.map(|i| i.context_limit)
|
||||||
|
.unwrap_or(0),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Register the launch on the parent board (also makes foreground results reusable).
|
// Register the launch on the parent board (also makes foreground results reusable).
|
||||||
@@ -867,8 +1234,8 @@ pub struct App {
|
|||||||
impl App {
|
impl App {
|
||||||
/// Persistent SQLite-backed store with an auto-approve permission frontend — the default
|
/// Persistent SQLite-backed store with an auto-approve permission frontend — the default
|
||||||
/// headless configuration used by `harness run -p`.
|
/// headless configuration used by `harness run -p`.
|
||||||
pub fn init(cwd: PathBuf) -> Result<Self, AppError> {
|
pub async fn init(cwd: PathBuf) -> Result<Self, AppError> {
|
||||||
let engine = EngineHandle::init(cwd)?;
|
let engine = EngineHandle::init(cwd).await?;
|
||||||
let _auto_approve_handle = Some(spawn_auto_approve_task(&engine));
|
let _auto_approve_handle = Some(spawn_auto_approve_task(&engine));
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
engine,
|
engine,
|
||||||
@@ -997,6 +1364,7 @@ mod tests {
|
|||||||
Store::open_in_memory().unwrap(),
|
Store::open_in_memory().unwrap(),
|
||||||
Config::default(),
|
Config::default(),
|
||||||
providers,
|
providers,
|
||||||
|
Vec::new(),
|
||||||
)
|
)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
@@ -1086,6 +1454,7 @@ mod tests {
|
|||||||
Store::open_in_memory().unwrap(),
|
Store::open_in_memory().unwrap(),
|
||||||
Config::default(),
|
Config::default(),
|
||||||
providers,
|
providers,
|
||||||
|
Vec::new(),
|
||||||
)
|
)
|
||||||
.unwrap();
|
.unwrap();
|
||||||
// Auto-approve permission asks (the child's read tool gates on `read`).
|
// Auto-approve permission asks (the child's read tool gates on `read`).
|
||||||
@@ -1263,6 +1632,184 @@ mod tests {
|
|||||||
assert_eq!(app.engine.inner.tools.all().len(), 7);
|
assert_eq!(app.engine.inner.tools.all().len(), 7);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn project_skill_registers_the_skill_tool_and_advertises_it() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let skill_dir = dir.path().join(".harness").join("skill").join("fmt");
|
||||||
|
std::fs::create_dir_all(&skill_dir).unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
skill_dir.join("SKILL.md"),
|
||||||
|
"---\ndescription: format the code\n---\nRun cargo fmt.",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let engine = EngineHandle::init_in_memory(dir.path().to_path_buf()).unwrap();
|
||||||
|
// 6 built-ins + task + skill.
|
||||||
|
assert_eq!(engine.inner.tools.all().len(), 8);
|
||||||
|
assert!(engine.inner.tools.get("skill").is_some());
|
||||||
|
let prompt = engine
|
||||||
|
.inner
|
||||||
|
.skills_prompt
|
||||||
|
.clone()
|
||||||
|
.expect("skills advertised");
|
||||||
|
assert!(prompt.contains("**fmt** — format the code"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn project_command_loads_and_expands() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let cmd_dir = dir.path().join(".harness").join("command");
|
||||||
|
std::fs::create_dir_all(&cmd_dir).unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
cmd_dir.join("greet.md"),
|
||||||
|
"---\ndescription: greet\nagent: explorer\n---\nHello $1, welcome.",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let engine = EngineHandle::init_in_memory(dir.path().to_path_buf()).unwrap();
|
||||||
|
let cmd = engine.command("greet").expect("command loaded");
|
||||||
|
assert_eq!(cmd.agent.as_deref(), Some("explorer"));
|
||||||
|
assert_eq!(cmd.expand("world"), "Hello world, welcome.");
|
||||||
|
assert!(engine.command("missing").is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn command_run_reaches_engine_with_agent_override() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let engine = mock_engine(dir.path().to_path_buf());
|
||||||
|
spawn_auto_approve_task(&engine);
|
||||||
|
let session = engine
|
||||||
|
.new_session("orchestrator", "mock/mock-model")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// Drive the command path directly: expand + agent override for this run only.
|
||||||
|
engine
|
||||||
|
.prompt_with(
|
||||||
|
session.clone(),
|
||||||
|
"do the thing".into(),
|
||||||
|
"mock/mock-model",
|
||||||
|
Some("explorer"),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// Wait for the run to finish.
|
||||||
|
let mut rx = engine.bus().subscribe();
|
||||||
|
loop {
|
||||||
|
if let Ok(AppEvent::RunFinished { session_id, .. }) = rx.recv().await {
|
||||||
|
if session_id == session {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The stored session agent is untouched by the per-run override.
|
||||||
|
let stored = engine.get_session(session).await.unwrap().unwrap();
|
||||||
|
assert_eq!(stored.agent, "orchestrator");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn repair_marks_crashed_assistant_aborted_and_interrupts_tool_parts() {
|
||||||
|
use harness_core::types::{MessageError, PartId, Role, ToolState};
|
||||||
|
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let engine = mock_engine(dir.path().to_path_buf());
|
||||||
|
let session = engine
|
||||||
|
.new_session("orchestrator", "mock/mock-model")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// A crashed assistant turn: no finish, no error, with a tool call left Running.
|
||||||
|
let model = ModelRef::new("mock", "mock-model");
|
||||||
|
let crashed = Message::new_assistant(session.clone(), model, "orchestrator", now_ms());
|
||||||
|
engine
|
||||||
|
.inner
|
||||||
|
.store
|
||||||
|
.upsert_message(crashed.clone())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let part = Part {
|
||||||
|
id: PartId::new(),
|
||||||
|
message_id: crashed.id.clone(),
|
||||||
|
session_id: session.clone(),
|
||||||
|
idx: 0,
|
||||||
|
body: PartBody::Tool {
|
||||||
|
call_id: "c1".into(),
|
||||||
|
name: "bash".into(),
|
||||||
|
state: ToolState::Running {
|
||||||
|
input: serde_json::json!({"command": "sleep 100"}),
|
||||||
|
title: None,
|
||||||
|
metadata: serde_json::Value::Null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
engine.inner.store.upsert_part(part).await.unwrap();
|
||||||
|
|
||||||
|
engine.inner.repair_unfinished(&session).await.unwrap();
|
||||||
|
|
||||||
|
let messages = engine.inner.store.messages(session.clone()).await.unwrap();
|
||||||
|
let repaired = messages.iter().find(|m| m.id == crashed.id).unwrap();
|
||||||
|
assert_eq!(repaired.role, Role::Assistant);
|
||||||
|
assert!(matches!(repaired.error, Some(MessageError::Aborted)));
|
||||||
|
|
||||||
|
let parts = engine.inner.store.parts(crashed.id.clone()).await.unwrap();
|
||||||
|
match &parts[0].body {
|
||||||
|
PartBody::Tool { state, .. } => match state {
|
||||||
|
ToolState::Error { error, .. } => assert_eq!(error, "interrupted"),
|
||||||
|
other => panic!("expected Error tool state, got {other:?}"),
|
||||||
|
},
|
||||||
|
other => panic!("expected Tool part, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn first_prompt_generates_a_session_title() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let mut providers = ProviderRegistry::new();
|
||||||
|
providers.register(Arc::new(MockProvider));
|
||||||
|
let config = Config {
|
||||||
|
small_model: Some("mock/mock-model".into()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let engine = EngineHandle::build(
|
||||||
|
dir.path().to_path_buf(),
|
||||||
|
Store::open_in_memory().unwrap(),
|
||||||
|
config,
|
||||||
|
providers,
|
||||||
|
Vec::new(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
spawn_auto_approve_task(&engine);
|
||||||
|
let session = engine
|
||||||
|
.new_session("orchestrator", "mock/mock-model")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let mut rx = engine.bus().subscribe();
|
||||||
|
engine
|
||||||
|
.prompt(
|
||||||
|
session.clone(),
|
||||||
|
"help me refactor the auth module".into(),
|
||||||
|
"mock/mock-model",
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// The title-generation task (small model = the mock) publishes a SessionUpdated whose
|
||||||
|
// title is the mock's canned text.
|
||||||
|
let title = tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||||
|
loop {
|
||||||
|
if let Ok(AppEvent::SessionUpdated { session: s }) = rx.recv().await {
|
||||||
|
if s.id == session && !s.title.is_empty() {
|
||||||
|
return s.title;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("a titled SessionUpdated within the timeout");
|
||||||
|
assert_eq!(title, "explored the code");
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn run_prompt_errors_on_unregistered_provider() {
|
async fn run_prompt_errors_on_unregistered_provider() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
@@ -0,0 +1,296 @@
|
|||||||
|
//! Markdown-defined commands and skills (M5). Both are YAML-frontmatter + body files loaded
|
||||||
|
//! from a global dir (`~/.config/ai-harness/<kind>/`) and a project dir (`<project>/.harness/
|
||||||
|
//! <kind>/`), project winning by name. See `docs/06-config.md` and `docs/09-integrations.md`.
|
||||||
|
//!
|
||||||
|
//! - Commands (`command/*.md`) are a pure input-layer concern: `/name args` expands the body
|
||||||
|
//! template (`$ARGUMENTS`, `$1..$9`) into the user message, optionally switching agent/model.
|
||||||
|
//! - Skills (`skill/<name>/SKILL.md`) advertise `name + description` in the system prompt; the
|
||||||
|
//! model pulls a skill's body on demand via the built-in `skill` tool.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
/// A slash command: a named prompt template with an optional agent/model override.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct CommandDef {
|
||||||
|
/// Invocation name (the file stem); used as `/name`.
|
||||||
|
pub name: String,
|
||||||
|
pub description: String,
|
||||||
|
/// Run the expanded prompt under this agent instead of the session's default.
|
||||||
|
pub agent: Option<String>,
|
||||||
|
/// Run under this `provider/model` instead of the session's default.
|
||||||
|
pub model: Option<String>,
|
||||||
|
/// The body, with `$ARGUMENTS` / `$1..$9` placeholders.
|
||||||
|
pub template: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CommandDef {
|
||||||
|
/// Substitutes `$ARGUMENTS` (the whole argument string) and `$1..$9` (whitespace-split
|
||||||
|
/// positionals; missing ones become empty) into the template.
|
||||||
|
pub fn expand(&self, arguments: &str) -> String {
|
||||||
|
let positionals: Vec<&str> = arguments.split_whitespace().collect();
|
||||||
|
let mut out = self.template.replace("$ARGUMENTS", arguments);
|
||||||
|
for i in 1..=9 {
|
||||||
|
let value = positionals.get(i - 1).copied().unwrap_or("");
|
||||||
|
out = out.replace(&format!("${i}"), value);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A skill: advertised by `name + description`, body loaded on demand by the `skill` tool.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct SkillDef {
|
||||||
|
/// Skill name (the containing directory name); used as the `skill` tool argument.
|
||||||
|
pub name: String,
|
||||||
|
pub description: String,
|
||||||
|
pub body: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Frontmatter fields shared by commands (all optional).
|
||||||
|
#[derive(Debug, Default, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
struct CommandFrontmatter {
|
||||||
|
description: Option<String>,
|
||||||
|
agent: Option<String>,
|
||||||
|
model: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
struct SkillFrontmatter {
|
||||||
|
description: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Splits `---\n…\n---\n` frontmatter from the body. A file with no leading fence is all body.
|
||||||
|
fn split_frontmatter(content: &str) -> (&str, &str) {
|
||||||
|
let rest = match content
|
||||||
|
.strip_prefix("---\n")
|
||||||
|
.or_else(|| content.strip_prefix("---\r\n"))
|
||||||
|
{
|
||||||
|
Some(r) => r,
|
||||||
|
None => return ("", content),
|
||||||
|
};
|
||||||
|
for delim in ["\n---\n", "\n---\r\n"] {
|
||||||
|
if let Some(idx) = rest.find(delim) {
|
||||||
|
return (&rest[..idx], &rest[idx + delim.len()..]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if rest.ends_with("\n---") {
|
||||||
|
return (rest.trim_end_matches("\n---"), "");
|
||||||
|
}
|
||||||
|
("", content)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_command(name: &str, content: &str) -> CommandDef {
|
||||||
|
let (fm_raw, body) = split_frontmatter(content);
|
||||||
|
let fm: CommandFrontmatter = if fm_raw.trim().is_empty() {
|
||||||
|
CommandFrontmatter::default()
|
||||||
|
} else {
|
||||||
|
serde_yaml_ng::from_str(fm_raw).unwrap_or_default()
|
||||||
|
};
|
||||||
|
CommandDef {
|
||||||
|
name: name.to_string(),
|
||||||
|
description: fm.description.unwrap_or_default(),
|
||||||
|
agent: fm.agent,
|
||||||
|
model: fm.model,
|
||||||
|
template: body.trim().to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_skill(name: &str, content: &str) -> SkillDef {
|
||||||
|
let (fm_raw, body) = split_frontmatter(content);
|
||||||
|
let fm: SkillFrontmatter = if fm_raw.trim().is_empty() {
|
||||||
|
SkillFrontmatter::default()
|
||||||
|
} else {
|
||||||
|
serde_yaml_ng::from_str(fm_raw).unwrap_or_default()
|
||||||
|
};
|
||||||
|
SkillDef {
|
||||||
|
name: name.to_string(),
|
||||||
|
description: fm.description.unwrap_or_default(),
|
||||||
|
body: body.trim().to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Loads `command/*.md` from global then project dirs (project wins by name).
|
||||||
|
pub fn load_commands(
|
||||||
|
global_dir: Option<&Path>,
|
||||||
|
project_dir: Option<&Path>,
|
||||||
|
) -> HashMap<String, CommandDef> {
|
||||||
|
let mut commands = HashMap::new();
|
||||||
|
for dir in [global_dir, project_dir].into_iter().flatten() {
|
||||||
|
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let path = entry.path();
|
||||||
|
if path.extension().and_then(|e| e.to_str()) != Some("md") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(name) = path.file_stem().and_then(|s| s.to_str()) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if let Ok(content) = std::fs::read_to_string(&path) {
|
||||||
|
commands.insert(name.to_string(), parse_command(name, &content));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
commands
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Loads `skill/<name>/SKILL.md` from global then project dirs (project wins by name),
|
||||||
|
/// returned name-sorted for a stable system-prompt listing.
|
||||||
|
pub fn load_skills(global_dir: Option<&Path>, project_dir: Option<&Path>) -> Vec<SkillDef> {
|
||||||
|
let mut by_name: HashMap<String, SkillDef> = HashMap::new();
|
||||||
|
for dir in [global_dir, project_dir].into_iter().flatten() {
|
||||||
|
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let path = entry.path();
|
||||||
|
if !path.is_dir() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(name) = path.file_name().and_then(|s| s.to_str()) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let skill_file = path.join("SKILL.md");
|
||||||
|
if let Ok(content) = std::fs::read_to_string(&skill_file) {
|
||||||
|
by_name.insert(name.to_string(), parse_skill(name, &content));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut skills: Vec<SkillDef> = by_name.into_values().collect();
|
||||||
|
skills.sort_by(|a, b| a.name.cmp(&b.name));
|
||||||
|
skills
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The system-prompt section advertising available skills (name + description). `None` when
|
||||||
|
/// there are no skills, so no empty section is injected.
|
||||||
|
pub fn skills_prompt(skills: &[SkillDef]) -> Option<String> {
|
||||||
|
if skills.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut section = String::from(
|
||||||
|
"## Skills\n\nThese skills are available. Load a skill's full instructions on demand \
|
||||||
|
by calling the `skill` tool with its name before doing the related work:\n",
|
||||||
|
);
|
||||||
|
for skill in skills {
|
||||||
|
section.push_str(&format!("- **{}** — {}\n", skill.name, skill.description));
|
||||||
|
}
|
||||||
|
Some(section.trim_end().to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn expand_substitutes_arguments_and_positionals() {
|
||||||
|
let cmd = CommandDef {
|
||||||
|
name: "greet".into(),
|
||||||
|
description: String::new(),
|
||||||
|
agent: None,
|
||||||
|
model: None,
|
||||||
|
template: "Say $1 to $2. All: $ARGUMENTS".into(),
|
||||||
|
};
|
||||||
|
assert_eq!(cmd.expand("hi there"), "Say hi to there. All: hi there");
|
||||||
|
// Missing positionals collapse to empty.
|
||||||
|
assert_eq!(cmd.expand("solo"), "Say solo to . All: solo");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_command_reads_frontmatter_and_body() {
|
||||||
|
let md = "---\ndescription: review a PR\nagent: oracle\nmodel: openai/gpt-5\n---\nReview $ARGUMENTS please.\n";
|
||||||
|
let cmd = parse_command("review", md);
|
||||||
|
assert_eq!(cmd.description, "review a PR");
|
||||||
|
assert_eq!(cmd.agent.as_deref(), Some("oracle"));
|
||||||
|
assert_eq!(cmd.model.as_deref(), Some("openai/gpt-5"));
|
||||||
|
assert_eq!(cmd.template, "Review $ARGUMENTS please.");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_command_without_frontmatter_is_all_template() {
|
||||||
|
let cmd = parse_command("x", "just do $1");
|
||||||
|
assert_eq!(cmd.template, "just do $1");
|
||||||
|
assert!(cmd.agent.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parse_skill_reads_description_and_body() {
|
||||||
|
let md = "---\ndescription: format code\n---\nRun the formatter.\n";
|
||||||
|
let skill = parse_skill("formatter", md);
|
||||||
|
assert_eq!(skill.name, "formatter");
|
||||||
|
assert_eq!(skill.description, "format code");
|
||||||
|
assert_eq!(skill.body, "Run the formatter.");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn skills_prompt_lists_each_and_is_none_when_empty() {
|
||||||
|
assert!(skills_prompt(&[]).is_none());
|
||||||
|
let skills = vec![
|
||||||
|
SkillDef {
|
||||||
|
name: "a".into(),
|
||||||
|
description: "does a".into(),
|
||||||
|
body: "…".into(),
|
||||||
|
},
|
||||||
|
SkillDef {
|
||||||
|
name: "b".into(),
|
||||||
|
description: "does b".into(),
|
||||||
|
body: "…".into(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
let prompt = skills_prompt(&skills).unwrap();
|
||||||
|
assert!(prompt.contains("- **a** — does a"));
|
||||||
|
assert!(prompt.contains("- **b** — does b"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_skills_reads_skill_dirs_and_project_wins() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let global = dir.path().join("global");
|
||||||
|
let project = dir.path().join("project");
|
||||||
|
std::fs::create_dir_all(global.join("fmt")).unwrap();
|
||||||
|
std::fs::create_dir_all(project.join("fmt")).unwrap();
|
||||||
|
std::fs::create_dir_all(global.join("lint")).unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
global.join("fmt/SKILL.md"),
|
||||||
|
"---\ndescription: global fmt\n---\nglobal body",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
project.join("fmt/SKILL.md"),
|
||||||
|
"---\ndescription: project fmt\n---\nproject body",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
global.join("lint/SKILL.md"),
|
||||||
|
"---\ndescription: lint\n---\nlint body",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let skills = load_skills(Some(&global), Some(&project));
|
||||||
|
assert_eq!(skills.len(), 2);
|
||||||
|
// Sorted by name: fmt, lint.
|
||||||
|
assert_eq!(skills[0].name, "fmt");
|
||||||
|
assert_eq!(skills[0].description, "project fmt"); // project overrode global
|
||||||
|
assert_eq!(skills[0].body, "project body");
|
||||||
|
assert_eq!(skills[1].name, "lint");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn load_commands_project_overrides_global() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let global = dir.path().join("g");
|
||||||
|
let project = dir.path().join("p");
|
||||||
|
std::fs::create_dir_all(&global).unwrap();
|
||||||
|
std::fs::create_dir_all(&project).unwrap();
|
||||||
|
std::fs::write(global.join("deploy.md"), "global deploy").unwrap();
|
||||||
|
std::fs::write(project.join("deploy.md"), "project deploy").unwrap();
|
||||||
|
let commands = load_commands(Some(&global), Some(&project));
|
||||||
|
assert_eq!(commands.len(), 1);
|
||||||
|
assert_eq!(commands["deploy"].template, "project deploy");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
pub mod load;
|
pub mod load;
|
||||||
|
pub mod markdown;
|
||||||
pub mod schema;
|
pub mod schema;
|
||||||
|
|
||||||
pub use load::{load, ConfigError};
|
pub use load::{load, ConfigError};
|
||||||
|
pub use markdown::{load_commands, load_skills, skills_prompt, CommandDef, SkillDef};
|
||||||
pub use schema::{
|
pub use schema::{
|
||||||
AgentPatch, Config, LspServerConfig, McpServerConfig, OrchestrationConfig, ProviderConfig,
|
AgentPatch, Config, LspServerConfig, McpServerConfig, OrchestrationConfig, ProviderConfig,
|
||||||
TuiConfig,
|
TuiConfig,
|
||||||
|
|||||||
@@ -0,0 +1,146 @@
|
|||||||
|
//! Auto-compaction (M6). When a session's context approaches the model's window the loop
|
||||||
|
//! summarizes the conversation so far via a small model, writes a `Compaction` marker, and
|
||||||
|
//! continues — subsequent requests replace the summarized history with the summary. See
|
||||||
|
//! `docs/02-engine.md`.
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
|
||||||
|
use crate::event::AppEvent;
|
||||||
|
use crate::llm::{ProviderError, WireMessage};
|
||||||
|
use crate::types::{Message, MessageId, Part, PartBody, PartId, SessionId};
|
||||||
|
|
||||||
|
use super::processor::StepContext;
|
||||||
|
|
||||||
|
/// Produces a compact recap of a conversation. Implemented by the composition root over the
|
||||||
|
/// configured `small_model`; absent in headless/test contexts (compaction then disabled).
|
||||||
|
#[async_trait]
|
||||||
|
pub trait Compactor: Send + Sync {
|
||||||
|
async fn summarize(&self, messages: &[WireMessage]) -> Result<String, ProviderError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// System prompt handed to the small model to summarize the conversation for continuation.
|
||||||
|
pub const SUMMARY_SYSTEM_PROMPT: &str = "You are compacting a long coding-assistant \
|
||||||
|
conversation so it can continue within a smaller context window. Write a dense, factual \
|
||||||
|
summary that preserves: the user's goal and constraints, decisions made and why, files \
|
||||||
|
and symbols touched, commands run and their results, and the exact next step in progress. \
|
||||||
|
Omit pleasantries. Output only the summary.";
|
||||||
|
|
||||||
|
/// Frames a raw summary as the synthetic user turn the model sees after compaction.
|
||||||
|
pub fn frame_summary(summary: &str) -> String {
|
||||||
|
format!(
|
||||||
|
"The earlier part of this conversation was summarized to save context. \
|
||||||
|
Continue from this summary:\n\n{summary}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Persists a compaction: a new user message carrying the `Compaction` marker (used to cut
|
||||||
|
/// history on the next load) plus a synthetic text part holding the framed summary (what the
|
||||||
|
/// model actually reads). Returns the new message id.
|
||||||
|
pub async fn write_compaction(
|
||||||
|
ctx: &StepContext,
|
||||||
|
session_id: &SessionId,
|
||||||
|
replaces_up_to: MessageId,
|
||||||
|
summary: String,
|
||||||
|
now: i64,
|
||||||
|
) -> Result<MessageId, ProviderError> {
|
||||||
|
let message = Message::new_user(session_id.clone(), now);
|
||||||
|
let message_id = message.id.clone();
|
||||||
|
let store_err = |e: crate::store::StoreError| ProviderError::Decode(e.to_string());
|
||||||
|
|
||||||
|
ctx.store
|
||||||
|
.upsert_message(message.clone())
|
||||||
|
.await
|
||||||
|
.map_err(store_err)?;
|
||||||
|
ctx.bus.publish(AppEvent::MessageCreated {
|
||||||
|
message: message.clone(),
|
||||||
|
});
|
||||||
|
|
||||||
|
let marker = Part {
|
||||||
|
id: PartId::new(),
|
||||||
|
message_id: message_id.clone(),
|
||||||
|
session_id: session_id.clone(),
|
||||||
|
idx: 0,
|
||||||
|
body: PartBody::Compaction {
|
||||||
|
replaces_up_to,
|
||||||
|
summary: summary.clone(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
ctx.store.upsert_part(marker).await.map_err(store_err)?;
|
||||||
|
|
||||||
|
let text = Part {
|
||||||
|
id: PartId::new(),
|
||||||
|
message_id: message_id.clone(),
|
||||||
|
session_id: session_id.clone(),
|
||||||
|
idx: 1,
|
||||||
|
body: PartBody::Text {
|
||||||
|
text: frame_summary(&summary),
|
||||||
|
synthetic: true,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
ctx.store
|
||||||
|
.upsert_part(text.clone())
|
||||||
|
.await
|
||||||
|
.map_err(store_err)?;
|
||||||
|
ctx.bus.publish(AppEvent::PartUpdated { part: text });
|
||||||
|
|
||||||
|
Ok(message_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Index of the last message carrying a `Compaction` part, given each message's parts. History
|
||||||
|
/// before it is dropped when building the request; `None` means no compaction yet.
|
||||||
|
pub fn last_compaction_index(parts_per_message: &[Vec<Part>]) -> Option<usize> {
|
||||||
|
parts_per_message.iter().rposition(|parts| {
|
||||||
|
parts
|
||||||
|
.iter()
|
||||||
|
.any(|p| matches!(p.body, PartBody::Compaction { .. }))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether accumulated `used` tokens have crossed the compaction threshold (90% of the
|
||||||
|
/// model's context window). `context_limit == 0` (unknown) disables the trigger.
|
||||||
|
pub fn over_threshold(used: u64, context_limit: u64) -> bool {
|
||||||
|
context_limit > 0 && used.saturating_mul(10) > context_limit.saturating_mul(9)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Effective context occupancy for a step's usage: prompt (incl. cache) plus generated output.
|
||||||
|
pub fn tokens_used(usage: &crate::types::TokenUsage) -> u64 {
|
||||||
|
usage.input + usage.cache_read + usage.cache_write + usage.output
|
||||||
|
}
|
||||||
|
|
||||||
|
/// True if a message list has real history to compact before `cut_start` (avoids a useless
|
||||||
|
/// compaction that would summarize nothing and could loop).
|
||||||
|
pub fn has_history_to_compact(messages: &[Message], cut_start: usize) -> bool {
|
||||||
|
messages.len().saturating_sub(cut_start) > 1
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn over_threshold_respects_ninety_percent_and_unknown_limit() {
|
||||||
|
assert!(over_threshold(91, 100));
|
||||||
|
assert!(!over_threshold(90, 100)); // exactly 90% is not yet over
|
||||||
|
assert!(!over_threshold(50, 100));
|
||||||
|
assert!(!over_threshold(1_000_000, 0)); // unknown limit disables the trigger
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tokens_used_sums_prompt_cache_and_output() {
|
||||||
|
let usage = crate::types::TokenUsage {
|
||||||
|
input: 10,
|
||||||
|
output: 5,
|
||||||
|
reasoning: 0,
|
||||||
|
cache_read: 3,
|
||||||
|
cache_write: 2,
|
||||||
|
};
|
||||||
|
assert_eq!(tokens_used(&usage), 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn frame_summary_wraps_text() {
|
||||||
|
let framed = frame_summary("did X");
|
||||||
|
assert!(framed.contains("did X"));
|
||||||
|
assert!(framed.contains("summarized"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -28,6 +28,11 @@ pub struct RunConfig {
|
|||||||
pub reminder_turn_start: Option<String>,
|
pub reminder_turn_start: Option<String>,
|
||||||
/// Optional user-provided reminder injected on the turn after a file tool ran.
|
/// Optional user-provided reminder injected on the turn after a file tool ran.
|
||||||
pub reminder_after_file_tool: Option<String>,
|
pub reminder_after_file_tool: Option<String>,
|
||||||
|
/// Pre-rendered "## Skills" system block advertising loadable skills. `None` = no skills.
|
||||||
|
pub skills_prompt: Option<String>,
|
||||||
|
/// The model's context window in tokens, for the auto-compaction trigger. `0` = unknown
|
||||||
|
/// (disables the threshold trigger; a hard `ContextOverflow` still compacts).
|
||||||
|
pub context_limit: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Adds a step's usage/cost onto the persisted session and republishes it. Cost accounting is
|
/// Adds a step's usage/cost onto the persisted session and republishes it. Cost accounting is
|
||||||
@@ -155,6 +160,54 @@ fn convert_message(message: &Message, parts: &[Part]) -> Vec<WireMessage> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Loads the session's messages, applies the compaction cut (drop everything before the last
|
||||||
|
/// `Compaction` marker), and converts the surviving window to wire messages. Returns the full
|
||||||
|
/// message list (for the "is there history to compact" check) alongside the wire window and
|
||||||
|
/// the cut start index.
|
||||||
|
async fn load_wire(
|
||||||
|
ctx: &StepContext,
|
||||||
|
) -> Result<(Vec<Message>, Vec<WireMessage>, usize), ProviderError> {
|
||||||
|
let messages = ctx
|
||||||
|
.store
|
||||||
|
.messages(ctx.session_id.clone())
|
||||||
|
.await
|
||||||
|
.map_err(|e| ProviderError::Decode(e.to_string()))?;
|
||||||
|
let mut parts_per_message = Vec::with_capacity(messages.len());
|
||||||
|
for message in &messages {
|
||||||
|
let parts = ctx
|
||||||
|
.store
|
||||||
|
.parts(message.id.clone())
|
||||||
|
.await
|
||||||
|
.map_err(|e| ProviderError::Decode(e.to_string()))?;
|
||||||
|
parts_per_message.push(parts);
|
||||||
|
}
|
||||||
|
let cut_start = super::compact::last_compaction_index(&parts_per_message).unwrap_or(0);
|
||||||
|
let mut wire = Vec::new();
|
||||||
|
for (message, parts) in messages.iter().zip(&parts_per_message).skip(cut_start) {
|
||||||
|
wire.extend(convert_message(message, parts));
|
||||||
|
}
|
||||||
|
Ok((messages, wire, cut_start))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Summarizes the current context window and persists a compaction marker. Returns `true` if a
|
||||||
|
/// compaction was actually written (there was history to summarize), `false` if there was
|
||||||
|
/// nothing to compact. Requires `ctx.compactor` to be set.
|
||||||
|
async fn do_compaction(ctx: &StepContext, now: i64) -> Result<bool, ProviderError> {
|
||||||
|
let Some(compactor) = ctx.compactor.clone() else {
|
||||||
|
return Ok(false);
|
||||||
|
};
|
||||||
|
let (messages, wire, cut_start) = load_wire(ctx).await?;
|
||||||
|
if !super::compact::has_history_to_compact(&messages, cut_start) {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
let Some(last) = messages.last() else {
|
||||||
|
return Ok(false);
|
||||||
|
};
|
||||||
|
let summary = compactor.summarize(&wire).await?;
|
||||||
|
super::compact::write_compaction(ctx, &ctx.session_id, last.id.clone(), summary, now).await?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
/// The outer loop: one call per session turn until the model stops asking for tool calls.
|
/// The outer loop: one call per session turn until the model stops asking for tool calls.
|
||||||
/// `now_fn` supplies `created_at`/`StepContext::now` stamps (kept out of the loop body so
|
/// `now_fn` supplies `created_at`/`StepContext::now` stamps (kept out of the loop body so
|
||||||
/// tests can drive deterministic timestamps).
|
/// tests can drive deterministic timestamps).
|
||||||
@@ -185,26 +238,14 @@ pub async fn run_session(
|
|||||||
steps += 1;
|
steps += 1;
|
||||||
ctx.now = now_fn();
|
ctx.now = now_fn();
|
||||||
|
|
||||||
let messages = match ctx.store.messages(ctx.session_id.clone()).await {
|
let mut wire_messages = match load_wire(&ctx).await {
|
||||||
Ok(m) => m,
|
Ok((_, wire, _)) => wire,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
return RunOutcome::Errored {
|
return RunOutcome::Errored {
|
||||||
message: e.to_string(),
|
message: e.to_string(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let mut wire_messages = Vec::new();
|
|
||||||
for message in &messages {
|
|
||||||
let parts = match ctx.store.parts(message.id.clone()).await {
|
|
||||||
Ok(p) => p,
|
|
||||||
Err(e) => {
|
|
||||||
return RunOutcome::Errored {
|
|
||||||
message: e.to_string(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
wire_messages.extend(convert_message(message, &parts));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Collect synthetic (non-persisted) blocks to append to the last user message this
|
// Collect synthetic (non-persisted) blocks to append to the last user message this
|
||||||
// turn: the optional turn-start reminder, the job board, and — if the previous step
|
// turn: the optional turn-start reminder, the job board, and — if the previous step
|
||||||
@@ -240,6 +281,7 @@ pub async fn run_session(
|
|||||||
let system_blocks = system::assemble(
|
let system_blocks = system::assemble(
|
||||||
system::env_header(&ctx.cwd),
|
system::env_header(&ctx.cwd),
|
||||||
&run_config.agent_prompt,
|
&run_config.agent_prompt,
|
||||||
|
run_config.skills_prompt.as_deref(),
|
||||||
&run_config.instructions,
|
&run_config.instructions,
|
||||||
);
|
);
|
||||||
let tools: Vec<ToolSchema> = ctx
|
let tools: Vec<ToolSchema> = ctx
|
||||||
@@ -309,15 +351,49 @@ pub async fn run_session(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Proactive compaction: if the context has crossed ~90% of the window and a
|
||||||
|
// compactor is wired in, summarize before the next request. Best-effort — a
|
||||||
|
// compaction failure just means we continue with the full history.
|
||||||
|
let near_limit = ctx.compactor.is_some()
|
||||||
|
&& super::compact::over_threshold(
|
||||||
|
super::compact::tokens_used(&outcome.usage),
|
||||||
|
run_config.context_limit,
|
||||||
|
);
|
||||||
match outcome.result {
|
match outcome.result {
|
||||||
StepResult::Continue => continue,
|
StepResult::Continue | StepResult::Compact => {
|
||||||
|
if near_limit || matches!(outcome.result, StepResult::Compact) {
|
||||||
|
if let Err(e) = do_compaction(&ctx, now_fn()).await {
|
||||||
|
tracing::warn!(error = %e, "compaction failed; continuing with full history");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
StepResult::Stop => return RunOutcome::Stopped,
|
StepResult::Stop => return RunOutcome::Stopped,
|
||||||
StepResult::Compact => return RunOutcome::Stopped, // stub until M6
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(step_err) if matches!(step_err.source, ProviderError::Cancelled) => {
|
Err(step_err) if matches!(step_err.source, ProviderError::Cancelled) => {
|
||||||
return RunOutcome::Aborted;
|
return RunOutcome::Aborted;
|
||||||
}
|
}
|
||||||
|
// A hard context-window overflow is recoverable when a compactor is available:
|
||||||
|
// summarize and retry. If there was nothing left to compact, surface the error.
|
||||||
|
Err(step_err)
|
||||||
|
if matches!(step_err.source, ProviderError::ContextOverflow)
|
||||||
|
&& ctx.compactor.is_some() =>
|
||||||
|
{
|
||||||
|
match do_compaction(&ctx, now_fn()).await {
|
||||||
|
Ok(true) => continue,
|
||||||
|
Ok(false) => {
|
||||||
|
return RunOutcome::Errored {
|
||||||
|
message: step_err.source.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
return RunOutcome::Errored {
|
||||||
|
message: e.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Err(step_err) => {
|
Err(step_err) => {
|
||||||
return RunOutcome::Errored {
|
return RunOutcome::Errored {
|
||||||
message: step_err.source.to_string(),
|
message: step_err.source.to_string(),
|
||||||
@@ -434,6 +510,8 @@ mod tests {
|
|||||||
spawner: None,
|
spawner: None,
|
||||||
job_board: None,
|
job_board: None,
|
||||||
context_reporter: None,
|
context_reporter: None,
|
||||||
|
diagnostics: None,
|
||||||
|
compactor: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -518,6 +596,8 @@ mod tests {
|
|||||||
inject_job_board: false,
|
inject_job_board: false,
|
||||||
reminder_turn_start: None,
|
reminder_turn_start: None,
|
||||||
reminder_after_file_tool: None,
|
reminder_after_file_tool: None,
|
||||||
|
skills_prompt: None,
|
||||||
|
context_limit: 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
let outcome = run_session(Arc::new(provider), ctx, &run_config, || 2).await;
|
let outcome = run_session(Arc::new(provider), ctx, &run_config, || 2).await;
|
||||||
@@ -581,6 +661,207 @@ mod tests {
|
|||||||
assert_eq!(final_text, "The file contains: mock file content");
|
assert_eq!(final_text, "The file contains: mock file content");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Records its calls and returns a fixed summary, so a test can assert compaction ran.
|
||||||
|
struct MockCompactor {
|
||||||
|
calls: Arc<std::sync::atomic::AtomicUsize>,
|
||||||
|
summary: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl crate::engine::compact::Compactor for MockCompactor {
|
||||||
|
async fn summarize(&self, _messages: &[WireMessage]) -> Result<String, ProviderError> {
|
||||||
|
self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||||
|
Ok(self.summary.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn seed_session_with_user_text(store: &Store, model: &ModelRef, text: &str) -> SessionId {
|
||||||
|
let session = Session::new_root("orchestrator", model.clone(), 1);
|
||||||
|
let session_id = session.id.clone();
|
||||||
|
store.upsert_session(session).await.unwrap();
|
||||||
|
let user_message = Message::new_user(session_id.clone(), 1);
|
||||||
|
store.upsert_message(user_message.clone()).await.unwrap();
|
||||||
|
store
|
||||||
|
.upsert_part(Part {
|
||||||
|
id: crate::types::PartId::new(),
|
||||||
|
message_id: user_message.id.clone(),
|
||||||
|
session_id: session_id.clone(),
|
||||||
|
idx: 0,
|
||||||
|
body: PartBody::Text {
|
||||||
|
text: text.into(),
|
||||||
|
synthetic: false,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
session_id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_config_with_limit(model: ModelRef, context_limit: u64) -> RunConfig {
|
||||||
|
RunConfig {
|
||||||
|
agent_name: "orchestrator".into(),
|
||||||
|
agent_prompt: "You are a helpful assistant.".into(),
|
||||||
|
model,
|
||||||
|
temperature: None,
|
||||||
|
max_steps: 10,
|
||||||
|
instructions: Vec::new(),
|
||||||
|
cost: None,
|
||||||
|
inject_job_board: false,
|
||||||
|
reminder_turn_start: None,
|
||||||
|
reminder_after_file_tool: None,
|
||||||
|
skills_prompt: None,
|
||||||
|
context_limit,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn compaction_parts(
|
||||||
|
store: &Store,
|
||||||
|
session_id: &SessionId,
|
||||||
|
) -> Vec<(crate::types::MessageId, String)> {
|
||||||
|
let messages = store.messages(session_id.clone()).await.unwrap();
|
||||||
|
let mut found = Vec::new();
|
||||||
|
for message in messages {
|
||||||
|
for part in store.parts(message.id.clone()).await.unwrap() {
|
||||||
|
if let PartBody::Compaction {
|
||||||
|
replaces_up_to,
|
||||||
|
summary,
|
||||||
|
} = part.body
|
||||||
|
{
|
||||||
|
found.push((replaces_up_to, summary));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
found
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn crossing_the_threshold_compacts_then_continues() {
|
||||||
|
let store = Store::open_in_memory().unwrap();
|
||||||
|
let bus = EventBus::new();
|
||||||
|
let model = ModelRef::new("mock", "mock-model");
|
||||||
|
let session_id = seed_session_with_user_text(&store, &model, "do a long task").await;
|
||||||
|
|
||||||
|
// Step 1: a tool-less "continue" whose usage (200) blows past 90% of a 100-token window.
|
||||||
|
// Step 2: a final answer, run against the compacted history.
|
||||||
|
let provider = MockProvider::scripted(vec![
|
||||||
|
vec![
|
||||||
|
Ok(LlmEvent::TextStart { id: "t1".into() }),
|
||||||
|
Ok(LlmEvent::TextDelta {
|
||||||
|
id: "t1".into(),
|
||||||
|
text: "working".into(),
|
||||||
|
}),
|
||||||
|
Ok(LlmEvent::TextEnd { id: "t1".into() }),
|
||||||
|
Ok(LlmEvent::Finish {
|
||||||
|
reason: FinishReason::ToolCalls,
|
||||||
|
usage: usage(200, 0),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
Ok(LlmEvent::TextStart { id: "t2".into() }),
|
||||||
|
Ok(LlmEvent::TextDelta {
|
||||||
|
id: "t2".into(),
|
||||||
|
text: "done".into(),
|
||||||
|
}),
|
||||||
|
Ok(LlmEvent::TextEnd { id: "t2".into() }),
|
||||||
|
Ok(LlmEvent::Finish {
|
||||||
|
reason: FinishReason::Stop,
|
||||||
|
usage: usage(5, 1),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
|
||||||
|
let cwd = tempfile::tempdir().unwrap();
|
||||||
|
let mut ctx = make_ctx(
|
||||||
|
store.clone(),
|
||||||
|
bus,
|
||||||
|
session_id.clone(),
|
||||||
|
cwd.path().to_path_buf(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||||
|
ctx.compactor = Some(Arc::new(MockCompactor {
|
||||||
|
calls: calls.clone(),
|
||||||
|
summary: "COMPACTED SUMMARY".into(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
let run_config = run_config_with_limit(model, 100);
|
||||||
|
let outcome = run_session(Arc::new(provider), ctx, &run_config, || 2).await;
|
||||||
|
assert!(matches!(outcome, RunOutcome::Stopped));
|
||||||
|
assert_eq!(
|
||||||
|
calls.load(std::sync::atomic::Ordering::SeqCst),
|
||||||
|
1,
|
||||||
|
"compacted once"
|
||||||
|
);
|
||||||
|
|
||||||
|
let parts = compaction_parts(&store, &session_id).await;
|
||||||
|
assert_eq!(parts.len(), 1, "one compaction marker written");
|
||||||
|
assert_eq!(parts[0].1, "COMPACTED SUMMARY");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn context_overflow_recovers_by_compacting() {
|
||||||
|
let store = Store::open_in_memory().unwrap();
|
||||||
|
let bus = EventBus::new();
|
||||||
|
let model = ModelRef::new("mock", "mock-model");
|
||||||
|
let session_id = seed_session_with_user_text(&store, &model, "hello").await;
|
||||||
|
// A prior assistant turn (still "in tool calls") so the loop keeps going into step 1 and
|
||||||
|
// there is real history to compact when the overflow hits.
|
||||||
|
let mut prior =
|
||||||
|
Message::new_assistant(session_id.clone(), model.clone(), "orchestrator", 1);
|
||||||
|
prior.finished = Some(FinishReason::ToolCalls);
|
||||||
|
store.upsert_message(prior.clone()).await.unwrap();
|
||||||
|
store
|
||||||
|
.upsert_part(Part {
|
||||||
|
id: crate::types::PartId::new(),
|
||||||
|
message_id: prior.id.clone(),
|
||||||
|
session_id: session_id.clone(),
|
||||||
|
idx: 0,
|
||||||
|
body: PartBody::Text {
|
||||||
|
text: "earlier work".into(),
|
||||||
|
synthetic: false,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// Step 1: hard context overflow (no output). Step 2: succeeds post-compaction.
|
||||||
|
let provider = MockProvider::scripted(vec![
|
||||||
|
vec![Err(ProviderError::ContextOverflow)],
|
||||||
|
vec![
|
||||||
|
Ok(LlmEvent::TextStart { id: "t".into() }),
|
||||||
|
Ok(LlmEvent::TextDelta {
|
||||||
|
id: "t".into(),
|
||||||
|
text: "recovered".into(),
|
||||||
|
}),
|
||||||
|
Ok(LlmEvent::TextEnd { id: "t".into() }),
|
||||||
|
Ok(LlmEvent::Finish {
|
||||||
|
reason: FinishReason::Stop,
|
||||||
|
usage: usage(1, 1),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
|
||||||
|
let cwd = tempfile::tempdir().unwrap();
|
||||||
|
let mut ctx = make_ctx(
|
||||||
|
store.clone(),
|
||||||
|
bus,
|
||||||
|
session_id.clone(),
|
||||||
|
cwd.path().to_path_buf(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||||
|
ctx.compactor = Some(Arc::new(MockCompactor {
|
||||||
|
calls: calls.clone(),
|
||||||
|
summary: "RECAP".into(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
let run_config = run_config_with_limit(model, 0); // threshold off; only overflow triggers
|
||||||
|
let outcome = run_session(Arc::new(provider), ctx, &run_config, || 2).await;
|
||||||
|
assert!(matches!(outcome, RunOutcome::Stopped));
|
||||||
|
assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
|
||||||
|
assert_eq!(compaction_parts(&store, &session_id).await.len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn provider_error_on_first_event_is_reported_and_run_errors() {
|
async fn provider_error_on_first_event_is_reported_and_run_errors() {
|
||||||
let store = Store::open_in_memory().unwrap();
|
let store = Store::open_in_memory().unwrap();
|
||||||
@@ -628,6 +909,8 @@ mod tests {
|
|||||||
inject_job_board: false,
|
inject_job_board: false,
|
||||||
reminder_turn_start: None,
|
reminder_turn_start: None,
|
||||||
reminder_after_file_tool: None,
|
reminder_after_file_tool: None,
|
||||||
|
skills_prompt: None,
|
||||||
|
context_limit: 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
let outcome = run_session(Arc::new(provider), ctx, &run_config, || 2).await;
|
let outcome = run_session(Arc::new(provider), ctx, &run_config, || 2).await;
|
||||||
@@ -735,6 +1018,8 @@ mod tests {
|
|||||||
inject_job_board: true,
|
inject_job_board: true,
|
||||||
reminder_turn_start: None,
|
reminder_turn_start: None,
|
||||||
reminder_after_file_tool: None,
|
reminder_after_file_tool: None,
|
||||||
|
skills_prompt: None,
|
||||||
|
context_limit: 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
let provider = std::sync::Arc::new(CapturingProvider {
|
let provider = std::sync::Arc::new(CapturingProvider {
|
||||||
@@ -802,6 +1087,8 @@ mod tests {
|
|||||||
inject_job_board: false,
|
inject_job_board: false,
|
||||||
reminder_turn_start: Some("REMEMBER: stay on task.".into()),
|
reminder_turn_start: Some("REMEMBER: stay on task.".into()),
|
||||||
reminder_after_file_tool: None,
|
reminder_after_file_tool: None,
|
||||||
|
skills_prompt: None,
|
||||||
|
context_limit: 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
let provider = std::sync::Arc::new(CapturingProvider {
|
let provider = std::sync::Arc::new(CapturingProvider {
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
pub mod compact;
|
||||||
pub mod doomloop;
|
pub mod doomloop;
|
||||||
pub mod jobs;
|
pub mod jobs;
|
||||||
pub mod processor;
|
pub mod processor;
|
||||||
@@ -6,6 +7,7 @@ pub mod retry;
|
|||||||
pub mod session_loop;
|
pub mod session_loop;
|
||||||
pub mod system;
|
pub mod system;
|
||||||
|
|
||||||
|
pub use compact::Compactor;
|
||||||
pub use doomloop::DoomLoopGuard;
|
pub use doomloop::DoomLoopGuard;
|
||||||
pub use jobs::{ContextFile, JobBoard, JobRecord, JobState};
|
pub use jobs::{ContextFile, JobBoard, JobRecord, JobState};
|
||||||
pub use processor::{process_step, StepContext, StepError, StepOutcome, StepResult};
|
pub use processor::{process_step, StepContext, StepError, StepOutcome, StepResult};
|
||||||
|
|||||||
@@ -72,6 +72,11 @@ pub struct StepContext {
|
|||||||
/// Present in subagent sessions: reports read files to this session's job on the parent
|
/// Present in subagent sessions: reports read files to this session's job on the parent
|
||||||
/// board. `None` for root sessions (nothing to report to).
|
/// board. `None` for root sessions (nothing to report to).
|
||||||
pub context_reporter: Option<Arc<dyn ContextReporter>>,
|
pub context_reporter: Option<Arc<dyn ContextReporter>>,
|
||||||
|
/// Language-server diagnostics source shared by the session's edit/write tool calls.
|
||||||
|
pub diagnostics: Option<Arc<dyn crate::lsp::DiagnosticsSource>>,
|
||||||
|
/// Summarizes history when the context nears the model's window. `None` disables
|
||||||
|
/// auto-compaction (headless/tests, or when no `small_model` is configured).
|
||||||
|
pub compactor: Option<Arc<dyn super::compact::Compactor>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct FlushTracker {
|
struct FlushTracker {
|
||||||
@@ -522,6 +527,7 @@ impl<'a> Run<'a> {
|
|||||||
metadata: metadata_sink,
|
metadata: metadata_sink,
|
||||||
spawner: self.ctx.spawner.clone(),
|
spawner: self.ctx.spawner.clone(),
|
||||||
context_reporter: self.ctx.context_reporter.clone(),
|
context_reporter: self.ctx.context_reporter.clone(),
|
||||||
|
diagnostics: self.ctx.diagnostics.clone(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let result = tokio::select! {
|
let result = tokio::select! {
|
||||||
|
|||||||
@@ -25,10 +25,18 @@ pub fn env_header(cwd: &Path) -> String {
|
|||||||
header
|
header
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Ordered system prompt blocks: environment header, agent prompt, then project
|
/// Ordered system prompt blocks: environment header, agent prompt, the optional skills
|
||||||
/// instructions (e.g. AGENTS.md contents). Order matches `02-engine.md`.
|
/// listing, then project instructions (e.g. AGENTS.md contents). Order matches `02-engine.md`.
|
||||||
pub fn assemble(env_header: String, agent_prompt: &str, instructions: &[String]) -> Vec<String> {
|
pub fn assemble(
|
||||||
|
env_header: String,
|
||||||
|
agent_prompt: &str,
|
||||||
|
skills: Option<&str>,
|
||||||
|
instructions: &[String],
|
||||||
|
) -> Vec<String> {
|
||||||
let mut blocks = vec![env_header, agent_prompt.to_string()];
|
let mut blocks = vec![env_header, agent_prompt.to_string()];
|
||||||
|
if let Some(skills) = skills {
|
||||||
|
blocks.push(skills.to_string());
|
||||||
|
}
|
||||||
blocks.extend(instructions.iter().cloned());
|
blocks.extend(instructions.iter().cloned());
|
||||||
blocks
|
blocks
|
||||||
}
|
}
|
||||||
@@ -49,8 +57,20 @@ mod tests {
|
|||||||
let blocks = assemble(
|
let blocks = assemble(
|
||||||
"ENV".to_string(),
|
"ENV".to_string(),
|
||||||
"AGENT",
|
"AGENT",
|
||||||
|
None,
|
||||||
&["AGENTS.md contents".to_string()],
|
&["AGENTS.md contents".to_string()],
|
||||||
);
|
);
|
||||||
assert_eq!(blocks, vec!["ENV", "AGENT", "AGENTS.md contents"]);
|
assert_eq!(blocks, vec!["ENV", "AGENT", "AGENTS.md contents"]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn assemble_inserts_skills_after_agent_before_instructions() {
|
||||||
|
let blocks = assemble(
|
||||||
|
"ENV".to_string(),
|
||||||
|
"AGENT",
|
||||||
|
Some("SKILLS"),
|
||||||
|
&["INSTR".to_string()],
|
||||||
|
);
|
||||||
|
assert_eq!(blocks, vec!["ENV", "AGENT", "SKILLS", "INSTR"]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ pub mod config;
|
|||||||
pub mod engine;
|
pub mod engine;
|
||||||
pub mod event;
|
pub mod event;
|
||||||
pub mod llm;
|
pub mod llm;
|
||||||
|
pub mod lsp;
|
||||||
pub mod permission;
|
pub mod permission;
|
||||||
pub mod store;
|
pub mod store;
|
||||||
pub mod tool;
|
pub mod tool;
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
//! Seam trait for language-server diagnostics, implemented by `harness-lsp` and consumed by
|
||||||
|
//! the edit/write tools. Kept in core so `harness-tools` never links the LSP crate directly.
|
||||||
|
//! See `docs/09-integrations.md`.
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum Severity {
|
||||||
|
Error,
|
||||||
|
Warning,
|
||||||
|
Info,
|
||||||
|
Hint,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One diagnostic reported by a language server. Line/character are 1-based for display.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Diagnostic {
|
||||||
|
pub line: u32,
|
||||||
|
pub character: u32,
|
||||||
|
pub severity: Severity,
|
||||||
|
pub message: String,
|
||||||
|
pub source: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Diagnostic {
|
||||||
|
/// `{file}: L{line}: {message}` — the one-line form appended to tool output.
|
||||||
|
pub fn display_line(&self, file: &str) -> String {
|
||||||
|
format!("{file}: L{}: {}", self.line, self.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A source of file diagnostics (an LSP pool). All methods are best-effort: failures are
|
||||||
|
/// swallowed (logged) so a broken language server never fails a tool call.
|
||||||
|
#[async_trait]
|
||||||
|
pub trait DiagnosticsSource: Send + Sync {
|
||||||
|
/// Ensure a server for `path`'s language is running and told about the file's current
|
||||||
|
/// contents (spawn-if-needed + didOpen/didChange).
|
||||||
|
async fn touch(&self, path: &Path);
|
||||||
|
|
||||||
|
/// Diagnostics for `path`, waiting up to `wait` for the server to (re)publish after a
|
||||||
|
/// change. Returns whatever is known on timeout.
|
||||||
|
async fn diagnostics(&self, path: &Path, wait: Duration) -> Vec<Diagnostic>;
|
||||||
|
}
|
||||||
@@ -195,6 +195,9 @@ pub struct ToolCtx {
|
|||||||
pub spawner: Option<Arc<dyn SubagentSpawner>>,
|
pub spawner: Option<Arc<dyn SubagentSpawner>>,
|
||||||
/// Present in subagent sessions: lets the read tool report files to the job board.
|
/// Present in subagent sessions: lets the read tool report files to the job board.
|
||||||
pub context_reporter: Option<Arc<dyn ContextReporter>>,
|
pub context_reporter: Option<Arc<dyn ContextReporter>>,
|
||||||
|
/// Language-server diagnostics source (edit/write surface errors after a change). `None`
|
||||||
|
/// disables LSP integration.
|
||||||
|
pub diagnostics: Option<Arc<dyn crate::lsp::DiagnosticsSource>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
|
|||||||
@@ -6,6 +6,13 @@ license.workspace = true
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
harness-core = { workspace = true }
|
harness-core = { workspace = true }
|
||||||
|
tokio = { workspace = true }
|
||||||
|
async-trait = { workspace = true }
|
||||||
|
serde_json = { workspace = true }
|
||||||
|
tracing = { workspace = true }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tempfile = { workspace = true }
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
workspace = true
|
||||||
|
|||||||
@@ -0,0 +1,325 @@
|
|||||||
|
//! Minimal JSON-RPC client over an LSP server's child stdio: `Content-Length` framing, a
|
||||||
|
//! request-id → oneshot map, and a diagnostics store keyed by document URI. Only the handful
|
||||||
|
//! of methods the edit/write flow needs are implemented (docs/09-integrations.md).
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::atomic::{AtomicI64, Ordering};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use harness_core::lsp::{Diagnostic, Severity};
|
||||||
|
use serde_json::{json, Value};
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncWriteExt, BufReader};
|
||||||
|
use tokio::process::{Child, Command};
|
||||||
|
use tokio::sync::{oneshot, Notify};
|
||||||
|
|
||||||
|
type Pending = Arc<Mutex<HashMap<i64, oneshot::Sender<Value>>>>;
|
||||||
|
type DiagStore = Arc<Mutex<HashMap<String, Vec<Diagnostic>>>>;
|
||||||
|
|
||||||
|
/// A running language server plus the state needed to talk to it.
|
||||||
|
pub struct LspClient {
|
||||||
|
outgoing: tokio::sync::mpsc::UnboundedSender<String>,
|
||||||
|
next_id: AtomicI64,
|
||||||
|
pending: Pending,
|
||||||
|
diagnostics: DiagStore,
|
||||||
|
diag_notify: Arc<Notify>,
|
||||||
|
// Kept alive so the child is killed on drop (`kill_on_drop`).
|
||||||
|
_child: Child,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LspClient {
|
||||||
|
/// Spawns `command args`, performs the `initialize`/`initialized` handshake rooted at
|
||||||
|
/// `root`, and returns a ready client.
|
||||||
|
pub async fn spawn(command: &str, args: &[String], root: &Path) -> std::io::Result<Self> {
|
||||||
|
let mut child = Command::new(command)
|
||||||
|
.args(args)
|
||||||
|
.current_dir(root)
|
||||||
|
.stdin(std::process::Stdio::piped())
|
||||||
|
.stdout(std::process::Stdio::piped())
|
||||||
|
.stderr(std::process::Stdio::null())
|
||||||
|
.kill_on_drop(true)
|
||||||
|
.spawn()?;
|
||||||
|
|
||||||
|
let stdin = child.stdin.take().expect("piped stdin");
|
||||||
|
let stdout = child.stdout.take().expect("piped stdout");
|
||||||
|
|
||||||
|
let (outgoing, mut out_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
|
||||||
|
let pending: Pending = Arc::default();
|
||||||
|
let diagnostics: DiagStore = Arc::default();
|
||||||
|
let diag_notify = Arc::new(Notify::new());
|
||||||
|
|
||||||
|
// Writer task: frame and forward outgoing payloads.
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let mut stdin = stdin;
|
||||||
|
while let Some(payload) = out_rx.recv().await {
|
||||||
|
let frame = format!("Content-Length: {}\r\n\r\n{}", payload.len(), payload);
|
||||||
|
if stdin.write_all(frame.as_bytes()).await.is_err() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let _ = stdin.flush().await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Reader task: parse frames, route responses, collect diagnostics, ack server requests.
|
||||||
|
{
|
||||||
|
let pending = pending.clone();
|
||||||
|
let diagnostics = diagnostics.clone();
|
||||||
|
let diag_notify = diag_notify.clone();
|
||||||
|
let outgoing_ack = outgoing.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let mut reader = BufReader::new(stdout);
|
||||||
|
while let Some(msg) = read_message(&mut reader).await {
|
||||||
|
dispatch(msg, &pending, &diagnostics, &diag_notify, &outgoing_ack);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let client = Self {
|
||||||
|
outgoing,
|
||||||
|
next_id: AtomicI64::new(1),
|
||||||
|
pending,
|
||||||
|
diagnostics,
|
||||||
|
diag_notify,
|
||||||
|
_child: child,
|
||||||
|
};
|
||||||
|
|
||||||
|
client.initialize(root).await?;
|
||||||
|
Ok(client)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn initialize(&self, root: &Path) -> std::io::Result<()> {
|
||||||
|
let root_uri = path_to_uri(root);
|
||||||
|
let params = json!({
|
||||||
|
"processId": std::process::id(),
|
||||||
|
"rootUri": root_uri,
|
||||||
|
"workspaceFolders": [{ "uri": root_uri, "name": "root" }],
|
||||||
|
"capabilities": {
|
||||||
|
"textDocument": {
|
||||||
|
"publishDiagnostics": { "relatedInformation": false }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"clientInfo": { "name": "ai-harness" }
|
||||||
|
});
|
||||||
|
// A slow server (rust-analyzer indexing) can take a while to answer initialize.
|
||||||
|
let _ = self
|
||||||
|
.request("initialize", params, Duration::from_secs(30))
|
||||||
|
.await;
|
||||||
|
self.notify("initialized", json!({}));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send(&self, payload: Value) {
|
||||||
|
if let Ok(text) = serde_json::to_string(&payload) {
|
||||||
|
let _ = self.outgoing.send(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn notify(&self, method: &str, params: Value) {
|
||||||
|
self.send(json!({ "jsonrpc": "2.0", "method": method, "params": params }));
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn request(&self, method: &str, params: Value, timeout: Duration) -> Option<Value> {
|
||||||
|
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
self.pending.lock().unwrap().insert(id, tx);
|
||||||
|
self.send(json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }));
|
||||||
|
match tokio::time::timeout(timeout, rx).await {
|
||||||
|
Ok(Ok(value)) => Some(value),
|
||||||
|
_ => {
|
||||||
|
self.pending.lock().unwrap().remove(&id);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn did_open(&self, path: &Path, language_id: &str, version: i32, text: &str) {
|
||||||
|
self.notify(
|
||||||
|
"textDocument/didOpen",
|
||||||
|
json!({
|
||||||
|
"textDocument": {
|
||||||
|
"uri": path_to_uri(path),
|
||||||
|
"languageId": language_id,
|
||||||
|
"version": version,
|
||||||
|
"text": text,
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn did_change(&self, path: &Path, version: i32, text: &str) {
|
||||||
|
self.notify(
|
||||||
|
"textDocument/didChange",
|
||||||
|
json!({
|
||||||
|
"textDocument": { "uri": path_to_uri(path), "version": version },
|
||||||
|
"contentChanges": [{ "text": text }],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Clears the stored diagnostics for `path` so the next `wait_diagnostics` observes a fresh
|
||||||
|
/// publish rather than a stale one.
|
||||||
|
pub fn clear(&self, path: &Path) {
|
||||||
|
self.diagnostics.lock().unwrap().remove(&path_to_uri(path));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Waits up to `wait` for the server to publish diagnostics for `path`, returning whatever
|
||||||
|
/// is stored on timeout (possibly empty).
|
||||||
|
pub async fn wait_diagnostics(&self, path: &Path, wait: Duration) -> Vec<Diagnostic> {
|
||||||
|
let uri = path_to_uri(path);
|
||||||
|
let deadline = tokio::time::Instant::now() + wait;
|
||||||
|
loop {
|
||||||
|
if let Some(diags) = self.diagnostics.lock().unwrap().get(&uri) {
|
||||||
|
return diags.clone();
|
||||||
|
}
|
||||||
|
let notified = self.diag_notify.notified();
|
||||||
|
let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
|
||||||
|
if remaining.is_zero() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if tokio::time::timeout(remaining, notified).await.is_err() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.diagnostics
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.get(&uri)
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dispatch(
|
||||||
|
msg: Value,
|
||||||
|
pending: &Pending,
|
||||||
|
diagnostics: &DiagStore,
|
||||||
|
diag_notify: &Arc<Notify>,
|
||||||
|
outgoing: &tokio::sync::mpsc::UnboundedSender<String>,
|
||||||
|
) {
|
||||||
|
let method = msg.get("method").and_then(|m| m.as_str());
|
||||||
|
let id = msg.get("id");
|
||||||
|
|
||||||
|
match (method, id) {
|
||||||
|
// Server → client request: ack with a null result so the server can proceed
|
||||||
|
// (e.g. client/registerCapability, window/workDoneProgress/create).
|
||||||
|
(Some(_), Some(id)) => {
|
||||||
|
let reply = json!({ "jsonrpc": "2.0", "id": id, "result": Value::Null });
|
||||||
|
if let Ok(text) = serde_json::to_string(&reply) {
|
||||||
|
let _ = outgoing.send(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Notification from the server.
|
||||||
|
(Some("textDocument/publishDiagnostics"), None) => {
|
||||||
|
if let Some(params) = msg.get("params") {
|
||||||
|
if let Some((uri, diags)) = parse_diagnostics(params) {
|
||||||
|
diagnostics.lock().unwrap().insert(uri, diags);
|
||||||
|
diag_notify.notify_waiters();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(Some(_), None) => {}
|
||||||
|
// Response to one of our requests.
|
||||||
|
(None, Some(id)) => {
|
||||||
|
if let Some(id) = id.as_i64() {
|
||||||
|
if let Some(tx) = pending.lock().unwrap().remove(&id) {
|
||||||
|
let result = msg.get("result").cloned().unwrap_or(Value::Null);
|
||||||
|
let _ = tx.send(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(None, None) => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_diagnostics(params: &Value) -> Option<(String, Vec<Diagnostic>)> {
|
||||||
|
let uri = params.get("uri")?.as_str()?.to_string();
|
||||||
|
let items = params.get("diagnostics")?.as_array()?;
|
||||||
|
let diags = items
|
||||||
|
.iter()
|
||||||
|
.filter_map(|d| {
|
||||||
|
let start = d.get("range")?.get("start")?;
|
||||||
|
Some(Diagnostic {
|
||||||
|
line: start.get("line")?.as_u64().unwrap_or(0) as u32 + 1,
|
||||||
|
character: start.get("character")?.as_u64().unwrap_or(0) as u32 + 1,
|
||||||
|
severity: match d.get("severity").and_then(|s| s.as_u64()) {
|
||||||
|
Some(1) => Severity::Error,
|
||||||
|
Some(2) => Severity::Warning,
|
||||||
|
Some(3) => Severity::Info,
|
||||||
|
_ => Severity::Hint,
|
||||||
|
},
|
||||||
|
message: d.get("message")?.as_str().unwrap_or("").to_string(),
|
||||||
|
source: d
|
||||||
|
.get("source")
|
||||||
|
.and_then(|s| s.as_str())
|
||||||
|
.map(|s| s.to_string()),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Some((uri, diags))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads one `Content-Length`-framed JSON-RPC message, or `None` at EOF.
|
||||||
|
async fn read_message<R: tokio::io::AsyncBufRead + Unpin>(reader: &mut R) -> Option<Value> {
|
||||||
|
use tokio::io::AsyncBufReadExt;
|
||||||
|
let mut content_length: Option<usize> = None;
|
||||||
|
loop {
|
||||||
|
let mut line = String::new();
|
||||||
|
let n = reader.read_line(&mut line).await.ok()?;
|
||||||
|
if n == 0 {
|
||||||
|
return None; // EOF
|
||||||
|
}
|
||||||
|
let trimmed = line.trim_end();
|
||||||
|
if trimmed.is_empty() {
|
||||||
|
break; // end of headers
|
||||||
|
}
|
||||||
|
if let Some(value) = trimmed.strip_prefix("Content-Length:") {
|
||||||
|
content_length = value.trim().parse().ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let len = content_length?;
|
||||||
|
let mut buf = vec![0u8; len];
|
||||||
|
reader.read_exact(&mut buf).await.ok()?;
|
||||||
|
serde_json::from_slice(&buf).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `file://` URI for an absolute path (best-effort; assumes UTF-8, no percent-encoding needed
|
||||||
|
/// for the local paths we handle).
|
||||||
|
fn path_to_uri(path: &Path) -> String {
|
||||||
|
let s = path.to_string_lossy();
|
||||||
|
if s.starts_with('/') {
|
||||||
|
format!("file://{s}")
|
||||||
|
} else {
|
||||||
|
format!("file:///{s}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parses_publish_diagnostics_into_one_based_positions() {
|
||||||
|
let params = json!({
|
||||||
|
"uri": "file:///tmp/a.rs",
|
||||||
|
"diagnostics": [{
|
||||||
|
"range": {"start": {"line": 4, "character": 8}, "end": {"line": 4, "character": 12}},
|
||||||
|
"severity": 1,
|
||||||
|
"message": "cannot find value `x`",
|
||||||
|
"source": "rustc"
|
||||||
|
}]
|
||||||
|
});
|
||||||
|
let (uri, diags) = parse_diagnostics(¶ms).unwrap();
|
||||||
|
assert_eq!(uri, "file:///tmp/a.rs");
|
||||||
|
assert_eq!(diags.len(), 1);
|
||||||
|
assert_eq!(diags[0].line, 5); // 0-based 4 → 1-based 5
|
||||||
|
assert_eq!(diags[0].character, 9);
|
||||||
|
assert_eq!(diags[0].severity, Severity::Error);
|
||||||
|
assert_eq!(diags[0].source.as_deref(), Some("rustc"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn path_to_uri_prefixes_file_scheme() {
|
||||||
|
assert_eq!(path_to_uri(Path::new("/tmp/a.rs")), "file:///tmp/a.rs");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1 +1,241 @@
|
|||||||
// LSP client pool + diagnostics service land here in M5.
|
//! LSP diagnostics pool: maps a file extension to a language server, lazily spawns one server
|
||||||
|
//! per language, and answers the core `DiagnosticsSource` seam. Built-in servers are only
|
||||||
|
//! offered when their binary is on `PATH`; config can add or override them.
|
||||||
|
//! See `docs/09-integrations.md`.
|
||||||
|
|
||||||
|
mod client;
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use harness_core::lsp::{Diagnostic, DiagnosticsSource};
|
||||||
|
|
||||||
|
use client::LspClient;
|
||||||
|
|
||||||
|
/// One language server: which binary to run and which extensions it handles.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ServerConfig {
|
||||||
|
pub name: String,
|
||||||
|
pub command: String,
|
||||||
|
pub args: Vec<String>,
|
||||||
|
pub extensions: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Built-in servers, tried only when their binary exists on `PATH`.
|
||||||
|
fn builtin_servers() -> Vec<ServerConfig> {
|
||||||
|
vec![
|
||||||
|
ServerConfig {
|
||||||
|
name: "rust".into(),
|
||||||
|
command: "rust-analyzer".into(),
|
||||||
|
args: vec![],
|
||||||
|
extensions: vec!["rs".into()],
|
||||||
|
},
|
||||||
|
ServerConfig {
|
||||||
|
name: "typescript".into(),
|
||||||
|
command: "typescript-language-server".into(),
|
||||||
|
args: vec!["--stdio".into()],
|
||||||
|
extensions: vec!["ts".into(), "tsx".into(), "js".into(), "jsx".into()],
|
||||||
|
},
|
||||||
|
ServerConfig {
|
||||||
|
name: "go".into(),
|
||||||
|
command: "gopls".into(),
|
||||||
|
args: vec![],
|
||||||
|
extensions: vec!["go".into()],
|
||||||
|
},
|
||||||
|
ServerConfig {
|
||||||
|
name: "python".into(),
|
||||||
|
command: "pyright-langserver".into(),
|
||||||
|
args: vec!["--stdio".into()],
|
||||||
|
extensions: vec!["py".into()],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// LSP `languageId` for a file extension (falls back to the extension itself).
|
||||||
|
fn language_id_for_ext(ext: &str) -> &str {
|
||||||
|
match ext {
|
||||||
|
"rs" => "rust",
|
||||||
|
"ts" => "typescript",
|
||||||
|
"tsx" => "typescriptreact",
|
||||||
|
"js" => "javascript",
|
||||||
|
"jsx" => "javascriptreact",
|
||||||
|
"go" => "go",
|
||||||
|
"py" => "python",
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns true if `command` is an absolute existing file or resolvable on `PATH`.
|
||||||
|
fn binary_exists(command: &str) -> bool {
|
||||||
|
let p = Path::new(command);
|
||||||
|
if p.is_absolute() {
|
||||||
|
return p.is_file();
|
||||||
|
}
|
||||||
|
let Some(paths) = std::env::var_os("PATH") else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
std::env::split_paths(&paths).any(|dir| dir.join(command).is_file())
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Slot {
|
||||||
|
Ready(Arc<LspClient>),
|
||||||
|
Failed,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct LspPool {
|
||||||
|
root: PathBuf,
|
||||||
|
servers: Vec<ServerConfig>,
|
||||||
|
/// One slot per server name; absent until first spawn attempt.
|
||||||
|
clients: tokio::sync::Mutex<HashMap<String, Slot>>,
|
||||||
|
/// Open documents → last-sent version, so `didChange` bumps monotonically.
|
||||||
|
open: Mutex<HashMap<PathBuf, i32>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LspPool {
|
||||||
|
/// Builds a pool: available built-ins plus any `config` servers (which override built-ins
|
||||||
|
/// by name; an empty command disables a built-in).
|
||||||
|
pub fn new(root: PathBuf, config: Vec<ServerConfig>) -> Self {
|
||||||
|
let mut by_name: HashMap<String, ServerConfig> = HashMap::new();
|
||||||
|
for server in builtin_servers() {
|
||||||
|
if binary_exists(&server.command) {
|
||||||
|
by_name.insert(server.name.clone(), server);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for server in config {
|
||||||
|
if server.command.is_empty() {
|
||||||
|
by_name.remove(&server.name);
|
||||||
|
} else {
|
||||||
|
by_name.insert(server.name.clone(), server);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Self {
|
||||||
|
root,
|
||||||
|
servers: by_name.into_values().collect(),
|
||||||
|
clients: tokio::sync::Mutex::new(HashMap::new()),
|
||||||
|
open: Mutex::new(HashMap::new()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn server_for(&self, path: &Path) -> Option<&ServerConfig> {
|
||||||
|
let ext = path.extension().and_then(|e| e.to_str())?;
|
||||||
|
self.servers
|
||||||
|
.iter()
|
||||||
|
.find(|s| s.extensions.iter().any(|e| e == ext))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gets or lazily spawns the client for `server`. Caches a failure so we don't respawn a
|
||||||
|
/// broken server on every edit.
|
||||||
|
async fn client_for(&self, server: &ServerConfig) -> Option<Arc<LspClient>> {
|
||||||
|
let mut clients = self.clients.lock().await;
|
||||||
|
match clients.get(&server.name) {
|
||||||
|
Some(Slot::Ready(c)) => return Some(c.clone()),
|
||||||
|
Some(Slot::Failed) => return None,
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
match LspClient::spawn(&server.command, &server.args, &self.root).await {
|
||||||
|
Ok(client) => {
|
||||||
|
let client = Arc::new(client);
|
||||||
|
clients.insert(server.name.clone(), Slot::Ready(client.clone()));
|
||||||
|
Some(client)
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(server = %server.name, error = %e, "LSP server failed to start");
|
||||||
|
clients.insert(server.name.clone(), Slot::Failed);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl DiagnosticsSource for LspPool {
|
||||||
|
async fn touch(&self, path: &Path) {
|
||||||
|
let Some(server) = self.server_for(path).cloned() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Ok(text) = tokio::fs::read_to_string(path).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some(client) = self.client_for(&server).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let ext = path
|
||||||
|
.extension()
|
||||||
|
.and_then(|e| e.to_str())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let language_id = language_id_for_ext(ext);
|
||||||
|
|
||||||
|
let existing_version = {
|
||||||
|
let mut open = self.open.lock().unwrap();
|
||||||
|
match open.get_mut(path) {
|
||||||
|
Some(version) => {
|
||||||
|
*version += 1;
|
||||||
|
Some(*version)
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
open.insert(path.to_path_buf(), 1);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Fresh diagnostics only reflect the current contents — drop any stale set first.
|
||||||
|
client.clear(path);
|
||||||
|
match existing_version {
|
||||||
|
None => client.did_open(path, language_id, 1, &text),
|
||||||
|
Some(version) => client.did_change(path, version, &text),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn diagnostics(&self, path: &Path, wait: Duration) -> Vec<Diagnostic> {
|
||||||
|
let Some(server) = self.server_for(path).cloned() else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let Some(client) = self.client_for(&server).await else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
client.wait_diagnostics(path, wait).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn language_ids_map_common_extensions() {
|
||||||
|
assert_eq!(language_id_for_ext("rs"), "rust");
|
||||||
|
assert_eq!(language_id_for_ext("tsx"), "typescriptreact");
|
||||||
|
assert_eq!(language_id_for_ext("unknown"), "unknown");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_server_overrides_builtin_by_name() {
|
||||||
|
let pool = LspPool::new(
|
||||||
|
std::env::temp_dir(),
|
||||||
|
vec![ServerConfig {
|
||||||
|
name: "rust".into(),
|
||||||
|
command: "my-custom-ra".into(),
|
||||||
|
args: vec!["--flag".into()],
|
||||||
|
extensions: vec!["rs".into()],
|
||||||
|
}],
|
||||||
|
);
|
||||||
|
let server = pool.server_for(Path::new("/x/a.rs")).unwrap();
|
||||||
|
assert_eq!(server.command, "my-custom-ra");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_server_for_unknown_extension() {
|
||||||
|
let pool = LspPool::new(std::env::temp_dir(), vec![]);
|
||||||
|
assert!(pool.server_for(Path::new("/x/a.zzz")).is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn binary_exists_finds_a_known_tool() {
|
||||||
|
assert!(binary_exists("sh"));
|
||||||
|
assert!(!binary_exists("definitely-not-a-real-binary-xyz"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
//! End-to-end LSP test against a real `rust-analyzer`. Ignored by default (requires the binary
|
||||||
|
//! on PATH and is slow — RA indexes the project). Run with:
|
||||||
|
//! cargo test -p harness-lsp --test rust_analyzer -- --ignored --nocapture
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use harness_core::lsp::{DiagnosticsSource, Severity};
|
||||||
|
use harness_lsp::LspPool;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
#[ignore = "requires rust-analyzer on PATH; slow"]
|
||||||
|
async fn rust_analyzer_reports_a_type_error() {
|
||||||
|
// Minimal cargo project with a deliberate type error.
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
std::fs::write(
|
||||||
|
dir.path().join("Cargo.toml"),
|
||||||
|
"[package]\nname = \"probe\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
std::fs::create_dir_all(dir.path().join("src")).unwrap();
|
||||||
|
let main_rs = dir.path().join("src/main.rs");
|
||||||
|
std::fs::write(
|
||||||
|
&main_rs,
|
||||||
|
"fn main() {\n let x: i32 = \"not an integer\";\n let _ = x;\n}\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let pool = LspPool::new(dir.path().to_path_buf(), vec![]);
|
||||||
|
pool.touch(&main_rs).await;
|
||||||
|
// Generous wait: rust-analyzer must index the workspace before it reports anything.
|
||||||
|
let diags = pool.diagnostics(&main_rs, Duration::from_secs(60)).await;
|
||||||
|
|
||||||
|
println!("diagnostics: {diags:#?}");
|
||||||
|
assert!(
|
||||||
|
diags.iter().any(|d| d.severity == Severity::Error),
|
||||||
|
"expected at least one error diagnostic, got: {diags:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -6,6 +6,17 @@ license.workspace = true
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
harness-core = { workspace = true }
|
harness-core = { workspace = true }
|
||||||
|
rmcp = { workspace = true, features = ["client", "transport-child-process"] }
|
||||||
|
tokio = { workspace = true }
|
||||||
|
async-trait = { workspace = true }
|
||||||
|
serde = { workspace = true }
|
||||||
|
serde_json = { workspace = true }
|
||||||
|
tracing = { workspace = true }
|
||||||
|
thiserror = { workspace = true }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tokio-util = { workspace = true }
|
||||||
|
tempfile = { workspace = true }
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
workspace = true
|
||||||
|
|||||||
@@ -1 +1,264 @@
|
|||||||
// MCP stdio client → Tool adapters land here in M5.
|
//! MCP stdio client → `Tool` adapters (M5). For each configured server we spawn the child
|
||||||
|
//! over rmcp's `TokioChildProcess` transport, `initialize`, `list_tools`, and wrap every
|
||||||
|
//! remote tool as an [`McpTool`] named `{server}_{tool}`. Servers are gated behind the `mcp`
|
||||||
|
//! permission key. See `docs/09-integrations.md`.
|
||||||
|
//!
|
||||||
|
//! Out of scope for v1 (matching the doc): resources, prompts, sampling, and non-stdio
|
||||||
|
//! transports.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use harness_core::tool::{Tool, ToolCtx, ToolError, ToolOutput};
|
||||||
|
use rmcp::model::{CallToolRequestParam, RawContent};
|
||||||
|
use rmcp::service::RunningService;
|
||||||
|
use rmcp::transport::TokioChildProcess;
|
||||||
|
use rmcp::{RoleClient, ServiceExt};
|
||||||
|
use tokio::process::Command;
|
||||||
|
|
||||||
|
/// Sanitized-name cap so a `{server}_{tool}` name stays a legal tool identifier.
|
||||||
|
const MAX_NAME_LEN: usize = 64;
|
||||||
|
|
||||||
|
/// One configured MCP server: the child command plus its environment.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ServerConfig {
|
||||||
|
pub command: String,
|
||||||
|
pub args: Vec<String>,
|
||||||
|
pub env: HashMap<String, String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
enum ConnectError {
|
||||||
|
#[error("spawn/transport failed: {0}")]
|
||||||
|
Transport(#[from] std::io::Error),
|
||||||
|
#[error("MCP service error: {0}")]
|
||||||
|
Service(#[from] rmcp::service::ServiceError),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Connects every configured server and returns ready tool adapters. A server that fails to
|
||||||
|
/// start (or list its tools) is logged and skipped — the rest are unaffected, and the session
|
||||||
|
/// still runs with whatever connected. `named_servers` is `{server_name: config}`.
|
||||||
|
pub async fn connect_all(named_servers: HashMap<String, ServerConfig>) -> Vec<Arc<dyn Tool>> {
|
||||||
|
let mut tools: Vec<Arc<dyn Tool>> = Vec::new();
|
||||||
|
for (name, config) in named_servers {
|
||||||
|
match connect(&name, &config).await {
|
||||||
|
Ok(mut server_tools) => {
|
||||||
|
tracing::info!(server = %name, count = server_tools.len(), "MCP server connected");
|
||||||
|
tools.append(&mut server_tools);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(server = %name, error = %e, "MCP server failed to start; skipping");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tools
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn connect(name: &str, config: &ServerConfig) -> Result<Vec<Arc<dyn Tool>>, ConnectError> {
|
||||||
|
let mut command = Command::new(&config.command);
|
||||||
|
command.args(&config.args);
|
||||||
|
for (key, value) in &config.env {
|
||||||
|
command.env(key, value);
|
||||||
|
}
|
||||||
|
// rmcp sets stdin/stdout to piped and kill-on-drop; the child dies with the `RunningService`.
|
||||||
|
let transport = TokioChildProcess::new(&mut command)?;
|
||||||
|
let service = Arc::new(().serve(transport).await?);
|
||||||
|
|
||||||
|
let remote_tools = service.peer().list_all_tools().await?;
|
||||||
|
let adapters = remote_tools
|
||||||
|
.into_iter()
|
||||||
|
.map(|tool| {
|
||||||
|
let full_name = qualified_name(name, &tool.name);
|
||||||
|
let parameters = serde_json::Value::Object((*tool.input_schema).clone());
|
||||||
|
Arc::new(McpTool {
|
||||||
|
full_name,
|
||||||
|
remote_name: tool.name.to_string(),
|
||||||
|
description: tool.description.to_string(),
|
||||||
|
parameters,
|
||||||
|
service: service.clone(),
|
||||||
|
}) as Arc<dyn Tool>
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Ok(adapters)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `{server}_{tool}` sanitized to `[a-zA-Z0-9_-]` and capped at [`MAX_NAME_LEN`] chars.
|
||||||
|
fn qualified_name(server: &str, tool: &str) -> String {
|
||||||
|
let mut name: String = format!("{server}_{tool}")
|
||||||
|
.chars()
|
||||||
|
.map(|c| {
|
||||||
|
if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
|
||||||
|
c
|
||||||
|
} else {
|
||||||
|
'_'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
name.truncate(MAX_NAME_LEN);
|
||||||
|
name
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A single remote MCP tool exposed to the engine as a `Tool`. Holds a shared handle to the
|
||||||
|
/// server's `RunningService` (kept alive for the whole session so the child stays up).
|
||||||
|
struct McpTool {
|
||||||
|
/// Engine-facing name: sanitized `{server}_{tool}`; also the permission pattern.
|
||||||
|
full_name: String,
|
||||||
|
/// The server's own tool name, sent back verbatim in `call_tool`.
|
||||||
|
remote_name: String,
|
||||||
|
description: String,
|
||||||
|
parameters: serde_json::Value,
|
||||||
|
service: Arc<RunningService<RoleClient, ()>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Tool for McpTool {
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
&self.full_name
|
||||||
|
}
|
||||||
|
|
||||||
|
fn description(&self) -> &str {
|
||||||
|
&self.description
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parameters(&self) -> serde_json::Value {
|
||||||
|
self.parameters.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
input: serde_json::Value,
|
||||||
|
ctx: ToolCtx,
|
||||||
|
) -> Result<ToolOutput, ToolError> {
|
||||||
|
ctx.ask
|
||||||
|
.ask(
|
||||||
|
"mcp",
|
||||||
|
self.full_name.clone(),
|
||||||
|
self.full_name.clone(),
|
||||||
|
input.clone(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let arguments = match input {
|
||||||
|
serde_json::Value::Object(map) => Some(map),
|
||||||
|
serde_json::Value::Null => None,
|
||||||
|
other => {
|
||||||
|
return Err(ToolError::Invalid(format!(
|
||||||
|
"MCP tool arguments must be a JSON object, got {other}"
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = self
|
||||||
|
.service
|
||||||
|
.peer()
|
||||||
|
.call_tool(CallToolRequestParam {
|
||||||
|
name: self.remote_name.clone().into(),
|
||||||
|
arguments,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| ToolError::Other(e.to_string()))?;
|
||||||
|
|
||||||
|
let mut text = String::new();
|
||||||
|
let mut image_index = 0;
|
||||||
|
for content in &result.content {
|
||||||
|
match &content.raw {
|
||||||
|
RawContent::Text(t) => {
|
||||||
|
if !text.is_empty() {
|
||||||
|
text.push('\n');
|
||||||
|
}
|
||||||
|
text.push_str(&t.text);
|
||||||
|
}
|
||||||
|
RawContent::Image(image) => {
|
||||||
|
let note = save_image(&ctx.data_dir, &self.full_name, image_index, image).await;
|
||||||
|
if !text.is_empty() {
|
||||||
|
text.push('\n');
|
||||||
|
}
|
||||||
|
text.push_str(¬e);
|
||||||
|
image_index += 1;
|
||||||
|
}
|
||||||
|
RawContent::Resource(resource) => {
|
||||||
|
let embedded = resource_text(resource);
|
||||||
|
if !embedded.is_empty() {
|
||||||
|
if !text.is_empty() {
|
||||||
|
text.push('\n');
|
||||||
|
}
|
||||||
|
text.push_str(&embedded);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MCP surfaces tool-level failures as `is_error` with the message in `content`; map
|
||||||
|
// that to a tool error so the model sees it as a failed call rather than a result.
|
||||||
|
if result.is_error.unwrap_or(false) {
|
||||||
|
return Err(ToolError::Other(if text.is_empty() {
|
||||||
|
"MCP tool reported an error".to_string()
|
||||||
|
} else {
|
||||||
|
text
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(ToolOutput::new(self.full_name.clone(), text))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes an image payload to the session data dir and returns a one-line note for the tool
|
||||||
|
/// output. Best-effort: a write failure still yields a note (without a path).
|
||||||
|
async fn save_image(
|
||||||
|
data_dir: &PathBuf,
|
||||||
|
tool_name: &str,
|
||||||
|
index: usize,
|
||||||
|
image: &rmcp::model::RawImageContent,
|
||||||
|
) -> String {
|
||||||
|
let ext = image.mime_type.rsplit('/').next().unwrap_or("bin");
|
||||||
|
let file_name = format!("{tool_name}-image-{index}.{ext}.b64");
|
||||||
|
let path = data_dir.join(&file_name);
|
||||||
|
let saved = tokio::fs::create_dir_all(data_dir).await.is_ok()
|
||||||
|
&& tokio::fs::write(&path, &image.data).await.is_ok();
|
||||||
|
if saved {
|
||||||
|
format!(
|
||||||
|
"[image: {} ({} base64 bytes) saved to {}]",
|
||||||
|
image.mime_type,
|
||||||
|
image.data.len(),
|
||||||
|
path.display()
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
format!(
|
||||||
|
"[image: {} ({} base64 bytes, not saved)]",
|
||||||
|
image.mime_type,
|
||||||
|
image.data.len()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Best-effort text extraction from an embedded resource (text resources only in v1).
|
||||||
|
fn resource_text(resource: &rmcp::model::RawEmbeddedResource) -> String {
|
||||||
|
match &resource.resource {
|
||||||
|
rmcp::model::ResourceContents::TextResourceContents { text, .. } => text.clone(),
|
||||||
|
_ => String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn qualified_name_prefixes_and_sanitizes() {
|
||||||
|
assert_eq!(qualified_name("fs", "read_file"), "fs_read_file");
|
||||||
|
assert_eq!(
|
||||||
|
qualified_name("my.server", "do/thing"),
|
||||||
|
"my_server_do_thing"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn qualified_name_caps_length() {
|
||||||
|
let long_tool = "t".repeat(100);
|
||||||
|
let name = qualified_name("srv", &long_tool);
|
||||||
|
assert_eq!(name.len(), MAX_NAME_LEN);
|
||||||
|
assert!(name.starts_with("srv_t"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,153 @@
|
|||||||
|
//! End-to-end MCP integration test: spawn a real stdio MCP server (a small Python fixture),
|
||||||
|
//! connect through the real rmcp client, and verify a discovered tool is callable and gated
|
||||||
|
//! behind the `mcp` permission key. This is the M5 milestone's ✅ for MCP.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use harness_core::event::{AppEvent, EventBus};
|
||||||
|
use harness_core::permission::{PermissionReply, PermissionService};
|
||||||
|
use harness_core::tool::{MetadataSink, PermissionHandle, ToolCtx, ToolError};
|
||||||
|
use harness_core::types::{MessageId, SessionId};
|
||||||
|
use harness_mcp::{connect_all, ServerConfig};
|
||||||
|
use tokio_util::sync::CancellationToken;
|
||||||
|
|
||||||
|
/// A permission frontend that replies `Once` to every ask and records the `permission`/`pattern`
|
||||||
|
/// of each, so a test can assert the call was actually gated.
|
||||||
|
fn recording_auto_approve(
|
||||||
|
bus: EventBus,
|
||||||
|
service: Arc<PermissionService>,
|
||||||
|
) -> Arc<Mutex<Vec<(String, String)>>> {
|
||||||
|
let asks = Arc::new(Mutex::new(Vec::new()));
|
||||||
|
let asks_task = asks.clone();
|
||||||
|
// Subscribe before spawning: a subscription created inside the task could miss the ask
|
||||||
|
// (tokio broadcast only delivers to receivers that exist at publish time).
|
||||||
|
let mut rx = bus.subscribe();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
while let Ok(event) = rx.recv().await {
|
||||||
|
if let AppEvent::PermissionAsked { request } = event {
|
||||||
|
asks_task
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.push((request.permission.clone(), request.pattern.clone()));
|
||||||
|
service.reply(&request.id, PermissionReply::Once);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
asks
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Harness {
|
||||||
|
ctx_data_dir: std::path::PathBuf,
|
||||||
|
service: Arc<PermissionService>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Harness {
|
||||||
|
fn ctx(&self) -> ToolCtx {
|
||||||
|
let (metadata, _rx) = MetadataSink::channel();
|
||||||
|
ToolCtx {
|
||||||
|
session_id: SessionId::new(),
|
||||||
|
message_id: MessageId::new(),
|
||||||
|
call_id: "call_1".into(),
|
||||||
|
data_dir: self.ctx_data_dir.clone(),
|
||||||
|
cwd: std::env::temp_dir(),
|
||||||
|
cancel: CancellationToken::new(),
|
||||||
|
ask: PermissionHandle::new(
|
||||||
|
self.service.clone(),
|
||||||
|
SessionId::new(),
|
||||||
|
Vec::new(),
|
||||||
|
Arc::new(Mutex::new(Vec::new())),
|
||||||
|
CancellationToken::new(),
|
||||||
|
),
|
||||||
|
metadata,
|
||||||
|
spawner: None,
|
||||||
|
context_reporter: None,
|
||||||
|
diagnostics: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fixture_server() -> HashMap<String, ServerConfig> {
|
||||||
|
let script = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/echo_server.py");
|
||||||
|
HashMap::from([(
|
||||||
|
"fix".to_string(),
|
||||||
|
ServerConfig {
|
||||||
|
command: "python3".to_string(),
|
||||||
|
args: vec![script.to_string()],
|
||||||
|
env: HashMap::new(),
|
||||||
|
},
|
||||||
|
)])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn discovers_and_calls_a_real_mcp_tool_with_permission() {
|
||||||
|
let tools = connect_all(fixture_server()).await;
|
||||||
|
let names: Vec<_> = tools.iter().map(|t| t.name().to_string()).collect();
|
||||||
|
assert!(
|
||||||
|
names.contains(&"fix_echo".to_string()),
|
||||||
|
"expected fix_echo among {names:?}"
|
||||||
|
);
|
||||||
|
assert!(names.contains(&"fix_boom".to_string()));
|
||||||
|
|
||||||
|
let echo = tools.iter().find(|t| t.name() == "fix_echo").unwrap();
|
||||||
|
// Schema passes through untouched from the server.
|
||||||
|
assert_eq!(echo.parameters()["properties"]["text"]["type"], "string");
|
||||||
|
|
||||||
|
let bus = EventBus::new();
|
||||||
|
let service = Arc::new(PermissionService::new(bus.clone()));
|
||||||
|
let asks = recording_auto_approve(bus, service.clone());
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let harness = Harness {
|
||||||
|
ctx_data_dir: dir.path().to_path_buf(),
|
||||||
|
service,
|
||||||
|
};
|
||||||
|
|
||||||
|
let out = echo
|
||||||
|
.execute(serde_json::json!({"text": "hi there"}), harness.ctx())
|
||||||
|
.await
|
||||||
|
.expect("echo call succeeds");
|
||||||
|
assert_eq!(out.output, "hi there");
|
||||||
|
|
||||||
|
// The call was gated on the `mcp` key with the qualified tool name as the pattern.
|
||||||
|
let recorded = asks.lock().unwrap().clone();
|
||||||
|
assert_eq!(recorded, vec![("mcp".to_string(), "fix_echo".to_string())]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn tool_error_result_maps_to_tool_error() {
|
||||||
|
let tools = connect_all(fixture_server()).await;
|
||||||
|
let boom = tools.iter().find(|t| t.name() == "fix_boom").unwrap();
|
||||||
|
|
||||||
|
let bus = EventBus::new();
|
||||||
|
let service = Arc::new(PermissionService::new(bus.clone()));
|
||||||
|
let _asks = recording_auto_approve(bus, service.clone());
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let harness = Harness {
|
||||||
|
ctx_data_dir: dir.path().to_path_buf(),
|
||||||
|
service,
|
||||||
|
};
|
||||||
|
|
||||||
|
let err = boom
|
||||||
|
.execute(serde_json::json!({}), harness.ctx())
|
||||||
|
.await
|
||||||
|
.expect_err("boom reports an error result");
|
||||||
|
match err {
|
||||||
|
ToolError::Other(msg) => assert_eq!(msg, "kaboom"),
|
||||||
|
other => panic!("expected ToolError::Other, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_failed_server_is_skipped_not_fatal() {
|
||||||
|
let servers = HashMap::from([(
|
||||||
|
"broken".to_string(),
|
||||||
|
ServerConfig {
|
||||||
|
command: "definitely-not-a-real-binary-xyz".to_string(),
|
||||||
|
args: vec![],
|
||||||
|
env: HashMap::new(),
|
||||||
|
},
|
||||||
|
)]);
|
||||||
|
// No panic, no tools — the missing server is logged and skipped.
|
||||||
|
let tools = connect_all(servers).await;
|
||||||
|
assert!(tools.is_empty());
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Minimal MCP stdio server fixture for harness-mcp integration tests.
|
||||||
|
|
||||||
|
Speaks newline-delimited JSON-RPC (the framing rmcp's child-process transport uses) and
|
||||||
|
implements just enough of the protocol to be discovered and called: `initialize`,
|
||||||
|
`notifications/initialized`, `tools/list`, and `tools/call`. Exposes one tool, `echo`,
|
||||||
|
which returns its `text` argument, plus `boom`, which returns an error result.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
|
||||||
|
PROTOCOL_VERSION = "2024-11-05"
|
||||||
|
|
||||||
|
TOOLS = [
|
||||||
|
{
|
||||||
|
"name": "echo",
|
||||||
|
"description": "Returns the text it is given.",
|
||||||
|
"inputSchema": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {"text": {"type": "string"}},
|
||||||
|
"required": ["text"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "boom",
|
||||||
|
"description": "Always fails.",
|
||||||
|
"inputSchema": {"type": "object", "properties": {}},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def reply(msg_id, result):
|
||||||
|
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": msg_id, "result": result}) + "\n")
|
||||||
|
sys.stdout.flush()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
# readline() rather than `for line in sys.stdin`: the latter's read-ahead buffer blocks
|
||||||
|
# until it fills, which would stall the JSON-RPC handshake line-by-line.
|
||||||
|
while True:
|
||||||
|
line = sys.stdin.readline()
|
||||||
|
if line == "": # EOF: parent closed stdin
|
||||||
|
break
|
||||||
|
line = line.strip()
|
||||||
|
if not line:
|
||||||
|
continue
|
||||||
|
msg = json.loads(line)
|
||||||
|
method = msg.get("method")
|
||||||
|
msg_id = msg.get("id")
|
||||||
|
|
||||||
|
if method == "initialize":
|
||||||
|
reply(msg_id, {
|
||||||
|
"protocolVersion": PROTOCOL_VERSION,
|
||||||
|
"capabilities": {"tools": {}},
|
||||||
|
"serverInfo": {"name": "echo-fixture", "version": "0.1.0"},
|
||||||
|
})
|
||||||
|
elif method == "notifications/initialized":
|
||||||
|
pass # notification: no response
|
||||||
|
elif method == "tools/list":
|
||||||
|
reply(msg_id, {"tools": TOOLS})
|
||||||
|
elif method == "tools/call":
|
||||||
|
params = msg.get("params") or {}
|
||||||
|
name = params.get("name")
|
||||||
|
args = params.get("arguments") or {}
|
||||||
|
if name == "echo":
|
||||||
|
reply(msg_id, {
|
||||||
|
"content": [{"type": "text", "text": args.get("text", "")}],
|
||||||
|
"isError": False,
|
||||||
|
})
|
||||||
|
elif name == "boom":
|
||||||
|
reply(msg_id, {
|
||||||
|
"content": [{"type": "text", "text": "kaboom"}],
|
||||||
|
"isError": True,
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
reply(msg_id, {
|
||||||
|
"content": [{"type": "text", "text": f"unknown tool {name}"}],
|
||||||
|
"isError": True,
|
||||||
|
})
|
||||||
|
elif msg_id is not None:
|
||||||
|
# Unknown request: empty result keeps the client happy.
|
||||||
|
reply(msg_id, {})
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -151,6 +151,7 @@ mod tests {
|
|||||||
metadata,
|
metadata,
|
||||||
spawner: None,
|
spawner: None,
|
||||||
context_reporter: None,
|
context_reporter: None,
|
||||||
|
diagnostics: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
//! Shared LSP-diagnostics reporting for the edit/write tools. After a file is written we ask
|
||||||
|
//! the (optional) diagnostics source to re-analyze it and append any error-severity items to
|
||||||
|
//! the tool output so the model sees mistakes it just introduced. Best-effort: no source, a
|
||||||
|
//! slow server, or a timeout all just mean "no diagnostics" — never a tool failure.
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use harness_core::lsp::Severity;
|
||||||
|
use harness_core::tool::{ToolCtx, ToolOutput};
|
||||||
|
|
||||||
|
/// docs/09-integrations.md: wait up to 1.5s for the server to (re)publish after the change.
|
||||||
|
const DIAGNOSTICS_WAIT: Duration = Duration::from_millis(1500);
|
||||||
|
|
||||||
|
/// Touches `path` in the language server and appends error-severity diagnostics to `output`
|
||||||
|
/// (both as a human-readable block in the text and the full set in metadata under `diagnostics`).
|
||||||
|
pub async fn append_diagnostics(
|
||||||
|
ctx: &ToolCtx,
|
||||||
|
path: &Path,
|
||||||
|
display_name: &str,
|
||||||
|
output: &mut ToolOutput,
|
||||||
|
) {
|
||||||
|
let Some(source) = &ctx.diagnostics else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
source.touch(path).await;
|
||||||
|
let diagnostics = source.diagnostics(path, DIAGNOSTICS_WAIT).await;
|
||||||
|
if diagnostics.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let errors: Vec<_> = diagnostics
|
||||||
|
.iter()
|
||||||
|
.filter(|d| d.severity == Severity::Error)
|
||||||
|
.collect();
|
||||||
|
if !errors.is_empty() {
|
||||||
|
output
|
||||||
|
.output
|
||||||
|
.push_str("\n\nLSP errors detected in this file, please fix:");
|
||||||
|
for diag in &errors {
|
||||||
|
output.output.push('\n');
|
||||||
|
output.output.push_str(&diag.display_line(display_name));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Full set (all severities) into metadata for the TUI.
|
||||||
|
let items: Vec<serde_json::Value> = diagnostics
|
||||||
|
.iter()
|
||||||
|
.map(|d| {
|
||||||
|
serde_json::json!({
|
||||||
|
"line": d.line,
|
||||||
|
"character": d.character,
|
||||||
|
"severity": severity_str(d.severity),
|
||||||
|
"message": d.message,
|
||||||
|
"source": d.source,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if let serde_json::Value::Object(map) = &mut output.metadata {
|
||||||
|
map.insert("diagnostics".into(), serde_json::Value::Array(items));
|
||||||
|
} else {
|
||||||
|
output.metadata = serde_json::json!({ "diagnostics": items });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn severity_str(severity: Severity) -> &'static str {
|
||||||
|
match severity {
|
||||||
|
Severity::Error => "error",
|
||||||
|
Severity::Warning => "warning",
|
||||||
|
Severity::Info => "info",
|
||||||
|
Severity::Hint => "hint",
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -196,8 +196,9 @@ impl Tool for EditTool {
|
|||||||
.map_err(|e| ToolError::Other(format!("{}: {e}", path.display())))?;
|
.map_err(|e| ToolError::Other(format!("{}: {e}", path.display())))?;
|
||||||
|
|
||||||
let (added, removed) = diff_stats(&content_old, &content_new);
|
let (added, removed) = diff_stats(&content_old, &content_new);
|
||||||
let mut output = ToolOutput::new(pattern, "Edit applied successfully.".to_string());
|
let mut output = ToolOutput::new(pattern.clone(), "Edit applied successfully.".to_string());
|
||||||
output.metadata = serde_json::json!({"diff": diff, "added": added, "removed": removed});
|
output.metadata = serde_json::json!({"diff": diff, "added": added, "removed": removed});
|
||||||
|
crate::diagnostics::append_diagnostics(&ctx, &path, &pattern, &mut output).await;
|
||||||
Ok(output)
|
Ok(output)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -234,6 +235,7 @@ mod tests {
|
|||||||
metadata,
|
metadata,
|
||||||
spawner: None,
|
spawner: None,
|
||||||
context_reporter: None,
|
context_reporter: None,
|
||||||
|
diagnostics: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -132,6 +132,7 @@ mod tests {
|
|||||||
metadata,
|
metadata,
|
||||||
spawner: None,
|
spawner: None,
|
||||||
context_reporter: None,
|
context_reporter: None,
|
||||||
|
diagnostics: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -161,6 +161,7 @@ mod tests {
|
|||||||
metadata,
|
metadata,
|
||||||
spawner: None,
|
spawner: None,
|
||||||
context_reporter: None,
|
context_reporter: None,
|
||||||
|
diagnostics: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
mod bash;
|
mod bash;
|
||||||
|
mod diagnostics;
|
||||||
mod edit;
|
mod edit;
|
||||||
mod glob;
|
mod glob;
|
||||||
mod grep;
|
mod grep;
|
||||||
mod paths;
|
mod paths;
|
||||||
mod read;
|
mod read;
|
||||||
|
mod skill;
|
||||||
mod task;
|
mod task;
|
||||||
mod write;
|
mod write;
|
||||||
|
|
||||||
@@ -12,6 +14,7 @@ pub use edit::EditTool;
|
|||||||
pub use glob::GlobTool;
|
pub use glob::GlobTool;
|
||||||
pub use grep::GrepTool;
|
pub use grep::GrepTool;
|
||||||
pub use read::ReadTool;
|
pub use read::ReadTool;
|
||||||
|
pub use skill::SkillTool;
|
||||||
pub use task::TaskTool;
|
pub use task::TaskTool;
|
||||||
pub use write::WriteTool;
|
pub use write::WriteTool;
|
||||||
|
|
||||||
@@ -35,3 +38,11 @@ pub fn register_builtins(registry: &mut ToolRegistry) {
|
|||||||
pub fn register_task_tool(registry: &mut ToolRegistry) {
|
pub fn register_task_tool(registry: &mut ToolRegistry) {
|
||||||
registry.register(Arc::new(TaskTool));
|
registry.register(Arc::new(TaskTool));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Registers the `skill` tool (M5) over a loaded skill set. No-op when there are no skills,
|
||||||
|
/// so the tool is only advertised when something can be loaded.
|
||||||
|
pub fn register_skill_tool(registry: &mut ToolRegistry, skills: &[harness_core::config::SkillDef]) {
|
||||||
|
if !skills.is_empty() {
|
||||||
|
registry.register(Arc::new(SkillTool::new(skills)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -148,6 +148,7 @@ mod tests {
|
|||||||
metadata,
|
metadata,
|
||||||
spawner: None,
|
spawner: None,
|
||||||
context_reporter: None,
|
context_reporter: None,
|
||||||
|
diagnostics: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,154 @@
|
|||||||
|
//! The `skill` tool (M5): the system prompt advertises each skill's name + description; when
|
||||||
|
//! the model decides a skill is relevant it calls this tool with the skill name to pull the
|
||||||
|
//! full instructions on demand. See `docs/09-integrations.md`.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use harness_core::config::SkillDef;
|
||||||
|
use harness_core::tool::{Tool, ToolCtx, ToolError, ToolOutput};
|
||||||
|
use schemars::JsonSchema;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, JsonSchema)]
|
||||||
|
struct SkillParams {
|
||||||
|
/// The name of the skill to load, as advertised in the system prompt.
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Serves skill bodies by name. Built from the loaded skill set; if there are no skills the
|
||||||
|
/// caller simply doesn't register the tool.
|
||||||
|
pub struct SkillTool {
|
||||||
|
/// name → (description, body).
|
||||||
|
skills: HashMap<String, (String, String)>,
|
||||||
|
/// Sorted names, for a stable "unknown skill" hint.
|
||||||
|
names: Vec<String>,
|
||||||
|
description: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SkillTool {
|
||||||
|
pub fn new(skills: &[SkillDef]) -> Self {
|
||||||
|
let mut names: Vec<String> = skills.iter().map(|s| s.name.clone()).collect();
|
||||||
|
names.sort();
|
||||||
|
let map = skills
|
||||||
|
.iter()
|
||||||
|
.map(|s| (s.name.clone(), (s.description.clone(), s.body.clone())))
|
||||||
|
.collect();
|
||||||
|
let description = format!(
|
||||||
|
"Load the full instructions for a named skill before doing the related work. \
|
||||||
|
Available skills: {}.",
|
||||||
|
names.join(", ")
|
||||||
|
);
|
||||||
|
Self {
|
||||||
|
skills: map,
|
||||||
|
names,
|
||||||
|
description,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Tool for SkillTool {
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
"skill"
|
||||||
|
}
|
||||||
|
|
||||||
|
fn description(&self) -> &str {
|
||||||
|
&self.description
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parameters(&self) -> serde_json::Value {
|
||||||
|
serde_json::to_value(schemars::schema_for!(SkillParams)).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn execute(
|
||||||
|
&self,
|
||||||
|
input: serde_json::Value,
|
||||||
|
_ctx: ToolCtx,
|
||||||
|
) -> Result<ToolOutput, ToolError> {
|
||||||
|
let params: SkillParams =
|
||||||
|
serde_json::from_value(input).map_err(|e| ToolError::Invalid(e.to_string()))?;
|
||||||
|
match self.skills.get(¶ms.name) {
|
||||||
|
Some((_description, body)) => Ok(ToolOutput::new(
|
||||||
|
format!("skill: {}", params.name),
|
||||||
|
body.clone(),
|
||||||
|
)),
|
||||||
|
None => Err(ToolError::Invalid(format!(
|
||||||
|
"unknown skill {:?}; available: {}",
|
||||||
|
params.name,
|
||||||
|
self.names.join(", ")
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use harness_core::event::EventBus;
|
||||||
|
use harness_core::permission::{spawn_auto_approve, PermissionService};
|
||||||
|
use harness_core::tool::{MetadataSink, PermissionHandle};
|
||||||
|
use harness_core::types::SessionId;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use tokio_util::sync::CancellationToken;
|
||||||
|
|
||||||
|
fn ctx() -> ToolCtx {
|
||||||
|
let bus = EventBus::new();
|
||||||
|
let service = Arc::new(PermissionService::new(bus.clone()));
|
||||||
|
spawn_auto_approve(bus, service.clone());
|
||||||
|
let (metadata, _rx) = MetadataSink::channel();
|
||||||
|
ToolCtx {
|
||||||
|
session_id: SessionId::new(),
|
||||||
|
message_id: harness_core::types::MessageId::new(),
|
||||||
|
call_id: "c1".into(),
|
||||||
|
data_dir: std::env::temp_dir(),
|
||||||
|
cwd: std::env::temp_dir(),
|
||||||
|
cancel: CancellationToken::new(),
|
||||||
|
ask: PermissionHandle::new(
|
||||||
|
service,
|
||||||
|
SessionId::new(),
|
||||||
|
Vec::new(),
|
||||||
|
Arc::new(Mutex::new(Vec::new())),
|
||||||
|
CancellationToken::new(),
|
||||||
|
),
|
||||||
|
metadata,
|
||||||
|
spawner: None,
|
||||||
|
context_reporter: None,
|
||||||
|
diagnostics: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sample() -> Vec<SkillDef> {
|
||||||
|
vec![SkillDef {
|
||||||
|
name: "formatter".into(),
|
||||||
|
description: "format code".into(),
|
||||||
|
body: "Run cargo fmt.".into(),
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn returns_skill_body_by_name() {
|
||||||
|
let tool = SkillTool::new(&sample());
|
||||||
|
let out = tool
|
||||||
|
.execute(serde_json::json!({"name": "formatter"}), ctx())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(out.output, "Run cargo fmt.");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn unknown_skill_is_an_input_error() {
|
||||||
|
let tool = SkillTool::new(&sample());
|
||||||
|
let err = tool
|
||||||
|
.execute(serde_json::json!({"name": "nope"}), ctx())
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(err, ToolError::Invalid(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn description_lists_available_skills() {
|
||||||
|
let tool = SkillTool::new(&sample());
|
||||||
|
assert!(tool.description().contains("formatter"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -80,6 +80,7 @@ impl Tool for WriteTool {
|
|||||||
format!("wrote {} bytes", params.content.len()),
|
format!("wrote {} bytes", params.content.len()),
|
||||||
);
|
);
|
||||||
output.metadata = serde_json::json!({"diff": diff, "added": added, "removed": removed});
|
output.metadata = serde_json::json!({"diff": diff, "added": added, "removed": removed});
|
||||||
|
crate::diagnostics::append_diagnostics(&ctx, &path, ¶ms.file_path, &mut output).await;
|
||||||
Ok(output)
|
Ok(output)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -116,6 +117,7 @@ mod tests {
|
|||||||
metadata,
|
metadata,
|
||||||
spawner: None,
|
spawner: None,
|
||||||
context_reporter: None,
|
context_reporter: None,
|
||||||
|
diagnostics: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ pub struct App {
|
|||||||
|
|
||||||
impl App {
|
impl App {
|
||||||
pub async fn new(cwd: PathBuf) -> anyhow::Result<Self> {
|
pub async fn new(cwd: PathBuf) -> anyhow::Result<Self> {
|
||||||
let engine = EngineHandle::init(cwd)?;
|
let engine = EngineHandle::init(cwd).await?;
|
||||||
let bus_rx = engine.bus().subscribe();
|
let bus_rx = engine.bus().subscribe();
|
||||||
|
|
||||||
let config = engine.config();
|
let config = engine.config();
|
||||||
|
|||||||
@@ -9,7 +9,16 @@ use crate::state::{AppState, ModalState};
|
|||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum InputAction {
|
pub enum InputAction {
|
||||||
None,
|
None,
|
||||||
Submit { text: String },
|
Submit {
|
||||||
|
text: String,
|
||||||
|
},
|
||||||
|
/// A user-defined slash command: `name` (no leading `/`), its `args`, and the `raw` input
|
||||||
|
/// to fall back to submitting verbatim if no such command is defined.
|
||||||
|
RunCommand {
|
||||||
|
name: String,
|
||||||
|
args: String,
|
||||||
|
raw: String,
|
||||||
|
},
|
||||||
Abort,
|
Abort,
|
||||||
Quit,
|
Quit,
|
||||||
LoadSessions,
|
LoadSessions,
|
||||||
@@ -176,7 +185,13 @@ fn parse_slash_command(text: &str) -> Option<InputAction> {
|
|||||||
"/sessions" => Some(InputAction::LoadSessions),
|
"/sessions" => Some(InputAction::LoadSessions),
|
||||||
"/jobs" => Some(InputAction::OpenJobs),
|
"/jobs" => Some(InputAction::OpenJobs),
|
||||||
"/quit" => Some(InputAction::Quit),
|
"/quit" => Some(InputAction::Quit),
|
||||||
_ => None,
|
// Any other `/word` is treated as a user-defined command, resolved against the engine's
|
||||||
|
// loaded commands when applied; if none matches, the raw text is submitted as-is.
|
||||||
|
other => Some(InputAction::RunCommand {
|
||||||
|
name: other.trim_start_matches('/').to_string(),
|
||||||
|
args: rest,
|
||||||
|
raw: trimmed.to_string(),
|
||||||
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -190,6 +205,30 @@ pub async fn apply_action(action: InputAction, state: &mut AppState, engine: &En
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
InputAction::RunCommand { name, args, raw } => {
|
||||||
|
let Some(session_id) = state.session_id.clone() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
match engine.command(&name) {
|
||||||
|
Some(cmd) => {
|
||||||
|
let text = cmd.expand(&args);
|
||||||
|
// A command may switch model/agent for this one run only.
|
||||||
|
let model_ref = cmd.model.clone().unwrap_or_else(|| state.model_ref.clone());
|
||||||
|
if let Err(e) = engine
|
||||||
|
.prompt_with(session_id, text, &model_ref, cmd.agent.as_deref())
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
tracing::error!(error = %e, "command prompt failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Unknown command: submit the original text as an ordinary message.
|
||||||
|
None => {
|
||||||
|
if let Err(e) = engine.prompt(session_id, raw, &state.model_ref).await {
|
||||||
|
tracing::error!(error = %e, "prompt failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
InputAction::Abort => {
|
InputAction::Abort => {
|
||||||
if let Some(session_id) = state.session_id.clone() {
|
if let Some(session_id) = state.session_id.clone() {
|
||||||
engine.abort(&session_id);
|
engine.abort(&session_id);
|
||||||
@@ -317,4 +356,33 @@ mod tests {
|
|||||||
assert!(state.dirty, "a keystroke must request a redraw");
|
assert!(state.dirty, "a keystroke must request a redraw");
|
||||||
assert_eq!(state.input.lines().join("\n"), "x");
|
assert_eq!(state.input.lines().join("\n"), "x");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn builtin_slash_commands_still_parse() {
|
||||||
|
assert!(matches!(
|
||||||
|
parse_slash_command("/new"),
|
||||||
|
Some(InputAction::NewSession)
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
parse_slash_command("/model openai/gpt-5"),
|
||||||
|
Some(InputAction::SetModel(m)) if m == "openai/gpt-5"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unknown_slash_becomes_a_run_command() {
|
||||||
|
match parse_slash_command("/deploy prod now") {
|
||||||
|
Some(InputAction::RunCommand { name, args, raw }) => {
|
||||||
|
assert_eq!(name, "deploy");
|
||||||
|
assert_eq!(args, "prod now");
|
||||||
|
assert_eq!(raw, "/deploy prod now");
|
||||||
|
}
|
||||||
|
other => panic!("expected RunCommand, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn non_slash_text_is_not_a_command() {
|
||||||
|
assert!(parse_slash_command("hello world").is_none());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,7 +50,7 @@ async fn run_headless(args: &[String]) -> i32 {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let app = match harness_app::App::init(cwd) {
|
let app = match harness_app::App::init(cwd).await {
|
||||||
Ok(app) => app,
|
Ok(app) => app,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
eprintln!("error: {e}");
|
eprintln!("error: {e}");
|
||||||
|
|||||||
@@ -26,6 +26,9 @@ pub async fn select_session(
|
|||||||
session: Session,
|
session: Session,
|
||||||
) -> Result<(), harness_app::AppError> {
|
) -> Result<(), harness_app::AppError> {
|
||||||
let session_id = session.id.clone();
|
let session_id = session.id.clone();
|
||||||
|
// Repair a session that crashed mid-run before loading it, so the transcript shows the
|
||||||
|
// aborted turn rather than a tool call frozen "running".
|
||||||
|
engine.repair_session(&session_id).await?;
|
||||||
let messages = engine.session_messages(session_id.clone()).await?;
|
let messages = engine.session_messages(session_id.clone()).await?;
|
||||||
let mut all_parts = Vec::new();
|
let mut all_parts = Vec::new();
|
||||||
for message in &messages {
|
for message in &messages {
|
||||||
|
|||||||
Reference in New Issue
Block a user