feat: 技能帶參數:argument-hint/arguments($ARGUMENTS、$0…、$名字)、allowed-tools(這一輪只准用這些)、context: fork(在支線做)
- SKILL.md 開頭多四個欄位,寫法跟 Claude Code 一樣(一行逗號、[a, b]、或一行一個 - 都讀得懂),存回去也寫得回去。 - 「/名稱 參數」:技能有參數時,替模型加的那一行帶上參數,use_skill 多一個 arguments,讀到的做法裡換好(都沒寫就附在最後);沒參數的技能照舊。/ 清單顯示 argument-hint。 - allowed-tools 是限制不是放行:讀了這個技能之後這一輪只准用那些(Claude Code 的名字對到 AnyBot 的工具,Bash(git log:*) 是 shell(git log *),走 gate.rs 的固定樣式),別的步驟不執行;use_skill、read_result、ask_person 一定能用。裝來的技能不能替自己開權限。 - context: fork:打「/名稱 …」改開支線(跟 /btw 一樣);走 commands.rs 的 command_for,電腦和手機/螢幕一樣。 已驗證:cargo test 597 通過(欄位讀寫來回、參數代換含引號和 $5、名稱對照和樣式、真的一輪裡 use_skill 之後 edit_file 被擋、fork 技能變支線、沒參數的技能提示不變)、clippy -D warnings 乾淨。 未驗證:真的模型拿到參數和限制時的做法。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
f463026aa3
commit
f4911b1b7e
|
|
@ -1577,6 +1577,11 @@ computer_use_screenshot、click、mouse_move、mouse_button(按住/放開)
|
||||||
- 一次顯示 60 條,按「再顯示 N」看更多。
|
- 一次顯示 60 條,按「再顯示 N」看更多。
|
||||||
- **技能**:教 Bot 一套做法後請它「存成技能」(save_skill),所有 Bot 共用;系統指示只列名稱和一句說明,Bot 要用時先用 use_skill 讀完整做法。設定 →「連接器」頁的「技能」卡可以刪除。
|
- **技能**:教 Bot 一套做法後請它「存成技能」(save_skill),所有 Bot 共用;系統指示只列名稱和一句說明,Bot 要用時先用 use_skill 讀完整做法。設定 →「連接器」頁的「技能」卡可以刪除。
|
||||||
- **技能在大腦上**:Bot 在大腦上跑,技能也從大腦的硬碟讀。所以在大腦的螢幕(連到大腦的電腦)上,設定 › 整合的「加入」「安裝」「刪除」都請大腦做:GitHub/網址由大腦自己下載;填這台電腦上的資料夾或 .md 檔,就在這台讀好,連同 scripts/、references/ 和其他附檔整包交給大腦;刪除時大腦連資料夾一起刪,大腦重開也不會再冒出來。「開啟」照舊是一般的設定同步。「把這台的 Bot 搬到大腦」時,這台有、大腦沒有的技能也是整包交過去(連同開關和可重播的步驟)。手機本來就是請大腦做。大腦是舊版時,螢幕上的這些動作會說要先更新大腦。
|
- **技能在大腦上**:Bot 在大腦上跑,技能也從大腦的硬碟讀。所以在大腦的螢幕(連到大腦的電腦)上,設定 › 整合的「加入」「安裝」「刪除」都請大腦做:GitHub/網址由大腦自己下載;填這台電腦上的資料夾或 .md 檔,就在這台讀好,連同 scripts/、references/ 和其他附檔整包交給大腦;刪除時大腦連資料夾一起刪,大腦重開也不會再冒出來。「開啟」照舊是一般的設定同步。「把這台的 Bot 搬到大腦」時,這台有、大腦沒有的技能也是整包交過去(連同開關和可重播的步驟)。手機本來就是請大腦做。大腦是舊版時,螢幕上的這些動作會說要先更新大腦。
|
||||||
|
- **技能帶參數**(SKILL.md 開頭的欄位,寫法跟 Claude Code 的技能一樣,裝來的技能直接能用;存回去時也寫得回去):
|
||||||
|
- `argument-hint: <版本> [格式]`:/ 清單裡技能說明前面顯示要打什麼。
|
||||||
|
- `arguments: [version, format]`:有名字的參數。「/名稱 參數」送出後(技能有寫 arguments、argument-hint,或做法裡用到 $ARGUMENTS、$0 這些才算有參數;沒有的話後面的字就是要做的事),大腦替模型加的那一行會帶上參數,模型用 `use_skill`(arguments 填那段參數)讀做法:$ARGUMENTS 換成全部、$ARGUMENTS[N] 和 $N 換成第 N 個(從 0 數,跟 Claude Code 一樣)、$version 換成那個名字的;做法裡都沒寫,就在最後附「ARGUMENTS: …」。引號("…" 或「…」)裡的字算一個。
|
||||||
|
- `allowed-tools`(一行用逗號隔開、[a, b],或一行一個 `- Read`):讀了這個技能之後,這一輪接下來只能用這些工具;別的步驟不執行,結果寫「沒有執行:這一輪用的技能「…」只准用 …」。Claude Code 的名字對應到 AnyBot 的(Read→read_file、Edit/Write→edit_file、Bash→shell、Grep/Glob→search、LS→list_dir、WebFetch→web_fetch),`Bash(git log:*)` 是 `shell(git log *)`;也可以直接寫 AnyBot 的固定樣式(shell(git *)、file(~/Projects/**)、connector(…))。use_skill、read_result、ask_person 一定能用。這是**限制**,不是放行:跟 Claude Code 把它當「不用問」不一樣——從網路裝的技能不能替自己開權限,要核准的照樣問。
|
||||||
|
- `context: fork`:使用者打「/名稱 …」時不在主對話做,改開一條支線(跟 /btw 一樣,做完回報),主對話不會被它的步驟塞滿。Bot 自己用 use_skill 讀它時照常在這一輪做。
|
||||||
- **用 / 指定技能**(現在只打「/」只列指令,打字後才找這個 Bot 自己的技能,見「「/」清單只放指令」):輸入框第一個字打「/」,上面就列出開著的技能(名稱開頭符合的先、名稱含有的次之、再來是說明裡有的,例如「/簡報」找到 pptx);點一下,或 ↑↓ 選、Enter/Tab 帶入,輸入框變成「/pptx 」接著打要做的事,Esc 關掉清單。電腦和手機都有,Bot 正在做事時不列(那時打的字會併進正在做的事)。送出後由大腦認出「/名稱」,在這則訊息後面替模型加一行「使用者用 /pptx 指定了技能「pptx」:先用 use_skill 讀出它的完整做法」,所以從手機、訊息管道打的也算;不是技能名稱的(例如 /Users/… 路徑)不加。新加的技能(技能市集、GitHub 安裝、Bot 存的或自己學會的、「教我做」)馬上就在清單裡:電腦直接讀技能名單(大腦的螢幕讀的是大腦同步過來的那份);手機每次打出新的「/」會向大腦再拿一次名單,拿到前先列手上已有的。篩選本身不連網,也不多送東西給模型(技能清單本來就在系統指示裡)。
|
- **用 / 指定技能**(現在只打「/」只列指令,打字後才找這個 Bot 自己的技能,見「「/」清單只放指令」):輸入框第一個字打「/」,上面就列出開著的技能(名稱開頭符合的先、名稱含有的次之、再來是說明裡有的,例如「/簡報」找到 pptx);點一下,或 ↑↓ 選、Enter/Tab 帶入,輸入框變成「/pptx 」接著打要做的事,Esc 關掉清單。電腦和手機都有,Bot 正在做事時不列(那時打的字會併進正在做的事)。送出後由大腦認出「/名稱」,在這則訊息後面替模型加一行「使用者用 /pptx 指定了技能「pptx」:先用 use_skill 讀出它的完整做法」,所以從手機、訊息管道打的也算;不是技能名稱的(例如 /Users/… 路徑)不加。新加的技能(技能市集、GitHub 安裝、Bot 存的或自己學會的、「教我做」)馬上就在清單裡:電腦直接讀技能名單(大腦的螢幕讀的是大腦同步過來的那份);手機每次打出新的「/」會向大腦再拿一次名單,拿到前先列手上已有的。篩選本身不連網,也不多送東西給模型(技能清單本來就在系統指示裡)。
|
||||||
- **/goal 目標**(照 Claude Code 的 /goal 做):給 Bot 一個「做到什麼程度才算完成」的條件,它就一輪接一輪做下去,不用每一步都叫它。關鍵是**做事的模型不能自己宣布完成**:每一輪結束後,另一個模型(Bot 的「執行步驟用的模型」,通常是快速模型;設成「關閉」就用 Bot 自己的模型)只看這段對話(Bot 說的話、用了哪些工具、工具回了什麼),判斷條件成立了沒有。
|
- **/goal 目標**(照 Claude Code 的 /goal 做):給 Bot 一個「做到什麼程度才算完成」的條件,它就一輪接一輪做下去,不用每一步都叫它。關鍵是**做事的模型不能自己宣布完成**:每一輪結束後,另一個模型(Bot 的「執行步驟用的模型」,通常是快速模型;設成「關閉」就用 Bot 自己的模型)只看這段對話(Bot 說的話、用了哪些工具、工具回了什麼),判斷條件成立了沒有。
|
||||||
- **用法**:「/goal 所有測試都通過,而且 clippy 沒有新的警告」設定並馬上開始做(已經有目標就換掉);「/goal」看目前的目標、做了多久、檢查了幾輪、最近一次檢查的理由;「/goal clear」清除(stop、off、reset、none、cancel、清除、取消、停止也可以)。在 / 清單最上面,標「指令和技能」。電腦、大腦的螢幕、手機打的都算,由大腦處理;訊息管道(Slack、Telegram…)和團隊成員打的不算指令,別人不能替你設目標。條件最多 4000 字;群組聊天還不能設目標。「清除聊天記錄」和「開始新對話」會連目標一起清掉;分享 Bot 的檔案不含目標。
|
- **用法**:「/goal 所有測試都通過,而且 clippy 沒有新的警告」設定並馬上開始做(已經有目標就換掉);「/goal」看目前的目標、做了多久、檢查了幾輪、最近一次檢查的理由;「/goal clear」清除(stop、off、reset、none、cancel、清除、取消、停止也可以)。在 / 清單最上面,標「指令和技能」。電腦、大腦的螢幕、手機打的都算,由大腦處理;訊息管道(Slack、Telegram…)和團隊成員打的不算指令,別人不能替你設目標。條件最多 4000 字;群組聊天還不能設目標。「清除聊天記錄」和「開始新對話」會連目標一起清掉;分享 Bot 的檔案不含目標。
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@
|
||||||
- 網站地圖:同一個網站的操作知識放在「<網站名> 網站地圖」這份技能,固定四段:## 功能、## 怎麼到、## 怎麼操作、## 陷阱。做事的技能只寫這件事特有的部分,開頭寫「先 use_skill 讀「<網站名> 網站地圖」」。
|
- 網站地圖:同一個網站的操作知識放在「<網站名> 網站地圖」這份技能,固定四段:## 功能、## 怎麼到、## 怎麼操作、## 陷阱。做事的技能只寫這件事特有的部分,開頭寫「先 use_skill 讀「<網站名> 網站地圖」」。
|
||||||
- 可重播:自動學時留下這次真的成功、會改變東西的步驟(不含截圖、讀取),每一步點的東西記成名字(「按鈕「Save」」),不記編號。每次不一樣的內容(留言文字、貼文網址、檔名)變成空格 `{{名稱}}`,重播時再填。
|
- 可重播:自動學時留下這次真的成功、會改變東西的步驟(不含截圖、讀取),每一步點的東西記成名字(「按鈕「Save」」),不記編號。每次不一樣的內容(留言文字、貼文網址、檔名)變成空格 `{{名稱}}`,重播時再填。
|
||||||
- 手機的「教我做(學這一回合)」:把那一回合成功的步驟存成可重播技能。
|
- 手機的「教我做(學這一回合)」:把那一回合成功的步驟存成可重播技能。
|
||||||
|
- 技能帶參數(SKILL.md 開頭,跟 Claude Code 一樣寫法):`argument-hint`(/ 清單裡顯示要打什麼)、`arguments: [版本, 格式]`;「/名稱 參數」送出後,`use_skill` 帶 arguments 讀到的做法裡 $ARGUMENTS 換成全部參數、$0 $1… 第幾個(從 0 數)、$版本 這種是有名字的那個,都沒寫就附在最後「ARGUMENTS: …」。`allowed-tools`(Read、Bash(git log:*) 這種 Claude Code 的寫法,或 shell(git *)、file(…)):讀了這個技能之後,這一輪只能用這些工具,其他的不執行。`context: fork`:使用者打「/名稱 …」時改在支線做(像 /btw),不佔主對話。
|
||||||
|
|
||||||
## 使用者怎麼到
|
## 使用者怎麼到
|
||||||
|
|
||||||
|
|
@ -24,7 +25,7 @@
|
||||||
## 怎麼操作
|
## 怎麼操作
|
||||||
|
|
||||||
- Bot:開始做事前先看技能清單,符合就 `use_skill`(name;要讀附檔加 `file`,例如 scripts/audit_xlsx.py)。使用者教你一套做法或請你建技能時用 `save_skill`(name、description 寫什麼時候用、instructions,可附 files)。`delete_skill` 刪除(要有「管理 App」能力)。要做的事和標著「可重播」的技能一模一樣時用 `replay_skill`(name;有空格就用 values 給每一格這次的內容;computer 只在要換到別台時給),做完自己看結果再回答;還有別的不一樣,就 `use_skill` 讀了自己做。
|
- Bot:開始做事前先看技能清單,符合就 `use_skill`(name;要讀附檔加 `file`,例如 scripts/audit_xlsx.py)。使用者教你一套做法或請你建技能時用 `save_skill`(name、description 寫什麼時候用、instructions,可附 files)。`delete_skill` 刪除(要有「管理 App」能力)。要做的事和標著「可重播」的技能一模一樣時用 `replay_skill`(name;有空格就用 values 給每一格這次的內容;computer 只在要換到別台時給),做完自己看結果再回答;還有別的不一樣,就 `use_skill` 讀了自己做。
|
||||||
- 驗證:設定 › 整合 › 技能 從「內建技能包」加一個,Bot 設定 › 技能 要看得到它;請 Bot 用它,步驟要出現「正在讀技能:…」。請 Bot 在網頁上做一件 5 步以上的事,回覆下面要出現「(學會了新做法「…」…)」,技能頁那一列按「檢視」要看到「可重播 N 步」;再請它做同一件事,要看到「正在照技能重做:…」,重播的步驟標「(重播)」。自動測試:`cargo test skills::`、`cargo test memory::`、`cargo test appctl::`、`cargo test agent::`、`cargo test profile::`。
|
- 驗證:設定 › 整合 › 技能 從「內建技能包」加一個,Bot 設定 › 技能 要看得到它;請 Bot 用它,步驟要出現「正在讀技能:…」。請 Bot 在網頁上做一件 5 步以上的事,回覆下面要出現「(學會了新做法「…」…)」,技能頁那一列按「檢視」要看到「可重播 N 步」;再請它做同一件事,要看到「正在照技能重做:…」,重播的步驟標「(重播)」。技能帶參數:做一個 `allowed-tools: Read` 的技能,打「/名稱」後請它改檔案,那一步要被擋(「只准用」)。自動測試:`cargo test skills::`、`cargo test a_skills_allowed_tools`、`cargo test a_fork_skill`、`cargo test memory::`、`cargo test appctl::`、`cargo test agent::`、`cargo test profile::`。
|
||||||
|
|
||||||
## 陷阱
|
## 陷阱
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -109,7 +109,7 @@
|
||||||
- 做法:Bot 給一條指令,每輸出一行就變成一則通知/訊息;自動 line-buffered;一次失敗不停;太多行自動停並說明。
|
- 做法:Bot 給一條指令,每輸出一行就變成一則通知/訊息;自動 line-buffered;一次失敗不停;太多行自動停並說明。
|
||||||
- 做完:`tail -f` 一個檔案,寫三行收到三則;一秒寫一千行會自動停。
|
- 做完:`tail -f` 一個檔案,寫三行收到三則;一秒寫一千行會自動停。
|
||||||
|
|
||||||
### M4. 技能帶參數 ⬜
|
### M4. 技能帶參數 ✅(allowed-tools 做成限制、不是放行:裝來的技能不能替自己開權限;$N 從 0 數,跟 Claude Code 一樣)
|
||||||
- 做法:SKILL.md frontmatter:`arguments`(`$ARGUMENTS`、`$1`…)、`allowed-tools`(只能用哪些工具,執行層擋)、`context: fork`(丟給支線做,不佔主對話)。「/技能名 參數」直接帶進去。
|
- 做法:SKILL.md frontmatter:`arguments`(`$ARGUMENTS`、`$1`…)、`allowed-tools`(只能用哪些工具,執行層擋)、`context: fork`(丟給支線做,不佔主對話)。「/技能名 參數」直接帶進去。
|
||||||
- 做完:測試涵蓋三種。
|
- 做完:測試涵蓋三種。
|
||||||
|
|
||||||
|
|
|
||||||
45
src/agent.rs
45
src/agent.rs
|
|
@ -1698,6 +1698,9 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
||||||
// 拒絕後停下: what the person refused this turn (tool and arguments). The same step isn't
|
// 拒絕後停下: what the person refused this turn (tool and arguments). The same step isn't
|
||||||
// put to them a second time — it is refused for them — until they write again.
|
// put to them a second time — it is refused for them — until they write again.
|
||||||
let said_no = std::cell::Cell::new(false);
|
let said_no = std::cell::Cell::new(false);
|
||||||
|
// 技能的 allowed-tools (M4): once a skill that names its tools is loaded, the rest of the
|
||||||
|
// turn uses only those (its name, its rules for gate::patterns).
|
||||||
|
let skill_limit: std::cell::RefCell<Option<(String, Vec<String>)>> = std::cell::RefCell::new(None);
|
||||||
let refused: std::cell::RefCell<Vec<String>> = Default::default();
|
let refused: std::cell::RefCell<Vec<String>> = Default::default();
|
||||||
// Turned on by an "always" answer mid-turn (the window saves the setting too).
|
// Turned on by an "always" answer mid-turn (the window saves the setting too).
|
||||||
let mut tools_on = job.tools_enabled;
|
let mut tools_on = job.tools_enabled;
|
||||||
|
|
@ -2120,6 +2123,13 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
||||||
finish(&mut history, &crate::profile::lacking_text(k), ToolStatus::Denied, None);
|
finish(&mut history, &crate::profile::lacking_text(k), ToolStatus::Denied, None);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
// A loaded skill's allowed-tools: anything else isn't run this turn.
|
||||||
|
let outside = skill_limit.borrow().as_ref().filter(|(_, rules)| !crate::skills::skill_allows(rules, &call.name, &call.args)).map(|(name, rules)| (name.clone(), rules.clone()));
|
||||||
|
if let Some((skill, rules)) = outside {
|
||||||
|
let text = format!("沒有執行:這一輪用的技能「{skill}」只准用 {},「{}」不在裡面。照技能的做法用那些工具做;真的需要別的,先告訴使用者。", rules.join("、"), call.name);
|
||||||
|
finish(&mut history, &text, ToolStatus::Denied, None);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if call.name == REPLAY_TOOL {
|
if call.name == REPLAY_TOOL {
|
||||||
let v = tools::args_of(&call.args);
|
let v = tools::args_of(&call.args);
|
||||||
let name = v["name"].as_str().unwrap_or("").trim().to_string();
|
let name = v["name"].as_str().unwrap_or("").trim().to_string();
|
||||||
|
|
@ -2201,6 +2211,12 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc<
|
||||||
if denied {
|
if denied {
|
||||||
said_no.set(true);
|
said_no.set(true);
|
||||||
}
|
}
|
||||||
|
if ok && call.name == "use_skill" && tools::args_of(&call.args)["file"].as_str().unwrap_or("").trim().is_empty() {
|
||||||
|
let want = tools::args_of(&call.args)["name"].as_str().unwrap_or("").trim().to_lowercase();
|
||||||
|
if let Some(k) = job.skills.iter().find(|k| k.name.to_lowercase() == want).filter(|k| !k.allowed_tools.is_empty()) {
|
||||||
|
*skill_limit.borrow_mut() = Some((k.name.clone(), crate::skills::tool_rules(k)));
|
||||||
|
}
|
||||||
|
}
|
||||||
finish(&mut history, &output, if ok { ToolStatus::Done } else if denied { ToolStatus::Denied } else { ToolStatus::Failed }, None);
|
finish(&mut history, &output, if ok { ToolStatus::Done } else if denied { ToolStatus::Denied } else { ToolStatus::Failed }, None);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
@ -5498,6 +5514,35 @@ echo '<meta charset=utf-8><title>done</title>送出了' > done.html; (setsid pyt
|
||||||
(evs, asked)
|
(evs, asked)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 技能的 allowed-tools (M4): after use_skill loads a skill that names its tools, a step
|
||||||
|
/// outside them is refused (not run) for the rest of the turn; one inside goes on.
|
||||||
|
#[test]
|
||||||
|
fn a_skills_allowed_tools_hold_for_the_turn() {
|
||||||
|
let (port, _) = fake_http(vec![
|
||||||
|
sse_call("c1", "use_skill", serde_json::json!({"name": "只讀"})),
|
||||||
|
sse_call("c2", "edit_file", serde_json::json!({"path": "x.txt", "new_text": "hi"})),
|
||||||
|
sse_text("好,我只讀"),
|
||||||
|
]);
|
||||||
|
let mut job = test_job();
|
||||||
|
job.req = ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "m".into(), system: String::new(), history: vec![Message::user("/只讀")], tools: tools::specs(), session: String::new(), effort: String::new() };
|
||||||
|
job.skills = vec![crate::memory::Skill { name: "只讀".into(), instructions: "只看".into(), allowed_tools: vec!["Read".into(), "Grep".into()], ..Default::default() }];
|
||||||
|
let (tx, rx) = channel();
|
||||||
|
spawn(job, 1, tx, Arc::new(AtomicBool::new(false)), eframe::egui::Context::default());
|
||||||
|
let mut results = vec![];
|
||||||
|
loop {
|
||||||
|
let (_, ev) = rx.recv_timeout(Duration::from_secs(15)).expect("loop stalled");
|
||||||
|
match ev {
|
||||||
|
StreamEvent::AppAction(a) => {
|
||||||
|
let _ = a.reply.send(("技能「只讀」的做法:只看".into(), true));
|
||||||
|
}
|
||||||
|
StreamEvent::ToolResult(m) => results.push(m.text.clone()),
|
||||||
|
StreamEvent::Done | StreamEvent::Error(_) => break,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(results.iter().any(|r| r.contains("只准用") && r.contains("edit_file")), "{results:?}");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_verdict_is_clear_or_the_review_failed() {
|
fn a_verdict_is_clear_or_the_review_failed() {
|
||||||
assert!(matches!(parse_verdict(r#"{"verdict":"ask","rule":"刪除前先問"}"#), ReviewVerdict::Ask(r) if r == "刪除前先問"));
|
assert!(matches!(parse_verdict(r#"{"verdict":"ask","rule":"刪除前先問"}"#), ReviewVerdict::Ask(r) if r == "刪除前先問"));
|
||||||
|
|
|
||||||
|
|
@ -45,7 +45,6 @@ mod memory_ui;
|
||||||
mod goal_ui;
|
mod goal_ui;
|
||||||
mod context_ui;
|
mod context_ui;
|
||||||
mod commands;
|
mod commands;
|
||||||
use commands::app_command;
|
|
||||||
mod doctor_ui;
|
mod doctor_ui;
|
||||||
mod plan_ui;
|
mod plan_ui;
|
||||||
mod mood_ui;
|
mod mood_ui;
|
||||||
|
|
@ -1431,7 +1430,7 @@ impl App {
|
||||||
}
|
}
|
||||||
// 先顯示: while it works (or the words travel to the brain) they aren't in the chat
|
// 先顯示: while it works (or the words travel to the brain) they aren't in the chat
|
||||||
// yet — the person sees them at once all the same. (A command here draws its own line.)
|
// yet — the person sees them at once all the same. (A command here draws its own line.)
|
||||||
let local_command = !self.mir.on && app_command(&text).is_some();
|
let local_command = !self.mir.on && self.command_for(bot_id, &text).is_some();
|
||||||
if self.streams.contains_key(&bot_id) && !text.trim().is_empty() && !local_command {
|
if self.streams.contains_key(&bot_id) && !text.trim().is_empty() && !local_command {
|
||||||
self.sending.entry(bot_id).or_default().push((text.trim().to_string(), Instant::now()));
|
self.sending.entry(bot_id).or_default().push((text.trim().to_string(), Instant::now()));
|
||||||
}
|
}
|
||||||
|
|
@ -1464,7 +1463,7 @@ impl App {
|
||||||
// AnyBot's own commands (/btw even while it works: it isn't steering; /goal, /plan,
|
// AnyBot's own commands (/btw even while it works: it isn't steering; /goal, /plan,
|
||||||
// /always-approve, /usage, /context, /compact, /fork — commands.rs); anything else takes a
|
// /always-approve, /usage, /context, /compact, /fork — commands.rs); anything else takes a
|
||||||
// paused goal up again.
|
// paused goal up again.
|
||||||
if let Some(cmd) = app_command(&text) {
|
if let Some(cmd) = self.command_for(bot_id, &text) {
|
||||||
self.run_app_command(ctx, bot_id, cmd, &text, attachments, picks);
|
self.run_app_command(ctx, bot_id, cmd, &text, attachments, picks);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
@ -6772,7 +6771,7 @@ fn group_history(messages: &[Message], speaker: Option<u64>, conv: u64, st: &Sta
|
||||||
}
|
}
|
||||||
// 「/pptx …」: the person picked the skill, so the model reads it before anything else.
|
// 「/pptx …」: the person picked the skill, so the model reads it before anything else.
|
||||||
if let Some(k) = crate::memory::named_skill(&m.text, &st.skills).filter(|_| m.goal.is_empty()) {
|
if let Some(k) = crate::memory::named_skill(&m.text, &st.skills).filter(|_| m.goal.is_empty()) {
|
||||||
let line = crate::memory::named_skill_line(k);
|
let line = crate::memory::named_skill_line(k, &m.text);
|
||||||
m.context = if m.context.is_empty() { line } else { format!("{}\n{line}", m.context) };
|
m.context = if m.context.is_empty() { line } else { format!("{}\n{line}", m.context) };
|
||||||
}
|
}
|
||||||
// 同事之間: who sent it, whether it waits for the answer, and that it isn't the
|
// 同事之間: who sent it, whether it waits for the answer, and that it isn't the
|
||||||
|
|
|
||||||
|
|
@ -1015,7 +1015,8 @@ impl App {
|
||||||
let mut list: Vec<(String, String)> = slash_commands(draft).into_iter().map(|(n, d)| (n.to_string(), t(d))).collect();
|
let mut list: Vec<(String, String)> = slash_commands(draft).into_iter().map(|(n, d)| (n.to_string(), t(d))).collect();
|
||||||
if draft.len() > 1 {
|
if draft.len() > 1 {
|
||||||
let mine = crate::memory::slash_matches(draft, &self.state.skills).unwrap_or_default().into_iter().filter(|k| !SLASH_COMMANDS.iter().any(|(n, _)| *n == k.name) && crate::profile::has_skill(bot, &k.name));
|
let mine = crate::memory::slash_matches(draft, &self.state.skills).unwrap_or_default().into_iter().filter(|k| !SLASH_COMMANDS.iter().any(|(n, _)| *n == k.name) && crate::profile::has_skill(bot, &k.name));
|
||||||
list.extend(mine.take(SLASH_SKILLS).map(|k| (k.name.clone(), k.description.clone())));
|
// (What to type after it, when the skill says: 「/pptx 〈主題〉」.)
|
||||||
|
list.extend(mine.take(SLASH_SKILLS).map(|k| (k.name.clone(), if k.argument_hint.is_empty() { k.description.clone() } else { format!("{} · {}", k.argument_hint, k.description) })));
|
||||||
}
|
}
|
||||||
list
|
list
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -70,6 +70,16 @@ pub(super) fn app_command(text: &str) -> Option<AppCommand> {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl App {
|
impl App {
|
||||||
|
/// The command these words are for this bot: AnyBot's own, or 「/技能 …」 for one of its skills
|
||||||
|
/// marked `context: fork` (技能帶參數, M4), which goes to a 支線 as it was typed.
|
||||||
|
pub(super) fn command_for(&self, bot_id: u64, text: &str) -> Option<AppCommand> {
|
||||||
|
app_command(text).or_else(|| {
|
||||||
|
let b = self.state.bot(bot_id)?;
|
||||||
|
let mine = crate::profile::skills_of(b, &self.state.skills);
|
||||||
|
crate::memory::named_skill(text, &mine).filter(|k| k.fork).map(|_| AppCommand::Btw(text.trim().to_string()))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// Carry out one of AnyBot's commands for this bot.
|
/// Carry out one of AnyBot's commands for this bot.
|
||||||
pub(super) fn run_app_command(&mut self, ctx: &egui::Context, bot_id: u64, cmd: AppCommand, text: &str, attachments: Vec<crate::attach::Attachment>, picks: Option<Vec<String>>) {
|
pub(super) fn run_app_command(&mut self, ctx: &egui::Context, bot_id: u64, cmd: AppCommand, text: &str, attachments: Vec<crate::attach::Attachment>, picks: Option<Vec<String>>) {
|
||||||
match cmd {
|
match cmd {
|
||||||
|
|
@ -293,4 +303,21 @@ mod tests {
|
||||||
assert!(!w.join("INSTALL.md").exists());
|
assert!(!w.join("INSTALL.md").exists());
|
||||||
let _ = std::fs::remove_dir_all(&w);
|
let _ = std::fs::remove_dir_all(&w);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 「/技能 …」 for a skill marked context: fork goes to a 支線; other skills and words don't.
|
||||||
|
#[test]
|
||||||
|
fn a_fork_skill_runs_off_the_main_chat() {
|
||||||
|
let ctx = egui::Context::default();
|
||||||
|
let mut app = App::new(&ctx, Some(std::env::temp_dir().join("anybot-fork-skill.png")));
|
||||||
|
let id = app.state.bots.iter().find(|b| b.members.is_empty()).unwrap().id;
|
||||||
|
app.state.skills.push(crate::memory::Skill { name: "研究".into(), description: "查資料".into(), instructions: "查 $ARGUMENTS".into(), fork: true, ..Default::default() });
|
||||||
|
app.state.skills.push(crate::memory::Skill { name: "簡報".into(), description: "做簡報".into(), instructions: "做".into(), ..Default::default() });
|
||||||
|
if let Some(b) = app.state.bot_mut(id) {
|
||||||
|
b.skills = None;
|
||||||
|
}
|
||||||
|
assert!(matches!(app.command_for(id, "/研究 台灣的太陽能"), Some(AppCommand::Btw(t)) if t == "/研究 台灣的太陽能"));
|
||||||
|
assert!(app.command_for(id, "/簡報 Q3").is_none());
|
||||||
|
assert!(app.command_for(id, "研究一下").is_none());
|
||||||
|
assert!(matches!(app.command_for(id, "/fork"), Some(AppCommand::Fork(_))));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -538,7 +538,7 @@ impl App {
|
||||||
// AnyBot's own commands from the phone or a screen (commands.rs): the owner's
|
// AnyBot's own commands from the phone or a screen (commands.rs): the owner's
|
||||||
// only (a teammate's words arrive as 「【名字】…」, never a command). A
|
// only (a teammate's words arrive as 「【名字】…」, never a command). A
|
||||||
// /doctor from there: the brain checks itself.
|
// /doctor from there: the brain checks itself.
|
||||||
if let Some(cmd) = super::app_command(&text) {
|
if let Some(cmd) = self.command_for(bot, &text) {
|
||||||
self.run_app_command(ctx, bot, cmd, &text, atts, memories);
|
self.run_app_command(ctx, bot, cmd, &text, atts, memories);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -96,7 +96,7 @@ pub fn specs() -> Vec<Value> {
|
||||||
json!({"name": "forget", "description": "Forget a remembered fact: give the fact's own words (or words in it).", "parameters": {"type": "object", "properties": {"what": {"type": "string"}}, "required": ["what"]}}),
|
json!({"name": "forget", "description": "Forget a remembered fact: give the fact's own words (or words in it).", "parameters": {"type": "object", "properties": {"what": {"type": "string"}}, "required": ["what"]}}),
|
||||||
json!({"name": "search_memory", "description": "Look through everything this bot remembers — what the person asked you to keep (facts, preferences, decisions) and what you did for them before (one line per past task, older ones folded by week and month) — by meaning as well as words. Use it when the memories that came with the message aren't enough: 「上次怎麼做的」, 「我說過喜歡哪家」, 「上個月那份報表」. Answers with dates.", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "What to look for, in the person's words."}, "kind": {"type": "string", "enum": ["all", "fact", "event"], "description": "fact = things to remember, event = things done before; default all."}}, "required": ["query"]}}),
|
json!({"name": "search_memory", "description": "Look through everything this bot remembers — what the person asked you to keep (facts, preferences, decisions) and what you did for them before (one line per past task, older ones folded by week and month) — by meaning as well as words. Use it when the memories that came with the message aren't enough: 「上次怎麼做的」, 「我說過喜歡哪家」, 「上個月那份報表」. Answers with dates.", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "What to look for, in the person's words."}, "kind": {"type": "string", "enum": ["all", "fact", "event"], "description": "fact = things to remember, event = things done before; default all."}}, "required": ["query"]}}),
|
||||||
json!({"name": "save_skill", "description": "Save a reusable procedure as an Agent Skill package (`SKILL.md` plus optional bundled `scripts/` or `references/` files) that every bot can use. Replaces one with the same name.", "parameters": {"type": "object", "properties": {"name": {"type": "string"}, "description": {"type": "string", "description": "What this skill does and WHEN bots should trigger it"}, "instructions": {"type": "string", "description": "The full Markdown instructions (`SKILL.md` body)"}, "files": {"type": "array", "description": "Optional bundled helper scripts or reference docs saved inside the skill folder.", "items": {"type": "object", "properties": {"path": {"type": "string", "description": "Relative path, e.g. scripts/check.py or references/guide.md"}, "content": {"type": "string"}}, "required": ["path", "content"]}}}, "required": ["name", "description", "instructions"]}}),
|
json!({"name": "save_skill", "description": "Save a reusable procedure as an Agent Skill package (`SKILL.md` plus optional bundled `scripts/` or `references/` files) that every bot can use. Replaces one with the same name.", "parameters": {"type": "object", "properties": {"name": {"type": "string"}, "description": {"type": "string", "description": "What this skill does and WHEN bots should trigger it"}, "instructions": {"type": "string", "description": "The full Markdown instructions (`SKILL.md` body)"}, "files": {"type": "array", "description": "Optional bundled helper scripts or reference docs saved inside the skill folder.", "items": {"type": "object", "properties": {"path": {"type": "string", "description": "Relative path, e.g. scripts/check.py or references/guide.md"}, "content": {"type": "string"}}, "required": ["path", "content"]}}}, "required": ["name", "description", "instructions"]}}),
|
||||||
json!({"name": "use_skill", "description": "Load a skill's full `SKILL.md` instructions before doing that kind of task, or pass `file` to read one of its bundled `scripts/` / `references/` files.", "parameters": {"type": "object", "properties": {"name": {"type": "string"}, "file": {"type": "string", "description": "Optional relative path of a bundled file listed by this skill, e.g. scripts/audit_xlsx.py"}}, "required": ["name"]}}),
|
json!({"name": "use_skill", "description": "Load a skill's full `SKILL.md` instructions before doing that kind of task, or pass `file` to read one of its bundled `scripts/` / `references/` files. `arguments`: what the person typed after 「/名稱」 (the skill's $ARGUMENTS). A skill with allowed-tools limits which tools you may use for the rest of this turn.", "parameters": {"type": "object", "properties": {"name": {"type": "string"}, "file": {"type": "string", "description": "Optional relative path of a bundled file listed by this skill, e.g. scripts/audit_xlsx.py"}, "arguments": {"type": "string", "description": "The words after 「/名稱」, put into the skill where it says $ARGUMENTS, $0, $1… or $name."}}, "required": ["name"]}}),
|
||||||
json!({"name": "delete_skill", "description": "Delete a skill.", "parameters": {"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]}}),
|
json!({"name": "delete_skill", "description": "Delete a skill.", "parameters": {"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]}}),
|
||||||
json!({"name": "create_routine", "description": "Set up a routine when the person wants something done on a schedule (every morning, every Monday, on the 1st…) or when something happens (a PR is merged, CI fails, a Slack message mentions a word, a Sentry/PagerDuty/Linear change, a new email, a webhook call): give schedule or trigger. The prompt is what you will be asked each time it runs.",
|
json!({"name": "create_routine", "description": "Set up a routine when the person wants something done on a schedule (every morning, every Monday, on the 1st…) or when something happens (a PR is merged, CI fails, a Slack message mentions a word, a Sentry/PagerDuty/Linear change, a new email, a webhook call): give schedule or trigger. The prompt is what you will be asked each time it runs.",
|
||||||
"parameters": {"type": "object", "properties": {
|
"parameters": {"type": "object", "properties": {
|
||||||
|
|
@ -714,7 +714,7 @@ pub fn apply(state: &mut State, bot_id: u64, name: &str, args: &str) -> Outcome
|
||||||
.find(|k| k.name.eq_ignore_ascii_case(want))
|
.find(|k| k.name.eq_ignore_ascii_case(want))
|
||||||
.or_else(|| mine.iter().find(|k| !want.is_empty() && k.name.to_lowercase().contains(&want.to_lowercase())));
|
.or_else(|| mine.iter().find(|k| !want.is_empty() && k.name.to_lowercase().contains(&want.to_lowercase())));
|
||||||
match found {
|
match found {
|
||||||
Some(k) => match crate::skills::format_skill_for_model(k, s("file").as_deref()) {
|
Some(k) => match crate::skills::format_skill_for_model(k, s("file").as_deref(), s("arguments").as_deref()) {
|
||||||
Ok(text) => ok(text),
|
Ok(text) => ok(text),
|
||||||
Err(e) => err(e),
|
Err(e) => err(e),
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -39,6 +39,18 @@ pub struct Skill {
|
||||||
/// Origin label (`builtin:<slug>`, `owner/repo/...`, `"learned"`, …).
|
/// Origin label (`builtin:<slug>`, `owner/repo/...`, `"learned"`, …).
|
||||||
#[serde(default, skip_serializing_if = "String::is_empty")]
|
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||||
pub source: String,
|
pub source: String,
|
||||||
|
/// 技能帶參數 (M4): what to type after 「/名稱」 (frontmatter `argument-hint`), shown in the / list.
|
||||||
|
#[serde(default, skip_serializing_if = "String::is_empty")]
|
||||||
|
pub argument_hint: String,
|
||||||
|
/// Named arguments (frontmatter `arguments`): `$name` is the one at its place.
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub arguments: Vec<String>,
|
||||||
|
/// The only tools it may use once loaded (frontmatter `allowed-tools`; empty: no limit).
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub allowed_tools: Vec<String>,
|
||||||
|
/// 「/名稱 …」 runs it in a 支線, off the main chat (frontmatter `context: fork`).
|
||||||
|
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||||
|
pub fork: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for Skill {
|
impl Default for Skill {
|
||||||
|
|
@ -52,6 +64,10 @@ impl Default for Skill {
|
||||||
dir: String::new(),
|
dir: String::new(),
|
||||||
resources: vec![],
|
resources: vec![],
|
||||||
source: String::new(),
|
source: String::new(),
|
||||||
|
argument_hint: String::new(),
|
||||||
|
arguments: vec![],
|
||||||
|
allowed_tools: vec![],
|
||||||
|
fork: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -729,9 +745,16 @@ pub fn named_skill<'a>(text: &str, skills: &'a [Skill]) -> Option<&'a Skill> {
|
||||||
.max_by_key(|k| k.name.len())
|
.max_by_key(|k| k.name.len())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What the model reads after a message that names a skill.
|
/// What the model reads after a message that names a skill (with what was typed after the name,
|
||||||
pub fn named_skill_line(k: &Skill) -> String {
|
/// its arguments, when anything was).
|
||||||
|
pub fn named_skill_line(k: &Skill, text: &str) -> String {
|
||||||
|
let args = crate::skills::arguments_after(text, &k.name);
|
||||||
|
// (A skill that takes no arguments: the words after its name are just the task, already there.)
|
||||||
|
if args.is_empty() || !crate::skills::takes_arguments(k) {
|
||||||
format!("〔使用者用 /{0} 指定了技能「{0}」:先用 use_skill 讀出它的完整做法,再照著做這件事〕", k.name)
|
format!("〔使用者用 /{0} 指定了技能「{0}」:先用 use_skill 讀出它的完整做法,再照著做這件事〕", k.name)
|
||||||
|
} else {
|
||||||
|
format!("〔使用者用 /{0} 指定了技能「{0}」,參數是「{1}」:先用 use_skill(name 填「{0}」,arguments 填「{1}」)讀出它的完整做法,再照著做〕", k.name, args)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The composer's / list for a draft like 「/pp」: the skills that are on, those whose name
|
/// The composer's / list for a draft like 「/pp」: the skills that are on, those whose name
|
||||||
|
|
@ -1352,7 +1375,10 @@ mod tests {
|
||||||
assert_eq!(named("/pptxx 做簡報"), None, "more of a word is another name");
|
assert_eq!(named("/pptxx 做簡報"), None, "more of a word is another name");
|
||||||
assert_eq!(named("/pptx-old 做簡報"), None, "a skill that is off");
|
assert_eq!(named("/pptx-old 做簡報"), None, "a skill that is off");
|
||||||
assert_eq!(named("/Users/me/a.pdf"), None);
|
assert_eq!(named("/Users/me/a.pdf"), None);
|
||||||
assert!(named_skill_line(&skills[1]).contains("use_skill") && named_skill_line(&skills[1]).contains("「pptx」"));
|
assert!(named_skill_line(&skills[1], "/pptx").contains("use_skill") && named_skill_line(&skills[1], "/pptx").contains("「pptx」"));
|
||||||
|
assert!(!named_skill_line(&skills[1], "/pptx Q3 報告").contains("arguments"), "takes none: the words are the task");
|
||||||
|
let with = Skill { argument_hint: "<主題>".into(), ..skills[1].clone() };
|
||||||
|
assert!(named_skill_line(&with, "/pptx Q3 報告").contains("arguments 填「Q3 報告」"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
|
||||||
229
src/skills.rs
229
src/skills.rs
|
|
@ -241,6 +241,7 @@ pub fn parse_skill_markdown(text: &str) -> Option<Skill> {
|
||||||
let mut name = String::new();
|
let mut name = String::new();
|
||||||
let mut description = String::new();
|
let mut description = String::new();
|
||||||
let mut enabled = true;
|
let mut enabled = true;
|
||||||
|
let (mut argument_hint, mut arguments, mut allowed_tools, mut fork) = (String::new(), vec![], vec![], false);
|
||||||
let mut rest = t;
|
let mut rest = t;
|
||||||
|
|
||||||
if let Some(after_open) = t.strip_prefix("---\n") {
|
if let Some(after_open) = t.strip_prefix("---\n") {
|
||||||
|
|
@ -271,6 +272,12 @@ pub fn parse_skill_markdown(text: &str) -> Option<Skill> {
|
||||||
};
|
};
|
||||||
let key = raw_key.trim();
|
let key = raw_key.trim();
|
||||||
let val = raw_val.trim();
|
let val = raw_val.trim();
|
||||||
|
// A block list under the key (`allowed-tools:` then ` - Read` lines).
|
||||||
|
let list_items: Vec<String> = if val.is_empty() {
|
||||||
|
lines[i + 1..].iter().take_while(|l| l.starts_with(' ') || l.starts_with('\t') || l.trim().is_empty()).filter_map(|l| l.trim().strip_prefix('-')).map(|x| unquote_yaml(x.trim())).filter(|x| !x.is_empty()).collect()
|
||||||
|
} else {
|
||||||
|
vec![]
|
||||||
|
};
|
||||||
let is_folded = matches!(val, ">" | ">-" | ">+");
|
let is_folded = matches!(val, ">" | ">-" | ">+");
|
||||||
let is_literal = matches!(val, "|" | "|-" | "|+");
|
let is_literal = matches!(val, "|" | "|-" | "|+");
|
||||||
let parsed_val = if is_folded || is_literal {
|
let parsed_val = if is_folded || is_literal {
|
||||||
|
|
@ -337,6 +344,10 @@ pub fn parse_skill_markdown(text: &str) -> Option<Skill> {
|
||||||
"name" => name = parsed_val.trim().to_string(),
|
"name" => name = parsed_val.trim().to_string(),
|
||||||
"description" => description = parsed_val.trim().to_string(),
|
"description" => description = parsed_val.trim().to_string(),
|
||||||
"enabled" => enabled = !matches!(parsed_val.trim().to_ascii_lowercase().as_str(), "false" | "0" | "no" | "off"),
|
"enabled" => enabled = !matches!(parsed_val.trim().to_ascii_lowercase().as_str(), "false" | "0" | "no" | "off"),
|
||||||
|
"argument-hint" | "argument_hint" => argument_hint = parsed_val.trim().to_string(),
|
||||||
|
"arguments" => arguments = yaml_list(&parsed_val, &list_items),
|
||||||
|
"allowed-tools" | "allowed_tools" => allowed_tools = yaml_list(&parsed_val, &list_items),
|
||||||
|
"context" => fork = parsed_val.trim().eq_ignore_ascii_case("fork"),
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -362,10 +373,177 @@ pub fn parse_skill_markdown(text: &str) -> Option<Skill> {
|
||||||
instructions,
|
instructions,
|
||||||
steps,
|
steps,
|
||||||
enabled,
|
enabled,
|
||||||
|
argument_hint,
|
||||||
|
arguments,
|
||||||
|
allowed_tools,
|
||||||
|
fork,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A YAML list as it may be written: a block list (`items`), a flow list `[a, b]`, or one line
|
||||||
|
/// `Read, Grep, Bash(git add:*)` (commas, or else spaces, outside parentheses).
|
||||||
|
fn yaml_list(val: &str, items: &[String]) -> Vec<String> {
|
||||||
|
if !items.is_empty() {
|
||||||
|
return items.to_vec();
|
||||||
|
}
|
||||||
|
let v = val.trim();
|
||||||
|
let v = v.strip_prefix('[').and_then(|x| x.strip_suffix(']')).unwrap_or(v);
|
||||||
|
let split_on = if v.contains(',') { ',' } else { ' ' };
|
||||||
|
let (mut out, mut cur, mut depth) = (vec![], String::new(), 0i32);
|
||||||
|
for c in v.chars() {
|
||||||
|
match c {
|
||||||
|
'(' => depth += 1,
|
||||||
|
')' => depth -= 1,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
if c == split_on && depth <= 0 {
|
||||||
|
out.push(std::mem::take(&mut cur));
|
||||||
|
} else {
|
||||||
|
cur.push(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push(cur);
|
||||||
|
out.into_iter().map(|x| unquote_yaml(x.trim())).filter(|x| !x.is_empty()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a skill takes arguments: it names them, hints at them, or its instructions use them.
|
||||||
|
pub fn takes_arguments(k: &Skill) -> bool {
|
||||||
|
!k.arguments.is_empty() || !k.argument_hint.is_empty() || k.instructions.contains("$ARGUMENTS") || k.instructions.match_indices('$').any(|(i, _)| k.instructions[i + 1..].starts_with(|c: char| c.is_ascii_digit()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What was typed after 「/名稱」 at the start of a message ("" when nothing).
|
||||||
|
pub fn arguments_after(text: &str, name: &str) -> String {
|
||||||
|
text.trim_start().strip_prefix('/').and_then(|r| r.strip_prefix(name)).map(|r| r.trim().to_string()).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Arguments the way a shell splits them: spaces apart, "quoted words" together.
|
||||||
|
fn split_arguments(args: &str) -> Vec<String> {
|
||||||
|
let (mut out, mut cur, mut quote, mut any) = (vec![], String::new(), None::<char>, false);
|
||||||
|
for c in args.chars() {
|
||||||
|
match (quote, c) {
|
||||||
|
(Some(q), c) if c == q => quote = None,
|
||||||
|
(Some(_), c) => cur.push(c),
|
||||||
|
(None, '"' | '\'' | '「') => {
|
||||||
|
quote = Some(if c == '「' { '」' } else { c });
|
||||||
|
any = true;
|
||||||
|
}
|
||||||
|
(None, c) if c.is_whitespace() => {
|
||||||
|
if any || !cur.is_empty() {
|
||||||
|
out.push(std::mem::take(&mut cur));
|
||||||
|
}
|
||||||
|
any = false;
|
||||||
|
}
|
||||||
|
(None, c) => cur.push(c),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if any || !cur.is_empty() {
|
||||||
|
out.push(cur);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The skill's instructions with this time's arguments in them (Claude Code's way): $ARGUMENTS all
|
||||||
|
/// of them, $ARGUMENTS[N] and $N the N-th (from 0), $name a named one; when it says none of those,
|
||||||
|
/// they go at the end as 「ARGUMENTS: …」.
|
||||||
|
pub fn with_arguments(k: &Skill, args: &str) -> String {
|
||||||
|
let args = args.trim();
|
||||||
|
if args.is_empty() {
|
||||||
|
return k.instructions.clone();
|
||||||
|
}
|
||||||
|
let parts = split_arguments(args);
|
||||||
|
let nth = |i: usize| parts.get(i).cloned().unwrap_or_default();
|
||||||
|
let mut out = String::new();
|
||||||
|
let mut used = false;
|
||||||
|
let text = &k.instructions;
|
||||||
|
let mut rest = text.as_str();
|
||||||
|
while let Some(at) = rest.find('$') {
|
||||||
|
out.push_str(&rest[..at]);
|
||||||
|
let after = &rest[at + 1..];
|
||||||
|
let digits: String = after.chars().take_while(char::is_ascii_digit).collect();
|
||||||
|
if let Some(r) = after.strip_prefix("ARGUMENTS[") {
|
||||||
|
let n: String = r.chars().take_while(char::is_ascii_digit).collect();
|
||||||
|
if let (Ok(i), Some(r2)) = (n.parse::<usize>(), r[n.len()..].strip_prefix(']')) {
|
||||||
|
out.push_str(&nth(i));
|
||||||
|
used = true;
|
||||||
|
rest = r2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(r) = after.strip_prefix("ARGUMENTS") {
|
||||||
|
out.push_str(args);
|
||||||
|
used = true;
|
||||||
|
rest = r;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !digits.is_empty() {
|
||||||
|
out.push_str(&nth(digits.parse().unwrap_or(usize::MAX)));
|
||||||
|
used = true;
|
||||||
|
rest = &after[digits.len()..];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let word: String = after.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
|
||||||
|
if let Some(i) = k.arguments.iter().position(|a| !word.is_empty() && *a == word) {
|
||||||
|
out.push_str(&nth(i));
|
||||||
|
used = true;
|
||||||
|
rest = &after[word.len()..];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.push('$');
|
||||||
|
rest = after;
|
||||||
|
}
|
||||||
|
out.push_str(rest);
|
||||||
|
if !used {
|
||||||
|
out.push_str(&format!("\n\nARGUMENTS: {args}"));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Claude Code's tool names, as AnyBot's (a skill written for it limits the same tools here).
|
||||||
|
fn anybot_tool(name: &str) -> &str {
|
||||||
|
match name {
|
||||||
|
"Read" => "read_file",
|
||||||
|
"Write" | "Edit" | "MultiEdit" | "NotebookEdit" => "edit_file",
|
||||||
|
"Bash" => "shell",
|
||||||
|
"Grep" | "Glob" => "search",
|
||||||
|
"LS" => "list_dir",
|
||||||
|
"WebFetch" => "web_fetch",
|
||||||
|
"WebSearch" => "web_search",
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A skill's allowed-tools as rules gate::patterns reads: a name → `tool(name)`, `Bash(git add:*)`
|
||||||
|
/// → `shell(git add *)`, AnyBot's own `shell(git *)` / `file(…)` / `connector(…)` as they are.
|
||||||
|
pub fn tool_rules(k: &Skill) -> Vec<String> {
|
||||||
|
k.allowed_tools
|
||||||
|
.iter()
|
||||||
|
.map(|t| {
|
||||||
|
let t = t.trim();
|
||||||
|
match t.split_once('(') {
|
||||||
|
Some((kind, inner)) => {
|
||||||
|
let inner = inner.strip_suffix(')').unwrap_or(inner).replace(":*", " *");
|
||||||
|
match kind.trim() {
|
||||||
|
"Bash" | "shell" => format!("shell({inner})"),
|
||||||
|
"Read" | "Write" | "Edit" | "file" => format!("file({inner})"),
|
||||||
|
"WebFetch" | "web" => format!("web({inner})"),
|
||||||
|
other => format!("{other}({inner})"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => format!("tool({})", anybot_tool(t)),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tools a skill's limit never takes away: reading skills and kept results, asking the person.
|
||||||
|
const ALWAYS_ALLOWED: [&str; 5] = ["use_skill", "read_result", "ask_person", "submit_plan", "update_plan"];
|
||||||
|
|
||||||
|
/// Whether a tool call is within a loaded skill's allowed-tools (`rules` from tool_rules).
|
||||||
|
pub fn skill_allows(rules: &[String], name: &str, args: &str) -> bool {
|
||||||
|
ALWAYS_ALLOWED.contains(&name) || matches!(crate::gate::patterns(name, args, rules, &[]), crate::gate::PatternVerdict::Allow(_))
|
||||||
|
}
|
||||||
|
|
||||||
fn quote_yaml_if_needed(s: &str) -> String {
|
fn quote_yaml_if_needed(s: &str) -> String {
|
||||||
let clean = s.replace('\r', "");
|
let clean = s.replace('\r', "");
|
||||||
if clean.contains('\n') {
|
if clean.contains('\n') {
|
||||||
|
|
@ -383,6 +561,17 @@ pub fn render_skill_markdown(s: &Skill) -> String {
|
||||||
if !s.enabled {
|
if !s.enabled {
|
||||||
o.push_str("enabled: false\n");
|
o.push_str("enabled: false\n");
|
||||||
}
|
}
|
||||||
|
if !s.argument_hint.is_empty() {
|
||||||
|
o.push_str(&format!("argument-hint: {}\n", quote_yaml_if_needed(&s.argument_hint)));
|
||||||
|
}
|
||||||
|
for (key, list) in [("arguments", &s.arguments), ("allowed-tools", &s.allowed_tools)] {
|
||||||
|
if !list.is_empty() {
|
||||||
|
o.push_str(&format!("{key}:\n{}", list.iter().map(|x| format!(" - {}\n", quote_yaml_if_needed(x))).collect::<String>()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s.fork {
|
||||||
|
o.push_str("context: fork\n");
|
||||||
|
}
|
||||||
o.push_str(&format!("---\n\n{}\n", s.instructions.trim()));
|
o.push_str(&format!("---\n\n{}\n", s.instructions.trim()));
|
||||||
if !s.steps.is_empty() {
|
if !s.steps.is_empty() {
|
||||||
if let Ok(j) = serde_json::to_string(&s.steps) {
|
if let Ok(j) = serde_json::to_string(&s.steps) {
|
||||||
|
|
@ -612,12 +801,15 @@ pub fn read_resource(k: &Skill, rel: &str) -> Result<String, String> {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Format what `use_skill` returns to the model: full `SKILL.md` instructions + progressive-disclosure resource index.
|
/// Format what `use_skill` returns to the model: full `SKILL.md` instructions + progressive-disclosure resource index.
|
||||||
pub fn format_skill_for_model(k: &Skill, file: Option<&str>) -> Result<String, String> {
|
pub fn format_skill_for_model(k: &Skill, file: Option<&str>, arguments: Option<&str>) -> Result<String, String> {
|
||||||
if let Some(f) = file.map(str::trim).filter(|f| !f.is_empty()) {
|
if let Some(f) = file.map(str::trim).filter(|f| !f.is_empty()) {
|
||||||
let content = read_resource(k, f)?;
|
let content = read_resource(k, f)?;
|
||||||
return Ok(format!("技能「{}」隨附檔案 `{f}`:\n\n{content}", k.name));
|
return Ok(format!("技能「{}」隨附檔案 `{f}`:\n\n{content}", k.name));
|
||||||
}
|
}
|
||||||
let mut out = format!("技能「{}」的做法:\n{}", k.name, k.instructions);
|
let mut out = format!("技能「{}」的做法:\n{}", k.name, with_arguments(k, arguments.unwrap_or("")));
|
||||||
|
if !k.allowed_tools.is_empty() {
|
||||||
|
out.push_str(&format!("\n\n(這個技能只准用這些工具:{}。這一輪接下來 AnyBot 只讓你用這些(還有 use_skill、read_result、ask_person);要用別的,先告訴使用者。)", k.allowed_tools.join("、")));
|
||||||
|
}
|
||||||
let resources = if !k.resources.is_empty() {
|
let resources = if !k.resources.is_empty() {
|
||||||
k.resources.clone()
|
k.resources.clone()
|
||||||
} else if let Some(dir) = resolve_skill_dir(k) {
|
} else if let Some(dir) = resolve_skill_dir(k) {
|
||||||
|
|
@ -1005,6 +1197,39 @@ mod package_tests {
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
/// 技能帶參數 (M4): the three new fields read from SKILL.md, written back the same.
|
||||||
|
#[test]
|
||||||
|
fn a_skill_takes_arguments_tools_and_fork() {
|
||||||
|
let md = "---\nname: release-notes\ndescription: 寫版本說明\nargument-hint: <版本> [格式]\narguments: [version, format]\nallowed-tools:\n - Read\n - Bash(git log:*)\n - shell(git tag *)\ncontext: fork\n---\n替 $version 寫說明(格式 $format),全部參數:$ARGUMENTS;第一個 $0、第二個 $ARGUMENTS[1]。價格 $5 不是參數。\n";
|
||||||
|
let k = parse_skill_markdown(md).unwrap();
|
||||||
|
assert_eq!(k.argument_hint, "<版本> [格式]");
|
||||||
|
assert_eq!(k.arguments, ["version", "format"]);
|
||||||
|
assert_eq!(k.allowed_tools, ["Read", "Bash(git log:*)", "shell(git tag *)"]);
|
||||||
|
assert!(k.fork);
|
||||||
|
assert_eq!(parse_skill_markdown(&render_skill_markdown(&k)).unwrap(), Skill { instructions: k.instructions.clone(), ..k.clone() });
|
||||||
|
let one_line = parse_skill_markdown("---\nname: x\nallowed-tools: Read, Grep, Bash(git add:*)\n---\nhi").unwrap();
|
||||||
|
assert_eq!(one_line.allowed_tools, ["Read", "Grep", "Bash(git add:*)"]);
|
||||||
|
// The arguments into the instructions.
|
||||||
|
let t = with_arguments(&k, "v2.3 \"條列 簡短\"");
|
||||||
|
assert!(t.contains("替 v2.3 寫說明(格式 條列 簡短)"), "{t}");
|
||||||
|
assert!(t.contains("全部參數:v2.3 \"條列 簡短\"") && t.contains("第一個 v2.3、第二個 條列 簡短"), "{t}");
|
||||||
|
assert!(t.contains("價格 不是參數") || t.contains("價格 $5"), "a $5 past the arguments is empty, as Claude Code does: {t}");
|
||||||
|
let plain = Skill { name: "p".into(), instructions: "照做".into(), ..Default::default() };
|
||||||
|
assert_eq!(with_arguments(&plain, "a b"), "照做\n\nARGUMENTS: a b");
|
||||||
|
assert_eq!(with_arguments(&plain, ""), "照做");
|
||||||
|
assert_eq!(arguments_after("/release-notes v2.3 條列", "release-notes"), "v2.3 條列");
|
||||||
|
// allowed-tools as rules: Claude Code's names are AnyBot's tools.
|
||||||
|
let rules = tool_rules(&k);
|
||||||
|
assert_eq!(rules, ["tool(read_file)", "shell(git log *)", "shell(git tag *)"]);
|
||||||
|
let sh = |c: &str| serde_json::json!({"command": c}).to_string();
|
||||||
|
assert!(skill_allows(&rules, "read_file", r#"{"path":"a"}"#));
|
||||||
|
assert!(skill_allows(&rules, "shell", &sh("git log --oneline")) && skill_allows(&rules, "shell", &sh("git tag v2")));
|
||||||
|
assert!(!skill_allows(&rules, "shell", &sh("rm -rf build")) && !skill_allows(&rules, "edit_file", r#"{"path":"a"}"#));
|
||||||
|
assert!(skill_allows(&rules, "use_skill", "{}") && skill_allows(&rules, "ask_person", "{}"));
|
||||||
|
let text = format_skill_for_model(&k, None, Some("v2.3")).unwrap();
|
||||||
|
assert!(text.contains("替 v2.3") && text.contains("只准用這些工具"), "{text}");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn parses_standard_agent_skills_frontmatter_and_blocks() {
|
fn parses_standard_agent_skills_frontmatter_and_blocks() {
|
||||||
let md = "\u{feff}---\r\nname: \"webapp-testing\"\r\ndescription: >-\r\n Toolkit for interacting with and testing local web applications\r\n using Playwright.\r\nlicense: Apache-2.0\r\nmetadata:\r\n author: anthropic\r\n---\r\n\r\n# Web Application Testing\r\n\r\nRun `scripts/with_server.py`.\r\n";
|
let md = "\u{feff}---\r\nname: \"webapp-testing\"\r\ndescription: >-\r\n Toolkit for interacting with and testing local web applications\r\n using Playwright.\r\nlicense: Apache-2.0\r\nmetadata:\r\n author: anthropic\r\n---\r\n\r\n# Web Application Testing\r\n\r\nRun `scripts/with_server.py`.\r\n";
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue