1use crate::app::{apply_model, apply_reasoning, apply_setting, AppState};
15use eclipse_core::commands::{self, Command, Front};
16
17#[derive(Debug, Clone)]
20pub struct Answer {
21 pub text: String,
22 pub refused: bool,
23 pub clear_session: bool,
24 pub yolo: Option<bool>,
27}
28
29impl Answer {
30 fn said(text: impl Into<String>) -> Self {
31 Self {
32 text: text.into(),
33 refused: false,
34 clear_session: false,
35 yolo: None,
36 }
37 }
38
39 pub(crate) fn refused(text: impl Into<String>) -> Self {
40 Self {
41 text: text.into(),
42 refused: true,
43 clear_session: false,
44 yolo: None,
45 }
46 }
47}
48
49pub fn bang_refusal(line: &str) -> Option<Answer> {
65 if !line.trim_start().starts_with('!') {
66 return None;
67 }
68 Some(Answer::refused(
69 "`!command` runs a shell in a terminal and nowhere else — nothing was run here. A `!` line \
70 is refused rather than sent on, because sending it would turn \"run this\" into \"ask the \
71 model about this\". Type it in the terminal, or send it without the `!` to ask about it.",
72 ))
73}
74
75pub async fn serve(st: &AppState, command: &Command, arg: &str, session: Option<&str>) -> Answer {
78 let arg = arg.trim();
79 match command.name {
80 "/help" => Answer::said(commands::help(Front::Web)),
83 "/new" => Answer {
86 text: "a new session starts with the next message".to_string(),
87 refused: false,
88 clear_session: true,
89 yolo: None,
90 },
91 "/id" => Answer::said(match session.filter(|s| !s.is_empty()) {
92 Some(id) => id.to_string(),
93 None => "(none yet — the next message opens one)".to_string(),
94 }),
95 "/model" if st.agent.is_none() => Answer::refused(crate::app::unconfigured(st)),
99 "/model" => match arg.is_empty() {
100 true => Answer::said(model_readout(st)),
101 false => match apply_model(st, Some(arg.to_string())).await {
102 Ok(answer) => Answer::said(format!(
103 "model: {} (the next turn uses it; config.toml is not touched)",
104 answer["model"].as_str().unwrap_or("?")
105 )),
106 Err((_, why)) => Answer::refused(why),
107 },
108 },
109 "/goal" => match session.filter(|s| !s.is_empty()) {
113 Some(id) => {
114 let now = eclipse_core::session::now_ms() as i64;
115 match eclipse_core::goals::manage(&st.store, id, arg, now) {
116 Ok(said) => Answer::said(said),
117 Err(why) => Answer::refused(format!("{why:#}")),
118 }
119 }
120 None => Answer::said(
121 "no session yet — send a message first, then `/goal <text>` sets a standing goal \
122 for it",
123 ),
124 },
125 "/loop" => match crate::loops_gateway::manage(st, session, arg) {
128 Ok(said) => Answer::said(said),
129 Err(why) => Answer::refused(why),
130 },
131 "/reasoning" => match arg.is_empty() {
132 true => Answer::said(reasoning_readout(st)),
133 false => {
134 let level = if arg == "default" {
135 None
136 } else {
137 Some(arg.to_string())
138 };
139 match apply_reasoning(st, level).await {
140 Ok(answer) => Answer::said(reasoning_line(&answer)),
141 Err((_, why)) => Answer::refused(why),
142 }
143 }
144 },
145 "/yolo" => match st.yolo.apply(arg) {
149 Ok(mut said) => {
150 let unasked = st.unasked.load(std::sync::atomic::Ordering::Relaxed);
153 if unasked > 0 {
154 said.push_str(&format!(
155 "\n\n{} tool call(s) have run in this dashboard without a card.",
156 unasked
157 ));
158 }
159 Answer {
160 yolo: Some(st.yolo.on()),
161 ..Answer::said(said)
162 }
163 }
164 Err(why) => Answer::refused(why),
165 },
166 "/status" => Answer::said(status_readout(st, session)),
167 "/settings" => Answer::said(settings_readout(st)),
168 "/set" => {
169 let Some((key, value)) = split_set(arg) else {
170 return Answer::refused("usage: /set <key> <value> — the keys are in /settings");
171 };
172 match apply_setting(st, key, Some(value)).await {
173 Ok(setting) => Answer::said(format!(
174 "{} = {} — written; the next run uses it",
175 setting["key"].as_str().unwrap_or(key),
176 setting["value"].as_str().unwrap_or(value)
177 )),
178 Err((_, why)) => Answer::refused(why),
179 }
180 }
181 "/cron" => Answer::said(cron_readout(st)),
182 "/compress" => match st.agent.clone() {
185 Some(agent) => {
186 agent.compress_now();
187 Answer::said(
188 "compacting: the older turns are replaced with the handoff on the next request",
189 )
190 }
191 None => Answer::refused(crate::app::unconfigured(st)),
192 },
193 "/archive" => {
198 let store = st.store.clone();
199 match arg {
200 "list" => match store.list_with_archived() {
201 Err(e) => Answer::refused(format!("cannot read the archive: {e}")),
206 Ok(listed) => {
207 let filed: Vec<_> = listed.iter().filter(|s| s.archived).collect();
208 if filed.is_empty() {
209 Answer::said("nothing is archived: every session is in the list")
210 } else {
211 let mut out = format!(
212 "{} archived session(s) — out of the list, still in the find box:",
213 filed.len()
214 );
215 for s in filed {
216 out.push_str(&format!("\n{} · {}", s.id, s.label()));
217 }
218 Answer::said(out)
219 }
220 }
221 },
222 "off" => match session.filter(|id| !id.is_empty()) {
223 None => Answer::refused("no session is open yet: there is nothing to put back"),
224 Some(id) => match store.set_archived(id, false) {
225 Ok(()) => Answer::said(format!(
226 "{id} is back in the list, and a prune may take it again"
227 )),
228 Err(e) => Answer::refused(e.to_string()),
229 },
230 },
231 "" => match session.filter(|id| !id.is_empty()) {
232 None => Answer::refused("no session is open yet: the next message opens one"),
233 Some(id) => match store.set_archived(id, true) {
234 Ok(()) => Answer::said(format!(
235 "{id} is out of the list and still in the find box — `/archive off` \
236 puts it back"
237 )),
238 Err(e) => Answer::refused(e.to_string()),
239 },
240 },
241 other => Answer::refused(format!("/archive takes `list` or `off`, not {other:?}")),
242 }
243 }
244 other => Answer::refused(format!(
248 "{other} has no implementation in the dashboard — that is a bug, not a refusal"
249 )),
250 }
251}
252
253fn split_set(arg: &str) -> Option<(&str, &str)> {
256 let (key, value) = arg.split_once(char::is_whitespace)?;
257 let value = value.trim();
258 (!key.is_empty() && !value.is_empty()).then_some((key, value))
259}
260
261fn model_readout(st: &AppState) -> String {
262 let current = st.current_model().unwrap_or_else(|| "(none)".into());
263 let configured = st.configured_model().unwrap_or_else(|| "(none)".into());
264 format!(
265 "model: {current} (configured: {configured}) — the picker in the stats row lists what the \
266 endpoint serves"
267 )
268}
269
270fn reasoning_line(answer: &serde_json::Value) -> String {
272 let effort = answer["effort"].as_str().unwrap_or("?");
273 let detail = answer["effort_detail"].as_str().unwrap_or("");
274 format!("effort: {effort} — {detail}")
275}
276
277fn reasoning_readout(st: &AppState) -> String {
278 let Some(agent) = st.agent.as_ref() else {
279 return crate::app::unconfigured(st);
280 };
281 let report = agent.reasoning_report();
282 let mut out = format!("effort: {} — {}", report.label, report.sentence());
283 match agent.reasoning_control() {
284 Some(eclipse_core::provider::Reasoning::Policy(policy)) => {
285 let words = policy.vocabulary();
286 if !words.is_empty() {
287 out.push_str(&format!("\nthis route takes: {}", words.join(" · ")));
288 }
289 }
290 Some(eclipse_core::provider::Reasoning::Off) => {
291 out.push_str("\nno reasoning control on this model");
292 }
293 Some(eclipse_core::provider::Reasoning::Undeclared) => {
294 out.push_str("\nthis backend declares no reasoning control");
295 }
296 None => {}
297 }
298 out
299}
300
301fn status_readout(st: &AppState, session: Option<&str>) -> String {
305 let model = st.current_model().unwrap_or_else(|| "(none)".into());
306 let window = st.agent.as_ref().map(|a| a.context_window()).unwrap_or(0);
307 let mut out = format!(
308 "model: {model}\ncontext window: {}",
309 match window {
310 0 => "not stated by the endpoint".to_string(),
311 n => format!("{n} tokens"),
312 }
313 );
314 if let Some(agent) = st.agent.as_ref() {
315 out.push_str(&format!(
316 "\neffort: {} — {}",
317 agent.reasoning_report().label,
318 agent.reasoning_report().sentence()
319 ));
320 out.push_str(&format!("\nmax iterations: {}", agent.max_iterations()));
321 }
322 out.push_str(&format!(
323 "\nsession: {}",
324 session.filter(|s| !s.is_empty()).unwrap_or("(none yet)")
325 ));
326 out
327}
328
329fn settings_readout(st: &AppState) -> String {
332 let cfg = match st.reload_config() {
333 Ok(cfg) => cfg,
334 Err(why) => return why,
335 };
336 let mut out = format!(
337 "{} key(s), profile {}\n",
338 cfg.settings().len(),
339 cfg.profile_name()
340 );
341 for s in cfg.settings() {
342 let shown = if s.secret {
343 if s.value.is_some() {
344 "(set)".to_string()
345 } else {
346 "(not set)".to_string()
347 }
348 } else {
349 s.rendered()
350 };
351 out.push_str(&format!(
352 "{} = {}{}\n",
353 s.path(),
354 shown,
355 if s.is_default() { " (default)" } else { "" }
356 ));
357 }
358 out.push_str("\n/set <key> <value> writes one");
359 out
360}
361
362fn cron_readout(st: &AppState) -> String {
369 let Some(root) = st.cron_root.as_ref() else {
370 return "this dashboard was started without an install root, so it has no cron state"
371 .to_string();
372 };
373 let now = eclipse_core::session::now_ms() as i64;
374 let jobs = match eclipse_core::cron::views(root, now) {
375 Ok(jobs) => jobs,
376 Err(e) => {
377 return format!(
378 "{} could not be read: {e}",
379 eclipse_core::cron::jobs_path(root).display()
380 )
381 }
382 };
383 if jobs.is_empty() {
384 return format!(
385 "nothing scheduled — {} holds no jobs",
386 eclipse_core::cron::jobs_path(root).display()
387 );
388 }
389 let width = jobs.iter().map(|j| j.name.len()).max().unwrap_or(4).max(4);
390 let mut out = format!("{:<width$} {:<18} next", "job", "schedule");
391 for job in &jobs {
392 let next = match (job.enabled, job.next_ms) {
393 (false, _) => "— (disabled)".to_string(),
394 (true, Some(ms)) => {
395 let (_, _, _, h, m) = eclipse_core::cron::local_parts(ms);
396 format!("{h:02}:{m:02}")
397 }
398 (true, None) => "—".to_string(),
399 };
400 out.push_str(&format!(
401 "\n{:<width$} {:<18} {next}",
402 job.name, job.schedule
403 ));
404 if let Some(outcome) = &job.last_outcome {
405 out.push_str(&format!(", last {outcome}"));
406 }
407 }
408 out.push_str("\nthe cron pane runs, edits and removes them");
409 out
410}