diff --git a/crates/harness-cli/src/host/application/controller.rs b/crates/harness-cli/src/host/application/controller.rs index 72956bfb..a1b9d015 100644 --- a/crates/harness-cli/src/host/application/controller.rs +++ b/crates/harness-cli/src/host/application/controller.rs @@ -1250,6 +1250,18 @@ impl InteractiveController { /// has to be: a key must never act on a list the user cannot see. The plain /// renderer draws no menu, and a panel or picker that owns the keyboard /// replaces it, so neither may consume an arrow or an Enter for it. + /// The highlight is on a flag the menu offered on a blank word, and the + /// person did not move it there. + fn offered_flag(&self) -> bool { + !self.editor.suggestion_moved() + && self.editor.display_buffer().ends_with(' ') + && self + .editor + .suggestions() + .get(self.editor.suggestion_selected()) + .is_some_and(|item| item.label.starts_with('-')) + } + fn suggestion_menu_open(&self) -> bool { !self.plain && self.pending_approval.is_none() @@ -1621,6 +1633,12 @@ impl InteractiveController { // through it, as prime-agent's and Claude Code's panels are, and the // composer is not being typed into while one is up. Escape still // closes it, which is what acceptance U09 asserts. + // Typing means the person is done reading: the panel closes and + // the key goes to the composer, which shows its cursor and its + // menu again (`/features`, then `/` opens the command menu). + if matches!(key, Key::Char(character) if !character.is_control()) { + let _ = self.editor.take_overlay(); + } let scrolled = match key { Key::Up => self.editor.scroll_overlay(-1), Key::Down => self.editor.scroll_overlay(1), @@ -1742,12 +1760,21 @@ impl InteractiveController { self.editor.accept_suggestion(); return vec![Effect::Redraw]; } - Key::Enter => { + // A flag the menu offers on a blank word is optional: Enter + // runs the line as it is (`/new ` starts a session) unless the + // person moved the highlight to the flag. A command whose + // blank offers nothing (`/resume`, `/learn`) runs once its + // name is completed. + Key::Enter if !self.offered_flag() => { let embedded = self.editor.suggestion_is_embedded(); self.editor.accept_suggestion(); + let line = self.editor.display_buffer(); + let whole = line + .strip_suffix(' ') + .is_some_and(super::commands::runs_bare); if embedded - || self.editor.display_buffer().ends_with(' ') - || !self.editor.suggestions().is_empty() + || (!whole + && (line.ends_with(' ') || !self.editor.suggestions().is_empty())) { return vec![Effect::Redraw]; } @@ -10730,8 +10757,8 @@ Command: \"npm run build\"" "plain mode must not complete a list it never showed: {lines}" ); - // TUI with a panel open: the panel owns the frame, so the same draft is - // submitted rather than silently completed into a list nobody can see. + // TUI with a panel open: typing closes it, so the menu that answers + // the draft is the one on screen. let mut tui = tui_bench(true); let _ = tui.controller.boot_lines(); let _ = submit_text(&mut tui.controller, "/help"); @@ -10741,9 +10768,14 @@ Command: \"npm run build\"" ); type_text(&mut tui.controller, "/he"); assert!( - !tui.controller.ui_state().suggestions.is_empty(), - "the editor still holds the candidates; the frame is what hides them" + tui.controller.ui_state().modal.is_none(), + "typing closed it" + ); + assert!( + tui.controller.suggestion_menu_open(), + "the menu for the draft is drawn" ); + let _ = tui.controller.handle_key(Key::Esc); let _ = tui.controller.handle_key(Key::Enter); assert!( tui.controller @@ -14426,6 +14458,87 @@ Command: \"npm run build\"" assert!(!harness.controller.editor.suggestions().is_empty()); } + /// A panel open (`/features`) does not keep the composer from being typed + /// into: a typed key closes it, and the menu answers that key. + #[test] + fn typing_closes_a_reference_panel_and_reaches_the_composer() { + let harness = tui_bench(true); + let mut controller = harness.controller; + let _ = controller.boot_lines(); + controller + .editor + .open_overlay("/features", vec!["no feature list".to_owned()]); + let _ = controller.handle_key(Key::Down); + assert!(controller.editor.overlay().is_some(), "arrows scroll it"); + type_text(&mut controller, "/fe"); + assert!(controller.editor.overlay().is_none()); + assert_eq!(controller.editor.text(), "/fe"); + assert!(controller.suggestion_menu_open(), "the menu is back"); + } + + /// A command whose argument is optional shows what it takes and runs on + /// Enter, typed in full or completed from its beginning. + #[test] + fn an_optional_argument_command_runs_on_enter() { + let harness = tui_bench(true); + let mut controller = harness.controller; + let _ = controller.boot_lines(); + type_text(&mut controller, "/resume"); + assert!( + controller.editor.suggestions()[0] + .label + .starts_with("/resume ["), + "{:?}", + controller.editor.suggestions() + ); + let _ = controller.handle_key(Key::Enter); + assert_eq!(controller.editor.text(), "", "Enter ran /resume"); + type_text(&mut controller, "/resu"); + let _ = controller.handle_key(Key::Enter); + assert_eq!( + controller.editor.text(), + "", + "Enter completed and ran /resume" + ); + } + + /// A blank word offers the command's flags; Enter runs the line as it is, + /// and a flag the person moves to is what Enter takes. + #[test] + fn a_blank_word_offers_the_flags_and_enter_runs_the_line() { + let harness = tui_bench(true); + let mut controller = harness.controller; + let _ = controller.boot_lines(); + type_text(&mut controller, "/refine "); + assert!( + controller + .editor + .suggestions() + .iter() + .any(|item| item.label.starts_with("--rollback")), + "{:?}", + controller.editor.suggestions() + ); + let _ = controller.handle_key(Key::Enter); + assert_eq!(controller.editor.text(), "", "Enter ran /refine as typed"); + type_text(&mut controller, "/refine "); + let _ = controller.handle_key(Key::Down); + let _ = controller.handle_key(Key::Enter); + assert_eq!( + controller.editor.text(), + "/refine --rollback ", + "the flag moved to is taken" + ); + // `/new` shows its flags first; the second Enter starts the session. + controller.editor.set_text(""); + type_text(&mut controller, "/new"); + let _ = controller.handle_key(Key::Enter); + assert_eq!(controller.editor.text(), "/new "); + assert!(!controller.editor.suggestions().is_empty(), "its flags"); + let _ = controller.handle_key(Key::Enter); + assert_eq!(controller.editor.text(), "", "Enter ran /new"); + } + /// The person's way through the review queue: `/memory` lists the waiting /// changes, and typing the accept offers the action and then each id; /// Enter on an id accepts it, and the next menu no longer offers it. diff --git a/crates/harness-cli/src/host/integrations/mcp_oauth.rs b/crates/harness-cli/src/host/integrations/mcp_oauth.rs index 60d32b17..9f70a498 100644 --- a/crates/harness-cli/src/host/integrations/mcp_oauth.rs +++ b/crates/harness-cli/src/host/integrations/mcp_oauth.rs @@ -97,9 +97,25 @@ fn authorization_server_metadata_urls(issuer: &Url) -> Vec { /// The `resource_metadata` pointer of a `WWW-Authenticate` header. fn header_resource_metadata(value: &str) -> Option { + header_parameter(value, "resource_metadata") +} + +/// The `scope` a `WWW-Authenticate` header asks for (MCP's scope selection). +fn header_scope(value: &str) -> Option { + header_parameter(value, "scope").filter(|scope| !scope.trim().is_empty()) +} + +/// One quoted parameter of a `WWW-Authenticate` header, by its exact name. +fn header_parameter(value: &str, name: &str) -> Option { let lower = value.to_ascii_lowercase(); - let at = lower.find("resource_metadata")?; - let rest = value[at + "resource_metadata".len()..].trim_start(); + let at = lower.match_indices(name).map(|(at, _)| at).find(|&at| { + lower[..at] + .chars() + .next_back() + .is_none_or(|before| before == ',' || before.is_whitespace()) + && lower[at + name.len()..].trim_start().starts_with('=') + })?; + let rest = value[at + name.len()..].trim_start(); let rest = rest.strip_prefix('=')?.trim_start().strip_prefix('"')?; let mut out = String::new(); let mut chars = rest.chars(); @@ -264,15 +280,50 @@ fn discover_server(issuer: &str) -> Result { )) } -/// What discovery found: the server metadata, and the resource indicator -/// when the server publishes protected-resource metadata. -fn discover(url: &str) -> Result<(ServerMetadata, Option), String> { +/// What discovery found: the server metadata, the resource indicator when +/// the server publishes protected-resource metadata, and the scope to ask for. +struct Discovered { + metadata: ServerMetadata, + resource: Option, + scope: Option, +} + +/// MCP's scope selection: the scope the server's challenge names, else the +/// resource's own `scopes_supported`. The authorization server's list is the +/// whole server's and may hold scopes this client may not ask for (Vercel's +/// `ema_issuer:manage`, refused as `invalid_scope`); it is asked for only +/// when the server publishes no resource metadata. +fn chosen_scope( + challenge: Option, + resource_metadata: Option<&serde_json::Value>, + server: &ServerMetadata, +) -> Option { + let joined = |scopes: Vec| Some(scopes.join(" ")).filter(|scope| !scope.is_empty()); + challenge.or_else(|| match resource_metadata { + Some(value) => joined( + value + .get("scopes_supported") + .and_then(serde_json::Value::as_array) + .map(|scopes| { + scopes + .iter() + .filter_map(|scope| scope.as_str().map(str::to_owned)) + .collect() + }) + .unwrap_or_default(), + ), + None => server.scopes_supported.clone().and_then(joined), + }) +} + +fn discover(url: &str) -> Result { let resource_url = validated_url(url, "MCP server URL")?; // The probe never carries a token. - let pointer = http("GET", url, None, None) + let challenge = http("GET", url, None, None) .ok() - .and_then(|(_, authenticate, ..)| authenticate) - .and_then(|value| header_resource_metadata(&value)); + .and_then(|(_, authenticate, ..)| authenticate); + let pointer = challenge.as_deref().and_then(header_resource_metadata); + let challenge_scope = challenge.as_deref().and_then(header_scope); let candidate = match &pointer { Some(pointer) => validated_url(pointer, "resource_metadata")?.to_string(), None => resource_metadata_url(&resource_url), @@ -293,12 +344,21 @@ fn discover(url: &str) -> Result<(ServerMetadata, Option), String> { .ok_or_else(|| { "Protected-resource metadata has no authorization_servers".to_owned() })?; - Ok((discover_server(issuer)?, Some(resource))) + let metadata = discover_server(issuer)?; + Ok(Discovered { + scope: chosen_scope(challenge_scope, Some(&value), &metadata), + metadata, + resource: Some(resource), + }) + } + Ok(None) if pointer.is_none() => { + let metadata = discover_server(&resource_url.origin().ascii_serialization())?; + Ok(Discovered { + scope: chosen_scope(challenge_scope, None, &metadata), + metadata, + resource: None, + }) } - Ok(None) if pointer.is_none() => Ok(( - discover_server(&resource_url.origin().ascii_serialization())?, - None, - )), Ok(None) => Err(format!("GET {candidate} failed: 404")), Err(error) => Err(error), } @@ -497,7 +557,11 @@ pub fn login( progress: &dyn Fn(&str), ) -> Result<(), String> { progress(&format!("Discovering OAuth metadata for {server}...")); - let (metadata, resource) = discover(url)?; + let Discovered { + metadata, + resource, + scope: discovered_scope, + } = discover(url)?; let client_id = if let Some(client_id) = client_id { client_id.to_owned() } else { @@ -516,12 +580,7 @@ pub fn login( let redirect = redirect_uri(port); let scope = scopes .map(str::to_owned) - .or_else(|| { - metadata - .scopes_supported - .as_ref() - .map(|scopes| scopes.join(" ")) - }) + .or(discovered_scope) .unwrap_or_default(); let mut params = vec![ ("client_id", client_id.as_str()), @@ -677,8 +736,9 @@ mod tests { } use super::{ - authorization_server_metadata_urls, canonical_resource, code_from, - header_resource_metadata, resource_metadata_url, server_metadata, validated_url, + authorization_server_metadata_urls, canonical_resource, chosen_scope, code_from, + header_resource_metadata, header_scope, resource_metadata_url, server_metadata, + validated_url, }; use reqwest::Url; @@ -801,6 +861,58 @@ mod tests { ); } + #[test] + fn the_scope_is_the_challenge_s_then_the_resource_s_not_the_server_s() { + // Vercel: the authorization server lists a scope a client may not ask + // for; the resource asks for `openid` only. + let server = server_metadata( + &serde_json::json!({ + "issuer": "https://vercel.com", + "authorization_endpoint": "https://vercel.com/oauth/authorize", + "token_endpoint": "https://api.vercel.com/login/oauth/token", + "scopes_supported": ["openid", "email", "profile", "offline_access", "ema_issuer:manage"], + }), + "https://vercel.com", + ) + .expect("metadata"); + let resource = serde_json::json!({ + "resource": "https://mcp.vercel.com/", + "authorization_servers": ["https://vercel.com"], + "scopes_supported": ["openid"], + }); + assert_eq!( + chosen_scope(None, Some(&resource), &server).as_deref(), + Some("openid") + ); + let challenge = header_scope( + r#"Bearer error="insufficient_scope", scope="files:read files:write", resource_metadata="https://x/.well-known/oauth-protected-resource""#, + ); + assert_eq!(challenge.as_deref(), Some("files:read files:write")); + assert_eq!( + chosen_scope(challenge, Some(&resource), &server).as_deref(), + Some("files:read files:write") + ); + // Resource metadata without scopes asks for none. + let bare = + serde_json::json!({"resource": "https://x/", "authorization_servers": ["https://x"]}); + assert_eq!(chosen_scope(None, Some(&bare), &server), None); + // No resource metadata at all: the server's own list, as before. + assert!( + chosen_scope(None, None, &server) + .is_some_and(|scope| scope.starts_with("openid email")) + ); + // `resource_metadata` is not read as `scope`, nor the reverse. + assert_eq!( + header_scope(r#"Bearer resource_metadata="https://x/meta""#), + None + ); + assert_eq!( + header_resource_metadata(r#"Bearer scope="a", resource_metadata="https://x/meta""#) + .as_deref(), + Some("https://x/meta") + ); + } + #[test] fn metadata_and_redirects_are_checked() { let metadata = server_metadata( diff --git a/crates/harness-cli/src/host/presentation/input.rs b/crates/harness-cli/src/host/presentation/input.rs index 60a7d474..ab3b6c23 100644 --- a/crates/harness-cli/src/host/presentation/input.rs +++ b/crates/harness-cli/src/host/presentation/input.rs @@ -117,6 +117,9 @@ pub struct LineEditor { suggestion: Vec, /// Which candidate the highlight is on. suggestion_index: usize, + /// The person moved the highlight since the menu last changed: the row is + /// their choice, not the menu's first offer. + suggestion_moved: bool, /// Skills and prompt commands, offered beside the built-in commands. menu_commands: Vec, /// Argument values that change at run time (`/model`, `/login`). @@ -238,9 +241,16 @@ impl LineEditor { .saturating_add(delta.unsigned_abs() as usize) }; self.suggestion_index = next.min(last); + self.suggestion_moved = true; true } + /// Whether the person moved the highlight to the row it is on. + #[must_use] + pub const fn suggestion_moved(&self) -> bool { + self.suggestion_moved + } + /// Accept the highlighted candidate, as prime-agent does: a command that takes /// an argument gains a space, so the argument menu opens next. /// @@ -857,6 +867,7 @@ impl LineEditor { /// secret buffer never offers anything, whatever is pasted into it. fn refresh_suggestion(&mut self) { self.suggestion_index = 0; + self.suggestion_moved = false; self.suggestion.clear(); if self.secret { return; diff --git a/crates/harness-cli/src/host/protocols/commands.rs b/crates/harness-cli/src/host/protocols/commands.rs index ed589191..75f4b21f 100644 --- a/crates/harness-cli/src/host/protocols/commands.rs +++ b/crates/harness-cli/src/host/protocols/commands.rs @@ -538,6 +538,21 @@ fn suggest_names(buffer: &str, extra: &[MenuCommand]) -> Vec { rank(scored, query.is_empty()) } +/// Whether the command `name` alone is whole and its blank argument offers +/// nothing to choose: Enter on its name runs it (`/resume` opens the picker, +/// `/learn` learns) rather than stopping at a space with an empty menu. +#[must_use] +pub fn runs_bare(name: &str) -> bool { + let Some(command) = builtin(name) else { + return false; + }; + if !command.arguments.starts_with('[') { + return false; + } + let blank = slot(command.name, &[], &ArgumentOptions::new()); + blank.typed_only || (blank.values.is_empty() && blank.flags.is_empty()) +} + /// The rows for the word being typed after a command: the values its grammar /// allows there ([`slot`]), the best match first. fn suggest_arguments(name: &str, argument: &str, dynamic: &ArgumentOptions) -> Vec { @@ -564,7 +579,10 @@ fn suggest_arguments(name: &str, argument: &str, dynamic: &ArgumentOptions) -> V .to_owned() }; let mut options = slot.values; - if typed.starts_with('-') { + // Right after the command a blank offers its flags too (`/refine `); + // later a blank is the gap between words of free text, where a flag is + // offered only once its dash is typed. + if (typed.is_empty() && words.is_empty()) || typed.starts_with('-') { options.extend(slot.flags); } // A value already on the line is not offered again (a second id, a flag). @@ -596,7 +614,7 @@ fn suggest_arguments(name: &str, argument: &str, dynamic: &ArgumentOptions) -> V // A value that names more input after its first word completes to // that word and a space: the argument is not finished, so accepting // it must not submit (`/mcp add` alone has no server to add). - let takes_more = value.trim() != first; + let takes_more = slot.more || value.trim() != first; Some(( score, order, @@ -654,8 +672,9 @@ struct Slot { /// own placeholder after its first word (`accept ...`): the menu shows /// it whole, and choosing it types the first word and a space. values: Vec<(String, String)>, - /// Flags, offered once the word starts with `-`, as a shell offers them: - /// a blank word with Enter keeps running the command as it is. + /// Flags, offered after the values on the blank right after the command, + /// and once a word starts with `-`. A flag is optional: Enter on a blank + /// runs the line as it is, unless the person moved the highlight to one. flags: Vec<(String, String)>, /// The word may be free text (`/goal `): only a value it begins /// is offered, so a word of a sentence never turns into a subcommand. @@ -667,6 +686,14 @@ struct Slot { /// word of the description finds one (`flutter` finds the memory change /// about Flutter). by_description: bool, + /// More must follow a value here (`/heartbeat every 10m `): + /// choosing one types a space, and Enter does not run the line yet. + more: bool, +} + +/// `slot`, whose values more words must follow. +fn then_more(slot: Slot) -> Slot { + Slot { more: true, ..slot } } fn fixed(values: &[(&str, &str)]) -> Vec<(String, String)> { @@ -956,7 +983,7 @@ fn slot(name: &str, words: &[&str], dynamic: &ArgumentOptions) -> Slot { .filter(|word| !word.starts_with("--")) .collect(); match when.as_slice() { - [] => free( + [] => then_more(free( &[ ("in ", "once, after a delay: in 10m"), ("every ", "again and again: every 1h"), @@ -967,8 +994,10 @@ fn slot(name: &str, words: &[&str], dynamic: &ArgumentOptions) -> Slot { ("@monthly", "the first of every month"), ], DELIVERY, - ), - ["in" | "every" | "each"] if !last.starts_with("--") => free(INTERVALS, &[]), + )), + ["in" | "every" | "each"] if !last.starts_with("--") => { + then_more(free(INTERVALS, &[])) + } _ => Slot::default(), } } @@ -976,7 +1005,7 @@ fn slot(name: &str, words: &[&str], dynamic: &ArgumentOptions) -> Slot { &[("every ", "how often it runs (5m without it)")], DELIVERY, ), - ("/heartbeat", ["every" | "each"]) => free(INTERVALS, &[]), + ("/heartbeat", ["every" | "each"]) => then_more(free(INTERVALS, &[])), ("/heartbeat", ["every" | "each", _, rest @ ..]) if rest.iter().all(|word| word.starts_with("--")) => { @@ -1058,6 +1087,8 @@ fn slot(name: &str, words: &[&str], dynamic: &ArgumentOptions) -> Slot { .insert(0, ("latest".to_owned(), "the latest session".to_owned())); slot.flags = fixed(&[("--compact", "summarize it first")]); slot.free = true; + // A blank runs `/resume` as it is: the session picker. + slot.typed_only = true; slot } ("/fork", []) | ("/tree", ["label"]) => records(dynamic, values::TURNS), @@ -1311,7 +1342,7 @@ mod tests { // Argument completion, command by command. - use super::{MenuItem, SLASH_COMMANDS, matching, values}; + use super::{MenuItem, SLASH_COMMANDS, matching, runs_bare, values}; fn records(entries: &[(&'static str, &[(&str, &str)])]) -> ArgumentOptions { let mut dynamic = ArgumentOptions::new(); @@ -1446,8 +1477,13 @@ mod tests { values::REFINEMENTS, &[("refine_1700_a", "Tightened the memory digest · global")], )]); + assert_eq!( + heads("/refine ", &dynamic), + ["--global", "--rollback", "--curate", "--history"], + "right after the command its flags are offered" + ); assert!( - heads("/refine ", &dynamic).is_empty(), + heads("/refine tighten ", &dynamic).is_empty(), "instructions are free text" ); assert_eq!( @@ -1552,12 +1588,50 @@ mod tests { assert_eq!(heads("/schedule cancel ", &dynamic), ["job-1"]); } + /// A command whose argument is optional and offers nothing on a blank is + /// whole by its name: Enter runs it, as `/copy` runs. + #[test] + fn a_command_whole_without_its_argument_runs_on_enter() { + assert!(bare("/copy").is_empty(), "/copy needs no menu"); + // Nothing to choose on a blank: the name alone runs. + for name in ["/resume", "/learn", "/name"] { + assert!(runs_bare(name), "{name}"); + } + // Values or flags to choose, or an argument that must be given: the + // name opens the argument menu first. + for name in [ + "/new", + "/refine", + "/effort", + "/steer", + "/heartbeat", + "/copy", + ] { + assert!(!runs_bare(name), "{name}"); + } + // The row still shows what the command takes. + assert!(bare("/resume")[0].starts_with("/resume")); + } + #[test] fn heartbeats_offer_the_interval_flags_and_the_heartbeats() { let dynamic = records(&[(values::HEARTBEATS, &[("hb-1", "active · 10m · check CI")])]); - assert_eq!(bare("/heartbeat "), ["every"]); + assert_eq!(bare("/heartbeat "), ["every", "--steer", "--follow-up"]); assert_eq!(bare("/heartbeat -"), ["--steer", "--follow-up"]); assert_eq!(bare("/heartbeat every ")[0], "5m"); + // The instruction follows the interval: choosing one does not run it. + assert_eq!( + rows("/heartbeat every ", &ArgumentOptions::new())[0].completion, + "/heartbeat every 5m " + ); + assert_eq!( + rows("/schedule add @da", &ArgumentOptions::new())[0].completion, + "/schedule add @daily " + ); + assert_eq!( + rows("/schedule add in 1", &ArgumentOptions::new())[0].completion, + "/schedule add in 10m " + ); assert_eq!(bare("/heartbeat every 10m -"), ["--steer", "--follow-up"]); assert!( bare("/heartbeat check").is_empty(), @@ -1684,10 +1758,13 @@ mod tests { bare("/agents messages "), ["status", "pause", "resume", "clear"] ); - assert_eq!(heads("/resume ", &dynamic), ["latest", "s-42"]); + // A blank runs `/resume` as it is, the session picker: a session is + // offered once its name is begun. + assert!(heads("/resume ", &dynamic).is_empty()); + assert_eq!(heads("/resume l", &dynamic), ["latest"]); assert_eq!(heads("/resume pars", &dynamic), ["s-42"]); assert_eq!(heads("/resume -", &dynamic), ["--compact"]); - assert_eq!(heads("/resume --compact ", &dynamic), ["latest", "s-42"]); + assert_eq!(heads("/resume --compact s", &dynamic), ["s-42"]); assert_eq!(heads("/fork ", &dynamic), ["1", "2"]); assert_eq!(heads("/tree ", &dynamic), ["1", "2", "label"]); assert_eq!(heads("/tree label ", &dynamic), ["1", "2"]); diff --git a/docs/guides/OPERATOR_GUIDE.en.md b/docs/guides/OPERATOR_GUIDE.en.md index 5893dec0..10f2ad55 100644 --- a/docs/guides/OPERATOR_GUIDE.en.md +++ b/docs/guides/OPERATOR_GUIDE.en.md @@ -533,12 +533,12 @@ Children nest up to `RLM_MAX_DEPTH`, with no limit by default (prime-agent's def The command table, its order, wording and aliases follow prime-agent's `slash-commands.ts`, and so does the menu: typing `/` lists every command, letters narrow it with prime-agent's fuzzy match (`/skil` offers `/skills` and every `/skill:`; prompt commands join too), and a command that takes an argument opens an argument menu on Tab or Enter - `/effort` offers the levels, `/model` the models, `/login` the providers - where Enter on a value applies it. A mistyped command is answered with the closest one. `/effort ` (alias `/thinking`) chooses how much the model reasons, from `off` through `minimal`, `low`, `medium`, `high`, `xhigh` to `max`, as prime-agent does; `/effort` alone shows the level in force and the levels the model offers. A level the model lacks is clamped to the nearest one it has (DeepSeek V4 offers `off`, `high` and `xhigh`, sent as `max`). Claude Opus 5.5, the Fable models and the Mythos models (`claude-mythos-5`, `-5-1`, `-5-2`, which answer only organizations Anthropic has verified) cannot turn thinking off, so `off` runs at `low`; Claude Sonnet 5.5 turns it off with `between_tools`, as its API refuses `disabled`; Claude Haiku 5.5 thinks adaptively like the other Claude 5 models, and a call whose prompt is over 100K tokens costs five times as much on it, as Anthropic prices it. The choice is kept with the conversation and, as prime-agent's `setThinkingLevel` does, saved as `defaultThinkingLevel` in `settings.json` for new conversations (not an `off` on a model that does not think); `provider.thinking` / `HA_PROVIDER_THINKING` is read after it. With thinking on, DeepSeek gets each assistant message's `reasoning_content` back and Claude its signed thinking block, within the turn; reasoning is never stored. A model the built-in table does not know is treated as not reasoning. -**Every argument completes, word by word.** The argument menu follows each command's grammar past its first word: after `/memory ` it offers `queue`, `list`, `show`, `accept` and `reject`; after `/memory queue accept ` every memory change that waits, by id with its title, then `all` (every one in one go), in the order `/memory` lists them (a word of the title finds one: `/memory queue accept flutter`); a second id is offered once you start typing it, never one already on the line. Tab completes the highlighted row; Enter completes it and, when it is whole, runs it. The same holds for every command that takes an argument: +**Every argument completes, word by word.** The argument menu follows each command's grammar past its first word: after `/memory ` it offers `queue`, `list`, `show`, `accept` and `reject`; after `/memory queue accept ` every memory change that waits, by id with its title, then `all` (every one in one go), in the order `/memory` lists them (a word of the title finds one: `/memory queue accept flutter`); a second id is offered once you start typing it, never one already on the line. Tab completes the highlighted row; Enter completes it and, when it is whole, runs it. Right after the command, the blank offers its flags too, after the values (later blanks are free text, where a flag shows once you type its `-`): a flag is optional, so Enter there runs the line as it is (`/new ` starts a session, `/refine ` refines) unless you moved the highlight to the flag. A command whose argument is optional and offers nothing on a blank runs once its name is complete: `/resume` and Enter opens the session picker (`latest` and the sessions are offered once you begin the name), `/learn` and Enter learns. A value more must follow types a space and waits: `/heartbeat every 10m ` waits for the instruction, `/schedule add @daily ` for `-- `. The same holds for every command that takes an argument: | Command | What the menu offers | |---|---| | `/memory` | `queue`, `list`, `show`, `accept`, `reject`, then the waiting ids and `all` (`/memory accept ` works without `queue`) | -| `/refine` | `--global`, `--rollback`, `--curate`, `--history` once you type `-`; after `--rollback `, the recorded refinements, newest first, with their summaries | +| `/refine` | `--global`, `--rollback`, `--curate`, `--history`; after `--rollback `, the recorded refinements, newest first, with their summaries | | `/jev` | `status`, `on`, `off` and its ten decisions; after a decision, `on` or `off` | | `/bank`, `/codemode`, `/factory`, `/refinements` | `status`, `on`, `off` | | `/knowledge` | its actions (`status`, `search`, `read`, `bootstrap`...) and `--global` | @@ -549,7 +549,7 @@ The command table, its order, wording and aliases follow prime-agent's `slash-co | `/package` | `install`, `remove`, `update`, `list`, then the installed packages (by source, user or project); `--local` | | `/autonomous` | `status`, `on`, `off`; after `on`, the budget flags | | `/queue`, `/agents` | `list`, `edit`, `drop`, `up`, `down`, then the queued follow-ups by number; `stop` (the running children, then `all`) and `messages` (`status`, `pause`, `resume`, `clear`) | -| `/resume`, `/fork`, `/tree` | `latest`, the sessions of the last listing and `--compact`; the turns of the last `/fork` or `/tree` listing, `label` and `--summarize` | +| `/resume`, `/fork`, `/tree` | `latest` and the sessions of the last listing once you begin the name, and `--compact`; the turns of the last `/fork` or `/tree` listing, `label` and `--summarize` | | `/model`, `/scoped-models`, `/effort`, `/tier`, `/permissions`, `/login`, `/logout`, `/subagent-*` | the models, levels, tiers, modes and providers, as before | | `/new`, `/handoff`, `/rlm-max-depth`, `/fullscreen`, `/trust`, `/goal`, `/plugins` | their flags and fixed values | @@ -706,7 +706,7 @@ Where ha differs from prime-agent: there is one worker per project rather than p **Dropping context without losing the cache.** AKV ("Cache Engineering for Agents", arXiv 2610.28577) drops tool results from a self-hosted model's KV cache and leaves the text alone; a hosted provider caches a request by its start, so there the same rules are kept in the text. What a turn shortened is kept with the conversation (`sent_results`, by call) and sent the same way by every later step and every later turn - a result is rewritten once, never twice, and never comes back whole. A turn of a conversation that was compacted sends its first packet at every step, as any turn does. A request that rewrote what the one before had sent is recorded (`cache.prefix_rewritten`, with what was rewritten: tools, system, a tool result, ...) and counted in the bug report's Patterns, so a falling cache share has a cause to point at; each model call records the tokens written to the cache (`cache_write`) beside those read from it. Dropping results that still fit is off by default, because on a hosted provider a drop makes the provider read the conversation again from the dropped message: `HA_CONTEXT_DROP=keep` (or `keep:`, 12 as in the paper) keeps a turn's newest n tool results and drops the older ones once there are twice as many, a batch at a time; `HA_CONTEXT_DROP=tool` gives the model `drop_context` (`keep_last`, and `tools` to name whose results) to drop its own stale results; `keep,tool` does both. Reasoning and the model's own messages are never dropped - the paper measures that dropping them costs accuracy. Its `drop` and `repos` on KV states, its radix tree and its drop-aware eviction need the serving engine and have no counterpart on a hosted API. -**MCP servers.** `ha mcp login [--client-id] [--scope]` signs in to a Streamable HTTP server that asks for OAuth (RFC 9728 / RFC 8414 discovery, dynamic client registration, PKCE on `localhost:53700-53709` or a pasted redirect URL); the tokens are saved in `auth.json` under `mcp:`, refreshed before they expire and sent only to that server's URL, and `ha mcp logout ` forgets them. A server takes `enabled = false`, `headers`, `header_env` (a header from an environment variable), `bearer_token_credential` (the `auth.json` entry whose saved key is the bearer; `/plugins` sets it) and `startup_timeout_seconds`. +**MCP servers.** `ha mcp login [--client-id] [--scope]` signs in to a Streamable HTTP server that asks for OAuth (RFC 9728 / RFC 8414 discovery, dynamic client registration, PKCE on `localhost:53700-53709` or a pasted redirect URL); the tokens are saved in `auth.json` under `mcp:`, refreshed before they expire and sent only to that server's URL, and `ha mcp logout ` forgets them. The scope it asks for is `--scope`, else the one the server's `WWW-Authenticate` challenge names, else the resource metadata's `scopes_supported`, never the authorization server's whole list (Vercel's lists a scope a client may not ask for). A server takes `enabled = false`, `headers`, `header_env` (a header from an environment variable), `bearer_token_credential` (the `auth.json` entry whose saved key is the bearer; `/plugins` sets it) and `startup_timeout_seconds`. **Conversation.** Goals carry a token budget (`goal.create(..., token_budget=...)`) and pause as budget-limited when it is spent. `/share` publishes the conversation as a secret GitHub gist (through `gh`); `/new ` starts a new conversation with that prompt; `/export` writes an HTML page by default. `/import` also reads prime-agent session files. `/btw` declares the session's tools and refuses every call, as prime-agent's side question does. `autoRefine.enabled` and `autoRefine.turnInterval` in `settings.json` control the automatic review. `run_shell` refuses a git command that would discard uncommitted work (`git checkout -- .`, `git reset --hard`, `git clean -f`, ...) unless `HA_ALLOW_DESTRUCTIVE_GIT=1`. `rlm.rename(...)` renames the session or a direct child. diff --git a/docs/guides/OPERATOR_GUIDE.vi.md b/docs/guides/OPERATOR_GUIDE.vi.md index 93ee8adb..2cea61af 100644 --- a/docs/guides/OPERATOR_GUIDE.vi.md +++ b/docs/guides/OPERATOR_GUIDE.vi.md @@ -532,12 +532,12 @@ Không có các giá trị trên thì đọc `[agents] max_depth` trong config, Bảng lệnh, thứ tự, mô tả và alias theo `slash-commands.ts` của prime-agent, menu cũng vậy: gõ `/` liệt kê mọi lệnh, gõ thêm chữ sẽ lọc bằng tìm mờ của prime-agent (`/skil` gợi ý `/skills` và mọi `/skill:`; prompt command cũng có mặt), và lệnh nhận tham số sẽ mở menu tham số khi Tab hoặc Enter - `/effort` gợi ý các mức, `/model` các model, `/login` các provider - Enter trên một giá trị là áp dụng luôn. Gõ sai lệnh sẽ được gợi ý lệnh gần nhất. `/effort ` (alias `/thinking`) chọn mức suy luận của model, từ `off` qua `minimal`, `low`, `medium`, `high`, `xhigh` tới `max`, giống prime-agent; `/effort` không kèm tham số cho xem mức đang dùng và các mức model hỗ trợ. Mức model không có sẽ được kẹp về mức gần nhất (DeepSeek V4 có `off`, `high` và `xhigh`, gửi đi là `max`). Claude Opus 5.5, các model Fable và các model Mythos (`claude-mythos-5`, `-5-1`, `-5-2`, chỉ trả lời tổ chức đã được Anthropic xác minh) không tắt được thinking, nên `off` chạy ở mức `low`; Claude Sonnet 5.5 tắt thinking bằng `between_tools`, vì API của nó từ chối `disabled`; Claude Haiku 5.5 dùng adaptive thinking như các model Claude 5 khác, và một lượt gọi có prompt trên 100K token tốn gấp năm lần, theo bảng giá của Anthropic. Lựa chọn được lưu cùng hội thoại và, như `setThinkingLevel` của prime-agent, lưu thành `defaultThinkingLevel` trong `settings.json` cho hội thoại mới (trừ `off` trên model không suy luận); sau đó mới đến `provider.thinking` / `HA_PROVIDER_THINKING`. Khi bật thinking, DeepSeek nhận lại `reasoning_content` của từng tin assistant và Claude nhận lại block thinking có chữ ký, trong phạm vi một lượt; reasoning không bao giờ được lưu. Model không có trong bảng dựng sẵn được coi là không suy luận. -**Mọi tham số đều có gợi ý, từng từ một.** Menu tham số đi theo cú pháp của từng lệnh, không chỉ từ đầu tiên: sau `/memory ` nó gợi ý `queue`, `list`, `show`, `accept` và `reject`; sau `/memory queue accept ` là mọi thay đổi memory đang chờ, theo id kèm tiêu đề, rồi `all` (tất cả trong một lần), đúng thứ tự `/memory` liệt kê (gõ một từ trong tiêu đề cũng tìm được: `/memory queue accept flutter`); id thứ hai chỉ được gợi ý khi bạn bắt đầu gõ nó, và không bao giờ gợi ý lại id đã có trên dòng. Tab điền dòng đang chọn; Enter điền và, khi lệnh đã đủ, chạy luôn. Mọi lệnh nhận tham số đều như vậy: +**Mọi tham số đều có gợi ý, từng từ một.** Menu tham số đi theo cú pháp của từng lệnh, không chỉ từ đầu tiên: sau `/memory ` nó gợi ý `queue`, `list`, `show`, `accept` và `reject`; sau `/memory queue accept ` là mọi thay đổi memory đang chờ, theo id kèm tiêu đề, rồi `all` (tất cả trong một lần), đúng thứ tự `/memory` liệt kê (gõ một từ trong tiêu đề cũng tìm được: `/memory queue accept flutter`); id thứ hai chỉ được gợi ý khi bạn bắt đầu gõ nó, và không bao giờ gợi ý lại id đã có trên dòng. Tab điền dòng đang chọn; Enter điền và, khi lệnh đã đủ, chạy luôn. Ngay sau tên lệnh, ô trống cũng gợi ý các cờ, sau các giá trị (các ô trống sau đó là văn bản tự do, cờ chỉ hiện khi bạn gõ `-`): cờ là tùy chọn, nên Enter ở đó chạy dòng như đã gõ (`/new ` mở session mới, `/refine ` chạy refine) trừ khi bạn đã dời chỗ chọn tới cờ. Lệnh có tham số tùy chọn mà ô trống không có gì để gợi ý thì chạy ngay khi tên lệnh đã đủ: `/resume` rồi Enter mở bộ chọn session (`latest` và các session được gợi ý khi bạn bắt đầu gõ tên), `/learn` rồi Enter chạy learn. Giá trị còn cần phần sau thì điền thêm dấu cách và chờ: `/heartbeat every 10m ` chờ instruction, `/schedule add @daily ` chờ `-- `. Mọi lệnh nhận tham số đều như vậy: | Lệnh | Menu gợi ý | |---|---| | `/memory` | `queue`, `list`, `show`, `accept`, `reject`, rồi các id đang chờ và `all` (`/memory accept ` chạy được không cần `queue`) | -| `/refine` | `--global`, `--rollback`, `--curate`, `--history` khi bạn gõ `-`; sau `--rollback ` là các refinement đã ghi, mới nhất trước, kèm tóm tắt | +| `/refine` | `--global`, `--rollback`, `--curate`, `--history`; sau `--rollback ` là các refinement đã ghi, mới nhất trước, kèm tóm tắt | | `/jev` | `status`, `on`, `off` và mười quyết định của nó; sau một quyết định là `on` hoặc `off` | | `/bank`, `/codemode`, `/factory`, `/refinements` | `status`, `on`, `off` | | `/knowledge` | các hành động (`status`, `search`, `read`, `bootstrap`...) và `--global` | @@ -548,7 +548,7 @@ Bảng lệnh, thứ tự, mô tả và alias theo `slash-commands.ts` của pri | `/package` | `install`, `remove`, `update`, `list`, rồi các gói đã cài (theo source, của người dùng hay project); `--local` | | `/autonomous` | `status`, `on`, `off`; sau `on` là các cờ ngân sách | | `/queue`, `/agents` | `list`, `edit`, `drop`, `up`, `down`, rồi các follow-up đang xếp theo số; `stop` (các child đang chạy, rồi `all`) và `messages` (`status`, `pause`, `resume`, `clear`) | -| `/resume`, `/fork`, `/tree` | `latest`, các session của lần liệt kê gần nhất và `--compact`; các lượt của lần `/fork` hoặc `/tree` gần nhất, `label` và `--summarize` | +| `/resume`, `/fork`, `/tree` | `latest` và các session của lần liệt kê gần nhất khi bạn bắt đầu gõ tên, và `--compact`; các lượt của lần `/fork` hoặc `/tree` gần nhất, `label` và `--summarize` | | `/model`, `/scoped-models`, `/effort`, `/tier`, `/permissions`, `/login`, `/logout`, `/subagent-*` | các model, mức, tier, chế độ và provider, như trước | | `/new`, `/handoff`, `/rlm-max-depth`, `/fullscreen`, `/trust`, `/goal`, `/plugins` | các cờ và giá trị cố định của chúng | @@ -705,7 +705,7 @@ Khác prime-agent ở chỗ: mỗi project một worker thay vì mỗi session, **Bỏ bớt ngữ cảnh mà không mất cache.** AKV ("Cache Engineering for Agents", arXiv 2610.28577) bỏ kết quả tool khỏi KV cache của model tự host và giữ nguyên văn bản; provider hosted cache một yêu cầu theo phần đầu của nó, nên ở đây các quy tắc đó được giữ trên văn bản. Kết quả nào một lượt đã rút gọn thì được lưu cùng hội thoại (`sent_results`, theo call) và mọi bước sau, mọi lượt sau gửi lại đúng như vậy - một kết quả chỉ bị viết lại một lần, không bao giờ hai lần, và không bao giờ quay lại nguyên văn. Một lượt của hội thoại đã compact gửi packet đầu tiên của nó ở mọi bước, như mọi lượt khác. Yêu cầu nào viết lại phần mà yêu cầu trước đã gửi thì được ghi nhận (`cache.prefix_rewritten`, kèm phần bị viết lại: tools, system, kết quả tool, ...) và được đếm trong mục Patterns của bug report, để tỉ lệ cache giảm có nguyên nhân để lần theo; mỗi lần gọi model ghi cả số token ghi vào cache (`cache_write`) bên cạnh số đọc từ cache. Việc bỏ các kết quả vẫn còn vừa mặc định tắt, vì trên provider hosted mỗi lần bỏ khiến provider đọc lại hội thoại từ tin nhắn bị bỏ: `HA_CONTEXT_DROP=keep` (hoặc `keep:`, 12 như trong bài báo) giữ n kết quả tool mới nhất của lượt và bỏ các kết quả cũ hơn khi số lượng đạt gấp đôi, theo từng lô; `HA_CONTEXT_DROP=tool` cho model tool `drop_context` (`keep_last`, và `tools` để chỉ tên tool) để tự bỏ kết quả cũ; `keep,tool` bật cả hai. Phần suy luận và tin nhắn của chính model không bao giờ bị bỏ - bài báo đo được rằng bỏ chúng làm giảm độ chính xác. `drop` và `repos` trên KV state, radix tree và eviction theo drop của bài báo cần engine phục vụ model và không có tương ứng trên API hosted. -**MCP server.** `ha mcp login [--client-id] [--scope]` đăng nhập vào server Streamable HTTP yêu cầu OAuth (khám phá RFC 9728 / RFC 8414, đăng ký client động, PKCE trên `localhost:53700-53709` hoặc dán URL chuyển hướng); token được lưu trong `auth.json` dưới `mcp:`, làm mới trước khi hết hạn và chỉ gửi tới đúng URL của server đó, `ha mcp logout ` xóa nó. Server nhận `enabled = false`, `headers`, `header_env` (header lấy từ biến môi trường), `bearer_token_credential` (mục trong `auth.json` có key dùng làm bearer; `/plugins` đặt nó) và `startup_timeout_seconds`. +**MCP server.** `ha mcp login [--client-id] [--scope]` đăng nhập vào server Streamable HTTP yêu cầu OAuth (khám phá RFC 9728 / RFC 8414, đăng ký client động, PKCE trên `localhost:53700-53709` hoặc dán URL chuyển hướng); token được lưu trong `auth.json` dưới `mcp:`, làm mới trước khi hết hạn và chỉ gửi tới đúng URL của server đó, `ha mcp logout ` xóa nó. Scope được xin là `--scope`, nếu không có thì là scope mà challenge `WWW-Authenticate` của server nêu, nếu không nữa thì là `scopes_supported` trong metadata của resource, không bao giờ là cả danh sách của authorization server (danh sách của Vercel có một scope mà client không được xin). Server nhận `enabled = false`, `headers`, `header_env` (header lấy từ biến môi trường), `bearer_token_credential` (mục trong `auth.json` có key dùng làm bearer; `/plugins` đặt nó) và `startup_timeout_seconds`. **Hội thoại.** Goal có token budget (`goal.create(..., token_budget=...)`) và tạm dừng ở trạng thái budget-limited khi dùng hết. `/share` đăng hội thoại thành GitHub gist bí mật (qua `gh`); `/new ` mở hội thoại mới với prompt đó; `/export` mặc định ghi trang HTML. `/import` đọc được cả file phiên của prime-agent. `/btw` khai báo tool của phiên nhưng từ chối mọi lời gọi, như câu hỏi bên lề của prime-agent. `autoRefine.enabled` và `autoRefine.turnInterval` trong `settings.json` điều khiển việc tự review. `run_shell` từ chối lệnh git làm mất thay đổi chưa commit (`git checkout -- .`, `git reset --hard`, `git clean -f`, ...) trừ khi `HA_ALLOW_DESTRUCTIVE_GIT=1`. `rlm.rename(...)` đổi tên phiên hoặc một agent con trực tiếp.