Compare commits
522 Commits
43fbe448cb
..
skills
| Author | SHA1 | Date | |
|---|---|---|---|
| 68a912ec38 | |||
| f405ec5e16 | |||
| b997e9493c | |||
| 8d6e9bef32 | |||
| e54a2e42c9 | |||
| b1696c3425 | |||
| feef3f67b5 | |||
| dc066bee0d | |||
| 6c4e042dad | |||
| 30f3b01358 | |||
| ebf3b5f776 | |||
| 84dcb3078b | |||
| 7b320e08c4 | |||
| 7078280b3d | |||
| 43607dbe8d | |||
| 8f7a57f8e6 | |||
| 40fdf3aaa7 | |||
| 46d4b78ccc | |||
| b0a3b0a9a5 | |||
| 53b3ce9ab1 | |||
| 44f533018e | |||
| bbb23f4884 | |||
| 8de0eef4f9 | |||
| 73a4499c68 | |||
| 97100bee29 | |||
| 9a25438643 | |||
| f6da937c5d | |||
| eeaeb42c9a | |||
| 1dde7f4442 | |||
| 9879980304 | |||
| 7ec81ae607 | |||
| dac2a16677 | |||
| 260bf4e5bc | |||
| ece66448e0 | |||
| a254d60876 | |||
| c36c4f4699 | |||
| 4a14d80d97 | |||
| c6a9268856 | |||
| 2914a1070b | |||
| 5ebf8649a6 | |||
| 0272412334 | |||
| 7a7824be6a | |||
| aa2d4f3265 | |||
| 28a283283f | |||
| 652ab0b180 | |||
| 8ad764527d | |||
| bba094086d | |||
| 658ca7fec3 | |||
| 156de15a33 | |||
| 695a684b8d | |||
| 307e2cfc50 | |||
| ed59f793fc | |||
| c17db05f39 | |||
| b1782b614f | |||
| 2acff31213 | |||
| a564085449 | |||
| 2d5cdb96d2 | |||
| 5a47a6637f | |||
| 625a251931 | |||
| d0ebe7408f | |||
| 976ba7066d | |||
| ff3789f869 | |||
| 744dd213f5 | |||
| f6b4bf05b6 | |||
| 94e3c3535c | |||
| 31b44fbeb7 | |||
| 07f4b134b6 | |||
| 5c374bb5bf | |||
| 0f90dd5f53 | |||
| d07caf2a4b | |||
| 81a2bd1d00 | |||
| 5fa6ffb81d | |||
| 1faab15377 | |||
| a4ddc3d65d | |||
| 588c69ea6c | |||
| bf8dad2a4f | |||
| 2e06c0e7d2 | |||
| de42cae87f | |||
| cdc4bd154a | |||
| aa2e627a5f | |||
| 3359c62429 | |||
| 75a6a5e145 | |||
| a9cad501ff | |||
| 26584c7500 | |||
| 62fdf4a2b5 | |||
| 296aa6f50f | |||
| 93cc498731 | |||
| b1cd8351fa | |||
| ccf5e73341 | |||
| be5d280c32 | |||
| 6633a8c0bf | |||
| 097d8936e3 | |||
| 8a53b7934b | |||
| 0facb15e32 | |||
| c172736362 | |||
| 4a2b9fa42a | |||
| 98db37866c | |||
| ad31fbd169 | |||
| d69e28fd39 | |||
| 279eaa5300 | |||
| e687d78931 | |||
| 0c2e4df647 | |||
| 6221875f64 | |||
| 895b9c27db | |||
| e661ca2eda | |||
| 7066edd904 | |||
| 61bdf29bea | |||
| ef39c7d9ff | |||
| e9e46158e7 | |||
| 34dc4b0dce | |||
| cd226577e7 | |||
| b5fc633454 | |||
| 484b18ef16 | |||
| 7333046cfe | |||
| 815f0e5c39 | |||
| dacccbfcf7 | |||
| 5370637274 | |||
| e6da252a5a | |||
| 4aaff21f45 | |||
| 2678afe02b | |||
| 558b764db8 | |||
| 0bb312a85c | |||
| d81d233527 | |||
| 597f823bdf | |||
| 81c037515e | |||
| 3c7d19da07 | |||
| 4536d00067 | |||
| 98d16d9a56 | |||
| 26de81e84e | |||
| 20c28b55d5 | |||
| 7d6f1dda26 | |||
| 9a061944ae | |||
| 1f50af0974 | |||
| bdacf9fc78 | |||
| a9f2a5edc2 | |||
| 2df8b1a541 | |||
| de055bf8a4 | |||
| 8fb0eece4b | |||
| ba03c3037d | |||
| afa0e4af67 | |||
| 5a9a00bc6f | |||
| e7bb668ac7 | |||
| 04498b96ec | |||
| eb2843d38a | |||
| 696ce03ee4 | |||
| a3d67bfbf7 | |||
| 5bd0766a60 | |||
| 35e1b14843 | |||
| 503c9b4699 | |||
| 7a8b09542d | |||
| da5cd21c1c | |||
| 27fcb1fc15 | |||
| e292c414c5 | |||
| 8a2f18204f | |||
| c70ac98223 | |||
| 249d1fc881 | |||
| 3f4fd91b3f | |||
| 48c52b5829 | |||
| f58f751c59 | |||
| fc7fdc98b4 | |||
| f4d7d0fb73 | |||
| 4b38f53488 | |||
| 186422ff58 | |||
| 9bc4f8b621 | |||
| 84497d3d65 | |||
| 3ea9116a23 | |||
| bfcd73c32a | |||
| 3cd3ba55ff | |||
| 3535edba79 | |||
| bf0343e245 | |||
| b001ae4c18 | |||
| 9ce088a530 | |||
| 16f3f71188 | |||
| 0af5fa02f9 | |||
| d6a0676264 | |||
| b582bab17c | |||
| a8732c63d6 | |||
| 389d0b768f | |||
| 70a251a7e2 | |||
| 462f136596 | |||
| bf9d7d750e | |||
| 540ec648c9 | |||
| e69352ee2d | |||
| ee4e3bc13f | |||
| a576961bd6 | |||
| 59c7fc1276 | |||
| bcf512fcfc | |||
| 195401c496 | |||
| 34d8d20ec6 | |||
| 08ba6f0446 | |||
| 26984892af | |||
| 526a426073 | |||
| c53e0546d4 | |||
| 349b3748bd | |||
| e23e5f9f7b | |||
| 8d02782de6 | |||
| 27ceefdb40 | |||
| 5168eb6781 | |||
| ddb73a9a33 | |||
| 53eff10d75 | |||
| 1df6114ff3 | |||
| 975484cc2b | |||
| 0421c9b643 | |||
| fb69c21252 | |||
| 0cb9122d16 | |||
| c164ad3cbb | |||
| 9b4171a468 | |||
| 5cae4e44fb | |||
| a145a42b2b | |||
| 715807645a | |||
| 1259c6865f | |||
| ff42460cb4 | |||
| 39a16f8d56 | |||
| 83de60f59c | |||
| cf60e090a5 | |||
| 0fb37c33ab | |||
| d81508c22a | |||
| 883ac659b2 | |||
| c6c10b5e24 | |||
| a4e5bef1b7 | |||
| f72c7b03f9 | |||
| bd6f709374 | |||
| 00f2201157 | |||
| b3f0d66071 | |||
| 8730d413bc | |||
| 79140fda3c | |||
| 67e749ea3a | |||
| 7bcfc133ae | |||
| e3e246607e | |||
| 16104cb2c5 | |||
| 224e51c386 | |||
| b022ca089c | |||
| 0ebb761c09 | |||
| c8067828d5 | |||
| 30eedd9b8c | |||
| d701b45057 | |||
| 722c9c101e | |||
| 86aa45f0c4 | |||
| cf45dc4820 | |||
| db77034431 | |||
| abdaec11b0 | |||
| 95fb349656 | |||
| d0b6b6c324 | |||
| d74c23ccf5 | |||
| ea1cfda0d6 | |||
| 5623f47f9a | |||
| e4df9ec193 | |||
| a6306d6b76 | |||
| 64529ba5cc | |||
| cc7f963b89 | |||
| 0ce86af116 | |||
| 2cb0ed3f64 | |||
| fb61854f11 | |||
| 53ba3344b1 | |||
| e20c8be8bb | |||
| 894dcb1d3c | |||
| 9a9e890f8a | |||
| 818ea634f0 | |||
| 780460f8d8 | |||
| e19483a920 | |||
| aca93f1cae | |||
| 1371a4aad2 | |||
| db4a45c0f6 | |||
| e95b1e5f82 | |||
| 15f4008f4b | |||
| f45f81fb45 | |||
| 2220fd2542 | |||
| 564480e165 | |||
| 297c63d91a | |||
| 26e2cd3f65 | |||
| 9f899466d4 | |||
| 38393ea4cf | |||
| a4f25826e3 | |||
| 93484fb33f | |||
| c90f003f92 | |||
| 24793b9b8d | |||
| 78e772f455 | |||
| 1e0d269aad | |||
| f6b1d408fc | |||
| 442b318b6c | |||
| a7c97aedb7 | |||
| 746f9e7b24 | |||
| 0d6c61af5c | |||
| 673f31c059 | |||
| 369a4f0a89 | |||
| 8d54eae4d0 | |||
| a805d5beab | |||
| dbb2aec8b6 | |||
| 1a98b76a1f | |||
| 51d10ab2b5 | |||
| 1aad750395 | |||
| e0aab6bd02 | |||
| 6cb93132b7 | |||
| 04126b99d6 | |||
| 0794eb960d | |||
| d619ad1d48 | |||
| 5b147e07b3 | |||
| 944ce441d8 | |||
| a7dcb8519b | |||
| d912d44fb3 | |||
| 4f7254a634 | |||
| bf923cb296 | |||
| d9f737e1bf | |||
| 59690d045e | |||
| 5d95acba53 | |||
| d46225d2a9 | |||
| 3af30a0e62 | |||
| 69eca4d96d | |||
| 7b2e4a83c9 | |||
| 344b80872a | |||
| ddf828ff5f | |||
| 4e170b069b | |||
| 22c75fb578 | |||
| 11ab9eb6b8 | |||
| 29b232f407 | |||
| 53e8c920e5 | |||
| 78d19bed4d | |||
| 10f4160635 | |||
| 7622836e8b | |||
| 4d4713a9fa | |||
| 25008599f9 | |||
| c00ab074f8 | |||
| aed1f1957f | |||
| c6a959e2e1 | |||
| 02b7ed37f6 | |||
| 0d84aaabb9 | |||
| 6efdcf9610 | |||
| 4266d317d8 | |||
| 4ce7aafcbd | |||
| 35d8b69f92 | |||
| 562057e608 | |||
| b7024e5340 | |||
| 088588231b | |||
| eff117d3d9 | |||
| 968c535709 | |||
| c8b6fa7b11 | |||
| 0aa334b54e | |||
| 78a49f841d | |||
| 43b2bd937e | |||
| a4326875ba | |||
| eb31a58346 | |||
| a6b0acc35d | |||
| cc7fcd0b5b | |||
| 02fe59b913 | |||
| 6fd5f47089 | |||
| 2a2922760e | |||
| a3793460fd | |||
| e0927a04d9 | |||
| 8665604bab | |||
| d4c3c135b3 | |||
| 60bd5e493c | |||
| 0753b2d841 | |||
| 17e6fbd692 | |||
| 0710441650 | |||
| 20a76cee3e | |||
| cb64785867 | |||
| e6e26103c4 | |||
| 15529a14f1 | |||
| 86839188e0 | |||
| 39701b378b | |||
| 45ff6da737 | |||
| a260dd1503 | |||
| 57859301df | |||
| 8c968d3f53 | |||
| 0034bfbe46 | |||
| a733b9247a | |||
| e0afa349b9 | |||
| 7d0ce94907 | |||
| 9045763c35 | |||
| 29898552d7 | |||
| 9d7c2f5c2f | |||
| 5c0fa42351 | |||
| ab045b0ef3 | |||
| 41e6843db1 | |||
| 911ec3c9b9 | |||
| fc6f0a1a7b | |||
| 21873da278 | |||
| d1cd6be2c9 | |||
| 0c0ae41bca | |||
| c9ed7a904a | |||
| d200a8f554 | |||
| 3d04c8fcf1 | |||
| f53f165d91 | |||
| e5645e4064 | |||
| 95e15ca8c4 | |||
| dbf7329e87 | |||
| ed6c3ae431 | |||
| 214d2ecc67 | |||
| 29c95671de | |||
| 238f93a096 | |||
| c76877e7b3 | |||
| 12e5a9c5aa | |||
| 7f4be2ca3f | |||
| 29ffe12d8c | |||
| d34bed4f15 | |||
| aec7ea7e80 | |||
| 5938e1af29 | |||
| 60902297c5 | |||
| 12a95aa6fa | |||
| 78fc459a97 | |||
| 281565804c | |||
| 33a32fd9c8 | |||
| b64aad55e9 | |||
| 2392958114 | |||
| ec04e8e24a | |||
| 4e14ee7f50 | |||
| 7ba4ab0608 | |||
| fd816112fb | |||
| d0ee85be40 | |||
| 9448704af3 | |||
| 9dad9d6ca8 | |||
| 3f41abed7c | |||
| debcbab445 | |||
| 7fcabf1de7 | |||
| e116a1841d | |||
| cd3103ca14 | |||
| 50d07a4b13 | |||
| ed1352936e | |||
| f4b4156a0c | |||
| 5cf2cce0e3 | |||
| 249453d829 | |||
| c14939cecc | |||
| 72f516abb1 | |||
| 66478ed264 | |||
| 6b10dff41d | |||
| f8cc736482 | |||
| a0794fecfc | |||
| c68059e5b3 | |||
| 832ca6b0de | |||
| 89ee43830e | |||
| f7cf13901e | |||
| ad41fa93fb | |||
| 617b7dcd49 | |||
| 417ea032c4 | |||
| b77bb6e200 | |||
| 1fa3b4a600 | |||
| 99bd502f62 | |||
| 25a271dc95 | |||
| 5002ac7716 | |||
| d92a559460 | |||
| 3d571e1a31 | |||
| d338daa4b6 | |||
| 6f802c2a58 | |||
| a3f0168817 | |||
| 677702655f | |||
| b0bbd0c083 | |||
| 5cbf23a1f4 | |||
| 39eb9b34ec | |||
| 5da8616518 | |||
| b267fe05cd | |||
| 29f7ebe559 | |||
| bbffaca511 | |||
| 80532836c3 | |||
| 9474f4f322 | |||
| 93a09d3a9f | |||
| e3935ce699 | |||
| 58c15e7833 | |||
| fd2b7f3aa0 | |||
| 5ccbc629d1 | |||
| e98ff5e8e5 | |||
| a6fffa7b57 | |||
| 3ac153dd06 | |||
| 8db3108c94 | |||
| e25ff4ad19 | |||
| 21e76c6461 | |||
| 103aa1a432 | |||
| d2f4fefcf3 | |||
| 629527988d | |||
| 7f520f1346 | |||
| e28619b55a | |||
| f474e6130e | |||
| 4b5bcb45ac | |||
| 50565a0f17 | |||
| cf37db4fa2 | |||
| ad9b4097ef | |||
| c22c01c6c3 | |||
| 31f7f50c4a | |||
| a7f6ed4b16 | |||
| 73ada5a221 | |||
| 2f96256893 | |||
| 23d9e0775f | |||
| 72ade39144 | |||
| ec64c68777 | |||
| 80932e069f | |||
| 2f9b154b07 | |||
| 20bf911732 | |||
| 65a3dbb228 | |||
| 5844cc93ca | |||
| 4d23ce58c4 | |||
| 2bb592d5f6 | |||
| 3146b20c15 | |||
| 455cf67750 | |||
| a6d6a877b0 | |||
| a7bd54471c | |||
| fe5f803163 | |||
| 66a9b5362a | |||
| f3569cf68b | |||
| 2573f14726 | |||
| f1fb2d6abf | |||
| 4934e0ff0a | |||
| f772a80501 | |||
| 8950843be2 | |||
| 9b89e68908 | |||
| ba134ca53f | |||
| 21dbd9c057 | |||
| 40a68f8e05 | |||
| 37d861a631 | |||
| 31f3e885ce | |||
| 7ffaab2012 | |||
| 35b7946b0d | |||
| 3a05a8e712 | |||
| 294a1149ef | |||
| 8d80370014 | |||
| 1cbdef36cf | |||
| 4c8accbfc1 | |||
| c4c2d9cb93 | |||
| 7aed112326 | |||
| 216a3d53cd | |||
| e0823b343b | |||
| cb0bc65ee4 | |||
| 5b9ab6636f | |||
| 9fd77feebb |
@@ -14,6 +14,21 @@ review_attempts=$(echo "$state" | jq -r '.review_attempts // 0')
|
||||
max_review_attempts=$(echo "$state" | jq -r '.max_review_attempts // 1')
|
||||
review_notes=$(echo "$state" | jq -r '.review_notes // ""')
|
||||
|
||||
if [[ "$review_clean" != "true" && "$review_clean" != "false" ]]; then
|
||||
echo "ERROR: review_clean must be boolean ('true'/'false'); got: $review_clean" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! [[ "$review_attempts" =~ ^[0-9]+$ ]]; then
|
||||
echo "ERROR: review_attempts must be a non-negative integer; got: $review_attempts" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! [[ "$max_review_attempts" =~ ^[0-9]+$ ]]; then
|
||||
echo "ERROR: max_review_attempts must be a non-negative integer; got: $max_review_attempts" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ "$review_clean" == "true" ]]; then
|
||||
jq -nc '{"_next": "end_success"}'
|
||||
exit 0
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
name: explore
|
||||
description: Fast codebase exploration agent - finds patterns, structures, and relevant files. Designed to be fanned out 2-5 in parallel by orchestrators.
|
||||
version: 2.0.0
|
||||
version: 3.0.0
|
||||
|
||||
skills_enabled: true
|
||||
enabled_skills: []
|
||||
enabled_skills:
|
||||
- ai-slop-remover
|
||||
|
||||
variables:
|
||||
- name: project_dir
|
||||
@@ -22,64 +23,85 @@ global_tools:
|
||||
instructions: |
|
||||
You are a codebase explorer. Your job: Search, find, report. Nothing else.
|
||||
|
||||
## Step 0: Load your skills
|
||||
|
||||
At the start of every exploration, call `skill__load` for `ai-slop-remover`. Your findings go directly into the orchestrator's synthesis, so concise, slop-free output is the contract. Apply the skill's standards to your final findings block:
|
||||
|
||||
- No filler ("It's important to note that…", "Let me explain…"). Just the finding.
|
||||
- No flattery, no padding, no status updates about your process.
|
||||
- No multi-paragraph commentary — bullet points with code snippets are enough.
|
||||
|
||||
## You may be one of many parallel explorers
|
||||
|
||||
Orchestrators (like Sisyphus) often fan out 2-5 explore agents at once, each covering a different angle of the same question. Assume you are ONE narrow slice of a larger investigation. Stay strictly within YOUR slice as defined by the prompt — don't broaden scope to cover what other parallel explorers might be handling.
|
||||
|
||||
If the prompt says "find auth middleware", you find auth middleware. You do NOT also tour the routing layer, the error system, and the database connection pool. Narrow scope is the contract.
|
||||
|
||||
## Your mission
|
||||
## Investigation methodology
|
||||
|
||||
1. Search for relevant files and patterns within YOUR slice.
|
||||
2. Read key files to understand structure.
|
||||
3. Report findings concisely.
|
||||
4. Signal completion with `EXPLORE_COMPLETE`.
|
||||
Before searching, build a quick mental model. Then narrow in. Then read.
|
||||
|
||||
## File reading strategy (minimize token usage)
|
||||
1. **Frame the question.** What kind of artifact am I looking for? Symbols (struct/class/function)? File patterns? Configuration? Implementation details? Tests? Different artifact kinds use different tools.
|
||||
|
||||
1. **Find first, read second** — never read a file without knowing why.
|
||||
2. **Use grep to locate** — `fs_grep --pattern "struct User" --include "*.rs"` finds where things are.
|
||||
3. **Use glob to discover** — `fs_glob --pattern "*.rs" --path src/` finds files by name.
|
||||
4. **Prefer `fs_read` with offset/limit** — `fs_read --path "src/main.rs" --offset 50 --limit 30` reads lines 50-79 only. `fs_read` adds line numbers but TRUNCATES long lines (over 2000 chars) and caps output at 2000 lines by default.
|
||||
5. **Use `fs_cat` only when you need the entire file untruncated** — for exploration this should be rare. If you find yourself reaching for `fs_cat`, ask whether `fs_grep` + a targeted `fs_read` would answer your question instead.
|
||||
6. **Never read entire large files** — if a file is 500+ lines, read the relevant section only.
|
||||
2. **Find first, read second.** Never `fs_read` a file without knowing why you're reading it.
|
||||
|
||||
3. **Build a directory mental model with `fs_ls` and `fs_glob`** — `fs_ls src/` to see what's there; `fs_glob '**/*.rs' src/` to see which files exist by name.
|
||||
|
||||
4. **Locate symbols with `fs_grep`** — for finding where things live across the codebase. `fs_grep --pattern "fn handle_request" --include "*.rs"` is faster than reading files.
|
||||
|
||||
5. **Read targeted sections with `fs_read --offset/--limit`** — `fs_read --path "src/main.rs" --offset 50 --limit 30` reads lines 50-79 only. `fs_read` adds line numbers but TRUNCATES long lines (over 2000 chars) and caps output at 2000 lines by default.
|
||||
|
||||
6. **Use `fs_cat` only when you need the full untruncated file** — rare in exploration. If you reach for `fs_cat`, ask whether `fs_grep` + targeted `fs_read` would answer your question with less context spend.
|
||||
|
||||
7. **Never read entire large files** — for files 500+ lines, read the relevant section only.
|
||||
|
||||
## Available actions
|
||||
|
||||
- `fs_grep --pattern "struct User" --include "*.rs"` — find content across files
|
||||
- `fs_grep --pattern "struct User" --include "*.rs"` — find content across files in a directory tree
|
||||
- `fs_grep --pattern "TODO" --path "src/main.rs"` — find content within a single file (--include is ignored in this mode)
|
||||
- `fs_glob --pattern "*.rs" --path src/` — find files by name pattern
|
||||
- `fs_read --path "src/main.rs"` — read a TRUNCATED view with line numbers (default 2000 lines, lines over 2000 chars cut off)
|
||||
- `fs_read --path "src/main.rs" --offset 100 --limit 50` — read lines 100-149 only (with line numbers, truncation rules still apply)
|
||||
- `fs_read --path "src/main.rs" --offset 100 --limit 50` — read lines 100-149 only (line numbers; truncation rules still apply)
|
||||
- `fs_cat --path "src/main.rs"` — read the FULL untruncated file (no line numbers); use only when you actually need every line
|
||||
- `fs_ls --path "src/"` — list directory contents
|
||||
|
||||
## When to use the web (ddg-search MCP)
|
||||
|
||||
Rarely. You are a CODEBASE explorer, not a web researcher. Use the web only when the codebase references an external library/framework whose documented behavior is the answer to the question (e.g., "how does Tokio's #[tokio::main] expand"), and the answer isn't in the local code. For internal questions ("how does OUR auth work"), grep the codebase — never the web.
|
||||
|
||||
## Output format
|
||||
|
||||
Always end your response with a findings summary. Include actual code snippets when they show the pattern — file paths alone are not enough for the orchestrator to delegate downstream:
|
||||
Always end your response with a structured findings block. Sisyphus reads this verbatim and may paste sections directly into delegation prompts for a coder agent, so the structure matters:
|
||||
|
||||
```
|
||||
FINDINGS:
|
||||
- [Key finding 1]
|
||||
- [Key finding 2]
|
||||
- Relevant files: [list]
|
||||
- [One-line concrete fact about what you found]
|
||||
- [Another one-line fact]
|
||||
- Relevant files: [list of paths, no commentary]
|
||||
|
||||
Code patterns (paste actual lines):
|
||||
- From `path/to/file.ext` lines N-M:
|
||||
<snippet>
|
||||
<5-20 lines of actual code that show the pattern>
|
||||
- From `path/to/other.ext` lines N-M:
|
||||
<another snippet>
|
||||
|
||||
Open questions (only if any):
|
||||
- [Anything you couldn't determine and the orchestrator should clarify or delegate elsewhere]
|
||||
|
||||
EXPLORE_COMPLETE
|
||||
```
|
||||
|
||||
Pasting actual code lines (5-20 lines per pattern) lets the orchestrator hand the snippet directly to a coder agent without re-exploration. That is the whole point of your existence in a fanned-out research phase.
|
||||
Pasting actual code lines (5-20 per pattern) lets the orchestrator hand snippets directly to a coder agent without re-exploration. That is the entire point of your existence in a parallel research phase. File paths alone make downstream delegation impossible — the coder would have to re-do your work.
|
||||
|
||||
## Rules
|
||||
|
||||
1. **Be fast** — don't read every file, read representative ones.
|
||||
2. **Stay in your slice** — narrow scope is the contract.
|
||||
3. **Be concise** — report findings, not your process.
|
||||
4. **Never modify files** — you are read-only.
|
||||
5. **Limit reads** — max 5 file reads per exploration.
|
||||
6. **Paste code snippets** — file paths alone make downstream delegation impossible.
|
||||
1. **Be fast.** Don't read every file, read representative ones.
|
||||
2. **Stay in your slice.** Narrow scope is the contract.
|
||||
3. **Be concise.** Report findings, not your process. Apply the `ai-slop-remover` skill to your output.
|
||||
4. **Never modify files.** You are read-only.
|
||||
5. **Limit reads.** Target around 5 file reads per exploration; go higher only when the question genuinely requires it.
|
||||
6. **Paste code snippets.** File paths alone make downstream delegation impossible.
|
||||
7. **Report what you didn't find.** If the prompt asked for X and X doesn't exist in your slice, say so explicitly — don't pad your findings with adjacent material to hide the gap.
|
||||
|
||||
## Context
|
||||
- Project: {{project_dir}}
|
||||
|
||||
@@ -239,11 +239,52 @@ instructions: |
|
||||
|
||||
**No evidence = not complete.** Mark a todo `completed` only after evidence is collected.
|
||||
|
||||
### Independent code review (post-coder, non-trivial work)
|
||||
|
||||
After completing delegated `coder` work, spawn `code-reviewer` for an independent review pass if ANY of these are true:
|
||||
|
||||
1. **2+ coder agents were spawned** for this task (multi-component change; no single coder saw the whole picture)
|
||||
2. **A single coder touched 5+ files** (broad-scope change; harder for self-review to hold in one context)
|
||||
3. **The change crosses architectural boundaries** — auth, public APIs, security-sensitive paths, schema/migration files, configuration that affects multiple services
|
||||
4. **You judge the change as architecturally significant** even if 1-3 don't trigger
|
||||
|
||||
If none of these fire, the work is "single coder, narrow scope, mechanical" — coder's internal `self_review` is sufficient.
|
||||
|
||||
**Why this matters.** Coder's `self_review` is a same-agent check: the agent that wrote the code reviews its own diff. It catches surface slop and obvious mistakes, but it's structurally weak at catching cross-cutting issues across parallel coders, subtle design problems the author justified to themselves, and rationalized "not my job" footguns. `code-reviewer` is independent — no commitment to the prior design decisions. The independence is the value, and it's how real-world engineering catches what authors miss.
|
||||
|
||||
**Spawn pattern:**
|
||||
|
||||
```
|
||||
agent__spawn --agent code-reviewer --prompt "Review the changes from the recent coder run(s) for this task.
|
||||
|
||||
Original request: <one-line summary of what the user asked for>
|
||||
Scope: <which directories or files the changes are expected to touch>
|
||||
|
||||
Coder summaries:
|
||||
- <coder 1 session_id>: <plan_summary from CODER_COMPLETE>
|
||||
- <coder 2 session_id>: <plan_summary if multiple coders ran>
|
||||
|
||||
Run `get_diff` against the staged or recent changes, fan out file-reviewers per changed file as usual, and synthesize."
|
||||
```
|
||||
|
||||
### 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.
|
||||
- **🟢 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.
|
||||
|
||||
### 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.
|
||||
|
||||
## File Operations (Direct Edits)
|
||||
|
||||
When you write or modify files yourself (rather than delegating to coder):
|
||||
|
||||
- **For writing files**, ALWAYS use `fs_write` (new file / full overwrite) or `fs_patch` (surgical edit). NEVER write files via `execute_command`. Do not use:
|
||||
- **For editing an existing file**, prefer `fs_patch`. It's a surgical edit that preserves unchanged content. Send only the diff hunks for the lines you want to change; do not re-send the whole file. This is faster, cheaper, and dramatically less prone to accidental data loss than a full rewrite.
|
||||
- **For writing a NEW file or doing a COMPLETE rewrite**, use `fs_write`. Use it only when most of the content is changing or the file doesn't exist yet.
|
||||
- **NEVER write files via `execute_command`.** Do not use:
|
||||
- `cat > file`, `cat >> file`, `tee`
|
||||
- `echo >`, `printf >`
|
||||
- Heredocs (`<<EOF`, `<<-EOF`, `<<'EOF'`)
|
||||
|
||||
@@ -32,7 +32,7 @@ def main():
|
||||
agent_data = parse_raw_data(raw_data)
|
||||
|
||||
root_dir = "{config_dir}"
|
||||
setup_env(root_dir, agent_func)
|
||||
setup_env(root_dir, agent_func, raw_data)
|
||||
|
||||
agent_tools_path = os.path.join(root_dir, "agents/{agent_name}/tools.py")
|
||||
run(agent_tools_path, agent_func, agent_data)
|
||||
@@ -65,13 +65,14 @@ def parse_argv():
|
||||
return agent_func, agent_data
|
||||
|
||||
|
||||
def setup_env(root_dir, agent_func):
|
||||
def setup_env(root_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_CACHE_DIR"] = os.path.join(root_dir, "cache", "{agent_name}")
|
||||
os.environ["LLM_AGENT_RAW_JSON"] = raw_data
|
||||
|
||||
|
||||
def load_env(file_path):
|
||||
|
||||
@@ -32,6 +32,7 @@ setup_env() {
|
||||
export LLM_AGENT_ROOT_DIR="$LLM_ROOT_DIR/agents/{agent_name}"
|
||||
export LLM_AGENT_CACHE_DIR="$LLM_ROOT_DIR/cache/{agent_name}"
|
||||
export LLM_PROMPT_UTILS_FILE="{prompt_utils_file}"
|
||||
export LLM_AGENT_RAW_JSON="$agent_data"
|
||||
}
|
||||
|
||||
load_env() {
|
||||
|
||||
@@ -11,7 +11,7 @@ async function main(): Promise<void> {
|
||||
const agentData = parseRawData(rawData);
|
||||
|
||||
const configDir = "{config_dir}";
|
||||
setupEnv(configDir, agentFunc);
|
||||
setupEnv(configDir, agentFunc, rawData);
|
||||
|
||||
const agentToolsPath = join(configDir, "agents", "{agent_name}", "tools.ts");
|
||||
await run(agentToolsPath, agentFunc, agentData);
|
||||
@@ -48,13 +48,14 @@ function parseArgv(): { agentFunc: string; rawData: string } {
|
||||
return { agentFunc, rawData: agentData };
|
||||
}
|
||||
|
||||
function setupEnv(configDir: string, agentFunc: string): void {
|
||||
function setupEnv(configDir: 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_CACHE_DIR"] = join(configDir, "cache", "{agent_name}");
|
||||
process.env["LLM_AGENT_RAW_JSON"] = rawData;
|
||||
}
|
||||
|
||||
function loadEnv(filePath: string): void {
|
||||
|
||||
@@ -32,7 +32,7 @@ def main():
|
||||
tool_data = parse_raw_data(raw_data)
|
||||
|
||||
root_dir = "{root_dir}"
|
||||
setup_env(root_dir)
|
||||
setup_env(root_dir, raw_data)
|
||||
|
||||
tool_path = "{tool_path}.py"
|
||||
run(tool_path, "run", tool_data)
|
||||
@@ -65,11 +65,12 @@ def parse_argv():
|
||||
return tool_data
|
||||
|
||||
|
||||
def setup_env(root_dir):
|
||||
def setup_env(root_dir, raw_data):
|
||||
load_env(os.path.join(root_dir, ".env"))
|
||||
os.environ["LLM_ROOT_DIR"] = root_dir
|
||||
os.environ["LLM_TOOL_NAME"] = "{function_name}"
|
||||
os.environ["LLM_TOOL_CACHE_DIR"] = os.path.join(root_dir, "cache", "{function_name}")
|
||||
os.environ["LLM_TOOL_RAW_JSON"] = raw_data
|
||||
|
||||
|
||||
def load_env(file_path):
|
||||
|
||||
@@ -29,6 +29,7 @@ setup_env() {
|
||||
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_TOOL_RAW_JSON="$tool_data"
|
||||
}
|
||||
|
||||
load_env() {
|
||||
|
||||
@@ -11,7 +11,7 @@ async function main(): Promise<void> {
|
||||
const toolData = parseRawData(rawData);
|
||||
|
||||
const rootDir = "{root_dir}";
|
||||
setupEnv(rootDir);
|
||||
setupEnv(rootDir, rawData);
|
||||
|
||||
const toolPath = "{tool_path}.ts";
|
||||
await run(toolPath, "run", toolData);
|
||||
@@ -45,11 +45,12 @@ function parseArgv(): string {
|
||||
return toolData;
|
||||
}
|
||||
|
||||
function setupEnv(rootDir: string): void {
|
||||
function setupEnv(rootDir: string, rawData: string): void {
|
||||
loadEnv(join(rootDir, ".env"));
|
||||
process.env["LLM_ROOT_DIR"] = rootDir;
|
||||
process.env["LLM_TOOL_NAME"] = "{function_name}";
|
||||
process.env["LLM_TOOL_CACHE_DIR"] = join(rootDir, "cache", "{function_name}");
|
||||
process.env["LLM_TOOL_RAW_JSON"] = rawData;
|
||||
}
|
||||
|
||||
function loadEnv(filePath: string): void {
|
||||
|
||||
@@ -10,6 +10,9 @@ set -e
|
||||
source "$LLM_PROMPT_UTILS_FILE"
|
||||
|
||||
main() {
|
||||
# shellcheck disable=SC2154
|
||||
argc_command="$(jq -r '.command' <<< "$LLM_TOOL_RAW_JSON")"
|
||||
|
||||
guard_operation
|
||||
local script
|
||||
script="$(mktemp)"
|
||||
@@ -17,5 +20,5 @@ main() {
|
||||
trap "rm -f '$script'" EXIT
|
||||
# shellcheck disable=SC2154
|
||||
printf '%s\n' "$argc_command" > "$script"
|
||||
bash "$script" >> "$LLM_OUTPUT"
|
||||
bash -e -o pipefail "$script" >> "$LLM_OUTPUT"
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ source "$LLM_PROMPT_UTILS_FILE"
|
||||
|
||||
# shellcheck disable=SC2154
|
||||
main() {
|
||||
argc_code="$(jq -r '.code' <<< "$LLM_TOOL_RAW_JSON")"
|
||||
|
||||
if ! grep -qi '^select' <<<"$argc_code"; then
|
||||
guard_operation ""
|
||||
fi
|
||||
|
||||
@@ -28,6 +28,8 @@ main() {
|
||||
local grep_args=(-nH --color=never)
|
||||
|
||||
if [[ -d "$search_path" ]]; then
|
||||
# Use -r (not -R) so symlinks to directories are NOT followed - this avoids
|
||||
# infinite loops on pathological symlink cycles (e.g. `ln -s . loop`).
|
||||
grep_args+=(-r)
|
||||
grep_args+=(
|
||||
--exclude-dir='.git'
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
#!/usr/bin/env bash
|
||||
set -e
|
||||
|
||||
# @describe Apply a patch to a file at the specified path.
|
||||
# This can be used to edit a file without having to rewrite the whole file.
|
||||
# @describe Apply a unified-diff patch to a file at the specified path. Use this for editing an existing file. It's the
|
||||
# PREFERRED way to modify a file. Prefer this over fs_write whenever the file already exists: it sends less data,
|
||||
# preserves unchanged content automatically, and is less prone to accidental data loss from full rewrites.
|
||||
# Use fs_write only when you are creating a new file or doing a complete rewrite where most of the content changes.
|
||||
|
||||
# @option --path! The path of the file to apply the patch to
|
||||
# @option --contents! The patch to apply to the file
|
||||
@@ -14,6 +16,9 @@ source "$LLM_PROMPT_UTILS_FILE"
|
||||
|
||||
# shellcheck disable=SC2154
|
||||
main() {
|
||||
argc_contents="$(jq -r '.contents' <<< "$LLM_TOOL_RAW_JSON")"
|
||||
argc_path="$(jq -r '.path' <<< "$LLM_TOOL_RAW_JSON")"
|
||||
|
||||
if [[ ! -f "$argc_path" ]]; then
|
||||
error "Unable to find the specified file: $argc_path"
|
||||
exit 1
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
set -e
|
||||
|
||||
# @describe Write the full file contents to a file at the specified path.
|
||||
# @describe Write the FULL file contents to a file at the specified path. Use this for NEW files or COMPLETE rewrites
|
||||
# only. For editing an existing file, prefer fs_patch. It's a surgical edit that preserves unchanged content, requires
|
||||
# sending less data, and is less prone to accidental data loss.
|
||||
|
||||
# @option --path! The path of the file to write to
|
||||
# @option --contents! The full contents to write to the file
|
||||
@@ -13,6 +15,9 @@ source "$LLM_PROMPT_UTILS_FILE"
|
||||
|
||||
# shellcheck disable=SC2154
|
||||
main() {
|
||||
argc_contents="$(jq -r '.contents' <<< "$LLM_TOOL_RAW_JSON")"
|
||||
argc_path="$(jq -r '.path' <<< "$LLM_TOOL_RAW_JSON")"
|
||||
|
||||
if [[ -f "$argc_path" ]]; then
|
||||
printf "%s" "$argc_contents" | git diff --no-index "$argc_path" - || true
|
||||
guard_operation "Apply changes?"
|
||||
|
||||
@@ -14,6 +14,10 @@ set -e
|
||||
|
||||
# shellcheck disable=SC2154
|
||||
main() {
|
||||
argc_recipient="$(jq -r '.recipient' <<< "$LLM_TOOL_RAW_JSON")"
|
||||
argc_subject="$(jq -r '.subject' <<< "$LLM_TOOL_RAW_JSON")"
|
||||
argc_body="$(jq -r '.body' <<< "$LLM_TOOL_RAW_JSON")"
|
||||
|
||||
sender_name="${EMAIL_SENDER_NAME:-$(echo "$EMAIL_SMTP_USER" | awk -F'@' '{print $1}')}"
|
||||
printf "%s\n" "From: $sender_name <$EMAIL_SMTP_USER>
|
||||
To: $argc_recipient
|
||||
|
||||
+20
-3
@@ -82,7 +82,14 @@ vault_password_file: null # Path to a file containing the password for th
|
||||
function_calling_support: true # Enables or disables function calling (Globally).
|
||||
mapping_tools: # Alias for a tool or toolset
|
||||
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. (e.g. 'fs,web_search_coyote')
|
||||
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: # Which tools are visible to be compiled (and are thus able to be defined in 'enabled_tools')
|
||||
# - demo_py.py
|
||||
# - demo_sh.sh
|
||||
@@ -118,7 +125,14 @@ visible_tools: # Which tools are visible to be compiled (and a
|
||||
mcp_server_support: true # Enables or disables MCP servers (globally).
|
||||
mapping_mcp_servers: # Alias for an MCP server or set of servers
|
||||
git: github,gitmcp
|
||||
enabled_mcp_servers: null # Which MCP servers to enable by default (e.g. 'github,slack,ddg-search')
|
||||
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
|
||||
|
||||
# ---- Skills ----
|
||||
# Skills are modular knowledge or capability packs the LLM can load and unload mid-conversation.
|
||||
@@ -131,10 +145,13 @@ visible_skills: # The universe of skills allowed to be enabled
|
||||
- frontend-ui-ux
|
||||
- git-master
|
||||
enabled_skills: null # Which skills are available by default (no role/agent/session active). null = all visible.
|
||||
# Example: only expose two skills in the bare REPL.
|
||||
# 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
|
||||
|
||||
# ---- Auto-Continue (Todo System) ----
|
||||
# The auto-continue system provides built-in task tracking for improved reliability.
|
||||
|
||||
@@ -8,12 +8,17 @@ name: <role-name> # The name of the role
|
||||
model: openai:gpt-4o # The model to use for this role
|
||||
temperature: 0.2 # The temperature to use for this role when querying the model
|
||||
top_p: 0 # The top_p to use for this role when querying the model
|
||||
enabled_tools: fs_ls,fs_cat # A comma-separated list of tools to enable for this role
|
||||
enabled_mcp_servers: github,gitmcp # A comma-separated list of MCP servers to enable for this role
|
||||
enabled_tools: # Tools to enable for this role. Accepts a YAML list (preferred)
|
||||
- fs_ls # or a comma-separated string (e.g. `enabled_tools: fs_ls,fs_cat`).
|
||||
- fs_cat # Use `all` to enable every visible tool.
|
||||
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.
|
||||
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: git-master,ai-slop-remover # Comma-separated list of skills available when this role is active.
|
||||
# Must be a subset of global `visible_skills`. Omit to inherit the global default.
|
||||
enabled_skills: # Skills available when this role is active. Accepts a YAML list (preferred)
|
||||
- git-master # or a comma-separated string (e.g. `enabled_skills: git-master,ai-slop-remover`).
|
||||
- ai-slop-remover # Must be a subset of global `visible_skills`. Omit to inherit the global default.
|
||||
prompt: null # A custom prompt to use for this role that will immediately query
|
||||
# the model for output instead of using the instructions below
|
||||
# Auto-Continue (Todo System)
|
||||
|
||||
+105
@@ -3,6 +3,62 @@
|
||||
# - https://platform.openai.com/docs/api-reference/chat
|
||||
- provider: openai
|
||||
models:
|
||||
- name: gpt-5.5
|
||||
max_input_tokens: 1050000
|
||||
max_output_tokens: 128000
|
||||
input_price: 5
|
||||
output_price: 30
|
||||
supports_vision: true
|
||||
supports_function_calling: true
|
||||
- name: gpt-5.5-pro
|
||||
max_input_tokens: 1050000
|
||||
max_output_tokens: 128000
|
||||
input_price: 30
|
||||
output_price: 180
|
||||
supports_vision: true
|
||||
supports_function_calling: true
|
||||
- name: gpt-5.4
|
||||
max_input_tokens: 1050000
|
||||
max_output_tokens: 128000
|
||||
input_price: 2.5
|
||||
output_price: 15
|
||||
supports_vision: true
|
||||
supports_function_calling: true
|
||||
- name: gpt-5.4-pro
|
||||
max_input_tokens: 1050000
|
||||
max_output_tokens: 128000
|
||||
input_price: 30
|
||||
output_price: 180
|
||||
supports_vision: true
|
||||
supports_function_calling: true
|
||||
- name: gpt-5.4-mini
|
||||
max_input_tokens: 400000
|
||||
max_output_tokens: 128000
|
||||
input_price: 0.75
|
||||
output_price: 4.5
|
||||
supports_vision: true
|
||||
supports_function_calling: true
|
||||
- name: gpt-5.4-nano
|
||||
max_input_tokens: 400000
|
||||
max_output_tokens: 128000
|
||||
input_price: 0.2
|
||||
output_price: 1.25
|
||||
supports_vision: true
|
||||
supports_function_calling: true
|
||||
- name: gpt-5.3-codex
|
||||
max_input_tokens: 400000
|
||||
max_output_tokens: 128000
|
||||
input_price: 1.75
|
||||
output_price: 14
|
||||
supports_vision: true
|
||||
supports_function_calling: true
|
||||
- name: chat-latest
|
||||
max_input_tokens: 400000
|
||||
max_output_tokens: 128000
|
||||
input_price: 5
|
||||
output_price: 30
|
||||
supports_vision: true
|
||||
supports_function_calling: true
|
||||
- name: gpt-5.2
|
||||
max_input_tokens: 400000
|
||||
max_output_tokens: 128000
|
||||
@@ -1540,6 +1596,55 @@
|
||||
# - https://openrouter.ai/docs/api-reference/chat-completion
|
||||
- provider: openrouter
|
||||
models:
|
||||
- name: openai/gpt-5.5
|
||||
max_input_tokens: 1050000
|
||||
max_output_tokens: 128000
|
||||
input_price: 5
|
||||
output_price: 30
|
||||
supports_vision: true
|
||||
supports_function_calling: true
|
||||
- name: openai/gpt-5.5-pro
|
||||
max_input_tokens: 1050000
|
||||
max_output_tokens: 128000
|
||||
input_price: 30
|
||||
output_price: 180
|
||||
supports_vision: true
|
||||
supports_function_calling: true
|
||||
- name: openai/gpt-5.4
|
||||
max_input_tokens: 1050000
|
||||
max_output_tokens: 128000
|
||||
input_price: 2.5
|
||||
output_price: 15
|
||||
supports_vision: true
|
||||
supports_function_calling: true
|
||||
- name: openai/gpt-5.4-pro
|
||||
max_input_tokens: 1050000
|
||||
max_output_tokens: 128000
|
||||
input_price: 30
|
||||
output_price: 180
|
||||
supports_vision: true
|
||||
supports_function_calling: true
|
||||
- name: openai/gpt-5.4-mini
|
||||
max_input_tokens: 400000
|
||||
max_output_tokens: 128000
|
||||
input_price: 0.75
|
||||
output_price: 4.5
|
||||
supports_vision: true
|
||||
supports_function_calling: true
|
||||
- name: openai/gpt-5.4-nano
|
||||
max_input_tokens: 400000
|
||||
max_output_tokens: 128000
|
||||
input_price: 0.2
|
||||
output_price: 1.25
|
||||
supports_vision: true
|
||||
supports_function_calling: true
|
||||
- name: openai/gpt-5.3-codex
|
||||
max_input_tokens: 400000
|
||||
max_output_tokens: 128000
|
||||
input_price: 1.75
|
||||
output_price: 14
|
||||
supports_vision: true
|
||||
supports_function_calling: true
|
||||
- name: openai/gpt-5.2
|
||||
max_input_tokens: 400000
|
||||
max_output_tokens: 128000
|
||||
|
||||
@@ -137,7 +137,8 @@ pub(super) fn session_completer(current: &OsStr) -> Vec<CompletionCandidate> {
|
||||
pub(super) fn secrets_completer(current: &OsStr) -> Vec<CompletionCandidate> {
|
||||
let cur = current.to_string_lossy();
|
||||
match load_app_config_for_completion() {
|
||||
Ok(app_config) => Vault::init(&app_config)
|
||||
Ok(app_config) => match Vault::init(&app_config) {
|
||||
Ok(vault) => vault
|
||||
.list_secrets(false)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
@@ -145,5 +146,7 @@ pub(super) fn secrets_completer(current: &OsStr) -> Vec<CompletionCandidate> {
|
||||
.map(CompletionCandidate::new)
|
||||
.collect(),
|
||||
Err(_) => vec![],
|
||||
},
|
||||
Err(_) => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ use clap::ValueHint;
|
||||
use clap::{Parser, crate_authors, crate_description, crate_version};
|
||||
use clap_complete::ArgValueCompleter;
|
||||
use is_terminal::IsTerminal;
|
||||
use std::collections::HashSet;
|
||||
use std::io::{Read, stdin};
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
@@ -163,6 +164,18 @@ pub struct Cli {
|
||||
}
|
||||
|
||||
impl Cli {
|
||||
pub fn skills(&self) -> Vec<String> {
|
||||
let mut seen = HashSet::new();
|
||||
let mut out = Vec::with_capacity(self.skill.len());
|
||||
for name in &self.skill {
|
||||
if seen.insert(name.clone()) {
|
||||
out.push(name.clone());
|
||||
}
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
pub fn text(&self) -> Result<Option<String>> {
|
||||
let mut stdin_text = String::new();
|
||||
if !stdin().is_terminal() {
|
||||
@@ -323,6 +336,21 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skills_method_dedupes_preserving_first_occurrence() {
|
||||
let cli = parse(&[
|
||||
"--skill", "alpha", "--skill", "beta", "--skill", "alpha", "--skill", "gamma",
|
||||
"--skill", "beta",
|
||||
]);
|
||||
|
||||
assert_eq!(cli.skills(), vec!["alpha", "beta", "gamma"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skills_method_returns_empty_when_no_flags() {
|
||||
assert!(parse(&[]).skills().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_file_flag_single() {
|
||||
let cli = parse(&["-f", "file.txt", "question"]);
|
||||
|
||||
@@ -354,7 +354,9 @@ pub async fn create_config(
|
||||
"type": client,
|
||||
});
|
||||
for (key, desc, help_message, is_secret) in prompts {
|
||||
let env_name = format!("{client}_{key}").to_ascii_uppercase();
|
||||
let env_name = format!("{client}-{key}")
|
||||
.to_ascii_uppercase()
|
||||
.replace("_", "-");
|
||||
let required = std::env::var(&env_name).is_err();
|
||||
let value = if !is_secret {
|
||||
prompt_input_string(desc, required, *help_message)?
|
||||
|
||||
+9
-11
@@ -548,12 +548,12 @@ impl RoleLike for Agent {
|
||||
self.config.top_p
|
||||
}
|
||||
|
||||
fn enabled_tools(&self) -> Option<String> {
|
||||
fn enabled_tools(&self) -> Option<Vec<String>> {
|
||||
None
|
||||
}
|
||||
|
||||
fn enabled_mcp_servers(&self) -> Option<String> {
|
||||
self.config.mcp_servers.clone().join(",").into()
|
||||
fn enabled_mcp_servers(&self) -> Option<Vec<String>> {
|
||||
Some(self.config.mcp_servers.clone())
|
||||
}
|
||||
|
||||
fn set_model(&mut self, model: Model) {
|
||||
@@ -569,15 +569,14 @@ impl RoleLike for Agent {
|
||||
self.config.top_p = value;
|
||||
}
|
||||
|
||||
fn set_enabled_tools(&mut self, value: Option<String>) {
|
||||
fn set_enabled_tools(&mut self, value: Option<Vec<String>>) {
|
||||
match value {
|
||||
Some(tools) => {
|
||||
let tools = tools
|
||||
.split(',')
|
||||
self.config.global_tools = tools
|
||||
.into_iter()
|
||||
.map(|v| v.trim().to_string())
|
||||
.filter(|v| !v.is_empty())
|
||||
.collect::<Vec<_>>();
|
||||
self.config.global_tools = tools;
|
||||
}
|
||||
None => {
|
||||
self.config.global_tools.clear();
|
||||
@@ -585,15 +584,14 @@ impl RoleLike for Agent {
|
||||
}
|
||||
}
|
||||
|
||||
fn set_enabled_mcp_servers(&mut self, value: Option<String>) {
|
||||
fn set_enabled_mcp_servers(&mut self, value: Option<Vec<String>>) {
|
||||
match value {
|
||||
Some(servers) => {
|
||||
let servers = servers
|
||||
.split(',')
|
||||
self.config.mcp_servers = servers
|
||||
.into_iter()
|
||||
.map(|v| v.trim().to_string())
|
||||
.filter(|v| !v.is_empty())
|
||||
.collect::<Vec<_>>();
|
||||
self.config.mcp_servers = servers;
|
||||
}
|
||||
None => {
|
||||
self.config.mcp_servers.clear();
|
||||
|
||||
+31
-10
@@ -3,7 +3,7 @@ use crate::render::{MarkdownRender, RenderOptions};
|
||||
use crate::utils::{IS_STDOUT_TERMINAL, NO_COLOR, decode_bin, get_env_name};
|
||||
|
||||
use super::paths;
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use gman::providers::SupportedProvider;
|
||||
use indexmap::IndexMap;
|
||||
use serde::Deserialize;
|
||||
@@ -34,16 +34,19 @@ pub struct AppConfig {
|
||||
|
||||
pub function_calling_support: bool,
|
||||
pub mapping_tools: IndexMap<String, String>,
|
||||
pub enabled_tools: Option<String>,
|
||||
#[serde(default, deserialize_with = "super::deserialize_csv_or_vec")]
|
||||
pub enabled_tools: Option<Vec<String>>,
|
||||
pub visible_tools: Option<Vec<String>>,
|
||||
|
||||
pub skills_enabled: bool,
|
||||
pub enabled_skills: Option<String>,
|
||||
#[serde(default, deserialize_with = "super::deserialize_csv_or_vec")]
|
||||
pub enabled_skills: Option<Vec<String>>,
|
||||
pub visible_skills: Option<Vec<String>>,
|
||||
|
||||
pub mcp_server_support: bool,
|
||||
pub mapping_mcp_servers: IndexMap<String, String>,
|
||||
pub enabled_mcp_servers: Option<String>,
|
||||
#[serde(default, deserialize_with = "super::deserialize_csv_or_vec")]
|
||||
pub enabled_mcp_servers: Option<Vec<String>>,
|
||||
|
||||
pub auto_continue: bool,
|
||||
pub max_auto_continues: usize,
|
||||
@@ -213,6 +216,7 @@ impl AppConfig {
|
||||
clients: config.clients,
|
||||
};
|
||||
app_config.load_envs();
|
||||
app_config.validate_visible_skills()?;
|
||||
if let Some(wrap) = app_config.wrap.clone() {
|
||||
app_config.set_wrap(&wrap)?;
|
||||
}
|
||||
@@ -222,11 +226,28 @@ impl AppConfig {
|
||||
Ok(app_config)
|
||||
}
|
||||
|
||||
fn validate_visible_skills(&self) -> Result<()> {
|
||||
let Some(skills) = self.visible_skills.as_ref() else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
for name in skills {
|
||||
paths::validate_skill_name(name)
|
||||
.map_err(|e| anyhow!("invalid entry in visible_skills: {e}"))?;
|
||||
|
||||
if !paths::has_skill(name) {
|
||||
bail!("visible_skills references skill '{name}' which is not installed");
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn resolve_model(&mut self) -> Result<()> {
|
||||
if self.model_id.is_empty() {
|
||||
let models = list_models(self, crate::client::ModelType::Chat);
|
||||
if models.is_empty() {
|
||||
anyhow::bail!("No available model");
|
||||
bail!("No available model");
|
||||
}
|
||||
self.model_id = models[0].id();
|
||||
}
|
||||
@@ -392,7 +413,7 @@ impl AppConfig {
|
||||
self.mapping_tools = v;
|
||||
}
|
||||
if let Some(v) = super::read_env_value::<String>(&get_env_name("enabled_tools")) {
|
||||
self.enabled_tools = v;
|
||||
self.enabled_tools = v.map(|raw| super::csv_to_vec(&raw));
|
||||
}
|
||||
|
||||
if let Some(Some(v)) = super::read_env_bool(&get_env_name("skills_enabled")) {
|
||||
@@ -400,7 +421,7 @@ impl AppConfig {
|
||||
}
|
||||
|
||||
if let Some(v) = super::read_env_value::<String>(&get_env_name("enabled_skills")) {
|
||||
self.enabled_skills = v;
|
||||
self.enabled_skills = v.map(|raw| super::csv_to_vec(&raw));
|
||||
}
|
||||
|
||||
if let Some(Some(v)) = super::read_env_bool(&get_env_name("mcp_server_support")) {
|
||||
@@ -412,7 +433,7 @@ impl AppConfig {
|
||||
self.mapping_mcp_servers = v;
|
||||
}
|
||||
if let Some(v) = super::read_env_value::<String>(&get_env_name("enabled_mcp_servers")) {
|
||||
self.enabled_mcp_servers = v;
|
||||
self.enabled_mcp_servers = v.map(|raw| super::csv_to_vec(&raw));
|
||||
}
|
||||
|
||||
if let Some(v) = super::read_env_value::<String>(&get_env_name("repl_prelude")) {
|
||||
@@ -514,12 +535,12 @@ impl AppConfig {
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn set_enabled_tools_default(&mut self, value: Option<String>) {
|
||||
pub fn set_enabled_tools_default(&mut self, value: Option<Vec<String>>) {
|
||||
self.enabled_tools = value;
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn set_enabled_mcp_servers_default(&mut self, value: Option<String>) {
|
||||
pub fn set_enabled_mcp_servers_default(&mut self, value: Option<Vec<String>>) {
|
||||
self.enabled_mcp_servers = value;
|
||||
}
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ impl AppState {
|
||||
start_mcp_servers: bool,
|
||||
abort_signal: AbortSignal,
|
||||
) -> Result<Self> {
|
||||
let vault = Arc::new(Vault::init(&config));
|
||||
let vault = Arc::new(Vault::init(&config)?);
|
||||
|
||||
let mcp_registry = McpRegistry::init(
|
||||
log_path,
|
||||
|
||||
+31
-31
@@ -38,10 +38,10 @@ pub struct Input {
|
||||
}
|
||||
|
||||
impl Input {
|
||||
pub fn from_str(ctx: &RequestContext, text: &str, role: Option<Role>) -> Self {
|
||||
let (role, with_session, with_agent) = resolve_role(ctx, role);
|
||||
pub fn from_str(ctx: &RequestContext, text: &str, role: Option<Role>) -> Result<Self> {
|
||||
let (role, with_session, with_agent) = resolve_role(ctx, role)?;
|
||||
let captured = capture_input_config(ctx, &role);
|
||||
Self {
|
||||
Ok(Self {
|
||||
app_config: Arc::clone(&ctx.app.config),
|
||||
stream_enabled: captured.stream_enabled,
|
||||
session: captured.session,
|
||||
@@ -60,7 +60,7 @@ impl Input {
|
||||
rag_name: None,
|
||||
with_session,
|
||||
with_agent,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn from_files(
|
||||
@@ -111,7 +111,7 @@ impl Input {
|
||||
));
|
||||
}
|
||||
}
|
||||
let (role, with_session, with_agent) = resolve_role(ctx, role);
|
||||
let (role, with_session, with_agent) = resolve_role(ctx, role)?;
|
||||
let captured = capture_input_config(ctx, &role);
|
||||
Ok(Self {
|
||||
app_config: Arc::clone(&ctx.app.config),
|
||||
@@ -398,14 +398,14 @@ impl Input {
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_role(ctx: &RequestContext, role: Option<Role>) -> (Role, bool, bool) {
|
||||
fn resolve_role(ctx: &RequestContext, role: Option<Role>) -> Result<(Role, bool, bool)> {
|
||||
match role {
|
||||
Some(v) => (v, false, false),
|
||||
None => (
|
||||
ctx.extract_role(ctx.app.config.as_ref()),
|
||||
Some(v) => Ok((v, false, false)),
|
||||
None => Ok((
|
||||
ctx.extract_role(ctx.app.config.as_ref())?,
|
||||
ctx.session.is_some(),
|
||||
ctx.agent.is_some(),
|
||||
),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -600,7 +600,7 @@ mod tests {
|
||||
fn resolve_role_with_explicit_role() {
|
||||
let ctx = create_test_ctx();
|
||||
let role = Role::new("custom", "be helpful");
|
||||
let (resolved, with_session, with_agent) = resolve_role(&ctx, Some(role));
|
||||
let (resolved, with_session, with_agent) = resolve_role(&ctx, Some(role)).unwrap();
|
||||
assert_eq!(resolved.name(), "custom");
|
||||
assert!(!with_session);
|
||||
assert!(!with_agent);
|
||||
@@ -609,7 +609,7 @@ mod tests {
|
||||
#[test]
|
||||
fn resolve_role_without_role_no_session_no_agent() {
|
||||
let ctx = create_test_ctx();
|
||||
let (resolved, with_session, with_agent) = resolve_role(&ctx, None);
|
||||
let (resolved, with_session, with_agent) = resolve_role(&ctx, None).unwrap();
|
||||
assert_eq!(resolved.name(), "");
|
||||
assert!(!with_session);
|
||||
assert!(!with_agent);
|
||||
@@ -619,7 +619,7 @@ mod tests {
|
||||
fn resolve_role_without_role_with_session() {
|
||||
let mut ctx = create_test_ctx();
|
||||
ctx.session = Some(Session::default());
|
||||
let (_resolved, with_session, with_agent) = resolve_role(&ctx, None);
|
||||
let (_resolved, with_session, with_agent) = resolve_role(&ctx, None).unwrap();
|
||||
assert!(with_session);
|
||||
assert!(!with_agent);
|
||||
}
|
||||
@@ -629,7 +629,7 @@ mod tests {
|
||||
let mut ctx = create_test_ctx();
|
||||
ctx.session = Some(Session::default());
|
||||
let role = Role::new("explicit", "prompt");
|
||||
let (_resolved, with_session, _with_agent) = resolve_role(&ctx, Some(role));
|
||||
let (_resolved, with_session, _with_agent) = resolve_role(&ctx, Some(role)).unwrap();
|
||||
assert!(!with_session);
|
||||
}
|
||||
|
||||
@@ -695,7 +695,7 @@ mod tests {
|
||||
#[test]
|
||||
fn input_from_str_captures_text() {
|
||||
let ctx = create_test_ctx();
|
||||
let input = Input::from_str(&ctx, "hello world", None);
|
||||
let input = Input::from_str(&ctx, "hello world", None).unwrap();
|
||||
assert_eq!(input.text(), "hello world");
|
||||
}
|
||||
|
||||
@@ -703,7 +703,7 @@ mod tests {
|
||||
fn input_from_str_with_explicit_role() {
|
||||
let ctx = create_test_ctx();
|
||||
let role = Role::new("pirate", "you are a pirate");
|
||||
let input = Input::from_str(&ctx, "ahoy", Some(role));
|
||||
let input = Input::from_str(&ctx, "ahoy", Some(role)).unwrap();
|
||||
assert_eq!(input.role().name(), "pirate");
|
||||
assert!(!input.with_agent());
|
||||
}
|
||||
@@ -715,28 +715,28 @@ mod tests {
|
||||
config.stream = false;
|
||||
state.config = Arc::new(config);
|
||||
let ctx = RequestContext::new(Arc::new(state), WorkingMode::Cmd);
|
||||
let input = Input::from_str(&ctx, "test", None);
|
||||
let input = Input::from_str(&ctx, "test", None).unwrap();
|
||||
assert!(!input.stream_enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn input_is_empty_with_no_text_and_no_medias() {
|
||||
let ctx = create_test_ctx();
|
||||
let input = Input::from_str(&ctx, "", None);
|
||||
let input = Input::from_str(&ctx, "", None).unwrap();
|
||||
assert!(input.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn input_is_not_empty_with_text() {
|
||||
let ctx = create_test_ctx();
|
||||
let input = Input::from_str(&ctx, "hello", None);
|
||||
let input = Input::from_str(&ctx, "hello", None).unwrap();
|
||||
assert!(!input.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn input_set_text_changes_text() {
|
||||
let ctx = create_test_ctx();
|
||||
let mut input = Input::from_str(&ctx, "original", None);
|
||||
let mut input = Input::from_str(&ctx, "original", None).unwrap();
|
||||
input.set_text("modified".to_string());
|
||||
assert_eq!(input.text(), "modified");
|
||||
}
|
||||
@@ -744,7 +744,7 @@ mod tests {
|
||||
#[test]
|
||||
fn input_text_returns_patched_when_set() {
|
||||
let ctx = create_test_ctx();
|
||||
let mut input = Input::from_str(&ctx, "original", None);
|
||||
let mut input = Input::from_str(&ctx, "original", None).unwrap();
|
||||
input.patched_text = Some("patched".to_string());
|
||||
assert_eq!(input.text(), "patched");
|
||||
}
|
||||
@@ -752,7 +752,7 @@ mod tests {
|
||||
#[test]
|
||||
fn input_clear_patch_restores_original() {
|
||||
let ctx = create_test_ctx();
|
||||
let mut input = Input::from_str(&ctx, "original", None);
|
||||
let mut input = Input::from_str(&ctx, "original", None).unwrap();
|
||||
input.patched_text = Some("patched".to_string());
|
||||
input.clear_patch();
|
||||
assert_eq!(input.text(), "original");
|
||||
@@ -761,7 +761,7 @@ mod tests {
|
||||
#[test]
|
||||
fn input_set_continue_output_accumulates() {
|
||||
let ctx = create_test_ctx();
|
||||
let mut input = Input::from_str(&ctx, "test", None);
|
||||
let mut input = Input::from_str(&ctx, "test", None).unwrap();
|
||||
assert!(input.continue_output().is_none());
|
||||
input.set_continue_output("first ");
|
||||
assert_eq!(input.continue_output(), Some("first "));
|
||||
@@ -772,7 +772,7 @@ mod tests {
|
||||
#[test]
|
||||
fn input_set_regenerate_sets_flag_and_clears_tool_calls() {
|
||||
let ctx = create_test_ctx();
|
||||
let mut input = Input::from_str(&ctx, "test", None);
|
||||
let mut input = Input::from_str(&ctx, "test", None).unwrap();
|
||||
let role = input.role().clone();
|
||||
assert!(!input.regenerate());
|
||||
input.set_regenerate(role);
|
||||
@@ -784,7 +784,7 @@ mod tests {
|
||||
fn input_summary_truncates_long_text() {
|
||||
let ctx = create_test_ctx();
|
||||
let long_text = "a".repeat(200);
|
||||
let input = Input::from_str(&ctx, &long_text, None);
|
||||
let input = Input::from_str(&ctx, &long_text, None).unwrap();
|
||||
let summary = input.summary();
|
||||
assert!(summary.len() < 200);
|
||||
assert!(summary.ends_with("..."));
|
||||
@@ -793,35 +793,35 @@ mod tests {
|
||||
#[test]
|
||||
fn input_summary_preserves_short_text() {
|
||||
let ctx = create_test_ctx();
|
||||
let input = Input::from_str(&ctx, "short", None);
|
||||
let input = Input::from_str(&ctx, "short", None).unwrap();
|
||||
assert_eq!(input.summary(), "short");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn input_raw_with_no_files() {
|
||||
let ctx = create_test_ctx();
|
||||
let input = Input::from_str(&ctx, "hello", None);
|
||||
let input = Input::from_str(&ctx, "hello", None).unwrap();
|
||||
assert_eq!(input.raw(), "hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn input_render_with_no_medias() {
|
||||
let ctx = create_test_ctx();
|
||||
let input = Input::from_str(&ctx, "hello", None);
|
||||
let input = Input::from_str(&ctx, "hello", None).unwrap();
|
||||
assert_eq!(input.render(), "hello");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn input_with_agent_false_when_no_agent() {
|
||||
let ctx = create_test_ctx();
|
||||
let input = Input::from_str(&ctx, "test", None);
|
||||
let input = Input::from_str(&ctx, "test", None).unwrap();
|
||||
assert!(!input.with_agent());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn input_session_returns_none_when_with_session_false() {
|
||||
let ctx = create_test_ctx();
|
||||
let input = Input::from_str(&ctx, "test", Some(Role::new("r", "p")));
|
||||
let input = Input::from_str(&ctx, "test", Some(Role::new("r", "p"))).unwrap();
|
||||
let session = Some(Session::default());
|
||||
assert!(input.session(&session).is_none());
|
||||
}
|
||||
@@ -830,7 +830,7 @@ mod tests {
|
||||
fn input_session_returns_some_when_with_session_true() {
|
||||
let mut ctx = create_test_ctx();
|
||||
ctx.session = Some(Session::default());
|
||||
let input = Input::from_str(&ctx, "test", None);
|
||||
let input = Input::from_str(&ctx, "test", None).unwrap();
|
||||
let session = Some(Session::default());
|
||||
assert!(input.session(&session).is_some());
|
||||
}
|
||||
|
||||
+107
-10
@@ -1,10 +1,3 @@
|
||||
use anyhow::{Context, Result, bail};
|
||||
use indexmap::IndexMap;
|
||||
use inquire::{Confirm, Select};
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::config::{InstallFilter, paths};
|
||||
#[cfg(not(windows))]
|
||||
use crate::function::Language;
|
||||
@@ -12,6 +5,13 @@ use crate::mcp::{McpServer, McpServersConfig};
|
||||
use crate::utils;
|
||||
use crate::utils::IS_STDOUT_TERMINAL;
|
||||
use crate::vault::{Vault, create_vault_password_file, interpolate_secrets};
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use indexmap::IndexMap;
|
||||
use indoc::formatdoc;
|
||||
use inquire::{Confirm, Select};
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub fn install_remote(git_url: &str, filter: Option<InstallFilter>, force: bool) -> Result<()> {
|
||||
let (url, reference) = parse_url_with_ref(git_url)?;
|
||||
@@ -418,6 +418,26 @@ fn plan_dir_into(
|
||||
let rel = src
|
||||
.strip_prefix(src_dir)
|
||||
.expect("walk_files only returns paths under src_dir");
|
||||
|
||||
if category == TopCategory::Skills {
|
||||
let skill_name = rel
|
||||
.components()
|
||||
.next()
|
||||
.and_then(|c| c.as_os_str().to_str())
|
||||
.ok_or_else(|| {
|
||||
anyhow!(
|
||||
"remote skill bundle has unparseable path component: {}",
|
||||
rel.display()
|
||||
)
|
||||
})?;
|
||||
paths::validate_skill_name(skill_name).with_context(|| {
|
||||
format!(
|
||||
"remote skill '{skill_name}' has an invalid name \
|
||||
(skill names must contain only ASCII alphanumerics, '-', or '_')"
|
||||
)
|
||||
})?;
|
||||
}
|
||||
|
||||
let dst = dst_dir.join(rel);
|
||||
let kind = classify_file(&src, &dst)?;
|
||||
out.push(PlannedFile {
|
||||
@@ -731,8 +751,21 @@ fn merge_mcp_json(
|
||||
serde_json::to_string_pretty(&merged).context("failed to serialize merged mcp.json")?;
|
||||
write_atomically(&final_path, &serialized)?;
|
||||
|
||||
let vault = Vault::init_bare();
|
||||
let (_parsed, missing) = interpolate_secrets(&serialized, &vault)?;
|
||||
let vault = Vault::init_bare()?;
|
||||
let missing = match interpolate_secrets(&serialized, &vault) {
|
||||
Ok((_, missing)) => missing,
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"{}",
|
||||
formatdoc! {"
|
||||
Skipping secret resolution for merged mcp.json: {e:#}
|
||||
Continuing without resolving missing secrets
|
||||
You may need to add any additional missing secrets to the vault manually.
|
||||
"}
|
||||
);
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
let mut deduped: Vec<String> = Vec::new();
|
||||
for s in missing {
|
||||
if !deduped.contains(&s) {
|
||||
@@ -860,7 +893,7 @@ fn handle_missing_secrets(missing: &[String]) -> Result<()> {
|
||||
}
|
||||
|
||||
fn prompt_for_each_secret(missing: &[String]) -> Result<(Vec<String>, Vec<String>)> {
|
||||
let mut vault = Vault::init_bare();
|
||||
let mut vault = Vault::init_bare()?;
|
||||
let mut password_file_ensured = false;
|
||||
let mut added = Vec::new();
|
||||
let mut deferred = Vec::new();
|
||||
@@ -914,6 +947,62 @@ fn print_secret_summary(added: &[String], deferred: &[String]) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::utils::get_env_name;
|
||||
use serial_test::serial;
|
||||
use std::env;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
struct TestVaultConfigGuard {
|
||||
dir_key: String,
|
||||
file_key: String,
|
||||
previous_dir: Option<OsString>,
|
||||
previous_file: Option<OsString>,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TestVaultConfigGuard {
|
||||
fn new(label: &str) -> Self {
|
||||
let dir_key = get_env_name("config_dir");
|
||||
let file_key = get_env_name("config_file");
|
||||
let previous_dir = env::var_os(&dir_key);
|
||||
let previous_file = env::var_os(&file_key);
|
||||
let unique = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
let path = env::temp_dir().join(format!("coyote-vault-test-{label}-{unique}"));
|
||||
fs::create_dir_all(&path).unwrap();
|
||||
let config_path = path.join("config.yaml");
|
||||
fs::write(&config_path, "{}").unwrap();
|
||||
unsafe {
|
||||
env::set_var(&dir_key, &path);
|
||||
env::set_var(&file_key, &config_path);
|
||||
}
|
||||
Self {
|
||||
dir_key,
|
||||
file_key,
|
||||
previous_dir,
|
||||
previous_file,
|
||||
path,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TestVaultConfigGuard {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
match &self.previous_dir {
|
||||
Some(p) => env::set_var(&self.dir_key, p),
|
||||
None => env::remove_var(&self.dir_key),
|
||||
}
|
||||
match &self.previous_file {
|
||||
Some(p) => env::set_var(&self.file_key, p),
|
||||
None => env::remove_var(&self.file_key),
|
||||
}
|
||||
}
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_url_no_ref() {
|
||||
@@ -1253,7 +1342,9 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn merge_into_empty_local_adds_all_remote_servers() {
|
||||
let _guard = TestVaultConfigGuard::new("merge-empty");
|
||||
let dir = fresh_temp_dir("merge-empty-");
|
||||
let remote = dir.join("remote.json");
|
||||
let target = dir.join("target.json");
|
||||
@@ -1270,7 +1361,9 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn merge_force_replaces_local_on_conflict() {
|
||||
let _guard = TestVaultConfigGuard::new("merge-force");
|
||||
let dir = fresh_temp_dir("merge-force-");
|
||||
let remote = dir.join("remote.json");
|
||||
let target = dir.join("target.json");
|
||||
@@ -1336,7 +1429,9 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
|
||||
#[serial]
|
||||
async fn merge_detects_missing_secrets_in_output() {
|
||||
let _guard = TestVaultConfigGuard::new("merge-secret");
|
||||
let dir = fresh_temp_dir("merge-secret-");
|
||||
let remote = dir.join("remote.json");
|
||||
let target = dir.join("target.json");
|
||||
@@ -1352,7 +1447,9 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[serial]
|
||||
fn merge_is_idempotent_on_re_run() {
|
||||
let _guard = TestVaultConfigGuard::new("merge-idempotent");
|
||||
let dir = fresh_temp_dir("merge-idempotent-");
|
||||
let remote = dir.join("remote.json");
|
||||
let target = dir.join("target.json");
|
||||
|
||||
@@ -29,12 +29,12 @@ pub async fn macro_execute(
|
||||
let variables = macro_value
|
||||
.resolve_variables(&new_args)
|
||||
.map_err(|err| anyhow!("{err}. Usage: {}", macro_value.usage(name)))?;
|
||||
let role = ctx.extract_role(ctx.app.config.as_ref());
|
||||
let role = ctx.extract_role(ctx.app.config.as_ref())?;
|
||||
let mut app_config = (*ctx.app.config).clone();
|
||||
app_config.temperature = role.temperature();
|
||||
app_config.top_p = role.top_p();
|
||||
app_config.enabled_tools = role.enabled_tools().clone();
|
||||
app_config.enabled_mcp_servers = role.enabled_mcp_servers().clone();
|
||||
app_config.enabled_tools = role.enabled_tools();
|
||||
app_config.enabled_mcp_servers = role.enabled_mcp_servers();
|
||||
|
||||
let mut app_state = (*ctx.app).clone();
|
||||
app_state.config = Arc::new(app_config);
|
||||
|
||||
+75
-5
@@ -196,16 +196,19 @@ pub struct Config {
|
||||
|
||||
pub function_calling_support: bool,
|
||||
pub mapping_tools: IndexMap<String, String>,
|
||||
pub enabled_tools: Option<String>,
|
||||
#[serde(default, deserialize_with = "deserialize_csv_or_vec")]
|
||||
pub enabled_tools: Option<Vec<String>>,
|
||||
pub visible_tools: Option<Vec<String>>,
|
||||
|
||||
pub skills_enabled: bool,
|
||||
pub enabled_skills: Option<String>,
|
||||
#[serde(default, deserialize_with = "deserialize_csv_or_vec")]
|
||||
pub enabled_skills: Option<Vec<String>>,
|
||||
pub visible_skills: Option<Vec<String>>,
|
||||
|
||||
pub mcp_server_support: bool,
|
||||
pub mapping_mcp_servers: IndexMap<String, String>,
|
||||
pub enabled_mcp_servers: Option<String>,
|
||||
#[serde(default, deserialize_with = "deserialize_csv_or_vec")]
|
||||
pub enabled_mcp_servers: Option<Vec<String>>,
|
||||
|
||||
pub auto_continue: bool,
|
||||
pub max_auto_continues: usize,
|
||||
@@ -484,9 +487,10 @@ impl Config {
|
||||
|
||||
let bootstrap_app = AppConfig {
|
||||
vault_password_file: config.vault_password_file.clone(),
|
||||
secrets_provider: config.secrets_provider.clone(),
|
||||
..AppConfig::default()
|
||||
};
|
||||
let vault = Vault::init(&bootstrap_app);
|
||||
let vault = Vault::init(&bootstrap_app)?;
|
||||
let (parsed_config, missing_secrets) = interpolate_secrets(&content, &vault)?;
|
||||
if !missing_secrets.is_empty() && !info_flag {
|
||||
debug!(
|
||||
@@ -681,7 +685,7 @@ pub async fn create_config_file(config_path: &Path) -> Result<()> {
|
||||
|
||||
let provider_choice = prompt_provider_choice()?;
|
||||
let mut vault = match &provider_choice {
|
||||
None => Vault::init_bare(),
|
||||
None => Vault::default_local(),
|
||||
Some(provider) => Vault {
|
||||
provider: provider.clone(),
|
||||
},
|
||||
@@ -783,6 +787,72 @@ where
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub(super) fn csv_to_vec(raw: &str) -> Vec<String> {
|
||||
raw.split(',')
|
||||
.map(|t| t.trim().to_string())
|
||||
.filter(|t| !t.is_empty())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn deserialize_csv_or_vec<'de, D>(
|
||||
deserializer: D,
|
||||
) -> std::result::Result<Option<Vec<String>>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
use serde::de::{self, SeqAccess, Visitor};
|
||||
use std::fmt;
|
||||
|
||||
struct CsvOrVec;
|
||||
|
||||
impl<'de> Visitor<'de> for CsvOrVec {
|
||||
type Value = Option<Vec<String>>;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
formatter.write_str("a comma-separated string, a list of strings, or null")
|
||||
}
|
||||
|
||||
fn visit_str<E: de::Error>(self, value: &str) -> std::result::Result<Self::Value, E> {
|
||||
Ok(Some(csv_to_vec(value)))
|
||||
}
|
||||
|
||||
fn visit_string<E: de::Error>(self, value: String) -> std::result::Result<Self::Value, E> {
|
||||
Ok(Some(csv_to_vec(&value)))
|
||||
}
|
||||
|
||||
fn visit_none<E: de::Error>(self) -> std::result::Result<Self::Value, E> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn visit_some<D2: serde::Deserializer<'de>>(
|
||||
self,
|
||||
deserializer: D2,
|
||||
) -> std::result::Result<Self::Value, D2::Error> {
|
||||
deserializer.deserialize_any(self)
|
||||
}
|
||||
|
||||
fn visit_unit<E: de::Error>(self) -> std::result::Result<Self::Value, E> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn visit_seq<A: SeqAccess<'de>>(
|
||||
self,
|
||||
mut seq: A,
|
||||
) -> std::result::Result<Self::Value, A::Error> {
|
||||
let mut vec = Vec::new();
|
||||
while let Some(item) = seq.next_element::<String>()? {
|
||||
let trimmed = item.trim().to_string();
|
||||
if !trimmed.is_empty() {
|
||||
vec.push(trimmed);
|
||||
}
|
||||
}
|
||||
Ok(Some(vec))
|
||||
}
|
||||
}
|
||||
|
||||
deserializer.deserialize_option(CsvOrVec)
|
||||
}
|
||||
|
||||
fn read_env_bool(key: &str) -> Option<Option<bool>> {
|
||||
let value = env::var(key).ok()?;
|
||||
Some(parse_bool(&value))
|
||||
|
||||
@@ -80,6 +80,19 @@ pub fn skill_file(name: &str) -> PathBuf {
|
||||
skill_dir(name).join("SKILL.md")
|
||||
}
|
||||
|
||||
pub fn validate_skill_name(name: &str) -> Result<()> {
|
||||
if name.is_empty() {
|
||||
bail!("Skill name cannot be empty");
|
||||
}
|
||||
if !name
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
|
||||
{
|
||||
bail!("Invalid skill name '{name}': only letters, digits, '-', and '_' are allowed");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn macros_dir() -> PathBuf {
|
||||
match env::var(get_env_name("macros_dir")) {
|
||||
Ok(value) => PathBuf::from(value),
|
||||
@@ -257,6 +270,7 @@ pub fn list_skills() -> Vec<String> {
|
||||
&& file_type.is_dir()
|
||||
&& let Some(name) = entry.file_name().to_str()
|
||||
&& entry.path().join("SKILL.md").is_file()
|
||||
&& validate_skill_name(name).is_ok()
|
||||
{
|
||||
names.push(name.to_string());
|
||||
}
|
||||
@@ -286,3 +300,84 @@ pub fn local_models_override() -> Result<Vec<ProviderModels>> {
|
||||
}
|
||||
Ok(models_override.list)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::{fs, time};
|
||||
|
||||
#[test]
|
||||
fn validate_skill_name_accepts_alphanumerics_and_dashes() {
|
||||
assert!(validate_skill_name("git-master").is_ok());
|
||||
assert!(validate_skill_name("code_review").is_ok());
|
||||
assert!(validate_skill_name("Skill1").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_skill_name_rejects_empty() {
|
||||
let err = validate_skill_name("").unwrap_err();
|
||||
assert!(err.to_string().contains("cannot be empty"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_skill_name_rejects_path_traversal() {
|
||||
for bad in ["../escape", "..", "foo/bar", "foo\\bar", "./hidden"] {
|
||||
let err = validate_skill_name(bad).unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("Invalid skill name"),
|
||||
"expected rejection for {bad:?}, got: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_skill_name_rejects_other_special_chars() {
|
||||
for bad in ["with space", "null\0byte", "weird?char", "dot.name"] {
|
||||
assert!(
|
||||
validate_skill_name(bad).is_err(),
|
||||
"expected rejection for {bad:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn has_skill_returns_false_for_missing_paths() {
|
||||
for absent in ["definitely-not-installed-skill-xyz", "another-missing"] {
|
||||
assert!(
|
||||
!has_skill(absent),
|
||||
"has_skill({absent:?}) should be false for a missing skill"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_skills_skips_invalid_directory_names() {
|
||||
let unique = time::SystemTime::now()
|
||||
.duration_since(time::UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos();
|
||||
let root = env::temp_dir().join(format!("coyote-list-skills-test-{unique}"));
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
let prev = env::var_os(get_env_name("skills_dir"));
|
||||
unsafe {
|
||||
env::set_var(get_env_name("skills_dir"), &root);
|
||||
}
|
||||
|
||||
for name in ["valid-skill", "with space", ".hidden", "dot.name"] {
|
||||
let dir = root.join(name);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::write(dir.join("SKILL.md"), "body").unwrap();
|
||||
}
|
||||
|
||||
let listed = list_skills();
|
||||
assert_eq!(listed, vec!["valid-skill".to_string()]);
|
||||
|
||||
unsafe {
|
||||
match prev {
|
||||
Some(v) => env::set_var(get_env_name("skills_dir"), v),
|
||||
None => env::remove_var(get_env_name("skills_dir")),
|
||||
}
|
||||
}
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
|
||||
+133
-60
@@ -37,6 +37,7 @@ use gman::providers::SupportedProvider;
|
||||
use indexmap::IndexMap;
|
||||
use indoc::formatdoc;
|
||||
use inquire::{Confirm, MultiSelect, Text, list_option::ListOption, validator::Validation};
|
||||
use log::warn;
|
||||
use parking_lot::RwLock;
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
use std::fs::{File, OpenOptions, read_dir, read_to_string, remove_dir_all, remove_file};
|
||||
@@ -601,7 +602,7 @@ impl RequestContext {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn extract_role(&self, app: &AppConfig) -> Role {
|
||||
pub fn extract_role(&self, app: &AppConfig) -> Result<Role> {
|
||||
let mut role = if let Some(session) = self.session.as_ref() {
|
||||
session.to_role()
|
||||
} else if let Some(agent) = self.agent.as_ref() {
|
||||
@@ -627,7 +628,13 @@ impl RequestContext {
|
||||
}
|
||||
}
|
||||
|
||||
self.skill_registry.effective_role(&role)
|
||||
let policy = SkillPolicy::effective(
|
||||
app,
|
||||
self.role.as_ref(),
|
||||
self.agent.as_ref(),
|
||||
self.session.as_ref(),
|
||||
)?;
|
||||
Ok(self.skill_registry.effective_role(&role, &policy))
|
||||
}
|
||||
|
||||
pub fn auto_continue_config(&self) -> AutoContinueConfig {
|
||||
@@ -700,7 +707,7 @@ impl RequestContext {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_enabled_tools_on_role_like(&mut self, value: Option<String>) -> bool {
|
||||
pub fn set_enabled_tools_on_role_like(&mut self, value: Option<Vec<String>>) -> bool {
|
||||
match self.role_like_mut() {
|
||||
Some(role_like) => {
|
||||
role_like.set_enabled_tools(value);
|
||||
@@ -710,7 +717,7 @@ impl RequestContext {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_enabled_mcp_servers_on_role_like(&mut self, value: Option<String>) -> bool {
|
||||
pub fn set_enabled_mcp_servers_on_role_like(&mut self, value: Option<Vec<String>>) -> bool {
|
||||
match self.role_like_mut() {
|
||||
Some(role_like) => {
|
||||
role_like.set_enabled_mcp_servers(value);
|
||||
@@ -844,7 +851,7 @@ impl RequestContext {
|
||||
Some(rag) => rag.get_config(),
|
||||
None => (app.rag_reranker_model.clone(), app.rag_top_k),
|
||||
};
|
||||
let role = self.extract_role(app);
|
||||
let role = self.extract_role(app)?;
|
||||
let mut items = vec![
|
||||
("model", role.model().id()),
|
||||
(
|
||||
@@ -854,11 +861,11 @@ impl RequestContext {
|
||||
("top_p", super::format_option_value(&role.top_p())),
|
||||
(
|
||||
"enabled_tools",
|
||||
super::format_option_value(&role.enabled_tools()),
|
||||
super::format_option_value(&role.enabled_tools().map(|v| v.join(","))),
|
||||
),
|
||||
(
|
||||
"enabled_mcp_servers",
|
||||
super::format_option_value(&role.enabled_mcp_servers()),
|
||||
super::format_option_value(&role.enabled_mcp_servers().map(|v| v.join(","))),
|
||||
),
|
||||
(
|
||||
"max_output_tokens",
|
||||
@@ -1017,7 +1024,10 @@ impl RequestContext {
|
||||
|
||||
pub fn generate_prompt_context(&self, app: &AppConfig) -> HashMap<&str, String> {
|
||||
let mut output = HashMap::new();
|
||||
let role = self.extract_role(app);
|
||||
let role = self.extract_role(app).unwrap_or_else(|err| {
|
||||
warn!("failed to compute effective role for prompt rendering: {err}");
|
||||
Role::default()
|
||||
});
|
||||
output.insert("model", role.model().id());
|
||||
output.insert("client_name", role.model().client_name().to_string());
|
||||
output.insert("model_name", role.model().name().to_string());
|
||||
@@ -1148,10 +1158,10 @@ impl RequestContext {
|
||||
}
|
||||
|
||||
let mut tool_names: HashSet<String> = Default::default();
|
||||
if enabled_tools == "all" {
|
||||
if enabled_tools.iter().any(|s| s.trim() == "all") {
|
||||
tool_names.extend(declaration_names);
|
||||
} else {
|
||||
for item in enabled_tools.split(',') {
|
||||
for item in enabled_tools.iter() {
|
||||
let item = item.trim();
|
||||
if item.is_empty() {
|
||||
continue;
|
||||
@@ -1219,7 +1229,12 @@ impl RequestContext {
|
||||
.collect();
|
||||
|
||||
if let Some(ref tool_names) = role_filter {
|
||||
agent_functions.retain(|v| tool_names.contains(&v.name));
|
||||
agent_functions.retain(|v| {
|
||||
tool_names.contains(&v.name)
|
||||
|| (!matches!(agent.skills_enabled(), Some(false))
|
||||
&& v.name.starts_with(SKILL_FUNCTION_PREFIX))
|
||||
|| v.name.starts_with(USER_FUNCTION_PREFIX)
|
||||
});
|
||||
}
|
||||
|
||||
let tool_names: HashSet<String> = agent_functions
|
||||
@@ -1279,10 +1294,10 @@ impl RequestContext {
|
||||
}
|
||||
|
||||
let mut server_names: HashSet<String> = Default::default();
|
||||
if enabled_mcp_servers == "all" {
|
||||
if enabled_mcp_servers.iter().any(|s| s.trim() == "all") {
|
||||
server_names.extend(mcp_declaration_names);
|
||||
} else {
|
||||
for item in enabled_mcp_servers.split(',') {
|
||||
for item in enabled_mcp_servers.iter() {
|
||||
let item = item.trim();
|
||||
if item.is_empty() {
|
||||
continue;
|
||||
@@ -1714,14 +1729,49 @@ impl RequestContext {
|
||||
}
|
||||
}
|
||||
"enabled_tools" => {
|
||||
let value = super::parse_value(value)?;
|
||||
if !self.set_enabled_tools_on_role_like(value.clone()) {
|
||||
self.update_app_config(|app| app.enabled_tools = value);
|
||||
let raw: Option<String> = super::parse_value(value)?;
|
||||
let parsed: Option<Vec<String>> = raw.map(|s| super::csv_to_vec(&s));
|
||||
if !self.set_enabled_tools_on_role_like(parsed.clone()) {
|
||||
self.update_app_config(|app| app.enabled_tools = parsed.clone());
|
||||
}
|
||||
}
|
||||
"enabled_skills" => {
|
||||
let raw: Option<String> = super::parse_value(value)?;
|
||||
let parsed: Option<Vec<String>> = raw.map(|s| super::csv_to_vec(&s));
|
||||
if let Some(names) = parsed.as_ref() {
|
||||
let visible = self.app.config.visible_skills.as_deref();
|
||||
for name in names {
|
||||
paths::validate_skill_name(name)?;
|
||||
match visible {
|
||||
Some(vs) => {
|
||||
if !vs.iter().any(|s| s == name) {
|
||||
bail!(
|
||||
"skill '{name}' is not in the global 'visible_skills' allow-list"
|
||||
);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if !paths::has_skill(name) {
|
||||
bail!("skill '{name}' is not installed");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.update_app_config(|app| app.enabled_skills = parsed.clone());
|
||||
}
|
||||
"skills_enabled" => {
|
||||
let value: Option<bool> = super::parse_value(value)?;
|
||||
if let Some(session) = self.session.as_mut() {
|
||||
session.set_skills_enabled(value);
|
||||
} else {
|
||||
self.update_app_config(|app| app.skills_enabled = value.unwrap_or(true));
|
||||
}
|
||||
}
|
||||
"enabled_mcp_servers" => {
|
||||
let value: Option<String> = super::parse_value(value)?;
|
||||
if let Some(servers) = value.as_ref() {
|
||||
let raw: Option<String> = super::parse_value(value)?;
|
||||
let parsed: Option<Vec<String>> = raw.map(|s| super::csv_to_vec(&s));
|
||||
if let Some(servers) = parsed.as_ref() {
|
||||
let Some(mcp_config) = &self.app.mcp_config else {
|
||||
bail!(
|
||||
"No MCP servers are configured. Please configure MCP servers first before setting 'enabled_mcp_servers'."
|
||||
@@ -1733,7 +1783,7 @@ impl RequestContext {
|
||||
);
|
||||
}
|
||||
|
||||
if !servers.split(',').all(|s| {
|
||||
if !servers.iter().all(|s| {
|
||||
let server = s.trim();
|
||||
server == "all" || mcp_config.mcp_servers.contains_key(server)
|
||||
}) {
|
||||
@@ -1742,8 +1792,8 @@ impl RequestContext {
|
||||
);
|
||||
}
|
||||
}
|
||||
if !self.set_enabled_mcp_servers_on_role_like(value.clone()) {
|
||||
self.update_app_config(|app| app.enabled_mcp_servers = value.clone());
|
||||
if !self.set_enabled_mcp_servers_on_role_like(parsed.clone()) {
|
||||
self.update_app_config(|app| app.enabled_mcp_servers = parsed.clone());
|
||||
}
|
||||
if self.app.config.mcp_server_support {
|
||||
let app = Arc::clone(&self.app.config);
|
||||
@@ -1965,6 +2015,7 @@ impl RequestContext {
|
||||
"dry_run",
|
||||
"function_calling_support",
|
||||
"mcp_server_support",
|
||||
"skills_enabled",
|
||||
"stream",
|
||||
"save",
|
||||
"highlight",
|
||||
@@ -2063,6 +2114,14 @@ impl RequestContext {
|
||||
.collect()
|
||||
}
|
||||
"mcp_server_support" => super::complete_bool(app.mcp_server_support),
|
||||
"skills_enabled" => {
|
||||
let current = if let Some(session) = &self.session {
|
||||
session.skills_enabled()
|
||||
} else {
|
||||
Some(app.skills_enabled)
|
||||
};
|
||||
super::complete_option_bool(current)
|
||||
}
|
||||
"enabled_mcp_servers" => {
|
||||
let mut prefix = String::new();
|
||||
let mut ignores = HashSet::new();
|
||||
@@ -2141,7 +2200,7 @@ impl RequestContext {
|
||||
async fn rebuild_tool_scope(
|
||||
&mut self,
|
||||
app: &AppConfig,
|
||||
enabled_mcp_servers: Option<String>,
|
||||
enabled_mcp_servers: Option<Vec<String>>,
|
||||
abort_signal: AbortSignal,
|
||||
) -> Result<()> {
|
||||
let policy = SkillPolicy::effective(
|
||||
@@ -2153,21 +2212,23 @@ impl RequestContext {
|
||||
|
||||
let enabled_mcp_servers = if policy.skills_enabled && app.mcp_server_support {
|
||||
let skill_mcps = self.skill_registry.loaded_mcp_servers();
|
||||
match (enabled_mcp_servers.as_deref(), skill_mcps.is_empty()) {
|
||||
(Some("all"), _) | (_, true) => enabled_mcp_servers,
|
||||
(base, false) => {
|
||||
let has_all = enabled_mcp_servers
|
||||
.as_ref()
|
||||
.map(|v| v.iter().any(|s| s.trim() == "all"))
|
||||
.unwrap_or(false);
|
||||
if has_all || skill_mcps.is_empty() {
|
||||
enabled_mcp_servers
|
||||
} else {
|
||||
let mut merged: BTreeSet<String> = skill_mcps;
|
||||
if let Some(s) = base {
|
||||
for token in s.split(',') {
|
||||
if let Some(servers) = &enabled_mcp_servers {
|
||||
for token in servers {
|
||||
let t = token.trim();
|
||||
if !t.is_empty() {
|
||||
merged.insert(t.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(merged.into_iter().collect::<Vec<_>>().join(","))
|
||||
}
|
||||
Some(merged.into_iter().collect())
|
||||
}
|
||||
} else {
|
||||
enabled_mcp_servers
|
||||
@@ -2179,12 +2240,12 @@ impl RequestContext {
|
||||
&& let Some(mcp_config) = &self.app.mcp_config
|
||||
{
|
||||
let server_ids: Vec<String> = match &enabled_mcp_servers {
|
||||
Some(servers) if servers == "all" => {
|
||||
Some(servers) if servers.iter().any(|s| s.trim() == "all") => {
|
||||
mcp_config.mcp_servers.keys().cloned().collect()
|
||||
}
|
||||
Some(servers) => {
|
||||
let mut ids = Vec::new();
|
||||
for item in servers.split(',').map(|s| s.trim()) {
|
||||
for item in servers.iter().map(|s| s.trim()) {
|
||||
if mcp_config.mcp_servers.contains_key(item) {
|
||||
ids.push(item.to_string());
|
||||
} else if let Some(mapped) = app.mapping_mcp_servers.get(item) {
|
||||
@@ -2263,7 +2324,7 @@ impl RequestContext {
|
||||
if names.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(names.join(","))
|
||||
Some(names.to_vec())
|
||||
}
|
||||
} else if let Some(role) = &self.role {
|
||||
role.enabled_mcp_servers()
|
||||
@@ -2330,12 +2391,12 @@ impl RequestContext {
|
||||
format!("Failed to cleanup previous '{TEMP_SESSION_NAME}' session")
|
||||
})?;
|
||||
}
|
||||
session = Some(Session::new_from_ctx(self, app, TEMP_SESSION_NAME));
|
||||
session = Some(Session::new_from_ctx(self, app, TEMP_SESSION_NAME)?);
|
||||
}
|
||||
Some(name) => {
|
||||
let session_path = self.session_file(name);
|
||||
if !session_path.exists() {
|
||||
session = Some(Session::new_from_ctx(self, app, name));
|
||||
session = Some(Session::new_from_ctx(self, app, name)?);
|
||||
} else {
|
||||
session = Some(Session::load_from_ctx(self, app, name, &session_path)?);
|
||||
}
|
||||
@@ -2423,7 +2484,7 @@ impl RequestContext {
|
||||
}
|
||||
|
||||
let mcp_servers = if app.mcp_server_support {
|
||||
(!agent.mcp_server_names().is_empty()).then(|| agent.mcp_server_names().join(","))
|
||||
(!agent.mcp_server_names().is_empty()).then(|| agent.mcp_server_names().to_vec())
|
||||
} else {
|
||||
if !agent.mcp_server_names().is_empty() {
|
||||
bail!(
|
||||
@@ -2550,6 +2611,7 @@ impl RequestContext {
|
||||
}
|
||||
|
||||
pub fn upsert_skill(&self, app: &AppConfig, name: &str) -> Result<()> {
|
||||
paths::validate_skill_name(name)?;
|
||||
let path = paths::skill_file(name);
|
||||
ensure_parent_exists(&path)?;
|
||||
let is_new = !path.exists();
|
||||
@@ -2568,6 +2630,7 @@ impl RequestContext {
|
||||
}
|
||||
|
||||
pub async fn load_skill_repl(&mut self, name: &str, abort_signal: AbortSignal) -> Result<()> {
|
||||
paths::validate_skill_name(name)?;
|
||||
if !self.app.config.function_calling_support {
|
||||
bail!(
|
||||
"Skills require function calling, which is disabled. Enable function calling in your config then try again."
|
||||
@@ -2599,7 +2662,7 @@ impl RequestContext {
|
||||
let skill = Skill::load(name)?;
|
||||
let needs_mcps = skill
|
||||
.enabled_mcp_servers()
|
||||
.map(|s| !s.trim().is_empty())
|
||||
.map(|v| !v.is_empty())
|
||||
.unwrap_or(false);
|
||||
|
||||
if needs_mcps && !self.app.config.mcp_server_support {
|
||||
@@ -2608,7 +2671,9 @@ impl RequestContext {
|
||||
|
||||
self.skill_registry.insert(skill)?;
|
||||
if let Err(e) = self.refresh_tool_scope(abort_signal).await {
|
||||
let _ = self.skill_registry.unload(name);
|
||||
if let Err(unload_err) = self.skill_registry.unload(name) {
|
||||
warn!("Failed to unload skill '{name}' during error recovery: {unload_err}");
|
||||
}
|
||||
bail!("Loaded skill '{name}' but failed to refresh tool scope: {e}");
|
||||
}
|
||||
|
||||
@@ -2617,10 +2682,15 @@ impl RequestContext {
|
||||
}
|
||||
|
||||
pub async fn unload_skill_repl(&mut self, name: &str, abort_signal: AbortSignal) -> Result<()> {
|
||||
self.skill_registry.unload(name)?;
|
||||
let skill = self.skill_registry.unload(name)?;
|
||||
|
||||
if let Err(e) = self.refresh_tool_scope(abort_signal).await {
|
||||
eprintln!("Warning: unloaded skill '{name}' but tool scope refresh failed: {e}");
|
||||
if let Err(restore_err) = self.skill_registry.insert(skill) {
|
||||
warn!(
|
||||
"Failed to restore skill '{name}' after tool-scope refresh failure: {restore_err}"
|
||||
);
|
||||
}
|
||||
bail!("Unloaded skill '{name}' but failed to refresh tool scope; restored: {e}");
|
||||
}
|
||||
|
||||
println!("✓ Unloaded skill '{name}'.");
|
||||
@@ -2706,13 +2776,13 @@ impl RequestContext {
|
||||
&self,
|
||||
app: &AppConfig,
|
||||
start_mcp_servers: bool,
|
||||
) -> Option<String> {
|
||||
) -> Option<Vec<String>> {
|
||||
if !start_mcp_servers || !app.mcp_server_support {
|
||||
return None;
|
||||
}
|
||||
if let Some(agent) = self.agent.as_ref() {
|
||||
return (!agent.mcp_server_names().is_empty())
|
||||
.then(|| agent.mcp_server_names().join(","));
|
||||
.then(|| agent.mcp_server_names().to_vec());
|
||||
}
|
||||
if let Some(session) = self.session.as_ref() {
|
||||
return session.enabled_mcp_servers();
|
||||
@@ -2752,7 +2822,7 @@ impl RequestContext {
|
||||
.summarization_prompt
|
||||
.clone()
|
||||
.unwrap_or_else(|| SUMMARIZATION_PROMPT.into());
|
||||
let input = Input::from_str(self, &prompt, None);
|
||||
let input = Input::from_str(self, &prompt, None)?;
|
||||
let summary = input.fetch_chat_text().await?;
|
||||
let summary_context_prompt = self
|
||||
.app
|
||||
@@ -2787,7 +2857,7 @@ impl RequestContext {
|
||||
None => bail!("No chat history"),
|
||||
};
|
||||
let role = self.retrieve_role(app, CREATE_TITLE_ROLE)?;
|
||||
let input = Input::from_str(self, &text, Some(role));
|
||||
let input = Input::from_str(self, &text, Some(role))?;
|
||||
let text = input.fetch_chat_text().await?;
|
||||
if let Some(session) = self.session.as_mut() {
|
||||
session.set_autoname(&text);
|
||||
@@ -3041,7 +3111,7 @@ mod tests {
|
||||
let app = ctx.app.config.clone();
|
||||
let role = Role::new("myrole", "my prompt");
|
||||
ctx.use_role_obj(role).unwrap();
|
||||
let extracted = ctx.extract_role(&app);
|
||||
let extracted = ctx.extract_role(&app).unwrap();
|
||||
assert_eq!(extracted.name(), "myrole");
|
||||
}
|
||||
|
||||
@@ -3049,7 +3119,7 @@ mod tests {
|
||||
fn extract_role_returns_default_when_nothing_active() {
|
||||
let ctx = create_test_ctx();
|
||||
let app = ctx.app.config.clone();
|
||||
let extracted = ctx.extract_role(&app);
|
||||
let extracted = ctx.extract_role(&app).unwrap();
|
||||
assert_eq!(extracted.name(), "");
|
||||
}
|
||||
|
||||
@@ -3205,7 +3275,7 @@ mod tests {
|
||||
let app = ctx.app.config.clone();
|
||||
let abort = utils::create_abort_signal();
|
||||
|
||||
run_async(ctx.rebuild_tool_scope(&app, Some("all".to_string()), abort)).unwrap();
|
||||
run_async(ctx.rebuild_tool_scope(&app, Some(vec!["all".to_string()]), abort)).unwrap();
|
||||
|
||||
assert!(ctx.tool_scope.mcp_runtime.is_empty());
|
||||
}
|
||||
@@ -3233,7 +3303,7 @@ mod tests {
|
||||
let app = ctx.app.config.clone();
|
||||
let abort = utils::create_abort_signal();
|
||||
|
||||
run_async(ctx.rebuild_tool_scope(&app, Some("all".to_string()), abort)).unwrap();
|
||||
run_async(ctx.rebuild_tool_scope(&app, Some(vec!["all".to_string()]), abort)).unwrap();
|
||||
|
||||
assert!(ctx.tool_scope.mcp_runtime.is_empty());
|
||||
}
|
||||
@@ -3341,7 +3411,7 @@ mod tests {
|
||||
};
|
||||
let ctx = RequestContext::new(app_state, WorkingMode::Cmd);
|
||||
let mut role = Role::new("r", "p");
|
||||
role.set_enabled_tools(Some("all".to_string()));
|
||||
role.set_enabled_tools(Some(vec!["all".to_string()]));
|
||||
assert!(ctx.select_functions(&role).is_none());
|
||||
}
|
||||
|
||||
@@ -3352,7 +3422,7 @@ mod tests {
|
||||
ctx.tool_scope.functions.append_user_interaction_functions();
|
||||
|
||||
let mut role = Role::new("r", "p");
|
||||
role.set_enabled_tools(Some("all".to_string()));
|
||||
role.set_enabled_tools(Some(vec!["all".to_string()]));
|
||||
|
||||
let fns = ctx.select_functions(&role).unwrap();
|
||||
let names: Vec<&str> = fns.iter().map(|f| f.name.as_str()).collect();
|
||||
@@ -3366,7 +3436,10 @@ mod tests {
|
||||
ctx.tool_scope.functions.append_todo_functions();
|
||||
|
||||
let mut role = Role::new("r", "p");
|
||||
role.set_enabled_tools(Some("todo__init, todo__add".to_string()));
|
||||
role.set_enabled_tools(Some(vec![
|
||||
"todo__init".to_string(),
|
||||
"todo__add".to_string(),
|
||||
]));
|
||||
|
||||
let fns = ctx.select_functions(&role).unwrap();
|
||||
let names: Vec<&str> = fns.iter().map(|f| f.name.as_str()).collect();
|
||||
@@ -3395,7 +3468,7 @@ mod tests {
|
||||
};
|
||||
let ctx = RequestContext::new(app_state, WorkingMode::Cmd);
|
||||
let mut role = Role::new("r", "p");
|
||||
role.set_enabled_mcp_servers(Some("all".to_string()));
|
||||
role.set_enabled_mcp_servers(Some(vec!["all".to_string()]));
|
||||
let result = ctx.select_enabled_mcp_servers(&role);
|
||||
assert!(result.is_empty());
|
||||
}
|
||||
@@ -3408,7 +3481,7 @@ mod tests {
|
||||
.append_mcp_meta_functions(vec!["github".into(), "slack".into()]);
|
||||
|
||||
let mut role = Role::new("r", "p");
|
||||
role.set_enabled_mcp_servers(Some("all".to_string()));
|
||||
role.set_enabled_mcp_servers(Some(vec!["all".to_string()]));
|
||||
|
||||
let fns = ctx.select_enabled_mcp_servers(&role);
|
||||
let names: Vec<&str> = fns.iter().map(|f| f.name.as_str()).collect();
|
||||
@@ -3425,7 +3498,7 @@ mod tests {
|
||||
.append_mcp_meta_functions(vec!["github".into(), "slack".into()]);
|
||||
|
||||
let mut role = Role::new("r", "p");
|
||||
role.set_enabled_mcp_servers(Some("github".to_string()));
|
||||
role.set_enabled_mcp_servers(Some(vec!["github".to_string()]));
|
||||
|
||||
let fns = ctx.select_enabled_mcp_servers(&role);
|
||||
let names: Vec<&str> = fns.iter().map(|f| f.name.as_str()).collect();
|
||||
@@ -3537,7 +3610,7 @@ mod tests {
|
||||
#[test]
|
||||
fn discontinuous_last_message_sets_continuous_false() {
|
||||
let mut ctx = create_test_ctx();
|
||||
let input = Input::from_str(&ctx, "test", None);
|
||||
let input = Input::from_str(&ctx, "test", None).unwrap();
|
||||
ctx.last_message = Some(LastMessage::new(input, "reply".to_string()));
|
||||
assert!(ctx.last_message.as_ref().unwrap().continuous);
|
||||
ctx.discontinuous_last_message();
|
||||
@@ -3555,7 +3628,7 @@ mod tests {
|
||||
#[test]
|
||||
fn before_chat_completion_sets_last_message() {
|
||||
let mut ctx = create_test_ctx();
|
||||
let input = Input::from_str(&ctx, "hello", None);
|
||||
let input = Input::from_str(&ctx, "hello", None).unwrap();
|
||||
ctx.before_chat_completion(&input).unwrap();
|
||||
assert!(ctx.last_message.is_some());
|
||||
let lm = ctx.last_message.as_ref().unwrap();
|
||||
@@ -3579,7 +3652,7 @@ mod tests {
|
||||
ctx.skill_registry.insert(ephemeral).unwrap();
|
||||
ctx.skill_registry.insert(persistent).unwrap();
|
||||
|
||||
let input = Input::from_str(&ctx, "hello", None);
|
||||
let input = Input::from_str(&ctx, "hello", None).unwrap();
|
||||
let app = Arc::clone(&ctx.app.config);
|
||||
ctx.after_chat_completion(app.as_ref(), &input, "response", &[])
|
||||
.unwrap();
|
||||
@@ -3602,7 +3675,7 @@ mod tests {
|
||||
let ephemeral = Skill::new("ephemeral", "---\nauto_unload: true\n---\nbody");
|
||||
ctx.skill_registry.insert(ephemeral).unwrap();
|
||||
|
||||
let input = Input::from_str(&ctx, "hello", None);
|
||||
let input = Input::from_str(&ctx, "hello", None).unwrap();
|
||||
let app = Arc::clone(&ctx.app.config);
|
||||
let tool_result =
|
||||
ToolResult::new(crate::function::ToolCall::default(), serde_json::json!({}));
|
||||
@@ -3764,7 +3837,7 @@ mod tests {
|
||||
fn session_new_from_ctx_captures_state() {
|
||||
let _guard = TestConfigDirGuard::new();
|
||||
let ctx = create_test_ctx();
|
||||
let session = Session::new_from_ctx(&ctx, &ctx.app.config, "test-session");
|
||||
let session = Session::new_from_ctx(&ctx, &ctx.app.config, "test-session").unwrap();
|
||||
assert_eq!(session.name(), "test-session");
|
||||
assert!(session.is_empty());
|
||||
}
|
||||
@@ -3774,7 +3847,7 @@ mod tests {
|
||||
fn session_save_creates_file() {
|
||||
let _guard = TestConfigDirGuard::new();
|
||||
let ctx = create_test_ctx();
|
||||
let mut session = Session::new_from_ctx(&ctx, &ctx.app.config, "save-test");
|
||||
let mut session = Session::new_from_ctx(&ctx, &ctx.app.config, "save-test").unwrap();
|
||||
let session_path = ctx.session_file("save-test");
|
||||
ensure_parent_exists(&session_path).unwrap();
|
||||
|
||||
|
||||
+71
-27
@@ -28,13 +28,13 @@ pub trait RoleLike {
|
||||
fn model(&self) -> &Model;
|
||||
fn temperature(&self) -> Option<f64>;
|
||||
fn top_p(&self) -> Option<f64>;
|
||||
fn enabled_tools(&self) -> Option<String>;
|
||||
fn enabled_mcp_servers(&self) -> Option<String>;
|
||||
fn enabled_tools(&self) -> Option<Vec<String>>;
|
||||
fn enabled_mcp_servers(&self) -> Option<Vec<String>>;
|
||||
fn set_model(&mut self, model: Model);
|
||||
fn set_temperature(&mut self, value: Option<f64>);
|
||||
fn set_top_p(&mut self, value: Option<f64>);
|
||||
fn set_enabled_tools(&mut self, value: Option<String>);
|
||||
fn set_enabled_mcp_servers(&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>>);
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||
@@ -51,14 +51,26 @@ pub struct Role {
|
||||
temperature: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
top_p: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
enabled_tools: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
enabled_mcp_servers: Option<String>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "super::deserialize_csv_or_vec"
|
||||
)]
|
||||
enabled_tools: Option<Vec<String>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "super::deserialize_csv_or_vec"
|
||||
)]
|
||||
enabled_mcp_servers: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
skills_enabled: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
enabled_skills: Option<String>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "super::deserialize_csv_or_vec"
|
||||
)]
|
||||
enabled_skills: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
auto_continue: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -98,12 +110,12 @@ impl Role {
|
||||
"model" => role.model_id = value.as_str().map(|v| v.to_string()),
|
||||
"temperature" => role.temperature = value.as_f64(),
|
||||
"top_p" => role.top_p = value.as_f64(),
|
||||
"enabled_tools" => role.enabled_tools = value.as_str().map(|v| v.to_string()),
|
||||
"enabled_tools" => role.enabled_tools = parse_string_or_array(value),
|
||||
"enabled_mcp_servers" => {
|
||||
role.enabled_mcp_servers = value.as_str().map(|v| v.to_string())
|
||||
role.enabled_mcp_servers = parse_string_or_array(value)
|
||||
}
|
||||
"skills_enabled" => role.skills_enabled = value.as_bool(),
|
||||
"enabled_skills" => role.enabled_skills = value.as_str().map(|v| v.to_string()),
|
||||
"enabled_skills" => role.enabled_skills = parse_string_or_array(value),
|
||||
"auto_continue" => role.auto_continue = value.as_bool(),
|
||||
"max_auto_continues" => {
|
||||
role.max_auto_continues = value.as_u64().map(|v| v as usize)
|
||||
@@ -147,17 +159,21 @@ impl Role {
|
||||
if let Some(top_p) = self.top_p() {
|
||||
metadata.push(format!("top_p: {top_p}"));
|
||||
}
|
||||
if let Some(enabled_tools) = self.enabled_tools() {
|
||||
metadata.push(format!("enabled_tools: {enabled_tools}"));
|
||||
if let Some(enabled_tools) = &self.enabled_tools {
|
||||
let inline = serde_json::to_string(enabled_tools).unwrap_or_else(|_| "[]".to_string());
|
||||
metadata.push(format!("enabled_tools: {inline}"));
|
||||
}
|
||||
if let Some(enabled_mcp_servers) = self.enabled_mcp_servers() {
|
||||
metadata.push(format!("enabled_mcp_servers: {enabled_mcp_servers}"));
|
||||
if let Some(enabled_mcp_servers) = &self.enabled_mcp_servers {
|
||||
let inline =
|
||||
serde_json::to_string(enabled_mcp_servers).unwrap_or_else(|_| "[]".to_string());
|
||||
metadata.push(format!("enabled_mcp_servers: {inline}"));
|
||||
}
|
||||
if let Some(skills_enabled) = self.skills_enabled {
|
||||
metadata.push(format!("skills_enabled: {skills_enabled}"));
|
||||
}
|
||||
if let Some(enabled_skills) = &self.enabled_skills {
|
||||
metadata.push(format!("enabled_skills: {enabled_skills}"));
|
||||
let inline = serde_json::to_string(enabled_skills).unwrap_or_else(|_| "[]".to_string());
|
||||
metadata.push(format!("enabled_skills: {inline}"));
|
||||
}
|
||||
if let Some(auto_continue) = self.auto_continue {
|
||||
metadata.push(format!("auto_continue: {auto_continue}"));
|
||||
@@ -225,8 +241,8 @@ impl Role {
|
||||
model: &Model,
|
||||
temperature: Option<f64>,
|
||||
top_p: Option<f64>,
|
||||
enabled_tools: Option<String>,
|
||||
enabled_mcp_servers: Option<String>,
|
||||
enabled_tools: Option<Vec<String>>,
|
||||
enabled_mcp_servers: Option<Vec<String>>,
|
||||
) {
|
||||
self.set_model(model.clone());
|
||||
if temperature.is_some() {
|
||||
@@ -287,7 +303,7 @@ impl Role {
|
||||
self.skills_enabled
|
||||
}
|
||||
|
||||
pub fn enabled_skills(&self) -> Option<&str> {
|
||||
pub fn enabled_skills(&self) -> Option<&[String]> {
|
||||
self.enabled_skills.as_deref()
|
||||
}
|
||||
|
||||
@@ -360,11 +376,11 @@ impl RoleLike for Role {
|
||||
self.top_p
|
||||
}
|
||||
|
||||
fn enabled_tools(&self) -> Option<String> {
|
||||
fn enabled_tools(&self) -> Option<Vec<String>> {
|
||||
self.enabled_tools.clone()
|
||||
}
|
||||
|
||||
fn enabled_mcp_servers(&self) -> Option<String> {
|
||||
fn enabled_mcp_servers(&self) -> Option<Vec<String>> {
|
||||
self.enabled_mcp_servers.clone()
|
||||
}
|
||||
|
||||
@@ -383,15 +399,37 @@ impl RoleLike for Role {
|
||||
self.top_p = value;
|
||||
}
|
||||
|
||||
fn set_enabled_tools(&mut self, value: Option<String>) {
|
||||
fn set_enabled_tools(&mut self, value: Option<Vec<String>>) {
|
||||
self.enabled_tools = value;
|
||||
}
|
||||
|
||||
fn set_enabled_mcp_servers(&mut self, value: Option<String>) {
|
||||
fn set_enabled_mcp_servers(&mut self, value: Option<Vec<String>>) {
|
||||
self.enabled_mcp_servers = value;
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_string_or_array(value: &Value) -> Option<Vec<String>> {
|
||||
if value.is_null() {
|
||||
return None;
|
||||
}
|
||||
|
||||
if let Some(s) = value.as_str() {
|
||||
return Some(csv_to_vec(s));
|
||||
}
|
||||
|
||||
if let Some(arr) = value.as_array() {
|
||||
let items: Vec<String> = arr
|
||||
.iter()
|
||||
.filter_map(|v| v.as_str().map(|s| s.trim().to_string()))
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect();
|
||||
|
||||
return Some(items);
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn parse_structure_prompt(prompt: &str) -> (&str, Vec<(&str, &str)>) {
|
||||
let mut text = prompt;
|
||||
let mut search_input = true;
|
||||
@@ -466,14 +504,20 @@ mod tests {
|
||||
fn role_new_parses_enabled_tools() {
|
||||
let content = "---\nenabled_tools: tool1,tool2\n---\nPrompt";
|
||||
let role = Role::new("test", content);
|
||||
assert_eq!(role.enabled_tools(), Some("tool1,tool2".to_string()));
|
||||
assert_eq!(
|
||||
role.enabled_tools(),
|
||||
Some(vec!["tool1".to_string(), "tool2".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn role_new_parses_enabled_mcp_servers() {
|
||||
let content = "---\nenabled_mcp_servers: github,jira\n---\nPrompt";
|
||||
let role = Role::new("test", content);
|
||||
assert_eq!(role.enabled_mcp_servers(), Some("github,jira".to_string()));
|
||||
assert_eq!(
|
||||
role.enabled_mcp_servers(),
|
||||
Some(vec!["github".to_string(), "jira".to_string()])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+52
-19
@@ -24,14 +24,26 @@ pub struct Session {
|
||||
temperature: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
top_p: Option<f64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
enabled_tools: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
enabled_mcp_servers: Option<String>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "super::deserialize_csv_or_vec"
|
||||
)]
|
||||
enabled_tools: Option<Vec<String>>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "super::deserialize_csv_or_vec"
|
||||
)]
|
||||
enabled_mcp_servers: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
skills_enabled: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
enabled_skills: Option<String>,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "super::deserialize_csv_or_vec"
|
||||
)]
|
||||
enabled_skills: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
save_session: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -83,12 +95,19 @@ impl Session {
|
||||
self.skills_enabled
|
||||
}
|
||||
|
||||
pub fn enabled_skills(&self) -> Option<&str> {
|
||||
pub fn enabled_skills(&self) -> Option<&[String]> {
|
||||
self.enabled_skills.as_deref()
|
||||
}
|
||||
|
||||
pub fn new_from_ctx(ctx: &RequestContext, app: &AppConfig, name: &str) -> Self {
|
||||
let role = ctx.extract_role(app);
|
||||
pub fn set_skills_enabled(&mut self, value: Option<bool>) {
|
||||
if self.skills_enabled != value {
|
||||
self.skills_enabled = value;
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_from_ctx(ctx: &RequestContext, app: &AppConfig, name: &str) -> Result<Self> {
|
||||
let role = ctx.extract_role(app)?;
|
||||
let mut session = Self {
|
||||
name: name.to_string(),
|
||||
save_session: app.save_session,
|
||||
@@ -96,7 +115,7 @@ impl Session {
|
||||
};
|
||||
session.set_role(role);
|
||||
session.dirty = false;
|
||||
session
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
pub fn load_from_ctx(
|
||||
@@ -182,10 +201,16 @@ impl Session {
|
||||
data["top_p"] = top_p.into();
|
||||
}
|
||||
if let Some(enabled_tools) = self.enabled_tools() {
|
||||
data["enabled_tools"] = enabled_tools.into();
|
||||
data["enabled_tools"] = json!(enabled_tools);
|
||||
}
|
||||
if let Some(enabled_mcp_servers) = self.enabled_mcp_servers() {
|
||||
data["enabled_mcp_servers"] = enabled_mcp_servers.into();
|
||||
data["enabled_mcp_servers"] = json!(enabled_mcp_servers);
|
||||
}
|
||||
if let Some(skills_enabled) = self.skills_enabled() {
|
||||
data["skills_enabled"] = skills_enabled.into();
|
||||
}
|
||||
if let Some(enabled_skills) = self.enabled_skills() {
|
||||
data["enabled_skills"] = json!(enabled_skills);
|
||||
}
|
||||
if let Some(save_session) = self.save_session() {
|
||||
data["save_session"] = save_session.into();
|
||||
@@ -242,11 +267,19 @@ impl Session {
|
||||
}
|
||||
|
||||
if let Some(enabled_tools) = self.enabled_tools() {
|
||||
items.push(("enabled_tools", enabled_tools));
|
||||
items.push(("enabled_tools", enabled_tools.join(",")));
|
||||
}
|
||||
|
||||
if let Some(enabled_mcp_servers) = self.enabled_mcp_servers() {
|
||||
items.push(("enabled_mcp_servers", enabled_mcp_servers));
|
||||
items.push(("enabled_mcp_servers", enabled_mcp_servers.join(",")));
|
||||
}
|
||||
|
||||
if let Some(skills_enabled) = self.skills_enabled() {
|
||||
items.push(("skills_enabled", skills_enabled.to_string()));
|
||||
}
|
||||
|
||||
if let Some(enabled_skills) = self.enabled_skills() {
|
||||
items.push(("enabled_skills", enabled_skills.join(",")));
|
||||
}
|
||||
|
||||
if let Some(save_session) = self.save_session() {
|
||||
@@ -682,11 +715,11 @@ impl RoleLike for Session {
|
||||
self.top_p
|
||||
}
|
||||
|
||||
fn enabled_tools(&self) -> Option<String> {
|
||||
fn enabled_tools(&self) -> Option<Vec<String>> {
|
||||
self.enabled_tools.clone()
|
||||
}
|
||||
|
||||
fn enabled_mcp_servers(&self) -> Option<String> {
|
||||
fn enabled_mcp_servers(&self) -> Option<Vec<String>> {
|
||||
self.enabled_mcp_servers.clone()
|
||||
}
|
||||
|
||||
@@ -713,14 +746,14 @@ impl RoleLike for Session {
|
||||
}
|
||||
}
|
||||
|
||||
fn set_enabled_tools(&mut self, value: Option<String>) {
|
||||
fn set_enabled_tools(&mut self, value: Option<Vec<String>>) {
|
||||
if self.enabled_tools != value {
|
||||
self.enabled_tools = value;
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn set_enabled_mcp_servers(&mut self, value: Option<String>) {
|
||||
fn set_enabled_mcp_servers(&mut self, value: Option<Vec<String>>) {
|
||||
if self.enabled_mcp_servers != value {
|
||||
self.enabled_mcp_servers = value;
|
||||
self.dirty = true;
|
||||
@@ -784,7 +817,7 @@ mod tests {
|
||||
functions: Functions::default(),
|
||||
});
|
||||
let ctx = RequestContext::new(app_state, WorkingMode::Cmd);
|
||||
let session = Session::new_from_ctx(&ctx, &app_config, "test-session");
|
||||
let session = Session::new_from_ctx(&ctx, &app_config, "test-session").unwrap();
|
||||
|
||||
assert_eq!(session.name(), "test-session");
|
||||
assert_eq!(session.save_session(), app_config.save_session);
|
||||
|
||||
+34
-9
@@ -33,9 +33,9 @@ pub struct Skill {
|
||||
#[serde(default)]
|
||||
body: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
enabled_tools: Option<String>,
|
||||
enabled_tools: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
enabled_mcp_servers: Option<String>,
|
||||
enabled_mcp_servers: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
auto_unload: Option<bool>,
|
||||
}
|
||||
@@ -69,10 +69,10 @@ impl Skill {
|
||||
}
|
||||
}
|
||||
"enabled_tools" => {
|
||||
skill.enabled_tools = value.as_str().map(|v| v.to_string());
|
||||
skill.enabled_tools = parse_skill_string_or_array(value);
|
||||
}
|
||||
"enabled_mcp_servers" => {
|
||||
skill.enabled_mcp_servers = value.as_str().map(|v| v.to_string());
|
||||
skill.enabled_mcp_servers = parse_skill_string_or_array(value);
|
||||
}
|
||||
"auto_unload" => {
|
||||
skill.auto_unload = value.as_bool();
|
||||
@@ -116,6 +116,7 @@ impl Skill {
|
||||
}
|
||||
|
||||
pub fn load(name: &str) -> Result<Self> {
|
||||
paths::validate_skill_name(name)?;
|
||||
let path = paths::skill_file(name);
|
||||
let content = read_to_string(&path)
|
||||
.with_context(|| format!("Failed to read skill '{name}' at {}", path.display()))?;
|
||||
@@ -134,11 +135,11 @@ impl Skill {
|
||||
&self.body
|
||||
}
|
||||
|
||||
pub fn enabled_tools(&self) -> Option<&str> {
|
||||
pub fn enabled_tools(&self) -> Option<&[String]> {
|
||||
self.enabled_tools.as_deref()
|
||||
}
|
||||
|
||||
pub fn enabled_mcp_servers(&self) -> Option<&str> {
|
||||
pub fn enabled_mcp_servers(&self) -> Option<&[String]> {
|
||||
self.enabled_mcp_servers.as_deref()
|
||||
}
|
||||
|
||||
@@ -157,11 +158,29 @@ impl Skill {
|
||||
fn declares_mcp_servers(&self) -> bool {
|
||||
self.enabled_mcp_servers
|
||||
.as_deref()
|
||||
.map(|s| !s.trim().is_empty())
|
||||
.map(|servers| !servers.is_empty())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_skill_string_or_array(value: &Value) -> Option<Vec<String>> {
|
||||
if value.is_null() {
|
||||
return None;
|
||||
}
|
||||
if let Some(s) = value.as_str() {
|
||||
return Some(csv_to_vec(s));
|
||||
}
|
||||
if let Some(arr) = value.as_array() {
|
||||
let items: Vec<String> = arr
|
||||
.iter()
|
||||
.filter_map(|v| v.as_str().map(|s| s.trim().to_string()))
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect();
|
||||
return Some(items);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -189,8 +208,14 @@ mod tests {
|
||||
|
||||
assert_eq!(skill.name(), "git-master");
|
||||
assert_eq!(skill.description(), "Atomic commits, rebase surgery");
|
||||
assert_eq!(skill.enabled_tools(), Some("shell,fs"));
|
||||
assert_eq!(skill.enabled_mcp_servers(), Some("github"));
|
||||
assert_eq!(
|
||||
skill.enabled_tools(),
|
||||
Some(["shell".to_string(), "fs".to_string()].as_slice())
|
||||
);
|
||||
assert_eq!(
|
||||
skill.enabled_mcp_servers(),
|
||||
Some(["github".to_string()].as_slice())
|
||||
);
|
||||
assert!(skill.auto_unload());
|
||||
assert_eq!(skill.body(), "You are a git expert");
|
||||
}
|
||||
|
||||
+26
-23
@@ -4,7 +4,7 @@ use super::paths;
|
||||
use super::role::Role;
|
||||
use super::session::Session;
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -67,27 +67,35 @@ impl SkillPolicy {
|
||||
.map(|v| v.iter().cloned().collect());
|
||||
|
||||
let enabled_raw: Option<Vec<String>> = session
|
||||
.and_then(|s| parse_csv_opt(s.enabled_skills()))
|
||||
.and_then(|s| s.enabled_skills().map(|v| v.to_vec()))
|
||||
.or_else(|| agent.and_then(|a| a.enabled_skills().map(|v| v.to_vec())))
|
||||
.or_else(|| role.and_then(|r| parse_csv_opt(r.enabled_skills())))
|
||||
.or_else(|| parse_csv_opt(global.enabled_skills.as_deref()));
|
||||
.or_else(|| role.and_then(|r| r.enabled_skills().map(|v| v.to_vec())))
|
||||
.or_else(|| global.enabled_skills.clone());
|
||||
|
||||
let enabled: HashSet<String> = match enabled_raw {
|
||||
Some(explicit) => {
|
||||
let set: HashSet<String> = explicit.into_iter().collect();
|
||||
for name in &set {
|
||||
if !skill_exists(name) {
|
||||
bail!("enabled_skills references skill '{name}' which is not installed");
|
||||
}
|
||||
|
||||
if let Some(vs) = &visible
|
||||
&& !vs.contains(name)
|
||||
{
|
||||
paths::validate_skill_name(name).map_err(|e| {
|
||||
anyhow!("enabled_skills contains invalid name '{name}': {e}")
|
||||
})?;
|
||||
match &visible {
|
||||
Some(vs) => {
|
||||
if !vs.contains(name) {
|
||||
bail!(
|
||||
"enabled_skills references skill '{name}' which is not in visible_skills"
|
||||
"enabled_skills references skill '{name}' which is not in the global 'visible_skills' allow-list"
|
||||
);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if !skill_exists(name) {
|
||||
bail!(
|
||||
"enabled_skills references skill '{name}' which is not installed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
set
|
||||
}
|
||||
None => match &visible {
|
||||
@@ -107,17 +115,9 @@ impl SkillPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_csv_opt(s: Option<&str>) -> Option<Vec<String>> {
|
||||
s.map(|raw| {
|
||||
raw.split(',')
|
||||
.map(|t| t.trim().to_string())
|
||||
.filter(|t| !t.is_empty())
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::csv_to_vec;
|
||||
use super::*;
|
||||
|
||||
fn always_true(_: &str) -> bool {
|
||||
@@ -135,7 +135,7 @@ mod tests {
|
||||
) -> AppConfig {
|
||||
AppConfig {
|
||||
skills_enabled,
|
||||
enabled_skills: enabled.map(|s| s.to_string()),
|
||||
enabled_skills: enabled.map(csv_to_vec),
|
||||
visible_skills: visible.map(|v| v.iter().map(|s| s.to_string()).collect()),
|
||||
..AppConfig::default()
|
||||
}
|
||||
@@ -277,7 +277,10 @@ mod tests {
|
||||
SkillPolicy::effective_with(&global, None, None, None, &always_true, &empty_installed)
|
||||
.unwrap_err();
|
||||
|
||||
assert!(err.to_string().contains("not in visible_skills"));
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("not in the global 'visible_skills'")
|
||||
);
|
||||
assert!(err.to_string().contains("beta"));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
use super::role::{Role, RoleLike};
|
||||
use super::skill::Skill;
|
||||
use super::skill_policy::SkillPolicy;
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use indexmap::IndexMap;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
@@ -23,12 +24,10 @@ impl SkillRegistry {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn unload(&mut self, name: &str) -> Result<()> {
|
||||
if self.loaded.shift_remove(name).is_none() {
|
||||
bail!("Skill '{name}' is not loaded");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
pub fn unload(&mut self, name: &str) -> Result<Skill> {
|
||||
self.loaded
|
||||
.shift_remove(name)
|
||||
.ok_or_else(|| anyhow!("Skill '{name}' is not loaded"))
|
||||
}
|
||||
|
||||
pub fn loaded_names(&self) -> Vec<String> {
|
||||
@@ -38,8 +37,8 @@ impl SkillRegistry {
|
||||
pub fn loaded_mcp_servers(&self) -> BTreeSet<String> {
|
||||
let mut out = BTreeSet::new();
|
||||
for skill in self.loaded.values() {
|
||||
if let Some(csv) = skill.enabled_mcp_servers() {
|
||||
for token in csv.split(',') {
|
||||
if let Some(servers) = skill.enabled_mcp_servers() {
|
||||
for token in servers {
|
||||
let t = token.trim();
|
||||
if !t.is_empty() {
|
||||
out.insert(t.to_string());
|
||||
@@ -58,23 +57,32 @@ impl SkillRegistry {
|
||||
self.loaded.retain(|_, skill| !skill.auto_unload());
|
||||
}
|
||||
|
||||
pub fn effective_role(&self, base: &Role) -> Role {
|
||||
if self.loaded.is_empty() {
|
||||
pub fn effective_role(&self, base: &Role, policy: &SkillPolicy) -> Role {
|
||||
if !policy.skills_enabled || self.loaded.is_empty() {
|
||||
return base.clone();
|
||||
}
|
||||
|
||||
let mut effective = base.clone();
|
||||
let skip_body = effective.is_embedded_prompt();
|
||||
|
||||
let base_tools_set = effective.enabled_tools().is_some();
|
||||
let base_mcps_set = effective.enabled_mcp_servers().is_some();
|
||||
let base_tools = effective.enabled_tools();
|
||||
let base_tools_set = base_tools.is_some();
|
||||
let base_mcps = effective.enabled_mcp_servers();
|
||||
let base_mcps_set = base_mcps.is_some();
|
||||
|
||||
let mut tools = parse_csv(effective.enabled_tools().as_deref());
|
||||
let mut mcps = parse_csv(effective.enabled_mcp_servers().as_deref());
|
||||
let mut tools: BTreeSet<String> = base_tools.unwrap_or_default().into_iter().collect();
|
||||
let mut mcps: BTreeSet<String> = base_mcps.unwrap_or_default().into_iter().collect();
|
||||
|
||||
for (_, skill) in &self.loaded {
|
||||
tools.extend(parse_csv(skill.enabled_tools()));
|
||||
mcps.extend(parse_csv(skill.enabled_mcp_servers()));
|
||||
for (name, skill) in &self.loaded {
|
||||
if !policy.allows(name) {
|
||||
continue;
|
||||
}
|
||||
if let Some(skill_tools) = skill.enabled_tools() {
|
||||
tools.extend(skill_tools.iter().cloned());
|
||||
}
|
||||
if let Some(servers) = skill.enabled_mcp_servers() {
|
||||
mcps.extend(servers.iter().cloned());
|
||||
}
|
||||
if !skip_body && !skill.body().is_empty() {
|
||||
let separator = if effective.is_empty_prompt() {
|
||||
""
|
||||
@@ -87,39 +95,30 @@ impl SkillRegistry {
|
||||
}
|
||||
|
||||
if base_tools_set || !tools.is_empty() {
|
||||
effective.set_enabled_tools(Some(join_csv(&tools)));
|
||||
effective.set_enabled_tools(Some(tools.into_iter().collect()));
|
||||
}
|
||||
|
||||
if base_mcps_set || !mcps.is_empty() {
|
||||
effective.set_enabled_mcp_servers(Some(join_csv(&mcps)));
|
||||
effective.set_enabled_mcp_servers(Some(mcps.into_iter().collect()));
|
||||
}
|
||||
|
||||
effective
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_csv(s: Option<&str>) -> BTreeSet<String> {
|
||||
let mut set = BTreeSet::new();
|
||||
if let Some(raw) = s {
|
||||
for token in raw.split(',') {
|
||||
let trimmed = token.trim();
|
||||
if !trimmed.is_empty() {
|
||||
set.insert(trimmed.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
set
|
||||
}
|
||||
|
||||
fn join_csv(set: &BTreeSet<String>) -> String {
|
||||
set.iter().cloned().collect::<Vec<_>>().join(",")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl SkillRegistry {
|
||||
fn insert_for_test(&mut self, skill: Skill) {
|
||||
self.loaded.insert(skill.name().to_string(), skill);
|
||||
}
|
||||
|
||||
fn effective_role_for_test(&self, base: &Role) -> Role {
|
||||
let policy = SkillPolicy {
|
||||
skills_enabled: true,
|
||||
enabled: self.loaded.keys().cloned().collect(),
|
||||
};
|
||||
self.effective_role(base, &policy)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -140,7 +139,7 @@ mod tests {
|
||||
let base = Role::new("test", "You are a helper");
|
||||
let registry = SkillRegistry::default();
|
||||
|
||||
let effective = registry.effective_role(&base);
|
||||
let effective = registry.effective_role_for_test(&base);
|
||||
|
||||
assert_eq!(effective.prompt(), base.prompt());
|
||||
}
|
||||
@@ -151,7 +150,7 @@ mod tests {
|
||||
registry.insert_for_test(make_skill("git-master", "description: D", "Git knowledge"));
|
||||
|
||||
let base = Role::new("test", "You are a helper");
|
||||
let effective = registry.effective_role(&base);
|
||||
let effective = registry.effective_role_for_test(&base);
|
||||
|
||||
assert_eq!(effective.prompt(), "You are a helper\n\nGit knowledge");
|
||||
}
|
||||
@@ -163,7 +162,7 @@ mod tests {
|
||||
registry.insert_for_test(make_skill("b", "", "Beta body"));
|
||||
|
||||
let base = Role::new("test", "Base");
|
||||
let effective = registry.effective_role(&base);
|
||||
let effective = registry.effective_role_for_test(&base);
|
||||
|
||||
assert_eq!(effective.prompt(), "Base\n\nAlpha body\n\nBeta body");
|
||||
}
|
||||
@@ -175,7 +174,7 @@ mod tests {
|
||||
registry.insert_for_test(make_skill("b", "", "Beta"));
|
||||
|
||||
let base = Role::new("test", "");
|
||||
let effective = registry.effective_role(&base);
|
||||
let effective = registry.effective_role_for_test(&base);
|
||||
|
||||
assert_eq!(effective.prompt(), "Alpha\n\nBeta");
|
||||
}
|
||||
@@ -190,11 +189,11 @@ mod tests {
|
||||
));
|
||||
|
||||
let base = Role::new("test", "Process: __INPUT__");
|
||||
let effective = registry.effective_role(&base);
|
||||
let effective = registry.effective_role_for_test(&base);
|
||||
|
||||
assert_eq!(effective.prompt(), "Process: __INPUT__");
|
||||
let tools = effective.enabled_tools().expect("tools set by skill");
|
||||
assert!(tools.contains("shell"));
|
||||
assert!(tools.iter().any(|s| s == "shell"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -203,7 +202,7 @@ mod tests {
|
||||
registry.insert_for_test(make_skill("knowledge", "enabled_tools: fs", ""));
|
||||
|
||||
let base = Role::new("test", "Base");
|
||||
let effective = registry.effective_role(&base);
|
||||
let effective = registry.effective_role_for_test(&base);
|
||||
|
||||
assert_eq!(effective.prompt(), "Base");
|
||||
}
|
||||
@@ -223,16 +222,16 @@ mod tests {
|
||||
));
|
||||
|
||||
let mut base = Role::new("test", "body");
|
||||
base.set_enabled_tools(Some("web_search".to_string()));
|
||||
base.set_enabled_tools(Some(vec!["web_search".to_string()]));
|
||||
|
||||
let effective = registry.effective_role(&base);
|
||||
let effective = registry.effective_role_for_test(&base);
|
||||
|
||||
let tools_str = effective.enabled_tools().unwrap();
|
||||
let tools: BTreeSet<&str> = tools_str.split(',').collect();
|
||||
let tools_vec = effective.enabled_tools().unwrap();
|
||||
let tools: BTreeSet<&str> = tools_vec.iter().map(|s| s.as_str()).collect();
|
||||
assert_eq!(tools, BTreeSet::from(["fs", "git", "shell", "web_search"]));
|
||||
|
||||
let mcps_str = effective.enabled_mcp_servers().unwrap();
|
||||
let mcps: BTreeSet<&str> = mcps_str.split(',').collect();
|
||||
let mcps_vec = effective.enabled_mcp_servers().unwrap();
|
||||
let mcps: BTreeSet<&str> = mcps_vec.iter().map(|s| s.as_str()).collect();
|
||||
assert_eq!(mcps, BTreeSet::from(["github", "jira"]));
|
||||
}
|
||||
|
||||
@@ -242,7 +241,7 @@ mod tests {
|
||||
registry.insert_for_test(make_skill("knowledge", "", "Pure knowledge"));
|
||||
|
||||
let base = Role::new("test", "Base");
|
||||
let effective = registry.effective_role(&base);
|
||||
let effective = registry.effective_role_for_test(&base);
|
||||
|
||||
assert!(effective.enabled_tools().is_none());
|
||||
assert!(effective.enabled_mcp_servers().is_none());
|
||||
@@ -254,10 +253,10 @@ mod tests {
|
||||
registry.insert_for_test(make_skill("knowledge", "", "Pure knowledge"));
|
||||
|
||||
let mut base = Role::new("test", "Base");
|
||||
base.set_enabled_tools(Some(String::new()));
|
||||
let effective = registry.effective_role(&base);
|
||||
base.set_enabled_tools(Some(Vec::new()));
|
||||
let effective = registry.effective_role_for_test(&base);
|
||||
|
||||
assert_eq!(effective.enabled_tools().as_deref(), Some(""));
|
||||
assert_eq!(effective.enabled_tools().as_deref(), Some([].as_slice()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+29
-32
@@ -104,8 +104,13 @@ pub async fn handle_skill_tool(
|
||||
fn handle_list(ctx: &RequestContext, policy: &SkillPolicy) -> Result<Value> {
|
||||
let mcp_on = ctx.app.config.mcp_server_support;
|
||||
|
||||
let visible_names: Vec<String> = match ctx.app.config.visible_skills.as_deref() {
|
||||
Some(list) => list.to_vec(),
|
||||
None => paths::list_skills(),
|
||||
};
|
||||
|
||||
let mut entries = Vec::new();
|
||||
for name in paths::list_skills() {
|
||||
for name in visible_names {
|
||||
if !policy.allows(&name) {
|
||||
continue;
|
||||
}
|
||||
@@ -127,8 +132,8 @@ fn handle_list(ctx: &RequestContext, policy: &SkillPolicy) -> Result<Value> {
|
||||
entries.push(json!({
|
||||
"name": skill.name(),
|
||||
"description": skill.description(),
|
||||
"grants_tools": csv_to_vec(skill.enabled_tools()),
|
||||
"grants_mcp_servers": csv_to_vec(skill.enabled_mcp_servers()),
|
||||
"grants_tools": skill.enabled_tools().unwrap_or_default(),
|
||||
"grants_mcp_servers": skill.enabled_mcp_servers().unwrap_or_default(),
|
||||
"loaded": ctx.skill_registry.is_loaded(skill.name()),
|
||||
}));
|
||||
}
|
||||
@@ -166,11 +171,11 @@ async fn handle_load(
|
||||
|
||||
let tools_declared = skill
|
||||
.enabled_tools()
|
||||
.map(|s| !s.trim().is_empty())
|
||||
.map(|v| !v.is_empty())
|
||||
.unwrap_or(false);
|
||||
let mcps_declared = skill
|
||||
.enabled_mcp_servers()
|
||||
.map(|s| !s.trim().is_empty())
|
||||
.map(|v| !v.is_empty())
|
||||
.unwrap_or(false);
|
||||
|
||||
if tools_declared && !function_calling_on {
|
||||
@@ -193,7 +198,10 @@ async fn handle_load(
|
||||
}
|
||||
|
||||
if let Err(e) = ctx.refresh_tool_scope(create_abort_signal()).await {
|
||||
let _ = ctx.skill_registry.unload(name);
|
||||
if let Err(unload_err) = ctx.skill_registry.unload(name) {
|
||||
warn!("Failed to unload skill '{name}' during error recovery: {unload_err}");
|
||||
}
|
||||
|
||||
return Ok(json!({
|
||||
"error": format!("Loaded skill '{name}' but failed to refresh tool scope: {e}")
|
||||
}));
|
||||
@@ -212,12 +220,25 @@ async fn handle_unload(ctx: &mut RequestContext, args: &Value) -> Result<Value>
|
||||
_ => return Ok(json!({"error": "name is required"})),
|
||||
};
|
||||
|
||||
if let Err(e) = ctx.skill_registry.unload(name) {
|
||||
if let Err(e) = paths::validate_skill_name(name) {
|
||||
return Ok(json!({"error": e.to_string()}));
|
||||
}
|
||||
|
||||
let skill = match ctx.skill_registry.unload(name) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return Ok(json!({"error": e.to_string()})),
|
||||
};
|
||||
|
||||
if let Err(e) = ctx.refresh_tool_scope(create_abort_signal()).await {
|
||||
warn!("Unloaded skill '{name}' but failed to refresh tool scope: {e}");
|
||||
if let Err(insert_err) = ctx.skill_registry.insert(skill) {
|
||||
warn!("Failed to restore skill '{name}' after unload recovery: {insert_err}");
|
||||
}
|
||||
|
||||
return Ok(json!({
|
||||
"error": format!(
|
||||
"Unloaded skill '{name}' but failed to refresh tool scope; restored: {e}"
|
||||
)
|
||||
}));
|
||||
}
|
||||
|
||||
Ok(json!({
|
||||
@@ -226,16 +247,6 @@ async fn handle_unload(ctx: &mut RequestContext, args: &Value) -> Result<Value>
|
||||
}))
|
||||
}
|
||||
|
||||
fn csv_to_vec(csv: Option<&str>) -> Vec<String> {
|
||||
csv.map(|raw| {
|
||||
raw.split(',')
|
||||
.map(|t| t.trim().to_string())
|
||||
.filter(|t| !t.is_empty())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -293,18 +304,4 @@ mod tests {
|
||||
|
||||
assert!(required, "skill__list should have no required parameters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_to_vec_empty_input() {
|
||||
assert!(csv_to_vec(None).is_empty());
|
||||
assert!(csv_to_vec(Some("")).is_empty());
|
||||
assert!(csv_to_vec(Some(" ")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_to_vec_parses_and_trims() {
|
||||
let v = csv_to_vec(Some("a, b ,c,, d"));
|
||||
|
||||
assert_eq!(v, vec!["a", "b", "c", "d"]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -469,7 +469,7 @@ pub async fn run_agent_for_graph(
|
||||
child_ctx.init_agent_shared_variables()?;
|
||||
}
|
||||
|
||||
let input = Input::from_str(&child_ctx, prompt, None);
|
||||
let input = Input::from_str(&child_ctx, prompt, None)?;
|
||||
|
||||
debug!("Spawning agent '{agent_name}' for graph node as '{agent_id}'");
|
||||
|
||||
@@ -635,7 +635,7 @@ async fn handle_spawn(ctx: &mut RequestContext, args: &Value) -> Result<Value> {
|
||||
child_ctx.init_agent_shared_variables()?;
|
||||
}
|
||||
|
||||
let input = Input::from_str(&child_ctx, &prompt, None);
|
||||
let input = Input::from_str(&child_ctx, &prompt, None)?;
|
||||
|
||||
debug!("Spawning child agent '{agent_name}' as '{agent_id}'");
|
||||
|
||||
@@ -1228,7 +1228,7 @@ async fn summarize_output(ctx: &RequestContext, agent_name: &str, output: &str)
|
||||
"Summarize the following sub-agent output from '{}':\n\n{}",
|
||||
agent_name, output
|
||||
);
|
||||
let input = Input::from_str(ctx, &user_message, Some(role));
|
||||
let input = Input::from_str(ctx, &user_message, Some(role))?;
|
||||
|
||||
let summary = input.fetch_chat_text().await?;
|
||||
|
||||
|
||||
+34
-10
@@ -2,7 +2,8 @@ use super::state::StateManager;
|
||||
use super::structured;
|
||||
use super::types::LlmNode;
|
||||
use crate::client::{Model, ModelType, call_chat_completions};
|
||||
use crate::config::{Input, RequestContext, Role, RoleLike};
|
||||
use crate::config::{Input, RequestContext, Role, RoleLike, SkillPolicy};
|
||||
use crate::function::skill::skill_function_declarations;
|
||||
use crate::utils::create_abort_signal;
|
||||
use anyhow::{Context, Error, Result, anyhow, bail};
|
||||
use serde_json::Value;
|
||||
@@ -105,7 +106,7 @@ async fn run(
|
||||
let (regular_tools, mcp_servers) = categorize_tools(node.tools.as_deref());
|
||||
validate_tools_subset(®ular_tools, &mcp_servers, parent_ctx)?;
|
||||
|
||||
let role = build_inline_role(
|
||||
let mut role = build_inline_role(
|
||||
node,
|
||||
instructions.as_deref(),
|
||||
®ular_tools,
|
||||
@@ -115,7 +116,30 @@ async fn run(
|
||||
|
||||
let saved_agent_skill_state = swap_in_node_skill_policy(node, parent_ctx);
|
||||
|
||||
let composed_role = parent_ctx.skill_registry.effective_role(&role);
|
||||
let policy = match SkillPolicy::effective(
|
||||
&parent_ctx.app.config,
|
||||
parent_ctx.role.as_ref(),
|
||||
parent_ctx.agent.as_ref(),
|
||||
parent_ctx.session.as_ref(),
|
||||
) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
restore_agent_skill_policy(parent_ctx, saved_agent_skill_state);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
|
||||
if policy.skills_enabled {
|
||||
let mut tools = role.enabled_tools().map(|v| v.to_vec()).unwrap_or_default();
|
||||
for decl in skill_function_declarations() {
|
||||
if !tools.contains(&decl.name) {
|
||||
tools.push(decl.name);
|
||||
}
|
||||
}
|
||||
role.set_enabled_tools(Some(tools));
|
||||
}
|
||||
|
||||
let composed_role = parent_ctx.skill_registry.effective_role(&role, &policy);
|
||||
|
||||
let saved_role = parent_ctx.role.clone();
|
||||
parent_ctx.role = Some(composed_role);
|
||||
@@ -195,7 +219,7 @@ async fn run_chat_loop(node: &LlmNode, prompt: &str, ctx: &mut RequestContext) -
|
||||
let abort = create_abort_signal();
|
||||
let app_cfg = Arc::clone(&ctx.app.config);
|
||||
let role_for_input = ctx.role.clone();
|
||||
let mut input = Input::from_str(ctx, prompt, role_for_input);
|
||||
let mut input = Input::from_str(ctx, prompt, role_for_input)?;
|
||||
let mut accumulated = String::new();
|
||||
|
||||
for turn in 0..node.max_iterations {
|
||||
@@ -256,18 +280,18 @@ fn build_inline_role(
|
||||
}
|
||||
|
||||
if node.tools.as_deref().unwrap_or_default().is_empty() {
|
||||
role.set_enabled_tools(Some(String::new()));
|
||||
role.set_enabled_mcp_servers(Some(String::new()));
|
||||
role.set_enabled_tools(Some(Vec::new()));
|
||||
role.set_enabled_mcp_servers(Some(Vec::new()));
|
||||
} else {
|
||||
if !regular_tools.is_empty() {
|
||||
role.set_enabled_tools(Some(regular_tools.join(",")));
|
||||
role.set_enabled_tools(Some(regular_tools.to_vec()));
|
||||
} else {
|
||||
role.set_enabled_tools(Some(String::new()));
|
||||
role.set_enabled_tools(Some(Vec::new()));
|
||||
}
|
||||
if !mcp_servers.is_empty() {
|
||||
role.set_enabled_mcp_servers(Some(mcp_servers.join(",")));
|
||||
role.set_enabled_mcp_servers(Some(mcp_servers.to_vec()));
|
||||
} else {
|
||||
role.set_enabled_mcp_servers(Some(String::new()));
|
||||
role.set_enabled_mcp_servers(Some(Vec::new()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -55,8 +55,8 @@ async fn extract_via_extractor(
|
||||
|
||||
fn build_extractor_role() -> Result<Role> {
|
||||
let mut role = Role::new(EXTRACTOR_ROLE_NAME, EXTRACTOR_ROLE_PROMPT);
|
||||
role.set_enabled_tools(Some(String::new()));
|
||||
role.set_enabled_mcp_servers(Some(String::new()));
|
||||
role.set_enabled_tools(Some(Vec::new()));
|
||||
role.set_enabled_mcp_servers(Some(Vec::new()));
|
||||
Ok(role)
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@ async fn run_one_shot(prompt: &str, ctx: &mut RequestContext) -> Result<String>
|
||||
let abort = create_abort_signal();
|
||||
let app_cfg = Arc::clone(&ctx.app.config);
|
||||
let role_for_input = ctx.role.clone();
|
||||
let input = Input::from_str(ctx, prompt, role_for_input);
|
||||
let input = Input::from_str(ctx, prompt, role_for_input)?;
|
||||
let client = input.create_client()?;
|
||||
ctx.before_chat_completion(&input)?;
|
||||
let (output, tool_results) =
|
||||
@@ -183,7 +183,7 @@ mod tests {
|
||||
fn build_extractor_role_disables_tools_and_mcp() {
|
||||
let role = build_extractor_role().expect("builtin role must exist");
|
||||
|
||||
assert_eq!(role.enabled_tools().as_deref(), Some(""));
|
||||
assert_eq!(role.enabled_mcp_servers().as_deref(), Some(""));
|
||||
assert_eq!(role.enabled_tools().as_deref(), Some([].as_slice()));
|
||||
assert_eq!(role.enabled_mcp_servers().as_deref(), Some([].as_slice()));
|
||||
}
|
||||
}
|
||||
|
||||
+68
-1
@@ -93,6 +93,7 @@ impl AgentValidationContext {
|
||||
pub struct GraphValidator {
|
||||
base_dir: PathBuf,
|
||||
agent_ctx: Option<AgentValidationContext>,
|
||||
skill_exists: fn(&str) -> bool,
|
||||
}
|
||||
|
||||
impl GraphValidator {
|
||||
@@ -100,6 +101,7 @@ impl GraphValidator {
|
||||
Self {
|
||||
base_dir: base_dir.into(),
|
||||
agent_ctx: None,
|
||||
skill_exists: paths::has_skill,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,6 +110,12 @@ impl GraphValidator {
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn with_skill_exists(mut self, f: fn(&str) -> bool) -> Self {
|
||||
self.skill_exists = f;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn validate(&self, graph: &Graph) -> ValidationResult {
|
||||
let mut result = ValidationResult::default();
|
||||
self.validate_node_references(graph, &mut result);
|
||||
@@ -191,6 +199,49 @@ impl GraphValidator {
|
||||
}
|
||||
|
||||
fn validate_llm_skills(&self, graph: &Graph, result: &mut ValidationResult) {
|
||||
let visible_skills = self
|
||||
.agent_ctx
|
||||
.as_ref()
|
||||
.and_then(|c| c.app_config.visible_skills.as_deref());
|
||||
|
||||
let skill_exists = self.skill_exists;
|
||||
let has_agent_ctx = self.agent_ctx.is_some();
|
||||
let check_visibility = |name: &str| -> Option<String> {
|
||||
if !has_agent_ctx {
|
||||
return None;
|
||||
}
|
||||
|
||||
match visible_skills {
|
||||
Some(list) if !list.iter().any(|s| s == name) => Some(format!(
|
||||
"'{name}' is not in the global 'visible_skills' allow-list"
|
||||
)),
|
||||
None if !skill_exists(name) => Some(format!("'{name}' is not installed")),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(graph_skills) = &graph.enabled_skills {
|
||||
for name in graph_skills {
|
||||
if name.trim().is_empty() {
|
||||
result.error(ValidationError::new(
|
||||
"graph 'enabled_skills' contains an empty skill name",
|
||||
));
|
||||
continue;
|
||||
}
|
||||
if let Err(e) = paths::validate_skill_name(name) {
|
||||
result.error(ValidationError::new(format!(
|
||||
"graph 'enabled_skills' contains an invalid skill name: '{name}': {e}"
|
||||
)));
|
||||
continue;
|
||||
}
|
||||
if let Some(reason) = check_visibility(name) {
|
||||
result.error(ValidationError::new(format!(
|
||||
"graph 'enabled_skills': {reason}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (node_id, node) in &graph.nodes {
|
||||
let NodeType::Llm(llm) = &node.node_type else {
|
||||
continue;
|
||||
@@ -207,6 +258,22 @@ impl GraphValidator {
|
||||
));
|
||||
continue;
|
||||
}
|
||||
if let Err(e) = paths::validate_skill_name(name) {
|
||||
result.error(ValidationError::with_node(
|
||||
node_id,
|
||||
format!(
|
||||
"llm node 'enabled_skills' contains an invalid skill name: '{name}': {e}"
|
||||
)));
|
||||
continue;
|
||||
}
|
||||
if let Some(reason) = check_visibility(name) {
|
||||
result.error(ValidationError::with_node(
|
||||
node_id,
|
||||
format!("llm node 'enabled_skills': {reason}"),
|
||||
));
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(graph_skills) = &graph.enabled_skills
|
||||
&& !graph_skills.iter().any(|g| g == name)
|
||||
{
|
||||
@@ -1325,7 +1392,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn validator() -> GraphValidator {
|
||||
GraphValidator::new(env::current_dir().unwrap())
|
||||
GraphValidator::new(env::current_dir().unwrap()).with_skill_exists(|_: &str| true)
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+12
-8
@@ -113,7 +113,7 @@ async fn main() -> Result<()> {
|
||||
if vault_flags {
|
||||
let cfg = Config::load_with_interpolation(true).await?;
|
||||
let app_config = AppConfig::from_config(cfg)?;
|
||||
let vault = Vault::init(&app_config);
|
||||
let vault = Vault::init(&app_config)?;
|
||||
return Vault::handle_vault_flags(cli, &vault);
|
||||
}
|
||||
|
||||
@@ -197,14 +197,18 @@ async fn run(
|
||||
println!("{skills}");
|
||||
return Ok(());
|
||||
}
|
||||
if cli.skill.len() == 1 && !paths::has_skill(&cli.skill[0]) {
|
||||
let name = &cli.skill[0];
|
||||
let skills = cli.skills();
|
||||
if skills.len() == 1 {
|
||||
let name = &skills[0];
|
||||
paths::validate_skill_name(name)?;
|
||||
if !paths::has_skill(name) {
|
||||
let app = Arc::clone(&ctx.app.config);
|
||||
ctx.upsert_skill(app.as_ref(), name)?;
|
||||
return Ok(());
|
||||
}
|
||||
if cli.skill.len() > 1 {
|
||||
for name in &cli.skill {
|
||||
} else if skills.len() > 1 {
|
||||
for name in &skills {
|
||||
paths::validate_skill_name(name)?;
|
||||
if !paths::has_skill(name) {
|
||||
bail!("Skill '{name}' is not installed");
|
||||
}
|
||||
@@ -323,7 +327,7 @@ async fn run(
|
||||
.await?;
|
||||
}
|
||||
|
||||
for name in &cli.skill {
|
||||
for name in &cli.skills() {
|
||||
ctx.load_skill_repl(name, abort_signal.clone()).await?;
|
||||
}
|
||||
|
||||
@@ -457,7 +461,7 @@ async fn shell_execute(
|
||||
}
|
||||
'd' => {
|
||||
let role = ctx.retrieve_role(app.as_ref(), EXPLAIN_SHELL_ROLE)?;
|
||||
let input = Input::from_str(ctx, &eval_str, Some(role));
|
||||
let input = Input::from_str(ctx, &eval_str, Some(role))?;
|
||||
if input.stream() {
|
||||
call_chat_completions_streaming(
|
||||
&input,
|
||||
@@ -502,7 +506,7 @@ async fn create_input(
|
||||
) -> Result<Input> {
|
||||
let text = text.unwrap_or_default();
|
||||
let input = if file.is_empty() {
|
||||
Input::from_str(ctx, &text, None)
|
||||
Input::from_str(ctx, &text, None)?
|
||||
} else {
|
||||
Input::from_files_with_spinner(ctx, &text, file.to_vec(), None, abort_signal).await?
|
||||
};
|
||||
|
||||
+17
-12
@@ -146,7 +146,7 @@ impl McpRegistry {
|
||||
pub async fn init(
|
||||
log_path: Option<PathBuf>,
|
||||
start_mcp_servers: bool,
|
||||
enabled_mcp_servers: Option<String>,
|
||||
enabled_mcp_servers: Option<Vec<String>>,
|
||||
abort_signal: AbortSignal,
|
||||
app_config: &AppConfig,
|
||||
vault: &Vault,
|
||||
@@ -216,7 +216,7 @@ impl McpRegistry {
|
||||
|
||||
async fn start_select_mcp_servers(
|
||||
&mut self,
|
||||
enabled_mcp_servers: Option<String>,
|
||||
enabled_mcp_servers: Option<Vec<String>>,
|
||||
) -> Result<()> {
|
||||
if self.config.is_none() {
|
||||
debug!(
|
||||
@@ -292,15 +292,15 @@ impl McpRegistry {
|
||||
Ok((id.to_string(), service, catalog))
|
||||
}
|
||||
|
||||
fn resolve_server_ids(&self, enabled_mcp_servers: Option<String>) -> Vec<String> {
|
||||
fn resolve_server_ids(&self, enabled_mcp_servers: Option<Vec<String>>) -> Vec<String> {
|
||||
if let Some(config) = &self.config
|
||||
&& let Some(servers) = enabled_mcp_servers
|
||||
{
|
||||
if servers == "all" {
|
||||
if servers.iter().any(|s| s.trim() == "all") {
|
||||
config.mcp_servers.keys().cloned().collect()
|
||||
} else {
|
||||
let enabled_servers: HashSet<String> =
|
||||
servers.split(',').map(|s| s.trim().to_string()).collect();
|
||||
servers.into_iter().map(|s| s.trim().to_string()).collect();
|
||||
config
|
||||
.mcp_servers
|
||||
.keys()
|
||||
@@ -754,7 +754,7 @@ mod tests {
|
||||
#[test]
|
||||
fn resolve_all_returns_all_configured_servers() {
|
||||
let registry = make_registry_with_config(&["github", "slack", "jira"]);
|
||||
let mut ids = registry.resolve_server_ids(Some("all".to_string()));
|
||||
let mut ids = registry.resolve_server_ids(Some(vec!["all".to_string()]));
|
||||
ids.sort();
|
||||
assert_eq!(ids, vec!["github", "jira", "slack"]);
|
||||
}
|
||||
@@ -762,7 +762,8 @@ mod tests {
|
||||
#[test]
|
||||
fn resolve_comma_separated_returns_matching_servers() {
|
||||
let registry = make_registry_with_config(&["github", "slack", "jira"]);
|
||||
let mut ids = registry.resolve_server_ids(Some("github, jira".to_string()));
|
||||
let mut ids =
|
||||
registry.resolve_server_ids(Some(vec!["github".to_string(), "jira".to_string()]));
|
||||
ids.sort();
|
||||
assert_eq!(ids, vec!["github", "jira"]);
|
||||
}
|
||||
@@ -770,7 +771,7 @@ mod tests {
|
||||
#[test]
|
||||
fn resolve_single_server_name() {
|
||||
let registry = make_registry_with_config(&["github", "slack"]);
|
||||
let ids = registry.resolve_server_ids(Some("slack".to_string()));
|
||||
let ids = registry.resolve_server_ids(Some(vec!["slack".to_string()]));
|
||||
assert_eq!(ids, vec!["slack"]);
|
||||
}
|
||||
|
||||
@@ -784,28 +785,32 @@ mod tests {
|
||||
#[test]
|
||||
fn resolve_no_config_returns_empty() {
|
||||
let registry = McpRegistry::default();
|
||||
let ids = registry.resolve_server_ids(Some("all".to_string()));
|
||||
let ids = registry.resolve_server_ids(Some(vec!["all".to_string()]));
|
||||
assert!(ids.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_nonexistent_server_filtered_out() {
|
||||
let registry = make_registry_with_config(&["github"]);
|
||||
let ids = registry.resolve_server_ids(Some("github, nonexistent".to_string()));
|
||||
let ids = registry
|
||||
.resolve_server_ids(Some(vec!["github".to_string(), "nonexistent".to_string()]));
|
||||
assert_eq!(ids, vec!["github"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_all_nonexistent_returns_empty() {
|
||||
let registry = make_registry_with_config(&["github"]);
|
||||
let ids = registry.resolve_server_ids(Some("foo, bar".to_string()));
|
||||
let ids = registry.resolve_server_ids(Some(vec!["foo".to_string(), "bar".to_string()]));
|
||||
assert!(ids.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_trims_whitespace() {
|
||||
let registry = make_registry_with_config(&["github", "slack"]);
|
||||
let mut ids = registry.resolve_server_ids(Some(" github , slack ".to_string()));
|
||||
let mut ids = registry.resolve_server_ids(Some(vec![
|
||||
" github ".to_string(),
|
||||
" slack ".to_string(),
|
||||
]));
|
||||
ids.sort();
|
||||
assert_eq!(ids, vec!["github", "slack"]);
|
||||
}
|
||||
|
||||
+8
-6
@@ -503,7 +503,7 @@ pub async fn run_repl_command(
|
||||
Some((name, text)) => {
|
||||
let app = Arc::clone(&ctx.app.config);
|
||||
let role = ctx.retrieve_role(app.as_ref(), name.trim())?;
|
||||
let input = Input::from_str(ctx, text, Some(role));
|
||||
let input = Input::from_str(ctx, text, Some(role))?;
|
||||
ask(ctx, abort_signal.clone(), input, false).await?;
|
||||
}
|
||||
None => {
|
||||
@@ -654,7 +654,7 @@ pub async fn run_repl_command(
|
||||
match text {
|
||||
Some(text) => {
|
||||
println!("{}", dimmed_text(&format!(">> {text}")));
|
||||
let input = Input::from_str(ctx, &text, None);
|
||||
let input = Input::from_str(ctx, &text, None)?;
|
||||
ask(ctx, abort_signal.clone(), input, true).await?;
|
||||
}
|
||||
None => {
|
||||
@@ -708,6 +708,8 @@ pub async fn run_repl_command(
|
||||
let name = s.strip_prefix("skill").unwrap_or("").trim();
|
||||
if name.is_empty() {
|
||||
println!("Usage: .edit skill <name>");
|
||||
} else if let Err(e) = paths::validate_skill_name(name) {
|
||||
bail!(e);
|
||||
} else if !paths::has_skill(name) {
|
||||
bail!(
|
||||
"Skill '{name}' is not installed (expected at {})",
|
||||
@@ -822,7 +824,7 @@ pub async fn run_repl_command(
|
||||
None => bail!("Unable to regenerate the response"),
|
||||
};
|
||||
let app = Arc::clone(&ctx.app.config);
|
||||
input.set_regenerate(ctx.extract_role(&app));
|
||||
input.set_regenerate(ctx.extract_role(&app)?);
|
||||
ask(ctx, abort_signal.clone(), input, true).await?;
|
||||
}
|
||||
".set" => match args {
|
||||
@@ -944,7 +946,7 @@ pub async fn run_repl_command(
|
||||
},
|
||||
None => {
|
||||
reset_continuation(ctx);
|
||||
let input = Input::from_str(ctx, line, None);
|
||||
let input = Input::from_str(ctx, line, None)?;
|
||||
ask(ctx, abort_signal.clone(), input, true).await?;
|
||||
}
|
||||
}
|
||||
@@ -1040,7 +1042,7 @@ async fn ask(
|
||||
|
||||
format!("{prompt}\n\n{todo_state}")
|
||||
};
|
||||
let continuation_input = Input::from_str(ctx, &full_prompt, None);
|
||||
let continuation_input = Input::from_str(ctx, &full_prompt, None)?;
|
||||
ask(ctx, abort_signal, continuation_input, false).await
|
||||
} else {
|
||||
reset_continuation(ctx);
|
||||
@@ -1113,7 +1115,7 @@ async fn ask(
|
||||
|
||||
format!("{prompt}\n\n{todo_state}")
|
||||
};
|
||||
let continuation_input = Input::from_str(ctx, &full_prompt, None);
|
||||
let continuation_input = Input::from_str(ctx, &full_prompt, None)?;
|
||||
return ask(ctx, abort_signal, continuation_input, false).await;
|
||||
}
|
||||
}
|
||||
|
||||
+59
-14
@@ -1,6 +1,9 @@
|
||||
mod utils;
|
||||
|
||||
use std::fs::read_to_string;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::config::paths;
|
||||
pub use utils::create_vault_password_file;
|
||||
pub use utils::interpolate_secrets;
|
||||
pub use utils::prompt_provider_choice;
|
||||
@@ -14,10 +17,13 @@ use gman::providers::SecretProvider;
|
||||
use gman::providers::SupportedProvider;
|
||||
use gman::providers::local::LocalProvider;
|
||||
use inquire::{Password, PasswordDisplayMode, required};
|
||||
use log::warn;
|
||||
use serde_yaml::Value;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use tokio::runtime::Handle;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub static SECRET_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\{\{(.+)}}").unwrap());
|
||||
pub static SECRET_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\{\{([^{}]+)}}").unwrap());
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct Vault {
|
||||
@@ -27,22 +33,54 @@ pub struct Vault {
|
||||
pub type GlobalVault = Arc<Vault>;
|
||||
|
||||
impl Vault {
|
||||
pub fn init_bare() -> Self {
|
||||
let vault_password_file = AppConfig::default().vault_password_file();
|
||||
let local_provider = LocalProvider {
|
||||
password_file: Some(vault_password_file),
|
||||
pub fn init_bare() -> Result<Self> {
|
||||
let config_path = paths::config_file();
|
||||
if !config_path.exists() {
|
||||
bail!(
|
||||
"Coyote config not found at {}. Run first-run setup before using the vault.",
|
||||
config_path.display()
|
||||
);
|
||||
}
|
||||
let content = read_to_string(&config_path)
|
||||
.with_context(|| format!("failed to read config at {}", config_path.display()))?;
|
||||
let value: Value = serde_yaml::from_str(&content)
|
||||
.with_context(|| format!("failed to parse config at {}", config_path.display()))?;
|
||||
|
||||
let provider = match value.get("secrets_provider") {
|
||||
Some(v) if !v.is_null() => serde_yaml::from_value::<SupportedProvider>(v.clone())
|
||||
.with_context(|| "failed to parse 'secrets_provider' from config")?,
|
||||
_ => {
|
||||
let password_file = value
|
||||
.get("vault_password_file")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| AppConfig::default().vault_password_file());
|
||||
SupportedProvider::Local {
|
||||
provider_def: LocalProvider {
|
||||
password_file: Some(password_file),
|
||||
git_branch: None,
|
||||
..LocalProvider::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(Self { provider })
|
||||
}
|
||||
|
||||
pub fn default_local() -> Self {
|
||||
Self {
|
||||
provider: SupportedProvider::Local {
|
||||
provider_def: local_provider,
|
||||
provider_def: LocalProvider {
|
||||
password_file: Some(AppConfig::default().vault_password_file()),
|
||||
git_branch: None,
|
||||
..LocalProvider::default()
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init(config: &AppConfig) -> Self {
|
||||
pub fn init(config: &AppConfig) -> Result<Self> {
|
||||
let mut provider = match &config.secrets_provider {
|
||||
Some(p) => p.clone(),
|
||||
None => SupportedProvider::Local {
|
||||
@@ -54,11 +92,10 @@ impl Vault {
|
||||
};
|
||||
|
||||
if let SupportedProvider::Local { provider_def } = &mut provider {
|
||||
ensure_password_file_initialized(provider_def)
|
||||
.expect("Failed to initialize password file");
|
||||
ensure_password_file_initialized(provider_def)?;
|
||||
}
|
||||
|
||||
Self { provider }
|
||||
Ok(Self { provider })
|
||||
}
|
||||
|
||||
pub fn local_password_file(&self) -> Result<PathBuf> {
|
||||
@@ -175,25 +212,33 @@ impl Vault {
|
||||
}
|
||||
|
||||
pub fn validate_round_trip(&self) -> Result<()> {
|
||||
const PROBE_KEY: &str = "__coyote_setup_probe__";
|
||||
const PROBE_VALUE: &str = "ok";
|
||||
let probe_key = format!("coyote-setup-probe-{}", Uuid::new_v4().simple());
|
||||
|
||||
let h = Handle::current();
|
||||
let result: Result<()> = tokio::task::block_in_place(|| {
|
||||
h.block_on(async {
|
||||
self.provider_ref()
|
||||
.set_secret(PROBE_KEY, PROBE_VALUE)
|
||||
.set_secret(&probe_key, PROBE_VALUE)
|
||||
.await
|
||||
.with_context(|| "vault write probe failed")?;
|
||||
let got = self
|
||||
.provider_ref()
|
||||
.get_secret(PROBE_KEY)
|
||||
.get_secret(&probe_key)
|
||||
.await
|
||||
.with_context(|| "vault read probe failed")?;
|
||||
let _ = self.provider_ref().delete_secret(PROBE_KEY).await;
|
||||
if got != PROBE_VALUE {
|
||||
if let Err(cleanup_err) = self.provider_ref().delete_secret(&probe_key).await {
|
||||
warn!("vault probe cleanup failed for key '{probe_key}': {cleanup_err}");
|
||||
}
|
||||
bail!("vault read probe returned an unexpected value");
|
||||
}
|
||||
|
||||
self.provider_ref()
|
||||
.delete_secret(&probe_key)
|
||||
.await
|
||||
.with_context(|| "vault delete probe failed")?;
|
||||
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
|
||||
+219
-3
@@ -13,7 +13,8 @@ use gman::providers::one_password::OnePasswordProvider;
|
||||
use indoc::formatdoc;
|
||||
use inquire::validator::Validation;
|
||||
use inquire::{Confirm, Password, PasswordDisplayMode, Select, Text, min_length, required};
|
||||
use std::path::PathBuf;
|
||||
use log::debug;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
pub fn ensure_password_file_initialized(local_provider: &mut LocalProvider) -> Result<()> {
|
||||
@@ -91,6 +92,7 @@ pub fn create_vault_password_file(vault: &mut Vault) -> Result<()> {
|
||||
match password {
|
||||
Ok(pw) => {
|
||||
std::fs::write(&vault_password_file, pw.as_bytes())?;
|
||||
set_password_file_permissions(&vault_password_file)?;
|
||||
println!(
|
||||
"✓ Password file '{}' updated.",
|
||||
vault_password_file.display()
|
||||
@@ -162,6 +164,7 @@ pub fn create_vault_password_file(vault: &mut Vault) -> Result<()> {
|
||||
match password {
|
||||
Ok(pw) => {
|
||||
std::fs::write(&password_file, pw.as_bytes())?;
|
||||
set_password_file_permissions(&password_file)?;
|
||||
local_provider.password_file = Some(password_file);
|
||||
println!(
|
||||
"✓ Password file '{}' created.",
|
||||
@@ -352,6 +355,19 @@ fn required_cli_preflight(label: &str, cli: &str, install_url: &str) {
|
||||
}
|
||||
|
||||
pub fn interpolate_secrets(content: &str, vault: &Vault) -> Result<(String, Vec<String>)> {
|
||||
interpolate_secrets_with(content, vault.auth_hint(), |name| {
|
||||
vault.get_secret(name, false)
|
||||
})
|
||||
}
|
||||
|
||||
fn interpolate_secrets_with<F>(
|
||||
content: &str,
|
||||
auth_hint: Option<&'static str>,
|
||||
mut get_secret: F,
|
||||
) -> Result<(String, Vec<String>)>
|
||||
where
|
||||
F: FnMut(&str) -> Result<String>,
|
||||
{
|
||||
let mut missing_secrets = vec![];
|
||||
let mut fatal_error: Option<anyhow::Error> = None;
|
||||
|
||||
@@ -364,8 +380,12 @@ pub fn interpolate_secrets(content: &str, vault: &Vault) -> Result<(String, Vec<
|
||||
|
||||
SECRET_RE
|
||||
.replace_all(line, |caps: &fancy_regex::Captures<'_>| {
|
||||
if fatal_error.is_some() {
|
||||
return String::new();
|
||||
}
|
||||
|
||||
let name = caps[1].trim();
|
||||
match vault.get_secret(name, false) {
|
||||
match get_secret(name) {
|
||||
Ok(s) => s,
|
||||
Err(e) => match e.downcast_ref::<SecretError>() {
|
||||
Some(SecretError::NotFound { .. }) => {
|
||||
@@ -375,7 +395,7 @@ pub fn interpolate_secrets(content: &str, vault: &Vault) -> Result<(String, Vec<
|
||||
Some(SecretError::AuthFailed { .. }) => {
|
||||
let base =
|
||||
format!("Failed to fetch secret '{name}' from vault: {e}");
|
||||
let msg = match vault.auth_hint() {
|
||||
let msg = match auth_hint {
|
||||
Some(hint) => format!("{base}\n\nHint: {hint}"),
|
||||
None => base,
|
||||
};
|
||||
@@ -402,3 +422,199 @@ pub fn interpolate_secrets(content: &str, vault: &Vault) -> Result<(String, Vec<
|
||||
|
||||
Ok((parsed_content, missing_secrets))
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn set_password_file_permissions(path: &Path) -> Result<()> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).map_err(|e| {
|
||||
anyhow!(
|
||||
"Failed to set 0600 permissions on '{}': {e}",
|
||||
path.display()
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn set_password_file_permissions(_path: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use anyhow::Error;
|
||||
use std::cell::RefCell;
|
||||
|
||||
fn not_found(name: &str) -> Error {
|
||||
Error::new(SecretError::NotFound {
|
||||
key: name.to_string(),
|
||||
provider: "test",
|
||||
})
|
||||
}
|
||||
|
||||
fn auth_failed() -> Error {
|
||||
Error::new(SecretError::AuthFailed {
|
||||
provider: "test",
|
||||
source: anyhow!("auth failure"),
|
||||
})
|
||||
}
|
||||
|
||||
struct Calls(RefCell<Vec<String>>);
|
||||
|
||||
impl Calls {
|
||||
fn new() -> Self {
|
||||
Self(RefCell::new(Vec::new()))
|
||||
}
|
||||
|
||||
fn record(&self, name: &str) {
|
||||
self.0.borrow_mut().push(name.to_string());
|
||||
}
|
||||
|
||||
fn snapshot(&self) -> Vec<String> {
|
||||
self.0.borrow().clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interpolates_single_secret_per_line() {
|
||||
let (out, missing) =
|
||||
interpolate_secrets_with("api_key={{API_KEY}}", None, |name| match name {
|
||||
"API_KEY" => Ok("sk-12345".to_string()),
|
||||
other => panic!("unexpected lookup: {other}"),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(out, "api_key=sk-12345");
|
||||
assert!(missing.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regex_matches_each_secret_independently_when_one_per_line() {
|
||||
let calls = Calls::new();
|
||||
let (out, missing) = interpolate_secrets_with("{{ONE}}\nmiddle\n{{TWO}}", None, |name| {
|
||||
calls.record(name);
|
||||
Ok(name.to_lowercase())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(calls.snapshot(), vec!["ONE".to_string(), "TWO".to_string()]);
|
||||
assert_eq!(out, "one\nmiddle\ntwo");
|
||||
assert!(missing.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_comment_lines() {
|
||||
let calls = Calls::new();
|
||||
|
||||
let (out, missing) =
|
||||
interpolate_secrets_with("# api_key={{NEVER_FETCHED}}\nreal={{S}}", None, |name| {
|
||||
calls.record(name);
|
||||
Ok("v".to_string())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(out, "# api_key={{NEVER_FETCHED}}\nreal=v");
|
||||
assert!(missing.is_empty());
|
||||
assert_eq!(calls.snapshot(), vec!["S".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_secrets_become_empty_strings_and_are_reported() {
|
||||
let (out, missing) = interpolate_secrets_with(
|
||||
"a={{HAVE}}\nb={{MISSING_1}}\nc={{MISSING_2}}",
|
||||
None,
|
||||
|name| match name {
|
||||
"HAVE" => Ok("present".to_string()),
|
||||
missing => Err(not_found(missing)),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(out, "a=present\nb=\nc=");
|
||||
assert_eq!(
|
||||
missing,
|
||||
vec!["MISSING_1".to_string(), "MISSING_2".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interpolates_multiple_secrets_on_same_line() {
|
||||
let calls = Calls::new();
|
||||
|
||||
let (out, missing) = interpolate_secrets_with("url={{URL}} key={{KEY}}", None, |name| {
|
||||
calls.record(name);
|
||||
match name {
|
||||
"URL" => Ok("https://example.test".to_string()),
|
||||
"KEY" => Ok("sk-12345".to_string()),
|
||||
other => panic!("unexpected lookup: {other}"),
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(calls.snapshot(), vec!["URL".to_string(), "KEY".to_string()]);
|
||||
assert_eq!(out, "url=https://example.test key=sk-12345");
|
||||
assert!(missing.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regex_rejects_braces_in_secret_names() {
|
||||
let calls = Calls::new();
|
||||
|
||||
let (out, missing) =
|
||||
interpolate_secrets_with("literal {{ {NOT_A_NAME} }} text", None, |name| {
|
||||
calls.record(name);
|
||||
Ok(format!("got-{name}"))
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert!(
|
||||
calls.snapshot().is_empty(),
|
||||
"name with embedded braces must not match"
|
||||
);
|
||||
assert_eq!(out, "literal {{ {NOT_A_NAME} }} text");
|
||||
assert!(missing.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fatal_failure_short_circuits_remaining_lines() {
|
||||
let calls = Calls::new();
|
||||
|
||||
let result =
|
||||
interpolate_secrets_with("a={{S1}}\nb={{S2}}\nc={{S3}}\nd={{S4}}", None, |name| {
|
||||
calls.record(name);
|
||||
match name {
|
||||
"S1" => Ok("first".to_string()),
|
||||
"S2" => Err(auth_failed()),
|
||||
other => Ok(format!("late-{other}")),
|
||||
}
|
||||
});
|
||||
|
||||
let err = result.unwrap_err().to_string();
|
||||
assert!(
|
||||
err.contains("S2"),
|
||||
"error should name the offending secret, got: {err}"
|
||||
);
|
||||
assert_eq!(
|
||||
calls.snapshot(),
|
||||
vec!["S1".to_string(), "S2".to_string()],
|
||||
"lookups must stop at the failing secret - S3 and S4 should never be fetched"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auth_failure_appends_hint_when_provided() {
|
||||
let result = interpolate_secrets_with(
|
||||
"k={{K}}",
|
||||
Some("run `coyote --authenticate` to reauth"),
|
||||
|_| Err(auth_failed()),
|
||||
);
|
||||
|
||||
let err = result.unwrap_err().to_string();
|
||||
|
||||
assert!(err.contains("Hint:"), "expected hint in error, got: {err}");
|
||||
assert!(
|
||||
err.contains("coyote --authenticate"),
|
||||
"expected hint contents, got: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user