Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down Expand Up @@ -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/<name>.md`
(yours) or `.incode/styles/<name>.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": "<name>"` 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 <name>` 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
Expand Down
23 changes: 23 additions & 0 deletions src/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,11 @@ pub struct AdminConfig {
/// toggles it for the session.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub editing_mode: Option<String>,
/// 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<String>,
/// 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.
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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()],
Expand Down
1 change: 1 addition & 0 deletions src/agent/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,7 @@ pub fn budget_for_spawn(
|| lower.contains("<asking>")
|| lower.contains("<roles>")
|| lower.contains("<project-instructions")
|| lower.contains(crate::styles::TAG)
|| lower.contains("disallowedtools")
{
high_priority.push(trimmed);
Expand Down
58 changes: 58 additions & 0 deletions src/cli/agent_turn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -621,6 +621,16 @@ impl AgentSession {
}
}

/// The output style for the following turns (`crate::styles`): the old
/// block out of the standing context, `block` in — last, as the session
/// started with it — and every backend told. `None` leaves no style.
pub fn set_output_style(&mut self, block: Option<String>) {
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());
Expand Down Expand Up @@ -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<Mutex<Seen>>| {
seen.lock()
.expect("seen")
.context
.iter()
.filter(|b| crate::styles::is_block(b))
.cloned()
.collect::<Vec<_>>()
};

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}
Expand Down
29 changes: 29 additions & 0 deletions src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,8 @@ pub(crate) struct Prepared {
pub(crate) lifecycle_hooks: LifecycleHooks,
pub(crate) git_context: Option<git_context::GitContext>,
pub(crate) system_prompt: Vec<String>,
/// The output style the session started with, by name.
pub(crate) output_style: Option<String>,
pub(crate) catalogue: crate::agent::catalogue::Catalogue,
pub(crate) agent: crate::agent::DetectedAgent,
pub(crate) fleet: crate::fleet::Fleet,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -683,6 +699,7 @@ pub(crate) fn prepare_session(
lifecycle_hooks,
git_context,
system_prompt,
output_style: style.name,
catalogue,
agent,
fleet,
Expand All @@ -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 {
Expand Down Expand Up @@ -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(),
Expand Down
88 changes: 88 additions & 0 deletions src/cli/slash_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ pub enum SlashCommand {
Review(Option<String>),
/// A prefilled GitHub issue link for what happened; sends nothing.
Bug(Option<String>),
/// List the output styles, or switch to one (`off`: none).
Style(Option<String>),
/// The tools incode runs, or with an argument the external tools:
/// `add <name>…`, `update [name]`, `remove <name>`.
Tools(Option<String>),
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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<String>,
) -> Option<Option<String>> {
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 <name> 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
// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -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())))
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Loading
Loading