diff --git a/README.md b/README.md index 6968f99..48268ae 100644 --- a/README.md +++ b/README.md @@ -583,6 +583,7 @@ All optional, in `~/.incode/admin.json`: - **`notify`** — when a turn that ran longer than `notify_after_secs` (default 10) finishes, or the agent stops to ask for permission or an answer: `auto` (default) sends an OSC 9 notification on terminals known to show one (iTerm2, WezTerm, Windows Terminal, kitty, Ghostty) and a bell elsewhere; `bell`; `desktop` (`notify-send` on Linux, `osascript` on macOS, a BurntToast or WinRT toast through PowerShell on Windows, a bell when that cannot start); `off`. `notify_command` also runs, with `INCODE_EVENT` (`done` or `input`) and `INCODE_MESSAGE` set. Nothing waits on either. - **`statusline_command`** — run at start and after each turn with the session as JSON on stdin (`cwd`, `workspace`, `model`, `session_id`, `git_branch`, `git_dirty`, `tokens` {`input`, `output`, `cache_write`, `cache_read`, `total`}, `cost_usd`, null when a model is unpriced). Its first line replaces the facts on the input box's top rule. It gets 1.5 s; a slow or failing run keeps the last good line. +- **`output_style`** — the [output style](#output-styles) sessions start with; `INCODE_OUTPUT_STYLE` overrides it, `/style` switches it. - **`editing_mode`** — `emacs` (default) or `vi`. In vi mode Esc enters normal mode (`h l w b e 0 ^ $ x X D C s S dd cc i a I A j k`) and Enter submits from either mode. - **`~/.incode/keybindings.toml`** — flat `"key" = "action"` lines, checked before the built-in keys. Keys: `ctrl-`, `alt-`, `shift-` plus a character, `enter`, `tab`, `esc`, `backspace`, `delete`, arrows, `home`, `end`, `space`, `f1`–`f12`. Actions: `clear-line`, `kill-to-start`, `kill-to-end`, `delete-word`, `line-start`, `line-end`, `char-left`, `char-right`, `word-left`, `word-right`, `history-prev`, `history-next`, `newline`, `submit`, `complete`. @@ -686,6 +687,39 @@ A plugin's hooks and servers run with your authority; install only what you would run yourself. Skills and hooks are read for the directory incode was started in. +### Output styles + +An output style is a way of answering you choose: a Markdown file whose body +the agent is told to follow in every reply, in `~/.incode/styles/.md` +(yours) or `.incode/styles/.md` (this project's). **Yours wins a +clash**: a project's styles arrive with whatever you cloned, so a repository +cannot replace the style you named, and the prompt, `/style` and `--admin` all +say which folder the text came from. A symbolic link is refused in either +folder. An optional front matter gives `/style` a line to show: + +```markdown +--- +description: Short answers, no preamble +--- +Answer in three sentences or fewer. Lead with the answer. +``` + +- **Which one:** `INCODE_OUTPUT_STYLE`, else `"output_style": ""` in + `~/.incode/admin.json`, else none (`off` or `none` say none on purpose). + `--admin` shows it and where it came from; a name no folder has is said, not + ignored. +- **`/style`** lists them, `/style ` answers in one from the next reply, + `/style off` stops. It holds for that session. This is the REPL's command: + `--acp` runs built-in commands only from its `OFFERED` list + (`src/acp_agent/commands.rs`), which does not include `/style`, so an ACP + session keeps the style it was started with. +- It reaches every route — the API, claude, codex and agy — and `-t` runs. It + goes after every other block of the prompt and says those still win: a + style changes how answers read, never what the agent may do. It is kept + when a long prompt has to be cut to fit a command line. +- None ships with incode; a file of more than 64 KB, an empty one, or one with + an unknown front-matter key is left out and said so. + ## Tools Every tool the model can call is incode's own, in `src/toolbox/`. Each call is diff --git a/src/admin.rs b/src/admin.rs index 9b959a5..261a36c 100644 --- a/src/admin.rs +++ b/src/admin.rs @@ -336,6 +336,11 @@ pub struct AdminConfig { /// toggles it for the session. #[serde(default, skip_serializing_if = "Option::is_none")] pub editing_mode: Option, + /// The output style every session starts with: a file in + /// `.incode/styles/` or `~/.incode/styles/` ([`crate::styles`]). + /// `INCODE_OUTPUT_STYLE` overrides it; `/style` switches it per session. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub output_style: Option, /// Per-command permission rules — `allow`, `ask`, `deny` lists of `Tool` /// or `Tool(specifier)` — applied to every tool call the toolbox runs. /// Unioned with the managed and project rules; deny beats ask beats allow. @@ -1129,6 +1134,23 @@ impl AdminConfig { codex_tools.source.as_str() )); + let env_style = std::env::var(crate::styles::ENV).ok(); + out.push_str(&match crate::styles::chosen( + env_style.as_deref(), + self.output_style.as_deref(), + ) { + Some(style) => format!( + " output style {} <- {}{}\n", + style.value, + style.source.as_str(), + match crate::styles::load(workspace).find(&style.value) { + Some(found) => format!(" ({})", found.source.display()), + None => " (no such file: none is applied)".to_string(), + } + ), + None => " output style none\n".to_string(), + }); + // Every one of these is optional. Saying which are OFF is the point: a // harness quietly doing less looks exactly like one doing nothing. let off = self.plugins.disabled(); @@ -1595,6 +1617,7 @@ mod tests { notify_after_secs: Some(30), statusline_command: Some("~/.incode/statusline.sh".to_string()), editing_mode: Some("vi".to_string()), + output_style: Some("concise".to_string()), // The permission rules, or a `/roles` save would drop them. permissions: crate::permissions::rules::RuleLists { allow: vec!["Bash(npm test:*)".to_string()], diff --git a/src/agent/mod.rs b/src/agent/mod.rs index 3b68451..53b140a 100644 --- a/src/agent/mod.rs +++ b/src/agent/mod.rs @@ -411,6 +411,7 @@ pub fn budget_for_spawn( || lower.contains("") || lower.contains("") || lower.contains(") { + self.base_context + .retain(|existing| !crate::styles::is_block(existing)); + self.base_context.extend(block); + self.carry_context(); + } + /// How much the agent may do on its own for the following turns. pub fn set_permission_mode(&mut self, mode: &str) { self.mode = Some(mode.to_string()); @@ -1846,6 +1856,54 @@ mod tests { s } + /// **`/style` REACHES THE AGENT.** The old style's block goes, the new one + /// comes, the rest of the standing context stays, and there is never more + /// than one style. + #[test] + fn an_output_style_swap_reaches_the_backend_and_keeps_the_rest() { + let ws = tempfile::tempdir().expect("ws"); + let seen = Arc::new(Mutex::new(Seen::default())); + let style = |name: &str, body: &str| { + crate::styles::block(&crate::styles::Style { + name: name.into(), + description: None, + body: body.into(), + source: PathBuf::from(format!("{name}.md")), + origin: crate::styles::Origin::Operator, + }) + }; + let mut s = AgentSession::new( + ws.path().to_path_buf(), + "claude-code", + "claude".to_string(), + &crate::guards::Guards::default(), + vec!["BASE".to_string(), style("concise", "Be brief.")], + ) + .with_backend(Box::new(Recording { + seen: Arc::clone(&seen), + on_run: Box::new(|_| {}), + })); + let styles_in = |seen: &Arc>| { + seen.lock() + .expect("seen") + .context + .iter() + .filter(|b| crate::styles::is_block(b)) + .cloned() + .collect::>() + }; + + s.set_output_style(Some(style("teacher", "Explain why."))); + let found = styles_in(&seen); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].contains("Explain why."), "{found:?}"); + assert_eq!(seen.lock().expect("seen").context[0], "BASE"); + + s.set_output_style(None); + assert!(styles_in(&seen).is_empty()); + assert_eq!(seen.lock().expect("seen").context, ["BASE"]); + } + fn start_context(text: &str) -> String { serde_json::json!({ "hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": text} diff --git a/src/cli/mod.rs b/src/cli/mod.rs index f844058..d703c71 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -149,6 +149,8 @@ pub(crate) struct Prepared { pub(crate) lifecycle_hooks: LifecycleHooks, pub(crate) git_context: Option, pub(crate) system_prompt: Vec, + /// The output style the session started with, by name. + pub(crate) output_style: Option, pub(crate) catalogue: crate::agent::catalogue::Catalogue, pub(crate) agent: crate::agent::DetectedAgent, pub(crate) fleet: crate::fleet::Fleet, @@ -527,6 +529,20 @@ pub(crate) fn prepare_session( if let Some(block) = roles.prompt_block() { system_prompt.push(block); } + // The answering style the person chose (`crate::styles`). Pushed LAST + // and kept last — the guards and the intake are inserted earlier — after + // every block it is weighed against: it shapes how replies read, and its + // own words say the rules above it win. + let style = crate::styles::for_session(&workspace, admin.output_style.as_deref()); + for note in &style.notes { + render::print_info(note); + } + for warning in &style.warnings { + render::print_error(warning); + } + if let Some(block) = &style.block { + system_prompt.push(block.clone()); + } // The agent that will do the work. // // TWO ROUTES, and this harness keeps the judging on both — the ledger, @@ -683,6 +699,7 @@ pub(crate) fn prepare_session( lifecycle_hooks, git_context, system_prompt, + output_style: style.name, catalogue, agent, fleet, @@ -707,11 +724,14 @@ impl CliApp { lifecycle_hooks, git_context, system_prompt, + output_style, catalogue, agent, fleet, mut session, } = prepared; + // `/style` changes it for this session. + let mut output_style = output_style; let turn_cancel = cancel.clone(); tokio::spawn(async move { loop { @@ -933,6 +953,15 @@ impl CliApp { } SlashCommand::Help => slash_commands::handle_help(), SlashCommand::Cost => ux::print_cost(&session), + SlashCommand::Style(name) => { + if let Some(block) = slash_commands::handle_style( + name.as_deref(), + &workspace, + &mut output_style, + ) { + session.set_output_style(block); + } + } SlashCommand::Bug(description) => slash_commands::handle_bug( &display_model, permission_mode.as_str(), diff --git a/src/cli/slash_commands.rs b/src/cli/slash_commands.rs index a52e27c..76ef185 100644 --- a/src/cli/slash_commands.rs +++ b/src/cli/slash_commands.rs @@ -20,6 +20,8 @@ pub enum SlashCommand { Review(Option), /// A prefilled GitHub issue link for what happened; sends nothing. Bug(Option), + /// List the output styles, or switch to one (`off`: none). + Style(Option), /// The tools incode runs, or with an argument the external tools: /// `add …`, `update [name]`, `remove `. Tools(Option), @@ -112,6 +114,7 @@ impl SlashCommand { "/compact" => Self::Compact(arg.filter(|a| !a.is_empty())), "/review" => Self::Review(arg.filter(|a| !a.is_empty())), "/bug" | "/feedback" => Self::Bug(arg.filter(|a| !a.is_empty())), + "/style" => Self::Style(arg.filter(|a| !a.is_empty())), "/cost" => Self::Cost, "/vim" => Self::Vim, "/undo" | "/u" => Self::Undo, @@ -209,6 +212,10 @@ pub const COMMANDS: &[(&str, &str)] = &[ ("/help", "Show this help message"), ("/status", "Session info, token usage, model"), ("/cost", "Tokens and estimated cost, per model"), + ( + "/style [name|off]", + "List the output styles (.incode/styles, ~/.incode/styles), or answer in one from now on", + ), ( "/bug [what happened]", "A prefilled GitHub issue link: version, OS, model, your words scrubbed. Sends nothing", @@ -1532,6 +1539,79 @@ fn handle_pull_request_merge(words: &[&str], workspace: &std::path::Path) { // SSH handler // --------------------------------------------------------------------------- +// --------------------------------------------------------------------------- +// Output style handler +// --------------------------------------------------------------------------- + +/// `/style [name|off]`: with no name, list the styles and the one in force; +/// with one, switch to it. Returns the session's new style block when it +/// changes (`Some(None)`: none); the caller hands it to +/// `AgentSession::set_output_style`. `current` is the style's name. +pub fn handle_style( + arg: Option<&str>, + workspace: &std::path::Path, + current: &mut Option, +) -> Option> { + let styles = crate::styles::load(workspace); + for problem in &styles.problems { + render::print_error(problem); + } + let Some(name) = arg.map(str::trim) else { + render::print_header("Output styles"); + if styles.styles.is_empty() { + outln!( + " none yet: write one as a Markdown file in {}/ or ~/.incode/{}/", + crate::styles::PROJECT_DIR, + crate::styles::USER_DIR + ); + } + for style in &styles.styles { + let mark = if current.as_deref() == Some(style.name.as_str()) { + "*" + } else { + " " + }; + // Said beside each: a project's style came with the repository. + let from = match style.origin { + crate::styles::Origin::Operator => "yours", + crate::styles::Origin::Project => "this project", + }; + outln!( + " {mark} {:<16} {:<13} {}", + style.name, + from, + style.description.as_deref().unwrap_or("") + ); + } + outln!(); + render::print_info("/style to answer in one, /style off for none."); + return None; + }; + if name.eq_ignore_ascii_case("off") || name.eq_ignore_ascii_case("none") { + *current = None; + render::print_info("No output style from the next reply."); + return Some(None); + } + match styles.find(name) { + Some(style) => { + *current = Some(style.name.clone()); + render::print_info(&format!( + "Output style `{}` from the next reply, for this session.", + style.name + )); + Some(Some(crate::styles::block(style))) + } + None => { + render::print_error(&format!( + "No style `{name}` in {}/ or ~/.incode/{}/. /style lists them.", + crate::styles::PROJECT_DIR, + crate::styles::USER_DIR + )); + None + } + } +} + // --------------------------------------------------------------------------- // Bug report handler // --------------------------------------------------------------------------- @@ -1778,6 +1858,14 @@ mod tests { Some(SlashCommand::Compact(Some("keep the API notes".into()))) ); assert_eq!(SlashCommand::parse("/bug"), Some(SlashCommand::Bug(None))); + assert_eq!( + SlashCommand::parse("/style"), + Some(SlashCommand::Style(None)) + ); + assert_eq!( + SlashCommand::parse("/style teacher"), + Some(SlashCommand::Style(Some("teacher".into()))) + ); assert_eq!( SlashCommand::parse("/feedback the footer flickers"), Some(SlashCommand::Bug(Some("the footer flickers".into()))) diff --git a/src/lib.rs b/src/lib.rs index 13ce58e..326eaf3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -56,6 +56,7 @@ pub mod serve; pub mod session; pub mod skills; pub mod spec; +pub mod styles; pub mod subagents; pub mod task_run; pub mod team; diff --git a/src/styles.rs b/src/styles.rs new file mode 100644 index 0000000..9562a50 --- /dev/null +++ b/src/styles.rs @@ -0,0 +1,543 @@ +//! Output styles: a named way of answering, added to the system prompt. +//! +//! A style is a Markdown file — `~/.incode/styles/.md`, then +//! `/.incode/styles/.md` — whose body is told to the agent, +//! and whose optional front matter gives a `description`. None ships with +//! incode: which ones exist is the operator's to write. +//! +//! # A repository is not the operator +//! +//! A project's styles arrive with whatever was cloned. So the operator's own +//! file wins a clash — a repository cannot replace the `concise` they chose — +//! and the block says which folder its text came from, as `--admin` and +//! `/style` do. A symbolic link is refused in either folder: a repository's +//! `x.md` pointing at a key file would otherwise put that file in the prompt. +//! A `` in a body is broken up, so no file can close the block +//! early and write outside it. +//! +//! Which one is in force: `INCODE_OUTPUT_STYLE`, else `output_style` in +//! `~/.incode/admin.json`, else none (`off` or `none` names none on purpose). +//! A name no folder has is said, never quietly dropped. `/style` lists them +//! and switches for the rest of a session. +//! +//! The block shapes how replies read; it does not loosen anything. It goes +//! after every other block of the prompt and says the rules above it win. +//! +//! # Wired to +//! +//! - `cli::prepare_session` (REPL and `--acp`) and `task_run` (`-t`) add the +//! block; `cli::agent_turn::AgentSession::set_output_style` swaps it. +//! - `agent::budget_for_spawn` keeps it when a long prompt has to be cut: it +//! is one of the blocks matched as high priority by [`TAG`]. +//! - `admin::AdminConfig::report` names the style and where it came from. + +use std::path::{Path, PathBuf}; + +use crate::admin::{Resolved, Source}; + +/// In the workspace. +pub const PROJECT_DIR: &str = ".incode/styles"; +/// In incode's data directory (`~/.incode/`). +pub const USER_DIR: &str = "styles"; +/// Names the style for this shell, ahead of `admin.json`. +pub const ENV: &str = "INCODE_OUTPUT_STYLE"; +/// The block's tag. `agent::budget_for_spawn` matches it. +pub const TAG: &str = " &'static str { + match self { + Self::Operator => "the person's own (~/.incode/styles)", + Self::Project => "this project's (.incode/styles, from the repository)", + } + } +} + +/// One style. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Style { + pub name: String, + pub description: Option, + pub body: String, + pub source: PathBuf, + pub origin: Origin, +} + +/// Every style found, and why any file was left out. +#[derive(Debug, Clone, Default)] +pub struct Styles { + pub styles: Vec