Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <note>` starts a clean linked session from a note; both record `parent_session` and leave the parent untouched.

Skills: `~/.limbo/skills/<name>/SKILL.md` (user) and `<workdir>/.agents/skills/<name>/SKILL.md` (project, wins collisions); daily sessions also see the bundled pack (lowest, unpacked to `~/.limbo/daily/bundled/<version>/`) and `~/.limbo/daily/skills/` (highest), coding sessions never do — injected as an `<available_skills>` catalog in the system prompt and invocable via `/<name> [args]`.
Skills: `~/.agents/skills/<name>/SKILL.md` (global, shared with other agents; lowest of the non-bundled), `~/.limbo/skills/<name>/SKILL.md` (user) and `<workdir>/.agents/skills/<name>/SKILL.md` (project, wins collisions); daily sessions also see the bundled pack (lowest, unpacked to `~/.limbo/daily/bundled/<version>/`) and `~/.limbo/daily/skills/` (highest), coding sessions never do — injected as an `<available_skills>` catalog in the system prompt and invocable via `/<name> [args]`.

## UI

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<project>/.agents/skills/<name>/` or
`~/.limbo/skills/<name>/`. The model loads it when the task matches, or you
- **Skills.** Drop a `SKILL.md` into `<project>/.agents/skills/<name>/`,
`~/.limbo/skills/<name>/` or the cross-agent `~/.agents/skills/<name>/`. The model loads it when the task matches, or you
call it as `/<name>`. See [docs/skills.md](docs/skills.md).

## Safety
Expand Down
2 changes: 1 addition & 1 deletion docs/daily-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<workdir>/.agents/skills`
2. 全局 skill `~/.agents/skills`、用户 skill `~/.limbo/skills`、项目 skill `<workdir>/.agents/skills`
3. **daily skill** `~/.limbo/daily/skills/<name>/SKILL.md`

coding 会话只看 2,看不到起步包和 daily skill。
Expand Down
9 changes: 7 additions & 2 deletions docs/skills.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,18 @@ description: Test-driven development workflow.
# 指令正文,调用时作为 prompt 注入对话
```

- frontmatter 为简单的 `key: value` 行(支持 `name`、`description`)
- frontmatter 读顶层的 `name`、`description`、`disable-model-invocation`;值可以是普通、
带引号(`"..."` / `'...'`)、缩进续行或 YAML 块标量(`>` / `|`)。嵌套在 `metadata:` 等
下面的同名键不算
- description 超过 1024 字符时截断后照常列出(不再跳过)
- 无 frontmatter 时:name 取目录名,整个文件作为正文

## 发现路径(同名时后者覆盖前者)

| 来源 | 路径 |
|------|------|
| 内置 daily 起步包(仅 daily 会话) | `assets/daily_skills/`(编进二进制,从 Hermes 移植) |
| 全局(与其他 agent 共用,`npx skills add -g` 装在这里) | `~/.agents/skills/<name>/SKILL.md` |
| 用户级 | `~/.limbo/skills/<name>/SKILL.md` |
| 项目级 | `<workdir>/.agents/skills/<name>/SKILL.md` |
| Daily(仅 daily 会话) | `~/.limbo/daily/skills/<name>/SKILL.md` |
Expand All @@ -47,7 +51,8 @@ description: Test-driven development workflow.
## 交互

- 输入 `/` 弹出命令菜单,skills 与内置命令一同列出(skill 带 `[skill]` 标记)
- 继续输入实时过滤;菜单在每次弹出时重新扫描,运行中新增的 skill 立即可用
- 继续输入实时过滤;菜单在每次弹出时重新扫描,运行中新增的 skill 立即可用;
每轮开始前若 skill 有增删改,也会重建 system prompt 里的 `<available_skills>` 目录
- 选中 skill:
- **部分匹配 + Enter / Tab** → 补全为 `/<name> `,可继续输入参数
- **完整输入 `/<name>` + Enter** → 直接无参调用
Expand Down
24 changes: 24 additions & 0 deletions src/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,8 @@ pub struct Agent {
persisted: HashSet<String>,
file_created: bool,
needs_rewrite: bool,
/// The skills catalog the current system prompt was built with.
skills_catalog: String,
pub steer: Arc<SteerQueue>,
rerun: Vec<ToolCall>,
/// Last real prompt size, and the history length it was measured at.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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(),
Expand Down
1 change: 1 addition & 0 deletions src/pump.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<AgentEvent>();
Expand Down
218 changes: 205 additions & 13 deletions src/skills.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
//!
//! Discovery (later sources win on name collisions):
//! - bundled daily pack (daily sessions only, lowest priority)
//! - global: `~/.agents/skills/<name>/SKILL.md` (shared with other agents;
//! where `npx skills add -g` installs)
//! - user: `~/.limbo/skills/<name>/SKILL.md`
//! - project: `<workdir>/.agents/skills/<name>/SKILL.md`
//! - daily: `~/.limbo/daily/skills/<name>/SKILL.md` (daily sessions only)
Expand Down Expand Up @@ -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<PathBuf> {
dirs::home_dir().map(|h| h.join(".agents").join("skills"))
}
pub fn user_skills_dir() -> PathBuf {
limbo_home().join("skills")
}
Expand Down Expand Up @@ -79,31 +85,156 @@ 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);
}
(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<String> {
let mut errors = Vec::new();
Expand Down Expand Up @@ -142,7 +273,16 @@ fn load_from(dir: &Path) -> Vec<Skill> {
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;
}
Expand All @@ -159,7 +299,9 @@ fn load_from(dir: &Path) -> Vec<Skill> {

/// All skills visible to a session, sorted by name.
pub fn discover_skills(workdir: &Path, daily: bool) -> Vec<Skill> {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Health regression — discover_skills()

6 callers depend on it (afferent coupling).

Grounded coupling-delta finding (deterministic), not an LLM guess.

let mut sources = vec![user_skills_dir(), workdir.join(".agents/skills")];
let mut sources: Vec<PathBuf> = 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());
Expand Down Expand Up @@ -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());
Expand Down
Loading
Loading