use eclipse_core::reasoning::{self, InForce};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Change {
Effort(String),
Global(String),
Reset,
Display(Mode),
Report,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Mode {
#[default]
Folded,
Full,
Hidden,
Clamp(usize),
}
impl Mode {
pub fn word(self) -> String {
match self {
Mode::Folded => "folded".to_string(),
Mode::Full => "full".to_string(),
Mode::Hidden => "hidden".to_string(),
Mode::Clamp(n) => format!("clamped at {n} chars"),
}
}
pub fn hidden(self) -> bool {
self == Mode::Hidden
}
pub fn unfolded(self) -> bool {
self == Mode::Full
}
pub fn clamp(self) -> Option<usize> {
match self {
Mode::Clamp(n) => Some(n),
_ => None,
}
}
}
pub fn parse(arg: &str) -> Result<Change, String> {
let words: Vec<&str> = arg.split_whitespace().collect();
match words.as_slice() {
[] => Ok(Change::Report),
["show"] | ["full"] => Ok(Change::Display(Mode::Full)),
["hide"] => Ok(Change::Display(Mode::Hidden)),
["fold"] | ["folded"] => Ok(Change::Display(Mode::Folded)),
["default"] | ["reset"] | ["auto"] => Ok(Change::Reset),
["clamp", n] => match n.parse::<usize>() {
Ok(0) => Err("clamp needs a positive number of characters".to_string()),
Ok(chars) => Ok(Change::Display(Mode::Clamp(chars))),
Err(_) => Err(format!("{n:?} is not a number of characters")),
},
["clamp"] => Err("clamp needs a number: `/reasoning clamp 200`".to_string()),
["--global", level] | ["global", level] => match checked_level(level) {
Ok(level) => Ok(Change::Global(level)),
Err(why) => Err(why),
},
["--global"] | ["global"] => {
Err("--global needs a level: `/reasoning --global high`".to_string())
}
[level] => Ok(Change::Effort(checked_level(level)?)),
[first, ..] => Err(format!("{first:?} is not something /reasoning does")),
}
}
pub fn is_display(arg: &str) -> bool {
matches!(parse(arg), Ok(Change::Display(_)))
}
fn checked_level(word: &str) -> Result<String, String> {
let level = word.trim().to_lowercase();
if reasoning::is_level(&level) || reasoning::is_omit(&level) {
return Ok(level);
}
Err(format!(
"{word:?} is not a level; the ladder is {}, or {} for no field at all",
reasoning::LADDER.join(" · "),
reasoning::OMIT
))
}
pub fn report(in_force: &InForce, display: Mode) -> String {
let mut out = String::new();
out.push_str(&format!("effort: {}\n", in_force.in_force));
out.push_str(&format!(
" on this backend {}\n",
if in_force.resolved.is_empty() {
"(unknown)"
} else {
&in_force.resolved
}
));
out.push_str(&format!(" display {}\n", display.word()));
out.push('\n');
out.push_str("levels: ");
out.push_str(&reasoning::LADDER.join(" · "));
out.push('\n');
out.push_str(&format!(
"{}: send no reasoning field at all (not the same as `none`, which turns thinking off)\n",
reasoning::OMIT
));
out.push_str(
"note: `/reasoning high` is this session; `--global high` writes config.toml; `default` \n\
drops the session override; `show` · `hide` · `clamp <n>` change what is drawn",
);
out
}
pub struct Live {
pub dial: eclipse_core::reasoning::Shared,
pub config: Option<std::path::PathBuf>,
pub profile: Option<String>,
pub display: Mode,
}
impl Live {
pub fn new(
dial: eclipse_core::reasoning::Shared,
config: Option<std::path::PathBuf>,
profile: Option<String>,
) -> Self {
Self {
dial,
config,
profile,
display: Mode::Folded,
}
}
#[cfg(test)]
pub fn bare(dial: eclipse_core::reasoning::Shared) -> Self {
Self::new(dial, None, None)
}
pub fn apply(
&mut self,
arg: &str,
describe: &dyn Fn(Option<&str>) -> String,
now: &dyn Fn() -> InForce,
) -> Result<String, String> {
match parse(arg)? {
Change::Report => Ok(report(&now(), self.display)),
Change::Effort(level) => {
self.dial.set_session(Some(level.clone()));
Ok(format!(
"effort: {level}\n {}\nnote: this session only — `--global {level}` writes \
config.toml and starts the next process with it",
describe(Some(&level))
))
}
Change::Global(level) => {
let Some(path) = self.config.clone() else {
return Err(
"no config file to write: this session was started without one".to_string(),
);
};
crate::settings_cli::set_one(
&path,
self.profile.as_deref(),
"provider.reasoning_effort",
&level,
)?;
self.dial.set_session(Some(level.clone()));
Ok(format!(
"effort: {level} — written to {}, and in force here\n {}",
path.display(),
describe(Some(&level))
))
}
Change::Reset => {
self.dial.clear_session();
let now = now();
let tail = match (self.dial.configured(), now.by_default) {
(Some(_), _) => "config.toml is in charge".to_string(),
(None, true) => format!(
"nothing is configured, so `{}` is what this backend sends by default",
now.label
),
(None, false) => format!(
"nothing is configured and this backend declares no default, so {}",
reasoning::NOT_SENT
),
};
Ok(format!(
"effort: {} — the session override is gone; {tail}",
now.label
))
}
Change::Display(mode) => {
self.display = mode;
Ok(match mode {
Mode::Hidden => {
"reasoning: hidden — no block is drawn; it is still stored in the session"
.to_string()
}
Mode::Full => "reasoning: shown whole — never folded".to_string(),
Mode::Folded => "reasoning: folded to a preview with a count".to_string(),
Mode::Clamp(n) => {
format!("reasoning: folded, previewing {n} characters and an ellipsis")
}
})
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use eclipse_core::reasoning::Dial;
#[test]
fn one_word_is_a_level_and_the_display_words_are_their_own() {
assert_eq!(parse("high"), Ok(Change::Effort("high".into())));
assert_eq!(parse(" HIGH "), Ok(Change::Effort("high".into())));
assert_eq!(parse(""), Ok(Change::Report));
for (word, mode) in [
("show", Mode::Full),
("full", Mode::Full),
("hide", Mode::Hidden),
("fold", Mode::Folded),
("folded", Mode::Folded),
("clamp 200", Mode::Clamp(200)),
] {
assert_eq!(parse(word), Ok(Change::Display(mode)), "{word}");
}
assert_eq!(parse("default"), Ok(Change::Reset));
assert_eq!(parse("--global high"), Ok(Change::Global("high".into())));
}
#[test]
fn omit_is_a_word_slash_reasoning_accepts() {
assert_eq!(parse("omit"), Ok(Change::Effort("omit".into())));
assert_eq!(parse(" OMIT "), Ok(Change::Effort("omit".into())));
assert_eq!(parse("--global omit"), Ok(Change::Global("omit".into())));
let shown = report(
&InForce {
label: "not sent".into(),
in_force: "not sent (this session; config.toml says medium)".into(),
session: true,
by_default: false,
resolved: "not sent: asked for no field on this route".into(),
},
Mode::Folded,
);
assert!(shown.contains("omit"), "{shown}");
assert!(
shown.contains("not the same as `none`"),
"the two words are told apart where a person picks one: {shown}"
);
}
#[test]
fn a_word_it_does_not_know_is_refused_with_the_ladder() {
let why = parse("turbo").unwrap_err();
assert!(why.contains("turbo"), "{why}");
assert!(why.contains("xhigh"), "the ladder is spelled: {why}");
assert!(
parse("").is_ok(),
"no argument is the report, not a refusal"
);
assert!(parse("clamp").unwrap_err().contains("clamp 200"));
assert!(parse("clamp 0").unwrap_err().contains("positive"));
assert!(parse("clamp lots").unwrap_err().contains("lots"));
assert!(parse("--global").unwrap_err().contains("needs a level"));
}
fn report_of(dial: &Dial, default: Option<&str>) -> InForce {
dial.in_force_report(default)
}
#[test]
fn the_report_names_the_session_override_only_when_there_is_one() {
let dial = Dial::new(Some("low".into()));
let mut quiet = report_of(&dial, None);
quiet.resolved = "sends low".into();
let quiet = report(&quiet, Mode::Folded);
assert!(quiet.contains("effort: low\n"), "{quiet}");
assert!(
!quiet.contains("(this session"),
"the steady state stays quiet — the note at the bottom is instructions, not state: \
{quiet}"
);
dial.set_session(Some("high".into()));
let loud = report(&report_of(&dial, None), Mode::Folded);
assert!(
loud.contains("effort: high (this session; config.toml says low)"),
"{loud}"
);
assert!(loud.contains("display folded"), "{loud}");
assert!(loud.contains("clamp <n>"), "{loud}");
}
#[test]
fn the_backend_sentence_comes_from_the_policy() {
fn say(
policy: Option<reasoning::Policy>,
) -> (impl Fn(Option<&str>) -> String, impl Fn() -> InForce) {
let policy = std::sync::Arc::new(policy);
let describe = {
let policy = policy.clone();
move |level: Option<&str>| match policy.as_ref() {
Some(policy) => policy.describe(level),
None => "sent as-is (this backend declares no reasoning control)".to_string(),
}
};
let now = move || InForce {
resolved: match policy.as_ref() {
Some(policy) => policy.describe(None),
None => "sent as-is (this backend declares no reasoning control)".to_string(),
},
..InForce::default()
};
(describe, now)
}
let policy = reasoning::Policy::llamacpp();
let mut clamped = Live::bare(std::sync::Arc::new(Dial::new(None)));
let (describe, now) = say(Some(policy));
let said = clamped.apply("xhigh", &describe, &now).unwrap();
assert!(said.contains("effort: xhigh"), "{said}");
assert!(said.contains("xhigh → sends high"), "{said}");
assert!(said.contains("--global xhigh"), "{said}");
let off_only = reasoning::Policy {
field: "reasoning_effort".into(),
levels: Vec::new(),
off: Some("none".into()),
..Default::default()
};
let (describe, now) = say(Some(off_only));
let mut said = Live::bare(std::sync::Arc::new(Dial::new(None)))
.apply("high", &describe, &now)
.unwrap();
assert!(said.contains("no levels"), "{said}");
let (describe, now) = say(None);
said = Live::bare(std::sync::Arc::new(Dial::new(None)))
.apply("high", &describe, &now)
.unwrap();
assert!(said.contains("sent as-is"), "{said}");
}
#[test]
fn an_unset_effort_says_nothing_is_sent_rather_than_naming_a_default() {
let dial = Dial::new(None);
let mut report = dial.in_force_report(None);
report.resolved = "not sent: nothing asked and this backend declares no default".into();
let said = super::report(&report, Mode::Hidden);
assert!(said.contains("effort: not sent\n"), "{said}");
assert!(
said.contains("not sent: nothing asked and this backend declares no default"),
"the backend's reason is the sentence: {said}"
);
assert!(said.contains("display hidden"), "{said}");
let shipped = dial.in_force_report(Some(reasoning::SHIPPED_DEFAULT));
let said = super::report(&shipped, Mode::Hidden);
assert!(
said.contains("effort: medium (this backend's default; config.toml sets nothing)"),
"{said}"
);
}
}