diff --git a/DESCRIPTION b/DESCRIPTION
index e9d3ff5f..ac740b19 100644
--- a/DESCRIPTION
+++ b/DESCRIPTION
@@ -99,6 +99,7 @@ Collate:
'mcp.R'
'task_create_btw_md.R'
'task_create_readme.R'
+ 'task_create_skill.R'
'tool-result.R'
'tool-agent-subagent.R'
'tool-agent-custom.R'
@@ -121,6 +122,7 @@ Collate:
'tool-run.R'
'tool-session-package-installed.R'
'tool-sessioninfo.R'
+ 'tool-skills.R'
'tool-web.R'
'tools.R'
'utils-ellmer.R'
diff --git a/NAMESPACE b/NAMESPACE
index 948d1884..23b548a5 100644
--- a/NAMESPACE
+++ b/NAMESPACE
@@ -26,9 +26,12 @@ export(btw_app)
export(btw_client)
export(btw_mcp_server)
export(btw_mcp_session)
+export(btw_skill_install_github)
+export(btw_skill_install_package)
export(btw_task)
export(btw_task_create_btw_md)
export(btw_task_create_readme)
+export(btw_task_create_skill)
export(btw_this)
export(btw_tool_agent_subagent)
export(btw_tool_cran_package)
@@ -73,6 +76,7 @@ export(btw_tool_session_platform_info)
export(btw_tool_sessioninfo_is_package_installed)
export(btw_tool_sessioninfo_package)
export(btw_tool_sessioninfo_platform)
+export(btw_tool_skill)
export(btw_tool_web_read_url)
export(btw_tools)
export(edit_btw_md)
diff --git a/R/btw_client.R b/R/btw_client.R
index b3f7063e..4400cb56 100644
--- a/R/btw_client.R
+++ b/R/btw_client.R
@@ -151,12 +151,16 @@ btw_client <- function(
llms_txt <- read_llms_txt(path_llms_txt)
project_context <- c(llms_txt, config$btw_system_prompt)
project_context <- paste(project_context, collapse = "\n\n")
+ skills_prompt <- btw_skills_system_prompt()
sys_prompt <- c(
btw_prompt("btw-system_session.md"),
if (!skip_tools) {
btw_prompt("btw-system_tools.md")
},
+ if (nzchar(skills_prompt)) {
+ skills_prompt
+ },
if (nzchar(project_context)) {
btw_prompt("btw-system_project.md")
},
@@ -170,6 +174,8 @@ btw_client <- function(
client$set_tools(tools = c(client$get_tools(), config$tools))
}
+ warn_skills_without_read_file(client$get_tools())
+
client
}
@@ -661,3 +667,16 @@ remove_hidden_content <- function(text) {
paste(lines[starts - shift(cumsum(ends)) <= 0], collapse = "\n")
}
+
+warn_skills_without_read_file <- function(tools) {
+ tool_names <- names(tools)
+ has_skills <- "btw_tool_skill" %in% tool_names
+ has_read_file <- "btw_tool_files_read" %in% tool_names
+ if (has_skills && !has_read_file) {
+ cli::cli_warn(c(
+ "The {.fn btw_tool_skill} tool is enabled but {.fn btw_tool_files_read} is not.",
+ "i" = "Skills work best with the read file tool, which lets the model read skill resource files.",
+ "i" = "Add {.code btw_tools(\"files\")} or enable {.fn btw_tool_files_read} to get full skill support."
+ ))
+ }
+}
diff --git a/R/btw_client_app.R b/R/btw_client_app.R
index 426e9f7a..4bdda61c 100644
--- a/R/btw_client_app.R
+++ b/R/btw_client_app.R
@@ -270,6 +270,43 @@ btw_app_from_client <- function(
}
})
+ skills_read_file_mismatch <- shiny::reactive({
+ sel <- selected_tools()
+ "btw_tool_skill" %in% sel && !"btw_tool_files_read" %in% sel
+ })
+
+ shiny::observeEvent(skills_read_file_mismatch(), {
+ if (isTRUE(skills_read_file_mismatch())) {
+ notifier(
+ id = "skills_read_file_mismatch",
+ shiny::icon("triangle-exclamation", class = "text-warning"),
+ shiny::tagList(
+ shiny::HTML(
+ "The Load Skill tool works best with the Read File tool enabled"
+ ),
+ shiny::actionButton(
+ class = "btn-sm mt-2",
+ "enable_read_file_tool",
+ "Enable Read File Tool"
+ )
+ )
+ )
+ }
+ })
+
+ shiny::observeEvent(input$enable_read_file_tool, {
+ file_tools <- c(input$tools_files, "btw_tool_files_read")
+ shiny::updateCheckboxGroupInput(
+ session = session,
+ inputId = "tools_files",
+ selected = file_tools
+ )
+ bslib_hide_toast <- asNamespace("bslib")[["hide_toast"]]
+ if (!is.null(bslib_hide_toast)) {
+ bslib_hide_toast("skills_read_file_mismatch")
+ }
+ })
+
output$ui_other_tools <- shiny::renderUI({
if (length(other_tools) == 0) {
return(NULL)
@@ -392,6 +429,47 @@ btw_app_from_client <- function(
# Status Bar ----
+notifier <- function(icon, action, error = NULL, ...) {
+ error_body <- if (!is.null(error)) {
+ shiny::p(shiny::HTML(sprintf("%s", error$message)))
+ }
+
+ bslib_toast <- asNamespace("bslib")[["toast"]]
+ bslib_show_toast <- asNamespace("bslib")[["show_toast"]]
+ bslib_toast_header <- asNamespace("bslib")[["toast_header"]]
+
+ if (is.null(bslib_toast) || is.null(bslib_show_toast)) {
+ if (!is.null(error)) {
+ body <- shiny::span(icon, action)
+ } else {
+ body <- shiny::tagList(
+ shiny::p(
+ shiny::icon("warning"),
+ "Failed to update system prompt",
+ class = "fw-bold"
+ ),
+ error_body
+ )
+ }
+ shiny::showNotification(
+ body,
+ type = if (is.null(error)) "message" else "error"
+ )
+ return()
+ }
+
+ toast <- bslib_toast(
+ if (is.null(error)) action else error_body,
+ header = if (!is.null(error)) {
+ bslib_toast_header(action, icon = icon)
+ },
+ icon = if (is.null(error)) icon,
+ position = "top-right",
+ ...
+ )
+ bslib_show_toast(toast)
+}
+
btw_status_bar_ui <- function(id, provider_model) {
ns <- shiny::NS(id)
shiny::tagList(
@@ -575,46 +653,6 @@ btw_status_bar_server <- function(id, chat) {
shiny::showModal(modal)
})
- notifier <- function(icon, action, error = NULL) {
- error_body <- if (!is.null(error)) {
- shiny::p(shiny::HTML(sprintf("%s", error$message)))
- }
-
- bslib_toast <- asNamespace("bslib")[["toast"]]
- bslib_show_toast <- asNamespace("bslib")[["show_toast"]]
- bslib_toast_header <- asNamespace("bslib")[["toast_header"]]
-
- if (is.null(bslib_toast) || is.null(bslib_show_toast)) {
- if (!is.null(error)) {
- body <- shiny::span(icon, action)
- } else {
- body <- shiny::tagList(
- shiny::p(
- shiny::icon("warning"),
- "Failed to update system prompt",
- class = "fw-bold"
- ),
- error_body
- )
- }
- shiny::showNotification(
- body,
- type = if (is.null(error)) "message" else "error"
- )
- return()
- }
-
- toast <- bslib_toast(
- if (is.null(error)) action else error_body,
- header = if (!is.null(error)) {
- bslib_toast_header(action, icon = icon)
- },
- icon = if (is.null(error)) icon,
- position = "top-right"
- )
- bslib_show_toast(toast)
- }
-
shiny::observeEvent(
input$system_prompt,
ignoreInit = TRUE,
@@ -691,7 +729,7 @@ app_tool_group_inputs <- function(tools_df, initial_tool_names = NULL) {
# then other, then deprecated (if shown)
group_names <- names(tools_df)
- priority_groups <- c("agent", "docs", "files", "env")
+ priority_groups <- c("agent", "skills", "docs", "files", "env")
trailing_groups <- c("other", "deprecated")
priority_present <- intersect(priority_groups, group_names)
middle_groups <- sort(setdiff(
@@ -737,6 +775,7 @@ app_tool_group_choice_input <- function(
"pkg" = shiny::span(label_icon, "Package Tools"),
"run" = shiny::span(label_icon, "Run Code"),
"sessioninfo" = shiny::span(label_icon, "Session Info"),
+ "skills" = shiny::span(label_icon, "Skills"),
"web" = shiny::span(label_icon, "Web Tools"),
"other" = shiny::span(label_icon, "Other Tools"),
to_title_case(group)
diff --git a/R/mcp.R b/R/mcp.R
index 9405e356..868ac63a 100644
--- a/R/mcp.R
+++ b/R/mcp.R
@@ -153,7 +153,7 @@
#'
#' @name mcp
#' @export
-btw_mcp_server <- function(tools = btw_tools()) {
+btw_mcp_server <- function(tools = btw_mcp_tools()) {
# If given a path to an R script, we'll pass it on to mcp_server()
is_likely_r_file <-
is.character(tools) &&
@@ -172,3 +172,16 @@ btw_mcp_server <- function(tools = btw_tools()) {
btw_mcp_session <- function() {
mcptools::mcp_session()
}
+
+btw_mcp_tools <- function() {
+ # Skills are excluded from MCP by default: the skill system prompt
+ # (with metadata) is injected by btw_client(), not by
+ # MCP. Without that context the model has no way to know which skills are
+ # available. Filesystem-based agents (e.g. Claude Code) can read SKILL.md
+ # files directly via their paths in the system prompt.
+ all_tools <- btw_tools()
+ Filter(
+ function(tool) !identical(tool@annotations$btw_group, "skills"),
+ all_tools
+ )
+}
diff --git a/R/task_create_skill.R b/R/task_create_skill.R
new file mode 100644
index 00000000..1dd13ee9
--- /dev/null
+++ b/R/task_create_skill.R
@@ -0,0 +1,188 @@
+#' Task: Create a Skill
+#'
+#' @description
+#' Create a new skill for your project using interactive guidance. If launched
+#' in app or console mode, this task will start an interactive chat session to
+#' guide you through the process of creating a skill that extends Claude's
+#' capabilities with specialized knowledge, workflows, or tool integrations.
+#'
+#' @examples
+#' withr::with_envvar(list(ANTHROPIC_API_KEY = "example"), {
+#' btw_task_create_skill(mode = "tool", client = "anthropic")
+#' })
+#'
+#' @param name Optional skill name. If provided, the AI will skip the naming
+#' step and use this name directly.
+#' @param tools Optional list or character vector of tools to allow the task to
+#' use when creating the skill. By default documentation tools are included to
+#' allow the task to help create package-based skills. You can include
+#' additional tools as needed.
+#'
+#' Because the task requires file tools to create skills with resources, tools
+#' for listing, reading and writing files are always included.
+#' @inheritParams btw_task_create_readme
+#' @inheritParams btw_client
+#'
+#' @return When `mode` is `"app"` or `"console"`, this function launches an
+#' interactive session in the browser or the R console, respectively. The
+#' ellmer chat object with the conversation history is returned invisibly
+#' when the session ends.
+#'
+#' When `mode` is `"client"`, this function returns the configured ellmer
+#' chat client object. When `mode` is `"tool"`, this function returns an
+#' ellmer tool object that can be used in other chat instances.
+#'
+#' @family task and agent functions
+#' @export
+btw_task_create_skill <- function(
+ ...,
+ name = NULL,
+ client = NULL,
+ mode = c("app", "console", "client", "tool"),
+ tools = "docs"
+) {
+ mode <- arg_match(mode)
+
+ client <- btw_client(
+ client = client,
+ tools = list2(
+ !!!tools,
+ "btw_tool_files_list",
+ "btw_tool_files_read",
+ "btw_tool_files_write",
+ "btw_tool_files_replace"
+ )
+ )
+
+ skill_path <- fs::path_package("btw", "skills", "skill-creator")
+ skill_info <- validate_skill(skill_path)
+
+ fm <- frontmatter::read_front_matter(fs::path(skill_path, "SKILL.md"))
+ skill_text <- fm$body %||% ""
+
+ resources <- list_skill_resources(skill_path)
+ resources_listing <- format_resources_listing(resources, skill_path)
+
+ sys_prompt <- paste0(skill_text, resources_listing)
+
+ dots <- dots_list(...)
+ if (length(dots) > 0) {
+ user_context <- btw(..., clipboard = FALSE)
+ if (nzchar(user_context)) {
+ sys_prompt <- paste0(
+ sys_prompt,
+ "\n\n---\n\n",
+ "# Additional context provided by the user\n\n",
+ user_context
+ )
+ }
+ }
+
+ extra_instructions <- r"---(
+## Additional Instructions
+
+If you don't have access to a bash tool, do not attempt to run the bundled Python scripts. Instead, read the script contents and accomplish the same tasks using the file tools available to you.
+
+Do not attempt to package the skill (step 5). The user will handle distribution.
+
+You can only create skills within the current project directory (e.g. `.btw/skills/` or `.agents/skills/`). If the user wants a user-level skill, create it in the project first and advise them to move it to their user skills directory (e.g. `~/.config/btw/skills/` or similar).
+)---"
+
+ if (!is.null(name)) {
+ check_string(name)
+ extra_instructions <- c(
+ extra_instructions,
+ "",
+ sprintf(
+ "The user has already chosen the skill name: %s. Skip the naming step.",
+ name
+ )
+ )
+ }
+
+ sys_prompt <- paste0(
+ sys_prompt,
+ "\n\n---\n\n",
+ paste(extra_instructions, collapse = "\n")
+ )
+
+ client$set_system_prompt(sys_prompt)
+
+ if (mode == "client") {
+ return(client)
+ }
+
+ if (mode == "tool") {
+ btw_task_create_skill_tool <- function(prompt = "", name = NULL) {
+ this_client <- client$clone()
+
+ tool_prompt <- this_client$get_system_prompt()
+
+ if (!is.null(name)) {
+ tool_prompt <- paste0(
+ tool_prompt,
+ "\n\n",
+ sprintf(
+ "The user has already chosen the skill name: %s. Skip the naming step.",
+ name
+ )
+ )
+ }
+
+ tool_prompt <- paste0(
+ tool_prompt,
+ "\n\n---\n\n",
+ "YOU ARE NOW OPERATING IN TOOL MODE. ",
+ "The user cannot respond directly to you. ",
+ "Because you cannot talk to the user, you will need to make your own decisions using the information available to you and the best of your abilities. ",
+ "You may compensate by doing additional file exploration as needed."
+ )
+
+ this_client$set_system_prompt(tool_prompt)
+ this_client$chat(prompt)
+ }
+
+ tool <- ellmer::tool(
+ function(prompt, name = NULL) btw_task_create_skill_tool(prompt, name),
+ name = "btw_task_create_skill",
+ description = "Create a new skill for your project with interactive guidance.",
+ arguments = list(
+ prompt = ellmer::type_string(
+ "Additional instructions to the AI. Leave empty to proceed automatically.",
+ required = FALSE
+ ),
+ name = ellmer::type_string(
+ "Optional skill name. If provided, the AI will skip the naming step.",
+ required = FALSE
+ )
+ ),
+ annotations = ellmer::tool_annotations(
+ title = "Create Skill",
+ icon = tool_icon("post-add")
+ )
+ )
+ return(tool)
+ }
+
+ if (mode == "console") {
+ cli::cli_text(
+ "Starting {.strong btw_task_create_skill()} in live console mode."
+ )
+ cli::cli_text(
+ "{cli::col_yellow(cli::symbol$play)} ",
+ "Say {.strong {cli::col_magenta(\"Let's get started.\")}} to begin."
+ )
+ ellmer::live_console(client)
+ } else {
+ btw_app_from_client(
+ client = client,
+ messages = list(list(
+ role = "assistant",
+ content = paste(
+ "\U1F44B Hi! I'm ready to help you create a new skill for your project.",
+ "Say Let's get started. to begin."
+ )
+ ))
+ )
+ }
+}
diff --git a/R/tool-skills.R b/R/tool-skills.R
new file mode 100644
index 00000000..9ad8b98b
--- /dev/null
+++ b/R/tool-skills.R
@@ -0,0 +1,895 @@
+#' @include tool-result.R
+NULL
+
+#' Tool: Load a skill
+#'
+#' @description
+#' Load a skill's specialized instructions and list its bundled resources.
+#'
+#' Skills are modular capabilities that extend Claude's functionality with
+#' specialized knowledge, workflows, and tools. Each skill is a directory
+#' containing a `SKILL.md` file with instructions and optional bundled
+#' resources (scripts, references, assets).
+#'
+#' @param name The name of the skill to load.
+#' @inheritParams btw_tool_docs_package_news
+#'
+#' @return A `btw_tool_result` containing the skill instructions and a listing
+#' of bundled resources with their paths.
+#'
+#' @family skills
+#' @export
+btw_tool_skill <- function(name, `_intent`) {}
+
+btw_tool_skill_impl <- function(name) {
+ check_string(name)
+
+ skill_info <- find_skill(name)
+
+ if (is.null(skill_info)) {
+ available <- btw_list_skills()
+ skill_names <- vapply(available, function(x) x$name, character(1))
+ cli::cli_abort(
+ c(
+ "Skill {.val {name}} not found.",
+ "i" = "Available skills: {.val {skill_names}}"
+ )
+ )
+ }
+
+ if (!skill_info$validation$valid) {
+ cli::cli_abort(
+ c(
+ "Skill {.val {name}} exists but has validation errors:",
+ set_names(
+ skill_info$validation$errors,
+ rep("!", length(skill_info$validation$errors))
+ )
+ )
+ )
+ }
+
+ fm <- frontmatter::read_front_matter(skill_info$path)
+ skill_text <- fm$body %||% ""
+
+ resources <- list_skill_resources(skill_info$base_dir)
+ resources_listing <- format_resources_listing(resources, skill_info$base_dir)
+
+ full_content <- paste0(skill_text, resources_listing)
+
+ btw_tool_result(
+ value = full_content,
+ data = list(
+ name = name,
+ path = skill_info$path,
+ base_dir = skill_info$base_dir,
+ metadata = fm$data,
+ resources = resources
+ ),
+ display = list(
+ title = sprintf("Skill: %s", name),
+ markdown = full_content
+ )
+ )
+}
+
+.btw_add_to_tools(
+ name = "btw_tool_skill",
+ group = "skills",
+
+ tool = function() {
+ ellmer::tool(
+ btw_tool_skill_impl,
+ name = "btw_tool_skill",
+ description = paste(
+ "Load a skill's specialized instructions and list its bundled",
+ "resources. When you recognize that a task matches one of the",
+ "available skills, use this tool to load the full skill",
+ "instructions. If the user references a skill with /{name}",
+ "syntax, use this tool to load that skill. After loading, use",
+ "file read tools to access bundled references, or adapt bundled",
+ "scripts into R code."
+ ),
+ annotations = ellmer::tool_annotations(
+ title = "Load Skill",
+ read_only_hint = TRUE,
+ open_world_hint = FALSE,
+ btw_can_register = function() any_skills_exist()
+ ),
+ arguments = list(
+ name = ellmer::type_string(
+ "The name of the skill to load"
+ )
+ )
+ )
+ }
+)
+
+# Skill Discovery ----------------------------------------------------------
+
+btw_skill_directories <- function(project_dir = getwd()) {
+ dirs <- character()
+
+ # Package-bundled skills
+ package_skills <- system.file("skills", package = "btw")
+ if (nzchar(package_skills) && dir.exists(package_skills)) {
+ dirs <- c(dirs, package_skills)
+ }
+
+ # User-level skills (global installation)
+ user_skills_dir <- file.path(
+ tools::R_user_dir("btw", "config"),
+ "skills"
+ )
+ if (dir.exists(user_skills_dir)) {
+ dirs <- c(dirs, user_skills_dir)
+ }
+
+ # Project-level skills from multiple conventions
+ for (project_subdir in project_skill_subdirs()) {
+ project_skills_dir <- file.path(project_dir, project_subdir)
+ if (dir.exists(project_skills_dir)) {
+ dirs <- c(dirs, project_skills_dir)
+ }
+ }
+
+ dirs
+}
+
+any_skills_exist <- function() {
+ for (dir in btw_skill_directories()) {
+ subdirs <- list.dirs(dir, full.names = TRUE, recursive = FALSE)
+ for (subdir in subdirs) {
+ if (file.exists(file.path(subdir, "SKILL.md"))) {
+ return(TRUE)
+ }
+ }
+ }
+ FALSE
+}
+
+project_skill_subdirs <- function() {
+ c(
+ file.path(".btw", "skills"),
+ file.path(".agents", "skills")
+ )
+}
+
+resolve_project_skill_dir <- function(error_call = caller_env()) {
+ candidates <- file.path(getwd(), project_skill_subdirs())
+ existing <- candidates[dir.exists(candidates)]
+
+ if (length(existing) == 0) {
+ # None exist yet, default to .btw/skills
+ return(candidates[[1]])
+ }
+
+ if (length(existing) == 1) {
+ return(existing[[1]])
+ }
+
+ # Multiple exist — if interactive, let the user choose
+ if (!is_interactive()) {
+ return(existing[[1]])
+ }
+
+ cli::cli_alert_info("Multiple skill directories found in project:")
+ choice <- utils::menu(
+ choices = existing,
+ graphics = FALSE,
+ title = "\u276F Which directory should be used?"
+ )
+
+ if (choice == 0) {
+ cli::cli_abort("Aborted by user.", call = error_call)
+ }
+
+ existing[[choice]]
+}
+
+btw_list_skills <- function() {
+ skill_dirs <- btw_skill_directories()
+ all_skills <- list()
+
+ for (dir in skill_dirs) {
+ if (!dir.exists(dir)) {
+ next
+ }
+
+ subdirs <- list.dirs(dir, full.names = TRUE, recursive = FALSE)
+
+ for (subdir in subdirs) {
+ skill_md_path <- file.path(subdir, "SKILL.md")
+ if (!file.exists(skill_md_path)) {
+ next
+ }
+
+ validation <- validate_skill(subdir)
+ if (!validation$valid) {
+ cli::cli_warn(c(
+ "Skipping invalid skill in {.path {subdir}}.",
+ set_names(validation$errors, rep("!", length(validation$errors)))
+ ))
+ next
+ }
+
+ if (length(validation$warnings) > 0) {
+ cli::cli_warn(c(
+ "Skill in {.path {subdir}} has validation warnings.",
+ set_names(
+ validation$warnings,
+ rep("!", length(validation$warnings))
+ )
+ ))
+ }
+
+ metadata <- validation$metadata
+ skill_name <- metadata$name
+
+ skill_entry <- list(
+ name = skill_name,
+ description = metadata$description,
+ path = skill_md_path
+ )
+
+ if (!is.null(metadata$compatibility)) {
+ skill_entry$compatibility <- metadata$compatibility
+ }
+ if (!is.null(metadata[["allowed-tools"]])) {
+ skill_entry$allowed_tools <- metadata[["allowed-tools"]]
+ }
+
+ if (skill_name %in% names(all_skills)) {
+ cli::cli_inform(
+ "Skill {.val {skill_name}} in {.path {subdir}} overrides earlier skill at {.path {all_skills[[skill_name]]$path}}."
+ )
+ }
+
+ all_skills[[skill_name]] <- skill_entry
+ }
+ }
+
+ all_skills
+}
+
+find_skill <- function(skill_name) {
+ skill_dirs <- btw_skill_directories()
+
+ # Fast path: directory named skill_name
+ for (dir in skill_dirs) {
+ skill_dir <- file.path(dir, skill_name)
+ skill_md_path <- file.path(skill_dir, "SKILL.md")
+ if (dir.exists(skill_dir) && file.exists(skill_md_path)) {
+ validation <- validate_skill(skill_dir)
+ return(list(
+ path = skill_md_path,
+ base_dir = skill_dir,
+ validation = validation
+ ))
+ }
+ }
+
+ # Slow path: scan all skills for a matching metadata$name (handles name/dir mismatch)
+ for (dir in skill_dirs) {
+ subdirs <- list.dirs(dir, full.names = TRUE, recursive = FALSE)
+ for (subdir in subdirs) {
+ skill_md_path <- file.path(subdir, "SKILL.md")
+ if (!file.exists(skill_md_path)) next
+ validation <- validate_skill(subdir)
+ if (!is.null(validation$metadata$name) &&
+ validation$metadata$name == skill_name) {
+ return(list(
+ path = skill_md_path,
+ base_dir = subdir,
+ validation = validation
+ ))
+ }
+ }
+ }
+
+ NULL
+}
+
+extract_skill_metadata <- function(skill_path) {
+ tryCatch(
+ {
+ fm <- frontmatter::read_front_matter(skill_path)
+ fm$data %||% list()
+ },
+ error = function(e) {
+ cli::cli_warn(
+ "Failed to parse frontmatter in {.path {skill_path}}: {e$message}"
+ )
+ list()
+ }
+ )
+}
+
+# Skill Validation ---------------------------------------------------------
+
+validate_skill_name_format <- function(name) {
+ issues <- character()
+
+ if (nchar(name) > 64) {
+ issues <- c(
+ issues,
+ sprintf("Name is too long (%d characters, max 64).", nchar(name))
+ )
+ }
+ if (!grepl("^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$", name)) {
+ issues <- c(
+ issues,
+ sprintf(
+ "Name '%s' must contain only lowercase letters, numbers, and hyphens, and must not start or end with a hyphen.",
+ name
+ )
+ )
+ }
+ if (grepl("--", name)) {
+ issues <- c(
+ issues,
+ sprintf("Name '%s' must not contain consecutive hyphens.", name)
+ )
+ }
+
+ issues
+}
+
+validate_skill <- function(skill_dir) {
+ skill_dir <- normalizePath(skill_dir, mustWork = FALSE)
+ errors <- character()
+ warnings <- character()
+
+ skill_md_path <- file.path(skill_dir, "SKILL.md")
+ if (!file.exists(skill_md_path)) {
+ return(skill_validation(errors = "SKILL.md not found."))
+ }
+
+ # Parse frontmatter — return the result or the error, never use <<-
+ parse_result <- tryCatch(
+ frontmatter::read_front_matter(skill_md_path),
+ error = function(e) e
+ )
+
+ if (inherits(parse_result, "error")) {
+ return(skill_validation(
+ errors = sprintf("Failed to parse frontmatter: %s", parse_result$message)
+ ))
+ }
+
+ metadata <- parse_result$data
+
+ if (is.null(metadata)) {
+ return(skill_validation(errors = "No YAML frontmatter found."))
+ }
+
+ if (!is.list(metadata)) {
+ return(skill_validation(errors = "Frontmatter must be a YAML mapping."))
+ }
+
+ # --- Hard errors: things that prevent the skill from working ---
+
+ # Validate name (missing/empty is an error, format issues are warnings)
+ name <- metadata$name
+ if (is.null(name) || !is.character(name) || !nzchar(name)) {
+ errors <- c(errors, "Missing or empty 'name' field in frontmatter.")
+ } else {
+ name_format_issues <- validate_skill_name_format(name)
+ warnings <- c(warnings, name_format_issues)
+
+ if (!is.null(skill_dir) && name != basename(skill_dir)) {
+ warnings <- c(
+ warnings,
+ sprintf(
+ "Name '%s' in frontmatter does not match directory name '%s'. Consider renaming the directory to '%s'.",
+ name,
+ basename(skill_dir),
+ name
+ )
+ )
+ }
+ }
+
+ # Validate description (missing/empty is an error, too long is a warning)
+ description <- metadata$description
+ if (
+ is.null(description) || !is.character(description) || !nzchar(description)
+ ) {
+ errors <- c(errors, "Missing or empty 'description' field in frontmatter.")
+ } else if (nchar(description) > 1024) {
+ warnings <- c(
+ warnings,
+ sprintf(
+ "Description is too long (%d characters, max 1024).",
+ nchar(description)
+ )
+ )
+ }
+
+ # --- Soft warnings: spec compliance that doesn't break functionality ---
+
+ # Check for unexpected properties
+ allowed_fields <- c(
+ "name",
+ "description",
+ "license",
+ "compatibility",
+ "metadata",
+ "allowed-tools"
+ )
+ unexpected <- setdiff(names(metadata), allowed_fields)
+ if (length(unexpected) > 0) {
+ warnings <- c(
+ warnings,
+ sprintf(
+ "Unexpected frontmatter field(s): %s. Allowed fields: %s.",
+ paste(unexpected, collapse = ", "),
+ paste(allowed_fields, collapse = ", ")
+ )
+ )
+ }
+
+ # Validate optional fields
+ if (!is.null(metadata$compatibility)) {
+ if (!is.character(metadata$compatibility)) {
+ warnings <- c(
+ warnings,
+ "The 'compatibility' field must be a character string."
+ )
+ } else if (nchar(metadata$compatibility) > 500) {
+ warnings <- c(
+ warnings,
+ sprintf(
+ "Compatibility field is too long (%d characters, max 500).",
+ nchar(metadata$compatibility)
+ )
+ )
+ }
+ }
+
+ if (!is.null(metadata$metadata) && !is.list(metadata$metadata)) {
+ warnings <- c(
+ warnings,
+ "The 'metadata' field must be a key-value mapping."
+ )
+ }
+
+ skill_validation(errors = errors, warnings = warnings, metadata = metadata)
+}
+
+skill_validation <- function(
+ errors = character(),
+ warnings = character(),
+ metadata = NULL
+) {
+ list(
+ valid = length(errors) == 0,
+ errors = errors,
+ warnings = warnings,
+ # Combined for backward compatibility with callers using $issues
+ issues = c(errors, warnings),
+ metadata = metadata
+ )
+}
+
+# Skill Resources ----------------------------------------------------------
+
+list_skill_resources <- function(skill_dir) {
+ list(
+ scripts = list_files_in_subdir(skill_dir, "scripts"),
+ references = list_files_in_subdir(skill_dir, "references"),
+ assets = list_files_in_subdir(skill_dir, "assets")
+ )
+}
+
+list_files_in_subdir <- function(base_dir, subdir) {
+ full_path <- file.path(base_dir, subdir)
+ if (!dir.exists(full_path)) {
+ return(character(0))
+ }
+ list.files(full_path, full.names = FALSE, recursive = TRUE)
+}
+
+has_skill_resources <- function(resources) {
+ length(resources$scripts) > 0 ||
+ length(resources$references) > 0 ||
+ length(resources$assets) > 0
+}
+
+format_resources_listing <- function(resources, base_dir) {
+ if (!has_skill_resources(resources)) {
+ return("")
+ }
+
+ parts <- character()
+ parts <- c(parts, "\n\n---\n\n## Bundled Resources\n")
+
+ if (length(resources$scripts) > 0) {
+ parts <- c(parts, "\n\n**Scripts:**\n")
+ script_paths <- file.path(base_dir, "scripts", resources$scripts)
+ parts <- c(parts, paste0("- ", script_paths, collapse = "\n"))
+ }
+
+ if (length(resources$references) > 0) {
+ parts <- c(parts, "\n\n**References:**\n")
+ ref_paths <- file.path(base_dir, "references", resources$references)
+ parts <- c(parts, paste0("- ", ref_paths, collapse = "\n"))
+ }
+
+ if (length(resources$assets) > 0) {
+ parts <- c(parts, "\n\n**Assets:**\n")
+ asset_paths <- file.path(base_dir, "assets", resources$assets)
+ parts <- c(parts, paste0("- ", asset_paths, collapse = "\n"))
+ }
+
+ paste(parts, collapse = "")
+}
+
+xml_escape <- function(x) {
+ x <- gsub("&", "&", x, fixed = TRUE)
+ x <- gsub("<", "<", x, fixed = TRUE)
+ x <- gsub(">", ">", x, fixed = TRUE)
+ x
+}
+
+# System Prompt ------------------------------------------------------------
+
+btw_skills_system_prompt <- function() {
+ skills <- btw_list_skills()
+
+ if (length(skills) == 0) {
+ return("")
+ }
+
+ skills_prompt_path <- system.file("prompts", "skills.md", package = "btw")
+ explanation <- if (file.exists(skills_prompt_path)) {
+ paste(readLines(skills_prompt_path, warn = FALSE), collapse = "\n")
+ } else {
+ "## Skills\n\nYou have access to specialized skills that provide detailed guidance for specific tasks."
+ }
+
+ skill_items <- vapply(
+ skills,
+ function(skill) {
+ parts <- sprintf(
+ "\n%s\n%s\n%s",
+ xml_escape(skill$name),
+ xml_escape(skill$description),
+ xml_escape(skill$path)
+ )
+ if (!is.null(skill$compatibility)) {
+ parts <- paste0(
+ parts,
+ sprintf(
+ "\n%s",
+ xml_escape(skill$compatibility)
+ )
+ )
+ }
+ if (!is.null(skill$allowed_tools)) {
+ parts <- paste0(
+ parts,
+ sprintf(
+ "\n%s",
+ xml_escape(skill$allowed_tools)
+ )
+ )
+ }
+ paste0(parts, "\n")
+ },
+ character(1)
+ )
+
+ paste0(
+ explanation,
+ "\n\n\n",
+ paste(skill_items, collapse = "\n"),
+ "\n"
+ )
+}
+
+# Scope Resolution ---------------------------------------------------------
+
+resolve_skill_scope <- function(scope, error_call = caller_env()) {
+ if (inherits(scope, "AsIs")) {
+ return(as.character(scope))
+ }
+
+ switch(
+ scope,
+ project = resolve_project_skill_dir(error_call = error_call),
+ user = file.path(tools::R_user_dir("btw", "config"), "skills"),
+ scope
+ )
+}
+
+select_skill_dir <- function(
+ skill_dirs,
+ skill = NULL,
+ source_label = "source"
+) {
+ if (length(skill_dirs) == 0) {
+ cli::cli_abort("No skills found in {source_label}.")
+ }
+
+ if (!is.null(skill)) {
+ check_string(skill)
+ match_idx <- match(skill, basename(skill_dirs))
+ if (is.na(match_idx)) {
+ available <- basename(skill_dirs)
+ cli::cli_abort(c(
+ "Skill {.val {skill}} not found in {source_label}.",
+ "i" = "Available skills: {.val {available}}"
+ ))
+ }
+ return(skill_dirs[[match_idx]])
+ }
+
+ if (length(skill_dirs) == 1) {
+ return(skill_dirs[[1]])
+ }
+
+ # Multiple skills, no name specified
+
+ if (!is_interactive()) {
+ available <- basename(skill_dirs)
+ cli::cli_abort(c(
+ "Multiple skills found in {source_label}.",
+ "i" = "Available skills: {.val {available}}",
+ "i" = "Use the {.arg skill} argument to select one."
+ ))
+ }
+
+ cli::cli_alert_info("Multiple skills found in {source_label}:")
+ choice <- utils::menu(
+ choices = basename(skill_dirs),
+ graphics = FALSE,
+ title = "\u276F Which skill would you like to install?"
+ )
+
+ if (choice == 0) {
+ cli::cli_abort("Aborted by user.")
+ }
+
+ skill_dirs[[choice]]
+}
+
+#' Install a skill from GitHub
+#'
+#' @description
+#' Download and install a skill from a GitHub repository. The repository
+#' should contain one or more skill directories, each with a `SKILL.md` file.
+#'
+#' @param repo GitHub repository in `"owner/repo"` format. Optionally include
+#' a Git reference (branch, tag, or SHA) as `"owner/repo@ref"`, following the
+#' convention used by [pak::pak()] and [remotes::install_github()]. Defaults to
+#' `"HEAD"` when no ref is specified.
+#' @param skill Optional skill name. If `NULL` and the repository contains
+#' multiple skills, an interactive picker is shown (or an error in
+#' non-interactive sessions).
+#' @param scope Where to install the skill. One of:
+#' - `"project"` (default): Installs to a project-level skills directory,
+#' chosen from `.btw/skills/` or `.agents/skills/`
+#' in that order. If one already exists, it is used; otherwise
+#' `.btw/skills/` is created.
+#' - `"user"`: Installs to the user-level skills directory
+#' (`tools::R_user_dir("btw", "config")/skills`).
+#' - A directory path: Installs to a custom directory, e.g.
+#' `scope = ".openhands/skills"`. Use `I("project")` or `I("user")`
+#' if you need a literal directory with those names.
+#' @param overwrite Whether to overwrite an existing skill with the same name.
+#' If `NULL` (default), prompts interactively when a conflict exists; in
+#' non-interactive sessions defaults to `FALSE`, which errors. Set to `TRUE`
+#' to always overwrite, or `FALSE` to always error on conflict.
+#'
+#' @return The path to the installed skill directory, invisibly.
+#'
+#' @family skills
+#' @export
+btw_skill_install_github <- function(
+ repo,
+ skill = NULL,
+ scope = "project",
+ overwrite = NULL
+) {
+ check_string(repo)
+ if (!is.null(skill)) {
+ check_string(skill)
+ }
+ check_string(scope)
+ if (!is.null(overwrite)) check_bool(overwrite)
+
+ rlang::check_installed("gh", reason = "to install skills from GitHub.")
+
+ repo_og <- repo
+ repo <- parse_github_repo(repo)
+
+ # Download zipball
+ tmp_zip <- tempfile(fileext = ".zip")
+ on.exit(unlink(tmp_zip), add = TRUE)
+
+ tryCatch(
+ gh::gh(
+ "/repos/{owner}/{repo}/zipball/{ref}",
+ owner = repo$owner,
+ repo = repo$repo,
+ ref = repo$ref,
+ .destfile = tmp_zip
+ ),
+ error = function(e) {
+ cli::cli_abort(
+ "Failed to download from GitHub repository {.val {repo_og}}: {e$message}",
+ parent = e
+ )
+ }
+ )
+
+ # Extract to temp dir
+ tmp_dir <- tempfile("btw_gh_skill_")
+ on.exit(unlink(tmp_dir, recursive = TRUE), add = TRUE)
+ utils::unzip(tmp_zip, exdir = tmp_dir)
+
+ # Find all SKILL.md files
+ skill_files <- list.files(
+ tmp_dir,
+ pattern = "^SKILL\\.md$",
+ recursive = TRUE,
+ full.names = TRUE
+ )
+
+ if (length(skill_files) == 0) {
+ cli::cli_abort("No skills found in GitHub repository {.val {repo_og}}.")
+ }
+
+ skill_dirs <- dirname(skill_files)
+
+ selected <- select_skill_dir(
+ skill_dirs,
+ skill = skill,
+ source_label = cli::format_inline("GitHub repository {.field {repo_og}}")
+ )
+
+ install_skill_from_dir(selected, scope = scope, overwrite = overwrite)
+}
+
+#' Install a skill from an R package
+#'
+#' @description
+#' Install a skill bundled in an R package. Packages can bundle skills in
+#' their `inst/skills/` directory, where each subdirectory containing a
+#' `SKILL.md` file is a skill.
+#'
+#' @param package Name of an installed R package that bundles skills.
+#' @param skill Optional skill name. If `NULL` and the package contains
+#' multiple skills, an interactive picker is shown (or an error in
+#' non-interactive sessions).
+#' @param scope Where to install the skill. One of:
+#' - `"project"` (default): Installs to a project-level skills directory,
+#' chosen from `.btw/skills/` or `.agents/skills/`
+#' in that order. If one already exists, it is used; otherwise
+#' `.btw/skills/` is created.
+#' - `"user"`: Installs to the user-level skills directory
+#' (`tools::R_user_dir("btw", "config")/skills`).
+#' - A directory path: Installs to a custom directory, e.g.
+#' `scope = ".openhands/skills"`. Use `I("project")` or `I("user")`
+#' if you need a literal directory with those names.
+#' @param overwrite Whether to overwrite an existing skill with the same name.
+#' If `NULL` (default), prompts interactively when a conflict exists; in
+#' non-interactive sessions defaults to `FALSE`, which errors. Set to `TRUE`
+#' to always overwrite, or `FALSE` to always error on conflict.
+#'
+#' @return The path to the installed skill directory, invisibly.
+#'
+#' @family skills
+#' @export
+btw_skill_install_package <- function(
+ package,
+ skill = NULL,
+ scope = "project",
+ overwrite = NULL
+) {
+ check_string(package)
+ if (!is.null(skill)) {
+ check_string(skill)
+ }
+ check_string(scope)
+ if (!is.null(overwrite)) check_bool(overwrite)
+
+ rlang::check_installed(package, reason = "to install skills from it.")
+
+ skills_dir <- system.file("skills", package = package)
+ if (!nzchar(skills_dir) || !dir.exists(skills_dir)) {
+ cli::cli_abort("Package {.pkg {package}} does not bundle any skills.")
+ }
+
+ # Find subdirectories that contain SKILL.md
+ subdirs <- list.dirs(skills_dir, full.names = TRUE, recursive = FALSE)
+ skill_dirs <- subdirs[file.exists(file.path(subdirs, "SKILL.md"))]
+
+ if (length(skill_dirs) == 0) {
+ cli::cli_abort("Package {.pkg {package}} does not bundle any skills.")
+ }
+
+ selected <- select_skill_dir(
+ skill_dirs,
+ skill = skill,
+ source_label = cli::format_inline("package {.pkg {package}}")
+ )
+
+ install_skill_from_dir(selected, scope = scope, overwrite = overwrite)
+}
+
+install_skill_from_dir <- function(
+ source_dir,
+ scope = "project",
+ overwrite = NULL
+) {
+ check_string(source_dir)
+ check_string(scope)
+ if (!is.null(overwrite)) check_bool(overwrite)
+
+ source_dir <- normalizePath(source_dir, mustWork = FALSE)
+ if (!dir.exists(source_dir)) {
+ cli::cli_abort("Source directory not found: {.path {source_dir}}")
+ }
+
+ # Determine target directory
+ target_parent <- resolve_skill_scope(scope)
+
+ skill_name <- basename(source_dir)
+ target_dir <- file.path(target_parent, skill_name)
+
+ if (dir.exists(target_dir)) {
+ do_overwrite <- if (is.null(overwrite)) {
+ if (rlang::is_interactive()) {
+ choice <- utils::menu(
+ c("Yes", "No"),
+ title = cli::format_inline(
+ "Skill {.val {skill_name}} already exists at {.path {target_dir}}. Overwrite?"
+ )
+ )
+ choice == 1L
+ } else {
+ FALSE
+ }
+ } else {
+ overwrite
+ }
+
+ if (do_overwrite) {
+ unlink(target_dir, recursive = TRUE)
+ } else {
+ cli::cli_abort(
+ "Skill {.val {skill_name}} already exists at {.path {target_dir}}."
+ )
+ }
+ }
+
+ # Validate before installing
+ validation <- validate_skill(source_dir)
+ if (!validation$valid) {
+ cli::cli_abort(c(
+ "Cannot install invalid skill:",
+ set_names(validation$errors, rep("!", length(validation$errors)))
+ ))
+ }
+
+ if (length(validation$warnings) > 0) {
+ cli::cli_warn(c(
+ "Installing skill {.val {skill_name}} with validation warnings:",
+ set_names(
+ validation$warnings,
+ rep("!", length(validation$warnings))
+ )
+ ))
+ }
+
+ dir.create(target_parent, recursive = TRUE, showWarnings = FALSE)
+ fs::dir_copy(source_dir, target_dir)
+
+ cli::cli_inform(c(
+ "v" = "Installed skill {.val {skill_name}} to {.path {target_dir}}"
+ ))
+
+ invisible(target_dir)
+}
diff --git a/R/tools.R b/R/tools.R
index cdc7bd38..1e4ec4b6 100644
--- a/R/tools.R
+++ b/R/tools.R
@@ -220,6 +220,7 @@ tool_group_icon <- function(group, default = NULL) {
"ide" = tool_icon("code-blocks"),
"pkg" = tool_icon("package"),
"sessioninfo" = tool_icon("screen-search-desktop"),
+ "skills" = tool_icon("category"),
"web" = tool_icon("globe-book"),
if (!is.null(default)) tool_icon(default)
)
diff --git a/R/utils.R b/R/utils.R
index ed09afb5..a2299571 100644
--- a/R/utils.R
+++ b/R/utils.R
@@ -320,3 +320,32 @@ strip_ansi <- function(text) {
to_title_case <- function(x) {
paste0(toupper(substring(x, 1, 1)), substring(x, 2))
}
+
+# GitHub repo parsing --------------------------------------------------------
+
+parse_github_repo <- function(repo, error_call = caller_env()) {
+ check_string(repo, call = error_call)
+
+ ref <- "HEAD"
+ if (grepl("@", repo, fixed = TRUE)) {
+ at_pos <- regexpr("@", repo, fixed = TRUE)
+ ref <- substring(repo, at_pos + 1L)
+ repo <- substring(repo, 1L, at_pos - 1L)
+ if (!nzchar(ref)) {
+ cli::cli_abort(
+ '{.arg repo} has an empty ref after {.val @}. Use {.val owner/repo@ref} format.',
+ call = error_call
+ )
+ }
+ }
+
+ parts <- strsplit(repo, "/", fixed = TRUE)[[1]]
+ if (length(parts) != 2 || !nzchar(parts[[1]]) || !nzchar(parts[[2]])) {
+ cli::cli_abort(
+ '{.arg repo} must be in {.val owner/repo} or {.val owner/repo@ref} format, not {.val {repo}}.',
+ call = error_call
+ )
+ }
+
+ list(owner = parts[[1]], repo = parts[[2]], ref = ref)
+}
diff --git a/inst/icons/category.svg b/inst/icons/category.svg
new file mode 100644
index 00000000..44038ac6
--- /dev/null
+++ b/inst/icons/category.svg
@@ -0,0 +1 @@
+
diff --git a/inst/prompts/skills.md b/inst/prompts/skills.md
new file mode 100644
index 00000000..e3ce8ce5
--- /dev/null
+++ b/inst/prompts/skills.md
@@ -0,0 +1,15 @@
+## Skills
+
+You have access to specialized skills that provide detailed guidance for specific tasks. Skills are loaded on-demand to provide domain-specific expertise without consuming context until needed.
+
+### Using Skills
+
+1. **Check available skills**: Review the `` listing below
+2. **Load when relevant**: When you recognize that a task matches a skill's description, call `btw_tool_skill(name)` to load the full skill instructions
+3. **Don't reload**: If a skill has already been loaded in this conversation, follow its instructions directly without loading it again
+4. **Access resources**: After loading, use file read tools to access references
+
+Skills may include bundled resources:
+- **Scripts**: Code bundled with the skill. Scripts are not directly executable by btw; read them for reference or adapt their logic into R code for use with the R code execution tool.
+- **References**: Additional documentation to consult as needed
+- **Assets**: Templates and files for use in outputs
diff --git a/inst/skills/skill-creator/SKILL.md b/inst/skills/skill-creator/SKILL.md
new file mode 100644
index 00000000..b7f86598
--- /dev/null
+++ b/inst/skills/skill-creator/SKILL.md
@@ -0,0 +1,356 @@
+---
+name: skill-creator
+description: Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends Claude's capabilities with specialized knowledge, workflows, or tool integrations.
+license: Complete terms in LICENSE.txt
+---
+
+# Skill Creator
+
+This skill provides guidance for creating effective skills.
+
+## About Skills
+
+Skills are modular, self-contained packages that extend Claude's capabilities by providing
+specialized knowledge, workflows, and tools. Think of them as "onboarding guides" for specific
+domains or tasks—they transform Claude from a general-purpose agent into a specialized agent
+equipped with procedural knowledge that no model can fully possess.
+
+### What Skills Provide
+
+1. Specialized workflows - Multi-step procedures for specific domains
+2. Tool integrations - Instructions for working with specific file formats or APIs
+3. Domain expertise - Company-specific knowledge, schemas, business logic
+4. Bundled resources - Scripts, references, and assets for complex and repetitive tasks
+
+## Core Principles
+
+### Concise is Key
+
+The context window is a public good. Skills share the context window with everything else Claude needs: system prompt, conversation history, other Skills' metadata, and the actual user request.
+
+**Default assumption: Claude is already very smart.** Only add context Claude doesn't already have. Challenge each piece of information: "Does Claude really need this explanation?" and "Does this paragraph justify its token cost?"
+
+Prefer concise examples over verbose explanations.
+
+### Set Appropriate Degrees of Freedom
+
+Match the level of specificity to the task's fragility and variability:
+
+**High freedom (text-based instructions)**: Use when multiple approaches are valid, decisions depend on context, or heuristics guide the approach.
+
+**Medium freedom (pseudocode or scripts with parameters)**: Use when a preferred pattern exists, some variation is acceptable, or configuration affects behavior.
+
+**Low freedom (specific scripts, few parameters)**: Use when operations are fragile and error-prone, consistency is critical, or a specific sequence must be followed.
+
+Think of Claude as exploring a path: a narrow bridge with cliffs needs specific guardrails (low freedom), while an open field allows many routes (high freedom).
+
+### Anatomy of a Skill
+
+Every skill consists of a required SKILL.md file and optional bundled resources:
+
+```
+skill-name/
+├── SKILL.md (required)
+│ ├── YAML frontmatter metadata (required)
+│ │ ├── name: (required)
+│ │ └── description: (required)
+│ └── Markdown instructions (required)
+└── Bundled Resources (optional)
+ ├── scripts/ - Executable code (Python/Bash/etc.)
+ ├── references/ - Documentation intended to be loaded into context as needed
+ └── assets/ - Files used in output (templates, icons, fonts, etc.)
+```
+
+#### SKILL.md (required)
+
+Every SKILL.md consists of:
+
+- **Frontmatter** (YAML): Contains `name` and `description` fields. These are the only fields that Claude reads to determine when the skill gets used, thus it is very important to be clear and comprehensive in describing what the skill is, and when it should be used.
+- **Body** (Markdown): Instructions and guidance for using the skill. Only loaded AFTER the skill triggers (if at all).
+
+#### Bundled Resources (optional)
+
+##### Scripts (`scripts/`)
+
+Executable code (Python/Bash/etc.) for tasks that require deterministic reliability or are repeatedly rewritten.
+
+- **When to include**: When the same code is being rewritten repeatedly or deterministic reliability is needed
+- **Example**: `scripts/rotate_pdf.py` for PDF rotation tasks
+- **Benefits**: Token efficient, deterministic, may be executed without loading into context
+- **Note**: Scripts may still need to be read by Claude for patching or environment-specific adjustments
+
+##### References (`references/`)
+
+Documentation and reference material intended to be loaded as needed into context to inform Claude's process and thinking.
+
+- **When to include**: For documentation that Claude should reference while working
+- **Examples**: `references/finance.md` for financial schemas, `references/mnda.md` for company NDA template, `references/policies.md` for company policies, `references/api_docs.md` for API specifications
+- **Use cases**: Database schemas, API documentation, domain knowledge, company policies, detailed workflow guides
+- **Benefits**: Keeps SKILL.md lean, loaded only when Claude determines it's needed
+- **Best practice**: If files are large (>10k words), include grep search patterns in SKILL.md
+- **Avoid duplication**: Information should live in either SKILL.md or references files, not both. Prefer references files for detailed information unless it's truly core to the skill—this keeps SKILL.md lean while making information discoverable without hogging the context window. Keep only essential procedural instructions and workflow guidance in SKILL.md; move detailed reference material, schemas, and examples to references files.
+
+##### Assets (`assets/`)
+
+Files not intended to be loaded into context, but rather used within the output Claude produces.
+
+- **When to include**: When the skill needs files that will be used in the final output
+- **Examples**: `assets/logo.png` for brand assets, `assets/slides.pptx` for PowerPoint templates, `assets/frontend-template/` for HTML/React boilerplate, `assets/font.ttf` for typography
+- **Use cases**: Templates, images, icons, boilerplate code, fonts, sample documents that get copied or modified
+- **Benefits**: Separates output resources from documentation, enables Claude to use files without loading them into context
+
+#### What to Not Include in a Skill
+
+A skill should only contain essential files that directly support its functionality. Do NOT create extraneous documentation or auxiliary files, including:
+
+- README.md
+- INSTALLATION_GUIDE.md
+- QUICK_REFERENCE.md
+- CHANGELOG.md
+- etc.
+
+The skill should only contain the information needed for an AI agent to do the job at hand. It should not contain auxilary context about the process that went into creating it, setup and testing procedures, user-facing documentation, etc. Creating additional documentation files just adds clutter and confusion.
+
+### Progressive Disclosure Design Principle
+
+Skills use a three-level loading system to manage context efficiently:
+
+1. **Metadata (name + description)** - Always in context (~100 words)
+2. **SKILL.md body** - When skill triggers (<5k words)
+3. **Bundled resources** - As needed by Claude (Unlimited because scripts can be executed without reading into context window)
+
+#### Progressive Disclosure Patterns
+
+Keep SKILL.md body to the essentials and under 500 lines to minimize context bloat. Split content into separate files when approaching this limit. When splitting out content into other files, it is very important to reference them from SKILL.md and describe clearly when to read them, to ensure the reader of the skill knows they exist and when to use them.
+
+**Key principle:** When a skill supports multiple variations, frameworks, or options, keep only the core workflow and selection guidance in SKILL.md. Move variant-specific details (patterns, examples, configuration) into separate reference files.
+
+**Pattern 1: High-level guide with references**
+
+```markdown
+# PDF Processing
+
+## Quick start
+
+Extract text with pdfplumber:
+[code example]
+
+## Advanced features
+
+- **Form filling**: See [FORMS.md](FORMS.md) for complete guide
+- **API reference**: See [REFERENCE.md](REFERENCE.md) for all methods
+- **Examples**: See [EXAMPLES.md](EXAMPLES.md) for common patterns
+```
+
+Claude loads FORMS.md, REFERENCE.md, or EXAMPLES.md only when needed.
+
+**Pattern 2: Domain-specific organization**
+
+For Skills with multiple domains, organize content by domain to avoid loading irrelevant context:
+
+```
+bigquery-skill/
+├── SKILL.md (overview and navigation)
+└── reference/
+ ├── finance.md (revenue, billing metrics)
+ ├── sales.md (opportunities, pipeline)
+ ├── product.md (API usage, features)
+ └── marketing.md (campaigns, attribution)
+```
+
+When a user asks about sales metrics, Claude only reads sales.md.
+
+Similarly, for skills supporting multiple frameworks or variants, organize by variant:
+
+```
+cloud-deploy/
+├── SKILL.md (workflow + provider selection)
+└── references/
+ ├── aws.md (AWS deployment patterns)
+ ├── gcp.md (GCP deployment patterns)
+ └── azure.md (Azure deployment patterns)
+```
+
+When the user chooses AWS, Claude only reads aws.md.
+
+**Pattern 3: Conditional details**
+
+Show basic content, link to advanced content:
+
+```markdown
+# DOCX Processing
+
+## Creating documents
+
+Use docx-js for new documents. See [DOCX-JS.md](DOCX-JS.md).
+
+## Editing documents
+
+For simple edits, modify the XML directly.
+
+**For tracked changes**: See [REDLINING.md](REDLINING.md)
+**For OOXML details**: See [OOXML.md](OOXML.md)
+```
+
+Claude reads REDLINING.md or OOXML.md only when the user needs those features.
+
+**Important guidelines:**
+
+- **Avoid deeply nested references** - Keep references one level deep from SKILL.md. All reference files should link directly from SKILL.md.
+- **Structure longer reference files** - For files longer than 100 lines, include a table of contents at the top so Claude can see the full scope when previewing.
+
+## Skill Creation Process
+
+Skill creation involves these steps:
+
+1. Understand the skill with concrete examples
+2. Plan reusable skill contents (scripts, references, assets)
+3. Initialize the skill (run init_skill.py)
+4. Edit the skill (implement resources and write SKILL.md)
+5. Package the skill (run package_skill.py)
+6. Iterate based on real usage
+
+Follow these steps in order, skipping only if there is a clear reason why they are not applicable.
+
+### Step 1: Understanding the Skill with Concrete Examples
+
+Skip this step only when the skill's usage patterns are already clearly understood. It remains valuable even when working with an existing skill.
+
+To create an effective skill, clearly understand concrete examples of how the skill will be used. This understanding can come from either direct user examples or generated examples that are validated with user feedback.
+
+For example, when building an image-editor skill, relevant questions include:
+
+- "What functionality should the image-editor skill support? Editing, rotating, anything else?"
+- "Can you give some examples of how this skill would be used?"
+- "I can imagine users asking for things like 'Remove the red-eye from this image' or 'Rotate this image'. Are there other ways you imagine this skill being used?"
+- "What would a user say that should trigger this skill?"
+
+To avoid overwhelming users, avoid asking too many questions in a single message. Start with the most important questions and follow up as needed for better effectiveness.
+
+Conclude this step when there is a clear sense of the functionality the skill should support.
+
+### Step 2: Planning the Reusable Skill Contents
+
+To turn concrete examples into an effective skill, analyze each example by:
+
+1. Considering how to execute on the example from scratch
+2. Identifying what scripts, references, and assets would be helpful when executing these workflows repeatedly
+
+Example: When building a `pdf-editor` skill to handle queries like "Help me rotate this PDF," the analysis shows:
+
+1. Rotating a PDF requires re-writing the same code each time
+2. A `scripts/rotate_pdf.py` script would be helpful to store in the skill
+
+Example: When designing a `frontend-webapp-builder` skill for queries like "Build me a todo app" or "Build me a dashboard to track my steps," the analysis shows:
+
+1. Writing a frontend webapp requires the same boilerplate HTML/React each time
+2. An `assets/hello-world/` template containing the boilerplate HTML/React project files would be helpful to store in the skill
+
+Example: When building a `big-query` skill to handle queries like "How many users have logged in today?" the analysis shows:
+
+1. Querying BigQuery requires re-discovering the table schemas and relationships each time
+2. A `references/schema.md` file documenting the table schemas would be helpful to store in the skill
+
+To establish the skill's contents, analyze each concrete example to create a list of the reusable resources to include: scripts, references, and assets.
+
+### Step 3: Initializing the Skill
+
+At this point, it is time to actually create the skill.
+
+Skip this step only if the skill being developed already exists, and iteration or packaging is needed. In this case, continue to the next step.
+
+When creating a new skill from scratch, always run the `init_skill.py` script. The script conveniently generates a new template skill directory that automatically includes everything a skill requires, making the skill creation process much more efficient and reliable.
+
+Usage:
+
+```bash
+scripts/init_skill.py --path
+```
+
+The script:
+
+- Creates the skill directory at the specified path
+- Generates a SKILL.md template with proper frontmatter and TODO placeholders
+- Creates example resource directories: `scripts/`, `references/`, and `assets/`
+- Adds example files in each directory that can be customized or deleted
+
+After initialization, customize or remove the generated SKILL.md and example files as needed.
+
+### Step 4: Edit the Skill
+
+When editing the (newly-generated or existing) skill, remember that the skill is being created for another instance of Claude to use. Include information that would be beneficial and non-obvious to Claude. Consider what procedural knowledge, domain-specific details, or reusable assets would help another Claude instance execute these tasks more effectively.
+
+#### Learn Proven Design Patterns
+
+Consult these helpful guides based on your skill's needs:
+
+- **Multi-step processes**: See references/workflows.md for sequential workflows and conditional logic
+- **Specific output formats or quality standards**: See references/output-patterns.md for template and example patterns
+
+These files contain established best practices for effective skill design.
+
+#### Start with Reusable Skill Contents
+
+To begin implementation, start with the reusable resources identified above: `scripts/`, `references/`, and `assets/` files. Note that this step may require user input. For example, when implementing a `brand-guidelines` skill, the user may need to provide brand assets or templates to store in `assets/`, or documentation to store in `references/`.
+
+Added scripts must be tested by actually running them to ensure there are no bugs and that the output matches what is expected. If there are many similar scripts, only a representative sample needs to be tested to ensure confidence that they all work while balancing time to completion.
+
+Any example files and directories not needed for the skill should be deleted. The initialization script creates example files in `scripts/`, `references/`, and `assets/` to demonstrate structure, but most skills won't need all of them.
+
+#### Update SKILL.md
+
+**Writing Guidelines:** Always use imperative/infinitive form.
+
+##### Frontmatter
+
+Write the YAML frontmatter with `name` and `description`:
+
+- `name`: The skill name
+- `description`: This is the primary triggering mechanism for your skill, and helps Claude understand when to use the skill.
+ - Include both what the Skill does and specific triggers/contexts for when to use it.
+ - Include all "when to use" information here - Not in the body. The body is only loaded after triggering, so "When to Use This Skill" sections in the body are not helpful to Claude.
+ - Example description for a `docx` skill: "Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. Use when Claude needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks"
+
+Do not include any other fields in YAML frontmatter.
+
+##### Body
+
+Write instructions for using the skill and its bundled resources.
+
+### Step 5: Packaging a Skill
+
+Once development of the skill is complete, it must be packaged into a distributable .skill file that gets shared with the user. The packaging process automatically validates the skill first to ensure it meets all requirements:
+
+```bash
+scripts/package_skill.py
+```
+
+Optional output directory specification:
+
+```bash
+scripts/package_skill.py ./dist
+```
+
+The packaging script will:
+
+1. **Validate** the skill automatically, checking:
+
+ - YAML frontmatter format and required fields
+ - Skill naming conventions and directory structure
+ - Description completeness and quality
+ - File organization and resource references
+
+2. **Package** the skill if validation passes, creating a .skill file named after the skill (e.g., `my-skill.skill`) that includes all files and maintains the proper directory structure for distribution. The .skill file is a zip file with a .skill extension.
+
+If validation fails, the script will report the errors and exit without creating a package. Fix any validation errors and run the packaging command again.
+
+### Step 6: Iterate
+
+After testing the skill, users may request improvements. Often this happens right after using the skill, with fresh context of how the skill performed.
+
+**Iteration workflow:**
+
+1. Use the skill on real tasks
+2. Notice struggles or inefficiencies
+3. Identify how SKILL.md or bundled resources should be updated
+4. Implement changes and test again
diff --git a/inst/skills/skill-creator/references/output-patterns.md b/inst/skills/skill-creator/references/output-patterns.md
new file mode 100644
index 00000000..073ddda5
--- /dev/null
+++ b/inst/skills/skill-creator/references/output-patterns.md
@@ -0,0 +1,82 @@
+# Output Patterns
+
+Use these patterns when skills need to produce consistent, high-quality output.
+
+## Template Pattern
+
+Provide templates for output format. Match the level of strictness to your needs.
+
+**For strict requirements (like API responses or data formats):**
+
+```markdown
+## Report structure
+
+ALWAYS use this exact template structure:
+
+# [Analysis Title]
+
+## Executive summary
+[One-paragraph overview of key findings]
+
+## Key findings
+- Finding 1 with supporting data
+- Finding 2 with supporting data
+- Finding 3 with supporting data
+
+## Recommendations
+1. Specific actionable recommendation
+2. Specific actionable recommendation
+```
+
+**For flexible guidance (when adaptation is useful):**
+
+```markdown
+## Report structure
+
+Here is a sensible default format, but use your best judgment:
+
+# [Analysis Title]
+
+## Executive summary
+[Overview]
+
+## Key findings
+[Adapt sections based on what you discover]
+
+## Recommendations
+[Tailor to the specific context]
+
+Adjust sections as needed for the specific analysis type.
+```
+
+## Examples Pattern
+
+For skills where output quality depends on seeing examples, provide input/output pairs:
+
+```markdown
+## Commit message format
+
+Generate commit messages following these examples:
+
+**Example 1:**
+Input: Added user authentication with JWT tokens
+Output:
+```
+feat(auth): implement JWT-based authentication
+
+Add login endpoint and token validation middleware
+```
+
+**Example 2:**
+Input: Fixed bug where dates displayed incorrectly in reports
+Output:
+```
+fix(reports): correct date formatting in timezone conversion
+
+Use UTC timestamps consistently across report generation
+```
+
+Follow this style: type(scope): brief description, then detailed explanation.
+```
+
+Examples help Claude understand the desired style and level of detail more clearly than descriptions alone.
diff --git a/inst/skills/skill-creator/references/workflows.md b/inst/skills/skill-creator/references/workflows.md
new file mode 100644
index 00000000..a350c3cc
--- /dev/null
+++ b/inst/skills/skill-creator/references/workflows.md
@@ -0,0 +1,28 @@
+# Workflow Patterns
+
+## Sequential Workflows
+
+For complex tasks, break operations into clear, sequential steps. It is often helpful to give Claude an overview of the process towards the beginning of SKILL.md:
+
+```markdown
+Filling a PDF form involves these steps:
+
+1. Analyze the form (run analyze_form.py)
+2. Create field mapping (edit fields.json)
+3. Validate mapping (run validate_fields.py)
+4. Fill the form (run fill_form.py)
+5. Verify output (run verify_output.py)
+```
+
+## Conditional Workflows
+
+For tasks with branching logic, guide Claude through decision points:
+
+```markdown
+1. Determine the modification type:
+ **Creating new content?** → Follow "Creation workflow" below
+ **Editing existing content?** → Follow "Editing workflow" below
+
+2. Creation workflow: [steps]
+3. Editing workflow: [steps]
+```
\ No newline at end of file
diff --git a/inst/skills/skill-creator/scripts/init_skill.py b/inst/skills/skill-creator/scripts/init_skill.py
new file mode 100644
index 00000000..329ad4e5
--- /dev/null
+++ b/inst/skills/skill-creator/scripts/init_skill.py
@@ -0,0 +1,303 @@
+#!/usr/bin/env python3
+"""
+Skill Initializer - Creates a new skill from template
+
+Usage:
+ init_skill.py --path
+
+Examples:
+ init_skill.py my-new-skill --path skills/public
+ init_skill.py my-api-helper --path skills/private
+ init_skill.py custom-skill --path /custom/location
+"""
+
+import sys
+from pathlib import Path
+
+
+SKILL_TEMPLATE = """---
+name: {skill_name}
+description: [TODO: Complete and informative explanation of what the skill does and when to use it. Include WHEN to use this skill - specific scenarios, file types, or tasks that trigger it.]
+---
+
+# {skill_title}
+
+## Overview
+
+[TODO: 1-2 sentences explaining what this skill enables]
+
+## Structuring This Skill
+
+[TODO: Choose the structure that best fits this skill's purpose. Common patterns:
+
+**1. Workflow-Based** (best for sequential processes)
+- Works well when there are clear step-by-step procedures
+- Example: DOCX skill with "Workflow Decision Tree" → "Reading" → "Creating" → "Editing"
+- Structure: ## Overview → ## Workflow Decision Tree → ## Step 1 → ## Step 2...
+
+**2. Task-Based** (best for tool collections)
+- Works well when the skill offers different operations/capabilities
+- Example: PDF skill with "Quick Start" → "Merge PDFs" → "Split PDFs" → "Extract Text"
+- Structure: ## Overview → ## Quick Start → ## Task Category 1 → ## Task Category 2...
+
+**3. Reference/Guidelines** (best for standards or specifications)
+- Works well for brand guidelines, coding standards, or requirements
+- Example: Brand styling with "Brand Guidelines" → "Colors" → "Typography" → "Features"
+- Structure: ## Overview → ## Guidelines → ## Specifications → ## Usage...
+
+**4. Capabilities-Based** (best for integrated systems)
+- Works well when the skill provides multiple interrelated features
+- Example: Product Management with "Core Capabilities" → numbered capability list
+- Structure: ## Overview → ## Core Capabilities → ### 1. Feature → ### 2. Feature...
+
+Patterns can be mixed and matched as needed. Most skills combine patterns (e.g., start with task-based, add workflow for complex operations).
+
+Delete this entire "Structuring This Skill" section when done - it's just guidance.]
+
+## [TODO: Replace with the first main section based on chosen structure]
+
+[TODO: Add content here. See examples in existing skills:
+- Code samples for technical skills
+- Decision trees for complex workflows
+- Concrete examples with realistic user requests
+- References to scripts/templates/references as needed]
+
+## Resources
+
+This skill includes example resource directories that demonstrate how to organize different types of bundled resources:
+
+### scripts/
+Executable code (Python/Bash/etc.) that can be run directly to perform specific operations.
+
+**Examples from other skills:**
+- PDF skill: `fill_fillable_fields.py`, `extract_form_field_info.py` - utilities for PDF manipulation
+- DOCX skill: `document.py`, `utilities.py` - Python modules for document processing
+
+**Appropriate for:** Python scripts, shell scripts, or any executable code that performs automation, data processing, or specific operations.
+
+**Note:** Scripts may be executed without loading into context, but can still be read by Claude for patching or environment adjustments.
+
+### references/
+Documentation and reference material intended to be loaded into context to inform Claude's process and thinking.
+
+**Examples from other skills:**
+- Product management: `communication.md`, `context_building.md` - detailed workflow guides
+- BigQuery: API reference documentation and query examples
+- Finance: Schema documentation, company policies
+
+**Appropriate for:** In-depth documentation, API references, database schemas, comprehensive guides, or any detailed information that Claude should reference while working.
+
+### assets/
+Files not intended to be loaded into context, but rather used within the output Claude produces.
+
+**Examples from other skills:**
+- Brand styling: PowerPoint template files (.pptx), logo files
+- Frontend builder: HTML/React boilerplate project directories
+- Typography: Font files (.ttf, .woff2)
+
+**Appropriate for:** Templates, boilerplate code, document templates, images, icons, fonts, or any files meant to be copied or used in the final output.
+
+---
+
+**Any unneeded directories can be deleted.** Not every skill requires all three types of resources.
+"""
+
+EXAMPLE_SCRIPT = '''#!/usr/bin/env python3
+"""
+Example helper script for {skill_name}
+
+This is a placeholder script that can be executed directly.
+Replace with actual implementation or delete if not needed.
+
+Example real scripts from other skills:
+- pdf/scripts/fill_fillable_fields.py - Fills PDF form fields
+- pdf/scripts/convert_pdf_to_images.py - Converts PDF pages to images
+"""
+
+def main():
+ print("This is an example script for {skill_name}")
+ # TODO: Add actual script logic here
+ # This could be data processing, file conversion, API calls, etc.
+
+if __name__ == "__main__":
+ main()
+'''
+
+EXAMPLE_REFERENCE = """# Reference Documentation for {skill_title}
+
+This is a placeholder for detailed reference documentation.
+Replace with actual reference content or delete if not needed.
+
+Example real reference docs from other skills:
+- product-management/references/communication.md - Comprehensive guide for status updates
+- product-management/references/context_building.md - Deep-dive on gathering context
+- bigquery/references/ - API references and query examples
+
+## When Reference Docs Are Useful
+
+Reference docs are ideal for:
+- Comprehensive API documentation
+- Detailed workflow guides
+- Complex multi-step processes
+- Information too lengthy for main SKILL.md
+- Content that's only needed for specific use cases
+
+## Structure Suggestions
+
+### API Reference Example
+- Overview
+- Authentication
+- Endpoints with examples
+- Error codes
+- Rate limits
+
+### Workflow Guide Example
+- Prerequisites
+- Step-by-step instructions
+- Common patterns
+- Troubleshooting
+- Best practices
+"""
+
+EXAMPLE_ASSET = """# Example Asset File
+
+This placeholder represents where asset files would be stored.
+Replace with actual asset files (templates, images, fonts, etc.) or delete if not needed.
+
+Asset files are NOT intended to be loaded into context, but rather used within
+the output Claude produces.
+
+Example asset files from other skills:
+- Brand guidelines: logo.png, slides_template.pptx
+- Frontend builder: hello-world/ directory with HTML/React boilerplate
+- Typography: custom-font.ttf, font-family.woff2
+- Data: sample_data.csv, test_dataset.json
+
+## Common Asset Types
+
+- Templates: .pptx, .docx, boilerplate directories
+- Images: .png, .jpg, .svg, .gif
+- Fonts: .ttf, .otf, .woff, .woff2
+- Boilerplate code: Project directories, starter files
+- Icons: .ico, .svg
+- Data files: .csv, .json, .xml, .yaml
+
+Note: This is a text placeholder. Actual assets can be any file type.
+"""
+
+
+def title_case_skill_name(skill_name):
+ """Convert hyphenated skill name to Title Case for display."""
+ return ' '.join(word.capitalize() for word in skill_name.split('-'))
+
+
+def init_skill(skill_name, path):
+ """
+ Initialize a new skill directory with template SKILL.md.
+
+ Args:
+ skill_name: Name of the skill
+ path: Path where the skill directory should be created
+
+ Returns:
+ Path to created skill directory, or None if error
+ """
+ # Determine skill directory path
+ skill_dir = Path(path).resolve() / skill_name
+
+ # Check if directory already exists
+ if skill_dir.exists():
+ print(f"❌ Error: Skill directory already exists: {skill_dir}")
+ return None
+
+ # Create skill directory
+ try:
+ skill_dir.mkdir(parents=True, exist_ok=False)
+ print(f"✅ Created skill directory: {skill_dir}")
+ except Exception as e:
+ print(f"❌ Error creating directory: {e}")
+ return None
+
+ # Create SKILL.md from template
+ skill_title = title_case_skill_name(skill_name)
+ skill_content = SKILL_TEMPLATE.format(
+ skill_name=skill_name,
+ skill_title=skill_title
+ )
+
+ skill_md_path = skill_dir / 'SKILL.md'
+ try:
+ skill_md_path.write_text(skill_content)
+ print("✅ Created SKILL.md")
+ except Exception as e:
+ print(f"❌ Error creating SKILL.md: {e}")
+ return None
+
+ # Create resource directories with example files
+ try:
+ # Create scripts/ directory with example script
+ scripts_dir = skill_dir / 'scripts'
+ scripts_dir.mkdir(exist_ok=True)
+ example_script = scripts_dir / 'example.py'
+ example_script.write_text(EXAMPLE_SCRIPT.format(skill_name=skill_name))
+ example_script.chmod(0o755)
+ print("✅ Created scripts/example.py")
+
+ # Create references/ directory with example reference doc
+ references_dir = skill_dir / 'references'
+ references_dir.mkdir(exist_ok=True)
+ example_reference = references_dir / 'api_reference.md'
+ example_reference.write_text(EXAMPLE_REFERENCE.format(skill_title=skill_title))
+ print("✅ Created references/api_reference.md")
+
+ # Create assets/ directory with example asset placeholder
+ assets_dir = skill_dir / 'assets'
+ assets_dir.mkdir(exist_ok=True)
+ example_asset = assets_dir / 'example_asset.txt'
+ example_asset.write_text(EXAMPLE_ASSET)
+ print("✅ Created assets/example_asset.txt")
+ except Exception as e:
+ print(f"❌ Error creating resource directories: {e}")
+ return None
+
+ # Print next steps
+ print(f"\n✅ Skill '{skill_name}' initialized successfully at {skill_dir}")
+ print("\nNext steps:")
+ print("1. Edit SKILL.md to complete the TODO items and update the description")
+ print("2. Customize or delete the example files in scripts/, references/, and assets/")
+ print("3. Run the validator when ready to check the skill structure")
+
+ return skill_dir
+
+
+def main():
+ if len(sys.argv) < 4 or sys.argv[2] != '--path':
+ print("Usage: init_skill.py --path ")
+ print("\nSkill name requirements:")
+ print(" - Hyphen-case identifier (e.g., 'data-analyzer')")
+ print(" - Lowercase letters, digits, and hyphens only")
+ print(" - Max 40 characters")
+ print(" - Must match directory name exactly")
+ print("\nExamples:")
+ print(" init_skill.py my-new-skill --path skills/public")
+ print(" init_skill.py my-api-helper --path skills/private")
+ print(" init_skill.py custom-skill --path /custom/location")
+ sys.exit(1)
+
+ skill_name = sys.argv[1]
+ path = sys.argv[3]
+
+ print(f"🚀 Initializing skill: {skill_name}")
+ print(f" Location: {path}")
+ print()
+
+ result = init_skill(skill_name, path)
+
+ if result:
+ sys.exit(0)
+ else:
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/inst/skills/skill-creator/scripts/package_skill.py b/inst/skills/skill-creator/scripts/package_skill.py
new file mode 100644
index 00000000..5cd36cb1
--- /dev/null
+++ b/inst/skills/skill-creator/scripts/package_skill.py
@@ -0,0 +1,110 @@
+#!/usr/bin/env python3
+"""
+Skill Packager - Creates a distributable .skill file of a skill folder
+
+Usage:
+ python utils/package_skill.py [output-directory]
+
+Example:
+ python utils/package_skill.py skills/public/my-skill
+ python utils/package_skill.py skills/public/my-skill ./dist
+"""
+
+import sys
+import zipfile
+from pathlib import Path
+from quick_validate import validate_skill
+
+
+def package_skill(skill_path, output_dir=None):
+ """
+ Package a skill folder into a .skill file.
+
+ Args:
+ skill_path: Path to the skill folder
+ output_dir: Optional output directory for the .skill file (defaults to current directory)
+
+ Returns:
+ Path to the created .skill file, or None if error
+ """
+ skill_path = Path(skill_path).resolve()
+
+ # Validate skill folder exists
+ if not skill_path.exists():
+ print(f"❌ Error: Skill folder not found: {skill_path}")
+ return None
+
+ if not skill_path.is_dir():
+ print(f"❌ Error: Path is not a directory: {skill_path}")
+ return None
+
+ # Validate SKILL.md exists
+ skill_md = skill_path / "SKILL.md"
+ if not skill_md.exists():
+ print(f"❌ Error: SKILL.md not found in {skill_path}")
+ return None
+
+ # Run validation before packaging
+ print("🔍 Validating skill...")
+ valid, message = validate_skill(skill_path)
+ if not valid:
+ print(f"❌ Validation failed: {message}")
+ print(" Please fix the validation errors before packaging.")
+ return None
+ print(f"✅ {message}\n")
+
+ # Determine output location
+ skill_name = skill_path.name
+ if output_dir:
+ output_path = Path(output_dir).resolve()
+ output_path.mkdir(parents=True, exist_ok=True)
+ else:
+ output_path = Path.cwd()
+
+ skill_filename = output_path / f"{skill_name}.skill"
+
+ # Create the .skill file (zip format)
+ try:
+ with zipfile.ZipFile(skill_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
+ # Walk through the skill directory
+ for file_path in skill_path.rglob('*'):
+ if file_path.is_file():
+ # Calculate the relative path within the zip
+ arcname = file_path.relative_to(skill_path.parent)
+ zipf.write(file_path, arcname)
+ print(f" Added: {arcname}")
+
+ print(f"\n✅ Successfully packaged skill to: {skill_filename}")
+ return skill_filename
+
+ except Exception as e:
+ print(f"❌ Error creating .skill file: {e}")
+ return None
+
+
+def main():
+ if len(sys.argv) < 2:
+ print("Usage: python utils/package_skill.py [output-directory]")
+ print("\nExample:")
+ print(" python utils/package_skill.py skills/public/my-skill")
+ print(" python utils/package_skill.py skills/public/my-skill ./dist")
+ sys.exit(1)
+
+ skill_path = sys.argv[1]
+ output_dir = sys.argv[2] if len(sys.argv) > 2 else None
+
+ print(f"📦 Packaging skill: {skill_path}")
+ if output_dir:
+ print(f" Output directory: {output_dir}")
+ print()
+
+ result = package_skill(skill_path, output_dir)
+
+ if result:
+ sys.exit(0)
+ else:
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/inst/skills/skill-creator/scripts/quick_validate.py b/inst/skills/skill-creator/scripts/quick_validate.py
new file mode 100644
index 00000000..d9fbeb75
--- /dev/null
+++ b/inst/skills/skill-creator/scripts/quick_validate.py
@@ -0,0 +1,95 @@
+#!/usr/bin/env python3
+"""
+Quick validation script for skills - minimal version
+"""
+
+import sys
+import os
+import re
+import yaml
+from pathlib import Path
+
+def validate_skill(skill_path):
+ """Basic validation of a skill"""
+ skill_path = Path(skill_path)
+
+ # Check SKILL.md exists
+ skill_md = skill_path / 'SKILL.md'
+ if not skill_md.exists():
+ return False, "SKILL.md not found"
+
+ # Read and validate frontmatter
+ content = skill_md.read_text()
+ if not content.startswith('---'):
+ return False, "No YAML frontmatter found"
+
+ # Extract frontmatter
+ match = re.match(r'^---\n(.*?)\n---', content, re.DOTALL)
+ if not match:
+ return False, "Invalid frontmatter format"
+
+ frontmatter_text = match.group(1)
+
+ # Parse YAML frontmatter
+ try:
+ frontmatter = yaml.safe_load(frontmatter_text)
+ if not isinstance(frontmatter, dict):
+ return False, "Frontmatter must be a YAML dictionary"
+ except yaml.YAMLError as e:
+ return False, f"Invalid YAML in frontmatter: {e}"
+
+ # Define allowed properties
+ ALLOWED_PROPERTIES = {'name', 'description', 'license', 'allowed-tools', 'metadata'}
+
+ # Check for unexpected properties (excluding nested keys under metadata)
+ unexpected_keys = set(frontmatter.keys()) - ALLOWED_PROPERTIES
+ if unexpected_keys:
+ return False, (
+ f"Unexpected key(s) in SKILL.md frontmatter: {', '.join(sorted(unexpected_keys))}. "
+ f"Allowed properties are: {', '.join(sorted(ALLOWED_PROPERTIES))}"
+ )
+
+ # Check required fields
+ if 'name' not in frontmatter:
+ return False, "Missing 'name' in frontmatter"
+ if 'description' not in frontmatter:
+ return False, "Missing 'description' in frontmatter"
+
+ # Extract name for validation
+ name = frontmatter.get('name', '')
+ if not isinstance(name, str):
+ return False, f"Name must be a string, got {type(name).__name__}"
+ name = name.strip()
+ if name:
+ # Check naming convention (hyphen-case: lowercase with hyphens)
+ if not re.match(r'^[a-z0-9-]+$', name):
+ return False, f"Name '{name}' should be hyphen-case (lowercase letters, digits, and hyphens only)"
+ if name.startswith('-') or name.endswith('-') or '--' in name:
+ return False, f"Name '{name}' cannot start/end with hyphen or contain consecutive hyphens"
+ # Check name length (max 64 characters per spec)
+ if len(name) > 64:
+ return False, f"Name is too long ({len(name)} characters). Maximum is 64 characters."
+
+ # Extract and validate description
+ description = frontmatter.get('description', '')
+ if not isinstance(description, str):
+ return False, f"Description must be a string, got {type(description).__name__}"
+ description = description.strip()
+ if description:
+ # Check for angle brackets
+ if '<' in description or '>' in description:
+ return False, "Description cannot contain angle brackets (< or >)"
+ # Check description length (max 1024 characters per spec)
+ if len(description) > 1024:
+ return False, f"Description is too long ({len(description)} characters). Maximum is 1024 characters."
+
+ return True, "Skill is valid!"
+
+if __name__ == "__main__":
+ if len(sys.argv) != 2:
+ print("Usage: python quick_validate.py ")
+ sys.exit(1)
+
+ valid, message = validate_skill(sys.argv[1])
+ print(message)
+ sys.exit(0 if valid else 1)
\ No newline at end of file
diff --git a/man/btw_agent_tool.Rd b/man/btw_agent_tool.Rd
index 0e3aa89b..e2b3c600 100644
--- a/man/btw_agent_tool.Rd
+++ b/man/btw_agent_tool.Rd
@@ -65,7 +65,7 @@ from other icon packages. Supported packages:\tabular{lll}{
bsicons \tab \code{bsicons::house} \tab \code{\link[bsicons:bs_icon]{bsicons::bs_icon()}} \cr
phosphoricons \tab \code{phosphoricons::house} \tab \code{\link[phosphoricons:ph]{phosphoricons::ph()}} \cr
rheroicons \tab \code{rheroicons::home} \tab \code{\link[rheroicons:rheroicon]{rheroicons::rheroicon()}} \cr
- tabler \tab \code{tabler::home} \tab \code{\link[tabler:icon]{tabler::icon()}} \cr
+ tabler \tab \code{tabler::home} \tab \code{\link[tabler:tabler-components]{tabler::icon()}} \cr
shiny \tab \code{shiny::home} \tab \code{\link[shiny:icon]{shiny::icon()}} \cr
}
diff --git a/man/btw_skill_install_github.Rd b/man/btw_skill_install_github.Rd
new file mode 100644
index 00000000..7b246b5f
--- /dev/null
+++ b/man/btw_skill_install_github.Rd
@@ -0,0 +1,54 @@
+% Generated by roxygen2: do not edit by hand
+% Please edit documentation in R/tool-skills.R
+\name{btw_skill_install_github}
+\alias{btw_skill_install_github}
+\title{Install a skill from GitHub}
+\usage{
+btw_skill_install_github(
+ repo,
+ skill = NULL,
+ scope = "project",
+ overwrite = NULL
+)
+}
+\arguments{
+\item{repo}{GitHub repository in \code{"owner/repo"} format. Optionally include
+a Git reference (branch, tag, or SHA) as \code{"owner/repo@ref"}, following the
+convention used by \code{\link[pak:pak]{pak::pak()}} and \code{\link[remotes:install_github]{remotes::install_github()}}. Defaults to
+\code{"HEAD"} when no ref is specified.}
+
+\item{skill}{Optional skill name. If \code{NULL} and the repository contains
+multiple skills, an interactive picker is shown (or an error in
+non-interactive sessions).}
+
+\item{scope}{Where to install the skill. One of:
+\itemize{
+\item \code{"project"} (default): Installs to a project-level skills directory,
+chosen from \verb{.btw/skills/} or \verb{.agents/skills/}
+in that order. If one already exists, it is used; otherwise
+\verb{.btw/skills/} is created.
+\item \code{"user"}: Installs to the user-level skills directory
+(\code{tools::R_user_dir("btw", "config")/skills}).
+\item A directory path: Installs to a custom directory, e.g.
+\code{scope = ".openhands/skills"}. Use \code{I("project")} or \code{I("user")}
+if you need a literal directory with those names.
+}}
+
+\item{overwrite}{Whether to overwrite an existing skill with the same name.
+If \code{NULL} (default), prompts interactively when a conflict exists; in
+non-interactive sessions defaults to \code{FALSE}, which errors. Set to \code{TRUE}
+to always overwrite, or \code{FALSE} to always error on conflict.}
+}
+\value{
+The path to the installed skill directory, invisibly.
+}
+\description{
+Download and install a skill from a GitHub repository. The repository
+should contain one or more skill directories, each with a \code{SKILL.md} file.
+}
+\seealso{
+Other skills:
+\code{\link{btw_skill_install_package}()},
+\code{\link{btw_tool_skill}()}
+}
+\concept{skills}
diff --git a/man/btw_skill_install_package.Rd b/man/btw_skill_install_package.Rd
new file mode 100644
index 00000000..f564d4b8
--- /dev/null
+++ b/man/btw_skill_install_package.Rd
@@ -0,0 +1,52 @@
+% Generated by roxygen2: do not edit by hand
+% Please edit documentation in R/tool-skills.R
+\name{btw_skill_install_package}
+\alias{btw_skill_install_package}
+\title{Install a skill from an R package}
+\usage{
+btw_skill_install_package(
+ package,
+ skill = NULL,
+ scope = "project",
+ overwrite = NULL
+)
+}
+\arguments{
+\item{package}{Name of an installed R package that bundles skills.}
+
+\item{skill}{Optional skill name. If \code{NULL} and the package contains
+multiple skills, an interactive picker is shown (or an error in
+non-interactive sessions).}
+
+\item{scope}{Where to install the skill. One of:
+\itemize{
+\item \code{"project"} (default): Installs to a project-level skills directory,
+chosen from \verb{.btw/skills/} or \verb{.agents/skills/}
+in that order. If one already exists, it is used; otherwise
+\verb{.btw/skills/} is created.
+\item \code{"user"}: Installs to the user-level skills directory
+(\code{tools::R_user_dir("btw", "config")/skills}).
+\item A directory path: Installs to a custom directory, e.g.
+\code{scope = ".openhands/skills"}. Use \code{I("project")} or \code{I("user")}
+if you need a literal directory with those names.
+}}
+
+\item{overwrite}{Whether to overwrite an existing skill with the same name.
+If \code{NULL} (default), prompts interactively when a conflict exists; in
+non-interactive sessions defaults to \code{FALSE}, which errors. Set to \code{TRUE}
+to always overwrite, or \code{FALSE} to always error on conflict.}
+}
+\value{
+The path to the installed skill directory, invisibly.
+}
+\description{
+Install a skill bundled in an R package. Packages can bundle skills in
+their \verb{inst/skills/} directory, where each subdirectory containing a
+\code{SKILL.md} file is a skill.
+}
+\seealso{
+Other skills:
+\code{\link{btw_skill_install_github}()},
+\code{\link{btw_tool_skill}()}
+}
+\concept{skills}
diff --git a/man/btw_task.Rd b/man/btw_task.Rd
index a173d23d..611aeba0 100644
--- a/man/btw_task.Rd
+++ b/man/btw_task.Rd
@@ -107,6 +107,7 @@ btw_task(
\seealso{
Other task and agent functions:
\code{\link{btw_task_create_btw_md}()},
-\code{\link{btw_task_create_readme}()}
+\code{\link{btw_task_create_readme}()},
+\code{\link{btw_task_create_skill}()}
}
\concept{task and agent functions}
diff --git a/man/btw_task_create_btw_md.Rd b/man/btw_task_create_btw_md.Rd
index e9ef2c90..b456b7c0 100644
--- a/man/btw_task_create_btw_md.Rd
+++ b/man/btw_task_create_btw_md.Rd
@@ -60,6 +60,7 @@ withr::with_envvar(list(ANTHROPIC_API_KEY = "example"), {
\seealso{
Other task and agent functions:
\code{\link{btw_task}()},
-\code{\link{btw_task_create_readme}()}
+\code{\link{btw_task_create_readme}()},
+\code{\link{btw_task_create_skill}()}
}
\concept{task and agent functions}
diff --git a/man/btw_task_create_readme.Rd b/man/btw_task_create_readme.Rd
index 696afdb8..81139151 100644
--- a/man/btw_task_create_readme.Rd
+++ b/man/btw_task_create_readme.Rd
@@ -59,6 +59,7 @@ withr::with_envvar(list(ANTHROPIC_API_KEY = "example"), {
\seealso{
Other task and agent functions:
\code{\link{btw_task}()},
-\code{\link{btw_task_create_btw_md}()}
+\code{\link{btw_task_create_btw_md}()},
+\code{\link{btw_task_create_skill}()}
}
\concept{task and agent functions}
diff --git a/man/btw_task_create_skill.Rd b/man/btw_task_create_skill.Rd
new file mode 100644
index 00000000..2d284513
--- /dev/null
+++ b/man/btw_task_create_skill.Rd
@@ -0,0 +1,72 @@
+% Generated by roxygen2: do not edit by hand
+% Please edit documentation in R/task_create_skill.R
+\name{btw_task_create_skill}
+\alias{btw_task_create_skill}
+\title{Task: Create a Skill}
+\usage{
+btw_task_create_skill(
+ ...,
+ name = NULL,
+ client = NULL,
+ mode = c("app", "console", "client", "tool"),
+ tools = "docs"
+)
+}
+\arguments{
+\item{...}{Additional context to provide to the AI. This can be any text or
+R objects that can be converted to text using \code{\link[=btw]{btw()}}.}
+
+\item{name}{Optional skill name. If provided, the AI will skip the naming
+step and use this name directly.}
+
+\item{client}{An \link[ellmer:Chat]{ellmer::Chat} client, or a \code{provider/model} string to be
+passed to \code{\link[ellmer:chat-any]{ellmer::chat()}} to create a chat client, or an alias to a client
+setting in your \code{btw.md} file (see "Multiple Providers" section). Defaults
+to \code{\link[ellmer:chat_anthropic]{ellmer::chat_anthropic()}}. You can use the \code{btw.client} option to set a
+default client for new \code{btw_client()} calls, or use a \code{btw.md} project file
+for default chat client settings, like provider and model. We check the
+\code{client} argument, then the \code{btw.client} R option, and finally the \code{btw.md}
+project file (falling back to user-level \code{btw.md} if needed), using only
+the client definition from the first of these that is available.}
+
+\item{mode}{The mode to run the task in, which affects what is returned from
+this function. \code{"app"} and \code{"console"} modes launch interactive sessions,
+while \code{"client"} and \code{"tool"} modes return objects for programmatic use.}
+
+\item{tools}{Optional list or character vector of tools to allow the task to
+use when creating the skill. By default documentation tools are included to
+allow the task to help create package-based skills. You can include
+additional tools as needed.
+
+Because the task requires file tools to create skills with resources, tools
+for listing, reading and writing files are always included.}
+}
+\value{
+When \code{mode} is \code{"app"} or \code{"console"}, this function launches an
+interactive session in the browser or the R console, respectively. The
+ellmer chat object with the conversation history is returned invisibly
+when the session ends.
+
+When \code{mode} is \code{"client"}, this function returns the configured ellmer
+chat client object. When \code{mode} is \code{"tool"}, this function returns an
+ellmer tool object that can be used in other chat instances.
+}
+\description{
+Create a new skill for your project using interactive guidance. If launched
+in app or console mode, this task will start an interactive chat session to
+guide you through the process of creating a skill that extends Claude's
+capabilities with specialized knowledge, workflows, or tool integrations.
+}
+\examples{
+withr::with_envvar(list(ANTHROPIC_API_KEY = "example"), {
+ btw_task_create_skill(mode = "tool", client = "anthropic")
+})
+
+}
+\seealso{
+Other task and agent functions:
+\code{\link{btw_task}()},
+\code{\link{btw_task_create_btw_md}()},
+\code{\link{btw_task_create_readme}()}
+}
+\concept{task and agent functions}
diff --git a/man/btw_tool_skill.Rd b/man/btw_tool_skill.Rd
new file mode 100644
index 00000000..fb4ff96b
--- /dev/null
+++ b/man/btw_tool_skill.Rd
@@ -0,0 +1,33 @@
+% Generated by roxygen2: do not edit by hand
+% Please edit documentation in R/tool-skills.R
+\name{btw_tool_skill}
+\alias{btw_tool_skill}
+\title{Tool: Load a skill}
+\usage{
+btw_tool_skill(name, `_intent` = "")
+}
+\arguments{
+\item{name}{The name of the skill to load.}
+
+\item{_intent}{An optional string describing the intent of the tool use.
+When the tool is used by an LLM, the model will use this argument to
+explain why it called the tool.}
+}
+\value{
+A \code{btw_tool_result} containing the skill instructions and a listing
+of bundled resources with their paths.
+}
+\description{
+Load a skill's specialized instructions and list its bundled resources.
+
+Skills are modular capabilities that extend Claude's functionality with
+specialized knowledge, workflows, and tools. Each skill is a directory
+containing a \code{SKILL.md} file with instructions and optional bundled
+resources (scripts, references, assets).
+}
+\seealso{
+Other skills:
+\code{\link{btw_skill_install_github}()},
+\code{\link{btw_skill_install_package}()}
+}
+\concept{skills}
diff --git a/man/btw_tools.Rd b/man/btw_tools.Rd
index 06b6361b..221b890b 100644
--- a/man/btw_tools.Rd
+++ b/man/btw_tools.Rd
@@ -131,6 +131,13 @@ this function have access to the tools:
}
+\subsection{Group: skills}{\tabular{ll}{
+ Name \tab Description \cr
+ \code{\link[=btw_tool_skill]{btw_tool_skill()}} \tab Load a skill's specialized instructions and list its bundled resources. \cr
+}
+
+}
+
\subsection{Group: web}{\tabular{ll}{
Name \tab Description \cr
\code{\link[=btw_tool_web_read_url]{btw_tool_web_read_url()}} \tab Read a web page and convert it to Markdown format. \cr
diff --git a/man/mcp.Rd b/man/mcp.Rd
index a37e51f0..fc2eb915 100644
--- a/man/mcp.Rd
+++ b/man/mcp.Rd
@@ -6,7 +6,7 @@
\alias{btw_mcp_session}
\title{Start a Model Context Protocol server with btw tools}
\usage{
-btw_mcp_server(tools = btw_tools())
+btw_mcp_server(tools = btw_mcp_tools())
btw_mcp_session()
}
diff --git a/tests/testthat/_snaps/tool_skills.md b/tests/testthat/_snaps/tool_skills.md
new file mode 100644
index 00000000..a3c47034
--- /dev/null
+++ b/tests/testthat/_snaps/tool_skills.md
@@ -0,0 +1,29 @@
+# btw_skills_system_prompt() works
+
+ Code
+ cat(btw_skills_system_prompt())
+ Output
+ ## Skills
+
+ You have access to specialized skills that provide detailed guidance for specific tasks. Skills are loaded on-demand to provide domain-specific expertise without consuming context until needed.
+
+ ### Using Skills
+
+ 1. **Check available skills**: Review the `` listing below
+ 2. **Load when relevant**: When you recognize that a task matches a skill's description, call `btw_tool_skill(name)` to load the full skill instructions
+ 3. **Don't reload**: If a skill has already been loaded in this conversation, follow its instructions directly without loading it again
+ 4. **Access resources**: After loading, use file read tools to access references
+
+ Skills may include bundled resources:
+ - **Scripts**: Code bundled with the skill. Scripts are not directly executable by btw; read them for reference or adapt their logic into R code for use with the R code execution tool.
+ - **References**: Additional documentation to consult as needed
+ - **Assets**: Templates and files for use in outputs
+
+
+
+ skill-creator
+ Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends Claude's capabilities with specialized knowledge, workflows, or tool integrations.
+ SKILL_PATH
+
+
+
diff --git a/tests/testthat/helpers-skills.R b/tests/testthat/helpers-skills.R
new file mode 100644
index 00000000..68d5de34
--- /dev/null
+++ b/tests/testthat/helpers-skills.R
@@ -0,0 +1,35 @@
+# Helper to create a temp skill directory with valid SKILL.md
+create_temp_skill <- function(
+ name = "test-skill",
+ description = "A test skill for unit testing.",
+ extra_frontmatter = list(),
+ body = "\n# Test Skill\n\nInstructions here.\n",
+ dir = NULL
+) {
+ if (is.null(dir)) {
+ dir <- withr::local_tempdir(.local_envir = parent.frame())
+ }
+
+ skill_dir <- file.path(dir, name)
+ dir.create(skill_dir, recursive = TRUE, showWarnings = FALSE)
+
+ skill <- list(
+ data = list2(
+ name = name,
+ description = description,
+ !!!extra_frontmatter
+ ),
+ body = body
+ )
+
+ frontmatter::write_front_matter(skill, file.path(skill_dir, "SKILL.md"))
+ skill_dir
+}
+
+# Helper to mock skill directories for discovery
+local_skill_dirs <- function(dirs, .env = parent.frame()) {
+ local_mocked_bindings(
+ btw_skill_directories = function() dirs,
+ .env = .env
+ )
+}
diff --git a/tests/testthat/test-btw_client.R b/tests/testthat/test-btw_client.R
index 9e3d7697..bfbd62cc 100644
--- a/tests/testthat/test-btw_client.R
+++ b/tests/testthat/test-btw_client.R
@@ -1,4 +1,5 @@
local_enable_tools()
+local_mocked_bindings(btw_skills_system_prompt = function(...) "")
local_sessioninfo_quarto_version()
withr::local_options(btw.client.quiet = TRUE)
@@ -1079,3 +1080,36 @@ describe("btw_client() with multiple clients", {
expect_s3_class(chat$get_provider(), "ellmer::ProviderAnthropic")
})
})
+
+# warn_skills_without_read_file() -----------------------------------------
+
+test_that("warn_skills_without_read_file() warns when skills present without read file", {
+ tools <- list(
+ btw_tool_skill = "placeholder",
+ btw_tool_docs_help_page = "placeholder"
+ )
+ expect_warning(
+ warn_skills_without_read_file(tools),
+ "btw_tool_files_read"
+ )
+})
+
+test_that("warn_skills_without_read_file() is silent when both skills and read file present", {
+ tools <- list(
+ btw_tool_skill = "placeholder",
+ btw_tool_files_read = "placeholder"
+ )
+ expect_no_warning(warn_skills_without_read_file(tools))
+})
+
+test_that("warn_skills_without_read_file() is silent when skills not present", {
+ tools <- list(
+ btw_tool_docs_help_page = "placeholder",
+ btw_tool_files_read = "placeholder"
+ )
+ expect_no_warning(warn_skills_without_read_file(tools))
+})
+
+test_that("warn_skills_without_read_file() is silent when no tools", {
+ expect_no_warning(warn_skills_without_read_file(list()))
+})
diff --git a/tests/testthat/test-mcp.R b/tests/testthat/test-mcp.R
index b26d6d50..2b14b185 100644
--- a/tests/testthat/test-mcp.R
+++ b/tests/testthat/test-mcp.R
@@ -11,3 +11,10 @@ test_that("btw_mcp_server errors informatively with bad `tools`", {
btw_mcp_server(tools = "bop")
)
})
+
+test_that("btw_mcp_tools() excludes skills group by default", {
+ local_enable_tools()
+ tools <- btw_mcp_tools()
+ tool_names <- vapply(tools, function(t) t@name, character(1))
+ expect_false("btw_tool_skill" %in% tool_names)
+})
diff --git a/tests/testthat/test-tool_skills.R b/tests/testthat/test-tool_skills.R
new file mode 100644
index 00000000..b526b93f
--- /dev/null
+++ b/tests/testthat/test-tool_skills.R
@@ -0,0 +1,1005 @@
+# Validation ---------------------------------------------------------------
+
+test_that("validate_skill() passes for valid skill", {
+ skill_dir <- create_temp_skill()
+ result <- validate_skill(skill_dir)
+ expect_true(result$valid)
+ expect_length(result$issues, 0)
+})
+
+test_that("validate_skill() fails when SKILL.md is missing", {
+ dir <- withr::local_tempdir()
+ result <- validate_skill(dir)
+ expect_false(result$valid)
+ expect_match(result$issues, "SKILL.md not found")
+})
+
+test_that("validate_skill() fails for missing name field", {
+ dir <- withr::local_tempdir()
+ skill_dir <- file.path(dir, "test-skill")
+ dir.create(skill_dir)
+ writeLines(
+ "---\ndescription: A skill.\n---\nBody.",
+ file.path(skill_dir, "SKILL.md")
+ )
+ result <- validate_skill(skill_dir)
+ expect_false(result$valid)
+ expect_match(result$issues, "Missing or empty 'name'", all = FALSE)
+})
+
+test_that("validate_skill() fails for missing description field", {
+ dir <- withr::local_tempdir()
+ skill_dir <- file.path(dir, "test-skill")
+ dir.create(skill_dir)
+ writeLines(
+ "---\nname: test-skill\n---\nBody.",
+ file.path(skill_dir, "SKILL.md")
+ )
+ result <- validate_skill(skill_dir)
+ expect_false(result$valid)
+ expect_match(result$issues, "Missing or empty 'description'", all = FALSE)
+})
+
+test_that("validate_skill() warns for name with uppercase", {
+ skill_dir <- create_temp_skill(name = "test-skill")
+ # Manually override the name in SKILL.md to have uppercase
+ writeLines(
+ "---\nname: Test-Skill\ndescription: A test.\n---\nBody.",
+ file.path(skill_dir, "SKILL.md")
+ )
+ result <- validate_skill(skill_dir)
+ expect_true(result$valid)
+ expect_match(result$warnings, "lowercase letters", all = FALSE)
+})
+
+test_that("validate_skill() warns for name starting with hyphen", {
+ dir <- withr::local_tempdir()
+ skill_dir <- file.path(dir, "-bad-name")
+ dir.create(skill_dir)
+ writeLines(
+ "---\nname: -bad-name\ndescription: A test.\n---\nBody.",
+ file.path(skill_dir, "SKILL.md")
+ )
+ result <- validate_skill(skill_dir)
+ expect_true(result$valid)
+ expect_match(
+ result$warnings,
+ "must not start or end with a hyphen",
+ all = FALSE
+ )
+})
+
+test_that("validate_skill() warns for consecutive hyphens", {
+ dir <- withr::local_tempdir()
+ skill_dir <- file.path(dir, "bad--name")
+ dir.create(skill_dir)
+ writeLines(
+ "---\nname: bad--name\ndescription: A test.\n---\nBody.",
+ file.path(skill_dir, "SKILL.md")
+ )
+ result <- validate_skill(skill_dir)
+ expect_true(result$valid)
+ expect_match(result$warnings, "consecutive hyphens", all = FALSE)
+})
+
+test_that("validate_skill() warns for name exceeding 64 characters", {
+ long_name <- paste(rep("a", 65), collapse = "")
+ dir <- withr::local_tempdir()
+ skill_dir <- file.path(dir, long_name)
+ dir.create(skill_dir)
+ writeLines(
+ paste0("---\nname: ", long_name, "\ndescription: A test.\n---\nBody."),
+ file.path(skill_dir, "SKILL.md")
+ )
+ result <- validate_skill(skill_dir)
+ expect_true(result$valid)
+ expect_match(result$warnings, "too long", all = FALSE)
+})
+
+test_that("validate_skill() warns when name doesn't match directory", {
+ skill_dir <- create_temp_skill(name = "test-skill")
+ writeLines(
+ "---\nname: other-name\ndescription: A test.\n---\nBody.",
+ file.path(skill_dir, "SKILL.md")
+ )
+ result <- validate_skill(skill_dir)
+ expect_true(result$valid)
+ expect_match(result$warnings, "does not match directory name", all = FALSE)
+})
+
+test_that("validate_skill() warns for description exceeding 1024 characters", {
+ long_desc <- paste(rep("a", 1025), collapse = "")
+ skill_dir <- create_temp_skill(description = long_desc)
+ result <- validate_skill(skill_dir)
+ expect_true(result$valid)
+ expect_match(result$warnings, "Description is too long", all = FALSE)
+})
+
+test_that("validate_skill() warns for unexpected frontmatter fields", {
+ skill_dir <- create_temp_skill(extra_frontmatter = list(bogus = TRUE))
+ result <- validate_skill(skill_dir)
+ expect_true(result$valid)
+ expect_match(result$warnings, "Unexpected frontmatter", all = FALSE)
+})
+
+test_that("validate_skill() accepts optional fields", {
+ skill_dir <- create_temp_skill(
+ extra_frontmatter = list(
+ license = "MIT",
+ compatibility = "Requires git",
+ "allowed-tools" = "Read Bash",
+ metadata = list(author = "test")
+ )
+ )
+ result <- validate_skill(skill_dir)
+ expect_true(result$valid)
+})
+
+test_that("validate_skill() warns for compatibility exceeding 500 chars", {
+ long_compat <- paste(rep("a", 501), collapse = "")
+ skill_dir <- create_temp_skill(
+ extra_frontmatter = list(compatibility = long_compat)
+ )
+ result <- validate_skill(skill_dir)
+ expect_true(result$valid)
+ expect_match(result$warnings, "Compatibility field is too long", all = FALSE)
+})
+
+# Discovery ----------------------------------------------------------------
+
+test_that("btw_list_skills() finds valid skills", {
+ dir <- withr::local_tempdir()
+ create_temp_skill(name = "my-skill", dir = dir)
+ local_skill_dirs(dir)
+
+ skills <- btw_list_skills()
+ expect_length(skills, 1)
+ expect_equal(skills[["my-skill"]]$name, "my-skill")
+})
+
+test_that("btw_list_skills() skips invalid skills with warning", {
+ dir <- withr::local_tempdir()
+
+ # Create a valid skill
+ create_temp_skill(name = "good-skill", dir = dir)
+
+ # Create an invalid skill (missing description)
+ bad_dir <- file.path(dir, "bad-skill")
+ dir.create(bad_dir)
+ frontmatter::write_front_matter(
+ list(data = list(name = "bad-skill"), body = "Body."),
+ file.path(bad_dir, "SKILL.md")
+ )
+
+ local_skill_dirs(dir)
+
+ expect_warning(
+ skills <- btw_list_skills(),
+ "Skipping invalid skill"
+ )
+ expect_length(skills, 1)
+ expect_equal(skills[["good-skill"]]$name, "good-skill")
+})
+
+test_that("btw_list_skills() later directories override earlier by name", {
+ dir1 <- withr::local_tempdir()
+ dir2 <- withr::local_tempdir()
+
+ create_temp_skill(
+ name = "shared-skill",
+ description = "From dir1.",
+ dir = dir1
+ )
+ create_temp_skill(
+ name = "shared-skill",
+ description = "From dir2.",
+ dir = dir2
+ )
+
+ local_skill_dirs(c(dir1, dir2))
+
+ expect_message(
+ skills <- btw_list_skills(),
+ "overrides earlier skill"
+ )
+ expect_length(skills, 1)
+ expect_equal(skills[["shared-skill"]]$description, "From dir2.")
+})
+
+test_that("btw_list_skills() includes compatibility and allowed-tools", {
+ dir <- withr::local_tempdir()
+ create_temp_skill(
+ name = "fancy-skill",
+ dir = dir,
+ extra_frontmatter = list(
+ compatibility = "Requires Python 3",
+ `allowed-tools` = "Read Bash"
+ )
+ )
+ local_skill_dirs(dir)
+
+ skills <- btw_list_skills()
+ expect_equal(skills[["fancy-skill"]]$compatibility, "Requires Python 3")
+ expect_equal(skills[["fancy-skill"]]$allowed_tools, "Read Bash")
+})
+
+test_that("btw_skill_directories() discovers skills from multiple project dirs", {
+ project <- withr::local_tempdir()
+ withr::local_dir(project)
+ project <- getwd() # resolve symlinks (e.g. /private/var on macOS)
+
+ # Create skills in .btw/skills and .agents/skills
+ btw_dir <- file.path(project, ".btw", "skills")
+ agents_dir <- file.path(project, ".agents", "skills")
+ dir.create(btw_dir, recursive = TRUE)
+ dir.create(agents_dir, recursive = TRUE)
+
+ dirs <- btw_skill_directories()
+ expect_true(btw_dir %in% dirs)
+ expect_true(agents_dir %in% dirs)
+})
+
+test_that("btw_skill_directories() discovers .agents/skills", {
+ project <- withr::local_tempdir()
+ withr::local_dir(project)
+ project <- getwd()
+
+ agents_dir <- file.path(project, ".agents", "skills")
+ dir.create(agents_dir, recursive = TRUE)
+
+ dirs <- btw_skill_directories()
+ expect_true(agents_dir %in% dirs)
+})
+
+test_that("resolve_project_skill_dir() defaults to .btw/skills when none exist", {
+ project <- withr::local_tempdir()
+ withr::local_dir(project)
+ project <- getwd()
+
+ result <- resolve_project_skill_dir()
+ expect_equal(result, file.path(project, ".btw", "skills"))
+})
+
+test_that("resolve_project_skill_dir() returns the one that exists", {
+ project <- withr::local_tempdir()
+ withr::local_dir(project)
+ project <- getwd()
+
+ agents_dir <- file.path(project, ".agents", "skills")
+ dir.create(agents_dir, recursive = TRUE)
+
+ result <- resolve_project_skill_dir()
+ expect_equal(result, agents_dir)
+})
+
+test_that("resolve_project_skill_dir() returns first existing when non-interactive", {
+ project <- withr::local_tempdir()
+ withr::local_dir(project)
+ project <- getwd()
+
+ btw_dir <- file.path(project, ".btw", "skills")
+ agents_dir <- file.path(project, ".agents", "skills")
+ dir.create(btw_dir, recursive = TRUE)
+ dir.create(agents_dir, recursive = TRUE)
+
+ local_mocked_bindings(is_interactive = function() FALSE)
+ result <- resolve_project_skill_dir()
+ expect_equal(result, btw_dir)
+})
+
+test_that("find_skill() returns NULL for nonexistent skill", {
+ dir <- withr::local_tempdir()
+ local_skill_dirs(dir)
+ expect_null(find_skill("nonexistent"))
+})
+
+test_that("find_skill() finds a valid skill", {
+ dir <- withr::local_tempdir()
+ create_temp_skill(name = "found-skill", dir = dir)
+ local_skill_dirs(dir)
+
+ result <- find_skill("found-skill")
+ expect_type(result, "list")
+ expect_true(file.exists(result$path))
+})
+
+# extract_skill_metadata ---------------------------------------------------
+
+test_that("extract_skill_metadata() returns parsed frontmatter", {
+ skill_dir <- create_temp_skill(
+ extra_frontmatter = list(license = "MIT")
+ )
+ metadata <- extract_skill_metadata(file.path(skill_dir, "SKILL.md"))
+ expect_equal(metadata$name, "test-skill")
+ expect_equal(metadata$license, "MIT")
+})
+
+test_that("extract_skill_metadata() returns empty list for bad files", {
+ tmp <- withr::local_tempfile(lines = "No frontmatter here", fileext = ".md")
+ metadata <- extract_skill_metadata(tmp)
+ expect_equal(metadata, list())
+})
+
+test_that("extract_skill_metadata() warns on parse failure", {
+ tmp <- withr::local_tempfile(fileext = ".md")
+ # Write invalid YAML frontmatter
+ writeLines("---\n: invalid yaml: [\n---\nBody.", tmp)
+ expect_warning(
+ metadata <- extract_skill_metadata(tmp),
+ "Failed to parse frontmatter"
+ )
+ expect_equal(metadata, list())
+})
+
+# Resources ----------------------------------------------------------------
+
+test_that("list_skill_resources() finds files recursively", {
+ dir <- withr::local_tempdir()
+ skill_dir <- file.path(dir, "test-skill")
+ dir.create(file.path(skill_dir, "scripts"), recursive = TRUE)
+ dir.create(file.path(skill_dir, "assets", "templates"), recursive = TRUE)
+ writeLines("print('hi')", file.path(skill_dir, "scripts", "run.py"))
+ writeLines(
+ "template",
+ file.path(skill_dir, "assets", "templates", "base.html")
+ )
+
+ resources <- list_skill_resources(skill_dir)
+ expect_equal(resources$scripts, "run.py")
+ expect_true("templates/base.html" %in% resources$assets)
+})
+
+test_that("format_resources_listing() returns empty string for no resources", {
+ resources <- list(
+ scripts = character(0),
+ references = character(0),
+ assets = character(0)
+ )
+ expect_equal(format_resources_listing(resources, "/tmp"), "")
+})
+
+# Skill Tool ----------------------------------------------------------------
+
+test_that("btw_tool_skill_impl() returns content and resources", {
+ dir <- withr::local_tempdir()
+ skill_dir <- create_temp_skill(name = "fetch-test", dir = dir)
+ dir.create(file.path(skill_dir, "references"))
+ writeLines("Reference doc.", file.path(skill_dir, "references", "guide.md"))
+
+ local_skill_dirs(dir)
+
+ result <- btw_tool_skill_impl("fetch-test")
+ expect_s3_class(result, "ellmer::ContentToolResult")
+ expect_match(result@value, "Test Skill")
+ expect_match(result@value, "References:")
+ expect_equal(result@extra$data$name, "fetch-test")
+ expect_equal(result@extra$data$resources$references, "guide.md")
+})
+
+test_that("btw_tool_skill_impl() errors for missing skill", {
+ dir <- withr::local_tempdir()
+ local_skill_dirs(dir)
+ expect_error(btw_tool_skill_impl("nonexistent"), "not found")
+})
+
+# System Prompt ------------------------------------------------------------
+
+test_that("btw_skills_system_prompt() returns empty for no skills", {
+ dir <- withr::local_tempdir()
+ local_skill_dirs(dir)
+ expect_equal(btw_skills_system_prompt(), "")
+})
+
+test_that("btw_skills_system_prompt() includes skill metadata", {
+ dir <- withr::local_tempdir()
+ create_temp_skill(
+ name = "prompt-test",
+ description = "A skill for testing prompts.",
+ dir = dir,
+ extra_frontmatter = list(compatibility = "Needs R 4.2")
+ )
+ local_skill_dirs(dir)
+
+ prompt <- btw_skills_system_prompt()
+ expect_match(prompt, "prompt-test")
+ expect_match(prompt, "A skill for testing prompts.")
+ expect_match(prompt, "Needs R 4.2")
+})
+
+# select_skill_dir ----------------------------------------------------------
+
+test_that("select_skill_dir() returns single dir directly", {
+ dir <- withr::local_tempdir()
+ skill_dir <- create_temp_skill(name = "only-skill", dir = dir)
+ result <- select_skill_dir(skill_dir)
+ expect_equal(result, skill_dir)
+})
+
+test_that("select_skill_dir() matches named skill", {
+ dir <- withr::local_tempdir()
+ skill_a <- create_temp_skill(name = "skill-a", dir = dir)
+ skill_b <- create_temp_skill(name = "skill-b", dir = dir)
+ result <- select_skill_dir(c(skill_a, skill_b), skill = "skill-b")
+ expect_equal(result, skill_b)
+})
+
+test_that("select_skill_dir() aborts when named skill not found", {
+ dir <- withr::local_tempdir()
+ skill_a <- create_temp_skill(name = "skill-a", dir = dir)
+ expect_error(
+ select_skill_dir(skill_a, skill = "nonexistent"),
+ "not found"
+ )
+})
+
+test_that("select_skill_dir() aborts for multiple dirs non-interactively", {
+ dir <- withr::local_tempdir()
+ skill_a <- create_temp_skill(name = "skill-a", dir = dir)
+ skill_b <- create_temp_skill(name = "skill-b", dir = dir)
+ local_mocked_bindings(is_interactive = function() FALSE)
+ expect_error(
+ select_skill_dir(c(skill_a, skill_b)),
+ "Multiple skills found"
+ )
+})
+
+test_that("select_skill_dir() uses menu for multiple dirs interactively", {
+ dir <- withr::local_tempdir()
+ skill_a <- create_temp_skill(name = "skill-a", dir = dir)
+ skill_b <- create_temp_skill(name = "skill-b", dir = dir)
+ local_mocked_bindings(is_interactive = function() TRUE)
+ local_mocked_bindings(menu = function(...) 2L, .package = "utils")
+ expect_message(
+ result <- select_skill_dir(c(skill_a, skill_b)),
+ "Multiple skills found"
+ )
+ expect_equal(result, skill_b)
+})
+
+test_that("select_skill_dir() aborts when no dirs provided", {
+ expect_error(select_skill_dir(character()), "No skills found")
+})
+
+# install_skill_from_dir ---------------------------------------------------
+
+test_that("install_skill_from_dir() installs from directory", {
+ source_dir <- withr::local_tempdir()
+ create_temp_skill(name = "installable", dir = source_dir)
+
+ target_base <- withr::local_tempdir()
+ withr::local_dir(target_base)
+ expect_message(
+ path <- install_skill_from_dir(
+ file.path(source_dir, "installable"),
+ scope = "project"
+ ),
+ "Installed skill"
+ )
+
+ expect_true(dir.exists(path))
+ expect_true(file.exists(file.path(path, "SKILL.md")))
+})
+
+test_that("install_skill_from_dir() refuses invalid skill", {
+ source_dir <- withr::local_tempdir()
+ bad_dir <- file.path(source_dir, "bad-skill")
+ dir.create(bad_dir)
+ writeLines("---\nname: bad-skill\n---\nBody.", file.path(bad_dir, "SKILL.md"))
+
+ target_base <- withr::local_tempdir()
+ withr::local_dir(target_base)
+
+ expect_error(
+ install_skill_from_dir(bad_dir, scope = "project"),
+ "Cannot install invalid"
+ )
+})
+
+test_that("install_skill_from_dir() errors for nonexistent source", {
+ expect_error(install_skill_from_dir("/nonexistent/path"), "not found")
+})
+
+test_that("install_skill_from_dir() accepts custom path as scope", {
+ source_dir <- withr::local_tempdir()
+ create_temp_skill(name = "custom-install", dir = source_dir)
+
+ target <- withr::local_tempdir()
+ custom_dir <- file.path(target, ".openhands", "skills")
+
+ expect_message(
+ path <- install_skill_from_dir(
+ file.path(source_dir, "custom-install"),
+ scope = custom_dir
+ ),
+ "Installed skill"
+ )
+ expect_equal(normalizePath(dirname(path)), normalizePath(custom_dir))
+ expect_true(file.exists(file.path(path, "SKILL.md")))
+})
+
+test_that("install_skill_from_dir() treats I('project') as literal path", {
+ source_dir <- withr::local_tempdir()
+ create_temp_skill(name = "literal-test", dir = source_dir)
+
+ target <- withr::local_tempdir()
+
+ expect_message(
+ path <- install_skill_from_dir(
+ file.path(source_dir, "literal-test"),
+ scope = I(file.path(target, "project"))
+ ),
+ "Installed skill"
+ )
+ expect_equal(normalizePath(dirname(path)), normalizePath(file.path(target, "project")))
+})
+
+# btw_skill_install_github -------------------------------------------------
+
+# Helper: create a zip mimicking GitHub's zipball format
+create_github_zipball <- function(skills, zip_path = NULL) {
+ tmp <- withr::local_tempdir(.local_envir = parent.frame())
+ repo_dir <- file.path(tmp, "owner-repo-abc1234")
+ dir.create(repo_dir)
+
+ for (skill in skills) {
+ skill_dir <- file.path(repo_dir, skill$name)
+ dir.create(skill_dir, recursive = TRUE)
+ writeLines(
+ paste0(
+ "---\nname: ",
+ skill$name,
+ "\ndescription: ",
+ skill$description %||% "A test skill.",
+ "\n---\n\n# ",
+ skill$name,
+ "\n\nInstructions.\n"
+ ),
+ file.path(skill_dir, "SKILL.md")
+ )
+ }
+
+ if (is.null(zip_path)) {
+ zip_path <- tempfile(fileext = ".zip", tmpdir = tmp)
+ }
+ withr::with_dir(tmp, {
+ utils::zip(zip_path, basename(repo_dir), flags = "-r9Xq")
+ })
+ zip_path
+}
+
+test_that("btw_skill_install_github() errors for invalid repo format", {
+ expect_error(btw_skill_install_github("badformat"), "owner/repo")
+ expect_error(btw_skill_install_github("a/b/c"), "owner/repo")
+ expect_error(btw_skill_install_github("/repo"), "owner/repo")
+ expect_error(btw_skill_install_github("owner/"), "owner/repo")
+ expect_error(btw_skill_install_github("owner/repo@"), "empty ref")
+})
+
+test_that("btw_skill_install_github() parses @ref from repo string", {
+ zip_path <- create_github_zipball(list(
+ list(name = "gh-skill", description = "A GitHub skill.")
+ ))
+
+ local_mocked_bindings(
+ check_installed = function(...) invisible(),
+ .package = "rlang"
+ )
+
+ captured_ref <- NULL
+ mock_gh <- function(..., .destfile = NULL) {
+ args <- list(...)
+ captured_ref <<- args$ref
+ file.copy(zip_path, .destfile)
+ }
+
+ local_mocked_bindings(gh = mock_gh, .package = "gh")
+
+ target_base <- withr::local_tempdir()
+ withr::local_dir(target_base)
+
+ expect_message(
+ btw_skill_install_github("owner/repo@v1.0", scope = "project"),
+ "Installed skill"
+ )
+ expect_equal(captured_ref, "v1.0")
+})
+
+test_that("btw_skill_install_github() installs single skill", {
+ zip_path <- create_github_zipball(list(
+ list(name = "gh-skill", description = "A GitHub skill.")
+ ))
+
+ local_mocked_bindings(
+ check_installed = function(...) invisible(),
+ .package = "rlang"
+ )
+
+ mock_gh <- function(..., .destfile = NULL) {
+ file.copy(zip_path, .destfile)
+ }
+
+ local_mocked_bindings(gh = mock_gh, .package = "gh")
+
+ target_base <- withr::local_tempdir()
+ withr::local_dir(target_base)
+
+ expect_message(
+ path <- btw_skill_install_github("owner/repo", scope = "project"),
+ "Installed skill"
+ )
+ expect_true(dir.exists(path))
+ expect_true(file.exists(file.path(path, "SKILL.md")))
+ expect_equal(basename(path), "gh-skill")
+})
+
+test_that("btw_skill_install_github() selects named skill from multiple", {
+ zip_path <- create_github_zipball(list(
+ list(name = "skill-a", description = "Skill A."),
+ list(name = "skill-b", description = "Skill B.")
+ ))
+
+ local_mocked_bindings(
+ check_installed = function(...) invisible(),
+ .package = "rlang"
+ )
+
+ mock_gh <- function(..., .destfile = NULL) {
+ file.copy(zip_path, .destfile)
+ }
+
+ local_mocked_bindings(gh = mock_gh, .package = "gh")
+
+ target_base <- withr::local_tempdir()
+ withr::local_dir(target_base)
+
+ expect_message(
+ path <- btw_skill_install_github(
+ "owner/repo",
+ skill = "skill-b",
+ scope = "project"
+ ),
+ "Installed skill"
+ )
+ expect_equal(basename(path), "skill-b")
+})
+
+test_that("btw_skill_install_github() errors when named skill not found", {
+ zip_path <- create_github_zipball(list(
+ list(name = "skill-a", description = "Skill A.")
+ ))
+
+ local_mocked_bindings(
+ check_installed = function(...) invisible(),
+ .package = "rlang"
+ )
+
+ mock_gh <- function(..., .destfile = NULL) {
+ file.copy(zip_path, .destfile)
+ }
+
+ local_mocked_bindings(gh = mock_gh, .package = "gh")
+
+ target_base <- withr::local_tempdir()
+ withr::local_dir(target_base)
+
+ expect_error(
+ btw_skill_install_github("owner/repo", skill = "nonexistent"),
+ "not found"
+ )
+})
+
+test_that("btw_skill_install_github() errors when no skills in repo", {
+ # Create a zip with no SKILL.md
+ tmp <- withr::local_tempdir()
+ repo_dir <- file.path(tmp, "owner-repo-abc1234")
+ dir.create(repo_dir)
+ writeLines("Just a README.", file.path(repo_dir, "README.md"))
+ zip_path <- file.path(tmp, "empty.zip")
+ withr::with_dir(tmp, {
+ utils::zip(zip_path, basename(repo_dir), flags = "-r9Xq")
+ })
+
+ local_mocked_bindings(
+ check_installed = function(...) invisible(),
+ .package = "rlang"
+ )
+
+ mock_gh <- function(..., .destfile = NULL) {
+ file.copy(zip_path, .destfile)
+ }
+
+ local_mocked_bindings(gh = mock_gh, .package = "gh")
+
+ target_base <- withr::local_tempdir()
+ withr::local_dir(target_base)
+
+ expect_error(
+ btw_skill_install_github("owner/repo"),
+ "No skills found"
+ )
+})
+
+test_that("btw_skill_install_github() aborts non-interactively with multiple skills", {
+ zip_path <- create_github_zipball(list(
+ list(name = "skill-a", description = "Skill A."),
+ list(name = "skill-b", description = "Skill B.")
+ ))
+
+ local_mocked_bindings(
+ check_installed = function(...) invisible(),
+ .package = "rlang"
+ )
+
+ mock_gh <- function(..., .destfile = NULL) {
+ file.copy(zip_path, .destfile)
+ }
+
+ local_mocked_bindings(gh = mock_gh, .package = "gh")
+ local_mocked_bindings(is_interactive = function() FALSE)
+
+ target_base <- withr::local_tempdir()
+ withr::local_dir(target_base)
+
+ expect_error(
+ btw_skill_install_github("owner/repo"),
+ "Multiple skills found"
+ )
+})
+
+test_that("btw_skill_install_github() wraps download errors", {
+ local_mocked_bindings(
+ check_installed = function(...) invisible(),
+ .package = "rlang"
+ )
+
+ mock_gh <- function(...) {
+ stop("GitHub API error: Not Found")
+ }
+
+ local_mocked_bindings(gh = mock_gh, .package = "gh")
+
+ expect_error(
+ btw_skill_install_github("owner/nonexistent"),
+ "Failed to download"
+ )
+})
+
+# btw_skill_install_package ------------------------------------------------
+
+test_that("btw_skill_install_package() installs single skill from package", {
+ # Create a mock package skills directory
+ pkg_skills <- withr::local_tempdir()
+ skill_dir <- file.path(pkg_skills, "pkg-skill")
+ dir.create(skill_dir)
+ writeLines(
+ "---\nname: pkg-skill\ndescription: A package skill.\n---\n\n# Pkg Skill\n",
+ file.path(skill_dir, "SKILL.md")
+ )
+
+ local_mocked_bindings(
+ check_installed = function(...) invisible(),
+ .package = "rlang"
+ )
+ local_mocked_bindings(
+ system.file = function(..., package = NULL) pkg_skills,
+ .package = "base"
+ )
+
+ target_base <- withr::local_tempdir()
+ withr::local_dir(target_base)
+
+ expect_message(
+ path <- btw_skill_install_package("mypkg", scope = "project"),
+ "Installed skill"
+ )
+ expect_true(dir.exists(path))
+ expect_equal(basename(path), "pkg-skill")
+})
+
+test_that("btw_skill_install_package() selects named skill", {
+ pkg_skills <- withr::local_tempdir()
+ for (nm in c("alpha", "beta")) {
+ d <- file.path(pkg_skills, nm)
+ dir.create(d)
+ writeLines(
+ paste0(
+ "---\nname: ",
+ nm,
+ "\ndescription: Skill ",
+ nm,
+ ".\n---\n\n# ",
+ nm,
+ "\n"
+ ),
+ file.path(d, "SKILL.md")
+ )
+ }
+
+ local_mocked_bindings(
+ check_installed = function(...) invisible(),
+ .package = "rlang"
+ )
+ local_mocked_bindings(
+ system.file = function(..., package = NULL) pkg_skills,
+ .package = "base"
+ )
+
+ target_base <- withr::local_tempdir()
+ withr::local_dir(target_base)
+
+ expect_message(
+ path <- btw_skill_install_package(
+ "mypkg",
+ skill = "beta",
+ scope = "project"
+ ),
+ "Installed skill"
+ )
+ expect_equal(basename(path), "beta")
+})
+
+test_that("btw_skill_install_package() errors when no skills dir", {
+ local_mocked_bindings(
+ check_installed = function(...) invisible(),
+ .package = "rlang"
+ )
+ local_mocked_bindings(
+ system.file = function(..., package = NULL) "",
+ .package = "base"
+ )
+
+ expect_error(
+ btw_skill_install_package("emptypkg"),
+ "does not bundle any skills"
+ )
+})
+
+test_that("btw_skill_install_package() errors when no SKILL.md in subdirs", {
+ pkg_skills <- withr::local_tempdir()
+ dir.create(file.path(pkg_skills, "not-a-skill"))
+ writeLines("just a file", file.path(pkg_skills, "not-a-skill", "README.md"))
+
+ local_mocked_bindings(
+ check_installed = function(...) invisible(),
+ .package = "rlang"
+ )
+ local_mocked_bindings(
+ system.file = function(..., package = NULL) pkg_skills,
+ .package = "base"
+ )
+
+ expect_error(
+ btw_skill_install_package("mypkg"),
+ "does not bundle any skills"
+ )
+})
+
+# Snapshot test for system prompt (existing) --------------------------------
+
+test_that("btw_skills_system_prompt() works", {
+ skip_if_not_snapshot_env()
+ expect_snapshot(
+ cat(btw_skills_system_prompt()),
+ transform = function(x) {
+ gsub(".*?", "SKILL_PATH", x)
+ }
+ )
+})
+
+# validate_skill_name() ----------------------------------------------------
+
+test_that("validate_skill() accepts single-character name", {
+ dir <- withr::local_tempdir()
+ skill_dir <- file.path(dir, "a")
+ dir.create(skill_dir)
+ writeLines(
+ "---\nname: a\ndescription: A minimal skill.\n---\nBody.",
+ file.path(skill_dir, "SKILL.md")
+ )
+ result <- validate_skill(skill_dir)
+ expect_true(result$valid)
+ expect_length(result$issues, 0)
+})
+
+test_that("validate_skill() flags non-character compatibility", {
+ dir <- withr::local_tempdir()
+ skill_dir <- file.path(dir, "test-skill")
+ dir.create(skill_dir)
+ writeLines(
+ "---\nname: test-skill\ndescription: A test.\ncompatibility: true\n---\nBody.",
+ file.path(skill_dir, "SKILL.md")
+ )
+
+ result <- validate_skill(skill_dir)
+ expect_true(result$valid)
+ expect_match(result$warnings, "must be a character string", all = FALSE)
+})
+
+# find_skill() with invalid skill ------------------------------------------
+
+test_that("find_skill() returns validation errors for invalid skill on disk", {
+ dir <- withr::local_tempdir()
+ # Create a skill that exists on disk but fails validation (missing description)
+ bad_dir <- file.path(dir, "bad-skill")
+ dir.create(bad_dir)
+ writeLines("---\nname: bad-skill\n---\nBody.", file.path(bad_dir, "SKILL.md"))
+
+ local_skill_dirs(dir)
+ result <- find_skill("bad-skill")
+ expect_type(result, "list")
+ expect_false(result$validation$valid)
+ expect_match(result$validation$errors, "description", all = FALSE)
+})
+
+# install_skill_from_dir() overwrite ----------------------------------------
+
+test_that("install_skill_from_dir() overwrites with overwrite = TRUE", {
+ source_dir <- withr::local_tempdir()
+ create_temp_skill(
+ name = "overwrite-me",
+ description = "Version 1.",
+ dir = source_dir
+ )
+
+ target_base <- withr::local_tempdir()
+ withr::local_dir(target_base)
+
+ # First install
+ expect_message(
+ path <- install_skill_from_dir(
+ file.path(source_dir, "overwrite-me"),
+ scope = "project"
+ ),
+ "Installed skill"
+ )
+
+ # Update source
+ writeLines(
+ "---\nname: overwrite-me\ndescription: Version 2.\n---\nUpdated.",
+ file.path(source_dir, "overwrite-me", "SKILL.md")
+ )
+
+ # Re-install with overwrite
+ expect_message(
+ path2 <- install_skill_from_dir(
+ file.path(source_dir, "overwrite-me"),
+ scope = "project",
+ overwrite = TRUE
+ ),
+ "Installed skill"
+ )
+
+ expect_equal(path, path2)
+ content <- readLines(file.path(path2, "SKILL.md"))
+ expect_true(any(grepl("Version 2", content)))
+})
+
+# xml_escape() in system prompt ---------------------------------------------
+
+test_that("btw_skills_system_prompt() escapes XML special characters", {
+ dir <- withr::local_tempdir()
+ create_temp_skill(
+ name = "esc-test",
+ description = "Uses & ampersands.",
+ dir = dir
+ )
+ local_skill_dirs(dir)
+
+ prompt <- btw_skills_system_prompt()
+ expect_match(prompt, "<tags>", fixed = TRUE)
+ expect_match(prompt, "& ampersands", fixed = TRUE)
+ expect_no_match(prompt, "", fixed = TRUE)
+})
+
+test_that("skills prompt is included in btw_client() system prompt", {
+ withr::local_envvar(list(ANTHROPIC_API_KEY = "beep"))
+
+ with_mocked_platform(ide = "rstudio", {
+ chat <- btw_client(path_btw = FALSE)
+ })
+
+ system_prompt <- chat$get_system_prompt()
+
+ expect_match(system_prompt, "## Skills", fixed = TRUE)
+ expect_match(system_prompt, "skill-creator", fixed = TRUE)
+})
diff --git a/tests/testthat/test-utils.R b/tests/testthat/test-utils.R
index 06566a91..e6e456d7 100644
--- a/tests/testthat/test-utils.R
+++ b/tests/testthat/test-utils.R
@@ -22,6 +22,59 @@ test_that("check_inherits() works", {
expect_error(check_inherits(as_btw_docs_package("btw"), "not_this_class"))
})
+# Tests for parse_github_repo() --------------------------------------------
+
+describe("parse_github_repo()", {
+ it("parses owner/repo", {
+ result <- parse_github_repo("owner/repo")
+ expect_equal(result$owner, "owner")
+ expect_equal(result$repo, "repo")
+ expect_equal(result$ref, "HEAD")
+ })
+
+ it("parses owner/repo@ref", {
+ result <- parse_github_repo("owner/repo@v1.0")
+ expect_equal(result$owner, "owner")
+ expect_equal(result$repo, "repo")
+ expect_equal(result$ref, "v1.0")
+ })
+
+ it("parses owner/repo@branch", {
+ result <- parse_github_repo("owner/repo@main")
+ expect_equal(result$ref, "main")
+ })
+
+ it("parses owner/repo@sha", {
+ result <- parse_github_repo("owner/repo@abc1234")
+ expect_equal(result$ref, "abc1234")
+ })
+
+ it("errors for empty ref after @", {
+ expect_error(parse_github_repo("owner/repo@"), "empty ref")
+ })
+
+ it("errors for missing slash", {
+ expect_error(parse_github_repo("badformat"), "owner/repo")
+ })
+
+ it("errors for too many slashes", {
+ expect_error(parse_github_repo("a/b/c"), "owner/repo")
+ })
+
+ it("errors for empty owner", {
+ expect_error(parse_github_repo("/repo"), "owner/repo")
+ })
+
+ it("errors for empty repo", {
+ expect_error(parse_github_repo("owner/"), "owner/repo")
+ })
+
+ it("errors for non-string input", {
+ expect_error(parse_github_repo(123))
+ expect_error(parse_github_repo(NULL))
+ })
+})
+
# Tests for remove_base64_images() -----------------------------------------
describe("remove_base64_images()", {