20 Commits
Author SHA1 Message Date
darman a930537207 WIP 2026-07-09 07:25:14 +02:00
darmanandClaude Opus 4.8 230e828b81 harness-providers + app: dedicated opencode (Zen) provider
OpenAiProvider gains a custom id and a chat-only mode; `OpenAiProvider::opencode`
builds an OpenCode Zen provider (id `opencode`, defaults to Zen's gateway, always
chat-completions so even gpt-*/o* model ids route correctly). Registered from a
`providers.opencode` config block / OPENCODE_API_KEY env, so it coexists with a
real `openai` provider. Models are referenced as `opencode/<model>`.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 06:59:46 +02:00
darmanandClaude Opus 4.8 7738ed55b9 harness-tui + engine: jobs pane, subtask drill-in, reminders (M4)
TUI: Ctrl+J (or /jobs) opens a jobs pane listing the current session's board —
alias, agent, state, objective, files read — populated on load and kept live via
JobUpdated events; Enter drills into a subtask's child session. Snapshot test added.

Engine: optional orchestration reminders (off by default) injected as synthetic,
non-persisted turn-start blocks and, after a file tool runs, an after-file-tool
block on the following turn. Processor reports file-tool usage via StepOutcome.

This completes M4.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 06:46:31 +02:00
darmanandClaude Opus 4.8 54f91b7e4c harness-tools + app: subagent context-file reporting to the job board (M4)
A ContextReporter wired into subagent sessions lets the read tool advertise the
files it reads (≥10 lines) on its job board entry, so a completed specialist
shows what it already looked at. Root sessions report nothing (no parent board).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 06:34:04 +02:00
darmanandClaude Opus 4.8 ecb3267a50 harness-tools + app: task tool, subagent spawner, board wiring (M4)
The `task` tool delegates to a SubagentSpawner (owned by the composition root):
resolves the agent, enforces the depth limit, applies permission intersection,
filters tools per-agent, and runs the child session foreground or background.
Foreground returns the child's final text; background registers on the job board
and detaches under the parent run token. The run loop injects the board into
primary-agent requests and reconciles terminal jobs each step.

Integration tests cover foreground run + alias reuse continuing the same child
session, depth-limit and unknown-agent rejection, and board prompt injection.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 06:29:12 +02:00
darmanandClaude Opus 4.8 8c859d91c9 harness-core: permission intersection + job board (M4)
evaluate_intersected() returns the more restrictive of a parent-effective
and child verdict (deny > ask > allow). JobBoard tracks subagent tasks with
per-agent aliases, reuse/LRU trimming, context-file reporting, reconcile, and
a formatForPrompt injection block; persisted to the `job` table so resume works.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 06:11:45 +02:00
darmanandClaude Opus 4.8 77873ccb69 harness-core: agent registry + bundled markdown agents (M4)
Layered agent definitions (bundled -> global -> project -> config patch),
opencode-compatible markdown frontmatter, generated {{SUBAGENTS}} routing.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 06:05:53 +02:00
darmanandClaude Opus 4.8 fa417a347d harness-providers: Copilot device-flow, token exchange, provider (M3)
Offline-verifiable building blocks for GitHub Copilot; network paths are the
flagged live-verification risk and are covered by pure unit tests only.

- copilot/device_flow.rs: OAuth device flow (RFC 8628). No hardcoded client id —
  ai-harness must register its own GitHub OAuth app and pass it in. Pure
  parse_poll_response (pending/slow_down/success/failed) + slow_down interval bump;
  request_device_code/poll_once/poll_for_token (injected sleep).
- copilot/token.rs: copilot_internal/v2/token exchange with cache + single-flight
  refresh (tokio::Mutex) and direct-Bearer fallback on 401/403/404; needs_refresh
  honors a 120s skew and expires_at==0 = never.
- copilot/provider.rs: CopilotProvider over api.githubcopilot.com, routing each
  model to chat/responses/anthropic codec by its /models supported_endpoints
  (parse_models + codec_for_endpoints); headers (X-GitHub-Api-Version, Openai-Intent,
  x-initiator, Copilot-Vision-Request, anthropic-beta for anthropic models).
- 11 unit tests (device-flow parsing, token refresh math, codec routing, /models
  parsing).

Deferred (needs live API + TUI work): EngineHandle::login device-flow modal,
startup /models fetch, auth.json-backed registry wiring.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 23:55:38 +02:00
darmanandClaude Opus 4.8 9301d387fa harness-providers: models.dev catalog + cost display wiring (M3)
- modelsdev.rs: ModelCatalog parses models.dev api.json → ModelInfo keyed by
  (provider, model); 24h file cache at ~/.cache/ai-harness/models.json with a
  baked assets/models-snapshot.json fallback so cost/limits work offline.
  load_cached_or_baked (no network) + refresh/refresh_default_cache (background).
- App: loads the catalog at init (cached-or-baked, never blocks), warms the cache
  in a background task, and passes the session model's pricing into RunConfig.cost
  so session cost accrues for real.
- TUI: AppState tracks session_cost/session_tokens from Session events; status bar
  shows "<tokens> · $<cost>". Snapshots updated.
- 7 modelsdev tests (parse, defaults, unknown-model, baked snapshot, cache TTL,
  cached-vs-baked load).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 23:51:23 +02:00
darmanandClaude Opus 4.8 2f3dfe2305 harness-core: model pricing + per-step cost accumulation (M3)
- types::ModelCost {input, output, cache_read, cache_write} (USD per 1M tokens)
  with cost_of(usage); reasoning tokens are billed within output by our providers
  so they are not charged separately. ModelInfo gains cost + reasoning/tool_call/
  attachment capability flags (all #[serde(default)] for forward-compat).
- Engine: RunConfig.cost threads pricing into process_step; on_finish now stamps
  the real dollar cost onto the StepFinish part; StepOutcome carries per-step cost.
- run_session accumulates each step's usage and cost onto the session (previously
  never updated) and republishes SessionUpdated — best-effort, store errors logged
  not fatal.
- Store gains a single-session getter (Session cmd + get_session).
- App passes cost: None for now (real rates land with models.dev wiring).
- Tests: ModelCost::cost_of math (+ reasoning exclusion), and the multi-step
  engine test now asserts session usage/cost accumulation.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 23:45:21 +02:00
darmanandClaude Opus 4.8 39d62348d8 harness-providers: auth.json credential storage (M3)
- auth.rs: AuthRecord (OAuth {access, refresh, expires} | Api {key}) with
  is_expired(now, skew) honoring expires==0 = never; AuthStorage keyed by
  provider id over ~/.local/share/ai-harness/auth.json.
- Read-modify-write on every op so concurrent refresh/login don't clobber;
  writes go through a temp-file rename set to 0600 (unix) to avoid truncated
  auth files.
- 6 tempdir tests: missing→empty, set/get/overwrite, multi-provider coexist,
  scoped remove (+ no-op on absent), expiry skew/never, 0600 perms.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 23:37:34 +02:00
darmanandClaude Opus 4.8 e2706a1560 harness-providers: OpenAI chat + responses codecs, provider, registry wiring (M3)
- codec/openai_chat.rs: /chat/completions request builder (flat messages,
  tool_calls, system → leading system message, reasoning_effort) + SSE decoder
  (content/tool_calls-by-index/reasoning_content accumulation, [DONE] sentinel,
  include_usage). Also the fallback codec for OpenAI-compatible endpoints.
- codec/openai_responses.rs: /responses request builder (input items, tool calls
  and results as top-level function_call/function_call_output, instructions,
  reasoning {effort, summary}) + SSE decoder (output_item add/done, output_text
  and reasoning_summary deltas, function_call_arguments, response.completed usage
  with separate reasoning_tokens).
- openai.rs: OpenAiProvider routing gpt-*/o-* → responses, else chat; Bearer auth;
  error classification incl. 400 context_length_exceeded → ContextOverflow.
- Registered in harness-app from config.providers["openai"] (api_key + optional
  base_url), sourced from OPENAI_API_KEY by the existing config loader.
- 21 codec/provider unit tests (decode fixtures + request-builder assertions).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 23:35:49 +02:00
darman 0812f6d94c M2 TUI: EngineHandle, ratatui app, markdown renderer, permission modal, session picker, snapshot tests
harness-app:
- EngineHandle: non-blocking multi-turn API (prompt/abort/permission_reply/
  list_sessions/session_messages/message_parts), persistent SQLite store,
  no auto-approve — TUI handles permission asks via real oneshot path
- App refactored to wrap EngineHandle; headless run -p keeps auto-approve

harness-tui:
- Terminal guard (raw mode, alternate screen, panic hook, Drop restore)
- Event loop: tokio::select! over crossterm events, bus events, 33ms render tick
- AppState with MessageView/PartView (cached Vec<Line> field), ModalState
- pulldown-cmark → ratatui markdown renderer (headings, bold, italic, code
  blocks, lists, blockquotes, links, manual word-wrap)
- Layout: header, chat viewport, input (tui-textarea), status bar
- Permission modal (y/a/n) wired to EngineHandle::permission_reply
- Session picker (Ctrl+S) with resume
- Abort (Esc), Ctrl+C×2 quit, slash commands (/new /model /agent /sessions)
- 7 TestBackend snapshot tests (empty, messages, tool cards, modals)
2026-07-08 23:35:40 +02:00
Erik Simon b6e94c67c7 harness-app + harness-tui: composition root and harness run -p debug command
App::init wires config loading, an in-memory Store, EventBus, PermissionService
with the M1 auto-approve stub frontend, the full built-in ToolRegistry, and a
ProviderRegistry populated with AnthropicProvider when an API key is available
(config or ANTHROPIC_API_KEY). App::run_prompt creates a root session, appends
the prompt as a user message, and drives engine::run_session to completion;
final_text reads back the concatenated text parts of the last message.

harness-tui's `harness` binary gains a `run -p "<prompt>" [-m provider/model]`
subcommand built on this. Manually verified end-to-end against the real
Anthropic API: an empty API key produced a genuine 401 that our SSE error
path correctly classified as ProviderError::Auth and surfaced as a clean
CLI error message (exit 1) -- confirming the full request/header/error-
handling pipeline works against the live service, not just fixtures.

This closes M1 (docs/10-milestones.md): headless core loop + Anthropic
provider, config loading, all six built-in tools, and the debug CLI.
131 tests passing across the workspace, clippy clean, fmt clean.
2026-07-08 17:28:37 +02:00
Erik Simon bbac60d744 harness-providers: Anthropic codec + provider
/v1/messages request builder (cache_control breakpoints on the first 2
system blocks + last 2 messages, tool schema -> input_schema, extended
thinking budget) and an SSE decoder built on eventsource-stream, mapping
content_block_start/delta/stop and message_delta into our normalized
LlmEvent stream (text, thinking+signature, streamed tool-call JSON
accumulated and parsed at content_block_stop, usage merged from
message_start + message_delta). AnthropicProvider wires this to reqwest
with x-api-key/anthropic-version/anthropic-beta headers and classifies
HTTP errors into RateLimited/Auth/Overloaded/Http. ProviderRegistry
resolves "provider/model" strings.

Also tightened processor::process_step's cancellation: the event loop now
selects the stream poll against ctx.cancel instead of only checking at the
top of the loop, so a blocked provider stream is actually interrupted by
abort (matches docs/02-engine.md's cancellation semantics).

127 tests passing, clippy clean.
2026-07-08 17:25:35 +02:00
Erik Simon bfb2dca7de harness-tools: edit tool with opencode's replacer chain, ported verbatim
Direct port of ~/repos/opencode/packages/opencode/src/tool/edit.ts: the
9-stage replacer chain (Simple, LineTrimmed, BlockAnchor, WhitespaceNormalized,
IndentationFlexible, EscapeNormalized, TrimmedBoundary, ContextAware,
MultiOccurrence), Levenshtein-based block-anchor similarity, and the
disproportionate-match guard that hard-stops rather than falling through to
the next candidate. Also ports edit.test.ts's scenarios: new-file creation,
BOM preservation, CRLF handling, replaceAll, directory/not-found/identical
errors, loose block-anchor rejection, and concurrent edits to the same file
serializing through a per-path tokio::Mutex without losing either change.

99 tests passing across the workspace, clippy clean. This lands the last
of the six M1 built-in tools (read/write/edit/bash/glob/grep).
2026-07-08 17:19:43 +02:00
Erik Simon 27ab6de4f5 harness-tools: read, write, bash, glob, grep
Five of the six M1 built-ins (edit's replacer chain is a separate port).
bash uses process_group(0) + SIGKILL-the-group on timeout/cancel; glob/grep
are gitignore-aware via ignore::WalkBuilder and don't ask permission
(read-only); read/write/bash ask through ctx.ask with opencode's coarser
"always" pattern (first word + wildcard for bash, path for edit/read).
Wired tool output through the central 30k-char truncate() in the processor
so every tool gets spill-to-disk behavior for free. 70 tests passing,
clippy clean.
2026-07-08 17:12:48 +02:00
Erik Simon a68ca02894 M1 core: tool trait, permission service, config, Provider trait, engine loop
harness-core now has everything the headless agent loop needs:
- Tool trait/ToolCtx/ToolRegistry + 30k-char head+tail output truncation
- PermissionService: async ask over a oneshot + AppEvent::PermissionAsked,
  Once/Always/Reject replies, an auto-approve stub for tests/headless runs
- Config: JSONC loading, bundled/global/project-chain/env precedence,
  {env:VAR} and {file:path} interpolation
- llm.rs: LlmEvent/LlmRequest/Provider trait, wire message/content types
- engine/: outer loop (run_session), inner stream processor (persists
  parts/messages as events arrive, executes tool calls inline), retry
  policy (retries only the pre-first-event window), doom-loop guard,
  system prompt assembly

Verified end-to-end against a scripted MockProvider: text -> tool call
(read) -> final text, with messages/parts persisted in the right shape,
plus a provider-error-before-any-event case surfacing as Errored (no
partial message left behind). 49 tests passing, clippy clean.
2026-07-08 17:05:37 +02:00
Erik Simon 5662b773b0 Remove GitHub Actions CI 2026-07-08 16:44:34 +02:00
Erik Simon 8b16348b4c M0: scaffold Cargo workspace, core types, event bus, permission engine, storage actor
Seven-crate workspace per docs/01-architecture.md. harness-core gets the
domain types (Session/Message/Part/ToolState), a broadcast EventBus, the
last-match-wins wildcard permission evaluator, and a SQLite storage actor
(dedicated thread + mpsc, JSON-blob rows) with roundtrip tests. All other
crates are compiling stubs. CI runs fmt/clippy -D warnings/test.
2026-07-08 16:28:42 +02:00
23 changed files with 91 additions and 2302 deletions
Generated
+2 -170
View File
@@ -35,15 +35,6 @@ version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
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]]
name = "anyhow"
version = "1.0.103"
@@ -101,18 +92,6 @@ version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
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]]
name = "base64"
version = "0.22.1"
@@ -196,20 +175,6 @@ dependencies = [
"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]]
name = "compact_str"
version = "0.8.2"
@@ -252,12 +217,6 @@ dependencies = [
"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]]
name = "cpufeatures"
version = "0.3.0"
@@ -764,16 +723,7 @@ dependencies = [
name = "harness-mcp"
version = "0.1.0"
dependencies = [
"async-trait",
"harness-core",
"rmcp",
"serde",
"serde_json",
"tempfile",
"thiserror 2.0.18",
"tokio",
"tokio-util",
"tracing",
]
[[package]]
@@ -964,7 +914,7 @@ version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
dependencies = [
"base64 0.22.1",
"base64",
"bytes",
"futures-channel",
"futures-util",
@@ -981,30 +931,6 @@ dependencies = [
"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]]
name = "icu_collections"
version = "2.2.0"
@@ -1372,15 +1298,6 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
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]]
name = "once_cell"
version = "1.21.4"
@@ -1688,7 +1605,7 @@ version = "0.12.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
dependencies = [
"base64 0.22.1",
"base64",
"bytes",
"futures-core",
"futures-util",
@@ -1737,38 +1654,6 @@ dependencies = [
"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]]
name = "rusqlite"
version = "0.32.1"
@@ -2720,65 +2605,12 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
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]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
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]]
name = "windows-sys"
version = "0.48.0"
-2
View File
@@ -12,8 +12,6 @@ harness-mcp = { workspace = true }
harness-lsp = { workspace = true }
tokio = { workspace = true }
tokio-util = { workspace = true }
futures = { workspace = true }
serde_json = { workspace = true }
async-trait = { workspace = true }
dirs = { workspace = true }
thiserror = { workspace = true }
+65 -591
View File
@@ -14,17 +14,13 @@ use async_trait::async_trait;
use harness_core::agent::{AgentDef, AgentRegistry};
use harness_core::config::{self, Config, ConfigError};
use harness_core::engine::jobs::{JobBoard, JobState, LaunchSpec};
use harness_core::engine::{run_session, Compactor, RunConfig, StepContext};
use harness_core::engine::{run_session, RunConfig, StepContext};
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::store::{Store, StoreError};
use harness_core::tool::{
ContextReporter, SpawnError, SpawnOutcome, SpawnRequest, SubagentSpawner, Tool, ToolRegistry,
ContextReporter, SpawnError, SpawnOutcome, SpawnRequest, SubagentSpawner, ToolRegistry,
};
use harness_core::types::{
Message, MessageId, ModelRef, Part, PartBody, PartId, Session, SessionId,
@@ -80,8 +76,58 @@ fn db_path(cwd: &Path) -> PathBuf {
base.join(format!("{}.sqlite", slug))
}
/// Builds the provider registry from config: every provider with an API key is registered.
fn providers_from_config(config: &Config) -> ProviderRegistry {
/// 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>>,
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();
if let Some(key) = config
.providers
@@ -105,8 +151,8 @@ fn providers_from_config(config: &Config) -> ProviderRegistry {
};
providers.register(Arc::new(provider));
}
// OpenCode Zen: OpenAI-compatible chat gateway under its own `opencode` provider id, so it
// coexists with a real `openai` provider. `base_url` defaults to Zen's endpoint.
// OpenCode Zen: OpenAI-compatible chat gateway under its own `opencode` provider id,
// so it coexists with a real `openai` provider. `base_url` defaults to Zen's endpoint.
if let Some(key) = config
.providers
.get("opencode")
@@ -118,109 +164,16 @@ fn providers_from_config(config: &Config) -> ProviderRegistry {
.and_then(|p| p.base_url.clone());
providers.register(Arc::new(OpenAiProvider::opencode(key, base_url)));
}
providers
}
/// 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)
Self::build(cwd, store, config, providers)
}
/// 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.
/// Shared construction over an explicit provider set — the seam tests use to inject a mock.
fn build(
cwd: PathBuf,
store: Store,
config: Config,
providers: ProviderRegistry,
extra_tools: Vec<Arc<dyn Tool>>,
) -> Result<Self, AppError> {
let bus = EventBus::new();
let permissions = Arc::new(PermissionService::new(bus.clone()));
@@ -228,24 +181,6 @@ impl EngineHandle {
let mut tools = ToolRegistry::new();
harness_tools::register_builtins(&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.
let global_agent_dir = dirs::config_dir().map(|d| d.join("ai-harness").join("agent"));
@@ -265,22 +200,6 @@ impl EngineHandle {
// `init` warms the cache in the background for the next launch.
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
@@ -292,9 +211,8 @@ impl EngineHandle {
extensions: c.extensions.clone(),
})
.collect();
let diagnostics: Option<Arc<dyn DiagnosticsSource>> = Some(Arc::new(
harness_lsp::LspPool::new(cwd.clone(), lsp_servers),
));
let diagnostics: Option<Arc<dyn DiagnosticsSource>> =
Some(Arc::new(harness_lsp::LspPool::new(cwd.clone(), lsp_servers)));
let inner = Arc::new(EngineInner {
config,
@@ -306,10 +224,6 @@ impl EngineHandle {
catalog,
agents,
diagnostics,
skills_prompt,
commands,
compactor,
small_model,
cwd,
data_dir,
runs: Mutex::new(HashMap::new()),
@@ -341,11 +255,6 @@ impl EngineHandle {
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> {
let (provider_id, model_id) = model_ref
.split_once('/')
@@ -364,18 +273,6 @@ impl EngineHandle {
session_id: SessionId,
text: String,
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> {
let (provider_id, model_id) = model_ref
.split_once('/')
@@ -394,12 +291,6 @@ 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 user_message = Message::new_user(session_id.clone(), now);
self.inner
@@ -413,9 +304,6 @@ impl EngineHandle {
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 {
id: PartId::new(),
message_id: user_message.id.clone(),
@@ -431,18 +319,14 @@ impl EngineHandle {
.bus
.publish(AppEvent::PartUpdated { part: user_part });
// Resolve the agent: a command's `agent:` override for this run, else the session's
// stored agent (falling back to a generic assistant).
let session_agent = match agent_override {
Some(name) => name.to_string(),
None => self
// Resolve the session's agent from the registry (falls back to a generic assistant).
let session_agent = self
.inner
.store
.session(session_id.clone())
.await?
.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 inject_job_board = self.inner.config.orchestration.job_board && agent.mode.is_primary();
let board = self.inner.board_for(&session_id).await?;
@@ -464,7 +348,6 @@ impl EngineHandle {
job_board: Some(board),
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 {
agent_name: agent.name.clone(),
@@ -477,13 +360,6 @@ impl EngineHandle {
inject_job_board,
reminder_turn_start: self.inner.reminder("turn_start"),
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
@@ -549,13 +425,6 @@ impl EngineHandle {
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.
pub async fn jobs(
&self,
@@ -608,116 +477,6 @@ impl EngineInner {
.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
/// unknown/misconfigured agent still runs rather than failing the session.
fn agent_def(&self, name: &str) -> AgentDef {
@@ -895,7 +654,6 @@ impl EngineInner {
job_board: Some(board),
context_reporter: reporter,
diagnostics: self.diagnostics.clone(),
compactor: self.compactor.clone(),
}
}
}
@@ -916,101 +674,6 @@ 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]
impl SubagentSpawner for EngineInner {
async fn spawn(&self, req: SpawnRequest) -> Result<SpawnOutcome, SpawnError> {
@@ -1109,15 +772,6 @@ impl SubagentSpawner for EngineInner {
inject_job_board: agent.mode.is_primary(),
reminder_turn_start: self.reminder("turn_start"),
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).
@@ -1234,8 +888,8 @@ pub struct App {
impl App {
/// Persistent SQLite-backed store with an auto-approve permission frontend — the default
/// headless configuration used by `harness run -p`.
pub async fn init(cwd: PathBuf) -> Result<Self, AppError> {
let engine = EngineHandle::init(cwd).await?;
pub fn init(cwd: PathBuf) -> Result<Self, AppError> {
let engine = EngineHandle::init(cwd)?;
let _auto_approve_handle = Some(spawn_auto_approve_task(&engine));
Ok(Self {
engine,
@@ -1364,7 +1018,6 @@ mod tests {
Store::open_in_memory().unwrap(),
Config::default(),
providers,
Vec::new(),
)
.unwrap()
}
@@ -1454,7 +1107,6 @@ mod tests {
Store::open_in_memory().unwrap(),
Config::default(),
providers,
Vec::new(),
)
.unwrap();
// Auto-approve permission asks (the child's read tool gates on `read`).
@@ -1632,184 +1284,6 @@ mod tests {
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]
async fn run_prompt_errors_on_unregistered_provider() {
let dir = tempfile::tempdir().unwrap();
-296
View File
@@ -1,296 +0,0 @@
//! 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");
}
}
-2
View File
@@ -1,9 +1,7 @@
pub mod load;
pub mod markdown;
pub mod schema;
pub use load::{load, ConfigError};
pub use markdown::{load_commands, load_skills, skills_prompt, CommandDef, SkillDef};
pub use schema::{
AgentPatch, Config, LspServerConfig, McpServerConfig, OrchestrationConfig, ProviderConfig,
TuiConfig,
-146
View File
@@ -1,146 +0,0 @@
//! 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"));
}
}
+16 -302
View File
@@ -28,11 +28,6 @@ pub struct RunConfig {
pub reminder_turn_start: Option<String>,
/// Optional user-provided reminder injected on the turn after a file tool ran.
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
@@ -160,54 +155,6 @@ 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.
/// `now_fn` supplies `created_at`/`StepContext::now` stamps (kept out of the loop body so
/// tests can drive deterministic timestamps).
@@ -238,14 +185,26 @@ pub async fn run_session(
steps += 1;
ctx.now = now_fn();
let mut wire_messages = match load_wire(&ctx).await {
Ok((_, wire, _)) => wire,
let messages = match ctx.store.messages(ctx.session_id.clone()).await {
Ok(m) => m,
Err(e) => {
return RunOutcome::Errored {
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
// turn: the optional turn-start reminder, the job board, and — if the previous step
@@ -281,7 +240,6 @@ pub async fn run_session(
let system_blocks = system::assemble(
system::env_header(&ctx.cwd),
&run_config.agent_prompt,
run_config.skills_prompt.as_deref(),
&run_config.instructions,
);
let tools: Vec<ToolSchema> = ctx
@@ -351,49 +309,15 @@ 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 {
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::Continue => continue,
StepResult::Stop => return RunOutcome::Stopped,
StepResult::Compact => return RunOutcome::Stopped, // stub until M6
}
}
Err(step_err) if matches!(step_err.source, ProviderError::Cancelled) => {
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) => {
return RunOutcome::Errored {
message: step_err.source.to_string(),
@@ -511,7 +435,6 @@ mod tests {
job_board: None,
context_reporter: None,
diagnostics: None,
compactor: None,
}
}
@@ -596,8 +519,6 @@ mod tests {
inject_job_board: false,
reminder_turn_start: None,
reminder_after_file_tool: None,
skills_prompt: None,
context_limit: 0,
};
let outcome = run_session(Arc::new(provider), ctx, &run_config, || 2).await;
@@ -661,207 +582,6 @@ mod tests {
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]
async fn provider_error_on_first_event_is_reported_and_run_errors() {
let store = Store::open_in_memory().unwrap();
@@ -909,8 +629,6 @@ mod tests {
inject_job_board: false,
reminder_turn_start: None,
reminder_after_file_tool: None,
skills_prompt: None,
context_limit: 0,
};
let outcome = run_session(Arc::new(provider), ctx, &run_config, || 2).await;
@@ -1018,8 +736,6 @@ mod tests {
inject_job_board: true,
reminder_turn_start: None,
reminder_after_file_tool: None,
skills_prompt: None,
context_limit: 0,
};
let provider = std::sync::Arc::new(CapturingProvider {
@@ -1087,8 +803,6 @@ mod tests {
inject_job_board: false,
reminder_turn_start: Some("REMEMBER: stay on task.".into()),
reminder_after_file_tool: None,
skills_prompt: None,
context_limit: 0,
};
let provider = std::sync::Arc::new(CapturingProvider {
-2
View File
@@ -1,4 +1,3 @@
pub mod compact;
pub mod doomloop;
pub mod jobs;
pub mod processor;
@@ -7,7 +6,6 @@ pub mod retry;
pub mod session_loop;
pub mod system;
pub use compact::Compactor;
pub use doomloop::DoomLoopGuard;
pub use jobs::{ContextFile, JobBoard, JobRecord, JobState};
pub use processor::{process_step, StepContext, StepError, StepOutcome, StepResult};
@@ -74,9 +74,6 @@ pub struct StepContext {
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 {
+3 -23
View File
@@ -25,18 +25,10 @@ pub fn env_header(cwd: &Path) -> String {
header
}
/// Ordered system prompt blocks: environment header, agent prompt, the optional skills
/// listing, then project instructions (e.g. AGENTS.md contents). Order matches `02-engine.md`.
pub fn assemble(
env_header: String,
agent_prompt: &str,
skills: Option<&str>,
instructions: &[String],
) -> Vec<String> {
/// Ordered system prompt blocks: environment header, agent prompt, 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> {
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
}
@@ -57,20 +49,8 @@ mod tests {
let blocks = assemble(
"ENV".to_string(),
"AGENT",
None,
&["AGENTS.md contents".to_string()],
);
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"]);
}
}
+1 -4
View File
@@ -162,10 +162,7 @@ impl DiagnosticsSource for LspPool {
let Some(client) = self.client_for(&server).await else {
return;
};
let ext = path
.extension()
.and_then(|e| e.to_str())
.unwrap_or_default();
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or_default();
let language_id = language_id_for_ext(ext);
let existing_version = {
+1 -5
View File
@@ -19,11 +19,7 @@ async fn rust_analyzer_reports_a_type_error() {
.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();
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;
-11
View File
@@ -6,17 +6,6 @@ license.workspace = true
[dependencies]
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]
workspace = true
+1 -264
View File
@@ -1,264 +1 @@
//! 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(&note);
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"));
}
}
// MCP stdio client → Tool adapters land here in M5.
-153
View File
@@ -1,153 +0,0 @@
//! 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());
}
-86
View File
@@ -1,86 +0,0 @@
#!/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()
+1 -6
View File
@@ -14,12 +14,7 @@ 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,
) {
pub async fn append_diagnostics(ctx: &ToolCtx, path: &Path, display_name: &str, output: &mut ToolOutput) {
let Some(source) = &ctx.diagnostics else {
return;
};
-10
View File
@@ -5,7 +5,6 @@ mod glob;
mod grep;
mod paths;
mod read;
mod skill;
mod task;
mod write;
@@ -14,7 +13,6 @@ pub use edit::EditTool;
pub use glob::GlobTool;
pub use grep::GrepTool;
pub use read::ReadTool;
pub use skill::SkillTool;
pub use task::TaskTool;
pub use write::WriteTool;
@@ -38,11 +36,3 @@ pub fn register_builtins(registry: &mut ToolRegistry) {
pub fn register_task_tool(registry: &mut ToolRegistry) {
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)));
}
}
-154
View File
@@ -1,154 +0,0 @@
//! 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(&params.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"));
}
}
+1 -1
View File
@@ -31,7 +31,7 @@ pub struct App {
impl App {
pub async fn new(cwd: PathBuf) -> anyhow::Result<Self> {
let engine = EngineHandle::init(cwd).await?;
let engine = EngineHandle::init(cwd)?;
let bus_rx = engine.bus().subscribe();
let config = engine.config();
+2 -70
View File
@@ -9,16 +9,7 @@ use crate::state::{AppState, ModalState};
#[derive(Debug)]
pub enum InputAction {
None,
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,
},
Submit { text: String },
Abort,
Quit,
LoadSessions,
@@ -185,13 +176,7 @@ fn parse_slash_command(text: &str) -> Option<InputAction> {
"/sessions" => Some(InputAction::LoadSessions),
"/jobs" => Some(InputAction::OpenJobs),
"/quit" => Some(InputAction::Quit),
// 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(),
}),
_ => None,
}
}
@@ -205,30 +190,6 @@ 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 => {
if let Some(session_id) = state.session_id.clone() {
engine.abort(&session_id);
@@ -356,33 +317,4 @@ mod tests {
assert!(state.dirty, "a keystroke must request a redraw");
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());
}
}
+1 -1
View File
@@ -50,7 +50,7 @@ async fn run_headless(args: &[String]) -> i32 {
}
};
let app = match harness_app::App::init(cwd).await {
let app = match harness_app::App::init(cwd) {
Ok(app) => app,
Err(e) => {
eprintln!("error: {e}");
-3
View File
@@ -26,9 +26,6 @@ pub async fn select_session(
session: Session,
) -> Result<(), harness_app::AppError> {
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 mut all_parts = Vec::new();
for message in &messages {