Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Add skill import from GitHub URL (#57458)
MartinYe12342984fafdf285
diff --git a/Cargo.lock b/Cargo.lockindex c60f0d7dcf4..3dc93b90add 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -16541,7 +16541,9 @@ dependencies = ["anyhow","editor","fs",+ "futures 0.3.32","gpui",+ "http_client","language","menu","platform_title_bar",diff --git a/crates/agent_skills/agent_skills.rs b/crates/agent_skills/agent_skills.rsindex 3a816020d4a..6a78346c380 100644--- a/crates/agent_skills/agent_skills.rs+++ b/crates/agent_skills/agent_skills.rs@@ -243,17 +243,7 @@ pub fn parse_skill_frontmatter(content: &str,source: SkillSource,) -> Result<Skill> {- if content.len() > MAX_SKILL_FILE_SIZE {- anyhow::bail!(- "SKILL.md file exceeds maximum size of {}KB",- MAX_SKILL_FILE_SIZE / 1024- );- }-- let (metadata, _body) = extract_frontmatter(content)?;-- validate_name(&metadata.name).map_err(anyhow::Error::msg)?;- validate_description(&metadata.description).map_err(anyhow::Error::msg)?;+ let (metadata, _body) = parse_skill_file_content(content)?;let directory_path = skill_file_path.parent()@@ -271,6 +261,29 @@ pub fn parse_skill_frontmatter(})}+/// Extract the YAML frontmatter and body from a SKILL.md file without+/// validating the metadata fields.+pub fn extract_skill_frontmatter(content: &str) -> Result<(SkillMetadata, &str)> {+ if content.len() > MAX_SKILL_FILE_SIZE {+ anyhow::bail!(+ "SKILL.md file exceeds maximum size of {}KB",+ MAX_SKILL_FILE_SIZE / 1024+ );+ }++ extract_frontmatter(content)+}++/// Parse and validate the YAML frontmatter and body from a SKILL.md file.+pub fn parse_skill_file_content(content: &str) -> Result<(SkillMetadata, &str)> {+ let (metadata, body) = extract_skill_frontmatter(content)?;++ validate_name(&metadata.name).map_err(anyhow::Error::msg)?;+ validate_description(&metadata.description).map_err(anyhow::Error::msg)?;++ Ok((metadata, body))+}+fn extract_frontmatter(content: &str) -> Result<(SkillMetadata, &str)> {let content = content.trim_start();@@ -853,6 +866,26 @@ Do the thing.assert!(!skill.disable_model_invocation);}+ #[test]+ fn test_parse_skill_file_content_returns_body() {+ let content = r#"---+name: my-skill+description: A test skill for testing purposes+---++# My Skill++Do the thing.+"#;++ let (metadata, body) = parse_skill_file_content(content)+ .expect("valid skill content should parse successfully");++ assert_eq!(metadata.name, "my-skill");+ assert_eq!(metadata.description, "A test skill for testing purposes");+ assert_eq!(body.trim(), "# My Skill\n\nDo the thing.");+ }+#[test]fn test_parse_disable_model_invocation_true() {let content = r#"---diff --git a/crates/agent_ui/src/agent_panel.rs b/crates/agent_ui/src/agent_panel.rsindex 9dcb3d11e4a..3dbd04bbddf 100644--- a/crates/agent_ui/src/agent_panel.rs+++ b/crates/agent_ui/src/agent_panel.rs@@ -27,7 +27,9 @@ use zed_actions::{ResetAgentZoom, ResetOnboarding, ResolveConflictedFilesWithAgent,ResolveConflictsWithAgent, ReviewBranchDiff,},- assistant::{FocusAgent, OpenRulesLibrary, OpenSkillCreator, Toggle, ToggleFocus},+ assistant::{+ CreateSkillFromUrl, FocusAgent, OpenRulesLibrary, OpenSkillCreator, Toggle, ToggleFocus,+ },};use crate::ExpandMessageEditor;@@ -74,7 +76,7 @@ use project::{Project, ProjectPath, Worktree};use prompt_store::PromptStore;use settings::TerminalDockPosition;use settings::{NotifyWhenAgentWaiting, Settings, update_settings_file};-use skill_creator::open_skill_creator;+use skill_creator::{SkillCreatorOpenMode, is_supported_skill_url, open_skill_creator};use terminal::{Event as TerminalEvent, terminal_settings::TerminalSettings};use terminal_view::{TerminalView, terminal_panel::TerminalPanel};use theme_settings::ThemeSettings;@@ -320,6 +322,14 @@ pub fn init(cx: &mut App) {});}})+ .register_action(|workspace, action: &CreateSkillFromUrl, window, cx| {+ if let Some(panel) = workspace.panel::<AgentPanel>(cx) {+ workspace.focus_panel::<AgentPanel>(window, cx);+ panel.update(cx, |panel, cx| {+ panel.deploy_skill_creator_from_url(action, window, cx)+ });+ }+ }).register_action(|workspace, _: &Follow, window, cx| {workspace.follow(CollaboratorId::Agent, window, cx);})@@ -3070,8 +3080,27 @@ impl AgentPanel {_window: &mut Window,cx: &mut Context<Self>,) {+ self.open_skill_creator(SkillCreatorOpenMode::Form, cx);+ }++ fn deploy_skill_creator_from_url(+ &mut self,+ _action: &CreateSkillFromUrl,+ _window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ let initial_url = cx+ .read_from_clipboard()+ .and_then(|clipboard| clipboard.text())+ .map(|text| text.trim().to_string())+ .filter(|text| is_supported_skill_url(text));++ self.open_skill_creator(SkillCreatorOpenMode::Url { initial_url }, cx);+ }++ fn open_skill_creator(&mut self, open_mode: SkillCreatorOpenMode, cx: &mut Context<Self>) {let this = cx.weak_entity();- let on_saved = Rc::new(move |cx: &mut App| {+ let on_saved: Rc<dyn Fn(&mut App)> = Rc::new(move |cx: &mut App| {this.update(cx, |this, cx| {if !this.has_open_project(cx) {return;@@ -3098,13 +3127,14 @@ impl AgentPanel {}).detach_and_log_err(cx);})- .ok();+ .log_err();});open_skill_creator(Some(self.workspace.clone()),self.language_registry.clone(),self.fs.clone(),+ open_mode,Some(on_saved),cx,)diff --git a/crates/agent_ui/src/agent_ui.rs b/crates/agent_ui/src/agent_ui.rsindex 209976c090a..807d0bdfd09 100644--- a/crates/agent_ui/src/agent_ui.rs+++ b/crates/agent_ui/src/agent_ui.rs@@ -692,7 +692,10 @@ fn update_command_palette_filter(cx: &mut App) {];let open_rules_library_action = [TypeId::of::<zed_actions::assistant::OpenRulesLibrary>()];- let open_skill_creator_action = [TypeId::of::<zed_actions::assistant::OpenSkillCreator>()];+ let skill_creator_actions = [+ TypeId::of::<zed_actions::assistant::OpenSkillCreator>(),+ TypeId::of::<zed_actions::assistant::CreateSkillFromUrl>(),+ ];if disable_ai {filter.hide_namespace("agent");@@ -750,10 +753,10 @@ fn update_command_palette_filter(cx: &mut App) {// rest of that namespace's actions.if !disable_ai {filter.hide_action_types(&open_rules_library_action);- filter.show_action_types(open_skill_creator_action.iter());+ filter.show_action_types(skill_creator_actions.iter());} else {filter.show_action_types(open_rules_library_action.iter());- filter.hide_action_types(&open_skill_creator_action);+ filter.hide_action_types(&skill_creator_actions);}});}@@ -895,6 +898,14 @@ mod tests {!filter.is_hidden(&NewTerminalThread),"NewTerminalThread should be visible by default");+ assert!(+ !filter.is_hidden(&zed_actions::assistant::OpenSkillCreator),+ "OpenSkillCreator should be visible by default"+ );+ assert!(+ !filter.is_hidden(&zed_actions::assistant::CreateSkillFromUrl),+ "CreateSkillFromUrl should be visible by default"+ );});// Disable agentdiff --git a/crates/skill_creator/Cargo.toml b/crates/skill_creator/Cargo.tomlindex 2ffd7bb85df..1bda7bfb6eb 100644--- a/crates/skill_creator/Cargo.toml+++ b/crates/skill_creator/Cargo.toml@@ -16,7 +16,9 @@ agent_skills.workspace = trueanyhow.workspace = trueeditor.workspace = truefs.workspace = true+futures.workspace = truegpui.workspace = true+http_client.workspace = truelanguage.workspace = truemenu.workspace = trueplatform_title_bar.workspace = truediff --git a/crates/skill_creator/src/skill_creator.rs b/crates/skill_creator/src/skill_creator.rsindex e95fe876ef3..c6540e2fbd9 100644--- a/crates/skill_creator/src/skill_creator.rs+++ b/crates/skill_creator/src/skill_creator.rs@@ -1,15 +1,17 @@use agent_skills::{- AGENTS_DIR_NAME, GLOBAL_SKILLS_DIR_DISPLAY, SKILL_FILE_NAME, SKILLS_DIR_NAME, SkillMetadata,- global_skills_dir, validate_description, validate_name,+ AGENTS_DIR_NAME, GLOBAL_SKILLS_DIR_DISPLAY, MAX_SKILL_DESCRIPTION_LEN, MAX_SKILL_FILE_SIZE,+ SKILL_FILE_NAME, SKILLS_DIR_NAME, SkillMetadata, global_skills_dir, parse_skill_file_content,+ slugify_skill_name, validate_description, validate_name,};-use anyhow::{Context as _, Result};+use anyhow::{Context as _, Result, anyhow};use editor::{CurrentLineHighlight, Editor, EditorElement, EditorEvent, EditorStyle};use fs::Fs;+use futures::AsyncReadExt;use gpui::{- App, Bounds, DEFAULT_ADDITIONAL_WINDOW_SIZE, Entity, FocusHandle, Focusable, Subscription,- Task, TextStyle, Tiling, TitlebarOptions, WeakEntity, WindowBounds, WindowHandle,- WindowOptions, actions, point,+ App, Bounds, Entity, FocusHandle, Focusable, Subscription, Task, TextStyle, Tiling,+ TitlebarOptions, WeakEntity, WindowBounds, WindowHandle, WindowOptions, actions, point,};+use http_client::{AsyncBody, HttpClient, HttpRequestExt, Request, StatusCode, Url};use language::{Buffer, LanguageRegistry, language_settings::SoftWrap};use platform_title_bar::PlatformTitleBar;use release_channel::ReleaseChannel;@@ -17,6 +19,7 @@ use settings::{ActionSequence, Settings};use std::path::PathBuf;use std::rc::Rc;use std::sync::Arc;+use std::time::Duration;use theme_settings::ThemeSettings;use ui::{ContextMenu, Divider, DropdownMenu, DropdownStyle, Headline, HeadlineSize, SwitchField,@@ -34,14 +37,41 @@ actions!([SaveSkill, Cancel, FocusNextField, FocusPreviousField,]);-const NAME_FIELD_TAB_INDEX: isize = 1;-const DESCRIPTION_FIELD_TAB_INDEX: isize = 2;-const DISABLE_MODEL_INVOCATION_TAB_INDEX: isize = 3;-const SCOPE_FIELD_TAB_INDEX: isize = 4;-const BODY_FIELD_TAB_INDEX: isize = 5;+const URL_FIELD_TAB_INDEX: isize = 1;+const NAME_FIELD_TAB_INDEX: isize = 2;+const DESCRIPTION_FIELD_TAB_INDEX: isize = 3;+const DISABLE_MODEL_INVOCATION_TAB_INDEX: isize = 4;+const SCOPE_FIELD_TAB_INDEX: isize = 5;+const BODY_FIELD_TAB_INDEX: isize = 6;+const URL_IMPORT_DEBOUNCE: Duration = Duration::from_millis(100);+const URL_IMPORT_ERROR_BODY_MAX_LEN: usize = 2048;pub fn init(_cx: &mut App) {}+#[derive(Clone, Debug, Default)]+pub enum SkillCreatorOpenMode {+ #[default]+ Form,+ Url {+ initial_url: Option<String>,+ },+}++#[derive(Clone, Debug)]+enum UrlImportStatus {+ Idle,+ Fetching,+ Error(SharedString),+}++#[derive(Debug)]+struct ImportedSkill {+ name: String,+ description: String,+ body: String,+ disable_model_invocation: bool,+}+#[derive(Clone, Debug)]enum ScopeChoice {Global,@@ -112,10 +142,13 @@ pub fn open_skill_creator(workspace: Option<WeakEntity<Workspace>>,language_registry: Arc<LanguageRegistry>,fs: Arc<dyn Fs>,+ open_mode: SkillCreatorOpenMode,on_saved: Option<Rc<dyn Fn(&mut App)>>,cx: &mut App,) -> Task<Result<WindowHandle<SkillCreator>>> {cx.spawn(async move |cx| {+ let open_mode_for_existing = open_mode.clone();+ let on_saved_for_existing = on_saved.clone();let existing = cx.update(|cx| {let handle = cx.windows()@@ -123,7 +156,11 @@ pub fn open_skill_creator(.find_map(|window| window.downcast::<SkillCreator>());if let Some(handle) = handle {handle- .update(cx, |_, window, _| window.activate_window())+ .update(cx, |this, window, cx| {+ window.activate_window();+ this.on_saved = on_saved_for_existing.clone();+ this.apply_open_mode(open_mode_for_existing.clone(), window, cx);+ }).ok();Some(handle)} else {@@ -134,9 +171,12 @@ pub fn open_skill_creator(return Ok(window);}+ let window_size = gpui::size(px(900.), px(1050.));+cx.update(|cx| {let app_id = ReleaseChannel::global(cx).app_id();- let bounds = Bounds::centered(None, DEFAULT_ADDITIONAL_WINDOW_SIZE, cx);+ let http_client = cx.http_client();+ let bounds = Bounds::centered(None, window_size, cx);let window_decorations = match std::env::var("ZED_WINDOW_DECORATIONS") {Ok(val) if val == "server" => gpui::WindowDecorations::Server,Ok(val) if val == "client" => gpui::WindowDecorations::Client,@@ -156,14 +196,26 @@ pub fn open_skill_creator(window_bounds: Some(WindowBounds::Windowed(bounds)),window_background: cx.theme().window_background_appearance(),window_decorations: Some(window_decorations),- window_min_size: Some(DEFAULT_ADDITIONAL_WINDOW_SIZE),+ window_min_size: Some(window_size),kind: gpui::WindowKind::Floating,..Default::default()},|window, cx| {- cx.new(|cx| {- SkillCreator::new(workspace, language_registry, fs, on_saved, window, cx)- })+ let skill_creator = cx.new(|cx| {+ SkillCreator::new(+ workspace,+ language_registry,+ fs,+ http_client,+ on_saved,+ window,+ cx,+ )+ });+ skill_creator.update(cx, |this, cx| {+ this.apply_open_mode(open_mode, window, cx);+ });+ skill_creator},)})@@ -175,7 +227,9 @@ pub struct SkillCreator {title_bar: Option<Entity<PlatformTitleBar>>,workspace: Option<WeakEntity<Workspace>>,fs: Arc<dyn Fs>,+ http_client: Arc<dyn HttpClient>,on_saved: Option<Rc<dyn Fn(&mut App)>>,+ url_editor: Entity<InputField>,name_editor: Entity<InputField>,description_editor: Entity<InputField>,body_editor: Entity<Editor>,@@ -187,12 +241,17 @@ pub struct SkillCreator {description_error: Option<&'static str>,body_error: Option<&'static str>,save_error: Option<SharedString>,+ url_import_status: UrlImportStatus,saving: bool,// Held so that dropping the entity (e.g. the window closing) cancels// an in-flight save. Detaching the task instead would let// `write_skill_to_disk` complete after the UI is gone, silently// creating a SKILL.md on disk with no toast and no error feedback.save_task: Option<Task<()>>,+ // Held so replacing it or switching back to the form cancels a pending debounced import.+ url_import_debounce_task: Option<Task<()>>,+ // Held so replacing it or switching back to the form cancels an in-flight import.+ url_import_task: Option<Task<()>>,_subscriptions: Vec<Subscription>,}@@ -201,6 +260,7 @@ impl SkillCreator {workspace: Option<WeakEntity<Workspace>>,language_registry: Arc<LanguageRegistry>,fs: Arc<dyn Fs>,+ http_client: Arc<dyn HttpClient>,on_saved: Option<Rc<dyn Fn(&mut App)>>,window: &mut Window,cx: &mut Context<Self>,@@ -219,6 +279,16 @@ impl SkillCreator {.map(|scope| scope.key()).unwrap_or_else(|| ScopeChoice::Global.key());+ let url_editor = cx.new(|cx| {+ InputField::new(+ window,+ cx,+ "https://github.com/owner/repo/blob/main/path/to/SKILL.md",+ )+ .tab_index(URL_FIELD_TAB_INDEX)+ .tab_stop(true)+ });+let name_editor = cx.new(|cx| {InputField::new(window, cx, "my-new-skill").label("Name")@@ -285,9 +355,21 @@ impl SkillCreator {}).detach();+ let url_input_editor = url_editor.read(cx).editor().clone();let name_input_editor = name_editor.read(cx).editor().clone();let description_input_editor = description_editor.read(cx).editor().clone();let weak = cx.weak_entity();+ let url_subscription = url_input_editor.subscribe(+ Box::new(move |event, window, cx| {+ weak.update(cx, |this, cx| {+ this.handle_url_input_event(&event, window, cx);+ })+ .ok();+ }),+ window,+ cx,+ );+ let weak = cx.weak_entity();let name_subscription = name_input_editor.subscribe(Box::new(move |event, window, cx| {weak.update(cx, |this, cx| {@@ -311,6 +393,7 @@ impl SkillCreator {);let subscriptions = vec![+ url_subscription,name_subscription,description_subscription,cx.subscribe_in(&body_editor, window, Self::handle_body_editor_event),@@ -325,7 +408,9 @@ impl SkillCreator {},workspace,fs,+ http_client,on_saved,+ url_editor,name_editor,description_editor,body_editor,@@ -337,12 +422,38 @@ impl SkillCreator {description_error: None,body_error: None,save_error: None,+ url_import_status: UrlImportStatus::Idle,saving: false,save_task: None,+ url_import_debounce_task: None,+ url_import_task: None,_subscriptions: subscriptions,}}+ fn handle_url_input_event(+ &mut self,+ event: &ErasedEditorEvent,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ if !matches!(event, ErasedEditorEvent::BufferEdited) {+ return;+ }++ // Convention from `thread_view::handle_title_editor_event` and+ // `agent_panel::handle_terminal_title_editor_event`: programmatic+ // `set_text` is performed while the editor is unfocused, so the+ // focus check filters synthesized `BufferEdited` events out of+ // the user-edit path without needing a one-shot suppression flag.+ if !self.url_editor.focus_handle(cx).is_focused(window) {+ return;+ }++ self.save_error = None;+ self.schedule_url_import(window, cx);+ }+fn handle_name_input_event(&mut self,event: &ErasedEditorEvent,@@ -395,6 +506,10 @@ impl SkillCreator {self.body_editor.read(cx).text(cx)}+ fn current_url(&self, cx: &App) -> String {+ self.url_editor.read(cx).text(cx)+ }+fn recompute_name_error(&mut self, cx: &App) {let name = self.current_name(cx);self.name_error = validate_name(&name).err();@@ -428,6 +543,163 @@ impl SkillCreator {.find(|scope| scope.key() == self.selected_scope_key)}+ fn apply_open_mode(+ &mut self,+ open_mode: SkillCreatorOpenMode,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ match open_mode {+ SkillCreatorOpenMode::Form => {}+ SkillCreatorOpenMode::Url { initial_url } => {+ self.open_url_import(initial_url, window, cx);+ }+ }+ }++ fn open_url_import(+ &mut self,+ initial_url: Option<String>,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ self.save_error = None;+ self.url_import_debounce_task = None;+ self.url_import_task = None;+ self.url_import_status = UrlImportStatus::Idle;++ let text = initial_url.unwrap_or_default();+ let should_fetch = !text.is_empty();+ let needs_set_text = should_fetch || !self.current_url(cx).is_empty();+ if !needs_set_text {+ // No text to write and nothing to clear: just move focus.+ window.focus(&self.url_editor.focus_handle(cx), cx);+ cx.notify();+ return;+ }++ // Defer so the programmatic `set_text` runs before we move focus+ // to the URL editor. `handle_url_input_event` uses+ // `url_editor.is_focused(window)` to distinguish user edits from+ // programmatic ones, so writing while unfocused is what keeps the+ // synthesized `BufferEdited` from being treated as a user edit.+ let skill_creator = cx.weak_entity();+ let url_editor = self.url_editor.clone();+ window.defer(cx, move |window, cx| {+ url_editor.update(cx, |input, cx| {+ input.set_text(&text, window, cx);+ });+ window.focus(&url_editor.focus_handle(cx), cx);+ if should_fetch {+ skill_creator+ .update(cx, |this, cx| {+ this.start_url_import(window, cx);+ })+ .log_err();+ }+ });+ cx.notify();+ }++ fn schedule_url_import(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ self.url_import_debounce_task = None;+ self.url_import_task = None;++ let url = self.current_url(cx).trim().to_string();+ if url.is_empty() {+ self.url_import_status = UrlImportStatus::Idle;+ cx.notify();+ return;+ }++ self.url_import_status = UrlImportStatus::Idle;+ let task = cx.spawn_in(window, async move |this, cx| {+ cx.background_executor().timer(URL_IMPORT_DEBOUNCE).await;+ this.update_in(cx, |this, window, cx| {+ this.start_url_import(window, cx);+ })+ .log_err();+ });+ self.url_import_debounce_task = Some(task);+ cx.notify();+ }++ fn start_url_import(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ // Cancel any pending debounce so the explicit start supersedes it,+ // instead of racing with a timer that's about to fire.+ self.url_import_debounce_task = None;+ self.url_import_task = None;++ let url = self.current_url(cx).trim().to_string();+ if url.is_empty() {+ self.url_import_status = UrlImportStatus::Idle;+ cx.notify();+ return;+ }++ if let Err(err) = github_raw_url(&url) {+ self.url_import_status = UrlImportStatus::Error(SharedString::from(err.to_string()));+ cx.notify();+ return;+ }++ self.url_import_status = UrlImportStatus::Fetching;+ let http_client = self.http_client.clone();+ let fetch_task = cx.background_spawn(fetch_imported_skill_from_url(http_client, url));+ let task = cx.spawn_in(window, async move |this, cx| {+ let result = fetch_task.await;+ let skill_creator = this.clone();+ this.update_in(cx, |this, window, cx| {+ this.url_import_debounce_task = None;+ this.url_import_task = None;+ match result {+ Ok(imported) => {+ this.url_import_status = UrlImportStatus::Idle;+ this.save_error = None;++ let name_editor = this.name_editor.clone();+ let description_editor = this.description_editor.clone();+ let body_editor = this.body_editor.clone();+ window.defer(cx, move |window, cx| {+ name_editor.update(cx, |input, cx| {+ input.set_text(&imported.name, window, cx);+ });+ description_editor.update(cx, |input, cx| {+ input.set_text(&imported.description, window, cx);+ });+ body_editor.update(cx, |editor, cx| {+ editor.set_text(imported.body.clone(), window, cx);+ });+ skill_creator+ .update(cx, |this, cx| {+ this.disable_model_invocation =+ imported.disable_model_invocation;+ this.url_import_status = UrlImportStatus::Idle;+ this.url_import_debounce_task = None;+ this.url_import_task = None;+ this.save_error = None;+ this.recompute_name_error(cx);+ this.recompute_description_error(cx);+ this.recompute_body_error(cx);+ cx.notify();+ })+ .log_err();+ window.focus(&name_editor.focus_handle(cx), cx);+ });+ }+ Err(err) => {+ this.url_import_status =+ UrlImportStatus::Error(SharedString::from(err.to_string()));+ cx.notify();+ }+ }+ })+ .log_err();+ });+ self.url_import_task = Some(task);+ cx.notify();+ }+fn save_skill(&mut self, _: &SaveSkill, window: &mut Window, cx: &mut Context<Self>) {// Surface any field-level errors before attempting to save.self.recompute_name_error(cx);@@ -529,6 +801,69 @@ impl SkillCreator {cx.notify();}+ fn render_url_import(&self) -> impl IntoElement {+ v_flex()+ .min_h_0()+ .gap_2()+ .child(+ h_flex()+ .gap_1()+ .child(Label::new("Import from URL"))+ .child(Label::new("(optional)").color(Color::Muted)),+ )+ .child(self.url_editor.clone())+ .child(match &self.url_import_status {+ UrlImportStatus::Idle => Label::new(+ "Paste a GitHub .md URL. Zed will fetch it and fill out the skill form.",+ )+ .size(LabelSize::Small)+ .color(Color::Muted)+ .into_any_element(),+ UrlImportStatus::Fetching => {+ LoadingLabel::new("Fetching and parsing…").into_any_element()+ }+ UrlImportStatus::Error(error) => h_flex()+ .gap_1()+ .child(+ Icon::new(IconName::XCircle)+ .size(IconSize::Small)+ .color(Color::Error),+ )+ .child(+ Label::new(error.clone())+ .size(LabelSize::Small)+ .color(Color::Error),+ )+ .into_any_element(),+ })+ }++ fn render_form_fields(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ v_flex()+ .id("skill-creator-form-fields")+ .flex_1()+ .min_h_0()+ .gap_4()+ .child(+ v_flex()+ .gap_2()+ .child(Label::new("Front-matter"))+ .child(self.name_editor.clone())+ .child(self.description_editor.clone()),+ )+ .child(self.render_optional_params(cx))+ .child(Divider::horizontal())+ .child(self.render_scope_field(window, cx))+ .child(Divider::horizontal())+ .child(+ v_flex()+ .flex_1()+ .gap_2()+ .child(Label::new("Skill Content"))+ .child(self.render_body_field(window, cx)),+ )+ }+fn render_scope_field(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {let scopes = self.scopes.clone();let selected = self.selected_scope().cloned();@@ -808,24 +1143,9 @@ impl Render for SkillCreator {.min_h_0().gap_4().p_4()- .child(- v_flex()- .gap_2()- .child(Label::new("Front-matter"))- .child(self.name_editor.clone())- .child(self.description_editor.clone()),- )- .child(self.render_optional_params(cx))- .child(Divider::horizontal())- .child(self.render_scope_field(window, cx))+ .child(self.render_url_import()).child(Divider::horizontal())- .child(- v_flex()- .flex_1()- .gap_2()- .child(Label::new("Skill Content"))- .child(self.render_body_field(window, cx)),- ),+ .child(self.render_form_fields(window, cx)),).child(h_flex()@@ -843,6 +1163,223 @@ impl Render for SkillCreator {}}+async fn fetch_imported_skill_from_url(+ http_client: Arc<dyn HttpClient>,+ url: String,+) -> Result<ImportedSkill> {+ let github_token = std::env::var("GITHUB_TOKEN").ok().and_then(|token| {+ let token = token.trim().to_string();+ (!token.is_empty()).then_some(token)+ });+ fetch_imported_skill_from_url_with_github_token(http_client, url, github_token).await+}++async fn fetch_imported_skill_from_url_with_github_token(+ http_client: Arc<dyn HttpClient>,+ url: String,+ github_token: Option<String>,+) -> Result<ImportedSkill> {+ let raw_url = github_raw_url(&url)?;+ let (mut status, mut body) =+ fetch_skill_url(http_client.clone(), raw_url.as_str(), None).await?;++ if status == StatusCode::NOT_FOUND+ && let Some(github_token) = github_token.as_deref()+ {+ (status, body) = fetch_skill_url(http_client, raw_url.as_str(), Some(github_token)).await?;+ }++ if !status.is_success() {+ return Err(github_fetch_error(status, &body));+ }++ if body.len() > MAX_SKILL_FILE_SIZE {+ anyhow::bail!(+ "SKILL.md file exceeds maximum size of {}KB",+ MAX_SKILL_FILE_SIZE / 1024+ );+ }++ let content = String::from_utf8(body).context("GitHub response was not valid UTF-8")?;+ parse_imported_skill(&content, raw_url.as_str())+}++async fn fetch_skill_url(+ http_client: Arc<dyn HttpClient>,+ raw_url: &str,+ github_token: Option<&str>,+) -> Result<(StatusCode, Vec<u8>)> {+ let request = Request::get(raw_url)+ .follow_redirects(http_client::RedirectPolicy::FollowAll)+ .when_some(github_token, |builder, token| {+ builder.header("Authorization", format!("Bearer {token}"))+ })+ .body(AsyncBody::default())?;++ let mut response = http_client+ .send(request)+ .await+ .with_context(|| format!("failed to fetch {raw_url}"))?;++ let status = response.status();+ let mut body = Vec::new();+ response+ .body_mut()+ .take(MAX_SKILL_FILE_SIZE as u64 + 1)+ .read_to_end(&mut body)+ .await+ .context("failed to read response body")?;++ Ok((status, body))+}++fn github_fetch_error(status: StatusCode, body: &[u8]) -> anyhow::Error {+ let mut message = if status == StatusCode::NOT_FOUND {+ "GitHub returned 404 while fetching the skill; no repository exists at this URL, or it is private"+ .to_string()+ } else {+ format!(+ "GitHub returned {} while fetching the skill",+ status.as_u16()+ )+ };++ let response_text = truncated_response_body_for_error(body);+ if !response_text.is_empty() {+ message.push_str(": ");+ message.push_str(&response_text);+ }++ anyhow!(message)+}++pub fn is_supported_skill_url(input: &str) -> bool {+ github_raw_url(input).is_ok()+}++fn github_raw_url(input: &str) -> Result<String> {+ let url = Url::parse(input.trim()).context("Enter a valid GitHub URL")?;+ if url.scheme() != "https" {+ anyhow::bail!("GitHub skill URLs must use https://");+ }++ let host = url+ .host_str()+ .ok_or_else(|| anyhow!("Enter a valid GitHub URL"))?;+ let path_segments = url+ .path_segments()+ .ok_or_else(|| anyhow!("Enter a valid GitHub URL"))?+ .collect::<Vec<_>>();++ match host {+ "github.com" => github_blob_raw_url(&path_segments),+ "raw.githubusercontent.com" => {+ ensure_markdown_path(&path_segments)?;+ Ok(url.into())+ }+ _ => anyhow::bail!("Paste a GitHub .md URL"),+ }+}++fn github_blob_raw_url(path_segments: &[&str]) -> Result<String> {+ let [owner, repo, kind, reference, file_path @ ..] = path_segments else {+ anyhow::bail!("Paste a GitHub blob URL that points to a .md file");+ };++ if *kind != "blob" {+ anyhow::bail!("Paste a GitHub blob URL that points to a .md file");+ }++ ensure_markdown_path(file_path)?;+ Ok(format!(+ "https://raw.githubusercontent.com/{owner}/{repo}/{reference}/{}",+ file_path.join("/")+ ))+}++fn ensure_markdown_path(path_segments: &[&str]) -> Result<()> {+ let Some(file_name) = path_segments.last() else {+ anyhow::bail!("Paste a GitHub .md URL");+ };++ if !file_name.to_ascii_lowercase().ends_with(".md") {+ anyhow::bail!("Paste a GitHub URL that points to a .md file");+ }++ Ok(())+}++fn parse_imported_skill(content: &str, source_url: &str) -> Result<ImportedSkill> {+ if content.trim_start().starts_with("---") {+ let (metadata, body) = parse_skill_file_content(content)?;+ return Ok(ImportedSkill {+ name: metadata.name,+ description: metadata.description,+ body: body.trim().to_string(),+ disable_model_invocation: metadata.disable_model_invocation,+ });+ }++ Ok(ImportedSkill {+ name: derived_skill_name_from_url(source_url).unwrap_or_else(|| "imported-skill".into()),+ description: derived_description_from_markdown(content).unwrap_or_default(),+ body: content.trim().to_string(),+ disable_model_invocation: false,+ })+}++fn derived_skill_name_from_url(source_url: &str) -> Option<String> {+ let url = Url::parse(source_url).ok()?;+ let file_name = url.path_segments()?.next_back()?;+ let stem = file_name+ .rsplit_once('.')+ .and_then(|(stem, extension)| extension.eq_ignore_ascii_case("md").then_some(stem))+ .unwrap_or(file_name);+ slugify_skill_name(stem)+}++fn truncated_response_body_for_error(body: &[u8]) -> String {+ let text = String::from_utf8_lossy(body);+ let text = text.trim();+ if text.len() <= URL_IMPORT_ERROR_BODY_MAX_LEN {+ return text.to_string();+ }++ let mut end = URL_IMPORT_ERROR_BODY_MAX_LEN;+ while !text.is_char_boundary(end) {+ end -= 1;+ }+ format!("{}…", text[..end].trim_end())+}++fn derived_description_from_markdown(content: &str) -> Option<String> {+ content.lines().find_map(|line| {+ let line = line.trim();+ if line.is_empty() || line == "---" {+ return None;+ }++ let text = line.trim_start_matches('#').trim();+ if text.is_empty() {+ None+ } else {+ Some(truncate_description(text))+ }+ })+}++fn truncate_description(description: &str) -> String {+ if description.len() <= MAX_SKILL_DESCRIPTION_LEN {+ return description.to_string();+ }++ let mut end = MAX_SKILL_DESCRIPTION_LEN;+ while !description.is_char_boundary(end) {+ end -= 1;+ }+ description[..end].trim().to_string()+}+/// Serialize the SKILL.md file to disk at `<skills_dir>/<name>/SKILL.md`.////// Refuses to overwrite an existing directory at `<skills_dir>/<name>`. The@@ -932,7 +1469,125 @@ mod tests {use super::*;use agent_skills::{SkillSource, parse_skill_frontmatter};use fs::FakeFs;- use std::path::Path;+ use std::{+ collections::VecDeque,+ io,+ path::Path,+ pin::Pin,+ sync::{Arc, Mutex},+ task::{self, Poll},+ };++ struct TestHttpClient {+ responses: Mutex<VecDeque<(StatusCode, AsyncBody)>>,+ authorization_headers: Mutex<Vec<Option<String>>>,+ }++ impl TestHttpClient {+ fn new(status: u16, body: AsyncBody) -> Arc<dyn HttpClient> {+ Self::new_sequence(vec![(status, body)])+ }++ fn new_sequence(responses: Vec<(u16, AsyncBody)>) -> Arc<Self> {+ Arc::new(Self {+ responses: Mutex::new(+ responses+ .into_iter()+ .map(|(status, body)| {+ (+ StatusCode::from_u16(status)+ .expect("test status code should be valid"),+ body,+ )+ })+ .collect(),+ ),+ authorization_headers: Mutex::new(Vec::new()),+ })+ }++ fn authorization_headers(&self) -> Vec<Option<String>> {+ self.authorization_headers+ .lock()+ .expect("authorization header mutex should not be poisoned")+ .clone()+ }+ }++ impl HttpClient for TestHttpClient {+ fn user_agent(&self) -> Option<&http_client::http::HeaderValue> {+ None+ }++ fn proxy(&self) -> Option<&Url> {+ None+ }++ fn send(+ &self,+ req: http_client::Request<AsyncBody>,+ ) -> futures::future::BoxFuture<'static, Result<http_client::Response<AsyncBody>>> {+ let authorization_header = req+ .headers()+ .get("Authorization")+ .and_then(|header| header.to_str().ok())+ .map(ToString::to_string);++ match self.authorization_headers.lock() {+ Ok(mut authorization_headers) => authorization_headers.push(authorization_header),+ Err(_) => {+ return Box::pin(async {+ Err(anyhow::anyhow!(+ "test authorization header mutex was poisoned"+ ))+ });+ }+ }++ let response = match self.responses.lock() {+ Ok(mut responses) => responses.pop_front(),+ Err(_) => {+ return Box::pin(async {+ Err(anyhow::anyhow!("test response body mutex was poisoned"))+ });+ }+ };+ let Some((status, body)) = response else {+ return Box::pin(async {+ Err(anyhow::anyhow!("test response body was already consumed"))+ });+ };++ Box::pin(async move {+ http_client::Response::builder()+ .status(status)+ .body(body)+ .map_err(anyhow::Error::new)+ })+ }+ }++ struct FailsAfterLimitReader {+ bytes_read: usize,+ limit: usize,+ }++ impl futures::AsyncRead for FailsAfterLimitReader {+ fn poll_read(+ mut self: Pin<&mut Self>,+ _cx: &mut task::Context<'_>,+ buffer: &mut [u8],+ ) -> Poll<io::Result<usize>> {+ if self.bytes_read >= self.limit {+ return Poll::Ready(Err(io::Error::other("read past limit")));+ }++ let byte_count = buffer.len().min(self.limit - self.bytes_read);+ buffer[..byte_count].fill(b'a');+ self.bytes_read += byte_count;+ Poll::Ready(Ok(byte_count))+ }+ }// Name and description validation rules are unit-tested in// `agent_skills`, which owns `validate_name` / `validate_description`@@ -983,6 +1638,177 @@ mod tests {assert_eq!(skill.description, tricky);}+ #[test]+ fn github_blob_url_converts_to_raw_url() {+ let source_url = "https://github.com/cursor/plugins/blob/3347cbab5b54136f6fba0994c3a01a56f7fb7fca/cursor-team-kit/agents/thermo-nuclear-code-quality-review.md";+ let raw_url = github_raw_url(source_url).expect("GitHub blob URLs should be importable");++ assert_eq!(+ raw_url,+ "https://raw.githubusercontent.com/cursor/plugins/3347cbab5b54136f6fba0994c3a01a56f7fb7fca/cursor-team-kit/agents/thermo-nuclear-code-quality-review.md"+ );+ assert!(is_supported_skill_url(source_url));+ assert!(!is_supported_skill_url(+ "https://example.com/not-a-skill.md"+ ));+ }++ #[test]+ fn derived_skill_name_strips_markdown_extension_case_insensitively() {+ let name = derived_skill_name_from_url(+ "https://raw.githubusercontent.com/owner/repo/main/README.MD",+ )+ .expect("name should be derived from Markdown URL");++ assert_eq!(name, "readme");+ }++ #[test]+ fn parse_imported_skill_reads_frontmatter_and_body() {+ let imported = parse_imported_skill(+ "---\nname: imported-skill\ndescription: Imported from GitHub.\ndisable-model-invocation: true\n---\n\n# Instructions\n\nDo the thing.\n",+ "https://raw.githubusercontent.com/owner/repo/main/imported-skill.md",+ )+ .expect("valid skill frontmatter should parse");++ assert_eq!(imported.name, "imported-skill");+ assert_eq!(imported.description, "Imported from GitHub.");+ assert_eq!(imported.body, "# Instructions\n\nDo the thing.");+ assert!(imported.disable_model_invocation);+ }++ #[test]+ fn parse_imported_skill_falls_back_to_markdown_when_frontmatter_is_missing() {+ let imported = parse_imported_skill(+ "# Code Review\n\nReview code for maintainability.",+ "https://raw.githubusercontent.com/owner/repo/main/code-review.md",+ )+ .expect("plain markdown should still import");++ assert_eq!(imported.name, "code-review");+ assert_eq!(imported.description, "Code Review");+ assert_eq!(+ imported.body,+ "# Code Review\n\nReview code for maintainability."+ );+ assert!(!imported.disable_model_invocation);+ }++ #[test]+ fn parse_imported_skill_reuses_skill_metadata_validation() {+ let error = parse_imported_skill(+ "---\nname: Imported Skill\ndescription: Imported from GitHub.\n---\n\n# Instructions\n",+ "https://raw.githubusercontent.com/owner/repo/main/imported-skill.md",+ )+ .expect_err("invalid skill metadata should be rejected instead of imported");+ let message = error.to_string();++ assert!(+ message.contains("Skill name must contain only lowercase letters"),+ "error should come from shared skill metadata validation, got: {message}"+ );+ }++ #[gpui::test]+ async fn fetch_imported_skill_retries_404_with_github_token(_cx: &mut gpui::TestAppContext) {+ let client = TestHttpClient::new_sequence(vec![+ (404, AsyncBody::from("Not Found")),+ (200, AsyncBody::from("# Imported Skill\n\nDo the thing.")),+ ]);++ let imported = fetch_imported_skill_from_url_with_github_token(+ client.clone(),+ "https://github.com/owner/repo/blob/main/skill.md".to_string(),+ Some("secret-token".to_string()),+ )+ .await+ .expect("private repo fallback should retry with the GitHub token");++ assert_eq!(imported.name, "skill");+ assert_eq!(imported.description, "Imported Skill");+ assert_eq!(+ client.authorization_headers(),+ vec![None, Some("Bearer secret-token".to_string())]+ );+ }++ #[gpui::test]+ async fn fetch_imported_skill_reports_private_or_missing_for_404(+ _cx: &mut gpui::TestAppContext,+ ) {+ let client = TestHttpClient::new_sequence(vec![(404, AsyncBody::from("Not Found"))]);++ let error = fetch_imported_skill_from_url_with_github_token(+ client.clone(),+ "https://github.com/owner/repo/blob/main/skill.md".to_string(),+ None,+ )+ .await+ .expect_err("404 without a GitHub token should fail");+ let message = error.to_string();++ assert!(+ message.contains("no repository exists at this URL, or it is private"),+ "404 error should mention private repositories, got: {message}"+ );+ assert_eq!(client.authorization_headers(), vec![None]);+ }++ #[gpui::test]+ async fn fetch_imported_skill_stops_reading_after_size_limit(_cx: &mut gpui::TestAppContext) {+ let client = TestHttpClient::new(+ 200,+ AsyncBody::from_reader(FailsAfterLimitReader {+ bytes_read: 0,+ limit: MAX_SKILL_FILE_SIZE + 1,+ }),+ );++ let error = fetch_imported_skill_from_url(+ client,+ "https://github.com/owner/repo/blob/main/skill.md".to_string(),+ )+ .await+ .expect_err("oversized responses should be rejected");+ let message = error.to_string();++ assert!(+ message.contains("exceeds maximum size"),+ "error should report the skill size limit, got: {message}"+ );+ assert!(+ !message.contains("failed to read response body"),+ "reader should not be polled past the limit, got: {message}"+ );+ }++ #[gpui::test]+ async fn fetch_imported_skill_truncates_error_response_body(_cx: &mut gpui::TestAppContext) {+ let body = format!(+ "{}tail-that-should-not-appear",+ "x".repeat(URL_IMPORT_ERROR_BODY_MAX_LEN + 20)+ );+ let client = TestHttpClient::new(500, AsyncBody::from(body));++ let error = fetch_imported_skill_from_url(+ client,+ "https://github.com/owner/repo/blob/main/skill.md".to_string(),+ )+ .await+ .expect_err("non-success responses should be rejected");+ let message = error.to_string();++ assert!(message.contains("GitHub returned 500"));+ assert!(+ message.ends_with('…'),+ "error body should be visibly truncated, got: {message}"+ );+ assert!(+ !message.contains("tail-that-should-not-appear"),+ "error body should not include the unbounded tail, got: {message}"+ );+ }+#[gpui::test]async fn write_skill_to_disk_creates_directory_and_file(cx: &mut gpui::TestAppContext) {let fs = FakeFs::new(cx.executor());diff --git a/crates/zed_actions/src/lib.rs b/crates/zed_actions/src/lib.rsindex ce1a1458dbe..7d51fcbd70e 100644--- a/crates/zed_actions/src/lib.rs+++ b/crates/zed_actions/src/lib.rs@@ -573,6 +573,8 @@ pub mod assistant {FocusAgent,/// Opens the skill creator window for creating a new skill.OpenSkillCreator,+ /// Opens the skill creator window to import a skill from a GitHub URL.+ CreateSkillFromUrl,]);diff --git a/docs/src/ai/skills.md b/docs/src/ai/skills.mdindex 2662b33e160..f6093262aed 100644--- a/docs/src/ai/skills.md+++ b/docs/src/ai/skills.md@@ -17,6 +17,8 @@ Zed includes a built-in `create-skill` skill — invoke it with `/create-skill`You can also open the Skill Creator from the Agent Panel using {#kb agent::OpenRulesLibrary}, or by clicking `...` and selecting **Skills**. Outside the panel, use the {#action agent::OpenSkillCreator} action from the command palette. It opens a window where you fill in the skill's name, description, scope (global or project-local), body, and optionally toggle `disable-model-invocation`.+Lastly, it's also possible to add a skill through importing it from an existing GitHub Markdown file. Open the command paeltte and look for the {#action agent::CreateSkillFromUrl} action. If your clipboard contains a supported GitHub `.md` URL, Zed pre-fills and fetches it automatically.+See [Skill format](#skill-format) below for the full format reference.### From the skills.sh Registry {#from-the-registry}