diff --git a/AGENTS.md b/AGENTS.md index 4e353e2..ac603b1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -93,7 +93,7 @@ Providers/models live in `llm/catalog.rs`; unknown models get generic OpenAI-com `/model` rebuilds the client mid-session (refused while busy) and persists via `toml_edit`. Sessions resume via `--continue` / `--resume` / `/sessions`; resume repairs dangling tool calls: each call commits a `tool_intent` record before it runs, so a crashed call is re-run on the next turn if its tool is `replay_safe` (read/grep/find/ls), otherwise marked "may have partially run" (intent committed) or "did not run" (no intent). `/export [path]` merges meta + trace + messages (Markdown if `.md`). `/fork [n]` copies the active history (first n user turns) into a new session, `/handoff ` starts a clean linked session from a note; both record `parent_session` and leave the parent untouched. -Skills: `~/.limbo/skills//SKILL.md` (user) and `/.agents/skills//SKILL.md` (project, wins collisions); daily sessions also see the bundled pack (lowest, unpacked to `~/.limbo/daily/bundled//`) and `~/.limbo/daily/skills/` (highest), coding sessions never do — injected as an `` catalog in the system prompt and invocable via `/ [args]`. +Skills: `~/.agents/skills//SKILL.md` (global, shared with other agents; lowest of the non-bundled), `~/.limbo/skills//SKILL.md` (user) and `/.agents/skills//SKILL.md` (project, wins collisions); daily sessions also see the bundled pack (lowest, unpacked to `~/.limbo/daily/bundled//`) and `~/.limbo/daily/skills/` (highest), coding sessions never do — injected as an `` catalog in the system prompt and invocable via `/ [args]`. ## UI diff --git a/README.md b/README.md index 1c8229a..30b561d 100644 --- a/README.md +++ b/README.md @@ -239,8 +239,8 @@ enabled = true - **Project instructions.** Limbo reads `AGENTS.md` from the working directory and `~/.limbo/AGENTS.md` into its system prompt. -- **Skills.** Drop a `SKILL.md` into `/.agents/skills//` or - `~/.limbo/skills//`. The model loads it when the task matches, or you +- **Skills.** Drop a `SKILL.md` into `/.agents/skills//`, + `~/.limbo/skills//` or the cross-agent `~/.agents/skills//`. The model loads it when the task matches, or you call it as `/`. See [docs/skills.md](docs/skills.md). ## Safety diff --git a/docs/daily-mode.md b/docs/daily-mode.md index c480863..0470c07 100644 --- a/docs/daily-mode.md +++ b/docs/daily-mode.md @@ -43,7 +43,7 @@ daily 会话按这个顺序收集 skill,同名时后者覆盖前者: 1. **内置起步包**(`assets/daily_skills/`,从 Hermes 移植,MIT;编进二进制,第一次用时解压到 `~/.limbo/daily/bundled/<版本>/`):pdf、docx、xlsx、powerpoint、 grounded-citations、blocked-page-recovery、meeting-action-items、document-to-action-items、 weekly-review-planning、youtube-content、arxiv。文档类 skill 需要的 Python 包按 skill 里的说明装。 -2. 用户 skill `~/.limbo/skills`、项目 skill `/.agents/skills` +2. 全局 skill `~/.agents/skills`、用户 skill `~/.limbo/skills`、项目 skill `/.agents/skills` 3. **daily skill** `~/.limbo/daily/skills//SKILL.md` coding 会话只看 2,看不到起步包和 daily skill。 diff --git a/docs/skills.md b/docs/skills.md index f7981a3..b7b73dd 100644 --- a/docs/skills.md +++ b/docs/skills.md @@ -30,7 +30,10 @@ description: Test-driven development workflow. # 指令正文,调用时作为 prompt 注入对话 ``` -- frontmatter 为简单的 `key: value` 行(支持 `name`、`description`) +- frontmatter 读顶层的 `name`、`description`、`disable-model-invocation`;值可以是普通、 + 带引号(`"..."` / `'...'`)、缩进续行或 YAML 块标量(`>` / `|`)。嵌套在 `metadata:` 等 + 下面的同名键不算 +- description 超过 1024 字符时截断后照常列出(不再跳过) - 无 frontmatter 时:name 取目录名,整个文件作为正文 ## 发现路径(同名时后者覆盖前者) @@ -38,6 +41,7 @@ description: Test-driven development workflow. | 来源 | 路径 | |------|------| | 内置 daily 起步包(仅 daily 会话) | `assets/daily_skills/`(编进二进制,从 Hermes 移植) | +| 全局(与其他 agent 共用,`npx skills add -g` 装在这里) | `~/.agents/skills//SKILL.md` | | 用户级 | `~/.limbo/skills//SKILL.md` | | 项目级 | `/.agents/skills//SKILL.md` | | Daily(仅 daily 会话) | `~/.limbo/daily/skills//SKILL.md` | @@ -47,7 +51,8 @@ description: Test-driven development workflow. ## 交互 - 输入 `/` 弹出命令菜单,skills 与内置命令一同列出(skill 带 `[skill]` 标记) -- 继续输入实时过滤;菜单在每次弹出时重新扫描,运行中新增的 skill 立即可用 +- 继续输入实时过滤;菜单在每次弹出时重新扫描,运行中新增的 skill 立即可用; + 每轮开始前若 skill 有增删改,也会重建 system prompt 里的 `` 目录 - 选中 skill: - **部分匹配 + Enter / Tab** → 补全为 `/ `,可继续输入参数 - **完整输入 `/` + Enter** → 直接无参调用 diff --git a/src/agent.rs b/src/agent.rs index f9e2909..7325653 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -239,6 +239,8 @@ pub struct Agent { persisted: HashSet, file_created: bool, needs_rewrite: bool, + /// The skills catalog the current system prompt was built with. + skills_catalog: String, pub steer: Arc, rerun: Vec, /// Last real prompt size, and the history length it was measured at. @@ -417,6 +419,7 @@ impl Agent { persisted: HashSet::new(), file_created: false, needs_rewrite: false, + skills_catalog: String::new(), steer, rerun: Vec::new(), last_prompt_tokens: None, @@ -559,8 +562,29 @@ impl Agent { .then(|| MemoryStore::new(memory_dir(), d.user_chars, d.notes_chars)) } + fn current_skills_catalog(&self) -> String { + crate::skills::format_skills(&crate::skills::discover_skills( + &self.workdir, + self.daily_mode(), + )) + } + + /// Rebuild the system prompt when skills were added, removed or changed + /// since it was built, so a skill installed mid-session is visible to the + /// model on the next turn. A no-op (prompt cache intact) otherwise. + pub fn sync_skills(&mut self) { + if self.system_override.is_some() { + return; + } + if self.current_skills_catalog() != self.skills_catalog { + self.init_system_message(); + self.needs_rewrite = true; + } + } + /// (Re)build the system prompt as message 0. pub fn init_system_message(&mut self) { + self.skills_catalog = self.current_skills_catalog(); let extras = PromptExtras { memory: self.memory.as_ref(), blocks: self.prompt_blocks.clone(), diff --git a/src/pump.rs b/src/pump.rs index 58e599d..8a69bac 100644 --- a/src/pump.rs +++ b/src/pump.rs @@ -42,6 +42,7 @@ pub async fn run_task( sup.set_main_busy(true); sup.flush_notices(); } + agent.sync_skills(); agent.learn.lock().unwrap().observe_user_text(&input); // Tap the event stream for the learn trigger. let (itx, mut irx) = tokio::sync::mpsc::unbounded_channel::(); diff --git a/src/skills.rs b/src/skills.rs index 6fedc4f..75c5327 100644 --- a/src/skills.rs +++ b/src/skills.rs @@ -3,6 +3,8 @@ //! //! Discovery (later sources win on name collisions): //! - bundled daily pack (daily sessions only, lowest priority) +//! - global: `~/.agents/skills//SKILL.md` (shared with other agents; +//! where `npx skills add -g` installs) //! - user: `~/.limbo/skills//SKILL.md` //! - project: `/.agents/skills//SKILL.md` //! - daily: `~/.limbo/daily/skills//SKILL.md` (daily sessions only) @@ -33,6 +35,10 @@ pub struct Skill { pub disable_model_invocation: bool, } +/// The cross-agent global skills dir (`~/.agents/skills`). +pub fn global_skills_dir() -> Option { + dirs::home_dir().map(|h| h.join(".agents").join("skills")) +} pub fn user_skills_dir() -> PathBuf { limbo_home().join("skills") } @@ -79,24 +85,30 @@ fn mark_scripts_executable(dir: &Path) { } /// Parse `---` frontmatter (`name`, `description`, `disable-model-invocation`). +/// +/// Only top-level keys count (a `name:` nested under `metadata:` is not the +/// skill's name). Values may be plain, quoted (`"..."` / `'...'`), continued +/// on indented lines, or YAML block scalars (`>`, `|`, with chomping +/// indicators): the forms skill installers commonly write. pub fn parse_skill_md(text: &str, fallback: &str) -> (String, String, String, bool) { + let text = text.strip_prefix('\u{feff}').unwrap_or(text); if let Some(rest) = text.strip_prefix("---") && let Some(end) = rest.find("\n---") { let header = &rest[..end]; - let body = rest[end + 4..].trim_start_matches('\n').to_string(); + let body = &rest[end + 4..]; + // Drop the rest of the closing `---` line. + let body = body.split_once('\n').map_or("", |(_, b)| b); + let body = body.trim_start_matches(['\n', '\r']).to_string(); let (mut name, mut desc, mut disable) = (fallback.to_string(), String::new(), false); - for line in header.lines() { - if let Some((k, v)) = line.split_once(':') { - let v = v.trim().to_string(); - match k.trim() { - "name" if !v.is_empty() => name = v, - "description" => desc = v, - "disable-model-invocation" => { - disable = matches!(v.to_lowercase().as_str(), "true" | "yes" | "1") - } - _ => {} + for (k, v) in frontmatter_fields(header) { + match k.as_str() { + "name" if !v.is_empty() => name = v, + "description" => desc = v, + "disable-model-invocation" => { + disable = matches!(v.to_lowercase().as_str(), "true" | "yes" | "1") } + _ => {} } } return (name, desc, body, disable); @@ -104,6 +116,125 @@ pub fn parse_skill_md(text: &str, fallback: &str) -> (String, String, String, bo (fallback.to_string(), String::new(), text.to_string(), false) } +/// Top-level `key: value` pairs of a frontmatter block, values unquoted and +/// block scalars folded. +fn frontmatter_fields(header: &str) -> Vec<(String, String)> { + let lines: Vec<&str> = header.lines().collect(); + let indented = |l: &str| l.starts_with([' ', '\t']); + let mut out = Vec::new(); + let mut i = 0; + while i < lines.len() { + let line = lines[i]; + i += 1; + if indented(line) || line.trim_start().starts_with('#') { + continue; + } + let Some((k, v)) = line.split_once(':') else { + continue; + }; + let key = k.trim().to_string(); + let v = v.trim(); + // The indented lines (and blank lines between them) that follow. + let mut cont = Vec::new(); + while i < lines.len() && (indented(lines[i]) || lines[i].trim().is_empty()) { + cont.push(lines[i]); + i += 1; + } + while cont.last().is_some_and(|l| l.trim().is_empty()) { + cont.pop(); + } + let value = if let Some(ind) = v.strip_prefix(['>', '|']) { + let literal = v.starts_with('|'); + let keep_newline = ind.contains('+'); + block_scalar(&cont, literal, keep_newline) + } else if v.starts_with('"') || v.starts_with('\'') { + let mut joined = v.to_string(); + for l in &cont { + joined.push(' '); + joined.push_str(l.trim()); + } + unquote(&joined) + } else { + let mut joined = v.to_string(); + for l in &cont { + let l = l.trim(); + if !l.is_empty() { + if !joined.is_empty() { + joined.push(' '); + } + joined.push_str(l); + } + } + joined + }; + out.push((key, value)); + } + out +} + +fn block_scalar(lines: &[&str], literal: bool, keep_newline: bool) -> String { + let indent = lines + .iter() + .filter(|l| !l.trim().is_empty()) + .map(|l| l.len() - l.trim_start().len()) + .min() + .unwrap_or(0); + let body: Vec<&str> = lines + .iter() + .map(|l| l.get(indent..).unwrap_or("").trim_end()) + .collect(); + let mut s = if literal { + body.join("\n") + } else { + // Folded: single newlines become spaces, blank lines stay newlines. + let mut s = String::new(); + let mut prev_blank = true; + for l in body { + if l.is_empty() { + s.push('\n'); + prev_blank = true; + } else { + if !prev_blank { + s.push(' '); + } + s.push_str(l); + prev_blank = false; + } + } + s + }; + if keep_newline { + s.push('\n'); + } + s.trim().to_string() +} + +fn unquote(v: &str) -> String { + let v = v.trim(); + if v.len() >= 2 && v.starts_with('\'') && v.ends_with('\'') { + return v[1..v.len() - 1].replace("''", "'"); + } + if v.len() >= 2 && v.starts_with('"') && v.ends_with('"') { + let inner = &v[1..v.len() - 1]; + let mut out = String::new(); + let mut chars = inner.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('n') => out.push('\n'), + Some('t') => out.push('\t'), + Some(o) => out.push(o), + None => out.push('\\'), + } + } + return out; + } + v.to_string() +} + /// Validate per the Agent Skills spec; returns error messages. pub fn validate_skill(name: &str, description: &str) -> Vec { let mut errors = Vec::new(); @@ -142,7 +273,16 @@ fn load_from(dir: &Path) -> Vec { continue; }; let fallback = e.file_name().to_string_lossy().into_owned(); - let (name, description, body, disable) = parse_skill_md(&text, &fallback); + let (name, mut description, body, disable) = parse_skill_md(&text, &fallback); + // Many published skills run past the spec's description limit; list + // them with the description cut rather than hiding them. + if description.chars().count() > MAX_DESCRIPTION_LENGTH { + description = description + .chars() + .take(MAX_DESCRIPTION_LENGTH - 1) + .collect(); + description.push('…'); + } if !validate_skill(&name, &description).is_empty() { continue; } @@ -159,7 +299,9 @@ fn load_from(dir: &Path) -> Vec { /// All skills visible to a session, sorted by name. pub fn discover_skills(workdir: &Path, daily: bool) -> Vec { - let mut sources = vec![user_skills_dir(), workdir.join(".agents/skills")]; + let mut sources: Vec = global_skills_dir().into_iter().collect(); + sources.push(user_skills_dir()); + sources.push(workdir.join(".agents/skills")); if daily { sources.insert(0, bundled_daily_dir()); sources.push(daily_skills_dir()); @@ -232,6 +374,56 @@ mod tests { ); } + #[test] + fn frontmatter_yaml_forms() { + let folded = "---\nname: ste\ndescription: >\n Report results\n in short sentences.\nlicense: MIT\n---\nBody"; + let (n, d, b, _) = parse_skill_md(folded, "x"); + assert_eq!( + (n.as_str(), d.as_str(), b.as_str()), + ("ste", "Report results in short sentences.", "Body") + ); + + let literal = "---\nname: a\ndescription: |-\n line one\n line two\n---\n"; + assert_eq!(parse_skill_md(literal, "x").1, "line one\nline two"); + + let quoted = "---\nname: lark-im\nversion: 1.0.0\ndescription: \"飞书: 收发消息 \\\"群聊\\\"\"\nmetadata:\n name: nested\n requires:\n bins: [\"lark-cli\"]\n---\nBody"; + let (n, d, _, _) = parse_skill_md(quoted, "x"); + assert_eq!( + (n.as_str(), d.as_str()), + ("lark-im", "飞书: 收发消息 \"群聊\"") + ); + + let single = "---\nname: s\ndescription: 'it''s fine'\n---\n"; + assert_eq!(parse_skill_md(single, "x").1, "it's fine"); + + let plain_multi = "---\nname: p\ndescription: first part\n second part\n---\n"; + assert_eq!(parse_skill_md(plain_multi, "x").1, "first part second part"); + + let crlf = "---\r\nname: c\r\ndescription: >\r\n windows\r\n file\r\n---\r\nBody"; + let (n, d, b, _) = parse_skill_md(crlf, "x"); + assert_eq!( + (n.as_str(), d.as_str(), b.as_str()), + ("c", "windows file", "Body") + ); + } + + #[test] + fn long_description_is_cut_not_skipped() { + let dir = std::env::temp_dir().join(format!("limbo-skills-{}", std::process::id())); + let skill = dir.join("long"); + std::fs::create_dir_all(&skill).unwrap(); + let desc = "x".repeat(MAX_DESCRIPTION_LENGTH + 60); + std::fs::write( + skill.join("SKILL.md"), + format!("---\nname: long\ndescription: \"{desc}\"\n---\nBody"), + ) + .unwrap(); + let found = load_from(&dir); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(found.len(), 1); + assert_eq!(found[0].description.chars().count(), MAX_DESCRIPTION_LENGTH); + } + #[test] fn validation() { assert!(validate_skill("weekly-report", "x").is_empty()); diff --git a/src/tui/app.rs b/src/tui/app.rs index c44ce91..e9e38e6 100644 --- a/src/tui/app.rs +++ b/src/tui/app.rs @@ -281,6 +281,9 @@ pub struct App { pub mouse_changed: bool, pub toast: Option<(String, Instant)>, pub skills: Vec, + /// Workdir and daily flag the skills were discovered for (the agent is + /// away while a turn runs). + skills_scope: (std::path::PathBuf, bool), pub dirty: bool, /// Collapsed pastes and attachment markers of the prompt box. pub paste: PasteStore, @@ -320,6 +323,7 @@ impl App { .or_else(|| std::env::var("LIMBO_MOTION").ok()); let entries = entries_from_history(&agent.messages); let skills = discover_skills(&agent.workdir, agent.daily_mode()); + let skills_scope = (agent.workdir.clone(), agent.daily_mode()); let sup = agent.supervisor.clone(); let viewer = crate::trace_viewer::Viewer::new( agent.session_dir.clone(), @@ -373,6 +377,7 @@ impl App { mouse_changed: false, toast: None, skills, + skills_scope, dirty: true, }; app.refresh_info(); @@ -962,6 +967,14 @@ impl App { // -- input ---------------------------------------------------------------- + /// Re-scan the skill directories (skills can be added while running). + pub fn refresh_skills(&mut self) { + if let Some(a) = &self.agent { + self.skills_scope = (a.workdir.clone(), a.daily_mode()); + } + self.skills = discover_skills(&self.skills_scope.0, self.skills_scope.1); + } + /// Slash-command suggestions for the current input. pub fn command_matches(&self) -> Vec<(String, String, String)> { let text = &self.input.text; @@ -1230,6 +1243,11 @@ impl App { KeyCode::Char(c) if !ctrl => { self.input.insert(c); self.cmd_selected = 0; + if self.input.text == "/" { + // The command menu just opened: pick up skills installed + // while Limbo is running. + self.refresh_skills(); + } } _ => {} } @@ -1475,6 +1493,9 @@ impl App { self.paste.clear(); return; } + if !self.skills.iter().any(|s| s.name == cmd) { + self.refresh_skills(); + } if let Some(skill) = self.skills.iter().find(|s| s.name == cmd).cloned() { let mut prompt = format!( "# Skill: {}\n\n{}\n\n(Skill 文件位于 {},其中引用的相对路径基于其所在目录解析。)", @@ -1767,6 +1788,7 @@ impl App { match parse_toggle(arg, a.daily_mode()) { None => self.toast(cmds::DAILY_USAGE), Some(on) if a.set_daily_mode(on) => { + self.skills_scope = (a.workdir.clone(), on); self.skills = discover_skills(&a.workdir, on); self.notice( NoticeKind::Info,