Compare commits
41
Commits
94ede264e5
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7b37eb4602 | ||
|
|
40996a06fe | ||
|
|
00a21ee777 | ||
|
|
016f2654e4 | ||
|
|
9a1d00f5e6 | ||
|
|
a14c768f9a | ||
|
|
c102da5665 | ||
|
|
4402d254f6 | ||
|
|
02974c8abc | ||
|
|
9f7eeb7dc6 | ||
|
|
f3d44212d5 | ||
|
|
f0661b4ea4 | ||
|
|
0946e3ec64 | ||
|
|
65e6249adb | ||
|
|
18c2cfeb41 | ||
|
|
50d2a74e80 | ||
|
|
ea001ade7a | ||
|
|
baa45970da | ||
|
|
5039b74926 | ||
|
|
176a81412a | ||
|
|
cebc32f70a | ||
|
|
d3914955e2 | ||
|
|
a8d730cf01 | ||
|
|
cf638305e6 | ||
|
|
3601faa969 | ||
|
|
e4c5f42a25 | ||
|
|
08dddb09fb | ||
|
|
f323c919f5 | ||
|
|
544a6bbbbc | ||
|
|
772c19f2bd | ||
|
|
1e15bc31d5 | ||
|
|
c170d08654 | ||
|
|
c707aaf3ee | ||
|
|
2d9829106d | ||
|
|
3d24719a71 | ||
|
|
290f6b257f | ||
|
|
e7811a6b87 | ||
|
|
c0224e20cb | ||
|
|
92d9464b38 | ||
|
|
a92ebb5b94 | ||
|
|
5711432ac4 |
@@ -0,0 +1 @@
|
||||
assets/config-template.yaml text eol=lf
|
||||
@@ -166,6 +166,9 @@ jobs:
|
||||
os: ubuntu-latest
|
||||
use-cross: true
|
||||
cargo-flags: ''
|
||||
- target: aarch64-unknown-linux-gnu
|
||||
os: ubuntu-24.04-arm
|
||||
cargo-flags: ''
|
||||
- target: aarch64-apple-darwin
|
||||
os: macos-latest
|
||||
use-cross: true
|
||||
@@ -253,7 +256,7 @@ jobs:
|
||||
run: echo "BUILD_CMD=cross" >> $GITHUB_ENV
|
||||
|
||||
- name: Install latest LLVM/Clang
|
||||
if: matrix.os == 'ubuntu-latest'
|
||||
if: startsWith(matrix.os, 'ubuntu')
|
||||
run: |
|
||||
wget https://apt.llvm.org/llvm.sh
|
||||
chmod +x llvm.sh
|
||||
|
||||
+199
@@ -1,3 +1,202 @@
|
||||
## v0.10.1 (2026-08-31)
|
||||
|
||||
### Fix
|
||||
|
||||
- make binary shims for custom tools cross-device compatible so users can't accidentally break sandboxes via `sbx cp ~/.config/coyote <sbx-name>:/home/agent/.config`
|
||||
|
||||
## v0.10.0 (2026-08-29)
|
||||
|
||||
### BREAKING CHANGE
|
||||
|
||||
- invocations using --prompt <text> must switch to
|
||||
--temp-role <text>; clap rejects the old flag loudly.
|
||||
|
||||
### Feat
|
||||
|
||||
- Support Linux ARM64 GNU
|
||||
- Note that duckdb RAG driver is unavailable on MUSL Linux builds when initializing a RAG so users know when using the binary, not just based on docs
|
||||
- updated coyote installation scripts to detect when gnu is installable
|
||||
- upgraded to v2 mixin schema
|
||||
- improved first-time run experience and included a templated configuration file that now has comments like the config.example.yaml so users don't have to go to the repo to see all the knobs
|
||||
- **TASK-005**: carry the quality bar through sisyphus and architect
|
||||
- **TASK-004**: reviewer routing — code-reviewer quality-bar resolution, domain linter pass, surface-skill routing, rigor folding; file-reviewer surface-skill whitelist + convention/correctness marker
|
||||
- **TASK-003**: add surface skills batch B — worker-review, iac-review, migration-review, cicd-review
|
||||
- **TASK-002**: add surface skills batch A — rest-api-review, cli-review, library-review
|
||||
- **TASK-001**: add rigor/surfaces declaration layer to planning skills
|
||||
- **repl**: color .info mcp-server verdicts and complete only running servers
|
||||
- **cli**: rename mcp_config asset category to mcp-config with snake_case alias
|
||||
- create a new probe agent to probe code verifications using usage-pattern testing
|
||||
- Add in the web_search_coyote tool where helpful
|
||||
- **mcp**: add .info mcp-server, .set mcp_tools, and filtered-server listing to the REPL
|
||||
- **mcp**: enforce per-server tool allowlists across runtime, jobs, agents, and graph nodes
|
||||
- **mcp**: add mcp_tools allowlist config surfaces across roles, sessions, agents, graphs, and skills
|
||||
- **mcp**: add per-server tool allowlist policy module and allowedTools config field
|
||||
- support mcp.json in the root of bundle repos as well as in the legacy functions directory
|
||||
- prefer ~/.config/coyote/mcp.json for the user-scope MCP config
|
||||
- claude and openai native web search via web_search_coyote
|
||||
- **jobs**: node-local job ownership and capability-gated job__* visibility
|
||||
- **graph**: support max_concurrent_jobs at the graph level
|
||||
- **jobs**: allow uncapped collect via full_result
|
||||
- **jobs**: exempt polling tools from loop tracker and hint on unchanged checks
|
||||
- **supervisor**: push agent completion notifications to the spawning context
|
||||
- **jobs**: push background-job completion notifications via per-context queue
|
||||
- inject background-jobs prompt guidance when jobs are enabled
|
||||
- add background job runner, job__* handlers, and start gates
|
||||
- generalize supervisor registry to TaskHandle enum with job scaffolding, kill discipline, and max_concurrent_jobs config
|
||||
- run an advisory observability pass after implementation in sisyphus
|
||||
- add an observability-review skill for post-implementation monitoring analysis
|
||||
- check under- and over-logging in the code review gate
|
||||
- calibrate logging registers in the code-writing agents
|
||||
- add a logging-discipline skill for calibrating log output to repo conventions
|
||||
- **cli**: rename --prompt to --temp-role
|
||||
- complete --filter and --force on the first .install argument
|
||||
- **mcp**: bound tool-result passthrough and surface resource audience annotations
|
||||
- **mcp**: add mcp_prompt meta-tool and harden prompt display rendering
|
||||
- **repl**: add .prompt command with live staged tab-completion
|
||||
- **mcp**: add mcp_read meta-tool for resource reads
|
||||
- **mcp**: gate meta-function emission on advertised server capabilities
|
||||
- **mcp**: add render.rs content policy (text paging, pattern filter, blob spill)
|
||||
- **mcp**: extend the server catalog to resources, templates, and prompts
|
||||
- complete --filter and --force on the first .install argument
|
||||
- run design interviews as grilling frontier rounds across the planning agents
|
||||
- add a grilling skill for frontier-round design interviews
|
||||
- add an on-demand architecture-reviewer agent for deepening scans
|
||||
- add a codebase-design skill with the deep-module design vocabulary
|
||||
- add a feedback-loop-first diagnosing-bugs skill to the coding suite
|
||||
- add a Fowler code-smell baseline to the code-review skill
|
||||
- flag duplicate helpers in code reviews with a repo-wide DRY check
|
||||
- add a transactional-integrity review skill to the code review gate
|
||||
- add an operational-history prior-art lane to the code-reviewer agent
|
||||
- support name=value macro arguments with variable tab completion
|
||||
- add --help guides to the .install and .uninstall REPL commands
|
||||
- expand owner/repo shorthand for --install with a --git-host flag
|
||||
- remove the deprecated --install-from flag and .install remote form
|
||||
- rename install flags and unify .install dispatch
|
||||
- add --uninstall and .uninstall for installed bundles
|
||||
- add --update-bundle with provenance-aware conflict handling
|
||||
- add --list-bundles and .list bundles with drift detection
|
||||
- record bundle provenance when installing from remote repos
|
||||
- add bundle provenance store
|
||||
- parse bundle manifests and capture resolved SHAs for remote installs
|
||||
- created a new comment-discipline skill for the built in sisyphus suite
|
||||
- created a dedicated git_command tool to tighten tool calling permissions in the git-master skill
|
||||
- Added a new security review step to the code writing quality gates
|
||||
- addressed review comments
|
||||
- add --no-workspace-macros opt-out for workspace macro loading
|
||||
- execute non-isolated macros on the live REPL context
|
||||
- surface macros as first-class custom commands in the REPL
|
||||
- add lazy macro resolver with two-dir discovery and per-macro states
|
||||
- add enabled_macros config field at global, role, agent, and session levels
|
||||
- add description and isolated fields to Macro struct
|
||||
- Dynamically detect RAG embedding model dimension for any given model
|
||||
- Support auto confirmation for gatekeeper agents
|
||||
- retry LLM API calls once after 401 by force-refreshing the OAuth token
|
||||
- identity-aware rejected-token marker for LLM OAuth cache
|
||||
- typed ApiStatusError carrying HTTP status through LLM client errors
|
||||
- per-request OAuth token injection with mid-session refresh for HTTP MCP servers
|
||||
- reason-specific warnings for MCP servers that fail OAuth at startup
|
||||
- Installed duckdb into the coyote image
|
||||
- Support managing MCP servers from the CLI directly
|
||||
- append new built-in rag__query function to RAG contexts to allow further querying by LLMs
|
||||
- support static file bundling with sbx-mixins
|
||||
- **rag**: offer the storage driver when an agent initializes its RAG
|
||||
- simplified the duckdb selection prompt
|
||||
- **rag**: let several Coyote processes query one duckdb RAG at once
|
||||
- **rag**: support string and UUID Qdrant point IDs
|
||||
- **rag**: create the API key secret inline in the attach wizard
|
||||
- let workflow rag nodes select a RAG driver
|
||||
- improved wording and heuristic detection for sisyphus suite of agents
|
||||
- upgraded to sbx kit v2 spec for improved integration
|
||||
- **rag**: add attach-only Qdrant provider, attach wizard and sandbox wiring
|
||||
- **rag**: add DuckDB provider behind the RAG driver abstraction
|
||||
- **rag**: add driver/attached fields, validation floors and force-reingest
|
||||
- **mcp**: send RFC 8707 resource indicator in OAuth flows
|
||||
- Added loaded indicators to .list tools/mcp-servers/skills
|
||||
- hide .recover from tab completions when no session is active
|
||||
- add a new .recover command for sessions to recover from errors
|
||||
- integrated the git-ssh-sign kit into the coyote sandbox kit
|
||||
|
||||
### Fix
|
||||
|
||||
- Harden install scripts: detect libssl3 without ldconfig on PATH, survive noexec tmp dirs, and guard against partial curl|bash execution
|
||||
- ldconfig on Debian-based distros lives in /usr/sbin
|
||||
- Prefer GNU linux builds in install scripts for duckdb support, and gate duckdb support on linux hosts that are MUSL until MUSL support is added
|
||||
- **mcp**: omit declared-but-empty prompt/resource capabilities from .info mcp-server
|
||||
- **mcp**: annotate declared-but-empty prompt/resource capabilities in .info mcp-server
|
||||
- also support the .continue edge case for session crashing checkpointing
|
||||
- checkpoint sessions that crash for easy resuming
|
||||
- job__check ring buffer also collects file output for LLM_OUTPUT as well as stdout
|
||||
- **tools**: interactive-shell semantics and stderr capture in execute_command
|
||||
- **function**: gate test-only declaration appender behind cfg(test)
|
||||
- **graph**: gate unix-only test imports behind cfg(unix)
|
||||
- harden job runner lifecycle and whitelist conformance
|
||||
- **function**: floor tool-output truncation cut to a UTF-8 char boundary
|
||||
- **supervisor**: make agent__check a pure status probe that never consumes the handle
|
||||
- **supervisor**: surface finished-but-uncollected tasks in turn-end guardrail
|
||||
- fix grep "binary" errors when searching UTF-8 files with unicode characters like some of the Coyote source
|
||||
- **bundles**: harden the install pipeline for cross-platform correctness
|
||||
- **mcp**: harden the spill path for cross-platform correctness
|
||||
- **repl**: offer prompts in .list tab completion and rename its listing helpers
|
||||
- **mcp**: gate unix-only spill permission APIs for windows builds
|
||||
- harden the bundle lifecycle per code review
|
||||
- address code review findings on the bundle lifecycle
|
||||
- reserve category names, confirm fork-name collisions, report secrets on uninstall
|
||||
- make bundle provenance portable to Windows
|
||||
- user__ask should have been renamed to user__select in graph agent user interaction invocations
|
||||
- support tab completions for graph-based agents with variables as well as standard agents
|
||||
- surface macro parse errors on top-level invocation
|
||||
- render .list macros as a comfy-table instead of fixed-width columns
|
||||
- drain crossterm characters in zellij in kitty contexts to prevent DA1 responses from entering prompt
|
||||
- drain tty input when displaying inquire prompts to prevent unintentional escapes
|
||||
- breaking iwe MCP server changes with newest version
|
||||
- improved handling of non service-specific secrets using sbx custom-secrets
|
||||
- include tool output to LLM_OUTPUT in errors as well as stderr
|
||||
- prevent tmp-overwriting
|
||||
- Corrected a rare edge case on how tool files are generated during parallel executions
|
||||
- cosmetic fix after improved bash tool handling
|
||||
- Improved subagent escalation handling
|
||||
- latent parsing bugs in fs_patch and argc
|
||||
- Prevent infinite hangs in coder agent and implement timeouts for LLM API calls and interactive tools
|
||||
- allow nested italics inside bold spans in markdown renderer
|
||||
- properly handle OAuth refreshes
|
||||
- correct newline removal from fs_write and fs_patch
|
||||
- detect duplicate tool call IDs client-side before sending to Claude
|
||||
- **rag**: warn when a duckdb store is empty but files are indexed
|
||||
- **rag**: keep a local Qdrant off an ambient proxy
|
||||
- keep loopback and LAN traffic off an ambient proxy
|
||||
- **rag**: stop routing Qdrant requests through an ambient proxy
|
||||
- **rag**: treat a zero min_score as no floor on Qdrant searches
|
||||
- **rag**: address Copilot review findings on the driver abstraction
|
||||
- **rag**: delete the DuckDB write-ahead log alongside the store
|
||||
- **sandbox**: discover agent-scoped RAG mixin sidecars
|
||||
- **rag**: stop the attach wizard from silently accepting an empty collection
|
||||
- **rag**: fail loudly when a RAG's vault secret is missing
|
||||
- **rag**: serialize DuckDB extension installs to stop a Windows race
|
||||
- **rag**: emit an sbx kit v2 mixin and declare RAG credentials to the proxy
|
||||
- **rag**: install DuckDB vss and fts extensions when they are missing
|
||||
- don't output thinking blocks for claude-based models
|
||||
- additional edge case fix for duplicate tool call IDs in anthropic API calls
|
||||
- removed temperature modifier in librarian agent to mitigate invisible errors
|
||||
- strip reasoning blocks for structured LLM output in graph agents
|
||||
- prevent rare duplicate tool call IDs in long running claude prompts
|
||||
- agents inherit global reasoning effort if unset
|
||||
|
||||
### Refactor
|
||||
|
||||
- **function**: finish supervisor-to-agent vocabulary migration
|
||||
- **function**: rename agent-tool symbols out of supervisor vocabulary
|
||||
- Modified the naming of several generalized supervisor values
|
||||
- pulled out some imports to clean up the MCP render module a bit
|
||||
- **mcp**: centralize meta-function prefix predicates and fix list_tools pagination
|
||||
- Refactored some bundle const locations
|
||||
- drop the .install remote migration hint
|
||||
- drop the --install-from tombstone entirely
|
||||
- render .list agents and .list skills as comfy-tables
|
||||
- **rag**: discover driver_config secrets by grammar, not field name
|
||||
- **rag**: drop the hardcoded embedding model hint from attach
|
||||
- **rag**: interpolate every driver_config value, not just api_key
|
||||
- **rag**: extract RagProvider trait and add YamlProvider
|
||||
|
||||
## v0.8.3 (2026-08-03)
|
||||
|
||||
### Fix
|
||||
|
||||
Generated
+196
-162
File diff suppressed because it is too large
Load Diff
+3
-2
@@ -1,9 +1,9 @@
|
||||
[package]
|
||||
name = "coyote-ai"
|
||||
version = "0.8.3"
|
||||
version = "0.10.1"
|
||||
edition = "2024"
|
||||
authors = ["Alex Clarke <alex.j.tusa@gmail.com>"]
|
||||
description = "An all-in-one, batteries-included LLM runtime"
|
||||
description = "The batteries-included runtime for LLMs"
|
||||
keywords = ["chatgpt", "llm", "cli", "ai", "repl"]
|
||||
homepage = "https://github.com/Dark-Alex-17/coyote"
|
||||
repository = "https://github.com/Dark-Alex-17/coyote"
|
||||
@@ -142,6 +142,7 @@ arboard = { version = "3.3.0", default-features = false }
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
ctor = "1.0.13"
|
||||
pretty_assertions = "1.4.0"
|
||||
rmcp = { version = "3.1.2", features = ["server"] }
|
||||
serial_test = "3"
|
||||
|
||||
+1
-1
@@ -99,7 +99,7 @@ LABEL com.docker.sandboxes="templates" \
|
||||
com.docker.sandboxes.flavor="shell-docker" \
|
||||
com.docker.sandboxes.start-docker="true" \
|
||||
org.opencontainers.image.title="coyote" \
|
||||
org.opencontainers.image.description="An all-in-one, batteries-included LLM runtime: Shell Assistant, CLI & REPL mode, RAG, AI tools & agents, MCP servers, skills, and macros." \
|
||||
org.opencontainers.image.description="The batteries-included runtime for LLMs: Shell Assistant, CLI & REPL mode, RAG, AI tools & agents, MCP servers, skills, and macros." \
|
||||
org.opencontainers.image.source="https://github.com/Dark-Alex-17/coyote" \
|
||||
org.opencontainers.image.version="${COYOTE_VERSION}"
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Coyote: All-in-one, batteries-included LLM runtime
|
||||
# Coyote: The batteries-included runtime for LLMs
|
||||
|
||||

|
||||
[](https://crates.io/crates/coyote-ai)
|
||||
@@ -8,12 +8,16 @@
|
||||

|
||||
[](https://github.com/Dark-Alex-17/coyote/blob/main/LICENSE)
|
||||
|
||||
Coyote is an all-in-one, batteries-included, LLM runtime featuring Shell Assistant, CLI & REPL Mode, RAG, AI Tools &
|
||||
Agents, and more.
|
||||
Coyote is an **all-in-one, batteries-included LLM runtime** for building, running, and interacting with AI from your terminal.
|
||||
It brings together a Shell Assistant, CLI & REPL modes, RAG, tools, agents, MCP, skills, sandboxes, multi-agent workflows, and
|
||||
more in a single runtime.
|
||||
|
||||
Coyote comes ready to use with built-in agents, roles, macros, and tools, so you can get started without assembling an AI
|
||||
stack from scratch. When you want to extend it, entire bundles of agents, roles, macros, tools, MCP servers, and other
|
||||
configurations can be installed directly from any Git repository.
|
||||
|
||||
See [Bundles](https://github.com/Dark-Alex-17/coyote/wiki/Bundles) to learn how to create, install, and share Coyote bundles.
|
||||
|
||||
It is designed to include a number of useful agents, roles, macros, and more so users can get up and running with Coyote
|
||||
in as little time as possible. You can also install entire bundles of agents, roles, macros, tools, and MCP servers from
|
||||
any git repository. See [Sharing Configurations](https://github.com/Dark-Alex-17/coyote/wiki/Sharing-Configurations) for more information.
|
||||
|
||||

|
||||
|
||||
@@ -23,7 +27,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, 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.
|
||||
* [Bundles](https://github.com/Dark-Alex-17/coyote/wiki/Bundles): 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.
|
||||
@@ -39,8 +43,8 @@ Coming from [AIChat](https://github.com/sigoden/aichat)? Follow the [migration g
|
||||
* Models interact with each server through a compact set of capability-gated meta-tools: `mcp_search`/`mcp_describe` for discovery across tools, resources, and prompts, `mcp_invoke` for tool calls, `mcp_read` for paged and regex-filterable resource reads, and `mcp_prompt` for server-defined prompts. Binary content is spilled to disk instead of inlined, and oversized tool results are bounded before they reach the model.
|
||||
* Invoke server prompts yourself with `.prompt <server> <name> [key=value ...]` in the REPL, with live staged tab-completion (servers, then prompt names, then `key=` arguments), and discover them with `.list prompts`.
|
||||
* [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`).
|
||||
* 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.
|
||||
@@ -78,7 +82,7 @@ Coyote requires the following tools to be installed on your system:
|
||||
* **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`
|
||||
* `curl https://install.duckdb.org | bash`
|
||||
|
||||
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.
|
||||
|
||||
@@ -137,6 +137,15 @@ instructions: |
|
||||
Open questions, and a **Task breakdown** where **each task is sized to ~1 engineer-day** (decompose
|
||||
anything bigger NOW).
|
||||
|
||||
Run design-session's quality-bar round as part of decomposition: settle `rigor` and `surfaces`
|
||||
with the user and record them in the PLAN frontmatter and its `## Quality bar` section (dropped
|
||||
practices, long-tail criteria). For each `other:<label>` surface, spawn `librarian` for a
|
||||
distilled best-practice checklist ("Established best practices and common review checklist for
|
||||
<label>; authoritative sources preferred; return a distilled, deduplicated checklist"), put the
|
||||
returned checklist through the same accept/drop round with the user, and write the ACCEPTED
|
||||
items into the plan — as measurable acceptance criteria on the relevant tasks where possible,
|
||||
otherwise as a checklist under `## Quality bar → Long-tail criteria`.
|
||||
|
||||
Ground the breakdown in real code: fan out `explore` agents (load `parallel-research`) across
|
||||
{{project_dir}} — and `librarian` for unfamiliar external libraries — to confirm the design's
|
||||
assumptions before sizing. Do NOT guess file/symbol names — verify them.
|
||||
@@ -255,6 +264,10 @@ instructions: |
|
||||
- Do NOT diverge from the task's stated scope; if the plan is wrong, STOP and report back.
|
||||
|
||||
## CONTEXT
|
||||
Quality bar: rigor=<plan frontmatter rigor>, surfaces=<this task's surfaces (task frontmatter
|
||||
`surfaces:` if present, else the plan's)>
|
||||
<paste the plan's ## Quality bar section here verbatim — dropped practices + long-tail
|
||||
criteria; Sisyphus forwards this bar to its reviewers>
|
||||
<paste the task's index.md body and the relevant PLAN section here verbatim — plus any code
|
||||
snippets explore found showing the patterns to follow>
|
||||
"
|
||||
@@ -278,7 +291,9 @@ instructions: |
|
||||
this isolates THIS task's commits on the shared run branch from earlier tasks' work.
|
||||
|
||||
PLAN — acceptance criteria to check against:
|
||||
<paste the task index.md body + the relevant PLAN-<slug>.md section VERBATIM>"
|
||||
<paste the task index.md body + the relevant PLAN-<slug>.md section VERBATIM>
|
||||
<paste the plan's ## Quality bar section VERBATIM — recorded dropped practices are
|
||||
conformance facts, not divergences>"
|
||||
```
|
||||
|
||||
- **`ADVERSARIAL_REVIEW: DIVERGES`** → treat it as a blocker: resume the SAME Sisyphus session
|
||||
@@ -328,7 +343,11 @@ instructions: |
|
||||
5. **Close the task.** Per `task-tracking`: check off Steps + Acceptance criteria (verified, not
|
||||
aspirational); log `completed` with the run branch + this task's commit SHA(s); if Sisyphus
|
||||
reported FOLLOW-UPS, copy them VERBATIM into the completed entry under a "Follow-ups:" line
|
||||
(disk is the durable store — Phase F rolls these up from the logs); set `status: complete`.
|
||||
(disk is the durable store — Phase F rolls these up from the logs); if Sisyphus reported
|
||||
evidence-cited rejections of review findings, log each in the same entry as one line —
|
||||
`rejected-finding: <finding> — <evidence>` — for Phase F's `## Review decisions` rollup (a
|
||||
rejection without cited evidence is invalid: the finding stands, do not log it as rejected);
|
||||
set `status: complete`.
|
||||
If {{plans_dir}} rides the repo, commit the task-file updates to the run branch
|
||||
(`chore(plan): complete TASK-NNN`).
|
||||
|
||||
@@ -391,9 +410,17 @@ instructions: |
|
||||
the responsible Sisyphus session) before any PR exists.
|
||||
2. **Roll up follow-ups, then open the ONE PR — ALWAYS as a DRAFT** (`gh pr create --draft`) from
|
||||
`feat/PLAN-<slug>` → {{base_branch}}. First collect every "Follow-ups:" line from the completed
|
||||
tasks' `log.md` files. Title: `PLAN-<slug>: <design doc title>`. Body MUST contain, in order:
|
||||
tasks' `log.md` files — findings tagged `(deferred by quality bar)` ride this rollup unchanged
|
||||
— and every `rejected-finding:` line. Title: `PLAN-<slug>: <design doc title>`. Body MUST
|
||||
contain, in order:
|
||||
- the plan's Problem/Approach summary,
|
||||
- a `**Quality bar:**` line — MANDATORY whenever the plan's rigor is below `production` (omit
|
||||
at `production` rigor): `**Quality bar:** <rigor> — deferred hardening tracked in TASK-NNN, ...`,
|
||||
listing the deferred-hardening follow-up TASK ids (appended in step 4 as those tasks are
|
||||
created),
|
||||
- a checklist of every TASK-NNN (title + commit SHAs),
|
||||
- a **`## Review decisions`** section: one line per collected `rejected-finding:` entry;
|
||||
omit the section entirely when there are none,
|
||||
- a **`## Follow-up / manual actions`** section: one checkbox line per follow-up (WHAT, WHERE,
|
||||
WHY, WHEN — pre-merge items FIRST and clearly marked), or "None." if there are none. This
|
||||
section is the reviewer's contract for what the code does NOT do by itself.
|
||||
@@ -411,7 +438,8 @@ instructions: |
|
||||
`status: pending`, with the WHAT/WHERE/WHY/WHEN and which TASK-NNN surfaced it. Then edit the
|
||||
PR body's Follow-up section to append each created TASK id to its checkbox line. Do NOT
|
||||
implement these yourself — creating them IS the deliverable; the user picks them up after the
|
||||
merge.
|
||||
merge. Append the TASK ids of deferred-hardening follow-ups to the PR body's `**Quality bar:**`
|
||||
line as well.
|
||||
5. Set `PLAN-<slug>.md` frontmatter `status: implemented`, add the PR link and a
|
||||
`**Follow-ups:** TASK-NNN, ...` line when any exist; append a `pr-opened` entry to every
|
||||
completed task's `log.md`. If {{plans_dir}} rides the repo, commit these planning updates to
|
||||
@@ -476,6 +504,10 @@ instructions: |
|
||||
- Polling `agent__collect` on a running agent.
|
||||
- Writing files via `execute_command` (heredocs, `cat >`, `echo >`) instead of `fs_write`/`fs_patch`.
|
||||
- Losing a Sisyphus `session_id` or a follow-up to chat-only memory.
|
||||
- Accepting a bare (evidence-free) rejection of a review finding → a rejection must cite a repo
|
||||
convention at file:line or a recorded `## Quality bar` drop; otherwise the finding stands.
|
||||
- Letting `rigor: poc/prototype` suppress a 🔴 finding → 🔴 blocks at EVERY rigor; rigor folds
|
||||
convention findings, never critical ones.
|
||||
|
||||
## Hard blocks (NEVER)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
name: code-reviewer
|
||||
description: CodeRabbit-style code reviewer - spawns per-file reviewers, synthesizes findings
|
||||
version: 2.3.0
|
||||
version: 2.4.0
|
||||
|
||||
auto_continue: true
|
||||
max_auto_continues: 20
|
||||
@@ -23,6 +23,12 @@ variables:
|
||||
- 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: rigor
|
||||
description: Quality bar governing finding folding (poc | prototype | production)
|
||||
default: 'production'
|
||||
- name: surfaces
|
||||
description: Declared surfaces as a CSV (e.g. 'rest-api,db-migration'); empty = auto-detect from the diff
|
||||
default: ''
|
||||
- name: auto_confirm
|
||||
description: Auto-confirm command execution
|
||||
default: '1'
|
||||
@@ -49,13 +55,20 @@ instructions: |
|
||||
## Workflow
|
||||
|
||||
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, 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. **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).
|
||||
2. **Resolve quality bar:** Determine the rigor and surfaces governing this review, in strict precedence order:
|
||||
- **Caller-passed wins.** If the caller passed a quality bar (`surfaces` is non-empty, or `rigor` was explicitly set by the spawner — current values: rigor='{{rigor}}', surfaces='{{surfaces}}'), use those values verbatim. Provenance: `passed`.
|
||||
- **Else plan frontmatter.** If the repo's plans directory contains a `PLAN-*.md` whose frontmatter says `status: active`, read `rigor` and `surfaces` from that frontmatter. Provenance: `plan`.
|
||||
- **Else detect from the diff.** Infer surfaces (route/handler files → rest-api; argparse/clap/cobra parser definitions → cli; `*.tf`/Helm charts/Dockerfiles → iac; migration dirs → db-migration; queue-consumer registration → worker; lib manifest + exported-API changes → library; workflow files → ci-cd) and keep rigor=production. Provenance: `detected-default`.
|
||||
|
||||
Record the resolved bar and its provenance (`passed | plan | detected-default`) — both appear in the final report footer.
|
||||
3. **Parse changed files:** Extract the list of files from the diff
|
||||
4. **Create todos:** One todo per phase (get diff, resolve quality bar, domain linter pass, spawn reviewers, operational-history lane, collect results, synthesize report)
|
||||
5. **Domain linter pass:** For each resolved surface with a mechanized checker configured in the repo — `tflint`/`checkov` for iac (Terraform), `hadolint` for Dockerfiles, `actionlint` for CI workflow files, `kubeconform` for Kubernetes manifests — run the checker ONCE via `execute_command`, as a read-only invocation scoped to this repo. Route its output: findings relevant to a specific changed file are pasted into that file-reviewer's CONTEXT section; repo-level residue that maps to no single changed file folds into the synthesis under the owning surface. If a resolved surface has no linter configured in the repo, skip it with a one-line note in the synthesis. Never install linters and never write files in this pass.
|
||||
6. **Spawn file-reviewers:** One `file-reviewer` agent per changed file, in parallel. Apply the `delegation-protocol` structured prompt format.
|
||||
7. **Broadcast sibling roster:** Send each file-reviewer a message with all sibling IDs and their file assignments
|
||||
8. **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.
|
||||
9. **Collect all results:** Per `parallel-research`, do not poll. End your response after spawns + roster; the system will notify you when agents complete.
|
||||
10. **Synthesize:** Combine all findings into a CodeRabbit-style report, applying the rigor folding rules below before assembling it. 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
|
||||
|
||||
@@ -77,6 +90,21 @@ instructions: |
|
||||
- Load `code-review` and `ai-slop-remover` skills before reading any code
|
||||
- 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)
|
||||
- Load `logging-discipline` as well if this file's diff touches boundaries, error paths, background jobs, or state transitions
|
||||
- Load the surface skill(s) routed to this file from the table below. Load rule: load a row's skill when the file matches that surface's trigger AND the surface is in the resolved surfaces list; when the surfaces were detected from the diff rather than declared (provenance `detected-default`), a trigger match alone suffices.
|
||||
|
||||
| declared surface | skill loaded |
|
||||
|---|---|
|
||||
| `rest-api` | `rest-api-review` |
|
||||
| `grpc` (alias) | `rest-api-review` (gRPC section) |
|
||||
| `graphql` (alias) | `rest-api-review` (GraphQL section) |
|
||||
| `cli` | `cli-review` |
|
||||
| `library` | `library-review` |
|
||||
| `worker` | `worker-review` |
|
||||
| `iac` | `iac-review` |
|
||||
| `db-migration` | `migration-review` |
|
||||
| `ci-cd` | `cicd-review` |
|
||||
| `frontend` | no file-reviewer skill in v1 — note the declared surface in the synthesis; generic review + aspect skills still apply |
|
||||
|
||||
- Apply all loaded skill checklists to the diff
|
||||
- Use targeted fs_read with offset/limit; max 5 file reads
|
||||
- End with REVIEW_COMPLETE
|
||||
@@ -89,6 +117,11 @@ instructions: |
|
||||
## CONTEXT
|
||||
Project: {{project_dir}}
|
||||
File under review: <file_path>
|
||||
Rigor: <resolved rigor>
|
||||
Surfaces: <resolved surfaces list — note when detected rather than declared>
|
||||
|
||||
Linter output for this file (from the domain linter pass; omit when none):
|
||||
<linter findings relevant to this file>
|
||||
|
||||
Diff:
|
||||
<diff content for this file>
|
||||
@@ -97,6 +130,18 @@ instructions: |
|
||||
|
||||
Paste the actual diff hunk(s) inline — the reviewer can't see your context. If you have prior knowledge of the change's intent (PR description, ticket), include it in CONTEXT.
|
||||
|
||||
### Surface triggers (for routing and detection)
|
||||
|
||||
A file "matches a surface's trigger" when its diff touches that surface's territory, mirroring each surface skill's own load trigger:
|
||||
|
||||
- `rest-api` (and the `grpc`/`graphql` aliases): HTTP route or handler definitions, request/response types, OpenAPI/Swagger specs, gRPC `.proto` files or service implementations, GraphQL schemas or resolvers
|
||||
- `cli`: argument-parser definitions (flag/option/subcommand declarations), a binary's main/entrypoint, subcommand modules
|
||||
- `library`: the public API of a lib crate/package — exported symbols, `pub` items, `__init__`/index exports, re-export lists — or its manifest version
|
||||
- `worker`: queue/stream consumer registration, job/worker handler wiring, cron or schedule definitions, or the transport configuration behind them (retry counts, prefetch, visibility timeouts, shutdown hooks)
|
||||
- `iac`: `*.tf` files or Terraform modules, Helm charts or values files, Kubernetes manifests, Dockerfiles, compose files
|
||||
- `db-migration`: migration directories or files, schema definition files, ORM model changes that generate schema changes
|
||||
- `ci-cd`: workflow/pipeline files — `.github/workflows/*`, GitLab CI config, or equivalent pipeline definitions
|
||||
|
||||
## Sibling Roster Broadcast
|
||||
|
||||
After spawning ALL file-reviewers (collecting their IDs), send each one a message with the roster:
|
||||
@@ -117,6 +162,23 @@ instructions: |
|
||||
|
||||
Skip binary files and files with only whitespace changes.
|
||||
|
||||
## Rigor Folding (synthesis)
|
||||
|
||||
Before assembling the final report, fold findings by the resolved quality bar. Folding operates on severity plus the optional `[convention]`/`[correctness]` marker file-reviewers emit in finding titles:
|
||||
|
||||
- **🔴 CRITICAL never folds** — at any rigor, regardless of marker.
|
||||
- **`production`**: nothing folds; report every finding as-is.
|
||||
- **`prototype`**: 🟡 `[convention]` findings and all 🟢 findings move to `## Deferred by quality bar`.
|
||||
- **`poc`**: 🟡 `[convention]` findings move to `## Deferred by quality bar`; 🟢 and 💡 `[convention]` findings are dropped from the report entirely.
|
||||
|
||||
Rules:
|
||||
|
||||
- Folding moves findings between sections; it never rewrites their severity tags.
|
||||
- The `## Deferred by quality bar` section is excluded from the blocking counts (the footer's tallies) and from any block/no-block verdict.
|
||||
- Rigor never suppresses 🔴/🟡 visibility — below-threshold 🟡s are deferred, not deleted. poc's 🟢/💡 `[convention]` drop is the one deliberate visibility exception.
|
||||
- **Dedup:** an identical finding reported by two skills (e.g. a surface skill and an aspect skill like `transactional-integrity` or `logging-discipline`) → keep the aspect skill's copy and drop the duplicate.
|
||||
- Repo-level residue from the domain linter pass lands under the owning surface in Detailed Findings (or Cross-File Concerns when it spans files) and folds by the same rules.
|
||||
|
||||
## Final Report Format
|
||||
|
||||
After collecting all file-reviewer results, synthesize into:
|
||||
@@ -148,8 +210,12 @@ instructions: |
|
||||
## Operational history
|
||||
<only when the lane ran: archaeology + prior-art findings with incident/commit references, or "no relevant incident history found">
|
||||
|
||||
## Deferred by quality bar
|
||||
<findings folded out of the blocking sections by the resolved rigor, severity tags preserved — excluded from the counts below; omit this section at production or when nothing folded>
|
||||
|
||||
---
|
||||
*Reviewed N files, found X critical, Y warnings, Z suggestions, W nitpicks*
|
||||
*Reviewed N files, found X critical, Y warnings, Z suggestions, W nitpicks (D deferred by quality bar)*
|
||||
*Quality bar: <resolved rigor> — provenance: <passed | plan | detected-default>; surfaces: <resolved surfaces>*
|
||||
```
|
||||
|
||||
## Edge Cases
|
||||
@@ -164,7 +230,7 @@ instructions: |
|
||||
1. **Always use `get_diff` first:** Don't assume what changed
|
||||
2. **Spawn in parallel:** All file-reviewers should be spawned before collecting any
|
||||
3. **Don't review code yourself:** Delegate ALL review work to file-reviewers
|
||||
4. **Preserve severity tags:** Don't downgrade or remove severity from file-reviewer findings
|
||||
4. **Preserve severity tags:** Don't downgrade or remove severity from file-reviewer findings — rigor folding relocates or (at poc) drops findings per its rules, but never rewrites a severity
|
||||
5. **Include ALL findings:** Don't summarize away specific issues
|
||||
6. **File reads:** If you do read a file directly (e.g. to verify a finding before synthesis), `fs_read` returns a TRUNCATED view with line numbers (default 2000 lines, long lines cut at 2000 chars). Use `fs_cat` only when you need the FULL untruncated contents of a file.
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
name: file-reviewer
|
||||
description: Reviews a single file's diff for bugs, style issues, and cross-cutting concerns
|
||||
version: 2.2.0
|
||||
version: 2.3.0
|
||||
|
||||
skills_enabled: true
|
||||
enabled_skills:
|
||||
@@ -8,6 +8,13 @@ enabled_skills:
|
||||
- ai-slop-remover
|
||||
- transactional-integrity
|
||||
- logging-discipline
|
||||
- rest-api-review
|
||||
- cli-review
|
||||
- library-review
|
||||
- worker-review
|
||||
- iac-review
|
||||
- migration-review
|
||||
- cicd-review
|
||||
|
||||
variables:
|
||||
- name: project_dir
|
||||
@@ -118,6 +125,10 @@ instructions: |
|
||||
- **🟢 SUGGESTION** — Clarity, coupling, naming, footgun mitigations, missing tests for the change
|
||||
- **💡 NITPICK** — Style if no formatter enforces it, minor naming, slop-remover findings on prose-style comments
|
||||
|
||||
### The `[convention]` / `[correctness]` marker
|
||||
|
||||
Finding titles may optionally carry a `[convention]` or `[correctness]` marker (e.g. `#### [convention] Collection endpoint without pagination`). Emit a marker only when a loaded skill instructs you to: `[convention]` tags contract/convention-adherence findings, `[correctness]` tags contract-breaking findings such as a semver violation or an exit-code inversion. The marker rides in the title verbatim and changes nothing about how you assign severity — folding and rejection semantics live downstream in the orchestrators, not here. The severity mapping above is unchanged.
|
||||
|
||||
## Rules
|
||||
|
||||
1. **Be specific.** Reference exact line numbers and code.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
schemaVersion: '1'
|
||||
schemaVersion: '2'
|
||||
kind: mixin
|
||||
name: agent-probe
|
||||
description: >
|
||||
@@ -12,16 +12,17 @@ description: >
|
||||
to libxml2.so.16). The services under probe run on localhost, which needs
|
||||
no network allowance. POSIX-only: sbx runs these commands with /bin/sh (dash).
|
||||
|
||||
network:
|
||||
allowedDomains:
|
||||
# Latest-release lookup + tarball downloads (GitHub redirects release
|
||||
# assets to *.githubusercontent.com object hosts)
|
||||
- 'api.github.com:443'
|
||||
- 'github.com:443'
|
||||
- 'objects.githubusercontent.com:443'
|
||||
- 'release-assets.githubusercontent.com:443'
|
||||
permissions:
|
||||
network:
|
||||
allow:
|
||||
# Latest-release lookup + tarball downloads (GitHub redirects release
|
||||
# assets to *.githubusercontent.com object hosts)
|
||||
- 'api.github.com:443'
|
||||
- 'github.com:443'
|
||||
- 'objects.githubusercontent.com:443'
|
||||
- 'release-assets.githubusercontent.com:443'
|
||||
|
||||
commands:
|
||||
setup:
|
||||
install:
|
||||
- command: |
|
||||
set -eu
|
||||
|
||||
@@ -306,6 +306,7 @@ instructions: |
|
||||
|
||||
Original request: <one-line summary of what the user asked for>
|
||||
Scope: <which directories or files the changes are expected to touch>
|
||||
Quality bar: rigor=<...>, surfaces=<...>
|
||||
|
||||
Coder summaries:
|
||||
- <coder 1 session_id>: <plan_summary from CODER_COMPLETE>
|
||||
@@ -314,13 +315,17 @@ instructions: |
|
||||
Run `get_diff` against the staged or recent changes, fan out file-reviewers per changed file as usual, and synthesize."
|
||||
```
|
||||
|
||||
Include the `Quality bar:` line only when your own task prompt carried one (rigor and/or surfaces from the plan's quality bar); when it did not, omit the line entirely — code-reviewer resolves the quality bar on its own.
|
||||
|
||||
### Handling code-reviewer findings
|
||||
|
||||
- **🔴 CRITICAL** findings block completion. Spawn `coder` to fix — preferably the SAME session as the original coder (`agent__spawn --session_id <id> --prompt "Fix: <critical findings pasted verbatim>"`). Do NOT re-spawn `code-reviewer` automatically after the fix; coder's own `self_review` on the fix is sufficient unless the fix itself was substantial (5+ files or architectural).
|
||||
- **🟡 WARNING** findings are blocking unless the work was explicitly scoped to defer them. If unsure, ASK the user via `user__ask` whether to fix or accept.
|
||||
- **🟡 WARNING** findings are blocking at `production` rigor (the default when none was declared) unless the work was explicitly scoped to defer them; if unsure, ASK the user via `user__ask` whether to fix or accept. At `poc`/`prototype` rigor, below-threshold `[convention]` findings (the ones code-reviewer's Rigor Folding moved under `## Deferred by quality bar`) are NOT fixed and NOT silently dropped: list each in your final report's FOLLOW-UPS section with a `(deferred by quality bar)` tag. 🔴 blocks at every rigor — rigor never lowers that bar.
|
||||
- **🟢 SUGGESTION / 💡 NITPICK** findings are informational. Surface them to the user with the final report. Do not block on them.
|
||||
- **`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.
|
||||
|
||||
**Rejecting a `[convention]` finding.** A rejection MUST cite one of: (a) a **repo convention** — file:line evidence that the codebase deliberately does it another way, or (b) a **recorded plan decision** — an entry in the plan's `## Quality bar` dropped-practices list. Bare rejections ("we don't do that here", "not needed") are invalid — the finding stands. NEVER rejectable: 🔴 findings and `[correctness]` findings. Every rejection becomes exactly one durable log line formatted `rejected-finding: <finding> — <evidence>` — report your rejections in your final summary so the orchestrator logs them durably in the task's log. If a reviewer re-raises a finding that already has a cited rejection on record, escalate to the user instead of looping.
|
||||
|
||||
### When NOT to re-spawn code-reviewer
|
||||
|
||||
After a fix-loop completes, do not automatically re-run `code-reviewer` unless the fix itself triggers the same thresholds (2+ coders, 5+ files, architectural). Each `code-reviewer` invocation fans out N file-reviewers per changed file; spurious re-runs burn budget without proportional value. Trust coder's `self_review` on bounded fixes.
|
||||
@@ -370,6 +375,8 @@ instructions: |
|
||||
- `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 your task prompt carries a declared rigor (a `Quality bar:` line, or the plan's `## Quality bar` section), derive the default posture from it unless the plan overrides the posture explicitly: rigor `poc` → `prototype` posture; rigor `prototype` → `standard`; rigor `production` → `standard`. `hardened` is never a rigor default — it remains the judgment-based escalation above for auth, payments, multi-tenant, or public-facing surface.
|
||||
|
||||
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):
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
# Coyote configuration. Generated by the first-run wizard.
|
||||
# Every setting is listed with its effective value and a short description.
|
||||
# For richer examples of each section, see
|
||||
# https://github.com/Dark-Alex-17/coyote/blob/main/config.example.yaml
|
||||
|
||||
# ---- LLM ----
|
||||
__MODEL_BLOCK__
|
||||
temperature: null # Set default temperature parameter (0, 1)
|
||||
top_p: null # Set default top-p parameter, with a range of (0, 1) or (0, 2) depending on the model
|
||||
|
||||
# ---- Behavior ----
|
||||
dry_run: false # Display the messages that would be sent to the LLM without actually sending them
|
||||
stream: true # Controls whether to use the stream-style APIs when querying for completions from LLM clients
|
||||
save: true # Indicates whether to persist the conversation to messages.md for posterity
|
||||
keybindings: emacs # Choose keybinding style (emacs, vi)
|
||||
editor: null # Specifies the editor used to edit the input buffer or session. (e.g. vim, emacs, nano, hx). Defaults to $EDITOR
|
||||
wrap: auto # Controls text wrapping (no, auto, <max-width>)
|
||||
wrap_code: false # Enables or disables the wrapping of code blocks
|
||||
|
||||
# ---- Vault ----
|
||||
# See the [Vault documentation](https://github.com/Dark-Alex-17/coyote/wiki/Vault) for more information on the Coyote vault.
|
||||
#
|
||||
# The secrets_provider tells Coyote where to read and write secrets referenced via {{SECRET_NAME}} syntax.
|
||||
#
|
||||
# Shorthand: set vault_password_file to enable the local provider with that password
|
||||
# file (it cannot be a secret template).
|
||||
#
|
||||
# Explicit: set secrets_provider to one of the supported types below. When secrets_provider is set,
|
||||
# vault_password_file is ignored. Note: secrets_provider itself cannot use secret template syntax.
|
||||
# The vault must be initialized before any secrets can be resolved.
|
||||
#
|
||||
# Local (same as the shorthand above):
|
||||
# secrets_provider:
|
||||
# type: local
|
||||
# password_file: ~/.coyote_password
|
||||
#
|
||||
# AWS Secrets Manager (requires an authenticated AWS CLI; see `aws sso login` or `aws configure`):
|
||||
# secrets_provider:
|
||||
# type: aws_secrets_manager
|
||||
# aws_profile: default
|
||||
# aws_region: us-east-1
|
||||
#
|
||||
# GCP Secret Manager (requires `gcloud auth application-default login`):
|
||||
# secrets_provider:
|
||||
# type: gcp_secret_manager
|
||||
# gcp_project_id: my-project-id
|
||||
#
|
||||
# Azure Key Vault (requires `az login`):
|
||||
# secrets_provider:
|
||||
# type: azure_key_vault
|
||||
# vault_name: my-vault-name
|
||||
#
|
||||
# gopass (requires the `gopass` CLI to be installed and initialized):
|
||||
# secrets_provider:
|
||||
# type: gopass
|
||||
# store: my-store # Optional; omit to use the default store
|
||||
#
|
||||
# 1Password (requires the `op` CLI to be installed and signed in via `op signin`):
|
||||
# secrets_provider:
|
||||
# type: one_password
|
||||
# vault: Production # Optional; omit to use the default vault
|
||||
# account: my.1password.com # Optional; omit to use the default account
|
||||
__SECRETS_BLOCK__
|
||||
|
||||
# ---- Function Calling ----
|
||||
# See the [Tools documentation](https://github.com/Dark-Alex-17/coyote/wiki/Tools) for more details
|
||||
function_calling_support: true # Enables or disables function calling (globally)
|
||||
mapping_tools: {} # Alias for a tool or toolset
|
||||
# Example:
|
||||
# mapping_tools:
|
||||
# fs: 'fs_cat,fs_ls,fs_mkdir,fs_rm,fs_write,fs_read,fs_glob,fs_grep'
|
||||
enabled_tools: null # Which tools to enable by default.
|
||||
# Accepts either a YAML list or a comma-separated string. Use 'all' to enable everything.
|
||||
# Example (list form):
|
||||
# enabled_tools:
|
||||
# - fs
|
||||
# - web_search_coyote
|
||||
# Example (comma-separated form):
|
||||
# enabled_tools: fs,web_search_coyote
|
||||
visible_tools: null # Which tools are visible to be compiled (and are thus able to be defined in 'enabled_tools').
|
||||
# Null/missing = all tools in the global tools dir are visible; [] = none;
|
||||
# an explicit list makes only those tools visible.
|
||||
# Example:
|
||||
# visible_tools:
|
||||
# - execute_command.sh
|
||||
# - fs_cat.sh
|
||||
# - fs_ls.sh
|
||||
|
||||
# ---- Skills ----
|
||||
# Skills are modular knowledge or capability packs the LLM can load and unload mid-conversation.
|
||||
# See the [Skills documentation](https://github.com/Dark-Alex-17/coyote/wiki/Skills) for more details.
|
||||
skills_enabled: true # Master switch. Set to false to hide all skill management tools from the model.
|
||||
# Skills also require `function_calling_support: true` above to work at all.
|
||||
enabled_skills: null # Which skills are available by default (no role/agent/session active). null = all visible.
|
||||
# Accepts either a YAML list or a comma-separated string.
|
||||
# Example (list form):
|
||||
# enabled_skills:
|
||||
# - git-master
|
||||
# - ai-slop-remover
|
||||
# Example (comma-separated form):
|
||||
# enabled_skills: git-master,ai-slop-remover
|
||||
visible_skills: null # The universe of skills allowed to be enabled in any context. null = all installed.
|
||||
# Example:
|
||||
# visible_skills:
|
||||
# - ai-slop-remover
|
||||
# - code-review
|
||||
# - git-master
|
||||
|
||||
# ---- 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
|
||||
|
||||
# ---- MCP Servers ----
|
||||
# See the [MCP Servers documentation](https://github.com/Dark-Alex-17/coyote/wiki/MCP-Servers) for more details
|
||||
mcp_server_support: true # Enables or disables MCP servers (globally)
|
||||
mapping_mcp_servers: {} # Alias for an MCP server or set of servers
|
||||
# Example:
|
||||
# mapping_mcp_servers:
|
||||
# git: github,gitmcp
|
||||
enabled_mcp_servers: null # Which MCP servers to enable by default.
|
||||
# Accepts either a YAML list or a comma-separated string. Use 'all' to enable everything.
|
||||
# Example (list form):
|
||||
# enabled_mcp_servers:
|
||||
# - github
|
||||
# - slack
|
||||
# Example (comma-separated form):
|
||||
# enabled_mcp_servers: github,slack,ddg-search
|
||||
mcp_tools: null # Per-server MCP tool allowlists (glob patterns: * and ? supported).
|
||||
# Tools that match no pattern are hidden from the model as if they
|
||||
# don't exist. Stacks with the other allowlist layers (mcp.json
|
||||
# `allowedTools`, role, agent, session, skill, graph node). Every
|
||||
# configured layer must allow a tool, so layers only ever narrow.
|
||||
# An empty list blocks all of a server's tools.
|
||||
# Example:
|
||||
# mcp_tools:
|
||||
# github:
|
||||
# - get_*
|
||||
# - list_*
|
||||
# slack: []
|
||||
|
||||
# ---- 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
|
||||
# prompt it to continue when incomplete tasks remain.
|
||||
# See the [Todo System documentation](https://github.com/Dark-Alex-17/coyote/wiki/TODO-System) for more information
|
||||
auto_continue: false # Enable automatic continuation when incomplete todos remain (default: false)
|
||||
max_auto_continues: 10 # Maximum number of automatic continuations before stopping (default: 10)
|
||||
inject_todo_instructions: true # Inject default todo usage instructions into the system prompt (default: true)
|
||||
continuation_prompt: null # Custom prompt used when auto-continuing. If null, uses built-in default
|
||||
inject_skill_instructions: true # Inject a short hint pointing the model at `skill__list` when skills are enabled
|
||||
# in this context. Only injected if `function_calling_support`, `skills_enabled`, and the
|
||||
# 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
|
||||
|
||||
# ---- Prelude ----
|
||||
repl_prelude: null # Set a default session or role for REPL mode to use (e.g. role:<name>, session:<name>, <session>:<role>)
|
||||
cmd_prelude: null # Set a default session or role for CMD mode to use (e.g. role:<name>, session:<name>, <session>:<role>)
|
||||
agent_session: null # Set a session to use when starting an agent (e.g. temp, default)
|
||||
|
||||
# ---- Session ----
|
||||
# See the [Session documentation](https://github.com/Dark-Alex-17/coyote/wiki/Sessions) for more information
|
||||
save_session: null # Controls the persistence of the session. If true, auto save; if false, don't auto-save; if null, ask the user what to do
|
||||
compression_threshold: 4000 # Compress the session when the token count reaches or exceeds this threshold
|
||||
compression_keep_last: 0 # Number of most-recent messages to keep visible after compression (0 = compress all messages)
|
||||
summarization_prompt: null # The text prompt used for creating a concise summary of session messages. If null, uses built-in default
|
||||
summary_context_prompt: null # The text prompt used for including the summary of the entire session as context to the model. If null, uses built-in default
|
||||
max_tool_result_chars: null # Cap on tool result characters forwarded to the model per call (null = no cap)
|
||||
max_concurrent_jobs: null # Max background jobs (`job__*` tools) running at once per context (null = 5; 0 disables background jobs entirely)
|
||||
|
||||
# ---- Memory ----
|
||||
# See the [Memory documentation](https://github.com/Dark-Alex-17/coyote/wiki/Memory) for more information.
|
||||
# Memory is opt-in by workspace presence (`.coyote/memory/MEMORY.md`) and global
|
||||
# presence (`<config_dir>/memory/MEMORY.md`). Set `memory: false` to disable
|
||||
# even when memory files exist. The cascade is: agent > session > role > app.
|
||||
# Bootstrap with `coyote --init-memory [global|workspace]` to create the marker file
|
||||
# the LLM needs before it will write any memory.
|
||||
memory: null # null = enabled when memory exists on disk; true = force on; false = force off
|
||||
memory_cap_with_tools: null # Char cap for injected memory when function calling is available (null = 6000).
|
||||
# Only MEMORY.md indexes are injected; the LLM uses memory__read to fetch drill files.
|
||||
memory_cap_without_tools: null # Char cap when function calling is unavailable (null = 12000).
|
||||
# Indexes plus drill file bodies are injected up to this cap.
|
||||
|
||||
# ---- Workspace Instructions ----
|
||||
# Human-curated project instructions injected read-only into the system prompt, in full.
|
||||
# Coyote walks up from the current directory and injects the first match from the file
|
||||
# chain below (per directory, in order). Scaffold with `coyote --init-instructions`.
|
||||
# Disable per-invocation with --no-workspace-instructions, or override the chain with
|
||||
# repeatable --workspace-instructions-file flags.
|
||||
workspace_instructions: null # null/true = inject when an instructions file exists; false = never inject
|
||||
workspace_instructions_files: null # File name chain to search, in priority order.
|
||||
# Default: [COYOTE.md, AGENTS.md, CLAUDE.md, GEMINI.md]
|
||||
# Set to a custom list to reorder or drop fallbacks, e.g.:
|
||||
# workspace_instructions_files: [COYOTE.md]
|
||||
|
||||
# ---- RAG ----
|
||||
# See the [RAG Docs](https://github.com/Dark-Alex-17/coyote/wiki/RAG) for more details.
|
||||
rag_embedding_model: null # Specifies the embedding model used for context retrieval
|
||||
rag_reranker_model: null # Specifies the reranker model used for sorting retrieved documents; Coyote uses Reciprocal Rank Fusion by default
|
||||
rag_top_k: 5 # Specifies the number of documents to retrieve for answering queries
|
||||
rag_chunk_size: null # Defines the size of chunks for document processing in characters
|
||||
rag_chunk_overlap: null # Defines the overlap between chunks
|
||||
rag_template: null # Defines the query structure using variables like __CONTEXT__, __SOURCES__, and __INPUT__
|
||||
# to tailor searches to specific needs. If null, uses built-in default
|
||||
rag_extractor_model: null # LLM model for graph-based entity/relationship extraction; when set, enables a graph RAG signal alongside vector and BM25
|
||||
rag_extractor_prompt: null # Custom extraction prompt template; must contain __CHUNK__ placeholder; defaults to built-in prompt when null
|
||||
rag_graph_hops: 1 # Number of hops to expand from matched entities at query time (0 = seed nodes only; 1 = direct neighbors; increase for denser graphs)
|
||||
|
||||
# Define document loaders to control how RAG and `.file`/`--file` load files of specific formats.
|
||||
document_loaders: {}
|
||||
# You can add custom loaders using the following syntax:
|
||||
# <file-extension>: <command-to-load-the-file>
|
||||
# Note: Use `$1` for input file and `$2` for output file. If `$2` is omitted, use stdout as output.
|
||||
# Examples:
|
||||
# document_loaders:
|
||||
# pdf: 'pdftotext $1 -' # https://poppler.freedesktop.org
|
||||
# docx: 'pandoc --to plain $1' # https://pandoc.org
|
||||
# jina: 'curl -fsSL https://r.jina.ai/$1 -H "Authorization: Bearer {{JINA_API_KEY}}"' # Requires a Jina API key in the Coyote vault
|
||||
|
||||
# ---- Appearance ----
|
||||
highlight: true # Controls syntax highlighting
|
||||
raw_markdown: false # When true, render markdown as raw text with syntax highlighting only. When false (default), transforms markdown syntax (headings, bold, lists, etc.) into styled terminal output
|
||||
theme: null # null = the built-in dark theme; set to `light` for the built-in light theme.
|
||||
# Custom themes: place a `dark.tmTheme` or `light.tmTheme` file in the Coyote config
|
||||
# directory and it is used in place of the corresponding built-in.
|
||||
|
||||
# ---- REPL Prompt ----
|
||||
# Custom REPL left/right prompts; see the [REPL Prompt Documentation](https://github.com/Dark-Alex-17/coyote/wiki/REPL-Prompt) for more information
|
||||
left_prompt: null # If null, uses the built-in default:
|
||||
# '{color.red}{model}){color.green}{?session {?agent {agent}>}{session}{?role /}}{!session {?agent {agent}>}}{role}{?rag @{rag}}{color.cyan}{?session )}{!session >}{color.reset} '
|
||||
right_prompt: null # If null, uses the built-in default:
|
||||
# '{color.cyan}{?reasoning_effort [{reasoning_effort}] }{color.purple}{?session {?consume_tokens {consume_tokens}({consume_percent}%)}{!consume_tokens {consume_tokens}}}{color.reset}'
|
||||
|
||||
# ---- Miscellaneous ----
|
||||
user_agent: null # Set User-Agent HTTP header, use `auto` for coyote/<current-version>
|
||||
save_shell_history: true # Whether to save shell execution command to the history file
|
||||
sync_models_url: null # URL to sync model changes from. If null, uses the built-in default:
|
||||
# https://raw.githubusercontent.com/Dark-Alex-17/coyote/refs/heads/main/models.yaml
|
||||
|
||||
# ---- Clients ----
|
||||
# See the [Clients documentation](https://github.com/Dark-Alex-17/coyote/wiki/Clients) for more details
|
||||
#
|
||||
# All clients have the following configuration:
|
||||
# - type: xxxx
|
||||
# name: xxxx # Only use it to distinguish clients with the same client type. Optional
|
||||
# models:
|
||||
# - name: xxxx # Chat model
|
||||
# max_input_tokens: 100000
|
||||
# supports_vision: true
|
||||
# supports_function_calling: true
|
||||
# - name: xxxx # Embedding model
|
||||
# type: embedding
|
||||
# default_chunk_size: 1500
|
||||
# max_batch_size: 100
|
||||
# - name: xxxx # Reranker model
|
||||
# type: reranker
|
||||
# patch: # Patch API calls
|
||||
# chat_completions: # API type; Possible values: chat_completions, embeddings, and rerank
|
||||
# <regex>: # The regex to match model names, e.g. '.*' 'gpt-4o' 'gpt-4o|gpt-4-.*'
|
||||
# url: '' # Patch request URL
|
||||
# body: # Patch request body
|
||||
# <json>
|
||||
# headers: # Patch request headers
|
||||
# <key>: <value>
|
||||
# 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)
|
||||
__CLIENTS_BLOCK__
|
||||
@@ -27,14 +27,30 @@ def _ensure_cwd_venv():
|
||||
_ensure_cwd_venv()
|
||||
|
||||
|
||||
def resolve_dir(env_name, default_path):
|
||||
"""Resolve a directory at run time.
|
||||
|
||||
Prefer the override env var when set, otherwise fall back to the default
|
||||
path derived from this script's own location, so the shim keeps working
|
||||
when the config dir moves or is shared across environments with different
|
||||
home directories.
|
||||
"""
|
||||
value = os.environ.get(env_name)
|
||||
if value:
|
||||
return value
|
||||
return os.path.normpath(default_path)
|
||||
|
||||
|
||||
def main():
|
||||
(agent_func, raw_data) = parse_argv()
|
||||
agent_data = parse_raw_data(raw_data)
|
||||
|
||||
root_dir = "{config_dir}"
|
||||
setup_env(root_dir, agent_func, raw_data)
|
||||
self_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
agent_dir = os.path.normpath(os.path.join(self_dir, ".."))
|
||||
root_dir = resolve_dir("{root_dir_env}", os.path.join(self_dir, "{root_dir_rel}"))
|
||||
setup_env(root_dir, agent_dir, agent_func, raw_data)
|
||||
|
||||
agent_tools_path = os.path.join(root_dir, "agents/{agent_name}/tools.py")
|
||||
agent_tools_path = os.path.join(agent_dir, "tools.py")
|
||||
run(agent_tools_path, agent_func, agent_data)
|
||||
|
||||
|
||||
@@ -65,12 +81,12 @@ def parse_argv():
|
||||
return agent_func, agent_data
|
||||
|
||||
|
||||
def setup_env(root_dir, agent_func, raw_data):
|
||||
def setup_env(root_dir, agent_dir, agent_func, raw_data):
|
||||
load_env(os.path.join(root_dir, ".env"))
|
||||
os.environ["LLM_ROOT_DIR"] = root_dir
|
||||
os.environ["LLM_AGENT_NAME"] = "{agent_name}"
|
||||
os.environ["LLM_AGENT_FUNC"] = agent_func
|
||||
os.environ["LLM_AGENT_ROOT_DIR"] = os.path.join(root_dir, "agents", "{agent_name}")
|
||||
os.environ["LLM_AGENT_ROOT_DIR"] = agent_dir
|
||||
os.environ["LLM_AGENT_CACHE_DIR"] = os.path.join(root_dir, "cache", "{agent_name}")
|
||||
os.environ["LLM_AGENT_RAW_JSON"] = raw_data
|
||||
|
||||
|
||||
@@ -5,13 +5,30 @@
|
||||
set -e
|
||||
|
||||
main() {
|
||||
root_dir="{config_dir}"
|
||||
self_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
agent_dir="$(cd "$self_dir/.." && pwd)"
|
||||
root_dir="$(resolve_dir "{root_dir_env}" "$self_dir/{root_dir_rel}")"
|
||||
functions_dir="$(resolve_dir "{functions_dir_env}" "$self_dir/{functions_dir_rel}")"
|
||||
parse_argv "$@"
|
||||
setup_env
|
||||
tools_path="$root_dir/agents/{agent_name}/tools.sh"
|
||||
tools_path="$agent_dir/tools.sh"
|
||||
run
|
||||
}
|
||||
|
||||
# Resolve a directory at run time: prefer the override env var ($1) when set,
|
||||
# otherwise fall back to the default path ($2) derived from this script's own
|
||||
# location, so the shim keeps working when the config dir moves or is shared
|
||||
# across environments with different home directories.
|
||||
resolve_dir() {
|
||||
local override
|
||||
override="$(printenv "$1" 2>/dev/null || true)"
|
||||
if [[ -n "$override" ]]; then
|
||||
echo "$override"
|
||||
else
|
||||
(cd "$2" 2>/dev/null && pwd) || echo "$2"
|
||||
fi
|
||||
}
|
||||
|
||||
parse_argv() {
|
||||
agent_func="$1"
|
||||
if [[ -n "$LLM_TOOL_DATA_FILE" ]] && [[ -f "$LLM_TOOL_DATA_FILE" ]]; then
|
||||
@@ -29,9 +46,9 @@ setup_env() {
|
||||
export LLM_ROOT_DIR="$root_dir"
|
||||
export LLM_AGENT_NAME="{agent_name}"
|
||||
export LLM_AGENT_FUNC="$agent_func"
|
||||
export LLM_AGENT_ROOT_DIR="$LLM_ROOT_DIR/agents/{agent_name}"
|
||||
export LLM_AGENT_ROOT_DIR="$agent_dir"
|
||||
export LLM_AGENT_CACHE_DIR="$LLM_ROOT_DIR/cache/{agent_name}"
|
||||
export LLM_PROMPT_UTILS_FILE="{prompt_utils_file}"
|
||||
export LLM_PROMPT_UTILS_FILE="$functions_dir/utils/prompt-utils.sh"
|
||||
export LLM_AGENT_RAW_JSON="$agent_data"
|
||||
}
|
||||
|
||||
@@ -59,6 +76,10 @@ run() {
|
||||
die "error: no JSON data"
|
||||
fi
|
||||
|
||||
if [[ ! -f "$tools_path" ]]; then
|
||||
die "error: agent tools script not found: $tools_path"
|
||||
fi
|
||||
|
||||
if [[ "$OS" == "Windows_NT" ]]; then
|
||||
set -o igncr
|
||||
tools_path="$(cygpath -w "$tools_path")"
|
||||
@@ -122,4 +143,3 @@ die() {
|
||||
}
|
||||
|
||||
main "$@"
|
||||
|
||||
|
||||
@@ -3,17 +3,38 @@
|
||||
// Usage: ./{agent_name}.ts <agent-func> <agent-data>
|
||||
|
||||
import { readFileSync, writeFileSync, existsSync } from "fs";
|
||||
import { join } from "path";
|
||||
import { pathToFileURL } from "url";
|
||||
import { dirname, join, resolve } from "path";
|
||||
import { fileURLToPath, pathToFileURL } from "url";
|
||||
|
||||
function selfDir(): string {
|
||||
if (typeof __dirname !== "undefined") {
|
||||
return __dirname;
|
||||
}
|
||||
return dirname(fileURLToPath(import.meta.url));
|
||||
}
|
||||
|
||||
// Resolve a directory at run time: prefer the override env var when set,
|
||||
// otherwise fall back to the default path derived from this script's own
|
||||
// location, so the shim keeps working when the config dir moves or is shared
|
||||
// across environments with different home directories.
|
||||
function resolveDir(envName: string, defaultPath: string): string {
|
||||
const value = process.env[envName];
|
||||
if (value) {
|
||||
return value;
|
||||
}
|
||||
return resolve(defaultPath);
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const { agentFunc, rawData } = parseArgv();
|
||||
const agentData = parseRawData(rawData);
|
||||
|
||||
const configDir = "{config_dir}";
|
||||
setupEnv(configDir, agentFunc, rawData);
|
||||
const binDir = selfDir();
|
||||
const agentDir = resolve(binDir, "..");
|
||||
const configDir = resolveDir("{root_dir_env}", join(binDir, "{root_dir_rel}"));
|
||||
setupEnv(configDir, agentDir, agentFunc, rawData);
|
||||
|
||||
const agentToolsPath = join(configDir, "agents", "{agent_name}", "tools.ts");
|
||||
const agentToolsPath = join(agentDir, "tools.ts");
|
||||
await run(agentToolsPath, agentFunc, agentData);
|
||||
}
|
||||
|
||||
@@ -48,12 +69,17 @@ function parseArgv(): { agentFunc: string; rawData: string } {
|
||||
return { agentFunc, rawData: agentData };
|
||||
}
|
||||
|
||||
function setupEnv(configDir: string, agentFunc: string, rawData: string): void {
|
||||
function setupEnv(
|
||||
configDir: string,
|
||||
agentDir: string,
|
||||
agentFunc: string,
|
||||
rawData: string,
|
||||
): void {
|
||||
loadEnv(join(configDir, ".env"));
|
||||
process.env["LLM_ROOT_DIR"] = configDir;
|
||||
process.env["LLM_AGENT_NAME"] = "{agent_name}";
|
||||
process.env["LLM_AGENT_FUNC"] = agentFunc;
|
||||
process.env["LLM_AGENT_ROOT_DIR"] = join(configDir, "agents", "{agent_name}");
|
||||
process.env["LLM_AGENT_ROOT_DIR"] = agentDir;
|
||||
process.env["LLM_AGENT_CACHE_DIR"] = join(configDir, "cache", "{agent_name}");
|
||||
process.env["LLM_AGENT_RAW_JSON"] = rawData;
|
||||
}
|
||||
|
||||
@@ -27,14 +27,30 @@ def _ensure_cwd_venv():
|
||||
_ensure_cwd_venv()
|
||||
|
||||
|
||||
def resolve_dir(env_name, default_path):
|
||||
"""Resolve a directory at run time.
|
||||
|
||||
Prefer the override env var when set, otherwise fall back to the default
|
||||
path derived from this script's own location, so the shim keeps working
|
||||
when the config dir moves or is shared across environments with different
|
||||
home directories.
|
||||
"""
|
||||
value = os.environ.get(env_name)
|
||||
if value:
|
||||
return value
|
||||
return os.path.normpath(default_path)
|
||||
|
||||
|
||||
def main():
|
||||
raw_data = parse_argv()
|
||||
tool_data = parse_raw_data(raw_data)
|
||||
|
||||
root_dir = "{root_dir}"
|
||||
self_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
root_dir = resolve_dir("{root_dir_env}", os.path.join(self_dir, "{root_dir_rel}"))
|
||||
functions_dir = resolve_dir("{functions_dir_env}", os.path.join(self_dir, "{functions_dir_rel}"))
|
||||
setup_env(root_dir, raw_data)
|
||||
|
||||
tool_path = "{tool_path}.py"
|
||||
tool_path = os.path.join(functions_dir, "tools", "{function_name}.py")
|
||||
run(tool_path, "run", tool_data)
|
||||
|
||||
|
||||
|
||||
@@ -5,13 +5,29 @@
|
||||
set -e
|
||||
|
||||
main() {
|
||||
root_dir="{root_dir}"
|
||||
self_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
root_dir="$(resolve_dir "{root_dir_env}" "$self_dir/{root_dir_rel}")"
|
||||
functions_dir="$(resolve_dir "{functions_dir_env}" "$self_dir/{functions_dir_rel}")"
|
||||
parse_argv "$@"
|
||||
setup_env
|
||||
tool_path="{tool_path}.sh"
|
||||
tool_path="$functions_dir/tools/{function_name}.sh"
|
||||
run
|
||||
}
|
||||
|
||||
# Resolve a directory at run time: prefer the override env var ($1) when set,
|
||||
# otherwise fall back to the default path ($2) derived from this script's own
|
||||
# location, so the shim keeps working when the config dir moves or is shared
|
||||
# across environments with different home directories.
|
||||
resolve_dir() {
|
||||
local override
|
||||
override="$(printenv "$1" 2>/dev/null || true)"
|
||||
if [[ -n "$override" ]]; then
|
||||
echo "$override"
|
||||
else
|
||||
(cd "$2" 2>/dev/null && pwd) || echo "$2"
|
||||
fi
|
||||
}
|
||||
|
||||
parse_argv() {
|
||||
if [[ -n "$LLM_TOOL_DATA_FILE" ]] && [[ -f "$LLM_TOOL_DATA_FILE" ]]; then
|
||||
tool_data="$(cat "$LLM_TOOL_DATA_FILE")"
|
||||
@@ -28,7 +44,7 @@ setup_env() {
|
||||
export LLM_ROOT_DIR="$root_dir"
|
||||
export LLM_TOOL_NAME="{function_name}"
|
||||
export LLM_TOOL_CACHE_DIR="$LLM_ROOT_DIR/cache/{function_name}"
|
||||
export LLM_PROMPT_UTILS_FILE="{prompt_utils_file}"
|
||||
export LLM_PROMPT_UTILS_FILE="$functions_dir/utils/prompt-utils.sh"
|
||||
export LLM_TOOL_RAW_JSON="$tool_data"
|
||||
}
|
||||
|
||||
@@ -56,6 +72,10 @@ run() {
|
||||
die "error: no JSON data"
|
||||
fi
|
||||
|
||||
if [[ ! -f "$tool_path" ]]; then
|
||||
die "error: tool script not found: $tool_path"
|
||||
fi
|
||||
|
||||
if [[ "$OS" == "Windows_NT" ]]; then
|
||||
set -o igncr
|
||||
tool_path="$(cygpath -w "$tool_path")"
|
||||
|
||||
@@ -3,17 +3,41 @@
|
||||
// Usage: ./{function_name}.ts <tool-data>
|
||||
|
||||
import { readFileSync, writeFileSync, existsSync } from "fs";
|
||||
import { join } from "path";
|
||||
import { pathToFileURL } from "url";
|
||||
import { dirname, join, resolve } from "path";
|
||||
import { fileURLToPath, pathToFileURL } from "url";
|
||||
|
||||
function selfDir(): string {
|
||||
if (typeof __dirname !== "undefined") {
|
||||
return __dirname;
|
||||
}
|
||||
return dirname(fileURLToPath(import.meta.url));
|
||||
}
|
||||
|
||||
// Resolve a directory at run time: prefer the override env var when set,
|
||||
// otherwise fall back to the default path derived from this script's own
|
||||
// location, so the shim keeps working when the config dir moves or is shared
|
||||
// across environments with different home directories.
|
||||
function resolveDir(envName: string, defaultPath: string): string {
|
||||
const value = process.env[envName];
|
||||
if (value) {
|
||||
return value;
|
||||
}
|
||||
return resolve(defaultPath);
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const rawData = parseArgv();
|
||||
const toolData = parseRawData(rawData);
|
||||
|
||||
const rootDir = "{root_dir}";
|
||||
const binDir = selfDir();
|
||||
const rootDir = resolveDir("{root_dir_env}", join(binDir, "{root_dir_rel}"));
|
||||
const functionsDir = resolveDir(
|
||||
"{functions_dir_env}",
|
||||
join(binDir, "{functions_dir_rel}"),
|
||||
);
|
||||
setupEnv(rootDir, rawData);
|
||||
|
||||
const toolPath = "{tool_path}.ts";
|
||||
const toolPath = join(functionsDir, "tools", "{function_name}.ts");
|
||||
await run(toolPath, "run", toolData);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,11 +9,11 @@ kind: sandbox
|
||||
name: coyote
|
||||
displayName: Coyote
|
||||
description: >
|
||||
An all-in-one, batteries-included LLM runtime featuring Shell Assistant,
|
||||
The batteries-included runtime for LLMs, featuring Shell Assistant,
|
||||
CLI & REPL mode, RAG, AI tools & agents, MCP servers, skills, and macros.
|
||||
|
||||
sandbox:
|
||||
image: 'darkalex17/coyote:v0.8.3'
|
||||
image: 'darkalex17/coyote:v0.10.1'
|
||||
entrypoint: ['bash', '-lc', 'exec /home/agent/.cargo/bin/coyote']
|
||||
|
||||
permissions:
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
description: Review CI/CD pipeline definitions - action/step pinning by SHA, token and credential permission scoping, secret exposure to fork-PR triggers, and cross-branch cache poisoning. Load when a diff touches workflow/pipeline files such as .github/workflows/*, GitLab CI config, or equivalent pipeline definitions. Findings fold into the standard code-review severity taxonomy. Grants read-only filesystem access for tracing workflows, triggers, and permission blocks.
|
||||
enabled_tools: fs_read, fs_grep, fs_glob, fs_cat, fs_ls
|
||||
---
|
||||
You are reviewing CI/CD pipeline definitions. The generic correctness checklist asks "does this pipeline run?"; you ask **"what can this pipeline be made to do by someone who controls an input to it — a tag, a fork PR, a cache key?"** A workflow file is production code with production credentials that runs third-party code on every push, yet it is otherwise reviewed by nobody. Most pipeline incidents are not broken builds — they are a mutable action tag that started doing something new, a token scoped far beyond its job, or a secret handed to code from a fork.
|
||||
|
||||
## When to load this skill
|
||||
|
||||
The diff touches ANY of: workflow/pipeline files — `.github/workflows/*`, GitLab CI config, or equivalent pipeline definitions in other systems. If the diff is application code with unchanged pipelines — unload; this checklist has nothing for you.
|
||||
|
||||
## Marker semantics
|
||||
|
||||
Every checklist item below carries a severity emoji AND a `[convention]` or `[correctness]` marker; both ride in the finding title so downstream tooling can act on them mechanically. `[convention]` findings are rigor-foldable (the orchestrator may lower them under a relaxed quality bar) and rejectable — but ONLY with cited evidence: a repo convention at file:line, or a recorded plan decision. `[correctness]` is reserved for contract breaks; those findings are neither foldable nor rejectable.
|
||||
|
||||
## Linters and mechanized checks
|
||||
|
||||
The review orchestrator runs the domain's mechanized checker — `actionlint` for GitHub Actions workflows; your CONTEXT may already include its output — do not re-derive it. Spend your prose on what the linter cannot reach: whether a token's permissions match what the job actually does, what a fork-triggered run can see, whether a cache key crosses a trust boundary. If the repo plausibly warrants a linter config it lacks (workflow files but no `actionlint` wiring), emit a 🟢 `[convention]` finding naming the gap.
|
||||
|
||||
## The checklist
|
||||
|
||||
Severities below are the production bar. Each item is a context-sensitive question, not an absolute — read the trigger blocks and permission blocks before flagging, and state any exemption you rely on.
|
||||
|
||||
### 1. 🟡 `[convention]` Actions pinned by mutable tag instead of SHA
|
||||
|
||||
Does the diff reference third-party actions or pipeline steps by a mutable tag (`@v4`, `@main`) rather than a full commit SHA? A mutable tag means the code your pipeline runs — with its credentials — can change without any change in your repo; tags have been retargeted maliciously in the wild. The house fix is SHA-pinning with a tag comment (and a bot to update pins). First-party actions from the same repo/org can be exempt per repo convention — cite the convention if you rely on it.
|
||||
|
||||
### 2. 🟡 `[convention]` Token/credential permissions broader than the job needs
|
||||
|
||||
Does each job's token grant match what the job actually does? Look for missing explicit permission blocks (falling back to a broad default), write scopes on jobs that only read, and org-level credentials in jobs that need repo-level access. The finding names the scoped alternative: the specific permissions the job's steps use. A workflow-level broad grant with per-job narrowing is acceptable shape; per-job broad grants "to be safe" are the finding.
|
||||
|
||||
### 3. 🔴 `[convention]` Secrets exposed to fork-PR triggers
|
||||
|
||||
Can a pull request from a fork reach this workflow's secrets? The dangerous shapes: triggers that run with secret access on fork-controlled code (e.g. `pull_request_target` checking out the PR head), secrets passed into steps that execute fork-modified scripts, and label-gated runs where the gate is applied after checkout. This item is co-owned with `security-review`'s supply-chain checklist item — that skill owns the full exploitation analysis; you flag the exposure the moment the trigger/secret/checkout combination makes it possible. The severity stays 🔴 regardless of the declared quality bar — fork-reachable secrets are critical at every rigor, and this item should never be folded down. Workflows that run on fork PRs WITHOUT secrets, or with secrets only after a trusted-code boundary, are the correct shapes — verify the checkout ref before accepting them.
|
||||
|
||||
### 4. 🟢 `[convention]` Cross-branch cache poisoning
|
||||
|
||||
Do cache keys let an untrusted branch write cache entries that a trusted branch (main, release) later restores? Caches written by fork-PR or feature-branch runs and restored by default-branch runs let attacker-influenced artifacts flow into trusted builds. Check the cache key/scope construction and the platform's cache-isolation rules — some platforms already isolate caches by branch with one-way fallback; a pattern the platform provably isolates is exempt, and worth citing.
|
||||
|
||||
## Ground-truth discipline
|
||||
|
||||
- READ the trigger block and permission block of every workflow the diff touches — the risk is almost always in the trigger/checkout/secret combination, not in the step commands.
|
||||
- `fs_grep` sibling workflows for the house idioms (SHA-pinning style, permission-block placement, cache-key construction) and cite the sibling at file:line when flagging deviation.
|
||||
- Check what each referenced action actually is (first-party vs third-party, checkout target) before applying the pinning and fork-exposure items.
|
||||
- Do not assert platform behavior (default permissions, cache isolation) from memory alone when the repo's config could override it — check the org/repo-level settings files if present, and state assumptions otherwise.
|
||||
|
||||
## What this skill does NOT check
|
||||
|
||||
- The full exploitation analysis of exposed secrets, injection via untrusted workflow inputs (`${{ }}` interpolation attacks), and supply-chain trust of the pinned actions themselves → `security-review` (item 3 above is explicitly co-owned with its supply-chain item).
|
||||
- Whether deploy/release steps the pipeline runs are idempotent and safe to re-run → `transactional-integrity`.
|
||||
- Log output conventions of pipeline steps → `logging-discipline`.
|
||||
- Metrics/alerts on pipeline health and deploy outcomes → `observability-review`.
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
description: Review the command-line surface contract of a change - exit codes, stdout/stderr channel discipline, help text, non-interactive operation, signal/cleanup behavior, and config precedence. Load when a diff touches argument-parser definitions, the main/entrypoint of a binary, or subcommand modules. Findings fold into the standard code-review severity taxonomy. Grants read-only filesystem access for tracing entrypoints, parsers, and exit paths.
|
||||
enabled_tools: fs_read, fs_grep, fs_glob, fs_cat, fs_ls
|
||||
---
|
||||
You are reviewing a command-line interface. The generic correctness checklist asks "does this command work when a human runs it?"; you ask **"does this command keep its contract with the scripts, pipes, and CI jobs that run it unattended?"** A CLI's real callers are rarely humans at a terminal — they are shell scripts branching on `$?`, pipelines parsing stdout, and cron jobs with no TTY. Most CLI breakage in the wild is not wrong logic; it is a success that exits 1, a diagnostic that corrupts a pipe, or a prompt that hangs a CI job forever.
|
||||
|
||||
## When to load this skill
|
||||
|
||||
The diff touches ANY of: argument-parser definitions (flag/option/subcommand declarations), the `main`/entrypoint of a binary, or subcommand modules. If the diff is library internals behind an unchanged command surface — unload; this checklist has nothing for you.
|
||||
|
||||
## Marker semantics
|
||||
|
||||
Every checklist item below carries a severity emoji AND a `[convention]` or `[correctness]` marker; both ride in the finding title so downstream tooling can act on them mechanically. `[convention]` findings are rigor-foldable (the orchestrator may lower them under a relaxed quality bar) and rejectable — but ONLY with cited evidence: a repo convention at file:line, or a recorded plan decision. `[correctness]` is reserved for contract breaks; those findings are neither foldable nor rejectable.
|
||||
|
||||
## Linters and mechanized checks
|
||||
|
||||
The review orchestrator runs mechanized checks (shell linters, help-text validators); your CONTEXT may already include their output — do not re-derive it. Spend your prose on what linters cannot reach: exit-code semantics on each error path, which stream a message lands on, whether a prompt has an escape hatch. If the repo plausibly warrants a linter config it lacks (shell scripts but no shell linter config), emit a 🟢 `[convention]` finding naming the gap.
|
||||
|
||||
## The checklist
|
||||
|
||||
Severities below are the production bar. Each item is a context-sensitive question, not an absolute — trace the actual exit paths and output calls before flagging.
|
||||
|
||||
### 1. 🔴 `[correctness]` Error paths exiting 0 / success paths exiting non-zero
|
||||
|
||||
Trace every exit path the diff adds or modifies: does each failure propagate a non-zero exit code all the way out of `main`, and does success exit 0? The classic bugs: an error that is printed and then falls through to a normal return; a caught exception that logs and continues; a match arm that swallows a `Result`. Scripts branch on `$?` — an inverted exit code silently corrupts every automation built on this command. This is the exit-code contract; it is never foldable and never rejectable.
|
||||
|
||||
### 2. 🟡 `[convention]` Diagnostics on stdout corrupting pipeable output
|
||||
|
||||
If the command's stdout is (or plausibly will be) piped or parsed — it prints data, JSON, lists, paths — then progress messages, warnings, and diagnostics on stdout corrupt the stream. Do new prints route diagnostics to stderr and reserve stdout for payload? A purely interactive command with no parseable output can be exempt — say so when you rely on that. Which *level and format* diagnostics use is `logging-discipline`'s question; yours is which stream they land on.
|
||||
|
||||
### 3. 🟢 `[convention]` Missing or wrong --help for new flags
|
||||
|
||||
Does every flag, option, and subcommand the diff adds appear in help output with an accurate description? Check the parser declarations: a flag with no help string, a stale description contradicting new behavior, or a new subcommand missing from the top-level help listing. Help text is the CLI's only discoverable documentation.
|
||||
|
||||
### 4. 🟡 `[convention]` Interactive prompt with no non-interactive escape
|
||||
|
||||
Does the diff add a prompt (confirmation, password, selection)? Then there must be a non-interactive path: a flag (`--yes`/`--force`-style), an environment variable, or reading from stdin — and ideally the prompt should detect a missing TTY rather than hang. A prompt with no escape hatch deadlocks CI and cron callers. Check what escape idiom the repo's existing prompts use and whether the new one matches.
|
||||
|
||||
### 5. 🟡 `[convention]` No signal/cleanup handling for long-running commands with temp state
|
||||
|
||||
If the diff adds a long-running command that creates temp files, lockfiles, partial output, or spawns children: what happens on Ctrl-C or SIGTERM? Look for signal handling, cleanup guards (drop/defer/finally/trap), or an idiom the repo already uses. Orphaned locks and half-written files are the finding. Short-lived commands with no temp state are exempt — this item is scoped to commands that hold state long enough for interruption to be a realistic event.
|
||||
|
||||
### 6. 🟢 `[convention]` Config precedence violated or undocumented
|
||||
|
||||
If the command reads configuration from more than one source, the conventional precedence is flag > environment variable > config file. Does the diff's resolution order honor that — and honor whatever order the repo has already established? A new setting that reads only the file when its siblings accept a flag override, or a precedence order documented nowhere, is the finding. Cite the repo's existing resolution code when flagging a deviation.
|
||||
|
||||
## Ground-truth discipline
|
||||
|
||||
- READ the full path from error site to process exit — exit-code bugs live in the propagation, not the error site. `fs_grep` for the exit/return conventions the entrypoint uses.
|
||||
- Check sibling subcommands for the established idioms (stderr usage, prompt escape flags, cleanup guards) — a new subcommand skipping the house pattern is the strongest form of evidence.
|
||||
- Do not flag hypothetical piping of a command that is documented interactive-only; note the assumption instead.
|
||||
|
||||
## What this skill does NOT check
|
||||
|
||||
- Whether argument or path inputs are exploitable (injection, traversal, secrets on the command line) → `security-review`.
|
||||
- Whether the state a command mutates is changed idempotently and atomically under reruns → `transactional-integrity`.
|
||||
- Log levels, formats, and message register of diagnostics → `logging-discipline` (this skill only checks which stream they use).
|
||||
- Metrics and alerting for operationally significant commands → `observability-review`.
|
||||
@@ -31,6 +31,18 @@ Produce a structured proposal (iterate with the user when interactive — load t
|
||||
- **Open questions** — ONLY questions the codebase cannot answer (business rules, priority calls). If none, say "No open questions."
|
||||
- **Task breakdown** — see below.
|
||||
|
||||
## Quality bar round (closes Step 2)
|
||||
|
||||
The last round of Step 2 sets the plan's quality bar. It is grilling-compatible — run it as numbered questions, each carrying a recommended answer, like any other frontier round:
|
||||
|
||||
1. **Propose `rigor`** — one of `poc | prototype | production` (default `production`). Infer the recommended value from the design doc's own language: "spike"/"demo" → `poc`; "iterate"/"internal" → `prototype`; otherwise `production`. Rigor calibrates which review-finding severities BLOCK downstream work: 🔴-critical findings block at EVERY rigor; at `poc`, suggestion/nitpick-level (🟢/💡) convention findings may be dropped from reports entirely. Anything a lower rigor defers is tracked as a follow-up — never silently dropped.
|
||||
2. **Propose `surfaces`** — zero or more of the closed enum: `rest-api`, `cli`, `library`, `worker`, `iac`, `db-migration`, `frontend`, `ci-cd` (`grpc`/`graphql` are aliases for `rest-api`), plus the escape hatch `other:<label>` for anything outside it. Infer from the approach: an HTTP handler → `rest-api`, a schema change → `db-migration`, and so on.
|
||||
3. **Per-surface confirm/drop** — for each accepted surface, present the headline best practices its reviewers will enforce and let the user confirm or drop each one. Every drop demands a one-line reason and lands in the plan's `## Quality bar` section — a dropped practice without a recorded reason WILL be re-litigated by a reviewer.
|
||||
|
||||
For an `other:<label>` surface no reviewer checklist exists, so the lane is: a librarian lookup distills an authoritative best-practice checklist for the label; the user confirms or drops each item; accepted items become task acceptance criteria where possible, otherwise they live under `## Quality bar → Long-tail criteria`. (The architect drives the lookup; this skill documents the shape the results take in the plan.)
|
||||
|
||||
Autonomous runs (no user to grill): take the inferred values, drop nothing, and note "quality bar inferred, not user-confirmed" in the plan.
|
||||
|
||||
## Task breakdown rules
|
||||
|
||||
| Rule | Why |
|
||||
@@ -51,6 +63,8 @@ Write `PLAN-<slug>.md` (kebab-case slug from the topic; verify no collision) to
|
||||
slug: <slug>
|
||||
status: draft # draft | active | implemented
|
||||
created: YYYY-MM-DD
|
||||
rigor: production # poc | prototype | production; omitted = production
|
||||
surfaces: [] # from the closed enum and/or other:<label>; omitted = []
|
||||
---
|
||||
|
||||
# <Title>
|
||||
@@ -60,6 +74,7 @@ created: YYYY-MM-DD
|
||||
## Approach
|
||||
## Alternatives considered
|
||||
## Constraints and risks
|
||||
## Quality bar
|
||||
## Open questions
|
||||
## Task breakdown
|
||||
|
||||
@@ -67,6 +82,8 @@ created: YYYY-MM-DD
|
||||
|---|------|------|-----------|-------|
|
||||
```
|
||||
|
||||
`## Quality bar` records the quality-bar round in human-readable form: the rigor line with its one-line reason, the surfaces line, the dropped-practices list (each entry with its one-line reason and the date it was decided), and the long-tail criteria block (`none`, or the distilled checklist for each `other:<label>` surface).
|
||||
|
||||
The plan is the implementers' entire context. Write for the "sealed container" standard: every question an implementer will hit is either answered inline or delegated via a pointer to the exact file/doc that answers it (where infra code goes, what DB tech, which layout to mirror, exact test commands). Paste short code snippets for load-bearing patterns — a path alone forces re-exploration; a stale claim fails the executor mid-implementation.
|
||||
|
||||
## Anti-patterns
|
||||
@@ -77,3 +94,4 @@ The plan is the implementers' entire context. Write for the "sealed container" s
|
||||
- Acceptance criteria describing implementation ("uses a for loop") instead of behavior.
|
||||
- Open questions the code could have answered — grep first, ask last.
|
||||
- Unrecorded decisions — every settled fork carries its reason.
|
||||
- Declaring `rigor: poc` to dodge review findings the user never agreed to drop.
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
description: Review the infrastructure-as-code surface of a change - Terraform, Helm charts, Kubernetes manifests, Dockerfiles, and compose files. Checks provider/module/base-image pinning, plaintext secret material, IAM/RBAC scoping, resource requests/limits, mutable image tags in deploy paths, and destructive plan operations without lifecycle guards. Load when a diff touches *.tf files, Helm charts, K8s manifests, Dockerfiles, or compose files. Findings fold into the standard code-review severity taxonomy. Grants read-only filesystem access for tracing modules, values files, and manifests.
|
||||
enabled_tools: fs_read, fs_grep, fs_glob, fs_cat, fs_ls
|
||||
---
|
||||
You are reviewing infrastructure-as-code. The generic correctness checklist asks "does this config apply cleanly?"; you ask **"what does this change do to the running system on apply day — and on every rebuild after?"** IaC is executable: an unpinned module resolves differently next month, a wildcard grant is a standing invitation, and a resource replacement that looked like an update deletes a database. Most IaC incidents are not syntax errors — they are a drifted dependency, a `latest` tag that moved, or a destroy the plan output showed and nobody read.
|
||||
|
||||
## When to load this skill
|
||||
|
||||
The diff touches ANY of: `*.tf` files or Terraform modules, Helm charts or values files, Kubernetes manifests, Dockerfiles, or compose files. If the diff is application code with unchanged infrastructure — unload; this checklist has nothing for you.
|
||||
|
||||
## Marker semantics
|
||||
|
||||
Every checklist item below carries a severity emoji AND a `[convention]` or `[correctness]` marker; both ride in the finding title so downstream tooling can act on them mechanically. `[convention]` findings are rigor-foldable (the orchestrator may lower them under a relaxed quality bar) and rejectable — but ONLY with cited evidence: a repo convention at file:line, or a recorded plan decision. `[correctness]` is reserved for contract breaks; those findings are neither foldable nor rejectable.
|
||||
|
||||
## Linters and mechanized checks
|
||||
|
||||
The review orchestrator runs the domain's mechanized checkers — `tflint`/`checkov` for Terraform, `hadolint` for Dockerfiles, `kubeconform` for Kubernetes manifests; your CONTEXT may already include their output — do not re-derive it. Spend your prose on what those tools cannot reach: blast radius of a destructive operation, whether a wildcard grant had a scoped alternative, whether a pin was omitted deliberately. If the repo plausibly warrants a linter config it lacks (Terraform but no `tflint`/`checkov` config, Dockerfiles but no `hadolint` config, manifests but no `kubeconform` wiring), emit a 🟢 `[convention]` finding naming the gap.
|
||||
|
||||
## The checklist
|
||||
|
||||
Severities below are the production bar. Each item is a context-sensitive question, not an absolute — read the module sources, values files, and sibling stacks before flagging, and state any exemption you rely on.
|
||||
|
||||
### 1. 🟡 `[convention]` Unpinned providers, modules, or base images
|
||||
|
||||
Does the diff add or modify a provider requirement, module source, or base image without pinning it to an exact version (or digest)? Unpinned means unbuildable-reproducibly: the same code produces different infrastructure next month. Check for version constraints on providers, ref/version on module sources, and tags-plus-digests on base images. A floating constraint that the repo's lockfile then pins is a weaker finding — cite the lockfile if it exists. Internal modules versioned by the same repo's release process can be exempt; say so.
|
||||
|
||||
### 2. 🔴 `[convention]` Plaintext secret material in code, state, or values
|
||||
|
||||
Does the diff introduce secret material — passwords, tokens, keys, connection strings with credentials — in plaintext in config files, values files, environment blocks, or anywhere it lands in state or the image? Report the finding and the location; defer the exploitation analysis to `security-review`, which owns the abuse question. The severity stays 🔴 regardless of the declared quality bar — a committed secret is critical at every rigor, and this item should never be folded down. Values wired from an external secret manager, encrypted-at-rest secret stores, or CI-injected references are the correct shapes — verify the reference is actually a reference, not an inlined value.
|
||||
|
||||
### 3. 🟡 `[convention]` Wildcard IAM/RBAC where a scoped grant is available
|
||||
|
||||
Does the diff grant `*` actions, `*` resources, cluster-admin, or a similarly broad role where the workload's actual needs are enumerable? The finding must name the scoped alternative: the specific actions the code paths use, the resource ARNs/namespaces in play. A genuinely dynamic resource set can justify a partial wildcard — the finding is a wildcard chosen for convenience when a scoped grant was available. Whether the over-grant is *exploitable* in this environment is `security-review`'s question; yours is the least-privilege contract.
|
||||
|
||||
### 4. 🟢 `[convention]` Missing resource requests/limits on workloads
|
||||
|
||||
Do new or modified workloads (Deployments, StatefulSets, Jobs, compose services in deploy paths) declare resource requests and limits? A workload with no requests schedules blind and a workload with no limits can starve its node neighbors. Check whether the repo sets these via a shared chart/library or namespace defaults (LimitRange) before flagging — a house mechanism that already applies them is an exemption worth citing.
|
||||
|
||||
### 5. 🟡 `[convention]` Mutable image tags in deploy paths
|
||||
|
||||
Does anything in a deploy path reference an image by a mutable tag — `latest`, a branch name, an unversioned tag? A mutable tag means the deployed artifact changes without a corresponding code change: rollbacks stop meaning anything and two environments running "the same tag" can run different code. The fix is an immutable version tag or digest. Local-development compose files not used for deployment are exempt — verify which one this file is before flagging, and say so.
|
||||
|
||||
### 6. 🟡 `[convention]` Destructive plan operations without lifecycle guards
|
||||
|
||||
Will applying this diff destroy or replace stateful resources — a changed identifier forcing replacement, a removed resource holding data, a rename the tool treats as destroy-and-create? For resources where destruction means data loss (databases, buckets, volumes), look for the guardrails: `prevent_destroy` lifecycle blocks, deletion protection flags, `moved`/state-migration blocks for renames. The finding names the resource, why the plan will destroy it, and the guard or migration that is missing. Stateless, freely recreatable resources are exempt.
|
||||
|
||||
## Ground-truth discipline
|
||||
|
||||
- READ the module source and values files a manifest consumes, not just the diff hunk — pins, secrets, and defaults often live one level up or down from the change.
|
||||
- `fs_grep` sibling stacks/charts for the house idioms (version-pinning style, secret-reference mechanism, shared resource-limit templates) and cite the sibling at file:line when flagging deviation.
|
||||
- Distinguish deploy-path files from local-dev scaffolding before applying deploy-path severities; the file's consumers, not its syntax, determine which it is.
|
||||
- Do not guess what a plan will do from the diff alone when the change is ambiguous — say what evidence would settle it (the plan output) and flag the ambiguity itself.
|
||||
|
||||
## What this skill does NOT check
|
||||
|
||||
- Whether an exposed secret, over-grant, or open ingress is actually exploitable, and supply-chain trust of images/modules → `security-review` (this skill reports the presence of the hazard; that skill owns the abuse analysis).
|
||||
- Whether provisioning/deployment scripts mutate state idempotently and survive reruns → `transactional-integrity`.
|
||||
- Log configuration conventions inside deployed workloads → `logging-discipline`.
|
||||
- Metrics, alerts, and dashboards for new infrastructure → `observability-review`.
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
description: Review the public-API surface contract of a library change - semver discipline against the manifest version, panic reachability from public entry points, doc coverage, error-type information quality, dependency weight/pinning, and internal-type leakage. Load when a diff touches the public API of a lib crate/package - exported symbols, pub items, __init__/index exports - or its manifest version. Findings fold into the standard code-review severity taxonomy. Grants read-only filesystem access for tracing exports, manifests, and public signatures.
|
||||
enabled_tools: fs_read, fs_grep, fs_glob, fs_cat, fs_ls
|
||||
---
|
||||
You are reviewing a library's public surface. The generic correctness checklist asks "does this code work?"; you ask **"what did downstream consumers just inherit?"** A library's public API is a versioned contract: every exported symbol, signature, error type, and transitive dependency becomes someone else's problem the moment it ships. Most library pain downstream is not broken logic — it is a silent semver break, a panic escaping an API that promised a `Result`, or a private type welded into a public signature that can now never change.
|
||||
|
||||
## When to load this skill
|
||||
|
||||
The diff touches ANY of: the public API of a lib crate/package — exported symbols, `pub` items, `__init__`/index exports, re-export lists — or its manifest version (Cargo.toml, package.json, pyproject.toml). If the diff is purely private internals with no public-surface or manifest change — unload; this checklist has nothing for you.
|
||||
|
||||
## Marker semantics
|
||||
|
||||
Every checklist item below carries a severity emoji AND a `[convention]` or `[correctness]` marker; both ride in the finding title so downstream tooling can act on them mechanically. `[convention]` findings are rigor-foldable (the orchestrator may lower them under a relaxed quality bar) and rejectable — but ONLY with cited evidence: a repo convention at file:line, or a recorded plan decision. `[correctness]` is reserved for contract breaks; those findings are neither foldable nor rejectable.
|
||||
|
||||
## Linters and mechanized checks
|
||||
|
||||
The review orchestrator runs mechanized checks (API-diff/semver checkers, doc-coverage lints); your CONTEXT may already include their output — do not re-derive it. Spend your prose on what linters cannot reach: whether a behavioral change breaks callers even though signatures held, whether an error type actually tells the caller what to do, whether a new dependency is worth its weight. If the repo plausibly warrants a linter config it lacks (a published library with no API-breakage check or doc lint configured), emit a 🟢 `[convention]` finding naming the gap.
|
||||
|
||||
## The checklist
|
||||
|
||||
Severities below are the production bar. Each item is a context-sensitive question, not an absolute — establish what is actually public and actually published before flagging.
|
||||
|
||||
### 1. 🔴 `[correctness]` Breaking public-API change without a major-version note
|
||||
|
||||
Does the diff remove, rename, or change the signature/behavior of anything exported — or tighten what an input accepts, or change what an error variant means? Compare against the manifest version: a breaking change is a 🔴 `[correctness]` finding unless the diff carries a major-version bump or an explicit note that one is planned for the release. Verify "published" first: symbols added earlier on this same unreleased branch are fair game to change freely, and a 0.x line may follow a different compatibility policy — read the repo's versioning statement before firing. Semver is the contract; this is never foldable and never rejectable.
|
||||
|
||||
### 2. 🟡 `[convention]` Panic/unwrap reachable from public API on user input
|
||||
|
||||
Trace new public entry points: can caller-supplied input reach a panic — `unwrap`/`expect` on values derived from arguments, unchecked indexing/slicing, unchecked arithmetic, assertions on caller data? A library that panics on bad input takes down the host application; the contract is to return the error type instead. Panics on programmer error (violated documented invariants) or in internal-only paths that input cannot reach are exempt — say so when you rely on that distinction.
|
||||
|
||||
### 3. 🟢 `[convention]` Public items with no doc comments
|
||||
|
||||
Does every new public item — function, type, trait/interface, module, re-export — carry a doc comment saying what it does, what its parameters mean, and what errors/panics it can produce? Match the repo's documentation register: in a library where every existing public item is documented, an undocumented newcomer is a clear finding; cite a documented sibling at file:line.
|
||||
|
||||
### 4. 🟡 `[convention]` Error types erasing caller-actionable information
|
||||
|
||||
Read the error paths crossing the public boundary: does the error type let a caller distinguish the cases they would handle differently — retry vs give up, bad input vs internal failure, which resource was missing? Stringly-typed errors, a single opaque variant swallowing distinct causes, and lossy conversions that drop the source error are the finding. The caller cannot match on a message string; they need variants, codes, or a source chain.
|
||||
|
||||
### 5. 🟢 `[convention]` Heavyweight or unpinned new required dependency
|
||||
|
||||
Does the diff add a required dependency? For a library, every required dependency lands in every consumer's tree: is it proportionate to what it is used for (a large framework pulled in for one helper is the finding), is its version constraint sane per the ecosystem's norm (a wildcard or unbounded range is the finding), and could it be optional/feature-gated instead? Dev/test-only dependencies are exempt. Whether the dependency is *trustworthy* (typosquats, abandonment, supply-chain risk) is `security-review`'s question.
|
||||
|
||||
### 6. 🟢 `[convention]` Internal types leaking through the public surface
|
||||
|
||||
Do new public signatures expose types that were meant to stay internal — a private module's struct now returned publicly, a third-party type welded into a public signature (locking the dependency into the public contract), or an implementation detail that consumers will now depend on? Once shipped, these can only be removed by a major version. Look for the repo's existing pattern (newtype wrappers, re-export boundaries, facade modules) and cite it when flagging.
|
||||
|
||||
## Ground-truth discipline
|
||||
|
||||
- Establish the actual public surface first: `fs_grep` the export list / re-exports / visibility modifiers — an item can be `pub` yet unreachable from outside, or private yet re-exported.
|
||||
- READ the manifest for the current version and any versioning policy notes before calling anything a semver break.
|
||||
- Check a documented, well-shaped sibling API for the house style (doc register, error-type shape, newtype boundaries) — deviation from a cited sibling is the strongest form of evidence.
|
||||
- Do not flag behavior-preserving refactors of private internals; the contract is the public surface.
|
||||
|
||||
## What this skill does NOT check
|
||||
|
||||
- Whether inputs are exploitable or a new dependency is malicious/compromised → `security-review` (this skill only weighs dependency size and pinning).
|
||||
- Whether stateful helpers the library exposes are idempotent, atomic, or retry-safe → `transactional-integrity`.
|
||||
- Log lines a library emits and their conventions → `logging-discipline`.
|
||||
- Metrics/alerts for the library's operational behavior → `observability-review`.
|
||||
@@ -0,0 +1,55 @@
|
||||
---
|
||||
description: Review database schema migrations - expand/contract compatibility with currently-running code, reversibility, online/concurrent index creation, backfills mixed into DDL transactions, and down-migrations. Load when a diff touches migration directories/files, schema definitions, or ORM model changes. Findings fold into the standard code-review severity taxonomy. Grants read-only filesystem access for tracing migrations, schema definitions, and the code that reads the affected tables.
|
||||
enabled_tools: fs_read, fs_grep, fs_glob, fs_cat, fs_ls
|
||||
---
|
||||
You are reviewing a schema migration. The generic correctness checklist asks "does this migration apply?"; you ask **"what happens in the window when this schema and the currently-running code coexist — and what happens if we have to go back?"** A migration does not run against an idle system: for the minutes (or hours) of a rolling deploy, old code runs against the new schema, and a rollback runs old code against it indefinitely. Most migration incidents are not failed DDL — they are a column dropped while running code still reads it, a lock held on a hot table during business hours, or a bad deploy with no way back.
|
||||
|
||||
## When to load this skill
|
||||
|
||||
The diff touches ANY of: migration directories or files, schema definition files, or ORM model changes that generate schema changes. If the diff is query/application logic against an unchanged schema — unload; this checklist has nothing for you.
|
||||
|
||||
## Marker semantics
|
||||
|
||||
Every checklist item below carries a severity emoji AND a `[convention]` or `[correctness]` marker; both ride in the finding title so downstream tooling can act on them mechanically. `[convention]` findings are rigor-foldable (the orchestrator may lower them under a relaxed quality bar) and rejectable — but ONLY with cited evidence: a repo convention at file:line, or a recorded plan decision. `[correctness]` is reserved for contract breaks; those findings are neither foldable nor rejectable.
|
||||
|
||||
## Linters and mechanized checks
|
||||
|
||||
The review orchestrator runs mechanized checks (migration linters, schema-diff tools, lock-analysis checkers); your CONTEXT may already include their output — do not re-derive it. Spend your prose on what those tools cannot reach: whether the currently-running code still depends on what this migration removes, whether irreversibility was a decision or an accident, whether a table is big enough for lock duration to matter. If the repo plausibly warrants a linter config it lacks (a migration directory but no migration linter or schema-diff check configured), emit a 🟢 `[convention]` finding naming the gap.
|
||||
|
||||
## The checklist
|
||||
|
||||
Severities below are the production bar. Each item is a context-sensitive question, not an absolute — read the code that touches the affected tables and the repo's deploy story before flagging, and state any exemption you rely on.
|
||||
|
||||
### 1. 🔴 `[correctness]` Expand/contract violation against currently-running code
|
||||
|
||||
Does this migration remove or rename a column/table, tighten a constraint, or change a type that the CURRENTLY-DEPLOYED code still reads or writes? During a rolling deploy — and after any rollback — that code runs against this schema, and the violation is an outage, not a style issue. The safe sequence is expand/contract: additive schema change first, code migrated in a separate deploy, contraction only after no running code references the old shape. `fs_grep` the codebase for references to everything this migration drops or renames; a rename must land as add-new/backfill/drop-old across deploys, not as a single in-place rename. This is a contract break with the running system: never foldable, never rejectable. The exemption is genuine confirmation that nothing running references the old shape — a column already unreferenced for several releases, or a pre-first-deploy table; cite the evidence when you rely on it.
|
||||
|
||||
### 2. 🟡 `[convention]` Irreversible migration without an explicit stated reason
|
||||
|
||||
Does the migration destroy information — dropping a column with data, lossy type narrowing, collapsing values — such that no down-migration could restore it? Irreversible is sometimes the right call, but it must be a *stated* decision: a comment in the migration or an equivalent recorded note saying what is lost and why that is acceptable. Silent irreversibility is the finding; the reviewer after an incident should not have to discover it from the diff.
|
||||
|
||||
### 3. 🟡 `[convention]` Index creation without concurrent/online mode on large tables
|
||||
|
||||
Does the migration create an index on a table that is large or hot in production? Default index builds take locks that block writes for the duration of the build — on a big table that is a self-inflicted outage. Look for the engine's online path (concurrent/online index creation, e.g. `CREATE INDEX CONCURRENTLY` in Postgres, `ALGORITHM=INPLACE` in MySQL) and note that concurrent builds often cannot run inside a transaction — the migration tool may need its transaction wrapper disabled for that step. A genuinely small, cold, or brand-new table is exempt — say which and why.
|
||||
|
||||
### 4. 🟡 `[convention]` Data backfill in the same transaction as DDL
|
||||
|
||||
Does the migration mix a data backfill (UPDATE/INSERT over existing rows) into the same transaction as schema changes? A backfill over a large table holds the DDL's locks for the whole rewrite, blocks concurrent writes, and can bloat/timeout the transaction. The safe shape is: schema change in the migration, backfill as a separate batched step (separate migration, background job, or chunked script). A backfill over a provably tiny table can be exempt — state the size reasoning. How the backfill itself behaves under interruption and rerun is `transactional-integrity`'s question.
|
||||
|
||||
### 5. 🟢 `[convention]` Missing down-migration where the tool supports it
|
||||
|
||||
Does the migration tool in this repo support down/rollback scripts, and do sibling migrations provide them? Then a new migration without one is the finding — the first schema rollback should not be authored during the incident that needs it. Where the down-path is genuinely impossible (see item 2), the down script should say so explicitly rather than be omitted. Repos whose tooling or stated convention is forward-only are exempt; cite the convention.
|
||||
|
||||
## Ground-truth discipline
|
||||
|
||||
- `fs_grep` the application code for every column, table, and constraint this migration touches — the expand/contract question is answered by the code, not by the migration file.
|
||||
- READ sibling migrations for the house idioms (down-scripts, concurrent-index flags, backfill separation, naming) and cite a sibling at file:line when flagging deviation.
|
||||
- Check the migration tool's config for transaction-wrapping behavior before reasoning about what runs atomically — tools differ, and per-migration overrides matter.
|
||||
- Reason about table size honestly: if you cannot tell whether a table is large, say so and frame the finding conditionally rather than asserting an outage.
|
||||
|
||||
## What this skill does NOT check
|
||||
|
||||
- Whether backfill or migration-adjacent application code is idempotent, atomic, and safe under rerun/crash → `transactional-integrity`.
|
||||
- Whether schema changes expose sensitive data or weaken access controls in exploitable ways → `security-review`.
|
||||
- Log output of migration runs and its conventions → `logging-discipline`.
|
||||
- Metrics/alerts for migration execution and post-migration health → `observability-review`.
|
||||
@@ -31,9 +31,12 @@ Walk EVERY category. For each, ask: "when the implementer hits this, does the pl
|
||||
| 8 | **Config, secrets & environments** | New env vars/config keys — where are they declared and injected? Secrets — vault/parameter store conventions? Staging vs production differences that affect implementation? |
|
||||
| 9 | **Scope boundaries** | Is Out of scope present and specific? Are "tempting adjacent fixes" explicitly deferred? |
|
||||
| 10 | **Settled decisions** | Are choices that were debated recorded WITH their one-line reason ("RDS over in-cluster Postgres because ops owns backups")? An unrecorded decision WILL be re-litigated by the implementer. |
|
||||
| 11 | **Quality bar** | Are `rigor` and `surfaces` declared (or the plan explicitly generic)? Is every dropped best practice recorded WITH a one-line reason? Does every `other:<label>` surface carry non-empty long-tail criteria? |
|
||||
|
||||
Not every category applies to every plan (a docs-only plan has no data layer). Mark inapplicable categories as such — silently skipping one is how leaks survive.
|
||||
|
||||
For category 11 specifically: a missing Quality bar declaration is FRICTION when the plan is plausibly `surfaces: []` (a docs-only or pure-refactor plan), BLOCKING when the plan self-evidently builds an enum surface (an HTTP API, a CLI, migrations…) but declares none.
|
||||
|
||||
## Pointer verification (do not trust, verify)
|
||||
|
||||
For every pointer the plan offers:
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
description: Review the API surface contract of a change - REST/HTTP routes and handlers, request/response types, OpenAPI specs, plus gRPC services and GraphQL schemas/resolvers when the diff is that flavor. Checks pagination, recorded auth decisions, HTTP method semantics, error-shape consistency, boundary validation, and versioned contract evolution. Load when a diff touches HTTP route/handler definitions, request/response types, OpenAPI specs, proto files, or GraphQL schemas/resolvers. Findings fold into the standard code-review severity taxonomy. Grants read-only filesystem access for tracing routes, types, and published contracts.
|
||||
enabled_tools: fs_read, fs_grep, fs_glob, fs_cat, fs_ls
|
||||
---
|
||||
You are reviewing an API surface. The generic correctness checklist asks "does this handler work?"; you ask **"does this endpoint honor the contract its callers already depend on — and did anyone record the decisions callers will need?"** An API is a promise: clients you cannot see build against the shapes, semantics, and error formats you ship. Most API pain in production is not broken logic — it is a silently changed shape, an unbounded list that grew, or an error format that differs from every sibling endpoint.
|
||||
|
||||
## When to load this skill
|
||||
|
||||
The diff touches ANY of: HTTP route or handler definitions, request/response types, OpenAPI/Swagger specs, gRPC `.proto` files or service implementations, GraphQL schemas or resolvers. If the diff is internal logic behind an unchanged API surface — unload; this checklist has nothing for you.
|
||||
|
||||
## Marker semantics
|
||||
|
||||
Every checklist item below carries a severity emoji AND a `[convention]` or `[correctness]` marker; both ride in the finding title so downstream tooling can act on them mechanically. `[convention]` findings are rigor-foldable (the orchestrator may lower them under a relaxed quality bar) and rejectable — but ONLY with cited evidence: a repo convention at file:line, or a recorded plan decision. `[correctness]` is reserved for contract breaks; those findings are neither foldable nor rejectable.
|
||||
|
||||
## Linters and mechanized checks
|
||||
|
||||
The review orchestrator runs mechanized checks (spec linters, schema diff tools, breaking-change detectors); your CONTEXT may already include their output — do not re-derive it. Spend your prose on what linters cannot reach: whether pagination is warranted, whether the auth decision was recorded, whether an evolution is actually compatible for real callers. If the repo plausibly warrants a linter config it lacks (an OpenAPI spec but no spec linter, protos but no breaking-change check), emit a 🟢 `[convention]` finding naming the gap.
|
||||
|
||||
## The checklist (REST/HTTP)
|
||||
|
||||
Severities below are the production bar. Each item is a context-sensitive question, not an absolute — read the surrounding code and the callers before flagging.
|
||||
|
||||
### 1. 🟡 `[convention]` Unbounded collection endpoint without pagination
|
||||
|
||||
Does the diff add or modify an endpoint that returns a collection? If the collection can grow without bound (rows in a table, user-generated items), missing pagination is a finding: name the endpoint, the backing query, and the growth vector. A provably bounded small set is exempt — an enum-backed list, a fixed config table, a per-user set with a hard cap — and when you rely on that exemption, say so explicitly in your notes so the next reviewer sees it was considered, not missed.
|
||||
|
||||
### 2. 🟡 `[convention]` Route without a recorded authn/z decision
|
||||
|
||||
For every new or changed route: is there a recorded decision that this route is public, authenticated, or role-gated? "Recorded" means visible in code or spec — middleware attached, an annotation, a spec `security` block, or an explicit comment for deliberately public routes. A route with no discernible decision is the finding. Whether the auth implementation is *bypassable* is not your question — that belongs to `security-review`; you only verify the decision exists and is stated.
|
||||
|
||||
### 3. 🟡 `[convention]` Non-idempotent PUT/DELETE semantics
|
||||
|
||||
PUT and DELETE carry idempotency promises by HTTP contract: repeating a PUT must converge on the same state; repeating a DELETE must not error in a way that breaks retrying clients (a second DELETE returning 404 or 204 is fine; returning 500 is not). Does the diff's handler honor the method it is mounted on — or should it be a POST? You check the *declared method semantics*; whether the state change is mechanically idempotent under retries and concurrency belongs to `transactional-integrity`.
|
||||
|
||||
### 4. 🟡/🟢 `[convention]` Error responses leaking internals or inconsistent error shape
|
||||
|
||||
Read the error paths: do responses leak internals — stack traces, SQL fragments, internal hostnames, framework default error pages (🟡)? Do they match the error shape the repo's sibling endpoints already return — same envelope, same code/message fields (🟢 when merely inconsistent)? `fs_grep` a sibling handler's error response to establish the house shape before flagging. Whether a leak is *exploitable* is `security-review`'s call; yours is the contract and consistency question.
|
||||
|
||||
### 5. 🔴 `[correctness]` Breaking a published request/response shape without versioning
|
||||
|
||||
Does the diff remove or rename a field, change a type, tighten accepted input, or change status codes on an endpoint that is already published (in a released spec, consumed by known clients, or exposed beyond this repo)? That is a contract break — a 🔴 `[correctness]` finding unless the change ships behind a new version (path version, header version, or an additive evolution that old clients tolerate). Verify "published" before firing: an endpoint added earlier in this same unreleased branch is not published, and changing it freely is fine.
|
||||
|
||||
### 6. 🟡 `[convention]` Missing boundary input validation
|
||||
|
||||
At the request boundary, is input validated at all — types enforced, required fields checked, sizes/ranges bounded — before it flows inward? Absence of any validation on a new input path is the finding. Whether unvalidated input is *exploitable* (injection, traversal) is deferred to `security-review`; you flag the missing guardrail, not the attack.
|
||||
|
||||
## gRPC section (apply when the diff touches protos or gRPC services)
|
||||
|
||||
- 🟡 `[convention]` **Deadlines** — do new client calls set deadlines, and do servers propagate the caller's deadline to their own outbound calls? A call chain with no deadline anywhere hangs forever on a stuck dependency.
|
||||
- 🟡 `[convention]` **Status-code discipline** — do handlers return meaningful gRPC status codes (`NOT_FOUND`, `INVALID_ARGUMENT`, `ALREADY_EXISTS`) rather than collapsing every failure into `UNKNOWN`/`INTERNAL`? Callers branch on these codes; a flattened code space breaks their error handling.
|
||||
- 🔴 `[correctness]` **Backwards-compatible proto evolution** — on a published proto: no field-number reuse, no type changes on existing fields, no renumbering, new fields optional with fresh numbers. Violating any of these silently corrupts data for old clients — same contract-break bar as item 5.
|
||||
- 🟢 `[convention]` **Field deprecation** — removed fields should be `reserved` (number and name) and deprecations marked with the `deprecated` option, not deleted outright, so the number can never be reused.
|
||||
|
||||
## GraphQL section (apply when the diff touches schemas or resolvers)
|
||||
|
||||
- 🟡 `[convention]` **Resolver N+1** — does a new list-field resolver fetch per-item (a query inside a loop, or a per-parent resolver hitting the DB)? Look for a dataloader/batching layer; its absence on a list path is the finding.
|
||||
- 🟡 `[convention]` **Depth/complexity limits** — if the diff grows the schema's reachable graph (new nested relations), is there a depth or complexity limit configured anywhere? An unlimited schema is a self-service DoS invitation; check the server setup before assuming.
|
||||
- 🟡 `[convention]` **Connection-style pagination** — list fields over unbounded collections should use the repo's established pagination idiom (connections/edges or equivalent). The same bounded-set exemption as REST item 1 applies — and state it when you use it. Breaking a published schema field without a deprecation cycle falls under item 5's 🔴 `[correctness]` bar.
|
||||
|
||||
## Ground-truth discipline
|
||||
|
||||
- READ the route registration and middleware chain, not just the handler — auth decisions and pagination defaults often live up-stack.
|
||||
- `fs_grep` for the spec file (OpenAPI, proto, GraphQL schema) that publishes the shape the diff changes; the spec, not the struct, is the contract.
|
||||
- Check sibling endpoints for the house error shape, pagination idiom, and auth annotation style before flagging deviation — the strongest finding cites the sibling at file:line.
|
||||
|
||||
## What this skill does NOT check
|
||||
|
||||
- Whether auth is bypassable, input is exploitable, or errors leak abusable secrets → `security-review`.
|
||||
- Whether state-changing handlers are mechanically idempotent, atomic, or retry-safe → `transactional-integrity`.
|
||||
- Log lines, levels, and message conventions in handlers → `logging-discipline`.
|
||||
- Metrics, alerts, and dashboards for new endpoints → `observability-review`.
|
||||
@@ -28,6 +28,7 @@ points: 1.0 # engineer-days; ~1.0 per the sizing rule
|
||||
plan: PLAN-<slug>.md
|
||||
blocked_by: [] # TASK ids that must be complete first
|
||||
created: YYYY-MM-DD
|
||||
surfaces: [] # this task's surfaces; omitted = inherit the plan's list
|
||||
---
|
||||
|
||||
## What
|
||||
@@ -47,6 +48,8 @@ One paragraph: what this task produces, named concretely (files, symbols, behavi
|
||||
|
||||
Status lives in frontmatter — there are no lifecycle directories. `status: complete` plus all boxes checked IS done.
|
||||
|
||||
`surfaces` come from the plan's `## Quality bar`; rigor is run-level only — there is no per-task rigor.
|
||||
|
||||
## log.md conventions
|
||||
|
||||
Append-only. Each entry is an H2: `## YYYY-MM-DD — <short label>` (`created`, `started`, `implemented`, `diverged`, `completed`, ...). Body is 1-3 sentences of prose; structured data lives in markdown links (branch URLs, commit SHAs, PR links). Never rewrite an old entry — add a new one.
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
---
|
||||
description: Review the background-work surface contract of a change - queue/stream consumers, scheduled jobs, and cron handlers. Checks retry/backoff policy, DLQ/poison-message routing, graceful-shutdown drain, concurrency/prefetch bounds, and visibility-timeout vs processing-time reasoning. Load when a diff touches queue/job/cron consumer registration, handler wiring, or schedule definitions. Findings fold into the standard code-review severity taxonomy. Grants read-only filesystem access for tracing consumer registration, transport config, and shutdown paths.
|
||||
enabled_tools: fs_read, fs_grep, fs_glob, fs_cat, fs_ls
|
||||
---
|
||||
You are reviewing background-work wiring. The generic correctness checklist asks "does this handler process a message?"; you ask **"what happens to this consumer on the bad days — a poison message, a deploy mid-batch, a downstream outage?"** A worker's contract is with the queue, the scheduler, and the deploy pipeline, not with a single happy-path message. Most worker incidents are not broken handler logic — they are a queue wedged behind one malformed message, in-flight work silently dropped by a rolling restart, or a retry storm hammering a struggling dependency.
|
||||
|
||||
## When to load this skill
|
||||
|
||||
The diff touches ANY of: queue/stream consumer registration, job/worker handler wiring, cron or schedule definitions, or the transport configuration behind them (retry counts, prefetch, visibility timeouts, shutdown hooks). If the diff is handler business logic behind unchanged wiring — unload; this checklist has nothing for you. Note: a diff that wires a consumer AND changes state is two reviews — this skill covers the consumer contract, and `transactional-integrity` covers the state changes; state-changing worker diffs load BOTH.
|
||||
|
||||
## Marker semantics
|
||||
|
||||
Every checklist item below carries a severity emoji AND a `[convention]` or `[correctness]` marker; both ride in the finding title so downstream tooling can act on them mechanically. `[convention]` findings are rigor-foldable (the orchestrator may lower them under a relaxed quality bar) and rejectable — but ONLY with cited evidence: a repo convention at file:line, or a recorded plan decision. `[correctness]` is reserved for contract breaks; those findings are neither foldable nor rejectable.
|
||||
|
||||
## Linters and mechanized checks
|
||||
|
||||
The review orchestrator runs mechanized checks (config validators, schema checks for queue/schedule definitions); your CONTEXT may already include their output — do not re-derive it. Spend your prose on what linters cannot reach: whether a retry policy exists at all, where a poison message goes, what a deploy does to in-flight work. If the repo plausibly warrants a linter config it lacks, emit a 🟢 `[convention]` finding naming the gap.
|
||||
|
||||
## The checklist
|
||||
|
||||
Severities below are the production bar. Each item is a context-sensitive question, not an absolute — read the transport's own guarantees and the deployment story before flagging, and when you rely on an exemption, state it so the next reviewer sees it was considered.
|
||||
|
||||
### 1. 🟡 `[convention]` No retry/backoff policy where the transport provides none
|
||||
|
||||
For each new or rewired consumer: when the handler fails, who retries, how many times, with what backoff? Some transports provide redelivery with backoff out of the box — READ the transport config before claiming they do here. If neither the transport nor the code establishes a policy, a transient downstream blip becomes permanent message loss (or an immediate hot-loop of retries). Name the consumer, the transport, and what a single failure currently does. A consumer whose transport is configured with sane redelivery is exempt — cite the config at file:line.
|
||||
|
||||
### 2. 🟡 `[convention]` No DLQ/poison-message route — one bad message wedges the queue
|
||||
|
||||
A message that fails every retry must go SOMEWHERE terminal: a dead-letter queue, a parked table, a quarantine topic. Trace the exhausted-retries path for each consumer the diff adds: if the message returns to the head of the queue forever, one malformed payload halts all processing behind it. Ordered/single-partition consumers are the highest-blast-radius case. Where the message *lands* is your question; whether the handler's error path also acknowledges correctly under at-least-once delivery is `transactional-integrity`'s.
|
||||
|
||||
### 3. 🟡 `[convention]` No graceful-shutdown drain — in-flight work lost on deploy
|
||||
|
||||
Every deploy sends this worker a termination signal mid-message. Does the diff's worker stop taking new work, finish (or cleanly nack) what is in flight, and exit within the platform's grace period? Look for a shutdown hook, drain loop, or the framework's built-in drain — and check the termination grace configured for the deployment. Exemptions are real: a stateless cron job reading a read-only source loses nothing on interruption, and an at-least-once transport redelivers whatever was in flight (making drain an efficiency concern, not a loss) — say explicitly which exemption you are relying on. The item bites hardest for at-least-once consumers with long-running in-flight work and for anything ack-early.
|
||||
|
||||
### 4. 🟢 `[convention]` Unbounded concurrency/prefetch
|
||||
|
||||
Does the new consumer bound how many messages it processes at once — worker-pool size, prefetch/fetch-count, max in-flight? An unbounded consumer amplifies a queue backlog into a self-inflicted outage: memory blowup, connection-pool exhaustion, a thundering herd against the downstream the handler calls. Check the transport defaults before flagging — some default to a sane prefetch; some default to unlimited. A low-volume schedule-driven job with structurally bounded input is exempt.
|
||||
|
||||
### 5. 🟢 `[convention]` Visibility-timeout vs processing-time reasoning absent
|
||||
|
||||
Where the transport uses a visibility timeout, lease, or lock (with redelivery when it expires): is there any evidence — a comment, a config value derived from measurements, a heartbeat/extension call — that the timeout exceeds the handler's realistic worst-case processing time? A timeout shorter than processing time means the message redelivers WHILE the first attempt is still running: duplicate concurrent processing by design. You flag the absent reasoning; whether the handler survives that concurrent duplicate is `transactional-integrity`'s question. Transports with no visibility/lease mechanism are exempt.
|
||||
|
||||
## Ground-truth discipline
|
||||
|
||||
- READ the transport/framework configuration, not just the handler — retry counts, DLQ wiring, prefetch, and drain behavior live in config and registration code, not in the handler body.
|
||||
- `fs_grep` sibling consumers for the established idioms (DLQ naming, shutdown hooks, backoff helpers) — a new consumer skipping the house pattern is the strongest form of evidence; cite the sibling at file:line.
|
||||
- Check the deployment manifests for termination grace periods when reasoning about drain — the code's drain loop is only as good as the time the platform gives it.
|
||||
- Do not flag a missing guard the transport demonstrably provides; cite the config that provides it instead.
|
||||
|
||||
## What this skill does NOT check
|
||||
|
||||
- Whether the handler is idempotent under redelivery, atomic across writes, or safe against dual-writes to a DB plus an external system → `transactional-integrity` (state-changing worker diffs load both skills).
|
||||
- Whether job payloads, queue names, or worker logs expose secrets or abusable data → `security-review` and `logging-discipline`.
|
||||
- Metrics, alerts, and dashboards for the new worker (queue depth, processing lag, failure rate) → `observability-review`.
|
||||
- Log lines, levels, and message conventions inside the handler → `logging-discipline`.
|
||||
+64
-54
@@ -11,64 +11,74 @@
|
||||
# - <agent-name>_AGENT_SESSION
|
||||
# - <agent-name>_VARIABLES (as JSON array of key-value pairs; e.g. '[{"name": "username", "value": "alex"}]')
|
||||
|
||||
model: openai:gpt-4o # Specify the LLM to use
|
||||
temperature: null # Set default temperature parameter, range (0, 1)
|
||||
top_p: null # Set default top-p parameter, with a range of (0, 1) or (0, 2) depending on the model
|
||||
reasoning_effort: null # Reasoning effort level for models that support it (e.g. low, medium, high).
|
||||
# Only valid when the agent's model declares reasoning_levels.
|
||||
agent_session: null # Set a session to use when starting the agent. (e.g. temp, default); defaults to globally set agent_session
|
||||
name: <agent-name> # Name of the agent, used in the UI and logs
|
||||
description: <description> # Description of the agent, used in the UI
|
||||
version: 1 # Version of the agent
|
||||
model: openai:gpt-4o # Specify the LLM to use
|
||||
temperature: null # Set default temperature parameter, range (0, 1)
|
||||
top_p: null # Set default top-p parameter, with a range of (0, 1) or (0, 2) depending on the model
|
||||
reasoning_effort:
|
||||
null # Reasoning effort level for models that support it (e.g. low, medium, high).
|
||||
# Only valid when the agent's model declares reasoning_levels.
|
||||
agent_session: null # Set a session to use when starting the agent. (e.g. temp, default); defaults to globally set agent_session
|
||||
name: <agent-name> # Name of the agent, used in the UI and logs
|
||||
description: <description> # Description of the agent, used in the UI
|
||||
version: 1 # Version of the agent
|
||||
# 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
|
||||
# prompt it to continue when incomplete tasks remain.
|
||||
# See the [Todo System documentation](https://github.com/Dark-Alex-17/coyote/wiki/TODO-System) for more information
|
||||
auto_continue: false # Enable automatic continuation when incomplete todos remain
|
||||
max_auto_continues: 10 # Maximum number of automatic continuations before stopping
|
||||
inject_todo_instructions: true # Inject the default todo tool usage instructions into the agent's system prompt
|
||||
continuation_prompt: null # Custom prompt used when auto-continuing (optional; uses default if null)
|
||||
auto_continue: false # Enable automatic continuation when incomplete todos remain
|
||||
max_auto_continues: 10 # Maximum number of automatic continuations before stopping
|
||||
inject_todo_instructions: true # Inject the default todo tool usage instructions into the agent's system prompt
|
||||
continuation_prompt: null # Custom prompt used when auto-continuing (optional; uses default if null)
|
||||
# Sub-Agent Spawning System
|
||||
# Enable this agent to spawn and manage child agents in parallel.
|
||||
# See https://github.com/Dark-Alex-17/coyote/wiki/Agents for detailed documentation.
|
||||
can_spawn_agents: false # Enable the agent to spawn child agents
|
||||
can_spawn_agents: false # Enable the agent to spawn child agents
|
||||
# spawnable_agents: # Optional whitelist restricting which agents can be spawned via `agent__spawn`.
|
||||
# - explore # If omitted (the default), ALL installed agents are spawnable. This is the unrestricted default.
|
||||
# - coder # Provide a list to restrict. Match is exact and case-sensitive (use directory names).
|
||||
# - oracle # An empty list ([]) means literally nothing spawnable.
|
||||
# Also filters `agent__list_available` output so the LLM only sees what it can spawn.
|
||||
# Graph agents (graph.yaml) ignore this; they declare spawn targets in agent nodes.
|
||||
max_concurrent_agents: 4 # Maximum number of agents that can run simultaneously
|
||||
max_agent_depth: 3 # Maximum nesting depth for sub-agents (prevents runaway spawning)
|
||||
max_concurrent_jobs: 5 # Max background jobs (`job__*` tools) running at once for this agent
|
||||
# (overrides the global setting; 0 disables background jobs for this agent)
|
||||
inject_spawn_instructions: true # Inject the default agent spawning instructions into the agent's system prompt
|
||||
summarization_model: null # Model to use for summarizing sub-agent output (e.g. 'openai:gpt-4o-mini'); defaults to current model
|
||||
summarization_threshold: 4000 # Character threshold above which sub-agent output is summarized before returning to parent
|
||||
escalation_timeout: 300 # Seconds a sub-agent waits for a user interaction response before timing out (default: 5 minutes)
|
||||
mcp_servers: # Optional list of MCP servers that the agent utilizes
|
||||
- github # Corresponds to the name of an MCP server in the `<coyote-config-dir>/mcp.json` file
|
||||
global_tools: # Optional list of additional global tools to enable for the agent; i.e. not tools specific to the agent
|
||||
# Also filters `agent__list_available` output so the LLM only sees what it can spawn.
|
||||
# Graph agents (graph.yaml) ignore this; they declare spawn targets in agent nodes.
|
||||
max_concurrent_agents: 4 # Maximum number of agents that can run simultaneously
|
||||
max_agent_depth: 3 # Maximum nesting depth for sub-agents (prevents runaway spawning)
|
||||
max_concurrent_jobs:
|
||||
5 # Max background jobs (`job__*` tools) running at once for this agent
|
||||
# (overrides the global setting; 0 disables background jobs for this agent)
|
||||
inject_spawn_instructions: true # Inject the default agent spawning instructions into the agent's system prompt
|
||||
summarization_model: null # Model to use for summarizing sub-agent output (e.g. 'openai:gpt-4o-mini'); defaults to current model
|
||||
summarization_threshold: 4000 # Character threshold above which sub-agent output is summarized before returning to parent
|
||||
escalation_timeout: 300 # Seconds a sub-agent waits for a user interaction response before timing out (default: 5 minutes)
|
||||
mcp_servers: # Optional list of MCP servers that the agent utilizes
|
||||
- github # Corresponds to the name of an MCP server in the `<coyote-config-dir>/mcp.json` file
|
||||
mcp_tools: # Optional per-server tool allowlist for the agent's MCP servers
|
||||
github: # (glob patterns: * and ?). Intersects with the global config,
|
||||
- get_* # mcp.json `allowedTools`, and every other configured layer. It
|
||||
- search_* # can only narrow access, never widen it.
|
||||
global_tools: # Optional list of additional global tools to enable for the agent; i.e. not tools specific to the agent
|
||||
- web_search
|
||||
- fs
|
||||
- python
|
||||
skills_enabled: true # Master switch for skills in this agent (default: inherit from global).
|
||||
# Skills also require `function_calling_support: true` in the global config.
|
||||
enabled_skills: # Optional list of skills available when this agent runs.
|
||||
# Must be a subset of global `visible_skills`. Omit to inherit the global default.
|
||||
skills_enabled:
|
||||
true # Master switch for skills in this agent (default: inherit from global).
|
||||
# Skills also require `function_calling_support: true` in the global config.
|
||||
enabled_skills: # Optional list of skills available when this agent runs.
|
||||
# Must be a subset of global `visible_skills`. Omit to inherit the global default.
|
||||
- git-master
|
||||
- ai-slop-remover
|
||||
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.
|
||||
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.
|
||||
|
||||
dynamic_instructions: false # Whether to use dynamic instructions for the agent; if false, static instructions are used
|
||||
instructions: | # Static instructions for the agent; ignored if dynamic instructions are used
|
||||
dynamic_instructions: false # Whether to use dynamic instructions for the agent; if false, static instructions are used
|
||||
instructions:
|
||||
| # Static instructions for the agent; ignored if dynamic instructions are used
|
||||
You are a AI agent designed to demonstrate agent capabilities.
|
||||
|
||||
<tools>
|
||||
@@ -88,12 +98,12 @@ instructions: | # Static instructions for the agent; ignored if
|
||||
<user>
|
||||
username: {{username}}
|
||||
</user>
|
||||
variables: # Optional variables for the agent
|
||||
# The variables defined above like {{__variable_name__}} are automatically available
|
||||
variables: # Optional variables for the agent
|
||||
# The variables defined above like {{__variable_name__}} are automatically available
|
||||
- name: username
|
||||
description: Your user name
|
||||
default: null # A default value for this variable; if null, the variable must be provided when starting the agent
|
||||
conversation_starters: # Optional conversation starters for the agent
|
||||
default: null # A default value for this variable; if null, the variable must be provided when starting the agent
|
||||
conversation_starters: # Optional conversation starters for the agent
|
||||
- What is the meaning of life?
|
||||
- Tell me a joke.
|
||||
- What is the capital of France?
|
||||
@@ -104,15 +114,15 @@ conversation_starters: # Optional conversation starters for the agent
|
||||
- How do I stay motivated?
|
||||
- What is the best way to exercise?
|
||||
- How do I manage my time effectively?
|
||||
documents: # Optional documents to load for the agent
|
||||
# To enable graph-based RAG (entity/relationship extraction + knowledge graph retrieval),
|
||||
# set `rag_extractor_model` in your global config.yaml.
|
||||
# See https://github.com/Dark-Alex-17/coyote/wiki/RAG#graph-based-rag
|
||||
- git:/some/repo # Explicitly tell Coyote to use the 'git' document loader using an absolute path
|
||||
- pdf:some-pdf-file.pdf # Explicitly tell Coyote to use the 'pdf' document loader using a relative path
|
||||
documents: # Optional documents to load for the agent
|
||||
# To enable graph-based RAG (entity/relationship extraction + knowledge graph retrieval),
|
||||
# set `rag_extractor_model` in your global config.yaml.
|
||||
# See https://github.com/Dark-Alex-17/coyote/wiki/RAG#graph-based-rag
|
||||
- git:/some/repo # Explicitly tell Coyote to use the 'git' document loader using an absolute path
|
||||
- pdf:some-pdf-file.pdf # Explicitly tell Coyote to use the 'pdf' document loader using a relative path
|
||||
- https://some-website.com/some-page
|
||||
- some-file.pdf # File with relative path to the <coyote-config-dir>/agents/<agent-name> directory; i.e. file in the same directory as this config file
|
||||
- ~/some-file.txt # File in the user's home directory
|
||||
- /absolute/path/to/some-file.md # File with absolute path
|
||||
- /absolute/path/**/NAME.txt # Find all NAME.txt files in the specified directory and all its subdirectories
|
||||
- some-file.pdf # File with relative path to the <coyote-config-dir>/agents/<agent-name> directory; i.e. file in the same directory as this config file
|
||||
- ~/some-file.txt # File in the user's home directory
|
||||
- /absolute/path/to/some-file.md # File with absolute path
|
||||
- /absolute/path/**/NAME.txt # Find all NAME.txt files in the specified directory and all its subdirectories
|
||||
- /absolute/path/to/*/README.md # Find all README.md files in all immediate subdirectories of the specified directory (depth=1)
|
||||
|
||||
+14
-1
@@ -93,7 +93,8 @@ enabled_tools: null # Which tools to enable by default.
|
||||
# - web_search_coyote
|
||||
# Example (comma-separated form):
|
||||
# enabled_tools: fs,web_search_coyote
|
||||
visible_tools: # Which tools are visible to be compiled (and are thus able to be defined in 'enabled_tools')
|
||||
visible_tools: # Which tools are visible to be compiled (and are thus able to be defined in 'enabled_tools').
|
||||
# Null/missing = all tools in the global tools dir are visible; [] = none.
|
||||
# - ast_grep.sh
|
||||
# - demo_py.py
|
||||
# - demo_sh.sh
|
||||
@@ -137,6 +138,18 @@ enabled_mcp_servers: null # Which MCP servers to enable by default.
|
||||
# - slack
|
||||
# Example (comma-separated form):
|
||||
# enabled_mcp_servers: github,slack,ddg-search
|
||||
mcp_tools: null # Per-server MCP tool allowlists (glob patterns: * and ? supported).
|
||||
# Tools that match no pattern are hidden from the model as if they
|
||||
# don't exist. Stacks with the other allowlist layers (mcp.json
|
||||
# `allowedTools`, role, agent, session, skill, graph node). Every
|
||||
# configured layer must allow a tool, so layers only ever narrow.
|
||||
# An empty list blocks all of a server's tools.
|
||||
# Example:
|
||||
# mcp_tools:
|
||||
# github:
|
||||
# - get_*
|
||||
# - list_*
|
||||
# slack: []
|
||||
no_workspace_mcp: false # Disable loading workspace-local MCP servers (default: false).
|
||||
# When false (the default), Coyote merges the first workspace MCP config it finds
|
||||
# into the global MCP registry at startup, checking in order:
|
||||
|
||||
@@ -16,6 +16,10 @@ enabled_tools: # Tools to enable for this role. Accepts a
|
||||
enabled_mcp_servers: # MCP servers to enable for this role. Accepts a YAML list (preferred)
|
||||
- github # or a comma-separated string (e.g. `enabled_mcp_servers: github,gitmcp`).
|
||||
- gitmcp # Use `all` to enable every configured MCP server.
|
||||
mcp_tools: # Per-server MCP tool allowlists for this role (globs: * and ?).
|
||||
github: # Intersects with the global config / mcp.json `allowedTools`.
|
||||
- get_* # Layers only narrow. Tools matching no pattern are hidden from
|
||||
- search_* # the model as if they don't exist.
|
||||
skills_enabled: true # Master switch for skills in this role (default: inherit from global).
|
||||
# Skills also require `function_calling_support: true` in the global config.
|
||||
enabled_skills: # Skills available when this role is active. Accepts a YAML list (preferred)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Documentation: https://docs.brew.sh/Formula-Cookbook
|
||||
# https://rubydoc.brew.sh/Formula
|
||||
class Coyote < Formula
|
||||
desc "All-in-one, batteries-included LLM runtime"
|
||||
desc "The batteries-included runtime for LLMs"
|
||||
homepage "https://github.com/Dark-Alex-17/coyote"
|
||||
if OS.mac? and Hardware::CPU.arm?
|
||||
url "https://github.com/Dark-Alex-17/coyote/releases/download/v$version/coyote-aarch64-apple-darwin.tar.gz"
|
||||
|
||||
@@ -51,6 +51,10 @@ global_tools: # Tool universe an `llm` node's `tools:` whit
|
||||
mcp_servers: # MCP servers an `llm` node may reference via `mcp:<server>`
|
||||
- ddg-search
|
||||
|
||||
mcp_tools: # Optional per-server tool allowlists (globs: * and ?) applied to
|
||||
ddg-search: # every node that uses `mcp:<server>`; intersects with the other
|
||||
- search # allowlist layers (global config, agent, mcp.json `allowedTools`).
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Skills policy (optional)
|
||||
# Skills only attach to `llm` nodes inside a graph. Both fields are optional.
|
||||
@@ -402,6 +406,9 @@ nodes:
|
||||
tools: # Narrow whitelist: exactly these entries, nothing else
|
||||
- web_search_coyote # an exact global-tool / custom-tool name
|
||||
- mcp:ddg-search # `mcp:<server>` includes that server's functions
|
||||
mcp_tools: # Optional per-node narrowing of MCP tools (globs: * and ?)
|
||||
ddg-search: # keys must be servers this graph enables; intersects with
|
||||
- search # the graph-level mcp_tools above and every other layer
|
||||
model: claude:claude-haiku-4-5 # Optional per-node model override
|
||||
temperature: 0.3 # Optional per-node sampling override
|
||||
reasoning_effort: null # Optional per-node reasoning effort override (e.g. low, medium, high)
|
||||
|
||||
+140
-62
@@ -16,6 +16,8 @@ param(
|
||||
[string]$BinDir = $env:BIN_DIR
|
||||
)
|
||||
|
||||
if ($Version -and $Version -match '^[0-9]') { $Version = "v$Version" }
|
||||
|
||||
$Repo = 'Dark-Alex-17/coyote'
|
||||
|
||||
function Write-Info($msg) { Write-Host "[coyote-install] $msg" }
|
||||
@@ -61,79 +63,155 @@ if ($os -eq 'windows') {
|
||||
if ($arch -eq 'x86_64') { $candidates += 'coyote-x86_64-apple-darwin.tar.gz' }
|
||||
else { $candidates += 'coyote-aarch64-apple-darwin.tar.gz' }
|
||||
} elseif ($os -eq 'linux') {
|
||||
if ($arch -eq 'x86_64') {
|
||||
$candidates += 'coyote-x86_64-unknown-linux-gnu.tar.gz'
|
||||
$candidates += 'coyote-x86_64-unknown-linux-musl.tar.gz'
|
||||
} else {
|
||||
$candidates += 'coyote-aarch64-unknown-linux-musl.tar.gz'
|
||||
$libc = 'musl'
|
||||
try { getconf GNU_LIBC_VERSION *> $null; if ($LASTEXITCODE -eq 0) { $libc = 'gnu' } } catch { }
|
||||
try { if ((ldd --version 2>&1 | Out-String) -imatch 'glibc') { $libc = 'gnu' } } catch { }
|
||||
if ($libc -eq 'gnu') {
|
||||
# ldconfig lives in /usr/sbin on Debian/Ubuntu, often missing from non-root
|
||||
# PATHs, so try its known locations and fall back to probing library dirs.
|
||||
$libssl3 = $false
|
||||
foreach ($ldc in @('ldconfig', '/sbin/ldconfig', '/usr/sbin/ldconfig')) {
|
||||
try { if ((& $ldc -p 2>&1 | Out-String) -match 'libssl\.so\.3') { $libssl3 = $true; break } } catch { }
|
||||
}
|
||||
if (-not $libssl3) {
|
||||
foreach ($libDir in @('/usr/lib/*/libssl.so.3', '/lib/*/libssl.so.3', '/usr/lib64/libssl.so.3', '/usr/lib/libssl.so.3', '/usr/local/lib/libssl.so.3', '/usr/local/lib/*/libssl.so.3')) {
|
||||
if (Get-Item -Path $libDir -ErrorAction SilentlyContinue) { $libssl3 = $true; break }
|
||||
}
|
||||
}
|
||||
if ($libssl3) {
|
||||
$candidates += "coyote-$arch-unknown-linux-gnu.tar.gz"
|
||||
} else {
|
||||
Write-Info "glibc detected but OpenSSL 3 (libssl.so.3) not found; using musl build"
|
||||
}
|
||||
}
|
||||
$candidates += "coyote-$arch-unknown-linux-musl.tar.gz"
|
||||
} else {
|
||||
Fail "Unsupported OS for this installer: $os"
|
||||
}
|
||||
|
||||
$asset = $null
|
||||
foreach ($c in $candidates) {
|
||||
$asset = $release.assets | Where-Object { $_.name -eq $c } | Select-Object -First 1
|
||||
if ($asset) { break }
|
||||
}
|
||||
if (-not $asset) {
|
||||
Write-Error "No matching asset found for $os-$arch. Tried:"; $candidates | ForEach-Object { Write-Error " - $_" }
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Info "Selected asset: $($asset.name)"
|
||||
Write-Info "Download URL: $($asset.browser_download_url)"
|
||||
|
||||
$tmp = New-Item -ItemType Directory -Force -Path ([IO.Path]::Combine([IO.Path]::GetTempPath(), "coyote-$(Get-Random)"))
|
||||
$archive = Join-Path $tmp.FullName 'asset'
|
||||
try { Invoke-WebRequest -UseBasicParsing -Headers @{ 'User-Agent' = 'coyote-installer' } -Uri $asset.browser_download_url -OutFile $archive } catch { Fail "Failed to download asset. $_" }
|
||||
|
||||
$extractDir = Join-Path $tmp.FullName 'extract'; New-Item -ItemType Directory -Force -Path $extractDir | Out-Null
|
||||
try {
|
||||
$exec = if ($isWin) { 'coyote.exe' } else { 'coyote' }
|
||||
$dest = Join-Path $BinDir $exec
|
||||
|
||||
if ($asset.name -match '\.zip$') {
|
||||
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||
[System.IO.Compression.ZipFile]::ExtractToDirectory($archive, $extractDir)
|
||||
} elseif ($asset.name -match '\.tar\.gz$' -or $asset.name -match '\.tgz$') {
|
||||
$tar = Get-Command tar -ErrorAction SilentlyContinue
|
||||
if ($tar) { & $tar.Source -xzf $archive -C $extractDir }
|
||||
else { Fail "Asset is tar archive but 'tar' is not available." }
|
||||
} else {
|
||||
try { Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::ExtractToDirectory($archive, $extractDir) }
|
||||
catch {
|
||||
$tar = Get-Command tar -ErrorAction SilentlyContinue
|
||||
if ($tar) { & $tar.Source -xf $archive -C $extractDir } else { Fail "Unknown archive format; neither zip nor tar workable." }
|
||||
$installed = $false
|
||||
$tried = @()
|
||||
$attempt = 0
|
||||
foreach ($c in $candidates) {
|
||||
$asset = $release.assets | Where-Object { $_.name -eq $c } | Select-Object -First 1
|
||||
if (-not $asset) {
|
||||
$tried += "${c}: no matching release asset"
|
||||
continue
|
||||
}
|
||||
|
||||
$attempt++
|
||||
$work = New-Item -ItemType Directory -Force -Path (Join-Path $tmp.FullName "attempt-$attempt")
|
||||
|
||||
Write-Info "Selected asset: $($asset.name)"
|
||||
Write-Info "Download URL: $($asset.browser_download_url)"
|
||||
|
||||
$archive = Join-Path $work.FullName 'asset'
|
||||
try {
|
||||
Invoke-WebRequest -UseBasicParsing -Headers @{ 'User-Agent' = 'coyote-installer' } -Uri $asset.browser_download_url -OutFile $archive
|
||||
} catch {
|
||||
Write-Info "Failed to download ${c}; trying next candidate. $_"
|
||||
$tried += "${c}: download failed"
|
||||
continue
|
||||
}
|
||||
|
||||
$extractDir = Join-Path $work.FullName 'extract'; New-Item -ItemType Directory -Force -Path $extractDir | Out-Null
|
||||
|
||||
try {
|
||||
if ($asset.name -match '\.zip$') {
|
||||
Add-Type -AssemblyName System.IO.Compression.FileSystem
|
||||
[System.IO.Compression.ZipFile]::ExtractToDirectory($archive, $extractDir)
|
||||
} elseif ($asset.name -match '\.tar\.gz$' -or $asset.name -match '\.tgz$') {
|
||||
$tar = Get-Command tar -ErrorAction SilentlyContinue
|
||||
if ($tar) { & $tar.Source -xzf $archive -C $extractDir }
|
||||
else { throw "Asset is tar archive but 'tar' is not available." }
|
||||
} else {
|
||||
try { Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::ExtractToDirectory($archive, $extractDir) }
|
||||
catch {
|
||||
$tar = Get-Command tar -ErrorAction SilentlyContinue
|
||||
if ($tar) { & $tar.Source -xf $archive -C $extractDir } else { throw "Unknown archive format; neither zip nor tar workable." }
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
Write-Info "Failed to extract ${c}; trying next candidate. $_"
|
||||
$tried += "${c}: extract failed"
|
||||
continue
|
||||
}
|
||||
|
||||
$bin = $null
|
||||
Get-ChildItem -Recurse -File $extractDir | ForEach-Object {
|
||||
if ($isWin) { if ($_.Name -ieq 'coyote.exe') { $bin = $_.FullName } }
|
||||
else { if ($_.Name -ieq 'coyote') { $bin = $_.FullName } }
|
||||
}
|
||||
if (-not $bin) {
|
||||
Write-Info "Could not find coyote binary inside ${c}; trying next candidate"
|
||||
$tried += "${c}: no coyote binary in archive"
|
||||
continue
|
||||
}
|
||||
|
||||
if (-not $isWin) { try { & chmod +x -- $bin } catch {} }
|
||||
|
||||
$works = $false
|
||||
try { & $bin --version *> $null; if ($LASTEXITCODE -eq 0) { $works = $true } } catch { }
|
||||
if (-not $works -and -not $isWin) {
|
||||
# The temp dir may live on a noexec mount; retry from a probe file in
|
||||
# the install directory before rejecting.
|
||||
$probe = Join-Path $BinDir ".coyote-install-probe-$PID"
|
||||
try {
|
||||
Copy-Item -Force $bin $probe
|
||||
& chmod +x -- $probe
|
||||
& $probe --version *> $null
|
||||
if ($LASTEXITCODE -eq 0) { $works = $true }
|
||||
} catch { } finally {
|
||||
Remove-Item -Force -ErrorAction SilentlyContinue $probe
|
||||
}
|
||||
}
|
||||
if (-not $works) {
|
||||
Write-Info "Downloaded $c but it failed to run on this system; trying next candidate"
|
||||
$tried += "${c}: binary failed to run on this system"
|
||||
continue
|
||||
}
|
||||
|
||||
Copy-Item -Force $bin $dest
|
||||
Write-Info "Installed: $dest"
|
||||
$installed = $true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
$bin = $null
|
||||
Get-ChildItem -Recurse -File $extractDir | ForEach-Object {
|
||||
if ($isWin) { if ($_.Name -ieq 'coyote.exe') { $bin = $_.FullName } }
|
||||
else { if ($_.Name -ieq 'coyote') { $bin = $_.FullName } }
|
||||
}
|
||||
if (-not $bin) { Fail "Could not find coyote binary inside the archive." }
|
||||
if (-not $installed) {
|
||||
Write-Error "No usable asset found for $os-$arch. Tried:"
|
||||
$tried | ForEach-Object { Write-Error " - $_" }
|
||||
exit 1
|
||||
}
|
||||
|
||||
if (-not $isWin) { try { & chmod +x -- $bin } catch {} }
|
||||
|
||||
$exec = if ($isWin) { 'coyote.exe'} else { 'coyote' }
|
||||
$dest = Join-Path $BinDir $exec
|
||||
Copy-Item -Force $bin $dest
|
||||
Write-Info "Installed: $dest"
|
||||
|
||||
if ($isWin) {
|
||||
$pathParts = ($env:Path -split ';') | Where-Object { $_ -ne '' }
|
||||
if ($pathParts -notcontains $BinDir) {
|
||||
$userPath = [Environment]::GetEnvironmentVariable('Path', 'User'); if (-not $userPath) { $userPath = '' }
|
||||
if (-not ($userPath -split ';' | Where-Object { $_ -eq $BinDir })) {
|
||||
$newUserPath = if ($userPath.Trim().Length -gt 0) { "$userPath;$BinDir" } else { $BinDir }
|
||||
[Environment]::SetEnvironmentVariable('Path', $newUserPath, 'User')
|
||||
Write-Info "Added to User PATH: $BinDir (restart shell to take effect)"
|
||||
if ($isWin) {
|
||||
$pathParts = ($env:Path -split ';') | Where-Object { $_ -ne '' }
|
||||
if ($pathParts -notcontains $BinDir) {
|
||||
# Read/write the User PATH via the registry directly: the [Environment]
|
||||
# round-trip expands %VAR% entries and bakes them in on write.
|
||||
$regKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
|
||||
if ($regKey) {
|
||||
$userPath = [string]$regKey.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
|
||||
if (-not (($userPath -split ';') -contains $BinDir)) {
|
||||
$newUserPath = if ($userPath.Trim().Length -gt 0) { "$userPath;$BinDir" } else { $BinDir }
|
||||
$regKey.SetValue('Path', $newUserPath, [Microsoft.Win32.RegistryValueKind]::ExpandString)
|
||||
Write-Info "Added to User PATH: $BinDir (restart shell to take effect)"
|
||||
}
|
||||
$regKey.Close()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (-not ($env:PATH -split ':' | Where-Object { $_ -eq $BinDir })) {
|
||||
Write-Info "Note: $BinDir is not in PATH. Add it to your shell profile."
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (-not ($env:PATH -split ':' | Where-Object { $_ -eq $BinDir })) {
|
||||
Write-Info "Note: $BinDir is not in PATH. Add it to your shell profile."
|
||||
}
|
||||
|
||||
Write-Info "Done. Try: coyote --help"
|
||||
} finally {
|
||||
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue $tmp
|
||||
}
|
||||
|
||||
Write-Info "Done. Try: coyote --help"
|
||||
|
||||
|
||||
+214
-144
@@ -13,8 +13,6 @@ set -euo pipefail
|
||||
# --bin-dir <dir> Install directory (default: /usr/local/bin or ~/.local/bin). Or set BIN_DIR.
|
||||
|
||||
REPO="Dark-Alex-17/coyote"
|
||||
VERSION="${COYOTE_VERSION:-}"
|
||||
BIN_DIR="${BIN_DIR:-}"
|
||||
|
||||
usage() {
|
||||
echo "coyote installer (Linux/macOS)"
|
||||
@@ -25,24 +23,6 @@ usage() {
|
||||
echo " -h, --help Show help"
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--version) VERSION="$2"; shift 2;;
|
||||
--bin-dir) BIN_DIR="$2"; shift 2;;
|
||||
-h|--help) usage; exit 0;;
|
||||
*) echo "Unknown argument: $1" >&2; usage; exit 2;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [[ -z "${BIN_DIR}" ]]; then
|
||||
if [[ -w "/usr/local/bin" ]]; then
|
||||
BIN_DIR="/usr/local/bin"
|
||||
else
|
||||
BIN_DIR="${HOME}/.local/bin"
|
||||
fi
|
||||
fi
|
||||
mkdir -p "${BIN_DIR}"
|
||||
|
||||
log() {
|
||||
echo "[coyote-install] $*"
|
||||
}
|
||||
@@ -54,42 +34,6 @@ need_cmd() {
|
||||
fi
|
||||
}
|
||||
|
||||
need_cmd uname
|
||||
need_cmd mktemp
|
||||
need_cmd tar
|
||||
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
DL=curl
|
||||
elif command -v wget >/dev/null 2>&1; then
|
||||
DL=wget
|
||||
else
|
||||
echo "Error: need curl or wget" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
UNAME_OS=$(uname -s | tr '[:upper:]' '[:lower:]')
|
||||
case "$UNAME_OS" in
|
||||
linux) OS=linux ;;
|
||||
darwin) OS=darwin ;;
|
||||
*) echo "Error: unsupported OS '$UNAME_OS'" >&2; exit 1;;
|
||||
esac
|
||||
|
||||
UNAME_ARCH=$(uname -m)
|
||||
case "$UNAME_ARCH" in
|
||||
x86_64|amd64) ARCH=x86_64 ;;
|
||||
aarch64|arm64) ARCH=aarch64 ;;
|
||||
*) echo "Error: unsupported arch '$UNAME_ARCH'" >&2; exit 1;;
|
||||
esac
|
||||
|
||||
log "Target: ${OS}-${ARCH}"
|
||||
|
||||
API_BASE="https://api.github.com/repos/${REPO}/releases"
|
||||
if [[ -z "${VERSION}" ]]; then
|
||||
RELEASE_URL="${API_BASE}/latest"
|
||||
else
|
||||
RELEASE_URL="${API_BASE}/tags/${VERSION}"
|
||||
fi
|
||||
|
||||
http_get() {
|
||||
if [[ "$DL" == "curl" ]]; then
|
||||
curl -fsSL -H 'User-Agent: coyote-installer' "$1"
|
||||
@@ -98,114 +42,240 @@ http_get() {
|
||||
fi
|
||||
}
|
||||
|
||||
TMPDIR="$(mktemp -d)"
|
||||
trap 'rm -rf "$TMPDIR"' EXIT
|
||||
|
||||
log "Fetching release metadata from $RELEASE_URL"
|
||||
JSON="$TMPDIR/release.json"
|
||||
if ! http_get "$RELEASE_URL" > "$JSON"; then
|
||||
echo "Error: failed to fetch release metadata. Check version tag." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
ASSET_CANDIDATES=()
|
||||
if [[ "$OS" == "darwin" ]]; then
|
||||
if [[ "$ARCH" == "x86_64" ]]; then
|
||||
ASSET_CANDIDATES+=("coyote-x86_64-apple-darwin.tar.gz")
|
||||
else
|
||||
ASSET_CANDIDATES+=("coyote-aarch64-apple-darwin.tar.gz")
|
||||
smoke_test() {
|
||||
# The scratch dir may live on a noexec mount; if running in place fails,
|
||||
# retry from a probe file in the install directory before rejecting.
|
||||
local bin="$1"
|
||||
if "$bin" --version >/dev/null 2>&1; then return 0; fi
|
||||
local probe="${BIN_DIR}/.coyote-install-probe.$$"
|
||||
local ok=1
|
||||
if cp "$bin" "$probe" 2>/dev/null && chmod +x "$probe" 2>/dev/null; then
|
||||
if "$probe" --version >/dev/null 2>&1; then ok=0; fi
|
||||
fi
|
||||
elif [[ "$OS" == "linux" ]]; then
|
||||
if [[ "$ARCH" == "x86_64" ]]; then
|
||||
rm -f "$probe"
|
||||
return "$ok"
|
||||
}
|
||||
|
||||
main() {
|
||||
VERSION="${COYOTE_VERSION:-}"
|
||||
BIN_DIR="${BIN_DIR:-}"
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--version) VERSION="$2"; shift 2;;
|
||||
--bin-dir) BIN_DIR="$2"; shift 2;;
|
||||
-h|--help) usage; exit 0;;
|
||||
*) echo "Unknown argument: $1" >&2; usage; exit 2;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [[ -n "$VERSION" && "$VERSION" =~ ^[0-9] ]]; then VERSION="v${VERSION}"; fi
|
||||
|
||||
if [[ -z "${BIN_DIR}" ]]; then
|
||||
if [[ -w "/usr/local/bin" ]]; then
|
||||
BIN_DIR="/usr/local/bin"
|
||||
else
|
||||
BIN_DIR="${HOME}/.local/bin"
|
||||
fi
|
||||
fi
|
||||
mkdir -p "${BIN_DIR}"
|
||||
|
||||
need_cmd uname
|
||||
need_cmd mktemp
|
||||
need_cmd tar
|
||||
|
||||
if command -v curl >/dev/null 2>&1; then
|
||||
DL=curl
|
||||
elif command -v wget >/dev/null 2>&1; then
|
||||
DL=wget
|
||||
else
|
||||
echo "Error: need curl or wget" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
UNAME_OS=$(uname -s | tr '[:upper:]' '[:lower:]')
|
||||
case "$UNAME_OS" in
|
||||
linux) OS=linux ;;
|
||||
darwin) OS=darwin ;;
|
||||
*) echo "Error: unsupported OS '$UNAME_OS'" >&2; exit 1;;
|
||||
esac
|
||||
|
||||
UNAME_ARCH=$(uname -m)
|
||||
case "$UNAME_ARCH" in
|
||||
x86_64|amd64) ARCH=x86_64 ;;
|
||||
aarch64|arm64) ARCH=aarch64 ;;
|
||||
*) echo "Error: unsupported arch '$UNAME_ARCH'" >&2; exit 1;;
|
||||
esac
|
||||
|
||||
log "Target: ${OS}-${ARCH}"
|
||||
|
||||
API_BASE="https://api.github.com/repos/${REPO}/releases"
|
||||
if [[ -z "${VERSION}" ]]; then
|
||||
RELEASE_URL="${API_BASE}/latest"
|
||||
else
|
||||
RELEASE_URL="${API_BASE}/tags/${VERSION}"
|
||||
fi
|
||||
|
||||
WORKDIR="$(mktemp -d)"
|
||||
trap 'rm -rf "$WORKDIR"; rm -f "${BIN_DIR}/.coyote-install-probe.$$"' EXIT
|
||||
|
||||
log "Fetching release metadata from $RELEASE_URL"
|
||||
JSON="$WORKDIR/release.json"
|
||||
if ! http_get "$RELEASE_URL" > "$JSON"; then
|
||||
echo "Error: failed to fetch release metadata. Check version tag." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
ASSET_CANDIDATES=()
|
||||
if [[ "$OS" == "darwin" ]]; then
|
||||
if [[ "$ARCH" == "x86_64" ]]; then
|
||||
ASSET_CANDIDATES+=("coyote-x86_64-apple-darwin.tar.gz")
|
||||
else
|
||||
ASSET_CANDIDATES+=("coyote-aarch64-apple-darwin.tar.gz")
|
||||
fi
|
||||
elif [[ "$OS" == "linux" ]]; then
|
||||
LIBC="musl"
|
||||
if command -v getconf >/dev/null 2>&1 && getconf GNU_LIBC_VERSION >/dev/null 2>&1; then LIBC="gnu"; fi
|
||||
if ldd --version 2>&1 | grep -qi glibc; then LIBC="gnu"; fi
|
||||
|
||||
if [[ "$LIBC" == "gnu" ]]; then
|
||||
ASSET_CANDIDATES+=("coyote-x86_64-unknown-linux-gnu.tar.gz")
|
||||
# The gnu binary dynamically links OpenSSL 3. On Debian/Ubuntu, ldconfig lives
|
||||
# in /usr/sbin, which is often missing from non-root PATHs, so try its known
|
||||
# locations and fall back to probing the usual library directories directly.
|
||||
LIBSSL3=""
|
||||
for LDCONFIG in ldconfig /sbin/ldconfig /usr/sbin/ldconfig; do
|
||||
if command -v "$LDCONFIG" >/dev/null 2>&1; then
|
||||
if "$LDCONFIG" -p 2>/dev/null | grep -q 'libssl\.so\.3'; then LIBSSL3="yes"; fi
|
||||
break
|
||||
fi
|
||||
done
|
||||
if [[ -z "$LIBSSL3" ]]; then
|
||||
for LIBSSL_CANDIDATE in /usr/lib/*/libssl.so.3 /lib/*/libssl.so.3 /usr/lib64/libssl.so.3 /usr/lib/libssl.so.3 /usr/local/lib/libssl.so.3 /usr/local/lib/*/libssl.so.3; do
|
||||
if [[ -e "$LIBSSL_CANDIDATE" ]]; then LIBSSL3="yes"; break; fi
|
||||
done
|
||||
fi
|
||||
if [[ -n "$LIBSSL3" ]]; then
|
||||
ASSET_CANDIDATES+=("coyote-${ARCH}-unknown-linux-gnu.tar.gz")
|
||||
else
|
||||
log "glibc detected but OpenSSL 3 (libssl.so.3) not found; using musl build"
|
||||
fi
|
||||
fi
|
||||
|
||||
ASSET_CANDIDATES+=("coyote-x86_64-unknown-linux-musl.tar.gz")
|
||||
ASSET_CANDIDATES+=("coyote-${ARCH}-unknown-linux-musl.tar.gz")
|
||||
else
|
||||
ASSET_CANDIDATES+=("coyote-aarch64-unknown-linux-musl.tar.gz")
|
||||
echo "Error: unsupported OS for this installer: $OS" >&2; exit 1
|
||||
fi
|
||||
else
|
||||
echo "Error: unsupported OS for this installer: $OS" >&2; exit 1
|
||||
fi
|
||||
|
||||
DL_URLS=$(grep -oE '"browser_download_url":[[:space:]]*"[^"]+"' "$JSON" \
|
||||
| sed -E 's/.*"browser_download_url":[[:space:]]*"//; s/"$//' \
|
||||
|| true)
|
||||
DL_URLS=$(grep -oE '"browser_download_url":[[:space:]]*"[^"]+"' "$JSON" \
|
||||
| sed -E 's/.*"browser_download_url":[[:space:]]*"//; s/"$//' \
|
||||
|| true)
|
||||
|
||||
ASSET_NAME=""; ASSET_URL=""
|
||||
for candidate in "${ASSET_CANDIDATES[@]}"; do
|
||||
while IFS= read -r url; do
|
||||
[[ -z "$url" ]] && continue
|
||||
if [[ "$url" == */"$candidate" ]]; then
|
||||
ASSET_NAME="$candidate"
|
||||
ASSET_URL="$url"
|
||||
break
|
||||
INSTALLED=""
|
||||
TRIED=()
|
||||
ATTEMPT=0
|
||||
for candidate in "${ASSET_CANDIDATES[@]}"; do
|
||||
ASSET_URL=""
|
||||
while IFS= read -r url; do
|
||||
[[ -z "$url" ]] && continue
|
||||
if [[ "$url" == */"$candidate" ]]; then
|
||||
ASSET_URL="$url"
|
||||
break
|
||||
fi
|
||||
done <<< "$DL_URLS"
|
||||
|
||||
if [[ -z "$ASSET_URL" ]]; then
|
||||
TRIED+=("$candidate: no matching release asset")
|
||||
continue
|
||||
fi
|
||||
done <<< "$DL_URLS"
|
||||
[[ -n "$ASSET_URL" ]] && break
|
||||
done
|
||||
|
||||
if [[ -z "$ASSET_URL" ]]; then
|
||||
echo "Error: no matching asset found for ${OS}-${ARCH}. Tried:" >&2
|
||||
for c in "${ASSET_CANDIDATES[@]}"; do echo " - $c" >&2; done
|
||||
exit 1
|
||||
fi
|
||||
ATTEMPT=$((ATTEMPT + 1))
|
||||
WORK="$WORKDIR/attempt-$ATTEMPT"
|
||||
mkdir -p "$WORK"
|
||||
|
||||
log "Selected asset: $ASSET_NAME"
|
||||
log "Download URL: $ASSET_URL"
|
||||
log "Selected asset: $candidate"
|
||||
log "Download URL: $ASSET_URL"
|
||||
|
||||
ARCHIVE="$TMPDIR/asset"
|
||||
if [[ "$DL" == "curl" ]]; then
|
||||
curl -fL -H 'User-Agent: coyote-installer' "$ASSET_URL" -o "$ARCHIVE"
|
||||
else
|
||||
wget -q --header='User-Agent: coyote-installer' "$ASSET_URL" -O "$ARCHIVE"
|
||||
fi
|
||||
ARCHIVE="$WORK/asset"
|
||||
if [[ "$DL" == "curl" ]]; then
|
||||
if ! curl -fL -H 'User-Agent: coyote-installer' "$ASSET_URL" -o "$ARCHIVE"; then
|
||||
log "Failed to download $candidate; trying next candidate"
|
||||
TRIED+=("$candidate: download failed")
|
||||
continue
|
||||
fi
|
||||
else
|
||||
if ! wget -q --header='User-Agent: coyote-installer' "$ASSET_URL" -O "$ARCHIVE"; then
|
||||
log "Failed to download $candidate; trying next candidate"
|
||||
TRIED+=("$candidate: download failed")
|
||||
continue
|
||||
fi
|
||||
fi
|
||||
|
||||
WORK="$TMPDIR/work"; mkdir -p "$WORK"
|
||||
EXTRACTED_DIR="$WORK/extracted"; mkdir -p "$EXTRACTED_DIR"
|
||||
EXTRACTED_DIR="$WORK/extracted"; mkdir -p "$EXTRACTED_DIR"
|
||||
|
||||
if tar -tf "$ARCHIVE" >/dev/null 2>&1; then
|
||||
tar -xzf "$ARCHIVE" -C "$EXTRACTED_DIR"
|
||||
else
|
||||
if command -v unzip >/dev/null 2>&1; then
|
||||
unzip -q "$ARCHIVE" -d "$EXTRACTED_DIR"
|
||||
else
|
||||
echo "Error: unknown archive format; install 'unzip'" >&2
|
||||
exit 1
|
||||
if tar -tf "$ARCHIVE" >/dev/null 2>&1; then
|
||||
if ! tar -xzf "$ARCHIVE" -C "$EXTRACTED_DIR"; then
|
||||
log "Failed to extract $candidate; trying next candidate"
|
||||
TRIED+=("$candidate: extract failed")
|
||||
continue
|
||||
fi
|
||||
else
|
||||
if command -v unzip >/dev/null 2>&1; then
|
||||
if ! unzip -q "$ARCHIVE" -d "$EXTRACTED_DIR"; then
|
||||
log "Failed to extract $candidate; trying next candidate"
|
||||
TRIED+=("$candidate: extract failed")
|
||||
continue
|
||||
fi
|
||||
else
|
||||
log "Unknown archive format for $candidate and 'unzip' is not available; trying next candidate"
|
||||
TRIED+=("$candidate: unknown archive format and 'unzip' unavailable")
|
||||
continue
|
||||
fi
|
||||
fi
|
||||
|
||||
BIN_PATH=""
|
||||
while IFS= read -r -d '' f; do
|
||||
base=$(basename "$f")
|
||||
if [[ "$base" == "coyote" ]]; then
|
||||
BIN_PATH="$f"
|
||||
break
|
||||
fi
|
||||
done < <(find "$EXTRACTED_DIR" -type f -print0)
|
||||
|
||||
if [[ -z "$BIN_PATH" ]]; then
|
||||
log "Could not find 'coyote' binary in $candidate; trying next candidate"
|
||||
TRIED+=("$candidate: no 'coyote' binary in archive")
|
||||
continue
|
||||
fi
|
||||
|
||||
chmod +x "$BIN_PATH"
|
||||
if ! smoke_test "$BIN_PATH"; then
|
||||
log "Downloaded $candidate but it failed to run on this system; trying next candidate"
|
||||
TRIED+=("$candidate: binary failed to run on this system")
|
||||
continue
|
||||
fi
|
||||
|
||||
install -m 0755 "$BIN_PATH" "${BIN_DIR}/coyote"
|
||||
INSTALLED="$candidate"
|
||||
break
|
||||
done
|
||||
|
||||
if [[ -z "$INSTALLED" ]]; then
|
||||
echo "Error: no usable asset found for ${OS}-${ARCH}. Tried:" >&2
|
||||
for t in "${TRIED[@]}"; do echo " - $t" >&2; done
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
BIN_PATH=""
|
||||
while IFS= read -r -d '' f; do
|
||||
base=$(basename "$f")
|
||||
if [[ "$base" == "coyote" ]]; then
|
||||
BIN_PATH="$f"
|
||||
break
|
||||
fi
|
||||
done < <(find "$EXTRACTED_DIR" -type f -print0)
|
||||
log "Installed: ${BIN_DIR}/coyote"
|
||||
|
||||
if [[ -z "$BIN_PATH" ]]; then
|
||||
echo "Error: could not find 'coyote' binary in the archive" >&2
|
||||
exit 1
|
||||
fi
|
||||
case ":$PATH:" in
|
||||
*":${BIN_DIR}:"*) ;;
|
||||
*)
|
||||
log "Note: ${BIN_DIR} is not in PATH. Add it, e.g.:"
|
||||
log " export PATH=\"${BIN_DIR}:\$PATH\""
|
||||
;;
|
||||
esac
|
||||
|
||||
chmod +x "$BIN_PATH"
|
||||
install -m 0755 "$BIN_PATH" "${BIN_DIR}/coyote"
|
||||
|
||||
log "Installed: ${BIN_DIR}/coyote"
|
||||
|
||||
case ":$PATH:" in
|
||||
*":${BIN_DIR}:"*) ;;
|
||||
*)
|
||||
log "Note: ${BIN_DIR} is not in PATH. Add it, e.g.:"
|
||||
log " export PATH=\"${BIN_DIR}:\$PATH\""
|
||||
;;
|
||||
esac
|
||||
|
||||
log "Done. Try: coyote --help"
|
||||
log "Done. Try: coyote --help"
|
||||
}
|
||||
|
||||
main "$@"
|
||||
|
||||
@@ -590,12 +590,33 @@ mod tests {
|
||||
parse(&["--install-builtins", "agents"]).install_builtins,
|
||||
Some(AssetCategory::Agents)
|
||||
);
|
||||
assert_eq!(
|
||||
parse(&["--install-builtins", "mcp-config"]).install_builtins,
|
||||
Some(AssetCategory::McpConfig)
|
||||
);
|
||||
assert_eq!(
|
||||
parse(&["--install-builtins", "mcp_config"]).install_builtins,
|
||||
Some(AssetCategory::McpConfig)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_config_canonical_value_is_kebab_case() {
|
||||
use clap::ValueEnum;
|
||||
|
||||
let category = AssetCategory::McpConfig.to_possible_value().unwrap();
|
||||
assert_eq!(category.get_name(), "mcp-config");
|
||||
assert!(category.get_name_and_aliases().any(|n| n == "mcp_config"));
|
||||
assert!(AssetCategory::NAMES.contains(&"mcp-config"));
|
||||
assert!(!AssetCategory::NAMES.contains(&"mcp_config"));
|
||||
|
||||
let filter = InstallFilter::McpConfig.to_possible_value().unwrap();
|
||||
assert_eq!(filter.get_name(), "mcp-config");
|
||||
assert!(filter.get_name_and_aliases().any(|n| n == "mcp_config"));
|
||||
assert!(InstallFilter::NAMES.contains(&"mcp-config"));
|
||||
assert!(!InstallFilter::NAMES.contains(&"mcp_config"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_install_builtins_conflicts_with_install() {
|
||||
assert!(
|
||||
@@ -633,6 +654,26 @@ mod tests {
|
||||
parse(&["--install", "https://github.com/x/y", "--filter", "agents"]).filter,
|
||||
Some(InstallFilter::Agents)
|
||||
);
|
||||
assert_eq!(
|
||||
parse(&[
|
||||
"--install",
|
||||
"https://github.com/x/y",
|
||||
"--filter",
|
||||
"mcp-config"
|
||||
])
|
||||
.filter,
|
||||
Some(InstallFilter::McpConfig)
|
||||
);
|
||||
assert_eq!(
|
||||
parse(&[
|
||||
"--install",
|
||||
"https://github.com/x/y",
|
||||
"--filter",
|
||||
"mcp_config"
|
||||
])
|
||||
.filter,
|
||||
Some(InstallFilter::McpConfig)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -682,6 +682,10 @@ impl RoleLike for Agent {
|
||||
Some(self.config.mcp_servers.clone())
|
||||
}
|
||||
|
||||
fn mcp_tools(&self) -> Option<IndexMap<String, Vec<String>>> {
|
||||
self.config.mcp_tools.clone()
|
||||
}
|
||||
|
||||
fn set_model(&mut self, model: Model) {
|
||||
self.config.model_id = Some(model.id());
|
||||
self.model = model;
|
||||
@@ -723,6 +727,10 @@ impl RoleLike for Agent {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn set_mcp_tools(&mut self, value: Option<IndexMap<String, Vec<String>>>) {
|
||||
self.config.mcp_tools = value;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||
@@ -774,6 +782,8 @@ pub struct AgentConfig {
|
||||
pub version: String,
|
||||
#[serde(default)]
|
||||
pub mcp_servers: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub mcp_tools: Option<IndexMap<String, Vec<String>>>,
|
||||
#[serde(default)]
|
||||
pub global_tools: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -846,6 +856,7 @@ impl AgentConfig {
|
||||
description: graph.description.clone(),
|
||||
global_tools: graph.global_tools.clone(),
|
||||
mcp_servers: graph.mcp_servers.clone(),
|
||||
mcp_tools: graph.mcp_tools.clone(),
|
||||
skills_enabled: graph.skills_enabled,
|
||||
enabled_skills: graph.enabled_skills.clone(),
|
||||
inject_skill_instructions: graph.inject_skill_instructions.unwrap_or(true),
|
||||
@@ -1285,6 +1296,33 @@ variables:
|
||||
assert_eq!(config.enabled_macros, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_config_parses_mcp_tools() {
|
||||
let yaml =
|
||||
"name: minimal\ninstructions: hi\nmcp_tools:\n github:\n - get_*\n - list_*\n";
|
||||
let config: AgentConfig = serde_yaml::from_str(yaml).unwrap();
|
||||
|
||||
let mcp_tools = config.mcp_tools.unwrap();
|
||||
assert_eq!(
|
||||
mcp_tools.get("github"),
|
||||
Some(&vec!["get_*".to_string(), "list_*".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_mcp_tools_role_like_round_trip() {
|
||||
let config: AgentConfig =
|
||||
serde_yaml::from_str("name: minimal\ninstructions: hi\n").unwrap();
|
||||
let mut agent = Agent::test_new(config);
|
||||
assert_eq!(agent.mcp_tools(), None);
|
||||
|
||||
let mut mcp_tools = IndexMap::new();
|
||||
mcp_tools.insert("github".to_string(), vec!["get_*".to_string()]);
|
||||
agent.set_mcp_tools(Some(mcp_tools.clone()));
|
||||
|
||||
assert_eq!(agent.mcp_tools(), Some(mcp_tools));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_config_enabled_macros_empty_list_is_some_empty() {
|
||||
let yaml = "name: minimal\ninstructions: hi\nenabled_macros: []\n";
|
||||
|
||||
@@ -50,6 +50,7 @@ pub struct AppConfig {
|
||||
pub mapping_mcp_servers: IndexMap<String, String>,
|
||||
#[serde(default, deserialize_with = "super::deserialize_csv_or_vec")]
|
||||
pub enabled_mcp_servers: Option<Vec<String>>,
|
||||
pub mcp_tools: Option<IndexMap<String, Vec<String>>>,
|
||||
|
||||
pub auto_continue: bool,
|
||||
pub max_auto_continues: usize,
|
||||
@@ -136,6 +137,7 @@ impl Default for AppConfig {
|
||||
mcp_server_support: true,
|
||||
mapping_mcp_servers: Default::default(),
|
||||
enabled_mcp_servers: None,
|
||||
mcp_tools: None,
|
||||
|
||||
auto_continue: false,
|
||||
max_auto_continues: 10,
|
||||
@@ -223,6 +225,7 @@ impl AppConfig {
|
||||
mcp_server_support: config.mcp_server_support,
|
||||
mapping_mcp_servers: config.mapping_mcp_servers,
|
||||
enabled_mcp_servers: config.enabled_mcp_servers,
|
||||
mcp_tools: config.mcp_tools,
|
||||
|
||||
auto_continue: config.auto_continue,
|
||||
max_auto_continues: config.max_auto_continues,
|
||||
@@ -786,6 +789,22 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_config_copies_mcp_tools() {
|
||||
let mut mcp_tools = IndexMap::new();
|
||||
mcp_tools.insert("github".to_string(), vec!["get_*".to_string()]);
|
||||
let cfg = Config {
|
||||
model_id: "test-model".to_string(),
|
||||
clients: vec![ClientConfig::default()],
|
||||
mcp_tools: Some(mcp_tools.clone()),
|
||||
..Config::default()
|
||||
};
|
||||
|
||||
let app = AppConfig::from_config(cfg).unwrap();
|
||||
|
||||
assert_eq!(app.mcp_tools, Some(mcp_tools));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial_test::serial]
|
||||
fn from_config_copies_enabled_macros() {
|
||||
|
||||
@@ -69,7 +69,7 @@ impl AppState {
|
||||
}
|
||||
}
|
||||
|
||||
let mut functions = Functions::init(config.visible_tools.as_ref().unwrap_or(&Vec::new()))?;
|
||||
let mut functions = Functions::init(config.visible_tools.as_deref())?;
|
||||
if !mcp_registry.is_empty() && config.mcp_server_support {
|
||||
functions.append_mcp_meta_functions(mcp_registry.server_features());
|
||||
}
|
||||
|
||||
@@ -4158,6 +4158,10 @@ mod tests {
|
||||
classify_install_target("agents", &owned_names(&["agents"])),
|
||||
InstallTarget::Category(AssetCategory::Agents)
|
||||
);
|
||||
assert_eq!(
|
||||
classify_install_target("mcp-config", &[]),
|
||||
InstallTarget::Category(AssetCategory::McpConfig)
|
||||
);
|
||||
assert_eq!(
|
||||
classify_install_target("mcp_config", &[]),
|
||||
InstallTarget::Category(AssetCategory::McpConfig)
|
||||
@@ -4790,6 +4794,49 @@ mod tests {
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uninstall_mcp_preserves_allowed_tools_on_surviving_entries() {
|
||||
let dir = fresh_temp_dir("uninst-mcp-allowed-tools-");
|
||||
let mut store = BundleStore::load_from(dir.join("installed-bundles.yaml")).unwrap();
|
||||
store
|
||||
.upsert_bundle("omc", test_metadata("https://github.com/x/omc"))
|
||||
.unwrap();
|
||||
let mcp = dir.join("mcp.json");
|
||||
write_mcp(
|
||||
&mcp,
|
||||
r#"{"mcpServers": {
|
||||
"srv": {"type": "stdio", "command": "echo"},
|
||||
"user-srv": {"type": "stdio", "command": "mine", "allowedTools": ["get_*", "list_issues"]}
|
||||
}}"#,
|
||||
);
|
||||
let parsed: McpServersConfig =
|
||||
serde_json::from_str(&fs::read_to_string(&mcp).unwrap()).unwrap();
|
||||
let hash = hash_bytes(
|
||||
serde_json::to_string(parsed.mcp_servers.get("srv").unwrap())
|
||||
.unwrap()
|
||||
.as_bytes(),
|
||||
);
|
||||
store
|
||||
.record_mcp_servers(
|
||||
"omc",
|
||||
vec![mcp_server_record("srv", McpAction::Added, Some(hash))],
|
||||
)
|
||||
.unwrap();
|
||||
let servers = store.get("omc").unwrap().mcp_servers.clone();
|
||||
|
||||
let summary = uninstall_mcp_entries(&mut store, "omc", &servers, &mcp, true).unwrap();
|
||||
|
||||
assert_eq!(summary.removed, vec!["srv"]);
|
||||
let raw = fs::read_to_string(&mcp).unwrap();
|
||||
assert!(raw.contains("allowedTools"));
|
||||
let written: McpServersConfig = serde_json::from_str(&raw).unwrap();
|
||||
assert_eq!(
|
||||
written.mcp_servers.get("user-srv").unwrap().allowed_tools,
|
||||
Some(vec!["get_*".to_string(), "list_issues".to_string()])
|
||||
);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uninstall_mcp_reports_referenced_secrets_without_removing_them() {
|
||||
let dir = fresh_temp_dir("uninst-mcp-secrets-");
|
||||
|
||||
@@ -139,6 +139,7 @@ mod tests {
|
||||
url: None,
|
||||
headers: None,
|
||||
oauth: None,
|
||||
allowed_tools: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,6 +157,7 @@ mod tests {
|
||||
url: Some(url.to_string()),
|
||||
headers,
|
||||
oauth: None,
|
||||
allowed_tools: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,859 @@
|
||||
use crate::mcp::McpServersConfig;
|
||||
|
||||
use fancy_regex::Regex;
|
||||
use indexmap::IndexMap;
|
||||
use log::warn;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
|
||||
/// The configuration level that contributed a layer of tool patterns for an
|
||||
/// MCP server, as rendered in diagnostics.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum LayerSource {
|
||||
Global,
|
||||
AppConfig,
|
||||
Role(String),
|
||||
Agent(String),
|
||||
Session,
|
||||
Skill(String),
|
||||
Node(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for LayerSource {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
LayerSource::Global => write!(f, "global (mcp.json)"),
|
||||
LayerSource::AppConfig => write!(f, "config (config.yaml)"),
|
||||
LayerSource::Role(name) => write!(f, "role ({name})"),
|
||||
LayerSource::Agent(name) => write!(f, "agent ({name})"),
|
||||
LayerSource::Session => write!(f, "session (.set)"),
|
||||
LayerSource::Skill(name) => write!(f, "skill ({name})"),
|
||||
LayerSource::Node(id) => write!(f, "node ({id})"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LayerSource {
|
||||
pub fn short_label(&self) -> &'static str {
|
||||
match self {
|
||||
LayerSource::Global => "global",
|
||||
LayerSource::AppConfig => "config",
|
||||
LayerSource::Role(_) => "role",
|
||||
LayerSource::Agent(_) => "agent",
|
||||
LayerSource::Session => "session",
|
||||
LayerSource::Skill(_) => "skill",
|
||||
LayerSource::Node(_) => "node",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CompiledPatterns {
|
||||
source: LayerSource,
|
||||
raw: Vec<String>,
|
||||
regexes: Vec<Regex>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ToolFilter {
|
||||
layers: Vec<CompiledPatterns>,
|
||||
}
|
||||
|
||||
impl ToolFilter {
|
||||
pub fn push_layer(&mut self, source: LayerSource, patterns: &[String]) {
|
||||
self.layers.push(CompiledPatterns {
|
||||
source,
|
||||
raw: patterns.to_vec(),
|
||||
regexes: patterns.iter().map(|p| compile_glob(p)).collect(),
|
||||
});
|
||||
}
|
||||
|
||||
pub fn layers(&self) -> impl Iterator<Item = (&LayerSource, &[String])> {
|
||||
self.layers
|
||||
.iter()
|
||||
.map(|layer| (&layer.source, layer.raw.as_slice()))
|
||||
}
|
||||
|
||||
pub fn allows(&self, tool: &str) -> bool {
|
||||
self.layers.iter().all(|layer| {
|
||||
layer
|
||||
.regexes
|
||||
.iter()
|
||||
.any(|regex| regex.is_match(tool).unwrap_or(false))
|
||||
})
|
||||
}
|
||||
|
||||
/// The first matching raw pattern per layer, in layer order, or the
|
||||
/// source of the first layer with no match.
|
||||
pub fn allows_explain(&self, tool: &str) -> Result<Vec<(&LayerSource, &str)>, &LayerSource> {
|
||||
let mut matched = Vec::with_capacity(self.layers.len());
|
||||
for layer in &self.layers {
|
||||
// fancy_regex can fail at match time (backtracking limits);
|
||||
// treat that as a non-match rather than allowing the tool.
|
||||
match layer
|
||||
.regexes
|
||||
.iter()
|
||||
.position(|regex| regex.is_match(tool).unwrap_or(false))
|
||||
{
|
||||
Some(index) => matched.push((&layer.source, layer.raw[index].as_str())),
|
||||
None => return Err(&layer.source),
|
||||
}
|
||||
}
|
||||
Ok(matched)
|
||||
}
|
||||
|
||||
pub fn dead_context_patterns(&self, advertised: &[String]) -> Vec<(&LayerSource, &str)> {
|
||||
let surviving: Vec<&String> = advertised
|
||||
.iter()
|
||||
.filter(|name| {
|
||||
self.layers
|
||||
.iter()
|
||||
.filter(|layer| layer.source == LayerSource::Global)
|
||||
.all(|layer| {
|
||||
layer
|
||||
.regexes
|
||||
.iter()
|
||||
.any(|regex| regex.is_match(name).unwrap_or(false))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut dead = Vec::new();
|
||||
for layer in self
|
||||
.layers
|
||||
.iter()
|
||||
.filter(|l| l.source != LayerSource::Global)
|
||||
{
|
||||
for (raw, regex) in layer.raw.iter().zip(&layer.regexes) {
|
||||
if !surviving
|
||||
.iter()
|
||||
.any(|name| regex.is_match(name).unwrap_or(false))
|
||||
{
|
||||
dead.push((&layer.source, raw.as_str()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dead
|
||||
}
|
||||
}
|
||||
|
||||
/// Translates a glob pattern (`*` = any run of characters, `?` = exactly one)
|
||||
/// into an anchored regex. Patterns that fail to compile match nothing.
|
||||
fn compile_glob(pattern: &str) -> Regex {
|
||||
let translated = format!(
|
||||
"^{}$",
|
||||
fancy_regex::escape(pattern)
|
||||
.replace("\\*", ".*")
|
||||
.replace("\\?", ".")
|
||||
);
|
||||
Regex::new(&translated).unwrap_or_else(|error| {
|
||||
warn!("Invalid MCP tool pattern '{pattern}': {error}. It will match nothing.");
|
||||
never_matching_regex()
|
||||
})
|
||||
}
|
||||
|
||||
fn never_matching_regex() -> Regex {
|
||||
Regex::new("(?!)").expect("'(?!)' is a valid never-matching regex")
|
||||
}
|
||||
|
||||
pub struct SkillMcpLayer {
|
||||
pub name: String,
|
||||
pub enabled_servers: Vec<String>,
|
||||
pub mcp_tools: IndexMap<String, Vec<String>>,
|
||||
}
|
||||
|
||||
pub struct McpToolPolicy;
|
||||
|
||||
impl McpToolPolicy {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn effective(
|
||||
mcp_config: &McpServersConfig,
|
||||
session: Option<&IndexMap<String, Vec<String>>>,
|
||||
agent: Option<(&str, &IndexMap<String, Vec<String>>)>,
|
||||
role: Option<(&str, &IndexMap<String, Vec<String>>)>,
|
||||
global: Option<&IndexMap<String, Vec<String>>>,
|
||||
skills: &[SkillMcpLayer],
|
||||
node: Option<(&str, &IndexMap<String, Vec<String>>)>,
|
||||
aliases: &IndexMap<String, String>,
|
||||
) -> HashMap<String, ToolFilter> {
|
||||
let mut filters: HashMap<String, ToolFilter> = HashMap::new();
|
||||
|
||||
for (server, spec) in &mcp_config.mcp_servers {
|
||||
if let Some(patterns) = &spec.allowed_tools {
|
||||
filters
|
||||
.entry(server.clone())
|
||||
.or_default()
|
||||
.push_layer(LayerSource::Global, patterns);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(map) = global {
|
||||
push_level(
|
||||
&mut filters,
|
||||
mcp_config,
|
||||
aliases,
|
||||
&LayerSource::AppConfig,
|
||||
map,
|
||||
None,
|
||||
);
|
||||
}
|
||||
if let Some((name, map)) = role {
|
||||
push_level(
|
||||
&mut filters,
|
||||
mcp_config,
|
||||
aliases,
|
||||
&LayerSource::Role(name.to_string()),
|
||||
map,
|
||||
None,
|
||||
);
|
||||
}
|
||||
if let Some((name, map)) = agent {
|
||||
push_level(
|
||||
&mut filters,
|
||||
mcp_config,
|
||||
aliases,
|
||||
&LayerSource::Agent(name.to_string()),
|
||||
map,
|
||||
None,
|
||||
);
|
||||
}
|
||||
if let Some(map) = session {
|
||||
push_level(
|
||||
&mut filters,
|
||||
mcp_config,
|
||||
aliases,
|
||||
&LayerSource::Session,
|
||||
map,
|
||||
None,
|
||||
);
|
||||
}
|
||||
for skill in skills {
|
||||
push_level(
|
||||
&mut filters,
|
||||
mcp_config,
|
||||
aliases,
|
||||
&LayerSource::Skill(skill.name.clone()),
|
||||
&skill.mcp_tools,
|
||||
Some(&skill.enabled_servers),
|
||||
);
|
||||
}
|
||||
if let Some((id, map)) = node {
|
||||
push_level(
|
||||
&mut filters,
|
||||
mcp_config,
|
||||
aliases,
|
||||
&LayerSource::Node(id.to_string()),
|
||||
map,
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
filters
|
||||
}
|
||||
}
|
||||
|
||||
fn push_level(
|
||||
filters: &mut HashMap<String, ToolFilter>,
|
||||
mcp_config: &McpServersConfig,
|
||||
aliases: &IndexMap<String, String>,
|
||||
source: &LayerSource,
|
||||
map: &IndexMap<String, Vec<String>>,
|
||||
enabled_servers: Option<&[String]>,
|
||||
) {
|
||||
for (server, patterns) in expand_server_keys(mcp_config, aliases, map) {
|
||||
if let Some(enabled) = enabled_servers
|
||||
&& !enabled.iter().any(|id| id == &server)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
filters
|
||||
.entry(server)
|
||||
.or_default()
|
||||
.push_layer(source.clone(), &patterns);
|
||||
}
|
||||
}
|
||||
|
||||
fn expand_server_keys(
|
||||
mcp_config: &McpServersConfig,
|
||||
aliases: &IndexMap<String, String>,
|
||||
map: &IndexMap<String, Vec<String>>,
|
||||
) -> IndexMap<String, Vec<String>> {
|
||||
let mut expanded: IndexMap<String, Vec<String>> = IndexMap::new();
|
||||
for (key, patterns) in map {
|
||||
let key = key.trim();
|
||||
if mcp_config.mcp_servers.contains_key(key) {
|
||||
expanded
|
||||
.entry(key.to_string())
|
||||
.or_default()
|
||||
.extend(patterns.iter().cloned());
|
||||
} else {
|
||||
for mapped_id in expand_mcp_server_alias(aliases, key) {
|
||||
if mcp_config.mcp_servers.contains_key(&mapped_id) {
|
||||
expanded
|
||||
.entry(mapped_id)
|
||||
.or_default()
|
||||
.extend(patterns.iter().cloned());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expanded
|
||||
}
|
||||
|
||||
pub(crate) fn expand_mcp_server_alias(
|
||||
aliases: &IndexMap<String, String>,
|
||||
key: &str,
|
||||
) -> Vec<String> {
|
||||
aliases
|
||||
.get(key)
|
||||
.map(|mapped| {
|
||||
mapped
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|id| !id.is_empty())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::mcp::{McpServer, McpServersConfig, McpTransportType};
|
||||
|
||||
fn spec(allowed_tools: Option<&[&str]>) -> McpServer {
|
||||
McpServer {
|
||||
transport_type: McpTransportType::Stdio,
|
||||
command: Some("echo".to_string()),
|
||||
args: None,
|
||||
env: None,
|
||||
cwd: None,
|
||||
url: None,
|
||||
headers: None,
|
||||
oauth: None,
|
||||
allowed_tools: allowed_tools.map(list),
|
||||
}
|
||||
}
|
||||
|
||||
fn config(servers: &[(&str, Option<&[&str]>)]) -> McpServersConfig {
|
||||
McpServersConfig {
|
||||
mcp_servers: servers
|
||||
.iter()
|
||||
.map(|(name, tools)| (name.to_string(), spec(*tools)))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn list(items: &[&str]) -> Vec<String> {
|
||||
items.iter().map(|s| s.to_string()).collect()
|
||||
}
|
||||
|
||||
fn tool_map(entries: &[(&str, &[&str])]) -> IndexMap<String, Vec<String>> {
|
||||
entries
|
||||
.iter()
|
||||
.map(|(server, patterns)| (server.to_string(), list(patterns)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn single_layer(patterns: &[&str]) -> ToolFilter {
|
||||
layered(&[(LayerSource::Global, patterns)])
|
||||
}
|
||||
|
||||
fn layered(layers: &[(LayerSource, &[&str])]) -> ToolFilter {
|
||||
let mut filter = ToolFilter::default();
|
||||
for (source, patterns) in layers {
|
||||
filter.push_layer(source.clone(), &list(patterns));
|
||||
}
|
||||
filter
|
||||
}
|
||||
|
||||
fn no_aliases() -> IndexMap<String, String> {
|
||||
IndexMap::new()
|
||||
}
|
||||
|
||||
fn aliases(entries: &[(&str, &str)]) -> IndexMap<String, String> {
|
||||
entries
|
||||
.iter()
|
||||
.map(|(key, value)| (key.to_string(), value.to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn resolve(
|
||||
config: &McpServersConfig,
|
||||
session: Option<&IndexMap<String, Vec<String>>>,
|
||||
role: Option<(&str, &IndexMap<String, Vec<String>>)>,
|
||||
) -> HashMap<String, ToolFilter> {
|
||||
McpToolPolicy::effective(config, session, None, role, None, &[], None, &no_aliases())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_pattern_matches_only_the_exact_name() {
|
||||
let filter = single_layer(&["get_issue"]);
|
||||
|
||||
assert!(filter.allows("get_issue"));
|
||||
assert!(!filter.allows("get_issues"));
|
||||
assert!(!filter.allows("get_issu"));
|
||||
assert!(!filter.allows("xget_issue"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn star_matches_any_run_of_characters() {
|
||||
let filter = single_layer(&["get_*"]);
|
||||
assert!(filter.allows("get_issue"));
|
||||
assert!(filter.allows("get_"));
|
||||
assert!(!filter.allows("set_issue"));
|
||||
|
||||
let filter = single_layer(&["*_issue"]);
|
||||
assert!(filter.allows("create_issue"));
|
||||
assert!(!filter.allows("create_pr"));
|
||||
|
||||
let filter = single_layer(&["get*sue"]);
|
||||
assert!(filter.allows("get_issue"));
|
||||
assert!(filter.allows("getsue"));
|
||||
|
||||
let filter = single_layer(&["*"]);
|
||||
assert!(filter.allows(""));
|
||||
assert!(filter.allows("anything_at_all"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn question_mark_matches_exactly_one_character() {
|
||||
let filter = single_layer(&["get_?"]);
|
||||
|
||||
assert!(filter.allows("get_a"));
|
||||
assert!(!filter.allows("get_"));
|
||||
assert!(!filter.allows("get_ab"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regex_metacharacters_are_matched_literally() {
|
||||
let filter = single_layer(&["get.issue"]);
|
||||
assert!(filter.allows("get.issue"));
|
||||
assert!(!filter.allows("getXissue"));
|
||||
|
||||
for pattern in ["a(b", "a[b", "a+b", "a|b", "a$b"] {
|
||||
let filter = single_layer(&[pattern]);
|
||||
assert!(filter.allows(pattern), "'{pattern}' should match itself");
|
||||
assert!(!filter.allows("ab"), "'{pattern}' should not match 'ab'");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn backslash_is_literal_and_star_still_wildcards() {
|
||||
let filter = single_layer(&["a\\b"]);
|
||||
assert!(filter.allows("a\\b"));
|
||||
assert!(!filter.allows("ab"));
|
||||
|
||||
let filter = single_layer(&["a\\*b"]);
|
||||
assert!(filter.allows("a\\b"));
|
||||
assert!(filter.allows("a\\xyzb"));
|
||||
assert!(!filter.allows("ab"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_never_matching_placeholder_matches_nothing() {
|
||||
let regex = never_matching_regex();
|
||||
|
||||
assert!(!regex.is_match("").unwrap());
|
||||
assert!(!regex.is_match("anything").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn within_a_layer_any_pattern_may_match() {
|
||||
let filter = single_layer(&["get_*", "set_*"]);
|
||||
|
||||
assert!(filter.allows("get_x"));
|
||||
assert!(filter.allows("set_x"));
|
||||
assert!(!filter.allows("delete_x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn across_layers_every_layer_must_match() {
|
||||
let filter = layered(&[
|
||||
(LayerSource::Global, &["get_*"]),
|
||||
(LayerSource::Session, &["*_issue"]),
|
||||
]);
|
||||
|
||||
assert!(filter.allows("get_issue"));
|
||||
assert!(!filter.allows("get_pr"));
|
||||
assert!(!filter.allows("create_issue"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_layer_blocks_everything() {
|
||||
let filter = layered(&[(LayerSource::Global, &["*"]), (LayerSource::Session, &[])]);
|
||||
|
||||
assert!(!filter.allows("anything"));
|
||||
assert_eq!(
|
||||
filter.allows_explain("anything"),
|
||||
Err(&LayerSource::Session)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allows_explain_reports_the_first_matching_pattern_per_layer() {
|
||||
let filter = layered(&[
|
||||
(LayerSource::Global, &["x_*", "get_*"]),
|
||||
(LayerSource::Session, &["*"]),
|
||||
]);
|
||||
|
||||
assert_eq!(
|
||||
filter.allows_explain("get_issue").unwrap(),
|
||||
vec![
|
||||
(&LayerSource::Global, "get_*"),
|
||||
(&LayerSource::Session, "*")
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allows_explain_reports_the_first_layer_without_a_match() {
|
||||
let filter = layered(&[
|
||||
(LayerSource::Global, &["get_*"]),
|
||||
(LayerSource::Session, &["*"]),
|
||||
]);
|
||||
assert_eq!(
|
||||
filter.allows_explain("delete_repo"),
|
||||
Err(&LayerSource::Global)
|
||||
);
|
||||
|
||||
let filter = layered(&[
|
||||
(LayerSource::Global, &["*"]),
|
||||
(LayerSource::Session, &["get_*"]),
|
||||
]);
|
||||
assert_eq!(
|
||||
filter.allows_explain("delete_repo"),
|
||||
Err(&LayerSource::Session)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_allowed_tools_from_mcp_json_is_the_first_layer() {
|
||||
let config = config(&[("gh", Some(&["get_*"]))]);
|
||||
let session_map = tool_map(&[("gh", &["*"])]);
|
||||
|
||||
let filters = resolve(&config, Some(&session_map), None);
|
||||
|
||||
assert_eq!(
|
||||
filters["gh"].allows_explain("get_issue").unwrap(),
|
||||
vec![
|
||||
(&LayerSource::Global, "get_*"),
|
||||
(&LayerSource::Session, "*")
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn servers_without_patterns_at_any_level_are_absent() {
|
||||
let config = config(&[("gh", None)]);
|
||||
|
||||
let filters = resolve(&config, None, None);
|
||||
|
||||
assert!(filters.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_absent_from_a_level_map_gets_no_layer_from_it() {
|
||||
let config = config(&[("gh", Some(&["get_*"])), ("gl", None)]);
|
||||
let role_map = tool_map(&[("gl", &["x_*"])]);
|
||||
|
||||
let filters = resolve(&config, None, Some(("dev", &role_map)));
|
||||
|
||||
assert!(filters["gh"].allows("get_issue"));
|
||||
assert!(!filters["gh"].allows("delete_repo"));
|
||||
assert_eq!(filters["gh"].allows_explain("get_issue").unwrap().len(), 1);
|
||||
assert!(filters["gl"].allows("x_1"));
|
||||
assert!(!filters["gl"].allows("y_1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_pattern_list_at_a_level_blocks_all_tools_for_that_server() {
|
||||
let config = config(&[("gh", Some(&["get_*"]))]);
|
||||
let session_map = tool_map(&[("gh", &[])]);
|
||||
|
||||
let filters = resolve(&config, Some(&session_map), None);
|
||||
|
||||
assert!(!filters["gh"].allows("get_issue"));
|
||||
assert_eq!(
|
||||
filters["gh"].allows_explain("get_issue"),
|
||||
Err(&LayerSource::Session)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_cannot_widen_a_role_restriction() {
|
||||
let config = config(&[("gh", None)]);
|
||||
let role_map = tool_map(&[("gh", &["get_*"])]);
|
||||
let session_map = tool_map(&[("gh", &["*"])]);
|
||||
|
||||
let filters = resolve(&config, Some(&session_map), Some(("dev", &role_map)));
|
||||
|
||||
assert!(filters["gh"].allows("get_issue"));
|
||||
assert!(!filters["gh"].allows("delete_repo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_config_map_contributes_its_own_layer() {
|
||||
let config = config(&[("gh", None)]);
|
||||
let app_map = tool_map(&[("gh", &["get_*"])]);
|
||||
|
||||
let filters = McpToolPolicy::effective(
|
||||
&config,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
Some(&app_map),
|
||||
&[],
|
||||
None,
|
||||
&no_aliases(),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
filters["gh"].allows_explain("get_issue").unwrap(),
|
||||
vec![(&LayerSource::AppConfig, "get_*")]
|
||||
);
|
||||
assert!(!filters["gh"].allows("delete_repo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skill_layer_applies_only_to_its_enabled_servers() {
|
||||
let config = config(&[("gh", None), ("gl", None)]);
|
||||
let skill = SkillMcpLayer {
|
||||
name: "reviewer".to_string(),
|
||||
enabled_servers: vec!["gh".to_string()],
|
||||
mcp_tools: tool_map(&[("gh", &["get_*"]), ("gl", &["*"])]),
|
||||
};
|
||||
|
||||
let filters = McpToolPolicy::effective(
|
||||
&config,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&[skill],
|
||||
None,
|
||||
&no_aliases(),
|
||||
);
|
||||
|
||||
assert!(filters.contains_key("gh"));
|
||||
assert!(!filters.contains_key("gl"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_skills_naming_the_same_server_stack_independent_layers() {
|
||||
let config = config(&[("gh", None)]);
|
||||
let skills = vec![
|
||||
SkillMcpLayer {
|
||||
name: "a".to_string(),
|
||||
enabled_servers: vec!["gh".to_string()],
|
||||
mcp_tools: tool_map(&[("gh", &["get_*"])]),
|
||||
},
|
||||
SkillMcpLayer {
|
||||
name: "b".to_string(),
|
||||
enabled_servers: vec!["gh".to_string()],
|
||||
mcp_tools: tool_map(&[("gh", &["*_issue"])]),
|
||||
},
|
||||
];
|
||||
|
||||
let filters = McpToolPolicy::effective(
|
||||
&config,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&skills,
|
||||
None,
|
||||
&no_aliases(),
|
||||
);
|
||||
|
||||
assert!(filters["gh"].allows("get_issue"));
|
||||
assert!(!filters["gh"].allows("get_pr"));
|
||||
assert!(!filters["gh"].allows("create_issue"));
|
||||
assert_eq!(filters["gh"].allows_explain("get_issue").unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_stack_in_documented_order_with_node_last() {
|
||||
let config = config(&[("gh", Some(&["*"]))]);
|
||||
let app_map = tool_map(&[("gh", &["*"])]);
|
||||
let role_map = tool_map(&[("gh", &["*"])]);
|
||||
let agent_map = tool_map(&[("gh", &["*"])]);
|
||||
let session_map = tool_map(&[("gh", &["*"])]);
|
||||
let skills = vec![SkillMcpLayer {
|
||||
name: "reviewer".to_string(),
|
||||
enabled_servers: vec!["gh".to_string()],
|
||||
mcp_tools: tool_map(&[("gh", &["*"])]),
|
||||
}];
|
||||
let node_map = tool_map(&[("gh", &["*"])]);
|
||||
|
||||
let filters = McpToolPolicy::effective(
|
||||
&config,
|
||||
Some(&session_map),
|
||||
Some(("worker", &agent_map)),
|
||||
Some(("dev", &role_map)),
|
||||
Some(&app_map),
|
||||
&skills,
|
||||
Some(("n1", &node_map)),
|
||||
&no_aliases(),
|
||||
);
|
||||
|
||||
let sources: Vec<String> = filters["gh"]
|
||||
.allows_explain("anything")
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|(source, _)| source.to_string())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
sources,
|
||||
vec![
|
||||
"global (mcp.json)",
|
||||
"config (config.yaml)",
|
||||
"role (dev)",
|
||||
"agent (worker)",
|
||||
"session (.set)",
|
||||
"skill (reviewer)",
|
||||
"node (n1)",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alias_key_expands_to_all_mapped_servers() {
|
||||
let config = config(&[("github", None), ("gitlab", None)]);
|
||||
let role_map = tool_map(&[("gh", &["get_*"])]);
|
||||
|
||||
let filters = McpToolPolicy::effective(
|
||||
&config,
|
||||
None,
|
||||
None,
|
||||
Some(("dev", &role_map)),
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
&aliases(&[("gh", "github,gitlab")]),
|
||||
);
|
||||
|
||||
assert!(filters["github"].allows("get_issue"));
|
||||
assert!(!filters["github"].allows("delete_repo"));
|
||||
assert!(filters["gitlab"].allows("get_issue"));
|
||||
assert!(!filters["gitlab"].allows("delete_repo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alias_ids_missing_from_the_config_are_skipped() {
|
||||
let config = config(&[("github", None)]);
|
||||
let role_map = tool_map(&[("gh", &["get_*"])]);
|
||||
|
||||
let filters = McpToolPolicy::effective(
|
||||
&config,
|
||||
None,
|
||||
None,
|
||||
Some(("dev", &role_map)),
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
&aliases(&[("gh", "github,missing")]),
|
||||
);
|
||||
|
||||
assert_eq!(filters.len(), 1);
|
||||
assert!(filters.contains_key("github"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_map_keys_are_dropped() {
|
||||
let config = config(&[("github", None)]);
|
||||
let role_map = tool_map(&[("nope", &["get_*"])]);
|
||||
|
||||
let filters = resolve(&config, None, Some(("dev", &role_map)));
|
||||
|
||||
assert!(filters.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alias_and_direct_key_for_the_same_server_merge_into_one_layer() {
|
||||
let config = config(&[("github", None)]);
|
||||
let role_map = tool_map(&[("gh", &["get_*"]), ("github", &["set_*"])]);
|
||||
|
||||
let filters = McpToolPolicy::effective(
|
||||
&config,
|
||||
None,
|
||||
None,
|
||||
Some(("dev", &role_map)),
|
||||
None,
|
||||
&[],
|
||||
None,
|
||||
&aliases(&[("gh", "github")]),
|
||||
);
|
||||
|
||||
assert!(filters["github"].allows("get_issue"));
|
||||
assert!(filters["github"].allows("set_topic"));
|
||||
assert!(!filters["github"].allows("delete_repo"));
|
||||
assert_eq!(
|
||||
filters["github"].allows_explain("get_issue").unwrap().len(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_source_display() {
|
||||
assert_eq!(LayerSource::Global.to_string(), "global (mcp.json)");
|
||||
assert_eq!(LayerSource::AppConfig.to_string(), "config (config.yaml)");
|
||||
assert_eq!(LayerSource::Role("dev".into()).to_string(), "role (dev)");
|
||||
assert_eq!(
|
||||
LayerSource::Agent("worker".into()).to_string(),
|
||||
"agent (worker)"
|
||||
);
|
||||
assert_eq!(LayerSource::Session.to_string(), "session (.set)");
|
||||
assert_eq!(
|
||||
LayerSource::Skill("review".into()).to_string(),
|
||||
"skill (review)"
|
||||
);
|
||||
assert_eq!(LayerSource::Node("n1".into()).to_string(), "node (n1)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dead_context_patterns_flags_patterns_matching_nothing() {
|
||||
let filter = layered(&[
|
||||
(LayerSource::Global, &["get_*"]),
|
||||
(LayerSource::Role("dev".into()), &["get_issue", "set_*"]),
|
||||
]);
|
||||
|
||||
let advertised = vec!["get_issue".to_string(), "set_topic".to_string()];
|
||||
let dead = filter.dead_context_patterns(&advertised);
|
||||
|
||||
// set_* only matches set_topic, which the global layer hides.
|
||||
assert_eq!(dead, vec![(&LayerSource::Role("dev".into()), "set_*")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dead_context_patterns_is_empty_when_every_pattern_is_live() {
|
||||
let filter = layered(&[
|
||||
(LayerSource::Global, &["get_*"]),
|
||||
(LayerSource::Session, &["get_issue"]),
|
||||
]);
|
||||
|
||||
let advertised = vec!["get_issue".to_string()];
|
||||
assert!(filter.dead_context_patterns(&advertised).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dead_context_patterns_ignores_the_global_layer_itself() {
|
||||
let filter = layered(&[(LayerSource::Global, &["zzz_*"])]);
|
||||
|
||||
let advertised = vec!["get_issue".to_string()];
|
||||
assert!(filter.dead_context_patterns(&advertised).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_mcp_server_alias_splits_and_trims() {
|
||||
let aliases = aliases(&[("gh", "github, gitlab,")]);
|
||||
|
||||
assert_eq!(
|
||||
expand_mcp_server_alias(&aliases, "gh"),
|
||||
vec!["github".to_string(), "gitlab".to_string()]
|
||||
);
|
||||
assert!(expand_mcp_server_alias(&aliases, "nope").is_empty());
|
||||
}
|
||||
}
|
||||
+144
-89
@@ -8,6 +8,7 @@ pub(crate) mod instructions;
|
||||
mod macro_policy;
|
||||
mod macros;
|
||||
mod mcp_factory;
|
||||
mod mcp_tool_policy;
|
||||
pub(crate) mod memory;
|
||||
pub(crate) mod paths;
|
||||
pub(crate) mod prompts;
|
||||
@@ -41,6 +42,9 @@ pub use self::install_remote::{
|
||||
pub use self::macro_policy::{
|
||||
MacroAllowlistLevel, MacroPolicy, MacroSource, MacroState, RESERVED_MACRO_NAMES, ResolvedMacro,
|
||||
};
|
||||
pub(crate) use self::mcp_tool_policy::expand_mcp_server_alias;
|
||||
#[cfg(test)]
|
||||
pub(crate) use self::mcp_tool_policy::{LayerSource, ToolFilter};
|
||||
#[allow(unused_imports)]
|
||||
pub use self::request_context::{
|
||||
RenderMode, RequestContext, effective_max_concurrent_jobs, jobs_enabled,
|
||||
@@ -146,6 +150,9 @@ fn validate_no_template_in_secrets_provider(content: &str) -> Result<()> {
|
||||
const DARK_THEME: &[u8] = include_bytes!("../../assets/monokai-extended.theme.bin");
|
||||
const LIGHT_THEME: &[u8] = include_bytes!("../../assets/monokai-extended-light.theme.bin");
|
||||
|
||||
/// Fully documented config skeleton the first-run wizard splices dynamic values into.
|
||||
const CONFIG_TEMPLATE: &str = include_str!("../../assets/config-template.yaml");
|
||||
|
||||
const CONFIG_FILE_NAME: &str = "config.yaml";
|
||||
const AGENT_GRAPH_FILE_NAME: &str = "graph.yaml";
|
||||
const ROLES_DIR_NAME: &str = "roles";
|
||||
@@ -176,27 +183,6 @@ 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";
|
||||
const DEFAULT_VISIBLE_TOOLS: [&str; 19] = [
|
||||
"execute_command.sh",
|
||||
"execute_py_code.py",
|
||||
"execute_sql_code.sh",
|
||||
"fetch_url_via_curl.sh",
|
||||
"fs_cat.sh",
|
||||
"fs_glob.sh",
|
||||
"fs_grep.sh",
|
||||
"fs_ls.sh",
|
||||
"fs_mkdir.sh",
|
||||
"fs_patch.sh",
|
||||
"fs_read.sh",
|
||||
"fs_rm.sh",
|
||||
"fs_write.sh",
|
||||
"ast_grep.sh",
|
||||
"get_current_time.sh",
|
||||
"get_current_weather.sh",
|
||||
"search_wikipedia.sh",
|
||||
"search_arxiv.sh",
|
||||
"web_search_coyote.sh",
|
||||
];
|
||||
|
||||
const CLIENTS_FIELD: &str = "clients";
|
||||
|
||||
@@ -250,6 +236,7 @@ pub struct Config {
|
||||
pub mapping_mcp_servers: IndexMap<String, String>,
|
||||
#[serde(default, deserialize_with = "deserialize_csv_or_vec")]
|
||||
pub enabled_mcp_servers: Option<Vec<String>>,
|
||||
pub mcp_tools: Option<IndexMap<String, Vec<String>>>,
|
||||
|
||||
pub auto_continue: bool,
|
||||
pub max_auto_continues: usize,
|
||||
@@ -333,6 +320,7 @@ impl Default for Config {
|
||||
mcp_server_support: true,
|
||||
mapping_mcp_servers: Default::default(),
|
||||
enabled_mcp_servers: None,
|
||||
mcp_tools: None,
|
||||
|
||||
auto_continue: false,
|
||||
max_auto_continues: 10,
|
||||
@@ -401,12 +389,12 @@ pub enum AssetCategory {
|
||||
Macros,
|
||||
Functions,
|
||||
Skills,
|
||||
#[value(name = "mcp_config")]
|
||||
#[value(name = "mcp-config", alias = "mcp_config")]
|
||||
McpConfig,
|
||||
}
|
||||
|
||||
impl AssetCategory {
|
||||
pub const NAMES: [&'static str; 5] = ["agents", "macros", "functions", "skills", "mcp_config"];
|
||||
pub const NAMES: [&'static str; 5] = ["agents", "macros", "functions", "skills", "mcp-config"];
|
||||
|
||||
pub fn parse(name: &str) -> Option<Self> {
|
||||
match name {
|
||||
@@ -414,7 +402,7 @@ impl AssetCategory {
|
||||
"macros" => Some(Self::Macros),
|
||||
"functions" => Some(Self::Functions),
|
||||
"skills" => Some(Self::Skills),
|
||||
"mcp_config" => Some(Self::McpConfig),
|
||||
"mcp-config" | "mcp_config" => Some(Self::McpConfig),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -433,7 +421,7 @@ pub enum InstallFilter {
|
||||
Skills,
|
||||
Macros,
|
||||
Functions,
|
||||
#[value(name = "mcp_config")]
|
||||
#[value(name = "mcp-config", alias = "mcp_config")]
|
||||
McpConfig,
|
||||
}
|
||||
|
||||
@@ -444,7 +432,7 @@ impl InstallFilter {
|
||||
"skills",
|
||||
"macros",
|
||||
"functions",
|
||||
"mcp_config",
|
||||
"mcp-config",
|
||||
];
|
||||
|
||||
pub fn parse(name: &str) -> Option<Self> {
|
||||
@@ -454,7 +442,7 @@ impl InstallFilter {
|
||||
"skills" => Some(Self::Skills),
|
||||
"macros" => Some(Self::Macros),
|
||||
"functions" => Some(Self::Functions),
|
||||
"mcp_config" => Some(Self::McpConfig),
|
||||
"mcp-config" | "mcp_config" => Some(Self::McpConfig),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -805,51 +793,20 @@ pub async fn create_config_file(config_path: &Path) -> Result<()> {
|
||||
|
||||
let client = Select::new("API Provider (required):", list_client_types()).prompt()?;
|
||||
|
||||
let mut config = json!({});
|
||||
let (model, clients_config) = create_client_config(client, &vault).await?;
|
||||
config["model"] = model.into();
|
||||
match &provider_choice {
|
||||
None => {
|
||||
config["vault_password_file"] =
|
||||
vault.local_password_file()?.display().to_string().into();
|
||||
}
|
||||
let secrets = match &provider_choice {
|
||||
None => json!({
|
||||
"vault_password_file": vault.local_password_file()?.display().to_string()
|
||||
}),
|
||||
Some(provider) => {
|
||||
config["secrets_provider"] = serde_json::to_value(provider)
|
||||
let provider = serde_json::to_value(provider)
|
||||
.with_context(|| "failed to serialize secrets_provider config")?;
|
||||
json!({ "secrets_provider": provider })
|
||||
}
|
||||
}
|
||||
config["stream"] = json!(true);
|
||||
config["save"] = json!(true);
|
||||
config["keybindings"] = json!("vi");
|
||||
config["wrap"] = json!("auto");
|
||||
config["wrap_code"] = json!(false);
|
||||
config["function_calling_support"] = json!(true);
|
||||
config["enabled_tools"] = json!(null);
|
||||
config["visible_tools"] = json!(DEFAULT_VISIBLE_TOOLS);
|
||||
config["mcp_server_support"] = json!(true);
|
||||
config["enabled_mcp_servers"] = json!(null);
|
||||
config["highlight"] = json!(true);
|
||||
config["light_theme"] = json!(false);
|
||||
config[CLIENTS_FIELD] = clients_config;
|
||||
};
|
||||
|
||||
let config_data = serde_yaml::to_string(&config).with_context(|| "Failed to create config")?;
|
||||
let config_data = format!(
|
||||
"# see https://github.com/Dark-Alex-17/coyote/blob/main/config.example.yaml\n\n{config_data}"
|
||||
);
|
||||
|
||||
ensure_parent_exists(config_path)?;
|
||||
std::fs::write(config_path, config_data)
|
||||
.with_context(|| format!("Failed to write to '{}'", config_path.display()))?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::prelude::PermissionsExt;
|
||||
let perms = std::fs::Permissions::from_mode(0o600);
|
||||
std::fs::set_permissions(config_path, perms)?;
|
||||
}
|
||||
|
||||
println!("✓ Saved the config file to '{}'.\n", config_path.display());
|
||||
|
||||
Ok(())
|
||||
let config_data = render_config_template(&model, Some(&secrets), &clients_config)?;
|
||||
write_config_file(config_path, &config_data)
|
||||
}
|
||||
|
||||
async fn create_config_file_sandbox(config_path: &Path) -> Result<()> {
|
||||
@@ -859,7 +816,7 @@ async fn create_config_file_sandbox(config_path: &Path) -> Result<()> {
|
||||
"Running in sandbox mode — your API provider credentials are managed by your host Coyote configuration if configured."
|
||||
);
|
||||
|
||||
let oai_api_base = client::OPENAI_COMPATIBLE_PROVIDERS
|
||||
let oai_api_base = OPENAI_COMPATIBLE_PROVIDERS
|
||||
.iter()
|
||||
.find(|(name, _)| *name == client)
|
||||
.map(|(_, url)| *url);
|
||||
@@ -872,13 +829,13 @@ async fn create_config_file_sandbox(config_path: &Path) -> Result<()> {
|
||||
} else {
|
||||
api_base.to_string()
|
||||
};
|
||||
serde_json::json!({
|
||||
json!({
|
||||
"type": "openai-compatible",
|
||||
"name": client,
|
||||
"api_base": api_base_str,
|
||||
})
|
||||
} else {
|
||||
serde_json::json!({ "type": client })
|
||||
json!({ "type": client })
|
||||
};
|
||||
|
||||
if client::client_type_supports_oauth(client) {
|
||||
@@ -892,27 +849,45 @@ async fn create_config_file_sandbox(config_path: &Path) -> Result<()> {
|
||||
|
||||
let model = set_client_models_config(&mut client_config, client).await?;
|
||||
|
||||
let mut config = serde_json::json!({});
|
||||
config["model"] = model.into();
|
||||
config["stream"] = serde_json::json!(true);
|
||||
config["save"] = serde_json::json!(true);
|
||||
config["keybindings"] = serde_json::json!("vi");
|
||||
config["wrap"] = serde_json::json!("auto");
|
||||
config["wrap_code"] = serde_json::json!(false);
|
||||
config["function_calling_support"] = serde_json::json!(true);
|
||||
config["enabled_tools"] = serde_json::json!(null);
|
||||
config["visible_tools"] = serde_json::json!(DEFAULT_VISIBLE_TOOLS);
|
||||
config["mcp_server_support"] = serde_json::json!(true);
|
||||
config["enabled_mcp_servers"] = serde_json::json!(null);
|
||||
config["highlight"] = serde_json::json!(true);
|
||||
config["light_theme"] = serde_json::json!(false);
|
||||
config[CLIENTS_FIELD] = serde_json::json!(vec![client_config]);
|
||||
let config_data = render_config_template(&model, None, &json!([client_config]))?;
|
||||
write_config_file(config_path, &config_data)
|
||||
}
|
||||
|
||||
let config_data = serde_yaml::to_string(&config).with_context(|| "Failed to create config")?;
|
||||
let config_data = format!(
|
||||
"# see https://github.com/Dark-Alex-17/coyote/blob/main/config.example.yaml\n\n{config_data}"
|
||||
);
|
||||
fn render_config_template(
|
||||
model: &str,
|
||||
secrets: Option<&serde_json::Value>,
|
||||
clients: &serde_json::Value,
|
||||
) -> Result<String> {
|
||||
render_config_template_from(CONFIG_TEMPLATE, model, secrets, clients)
|
||||
}
|
||||
|
||||
fn render_config_template_from(
|
||||
template: &str,
|
||||
model: &str,
|
||||
secrets: Option<&serde_json::Value>,
|
||||
clients: &serde_json::Value,
|
||||
) -> Result<String> {
|
||||
let to_yaml = |value: &serde_json::Value| {
|
||||
serde_yaml::to_string(value).with_context(|| "Failed to create config")
|
||||
};
|
||||
|
||||
let model_block = to_yaml(&json!({ "model": model }))?;
|
||||
let secrets_block = match secrets {
|
||||
Some(value) => to_yaml(value)?,
|
||||
None => "# Sandbox mode: no vault provider is configured; secrets are provisioned\n\
|
||||
# from the host when the sandbox is created.\n"
|
||||
.to_string(),
|
||||
};
|
||||
let clients_block = to_yaml(&json!({ CLIENTS_FIELD: clients }))?;
|
||||
|
||||
Ok(template
|
||||
.replace("\r\n", "\n")
|
||||
.replacen("__MODEL_BLOCK__\n", &model_block, 1)
|
||||
.replacen("__SECRETS_BLOCK__\n", &secrets_block, 1)
|
||||
.replacen("__CLIENTS_BLOCK__\n", &clients_block, 1))
|
||||
}
|
||||
|
||||
fn write_config_file(config_path: &Path, config_data: &str) -> Result<()> {
|
||||
ensure_parent_exists(config_path)?;
|
||||
std::fs::write(config_path, config_data)
|
||||
.with_context(|| format!("Failed to write to '{}'", config_path.display()))?;
|
||||
@@ -1128,6 +1103,17 @@ clients:
|
||||
assert!(validate_no_template_in_secrets_provider(yaml).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_yaml_parses_mcp_tools() {
|
||||
let cfg: Config = serde_yaml::from_str("mcp_tools:\n github:\n - get_*\n").unwrap();
|
||||
|
||||
assert_eq!(
|
||||
cfg.mcp_tools.as_ref().unwrap().get("github"),
|
||||
Some(&vec!["get_*".to_string()])
|
||||
);
|
||||
assert_eq!(Config::default().mcp_tools, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_defaults_match_expected() {
|
||||
let cfg = Config::default();
|
||||
@@ -1157,6 +1143,75 @@ clients:
|
||||
assert_eq!(cfg.enabled_macros, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_template_renders_parseable_config() {
|
||||
let secrets = json!({ "vault_password_file": "/home/user/.coyote_password" });
|
||||
let clients = json!([{ "type": "openai", "api_key": "sk-test" }]);
|
||||
|
||||
let rendered = render_config_template("openai:gpt-4o", Some(&secrets), &clients).unwrap();
|
||||
|
||||
assert!(!rendered.contains("__MODEL_BLOCK__"));
|
||||
assert!(!rendered.contains("__SECRETS_BLOCK__"));
|
||||
assert!(!rendered.contains("__CLIENTS_BLOCK__"));
|
||||
|
||||
let cfg = Config::load_from_str(&rendered).unwrap();
|
||||
assert_eq!(cfg.model_id, "openai:gpt-4o");
|
||||
assert_eq!(
|
||||
cfg.vault_password_file,
|
||||
Some(PathBuf::from("/home/user/.coyote_password"))
|
||||
);
|
||||
assert!(cfg.secrets_provider.is_none());
|
||||
assert_eq!(cfg.keybindings, "emacs");
|
||||
assert!(cfg.save);
|
||||
assert_eq!(cfg.wrap.as_deref(), Some("auto"));
|
||||
assert!(cfg.visible_tools.is_none());
|
||||
assert!(cfg.mapping_tools.is_empty());
|
||||
assert!(cfg.document_loaders.is_empty());
|
||||
assert_eq!(cfg.compression_threshold, 4000);
|
||||
assert!(cfg.theme.is_none());
|
||||
assert_eq!(cfg.clients.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_template_renders_parseable_sandbox_config() {
|
||||
let clients = json!([{ "type": "claude" }]);
|
||||
|
||||
let rendered =
|
||||
render_config_template("claude:claude-sonnet-4-20250514", None, &clients).unwrap();
|
||||
|
||||
assert!(!rendered.contains("__SECRETS_BLOCK__"));
|
||||
|
||||
let cfg = Config::load_from_str(&rendered).unwrap();
|
||||
assert_eq!(cfg.model_id, "claude:claude-sonnet-4-20250514");
|
||||
assert!(cfg.vault_password_file.is_none());
|
||||
assert!(cfg.secrets_provider.is_none());
|
||||
assert_eq!(cfg.keybindings, "emacs");
|
||||
assert!(cfg.save);
|
||||
assert!(cfg.visible_tools.is_none());
|
||||
assert_eq!(cfg.compression_threshold, 4000);
|
||||
assert_eq!(cfg.clients.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_template_renders_with_crlf_line_endings() {
|
||||
let crlf_template = CONFIG_TEMPLATE.replace('\n', "\r\n");
|
||||
let secrets = json!({ "vault_password_file": "/home/user/.coyote_password" });
|
||||
let clients = json!([{ "type": "openai", "api_key": "sk-test" }]);
|
||||
|
||||
let rendered =
|
||||
render_config_template_from(&crlf_template, "openai:gpt-4o", Some(&secrets), &clients)
|
||||
.unwrap();
|
||||
|
||||
assert!(!rendered.contains("__MODEL_BLOCK__"));
|
||||
assert!(!rendered.contains("__SECRETS_BLOCK__"));
|
||||
assert!(!rendered.contains("__CLIENTS_BLOCK__"));
|
||||
assert!(!rendered.contains('\r'));
|
||||
|
||||
let cfg = Config::load_from_str(&rendered).unwrap();
|
||||
assert_eq!(cfg.model_id, "openai:gpt-4o");
|
||||
assert_eq!(cfg.clients.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_enabled_macros_empty_string_is_some_empty() {
|
||||
let cfg: Config = serde_yaml::from_str("enabled_macros: \"\"").unwrap();
|
||||
|
||||
+1121
-52
File diff suppressed because it is too large
Load Diff
@@ -30,6 +30,7 @@ pub trait RoleLike {
|
||||
fn top_p(&self) -> Option<f64>;
|
||||
fn enabled_tools(&self) -> Option<Vec<String>>;
|
||||
fn enabled_mcp_servers(&self) -> Option<Vec<String>>;
|
||||
fn mcp_tools(&self) -> Option<IndexMap<String, Vec<String>>>;
|
||||
fn set_model(&mut self, model: Model);
|
||||
fn set_temperature(&mut self, value: Option<f64>);
|
||||
fn reasoning_effort(&self) -> Option<String>;
|
||||
@@ -37,6 +38,7 @@ pub trait RoleLike {
|
||||
fn set_reasoning_effort(&mut self, value: Option<String>);
|
||||
fn set_enabled_tools(&mut self, value: Option<Vec<String>>);
|
||||
fn set_enabled_mcp_servers(&mut self, value: Option<Vec<String>>);
|
||||
fn set_mcp_tools(&mut self, value: Option<IndexMap<String, Vec<String>>>);
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||
@@ -67,6 +69,8 @@ pub struct Role {
|
||||
deserialize_with = "super::deserialize_csv_or_vec"
|
||||
)]
|
||||
enabled_mcp_servers: Option<Vec<String>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
mcp_tools: Option<IndexMap<String, Vec<String>>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
skills_enabled: Option<bool>,
|
||||
#[serde(
|
||||
@@ -133,6 +137,7 @@ impl Role {
|
||||
"enabled_mcp_servers" => {
|
||||
role.enabled_mcp_servers = parse_string_or_array(value)
|
||||
}
|
||||
"mcp_tools" => role.mcp_tools = parse_mcp_tools_map(value),
|
||||
"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),
|
||||
@@ -196,6 +201,10 @@ impl Role {
|
||||
serde_json::to_string(enabled_mcp_servers).unwrap_or_else(|_| "[]".to_string());
|
||||
metadata.push(format!("enabled_mcp_servers: {inline}"));
|
||||
}
|
||||
if let Some(mcp_tools) = &self.mcp_tools {
|
||||
let inline = serde_json::to_string(mcp_tools).unwrap_or_else(|_| "{}".to_string());
|
||||
metadata.push(format!("mcp_tools: {inline}"));
|
||||
}
|
||||
if let Some(skills_enabled) = self.skills_enabled {
|
||||
metadata.push(format!("skills_enabled: {skills_enabled}"));
|
||||
}
|
||||
@@ -279,6 +288,10 @@ impl Role {
|
||||
enabled_tools,
|
||||
enabled_mcp_servers,
|
||||
);
|
||||
let mcp_tools = role_like.mcp_tools();
|
||||
if mcp_tools.is_some() {
|
||||
self.set_mcp_tools(mcp_tools);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn batch_set(
|
||||
@@ -453,6 +466,10 @@ impl RoleLike for Role {
|
||||
self.enabled_mcp_servers.clone()
|
||||
}
|
||||
|
||||
fn mcp_tools(&self) -> Option<IndexMap<String, Vec<String>>> {
|
||||
self.mcp_tools.clone()
|
||||
}
|
||||
|
||||
fn set_model(&mut self, model: Model) {
|
||||
if !self.model().id().is_empty() {
|
||||
self.model_id = Some(model.id().to_string());
|
||||
@@ -479,6 +496,10 @@ impl RoleLike for Role {
|
||||
fn set_enabled_mcp_servers(&mut self, value: Option<Vec<String>>) {
|
||||
self.enabled_mcp_servers = value;
|
||||
}
|
||||
|
||||
fn set_mcp_tools(&mut self, value: Option<IndexMap<String, Vec<String>>>) {
|
||||
self.mcp_tools = value;
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_string_or_array(value: &Value) -> Option<Vec<String>> {
|
||||
@@ -503,6 +524,19 @@ fn parse_string_or_array(value: &Value) -> Option<Vec<String>> {
|
||||
None
|
||||
}
|
||||
|
||||
fn parse_mcp_tools_map(value: &Value) -> Option<IndexMap<String, Vec<String>>> {
|
||||
let map = value.as_object()?;
|
||||
let mut mcp_tools = IndexMap::new();
|
||||
for (server, tools) in map {
|
||||
if tools.is_null() {
|
||||
mcp_tools.insert(server.clone(), Vec::new());
|
||||
} else if let Some(tools) = parse_string_or_array(tools) {
|
||||
mcp_tools.insert(server.clone(), tools);
|
||||
}
|
||||
}
|
||||
Some(mcp_tools)
|
||||
}
|
||||
|
||||
fn parse_structure_prompt(prompt: &str) -> (&str, Vec<(&str, &str)>) {
|
||||
let mut text = prompt;
|
||||
let mut search_input = true;
|
||||
@@ -652,6 +686,69 @@ mod tests {
|
||||
assert_eq!(role.enabled_macros, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_new_parses_mcp_tools_list_and_csv_values() {
|
||||
let content = "---\nmcp_tools:\n github: [get_*, list_*, search_code]\n slack: conversations_history,conversations_replies\n---\nPrompt";
|
||||
|
||||
let role = Role::new("test", content);
|
||||
|
||||
let mcp_tools = role.mcp_tools().unwrap();
|
||||
assert_eq!(
|
||||
mcp_tools.get("github"),
|
||||
Some(&vec![
|
||||
"get_*".to_string(),
|
||||
"list_*".to_string(),
|
||||
"search_code".to_string()
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
mcp_tools.get("slack"),
|
||||
Some(&vec![
|
||||
"conversations_history".to_string(),
|
||||
"conversations_replies".to_string()
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_new_mcp_tools_empty_list_server_is_some_empty() {
|
||||
let role = Role::new("test", "---\nmcp_tools:\n github: []\n---\nPrompt");
|
||||
|
||||
assert_eq!(role.mcp_tools().unwrap().get("github"), Some(&vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_new_mcp_tools_per_server_null_is_some_empty() {
|
||||
let role = Role::new("test", "---\nmcp_tools:\n github:\n---\nPrompt");
|
||||
|
||||
assert_eq!(role.mcp_tools().unwrap().get("github"), Some(&vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_new_mcp_tools_absent_is_none() {
|
||||
let role = Role::new("test", "---\ntemperature: 0.5\n---\nPrompt");
|
||||
|
||||
assert_eq!(role.mcp_tools(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_new_mcp_tools_null_is_none() {
|
||||
let role = Role::new("test", "---\nmcp_tools: null\n---\nPrompt");
|
||||
|
||||
assert_eq!(role.mcp_tools(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_export_mcp_tools_round_trips() {
|
||||
let content = "---\nmcp_tools:\n github: [get_issue]\n slack: a,b\n---\nPrompt";
|
||||
let role = Role::new("test", content);
|
||||
|
||||
let reparsed = Role::new("test", &role.export());
|
||||
|
||||
assert_eq!(reparsed.mcp_tools(), role.mcp_tools());
|
||||
assert!(role.mcp_tools().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_export_includes_enabled_macros() {
|
||||
let role = Role::new("test", "---\nenabled_macros: [a]\n---\nPrompt");
|
||||
|
||||
@@ -40,6 +40,8 @@ pub struct Session {
|
||||
deserialize_with = "super::deserialize_csv_or_vec"
|
||||
)]
|
||||
enabled_mcp_servers: Option<Vec<String>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
mcp_tools: Option<IndexMap<String, Vec<String>>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
skills_enabled: Option<bool>,
|
||||
#[serde(
|
||||
@@ -249,6 +251,9 @@ impl Session {
|
||||
if let Some(enabled_mcp_servers) = self.enabled_mcp_servers() {
|
||||
data["enabled_mcp_servers"] = json!(enabled_mcp_servers);
|
||||
}
|
||||
if let Some(mcp_tools) = self.mcp_tools() {
|
||||
data["mcp_tools"] = json!(mcp_tools);
|
||||
}
|
||||
if let Some(skills_enabled) = self.skills_enabled() {
|
||||
data["skills_enabled"] = skills_enabled.into();
|
||||
}
|
||||
@@ -329,6 +334,13 @@ impl Session {
|
||||
items.push(("enabled_mcp_servers", enabled_mcp_servers.join(",")));
|
||||
}
|
||||
|
||||
if let Some(mcp_tools) = self.mcp_tools() {
|
||||
items.push((
|
||||
"mcp_tools",
|
||||
serde_json::to_string(&mcp_tools).unwrap_or_default(),
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(skills_enabled) = self.skills_enabled() {
|
||||
items.push(("skills_enabled", skills_enabled.to_string()));
|
||||
}
|
||||
@@ -870,6 +882,10 @@ impl RoleLike for Session {
|
||||
self.enabled_mcp_servers.clone()
|
||||
}
|
||||
|
||||
fn mcp_tools(&self) -> Option<IndexMap<String, Vec<String>>> {
|
||||
self.mcp_tools.clone()
|
||||
}
|
||||
|
||||
fn set_model(&mut self, model: Model) {
|
||||
if self.model().id() != model.id() {
|
||||
self.model_id = model.id();
|
||||
@@ -913,6 +929,13 @@ impl RoleLike for Session {
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn set_mcp_tools(&mut self, value: Option<IndexMap<String, Vec<String>>>) {
|
||||
if self.mcp_tools != value {
|
||||
self.mcp_tools = value;
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
@@ -1044,6 +1067,45 @@ mod tests {
|
||||
assert_eq!(session.enabled_macros, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_mcp_tools_survives_yaml_round_trip() {
|
||||
let mut session = Session::default();
|
||||
let mut mcp_tools = IndexMap::new();
|
||||
mcp_tools.insert("github".to_string(), vec!["get_*".to_string()]);
|
||||
mcp_tools.insert("slack".to_string(), vec![]);
|
||||
session.set_mcp_tools(Some(mcp_tools.clone()));
|
||||
|
||||
let yaml = serde_yaml::to_string(&session).unwrap();
|
||||
let reloaded: Session = serde_yaml::from_str(&yaml).unwrap();
|
||||
|
||||
assert_eq!(reloaded.mcp_tools(), Some(mcp_tools));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_set_role_does_not_copy_mcp_tools() {
|
||||
let role = Role::new(
|
||||
"test",
|
||||
"---\nmcp_tools:\n github: [get_issue]\n---\nPrompt",
|
||||
);
|
||||
assert!(role.mcp_tools().is_some());
|
||||
let mut session = Session::default();
|
||||
|
||||
session.set_role(role);
|
||||
|
||||
assert_eq!(session.mcp_tools(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_set_mcp_tools_marks_dirty() {
|
||||
let mut session = Session::default();
|
||||
assert!(!session.dirty());
|
||||
|
||||
session.set_mcp_tools(Some(IndexMap::new()));
|
||||
|
||||
assert!(session.dirty());
|
||||
assert_eq!(session.mcp_tools(), Some(IndexMap::new()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_enabled_macros_empty_list_is_some_empty() {
|
||||
let session: Session =
|
||||
|
||||
@@ -37,6 +37,8 @@ pub struct Skill {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
enabled_mcp_servers: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
mcp_tools: Option<IndexMap<String, Vec<String>>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
auto_unload: Option<bool>,
|
||||
}
|
||||
|
||||
@@ -74,6 +76,9 @@ impl Skill {
|
||||
"enabled_mcp_servers" => {
|
||||
skill.enabled_mcp_servers = parse_skill_string_or_array(value);
|
||||
}
|
||||
"mcp_tools" => {
|
||||
skill.mcp_tools = parse_skill_mcp_tools_map(value);
|
||||
}
|
||||
"auto_unload" => {
|
||||
skill.auto_unload = value.as_bool();
|
||||
}
|
||||
@@ -147,6 +152,10 @@ impl Skill {
|
||||
self.enabled_mcp_servers.as_deref()
|
||||
}
|
||||
|
||||
pub fn mcp_tools(&self) -> Option<&IndexMap<String, Vec<String>>> {
|
||||
self.mcp_tools.as_ref()
|
||||
}
|
||||
|
||||
pub fn auto_unload(&self) -> bool {
|
||||
self.auto_unload.unwrap_or(false)
|
||||
}
|
||||
@@ -185,6 +194,21 @@ fn parse_skill_string_or_array(value: &Value) -> Option<Vec<String>> {
|
||||
None
|
||||
}
|
||||
|
||||
fn parse_skill_mcp_tools_map(value: &Value) -> Option<IndexMap<String, Vec<String>>> {
|
||||
let map = value.as_object()?;
|
||||
let mut mcp_tools = IndexMap::new();
|
||||
|
||||
for (server, tools) in map {
|
||||
if tools.is_null() {
|
||||
mcp_tools.insert(server.clone(), Vec::new());
|
||||
} else if let Some(tools) = parse_skill_string_or_array(tools) {
|
||||
mcp_tools.insert(server.clone(), tools);
|
||||
}
|
||||
}
|
||||
|
||||
Some(mcp_tools)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -198,6 +222,44 @@ mod tests {
|
||||
assert_eq!(skill.description(), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skill_new_parses_mcp_tools_list_and_csv_values() {
|
||||
let content = "---\nmcp_tools:\n github: [get_*, list_*]\n slack: a,b\n---\nBody";
|
||||
|
||||
let skill = Skill::new("test", content);
|
||||
|
||||
let mcp_tools = skill.mcp_tools().unwrap();
|
||||
assert_eq!(
|
||||
mcp_tools.get("github"),
|
||||
Some(&vec!["get_*".to_string(), "list_*".to_string()])
|
||||
);
|
||||
assert_eq!(
|
||||
mcp_tools.get("slack"),
|
||||
Some(&vec!["a".to_string(), "b".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skill_new_mcp_tools_absent_is_none() {
|
||||
let skill = Skill::new("test", "---\ndescription: d\n---\nBody");
|
||||
|
||||
assert_eq!(skill.mcp_tools(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skill_new_mcp_tools_empty_list_server_is_some_empty() {
|
||||
let skill = Skill::new("test", "---\nmcp_tools:\n github: []\n---\nBody");
|
||||
|
||||
assert_eq!(skill.mcp_tools().unwrap().get("github"), Some(&vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skill_new_mcp_tools_per_server_null_is_some_empty() {
|
||||
let skill = Skill::new("test", "---\nmcp_tools:\n github:\n---\nBody");
|
||||
|
||||
assert_eq!(skill.mcp_tools().unwrap().get("github"), Some(&vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skill_new_parses_full_metadata() {
|
||||
let content = "---\n\
|
||||
|
||||
@@ -34,6 +34,10 @@ impl SkillRegistry {
|
||||
self.loaded.keys().cloned().collect()
|
||||
}
|
||||
|
||||
pub fn loaded_skills(&self) -> impl Iterator<Item = &Skill> {
|
||||
self.loaded.values()
|
||||
}
|
||||
|
||||
pub fn loaded_mcp_servers(&self) -> BTreeSet<String> {
|
||||
let mut out = BTreeSet::new();
|
||||
for skill in self.loaded.values() {
|
||||
|
||||
+213
-12
@@ -1,3 +1,4 @@
|
||||
use super::mcp_tool_policy::ToolFilter;
|
||||
use crate::function::{Functions, ToolCallTracker};
|
||||
use crate::mcp::{CatalogItem, CatalogItemKind, ConnectedServer, McpRegistry, McpServerFeatures};
|
||||
|
||||
@@ -44,6 +45,8 @@ pub enum McpPromptCompletion {
|
||||
#[derive(Default, Clone)]
|
||||
pub struct McpRuntime {
|
||||
pub servers: HashMap<String, Arc<ConnectedServer>>,
|
||||
/// Per-server effective tool allowlists; a server absent here is unfiltered.
|
||||
pub tool_filters: HashMap<String, ToolFilter>,
|
||||
}
|
||||
|
||||
impl McpRuntime {
|
||||
@@ -100,12 +103,27 @@ impl McpRuntime {
|
||||
|
||||
if features.tools {
|
||||
match server_handle.list_all_tools().await {
|
||||
Ok(tools) => merge_catalog_items(
|
||||
&mut items,
|
||||
tools
|
||||
.into_iter()
|
||||
.map(|tool| tool_catalog_item(server, tool)),
|
||||
),
|
||||
Ok(mut tools) => {
|
||||
if let Some(filter) = self.tool_filters.get(server) {
|
||||
let advertised: Vec<String> =
|
||||
tools.iter().map(|tool| tool.name.to_string()).collect();
|
||||
|
||||
for (source, pattern) in filter.dead_context_patterns(&advertised) {
|
||||
warn!(
|
||||
"MCP tool pattern '{pattern}' from {source} matches no allowed tools on server '{server}'"
|
||||
);
|
||||
}
|
||||
|
||||
tools.retain(|tool| filter.allows(&tool.name));
|
||||
}
|
||||
|
||||
merge_catalog_items(
|
||||
&mut items,
|
||||
tools
|
||||
.into_iter()
|
||||
.map(|tool| tool_catalog_item(server, tool)),
|
||||
)
|
||||
}
|
||||
Err(e) => warn!("Failed to list tools on MCP server {server}: {e}"),
|
||||
}
|
||||
}
|
||||
@@ -195,6 +213,11 @@ impl McpRuntime {
|
||||
|
||||
match kind {
|
||||
"tool" => {
|
||||
if let Some(filter) = self.tool_filters.get(server)
|
||||
&& !filter.allows(tool)
|
||||
{
|
||||
return Err(anyhow!("{tool} not found in {server} MCP server catalog"));
|
||||
}
|
||||
let tool_schema = server_handle
|
||||
.list_all_tools()
|
||||
.await?
|
||||
@@ -297,6 +320,12 @@ impl McpRuntime {
|
||||
.cloned()
|
||||
.with_context(|| format!("Invoked MCP server does not exist: {server}"))?;
|
||||
|
||||
if let Some(filter) = self.tool_filters.get(server)
|
||||
&& !filter.allows(tool)
|
||||
{
|
||||
return Err(anyhow!("{tool} not found in {server} MCP server catalog"));
|
||||
}
|
||||
|
||||
let mut request = CallToolRequestParams::new(tool.to_owned());
|
||||
request.arguments = arguments.as_object().cloned();
|
||||
|
||||
@@ -614,11 +643,15 @@ pub(crate) mod test_fixtures {
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct FixtureServer {
|
||||
pub(crate) tools_capability: bool,
|
||||
pub(crate) tool_names: Vec<&'static str>,
|
||||
pub(crate) resources_capability: bool,
|
||||
pub(crate) prompts_capability: bool,
|
||||
pub(crate) hostile_prompt: bool,
|
||||
pub(crate) fail_resource_listings: bool,
|
||||
pub(crate) fail_template_listings: bool,
|
||||
pub(crate) fail_prompt_listings: bool,
|
||||
pub(crate) empty_resource_listings: bool,
|
||||
pub(crate) empty_prompt_listings: bool,
|
||||
pub(crate) fail_get_prompt: bool,
|
||||
pub(crate) prompt_delay: Option<Duration>,
|
||||
pub(crate) tool_result: Option<CallToolResult>,
|
||||
@@ -632,11 +665,15 @@ pub(crate) mod test_fixtures {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
tools_capability: true,
|
||||
tool_names: vec!["dup"],
|
||||
resources_capability: false,
|
||||
prompts_capability: false,
|
||||
hostile_prompt: false,
|
||||
fail_resource_listings: false,
|
||||
fail_template_listings: false,
|
||||
fail_prompt_listings: false,
|
||||
empty_resource_listings: false,
|
||||
empty_prompt_listings: false,
|
||||
fail_get_prompt: false,
|
||||
prompt_delay: None,
|
||||
tool_result: None,
|
||||
@@ -672,11 +709,12 @@ pub(crate) mod test_fixtures {
|
||||
.as_object()
|
||||
.cloned()
|
||||
.unwrap();
|
||||
Ok(ListToolsResult::with_all_items(vec![Tool::new(
|
||||
"dup",
|
||||
"Duplicate-named tool",
|
||||
schema,
|
||||
)]))
|
||||
Ok(ListToolsResult::with_all_items(
|
||||
self.tool_names
|
||||
.iter()
|
||||
.map(|name| Tool::new(*name, "Fixture tool", schema.clone()))
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
async fn call_tool(
|
||||
@@ -703,6 +741,9 @@ pub(crate) mod test_fixtures {
|
||||
if self.fail_resource_listings {
|
||||
return Err(ErrorData::internal_error("resource listing exploded", None));
|
||||
}
|
||||
if self.empty_resource_listings {
|
||||
return Ok(ListResourcesResult::with_all_items(vec![]));
|
||||
}
|
||||
Ok(ListResourcesResult::with_all_items(vec![
|
||||
Resource::new("dup", "dup-resource")
|
||||
.with_description("Duplicate-named resource")
|
||||
@@ -720,9 +761,12 @@ pub(crate) mod test_fixtures {
|
||||
_request: Option<PaginatedRequestParams>,
|
||||
_context: RequestContext<RoleServer>,
|
||||
) -> Result<ListResourceTemplatesResult, ErrorData> {
|
||||
if self.fail_resource_listings {
|
||||
if self.fail_resource_listings || self.fail_template_listings {
|
||||
return Err(ErrorData::internal_error("template listing exploded", None));
|
||||
}
|
||||
if self.empty_resource_listings {
|
||||
return Ok(ListResourceTemplatesResult::with_all_items(vec![]));
|
||||
}
|
||||
Ok(ListResourceTemplatesResult::with_all_items(vec![
|
||||
ResourceTemplate::new("file:///{path}/{name}", "file-template")
|
||||
.with_description("Read a file")
|
||||
@@ -778,6 +822,9 @@ pub(crate) mod test_fixtures {
|
||||
if self.fail_prompt_listings {
|
||||
return Err(ErrorData::internal_error("prompt listing exploded", None));
|
||||
}
|
||||
if self.empty_prompt_listings {
|
||||
return Ok(ListPromptsResult::with_all_items(vec![]));
|
||||
}
|
||||
let mut prompts = vec![Prompt::new(
|
||||
"summarize",
|
||||
Some("Summarize a document"),
|
||||
@@ -869,6 +916,7 @@ mod tests {
|
||||
FIXTURE_ANNOTATED_URI, FixtureServer, add_fixture_server, fixture_runtime,
|
||||
};
|
||||
use super::*;
|
||||
use crate::config::mcp_tool_policy::LayerSource;
|
||||
use crate::function::ToolCall;
|
||||
use log::{Level, LevelFilter, Log, Metadata, Record};
|
||||
use std::sync::atomic::Ordering;
|
||||
@@ -1643,4 +1691,157 @@ mod tests {
|
||||
assert_eq!(prompt, "summarize");
|
||||
assert_eq!(typed_keys, vec!["path".to_string()]);
|
||||
}
|
||||
|
||||
fn single_layer_filter(source: LayerSource, patterns: &[&str]) -> ToolFilter {
|
||||
let mut filter = ToolFilter::default();
|
||||
filter.push_layer(
|
||||
source,
|
||||
&patterns.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
|
||||
);
|
||||
filter
|
||||
}
|
||||
|
||||
fn deny_all_filter() -> ToolFilter {
|
||||
single_layer_filter(LayerSource::Global, &[])
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn catalog_items_drops_filtered_tools_but_keeps_other_kinds() {
|
||||
let fixture = FixtureServer {
|
||||
resources_capability: true,
|
||||
prompts_capability: true,
|
||||
..Default::default()
|
||||
};
|
||||
let (mut runtime, _server) = fixture_runtime(fixture).await;
|
||||
runtime
|
||||
.tool_filters
|
||||
.insert("fixture".to_string(), deny_all_filter());
|
||||
|
||||
let items = runtime.catalog_items("fixture").await.unwrap();
|
||||
|
||||
assert!(!items.contains_key("tool:dup"));
|
||||
assert!(items.contains_key("resource:dup"));
|
||||
assert!(items.contains_key("resource_template:file:///{path}/{name}"));
|
||||
assert!(items.contains_key("prompt:summarize"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn catalog_items_keeps_tools_the_filter_allows() {
|
||||
let (mut runtime, _server) = fixture_runtime(FixtureServer::default()).await;
|
||||
runtime.tool_filters.insert(
|
||||
"fixture".to_string(),
|
||||
single_layer_filter(LayerSource::Global, &["d*"]),
|
||||
);
|
||||
|
||||
let items = runtime.catalog_items("fixture").await.unwrap();
|
||||
|
||||
assert!(items.contains_key("tool:dup"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn search_never_surfaces_filtered_tools() {
|
||||
let fixture = FixtureServer {
|
||||
resources_capability: true,
|
||||
..Default::default()
|
||||
};
|
||||
let (mut runtime, _server) = fixture_runtime(fixture).await;
|
||||
runtime
|
||||
.tool_filters
|
||||
.insert("fixture".to_string(), deny_all_filter());
|
||||
|
||||
let results = runtime.search("fixture", "dup", 10).await.unwrap();
|
||||
|
||||
assert!(
|
||||
results
|
||||
.iter()
|
||||
.all(|item| item.kind != CatalogItemKind::Tool)
|
||||
);
|
||||
assert!(
|
||||
results
|
||||
.iter()
|
||||
.any(|item| item.kind == CatalogItemKind::Resource)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn describe_blocked_tool_is_indistinguishable_from_missing() {
|
||||
let (unfiltered, _server) = fixture_runtime(FixtureServer::default()).await;
|
||||
let missing = unfiltered
|
||||
.describe("fixture", "tool", "ghost")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
|
||||
let (mut filtered, _other_server) = fixture_runtime(FixtureServer::default()).await;
|
||||
filtered
|
||||
.tool_filters
|
||||
.insert("fixture".to_string(), deny_all_filter());
|
||||
let blocked = filtered
|
||||
.describe("fixture", "tool", "dup")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
|
||||
assert_eq!(blocked, "dup not found in fixture MCP server catalog");
|
||||
assert_eq!(blocked, missing.replace("ghost", "dup"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invoke_blocked_tool_errors_like_describe_and_never_reaches_server() {
|
||||
let fixture = FixtureServer::default();
|
||||
let call_tool_calls = Arc::clone(&fixture.call_tool_calls);
|
||||
let (mut runtime, _server) = fixture_runtime(fixture).await;
|
||||
runtime
|
||||
.tool_filters
|
||||
.insert("fixture".to_string(), deny_all_filter());
|
||||
|
||||
let invoke_err = runtime
|
||||
.invoke("fixture", "dup", json!({}))
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
let describe_err = runtime
|
||||
.describe("fixture", "tool", "dup")
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
|
||||
assert_eq!(invoke_err, "dup not found in fixture MCP server catalog");
|
||||
assert_eq!(invoke_err, describe_err);
|
||||
assert_eq!(call_tool_calls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invoke_allowed_tool_still_reaches_the_server() {
|
||||
let fixture = FixtureServer::default();
|
||||
let call_tool_calls = Arc::clone(&fixture.call_tool_calls);
|
||||
let (mut runtime, _server) = fixture_runtime(fixture).await;
|
||||
runtime.tool_filters.insert(
|
||||
"fixture".to_string(),
|
||||
single_layer_filter(LayerSource::Global, &["d*"]),
|
||||
);
|
||||
|
||||
let _ = runtime.invoke("fixture", "dup", json!({})).await;
|
||||
|
||||
assert_eq!(call_tool_calls.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn catalog_items_warns_on_dead_context_patterns() {
|
||||
install_warn_collector();
|
||||
let (mut runtime, _server) = fixture_runtime(FixtureServer::default()).await;
|
||||
let mut filter = single_layer_filter(LayerSource::Global, &["*"]);
|
||||
filter.push_layer(LayerSource::Session, &["zzz_*".to_string()]);
|
||||
runtime.tool_filters.insert("fixture".to_string(), filter);
|
||||
|
||||
runtime.catalog_items("fixture").await.unwrap();
|
||||
|
||||
let messages = warn_messages().lock().unwrap();
|
||||
assert!(
|
||||
messages.iter().any(|msg| msg.contains("'zzz_*'")
|
||||
&& msg.contains("session (.set)")
|
||||
&& msg.contains("'fixture'")),
|
||||
"missing dead-pattern warning in: {messages:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,7 +70,9 @@ fn normalize_version(requested: Option<String>) -> Option<String> {
|
||||
|
||||
fn preferred_update_target() -> Option<&'static str> {
|
||||
match (env::consts::OS, env::consts::ARCH) {
|
||||
("linux", "x86_64") if cfg!(target_env = "gnu") => Some("x86_64-unknown-linux-gnu"),
|
||||
("linux", "x86_64") => Some("x86_64-unknown-linux-musl"),
|
||||
("linux", "aarch64") if cfg!(target_env = "gnu") => Some("aarch64-unknown-linux-gnu"),
|
||||
("linux", "aarch64") => Some("aarch64-unknown-linux-musl"),
|
||||
_ => None,
|
||||
}
|
||||
|
||||
@@ -686,6 +686,7 @@ pub async fn run_agent_for_graph(
|
||||
sync_agent_functions_to_ctx(&mut child_ctx)?;
|
||||
} else {
|
||||
populate_agent_mcp_runtime(&mut child_ctx, &agent_mcp_servers).await?;
|
||||
child_ctx.refresh_mcp_tool_filters();
|
||||
sync_agent_functions_to_ctx(&mut child_ctx)?;
|
||||
child_ctx.init_agent_shared_variables()?;
|
||||
}
|
||||
@@ -869,6 +870,7 @@ async fn handle_spawn(ctx: &mut RequestContext, args: &Value) -> Result<Value> {
|
||||
sync_agent_functions_to_ctx(&mut child_ctx)?;
|
||||
} else {
|
||||
populate_agent_mcp_runtime(&mut child_ctx, &agent_mcp_servers).await?;
|
||||
child_ctx.refresh_mcp_tool_filters();
|
||||
sync_agent_functions_to_ctx(&mut child_ctx)?;
|
||||
child_ctx.init_agent_shared_variables()?;
|
||||
}
|
||||
@@ -1604,6 +1606,7 @@ mod tests {
|
||||
use crate::config::test_fixtures::{FixtureServer, fixture_runtime};
|
||||
use crate::config::{AgentConfig, AppState, WorkingMode};
|
||||
use crate::function::jobs::RingBuf;
|
||||
use crate::mcp::{McpServer, McpServersConfig, McpTransportType};
|
||||
use crate::supervisor::escalation::{EscalationQueue, EscalationRequest};
|
||||
use crate::supervisor::{JobHandle, JobResult, JobState, JobStatus};
|
||||
use parking_lot::Mutex;
|
||||
@@ -1791,6 +1794,61 @@ mod tests {
|
||||
assert!(!functions.contains("mcp_invoke_fixture"));
|
||||
}
|
||||
|
||||
fn app_state_with_fixture_mcp_config() -> Arc<AppState> {
|
||||
let mut state = AppState::test_default();
|
||||
state.mcp_config = Some(McpServersConfig {
|
||||
mcp_servers: [(
|
||||
"fixture".to_string(),
|
||||
McpServer {
|
||||
transport_type: McpTransportType::Stdio,
|
||||
command: Some("echo".to_string()),
|
||||
args: None,
|
||||
env: None,
|
||||
cwd: None,
|
||||
url: None,
|
||||
headers: None,
|
||||
oauth: None,
|
||||
allowed_tools: None,
|
||||
},
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
});
|
||||
Arc::new(state)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn spawned_child_runtime_enforces_child_agent_filters() {
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
let config = AgentConfig {
|
||||
mcp_tools: Some(IndexMap::from([(
|
||||
"fixture".to_string(),
|
||||
vec!["get_*".to_string()],
|
||||
)])),
|
||||
..Default::default()
|
||||
};
|
||||
let mut ctx = RequestContext::new(app_state_with_fixture_mcp_config(), WorkingMode::Cmd);
|
||||
ctx.agent = Some(Agent::test_new(config));
|
||||
let fixture = FixtureServer::default();
|
||||
let call_tool_calls = Arc::clone(&fixture.call_tool_calls);
|
||||
let (runtime, _server) = fixture_runtime(fixture).await;
|
||||
ctx.tool_scope.mcp_runtime = runtime;
|
||||
|
||||
populate_agent_mcp_runtime(&mut ctx, &[]).await.unwrap();
|
||||
ctx.refresh_mcp_tool_filters();
|
||||
|
||||
let err = ctx
|
||||
.tool_scope
|
||||
.mcp_runtime
|
||||
.invoke("fixture", "dup", json!({}))
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert_eq!(err, "dup not found in fixture MCP server catalog");
|
||||
assert_eq!(call_tool_calls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handle_list_running_empty_supervisor() {
|
||||
let mut ctx = ctx_with_supervisor(4, 3);
|
||||
|
||||
+44
-3
@@ -363,9 +363,6 @@ fn whitelist_rejection(tool: &str) -> Option<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a declared tool could be run as a background job. This is the
|
||||
/// declare-side twin of `whitelist_rejection`: a tool is backgroundable
|
||||
/// exactly when `job__start` would not reject it by name.
|
||||
pub fn is_backgroundable_tool(tool: &str) -> bool {
|
||||
whitelist_rejection(tool).is_none()
|
||||
}
|
||||
@@ -457,6 +454,11 @@ async fn handle_start(ctx: &mut RequestContext, args: &Value) -> Result<Value> {
|
||||
.unwrap_or_else(|| json!({}));
|
||||
let mut mcp_runtime = McpRuntime::new();
|
||||
mcp_runtime.insert(server.clone(), Arc::clone(server_handle));
|
||||
if let Some(filter) = ctx.tool_scope.mcp_runtime.tool_filters.get(&server) {
|
||||
mcp_runtime
|
||||
.tool_filters
|
||||
.insert(server.clone(), filter.clone());
|
||||
}
|
||||
let job_ctx = JobCtx {
|
||||
mcp_runtime,
|
||||
current_depth: ctx.current_depth,
|
||||
@@ -1263,7 +1265,9 @@ fn tail_chars(text: &str, max_chars: usize) -> Option<String> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::config::test_fixtures::{FixtureServer, fixture_runtime};
|
||||
use crate::config::{AppConfig, AppState, WorkingMode};
|
||||
use crate::config::{LayerSource, ToolFilter};
|
||||
use crate::function::agents::{
|
||||
GuardrailAction, check_pending_tasks_guardrail, handle_agent_tool,
|
||||
};
|
||||
@@ -1697,6 +1701,43 @@ mod tests {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn job_runtime_carries_the_servers_tool_filter() {
|
||||
run_async(async {
|
||||
let mut ctx = plain_ctx();
|
||||
ctx.declared_function_names
|
||||
.insert("mcp_invoke_fixture".into());
|
||||
let fixture = FixtureServer::default();
|
||||
let call_tool_calls = Arc::clone(&fixture.call_tool_calls);
|
||||
let (mut runtime, _server) = fixture_runtime(fixture).await;
|
||||
let mut filter = ToolFilter::default();
|
||||
filter.push_layer(LayerSource::Global, &[]);
|
||||
runtime.tool_filters.insert("fixture".to_string(), filter);
|
||||
ctx.tool_scope.mcp_runtime = runtime;
|
||||
|
||||
let started = handle_start(
|
||||
&mut ctx,
|
||||
&json!({"tool": "mcp_invoke_fixture", "arguments": {"tool": "dup"}}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id = started["job_id"].as_str().unwrap().to_string();
|
||||
|
||||
let collected = handle_collect(&ctx, &json!({"id": job_id})).await.unwrap();
|
||||
|
||||
assert_eq!(collected["status"], "failed");
|
||||
assert!(
|
||||
collected["error"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("dup not found in fixture MCP server catalog"),
|
||||
"unexpected error: {}",
|
||||
collected["error"]
|
||||
);
|
||||
assert_eq!(call_tool_calls.load(std::sync::atomic::Ordering::SeqCst), 0);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handle_start_rejects_unconnected_mcp_server() {
|
||||
let mut ctx = plain_ctx();
|
||||
|
||||
+262
-111
@@ -214,6 +214,57 @@ fn tool_source_stems() -> Result<HashSet<String>> {
|
||||
Ok(stems)
|
||||
}
|
||||
|
||||
fn all_tool_source_files() -> Result<Vec<String>> {
|
||||
let tools_dir = paths::global_tools_dir();
|
||||
if !tools_dir.exists() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let mut file_names = Vec::new();
|
||||
for entry in fs::read_dir(&tools_dir)? {
|
||||
let path = entry?.path();
|
||||
if path.is_file()
|
||||
&& let Some(name) = path.file_name().and_then(OsStr::to_str)
|
||||
{
|
||||
file_names.push(name.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(dedupe_tool_files_by_stem(file_names))
|
||||
}
|
||||
|
||||
fn dedupe_tool_files_by_stem(file_names: Vec<String>) -> Vec<String> {
|
||||
fn extension_rank(name: &str) -> Option<usize> {
|
||||
let ext = Path::new(name).extension().and_then(OsStr::to_str)?;
|
||||
match Language::from_extension(ext) {
|
||||
Language::Bash => Some(0),
|
||||
Language::Python => Some(1),
|
||||
Language::TypeScript => Some(2),
|
||||
Language::Unsupported => None,
|
||||
}
|
||||
}
|
||||
|
||||
let mut best: HashMap<String, (usize, String)> = HashMap::new();
|
||||
for name in file_names {
|
||||
let Some(rank) = extension_rank(&name) else {
|
||||
continue;
|
||||
};
|
||||
let Some(stem) = Path::new(&name).file_stem().and_then(OsStr::to_str) else {
|
||||
continue;
|
||||
};
|
||||
match best.get(stem) {
|
||||
Some((best_rank, _)) if *best_rank <= rank => {}
|
||||
_ => {
|
||||
best.insert(stem.to_string(), (rank, name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut files: Vec<String> = best.into_values().map(|(_, name)| name).collect();
|
||||
files.sort();
|
||||
files
|
||||
}
|
||||
|
||||
fn bin_entry_stem(file_name: &str) -> &str {
|
||||
let name = file_name.strip_prefix("run-").unwrap_or(file_name);
|
||||
Path::new(name)
|
||||
@@ -587,18 +638,23 @@ impl Functions {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn init(visible_tools: &[String]) -> Result<Self> {
|
||||
pub fn init(visible_tools: Option<&[String]>) -> Result<Self> {
|
||||
Self::remove_stale_global_function_binaries()?;
|
||||
|
||||
let (visible_tools, lenient) = match visible_tools {
|
||||
Some(tools) => (tools.to_vec(), false),
|
||||
None => (all_tool_source_files()?, true),
|
||||
};
|
||||
|
||||
let declarations = Self {
|
||||
declarations: Self::build_global_tool_declarations(visible_tools)?,
|
||||
declarations: Self::build_global_tool_declarations(&visible_tools, lenient)?,
|
||||
};
|
||||
|
||||
info!(
|
||||
"Building global function binaries in {}",
|
||||
paths::functions_bin_dir().display()
|
||||
);
|
||||
Self::build_global_function_binaries(visible_tools, None)?;
|
||||
Self::build_global_function_binaries(&visible_tools, None, lenient)?;
|
||||
|
||||
Ok(declarations)
|
||||
}
|
||||
@@ -608,13 +664,13 @@ impl Functions {
|
||||
|
||||
let global_tools_declarations = if !global_tools.is_empty() {
|
||||
info!("Loading global tools for agent: {name}: {global_tools:?}");
|
||||
let tools_declarations = Self::build_global_tool_declarations(global_tools)?;
|
||||
let tools_declarations = Self::build_global_tool_declarations(global_tools, false)?;
|
||||
|
||||
info!(
|
||||
"Building global function binaries required by agent: {name} in {}",
|
||||
paths::functions_bin_dir().display()
|
||||
);
|
||||
Self::build_global_function_binaries(global_tools, Some(name))?;
|
||||
Self::build_global_function_binaries(global_tools, Some(name), false)?;
|
||||
tools_declarations
|
||||
} else {
|
||||
debug!("No global tools found for agent: {}", name);
|
||||
@@ -964,13 +1020,17 @@ impl Functions {
|
||||
|
||||
fn build_global_tool_declarations(
|
||||
enabled_tools: &[String],
|
||||
lenient: bool,
|
||||
) -> Result<Vec<FunctionDeclaration>> {
|
||||
let global_tools_directory = paths::global_tools_dir();
|
||||
let mut function_declarations = Vec::new();
|
||||
|
||||
for tool in enabled_tools {
|
||||
let declaration = Self::generate_declarations(&global_tools_directory.join(tool))?;
|
||||
function_declarations.extend(declaration);
|
||||
match Self::generate_declarations(&global_tools_directory.join(tool)) {
|
||||
Ok(declaration) => function_declarations.extend(declaration),
|
||||
Err(err) if lenient => warn!("Skipping tool {tool}: {err}"),
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(function_declarations)
|
||||
@@ -1032,41 +1092,50 @@ impl Functions {
|
||||
fn build_global_function_binaries(
|
||||
enabled_tools: &[String],
|
||||
agent_name: Option<&str>,
|
||||
lenient: bool,
|
||||
) -> Result<()> {
|
||||
for tool in enabled_tools {
|
||||
let language = Language::from(
|
||||
&Path::new(&tool)
|
||||
.extension()
|
||||
.and_then(OsStr::to_str)
|
||||
.map(|s| s.to_lowercase())
|
||||
.ok_or_else(|| {
|
||||
anyhow::format_err!("Unable to extract file extension from path: {tool:?}")
|
||||
})?,
|
||||
);
|
||||
let binary_name = Path::new(&tool)
|
||||
.file_stem()
|
||||
.and_then(OsStr::to_str)
|
||||
.ok_or_else(|| {
|
||||
anyhow::format_err!("Unable to extract file name from path: {tool:?}")
|
||||
})?;
|
||||
|
||||
if language == Language::Unsupported {
|
||||
bail!("Unsupported tool file extension: {}", language.as_ref());
|
||||
match Self::build_global_function_binary(tool, agent_name) {
|
||||
Ok(()) => {}
|
||||
Err(err) if lenient => warn!("Skipping binary for tool {tool}: {err}"),
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
|
||||
let tool_path = paths::global_tools_dir().join(tool);
|
||||
let custom_runtime = extract_shebang_runtime(&tool_path);
|
||||
Self::build_binaries(
|
||||
binary_name,
|
||||
language,
|
||||
BinaryType::Tool(agent_name),
|
||||
custom_runtime.as_deref(),
|
||||
)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn build_global_function_binary(tool: &str, agent_name: Option<&str>) -> Result<()> {
|
||||
let language = Language::from(
|
||||
&Path::new(tool)
|
||||
.extension()
|
||||
.and_then(OsStr::to_str)
|
||||
.map(|s| s.to_lowercase())
|
||||
.ok_or_else(|| {
|
||||
anyhow::format_err!("Unable to extract file extension from path: {tool:?}")
|
||||
})?,
|
||||
);
|
||||
let binary_name = Path::new(tool)
|
||||
.file_stem()
|
||||
.and_then(OsStr::to_str)
|
||||
.ok_or_else(|| {
|
||||
anyhow::format_err!("Unable to extract file name from path: {tool:?}")
|
||||
})?;
|
||||
|
||||
if language == Language::Unsupported {
|
||||
bail!("Unsupported tool file extension: {}", language.as_ref());
|
||||
}
|
||||
|
||||
let tool_path = paths::global_tools_dir().join(tool);
|
||||
let custom_runtime = extract_shebang_runtime(&tool_path);
|
||||
Self::build_binaries(
|
||||
binary_name,
|
||||
language,
|
||||
BinaryType::Tool(agent_name),
|
||||
custom_runtime.as_deref(),
|
||||
)
|
||||
}
|
||||
|
||||
fn remove_stale_agent_bin_entries(name: &str) -> Result<()> {
|
||||
let agent_bin_directory = paths::agent_bin_dir(name);
|
||||
|
||||
@@ -1106,6 +1175,35 @@ impl Functions {
|
||||
Self::build_binaries(name, language, BinaryType::Agent, custom_runtime.as_deref())
|
||||
}
|
||||
|
||||
fn render_shim_template(
|
||||
content_template: &str,
|
||||
binary_name: &str,
|
||||
binary_type: &BinaryType,
|
||||
) -> String {
|
||||
let functions_dir_env = get_env_name("functions_dir");
|
||||
match binary_type {
|
||||
BinaryType::Tool(None) => content_template
|
||||
.replace("{function_name}", binary_name)
|
||||
.replace("{root_dir_env}", &functions_dir_env)
|
||||
.replace("{root_dir_rel}", "..")
|
||||
.replace("{functions_dir_rel}", ".."),
|
||||
BinaryType::Tool(Some(agent_name)) => content_template
|
||||
.replace("{function_name}", binary_name)
|
||||
.replace(
|
||||
"{root_dir_env}",
|
||||
&format!("{}_DATA_DIR", normalize_env_name(agent_name)),
|
||||
)
|
||||
.replace("{root_dir_rel}", "..")
|
||||
.replace("{functions_dir_rel}", "../../../functions"),
|
||||
BinaryType::Agent => content_template
|
||||
.replace("{agent_name}", binary_name)
|
||||
.replace("{root_dir_env}", &get_env_name("config_dir"))
|
||||
.replace("{root_dir_rel}", "../../..")
|
||||
.replace("{functions_dir_rel}", "../../../functions"),
|
||||
}
|
||||
.replace("{functions_dir_env}", &functions_dir_env)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn build_binaries(
|
||||
binary_name: &str,
|
||||
@@ -1149,41 +1247,7 @@ impl Functions {
|
||||
)
|
||||
})?;
|
||||
let content_template = unsafe { std::str::from_utf8_unchecked(&embedded_file.data) };
|
||||
let to_script_path = |p: &str| -> String { p.replace('\\', "/") };
|
||||
let content = match binary_type {
|
||||
BinaryType::Tool(None) => {
|
||||
let root_dir = paths::functions_dir();
|
||||
let tool_path = format!(
|
||||
"{}/{binary_name}",
|
||||
paths::global_tools_dir().to_string_lossy()
|
||||
);
|
||||
content_template
|
||||
.replace("{function_name}", binary_name)
|
||||
.replace("{root_dir}", &to_script_path(&root_dir.to_string_lossy()))
|
||||
.replace("{tool_path}", &to_script_path(&tool_path))
|
||||
}
|
||||
BinaryType::Tool(Some(agent_name)) => {
|
||||
let root_dir = paths::agent_data_dir(agent_name);
|
||||
let tool_path = format!(
|
||||
"{}/{binary_name}",
|
||||
paths::global_tools_dir().to_string_lossy()
|
||||
);
|
||||
content_template
|
||||
.replace("{function_name}", binary_name)
|
||||
.replace("{root_dir}", &to_script_path(&root_dir.to_string_lossy()))
|
||||
.replace("{tool_path}", &to_script_path(&tool_path))
|
||||
}
|
||||
BinaryType::Agent => content_template
|
||||
.replace("{agent_name}", binary_name)
|
||||
.replace(
|
||||
"{config_dir}",
|
||||
&to_script_path(&paths::config_dir().to_string_lossy()),
|
||||
),
|
||||
}
|
||||
.replace(
|
||||
"{prompt_utils_file}",
|
||||
&to_script_path(&paths::bash_prompt_utils_file().to_string_lossy()),
|
||||
);
|
||||
let content = Self::render_shim_template(content_template, binary_name, &binary_type);
|
||||
write_file_atomic(&binary_script_file, &content, None)?;
|
||||
|
||||
info!(
|
||||
@@ -1229,21 +1293,17 @@ impl Functions {
|
||||
_ => bail!("Unsupported language: {}", language.as_ref()),
|
||||
}
|
||||
};
|
||||
let bin_dir = binary_file
|
||||
.parent()
|
||||
.expect("Failed to get parent directory of binary file");
|
||||
let canonical_bin_dir = dunce::canonicalize(bin_dir)?.to_string_lossy().into_owned();
|
||||
let wrapper_binary = dunce::canonicalize(&binary_script_file)?
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
// %~dp0 (the .cmd's own directory) keeps the launcher relocatable: no
|
||||
// absolute paths may be baked into it (see render_shim_template).
|
||||
let script_name = format!("run-{binary_name}.{}", language.to_extension());
|
||||
let content = formatdoc!(
|
||||
r#"
|
||||
@echo off
|
||||
setlocal
|
||||
|
||||
set "bin_dir={canonical_bin_dir}"
|
||||
set "bin_dir=%~dp0"
|
||||
|
||||
{run} "{wrapper_binary}" %*"#,
|
||||
{run} "%~dp0{script_name}" %*"#,
|
||||
);
|
||||
|
||||
write_file_atomic(&binary_file, &content, None)?;
|
||||
@@ -1283,37 +1343,7 @@ impl Functions {
|
||||
)
|
||||
})?;
|
||||
let content_template = unsafe { std::str::from_utf8_unchecked(&embedded_file.data) };
|
||||
let mut content = match binary_type {
|
||||
BinaryType::Tool(None) => {
|
||||
let root_dir = paths::functions_dir();
|
||||
let tool_path = format!(
|
||||
"{}/{binary_name}",
|
||||
paths::global_tools_dir().to_string_lossy()
|
||||
);
|
||||
content_template
|
||||
.replace("{function_name}", binary_name)
|
||||
.replace("{root_dir}", &root_dir.to_string_lossy())
|
||||
.replace("{tool_path}", &tool_path)
|
||||
}
|
||||
BinaryType::Tool(Some(agent_name)) => {
|
||||
let root_dir = paths::agent_data_dir(agent_name);
|
||||
let tool_path = format!(
|
||||
"{}/{binary_name}",
|
||||
paths::global_tools_dir().to_string_lossy()
|
||||
);
|
||||
content_template
|
||||
.replace("{function_name}", binary_name)
|
||||
.replace("{root_dir}", &root_dir.to_string_lossy())
|
||||
.replace("{tool_path}", &tool_path)
|
||||
}
|
||||
BinaryType::Agent => content_template
|
||||
.replace("{agent_name}", binary_name)
|
||||
.replace("{config_dir}", &paths::config_dir().to_string_lossy()),
|
||||
}
|
||||
.replace(
|
||||
"{prompt_utils_file}",
|
||||
&paths::bash_prompt_utils_file().to_string_lossy(),
|
||||
);
|
||||
let mut content = Self::render_shim_template(content_template, binary_name, &binary_type);
|
||||
|
||||
if let Some(rt) = custom_runtime
|
||||
&& let Some(newline_pos) = content.find('\n')
|
||||
@@ -1329,9 +1359,10 @@ impl Functions {
|
||||
write_file_atomic(&script_file, &content, Some(0o755))?;
|
||||
|
||||
let ts_runtime = custom_runtime.unwrap_or("tsx");
|
||||
// Locate the script next to the wrapper at run time instead of
|
||||
// baking an absolute path (see render_shim_template).
|
||||
let wrapper = format!(
|
||||
"#!/bin/sh\nexec {ts_runtime} \"{}\" \"$@\"\n",
|
||||
script_file.display()
|
||||
"#!/bin/sh\nexec {ts_runtime} \"$(dirname \"$0\")/run-{binary_name}.ts\" \"$@\"\n",
|
||||
);
|
||||
write_file_atomic(&binary_file, &wrapper, Some(0o755))?;
|
||||
} else {
|
||||
@@ -2603,6 +2634,35 @@ mod tests {
|
||||
use std::sync::Arc;
|
||||
use std::{mem, process};
|
||||
|
||||
#[test]
|
||||
fn dedupe_tool_files_prefers_sh_over_py_over_ts() {
|
||||
let files = vec![
|
||||
"get_current_weather.ts".to_string(),
|
||||
"get_current_weather.py".to_string(),
|
||||
"get_current_weather.sh".to_string(),
|
||||
"fetch.ts".to_string(),
|
||||
"fetch.py".to_string(),
|
||||
"demo_ts.ts".to_string(),
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
dedupe_tool_files_by_stem(files),
|
||||
vec!["demo_ts.ts", "fetch.py", "get_current_weather.sh"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dedupe_tool_files_skips_unsupported_extensions() {
|
||||
let files = vec![
|
||||
"notes.md".to_string(),
|
||||
"tool.sh".to_string(),
|
||||
"README".to_string(),
|
||||
"archive.tar.gz".to_string(),
|
||||
];
|
||||
|
||||
assert_eq!(dedupe_tool_files_by_stem(files), vec!["tool.sh"]);
|
||||
}
|
||||
|
||||
fn call(name: &str, id: Option<&str>) -> ToolCall {
|
||||
ToolCall::new(name.to_string(), json!({}), id.map(|s| s.to_string()))
|
||||
}
|
||||
@@ -4515,6 +4575,97 @@ mod tests {
|
||||
fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
#[serial]
|
||||
fn built_shims_resolve_paths_at_runtime_after_relocation() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let root = temp_file("-shim-relocate-", "");
|
||||
let home_a = root.join("home-a");
|
||||
let config_a = home_a.join("coyote");
|
||||
let tools_dir = config_a.join("functions").join("tools");
|
||||
fs::create_dir_all(&tools_dir).unwrap();
|
||||
fs::create_dir_all(config_a.join("functions").join("bin")).unwrap();
|
||||
let tool_src = tools_dir.join("relocheck.sh");
|
||||
fs::write(
|
||||
&tool_src,
|
||||
"#!/usr/bin/env bash\necho \"relocated-ok\" >> \"$LLM_OUTPUT\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::set_permissions(&tool_src, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let config_env = get_env_name("config_dir");
|
||||
let functions_env = get_env_name("functions_dir");
|
||||
let saved_config = env::var(&config_env).ok();
|
||||
let saved_functions = env::var(&functions_env).ok();
|
||||
unsafe {
|
||||
env::set_var(&config_env, &config_a);
|
||||
env::remove_var(&functions_env);
|
||||
}
|
||||
|
||||
let build_result = Functions::build_global_function_binary("relocheck.sh", None);
|
||||
|
||||
unsafe {
|
||||
match saved_config {
|
||||
Some(v) => env::set_var(&config_env, v),
|
||||
None => env::remove_var(&config_env),
|
||||
}
|
||||
match saved_functions {
|
||||
Some(v) => env::set_var(&functions_env, v),
|
||||
None => env::remove_var(&functions_env),
|
||||
}
|
||||
}
|
||||
build_result.unwrap();
|
||||
|
||||
let shim = config_a.join("functions").join("bin").join("relocheck");
|
||||
let content = fs::read_to_string(&shim).unwrap();
|
||||
assert!(
|
||||
!content.contains(config_a.to_str().unwrap()),
|
||||
"shim must not bake the generation-time config path:\n{content}"
|
||||
);
|
||||
assert!(
|
||||
content.contains(&functions_env),
|
||||
"shim must consult the functions dir env override at run time:\n{content}"
|
||||
);
|
||||
|
||||
// Simulate the config dir landing under a different home directory
|
||||
// (shared/synced config dir, or a sandbox with another $HOME).
|
||||
let home_b = root.join("home-b");
|
||||
fs::rename(&home_a, &home_b).unwrap();
|
||||
let moved_shim = home_b
|
||||
.join("coyote")
|
||||
.join("functions")
|
||||
.join("bin")
|
||||
.join("relocheck");
|
||||
|
||||
if which::which("bash").is_err() || which::which("jq").is_err() {
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
return;
|
||||
}
|
||||
|
||||
let output = process::Command::new(&moved_shim)
|
||||
.arg("{}")
|
||||
.env_remove(&config_env)
|
||||
.env_remove(&functions_env)
|
||||
.env_remove("LLM_OUTPUT")
|
||||
.env_remove("LLM_TOOL_DATA_FILE")
|
||||
.output()
|
||||
.unwrap();
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"relocated shim failed: stderr={} stdout={stdout}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert!(
|
||||
stdout.contains("relocated-ok"),
|
||||
"unexpected output: {stdout}"
|
||||
);
|
||||
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_tool_calls_partitions_mcp_and_sequential_then_resorts() {
|
||||
let mut ctx = RequestContext::new(Arc::new(AppState::test_default()), WorkingMode::Cmd);
|
||||
|
||||
@@ -424,7 +424,7 @@ async fn step(
|
||||
Ok(StepResult::Continue(vec![next]))
|
||||
}
|
||||
NodeType::Llm(llm_node) => {
|
||||
let outcome = LlmNodeExecutor::execute(llm_node, state, ctx).await?;
|
||||
let outcome = LlmNodeExecutor::execute(current, llm_node, state, ctx).await?;
|
||||
let targets = match outcome {
|
||||
LlmExecutionOutcome::Continue => static_next_targets(node, current, "llm")?,
|
||||
LlmExecutionOutcome::FellBack(target) => vec![target],
|
||||
|
||||
+13
-1
@@ -30,11 +30,12 @@ pub struct LlmNodeExecutor;
|
||||
|
||||
impl LlmNodeExecutor {
|
||||
pub(super) async fn execute(
|
||||
node_id: &str,
|
||||
node: &LlmNode,
|
||||
state_manager: &mut StateManager,
|
||||
parent_ctx: &mut RequestContext,
|
||||
) -> Result<LlmExecutionOutcome> {
|
||||
let result = run(node, state_manager, parent_ctx).await;
|
||||
let result = run(node_id, node, state_manager, parent_ctx).await;
|
||||
let (output, failure_reason) = match result {
|
||||
Ok(raw) => match &node.output_schema {
|
||||
Some(schema) => match structured::extract(&raw, schema, parent_ctx).await {
|
||||
@@ -79,6 +80,7 @@ fn outcome_from(
|
||||
}
|
||||
|
||||
async fn run(
|
||||
node_id: &str,
|
||||
node: &LlmNode,
|
||||
state_manager: &mut StateManager,
|
||||
parent_ctx: &mut RequestContext,
|
||||
@@ -177,6 +179,13 @@ async fn run(
|
||||
// Jobs are node-local: everything job__start registers while this node
|
||||
// runs is recorded here and reaped on every exit path below.
|
||||
let saved_job_scope = parent_ctx.node_job_scope.replace(Vec::new());
|
||||
// The node's tool filter layer lives in tracked context state so any
|
||||
// mid-node filter recompute (e.g. a skill load) re-applies it last.
|
||||
let saved_node_mcp_tools = std::mem::replace(
|
||||
&mut parent_ctx.active_node_mcp_tools,
|
||||
node.mcp_tools.clone().map(|map| (node_id.to_string(), map)),
|
||||
);
|
||||
parent_ctx.refresh_mcp_tool_filters();
|
||||
let result = match node.timeout {
|
||||
Some(secs) => match timeout(
|
||||
Duration::from_secs(secs),
|
||||
@@ -193,6 +202,8 @@ async fn run(
|
||||
let node_jobs =
|
||||
std::mem::replace(&mut parent_ctx.node_job_scope, saved_job_scope).unwrap_or_default();
|
||||
reap_jobs(parent_ctx.supervisor.as_ref(), &node_jobs).await;
|
||||
parent_ctx.active_node_mcp_tools = saved_node_mcp_tools;
|
||||
parent_ctx.refresh_mcp_tool_filters();
|
||||
restore_agent_skill_policy(parent_ctx, saved_agent_skill_state);
|
||||
result
|
||||
}
|
||||
@@ -506,6 +517,7 @@ mod tests {
|
||||
instructions: Some("sys".into()),
|
||||
prompt: "user".into(),
|
||||
tools: None,
|
||||
mcp_tools: None,
|
||||
model: None,
|
||||
temperature: None,
|
||||
top_p: None,
|
||||
|
||||
+5
-3
@@ -85,9 +85,11 @@ impl MapNodeExecutor {
|
||||
let mut ctx = sub_ctx;
|
||||
|
||||
let exec_result: Result<()> = match &branch_clone.node_type {
|
||||
NodeType::Llm(n) => LlmNodeExecutor::execute(n, &mut state, &mut ctx)
|
||||
.await
|
||||
.map(|_| ()),
|
||||
NodeType::Llm(n) => {
|
||||
LlmNodeExecutor::execute(&branch_clone.id, n, &mut state, &mut ctx)
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
NodeType::Agent(n) => AgentNodeExecutor::execute(n, &mut state, &mut ctx)
|
||||
.await
|
||||
.map(|_| ()),
|
||||
|
||||
@@ -37,6 +37,9 @@ pub struct Graph {
|
||||
#[serde(default)]
|
||||
pub mcp_servers: Vec<String>,
|
||||
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub mcp_tools: Option<IndexMap<String, Vec<String>>>,
|
||||
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub skills_enabled: Option<bool>,
|
||||
|
||||
@@ -285,6 +288,9 @@ pub struct LlmNode {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tools: Option<Vec<String>>,
|
||||
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub mcp_tools: Option<IndexMap<String, Vec<String>>>,
|
||||
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub model: Option<String>,
|
||||
|
||||
@@ -530,6 +536,47 @@ nodes:
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserializes_mcp_tools_at_graph_and_node_level() {
|
||||
let yaml = r#"
|
||||
name: g
|
||||
mcp_servers: [github]
|
||||
mcp_tools:
|
||||
github:
|
||||
- get_*
|
||||
- list_*
|
||||
start: l
|
||||
nodes:
|
||||
l:
|
||||
id: l
|
||||
type: llm
|
||||
prompt: hi
|
||||
mcp_tools:
|
||||
github:
|
||||
- search_code
|
||||
next: e
|
||||
e:
|
||||
id: e
|
||||
type: end
|
||||
output: done
|
||||
"#;
|
||||
let graph: Graph = serde_yaml::from_str(yaml).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
graph.mcp_tools.as_ref().unwrap().get("github"),
|
||||
Some(&vec!["get_*".to_string(), "list_*".to_string()])
|
||||
);
|
||||
match &graph.get_node("l").unwrap().node_type {
|
||||
NodeType::Llm(llm) => {
|
||||
assert_eq!(
|
||||
llm.mcp_tools.as_ref().unwrap().get("github"),
|
||||
Some(&vec!["search_code".to_string()])
|
||||
);
|
||||
}
|
||||
_ => panic!("expected Llm variant"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserializes_every_node_type() {
|
||||
let yaml = r#"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::state::template_root_keys;
|
||||
use super::types::{Graph, Node, NodeType};
|
||||
use crate::client::{Model, ModelType};
|
||||
use crate::config;
|
||||
use crate::config::{Agent, AppConfig, paths};
|
||||
use crate::rag::{GraphRagConfig, RagData};
|
||||
use anyhow::{Result, bail};
|
||||
@@ -214,6 +215,14 @@ impl GraphValidator {
|
||||
return;
|
||||
};
|
||||
|
||||
let expand_alias =
|
||||
|name: &str| config::expand_mcp_server_alias(&ctx.app_config.mapping_mcp_servers, name);
|
||||
let mut enabled_servers: HashSet<String> = ctx.mcp_servers.clone();
|
||||
for server in &ctx.mcp_servers {
|
||||
enabled_servers.extend(expand_alias(server));
|
||||
}
|
||||
let all_servers_enabled = ctx.mcp_servers.iter().any(|s| s.trim() == "all");
|
||||
|
||||
for (node_id, node) in &graph.nodes {
|
||||
let NodeType::Llm(llm) = &node.node_type else {
|
||||
continue;
|
||||
@@ -237,6 +246,25 @@ impl GraphValidator {
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(mcp_tools) = &llm.mcp_tools
|
||||
&& !all_servers_enabled
|
||||
{
|
||||
for key in mcp_tools.keys() {
|
||||
let enabled = enabled_servers.contains(key)
|
||||
|| expand_alias(key)
|
||||
.iter()
|
||||
.any(|id| enabled_servers.contains(id));
|
||||
if !enabled {
|
||||
result.error(ValidationError::with_node(
|
||||
node_id,
|
||||
format!(
|
||||
"llm node 'mcp_tools' references MCP server '{key}' not enabled by this graph"
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(model_id) = &llm.model
|
||||
&& Model::retrieve_model(ctx.app_config.as_ref(), model_id, ModelType::Chat)
|
||||
.is_err()
|
||||
@@ -1001,6 +1029,7 @@ mod tests {
|
||||
max_concurrent_jobs: None,
|
||||
global_tools: Vec::new(),
|
||||
mcp_servers: Vec::new(),
|
||||
mcp_tools: None,
|
||||
skills_enabled: None,
|
||||
enabled_skills: None,
|
||||
inject_skill_instructions: None,
|
||||
@@ -1099,6 +1128,7 @@ mod tests {
|
||||
instructions: None,
|
||||
prompt: "p".into(),
|
||||
tools: None,
|
||||
mcp_tools: None,
|
||||
model: None,
|
||||
temperature: None,
|
||||
top_p: None,
|
||||
@@ -1257,6 +1287,19 @@ mod tests {
|
||||
node
|
||||
}
|
||||
|
||||
fn llm_node_with_mcp_tools(id: &str, servers: &[&str]) -> Node {
|
||||
let mut node = llm_node(id, None, Some("end"));
|
||||
if let NodeType::Llm(ref mut n) = node.node_type {
|
||||
let mut mcp_tools = IndexMap::new();
|
||||
for server in servers {
|
||||
mcp_tools.insert(server.to_string(), vec!["get_*".to_string()]);
|
||||
}
|
||||
n.mcp_tools = Some(mcp_tools);
|
||||
}
|
||||
|
||||
node
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn llm_node_unknown_tool_is_an_error() {
|
||||
let graph = graph_with(
|
||||
@@ -1340,6 +1383,103 @@ mod tests {
|
||||
assert!(result.is_valid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn llm_node_mcp_tools_enabled_server_passes() {
|
||||
let graph = graph_with(
|
||||
vec![
|
||||
("l", llm_node_with_mcp_tools("l", &["github"])),
|
||||
("end", end_node("end")),
|
||||
],
|
||||
"l",
|
||||
);
|
||||
|
||||
let result = validator()
|
||||
.with_agent_context(agent_ctx(&[], &["github"]))
|
||||
.validate(&graph);
|
||||
|
||||
assert!(result.is_valid());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn llm_node_mcp_tools_unknown_server_is_an_error() {
|
||||
let graph = graph_with(
|
||||
vec![
|
||||
("l", llm_node_with_mcp_tools("l", &["slack"])),
|
||||
("end", end_node("end")),
|
||||
],
|
||||
"l",
|
||||
);
|
||||
|
||||
let result = validator()
|
||||
.with_agent_context(agent_ctx(&[], &["github"]))
|
||||
.validate(&graph);
|
||||
|
||||
assert!(!result.is_valid());
|
||||
assert!(
|
||||
result
|
||||
.errors
|
||||
.iter()
|
||||
.any(|e| e.message.contains("'slack' not enabled"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn llm_node_mcp_tools_alias_key_passes() {
|
||||
let graph = graph_with(
|
||||
vec![
|
||||
("l", llm_node_with_mcp_tools("l", &["gh"])),
|
||||
("end", end_node("end")),
|
||||
],
|
||||
"l",
|
||||
);
|
||||
let mut ctx = agent_ctx(&[], &["github-mcp"]);
|
||||
let mut app = AppConfig::default();
|
||||
app.mapping_mcp_servers
|
||||
.insert("gh".to_string(), "github-mcp".to_string());
|
||||
ctx.app_config = Arc::new(app);
|
||||
|
||||
let result = validator().with_agent_context(ctx).validate(&graph);
|
||||
|
||||
assert!(result.is_valid(), "errors: {:?}", result.errors);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn llm_node_mcp_tools_key_matching_alias_expansion_passes() {
|
||||
let graph = graph_with(
|
||||
vec![
|
||||
("l", llm_node_with_mcp_tools("l", &["github-mcp"])),
|
||||
("end", end_node("end")),
|
||||
],
|
||||
"l",
|
||||
);
|
||||
let mut ctx = agent_ctx(&[], &["gh"]);
|
||||
let mut app = AppConfig::default();
|
||||
app.mapping_mcp_servers
|
||||
.insert("gh".to_string(), "github-mcp".to_string());
|
||||
ctx.app_config = Arc::new(app);
|
||||
|
||||
let result = validator().with_agent_context(ctx).validate(&graph);
|
||||
|
||||
assert!(result.is_valid(), "errors: {:?}", result.errors);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn llm_node_mcp_tools_with_all_sentinel_passes() {
|
||||
let graph = graph_with(
|
||||
vec![
|
||||
("l", llm_node_with_mcp_tools("l", &["github"])),
|
||||
("end", end_node("end")),
|
||||
],
|
||||
"l",
|
||||
);
|
||||
|
||||
let result = validator()
|
||||
.with_agent_context(agent_ctx(&[], &["all"]))
|
||||
.validate(&graph);
|
||||
|
||||
assert!(result.is_valid(), "errors: {:?}", result.errors);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn llm_node_unknown_model_is_an_error() {
|
||||
let graph = graph_with(
|
||||
|
||||
@@ -242,6 +242,7 @@ fn build_stdio(cli: &Cli, has_url: bool) -> Result<McpServer> {
|
||||
url: None,
|
||||
headers: None,
|
||||
oauth: None,
|
||||
allowed_tools: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -300,6 +301,7 @@ fn build_remote(cli: &Cli, transport: McpTransportType, has_command: bool) -> Re
|
||||
url: Some(url),
|
||||
headers: (!headers.is_empty()).then_some(headers),
|
||||
oauth,
|
||||
allowed_tools: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+23
-1
@@ -6,7 +6,7 @@ mod sse_transport;
|
||||
|
||||
use crate::config::AppConfig;
|
||||
use crate::config::paths;
|
||||
use crate::utils::{AbortSignal, abortable_run_with_spinner};
|
||||
use crate::utils::{AbortSignal, abortable_run_with_spinner, dimmed_text};
|
||||
use crate::vault::Vault;
|
||||
use crate::vault::interpolate_secrets;
|
||||
use anyhow::Error;
|
||||
@@ -166,6 +166,8 @@ pub(crate) struct McpServer {
|
||||
pub headers: Option<IndexMap<String, String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub oauth: Option<McpOAuthConfig>,
|
||||
#[serde(rename = "allowedTools", skip_serializing_if = "Option::is_none")]
|
||||
pub allowed_tools: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
impl McpServer {
|
||||
@@ -177,6 +179,15 @@ impl McpServer {
|
||||
}
|
||||
|
||||
pub fn validate(&self, name: &str) -> Result<()> {
|
||||
if let Some(tools) = &self.allowed_tools
|
||||
&& tools.is_empty()
|
||||
{
|
||||
let message = format!(
|
||||
"MCP server '{name}' has an empty \"allowedTools\" list, so none of its tools will be callable"
|
||||
);
|
||||
warn!("{message}");
|
||||
eprintln!("{}", dimmed_text(&message));
|
||||
}
|
||||
if self.is_remote() {
|
||||
let type_label = match self.transport_type {
|
||||
McpTransportType::Http => "http",
|
||||
@@ -802,6 +813,7 @@ mod tests {
|
||||
url: None,
|
||||
headers: None,
|
||||
oauth: None,
|
||||
allowed_tools: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -815,6 +827,7 @@ mod tests {
|
||||
url: Some(url.to_string()),
|
||||
headers: None,
|
||||
oauth: None,
|
||||
allowed_tools: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -828,6 +841,7 @@ mod tests {
|
||||
url: Some(url.to_string()),
|
||||
headers: None,
|
||||
oauth: None,
|
||||
allowed_tools: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -860,6 +874,7 @@ mod tests {
|
||||
url: None,
|
||||
headers: None,
|
||||
oauth: None,
|
||||
allowed_tools: None,
|
||||
};
|
||||
|
||||
let err = spec.validate("test").unwrap_err();
|
||||
@@ -878,6 +893,7 @@ mod tests {
|
||||
url: Some("http://localhost".into()),
|
||||
headers: None,
|
||||
oauth: None,
|
||||
allowed_tools: None,
|
||||
};
|
||||
|
||||
let err = spec.validate("test").unwrap_err();
|
||||
@@ -898,6 +914,7 @@ mod tests {
|
||||
url: None,
|
||||
headers: Some(headers),
|
||||
oauth: None,
|
||||
allowed_tools: None,
|
||||
};
|
||||
|
||||
let err = spec.validate("test").unwrap_err();
|
||||
@@ -923,6 +940,7 @@ mod tests {
|
||||
url: None,
|
||||
headers: None,
|
||||
oauth: None,
|
||||
allowed_tools: None,
|
||||
};
|
||||
|
||||
let err = spec.validate("test").unwrap_err();
|
||||
@@ -941,6 +959,7 @@ mod tests {
|
||||
url: Some("http://localhost".into()),
|
||||
headers: None,
|
||||
oauth: None,
|
||||
allowed_tools: None,
|
||||
};
|
||||
|
||||
let err = spec.validate("test").unwrap_err();
|
||||
@@ -959,6 +978,7 @@ mod tests {
|
||||
url: Some("http://localhost".into()),
|
||||
headers: None,
|
||||
oauth: None,
|
||||
allowed_tools: None,
|
||||
};
|
||||
|
||||
let err = spec.validate("test").unwrap_err();
|
||||
@@ -977,6 +997,7 @@ mod tests {
|
||||
url: Some("http://localhost".into()),
|
||||
headers: None,
|
||||
oauth: None,
|
||||
allowed_tools: None,
|
||||
};
|
||||
|
||||
let err = spec.validate("test").unwrap_err();
|
||||
@@ -1002,6 +1023,7 @@ mod tests {
|
||||
url: None,
|
||||
headers: None,
|
||||
oauth: None,
|
||||
allowed_tools: None,
|
||||
};
|
||||
|
||||
let err = spec.validate("test").unwrap_err();
|
||||
|
||||
+26
-14
@@ -1869,24 +1869,36 @@ fn select_embedding_model(models: &[&Model]) -> Result<String> {
|
||||
}
|
||||
|
||||
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") {
|
||||
#[cfg(target_env = "musl")]
|
||||
{
|
||||
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."
|
||||
"Note: the duckdb RAG driver is only available in GNU builds of coyote \
|
||||
(musl builds are statically linked and cannot load DuckDB extensions). \
|
||||
Using the yaml driver."
|
||||
);
|
||||
Ok("duckdb".to_string())
|
||||
} else {
|
||||
Ok("yaml".to_string())
|
||||
}
|
||||
#[cfg(not(target_env = "musl"))]
|
||||
{
|
||||
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";
|
||||
|
||||
@@ -85,6 +85,21 @@ pub struct DuckDbProvider {
|
||||
}
|
||||
|
||||
impl DuckDbProvider {
|
||||
/// Fail fast on musl builds, before any filesystem or DuckDB work. Coyote's musl
|
||||
/// builds are statically linked, and a statically linked binary cannot dlopen the
|
||||
/// `vss`/`fts` extension shared objects, so this driver can never work there.
|
||||
fn reject_musl() -> Result<()> {
|
||||
#[cfg(target_env = "musl")]
|
||||
bail!(
|
||||
"The duckdb RAG driver is unavailable in this build of coyote: musl builds \
|
||||
are statically linked, and a statically linked binary cannot load DuckDB \
|
||||
extensions like `vss`/`fts` (dlopen is unsupported). Use the `qdrant` RAG \
|
||||
driver instead, or a gnu-libc build of coyote."
|
||||
);
|
||||
#[cfg(not(target_env = "musl"))]
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Open (or create) the DuckDB file. `dim` is the embedding vector dimension,
|
||||
/// supplied by the caller who knows the model.
|
||||
///
|
||||
@@ -95,6 +110,7 @@ impl DuckDbProvider {
|
||||
/// created or initialized here, or lazily through `ensure_writable` on the rebuild
|
||||
/// path.
|
||||
pub fn open(db_path: &Path, dim: usize) -> Result<Self> {
|
||||
Self::reject_musl()?;
|
||||
let (conn, writable) = Self::open_for_workload(db_path, dim)?;
|
||||
// A reopened file may already carry a live FTS index from a previous session,
|
||||
// in which case keyword search works immediately.
|
||||
@@ -173,6 +189,7 @@ impl DuckDbProvider {
|
||||
}
|
||||
|
||||
pub fn introspect_dim(db_path: &Path) -> Result<Option<usize>> {
|
||||
Self::reject_musl()?;
|
||||
if !db_path.exists() {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -819,7 +836,9 @@ impl RagProvider for DuckDbProvider {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
// Not compiled for musl: `open` bails there (statically linked binaries cannot dlopen
|
||||
// the extension shared objects), so every test in this module would fail at setup.
|
||||
#[cfg(all(test, not(target_env = "musl")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::rag::provider::RagProvider;
|
||||
|
||||
+18
-3
@@ -55,7 +55,7 @@ pub const DEFAULT_CONTINUATION_PROMPT: &str = indoc! {"
|
||||
4. Continue with the next pending item now. Call tools immediately."
|
||||
};
|
||||
|
||||
static REPL_COMMANDS: LazyLock<[ReplCommand; 62]> = LazyLock::new(|| {
|
||||
static REPL_COMMANDS: LazyLock<[ReplCommand; 63]> = LazyLock::new(|| {
|
||||
[
|
||||
ReplCommand::new(".help", "Show this help guide", AssertState::pass()),
|
||||
ReplCommand::new(".info", "Show system info", AssertState::pass()),
|
||||
@@ -64,6 +64,11 @@ static REPL_COMMANDS: LazyLock<[ReplCommand; 62]> = LazyLock::new(|| {
|
||||
"Show the list of enabled tools to be passed to the LLM",
|
||||
AssertState::True(StateFlags::FUNCTION_CALLING),
|
||||
),
|
||||
ReplCommand::new(
|
||||
".info mcp-server",
|
||||
"Show an MCP server's tool filters and effective catalog",
|
||||
AssertState::pass(),
|
||||
),
|
||||
ReplCommand::new(
|
||||
".authenticate",
|
||||
"Authenticate the current model client via OAuth (if configured)",
|
||||
@@ -639,6 +644,16 @@ pub async fn run_repl_command(
|
||||
let info = ctx.todo_info()?;
|
||||
print!("{info}");
|
||||
}
|
||||
Some(arg) if arg.starts_with("mcp-server") => {
|
||||
let mut parts = arg.splitn(2, char::is_whitespace);
|
||||
parts.next();
|
||||
let name = parts.next().map(str::trim).unwrap_or("");
|
||||
if name.is_empty() {
|
||||
bail!("Usage: .info mcp-server <server>");
|
||||
}
|
||||
let info = ctx.mcp_server_info(name).await?;
|
||||
print!("{info}");
|
||||
}
|
||||
Some(_) => unknown_command()?,
|
||||
None => {
|
||||
let app = Arc::clone(&ctx.app.config);
|
||||
@@ -1959,8 +1974,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repl_commands_has_62_entries() {
|
||||
assert_eq!(REPL_COMMANDS.len(), 62);
|
||||
fn repl_commands_has_63_entries() {
|
||||
assert_eq!(REPL_COMMANDS.len(), 63);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user