Compare commits
107
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b972c12559 | ||
|
|
f8cab9b439 | ||
|
|
45333db5c2 | ||
|
|
7748b953f0 | ||
|
|
720591d24a | ||
|
|
dbb0c51b7e | ||
|
|
71cd50fe4d | ||
|
|
b5863dded0 | ||
|
|
03116d2f42 | ||
|
|
9b23247815 | ||
|
|
3493b01e9a | ||
|
|
fd989c44d0 | ||
|
|
e7307da6a9 | ||
|
|
b6721d6a15 | ||
|
|
9e72a52b1c | ||
|
|
30c1637dff | ||
|
|
6b5535956d | ||
|
|
fdfe4ba023 | ||
|
|
8f02bf1c33 | ||
|
|
80b082423c | ||
|
|
4324d551d6 | ||
|
|
1136b1385b | ||
|
|
84b90bfe26 | ||
|
|
53ccbda97c | ||
|
|
2d1bf372d8 | ||
|
|
4987d850f9 | ||
|
|
9541a094d8 | ||
|
|
89df8ec1ca | ||
|
|
bca85a4017 | ||
|
|
0e5d85f2ff | ||
|
|
0a806da8d2 | ||
|
|
2790a823b0 | ||
|
|
88acf2362f | ||
|
|
bfcc762ec9 | ||
|
|
b21699b749 | ||
|
|
5f23e2403f | ||
|
|
2af6fe64d4 | ||
|
|
da640f3dcd | ||
|
|
79ec2d87c7 | ||
|
|
faf9dd581f | ||
|
|
873deef7c7 | ||
|
|
f518c8a6fc | ||
|
|
aea5f3d615 | ||
|
|
bda37d9f38 | ||
|
|
96e5390621 | ||
|
|
b43acac8ee | ||
|
|
03687c8981 | ||
|
|
95dd31e24b | ||
|
|
e1b5562888 | ||
|
|
fba040c668 | ||
|
|
f61a8f7afd | ||
|
|
91328ca7e1 | ||
|
|
125360033d | ||
|
|
4323d4823c | ||
|
|
5478c5a239 | ||
|
|
e94bd450cd | ||
|
|
e8ddb61518 | ||
|
|
f39381aa9d | ||
|
|
e8b55bba15 | ||
|
|
9863c7a5f3 | ||
|
|
f44722df04
|
||
|
|
3eaae0e652 | ||
|
|
b12829db39 | ||
|
|
dffaf6b9db | ||
|
|
a9a4ccca88 | ||
|
|
7cb7d66575 | ||
|
|
400b50fbd0 | ||
|
|
7eeff2a226 | ||
|
|
374e8c0bf7
|
||
|
|
ede87df960
|
||
|
|
95a8c3df44
|
||
|
|
f57bd21ee4 | ||
|
|
e1b6e3f8c6 | ||
|
|
644d899f78 | ||
|
|
2596194417 | ||
|
|
684f19250a | ||
|
|
f3d59ade11 | ||
|
|
e1604c58ea | ||
|
|
dcacb3a962 | ||
|
|
d791098e51 | ||
|
|
d31110cd67
|
||
|
|
0f35e03a85
|
||
|
|
c2b0c120d7
|
||
|
|
65c9be36b2
|
||
|
|
2658ca776e
|
||
|
|
f8682102a0
|
||
|
|
3fa0f5c428
|
||
|
|
68135b97d1
|
||
|
|
b87a3460c4 | ||
|
|
cb23da6490
|
||
|
|
2a40a5a81d | ||
|
|
ebba976a27 | ||
|
|
c84f9522e9 | ||
|
|
81ed769f8a | ||
|
|
6f7defe25f | ||
|
|
b837f82d7e | ||
|
|
54685be9a2 | ||
|
|
4dd6e794b2 | ||
|
|
af9622d31c | ||
|
|
6f586bd535 | ||
|
|
78740db170 | ||
|
|
64d594f4ee | ||
|
|
1322d73c7b | ||
|
|
de91ffa517 | ||
|
|
74bc613d94 | ||
|
|
6d0a5550fe | ||
|
|
7b1c0342b4 |
@@ -5,3 +5,7 @@
|
||||
.idea/
|
||||
/coyote.iml
|
||||
/.idea/
|
||||
.coyote/**
|
||||
.sisyphus/**
|
||||
.coyote-project.json
|
||||
.coyote/memory/
|
||||
|
||||
+11
@@ -1,5 +1,16 @@
|
||||
# Credits
|
||||
|
||||
## Matt Pocock's Skills
|
||||
|
||||
The bundled `diagnosing-bugs`, `codebase-design`, and `grilling` skills, the
|
||||
`architecture-reviewer` agent, and the code smell baseline in the bundled
|
||||
`code-review` skill are adapted from
|
||||
[mattpocock/skills](https://github.com/mattpocock/skills) by Matt Pocock,
|
||||
licensed under the MIT License. The smell definitions trace back to Martin
|
||||
Fowler's *Refactoring* (ch. 3); the deep-module vocabulary builds on John
|
||||
Ousterhout's *A Philosophy of Software Design* and Michael Feathers'
|
||||
*Working Effectively with Legacy Code*.
|
||||
|
||||
## AIChat
|
||||
Coyote originally started as a fork of the fantastic
|
||||
[AIChat CLI](https://github.com/sigoden/aichat). The initial goal was simply
|
||||
|
||||
Generated
+43
-8
@@ -1962,6 +1962,16 @@ dependencies = [
|
||||
"darling_macro 0.23.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling"
|
||||
version = "0.24.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "88490bf1b990d87eaaa7ac8aa887f629a08e7359765b4911faf63c3763347d23"
|
||||
dependencies = [
|
||||
"darling_core 0.24.0",
|
||||
"darling_macro 0.24.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_core"
|
||||
version = "0.20.11"
|
||||
@@ -1989,6 +1999,19 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_core"
|
||||
version = "0.24.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "084e274f91c482280130e1e34e0b8d6e66776a060d7b6de7b84289ca778868c4"
|
||||
dependencies = [
|
||||
"ident_case",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"strsim",
|
||||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_macro"
|
||||
version = "0.20.11"
|
||||
@@ -2011,6 +2034,17 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "darling_macro"
|
||||
version = "0.24.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "68f5792fa0d41cd2325ce0ffa64f0a340eaebd4971a3a0c5e1ffd2cc488a355e"
|
||||
dependencies = [
|
||||
"darling_core 0.24.0",
|
||||
"quote",
|
||||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "defmt"
|
||||
version = "1.1.1"
|
||||
@@ -5303,12 +5337,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rmcp"
|
||||
version = "1.8.0"
|
||||
version = "3.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d1f571c72940a19d9532fe52dbea8bc9912bf1d766c2970bb824056b86f3f59"
|
||||
checksum = "c8dddc5b1924b9a59fba420166160ca2c4663a4e01803e52eda33070f56d63c8"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
"base64 0.23.1",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"futures",
|
||||
"http 1.5.0",
|
||||
@@ -5326,19 +5360,20 @@ dependencies = [
|
||||
"tokio-stream",
|
||||
"tokio-util",
|
||||
"tracing",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rmcp-macros"
|
||||
version = "1.8.0"
|
||||
version = "3.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1aad0035b69380782d78ea95b508327e6deaa2235909053e596eea8f27b5e1d5"
|
||||
checksum = "6898e24cd16342b59bfa8a53c2c04b9cf62fc8a2cfea57b9c038b09984bfc521"
|
||||
dependencies = [
|
||||
"darling 0.23.0",
|
||||
"darling 0.24.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"serde_json",
|
||||
"syn 2.0.119",
|
||||
"syn 3.0.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
+1
-1
@@ -84,7 +84,7 @@ duct = "1.0.0"
|
||||
argc = "1.23.0"
|
||||
strum_macros = "0.27.2"
|
||||
indoc = "2.0.6"
|
||||
rmcp = { version = "1.5.0", features = [
|
||||
rmcp = { version = "3.1.2", features = [
|
||||
"client",
|
||||
"transport-child-process",
|
||||
"transport-streamable-http-client-reqwest",
|
||||
|
||||
+15
@@ -36,6 +36,21 @@ RUN set -euo pipefail; \
|
||||
install -m 0755 "$TMPDIR/usql_static" /usr/local/bin/usql; \
|
||||
rm -rf "$TMPDIR"
|
||||
|
||||
RUN set -euo pipefail; \
|
||||
DUCKDB_VERSION=1.5.5; \
|
||||
case "${TARGETARCH}" in \
|
||||
amd64) DUCKDB_ARCH=amd64 ;; \
|
||||
arm64) DUCKDB_ARCH=arm64 ;; \
|
||||
*) echo "Unsupported TARGETARCH: ${TARGETARCH}" >&2; exit 1 ;; \
|
||||
esac; \
|
||||
TMPDIR=$(mktemp -d); \
|
||||
curl -fsSL --retry 3 \
|
||||
"https://github.com/duckdb/duckdb/releases/download/v${DUCKDB_VERSION}/duckdb_cli-linux-${DUCKDB_ARCH}.gz" \
|
||||
-o "$TMPDIR/duckdb.gz"; \
|
||||
gunzip "$TMPDIR/duckdb.gz"; \
|
||||
install -m 0755 "$TMPDIR/duckdb" /usr/local/bin/duckdb; \
|
||||
rm -rf "$TMPDIR"
|
||||
|
||||
USER 1000
|
||||
|
||||
RUN curl -LsSf https://astral.sh/uv/install.sh | sh && \
|
||||
|
||||
@@ -23,7 +23,7 @@ Coming from [AIChat](https://github.com/sigoden/aichat)? Follow the [migration g
|
||||
* [AIChat Migration Guide](https://github.com/Dark-Alex-17/coyote/wiki/AIChat-Migration): Coming from AIChat? Follow the migration guide to get started.
|
||||
* [Installation](#install): Install Coyote
|
||||
* [Getting Started](#getting-started): Get started with Coyote by doing first-run setup steps.
|
||||
* [Sharing Configurations](https://github.com/Dark-Alex-17/coyote/wiki/Sharing-Configurations): Install bundles of agents, roles, macros, tools, and MCP servers from any git repo, and share your own.
|
||||
* [Sharing Configurations](https://github.com/Dark-Alex-17/coyote/wiki/Sharing-Configurations): Install bundles of agents, roles, skills, macros, tools, and MCP servers from any git repo, and share your own. Bundles are Coyote's equivalent of plugins in other CLI agents.
|
||||
* [REPL](https://github.com/Dark-Alex-17/coyote/wiki/REPL): Interactive Read-Eval-Print Loop for conversational interactions with LLMs and Coyote.
|
||||
* [Custom REPL Prompt](https://github.com/Dark-Alex-17/coyote/wiki/REPL-Prompt): Customize the REPL prompt to provide useful contextual information.
|
||||
* [Vault](https://github.com/Dark-Alex-17/coyote/wiki/Vault): Securely store and manage sensitive information such as API keys and credentials.
|
||||
@@ -36,7 +36,11 @@ Coming from [AIChat](https://github.com/sigoden/aichat)? Follow the [migration g
|
||||
* [Create Custom Bash Tools](https://github.com/Dark-Alex-17/coyote/wiki/Custom-Bash-Tools)
|
||||
* [Bash Prompt Utilities](https://github.com/Dark-Alex-17/coyote/wiki/Bash-Prompt-Helpers)
|
||||
* [First-Class MCP Server Support](https://github.com/Dark-Alex-17/coyote/wiki/MCP-Servers): Easily connect and interact with MCP servers for advanced functionality.
|
||||
* [Macros](https://github.com/Dark-Alex-17/coyote/wiki/Macros): Automate repetitive tasks and workflows with Coyote "scripts" (macros).
|
||||
* [Macros](https://github.com/Dark-Alex-17/coyote/wiki/Macros): Automate repetitive tasks and workflows with Coyote "scripts" (macros). Macros are Coyote's custom commands: invoke any macro directly by name (e.g. `.review main`), with tab-completion, right alongside the built-in REPL commands.
|
||||
* Give a macro a `description` (shown in `.list macros` and completions) and set `isolated: false` to run its steps on the live session, exactly as if you typed them. Note that non-isolated steps are recorded in the session, and mutating steps (`.role`, `.model`, ...) persist after the macro ends — by design. Steps are fail-fast: an error aborts the remaining steps, but completed steps' effects remain. A non-isolated macro step cannot invoke another macro, and a `.exit` step never exits the REPL.
|
||||
* Commit project-specific macros to `.coyote/macros/` in your repo — they shadow same-named global macros (opt out with `--no-workspace-macros`).
|
||||
* Pass variables positionally or by name: leading `name=value` args set declared variables directly (letting earlier variables keep their defaults), and remaining args fill the rest in order. Tab completion after a macro name lists each variable with its description and default.
|
||||
* Scope which macros are invocable with `enabled_macros` in the global config, a role, an agent, or a session (most specific wins; an empty list disables all macros), and toggle at runtime with `.macro enable|disable <name>`.
|
||||
* [RAG](https://github.com/Dark-Alex-17/coyote/wiki/RAG): Retrieval-Augmented Generation for enhanced information retrieval and generation.
|
||||
* [Sessions](https://github.com/Dark-Alex-17/coyote/wiki/Sessions): Manage and persist conversational contexts and settings across multiple interactions.
|
||||
* [Memory](https://github.com/Dark-Alex-17/coyote/wiki/Memory): Persistent file-based memory that survives across sessions. Bootstrap with `coyote --init-memory [global|workspace]`.
|
||||
@@ -70,6 +74,8 @@ Coyote requires the following tools to be installed on your system:
|
||||
* **Cargo:** `cargo install ast-grep --locked`
|
||||
* **npm:** `npm i -g @ast-grep/cli`
|
||||
* Optional: if `ast-grep` is not installed, the `ast_grep` tool reports it and agents fall back to `fs_grep`
|
||||
* [duckdb](https://duckdb.org/) (for fast, local RAGs)
|
||||
* `curl https://install.duckdb.org | sh`
|
||||
|
||||
These tools are used to provide various functionalities within Coyote, such as document processing, JSON manipulation,
|
||||
etc., and they are used within agents and tools.
|
||||
|
||||
@@ -5,7 +5,7 @@ description: |
|
||||
spawns one Sisyphus per task on a single run branch, verifies each with an adversarial
|
||||
plan-conformance check, and finishes with ONE draft PR (CI checks watched to green) plus tracked
|
||||
follow-up tasks. Task state lives on disk in a plans directory, so runs survive context compression.
|
||||
version: 2.0.0
|
||||
version: 2.1.0
|
||||
agent_session: temp
|
||||
auto_continue: true
|
||||
max_auto_continues: 100
|
||||
@@ -27,6 +27,7 @@ summarization_threshold: 100000
|
||||
skills_enabled: true
|
||||
enabled_skills:
|
||||
- design-session
|
||||
- grilling
|
||||
- task-tracking
|
||||
- plan-authoring
|
||||
- delegation-protocol
|
||||
@@ -126,7 +127,10 @@ instructions: |
|
||||
|
||||
### Phase B — Design decomposition
|
||||
|
||||
Load and follow the `design-session` skill against the design doc. This produces
|
||||
Load and follow the `design-session` skill against the design doc. When running
|
||||
interactively, also load `grilling` and put the open design decisions to the user as
|
||||
frontier rounds (numbered questions, each with a recommended answer) instead of ad-hoc
|
||||
one-at-a-time questions. This produces
|
||||
`{{plans_dir}}/PLAN-<slug>.md` with Problem, Scope, Approach, Alternatives, Constraints/risks,
|
||||
Open questions, and a **Task breakdown** where **each task is sized to ~1 engineer-day** (decompose
|
||||
anything bigger NOW).
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
# Architecture Reviewer
|
||||
|
||||
An **on-demand architecture improvement scout**. It scans a codebase for **deepening
|
||||
opportunities** — refactors that turn shallow modules into deep ones — presents them as a visual
|
||||
report, then refines the candidate you pick into a concrete, implementation-ready interface
|
||||
proposal.
|
||||
|
||||
Two things it is deliberately **not**:
|
||||
|
||||
1. **Not a completion gate.** The review stack ([`code-reviewer`](../code-reviewer/README.md),
|
||||
[`adversary`](../adversary/README.md), [`security-reviewer`](../security-reviewer/README.md))
|
||||
judges *changes* before a task finishes. This agent is invoked on demand, when you want the
|
||||
codebase itself made deeper, more testable, and easier to navigate. A "cleanup gate" would
|
||||
produce noisy, opinionated churn on every diff; a cleanup *tool* produces focused proposals
|
||||
when you ask for them.
|
||||
2. **Not an implementer.** It proposes; you (or a `coder` you delegate to) implement. Its only
|
||||
write is the report file in the OS temp directory — repository files are never touched.
|
||||
|
||||
## How it works
|
||||
|
||||
Driven by the [`codebase-design`](../../skills/codebase-design/SKILL.md) skill — the shared
|
||||
deep-module vocabulary (**module**, **interface**, **depth**, **seam**, **adapter**, **leverage**,
|
||||
**locality**) and its principles (the deletion test, "the interface is the test surface", "one
|
||||
adapter = hypothetical seam, two = real").
|
||||
|
||||
1. **Scope by git history (YAGNI).** Deepening pays off where code keeps changing, so hot spots
|
||||
from the commit log rank first — unless you name a direction.
|
||||
2. **Explore for friction.** Fans out `explore` agents hunting shallow modules, leaked seams,
|
||||
concept-bouncing, and code that's hard to test through its current interface; every suspect
|
||||
gets the deletion test.
|
||||
3. **Report candidates.** 3-6 cards (problem / solution / leverage-and-locality benefits /
|
||||
before-after visual / `Strong`-`Worth exploring`-`Speculative` badge), as a self-contained
|
||||
Tailwind+Mermaid HTML file in your temp dir (default) or inline markdown
|
||||
(`report_format: markdown`). Ends with a top recommendation, then stops and asks which
|
||||
candidate to pursue.
|
||||
4. **Refine via design-it-twice.** For the chosen candidate: frame the constraints and dependency
|
||||
categories, produce 2-3 radically different interface designs (optionally spawning `oracle`
|
||||
for an independent alternative), compare on depth/locality/seam placement, and hand off ONE
|
||||
opinionated, implementation-ready proposal including the testing strategy ("replace, don't
|
||||
layer").
|
||||
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
# Scan the current repo, HTML report
|
||||
coyote -a architecture-reviewer "Find deepening opportunities"
|
||||
|
||||
# Aim it at a pain point, inline report
|
||||
coyote -a architecture-reviewer --agent-variable report_format markdown \
|
||||
"The billing/entitlements code is painful to test - what should be deepened?"
|
||||
```
|
||||
|
||||
Also spawnable from `sisyphus` when a request is explicitly architecture-scale ("improve the
|
||||
architecture of X", "make this module easier to test").
|
||||
|
||||
## Related
|
||||
|
||||
- [`codebase-design`](../../skills/codebase-design/SKILL.md) — the vocabulary and principles it runs on.
|
||||
- [`oracle`](../oracle/README.md) — advisory design review; also loads `codebase-design` for the shared vocabulary.
|
||||
- [`explore`](../explore/README.md) — the codebase walkers it fans out.
|
||||
|
||||
## Credits
|
||||
|
||||
Adapted from the `codebase-design` and `improve-codebase-architecture` skills in
|
||||
[mattpocock/skills](https://github.com/mattpocock/skills) (MIT), which build on ideas from John
|
||||
Ousterhout's *A Philosophy of Software Design* and Michael Feathers' *Working Effectively with
|
||||
Legacy Code*.
|
||||
@@ -0,0 +1,158 @@
|
||||
name: architecture-reviewer
|
||||
description: On-demand architecture improvement scout - scans a codebase for deepening opportunities (shallow modules, leaked seams, missing locality) weighted by git-history hot spots, presents candidates as a visual report, then refines the chosen candidate into a concrete interface proposal via design-it-twice. Proposes, never implements. NOT a completion gate - invoke it when you want the codebase made deeper, more testable, and easier to navigate.
|
||||
version: 1.1.0
|
||||
|
||||
agent_session: temp
|
||||
auto_continue: true
|
||||
max_auto_continues: 20
|
||||
inject_todo_instructions: true
|
||||
|
||||
can_spawn_agents: true
|
||||
spawnable_agents:
|
||||
- explore
|
||||
- oracle
|
||||
max_concurrent_agents: 4
|
||||
max_agent_depth: 2
|
||||
inject_spawn_instructions: true
|
||||
|
||||
skills_enabled: true
|
||||
enabled_skills:
|
||||
- codebase-design
|
||||
- delegation-protocol
|
||||
- grilling
|
||||
- parallel-research
|
||||
|
||||
variables:
|
||||
- name: project_dir
|
||||
description: Project directory to scan
|
||||
default: '.'
|
||||
- name: report_format
|
||||
description: Candidate report format - 'html' (self-contained file in the OS temp dir, opened for the user) or 'markdown' (inline in chat)
|
||||
default: html
|
||||
- name: auto_confirm
|
||||
description: Auto-confirm command execution
|
||||
default: '1'
|
||||
|
||||
global_tools:
|
||||
- ast_grep.sh
|
||||
- fs_read.sh
|
||||
- fs_cat.sh
|
||||
- fs_grep.sh
|
||||
- fs_glob.sh
|
||||
- fs_ls.sh
|
||||
- fs_write.sh
|
||||
- execute_command.sh
|
||||
|
||||
instructions: |
|
||||
You are an architecture improvement scout. You surface **deepening opportunities** — refactors
|
||||
that turn shallow modules into deep ones — and refine the one the user picks into a concrete
|
||||
interface proposal. The aim is testability, locality, and AI-navigability.
|
||||
|
||||
Two things you are NOT:
|
||||
1. **Not a completion gate.** The review stack (`code-reviewer`/`adversary`/`security-reviewer`)
|
||||
judges changes; you are invoked on demand to improve what already exists.
|
||||
2. **Not an implementer.** You produce candidates and interface proposals; the user (or a coder
|
||||
they delegate to) owns the code change. You never modify repository files — your only writes
|
||||
are the report file in the OS temp directory.
|
||||
|
||||
## Step 0: Load the skill
|
||||
|
||||
Before anything else, `skill__load` `codebase-design`. It is your source of truth for the
|
||||
vocabulary (**module**, **interface**, **depth**, **seam**, **adapter**, **leverage**,
|
||||
**locality**), the principles (the deletion test, "the interface is the test surface", "one
|
||||
adapter = hypothetical seam, two = real"), the dependency categories for safe deepening, and the
|
||||
design-it-twice pattern. Use those terms EXACTLY in every finding — no "component", "service",
|
||||
or "boundary". Load `delegation-protocol` and `parallel-research` before spawning sub-agents.
|
||||
|
||||
## Phase 1: Scope, then explore
|
||||
|
||||
**Scope before you scan — YAGNI.** Deepening pays off where code keeps changing:
|
||||
|
||||
- If the user named a direction (a module, subsystem, or pain point), take it and skip inference.
|
||||
- Otherwise mine the history for hot spots:
|
||||
`execute_command --command "git -C {{project_dir}} log --oneline --name-only -100"` (or
|
||||
similar) and let the files that keep recurring pull your attention. Scattered changes with no
|
||||
hot spot → widen the net.
|
||||
|
||||
Read the workspace instructions (`COYOTE.md`/`AGENTS.md`) if present — documented conventions and
|
||||
recorded decisions are constraints, not candidates; don't re-litigate them.
|
||||
|
||||
Then spawn 1-3 `explore` agents (per `delegation-protocol`, in parallel per `parallel-research`)
|
||||
to walk the scoped area. Brief them to report friction, not metrics:
|
||||
|
||||
- Where does understanding one concept require bouncing between many small modules?
|
||||
- Where are modules shallow — an interface nearly as complex as the implementation?
|
||||
- Where were pure functions extracted "for testability" while the real bugs hide in how they're
|
||||
called (no locality)?
|
||||
- Where do tightly-coupled modules leak across their seams?
|
||||
- What is untested, or hard to test through its current interface?
|
||||
|
||||
Apply the **deletion test** yourself to every suspect the explorers return: would deleting it
|
||||
concentrate complexity (real candidate) or just move it (pass-through)?
|
||||
|
||||
## Phase 2: Present candidates
|
||||
|
||||
Produce 3-6 candidates, each with:
|
||||
|
||||
- **Files**: the modules involved
|
||||
- **Problem**: the friction the current shape causes, in skill vocabulary
|
||||
- **Solution**: plain-English description of the deepening (no interface design yet)
|
||||
- **Benefits**: stated as leverage and locality gains, and how tests improve
|
||||
- **Recommendation strength**: `Strong` / `Worth exploring` / `Speculative`
|
||||
- **Before/after sketch**: for `html`, a visual per candidate; for `markdown`, a compact
|
||||
ASCII/mermaid sketch
|
||||
|
||||
**Report delivery** (per `report_format`, currently: {{report_format}}):
|
||||
|
||||
- `html` — write ONE self-contained file to the OS temp dir (`$TMPDIR`, falling back to `/tmp`)
|
||||
named `architecture-review-<timestamp>.html`. Use Tailwind via CDN for layout and Mermaid via
|
||||
CDN for graph-shaped structure (call graphs, dependencies); hand-built divs/SVG for editorial
|
||||
visuals (mass diagrams, collapse animations). One card per candidate with a side-by-side
|
||||
before/after diagram. Open it for the user (`open` on macOS, `xdg-open` on Linux, `start` on
|
||||
Windows) and print the absolute path. Nothing lands in the repo.
|
||||
- `markdown` — render the same cards inline in your response.
|
||||
|
||||
End the report with a **Top recommendation**: which candidate you'd tackle first and why.
|
||||
|
||||
Then STOP and ask which candidate to explore. Do NOT propose interfaces yet.
|
||||
|
||||
## Phase 3: Refine the chosen candidate
|
||||
|
||||
1. **Frame the problem space**: the constraints any new interface must satisfy, the dependencies
|
||||
and their category (in-process / local-substitutable / remote-but-owned / true external, per
|
||||
the skill), and a rough illustrative sketch to make the constraints concrete. Show the user.
|
||||
When the candidate carries open decisions (what sits behind the seam, which callers to
|
||||
optimise for, what tests must survive), load `grilling` and walk them as frontier rounds —
|
||||
recommended answer per question, facts fetched by you, decisions made by the user.
|
||||
2. **Design it twice**: produce 2-3 radically different interface designs per the skill's
|
||||
pattern (different constraint each: minimal interface / maximal flexibility / optimise the
|
||||
common caller). For a candidate worth the budget, spawn `oracle` to independently design or
|
||||
critique one alternative. Each design: interface (with invariants, ordering, error modes),
|
||||
caller example, what hides behind the seam, adapter strategy, trade-offs.
|
||||
3. **Compare and recommend**: contrast on depth, locality, and seam placement; give ONE
|
||||
opinionated recommendation or a justified hybrid.
|
||||
4. **Hand off**: summarize the chosen design as an implementation-ready proposal — files to
|
||||
change, the target interface, the testing strategy ("replace, don't layer": new tests at the
|
||||
deepened interface, old shallow-module tests deleted). Note that implementation belongs to
|
||||
the caller, not you.
|
||||
|
||||
## Rules
|
||||
|
||||
1. **Never modify repository files.** The temp-dir report is your only write.
|
||||
2. **Skill vocabulary, exactly.** Findings that say "service" or "boundary" get rewritten.
|
||||
3. **Friction over dogma.** A shallow module that never changes and confuses no one is not a
|
||||
candidate. Recent-change hot spots rank first.
|
||||
4. **Candidates are judgment calls.** Frame every problem as observed friction with evidence
|
||||
(file:line, test absence, change-history churn), not as rule violations.
|
||||
5. **Respect recorded decisions.** If a candidate contradicts a documented convention or
|
||||
decision, surface it only when the friction justifies revisiting — and mark the conflict
|
||||
clearly in the card.
|
||||
|
||||
## Context
|
||||
- Project: {{project_dir}}
|
||||
- Report format: {{report_format}}
|
||||
- CWD: {{__cwd__}}
|
||||
- Shell: {{__shell__}}
|
||||
|
||||
## Available Tools
|
||||
{{__tools__}}
|
||||
@@ -12,6 +12,31 @@ agents while handling coordination and final reporting.
|
||||
- 🔄 **Cross-File Context**: Broadcasts sibling rosters so reviewers can alert each other about cross-cutting changes.
|
||||
- 📊 **Unified Reporting**: Synthesizes findings into a structured, easy-to-read summary with severity levels.
|
||||
- ⚡ **Parallel Execution**: Runs reviews concurrently for maximum speed.
|
||||
- 🚨 **Operational History (optional)**: Checks the change against past production incidents via the [`incident-prior-art`](../../skills/incident-prior-art/SKILL.md) skill.
|
||||
|
||||
## Operational History Lane
|
||||
|
||||
Code review answers "is this code good?" — this lane answers "did we already get burned by this?"
|
||||
When the diff touches operationally-relevant surface (error handling, retries, timeouts, alerting,
|
||||
config controlling any of these), the orchestrator:
|
||||
|
||||
1. **Git archaeology** (always available): blames the lines the diff deletes or weakens. A guard
|
||||
that originated in an incident-fix commit and is being removed is a 🔴 CRITICAL finding — the
|
||||
change reintroduces a known production failure mode.
|
||||
2. **Prior-art delegation** (opt-in): if the `prior_art_agent` variable names an agent that can
|
||||
search your incident record (Slack, Jira, postmortems, handoff docs), it is spawned in REVIEW
|
||||
MODE with symptom-vocabulary search keys extracted from the diff (error strings, metric/alert
|
||||
names, config keys — the vocabulary operators actually use).
|
||||
|
||||
The lane is disabled by default (`prior_art_agent: ''`) and findings fold into the standard
|
||||
severity taxonomy under an "Operational history" report section — no separate verdict. Wire it up
|
||||
in a bundle or your local config:
|
||||
|
||||
```yaml
|
||||
variables:
|
||||
- name: prior_art_agent
|
||||
default: 'oncall-historian' # any spawnable agent that can search your incident record
|
||||
```
|
||||
|
||||
## Pro-Tip: Use an IDE MCP Server for Improved Performance
|
||||
Many modern IDEs now include MCP servers that let LLMs perform operations within the IDE itself and use IDE tools. Using
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
name: code-reviewer
|
||||
description: CodeRabbit-style code reviewer - spawns per-file reviewers, synthesizes findings
|
||||
version: 2.0.0
|
||||
version: 2.2.0
|
||||
|
||||
auto_continue: true
|
||||
max_auto_continues: 20
|
||||
@@ -14,11 +14,15 @@ skills_enabled: true
|
||||
enabled_skills:
|
||||
- delegation-protocol
|
||||
- parallel-research
|
||||
- incident-prior-art
|
||||
|
||||
variables:
|
||||
- name: project_dir
|
||||
description: Project directory to review
|
||||
default: '.'
|
||||
- name: prior_art_agent
|
||||
description: Optional agent that can search the incident record (Slack/Jira/postmortems) for operational prior art. Empty disables the delegation lane; git archaeology still runs.
|
||||
default: ''
|
||||
- name: auto_confirm
|
||||
description: Auto-confirm command execution
|
||||
default: '1'
|
||||
@@ -46,11 +50,12 @@ instructions: |
|
||||
|
||||
1. **Get the diff:** Run `get_diff` to get the git diff (defaults to staged changes, falls back to unstaged)
|
||||
2. **Parse changed files:** Extract the list of files from the diff
|
||||
3. **Create todos:** One todo per phase (get diff, spawn reviewers, collect results, synthesize report)
|
||||
3. **Create todos:** One todo per phase (get diff, spawn reviewers, operational-history lane, collect results, synthesize report)
|
||||
4. **Spawn file-reviewers:** One `file-reviewer` agent per changed file, in parallel. Apply the `delegation-protocol` structured prompt format.
|
||||
5. **Broadcast sibling roster:** Send each file-reviewer a message with all sibling IDs and their file assignments
|
||||
6. **Collect all results:** Per `parallel-research`, do not poll. End your response after spawns + roster; the system will notify you when agents complete.
|
||||
7. **Synthesize:** Combine all findings into a CodeRabbit-style report
|
||||
6. **Operational-history lane (conditional):** Load `incident-prior-art` and follow it. If the diff touches operationally-relevant surface (per the skill's trigger list), run its git-archaeology pass yourself, and — if `prior_art_agent` is set (currently: '{{prior_art_agent}}') — spawn that agent in REVIEW MODE alongside the file-reviewers using the skill's prompt template. If the surface is not operationally relevant, skip with a one-line note.
|
||||
7. **Collect all results:** Per `parallel-research`, do not poll. End your response after spawns + roster; the system will notify you when agents complete.
|
||||
8. **Synthesize:** Combine all findings into a CodeRabbit-style report. Prior-art findings go under an "Operational history" section using the skill's severity folding (reintroduction of a past incident's failure mode = CRITICAL).
|
||||
|
||||
## Spawning File Reviewers
|
||||
|
||||
@@ -70,7 +75,8 @@ instructions: |
|
||||
|
||||
## MUST DO
|
||||
- Load `code-review` and `ai-slop-remover` skills before reading any code
|
||||
- Apply both skill checklists to the diff
|
||||
- Load `transactional-integrity` as well if this file's diff touches state-changing code (DB writes, transactions, queue/webhook/job handlers, retries, external side effects)
|
||||
- Apply all loaded skill checklists to the diff
|
||||
- Use targeted fs_read with offset/limit; max 5 file reads
|
||||
- End with REVIEW_COMPLETE
|
||||
|
||||
@@ -138,6 +144,9 @@ instructions: |
|
||||
## Cross-File Concerns
|
||||
<any cross-cutting issues identified by the teammate pattern>
|
||||
|
||||
## Operational history
|
||||
<only when the lane ran: archaeology + prior-art findings with incident/commit references, or "no relevant incident history found">
|
||||
|
||||
---
|
||||
*Reviewed N files, found X critical, Y warnings, Z suggestions, W nitpicks*
|
||||
```
|
||||
|
||||
@@ -15,6 +15,8 @@ skills_enabled: true
|
||||
enabled_skills:
|
||||
- ai-slop-remover
|
||||
- code-review
|
||||
- comment-discipline
|
||||
- diagnosing-bugs
|
||||
- git-master
|
||||
- frontend-ui-ux
|
||||
- verification-gates
|
||||
@@ -31,7 +33,7 @@ settings:
|
||||
max_loop_iterations: 20
|
||||
log_state_snapshots: true
|
||||
validate_before_run: true
|
||||
timeout: 1800
|
||||
timeout: 14400
|
||||
|
||||
initial_state:
|
||||
project_dir: ''
|
||||
@@ -90,6 +92,7 @@ nodes:
|
||||
Project directory: {{project_dir}}
|
||||
prompt: '{{initial_prompt}}'
|
||||
tools: []
|
||||
timeout: 300
|
||||
output_schema:
|
||||
type: object
|
||||
properties:
|
||||
@@ -166,6 +169,8 @@ nodes:
|
||||
enabled_skills:
|
||||
- ai-slop-remover
|
||||
- code-review
|
||||
- comment-discipline
|
||||
- diagnosing-bugs
|
||||
- git-master
|
||||
- frontend-ui-ux
|
||||
- verification-gates
|
||||
@@ -176,9 +181,10 @@ nodes:
|
||||
## Skills
|
||||
|
||||
Use `skill__list` to see what's available, then `skill__load` the ones
|
||||
that fit the work: `ai-slop-remover` always, `frontend-ui-ux` when
|
||||
touching UI, `git-master` when touching history, `verification-gates`
|
||||
to remember what evidence is required. Unload when a phase ends.
|
||||
that fit the work: `ai-slop-remover` and `comment-discipline` always,
|
||||
`frontend-ui-ux` when touching UI, `git-master` when touching history,
|
||||
`verification-gates` to remember what evidence is required. Unload when
|
||||
a phase ends.
|
||||
|
||||
## Writing code
|
||||
|
||||
@@ -211,7 +217,11 @@ nodes:
|
||||
Before writing ANY file:
|
||||
1. Find a similar existing file (grep, then read).
|
||||
2. Match its style: imports, naming, structure, error handling.
|
||||
3. Follow the same patterns exactly. Do not invent new ones.
|
||||
3. While reading it, note the repo's comment register per
|
||||
`comment-discipline` (self-documenting / api-documented /
|
||||
comment-heavy) and write comments to match. When the signal is
|
||||
weak, write NO comment.
|
||||
4. Follow the same patterns exactly. Do not invent new ones.
|
||||
|
||||
## Fix loop
|
||||
|
||||
@@ -219,6 +229,11 @@ nodes:
|
||||
the previous attempt failed verification. Read the error, identify
|
||||
the minimal fix, apply it. Do not refactor while fixing.
|
||||
|
||||
If the fix is not obvious from the error, or a previous fix attempt
|
||||
for the SAME failure did not stick, `skill__load` `diagnosing-bugs`
|
||||
and follow it: build a red-capable reproduction loop before forming
|
||||
any hypothesis. Do not spend a second attempt on a blind retry.
|
||||
|
||||
## Rules
|
||||
|
||||
1. Match existing patterns - read examples first.
|
||||
@@ -254,6 +269,7 @@ nodes:
|
||||
- fs_patch
|
||||
- execute_command
|
||||
max_iterations: 100
|
||||
timeout: 1800
|
||||
state_updates:
|
||||
last_node_output: '{{output}}'
|
||||
fallback: end_failure
|
||||
@@ -327,6 +343,7 @@ nodes:
|
||||
- fs_ls
|
||||
- execute_command
|
||||
max_iterations: 15
|
||||
timeout: 600
|
||||
output_schema:
|
||||
type: object
|
||||
properties:
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
name: file-reviewer
|
||||
description: Reviews a single file's diff for bugs, style issues, and cross-cutting concerns
|
||||
version: 2.0.0
|
||||
version: 2.1.0
|
||||
|
||||
skills_enabled: true
|
||||
enabled_skills:
|
||||
- code-review
|
||||
- ai-slop-remover
|
||||
- transactional-integrity
|
||||
|
||||
variables:
|
||||
- name: project_dir
|
||||
@@ -29,7 +30,9 @@ instructions: |
|
||||
|
||||
Before reading any code, call `skill__load` for `code-review` and `ai-slop-remover`. They carry your detailed review methodology — the categories to check (correctness, tests, clarity, coupling, footguns), the investigation workflow (how to use the fs tools to build context before reviewing), the slop checklist (useless comments, dishonest naming, defensive handling of impossible cases), and the standard for when to flag vs. skip.
|
||||
|
||||
Apply BOTH checklists in every review. Skill bodies are your source of truth for what to flag; this agent's instructions handle workflow and output shape.
|
||||
Additionally load `transactional-integrity` when the diff touches state-changing code — database writes, transaction blocks, queue/webhook/job handlers, retry logic, or calls to external state-holding systems. It carries the atomicity/race/idempotency/dual-write checklist that generic correctness review misses. Skip it for pure reads, UI, and stateless computation.
|
||||
|
||||
Apply every loaded checklist in every review. Skill bodies are your source of truth for what to flag; this agent's instructions handle workflow and output shape.
|
||||
|
||||
## Your Mission
|
||||
|
||||
|
||||
@@ -14,6 +14,9 @@ variables:
|
||||
- name: project_dir
|
||||
description: Absolute path to the project the plan targets - the ground truth for pointer verification
|
||||
default: '.'
|
||||
- name: auto_confirm
|
||||
description: Auto-confirm command execution
|
||||
default: '1'
|
||||
|
||||
global_tools:
|
||||
- ast_grep.sh
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
name: oracle
|
||||
description: High-IQ advisor for architecture, debugging, and complex decisions. Blocking by design - the orchestrator is waiting on you.
|
||||
version: 2.1.0
|
||||
version: 2.2.0
|
||||
|
||||
skills_enabled: true
|
||||
enabled_skills:
|
||||
- code-review
|
||||
- ai-slop-remover
|
||||
- codebase-design
|
||||
- plan-review
|
||||
- plan-authoring
|
||||
- iwe-knowledge-base
|
||||
@@ -61,6 +62,7 @@ instructions: |
|
||||
|
||||
- `skill__load code-review` — when reviewing a diff or existing code; gives you a focused review checklist.
|
||||
- `skill__load ai-slop-remover` — when judging code quality (especially for advising on cleanups).
|
||||
- `skill__load codebase-design` — when advising on module/interface design, seam placement, testability, or refactoring structure; gives you the deep-module vocabulary (module, interface, depth, seam, adapter, leverage, locality) and its principles. Use those terms exactly.
|
||||
- `skill__load plan-review` — when asked to review an implementation plan; adversarial checklist plus the PLAN_REVIEW verdict format. Load `plan-authoring` alongside it — it defines the plan schema you are checking against.
|
||||
- `skill__load iwe-knowledge-base` — when the plans live in a large markdown corpus; navigate it structurally instead of globbing.
|
||||
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
# Security Reviewer
|
||||
|
||||
A **security analyst** for code changes. Where [`code-reviewer`](../code-reviewer/README.md) asks
|
||||
*"is this code good?"* and [`adversary`](../adversary/README.md) asks *"is this the code the plan
|
||||
asked for?"*, `security-reviewer` asks the third orthogonal question:
|
||||
|
||||
> **"Can this code be abused?"**
|
||||
|
||||
It traces untrusted data from sources (CLI args, HTTP input, file contents, LLM outputs) to
|
||||
dangerous sinks (shell, SQL, file paths, deserializers, network) and hunts the classic classes:
|
||||
injection, committed secrets, missing authn/authz, path traversal, SSRF, unsafe deserialization,
|
||||
supply-chain hazards, weak crypto, and sensitive-data exposure.
|
||||
|
||||
## Why it's a third reviewer
|
||||
|
||||
| | `code-reviewer` | `adversary` | `security-reviewer` |
|
||||
|---|---|---|---|
|
||||
| Question | Is the code correct/clean? | Does the code match the plan? | Can the code be abused? |
|
||||
| Unit of analysis | per-file diffs (fan-out) | criteria ↔ diff mapping | **data flows across files** |
|
||||
| Blind spot it covers | slop, bugs, coupling | skipped criteria, scope drift | source→sink paths, secrets, authz gaps |
|
||||
| Output | severity-tagged findings | `CONFORMS` / `DIVERGES` | `PASS` / `FAIL` (posture-gated) |
|
||||
|
||||
Security flaws live in the path between an input in one file and a sink in another —
|
||||
exactly what a per-file review fans out past, and what acceptance criteria almost never mention.
|
||||
|
||||
## Posture-gated blocking
|
||||
|
||||
Not every project needs production strictness — a POC shouldn't be blocked on missing rate
|
||||
limiting. The `security_posture` variable (or an explicit posture in the spawn prompt) sets the
|
||||
blocking threshold:
|
||||
|
||||
| Posture | Blocks (FAIL) | Intended for |
|
||||
|---|---|---|
|
||||
| `prototype` | 🔴 Critical only | POCs, spikes, demos, localhost-only tools |
|
||||
| `standard` (default) | 🔴 Critical + 🟠 High | Anything deployed, shared, or built upon |
|
||||
| `hardened` | 🔴 + 🟠 + 🟡 Medium | Auth, payments, secrets handling, public-facing, multi-tenant |
|
||||
|
||||
Two invariants that do not bend with posture:
|
||||
|
||||
1. **Critical always blocks.** A committed secret is Critical in a prototype too — git history
|
||||
outlives the prototype. Same for code that endangers the host machine or third-party systems.
|
||||
2. **Posture gates the verdict, not the report.** Non-blocking findings are still listed; the
|
||||
posture only decides PASS/FAIL.
|
||||
|
||||
Severity itself is calibrated by **reachability × blast radius**, not vulnerability class: SQL
|
||||
injection in a localhost-only debug script is not High, and a "small" secret in a repo is Critical.
|
||||
|
||||
## Verdict (blocking on FAIL)
|
||||
|
||||
The agent ends every review with one sentinel:
|
||||
|
||||
```
|
||||
SECURITY_REVIEW: PASS
|
||||
Posture: standard. Findings: 0 critical, 0 high, 2 medium, 1 low (none at or above the blocking threshold).
|
||||
```
|
||||
|
||||
```
|
||||
SECURITY_REVIEW: FAIL
|
||||
Posture: standard. Findings: 0 critical, 1 high, 1 medium, 0 low.
|
||||
Blocking findings:
|
||||
1. 🟠 Path traversal — export.rs:88 — 'name' from the HTTP body is joined into the output path with no canonicalization; '../../.ssh/authorized_keys' escapes the export root — canonicalize and verify the prefix before writing
|
||||
Non-blocking findings:
|
||||
1. 🟡 Sensitive data in logs — auth.rs:41 — bearer token logged at debug level — redact before logging
|
||||
```
|
||||
|
||||
A `FAIL` verdict **blocks** completion, exactly like adversary's `DIVERGES`. The caller
|
||||
(sisyphus/architect) resumes the SAME coder session with the blocking findings pasted verbatim,
|
||||
then re-runs `security-reviewer` ONCE to confirm the fix.
|
||||
|
||||
Every finding cites `file:line` and articulates the concrete attack path. Vague findings are not
|
||||
emitted.
|
||||
|
||||
## How it reviews
|
||||
|
||||
Driven by the [`security-review`](../../skills/security-review/SKILL.md) skill:
|
||||
|
||||
1. **Source→sink tracing** per hunk: where does untrusted data enter, what does it reach, and is
|
||||
the mediation between them real (read the sanitizer, don't trust its name)?
|
||||
2. **Ground-truth with read-only tools** (`fs_grep`/`fs_read`/`ast_grep`): confirm the vulnerable
|
||||
path is reachable, confirm callers can deliver untrusted data, compare sibling code for the
|
||||
security controls the new code should have mirrored.
|
||||
3. **Posture gating**: severities assigned by exploitability, verdict decided by the threshold.
|
||||
|
||||
It is **read-only** — it produces a verdict, never a fix.
|
||||
|
||||
## Usage
|
||||
|
||||
Typically spawned by `sisyphus` alongside `code-reviewer`/`adversary`. The spawn prompt IS its
|
||||
entire context, so include the diff (or a base ref), the posture, and any deployment context:
|
||||
|
||||
```sh
|
||||
agent__spawn --agent security-reviewer --prompt "
|
||||
## TASK
|
||||
Security-review the recent changes. Return PASS/FAIL.
|
||||
|
||||
## POSTURE
|
||||
standard # or: prototype (this is a throwaway POC) / hardened (this touches auth)
|
||||
|
||||
## DIFF
|
||||
Run get_diff (or --base main), or: <paste diff>
|
||||
|
||||
## DEPLOYMENT CONTEXT
|
||||
<what this code is for, who can reach it, whether it will be deployed/shared>
|
||||
"
|
||||
```
|
||||
|
||||
Direct invocation for ad-hoc use:
|
||||
|
||||
```sh
|
||||
coyote -a security-reviewer --agent-variable security_posture prototype \
|
||||
--agent-variable project_dir /path/to/repo \
|
||||
"Review the staged changes. This is a localhost-only spike."
|
||||
```
|
||||
|
||||
### Tools
|
||||
|
||||
- `get_diff [--base <ref>]` — staged → unstaged → `HEAD~1` fallback (or an explicit base/PR branch).
|
||||
- `get_changed_files [--base <ref>]` — quick map of the attack surface.
|
||||
- Plus read-only `fs_*` and `ast_grep` for ground-truth checks.
|
||||
|
||||
## Related
|
||||
|
||||
- [`security-review`](../../skills/security-review/SKILL.md) — the methodology it runs on.
|
||||
- [`code-reviewer`](../code-reviewer/README.md) — the quality reviewer it runs alongside.
|
||||
- [`adversary`](../adversary/README.md) — the plan-conformance reviewer it runs alongside.
|
||||
@@ -0,0 +1,121 @@
|
||||
name: security-reviewer
|
||||
description: Security analyst - hunts exploitable flaws in a code change (injection, secrets, authz gaps, SSRF, supply chain) by tracing untrusted data to dangerous sinks. Returns a posture-gated PASS/FAIL verdict so POCs aren't held to production strictness. Complements code-reviewer (quality) and adversary (plan conformance). Designed to be delegated to by sisyphus.
|
||||
version: 1.0.0
|
||||
|
||||
auto_continue: true
|
||||
max_auto_continues: 15
|
||||
inject_todo_instructions: true
|
||||
|
||||
skills_enabled: true
|
||||
enabled_skills:
|
||||
- security-review
|
||||
|
||||
variables:
|
||||
- name: project_dir
|
||||
description: Project directory containing the changes under review
|
||||
default: '.'
|
||||
- name: security_posture
|
||||
description: Blocking threshold - prototype (Critical only), standard (Critical+High), hardened (Critical+High+Medium)
|
||||
default: standard
|
||||
- name: auto_confirm
|
||||
description: Auto-confirm command execution
|
||||
default: '1'
|
||||
|
||||
global_tools:
|
||||
- ast_grep.sh
|
||||
- fs_read.sh
|
||||
- fs_cat.sh
|
||||
- fs_grep.sh
|
||||
- fs_glob.sh
|
||||
- fs_ls.sh
|
||||
- execute_command.sh
|
||||
|
||||
instructions: |
|
||||
You are a security reviewer. You answer ONE question: **can this code be abused?** You are NOT
|
||||
the code-quality reviewer (that is `code-reviewer`/`file-reviewer`) and NOT the plan-conformance
|
||||
reviewer (that is `adversary`). You hunt exploitable flaws in the CHANGE: injection, committed
|
||||
secrets, missing auth, path traversal, SSRF, unsafe deserialization, supply-chain hazards.
|
||||
|
||||
Your value is attacker mindset applied to fresh code with zero stake in the implementation. The
|
||||
implementer thought about the happy path; you think about the input that lies.
|
||||
|
||||
## Step 0: Load the skill
|
||||
|
||||
Before anything else, `skill__load` `security-review`. It carries your methodology: the
|
||||
source-to-sink tracing discipline, the severity model (calibrated by reachability and blast
|
||||
radius, not vulnerability class), the posture gating table, the hunt checklist, and the exact
|
||||
verdict format. The skill body is your source of truth for HOW to review and WHAT blocks; these
|
||||
instructions handle workflow and I/O.
|
||||
|
||||
## Input (the spawn prompt IS your entire context)
|
||||
|
||||
You are given:
|
||||
1. **The diff** — pasted inline, or run `get_diff` (optionally `--base <ref>`) if told to fetch it.
|
||||
2. **The security posture** — `prototype`, `standard`, or `hardened`. The `security_posture`
|
||||
variable (currently: {{security_posture}}) is the default; an explicit posture in the spawn
|
||||
prompt overrides it. If neither is given, use `standard` and say so in the report.
|
||||
3. **Deployment context** (optional but valuable) — what the code is for, who can reach it,
|
||||
whether it will be deployed/shared. Use it to calibrate severity; never to skip the review.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Load `security-review`.
|
||||
2. Get the diff (inline or via `get_diff`) and identify the changed files.
|
||||
3. For EACH hunk: identify untrusted-data sources, dangerous sinks, and the mediation (or lack of
|
||||
it) between them. Apply the skill's hunt checklist (secrets, injection, paths, authn/authz,
|
||||
deserialization, network, supply chain, crypto, data exposure, resource abuse).
|
||||
4. Ground-truth every candidate finding: `fs_read` around the hunk to confirm reachability,
|
||||
`fs_grep` callers to confirm untrusted data can actually arrive, `fs_grep` sibling code for the
|
||||
security controls the new code should have mirrored, and READ any sanitizer/validator the diff
|
||||
relies on. Use `ast_grep` for structural checks (e.g. string-built SQL, `sh -c` call sites).
|
||||
5. Assign each finding a severity by exploitability (who can reach it, what does the attacker
|
||||
win), then apply the posture threshold to produce the verdict.
|
||||
6. Emit the verdict in the skill's exact format.
|
||||
|
||||
## Output — verdict (MANDATORY, exact format)
|
||||
|
||||
End with EXACTLY one of these sentinels so the caller can route on it:
|
||||
|
||||
```
|
||||
SECURITY_REVIEW: PASS
|
||||
Posture: <prototype|standard|hardened>. Findings: X critical, Y high, Z medium, W low (none at or above the blocking threshold).
|
||||
<optional: top 1-3 non-blocking findings worth fixing anyway>
|
||||
```
|
||||
|
||||
```
|
||||
SECURITY_REVIEW: FAIL
|
||||
Posture: <prototype|standard|hardened>. Findings: X critical, Y high, Z medium, W low.
|
||||
Blocking findings:
|
||||
1. 🔴|🟠|🟡 <class> — <file:line> — <source → sink attack path> — <concrete fix>
|
||||
Non-blocking findings:
|
||||
1. 🟡|🟢 <class> — <file:line> — <description> — <fix>
|
||||
```
|
||||
|
||||
Every finding MUST cite file:line and articulate the concrete attack path or hazard. A finding
|
||||
with no location and no attack path is noise — do not emit it.
|
||||
|
||||
## Rules
|
||||
|
||||
1. **You are read-only.** Never modify files. You produce a verdict; the implementer owns the fix.
|
||||
2. **Security, not quality.** Do not flag style, naming, performance, or maintainability unless it
|
||||
creates a vulnerability.
|
||||
3. **Critical always blocks — in every posture.** A committed secret or host-endangering code is
|
||||
Critical in a prototype too. Posture gates High/Medium, never Critical.
|
||||
4. **Posture gates the verdict, not the report.** Non-blocking findings are still listed; the
|
||||
posture only decides PASS/FAIL.
|
||||
5. **Review the CHANGE.** Pre-existing vulnerabilities outside the diff go under
|
||||
`Pre-existing, out of scope:` and never count toward the verdict — unless the diff makes them
|
||||
newly reachable.
|
||||
6. **Severity = reachability × blast radius.** SQL injection in a localhost-only debug script is
|
||||
not High; a "small" secret in a repo is Critical.
|
||||
7. Be terse and decisive. Three exploitable findings beat fifteen theoretical ones. If everything
|
||||
is theoretical hardening, it PASSes — say so.
|
||||
|
||||
## Context
|
||||
- Project: {{project_dir}}
|
||||
- Security posture: {{security_posture}}
|
||||
- CWD: {{__cwd__}}
|
||||
- Shell: {{__shell__}}
|
||||
|
||||
## Available Tools
|
||||
{{__tools__}}
|
||||
Executable
+78
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env bash
|
||||
set -eo pipefail
|
||||
|
||||
# @env LLM_OUTPUT=/dev/stdout
|
||||
# @env LLM_AGENT_VAR_PROJECT_DIR=.
|
||||
# @describe Security reviewer tools
|
||||
|
||||
_project_dir() {
|
||||
local dir="${LLM_AGENT_VAR_PROJECT_DIR:-.}"
|
||||
(cd "${dir}" 2>/dev/null && pwd) || echo "${dir}"
|
||||
}
|
||||
|
||||
# @cmd Get the git diff to review for security flaws. Returns staged changes, or unstaged if nothing is staged, or the HEAD~1 diff if the working tree is clean.
|
||||
# @option --base Optional base ref to diff against (e.g., "main", "HEAD~3", a commit SHA, or a PR base branch)
|
||||
get_diff() {
|
||||
local project_dir
|
||||
project_dir=$(_project_dir)
|
||||
# shellcheck disable=SC2154
|
||||
local base="${argc_base:-}"
|
||||
|
||||
local diff_output=""
|
||||
if [[ -n "${base}" ]]; then
|
||||
diff_output=$(cd "${project_dir}" && git diff "${base}" 2>&1) || true
|
||||
else
|
||||
diff_output=$(cd "${project_dir}" && git diff --cached 2>&1) || true
|
||||
if [[ -z "${diff_output}" ]]; then
|
||||
diff_output=$(cd "${project_dir}" && git diff 2>&1) || true
|
||||
fi
|
||||
if [[ -z "${diff_output}" ]]; then
|
||||
diff_output=$(cd "${project_dir}" && git diff HEAD~1 2>&1) || true
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -z "${diff_output}" ]]; then
|
||||
echo "No changes found to review in ${project_dir}." >> "$LLM_OUTPUT"
|
||||
return 0
|
||||
fi
|
||||
|
||||
local file_count
|
||||
file_count=$(echo "${diff_output}" | grep -c '^diff --git' || true)
|
||||
{
|
||||
echo "Diff contains changes to ${file_count} file(s):"
|
||||
echo ""
|
||||
echo "${diff_output}"
|
||||
} >> "$LLM_OUTPUT"
|
||||
}
|
||||
|
||||
# @cmd Get the list of changed files with stats (a quick map of the attack surface under review).
|
||||
# @option --base Optional base ref to diff against
|
||||
get_changed_files() {
|
||||
local project_dir
|
||||
project_dir=$(_project_dir)
|
||||
local base="${argc_base:-}"
|
||||
|
||||
local stat_output=""
|
||||
if [[ -n "${base}" ]]; then
|
||||
stat_output=$(cd "${project_dir}" && git diff --stat "${base}" 2>&1) || true
|
||||
else
|
||||
stat_output=$(cd "${project_dir}" && git diff --cached --stat 2>&1) || true
|
||||
if [[ -z "${stat_output}" ]]; then
|
||||
stat_output=$(cd "${project_dir}" && git diff --stat 2>&1) || true
|
||||
fi
|
||||
if [[ -z "${stat_output}" ]]; then
|
||||
stat_output=$(cd "${project_dir}" && git diff --stat HEAD~1 2>&1) || true
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ -z "${stat_output}" ]]; then
|
||||
echo "No changes found in ${project_dir}." >> "$LLM_OUTPUT"
|
||||
return 0
|
||||
fi
|
||||
|
||||
{
|
||||
echo "Changed files:"
|
||||
echo ""
|
||||
echo "${stat_output}"
|
||||
} >> "$LLM_OUTPUT"
|
||||
}
|
||||
@@ -26,8 +26,11 @@ flowchart TD
|
||||
broad_gate -->|"no"| spec_gate
|
||||
code_reviewer --> spec_gate{"Implements<br/>a spec / plan?"}
|
||||
spec_gate -->|"yes"| adversary[["adversary<br/>plan-conformance"]]
|
||||
spec_gate -->|"no"| done
|
||||
adversary --> done
|
||||
spec_gate -->|"no"| sec_gate
|
||||
adversary --> sec_gate{"Touches attack surface?<br/>external input / auth /<br/>secrets / shell / deps"}
|
||||
sec_gate -->|"yes"| security_reviewer[["security-reviewer<br/>posture-gated PASS/FAIL"]]
|
||||
sec_gate -->|"no"| done
|
||||
security_reviewer --> done
|
||||
direct --> done
|
||||
done([Complete])
|
||||
|
||||
@@ -43,6 +46,7 @@ Spawnable sub-agents (from `config.yaml`):
|
||||
- **[coder](../coder/README.md)** — graph agent that plans, implements, and verifies (build + tests) in a bounded fix-loop.
|
||||
- **[code-reviewer](../code-reviewer/README.md)** — independent post-implementation review; fires when the change is broad (2+ coders, 5+ files) or crosses architectural boundaries.
|
||||
- **[adversary](../adversary/README.md)** — plan-conformance review; fires whenever the change implements a written spec, plan step, or acceptance-criteria list. Orthogonal to `code-reviewer` — both can run.
|
||||
- **[security-reviewer](../security-reviewer/README.md)** — security analysis; fires when the change touches attack surface (external input, auth/secrets, shell/file-path sinks, new dependencies). Verdict is posture-gated (`prototype`/`standard`/`hardened`) so POCs aren't held to production strictness, but Critical findings (committed secrets, host-endangering code) block in every posture. Orthogonal to both other reviewers — all three can run.
|
||||
- **[step-runner](../step-runner/README.md)** — graph agent that executes one step of a phased plan repo. Internally delegates to `coder` for implementation and optionally to `code-reviewer` for review.
|
||||
|
||||
## Features
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
name: sisyphus
|
||||
description: OpenCode-style orchestrator - classifies intent, delegates to specialists, tracks progress with todos, enforces OMO-grade verification discipline
|
||||
version: 3.2.0
|
||||
version: 3.7.0
|
||||
|
||||
agent_session: temp
|
||||
auto_continue: true
|
||||
@@ -15,16 +15,21 @@ spawnable_agents:
|
||||
- oracle
|
||||
- code-reviewer
|
||||
- adversary
|
||||
- security-reviewer
|
||||
- architecture-reviewer
|
||||
- step-runner
|
||||
max_concurrent_agents: 4
|
||||
max_concurrent_agents: 40
|
||||
max_agent_depth: 3
|
||||
inject_spawn_instructions: true
|
||||
summarization_threshold: 8000
|
||||
summarization_threshold: 80000
|
||||
|
||||
skills_enabled: true
|
||||
enabled_skills:
|
||||
- ai-slop-remover
|
||||
- code-review
|
||||
- comment-discipline
|
||||
- diagnosing-bugs
|
||||
- grilling
|
||||
- git-master
|
||||
- frontend-ui-ux
|
||||
- delegation-protocol
|
||||
@@ -124,6 +129,8 @@ instructions: |
|
||||
|
||||
For "improve X" / "refactor Y" / "clean up Z" type requests, quick-assess the codebase state BEFORE following patterns:
|
||||
|
||||
**Architecture-scale improvement requests** ("improve the architecture of X", "this module is hard to test", "make this easier to navigate") → delegate to `architecture-reviewer`. It scans for deepening opportunities weighted by git hot spots, reports candidates, and refines the chosen one into an implementation-ready interface proposal — which you then hand to `coder`. It proposes only; it is an on-demand tool, never a completion gate. For file-scale cleanups, proceed with the assessment below instead.
|
||||
|
||||
- **Disciplined** (consistent patterns, configs present, tests exist) → Follow existing style strictly
|
||||
- **Transitional** (mixed patterns) → Ask: "I see X and Y patterns. Which to follow?"
|
||||
- **Legacy/Chaotic** (no consistency) → Propose: "No clear conventions. I suggest [X]. OK?"
|
||||
@@ -336,10 +343,54 @@ instructions: |
|
||||
|
||||
Unlike `code-reviewer`, re-running `adversary` once after a conformance fix is expected — a DIVERGES verdict is a hard gate, and confirming the fix actually closed it is the point.
|
||||
|
||||
### Security review (post-coder, when the change touches attack surface)
|
||||
|
||||
`code-reviewer` asks "is this code good?" and `adversary` asks "is this the code the plan asked for?" — neither asks "can this code be abused?" Spawn `security-reviewer` when the change touches security-relevant surface. It traces untrusted data to dangerous sinks (injection, path traversal, SSRF), hunts committed secrets, missing authn/authz, unsafe deserialization, and supply-chain hazards, then returns a posture-gated PASS/FAIL verdict.
|
||||
|
||||
**When to spawn it** — ANY of these:
|
||||
|
||||
1. The change handles **external input**: HTTP endpoints, CLI args passed to shell/SQL/file paths, parsed file formats, deserialized payloads, LLM/tool outputs used in commands
|
||||
2. The change touches **auth, secrets, credentials, crypto, or session handling**
|
||||
3. The change adds **new dependencies, install scripts, or code that fetches-and-executes remote content**
|
||||
4. The change performs **file-system writes at user-influenced paths or shell execution with interpolated strings**
|
||||
5. **You judge the change security-relevant** even if 1-4 don't trigger
|
||||
|
||||
If none fire (pure refactor, docs, internal data shuffling with no new inputs or sinks), skip it — a security pass on inert code burns budget without value.
|
||||
|
||||
**Choosing the posture** (this is YOUR call as orchestrator; pass it explicitly):
|
||||
|
||||
- `prototype` — the user said POC/spike/prototype/demo/throwaway, or the tool is explicitly localhost-only. Blocks Critical only.
|
||||
- `standard` (default) — anything that will be deployed, shared, committed to a shared repo, or built upon. Blocks Critical + High.
|
||||
- `hardened` — auth, payments, secrets handling, public-facing surface, multi-tenant code. Blocks Critical + High + Medium.
|
||||
|
||||
When in doubt, use `standard`. Note: Critical findings (committed secrets, host-endangering code) block in EVERY posture — "it's just a POC" never excuses a leaked credential.
|
||||
|
||||
**Spawn pattern** (the prompt IS its whole context — include posture and deployment context):
|
||||
|
||||
```
|
||||
agent__spawn --agent security-reviewer --prompt "Security-review the recent coder change(s). Return PASS/FAIL.
|
||||
|
||||
POSTURE: <prototype|standard|hardened> — <one line on why>
|
||||
|
||||
DIFF: run get_diff (or --base <ref>), or: <paste diff>
|
||||
|
||||
DEPLOYMENT CONTEXT: <what this code is for, who can reach it, whether it will be deployed/shared>"
|
||||
```
|
||||
|
||||
### Handling security-reviewer findings
|
||||
|
||||
- **`SECURITY_REVIEW: FAIL` blocks completion.** Do not mark the task done. Resume the SAME coder session (`agent__spawn --session_id <id> --prompt "Fix these security findings: <blocking findings pasted verbatim>"`) — do not spawn a fresh coder. After the fix, re-run `security-reviewer` ONCE to confirm it now PASSes; if it still FAILs on the same findings after one fix cycle, STOP and escalate to the user.
|
||||
- **`SECURITY_REVIEW: PASS`** — proceed. Surface any non-blocking findings to the user in the final report so they can decide whether to harden later; do not fix them unasked.
|
||||
- **`Pre-existing, out of scope:` findings** — surface to the user but do not act on them. They predate this work and aren't the current task's responsibility.
|
||||
- **Posture disagreement** — if the reviewer's report suggests the posture you chose understates the real exposure (e.g. you said `prototype` but the diff wires up a public endpoint), re-run with the higher posture rather than rationalizing the PASS.
|
||||
|
||||
Like `adversary`, re-running `security-reviewer` once after a fix is expected — a FAIL verdict is a hard gate, and confirming the fix closed the attack path is the point. Run all applicable reviewers (`code-reviewer`, `adversary`, `security-reviewer`) — they cover disjoint failure modes; one passing says nothing about the others.
|
||||
|
||||
## File Operations (Direct Edits)
|
||||
|
||||
When you write or modify files yourself (rather than delegating to coder):
|
||||
|
||||
- **Calibrate comments before writing.** Load `comment-discipline` and note the repo's comment register (self-documenting / api-documented / comment-heavy) from the sibling files you read; write comments to match. When the signal is weak, write NO comment.
|
||||
- **For editing an existing file**, prefer `fs_patch`. It's a surgical edit that preserves unchanged content. Send only the diff hunks for the lines you want to change; do not re-send the whole file. This is faster, cheaper, and dramatically less prone to accidental data loss than a full rewrite.
|
||||
- **For writing a NEW file or doing a COMPLETE rewrite**, use `fs_write`. Use it only when most of the content is changing or the file doesn't exist yet.
|
||||
- **NEVER write files via `execute_command`.** Do not use:
|
||||
@@ -358,6 +409,10 @@ instructions: |
|
||||
|
||||
## Phase 7 - Failure Recovery
|
||||
|
||||
### Hard bugs: load `diagnosing-bugs` BEFORE strike 2
|
||||
|
||||
A first fix attempt may go on the error message alone. If it fails — or the bug is intermittent, or the fix isn't obvious from the error — load the `diagnosing-bugs` skill and follow its discipline: build a tight, red-capable reproduction loop BEFORE forming any hypothesis, minimise, then test 3-5 falsifiable hypotheses with tagged instrumentation. Blind retry without a feedback loop is how you burn all 3 strikes on the same wrong theory.
|
||||
|
||||
### 3-strike rule
|
||||
|
||||
After 3 consecutive failed fix attempts on the same problem:
|
||||
@@ -376,7 +431,7 @@ instructions: |
|
||||
|
||||
### Authoring lifecycle (no code changes)
|
||||
|
||||
1. Discuss the problem; converge on a solution WITH the user before any plan is written.
|
||||
1. Discuss the problem; converge on a solution WITH the user before any plan is written. Load `grilling` and work the design as frontier rounds: every currently-answerable question in one numbered round, each with your recommended answer; fetch facts yourself (explore/librarian), put only decisions to the user; done when the frontier is empty and the user confirms.
|
||||
2. Load `plan-authoring`. Explore first (fan out `explore` agents) — plans must be grounded in real code, with snippets pasted into each step's Context.
|
||||
3. Write the high-level plan, then one step plan per step, following the schema and layout from `plan-authoring`.
|
||||
4. **Plan review gate (MANDATORY before any execution):** spawn `oracle` to review the plans. Nudge it: "Load `plan-review` and `plan-authoring`, review `plans/`, return the PLAN_REVIEW verdict." REJECT → fix the complaints, re-submit. Do not start execution on an unreviewed or rejected plan.
|
||||
|
||||
@@ -21,8 +21,7 @@
|
||||
},
|
||||
"iwe": {
|
||||
"type": "stdio",
|
||||
"command": "iwec",
|
||||
"args": ["--project", "."]
|
||||
"command": "iwec"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,11 @@ set -e
|
||||
# is the most common cause of "unable to apply patch" failures, especially in files with sed/jq/regex pipelines or
|
||||
# embedded Python with quoted strings.
|
||||
# - Hunks are applied in order; the first hunk that fails aborts the whole patch — later hunks are NOT attempted.
|
||||
# - Hunks anchor at the FIRST exact match of their context in the file, so include enough context to make each hunk
|
||||
# unique. Hunks must appear in file order.
|
||||
# - Every hunk needs at least one context or removed line to anchor it; a hunk containing only additions is an error.
|
||||
# - Unrecognized lines inside a hunk are hard errors: every hunk line must start with ' ' (context), '-' (removal),
|
||||
# or '+' (addition).
|
||||
# - If you've edited this file in earlier tool calls, fs_cat it again before composing the patch. A stale view of the file
|
||||
# produces context lines that no longer match.
|
||||
# - On failure the error message names the failing hunk and shows the expected-vs-actual line. Fix that specific line and
|
||||
@@ -33,7 +38,11 @@ source "$LLM_PROMPT_UTILS_FILE"
|
||||
|
||||
# shellcheck disable=SC2154
|
||||
main() {
|
||||
argc_contents="$(jq -r '.content' <<< "$LLM_TOOL_RAW_JSON")"
|
||||
# Command substitution strips *all* trailing newlines and `jq -r` appends one
|
||||
# of its own, so read with `-j` and pin the real end of the content with a
|
||||
# sentinel that is removed afterwards.
|
||||
argc_contents="$(jq -j '.content' <<< "$LLM_TOOL_RAW_JSON"; printf x)"
|
||||
argc_contents="${argc_contents%x}"
|
||||
argc_path="$(jq -r '.path' <<< "$LLM_TOOL_RAW_JSON")"
|
||||
|
||||
if [[ ! -f "$argc_path" ]]; then
|
||||
@@ -41,7 +50,19 @@ main() {
|
||||
exit 1
|
||||
fi
|
||||
|
||||
new_contents="$(patch_file "$argc_path" <(printf "%s" "$argc_contents"))"
|
||||
# Same sentinel guard on the patched result, otherwise the trailing newline
|
||||
# is stripped again on the way back out. `rc` preserves patch_file's exit
|
||||
# status so a failure still aborts under `set -e`.
|
||||
new_contents="$(patch_file "$argc_path" <(printf "%s" "$argc_contents"); rc=$?; printf x; exit "$rc")"
|
||||
new_contents="${new_contents%x}"
|
||||
|
||||
# awk newline-terminates every printed line, so patching a file that lacks
|
||||
# a final newline would silently add one. Preserve the original file's
|
||||
# final-newline state instead.
|
||||
if [[ -n "$(tail -c 1 "$argc_path")" ]]; then
|
||||
new_contents="${new_contents%$'\n'}"
|
||||
fi
|
||||
|
||||
printf "%s" "$new_contents" | git diff --no-index "$argc_path" - || true
|
||||
|
||||
guard_operation "Apply changes?"
|
||||
|
||||
@@ -15,7 +15,12 @@ source "$LLM_PROMPT_UTILS_FILE"
|
||||
|
||||
# shellcheck disable=SC2154
|
||||
main() {
|
||||
argc_contents="$(jq -r '.content' <<< "$LLM_TOOL_RAW_JSON")"
|
||||
# Command substitution strips *all* trailing newlines and `jq -r` appends one
|
||||
# of its own, so read with `-j` and pin the real end of the content with a
|
||||
# sentinel that is removed afterwards. Without this every written file loses
|
||||
# its final newline, which breaks formatters such as `cargo fmt --check`.
|
||||
argc_contents="$(jq -j '.content' <<< "$LLM_TOOL_RAW_JSON"; printf x)"
|
||||
argc_contents="${argc_contents%x}"
|
||||
argc_path="$(jq -r '.path' <<< "$LLM_TOOL_RAW_JSON")"
|
||||
|
||||
if [[ -f "$argc_path" ]]; then
|
||||
|
||||
Executable
+79
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env bash
|
||||
set -e
|
||||
|
||||
# @describe Execute a git command. Strictly limited to a single git invocation: the command must start with 'git' and shell metacharacters (; & | < > ( ) $ `) are rejected outside single quotes — no pipes, chaining, redirection, or command substitution. Use git's own flags instead of pipes (e.g. 'git log -n 20' instead of piping to head). Output is never paginated and git will never prompt for input.
|
||||
# @option --command! The git command to execute (e.g. "git status --short").
|
||||
|
||||
# @env LLM_OUTPUT=/dev/stdout The output path
|
||||
|
||||
# shellcheck disable=SC1090
|
||||
source "$LLM_PROMPT_UTILS_FILE"
|
||||
|
||||
main() {
|
||||
# shellcheck disable=SC2154
|
||||
argc_command="$(jq -r '.command' <<< "$LLM_TOOL_RAW_JSON")"
|
||||
|
||||
validate_command "$argc_command" "git"
|
||||
|
||||
guard_operation "Execute git command: $argc_command"
|
||||
|
||||
export GIT_PAGER=cat PAGER=cat GIT_TERMINAL_PROMPT=0
|
||||
export GIT_EDITOR=true GIT_SEQUENCE_EDITOR=true
|
||||
|
||||
local script
|
||||
script="$(mktemp)"
|
||||
# shellcheck disable=SC2064
|
||||
trap "rm -f '$script'" EXIT
|
||||
printf '%s\n' "$argc_command" > "$script"
|
||||
bash -e -o pipefail "$script" >> "$LLM_OUTPUT"
|
||||
}
|
||||
|
||||
die() {
|
||||
echo "$*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Ensure the command is a single plain invocation of $2 with no shell escape
|
||||
# hatches. Metacharacters are allowed inside single quotes (where bash treats
|
||||
# them as literals) but rejected everywhere else, including $ and ` inside
|
||||
# double quotes (expansion/substitution).
|
||||
validate_command() {
|
||||
local cmd="$1" prog="$2"
|
||||
|
||||
local first
|
||||
first="$(awk '{print $1}' <<< "$cmd")"
|
||||
if [[ "$first" != "$prog" ]]; then
|
||||
die "error: this tool only executes $prog commands; the command must start with '$prog' (got: '${first:-<empty>}')"
|
||||
fi
|
||||
|
||||
local i c in_single=0 in_double=0 len=${#cmd}
|
||||
for (( i = 0; i < len; i++ )); do
|
||||
c="${cmd:i:1}"
|
||||
if (( in_single )); then
|
||||
[[ "$c" == "'" ]] && in_single=0
|
||||
continue
|
||||
fi
|
||||
if (( in_double )); then
|
||||
case "$c" in
|
||||
'\') i=$((i + 1)) ;;
|
||||
'"') in_double=0 ;;
|
||||
'$' | '`') die "error: '$c' is not allowed inside double quotes (expansion/substitution is blocked); use single quotes for literal text" ;;
|
||||
esac
|
||||
continue
|
||||
fi
|
||||
case "$c" in
|
||||
'\') i=$((i + 1)) ;;
|
||||
"'") in_single=1 ;;
|
||||
'"') in_double=1 ;;
|
||||
';' | '&' | '|' | '<' | '>' | '(' | ')' | '$' | '`')
|
||||
die "error: shell metacharacter '$c' is not allowed; run a single $prog command with no pipes, chaining, redirection, or substitution (use $prog's own flags instead, and single quotes for literal text)"
|
||||
;;
|
||||
$'\n')
|
||||
die "error: newlines are not allowed; run a single $prog command"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
if (( in_single || in_double )); then
|
||||
die "error: unbalanced quotes in command"
|
||||
fi
|
||||
}
|
||||
@@ -186,7 +186,9 @@ input() {
|
||||
}
|
||||
|
||||
confirm() {
|
||||
trap "stty echo; exit" EXIT
|
||||
# stty targets stdin, which is /dev/null when the host spawns tool scripts;
|
||||
# point it at the real terminal and stay quiet when there isn't one.
|
||||
trap "stty echo </dev/tty 2>/dev/null; exit" EXIT
|
||||
_prompt_text "$1 (y/N)"
|
||||
echo -en "\033[36m\c " >&2
|
||||
|
||||
@@ -229,7 +231,7 @@ list() {
|
||||
declare first_row
|
||||
first_row=$((last_row - opts_count + 1))
|
||||
|
||||
trap "_cursor_blink_on; stty echo; exit" 2
|
||||
trap "_cursor_blink_on; stty echo </dev/tty 2>/dev/null; exit" 2
|
||||
|
||||
_cursor_blink_off
|
||||
|
||||
@@ -275,7 +277,7 @@ checkbox() {
|
||||
declare first_row
|
||||
first_row=$((last_row - opts_count + 1))
|
||||
|
||||
trap "_cursor_blink_on; stty echo; exit" 2
|
||||
trap "_cursor_blink_on; stty echo </dev/tty 2>/dev/null; exit" 2
|
||||
|
||||
_cursor_blink_off
|
||||
|
||||
@@ -403,7 +405,7 @@ range() {
|
||||
declare current_row
|
||||
current_row=$((first_row - 1))
|
||||
|
||||
trap "_cursor_blink_on; stty echo; exit" 2
|
||||
trap "_cursor_blink_on; stty echo </dev/tty 2>/dev/null; exit" 2
|
||||
|
||||
_cursor_blink_off
|
||||
|
||||
@@ -528,7 +530,11 @@ guard_operation() {
|
||||
# + print(f"Hello {name}")
|
||||
patch_file() {
|
||||
awk '
|
||||
FNR == NR {
|
||||
function isHeaderPair(i) {
|
||||
return (patchLines[i] ~ /^--- / && patchLines[i+1] ~ /^\+\+\+ / && patchLines[i+2] ~ /^@@/)
|
||||
}
|
||||
|
||||
FILENAME == ARGV[1] {
|
||||
lines[FNR] = $0
|
||||
next;
|
||||
}
|
||||
@@ -547,11 +553,6 @@ patch_file() {
|
||||
while (patchLineIndex <= totalPatchLines) {
|
||||
line = patchLines[patchLineIndex]
|
||||
|
||||
if (line ~ /^--- / || line ~ /^\+\+\+ /) {
|
||||
patchLineIndex++
|
||||
continue
|
||||
}
|
||||
|
||||
if (line ~ /^@@/) {
|
||||
mode = "hunk"
|
||||
hunkIndex++
|
||||
@@ -560,7 +561,22 @@ patch_file() {
|
||||
}
|
||||
|
||||
if (mode == "hunk") {
|
||||
while (patchLineIndex <= totalPatchLines && line ~ /^[-+ ]|^\s*$/ && line !~ /^--- /) {
|
||||
while (patchLineIndex <= totalPatchLines) {
|
||||
line = patchLines[patchLineIndex]
|
||||
|
||||
if (line ~ /^\\ No newline/) {
|
||||
patchLineIndex++
|
||||
continue
|
||||
}
|
||||
|
||||
if (isHeaderPair(patchLineIndex)) {
|
||||
break
|
||||
}
|
||||
|
||||
if (line !~ /^[-+ ]/ && line !~ /^[ \t]*$/) {
|
||||
break
|
||||
}
|
||||
|
||||
sanitizedLine = substr(line, 2)
|
||||
|
||||
if (line !~ /^\+/) {
|
||||
@@ -574,13 +590,37 @@ patch_file() {
|
||||
}
|
||||
|
||||
patchLineIndex++
|
||||
line = patchLines[patchLineIndex]
|
||||
}
|
||||
|
||||
mode = "none"
|
||||
} else {
|
||||
patchLineIndex++
|
||||
continue
|
||||
}
|
||||
|
||||
if (isHeaderPair(patchLineIndex)) {
|
||||
patchLineIndex += 2
|
||||
continue
|
||||
}
|
||||
|
||||
if (line ~ /^\\ No newline/) {
|
||||
patchLineIndex++
|
||||
continue
|
||||
}
|
||||
|
||||
if (hunkIndex == 0) {
|
||||
# Preamble before the first hunk: tolerate prose, code fences, and lone headers.
|
||||
patchLineIndex++
|
||||
continue
|
||||
}
|
||||
|
||||
if (line ~ /^[ \t]*$/ || line ~ /^```/) {
|
||||
patchLineIndex++
|
||||
continue
|
||||
}
|
||||
|
||||
print "error: unrecognized line in patch (line " patchLineIndex "): " line > "/dev/stderr"
|
||||
print "" > "/dev/stderr"
|
||||
print "Every line inside a hunk must start with \" \" (context), \"-\" (removal), or \"+\" (addition)." > "/dev/stderr"
|
||||
exit 1
|
||||
}
|
||||
|
||||
if (hunkIndex == 0) {
|
||||
@@ -593,6 +633,36 @@ patch_file() {
|
||||
}
|
||||
|
||||
totalHunks = hunkIndex
|
||||
|
||||
if (totalLines == 0) {
|
||||
for (h = 1; h <= totalHunks; h++) {
|
||||
if (hunkTotalOriginalLines[h] > 0) {
|
||||
print "error: unable to apply patch" > "/dev/stderr"
|
||||
print "" > "/dev/stderr"
|
||||
print "Hunk " h " expects existing content but the file is empty." > "/dev/stderr"
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
for (h = 1; h <= totalHunks; h++) {
|
||||
for (i = 1; i <= hunkTotalUpdatedLines[h]; i++) {
|
||||
print hunkUpdatedLines[h,i]
|
||||
}
|
||||
}
|
||||
|
||||
exit 0
|
||||
}
|
||||
|
||||
for (h = 1; h <= totalHunks; h++) {
|
||||
if (hunkTotalOriginalLines[h] == 0) {
|
||||
print "error: unable to apply patch" > "/dev/stderr"
|
||||
print "" > "/dev/stderr"
|
||||
print "Hunk " h " contains no context or removed lines; include at least one" > "/dev/stderr"
|
||||
print "context line so the hunk can be anchored." > "/dev/stderr"
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
hunkIndex = 1
|
||||
|
||||
for (lineIndex = 1; lineIndex <= totalLines; lineIndex++) {
|
||||
@@ -603,7 +673,7 @@ patch_file() {
|
||||
nextLineIndex = lineIndex + 1
|
||||
|
||||
for (i = 2; i <= hunkTotalOriginalLines[hunkIndex]; i++) {
|
||||
if (lines[nextLineIndex] != hunkOriginalLines[hunkIndex,i]) {
|
||||
if (nextLineIndex > totalLines || lines[nextLineIndex] != hunkOriginalLines[hunkIndex,i]) {
|
||||
if (i - 1 > bestPartialLen[hunkIndex]) {
|
||||
bestPartialLen[hunkIndex] = i - 1
|
||||
bestPartialAnchorLine[hunkIndex] = lineIndex
|
||||
@@ -646,10 +716,14 @@ patch_file() {
|
||||
print "" > "/dev/stderr"
|
||||
print "Closest match: anchored at file line " bestPartialAnchorLine[failingHunk] ", matched " bestPartialLen[failingHunk] " of " hunkTotalOriginalLines[failingHunk] " original lines before diverging." > "/dev/stderr"
|
||||
print "" > "/dev/stderr"
|
||||
if (bestPartialDivergeLine[failingHunk] > totalLines) {
|
||||
print "The hunk expects additional lines beyond the end of the file (file has " totalLines " lines)." > "/dev/stderr"
|
||||
} else {
|
||||
print "At file line " bestPartialDivergeLine[failingHunk] " (hunk original line " bestPartialHunkPos[failingHunk] "):" > "/dev/stderr"
|
||||
print " expected: " bestPartialExpected[failingHunk] > "/dev/stderr"
|
||||
print " actual: " bestPartialActual[failingHunk] > "/dev/stderr"
|
||||
}
|
||||
}
|
||||
|
||||
print "" > "/dev/stderr"
|
||||
print "Lines must match byte-for-byte (no fuzzy matching). Check escaping, whitespace, and quoting." > "/dev/stderr"
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
description: Generate a git commit message from the current diff
|
||||
steps:
|
||||
- .file `git diff` -- generate a git commit message
|
||||
@@ -88,6 +88,7 @@ A diff review is a review of THE CHANGE, not the whole file:
|
||||
|
||||
- Are names accurate? `get_user` that mutates is a lie; rename or split.
|
||||
- Could a competent reader understand this without comments?
|
||||
- Do NEW comments match the repo's comment register? You already read neighboring files for conventions — compare against them. Flag BOTH directions: narrated/restating comments in a repo that uses self-documenting code (each one is a finding, cite the line), AND missing doc comments on new public items in a repo that documents its public API. Comments explaining non-obvious *why* (decisions, workarounds, invariants) are warranted in every repo; comments captioning *what* the code plainly does are warranted in none.
|
||||
- Is there a simpler way to express the same logic?
|
||||
- Is the function doing one thing, or several things glued together?
|
||||
|
||||
@@ -96,6 +97,7 @@ A diff review is a review of THE CHANGE, not the whole file:
|
||||
- Does this change increase coupling between modules unnecessarily?
|
||||
- Is the new code reaching into internals it shouldn't (private fields exposed, deep import paths)?
|
||||
- Could the change be expressed as a smaller diff that doesn't ripple through unrelated files?
|
||||
- New helper/utility/constant introduced? `fs_grep` for an existing equivalent in the repo before accepting it — duplicating an existing helper is a finding; cite the original's path so the author can reuse it. (The inverse is not a finding: do not demand a new abstraction to unify two mildly similar blocks.)
|
||||
|
||||
## 5. Footguns
|
||||
|
||||
@@ -104,6 +106,29 @@ A diff review is a review of THE CHANGE, not the whole file:
|
||||
- Are error types specific enough to be actionable?
|
||||
- Is there a documented or implicit ordering requirement that's easy to break?
|
||||
|
||||
## 6. Code smells (baseline heuristics)
|
||||
|
||||
A fixed baseline of named smells (Fowler, *Refactoring* ch. 3) that applies even when the repo documents no standards. Three calibration rules bind it:
|
||||
|
||||
1. **The repo overrides.** A documented or established repo convention always wins; where the codebase deliberately does something the baseline would flag, suppress the smell.
|
||||
2. **Always a judgment call.** Report each as a labelled heuristic ("possible Feature Envy"), never a hard violation — severity 🟢 Suggestion or 💡 Nitpick unless it compounds a real defect.
|
||||
3. **Skip anything tooling already enforces.** Linters and formatters own their territory.
|
||||
|
||||
Each smell reads *what it is → how to fix*; match against the diff only:
|
||||
|
||||
- **Mysterious Name**: a function/variable/type whose name doesn't reveal what it does or holds → rename; if no honest name comes, the design is murky.
|
||||
- **Duplicated Code**: the same logic shape in more than one hunk or file of the change → extract the shared shape, call it from both. (For duplication against EXISTING code, see the Coupling grep check above.)
|
||||
- **Feature Envy**: a method reaching into another object's data more than its own → move the method onto the data it envies.
|
||||
- **Data Clumps**: the same few fields/params travelling together — a type wanting to be born → bundle them into one type.
|
||||
- **Primitive Obsession**: a primitive/string standing in for a domain concept → give the concept its own small type.
|
||||
- **Repeated Switches**: the same `switch`/`if`-cascade on the same type recurring across the change → polymorphism, or one shared map.
|
||||
- **Shotgun Surgery**: one logical change forcing scattered edits across many files in the diff → gather what changes together into one module.
|
||||
- **Divergent Change**: one file edited for several unrelated reasons → split so each module changes for one reason.
|
||||
- **Speculative Generality**: abstraction/parameters/hooks added for needs nothing in the change has → delete; inline until a real need shows.
|
||||
- **Message Chains**: long `a.b().c().d()` navigation the caller shouldn't depend on → hide the walk behind one method on the first object.
|
||||
- **Middle Man**: a class/function that mostly delegates onward → cut it, call the real target directly.
|
||||
- **Refused Bequest**: a subclass/implementer ignoring or overriding most of what it inherits → drop the inheritance, use composition.
|
||||
|
||||
## What to flag
|
||||
|
||||
- Correctness bugs.
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
---
|
||||
description: Shared vocabulary and principles for designing deep modules - module, interface, depth, seam, adapter, leverage, locality - plus the deletion test, dependency categories for safe deepening, and the design-it-twice pattern for exploring alternative interfaces. Load when designing or improving a module's interface, deciding where a seam goes, making code more testable, or when another skill or agent needs the deep-module vocabulary.
|
||||
---
|
||||
Design **deep modules**: a lot of behaviour behind a small interface, placed at a clean seam, testable through that interface. Use this language and these principles wherever code is being designed or restructured. The aim is leverage for callers, locality for maintainers, and testability for everyone.
|
||||
|
||||
## Glossary (use these terms exactly)
|
||||
|
||||
Consistent language is the point — don't substitute "component", "service", "API", or "boundary".
|
||||
|
||||
- **Module**: anything with an interface and an implementation. Deliberately scale-agnostic: a function, class, package, or tier-spanning slice.
|
||||
- **Interface**: everything a caller must know to use the module correctly — the type signature, but also invariants, ordering constraints, error modes, required configuration, and performance characteristics. ("API"/"signature" are too narrow: they name only the type-level surface.)
|
||||
- **Implementation**: what's inside a module.
|
||||
- **Depth**: leverage at the interface — how much behaviour a caller (or test) can exercise per unit of interface they must learn. **Deep** = lots of behaviour behind a small interface. **Shallow** = an interface nearly as complex as the implementation.
|
||||
- **Seam** *(Feathers)*: a place where you can alter behaviour without editing in that place; the *location* where a module's interface lives. Where the seam goes is its own design decision, distinct from what goes behind it. (Avoid "boundary" — overloaded with DDD's bounded context.)
|
||||
- **Adapter**: a concrete thing that satisfies an interface at a seam. Names *role* (what slot it fills), not substance.
|
||||
- **Leverage**: what callers get from depth — more capability per unit of interface learned. One implementation pays back across N call sites and M tests.
|
||||
- **Locality**: what maintainers get from depth — change, bugs, knowledge, and verification concentrate in one place. Fix once, fixed everywhere.
|
||||
|
||||
## Principles
|
||||
|
||||
- **Depth is a property of the interface, not the implementation.** A deep module can be internally composed of small, mockable parts; they just aren't part of the interface. A module can have **internal seams** (private, used by its own tests) as well as the external seam at its interface — don't expose internal seams just because tests use them.
|
||||
- **The deletion test.** Imagine deleting the module. If complexity vanishes, it was a pass-through. If complexity reappears across N callers, it was earning its keep. Apply this to anything you suspect is shallow.
|
||||
- **The interface is the test surface.** Callers and tests cross the same seam. Wanting to test *past* the interface means the module is probably the wrong shape.
|
||||
- **One adapter means a hypothetical seam. Two adapters means a real one.** Don't introduce a seam unless something actually varies across it (typically production + test). A single-adapter seam is just indirection.
|
||||
- When designing an interface, ask: can I reduce the number of methods? simplify the parameters? hide more complexity inside?
|
||||
|
||||
## Designing for testability
|
||||
|
||||
1. **Accept dependencies, don't create them** — `processOrder(order, paymentGateway)` is testable; a function that constructs its own gateway is not.
|
||||
2. **Return results, don't produce side effects** — `calculateDiscount(cart): Discount` beats `applyDiscount(cart): void`.
|
||||
3. **Small surface area** — fewer methods = fewer tests needed; fewer params = simpler setup.
|
||||
|
||||
## Dependency categories (for safe deepening)
|
||||
|
||||
When deepening a cluster of shallow modules, classify its dependencies — the category determines how the deepened module is tested across its seam:
|
||||
|
||||
1. **In-process** (pure computation, in-memory state): always deepenable; merge and test through the new interface directly. No adapter needed.
|
||||
2. **Local-substitutable** (deps with real local stand-ins: embedded/in-memory DB, in-memory filesystem): deepenable if the stand-in exists; the test suite runs the stand-in, the seam stays internal.
|
||||
3. **Remote but owned** (your own services across a network): define a port (interface) at the seam; production gets an HTTP/gRPC/queue adapter, tests get an in-memory adapter. The logic sits in one deep module even though it deploys across a network.
|
||||
4. **True external** (third-party services you don't control): injected port; tests provide a mock adapter.
|
||||
|
||||
**Testing strategy: replace, don't layer.** Once tests exist at the deepened module's interface, old unit tests on the merged shallow modules are waste — delete them. New tests assert observable outcomes through the interface and survive internal refactors; a test that must change when the implementation changes is testing past the interface.
|
||||
|
||||
## Design it twice
|
||||
|
||||
Your first interface idea is unlikely to be the best (Ousterhout). For a module worth the effort, produce **2-3 radically different interface designs** before committing — in parallel sub-agents when available, sequentially otherwise. Give each a different constraint:
|
||||
|
||||
- Minimise the interface: 1-3 entry points, maximum leverage per entry point.
|
||||
- Maximise flexibility: many use cases, room for extension.
|
||||
- Optimise for the most common caller: make the default case trivial.
|
||||
- (When cross-seam dependencies dominate) design around ports & adapters.
|
||||
|
||||
Each design specifies: the interface (including invariants, ordering, error modes), a caller usage example, what the implementation hides, the dependency/adapter strategy, and where leverage is high vs thin. Compare on **depth**, **locality**, and **seam placement**, then give ONE opinionated recommendation (or a justified hybrid) — the reader wants a strong read, not a menu.
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
- Measuring depth as implementation-lines over interface-lines — rewards padding. Depth is leverage, not a ratio.
|
||||
- Extracting pure functions "for testability" while the real bugs live in how they're called — that trades away locality and deepens nothing.
|
||||
- Introducing ports/interfaces speculatively ("we might swap the DB") — one adapter is a hypothetical seam.
|
||||
- Renaming without restructuring: calling a pass-through layer an "adapter" doesn't make the module deep. Apply the deletion test.
|
||||
- Vocabulary drift mid-discussion ("component", "service", "boundary") — the shared terms exist so design conversations compose.
|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
description: Calibrate comment density and style to the repository's existing conventions before writing code. Detects the repo's comment register (self-documenting / api-documented / comment-heavy) from the sibling files you already read for pattern matching, or from a declared policy in workspace instructions, then dictates when a comment is warranted. Default when signal is weak - write NO comment. Complements ai-slop-remover (which bans comments that restate code in every register).
|
||||
---
|
||||
You are about to write or modify code. LLMs systematically over-comment — narrating every block, restating signatures, banner-ing sections — and that default is wrong in most repositories. Before writing, determine the repo's **comment register** and match it, exactly the way you already match imports, naming, and error handling.
|
||||
|
||||
## Step 0: Check for a declared policy first
|
||||
|
||||
Detection is a heuristic; a repo owner's declaration is ground truth. Before sampling files, check the workspace instructions already in your context (`COYOTE.md` / `AGENTS.md` / `CLAUDE.md`) for a stated comment policy (e.g. a "Comments" or "Style" section). If one exists, obey it and skip detection entirely.
|
||||
|
||||
## Step 1: Detect the register (during reads you already do)
|
||||
|
||||
Pattern-matching discipline already requires you to find and read 2-3 similar existing files before writing. While reading them, observe:
|
||||
|
||||
1. **Density** — roughly what fraction of lines are comments? Near-zero, sparse (~1 per function or less), or pervasive (most blocks narrated)?
|
||||
2. **Types present** — doc comments on public items (`///`, `/** */`, docstrings)? Inline "why" comments? Section banners (`// ===== Handlers =====`)? Commented-out code (a smell, not a convention — never imitate it)?
|
||||
3. **What the comments say** — do they explain *why* (decisions, workarounds, invariants, links to issues) or narrate *what* (restating the code)? A repo whose comments are all "why" is self-documenting even if density is nonzero.
|
||||
4. **Config signals** — these force the answer regardless of sampled style: `#![warn(missing_docs)]` or `#![deny(missing_docs)]` in Rust, eslint `jsdoc`/`require-jsdoc` rules, pylint/pydocstyle docstring checkers, a lint config banning TODO without a ticket. Lint-enforced conventions are mandatory.
|
||||
5. **TODO/FIXME conventions** — bare `TODO:`, or `TODO(name):`, or ticket-linked `TODO(#123):`? Match the observed form if you must leave one.
|
||||
|
||||
Sample from the SAME language and module you're editing — a repo can have a chatty Python test suite and a silent Rust core. The nearest siblings win.
|
||||
|
||||
## Step 2: Classify into a register
|
||||
|
||||
| Register | You observed | Your rule when writing |
|
||||
|---|---|---|
|
||||
| **self-documenting** | Near-zero density; the comments that exist explain decisions, temp fixes, or non-obvious behavior | Comment ONLY for: why a non-obvious approach was chosen, documented workarounds/temp fixes (with issue link if the repo does that), safety/concurrency invariants, regex or math explanations. Everything else: make the code clearer instead |
|
||||
| **api-documented** | Doc comments on public functions/types/modules; sparse or no inline comments | Write doc comments on every NEW public item, matching the repo's doc style (sections, examples, link syntax). Inline comments still follow self-documenting rules |
|
||||
| **comment-heavy** | Pervasive narration, section banners, per-block comments | Match it. Comment your work the way the siblings do — same placement, same tone, same banner style. Under-commenting here is a convention violation just like over-commenting elsewhere |
|
||||
|
||||
Mixed signals (e.g. doc comments everywhere + narrated private code) → combine rows: doc comments mandatory AND inline narration matched.
|
||||
|
||||
## Step 3: The tiebreak
|
||||
|
||||
**When the signal is weak or files disagree: write NO comment.** Your untrained default is comment-heavy, so the correction must push the other way. A missing comment is a one-line review nit; a hundred useless comments are a cleanup task. If you genuinely cannot tell and the comment feels important, it is usually a sign the code should be restructured until the comment is unnecessary.
|
||||
|
||||
## Invariants that do NOT bend with register
|
||||
|
||||
1. **Never restate the code.** `// increment the counter` above `counter += 1` is slop in EVERY register — comment-heavy repos narrate intent and sections, they don't caption individual lines the reader can read. (This is `ai-slop-remover`'s rule; it applies unconditionally.)
|
||||
2. **Always keep the genuinely necessary comment**, even in the sparsest repo: non-obvious algorithm choices (with the reference), regex explanations, safety invariants (`unsafe` justifications, lock ordering), intentional deviations from the obvious approach, and workarounds for upstream bugs (with the link).
|
||||
3. **Never leave commented-out code**, regardless of what the repo tolerates.
|
||||
4. **Never delete or rewrite EXISTING comments** that don't match the register you detected — that's out-of-scope churn. Register calibration governs comments YOU write.
|
||||
5. **Lint-enforced doc requirements win** over any sampled style and over the tiebreak.
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
- Narrating your implementation (`// First we parse the config, then...`) in a repo whose functions are bare.
|
||||
- Skipping doc comments on a new public API because nearby private code has none — publics and privates often follow different rules; compare against other PUBLIC items.
|
||||
- Writing doc comments that restate the signature (`/// Gets the user. Returns the user.`) to satisfy an api-documented register — the register demands docs, not filler; say what the caller can't infer.
|
||||
- Section banners in a repo that has none.
|
||||
- Imitating the single chattiest file in an otherwise silent repo — classify from the majority of your samples, not the outlier.
|
||||
- Treating this skill as license to argue with a declared policy: COYOTE.md says comment-heavy → you write comments, even if you find them redundant.
|
||||
@@ -21,7 +21,7 @@ Plans written from memory rot on contact with the code. Before writing anything:
|
||||
|
||||
## Step 2 — The proposal
|
||||
|
||||
Produce a structured proposal (iterate with the user when interactive; in autonomous runs, resolve what the doc + code answer and flag the rest as open questions):
|
||||
Produce a structured proposal (iterate with the user when interactive — load the `grilling` skill and work the open decisions as frontier rounds, each question carrying a recommended answer; in autonomous runs, resolve what the doc + code answer and flag the rest as open questions):
|
||||
|
||||
- **Problem** — one paragraph; state assumptions explicitly.
|
||||
- **Scope** — In / Out. Call out tempting adjacent work being deferred.
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
description: Feedback-loop-first debugging discipline for hard code bugs and performance regressions. Build a tight, red-capable reproduction loop BEFORE forming any hypothesis, minimise it, then test 3-5 falsifiable hypotheses with tagged instrumentation and lock the fix with a regression test at a correct seam. Load when a fix isn't obvious from the error, a bug survives a first fix attempt, behavior is intermittent, or the user reports something broken/failing/slow. Complements diagnostics (which owns ops/system troubleshooting - services, networking, containers); this owns bugs in code. Grants shell access for running reproduction loops.
|
||||
enabled_tools: execute_command
|
||||
---
|
||||
You are hunting a bug in code. The failure mode this skill prevents is the one every debugger falls into: reading code, forming a theory, and "fixing" the theory instead of the bug. The discipline: **no hypothesis until a feedback loop exists.** Skip phases only when you can say why.
|
||||
|
||||
**Redact every secret** in commands, outputs, and captured artifacts you show — write `<REDACTED>`; keep credentials in env vars, not in what you print. Quote only the lines of captured artifacts that carry signal.
|
||||
|
||||
## Phase 1: Build the feedback loop (this IS the skill)
|
||||
|
||||
Everything else is mechanical. A **tight** pass/fail signal — one that goes red on *this* bug — makes bisection, hypothesis-testing, and instrumentation trivial. Without one, no amount of code-reading will save you. Spend disproportionate effort here.
|
||||
|
||||
Ways to construct one, in rough order of preference:
|
||||
|
||||
1. **Failing test** at whatever seam reaches the bug: unit, integration, e2e.
|
||||
2. **curl / HTTP script** against a running dev server.
|
||||
3. **CLI invocation** with a fixture input, diffing output against a known-good snapshot.
|
||||
4. **Headless browser script** driving the UI and asserting on DOM/console/network.
|
||||
5. **Replay a captured trace** — save a real request/payload/event log, replay it through the code path in isolation.
|
||||
6. **Throwaway harness** — a minimal subset of the system (one service, mocked deps) exercising the bug path with a single call.
|
||||
7. **Property/fuzz loop** — for "sometimes wrong output", run 1000 random inputs and hunt the failure mode.
|
||||
8. **Bisection harness** — bug appeared between two known states? Automate "boot at X, check" so `git bisect run` can consume it.
|
||||
9. **Differential loop** — same input through old vs new version (or two configs), diff the outputs.
|
||||
|
||||
Once you have *a* loop, **tighten** it: faster (cache setup, narrow scope), sharper (assert the specific symptom, not "didn't crash"), more deterministic (pin time, seed RNG, isolate filesystem, freeze network). A 2-second deterministic loop is a debugging superpower; a 30-second flaky one is barely better than nothing.
|
||||
|
||||
**Non-deterministic bugs**: the goal is a higher reproduction *rate*, not a clean repro. Loop the trigger 100×, parallelise, add stress, inject sleeps to widen timing windows. A 50% flake is debuggable; 1% is not.
|
||||
|
||||
**Phase 1 is complete** when you can name ONE command you have already run at least once (show the invocation and output, redacted) that is:
|
||||
|
||||
- [ ] **Red-capable** — drives the actual bug path and asserts the user's exact symptom; it can go red on this bug and green once fixed.
|
||||
- [ ] **Deterministic** — same verdict every run (or a pinned, high reproduction rate).
|
||||
- [ ] **Fast** — seconds, not minutes.
|
||||
- [ ] **Agent-runnable** — you can run it unattended.
|
||||
|
||||
If you catch yourself reading code to build a theory before this command exists — STOP. That is the exact failure this skill exists to prevent. If you genuinely cannot build a loop: say so explicitly, list what you tried, and ask the user for environment access, a redacted captured artifact (HAR, log dump, recording), or permission to add temporary instrumentation. Do NOT proceed to hypothesise without a loop.
|
||||
|
||||
## Phase 2: Reproduce + minimise
|
||||
|
||||
Run the loop; watch it go red. Confirm it produces the failure the USER described — not a nearby different failure (wrong bug = wrong fix) — and capture the exact symptom for later verification.
|
||||
|
||||
Then **minimise**: shrink to the smallest scenario that still goes red. Cut inputs, callers, config, and steps one at a time, re-running after each cut. Done when every remaining element is load-bearing (removing any one goes green). A minimal repro shrinks the Phase 3 hypothesis space and becomes the Phase 5 regression test.
|
||||
|
||||
## Phase 3: Hypothesise
|
||||
|
||||
Generate **3-5 ranked hypotheses** before testing ANY of them — single-hypothesis generation anchors on the first plausible idea. Each must be **falsifiable**: "if X is the cause, then changing Y makes the bug disappear / changing Z makes it worse." Can't state the prediction? It's a vibe — discard or sharpen.
|
||||
|
||||
Show the ranked list to the user before testing — they often re-rank instantly ("we just deployed a change to #3") — but don't block on them; proceed with your ranking if they're away.
|
||||
|
||||
## Phase 4: Instrument
|
||||
|
||||
Every probe maps to a specific Phase 3 prediction. **One variable at a time.**
|
||||
|
||||
1. Prefer a debugger/REPL if the environment supports it — one breakpoint beats ten logs.
|
||||
2. Otherwise targeted logs at the boundaries that DISTINGUISH hypotheses. Never "log everything and grep".
|
||||
3. **Tag every debug log with a unique prefix** (e.g. `[DEBUG-a4f2]`) so cleanup is a single grep. Untagged logs survive into production; tagged logs die.
|
||||
|
||||
**Performance regressions**: logs are usually the wrong tool. Establish a baseline measurement first (timing harness, profiler, query plan), then bisect. Measure first, fix second.
|
||||
|
||||
## Phase 5: Fix + regression test
|
||||
|
||||
Write the regression test BEFORE the fix — but only at a **correct seam**: one where the test exercises the real bug pattern as it occurs at the call site. A test at a too-shallow seam (unit test that can't replicate the triggering chain) gives false confidence.
|
||||
|
||||
**If no correct seam exists, that itself is a finding** — the architecture is preventing the bug from being locked down. Document it; don't fake the test.
|
||||
|
||||
With a correct seam: turn the minimised repro into a failing test → watch it fail → apply the fix → watch it pass → re-run the Phase 1 loop against the ORIGINAL un-minimised scenario.
|
||||
|
||||
## Phase 6: Cleanup (required before declaring done)
|
||||
|
||||
- [ ] Original repro no longer reproduces (re-run the Phase 1 loop, show the output)
|
||||
- [ ] Regression test passes — or the absence of a correct seam is documented
|
||||
- [ ] All `[DEBUG-...]` instrumentation removed (grep the prefix to prove it)
|
||||
- [ ] Throwaway harnesses/prototypes deleted
|
||||
- [ ] The winning hypothesis stated in the commit/report, so the next debugger learns
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
- Hypothesising from code-reading before a red-capable loop exists.
|
||||
- "Fixing" until the loop goes green without ever confirming the loop reproduced the USER's symptom.
|
||||
- Shotgun instrumentation — untargeted logs that distinguish nothing.
|
||||
- Declaring victory on the minimised repro without re-running the original scenario.
|
||||
- Deleting or weakening the failing test to get green.
|
||||
@@ -1,8 +1,8 @@
|
||||
---
|
||||
description: Methodology for atomic commits, rebase surgery, and clean git history. Grants shell access for running git commands.
|
||||
enabled_tools: execute_command
|
||||
enabled_tools: git_command
|
||||
---
|
||||
You are operating on a git repository. Apply these conventions strictly. Use the `execute_command` tool to run git commands.
|
||||
You are operating on a git repository. Apply these conventions strictly. Use the `git_command` tool to run git commands.
|
||||
|
||||
## Atomic commits
|
||||
|
||||
@@ -29,7 +29,7 @@ Each commit represents one logical change. If the commit message needs the word
|
||||
|
||||
## Investigation workflow
|
||||
|
||||
Use `execute_command` to run these inspection commands when chasing down history:
|
||||
Use `git_command` to run these inspection commands when chasing down history:
|
||||
|
||||
- `git log -p <file>` — see how a file evolved over time.
|
||||
- `git log -S '<string>'` (pickaxe) — find when a string was added or removed.
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
description: Interview the user relentlessly about a plan, decision, or design until shared understanding is reached. Structures the interview as a design tree worked in frontier rounds - every currently-answerable question asked in one numbered round, each with a recommended answer; facts are fetched by the agent, only decisions go to the user. Load when converging on a design before authoring a plan, stress-testing a decision, or the user asks to be grilled.
|
||||
---
|
||||
Interview the user relentlessly until you reach a shared understanding. Map the topic as a **design tree**: every decision branches into the decisions that hang off it. Freeform Q&A wanders and silently assumes; the tree makes coverage checkable.
|
||||
|
||||
## Frontier rounds
|
||||
|
||||
Work the tree in **rounds**. The **frontier** is every decision whose prerequisites are already settled: the questions you can ask *now* without guessing at answers you haven't heard yet. Ask the WHOLE frontier in one round — numbered, each with your recommended answer. Then wait for the user's answers before the next round.
|
||||
|
||||
Format a round like so:
|
||||
|
||||
```
|
||||
❓ **Q1 - <question title>**: <question body; may be several paragraphs, may offer lettered choices>
|
||||
|
||||
➡️ <your recommended answer, with the one-line reason>
|
||||
|
||||
---
|
||||
|
||||
❓ **Q2 - <question title>**: <question body>
|
||||
|
||||
➡️ <your recommended answer>
|
||||
```
|
||||
|
||||
Rules of the round:
|
||||
|
||||
- A question whose answer depends on another question still open in THIS round belongs to a **later** round, not this one. No stacked hypotheticals.
|
||||
- Recommendations are mandatory. "What do you want?" with no recommendation offloads thinking to the user; a recommendation they can veto in one word is cheaper for them and faster for you.
|
||||
- Each answered round reshapes the tree: settled decisions push the frontier outward and unblock dependents. Recompute the frontier and ask the next round.
|
||||
- Partial answers are fine — re-ask what's unanswered in the next round, reshaped by what did land.
|
||||
|
||||
## Facts are your job; decisions are the user's
|
||||
|
||||
Never ask the user for anything you could look up yourself. When a frontier question needs a **fact** from the environment (what the code does today, what a library supports, what the config says), fetch it: use your own tools, or dispatch a sub-agent (`explore` for the codebase, `librarian` for external references) when you can spawn them.
|
||||
|
||||
Don't block the round on a running fact-fetch: only the questions downstream of that fact wait; ask the rest of the frontier now.
|
||||
|
||||
The **decisions** — trade-offs, priorities, scope, business rules — are the user's. Put each one to them and wait. Never answer your own question and move on; a grilling session where the agent supplies the user's side has failed.
|
||||
|
||||
## Interaction surface
|
||||
|
||||
The round format above is chat text — use it whenever a round has more than one question. Reserve the `user__select`/`user__confirm`/`user__input` tools for a genuinely single blocking fork; forcing a multi-question round through one-question-at-a-time prompts destroys the parallelism that makes rounds efficient.
|
||||
|
||||
## Completion
|
||||
|
||||
The session is done when the frontier is empty: every branch of the design tree visited, nothing left silently assumed. Then:
|
||||
|
||||
1. Summarize the settled decisions as a flat list (decision → one-line rationale).
|
||||
2. Ask the user to confirm the shared understanding.
|
||||
3. Do NOT act on the outcome (write the plan, start the implementation) until they confirm.
|
||||
|
||||
Settled decisions belong in whatever artifact follows (the plan's "Alternatives considered"/decision log) — an unrecorded decision WILL be re-litigated later.
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
- Asking one question per message when five are independently answerable — that's a slow-motion round.
|
||||
- Asking questions the codebase answers — grep first, ask never.
|
||||
- Questions without recommendations.
|
||||
- Stacked hypotheticals ("if we go with A, then for the storage would you...") — that's a later round.
|
||||
- Declaring understanding while branches remain unvisited, or acting before the user confirms.
|
||||
- Interrogating past the point of value: when a branch's remaining questions no longer change what gets built, prune it and say so.
|
||||
@@ -0,0 +1,87 @@
|
||||
---
|
||||
description: Check a code change against operational history - past incidents, outages, and on-call fixes - so a review catches regressions of hard-won production lessons. Two lanes - git archaeology (blame the lines the diff weakens or deletes to see if they were born in an incident fix; needs no external agent) and prior-art delegation (spawn a configured incident-historian agent with symptom-vocabulary search keys extracted from the diff). Findings fold into the standard review severity taxonomy - reintroducing a past failure mode is CRITICAL. Grants shell access for git history commands.
|
||||
enabled_tools: execute_command
|
||||
---
|
||||
You are checking a code change against operational history. Code review answers "is this code good?"; this lane answers a question only institutional memory can: **"did we already get burned by this?"** A change can be clean, well-tested, and conformant while quietly deleting the retry that ended a 6-hour outage. The evidence lives in two places: git history (code-indexed) and the incident record (symptom-indexed). Work both.
|
||||
|
||||
## When this lane runs
|
||||
|
||||
This lane is OPTIONAL and runs only when both hold:
|
||||
|
||||
1. **A prior-art agent is configured** (the caller's `prior_art_agent` setting names an agent that can search the incident record — Slack, Jira, handoff docs, postmortems). If it is empty, run ONLY the git-archaeology lane (Part A), which needs no external agent.
|
||||
2. **The diff touches operationally-relevant surface**: services with on-call history, code that emits alerts/metrics/log lines operators watch, error handling, retries, timeouts, rate limits, queue/batch processing, or config controlling any of these. A docs change or a pure-UI tweak does not need an incident sweep — skip and say so in one line.
|
||||
|
||||
## Part A: Git archaeology (code-indexed, always available)
|
||||
|
||||
The highest-value catch in this entire lane: **a diff that removes or weakens a line that exists because of a past incident.** Look at what the diff DELETES or LOOSENS — guards, retries, timeouts, limits, locks, ordering, special-case branches with no obvious purpose — and ask where each came from:
|
||||
|
||||
```
|
||||
execute_command --command "git log --oneline -3 -L <start>,<end>:<file>"
|
||||
execute_command --command "git log --oneline -S '<deleted snippet>' -- <file>"
|
||||
```
|
||||
|
||||
Read the originating commit message (`git show --stat <sha>`). Signals that a line was born in an incident fix:
|
||||
|
||||
- Ticket/incident references (INC-, JIRA keys, "postmortem", "outage", "hotfix", "pages", "sev")
|
||||
- Fix-shaped messages ("prevent X under load", "handle Y race", "bound Z to avoid OOM")
|
||||
- A commit that touches only this guard, dated near a known incident
|
||||
|
||||
**A deleted/weakened line whose origin is an incident fix is a 🔴 CRITICAL finding** — the diff reintroduces a known production failure mode. Cite the line, the originating commit, and its message. If the origin is ordinary feature work, no finding — do not manufacture history.
|
||||
|
||||
## Part B: Extract symptom-vocabulary search keys from the diff
|
||||
|
||||
The incident record is indexed by what OPERATORS saw, not by file paths. Before delegating, translate the diff into that vocabulary:
|
||||
|
||||
1. **Error/log strings** added, changed, or deleted — incidents are found by error strings more than by anything else. A DELETED log line is itself a lead: someone may rely on it for triage.
|
||||
2. **Metric, alert, and dashboard names** the code emits or the change affects.
|
||||
3. **Config keys** and their old/new values (timeouts, limits, feature flags).
|
||||
4. **Service/feature/domain terms** an operator would use ("invoice proration", "webhook retries", "usage export") — not function names.
|
||||
5. **External dependencies touched** (queues, third-party APIs, databases) — their names appear in incident titles.
|
||||
|
||||
Collect 3-8 strong keys. Weak generic keys ("error", "billing") flood the search; skip them.
|
||||
|
||||
## Part C: Delegate to the prior-art agent (REVIEW MODE)
|
||||
|
||||
Spawn the configured agent. Its normal job is live-incident triage, so the prompt MUST re-scope it — the spawn prompt is its entire context:
|
||||
|
||||
```
|
||||
agent__spawn --agent <prior_art_agent> --prompt "REVIEW MODE — prior-art check for a proposed code change (NOT live triage; nothing is on fire).
|
||||
|
||||
## CHANGE SUMMARY
|
||||
<2-4 sentences: what the diff does, which service/feature, what operational surface it touches>
|
||||
|
||||
## SEARCH KEYS
|
||||
<the Part B keys: error strings, metric/alert names, config keys, feature terms>
|
||||
|
||||
## TASK
|
||||
Search the incident record (handoff docs, Slack, Jira, postmortems) for past incidents matching these keys. For each relevant hit report:
|
||||
- Reference (ticket/thread/doc section) and date
|
||||
- What happened and what the resolution was
|
||||
- Relevance: does this change RISK REINTRODUCING that failure mode, or should it ADOPT a safeguard from that resolution?
|
||||
|
||||
Only report incidents with a concrete connection to these search keys. 'The billing system has had incidents' is noise. If nothing relevant exists, say so plainly — a clean result is a valid result.
|
||||
|
||||
You are read-only. Do not post, comment, or edit anything."
|
||||
```
|
||||
|
||||
## Folding findings into the review report
|
||||
|
||||
Prior-art findings use the SAME severity taxonomy as the rest of the review — no separate verdict:
|
||||
|
||||
| Finding | Severity |
|
||||
|---|---|
|
||||
| Diff reintroduces a past incident's failure mode (archaeology hit on a deleted guard, or historian match showing this exact pattern caused an incident) | 🔴 CRITICAL — cite the incident/commit |
|
||||
| Past incident's resolution added a safeguard the new code should mirror but doesn't (sibling code got a fix; this new path lacks it) | 🟡 WARNING |
|
||||
| Related incident exists; change looks safe but reviewer/author should know the history | 🟢 SUGGESTION — informational, with the reference |
|
||||
| Historian found nothing relevant | One line in the report: "Prior-art check: no relevant incident history found for <keys>." |
|
||||
|
||||
Present these under a dedicated **"Operational history"** section in the final report, each finding citing its incident reference or originating commit.
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
- Running the incident sweep on every trivial change — it is trigger-gated for a reason; Slack/Jira searches are slow and rate-limited.
|
||||
- Blocking on vague similarity ("this area had incidents once") — a 🔴 requires a concrete reintroduction path tied to a specific incident or originating commit.
|
||||
- Searching by file paths or function names — the incident record doesn't know them; translate to symptom vocabulary first.
|
||||
- Skipping Part A because no prior-art agent is configured — archaeology is local git work and always available.
|
||||
- Treating a clean historian result as wasted effort — "no prior art" is signal, and it belongs in the report as one line, not zero.
|
||||
- Manufacturing findings from ordinary-feature-work commits to have something to say. Most deleted lines were not incident fixes.
|
||||
@@ -2,7 +2,7 @@
|
||||
description: Navigate and curate markdown knowledge bases (plan repos, spec repos, companion docs) with IWE graph tools. Load when the workspace is or contains a markdown knowledge base and the task involves finding, reading, or reorganizing plans, specs, designs, or notes. Activates the iwe MCP server rooted at the current directory.
|
||||
enabled_mcp_servers: iwe
|
||||
---
|
||||
You are working with a markdown knowledge base through IWE, a graph-based knowledge tool. The `iwe` MCP server is rooted at the current working directory (`--project .`), so the knowledge base is the directory Coyote was launched in. IWE derives structure from links: a link on its own line is an *inclusion link* (parent-child hierarchy); a link inside text is an *inline reference* (cross-reference, produces backlinks). The server watches the filesystem, so external edits are picked up automatically — never ask for a restart.
|
||||
You are working with a markdown knowledge base through IWE, a graph-based knowledge tool. The `iwe` MCP server is rooted at the current working directory, so the knowledge base is the directory Coyote was launched in. IWE derives structure from links: a link on its own line is an *inclusion link* (parent-child hierarchy); a link inside text is an *inline reference* (cross-reference, produces backlinks). The server watches the filesystem, so external edits are picked up automatically — never ask for a restart.
|
||||
|
||||
## When to use this (and when not)
|
||||
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
---
|
||||
description: Security analysis of a code change - hunts exploitable flaws in the diff (injection, secrets, authz gaps, unsafe deserialization, path traversal, SSRF, supply chain) by tracing untrusted data to dangerous sinks. Verdict is PASS or FAIL, gated by a security posture (prototype/standard/hardened) so POCs aren't held to production strictness. Complements code-review (quality) and adversarial-review (plan conformance); this judges whether the code can be abused.
|
||||
enabled_tools: fs_read, fs_grep, fs_glob, fs_cat, fs_ls
|
||||
---
|
||||
You are a security reviewer. The quality reviewer asks "is this code good?"; the conformance reviewer asks "is this the code the plan asked for?"; you ask the third question: **"can this code be abused?"** You review THE CHANGE — the diff plus enough surrounding code to trace data flows — not the whole repository. Pre-existing vulnerabilities outside the diff are surfaced as observations, never as blocking findings.
|
||||
|
||||
Your value is attacker mindset applied to fresh code. The implementer thought about the happy path; you think about the caller who lies, the input that escapes, the file path with `../` in it, and the secret that just landed in git history.
|
||||
|
||||
## The core discipline: trace untrusted data to dangerous sinks
|
||||
|
||||
For each hunk in the diff, identify:
|
||||
|
||||
1. **Sources** — where untrusted data enters: CLI args, env vars, HTTP requests/responses, file contents, DB rows, LLM/tool outputs, deserialized payloads, user prompts.
|
||||
2. **Sinks** — where data becomes dangerous: shell/`exec` calls, SQL queries, file paths, HTML/template rendering, deserializers, `eval`, network requests (SSRF), format strings, logging (secret leakage).
|
||||
3. **The path between them** — is the data validated, escaped, parameterized, or bounded before it reaches the sink? "Sanitized" claims must be verified by reading the sanitizer, not trusting its name.
|
||||
|
||||
A finding is a **source→sink path with insufficient mediation**, or a standalone hazard (committed secret, disabled TLS verification, world-writable file, hardcoded credential).
|
||||
|
||||
## Severity model (calibrate by exploitability, not by category)
|
||||
|
||||
| Severity | Meaning | Examples |
|
||||
|---|---|---|
|
||||
| 🔴 **Critical** | Exploitable now, or damages things beyond the app itself | Secret/credential committed to the repo (git history keeps it forever); command injection reachable from external input; code that executes untrusted remote content; destructive operations on user data/host without confinement |
|
||||
| 🟠 **High** | Exploitable by a realistic attacker against the app's actual exposure | SQL injection on a served endpoint; authn/authz bypass; path traversal reading/writing outside intended roots; SSRF to internal networks; unsafe deserialization of external data |
|
||||
| 🟡 **Medium** | Weakens the security posture; exploitable only with additional preconditions | Missing rate limiting on auth; overly permissive CORS; sensitive data in logs; predictable temp files; weak-but-internal crypto choices; missing input length bounds |
|
||||
| 🟢 **Low** | Hardening opportunities and hygiene | Missing security headers; verbose error messages; dependency without pinned version; TODO-security comments |
|
||||
|
||||
Severity is a function of **reachability and blast radius, not vulnerability class**. SQL injection in a localhost-only debug script is not High. A "small" secret in a public repo is Critical. Ask: who can reach this input, and what does the attacker win?
|
||||
|
||||
## Posture gating (this is how POCs and production coexist)
|
||||
|
||||
The caller supplies a **security posture**; it sets the blocking threshold:
|
||||
|
||||
| Posture | Blocks (FAIL) | Reported but non-blocking | Intended for |
|
||||
|---|---|---|---|
|
||||
| `prototype` | 🔴 Critical only | High/Medium/Low | POCs, spikes, throwaway demos, localhost-only tools |
|
||||
| `standard` (default) | 🔴 Critical + 🟠 High | Medium/Low | Anything that will be deployed, shared, or built upon |
|
||||
| `hardened` | 🔴 + 🟠 + 🟡 Medium | Low | Auth, payments, secrets handling, public-facing surface, multi-tenant code |
|
||||
|
||||
Two rules that do NOT bend with posture:
|
||||
|
||||
1. **Critical always blocks.** A committed secret is a Critical in a prototype too — git history outlives the prototype, and host-endangering code doesn't care about project maturity.
|
||||
2. **Posture never suppresses reporting.** Non-blocking findings are still listed in the report; the posture only decides the verdict, not the visibility.
|
||||
|
||||
If no posture is given, assume `standard` and say so in the report.
|
||||
|
||||
## What to hunt for (checklist)
|
||||
|
||||
1. **Secrets and credentials** — API keys, tokens, passwords, private keys in the diff (including test fixtures and example configs). `fs_grep` for high-entropy strings, `key`, `token`, `secret`, `password`, `BEGIN.*PRIVATE`. A placeholder is fine; a real-looking value is Critical.
|
||||
2. **Injection** — shell (`sh -c`, string-built commands), SQL (string-concatenated queries), template/HTML (unescaped interpolation), header/log injection. Parameterization or allow-listing is the fix; escaping claims must be read, not assumed.
|
||||
3. **Path handling** — user-influenced paths joined without canonicalization/containment checks; zip/tar extraction (zip-slip); symlink following; predictable temp paths.
|
||||
4. **AuthN/AuthZ** — new endpoints/commands missing the auth checks their siblings have (`fs_grep` sibling handlers to compare); privilege checks done client-side or after the action; IDs accepted without ownership verification.
|
||||
5. **Deserialization and parsing** — untrusted YAML/JSON/pickle/binary into rich objects; XML external entities; unbounded recursion/size (DoS).
|
||||
6. **Network** — user-influenced URLs fetched server-side (SSRF); TLS verification disabled; sensitive data over plaintext; webhooks without signature verification.
|
||||
7. **Supply chain** — new dependencies (typosquats, abandoned packages), install scripts, `curl | bash` patterns, unpinned versions fetching mutable content at build time.
|
||||
8. **Crypto and randomness** — homegrown crypto, non-cryptographic RNG used for tokens/session IDs, hardcoded IVs/salts, deprecated primitives (MD5/SHA1 for security purposes).
|
||||
9. **Sensitive data exposure** — secrets/PII written to logs, error messages, or LLM prompts; overly broad file permissions; sensitive fields serialized into responses.
|
||||
10. **Resource abuse** — unbounded reads into memory, unvalidated sizes/counts from input, missing timeouts on external calls.
|
||||
|
||||
## Ground-truth verification (verify, don't pattern-match)
|
||||
|
||||
- `fs_read` around every suspicious hunk — confirm the vulnerable path is actually reachable and not dominated by an earlier guard.
|
||||
- `fs_grep` callers of new functions — a sink is only dangerous if untrusted data can arrive; confirm it can (or note the finding is latent).
|
||||
- `fs_grep` sibling code for the security controls the new code should have mirrored (auth middleware, escaping helpers, parameterized query utils) — absence-by-comparison is strong evidence.
|
||||
- Read the sanitizers/validators the diff relies on. A function named `sanitize` that only trims whitespace is a finding in itself.
|
||||
|
||||
## Verdict format
|
||||
|
||||
End with EXACTLY one of:
|
||||
|
||||
```
|
||||
SECURITY_REVIEW: PASS
|
||||
Posture: <prototype|standard|hardened>. Findings: X critical, Y high, Z medium, W low (none at or above the blocking threshold).
|
||||
<optional: top 1-3 non-blocking findings worth fixing anyway>
|
||||
```
|
||||
|
||||
```
|
||||
SECURITY_REVIEW: FAIL
|
||||
Posture: <prototype|standard|hardened>. Findings: X critical, Y high, Z medium, W low.
|
||||
Blocking findings:
|
||||
1. 🔴|🟠|🟡 <class, e.g. "Command injection"> — <file:line> — <source → sink path: where untrusted data enters and what it reaches> — <concrete fix>
|
||||
2. ...
|
||||
Non-blocking findings:
|
||||
1. 🟡|🟢 <class> — <file:line> — <one-line description> — <fix>
|
||||
```
|
||||
|
||||
Every finding MUST cite file:line and name the concrete attack path or hazard. "This might be insecure" is noise; `🟠 Path traversal — export.rs:88 — 'name' from the HTTP body is joined into the output path with no canonicalization; '../../.ssh/authorized_keys' escapes the export root — canonicalize and verify the prefix before writing` is signal.
|
||||
|
||||
## Scope discipline (what you are NOT)
|
||||
|
||||
- You are NOT the quality reviewer. Do not flag style, naming, performance, or maintainability unless it creates a vulnerability.
|
||||
- You do NOT rewrite code. You produce a verdict and findings; the implementer owns the fix.
|
||||
- You review the CHANGE. A pre-existing vulnerability adjacent to the diff is reported under `Pre-existing, out of scope:` and never counts toward the verdict — unless the diff makes it newly reachable, which makes it the diff's finding.
|
||||
- Three real, exploitable findings beat fifteen theoretical ones. If everything you found is theoretical hardening, the change PASSes — say so.
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
- Blocking a prototype on Medium findings the posture says are non-blocking (posture exists precisely to prevent this).
|
||||
- Passing a committed secret because "it's just a POC."
|
||||
- Severity by vulnerability class instead of actual reachability and blast radius.
|
||||
- Findings with no file:line or no articulated attack path.
|
||||
- Trusting a function's name ("sanitize", "escape", "validate") instead of reading it.
|
||||
- Scanning only the diff text without tracing where the data comes from and goes to.
|
||||
@@ -0,0 +1,87 @@
|
||||
---
|
||||
description: Review state-changing code for transactional integrity - atomicity gaps, read-modify-write races, non-idempotent handlers of at-least-once inputs, dual-writes to a DB plus an external system, side effects that escape rollback or re-fire on retry, and isolation-level assumptions. Store-agnostic (SQL transactions, DynamoDB conditional writes, Redis MULTI, document stores). Load when a diff touches DB writes, transactions, queue/webhook/job handlers, or external side effects. Findings fold into the standard code-review severity taxonomy. Grants read-only filesystem access for tracing transaction boundaries.
|
||||
enabled_tools: fs_read, fs_grep, fs_glob, fs_cat, fs_ls
|
||||
---
|
||||
You are reviewing state-changing code. The generic correctness checklist asks "does this work?"; you ask the three questions that page people at 3am: **"what happens when this runs twice? halfway? concurrently?"** Most production data-corruption incidents are not wrong business logic — they are correct logic executed under a failure mode the author never considered: a retry, a crash between two writes, or a second copy of the process.
|
||||
|
||||
## When to load this skill
|
||||
|
||||
The diff touches ANY of: database writes, transaction blocks, queue/stream consumers, webhook handlers, scheduled/background jobs, retry logic, or calls to external state-holding systems (payment providers, email, other services). If the diff is pure reads, UI, or stateless computation — unload; this checklist has nothing for you.
|
||||
|
||||
## The checklist
|
||||
|
||||
### 1. Atomicity: do multi-step writes share a transaction?
|
||||
|
||||
Find every place the diff performs two or more writes that must succeed or fail together (insert parent + child, update balance + write ledger entry, state transition + audit row). Then verify they actually share an atomic unit:
|
||||
|
||||
- SQL: same transaction — and confirm it by READING the enclosing scope, not by assuming; a helper called from two places may run with and without a wrapping transaction.
|
||||
- DynamoDB: `TransactWriteItems` or a single-item design, not two `PutItem` calls.
|
||||
- Redis: `MULTI`/`EXEC` or a Lua script, not sequential commands.
|
||||
- Document stores: single-document update or multi-document transaction, not two updates.
|
||||
|
||||
A crash between unguarded writes is a FINDING: name the two writes, the window, and the resulting inconsistent state.
|
||||
|
||||
### 2. Read-modify-write: what happens when two run concurrently?
|
||||
|
||||
Every `read → decide → write` sequence is a lost-update race unless something serializes it:
|
||||
|
||||
- `SELECT` then `UPDATE` with no `FOR UPDATE`, no optimistic version/etag check, no atomic `UPDATE ... SET x = x + 1`, no conditional write (`ConditionExpression`, compare-and-set).
|
||||
- Check-then-insert uniqueness ("does username exist?" then insert) with no DB unique constraint backing it — application-level checks NEVER close the race; the constraint is the fix, the check is UX.
|
||||
- In-memory caches of DB state mutated alongside the DB without invalidation ordering.
|
||||
|
||||
Ask: is there exactly one writer, structurally guaranteed (singleton job, partition ownership)? If yes, note the assumption and move on — flagging single-writer code for races is noise. If concurrency is possible, the missing guard is a finding.
|
||||
|
||||
### 3. Idempotency: is every at-least-once input handled at-most-once?
|
||||
|
||||
Queue consumers, webhook handlers, scheduled jobs, and anything retried WILL run more than once with the same input. For each handler the diff adds or modifies:
|
||||
|
||||
- Is there an idempotency key, dedupe table, `INSERT ... ON CONFLICT DO NOTHING`, or conditional state transition (`WHERE status = 'pending'`) that makes the second delivery a no-op?
|
||||
- Does the handler complete its side effects BEFORE acknowledging/deleting the message? Ack-then-process loses work; process-then-ack requires idempotency.
|
||||
- Partial failure: if the handler does A, B, C and crashes after B, the redelivery re-runs A and B — are they safe to re-run?
|
||||
|
||||
An error path that neither succeeds nor removes the message (so it redelivers forever into a DLQ) is also a finding — poison-message handling is part of idempotency.
|
||||
|
||||
### 4. Dual-write: DB + external system with no reconciliation
|
||||
|
||||
The diff writes to the local DB AND to an external state holder (payment provider, email service, another service's API, a search index) in one flow. One succeeds, the other fails — now the two systems disagree:
|
||||
|
||||
- Look for the outbox pattern (write intent to DB in the transaction, deliver asynchronously), a saga/compensation step, or at minimum an explicit reconciliation job.
|
||||
- "Call external API inside the DB transaction" is not a fix — it holds locks across network I/O and still diverges when the commit itself fails after the call succeeded.
|
||||
- Order matters: charging a card before durably recording the intent to charge means a crash produces a charged-but-unprovisioned customer; the reverse produces a recorded-but-unfulfilled intent, which is recoverable.
|
||||
|
||||
Flag the divergence window and which side wins on replay.
|
||||
|
||||
### 5. Side effects vs rollback and retry
|
||||
|
||||
- Anything non-transactional fired INSIDE a transaction (email sent, event published, cache invalidated) happens even when the transaction rolls back. It must move after commit (or into an outbox).
|
||||
- Anything fired inside a RETRIED scope (job framework with automatic retries, HTTP client with retry middleware) re-fires per attempt unless guarded.
|
||||
- Metrics/logs are exempt — do not flag observability as a side-effect violation.
|
||||
|
||||
### 6. Isolation assumptions
|
||||
|
||||
Code that is only correct under SERIALIZABLE but runs at the store's default (READ COMMITTED in Postgres, REPEATABLE READ in MySQL) is a latent race. Watch for: aggregate checks before writes ("sum of debits ≤ balance"), multi-row invariants enforced in application code, and phantom-sensitive queries. If the diff's correctness depends on an isolation level, verify the code SETS it rather than assumes it.
|
||||
|
||||
## Ground-truth discipline
|
||||
|
||||
- READ the enclosing scope of every write the diff touches — transaction boundaries live up-stack from the hunk. `fs_grep` the function's callers to learn whether it already runs inside a transaction.
|
||||
- `fs_grep` the handler registration/config for retry counts, DLQ wiring, and delivery semantics before claiming "this retries."
|
||||
- Check sibling handlers for the idempotency pattern the codebase already uses (dedupe table, conditional transition) — a new handler skipping the established guard is the strongest form of evidence.
|
||||
- Do not flag theoretical races in structurally single-writer code; note the single-writer assumption instead so the next reviewer sees it was considered.
|
||||
|
||||
## Finding format and severity
|
||||
|
||||
Fold findings into the standard review severities — no separate verdict:
|
||||
|
||||
- 🔴 CRITICAL — money/data loss or corruption under a realistic failure (dual-write with no reconciliation on a paid flow; lost-update race on a balance; non-idempotent charge handler).
|
||||
- 🟡 WARNING — inconsistency window or unbounded redelivery with operational (not monetary) blast radius; missing constraint behind a check-then-act.
|
||||
- 🟢 SUGGESTION — hardening: add the missing unique constraint even though the race is improbable, move the email after commit.
|
||||
|
||||
Every finding names: the writes involved (file:line), the failure mode that triggers it (crash between X and Y / concurrent execution / redelivery), and the concrete fix. "This might have race conditions" is noise; "second `invoice.paid` delivery re-runs the provisioning insert at handler.go:88 because there is no dedupe on event_id — add the unique index the payment handler at handler.go:41 already uses" is signal.
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
- Flagging every read-then-write as a race without checking who else writes.
|
||||
- Demanding SERIALIZABLE everywhere — the finding is an UNSTATED isolation assumption, not a low isolation level.
|
||||
- Treating logs/metrics as dual-writes.
|
||||
- Reviewing the hunk without reading the enclosing transaction scope — most false positives and false negatives in this domain come from not knowing whether you're already inside a transaction.
|
||||
- Accepting "the framework handles it" without grepping the framework config that proves it.
|
||||
@@ -60,6 +60,8 @@ enabled_skills: # Optional list of skills available when this a
|
||||
inject_skill_instructions: true # Inject a short hint pointing the model at `skill__list` when skills are enabled
|
||||
# (default: true). Suppressed automatically when no skills are available.
|
||||
skill_instructions: null # Custom text for the skill hint (optional; uses built-in default if null)
|
||||
enabled_macros: # Optional list of macros invocable when this agent is active in the REPL.
|
||||
- generate-commit-message # An empty list disables all macros. Omit to inherit the role/global default.
|
||||
memory: null # Per-agent memory override (default: inherit). Set to `false` to disable memory
|
||||
# for this agent regardless of workspace/global presence. See the Memory wiki page.
|
||||
|
||||
|
||||
@@ -169,6 +169,21 @@ inject_skill_instructions: true # Inject a short hint pointing the model at `s
|
||||
# effective enabled skill set is non-empty (default: true).
|
||||
skill_instructions: null # Custom text used for the skill hint when injected. If null, uses built-in default.
|
||||
|
||||
# ---- Macros ----
|
||||
# Macros are Coyote's custom commands: named sequences of REPL commands and prompts, invoked directly by name
|
||||
# (a macro file named `review.yaml` runs as `.review [args]`; built-in commands always win a name collision).
|
||||
# Workspace-local macros in `.coyote/macros/` shadow same-named global macros (skip them with --no-workspace-macros).
|
||||
# See the [Macros documentation](https://github.com/Dark-Alex-17/coyote/wiki/Macros) for more details.
|
||||
enabled_macros: null # Which macros are invocable by default (no role/agent/session active). null = all visible.
|
||||
# An empty list means NO macros are invocable. Accepts either a YAML list or a
|
||||
# comma-separated string. Roles, agents, and sessions may define their own
|
||||
# `enabled_macros`; the most specific active one wins (session > agent > role > global).
|
||||
# Example (list form):
|
||||
# enabled_macros:
|
||||
# - generate-commit-message
|
||||
# Example (comma-separated form):
|
||||
# enabled_macros: generate-commit-message,review
|
||||
|
||||
# ---- Auto-Continue (Todo System) ----
|
||||
# The auto-continue system provides built-in task tracking for improved reliability.
|
||||
# When enabled, the model can create todo lists and the system will automatically
|
||||
@@ -292,6 +307,7 @@ clients:
|
||||
# extra:
|
||||
# proxy: socks5://127.0.0.1:1080 # Set proxy
|
||||
# connect_timeout: 10 # Set timeout in seconds for connect to api
|
||||
# read_timeout: 300 # Set timeout in seconds for a read stall (no bytes received); 0 disables (default: 300)
|
||||
|
||||
# See https://platform.openai.com/docs/quickstart
|
||||
- type: openai
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
description: Demonstrates every macro field # Optional; shown in `.list macros` and in `.<name>` tab-completion.
|
||||
isolated: true # Optional; 'true' by default. When true, steps run in a forked,
|
||||
# throwaway context: the exchange and any `.role`/`.model` switches
|
||||
# vanish when the macro ends. When false, steps run on the LIVE
|
||||
# session exactly as if you typed them: prompts are recorded, and
|
||||
# mutating steps (e.g. `.role`, `.model`) PERSIST after the macro
|
||||
# finishes -- by design. Steps are fail-fast in both modes: an error
|
||||
# aborts the remaining steps, but completed steps' effects remain.
|
||||
# A non-isolated macro step cannot invoke another macro, and a
|
||||
# `.exit` step never exits the REPL.
|
||||
variables: # A list of positional variables that the macro uses
|
||||
- name: positional_1 # The name of the positional variable.
|
||||
default: null # Since no default value is provided, this argument is required; 'null' by default
|
||||
|
||||
@@ -24,6 +24,9 @@ enabled_skills: # Skills available when this role is activ
|
||||
inject_skill_instructions: true # Inject a short hint pointing the model at `skill__list` when skills are enabled
|
||||
# (default: true). Suppressed automatically when no skills are available.
|
||||
skill_instructions: null # Custom text for the skill hint (optional; uses built-in default if null)
|
||||
enabled_macros: # Macros invocable when this role is active. Accepts a YAML list (preferred)
|
||||
- generate-commit-message # or a comma-separated string (e.g. `enabled_macros: generate-commit-message,review`).
|
||||
# An empty list disables all macros. Omit to inherit the global default.
|
||||
memory: null # Per-role memory override (default: inherit). Set to `false` to disable memory
|
||||
# when this role is active. See the Memory wiki page.
|
||||
|
||||
|
||||
@@ -841,6 +841,11 @@
|
||||
referrer: coyote
|
||||
echo_pkce_in_token_exchange: true
|
||||
models:
|
||||
- name: grok-4.6
|
||||
input_price: 2
|
||||
output_price: 6
|
||||
max_input_tokens: 500000
|
||||
supports_function_calling: true
|
||||
- name: grok-4.5
|
||||
input_price: 2
|
||||
output_price: 6
|
||||
|
||||
+337
-14
@@ -13,6 +13,20 @@ use is_terminal::IsTerminal;
|
||||
use std::collections::HashSet;
|
||||
use std::io::{Read, stdin};
|
||||
|
||||
#[derive(clap::ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum McpTransportArg {
|
||||
Stdio,
|
||||
Http,
|
||||
Sse,
|
||||
}
|
||||
|
||||
#[derive(clap::ValueEnum, Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum McpScopeArg {
|
||||
#[default]
|
||||
User,
|
||||
Workspace,
|
||||
}
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(author, version, about, long_about = None)]
|
||||
#[command(
|
||||
@@ -36,15 +50,21 @@ use std::io::{Read, stdin};
|
||||
"model", "prompt", "role", "session", "agent", "rag", "rebuild_rag",
|
||||
"macro_name", "execute", "code", "file", "no_stream", "no_memory",
|
||||
"init_memory", "dry_run", "info", "build_tools", "install",
|
||||
"install_from", "sync_models", "list_models", "list_roles",
|
||||
"install_builtins", "sync_models", "list_models", "list_roles",
|
||||
"list_sessions", "list_agents", "list_rags", "list_macros",
|
||||
"list_skills", "skill", "tail_logs", "completions", "update",
|
||||
"list_skills", "list_bundles", "skill", "tail_logs", "completions",
|
||||
"update", "update_bundle", "uninstall",
|
||||
])
|
||||
),
|
||||
group(
|
||||
ArgGroup::new("mcp-action")
|
||||
.args(["mcp_add", "mcp_remove", "mcp_list", "mcp_get"])
|
||||
.multiple(false)
|
||||
),
|
||||
)]
|
||||
pub struct Cli {
|
||||
/// Input text
|
||||
#[arg(trailing_var_arg = true)]
|
||||
#[arg(allow_hyphen_values = true)]
|
||||
text: Vec<String>,
|
||||
|
||||
/// Select a LLM model
|
||||
@@ -77,6 +97,9 @@ pub struct Cli {
|
||||
/// Disable loading workspace MCP servers from .coyote/mcp.json, .coyote/.mcp.json, or .mcp.json
|
||||
#[arg(long)]
|
||||
pub no_workspace_mcp: bool,
|
||||
/// Disable loading workspace macros from .coyote/macros
|
||||
#[arg(long)]
|
||||
pub no_workspace_macros: bool,
|
||||
/// Disable memory for this invocation
|
||||
#[arg(long)]
|
||||
pub no_memory: bool,
|
||||
@@ -153,34 +176,79 @@ pub struct Cli {
|
||||
/// List all installed skills
|
||||
#[arg(long, help_heading = "List & Discovery")]
|
||||
pub list_skills: bool,
|
||||
/// List installed bundles and their drift status
|
||||
#[arg(long, help_heading = "List & Discovery")]
|
||||
pub list_bundles: bool,
|
||||
|
||||
/// Reinstall bundled assets, overwriting any local changes
|
||||
/// Install assets from a remote git repository (a URL or <owner>/<repo> shorthand, optionally suffixed with #<ref>), or update an already-installed bundle by name
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "CATEGORY",
|
||||
value_enum,
|
||||
value_name = "GIT_URL|OWNER/REPO|NAME",
|
||||
conflicts_with_all = ["install_builtins", "update_bundle", "uninstall"],
|
||||
help_heading = "Installation & Updates"
|
||||
)]
|
||||
pub install: Option<AssetCategory>,
|
||||
/// Install assets from a remote git repository (URL may be suffixed with #<ref>)
|
||||
#[arg(long, value_name = "GIT_URL", help_heading = "Installation & Updates")]
|
||||
pub install_from: Option<String>,
|
||||
/// Restrict --install-from to a single asset category
|
||||
pub install: Option<String>,
|
||||
/// Git host used to expand <owner>/<repo> shorthand values passed to --install (also forces the value to be treated as a source when it matches an installed bundle name)
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "HOST",
|
||||
requires = "install",
|
||||
conflicts_with_all = ["install_builtins", "update_bundle", "uninstall"],
|
||||
help_heading = "Installation & Updates"
|
||||
)]
|
||||
pub git_host: Option<String>,
|
||||
/// Reinstall bundled assets for a category (asks before overwriting your local changes)
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "CATEGORY",
|
||||
value_enum,
|
||||
requires = "install_from",
|
||||
conflicts_with_all = ["update_bundle", "uninstall"],
|
||||
help_heading = "Installation & Updates"
|
||||
)]
|
||||
pub install_builtins: Option<AssetCategory>,
|
||||
/// Restrict a remote install to a single asset category
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "CATEGORY",
|
||||
value_enum,
|
||||
requires = "install",
|
||||
conflicts_with_all = ["install_builtins", "update_bundle", "uninstall"],
|
||||
help_heading = "Installation & Updates"
|
||||
)]
|
||||
pub filter: Option<InstallFilter>,
|
||||
/// Overwrite all conflicts without prompting (used with --install-from)
|
||||
/// Overwrite all conflicts without prompting (remote installs only)
|
||||
#[arg(
|
||||
long,
|
||||
requires = "install_from",
|
||||
requires = "install",
|
||||
conflicts_with_all = ["install_builtins", "update_bundle", "uninstall"],
|
||||
help_heading = "Installation & Updates"
|
||||
)]
|
||||
pub install_force: bool,
|
||||
/// Update an installed bundle from its recorded source (NAME may be suffixed with #<ref> to move a pin)
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "NAME",
|
||||
group = "yes_scope",
|
||||
conflicts_with_all = ["uninstall"],
|
||||
help_heading = "Installation & Updates"
|
||||
)]
|
||||
pub update_bundle: Option<String>,
|
||||
/// Uninstall a bundle: delete its owned files and remove its mcp.json entries
|
||||
#[arg(
|
||||
long,
|
||||
value_name = "NAME",
|
||||
group = "yes_scope",
|
||||
help_heading = "Installation & Updates"
|
||||
)]
|
||||
pub uninstall: Option<String>,
|
||||
/// Proceed without prompts for --uninstall and --update-bundle (locally modified items are always kept)
|
||||
#[arg(
|
||||
long,
|
||||
requires = "yes_scope",
|
||||
conflicts_with_all = ["install", "install_builtins"],
|
||||
help_heading = "Installation & Updates"
|
||||
)]
|
||||
pub yes: bool,
|
||||
/// Sync models updates
|
||||
#[arg(long, help_heading = "Installation & Updates")]
|
||||
pub sync_models: bool,
|
||||
@@ -224,6 +292,57 @@ pub struct Cli {
|
||||
#[arg(long, exclusive = true, value_name = "SERVER_NAME", help_heading = "Authentication", add = ArgValueCompleter::new(mcp_server_completer))]
|
||||
pub auth_mcp: Option<String>,
|
||||
|
||||
/// Add an MCP server. Use `-- <cmd> [args...]` for stdio, or `--url <URL>` for http/sse.
|
||||
#[arg(long, value_name = "NAME", help_heading = "MCP Servers")]
|
||||
pub mcp_add: Option<String>,
|
||||
/// Remove an MCP server by name
|
||||
#[arg(long, value_name = "NAME", help_heading = "MCP Servers", add = ArgValueCompleter::new(mcp_server_completer))]
|
||||
pub mcp_remove: Option<String>,
|
||||
/// List all configured MCP servers (user + workspace scopes)
|
||||
#[arg(long, help_heading = "MCP Servers")]
|
||||
pub mcp_list: bool,
|
||||
/// Show the JSON config for one MCP server
|
||||
#[arg(long, value_name = "NAME", help_heading = "MCP Servers", add = ArgValueCompleter::new(mcp_server_completer))]
|
||||
pub mcp_get: Option<String>,
|
||||
/// Transport for --mcp-add: stdio (default when `--` present), http, or sse
|
||||
#[arg(
|
||||
long,
|
||||
value_enum,
|
||||
value_name = "TRANSPORT",
|
||||
help_heading = "MCP Servers"
|
||||
)]
|
||||
pub transport: Option<McpTransportArg>,
|
||||
/// URL for http/sse MCP server (used with --mcp-add)
|
||||
#[arg(long, value_name = "URL", help_heading = "MCP Servers")]
|
||||
pub url: Option<String>,
|
||||
/// Scope for MCP config: user (~/.config/coyote/functions/mcp.json) or workspace (./.coyote/mcp.json). Default: user
|
||||
#[arg(long, value_enum, value_name = "SCOPE", help_heading = "MCP Servers")]
|
||||
pub scope: Option<McpScopeArg>,
|
||||
/// Environment variable for stdio MCP server (repeatable): --env KEY=VALUE
|
||||
#[arg(long, value_name = "KEY=VALUE", help_heading = "MCP Servers")]
|
||||
pub env: Vec<String>,
|
||||
/// HTTP header for http/sse MCP server (repeatable): --header "Name: Value"
|
||||
#[arg(long, value_name = "HEADER", help_heading = "MCP Servers")]
|
||||
pub header: Vec<String>,
|
||||
/// Working directory for stdio MCP server
|
||||
#[arg(long, value_name = "PATH", value_hint = ValueHint::AnyPath, help_heading = "MCP Servers")]
|
||||
pub cwd: Option<String>,
|
||||
/// OAuth client ID for http/sse MCP server
|
||||
#[arg(long, value_name = "ID", help_heading = "MCP Servers")]
|
||||
pub client_id: Option<String>,
|
||||
/// OAuth client secret for http/sse MCP server (use {{NAME}} to reference a vault secret)
|
||||
#[arg(long, value_name = "SECRET", help_heading = "MCP Servers")]
|
||||
pub client_secret: Option<String>,
|
||||
/// OAuth callback port for http/sse MCP server
|
||||
#[arg(long, value_name = "PORT", help_heading = "MCP Servers")]
|
||||
pub callback_port: Option<u16>,
|
||||
/// OAuth redirect host for http/sse MCP server
|
||||
#[arg(long, value_name = "HOST", help_heading = "MCP Servers")]
|
||||
pub redirect_host: Option<String>,
|
||||
/// Overwrite an existing MCP server (with --mcp-add) or skip confirmation (with --mcp-remove)
|
||||
#[arg(long, help_heading = "MCP Servers")]
|
||||
pub mcp_force: bool,
|
||||
|
||||
/// Launch Coyote inside a Docker sandbox (via `sbx`); name defaults to current directory basename
|
||||
#[arg(long, value_name = "NAME", help_heading = "Sandbox")]
|
||||
pub sandbox: Option<Option<String>>,
|
||||
@@ -254,6 +373,15 @@ pub struct Cli {
|
||||
/// Generate static shell completion scripts
|
||||
#[arg(long, value_name = "SHELL", value_enum, help_heading = "Shell")]
|
||||
pub completions: Option<ShellCompletion>,
|
||||
|
||||
/// Stdio command for --mcp-add: everything after `--` is passed to the server verbatim
|
||||
#[arg(
|
||||
last = true,
|
||||
allow_hyphen_values = true,
|
||||
value_name = "CMD",
|
||||
help_heading = "MCP Servers"
|
||||
)]
|
||||
pub mcp_command: Vec<String>,
|
||||
}
|
||||
|
||||
impl Cli {
|
||||
@@ -413,6 +541,7 @@ mod tests {
|
||||
assert!(parse(&["--list-rags"]).list_rags);
|
||||
assert!(parse(&["--list-macros"]).list_macros);
|
||||
assert!(parse(&["--list-skills"]).list_skills);
|
||||
assert!(parse(&["--list-bundles"]).list_bundles);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -421,6 +550,119 @@ mod tests {
|
||||
assert!(parse(&[]).skill.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_update_bundle_flag_takes_name() {
|
||||
assert_eq!(
|
||||
parse(&["--update-bundle", "foo"]).update_bundle.as_deref(),
|
||||
Some("foo")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_uninstall_flag_takes_name() {
|
||||
assert_eq!(
|
||||
parse(&["--uninstall", "foo"]).uninstall.as_deref(),
|
||||
Some("foo")
|
||||
);
|
||||
assert!(!parse(&["--uninstall", "foo"]).yes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_yes_flag_requires_uninstall_or_update_bundle() {
|
||||
assert!(parse(&["--uninstall", "foo", "--yes"]).yes);
|
||||
assert!(parse(&["--update-bundle", "foo", "--yes"]).yes);
|
||||
assert!(Cli::try_parse_from(["coyote", "--yes"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_install_flag_takes_url_or_name() {
|
||||
assert_eq!(
|
||||
parse(&["--install", "https://github.com/x/y"])
|
||||
.install
|
||||
.as_deref(),
|
||||
Some("https://github.com/x/y")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_install_builtins_flag_takes_category() {
|
||||
assert_eq!(
|
||||
parse(&["--install-builtins", "agents"]).install_builtins,
|
||||
Some(AssetCategory::Agents)
|
||||
);
|
||||
assert_eq!(
|
||||
parse(&["--install-builtins", "mcp_config"]).install_builtins,
|
||||
Some(AssetCategory::McpConfig)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_install_builtins_conflicts_with_install() {
|
||||
assert!(
|
||||
Cli::try_parse_from(["coyote", "--install-builtins", "agents", "--install", "x"])
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_lifecycle_flags_are_mutually_exclusive() {
|
||||
assert!(Cli::try_parse_from(["coyote", "--install", "x", "--uninstall", "y"]).is_err());
|
||||
assert!(
|
||||
Cli::try_parse_from(["coyote", "--update-bundle", "x", "--uninstall", "y"]).is_err()
|
||||
);
|
||||
assert!(
|
||||
Cli::try_parse_from(["coyote", "--install-builtins", "agents", "--uninstall", "y"])
|
||||
.is_err()
|
||||
);
|
||||
assert!(Cli::try_parse_from(["coyote", "--install", "x", "--update-bundle", "y"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_companion_flags_conflict_with_other_lifecycle_actions() {
|
||||
assert!(
|
||||
Cli::try_parse_from(["coyote", "--update-bundle", "x", "--filter", "agents"]).is_err()
|
||||
);
|
||||
assert!(Cli::try_parse_from(["coyote", "--uninstall", "x", "--install-force"]).is_err());
|
||||
assert!(Cli::try_parse_from(["coyote", "--install", "x", "--yes"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_filter_requires_install() {
|
||||
assert!(Cli::try_parse_from(["coyote", "--filter", "agents"]).is_err());
|
||||
assert_eq!(
|
||||
parse(&["--install", "https://github.com/x/y", "--filter", "agents"]).filter,
|
||||
Some(InstallFilter::Agents)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_install_force_requires_install() {
|
||||
assert!(Cli::try_parse_from(["coyote", "--install-force"]).is_err());
|
||||
assert!(parse(&["--install", "https://github.com/x/y", "--install-force"]).install_force);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_git_host_requires_install() {
|
||||
assert!(Cli::try_parse_from(["coyote", "--git-host", "git.x.com"]).is_err());
|
||||
assert!(
|
||||
Cli::try_parse_from(["coyote", "--git-host", "gitlab.com", "--update-bundle", "x"])
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(
|
||||
parse(&["--install", "someuser/omc", "--git-host", "git.x.com"])
|
||||
.git_host
|
||||
.as_deref(),
|
||||
Some("git.x.com")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_shows_install_builtins() {
|
||||
use clap::CommandFactory;
|
||||
let help = Cli::command().render_long_help().to_string();
|
||||
assert!(help.contains("--install-builtins"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_multiple_skill_flags_preserves_order() {
|
||||
assert_eq!(
|
||||
@@ -633,4 +875,85 @@ mod tests {
|
||||
fn parse_sandbox_is_exclusive() {
|
||||
assert!(Cli::try_parse_from(["coyote", "--sandbox", "--agent", "foo"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_mcp_add_stdio_with_trailing_command() {
|
||||
let cli = parse(&[
|
||||
"--mcp-add",
|
||||
"myserver",
|
||||
"--",
|
||||
"npx",
|
||||
"some-server",
|
||||
"--flag",
|
||||
"arg1",
|
||||
]);
|
||||
assert_eq!(cli.mcp_add, Some("myserver".to_string()));
|
||||
assert_eq!(
|
||||
cli.mcp_command,
|
||||
vec!["npx", "some-server", "--flag", "arg1"]
|
||||
);
|
||||
assert!(cli.text.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_mcp_add_stdio_with_env_and_command() {
|
||||
let cli = parse(&[
|
||||
"--mcp-add",
|
||||
"s",
|
||||
"--env",
|
||||
"API_KEY={{API_KEY}}",
|
||||
"--env",
|
||||
"MODE=dev",
|
||||
"--",
|
||||
"npx",
|
||||
"srv",
|
||||
]);
|
||||
assert_eq!(cli.mcp_add, Some("s".to_string()));
|
||||
assert_eq!(cli.env, vec!["API_KEY={{API_KEY}}", "MODE=dev"]);
|
||||
assert_eq!(cli.mcp_command, vec!["npx", "srv"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_mcp_add_http_with_header() {
|
||||
let cli = parse(&[
|
||||
"--mcp-add",
|
||||
"notion",
|
||||
"--transport",
|
||||
"http",
|
||||
"--url",
|
||||
"https://mcp.notion.com/mcp",
|
||||
"--header",
|
||||
"Authorization: Bearer {{NOTION_TOKEN}}",
|
||||
]);
|
||||
assert_eq!(cli.mcp_add, Some("notion".to_string()));
|
||||
assert!(matches!(cli.transport, Some(McpTransportArg::Http)));
|
||||
assert_eq!(cli.url, Some("https://mcp.notion.com/mcp".to_string()));
|
||||
assert_eq!(cli.header, vec!["Authorization: Bearer {{NOTION_TOKEN}}"]);
|
||||
assert!(cli.mcp_command.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_mcp_list_flag() {
|
||||
let cli = parse(&["--mcp-list"]);
|
||||
assert!(cli.mcp_list);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_mcp_scope_workspace() {
|
||||
let cli = parse(&["--mcp-list", "--scope", "workspace"]);
|
||||
assert!(cli.mcp_list);
|
||||
assert!(matches!(cli.scope, Some(McpScopeArg::Workspace)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_mcp_action_group_is_exclusive() {
|
||||
assert!(Cli::try_parse_from(["coyote", "--mcp-list", "--mcp-get", "foo"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_trailing_text_unchanged_without_dash_dash() {
|
||||
let cli = parse(&["hello", "world"]);
|
||||
assert_eq!(cli.text, vec!["hello", "world"]);
|
||||
assert!(cli.mcp_command.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
+116
-1
@@ -2,6 +2,7 @@ use anyhow::{Result, anyhow};
|
||||
use chrono::Utc;
|
||||
use indexmap::IndexMap;
|
||||
use parking_lot::RwLock;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
type AccessTokenEntry = (String, i64, Option<String>);
|
||||
@@ -9,6 +10,12 @@ type AccessTokenEntry = (String, i64, Option<String>);
|
||||
static ACCESS_TOKENS: LazyLock<RwLock<IndexMap<String, AccessTokenEntry>>> =
|
||||
LazyLock::new(|| RwLock::new(IndexMap::new()));
|
||||
|
||||
/// Tokens a provider rejected (401) despite being locally unexpired.
|
||||
/// Maps client name → the exact rejected token so a concurrently-refreshed
|
||||
/// different token is never distrusted by mistake.
|
||||
static REJECTED_TOKENS: LazyLock<RwLock<HashMap<String, String>>> =
|
||||
LazyLock::new(|| RwLock::new(HashMap::new()));
|
||||
|
||||
pub fn get_access_token(client_name: &str) -> Result<String> {
|
||||
ACCESS_TOKENS
|
||||
.read()
|
||||
@@ -30,7 +37,7 @@ pub fn is_valid_access_token(client_name: &str) -> bool {
|
||||
Some(v) => v,
|
||||
None => return false,
|
||||
};
|
||||
!token.is_empty() && Utc::now().timestamp() < *expires_at
|
||||
!token.is_empty() && Utc::now().timestamp() < *expires_at && !is_rejected(client_name, token)
|
||||
}
|
||||
|
||||
pub fn set_access_token(
|
||||
@@ -45,3 +52,111 @@ pub fn set_access_token(
|
||||
entry.1 = expires_at;
|
||||
entry.2 = account_id;
|
||||
}
|
||||
|
||||
/// Compare-and-invalidate a provider-rejected token.
|
||||
///
|
||||
/// Only if the currently-cached token EQUALS `rejected` is the cache entry
|
||||
/// removed and the rejection marker recorded; a concurrently-refreshed
|
||||
/// different token is left untouched and no marker is set.
|
||||
///
|
||||
/// Returns true if a cache entry existed for this client at all (whether or
|
||||
/// not it matched `rejected`) — i.e. the client is token-authed and a retry
|
||||
/// after refresh is worthwhile. Returns false when there is no entry
|
||||
/// (API-key clients).
|
||||
pub fn distrust_access_token(client_name: &str, rejected: &str) -> bool {
|
||||
let mut access_tokens = ACCESS_TOKENS.write();
|
||||
let (token, _, _) = match access_tokens.get(client_name) {
|
||||
Some(v) => v,
|
||||
None => return false,
|
||||
};
|
||||
if token == rejected {
|
||||
access_tokens.shift_remove(client_name);
|
||||
REJECTED_TOKENS
|
||||
.write()
|
||||
.insert(client_name.to_string(), rejected.to_string());
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub fn is_rejected(client_name: &str, token: &str) -> bool {
|
||||
REJECTED_TOKENS
|
||||
.read()
|
||||
.get(client_name)
|
||||
.is_some_and(|rejected| rejected == token)
|
||||
}
|
||||
|
||||
pub fn clear_rejected(client_name: &str) {
|
||||
REJECTED_TOKENS.write().remove(client_name);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn distrust_removes_matching_token_and_sets_marker() {
|
||||
let client = "distrust-match-test";
|
||||
set_access_token(client, "at-1".into(), Utc::now().timestamp() + 3600, None);
|
||||
|
||||
assert!(distrust_access_token(client, "at-1"));
|
||||
|
||||
assert!(get_access_token(client).is_err(), "cache entry not removed");
|
||||
assert!(is_rejected(client, "at-1"), "marker not set");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distrust_keeps_differing_token_and_skips_marker() {
|
||||
let client = "distrust-differ-test";
|
||||
set_access_token(client, "at-new".into(), Utc::now().timestamp() + 3600, None);
|
||||
|
||||
assert!(distrust_access_token(client, "at-old"));
|
||||
|
||||
assert_eq!(get_access_token(client).unwrap(), "at-new");
|
||||
assert!(!is_rejected(client, "at-old"), "marker set for stale token");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn distrust_returns_false_without_cache_entry() {
|
||||
let client = "distrust-missing-test";
|
||||
|
||||
assert!(!distrust_access_token(client, "at-1"));
|
||||
assert!(!is_rejected(client, "at-1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_valid_access_token_false_for_rejected_token() {
|
||||
let client = "rejected-valid-test";
|
||||
set_access_token(client, "at-1".into(), Utc::now().timestamp() + 3600, None);
|
||||
assert!(is_valid_access_token(client));
|
||||
|
||||
distrust_access_token(client, "at-1");
|
||||
// A concurrent in-flight prepare re-caches the rejected file token
|
||||
// between mark and refresh; it must still be treated as invalid.
|
||||
set_access_token(client, "at-1".into(), Utc::now().timestamp() + 3600, None);
|
||||
|
||||
assert!(!is_valid_access_token(client));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_rejected_clears_marker_and_clients_are_isolated() {
|
||||
let client_a = "rejected-isolation-a";
|
||||
let client_b = "rejected-isolation-b";
|
||||
set_access_token(client_a, "at-1".into(), Utc::now().timestamp() + 3600, None);
|
||||
distrust_access_token(client_a, "at-1");
|
||||
|
||||
assert!(is_rejected(client_a, "at-1"));
|
||||
assert!(
|
||||
!is_rejected(client_b, "at-1"),
|
||||
"marker leaked across clients"
|
||||
);
|
||||
|
||||
clear_rejected(client_b);
|
||||
assert!(
|
||||
is_rejected(client_a, "at-1"),
|
||||
"wrong client's marker cleared"
|
||||
);
|
||||
|
||||
clear_rejected(client_a);
|
||||
assert!(!is_rejected(client_a, "at-1"));
|
||||
}
|
||||
}
|
||||
|
||||
+115
-5
@@ -1,3 +1,4 @@
|
||||
use std::collections::HashSet;
|
||||
use std::mem;
|
||||
|
||||
use super::access_token::get_access_token;
|
||||
@@ -368,17 +369,32 @@ pub fn claude_build_chat_completions_body(
|
||||
]
|
||||
} else {
|
||||
// One pair per round: Claude can reuse tool_use IDs across API calls.
|
||||
// A round boundary is detected by the presence of round text, but
|
||||
// rounds where the model emitted only tool calls (no narration)
|
||||
// carry no text marker. As a backstop, also split whenever a
|
||||
// tool_use ID would repeat within the current assistant message —
|
||||
// the API rejects duplicate tool_use IDs in a single message.
|
||||
let mut messages = vec![];
|
||||
let mut assistant_parts: Vec<serde_json::Value> = vec![];
|
||||
let mut user_parts: Vec<serde_json::Value> = vec![];
|
||||
let mut chunk_ids: HashSet<&str> = HashSet::new();
|
||||
for (index, tool_result) in tool_results.iter().enumerate() {
|
||||
if index > 0 && tool_result.text.is_some() {
|
||||
let id_collision = tool_result
|
||||
.call
|
||||
.id
|
||||
.as_deref()
|
||||
.is_some_and(|id| chunk_ids.contains(id));
|
||||
if index > 0 && (tool_result.text.is_some() || id_collision) {
|
||||
messages.push(
|
||||
json!({ "role": "assistant", "content": assistant_parts }),
|
||||
);
|
||||
messages.push(json!({ "role": "user", "content": user_parts }));
|
||||
assistant_parts = vec![];
|
||||
user_parts = vec![];
|
||||
chunk_ids.clear();
|
||||
}
|
||||
if let Some(id) = tool_result.call.id.as_deref() {
|
||||
chunk_ids.insert(id);
|
||||
}
|
||||
for block in &tool_result.thinking {
|
||||
assistant_parts.push(json!(block));
|
||||
@@ -485,10 +501,7 @@ pub fn claude_extract_chat_completions(data: &Value) -> Result<ChatCompletionsOu
|
||||
if let Some(v) = item["thinking"].as_str() {
|
||||
thinking.push(ThinkingBlock::Thinking {
|
||||
thinking: v.to_string(),
|
||||
signature: item["signature"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.to_string(),
|
||||
signature: item["signature"].as_str().unwrap_or_default().to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -535,3 +548,100 @@ pub fn claude_extract_chat_completions(data: &Value) -> Result<ChatCompletionsOu
|
||||
};
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::function::{ToolCall, ToolResult};
|
||||
|
||||
fn tool_result(id: &str, text: Option<&str>) -> ToolResult {
|
||||
ToolResult {
|
||||
call: ToolCall::new("fs_read".into(), json!({"path": "x"}), Some(id.into())),
|
||||
output: json!("ok"),
|
||||
text: text.map(|t| t.to_string()),
|
||||
thinking: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn build_body(tool_results: Vec<ToolResult>) -> Value {
|
||||
let data = ChatCompletionsData {
|
||||
messages: vec![
|
||||
Message::new(MessageRole::User, MessageContent::Text("hello".to_string())),
|
||||
Message::new(
|
||||
MessageRole::Assistant,
|
||||
MessageContent::ToolCalls(MessageContentToolCalls {
|
||||
tool_results,
|
||||
text: String::new(),
|
||||
sequence: true,
|
||||
}),
|
||||
),
|
||||
],
|
||||
temperature: None,
|
||||
top_p: None,
|
||||
reasoning_effort: None,
|
||||
functions: None,
|
||||
stream: false,
|
||||
};
|
||||
claude_build_chat_completions_body(data, &Model::new("claude", "claude-test")).unwrap()
|
||||
}
|
||||
|
||||
fn assert_unique_tool_use_ids_per_message(body: &Value) {
|
||||
for message in body["messages"].as_array().unwrap() {
|
||||
let Some(content) = message["content"].as_array() else {
|
||||
continue;
|
||||
};
|
||||
let mut seen = HashSet::new();
|
||||
for block in content {
|
||||
if block["type"] == "tool_use" {
|
||||
let id = block["id"].as_str().unwrap();
|
||||
assert!(
|
||||
seen.insert(id.to_string()),
|
||||
"duplicate tool_use id `{id}` within a single assistant message: {message}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_splits_on_round_text() {
|
||||
let body = build_body(vec![
|
||||
tool_result("toolu_A", None),
|
||||
tool_result("toolu_B", None),
|
||||
tool_result("toolu_C", Some("running another tool")),
|
||||
]);
|
||||
|
||||
let messages = body["messages"].as_array().unwrap();
|
||||
|
||||
assert_eq!(messages.len(), 5, "body: {body}");
|
||||
assert_unique_tool_use_ids_per_message(&body);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_splits_on_reused_id_in_textless_round() {
|
||||
let body = build_body(vec![
|
||||
tool_result("toolu_A", None),
|
||||
tool_result("toolu_B", None),
|
||||
tool_result("toolu_A", None),
|
||||
]);
|
||||
|
||||
let messages = body["messages"].as_array().unwrap();
|
||||
|
||||
assert_eq!(messages.len(), 5, "body: {body}");
|
||||
assert_unique_tool_use_ids_per_message(&body);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequence_keeps_textless_rounds_merged_when_ids_are_unique() {
|
||||
let body = build_body(vec![
|
||||
tool_result("toolu_A", None),
|
||||
tool_result("toolu_B", None),
|
||||
tool_result("toolu_C", None),
|
||||
]);
|
||||
|
||||
let messages = body["messages"].as_array().unwrap();
|
||||
|
||||
assert_eq!(messages.len(), 3, "body: {body}");
|
||||
assert_unique_tool_use_ids_per_message(&body);
|
||||
}
|
||||
}
|
||||
|
||||
+289
-15
@@ -1,5 +1,6 @@
|
||||
use super::*;
|
||||
|
||||
use super::access_token::{distrust_access_token, get_access_token};
|
||||
use crate::config::{RenderMode, paths};
|
||||
use crate::{
|
||||
config::{AppConfig, Input, RequestContext},
|
||||
@@ -56,12 +57,16 @@ pub trait Client: Sync + Send {
|
||||
let mut builder = ReqwestClient::builder();
|
||||
let extra = self.extra_config();
|
||||
let timeout = extra.and_then(|v| v.connect_timeout).unwrap_or(10);
|
||||
let read_timeout = extra.and_then(|v| v.read_timeout).unwrap_or(300);
|
||||
if let Some(proxy) = extra.and_then(|v| v.proxy.as_deref()) {
|
||||
builder = set_proxy(builder, proxy)?;
|
||||
}
|
||||
if let Some(user_agent) = self.app_config().user_agent.as_ref() {
|
||||
builder = builder.user_agent(user_agent);
|
||||
}
|
||||
if read_timeout > 0 {
|
||||
builder = builder.read_timeout(Duration::from_secs(read_timeout));
|
||||
}
|
||||
let client = builder
|
||||
.connect_timeout(Duration::from_secs(timeout))
|
||||
.build()
|
||||
@@ -69,6 +74,11 @@ pub trait Client: Sync + Send {
|
||||
Ok(client)
|
||||
}
|
||||
|
||||
/// On a 401 the cached access token is distrusted and the call retried
|
||||
/// exactly once; the retry re-runs the per-client prepare step, which
|
||||
/// sees the rejection marker, force-refreshes the token, and rebuilds
|
||||
/// the whole request. A second 401 propagates the original error; any
|
||||
/// other retry failure propagates as-is.
|
||||
async fn chat_completions(&self, input: Input) -> Result<ChatCompletionsOutput> {
|
||||
if self.app_config().dry_run {
|
||||
let content = input.echo_messages();
|
||||
@@ -76,11 +86,30 @@ pub trait Client: Sync + Send {
|
||||
}
|
||||
let client = self.build_client()?;
|
||||
let data = input.prepare_completion_data(self.model(), false)?;
|
||||
self.chat_completions_inner(&client, data)
|
||||
.await
|
||||
.with_context(|| "Failed to call chat-completions api")
|
||||
let err = match self.chat_completions_inner(&client, data).await {
|
||||
Ok(output) => return Ok(output),
|
||||
Err(err) => err,
|
||||
};
|
||||
let ret = if should_retry_auth(&err, self.name()) {
|
||||
debug!(
|
||||
"provider '{}' rejected access token (401); refreshing and retrying once",
|
||||
self.name()
|
||||
);
|
||||
let data = input.prepare_completion_data(self.model(), false)?;
|
||||
match self.chat_completions_inner(&client, data).await {
|
||||
Err(retry_err) if is_auth_error(&retry_err) => Err(err),
|
||||
ret => ret,
|
||||
}
|
||||
} else {
|
||||
Err(err)
|
||||
};
|
||||
ret.with_context(|| "Failed to call chat-completions api")
|
||||
}
|
||||
|
||||
/// Same retry-once-on-401 semantics as [`Self::chat_completions`], but
|
||||
/// only while the handler has received nothing yet: retrying after
|
||||
/// partial output has streamed would render it to the user twice. The
|
||||
/// retry lives inside the same `select!` arm so abort stays responsive.
|
||||
async fn chat_completions_streaming(
|
||||
&self,
|
||||
input: &Input,
|
||||
@@ -97,7 +126,22 @@ pub trait Client: Sync + Send {
|
||||
}
|
||||
let client = self.build_client()?;
|
||||
let data = input.prepare_completion_data(self.model(), true)?;
|
||||
self.chat_completions_streaming_inner(&client, handler, data).await
|
||||
let err = match self.chat_completions_streaming_inner(&client, handler, data).await {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(err) => err,
|
||||
};
|
||||
if handler.has_received_content() || !should_retry_auth(&err, self.name()) {
|
||||
return Err(err);
|
||||
}
|
||||
debug!(
|
||||
"provider '{}' rejected access token (401); refreshing and retrying once",
|
||||
self.name()
|
||||
);
|
||||
let data = input.prepare_completion_data(self.model(), true)?;
|
||||
match self.chat_completions_streaming_inner(&client, handler, data).await {
|
||||
Err(retry_err) if is_auth_error(&retry_err) => Err(err),
|
||||
ret => ret,
|
||||
}
|
||||
} => {
|
||||
handler.done();
|
||||
ret.with_context(|| "Failed to call chat-completions api")
|
||||
@@ -109,11 +153,27 @@ pub trait Client: Sync + Send {
|
||||
}
|
||||
}
|
||||
|
||||
/// Same retry-once-on-401 semantics as [`Self::chat_completions`]
|
||||
/// (gemini OAuth embeddings route here).
|
||||
async fn embeddings(&self, data: &EmbeddingsData) -> Result<Vec<Vec<f32>>> {
|
||||
let client = self.build_client()?;
|
||||
self.embeddings_inner(&client, data)
|
||||
.await
|
||||
.context("Failed to call embeddings api")
|
||||
let err = match self.embeddings_inner(&client, data).await {
|
||||
Ok(output) => return Ok(output),
|
||||
Err(err) => err,
|
||||
};
|
||||
let ret = if should_retry_auth(&err, self.name()) {
|
||||
debug!(
|
||||
"provider '{}' rejected access token (401); refreshing and retrying once",
|
||||
self.name()
|
||||
);
|
||||
match self.embeddings_inner(&client, data).await {
|
||||
Err(retry_err) if is_auth_error(&retry_err) => Err(err),
|
||||
ret => ret,
|
||||
}
|
||||
} else {
|
||||
Err(err)
|
||||
};
|
||||
ret.context("Failed to call embeddings api")
|
||||
}
|
||||
|
||||
async fn rerank(&self, data: &RerankData) -> Result<RerankOutput> {
|
||||
@@ -205,6 +265,7 @@ impl Default for ClientConfig {
|
||||
pub struct ExtraConfig {
|
||||
pub proxy: Option<String>,
|
||||
pub connect_timeout: Option<u64>,
|
||||
pub read_timeout: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Default)]
|
||||
@@ -557,46 +618,90 @@ pub async fn noop_rerank(_builder: RequestBuilder, _model: &Model) -> Result<Rer
|
||||
bail!("The client doesn't support rerank api")
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ApiStatusError {
|
||||
pub status: u16,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ApiStatusError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ApiStatusError {}
|
||||
|
||||
/// True when the error chain bottoms out in an [`ApiStatusError`] with
|
||||
/// status 401 EXACTLY. 403 (entitlement) and 429 (rate limit) are never
|
||||
/// auth failures, and message text is never inspected.
|
||||
fn is_auth_error(err: &anyhow::Error) -> bool {
|
||||
err.downcast_ref::<ApiStatusError>()
|
||||
.is_some_and(|api_err| api_err.status == 401)
|
||||
}
|
||||
|
||||
/// Decides whether a 401 from `client_name` warrants a single retry after a
|
||||
/// forced token refresh: the error must be a 401 [`ApiStatusError`], and the
|
||||
/// client must have a cached access token to distrust (API-key clients have
|
||||
/// none and never retry). Distrusting marks the exact rejected token so the
|
||||
/// retry's prepare step force-refreshes it. There is deliberately no backoff:
|
||||
/// the blast radius is bounded at one extra request per user-visible call.
|
||||
///
|
||||
/// Note: vertexai shares the ACCESS_TOKENS cache, so a 401 there also
|
||||
/// triggers distrust+retry — deliberate.
|
||||
fn should_retry_auth(err: &anyhow::Error, client_name: &str) -> bool {
|
||||
if !is_auth_error(err) {
|
||||
return false;
|
||||
}
|
||||
let Ok(token) = get_access_token(client_name) else {
|
||||
return false;
|
||||
};
|
||||
distrust_access_token(client_name, &token)
|
||||
}
|
||||
|
||||
pub fn catch_error(data: &Value, status: u16) -> Result<()> {
|
||||
if (200..300).contains(&status) {
|
||||
return Ok(());
|
||||
}
|
||||
debug!("Invalid response, status: {status}, data: {data}");
|
||||
let api_error = |message: String| anyhow::Error::new(ApiStatusError { status, message });
|
||||
if let Some(error) = data["error"].as_object() {
|
||||
if let (Some(typ), Some(message)) = (
|
||||
json_str_from_map(error, "type"),
|
||||
json_str_from_map(error, "message"),
|
||||
) {
|
||||
bail!("{message} (type: {typ})");
|
||||
return Err(api_error(format!("{message} (type: {typ})")));
|
||||
} else if let (Some(typ), Some(message)) = (
|
||||
json_str_from_map(error, "code"),
|
||||
json_str_from_map(error, "message"),
|
||||
) {
|
||||
bail!("{message} (code: {typ})");
|
||||
return Err(api_error(format!("{message} (code: {typ})")));
|
||||
}
|
||||
} else if let Some(error) = data["errors"][0].as_object() {
|
||||
if let (Some(code), Some(message)) = (
|
||||
error.get("code").and_then(|v| v.as_u64()),
|
||||
json_str_from_map(error, "message"),
|
||||
) {
|
||||
bail!("{message} (status: {code})")
|
||||
return Err(api_error(format!("{message} (status: {code})")));
|
||||
}
|
||||
} else if let Some(error) = data[0]["error"].as_object() {
|
||||
if let (Some(status), Some(message)) = (
|
||||
json_str_from_map(error, "status"),
|
||||
json_str_from_map(error, "message"),
|
||||
) {
|
||||
bail!("{message} (status: {status})")
|
||||
return Err(api_error(format!("{message} (status: {status})")));
|
||||
}
|
||||
} else if let (Some(detail), Some(status)) = (data["detail"].as_str(), data["status"].as_i64())
|
||||
{
|
||||
bail!("{detail} (status: {status})");
|
||||
return Err(api_error(format!("{detail} (status: {status})")));
|
||||
} else if let Some(error) = data["error"].as_str() {
|
||||
bail!("{error}");
|
||||
return Err(api_error(error.to_string()));
|
||||
} else if let Some(message) = data["message"].as_str() {
|
||||
bail!("{message}");
|
||||
return Err(api_error(message.to_string()));
|
||||
}
|
||||
bail!("Invalid response data: {data} (status: {status})");
|
||||
Err(api_error(format!(
|
||||
"Invalid response data: {data} (status: {status})"
|
||||
)))
|
||||
}
|
||||
|
||||
pub fn json_str_from_map<'a>(
|
||||
@@ -737,3 +842,172 @@ fn prompt_input_string(desc: &str, required: bool, help_message: Option<&str>) -
|
||||
let text = text.prompt()?;
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
use super::super::access_token::{is_rejected, set_access_token};
|
||||
|
||||
fn catch_error_message(data: &Value, status: u16) -> String {
|
||||
catch_error(data, status).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_catch_error_display_json_with_type() {
|
||||
let data = json!({"error": {"type": "invalid_request_error", "message": "Bad request"}});
|
||||
assert_eq!(
|
||||
catch_error_message(&data, 400),
|
||||
"Bad request (type: invalid_request_error)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_catch_error_display_json_with_code() {
|
||||
let data = json!({"error": {"code": "rate_limited", "message": "Too many requests"}});
|
||||
assert_eq!(
|
||||
catch_error_message(&data, 429),
|
||||
"Too many requests (code: rate_limited)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_catch_error_display_errors_array() {
|
||||
let data = json!({"errors": [{"code": 7000, "message": "No route"}]});
|
||||
assert_eq!(catch_error_message(&data, 404), "No route (status: 7000)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_catch_error_display_array_error_status() {
|
||||
let data = json!([{"error": {"status": "PERMISSION_DENIED", "message": "Denied"}}]);
|
||||
assert_eq!(
|
||||
catch_error_message(&data, 403),
|
||||
"Denied (status: PERMISSION_DENIED)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_catch_error_display_detail_status() {
|
||||
let data = json!({"detail": "Not found", "status": 404});
|
||||
assert_eq!(catch_error_message(&data, 404), "Not found (status: 404)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_catch_error_display_error_string() {
|
||||
let data = json!({"error": "Something went wrong"});
|
||||
assert_eq!(catch_error_message(&data, 500), "Something went wrong");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_catch_error_display_message_string() {
|
||||
let data = json!({"message": "Unauthorized"});
|
||||
assert_eq!(catch_error_message(&data, 401), "Unauthorized");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_catch_error_display_fallback() {
|
||||
let data = json!({"unexpected": true});
|
||||
assert_eq!(
|
||||
catch_error_message(&data, 500),
|
||||
format!("Invalid response data: {data} (status: 500)")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_catch_error_ok_on_success_status() {
|
||||
let data = json!({"error": {"type": "x", "message": "y"}});
|
||||
assert!(catch_error(&data, 200).is_ok());
|
||||
assert!(catch_error(&data, 299).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_catch_error_downcast_through_context_chain() {
|
||||
let data = json!({"error": {"type": "authentication_error", "message": "Invalid key"}});
|
||||
let err = catch_error(&data, 401)
|
||||
.context("Failed to call chat-completions api")
|
||||
.unwrap_err();
|
||||
let api_err = err
|
||||
.downcast_ref::<ApiStatusError>()
|
||||
.expect("should downcast through context chain");
|
||||
assert_eq!(api_err.status, 401);
|
||||
assert_eq!(api_err.message, "Invalid key (type: authentication_error)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_catch_error_preserves_status() {
|
||||
let data = json!({"message": "Unauthorized"});
|
||||
let err = catch_error(&data, 401).unwrap_err();
|
||||
assert_eq!(err.downcast_ref::<ApiStatusError>().unwrap().status, 401);
|
||||
|
||||
let data = json!({"detail": "Rate limited", "status": 429});
|
||||
let err = catch_error(&data, 429).unwrap_err();
|
||||
assert_eq!(err.downcast_ref::<ApiStatusError>().unwrap().status, 429);
|
||||
|
||||
// The struct carries the outer HTTP status even when the body embeds another code
|
||||
let data = json!({"errors": [{"code": 7000, "message": "No route"}]});
|
||||
let err = catch_error(&data, 429).unwrap_err();
|
||||
assert_eq!(err.downcast_ref::<ApiStatusError>().unwrap().status, 429);
|
||||
}
|
||||
|
||||
/// Wrapped in `.context(...)` so every test below proves the downcast
|
||||
/// works through an anyhow context chain, as in the trait methods.
|
||||
fn api_status_error(status: u16) -> anyhow::Error {
|
||||
anyhow::Error::new(ApiStatusError {
|
||||
status,
|
||||
message: format!("error (status: {status})"),
|
||||
})
|
||||
.context("Failed to call chat-completions api")
|
||||
}
|
||||
|
||||
fn cache_token(client: &str, token: &str) {
|
||||
set_access_token(
|
||||
client,
|
||||
token.into(),
|
||||
chrono::Utc::now().timestamp() + 3600,
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_should_retry_auth_401_with_cached_token() {
|
||||
let client = "should-retry-auth-401";
|
||||
cache_token(client, "at-1");
|
||||
|
||||
assert!(should_retry_auth(&api_status_error(401), client));
|
||||
assert!(is_rejected(client, "at-1"), "rejected marker not set");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_should_retry_auth_non_401_statuses() {
|
||||
let client = "should-retry-auth-non-401";
|
||||
cache_token(client, "at-1");
|
||||
|
||||
for status in [403, 429, 500] {
|
||||
assert!(
|
||||
!should_retry_auth(&api_status_error(status), client),
|
||||
"retried on {status}"
|
||||
);
|
||||
}
|
||||
assert_eq!(get_access_token(client).unwrap(), "at-1");
|
||||
assert!(!is_rejected(client, "at-1"), "marker set without a 401");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_should_retry_auth_non_api_status_error() {
|
||||
let client = "should-retry-auth-non-api";
|
||||
cache_token(client, "at-1");
|
||||
|
||||
let err = anyhow::anyhow!("connection reset").context("Failed to call embeddings api");
|
||||
assert!(!should_retry_auth(&err, client));
|
||||
assert_eq!(get_access_token(client).unwrap(), "at-1");
|
||||
assert!(!is_rejected(client, "at-1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_should_retry_auth_401_without_cached_token() {
|
||||
let client = "should-retry-auth-no-token";
|
||||
|
||||
assert!(!should_retry_auth(&api_status_error(401), client));
|
||||
assert!(!is_rejected(client, "at-1"));
|
||||
}
|
||||
}
|
||||
|
||||
+404
-37
@@ -1,14 +1,14 @@
|
||||
use super::access_token::{is_valid_access_token, set_access_token};
|
||||
use super::access_token::{clear_rejected, is_rejected, is_valid_access_token, set_access_token};
|
||||
use super::openai_compatible_oauth::OpenAICompatibleOAuthProvider;
|
||||
use super::{ClientConfig, ProviderModels};
|
||||
use crate::config::paths;
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use anyhow::{Context, Error, Result, anyhow, bail};
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use chrono::Utc;
|
||||
use indexmap::IndexMap;
|
||||
use inquire::Text;
|
||||
use reqwest::{Client as ReqwestClient, RequestBuilder};
|
||||
use reqwest::{Client as ReqwestClient, RequestBuilder, StatusCode};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use sha2::{Digest, Sha256};
|
||||
@@ -16,6 +16,10 @@ use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::Duration;
|
||||
use tokio::sync;
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -197,10 +201,20 @@ pub struct OAuthTokens {
|
||||
pub account_id: Option<String>,
|
||||
}
|
||||
|
||||
const TOKEN_ENDPOINT_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
pub async fn run_oauth_flow(provider: &dyn OAuthProvider, client_name: &str) -> Result<()> {
|
||||
match provider.flow() {
|
||||
OAuthFlow::Pkce => run_pkce_flow(provider, client_name).await,
|
||||
OAuthFlow::ClientCredentials => run_client_credentials_flow(provider, client_name).await,
|
||||
OAuthFlow::ClientCredentials => {
|
||||
run_client_credentials_flow(provider, client_name).await?;
|
||||
println!(
|
||||
"Successfully authenticated client '{}' with {} via OAuth (client_credentials). Tokens saved.",
|
||||
client_name,
|
||||
provider.provider_name()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
OAuthFlow::DeviceCode => run_device_code_flow(provider, client_name).await,
|
||||
}
|
||||
}
|
||||
@@ -301,12 +315,20 @@ async fn run_pkce_flow(provider: &dyn OAuthProvider, client_name: &str) -> Resul
|
||||
|
||||
let access_token = response["access_token"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow!("Missing access_token in response: {response}"))?
|
||||
.ok_or_else(|| {
|
||||
anyhow!(
|
||||
"Missing access_token in response (keys: {})",
|
||||
token_response_keys(&response)
|
||||
)
|
||||
})?
|
||||
.to_string();
|
||||
let refresh_token = response["refresh_token"].as_str().map(|s| s.to_string());
|
||||
let expires_in = response["expires_in"]
|
||||
.as_i64()
|
||||
.ok_or_else(|| anyhow!("Missing expires_in in response: {response}"))?;
|
||||
let expires_in = response["expires_in"].as_i64().ok_or_else(|| {
|
||||
anyhow!(
|
||||
"Missing expires_in in response (keys: {})",
|
||||
token_response_keys(&response)
|
||||
)
|
||||
})?;
|
||||
|
||||
let expires_at = Utc::now().timestamp() + expires_in;
|
||||
|
||||
@@ -334,7 +356,9 @@ async fn run_client_credentials_flow(
|
||||
provider: &dyn OAuthProvider,
|
||||
client_name: &str,
|
||||
) -> Result<()> {
|
||||
let client = ReqwestClient::new();
|
||||
let client = ReqwestClient::builder()
|
||||
.timeout(TOKEN_ENDPOINT_TIMEOUT)
|
||||
.build()?;
|
||||
let scopes = provider.scopes();
|
||||
let mut params: Vec<(&str, &str)> = vec![
|
||||
("grant_type", "client_credentials"),
|
||||
@@ -349,11 +373,19 @@ async fn run_client_credentials_flow(
|
||||
|
||||
let access_token = response["access_token"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow!("Missing access_token in client_credentials response: {response}"))?
|
||||
.ok_or_else(|| {
|
||||
anyhow!(
|
||||
"Missing access_token in client_credentials response (keys: {})",
|
||||
token_response_keys(&response)
|
||||
)
|
||||
})?
|
||||
.to_string();
|
||||
let expires_in = response["expires_in"]
|
||||
.as_i64()
|
||||
.ok_or_else(|| anyhow!("Missing expires_in in client_credentials response: {response}"))?;
|
||||
let expires_in = response["expires_in"].as_i64().ok_or_else(|| {
|
||||
anyhow!(
|
||||
"Missing expires_in in client_credentials response (keys: {})",
|
||||
token_response_keys(&response)
|
||||
)
|
||||
})?;
|
||||
let expires_at = Utc::now().timestamp() + expires_in;
|
||||
|
||||
let tokens = OAuthTokens {
|
||||
@@ -363,11 +395,6 @@ async fn run_client_credentials_flow(
|
||||
account_id: provider.extract_account_id(&response),
|
||||
};
|
||||
save_oauth_tokens(client_name, &tokens)?;
|
||||
println!(
|
||||
"Successfully authenticated client '{}' with {} via OAuth (client_credentials). Tokens saved.",
|
||||
client_name,
|
||||
provider.provider_name()
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -417,19 +444,28 @@ async fn run_device_code_flow(provider: &dyn OAuthProvider, client_name: &str) -
|
||||
let device_code = device_response["device_code"]
|
||||
.as_str()
|
||||
.ok_or_else(|| {
|
||||
anyhow!("Missing device_code in device authorization response: {device_response}")
|
||||
anyhow!(
|
||||
"Missing device_code in device authorization response (keys: {})",
|
||||
token_response_keys(&device_response)
|
||||
)
|
||||
})?
|
||||
.to_string();
|
||||
let user_code = device_response["user_code"]
|
||||
.as_str()
|
||||
.ok_or_else(|| {
|
||||
anyhow!("Missing user_code in device authorization response: {device_response}")
|
||||
anyhow!(
|
||||
"Missing user_code in device authorization response (keys: {})",
|
||||
token_response_keys(&device_response)
|
||||
)
|
||||
})?
|
||||
.to_string();
|
||||
let verification_uri = device_response["verification_uri"]
|
||||
.as_str()
|
||||
.ok_or_else(|| {
|
||||
anyhow!("Missing verification_uri in device authorization response: {device_response}")
|
||||
anyhow!(
|
||||
"Missing verification_uri in device authorization response (keys: {})",
|
||||
token_response_keys(&device_response)
|
||||
)
|
||||
})?
|
||||
.to_string();
|
||||
let verification_uri_complete = device_response["verification_uri_complete"]
|
||||
@@ -551,10 +587,76 @@ fn save_oauth_tokens(client_name: &str, tokens: &OAuthTokens) -> Result<()> {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
let json = serde_json::to_string_pretty(tokens)?;
|
||||
fs::write(path, json)?;
|
||||
// Write-then-rename so a crash mid-write never truncates the live token file.
|
||||
let mut tmp = path.clone().into_os_string();
|
||||
tmp.push(".tmp");
|
||||
let tmp = PathBuf::from(tmp);
|
||||
// Tokens are live credentials: create the file owner-only, not umask-default.
|
||||
let mut options = fs::OpenOptions::new();
|
||||
options.write(true).create(true).truncate(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
options.open(&tmp)?.write_all(json.as_bytes())?;
|
||||
fs::rename(&tmp, &path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn token_response_keys(response: &Value) -> String {
|
||||
match response.as_object() {
|
||||
Some(map) => {
|
||||
let keys: Vec<&str> = map.keys().map(String::as_str).collect();
|
||||
format!("[{}]", keys.join(", "))
|
||||
}
|
||||
None => "<non-object response>".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_refresh_response(
|
||||
status: StatusCode,
|
||||
response: &Value,
|
||||
previous_refresh_token: Option<&str>,
|
||||
) -> Result<(String, Option<String>, i64)> {
|
||||
if let Some(error) = response["error"].as_str() {
|
||||
let description = response["error_description"]
|
||||
.as_str()
|
||||
.unwrap_or("no description");
|
||||
if matches!(error, "invalid_grant" | "invalid_token") {
|
||||
bail!(
|
||||
"OAuth refresh token was rejected ({error}: {description}). Please re-authenticate."
|
||||
);
|
||||
}
|
||||
bail!("Token refresh failed ({error}: {description})");
|
||||
}
|
||||
if !status.is_success() {
|
||||
bail!("Token refresh failed with HTTP status {status}");
|
||||
}
|
||||
|
||||
let access_token = response["access_token"]
|
||||
.as_str()
|
||||
.ok_or_else(|| {
|
||||
anyhow!(
|
||||
"Missing access_token in refresh response (keys: {})",
|
||||
token_response_keys(response)
|
||||
)
|
||||
})?
|
||||
.to_string();
|
||||
let refresh_token = response["refresh_token"]
|
||||
.as_str()
|
||||
.or(previous_refresh_token)
|
||||
.map(str::to_string);
|
||||
let expires_in = response["expires_in"].as_i64().ok_or_else(|| {
|
||||
anyhow!(
|
||||
"Missing expires_in in refresh response (keys: {})",
|
||||
token_response_keys(response)
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok((access_token, refresh_token, expires_in))
|
||||
}
|
||||
|
||||
pub async fn refresh_oauth_token(
|
||||
client: &ReqwestClient,
|
||||
provider: &dyn OAuthProvider,
|
||||
@@ -577,19 +679,23 @@ pub async fn refresh_oauth_token(
|
||||
],
|
||||
);
|
||||
|
||||
let response: Value = request.send().await?.json().await?;
|
||||
let (status, response) = tokio::time::timeout(TOKEN_ENDPOINT_TIMEOUT, async {
|
||||
let response = request.send().await?;
|
||||
let status = response.status();
|
||||
let body: Value = response.json().await?;
|
||||
Ok::<_, Error>((status, body))
|
||||
})
|
||||
.await
|
||||
.map_err(|_| {
|
||||
anyhow!(
|
||||
"Token refresh for '{}' timed out after {}s",
|
||||
client_name,
|
||||
TOKEN_ENDPOINT_TIMEOUT.as_secs()
|
||||
)
|
||||
})??;
|
||||
|
||||
let access_token = response["access_token"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow!("Missing access_token in refresh response: {response}"))?
|
||||
.to_string();
|
||||
let refresh_token = response["refresh_token"]
|
||||
.as_str()
|
||||
.map(|s| s.to_string())
|
||||
.or_else(|| tokens.refresh_token.clone());
|
||||
let expires_in = response["expires_in"]
|
||||
.as_i64()
|
||||
.ok_or_else(|| anyhow!("Missing expires_in in refresh response: {response}"))?;
|
||||
let (access_token, refresh_token, expires_in) =
|
||||
parse_refresh_response(status, &response, tokens.refresh_token.as_deref())?;
|
||||
|
||||
let expires_at = Utc::now().timestamp() + expires_in;
|
||||
|
||||
@@ -609,6 +715,20 @@ pub async fn refresh_oauth_token(
|
||||
Ok(new_tokens)
|
||||
}
|
||||
|
||||
/// Per-client lock so concurrent requests perform a single refresh.
|
||||
/// Returns a clone of the Arc so the parking_lot guard is dropped before the
|
||||
/// caller awaits on the tokio mutex.
|
||||
fn refresh_guard(client_name: &str) -> Arc<sync::Mutex<()>> {
|
||||
static GUARDS: OnceLock<parking_lot::Mutex<HashMap<String, Arc<sync::Mutex<()>>>>> =
|
||||
OnceLock::new();
|
||||
GUARDS
|
||||
.get_or_init(Default::default)
|
||||
.lock()
|
||||
.entry(client_name.to_string())
|
||||
.or_default()
|
||||
.clone()
|
||||
}
|
||||
|
||||
pub async fn prepare_oauth_access_token(
|
||||
client: &ReqwestClient,
|
||||
provider: &dyn OAuthProvider,
|
||||
@@ -623,19 +743,43 @@ pub async fn prepare_oauth_access_token(
|
||||
None => return Ok(false),
|
||||
};
|
||||
|
||||
let tokens = if Utc::now().timestamp() >= tokens.expires_at {
|
||||
let tokens = if Utc::now().timestamp() >= tokens.expires_at
|
||||
|| is_rejected(client_name, &tokens.access_token)
|
||||
{
|
||||
let guard = refresh_guard(client_name);
|
||||
let _guard = guard.lock().await;
|
||||
|
||||
// A concurrent caller may have refreshed while we waited for the
|
||||
// lock; a valid in-memory token means the winner already populated
|
||||
// the cache.
|
||||
if is_valid_access_token(client_name) {
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
let tokens = match load_oauth_tokens(client_name) {
|
||||
Some(t) => t,
|
||||
None => return Ok(false),
|
||||
};
|
||||
|
||||
if Utc::now().timestamp() >= tokens.expires_at
|
||||
|| is_rejected(client_name, &tokens.access_token)
|
||||
{
|
||||
match provider.flow() {
|
||||
OAuthFlow::Pkce | OAuthFlow::DeviceCode => {
|
||||
refresh_oauth_token(client, provider, client_name, &tokens).await?
|
||||
}
|
||||
OAuthFlow::ClientCredentials => {
|
||||
run_client_credentials_flow(provider, client_name).await?;
|
||||
load_oauth_tokens(client_name)
|
||||
.ok_or_else(|| anyhow!("Token file missing after client_credentials refresh"))?
|
||||
load_oauth_tokens(client_name).ok_or_else(|| {
|
||||
anyhow!("Token file missing after client_credentials refresh")
|
||||
})?
|
||||
}
|
||||
}
|
||||
} else {
|
||||
tokens
|
||||
}
|
||||
} else {
|
||||
tokens
|
||||
};
|
||||
|
||||
set_access_token(
|
||||
@@ -644,6 +788,9 @@ pub async fn prepare_oauth_access_token(
|
||||
tokens.expires_at,
|
||||
tokens.account_id,
|
||||
);
|
||||
// Clear even when the refresh returned the same token (some IdPs reuse
|
||||
// JWTs within validity); otherwise every request re-hits the token endpoint.
|
||||
clear_rejected(client_name);
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
@@ -886,11 +1033,55 @@ pub(crate) fn client_config_info(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
use std::str;
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
use super::*;
|
||||
use crate::client::access_token::{distrust_access_token, get_access_token};
|
||||
use crate::client::openai_compatible::OpenAICompatibleConfig;
|
||||
use crate::client::{ModelData, ProviderModels};
|
||||
use crate::utils::get_env_name;
|
||||
use serial_test::serial;
|
||||
use std::{env, time::SystemTime};
|
||||
|
||||
fn with_temp_cache<F: FnOnce()>(f: F) {
|
||||
struct Restore {
|
||||
key: String,
|
||||
prev: Option<OsString>,
|
||||
root: PathBuf,
|
||||
}
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
match self.prev.take() {
|
||||
Some(v) => env::set_var(&self.key, v),
|
||||
None => env::remove_var(&self.key),
|
||||
}
|
||||
}
|
||||
let _ = fs::remove_dir_all(&self.root);
|
||||
}
|
||||
}
|
||||
|
||||
let unique = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
let root = env::temp_dir().join(format!("coyote-client-oauth-test-{unique}"));
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
let env_key = get_env_name("cache_dir");
|
||||
let prev = env::var_os(&env_key);
|
||||
unsafe {
|
||||
env::set_var(&env_key, &root);
|
||||
}
|
||||
let _restore = Restore {
|
||||
key: env_key,
|
||||
prev,
|
||||
root,
|
||||
};
|
||||
f();
|
||||
}
|
||||
|
||||
fn base_config() -> OAuthConfig {
|
||||
OAuthConfig {
|
||||
@@ -1468,4 +1659,180 @@ scopes:
|
||||
"body missing grant_type param: {body}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn save_oauth_tokens_roundtrips_and_leaves_no_tmp_file() {
|
||||
with_temp_cache(|| {
|
||||
let tokens = OAuthTokens {
|
||||
access_token: "at-123".into(),
|
||||
refresh_token: Some("rt-456".into()),
|
||||
expires_at: 1234567890,
|
||||
account_id: Some("acct-789".into()),
|
||||
};
|
||||
|
||||
save_oauth_tokens("atomic-test", &tokens).unwrap();
|
||||
|
||||
let loaded = load_oauth_tokens("atomic-test").unwrap();
|
||||
assert_eq!(loaded.access_token, "at-123");
|
||||
assert_eq!(loaded.refresh_token.as_deref(), Some("rt-456"));
|
||||
assert_eq!(loaded.expires_at, 1234567890);
|
||||
assert_eq!(loaded.account_id.as_deref(), Some("acct-789"));
|
||||
|
||||
let dir = paths::oauth_tokens_dir();
|
||||
let leftover_tmp = fs::read_dir(&dir)
|
||||
.unwrap()
|
||||
.any(|e| e.unwrap().file_name().to_string_lossy().ends_with(".tmp"));
|
||||
assert!(!leftover_tmp, "temp file left behind in {dir:?}");
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = fs::metadata(paths::token_file("atomic-test"))
|
||||
.unwrap()
|
||||
.permissions()
|
||||
.mode();
|
||||
assert_eq!(mode & 0o777, 0o600, "token file mode was {mode:o}");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn prepare_rejected_valid_file_token_attempts_refresh_branch() {
|
||||
with_temp_cache(|| {
|
||||
let client_name = "prepare-rejected-branch-test";
|
||||
let expires_at = Utc::now().timestamp() + 3600;
|
||||
save_oauth_tokens(
|
||||
client_name,
|
||||
&OAuthTokens {
|
||||
access_token: "rejected-at".into(),
|
||||
refresh_token: None,
|
||||
expires_at,
|
||||
account_id: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
set_access_token(client_name, "rejected-at".into(), expires_at, None);
|
||||
assert!(distrust_access_token(client_name, "rejected-at"));
|
||||
|
||||
let err = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap()
|
||||
.block_on(prepare_oauth_access_token(
|
||||
&ReqwestClient::new(),
|
||||
&ResourceStubProvider,
|
||||
client_name,
|
||||
))
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
|
||||
// The timestamp-valid but rejected file token must not be trusted;
|
||||
// the refresh branch is taken and bails on the missing refresh token.
|
||||
assert!(err.contains("No refresh token"), "unexpected error: {err}");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn prepare_trusts_differing_unmarked_valid_file_token() {
|
||||
with_temp_cache(|| {
|
||||
let client_name = "prepare-differing-token-test";
|
||||
let expires_at = Utc::now().timestamp() + 3600;
|
||||
set_access_token(client_name, "rejected-at".into(), expires_at, None);
|
||||
assert!(distrust_access_token(client_name, "rejected-at"));
|
||||
save_oauth_tokens(
|
||||
client_name,
|
||||
&OAuthTokens {
|
||||
access_token: "fresh-at".into(),
|
||||
refresh_token: None,
|
||||
expires_at,
|
||||
account_id: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let ready = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap()
|
||||
.block_on(prepare_oauth_access_token(
|
||||
&ReqwestClient::new(),
|
||||
&ResourceStubProvider,
|
||||
client_name,
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
assert!(ready);
|
||||
assert_eq!(get_access_token(client_name).unwrap(), "fresh-at");
|
||||
assert!(
|
||||
!is_rejected(client_name, "rejected-at"),
|
||||
"marker not cleared after successful prepare"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_refresh_response_invalid_grant_redacts_and_prompts_reauth() {
|
||||
let response = serde_json::json!({
|
||||
"error": "invalid_grant",
|
||||
"error_description": "refresh token revoked",
|
||||
"refresh_token": "planted-secret-token",
|
||||
});
|
||||
|
||||
let err = parse_refresh_response(StatusCode::BAD_REQUEST, &response, Some("old-rt"))
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
|
||||
assert!(err.contains("re-authenticate"), "unexpected error: {err}");
|
||||
assert!(
|
||||
!err.contains("planted-secret-token"),
|
||||
"error leaked token material: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_response_keys_lists_keys_without_values() {
|
||||
let response = serde_json::json!({
|
||||
"access_token": "secret-at",
|
||||
"token_type": "SecretBearer",
|
||||
});
|
||||
|
||||
let keys = token_response_keys(&response);
|
||||
|
||||
assert!(keys.contains("access_token"), "missing key name: {keys}");
|
||||
assert!(keys.contains("token_type"), "missing key name: {keys}");
|
||||
assert!(!keys.contains("secret-at"), "leaked value: {keys}");
|
||||
assert!(!keys.contains("SecretBearer"), "leaked value: {keys}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_refresh_response_rotates_refresh_token_when_present() {
|
||||
let response = serde_json::json!({
|
||||
"access_token": "new-at",
|
||||
"refresh_token": "new-rt",
|
||||
"expires_in": 3600,
|
||||
});
|
||||
|
||||
let (access_token, refresh_token, expires_in) =
|
||||
parse_refresh_response(StatusCode::OK, &response, Some("old-rt")).unwrap();
|
||||
|
||||
assert_eq!(access_token, "new-at");
|
||||
assert_eq!(refresh_token.as_deref(), Some("new-rt"));
|
||||
assert_eq!(expires_in, 3600);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_refresh_response_keeps_old_refresh_token_when_absent() {
|
||||
let response = serde_json::json!({
|
||||
"access_token": "new-at",
|
||||
"expires_in": 3600,
|
||||
});
|
||||
|
||||
let (_, refresh_token, _) =
|
||||
parse_refresh_response(StatusCode::OK, &response, Some("old-rt")).unwrap();
|
||||
|
||||
assert_eq!(refresh_token.as_deref(), Some("old-rt"));
|
||||
}
|
||||
}
|
||||
|
||||
+52
-3
@@ -1,4 +1,4 @@
|
||||
use super::{ThinkingBlock, ToolCall, catch_error};
|
||||
use super::{ApiStatusError, ThinkingBlock, ToolCall, catch_error};
|
||||
use crate::utils::AbortSignal;
|
||||
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
@@ -176,6 +176,14 @@ impl SseHandler {
|
||||
self.thinking.push(block);
|
||||
}
|
||||
|
||||
/// Whether any output (text, tool calls, or thinking blocks) has been
|
||||
/// accumulated. `Client::chat_completions_streaming` gates its 401 retry
|
||||
/// on this: content already streamed to the user would be rendered a
|
||||
/// second time by a retry, so partial responses are never retried.
|
||||
pub fn has_received_content(&self) -> bool {
|
||||
!self.buffer.is_empty() || !self.tool_calls.is_empty() || !self.thinking.is_empty()
|
||||
}
|
||||
|
||||
pub fn abort(&self) -> AbortSignal {
|
||||
self.abort_signal.clone()
|
||||
}
|
||||
@@ -224,10 +232,14 @@ where
|
||||
let data: Value = match text.parse() {
|
||||
Ok(data) => data,
|
||||
Err(_) => {
|
||||
bail!(
|
||||
return Err(ApiStatusError {
|
||||
status: status.as_u16(),
|
||||
message: format!(
|
||||
"Invalid response data: {text} (status: {})",
|
||||
status.as_u16()
|
||||
);
|
||||
),
|
||||
}
|
||||
.into());
|
||||
}
|
||||
};
|
||||
catch_error(&data, status.as_u16())?;
|
||||
@@ -418,6 +430,43 @@ mod tests {
|
||||
assert!(error_message.contains("test_function_loop"));
|
||||
}
|
||||
|
||||
fn new_handler() -> (SseHandler, tokio::sync::mpsc::UnboundedReceiver<SseEvent>) {
|
||||
let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
|
||||
let abort_signal = crate::utils::create_abort_signal();
|
||||
(SseHandler::new(sender, abort_signal), receiver)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_has_received_content_text() {
|
||||
let (mut handler, _rx) = new_handler();
|
||||
assert!(!handler.has_received_content());
|
||||
|
||||
handler.text("hello").unwrap();
|
||||
assert!(handler.has_received_content());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_has_received_content_tool_call() {
|
||||
let (mut handler, _rx) = new_handler();
|
||||
assert!(!handler.has_received_content());
|
||||
|
||||
let call = ToolCall::new("test_function".to_string(), json!({"param": 1}), None);
|
||||
handler.tool_call(call).unwrap();
|
||||
assert!(handler.has_received_content());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_has_received_content_thinking() {
|
||||
let (mut handler, _rx) = new_handler();
|
||||
assert!(!handler.has_received_content());
|
||||
|
||||
handler.thinking_block(ThinkingBlock::Thinking {
|
||||
thinking: "hmm".to_string(),
|
||||
signature: "sig".to_string(),
|
||||
});
|
||||
assert!(handler.has_received_content());
|
||||
}
|
||||
|
||||
fn split_chunks(text: &str) -> Vec<Vec<u8>> {
|
||||
let len = text.len();
|
||||
let cut1 = random_range(1..len - 1);
|
||||
|
||||
+98
-12
@@ -4,6 +4,7 @@ use crate::{
|
||||
client::Model,
|
||||
config::memory,
|
||||
function::{Functions, run_llm_function},
|
||||
graph, rag,
|
||||
};
|
||||
|
||||
use super::rag_cache::RagKey;
|
||||
@@ -185,7 +186,7 @@ impl Agent {
|
||||
&rag_path_clone,
|
||||
&document_paths,
|
||||
abort,
|
||||
false,
|
||||
true,
|
||||
)
|
||||
.await
|
||||
})
|
||||
@@ -247,6 +248,10 @@ impl Agent {
|
||||
}
|
||||
}
|
||||
|
||||
if rag.is_some() && app.function_calling_support && graph_for_rag.is_none() {
|
||||
functions.append_rag_query_functions();
|
||||
}
|
||||
|
||||
agent_config.replace_tools_placeholder(&functions);
|
||||
|
||||
Ok(Self {
|
||||
@@ -395,6 +400,10 @@ impl Agent {
|
||||
self.config.enabled_skills.as_deref()
|
||||
}
|
||||
|
||||
pub fn enabled_macros(&self) -> Option<&[String]> {
|
||||
self.config.enabled_macros.as_deref()
|
||||
}
|
||||
|
||||
pub fn memory(&self) -> Option<bool> {
|
||||
self.config.memory
|
||||
}
|
||||
@@ -739,6 +748,8 @@ pub struct AgentConfig {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub enabled_skills: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub enabled_macros: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub continuation_prompt: Option<String>,
|
||||
#[serde(default)]
|
||||
pub instructions: String,
|
||||
@@ -1021,11 +1032,11 @@ async fn init_graph_rags(
|
||||
// Graph validation catches this too, but it is skipped when
|
||||
// `validate_before_run` is off, so this guard is the load-bearing one.
|
||||
if let Some(driver) = &rag_node.driver
|
||||
&& let Some(message) = crate::graph::validator::rag_driver_error(driver)
|
||||
&& let Some(message) = graph::validator::rag_driver_error(driver)
|
||||
{
|
||||
bail!("rag node '{node_id}': {message}");
|
||||
}
|
||||
let config = rag_init_config(rag_node);
|
||||
let mut config = rag_init_config(rag_node);
|
||||
let fully_specified = config.embedding_model.is_some()
|
||||
&& config.chunk_size.is_some()
|
||||
&& config.chunk_overlap.is_some();
|
||||
@@ -1051,6 +1062,10 @@ async fn init_graph_rags(
|
||||
initialized. RAG initialization is required for this agent."
|
||||
);
|
||||
}
|
||||
|
||||
if config.driver.is_none() {
|
||||
config.driver = Some(rag::select_rag_driver()?);
|
||||
}
|
||||
}
|
||||
|
||||
let document_paths =
|
||||
@@ -1116,6 +1131,12 @@ struct AgentMetadataStub {
|
||||
description: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AgentVariablesStub {
|
||||
#[serde(default)]
|
||||
variables: Vec<AgentVariable>,
|
||||
}
|
||||
|
||||
fn load_agent_description(name: &str) -> String {
|
||||
if let Ok(config) = AgentConfig::load(&paths::agent_config_file(name)) {
|
||||
return config.description;
|
||||
@@ -1130,16 +1151,22 @@ fn load_agent_description(name: &str) -> String {
|
||||
String::new()
|
||||
}
|
||||
|
||||
pub fn complete_agent_variables(agent_name: &str) -> Vec<(String, Option<String>)> {
|
||||
let config_path = paths::agent_config_file(agent_name);
|
||||
if !config_path.exists() {
|
||||
return vec![];
|
||||
fn load_agent_variables(name: &str) -> Vec<AgentVariable> {
|
||||
if let Ok(config) = AgentConfig::load(&paths::agent_config_file(name)) {
|
||||
return config.variables;
|
||||
}
|
||||
let Ok(config) = AgentConfig::load(&config_path) else {
|
||||
return vec![];
|
||||
};
|
||||
config
|
||||
.variables
|
||||
|
||||
if let Ok(contents) = read_to_string(paths::agent_graph_file(name))
|
||||
&& let Ok(stub) = serde_yaml::from_str::<AgentVariablesStub>(&contents)
|
||||
{
|
||||
return stub.variables;
|
||||
}
|
||||
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
pub fn complete_agent_variables(agent_name: &str) -> Vec<(String, Option<String>)> {
|
||||
load_agent_variables(agent_name)
|
||||
.iter()
|
||||
.map(|v| {
|
||||
let description = match &v.default {
|
||||
@@ -1216,6 +1243,30 @@ variables:
|
||||
assert!(config.top_p.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_config_enabled_macros_absent_is_none() {
|
||||
let yaml = "name: minimal\ninstructions: hi\n";
|
||||
let config: AgentConfig = serde_yaml::from_str(yaml).unwrap();
|
||||
|
||||
assert_eq!(config.enabled_macros, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_config_enabled_macros_empty_list_is_some_empty() {
|
||||
let yaml = "name: minimal\ninstructions: hi\nenabled_macros: []\n";
|
||||
let config: AgentConfig = serde_yaml::from_str(yaml).unwrap();
|
||||
|
||||
assert_eq!(config.enabled_macros, Some(vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_config_enabled_macros_list() {
|
||||
let yaml = "name: minimal\ninstructions: hi\nenabled_macros:\n - a\n";
|
||||
let config: AgentConfig = serde_yaml::from_str(yaml).unwrap();
|
||||
|
||||
assert_eq!(config.enabled_macros, Some(vec!["a".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_config_with_model() {
|
||||
let yaml =
|
||||
@@ -1360,6 +1411,41 @@ version: "1.0"
|
||||
assert_eq!(meta.description, "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_variables_stub_extracts_variables_from_graph_yaml() {
|
||||
let yaml = r#"
|
||||
name: coder
|
||||
description: Implementation agent.
|
||||
version: "1.0"
|
||||
variables:
|
||||
- name: task
|
||||
description: The task to implement
|
||||
- name: scope
|
||||
description: Directory scope
|
||||
default: src/
|
||||
start: plan
|
||||
nodes: {}
|
||||
"#;
|
||||
|
||||
let stub: AgentVariablesStub = serde_yaml::from_str(yaml).unwrap();
|
||||
|
||||
assert_eq!(stub.variables.len(), 2);
|
||||
assert_eq!(stub.variables[0].name, "task");
|
||||
assert_eq!(stub.variables[0].description, "The task to implement");
|
||||
assert_eq!(stub.variables[0].default, None);
|
||||
assert_eq!(stub.variables[1].name, "scope");
|
||||
assert_eq!(stub.variables[1].default.as_deref(), Some("src/"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_variables_stub_defaults_when_variables_missing() {
|
||||
let yaml = "name: coder\nversion: \"1.0\"\nstart: plan\nnodes: {}\n";
|
||||
|
||||
let stub: AgentVariablesStub = serde_yaml::from_str(yaml).unwrap();
|
||||
|
||||
assert!(stub.variables.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rag_init_config_forwards_an_explicit_driver() {
|
||||
let node: RagNode =
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::client::{ClientConfig, Model, ModelType, list_models};
|
||||
use crate::render::{MarkdownRender, RenderOptions};
|
||||
use crate::utils::{IS_STDOUT_TERMINAL, NO_COLOR, decode_bin, get_env_name};
|
||||
use crate::utils::{IS_STDOUT_TERMINAL, NO_COLOR, decode_bin, drain_stale_tty_input, get_env_name};
|
||||
|
||||
use super::paths;
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
@@ -43,6 +43,8 @@ pub struct AppConfig {
|
||||
#[serde(default, deserialize_with = "super::deserialize_csv_or_vec")]
|
||||
pub enabled_skills: Option<Vec<String>>,
|
||||
pub visible_skills: Option<Vec<String>>,
|
||||
#[serde(default, deserialize_with = "super::deserialize_csv_or_vec")]
|
||||
pub enabled_macros: Option<Vec<String>>,
|
||||
|
||||
pub mcp_server_support: bool,
|
||||
pub mapping_mcp_servers: IndexMap<String, String>,
|
||||
@@ -96,6 +98,7 @@ pub struct AppConfig {
|
||||
pub user_agent: Option<String>,
|
||||
pub save_shell_history: bool,
|
||||
pub no_workspace_mcp: bool,
|
||||
pub no_workspace_macros: bool,
|
||||
pub sync_models_url: Option<String>,
|
||||
|
||||
pub clients: Vec<ClientConfig>,
|
||||
@@ -127,6 +130,7 @@ impl Default for AppConfig {
|
||||
skills_enabled: true,
|
||||
enabled_skills: None,
|
||||
visible_skills: None,
|
||||
enabled_macros: None,
|
||||
|
||||
mcp_server_support: true,
|
||||
mapping_mcp_servers: Default::default(),
|
||||
@@ -178,6 +182,7 @@ impl Default for AppConfig {
|
||||
user_agent: None,
|
||||
save_shell_history: true,
|
||||
no_workspace_mcp: false,
|
||||
no_workspace_macros: false,
|
||||
sync_models_url: None,
|
||||
|
||||
clients: vec![],
|
||||
@@ -211,6 +216,7 @@ impl AppConfig {
|
||||
skills_enabled: config.skills_enabled,
|
||||
enabled_skills: config.enabled_skills,
|
||||
visible_skills: config.visible_skills,
|
||||
enabled_macros: config.enabled_macros,
|
||||
|
||||
mcp_server_support: config.mcp_server_support,
|
||||
mapping_mcp_servers: config.mapping_mcp_servers,
|
||||
@@ -262,6 +268,7 @@ impl AppConfig {
|
||||
user_agent: config.user_agent,
|
||||
save_shell_history: config.save_shell_history,
|
||||
no_workspace_mcp: false,
|
||||
no_workspace_macros: false,
|
||||
sync_models_url: config.sync_models_url,
|
||||
|
||||
clients: config.clients,
|
||||
@@ -533,6 +540,10 @@ impl AppConfig {
|
||||
self.enabled_skills = v.map(|raw| super::csv_to_vec(&raw));
|
||||
}
|
||||
|
||||
if let Some(v) = super::read_env_value::<String>(&get_env_name("enabled_macros")) {
|
||||
self.enabled_macros = v.map(|raw| super::csv_to_vec(&raw));
|
||||
}
|
||||
|
||||
if let Some(Some(v)) = super::read_env_bool(&get_env_name("mcp_server_support")) {
|
||||
self.mcp_server_support = v;
|
||||
}
|
||||
@@ -616,15 +627,19 @@ impl AppConfig {
|
||||
if self.highlight && self.theme.is_none() {
|
||||
if let Some(v) = super::read_env_value::<String>(&get_env_name("theme")) {
|
||||
self.theme = v;
|
||||
} else if *IS_STDOUT_TERMINAL
|
||||
&& let Ok(color_scheme) = color_scheme(QueryOptions::default())
|
||||
{
|
||||
} else if *IS_STDOUT_TERMINAL {
|
||||
if let Ok(color_scheme) = color_scheme(QueryOptions::default()) {
|
||||
let theme = match color_scheme {
|
||||
ColorScheme::Dark => "dark",
|
||||
ColorScheme::Light => "light",
|
||||
};
|
||||
self.theme = Some(theme.into());
|
||||
}
|
||||
// The OSC/DA1 reply can arrive after colorsaurus stops reading
|
||||
// (observed under zellij-in-kitty). Drain any late reply bytes so
|
||||
// they are neither echoed nor read as line-editor input.
|
||||
drain_stale_tty_input();
|
||||
}
|
||||
}
|
||||
if let Some(v) = super::read_env_value::<String>(&get_env_name("left_prompt")) {
|
||||
self.left_prompt = v;
|
||||
@@ -765,6 +780,70 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn from_config_copies_enabled_macros() {
|
||||
let cfg = Config {
|
||||
model_id: "provider:test".to_string(),
|
||||
enabled_macros: Some(vec!["a".to_string()]),
|
||||
..Config::default()
|
||||
};
|
||||
|
||||
let app = AppConfig::from_config(cfg).unwrap();
|
||||
|
||||
assert_eq!(app.enabled_macros, Some(vec!["a".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn from_config_preserves_explicit_empty_enabled_macros() {
|
||||
let cfg = Config {
|
||||
model_id: "provider:test".to_string(),
|
||||
enabled_macros: Some(vec![]),
|
||||
..Config::default()
|
||||
};
|
||||
|
||||
let app = AppConfig::from_config(cfg).unwrap();
|
||||
|
||||
assert_eq!(app.enabled_macros, Some(vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn load_envs_overrides_enabled_macros() {
|
||||
let env_name = get_env_name("enabled_macros");
|
||||
let prev = std::env::var_os(&env_name);
|
||||
|
||||
let mut app = AppConfig::default();
|
||||
|
||||
unsafe { std::env::set_var(&env_name, "a,b") };
|
||||
app.load_envs();
|
||||
assert_eq!(
|
||||
app.enabled_macros,
|
||||
Some(vec!["a".to_string(), "b".to_string()])
|
||||
);
|
||||
|
||||
unsafe { std::env::set_var(&env_name, "") };
|
||||
app.load_envs();
|
||||
assert_eq!(app.enabled_macros, Some(vec![]));
|
||||
|
||||
unsafe { std::env::set_var(&env_name, "null") };
|
||||
app.load_envs();
|
||||
assert_eq!(app.enabled_macros, None);
|
||||
|
||||
unsafe { std::env::remove_var(&env_name) };
|
||||
app.enabled_macros = Some(vec!["keep".to_string()]);
|
||||
app.load_envs();
|
||||
assert_eq!(app.enabled_macros, Some(vec!["keep".to_string()]));
|
||||
|
||||
unsafe {
|
||||
match prev {
|
||||
Some(v) => std::env::set_var(&env_name, v),
|
||||
None => std::env::remove_var(&env_name),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editor_returns_configured_value() {
|
||||
let configured = cached_editor()
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+3392
-54
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,983 @@
|
||||
use super::agent::Agent;
|
||||
use super::app_config::AppConfig;
|
||||
use super::macros::Macro;
|
||||
use super::paths;
|
||||
use super::role::Role;
|
||||
use super::session::Session;
|
||||
|
||||
use log::warn;
|
||||
use std::collections::HashSet;
|
||||
use std::fmt;
|
||||
use std::fs::{read_dir, read_to_string};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub const RESERVED_MACRO_NAMES: [&str; 2] = ["enable", "disable"];
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MacroSource {
|
||||
Workspace,
|
||||
Global,
|
||||
}
|
||||
|
||||
impl fmt::Display for MacroSource {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
MacroSource::Workspace => write!(f, "workspace"),
|
||||
MacroSource::Global => write!(f, "global"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The configuration level whose `enabled_macros` allowlist won the
|
||||
/// first-`Some`-wins precedence chain (session > agent > role > global).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MacroAllowlistLevel {
|
||||
Session,
|
||||
Agent,
|
||||
Role,
|
||||
Global,
|
||||
}
|
||||
|
||||
impl fmt::Display for MacroAllowlistLevel {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
MacroAllowlistLevel::Session => write!(f, "session"),
|
||||
MacroAllowlistLevel::Agent => write!(f, "agent"),
|
||||
MacroAllowlistLevel::Role => write!(f, "role"),
|
||||
MacroAllowlistLevel::Global => write!(f, "global"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum MacroState {
|
||||
Enabled,
|
||||
DisabledRuntime,
|
||||
Locked { level: MacroAllowlistLevel },
|
||||
Missing,
|
||||
ShadowedBuiltin,
|
||||
Invalid { reason: String },
|
||||
}
|
||||
|
||||
impl MacroState {
|
||||
pub fn is_invocable(&self) -> bool {
|
||||
matches!(self, MacroState::Enabled | MacroState::ShadowedBuiltin)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DiscoveredMacro {
|
||||
pub name: String,
|
||||
pub source: MacroSource,
|
||||
pub definition: Result<Macro, String>,
|
||||
pub shadowed_by_workspace: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ResolvedMacro {
|
||||
pub name: String,
|
||||
pub source: Option<MacroSource>,
|
||||
pub description: Option<String>,
|
||||
pub isolated: Option<bool>,
|
||||
pub shadowed_by_workspace: bool,
|
||||
pub state: MacroState,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct MacroPolicy {
|
||||
pub macros: Vec<ResolvedMacro>,
|
||||
}
|
||||
|
||||
impl MacroPolicy {
|
||||
pub fn effective(
|
||||
global: &AppConfig,
|
||||
role: Option<&Role>,
|
||||
agent: Option<&Agent>,
|
||||
session: Option<&Session>,
|
||||
builtin_commands: &[&str],
|
||||
no_workspace_macros: bool,
|
||||
) -> Self {
|
||||
Self::effective_with(
|
||||
discover_macros(no_workspace_macros),
|
||||
session.and_then(|s| s.enabled_macros()),
|
||||
agent.and_then(|a| a.enabled_macros()),
|
||||
role.and_then(|r| r.enabled_macros()),
|
||||
global.enabled_macros.as_deref(),
|
||||
builtin_commands,
|
||||
)
|
||||
}
|
||||
|
||||
fn effective_with(
|
||||
discovered: Vec<DiscoveredMacro>,
|
||||
session_list: Option<&[String]>,
|
||||
agent_list: Option<&[String]>,
|
||||
role_list: Option<&[String]>,
|
||||
global_list: Option<&[String]>,
|
||||
builtin_commands: &[&str],
|
||||
) -> Self {
|
||||
let allowlist = session_list
|
||||
.map(|list| (MacroAllowlistLevel::Session, list))
|
||||
.or_else(|| agent_list.map(|list| (MacroAllowlistLevel::Agent, list)))
|
||||
.or_else(|| role_list.map(|list| (MacroAllowlistLevel::Role, list)))
|
||||
.or_else(|| global_list.map(|list| (MacroAllowlistLevel::Global, list)));
|
||||
|
||||
let mut macros: Vec<ResolvedMacro> = discovered
|
||||
.into_iter()
|
||||
.map(|discovered_macro| {
|
||||
let state = resolve_state(&discovered_macro, allowlist, builtin_commands);
|
||||
let (description, isolated) = match &discovered_macro.definition {
|
||||
Ok(value) => (value.description.clone(), Some(value.isolated)),
|
||||
Err(_) => (None, None),
|
||||
};
|
||||
ResolvedMacro {
|
||||
name: discovered_macro.name,
|
||||
source: Some(discovered_macro.source),
|
||||
description,
|
||||
isolated,
|
||||
shadowed_by_workspace: discovered_macro.shadowed_by_workspace,
|
||||
state,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
if let Some((_, list)) = allowlist {
|
||||
let known: HashSet<&str> = macros.iter().map(|m| m.name.as_str()).collect();
|
||||
let mut missing: Vec<ResolvedMacro> = vec![];
|
||||
for name in list {
|
||||
if !known.contains(name.as_str()) && !missing.iter().any(|m| &m.name == name) {
|
||||
warn!("enabled_macros references macro '{name}' which is not installed");
|
||||
missing.push(ResolvedMacro {
|
||||
name: name.clone(),
|
||||
source: None,
|
||||
description: None,
|
||||
isolated: None,
|
||||
shadowed_by_workspace: false,
|
||||
state: MacroState::Missing,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
macros.extend(missing);
|
||||
}
|
||||
|
||||
macros.sort_by(|a, b| {
|
||||
a.name
|
||||
.cmp(&b.name)
|
||||
.then_with(|| source_rank(a.source).cmp(&source_rank(b.source)))
|
||||
});
|
||||
|
||||
Self { macros }
|
||||
}
|
||||
|
||||
pub fn find(&self, name: &str) -> Option<&ResolvedMacro> {
|
||||
self.macros
|
||||
.iter()
|
||||
.find(|m| m.name == name && m.source.is_some() && !m.shadowed_by_workspace)
|
||||
}
|
||||
}
|
||||
|
||||
fn source_rank(source: Option<MacroSource>) -> u8 {
|
||||
match source {
|
||||
Some(MacroSource::Workspace) => 0,
|
||||
Some(MacroSource::Global) => 1,
|
||||
None => 2,
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_state(
|
||||
discovered: &DiscoveredMacro,
|
||||
allowlist: Option<(MacroAllowlistLevel, &[String])>,
|
||||
builtin_commands: &[&str],
|
||||
) -> MacroState {
|
||||
if RESERVED_MACRO_NAMES.contains(&discovered.name.as_str()) {
|
||||
warn!(
|
||||
"Ignoring macro '{}': the name is reserved for '.macro {}'",
|
||||
discovered.name, discovered.name
|
||||
);
|
||||
|
||||
return MacroState::Invalid {
|
||||
reason: format!("'{}' is a reserved macro name", discovered.name),
|
||||
};
|
||||
}
|
||||
|
||||
if let Err(reason) = &discovered.definition {
|
||||
return MacroState::Invalid {
|
||||
reason: reason.clone(),
|
||||
};
|
||||
}
|
||||
|
||||
if let Some((level, list)) = allowlist
|
||||
&& !list.iter().any(|name| name == &discovered.name)
|
||||
{
|
||||
return match level {
|
||||
MacroAllowlistLevel::Global => MacroState::DisabledRuntime,
|
||||
level => MacroState::Locked { level },
|
||||
};
|
||||
}
|
||||
|
||||
if builtin_commands.contains(&discovered.name.as_str()) {
|
||||
return MacroState::ShadowedBuiltin;
|
||||
}
|
||||
|
||||
MacroState::Enabled
|
||||
}
|
||||
|
||||
pub fn discover_macros(no_workspace_macros: bool) -> Vec<DiscoveredMacro> {
|
||||
let mut dirs = vec![];
|
||||
if !no_workspace_macros {
|
||||
dirs.push((MacroSource::Workspace, paths::workspace_macros_dir()));
|
||||
}
|
||||
|
||||
dirs.push((MacroSource::Global, paths::macros_dir()));
|
||||
discover_macros_in(&dirs)
|
||||
}
|
||||
|
||||
fn discover_macros_in(dirs: &[(MacroSource, PathBuf)]) -> Vec<DiscoveredMacro> {
|
||||
let mut seen: HashSet<String> = HashSet::new();
|
||||
let mut output = vec![];
|
||||
|
||||
for (source, dir) in dirs {
|
||||
let Ok(rd) = read_dir(dir) else {
|
||||
continue;
|
||||
};
|
||||
let mut entries: Vec<_> = rd.flatten().collect();
|
||||
entries.sort_by_key(|entry| entry.file_name());
|
||||
|
||||
for entry in entries {
|
||||
let is_file = entry
|
||||
.file_type()
|
||||
.map(|file_type| file_type.is_file())
|
||||
.unwrap_or(false);
|
||||
|
||||
if !is_file {
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(name) = entry
|
||||
.file_name()
|
||||
.to_str()
|
||||
.and_then(|v| v.strip_suffix(".yaml"))
|
||||
.map(str::to_string)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let definition = read_to_string(entry.path())
|
||||
.map_err(|err| err.to_string())
|
||||
.and_then(|content| {
|
||||
serde_yaml::from_str::<Macro>(&content).map_err(|err| err.to_string())
|
||||
});
|
||||
let shadowed_by_workspace = !seen.insert(name.clone());
|
||||
output.push(DiscoveredMacro {
|
||||
name,
|
||||
source: *source,
|
||||
definition,
|
||||
shadowed_by_workspace,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
output
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::utils::get_env_name;
|
||||
use serial_test::serial;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::{env, fs, process};
|
||||
|
||||
fn valid_macro() -> Macro {
|
||||
Macro {
|
||||
description: Some("a test macro".to_string()),
|
||||
isolated: true,
|
||||
variables: vec![],
|
||||
steps: vec![".help".to_string()],
|
||||
}
|
||||
}
|
||||
|
||||
fn disc(name: &str, source: MacroSource) -> DiscoveredMacro {
|
||||
DiscoveredMacro {
|
||||
name: name.to_string(),
|
||||
source,
|
||||
definition: Ok(valid_macro()),
|
||||
shadowed_by_workspace: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn disc_invalid(name: &str, reason: &str) -> DiscoveredMacro {
|
||||
DiscoveredMacro {
|
||||
name: name.to_string(),
|
||||
source: MacroSource::Global,
|
||||
definition: Err(reason.to_string()),
|
||||
shadowed_by_workspace: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn globals(names: &[&str]) -> Vec<DiscoveredMacro> {
|
||||
names.iter().map(|n| disc(n, MacroSource::Global)).collect()
|
||||
}
|
||||
|
||||
fn list(names: &[&str]) -> Vec<String> {
|
||||
names.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
fn resolve(
|
||||
discovered: Vec<DiscoveredMacro>,
|
||||
session: Option<&[String]>,
|
||||
agent: Option<&[String]>,
|
||||
role: Option<&[String]>,
|
||||
global: Option<&[String]>,
|
||||
) -> MacroPolicy {
|
||||
MacroPolicy::effective_with(discovered, session, agent, role, global, &[])
|
||||
}
|
||||
|
||||
fn state_of<'a>(policy: &'a MacroPolicy, name: &str) -> &'a MacroState {
|
||||
&policy
|
||||
.macros
|
||||
.iter()
|
||||
.find(|m| m.name == name)
|
||||
.unwrap_or_else(|| panic!("no row for macro '{name}'"))
|
||||
.state
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_none_enables_everything() {
|
||||
let policy = resolve(globals(&["a", "b"]), None, None, None, None);
|
||||
|
||||
assert_eq!(state_of(&policy, "a"), &MacroState::Enabled);
|
||||
assert_eq!(state_of(&policy, "b"), &MacroState::Enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_empty_list_disables_all_as_runtime() {
|
||||
let l = list(&[]);
|
||||
let policy = resolve(globals(&["a", "b"]), None, None, None, Some(&l));
|
||||
|
||||
assert_eq!(state_of(&policy, "a"), &MacroState::DisabledRuntime);
|
||||
assert_eq!(state_of(&policy, "b"), &MacroState::DisabledRuntime);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_populated_partitions_enabled_and_disabled_runtime() {
|
||||
let l = list(&["a"]);
|
||||
let policy = resolve(globals(&["a", "b"]), None, None, None, Some(&l));
|
||||
|
||||
assert_eq!(state_of(&policy, "a"), &MacroState::Enabled);
|
||||
assert_eq!(state_of(&policy, "b"), &MacroState::DisabledRuntime);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_populated_locks_excluded_at_role_level() {
|
||||
let l = list(&["a"]);
|
||||
|
||||
let policy = resolve(globals(&["a", "b"]), None, None, Some(&l), None);
|
||||
|
||||
assert_eq!(state_of(&policy, "a"), &MacroState::Enabled);
|
||||
assert_eq!(
|
||||
state_of(&policy, "b"),
|
||||
&MacroState::Locked {
|
||||
level: MacroAllowlistLevel::Role
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_populated_locks_excluded_at_agent_level() {
|
||||
let l = list(&["a"]);
|
||||
|
||||
let policy = resolve(globals(&["a", "b"]), None, Some(&l), None, None);
|
||||
|
||||
assert_eq!(
|
||||
state_of(&policy, "b"),
|
||||
&MacroState::Locked {
|
||||
level: MacroAllowlistLevel::Agent
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_populated_locks_excluded_at_session_level() {
|
||||
let l = list(&["a"]);
|
||||
|
||||
let policy = resolve(globals(&["a", "b"]), Some(&l), None, None, None);
|
||||
|
||||
assert_eq!(
|
||||
state_of(&policy, "b"),
|
||||
&MacroState::Locked {
|
||||
level: MacroAllowlistLevel::Session
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_empty_list_locks_everything_at_role_level() {
|
||||
let l = list(&[]);
|
||||
|
||||
let policy = resolve(globals(&["a"]), None, None, Some(&l), None);
|
||||
|
||||
assert_eq!(
|
||||
state_of(&policy, "a"),
|
||||
&MacroState::Locked {
|
||||
level: MacroAllowlistLevel::Role
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_empty_list_locks_everything_at_agent_level() {
|
||||
let l = list(&[]);
|
||||
|
||||
let policy = resolve(globals(&["a"]), None, Some(&l), None, None);
|
||||
|
||||
assert_eq!(
|
||||
state_of(&policy, "a"),
|
||||
&MacroState::Locked {
|
||||
level: MacroAllowlistLevel::Agent
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_empty_list_locks_everything_at_session_level() {
|
||||
let l = list(&[]);
|
||||
|
||||
let policy = resolve(globals(&["a"]), Some(&l), None, None, None);
|
||||
|
||||
assert_eq!(
|
||||
state_of(&policy, "a"),
|
||||
&MacroState::Locked {
|
||||
level: MacroAllowlistLevel::Session
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_wins_over_agent() {
|
||||
let session = list(&["a"]);
|
||||
let agent = list(&["b"]);
|
||||
|
||||
let policy = resolve(
|
||||
globals(&["a", "b"]),
|
||||
Some(&session),
|
||||
Some(&agent),
|
||||
None,
|
||||
None,
|
||||
);
|
||||
|
||||
assert_eq!(state_of(&policy, "a"), &MacroState::Enabled);
|
||||
assert_eq!(
|
||||
state_of(&policy, "b"),
|
||||
&MacroState::Locked {
|
||||
level: MacroAllowlistLevel::Session
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_wins_over_role() {
|
||||
let agent = list(&["a"]);
|
||||
let role = list(&["b"]);
|
||||
|
||||
let policy = resolve(globals(&["a", "b"]), None, Some(&agent), Some(&role), None);
|
||||
|
||||
assert_eq!(state_of(&policy, "a"), &MacroState::Enabled);
|
||||
assert_eq!(
|
||||
state_of(&policy, "b"),
|
||||
&MacroState::Locked {
|
||||
level: MacroAllowlistLevel::Agent
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_wins_over_global() {
|
||||
let role = list(&["a"]);
|
||||
let global = list(&["b"]);
|
||||
|
||||
let policy = resolve(globals(&["a", "b"]), None, None, Some(&role), Some(&global));
|
||||
|
||||
assert_eq!(state_of(&policy, "a"), &MacroState::Enabled);
|
||||
assert_eq!(
|
||||
state_of(&policy, "b"),
|
||||
&MacroState::Locked {
|
||||
level: MacroAllowlistLevel::Role
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_list_at_session_beats_populated_global() {
|
||||
let session = list(&[]);
|
||||
let global = list(&["a"]);
|
||||
|
||||
let policy = resolve(globals(&["a"]), Some(&session), None, None, Some(&global));
|
||||
|
||||
assert_eq!(
|
||||
state_of(&policy, "a"),
|
||||
&MacroState::Locked {
|
||||
level: MacroAllowlistLevel::Session
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_allowlist_name_yields_missing_row_without_error() {
|
||||
let l = list(&["a", "ghost"]);
|
||||
|
||||
let policy = resolve(globals(&["a"]), None, None, None, Some(&l));
|
||||
|
||||
assert_eq!(state_of(&policy, "a"), &MacroState::Enabled);
|
||||
assert_eq!(state_of(&policy, "ghost"), &MacroState::Missing);
|
||||
let ghost = policy.macros.iter().find(|m| m.name == "ghost").unwrap();
|
||||
assert_eq!(ghost.source, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_row_deduplicated_for_repeated_allowlist_names() {
|
||||
let l = list(&["ghost", "ghost"]);
|
||||
|
||||
let policy = resolve(vec![], None, None, None, Some(&l));
|
||||
|
||||
assert_eq!(policy.macros.len(), 1);
|
||||
assert_eq!(state_of(&policy, "ghost"), &MacroState::Missing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_missing_rows_without_an_allowlist() {
|
||||
let policy = resolve(globals(&["a"]), None, None, None, None);
|
||||
|
||||
assert_eq!(policy.macros.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtin_name_collision_is_shadowed() {
|
||||
let policy =
|
||||
MacroPolicy::effective_with(globals(&["help", "a"]), None, None, None, None, &["help"]);
|
||||
|
||||
assert_eq!(state_of(&policy, "help"), &MacroState::ShadowedBuiltin);
|
||||
assert_eq!(state_of(&policy, "a"), &MacroState::Enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_wins_over_shadowed_builtin() {
|
||||
let l = list(&["a"]);
|
||||
|
||||
let policy = MacroPolicy::effective_with(
|
||||
globals(&["help", "a"]),
|
||||
Some(&l),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&["help"],
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
state_of(&policy, "help"),
|
||||
&MacroState::Locked {
|
||||
level: MacroAllowlistLevel::Session
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allowlisted_builtin_collision_stays_shadowed() {
|
||||
let l = list(&["help"]);
|
||||
|
||||
let policy =
|
||||
MacroPolicy::effective_with(globals(&["help"]), None, None, None, Some(&l), &["help"]);
|
||||
|
||||
assert_eq!(state_of(&policy, "help"), &MacroState::ShadowedBuiltin);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserved_names_are_invalid() {
|
||||
let policy = resolve(globals(&["enable", "disable"]), None, None, None, None);
|
||||
for name in RESERVED_MACRO_NAMES {
|
||||
assert_eq!(
|
||||
state_of(&policy, name),
|
||||
&MacroState::Invalid {
|
||||
reason: format!("'{name}' is a reserved macro name")
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserved_name_invalid_even_when_allowlisted() {
|
||||
let l = list(&["enable"]);
|
||||
|
||||
let policy = resolve(globals(&["enable"]), Some(&l), None, None, None);
|
||||
|
||||
assert_eq!(
|
||||
state_of(&policy, "enable"),
|
||||
&MacroState::Invalid {
|
||||
reason: "'enable' is a reserved macro name".to_string()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserved_name_invalid_wins_over_builtin_collision() {
|
||||
let policy =
|
||||
MacroPolicy::effective_with(globals(&["enable"]), None, None, None, None, &["enable"]);
|
||||
|
||||
assert_eq!(
|
||||
state_of(&policy, "enable"),
|
||||
&MacroState::Invalid {
|
||||
reason: "'enable' is a reserved macro name".to_string()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_failure_is_invalid() {
|
||||
let policy = resolve(vec![disc_invalid("bad", "boom")], None, None, None, None);
|
||||
|
||||
assert_eq!(
|
||||
state_of(&policy, "bad"),
|
||||
&MacroState::Invalid {
|
||||
reason: "boom".to_string()
|
||||
}
|
||||
);
|
||||
let bad = policy.macros.iter().find(|m| m.name == "bad").unwrap();
|
||||
assert_eq!(bad.description, None);
|
||||
assert_eq!(bad.isolated, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_wins_over_allowlist_exclusion() {
|
||||
let l = list(&["other"]);
|
||||
|
||||
let policy = resolve(
|
||||
vec![disc_invalid("bad", "boom")],
|
||||
Some(&l),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
state_of(&policy, "bad"),
|
||||
&MacroState::Invalid {
|
||||
reason: "boom".to_string()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_shadowing_keeps_both_rows_and_find_returns_workspace() {
|
||||
let discovered = vec![
|
||||
disc("a", MacroSource::Workspace),
|
||||
DiscoveredMacro {
|
||||
shadowed_by_workspace: true,
|
||||
..disc("a", MacroSource::Global)
|
||||
},
|
||||
];
|
||||
|
||||
let policy = resolve(discovered, None, None, None, None);
|
||||
|
||||
assert_eq!(policy.macros.len(), 2);
|
||||
assert_eq!(policy.macros[0].source, Some(MacroSource::Workspace));
|
||||
assert!(!policy.macros[0].shadowed_by_workspace);
|
||||
assert_eq!(policy.macros[1].source, Some(MacroSource::Global));
|
||||
assert!(policy.macros[1].shadowed_by_workspace);
|
||||
let found = policy.find("a").unwrap();
|
||||
assert_eq!(found.source, Some(MacroSource::Workspace));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_skips_missing_rows() {
|
||||
let l = list(&["ghost"]);
|
||||
|
||||
let policy = resolve(vec![], None, None, None, Some(&l));
|
||||
|
||||
assert!(policy.find("ghost").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_are_sorted_by_name() {
|
||||
let policy = resolve(globals(&["c", "a", "b"]), None, None, None, None);
|
||||
|
||||
let names: Vec<&str> = policy.macros.iter().map(|m| m.name.as_str()).collect();
|
||||
assert_eq!(names, vec!["a", "b", "c"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolved_rows_carry_description_and_isolated() {
|
||||
let policy = resolve(globals(&["a"]), None, None, None, None);
|
||||
|
||||
let row = policy.macros.first().unwrap();
|
||||
assert_eq!(row.description.as_deref(), Some("a test macro"));
|
||||
assert_eq!(row.isolated, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_invocable_only_for_enabled_and_shadowed() {
|
||||
assert!(MacroState::Enabled.is_invocable());
|
||||
assert!(MacroState::ShadowedBuiltin.is_invocable());
|
||||
assert!(!MacroState::DisabledRuntime.is_invocable());
|
||||
assert!(
|
||||
!MacroState::Locked {
|
||||
level: MacroAllowlistLevel::Role
|
||||
}
|
||||
.is_invocable()
|
||||
);
|
||||
assert!(!MacroState::Missing.is_invocable());
|
||||
assert!(
|
||||
!MacroState::Invalid {
|
||||
reason: "x".to_string()
|
||||
}
|
||||
.is_invocable()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn level_and_source_display() {
|
||||
assert_eq!(MacroAllowlistLevel::Session.to_string(), "session");
|
||||
assert_eq!(MacroAllowlistLevel::Agent.to_string(), "agent");
|
||||
assert_eq!(MacroAllowlistLevel::Role.to_string(), "role");
|
||||
assert_eq!(MacroAllowlistLevel::Global.to_string(), "global");
|
||||
assert_eq!(MacroSource::Workspace.to_string(), "workspace");
|
||||
assert_eq!(MacroSource::Global.to_string(), "global");
|
||||
}
|
||||
|
||||
fn with_macro_dirs<F: FnOnce(&Path, &Path)>(f: F) {
|
||||
static COUNTER: AtomicUsize = AtomicUsize::new(0);
|
||||
let unique = format!(
|
||||
"{}-{}",
|
||||
process::id(),
|
||||
COUNTER.fetch_add(1, Ordering::Relaxed)
|
||||
);
|
||||
let root = env::temp_dir().join(format!("coyote-macro-policy-test-{unique}"));
|
||||
let workspace = root.join("workspace-macros");
|
||||
let global = root.join("global-macros");
|
||||
fs::create_dir_all(&workspace).unwrap();
|
||||
fs::create_dir_all(&global).unwrap();
|
||||
f(&workspace, &global);
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
fn write_macro(dir: &Path, name: &str, content: &str) {
|
||||
fs::write(dir.join(format!("{name}.yaml")), content).unwrap();
|
||||
}
|
||||
|
||||
const VALID_YAML: &str = "steps:\n - \".help\"\n";
|
||||
|
||||
#[test]
|
||||
fn discovery_scans_workspace_then_global_with_shadowing() {
|
||||
with_macro_dirs(|workspace, global| {
|
||||
write_macro(workspace, "both", VALID_YAML);
|
||||
write_macro(workspace, "ws-only", VALID_YAML);
|
||||
write_macro(global, "both", VALID_YAML);
|
||||
write_macro(global, "global-only", VALID_YAML);
|
||||
|
||||
let discovered = discover_macros_in(&[
|
||||
(MacroSource::Workspace, workspace.to_path_buf()),
|
||||
(MacroSource::Global, global.to_path_buf()),
|
||||
]);
|
||||
|
||||
assert_eq!(discovered.len(), 4);
|
||||
let both_ws = discovered
|
||||
.iter()
|
||||
.find(|d| d.name == "both" && d.source == MacroSource::Workspace)
|
||||
.unwrap();
|
||||
assert!(!both_ws.shadowed_by_workspace);
|
||||
let both_global = discovered
|
||||
.iter()
|
||||
.find(|d| d.name == "both" && d.source == MacroSource::Global)
|
||||
.unwrap();
|
||||
assert!(both_global.shadowed_by_workspace);
|
||||
let global_only = discovered.iter().find(|d| d.name == "global-only").unwrap();
|
||||
assert!(!global_only.shadowed_by_workspace);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovery_ignores_non_yaml_files_and_directories() {
|
||||
with_macro_dirs(|_, global| {
|
||||
write_macro(global, "good", VALID_YAML);
|
||||
fs::write(global.join("notes.txt"), "not a macro").unwrap();
|
||||
fs::write(global.join(".yaml"), VALID_YAML).unwrap();
|
||||
fs::create_dir_all(global.join("subdir.yaml")).unwrap();
|
||||
|
||||
let discovered = discover_macros_in(&[(MacroSource::Global, global.to_path_buf())]);
|
||||
|
||||
assert_eq!(discovered.len(), 1);
|
||||
assert_eq!(discovered[0].name, "good");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovery_records_parse_failures() {
|
||||
with_macro_dirs(|_, global| {
|
||||
write_macro(global, "broken", "steps: {not valid");
|
||||
|
||||
let discovered = discover_macros_in(&[(MacroSource::Global, global.to_path_buf())]);
|
||||
|
||||
assert_eq!(discovered.len(), 1);
|
||||
assert!(discovered[0].definition.is_err());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discovery_of_nonexistent_dirs_is_empty() {
|
||||
let discovered = discover_macros_in(&[(
|
||||
MacroSource::Global,
|
||||
PathBuf::from("/nonexistent/coyote-macro-policy-test"),
|
||||
)]);
|
||||
assert!(discovered.is_empty());
|
||||
}
|
||||
|
||||
fn with_macro_dir_envs<F: FnOnce()>(workspace: &Path, global: &Path, f: F) {
|
||||
let ws_env = get_env_name("workspace_config_dir");
|
||||
let global_env = get_env_name("macros_dir");
|
||||
let prev_ws = env::var_os(&ws_env);
|
||||
let prev_global = env::var_os(&global_env);
|
||||
unsafe {
|
||||
env::set_var(&ws_env, workspace);
|
||||
env::set_var(&global_env, global);
|
||||
}
|
||||
f();
|
||||
unsafe {
|
||||
match prev_ws {
|
||||
Some(v) => env::set_var(&ws_env, v),
|
||||
None => env::remove_var(&ws_env),
|
||||
}
|
||||
match prev_global {
|
||||
Some(v) => env::set_var(&global_env, v),
|
||||
None => env::remove_var(&global_env),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn discover_macros_honors_no_workspace_macros() {
|
||||
with_macro_dirs(|workspace_root, global| {
|
||||
let macros_subdir = workspace_root.join("macros");
|
||||
fs::create_dir_all(¯os_subdir).unwrap();
|
||||
write_macro(¯os_subdir, "ws-macro", VALID_YAML);
|
||||
write_macro(global, "global-macro", VALID_YAML);
|
||||
|
||||
with_macro_dir_envs(workspace_root, global, || {
|
||||
let with_workspace = discover_macros(false);
|
||||
let names: Vec<&str> = with_workspace.iter().map(|d| d.name.as_str()).collect();
|
||||
assert!(names.contains(&"ws-macro"));
|
||||
assert!(names.contains(&"global-macro"));
|
||||
|
||||
let without_workspace = discover_macros(true);
|
||||
let names: Vec<&str> = without_workspace.iter().map(|d| d.name.as_str()).collect();
|
||||
assert!(!names.contains(&"ws-macro"));
|
||||
assert!(names.contains(&"global-macro"));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn effective_honors_no_workspace_macros() {
|
||||
with_macro_dirs(|workspace_root, global| {
|
||||
let macros_subdir = workspace_root.join("macros");
|
||||
fs::create_dir_all(¯os_subdir).unwrap();
|
||||
write_macro(¯os_subdir, "shared", VALID_YAML);
|
||||
write_macro(¯os_subdir, "ws-only", VALID_YAML);
|
||||
write_macro(global, "shared", VALID_YAML);
|
||||
write_macro(global, "global-only", VALID_YAML);
|
||||
|
||||
with_macro_dir_envs(workspace_root, global, || {
|
||||
let config = AppConfig::default();
|
||||
|
||||
let policy = MacroPolicy::effective(&config, None, None, None, &[], false);
|
||||
assert_eq!(
|
||||
policy.find("shared").unwrap().source,
|
||||
Some(MacroSource::Workspace)
|
||||
);
|
||||
assert!(policy.find("ws-only").is_some());
|
||||
assert!(policy.find("global-only").is_some());
|
||||
|
||||
let policy = MacroPolicy::effective(&config, None, None, None, &[], true);
|
||||
assert_eq!(
|
||||
policy.find("shared").unwrap().source,
|
||||
Some(MacroSource::Global)
|
||||
);
|
||||
assert!(policy.find("ws-only").is_none());
|
||||
assert!(policy.find("global-only").is_some());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn effective_resolves_role_session_and_global_levels() {
|
||||
with_macro_dirs(|workspace_root, global_dir| {
|
||||
write_macro(global_dir, "a", VALID_YAML);
|
||||
write_macro(global_dir, "b", VALID_YAML);
|
||||
|
||||
with_macro_dir_envs(workspace_root, global_dir, || {
|
||||
let global = AppConfig {
|
||||
enabled_macros: Some(vec!["a".to_string()]),
|
||||
..AppConfig::default()
|
||||
};
|
||||
|
||||
let policy = MacroPolicy::effective(&global, None, None, None, &[], false);
|
||||
assert_eq!(state_of(&policy, "a"), &MacroState::Enabled);
|
||||
assert_eq!(state_of(&policy, "b"), &MacroState::DisabledRuntime);
|
||||
|
||||
let role = Role::new("test", "---\nenabled_macros: b\n---\nbody");
|
||||
let policy = MacroPolicy::effective(&global, Some(&role), None, None, &[], false);
|
||||
assert_eq!(
|
||||
state_of(&policy, "a"),
|
||||
&MacroState::Locked {
|
||||
level: MacroAllowlistLevel::Role
|
||||
}
|
||||
);
|
||||
assert_eq!(state_of(&policy, "b"), &MacroState::Enabled);
|
||||
|
||||
let session: Session = serde_yaml::from_str(
|
||||
"model: provider:test\nenabled_macros: \"a\"\nmessages: []",
|
||||
)
|
||||
.unwrap();
|
||||
let policy =
|
||||
MacroPolicy::effective(&global, Some(&role), None, Some(&session), &[], false);
|
||||
assert_eq!(state_of(&policy, "a"), &MacroState::Enabled);
|
||||
assert_eq!(
|
||||
state_of(&policy, "b"),
|
||||
&MacroState::Locked {
|
||||
level: MacroAllowlistLevel::Session
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn effective_pins_empty_string_role_allowlist_as_explicit_zero() {
|
||||
with_macro_dirs(|workspace_root, global_dir| {
|
||||
write_macro(global_dir, "a", VALID_YAML);
|
||||
|
||||
with_macro_dir_envs(workspace_root, global_dir, || {
|
||||
let global = AppConfig {
|
||||
enabled_macros: Some(vec!["a".to_string()]),
|
||||
..AppConfig::default()
|
||||
};
|
||||
let role = Role::new("test", "---\nenabled_macros: \"\"\n---\nbody");
|
||||
|
||||
let policy = MacroPolicy::effective(&global, Some(&role), None, None, &[], false);
|
||||
assert_eq!(
|
||||
state_of(&policy, "a"),
|
||||
&MacroState::Locked {
|
||||
level: MacroAllowlistLevel::Role
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
+827
-27
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
use crate::mcp::{
|
||||
ConnectedServer, JsonField, McpServer, McpTransportType, is_auth_required_error, oauth,
|
||||
spawn_mcp_server,
|
||||
ConnectedServer, JsonField, McpAuthRequired, McpServer, McpTransportType,
|
||||
is_auth_required_error, resolve_http_auth, spawn_mcp_server,
|
||||
};
|
||||
|
||||
use anyhow::Result;
|
||||
@@ -102,19 +102,13 @@ impl McpFactory {
|
||||
return Ok(existing);
|
||||
}
|
||||
|
||||
let bearer_token = if spec.is_remote() {
|
||||
oauth::load_valid_mcp_token(name)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let handle = spawn_mcp_server(spec, log_path, bearer_token)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
let (auth, auth_reason) = resolve_http_auth(name, spec).await;
|
||||
let handle = spawn_mcp_server(spec, log_path, auth).await.map_err(|e| {
|
||||
if is_auth_required_error(&e) {
|
||||
e.context(format!(
|
||||
"MCP server '{name}' requires OAuth authentication. \
|
||||
Run `coyote --auth-mcp {name}` or `.mcp auth {name}` in the REPL to authenticate."
|
||||
))
|
||||
e.context(McpAuthRequired {
|
||||
server: name.to_string(),
|
||||
reason: auth_reason,
|
||||
})
|
||||
} else {
|
||||
e
|
||||
}
|
||||
|
||||
+63
-1
@@ -1,9 +1,11 @@
|
||||
mod agent;
|
||||
mod app_config;
|
||||
mod app_state;
|
||||
mod bundles;
|
||||
mod input;
|
||||
mod install_remote;
|
||||
pub(crate) mod instructions;
|
||||
mod macro_policy;
|
||||
mod macros;
|
||||
mod mcp_factory;
|
||||
pub(crate) mod memory;
|
||||
@@ -28,8 +30,15 @@ pub use self::agent::{
|
||||
pub use self::app_config::AppConfig;
|
||||
#[allow(unused_imports)]
|
||||
pub use self::app_state::AppState;
|
||||
pub use self::bundles::list_installed_bundles;
|
||||
pub use self::input::Input;
|
||||
pub use self::install_remote::{install_remote, install_remote_from_repl_args};
|
||||
pub use self::install_remote::{
|
||||
DEFAULT_GIT_HOST, install_or_update, install_or_update_from_repl_args, uninstall_bundle,
|
||||
update_bundle,
|
||||
};
|
||||
pub use self::macro_policy::{
|
||||
MacroAllowlistLevel, MacroPolicy, MacroSource, MacroState, RESERVED_MACRO_NAMES, ResolvedMacro,
|
||||
};
|
||||
#[allow(unused_imports)]
|
||||
pub use self::request_context::{RenderMode, RequestContext, should_inject_skill_instructions};
|
||||
pub use self::role::{
|
||||
@@ -151,6 +160,8 @@ const SBX_KIT_DIR_NAME: &str = "sbx-kit";
|
||||
const SBX_KIT_HASH_FILE: &str = "kit.sha256";
|
||||
const SBX_MIXIN_FILE_NAME: &str = "sbx-mixin.yaml";
|
||||
pub(crate) const VAULT_DATA_FILE_NAME: &str = "vault.yml";
|
||||
const INSTALLED_BUNDLES_FILE_NAME: &str = "installed-bundles.yaml";
|
||||
const BUNDLE_MANIFEST_FILE: &str = "coyote-bundle.yaml";
|
||||
const SBX_MIXIN_KITS_DIR_NAME: &str = "sbx-mixin-kits";
|
||||
const GIT_DIR_NAME: &str = ".git";
|
||||
const GITIGNORE_FILE_NAME: &str = ".gitignore";
|
||||
@@ -221,6 +232,8 @@ pub struct Config {
|
||||
#[serde(default, deserialize_with = "deserialize_csv_or_vec")]
|
||||
pub enabled_skills: Option<Vec<String>>,
|
||||
pub visible_skills: Option<Vec<String>>,
|
||||
#[serde(default, deserialize_with = "deserialize_csv_or_vec")]
|
||||
pub enabled_macros: Option<Vec<String>>,
|
||||
|
||||
pub mcp_server_support: bool,
|
||||
pub mapping_mcp_servers: IndexMap<String, String>,
|
||||
@@ -303,6 +316,7 @@ impl Default for Config {
|
||||
skills_enabled: true,
|
||||
enabled_skills: None,
|
||||
visible_skills: None,
|
||||
enabled_macros: None,
|
||||
|
||||
mcp_server_support: true,
|
||||
mapping_mcp_servers: Default::default(),
|
||||
@@ -1124,9 +1138,50 @@ clients:
|
||||
assert!(cfg.enabled_mcp_servers.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_enabled_macros_absent_is_none() {
|
||||
let cfg: Config = serde_yaml::from_str("model: provider:test").unwrap();
|
||||
assert_eq!(cfg.enabled_macros, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_enabled_macros_empty_string_is_some_empty() {
|
||||
let cfg: Config = serde_yaml::from_str("enabled_macros: \"\"").unwrap();
|
||||
|
||||
assert_eq!(cfg.enabled_macros, Some(vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_enabled_macros_csv_string() {
|
||||
let cfg: Config = serde_yaml::from_str("enabled_macros: \"a, b\"").unwrap();
|
||||
|
||||
assert_eq!(
|
||||
cfg.enabled_macros,
|
||||
Some(vec!["a".to_string(), "b".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_enabled_macros_list() {
|
||||
let cfg: Config = serde_yaml::from_str("enabled_macros:\n - a\n - b").unwrap();
|
||||
|
||||
assert_eq!(
|
||||
cfg.enabled_macros,
|
||||
Some(vec!["a".to_string(), "b".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_enabled_macros_null_is_none() {
|
||||
let cfg: Config = serde_yaml::from_str("enabled_macros: null").unwrap();
|
||||
|
||||
assert_eq!(cfg.enabled_macros, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assert_state_pass_always_true() {
|
||||
let pass = AssertState::pass();
|
||||
|
||||
assert!(pass.assert(StateFlags::empty()));
|
||||
assert!(pass.assert(StateFlags::ROLE));
|
||||
assert!(pass.assert(StateFlags::SESSION | StateFlags::AGENT));
|
||||
@@ -1136,6 +1191,7 @@ clients:
|
||||
#[test]
|
||||
fn assert_state_bare_only_empty() {
|
||||
let bare = AssertState::bare();
|
||||
|
||||
assert!(bare.assert(StateFlags::empty()));
|
||||
assert!(!bare.assert(StateFlags::ROLE));
|
||||
assert!(!bare.assert(StateFlags::SESSION));
|
||||
@@ -1144,6 +1200,7 @@ clients:
|
||||
#[test]
|
||||
fn assert_state_true_requires_flag_present() {
|
||||
let state = AssertState::True(StateFlags::ROLE);
|
||||
|
||||
assert!(state.assert(StateFlags::ROLE));
|
||||
assert!(state.assert(StateFlags::ROLE | StateFlags::SESSION));
|
||||
assert!(!state.assert(StateFlags::empty()));
|
||||
@@ -1153,6 +1210,7 @@ clients:
|
||||
#[test]
|
||||
fn assert_state_true_with_multiple_flags_any_match() {
|
||||
let state = AssertState::True(StateFlags::SESSION_EMPTY | StateFlags::SESSION);
|
||||
|
||||
assert!(state.assert(StateFlags::SESSION_EMPTY));
|
||||
assert!(state.assert(StateFlags::SESSION));
|
||||
assert!(state.assert(StateFlags::SESSION | StateFlags::ROLE));
|
||||
@@ -1163,6 +1221,7 @@ clients:
|
||||
#[test]
|
||||
fn assert_state_false_requires_flag_absent() {
|
||||
let state = AssertState::False(StateFlags::AGENT);
|
||||
|
||||
assert!(state.assert(StateFlags::empty()));
|
||||
assert!(state.assert(StateFlags::ROLE));
|
||||
assert!(!state.assert(StateFlags::AGENT));
|
||||
@@ -1172,6 +1231,7 @@ clients:
|
||||
#[test]
|
||||
fn assert_state_false_with_multiple_flags() {
|
||||
let state = AssertState::False(StateFlags::SESSION | StateFlags::AGENT);
|
||||
|
||||
assert!(state.assert(StateFlags::empty()));
|
||||
assert!(state.assert(StateFlags::ROLE));
|
||||
assert!(!state.assert(StateFlags::SESSION));
|
||||
@@ -1182,6 +1242,7 @@ clients:
|
||||
#[test]
|
||||
fn assert_state_truefalse_requires_true_present_and_false_absent() {
|
||||
let state = AssertState::TrueFalse(StateFlags::ROLE, StateFlags::SESSION);
|
||||
|
||||
assert!(state.assert(StateFlags::ROLE));
|
||||
assert!(state.assert(StateFlags::ROLE | StateFlags::RAG));
|
||||
assert!(!state.assert(StateFlags::empty()));
|
||||
@@ -1192,6 +1253,7 @@ clients:
|
||||
#[test]
|
||||
fn assert_state_equal_exact_match() {
|
||||
let state = AssertState::Equal(StateFlags::ROLE | StateFlags::SESSION);
|
||||
|
||||
assert!(state.assert(StateFlags::ROLE | StateFlags::SESSION));
|
||||
assert!(!state.assert(StateFlags::ROLE));
|
||||
assert!(!state.assert(StateFlags::SESSION));
|
||||
|
||||
+30
-10
@@ -2,10 +2,10 @@ use super::role::Role;
|
||||
use super::{
|
||||
AGENT_GRAPH_FILE_NAME, AGENTS_DIR_NAME, BASH_PROMPT_UTILS_FILE_NAME, CONFIG_FILE_NAME,
|
||||
ENV_FILE_NAME, FUNCTIONS_BIN_DIR_NAME, FUNCTIONS_DIR_NAME, GLOBAL_TOOLS_DIR_NAME,
|
||||
GLOBAL_TOOLS_UTILS_DIR_NAME, HIDDEN_MCP_FILE_NAME, MACROS_DIR_NAME, MCP_FILE_NAME,
|
||||
MEMORY_DIR_NAME, MEMORY_INDEX_FILE_NAME, ModelsOverride, RAGS_DIR_NAME, ROLES_DIR_NAME,
|
||||
SBX_KIT_DIR_NAME, SBX_KIT_HASH_FILE, SBX_MIXIN_FILE_NAME, SBX_MIXIN_KITS_DIR_NAME,
|
||||
SKILLS_DIR_NAME, WORKSPACE_COYOTE_DIR_NAME,
|
||||
GLOBAL_TOOLS_UTILS_DIR_NAME, HIDDEN_MCP_FILE_NAME, INSTALLED_BUNDLES_FILE_NAME,
|
||||
MACROS_DIR_NAME, MCP_FILE_NAME, MEMORY_DIR_NAME, MEMORY_INDEX_FILE_NAME, ModelsOverride,
|
||||
RAGS_DIR_NAME, ROLES_DIR_NAME, SBX_KIT_DIR_NAME, SBX_KIT_HASH_FILE, SBX_MIXIN_FILE_NAME,
|
||||
SBX_MIXIN_KITS_DIR_NAME, SKILLS_DIR_NAME, WORKSPACE_COYOTE_DIR_NAME,
|
||||
};
|
||||
use crate::client::ProviderModels;
|
||||
use crate::config::REPL_HISTORY_DIR_NAME;
|
||||
@@ -148,6 +148,16 @@ pub fn sbx_kit_hash_file() -> PathBuf {
|
||||
sbx_kit_dir().join(SBX_KIT_HASH_FILE)
|
||||
}
|
||||
|
||||
pub fn sandbox_mixin_hashes_dir() -> PathBuf {
|
||||
cache_dir().join("sandbox-mixin-hashes")
|
||||
}
|
||||
|
||||
pub fn sandbox_mixin_hash_file(sandbox_name: &str) -> PathBuf {
|
||||
// Sandbox names are sanitized by the caller, but never trust a path
|
||||
// component: a stray separator must not escape the hash directory.
|
||||
sandbox_mixin_hashes_dir().join(format!("{}.hash", sandbox_name.replace('/', "_")))
|
||||
}
|
||||
|
||||
pub fn sbx_mixin_kits_dir() -> PathBuf {
|
||||
cache_dir().join(SBX_MIXIN_KITS_DIR_NAME)
|
||||
}
|
||||
@@ -159,6 +169,10 @@ pub fn config_file() -> PathBuf {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn installed_bundles_file() -> PathBuf {
|
||||
local_dir(INSTALLED_BUNDLES_FILE_NAME)
|
||||
}
|
||||
|
||||
pub fn roles_dir() -> PathBuf {
|
||||
match env::var(get_env_name("roles_dir")) {
|
||||
Ok(value) => PathBuf::from(value),
|
||||
@@ -204,6 +218,10 @@ pub fn workspace_skill_file(name: &str) -> PathBuf {
|
||||
workspace_skills_dir().join(name).join("SKILL.md")
|
||||
}
|
||||
|
||||
pub fn workspace_macros_dir() -> PathBuf {
|
||||
workspace_config_dir().join(MACROS_DIR_NAME)
|
||||
}
|
||||
|
||||
pub fn workspace_mcp_config_file() -> Option<PathBuf> {
|
||||
workspace_mcp_config_file_in(&env::current_dir().unwrap_or_default())
|
||||
}
|
||||
@@ -437,6 +455,10 @@ pub(crate) fn remove_rag_sidecars(dir: &Path, name: &str) -> Result<()> {
|
||||
if duckdb_path.exists() {
|
||||
let _ = remove_file(&duckdb_path);
|
||||
}
|
||||
let wal_path = dir.join(format!("{name}.duckdb.wal"));
|
||||
if wal_path.exists() {
|
||||
let _ = remove_file(&wal_path);
|
||||
}
|
||||
let mixin_path = dir.join(format!("{name}.sbx-mixin.yaml"));
|
||||
if mixin_path.exists() {
|
||||
remove_file(&mixin_path).with_context(|| {
|
||||
@@ -456,11 +478,6 @@ pub fn list_macros() -> Vec<String> {
|
||||
list_file_names(macros_dir(), ".yaml")
|
||||
}
|
||||
|
||||
pub fn has_macro(name: &str) -> bool {
|
||||
let names = list_macros();
|
||||
names.contains(&name.to_string())
|
||||
}
|
||||
|
||||
pub fn list_skills() -> Vec<String> {
|
||||
let mut names = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
@@ -894,16 +911,19 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_rag_sidecars_removes_both() {
|
||||
fn remove_rag_sidecars_removes_duckdb_wal_and_mixin() {
|
||||
let root = sidecar_temp_dir("rag-sidecars-both");
|
||||
let duckdb = root.join("docs.duckdb");
|
||||
let wal = root.join("docs.duckdb.wal");
|
||||
let mixin = root.join("docs.sbx-mixin.yaml");
|
||||
fs::write(&duckdb, "db").unwrap();
|
||||
fs::write(&wal, "wal").unwrap();
|
||||
fs::write(&mixin, "mixin").unwrap();
|
||||
|
||||
remove_rag_sidecars(&root, "docs").unwrap();
|
||||
|
||||
assert!(!duckdb.exists(), "the .duckdb sidecar must be removed");
|
||||
assert!(!wal.exists(), "the .duckdb.wal sidecar must be removed");
|
||||
assert!(
|
||||
!mixin.exists(),
|
||||
"the .sbx-mixin.yaml sidecar must be removed"
|
||||
|
||||
+673
-57
File diff suppressed because it is too large
Load Diff
@@ -75,6 +75,12 @@ pub struct Role {
|
||||
deserialize_with = "super::deserialize_csv_or_vec"
|
||||
)]
|
||||
enabled_skills: Option<Vec<String>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "super::deserialize_csv_or_vec"
|
||||
)]
|
||||
enabled_macros: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
auto_continue: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -129,6 +135,7 @@ impl Role {
|
||||
}
|
||||
"skills_enabled" => role.skills_enabled = value.as_bool(),
|
||||
"enabled_skills" => role.enabled_skills = parse_string_or_array(value),
|
||||
"enabled_macros" => role.enabled_macros = parse_string_or_array(value),
|
||||
"auto_continue" => role.auto_continue = value.as_bool(),
|
||||
"max_auto_continues" => {
|
||||
role.max_auto_continues = value.as_u64().map(|v| v as usize)
|
||||
@@ -196,6 +203,10 @@ impl Role {
|
||||
let inline = serde_json::to_string(enabled_skills).unwrap_or_else(|_| "[]".to_string());
|
||||
metadata.push(format!("enabled_skills: {inline}"));
|
||||
}
|
||||
if let Some(enabled_macros) = &self.enabled_macros {
|
||||
let inline = serde_json::to_string(enabled_macros).unwrap_or_else(|_| "[]".to_string());
|
||||
metadata.push(format!("enabled_macros: {inline}"));
|
||||
}
|
||||
if let Some(auto_continue) = self.auto_continue {
|
||||
metadata.push(format!("auto_continue: {auto_continue}"));
|
||||
}
|
||||
@@ -357,6 +368,10 @@ impl Role {
|
||||
self.enabled_skills.as_deref()
|
||||
}
|
||||
|
||||
pub fn enabled_macros(&self) -> Option<&[String]> {
|
||||
self.enabled_macros.as_deref()
|
||||
}
|
||||
|
||||
pub fn append_to_prompt(&mut self, text: &str) {
|
||||
self.prompt.push_str(text);
|
||||
}
|
||||
@@ -543,6 +558,7 @@ mod tests {
|
||||
#[test]
|
||||
fn role_new_parses_prompt() {
|
||||
let role = Role::new("test", "You are a helpful assistant");
|
||||
|
||||
assert_eq!(role.name(), "test");
|
||||
assert_eq!(role.prompt(), "You are a helpful assistant");
|
||||
}
|
||||
@@ -551,7 +567,9 @@ mod tests {
|
||||
fn role_new_parses_metadata() {
|
||||
let content =
|
||||
"---\nmodel: openai:gpt-4\ntemperature: 0.7\ntop_p: 0.9\n---\nYou are helpful";
|
||||
|
||||
let role = Role::new("test", content);
|
||||
|
||||
assert_eq!(role.model_id(), Some("openai:gpt-4"));
|
||||
assert_eq!(role.temperature(), Some(0.7));
|
||||
assert_eq!(role.top_p(), Some(0.9));
|
||||
@@ -561,7 +579,9 @@ mod tests {
|
||||
#[test]
|
||||
fn role_new_parses_enabled_tools() {
|
||||
let content = "---\nenabled_tools: tool1,tool2\n---\nPrompt";
|
||||
|
||||
let role = Role::new("test", content);
|
||||
|
||||
assert_eq!(
|
||||
role.enabled_tools(),
|
||||
Some(vec!["tool1".to_string(), "tool2".to_string()])
|
||||
@@ -571,7 +591,9 @@ mod tests {
|
||||
#[test]
|
||||
fn role_new_parses_enabled_mcp_servers() {
|
||||
let content = "---\nenabled_mcp_servers: github,jira\n---\nPrompt";
|
||||
|
||||
let role = Role::new("test", content);
|
||||
|
||||
assert_eq!(
|
||||
role.enabled_mcp_servers(),
|
||||
Some(vec!["github".to_string(), "jira".to_string()])
|
||||
@@ -581,6 +603,7 @@ mod tests {
|
||||
#[test]
|
||||
fn role_new_no_metadata_has_none_fields() {
|
||||
let role = Role::new("test", "Just a prompt");
|
||||
|
||||
assert_eq!(role.model_id(), None);
|
||||
assert_eq!(role.temperature(), None);
|
||||
assert_eq!(role.top_p(), None);
|
||||
@@ -588,9 +611,67 @@ mod tests {
|
||||
assert_eq!(role.enabled_mcp_servers(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_new_enabled_macros_absent_is_none() {
|
||||
let role = Role::new("test", "---\ntemperature: 0.5\n---\nPrompt");
|
||||
|
||||
assert_eq!(role.enabled_macros, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_new_enabled_macros_empty_string_is_some_empty() {
|
||||
let role = Role::new("test", "---\nenabled_macros: \"\"\n---\nPrompt");
|
||||
|
||||
assert_eq!(role.enabled_macros, Some(vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_new_enabled_macros_csv_string() {
|
||||
let role = Role::new("test", "---\nenabled_macros: a, b\n---\nPrompt");
|
||||
|
||||
assert_eq!(
|
||||
role.enabled_macros,
|
||||
Some(vec!["a".to_string(), "b".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_new_enabled_macros_list() {
|
||||
let role = Role::new("test", "---\nenabled_macros: [a, b]\n---\nPrompt");
|
||||
|
||||
assert_eq!(
|
||||
role.enabled_macros,
|
||||
Some(vec!["a".to_string(), "b".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_new_enabled_macros_null_is_none() {
|
||||
let role = Role::new("test", "---\nenabled_macros: null\n---\nPrompt");
|
||||
|
||||
assert_eq!(role.enabled_macros, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_export_includes_enabled_macros() {
|
||||
let role = Role::new("test", "---\nenabled_macros: [a]\n---\nPrompt");
|
||||
|
||||
let exported = role.export();
|
||||
|
||||
assert!(exported.contains("enabled_macros: [\"a\"]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_export_omits_enabled_macros_when_none() {
|
||||
let role = Role::new("test", "Just a prompt");
|
||||
|
||||
assert!(!role.export().contains("enabled_macros"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_builtin_shell_loads() {
|
||||
let role = Role::builtin("shell").unwrap();
|
||||
|
||||
assert_eq!(role.name(), "shell");
|
||||
assert!(!role.prompt().is_empty());
|
||||
}
|
||||
@@ -598,6 +679,7 @@ mod tests {
|
||||
#[test]
|
||||
fn role_builtin_code_loads() {
|
||||
let role = Role::builtin("code").unwrap();
|
||||
|
||||
assert_eq!(role.name(), "code");
|
||||
assert!(!role.prompt().is_empty());
|
||||
}
|
||||
@@ -605,12 +687,14 @@ mod tests {
|
||||
#[test]
|
||||
fn role_builtin_nonexistent_errors() {
|
||||
let result = Role::builtin("nonexistent_role_xyz");
|
||||
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_default_has_empty_fields() {
|
||||
let role = Role::default();
|
||||
|
||||
assert_eq!(role.name(), "");
|
||||
assert_eq!(role.prompt(), "");
|
||||
assert_eq!(role.model_id(), None);
|
||||
@@ -620,14 +704,18 @@ mod tests {
|
||||
fn role_set_model_updates_model() {
|
||||
let mut role = Role::new("test", "prompt");
|
||||
let model = Model::default();
|
||||
|
||||
role.set_model(model.clone());
|
||||
|
||||
assert_eq!(role.model().id(), model.id());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_set_temperature_works() {
|
||||
let mut role = Role::new("test", "prompt");
|
||||
|
||||
role.set_temperature(Some(0.5));
|
||||
|
||||
assert_eq!(role.temperature(), Some(0.5));
|
||||
}
|
||||
|
||||
@@ -635,7 +723,9 @@ mod tests {
|
||||
fn role_export_includes_metadata() {
|
||||
let content = "---\ntemperature: 0.8\n---\nMy prompt";
|
||||
let role = Role::new("test", content);
|
||||
|
||||
let exported = role.export();
|
||||
|
||||
assert!(exported.contains("temperature"));
|
||||
assert!(exported.contains("My prompt"));
|
||||
}
|
||||
@@ -649,6 +739,7 @@ Input 1
|
||||
### OUTPUT:
|
||||
Output 1
|
||||
"#;
|
||||
|
||||
assert_eq!(
|
||||
parse_structure_prompt(prompt),
|
||||
("System message", vec![("Input 1", "Output 1")])
|
||||
@@ -663,6 +754,7 @@ Input 1
|
||||
### OUTPUT:
|
||||
Output 1
|
||||
"#;
|
||||
|
||||
assert_eq!(
|
||||
parse_structure_prompt(prompt),
|
||||
("", vec![("Input 1", "Output 1")])
|
||||
@@ -676,6 +768,7 @@ System message
|
||||
### INPUT:
|
||||
Input 1
|
||||
"#;
|
||||
|
||||
assert_eq!(parse_structure_prompt(prompt), (prompt, vec![]));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +46,12 @@ pub struct Session {
|
||||
deserialize_with = "super::deserialize_csv_or_vec"
|
||||
)]
|
||||
enabled_skills: Option<Vec<String>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "super::deserialize_csv_or_vec"
|
||||
)]
|
||||
enabled_macros: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
save_session: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -107,6 +113,10 @@ impl Session {
|
||||
self.enabled_skills.as_deref()
|
||||
}
|
||||
|
||||
pub fn enabled_macros(&self) -> Option<&[String]> {
|
||||
self.enabled_macros.as_deref()
|
||||
}
|
||||
|
||||
pub fn set_skills_enabled(&mut self, value: Option<bool>) {
|
||||
if self.skills_enabled != value {
|
||||
self.skills_enabled = value;
|
||||
@@ -236,6 +246,9 @@ impl Session {
|
||||
if let Some(enabled_skills) = self.enabled_skills() {
|
||||
data["enabled_skills"] = json!(enabled_skills);
|
||||
}
|
||||
if let Some(enabled_macros) = self.enabled_macros() {
|
||||
data["enabled_macros"] = json!(enabled_macros);
|
||||
}
|
||||
if let Some(save_session) = self.save_session() {
|
||||
data["save_session"] = save_session.into();
|
||||
}
|
||||
@@ -315,6 +328,10 @@ impl Session {
|
||||
items.push(("enabled_skills", enabled_skills.join(",")));
|
||||
}
|
||||
|
||||
if let Some(enabled_macros) = self.enabled_macros() {
|
||||
items.push(("enabled_macros", enabled_macros.join(",")));
|
||||
}
|
||||
|
||||
if let Some(save_session) = self.save_session() {
|
||||
items.push(("save_session", save_session.to_string()));
|
||||
}
|
||||
@@ -925,12 +942,57 @@ mod tests {
|
||||
#[test]
|
||||
fn session_default_is_empty() {
|
||||
let session = Session::default();
|
||||
|
||||
assert!(session.is_empty());
|
||||
assert_eq!(session.name(), "");
|
||||
assert_eq!(session.role_name(), None);
|
||||
assert!(!session.dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_enabled_macros_absent_is_none() {
|
||||
let session: Session = serde_yaml::from_str("model: provider:test\nmessages: []").unwrap();
|
||||
|
||||
assert_eq!(session.enabled_macros, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_enabled_macros_empty_list_is_some_empty() {
|
||||
let session: Session =
|
||||
serde_yaml::from_str("model: provider:test\nenabled_macros: []\nmessages: []").unwrap();
|
||||
|
||||
assert_eq!(session.enabled_macros, Some(vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_enabled_macros_empty_string_is_some_empty() {
|
||||
let session: Session =
|
||||
serde_yaml::from_str("model: provider:test\nenabled_macros: \"\"\nmessages: []")
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(session.enabled_macros, Some(vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_enabled_macros_csv_string() {
|
||||
let session: Session =
|
||||
serde_yaml::from_str("model: provider:test\nenabled_macros: \"a,b\"\nmessages: []")
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
session.enabled_macros,
|
||||
Some(vec!["a".to_string(), "b".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_serialize_omits_enabled_macros_when_none() {
|
||||
let session = Session::default();
|
||||
let yaml = serde_yaml::to_string(&session).unwrap();
|
||||
|
||||
assert!(!yaml.contains("enabled_macros"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_new_from_ctx_captures_save_session() {
|
||||
let app_config = Arc::new(AppConfig::default());
|
||||
@@ -945,6 +1007,7 @@ mod tests {
|
||||
functions: Functions::default(),
|
||||
});
|
||||
let ctx = RequestContext::new(app_state, WorkingMode::Cmd);
|
||||
|
||||
let session = Session::new_from_ctx(&ctx, &app_config, "test-session").unwrap();
|
||||
|
||||
assert_eq!(session.name(), "test-session");
|
||||
@@ -984,25 +1047,30 @@ mod tests {
|
||||
#[test]
|
||||
fn session_guard_empty_passes_when_empty() {
|
||||
let session = Session::default();
|
||||
|
||||
assert!(session.guard_empty().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_needs_compression_threshold() {
|
||||
let session = Session::default();
|
||||
|
||||
assert!(!session.needs_compression(4000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_needs_compression_returns_false_when_compressing() {
|
||||
let mut session = Session::default();
|
||||
|
||||
session.set_compressing(true);
|
||||
|
||||
assert!(!session.needs_compression(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_needs_compression_returns_false_when_threshold_zero() {
|
||||
let session = Session::default();
|
||||
|
||||
assert!(!session.needs_compression(0));
|
||||
}
|
||||
|
||||
@@ -1074,13 +1142,16 @@ mod tests {
|
||||
#[test]
|
||||
fn session_need_autoname_default_false() {
|
||||
let session = Session::default();
|
||||
|
||||
assert!(!session.need_autoname());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_set_autonaming_doesnt_panic_without_autoname() {
|
||||
let mut session = Session::default();
|
||||
|
||||
session.set_autonaming(true);
|
||||
|
||||
assert!(!session.need_autoname());
|
||||
}
|
||||
|
||||
|
||||
+475
-98
@@ -1,4 +1,5 @@
|
||||
pub(crate) mod memory;
|
||||
pub(crate) mod rag_query;
|
||||
pub(crate) mod skill;
|
||||
pub(crate) mod supervisor;
|
||||
pub(crate) mod todo;
|
||||
@@ -23,20 +24,22 @@ use futures_util::future;
|
||||
use indexmap::IndexMap;
|
||||
use indoc::formatdoc;
|
||||
use memory::MEMORY_FUNCTION_PREFIX;
|
||||
use rag_query::RAG_FUNCTION_PREFIX;
|
||||
use rust_embed::Embed;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use skill::SKILL_FUNCTION_PREFIX;
|
||||
use std::collections::VecDeque;
|
||||
use std::ffi::OsStr;
|
||||
use std::fs::File;
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::{collections::VecDeque, thread};
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
env, fs, io,
|
||||
path::{Path, PathBuf},
|
||||
process::{Command, Stdio},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use strum_macros::AsRefStr;
|
||||
use supervisor::SUPERVISOR_FUNCTION_PREFIX;
|
||||
@@ -135,6 +138,123 @@ fn extract_shebang_runtime(path: &Path) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_file_atomic(
|
||||
path: &Path,
|
||||
content: &str,
|
||||
#[cfg_attr(not(unix), expect(unused))] mode: Option<u32>,
|
||||
) -> Result<()> {
|
||||
#[cfg(unix)]
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
if fs::read_to_string(path).is_ok_and(|existing| existing == content) {
|
||||
#[cfg(unix)]
|
||||
if let Some(mode) = mode {
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(mode))?;
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let file_name = path
|
||||
.file_name()
|
||||
.and_then(OsStr::to_str)
|
||||
.ok_or_else(|| anyhow!("Unable to extract file name from path: {}", path.display()))?;
|
||||
static TMP_COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let tmp = path.with_file_name(format!(
|
||||
".{file_name}.tmp.{}.{}",
|
||||
std::process::id(),
|
||||
TMP_COUNTER.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
let write_synced = || -> io::Result<()> {
|
||||
use std::io::Write;
|
||||
let mut file = File::create(&tmp)?;
|
||||
file.write_all(content.as_bytes())?;
|
||||
file.sync_all()
|
||||
};
|
||||
if let Err(err) = write_synced() {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(err.into());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
if let Some(mode) = mode {
|
||||
fs::set_permissions(&tmp, fs::Permissions::from_mode(mode))?;
|
||||
}
|
||||
|
||||
if let Err(err) = fs::rename(&tmp, path) {
|
||||
let _ = fs::remove_file(&tmp);
|
||||
return Err(err.into());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn tool_source_stems() -> Result<HashSet<String>> {
|
||||
let mut stems = HashSet::new();
|
||||
let tools_dir = paths::global_tools_dir();
|
||||
if !tools_dir.exists() {
|
||||
return Ok(stems);
|
||||
}
|
||||
|
||||
for entry in fs::read_dir(&tools_dir)? {
|
||||
let path = entry?.path();
|
||||
if path.is_file()
|
||||
&& let Some(stem) = path.file_stem().and_then(OsStr::to_str)
|
||||
{
|
||||
stems.insert(stem.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(stems)
|
||||
}
|
||||
|
||||
fn bin_entry_stem(file_name: &str) -> &str {
|
||||
let name = file_name.strip_prefix("run-").unwrap_or(file_name);
|
||||
Path::new(name)
|
||||
.file_stem()
|
||||
.and_then(OsStr::to_str)
|
||||
.unwrap_or(name)
|
||||
}
|
||||
|
||||
fn prune_stale_bin_entries(
|
||||
bin_dir: &Path,
|
||||
valid_stems: &HashSet<String>,
|
||||
extra_valid_stem: Option<&str>,
|
||||
) -> Result<()> {
|
||||
if !bin_dir.exists() {
|
||||
fs::create_dir_all(bin_dir)?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for entry in fs::read_dir(bin_dir)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
debug!(
|
||||
"Removing unexpected directory in bin dir: {}",
|
||||
path.display()
|
||||
);
|
||||
fs::remove_dir_all(&path)?;
|
||||
continue;
|
||||
}
|
||||
|
||||
let file_name = entry.file_name();
|
||||
let Some(file_name) = file_name.to_str() else {
|
||||
continue;
|
||||
};
|
||||
let stem = bin_entry_stem(file_name);
|
||||
|
||||
if valid_stems.contains(stem) || extra_valid_stem == Some(stem) {
|
||||
continue;
|
||||
}
|
||||
|
||||
debug!("Removing stale bin entry: {}", path.display());
|
||||
fs::remove_file(&path)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn eval_tool_calls(
|
||||
ctx: &mut RequestContext,
|
||||
mut calls: Vec<ToolCall>,
|
||||
@@ -183,42 +303,29 @@ pub async fn eval_tool_calls(
|
||||
})
|
||||
.collect();
|
||||
for (idx, call, result) in future::join_all(futs).await {
|
||||
indexed_results.push((idx, ToolResult::new(call, normalize_tool_result(result?))));
|
||||
let value = match result {
|
||||
Ok(v) => normalize_tool_result(v),
|
||||
Err(e) => json!({"tool_call_error": format!("{e}")}),
|
||||
};
|
||||
indexed_results.push((idx, ToolResult::new(call, value)));
|
||||
}
|
||||
}
|
||||
|
||||
for (idx, call) in sequential_calls {
|
||||
let result = call.eval(ctx).await?;
|
||||
indexed_results.push((idx, ToolResult::new(call, normalize_tool_result(result))));
|
||||
let value = match call.eval(ctx).await {
|
||||
Ok(v) => normalize_tool_result(v),
|
||||
Err(e) => json!({
|
||||
"tool_call_error": format!(
|
||||
"{e}. This tool is not available or the call failed; use only tools listed in your catalog."
|
||||
)
|
||||
}),
|
||||
};
|
||||
indexed_results.push((idx, ToolResult::new(call, value)));
|
||||
}
|
||||
|
||||
indexed_results.sort_unstable_by_key(|(idx, _)| *idx);
|
||||
output = indexed_results.into_iter().map(|(_, r)| r).collect();
|
||||
|
||||
if !output.is_empty() {
|
||||
let (has_escalations, summary) = if ctx.current_depth == 0
|
||||
&& let Some(queue) = ctx.root_escalation_queue()
|
||||
&& queue.has_pending()
|
||||
{
|
||||
(true, queue.pending_summary())
|
||||
} else {
|
||||
(false, vec![])
|
||||
};
|
||||
|
||||
if has_escalations {
|
||||
let notification = json!({
|
||||
"pending_escalations": summary,
|
||||
"instruction": "Child agents are BLOCKED waiting for your reply. Call agent__reply_escalation for each pending escalation to unblock them."
|
||||
});
|
||||
let synthetic_call = ToolCall::new(
|
||||
"__escalation_notification".to_string(),
|
||||
json!({}),
|
||||
Some("escalation_check".to_string()),
|
||||
);
|
||||
output.push(ToolResult::new(synthetic_call, notification));
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
let max_chars = ctx
|
||||
.agent
|
||||
@@ -233,6 +340,14 @@ pub async fn eval_tool_calls(
|
||||
}
|
||||
}
|
||||
|
||||
if ctx.current_depth == 0
|
||||
&& let Some(queue) = ctx.root_escalation_queue()
|
||||
&& queue.has_pending()
|
||||
&& let Some(last) = output.last_mut()
|
||||
{
|
||||
inject_escalation_notification(last, queue.pending_summary());
|
||||
}
|
||||
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
@@ -249,6 +364,24 @@ fn normalize_tool_result(result: Value) -> Value {
|
||||
}
|
||||
}
|
||||
|
||||
fn inject_escalation_notification(last: &mut ToolResult, summary: Vec<Value>) {
|
||||
let instruction = "Child agents are BLOCKED waiting for your reply. \
|
||||
Call agent__reply_escalation for each pending escalation to unblock them.";
|
||||
match &mut last.output {
|
||||
Value::Object(map) => {
|
||||
map.insert("pending_escalations".into(), json!(summary));
|
||||
map.insert("escalation_instruction".into(), json!(instruction));
|
||||
}
|
||||
other => {
|
||||
*other = json!({
|
||||
"output": other.take(),
|
||||
"pending_escalations": summary,
|
||||
"escalation_instruction": instruction,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct ToolResult {
|
||||
pub call: ToolCall,
|
||||
@@ -305,7 +438,6 @@ impl Functions {
|
||||
})?;
|
||||
let content = unsafe { std::str::from_utf8_unchecked(&embedded_file.data) };
|
||||
let file_path = paths::functions_dir().join(file.as_ref());
|
||||
#[cfg_attr(not(unix), expect(unused))]
|
||||
let is_script = file_path
|
||||
.extension()
|
||||
.and_then(OsStr::to_str)
|
||||
@@ -322,14 +454,7 @@ impl Functions {
|
||||
|
||||
ensure_parent_exists(&file_path)?;
|
||||
info!("Creating function file: {}", file_path.display());
|
||||
let mut function_file = File::create(&file_path)?;
|
||||
function_file.write_all(content.as_bytes())?;
|
||||
|
||||
#[cfg(unix)]
|
||||
if is_script {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::set_permissions(&file_path, fs::Permissions::from_mode(0o755))?;
|
||||
}
|
||||
write_file_atomic(&file_path, content, is_script.then_some(0o755))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -368,9 +493,8 @@ impl Functions {
|
||||
|
||||
let serialized =
|
||||
serde_json::to_string_pretty(&merged).context("failed to serialize merged mcp.json")?;
|
||||
let tmp = file_path.with_extension("json.tmp");
|
||||
fs::write(&tmp, &serialized).context("failed to write temporary mcp.json")?;
|
||||
fs::rename(&tmp, &file_path).context("failed to finalize mcp.json")?;
|
||||
write_file_atomic(&file_path, &serialized, None)
|
||||
.context("failed to write merged mcp.json")?;
|
||||
|
||||
if !added.is_empty() {
|
||||
println!(" + new MCP servers: {}", added.join(", "));
|
||||
@@ -380,7 +504,7 @@ impl Functions {
|
||||
}
|
||||
|
||||
pub fn init(visible_tools: &[String]) -> Result<Self> {
|
||||
Self::clear_global_functions_bin_dir()?;
|
||||
Self::remove_stale_global_function_binaries()?;
|
||||
|
||||
let declarations = Self {
|
||||
declarations: Self::build_global_tool_declarations(visible_tools)?,
|
||||
@@ -396,7 +520,7 @@ impl Functions {
|
||||
}
|
||||
|
||||
pub fn init_agent(name: &str, global_tools: &[String]) -> Result<Self> {
|
||||
Self::clear_agent_bin_dir(name)?;
|
||||
Self::remove_stale_agent_bin_entries(name)?;
|
||||
|
||||
let global_tools_declarations = if !global_tools.is_empty() {
|
||||
info!("Loading global tools for agent: {name}: {global_tools:?}");
|
||||
@@ -495,6 +619,16 @@ impl Functions {
|
||||
.extend(user_interaction::user_interaction_function_declarations());
|
||||
}
|
||||
|
||||
pub fn append_rag_query_functions(&mut self) {
|
||||
self.declarations
|
||||
.extend(rag_query::rag_query_function_declarations());
|
||||
}
|
||||
|
||||
pub fn remove_rag_query_functions(&mut self) {
|
||||
self.declarations
|
||||
.retain(|f| !f.name.starts_with(RAG_FUNCTION_PREFIX));
|
||||
}
|
||||
|
||||
pub fn append_mcp_meta_functions(&mut self, mcp_servers: Vec<String>) {
|
||||
let mut invoke_function_properties = IndexMap::new();
|
||||
invoke_function_properties.insert(
|
||||
@@ -700,38 +834,23 @@ impl Functions {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn clear_agent_bin_dir(name: &str) -> Result<()> {
|
||||
fn remove_stale_agent_bin_entries(name: &str) -> Result<()> {
|
||||
let agent_bin_directory = paths::agent_bin_dir(name);
|
||||
if !agent_bin_directory.exists() {
|
||||
|
||||
debug!(
|
||||
"Creating agent bin directory: {}",
|
||||
"Pruning stale entries in agent bin directory: {}",
|
||||
agent_bin_directory.display()
|
||||
);
|
||||
fs::create_dir_all(&agent_bin_directory)?;
|
||||
} else {
|
||||
debug!(
|
||||
"Clearing existing agent bin directory: {}",
|
||||
agent_bin_directory.display()
|
||||
);
|
||||
clear_dir(&agent_bin_directory)?;
|
||||
|
||||
prune_stale_bin_entries(&agent_bin_directory, &tool_source_stems()?, Some(name))
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn clear_global_functions_bin_dir() -> Result<()> {
|
||||
fn remove_stale_global_function_binaries() -> Result<()> {
|
||||
let bin_dir = paths::functions_bin_dir();
|
||||
if !bin_dir.exists() {
|
||||
fs::create_dir_all(&bin_dir)?;
|
||||
}
|
||||
|
||||
info!(
|
||||
"Clearing existing function binaries in {}",
|
||||
bin_dir.display()
|
||||
);
|
||||
clear_dir(&bin_dir)?;
|
||||
info!("Pruning stale function binaries in {}", bin_dir.display());
|
||||
|
||||
Ok(())
|
||||
prune_stale_bin_entries(&bin_dir, &tool_source_stems()?, None)
|
||||
}
|
||||
|
||||
fn build_agent_tool_binaries(name: &str) -> Result<()> {
|
||||
@@ -832,11 +951,7 @@ impl Functions {
|
||||
"{prompt_utils_file}",
|
||||
&to_script_path(&paths::bash_prompt_utils_file().to_string_lossy()),
|
||||
);
|
||||
if binary_script_file.exists() {
|
||||
fs::remove_file(&binary_script_file)?;
|
||||
}
|
||||
let mut script_file = File::create(&binary_script_file)?;
|
||||
script_file.write_all(content.as_bytes())?;
|
||||
write_file_atomic(&binary_script_file, &content, None)?;
|
||||
|
||||
info!(
|
||||
"Building binary for function: {} ({})",
|
||||
@@ -898,8 +1013,7 @@ impl Functions {
|
||||
{run} "{wrapper_binary}" %*"#,
|
||||
);
|
||||
|
||||
let mut file = File::create(&binary_file)?;
|
||||
file.write_all(content.as_bytes())?;
|
||||
write_file_atomic(&binary_file, &content, None)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -911,8 +1025,6 @@ impl Functions {
|
||||
binary_type: BinaryType,
|
||||
custom_runtime: Option<&str>,
|
||||
) -> Result<()> {
|
||||
use std::os::unix::prelude::PermissionsExt;
|
||||
|
||||
let binary_file = match binary_type {
|
||||
BinaryType::Tool(None) => paths::functions_bin_dir().join(binary_name),
|
||||
BinaryType::Tool(Some(agent_name)) => {
|
||||
@@ -981,31 +1093,16 @@ impl Functions {
|
||||
.parent()
|
||||
.expect("Failed to get parent directory of binary file");
|
||||
let script_file = bin_dir.join(format!("run-{binary_name}.ts"));
|
||||
if script_file.exists() {
|
||||
fs::remove_file(&script_file)?;
|
||||
}
|
||||
let mut sf = File::create(&script_file)?;
|
||||
sf.write_all(content.as_bytes())?;
|
||||
fs::set_permissions(&script_file, fs::Permissions::from_mode(0o755))?;
|
||||
write_file_atomic(&script_file, &content, Some(0o755))?;
|
||||
|
||||
let ts_runtime = custom_runtime.unwrap_or("tsx");
|
||||
let wrapper = format!(
|
||||
"#!/bin/sh\nexec {ts_runtime} \"{}\" \"$@\"\n",
|
||||
script_file.display()
|
||||
);
|
||||
if binary_file.exists() {
|
||||
fs::remove_file(&binary_file)?;
|
||||
}
|
||||
let mut wf = File::create(&binary_file)?;
|
||||
wf.write_all(wrapper.as_bytes())?;
|
||||
fs::set_permissions(&binary_file, fs::Permissions::from_mode(0o755))?;
|
||||
write_file_atomic(&binary_file, &wrapper, Some(0o755))?;
|
||||
} else {
|
||||
if binary_file.exists() {
|
||||
fs::remove_file(&binary_file)?;
|
||||
}
|
||||
let mut file = File::create(&binary_file)?;
|
||||
file.write_all(content.as_bytes())?;
|
||||
fs::set_permissions(&binary_file, fs::Permissions::from_mode(0o755))?;
|
||||
write_file_atomic(&binary_file, &content, Some(0o755))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -1252,6 +1349,15 @@ impl ToolCall {
|
||||
json!({"tool_call_error": error_msg})
|
||||
})
|
||||
}
|
||||
_ if cmd_name.starts_with(RAG_FUNCTION_PREFIX) => {
|
||||
rag_query::handle_rag_tool(ctx, &cmd_name, &json_data)
|
||||
.await
|
||||
.unwrap_or_else(|e| {
|
||||
let error_msg = format!("RAG query failed: {e}");
|
||||
eprintln!("{}", muted_warning_text(&format!("⚠️ {error_msg} ⚠️")));
|
||||
json!({"tool_call_error": error_msg})
|
||||
})
|
||||
}
|
||||
_ => match run_llm_function(cmd_name, cmd_args, envs, agent_name) {
|
||||
Ok(Some(contents)) => serde_json::from_str(&contents)
|
||||
.ok()
|
||||
@@ -1435,6 +1541,7 @@ pub fn run_llm_function(
|
||||
let mut child = Command::new(&cmd_name)
|
||||
.args(&cmd_args)
|
||||
.envs(envs)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
@@ -1443,7 +1550,7 @@ pub fn run_llm_function(
|
||||
let stdout = child.stdout.take().expect("Failed to capture stdout");
|
||||
let stderr = child.stderr.take().expect("Failed to capture stderr");
|
||||
|
||||
let stdout_thread = std::thread::spawn(move || {
|
||||
let stdout_thread = thread::spawn(move || {
|
||||
let mut buffer = [0; 1024];
|
||||
let mut reader = stdout;
|
||||
let mut out = io::stdout();
|
||||
@@ -1470,7 +1577,7 @@ pub fn run_llm_function(
|
||||
buf
|
||||
});
|
||||
|
||||
let stderr_thread = std::thread::spawn(move || {
|
||||
let stderr_thread = thread::spawn(move || {
|
||||
let mut buffer = [0; 1024];
|
||||
let mut reader = stderr;
|
||||
let mut err = io::stderr();
|
||||
@@ -1497,9 +1604,39 @@ pub fn run_llm_function(
|
||||
buf
|
||||
});
|
||||
|
||||
let status = child
|
||||
.wait()
|
||||
.map_err(|err| anyhow!("Unable to run {command_name}, {err}"))?;
|
||||
let timeout_secs = env::var("COYOTE_TOOL_TIMEOUT")
|
||||
.ok()
|
||||
.and_then(|v| v.parse::<u64>().ok())
|
||||
.unwrap_or(1800);
|
||||
let deadline = (timeout_secs > 0).then(|| Instant::now() + Duration::from_secs(timeout_secs));
|
||||
let status = loop {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => break status,
|
||||
Ok(None) => {}
|
||||
Err(err) => bail!("Unable to run {command_name}, {err}"),
|
||||
}
|
||||
if let Some(deadline) = deadline
|
||||
&& Instant::now() >= deadline
|
||||
{
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
drop(stdout_thread);
|
||||
drop(stderr_thread);
|
||||
let tool_error_message = format!(
|
||||
"Tool call '{command_name}' timed out after {timeout_secs}s and was killed (set COYOTE_TOOL_TIMEOUT to adjust; 0 = unlimited)"
|
||||
);
|
||||
eprintln!(
|
||||
"{}",
|
||||
muted_warning_text(&format!("⚠️ {tool_error_message} ⚠️"))
|
||||
);
|
||||
let error_json = json!({"tool_call_error": tool_error_message});
|
||||
|
||||
debug!("Tool call error: {error_json:?}");
|
||||
|
||||
return Ok(Some(error_json.to_string()));
|
||||
}
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
};
|
||||
let stdout_bytes = stdout_thread.join().unwrap_or_default();
|
||||
let stderr_bytes = stderr_thread.join().unwrap_or_default();
|
||||
|
||||
@@ -1519,6 +1656,11 @@ pub fn run_llm_function(
|
||||
if !stdout.is_empty() {
|
||||
error_json["stdout"] = json!(stdout);
|
||||
}
|
||||
if let Ok(contents) = fs::read_to_string(&tmp_file)
|
||||
&& !contents.trim().is_empty()
|
||||
{
|
||||
error_json["output"] = json!(contents);
|
||||
}
|
||||
debug!("Tool call error: {error_json:?}");
|
||||
return Ok(Some(error_json.to_string()));
|
||||
}
|
||||
@@ -1688,7 +1830,10 @@ fn format_json_colored_keys(value: &serde_json::Value) -> String {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::config::{AppState, WorkingMode};
|
||||
use crate::supervisor::escalation::{EscalationQueue, EscalationRequest};
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn call(name: &str, id: Option<&str>) -> ToolCall {
|
||||
ToolCall::new(name.to_string(), json!({}), id.map(|s| s.to_string()))
|
||||
@@ -1698,11 +1843,98 @@ mod tests {
|
||||
ToolCall::new(name.to_string(), args, Some("id1".to_string()))
|
||||
}
|
||||
|
||||
fn run_async<F: Future>(f: F) -> F::Output {
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap()
|
||||
.block_on(f)
|
||||
}
|
||||
|
||||
fn submit_escalation(queue: &EscalationQueue, id: &str) {
|
||||
let (tx, _rx) = tokio::sync::oneshot::channel();
|
||||
queue.submit(EscalationRequest {
|
||||
id: id.to_string(),
|
||||
from_agent_id: "a1".into(),
|
||||
from_agent_name: "explore".into(),
|
||||
question: "What do?".into(),
|
||||
options: None,
|
||||
reply_tx: tx,
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_tool_result_substitutes_done_for_null() {
|
||||
assert_eq!(normalize_tool_result(Value::Null), json!("DONE"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inject_escalation_notification_extends_object_output() {
|
||||
let mut result = ToolResult::new(call("t", Some("id-1")), json!({"status": "ok"}));
|
||||
inject_escalation_notification(&mut result, vec![json!({"escalation_id": "esc_1"})]);
|
||||
assert_eq!(result.output["status"], "ok");
|
||||
assert_eq!(
|
||||
result.output["pending_escalations"],
|
||||
json!([{"escalation_id": "esc_1"}])
|
||||
);
|
||||
assert!(
|
||||
result.output["escalation_instruction"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("agent__reply_escalation")
|
||||
);
|
||||
assert!(result.text.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inject_escalation_notification_wraps_non_object_output() {
|
||||
let mut result = ToolResult::new(call("t", Some("id-1")), json!("DONE"));
|
||||
inject_escalation_notification(&mut result, vec![json!({"escalation_id": "esc_2"})]);
|
||||
assert_eq!(result.output["output"], json!("DONE"));
|
||||
assert_eq!(
|
||||
result.output["pending_escalations"],
|
||||
json!([{"escalation_id": "esc_2"}])
|
||||
);
|
||||
assert!(result.output["escalation_instruction"].is_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_tool_calls_soft_fails_unknown_tool() {
|
||||
let mut ctx = RequestContext::new(Arc::new(AppState::test_default()), WorkingMode::Cmd);
|
||||
let calls = vec![call("__escalation_notification", Some("id-1"))];
|
||||
let results = run_async(eval_tool_calls(&mut ctx, calls)).unwrap();
|
||||
assert_eq!(results.len(), 1);
|
||||
let err = results[0].output["tool_call_error"].as_str().unwrap();
|
||||
assert!(err.contains("Unexpected call"));
|
||||
assert!(err.contains("use only tools listed in your catalog"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_tool_calls_injects_escalations_into_last_result() {
|
||||
let mut ctx = RequestContext::new(Arc::new(AppState::test_default()), WorkingMode::Cmd);
|
||||
let queue = ctx.ensure_root_escalation_queue();
|
||||
submit_escalation(&queue, "esc_1");
|
||||
|
||||
let calls = vec![call("unknown_tool", Some("id-1"))];
|
||||
let results = run_async(eval_tool_calls(&mut ctx, calls)).unwrap();
|
||||
|
||||
assert_eq!(results.len(), 1);
|
||||
assert!(
|
||||
results
|
||||
.iter()
|
||||
.all(|r| r.call.name != "__escalation_notification")
|
||||
);
|
||||
let out = &results[0].output;
|
||||
assert!(out["tool_call_error"].is_string());
|
||||
assert_eq!(out["pending_escalations"][0]["escalation_id"], "esc_1");
|
||||
assert!(
|
||||
out["escalation_instruction"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("agent__reply_escalation")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_tool_result_preserves_non_null_values() {
|
||||
assert_eq!(
|
||||
@@ -2130,4 +2362,149 @@ mod tests {
|
||||
let tc = call_with_args("t", json!(42));
|
||||
assert!(tc.parse_arguments().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_file_atomic_writes_and_skips_unchanged() {
|
||||
let dir = temp_file("-atomic-", "");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("shim");
|
||||
|
||||
write_file_atomic(&path, "one", Some(0o755)).unwrap();
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "one");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
assert_eq!(
|
||||
fs::metadata(&path).unwrap().permissions().mode() & 0o777,
|
||||
0o755
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
let ino = fs::metadata(&path).unwrap().ino();
|
||||
write_file_atomic(&path, "one", Some(0o755)).unwrap();
|
||||
assert_eq!(
|
||||
fs::metadata(&path).unwrap().ino(),
|
||||
ino,
|
||||
"unchanged content must not be rewritten"
|
||||
);
|
||||
}
|
||||
|
||||
write_file_atomic(&path, "two", None).unwrap();
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "two");
|
||||
assert_eq!(
|
||||
fs::read_dir(&dir).unwrap().count(),
|
||||
1,
|
||||
"no tmp files left behind"
|
||||
);
|
||||
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_file_atomic_concurrent_writers_to_same_target() {
|
||||
let dir = temp_file("-atomic-concurrent-", "");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("shim");
|
||||
|
||||
let contents: Vec<String> = (0..8)
|
||||
.map(|i| format!("#!/bin/sh\necho writer-{i}\n"))
|
||||
.collect();
|
||||
thread::scope(|scope| {
|
||||
for content in &contents {
|
||||
scope.spawn(|| {
|
||||
for _ in 0..50 {
|
||||
write_file_atomic(&path, content, Some(0o755)).unwrap();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
let final_content = fs::read_to_string(&path).unwrap();
|
||||
assert!(
|
||||
contents.contains(&final_content),
|
||||
"final content must be one writer's complete content, got: {final_content:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_dir(&dir).unwrap().count(),
|
||||
1,
|
||||
"no tmp files left behind"
|
||||
);
|
||||
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn run_llm_function_includes_llm_output_on_nonzero_exit() {
|
||||
let result = run_llm_function(
|
||||
"bash".into(),
|
||||
vec![
|
||||
"-c".into(),
|
||||
"echo partial-output >> \"$LLM_OUTPUT\"; echo err-text >&2; exit 3".into(),
|
||||
],
|
||||
HashMap::new(),
|
||||
None,
|
||||
)
|
||||
.unwrap()
|
||||
.expect("nonzero exit must return an error payload");
|
||||
|
||||
let json: serde_json::Value = serde_json::from_str(&result).unwrap();
|
||||
assert!(
|
||||
json["tool_call_error"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("exited with code 3")
|
||||
);
|
||||
assert_eq!(json["stderr"], "err-text");
|
||||
assert_eq!(json["output"], "partial-output\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bin_entry_stem_strips_run_prefix_and_extension() {
|
||||
assert_eq!(bin_entry_stem("fs_grep"), "fs_grep");
|
||||
assert_eq!(bin_entry_stem("fs_grep.cmd"), "fs_grep");
|
||||
assert_eq!(bin_entry_stem("run-web_search.ts"), "web_search");
|
||||
assert_eq!(bin_entry_stem("run-fs_grep.sh"), "fs_grep");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prune_stale_bin_entries_removes_only_stale_files() {
|
||||
let dir = temp_file("-prune-", "");
|
||||
fs::create_dir_all(dir.join("nested")).unwrap();
|
||||
for name in [
|
||||
"fs_grep",
|
||||
"run-web_search.ts",
|
||||
"old_tool",
|
||||
"run-old_tool.ts",
|
||||
"myagent",
|
||||
] {
|
||||
fs::write(dir.join(name), "x").unwrap();
|
||||
}
|
||||
let valid_stems: HashSet<String> = ["fs_grep", "web_search"]
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
|
||||
prune_stale_bin_entries(&dir, &valid_stems, Some("myagent")).unwrap();
|
||||
|
||||
assert!(dir.join("fs_grep").exists());
|
||||
assert!(dir.join("run-web_search.ts").exists());
|
||||
assert!(dir.join("myagent").exists(), "agent binary must survive");
|
||||
assert!(!dir.join("old_tool").exists());
|
||||
assert!(!dir.join("run-old_tool.ts").exists());
|
||||
assert!(!dir.join("nested").exists(), "directories must be removed");
|
||||
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prune_stale_bin_entries_creates_missing_dir() {
|
||||
let dir = temp_file("-prune-missing-", "");
|
||||
prune_stale_bin_entries(&dir, &HashSet::new(), None).unwrap();
|
||||
assert!(dir.is_dir());
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
use super::{FunctionDeclaration, JsonSchema};
|
||||
use crate::config::RequestContext;
|
||||
|
||||
use anyhow::{Result, anyhow};
|
||||
use indexmap::IndexMap;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub const RAG_FUNCTION_PREFIX: &str = "rag__";
|
||||
|
||||
pub fn rag_query_function_declarations() -> Vec<FunctionDeclaration> {
|
||||
vec![FunctionDeclaration {
|
||||
name: format!("{RAG_FUNCTION_PREFIX}query"),
|
||||
description: "Search the RAG knowledge base attached to this session and return \
|
||||
the most relevant text chunks with their source paths. The relevant \
|
||||
context has already been injected into the prompt up-front; use this \
|
||||
tool to pull additional context on-demand when the initial retrieval \
|
||||
does not fully answer the question. Prefer specific, keyword-rich queries."
|
||||
.to_string(),
|
||||
parameters: JsonSchema {
|
||||
type_value: Some("object".to_string()),
|
||||
properties: Some(IndexMap::from([
|
||||
(
|
||||
"query".to_string(),
|
||||
JsonSchema {
|
||||
type_value: Some("string".to_string()),
|
||||
description: Some(
|
||||
"Natural language search query used to retrieve relevant chunks."
|
||||
.into(),
|
||||
),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
(
|
||||
"top_k".to_string(),
|
||||
JsonSchema {
|
||||
type_value: Some("integer".to_string()),
|
||||
description: Some(
|
||||
"Maximum number of chunks to return. Defaults to the RAG's \
|
||||
configured top_k when omitted."
|
||||
.into(),
|
||||
),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
])),
|
||||
required: Some(vec!["query".to_string()]),
|
||||
..Default::default()
|
||||
},
|
||||
agent: false,
|
||||
}]
|
||||
}
|
||||
|
||||
pub async fn handle_rag_tool(
|
||||
ctx: &mut RequestContext,
|
||||
cmd_name: &str,
|
||||
args: &Value,
|
||||
) -> Result<Value> {
|
||||
let action = cmd_name
|
||||
.strip_prefix(RAG_FUNCTION_PREFIX)
|
||||
.unwrap_or(cmd_name);
|
||||
|
||||
match action {
|
||||
"query" => handle_query(ctx, args).await,
|
||||
_ => Err(anyhow!("Unknown RAG action: {action}")),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_query(ctx: &RequestContext, args: &Value) -> Result<Value> {
|
||||
let rag = ctx
|
||||
.rag
|
||||
.clone()
|
||||
.ok_or_else(|| anyhow!("No RAG is attached to this session"))?;
|
||||
|
||||
let query = args
|
||||
.get("query")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| anyhow!("'query' is required"))?;
|
||||
|
||||
let top_k = args
|
||||
.get("top_k")
|
||||
.and_then(Value::as_u64)
|
||||
.map(|v| v as usize)
|
||||
.unwrap_or_else(|| rag.configured_top_k());
|
||||
|
||||
let rerank_model = rag.configured_reranker().map(|s| s.to_string());
|
||||
|
||||
let chunks = rag
|
||||
.search_chunks(query, top_k, rerank_model.as_deref())
|
||||
.await?;
|
||||
|
||||
let chunks_json: Vec<Value> = chunks
|
||||
.into_iter()
|
||||
.map(|(text, source)| json!({ "text": text, "source": source }))
|
||||
.collect();
|
||||
|
||||
Ok(json!({
|
||||
"rag_name": rag.name(),
|
||||
"count": chunks_json.len(),
|
||||
"chunks": chunks_json,
|
||||
}))
|
||||
}
|
||||
+109
-1
@@ -85,7 +85,17 @@ pub fn check_pending_agents_guardrail(ctx: &mut RequestContext) -> GuardrailActi
|
||||
}
|
||||
|
||||
ctx.pending_agents_guardrail_count += 1;
|
||||
GuardrailAction::Inject(build_pending_agents_guardrail_prompt(&pending))
|
||||
let mut prompt = build_pending_agents_guardrail_prompt(&pending);
|
||||
if let Some(queue) = ctx.root_escalation_queue()
|
||||
&& queue.has_pending()
|
||||
{
|
||||
let summary = serde_json::to_string(&queue.pending_summary()).unwrap_or_default();
|
||||
prompt.push_str(&format!(
|
||||
"\n\nAdditionally, child agents have pending escalations blocking them. Reply to each \
|
||||
via `agent__reply_escalation` first:\n{summary}"
|
||||
));
|
||||
}
|
||||
GuardrailAction::Inject(prompt)
|
||||
}
|
||||
|
||||
pub fn escalation_function_declarations() -> Vec<FunctionDeclaration> {
|
||||
@@ -1996,4 +2006,102 @@ mod tests {
|
||||
let q2 = ctx.ensure_root_escalation_queue();
|
||||
assert!(Arc::ptr_eq(&q1, &q2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guardrail_prompt_mentions_pending_escalations() {
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
rt.block_on(async {
|
||||
let mut ctx = ctx_with_supervisor(4, 3);
|
||||
let join_handle = tokio::spawn(async {
|
||||
time::sleep(Duration::from_secs(60)).await;
|
||||
Ok(AgentResult {
|
||||
id: "slow".into(),
|
||||
agent_name: "test".into(),
|
||||
output: String::new(),
|
||||
exit_status: AgentExitStatus::Completed,
|
||||
})
|
||||
});
|
||||
let handle = AgentHandle {
|
||||
id: "slow".into(),
|
||||
agent_name: "test".into(),
|
||||
depth: 1,
|
||||
inbox: Arc::new(Inbox::new()),
|
||||
abort_signal: create_abort_signal(),
|
||||
join_handle,
|
||||
child_supervisor: None,
|
||||
};
|
||||
ctx.supervisor
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.write()
|
||||
.register(handle)
|
||||
.unwrap();
|
||||
|
||||
let queue = ctx.ensure_root_escalation_queue();
|
||||
let (tx, _rx) = tokio::sync::oneshot::channel();
|
||||
queue.submit(EscalationRequest {
|
||||
id: "esc_9".into(),
|
||||
from_agent_id: "a1".into(),
|
||||
from_agent_name: "explore".into(),
|
||||
question: "Which option?".into(),
|
||||
options: None,
|
||||
reply_tx: tx,
|
||||
});
|
||||
|
||||
match check_pending_agents_guardrail(&mut ctx) {
|
||||
GuardrailAction::Inject(prompt) => {
|
||||
assert!(prompt.contains("agent__reply_escalation"));
|
||||
assert!(prompt.contains("esc_9"));
|
||||
}
|
||||
_ => panic!("expected Inject action"),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guardrail_prompt_omits_escalations_when_none_pending() {
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
rt.block_on(async {
|
||||
let mut ctx = ctx_with_supervisor(4, 3);
|
||||
let join_handle = tokio::spawn(async {
|
||||
time::sleep(Duration::from_secs(60)).await;
|
||||
Ok(AgentResult {
|
||||
id: "slow".into(),
|
||||
agent_name: "test".into(),
|
||||
output: String::new(),
|
||||
exit_status: AgentExitStatus::Completed,
|
||||
})
|
||||
});
|
||||
let handle = AgentHandle {
|
||||
id: "slow".into(),
|
||||
agent_name: "test".into(),
|
||||
depth: 1,
|
||||
inbox: Arc::new(Inbox::new()),
|
||||
abort_signal: create_abort_signal(),
|
||||
join_handle,
|
||||
child_supervisor: None,
|
||||
};
|
||||
ctx.supervisor
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.write()
|
||||
.register(handle)
|
||||
.unwrap();
|
||||
|
||||
match check_pending_agents_guardrail(&mut ctx) {
|
||||
GuardrailAction::Inject(prompt) => {
|
||||
assert!(!prompt.contains("agent__reply_escalation"));
|
||||
}
|
||||
_ => panic!("expected Inject action"),
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+64
-1
@@ -250,7 +250,30 @@ impl GraphExecutor {
|
||||
branch_tasks.push(task);
|
||||
}
|
||||
|
||||
let joined = join_all(branch_tasks).await;
|
||||
let joined = match graph_timeout {
|
||||
Some(t) => {
|
||||
let remaining = t.saturating_sub(start.elapsed());
|
||||
let abort_handles: Vec<_> = branch_tasks
|
||||
.iter()
|
||||
.map(|task| task.abort_handle())
|
||||
.collect();
|
||||
match tokio::time::timeout(remaining, join_all(branch_tasks)).await {
|
||||
Ok(joined) => joined,
|
||||
Err(_) => {
|
||||
for handle in abort_handles {
|
||||
handle.abort();
|
||||
}
|
||||
bail!(
|
||||
"Graph '{}' timed out after {}s during super-step with frontier {:?}",
|
||||
graph.name,
|
||||
t.as_secs(),
|
||||
sorted_frontier(&frontier)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
None => join_all(branch_tasks).await,
|
||||
};
|
||||
|
||||
let mut branch_writes: Vec<BranchWrites> = Vec::new();
|
||||
let mut next_frontier: HashSet<String> = HashSet::new();
|
||||
@@ -793,4 +816,44 @@ nodes:
|
||||
"error should list both End nodes: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn graph_timeout_interrupts_in_flight_super_step() {
|
||||
if !cmd_available("bash") {
|
||||
eprintln!("skipping: bash not available");
|
||||
return;
|
||||
}
|
||||
let ws = TestWorkspace::new();
|
||||
ws.write_script("sleeper.sh", "#!/bin/bash\nsleep 10\necho '{}'\n");
|
||||
|
||||
let yaml = r#"
|
||||
name: inflight_timeout_test
|
||||
start: sleeper
|
||||
settings:
|
||||
timeout: 1
|
||||
nodes:
|
||||
sleeper:
|
||||
type: script
|
||||
script: sleeper.sh
|
||||
state_updates: {}
|
||||
next: done
|
||||
done:
|
||||
type: end
|
||||
output: "done"
|
||||
"#;
|
||||
let graph: Graph = serde_yaml::from_str(yaml).unwrap();
|
||||
let mut ctx = make_ctx();
|
||||
let abort = create_abort_signal();
|
||||
let result = GraphExecutor::new(graph, &ws.dir)
|
||||
.execute(&mut ctx, abort)
|
||||
.await;
|
||||
|
||||
assert!(result.is_err(), "expected in-flight timeout to error");
|
||||
let err = format!("{:#}", result.unwrap_err());
|
||||
assert!(
|
||||
err.contains("timed out after 1s during super-step"),
|
||||
"error should report during-super-step timeout: {err}"
|
||||
);
|
||||
assert!(err.contains("sleeper"), "error should name frontier: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,6 +54,7 @@ impl ScriptExecutor {
|
||||
let mut cmd = build_command(language, &script_path)?;
|
||||
cmd.stdout(Stdio::piped());
|
||||
cmd.stderr(Stdio::piped());
|
||||
cmd.kill_on_drop(true);
|
||||
cmd.envs(&self.extra_envs);
|
||||
cmd.env("AUTO_CONFIRM", "true");
|
||||
match &state_repr {
|
||||
|
||||
@@ -588,6 +588,16 @@ nodes:
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graph_silently_ignores_enabled_macros_key() {
|
||||
let yaml = "name: g\nenabled_macros: [\"x\"]\nstart: x\nnodes:\n x:\n id: x\n type: end\n output: ok\n";
|
||||
|
||||
let graph: Graph = serde_yaml::from_str(yaml).unwrap();
|
||||
|
||||
assert_eq!(graph.name, "g");
|
||||
assert_eq!(graph.start, "x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graph_settings_have_sensible_defaults() {
|
||||
let yaml = "name: g\nstart: x\nnodes:\n x:\n id: x\n type: end\n output: ok\n";
|
||||
|
||||
@@ -23,7 +23,7 @@ impl ApprovalNodeExecutor {
|
||||
|
||||
let response = handle_user_tool(
|
||||
ctx,
|
||||
&format!("{USER_FUNCTION_PREFIX}ask"),
|
||||
&format!("{USER_FUNCTION_PREFIX}select"),
|
||||
&json!({ "question": question, "options": node.options }),
|
||||
)
|
||||
.await
|
||||
|
||||
+35
-3
@@ -127,14 +127,31 @@ async fn main() -> Result<()> {
|
||||
return sandbox::launch(name.clone(), cli.fresh);
|
||||
}
|
||||
|
||||
if cli.list_bundles {
|
||||
return config::list_installed_bundles();
|
||||
}
|
||||
|
||||
install_builtins()?;
|
||||
|
||||
if let Some(category) = cli.install {
|
||||
if let Some(category) = cli.install_builtins {
|
||||
return config::install_assets(category);
|
||||
}
|
||||
|
||||
if let Some(url) = cli.install_from.as_deref() {
|
||||
return config::install_remote(url, cli.filter, cli.install_force);
|
||||
if let Some(value) = cli.install.as_deref() {
|
||||
return config::install_or_update(
|
||||
value,
|
||||
cli.git_host.as_deref(),
|
||||
cli.filter,
|
||||
cli.install_force,
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(spec) = cli.update_bundle.as_deref() {
|
||||
return config::update_bundle(spec, cli.yes);
|
||||
}
|
||||
|
||||
if let Some(name) = cli.uninstall.as_deref() {
|
||||
return config::uninstall_bundle(name, cli.yes);
|
||||
}
|
||||
|
||||
if let Some(client_arg) = &cli.authenticate {
|
||||
@@ -196,6 +213,18 @@ async fn main() -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mcp_action =
|
||||
cli.mcp_list || cli.mcp_get.is_some() || cli.mcp_remove.is_some() || cli.mcp_add.is_some();
|
||||
if mcp_action {
|
||||
let cfg = Config::load_with_interpolation(true).await?;
|
||||
let app_config = AppConfig::from_config(cfg)?;
|
||||
let vault = Vault::init(&app_config)?;
|
||||
|
||||
mcp::manage::handle(&cli, &vault)?;
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if vault_flags {
|
||||
let cfg = Config::load_with_interpolation(true).await?;
|
||||
let app_config = AppConfig::from_config(cfg)?;
|
||||
@@ -210,6 +239,9 @@ async fn main() -> Result<()> {
|
||||
if cli.no_workspace_mcp {
|
||||
app_config.no_workspace_mcp = true;
|
||||
}
|
||||
if cli.no_workspace_macros {
|
||||
app_config.no_workspace_macros = true;
|
||||
}
|
||||
let app_config: Arc<AppConfig> = Arc::new(app_config);
|
||||
let app_state: Arc<AppState> = Arc::new(
|
||||
AppState::init(
|
||||
|
||||
@@ -0,0 +1,651 @@
|
||||
use crate::mcp::oauth::{force_refresh_mcp_token, load_or_refresh_mcp_token};
|
||||
use http::{HeaderName, HeaderValue};
|
||||
use log::debug;
|
||||
use rmcp::model::ClientJsonRpcMessage;
|
||||
use rmcp::transport::common::client_side_sse::BoxedSseResponse;
|
||||
use rmcp::transport::streamable_http_client::{
|
||||
AuthRequiredError, StreamableHttpClient, StreamableHttpError, StreamableHttpPostResponse,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// [`StreamableHttpClient`] wrapper that injects the OAuth bearer token for an
|
||||
/// MCP server on every request instead of pinning it at spawn time, so tokens
|
||||
/// refreshed mid-session take effect without reconnecting.
|
||||
///
|
||||
/// A caller-supplied `auth_header` always passes through untouched; only a
|
||||
/// `None` header is filled from the stored token. When the wrapper injected
|
||||
/// the token and a POST comes back 401, it forces a token refresh and retries
|
||||
/// exactly once (see [`Self::post_with_retry`]).
|
||||
#[derive(Clone)]
|
||||
pub struct McpOAuthClient<C = reqwest::Client> {
|
||||
inner: C,
|
||||
server: Arc<str>,
|
||||
}
|
||||
|
||||
impl<C> McpOAuthClient<C> {
|
||||
pub fn new(inner: C, server: &str) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
server: Arc::from(server),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: StreamableHttpClient + Sync> McpOAuthClient<C> {
|
||||
/// Resolves the effective auth header. Caller-supplied values pass through
|
||||
/// untouched; `None` is filled from the stored token for this server.
|
||||
/// Returns the header plus whether the wrapper injected it. Errors with
|
||||
/// [`StreamableHttpError::AuthRequired`] (without contacting the server)
|
||||
/// when no usable token exists.
|
||||
async fn resolve_auth(
|
||||
&self,
|
||||
auth_header: Option<String>,
|
||||
) -> Result<(Option<String>, bool), StreamableHttpError<C::Error>> {
|
||||
if auth_header.is_some() {
|
||||
return Ok((auth_header, false));
|
||||
}
|
||||
match load_or_refresh_mcp_token(&self.server).await.into_token() {
|
||||
Some(token) => Ok((Some(token), true)),
|
||||
None => Err(self.auth_required()),
|
||||
}
|
||||
}
|
||||
|
||||
fn auth_required(&self) -> StreamableHttpError<C::Error> {
|
||||
StreamableHttpError::AuthRequired(AuthRequiredError::new(format!(
|
||||
"no valid OAuth token for MCP server '{server}'; \
|
||||
run `.mcp auth {server}` to re-authenticate",
|
||||
server = self.server
|
||||
)))
|
||||
}
|
||||
|
||||
async fn post_with_retry<F, Fut>(
|
||||
&self,
|
||||
auth_header: Option<String>,
|
||||
mut post: F,
|
||||
) -> Result<StreamableHttpPostResponse, StreamableHttpError<C::Error>>
|
||||
where
|
||||
F: FnMut(Option<String>) -> Fut,
|
||||
Fut: Future<Output = Result<StreamableHttpPostResponse, StreamableHttpError<C::Error>>>,
|
||||
{
|
||||
let (auth, injected) = self.resolve_auth(auth_header).await?;
|
||||
let (original, rejected) = match (post(auth.clone()).await, auth) {
|
||||
(Err(err @ StreamableHttpError::AuthRequired(_)), Some(rejected)) if injected => {
|
||||
(err, rejected)
|
||||
}
|
||||
(result, _) => return result,
|
||||
};
|
||||
|
||||
debug!(
|
||||
"MCP server '{}' rejected the injected token; forcing a refresh and retrying once",
|
||||
self.server
|
||||
);
|
||||
|
||||
let Some(token) = force_refresh_mcp_token(&self.server, &rejected).await else {
|
||||
return Err(original);
|
||||
};
|
||||
|
||||
match post(Some(token)).await {
|
||||
Err(StreamableHttpError::AuthRequired(_)) => {
|
||||
debug!(
|
||||
"Retry after forced token refresh was rejected again by MCP server '{}'",
|
||||
self.server
|
||||
);
|
||||
Err(original)
|
||||
}
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: StreamableHttpClient + Sync> StreamableHttpClient for McpOAuthClient<C> {
|
||||
type Error = C::Error;
|
||||
|
||||
async fn post_message(
|
||||
&self,
|
||||
uri: Arc<str>,
|
||||
message: ClientJsonRpcMessage,
|
||||
session_id: Option<Arc<str>>,
|
||||
auth_header: Option<String>,
|
||||
custom_headers: HashMap<HeaderName, HeaderValue>,
|
||||
) -> Result<StreamableHttpPostResponse, StreamableHttpError<Self::Error>> {
|
||||
self.post_with_retry(auth_header, |auth| {
|
||||
self.inner.post_message(
|
||||
uri.clone(),
|
||||
message.clone(),
|
||||
session_id.clone(),
|
||||
auth,
|
||||
custom_headers.clone(),
|
||||
)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Overridden rather than left to the trait default: the default impl
|
||||
/// delegates to [`Self::post_message`], silently dropping the
|
||||
/// transport-wide SSE event size limit. Delegating to the inner client's
|
||||
/// size-enforcing variant keeps the limit applied at the raw byte layer.
|
||||
async fn post_message_with_max_sse_event_size(
|
||||
&self,
|
||||
uri: Arc<str>,
|
||||
message: ClientJsonRpcMessage,
|
||||
session_id: Option<Arc<str>>,
|
||||
auth_header: Option<String>,
|
||||
custom_headers: HashMap<HeaderName, HeaderValue>,
|
||||
max_sse_event_size: usize,
|
||||
) -> Result<StreamableHttpPostResponse, StreamableHttpError<Self::Error>> {
|
||||
self.post_with_retry(auth_header, |auth| {
|
||||
self.inner.post_message_with_max_sse_event_size(
|
||||
uri.clone(),
|
||||
message.clone(),
|
||||
session_id.clone(),
|
||||
auth,
|
||||
custom_headers.clone(),
|
||||
max_sse_event_size,
|
||||
)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn delete_session(
|
||||
&self,
|
||||
uri: Arc<str>,
|
||||
session_id: Arc<str>,
|
||||
auth_header: Option<String>,
|
||||
custom_headers: HashMap<HeaderName, HeaderValue>,
|
||||
) -> Result<(), StreamableHttpError<Self::Error>> {
|
||||
let (auth, _) = self.resolve_auth(auth_header).await?;
|
||||
self.inner
|
||||
.delete_session(uri, session_id, auth, custom_headers)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn get_stream(
|
||||
&self,
|
||||
uri: Arc<str>,
|
||||
session_id: Option<Arc<str>>,
|
||||
last_event_id: Option<String>,
|
||||
auth_header: Option<String>,
|
||||
custom_headers: HashMap<HeaderName, HeaderValue>,
|
||||
) -> Result<BoxedSseResponse, StreamableHttpError<Self::Error>> {
|
||||
let (auth, _) = self.resolve_auth(auth_header).await?;
|
||||
self.inner
|
||||
.get_stream(uri, session_id, last_event_id, auth, custom_headers)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Overridden for the same reason as
|
||||
/// [`Self::post_message_with_max_sse_event_size`]: the trait default
|
||||
/// bypasses SSE event size enforcement.
|
||||
async fn get_stream_with_max_sse_event_size(
|
||||
&self,
|
||||
uri: Arc<str>,
|
||||
session_id: Option<Arc<str>>,
|
||||
last_event_id: Option<String>,
|
||||
auth_header: Option<String>,
|
||||
custom_headers: HashMap<HeaderName, HeaderValue>,
|
||||
max_sse_event_size: usize,
|
||||
) -> Result<BoxedSseResponse, StreamableHttpError<Self::Error>> {
|
||||
let (auth, _) = self.resolve_auth(auth_header).await?;
|
||||
self.inner
|
||||
.get_stream_with_max_sse_event_size(
|
||||
uri,
|
||||
session_id,
|
||||
last_event_id,
|
||||
auth,
|
||||
custom_headers,
|
||||
max_sse_event_size,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::config::paths;
|
||||
use crate::mcp::oauth::test_support::with_temp_cache;
|
||||
use futures_util::StreamExt;
|
||||
use parking_lot::Mutex;
|
||||
use serial_test::serial;
|
||||
use std::convert::Infallible;
|
||||
use std::fs;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
const FRESH: i64 = 9999999999;
|
||||
|
||||
type Calls = Arc<Mutex<Vec<(&'static str, Option<String>)>>>;
|
||||
|
||||
type AfterFirstCallAction = Option<Box<dyn FnOnce() + Send + 'static>>;
|
||||
|
||||
/// Inner client that records `(method, auth_header)` per call, rejects the
|
||||
/// first `reject_times` POSTs/streams with `AuthRequired` (then the next
|
||||
/// `transport_error_times` with a non-auth error), and runs an optional
|
||||
/// side effect after the first call (to mutate token files between the
|
||||
/// initial attempt and the retry).
|
||||
#[derive(Clone, Default)]
|
||||
struct FakeInner {
|
||||
calls: Calls,
|
||||
reject_times: Arc<AtomicUsize>,
|
||||
transport_error_times: Arc<AtomicUsize>,
|
||||
after_first_call: Arc<Mutex<AfterFirstCallAction>>,
|
||||
}
|
||||
|
||||
impl FakeInner {
|
||||
fn record(
|
||||
&self,
|
||||
method: &'static str,
|
||||
auth: Option<String>,
|
||||
) -> Result<(), StreamableHttpError<Infallible>> {
|
||||
self.calls.lock().push((method, auth));
|
||||
if let Some(f) = self.after_first_call.lock().take() {
|
||||
f();
|
||||
}
|
||||
if self.reject_times.load(Ordering::SeqCst) > 0 {
|
||||
self.reject_times.fetch_sub(1, Ordering::SeqCst);
|
||||
return Err(Self::rejection());
|
||||
}
|
||||
if self.transport_error_times.load(Ordering::SeqCst) > 0 {
|
||||
self.transport_error_times.fetch_sub(1, Ordering::SeqCst);
|
||||
return Err(StreamableHttpError::UnexpectedServerResponse(
|
||||
"connection reset".into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rejection() -> StreamableHttpError<Infallible> {
|
||||
StreamableHttpError::AuthRequired(AuthRequiredError::new(
|
||||
"Bearer error=\"invalid_token\"".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl StreamableHttpClient for FakeInner {
|
||||
type Error = Infallible;
|
||||
|
||||
async fn post_message(
|
||||
&self,
|
||||
_uri: Arc<str>,
|
||||
_message: ClientJsonRpcMessage,
|
||||
_session_id: Option<Arc<str>>,
|
||||
auth_header: Option<String>,
|
||||
_custom_headers: HashMap<HeaderName, HeaderValue>,
|
||||
) -> Result<StreamableHttpPostResponse, StreamableHttpError<Self::Error>> {
|
||||
self.record("post_message", auth_header)?;
|
||||
Ok(StreamableHttpPostResponse::Accepted)
|
||||
}
|
||||
|
||||
async fn post_message_with_max_sse_event_size(
|
||||
&self,
|
||||
_uri: Arc<str>,
|
||||
_message: ClientJsonRpcMessage,
|
||||
_session_id: Option<Arc<str>>,
|
||||
auth_header: Option<String>,
|
||||
_custom_headers: HashMap<HeaderName, HeaderValue>,
|
||||
_max_sse_event_size: usize,
|
||||
) -> Result<StreamableHttpPostResponse, StreamableHttpError<Self::Error>> {
|
||||
self.record("post_message_with_max_sse_event_size", auth_header)?;
|
||||
Ok(StreamableHttpPostResponse::Accepted)
|
||||
}
|
||||
|
||||
async fn delete_session(
|
||||
&self,
|
||||
_uri: Arc<str>,
|
||||
_session_id: Arc<str>,
|
||||
auth_header: Option<String>,
|
||||
_custom_headers: HashMap<HeaderName, HeaderValue>,
|
||||
) -> Result<(), StreamableHttpError<Self::Error>> {
|
||||
self.record("delete_session", auth_header)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn get_stream(
|
||||
&self,
|
||||
_uri: Arc<str>,
|
||||
_session_id: Option<Arc<str>>,
|
||||
_last_event_id: Option<String>,
|
||||
auth_header: Option<String>,
|
||||
_custom_headers: HashMap<HeaderName, HeaderValue>,
|
||||
) -> Result<BoxedSseResponse, StreamableHttpError<Self::Error>> {
|
||||
self.record("get_stream", auth_header)?;
|
||||
Ok(futures_util::stream::empty().boxed())
|
||||
}
|
||||
|
||||
async fn get_stream_with_max_sse_event_size(
|
||||
&self,
|
||||
_uri: Arc<str>,
|
||||
_session_id: Option<Arc<str>>,
|
||||
_last_event_id: Option<String>,
|
||||
auth_header: Option<String>,
|
||||
_custom_headers: HashMap<HeaderName, HeaderValue>,
|
||||
_max_sse_event_size: usize,
|
||||
) -> Result<BoxedSseResponse, StreamableHttpError<Self::Error>> {
|
||||
self.record("get_stream_with_max_sse_event_size", auth_header)?;
|
||||
Ok(futures_util::stream::empty().boxed())
|
||||
}
|
||||
}
|
||||
|
||||
fn write_token_file(server: &str, access_token: &str, expires_at: i64) {
|
||||
fs::create_dir_all(paths::oauth_tokens_dir()).unwrap();
|
||||
fs::write(
|
||||
paths::token_file(&format!("mcp_{server}")),
|
||||
format!(
|
||||
r#"{{"access_token":"{access_token}","refresh_token":"r","expires_at":{expires_at}}}"#
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn ping() -> ClientJsonRpcMessage {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "ping"
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn rt() -> tokio::runtime::Runtime {
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn post(
|
||||
client: &McpOAuthClient<FakeInner>,
|
||||
auth_header: Option<String>,
|
||||
) -> Result<StreamableHttpPostResponse, StreamableHttpError<Infallible>> {
|
||||
rt().block_on(client.post_message(
|
||||
Arc::from("http://mcp.test/mcp"),
|
||||
ping(),
|
||||
None,
|
||||
auth_header,
|
||||
HashMap::new(),
|
||||
))
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn injects_token_from_disk_when_auth_header_none() {
|
||||
with_temp_cache(|| {
|
||||
write_token_file("wrapper-inject", "tok-live", FRESH);
|
||||
let inner = FakeInner::default();
|
||||
let client = McpOAuthClient::new(inner.clone(), "wrapper-inject");
|
||||
|
||||
let result = post(&client, None);
|
||||
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(
|
||||
*inner.calls.lock(),
|
||||
vec![("post_message", Some("tok-live".to_string()))]
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn caller_supplied_auth_header_passes_through() {
|
||||
with_temp_cache(|| {
|
||||
write_token_file("wrapper-passthrough", "tok-disk", FRESH);
|
||||
let inner = FakeInner::default();
|
||||
let client = McpOAuthClient::new(inner.clone(), "wrapper-passthrough");
|
||||
|
||||
let result = post(&client, Some("caller-tok".to_string()));
|
||||
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(
|
||||
*inner.calls.lock(),
|
||||
vec![("post_message", Some("caller-tok".to_string()))]
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn caller_supplied_header_rejection_propagates_without_refresh() {
|
||||
with_temp_cache(|| {
|
||||
// A fresh, different token sits on disk: if the injected guard
|
||||
// were dropped, the wrapper would refresh and retry with it.
|
||||
write_token_file("wrapper-caller-401", "tok-disk", FRESH);
|
||||
let inner = FakeInner::default();
|
||||
inner.reject_times.store(1, Ordering::SeqCst);
|
||||
let client = McpOAuthClient::new(inner.clone(), "wrapper-caller-401");
|
||||
|
||||
let result = post(&client, Some("caller-tok".to_string()));
|
||||
|
||||
assert!(matches!(result, Err(StreamableHttpError::AuthRequired(_))));
|
||||
assert_eq!(
|
||||
*inner.calls.lock(),
|
||||
vec![("post_message", Some("caller-tok".to_string()))]
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn missing_token_returns_auth_required_without_calling_inner() {
|
||||
with_temp_cache(|| {
|
||||
let inner = FakeInner::default();
|
||||
let client = McpOAuthClient::new(inner.clone(), "wrapper-no-token");
|
||||
|
||||
let result = post(&client, None);
|
||||
|
||||
assert!(matches!(result, Err(StreamableHttpError::AuthRequired(_))));
|
||||
assert!(inner.calls.lock().is_empty());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn rejected_token_forces_refresh_and_retries_once() {
|
||||
with_temp_cache(|| {
|
||||
write_token_file("wrapper-retry", "tok-a", FRESH);
|
||||
let inner = FakeInner::default();
|
||||
inner.reject_times.store(1, Ordering::SeqCst);
|
||||
// Simulate a concurrent refresh landing between the rejection and
|
||||
// the forced refresh: the retry must carry the new token.
|
||||
*inner.after_first_call.lock() = Some(Box::new(|| {
|
||||
write_token_file("wrapper-retry", "tok-b", FRESH);
|
||||
}));
|
||||
let client = McpOAuthClient::new(inner.clone(), "wrapper-retry");
|
||||
|
||||
let result = post(&client, None);
|
||||
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(
|
||||
*inner.calls.lock(),
|
||||
vec![
|
||||
("post_message", Some("tok-a".to_string())),
|
||||
("post_message", Some("tok-b".to_string())),
|
||||
]
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn failed_force_refresh_propagates_original_error_after_one_call() {
|
||||
with_temp_cache(|| {
|
||||
write_token_file("wrapper-refresh-fail", "tok-a", FRESH);
|
||||
let inner = FakeInner::default();
|
||||
inner.reject_times.store(1, Ordering::SeqCst);
|
||||
// Token file gone by refresh time: force refresh yields nothing.
|
||||
*inner.after_first_call.lock() = Some(Box::new(|| {
|
||||
fs::remove_file(paths::token_file("mcp_wrapper-refresh-fail")).unwrap();
|
||||
}));
|
||||
let client = McpOAuthClient::new(inner.clone(), "wrapper-refresh-fail");
|
||||
|
||||
let result = post(&client, None);
|
||||
|
||||
assert!(matches!(result, Err(StreamableHttpError::AuthRequired(_))));
|
||||
assert_eq!(inner.calls.lock().len(), 1);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn second_rejection_after_retry_propagates_original_error() {
|
||||
with_temp_cache(|| {
|
||||
write_token_file("wrapper-double-401", "tok-a", FRESH);
|
||||
let inner = FakeInner::default();
|
||||
inner.reject_times.store(2, Ordering::SeqCst);
|
||||
// A changed token appears before the forced refresh, so the retry
|
||||
// actually runs (an unchanged token would trigger a real refresh
|
||||
// attempt, which fails without a cached registration).
|
||||
*inner.after_first_call.lock() = Some(Box::new(|| {
|
||||
write_token_file("wrapper-double-401", "tok-b", FRESH);
|
||||
}));
|
||||
let client = McpOAuthClient::new(inner.clone(), "wrapper-double-401");
|
||||
|
||||
let result = post(&client, None);
|
||||
|
||||
assert!(matches!(result, Err(StreamableHttpError::AuthRequired(_))));
|
||||
assert_eq!(inner.calls.lock().len(), 2);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn non_auth_retry_error_propagates_as_is() {
|
||||
with_temp_cache(|| {
|
||||
write_token_file("wrapper-retry-transport", "tok-a", FRESH);
|
||||
let inner = FakeInner::default();
|
||||
inner.reject_times.store(1, Ordering::SeqCst);
|
||||
inner.transport_error_times.store(1, Ordering::SeqCst);
|
||||
*inner.after_first_call.lock() = Some(Box::new(|| {
|
||||
write_token_file("wrapper-retry-transport", "tok-b", FRESH);
|
||||
}));
|
||||
let client = McpOAuthClient::new(inner.clone(), "wrapper-retry-transport");
|
||||
|
||||
let result = post(&client, None);
|
||||
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(StreamableHttpError::UnexpectedServerResponse(_))
|
||||
));
|
||||
assert_eq!(inner.calls.lock().len(), 2);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn sized_post_delegates_to_inner_sized_variant() {
|
||||
with_temp_cache(|| {
|
||||
write_token_file("wrapper-sized-post", "tok-live", FRESH);
|
||||
let inner = FakeInner::default();
|
||||
let client = McpOAuthClient::new(inner.clone(), "wrapper-sized-post");
|
||||
|
||||
let result = rt().block_on(client.post_message_with_max_sse_event_size(
|
||||
Arc::from("http://mcp.test/mcp"),
|
||||
ping(),
|
||||
None,
|
||||
None,
|
||||
HashMap::new(),
|
||||
4096,
|
||||
));
|
||||
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(
|
||||
*inner.calls.lock(),
|
||||
vec![(
|
||||
"post_message_with_max_sse_event_size",
|
||||
Some("tok-live".to_string())
|
||||
)]
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn sized_get_stream_delegates_to_inner_sized_variant() {
|
||||
with_temp_cache(|| {
|
||||
write_token_file("wrapper-sized-get", "tok-live", FRESH);
|
||||
let inner = FakeInner::default();
|
||||
let client = McpOAuthClient::new(inner.clone(), "wrapper-sized-get");
|
||||
|
||||
let result = rt().block_on(client.get_stream_with_max_sse_event_size(
|
||||
Arc::from("http://mcp.test/mcp"),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
HashMap::new(),
|
||||
4096,
|
||||
));
|
||||
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(
|
||||
*inner.calls.lock(),
|
||||
vec![(
|
||||
"get_stream_with_max_sse_event_size",
|
||||
Some("tok-live".to_string())
|
||||
)]
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn get_stream_does_not_retry_on_rejection() {
|
||||
with_temp_cache(|| {
|
||||
write_token_file("wrapper-get-401", "tok-live", FRESH);
|
||||
let inner = FakeInner::default();
|
||||
inner.reject_times.store(1, Ordering::SeqCst);
|
||||
let client = McpOAuthClient::new(inner.clone(), "wrapper-get-401");
|
||||
|
||||
let result = rt().block_on(client.get_stream(
|
||||
Arc::from("http://mcp.test/mcp"),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
HashMap::new(),
|
||||
));
|
||||
|
||||
assert!(matches!(result, Err(StreamableHttpError::AuthRequired(_))));
|
||||
assert_eq!(inner.calls.lock().len(), 1);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn delete_session_injects_token() {
|
||||
with_temp_cache(|| {
|
||||
write_token_file("wrapper-delete", "tok-live", FRESH);
|
||||
let inner = FakeInner::default();
|
||||
let client = McpOAuthClient::new(inner.clone(), "wrapper-delete");
|
||||
|
||||
let result = rt().block_on(client.delete_session(
|
||||
Arc::from("http://mcp.test/mcp"),
|
||||
Arc::from("session-1"),
|
||||
None,
|
||||
HashMap::new(),
|
||||
));
|
||||
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(
|
||||
*inner.calls.lock(),
|
||||
vec![("delete_session", Some("tok-live".to_string()))]
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn auth_required_error_contains_no_token_material() {
|
||||
with_temp_cache(|| {
|
||||
write_token_file("wrapper-redact", "stale-secret-token", 0);
|
||||
let inner = FakeInner::default();
|
||||
let client = McpOAuthClient::new(inner.clone(), "wrapper-redact");
|
||||
|
||||
let err = post(&client, None).unwrap_err();
|
||||
|
||||
let display = format!("{err}");
|
||||
let debug = format!("{err:?}");
|
||||
assert!(!display.contains("stale-secret-token"));
|
||||
assert!(!debug.contains("stale-secret-token"));
|
||||
assert!(inner.calls.lock().is_empty());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,443 @@
|
||||
use crate::cli::{Cli, McpScopeArg, McpTransportArg};
|
||||
use crate::config::{ensure_parent_exists, paths};
|
||||
use crate::mcp::{JsonField, McpOAuthConfig, McpServer, McpServersConfig, McpTransportType};
|
||||
use crate::vault::{SECRET_RE, Vault};
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use indexmap::{IndexMap, IndexSet};
|
||||
use inquire::Confirm;
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
impl From<McpTransportArg> for McpTransportType {
|
||||
fn from(value: McpTransportArg) -> Self {
|
||||
match value {
|
||||
McpTransportArg::Stdio => McpTransportType::Stdio,
|
||||
McpTransportArg::Http => McpTransportType::Http,
|
||||
McpTransportArg::Sse => McpTransportType::Sse,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle(cli: &Cli, vault: &Vault) -> Result<()> {
|
||||
if cli.mcp_list {
|
||||
return handle_list(cli.scope);
|
||||
}
|
||||
if let Some(name) = &cli.mcp_get {
|
||||
return handle_get(name, cli.scope);
|
||||
}
|
||||
if let Some(name) = &cli.mcp_remove {
|
||||
return handle_remove(name, cli.scope, cli.mcp_force);
|
||||
}
|
||||
if let Some(name) = &cli.mcp_add {
|
||||
return handle_add(cli, name, vault);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_list(scope: Option<McpScopeArg>) -> Result<()> {
|
||||
let show_user = scope != Some(McpScopeArg::Workspace);
|
||||
let show_workspace = scope != Some(McpScopeArg::User);
|
||||
|
||||
if show_user {
|
||||
let user_path = paths::mcp_config_file();
|
||||
let user_cfg = load_config_raw(&user_path)?;
|
||||
println!("User ({})", user_path.display());
|
||||
print_server_list(&user_cfg);
|
||||
}
|
||||
|
||||
if show_workspace {
|
||||
match paths::workspace_mcp_config_file() {
|
||||
Some(ws_path) => {
|
||||
let ws_cfg = load_config_raw(&ws_path)?;
|
||||
if show_user {
|
||||
println!();
|
||||
}
|
||||
println!("Workspace ({})", ws_path.display());
|
||||
print_server_list(&ws_cfg);
|
||||
}
|
||||
None if scope == Some(McpScopeArg::Workspace) => {
|
||||
println!("Workspace: no mcp.json found in current directory");
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_server_list(cfg: &McpServersConfig) {
|
||||
if cfg.mcp_servers.is_empty() {
|
||||
println!(" (none)");
|
||||
return;
|
||||
}
|
||||
let name_width = cfg.mcp_servers.keys().map(String::len).max().unwrap_or(0);
|
||||
for (name, spec) in &cfg.mcp_servers {
|
||||
let transport = match spec.transport_type {
|
||||
McpTransportType::Stdio => "stdio",
|
||||
McpTransportType::Http => "http",
|
||||
McpTransportType::Sse => "sse",
|
||||
};
|
||||
let target = spec.url.clone().unwrap_or_else(|| {
|
||||
let cmd = spec.command.clone().unwrap_or_default();
|
||||
let args = spec.args.as_ref().map(|a| a.join(" ")).unwrap_or_default();
|
||||
if args.is_empty() {
|
||||
cmd
|
||||
} else {
|
||||
format!("{cmd} {args}")
|
||||
}
|
||||
});
|
||||
println!(
|
||||
" {name:<name_width$} {transport:<5} {target}",
|
||||
name_width = name_width
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_get(name: &str, scope: Option<McpScopeArg>) -> Result<()> {
|
||||
let (path, cfg) = load_for_scope_or_search(name, scope)?;
|
||||
let spec = cfg
|
||||
.mcp_servers
|
||||
.get(name)
|
||||
.ok_or_else(|| anyhow!("MCP server '{name}' not found"))?;
|
||||
let pretty =
|
||||
serde_json::to_string_pretty(spec).context("failed to serialize MCP server config")?;
|
||||
println!("# {}", path.display());
|
||||
println!("{pretty}");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_remove(name: &str, scope: Option<McpScopeArg>, force: bool) -> Result<()> {
|
||||
let (path, mut cfg) = load_for_scope_or_search(name, scope)?;
|
||||
if !force {
|
||||
let ok = Confirm::new(&format!(
|
||||
"Remove MCP server '{name}' from {}?",
|
||||
path.display()
|
||||
))
|
||||
.with_default(false)
|
||||
.prompt()?;
|
||||
|
||||
if !ok {
|
||||
println!("Aborted.");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
cfg.mcp_servers.shift_remove(name);
|
||||
save_config(&path, &cfg)?;
|
||||
println!("✓ Removed MCP server '{name}' from {}", path.display());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_add(cli: &Cli, name: &str, vault: &Vault) -> Result<()> {
|
||||
validate_name(name)?;
|
||||
let server = build_server(cli)?;
|
||||
server.validate(name)?;
|
||||
|
||||
let scope = cli.scope.unwrap_or_default();
|
||||
let path = write_path_for_scope(scope);
|
||||
let mut cfg = load_config_raw(&path)?;
|
||||
|
||||
if cfg.mcp_servers.contains_key(name) && !cli.mcp_force {
|
||||
let ok = Confirm::new(&format!(
|
||||
"MCP server '{name}' already exists in {}. Overwrite?",
|
||||
path.display()
|
||||
))
|
||||
.with_default(false)
|
||||
.prompt()?;
|
||||
if !ok {
|
||||
println!("Aborted. Use --mcp-force to overwrite without prompting.");
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
provision_secrets(cli, vault)?;
|
||||
|
||||
cfg.mcp_servers.insert(name.to_string(), server);
|
||||
save_config(&path, &cfg)?;
|
||||
println!("✓ Added MCP server '{name}' to {}", path.display());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_name(name: &str) -> Result<()> {
|
||||
if name.is_empty() {
|
||||
bail!("MCP server name cannot be empty");
|
||||
}
|
||||
|
||||
if !name
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
|
||||
{
|
||||
bail!("Invalid MCP server name '{name}': only letters, digits, '-', and '_' are allowed");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn build_server(cli: &Cli) -> Result<McpServer> {
|
||||
let has_command = !cli.mcp_command.is_empty();
|
||||
let has_url = cli.url.is_some();
|
||||
|
||||
let transport = cli
|
||||
.transport
|
||||
.map(McpTransportType::from)
|
||||
.unwrap_or_else(|| {
|
||||
if has_command {
|
||||
McpTransportType::Stdio
|
||||
} else {
|
||||
McpTransportType::Http
|
||||
}
|
||||
});
|
||||
|
||||
match transport {
|
||||
McpTransportType::Stdio => build_stdio(cli, has_url),
|
||||
McpTransportType::Http | McpTransportType::Sse => build_remote(cli, transport, has_command),
|
||||
}
|
||||
}
|
||||
|
||||
fn build_stdio(cli: &Cli, has_url: bool) -> Result<McpServer> {
|
||||
if cli.mcp_command.is_empty() {
|
||||
bail!(
|
||||
"stdio MCP server requires a command. Pass it after `--`, e.g. \
|
||||
`--mcp-add NAME -- npx some-server --flag`"
|
||||
);
|
||||
}
|
||||
if has_url {
|
||||
bail!("stdio MCP server does not accept --url");
|
||||
}
|
||||
if !cli.header.is_empty() {
|
||||
bail!("stdio MCP server does not accept --header");
|
||||
}
|
||||
if cli.client_id.is_some()
|
||||
|| cli.client_secret.is_some()
|
||||
|| cli.callback_port.is_some()
|
||||
|| cli.redirect_host.is_some()
|
||||
{
|
||||
bail!("stdio MCP server does not accept OAuth flags");
|
||||
}
|
||||
|
||||
let (cmd, args) = cli.mcp_command.split_first().unwrap();
|
||||
|
||||
let mut env: IndexMap<String, JsonField> = IndexMap::new();
|
||||
for kv in &cli.env {
|
||||
let (k, v) = kv
|
||||
.split_once('=')
|
||||
.ok_or_else(|| anyhow!("invalid --env value '{kv}': expected KEY=VALUE"))?;
|
||||
if k.is_empty() {
|
||||
bail!("invalid --env value '{kv}': KEY cannot be empty");
|
||||
}
|
||||
env.insert(k.to_string(), JsonField::Str(v.to_string()));
|
||||
}
|
||||
|
||||
Ok(McpServer {
|
||||
transport_type: McpTransportType::Stdio,
|
||||
command: Some(cmd.clone()),
|
||||
args: (!args.is_empty()).then(|| args.to_vec()),
|
||||
env: (!env.is_empty()).then_some(env),
|
||||
cwd: cli.cwd.clone(),
|
||||
url: None,
|
||||
headers: None,
|
||||
oauth: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn build_remote(cli: &Cli, transport: McpTransportType, has_command: bool) -> Result<McpServer> {
|
||||
if has_command {
|
||||
bail!(
|
||||
"http/sse MCP server does not accept a trailing `-- <cmd>`. Use `--url` \
|
||||
to specify the endpoint."
|
||||
);
|
||||
}
|
||||
let url = cli
|
||||
.url
|
||||
.clone()
|
||||
.ok_or_else(|| anyhow!("http/sse MCP server requires --url <URL>"))?;
|
||||
if !cli.env.is_empty() {
|
||||
bail!("http/sse MCP server does not accept --env; use --header instead");
|
||||
}
|
||||
if cli.cwd.is_some() {
|
||||
bail!("http/sse MCP server does not accept --cwd");
|
||||
}
|
||||
|
||||
let mut headers: IndexMap<String, String> = IndexMap::new();
|
||||
for h in &cli.header {
|
||||
let (name, value) = h
|
||||
.split_once(':')
|
||||
.ok_or_else(|| anyhow!("invalid --header value '{h}': expected 'Name: Value'"))?;
|
||||
let name = name.trim();
|
||||
let value = value.trim_start_matches(' ');
|
||||
if name.is_empty() {
|
||||
bail!("invalid --header value '{h}': header name cannot be empty");
|
||||
}
|
||||
headers.insert(name.to_string(), value.to_string());
|
||||
}
|
||||
|
||||
let oauth = if cli.client_id.is_some()
|
||||
|| cli.client_secret.is_some()
|
||||
|| cli.callback_port.is_some()
|
||||
|| cli.redirect_host.is_some()
|
||||
{
|
||||
Some(McpOAuthConfig {
|
||||
client_id: cli.client_id.clone(),
|
||||
client_secret: cli.client_secret.clone(),
|
||||
callback_port: cli.callback_port,
|
||||
redirect_host: cli.redirect_host.clone(),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(McpServer {
|
||||
transport_type: transport,
|
||||
command: None,
|
||||
args: None,
|
||||
env: None,
|
||||
cwd: None,
|
||||
url: Some(url),
|
||||
headers: (!headers.is_empty()).then_some(headers),
|
||||
oauth,
|
||||
})
|
||||
}
|
||||
|
||||
fn provision_secrets(cli: &Cli, vault: &Vault) -> Result<()> {
|
||||
let mut sources: Vec<&str> = Vec::new();
|
||||
if let Some(s) = cli.url.as_deref() {
|
||||
sources.push(s);
|
||||
}
|
||||
if let Some(s) = cli.client_secret.as_deref() {
|
||||
sources.push(s);
|
||||
}
|
||||
if let Some(s) = cli.client_id.as_deref() {
|
||||
sources.push(s);
|
||||
}
|
||||
if let Some(s) = cli.redirect_host.as_deref() {
|
||||
sources.push(s);
|
||||
}
|
||||
if let Some(s) = cli.cwd.as_deref() {
|
||||
sources.push(s);
|
||||
}
|
||||
sources.extend(cli.env.iter().map(String::as_str));
|
||||
sources.extend(cli.header.iter().map(String::as_str));
|
||||
|
||||
let mut needed: IndexSet<String> = IndexSet::new();
|
||||
for value in sources {
|
||||
for caps in SECRET_RE.captures_iter(value).filter_map(Result::ok) {
|
||||
if let Some(m) = caps.get(1) {
|
||||
needed.insert(m.as_str().trim().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if needed.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let existing: HashSet<String> = vault.list_secrets(false)?.into_iter().collect();
|
||||
for name in needed {
|
||||
if existing.contains(&name) {
|
||||
continue;
|
||||
}
|
||||
eprintln!("Value references vault secret {{{{ {name} }}}} which is not stored yet.");
|
||||
let ok = Confirm::new(&format!("Add '{name}' to the vault now?"))
|
||||
.with_default(true)
|
||||
.prompt()?;
|
||||
if !ok {
|
||||
bail!(
|
||||
"Vault secret '{name}' is required by the config; aborting. \
|
||||
Add it later with `coyote --add-secret {name}`."
|
||||
);
|
||||
}
|
||||
vault.add_secret(&name)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_for_scope_or_search(
|
||||
name: &str,
|
||||
scope: Option<McpScopeArg>,
|
||||
) -> Result<(PathBuf, McpServersConfig)> {
|
||||
if let Some(s) = scope {
|
||||
let path = match s {
|
||||
McpScopeArg::User => paths::mcp_config_file(),
|
||||
McpScopeArg::Workspace => paths::workspace_mcp_config_file()
|
||||
.ok_or_else(|| anyhow!("no workspace mcp.json found in the current directory"))?,
|
||||
};
|
||||
let cfg = load_config_raw(&path)?;
|
||||
if !cfg.mcp_servers.contains_key(name) {
|
||||
bail!(
|
||||
"MCP server '{name}' not found in {} scope ({})",
|
||||
scope_label(s),
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
|
||||
return Ok((path, cfg));
|
||||
}
|
||||
|
||||
let user_path = paths::mcp_config_file();
|
||||
let user_cfg = load_config_raw(&user_path)?;
|
||||
if user_cfg.mcp_servers.contains_key(name) {
|
||||
return Ok((user_path, user_cfg));
|
||||
}
|
||||
|
||||
if let Some(ws_path) = paths::workspace_mcp_config_file() {
|
||||
let ws_cfg = load_config_raw(&ws_path)?;
|
||||
if ws_cfg.mcp_servers.contains_key(name) {
|
||||
return Ok((ws_path, ws_cfg));
|
||||
}
|
||||
}
|
||||
|
||||
bail!("MCP server '{name}' not found in any scope");
|
||||
}
|
||||
|
||||
fn write_path_for_scope(scope: McpScopeArg) -> PathBuf {
|
||||
match scope {
|
||||
McpScopeArg::User => paths::mcp_config_file(),
|
||||
McpScopeArg::Workspace => paths::workspace_mcp_config_file()
|
||||
.unwrap_or_else(|| paths::workspace_config_dir().join("mcp.json")),
|
||||
}
|
||||
}
|
||||
|
||||
fn scope_label(scope: McpScopeArg) -> &'static str {
|
||||
match scope {
|
||||
McpScopeArg::User => "user",
|
||||
McpScopeArg::Workspace => "workspace",
|
||||
}
|
||||
}
|
||||
|
||||
fn load_config_raw(path: &Path) -> Result<McpServersConfig> {
|
||||
if !path.exists() {
|
||||
return Ok(McpServersConfig {
|
||||
mcp_servers: IndexMap::new(),
|
||||
});
|
||||
}
|
||||
|
||||
let raw = fs::read_to_string(path)
|
||||
.with_context(|| format!("failed to read MCP config at {}", path.display()))?;
|
||||
if raw.trim().is_empty() {
|
||||
return Ok(McpServersConfig {
|
||||
mcp_servers: IndexMap::new(),
|
||||
});
|
||||
}
|
||||
|
||||
serde_json::from_str(&raw)
|
||||
.with_context(|| format!("failed to parse MCP config at {}", path.display()))
|
||||
}
|
||||
|
||||
fn save_config(path: &Path, config: &McpServersConfig) -> Result<()> {
|
||||
ensure_parent_exists(path)?;
|
||||
let serialized =
|
||||
serde_json::to_string_pretty(config).context("failed to serialize MCP config")?;
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
fs::write(&tmp, &serialized)
|
||||
.with_context(|| format!("failed to write temporary MCP config at {}", tmp.display()))?;
|
||||
fs::rename(&tmp, path)
|
||||
.with_context(|| format!("failed to finalize MCP config at {}", path.display()))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+316
-12
@@ -1,3 +1,5 @@
|
||||
mod auth_client;
|
||||
pub(crate) mod manage;
|
||||
pub(crate) mod oauth;
|
||||
mod sse_transport;
|
||||
|
||||
@@ -8,6 +10,7 @@ use crate::vault::Vault;
|
||||
use crate::vault::interpolate_secrets;
|
||||
use anyhow::Error;
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use auth_client::McpOAuthClient;
|
||||
use futures_util::{StreamExt, TryStreamExt, stream};
|
||||
use http::{HeaderName, HeaderValue};
|
||||
use indexmap::IndexMap;
|
||||
@@ -20,6 +23,8 @@ use rmcp::{RoleClient, ServiceExt};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sse_transport::LegacySseTransport;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fmt;
|
||||
use std::fmt::Display;
|
||||
use std::fs::OpenOptions;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Stdio;
|
||||
@@ -62,6 +67,8 @@ pub(crate) struct McpServersConfig {
|
||||
pub(crate) struct McpOAuthConfig {
|
||||
#[serde(rename = "clientId", skip_serializing_if = "Option::is_none")]
|
||||
pub client_id: Option<String>,
|
||||
#[serde(rename = "clientSecret", skip_serializing_if = "Option::is_none")]
|
||||
pub client_secret: Option<String>,
|
||||
#[serde(rename = "callbackPort", skip_serializing_if = "Option::is_none")]
|
||||
pub callback_port: Option<u16>,
|
||||
#[serde(rename = "redirectHost", skip_serializing_if = "Option::is_none")]
|
||||
@@ -323,18 +330,17 @@ impl McpRegistry {
|
||||
.and_then(|c| c.mcp_servers.get(&id))
|
||||
.with_context(|| format!("MCP server not found in config: {id}"))?;
|
||||
|
||||
let bearer_token = if spec.is_remote() {
|
||||
oauth::load_valid_mcp_token(&id)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let (auth, auth_reason) = resolve_http_auth(&id, spec).await;
|
||||
|
||||
let service = match spawn_mcp_server(spec, self.log_path.as_deref(), bearer_token).await {
|
||||
let service = match spawn_mcp_server(spec, self.log_path.as_deref(), auth).await {
|
||||
Ok(s) => s,
|
||||
Err(e) if is_auth_required_error(&e) => {
|
||||
warn!(
|
||||
"MCP server '{id}' requires OAuth authentication. \
|
||||
Run `coyote --auth-mcp {id}` or `.mcp auth {id}` in the REPL to authenticate."
|
||||
"{}",
|
||||
McpAuthRequired {
|
||||
server: id,
|
||||
reason: auth_reason,
|
||||
}
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -409,19 +415,76 @@ impl McpRegistry {
|
||||
}
|
||||
}
|
||||
|
||||
/// How a remote MCP server authenticates outgoing requests.
|
||||
pub(crate) enum HttpAuth {
|
||||
/// Only the static headers from the server spec; no OAuth token.
|
||||
StaticOnly,
|
||||
/// OAuth-managed: HTTP transports inject a fresh bearer token per request
|
||||
/// via [`McpOAuthClient`] (ignoring the carried token); SSE transports
|
||||
/// send the carried token as a static header.
|
||||
Managed { server: String, token: String },
|
||||
}
|
||||
|
||||
impl fmt::Debug for HttpAuth {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::StaticOnly => f.write_str("StaticOnly"),
|
||||
Self::Managed { server, token: _ } => f
|
||||
.debug_struct("Managed")
|
||||
.field("server", server)
|
||||
.field("token", &"<redacted>")
|
||||
.finish(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HttpAuth {
|
||||
pub(crate) fn from_token_status(status: &oauth::McpTokenStatus, server: &str) -> Self {
|
||||
match status {
|
||||
oauth::McpTokenStatus::Token(token) => Self::Managed {
|
||||
server: server.to_string(),
|
||||
token: token.clone(),
|
||||
},
|
||||
oauth::McpTokenStatus::NotAuthenticated | oauth::McpTokenStatus::RefreshFailed => {
|
||||
Self::StaticOnly
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn resolve_http_auth(name: &str, spec: &McpServer) -> (HttpAuth, McpAuthReason) {
|
||||
let token_status = if spec.is_remote() {
|
||||
oauth::load_or_refresh_mcp_token(name).await
|
||||
} else {
|
||||
oauth::McpTokenStatus::NotAuthenticated
|
||||
};
|
||||
(
|
||||
HttpAuth::from_token_status(&token_status, name),
|
||||
McpAuthReason::from_token_status(&token_status),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) async fn spawn_mcp_server(
|
||||
spec: &McpServer,
|
||||
log_path: Option<&Path>,
|
||||
bearer_token: Option<String>,
|
||||
auth: HttpAuth,
|
||||
) -> Result<Arc<ConnectedServer>> {
|
||||
match spec.transport_type {
|
||||
McpTransportType::Http => {
|
||||
let url = spec.url.as_deref().expect("validated: http spec has url");
|
||||
let headers = merge_bearer_token(spec.headers.as_ref(), bearer_token);
|
||||
spawn_http_mcp_server(url, headers.as_ref()).await
|
||||
match auth {
|
||||
HttpAuth::Managed { server, token: _ } => {
|
||||
spawn_oauth_http_mcp_server(url, &server, spec.headers.as_ref()).await
|
||||
}
|
||||
HttpAuth::StaticOnly => spawn_http_mcp_server(url, spec.headers.as_ref()).await,
|
||||
}
|
||||
}
|
||||
McpTransportType::Sse => {
|
||||
let url = spec.url.as_deref().expect("validated: sse spec has url");
|
||||
let bearer_token = match auth {
|
||||
HttpAuth::Managed { server: _, token } => Some(token),
|
||||
HttpAuth::StaticOnly => None,
|
||||
};
|
||||
let headers = merge_bearer_token(spec.headers.as_ref(), bearer_token);
|
||||
spawn_sse_mcp_server(url, headers.as_ref()).await
|
||||
}
|
||||
@@ -449,14 +512,65 @@ fn merge_bearer_token(
|
||||
}
|
||||
(Some(h), Some(token)) => {
|
||||
let mut m = h.clone();
|
||||
m.retain(|k, _| !k.eq_ignore_ascii_case("authorization"));
|
||||
m.insert("Authorization".to_string(), format!("Bearer {token}"));
|
||||
Some(m)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum McpAuthReason {
|
||||
NotAuthenticated,
|
||||
RefreshFailed,
|
||||
TokenRejected,
|
||||
}
|
||||
|
||||
impl McpAuthReason {
|
||||
pub(crate) fn from_token_status(status: &oauth::McpTokenStatus) -> Self {
|
||||
match status {
|
||||
oauth::McpTokenStatus::Token(_) => Self::TokenRejected,
|
||||
oauth::McpTokenStatus::NotAuthenticated => Self::NotAuthenticated,
|
||||
oauth::McpTokenStatus::RefreshFailed => Self::RefreshFailed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct McpAuthRequired {
|
||||
pub server: String,
|
||||
pub reason: McpAuthReason,
|
||||
}
|
||||
|
||||
impl Display for McpAuthRequired {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let server = &self.server;
|
||||
match self.reason {
|
||||
McpAuthReason::NotAuthenticated => write!(
|
||||
f,
|
||||
"MCP server '{server}' requires OAuth authentication and was not started \
|
||||
(no stored credentials). Run `.mcp auth {server}` (or `coyote --auth-mcp \
|
||||
{server}`) to authenticate and attach it."
|
||||
),
|
||||
McpAuthReason::RefreshFailed => write!(
|
||||
f,
|
||||
"MCP server '{server}' was not started: stored OAuth token has expired and \
|
||||
automatic refresh failed. Run `.mcp auth {server}` (or `coyote --auth-mcp \
|
||||
{server}`) to re-authenticate and attach it."
|
||||
),
|
||||
McpAuthReason::TokenRejected => write!(
|
||||
f,
|
||||
"MCP server '{server}' was not started: the server rejected the stored OAuth \
|
||||
token. Run `.mcp auth {server}` (or `coyote --auth-mcp {server}`) to \
|
||||
re-authenticate and attach it."
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_auth_required_error(e: &Error) -> bool {
|
||||
e.chain()
|
||||
e.downcast_ref::<McpAuthRequired>().is_some()
|
||||
|| e.chain()
|
||||
.any(|cause| cause.to_string().contains("Auth required"))
|
||||
}
|
||||
|
||||
@@ -490,6 +604,66 @@ async fn spawn_http_mcp_server(
|
||||
Ok(service)
|
||||
}
|
||||
|
||||
/// Builds the custom-header map for an OAuth-managed HTTP transport, dropping
|
||||
/// any static `Authorization` entry case-insensitively: [`McpOAuthClient`]
|
||||
/// owns that header, and a stale configured value must not collide with the
|
||||
/// per-request token.
|
||||
fn oauth_custom_headers(
|
||||
headers: Option<&IndexMap<String, String>>,
|
||||
) -> Result<HashMap<HeaderName, HeaderValue>> {
|
||||
let mut custom = HashMap::new();
|
||||
let Some(hdrs) = headers else {
|
||||
return Ok(custom);
|
||||
};
|
||||
|
||||
for (k, v) in hdrs {
|
||||
if k.eq_ignore_ascii_case("authorization") {
|
||||
continue;
|
||||
}
|
||||
let name = k
|
||||
.parse::<HeaderName>()
|
||||
.with_context(|| format!("Invalid header name: {k}"))?;
|
||||
let value = v
|
||||
.parse::<HeaderValue>()
|
||||
.with_context(|| format!("Invalid header value for {k}"))?;
|
||||
custom.insert(name, value);
|
||||
}
|
||||
|
||||
Ok(custom)
|
||||
}
|
||||
|
||||
async fn spawn_oauth_http_mcp_server(
|
||||
url: &str,
|
||||
server: &str,
|
||||
headers: Option<&IndexMap<String, String>>,
|
||||
) -> Result<Arc<ConnectedServer>> {
|
||||
// Mirror rmcp's default_http_client, which `with_client` bypasses:
|
||||
// idle pooling off avoids a documented TCP delayed-ACK stall, and
|
||||
// redirects off keeps custom headers from being replayed to a redirect
|
||||
// target.
|
||||
let inner = reqwest::Client::builder()
|
||||
.pool_max_idle_per_host(0)
|
||||
.redirect(reqwest::redirect::Policy::none())
|
||||
.build()
|
||||
.context("Failed to build HTTP client for OAuth-managed MCP transport")?;
|
||||
let client = McpOAuthClient::new(inner, server);
|
||||
// `auth_header` stays None so the wrapper injects a fresh token per
|
||||
// request; `reinit_on_expired_session` defaults to true in rmcp 3.1.2
|
||||
// but is pinned explicitly because transparent session re-init is
|
||||
// load-bearing for long-lived sessions.
|
||||
let config = StreamableHttpClientTransportConfig::with_uri(url)
|
||||
.custom_headers(oauth_custom_headers(headers)?)
|
||||
.reinit_on_expired_session(true);
|
||||
let transport = StreamableHttpClientTransport::with_client(client, config);
|
||||
let service = Arc::new(
|
||||
().serve(transport)
|
||||
.await
|
||||
.with_context(|| format!("Failed to connect to HTTP MCP server: {url}"))?,
|
||||
);
|
||||
|
||||
Ok(service)
|
||||
}
|
||||
|
||||
async fn spawn_sse_mcp_server(
|
||||
url: &str,
|
||||
headers: Option<&IndexMap<String, String>>,
|
||||
@@ -1048,6 +1222,92 @@ mod tests {
|
||||
assert_eq!(result["X-Custom"], "keep");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_bearer_token_replaces_authorization_case_insensitively() {
|
||||
let mut h = IndexMap::new();
|
||||
h.insert("authorization".to_string(), "Bearer stale-1".to_string());
|
||||
h.insert("AUTHORIZATION".to_string(), "Bearer stale-2".to_string());
|
||||
h.insert("X-Custom".to_string(), "keep".to_string());
|
||||
|
||||
let result = merge_bearer_token(Some(&h), Some("newtoken".to_string())).unwrap();
|
||||
|
||||
assert_eq!(result.len(), 2);
|
||||
assert_eq!(result["Authorization"], "Bearer newtoken");
|
||||
assert_eq!(result["X-Custom"], "keep");
|
||||
assert!(!result.contains_key("authorization"));
|
||||
assert!(!result.contains_key("AUTHORIZATION"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_auth_from_token_status_maps_token_to_managed() {
|
||||
assert!(matches!(
|
||||
HttpAuth::from_token_status(&oauth::McpTokenStatus::Token("tok".into()), "srv"),
|
||||
HttpAuth::Managed { server, token } if server == "srv" && token == "tok"
|
||||
));
|
||||
assert!(matches!(
|
||||
HttpAuth::from_token_status(&oauth::McpTokenStatus::NotAuthenticated, "srv"),
|
||||
HttpAuth::StaticOnly
|
||||
));
|
||||
assert!(matches!(
|
||||
HttpAuth::from_token_status(&oauth::McpTokenStatus::RefreshFailed, "srv"),
|
||||
HttpAuth::StaticOnly
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_auth_debug_redacts_token() {
|
||||
let auth = HttpAuth::Managed {
|
||||
server: "srv".into(),
|
||||
token: "live-secret".into(),
|
||||
};
|
||||
|
||||
let debug = format!("{auth:?}");
|
||||
|
||||
assert!(debug.contains("srv"));
|
||||
assert!(debug.contains("<redacted>"));
|
||||
assert!(!debug.contains("live-secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oauth_custom_headers_strips_authorization_case_insensitively() {
|
||||
let mut h = IndexMap::new();
|
||||
h.insert("Authorization".to_string(), "Bearer stale-1".to_string());
|
||||
h.insert("authorization".to_string(), "Bearer stale-2".to_string());
|
||||
h.insert("AUTHORIZATION".to_string(), "Bearer stale-3".to_string());
|
||||
h.insert("X-Custom".to_string(), "keep".to_string());
|
||||
|
||||
let custom = oauth_custom_headers(Some(&h)).unwrap();
|
||||
|
||||
assert_eq!(custom.len(), 1);
|
||||
assert_eq!(custom[&HeaderName::from_static("x-custom")], "keep");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oauth_custom_headers_none_is_empty() {
|
||||
assert!(oauth_custom_headers(None).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oauth_custom_headers_rejects_invalid_header_name() {
|
||||
let mut h = IndexMap::new();
|
||||
h.insert("bad header".to_string(), "v".to_string());
|
||||
|
||||
assert!(oauth_custom_headers(Some(&h)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oauth_custom_headers_keeps_non_authorization_headers() {
|
||||
let mut h = IndexMap::new();
|
||||
h.insert("X-Api-Key".to_string(), "k".to_string());
|
||||
h.insert("X-Trace".to_string(), "t".to_string());
|
||||
|
||||
let custom = oauth_custom_headers(Some(&h)).unwrap();
|
||||
|
||||
assert_eq!(custom.len(), 2);
|
||||
assert_eq!(custom[&HeaderName::from_static("x-api-key")], "k");
|
||||
assert_eq!(custom[&HeaderName::from_static("x-trace")], "t");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_auth_required_error_matches_rmcp_message() {
|
||||
let e = anyhow!("Auth required, when send initialize request");
|
||||
@@ -1071,4 +1331,48 @@ mod tests {
|
||||
|
||||
assert!(is_auth_required_error(&e));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auth_reason_maps_token_status() {
|
||||
assert_eq!(
|
||||
McpAuthReason::from_token_status(&oauth::McpTokenStatus::Token("tok".into())),
|
||||
McpAuthReason::TokenRejected
|
||||
);
|
||||
assert_eq!(
|
||||
McpAuthReason::from_token_status(&oauth::McpTokenStatus::NotAuthenticated),
|
||||
McpAuthReason::NotAuthenticated
|
||||
);
|
||||
assert_eq!(
|
||||
McpAuthReason::from_token_status(&oauth::McpTokenStatus::RefreshFailed),
|
||||
McpAuthReason::RefreshFailed
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_auth_required_context_downcasts_with_reason() {
|
||||
let e = anyhow!("Auth required, when send initialize request").context(McpAuthRequired {
|
||||
server: "github".into(),
|
||||
reason: McpAuthReason::RefreshFailed,
|
||||
});
|
||||
|
||||
assert!(is_auth_required_error(&e));
|
||||
let ctx = e.downcast_ref::<McpAuthRequired>().unwrap();
|
||||
assert_eq!(ctx.server, "github");
|
||||
assert_eq!(ctx.reason, McpAuthReason::RefreshFailed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_auth_required_display_is_reason_specific() {
|
||||
let msg = |reason| {
|
||||
McpAuthRequired {
|
||||
server: "github".into(),
|
||||
reason,
|
||||
}
|
||||
.to_string()
|
||||
};
|
||||
|
||||
assert!(msg(McpAuthReason::NotAuthenticated).contains("no stored credentials"));
|
||||
assert!(msg(McpAuthReason::RefreshFailed).contains("expired and automatic refresh failed"));
|
||||
assert!(msg(McpAuthReason::TokenRejected).contains("rejected the stored OAuth token"));
|
||||
}
|
||||
}
|
||||
|
||||
+531
-32
@@ -1,15 +1,26 @@
|
||||
use crate::client::oauth::{OAuthProvider, TokenRequestFormat, load_oauth_tokens, run_oauth_flow};
|
||||
use crate::client::oauth::{
|
||||
OAuthProvider, OAuthTokens, TokenRequestFormat, load_oauth_tokens, refresh_oauth_token,
|
||||
run_oauth_flow, token_response_keys,
|
||||
};
|
||||
use crate::config::paths;
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use chrono::Utc;
|
||||
use inquire::Text;
|
||||
use log::warn;
|
||||
use log::{debug, warn};
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::fs;
|
||||
use std::net::TcpListener;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::sync;
|
||||
use url::Url;
|
||||
|
||||
const REFRESH_HTTP_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const REFRESH_FAILURE_BACKOFF: Duration = Duration::from_secs(60);
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ProtectedResourceMetadata {
|
||||
#[serde(default)]
|
||||
@@ -34,6 +45,10 @@ struct McpRegistration {
|
||||
client_id: String,
|
||||
#[serde(default)]
|
||||
redirect_uri: Option<String>,
|
||||
#[serde(default)]
|
||||
token_url: Option<String>,
|
||||
#[serde(default)]
|
||||
resource: Option<String>,
|
||||
}
|
||||
|
||||
struct DiscoveredOAuth {
|
||||
@@ -124,8 +139,19 @@ pub async fn run_mcp_oauth_flow(
|
||||
None
|
||||
};
|
||||
|
||||
let (client_id, redirect_uri) = if let Some(reused) = cached_reuse {
|
||||
reused
|
||||
let (client_id, redirect_uri) = if let Some((client_id, redirect_uri)) = cached_reuse {
|
||||
// Re-save so registrations cached before token_url/resource were
|
||||
// persisted gain them, enabling token refresh next time.
|
||||
if let Err(e) = save_registration(
|
||||
server_name,
|
||||
&client_id,
|
||||
&redirect_uri,
|
||||
&metadata.token_endpoint,
|
||||
&resource,
|
||||
) {
|
||||
debug!("Failed to update cached MCP registration for '{server_name}': {e}");
|
||||
}
|
||||
(client_id, redirect_uri)
|
||||
} else {
|
||||
let bind_addr = format!("127.0.0.1:{}", callback_port.unwrap_or(0));
|
||||
let listener = TcpListener::bind(&bind_addr)?;
|
||||
@@ -137,10 +163,7 @@ pub async fn run_mcp_oauth_flow(
|
||||
id.to_string()
|
||||
} else if let Some(reg_endpoint) = &metadata.registration_endpoint {
|
||||
match register_client(reg_endpoint, &redirect_uri).await {
|
||||
Ok(id) => {
|
||||
let _ = save_registration(server_name, &id, &redirect_uri);
|
||||
id
|
||||
}
|
||||
Ok(id) => id,
|
||||
Err(e) => {
|
||||
warn!("Dynamic client registration failed: {e}. Falling back to manual entry.");
|
||||
Text::new("Enter the OAuth client ID for this MCP server:")
|
||||
@@ -153,6 +176,18 @@ pub async fn run_mcp_oauth_flow(
|
||||
.prompt()
|
||||
.context("Failed to read client ID")?
|
||||
};
|
||||
// Persist regardless of how the client_id was obtained (DCR, config,
|
||||
// or manual entry) so refresh_mcp_token can run the refresh_token
|
||||
// grant later without interactive re-auth.
|
||||
if let Err(e) = save_registration(
|
||||
server_name,
|
||||
&client_id,
|
||||
&redirect_uri,
|
||||
&metadata.token_endpoint,
|
||||
&resource,
|
||||
) {
|
||||
debug!("Failed to cache MCP registration for '{server_name}': {e}");
|
||||
}
|
||||
(client_id, redirect_uri)
|
||||
};
|
||||
|
||||
@@ -168,12 +203,164 @@ pub async fn run_mcp_oauth_flow(
|
||||
run_oauth_flow(&provider, &mcp_token_key(server_name)).await
|
||||
}
|
||||
|
||||
pub fn load_valid_mcp_token(server_name: &str) -> Option<String> {
|
||||
let tokens = load_oauth_tokens(&mcp_token_key(server_name))?;
|
||||
if Utc::now().timestamp() < tokens.expires_at {
|
||||
Some(tokens.access_token)
|
||||
} else {
|
||||
None
|
||||
#[derive(PartialEq, Eq)]
|
||||
pub enum McpTokenStatus {
|
||||
Token(String),
|
||||
NotAuthenticated,
|
||||
RefreshFailed,
|
||||
}
|
||||
|
||||
impl fmt::Debug for McpTokenStatus {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Token(_) => f.write_str("Token(<redacted>)"),
|
||||
Self::NotAuthenticated => f.write_str("NotAuthenticated"),
|
||||
Self::RefreshFailed => f.write_str("RefreshFailed"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl McpTokenStatus {
|
||||
pub fn into_token(self) -> Option<String> {
|
||||
match self {
|
||||
Self::Token(token) => Some(token),
|
||||
Self::NotAuthenticated | Self::RefreshFailed => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn load_or_refresh_mcp_token(server_name: &str) -> McpTokenStatus {
|
||||
load_or_refresh_inner(server_name, None).await
|
||||
}
|
||||
|
||||
/// Re-acquires a token after the server rejected the current one mid-session
|
||||
/// (HTTP 401). The rejection proves the stored token is bad regardless of its
|
||||
/// expiry timestamp, so the unexpired fast-paths only short-circuit when the
|
||||
/// stored token DIFFERS from `rejected_token` (a concurrent caller genuinely
|
||||
/// refreshed while we waited); an unexpired copy of the rejected token is
|
||||
/// refreshed anyway. The failure backoff and per-server single-flight lock
|
||||
/// still apply.
|
||||
pub async fn force_refresh_mcp_token(server_name: &str, rejected_token: &str) -> Option<String> {
|
||||
load_or_refresh_inner(server_name, Some(rejected_token))
|
||||
.await
|
||||
.into_token()
|
||||
}
|
||||
|
||||
async fn load_or_refresh_inner(server_name: &str, rejected_token: Option<&str>) -> McpTokenStatus {
|
||||
let key = mcp_token_key(server_name);
|
||||
let Some(tokens) = load_oauth_tokens(&key) else {
|
||||
return McpTokenStatus::NotAuthenticated;
|
||||
};
|
||||
if rejected_token.is_none() && Utc::now().timestamp() < tokens.expires_at {
|
||||
return McpTokenStatus::Token(tokens.access_token);
|
||||
}
|
||||
|
||||
if in_refresh_failure_backoff(server_name) {
|
||||
debug!("Skipping token refresh for MCP server '{server_name}': recent attempt failed");
|
||||
return McpTokenStatus::RefreshFailed;
|
||||
}
|
||||
|
||||
let lock = refresh_lock(server_name);
|
||||
let _guard = lock.lock().await;
|
||||
|
||||
// A concurrent caller may have refreshed while we waited for the lock. An
|
||||
// unexpired token is only trusted if it differs from the rejected one:
|
||||
// the server already proved that exact token bad.
|
||||
let Some(tokens) = load_oauth_tokens(&key) else {
|
||||
return McpTokenStatus::NotAuthenticated;
|
||||
};
|
||||
if Utc::now().timestamp() < tokens.expires_at
|
||||
&& rejected_token.is_none_or(|rejected| rejected != tokens.access_token)
|
||||
{
|
||||
return McpTokenStatus::Token(tokens.access_token);
|
||||
}
|
||||
|
||||
if in_refresh_failure_backoff(server_name) {
|
||||
debug!("Skipping token refresh for MCP server '{server_name}': recent attempt failed");
|
||||
return McpTokenStatus::RefreshFailed;
|
||||
}
|
||||
|
||||
match refresh_mcp_token(server_name, &key, &tokens).await {
|
||||
Ok(access_token) => McpTokenStatus::Token(access_token),
|
||||
Err(e) => {
|
||||
note_refresh_failure(server_name);
|
||||
warn!(
|
||||
"Failed to refresh OAuth token for MCP server '{server_name}'. \
|
||||
Run `.mcp auth {server_name}` to re-authenticate."
|
||||
);
|
||||
debug!(
|
||||
"Token refresh error for MCP server '{server_name}': {}",
|
||||
redact_refresh_error(&e)
|
||||
);
|
||||
McpTokenStatus::RefreshFailed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn refresh_mcp_token(server_name: &str, key: &str, tokens: &OAuthTokens) -> Result<String> {
|
||||
if tokens.refresh_token.is_none() {
|
||||
return Err(anyhow!("no refresh token stored"));
|
||||
}
|
||||
|
||||
let reg =
|
||||
load_registration(server_name).ok_or_else(|| anyhow!("no cached client registration"))?;
|
||||
let token_url = reg.token_url.ok_or_else(|| {
|
||||
anyhow!("cached registration has no token URL (saved by an older version)")
|
||||
})?;
|
||||
let resource = reg.resource.ok_or_else(|| {
|
||||
anyhow!("cached registration has no resource (saved by an older version)")
|
||||
})?;
|
||||
|
||||
let provider = McpOAuthProvider {
|
||||
client_id: reg.client_id,
|
||||
authorize_url: String::new(),
|
||||
token_url,
|
||||
scopes: String::new(),
|
||||
fixed_redirect: String::new(),
|
||||
resource,
|
||||
};
|
||||
|
||||
let client = Client::builder().timeout(REFRESH_HTTP_TIMEOUT).build()?;
|
||||
let refreshed = refresh_oauth_token(&client, &provider, key, tokens).await?;
|
||||
Ok(refreshed.access_token)
|
||||
}
|
||||
|
||||
fn refresh_lock(server_name: &str) -> Arc<sync::Mutex<()>> {
|
||||
static LOCKS: OnceLock<parking_lot::Mutex<HashMap<String, Arc<sync::Mutex<()>>>>> =
|
||||
OnceLock::new();
|
||||
LOCKS
|
||||
.get_or_init(Default::default)
|
||||
.lock()
|
||||
.entry(server_name.to_string())
|
||||
.or_default()
|
||||
.clone()
|
||||
}
|
||||
|
||||
fn refresh_failures() -> &'static parking_lot::Mutex<HashMap<String, Instant>> {
|
||||
static FAILURES: OnceLock<parking_lot::Mutex<HashMap<String, Instant>>> = OnceLock::new();
|
||||
FAILURES.get_or_init(Default::default)
|
||||
}
|
||||
|
||||
fn note_refresh_failure(server_name: &str) {
|
||||
refresh_failures()
|
||||
.lock()
|
||||
.insert(server_name.to_string(), Instant::now());
|
||||
}
|
||||
|
||||
fn in_refresh_failure_backoff(server_name: &str) -> bool {
|
||||
refresh_failures()
|
||||
.lock()
|
||||
.get(server_name)
|
||||
.is_some_and(|failed_at| failed_at.elapsed() < REFRESH_FAILURE_BACKOFF)
|
||||
}
|
||||
|
||||
/// Refresh errors may embed the token endpoint's JSON response, which can
|
||||
/// contain live tokens; strip everything from the first `{` before logging.
|
||||
fn redact_refresh_error(e: &anyhow::Error) -> String {
|
||||
let msg = e.to_string();
|
||||
match msg.find('{') {
|
||||
Some(idx) => format!("{}<response body redacted>", &msg[..idx]),
|
||||
None => msg,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,7 +374,13 @@ fn load_registration(server_name: &str) -> Option<McpRegistration> {
|
||||
serde_json::from_str(&content).ok()
|
||||
}
|
||||
|
||||
fn save_registration(server_name: &str, client_id: &str, redirect_uri: &str) -> Result<()> {
|
||||
fn save_registration(
|
||||
server_name: &str,
|
||||
client_id: &str,
|
||||
redirect_uri: &str,
|
||||
token_url: &str,
|
||||
resource: &str,
|
||||
) -> Result<()> {
|
||||
let dir = paths::oauth_tokens_dir();
|
||||
fs::create_dir_all(&dir)?;
|
||||
|
||||
@@ -195,6 +388,8 @@ fn save_registration(server_name: &str, client_id: &str, redirect_uri: &str) ->
|
||||
let reg = McpRegistration {
|
||||
client_id: client_id.to_string(),
|
||||
redirect_uri: Some(redirect_uri.to_string()),
|
||||
token_url: Some(token_url.to_string()),
|
||||
resource: Some(resource.to_string()),
|
||||
};
|
||||
|
||||
fs::write(path, serde_json::to_string_pretty(®)?)?;
|
||||
@@ -244,7 +439,12 @@ async fn register_client(endpoint: &str, redirect_uri: &str) -> Result<String> {
|
||||
|
||||
response["client_id"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow!("Missing client_id in registration response: {response}"))
|
||||
.ok_or_else(|| {
|
||||
anyhow!(
|
||||
"Missing client_id in registration response (keys: {})",
|
||||
token_response_keys(&response)
|
||||
)
|
||||
})
|
||||
.map(|s| s.to_string())
|
||||
}
|
||||
|
||||
@@ -421,16 +621,34 @@ fn extract_base_url(url: &str) -> Result<String> {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
pub(crate) mod test_support {
|
||||
use crate::utils::get_env_name;
|
||||
use serial_test::serial;
|
||||
use std::{
|
||||
env, fs,
|
||||
env,
|
||||
ffi::OsString,
|
||||
fs,
|
||||
path::PathBuf,
|
||||
time::{self, SystemTime},
|
||||
};
|
||||
|
||||
fn with_temp_cache<F: FnOnce()>(f: F) {
|
||||
pub(crate) fn with_temp_cache<F: FnOnce()>(f: F) {
|
||||
struct Restore {
|
||||
key: String,
|
||||
prev: Option<OsString>,
|
||||
root: PathBuf,
|
||||
}
|
||||
impl Drop for Restore {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
match self.prev.take() {
|
||||
Some(v) => env::set_var(&self.key, v),
|
||||
None => env::remove_var(&self.key),
|
||||
}
|
||||
}
|
||||
let _ = fs::remove_dir_all(&self.root);
|
||||
}
|
||||
}
|
||||
|
||||
let unique = SystemTime::now()
|
||||
.duration_since(time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
@@ -442,15 +660,21 @@ mod tests {
|
||||
unsafe {
|
||||
env::set_var(&env_key, &root);
|
||||
}
|
||||
let _restore = Restore {
|
||||
key: env_key,
|
||||
prev,
|
||||
root,
|
||||
};
|
||||
f();
|
||||
unsafe {
|
||||
match prev {
|
||||
Some(v) => env::set_var(&env_key, v),
|
||||
None => env::remove_var(&env_key),
|
||||
}
|
||||
}
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::test_support::with_temp_cache;
|
||||
use super::*;
|
||||
use serial_test::serial;
|
||||
use std::fs;
|
||||
|
||||
#[test]
|
||||
fn extract_base_url_strips_path_and_query() {
|
||||
@@ -685,12 +909,19 @@ mod tests {
|
||||
"notion",
|
||||
"client-xyz-123",
|
||||
"http://127.0.0.1:49152/callback",
|
||||
"https://as.example/token",
|
||||
"https://mcp.example/mcp",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let loaded = load_registration("notion");
|
||||
let loaded = load_registration("notion").unwrap();
|
||||
|
||||
assert_eq!(loaded.unwrap().client_id, "client-xyz-123");
|
||||
assert_eq!(loaded.client_id, "client-xyz-123");
|
||||
assert_eq!(
|
||||
loaded.token_url.as_deref(),
|
||||
Some("https://as.example/token")
|
||||
);
|
||||
assert_eq!(loaded.resource.as_deref(), Some("https://mcp.example/mcp"));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -708,8 +939,22 @@ mod tests {
|
||||
#[serial]
|
||||
fn registration_second_save_overwrites_first() {
|
||||
with_temp_cache(|| {
|
||||
save_registration("github", "first-id", "http://127.0.0.1:49152/callback").unwrap();
|
||||
save_registration("github", "second-id", "http://127.0.0.1:49153/callback").unwrap();
|
||||
save_registration(
|
||||
"github",
|
||||
"first-id",
|
||||
"http://127.0.0.1:49152/callback",
|
||||
"https://as.example/token",
|
||||
"https://mcp.example/mcp",
|
||||
)
|
||||
.unwrap();
|
||||
save_registration(
|
||||
"github",
|
||||
"second-id",
|
||||
"http://127.0.0.1:49153/callback",
|
||||
"https://as.example/token",
|
||||
"https://mcp.example/mcp",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let loaded = load_registration("github").unwrap();
|
||||
|
||||
@@ -737,6 +982,8 @@ mod tests {
|
||||
|
||||
assert_eq!(loaded.client_id, "legacy-id");
|
||||
assert_eq!(loaded.redirect_uri, None);
|
||||
assert_eq!(loaded.token_url, None);
|
||||
assert_eq!(loaded.resource, None);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -744,7 +991,14 @@ mod tests {
|
||||
#[serial]
|
||||
fn save_registration_persists_redirect_uri() {
|
||||
with_temp_cache(|| {
|
||||
save_registration("aws", "client-abc", "http://127.0.0.1:49152/callback").unwrap();
|
||||
save_registration(
|
||||
"aws",
|
||||
"client-abc",
|
||||
"http://127.0.0.1:49152/callback",
|
||||
"https://as.example/token",
|
||||
"https://mcp.example/mcp",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let loaded = load_registration("aws").unwrap();
|
||||
|
||||
@@ -756,6 +1010,251 @@ mod tests {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_registration_deserializes_without_new_fields_and_roundtrips() {
|
||||
let old: McpRegistration = serde_json::from_str(r#"{"client_id":"legacy-id"}"#).unwrap();
|
||||
|
||||
assert_eq!(old.client_id, "legacy-id");
|
||||
assert_eq!(old.token_url, None);
|
||||
assert_eq!(old.resource, None);
|
||||
|
||||
let full = McpRegistration {
|
||||
client_id: "client-abc".into(),
|
||||
redirect_uri: Some("http://127.0.0.1:49152/callback".into()),
|
||||
token_url: Some("https://as.example/token".into()),
|
||||
resource: Some("https://mcp.example/mcp".into()),
|
||||
};
|
||||
let json = serde_json::to_string(&full).unwrap();
|
||||
let back: McpRegistration = serde_json::from_str(&json).unwrap();
|
||||
|
||||
assert_eq!(back.token_url.as_deref(), Some("https://as.example/token"));
|
||||
assert_eq!(back.resource.as_deref(), Some("https://mcp.example/mcp"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn expired_token_with_old_format_registration_reports_refresh_failed() {
|
||||
with_temp_cache(|| {
|
||||
let dir = paths::oauth_tokens_dir();
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::write(
|
||||
paths::token_file("mcp_legacyref"),
|
||||
r#"{"access_token":"stale","refresh_token":"refresh-abc","expires_at":0}"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
dir.join("mcp_legacyref_registration.json"),
|
||||
r#"{"client_id":"legacy-id"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let status = rt.block_on(load_or_refresh_mcp_token("legacyref"));
|
||||
|
||||
assert_eq!(status, McpTokenStatus::RefreshFailed);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn missing_token_file_reports_not_authenticated() {
|
||||
with_temp_cache(|| {
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let status = rt.block_on(load_or_refresh_mcp_token("never-authed"));
|
||||
|
||||
assert_eq!(status, McpTokenStatus::NotAuthenticated);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn force_refresh_returns_concurrently_refreshed_token() {
|
||||
with_temp_cache(|| {
|
||||
fs::create_dir_all(paths::oauth_tokens_dir()).unwrap();
|
||||
fs::write(
|
||||
paths::token_file("mcp_force-fresh"),
|
||||
r#"{"access_token":"fresh-tok","refresh_token":"r","expires_at":9999999999}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let token = rt.block_on(force_refresh_mcp_token("force-fresh", "rejected-tok"));
|
||||
|
||||
assert_eq!(token.as_deref(), Some("fresh-tok"));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn force_refresh_unexpired_rejected_token_attempts_real_refresh() {
|
||||
with_temp_cache(|| {
|
||||
fs::create_dir_all(paths::oauth_tokens_dir()).unwrap();
|
||||
fs::write(
|
||||
paths::token_file("mcp_force-rejected"),
|
||||
r#"{"access_token":"same-tok","refresh_token":"r","expires_at":9999999999}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let token = rt.block_on(force_refresh_mcp_token("force-rejected", "same-tok"));
|
||||
|
||||
assert_eq!(token, None);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn force_refresh_missing_token_file_returns_none() {
|
||||
with_temp_cache(|| {
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let token = rt.block_on(force_refresh_mcp_token(
|
||||
"force-never-authed",
|
||||
"rejected-tok",
|
||||
));
|
||||
|
||||
assert_eq!(token, None);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn force_refresh_failed_refresh_returns_none() {
|
||||
with_temp_cache(|| {
|
||||
fs::create_dir_all(paths::oauth_tokens_dir()).unwrap();
|
||||
fs::write(
|
||||
paths::token_file("mcp_force-fail"),
|
||||
r#"{"access_token":"stale","refresh_token":"r","expires_at":0}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let token = rt.block_on(force_refresh_mcp_token("force-fail", "stale"));
|
||||
|
||||
assert_eq!(token, None);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn force_refresh_concurrent_callers_complete_without_deadlock() {
|
||||
with_temp_cache(|| {
|
||||
fs::create_dir_all(paths::oauth_tokens_dir()).unwrap();
|
||||
fs::write(
|
||||
paths::token_file("mcp_force-concurrent"),
|
||||
r#"{"access_token":"same-tok","refresh_token":"r","expires_at":9999999999}"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let (a, b) = rt.block_on(async {
|
||||
tokio::join!(
|
||||
force_refresh_mcp_token("force-concurrent", "same-tok"),
|
||||
force_refresh_mcp_token("force-concurrent", "same-tok"),
|
||||
)
|
||||
});
|
||||
|
||||
assert_eq!(a, None);
|
||||
assert_eq!(b, None);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn force_refresh_respects_failure_backoff() {
|
||||
with_temp_cache(|| {
|
||||
fs::create_dir_all(paths::oauth_tokens_dir()).unwrap();
|
||||
fs::write(
|
||||
paths::token_file("mcp_force-backoff"),
|
||||
r#"{"access_token":"same-tok","refresh_token":"r","expires_at":9999999999}"#,
|
||||
)
|
||||
.unwrap();
|
||||
note_refresh_failure("force-backoff");
|
||||
|
||||
let rt = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
let token = rt.block_on(force_refresh_mcp_token("force-backoff", "same-tok"));
|
||||
|
||||
assert_eq!(token, None);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_status_debug_redacts_token() {
|
||||
assert_eq!(
|
||||
format!("{:?}", McpTokenStatus::Token("live-secret".into())),
|
||||
"Token(<redacted>)"
|
||||
);
|
||||
assert_eq!(
|
||||
format!("{:?}", McpTokenStatus::NotAuthenticated),
|
||||
"NotAuthenticated"
|
||||
);
|
||||
assert_eq!(
|
||||
format!("{:?}", McpTokenStatus::RefreshFailed),
|
||||
"RefreshFailed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_status_into_token_extracts_only_token_variant() {
|
||||
assert_eq!(
|
||||
McpTokenStatus::Token("tok".into()).into_token(),
|
||||
Some("tok".to_string())
|
||||
);
|
||||
assert_eq!(McpTokenStatus::NotAuthenticated.into_token(), None);
|
||||
assert_eq!(McpTokenStatus::RefreshFailed.into_token(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refresh_failure_backoff_memoizes_per_server() {
|
||||
assert!(!in_refresh_failure_backoff("backoff-test-server"));
|
||||
|
||||
note_refresh_failure("backoff-test-server");
|
||||
|
||||
assert!(in_refresh_failure_backoff("backoff-test-server"));
|
||||
assert!(!in_refresh_failure_backoff("backoff-other-server"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redact_refresh_error_strips_response_body() {
|
||||
let with_body = anyhow!(
|
||||
"Missing access_token in refresh response: {}",
|
||||
r#"{"access_token":"live-secret"}"#
|
||||
);
|
||||
let without_body = anyhow!("no refresh token stored");
|
||||
|
||||
assert_eq!(
|
||||
redact_refresh_error(&with_body),
|
||||
"Missing access_token in refresh response: <response body redacted>"
|
||||
);
|
||||
assert_eq!(
|
||||
redact_refresh_error(&without_body),
|
||||
"no refresh token stored"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_redirect_port_matches() {
|
||||
let port = cached_redirect_port("http://127.0.0.1:49152/callback", "127.0.0.1", None);
|
||||
|
||||
+68
-3
@@ -1,11 +1,11 @@
|
||||
use crate::function::{FunctionDeclaration, JsonSchema};
|
||||
use crate::function::{self, FunctionDeclaration, JsonSchema};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use argc::{ChoiceValue, CommandValue, FlagOptionValue};
|
||||
use indexmap::IndexMap;
|
||||
use std::env;
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::{env, fs};
|
||||
|
||||
pub fn generate_bash_declarations(
|
||||
mut tool_file: File,
|
||||
@@ -23,7 +23,8 @@ pub fn generate_bash_declarations(
|
||||
"",
|
||||
env::var("TERM_WIDTH").ok().and_then(|v| v.parse().ok()),
|
||||
)?;
|
||||
fs::write(tools_file_path, &build_script)
|
||||
let build_script = allow_empty_required_values(&build_script);
|
||||
function::write_file_atomic(tools_file_path, &build_script, Some(0o755))
|
||||
.with_context(|| format!("Failed to write built script to '{tools_file_path:?}'"))?;
|
||||
|
||||
let command_value = argc::export(&build_script, file_name)
|
||||
@@ -74,6 +75,20 @@ fn underscore(s: &str) -> String {
|
||||
s.replace('-', "_")
|
||||
}
|
||||
|
||||
/// argc's generated required-param check uses `-z "${!name:-}"`, which
|
||||
/// conflates "not provided" with "provided but empty", so a required option
|
||||
/// passed an explicit empty string (e.g. `fs_write --content=''` to create an
|
||||
/// empty file) is rejected as "required arguments were not provided". The
|
||||
/// JSON schema we advertise to models treats `required` as *presence*, so
|
||||
/// rewrite the check to a set-ness test to keep runtime behavior consistent
|
||||
/// with the schema. Applied post-build so it survives every regeneration.
|
||||
fn allow_empty_required_values(build_script: &str) -> String {
|
||||
build_script.replace(
|
||||
r#"if [[ -z "${!name:-}" ]]; then"#,
|
||||
r#"if [[ -z "${!name+x}" ]]; then"#,
|
||||
)
|
||||
}
|
||||
|
||||
fn schema_ty(t: &str) -> JsonSchema {
|
||||
JsonSchema {
|
||||
type_value: Some(t.to_string()),
|
||||
@@ -147,3 +162,53 @@ fn parse_parameters_schema(flags: &[FlagOptionValue]) -> JsonSchema {
|
||||
required: Some(required),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rewrites_argc_required_check_to_setness_test() {
|
||||
let src = "# @describe test tool\n# @option --content! The content\nmain() { :; }\n";
|
||||
let built = argc::build(src, "", None).expect("argc build failed");
|
||||
assert!(
|
||||
built.contains(r#"if [[ -z "${!name:-}" ]]; then"#),
|
||||
"argc changed its generated required-param template; update allow_empty_required_values()"
|
||||
);
|
||||
|
||||
let fixed = allow_empty_required_values(&built);
|
||||
|
||||
assert!(fixed.contains(r#"if [[ -z "${!name+x}" ]]; then"#));
|
||||
assert!(!fixed.contains(r#"if [[ -z "${!name:-}" ]]; then"#));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn second_build_does_not_rewrite_tool_file_test() {
|
||||
use std::fs;
|
||||
use std::os::unix::fs::{MetadataExt, PermissionsExt};
|
||||
|
||||
let src = "# @describe test tool\n# @option --content! The content\nmain() { :; }\n";
|
||||
let path = crate::utils::temp_file("bash-build", ".sh");
|
||||
fs::write(&path, src).expect("failed to write temp script");
|
||||
|
||||
let declarations = generate_bash_declarations(File::open(&path).unwrap(), &path, "test")
|
||||
.expect("first build failed");
|
||||
assert!(!declarations.is_empty());
|
||||
let first_ino = fs::metadata(&path).unwrap().ino();
|
||||
|
||||
let declarations = generate_bash_declarations(File::open(&path).unwrap(), &path, "test")
|
||||
.expect("second build failed");
|
||||
assert!(!declarations.is_empty());
|
||||
|
||||
let metadata = fs::metadata(&path).unwrap();
|
||||
assert_eq!(
|
||||
metadata.ino(),
|
||||
first_ino,
|
||||
"second build rewrote an already-built tool file"
|
||||
);
|
||||
assert_eq!(metadata.permissions().mode() & 0o777, 0o755);
|
||||
|
||||
fs::remove_file(&path).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
+109
-70
@@ -151,7 +151,7 @@ impl Rag {
|
||||
println!("⚙ Initializing RAG...");
|
||||
let mut data = Self::resolve_init_data(app, config)?;
|
||||
data.driver = config.driver.clone().unwrap_or_else(|| "yaml".to_string());
|
||||
let mut rag = Self::create(app, name, save_path, data)?;
|
||||
let mut rag = Self::create(app, name, save_path, data).await?;
|
||||
let loaders = app.document_loaders.clone();
|
||||
let (spinner, spinner_rx) = Spinner::create("");
|
||||
abortable_run_with_spinner_rx(
|
||||
@@ -267,31 +267,10 @@ impl Rag {
|
||||
}
|
||||
println!("⚙ Initializing RAG...");
|
||||
let (embedding_model, chunk_size, chunk_overlap) = Self::create_config(app)?;
|
||||
// Only interactive named-RAG creation offers a driver choice. Temp RAGs and
|
||||
// agent startup pass `false`; an explicit flag is used rather than inferring
|
||||
// from the name because the agent path passes the literal name "rag", which is
|
||||
// indistinguishable from a user creating a RAG genuinely named `rag`.
|
||||
let driver = if prompt_for_driver {
|
||||
let options = vec![
|
||||
"yaml — portable, in-memory HNSW; usable from several Coyote processes at once (default)",
|
||||
"duckdb — persistent on-disk store; vectors and content survive restarts; HNSW approximate search.",
|
||||
];
|
||||
let sel = Select::new("RAG storage driver:", options)
|
||||
.with_starting_cursor(0)
|
||||
.prompt()?;
|
||||
if sel.starts_with("duckdb") {
|
||||
println!(
|
||||
"Note: several Coyote processes can query a duckdb RAG at the same time, \
|
||||
but while one process is ingesting or rebuilding it the others cannot \
|
||||
read it until that finishes. Changing its driver later means deleting \
|
||||
and recreating the RAG."
|
||||
);
|
||||
"duckdb"
|
||||
select_rag_driver()?
|
||||
} else {
|
||||
"yaml"
|
||||
}
|
||||
} else {
|
||||
"yaml"
|
||||
"yaml".to_string()
|
||||
};
|
||||
let reranker_model = app.rag_reranker_model.clone();
|
||||
let top_k = app.rag_top_k;
|
||||
@@ -318,8 +297,8 @@ impl Rag {
|
||||
graph_hops: Some(graph_hops),
|
||||
},
|
||||
);
|
||||
data.driver = driver.to_string();
|
||||
let mut rag = Self::create(app, name, save_path, data)?;
|
||||
data.driver = driver;
|
||||
let mut rag = Self::create(app, name, save_path, data).await?;
|
||||
let mut paths = doc_paths.to_vec();
|
||||
if paths.is_empty() {
|
||||
paths = add_documents()?;
|
||||
@@ -338,12 +317,12 @@ impl Rag {
|
||||
Ok(rag)
|
||||
}
|
||||
|
||||
pub fn load(app: &AppConfig, name: &str, path: &Path) -> Result<Self> {
|
||||
pub async fn load(app: &AppConfig, name: &str, path: &Path) -> Result<Self> {
|
||||
let err = || format!("Failed to load rag '{name}' at '{}'", path.display());
|
||||
let content = fs::read_to_string(path).with_context(err)?;
|
||||
let data: RagData = serde_yaml::from_str(&content).with_context(err)?;
|
||||
data.validate().with_context(err)?;
|
||||
Self::create(app, name, path, data)
|
||||
Self::create(app, name, path, data).await
|
||||
}
|
||||
|
||||
/// Loads a RAG from a YAML file. External drivers need an async constructor
|
||||
@@ -393,7 +372,7 @@ impl Rag {
|
||||
last_sources: RwLock::new(None),
|
||||
})
|
||||
}
|
||||
_ => Self::load(app, name, path),
|
||||
_ => Self::load(app, name, path).await,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -558,14 +537,22 @@ impl Rag {
|
||||
Ok(rag)
|
||||
}
|
||||
|
||||
pub fn create(app: &AppConfig, name: &str, path: &Path, mut data: RagData) -> Result<Self> {
|
||||
pub async fn create(
|
||||
app: &AppConfig,
|
||||
name: &str,
|
||||
path: &Path,
|
||||
mut data: RagData,
|
||||
) -> Result<Self> {
|
||||
// Deliberately does NOT call rebuild_indexes: both callers construct the Rag
|
||||
// before any documents are added, so rebuilding empty data would be a no-op.
|
||||
// Actual population happens later via sync_documents.
|
||||
let (provider, bm25): (Box<dyn RagProvider>, _) = match data.driver.as_str() {
|
||||
"duckdb" => {
|
||||
let db_path = providers::duckdb_path_from_yaml(path);
|
||||
let dim = embedding_dim_for_model(&data.embedding_model);
|
||||
let dim = match DuckDbProvider::introspect_dim(&db_path)? {
|
||||
Some(existing) => existing,
|
||||
None => probe_embedding_dim(app, &data.embedding_model).await?,
|
||||
};
|
||||
let duck = DuckDbProvider::open(&db_path, dim)?;
|
||||
// HYDRATE — mandatory, not an optimization. The YAML file for a duckdb
|
||||
// RAG deliberately omits `vectors`, so `data.vectors` arrives empty from
|
||||
@@ -586,19 +573,40 @@ impl Rag {
|
||||
if data.vectors.is_empty() {
|
||||
data.vectors = duck.read_all_vectors()?;
|
||||
}
|
||||
if data.vectors.is_empty() && !data.files.is_empty() {
|
||||
println!(
|
||||
"{} RAG '{name}' lists {} indexed file(s), but its vector store \
|
||||
'{}' holds no vectors, so every search will return nothing. A \
|
||||
duckdb RAG is two files: bring the .duckdb sidecar along with \
|
||||
the .yaml, or re-embed with `.rebuild rag`.",
|
||||
warning_text("WARNING:"),
|
||||
data.files.len(),
|
||||
db_path.display()
|
||||
);
|
||||
}
|
||||
// data.files is always populated for duckdb, so build_bm25() is the only
|
||||
// path; there is no from-DuckDB fallback.
|
||||
let bm25 = data.build_bm25();
|
||||
(Box::new(duck), bm25)
|
||||
}
|
||||
"qdrant" => bail!(
|
||||
"Qdrant RAGs cannot be constructed via Rag::create(); \
|
||||
use Rag::attach() or Rag::load_async() instead"
|
||||
"RAG '{name}' uses driver 'qdrant' without `attached: true`. \
|
||||
Coyote can currently only READ a pre-existing Qdrant \
|
||||
collection — attach one with `.rag attach`. Writing to a \
|
||||
Coyote-owned Qdrant collection is not supported yet."
|
||||
),
|
||||
_ => {
|
||||
"yaml" => {
|
||||
let bm25 = data.build_bm25();
|
||||
(Box::new(YamlProvider::from_data(&data)), bm25)
|
||||
}
|
||||
// Explicitly NOT a catch-all falling through to yaml. A typo'd driver
|
||||
// used to build a yaml store, pay to embed the whole corpus, persist
|
||||
// the bad driver, and only fail on the NEXT run, leaving the RAG
|
||||
// unusable without hand-editing the YAML.
|
||||
other => bail!(
|
||||
"Unknown RAG driver '{other}' for RAG '{name}'. \
|
||||
Valid drivers: yaml, duckdb, qdrant."
|
||||
),
|
||||
};
|
||||
let node_to_docs = data.knowledge_graph.build_node_to_docs();
|
||||
let embedding_model =
|
||||
@@ -856,6 +864,20 @@ impl Rag {
|
||||
Ok((embeddings, sources, ids))
|
||||
}
|
||||
|
||||
pub async fn search_chunks(
|
||||
&self,
|
||||
text: &str,
|
||||
top_k: usize,
|
||||
rerank_model: Option<&str>,
|
||||
) -> Result<Vec<(String, String)>> {
|
||||
let results = self.hybrid_search(text, top_k, rerank_model).await?;
|
||||
|
||||
Ok(results
|
||||
.into_iter()
|
||||
.map(|(id, content)| (content, self.resolve_source(&id)))
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub async fn search_with_template(
|
||||
&self,
|
||||
app: &AppConfig,
|
||||
@@ -1169,12 +1191,7 @@ impl Rag {
|
||||
top_k: usize,
|
||||
rerank_model: Option<&str>,
|
||||
) -> Result<Vec<(DocumentId, String)>> {
|
||||
let vector_search_results = self.vector_search(query, top_k, 0.0).await?;
|
||||
debug!("vector_search_results: {vector_search_results:?}",);
|
||||
let vector_search_ids: Vec<DocumentId> =
|
||||
vector_search_results.into_iter().map(|(v, _)| v).collect();
|
||||
|
||||
let keyword_search_results: Vec<(DocumentId, f32)> =
|
||||
let keyword_leg = async {
|
||||
if self.provider.has_native_keyword_search() {
|
||||
self.provider
|
||||
.keyword_search(query, top_k)
|
||||
@@ -1185,7 +1202,16 @@ impl Rag {
|
||||
})
|
||||
} else {
|
||||
self.keyword_search(query, top_k, 0.0)
|
||||
}
|
||||
};
|
||||
let (vector_search_results, keyword_search_results) =
|
||||
tokio::join!(self.vector_search(query, top_k, 0.0), keyword_leg);
|
||||
|
||||
let vector_search_results = vector_search_results?;
|
||||
debug!("vector_search_results: {vector_search_results:?}",);
|
||||
let vector_search_ids: Vec<DocumentId> =
|
||||
vector_search_results.into_iter().map(|(v, _)| v).collect();
|
||||
|
||||
debug!("keyword_search_results: {keyword_search_results:?}",);
|
||||
let keyword_search_ids: Vec<DocumentId> =
|
||||
keyword_search_results.into_iter().map(|(v, _)| v).collect();
|
||||
@@ -1842,6 +1868,27 @@ fn select_embedding_model(models: &[&Model]) -> Result<String> {
|
||||
Ok(result.value)
|
||||
}
|
||||
|
||||
pub(crate) fn select_rag_driver() -> Result<String> {
|
||||
let options = vec![
|
||||
"yaml — portable, in-memory HNSW; usable from several Coyote processes at once (default)",
|
||||
"duckdb — persistent on-disk store; vectors and content survive restarts; HNSW approximate search.",
|
||||
];
|
||||
let sel = Select::new("RAG storage driver:", options)
|
||||
.with_starting_cursor(0)
|
||||
.prompt()?;
|
||||
if sel.starts_with("duckdb") {
|
||||
println!(
|
||||
"Note: several Coyote processes can query a duckdb RAG at the same time, \
|
||||
but while one process is ingesting or rebuilding it the others cannot \
|
||||
read it until that finishes. Changing its driver later means deleting \
|
||||
and recreating the RAG."
|
||||
);
|
||||
Ok("duckdb".to_string())
|
||||
} else {
|
||||
Ok("yaml".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
const EXTRACTOR_SKIP: &str = "Skip";
|
||||
|
||||
fn select_extractor_model(app: &AppConfig) -> Result<Option<String>> {
|
||||
@@ -2080,21 +2127,25 @@ fn reciprocal_rank_fusion(
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Map an embedding model id to its vector dimension.
|
||||
///
|
||||
/// The DuckDB `FLOAT[N]` column type and its HNSW index are fixed at schema-creation
|
||||
/// time, so this value must be decided before the first insert. An unrecognized model
|
||||
/// falls back to 1536; if that is wrong, DuckDB raises a dimension-mismatch error on
|
||||
/// the first insert rather than silently corrupting the schema, and the recovery is to
|
||||
/// delete the sidecar and re-ingest from source.
|
||||
fn embedding_dim_for_model(model_id: &str) -> usize {
|
||||
match model_id {
|
||||
m if m.contains("3-large") => 3072,
|
||||
m if m.contains("3-small") || m.contains("ada-002") => 1536,
|
||||
m if m.contains("nomic-embed-text") || m.contains("all-minilm") => 768,
|
||||
m if m.contains("jina-embeddings-v2") => 1024,
|
||||
_ => 1536,
|
||||
async fn probe_embedding_dim(app: &AppConfig, model_id: &str) -> Result<usize> {
|
||||
let model = Model::retrieve_model(app, model_id, ModelType::Embedding)?;
|
||||
let client = init_client(&Arc::new(app.clone()), model)?;
|
||||
let out = client
|
||||
.embeddings(&EmbeddingsData::new(vec!["dimension probe".into()], false))
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to probe the embedding dimension of model '{model_id}'. \
|
||||
Creating a duckdb RAG requires one call to the embedding endpoint."
|
||||
)
|
||||
})?;
|
||||
let dim = out.first().map(|v| v.len()).unwrap_or(0);
|
||||
|
||||
if dim == 0 {
|
||||
bail!("Embedding model '{model_id}' returned an empty vector during the dimension probe");
|
||||
}
|
||||
|
||||
Ok(dim)
|
||||
}
|
||||
|
||||
/// True only for "the vault does not hold this key".
|
||||
@@ -2634,18 +2685,6 @@ mod tests {
|
||||
assert_eq!(data.attached_source_label(), "[external collection]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embedding_dim_for_model_maps_known_models() {
|
||||
assert_eq!(embedding_dim_for_model("text-embedding-3-large"), 3072);
|
||||
assert_eq!(embedding_dim_for_model("text-embedding-3-small"), 1536);
|
||||
assert_eq!(embedding_dim_for_model("text-embedding-ada-002"), 1536);
|
||||
assert_eq!(embedding_dim_for_model("nomic-embed-text"), 768);
|
||||
assert_eq!(embedding_dim_for_model("all-minilm"), 768);
|
||||
assert_eq!(embedding_dim_for_model("jina-embeddings-v2-base-en"), 1024);
|
||||
// Unknown models fall back to the OpenAI-compatible default.
|
||||
assert_eq!(embedding_dim_for_model("some-unknown-model"), 1536);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_id_round_trip() {
|
||||
let id = DocumentId::new(5, 17);
|
||||
@@ -3005,7 +3044,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn reciprocal_rank_fusion_empty_lists() {
|
||||
let result = super::reciprocal_rank_fusion(vec![], vec![], 5);
|
||||
let result = reciprocal_rank_fusion(vec![], vec![], 5);
|
||||
assert!(result.is_empty(), "empty input should produce empty output");
|
||||
}
|
||||
|
||||
@@ -3013,7 +3052,7 @@ mod tests {
|
||||
fn reciprocal_rank_fusion_deduplicates_across_signals() {
|
||||
let doc_a = DocumentId::new(0, 0);
|
||||
let doc_b = DocumentId::new(0, 1);
|
||||
let result = super::reciprocal_rank_fusion(
|
||||
let result = reciprocal_rank_fusion(
|
||||
vec![vec![doc_a, doc_b], vec![doc_a, doc_b]],
|
||||
vec![1.0, 1.0],
|
||||
5,
|
||||
@@ -3030,7 +3069,7 @@ mod tests {
|
||||
#[test]
|
||||
fn reciprocal_rank_fusion_respects_top_k() {
|
||||
let docs: Vec<DocumentId> = (0..10).map(|i| DocumentId::new(0, i)).collect();
|
||||
let result = super::reciprocal_rank_fusion(vec![docs], vec![1.0], 3);
|
||||
let result = reciprocal_rank_fusion(vec![docs], vec![1.0], 3);
|
||||
assert_eq!(result.len(), 3, "result should be capped at top_k=3");
|
||||
}
|
||||
|
||||
@@ -3038,7 +3077,7 @@ mod tests {
|
||||
fn reciprocal_rank_fusion_weights_affect_ranking() {
|
||||
let doc_a = DocumentId::new(0, 0);
|
||||
let doc_b = DocumentId::new(0, 1);
|
||||
let result = super::reciprocal_rank_fusion(
|
||||
let result = reciprocal_rank_fusion(
|
||||
vec![vec![doc_a, doc_b], vec![doc_b, doc_a]],
|
||||
vec![10.0, 1.0],
|
||||
2,
|
||||
|
||||
+211
-9
@@ -5,7 +5,7 @@ use std::collections::HashMap;
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use async_trait::async_trait;
|
||||
use duckdb::types::Value;
|
||||
use duckdb::{AccessMode, Config, Connection};
|
||||
use duckdb::{AccessMode, Config, Connection, OptionalExt};
|
||||
use indexmap::IndexMap;
|
||||
use log::warn;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -30,6 +30,11 @@ pub(crate) fn duckdb_path_from_yaml(yaml_path: &Path) -> PathBuf {
|
||||
yaml_path.with_extension("duckdb")
|
||||
}
|
||||
|
||||
fn parse_float_array_dim(data_type: &str) -> Option<usize> {
|
||||
let inner = data_type.strip_prefix("FLOAT[")?.strip_suffix(']')?;
|
||||
inner.parse::<usize>().ok().filter(|&n| n > 0)
|
||||
}
|
||||
|
||||
/// The shared connection together with the access mode it was opened with.
|
||||
///
|
||||
/// `conn` is an `Option` only so that an upgrade can DROP the read-only connection
|
||||
@@ -42,6 +47,11 @@ struct ConnHandle {
|
||||
/// `duplicate()` clone sharing the `Arc` observes an upgrade performed through any
|
||||
/// other handle instead of keeping its own stale copy of the mode.
|
||||
writable: bool,
|
||||
/// Embedding dimension the `FLOAT[N]` column was opened (or last rebuilt) with.
|
||||
/// Shared for the same reason as `writable`: a self-healing rebuild through one
|
||||
/// handle updates the width, and every `duplicate()` clone must cast with the new
|
||||
/// width instead of erroring on a healthy store with its stale copy.
|
||||
dim: usize,
|
||||
}
|
||||
|
||||
impl ConnHandle {
|
||||
@@ -68,8 +78,6 @@ impl ConnHandle {
|
||||
pub struct DuckDbProvider {
|
||||
path: PathBuf,
|
||||
conn: Arc<Mutex<ConnHandle>>,
|
||||
/// Embedding dimension; fixed at open time because the `FLOAT[N]` column depends on it.
|
||||
dim: usize,
|
||||
/// True once an FTS index has been built on `documents`. Until then
|
||||
/// `fts_main_documents.match_bm25` does not exist and any keyword query would
|
||||
/// fail with a DuckDB catalog error. Backs `has_native_keyword_search`.
|
||||
@@ -96,8 +104,8 @@ impl DuckDbProvider {
|
||||
conn: Arc::new(Mutex::new(ConnHandle {
|
||||
conn: Some(conn),
|
||||
writable,
|
||||
})),
|
||||
dim,
|
||||
})),
|
||||
fts_ready: AtomicBool::new(fts_exists),
|
||||
})
|
||||
}
|
||||
@@ -164,6 +172,35 @@ impl DuckDbProvider {
|
||||
Ok(conn)
|
||||
}
|
||||
|
||||
pub fn introspect_dim(db_path: &Path) -> Result<Option<usize>> {
|
||||
if !db_path.exists() {
|
||||
return Ok(None);
|
||||
}
|
||||
let conn = Self::open_read_only(db_path).with_context(|| {
|
||||
format!(
|
||||
"Cannot inspect the existing RAG store at '{}'",
|
||||
db_path.display()
|
||||
)
|
||||
})?;
|
||||
let ty: Option<String> = conn
|
||||
.query_row(
|
||||
"SELECT data_type FROM duckdb_columns() \
|
||||
WHERE table_name = 'vectors' AND column_name = 'embedding'",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"Failed to introspect the embedding dimension of the DuckDB store \
|
||||
at '{}'",
|
||||
db_path.display()
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(ty.and_then(|t| parse_float_array_dim(&t)))
|
||||
}
|
||||
|
||||
/// Open the store read-write and make sure its schema exists. Exactly one process
|
||||
/// may hold such a handle, and no reader from another process may hold it meanwhile.
|
||||
fn open_read_write(db_path: &Path, dim: usize) -> Result<Connection> {
|
||||
@@ -245,7 +282,7 @@ impl DuckDbProvider {
|
||||
return Ok(());
|
||||
}
|
||||
drop(handle.conn.take());
|
||||
match Self::open_read_write(&self.path, self.dim) {
|
||||
match Self::open_read_write(&self.path, handle.dim) {
|
||||
Ok(conn) => {
|
||||
handle.conn = Some(conn);
|
||||
handle.writable = true;
|
||||
@@ -428,13 +465,33 @@ impl RagProvider for DuckDbProvider {
|
||||
if embedding.iter().any(|f| !f.is_finite()) {
|
||||
bail!("Query embedding contains a non-finite value (NaN or infinity)");
|
||||
}
|
||||
let handle = self.lock_conn()?;
|
||||
let dim = handle.dim;
|
||||
if embedding.len() != dim {
|
||||
let rows: i64 = handle
|
||||
.conn()?
|
||||
.query_row("SELECT count(*) FROM vectors", [], |r| r.get(0))
|
||||
.context("Failed to count vectors before a dimension-mismatch query")?;
|
||||
if rows == 0 {
|
||||
// A never-synced store answers "nothing", not a cast error.
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
bail!(
|
||||
"RAG store at '{}' was built with {dim}-dim embeddings, but the \
|
||||
embedding model now returns {}-dim vectors. The embedding model \
|
||||
changed since ingestion. Re-embed the documents, or delete the \
|
||||
sidecar file and re-ingest.",
|
||||
self.path.display(),
|
||||
embedding.len()
|
||||
);
|
||||
}
|
||||
|
||||
let vals: String = embedding
|
||||
.iter()
|
||||
.map(|f| f.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let dim = self.dim;
|
||||
let handle = self.lock_conn()?;
|
||||
// array_cosine_distance requires a FLOAT[N] ARRAY, not the LIST type FLOAT[].
|
||||
// ORDER BY distance ASC is required for the planner to use hnsw_idx; the
|
||||
// similarity form (DESC) does NOT trigger the ANN index. Distance is converted
|
||||
@@ -554,7 +611,28 @@ impl RagProvider for DuckDbProvider {
|
||||
);
|
||||
}
|
||||
}
|
||||
let dim = self.dim;
|
||||
let dim = match data.vectors.first() {
|
||||
None => self.lock_conn()?.dim,
|
||||
Some((_, first)) => {
|
||||
let dim = first.len();
|
||||
if let Some((doc_id, other)) = data.vectors.iter().find(|(_, e)| e.len() != dim) {
|
||||
let matching = data.vectors.values().filter(|e| e.len() == dim).count();
|
||||
|
||||
bail!(
|
||||
"Refusing to rebuild the RAG store at '{}': the rebuild batch \
|
||||
mixes {dim}-dim and {}-dim vectors ({matching} vs {} vectors; \
|
||||
first mismatch: document {}). Re-embed the documents, or \
|
||||
delete the sidecar file and re-ingest.",
|
||||
self.path.display(),
|
||||
other.len(),
|
||||
data.vectors.len() - matching,
|
||||
doc_id.0
|
||||
);
|
||||
}
|
||||
|
||||
dim
|
||||
}
|
||||
};
|
||||
// THE write path. Everything above this line only reads, so the upgrade happens
|
||||
// here, after both guards have had their say: a rebuild that is going to be
|
||||
// refused must not first take the exclusive lock away from other processes.
|
||||
@@ -664,6 +742,8 @@ impl RagProvider for DuckDbProvider {
|
||||
// fall back to local BM25, which is also empty, and therefore correct.
|
||||
self.fts_ready.store(doc_count > 0, Ordering::Relaxed);
|
||||
|
||||
handle.dim = dim;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -729,10 +809,11 @@ impl RagProvider for DuckDbProvider {
|
||||
// Sharing the Arc also shares the ACCESS MODE, which lives inside the ConnHandle
|
||||
// rather than beside it: when one handle upgrades itself to read-write, every
|
||||
// clone is upgraded with it and none is left holding a stale "read-only" belief.
|
||||
// The embedding dimension lives there too, so a self-healing rebuild through
|
||||
// one handle updates the width every clone casts with.
|
||||
Box::new(DuckDbProvider {
|
||||
path: self.path.clone(),
|
||||
conn: Arc::clone(&self.conn),
|
||||
dim: self.dim,
|
||||
fts_ready: AtomicBool::new(self.fts_ready.load(Ordering::Relaxed)),
|
||||
})
|
||||
}
|
||||
@@ -1074,6 +1155,127 @@ mod tests {
|
||||
.expect("a fresh RAG with nothing indexed must rebuild cleanly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_float_array_dim_handles_arrays_lists_and_scalars() {
|
||||
assert_eq!(parse_float_array_dim("FLOAT[768]"), Some(768));
|
||||
assert_eq!(parse_float_array_dim("FLOAT[]"), None);
|
||||
assert_eq!(parse_float_array_dim("VARCHAR"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn introspect_dim_round_trips_the_open_dim() {
|
||||
let db = TempDb::new("introspect");
|
||||
|
||||
assert_eq!(
|
||||
DuckDbProvider::introspect_dim(&db.path).unwrap(),
|
||||
None,
|
||||
"a file that does not exist has no dim"
|
||||
);
|
||||
{
|
||||
let _provider = DuckDbProvider::open(&db.path, 5).unwrap();
|
||||
}
|
||||
assert_eq!(DuckDbProvider::introspect_dim(&db.path).unwrap(), Some(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn introspect_dim_propagates_an_unopenable_existing_file() {
|
||||
let db = TempDb::new("introspectgarbage");
|
||||
fs::write(&db.path, b"not a duckdb database").unwrap();
|
||||
|
||||
let err = DuckDbProvider::introspect_dim(&db.path).unwrap_err();
|
||||
|
||||
assert!(
|
||||
format!("{err:#}").contains(&format!(
|
||||
"Cannot inspect the existing RAG store at '{}'",
|
||||
db.path.display()
|
||||
)),
|
||||
"an existing-but-unopenable file must be an error naming the path; got: {err:#}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rebuild_indexes_self_heals_dim_from_the_vectors_it_writes() {
|
||||
let db = TempDb::new("selfheal");
|
||||
let mut provider = DuckDbProvider::open(&db.path, 5).unwrap();
|
||||
let mut data = minimal_rag_data();
|
||||
data.vectors.insert(DocumentId(0), vec![0.1, 0.2, 0.3]);
|
||||
|
||||
provider.rebuild_indexes(&data, true).await.unwrap();
|
||||
|
||||
let results = provider
|
||||
.vector_search(&[0.1, 0.2, 0.3], 5, 0.0)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(results.len(), 1);
|
||||
|
||||
drop(provider);
|
||||
assert_eq!(DuckDbProvider::introspect_dim(&db.path).unwrap(), Some(3));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_self_healed_dim_is_visible_through_duplicate_clones() {
|
||||
let db = TempDb::new("dimdup");
|
||||
let mut provider = DuckDbProvider::open(&db.path, 5).unwrap();
|
||||
let dup = provider.duplicate(&minimal_rag_data());
|
||||
|
||||
let mut data = minimal_rag_data();
|
||||
data.vectors.insert(DocumentId(0), vec![0.1, 0.2, 0.3]);
|
||||
provider.rebuild_indexes(&data, true).await.unwrap();
|
||||
|
||||
let results = dup.vector_search(&[0.1, 0.2, 0.3], 5, 0.0).await.unwrap();
|
||||
assert_eq!(
|
||||
results.len(),
|
||||
1,
|
||||
"a duplicate() clone must observe the dim written by a rebuild through \
|
||||
the original"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rebuild_indexes_rejects_mixed_dim_vectors() {
|
||||
let db = TempDb::new("mixeddim");
|
||||
let mut provider = DuckDbProvider::open(&db.path, 3).unwrap();
|
||||
let mut data = minimal_rag_data();
|
||||
data.vectors.insert(DocumentId(0), vec![0.1, 0.2, 0.3]);
|
||||
data.vectors.insert(DocumentId(1), vec![0.1, 0.2, 0.3, 0.4]);
|
||||
|
||||
let err = provider.rebuild_indexes(&data, true).await.unwrap_err();
|
||||
|
||||
assert!(
|
||||
err.to_string().contains("rebuild batch mixes"),
|
||||
"got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn vector_search_dim_mismatch_on_empty_store_returns_nothing() {
|
||||
let db = TempDb::new("dimempty");
|
||||
let provider = DuckDbProvider::open(&db.path, 3).unwrap();
|
||||
|
||||
let results = provider.vector_search(&[0.1, 0.2], 5, 0.0).await.unwrap();
|
||||
|
||||
assert!(
|
||||
results.is_empty(),
|
||||
"a never-synced store must answer 'nothing', not a cast error"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn vector_search_dim_mismatch_on_populated_store_errors() {
|
||||
let db = TempDb::new("dimfull");
|
||||
let mut provider = DuckDbProvider::open(&db.path, 3).unwrap();
|
||||
let mut data = minimal_rag_data();
|
||||
data.vectors.insert(DocumentId(0), vec![0.1, 0.2, 0.3]);
|
||||
provider.rebuild_indexes(&data, true).await.unwrap();
|
||||
|
||||
let err = provider
|
||||
.vector_search(&[0.1, 0.2], 5, 0.0)
|
||||
.await
|
||||
.unwrap_err();
|
||||
|
||||
assert!(err.to_string().contains("was built with"), "got: {err}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn duplicate_shares_the_same_connection() {
|
||||
let db = TempDb::new("dup");
|
||||
|
||||
+96
-11
@@ -9,6 +9,7 @@ use reqwest::{Client, Response, StatusCode};
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use url::{Host, Url};
|
||||
|
||||
/// Marks a `DocumentId` that stands in for a point id Coyote cannot carry
|
||||
/// directly. Qdrant accepts UUID strings as point ids, and that is what
|
||||
@@ -104,7 +105,7 @@ fn parse_search_hits(
|
||||
let score = pt["score"].as_f64()? as f32;
|
||||
Some((interner.document_id(&pt["id"])?, score))
|
||||
})
|
||||
.filter(|(_, score)| *score > min_score)
|
||||
.filter(|(_, score)| min_score <= 0.0 || *score > min_score)
|
||||
.collect())
|
||||
}
|
||||
|
||||
@@ -183,7 +184,22 @@ pub struct QdrantProvider {
|
||||
}
|
||||
|
||||
impl QdrantProvider {
|
||||
fn make_client(api_key: Option<&str>) -> Result<Client> {
|
||||
fn skips_proxy(base_url: &str) -> bool {
|
||||
let Ok(url) = Url::parse(base_url) else {
|
||||
return false;
|
||||
};
|
||||
match url.host() {
|
||||
Some(Host::Domain(name)) => {
|
||||
name == "localhost" || name.ends_with(".localhost") || name.ends_with(".local")
|
||||
}
|
||||
Some(Host::Ipv4(ip)) => ip.is_loopback() || ip.is_private() || ip.is_link_local(),
|
||||
// No stable is_unique_local, so fc00::/7 is matched directly.
|
||||
Some(Host::Ipv6(ip)) => ip.is_loopback() || ip.segments()[0] & 0xfe00 == 0xfc00,
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn make_client(base_url: &str, api_key: Option<&str>) -> Result<Client> {
|
||||
let mut headers = HeaderMap::new();
|
||||
if let Some(key) = api_key {
|
||||
let mut value =
|
||||
@@ -191,10 +207,11 @@ impl QdrantProvider {
|
||||
value.set_sensitive(true);
|
||||
headers.insert("api-key", value);
|
||||
}
|
||||
Client::builder()
|
||||
.default_headers(headers)
|
||||
.build()
|
||||
.context("Failed to build reqwest client")
|
||||
let mut builder = Client::builder().default_headers(headers);
|
||||
if Self::skips_proxy(base_url) {
|
||||
builder = builder.no_proxy();
|
||||
}
|
||||
builder.build().context("Failed to build reqwest client")
|
||||
}
|
||||
|
||||
pub(crate) fn normalize_base_url(host: &str) -> String {
|
||||
@@ -219,7 +236,7 @@ impl QdrantProvider {
|
||||
api_key: Option<&str>,
|
||||
) -> Result<Value> {
|
||||
let base_url = Self::normalize_base_url(host);
|
||||
let client = Self::make_client(api_key)?;
|
||||
let client = Self::make_client(&base_url, api_key)?;
|
||||
let resp = client
|
||||
.get(format!("{base_url}/collections/{collection}"))
|
||||
.send()
|
||||
@@ -237,7 +254,7 @@ impl QdrantProvider {
|
||||
|
||||
pub async fn new(host: &str, collection: &str, api_key: Option<&str>) -> Result<Self> {
|
||||
let base_url = Self::normalize_base_url(host);
|
||||
let client = Self::make_client(api_key)?;
|
||||
let client = Self::make_client(&base_url, api_key)?;
|
||||
let resp = client
|
||||
.get(format!("{base_url}/collections/{collection}"))
|
||||
.send()
|
||||
@@ -260,7 +277,7 @@ impl QdrantProvider {
|
||||
|
||||
pub async fn list_collections(host: &str, api_key: Option<&str>) -> Result<Vec<String>> {
|
||||
let base_url = Self::normalize_base_url(host);
|
||||
let client = Self::make_client(api_key)?;
|
||||
let client = Self::make_client(&base_url, api_key)?;
|
||||
let resp = client
|
||||
.get(format!("{base_url}/collections"))
|
||||
.send()
|
||||
@@ -310,7 +327,7 @@ impl QdrantProvider {
|
||||
api_key: Option<&str>,
|
||||
) -> Result<Option<String>> {
|
||||
let base_url = Self::normalize_base_url(host);
|
||||
let client = Self::make_client(api_key)?;
|
||||
let client = Self::make_client(&base_url, api_key)?;
|
||||
let url = format!("{base_url}/collections/{collection}/points/scroll");
|
||||
let body = serde_json::json!({ "limit": 1, "with_payload": false });
|
||||
|
||||
@@ -353,7 +370,8 @@ impl RagProvider for QdrantProvider {
|
||||
// `score_threshold` is deliberately NOT sent. It is metric-aware: on Cosine
|
||||
// collections 0.0 means "no floor" as expected, but Euclid collections score
|
||||
// by negative distance, where 0.0 filters everything out. The attach wizard
|
||||
// does not pin the distance metric, so filter locally instead.
|
||||
// does not pin the distance metric, so filter locally instead; i.e. where a
|
||||
// 0.0 floor is correctly treated as "no floor" (see `parse_search_hits`).
|
||||
let body = serde_json::json!({
|
||||
"vector": embedding,
|
||||
"limit": top_k,
|
||||
@@ -576,6 +594,73 @@ mod tests {
|
||||
assert!(provider.fetch_content(&[]).await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_and_private_hosts_skip_the_proxy() {
|
||||
for host in [
|
||||
"http://localhost:6333",
|
||||
"http://127.0.0.1:6333",
|
||||
"http://192.168.0.56:6333",
|
||||
"http://10.1.2.3:6333",
|
||||
"http://172.16.4.5:6333",
|
||||
"http://qdrant.local:6333",
|
||||
"http://[::1]:6333",
|
||||
] {
|
||||
assert!(
|
||||
QdrantProvider::skips_proxy(host),
|
||||
"{host} should not be proxied"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_hosts_still_honour_the_environment() {
|
||||
for host in [
|
||||
"https://qdrant.example.com",
|
||||
"http://8.8.8.8:6333",
|
||||
"https://xyz.eu-central.aws.cloud.qdrant.io:6333",
|
||||
"http://172.32.0.1:6333",
|
||||
] {
|
||||
assert!(
|
||||
!QdrantProvider::skips_proxy(host),
|
||||
"{host} must keep the environment's proxy"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Euclid collections score by NEGATIVE distance, so the 0.0 the caller
|
||||
/// passes must mean "no floor". Filtering on it drops every hit — the exact
|
||||
/// bug that keeps Qdrant's own `score_threshold` off the wire.
|
||||
#[test]
|
||||
fn a_zero_floor_keeps_negative_euclid_scores() {
|
||||
let mut interner = PointIdInterner::default();
|
||||
let search = serde_json::json!({
|
||||
"result": [
|
||||
{"id": 1, "score": -0.12},
|
||||
{"id": 2, "score": -8.5},
|
||||
]
|
||||
});
|
||||
|
||||
let hits = parse_search_hits(&mut interner, &search, 0.0).unwrap();
|
||||
|
||||
assert_eq!(hits.len(), 2, "a 0.0 floor must not drop negative scores");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_positive_floor_still_filters() {
|
||||
let mut interner = PointIdInterner::default();
|
||||
let search = serde_json::json!({
|
||||
"result": [
|
||||
{"id": 1, "score": 0.9},
|
||||
{"id": 2, "score": 0.2},
|
||||
]
|
||||
});
|
||||
|
||||
let hits = parse_search_hits(&mut interner, &search, 0.5).unwrap();
|
||||
|
||||
assert_eq!(hits.len(), 1);
|
||||
assert_eq!(hits[0].0, DocumentId(1));
|
||||
}
|
||||
|
||||
/// A UUID-keyed collection has to survive the whole `vector_search` →
|
||||
/// `fetch_content` round trip, and the fetch must ask Qdrant for the ORIGINAL
|
||||
/// string id. Parsing ids with `as_u64()` used to drop these hits inside a
|
||||
|
||||
+34
-2
@@ -39,8 +39,10 @@ static INLINE_CODE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"`([^`\n]+
|
||||
static IMAGE_RE: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"!\[([^\]]*)\]\(([^)]+)\)").unwrap());
|
||||
static LINK_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[([^\]]+)\]\(([^)]+)\)").unwrap());
|
||||
static BOLD_AST_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\*\*([^*\n]+)\*\*").unwrap());
|
||||
static BOLD_US_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"__([^_\n]+)__").unwrap());
|
||||
static BOLD_AST_RE: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"\*\*((?:[^*\n]|\*(?!\*))+?)\*\*").unwrap());
|
||||
static BOLD_US_RE: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"__((?:[^_\n]|_(?!_))+?)__").unwrap());
|
||||
static ITALIC_AST_RE: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"(?<![*\w])\*(?!\s)([^*\n]+?)(?<!\s)\*(?!\*)").unwrap());
|
||||
static ITALIC_US_RE: LazyLock<Regex> =
|
||||
@@ -2419,6 +2421,36 @@ std::error::Error>> {
|
||||
assert!(result.contains("\x1b[9m"), "strikethrough SGR: {result:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bold_asterisk_wraps_italic_asterisk() {
|
||||
let styles = test_styles();
|
||||
|
||||
let result = apply_inline("**loud *soft* loud**", &styles);
|
||||
|
||||
assert!(
|
||||
!result.contains("**"),
|
||||
"outer bold markers stripped: {result:?}"
|
||||
);
|
||||
assert!(result.contains("\x1b[1m"), "bold SGR present: {result:?}");
|
||||
assert!(result.contains("\x1b[3m"), "italic SGR present: {result:?}");
|
||||
assert!(result.contains("soft"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bold_underscore_wraps_italic_underscore() {
|
||||
let styles = test_styles();
|
||||
|
||||
let result = apply_inline("__loud _soft_ loud__", &styles);
|
||||
|
||||
assert!(
|
||||
!result.contains("__"),
|
||||
"outer bold markers stripped: {result:?}"
|
||||
);
|
||||
assert!(result.contains("\x1b[1m"), "bold SGR present: {result:?}");
|
||||
assert!(result.contains("\x1b[3m"), "italic SGR present: {result:?}");
|
||||
assert!(result.contains("soft"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bold_wraps_inline_code() {
|
||||
let styles = test_styles();
|
||||
|
||||
+19
-1
@@ -74,7 +74,25 @@ impl Completer for ReplCompleter {
|
||||
format!("{name} ")
|
||||
};
|
||||
create_suggestion(&name, description, span)
|
||||
}))
|
||||
}));
|
||||
|
||||
let macros: Vec<(String, Option<String>)> = ctx
|
||||
.visible_macro_completions()
|
||||
.into_iter()
|
||||
.map(|(name, description)| (format!(".{name}"), description))
|
||||
.filter(|(name, _)| {
|
||||
command_filter.len() == 1
|
||||
|| name.starts_with(command_filter.get(..2).unwrap_or(&command_filter))
|
||||
})
|
||||
.collect();
|
||||
let macros = fuzzy_filter(macros, |(name, _)| name.as_str(), &command_filter);
|
||||
suggestions.extend(macros.iter().map(|(name, description)| {
|
||||
create_suggestion(
|
||||
&format!("{name} "),
|
||||
description.as_deref().unwrap_or_default(),
|
||||
span,
|
||||
)
|
||||
}));
|
||||
}
|
||||
suggestions
|
||||
}
|
||||
|
||||
+313
-31
@@ -12,15 +12,15 @@ use crate::client::{
|
||||
oauth,
|
||||
};
|
||||
use crate::config::{
|
||||
AgentVariables, AppConfig, AssertState, Input, LastMessage, RequestContext, StateFlags,
|
||||
macro_execute,
|
||||
AgentVariables, AppConfig, AssertState, Input, LastMessage, MacroState, RequestContext,
|
||||
StateFlags, macro_execute,
|
||||
};
|
||||
use crate::config::{AssetCategory, paths};
|
||||
use crate::function::supervisor::{GuardrailAction, check_pending_agents_guardrail};
|
||||
use crate::render::render_error;
|
||||
use crate::utils::{
|
||||
AbortSignal, SHELL, abortable_run_with_spinner, create_abort_signal, dimmed_text, run_command,
|
||||
set_text, temp_file,
|
||||
AbortSignal, SHELL, abortable_run_with_spinner, create_abort_signal, dimmed_text,
|
||||
drain_stale_tty_input, run_command, set_text, temp_file,
|
||||
};
|
||||
|
||||
use crate::sandbox::SANDBOX_ENV_FLAG;
|
||||
@@ -53,7 +53,7 @@ pub const DEFAULT_CONTINUATION_PROMPT: &str = indoc! {"
|
||||
4. Continue with the next pending item now. Call tools immediately."
|
||||
};
|
||||
|
||||
static REPL_COMMANDS: LazyLock<[ReplCommand; 60]> = LazyLock::new(|| {
|
||||
static REPL_COMMANDS: LazyLock<[ReplCommand; 61]> = LazyLock::new(|| {
|
||||
[
|
||||
ReplCommand::new(".help", "Show this help guide", AssertState::pass()),
|
||||
ReplCommand::new(".info", "Show system info", AssertState::pass()),
|
||||
@@ -307,7 +307,7 @@ static REPL_COMMANDS: LazyLock<[ReplCommand; 60]> = LazyLock::new(|| {
|
||||
),
|
||||
ReplCommand::new(
|
||||
".list",
|
||||
"List roles, sessions, agents, RAGs, macros, skills, tools, or MCP servers",
|
||||
"List roles, sessions, agents, RAGs, macros, skills, tools, MCP servers, or bundles",
|
||||
AssertState::pass(),
|
||||
),
|
||||
ReplCommand::new(
|
||||
@@ -317,7 +317,12 @@ static REPL_COMMANDS: LazyLock<[ReplCommand; 60]> = LazyLock::new(|| {
|
||||
),
|
||||
ReplCommand::new(
|
||||
".install",
|
||||
"Reinstall bundled assets, or install assets from a remote git repo (.install remote <url>)",
|
||||
"Reinstall bundled assets, install a bundle from a git repo, or update an installed bundle",
|
||||
AssertState::pass(),
|
||||
),
|
||||
ReplCommand::new(
|
||||
".uninstall",
|
||||
"Uninstall an installed bundle (delete its owned files and MCP entries)",
|
||||
AssertState::pass(),
|
||||
),
|
||||
ReplCommand::new(
|
||||
@@ -411,6 +416,10 @@ Type ".help" for additional help.
|
||||
}
|
||||
}
|
||||
|
||||
// Discard any stray terminal-query reply bytes (e.g. late colorsaurus
|
||||
// OSC 11 / DA1 responses) so they don't get injected into the prompt.
|
||||
drain_stale_tty_input();
|
||||
|
||||
loop {
|
||||
if self.abort_signal.aborted_ctrld() {
|
||||
break;
|
||||
@@ -861,27 +870,18 @@ pub async fn run_repl_command(
|
||||
replay::render(app.as_ref(), &compressed, &active)?;
|
||||
}
|
||||
}
|
||||
".install" => {
|
||||
let trimmed = args.map(str::trim).unwrap_or("");
|
||||
let mut parts = trimmed.splitn(2, char::is_whitespace);
|
||||
match parts.next() {
|
||||
Some("remote") => {
|
||||
let rest = parts.next().unwrap_or("").trim();
|
||||
config::install_remote_from_repl_args(rest)?;
|
||||
".install" => match parse_repl_install(args) {
|
||||
ReplInstallDispatch::Builtins(category) => config::install_assets(category)?,
|
||||
ReplInstallDispatch::Unified(value) => {
|
||||
config::install_or_update_from_repl_args(value)?;
|
||||
}
|
||||
Some(name) if !name.is_empty() => match AssetCategory::parse(name) {
|
||||
Some(category) => config::install_assets(category)?,
|
||||
None => println!(
|
||||
"Unknown asset category '{name}'. Valid categories: {}",
|
||||
AssetCategory::NAMES.join(", ")
|
||||
),
|
||||
},
|
||||
_ => println!(
|
||||
"Usage: .install <{}> | .install remote <git-url>",
|
||||
ReplInstallDispatch::Help => println!("{}", repl_install_help()),
|
||||
ReplInstallDispatch::Usage => println!(
|
||||
"Usage: .install <{}> | .install <git-url|owner/repo|installed-bundle> \
|
||||
[--git-host <host>] [--filter <cat>] [--force] (see `.install --help`)",
|
||||
AssetCategory::NAMES.join("|")
|
||||
),
|
||||
}
|
||||
}
|
||||
},
|
||||
".update" => {
|
||||
if ctx.macro_flag {
|
||||
bail!("Cannot perform this operation because you are in a macro")
|
||||
@@ -892,7 +892,7 @@ pub async fn run_repl_command(
|
||||
".rag" => match split_first_arg(args) {
|
||||
Some(("attach", rest)) => match rest {
|
||||
Some(name) if !name.trim().is_empty() => {
|
||||
ctx.attach_rag(name.trim()).await?;
|
||||
ctx.attach_rag(name.trim(), abort_signal.clone()).await?;
|
||||
}
|
||||
_ => println!("Usage: .rag attach <name>"),
|
||||
},
|
||||
@@ -1069,15 +1069,44 @@ pub async fn run_repl_command(
|
||||
}
|
||||
},
|
||||
".macro" => match split_first_arg(args) {
|
||||
Some((sub @ ("enable" | "disable"), rest)) => {
|
||||
match rest.and_then(|v| v.split_whitespace().next()) {
|
||||
Some(name) => ctx.macro_toggle(name, sub == "enable")?,
|
||||
None => println!("Usage: .macro {sub} <name>"),
|
||||
}
|
||||
}
|
||||
Some((name, extra)) => {
|
||||
let policy = ctx.macro_policy();
|
||||
match policy.find(name).map(|row| &row.state) {
|
||||
Some(state) if state.is_invocable() => {
|
||||
macro_execute(ctx, name, extra, abort_signal.clone()).await?;
|
||||
}
|
||||
Some(MacroState::DisabledRuntime) => bail!(
|
||||
r#"Macro '{name}' is disabled. Re-enable it with ".macro enable {name}""#
|
||||
),
|
||||
Some(MacroState::Locked { level }) => bail!(
|
||||
"Macro '{name}' is restricted by {} enabled_macros",
|
||||
ctx.macro_lock_owner(*level)
|
||||
),
|
||||
Some(MacroState::Invalid { reason }) => {
|
||||
bail!("Macro '{name}' is invalid: {reason}")
|
||||
}
|
||||
Some(_) | None => {
|
||||
if extra.is_none() {
|
||||
let app = Arc::clone(&ctx.app.config);
|
||||
if !paths::has_macro(name) && extra.is_none() {
|
||||
ctx.new_macro(app.as_ref(), name)?;
|
||||
} else {
|
||||
macro_execute(ctx, name, extra, abort_signal.clone()).await?;
|
||||
}
|
||||
}
|
||||
None => println!("Usage: .macro <name> <text>..."),
|
||||
}
|
||||
}
|
||||
None => println!(
|
||||
r#"Usage:
|
||||
.macro <name> [text]... # Execute a macro
|
||||
.macro enable <name> # Re-enable a runtime-disabled macro
|
||||
.macro disable <name> # Disable a macro for the rest of this process"#
|
||||
),
|
||||
},
|
||||
".file" => match args {
|
||||
Some(args) => {
|
||||
@@ -1169,13 +1198,22 @@ pub async fn run_repl_command(
|
||||
println!("Usage: .delete <role|session|rag|macro|skill|agent-data>")
|
||||
}
|
||||
},
|
||||
".uninstall" => match parse_repl_uninstall(args) {
|
||||
ReplUninstallDispatch::Run(name, assume_yes) => {
|
||||
config::uninstall_bundle(&name, assume_yes)?
|
||||
}
|
||||
ReplUninstallDispatch::Help => println!("{}", repl_uninstall_help()),
|
||||
ReplUninstallDispatch::Usage => {
|
||||
println!("Usage: .uninstall <bundle-name> [--yes] (see `.uninstall --help`)")
|
||||
}
|
||||
},
|
||||
".list" => match args {
|
||||
Some(args) => {
|
||||
ctx.list_assets(args.trim())?;
|
||||
}
|
||||
_ => {
|
||||
println!(
|
||||
"Usage: .list <roles|sessions|agents|rags|macros|skills|tools|mcp-servers>"
|
||||
"Usage: .list <roles|sessions|agents|rags|macros|skills|tools|mcp-servers|bundles>"
|
||||
)
|
||||
}
|
||||
},
|
||||
@@ -1290,7 +1328,26 @@ pub async fn run_repl_command(
|
||||
println!("Usage: .vault <add|get|update|delete|list> [name]")
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
let name = cmd.strip_prefix('.').unwrap_or(cmd);
|
||||
let policy = ctx.macro_policy();
|
||||
match policy.find(name).map(|row| &row.state) {
|
||||
Some(MacroState::Enabled) => {
|
||||
macro_execute(ctx, name, args, abort_signal.clone()).await?;
|
||||
}
|
||||
Some(MacroState::DisabledRuntime) => bail!(
|
||||
r#"Macro '{name}' is disabled. Re-enable it with ".macro enable {name}""#
|
||||
),
|
||||
Some(MacroState::Locked { level }) => bail!(
|
||||
"Macro '{name}' is restricted by {} enabled_macros",
|
||||
ctx.macro_lock_owner(*level)
|
||||
),
|
||||
Some(MacroState::Invalid { reason }) => {
|
||||
bail!("Macro '{name}' is invalid: {reason}")
|
||||
}
|
||||
_ => unknown_command()?,
|
||||
}
|
||||
}
|
||||
},
|
||||
None => {
|
||||
if let Some(cmd) = try_extract_shell_command(line) {
|
||||
@@ -1518,6 +1575,109 @@ fn unknown_command() -> Result<()> {
|
||||
bail!(r#"Unknown command. Type ".help" for additional help."#);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum ReplInstallDispatch<'a> {
|
||||
Builtins(AssetCategory),
|
||||
Unified(&'a str),
|
||||
Help,
|
||||
Usage,
|
||||
}
|
||||
|
||||
fn parse_repl_install(args: Option<&str>) -> ReplInstallDispatch<'_> {
|
||||
let trimmed = args.map(str::trim).unwrap_or("");
|
||||
if trimmed
|
||||
.split_whitespace()
|
||||
.any(|token| token == "--help" || token == "-h")
|
||||
{
|
||||
return ReplInstallDispatch::Help;
|
||||
}
|
||||
let mut parts = trimmed.splitn(2, char::is_whitespace);
|
||||
match parts.next() {
|
||||
Some(name) if !name.is_empty() => {
|
||||
let rest = parts.next().map(str::trim).unwrap_or("");
|
||||
match AssetCategory::parse(name) {
|
||||
Some(category) if rest.is_empty() => ReplInstallDispatch::Builtins(category),
|
||||
Some(_) => ReplInstallDispatch::Usage,
|
||||
None => ReplInstallDispatch::Unified(trimmed),
|
||||
}
|
||||
}
|
||||
_ => ReplInstallDispatch::Usage,
|
||||
}
|
||||
}
|
||||
|
||||
fn repl_install_help() -> String {
|
||||
format!(
|
||||
r#"Install built-in assets, install a bundle from a Git source, or update an installed bundle.
|
||||
|
||||
Usage:
|
||||
.install <category> Reinstall built-in assets ({categories})
|
||||
.install <owner/repo>[#ref] Install a bundle from {default_host} (change the host with --git-host)
|
||||
.install <git-url>[#ref] Install a bundle from any Git URL, scp-style path, or local path
|
||||
.install <installed-bundle>[#ref] Update an installed bundle from its recorded source
|
||||
|
||||
Flags:
|
||||
--git-host <host> Host the <owner/repo> shorthand expands against (default {default_host})
|
||||
--filter <cat> Restrict a remote install to one category ({filters})
|
||||
--force Overwrite all conflicts without prompting (remote installs only)
|
||||
|
||||
Suffix #<ref> to pin a branch, tag, or commit. List installed bundles with
|
||||
`.list bundles`; remove one with `.uninstall <name>`."#,
|
||||
categories = AssetCategory::NAMES.join("|"),
|
||||
default_host = config::DEFAULT_GIT_HOST,
|
||||
filters = config::InstallFilter::NAMES.join("|"),
|
||||
)
|
||||
}
|
||||
|
||||
fn repl_uninstall_help() -> String {
|
||||
r#"Remove an installed bundle: delete the files it owns and the mcp.json entries it added.
|
||||
|
||||
Usage:
|
||||
.uninstall <bundle-name> [--yes]
|
||||
|
||||
Flags:
|
||||
--yes, -y Skip the confirmation prompt
|
||||
|
||||
Files you modified after install are prompted for individually and kept by
|
||||
default; --yes never deletes modified files. List installed bundles with
|
||||
`.list bundles`."#
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
enum ReplUninstallDispatch {
|
||||
Run(String, bool),
|
||||
Help,
|
||||
Usage,
|
||||
}
|
||||
|
||||
fn parse_repl_uninstall(args: Option<&str>) -> ReplUninstallDispatch {
|
||||
let mut assume_yes = false;
|
||||
let mut names = Vec::new();
|
||||
for token in args.unwrap_or("").split_whitespace() {
|
||||
match token {
|
||||
"--help" | "-h" => return ReplUninstallDispatch::Help,
|
||||
"--yes" | "-y" => assume_yes = true,
|
||||
other if other.starts_with('-') => return ReplUninstallDispatch::Usage,
|
||||
other => names.push(other),
|
||||
}
|
||||
}
|
||||
match names.as_slice() {
|
||||
[name] => ReplUninstallDispatch::Run(name.to_string(), assume_yes),
|
||||
_ => ReplUninstallDispatch::Usage,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn builtin_command_names() -> Vec<&'static str> {
|
||||
let mut names: Vec<&'static str> = REPL_COMMANDS
|
||||
.iter()
|
||||
.filter_map(|cmd| cmd.name.split_whitespace().next())
|
||||
.filter_map(|name| name.strip_prefix('.'))
|
||||
.collect();
|
||||
names.sort_unstable();
|
||||
names.dedup();
|
||||
names
|
||||
}
|
||||
|
||||
fn dump_repl_help() {
|
||||
let head = REPL_COMMANDS
|
||||
.iter()
|
||||
@@ -1528,6 +1688,10 @@ fn dump_repl_help() {
|
||||
r###"{head}
|
||||
{:<24} Run an arbitrary shell command (stdout/stderr stream to your terminal; Ctrl+C interrupts)
|
||||
|
||||
Custom commands (macros): macros are coyote's custom commands. An enabled
|
||||
macro <name> runs top-level as .<name> [args...], equivalent to ".macro <name>".
|
||||
List them with ".list macros"; toggle them with ".macro enable|disable <name>".
|
||||
|
||||
Type ::: to start multi-line editing, type ::: to finish it.
|
||||
Press Ctrl+O to open an editor for editing the input buffer.
|
||||
Press Ctrl+C to cancel the response, Ctrl+D to exit the REPL."###,
|
||||
@@ -1724,8 +1888,126 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repl_commands_has_60_entries() {
|
||||
assert_eq!(REPL_COMMANDS.len(), 60);
|
||||
fn repl_commands_has_61_entries() {
|
||||
assert_eq!(REPL_COMMANDS.len(), 61);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_repl_install_routes_categories_to_builtins() {
|
||||
assert_eq!(
|
||||
parse_repl_install(Some("agents")),
|
||||
ReplInstallDispatch::Builtins(AssetCategory::Agents)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_repl_install_routes_other_values_to_unified_dispatch() {
|
||||
assert_eq!(
|
||||
parse_repl_install(Some("https://github.com/x/y")),
|
||||
ReplInstallDispatch::Unified("https://github.com/x/y")
|
||||
);
|
||||
assert_eq!(
|
||||
parse_repl_install(Some("my-bundle")),
|
||||
ReplInstallDispatch::Unified("my-bundle")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_repl_install_empty_args_ask_for_usage() {
|
||||
assert_eq!(parse_repl_install(None), ReplInstallDispatch::Usage);
|
||||
assert_eq!(parse_repl_install(Some(" ")), ReplInstallDispatch::Usage);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_repl_install_rejects_extra_tokens_after_a_category() {
|
||||
assert_eq!(
|
||||
parse_repl_install(Some("agents --force")),
|
||||
ReplInstallDispatch::Usage
|
||||
);
|
||||
assert_eq!(
|
||||
parse_repl_install(Some("agents extra")),
|
||||
ReplInstallDispatch::Usage
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_repl_install_routes_help_from_any_position() {
|
||||
assert_eq!(
|
||||
parse_repl_install(Some("--help")),
|
||||
ReplInstallDispatch::Help
|
||||
);
|
||||
assert_eq!(parse_repl_install(Some("-h")), ReplInstallDispatch::Help);
|
||||
assert_eq!(
|
||||
parse_repl_install(Some("agents --help")),
|
||||
ReplInstallDispatch::Help
|
||||
);
|
||||
assert_eq!(
|
||||
parse_repl_install(Some("owner/repo --help")),
|
||||
ReplInstallDispatch::Help
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_repl_uninstall_routes_run_help_and_usage() {
|
||||
assert_eq!(
|
||||
parse_repl_uninstall(Some("my-bundle --yes")),
|
||||
ReplUninstallDispatch::Run("my-bundle".to_string(), true)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_repl_uninstall(Some("my-bundle")),
|
||||
ReplUninstallDispatch::Run("my-bundle".to_string(), false)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_repl_uninstall(Some("--help")),
|
||||
ReplUninstallDispatch::Help
|
||||
);
|
||||
assert_eq!(
|
||||
parse_repl_uninstall(Some("my-bundle -h")),
|
||||
ReplUninstallDispatch::Help
|
||||
);
|
||||
assert_eq!(
|
||||
parse_repl_uninstall(Some("--force my-bundle")),
|
||||
ReplUninstallDispatch::Usage
|
||||
);
|
||||
assert_eq!(parse_repl_uninstall(None), ReplUninstallDispatch::Usage);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repl_install_and_uninstall_help_text_cover_the_full_surface() {
|
||||
let install = repl_install_help();
|
||||
for needle in [
|
||||
"--git-host",
|
||||
"--filter",
|
||||
"--force",
|
||||
"#ref",
|
||||
"owner/repo",
|
||||
".list bundles",
|
||||
] {
|
||||
assert!(install.contains(needle), "install help missing {needle}");
|
||||
}
|
||||
let uninstall = repl_uninstall_help();
|
||||
for needle in ["--yes", ".list bundles", "<bundle-name>"] {
|
||||
assert!(
|
||||
uninstall.contains(needle),
|
||||
"uninstall help missing {needle}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtin_command_names_are_sorted_deduped_first_words_without_dots() {
|
||||
let names = builtin_command_names();
|
||||
assert!(!names.is_empty());
|
||||
for name in &names {
|
||||
assert!(!name.starts_with('.'), "'{name}' should not keep the dot");
|
||||
assert!(!name.contains(' '), "'{name}' should be a single word");
|
||||
}
|
||||
assert!(
|
||||
names.windows(2).all(|w| w[0] < w[1]),
|
||||
"names should be sorted and deduplicated: {names:?}"
|
||||
);
|
||||
assert!(names.contains(&"help"));
|
||||
assert!(names.contains(&"macro"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+295
-14
@@ -80,6 +80,8 @@ pub(crate) struct CredentialSpec {
|
||||
pub env_var: String,
|
||||
pub proxy_managed: bool,
|
||||
pub inject: Vec<InjectRule>,
|
||||
pub custom_hosts: Vec<String>,
|
||||
pub custom_allow_entries: Vec<String>,
|
||||
pub servers: Vec<String>,
|
||||
}
|
||||
|
||||
@@ -110,8 +112,13 @@ pub(crate) fn collect_credentials(
|
||||
}
|
||||
|
||||
let mut by_secret: BTreeMap<String, Aggregate> = BTreeMap::new();
|
||||
let mut hosts_by_server: BTreeMap<String, ServerSecretHosts> = BTreeMap::new();
|
||||
for (server_name, config) in servers {
|
||||
for occurrence in collect_server_occurrences(config)? {
|
||||
let occurrences = collect_server_occurrences(config)?;
|
||||
if !occurrences.is_empty() {
|
||||
hosts_by_server.insert(server_name.clone(), server_secret_hosts(config));
|
||||
}
|
||||
for occurrence in occurrences {
|
||||
let agg = by_secret
|
||||
.entry(occurrence.secret_name)
|
||||
.or_insert_with(|| Aggregate {
|
||||
@@ -152,8 +159,9 @@ pub(crate) fn collect_credentials(
|
||||
eprintln!(
|
||||
"MCP secrets {} all target the '{header}' header for '{domain}'. The \
|
||||
sandbox proxy cannot tell which one a given request needs, so these \
|
||||
secrets will be resolved from environment variables inside the \
|
||||
sandbox instead.",
|
||||
secrets will be provisioned as placeholder-based custom secrets \
|
||||
instead: each env var holds a unique placeholder that the proxy \
|
||||
swaps for the real value in outbound request headers.",
|
||||
quoted_list(secrets)
|
||||
);
|
||||
slot_conflicted.extend(secrets.iter().cloned());
|
||||
@@ -191,6 +199,21 @@ pub(crate) fn collect_credentials(
|
||||
}
|
||||
|
||||
let proxy_managed = agg.all_injectable && !slot_conflicted.contains(&secret_name);
|
||||
let (custom_hosts, custom_allow_entries) = if proxy_managed {
|
||||
(Vec::new(), Vec::new())
|
||||
} else {
|
||||
let mut targets: BTreeSet<String> = BTreeSet::new();
|
||||
let mut allow: BTreeSet<String> = BTreeSet::new();
|
||||
for hosts in agg
|
||||
.servers
|
||||
.iter()
|
||||
.filter_map(|server| hosts_by_server.get(server))
|
||||
{
|
||||
targets.extend(hosts.targets.iter().cloned());
|
||||
allow.extend(hosts.allow_entries.iter().cloned());
|
||||
}
|
||||
(targets.into_iter().collect(), allow.into_iter().collect())
|
||||
};
|
||||
credentials.push(CredentialSpec {
|
||||
secret_name,
|
||||
service_id,
|
||||
@@ -201,6 +224,8 @@ pub(crate) fn collect_credentials(
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
custom_hosts,
|
||||
custom_allow_entries,
|
||||
servers: agg.servers.into_iter().collect(),
|
||||
});
|
||||
}
|
||||
@@ -365,6 +390,98 @@ fn parse_https_domain(raw: &str) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct ServerSecretHosts {
|
||||
pub targets: BTreeSet<String>,
|
||||
pub allow_entries: BTreeSet<String>,
|
||||
}
|
||||
|
||||
pub(crate) fn server_secret_hosts(server: &Value) -> ServerSecretHosts {
|
||||
let mut hosts = ServerSecretHosts::default();
|
||||
scrape_hosts_value(server, &mut hosts);
|
||||
|
||||
if let Some(host) = server
|
||||
.get("url")
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|raw| Url::parse(raw).ok())
|
||||
.and_then(|url| url.host_str().map(str::to_string))
|
||||
.filter(|host| is_usable_host(host))
|
||||
{
|
||||
hosts.targets.insert(host);
|
||||
}
|
||||
|
||||
hosts
|
||||
}
|
||||
|
||||
fn scrape_hosts_value(value: &Value, out: &mut ServerSecretHosts) {
|
||||
match value {
|
||||
Value::String(s) => {
|
||||
for url in urls_in_text(s) {
|
||||
let Some(host) = url.host_str().filter(|h| is_usable_host(h)) else {
|
||||
continue;
|
||||
};
|
||||
out.targets.insert(host.to_string());
|
||||
if let Some(entry) = allow_entry_for_parsed(&url) {
|
||||
out.allow_entries.insert(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Object(map) => {
|
||||
for v in map.values() {
|
||||
scrape_hosts_value(v, out);
|
||||
}
|
||||
}
|
||||
Value::Array(arr) => {
|
||||
for v in arr {
|
||||
scrape_hosts_value(v, out);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// A host usable in the sbx target and allow grammars: non-empty, not a
|
||||
/// bracketed IPv6 literal (no spelling in either grammar), and not an
|
||||
/// unresolved `{{placeholder}}` fragment (would register garbage targets
|
||||
/// and could fail kit validation at create).
|
||||
fn is_usable_host(host: &str) -> bool {
|
||||
!host.is_empty() && !host.starts_with('[') && !host.contains('{') && !host.contains('}')
|
||||
}
|
||||
|
||||
/// Every http(s) URL embedded in `text`. Tokens end at whitespace, quotes,
|
||||
/// or URL-hostile punctuation so comma- or bracket-separated lists don't
|
||||
/// bleed into one another.
|
||||
fn urls_in_text(text: &str) -> Vec<Url> {
|
||||
const TERMINATORS: &[char] = &['"', '\'', ',', ';', '(', ')', '[', ']', '{', '}', '<', '>'];
|
||||
|
||||
let mut out = Vec::new();
|
||||
for (idx, _) in text.match_indices("http") {
|
||||
let candidate = &text[idx..];
|
||||
if !candidate.starts_with("http://") && !candidate.starts_with("https://") {
|
||||
continue;
|
||||
}
|
||||
let end = candidate
|
||||
.find(|c: char| c.is_whitespace() || TERMINATORS.contains(&c))
|
||||
.unwrap_or(candidate.len());
|
||||
if let Ok(url) = Url::parse(&candidate[..end]) {
|
||||
out.push(url);
|
||||
}
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
/// Extracts the host of every http(s) URL embedded in `text`, ports stripped.
|
||||
/// Bracketed IPv6 hosts and placeholder fragments are skipped.
|
||||
pub(crate) fn hosts_in_text(text: &str) -> BTreeSet<String> {
|
||||
urls_in_text(text)
|
||||
.iter()
|
||||
.filter_map(|url| url.host_str())
|
||||
.filter(|host| is_usable_host(host))
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Collects a network allow-list entry for every remote MCP server `url`
|
||||
/// (http/https), so user-configured servers are reachable regardless of how,
|
||||
/// or whether, their credentials are provisioned. Https on the default port
|
||||
@@ -394,13 +511,14 @@ pub(crate) fn allow_entry_for_url(raw: &str) -> Option<String> {
|
||||
return None;
|
||||
}
|
||||
|
||||
let host = url.host_str()?;
|
||||
if host.is_empty() || host.starts_with('[') {
|
||||
return None;
|
||||
allow_entry_for_parsed(&url)
|
||||
}
|
||||
|
||||
fn allow_entry_for_parsed(url: &Url) -> Option<String> {
|
||||
let host = url.host_str().filter(|h| is_usable_host(h))?;
|
||||
|
||||
match url.port_or_known_default() {
|
||||
Some(443) if scheme == "https" => Some(host.to_string()),
|
||||
Some(443) if url.scheme() == "https" => Some(host.to_string()),
|
||||
Some(port) => Some(format!("{host}:{port}")),
|
||||
None => None,
|
||||
}
|
||||
@@ -489,12 +607,17 @@ pub(crate) fn render_mixin_document(
|
||||
serde_yaml::to_string(&mixin).context("Failed to serialize generated sandbox mixin")
|
||||
}
|
||||
|
||||
/// Renders the generated `coyote-mcp` mixin. Only proxy-managed credentials
|
||||
/// are declared. sbx does not materialize env vars for `proxyManaged: false`
|
||||
/// mixin credentials, so the rest are provisioned as custom secrets outside
|
||||
/// the mixin, and only their target hosts join the network allow list here.
|
||||
pub(crate) fn render_mixin_yaml(
|
||||
credentials: &[CredentialSpec],
|
||||
server_allow_entries: &[String],
|
||||
) -> Result<String> {
|
||||
let entries = credentials
|
||||
.iter()
|
||||
.filter(|c| c.proxy_managed)
|
||||
.map(|c| CredentialEntry {
|
||||
service: c.service_id.clone(),
|
||||
description: format!(
|
||||
@@ -510,14 +633,20 @@ pub(crate) fn render_mixin_yaml(
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut allow_entries: Vec<String> = server_allow_entries.to_vec();
|
||||
for credential in credentials.iter().filter(|c| !c.proxy_managed) {
|
||||
allow_entries.extend(credential.custom_allow_entries.iter().cloned());
|
||||
}
|
||||
|
||||
render_mixin_document(
|
||||
MCP_MIXIN_NAME,
|
||||
"Auto-generated by Coyote at launch: allows network egress to the user's remote MCP \
|
||||
servers and declares their credentials so Docker Sandboxes binds them (bindings are \
|
||||
approved on first interactive run). Values are pre-seeded from Coyote's vault via \
|
||||
`sbx secret set`.",
|
||||
approved on first interactive run). Proxy-injectable values are pre-seeded from \
|
||||
Coyote's vault via `sbx secret set`; the remaining secrets are provisioned as \
|
||||
placeholder-based custom secrets via `sbx secret set-custom`.",
|
||||
entries,
|
||||
server_allow_entries,
|
||||
&allow_entries,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -603,6 +732,11 @@ mod tests {
|
||||
assert_eq!(cred.service_id, "github-pat");
|
||||
assert_eq!(cred.env_var, "COYOTE_SECRET_GITHUB_PAT");
|
||||
assert!(cred.proxy_managed);
|
||||
assert!(
|
||||
cred.custom_hosts.is_empty(),
|
||||
"proxy-managed credentials are provisioned via `sbx secret set`, \
|
||||
not set-custom, so they carry no custom hosts"
|
||||
);
|
||||
assert_eq!(
|
||||
cred.inject,
|
||||
vec![InjectRule {
|
||||
@@ -839,6 +973,12 @@ mod tests {
|
||||
"secrets sharing an inject domain must both fall back to env"
|
||||
);
|
||||
assert!(creds.iter().all(|c| c.inject.is_empty()));
|
||||
assert!(
|
||||
creds
|
||||
.iter()
|
||||
.all(|c| c.custom_hosts == vec!["api.githubcopilot.com".to_string()]),
|
||||
"demoted secrets must derive their set-custom targets from the server url"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1018,21 +1158,162 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rendered_mixin_omits_inject_and_permissions_for_env_based_secrets() {
|
||||
fn rendered_mixin_drops_env_based_credentials() {
|
||||
let servers = servers(json!({
|
||||
"local": { "command": "run", "env": { "KEY": "{{NOTION_TOKEN}}" } }
|
||||
}));
|
||||
|
||||
let creds = collect_credentials(&servers).unwrap();
|
||||
assert_eq!(creds.len(), 1);
|
||||
assert!(!creds[0].proxy_managed, "precondition");
|
||||
assert!(
|
||||
creds[0].custom_hosts.is_empty(),
|
||||
"a stdio server with no URLs anywhere yields no derivable hosts"
|
||||
);
|
||||
|
||||
let yaml = render_mixin_yaml(&creds, &[]).unwrap();
|
||||
let value: serde_yaml::Value = serde_yaml::from_str(&yaml).unwrap();
|
||||
|
||||
let cred = &value["credentials"][0];
|
||||
assert_eq!(cred["apiKey"]["proxyManaged"].as_bool(), Some(false));
|
||||
assert!(cred["apiKey"].get("inject").is_none());
|
||||
assert!(
|
||||
value.get("credentials").is_none(),
|
||||
"sbx does not materialize env vars for proxyManaged:false mixin \
|
||||
credentials; declaring them would be dead config"
|
||||
);
|
||||
assert!(value.get("permissions").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hosts_in_text_extracts_hosts_and_strips_ports() {
|
||||
assert_eq!(
|
||||
hosts_in_text("https://api.example.com:8443/v1"),
|
||||
BTreeSet::from(["api.example.com".to_string()])
|
||||
);
|
||||
assert_eq!(
|
||||
hosts_in_text("see http://a.example.com/x and https://b.example.com/y"),
|
||||
BTreeSet::from(["a.example.com".to_string(), "b.example.com".to_string()])
|
||||
);
|
||||
assert_eq!(
|
||||
hosts_in_text("https://api.example.com/mcp?key={{KEY}}"),
|
||||
BTreeSet::from(["api.example.com".to_string()])
|
||||
);
|
||||
assert!(hosts_in_text("ws://sock.example.com/mcp").is_empty());
|
||||
assert!(hosts_in_text("qdrant.example.com:6333").is_empty());
|
||||
assert!(hosts_in_text("https://[::1]:8443/mcp").is_empty());
|
||||
assert!(hosts_in_text("httpserver is not a scheme").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hosts_in_text_terminates_urls_at_punctuation() {
|
||||
assert_eq!(
|
||||
hosts_in_text("https://a.example.com,https://b.example.com;https://c.example.com"),
|
||||
BTreeSet::from([
|
||||
"a.example.com".to_string(),
|
||||
"b.example.com".to_string(),
|
||||
"c.example.com".to_string()
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
hosts_in_text("(see https://docs.example.com)"),
|
||||
BTreeSet::from(["docs.example.com".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_secret_hosts_unions_url_host_and_scraped_urls() {
|
||||
let server = json!({
|
||||
"command": "run",
|
||||
"args": ["--endpoint", "https://api.vendor.example/v2"],
|
||||
"env": { "BASE_URL": "http://internal.example.com:8080/api" }
|
||||
});
|
||||
|
||||
let hosts = server_secret_hosts(&server);
|
||||
|
||||
assert_eq!(
|
||||
hosts.targets,
|
||||
BTreeSet::from([
|
||||
"api.vendor.example".to_string(),
|
||||
"internal.example.com".to_string()
|
||||
]),
|
||||
"set-custom targets are port-stripped"
|
||||
);
|
||||
assert_eq!(
|
||||
hosts.allow_entries,
|
||||
BTreeSet::from([
|
||||
"api.vendor.example".to_string(),
|
||||
"internal.example.com:8080".to_string()
|
||||
]),
|
||||
"allow entries keep non-default ports so the hosts stay reachable"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_secret_hosts_includes_non_http_url_host() {
|
||||
let server = json!({ "url": "ws://sock.example.com/mcp" });
|
||||
|
||||
let hosts = server_secret_hosts(&server);
|
||||
|
||||
assert_eq!(
|
||||
hosts.targets,
|
||||
BTreeSet::from(["sock.example.com".to_string()])
|
||||
);
|
||||
assert!(
|
||||
hosts.allow_entries.is_empty(),
|
||||
"non-http(s) urls have no spelling in the allow grammar"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_secret_hosts_skips_placeholder_hosts() {
|
||||
let server = json!({
|
||||
"url": "https://{{TENANT}}.example.com/mcp",
|
||||
"env": { "API_URL": "https://{{REGION}}.api.example.com/v1" }
|
||||
});
|
||||
|
||||
let hosts = server_secret_hosts(&server);
|
||||
|
||||
assert!(
|
||||
hosts.targets.is_empty() && hosts.allow_entries.is_empty(),
|
||||
"a host containing an unresolved placeholder must never reach \
|
||||
set-custom argv or the mixin allow list: {hosts:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn demoted_credential_hosts_are_unioned_into_allow() {
|
||||
let servers = servers(json!({
|
||||
"local": {
|
||||
"command": "run",
|
||||
"env": {
|
||||
"KEY": "{{TOKEN}}",
|
||||
"API_URL": "https://api.internal.example.com:8443/v1"
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
let creds = collect_credentials(&servers).unwrap();
|
||||
assert_eq!(creds.len(), 1);
|
||||
assert!(!creds[0].proxy_managed, "precondition");
|
||||
assert_eq!(
|
||||
creds[0].custom_hosts,
|
||||
vec!["api.internal.example.com".to_string()]
|
||||
);
|
||||
assert_eq!(
|
||||
creds[0].custom_allow_entries,
|
||||
vec!["api.internal.example.com:8443".to_string()],
|
||||
"allow entries keep the port that set-custom targets must strip"
|
||||
);
|
||||
|
||||
let yaml = render_mixin_yaml(&creds, &[]).unwrap();
|
||||
let value: serde_yaml::Value = serde_yaml::from_str(&yaml).unwrap();
|
||||
|
||||
assert!(value.get("credentials").is_none());
|
||||
assert_eq!(
|
||||
value["permissions"]["network"]["allow"][0].as_str(),
|
||||
Some("api.internal.example.com:8443"),
|
||||
"a demoted credential's derived hosts must still be reachable"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rendered_mixin_is_deterministic() {
|
||||
let servers = servers(json!({
|
||||
|
||||
+318
-7
@@ -1,9 +1,10 @@
|
||||
use std::env;
|
||||
use std::fs;
|
||||
use std::fs::{read_dir, read_to_string};
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use serde_yaml::Value;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
@@ -12,6 +13,7 @@ use crate::config::paths;
|
||||
const SBX_MIXIN_FILE_NAME: &str = "sbx-mixin.yaml";
|
||||
const SBX_MIXIN_FILE_SUFFIX: &str = ".sbx-mixin.yaml";
|
||||
const KIT_SPEC_FILE_NAME: &str = "spec.yaml";
|
||||
const MIXIN_FILES_DIR_NAME: &str = "files";
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DiscoveredMixin {
|
||||
@@ -34,33 +36,152 @@ impl DiscoveredMixin {
|
||||
pub fn wrap_mixin_as_kit(mixin_path: &Path) -> Result<PathBuf> {
|
||||
let bytes = fs::read(mixin_path)
|
||||
.with_context(|| format!("Failed to read sbx mixin {}", mixin_path.display()))?;
|
||||
wrap_mixin_bytes_as_kit(&bytes, &mixin_path.display().to_string())
|
||||
let label = mixin_path.display().to_string();
|
||||
|
||||
let files = mixin_path
|
||||
.parent()
|
||||
.map(|p| p.join(MIXIN_FILES_DIR_NAME))
|
||||
.filter(|p| p.is_dir())
|
||||
.map(|dir| collect_staged_files(&dir))
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
|
||||
stage_kit(&bytes, &files, &label)
|
||||
}
|
||||
|
||||
pub fn wrap_mixin_bytes_as_kit(bytes: &[u8], label: &str) -> Result<PathBuf> {
|
||||
stage_kit(bytes, &[], label)
|
||||
}
|
||||
|
||||
struct StagedFile {
|
||||
relpath: PathBuf,
|
||||
mode: u32,
|
||||
bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
fn stage_kit(spec_bytes: &[u8], files: &[StagedFile], label: &str) -> Result<PathBuf> {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(bytes);
|
||||
hasher.update(spec_bytes);
|
||||
for f in files {
|
||||
let rel_str = f.relpath.to_str().ok_or_else(|| {
|
||||
anyhow!(
|
||||
"Non-UTF-8 path inside mixin {MIXIN_FILES_DIR_NAME}/: {}",
|
||||
f.relpath.display()
|
||||
)
|
||||
})?;
|
||||
hasher.update(b"\0COYOTE_MIXIN_FILE\0");
|
||||
hasher.update((rel_str.len() as u64).to_le_bytes());
|
||||
hasher.update(rel_str.as_bytes());
|
||||
hasher.update(f.mode.to_le_bytes());
|
||||
hasher.update((f.bytes.len() as u64).to_le_bytes());
|
||||
hasher.update(&f.bytes);
|
||||
}
|
||||
let hash = format!("{:x}", hasher.finalize());
|
||||
|
||||
let kit_dir = paths::sbx_mixin_kits_dir().join(&hash);
|
||||
let spec_path = kit_dir.join(KIT_SPEC_FILE_NAME);
|
||||
let files_dst = kit_dir.join(MIXIN_FILES_DIR_NAME);
|
||||
|
||||
if let Ok(existing) = fs::read(&spec_path)
|
||||
&& existing == bytes
|
||||
{
|
||||
let spec_matches = fs::read(&spec_path).is_ok_and(|existing| existing == spec_bytes);
|
||||
let files_ready = files.is_empty() || files_dst.is_dir();
|
||||
if spec_matches && files_ready {
|
||||
return Ok(kit_dir);
|
||||
}
|
||||
|
||||
fs::create_dir_all(&kit_dir)
|
||||
.with_context(|| format!("Failed to create mixin kit dir {}", kit_dir.display()))?;
|
||||
fs::write(&spec_path, bytes)
|
||||
fs::write(&spec_path, spec_bytes)
|
||||
.with_context(|| format!("Failed to write {}", spec_path.display()))?;
|
||||
|
||||
if !files.is_empty() {
|
||||
if files_dst.exists() {
|
||||
fs::remove_dir_all(&files_dst).with_context(|| {
|
||||
format!(
|
||||
"Failed to clear stale mixin files at {}",
|
||||
files_dst.display()
|
||||
)
|
||||
})?;
|
||||
}
|
||||
for f in files {
|
||||
let dst = files_dst.join(&f.relpath);
|
||||
if let Some(parent) = dst.parent() {
|
||||
fs::create_dir_all(parent)
|
||||
.with_context(|| format!("Failed to create dir {}", parent.display()))?;
|
||||
}
|
||||
fs::write(&dst, &f.bytes)
|
||||
.with_context(|| format!("Failed to write staged mixin file {}", dst.display()))?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
fs::set_permissions(&dst, fs::Permissions::from_mode(f.mode))
|
||||
.with_context(|| format!("Failed to set mode on {}", dst.display()))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
debug!("Wrapped mixin {label} as kit at {}", kit_dir.display());
|
||||
|
||||
Ok(kit_dir)
|
||||
}
|
||||
|
||||
fn collect_staged_files(root: &Path) -> Result<Vec<StagedFile>> {
|
||||
let mut out = Vec::new();
|
||||
walk_staged_files(root, Path::new(""), &mut out)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn walk_staged_files(abs_dir: &Path, rel_dir: &Path, out: &mut Vec<StagedFile>) -> Result<()> {
|
||||
let rd = fs::read_dir(abs_dir)
|
||||
.with_context(|| format!("Failed to read mixin files dir {}", abs_dir.display()))?;
|
||||
let mut entries: Vec<_> = rd
|
||||
.collect::<io::Result<Vec<_>>>()
|
||||
.with_context(|| format!("Failed to iterate mixin files dir {}", abs_dir.display()))?;
|
||||
entries.sort_by_key(|e| e.file_name());
|
||||
|
||||
for entry in entries {
|
||||
let file_type = entry
|
||||
.file_type()
|
||||
.with_context(|| format!("Failed to stat {}", entry.path().display()))?;
|
||||
let abs = entry.path();
|
||||
let rel = rel_dir.join(entry.file_name());
|
||||
|
||||
if file_type.is_symlink() {
|
||||
bail!(
|
||||
"Symlinks are not allowed inside a mixin {MIXIN_FILES_DIR_NAME}/ tree: {}",
|
||||
abs.display()
|
||||
);
|
||||
}
|
||||
|
||||
if file_type.is_dir() {
|
||||
walk_staged_files(&abs, &rel, out)?;
|
||||
} else if file_type.is_file() {
|
||||
let bytes = fs::read(&abs)
|
||||
.with_context(|| format!("Failed to read staged mixin file {}", abs.display()))?;
|
||||
let mode = staged_file_mode(&entry)?;
|
||||
out.push(StagedFile {
|
||||
relpath: rel,
|
||||
mode,
|
||||
bytes,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn staged_file_mode(entry: &fs::DirEntry) -> Result<u32> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let meta = entry
|
||||
.metadata()
|
||||
.with_context(|| format!("Failed to stat {}", entry.path().display()))?;
|
||||
Ok(meta.permissions().mode() & 0o777)
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn staged_file_mode(_entry: &fs::DirEntry) -> Result<u32> {
|
||||
Ok(0o644)
|
||||
}
|
||||
|
||||
pub fn discover() -> Result<Vec<DiscoveredMixin>> {
|
||||
let mut out = Vec::new();
|
||||
|
||||
@@ -556,6 +677,196 @@ network:
|
||||
"kit_path should not return the original file path"
|
||||
);
|
||||
}
|
||||
|
||||
fn write_staged_file(mixin: &Path, rel: &str, content: &[u8]) {
|
||||
let dst = mixin.parent().unwrap().join(MIXIN_FILES_DIR_NAME).join(rel);
|
||||
fs::create_dir_all(dst.parent().unwrap()).unwrap();
|
||||
fs::write(&dst, content).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn wrap_mixin_as_kit_copies_sibling_files_tree_into_kit() {
|
||||
let _guard = TestCacheDirGuard::new();
|
||||
let mixin = write_mixin("files-copy", "kind: mixin\nname: probe\n");
|
||||
write_staged_file(&mixin, "home/hello.md", b"# hello\n");
|
||||
write_staged_file(&mixin, "home/nested/deep.txt", b"deep\n");
|
||||
|
||||
let kit_dir = wrap_mixin_as_kit(&mixin).unwrap();
|
||||
|
||||
assert!(kit_dir.join("spec.yaml").exists());
|
||||
let files_root = kit_dir.join(MIXIN_FILES_DIR_NAME);
|
||||
assert!(files_root.is_dir(), "kit dir must contain a files/ tree");
|
||||
assert_eq!(
|
||||
fs::read(files_root.join("home/hello.md")).unwrap(),
|
||||
b"# hello\n"
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read(files_root.join("home/nested/deep.txt")).unwrap(),
|
||||
b"deep\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn wrap_mixin_as_kit_hash_changes_when_a_staged_file_is_edited() {
|
||||
let _guard = TestCacheDirGuard::new();
|
||||
let mixin = write_mixin("files-hash-content", "kind: mixin\nname: probe\n");
|
||||
write_staged_file(&mixin, "home/note.md", b"before\n");
|
||||
let kit_before = wrap_mixin_as_kit(&mixin).unwrap();
|
||||
|
||||
write_staged_file(&mixin, "home/note.md", b"after\n");
|
||||
let kit_after = wrap_mixin_as_kit(&mixin).unwrap();
|
||||
|
||||
assert_ne!(
|
||||
kit_before, kit_after,
|
||||
"editing a staged file must invalidate the kit hash"
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read(kit_after.join("files/home/note.md")).unwrap(),
|
||||
b"after\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn wrap_mixin_as_kit_hash_changes_when_a_staged_file_is_added() {
|
||||
let _guard = TestCacheDirGuard::new();
|
||||
let mixin = write_mixin("files-hash-added", "kind: mixin\nname: probe\n");
|
||||
write_staged_file(&mixin, "home/one.md", b"one\n");
|
||||
let kit_before = wrap_mixin_as_kit(&mixin).unwrap();
|
||||
|
||||
write_staged_file(&mixin, "home/two.md", b"two\n");
|
||||
let kit_after = wrap_mixin_as_kit(&mixin).unwrap();
|
||||
|
||||
assert_ne!(
|
||||
kit_before, kit_after,
|
||||
"adding a staged file must invalidate the kit hash"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn wrap_mixin_as_kit_hash_unchanged_when_no_files_dir() {
|
||||
let _guard = TestCacheDirGuard::new();
|
||||
let content = "kind: mixin\nname: legacy\n";
|
||||
let mixin = write_mixin("legacy-no-files", content);
|
||||
|
||||
let with_helper = wrap_mixin_as_kit(&mixin).unwrap();
|
||||
let bytes_only = wrap_mixin_bytes_as_kit(content.as_bytes(), "legacy").unwrap();
|
||||
|
||||
assert_eq!(
|
||||
with_helper, bytes_only,
|
||||
"mixins without a sibling files/ must keep the legacy bytes-only hash to reuse existing cache dirs"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn wrap_mixin_as_kit_ignores_sibling_files_that_is_not_a_directory() {
|
||||
let _guard = TestCacheDirGuard::new();
|
||||
let content = "kind: mixin\nname: probe\n";
|
||||
let mixin = write_mixin("files-not-a-dir", content);
|
||||
fs::write(mixin.parent().unwrap().join(MIXIN_FILES_DIR_NAME), b"decoy").unwrap();
|
||||
|
||||
let wrapped = wrap_mixin_as_kit(&mixin).unwrap();
|
||||
let bytes_only = wrap_mixin_bytes_as_kit(content.as_bytes(), "probe").unwrap();
|
||||
|
||||
assert_eq!(
|
||||
wrapped, bytes_only,
|
||||
"a regular file named files must be ignored, not staged"
|
||||
);
|
||||
assert!(!wrapped.join(MIXIN_FILES_DIR_NAME).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn wrap_mixin_as_kit_rebuilds_files_when_cache_dir_missing_files_tree() {
|
||||
let _guard = TestCacheDirGuard::new();
|
||||
let mixin = write_mixin("files-rebuild", "kind: mixin\nname: probe\n");
|
||||
write_staged_file(&mixin, "home/hello.md", b"hi\n");
|
||||
|
||||
let kit_dir = wrap_mixin_as_kit(&mixin).unwrap();
|
||||
let files_dst = kit_dir.join(MIXIN_FILES_DIR_NAME);
|
||||
fs::remove_dir_all(&files_dst).unwrap();
|
||||
assert!(!files_dst.exists());
|
||||
|
||||
let kit_again = wrap_mixin_as_kit(&mixin).unwrap();
|
||||
|
||||
assert_eq!(kit_again, kit_dir, "kit path is content-addressed");
|
||||
assert!(
|
||||
files_dst.is_dir(),
|
||||
"a partial cache (spec present, files/ missing) must be rebuilt"
|
||||
);
|
||||
assert_eq!(fs::read(files_dst.join("home/hello.md")).unwrap(), b"hi\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn wrap_mixin_as_kit_deterministic_with_staged_files() {
|
||||
let _guard = TestCacheDirGuard::new();
|
||||
let content = "kind: mixin\nname: probe\n";
|
||||
let mixin_one = write_mixin("determ-1", content);
|
||||
write_staged_file(&mixin_one, "home/note.md", b"same\n");
|
||||
let mixin_two = write_mixin("determ-2", content);
|
||||
write_staged_file(&mixin_two, "home/note.md", b"same\n");
|
||||
|
||||
let kit_a = wrap_mixin_as_kit(&mixin_one).unwrap();
|
||||
let kit_b = wrap_mixin_as_kit(&mixin_two).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
kit_a, kit_b,
|
||||
"identical spec+files must produce the same content-addressed kit dir"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
#[serial]
|
||||
fn wrap_mixin_as_kit_rejects_symlinks_inside_files_tree() {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let _guard = TestCacheDirGuard::new();
|
||||
let mixin = write_mixin("files-symlink", "kind: mixin\nname: probe\n");
|
||||
let files_dir = mixin.parent().unwrap().join(MIXIN_FILES_DIR_NAME);
|
||||
fs::create_dir_all(&files_dir).unwrap();
|
||||
let target = files_dir.join("target.txt");
|
||||
fs::write(&target, b"real").unwrap();
|
||||
symlink(&target, files_dir.join("link.txt")).unwrap();
|
||||
|
||||
let err = wrap_mixin_as_kit(&mixin).unwrap_err();
|
||||
let msg = format!("{err:#}");
|
||||
assert!(
|
||||
msg.contains("Symlinks are not allowed"),
|
||||
"expected symlink rejection, got: {msg}"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
#[serial]
|
||||
fn wrap_mixin_as_kit_preserves_executable_bit() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let _guard = TestCacheDirGuard::new();
|
||||
let mixin = write_mixin("files-exec", "kind: mixin\nname: probe\n");
|
||||
write_staged_file(&mixin, "bin/run.sh", b"#!/bin/sh\necho hi\n");
|
||||
let src = mixin
|
||||
.parent()
|
||||
.unwrap()
|
||||
.join(MIXIN_FILES_DIR_NAME)
|
||||
.join("bin/run.sh");
|
||||
fs::set_permissions(&src, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let kit_dir = wrap_mixin_as_kit(&mixin).unwrap();
|
||||
let dst = kit_dir.join("files/bin/run.sh");
|
||||
let mode = fs::metadata(&dst).unwrap().permissions().mode() & 0o777;
|
||||
|
||||
assert_eq!(
|
||||
mode, 0o755,
|
||||
"executable bit must survive the copy into the kit dir"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+889
-60
File diff suppressed because it is too large
Load Diff
+29
-1
@@ -35,6 +35,7 @@ use nu_ansi_term::Color;
|
||||
use serde_json::Value;
|
||||
use std::borrow::Cow;
|
||||
use std::collections::VecDeque;
|
||||
use std::io;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::{LazyLock, Mutex, OnceLock};
|
||||
use std::{cmp, env, path::PathBuf, process};
|
||||
@@ -45,7 +46,7 @@ pub static CODE_BLOCK_RE: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"(?ms)```\w*(.*)```").unwrap());
|
||||
pub static THINK_TAG_RE: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"(?s)^\s*<think>.*?</think>(\s*|$)").unwrap());
|
||||
pub static IS_STDOUT_TERMINAL: LazyLock<bool> = LazyLock::new(|| std::io::stdout().is_terminal());
|
||||
pub static IS_STDOUT_TERMINAL: LazyLock<bool> = LazyLock::new(|| io::stdout().is_terminal());
|
||||
pub static HEADLESS: AtomicBool = AtomicBool::new(false);
|
||||
pub static ACP_SERVER: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
@@ -133,6 +134,33 @@ pub fn parse_bool(value: &str) -> Option<bool> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn drain_stale_tty_input() {
|
||||
use crossterm::event::{poll, read};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
if !io::stdin().is_terminal() {
|
||||
return;
|
||||
}
|
||||
|
||||
if crossterm::terminal::enable_raw_mode().is_err() {
|
||||
return;
|
||||
}
|
||||
|
||||
let deadline = Instant::now() + Duration::from_millis(100);
|
||||
while Instant::now() < deadline {
|
||||
match poll(Duration::from_millis(10)) {
|
||||
Ok(true) => {
|
||||
if read().is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
|
||||
let _ = crossterm::terminal::disable_raw_mode();
|
||||
}
|
||||
|
||||
pub fn estimate_token_length(text: &str) -> usize {
|
||||
let weighted: usize = text.chars().map(|c| if c.is_ascii() { 1 } else { 2 }).sum();
|
||||
weighted.div_ceil(4)
|
||||
|
||||
@@ -54,20 +54,6 @@ pub async fn expand_glob_paths<T: AsRef<str>>(
|
||||
Ok(new_paths)
|
||||
}
|
||||
|
||||
pub fn clear_dir(dir: &Path) -> Result<()> {
|
||||
for entry in fs::read_dir(dir)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
|
||||
if path.is_dir() {
|
||||
fs::remove_dir_all(&path)?;
|
||||
} else {
|
||||
fs::remove_file(&path)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn list_file_names<T: AsRef<Path>>(dir: T, ext: &str) -> Vec<String> {
|
||||
match fs::read_dir(dir.as_ref()) {
|
||||
Ok(rd) => {
|
||||
|
||||
@@ -12,6 +12,7 @@ pub use utils::prompt_provider_choice;
|
||||
|
||||
use crate::cli::Cli;
|
||||
use crate::config::AppConfig;
|
||||
use crate::utils::drain_stale_tty_input;
|
||||
use crate::vault::utils::ensure_password_file_initialized;
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use fancy_regex::Regex;
|
||||
@@ -151,6 +152,7 @@ impl Vault {
|
||||
"Vault management is disabled in sandbox mode. Use `coyote --add-secret` on your host."
|
||||
);
|
||||
}
|
||||
drain_stale_tty_input();
|
||||
let secret_value = Password::new("Enter the secret value:")
|
||||
.with_validator(required!())
|
||||
.with_display_mode(PasswordDisplayMode::Masked)
|
||||
@@ -190,6 +192,7 @@ impl Vault {
|
||||
"Vault management is disabled in sandbox mode. Use `coyote --add-secret` on your host."
|
||||
);
|
||||
}
|
||||
drain_stale_tty_input();
|
||||
let secret_value = Password::new("Enter the secret value:")
|
||||
.with_validator(required!())
|
||||
.with_display_mode(PasswordDisplayMode::Masked)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::config::ensure_parent_exists;
|
||||
use crate::sandbox::{SANDBOX_ENV_FLAG, sandbox_secret_env_var};
|
||||
use crate::utils::drain_stale_tty_input;
|
||||
use crate::vault::{SECRET_RE, Vault};
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
@@ -68,6 +69,7 @@ pub fn create_vault_password_file(vault: &mut Vault) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
drain_stale_tty_input();
|
||||
let ans = Confirm::new(
|
||||
format!(
|
||||
"The configured password file '{}' is empty. Create a password?",
|
||||
@@ -107,6 +109,7 @@ pub fn create_vault_password_file(vault: &mut Vault) -> Result<()> {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
drain_stale_tty_input();
|
||||
let ans = Confirm::new("No password file configured. Do you want to create one now?")
|
||||
.with_default(true)
|
||||
.prompt()?;
|
||||
@@ -185,6 +188,7 @@ pub fn create_vault_password_file(vault: &mut Vault) -> Result<()> {
|
||||
}
|
||||
|
||||
pub fn prompt_provider_choice() -> Result<Option<SupportedProvider>> {
|
||||
drain_stale_tty_input();
|
||||
let choices = vec![
|
||||
"local - encrypted file on this machine",
|
||||
"aws_secrets_manager - AWS Secrets Manager",
|
||||
|
||||
Reference in New Issue
Block a user