From 870be3487d23daf940c0a880eb277eb81e2a815e Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 19:12:52 +0200 Subject: [PATCH 01/31] fix: warn on stderr when piped stdin is empty --- src/main.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main.rs b/src/main.rs index e55942a..ed36b51 100644 --- a/src/main.rs +++ b/src/main.rs @@ -248,6 +248,10 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { bail!("nothing to do. Usage: prinia \"question\" or cmd | prinia \"instruction\""); } + if !stdin_tty && payload.trim().is_empty() { + eprintln!("prinia: warning: stdin is empty, answering the instruction alone"); + } + // Raw output whenever either end is a pipe. let piped = !stdin_tty || !stdout_tty; let mode = if cli.agent { From fd7f292ab2fedba6b803b262c8445c69b89c1485 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:00:47 +0200 Subject: [PATCH 02/31] fix: agent cache key, truncated streams, timeouts, panic, symlink write, process-group kill; add -x and agent/write/run settings; local-model docs --- README.md | 20 ++++++++++++++++++++ docs/agent.md | 10 ++++++++++ src/agent.rs | 29 +++++++++++++++++++++++++++++ src/config.rs | 3 +++ src/curate.rs | 4 ++++ src/main.rs | 29 +++++++++++++++++++++-------- src/provider.rs | 6 ++++++ tests/cli.rs | 4 ---- 8 files changed, 93 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index bec7d7a..3320c03 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,25 @@ export ANTHROPIC_API_KEY=... # or OPENAI_API_KEY, or configure a local mode prinia "hello" ``` +### Local models + +No account or API key needed. With [Ollama](https://ollama.com) running: + +```bash +ollama pull qwen2.5:14b # ~9 GB; fits a 16 GB machine, fast on Apple silicon +mkdir -p ~/.config/prinia && cat > ~/.config/prinia/config.toml <<'EOF' +provider = "local" + +[providers.local] +type = "openai" +base_url = "http://localhost:11434/v1" +model = "qwen2.5:14b" +EOF +prinia "how do I find the largest files in a directory?" +``` + +Small models (3B and under) invent commands and ignore instructions; `qwen2.5:14b` is a good starting point, and `qwen2.5:32b` is better if you have the memory. Other local runners with an OpenAI-compatible endpoint (LM Studio, llama.cpp, vLLM) work the same way with a different `base_url`. + See [Install](docs/install.md) for other platforms and building from source, and [Configuration](docs/configuration.md) for local models and other providers. ## Usage @@ -44,6 +63,7 @@ cmd | prinia "instruction" | cmd2 # a pipeline step prinia -f "..." # fast tier prinia -d "..." # reasoning tier prinia -p local "..." # a configured provider +prinia -x "..." # let the model run commands to answer (agent + --run) prinia -a "..." # agent: the model reads and searches files here (--write, --run to allow more) prinia -c "..." # include earlier turns from this directory prinia --no-cache "..." # ask again even if the call is in your history diff --git a/docs/agent.md b/docs/agent.md index 1de3c07..bb5406b 100644 --- a/docs/agent.md +++ b/docs/agent.md @@ -4,10 +4,20 @@ prinia -a "which file defines the retry logic, and how many times does it retry?" prinia -a --write "rename the function parse to parse_config everywhere" prinia -a --run "run the tests and tell me what fails" +prinia -x "what is my public ip" # -x = --agent --run ``` With `-a` (`--agent`) the model can look around in the current directory before it answers: it calls tools, `prinia` runs them and returns the results, and this repeats until the model gives a final answer. The answer goes to stdout like any other call, and one line per tool call goes to stderr so you can see what it did. +## Making it the default + +```toml +agent = true # use agent mode for every call at a terminal +run = true # and let it run commands (`write = true` for file edits) +``` + +The model then decides per question whether to call a tool. The `agent` setting only applies when both stdin and stdout are terminals, so pipelines stay plain filters; `-a` forces it anywhere, `--no-agent` turns it off for one call. `--json` and `--check` never use it. `run` and `write` are the same permissions as the flags: no confirmation, so enable them only where you are comfortable with that. + ## What it can do | Tool | Needs | What it does | diff --git a/src/agent.rs b/src/agent.rs index 07ee59c..b3ea151 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -77,6 +77,10 @@ fn resolve(root: &Path, p: &str) -> Result { let canon = match joined.canonicalize() { Ok(c) => c, Err(_) => { + // a dangling symlink would be followed by the write + if joined.symlink_metadata().is_ok_and(|m| m.is_symlink()) { + bail!("{p:?} is a dangling symbolic link"); + } let name = joined .file_name() .ok_or_else(|| anyhow!("bad path {p:?}"))?; @@ -233,6 +237,8 @@ fn run_command(root: &Path, a: &Value) -> Result { c.args(["-c", &format!("({cmd}) 2>&1")]); c }; + #[cfg(unix)] + std::os::unix::process::CommandExt::process_group(&mut c, 0); let mut child = c .current_dir(root) .stdin(Stdio::null()) @@ -250,6 +256,11 @@ fn run_command(root: &Path, a: &Value) -> Result { break Some(s); } if started.elapsed() > Duration::from_secs(60) { + // kill the group, or a background grandchild keeps the output pipe open + #[cfg(unix)] + let _ = Command::new("kill") + .args(["-KILL", &format!("-{}", child.id())]) + .status(); let _ = child.kill(); let _ = child.wait(); break None; @@ -361,4 +372,22 @@ mod tests { assert!(resolve(&root, "/etc/passwd").is_err()); assert!(resolve(&root, ".").is_ok()); } + + #[cfg(unix)] + #[test] + fn dangling_symlinks_are_refused() { + let root = std::env::temp_dir() + .join("prinia-symlink-test") + .canonicalize() + .unwrap_or_else(|_| { + let d = std::env::temp_dir().join("prinia-symlink-test"); + std::fs::create_dir_all(&d).unwrap(); + d.canonicalize().unwrap() + }); + let link = root.join("link"); + let _ = std::fs::remove_file(&link); + std::os::unix::fs::symlink("/nonexistent-outside/new", &link).unwrap(); + assert!(resolve(&root, "link").is_err()); + let _ = std::fs::remove_file(&link); + } } diff --git a/src/config.rs b/src/config.rs index e1c1961..81bbb14 100644 --- a/src/config.rs +++ b/src/config.rs @@ -33,6 +33,9 @@ pub const KEYS: &[(&str, Ty)] = &[ ("history_scan", Ty::Num), ("excerpt_prompt", Ty::Num), ("excerpt_reply", Ty::Num), + ("agent", Ty::Bool), + ("write", Ty::Bool), + ("run", Ty::Bool), ("agent_steps", Ty::Num), ("check_retries", Ty::Num), ("keychain", Ty::Bool), diff --git a/src/curate.rs b/src/curate.rs index b190ecb..e0c1d0e 100644 --- a/src/curate.rs +++ b/src/curate.rs @@ -81,6 +81,9 @@ fn picked(reply: &str, offered: &[Turn]) -> Vec { let (Some(a), Some(b)) = (reply.find('['), reply.rfind(']')) else { return Vec::new(); }; + if a > b { + return Vec::new(); + } let ids: Vec = serde_json::from_str(&reply[a..=b]).unwrap_or_default(); offered .iter() @@ -144,6 +147,7 @@ mod tests { let offered = [turn(1), turn(2), turn(3)]; assert_eq!(picked("```json\n[3, 1, 99]\n```", &offered), [1, 3]); assert!(picked("no idea", &offered).is_empty()); + assert!(picked("x] y [3", &offered).is_empty()); // ] before [ must not panic assert!(picked("[\"x\"]", &offered).is_empty()); } } diff --git a/src/main.rs b/src/main.rs index ed36b51..43b1f9c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -61,14 +61,22 @@ struct Cli { #[arg(short = 'a', long)] agent: bool, + /// Shorthand for --agent --run: let the model run commands to answer + #[arg(short = 'x', long = "do", conflicts_with = "no_agent")] + do_it: bool, + /// With --agent: allow creating and editing files - #[arg(long, requires = "agent")] + #[arg(long)] write: bool, /// With --agent: allow running shell commands - #[arg(long, requires = "agent")] + #[arg(long)] run: bool, + /// Don't use agent mode, even if the `agent` setting is on + #[arg(long, conflicts_with = "agent")] + no_agent: bool, + /// Require the answer to be valid JSON; ask again if it is not #[arg(long, conflicts_with = "agent")] json: bool, @@ -254,7 +262,12 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { // Raw output whenever either end is a pipe. let piped = !stdin_tty || !stdout_tty; - let mode = if cli.agent { + let validate = cli.json || cli.check.is_some(); + // The setting only applies at a terminal; pipelines stay plain filters. + let agent = cli.agent + || cli.do_it + || (!cli.no_agent && !validate && !piped && cfg.bool("agent").unwrap_or(false)); + let mode = if agent { "agent" } else if piped { "pipe" @@ -268,7 +281,6 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { .unwrap_or_else(|| PROMPT_INTERACTIVE.into()) }; - let validate = cli.json || cli.check.is_some(); let system = if cli.json { format!("{system} Respond with a single valid JSON value and nothing else.") } else { @@ -310,7 +322,7 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { bail!("`cache` must be \"pipe\", \"always\" or \"off\""); } let use_cache = - !cli.no_cache && !cli.agent && (cache_mode == "always" || (cache_mode == "pipe" && piped)); + !cli.no_cache && !agent && (cache_mode == "always" || (cache_mode == "pipe" && piped)); let cwd = std::env::current_dir()?; let dir = store::dir_hash(&cwd); @@ -347,6 +359,7 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { &serde_json::json!(history).to_string(), effort.as_deref().unwrap_or(""), &max_tokens.map(|m| m.to_string()).unwrap_or_default(), + if agent { "agent" } else { "" }, ]) }) .unwrap_or_default(); @@ -390,7 +403,7 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { let mut tried = 0; let (reply, mut text) = loop { tried += 1; - let reply = if cli.agent { + let reply = if agent { agent::run( &agent::Opts { cfg, @@ -399,8 +412,8 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { effort: effort.as_deref(), max_tokens, user: &user, - write: cli.write, - run: cli.run, + write: cli.write || cfg.bool("write").unwrap_or(false), + run: cli.run || cli.do_it || cfg.bool("run").unwrap_or(false), }, &mut show, )? diff --git a/src/provider.rs b/src/provider.rs index 27126d8..4139327 100644 --- a/src/provider.rs +++ b/src/provider.rs @@ -210,6 +210,9 @@ impl Provider { let agent: ureq::Agent = ureq::Agent::config_builder() .http_status_as_error(false) .timeout_connect(Some(Duration::from_secs(15))) + // ponytail: no idle timeout in ureq; these backstops cover a hung server, a cold local model load fits in 5 min + .timeout_recv_response(Some(Duration::from_secs(300))) + .timeout_recv_body(Some(Duration::from_secs(1800))) .build() .into(); @@ -276,6 +279,9 @@ impl Provider { reply.text.push_str(&t); } } + if reply.stop.is_empty() { + bail!("the response ended before the model finished (connection dropped?)"); + } reply.calls = reply .pending .drain(..) diff --git a/tests/cli.rs b/tests/cli.rs index bc873a6..cfbcc90 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -766,10 +766,6 @@ fn agent_changes_files_and_runs_commands_only_when_allowed() { env.run(&["-a", "--run", "go"], "", &[]); let r = result_of_first_call(&mock); assert!(r.contains("hi-from-run") && r.contains("[exit 0]"), "{r}"); - - // --write and --run only make sense with --agent - let (_, err, code) = env.run(&["--write", "x"], "", &[]); - assert!(code != 0 && err.contains("--agent"), "{err}"); } #[test] From 1250ffdf4446cfc35f1a2fb50073170233405951 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:01:14 +0200 Subject: [PATCH 03/31] feat: repo .priniarc cannot set providers/run/write until trusted --- docs/configuration.md | 2 ++ src/config.rs | 51 +++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 12 ++++++++++ 3 files changed, 65 insertions(+) diff --git a/docs/configuration.md b/docs/configuration.md index 9f9b272..8ee6ba5 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -16,6 +16,8 @@ cache_ttl = "3d" `prinia config` prints every setting, its effective value and its source (`env`, `config` or `default`), the files that were read and the configured providers. Unknown keys and values of the wrong type are reported on stderr and ignored, so a typo never silently changes behaviour. Booleans in environment variables accept `1/0`, `true/false`, `yes/no`, `on/off`. +A repository's `.priniarc` cannot set `providers`, `run` or `write` (they could send your API key elsewhere or let the model run commands) until you read the file and run `prinia trust`. Trust is tied to the file's exact contents, so any later change, such as from a `git pull`, needs trusting again. Your own global config is always trusted. + A `.priniarc` is how a project gets its own behaviour: a repository that should never be recorded says `record = false`; one that must use a local model says `provider = "local"`. ## Providers diff --git a/src/config.rs b/src/config.rs index 81bbb14..2deb68f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -43,6 +43,48 @@ pub const KEYS: &[(&str, Ty)] = &[ ("prompt_interactive", Ty::Str), ]; +/// Keys a repository's `.priniarc` may not set until the user runs `prinia trust`: they redirect +/// the API key or let the model act on the machine. +const RISKY: &[&str] = &["providers", "run", "write"]; + +fn trust_path() -> Option { + Some(global_path()?.with_file_name("trusted")) +} + +fn digest(text: &str) -> String { + blake3::hash(text.as_bytes()).to_hex().to_string() +} + +fn is_trusted(text: &str) -> bool { + trust_path() + .and_then(|p| fs::read_to_string(p).ok()) + .is_some_and(|t| t.lines().any(|l| l.trim() == digest(text))) +} + +/// Trusts the exact current contents of every `.priniarc` above `cwd`; an edit revokes it. +pub fn trust(cwd: &Path) -> std::io::Result> { + let Some(tp) = trust_path() else { + return Ok(Vec::new()); + }; + let mut known = fs::read_to_string(&tp).unwrap_or_default(); + let mut done = Vec::new(); + for p in cwd.ancestors().map(|d| d.join(".priniarc")) { + let Ok(text) = fs::read_to_string(&p) else { + continue; + }; + if !is_trusted(&text) { + known.push_str(&digest(&text)); + known.push('\n'); + } + done.push(p); + } + if let Some(d) = tp.parent() { + fs::create_dir_all(d)?; + } + fs::write(tp, known)?; + Ok(done) +} + pub struct Config { table: Table, providers: Table, @@ -102,6 +144,8 @@ impl Config { let Ok(text) = fs::read_to_string(&p) else { continue; }; + let global = Some(&p) == global_path().as_ref(); + let trusted = global || is_trusted(&text); let t = match toml::from_str::(&text) { Ok(t) => t, Err(e) => { @@ -110,6 +154,13 @@ impl Config { } }; for (k, v) in t { + if !trusted && RISKY.contains(&k.as_str()) { + eprintln!( + "[prinia] {}: `{k}` ignored until you run `prinia trust` here", + p.display() + ); + continue; + } // a typo must not silently change behaviour, and a bad value must not shadow a // good one from a lower layer if k == "providers" { diff --git a/src/main.rs b/src/main.rs index 43b1f9c..dd8d55f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -127,6 +127,8 @@ enum Cmd { #[arg(long)] format: Option, }, + /// Allow the `.priniarc` files here to set providers, `run` and `write` + Trust, /// Back up, restore or rotate the key that protects the history Key { #[command(subcommand)] @@ -200,6 +202,16 @@ fn run() -> Result<()> { let keychain = cfg.bool("keychain").unwrap_or(false); match &cli.command { Some(Cmd::Config) => show_config(&cfg), + Some(Cmd::Trust) => { + let done = config::trust(&std::env::current_dir()?)?; + if done.is_empty() { + bail!("no .priniarc here or above"); + } + for p in done { + println!("trusted {}", p.display()); + } + Ok(()) + } Some(Cmd::Key { action }) => key_cmd(action, keychain), Some(Cmd::Stats { here, From d5995fb46b63f11714656cdc34b4b49f39e99b52 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:01:22 +0200 Subject: [PATCH 04/31] fix: the passed global config is trusted in load_from --- src/config.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/config.rs b/src/config.rs index 2deb68f..27e3f84 100644 --- a/src/config.rs +++ b/src/config.rs @@ -130,7 +130,7 @@ impl Config { } pub fn load_from(global: Option, cwd: &Path) -> Config { - let mut paths: Vec = global.into_iter().collect(); + let mut paths: Vec = global.iter().cloned().collect(); let mut dirs: Vec = cwd.ancestors().map(|d| d.join(".priniarc")).collect(); dirs.reverse(); // farthest first, so the nearest file wins paths.extend(dirs); @@ -144,7 +144,7 @@ impl Config { let Ok(text) = fs::read_to_string(&p) else { continue; }; - let global = Some(&p) == global_path().as_ref(); + let global = Some(&p) == global.as_ref(); let trusted = global || is_trusted(&text); let t = match toml::from_str::
(&text) { Ok(t) => t, From f507ebf34f32e167e1069fa2bc86cbbfe8a922a1 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:01:52 +0200 Subject: [PATCH 05/31] feat: --run asks before non-read-only commands; -y skips the question --- docs/agent.md | 4 +-- src/agent.rs | 93 ++++++++++++++++++++++++++++++++++++++++++++++++--- src/main.rs | 5 +++ 3 files changed, 96 insertions(+), 6 deletions(-) diff --git a/docs/agent.md b/docs/agent.md index bb5406b..3f0ae7a 100644 --- a/docs/agent.md +++ b/docs/agent.md @@ -26,9 +26,9 @@ The model then decides per question whether to call a tool. The `agent` setting | `list_dir` | nothing | Lists a directory | | `search` | nothing | Finds lines containing a text (case-insensitive) under a path; skips hidden directories, `target` and `node_modules` | | `write_file`, `replace` | `--write` | Creates or overwrites a file; replaces one exact, unique piece of text | -| `run_command` | `--run` | Runs a shell command in the directory and returns its output and exit code; stopped after 60 seconds | +| `run_command` | `--run` | Runs a shell command (asking first unless read-only) in the directory and returns its output and exit code; stopped after 60 seconds | -Reading is the default and changes nothing. Writing and running commands are separate switches, so you can allow one without the other. There is no per-action confirmation: the flag is the permission, so use `--write` and `--run` where you would be comfortable letting a script run, and in a git repository where changes can be reviewed. +Reading is the default and changes nothing. Writing and running commands are separate switches, so you can allow one without the other. `--run` asks before each command on your terminal (`[y/N]`), except a pipeline of read-only commands (`ls`, `cat`, `find`, `grep`, `rg`, `git status|log|diff|show`, `date`, ...), which runs straight away. Anything with `;`, `&&`, `$(...)`, redirects, or flags like `find -exec` or `-delete` asks. With no terminal to ask on, such a command is refused and the model is told. `-y` (`--yes`) runs everything without asking. `--write` has no per-file confirmation, so use it in a git repository where changes can be reviewed. All file tools stay inside the directory you ran the command in. A path that leaves it, by `..`, an absolute path or a symbolic link, is refused. `run_command` is not limited this way, since a shell command can do anything your account can. diff --git a/src/agent.rs b/src/agent.rs index b3ea151..9183808 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -18,6 +18,8 @@ pub struct Opts<'a> { pub user: &'a str, pub write: bool, pub run: bool, + /// Run every command without asking. + pub yes: bool, } const OUTPUT_CAP: usize = 20_000; @@ -226,8 +228,63 @@ fn replace(root: &Path, a: &Value) -> Result { } } -fn run_command(root: &Path, a: &Value) -> Result { +/// True for a pipeline of read-only commands. Anything with shell syntax beyond `|` (chaining, +/// substitution, redirects, background) or a flag that can write or execute needs approval. +fn read_only(cmd: &str) -> bool { + const OK: &[&str] = &[ + "ls", "cat", "head", "tail", "wc", "date", "pwd", "echo", "grep", "rg", "sort", "uniq", + "du", "df", "which", "whoami", "uname", "file", "stat", "tree", "find", "git", "basename", + "dirname", "uptime", "hostname", + ]; + const GIT: &[&str] = &[ + "status", "log", "diff", "show", "branch", "ls-files", "remote", + ]; + if cmd.contains([';', '&', '`', '$', '(', ')', '<', '>', '\n', '\\']) { + return false; + } + cmd.split('|').all(|seg| { + let w: Vec<&str> = seg.split_whitespace().collect(); + let Some(&first) = w.first() else { + return false; + }; + let bad_flag = w.iter().any(|a| { + matches!( + *a, + "-exec" | "-execdir" | "-ok" | "-delete" | "-o" | "--pre" + ) || a.starts_with("-fprint") + || a.starts_with("--output") + || a.starts_with("--pre=") + }); + OK.contains(&first) + && !bad_flag + && (first != "git" || w.get(1).is_some_and(|s| GIT.contains(s))) + }) +} + +/// Asks on the terminal; with no terminal the answer is no. +fn approve(cmd: &str) -> bool { + use std::io::{BufRead, Write}; + let Ok(mut tty) = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open("/dev/tty") + else { + return false; + }; + let _ = write!(tty, "[prinia] run `{cmd}`? [y/N] "); + let mut line = String::new(); + let _ = std::io::BufReader::new(&tty).read_line(&mut line); + line.trim().eq_ignore_ascii_case("y") +} + +fn run_command(root: &Path, a: &Value, yes: bool) -> Result { let cmd = arg(a, "command")?; + if !yes && !read_only(&cmd) && !approve(&cmd) { + return Ok( + "[not run: the user did not approve this command, or there is no terminal to ask on]" + .into(), + ); + } let mut c = if cfg!(windows) { let mut c = Command::new("cmd"); c.args(["/C", &format!("({cmd}) 2>&1")]); @@ -276,7 +333,7 @@ fn run_command(root: &Path, a: &Value) -> Result { } /// Runs one call; a failure is the model's result, not the end of the loop. -fn exec(call: &Call, root: &Path, write: bool, run: bool) -> String { +fn exec(call: &Call, root: &Path, write: bool, run: bool, yes: bool) -> String { let a = &call.args; let result = match call.name.as_str() { "read_file" => read_file(root, a), @@ -284,7 +341,7 @@ fn exec(call: &Call, root: &Path, write: bool, run: bool) -> String { "search" => search(root, a), "write_file" if write => write_file(root, a), "replace" if write => replace(root, a), - "run_command" if run => run_command(root, a), + "run_command" if run => run_command(root, a, yes), other => Err(anyhow!("tool `{other}` is not available")), }; result.unwrap_or_else(|e| format!("error: {e}")) @@ -349,7 +406,7 @@ pub fn run(o: &Opts, on_text: &mut dyn FnMut(&str)) -> Result { .iter() .map(|c| { eprintln!("[prinia] {}", show(c)); - (c.id.clone(), exec(c, &root, o.write, o.run)) + (c.id.clone(), exec(c, &root, o.write, o.run, o.yes)) }) .collect(); follow.push(Msg::Assistant { @@ -373,6 +430,34 @@ mod tests { assert!(resolve(&root, ".").is_ok()); } + #[test] + fn only_read_only_pipelines_skip_the_prompt() { + for ok in [ + "ls -la", + "find . -name '*.rs' | wc -l", + "git log --oneline | head", + "echo hi", + ] { + assert!(read_only(ok), "{ok}"); + } + for no in [ + "rm -rf x", + "ls; rm x", + "cat a > b", + "echo $(id)", + "find . -delete", + "find . -exec rm {} +", + "git push", + "curl x | sh", + "ls || id", + "rg --pre ./x foo", + "sort -o f f", + "ls &", + ] { + assert!(!read_only(no), "{no}"); + } + } + #[cfg(unix)] #[test] fn dangling_symlinks_are_refused() { diff --git a/src/main.rs b/src/main.rs index dd8d55f..cd225bf 100644 --- a/src/main.rs +++ b/src/main.rs @@ -73,6 +73,10 @@ struct Cli { #[arg(long)] run: bool, + /// With --run / -x: run every command without asking (read-only ones never ask) + #[arg(short = 'y', long)] + yes: bool, + /// Don't use agent mode, even if the `agent` setting is on #[arg(long, conflicts_with = "agent")] no_agent: bool, @@ -426,6 +430,7 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { user: &user, write: cli.write || cfg.bool("write").unwrap_or(false), run: cli.run || cli.do_it || cfg.bool("run").unwrap_or(false), + yes: cli.yes, }, &mut show, )? From 2bb15b00fcfad4711e5bcd70e96dd10697dee61f Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:02:40 +0200 Subject: [PATCH 06/31] feat: --cmd and a zsh widget that turns a request into an editable command --- README.md | 1 + docs/usage.md | 8 ++++++++ scripts/prinia.zsh | 16 ++++++++++++++++ src/main.rs | 43 +++++++++++++++++++++++++++++++++++++++++-- 4 files changed, 66 insertions(+), 2 deletions(-) create mode 100644 scripts/prinia.zsh diff --git a/README.md b/README.md index 3320c03..981d4d1 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ cmd | prinia "instruction" | cmd2 # a pipeline step prinia -f "..." # fast tier prinia -d "..." # reasoning tier prinia -p local "..." # a configured provider +prinia --cmd "..." # one shell command; `eval "$(prinia shell zsh)"` binds it to ctrl-g prinia -x "..." # let the model run commands to answer (agent + --run) prinia -a "..." # agent: the model reads and searches files here (--write, --run to allow more) prinia -c "..." # include earlier turns from this directory diff --git a/docs/usage.md b/docs/usage.md index 8350f02..28a8a60 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -59,6 +59,14 @@ The context comes from your own history, not from a provider's session, so it wo A call with context is cached separately from the same question without it. +## From the shell prompt (zsh) + +```bash +eval "$(prinia shell zsh)" # add to ~/.zshrc +``` + +Type what you want in plain words and press ctrl-g (`PRINIA_WIDGET_KEY` changes the key). The line is replaced by one shell command, which you can edit; nothing runs until you press enter. The model is told your shell and OS and which of `rg`, `fd`, `jq` and `yq` are installed. `prinia --cmd "..."` does the same without the widget. Answers from small local models can be wrong, so read the command before running it. + ## Checking the answer Models sometimes return something a script cannot use. Two flags make a call refuse bad answers: diff --git a/scripts/prinia.zsh b/scripts/prinia.zsh new file mode 100644 index 0000000..862d9bb --- /dev/null +++ b/scripts/prinia.zsh @@ -0,0 +1,16 @@ +# prinia shell integration. Type a request, press the key (default ctrl-g): the line becomes a +# command you can edit and run. Nothing runs until you press enter. +_prinia_widget() { + [[ -z $BUFFER ]] && return + local out + zle -M "prinia: thinking..." + if out=$(command prinia --cmd -- "$BUFFER" 2>/dev/null) && [[ -n $out ]]; then + BUFFER=$out + CURSOR=${#BUFFER} + zle -M "" + else + zle -M "prinia: no answer (is your model running?)" + fi +} +zle -N _prinia_widget +bindkey "${PRINIA_WIDGET_KEY:-^g}" _prinia_widget diff --git a/src/main.rs b/src/main.rs index cd225bf..653c89e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -77,6 +77,10 @@ struct Cli { #[arg(short = 'y', long)] yes: bool, + /// Answer with one shell command and nothing else (what the shell widget uses) + #[arg(long, conflicts_with_all = ["agent", "do_it", "json", "check"])] + cmd: bool, + /// Don't use agent mode, even if the `agent` setting is on #[arg(long, conflicts_with = "agent")] no_agent: bool, @@ -131,6 +135,11 @@ enum Cmd { #[arg(long)] format: Option, }, + /// Print the shell integration to load: `eval "$(prinia shell zsh)"` + Shell { + #[arg(value_parser = ["zsh"])] + shell: String, + }, /// Allow the `.priniarc` files here to set providers, `run` and `write` Trust, /// Back up, restore or rotate the key that protects the history @@ -206,6 +215,10 @@ fn run() -> Result<()> { let keychain = cfg.bool("keychain").unwrap_or(false); match &cli.command { Some(Cmd::Config) => show_config(&cfg), + Some(Cmd::Shell { .. }) => { + print!("{}", include_str!("../scripts/prinia.zsh")); + Ok(()) + } Some(Cmd::Trust) => { let done = config::trust(&std::env::current_dir()?)?; if done.is_empty() { @@ -277,7 +290,7 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { } // Raw output whenever either end is a pipe. - let piped = !stdin_tty || !stdout_tty; + let piped = !stdin_tty || !stdout_tty || cli.cmd; let validate = cli.json || cli.check.is_some(); // The setting only applies at a terminal; pipelines stay plain filters. let agent = cli.agent @@ -290,7 +303,9 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { } else { "interactive" }; - let system = if piped { + let system = if cli.cmd { + cmd_prompt() + } else if piped { cfg.str("prompt_pipe").unwrap_or_else(|| PROMPT_PIPE.into()) } else { cfg.str("prompt_interactive") @@ -513,6 +528,30 @@ fn combine(instruction: &str, payload: &str) -> String { } } +/// The system prompt for `--cmd`: names the shell and OS, and the modern tools actually installed. +fn cmd_prompt() -> String { + let shell = std::env::var("SHELL").unwrap_or_default(); + let shell = shell + .rsplit('/') + .next() + .filter(|s| !s.is_empty()) + .unwrap_or("sh"); + let path = std::env::var_os("PATH").unwrap_or_default(); + let tools: Vec<&str> = ["rg", "fd", "jq", "yq"] + .into_iter() + .filter(|t| std::env::split_paths(&path).any(|d| d.join(t).is_file())) + .collect(); + format!( + "Turn the user's request into ONE shell command for {shell} on {}. Output only the command on a single line: no explanation, no markdown, no code fences. Combine steps with | or &&. Installed tools you may prefer when they fit: {}. If the request is not something a command can do, output a single line starting with # that says why.", + std::env::consts::OS, + if tools.is_empty() { + "none".into() + } else { + tools.join(", ") + } + ) +} + fn strip_fence(s: &str) -> String { let t = s.trim(); if let Some(body) = t.strip_prefix("```").and_then(|r| r.strip_suffix("```")) From 49c915ef1692c522b2a9fddb4a4dce2263da1b8f Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:03:12 +0200 Subject: [PATCH 07/31] feat: directory config beats env; a repo can always tighten run/write --- docs/configuration.md | 8 ++-- src/config.rs | 93 ++++++++++++++++++++++++++++++++----------- src/main.rs | 2 +- 3 files changed, 75 insertions(+), 28 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 8ee6ba5..99824c6 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -3,10 +3,12 @@ Every setting can be given four ways. The first that applies wins: 1. A **flag** (where one exists, such as `-m` or `--no-record`) -2. An **environment variable**: `PRINIA_` plus the setting name in capitals, e.g. `PRINIA_MAX_TOKENS=2000` -3. A **`.priniarc`** file in the current directory or a parent. Closer files win over farther ones +2. A **`.priniarc`** file in the current directory or a parent. Closer files win over farther ones +3. An **environment variable**: `PRINIA_` plus the setting name in capitals, e.g. `PRINIA_MAX_TOKENS=2000` 4. The **global config**: `~/.config/prinia/config.toml` (`$XDG_CONFIG_HOME` is respected, on Windows `%APPDATA%\prinia`; `PRINIA_CONFIG` points at another file) +A directory beats the environment on purpose: a project that says `record = false` or `run = false` keeps saying it, whatever your shell exports. Only a flag overrides it, for one call. + ```toml # ~/.config/prinia/config.toml, or .priniarc in a project provider = "anthropic" @@ -14,7 +16,7 @@ record = true cache_ttl = "3d" ``` -`prinia config` prints every setting, its effective value and its source (`env`, `config` or `default`), the files that were read and the configured providers. Unknown keys and values of the wrong type are reported on stderr and ignored, so a typo never silently changes behaviour. Booleans in environment variables accept `1/0`, `true/false`, `yes/no`, `on/off`. +`prinia config` prints every setting, its effective value and its source (`directory`, `env`, `global` or `default`), the files that were read and the configured providers. Unknown keys and values of the wrong type are reported on stderr and ignored, so a typo never silently changes behaviour. Booleans in environment variables accept `1/0`, `true/false`, `yes/no`, `on/off`. A repository's `.priniarc` cannot set `providers`, `run` or `write` (they could send your API key elsewhere or let the model run commands) until you read the file and run `prinia trust`. Trust is tied to the file's exact contents, so any later change, such as from a `git pull`, needs trusting again. Your own global config is always trusted. diff --git a/src/config.rs b/src/config.rs index 27e3f84..fef1a2b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -85,8 +85,17 @@ pub fn trust(cwd: &Path) -> std::io::Result> { Ok(done) } +#[derive(Clone, Copy, PartialEq)] +enum Layer { + Project, + Env, + Global, +} + pub struct Config { - table: Table, + /// `.priniarc` files, nearest last. + project: Table, + global: Table, providers: Table, pub files: Vec, } @@ -136,7 +145,8 @@ impl Config { paths.extend(dirs); let mut cfg = Config { - table: Table::new(), + project: Table::new(), + global: Table::new(), providers: Table::new(), files: Vec::new(), }; @@ -154,7 +164,8 @@ impl Config { } }; for (k, v) in t { - if !trusted && RISKY.contains(&k.as_str()) { + // a repo may always tighten (`run = false`); loosening needs trust + if !trusted && RISKY.contains(&k.as_str()) && v != Value::Boolean(false) { eprintln!( "[prinia] {}: `{k}` ignored until you run `prinia trust` here", p.display() @@ -185,7 +196,11 @@ impl Config { p.display() ), Some(_) => { - cfg.table.insert(k, v); + if global { + cfg.global.insert(k, v); + } else { + cfg.project.insert(k, v); + } } } } @@ -194,33 +209,38 @@ impl Config { cfg } + /// Directory settings win over the environment, which wins over the global file, so a + /// project can say "never record" and have it hold. Flags are applied by the caller. + fn layered(&self, key: &str) -> Option<(Layer, Value)> { + if let Some(v) = self.project.get(key) { + return Some((Layer::Project, v.clone())); + } + if let Some(e) = env(key) { + return Some((Layer::Env, Value::String(e))); + } + self.global.get(key).map(|v| (Layer::Global, v.clone())) + } + pub fn str(&self, key: &str) -> Option { - env(key).or_else(|| { - self.table - .get(key) - .and_then(|v| v.as_str()) - .map(str::to_owned) - }) + self.layered(key)?.1.as_str().map(str::to_owned) } pub fn bool(&self, key: &str) -> Option { - match env(key) { - Some(e) => match e.to_lowercase().as_str() { + match self.layered(key)? { + (Layer::Env, Value::String(e)) => match e.to_lowercase().as_str() { "1" | "true" | "yes" | "on" => Some(true), "0" | "false" | "no" | "off" => Some(false), _ => None, }, - None => self.table.get(key).and_then(|v| v.as_bool()), + (_, v) => v.as_bool(), } } pub fn num(&self, key: &str) -> Option { - env(key).and_then(|e| e.parse().ok()).or_else(|| { - self.table - .get(key) - .and_then(|v| v.as_integer()) - .map(|n| n as u64) - }) + match self.layered(key)? { + (Layer::Env, Value::String(e)) => e.parse().ok(), + (_, v) => v.as_integer().map(|n| n as u64), + } } /// A field of `[providers.]`. @@ -238,11 +258,10 @@ impl Config { /// Effective value and where it came from, for `prinia config`. pub fn describe(&self, key: &str) -> (String, &'static str) { - if let Some(e) = env(key) { - return (e, "env"); - } - match self.table.get(key) { - Some(v) => (v.to_string(), "config"), + match self.layered(key) { + Some((Layer::Project, v)) => (v.to_string(), "directory"), + Some((Layer::Env, Value::String(e))) => (e, "env"), + Some((_, v)) => (v.to_string(), "global"), None => ("-".into(), "default"), } } @@ -281,4 +300,30 @@ mod tests { assert_eq!(c.provider_str("nope", "type"), None); fs::remove_dir_all(&root).unwrap(); } + + #[test] + fn directory_beats_env_beats_global() { + let root = std::env::temp_dir().join(format!("prinia-order-{}", std::process::id())); + fs::create_dir_all(&root).unwrap(); + let global = root.join("g.toml"); + fs::write(&global, "max_tokens = 1\ncache_ttl = \"1d\"\n").unwrap(); + fs::write(root.join(".priniarc"), "max_tokens = 2\n").unwrap(); + // SAFETY: only this test touches these variables + unsafe { + std::env::set_var("PRINIA_MAX_TOKENS", "3"); + std::env::set_var("PRINIA_CACHE_TTL", "2d"); + } + let c = Config::load_from(Some(global), &root); + assert_eq!(c.num("max_tokens"), Some(2), "directory beats env"); + assert_eq!( + c.str("cache_ttl").as_deref(), + Some("2d"), + "env beats global" + ); + unsafe { + std::env::remove_var("PRINIA_MAX_TOKENS"); + std::env::remove_var("PRINIA_CACHE_TTL"); + } + fs::remove_dir_all(&root).unwrap(); + } } diff --git a/src/main.rs b/src/main.rs index 653c89e..c563fbe 100644 --- a/src/main.rs +++ b/src/main.rs @@ -634,7 +634,7 @@ fn show_config(cfg: &Config) -> Result<()> { .map(|p| p.display().to_string()) .unwrap_or_default() ); - println!("# env: PRINIA_ overrides any file; flags override env"); + println!("# order: flag > .priniarc (directory) > env PRINIA_ > global file > default"); for (key, _) in config::KEYS { let (value, source) = cfg.describe(key); let value: String = value.chars().take(60).collect(); From c35fc10fea3626ff4505daefb23a9cc0a933b69d Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:03:23 +0200 Subject: [PATCH 08/31] test: use a setting the layering test does not read --- src/config.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/config.rs b/src/config.rs index fef1a2b..ae06f89 100644 --- a/src/config.rs +++ b/src/config.rs @@ -306,22 +306,22 @@ mod tests { let root = std::env::temp_dir().join(format!("prinia-order-{}", std::process::id())); fs::create_dir_all(&root).unwrap(); let global = root.join("g.toml"); - fs::write(&global, "max_tokens = 1\ncache_ttl = \"1d\"\n").unwrap(); - fs::write(root.join(".priniarc"), "max_tokens = 2\n").unwrap(); + fs::write(&global, "fast_under = 1\ncache_ttl = \"1d\"\n").unwrap(); + fs::write(root.join(".priniarc"), "fast_under = 2\n").unwrap(); // SAFETY: only this test touches these variables unsafe { - std::env::set_var("PRINIA_MAX_TOKENS", "3"); + std::env::set_var("PRINIA_FAST_UNDER", "3"); std::env::set_var("PRINIA_CACHE_TTL", "2d"); } let c = Config::load_from(Some(global), &root); - assert_eq!(c.num("max_tokens"), Some(2), "directory beats env"); + assert_eq!(c.num("fast_under"), Some(2), "directory beats env"); assert_eq!( c.str("cache_ttl").as_deref(), Some("2d"), "env beats global" ); unsafe { - std::env::remove_var("PRINIA_MAX_TOKENS"); + std::env::remove_var("PRINIA_FAST_UNDER"); std::env::remove_var("PRINIA_CACHE_TTL"); } fs::remove_dir_all(&root).unwrap(); From 18f54149f1eebb590b1eaa05815441abce348c0f Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:03:50 +0200 Subject: [PATCH 09/31] feat: prinia init picks a local model for this machine and writes the config --- README.md | 15 ++---- src/init.rs | 145 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 4 ++ 3 files changed, 153 insertions(+), 11 deletions(-) create mode 100644 src/init.rs diff --git a/README.md b/README.md index 981d4d1..b0bcc6a 100644 --- a/README.md +++ b/README.md @@ -39,19 +39,12 @@ prinia "hello" No account or API key needed. With [Ollama](https://ollama.com) running: ```bash -ollama pull qwen2.5:14b # ~9 GB; fits a 16 GB machine, fast on Apple silicon -mkdir -p ~/.config/prinia && cat > ~/.config/prinia/config.toml <<'EOF' -provider = "local" - -[providers.local] -type = "openai" -base_url = "http://localhost:11434/v1" -model = "qwen2.5:14b" -EOF -prinia "how do I find the largest files in a directory?" +prinia init ``` -Small models (3B and under) invent commands and ignore instructions; `qwen2.5:14b` is a good starting point, and `qwen2.5:32b` is better if you have the memory. Other local runners with an OpenAI-compatible endpoint (LM Studio, llama.cpp, vLLM) work the same way with a different `base_url`. +It checks how much memory you have, suggests a model that fits (for example `qwen2.5:14b` on 16 GB or more, plus `qwen2.5:32b` for `-d` on 40 GB or more), offers to `ollama pull` it, and writes `~/.config/prinia/config.toml` (it never overwrites an existing one). To do it by hand, see [Configuration](docs/configuration.md#providers). + +Small models (3B and under) invent commands and ignore instructions. Other OpenAI-compatible runners (LM Studio, llama.cpp, vLLM) work with a different `base_url`. See [Install](docs/install.md) for other platforms and building from source, and [Configuration](docs/configuration.md) for local models and other providers. diff --git a/src/init.rs b/src/init.rs new file mode 100644 index 0000000..8b4e1ce --- /dev/null +++ b/src/init.rs @@ -0,0 +1,145 @@ +//! `prinia init`: find a local model server, pick a model that fits this machine, write the config. +use crate::config; +use anyhow::{Result, anyhow}; +use std::io::{BufRead, IsTerminal, Write}; +use std::process::Command; +use std::time::Duration; + +const OLLAMA: &str = "http://localhost:11434"; + +/// (regular model, approximate download in GB, deep model) for this much memory. +fn recommend(gb: u64) -> (&'static str, u64, Option<&'static str>) { + match gb { + 40.. => ("qwen2.5:14b", 9, Some("qwen2.5:32b")), + 16.. => ("qwen2.5:14b", 9, None), + 8.. => ("qwen2.5:7b", 5, None), + _ => ("llama3.2:3b", 2, None), + } +} + +fn memory_gb() -> Option { + let bytes = if cfg!(target_os = "macos") { + let out = Command::new("sysctl") + .args(["-n", "hw.memsize"]) + .output() + .ok()?; + String::from_utf8_lossy(&out.stdout) + .trim() + .parse::() + .ok()? + } else { + let t = std::fs::read_to_string("/proc/meminfo").ok()?; + let kb: u64 = t + .lines() + .find_map(|l| l.strip_prefix("MemTotal:"))? + .split_whitespace() + .next()? + .parse() + .ok()?; + kb * 1024 + }; + Some(bytes / (1 << 30)) +} + +fn installed() -> Option> { + let agent: ureq::Agent = ureq::Agent::config_builder() + .timeout_global(Some(Duration::from_secs(2))) + .build() + .into(); + let v: serde_json::Value = agent + .get(format!("{OLLAMA}/api/tags")) + .call() + .ok()? + .body_mut() + .read_json() + .ok()?; + Some( + v["models"] + .as_array()? + .iter() + .filter_map(|m| m["name"].as_str().map(str::to_owned)) + .collect(), + ) +} + +fn ask(question: &str) -> bool { + if !std::io::stdin().is_terminal() { + return false; + } + print!("{question} [y/N] "); + let _ = std::io::stdout().flush(); + let mut l = String::new(); + let _ = std::io::stdin().lock().read_line(&mut l); + l.trim().eq_ignore_ascii_case("y") +} + +fn pull(model: &str, gb: u64) -> Result<()> { + if installed().is_some_and(|m| m.iter().any(|n| n == model)) { + return Ok(()); + } + if ask(&format!( + "Download {model} (about {gb} GB) with `ollama pull`?" + )) { + Command::new("ollama").args(["pull", model]).status()?; + } else { + println!("Later: ollama pull {model}"); + } + Ok(()) +} + +pub fn run() -> Result<()> { + let keys = ["ANTHROPIC_API_KEY", "OPENAI_API_KEY"] + .iter() + .any(|k| std::env::var_os(k).is_some()); + let Some(_) = installed() else { + if keys { + println!("An API key is set in your environment: `prinia \"hello\"` already works."); + } else { + println!( + "No model server found at {OLLAMA} and no API key set.\nInstall Ollama (https://ollama.com), start it and run `prinia init` again, or export ANTHROPIC_API_KEY / OPENAI_API_KEY." + ); + } + return Ok(()); + }; + let gb = memory_gb().unwrap_or(8); + let (model, size, deep) = recommend(gb); + println!( + "Ollama is running; this machine has about {gb} GB of memory. Recommended: {model}{}.", + deep.map(|d| format!(" (deep: {d})")).unwrap_or_default() + ); + pull(model, size)?; + if let Some(d) = deep { + pull(d, 20)?; + } + let mut cfg = format!( + "provider = \"local\"\n\n[providers.local]\ntype = \"openai\"\nbase_url = \"{OLLAMA}/v1\"\nmodel = \"{model}\"\nfast_model = \"{model}\"\n" + ); + if let Some(d) = deep { + cfg.push_str(&format!("deep_model = \"{d}\"\n")); + } + let path = config::global_path().ok_or_else(|| anyhow!("no config directory"))?; + if path.exists() { + println!( + "{} already exists and was not changed. Add this to use the model:\n\n{cfg}", + path.display() + ); + } else { + std::fs::create_dir_all(path.parent().ok_or_else(|| anyhow!("bad config path"))?)?; + std::fs::write(&path, cfg)?; + println!("Wrote {}. Try: prinia \"hello\"", path.display()); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn model_scales_with_memory() { + assert_eq!(recommend(48).2, Some("qwen2.5:32b")); + assert_eq!(recommend(16).0, "qwen2.5:14b"); + assert_eq!(recommend(8).0, "qwen2.5:7b"); + assert_eq!(recommend(4).0, "llama3.2:3b"); + } +} diff --git a/src/main.rs b/src/main.rs index c563fbe..2d3c6c2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,6 +14,7 @@ mod config; mod context; mod curate; mod history; +mod init; mod key; mod keychain; mod provider; @@ -135,6 +136,8 @@ enum Cmd { #[arg(long)] format: Option, }, + /// Find a local model server, pick a model for this machine and write the config + Init, /// Print the shell integration to load: `eval "$(prinia shell zsh)"` Shell { #[arg(value_parser = ["zsh"])] @@ -215,6 +218,7 @@ fn run() -> Result<()> { let keychain = cfg.bool("keychain").unwrap_or(false); match &cli.command { Some(Cmd::Config) => show_config(&cfg), + Some(Cmd::Init) => init::run(), Some(Cmd::Shell { .. }) => { print!("{}", include_str!("../scripts/prinia.zsh")); Ok(()) From 967005f7c3f410b1ae91ae5b10e9e2b079ba2f08 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:04:31 +0200 Subject: [PATCH 10/31] feat: -t NAME runs a saved instruction from .prinia/templates --- README.md | 1 + docs/usage.md | 13 +++++++++++++ src/config.rs | 36 ++++++++++++++++++++++++++++++++++++ src/main.rs | 14 +++++++++++++- 4 files changed, 63 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b0bcc6a..3547718 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ cmd | prinia "instruction" | cmd2 # a pipeline step prinia -f "..." # fast tier prinia -d "..." # reasoning tier prinia -p local "..." # a configured provider +prinia -t NAME "..." # a saved instruction (docs/usage.md#templates) prinia --cmd "..." # one shell command; `eval "$(prinia shell zsh)"` binds it to ctrl-g prinia -x "..." # let the model run commands to answer (agent + --run) prinia -a "..." # agent: the model reads and searches files here (--write, --run to allow more) diff --git a/docs/usage.md b/docs/usage.md index 28a8a60..d484f0e 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -59,6 +59,19 @@ The context comes from your own history, not from a provider's session, so it wo A call with context is cached separately from the same question without it. +## Templates + +Save an instruction you reuse as a file, then call it by name: + +```bash +mkdir -p .prinia/templates +echo "Write a one-line conventional commit message for this diff." > .prinia/templates/commit +git diff | prinia -t commit | pbcopy +git diff | prinia -t commit "mention the ticket ABC-12" # extra words are added after the template +``` + +`prinia -t NAME` looks for `.prinia/templates/NAME` in the current directory and its parents (so a repository can ship its own), then `templates/NAME` next to your global config. A template is plain text; it is the instruction, nothing more, so it cannot change settings. + ## From the shell prompt (zsh) ```bash diff --git a/src/config.rs b/src/config.rs index ae06f89..58932b4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -92,6 +92,29 @@ enum Layer { Global, } +/// A saved instruction: the nearest `.prinia/templates/NAME` above `cwd`, else the config directory's. +pub fn template(name: &str, cwd: &Path) -> anyhow::Result { + if name.is_empty() || name.contains(['/', '\\']) || name.starts_with('.') { + anyhow::bail!("bad template name {name:?}"); + } + let mut dirs: Vec = cwd + .ancestors() + .map(|d| d.join(".prinia/templates")) + .collect(); + dirs.extend(global_path().and_then(|p| Some(p.parent()?.join("templates")))); + for d in &dirs { + if let Ok(t) = fs::read_to_string(d.join(name)) { + return Ok(t.trim().to_string()); + } + } + anyhow::bail!( + "no template `{name}`; put the instruction in .prinia/templates/{name} or {}", + dirs.last() + .map(|d| d.join(name).display().to_string()) + .unwrap_or_default() + ) +} + pub struct Config { /// `.priniarc` files, nearest last. project: Table, @@ -326,4 +349,17 @@ mod tests { } fs::remove_dir_all(&root).unwrap(); } + + #[test] + fn templates_come_from_the_nearest_directory_and_reject_paths() { + let root = std::env::temp_dir().join(format!("prinia-tpl-{}", std::process::id())); + let sub = root.join("a"); + fs::create_dir_all(root.join(".prinia/templates")).unwrap(); + fs::create_dir_all(&sub).unwrap(); + fs::write(root.join(".prinia/templates/t"), "do it\n").unwrap(); + assert_eq!(template("t", &sub).unwrap(), "do it"); + assert!(template("../t", &sub).is_err()); + assert!(template("missing-template-xyz", &sub).is_err()); + fs::remove_dir_all(&root).unwrap(); + } } diff --git a/src/main.rs b/src/main.rs index 2d3c6c2..0f62959 100644 --- a/src/main.rs +++ b/src/main.rs @@ -78,6 +78,10 @@ struct Cli { #[arg(short = 'y', long)] yes: bool, + /// Use a saved instruction: `.prinia/templates/NAME` here or above, or `templates/NAME` in the config directory + #[arg(short = 't', long, value_name = "NAME")] + template: Option, + /// Answer with one shell command and nothing else (what the shell widget uses) #[arg(long, conflicts_with_all = ["agent", "do_it", "json", "check"])] cmd: bool, @@ -284,7 +288,15 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { if !stdin_tty { std::io::stdin().read_to_string(&mut payload)?; } - let instruction = cli.prompt.clone().unwrap_or_default(); + let mut instruction = cli.prompt.clone().unwrap_or_default(); + if let Some(name) = &cli.template { + let t = config::template(name, &std::env::current_dir()?)?; + instruction = if instruction.is_empty() { + t + } else { + format!("{t}\n\n{instruction}") + }; + } if instruction.is_empty() && payload.trim().is_empty() { bail!("nothing to do. Usage: prinia \"question\" or cmd | prinia \"instruction\""); } From 3bce0795bc6903ff1f1323f8e7f3d53cfdc0867d Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:05:11 +0200 Subject: [PATCH 11/31] feat: --each runs one call per stdin line in parallel; providers are device-level only --- docs/configuration.md | 2 +- docs/usage.md | 9 +++++ src/config.rs | 13 +++++-- src/main.rs | 81 ++++++++++++++++++++++++++++++++++++++++++- tests/cli.rs | 25 +++++++++++++ 5 files changed, 125 insertions(+), 5 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 99824c6..5c81029 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -18,7 +18,7 @@ cache_ttl = "3d" `prinia config` prints every setting, its effective value and its source (`directory`, `env`, `global` or `default`), the files that were read and the configured providers. Unknown keys and values of the wrong type are reported on stderr and ignored, so a typo never silently changes behaviour. Booleans in environment variables accept `1/0`, `true/false`, `yes/no`, `on/off`. -A repository's `.priniarc` cannot set `providers`, `run` or `write` (they could send your API key elsewhere or let the model run commands) until you read the file and run `prinia trust`. Trust is tied to the file's exact contents, so any later change, such as from a `git pull`, needs trusting again. Your own global config is always trusted. +Providers (URLs and key names) are device-level: `[providers.*]` is only read from your global config, and a `.priniarc` that defines one is ignored with a warning. A `.priniarc` can still choose among your providers with `provider = "local"`. A repository's `.priniarc` also cannot turn on `run` or `write` (they let the model act on your machine) until you read the file and run `prinia trust`; turning them off needs no trust. Trust is tied to the file's exact contents, so any later change, such as from a `git pull`, needs trusting again. Your own global config is always trusted. A `.priniarc` is how a project gets its own behaviour: a repository that should never be recorded says `record = false`; one that must use a local model says `provider = "local"`. diff --git a/docs/usage.md b/docs/usage.md index d484f0e..0764ad0 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -59,6 +59,15 @@ The context comes from your own history, not from a provider's session, so it wo A call with context is cached separately from the same question without it. +## One call per line + +```bash +cat urls.txt | prinia --each "one-line summary of the page at this URL" +git ls-files '*.py' | prinia --each -j 8 "does this file name suggest a test? answer yes or no" +``` + +`--each` makes a separate call for every non-empty stdin line, `-j N` at a time (default 4), and prints the answers in input order, one per line. Each call is cached and recorded like any other, so rerunning a half-finished batch only asks for what is missing. A failed line prints an empty answer, reports the reason on stderr, and the exit code is non-zero. Ask for one-line answers; a multi-line answer breaks the one-answer-per-line pairing. + ## Templates Save an instruction you reuse as a file, then call it by name: diff --git a/src/config.rs b/src/config.rs index 58932b4..e6138c4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -43,9 +43,9 @@ pub const KEYS: &[(&str, Ty)] = &[ ("prompt_interactive", Ty::Str), ]; -/// Keys a repository's `.priniarc` may not set until the user runs `prinia trust`: they redirect -/// the API key or let the model act on the machine. -const RISKY: &[&str] = &["providers", "run", "write"]; +/// Keys a repository's `.priniarc` may not set until the user runs `prinia trust`: they let the +/// model act on the machine. `[providers]` is never accepted from a repository. +const RISKY: &[&str] = &["run", "write"]; fn trust_path() -> Option { Some(global_path()?.with_file_name("trusted")) @@ -198,6 +198,13 @@ impl Config { // a typo must not silently change behaviour, and a bad value must not shadow a // good one from a lower layer if k == "providers" { + if !global { + eprintln!( + "[prinia] {}: providers are device-level; define them in your global config", + p.display() + ); + continue; + } match v { Value::Table(ps) => cfg .providers diff --git a/src/main.rs b/src/main.rs index 0f62959..2ac1d43 100644 --- a/src/main.rs +++ b/src/main.rs @@ -82,6 +82,14 @@ struct Cli { #[arg(short = 't', long, value_name = "NAME")] template: Option, + /// Run the instruction once per line of stdin, in parallel; answers are printed in input order + #[arg(long, conflicts_with_all = ["agent", "do_it", "cmd"])] + each: bool, + + /// With --each: how many calls run at once + #[arg(short = 'j', long, default_value_t = 4, value_parser = clap::value_parser!(u32).range(1..=64))] + jobs: u32, + /// Answer with one shell command and nothing else (what the shell widget uses) #[arg(long, conflicts_with_all = ["agent", "do_it", "json", "check"])] cmd: bool, @@ -147,7 +155,7 @@ enum Cmd { #[arg(value_parser = ["zsh"])] shell: String, }, - /// Allow the `.priniarc` files here to set providers, `run` and `write` + /// Allow the `.priniarc` files here to turn on `run` and `write` Trust, /// Back up, restore or rotate the key that protects the history Key { @@ -277,10 +285,81 @@ fn run() -> Result<()> { action: Some(HistoryCmd::Clean { yes }), .. }) => history::clean(&Store::open(keychain)?, &cfg, *yes), + None if cli.each => each(&cli), None => ask(&cli, &cfg, keychain), } } +/// One child `prinia` per stdin line, so caching, recording, checks and errors behave exactly as +/// for a single call. Answers come back in input order; failed lines are reported and counted. +fn each(cli: &Cli) -> Result<()> { + let mut input = String::new(); + std::io::stdin().read_to_string(&mut input)?; + let lines: Vec<&str> = input.lines().filter(|l| !l.trim().is_empty()).collect(); + let mut args: Vec = Vec::new(); + let mut raw = std::env::args().skip(1); + while let Some(a) = raw.next() { + match a.as_str() { + "--each" => {} + "-j" | "--jobs" => { + raw.next(); + } + _ if a.starts_with("--jobs=") => {} + _ => args.push(a), + } + } + let exe = std::env::current_exe()?; + let results = std::sync::Mutex::new(vec![None::<(String, bool)>; lines.len()]); + let next = std::sync::atomic::AtomicUsize::new(0); + let done = std::sync::atomic::AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..(cli.jobs as usize).min(lines.len()) { + s.spawn(|| { + loop { + let i = next.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let Some(line) = lines.get(i) else { return }; + let r = std::process::Command::new(&exe) + .args(&args) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .and_then(|mut c| { + let _ = c.stdin.take().map(|mut p| p.write_all(line.as_bytes())); + c.wait_with_output() + }); + let (text, ok) = match r { + Ok(o) if o.status.success() => ( + String::from_utf8_lossy(&o.stdout).trim_end().to_string(), + true, + ), + Ok(o) => (String::from_utf8_lossy(&o.stderr).trim().to_string(), false), + Err(e) => (e.to_string(), false), + }; + results.lock().unwrap()[i] = Some((text, ok)); + let n = done.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1; + eprintln!("[prinia] {n}/{}", lines.len()); + } + }); + } + }); + let mut failed = 0; + for (i, r) in results.into_inner().unwrap().into_iter().enumerate() { + let (text, ok) = r.unwrap_or_default(); + if ok { + let _ = writeln!(std::io::stdout(), "{text}"); + } else { + failed += 1; + eprintln!("[prinia] line {} failed: {text}", i + 1); + let _ = writeln!(std::io::stdout()); + } + } + if failed > 0 { + bail!("{failed} of {} lines failed", lines.len()); + } + Ok(()) +} + fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { let stdin_tty = std::io::stdin().is_terminal(); let stdout_tty = std::io::stdout().is_terminal(); diff --git a/tests/cli.rs b/tests/cli.rs index cfbcc90..d3f9f3b 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -301,6 +301,31 @@ fn openai_compatible_provider() { ); } +#[test] +fn each_runs_one_call_per_line_and_reports_failures() { + let mock = Mock::start("answer", 200); + let env = Env::new("each", &mock); + let (out, err, code) = env.run( + &["-p", "local", "--each", "-j", "2", "summarize"], + "a\n\nb\nc\n", + &[], + ); + assert_eq!( + (out.as_str(), code), + ("answer\nanswer\nanswer\n", 0), + "stderr: {err}" + ); + assert_eq!(mock.hits(), 3, "blank lines are skipped, one call per line"); + + let bad = Mock::start("x", 401); + let env = Env::new("each-bad", &bad); + let (out, err, code) = env.run(&["-p", "local", "--each", "q"], "a\nb\n", &[]); + assert!( + code != 0 && out == "\n\n" && err.contains("line 1 failed"), + "{out:?} {err}" + ); +} + #[test] fn piped_output_loses_its_code_fence() { let mock = Mock::start("```json\n{\"a\":1}\n```", 200); From 00dbba12e025b46fd254c8a02d38b7ecfda74d66 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:06:24 +0200 Subject: [PATCH 12/31] feat: max_input splits long stdin into parts and combines the answers; .priniarc holds behaviour only --- docs/configuration.md | 8 ++- docs/usage.md | 11 ++++ src/config.rs | 50 ++++++++++++-- src/init.rs | 2 +- src/main.rs | 150 +++++++++++++++++++++++++++++++++++++----- 5 files changed, 193 insertions(+), 28 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 5c81029..b0e2563 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -7,7 +7,7 @@ Every setting can be given four ways. The first that applies wins: 3. An **environment variable**: `PRINIA_` plus the setting name in capitals, e.g. `PRINIA_MAX_TOKENS=2000` 4. The **global config**: `~/.config/prinia/config.toml` (`$XDG_CONFIG_HOME` is respected, on Windows `%APPDATA%\prinia`; `PRINIA_CONFIG` points at another file) -A directory beats the environment on purpose: a project that says `record = false` or `run = false` keeps saying it, whatever your shell exports. Only a flag overrides it, for one call. +A directory beats the environment on purpose: a project that says `record = false` or `run = false` keeps saying it, whatever your shell exports. Only a flag overrides it, for one call. This is safe because a project file can only set behaviour (below), never where your data goes. ```toml # ~/.config/prinia/config.toml, or .priniarc in a project @@ -18,9 +18,11 @@ cache_ttl = "3d" `prinia config` prints every setting, its effective value and its source (`directory`, `env`, `global` or `default`), the files that were read and the configured providers. Unknown keys and values of the wrong type are reported on stderr and ignored, so a typo never silently changes behaviour. Booleans in environment variables accept `1/0`, `true/false`, `yes/no`, `on/off`. -Providers (URLs and key names) are device-level: `[providers.*]` is only read from your global config, and a `.priniarc` that defines one is ignored with a warning. A `.priniarc` can still choose among your providers with `provider = "local"`. A repository's `.priniarc` also cannot turn on `run` or `write` (they let the model act on your machine) until you read the file and run `prinia trust`; turning them off needs no trust. Trust is tied to the file's exact contents, so any later change, such as from a `git pull`, needs trusting again. Your own global config is always trusted. +A `.priniarc` holds behaviour only: `record`, `cache`, `cache_ttl`, `context`, `context_chars`, `max_tokens`, `effort`, `fast_under`, `deep_over`, `check_retries`, `max_input`, `agent`, `agent_steps`, `run`, `write` and the two prompts. Everything about the device is read only from your global config and ignored, with a warning, in a project file: `[providers.*]`, `provider`, the model names, `keychain` and the history limits. A repository therefore cannot choose where your prompts go. -A `.priniarc` is how a project gets its own behaviour: a repository that should never be recorded says `record = false`; one that must use a local model says `provider = "local"`. +Settings that let the model act on your machine or change what it is told (`run`, `write`, `agent`, `prompt_pipe`, `prompt_interactive`) are ignored in a project file until you read it and run `prinia trust`. Turning `run`, `write` or `agent` off needs no trust. Trust is tied to the file's exact contents, so any later change, such as from a `git pull`, needs trusting again. Your own global config is always trusted. + +A `.priniarc` is how a project gets its own behaviour: a repository that should never be recorded says `record = false`, one that must never run commands says `run = false`. ## Providers diff --git a/docs/usage.md b/docs/usage.md index 0764ad0..6a860eb 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -59,6 +59,17 @@ The context comes from your own history, not from a provider's session, so it wo A call with context is cached separately from the same question without it. +## Long input + +Models have a context limit. Set `max_input` (characters, `0` = off, which is the default) and prinia handles longer stdin in two steps: it runs your instruction on each part separately (in parallel, `-j` at a time, cut at line ends), then asks once more to combine the partial answers. + +```bash +prinia init # sets max_input = 48000 for a local model +cat huge.log | PRINIA_MAX_INPUT=40000 prinia "what went wrong, in 5 bullets?" +``` + +This works for summaries and extraction. It does not work for questions that need the whole text at once, such as counting across parts or comparing the first line with the last: each part is answered blind to the others, and a small model's combined answer to those can be wrong. `max_input` is a project setting too. + ## One call per line ```bash diff --git a/src/config.rs b/src/config.rs index e6138c4..37fb349 100644 --- a/src/config.rs +++ b/src/config.rs @@ -36,6 +36,7 @@ pub const KEYS: &[(&str, Ty)] = &[ ("agent", Ty::Bool), ("write", Ty::Bool), ("run", Ty::Bool), + ("max_input", Ty::Num), ("agent_steps", Ty::Num), ("check_retries", Ty::Num), ("keychain", Ty::Bool), @@ -43,9 +44,33 @@ pub const KEYS: &[(&str, Ty)] = &[ ("prompt_interactive", Ty::Str), ]; -/// Keys a repository's `.priniarc` may not set until the user runs `prinia trust`: they let the -/// model act on the machine. `[providers]` is never accepted from a repository. -const RISKY: &[&str] = &["run", "write"]; +/// Behaviour keys a repository's `.priniarc` may not turn on until the user runs `prinia trust`: +/// they let the model act on the machine or change what it is told. +const RISKY: &[&str] = &["run", "write", "agent", "prompt_pipe", "prompt_interactive"]; + +/// What a repository's `.priniarc` may set: how prinia behaves in that directory. Where data goes +/// (provider, models, keys) and how the shared history is kept are decisions for the device. +const PROJECT: &[&str] = &[ + "record", + "cache", + "cache_ttl", + "context", + "context_chars", + "max_tokens", + "effort", + "fast_effort", + "deep_effort", + "fast_under", + "deep_over", + "check_retries", + "max_input", + "agent", + "agent_steps", + "run", + "write", + "prompt_pipe", + "prompt_interactive", +]; fn trust_path() -> Option { Some(global_path()?.with_file_name("trusted")) @@ -187,6 +212,15 @@ impl Config { } }; for (k, v) in t { + if !global && k != "providers" && !PROJECT.contains(&k.as_str()) { + if KEYS.iter().any(|(n, _)| *n == k) { + eprintln!( + "[prinia] {}: `{k}` is device-level; set it in your global config", + p.display() + ); + continue; + } + } // a repo may always tighten (`run = false`); loosening needs trust if !trusted && RISKY.contains(&k.as_str()) && v != Value::Boolean(false) { eprintln!( @@ -308,13 +342,17 @@ mod tests { fs::create_dir_all(&sub).unwrap(); let global = root.join("global.toml"); fs::write(&global, "record = false\nmodel = \"g\"\nmax_tokens = 100\n[providers.local]\ntype = \"openai\"\nbase_url = \"http://x/v1\"\n").unwrap(); - fs::write(root.join(".priniarc"), "model = \"proj\"\nrecrod = true\n").unwrap(); - fs::write(sub.join(".priniarc"), "record = true\nmodel = 5\n").unwrap(); + fs::write( + root.join(".priniarc"), + "cache_ttl = \"proj\"\nrecrod = true\n", + ) + .unwrap(); + fs::write(sub.join(".priniarc"), "record = true\ncache_ttl = 5\n").unwrap(); let c = Config::load_from(Some(global), &sub); assert_eq!(c.bool("record"), Some(true), "nearest file wins"); assert_eq!( - c.str("model").as_deref(), + c.str("cache_ttl").as_deref(), Some("proj"), "a wrongly typed value does not shadow the parent's" ); diff --git a/src/init.rs b/src/init.rs index 8b4e1ce..bf1076e 100644 --- a/src/init.rs +++ b/src/init.rs @@ -112,7 +112,7 @@ pub fn run() -> Result<()> { pull(d, 20)?; } let mut cfg = format!( - "provider = \"local\"\n\n[providers.local]\ntype = \"openai\"\nbase_url = \"{OLLAMA}/v1\"\nmodel = \"{model}\"\nfast_model = \"{model}\"\n" + "provider = \"local\"\nmax_input = 48000 # longer input is processed in parts\n\n[providers.local]\ntype = \"openai\"\nbase_url = \"{OLLAMA}/v1\"\nmodel = \"{model}\"\nfast_model = \"{model}\"\n" ); if let Some(d) = deep { cfg.push_str(&format!("deep_model = \"{d}\"\n")); diff --git a/src/main.rs b/src/main.rs index 2ac1d43..ea93bb7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -290,13 +290,9 @@ fn run() -> Result<()> { } } -/// One child `prinia` per stdin line, so caching, recording, checks and errors behave exactly as -/// for a single call. Answers come back in input order; failed lines are reported and counted. -fn each(cli: &Cli) -> Result<()> { - let mut input = String::new(); - std::io::stdin().read_to_string(&mut input)?; - let lines: Vec<&str> = input.lines().filter(|l| !l.trim().is_empty()).collect(); - let mut args: Vec = Vec::new(); +/// The command line without the flags that only drive batching. +fn child_args() -> Vec { + let mut args = Vec::new(); let mut raw = std::env::args().skip(1); while let Some(a) = raw.next() { match a.as_str() { @@ -308,27 +304,37 @@ fn each(cli: &Cli) -> Result<()> { _ => args.push(a), } } - let exe = std::env::current_exe()?; - let results = std::sync::Mutex::new(vec![None::<(String, bool)>; lines.len()]); + args +} + +/// One child `prinia` per input, `jobs` at a time, so caching, recording, checks and errors behave +/// exactly as for a single call. Results come back in input order as (text, succeeded). +fn fan_out(args: &[String], inputs: &[String], jobs: usize) -> Vec<(String, bool)> { + let Ok(exe) = std::env::current_exe() else { + return vec![("cannot find the prinia binary".into(), false); inputs.len()]; + }; + let results = std::sync::Mutex::new(vec![(String::new(), false); inputs.len()]); let next = std::sync::atomic::AtomicUsize::new(0); let done = std::sync::atomic::AtomicUsize::new(0); std::thread::scope(|s| { - for _ in 0..(cli.jobs as usize).min(lines.len()) { + for _ in 0..jobs.min(inputs.len()) { s.spawn(|| { loop { let i = next.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - let Some(line) = lines.get(i) else { return }; + let Some(input) = inputs.get(i) else { return }; let r = std::process::Command::new(&exe) - .args(&args) + .args(args) + // chunks are already small; never split them again + .env("PRINIA_MAX_INPUT", "0") .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) .spawn() .and_then(|mut c| { - let _ = c.stdin.take().map(|mut p| p.write_all(line.as_bytes())); + let _ = c.stdin.take().map(|mut p| p.write_all(input.as_bytes())); c.wait_with_output() }); - let (text, ok) = match r { + let r = match r { Ok(o) if o.status.success() => ( String::from_utf8_lossy(&o.stdout).trim_end().to_string(), true, @@ -336,16 +342,29 @@ fn each(cli: &Cli) -> Result<()> { Ok(o) => (String::from_utf8_lossy(&o.stderr).trim().to_string(), false), Err(e) => (e.to_string(), false), }; - results.lock().unwrap()[i] = Some((text, ok)); + results.lock().unwrap()[i] = r; let n = done.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1; - eprintln!("[prinia] {n}/{}", lines.len()); + eprintln!("[prinia] {n}/{}", inputs.len()); } }); } }); + results.into_inner().unwrap() +} + +fn each(cli: &Cli) -> Result<()> { + let mut input = String::new(); + std::io::stdin().read_to_string(&mut input)?; + let lines: Vec = input + .lines() + .filter(|l| !l.trim().is_empty()) + .map(str::to_owned) + .collect(); let mut failed = 0; - for (i, r) in results.into_inner().unwrap().into_iter().enumerate() { - let (text, ok) = r.unwrap_or_default(); + for (i, (text, ok)) in fan_out(&child_args(), &lines, cli.jobs as usize) + .into_iter() + .enumerate() + { if ok { let _ = writeln!(std::io::stdout(), "{text}"); } else { @@ -360,6 +379,83 @@ fn each(cli: &Cli) -> Result<()> { Ok(()) } +/// Pieces of at most `max` characters, cut at line ends where possible. +fn chunks(text: &str, max: usize) -> Vec { + let mut out = Vec::new(); + let mut cur = String::new(); + for line in text.split_inclusive('\n') { + let mut rest = line; + while cur.chars().count() + rest.chars().count() > max { + let room = max - cur.chars().count(); + if room == 0 { + out.push(std::mem::take(&mut cur)); + continue; + } + // a single over-long line is cut mid-line + let cut = rest.char_indices().nth(room).map_or(rest.len(), |(i, _)| i); + if cur.is_empty() { + out.push(rest[..cut].to_string()); + rest = &rest[cut..]; + } else { + out.push(std::mem::take(&mut cur)); + } + } + cur.push_str(rest); + } + if !cur.is_empty() { + out.push(cur); + } + out +} + +/// Input over `max_input` characters: run the instruction on each piece, then once more over the +/// partial answers. +fn map_reduce(cli: &Cli, instruction: &str, payload: &str, max: usize) -> Result<()> { + let pieces = chunks(payload, max); + eprintln!( + "[prinia] input is {} characters; processing it in {} parts", + payload.chars().count(), + pieces.len() + ); + let partial = fan_out(&child_args(), &pieces, cli.jobs as usize); + if let Some(i) = partial.iter().position(|(_, ok)| !ok) { + bail!("part {} failed: {}", i + 1, partial[i].0); + } + let joined = partial + .iter() + .enumerate() + .map(|(i, (t, _))| format!("--- part {} ---\n{t}", i + 1)) + .collect::>() + .join("\n\n"); + let final_instruction = format!( + "The input was too long, so the instruction below was applied to consecutive parts of it separately; the results are given as the input. Combine them into one final answer to the instruction, without mentioning the parts.\n\nInstruction: {instruction}" + ); + let mut args = child_args(); + // the final call carries the full instruction itself, so drop the template and the original one + let mut skip = false; + args.retain(|a| { + if skip { + skip = false; + return false; + } + match a.as_str() { + "-t" | "--template" => { + skip = true; + false + } + _ if a.starts_with("--template=") => false, + _ => cli.prompt.as_deref() != Some(a.as_str()), + } + }); + args.push(final_instruction); + let (text, ok) = fan_out(&args, &[joined], 1).remove(0); + if !ok { + bail!("{text}"); + } + println!("{text}"); + Ok(()) +} + fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { let stdin_tty = std::io::stdin().is_terminal(); let stdout_tty = std::io::stdout().is_terminal(); @@ -380,6 +476,10 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { bail!("nothing to do. Usage: prinia \"question\" or cmd | prinia \"instruction\""); } + let max_input = cfg.num("max_input").unwrap_or(0) as usize; + if max_input > 0 && payload.chars().count() > max_input && !cli.cmd { + return map_reduce(cli, &instruction, &payload, max_input); + } if !stdin_tty && payload.trim().is_empty() { eprintln!("prinia: warning: stdin is empty, answering the instruction alone"); } @@ -749,6 +849,20 @@ fn show_config(cfg: &Config) -> Result<()> { mod tests { use super::*; + #[test] + fn chunks_cut_at_lines_and_lose_nothing() { + let text = "aaaa\nbbbb\ncc\n"; + let c = chunks(text, 10); + assert_eq!(c, ["aaaa\nbbbb\n", "cc\n"]); + assert_eq!(chunks("xxxxxxxxxxxx", 5).concat(), "xxxxxxxxxxxx"); + assert!( + chunks("é".repeat(7).as_str(), 3) + .iter() + .all(|p| p.chars().count() <= 3) + ); + assert!(chunks("", 5).is_empty()); + } + #[test] fn combine_and_fence() { assert_eq!(combine("do x", "data"), "do x\n\ndata"); From e77ed842dd6b0067566279bab24d50efdf5a6cba Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:07:21 +0200 Subject: [PATCH 13/31] chore: clippy, README entries for init, trust and --each --- README.md | 3 +++ src/agent.rs | 2 +- src/config.rs | 18 ++++++++++-------- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 3547718..7454c69 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ cmd | prinia "instruction" | cmd2 # a pipeline step prinia -f "..." # fast tier prinia -d "..." # reasoning tier prinia -p local "..." # a configured provider +cat list.txt | prinia --each "..." # one call per line, in parallel (-j N) prinia -t NAME "..." # a saved instruction (docs/usage.md#templates) prinia --cmd "..." # one shell command; `eval "$(prinia shell zsh)"` binds it to ctrl-g prinia -x "..." # let the model run commands to answer (agent + --run) @@ -64,6 +65,8 @@ prinia -c "..." # include earlier turns from this directory prinia --no-cache "..." # ask again even if the call is in your history prinia --no-record "..." # don't save this call +prinia init # pick a local model for this machine and write the config +prinia trust # allow this repo's .priniarc to turn on run/write/agent prinia history # browse everything you asked (fzf when available) prinia history search kestrel # find turns by words in prompt, input or answer prinia history ask "what did I ask about TLS?" # a fast model answers from your history diff --git a/src/agent.rs b/src/agent.rs index 9183808..b6feb54 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -279,7 +279,7 @@ fn approve(cmd: &str) -> bool { fn run_command(root: &Path, a: &Value, yes: bool) -> Result { let cmd = arg(a, "command")?; - if !yes && !read_only(&cmd) && !approve(&cmd) { + if !yes && !read_only(cmd) && !approve(cmd) { return Ok( "[not run: the user did not approve this command, or there is no terminal to ask on]" .into(), diff --git a/src/config.rs b/src/config.rs index 37fb349..c3e3691 100644 --- a/src/config.rs +++ b/src/config.rs @@ -212,14 +212,16 @@ impl Config { } }; for (k, v) in t { - if !global && k != "providers" && !PROJECT.contains(&k.as_str()) { - if KEYS.iter().any(|(n, _)| *n == k) { - eprintln!( - "[prinia] {}: `{k}` is device-level; set it in your global config", - p.display() - ); - continue; - } + if !global + && k != "providers" + && !PROJECT.contains(&k.as_str()) + && KEYS.iter().any(|(n, _)| *n == k) + { + eprintln!( + "[prinia] {}: `{k}` is device-level; set it in your global config", + p.display() + ); + continue; } // a repo may always tighten (`run = false`); loosening needs trust if !trusted && RISKY.contains(&k.as_str()) && v != Value::Boolean(false) { From 9696ae2c56d9cb3e265577f858669d33697b9937 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:09:38 +0200 Subject: [PATCH 14/31] feat: private mode; providers marked private = true are the only ones allowed --- docs/configuration.md | 24 ++++++++++++++++++++++++ src/config.rs | 6 ++++++ src/init.rs | 2 +- src/provider.rs | 7 +++++++ tests/cli.rs | 25 +++++++++++++++++++++++++ 5 files changed, 63 insertions(+), 1 deletion(-) diff --git a/docs/configuration.md b/docs/configuration.md index b0e2563..e0eef61 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -22,6 +22,30 @@ A `.priniarc` holds behaviour only: `record`, `cache`, `cache_ttl`, `context`, ` Settings that let the model act on your machine or change what it is told (`run`, `write`, `agent`, `prompt_pipe`, `prompt_interactive`) are ignored in a project file until you read it and run `prinia trust`. Turning `run`, `write` or `agent` off needs no trust. Trust is tied to the file's exact contents, so any later change, such as from a `git pull`, needs trusting again. Your own global config is always trusted. +### Private mode + +A provider can be marked `private = true` in your global config: a local model, or a hosted one you use under your own agreement (a company API key with the right terms). Then `private = true` as a setting, in a `.priniarc` or your global config, makes prinia refuse every provider that is not marked, before anything is sent. Built-in `anthropic` and `openai` are not private unless you define `[providers.anthropic]` with `private = true`. + +```toml +# ~/.config/prinia/config.toml +[providers.local] +type = "openai" +base_url = "http://localhost:11434/v1" +private = true + +[providers.corp] # a company key covered by an NDA +type = "anthropic" +api_key_env = "CORP_ANTHROPIC_KEY" +private = true +``` + +```toml +# .priniarc in a confidential repository +private = true # only local / `private` providers, whatever your shell exports +``` + +`prinia init` marks the local model private. Only a project file or your own config can switch it on, and it only ever restricts. The check covers every call, including `history ask` and agent mode. + A `.priniarc` is how a project gets its own behaviour: a repository that should never be recorded says `record = false`, one that must never run commands says `run = false`. ## Providers diff --git a/src/config.rs b/src/config.rs index c3e3691..cf93396 100644 --- a/src/config.rs +++ b/src/config.rs @@ -37,6 +37,7 @@ pub const KEYS: &[(&str, Ty)] = &[ ("write", Ty::Bool), ("run", Ty::Bool), ("max_input", Ty::Num), + ("private", Ty::Bool), ("agent_steps", Ty::Num), ("check_retries", Ty::Num), ("keychain", Ty::Bool), @@ -64,6 +65,7 @@ const PROJECT: &[&str] = &[ "deep_over", "check_retries", "max_input", + "private", "agent", "agent_steps", "run", @@ -318,6 +320,10 @@ impl Config { .map(str::to_owned) } + pub fn provider_bool(&self, name: &str, field: &str) -> Option { + self.providers.get(name)?.get(field)?.as_bool() + } + pub fn provider_names(&self) -> Vec<&String> { self.providers.keys().collect() } diff --git a/src/init.rs b/src/init.rs index bf1076e..249d3f7 100644 --- a/src/init.rs +++ b/src/init.rs @@ -112,7 +112,7 @@ pub fn run() -> Result<()> { pull(d, 20)?; } let mut cfg = format!( - "provider = \"local\"\nmax_input = 48000 # longer input is processed in parts\n\n[providers.local]\ntype = \"openai\"\nbase_url = \"{OLLAMA}/v1\"\nmodel = \"{model}\"\nfast_model = \"{model}\"\n" + "provider = \"local\"\nmax_input = 48000 # longer input is processed in parts\n\n[providers.local]\ntype = \"openai\"\nprivate = true\nbase_url = \"{OLLAMA}/v1\"\nmodel = \"{model}\"\nfast_model = \"{model}\"\n" ); if let Some(d) = deep { cfg.push_str(&format!("deep_model = \"{d}\"\n")); diff --git a/src/provider.rs b/src/provider.rs index 4139327..8cda06f 100644 --- a/src/provider.rs +++ b/src/provider.rs @@ -149,6 +149,13 @@ impl Provider { if api_key.is_none() && official { bail!("provider `{name}` needs an API key in ${key_env}"); } + // `private = true` (a directory, or your global config) allows only providers you marked + // `private = true`: a local model, or a hosted one covered by your own agreement. + if cfg.bool("private") == Some(true) && cfg.provider_bool(&name, "private") != Some(true) { + bail!( + "private mode is on, but provider `{name}` is not marked private; use one with `private = true` under [providers.] in your global config (-p NAME), or turn `private` off" + ); + } Ok(Provider { name, kind, diff --git a/tests/cli.rs b/tests/cli.rs index d3f9f3b..350487e 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -326,6 +326,31 @@ fn each_runs_one_call_per_line_and_reports_failures() { ); } +#[test] +fn private_mode_allows_only_providers_marked_private() { + let mock = Mock::start("ok", 200); + let env = Env::new("private", &mock); + let cfg = env.dir.join("cfg/config.toml"); + let mut text = std::fs::read_to_string(&cfg).unwrap(); + text.push_str(&format!( + "\n[providers.corp]\ntype = \"openai\"\nbase_url = \"http://127.0.0.1:{}/v1\"\nmodel = \"m\"\nprivate = true\n", + mock.port + )); + std::fs::write(&cfg, text).unwrap(); + // a project file switches it on; the user's own env cannot undo it + std::fs::write(env.dir.join("work/.priniarc"), "private = true\n").unwrap(); + for p in ["local", "anthropic"] { + let (_, err, code) = env.run(&["-p", p, "q"], "", &[("PRINIA_PRIVATE", "0")]); + assert!( + code != 0 && err.contains("not marked private"), + "{p}: {err}" + ); + } + assert_eq!(mock.hits(), 0, "nothing was sent"); + let (out, err, code) = env.run(&["-p", "corp", "q"], "", &[]); + assert_eq!((out.as_str(), code), ("ok\n", 0), "{err}"); +} + #[test] fn piped_output_loses_its_code_fence() { let mock = Mock::start("```json\n{\"a\":1}\n```", 200); From e05badf0f605130979cacf6e918fdcb9786a6312 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:12:17 +0200 Subject: [PATCH 15/31] feat: provider tags; a project's tag setting picks the provider that has it --- docs/configuration.md | 20 +++++++++++++------- src/config.rs | 22 ++++++++++++++++++++-- src/init.rs | 2 +- src/provider.rs | 35 ++++++++++++++++++++++++++--------- tests/cli.rs | 27 ++++++++++++++++++++++++++- 5 files changed, 86 insertions(+), 20 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index e0eef61..3cbc65c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -22,29 +22,35 @@ A `.priniarc` holds behaviour only: `record`, `cache`, `cache_ttl`, `context`, ` Settings that let the model act on your machine or change what it is told (`run`, `write`, `agent`, `prompt_pipe`, `prompt_interactive`) are ignored in a project file until you read it and run `prinia trust`. Turning `run`, `write` or `agent` off needs no trust. Trust is tied to the file's exact contents, so any later change, such as from a `git pull`, needs trusting again. Your own global config is always trusted. -### Private mode +### Tags and private mode -A provider can be marked `private = true` in your global config: a local model, or a hosted one you use under your own agreement (a company API key with the right terms). Then `private = true` as a setting, in a `.priniarc` or your global config, makes prinia refuse every provider that is not marked, before anything is sent. Built-in `anthropic` and `openai` are not private unless you define `[providers.anthropic]` with `private = true`. +Providers can carry tags, and a project asks for a tag instead of naming a provider. The device decides which provider that means, so the same `.priniarc` works on every machine. ```toml # ~/.config/prinia/config.toml +provider = "local" + [providers.local] type = "openai" base_url = "http://localhost:11434/v1" -private = true +tags = ["private"] [providers.corp] # a company key covered by an NDA type = "anthropic" api_key_env = "CORP_ANTHROPIC_KEY" -private = true +tags = ["private", "work"] ``` ```toml -# .priniarc in a confidential repository -private = true # only local / `private` providers, whatever your shell exports +# .priniarc +tag = "work" # use a provider tagged "work" (your default if it has the tag, else the first by name) ``` -`prinia init` marks the local model private. Only a project file or your own config can switch it on, and it only ever restricts. The check covers every call, including `history ask` and agent mode. +- `tag = "NAME"` (project or global setting) makes prinia use a provider with that tag. If none has it, the call fails; there is no fallback to another provider. `-p NAME` must name a provider with the tag, or it is refused before anything is sent. +- `private` is a tag with shorthand: `private = true` on a provider means `tags = ["private"]`, and `private = true` as a setting requires that tag. It combines with `tag`, so a project can need both `work` and `private`. +- Built-in `anthropic` and `openai` have no tags unless you define `[providers.anthropic]` with them. +- Tags mean what you decide. prinia cannot check that a provider is covered by an agreement; marking it `private` is your statement that it is. +- The check covers every call, including `history ask` and agent mode. `prinia init` tags the local model `private`. A `.priniarc` is how a project gets its own behaviour: a repository that should never be recorded says `record = false`, one that must never run commands says `run = false`. diff --git a/src/config.rs b/src/config.rs index cf93396..0d2e10a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -38,6 +38,7 @@ pub const KEYS: &[(&str, Ty)] = &[ ("run", Ty::Bool), ("max_input", Ty::Num), ("private", Ty::Bool), + ("tag", Ty::Str), ("agent_steps", Ty::Num), ("check_retries", Ty::Num), ("keychain", Ty::Bool), @@ -66,6 +67,7 @@ const PROJECT: &[&str] = &[ "check_retries", "max_input", "private", + "tag", "agent", "agent_steps", "run", @@ -320,8 +322,24 @@ impl Config { .map(str::to_owned) } - pub fn provider_bool(&self, name: &str, field: &str) -> Option { - self.providers.get(name)?.get(field)?.as_bool() + /// `tags = [...]` on the provider; `private = true` counts as the tag `private`. + pub fn provider_has_tag(&self, name: &str, tag: &str) -> bool { + let Some(p) = self.providers.get(name) else { + return false; + }; + (tag == "private" && p.get("private").and_then(|v| v.as_bool()) == Some(true)) + || p.get("tags") + .and_then(|v| v.as_array()) + .is_some_and(|a| a.iter().any(|t| t.as_str() == Some(tag))) + } + + /// Tags a provider must have: the `tag` setting, plus `private` when private mode is on. + pub fn required_tags(&self) -> Vec { + let mut t: Vec = self.str("tag").into_iter().collect(); + if self.bool("private") == Some(true) && !t.iter().any(|x| x == "private") { + t.push("private".into()); + } + t } pub fn provider_names(&self) -> Vec<&String> { diff --git a/src/init.rs b/src/init.rs index 249d3f7..f6015d1 100644 --- a/src/init.rs +++ b/src/init.rs @@ -112,7 +112,7 @@ pub fn run() -> Result<()> { pull(d, 20)?; } let mut cfg = format!( - "provider = \"local\"\nmax_input = 48000 # longer input is processed in parts\n\n[providers.local]\ntype = \"openai\"\nprivate = true\nbase_url = \"{OLLAMA}/v1\"\nmodel = \"{model}\"\nfast_model = \"{model}\"\n" + "provider = \"local\"\nmax_input = 48000 # longer input is processed in parts\n\n[providers.local]\ntype = \"openai\"\ntags = [\"private\"]\nbase_url = \"{OLLAMA}/v1\"\nmodel = \"{model}\"\nfast_model = \"{model}\"\n" ); if let Some(d) = deep { cfg.push_str(&format!("deep_model = \"{d}\"\n")); diff --git a/src/provider.rs b/src/provider.rs index 8cda06f..6daa3ee 100644 --- a/src/provider.rs +++ b/src/provider.rs @@ -104,11 +104,29 @@ impl Provider { /// `--provider`, then the `provider` setting, then whichever built-in has its API key set. pub fn resolve(cfg: &Config, flag: Option<&str>) -> Result { let has = |v: &str| std::env::var(v).is_ok_and(|k| !k.is_empty()); - let name = match flag.map(str::to_owned).or_else(|| cfg.str("provider")) { - Some(n) => n, - None if has("ANTHROPIC_API_KEY") => "anthropic".into(), - None if has("OPENAI_API_KEY") => "openai".into(), - None => bail!( + let need = cfg.required_tags(); + let tagged = |n: &str| need.iter().all(|t| cfg.provider_has_tag(n, t)); + let default = cfg.str("provider"); + let name = match (flag, default) { + (Some(n), _) => n.to_owned(), + (None, Some(n)) if tagged(&n) => n, + // a project asked for a tag: the first provider (by name) that has it + _ if !need.is_empty() => cfg + .provider_names() + .into_iter() + .find(|n| tagged(n)) + .cloned() + .ok_or_else(|| { + anyhow!( + "no provider has the tag(s) {}; add `tags = [\"{}\"]` under a [providers.] in your global config", + need.join(", "), + need[0] + ) + })?, + (None, Some(n)) => n, + (None, None) if has("ANTHROPIC_API_KEY") => "anthropic".into(), + (None, None) if has("OPENAI_API_KEY") => "openai".into(), + (None, None) => bail!( "no provider configured. Set ANTHROPIC_API_KEY or OPENAI_API_KEY, or add one to the config, e.g. a local model:\n\n provider = \"local\"\n [providers.local]\n type = \"openai\"\n base_url = \"http://localhost:11434/v1\"\n model = \"llama3.2\"" ), }; @@ -149,11 +167,10 @@ impl Provider { if api_key.is_none() && official { bail!("provider `{name}` needs an API key in ${key_env}"); } - // `private = true` (a directory, or your global config) allows only providers you marked - // `private = true`: a local model, or a hosted one covered by your own agreement. - if cfg.bool("private") == Some(true) && cfg.provider_bool(&name, "private") != Some(true) { + if !tagged(&name) { bail!( - "private mode is on, but provider `{name}` is not marked private; use one with `private = true` under [providers.] in your global config (-p NAME), or turn `private` off" + "provider `{name}` lacks the required tag(s) {}; pick one that has them (-p NAME) or change the `tag` / `private` setting", + need.join(", ") ); } Ok(Provider { diff --git a/tests/cli.rs b/tests/cli.rs index 350487e..e00b9cb 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -342,7 +342,7 @@ fn private_mode_allows_only_providers_marked_private() { for p in ["local", "anthropic"] { let (_, err, code) = env.run(&["-p", p, "q"], "", &[("PRINIA_PRIVATE", "0")]); assert!( - code != 0 && err.contains("not marked private"), + code != 0 && err.contains("lacks the required tag"), "{p}: {err}" ); } @@ -351,6 +351,31 @@ fn private_mode_allows_only_providers_marked_private() { assert_eq!((out.as_str(), code), ("ok\n", 0), "{err}"); } +#[test] +fn a_project_tag_picks_the_provider_that_has_it() { + let mock = Mock::start("tagged", 200); + let env = Env::new("tags", &mock); + let cfg = env.dir.join("cfg/config.toml"); + let mut text = std::fs::read_to_string(&cfg).unwrap(); + text.push_str(&format!( + "\n[providers.work]\ntype = \"openai\"\nbase_url = \"http://127.0.0.1:{}/v1\"\nmodel = \"m\"\ntags = [\"work\", \"eu\"]\n", + mock.port + )); + std::fs::write(&cfg, text).unwrap(); + std::fs::write(env.dir.join("work/.priniarc"), "tag = \"work\"\n").unwrap(); + // no -p and no `provider` setting: the tag chooses + let (out, err, code) = env.run(&["q"], "", &[]); + assert_eq!((out.as_str(), code), ("tagged\n", 0), "{err}"); + let (_, err, code) = env.run(&["-p", "local", "q"], "", &[]); + assert!(code != 0 && err.contains("lacks the required tag"), "{err}"); + std::fs::write(env.dir.join("work/.priniarc"), "tag = \"nobody\"\n").unwrap(); + let (_, err, code) = env.run(&["q"], "", &[]); + assert!( + code != 0 && err.contains("no provider has the tag"), + "{err}" + ); +} + #[test] fn piped_output_loses_its_code_fence() { let mock = Mock::start("```json\n{\"a\":1}\n```", 200); From df7d590c614ca9c0f052a4fa4f2a80cfbf493140 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:15:50 +0200 Subject: [PATCH 16/31] feat: tiered context (verbatim, older questions, opt-in summaries) and prinia context --- docs/usage.md | 8 +++ src/config.rs | 6 ++ src/context.rs | 181 +++++++++++++++++++++++++++++++++++++++++++------ src/main.rs | 51 +++++++++++++- src/store.rs | 28 ++++++++ tests/cli.rs | 99 ++++++++++++++++++++++++++- 6 files changed, 346 insertions(+), 27 deletions(-) diff --git a/docs/usage.md b/docs/usage.md index 6a860eb..d9be343 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -57,6 +57,14 @@ prinia -c "and how do I ignore it in Rust?" The context comes from your own history, not from a provider's session, so it works with any provider and survives a switch of model. Only turns from the current directory are used, oldest first, and long turns are cut. Set `context = 5` (a number of turns) to include it on every call and `--no-context` to leave it out once. `context_chars` (default 16000) caps its size; the oldest turns are dropped first. Calls made with `--no-record` are not in the history, so they are never part of a context. +Older turns are not simply dropped. The context has three tiers by age: + +1. **Recent turns, word for word**: the newest `context` turns. +2. **Older questions, one line each**: the next `context_older` turns (default 30; `0` turns it off), cut to 160 characters, so the model knows what you were working on. +3. **Summaries** (opt-in, `context_summary = true`): older turns are grouped into blocks of about 25 history entries, and each finished block is summarized once by the fast tier of the *same provider as the call*, so `private` and `tag` rules hold. Only the newest `context_blocks` blocks (default 4) are included. A summary is stored encrypted next to the history and is derived from it: any delete (`history rm`, size or age limits) drops all stored summaries, and they are rebuilt from what is left. Summaries are lossy; the model can be wrong about details it never saw in full. + +`prinia context` prints exactly what `-c` would send for this directory, so nothing about it is hidden. `prinia context --summarize` builds and stores the summaries now (tier 3) instead of at the first `-c` call that needs them. Starting a call with `-c` is how you use it: `prinia -c "continue the API retry work from earlier"`. + A call with context is cached separately from the same question without it. ## Long input diff --git a/src/config.rs b/src/config.rs index 0d2e10a..de2634e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -26,6 +26,9 @@ pub const KEYS: &[(&str, Ty)] = &[ ("cache_ttl", Ty::Str), ("context", Ty::Num), ("context_chars", Ty::Num), + ("context_older", Ty::Num), + ("context_summary", Ty::Bool), + ("context_blocks", Ty::Num), ("max_size", Ty::Str), ("max_age", Ty::Str), ("fast_under", Ty::Num), @@ -58,6 +61,9 @@ const PROJECT: &[&str] = &[ "cache_ttl", "context", "context_chars", + "context_older", + "context_summary", + "context_blocks", "max_tokens", "effort", "fast_effort", diff --git a/src/context.rs b/src/context.rs index 6437f82..3b7d47a 100644 --- a/src/context.rs +++ b/src/context.rs @@ -1,8 +1,33 @@ -use crate::store::{Filter, Store}; +//! Earlier turns from this directory's history, sent as context. Three tiers by age: +//! the newest turns word for word, then one line per older question, then (opt-in) model-written +//! summaries of still older blocks of turns. Summaries are derived from the history, cached by the +//! exact turns they cover, and dropped whenever anything is deleted. +use crate::provider::{Provider, Request}; +use crate::store::{Filter, Store, Turn}; use anyhow::Result; const USER_CAP: usize = 2_000; const REPLY_CAP: usize = 4_000; +/// Turns are grouped into blocks by `id / BLOCK`; a block is summarized once, when no new turn can +/// land in it any more. +const BLOCK: i64 = 25; +const LIST_LIMIT: usize = 1_000; + +pub struct Params<'a> { + pub dir: &'a str, + pub verbatim: usize, + pub budget: usize, + /// How many turns beyond the verbatim ones are listed as one-line questions. + pub older: usize, + /// Summarize older blocks with this provider and model (the call's own, so privacy rules hold). + pub summary: Option>, +} + +pub struct Summary<'a> { + pub provider: &'a Provider, + pub model: &'a str, + pub blocks: usize, +} fn cut(s: &str, max: usize) -> String { if s.chars().count() <= max { @@ -12,36 +37,148 @@ fn cut(s: &str, max: usize) -> String { format!("{head}\n[...cut]") } -/// The newest `turns` turns from this directory as (user, assistant) messages, oldest first, -/// kept within `budget` characters (the oldest turns are dropped first). -pub fn build( - store: &Store, - dir: &str, - turns: usize, - budget: usize, -) -> Result> { +fn user_text(t: &Turn) -> String { + let c = &t.content; + match (c.instruction.is_empty(), c.payload.is_empty()) { + (false, false) => format!("{}\n\n{}", c.instruction, c.payload), + (false, true) => c.instruction.clone(), + _ => c.payload.clone(), + } +} + +fn question(t: &Turn) -> String { + let first = if t.content.instruction.is_empty() { + &t.content.payload + } else { + &t.content.instruction + }; + let line = first.lines().find(|l| !l.trim().is_empty()).unwrap_or(""); + let short: String = line.trim().chars().take(160).collect(); + format!("- {short}") +} + +fn note(title: &str, body: &str) -> (String, String) { + (format!("{title}\n{body}"), "Understood.".to_string()) +} + +/// Turns summarized per block are cut so a block fits any model. +fn block_text(turns: &[&Turn]) -> String { + turns + .iter() + .map(|t| { + format!( + "Q: {}\nA: {}", + cut(&user_text(t), 300), + cut(t.content.response.trim(), 300) + ) + }) + .collect::>() + .join("\n\n") +} + +fn summarize(store: &Store, s: &Summary, block: &[&Turn]) -> Result { + let ids = block + .iter() + .map(|t| t.id.to_string()) + .collect::>() + .join(","); + let key = store.cache_key(&["summary-v1", &s.provider.identity(), s.model, &ids]); + if let Some(hit) = store.summary_get(&key)? { + return Ok(hit); + } + let text = block_text(block); + let req = Request { + model: s.model, + system: "Summarize this stretch of a user's terminal question-and-answer history in under 120 words. Keep names, commands, file paths, decisions and open questions. No preamble.", + user: &text, + history: &[], + tools: &[], + follow: &[], + effort: None, + max_tokens: Some(400), + }; + let reply = s.provider.complete(&req, &mut |_| {})?; + let out = reply.text.trim().to_string(); + if !out.is_empty() && reply.stop != "max_tokens" && reply.stop != "length" { + store.summary_put(&key, &out)?; + } + Ok(out) +} + +/// Messages to send before the new one, oldest first. +pub fn build(store: &Store, p: &Params) -> Result> { let filter = Filter { - dir: Some(dir.to_string()), + dir: Some(p.dir.to_string()), ..Filter::default() }; - let mut out = Vec::new(); + let limit = if p.summary.is_some() { + LIST_LIMIT + } else { + p.verbatim + p.older + }; + let turns = store.list(&filter, limit)?; // newest first + + // tier 1: newest turns word for word, within the character budget let mut used = 0; - for t in store.list(&filter, turns)? { - let c = t.content; - let user = match (c.instruction.is_empty(), c.payload.is_empty()) { - (false, false) => format!("{}\n\n{}", c.instruction, c.payload), - (false, true) => c.instruction, - _ => c.payload, - }; - let pair = (cut(&user, USER_CAP), cut(c.response.trim_end(), REPLY_CAP)); + let mut recent = Vec::new(); + for t in turns.iter().take(p.verbatim) { + let pair = ( + cut(&user_text(t), USER_CAP), + cut(t.content.response.trim_end(), REPLY_CAP), + ); let size = pair.0.chars().count() + pair.1.chars().count(); - if used + size > budget { + if used + size > p.budget { break; } used += size; - out.push(pair); + recent.push(pair); + } + recent.reverse(); + + // tier 2: one line per older question + let rest = &turns[recent.len()..]; + let asked = &rest[..p.older.min(rest.len())]; + let beyond = &rest[asked.len()..]; + + let mut out = Vec::new(); + // tier 3: summaries of complete older blocks, newest blocks first, at most `blocks` of them + if let Some(s) = &p.summary { + let edge = rest.first().map_or(i64::MAX, |_| { + turns[..recent.len() + asked.len()] + .iter() + .map(|t| t.id) + .min() + .unwrap_or(i64::MAX) + }) / BLOCK; + let mut by_block: std::collections::BTreeMap> = Default::default(); + for t in beyond.iter().filter(|t| t.id / BLOCK < edge) { + by_block.entry(t.id / BLOCK).or_default().push(t); + } + let mut lines = Vec::new(); + for (_, mut block) in by_block.into_iter().rev().take(s.blocks) { + block.reverse(); // oldest first + match summarize(store, s, &block) { + Ok(t) if !t.is_empty() => lines.push(format!("- {}", t.replace('\n', " "))), + Ok(_) => {} + Err(e) => eprintln!("[prinia] could not summarize older turns: {e}"), + } + } + if !lines.is_empty() { + lines.reverse(); // oldest first + out.push(note( + "Summaries of older exchanges in this directory (oldest first), for background:", + &lines.join("\n"), + )); + } + } + if !asked.is_empty() { + let lines: Vec = asked.iter().rev().map(question).collect(); + out.push(note( + "Earlier questions asked in this directory (oldest first), for background:", + &lines.join("\n"), + )); } - out.reverse(); + out.extend(recent); Ok(out) } diff --git a/src/main.rs b/src/main.rs index ea93bb7..a3e440f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -148,6 +148,12 @@ enum Cmd { #[arg(long)] format: Option, }, + /// Show the context `-c` would send for this directory; `--summarize` builds the summaries first + Context { + /// Build and store summaries of older turns now (uses the fast tier of your provider) + #[arg(long)] + summarize: bool, + }, /// Find a local model server, pick a model for this machine and write the config Init, /// Print the shell integration to load: `eval "$(prinia shell zsh)"` @@ -230,6 +236,34 @@ fn run() -> Result<()> { let keychain = cfg.bool("keychain").unwrap_or(false); match &cli.command { Some(Cmd::Config) => show_config(&cfg), + Some(Cmd::Context { summarize }) => { + let provider = Provider::resolve(&cfg, cli.provider.as_deref())?; + let model = provider.model(&cfg, Tier::Fast)?; + let store = Store::open(keychain)?; + let dir = store::dir_hash(&std::env::current_dir()?); + let on = *summarize || cfg.bool("context_summary") == Some(true); + let msgs = context::build( + &store, + &context::Params { + dir: &dir, + verbatim: (cfg.num("context").unwrap_or(0) as usize).max(5), + budget: cfg.num("context_chars").unwrap_or(16_000) as usize, + older: cfg.num("context_older").unwrap_or(30) as usize, + summary: on.then(|| context::Summary { + provider: &provider, + model: &model, + blocks: cfg.num("context_blocks").unwrap_or(4) as usize, + }), + }, + )?; + if msgs.is_empty() { + println!("no history in this directory yet"); + } + for (user, assistant) in msgs { + println!("[you]\n{user}\n[model]\n{assistant}\n"); + } + Ok(()) + } Some(Cmd::Init) => init::run(), Some(Cmd::Shell { .. }) => { print!("{}", include_str!("../scripts/prinia.zsh")); @@ -534,6 +568,9 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { }; let effort = provider.effort(cfg, tier); let max_tokens = cfg.num("max_tokens"); + let summary_model = provider + .model(cfg, Tier::Fast) + .unwrap_or_else(|_| model.clone()); let user = combine(&instruction, &payload); let record = if cli.record { @@ -568,9 +605,17 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { let history = match &store { Some(s) if ctx_turns > 0 => context::build( s, - &dir, - ctx_turns, - cfg.num("context_chars").unwrap_or(16_000) as usize, + &context::Params { + dir: &dir, + verbatim: ctx_turns, + budget: cfg.num("context_chars").unwrap_or(16_000) as usize, + older: cfg.num("context_older").unwrap_or(30) as usize, + summary: (cfg.bool("context_summary") == Some(true)).then(|| context::Summary { + provider: &provider, + model: &summary_model, + blocks: cfg.num("context_blocks").unwrap_or(4) as usize, + }), + }, )?, _ => Vec::new(), }; diff --git a/src/store.rs b/src/store.rs index 41929de..4f685e8 100644 --- a/src/store.rs +++ b/src/store.rs @@ -191,6 +191,10 @@ impl Store { output_tokens INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (day, dir) ); + CREATE TABLE IF NOT EXISTS summaries ( + key TEXT PRIMARY KEY, + content BLOB NOT NULL + ); PRAGMA user_version = {SCHEMA_VERSION};" ))?; @@ -389,8 +393,32 @@ impl Store { Ok(()) } + /// A stored summary of a block of turns (see `context`), keyed by the exact turns it covers. + pub fn summary_get(&self, key: &str) -> Result> { + let blob: Option> = self + .conn + .query_row( + "SELECT content FROM summaries WHERE key = ?1", + params![key], + |r| r.get(0), + ) + .optional()?; + blob.map(|b| Ok(String::from_utf8_lossy(&unseal(&self.data_key, &b)?).into_owned())) + .transpose() + } + + pub fn summary_put(&self, key: &str, text: &str) -> Result<()> { + self.conn.execute( + "INSERT OR REPLACE INTO summaries (key, content) VALUES (?1, ?2)", + params![key, seal(&self.data_key, text.as_bytes())?], + )?; + Ok(()) + } + pub fn delete(&self, ids: &[i64]) -> Result { let tx = self.conn.unchecked_transaction()?; + // a summary may contain what was just deleted; they are rebuilt on demand + tx.execute("DELETE FROM summaries", [])?; let mut n = 0; for id in ids { n += tx.execute("DELETE FROM turns WHERE id = ?1", params![id])?; diff --git a/tests/cli.rs b/tests/cli.rs index e00b9cb..937d0b4 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -376,6 +376,100 @@ fn a_project_tag_picks_the_provider_that_has_it() { ); } +#[test] +fn context_has_verbatim_turns_then_one_line_questions() { + let mock = Mock::start("an answer", 200); + let env = Env::new("ctx-tiers", &mock); + for q in [ + "first question", + "second question", + "third question", + "fourth question", + ] { + env.run(&["-p", "local", q], "", &[]); + } + let (_, err, code) = env.run( + &["-p", "local", "-c", "fifth"], + "", + &[("PRINIA_CONTEXT", "1"), ("PRINIA_CONTEXT_OLDER", "2")], + ); + assert_eq!(code, 0, "{err}"); + let (_, body) = mock.last(); + let msgs = body["messages"].as_array().unwrap(); + let text: Vec = msgs + .iter() + .map(|m| m["content"].as_str().unwrap_or("").to_string()) + .collect(); + // system, questions note, "Understood.", the newest turn, its answer, the new question + assert!(text[1].contains("Earlier questions"), "{text:?}"); + assert!( + text[1].contains("- second question") && text[1].contains("- third question"), + "{}", + text[1] + ); + assert!( + !text[1].contains("first question") && !text[1].contains("fourth"), + "{}", + text[1] + ); + assert_eq!(text[3], "fourth question"); + assert_eq!(text.last().unwrap(), "fifth"); +} + +#[test] +fn context_command_shows_what_c_would_send() { + let mock = Mock::start("an answer", 200); + let env = Env::new("ctx-show", &mock); + let (out, _, _) = env.run(&["-p", "local", "context"], "", &[]); + assert!(out.contains("no history"), "{out}"); + for q in ["alpha question", "beta question"] { + env.run(&["-p", "local", q], "", &[]); + } + let (out, err, code) = env.run(&["-p", "local", "context"], "", &[]); + assert_eq!(code, 0, "{err}"); + assert!( + out.contains("alpha question") + && out.contains("beta question") + && out.contains("an answer"), + "{out}" + ); +} + +#[test] +fn old_blocks_are_summarized_once_and_rebuilt_after_a_delete() { + let mock = Mock::start("an answer", 200); + let env = Env::new("ctx-summary", &mock); + for n in 0..60 { + env.run(&["-p", "local", &format!("question {n}")], "", &[]); + } + let on = [ + ("PRINIA_CONTEXT", "1"), + ("PRINIA_CONTEXT_OLDER", "2"), + ("PRINIA_CONTEXT_SUMMARY", "1"), + ]; + let before = mock.hits(); + let (_, err, code) = env.run(&["-p", "local", "-c", "next"], "", &on); + assert_eq!(code, 0, "{err}"); + // two complete older blocks were summarized, then the real call + assert_eq!(mock.hits(), before + 3); + let (_, body) = mock.last(); + let first = body["messages"][1]["content"].as_str().unwrap(); + assert!(first.starts_with("Summaries of older exchanges"), "{first}"); + let before = mock.hits(); + env.run(&["-p", "local", "-c", "again"], "", &on); + assert_eq!( + mock.hits(), + before + 1, + "summaries come from the stored copy" + ); + + // deleting any turn drops the stored summaries; they are rebuilt from what is left + env.run(&["history", "rm", "3", "--yes"], "", &[]); + let before = mock.hits(); + env.run(&["-p", "local", "-c", "after delete"], "", &on); + assert_eq!(mock.hits(), before + 3); +} + #[test] fn piped_output_loses_its_code_fence() { let mock = Mock::start("```json\n{\"a\":1}\n```", 200); @@ -492,9 +586,10 @@ fn context_comes_from_history_of_this_directory() { "", &[("PRINIA_CONTEXT", "1")], ); - assert_eq!(mock.last().1["messages"].as_array().unwrap().len(), 4); + // system + older-questions note (2) + the one verbatim turn (2) + the new question + assert_eq!(mock.last().1["messages"].as_array().unwrap().len(), 6); env.run(&args("", "fifth question"), "", &[("PRINIA_CONTEXT", "1")]); - assert_eq!(mock.last().1["messages"].as_array().unwrap().len(), 4); + assert_eq!(mock.last().1["messages"].as_array().unwrap().len(), 6); env.run( &args("--no-context", "sixth"), "", From b9f621def3b86d328dbc671744208825af271719 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:18:08 +0200 Subject: [PATCH 17/31] feat: history ask finds matching turns across the whole history (time words, keywords, ranking) --- docs/configuration.md | 5 +- docs/history.md | 10 +- src/config.rs | 1 + src/curate.rs | 268 ++++++++++++++++++++++++++++++++++++++++-- 4 files changed, 271 insertions(+), 13 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 3cbc65c..4c154e1 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -103,8 +103,9 @@ API keys are read from the environment and are never written to the history or t | `max_age` | none | Also drop turns older than this (`90d`, `52w`) | | `fast_under` | `0` (off) | Calls with fewer characters than this use the fast tier unless a tier or model is given | | `deep_over` | none | Calls with more characters than this use the deep tier unless a tier or model is given | -| `history_scan` | `200` | Newest turns that `history ask` and `history agent` read | -| `excerpt_prompt` / `excerpt_reply` | `200` / `400` | Characters of each prompt and answer sent for `history ask` and `history agent` | +| `history_scan` | `200` | Newest turns that `history agent` reads | +| `ask_turns` | `15` | Best-matching turns `history ask` sends to the model | +| `excerpt_prompt` / `excerpt_reply` | `200` / `400` (`history ask`: `400` / `1000`) | Characters of each prompt and answer sent for `history ask` and `history agent` | | `check_retries` | `2` | Extra attempts when an answer fails `--json` or `--check` | | `keychain` | `false` | Keep the history key in the OS credential store instead of a file ([History](history.md#where-the-key-lives)) | | `prompt_pipe`, `prompt_interactive` | see below | The system prompts | diff --git a/docs/history.md b/docs/history.md index f6b20cf..498d351 100644 --- a/docs/history.md +++ b/docs/history.md @@ -65,7 +65,15 @@ prinia history search kestrel nest # turns containing every word, any case, prinia history ask "what did I ask about TLS last month?" ``` -`search` is plain text matching and makes no network call. `ask` sends excerpts of your most recent turns to the fast model and prints its answer, so those excerpts leave your machine like any other prompt. The excerpt size and how many turns are scanned are settings (`excerpt_prompt`, `excerpt_reply`, `history_scan`). Neither command is recorded in the history. Filters (`--since`, `--older`, `--here`) narrow what is searched. +`search` is plain text matching and makes no network call. + +`ask` finds the turns that match your question across the whole history, then a fast model answers from them: + +1. **Time:** words like `yesterday`, `last week`, `last month`, `this week` or `3 days ago` narrow the range (generously: "last week" means the past two weeks). `--since`, `--older` and `--here` replace the guess. If nothing falls in the guessed range, it searches everything. +2. **Keywords:** the remaining meaningful words are matched against prompt, input and answer; a match in the prompt counts most. With no keyword hit, the newest turns are used. +3. **Answer:** the best `ask_turns` turns (default 15) go to the model with longer excerpts (`excerpt_prompt` 400, `excerpt_reply` 1000 characters), and it answers citing `#id`. If they do not contain the answer it should say so. stderr lists the turns used; open one with `prinia history show ID`. + +Those excerpts leave your machine like any other prompt, so `ask` uses your configured provider and the `private` / `tag` rules apply. It is not recorded. Matching is plain words, not meaning: ask with the words you would have used at the time. ## Deleting diff --git a/src/config.rs b/src/config.rs index de2634e..7add0e1 100644 --- a/src/config.rs +++ b/src/config.rs @@ -34,6 +34,7 @@ pub const KEYS: &[(&str, Ty)] = &[ ("fast_under", Ty::Num), ("deep_over", Ty::Num), ("history_scan", Ty::Num), + ("ask_turns", Ty::Num), ("excerpt_prompt", Ty::Num), ("excerpt_reply", Ty::Num), ("agent", Ty::Bool), diff --git a/src/curate.rs b/src/curate.rs index e0c1d0e..ae258ce 100644 --- a/src/curate.rs +++ b/src/curate.rs @@ -7,14 +7,12 @@ use crate::store::{Store, Turn}; use anyhow::{Result, bail}; use std::io::Write; -const ASK_SYSTEM: &str = "You answer questions about a user's command-line AI history. Each entry is `id | date | place | Q: prompt | A: answer`. Answer briefly and cite entry ids as #id. If the history does not contain the answer, say so."; +const ASK_SYSTEM: &str = "You answer questions about a user's command-line AI history. The entries are the best matches for the question, not the whole history. Each is `id | date | place | Q: prompt | A: answer`. Answer briefly and cite entry ids as #id. If the entries do not contain the answer, say so instead of guessing."; const AGENT_SYSTEM: &str = "You help clean up a user's command-line AI history. Each entry is `id | date | place | Q: prompt | A: answer`. Follow the user's instruction and reply with ONLY a JSON array of the integer ids of the entries to delete, for example [3,8]. Use only ids that are listed. If nothing matches, reply []."; -fn listing(turns: &[Turn], cfg: &Config) -> String { - let q = cfg.num("excerpt_prompt").unwrap_or(200) as usize; - let a = cfg.num("excerpt_reply").unwrap_or(400) as usize; +fn listing<'a>(turns: impl IntoIterator, q: usize, a: usize) -> String { turns - .iter() + .into_iter() .map(|t| { let c = &t.content; let place = c.repo.as_deref().unwrap_or(&c.cwd); @@ -65,14 +63,205 @@ fn scan(store: &Store, f: &FilterArgs, cfg: &Config) -> Result> { Ok(turns) } -/// Answer a question about the history, using the fast tier. +const FILLER: &[&str] = &[ + "the", + "and", + "was", + "were", + "what", + "which", + "who", + "how", + "why", + "when", + "where", + "did", + "does", + "for", + "with", + "about", + "that", + "this", + "these", + "those", + "have", + "had", + "has", + "from", + "into", + "you", + "your", + "our", + "can", + "could", + "would", + "should", + "last", + "ago", + "week", + "weeks", + "day", + "days", + "month", + "months", + "year", + "yesterday", + "today", + "recently", + "tell", + "show", + "find", + "ask", + "asked", + "remember", + "again", + "there", + "then", + "than", +]; + +/// Time words in a question as (newer than, older than) seconds. Generous on purpose: "last week" +/// covers the past two weeks, and the keywords do the narrowing. +fn parse_when(q: &str) -> (Option, Option) { + const D: i64 = 86_400; + let q = q.to_lowercase(); + let w: Vec<&str> = q + .split(|c: char| !c.is_alphanumeric()) + .filter(|s| !s.is_empty()) + .collect(); + for pair in w.windows(3) { + if let (Ok(n), Some(unit), "ago") = ( + pair[0].parse::(), + ["hour", "day", "week", "month"] + .iter() + .position(|u| pair[1].trim_end_matches('s') == *u), + pair[2], + ) { + let u = [3600, D, 7 * D, 30 * D][unit]; + return ( + Some((n + 1) * u), + Some((n - 1).max(0) * u).filter(|o| *o > 0), + ); + } + } + let has = |p: &str| q.contains(p); + if has("last week") || has("past week") { + (Some(14 * D), None) + } else if has("last month") || has("past month") { + (Some(62 * D), None) + } else if has("yesterday") { + (Some(2 * D), None) + } else if has("today") { + (Some(D), None) + } else if has("this week") || has("recently") { + (Some(7 * D), None) + } else { + (None, None) + } +} + +fn keywords(q: &str) -> Vec { + let mut out: Vec = Vec::new(); + for w in q + .to_lowercase() + .split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '-')) + { + if w.chars().count() >= 3 && !FILLER.contains(&w) && !out.iter().any(|o| o == w) { + out.push(w.to_string()); + } + } + out +} + +/// The `k` turns that match the keywords best (prompt counts most, then input, then answer), +/// best first; newest first among equals. With no keyword hit, simply the newest `k`. +fn rank<'a>(turns: &'a [Turn], kws: &[String], k: usize) -> Vec<&'a Turn> { + let score = |t: &Turn| -> usize { + let c = &t.content; + let (i, p, r) = ( + c.instruction.to_lowercase(), + c.payload.to_lowercase(), + c.response.to_lowercase(), + ); + kws.iter() + .map(|w| { + 3 * i.contains(w.as_str()) as usize + + 2 * p.contains(w.as_str()) as usize + + r.contains(w.as_str()) as usize + }) + .sum() + }; + let mut scored: Vec<(usize, &Turn)> = turns.iter().map(|t| (score(t), t)).collect(); + if scored.iter().all(|(s, _)| *s == 0) { + return turns.iter().take(k).collect(); + } + scored.retain(|(s, _)| *s > 0); + scored.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.id.cmp(&a.1.id))); + scored.into_iter().take(k).map(|(_, t)| t).collect() +} + +/// Answer a question about the history, using the fast tier: find the matching turns across the +/// whole history (time words and keywords from the question, or `--since` / `--older`), then let +/// the model answer from them. pub fn ask(store: &Store, cfg: &Config, f: &FilterArgs, question: &str) -> Result<()> { - let turns = scan(store, f, cfg)?; - let user = format!("{}\n\nQuestion: {question}", listing(&turns, cfg)); - let text = call(cfg, Tier::Fast, ASK_SYSTEM, &user, true)?; + let mut filter = f.filter()?; + let (since, older) = parse_when(question); + let mut guessed = false; + if filter.since.is_none() && filter.older.is_none() && (since.is_some() || older.is_some()) { + filter.since = since; + filter.older = older; + guessed = true; + } + let mut turns = store.list(&filter, 20_000)?; + if turns.is_empty() && guessed { + eprintln!("[prinia] nothing in that time range; searching all of the history"); + filter.since = None; + filter.older = None; + turns = store.list(&filter, 20_000)?; + } + if turns.is_empty() { + bail!("the history has no matching turns"); + } + let kws = keywords(question); + let k = cfg.num("ask_turns").unwrap_or(15) as usize; + let best = rank(&turns, &kws, k); + eprintln!( + "[prinia] {} of {} turns{}{}", + best.len(), + turns.len(), + if kws.is_empty() { + String::new() + } else { + format!(" for: {}", kws.join(", ")) + }, + if guessed { + " (time range taken from the question)" + } else { + "" + } + ); + let listing = listing( + best.iter().copied(), + cfg.num("excerpt_prompt").unwrap_or(400) as usize, + cfg.num("excerpt_reply").unwrap_or(1000) as usize, + ); + let text = call( + cfg, + Tier::Fast, + ASK_SYSTEM, + &format!("{listing}\n\nQuestion: {question}"), + true, + )?; if !text.ends_with('\n') { println!(); } + eprintln!( + "[prinia] turns used: {} (prinia history show ID)", + best.iter() + .map(|t| format!("#{}", t.id)) + .collect::>() + .join(" ") + ); Ok(()) } @@ -101,7 +290,14 @@ pub fn agent( yes: bool, ) -> Result<()> { let turns = scan(store, f, cfg)?; - let user = format!("{}\n\nInstruction: {instruction}", listing(&turns, cfg)); + let user = format!( + "{}\n\nInstruction: {instruction}", + listing( + &turns, + cfg.num("excerpt_prompt").unwrap_or(200) as usize, + cfg.num("excerpt_reply").unwrap_or(400) as usize + ) + ); let reply = call(cfg, Tier::Regular, AGENT_SYSTEM, &user, false)?; let ids = picked(&reply, &turns); if ids.is_empty() { @@ -150,4 +346,56 @@ mod tests { assert!(picked("x] y [3", &offered).is_empty()); // ] before [ must not panic assert!(picked("[\"x\"]", &offered).is_empty()); } + + fn turn_with(id: i64, instruction: &str, response: &str) -> Turn { + let mut t = Turn { + id, + when: String::new(), + provider: String::new(), + model: String::new(), + mode: String::new(), + input_tokens: 0, + output_tokens: 0, + content: Default::default(), + }; + t.content.instruction = instruction.into(); + t.content.response = response.into(); + t + } + + #[test] + fn time_words_and_keywords_come_from_the_question() { + const D: i64 = 86_400; + assert_eq!( + parse_when("what was the API issue last week"), + (Some(14 * D), None) + ); + assert_eq!(parse_when("what did I ask yesterday"), (Some(2 * D), None)); + assert_eq!( + parse_when("the retry bug 3 days ago"), + (Some(4 * D), Some(2 * D)) + ); + assert_eq!(parse_when("how do pipes work"), (None, None)); + assert_eq!( + keywords("what was the issue with the API request last week"), + ["issue", "api", "request"] + ); + } + + #[test] + fn rank_prefers_prompt_matches_and_falls_back_to_newest() { + let turns = [ + turn_with(3, "unrelated", "the api answered"), + turn_with(2, "why does the api request fail", "timeout"), + turn_with(1, "other", "other"), + ]; + let kws = keywords("api request"); + let ids: Vec = rank(&turns, &kws, 2).iter().map(|t| t.id).collect(); + assert_eq!(ids, [2, 3]); + let none: Vec = rank(&turns, &keywords("zebra"), 2) + .iter() + .map(|t| t.id) + .collect(); + assert_eq!(none, [3, 2], "no hit: the newest turns"); + } } From 8681b3e3f789c123e43dd5eff21301c0b2c07d12 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:21:23 +0200 Subject: [PATCH 18/31] feat: -c pulls in older turns that match the new question; fix first-use race on the history key --- docs/usage.md | 9 +-- src/config.rs | 2 + src/context.rs | 38 ++++++++++- src/curate.rs | 140 ++------------------------------------ src/main.rs | 17 ++++- src/retrieve.rs | 176 ++++++++++++++++++++++++++++++++++++++++++++++++ src/store.rs | 46 ++++++++----- tests/cli.rs | 58 ++++++++++++++++ 8 files changed, 326 insertions(+), 160 deletions(-) create mode 100644 src/retrieve.rs diff --git a/docs/usage.md b/docs/usage.md index d9be343..6139222 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -57,13 +57,14 @@ prinia -c "and how do I ignore it in Rust?" The context comes from your own history, not from a provider's session, so it works with any provider and survives a switch of model. Only turns from the current directory are used, oldest first, and long turns are cut. Set `context = 5` (a number of turns) to include it on every call and `--no-context` to leave it out once. `context_chars` (default 16000) caps its size; the oldest turns are dropped first. Calls made with `--no-record` are not in the history, so they are never part of a context. -Older turns are not simply dropped. The context has three tiers by age: +Older turns are not simply dropped. The context has four tiers: 1. **Recent turns, word for word**: the newest `context` turns. -2. **Older questions, one line each**: the next `context_older` turns (default 30; `0` turns it off), cut to 160 characters, so the model knows what you were working on. -3. **Summaries** (opt-in, `context_summary = true`): older turns are grouped into blocks of about 25 history entries, and each finished block is summarized once by the fast tier of the *same provider as the call*, so `private` and `tag` rules hold. Only the newest `context_blocks` blocks (default 4) are included. A summary is stored encrypted next to the history and is derived from it: any delete (`history rm`, size or age limits) drops all stored summaries, and they are rebuilt from what is left. Summaries are lossy; the model can be wrong about details it never saw in full. +2. **Relevant older turns, in full**: up to `context_relevant` turns (default 3; `0` turns it off) from further back that match the words of your new question (prompt matches count most; a word that is in most of your turns is ignored). They use up to half of `context_chars`. This is what lets `prinia -c "why did the payments API time out again?"` find the exchange from three weeks ago. +3. **Older questions, one line each**: the next `context_older` turns (default 30; `0` turns it off), cut to 160 characters, so the model knows what you were working on. +4. **Summaries** (opt-in, `context_summary = true`): older turns are grouped into blocks of about 25 history entries, and each finished block is summarized once by the fast tier of the *same provider as the call*, so `private` and `tag` rules hold. Only the newest `context_blocks` blocks (default 4) are included. A summary is stored encrypted next to the history and is derived from it: any delete (`history rm`, size or age limits) drops all stored summaries, and they are rebuilt from what is left. Summaries are lossy; the model can be wrong about details it never saw in full. -`prinia context` prints exactly what `-c` would send for this directory, so nothing about it is hidden. `prinia context --summarize` builds and stores the summaries now (tier 3) instead of at the first `-c` call that needs them. Starting a call with `-c` is how you use it: `prinia -c "continue the API retry work from earlier"`. +`prinia context [QUESTION]` prints exactly what `-c` would send for this directory (give it the question to see which older turns it would pull in), so nothing about it is hidden. `prinia context --summarize` builds and stores the summaries now (tier 3) instead of at the first `-c` call that needs them. Starting a call with `-c` is how you use it: `prinia -c "continue the API retry work from earlier"`. A call with context is cached separately from the same question without it. diff --git a/src/config.rs b/src/config.rs index 7add0e1..1f341c6 100644 --- a/src/config.rs +++ b/src/config.rs @@ -27,6 +27,7 @@ pub const KEYS: &[(&str, Ty)] = &[ ("context", Ty::Num), ("context_chars", Ty::Num), ("context_older", Ty::Num), + ("context_relevant", Ty::Num), ("context_summary", Ty::Bool), ("context_blocks", Ty::Num), ("max_size", Ty::Str), @@ -63,6 +64,7 @@ const PROJECT: &[&str] = &[ "context", "context_chars", "context_older", + "context_relevant", "context_summary", "context_blocks", "max_tokens", diff --git a/src/context.rs b/src/context.rs index 3b7d47a..ec39c2a 100644 --- a/src/context.rs +++ b/src/context.rs @@ -3,6 +3,7 @@ //! summaries of still older blocks of turns. Summaries are derived from the history, cached by the //! exact turns they cover, and dropped whenever anything is deleted. use crate::provider::{Provider, Request}; +use crate::retrieve::{keywords, rank}; use crate::store::{Filter, Store, Turn}; use anyhow::Result; @@ -19,6 +20,9 @@ pub struct Params<'a> { pub budget: usize, /// How many turns beyond the verbatim ones are listed as one-line questions. pub older: usize, + /// The new question; older turns that match its words are included in full. + pub query: &'a str, + pub relevant: usize, /// Summarize older blocks with this provider and model (the call's own, so privacy rules hold). pub summary: Option>, } @@ -111,7 +115,7 @@ pub fn build(store: &Store, p: &Params) -> Result> { dir: Some(p.dir.to_string()), ..Filter::default() }; - let limit = if p.summary.is_some() { + let limit = if p.summary.is_some() || (p.relevant > 0 && !p.query.is_empty()) { LIST_LIMIT } else { p.verbatim + p.older @@ -140,6 +144,28 @@ pub fn build(store: &Store, p: &Params) -> Result> { let asked = &rest[..p.older.min(rest.len())]; let beyond = &rest[asked.len()..]; + // retrieval: older turns about what is being asked now, in full, within half the budget + let mut related = Vec::new(); + let mut related_ids = Vec::new(); + if p.relevant > 0 && !p.query.is_empty() { + let kws = keywords(&p.query.chars().take(500).collect::()); + let mut used = 0; + for t in rank(rest, &kws, p.relevant, 2) { + let pair = ( + cut(&user_text(t), USER_CAP), + cut(t.content.response.trim_end(), REPLY_CAP), + ); + let size = pair.0.chars().count() + pair.1.chars().count(); + if used + size > p.budget / 2 { + continue; + } + used += size; + related_ids.push(t.id); + related.push(pair); + } + related.reverse(); // oldest first, like the rest of the context + } + let mut out = Vec::new(); // tier 3: summaries of complete older blocks, newest blocks first, at most `blocks` of them if let Some(s) = &p.summary { @@ -171,13 +197,19 @@ pub fn build(store: &Store, p: &Params) -> Result> { )); } } - if !asked.is_empty() { - let lines: Vec = asked.iter().rev().map(question).collect(); + let lines: Vec = asked + .iter() + .rev() + .filter(|t| !related_ids.contains(&t.id)) + .map(question) + .collect(); + if !lines.is_empty() { out.push(note( "Earlier questions asked in this directory (oldest first), for background:", &lines.join("\n"), )); } + out.extend(related); out.extend(recent); Ok(out) } diff --git a/src/curate.rs b/src/curate.rs index ae258ce..6b7d8cf 100644 --- a/src/curate.rs +++ b/src/curate.rs @@ -3,6 +3,7 @@ use crate::config::Config; use crate::history::{FilterArgs, confirm, oneline}; use crate::provider::{Provider, Request, Tier}; +use crate::retrieve::{keywords, rank}; use crate::store::{Store, Turn}; use anyhow::{Result, bail}; use std::io::Write; @@ -63,63 +64,6 @@ fn scan(store: &Store, f: &FilterArgs, cfg: &Config) -> Result> { Ok(turns) } -const FILLER: &[&str] = &[ - "the", - "and", - "was", - "were", - "what", - "which", - "who", - "how", - "why", - "when", - "where", - "did", - "does", - "for", - "with", - "about", - "that", - "this", - "these", - "those", - "have", - "had", - "has", - "from", - "into", - "you", - "your", - "our", - "can", - "could", - "would", - "should", - "last", - "ago", - "week", - "weeks", - "day", - "days", - "month", - "months", - "year", - "yesterday", - "today", - "recently", - "tell", - "show", - "find", - "ask", - "asked", - "remember", - "again", - "there", - "then", - "than", -]; - /// Time words in a question as (newer than, older than) seconds. Generous on purpose: "last week" /// covers the past two weeks, and the keywords do the narrowing. fn parse_when(q: &str) -> (Option, Option) { @@ -160,46 +104,6 @@ fn parse_when(q: &str) -> (Option, Option) { } } -fn keywords(q: &str) -> Vec { - let mut out: Vec = Vec::new(); - for w in q - .to_lowercase() - .split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '-')) - { - if w.chars().count() >= 3 && !FILLER.contains(&w) && !out.iter().any(|o| o == w) { - out.push(w.to_string()); - } - } - out -} - -/// The `k` turns that match the keywords best (prompt counts most, then input, then answer), -/// best first; newest first among equals. With no keyword hit, simply the newest `k`. -fn rank<'a>(turns: &'a [Turn], kws: &[String], k: usize) -> Vec<&'a Turn> { - let score = |t: &Turn| -> usize { - let c = &t.content; - let (i, p, r) = ( - c.instruction.to_lowercase(), - c.payload.to_lowercase(), - c.response.to_lowercase(), - ); - kws.iter() - .map(|w| { - 3 * i.contains(w.as_str()) as usize - + 2 * p.contains(w.as_str()) as usize - + r.contains(w.as_str()) as usize - }) - .sum() - }; - let mut scored: Vec<(usize, &Turn)> = turns.iter().map(|t| (score(t), t)).collect(); - if scored.iter().all(|(s, _)| *s == 0) { - return turns.iter().take(k).collect(); - } - scored.retain(|(s, _)| *s > 0); - scored.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.id.cmp(&a.1.id))); - scored.into_iter().take(k).map(|(_, t)| t).collect() -} - /// Answer a question about the history, using the fast tier: find the matching turns across the /// whole history (time words and keywords from the question, or `--since` / `--older`), then let /// the model answer from them. @@ -224,7 +128,10 @@ pub fn ask(store: &Store, cfg: &Config, f: &FilterArgs, question: &str) -> Resul } let kws = keywords(question); let k = cfg.num("ask_turns").unwrap_or(15) as usize; - let best = rank(&turns, &kws, k); + let mut best = rank(&turns, &kws, k, 1); + if best.is_empty() { + best = turns.iter().take(k).collect(); // no keyword hit: the newest turns + } eprintln!( "[prinia] {} of {} turns{}{}", best.len(), @@ -347,22 +254,6 @@ mod tests { assert!(picked("[\"x\"]", &offered).is_empty()); } - fn turn_with(id: i64, instruction: &str, response: &str) -> Turn { - let mut t = Turn { - id, - when: String::new(), - provider: String::new(), - model: String::new(), - mode: String::new(), - input_tokens: 0, - output_tokens: 0, - content: Default::default(), - }; - t.content.instruction = instruction.into(); - t.content.response = response.into(); - t - } - #[test] fn time_words_and_keywords_come_from_the_question() { const D: i64 = 86_400; @@ -376,26 +267,5 @@ mod tests { (Some(4 * D), Some(2 * D)) ); assert_eq!(parse_when("how do pipes work"), (None, None)); - assert_eq!( - keywords("what was the issue with the API request last week"), - ["issue", "api", "request"] - ); - } - - #[test] - fn rank_prefers_prompt_matches_and_falls_back_to_newest() { - let turns = [ - turn_with(3, "unrelated", "the api answered"), - turn_with(2, "why does the api request fail", "timeout"), - turn_with(1, "other", "other"), - ]; - let kws = keywords("api request"); - let ids: Vec = rank(&turns, &kws, 2).iter().map(|t| t.id).collect(); - assert_eq!(ids, [2, 3]); - let none: Vec = rank(&turns, &keywords("zebra"), 2) - .iter() - .map(|t| t.id) - .collect(); - assert_eq!(none, [3, 2], "no hit: the newest turns"); } } diff --git a/src/main.rs b/src/main.rs index a3e440f..3f8ea40 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,6 +18,7 @@ mod init; mod key; mod keychain; mod provider; +mod retrieve; mod stats; mod store; @@ -150,6 +151,8 @@ enum Cmd { }, /// Show the context `-c` would send for this directory; `--summarize` builds the summaries first Context { + /// A question: shows which older turns it would pull in + question: Option, /// Build and store summaries of older turns now (uses the fast tier of your provider) #[arg(long)] summarize: bool, @@ -236,7 +239,10 @@ fn run() -> Result<()> { let keychain = cfg.bool("keychain").unwrap_or(false); match &cli.command { Some(Cmd::Config) => show_config(&cfg), - Some(Cmd::Context { summarize }) => { + Some(Cmd::Context { + question, + summarize, + }) => { let provider = Provider::resolve(&cfg, cli.provider.as_deref())?; let model = provider.model(&cfg, Tier::Fast)?; let store = Store::open(keychain)?; @@ -246,9 +252,14 @@ fn run() -> Result<()> { &store, &context::Params { dir: &dir, - verbatim: (cfg.num("context").unwrap_or(0) as usize).max(5), + verbatim: match cfg.num("context").unwrap_or(0) { + 0 => 5, + n => n as usize, + }, budget: cfg.num("context_chars").unwrap_or(16_000) as usize, older: cfg.num("context_older").unwrap_or(30) as usize, + query: question.as_deref().unwrap_or(""), + relevant: cfg.num("context_relevant").unwrap_or(3) as usize, summary: on.then(|| context::Summary { provider: &provider, model: &model, @@ -610,6 +621,8 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { verbatim: ctx_turns, budget: cfg.num("context_chars").unwrap_or(16_000) as usize, older: cfg.num("context_older").unwrap_or(30) as usize, + query: &user, + relevant: cfg.num("context_relevant").unwrap_or(3) as usize, summary: (cfg.bool("context_summary") == Some(true)).then(|| context::Summary { provider: &provider, model: &summary_model, diff --git a/src/retrieve.rs b/src/retrieve.rs new file mode 100644 index 0000000..66dca27 --- /dev/null +++ b/src/retrieve.rs @@ -0,0 +1,176 @@ +//! Finding the turns of a history that match some words: used by `history ask` and by `-c`. +use crate::store::Turn; + +const FILLER: &[&str] = &[ + "the", + "and", + "was", + "were", + "what", + "which", + "who", + "how", + "why", + "when", + "where", + "did", + "does", + "for", + "with", + "about", + "that", + "this", + "these", + "those", + "have", + "had", + "has", + "from", + "into", + "you", + "your", + "our", + "can", + "could", + "would", + "should", + "last", + "ago", + "week", + "weeks", + "day", + "days", + "month", + "months", + "year", + "yesterday", + "today", + "recently", + "tell", + "show", + "find", + "ask", + "asked", + "remember", + "again", + "there", + "then", + "than", +]; + +/// The meaningful lowercase words of a question, without repeats. +pub fn keywords(q: &str) -> Vec { + let mut out: Vec = Vec::new(); + for w in q + .to_lowercase() + .split(|c: char| !(c.is_alphanumeric() || c == '_' || c == '-')) + { + if w.chars().count() >= 3 && !FILLER.contains(&w) && !out.iter().any(|o| o == w) { + out.push(w.to_string()); + } + } + out +} + +/// Up to `k` turns scoring at least `min` for the keywords (a prompt match counts 3, input 2, +/// answer 1, per keyword), best first, newest first among equals. A word that appears in more than +/// half of a larger set says nothing about any one turn and is ignored. +pub fn rank<'a>(turns: &'a [Turn], kws: &[String], k: usize, min: usize) -> Vec<&'a Turn> { + let low: Vec<[String; 3]> = turns + .iter() + .map(|t| { + let c = &t.content; + [ + c.instruction.to_lowercase(), + c.payload.to_lowercase(), + c.response.to_lowercase(), + ] + }) + .collect(); + let common = |w: &String| { + turns.len() >= 4 + && low + .iter() + .filter(|l| l.iter().any(|x| x.contains(w.as_str()))) + .count() + * 2 + > turns.len() + }; + let kws: Vec<&String> = kws.iter().filter(|w| !common(w)).collect(); + let mut scored: Vec<(usize, &Turn)> = turns + .iter() + .zip(&low) + .map(|(t, [i, p, r])| { + let s = kws + .iter() + .map(|w| { + 3 * i.contains(w.as_str()) as usize + + 2 * p.contains(w.as_str()) as usize + + r.contains(w.as_str()) as usize + }) + .sum(); + (s, t) + }) + .collect(); + scored.retain(|(s, _)| *s >= min.max(1)); + scored.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.id.cmp(&a.1.id))); + scored.into_iter().take(k).map(|(_, t)| t).collect() +} + +#[cfg(test)] +pub mod tests { + use super::*; + + pub fn turn_with(id: i64, instruction: &str, response: &str) -> Turn { + let mut t = Turn { + id, + when: String::new(), + provider: String::new(), + model: String::new(), + mode: String::new(), + input_tokens: 0, + output_tokens: 0, + content: Default::default(), + }; + t.content.instruction = instruction.into(); + t.content.response = response.into(); + t + } + + #[test] + fn keywords_drop_filler_and_repeats() { + assert_eq!( + keywords("what was the issue with the API request last week, API?"), + ["issue", "api", "request"] + ); + } + + #[test] + fn rank_prefers_prompt_matches_and_honours_the_minimum() { + let turns = [ + turn_with(3, "unrelated", "the api answered"), + turn_with(2, "why does the api request fail", "timeout"), + turn_with(1, "other", "other"), + ]; + let kws = keywords("api request"); + let ids = |min| -> Vec { rank(&turns, &kws, 2, min).iter().map(|t| t.id).collect() }; + assert_eq!(ids(1), [2, 3]); + assert_eq!(ids(2), [2], "a lone answer match is too weak"); + assert!(rank(&turns, &keywords("zebra"), 2, 1).is_empty()); + } + + #[test] + fn words_in_most_turns_are_ignored() { + let turns = [ + turn_with(4, "question about pipes", "a"), + turn_with(3, "question about git", "b"), + turn_with(2, "question about make", "c"), + turn_with(1, "question about the payments api", "d"), + ]; + let ids: Vec = rank(&turns, &keywords("question payments"), 3, 2) + .iter() + .map(|t| t.id) + .collect(); + assert_eq!(ids, [1], "`question` is in every turn, `payments` in one"); + } +} diff --git a/src/store.rs b/src/store.rs index 4f685e8..1b4875b 100644 --- a/src/store.rs +++ b/src/store.rs @@ -160,6 +160,8 @@ impl Store { pub fn open_at(path: &Path, keychain: bool) -> Result { let conn = Connection::open(path).with_context(|| format!("cannot open {}", path.display()))?; + // parallel prinia processes (`--each`, shell prompts) share this file + conn.busy_timeout(std::time::Duration::from_secs(5))?; let version: i64 = conn.query_row("PRAGMA user_version", [], |r| r.get(0))?; if version > SCHEMA_VERSION { bail!("the history was written by a newer version of prinia (schema {version})"); @@ -198,21 +200,21 @@ impl Store { PRAGMA user_version = {SCHEMA_VERSION};" ))?; - let wrapped: Option> = conn - .query_row("SELECT value FROM meta WHERE key = 'data_key'", [], |r| { - r.get(0) - }) - .optional()?; - let data_key = match (wrapped, key::load(keychain)?) { - (Some(w), Some(master)) => unseal(&master, &w) - .context("the key does not match this history")? - .try_into() - .map_err(|_| anyhow!("corrupt data key"))?, - (Some(_), None) => bail!( - "the history exists but its key is missing; restore it with `prinia key import`" - ), - (None, master) => { - let master = match master { + let read_wrapped = || -> Result>> { + Ok(conn + .query_row("SELECT value FROM meta WHERE key = 'data_key'", [], |r| { + r.get(0) + }) + .optional()?) + }; + let mut wrapped = read_wrapped()?; + if wrapped.is_none() { + // First use. Take the write lock before creating any key, so two processes starting + // at once cannot each make their own master key and lock each other out. + conn.execute_batch("BEGIN IMMEDIATE")?; + wrapped = read_wrapped()?; + if wrapped.is_none() { + let master = match key::load(keychain)? { Some(m) => m, None => { let m = key::random()?; @@ -225,8 +227,20 @@ impl Store { "INSERT INTO meta (key, value) VALUES ('data_key', ?1)", params![seal(&master, &dk)?], )?; - dk + conn.execute_batch("COMMIT")?; + return Ok(Store { conn, data_key: dk }); } + conn.execute_batch("COMMIT")?; + } + let data_key = match (wrapped, key::load(keychain)?) { + (Some(w), Some(master)) => unseal(&master, &w) + .context("the key does not match this history")? + .try_into() + .map_err(|_| anyhow!("corrupt data key"))?, + (Some(_), None) => bail!( + "the history exists but its key is missing; restore it with `prinia key import`" + ), + (None, _) => bail!("the history has no data key"), }; Ok(Store { conn, data_key }) } diff --git a/tests/cli.rs b/tests/cli.rs index 937d0b4..9262f4e 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -376,6 +376,64 @@ fn a_project_tag_picks_the_provider_that_has_it() { ); } +#[test] +fn context_pulls_in_older_turns_that_match_the_new_question() { + let mock = Mock::start("an answer", 200); + let env = Env::new("ctx-relevant", &mock); + for q in [ + "how do I rotate the payments api keys", + "what is a unix pipe", + "explain git rebase", + "make vs ninja", + "list open ports", + ] { + env.run(&["-p", "local", q], "", &[]); + } + let on = [("PRINIA_CONTEXT", "1"), ("PRINIA_CONTEXT_OLDER", "0")]; + let (_, err, code) = env.run(&["-p", "local", "-c", "payments api timeout"], "", &on); + assert_eq!(code, 0, "{err}"); + let (_, body) = mock.last(); + let all = body["messages"].to_string(); + assert!(all.contains("rotate the payments api keys"), "{all}"); + assert!( + all.contains("list open ports"), + "the newest turn is still sent verbatim" + ); + assert!( + !all.contains("unix pipe") && !all.contains("git rebase"), + "{all}" + ); + let (out, _, _) = env.run(&["context", "payments api timeout"], "", &on); + assert!( + out.contains("rotate the payments api keys") && !out.contains("unix pipe"), + "{out}" + ); + // `context_relevant = 0` switches it off + let off = [ + ("PRINIA_CONTEXT", "1"), + ("PRINIA_CONTEXT_OLDER", "0"), + ("PRINIA_CONTEXT_RELEVANT", "0"), + ]; + env.run(&["-p", "local", "-c", "payments api timeout 2"], "", &off); + assert!( + !mock.last().1["messages"] + .to_string() + .contains("rotate the payments") + ); +} + +#[test] +fn many_first_calls_at_once_share_one_key() { + let mock = Mock::start("answer", 200); + let env = Env::new("first-use-race", &mock); + let lines = (0..16).map(|n| format!("l{n}\n")).collect::(); + let (_, err, code) = env.run(&["-p", "local", "--each", "-j", "16", "q"], &lines, &[]); + assert_eq!(code, 0, "{err}"); + // every turn decrypts with the one key that exists + let (out, err, code) = env.run(&["history", "show", "16"], "", &[]); + assert!(code == 0 && out.contains("answer"), "{out} {err}"); +} + #[test] fn context_has_verbatim_turns_then_one_line_questions() { let mock = Mock::start("an answer", 200); From a9319f0db70854fea226aed7ca9e4440e6ba5713 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:25:44 +0200 Subject: [PATCH 19/31] fix: audit items - tighter read-only list, private turns stay with private providers, [DONE] ends a stream, safe file reads, shared shell spawn, fewer git spawns --- src/agent.rs | 78 ++++++++++++++++++++++++++++++++++--------------- src/check.rs | 13 ++------- src/context.rs | 5 +++- src/curate.rs | 7 ++++- src/init.rs | 5 +++- src/main.rs | 7 +++++ src/provider.rs | 13 ++++++++- src/sh.rs | 13 +++++++++ tests/cli.rs | 68 +++++++++++++++++++++++++++++++++++++----- 9 files changed, 163 insertions(+), 46 deletions(-) create mode 100644 src/sh.rs diff --git a/src/agent.rs b/src/agent.rs index b6feb54..dd08f99 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -113,9 +113,24 @@ fn arg<'a>(a: &'a Value, k: &str) -> Result<&'a str> { .ok_or_else(|| anyhow!("missing text argument `{k}`")) } +const MAX_FILE: u64 = 10_000_000; + +/// A regular text file of a sane size: a named pipe would block forever and a huge file would +/// be loaded whole before any cut. +fn text_of(path: &Path) -> Result { + let m = std::fs::metadata(path)?; + if !m.is_file() { + bail!("not a regular file"); + } + if m.len() > MAX_FILE { + bail!("the file is larger than 10 MB; read part of it with `search`"); + } + std::fs::read_to_string(path).map_err(|e| anyhow!("cannot read as text: {e}")) +} + fn read_file(root: &Path, a: &Value) -> Result { let path = resolve(root, arg(a, "path")?)?; - let text = std::fs::read_to_string(&path).map_err(|e| anyhow!("cannot read as text: {e}"))?; + let text = text_of(&path)?; let start = a["start"].as_u64().unwrap_or(1).max(1) as usize; let end = a["end"].as_u64().map(|e| e as usize).unwrap_or(usize::MAX); let out: Vec = text @@ -165,7 +180,8 @@ fn walk(dir: &Path, needle: &str, out: &mut Vec, root: &Path) { if name != "target" && name != "node_modules" { walk(&path, needle, out, root); } - } else if e.metadata().map(|m| m.len() < 1_000_000).unwrap_or(false) + } else if ft.is_file() + && e.metadata().map(|m| m.len() < 1_000_000).unwrap_or(false) && let Ok(text) = std::fs::read_to_string(&path) { let rel = path.strip_prefix(root).unwrap_or(&path).display(); @@ -186,7 +202,7 @@ fn search(root: &Path, a: &Value) -> Result { let needle = arg(a, "pattern")?.to_lowercase(); let mut out = Vec::new(); if start.is_file() { - let text = std::fs::read_to_string(&start)?; + let text = text_of(&start)?; for (i, l) in text.lines().enumerate() { if l.to_lowercase().contains(&needle) { out.push(format!( @@ -231,13 +247,12 @@ fn replace(root: &Path, a: &Value) -> Result { /// True for a pipeline of read-only commands. Anything with shell syntax beyond `|` (chaining, /// substitution, redirects, background) or a flag that can write or execute needs approval. fn read_only(cmd: &str) -> bool { + // No `git` (a repository's own config can make `git status` or `git diff` run a program), + // no `hostname`/`uniq`/`sort -o` style commands that write. const OK: &[&str] = &[ - "ls", "cat", "head", "tail", "wc", "date", "pwd", "echo", "grep", "rg", "sort", "uniq", - "du", "df", "which", "whoami", "uname", "file", "stat", "tree", "find", "git", "basename", - "dirname", "uptime", "hostname", - ]; - const GIT: &[&str] = &[ - "status", "log", "diff", "show", "branch", "ls-files", "remote", + "ls", "cat", "head", "tail", "wc", "date", "pwd", "echo", "grep", "rg", "sort", "du", "df", + "which", "whoami", "uname", "file", "stat", "tree", "find", "basename", "dirname", + "uptime", ]; if cmd.contains([';', '&', '`', '$', '(', ')', '<', '>', '\n', '\\']) { return false; @@ -247,17 +262,18 @@ fn read_only(cmd: &str) -> bool { let Some(&first) = w.first() else { return false; }; + // flags that write a file or run a program let bad_flag = w.iter().any(|a| { matches!( *a, - "-exec" | "-execdir" | "-ok" | "-delete" | "-o" | "--pre" + "-exec" | "-execdir" | "-ok" | "-okdir" | "-delete" | "-o" | "-fls" ) || a.starts_with("-fprint") || a.starts_with("--output") - || a.starts_with("--pre=") + || a.starts_with("--pre") + || a.starts_with("--compress-program") + || a.starts_with("--hostname-bin") }); - OK.contains(&first) - && !bad_flag - && (first != "git" || w.get(1).is_some_and(|s| GIT.contains(s))) + OK.contains(&first) && !bad_flag }) } @@ -285,15 +301,7 @@ fn run_command(root: &Path, a: &Value, yes: bool) -> Result { .into(), ); } - let mut c = if cfg!(windows) { - let mut c = Command::new("cmd"); - c.args(["/C", &format!("({cmd}) 2>&1")]); - c - } else { - let mut c = Command::new("sh"); - c.args(["-c", &format!("({cmd}) 2>&1")]); - c - }; + let mut c = crate::sh::command(&format!("({cmd}) 2>&1")); #[cfg(unix)] std::os::unix::process::CommandExt::process_group(&mut c, 0); let mut child = c @@ -435,7 +443,7 @@ mod tests { for ok in [ "ls -la", "find . -name '*.rs' | wc -l", - "git log --oneline | head", + "cat a | sort | head", "echo hi", ] { assert!(read_only(ok), "{ok}"); @@ -452,6 +460,13 @@ mod tests { "ls || id", "rg --pre ./x foo", "sort -o f f", + "git status", + "git remote set-url origin x", + "git branch -D main", + "uniq in out", + "sort --compress-program=sh f", + "rg --hostname-bin=sh x", + "find . -fls out", "ls &", ] { assert!(!read_only(no), "{no}"); @@ -475,4 +490,19 @@ mod tests { assert!(resolve(&root, "link").is_err()); let _ = std::fs::remove_file(&link); } + + #[cfg(unix)] + #[test] + fn a_named_pipe_is_not_read() { + let p = std::env::temp_dir().join(format!("prinia-fifo-{}", std::process::id())); + let _ = std::fs::remove_file(&p); + if Command::new("mkfifo") + .arg(&p) + .status() + .is_ok_and(|s| s.success()) + { + assert!(text_of(&p).is_err()); + let _ = std::fs::remove_file(&p); + } + } } diff --git a/src/check.rs b/src/check.rs index e8787ab..5f381db 100644 --- a/src/check.rs +++ b/src/check.rs @@ -1,6 +1,6 @@ use serde_json::Value; use std::io::Write; -use std::process::{Command, Stdio}; +use std::process::Stdio; /// Whether `text` satisfies `--json` (parses as one JSON value) and `--check` (the command /// reads it on stdin and exits 0). @@ -10,16 +10,7 @@ pub fn passes(text: &str, json: bool, cmd: Option<&str>) -> bool { } fn run(cmd: &str, text: &str) -> bool { - let mut c = if cfg!(windows) { - let mut c = Command::new("cmd"); - c.args(["/C", cmd]); - c - } else { - let mut c = Command::new("sh"); - c.args(["-c", cmd]); - c - }; - let Ok(mut child) = c + let Ok(mut child) = crate::sh::command(cmd) .stdin(Stdio::piped()) .stdout(Stdio::null()) .stderr(Stdio::null()) diff --git a/src/context.rs b/src/context.rs index ec39c2a..162d74c 100644 --- a/src/context.rs +++ b/src/context.rs @@ -23,6 +23,8 @@ pub struct Params<'a> { /// The new question; older turns that match its words are included in full. pub query: &'a str, pub relevant: usize, + /// Which turns this call may show to its provider (see `Provider::may_see`). + pub visible: &'a dyn Fn(&Turn) -> bool, /// Summarize older blocks with this provider and model (the call's own, so privacy rules hold). pub summary: Option>, } @@ -120,7 +122,8 @@ pub fn build(store: &Store, p: &Params) -> Result> { } else { p.verbatim + p.older }; - let turns = store.list(&filter, limit)?; // newest first + let mut turns = store.list(&filter, limit)?; // newest first + turns.retain(|t| (p.visible)(t)); // tier 1: newest turns word for word, within the character budget let mut used = 0; diff --git a/src/curate.rs b/src/curate.rs index 6b7d8cf..9014d38 100644 --- a/src/curate.rs +++ b/src/curate.rs @@ -54,10 +54,12 @@ fn call(cfg: &Config, tier: Tier, system: &str, user: &str, show: bool) -> Resul } fn scan(store: &Store, f: &FilterArgs, cfg: &Config) -> Result> { - let turns = store.list( + let provider = Provider::resolve(cfg, None)?; + let mut turns = store.list( &f.filter()?, cfg.num("history_scan").unwrap_or(200) as usize, )?; + turns.retain(|t| provider.may_see(cfg, &t.provider)); if turns.is_empty() { bail!("the history has no matching turns"); } @@ -116,12 +118,15 @@ pub fn ask(store: &Store, cfg: &Config, f: &FilterArgs, question: &str) -> Resul filter.older = older; guessed = true; } + let provider = Provider::resolve(cfg, None)?; let mut turns = store.list(&filter, 20_000)?; + turns.retain(|t| provider.may_see(cfg, &t.provider)); if turns.is_empty() && guessed { eprintln!("[prinia] nothing in that time range; searching all of the history"); filter.since = None; filter.older = None; turns = store.list(&filter, 20_000)?; + turns.retain(|t| provider.may_see(cfg, &t.provider)); } if turns.is_empty() { bail!("the history has no matching turns"); diff --git a/src/init.rs b/src/init.rs index f6015d1..35cc4fc 100644 --- a/src/init.rs +++ b/src/init.rs @@ -101,7 +101,10 @@ pub fn run() -> Result<()> { } return Ok(()); }; - let gb = memory_gb().unwrap_or(8); + let gb = memory_gb().unwrap_or_else(|| { + println!("Could not read this machine's memory size; assuming 8 GB (a small model)."); + 8 + }); let (model, size, deep) = recommend(gb); println!( "Ollama is running; this machine has about {gb} GB of memory. Recommended: {model}{}.", diff --git a/src/main.rs b/src/main.rs index 3f8ea40..2514cf6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -19,6 +19,7 @@ mod key; mod keychain; mod provider; mod retrieve; +mod sh; mod stats; mod store; @@ -260,6 +261,7 @@ fn run() -> Result<()> { older: cfg.num("context_older").unwrap_or(30) as usize, query: question.as_deref().unwrap_or(""), relevant: cfg.num("context_relevant").unwrap_or(3) as usize, + visible: &|t| provider.may_see(&cfg, &t.provider), summary: on.then(|| context::Summary { provider: &provider, model: &model, @@ -623,6 +625,7 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { older: cfg.num("context_older").unwrap_or(30) as usize, query: &user, relevant: cfg.num("context_relevant").unwrap_or(3) as usize, + visible: &|t| provider.may_see(cfg, &t.provider), summary: (cfg.bool("context_summary") == Some(true)).then(|| context::Summary { provider: &provider, model: &summary_model, @@ -817,6 +820,10 @@ fn strip_fence(s: &str) -> String { } fn git_info(cwd: &Path) -> (Option, Option) { + // no `.git` above: skip the two process spawns + if !cwd.ancestors().any(|d| d.join(".git").exists()) { + return (None, None); + } let run = |args: &[&str]| { Command::new("git") .arg("-C") diff --git a/src/provider.rs b/src/provider.rs index 6daa3ee..349dac8 100644 --- a/src/provider.rs +++ b/src/provider.rs @@ -181,6 +181,12 @@ impl Provider { }) } + /// Whether this provider may be shown a turn made with `made_with`: turns from a provider + /// tagged `private` only go to another provider tagged `private`. + pub fn may_see(&self, cfg: &Config, made_with: &str) -> bool { + cfg.provider_has_tag(&self.name, "private") || !cfg.provider_has_tag(made_with, "private") + } + /// The provider's own table wins over the top-level setting, then the built-in default. pub fn model(&self, cfg: &Config, tier: Tier) -> Result { let builtin = match (self.kind, tier) { @@ -283,11 +289,15 @@ impl Provider { model: req.model.to_string(), ..Default::default() }; + let mut done = false; for line in BufReader::new(resp.into_body().into_reader()).lines() { let line = line.context("the response stream broke off")?; let Some(data) = line.strip_prefix("data:").map(str::trim) else { continue; }; + if data == "[DONE]" { + done = true; + } if data.is_empty() || data == "[DONE]" { continue; } @@ -303,7 +313,8 @@ impl Provider { reply.text.push_str(&t); } } - if reply.stop.is_empty() { + // a finish reason or the closing `[DONE]` marks a complete answer; a dropped connection has neither + if reply.stop.is_empty() && !done { bail!("the response ended before the model finished (connection dropped?)"); } reply.calls = reply diff --git a/src/sh.rs b/src/sh.rs new file mode 100644 index 0000000..216b9bc --- /dev/null +++ b/src/sh.rs @@ -0,0 +1,13 @@ +use std::process::Command; + +/// A command that runs `cmd` through the platform shell. +pub fn command(cmd: &str) -> Command { + let (shell, flag) = if cfg!(windows) { + ("cmd", "/C") + } else { + ("sh", "-c") + }; + let mut c = Command::new(shell); + c.args([flag, cmd]); + c +} diff --git a/tests/cli.rs b/tests/cli.rs index 9262f4e..e1a0b4f 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -11,6 +11,10 @@ enum Step { Text(&'static str), /// text, ended by the output limit (OpenAI-style `length`) Cut(&'static str), + /// text with no finish reason, closed by `[DONE]` + NoFinish(&'static str), + /// text with no finish reason and no `[DONE]`: a dropped connection + Dropped(&'static str), /// tool name, arguments as JSON text Call(&'static str, &'static str), } @@ -94,7 +98,9 @@ impl Mock { ) } else { let shown = match &step { - Some(Step::Text(t)) | Some(Step::Cut(t)) => *t, + Some( + Step::Text(t) | Step::Cut(t) | Step::NoFinish(t) | Step::Dropped(t), + ) => *t, _ => text, }; let (a, b) = shown.split_at(shown.len() / 2); @@ -115,15 +121,19 @@ impl Mock { } else { format!( "data: {{\"model\":\"served-model\",\"choices\":[{{\"delta\":{{\"content\":{}}}}}]}}\n\n\ - data: {{\"model\":\"served-model\",\"choices\":[{{\"delta\":{{\"content\":{}}},\"finish_reason\":\"{}\"}}]}}\n\n\ - data: {{\"model\":\"served-model\",\"choices\":[],\"usage\":{{\"prompt_tokens\":5,\"completion_tokens\":3}}}}\n\n\ - data: [DONE]\n\n", + data: {{\"model\":\"served-model\",\"choices\":[{{\"delta\":{{\"content\":{}}},\"finish_reason\":{}}}]}}\n\n\ + data: {{\"model\":\"served-model\",\"choices\":[],\"usage\":{{\"prompt_tokens\":5,\"completion_tokens\":3}}}}\n\n{}", q(a), q(b), - if matches!(step, Some(Step::Cut(_))) { - "length" + match step { + Some(Step::Cut(_)) => "\"length\"", + Some(Step::NoFinish(_) | Step::Dropped(_)) => "null", + _ => "\"stop\"", + }, + if matches!(step, Some(Step::Dropped(_))) { + "" } else { - "stop" + "data: [DONE]\n\n" } ) }; @@ -422,6 +432,50 @@ fn context_pulls_in_older_turns_that_match_the_new_question() { ); } +#[test] +fn a_dropped_stream_is_an_error_but_done_without_a_finish_reason_is_complete() { + let mock = Mock::start_with("", 200, vec![Step::Dropped("half an ans")]); + let env = Env::new("dropped", &mock); + let (out, err, code) = env.run(&["-p", "local", "q"], "", &[]); + assert!( + code != 0 && out.is_empty() && err.contains("ended before"), + "{out:?} {err}" + ); + let (shown, _, _) = env.run(&["history", "show", "1"], "", &[]); + assert!( + !shown.contains("half an ans"), + "a cut-off answer must not be saved" + ); + + let mock = Mock::start_with("", 200, vec![Step::NoFinish("whole answer")]); + let env = Env::new("no-finish", &mock); + let (out, err, code) = env.run(&["-p", "local", "q"], "", &[]); + assert_eq!((out.as_str(), code), ("whole answer\n", 0), "{err}"); +} + +#[test] +fn turns_from_a_private_provider_are_not_sent_to_another_one() { + let mock = Mock::start("an answer", 200); + let env = Env::new("private-turns", &mock); + let cfg = env.dir.join("cfg/config.toml"); + let text = std::fs::read_to_string(&cfg).unwrap().replace( + "type = \"openai\"", + "type = \"openai\"\ntags = [\"private\"]", + ); + std::fs::write(&cfg, text).unwrap(); + env.run(&["-p", "local", "secret roadmap question"], "", &[]); + let ctx = [("PRINIA_CONTEXT", "5")]; + // a private provider sees it; the cloud one does not + env.run(&["-p", "local", "-c", "follow up"], "", &ctx); + assert!(mock.last().1.to_string().contains("secret roadmap")); + env.run(&["-p", "anthropic", "-c", "follow up"], "", &ctx); + assert!(!mock.last().1.to_string().contains("secret roadmap")); + // `history ask` goes to the default (cloud) provider: the private turn must not be in it + let (_, err, code) = env.run(&["history", "ask", "what was the roadmap"], "", &[]); + assert_eq!(code, 0, "{err}"); + assert!(!mock.last().1.to_string().contains("secret roadmap")); +} + #[test] fn many_first_calls_at_once_share_one_key() { let mock = Mock::start("answer", 200); From 63f810f755e199926a0509b87ed50998dcecfcc7 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:29:06 +0200 Subject: [PATCH 20/31] fix: children never re-split input, trust shows files and asks, key rotation is crash-safe; tests --- src/config.rs | 34 ++++++++------- src/main.rs | 38 +++++++++++----- src/store.rs | 117 ++++++++++++++++++++++++++++++++++++++++++-------- tests/cli.rs | 63 +++++++++++++++++++++++++++ 4 files changed, 210 insertions(+), 42 deletions(-) diff --git a/src/config.rs b/src/config.rs index 1f341c6..1b09b23 100644 --- a/src/config.rs +++ b/src/config.rs @@ -99,28 +99,32 @@ fn is_trusted(text: &str) -> bool { .is_some_and(|t| t.lines().any(|l| l.trim() == digest(text))) } -/// Trusts the exact current contents of every `.priniarc` above `cwd`; an edit revokes it. -pub fn trust(cwd: &Path) -> std::io::Result> { +/// The `.priniarc` files above `cwd` as (path, contents, already trusted), nearest first. +pub fn project_files(cwd: &Path) -> Vec<(PathBuf, String, bool)> { + cwd.ancestors() + .map(|d| d.join(".priniarc")) + .filter_map(|p| { + let text = fs::read_to_string(&p).ok()?; + let trusted = is_trusted(&text); + Some((p, text, trusted)) + }) + .collect() +} + +/// Trusts the exact contents given; an edit to a file revokes it. +pub fn trust(texts: &[&str]) -> std::io::Result<()> { let Some(tp) = trust_path() else { - return Ok(Vec::new()); + return Ok(()); }; let mut known = fs::read_to_string(&tp).unwrap_or_default(); - let mut done = Vec::new(); - for p in cwd.ancestors().map(|d| d.join(".priniarc")) { - let Ok(text) = fs::read_to_string(&p) else { - continue; - }; - if !is_trusted(&text) { - known.push_str(&digest(&text)); - known.push('\n'); - } - done.push(p); + for t in texts { + known.push_str(&digest(t)); + known.push('\n'); } if let Some(d) = tp.parent() { fs::create_dir_all(d)?; } - fs::write(tp, known)?; - Ok(done) + fs::write(tp, known) } #[derive(Clone, Copy, PartialEq)] diff --git a/src/main.rs b/src/main.rs index 2514cf6..f2fa984 100644 --- a/src/main.rs +++ b/src/main.rs @@ -165,8 +165,12 @@ enum Cmd { #[arg(value_parser = ["zsh"])] shell: String, }, - /// Allow the `.priniarc` files here to turn on `run` and `write` - Trust, + /// Show the `.priniarc` files here and above, and allow them to turn on `run`, `write` and `agent` + Trust { + /// Skip the question + #[arg(long)] + yes: bool, + }, /// Back up, restore or rotate the key that protects the history Key { #[command(subcommand)] @@ -282,14 +286,24 @@ fn run() -> Result<()> { print!("{}", include_str!("../scripts/prinia.zsh")); Ok(()) } - Some(Cmd::Trust) => { - let done = config::trust(&std::env::current_dir()?)?; - if done.is_empty() { + Some(Cmd::Trust { yes }) => { + let files = config::project_files(&std::env::current_dir()?); + if files.is_empty() { bail!("no .priniarc here or above"); } - for p in done { - println!("trusted {}", p.display()); + let pending: Vec<_> = files.iter().filter(|f| !f.2).collect(); + if pending.is_empty() { + println!("already trusted"); + return Ok(()); } + for (p, text, _) in &pending { + println!("--- {} ---\n{}", p.display(), text.trim_end()); + } + if !history::confirm("Trust these files exactly as shown?", *yes)? { + bail!("not trusted"); + } + config::trust(&pending.iter().map(|f| f.1.as_str()).collect::>())?; + println!("trusted {} file(s)", pending.len()); Ok(()) } Some(Cmd::Key { action }) => key_cmd(action, keychain), @@ -371,8 +385,8 @@ fn fan_out(args: &[String], inputs: &[String], jobs: usize) -> Vec<(String, bool let Some(input) = inputs.get(i) else { return }; let r = std::process::Command::new(&exe) .args(args) - // chunks are already small; never split them again - .env("PRINIA_MAX_INPUT", "0") + // set directly, not through `max_input`: a project file would beat the env + .env("PRINIA_CHILD", "1") .stdin(std::process::Stdio::piped()) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) @@ -524,7 +538,11 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { } let max_input = cfg.num("max_input").unwrap_or(0) as usize; - if max_input > 0 && payload.chars().count() > max_input && !cli.cmd { + if max_input > 0 + && payload.chars().count() > max_input + && !cli.cmd + && std::env::var_os("PRINIA_CHILD").is_none() + { return map_reduce(cli, &instruction, &payload, max_input); } if !stdin_tty && payload.trim().is_empty() { diff --git a/src/store.rs b/src/store.rs index 1b4875b..7ce526d 100644 --- a/src/store.rs +++ b/src/store.rs @@ -131,6 +131,29 @@ pub fn read_stats(dir: Option<&str>, since_days: Option) -> Result { )?) } +/// The data key from an unfinished rotation, if `master` unlocks it. +fn pending_key(conn: &Connection, master: &Key) -> Option> { + let w: Vec = conn + .query_row( + "SELECT value FROM meta WHERE key = 'data_key_pending'", + [], + |r| r.get(0), + ) + .optional() + .ok()??; + unseal(master, &w).ok() +} + +fn promote_pending(conn: &Connection) -> Result<()> { + let tx = conn.unchecked_transaction()?; + tx.execute( + "UPDATE meta SET value = (SELECT value FROM meta WHERE key = 'data_key_pending') WHERE key = 'data_key'", + [], + )?; + tx.execute("DELETE FROM meta WHERE key = 'data_key_pending'", [])?; + Ok(tx.commit()?) +} + fn pack(key: &Key, c: &Content) -> Result> { let v = json!({"i": c.instruction, "p": c.payload, "r": c.response, "cwd": c.cwd, "repo": c.repo, "branch": c.branch}); seal(key, &zstd::encode_all(v.to_string().as_bytes(), 3)?) @@ -233,10 +256,20 @@ impl Store { conn.execute_batch("COMMIT")?; } let data_key = match (wrapped, key::load(keychain)?) { - (Some(w), Some(master)) => unseal(&master, &w) - .context("the key does not match this history")? - .try_into() - .map_err(|_| anyhow!("corrupt data key"))?, + (Some(w), Some(master)) => { + let dk = match unseal(&master, &w) { + Ok(k) => k, + // `key rotate` saved the new key file but stopped before the database caught up + Err(e) => match pending_key(&conn, &master) { + Some(k) => { + promote_pending(&conn)?; + k + } + None => return Err(e).context("the key does not match this history"), + }, + }; + dk.try_into().map_err(|_| anyhow!("corrupt data key"))? + } (Some(_), None) => bail!( "the history exists but its key is missing; restore it with `prinia key import`" ), @@ -246,25 +279,20 @@ impl Store { } /// Re-wrap the data key under a new master key. The history itself is not rewritten. - // NOTE: the database is updated before the key is saved; if saving fails the old wrapping is restored. + /// Crash-safe in three steps: the new wrapping is stored beside the old, then the key is + /// saved, then the new wrapping replaces the old. `open_at` finishes it if the process stopped + /// between the last two. pub fn rewrap(&self, new_master: &Key, keychain: bool) -> Result<()> { - let old: Vec = - self.conn - .query_row("SELECT value FROM meta WHERE key = 'data_key'", [], |r| { - r.get(0) - })?; self.conn.execute( - "UPDATE meta SET value = ?1 WHERE key = 'data_key'", + "INSERT OR REPLACE INTO meta (key, value) VALUES ('data_key_pending', ?1)", params![seal(new_master, &self.data_key)?], )?; if let Err(e) = key::save(new_master, keychain) { - self.conn.execute( - "UPDATE meta SET value = ?1 WHERE key = 'data_key'", - params![old], - )?; + self.conn + .execute("DELETE FROM meta WHERE key = 'data_key_pending'", [])?; return Err(e); } - Ok(()) + promote_pending(&self.conn) } /// Whether `master` unlocks the history at `path` (used before importing a key). @@ -279,7 +307,8 @@ impl Store { }) .optional() .unwrap_or(None); - Ok(wrapped.is_none_or(|w| unseal(master, &w).is_ok())) + Ok(wrapped.is_none_or(|w| unseal(master, &w).is_ok()) + || pending_key(&conn, master).is_some()) } /// A keyed hash, so the stored value reveals nothing about the prompt it stands for. @@ -441,3 +470,57 @@ impl Store { Ok(n) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rotation_survives_a_crash_after_the_key_file_was_replaced() { + let d = std::env::temp_dir().join(format!("prinia-rot-{}", std::process::id())); + std::fs::create_dir_all(d.join("cfg")).unwrap(); + // SAFETY: no other test reads the config location while this one runs a store + unsafe { std::env::set_var("PRINIA_CONFIG", d.join("cfg/config.toml")) }; + let db = d.join("h.db"); + let s = Store::open_at(&db, false).unwrap(); + let meta = Meta { + dir: "d", + provider: "p", + model: "m", + mode: "pipe", + tier: "t", + input_tokens: 1, + output_tokens: 1, + duration_ms: 1, + cache_key: "k", + }; + let content = Content { + response: "kept".into(), + ..Default::default() + }; + s.record(&meta, &content).unwrap(); + // the crash: new key saved and its wrapping stored, but `data_key` still the old one + let new = key::random().unwrap(); + s.conn + .execute( + "INSERT OR REPLACE INTO meta (key, value) VALUES ('data_key_pending', ?1)", + params![seal(&new, &s.data_key).unwrap()], + ) + .unwrap(); + key::save(&new, false).unwrap(); + drop(s); + let s = Store::open_at(&db, false).unwrap(); + assert_eq!(s.get(1).unwrap().unwrap().content.response, "kept"); + let pending: Option> = s + .conn + .query_row( + "SELECT value FROM meta WHERE key = 'data_key_pending'", + [], + |r| r.get(0), + ) + .optional() + .unwrap(); + assert!(pending.is_none(), "the rotation was finished"); + std::fs::remove_dir_all(&d).unwrap(); + } +} diff --git a/tests/cli.rs b/tests/cli.rs index e1a0b4f..465c4f0 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -476,6 +476,69 @@ fn turns_from_a_private_provider_are_not_sent_to_another_one() { assert!(!mock.last().1.to_string().contains("secret roadmap")); } +#[test] +fn long_input_is_split_once_even_when_a_project_sets_max_input() { + let mock = Mock::start("partial", 200); + let env = Env::new("max-input", &mock); + // a project file beats the environment, so the children must not rely on an env override + std::fs::write(env.dir.join("work/.priniarc"), "max_input = 40\n").unwrap(); + let input = (0..6) + .map(|n| format!("line-{n}-aaaaaaaa\n")) + .collect::(); // 96 characters + let (out, err, code) = env.run(&["-p", "local", "summarize this"], &input, &[]); + assert_eq!((out.as_str(), code), ("partial\n", 0), "{err}"); + // three parts of at most 40 characters, then one combining call (itself over 40, never re-split) + assert_eq!(mock.hits(), 4, "{err}"); + let last = mock.last().1.to_string(); + assert!( + last.contains("--- part 1 ---") && last.contains("Combine them"), + "{last}" + ); + assert!( + last.contains("summarize this"), + "the combining call carries the instruction" + ); +} + +#[test] +fn trust_shows_the_file_asks_and_expires_when_the_file_changes() { + let mock = Mock::start("ok", 200); + let env = Env::new("trust", &mock); + let rc = env.dir.join("work/.priniarc"); + std::fs::write(&rc, "run = true\n").unwrap(); + let run_setting = |env: &Env| env.run(&["config"], "", &[]).0; + assert!( + !run_setting(&env) + .lines() + .any(|l| l.starts_with("run ") && l.contains("true")) + ); + // no terminal and no --yes: nothing is trusted + let (out, err, code) = env.run(&["trust"], "", &[]); + assert!( + code != 0 && out.contains("run = true") && err.contains("--yes"), + "{out} {err}" + ); + assert!( + !run_setting(&env) + .lines() + .any(|l| l.starts_with("run ") && l.contains("true")) + ); + let (_, err, code) = env.run(&["trust", "--yes"], "", &[]); + assert_eq!(code, 0, "{err}"); + assert!( + run_setting(&env) + .lines() + .any(|l| l.starts_with("run ") && l.contains("true")) + ); + // any change to the file needs trusting again + std::fs::write(&rc, "run = true\nwrite = true\n").unwrap(); + assert!( + !run_setting(&env) + .lines() + .any(|l| l.starts_with("run ") && l.contains("true")) + ); +} + #[test] fn many_first_calls_at_once_share_one_key() { let mock = Mock::start("answer", 200); From 56299527e0e1f8900a3934c0fb3a74037be28a79 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:30:37 +0200 Subject: [PATCH 21/31] refactor: split ask(), share Request::plain; fix: init test hook, history cap, docs for the audit fixes --- docs/agent.md | 4 +- docs/configuration.md | 2 +- docs/history.md | 2 +- docs/usage.md | 4 +- src/agent.rs | 5 +- src/context.rs | 14 +- src/curate.rs | 7 +- src/init.rs | 43 ++++-- src/main.rs | 333 +++++++++++++++++++++++++----------------- src/provider.rs | 16 ++ tests/cli.rs | 16 ++ 11 files changed, 281 insertions(+), 165 deletions(-) diff --git a/docs/agent.md b/docs/agent.md index 3f0ae7a..fd5ca5a 100644 --- a/docs/agent.md +++ b/docs/agent.md @@ -22,13 +22,13 @@ The model then decides per question whether to call a tool. The `agent` setting | Tool | Needs | What it does | | :--- | :--- | :--- | -| `read_file` | nothing | Reads a text file, with line numbers, optionally a line range | +| `read_file` | nothing | Reads a text file (regular files up to 10 MB), with line numbers, optionally a line range | | `list_dir` | nothing | Lists a directory | | `search` | nothing | Finds lines containing a text (case-insensitive) under a path; skips hidden directories, `target` and `node_modules` | | `write_file`, `replace` | `--write` | Creates or overwrites a file; replaces one exact, unique piece of text | | `run_command` | `--run` | Runs a shell command (asking first unless read-only) in the directory and returns its output and exit code; stopped after 60 seconds | -Reading is the default and changes nothing. Writing and running commands are separate switches, so you can allow one without the other. `--run` asks before each command on your terminal (`[y/N]`), except a pipeline of read-only commands (`ls`, `cat`, `find`, `grep`, `rg`, `git status|log|diff|show`, `date`, ...), which runs straight away. Anything with `;`, `&&`, `$(...)`, redirects, or flags like `find -exec` or `-delete` asks. With no terminal to ask on, such a command is refused and the model is told. `-y` (`--yes`) runs everything without asking. `--write` has no per-file confirmation, so use it in a git repository where changes can be reviewed. +Reading is the default and changes nothing. Writing and running commands are separate switches, so you can allow one without the other. `--run` asks before each command on your terminal (`[y/N]`), except a pipeline of read-only commands (`ls`, `cat`, `head`, `find`, `grep`, `rg`, `sort`, `wc`, `date`, ...), which runs straight away. Anything with `;`, `&&`, `$(...)`, redirects, or flags that write or run a program (`find -exec`, `-delete`, `sort -o`, `rg --pre`) asks. `git` always asks, because a repository's own config can make even `git status` run a program. With no terminal to ask on, such a command is refused and the model is told. `-y` (`--yes`) runs everything without asking. `--write` has no per-file confirmation, so use it in a git repository where changes can be reviewed. All file tools stay inside the directory you ran the command in. A path that leaves it, by `..`, an absolute path or a symbolic link, is refused. `run_command` is not limited this way, since a shell command can do anything your account can. diff --git a/docs/configuration.md b/docs/configuration.md index 4c154e1..2663fb2 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -20,7 +20,7 @@ cache_ttl = "3d" A `.priniarc` holds behaviour only: `record`, `cache`, `cache_ttl`, `context`, `context_chars`, `max_tokens`, `effort`, `fast_under`, `deep_over`, `check_retries`, `max_input`, `agent`, `agent_steps`, `run`, `write` and the two prompts. Everything about the device is read only from your global config and ignored, with a warning, in a project file: `[providers.*]`, `provider`, the model names, `keychain` and the history limits. A repository therefore cannot choose where your prompts go. -Settings that let the model act on your machine or change what it is told (`run`, `write`, `agent`, `prompt_pipe`, `prompt_interactive`) are ignored in a project file until you read it and run `prinia trust`. Turning `run`, `write` or `agent` off needs no trust. Trust is tied to the file's exact contents, so any later change, such as from a `git pull`, needs trusting again. Your own global config is always trusted. +Settings that let the model act on your machine or change what it is told (`run`, `write`, `agent`, `prompt_pipe`, `prompt_interactive`) are ignored in a project file until you run `prinia trust`, which prints each file and asks before trusting it (`--yes` skips the question). Turning `run`, `write` or `agent` off needs no trust. Trust is tied to the file's exact contents, so any later change, such as from a `git pull`, needs trusting again. Your own global config is always trusted. ### Tags and private mode diff --git a/docs/history.md b/docs/history.md index 498d351..85ed68b 100644 --- a/docs/history.md +++ b/docs/history.md @@ -73,7 +73,7 @@ prinia history ask "what did I ask about TLS last month?" 2. **Keywords:** the remaining meaningful words are matched against prompt, input and answer; a match in the prompt counts most. With no keyword hit, the newest turns are used. 3. **Answer:** the best `ask_turns` turns (default 15) go to the model with longer excerpts (`excerpt_prompt` 400, `excerpt_reply` 1000 characters), and it answers citing `#id`. If they do not contain the answer it should say so. stderr lists the turns used; open one with `prinia history show ID`. -Those excerpts leave your machine like any other prompt, so `ask` uses your configured provider and the `private` / `tag` rules apply. It is not recorded. Matching is plain words, not meaning: ask with the words you would have used at the time. +Those excerpts leave your machine like any other prompt, so `ask` uses your configured provider and the `private` / `tag` rules apply. Turns made with a `private` provider are left out unless the provider answering is `private` too (the same goes for `history agent`). It is not recorded. Matching is plain words, not meaning: ask with the words you would have used at the time. ## Deleting diff --git a/docs/usage.md b/docs/usage.md index 6139222..7adedcc 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -55,12 +55,12 @@ prinia "what does SIGPIPE do?" prinia -c "and how do I ignore it in Rust?" ``` -The context comes from your own history, not from a provider's session, so it works with any provider and survives a switch of model. Only turns from the current directory are used, oldest first, and long turns are cut. Set `context = 5` (a number of turns) to include it on every call and `--no-context` to leave it out once. `context_chars` (default 16000) caps its size; the oldest turns are dropped first. Calls made with `--no-record` are not in the history, so they are never part of a context. +Turns made with a provider tagged `private` are never sent to a provider that is not (see [Tags and private mode](configuration.md#tags-and-private-mode)). The context comes from your own history, not from a provider's session, so it works with any provider and survives a switch of model. Only turns from the current directory are used, oldest first, and long turns are cut. Set `context = 5` (a number of turns) to include it on every call and `--no-context` to leave it out once. `context_chars` (default 16000) caps its size; the oldest turns are dropped first. Calls made with `--no-record` are not in the history, so they are never part of a context. Older turns are not simply dropped. The context has four tiers: 1. **Recent turns, word for word**: the newest `context` turns. -2. **Relevant older turns, in full**: up to `context_relevant` turns (default 3; `0` turns it off) from further back that match the words of your new question (prompt matches count most; a word that is in most of your turns is ignored). They use up to half of `context_chars`. This is what lets `prinia -c "why did the payments API time out again?"` find the exchange from three weeks ago. +2. **Relevant older turns, in full**: up to `context_relevant` turns (default 3; `0` turns it off) from further back that match the words of your new question (prompt matches count most; a word that is in most of your turns is ignored). They use up to half of `context_chars`. Only the newest 300 turns of the directory are searched. This is what lets `prinia -c "why did the payments API time out again?"` find the exchange from three weeks ago. 3. **Older questions, one line each**: the next `context_older` turns (default 30; `0` turns it off), cut to 160 characters, so the model knows what you were working on. 4. **Summaries** (opt-in, `context_summary = true`): older turns are grouped into blocks of about 25 history entries, and each finished block is summarized once by the fast tier of the *same provider as the call*, so `private` and `tag` rules hold. Only the newest `context_blocks` blocks (default 4) are included. A summary is stored encrypted next to the history and is derived from it: any delete (`history rm`, size or age limits) drops all stored summaries, and they are rebuilt from what is left. Summaries are lossy; the model can be wrong about details it never saw in full. diff --git a/src/agent.rs b/src/agent.rs index dd08f99..fa112a5 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -387,14 +387,11 @@ pub fn run(o: &Opts, on_text: &mut dyn FnMut(&str)) -> Result { let mut total = Reply::default(); for _ in 0..max { let req = Request { - model: o.model, - system: &system, - user: o.user, - history: &[], tools: &tools, follow: &follow, effort: o.effort, max_tokens: o.max_tokens, + ..Request::plain(o.model, &system, o.user) }; let r = o.provider.complete(&req, &mut |_| {})?; total.input_tokens += r.input_tokens; diff --git a/src/context.rs b/src/context.rs index 162d74c..610b32d 100644 --- a/src/context.rs +++ b/src/context.rs @@ -12,7 +12,7 @@ const REPLY_CAP: usize = 4_000; /// Turns are grouped into blocks by `id / BLOCK`; a block is summarized once, when no new turn can /// land in it any more. const BLOCK: i64 = 25; -const LIST_LIMIT: usize = 1_000; +const LIST_LIMIT: usize = 300; pub struct Params<'a> { pub dir: &'a str, @@ -94,14 +94,12 @@ fn summarize(store: &Store, s: &Summary, block: &[&Turn]) -> Result { } let text = block_text(block); let req = Request { - model: s.model, - system: "Summarize this stretch of a user's terminal question-and-answer history in under 120 words. Keep names, commands, file paths, decisions and open questions. No preamble.", - user: &text, - history: &[], - tools: &[], - follow: &[], - effort: None, max_tokens: Some(400), + ..Request::plain( + s.model, + "Summarize this stretch of a user's terminal question-and-answer history in under 120 words. Keep names, commands, file paths, decisions and open questions. No preamble.", + &text, + ) }; let reply = s.provider.complete(&req, &mut |_| {})?; let out = reply.text.trim().to_string(); diff --git a/src/curate.rs b/src/curate.rs index 9014d38..db74c66 100644 --- a/src/curate.rs +++ b/src/curate.rs @@ -35,14 +35,9 @@ fn call(cfg: &Config, tier: Tier, system: &str, user: &str, show: bool) -> Resul let model = provider.model(cfg, tier)?; let effort = provider.effort(cfg, tier); let req = Request { - model: &model, - system, - user, - history: &[], - tools: &[], - follow: &[], effort: effort.as_deref(), max_tokens: cfg.num("max_tokens"), + ..Request::plain(&model, system, user) }; let reply = provider.complete(&req, &mut |piece| { if show { diff --git a/src/init.rs b/src/init.rs index 35cc4fc..e158b1c 100644 --- a/src/init.rs +++ b/src/init.rs @@ -7,6 +7,11 @@ use std::time::Duration; const OLLAMA: &str = "http://localhost:11434"; +/// `PRINIA_OLLAMA_URL` points at another server (and lets tests avoid the real one). +fn ollama() -> String { + std::env::var("PRINIA_OLLAMA_URL").unwrap_or_else(|_| OLLAMA.into()) +} + /// (regular model, approximate download in GB, deep model) for this much memory. fn recommend(gb: u64) -> (&'static str, u64, Option<&'static str>) { match gb { @@ -47,7 +52,7 @@ fn installed() -> Option> { .build() .into(); let v: serde_json::Value = agent - .get(format!("{OLLAMA}/api/tags")) + .get(format!("{}/api/tags", ollama())) .call() .ok()? .body_mut() @@ -87,16 +92,28 @@ fn pull(model: &str, gb: u64) -> Result<()> { Ok(()) } +/// The global config for a local Ollama model. +fn config_text(url: &str, model: &str, deep: Option<&str>) -> String { + let mut cfg = format!( + "provider = \"local\"\nmax_input = 48000 # longer input is processed in parts\n\n[providers.local]\ntype = \"openai\"\ntags = [\"private\"]\nbase_url = \"{url}/v1\"\nmodel = \"{model}\"\nfast_model = \"{model}\"\n" + ); + if let Some(d) = deep { + cfg.push_str(&format!("deep_model = \"{d}\"\n")); + } + cfg +} + pub fn run() -> Result<()> { let keys = ["ANTHROPIC_API_KEY", "OPENAI_API_KEY"] .iter() - .any(|k| std::env::var_os(k).is_some()); + .any(|k| std::env::var(k).is_ok_and(|v| !v.is_empty())); let Some(_) = installed() else { if keys { println!("An API key is set in your environment: `prinia \"hello\"` already works."); } else { println!( - "No model server found at {OLLAMA} and no API key set.\nInstall Ollama (https://ollama.com), start it and run `prinia init` again, or export ANTHROPIC_API_KEY / OPENAI_API_KEY." + "No model server found at {} and no API key set.\nInstall Ollama (https://ollama.com), start it and run `prinia init` again, or export ANTHROPIC_API_KEY / OPENAI_API_KEY.", + ollama() ); } return Ok(()); @@ -114,12 +131,7 @@ pub fn run() -> Result<()> { if let Some(d) = deep { pull(d, 20)?; } - let mut cfg = format!( - "provider = \"local\"\nmax_input = 48000 # longer input is processed in parts\n\n[providers.local]\ntype = \"openai\"\ntags = [\"private\"]\nbase_url = \"{OLLAMA}/v1\"\nmodel = \"{model}\"\nfast_model = \"{model}\"\n" - ); - if let Some(d) = deep { - cfg.push_str(&format!("deep_model = \"{d}\"\n")); - } + let cfg = config_text(&ollama(), model, deep); let path = config::global_path().ok_or_else(|| anyhow!("no config directory"))?; if path.exists() { println!( @@ -138,6 +150,19 @@ pub fn run() -> Result<()> { mod tests { use super::*; + #[test] + fn the_written_config_is_valid_toml_with_the_model_private_and_tiered() { + let t: toml::Table = toml::from_str(&config_text("http://h:1", "m1", Some("m2"))).unwrap(); + let p = &t["providers"]["local"]; + assert_eq!(p["base_url"].as_str(), Some("http://h:1/v1")); + assert_eq!(p["tags"][0].as_str(), Some("private")); + assert_eq!( + (p["model"].as_str(), p["deep_model"].as_str()), + (Some("m1"), Some("m2")) + ); + assert_eq!(t["max_input"].as_integer(), Some(48000)); + } + #[test] fn model_scales_with_memory() { assert_eq!(recommend(48).2, Some("qwen2.5:32b")); diff --git a/src/main.rs b/src/main.rs index f2fa984..66b9833 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,7 @@ use anyhow::{Result, anyhow, bail}; use clap::{Parser, Subcommand}; use config::Config; -use provider::{Provider, Request, Tier}; +use provider::{Provider, Reply, Request, Tier}; use std::io::{IsTerminal, Read, Write}; use std::path::Path; use std::process::{Command, Stdio, exit}; @@ -517,9 +517,8 @@ fn map_reduce(cli: &Cli, instruction: &str, payload: &str, max: usize) -> Result Ok(()) } -fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { - let stdin_tty = std::io::stdin().is_terminal(); - let stdout_tty = std::io::stdout().is_terminal(); +/// The instruction (with any template) and the piped input. +fn read_input(cli: &Cli, stdin_tty: bool) -> Result<(String, String)> { let mut payload = String::new(); if !stdin_tty { std::io::stdin().read_to_string(&mut payload)?; @@ -536,33 +535,10 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { if instruction.is_empty() && payload.trim().is_empty() { bail!("nothing to do. Usage: prinia \"question\" or cmd | prinia \"instruction\""); } + Ok((instruction, payload)) +} - let max_input = cfg.num("max_input").unwrap_or(0) as usize; - if max_input > 0 - && payload.chars().count() > max_input - && !cli.cmd - && std::env::var_os("PRINIA_CHILD").is_none() - { - return map_reduce(cli, &instruction, &payload, max_input); - } - if !stdin_tty && payload.trim().is_empty() { - eprintln!("prinia: warning: stdin is empty, answering the instruction alone"); - } - - // Raw output whenever either end is a pipe. - let piped = !stdin_tty || !stdout_tty || cli.cmd; - let validate = cli.json || cli.check.is_some(); - // The setting only applies at a terminal; pipelines stay plain filters. - let agent = cli.agent - || cli.do_it - || (!cli.no_agent && !validate && !piped && cfg.bool("agent").unwrap_or(false)); - let mode = if agent { - "agent" - } else if piped { - "pipe" - } else { - "interactive" - }; +fn system_prompt(cli: &Cli, cfg: &Config, piped: bool) -> String { let system = if cli.cmd { cmd_prompt() } else if piped { @@ -571,15 +547,15 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { cfg.str("prompt_interactive") .unwrap_or_else(|| PROMPT_INTERACTIVE.into()) }; - - let system = if cli.json { + if cli.json { format!("{system} Respond with a single valid JSON value and nothing else.") } else { system - }; + } +} - let provider = Provider::resolve(cfg, cli.provider.as_deref())?; - let size = combine(&instruction, &payload).chars().count() as u64; +/// The tier (a flag, else the size rules) and the model for it. +fn route(cli: &Cli, cfg: &Config, provider: &Provider, size: u64) -> Result<(Tier, String)> { let tier = if cli.fast { Tier::Fast } else if cli.deep { @@ -597,12 +573,174 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { Some(m) => m.clone(), None => provider.model(cfg, tier)?, }; + Ok((tier, model)) +} + +/// How many earlier turns this call sends (`-c`, `--no-context`, the `context` setting). +fn context_turns(cli: &Cli, cfg: &Config) -> usize { + let setting = cfg.num("context").unwrap_or(0) as usize; + if cli.no_context { + 0 + } else if cli.context { + if setting > 0 { setting } else { 5 } + } else { + setting + } +} + +/// One model call (or an agent run), retried while a `--json` / `--check` validation fails. +struct Call<'a> { + cli: &'a Cli, + cfg: &'a Config, + provider: &'a Provider, + req: Request<'a>, + agent: bool, + piped: bool, +} + +impl Call<'_> { + fn run(&self) -> Result<(Reply, String)> { + let (cli, cfg) = (self.cli, self.cfg); + let validate = cli.json || cli.check.is_some(); + // A terminal gets the answer as it arrives; a pipe gets it whole, so a wrapping code fence + // can be stripped. NOTE: filter the fence while streaming if piped latency ever matters. + let piped = self.piped; + let mut show = |piece: &str| { + if !piped && !validate { + print!("{piece}"); + let _ = std::io::stdout().flush(); + } + }; + // Checks need the whole answer, so nothing is printed (or saved) until it passes. + let attempts = if validate { + cfg.num("check_retries").unwrap_or(2) + 1 + } else { + 1 + }; + let mut tried = 0; + loop { + tried += 1; + let reply = if self.agent { + agent::run( + &agent::Opts { + cfg, + provider: self.provider, + model: self.req.model, + effort: self.req.effort, + max_tokens: self.req.max_tokens, + user: self.req.user, + write: cli.write || cfg.bool("write").unwrap_or(false), + run: cli.run || cli.do_it || cfg.bool("run").unwrap_or(false), + yes: cli.yes, + }, + &mut show, + )? + } else { + self.provider.complete(&self.req, &mut show)? + }; + if reply.stop == "refusal" { + bail!("the model declined this request"); + } + let text = if piped || validate { + strip_fence(&reply.text) + } else { + reply.text.clone() + }; + if !validate || check::passes(&text, cli.json, cli.check.as_deref()) { + return Ok((reply, text)); + } + if tried >= attempts { + bail!("the answer failed the check {tried} time(s); nothing was printed or saved"); + } + eprintln!("[prinia] the answer failed the check; asking again ({tried}/{attempts})"); + } + } +} + +/// Everything `record_turn` saves besides the answer. +struct Recorded<'a> { + dir: &'a str, + cwd: &'a Path, + provider: &'a Provider, + mode: &'a str, + tier: &'a str, + cache_key: &'a str, + started: Instant, + instruction: String, + payload: String, +} + +/// Bookkeeping happens after the output is out, so nothing downstream waits for it. +fn record_turn(s: &Store, cfg: &Config, r: Recorded, reply: &Reply, text: String) { + let cut_off = matches!(reply.stop.as_str(), "max_tokens" | "length"); + let (repo, branch) = git_info(r.cwd); + let meta = Meta { + dir: r.dir, + provider: &r.provider.name, + model: &reply.model, + mode: r.mode, + tier: r.tier, + input_tokens: reply.input_tokens, + output_tokens: reply.output_tokens, + duration_ms: r.started.elapsed().as_millis() as u64, + // an answer cut off at the limit stays in the history but never answers a later call + cache_key: if cut_off { "" } else { r.cache_key }, + }; + let content = Content { + instruction: r.instruction, + payload: r.payload, + response: text, + cwd: r.cwd.to_string_lossy().into_owned(), + repo, + branch, + }; + if let Err(e) = s.record(&meta, &content) { + eprintln!("[prinia] history not saved: {e:#}"); + } else { + history::enforce_limits(s, cfg); + } +} + +fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { + let stdin_tty = std::io::stdin().is_terminal(); + let (instruction, payload) = read_input(cli, stdin_tty)?; + + let max_input = cfg.num("max_input").unwrap_or(0) as usize; + if max_input > 0 + && payload.chars().count() > max_input + && !cli.cmd + && std::env::var_os("PRINIA_CHILD").is_none() + { + return map_reduce(cli, &instruction, &payload, max_input); + } + if !stdin_tty && payload.trim().is_empty() { + eprintln!("prinia: warning: stdin is empty, answering the instruction alone"); + } + + // Raw output whenever either end is a pipe. + let piped = !stdin_tty || !std::io::stdout().is_terminal() || cli.cmd; + let validate = cli.json || cli.check.is_some(); + // The setting only applies at a terminal; pipelines stay plain filters. + let agent = cli.agent + || cli.do_it + || (!cli.no_agent && !validate && !piped && cfg.bool("agent").unwrap_or(false)); + let mode = if agent { + "agent" + } else if piped { + "pipe" + } else { + "interactive" + }; + let system = system_prompt(cli, cfg, piped); + + let provider = Provider::resolve(cfg, cli.provider.as_deref())?; + let user = combine(&instruction, &payload); + let (tier, model) = route(cli, cfg, &provider, user.chars().count() as u64)?; let effort = provider.effort(cfg, tier); let max_tokens = cfg.num("max_tokens"); let summary_model = provider .model(cfg, Tier::Fast) .unwrap_or_else(|_| model.clone()); - let user = combine(&instruction, &payload); let record = if cli.record { true @@ -620,14 +758,7 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { let cwd = std::env::current_dir()?; let dir = store::dir_hash(&cwd); - let setting = cfg.num("context").unwrap_or(0) as usize; - let ctx_turns = if cli.no_context { - 0 - } else if cli.context { - if setting > 0 { setting } else { 5 } - } else { - setting - }; + let ctx_turns = context_turns(cli, cfg); let store = if record || use_cache || ctx_turns > 0 { Some(Store::open(keychain)?) } else { @@ -681,67 +812,20 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { } let started = Instant::now(); - let req = Request { - model: &model, - system: &system, - user: &user, - history: &history, - tools: &[], - follow: &[], - effort: effort.as_deref(), - max_tokens, - }; - // A terminal gets the answer as it arrives; a pipe gets it whole, so a wrapping code fence - // can be stripped. NOTE: filter the fence while streaming if piped latency ever matters. - let mut show = |piece: &str| { - if !piped && !validate { - print!("{piece}"); - let _ = std::io::stdout().flush(); - } - }; - // Checks need the whole answer, so nothing is printed (or saved) until it passes. - let attempts = if validate { - cfg.num("check_retries").unwrap_or(2) + 1 - } else { - 1 - }; - let mut tried = 0; - let (reply, mut text) = loop { - tried += 1; - let reply = if agent { - agent::run( - &agent::Opts { - cfg, - provider: &provider, - model: &model, - effort: effort.as_deref(), - max_tokens, - user: &user, - write: cli.write || cfg.bool("write").unwrap_or(false), - run: cli.run || cli.do_it || cfg.bool("run").unwrap_or(false), - yes: cli.yes, - }, - &mut show, - )? - } else { - provider.complete(&req, &mut show)? - }; - if reply.stop == "refusal" { - bail!("the model declined this request"); - } - let text = if piped || validate { - strip_fence(&reply.text) - } else { - reply.text.clone() - }; - if !validate || check::passes(&text, cli.json, cli.check.as_deref()) { - break (reply, text); - } - if tried >= attempts { - bail!("the answer failed the check {tried} time(s); nothing was printed or saved"); - } - eprintln!("[prinia] the answer failed the check; asking again ({tried}/{attempts})"); + let call = Call { + cli, + cfg, + provider: &provider, + req: Request { + history: &history, + effort: effort.as_deref(), + max_tokens, + ..Request::plain(&model, &system, &user) + }, + agent, + piped, }; + let (reply, mut text) = call.run()?; if !text.ends_with('\n') { text.push('\n'); if !piped && !validate { @@ -753,43 +837,28 @@ fn ask(cli: &Cli, cfg: &Config, keychain: bool) -> Result<()> { let _ = std::io::stdout().write_all(text.as_bytes()); } let _ = std::io::stdout().flush(); - let cut_off = matches!(reply.stop.as_str(), "max_tokens" | "length"); - if cut_off { + if matches!(reply.stop.as_str(), "max_tokens" | "length") { eprintln!("[prinia] the answer was cut off at the output limit (raise `max_tokens`)"); } - // Bookkeeping happens after the output is out, so nothing downstream waits for it. if record && let Some(s) = &store { - let (repo, branch) = git_info(&cwd); - let meta = Meta { + let tier = if cli.model.is_some() { + "custom" + } else { + tier.name() + }; + let r = Recorded { dir: &dir, - provider: &provider.name, - model: &reply.model, + cwd: &cwd, + provider: &provider, mode, - tier: if cli.model.is_some() { - "custom" - } else { - tier.name() - }, - input_tokens: reply.input_tokens, - output_tokens: reply.output_tokens, - duration_ms: started.elapsed().as_millis() as u64, - // an answer cut off at the limit stays in the history but never answers a later call - cache_key: if cut_off { "" } else { &cache_key }, - }; - let content = Content { + tier, + cache_key: &cache_key, + started, instruction, payload, - response: text, - cwd: cwd.to_string_lossy().into_owned(), - repo, - branch, }; - if let Err(e) = s.record(&meta, &content) { - eprintln!("[prinia] history not saved: {e:#}"); - } else { - history::enforce_limits(s, cfg); - } + record_turn(s, cfg, r, &reply, text); } Ok(()) } diff --git a/src/provider.rs b/src/provider.rs index 349dac8..2c28366 100644 --- a/src/provider.rs +++ b/src/provider.rs @@ -85,6 +85,22 @@ pub struct Request<'a> { pub max_tokens: Option, } +impl<'a> Request<'a> { + /// A single question with no earlier turns and no tools; callers override what they need. + pub fn plain(model: &'a str, system: &'a str, user: &'a str) -> Self { + Request { + model, + system, + user, + history: &[], + tools: &[], + follow: &[], + effort: None, + max_tokens: None, + } + } +} + #[derive(Default)] pub struct Reply { pub text: String, diff --git a/tests/cli.rs b/tests/cli.rs index 465c4f0..ec7762a 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -539,6 +539,22 @@ fn trust_shows_the_file_asks_and_expires_when_the_file_changes() { ); } +#[test] +fn init_reports_when_there_is_no_model_server_and_writes_nothing() { + let mock = Mock::start("x", 200); + let env = Env::new("init", &mock); + let down = [("PRINIA_OLLAMA_URL", "http://127.0.0.1:1")]; + let (out, _, code) = env.run(&["init"], "", &down); + assert_eq!(code, 0); + assert!(out.contains("An API key is set"), "{out}"); + let (out, _, code) = env.run(&["init"], "", &[down[0], ("ANTHROPIC_API_KEY", "")]); + assert_eq!(code, 0); + assert!( + out.contains("No model server found at http://127.0.0.1:1"), + "{out}" + ); +} + #[test] fn many_first_calls_at_once_share_one_key() { let mock = Mock::start("answer", 200); From 3a22f526c1968d9216a562b4ad9b8169e2c5c306 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:35:58 +0200 Subject: [PATCH 22/31] feat: widget works in vi modes; PRINIA_WIDGET_KEY takes several keys --- docs/usage.md | 2 +- scripts/prinia.zsh | 8 +++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/usage.md b/docs/usage.md index 7adedcc..f3f8ee8 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -107,7 +107,7 @@ git diff | prinia -t commit "mention the ticket ABC-12" # extra words are adde eval "$(prinia shell zsh)" # add to ~/.zshrc ``` -Type what you want in plain words and press ctrl-g (`PRINIA_WIDGET_KEY` changes the key). The line is replaced by one shell command, which you can edit; nothing runs until you press enter. The model is told your shell and OS and which of `rg`, `fd`, `jq` and `yq` are installed. `prinia --cmd "..."` does the same without the widget. Answers from small local models can be wrong, so read the command before running it. +Type what you want in plain words and press ctrl-g. It is bound in emacs mode and in both vi modes. Set `PRINIA_WIDGET_KEY` before the `eval` line to change it, or to use several keys: `export PRINIA_WIDGET_KEY='^x^p ^n'` (zsh key notation; `^g` is ctrl-g). To free ctrl-g again, rebind it after the `eval`: `bindkey '^g' list-expand`. The line is replaced by one shell command, which you can edit; nothing runs until you press enter. The model is told your shell and OS and which of `rg`, `fd`, `jq` and `yq` are installed. `prinia --cmd "..."` does the same without the widget. Answers from small local models can be wrong, so read the command before running it. ## Checking the answer diff --git a/scripts/prinia.zsh b/scripts/prinia.zsh index 862d9bb..010689c 100644 --- a/scripts/prinia.zsh +++ b/scripts/prinia.zsh @@ -13,4 +13,10 @@ _prinia_widget() { fi } zle -N _prinia_widget -bindkey "${PRINIA_WIDGET_KEY:-^g}" _prinia_widget +# Keys: PRINIA_WIDGET_KEY, a space-separated list (default ^g), bound in emacs mode and both vi modes. +for _prinia_map in emacs viins vicmd; do + for _prinia_key in ${=PRINIA_WIDGET_KEY:-^g}; do + bindkey -M $_prinia_map "$_prinia_key" _prinia_widget 2>/dev/null + done +done +unset _prinia_map _prinia_key From 3b1f36f5540c02fe5465680cd64d0b1067071516 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:43:16 +0200 Subject: [PATCH 23/31] feat: Windows approval prompt (CONIN$/CONOUT$) and process-tree kill (taskkill /T); informational Windows CI job --- .github/workflows/ci.yml | 15 +++++++++++++++ src/agent.rs | 33 ++++++++++++++++++++++++--------- 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1970874..dbf5839 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,6 +31,21 @@ jobs: - run: cargo clippy --locked --all-targets -- -D warnings - run: cargo test --locked + # Windows is not supported yet: this job shows whether it builds and which tests fail, + # without blocking a merge (it is not in required-checks-passed). + test-windows: + name: Test (windows-latest, informational) + runs-on: windows-latest + timeout-minutes: 30 + continue-on-error: true + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + - run: cargo clippy --locked --all-targets -- -D warnings + - run: cargo test --locked + # The installer is piped into sh on users' machines. shell: name: Shell scripts diff --git a/src/agent.rs b/src/agent.rs index fa112a5..b1ac194 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -277,19 +277,28 @@ fn read_only(cmd: &str) -> bool { }) } -/// Asks on the terminal; with no terminal the answer is no. +/// Asks on the terminal, even when stdin and stdout are pipes; with no terminal the answer is no. fn approve(cmd: &str) -> bool { use std::io::{BufRead, Write}; - let Ok(mut tty) = std::fs::OpenOptions::new() - .read(true) - .write(true) - .open("/dev/tty") - else { + // the console device: one file on Unix, separate input and output handles on Windows + let (input, output) = if cfg!(windows) { + ("CONIN$", "CONOUT$") + } else { + ("/dev/tty", "/dev/tty") + }; + let open = |path: &str, write: bool| { + std::fs::OpenOptions::new() + .read(!write) + .write(write) + .open(path) + }; + let (Ok(mut out), Ok(inp)) = (open(output, true), open(input, false)) else { return false; }; - let _ = write!(tty, "[prinia] run `{cmd}`? [y/N] "); + let _ = write!(out, "[prinia] run `{cmd}`? [y/N] "); + let _ = out.flush(); let mut line = String::new(); - let _ = std::io::BufReader::new(&tty).read_line(&mut line); + let _ = std::io::BufReader::new(inp).read_line(&mut line); line.trim().eq_ignore_ascii_case("y") } @@ -321,11 +330,17 @@ fn run_command(root: &Path, a: &Value, yes: bool) -> Result { break Some(s); } if started.elapsed() > Duration::from_secs(60) { - // kill the group, or a background grandchild keeps the output pipe open + // kill the whole tree, or a background grandchild keeps the output pipe open #[cfg(unix)] let _ = Command::new("kill") .args(["-KILL", &format!("-{}", child.id())]) .status(); + #[cfg(windows)] + let _ = Command::new("taskkill") + .args(["/T", "/F", "/PID", &child.id().to_string()]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); let _ = child.kill(); let _ = child.wait(); break None; From 0faee6d2d731c283c5420c4b64deaffb69d3ad66 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:45:27 +0200 Subject: [PATCH 24/31] fix: key.rs built on Windows (bail! only used under cfg(unix)) --- src/key.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/key.rs b/src/key.rs index fcb61d4..fa0d489 100644 --- a/src/key.rs +++ b/src/key.rs @@ -2,7 +2,7 @@ //! store with `keychain = true`). It wraps the data key that encrypts history content, so it can //! be rotated without rewriting the history, and it can be shown as words for backup. use crate::config; -use anyhow::{Context, Result, anyhow, bail}; +use anyhow::{Context, Result, anyhow}; use std::path::{Path, PathBuf}; use std::{fs, io::Write}; @@ -59,7 +59,7 @@ fn read_file(path: &Path) -> Result> { }; #[cfg(unix)] if std::os::unix::fs::PermissionsExt::mode(&meta.permissions()) & 0o077 != 0 { - bail!( + anyhow::bail!( "{} is readable by others; run: chmod 600 {}", path.display(), path.display() From f6624829a7692b0ba830970605b73c357b65e346 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:46:53 +0200 Subject: [PATCH 25/31] docs: settings, provider fields, env vars and flags added in this PR --- README.md | 5 +++-- docs/agent.md | 2 +- docs/configuration.md | 14 ++++++++++++++ docs/usage.md | 9 +++++++++ 4 files changed, 27 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 7454c69..beff772 100644 --- a/README.md +++ b/README.md @@ -59,9 +59,10 @@ prinia -p local "..." # a configured provider cat list.txt | prinia --each "..." # one call per line, in parallel (-j N) prinia -t NAME "..." # a saved instruction (docs/usage.md#templates) prinia --cmd "..." # one shell command; `eval "$(prinia shell zsh)"` binds it to ctrl-g -prinia -x "..." # let the model run commands to answer (agent + --run) +prinia -x "..." # let the model run commands to answer (agent + --run); asks before anything not read-only, -y skips that prinia -a "..." # agent: the model reads and searches files here (--write, --run to allow more) -prinia -c "..." # include earlier turns from this directory +prinia -c "..." # include earlier turns from this directory (recent, relevant, older questions) +prinia context ["question"] # show what -c would send prinia --no-cache "..." # ask again even if the call is in your history prinia --no-record "..." # don't save this call diff --git a/docs/agent.md b/docs/agent.md index fd5ca5a..a46cdea 100644 --- a/docs/agent.md +++ b/docs/agent.md @@ -16,7 +16,7 @@ agent = true # use agent mode for every call at a terminal run = true # and let it run commands (`write = true` for file edits) ``` -The model then decides per question whether to call a tool. The `agent` setting only applies when both stdin and stdout are terminals, so pipelines stay plain filters; `-a` forces it anywhere, `--no-agent` turns it off for one call. `--json` and `--check` never use it. `run` and `write` are the same permissions as the flags: no confirmation, so enable them only where you are comfortable with that. +The model then decides per question whether to call a tool. The `agent` setting only applies when both stdin and stdout are terminals, so pipelines stay plain filters; `-a` forces it anywhere, `--no-agent` turns it off for one call. `--json` and `--check` never use it. `run` and `write` are the same permissions as the flags: commands still ask first unless they are read-only, but file writes do not, so enable `write` only where changes can be reviewed. ## What it can do diff --git a/docs/configuration.md b/docs/configuration.md index 2663fb2..0139e2d 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -80,6 +80,8 @@ fast_model = "meta-llama/Llama-3.2-3B-Instruct-Turbo" | `base_url` | The API endpoint. Defaults to the official one for the type | | `api_key_env` | Environment variable holding the key. Defaults to `ANTHROPIC_API_KEY` / `OPENAI_API_KEY`. Not needed for a local endpoint | | `model`, `fast_model`, `deep_model` | Models for the three tiers | +| `tags` | Labels a project can ask for with the `tag` setting, e.g. `["private", "work"]` ([Tags and private mode](#tags-and-private-mode)) | +| `private` | `true` is shorthand for the tag `private` | Without `-p` or `provider`, prinia uses the first of `ANTHROPIC_API_KEY` and `OPENAI_API_KEY` that is set. @@ -98,6 +100,10 @@ API keys are read from the environment and are never written to the history or t | `cache` | `pipe` | When identical calls are answered from history: `pipe`, `always`, `off` | | `context` | `0` | Earlier turns from this directory sent with every call; `-c` uses it, or 5 when unset | | `context_chars` | `16000` | Size cap for that context (characters; oldest turns are dropped first) | +| `context_relevant` | `3` | Older turns matching the new question, sent in full (`0` = off; see [Context](usage.md#context)) | +| `context_older` | `30` | Further older turns sent as one line each (`0` = off) | +| `context_summary` | `false` | Add model-written summaries of older blocks of turns | +| `context_blocks` | `4` | How many of those summaries | | `cache_ttl` | `7d` | How long a history entry can answer a call (`12h`, `3d`, `2w`, `1m`) | | `max_size` | `500m` | Size limit for the history's stored content (`100k`, `500m`, `2g`); the oldest turns go first | | `max_age` | none | Also drop turns older than this (`90d`, `52w`) | @@ -106,6 +112,12 @@ API keys are read from the environment and are never written to the history or t | `history_scan` | `200` | Newest turns that `history agent` reads | | `ask_turns` | `15` | Best-matching turns `history ask` sends to the model | | `excerpt_prompt` / `excerpt_reply` | `200` / `400` (`history ask`: `400` / `1000`) | Characters of each prompt and answer sent for `history ask` and `history agent` | +| `max_input` | `0` (off) | Longer stdin is processed in parts and combined ([Long input](usage.md#long-input)) | +| `private` | `false` | Only use providers tagged `private` ([Tags and private mode](#tags-and-private-mode)) | +| `tag` | none | Only use a provider with this tag | +| `agent` | `false` | Agent mode for every call at a terminal ([Agent](agent.md)) | +| `run` / `write` | `false` | Let agent mode run commands / change files | +| `agent_steps` | `25` | Tool rounds before an agent session stops | | `check_retries` | `2` | Extra attempts when an answer fails `--json` or `--check` | | `keychain` | `false` | Keep the history key in the OS credential store instead of a file ([History](history.md#where-the-key-lives)) | | `prompt_pipe`, `prompt_interactive` | see below | The system prompts | @@ -130,3 +142,5 @@ prinia sends one of these as the system prompt, depending on whether input or ou | :--- | :--- | | `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` (or the variable named by `api_key_env`) | Provider credentials | | `PRINIA_CONFIG` | Path of the global config file | +| `PRINIA_WIDGET_KEY` | Keys for the zsh widget, space-separated (default `^g`); set before `eval "$(prinia shell zsh)"` | +| `PRINIA_OLLAMA_URL` | Where `prinia init` looks for Ollama (default `http://localhost:11434`) | diff --git a/docs/usage.md b/docs/usage.md index f3f8ee8..24dd5c0 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -145,9 +145,18 @@ Every successful call is saved to the [history](history.md) after its output has | `--check COMMAND` | Require the command to accept the answer on stdin; retry if not | | `--no-cache` | Skip the history cache | | `--record` / `--no-record` | Save or don't save this call | +| `-t`, `--template NAME` | Use a saved instruction ([Templates](#templates)) | +| `--each`, `-j N` | One call per stdin line, N at a time ([One call per line](#one-call-per-line)) | +| `--cmd` | Answer with one shell command (what the zsh widget uses) | +| `-a`, `--agent` / `-x`, `--do` | Agent mode / agent mode that may run commands ([Agent](agent.md)) | +| `--write`, `--run`, `-y`, `--no-agent` | Agent permissions, skip the command question, turn the `agent` setting off once | | Command | | | :--- | :--- | | `prinia config` | Show every setting and where its value comes from | +| `prinia init` | Find Ollama, pick a model for this machine, write the config | +| `prinia trust` | Review and trust this project's `.priniarc` ([Configuration](configuration.md)) | +| `prinia context [QUESTION]` | Show what `-c` would send; `--summarize` builds summaries now | +| `prinia shell zsh` | The zsh widget, for `eval` in `~/.zshrc` | | `prinia history` | Browse, `show`, `rm` ([History](history.md)) | | `prinia key` | `show`, `import`, `rotate` ([History](history.md#the-key)) | From c3e095454a59fd0d48c5952692c160d64cf765d3 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:48:56 +0200 Subject: [PATCH 26/31] test: close the store before deleting its folder (Windows) --- src/store.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/store.rs b/src/store.rs index 7ce526d..e27d954 100644 --- a/src/store.rs +++ b/src/store.rs @@ -521,6 +521,7 @@ mod tests { .optional() .unwrap(); assert!(pending.is_none(), "the rotation was finished"); + drop(s); // Windows will not delete a file that is still open std::fs::remove_dir_all(&d).unwrap(); } } From 3fed4dd877a8575cdeec1d89cde06ac85a0b95c6 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:52:03 +0200 Subject: [PATCH 27/31] test: keep SystemRoot and temp vars in the cleared test environment (Windows sockets) --- tests/cli.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/tests/cli.rs b/tests/cli.rs index ec7762a..dd351be 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -6,6 +6,15 @@ use std::process::{Command, Stdio}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; +/// Windows cannot open a socket without `SystemRoot` (os error 10106), so a cleared +/// environment keeps it, and the temp folders, wherever they exist. +fn windows_basics() -> Vec<(String, String)> { + ["SystemRoot", "TEMP", "TMP"] + .iter() + .filter_map(|k| std::env::var(k).ok().map(|v| (k.to_string(), v))) + .collect() +} + #[derive(Clone)] enum Step { Text(&'static str), @@ -193,6 +202,7 @@ impl Env { cmd.args(args) .current_dir(self.dir.join("work")) .env_clear() + .envs(windows_basics()) .env("PATH", std::env::var("PATH").unwrap_or_default()) .env("HOME", &self.dir) .env("PRINIA_CONFIG", self.dir.join("cfg/config.toml")) @@ -794,6 +804,7 @@ fn context_comes_from_history_of_this_directory() { .args(["-c", "seventh question"]) .current_dir(env.dir.join("work/other")) .env_clear() + .envs(windows_basics()) .env("HOME", &env.dir) .env("PRINIA_CONFIG", env.dir.join("cfg/config.toml")) .env("PRINIA_DB", env.db()) @@ -991,6 +1002,7 @@ fn stats_count_calls_hits_and_tokens_without_the_key() { .args(["stats", "--here", "--json"]) .current_dir(env.dir.join("work/elsewhere")) .env_clear() + .envs(windows_basics()) .env("HOME", &env.dir) .env("PRINIA_CONFIG", env.dir.join("cfg/config.toml")) .env("PRINIA_DB", env.db()) From 8379158eacfe668cca6b474748a76315466681ca Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:54:18 +0200 Subject: [PATCH 28/31] ci: Windows tests are a required check --- .github/workflows/ci.yml | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dbf5839..2106e22 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,13 +31,11 @@ jobs: - run: cargo clippy --locked --all-targets -- -D warnings - run: cargo test --locked - # Windows is not supported yet: this job shows whether it builds and which tests fail, - # without blocking a merge (it is not in required-checks-passed). + # Separate from the matrix: no fmt step (line endings), the rest as on Unix. test-windows: - name: Test (windows-latest, informational) + name: Test (windows-latest) runs-on: windows-latest timeout-minutes: 30 - continue-on-error: true steps: - uses: actions/checkout@v7 with: @@ -75,7 +73,7 @@ jobs: required-checks-passed: name: Required checks passed runs-on: ubuntu-latest - needs: [test, shell, zizmor, actionlint] + needs: [test, test-windows, shell, zizmor, actionlint] if: always() steps: - if: contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') From bb5874d190f7653ccfe454d0b2380ebe2c4ce6e6 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:54:34 +0200 Subject: [PATCH 29/31] docs: Windows status (CI only) --- README.md | 2 +- docs/install.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index beff772..2b05577 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,7 @@ More in [Usage](docs/usage.md) and [History](docs/history.md). prinia is beta software. -- macOS and Linux are tested. Windows is untested. +- macOS and Linux are tested. Windows builds and passes the tests in CI, but has not been used by hand. - Agent mode has run against a mock server and one OpenAI-compatible provider; the Anthropic tool-call format has not run against the real API yet. ## License diff --git a/docs/install.md b/docs/install.md index b41fe4a..75f285f 100644 --- a/docs/install.md +++ b/docs/install.md @@ -40,9 +40,9 @@ Building needs a Rust toolchain and a C compiler (SQLite and zstd are compiled f | :--- | :--- | :--- | | macOS, arm64 and x86-64 | yes | yes | | Linux, arm64 and x86-64 | yes (glibc 2.39 or newer: Ubuntu 24.04, Debian 13, Fedora 40) | yes | -| Windows | no | no | +| Windows | no | in CI only | -On older Linux systems, build from source. Windows has code paths (Credential Manager for the optional [credential store](history.md#where-the-key-lives)) that have never been built or run. +On older Linux systems, build from source. On Windows, build from source (`cargo install --path .`). It builds and passes the test suite in CI on every change, but nobody has used it by hand yet: the command approval prompt (`CONIN$` / `CONOUT$`) and the Credential Manager key store (`keychain = true`) have not run on a real Windows console. The command is `prinia`. If you want something shorter, alias it in your shell: `alias ai=prinia`. From 0ff07b25afd787032f728d955ccd11a3c18de0c6 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:57:18 +0200 Subject: [PATCH 30/31] feat: prinia update [--check] runs the release installer in place; refuses Homebrew, cargo and dev builds --- README.md | 1 + docs/install.md | 13 +++++ docs/usage.md | 1 + src/main.rs | 8 +++ src/update.rs | 129 ++++++++++++++++++++++++++++++++++++++++++++++++ tests/cli.rs | 97 ++++++++++++++++++++++++++++++++++++ 6 files changed, 249 insertions(+) create mode 100644 src/update.rs diff --git a/README.md b/README.md index 2b05577..db725f1 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,7 @@ prinia --no-cache "..." # ask again even if the call is in your his prinia --no-record "..." # don't save this call prinia init # pick a local model for this machine and write the config +prinia update [--check] # update prinia (curl-installed binaries; brew users: brew upgrade) prinia trust # allow this repo's .priniarc to turn on run/write/agent prinia history # browse everything you asked (fzf when available) prinia history search kestrel # find turns by words in prompt, input or answer diff --git a/docs/install.md b/docs/install.md index 75f285f..d32c91f 100644 --- a/docs/install.md +++ b/docs/install.md @@ -18,6 +18,19 @@ The script picks the release for your OS and architecture, verifies it against t | `PRINIA_INSTALL_DIR=/usr/local/bin` | Install somewhere else | | `PRINIA_DOWNLOAD_URL=...` | Download from a mirror | +## Updating + +```bash +prinia update --check # is a newer release out? +prinia update # install it in place +``` + +`prinia update` downloads the installer from the latest release and runs it into the folder the current binary lives in, so it does exactly what the install script does, including the checksum check; the installer is the only copy of that logic. Nothing is checked or downloaded unless you run the command. + +It refuses for a binary installed by Homebrew or cargo (use `brew upgrade prinia` or `cargo install`) and for a development build. It is not available on Windows. Running the install script again always works as well, for any version. + +Note that the checksum comes from the same release as the binary: it catches a corrupt download, not a compromised release. + ## Homebrew ```bash diff --git a/docs/usage.md b/docs/usage.md index 24dd5c0..fd730c8 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -154,6 +154,7 @@ Every successful call is saved to the [history](history.md) after its output has | Command | | | :--- | :--- | | `prinia config` | Show every setting and where its value comes from | +| `prinia update [--check]` | Update prinia to the latest release ([Install](install.md#updating)) | | `prinia init` | Find Ollama, pick a model for this machine, write the config | | `prinia trust` | Review and trust this project's `.priniarc` ([Configuration](configuration.md)) | | `prinia context [QUESTION]` | Show what `-c` would send; `--summarize` builds summaries now | diff --git a/src/main.rs b/src/main.rs index 66b9833..2a00688 100644 --- a/src/main.rs +++ b/src/main.rs @@ -22,6 +22,7 @@ mod retrieve; mod sh; mod stats; mod store; +mod update; const PROMPT_PIPE: &str = "You are a command-line tool in a UNIX pipeline. Output ONLY the raw text or data requested. No markdown, no code fences, no greetings, no commentary."; const PROMPT_INTERACTIVE: &str = "You are an inline terminal companion. Answer directly, no pleasantries. Keep it under 15 lines unless asked for more. Prefer commands, snippets and paths over background."; @@ -158,6 +159,12 @@ enum Cmd { #[arg(long)] summarize: bool, }, + /// Update prinia to the latest release (not for Homebrew or cargo installs) + Update { + /// Only say whether a newer release exists + #[arg(long)] + check: bool, + }, /// Find a local model server, pick a model for this machine and write the config Init, /// Print the shell integration to load: `eval "$(prinia shell zsh)"` @@ -281,6 +288,7 @@ fn run() -> Result<()> { } Ok(()) } + Some(Cmd::Update { check }) => update::run(*check), Some(Cmd::Init) => init::run(), Some(Cmd::Shell { .. }) => { print!("{}", include_str!("../scripts/prinia.zsh")); diff --git a/src/update.rs b/src/update.rs new file mode 100644 index 0000000..5bd7162 --- /dev/null +++ b/src/update.rs @@ -0,0 +1,129 @@ +//! `prinia update`: runs the release's own installer into the folder this binary lives in, so +//! the download and checksum code exists once (scripts/install.sh). `--check` only compares versions. +use anyhow::{Context, Result, anyhow, bail}; +use std::io::Write; +use std::process::{Command, Stdio}; +use std::time::Duration; + +const REPO: &str = "drumandbytes/prinia"; + +/// Paths of binaries that a package manager or a build tree owns: updating them here would fight it. +fn managed_by(path: &str) -> Option<&'static str> { + if path.contains("/Cellar/") || path.contains("/homebrew/") || path.contains("/linuxbrew/") { + Some("installed by Homebrew: run `brew upgrade prinia`") + } else if path.contains("/.cargo/") { + Some( + "installed by cargo: run `cargo install --locked --force prinia` (or from your checkout)", + ) + } else if path.contains("/target/debug/") || path.contains("/target/release/") { + Some("this is a development build; rebuild it with cargo") + } else { + None + } +} + +fn agent() -> ureq::Agent { + ureq::Agent::config_builder() + .timeout_global(Some(Duration::from_secs(30))) + .build() + .into() +} + +/// The newest release tag, e.g. `v0.2.0`. `PRINIA_RELEASES_API` replaces the GitHub API URL (tests, mirrors). +fn latest_tag() -> Result { + let url = std::env::var("PRINIA_RELEASES_API") + .unwrap_or_else(|_| format!("https://api.github.com/repos/{REPO}/releases/latest")); + let v: serde_json::Value = agent() + .get(&url) + .header("user-agent", "prinia") + .call() + .with_context(|| format!("cannot reach {url}"))? + .body_mut() + .read_json()?; + v["tag_name"] + .as_str() + .map(str::to_owned) + .ok_or_else(|| anyhow!("no release found at {url}")) +} + +fn parts(v: &str) -> Vec { + v.trim_start_matches('v') + .split(['.', '-', '+']) + .map_while(|p| p.parse().ok()) + .collect() +} + +pub fn run(check: bool) -> Result<()> { + if cfg!(windows) { + bail!("update is not supported on Windows yet; build from source"); + } + let exe = std::env::current_exe()?.canonicalize()?; + let current = env!("CARGO_PKG_VERSION"); + let latest = latest_tag()?; + use std::cmp::Ordering::*; + match parts(&latest).cmp(&parts(current)) { + Equal => { + println!("prinia {current} is the latest release"); + return Ok(()); + } + Less => { + println!("prinia {current} is newer than the latest release ({latest})"); + return Ok(()); + } + Greater => {} + } + if check { + println!("prinia {current} -> {latest} is available: run `prinia update`"); + return Ok(()); + } + if let Some(why) = managed_by(&exe.to_string_lossy()) { + bail!("{} is {why}", exe.display()); + } + let dir = exe + .parent() + .ok_or_else(|| anyhow!("no install directory"))?; + let base = std::env::var("PRINIA_DOWNLOAD_URL") + .unwrap_or_else(|_| format!("https://github.com/{REPO}/releases/latest/download")); + let script = agent() + .get(&format!("{base}/install.sh")) + .header("user-agent", "prinia") + .call() + .context("cannot download the installer")? + .body_mut() + .read_to_string()?; + println!("Updating {} from {current} to {latest}", exe.display()); + let mut child = Command::new("sh") + .arg("-s") + .env("PRINIA_INSTALL_DIR", dir) + .stdin(Stdio::piped()) + .spawn()?; + child + .stdin + .take() + .expect("piped") + .write_all(script.as_bytes())?; + if !child.wait()?.success() { + bail!("the installer failed; prinia was not changed"); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn versions_compare_by_number_not_text() { + assert!(parts("v0.10.0") > parts("0.9.9")); + assert_eq!(parts("v1.2.3"), parts("1.2.3")); + assert!(parts("v1.2.3-rc1") >= parts("1.2.3")); + } + + #[test] + fn package_managed_and_dev_builds_are_not_self_updated() { + assert!(managed_by("/opt/homebrew/Cellar/prinia/0.1.0/bin/prinia").is_some()); + assert!(managed_by("/home/u/.cargo/bin/prinia").is_some()); + assert!(managed_by("/home/u/prinia/target/debug/prinia").is_some()); + assert!(managed_by("/home/u/.local/bin/prinia").is_none()); + } +} diff --git a/tests/cli.rs b/tests/cli.rs index dd351be..0eb47d4 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -565,6 +565,103 @@ fn init_reports_when_there_is_no_model_server_and_writes_nothing() { ); } +/// A tiny release server: `/api` answers like GitHub's "latest release", `/install.sh` is the installer. +fn release_server(tag: &'static str, installer: &'static str) -> u16 { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let mut stream = stream.unwrap(); + let mut buf = [0u8; 2048]; + let n = stream.read(&mut buf).unwrap_or(0); + let req = String::from_utf8_lossy(&buf[..n]).to_string(); + let body = if req.starts_with("GET /api") { + format!("{{\"tag_name\":\"{tag}\"}}") + } else if req.starts_with("GET /install.sh") { + installer.to_string() + } else { + String::new() + }; + let _ = write!( + stream, + "HTTP/1.1 200 OK\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", + body.len() + ); + } + }); + port +} + +#[cfg(unix)] +#[test] +fn update_checks_versions_and_runs_the_installer_only_for_a_self_managed_binary() { + let mock = Mock::start("x", 200); + let env = Env::new("update", &mock); + let marker = env.dir.join("bin/marker"); + let port = release_server( + "v99.0.0", + "echo \"ran in $PRINIA_INSTALL_DIR\" > \"$PRINIA_INSTALL_DIR/marker\"\n", + ); + let api = format!("http://127.0.0.1:{port}/api"); + let base = format!("http://127.0.0.1:{port}"); + let env_vars = [ + ("PRINIA_RELEASES_API", api.as_str()), + ("PRINIA_DOWNLOAD_URL", base.as_str()), + ]; + + // --check only compares versions, from the real (development-build) path + let (out, err, code) = env.run(&["update", "--check"], "", &env_vars); + assert!( + code == 0 && out.contains("v99.0.0 is available"), + "{out} {err}" + ); + // a development build is not self-updated + let (_, err, code) = env.run(&["update"], "", &env_vars); + assert!(code != 0 && err.contains("development build"), "{err}"); + + // a copy outside any package manager or build tree is updated in place by the installer + std::fs::create_dir_all(env.dir.join("bin")).unwrap(); + let copy = env.dir.join("bin/prinia"); + std::fs::copy(env!("CARGO_BIN_EXE_prinia"), ©).unwrap(); + let run_copy = |extra: &[(&str, &str)]| { + Command::new(©) + .args(["update"]) + .env_clear() + .envs(windows_basics()) + .env("PATH", std::env::var("PATH").unwrap_or_default()) + .envs(extra.iter().copied()) + .output() + .unwrap() + }; + let out = run_copy(&env_vars); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let ran = std::fs::read_to_string(&marker).unwrap(); + assert!(ran.contains("bin"), "{ran}"); + + // when the installer fails, the user is told nothing changed + let bad_port = release_server("v99.0.0", "exit 3\n"); + let bad_base = format!("http://127.0.0.1:{bad_port}"); + let bad_api = format!("http://127.0.0.1:{bad_port}/api"); + let out = run_copy(&[ + ("PRINIA_RELEASES_API", &bad_api), + ("PRINIA_DOWNLOAD_URL", &bad_base), + ]); + assert!(!out.status.success()); + assert!(String::from_utf8_lossy(&out.stderr).contains("prinia was not changed")); + + // already current: nothing to do + let same = release_server(concat!("v", env!("CARGO_PKG_VERSION")), "exit 9\n"); + let same_api = format!("http://127.0.0.1:{same}/api"); + let out = run_copy(&[("PRINIA_RELEASES_API", &same_api)]); + assert!( + out.status.success() && String::from_utf8_lossy(&out.stdout).contains("latest release") + ); +} + #[test] fn many_first_calls_at_once_share_one_key() { let mock = Mock::start("answer", 200); From 5cf3146dadb0acce684e778a2cee8788787e9bb5 Mon Sep 17 00:00:00 2001 From: Maris Popens Date: Tue, 24 Nov 2026 20:59:27 +0200 Subject: [PATCH 31/31] test: release_server helper only builds where its test does (Windows dead-code lint) --- tests/cli.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/cli.rs b/tests/cli.rs index 0eb47d4..adf6917 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -565,6 +565,7 @@ fn init_reports_when_there_is_no_model_server_and_writes_nothing() { ); } +#[cfg(unix)] /// A tiny release server: `/api` answers like GitHub's "latest release", `/install.sh` is the installer. fn release_server(tag: &'static str, installer: &'static str) -> u16 { let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();