Compare commits

..

No commits in common. "main" and "v0.1.0" have entirely different histories.
main ... v0.1.0

21 changed files with 286 additions and 5814 deletions

1
.gitignore vendored
View file

@ -2,4 +2,3 @@
.superpowers/
**/*.rs.bk
Cargo.lock
PROJECT_CONTEXT.md

View file

@ -1,68 +0,0 @@
stages:
- check
- build
variables:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: "1"
cache:
key:
files:
- Cargo.lock
prefix: cargo
paths:
- target/
fmt:
stage: check
image: rust:latest
script:
- rustup component add rustfmt
- cargo fmt --check
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
clippy:
stage: check
image: rust:latest
before_script:
- rustup component add clippy
script:
- cargo clippy --all-targets -- --deny warnings
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
allow_failure: true
test:
stage: check
image: rust:latest
script:
- cargo test --locked
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
build:
stage: build
image: rust:latest
script:
- cargo build --release --locked
artifacts:
name: "brokecream-linux-x86_64"
paths:
- target/release/brokecrew
expire_in: 30 days
# Only on tags, so routine pushes don't eat the free CI minutes.
release:
stage: build
image: rust:latest
rules:
- if: $CI_COMMIT_TAG
script:
- cargo build --release --locked
artifacts:
name: "brokecrew-$CI_COMMIT_TAG"
paths:
- target/release/brokecrew
expire_in: 90 days

View file

@ -1,6 +1,6 @@
[package]
name = "brokecrew"
version = "0.1.1"
version = "0.1.0"
edition = "2021"
authors = ["oiupoyt <oiupoyt.cat@gmail.com>"]
description = "A Rust-native multi-model AI team CLI with resilient OpenRouter fallback routing"
@ -28,11 +28,7 @@ owo-colors = "4.1"
regex = "1.10"
chrono = { version = "0.4", features = ["serde"] }
dirs = "5.0"
rand = "0.8"
arc-swap = "1.7"
tempfile = "3.12"
ratatui = "0.29"
crossterm = { version = "0.28", features = ["event-stream"] }
[dev-dependencies]
wiremock = "0.6"

View file

@ -1,5 +1,6 @@
# BrokeCrew
# BrokeCrew 🤖⚡
[![CI](https://github.com/oiupoyt/brokecrew/actions/workflows/ci.yml/badge.svg)](https://github.com/oiupoyt/brokecrew/actions)
[![License](https://img.shields.io/badge/license-MIT%20OR%20Apache--2.0-blue.svg)](LICENSE-MIT)
[![Crates.io](https://img.shields.io/crates/v/brokecrew.svg)](https://crates.io/crates/brokecrew)
@ -22,31 +23,24 @@ BrokeCrew makes free-tier models first-class citizens while eliminating their in
---
### Technical Invariants
- **Fail-Fast Cascade Walk**: Free endpoints on OpenRouter frequently return transient `429`, `503`, or drop out of `/v1/models` without warning. Candidate resolution treats failures as cascade triggers rather than fatal aborts, stepping to the next viable candidate model within `<250ms`.
- **Sliding-Window Budgeting**: Token usage and request counts are stored in atomic sliding windows (`VecDeque<DateTime<Utc>>`). Router and classifier calls deduct from the shared account budget to prevent downstream API lockouts.
- **Async Non-Blocking SSE**: Streaming tokens are decoupled from the Ratatui TUI render loop via crossbeam/tokio MPSC channels, ensuring UI frame rates remain at 60 FPS even during erratic remote network jitter.
## Terminal Experience
---
BrokeCrew formats multi-agent discussions like a vibrant team group chat:
## Brokecrew Interactive TUI
```text
$ brokecrew chat --pipeline build-and-review "Write a Rust LRU cache"
Simply run `brokecrew` to enter the rich, full-screen interactive TUI:
[coder] (qwen/qwen-2.5-coder-32b-instruct:free)
Here is a thread-safe, high-performance LRU cache implementation using std::collections::HashMap
and a doubly-linked list with generational indexing...
```bash
brokecrew
[reviewer] (meta-llama/llama-3.3-70b-instruct:free)
Code Review:
1. Concurrency: Eviction edge case when capacity is 0 is unhandled.
2. Memory Safety: Generational indices avoid raw pointers; good choice.
3. Suggestion: Implement std::borrow::Borrow to allow lookup by &str rather than String.
```
- **Live Team View**: Color-coded persona indicators (`● coder`, `● reviewer`, `● architect`), token streaming with markdown & syntax formatting.
- **Quota & Budget Monitor**: Real-time headers displaying rolling minute and 24h limits (`1m: 2/20`, `24h: 14/50`).
- **Interactive Modals**:
- `[Tab]` — Open Persona Selector (switch between intelligent Stage A/B `Auto-Route` and dedicated personas).
- `[Ctrl+P]` — Open Pipeline Selector (execute multi-agent pipelines like `build-and-review`).
- `[PgUp/PgDn]` — Scroll conversation history.
- `[Ctrl+L]` — Clear screen.
- `[Esc]` — Dismiss modal or exit.
- **Non-TUI / Scripting**: Use `brokecrew --cli` or `brokecrew chat "..."` for headless pipelines or script integration.
---
## Quickstart

View file

@ -1,7 +1,7 @@
# BrokeCrew Personas & Pipelines Configuration
default_persona = "general"
router_model = "liquid/lfm-2.5-2.6b:free"
router_model = "meta-llama/llama-3.2-3b-instruct:free"
complexity_threshold = 7
[[persona]]
@ -10,20 +10,25 @@ system_prompt = "You are a precise, terse coding assistant. Output working code
trigger_words = ["build", "code", "script", "function", "website", "api", "rust", "python", "algorithm", "backend", "frontend"]
[[persona.candidates]]
id = "cohere/north-mini-code:free"
id = "qwen/qwen-2.5-coder-32b-instruct:free"
tier = "free"
is_stealth = false
[[persona.candidates]]
id = "qwen/qwen3.8-27b:free"
id = "deepseek/deepseek-coder:free"
tier = "free"
is_stealth = false
[[persona.candidates]]
id = "google/gemma-4-31b-it:free"
id = "meta-llama/llama-3.3-70b-instruct:free"
tier = "free"
is_stealth = false
[[persona.candidates]]
id = "openrouter/auto:free"
tier = "free"
is_stealth = true
[[persona.candidates]]
id = "google/gemini-2.0-flash-001"
tier = "paid"
@ -35,17 +40,12 @@ system_prompt = "You are a meticulous, security-minded code reviewer. Flag bugs,
trigger_words = ["review", "check", "audit", "critique", "inspect", "lint", "vulnerability", "security"]
[[persona.candidates]]
id = "google/gemma-4-31b-it:free"
id = "meta-llama/llama-3.3-70b-instruct:free"
tier = "free"
is_stealth = false
[[persona.candidates]]
id = "nvidia/nemotron-3.5-lightning:free"
tier = "free"
is_stealth = false
[[persona.candidates]]
id = "nvidia/nemotron-3-super-120b-a12b:free"
id = "deepseek/deepseek-chat:free"
tier = "free"
is_stealth = false
@ -60,12 +60,12 @@ system_prompt = "You are a senior principal systems architect. Spec out distribu
trigger_words = ["design", "architecture", "system", "structure", "schema", "scale", "spec", "blueprint"]
[[persona.candidates]]
id = "nvidia/nemotron-3-ultra-550b-a55b:free"
id = "meta-llama/llama-3.3-70b-instruct:free"
tier = "free"
is_stealth = false
[[persona.candidates]]
id = "google/gemma-4-31b-it:free"
id = "deepseek/deepseek-r1:free"
tier = "free"
is_stealth = false
@ -77,20 +77,15 @@ is_stealth = false
[[persona]]
name = "general"
system_prompt = "You are BrokeCrew's general assistant: insightful, direct, and concise."
trigger_words = ["help", "explain", "summarize", "what", "who", "why", "how", "hello", "hi", "hey", "yo", "sup", "greetings"]
trigger_words = ["help", "explain", "summarize", "what", "who", "why", "how", "hello"]
[[persona.candidates]]
id = "liquid/lfm-2.5-2.6b:free"
id = "meta-llama/llama-3.3-70b-instruct:free"
tier = "free"
is_stealth = false
[[persona.candidates]]
id = "google/gemma-4-26b-a4b-it:free"
tier = "free"
is_stealth = false
[[persona.candidates]]
id = "qwen/qwen3.8-27b:free"
id = "qwen/qwen-2.5-72b-instruct:free"
tier = "free"
is_stealth = false

View file

@ -7,14 +7,6 @@ use std::path::{Path, PathBuf};
const MINUTE_LIMIT: usize = 20;
/// Estimates token count from text using standard heuristic (~4 characters per token).
pub fn estimate_tokens(text: &str) -> usize {
if text.is_empty() {
return 0;
}
text.len().div_ceil(4).max(1)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CreditTier {
LowBalance, // < $10 lifetime purchased: 50 requests/day
@ -36,7 +28,6 @@ pub struct BudgetStatus {
pub minute_limit: usize,
pub daily_requests: usize,
pub daily_limit: usize,
pub daily_paid_requests: usize,
pub approaching_daily_limit: bool,
}
@ -51,7 +42,6 @@ pub enum BudgetExceeded {
#[derive(Debug, Serialize, Deserialize, Default)]
struct StoredBudgetState {
daily_count: usize,
daily_paid_count: usize,
last_day_utc: String, // YYYY-MM-DD
recent_calls: VecDeque<DateTime<Utc>>,
}
@ -60,7 +50,6 @@ pub struct BudgetTracker {
storage_path: Option<PathBuf>,
credit_tier: CreditTier,
daily_count: usize,
daily_paid_count: usize,
last_day_utc: String,
recent_calls: VecDeque<DateTime<Utc>>,
}
@ -71,7 +60,6 @@ impl BudgetTracker {
storage_path,
credit_tier,
daily_count: 0,
daily_paid_count: 0,
last_day_utc: Utc::now().format("%Y-%m-%d").to_string(),
recent_calls: VecDeque::new(),
};
@ -95,7 +83,6 @@ impl BudgetTracker {
// Day rollover check
if self.last_day_utc != current_day {
self.daily_count = 0;
self.daily_paid_count = 0;
self.last_day_utc = current_day;
}
@ -137,49 +124,16 @@ impl BudgetTracker {
minute_limit: MINUTE_LIMIT,
daily_requests: self.daily_count,
daily_limit,
daily_paid_requests: self.daily_paid_count,
approaching_daily_limit,
})
}
/// Atomically checks limits and records one call. Replaces the racy
/// check-then-record sequence: a single call either acquires budget or
/// reports exhaustion, never both passing then both recording.
pub fn try_acquire(&mut self, is_paid: bool) -> Result<BudgetStatus, BudgetExceeded> {
// Reuse check_budget for limit evaluation (it refreshes the window).
let _ = self.check_budget()?;
let now = Utc::now();
self.recent_calls.push_back(now);
self.daily_count += 1;
if is_paid {
self.daily_paid_count += 1;
}
if let Some(ref path) = self.storage_path.clone() {
let _ = self.save_to_disk(path);
}
// Status after recording.
let daily_limit = self.credit_tier.daily_limit();
Ok(BudgetStatus {
minute_requests: self.recent_calls.len(),
minute_limit: MINUTE_LIMIT,
daily_requests: self.daily_count,
daily_limit,
daily_paid_requests: self.daily_paid_count,
approaching_daily_limit: self.daily_count >= (daily_limit * 80) / 100,
})
}
/// Records an outbound call and persists updated state to disk atomically.
pub fn record_call(&mut self, is_paid: bool) -> Result<(), std::io::Error> {
pub fn record_call(&mut self, _is_paid: bool) -> Result<(), std::io::Error> {
self.refresh_window();
let now = Utc::now();
self.recent_calls.push_back(now);
self.daily_count += 1;
if is_paid {
self.daily_paid_count += 1;
}
if let Some(ref path) = self.storage_path.clone() {
self.save_to_disk(path)?;
@ -194,7 +148,6 @@ impl BudgetTracker {
let data = fs::read_to_string(path)?;
if let Ok(state) = serde_json::from_str::<StoredBudgetState>(&data) {
self.daily_count = state.daily_count;
self.daily_paid_count = state.daily_paid_count;
self.last_day_utc = state.last_day_utc;
self.recent_calls = state.recent_calls;
}
@ -207,7 +160,6 @@ impl BudgetTracker {
}
let state = StoredBudgetState {
daily_count: self.daily_count,
daily_paid_count: self.daily_paid_count,
last_day_utc: self.last_day_utc.clone(),
recent_calls: self.recent_calls.clone(),
};
@ -285,36 +237,4 @@ mod tests {
assert_eq!(status.daily_requests, 2);
assert_eq!(status.minute_requests, 2);
}
#[test]
fn test_try_acquire_tracks_paid_and_enforces_limits() {
let mut tracker = BudgetTracker::new(None, CreditTier::LowBalance);
let s1 = tracker.try_acquire(false).expect("first acquire");
assert_eq!(s1.daily_requests, 1);
assert_eq!(s1.daily_paid_requests, 0);
let s2 = tracker.try_acquire(true).expect("paid acquire");
assert_eq!(s2.daily_requests, 2);
assert_eq!(s2.daily_paid_requests, 1);
// Fill the minute window through try_acquire: 18 more on top of the
// 2 already recorded. At 20 calls the window is full, so check_budget
// reports the limit (it returns Err at capacity, not Ok(20)).
for _ in 0..18 {
tracker.try_acquire(false).expect("window fill");
}
match tracker.check_budget() {
Err(BudgetExceeded::MinuteLimit(20, _)) => (),
other => panic!("window should be exactly full, got {other:?}"),
}
// The next acquire must fail atomically (no record on failure).
// NOTE: wait-seconds hints differ per call, so match variants only.
match tracker.try_acquire(false) {
Err(BudgetExceeded::MinuteLimit(_, _)) => (),
other => panic!("expected minute limit, got {other:?}"),
}
match tracker.check_budget() {
Err(BudgetExceeded::MinuteLimit(_, _)) => (),
other => panic!("expected still-limited window, got {other:?}"),
}
}
}

View file

@ -33,18 +33,12 @@ pub struct Cli {
#[arg(long, short, global = true, help = "Enable verbose debug logs")]
pub verbose: bool,
#[arg(long, global = true, help = "Force non-TUI line CLI mode")]
pub cli: bool,
#[command(subcommand)]
pub command: Option<Commands>,
}
#[derive(Subcommand, Debug)]
pub enum Commands {
#[command(about = "Launch interactive OpenCode/Pi-style TUI")]
Tui(TuiArgs),
#[command(about = "Chat with a persona or multi-agent pipeline")]
Chat(ChatArgs),
@ -58,15 +52,6 @@ pub enum Commands {
Status,
}
#[derive(Args, Debug, Default)]
pub struct TuiArgs {
#[arg(long, help = "Allow experimental stealth model candidates")]
pub allow_stealth: bool,
#[arg(long, help = "Force escalation to paid model candidates")]
pub escalate: bool,
}
#[derive(Args, Debug, Default)]
pub struct ChatArgs {
#[arg(help = "The message or prompt to send. If omitted, starts interactive chat REPL.")]
@ -98,20 +83,6 @@ pub enum ConfigSubcommand {
#[arg(help = "Optional key directly passed; if omitted, securely prompted")]
key: Option<String>,
},
#[command(about = "Set and persist provider base URL")]
SetUrl {
#[arg(
help = "Provider API base URL (e.g. https://openrouter.ai/api/v1 or http://localhost:11434/v1)"
)]
url: String,
},
#[command(about = "Set and persist Stage B router model")]
SetRouterModel {
#[arg(help = "Model identifier to use for Stage B classification")]
model: String,
},
#[command(about = "Display active configuration and credentials status")]
Show,
}
#[derive(Args, Debug)]

View file

@ -3,7 +3,6 @@ use futures_util::StreamExt;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;
@ -38,17 +37,9 @@ pub trait ModelClient: Send + Sync {
) -> Result<String, ClientError>;
}
/// Immutable snapshot of client credentials. Rebuilt wholesale on
/// /provider or /key change and swapped behind an Arc, so request paths
/// never block on a lock.
#[derive(Debug, Clone)]
struct ClientConfig {
pub struct OpenRouterClient {
api_key: String,
base_url: String,
}
pub struct OpenRouterClient {
config: Arc<arc_swap::ArcSwap<ClientConfig>>,
http: reqwest::Client,
}
@ -56,7 +47,7 @@ impl fmt::Debug for OpenRouterClient {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OpenRouterClient")
.field("api_key", &"[REDACTED]")
.field("base_url", &self.config.load().base_url)
.field("base_url", &self.base_url)
.finish()
}
}
@ -106,38 +97,12 @@ impl OpenRouterClient {
.unwrap_or_else(|_| reqwest::Client::new());
Self {
config: Arc::new(arc_swap::ArcSwap::new(Arc::new(ClientConfig {
api_key,
base_url,
}))),
api_key,
base_url,
http,
}
}
pub fn set_api_key(&self, key: String) {
let current = self.config.load();
self.config.store(Arc::new(ClientConfig {
api_key: key,
base_url: current.base_url.clone(),
}));
}
pub fn set_base_url(&self, url: String) {
let current = self.config.load();
self.config.store(Arc::new(ClientConfig {
api_key: current.api_key.clone(),
base_url: url,
}));
}
pub fn get_api_key(&self) -> String {
self.config.load().api_key.clone()
}
pub fn get_base_url(&self) -> String {
self.config.load().base_url.clone()
}
/// Parses an SSE formatted line into a token delta if available
pub fn parse_sse_line(line: &str) -> Option<String> {
let trimmed = line.trim();
@ -171,30 +136,31 @@ impl OpenRouterClient {
None
}
/// Maps an HTTP response to an optional client error. `None` means success.
/// Returns `Option` instead of `Result` so error paths stay total: there
/// is no `Ok` value to unwrap out from under a future caller.
fn check_status(
status: reqwest::StatusCode,
body: &str,
headers: &reqwest::header::HeaderMap,
) -> Option<ClientError> {
) -> Result<(), ClientError> {
match status.as_u16() {
200..=299 => None,
401 => Some(ClientError::Unauthorized),
402 => Some(ClientError::PaymentRequired),
200..=299 => Ok(()),
401 => Err(ClientError::Unauthorized),
402 => Err(ClientError::PaymentRequired),
429 => {
let retry_after = headers
.get("retry-after")
.and_then(|h| h.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(5);
Some(ClientError::RateLimited(retry_after))
Err(ClientError::RateLimited(retry_after))
}
404 => Some(ClientError::ModelUnavailable(format!(
404 => Err(ClientError::ModelUnavailable(format!(
"Model not found (404): {body}"
))),
s => Some(ClientError::ServerError {
s if s >= 500 => Err(ClientError::ServerError {
status: s,
message: body.to_string(),
}),
s => Err(ClientError::ServerError {
status: s,
message: body.to_string(),
}),
@ -209,9 +175,7 @@ impl OpenRouterClient {
max_tokens: Option<u32>,
temperature: Option<f32>,
) -> Result<String, ClientError> {
let base_url = self.get_base_url();
let api_key = self.get_api_key();
let endpoint = format!("{}/chat/completions", base_url.trim_end_matches('/'));
let endpoint = format!("{}/chat/completions", self.base_url.trim_end_matches('/'));
let body = ChatCompletionRequest {
model,
@ -230,8 +194,9 @@ impl OpenRouterClient {
temperature,
};
let mut auth_val = reqwest::header::HeaderValue::from_str(&format!("Bearer {}", api_key))
.unwrap_or_else(|_| reqwest::header::HeaderValue::from_static(""));
let mut auth_val =
reqwest::header::HeaderValue::from_str(&format!("Bearer {}", self.api_key))
.unwrap_or_else(|_| reqwest::header::HeaderValue::from_static(""));
auth_val.set_sensitive(true);
let res = self
@ -248,10 +213,9 @@ impl OpenRouterClient {
let status = res.status();
let headers = res.headers().clone();
if let Some(err) = Self::check_status(status, "", &headers) {
if !status.is_success() {
let error_text = res.text().await.unwrap_or_default();
// Re-map with the body so 4xx/5xx messages carry server detail.
return Err(Self::check_status(status, &error_text, &headers).unwrap_or(err));
return Err(Self::check_status(status, &error_text, &headers).unwrap_err());
}
let resp_json: ChatCompletionResponse = res.json().await?;
@ -281,9 +245,7 @@ impl ModelClient for OpenRouterClient {
user: &str,
chunk_sender: mpsc::Sender<String>,
) -> Result<String, ClientError> {
let base_url = self.get_base_url();
let api_key = self.get_api_key();
let endpoint = format!("{}/chat/completions", base_url.trim_end_matches('/'));
let endpoint = format!("{}/chat/completions", self.base_url.trim_end_matches('/'));
let body = ChatCompletionRequest {
model,
@ -302,8 +264,9 @@ impl ModelClient for OpenRouterClient {
temperature: None,
};
let mut auth_val = reqwest::header::HeaderValue::from_str(&format!("Bearer {}", api_key))
.unwrap_or_else(|_| reqwest::header::HeaderValue::from_static(""));
let mut auth_val =
reqwest::header::HeaderValue::from_str(&format!("Bearer {}", self.api_key))
.unwrap_or_else(|_| reqwest::header::HeaderValue::from_static(""));
auth_val.set_sensitive(true);
let res = self
@ -320,9 +283,9 @@ impl ModelClient for OpenRouterClient {
let status = res.status();
let headers = res.headers().clone();
if let Some(err) = Self::check_status(status, "", &headers) {
if !status.is_success() {
let error_text = res.text().await.unwrap_or_default();
return Err(Self::check_status(status, &error_text, &headers).unwrap_or(err));
return Err(Self::check_status(status, &error_text, &headers).unwrap_err());
}
let mut stream = res.bytes_stream();
@ -390,11 +353,9 @@ mod tests {
reqwest::header::HeaderValue::from_static("12"),
);
assert!(OpenRouterClient::check_status(reqwest::StatusCode::OK, "", &headers).is_none());
let err_401 =
OpenRouterClient::check_status(reqwest::StatusCode::UNAUTHORIZED, "bad key", &headers)
.expect("401 must map to an error");
.unwrap_err();
match err_401 {
ClientError::Unauthorized => (),
_ => panic!("Expected Unauthorized, got {:?}", err_401),
@ -405,7 +366,7 @@ mod tests {
"low balance",
&headers,
)
.expect("402 must map to an error");
.unwrap_err();
match err_402 {
ClientError::PaymentRequired => (),
_ => panic!("Expected PaymentRequired, got {:?}", err_402),
@ -416,7 +377,7 @@ mod tests {
"rate limited",
&headers,
)
.expect("429 must map to an error");
.unwrap_err();
match err_429 {
ClientError::RateLimited(secs) => assert_eq!(secs, 12),
_ => panic!("Expected RateLimited(12), got {:?}", err_429),
@ -427,7 +388,7 @@ mod tests {
"outage",
&headers,
)
.expect("503 must map to an error");
.unwrap_err();
match err_503 {
ClientError::ServerError { status, .. } => assert_eq!(status, 503),
_ => panic!("Expected ServerError 503, got {:?}", err_503),

View file

@ -9,25 +9,6 @@ const KEYRING_SERVICE: &str = "brokecrew";
const KEYRING_USER: &str = "openrouter_api_key";
const DEFAULT_PERSONAS_TOML: &str = include_str!("../config/personas.example.toml");
fn default_persona_str() -> String {
"general".to_string()
}
fn default_router_model() -> String {
"liquid/lfm-2.5-2.6b:free".to_string()
}
fn default_complexity_threshold() -> u8 {
7
}
fn default_credit_tier() -> CreditTier {
CreditTier::LowBalance
}
fn default_base_url() -> String {
"https://openrouter.ai/api/v1".to_string()
}
fn default_theme_str() -> String {
"opencode".to_string()
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppConfigFile {
#[serde(default = "default_persona_str")]
@ -42,11 +23,25 @@ pub struct AppConfigFile {
pub credit_tier: CreditTier,
#[serde(default = "default_base_url")]
pub openrouter_base_url: String,
#[serde(default = "default_theme_str")]
pub theme: String,
pub api_key: Option<String>,
}
fn default_persona_str() -> String {
"general".to_string()
}
fn default_router_model() -> String {
"meta-llama/llama-3.2-3b-instruct:free".to_string()
}
fn default_complexity_threshold() -> u8 {
7
}
fn default_credit_tier() -> CreditTier {
CreditTier::LowBalance
}
fn default_base_url() -> String {
"https://openrouter.ai/api/v1".to_string()
}
impl Default for AppConfigFile {
fn default() -> Self {
Self {
@ -56,7 +51,6 @@ impl Default for AppConfigFile {
allow_stealth: false,
credit_tier: default_credit_tier(),
openrouter_base_url: default_base_url(),
theme: default_theme_str(),
api_key: None,
}
}
@ -77,7 +71,6 @@ pub struct AppConfig {
pub allow_stealth: bool,
pub credit_tier: CreditTier,
pub openrouter_base_url: String,
pub theme: String,
pub api_key: Option<String>,
pub persona_registry: PersonaRegistry,
pub pipelines: Vec<PipelineConfig>,
@ -138,7 +131,6 @@ impl AppConfig {
allow_stealth: app_file.allow_stealth,
credit_tier: app_file.credit_tier,
openrouter_base_url: app_file.openrouter_base_url,
theme: app_file.theme,
api_key,
persona_registry: PersonaRegistry::new(personas_config.personas),
pipelines: personas_config.pipelines,
@ -146,107 +138,6 @@ impl AppConfig {
})
}
/// Persists the selected theme into `config.toml`
pub fn save_theme(config_dir: &Path, theme: &str) -> Result<(), String> {
let config_file_path = config_dir.join("config.toml");
let mut app_file = if config_file_path.exists() {
let data = fs::read_to_string(&config_file_path)
.map_err(|e| format!("Failed to read {}: {e}", config_file_path.display()))?;
toml::from_str::<AppConfigFile>(&data).unwrap_or_default()
} else {
AppConfigFile::default()
};
app_file.theme = theme.to_string();
let serialized = toml::to_string_pretty(&app_file)
.map_err(|e| format!("Failed to serialize config: {e}"))?;
fs::create_dir_all(config_dir).map_err(|e| format!("Failed to create config dir: {e}"))?;
fs::write(&config_file_path, serialized)
.map_err(|e| format!("Failed to write {}: {e}", config_file_path.display()))?;
Ok(())
}
/// Persists the provider base URL into `config.toml`
pub fn save_openrouter_base_url(config_dir: &Path, base_url: &str) -> Result<(), String> {
let config_file_path = config_dir.join("config.toml");
let mut app_file = if config_file_path.exists() {
let data = fs::read_to_string(&config_file_path)
.map_err(|e| format!("Failed to read {}: {e}", config_file_path.display()))?;
toml::from_str::<AppConfigFile>(&data).unwrap_or_default()
} else {
AppConfigFile::default()
};
app_file.openrouter_base_url = base_url.to_string();
let serialized = toml::to_string_pretty(&app_file)
.map_err(|e| format!("Failed to serialize config: {e}"))?;
fs::create_dir_all(config_dir).map_err(|e| format!("Failed to create config dir: {e}"))?;
fs::write(&config_file_path, serialized)
.map_err(|e| format!("Failed to write {}: {e}", config_file_path.display()))?;
Ok(())
}
/// Persists the selected router model into `config.toml`
pub fn save_router_model(config_dir: &Path, router_model: &str) -> Result<(), String> {
let config_file_path = config_dir.join("config.toml");
let mut app_file = if config_file_path.exists() {
let data = fs::read_to_string(&config_file_path)
.map_err(|e| format!("Failed to read {}: {e}", config_file_path.display()))?;
toml::from_str::<AppConfigFile>(&data).unwrap_or_default()
} else {
AppConfigFile::default()
};
app_file.router_model = router_model.to_string();
let serialized = toml::to_string_pretty(&app_file)
.map_err(|e| format!("Failed to serialize config: {e}"))?;
fs::create_dir_all(config_dir).map_err(|e| format!("Failed to create config dir: {e}"))?;
fs::write(&config_file_path, serialized)
.map_err(|e| format!("Failed to write {}: {e}", config_file_path.display()))?;
Ok(())
}
/// Persists the complexity escalation threshold into `config.toml`
pub fn save_complexity_threshold(config_dir: &Path, threshold: u8) -> Result<(), String> {
let config_file_path = config_dir.join("config.toml");
let mut app_file = if config_file_path.exists() {
let data = fs::read_to_string(&config_file_path)
.map_err(|e| format!("Failed to read {}: {e}", config_file_path.display()))?;
toml::from_str::<AppConfigFile>(&data).unwrap_or_default()
} else {
AppConfigFile::default()
};
app_file.complexity_threshold = threshold.clamp(1, 10);
let serialized = toml::to_string_pretty(&app_file)
.map_err(|e| format!("Failed to serialize config: {e}"))?;
fs::create_dir_all(config_dir).map_err(|e| format!("Failed to create config dir: {e}"))?;
fs::write(&config_file_path, serialized)
.map_err(|e| format!("Failed to write {}: {e}", config_file_path.display()))?;
Ok(())
}
/// Masks an API key for safe display (e.g. `sk-or-v••••••••`)
pub fn mask_api_key(key: &str) -> String {
let trimmed = key.trim();
if trimmed.is_empty() {
return "not configured".to_string();
}
if trimmed.len() <= 8 {
return "••••••••".to_string();
}
let prefix = &trimmed[..trimmed.len().min(7)];
format!("{prefix}••••••••")
}
/// Resolves the API key using precedence:
/// 1. CLI argument
/// 2. `OPENROUTER_API_KEY` environment variable
@ -346,49 +237,4 @@ mod tests {
assert!(parsed.personas.len() >= 3);
assert!(!parsed.pipelines.is_empty());
}
#[test]
fn test_theme_persistence() {
let temp_dir = tempfile::tempdir().unwrap();
AppConfig::save_theme(temp_dir.path(), "dracula").expect("save theme");
let loaded =
AppConfig::load_from_paths(Some(&temp_dir.path().join("config.toml")), None, None)
.expect("load config");
assert_eq!(loaded.theme, "dracula");
}
#[test]
fn test_provider_url_and_router_model_persistence() {
let temp_dir = tempfile::tempdir().unwrap();
AppConfig::save_openrouter_base_url(temp_dir.path(), "http://localhost:11434/v1")
.expect("save base url");
AppConfig::save_router_model(temp_dir.path(), "qwen/qwen-2.5-7b:free")
.expect("save router model");
let loaded =
AppConfig::load_from_paths(Some(&temp_dir.path().join("config.toml")), None, None)
.expect("load config");
assert_eq!(loaded.openrouter_base_url, "http://localhost:11434/v1");
assert_eq!(loaded.router_model, "qwen/qwen-2.5-7b:free");
}
#[test]
fn test_mask_api_key() {
assert_eq!(AppConfig::mask_api_key(""), "not configured");
assert_eq!(AppConfig::mask_api_key("short"), "••••••••");
assert_eq!(
AppConfig::mask_api_key("sk-or-v1-abcdef123456"),
"sk-or-v••••••••"
);
}
#[test]
fn test_complexity_threshold_persistence() {
let temp_dir = tempfile::tempdir().unwrap();
AppConfig::save_complexity_threshold(temp_dir.path(), 9).expect("save threshold");
let loaded =
AppConfig::load_from_paths(Some(&temp_dir.path().join("config.toml")), None, None)
.expect("load config");
assert_eq!(loaded.complexity_threshold, 9);
}
}

View file

@ -7,18 +7,11 @@ pub mod persona;
pub mod pipeline;
pub mod registry;
pub mod router;
pub mod session;
pub mod tool;
pub use budget::{estimate_tokens, BudgetExceeded, BudgetStatus, BudgetTracker, CreditTier};
pub use budget::{BudgetExceeded, BudgetStatus, BudgetTracker, CreditTier};
pub use client::{ClientError, ModelClient, OpenRouterClient};
pub use config::{AppConfig, AppConfigFile, PersonasConfigFile};
pub use persona::{DispatchResult, ModelAttempt, ModelCandidate, Persona, PersonaRegistry, Tier};
pub use pipeline::{
CliRunParams, DispatchParams, PipelineConfig, PipelineEvent, PipelineExecutor, PipelineOutcome,
PipelineRunParams, PipelineStep,
};
pub use pipeline::{PipelineConfig, PipelineEvent, PipelineExecutor, PipelineStep};
pub use registry::{ModelInfo, ModelPricing, ModelRegistry};
pub use router::{KeywordRouter, LlmRouter, RouteDecision, RouteStage, Router};
pub use session::{Session, SessionMessage, SessionSummary};
pub use tool::{ToolEngine, ToolOutput};

View file

@ -1,58 +1,29 @@
mod cli;
mod tui;
use brokecrew::budget::BudgetTracker;
use brokecrew::client::OpenRouterClient;
use brokecrew::config::AppConfig;
use brokecrew::persona::Tier;
use brokecrew::pipeline::{
CliRunParams, DispatchParams, PipelineEvent, PipelineExecutor, PipelineRunParams,
};
use brokecrew::pipeline::{PipelineConfig, PipelineEvent, PipelineExecutor};
use brokecrew::registry::ModelRegistry;
use brokecrew::router::{RouteStage, Router};
use clap::Parser;
use cli::{ChatArgs, Cli, Commands, ConfigSubcommand, PersonasSubcommand};
use indicatif::{ProgressBar, ProgressStyle};
use owo_colors::OwoColorize;
use std::io::{self, BufRead, IsTerminal, Write};
use std::io::{self, BufRead, Write};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
fn init_logging(
json_logs: bool,
verbose: bool,
is_tui: bool,
log_path: Option<std::path::PathBuf>,
) {
fn init_logging(json_logs: bool, verbose: bool) {
let filter = if verbose {
EnvFilter::new("brokecrew=debug,reqwest=debug")
} else {
EnvFilter::new("brokecrew=info")
};
if is_tui {
if let Some(path) = log_path {
if let Ok(file) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)
{
tracing_subscriber::registry()
.with(filter)
.with(tracing_subscriber::fmt::layer().with_writer(file))
.init();
return;
}
}
tracing_subscriber::registry()
.with(filter)
.with(tracing_subscriber::fmt::layer().with_writer(std::io::sink))
.init();
return;
}
if json_logs {
tracing_subscriber::registry()
.with(filter)
@ -97,6 +68,7 @@ fn create_spinner(message: &'static str) -> ProgressBar {
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let cli = Cli::parse();
init_logging(cli.json_logs, cli.verbose);
let config = AppConfig::load_from_paths(
cli.config_file.as_deref(),
@ -105,19 +77,6 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
)
.map_err(|e| format!("Configuration error: {e}"))?;
let is_tui = match cli.command {
Some(Commands::Tui(_)) => true,
None => !cli.cli && io::stdout().is_terminal(),
_ => false,
};
init_logging(
cli.json_logs,
cli.verbose,
is_tui,
Some(config.config_dir.join("brokecrew.log")),
);
let budget_path = config.config_dir.join("budget.json");
let mut budget_tracker = BudgetTracker::new(Some(budget_path), config.credit_tier);
let model_registry = Arc::new(ModelRegistry::new());
@ -146,69 +105,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.map_err(|e| format!("Failed to save API key to OS credential store: {e}"))?;
println!(
"{}",
"✓ OpenRouter API key saved securely in OS credential store."
"✔ OpenRouter API key saved securely in OS credential store."
.bright_green()
.bold()
);
return Ok(());
}
ConfigSubcommand::SetUrl { url } => {
AppConfig::save_openrouter_base_url(&config.config_dir, &url)
.map_err(|e| format!("Failed to save provider base URL: {e}"))?;
println!(
"{}",
format!(
"✓ Provider base URL updated to '{}' and saved to config.toml",
url
)
.bright_green()
.bold()
);
return Ok(());
}
ConfigSubcommand::SetRouterModel { model } => {
AppConfig::save_router_model(&config.config_dir, &model)
.map_err(|e| format!("Failed to save router model: {e}"))?;
println!(
"{}",
format!(
"✓ Stage B router model updated to '{}' and saved to config.toml",
model
)
.bright_green()
.bold()
);
return Ok(());
}
ConfigSubcommand::Show => {
let key_str = config.api_key.as_deref().unwrap_or("");
let masked = AppConfig::mask_api_key(key_str);
println!("\n{}", "BrokeCrew Configuration:".bold().underline());
println!(
" Provider Base URL: {}",
config.openrouter_base_url.bright_cyan()
);
println!(
" Router Model: {}",
config.router_model.bright_white().bold()
);
println!(
" Default Persona: {}",
config.default_persona.bright_yellow()
);
println!(" API Key: {}", masked);
println!(" Stealth Allowed: {}", config.allow_stealth);
println!(" Complexity Threshold: {}", config.complexity_threshold);
println!(" Theme: {}", config.theme.bright_magenta());
println!(
" Config Directory: {}\n",
config.config_dir.display().to_string().dimmed()
);
return Ok(());
}
},
Some(Commands::Personas(personas_args)) => match personas_args.action {
@ -322,7 +224,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
);
println!(" Daily requests today: {}", daily_color);
if status.approaching_daily_limit {
println!(" {}", "! Notice: Approaching daily free-tier limit. Non-urgent calls may be deferred.".yellow().bold());
println!(" {}", "⚠ Notice: Approaching daily free-tier limit. Non-urgent calls may be deferred.".yellow().bold());
}
}
Err(e) => {
@ -333,102 +235,52 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
return Ok(());
}
Some(Commands::Tui(tui_args)) => {
let api_key = ensure_api_key(&config)?;
let mut conf = config;
conf.api_key = Some(api_key);
tui::run_tui(
conf,
budget_tracker,
model_registry,
tui_args.allow_stealth,
tui_args.escalate,
)
.await?;
}
Some(Commands::Chat(args)) => {
run_chat(args, &config, &mut budget_tracker, model_registry).await?;
}
None => {
if !cli.cli && io::stdout().is_terminal() {
let api_key = ensure_api_key(&config)?;
let mut conf = config;
conf.api_key = Some(api_key);
tui::run_tui(conf, budget_tracker, model_registry, false, false).await?;
} else {
run_chat(
ChatArgs::default(),
&config,
&mut budget_tracker,
model_registry,
)
.await?;
}
// Default to chat if no subcommand passed
run_chat(
ChatArgs::default(),
&config,
&mut budget_tracker,
model_registry,
)
.await?;
}
}
Ok(())
}
fn ensure_api_key(config: &AppConfig) -> Result<String, Box<dyn std::error::Error>> {
if let Some(ref k) = config.api_key {
if !k.trim().is_empty() {
return Ok(k.clone());
}
}
if io::stdin().is_terminal() {
eprintln!(
"{}",
":: Welcome to BrokeCrew! No OpenRouter API key found in keyring, env, or config."
.bright_cyan()
.bold()
);
eprint!("Enter OpenRouter API Key: ");
io::stderr().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
let trimmed = input.trim().to_string();
if trimmed.is_empty() {
eprintln!("{}", "Error: API key cannot be empty.".red().bold());
std::process::exit(1);
}
let _ = AppConfig::save_api_key_to_keyring(&trimmed);
eprintln!(
"{}",
"✓ OpenRouter API key saved securely in OS credential store."
.bright_green()
.bold()
);
Ok(trimmed)
} else {
eprintln!(
"{}\nRun: {}\nOr set: {}",
"Error: OpenRouter API key not configured.".red().bold(),
"brokecrew config set-key".bright_green().bold(),
"export OPENROUTER_API_KEY=\"sk-or-v1-...\"".cyan()
);
std::process::exit(1);
}
}
async fn run_chat(
args: ChatArgs,
config: &AppConfig,
budget_tracker: &mut BudgetTracker,
model_registry: Arc<ModelRegistry>,
) -> Result<(), Box<dyn std::error::Error>> {
let api_key = ensure_api_key(config)?;
let api_key = match config.api_key.clone() {
Some(k) if !k.trim().is_empty() => k,
_ => {
eprintln!(
"{}\nRun: {}\nOr set: {}",
"Error: OpenRouter API key not configured.".red().bold(),
"brokecrew config set-key".bright_green().bold(),
"export OPENROUTER_API_KEY=\"sk-or-v1-...\"".cyan()
);
std::process::exit(1);
}
};
let client = OpenRouterClient::with_base_url(api_key, config.openrouter_base_url.clone());
// Start background sync for model registry (immediate + every 30 min).
let _registry_sync = model_registry.start_background_sync(
config.openrouter_base_url.clone(),
std::time::Duration::from_secs(30 * 60),
);
// Start background sync for model registry
let reg_clone = model_registry.clone();
let base_url = config.openrouter_base_url.clone();
tokio::spawn(async move {
let _ = reg_clone.fetch_live(&base_url).await;
});
let router = Router::new(
config.default_persona.clone(),
@ -506,13 +358,13 @@ async fn execute_prompt(
router: &Router,
client: &OpenRouterClient,
) -> Result<(), Box<dyn std::error::Error>> {
// 1. Budget pre-check (advisory only; each dispatch records atomically).
// 1. Budget check
match budget_tracker.check_budget() {
Ok(status) => {
if status.approaching_daily_limit {
eprintln!(
"{} Daily usage: {}/{}",
"! Budget notice: Approaching daily ceiling.".yellow(),
"⚠ Budget notice: Approaching daily ceiling.".yellow(),
status.daily_requests,
status.daily_limit
);
@ -535,7 +387,7 @@ async fn execute_prompt(
.find(|p| p.name == *pipe_name)
.ok_or_else(|| format!("Pipeline '{pipe_name}' not found in configuration"))?;
run_pipeline(CliRunParams {
run_pipeline(
pipeline,
config,
budget_tracker,
@ -544,7 +396,7 @@ async fn execute_prompt(
prompt,
allow_stealth,
require_paid,
})
)
.await?;
return Ok(());
}
@ -563,7 +415,7 @@ async fn execute_prompt(
match decision {
Ok(dec) => {
if dec.stage_used == RouteStage::StageBLlm {
let _ = budget_tracker.try_acquire(false);
let _ = budget_tracker.record_call(false);
}
let info = match dec.stage_used {
RouteStage::StageAKeyword => "routed via keyword pre-filter".to_string(),
@ -584,7 +436,7 @@ async fn execute_prompt(
if let Some(info) = route_info {
eprintln!(
"{}",
format!("› [BrokeCrew: {info} ➔ {}]", target_persona).dimmed()
format!("⚡ [BrokeCrew: {info} ➔ {}]", target_persona).dimmed()
);
}
@ -592,16 +444,16 @@ async fn execute_prompt(
let persona_tag = get_persona_color_tag(&target_persona);
let spinner = create_spinner("Thinking...");
let dispatch_future = PipelineExecutor::dispatch_persona(DispatchParams {
persona_name: &target_persona,
persona_registry: &config.persona_registry,
let dispatch_future = PipelineExecutor::dispatch_persona(
&target_persona,
&config.persona_registry,
model_registry,
client,
prompt,
allow_stealth,
require_paid,
chunk_sender: Some(chunk_tx),
});
Some(chunk_tx),
);
let printer = tokio::spawn(async move {
let mut first = true;
@ -625,14 +477,14 @@ async fn execute_prompt(
if res.fell_back {
eprintln!(
"{}",
format!("! Candidate fallback: served by {}", res.model_used).yellow()
format!("⚠ Candidate fallback: served by {}", res.model_used).yellow()
);
}
// Record budget for each failed attempt plus the successful one
for _ in 0..res.attempts.len() {
let _ = budget_tracker.try_acquire(false);
let _ = budget_tracker.record_call(false);
}
let _ = budget_tracker.try_acquire(res.tier_used == Tier::Paid);
let _ = budget_tracker.record_call(res.tier_used == Tier::Paid);
}
Err(e) => {
eprintln!("\n{} {}", "Error dispatching to persona:".red().bold(), e);
@ -642,36 +494,36 @@ async fn execute_prompt(
Ok(())
}
async fn run_pipeline(params: CliRunParams<'_>) -> Result<(), Box<dyn std::error::Error>> {
let CliRunParams {
pipeline,
config,
budget_tracker,
model_registry,
client,
prompt,
allow_stealth,
require_paid,
} = params;
#[allow(clippy::too_many_arguments)]
async fn run_pipeline(
pipeline: &PipelineConfig,
config: &AppConfig,
budget_tracker: &mut BudgetTracker,
model_registry: &ModelRegistry,
client: &OpenRouterClient,
prompt: &str,
allow_stealth: bool,
require_paid: bool,
) -> Result<(), Box<dyn std::error::Error>> {
println!(
"\n{} Starting pipeline '{}' ({} steps)",
"›".bright_cyan(),
"⚡".bright_cyan(),
pipeline.name.bold(),
pipeline.steps.len()
);
let (event_tx, mut event_rx) = mpsc::channel::<PipelineEvent>(100);
let exec_future = PipelineExecutor::execute(PipelineRunParams {
let exec_future = PipelineExecutor::execute(
pipeline,
persona_registry: &config.persona_registry,
&config.persona_registry,
model_registry,
client,
initial_prompt: prompt,
prompt,
allow_stealth,
require_paid,
event_sender: Some(event_tx),
});
Some(event_tx),
);
let event_handler = tokio::spawn(async move {
let mut current_spinner: Option<ProgressBar> = None;
@ -682,46 +534,23 @@ async fn run_pipeline(params: CliRunParams<'_>) -> Result<(), Box<dyn std::error
step_index,
total_steps,
persona,
model,
..
} => {
if let Some(sp) = current_spinner.take() {
sp.finish_and_clear();
}
let badge = get_persona_color_tag(&persona);
println!(
"\n--- Step {}/{} {} ---",
"\n--- Step {}/{} {} ({}) ---",
step_index + 1,
total_steps,
badge,
model.dimmed()
);
let sp = create_spinner("Thinking...");
current_spinner = Some(sp);
}
PipelineEvent::StepFailed {
step_index,
persona,
error,
} => {
if let Some(sp) = current_spinner.take() {
sp.finish_and_clear();
}
eprintln!(
"{}",
format!("! Step {}/{persona} failed: {error}", step_index + 1,).red()
);
}
PipelineEvent::CandidateAttempt {
model,
attempt,
total_candidates,
..
} => {
if let Some(ref sp) = current_spinner {
sp.set_message(format!("Trying {model} ({attempt}/{total_candidates})..."));
}
}
PipelineEvent::CandidateFailed { model, error, .. } => {
tracing::debug!(model = %model, error = %error, "Candidate attempt failed");
}
PipelineEvent::Chunk { delta, .. } => {
if let Some(sp) = current_spinner.take() {
sp.finish_and_clear();
@ -729,18 +558,13 @@ async fn run_pipeline(params: CliRunParams<'_>) -> Result<(), Box<dyn std::error
print!("{delta}");
let _ = io::stdout().flush();
}
PipelineEvent::StepCompleted {
model_used,
fell_back,
..
} => {
PipelineEvent::StepCompleted { fell_back, .. } => {
if let Some(sp) = current_spinner.take() {
sp.finish_and_clear();
}
println!();
eprintln!("{}", format!("› served by {model_used}").dimmed());
if fell_back {
eprintln!("{}", "! Fallback occurred during step execution".yellow());
eprintln!("{}", "⚠ Fallback occurred during step execution".yellow());
}
}
}
@ -752,9 +576,9 @@ async fn run_pipeline(params: CliRunParams<'_>) -> Result<(), Box<dyn std::error
for r in &results {
for _ in 0..r.attempts.len() {
let _ = budget_tracker.try_acquire(false);
let _ = budget_tracker.record_call(false);
}
let _ = budget_tracker.try_acquire(r.tier_used == Tier::Paid);
let _ = budget_tracker.record_call(r.tier_used == Tier::Paid);
}
Ok(())

View file

@ -102,21 +102,6 @@ impl PersonaRegistry {
Ok(eligible)
}
}
/// Returns a new PersonaRegistry with tool execution prompts injected into persona system prompts
pub fn with_tool_capabilities(&self) -> Self {
let tool_prompt = crate::tool::ToolEngine::system_tool_prompt();
let personas = self
.personas
.iter()
.map(|p| {
let mut cp = p.clone();
cp.system_prompt.push_str(tool_prompt);
cp
})
.collect();
Self { personas }
}
}
#[cfg(test)]

View file

@ -1,7 +1,5 @@
use crate::budget::BudgetTracker;
use crate::client::{ClientError, ModelClient, OpenRouterClient};
use crate::config::AppConfig;
use crate::persona::{DispatchResult, ModelAttempt, ModelCandidate, PersonaRegistry, Tier};
use crate::client::{ClientError, ModelClient};
use crate::persona::{DispatchResult, ModelAttempt, PersonaRegistry, Tier};
use crate::registry::ModelRegistry;
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;
@ -19,23 +17,6 @@ pub struct PipelineStep {
pub struct PipelineConfig {
pub name: String,
pub steps: Vec<PipelineStep>,
/// When false (default), a failed step aborts the pipeline but completed
/// step results are preserved in the returned outcome.
#[serde(default = "default_abort_on_failure")]
pub abort_on_failure: bool,
}
fn default_abort_on_failure() -> bool {
true
}
/// Outcome of a pipeline run: completed step results plus, on failure,
/// which step failed and why. Callers keep partial results either way.
#[derive(Debug)]
pub struct PipelineOutcome {
pub results: Vec<DispatchResult>,
pub failed_step: Option<usize>,
pub error: Option<ClientError>,
}
#[derive(Debug, Clone)]
@ -44,21 +25,9 @@ pub enum PipelineEvent {
step_index: usize,
total_steps: usize,
persona: String,
},
CandidateAttempt {
step_index: usize,
persona: String,
model: String,
attempt: usize,
total_candidates: usize,
tier: Tier,
},
CandidateFailed {
step_index: usize,
persona: String,
model: String,
error: String,
},
Chunk {
step_index: usize,
delta: String,
@ -66,83 +35,27 @@ pub enum PipelineEvent {
StepCompleted {
step_index: usize,
persona: String,
model_used: String,
tier_used: Tier,
full_reply: String,
fell_back: bool,
attempts: Vec<ModelAttempt>,
},
StepFailed {
step_index: usize,
persona: String,
error: String,
},
}
/// Parameters for a single persona dispatch. Bundles the 8-argument
/// call sites into one value so callers stay readable.
#[derive(Clone)]
pub struct DispatchParams<'a> {
pub persona_name: &'a str,
pub persona_registry: &'a PersonaRegistry,
pub model_registry: &'a ModelRegistry,
pub client: &'a dyn ModelClient,
pub prompt: &'a str,
pub allow_stealth: bool,
pub require_paid: bool,
pub chunk_sender: Option<mpsc::Sender<String>>,
}
/// Parameters for a full pipeline run. See [`DispatchParams`].
#[derive(Clone)]
pub struct PipelineRunParams<'a> {
pub pipeline: &'a PipelineConfig,
pub persona_registry: &'a PersonaRegistry,
pub model_registry: &'a ModelRegistry,
pub client: &'a dyn ModelClient,
pub initial_prompt: &'a str,
pub allow_stealth: bool,
pub require_paid: bool,
pub event_sender: Option<mpsc::Sender<PipelineEvent>>,
}
/// Parameters for the CLI `run_pipeline` presentation loop.
pub struct CliRunParams<'a> {
pub pipeline: &'a PipelineConfig,
pub config: &'a AppConfig,
pub budget_tracker: &'a mut BudgetTracker,
pub model_registry: &'a ModelRegistry,
pub client: &'a OpenRouterClient,
pub prompt: &'a str,
pub allow_stealth: bool,
pub require_paid: bool,
}
pub struct PipelineExecutor;
impl PipelineExecutor {
/// Executes a single persona query with candidate fallback walk
#[allow(clippy::too_many_arguments)]
pub async fn dispatch_persona(
params: DispatchParams<'_>,
persona_name: &str,
persona_registry: &PersonaRegistry,
model_registry: &ModelRegistry,
client: &dyn ModelClient,
prompt: &str,
allow_stealth: bool,
require_paid: bool,
chunk_sender: Option<mpsc::Sender<String>>,
) -> Result<DispatchResult, ClientError> {
Self::dispatch_persona_with_events(params, None).await
}
/// Executes a single persona query with candidate fallback walk and telemetry event streaming
pub async fn dispatch_persona_with_events(
params: DispatchParams<'_>,
event_sender: Option<mpsc::Sender<PipelineEvent>>,
) -> Result<DispatchResult, ClientError> {
let DispatchParams {
persona_name,
persona_registry,
model_registry,
client,
prompt,
allow_stealth,
require_paid,
chunk_sender,
} = params;
let persona = persona_registry.get(persona_name).ok_or_else(|| {
ClientError::ModelUnavailable(format!("Persona '{persona_name}' not found"))
})?;
@ -152,8 +65,7 @@ impl PipelineExecutor {
.filter_eligible(&persona.candidates, allow_stealth, require_paid)
.await;
let dynamic_discovered;
let candidates_to_try: Vec<&ModelCandidate> = if !eligible.is_empty() {
let candidates_to_try = if !eligible.is_empty() {
eligible
} else if model_registry.model_count().await == 0 {
// Uninitialized / offline degraded state: allow raw candidates
@ -163,21 +75,8 @@ impl PipelineExecutor {
.filter(|c| allow_stealth || !c.is_stealth)
.collect()
} else {
// Live catalog was fetched, but declared candidates were rotated out.
// Dynamically discover active live free models for this persona:
dynamic_discovered = model_registry
.discover_free_candidates_for_role(persona_name)
.await;
if !dynamic_discovered.is_empty() {
tracing::info!(
persona = %persona_name,
count = dynamic_discovered.len(),
"Auto-discovered live free fallback candidates from OpenRouter catalog"
);
dynamic_discovered.iter().collect()
} else {
vec![]
}
// Live catalog was fetched and deliberately excluded all candidates as offline/unlisted
vec![]
};
if candidates_to_try.is_empty() {
@ -199,19 +98,6 @@ impl PipelineExecutor {
"Attempting candidate dispatch"
);
if let Some(ref tx) = event_sender {
let _ = tx
.send(PipelineEvent::CandidateAttempt {
step_index: 0,
persona: persona_name.to_string(),
model: model_id.clone(),
attempt: idx + 1,
total_candidates,
tier: candidate.tier,
})
.await;
}
// Channel for streaming chunks if sender provided
let (tx, mut rx) = mpsc::channel::<String>(100);
let forwarder = {
@ -265,17 +151,6 @@ impl PipelineExecutor {
error: Some(err_msg.clone()),
});
if let Some(ref tx) = event_sender {
let _ = tx
.send(PipelineEvent::CandidateFailed {
step_index: 0,
persona: persona_name.to_string(),
model: model_id.clone(),
error: err_msg.clone(),
})
.await;
}
// Fast-fail on auth or billing errors
match e {
ClientError::Unauthorized | ClientError::PaymentRequired => return Err(e),
@ -320,55 +195,26 @@ impl PipelineExecutor {
)))
}
/// Executes an entire pipeline sequentially, passing outputs between steps.
/// On step failure the outcome carries completed results plus the failure;
/// callers decide whether partial output is usable. `abort_on_failure=false`
/// continues with the remaining steps instead of stopping.
/// Executes an entire pipeline sequentially, passing outputs between steps
#[allow(clippy::too_many_arguments)]
pub async fn execute(
params: PipelineRunParams<'_>,
pipeline: &PipelineConfig,
persona_registry: &PersonaRegistry,
model_registry: &ModelRegistry,
client: &dyn ModelClient,
initial_prompt: &str,
allow_stealth: bool,
require_paid: bool,
event_sender: Option<mpsc::Sender<PipelineEvent>>,
) -> Result<Vec<DispatchResult>, ClientError> {
let outcome = Self::execute_outcome(params).await;
match outcome.error {
None => Ok(outcome.results),
Some(e) => Err(e),
}
}
/// Variant of [`Self::execute`] that preserves partial results on failure.
pub async fn execute_outcome(params: PipelineRunParams<'_>) -> PipelineOutcome {
let PipelineRunParams {
pipeline,
persona_registry,
model_registry,
client,
initial_prompt,
allow_stealth,
require_paid,
event_sender,
} = params;
let mut results = Vec::new();
let mut previous_output = String::new();
let total_steps = pipeline.steps.len();
for (step_idx, step) in pipeline.steps.iter().enumerate() {
if persona_registry.get(&step.persona).is_none() {
let err =
ClientError::ModelUnavailable(format!("Persona '{}' not found", step.persona));
if let Some(ref tx) = event_sender {
let _ = tx
.send(PipelineEvent::StepFailed {
step_index: step_idx,
persona: step.persona.clone(),
error: err.to_string(),
})
.await;
}
return PipelineOutcome {
results,
failed_step: Some(step_idx),
error: Some(err),
};
}
let persona = persona_registry.get(&step.persona).ok_or_else(|| {
ClientError::ModelUnavailable(format!("Persona '{}' not found", step.persona))
})?;
// Prepare prompt for this step
let step_prompt = if step.pass_previous_output && !previous_output.is_empty() {
@ -402,84 +248,58 @@ impl PipelineExecutor {
}
});
// Notify step start. The model is intentionally omitted here:
// the fallback walk has not run yet, so any advertised model
// would be a guess. The resolved model arrives via
// CandidateAttempt events and the StepCompleted model_used field.
// Notify step start
if let Some(ref tx) = event_sender {
// Peek top candidate to inform UI
let top_candidate = persona
.candidates
.first()
.map(|c| (c.id.clone(), c.tier))
.unwrap_or_else(|| ("unknown".into(), Tier::Free));
let _ = tx
.send(PipelineEvent::StepStarted {
step_index: step_idx,
total_steps,
persona: step.persona.clone(),
model: top_candidate.0,
tier: top_candidate.1,
})
.await;
}
let dispatch_result = Self::dispatch_persona_with_events(
DispatchParams {
persona_name: &step.persona,
persona_registry,
model_registry,
client,
prompt: &step_prompt,
allow_stealth,
require_paid,
chunk_sender: Some(chunk_tx),
},
event_sender.clone(),
let dispatch_result = Self::dispatch_persona(
&step.persona,
persona_registry,
model_registry,
client,
&step_prompt,
allow_stealth,
require_paid,
Some(chunk_tx),
)
.await;
.await?;
let _ = forwarder.await;
match dispatch_result {
Ok(dispatch_result) => {
previous_output = dispatch_result.reply.clone();
previous_output = dispatch_result.reply.clone();
if let Some(ref tx) = event_sender {
let _ = tx
.send(PipelineEvent::StepCompleted {
step_index: step_idx,
persona: step.persona.clone(),
model_used: dispatch_result.model_used.clone(),
tier_used: dispatch_result.tier_used,
full_reply: dispatch_result.reply.clone(),
fell_back: dispatch_result.fell_back,
attempts: dispatch_result.attempts.clone(),
})
.await;
}
results.push(dispatch_result);
}
Err(e) => {
if let Some(ref tx) = event_sender {
let _ = tx
.send(PipelineEvent::StepFailed {
step_index: step_idx,
persona: step.persona.clone(),
error: e.to_string(),
})
.await;
}
if pipeline.abort_on_failure {
return PipelineOutcome {
results,
failed_step: Some(step_idx),
error: Some(e),
};
}
// Continue: keep previous_output from the last success.
}
if let Some(ref tx) = event_sender {
let _ = tx
.send(PipelineEvent::StepCompleted {
step_index: step_idx,
persona: step.persona.clone(),
full_reply: dispatch_result.reply.clone(),
fell_back: dispatch_result.fell_back,
attempts: dispatch_result.attempts.clone(),
})
.await;
}
results.push(dispatch_result);
}
PipelineOutcome {
results,
failed_step: None,
error: None,
}
Ok(results)
}
}
@ -561,7 +381,6 @@ mod tests {
custom_prompt_template: None,
},
],
abort_on_failure: true,
};
let calls = Arc::new(AtomicUsize::new(0));
@ -569,16 +388,16 @@ mod tests {
calls: calls.clone(),
};
let results = PipelineExecutor::execute(PipelineRunParams {
pipeline: &pipeline,
persona_registry: &persona_reg,
model_registry: &model_reg,
client: &client,
initial_prompt: "Build website",
allow_stealth: false,
require_paid: false,
event_sender: None,
})
let results = PipelineExecutor::execute(
&pipeline,
&persona_reg,
&model_reg,
&client,
"Build website",
false,
false,
None,
)
.await
.expect("pipeline execution failed");
@ -591,160 +410,4 @@ mod tests {
assert!(results[1].reply.contains("Output from coder-model"));
assert_eq!(calls.load(Ordering::SeqCst), 2);
}
struct AlwaysFailClient;
#[async_trait]
impl ModelClient for AlwaysFailClient {
async fn complete(
&self,
_model: &str,
_system: &str,
_user: &str,
) -> Result<String, ClientError> {
Err(ClientError::ServerError {
status: 503,
message: "down".into(),
})
}
async fn complete_stream(
&self,
model: &str,
system: &str,
user: &str,
_chunk_sender: mpsc::Sender<String>,
) -> Result<String, ClientError> {
self.complete(model, system, user).await
}
}
fn failing_two_step_pipeline() -> (PersonaRegistry, PipelineConfig) {
let mk = |name: &str| Persona {
name: name.into(),
system_prompt: name.into(),
trigger_words: vec![],
candidates: vec![ModelCandidate {
id: format!("{name}-model"),
tier: Tier::Free,
is_stealth: false,
}],
};
let reg = PersonaRegistry::new(vec![mk("coder"), mk("reviewer")]);
let pipe = PipelineConfig {
name: "fail-fast".into(),
steps: vec![
PipelineStep {
persona: "coder".into(),
pass_previous_output: false,
custom_prompt_template: None,
},
PipelineStep {
persona: "reviewer".into(),
pass_previous_output: true,
custom_prompt_template: None,
},
],
abort_on_failure: true,
};
(reg, pipe)
}
#[tokio::test]
async fn test_pipeline_failure_preserves_partial_results() {
struct FailSecondClient;
#[async_trait]
impl ModelClient for FailSecondClient {
async fn complete(
&self,
model: &str,
_system: &str,
user: &str,
) -> Result<String, ClientError> {
if model == "reviewer-model" {
return Err(ClientError::ServerError {
status: 503,
message: "reviewer down".into(),
});
}
Ok(format!("Output from {model} for: {user}"))
}
async fn complete_stream(
&self,
model: &str,
system: &str,
user: &str,
chunk_sender: mpsc::Sender<String>,
) -> Result<String, ClientError> {
let res = self.complete(model, system, user).await?;
let _ = chunk_sender.send(res.clone()).await;
Ok(res)
}
}
let (reg, pipe) = failing_two_step_pipeline();
let model_reg = ModelRegistry::new();
let (event_tx, mut event_rx) = mpsc::channel::<PipelineEvent>(16);
let outcome = PipelineExecutor::execute_outcome(PipelineRunParams {
pipeline: &pipe,
persona_registry: &reg,
model_registry: &model_reg,
client: &FailSecondClient,
initial_prompt: "Build website",
allow_stealth: false,
require_paid: false,
event_sender: Some(event_tx),
})
.await;
// First step succeeded and is preserved despite the abort.
assert_eq!(outcome.results.len(), 1);
assert_eq!(outcome.failed_step, Some(1));
assert!(outcome.error.is_some());
// A StepFailed event must have been emitted for the UI.
let mut saw_failed = false;
while let Ok(ev) = event_rx.try_recv() {
if matches!(ev, PipelineEvent::StepFailed { step_index: 1, .. }) {
saw_failed = true;
}
}
assert!(saw_failed, "expected StepFailed event for step 1");
// Legacy execute() still surfaces the error.
let err = PipelineExecutor::execute(PipelineRunParams {
pipeline: &pipe,
persona_registry: &reg,
model_registry: &model_reg,
client: &FailSecondClient,
initial_prompt: "Build website",
allow_stealth: false,
require_paid: false,
event_sender: None,
})
.await
.unwrap_err();
assert!(err.to_string().contains("reviewer down"));
}
#[tokio::test]
async fn test_pipeline_continue_on_failure_policy() {
let (reg, mut pipe) = failing_two_step_pipeline();
pipe.abort_on_failure = false;
let model_reg = ModelRegistry::new();
let outcome = PipelineExecutor::execute_outcome(PipelineRunParams {
pipeline: &pipe,
persona_registry: &reg,
model_registry: &model_reg,
client: &AlwaysFailClient,
initial_prompt: "Build website",
allow_stealth: false,
require_paid: false,
event_sender: None,
})
.await;
assert_eq!(outcome.failed_step, None);
assert!(outcome.error.is_none());
assert!(outcome.results.is_empty());
}
}

View file

@ -33,7 +33,6 @@ struct OpenRouterModelsResponse {
pub struct ModelRegistry {
models: Arc<RwLock<HashMap<String, ModelInfo>>>,
last_refreshed: Arc<RwLock<Option<Instant>>>,
http: reqwest::Client,
}
impl Default for ModelRegistry {
@ -44,14 +43,9 @@ impl Default for ModelRegistry {
impl ModelRegistry {
pub fn new() -> Self {
let http = reqwest::Client::builder()
.timeout(Duration::from_secs(15))
.build()
.unwrap_or_else(|_| reqwest::Client::new());
Self {
models: Arc::new(RwLock::new(HashMap::new())),
last_refreshed: Arc::new(RwLock::new(None)),
http,
}
}
@ -90,9 +84,12 @@ impl ModelRegistry {
/// Fetches live models catalog from OpenRouter `/v1/models`
pub async fn fetch_live(&self, base_url: &str) -> Result<usize, String> {
let endpoint = format!("{}/models", base_url.trim_end_matches('/'));
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(15))
.build()
.map_err(|e| e.to_string())?;
let res = self
.http
let res = client
.get(&endpoint)
.header("HTTP-Referer", "https://github.com/brokecrew/brokecrew")
.header("X-Title", "BrokeCrew")
@ -115,32 +112,19 @@ impl ModelRegistry {
self.update_from_json(&body).await
}
/// Starts a background task refreshing the models registry periodically.
/// Returns a handle the caller can abort on shutdown; the task does an
/// immediate fetch, then repeats on `interval` (30 min recommended).
pub fn start_background_sync(
self: &Arc<Self>,
base_url: String,
interval: Duration,
) -> tokio::task::JoinHandle<()> {
let this = Arc::clone(self);
/// Starts a background task refreshing the models registry periodically
pub fn start_background_sync(self: Arc<Self>, base_url: String, interval: Duration) {
tokio::spawn(async move {
// Immediate first sync so the catalog is warm before first dispatch.
if let Err(e) = this.fetch_live(&base_url).await {
tracing::warn!("Initial models registry sync failed: {}", e);
}
let mut ticker = tokio::time::interval(interval);
// Skip the immediate first tick: we just synced above.
ticker.tick().await;
loop {
ticker.tick().await;
if let Err(e) = this.fetch_live(&base_url).await {
if let Err(e) = self.fetch_live(&base_url).await {
tracing::warn!("Periodic models registry sync failed: {}", e);
} else {
tracing::debug!("Periodic models registry sync succeeded");
}
}
})
});
}
pub async fn is_model_available(&self, model_id: &str) -> bool {
@ -176,46 +160,6 @@ impl ModelRegistry {
})
.collect()
}
/// Discovers active `:free` models in the catalog that best match a persona role hint.
pub async fn discover_free_candidates_for_role(&self, role_hint: &str) -> Vec<ModelCandidate> {
let read = self.models.read().await;
let mut matching = Vec::new();
let mut generic_free = Vec::new();
let hint_lower = role_hint.to_lowercase();
let keywords: &[&str] = match hint_lower.as_str() {
"coder" => &["code", "coder", "qwen", "gemma", "north"],
"reviewer" => &["review", "gemma", "nemotron", "reasoning", "qwen"],
"architect" => &["ultra", "super", "550b", "120b", "gemma", "nemotron"],
_ => &["gemma", "qwen", "nemotron", "liquid", "inkling", "ling"],
};
for id in read.keys() {
if id.ends_with(":free") {
let id_lower = id.to_lowercase();
if keywords.iter().any(|&kw| id_lower.contains(kw)) {
matching.push(ModelCandidate {
id: id.clone(),
tier: Tier::Free,
is_stealth: false,
});
} else {
generic_free.push(ModelCandidate {
id: id.clone(),
tier: Tier::Free,
is_stealth: false,
});
}
}
}
matching.sort_by(|a, b| a.id.cmp(&b.id));
generic_free.sort_by(|a, b| a.id.cmp(&b.id));
matching.extend(generic_free);
matching
}
}
#[cfg(test)]

View file

@ -23,39 +23,19 @@ pub struct RouteDecision {
pub struct Router {
pub default_persona: String,
router_model: arc_swap::ArcSwap<String>,
complexity_threshold: std::sync::atomic::AtomicU8,
pub router_model: String,
pub complexity_threshold: u8,
}
impl Router {
pub fn new(default_persona: String, router_model: String, complexity_threshold: u8) -> Self {
Self {
default_persona,
router_model: arc_swap::ArcSwap::new(std::sync::Arc::new(router_model)),
complexity_threshold: std::sync::atomic::AtomicU8::new(
complexity_threshold.clamp(1, 10),
),
router_model,
complexity_threshold,
}
}
pub fn complexity_threshold(&self) -> u8 {
self.complexity_threshold
.load(std::sync::atomic::Ordering::Relaxed)
}
pub fn set_router_model(&self, model: String) {
self.router_model.store(std::sync::Arc::new(model));
}
pub fn get_router_model(&self) -> String {
self.router_model.load_full().as_ref().clone()
}
pub fn set_complexity_threshold(&self, threshold: u8) {
self.complexity_threshold
.store(threshold.clamp(1, 10), std::sync::atomic::Ordering::Relaxed);
}
pub async fn route(
&self,
registry: &PersonaRegistry,
@ -64,7 +44,7 @@ impl Router {
force_escalate: bool,
) -> Result<RouteDecision, ClientError> {
let complexity_score = LlmRouter::estimate_complexity(prompt);
let escalate_to_paid = force_escalate || complexity_score >= self.complexity_threshold();
let escalate_to_paid = force_escalate || complexity_score >= self.complexity_threshold;
// Stage A: Free, instant keyword matching
if let Some(matched) = KeywordRouter::classify(registry.list(), prompt) {
@ -78,10 +58,14 @@ impl Router {
// Stage B: LLM classification fallback
let known: Vec<String> = registry.list().iter().map(|p| p.name.clone()).collect();
let router_model = self.get_router_model();
let selected =
LlmRouter::classify(client, &router_model, &known, &self.default_persona, prompt)
.await?;
let selected = LlmRouter::classify(
client,
&self.router_model,
&known,
&self.default_persona,
prompt,
)
.await?;
Ok(RouteDecision {
persona: selected,
@ -163,16 +147,4 @@ mod tests {
assert_eq!(dec2.persona, "coder");
assert!(dec2.escalate_to_paid);
}
#[test]
fn test_set_complexity_threshold_clamps_and_reads() {
let router = Router::new("general".into(), "router-model".into(), 7);
assert_eq!(router.complexity_threshold(), 7);
router.set_complexity_threshold(9);
assert_eq!(router.complexity_threshold(), 9);
router.set_complexity_threshold(0);
assert_eq!(router.complexity_threshold(), 1);
router.set_complexity_threshold(255);
assert_eq!(router.complexity_threshold(), 10);
}
}

View file

@ -1,180 +0,0 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fs;
use std::io;
use std::path::Path;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionMessage {
pub sender: String,
pub content: String,
pub model: Option<String>,
pub timestamp: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
pub id: String,
pub title: String,
pub persona: String,
pub created_at: String,
pub updated_at: String,
pub messages: Vec<SessionMessage>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionSummary {
pub id: String,
pub title: String,
pub persona: String,
pub updated_at: String,
pub message_count: usize,
}
impl Session {
pub fn new(persona: &str) -> Self {
let now: DateTime<Utc> = Utc::now();
let timestamp_str = now.format("%Y%m%d-%H%M%S-%f").to_string();
// Sub-second timestamp plus random suffix: two sessions created in the
// same microsecond still get distinct ids and never overwrite each other.
let rand_suffix: u32 = rand::random::<u32>() % 0xFFFF;
let id = format!("session-{timestamp_str}-{rand_suffix:04x}");
Self {
id,
title: "New Session".to_string(),
persona: persona.to_string(),
created_at: now.to_rfc3339(),
updated_at: now.to_rfc3339(),
messages: Vec::new(),
}
}
pub fn add_message(&mut self, sender: &str, content: &str, model: Option<&str>) {
let now: DateTime<Utc> = Utc::now();
self.updated_at = now.to_rfc3339();
// Update session title from first user prompt if still default
if self.title == "New Session" && sender.eq_ignore_ascii_case("you") {
let truncated: String = content.chars().take(40).collect();
self.title = truncated.trim().to_string();
}
self.messages.push(SessionMessage {
sender: sender.to_string(),
content: content.to_string(),
model: model.map(|m| m.to_string()),
timestamp: now.to_rfc3339(),
});
}
pub fn save(&self, base_dir: &Path) -> Result<(), io::Error> {
let sessions_dir = base_dir.join("sessions");
fs::create_dir_all(&sessions_dir)?;
let file_path = sessions_dir.join(format!("{}.json", self.id));
let json = serde_json::to_string_pretty(self)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
fs::write(file_path, json)?;
// Also save latest symlink/copy for convenient continuation
let latest_path = sessions_dir.join("latest.json");
let _ = fs::write(
latest_path,
serde_json::to_string_pretty(self).unwrap_or_default(),
);
Ok(())
}
pub fn load(base_dir: &Path, id: &str) -> Result<Self, io::Error> {
let sessions_dir = base_dir.join("sessions");
let file_path = if id == "latest" {
sessions_dir.join("latest.json")
} else {
sessions_dir.join(format!("{id}.json"))
};
let content = fs::read_to_string(file_path)?;
let session: Session = serde_json::from_str(&content)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
Ok(session)
}
pub fn list(base_dir: &Path) -> Result<Vec<SessionSummary>, io::Error> {
let sessions_dir = base_dir.join("sessions");
if !sessions_dir.exists() {
return Ok(Vec::new());
}
let mut list = Vec::new();
for entry in fs::read_dir(sessions_dir)? {
let entry = entry?;
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) == Some("json") {
let filename = path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or_default();
if filename == "latest" {
continue;
}
if let Ok(content) = fs::read_to_string(&path) {
if let Ok(session) = serde_json::from_str::<Session>(&content) {
list.push(SessionSummary {
id: session.id,
title: session.title,
persona: session.persona,
updated_at: session.updated_at,
message_count: session.messages.len(),
});
}
}
}
}
list.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
Ok(list)
}
pub fn delete(base_dir: &Path, id: &str) -> Result<(), io::Error> {
let file_path = base_dir.join("sessions").join(format!("{id}.json"));
if file_path.exists() {
fs::remove_file(file_path)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn test_session_lifecycle_save_and_load() {
let dir = tempdir().unwrap();
let mut session = Session::new("coder");
session.add_message("you", "Write an LRU cache", None);
session.add_message("coder", "Here is the code", Some("qwen"));
assert_eq!(session.title, "Write an LRU cache");
session.save(dir.path()).expect("save succeeds");
let loaded = Session::load(dir.path(), &session.id).expect("load succeeds");
assert_eq!(loaded.messages.len(), 2);
assert_eq!(loaded.persona, "coder");
let summaries = Session::list(dir.path()).expect("list succeeds");
assert_eq!(summaries.len(), 1);
assert_eq!(summaries[0].id, session.id);
}
#[test]
fn test_session_ids_unique_same_instant() {
// Regression test: two sessions created back-to-back must never collide.
let a = Session::new("coder");
let b = Session::new("coder");
assert_ne!(a.id, b.id, "session ids must be unique");
}
}

View file

@ -1,182 +0,0 @@
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::time::Duration;
use tokio::process::Command;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolOutput {
pub command: String,
pub exit_code: i32,
pub stdout: String,
pub stderr: String,
pub duration_ms: u64,
}
impl ToolOutput {
pub fn is_success(&self) -> bool {
self.exit_code == 0
}
pub fn format_for_model(&self) -> String {
let mut out = format!(
"[Command: `{}` exit code: {}]\n",
self.command, self.exit_code
);
if !self.stdout.is_empty() {
out.push_str("stdout:\n");
out.push_str(&self.stdout);
if !self.stdout.ends_with('\n') {
out.push('\n');
}
}
if !self.stderr.is_empty() {
out.push_str("stderr:\n");
out.push_str(&self.stderr);
if !self.stderr.ends_with('\n') {
out.push('\n');
}
}
if self.stdout.is_empty() && self.stderr.is_empty() {
out.push_str("(No output produced)\n");
}
out
}
}
pub struct ToolEngine;
impl ToolEngine {
/// Executes a bash command locally with timeout and output capture
pub async fn execute_bash(
command: &str,
cwd: Option<&Path>,
timeout_duration: Duration,
) -> Result<ToolOutput, String> {
let start = std::time::Instant::now();
let mut cmd = Command::new("bash");
cmd.arg("-c").arg(command);
if let Some(dir) = cwd {
cmd.current_dir(dir);
}
let child = cmd.output();
match tokio::time::timeout(timeout_duration, child).await {
Ok(Ok(output)) => {
let duration_ms = start.elapsed().as_millis() as u64;
let exit_code = output.status.code().unwrap_or(-1);
let stdout_raw = String::from_utf8_lossy(&output.stdout);
let stderr_raw = String::from_utf8_lossy(&output.stderr);
// Truncate to maximum 32KB to protect token context
let stdout = truncate_output(&stdout_raw, 32 * 1024);
let stderr = truncate_output(&stderr_raw, 16 * 1024);
Ok(ToolOutput {
command: command.to_string(),
exit_code,
stdout,
stderr,
duration_ms,
})
}
Ok(Err(e)) => Err(format!("Process spawn error: {e}")),
Err(_) => Err(format!(
"Command timed out after {}s",
timeout_duration.as_secs()
)),
}
}
/// Extracts any command execution requests formatted as:
/// `<run>cmd</run>`, `<bash>cmd</bash>`, or markdown ```bash blocks tagged for execution
pub fn extract_command_calls(text: &str) -> Vec<String> {
let mut commands = Vec::new();
// 1. Check for <run>...</run> tags
let mut rest = text;
while let Some(start_idx) = rest.find("<run>") {
let after_start = &rest[start_idx + 5..];
if let Some(end_idx) = after_start.find("</run>") {
let cmd = after_start[..end_idx].trim();
if !cmd.is_empty() {
commands.push(cmd.to_string());
}
rest = &after_start[end_idx + 6..];
} else {
break;
}
}
// 2. Check for <bash>...</bash> tags
let mut rest_bash = text;
while let Some(start_idx) = rest_bash.find("<bash>") {
let after_start = &rest_bash[start_idx + 6..];
if let Some(end_idx) = after_start.find("</bash>") {
let cmd = after_start[..end_idx].trim();
if !cmd.is_empty() && !commands.contains(&cmd.to_string()) {
commands.push(cmd.to_string());
}
rest_bash = &after_start[end_idx + 7..];
} else {
break;
}
}
commands
}
/// Tool instructions appended to persona system prompts
pub fn system_tool_prompt() -> &'static str {
"\n\n[TOOL CAPABILITY: LOCAL BASH]\nYou can execute local shell commands on the user's system when needed (e.g. running tests, reading files, inspecting directories, running git/cargo/python/npm). To run a command, output it enclosed in <run>...</run> tags, for example:\n<run>cargo check</run>\nor\n<run>git status</run>\nThe command output will be executed and returned to you."
}
}
fn truncate_output(s: &str, max_bytes: usize) -> String {
if s.len() <= max_bytes {
s.to_string()
} else {
// Walk back to a char boundary so multibyte output never panics.
let mut end = max_bytes.min(s.len());
while end > 0 && !s.is_char_boundary(end) {
end -= 1;
}
format!("{}\n...[output truncated by BrokeCrew]", &s[..end])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_extract_command_calls() {
let text = "Let me check the repository status:\n<run>git status</run>\nand also list files:\n<bash>ls -la</bash>";
let calls = ToolEngine::extract_command_calls(text);
assert_eq!(calls, vec!["git status", "ls -la"]);
}
#[tokio::test]
async fn test_execute_echo_command() {
let res =
ToolEngine::execute_bash("echo 'hello from brokecrew'", None, Duration::from_secs(5))
.await
.expect("execution succeeds");
assert_eq!(res.exit_code, 0);
assert!(res.stdout.contains("hello from brokecrew"));
}
#[test]
fn test_truncate_output_respects_char_boundary() {
// 32KB+ of multibyte output must truncate without panicking.
let big = "日本語テスト出力 ".repeat(4000);
let out = truncate_output(&big, 32 * 1024);
assert!(out.ends_with("...[output truncated by BrokeCrew]"));
assert!(out.len() <= 32 * 1024 + 64);
// Short output passes through untouched.
assert_eq!(truncate_output("ok", 1024), "ok");
}
}

View file

@ -1,883 +0,0 @@
use brokecrew::persona::Tier;
use brokecrew::pipeline::PipelineConfig;
use brokecrew::session::{Session, SessionSummary};
use std::path::PathBuf;
use std::time::Instant;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MessageSender {
User,
Persona {
name: String,
model: String,
tier: Tier,
},
Tool {
command: String,
exit_code: i32,
duration_ms: u64,
},
System,
}
#[derive(Debug, Clone)]
pub struct ChatMessage {
pub sender: MessageSender,
pub content: String,
pub fell_back: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TuiMode {
Normal,
PersonaSelect,
PipelineSelect,
SessionSelect,
ThemeSelect,
Settings,
}
#[derive(Debug, Clone)]
pub struct CommandSuggestion {
pub name: &'static str,
pub description: &'static str,
}
pub const ALL_COMMANDS: &[CommandSuggestion] = &[
CommandSuggestion {
name: "/settings",
description: "Open settings and feature menu",
},
CommandSuggestion {
name: "/provider",
description: "View or change LLM provider base URL",
},
CommandSuggestion {
name: "/key",
description: "View or update OpenRouter API key",
},
CommandSuggestion {
name: "/model",
description: "View or set Stage B router model",
},
CommandSuggestion {
name: "/models",
description: "Search live cached models catalog",
},
CommandSuggestion {
name: "/session",
description: "Resume or manage saved sessions",
},
CommandSuggestion {
name: "/theme",
description: "Select UI color theme",
},
CommandSuggestion {
name: "/new",
description: "Start a fresh session",
},
CommandSuggestion {
name: "/usage",
description: "View rate limit and budget usage counters",
},
CommandSuggestion {
name: "/stats",
description: "Detailed usage and token analytics",
},
CommandSuggestion {
name: "/export",
description: "Export current chat to Markdown or JSON",
},
CommandSuggestion {
name: "/config",
description: "View active system configuration",
},
CommandSuggestion {
name: "/stealth",
description: "Toggle stealth candidate models",
},
CommandSuggestion {
name: "/escalate",
description: "Toggle complexity escalation",
},
CommandSuggestion {
name: "/persona",
description: "Select active persona or pass name",
},
CommandSuggestion {
name: "/p",
description: "Quick switch persona (e.g. /p coder, /p next)",
},
CommandSuggestion {
name: "/pipeline",
description: "Select active pipeline or pass name",
},
CommandSuggestion {
name: "/clear",
description: "Clear current conversation screen",
},
CommandSuggestion {
name: "/help",
description: "Show command and shortcut help",
},
];
pub const THEMES: &[(&str, &str)] = &[
(
"opencode",
"Default OpenCode Dark - Deep slate, cyan accent, forest tools",
),
("warm", "Warm Amber - Dark charcoal, golden amber accents"),
("forest", "Forest Mint - Deep pine, emerald & mint accents"),
(
"cyberpunk",
"Cyberpunk - Midnight, neon pink & electric blue",
),
("mono", "Monochrome - High contrast grayscale minimal"),
(
"catppuccin",
"Catppuccin Mocha - Soothing lavender, peach & velvet navy",
),
(
"tokyo_night",
"Tokyo Night - Midnight indigo, vibrant neon blue & cyan",
),
(
"nord",
"Nord - Polar night arctic frost, glacial blue & snow",
),
(
"dracula",
"Dracula - Classic vampire dark slate, neon purple & green",
),
(
"solarized",
"Solarized Dark - Deep ocean teal, cyan & solar amber",
),
(
"gruvbox",
"Gruvbox Dark - Retro dark charcoal, warm bright orange",
),
];
#[derive(Debug, Clone)]
pub struct PersonaItem {
pub name: String,
pub description: String,
}
#[derive(Debug, Clone)]
pub struct CandidateAttemptInfo {
pub model: String,
pub tier: Tier,
pub status: String,
pub is_error: bool,
pub is_success: bool,
}
#[derive(Debug, Clone)]
pub struct PipelineStepTelemetry {
pub persona: String,
pub model: String,
pub tier: Tier,
pub is_active: bool,
pub is_completed: bool,
pub fell_back: bool,
}
#[derive(Debug, Clone)]
pub struct WorkingsState {
pub active_persona: String,
pub active_pipeline: Option<String>,
pub route_stage: Option<String>,
pub route_details: Option<String>,
pub complexity_score: Option<u8>,
pub candidate_attempts: Vec<CandidateAttemptInfo>,
pub pipeline_steps: Vec<PipelineStepTelemetry>,
pub events: Vec<String>,
}
impl Default for WorkingsState {
fn default() -> Self {
Self {
active_persona: "auto".to_string(),
active_pipeline: None,
route_stage: None,
route_details: None,
complexity_score: None,
candidate_attempts: Vec::new(),
pipeline_steps: Vec::new(),
events: vec![
format!(
"{} brokecrew online",
chrono::Local::now().format("%H:%M:%S")
),
format!(
"{} catalog and budget initialized",
chrono::Local::now().format("%H:%M:%S")
),
],
}
}
}
pub struct AppState {
pub messages: Vec<ChatMessage>,
pub input: String,
pub cursor_pos: usize,
pub mode: TuiMode,
pub is_generating: bool,
pub spinner_tick: usize,
pub status_message: String,
pub scroll_offset: u16,
pub auto_scroll: bool,
// Esc confirmation
pub esc_pressed_at: Option<Instant>,
// Personas & selection
pub persona_items: Vec<PersonaItem>,
pub selected_persona_idx: usize,
// Pipelines & selection
pub pipelines: Vec<PipelineConfig>,
pub selected_pipeline_idx: usize,
pub active_pipeline_for_prompt: Option<String>,
// Sessions & persistence
pub active_session: Session,
pub session_summaries: Vec<SessionSummary>,
pub selected_session_idx: usize,
pub config_dir: PathBuf,
// Workings telemetry
pub workings: WorkingsState,
// Rate limits & budget
pub minute_requests: usize,
pub minute_limit: usize,
pub daily_requests: usize,
pub daily_limit: usize,
pub models_cached: usize,
pub tokens_in: usize,
pub tokens_out: usize,
// Options
pub allow_stealth: bool,
pub escalate: bool,
pub complexity_threshold: u8,
pub tool_execution_enabled: bool,
pub selected_setting_idx: usize,
// UX & Theme
pub expand_tool_outputs: bool,
pub current_theme: String,
pub selected_suggestion_idx: usize,
pub selected_theme_idx: usize,
}
impl AppState {
pub fn new(
raw_personas: Vec<(String, String)>,
pipelines: Vec<PipelineConfig>,
minute_limit: usize,
daily_limit: usize,
config_dir: PathBuf,
initial_theme: String,
complexity_threshold: u8,
) -> Self {
let mut persona_items = Vec::new();
// Item 0 is always the smart Auto-Router
persona_items.push(PersonaItem {
name: "auto".to_string(),
description: "keyword filter + LLM classifier".to_string(),
});
for (name, desc) in raw_personas {
persona_items.push(PersonaItem {
name,
description: desc,
});
}
let session = Session::new("auto");
let session_summaries = Session::list(&config_dir).unwrap_or_default();
let selected_theme_idx = THEMES
.iter()
.position(|(name, _)| *name == initial_theme)
.unwrap_or(0);
Self {
messages: Vec::new(),
input: String::new(),
cursor_pos: 0,
mode: TuiMode::Normal,
is_generating: false,
spinner_tick: 0,
status_message: "ready".to_string(),
scroll_offset: 0,
auto_scroll: true,
esc_pressed_at: None,
persona_items,
selected_persona_idx: 0,
pipelines,
selected_pipeline_idx: 0,
active_pipeline_for_prompt: None,
active_session: session,
session_summaries,
selected_session_idx: 0,
config_dir,
workings: WorkingsState::default(),
minute_requests: 0,
minute_limit,
daily_requests: 0,
daily_limit,
models_cached: 0,
tokens_in: 0,
tokens_out: 0,
allow_stealth: false,
escalate: false,
complexity_threshold,
tool_execution_enabled: true,
selected_setting_idx: 0,
expand_tool_outputs: false,
current_theme: initial_theme,
selected_suggestion_idx: 0,
selected_theme_idx,
}
}
pub fn format_tokens(tokens: usize) -> String {
if tokens < 1000 {
format!("{tokens}")
} else {
format!("{:.1}k", tokens as f64 / 1000.0)
}
}
pub fn get_matching_suggestions(&self) -> Vec<&'static CommandSuggestion> {
if !self.input.starts_with('/') {
return Vec::new();
}
let query = self.input.to_lowercase();
ALL_COMMANDS
.iter()
.filter(|c| c.name.starts_with(&query))
.collect()
}
pub fn is_start_screen(&self) -> bool {
self.messages.is_empty()
}
pub fn cycle_theme(&mut self) {
let current_pos = THEMES
.iter()
.position(|(name, _)| *name == self.current_theme)
.unwrap_or(0);
let next_pos = (current_pos + 1) % THEMES.len();
self.current_theme = THEMES[next_pos].0.to_string();
self.selected_theme_idx = next_pos;
}
pub fn current_persona_name(&self) -> &str {
if self.selected_persona_idx == 0 {
"auto"
} else if let Some(item) = self.persona_items.get(self.selected_persona_idx) {
&item.name
} else {
"auto"
}
}
pub fn is_auto_route(&self) -> bool {
self.selected_persona_idx == 0
}
pub fn cycle_persona(&mut self) {
if !self.persona_items.is_empty() {
self.selected_persona_idx = (self.selected_persona_idx + 1) % self.persona_items.len();
self.active_pipeline_for_prompt = None;
}
}
pub fn set_persona_by_name(&mut self, query: &str) -> Result<String, String> {
let q = query.trim().to_lowercase();
if q.is_empty() {
return Err("Persona name cannot be empty".to_string());
}
// Exact match
if let Some(pos) = self
.persona_items
.iter()
.position(|p| p.name.to_lowercase() == q)
{
self.selected_persona_idx = pos;
self.active_pipeline_for_prompt = None;
return Ok(self.current_persona_name().to_string());
}
// Prefix match
if let Some(pos) = self
.persona_items
.iter()
.position(|p| p.name.to_lowercase().starts_with(&q))
{
self.selected_persona_idx = pos;
self.active_pipeline_for_prompt = None;
return Ok(self.current_persona_name().to_string());
}
// Substring match
if let Some(pos) = self
.persona_items
.iter()
.position(|p| p.name.to_lowercase().contains(&q))
{
self.selected_persona_idx = pos;
self.active_pipeline_for_prompt = None;
return Ok(self.current_persona_name().to_string());
}
let names: Vec<String> = self.persona_items.iter().map(|p| p.name.clone()).collect();
Err(format!(
"No persona matching '{query}'. Available: {}",
names.join(", ")
))
}
pub fn log_working_event(&mut self, text: &str) {
let now = chrono::Local::now().format("%H:%M:%S").to_string();
self.workings.events.push(format!("{now} {text}"));
if self.workings.events.len() > 60 {
self.workings.events.remove(0);
}
}
pub fn reset_turn_telemetry(&mut self, persona: &str, pipeline: Option<String>) {
self.workings.active_persona = persona.to_string();
self.workings.active_pipeline = pipeline;
self.workings.route_stage = None;
self.workings.route_details = None;
self.workings.complexity_score = None;
self.workings.candidate_attempts.clear();
self.workings.pipeline_steps.clear();
}
pub fn update_current_message_model(&mut self, model_id: &str) {
if let Some(msg) = self.messages.last_mut() {
if let MessageSender::Persona { model, .. } = &mut msg.sender {
*model = model_id.to_string();
}
}
}
pub fn add_user_message(&mut self, text: String) {
self.active_session.add_message("you", &text, None);
self.messages.push(ChatMessage {
sender: MessageSender::User,
content: text,
fell_back: false,
});
if self.auto_scroll {
self.scroll_offset = 0;
}
}
pub fn start_assistant_message(&mut self, name: &str, model: &str, tier: Tier) {
self.messages.push(ChatMessage {
sender: MessageSender::Persona {
name: name.to_string(),
model: model.to_string(),
tier,
},
content: String::new(),
fell_back: false,
});
if self.auto_scroll {
self.scroll_offset = 0;
}
}
pub fn add_tool_result_message(
&mut self,
command: String,
exit_code: i32,
output: String,
duration_ms: u64,
) {
self.active_session
.add_message("tool", &format!("$ {}\n{}", command, output), None);
self.messages.push(ChatMessage {
sender: MessageSender::Tool {
command,
exit_code,
duration_ms,
},
content: output,
fell_back: false,
});
if self.auto_scroll {
self.scroll_offset = 0;
}
}
pub fn append_to_current_message(&mut self, chunk: &str) {
if let Some(msg) = self.messages.last_mut() {
msg.content.push_str(chunk);
}
}
pub fn mark_current_message_fallback(&mut self) {
if let Some(msg) = self.messages.last_mut() {
msg.fell_back = true;
}
}
pub fn add_system_message(&mut self, text: String) {
self.messages.push(ChatMessage {
sender: MessageSender::System,
content: text,
fell_back: false,
});
}
pub fn save_current_session(&mut self) {
self.active_session.messages.clear();
// Sync active_session messages
for msg in &self.messages {
let role = match &msg.sender {
MessageSender::User => "you",
MessageSender::Persona { name, .. } => name.as_str(),
MessageSender::Tool { .. } => "tool",
MessageSender::System => "system",
};
let model = match &msg.sender {
MessageSender::Persona { model, .. } => Some(model.as_str()),
_ => None,
};
self.active_session.add_message(role, &msg.content, model);
}
let _ = self.active_session.save(&self.config_dir);
self.session_summaries = Session::list(&self.config_dir).unwrap_or_default();
}
pub fn load_session_by_id(&mut self, session_id: &str) -> Result<(), String> {
let loaded = Session::load(&self.config_dir, session_id).map_err(|e| e.to_string())?;
self.messages.clear();
for m in &loaded.messages {
let sender = match m.sender.to_lowercase().as_str() {
"you" | "user" => MessageSender::User,
"system" => MessageSender::System,
"tool" => MessageSender::Tool {
command: "exec".to_string(),
exit_code: 0,
duration_ms: 0,
},
other => MessageSender::Persona {
name: other.to_string(),
model: m.model.clone().unwrap_or_else(|| "unknown".to_string()),
tier: Tier::Free,
},
};
self.messages.push(ChatMessage {
sender,
content: m.content.clone(),
fell_back: false,
});
}
self.tokens_in = self
.messages
.iter()
.filter(|m| matches!(m.sender, MessageSender::User))
.map(|m| brokecrew::estimate_tokens(&m.content))
.sum();
self.tokens_out = self
.messages
.iter()
.filter(|m| !matches!(m.sender, MessageSender::User | MessageSender::System))
.map(|m| brokecrew::estimate_tokens(&m.content))
.sum();
self.active_session = loaded;
self.scroll_offset = 0;
self.log_working_event(&format!("[session] loaded {}", session_id));
Ok(())
}
pub fn start_new_session(&mut self) {
let persona = self.current_persona_name().to_string();
self.active_session = Session::new(&persona);
self.messages.clear();
self.tokens_in = 0;
self.tokens_out = 0;
self.add_system_message("Started fresh session.".to_string());
self.scroll_offset = 0;
self.log_working_event("[session] started fresh session");
}
/// Exports active conversation to Markdown file in `~/.config/brokecrew/exports/`
pub fn export_active_session_md(&self) -> Result<PathBuf, std::io::Error> {
let export_dir = self.config_dir.join("exports");
std::fs::create_dir_all(&export_dir)?;
let filename = format!("{}.md", self.active_session.id);
let path = export_dir.join(filename);
let mut content = format!("# BrokeCrew Session: {}\n", self.active_session.title);
content.push_str(&format!("- **ID:** `{}`\n", self.active_session.id));
content.push_str(&format!(
"- **Created:** {}\n",
self.active_session.created_at
));
content.push_str(&format!(
"- **Updated:** {}\n\n---\n\n",
self.active_session.updated_at
));
for msg in &self.messages {
match &msg.sender {
MessageSender::User => {
content.push_str(&format!("### User\n\n{}\n\n", msg.content.trim()));
}
MessageSender::Persona { name, model, tier } => {
let tier_s = match tier {
Tier::Free => "free",
Tier::Paid => "paid",
};
content.push_str(&format!(
"### Assistant ({} • {} [{}])\n\n{}\n\n",
name,
model,
tier_s,
msg.content.trim()
));
}
MessageSender::Tool {
command,
exit_code,
duration_ms,
} => {
let dur_s = (*duration_ms as f64) / 1000.0;
content.push_str(&format!(
"```bash\n$ {command}\n# exit {exit_code} ({dur_s:.1}s)\n{}\n```\n\n",
msg.content.trim()
));
}
MessageSender::System => {
content.push_str(&format!("> *System: {}*\n\n", msg.content.trim()));
}
}
}
std::fs::write(&path, content)?;
Ok(path)
}
/// Exports active conversation to JSON file in `~/.config/brokecrew/exports/`
pub fn export_active_session_json(&self) -> Result<PathBuf, std::io::Error> {
let export_dir = self.config_dir.join("exports");
std::fs::create_dir_all(&export_dir)?;
let filename = format!("{}.json", self.active_session.id);
let path = export_dir.join(filename);
let json = serde_json::to_string_pretty(&self.active_session)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
std::fs::write(&path, json)?;
Ok(path)
}
pub fn clear_chat(&mut self) {
self.messages.clear();
self.add_system_message("Chat history cleared.".to_string());
self.scroll_offset = 0;
self.log_working_event("[chat] history cleared");
}
pub fn insert_char(&mut self, c: char) {
self.esc_pressed_at = None;
self.input.insert(self.cursor_pos, c);
self.cursor_pos += c.len_utf8();
}
pub fn delete_char_before_cursor(&mut self) {
self.esc_pressed_at = None;
if self.cursor_pos > 0 {
let mut prev = self.cursor_pos - 1;
while !self.input.is_char_boundary(prev) && prev > 0 {
prev -= 1;
}
self.input.remove(prev);
self.cursor_pos = prev;
}
}
pub fn delete_char_under_cursor(&mut self) {
self.esc_pressed_at = None;
if self.cursor_pos < self.input.len() {
self.input.remove(self.cursor_pos);
}
}
pub fn move_cursor_left(&mut self) {
self.esc_pressed_at = None;
if self.cursor_pos > 0 {
let mut prev = self.cursor_pos - 1;
while !self.input.is_char_boundary(prev) && prev > 0 {
prev -= 1;
}
self.cursor_pos = prev;
}
}
pub fn move_cursor_right(&mut self) {
self.esc_pressed_at = None;
if self.cursor_pos < self.input.len() {
let mut next = self.cursor_pos + 1;
while !self.input.is_char_boundary(next) && next < self.input.len() {
next += 1;
}
self.cursor_pos = next;
}
}
pub fn move_cursor_start(&mut self) {
self.esc_pressed_at = None;
self.cursor_pos = 0;
}
pub fn move_cursor_end(&mut self) {
self.esc_pressed_at = None;
self.cursor_pos = self.input.len();
}
pub fn scroll_up(&mut self, delta: u16) {
self.auto_scroll = false;
self.scroll_offset = self.scroll_offset.saturating_add(delta);
}
pub fn scroll_down(&mut self, delta: u16) {
self.scroll_offset = self.scroll_offset.saturating_sub(delta);
if self.scroll_offset == 0 {
self.auto_scroll = true;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn test_app_start_screen_and_suggestions() {
let mut app = AppState::new(
vec![],
vec![],
20,
50,
PathBuf::from("/tmp/brokecrew_test"),
"opencode".to_string(),
7,
);
assert!(app.is_start_screen());
app.input = "/se".to_string();
let sugs = app.get_matching_suggestions();
assert!(!sugs.is_empty());
assert!(sugs.iter().any(|s| s.name == "/session"));
assert!(sugs.iter().any(|s| s.name == "/settings"));
app.input = "hello world".to_string();
let sugs2 = app.get_matching_suggestions();
assert!(sugs2.is_empty());
app.add_user_message("hello".to_string());
assert!(!app.is_start_screen());
}
#[test]
fn test_app_theme_cycling() {
let mut app = AppState::new(
vec![],
vec![],
20,
50,
PathBuf::from("/tmp/brokecrew_test"),
"opencode".to_string(),
7,
);
assert_eq!(app.current_theme, "opencode");
app.cycle_theme();
assert_eq!(app.current_theme, "warm");
app.cycle_theme();
assert_eq!(app.current_theme, "forest");
app.cycle_theme();
assert_eq!(app.current_theme, "cyberpunk");
app.cycle_theme();
assert_eq!(app.current_theme, "mono");
app.cycle_theme();
assert_eq!(app.current_theme, "catppuccin");
app.cycle_theme();
assert_eq!(app.current_theme, "tokyo_night");
}
#[test]
fn test_app_export() {
let temp_dir = tempfile::tempdir().unwrap();
let mut app = AppState::new(
vec![],
vec![],
20,
50,
temp_dir.path().to_path_buf(),
"opencode".to_string(),
7,
);
app.add_user_message("Hello from user".to_string());
app.start_assistant_message("coder", "qwen-coder", Tier::Free);
app.append_to_current_message("Hello from coder");
let md_path = app.export_active_session_md().expect("export md");
assert!(md_path.exists());
let md_content = std::fs::read_to_string(&md_path).unwrap();
assert!(md_content.contains("Hello from user"));
assert!(md_content.contains("Hello from coder"));
let json_path = app.export_active_session_json().expect("export json");
assert!(json_path.exists());
}
#[test]
fn test_persona_quick_switch() {
let personas = vec![
("coder".to_string(), "coding assistant".to_string()),
("reviewer".to_string(), "review assistant".to_string()),
];
let mut app = AppState::new(
personas,
vec![],
20,
50,
PathBuf::from("/tmp/brokecrew_test"),
"opencode".to_string(),
7,
);
assert_eq!(app.current_persona_name(), "auto");
assert_eq!(app.set_persona_by_name("c").unwrap(), "coder");
assert_eq!(app.current_persona_name(), "coder");
assert_eq!(app.set_persona_by_name("rev").unwrap(), "reviewer");
assert_eq!(app.current_persona_name(), "reviewer");
assert_eq!(app.set_persona_by_name("auto").unwrap(), "auto");
assert_eq!(app.current_persona_name(), "auto");
assert!(app.set_persona_by_name("nonexistent").is_err());
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,7 @@
use async_trait::async_trait;
use brokecrew::client::{ClientError, ModelClient};
use brokecrew::persona::{ModelCandidate, Persona, PersonaRegistry, Tier};
use brokecrew::pipeline::{DispatchParams, PipelineExecutor};
use brokecrew::pipeline::PipelineExecutor;
use brokecrew::registry::ModelRegistry;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
@ -84,16 +84,16 @@ async fn test_candidate_cascade_on_503_service_unavailable() {
calls: calls.clone(),
};
let result = PipelineExecutor::dispatch_persona(DispatchParams {
persona_name: "resilient-coder",
persona_registry: &persona_reg,
model_registry: &model_reg,
client: &client,
prompt: "write rust code",
allow_stealth: false,
require_paid: false,
chunk_sender: None,
})
let result = PipelineExecutor::dispatch_persona(
"resilient-coder",
&persona_reg,
&model_reg,
&client,
"write rust code",
false,
false,
None,
)
.await
.expect("fallback to candidate-2 should succeed");
@ -121,16 +121,16 @@ async fn test_candidate_cascade_on_429_rate_limited() {
calls: calls.clone(),
};
let result = PipelineExecutor::dispatch_persona(DispatchParams {
persona_name: "resilient-coder",
persona_registry: &persona_reg,
model_registry: &model_reg,
client: &client,
prompt: "write python code",
allow_stealth: false,
require_paid: false,
chunk_sender: None,
})
let result = PipelineExecutor::dispatch_persona(
"resilient-coder",
&persona_reg,
&model_reg,
&client,
"write python code",
false,
false,
None,
)
.await
.expect("fallback to candidate-2 should succeed");
@ -151,16 +151,16 @@ async fn test_fail_fast_on_401_unauthorized() {
calls: calls.clone(),
};
let err = PipelineExecutor::dispatch_persona(DispatchParams {
persona_name: "resilient-coder",
persona_registry: &persona_reg,
model_registry: &model_reg,
client: &client,
prompt: "test query",
allow_stealth: false,
require_paid: false,
chunk_sender: None,
})
let err = PipelineExecutor::dispatch_persona(
"resilient-coder",
&persona_reg,
&model_reg,
&client,
"test query",
false,
false,
None,
)
.await
.unwrap_err();
@ -208,16 +208,16 @@ async fn test_total_cascade_failure_reports_all_attempts() {
}
}
let err = PipelineExecutor::dispatch_persona(DispatchParams {
persona_name: "resilient-coder",
persona_registry: &persona_reg,
model_registry: &model_reg,
client: &AllFailingClient,
prompt: "test query",
allow_stealth: false,
require_paid: false,
chunk_sender: None,
})
let err = PipelineExecutor::dispatch_persona(
"resilient-coder",
&persona_reg,
&model_reg,
&AllFailingClient,
"test query",
false,
false,
None,
)
.await
.unwrap_err();