diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1970874..2106e22 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,6 +31,19 @@ jobs: - run: cargo clippy --locked --all-targets -- -D warnings - run: cargo test --locked + # Separate from the matrix: no fmt step (line endings), the rest as on Unix. + test-windows: + name: Test (windows-latest) + runs-on: windows-latest + timeout-minutes: 30 + 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 @@ -60,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') diff --git a/README.md b/README.md index bec7d7a..db725f1 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,18 @@ 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 +prinia init +``` + +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. ## Usage @@ -44,11 +56,19 @@ 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); 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 +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 prinia history ask "what did I ask about TLS?" # a fast model answers from your history @@ -76,7 +96,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/agent.md b/docs/agent.md index 1de3c07..a46cdea 100644 --- a/docs/agent.md +++ b/docs/agent.md @@ -4,21 +4,31 @@ 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: 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 | 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 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`, `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 9f9b272..0139e2d 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. 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 provider = "anthropic" @@ -14,9 +16,43 @@ 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 `.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 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 + +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" +tags = ["private"] + +[providers.corp] # a company key covered by an NDA +type = "anthropic" +api_key_env = "CORP_ANTHROPIC_KEY" +tags = ["private", "work"] +``` + +```toml +# .priniarc +tag = "work" # use a provider tagged "work" (your default if it has the tag, else the first by name) +``` + +- `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 use a local model says `provider = "local"`. +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 @@ -44,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. @@ -62,13 +100,24 @@ 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`) | | `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` | +| `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 | @@ -93,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/history.md b/docs/history.md index f6b20cf..85ed68b 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. 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/install.md b/docs/install.md index b41fe4a..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 @@ -40,9 +53,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`. diff --git a/docs/usage.md b/docs/usage.md index 8350f02..fd730c8 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -55,10 +55,60 @@ 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`. 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. + +`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. +## 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 +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: + +```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 +eval "$(prinia shell zsh)" # add to ~/.zshrc +``` + +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 Models sometimes return something a script cannot use. Two flags make a call refuse bad answers: @@ -95,9 +145,19 @@ 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 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 | +| `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)) | diff --git a/scripts/prinia.zsh b/scripts/prinia.zsh new file mode 100644 index 0000000..010689c --- /dev/null +++ b/scripts/prinia.zsh @@ -0,0 +1,22 @@ +# 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 +# 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 diff --git a/src/agent.rs b/src/agent.rs index 07ee59c..b1ac194 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; @@ -77,6 +79,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:?}"))?; @@ -107,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 @@ -159,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(); @@ -180,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!( @@ -222,17 +244,75 @@ fn replace(root: &Path, a: &Value) -> Result { } } -fn run_command(root: &Path, a: &Value) -> Result { - let cmd = arg(a, "command")?; - let mut c = if cfg!(windows) { - let mut c = Command::new("cmd"); - c.args(["/C", &format!("({cmd}) 2>&1")]); - c +/// 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", "du", "df", + "which", "whoami", "uname", "file", "stat", "tree", "find", "basename", "dirname", + "uptime", + ]; + 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; + }; + // flags that write a file or run a program + let bad_flag = w.iter().any(|a| { + matches!( + *a, + "-exec" | "-execdir" | "-ok" | "-okdir" | "-delete" | "-o" | "-fls" + ) || a.starts_with("-fprint") + || a.starts_with("--output") + || a.starts_with("--pre") + || a.starts_with("--compress-program") + || a.starts_with("--hostname-bin") + }); + OK.contains(&first) && !bad_flag + }) +} + +/// 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}; + // the console device: one file on Unix, separate input and output handles on Windows + let (input, output) = if cfg!(windows) { + ("CONIN$", "CONOUT$") } else { - let mut c = Command::new("sh"); - c.args(["-c", &format!("({cmd}) 2>&1")]); - c + ("/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!(out, "[prinia] run `{cmd}`? [y/N] "); + let _ = out.flush(); + let mut line = String::new(); + let _ = std::io::BufReader::new(inp).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 = crate::sh::command(&format!("({cmd}) 2>&1")); + #[cfg(unix)] + std::os::unix::process::CommandExt::process_group(&mut c, 0); let mut child = c .current_dir(root) .stdin(Stdio::null()) @@ -250,6 +330,17 @@ fn run_command(root: &Path, a: &Value) -> Result { break Some(s); } if started.elapsed() > Duration::from_secs(60) { + // 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; @@ -265,7 +356,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), @@ -273,7 +364,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}")) @@ -311,14 +402,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; @@ -338,7 +426,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 { @@ -361,4 +449,72 @@ mod tests { assert!(resolve(&root, "/etc/passwd").is_err()); assert!(resolve(&root, ".").is_ok()); } + + #[test] + fn only_read_only_pipelines_skip_the_prompt() { + for ok in [ + "ls -la", + "find . -name '*.rs' | wc -l", + "cat a | sort | 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", + "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}"); + } + } + + #[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); + } + + #[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/config.rs b/src/config.rs index e1c1961..1b09b23 100644 --- a/src/config.rs +++ b/src/config.rs @@ -26,13 +26,24 @@ pub const KEYS: &[(&str, Ty)] = &[ ("cache_ttl", Ty::Str), ("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), ("max_age", Ty::Str), ("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), + ("write", Ty::Bool), + ("run", Ty::Bool), + ("max_input", Ty::Num), + ("private", Ty::Bool), + ("tag", Ty::Str), ("agent_steps", Ty::Num), ("check_retries", Ty::Num), ("keychain", Ty::Bool), @@ -40,8 +51,116 @@ pub const KEYS: &[(&str, Ty)] = &[ ("prompt_interactive", Ty::Str), ]; +/// 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", + "context_older", + "context_relevant", + "context_summary", + "context_blocks", + "max_tokens", + "effort", + "fast_effort", + "deep_effort", + "fast_under", + "deep_over", + "check_retries", + "max_input", + "private", + "tag", + "agent", + "agent_steps", + "run", + "write", + "prompt_pipe", + "prompt_interactive", +]; + +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))) +} + +/// 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(()); + }; + let mut known = fs::read_to_string(&tp).unwrap_or_default(); + 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) +} + +#[derive(Clone, Copy, PartialEq)] +enum Layer { + Project, + Env, + 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 { - table: Table, + /// `.priniarc` files, nearest last. + project: Table, + global: Table, providers: Table, pub files: Vec, } @@ -85,13 +204,14 @@ 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); let mut cfg = Config { - table: Table::new(), + project: Table::new(), + global: Table::new(), providers: Table::new(), files: Vec::new(), }; @@ -99,6 +219,8 @@ impl Config { let Ok(text) = fs::read_to_string(&p) else { continue; }; + let global = Some(&p) == global.as_ref(); + let trusted = global || is_trusted(&text); let t = match toml::from_str::(&text) { Ok(t) => t, Err(e) => { @@ -107,9 +229,35 @@ impl Config { } }; for (k, v) in t { + 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) { + 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" { + if !global { + eprintln!( + "[prinia] {}: providers are device-level; define them in your global config", + p.display() + ); + continue; + } match v { Value::Table(ps) => cfg .providers @@ -131,7 +279,11 @@ impl Config { p.display() ), Some(_) => { - cfg.table.insert(k, v); + if global { + cfg.global.insert(k, v); + } else { + cfg.project.insert(k, v); + } } } } @@ -140,33 +292,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.]`. @@ -178,17 +335,36 @@ impl Config { .map(str::to_owned) } + /// `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> { self.providers.keys().collect() } /// 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"), } } @@ -205,13 +381,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" ); @@ -227,4 +407,43 @@ 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, "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_FAST_UNDER", "3"); + std::env::set_var("PRINIA_CACHE_TTL", "2d"); + } + let c = Config::load_from(Some(global), &root); + 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_FAST_UNDER"); + std::env::remove_var("PRINIA_CACHE_TTL"); + } + 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/context.rs b/src/context.rs index 6437f82..610b32d 100644 --- a/src/context.rs +++ b/src/context.rs @@ -1,8 +1,39 @@ -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::retrieve::{keywords, rank}; +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 = 300; + +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, + /// 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>, +} + +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 +43,175 @@ 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 { + 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(); + 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() || (p.relevant > 0 && !p.query.is_empty()) { + LIST_LIMIT + } else { + p.verbatim + p.older + }; + 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; - 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()..]; + + // 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 { + 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"), + )); + } + } + 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.reverse(); + out.extend(related); + out.extend(recent); Ok(out) } diff --git a/src/curate.rs b/src/curate.rs index b190ecb..db74c66 100644 --- a/src/curate.rs +++ b/src/curate.rs @@ -3,18 +3,17 @@ 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; -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); @@ -36,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 { @@ -55,24 +49,126 @@ 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"); } Ok(turns) } -/// Answer a question about the history, using the fast tier. +/// 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) + } +} + +/// 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 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"); + } + let kws = keywords(question); + let k = cfg.num("ask_turns").unwrap_or(15) as usize; + 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(), + 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(()) } @@ -81,6 +177,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() @@ -98,7 +197,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() { @@ -144,6 +250,22 @@ 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()); } + + #[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)); + } } diff --git a/src/init.rs b/src/init.rs new file mode 100644 index 0000000..e158b1c --- /dev/null +++ b/src/init.rs @@ -0,0 +1,173 @@ +//! `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"; + +/// `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 { + 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!("{}/api/tags", ollama())) + .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(()) +} + +/// 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(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 {} 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(()); + }; + 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}{}.", + deep.map(|d| format!(" (deep: {d})")).unwrap_or_default() + ); + pull(model, size)?; + if let Some(d) = deep { + pull(d, 20)?; + } + let cfg = config_text(&ollama(), model, deep); + 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 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")); + 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/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() diff --git a/src/main.rs b/src/main.rs index e55942a..2a00688 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}; @@ -14,11 +14,15 @@ mod config; mod context; mod curate; mod history; +mod init; mod key; mod keychain; mod provider; +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."; @@ -61,14 +65,42 @@ 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, + /// With --run / -x: run every command without asking (read-only ones never ask) + #[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, + + /// 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, + + /// 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, @@ -119,6 +151,33 @@ enum Cmd { #[arg(long)] format: Option, }, + /// 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, + }, + /// 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)"` + Shell { + #[arg(value_parser = ["zsh"])] + shell: String, + }, + /// 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)] @@ -192,6 +251,69 @@ fn run() -> Result<()> { let keychain = cfg.bool("keychain").unwrap_or(false); match &cli.command { Some(Cmd::Config) => show_config(&cfg), + 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)?; + 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: 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, + visible: &|t| provider.may_see(&cfg, &t.provider), + 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::Update { check }) => update::run(*check), + Some(Cmd::Init) => init::run(), + Some(Cmd::Shell { .. }) => { + print!("{}", include_str!("../scripts/prinia.zsh")); + Ok(()) + } + Some(Cmd::Trust { yes }) => { + let files = config::project_files(&std::env::current_dir()?); + if files.is_empty() { + bail!("no .priniarc here or above"); + } + 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), Some(Cmd::Stats { here, @@ -232,47 +354,216 @@ 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), } } -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 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() { + "--each" => {} + "-j" | "--jobs" => { + raw.next(); + } + _ if a.starts_with("--jobs=") => {} + _ => args.push(a), + } + } + 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..jobs.min(inputs.len()) { + s.spawn(|| { + loop { + let i = next.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let Some(input) = inputs.get(i) else { return }; + let r = std::process::Command::new(&exe) + .args(args) + // 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()) + .spawn() + .and_then(|mut c| { + let _ = c.stdin.take().map(|mut p| p.write_all(input.as_bytes())); + c.wait_with_output() + }); + let r = 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] = r; + let n = done.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1; + 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, (text, ok)) in fan_out(&child_args(), &lines, cli.jobs as usize) + .into_iter() + .enumerate() + { + 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(()) +} + +/// 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(()) +} + +/// 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)?; } - 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\""); } + Ok((instruction, payload)) +} - // Raw output whenever either end is a pipe. - let piped = !stdin_tty || !stdout_tty; - let mode = if cli.agent { - "agent" +fn system_prompt(cli: &Cli, cfg: &Config, piped: bool) -> String { + let system = if cli.cmd { + cmd_prompt() } else if piped { - "pipe" - } else { - "interactive" - }; - let system = if piped { cfg.str("prompt_pipe").unwrap_or_else(|| PROMPT_PIPE.into()) } else { cfg.str("prompt_interactive") .unwrap_or_else(|| PROMPT_INTERACTIVE.into()) }; - - let validate = cli.json || cli.check.is_some(); - 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 { @@ -290,9 +581,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 user = combine(&instruction, &payload); + let summary_model = provider + .model(cfg, Tier::Fast) + .unwrap_or_else(|_| model.clone()); let record = if cli.record { true @@ -306,18 +762,11 @@ 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); - 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 { @@ -326,9 +775,20 @@ 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, + 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, + blocks: cfg.num("context_blocks").unwrap_or(4) as usize, + }), + }, )?, _ => Vec::new(), }; @@ -343,6 +803,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(); @@ -359,66 +820,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 cli.agent { - agent::run( - &agent::Opts { - cfg, - provider: &provider, - model: &model, - effort: effort.as_deref(), - max_tokens, - user: &user, - write: cli.write, - run: cli.run, - }, - &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 { @@ -430,43 +845,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(()) } @@ -479,6 +879,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("```")) @@ -491,6 +915,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") @@ -561,7 +989,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(); @@ -581,6 +1009,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"); diff --git a/src/provider.rs b/src/provider.rs index 27126d8..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, @@ -104,11 +120,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,6 +183,12 @@ impl Provider { if api_key.is_none() && official { bail!("provider `{name}` needs an API key in ${key_env}"); } + if !tagged(&name) { + bail!( + "provider `{name}` lacks the required tag(s) {}; pick one that has them (-p NAME) or change the `tag` / `private` setting", + need.join(", ") + ); + } Ok(Provider { name, kind, @@ -157,6 +197,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) { @@ -210,6 +256,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(); @@ -256,11 +305,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; } @@ -276,6 +329,10 @@ impl Provider { reply.text.push_str(&t); } } + // 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 .pending .drain(..) 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/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/src/store.rs b/src/store.rs index 41929de..e27d954 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)?) @@ -160,6 +183,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})"); @@ -191,24 +216,28 @@ 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};" ))?; - 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()?; @@ -221,32 +250,49 @@ 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)) => { + 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`" + ), + (None, _) => bail!("the history has no data key"), }; Ok(Store { conn, data_key }) } /// 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). @@ -261,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. @@ -389,8 +436,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])?; @@ -399,3 +470,58 @@ 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"); + drop(s); // Windows will not delete a file that is still open + std::fs::remove_dir_all(&d).unwrap(); + } +} 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 bc873a6..adf6917 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -6,11 +6,24 @@ 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), /// 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 +107,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 +130,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" } ) }; @@ -183,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")) @@ -301,6 +321,454 @@ 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 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("lacks the required tag"), + "{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 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 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 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 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 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}" + ); +} + +#[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(); + 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); + 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); + 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); @@ -417,9 +885,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"), "", @@ -433,6 +902,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()) @@ -630,6 +1100,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()) @@ -766,10 +1237,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]