lib.rs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. use runtime::{compact_session, CompactionConfig, Session};
  2. #[derive(Debug, Clone, PartialEq, Eq)]
  3. pub struct CommandManifestEntry {
  4. pub name: String,
  5. pub source: CommandSource,
  6. }
  7. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  8. pub enum CommandSource {
  9. Builtin,
  10. InternalOnly,
  11. FeatureGated,
  12. }
  13. #[derive(Debug, Clone, Default, PartialEq, Eq)]
  14. pub struct CommandRegistry {
  15. entries: Vec<CommandManifestEntry>,
  16. }
  17. impl CommandRegistry {
  18. #[must_use]
  19. pub fn new(entries: Vec<CommandManifestEntry>) -> Self {
  20. Self { entries }
  21. }
  22. #[must_use]
  23. pub fn entries(&self) -> &[CommandManifestEntry] {
  24. &self.entries
  25. }
  26. }
  27. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  28. pub struct SlashCommandSpec {
  29. pub name: &'static str,
  30. pub summary: &'static str,
  31. pub argument_hint: Option<&'static str>,
  32. }
  33. const SLASH_COMMAND_SPECS: &[SlashCommandSpec] = &[
  34. SlashCommandSpec {
  35. name: "help",
  36. summary: "Show available slash commands",
  37. argument_hint: None,
  38. },
  39. SlashCommandSpec {
  40. name: "status",
  41. summary: "Show current session status",
  42. argument_hint: None,
  43. },
  44. SlashCommandSpec {
  45. name: "compact",
  46. summary: "Compact local session history",
  47. argument_hint: None,
  48. },
  49. SlashCommandSpec {
  50. name: "model",
  51. summary: "Show or switch the active model",
  52. argument_hint: Some("[model]"),
  53. },
  54. SlashCommandSpec {
  55. name: "permissions",
  56. summary: "Show or switch the active permission mode",
  57. argument_hint: Some("[read-only|workspace-write|danger-full-access]"),
  58. },
  59. SlashCommandSpec {
  60. name: "clear",
  61. summary: "Start a fresh local session",
  62. argument_hint: None,
  63. },
  64. SlashCommandSpec {
  65. name: "cost",
  66. summary: "Show cumulative token usage for this session",
  67. argument_hint: None,
  68. },
  69. SlashCommandSpec {
  70. name: "resume",
  71. summary: "Load a saved session into the REPL",
  72. argument_hint: Some("<session-path>"),
  73. },
  74. SlashCommandSpec {
  75. name: "config",
  76. summary: "Inspect discovered Claude config files",
  77. argument_hint: None,
  78. },
  79. ];
  80. #[derive(Debug, Clone, PartialEq, Eq)]
  81. pub enum SlashCommand {
  82. Help,
  83. Status,
  84. Compact,
  85. Model { model: Option<String> },
  86. Permissions { mode: Option<String> },
  87. Clear,
  88. Cost,
  89. Resume { session_path: Option<String> },
  90. Config,
  91. Unknown(String),
  92. }
  93. impl SlashCommand {
  94. #[must_use]
  95. pub fn parse(input: &str) -> Option<Self> {
  96. let trimmed = input.trim();
  97. if !trimmed.starts_with('/') {
  98. return None;
  99. }
  100. let mut parts = trimmed.trim_start_matches('/').split_whitespace();
  101. let command = parts.next().unwrap_or_default();
  102. Some(match command {
  103. "help" => Self::Help,
  104. "status" => Self::Status,
  105. "compact" => Self::Compact,
  106. "model" => Self::Model {
  107. model: parts.next().map(ToOwned::to_owned),
  108. },
  109. "permissions" => Self::Permissions {
  110. mode: parts.next().map(ToOwned::to_owned),
  111. },
  112. "clear" => Self::Clear,
  113. "cost" => Self::Cost,
  114. "resume" => Self::Resume {
  115. session_path: parts.next().map(ToOwned::to_owned),
  116. },
  117. "config" => Self::Config,
  118. other => Self::Unknown(other.to_string()),
  119. })
  120. }
  121. }
  122. #[must_use]
  123. pub fn slash_command_specs() -> &'static [SlashCommandSpec] {
  124. SLASH_COMMAND_SPECS
  125. }
  126. #[must_use]
  127. pub fn render_slash_command_help() -> String {
  128. let mut lines = vec!["Available commands:".to_string()];
  129. for spec in slash_command_specs() {
  130. let name = match spec.argument_hint {
  131. Some(argument_hint) => format!("/{} {}", spec.name, argument_hint),
  132. None => format!("/{}", spec.name),
  133. };
  134. lines.push(format!(" {name:<20} {}", spec.summary));
  135. }
  136. lines.join("\n")
  137. }
  138. #[derive(Debug, Clone, PartialEq, Eq)]
  139. pub struct SlashCommandResult {
  140. pub message: String,
  141. pub session: Session,
  142. }
  143. #[must_use]
  144. pub fn handle_slash_command(
  145. input: &str,
  146. session: &Session,
  147. compaction: CompactionConfig,
  148. ) -> Option<SlashCommandResult> {
  149. match SlashCommand::parse(input)? {
  150. SlashCommand::Compact => {
  151. let result = compact_session(session, compaction);
  152. let message = if result.removed_message_count == 0 {
  153. "Compaction skipped: session is below the compaction threshold.".to_string()
  154. } else {
  155. format!(
  156. "Compacted {} messages into a resumable system summary.",
  157. result.removed_message_count
  158. )
  159. };
  160. Some(SlashCommandResult {
  161. message,
  162. session: result.compacted_session,
  163. })
  164. }
  165. SlashCommand::Help => Some(SlashCommandResult {
  166. message: render_slash_command_help(),
  167. session: session.clone(),
  168. }),
  169. SlashCommand::Status
  170. | SlashCommand::Model { .. }
  171. | SlashCommand::Permissions { .. }
  172. | SlashCommand::Clear
  173. | SlashCommand::Cost
  174. | SlashCommand::Resume { .. }
  175. | SlashCommand::Config
  176. | SlashCommand::Unknown(_) => None,
  177. }
  178. }
  179. #[cfg(test)]
  180. mod tests {
  181. use super::{
  182. handle_slash_command, render_slash_command_help, slash_command_specs, SlashCommand,
  183. };
  184. use runtime::{CompactionConfig, ContentBlock, ConversationMessage, MessageRole, Session};
  185. #[test]
  186. fn parses_supported_slash_commands() {
  187. assert_eq!(SlashCommand::parse("/help"), Some(SlashCommand::Help));
  188. assert_eq!(SlashCommand::parse(" /status "), Some(SlashCommand::Status));
  189. assert_eq!(
  190. SlashCommand::parse("/model claude-opus"),
  191. Some(SlashCommand::Model {
  192. model: Some("claude-opus".to_string()),
  193. })
  194. );
  195. assert_eq!(
  196. SlashCommand::parse("/model"),
  197. Some(SlashCommand::Model { model: None })
  198. );
  199. assert_eq!(
  200. SlashCommand::parse("/permissions read-only"),
  201. Some(SlashCommand::Permissions {
  202. mode: Some("read-only".to_string()),
  203. })
  204. );
  205. assert_eq!(SlashCommand::parse("/clear"), Some(SlashCommand::Clear));
  206. assert_eq!(SlashCommand::parse("/cost"), Some(SlashCommand::Cost));
  207. assert_eq!(
  208. SlashCommand::parse("/resume session.json"),
  209. Some(SlashCommand::Resume {
  210. session_path: Some("session.json".to_string()),
  211. })
  212. );
  213. assert_eq!(SlashCommand::parse("/config"), Some(SlashCommand::Config));
  214. }
  215. #[test]
  216. fn renders_help_from_shared_specs() {
  217. let help = render_slash_command_help();
  218. assert!(help.contains("/help"));
  219. assert!(help.contains("/status"));
  220. assert!(help.contains("/compact"));
  221. assert!(help.contains("/model [model]"));
  222. assert!(help.contains("/permissions [read-only|workspace-write|danger-full-access]"));
  223. assert!(help.contains("/clear"));
  224. assert!(help.contains("/cost"));
  225. assert!(help.contains("/resume <session-path>"));
  226. assert!(help.contains("/config"));
  227. assert_eq!(slash_command_specs().len(), 9);
  228. }
  229. #[test]
  230. fn compacts_sessions_via_slash_command() {
  231. let session = Session {
  232. version: 1,
  233. messages: vec![
  234. ConversationMessage::user_text("a ".repeat(200)),
  235. ConversationMessage::assistant(vec![ContentBlock::Text {
  236. text: "b ".repeat(200),
  237. }]),
  238. ConversationMessage::tool_result("1", "bash", "ok ".repeat(200), false),
  239. ConversationMessage::assistant(vec![ContentBlock::Text {
  240. text: "recent".to_string(),
  241. }]),
  242. ],
  243. };
  244. let result = handle_slash_command(
  245. "/compact",
  246. &session,
  247. CompactionConfig {
  248. preserve_recent_messages: 2,
  249. max_estimated_tokens: 1,
  250. },
  251. )
  252. .expect("slash command should be handled");
  253. assert!(result.message.contains("Compacted 2 messages"));
  254. assert_eq!(result.session.messages[0].role, MessageRole::System);
  255. }
  256. #[test]
  257. fn help_command_is_non_mutating() {
  258. let session = Session::new();
  259. let result = handle_slash_command("/help", &session, CompactionConfig::default())
  260. .expect("help command should be handled");
  261. assert_eq!(result.session, session);
  262. assert!(result.message.contains("Available commands:"));
  263. }
  264. #[test]
  265. fn ignores_unknown_or_runtime_bound_slash_commands() {
  266. let session = Session::new();
  267. assert!(handle_slash_command("/unknown", &session, CompactionConfig::default()).is_none());
  268. assert!(handle_slash_command("/status", &session, CompactionConfig::default()).is_none());
  269. assert!(
  270. handle_slash_command("/model claude", &session, CompactionConfig::default()).is_none()
  271. );
  272. assert!(handle_slash_command(
  273. "/permissions read-only",
  274. &session,
  275. CompactionConfig::default()
  276. )
  277. .is_none());
  278. assert!(handle_slash_command("/clear", &session, CompactionConfig::default()).is_none());
  279. assert!(handle_slash_command("/cost", &session, CompactionConfig::default()).is_none());
  280. assert!(handle_slash_command(
  281. "/resume session.json",
  282. &session,
  283. CompactionConfig::default()
  284. )
  285. .is_none());
  286. assert!(handle_slash_command("/config", &session, CompactionConfig::default()).is_none());
  287. }
  288. }
备用站点 当前处于降级运行的备用站点,仅供应急访问,数据和功能可能不是最新。