An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support managing agent skill files in settings https://github.com/siyuan-note/siyuan/issues/19227
Daniel3233f17117e7
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex b68febda53..9c0ea069ac 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "مهارات مساحة العمل",+ "agentWorkspaceSkillsTip": "إدارة المهارات وملفات Markdown في مساحة العمل الحالية",+ "agentSkillManager": "إدارة المهارات",+ "agentSkillNew": "مهارة جديدة",+ "agentSkillNewFile": "ملف Markdown جديد",+ "agentSkillNewFolder": "مجلد جديد",+ "agentSkillSearch": "البحث في ملفات المهارات",+ "agentSkillSource": "مصدر Markdown",+ "agentSkillDeleteTip": "سيُحذف الملف أو المجلد المحدد وكل محتوياته نهائيًا؛ لا يمكن التراجع عن هذا الإجراء",+ "agentSkillNameTip": "أدخل اسمًا صالحًا للملف أو المجلد",+ "agentSkillResourceTip": "لا يمكن فتح موقع هذا الملف إلا في تطبيق سطح المكتب المحلي","agentStreamingMarkdown": "معاينة Markdown أثناء البث","agentStreamingMarkdownTip": "معاينة Markdown أثناء رد الوكيل؛ قد يؤثر ذلك في الأداء","taskStatus": "حالة المهمة",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 0bfa0c0cc5..18a8c127c6 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "Arbeitsbereich-Fähigkeiten",+ "agentWorkspaceSkillsTip": "Fähigkeiten und Markdown-Dateien im aktuellen Arbeitsbereich verwalten",+ "agentSkillManager": "Fähigkeitenverwaltung",+ "agentSkillNew": "Neue Fähigkeit",+ "agentSkillNewFile": "Neue Markdown-Datei",+ "agentSkillNewFolder": "Neuer Ordner",+ "agentSkillSearch": "Fähigkeitsdateien durchsuchen",+ "agentSkillSource": "Markdown-Quelltext",+ "agentSkillDeleteTip": "Die ausgewählte Datei oder der Ordner samt Inhalt wird dauerhaft gelöscht; dies kann nicht rückgängig gemacht werden",+ "agentSkillNameTip": "Gültigen Datei- oder Ordnernamen eingeben",+ "agentSkillResourceTip": "Der Speicherort dieser Datei kann nur im lokalen Desktop-Client geöffnet werden","agentStreamingMarkdown": "Markdown-Vorschau beim Streaming","agentStreamingMarkdownTip": "Markdown während der Agentenantwort anzeigen; kann die Leistung beeinträchtigen","taskStatus": "Aufgabenstatus",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex a9ba5de515..209a68defb 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "Workspace skills",+ "agentWorkspaceSkillsTip": "Manage skills and Markdown files in the current workspace",+ "agentSkillManager": "Skill manager",+ "agentSkillNew": "New skill",+ "agentSkillNewFile": "New Markdown file",+ "agentSkillNewFolder": "New folder",+ "agentSkillSearch": "Search skill files",+ "agentSkillSource": "Markdown source",+ "agentSkillDeleteTip": "The selected file or folder and all its contents will be permanently deleted; this cannot be undone",+ "agentSkillNameTip": "Enter a valid file or folder name",+ "agentSkillResourceTip": "This file's location can only be opened in the local desktop client","agentStreamingMarkdown": "Streaming Markdown preview","agentStreamingMarkdownTip": "Preview Markdown while the agent responds; may affect performance","taskStatus": "Task status",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex e98d5b0846..860c0e1289 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "Habilidades del espacio de trabajo",+ "agentWorkspaceSkillsTip": "Gestionar habilidades y archivos Markdown del espacio de trabajo actual",+ "agentSkillManager": "Gestor de habilidades",+ "agentSkillNew": "Nueva habilidad",+ "agentSkillNewFile": "Nuevo archivo Markdown",+ "agentSkillNewFolder": "Nueva carpeta",+ "agentSkillSearch": "Buscar archivos de habilidades",+ "agentSkillSource": "Código fuente Markdown",+ "agentSkillDeleteTip": "El archivo o la carpeta seleccionados y todo su contenido se eliminarán permanentemente; esta acción no se puede deshacer",+ "agentSkillNameTip": "Introduce un nombre válido de archivo o carpeta",+ "agentSkillResourceTip": "La ubicación de este archivo solo se puede abrir en el cliente de escritorio local","agentStreamingMarkdown": "Vista previa de Markdown en streaming","agentStreamingMarkdownTip": "Previsualizar Markdown durante la respuesta del agente; puede afectar al rendimiento","taskStatus": "Estado de la tarea",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex ca9e354b7b..f14422ec77 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "Compétences de l’espace de travail",+ "agentWorkspaceSkillsTip": "Gérer les compétences et les fichiers Markdown de l’espace de travail actuel",+ "agentSkillManager": "Gestion des compétences",+ "agentSkillNew": "Nouvelle compétence",+ "agentSkillNewFile": "Nouveau fichier Markdown",+ "agentSkillNewFolder": "Nouveau dossier",+ "agentSkillSearch": "Rechercher des fichiers de compétences",+ "agentSkillSource": "Source Markdown",+ "agentSkillDeleteTip": "Le fichier ou dossier sélectionné et tout son contenu seront supprimés définitivement ; cette action est irréversible",+ "agentSkillNameTip": "Saisissez un nom de fichier ou de dossier valide",+ "agentSkillResourceTip": "L’emplacement de ce fichier ne peut être ouvert que dans le client de bureau local","agentStreamingMarkdown": "Aperçu Markdown en continu","agentStreamingMarkdownTip": "Prévisualiser le Markdown pendant la réponse de l’agent ; peut affecter les performances","taskStatus": "État de la tâche",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 37a06c2229..df15045e4d 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "מיומנויות סביבת העבודה",+ "agentWorkspaceSkillsTip": "ניהול מיומנויות וקובצי Markdown בסביבת העבודה הנוכחית",+ "agentSkillManager": "מנהל המיומנויות",+ "agentSkillNew": "מיומנות חדשה",+ "agentSkillNewFile": "קובץ Markdown חדש",+ "agentSkillNewFolder": "תיקייה חדשה",+ "agentSkillSearch": "חיפוש בקובצי מיומנויות",+ "agentSkillSource": "קוד מקור Markdown",+ "agentSkillDeleteTip": "הקובץ או התיקייה שנבחרו וכל תוכנם יימחקו לצמיתות; לא ניתן לבטל פעולה זו",+ "agentSkillNameTip": "יש להזין שם תקין לקובץ או לתיקייה",+ "agentSkillResourceTip": "ניתן לפתוח את מיקום הקובץ רק ביישום שולחן העבודה המקומי","agentStreamingMarkdown": "תצוגה מקדימה של Markdown בזמן הזרמה","agentStreamingMarkdownTip": "תצוגה מקדימה של Markdown בזמן תגובת הסוכן; עשויה להשפיע על הביצועים","taskStatus": "מצב משימה",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 00dc86c9fd..565230af1e 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "कार्यक्षेत्र कौशल",+ "agentWorkspaceSkillsTip": "वर्तमान कार्यक्षेत्र में कौशल और Markdown फ़ाइलें प्रबंधित करें",+ "agentSkillManager": "कौशल प्रबंधक",+ "agentSkillNew": "नया कौशल",+ "agentSkillNewFile": "नई Markdown फ़ाइल",+ "agentSkillNewFolder": "नया फ़ोल्डर",+ "agentSkillSearch": "कौशल फ़ाइलें खोजें",+ "agentSkillSource": "Markdown स्रोत",+ "agentSkillDeleteTip": "चुनी गई फ़ाइल या फ़ोल्डर और उसकी सारी सामग्री स्थायी रूप से हटा दी जाएगी; इस कार्रवाई को पूर्ववत नहीं किया जा सकता",+ "agentSkillNameTip": "मान्य फ़ाइल या फ़ोल्डर का नाम दर्ज करें",+ "agentSkillResourceTip": "इस फ़ाइल का स्थान केवल स्थानीय डेस्कटॉप क्लाइंट में खोला जा सकता है","agentStreamingMarkdown": "स्ट्रीमिंग Markdown पूर्वावलोकन","agentStreamingMarkdownTip": "एजेंट के उत्तर के दौरान Markdown का पूर्वावलोकन करें; प्रदर्शन प्रभावित हो सकता है","taskStatus": "कार्य की स्थिति",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex ae9dac66bf..a03fa883c6 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "Keterampilan ruang kerja",+ "agentWorkspaceSkillsTip": "Kelola keterampilan dan berkas Markdown di ruang kerja saat ini",+ "agentSkillManager": "Pengelola keterampilan",+ "agentSkillNew": "Keterampilan baru",+ "agentSkillNewFile": "Berkas Markdown baru",+ "agentSkillNewFolder": "Folder baru",+ "agentSkillSearch": "Cari berkas keterampilan",+ "agentSkillSource": "Sumber Markdown",+ "agentSkillDeleteTip": "Berkas atau folder yang dipilih beserta seluruh isinya akan dihapus secara permanen; tindakan ini tidak dapat dibatalkan",+ "agentSkillNameTip": "Masukkan nama berkas atau folder yang valid",+ "agentSkillResourceTip": "Lokasi berkas ini hanya dapat dibuka di klien desktop lokal","agentStreamingMarkdown": "Pratinjau Markdown saat streaming","agentStreamingMarkdownTip": "Pratinjau Markdown saat agen merespons; dapat memengaruhi kinerja","taskStatus": "Status tugas",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 024d4ae23c..ee8c97a7cd 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "Competenze dell'area di lavoro",+ "agentWorkspaceSkillsTip": "Gestisci competenze e file Markdown nell'area di lavoro corrente",+ "agentSkillManager": "Gestione competenze",+ "agentSkillNew": "Nuova competenza",+ "agentSkillNewFile": "Nuovo file Markdown",+ "agentSkillNewFolder": "Nuova cartella",+ "agentSkillSearch": "Cerca file delle competenze",+ "agentSkillSource": "Sorgente Markdown",+ "agentSkillDeleteTip": "Il file o la cartella selezionati e tutto il loro contenuto verranno eliminati definitivamente; l'operazione non può essere annullata",+ "agentSkillNameTip": "Inserisci un nome valido per il file o la cartella",+ "agentSkillResourceTip": "La posizione di questo file può essere aperta solo nel client desktop locale","agentStreamingMarkdown": "Anteprima Markdown in streaming","agentStreamingMarkdownTip": "Mostra l’anteprima Markdown durante la risposta dell’agente; può influire sulle prestazioni","taskStatus": "Stato dell'attività",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 884044574a..ce264fa534 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "ワークスペースのスキル",+ "agentWorkspaceSkillsTip": "現在のワークスペースのスキルと Markdown ファイルを管理",+ "agentSkillManager": "スキル管理",+ "agentSkillNew": "新しいスキル",+ "agentSkillNewFile": "新しい Markdown ファイル",+ "agentSkillNewFolder": "新しいフォルダー",+ "agentSkillSearch": "スキルファイルを検索",+ "agentSkillSource": "Markdown ソース",+ "agentSkillDeleteTip": "選択したファイルまたはフォルダーとその内容をすべて完全に削除します。この操作は元に戻せません",+ "agentSkillNameTip": "有効なファイル名またはフォルダー名を入力してください",+ "agentSkillResourceTip": "このファイルの保存場所はローカルのデスクトップクライアントでのみ開けます","agentStreamingMarkdown": "ストリーミング Markdown プレビュー","agentStreamingMarkdownTip": "応答中に Markdown をプレビューします(パフォーマンスに影響する場合があります)","taskStatus": "タスクの状態",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 926d549a4a..d955bc2a88 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "작업 공간 스킬",+ "agentWorkspaceSkillsTip": "현재 작업 공간의 스킬과 Markdown 파일 관리",+ "agentSkillManager": "스킬 관리",+ "agentSkillNew": "새 스킬",+ "agentSkillNewFile": "새 Markdown 파일",+ "agentSkillNewFolder": "새 폴더",+ "agentSkillSearch": "스킬 파일 검색",+ "agentSkillSource": "Markdown 소스",+ "agentSkillDeleteTip": "선택한 파일 또는 폴더와 그 안의 모든 내용이 영구적으로 삭제되며, 이 작업은 되돌릴 수 없습니다",+ "agentSkillNameTip": "올바른 파일 또는 폴더 이름을 입력하세요",+ "agentSkillResourceTip": "이 파일의 위치는 로컬 데스크톱 클라이언트에서만 열 수 있습니다","agentStreamingMarkdown": "스트리밍 Markdown 미리보기","agentStreamingMarkdownTip": "에이전트 응답 중 Markdown을 미리 표시하며, 성능에 영향을 줄 수 있습니다","taskStatus": "작업 상태",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex f831420511..159a7bcb0f 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "Werkruimtevaardigheden",+ "agentWorkspaceSkillsTip": "Vaardigheden en Markdown-bestanden in de huidige werkruimte beheren",+ "agentSkillManager": "Vaardighedenbeheer",+ "agentSkillNew": "Nieuwe vaardigheid",+ "agentSkillNewFile": "Nieuw Markdown-bestand",+ "agentSkillNewFolder": "Nieuwe map",+ "agentSkillSearch": "Vaardigheidsbestanden zoeken",+ "agentSkillSource": "Markdown-broncode",+ "agentSkillDeleteTip": "Het geselecteerde bestand of de geselecteerde map en alle inhoud worden permanent verwijderd; dit kan niet ongedaan worden gemaakt",+ "agentSkillNameTip": "Voer een geldige bestands- of mapnaam in",+ "agentSkillResourceTip": "De locatie van dit bestand kan alleen in de lokale desktopclient worden geopend","agentStreamingMarkdown": "Markdown-voorbeeld tijdens streaming","agentStreamingMarkdownTip": "Markdown tijdens het antwoord van de agent weergeven; kan de prestaties beïnvloeden","taskStatus": "Taakstatus",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 9c2deafaca..2865dae0f5 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "Umiejętności przestrzeni roboczej",+ "agentWorkspaceSkillsTip": "Zarządzaj umiejętnościami i plikami Markdown w bieżącej przestrzeni roboczej",+ "agentSkillManager": "Menedżer umiejętności",+ "agentSkillNew": "Nowa umiejętność",+ "agentSkillNewFile": "Nowy plik Markdown",+ "agentSkillNewFolder": "Nowy folder",+ "agentSkillSearch": "Szukaj plików umiejętności",+ "agentSkillSource": "Źródło Markdown",+ "agentSkillDeleteTip": "Wybrany plik lub folder wraz z całą zawartością zostanie trwale usunięty; tej operacji nie można cofnąć",+ "agentSkillNameTip": "Wprowadź prawidłową nazwę pliku lub folderu",+ "agentSkillResourceTip": "Lokalizację tego pliku można otworzyć tylko w lokalnym kliencie komputerowym","agentStreamingMarkdown": "Podgląd Markdown podczas przesyłania","agentStreamingMarkdownTip": "Podgląd Markdown podczas odpowiedzi agenta; może wpływać na wydajność","taskStatus": "Stan zadania",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 639e08593a..3d651ca7a9 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "Habilidades do espaço de trabalho",+ "agentWorkspaceSkillsTip": "Gerenciar habilidades e arquivos Markdown no espaço de trabalho atual",+ "agentSkillManager": "Gerenciador de habilidades",+ "agentSkillNew": "Nova habilidade",+ "agentSkillNewFile": "Novo arquivo Markdown",+ "agentSkillNewFolder": "Nova pasta",+ "agentSkillSearch": "Pesquisar arquivos de habilidades",+ "agentSkillSource": "Código-fonte Markdown",+ "agentSkillDeleteTip": "O arquivo ou a pasta selecionados e todo o seu conteúdo serão excluídos permanentemente; esta ação não pode ser desfeita",+ "agentSkillNameTip": "Insira um nome válido de arquivo ou pasta",+ "agentSkillResourceTip": "O local deste arquivo só pode ser aberto no cliente de desktop local","agentStreamingMarkdown": "Prévia de Markdown durante o streaming","agentStreamingMarkdownTip": "Pré-visualizar Markdown durante a resposta do agente; pode afetar o desempenho","taskStatus": "Status da tarefa",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 466bed1e7d..df0caa9c60 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "Навыки рабочего пространства",+ "agentWorkspaceSkillsTip": "Управление навыками и файлами Markdown в текущем рабочем пространстве",+ "agentSkillManager": "Управление навыками",+ "agentSkillNew": "Новый навык",+ "agentSkillNewFile": "Новый файл Markdown",+ "agentSkillNewFolder": "Новая папка",+ "agentSkillSearch": "Поиск файлов навыков",+ "agentSkillSource": "Исходный текст Markdown",+ "agentSkillDeleteTip": "Выбранный файл или папка со всем содержимым будут удалены безвозвратно; это действие нельзя отменить",+ "agentSkillNameTip": "Введите допустимое имя файла или папки",+ "agentSkillResourceTip": "Расположение этого файла можно открыть только в локальном настольном клиенте","agentStreamingMarkdown": "Предпросмотр Markdown при потоковом выводе","agentStreamingMarkdownTip": "Предпросмотр Markdown во время ответа агента; может влиять на производительность","taskStatus": "Статус задачи",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex af5a2748d3..23391a4858 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "Zručnosti pracovného priestoru",+ "agentWorkspaceSkillsTip": "Správa zručností a súborov Markdown v aktuálnom pracovnom priestore",+ "agentSkillManager": "Správca zručností",+ "agentSkillNew": "Nová zručnosť",+ "agentSkillNewFile": "Nový súbor Markdown",+ "agentSkillNewFolder": "Nový priečinok",+ "agentSkillSearch": "Hľadať súbory zručností",+ "agentSkillSource": "Zdrojový text Markdown",+ "agentSkillDeleteTip": "Vybraný súbor alebo priečinok so všetkým obsahom sa natrvalo odstráni; túto akciu nemožno vrátiť späť",+ "agentSkillNameTip": "Zadajte platný názov súboru alebo priečinka",+ "agentSkillResourceTip": "Umiestnenie tohto súboru možno otvoriť iba v lokálnom počítačovom klientovi","agentStreamingMarkdown": "Náhľad Markdown počas streamovania","agentStreamingMarkdownTip": "Náhľad Markdown počas odpovede agenta; môže ovplyvniť výkon","taskStatus": "Stav úlohy",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex 7135dc1526..8bffd54f35 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "Вештине радног простора",+ "agentWorkspaceSkillsTip": "Управљајте вештинама и Markdown датотекама у тренутном радном простору",+ "agentSkillManager": "Управљање вештинама",+ "agentSkillNew": "Нова вештина",+ "agentSkillNewFile": "Нова Markdown датотека",+ "agentSkillNewFolder": "Нова фасцикла",+ "agentSkillSearch": "Претражи датотеке вештина",+ "agentSkillSource": "Markdown извор",+ "agentSkillDeleteTip": "Изабрана датотека или фасцикла и сав њен садржај биће трајно обрисани; ова радња се не може опозвати",+ "agentSkillNameTip": "Унесите важеће име датотеке или фасцикле",+ "agentSkillResourceTip": "Локација ове датотеке може се отворити само у локалном десктоп клијенту","agentStreamingMarkdown": "Преглед Markdown-а током стримовања","agentStreamingMarkdownTip": "Преглед Markdown-а током одговора агента; може утицати на перформансе","taskStatus": "Статус задатка",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 6e8b117960..ed148a1566 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "ทักษะของพื้นที่ทำงาน",+ "agentWorkspaceSkillsTip": "จัดการทักษะและไฟล์ Markdown ในพื้นที่ทำงานปัจจุบัน",+ "agentSkillManager": "ตัวจัดการทักษะ",+ "agentSkillNew": "ทักษะใหม่",+ "agentSkillNewFile": "ไฟล์ Markdown ใหม่",+ "agentSkillNewFolder": "โฟลเดอร์ใหม่",+ "agentSkillSearch": "ค้นหาไฟล์ทักษะ",+ "agentSkillSource": "ซอร์ส Markdown",+ "agentSkillDeleteTip": "ไฟล์หรือโฟลเดอร์ที่เลือกและเนื้อหาทั้งหมดจะถูกลบอย่างถาวร และไม่สามารถเลิกทำได้",+ "agentSkillNameTip": "ป้อนชื่อไฟล์หรือโฟลเดอร์ที่ถูกต้อง",+ "agentSkillResourceTip": "เปิดตำแหน่งของไฟล์นี้ได้เฉพาะในไคลเอนต์เดสก์ท็อปบนเครื่องนี้เท่านั้น","agentStreamingMarkdown": "แสดงตัวอย่าง Markdown ระหว่างสตรีม","agentStreamingMarkdownTip": "แสดงตัวอย่าง Markdown ขณะเอเจนต์ตอบกลับ อาจส่งผลต่อประสิทธิภาพ","taskStatus": "สถานะงาน",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 55267f28d3..0ca096ce9a 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "Çalışma alanı becerileri",+ "agentWorkspaceSkillsTip": "Geçerli çalışma alanındaki becerileri ve Markdown dosyalarını yönetin",+ "agentSkillManager": "Beceri yöneticisi",+ "agentSkillNew": "Yeni beceri",+ "agentSkillNewFile": "Yeni Markdown dosyası",+ "agentSkillNewFolder": "Yeni klasör",+ "agentSkillSearch": "Beceri dosyalarını ara",+ "agentSkillSource": "Markdown kaynağı",+ "agentSkillDeleteTip": "Seçilen dosya veya klasör ve tüm içeriği kalıcı olarak silinecek; bu işlem geri alınamaz",+ "agentSkillNameTip": "Geçerli bir dosya veya klasör adı girin",+ "agentSkillResourceTip": "Bu dosyanın konumu yalnızca yerel masaüstü istemcisinde açılabilir","agentStreamingMarkdown": "Akış sırasında Markdown önizlemesi","agentStreamingMarkdownTip": "Ajan yanıt verirken Markdown önizlemesi göster; performansı etkileyebilir","taskStatus": "Görev durumu",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 2f0ea4ad51..1ca3d028c5 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "Навички робочого простору",+ "agentWorkspaceSkillsTip": "Керування навичками та файлами Markdown у поточному робочому просторі",+ "agentSkillManager": "Керування навичками",+ "agentSkillNew": "Нова навичка",+ "agentSkillNewFile": "Новий файл Markdown",+ "agentSkillNewFolder": "Нова тека",+ "agentSkillSearch": "Пошук файлів навичок",+ "agentSkillSource": "Вихідний текст Markdown",+ "agentSkillDeleteTip": "Вибраний файл або теку з усім вмістом буде видалено назавжди; цю дію неможливо скасувати",+ "agentSkillNameTip": "Введіть припустиму назву файлу або теки",+ "agentSkillResourceTip": "Розташування цього файлу можна відкрити лише в локальному настільному клієнті","agentStreamingMarkdown": "Попередній перегляд Markdown під час потокового виведення","agentStreamingMarkdownTip": "Попередній перегляд Markdown під час відповіді агента; може впливати на продуктивність","taskStatus": "Статус завдання",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex c5f03b5454..a87fb0cfb5 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "工作空间技能",+ "agentWorkspaceSkillsTip": "管理当前工作空间中的技能及 Markdown 文件",+ "agentSkillManager": "技能管理",+ "agentSkillNew": "新建技能",+ "agentSkillNewFile": "新建 Markdown 文件",+ "agentSkillNewFolder": "新建文件夹",+ "agentSkillSearch": "搜索技能文件",+ "agentSkillSource": "Markdown 源码",+ "agentSkillDeleteTip": "将永久删除所选文件或文件夹及其全部内容,此操作无法撤销",+ "agentSkillNameTip": "请输入有效的文件或文件夹名称",+ "agentSkillResourceTip": "此文件仅支持在本地桌面端打开文件位置","agentStreamingMarkdown": "流式 Markdown 预览","agentStreamingMarkdownTip": "在回复过程中预览 Markdown,可能影响性能","taskStatus": "任务状态",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex c8637d9ad5..df78a2cc84 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,15 @@{+ "agentWorkspaceSkills": "工作空間技能",+ "agentWorkspaceSkillsTip": "管理目前工作空間中的技能及 Markdown 檔案",+ "agentSkillManager": "技能管理",+ "agentSkillNew": "新增技能",+ "agentSkillNewFile": "新增 Markdown 檔案",+ "agentSkillNewFolder": "新增資料夾",+ "agentSkillSearch": "搜尋技能檔案",+ "agentSkillSource": "Markdown 原始碼",+ "agentSkillDeleteTip": "將永久刪除所選檔案或資料夾及其全部內容,此操作無法復原",+ "agentSkillNameTip": "請輸入有效的檔案或資料夾名稱",+ "agentSkillResourceTip": "此檔案僅支援在本機桌面端開啟檔案位置","agentStreamingMarkdown": "串流 Markdown 預覽","agentStreamingMarkdownTip": "在回覆過程中預覽 Markdown,可能影響效能","taskStatus": "任務狀態",diff --git a/app/src/ai/skills/manager.ts b/app/src/ai/skills/manager.tsnew file mode 100644index 0000000000..dad2e6a79d--- /dev/null+++ b/app/src/ai/skills/manager.ts@@ -0,0 +1,437 @@+import {Dialog} from "../../dialog";+import {openInputDialog} from "../../dialog/inputDialog";+import {showMessage} from "../../dialog/message";+import {fetchSyncPost} from "../../util/fetch";+import {escapeHtml} from "../../util/escape";+import {getFileRenameTarget, getFileTree} from "../../util/fileTree";+import {getHostCapabilities} from "../../util/hostCapabilities";+import {isBrowser, isMobile} from "../../util/functions";+import {bindBottomSheetDialog} from "../../mobile/util/bindBottomSheetDialog";+import {canChangeSkillEntry, getSkillDirectory, SkillSourceState} from "./state";+import type {AISkillFileEntry, AISkillFileRequestInput} from "../../types/api";+/// #if !MOBILE+import {openBy} from "../../editor/util";+/// #endif++const confirmSkillAction = (title: string, text: string, remove = false): Promise<boolean> => new Promise(resolve => {+ let accepted = false;+ let disposeSheet: () => void;+ const dialog = new Dialog({+ title,+ width: isMobile() ? "100%" : "520px",+ content: `<div class="b3-dialog__content ft__breakword">${text}</div>+<div class="b3-dialog__action">+<button class="b3-button b3-button--cancel" id="cancelDialogConfirmBtn" data-action="cancel">${window.siyuan.languages.cancel}</button><div class="fn__space"></div>+<button class="b3-button b3-button--${remove ? "remove" : "text"}" id="confirmDialogConfirmBtn" data-action="confirm">${window.siyuan.languages.confirm}</button></div>`,+ destroyCallback: () => {+ disposeSheet?.();+ resolve(accepted);+ },+ });+ dialog.element.querySelector("[data-action=cancel]").addEventListener("click", () => dialog.destroy());+ const confirm = dialog.element.querySelector<HTMLButtonElement>("[data-action=confirm]");+ confirm.addEventListener("click", () => {+ accepted = true;+ dialog.destroy();+ });+ dialog.element.addEventListener("keydown", event => {+ event.stopPropagation();+ if (event.key === "Escape" && !event.isComposing) {+ event.preventDefault();+ dialog.destroy();+ }+ });+ if (isMobile()) {+ disposeSheet = bindBottomSheetDialog(dialog, async () => dialog.destroy());+ }+ confirm.focus({preventScroll: true});+});++export const openSkillManager = () => {+ const lang = window.siyuan.languages;+ const state = new SkillSourceState();+ const expandedPaths = new Set<string>();+ const localFiles = !isBrowser() && !isMobile() && getHostCapabilities().localFileSystem;+ let entries: AISkillFileEntry[] = [];+ let selected: AISkillFileEntry;+ let selectedRevision = "";+ let busy = false;+ let closed = false;+ let confirming = false;+ let prompting = false;+ let listScrollTop = 0;+ let disposeSheet: () => void;+ const button = (action: string, label: string, extraClass = "") =>+ `<button type="button" class="b3-button b3-button--outline ${extraClass}" data-action="${action}">${label}</button>`;+ const dialog = new Dialog({+ title: lang.agentSkillManager,+ width: isMobile() ? "100%" : "min(1100px, 96vw)",+ height: "min(800px, 90vh)",+ containerClassName: "skill-manager-dialog",+ content: `<div class="skill-manager${isMobile() ? " skill-manager--mobile" : ""}">+<div class="skill-manager__actions skill-manager__main-actions">+${button("newSkill", lang.agentSkillNew)}${button("newFile", lang.agentSkillNewFile)}${button("mkdir", lang.agentSkillNewFolder)}+${button("rename", lang.rename)}${button("remove", lang.remove)}${button("refresh", lang.refresh)}+${localFiles ? button("open", lang.showInFolder) : ""}</div>+<div class="skill-manager__panels">+<div class="skill-manager__sidebar">+<input class="b3-text-field skill-manager__search" type="search" placeholder="${lang.agentSkillSearch}" aria-label="${lang.agentSkillSearch}">+<ul class="skill-manager__files b3-list b3-list--background" aria-label="${lang.agentWorkspaceSkills}"></ul></div>+<div class="skill-manager__editor">+<div class="skill-manager__editor-header">${button("back", lang.back, "skill-manager__back")}<div class="skill-manager__path ft__breakword"></div></div>+<div class="skill-manager__hint ft__on-surface">${lang.emptyContent}</div>+<textarea class="b3-text-field skill-manager__source fn__none" spellcheck="false" aria-label="${lang.agentSkillSource}" disabled></textarea>+<div class="skill-manager__actions">${button("save", lang.save)}${localFiles ? button("open", lang.showInFolder, "skill-manager__editor-open") : ""}</div>+</div></div></div>`,+ destroyCallback: () => {+ disposeSheet?.();+ window.removeEventListener("beforeunload", beforeUnload);+ },+ });+ const root = dialog.element.querySelector<HTMLElement>(".skill-manager");+ const list = root.querySelector<HTMLElement>(".skill-manager__files");+ const search = root.querySelector<HTMLInputElement>(".skill-manager__search");+ const source = root.querySelector<HTMLTextAreaElement>("textarea");+ const path = root.querySelector<HTMLElement>(".skill-manager__path");+ const hint = root.querySelector<HTMLElement>(".skill-manager__hint");+ const beforeUnload = (event: BeforeUnloadEvent) => {+ if (state.dirty || busy) {+ event.preventDefault();+ event.returnValue = "";+ }+ };+ window.addEventListener("beforeunload", beforeUnload);+ const narrow = () => isMobile() || window.matchMedia("(max-width: 600px)").matches;+ const update = () => {+ const editable = !!state.path;+ source.disabled = !editable;+ source.readOnly = busy;+ source.classList.toggle("fn__none", !editable);+ hint.classList.toggle("fn__none", editable);+ hint.textContent = selected && !selected.isDir ? lang.agentSkillResourceTip : lang.emptyContent;+ path.textContent = (state.path || selected?.path || "") + (state.dirty ? " *" : "");+ list.setAttribute("aria-busy", String(busy));+ root.querySelectorAll<HTMLButtonElement>(".skill-manager__actions > [data-action]").forEach(element => {+ const action = element.dataset.action;+ element.disabled = busy || confirming || prompting ||+ (action === "save" && (!editable || !state.dirty)) ||+ (["newFile", "mkdir"].includes(action) && !getSkillDirectory(selected)) ||+ (["rename", "remove"].includes(action) && !canChangeSkillEntry(selected));+ });+ };+ const canDiscard = async () => {+ if (busy || closed || confirming || prompting) {+ return false;+ }+ if (!state.dirty) {+ return true;+ }+ confirming = true;+ update();+ try {+ return await confirmSkillAction(lang.confirm, escapeHtml(lang.discardUnsavedChanges));+ } finally {+ confirming = false;+ update();+ }+ };+ const destroy = dialog.destroy.bind(dialog);+ const close = async () => {+ if (await canDiscard()) {+ closed = true;+ destroy();+ }+ };+ dialog.destroy = () => { void close(); };+ if (isMobile()) {+ disposeSheet = bindBottomSheetDialog(dialog, close);+ }+ const run = async (action: () => Promise<void>) => {+ if (busy || closed || confirming || prompting) {+ return;+ }+ busy = true;+ update();+ try {+ await action();+ } catch (error) {+ showMessage(escapeHtml(String(error)), 5000, "error");+ } finally {+ busy = false;+ update();+ }+ };+ const guardedRun = async (action: () => Promise<void>) => {+ if (await canDiscard()) {+ await run(action);+ }+ };+ const api = async (data: AISkillFileRequestInput) => {+ const response = await fetchSyncPost("/api/ai/agent/manageSkills", data);+ return response.code === 0 ? response.data : undefined;+ };+ const showEditor = () => {+ listScrollTop = list.scrollTop;+ root.classList.add("skill-manager--editing");+ if (narrow()) {+ root.querySelector<HTMLButtonElement>("[data-action=back]").focus({preventScroll: true});+ }+ };+ const select = async (entry?: AISkillFileEntry, reveal = true) => {+ const data = entry ? await api({action: "read", path: entry.path}) : undefined;+ if (entry && !data) {+ return;+ }+ selected = entry;+ selectedRevision = data?.revision || "";+ if (!entry?.isDir) {+ state.load(entry?.editable ? entry.path : "", data?.content || "", selectedRevision);+ source.value = state.text;+ source.scrollTop = 0;+ if (entry && reveal) {+ showEditor();+ }+ }+ update();+ };+ const renderList = () => {+ const scrollTop = root.classList.contains("skill-manager--editing") && narrow() ? listScrollTop : list.scrollTop;+ list.replaceChildren();+ const rows = getFileTree(entries, search.value, expandedPaths);+ if (!rows.length) {+ const empty = document.createElement("li");+ empty.className = "ft__on-surface skill-manager__empty";+ empty.textContent = lang.emptyContent;+ list.append(empty);+ }+ rows.forEach(entry => {+ const row = document.createElement("li");+ row.className = "b3-list-item" + (entry.path === selected?.path ? " b3-list-item--focus" : "");+ row.style.paddingInlineStart = `${Math.min(entry.depth, 16) * 16 + 4}px`;+ row.dataset.path = entry.path;+ if (entry.isDir) {+ const toggle = document.createElement("button");+ toggle.type = "button";+ toggle.className = "skill-manager__toggle";+ toggle.setAttribute("aria-expanded", String(entry.expanded));+ toggle.setAttribute("aria-label", (entry.expanded ? lang.collapse : lang.expand) + " " + entry.name);+ toggle.innerHTML = `<svg><use xlink:href="#${entry.expanded ? "iconDown" : "iconRight"}"></use></svg>`;+ toggle.disabled = !!search.value.trim();+ toggle.addEventListener("click", () => {+ if (expandedPaths.has(entry.path)) {+ expandedPaths.delete(entry.path);+ } else {+ expandedPaths.add(entry.path);+ }+ renderList();+ });+ row.append(toggle);+ } else {+ const spacer = document.createElement("span");+ spacer.className = "skill-manager__toggle";+ row.append(spacer);+ }+ const item = document.createElement("button");+ item.type = "button";+ item.className = "skill-manager__file";+ item.setAttribute("aria-current", String(entry.path === selected?.path));+ item.innerHTML = `<svg class="b3-list-item__graphic"><use xlink:href="#${entry.isDir ? "iconFolder" : "iconFile"}"></use></svg>`;+ const name = document.createElement("span");+ name.className = "b3-list-item__text";+ name.textContent = entry.name;+ item.append(name);+ item.title = entry.path;+ item.addEventListener("click", () => {+ if (busy || confirming || prompting || closed) {+ return;+ }+ if (entry.path === state.path) {+ selected = entry;+ selectedRevision = state.revision;+ showEditor();+ renderList();+ update();+ return;+ }+ const action = async () => {+ await select(entry);+ if (entry.isDir && !search.value.trim()) {+ if (expandedPaths.has(entry.path)) {+ expandedPaths.delete(entry.path);+ } else {+ expandedPaths.add(entry.path);+ }+ }+ renderList();+ };+ void (entry.isDir ? run(action) : guardedRun(action));+ });+ row.append(item);+ list.append(row);+ });+ list.scrollTop = scrollTop;+ };+ const reload = async (selectedPath = selected?.path, reveal = false) => {+ const data = await api({action: "list"});+ if (!data?.entries) {+ return;+ }+ entries = data.entries;+ if (reveal) {+ search.value = "";+ }+ let parent = selectedPath?.substring(0, selectedPath.lastIndexOf("/"));+ while (parent) {+ expandedPaths.add(parent);+ parent = parent.substring(0, parent.lastIndexOf("/"));+ }+ state.load("", "", "");+ source.value = "";+ await select(entries.find(entry => entry.path === selectedPath), reveal);+ if (!selected || selected.isDir) {+ root.classList.remove("skill-manager--editing");+ }+ renderList();+ };+ const inputName = (action: "newSkill" | "newFile" | "mkdir" | "rename") => {+ if (busy || closed || confirming || prompting) {+ return;+ }+ prompting = true;+ update();+ const entry = selected;+ const directory = getSkillDirectory(entry);+ const title = action === "newSkill" ? lang.agentSkillNew : action === "newFile" ? lang.agentSkillNewFile :+ action === "mkdir" ? lang.agentSkillNewFolder : lang.rename;+ let disposeInputSheet: () => void;+ const prompt = openInputDialog({+ title,+ label: lang.name,+ value: action === "rename" ? entry.path.split("/").pop() : "",+ width: isMobile() ? "100%" : "520px",+ destroyCallback: () => {+ disposeInputSheet?.();+ prompting = false;+ update();+ },+ onConfirm: (value, inputDialog) => {+ const input = inputDialog.element.querySelector<HTMLInputElement>("input");+ const name = value.trim();+ const target = getFileRenameTarget(action === "rename" ? entry.path : "", name);+ if (target === undefined || (action === "rename" && !entry.isDir && !/\.md$/i.test(name))) {+ input.setCustomValidity(lang.agentSkillNameTip);+ input.reportValidity();+ return;+ }+ prompting = false;+ inputDialog.destroy();+ void run(async () => {+ let next = target;+ let data;+ if (action === "newSkill") {+ data = await api({action: "create", path: name});+ next = name + "/SKILL.md";+ } else if (action === "rename") {+ if (entry.path === target) {+ return;+ }+ data = await api({action: "move", path: entry.path, target, revision: selectedRevision});+ } else {+ next = directory + "/" + (action === "newFile" && !/\.md$/i.test(name) ? name + ".md" : name);+ data = await api(action === "mkdir" ? {action: "mkdir", path: next} :+ {action: "write", path: next, content: "", revision: ""});+ }+ if (data) {+ await reload(next, true);+ }+ });+ },+ });+ prompt.element.querySelector("input").addEventListener("input", event =>+ (event.target as HTMLInputElement).setCustomValidity(""));+ if (isMobile()) {+ disposeInputSheet = bindBottomSheetDialog(prompt, async () => prompt.destroy());+ }+ };+ source.addEventListener("input", () => {+ state.text = source.value;+ update();+ });+ search.addEventListener("input", renderList);+ root.addEventListener("click", event => {+ const target = (event.target as Element).closest<HTMLButtonElement>("button[data-action]");+ if (!target || target.disabled || busy || confirming || prompting || closed) {+ return;+ }+ const action = target.dataset.action;+ if (action === "save") {+ void run(async () => {+ const data = await api({action: "write", path: state.path, content: state.content, revision: state.revision});+ if (data) {+ state.acceptSave(data.revision);+ if (selected?.path === state.path) {+ selectedRevision = state.revision;+ } else if (selected?.isDir && state.path.startsWith(selected.path + "/")) {+ const directory = await api({action: "read", path: selected.path});+ if (directory) {+ selectedRevision = directory.revision;+ }+ }+ }+ });+ } else if (action === "back") {+ void canDiscard().then(allowed => {+ if (allowed) {+ state.discard();+ source.value = state.text;+ root.classList.remove("skill-manager--editing");+ list.scrollTop = listScrollTop;+ update();+ list.querySelector<HTMLButtonElement>("[aria-current=true]")?.focus({preventScroll: true});+ }+ });+ } else if (action === "open") {+ /// #if !MOBILE+ const directory = window.siyuan.config.system.dataDir.replace(/\\/g, "/").replace(/\/$/, "") + "/storage/ai/agent/skills";+ openBy(selected ? directory + "/" + selected.path : directory, selected ? "folder" : "app");+ /// #endif+ } else if (action === "refresh") {+ void guardedRun(() => reload());+ } else if (action === "remove") {+ void canDiscard().then(async allowed => {+ if (!allowed || busy || confirming || prompting || closed) {+ return;+ }+ const entry = selected;+ confirming = true;+ update();+ const accepted = await confirmSkillAction(lang.remove,+ escapeHtml(entry.path) + "<br>" + escapeHtml(lang.agentSkillDeleteTip), true);+ confirming = false;+ update();+ if (accepted) {+ await run(async () => {+ if (await api({action: "remove", path: entry.path, revision: selectedRevision})) {+ await reload("");+ }+ });+ }+ });+ } else if (["newSkill", "newFile", "mkdir", "rename"].includes(action)) {+ void canDiscard().then(allowed => {+ if (allowed) {+ inputName(action as "newSkill" | "newFile" | "mkdir" | "rename");+ }+ });+ }+ });+ dialog.element.addEventListener("keydown", event => {+ event.stopPropagation();+ if (event.key === "Escape" && !event.isComposing) {+ event.preventDefault();+ dialog.destroy();+ }+ });+ update();+ void run(() => reload());+};diff --git a/app/src/ai/skills/state.test.ts b/app/src/ai/skills/state.test.tsnew file mode 100644index 0000000000..8db77e26d2--- /dev/null+++ b/app/src/ai/skills/state.test.ts@@ -0,0 +1,55 @@+import * as assert from "node:assert/strict";+import {test} from "node:test";+import {canChangeSkillEntry, getSkillDirectory, isSkillEntryPoint, SkillSourceState} from "./state";++test("skill entry points and resources cannot be renamed or deleted separately", () => {+ assert.equal(isSkillEntryPoint({path: "review/SKILL.md", isDir: false, editable: true}), true);+ assert.equal(canChangeSkillEntry({path: "review/skill.MD", isDir: false, editable: true}), false);+ assert.equal(canChangeSkillEntry({path: "review/references/SKILL.md", isDir: false, editable: true}), true);+ assert.equal(canChangeSkillEntry({path: "review/run.js", isDir: false, editable: false}), false);+ assert.equal(canChangeSkillEntry({path: "review", isDir: true, editable: false}), true);+ assert.equal(canChangeSkillEntry(undefined), false);+});++test("new Markdown files stay inside the selected skill directory", () => {+ assert.equal(getSkillDirectory(), "");+ assert.equal(getSkillDirectory({path: "review", isDir: true, editable: false}), "review");+ assert.equal(getSkillDirectory({path: "review/references/info.md", isDir: false, editable: true}), "review/references");+ assert.equal(getSkillDirectory({path: "loose.md", isDir: false, editable: false}), "");+});++test("editing preserves Markdown front matter, Unicode, and CRLF", () => {+ const state = new SkillSourceState();+ const content = "---\r\nname: review\r\ndescription: \"检查\"\r\n---\r\n\r\n# Notes\r\n";+ state.load("folder/SKILL.md", content, "original");+ assert.equal(state.content, content);+ state.text += "更多内容\n";+ assert.equal(state.dirty, true);+ assert.equal(state.content, content + "更多内容\r\n");+ assert.equal(state.revision, "original");+ state.acceptSave("updated");+ assert.equal(state.dirty, false);+ assert.equal(state.revision, "updated");+});++test("a rejected save retains draft and original revision, and discard restores the saved version", () => {+ const state = new SkillSourceState();+ state.load("folder/SKILL.md", "saved\n", "original");+ state.text = "draft\n";+ assert.equal(state.content, "draft\n");+ assert.equal(state.revision, "original");+ assert.equal(state.dirty, true);+ state.discard();+ assert.equal(state.content, "saved\n");+ assert.equal(state.dirty, false);+});++test("unchanged mixed line endings retain the original source", () => {+ const state = new SkillSourceState();+ const content = "---\r\nname: review\n---\r\n正文\r\n";+ state.load("review/SKILL.md", content, "original");+ assert.equal(state.content, content);+ state.text += "extra";+ state.discard();+ assert.equal(state.content, content);+});diff --git a/app/src/ai/skills/state.ts b/app/src/ai/skills/state.tsnew file mode 100644index 0000000000..0a5a77aaad--- /dev/null+++ b/app/src/ai/skills/state.ts@@ -0,0 +1,49 @@+import type {AISkillFileEntry} from "../../types/api";++export const isSkillEntryPoint = (entry: AISkillFileEntry) =>+ !entry.isDir && /^[^/]+\/SKILL\.md$/i.test(entry.path);++export const getSkillDirectory = (entry?: AISkillFileEntry) => entry ?+ (entry.isDir ? entry.path : entry.path.substring(0, entry.path.lastIndexOf("/"))) : "";++export const canChangeSkillEntry = (entry?: AISkillFileEntry) =>+ !!entry && (entry.isDir || (entry.editable && !isSkillEntryPoint(entry)));++export class SkillSourceState {+ public path = "";+ public revision = "";+ public text = "";+ private saved = "";+ private original = "";+ private crlf = false;++ public load(path: string, content: string, revision: string) {+ this.path = path;+ this.original = content;+ this.revision = revision;+ this.crlf = content.includes("\r\n") && !content.replace(/\r\n/g, "").includes("\n");+ this.text = content.replace(/\r\n?/g, "\n");+ this.saved = this.text;+ }++ public get dirty() {+ return this.text !== this.saved;+ }++ public get content() {+ if (!this.dirty) {+ return this.original;+ }+ return this.crlf ? this.text.replace(/\n/g, "\r\n") : this.text;+ }++ public acceptSave(revision: string) {+ this.original = this.content;+ this.revision = revision;+ this.saved = this.text;+ }++ public discard() {+ this.text = this.saved;+ }+}diff --git a/app/src/assets/scss/base.scss b/app/src/assets/scss/base.scssindex 7dc47a334b..1b7aaa1961 100644--- a/app/src/assets/scss/base.scss+++ b/app/src/assets/scss/base.scss@@ -2,6 +2,7 @@@use "util/function" as *;@use "business/history" as *;@use "business/template-manager" as *;+@use "business/skill-manager" as *;@use "component/chip" as *;@use "component/slider" as *;@use "component/switch" as *;diff --git a/app/src/assets/scss/business/_skill-manager.scss b/app/src/assets/scss/business/_skill-manager.scssnew file mode 100644index 0000000000..cbfcad25bb--- /dev/null+++ b/app/src/assets/scss/business/_skill-manager.scss@@ -0,0 +1,185 @@+.skill-manager-dialog > .b3-dialog__body {+ min-height: 0;+ overflow: hidden;+}++.skill-manager {+ display: flex;+ flex: 1;+ flex-direction: column;+ min-height: 0;+ padding: 12px;+ box-sizing: border-box;+ gap: 8px;++ &__actions {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+ }++ &__panels {+ display: flex;+ flex: 1;+ min-height: 0;+ gap: 12px;+ }++ &__sidebar {+ display: flex;+ flex-direction: column;+ width: 30%;+ min-width: 0;+ min-height: 0;+ gap: 8px;+ padding-inline-end: 8px;+ border-right: 1px solid var(--b3-border-color);+ }++ &__search {+ width: 100%;+ min-width: 0;+ box-sizing: border-box;+ }++ &__files {+ flex: 1;+ min-height: 0;+ overflow: auto;+ margin: 0;+ padding: 0;+ list-style: none;++ .b3-list-item {+ min-height: 36px;+ height: auto;+ }+ }++ &__file,+ &__toggle {+ display: flex;+ align-items: center;+ padding: 0;+ border: 0;+ border-radius: var(--b3-border-radius);+ background: transparent;+ color: inherit;+ font: inherit;+ cursor: pointer;+ }++ &__file {+ flex: 1;+ min-width: 0;+ min-height: 36px;+ text-align: start;++ .b3-list-item__text {+ text-align: start;+ }+ }++ &__toggle {+ flex: 0 0 24px;+ height: 32px;+ justify-content: center;++ svg {+ width: 12px;+ height: 12px;+ }++ &:disabled {+ cursor: default;+ }+ }++ &__empty {+ padding: 8px;+ }++ &__editor {+ display: flex;+ flex: 1;+ flex-direction: column;+ min-width: 0;+ min-height: 0;+ gap: 8px;+ }++ &__editor-header {+ display: flex;+ align-items: center;+ gap: 8px;+ }++ &__path {+ flex: 1;+ min-width: 0;+ max-height: 20vh;+ overflow: auto;+ }++ .skill-manager__back,+ .skill-manager__editor-open {+ display: none;+ flex-shrink: 0;+ }++ &__hint {+ flex: 1;+ }++ &__source {+ flex: 1;+ width: 100%;+ min-height: 0;+ box-sizing: border-box;+ resize: none;+ font-family: var(--b3-font-family-code);+ tab-size: 4;+ }+}++@mixin skill-manager-pages {+ .skill-manager__sidebar {+ width: 100%;+ padding-inline-end: 0;+ border-right: 0;+ }++ .skill-manager__editor {+ display: none;+ }++ .skill-manager__back,+ .skill-manager__editor-open {+ display: inline-flex;+ }++ &.skill-manager--editing {+ .skill-manager__sidebar,+ .skill-manager__main-actions {+ display: none;+ }++ .skill-manager__editor {+ display: flex;+ }+ }+}++.skill-manager--mobile {+ @include skill-manager-pages;+}++@media (max-width: 600px) {+ .skill-manager {+ @include skill-manager-pages;+ }+}++.mobile-bottom-sheet-dialog .skill-manager-dialog.mobile-bottom-sheet {+ max-height: 100%;+}diff --git a/app/src/assets/scss/mobile.scss b/app/src/assets/scss/mobile.scssindex 739dc1e314..d6e3aec463 100644--- a/app/src/assets/scss/mobile.scss+++ b/app/src/assets/scss/mobile.scss@@ -20,6 +20,7 @@@use "util/function" as *;@use "business/history" as *;@use "business/template-manager" as *;+@use "business/skill-manager" as *;@use "business/color" as *;@use "protyle/protyle" as *;@use "component/typography" as *;diff --git a/app/src/config/tabs/ai/aiTab.ts b/app/src/config/tabs/ai/aiTab.tsindex a44d87cdf0..964868c785 100644--- a/app/src/config/tabs/ai/aiTab.ts+++ b/app/src/config/tabs/ai/aiTab.ts@@ -29,6 +29,7 @@ import {mountUserSkillsBlock,} from "./aiSkillUi";import {isAgentStreamingMarkdownEnabled, setAgentStreamingMarkdownEnabled} from "./agentStreamingMarkdown";+import {openSkillManager} from "../../../ai/skills/manager";const registerAiProvidersGroup = (tab: SettingTabBuilder) => {const group = tab.group("providers", window.siyuan.languages.apiProvider);@@ -169,6 +170,16 @@ const registerAiImageGenerationGroup = (tab: SettingTabBuilder) => {const registerAiSkillsGroup = (tab: SettingTabBuilder) => {const group = tab.group("skills", window.siyuan.languages.tokenCatSkills);+ group.button({+ id: "aiWorkspaceSkills",+ title: window.siyuan.languages.agentWorkspaceSkills,+ desc: window.siyuan.languages.agentWorkspaceSkillsTip,+ label: window.siyuan.languages.manage,+ icon: "iconSettings",+ afterMount: root => {+ root.querySelector("#aiWorkspaceSkills")?.addEventListener("click", openSkillManager);+ },+ });group.button({id: "aiUserSkills",title: window.siyuan.languages.agentUserSkills,diff --git a/app/src/template/fileTree.test.ts b/app/src/template/fileTree.test.tsindex b083b8b962..967d0af0a7 100644--- a/app/src/template/fileTree.test.ts+++ b/app/src/template/fileTree.test.ts@@ -1,6 +1,7 @@import {describe, it} from "node:test";import * as assert from "node:assert/strict";-import {getTemplateRenameTarget, getTemplateTree, TemplateEntry} from "./fileTree";+import type {TemplateEntry} from "./fileTree";+import {getFileRenameTarget, getFileTree} from "../util/fileTree";const entries: TemplateEntry[] = [{path: "note10.md", isDir: false},@@ -14,31 +15,31 @@ const entries: TemplateEntry[] = [describe("template file tree", () => {it("keeps normalized slashes in the basename without changing the parent directory", () => {- assert.equal(getTemplateRenameTarget("模板.md", "22/1111.md"), "22/1111.md");- assert.equal(getTemplateRenameTarget("子文件夹/模板.md", "22/1111.md"), "子文件夹/22/1111.md");- assert.equal(getTemplateRenameTarget("Work/Weekly", "Daily/Review"), "Work/Daily/Review");- assert.equal(getTemplateRenameTarget("folder/note.md", "../outside.md"), "folder/../outside.md");- assert.equal(getTemplateRenameTarget("folder/note.md", "//note.md"), "folder///note.md");+ assert.equal(getFileRenameTarget("模板.md", "22/1111.md"), "22/1111.md");+ assert.equal(getFileRenameTarget("子文件夹/模板.md", "22/1111.md"), "子文件夹/22/1111.md");+ assert.equal(getFileRenameTarget("Work/Weekly", "Daily/Review"), "Work/Daily/Review");+ assert.equal(getFileRenameTarget("folder/note.md", "../outside.md"), "folder/../outside.md");+ assert.equal(getFileRenameTarget("folder/note.md", "//note.md"), "folder///note.md");});it("renames only the basename while preserving nested and non-ASCII paths", () => {- assert.equal(getTemplateRenameTarget("子文件夹/模板.md", "新模板.md"), "子文件夹/新模板.md");- assert.equal(getTemplateRenameTarget("Work/Weekly", "Daily"), "Work/Daily");- assert.equal(getTemplateRenameTarget("模板.md", "O'Reilly.md"), "O'Reilly.md");- assert.equal(getTemplateRenameTarget("folder /template.md", "new.md"), "folder /new.md");+ assert.equal(getFileRenameTarget("子文件夹/模板.md", "新模板.md"), "子文件夹/新模板.md");+ assert.equal(getFileRenameTarget("Work/Weekly", "Daily"), "Work/Daily");+ assert.equal(getFileRenameTarget("模板.md", "O'Reilly.md"), "O'Reilly.md");+ assert.equal(getFileRenameTarget("folder /template.md", "new.md"), "folder /new.md");for (const name of ["", ".", "..", "../outside.md", "new/note.md", "new\\note.md", "C:note.md"]) {- assert.equal(getTemplateRenameTarget("folder/note.md", name), undefined, name);+ assert.equal(getFileRenameTarget("folder/note.md", name), undefined, name);}});it("groups folders first and naturally sorts files without changing the input", () => {const original = entries.slice();- const rows = getTemplateTree(entries, "", new Set());+ const rows = getFileTree(entries, "", new Set());assert.deepEqual(rows.map(item => item.path), ["Empty", "Work", "note2.md", "note10.md"]);assert.equal(rows[1].isPackage, true);assert.deepEqual(entries, original);});it("respects nested expansion and keeps empty directories", () => {- const rows = getTemplateTree(entries, "", new Set(["Work", "Work/Weekly", "Empty"]));+ const rows = getFileTree(entries, "", new Set(["Work", "Work/Weekly", "Empty"]));assert.deepEqual(rows.map(item => [item.path, item.depth]), [["Empty", 0], ["Work", 0], ["Work/Weekly", 1], ["Work/Weekly/Review.md", 2],["Work/daily.md", 1], ["note2.md", 0], ["note10.md", 0],@@ -48,19 +49,19 @@ describe("template file tree", () => {it("searches names case-insensitively and reveals ancestors without changing expansion", () => {const expanded = new Set(["Empty"]);- const rows = getTemplateTree(entries, " REVIEW ", expanded);+ const rows = getFileTree(entries, " REVIEW ", expanded);assert.deepEqual(rows.map(item => item.path), ["Work", "Work/Weekly", "Work/Weekly/Review.md"]);assert.equal(rows[0].expanded, true);assert.equal(rows[1].expanded, true);assert.deepEqual([...expanded], ["Empty"]);- assert.deepEqual(getTemplateTree(entries, "", expanded).map(item => item.path),+ assert.deepEqual(getFileTree(entries, "", expanded).map(item => item.path),["Empty", "Work", "note2.md", "note10.md"]);});it("matches full paths and includes descendants of matching folders", () => {- assert.deepEqual(getTemplateTree(entries, "work/week", new Set()).map(item => item.path),+ assert.deepEqual(getFileTree(entries, "work/week", new Set()).map(item => item.path),["Work", "Work/Weekly", "Work/Weekly/Review.md"]);- assert.deepEqual(getTemplateTree(entries, "missing", new Set()), []);- assert.deepEqual(getTemplateTree([], "", new Set()), []);+ assert.deepEqual(getFileTree(entries, "missing", new Set()), []);+ assert.deepEqual(getFileTree([], "", new Set()), []);});});diff --git a/app/src/template/fileTree.ts b/app/src/template/fileTree.tsindex 2cf280cef2..28bd749dbc 100644--- a/app/src/template/fileTree.ts+++ b/app/src/template/fileTree.ts@@ -3,55 +3,3 @@ export interface TemplateEntry {isDir: boolean;isPackage?: boolean;}--// 重命名只接受单个名称,始终保留原父目录。-export const getTemplateRenameTarget = (path: string, name: string): string | undefined => {- if (!name || name === "." || name === ".." || /[\\/:]/.test(name)) {- return undefined;- }- return path.substring(0, path.lastIndexOf("/") + 1) + name;-};--export interface TemplateTreeEntry extends TemplateEntry {- name: string;- depth: number;- expanded: boolean;-}--export const getTemplateTree = (entries: TemplateEntry[], query: string, expandedPaths: Set<string>): TemplateTreeEntry[] => {- const keyword = query.trim().toLowerCase();- const children = new Map<string, TemplateEntry[]>();- const matches = new Set<string>();- entries.forEach(entry => {- const parent = entry.path.substring(0, entry.path.lastIndexOf("/"));- if (!children.has(parent)) {- children.set(parent, []);- }- children.get(parent).push(entry);- if (keyword && entry.path.toLowerCase().includes(keyword)) {- // 搜索结果保留祖先目录,临时展开但不改变用户的展开状态。- let path = entry.path;- while (path) {- matches.add(path);- path = path.substring(0, path.lastIndexOf("/"));- }- }- });- children.forEach(items => items.sort((a, b) => Number(b.isDir) - Number(a.isDir) ||- a.path.localeCompare(b.path, undefined, {numeric: true, sensitivity: "base"})));- const result: TemplateTreeEntry[] = [];- const visit = (parent: string, depth: number) => {- children.get(parent)?.forEach(entry => {- if (keyword && !matches.has(entry.path)) {- return;- }- const expanded = entry.isDir && (!!keyword || expandedPaths.has(entry.path));- result.push({...entry, name: entry.path.split("/").pop(), depth, expanded});- if (expanded) {- visit(entry.path, depth + 1);- }- });- };- visit("", 0);- return result;-};diff --git a/app/src/template/manager.ts b/app/src/template/manager.tsindex 90caffd5ee..ce69166911 100644--- a/app/src/template/manager.ts+++ b/app/src/template/manager.ts@@ -5,7 +5,8 @@ import {fetchSyncPost} from "../util/fetch";import {escapeHtml} from "../util/escape";import {showMessage} from "../dialog/message";import {clearTemplatePreview, previewTemplate} from "../protyle/toolbar/util";-import {getTemplateRenameTarget, getTemplateTree, TemplateEntry} from "./fileTree";+import type {TemplateEntry} from "./fileTree";+import {getFileRenameTarget, getFileTree} from "../util/fileTree";import {getTemplateActionEntry, getTemplateActionState} from "./actionState";/// #if !MOBILEimport {openBy} from "../editor/util";@@ -156,7 +157,7 @@ ${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button(const renderList = () => {const scrollTop = list.scrollTop;list.replaceChildren();- const rows = getTemplateTree(entries, fileSearch.value, expandedPaths);+ const rows = getFileTree(entries, fileSearch.value, expandedPaths);if (rows.length === 0) {const empty = document.createElement("li");empty.className = "ft__on-surface template-manager__empty";@@ -297,7 +298,7 @@ ${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button(input.focus();return;}- if (nameOnly && getTemplateRenameTarget(selected.path, input.value.trim()) === undefined) {+ if (nameOnly && getFileRenameTarget(selected.path, input.value.trim()) === undefined) {input.setCustomValidity(lang.templateNameTip);input.reportValidity();return;@@ -444,7 +445,7 @@ ${!isBrowser() && !isMobile() && getHostCapabilities().localFileSystem ? button(} else if (action === "mkdir") {response = await api({action: "mkdir", path: value});} else {- value = getTemplateRenameTarget(selected.path, value);+ value = getFileRenameTarget(selected.path, value);if (value === selected.path) {return;}diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 74972ec0dc..0b54b2f2d6 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -172,6 +172,12 @@ export type AISessionsRequestInput = { "keyword"?: string | null; "page"?: numbeexport type AISkillData = { "content": string; "name": string; };+export type AISkillFileData = { "content"?: string; "entries"?: Array<AISkillFileEntry> | null; "revision"?: string; };++export type AISkillFileEntry = { "editable": boolean; "isDir": boolean; "path": string; };++export type AISkillFileRequestInput = { "action": string; "content"?: string; "path"?: string; "revision"?: string; "target"?: string; };+export type AISkillInfo = { "description": string; "name": string; };export type AISkillNameRequestInput = { "name"?: string | null; };@@ -2461,6 +2467,11 @@ export interface APIPOSTRoutes {response: { "code": 0; "data": Array<AIUserSkillInfo> | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };body: "none";};+ "/api/ai/agent/manageSkills": {+ request: AISkillFileRequestInput;+ response: { "code": 0; "data": AISkillFileData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };"/api/ai/agent/question": {request: AIQuestionRequestInput;response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };diff --git a/app/src/util/fileTree.ts b/app/src/util/fileTree.tsnew file mode 100644index 0000000000..e02b9e9890--- /dev/null+++ b/app/src/util/fileTree.ts@@ -0,0 +1,56 @@+export interface FileEntry {+ path: string;+ isDir: boolean;+}++// 重命名只接受单个名称,始终保留原父目录。+export const getFileRenameTarget = (path: string, name: string): string | undefined => {+ if (!name || name === "." || name === ".." || /[\\/:]/.test(name)) {+ return undefined;+ }+ return path.substring(0, path.lastIndexOf("/") + 1) + name;+};++export type FileTreeEntry<T extends FileEntry> = T & {+ name: string;+ depth: number;+ expanded: boolean;+};++export const getFileTree = <T extends FileEntry>(entries: T[], query: string, expandedPaths: Set<string>): FileTreeEntry<T>[] => {+ const keyword = query.trim().toLowerCase();+ const children = new Map<string, T[]>();+ const matches = new Set<string>();+ entries.forEach(entry => {+ const parent = entry.path.substring(0, entry.path.lastIndexOf("/"));+ if (!children.has(parent)) {+ children.set(parent, []);+ }+ children.get(parent).push(entry);+ if (keyword && entry.path.toLowerCase().includes(keyword)) {+ // 搜索结果保留祖先目录,临时展开但不改变用户的展开状态。+ let path = entry.path;+ while (path) {+ matches.add(path);+ path = path.substring(0, path.lastIndexOf("/"));+ }+ }+ });+ children.forEach(items => items.sort((a, b) => Number(b.isDir) - Number(a.isDir) ||+ a.path.localeCompare(b.path, undefined, {numeric: true, sensitivity: "base"})));+ const result: FileTreeEntry<T>[] = [];+ const visit = (parent: string, depth: number) => {+ children.get(parent)?.forEach(entry => {+ if (keyword && !matches.has(entry.path)) {+ return;+ }+ const expanded = entry.isDir && (!!keyword || expandedPaths.has(entry.path));+ result.push({...entry, name: entry.path.split("/").pop(), depth, expanded});+ if (expanded) {+ visit(entry.path, depth + 1);+ }+ });+ };+ visit("", 0);+ return result;+};diff --git a/app/tests/api-contract.types.ts b/app/tests/api-contract.types.tsindex 95b95bf499..bdf293c05f 100644--- a/app/tests/api-contract.types.ts+++ b/app/tests/api-contract.types.ts@@ -6,6 +6,24 @@ declare const fetchGet: FetchGet;declare const fetchSyncPost: FetchSyncPost;declare const dynamicURL: string;+fetchPost("/api/ai/agent/manageSkills", {action: "list"}, response => {+ if (response.code === 0) {+ const entries: {path: string, isDir: boolean, editable: boolean}[] | null | undefined = response.data.entries;+ const content: string | undefined = response.data.content;+ const revision: string | undefined = response.data.revision;+ void [entries, content, revision];+ }+});+fetchPost("/api/ai/agent/manageSkills", {action: "write", path: "example/SKILL.md", content: "", revision: "hash"});+// @ts-expect-error 技能管理操作不能省略。+fetchPost("/api/ai/agent/manageSkills", {});+// @ts-expect-error 文件修订号必须是字符串。+fetchPost("/api/ai/agent/manageSkills", {action: "write", path: "example/SKILL.md", revision: 1});+// @ts-expect-error 技能文件定位使用相对路径,不接受显示名称。+fetchPost("/api/ai/agent/manageSkills", {action: "read", name: "example"});+// @ts-expect-error 技能文件管理只支持 POST。+fetchGet("/api/ai/agent/manageSkills", () => undefined);+fetchPost("/api/petal/savePluginPublishData", {packageName: "example", data: {theme: "dark", enabled: true, count: 1, empty: null}});fetchPost("/api/petal/setPluginPublishDataGrant", {packageName: "example", fields: ["theme"], enabled: true});// @ts-expect-error 公开字段不能包含未经独立授权的嵌套对象。diff --git a/app/tests/skillManager.test.js b/app/tests/skillManager.test.jsnew file mode 100644index 0000000000..1f28d2e855--- /dev/null+++ b/app/tests/skillManager.test.js@@ -0,0 +1,303 @@+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");++const runCases = async (appDirectory, mode, capture) => {+ const assert = require("node:assert/strict");+ const fs = require("node:fs");+ const path = require("node:path");+ const ts = require(path.join(appDirectory, "node_modules/typescript"));+ const tick = () => new Promise(resolve => setTimeout(resolve, 30));+ const mobile = mode === "mobile";+ const viewport = new EventTarget();+ viewport.height = window.innerHeight;+ viewport.offsetTop = 0;+ if (mobile) {+ Object.defineProperty(window, "visualViewport", {value: viewport, configurable: true});+ }+ const requests = [];+ const opened = [];+ const messages = [];+ const original = "---\r\nname: Display Name\r\ndescription: Review notes\r\n---\r\nOriginal\r\n";+ let stored = original;+ let conflict = false;+ let id = 0;+ const entries = [+ {path: "directory-id", isDir: true, editable: false},+ {path: "directory-id/SKILL.md", isDir: false, editable: true},+ {path: "directory-id/resources", isDir: true, editable: false},+ {path: "directory-id/resources/notes.md", isDir: false, editable: true},+ {path: "directory-id/image.png", isDir: false, editable: false},+ ...Array.from({length: 40}, (_, index) => ({path: `extra-${index}`, isDir: true, editable: false})),+ ];+ window.siyuan = {+ dialogs: [], zIndex: 1, storage: {},+ languages: JSON.parse(fs.readFileSync(path.join(appDirectory, "appearance/langs/en.json"), "utf8")),+ config: {system: {dataDir: "D:/workspace/data"}},+ menus: {menu: {element: document.createElement("div"), remove() {}}},+ };+ const overrides = {+ "util/genID": {genUUID: () => String(++id)},+ "util/zIndex": {isAbove: () => false},+ "dialog/moveResize": {moveResize() {}},+ "util/functions": {isMobile: () => mobile, isBrowser: () => mode === "browser"},+ "util/hostCapabilities": {getHostCapabilities: () => ({localFileSystem: mode !== "remote"})},+ "protyle/util/compatibility": {isNotCtrl: () => true},+ "constants": {Constants: {TIMEOUT_OPENDIALOG: 0, TIMEOUT_DBLCLICK: 0, DIALOG_CONFIRM: "confirm"}},+ "editor/util": {openBy: (...args) => opened.push(args)},+ "editor/rename": {replaceFileName: value => value.replace(/\//g, "\uff0f")},+ "dialog/message": {showMessage: (...args) => messages.push(args)},+ "util/fetch": {fetchSyncPost: async (url, request) => {+ assert.equal(url, "/api/ai/agent/manageSkills");+ requests.push({...request});+ await tick();+ if (request.action === "list") {+ return {code: 0, data: {entries}};+ }+ if (request.action === "read") {+ const entry = entries.find(item => item.path === request.path);+ assert.ok(entry, request.path);+ return {code: 0, data: {+ revision: "revision-1",+ ...(entry.editable ? {content: request.path.endsWith("SKILL.md") ? stored : "Resource text"} : {}),+ }};+ }+ if (request.action === "write") {+ if (conflict) {+ return {code: -1, msg: "File changed", data: null};+ }+ stored = request.content;+ return {code: 0, data: {revision: "revision-2"}};+ }+ throw new Error(`Unexpected action: ${request.action}`);+ }},+ };+ const cache = new Map();+ const load = (name, parent = "") => {+ const key = path.posix.normalize(path.posix.join(parent, name)).replace(/\.ts$/, "");+ if (overrides[key]) {+ return overrides[key];+ }+ if (cache.has(key)) {+ return cache.get(key);+ }+ const sourceRoot = path.join(appDirectory, "src");+ let file = path.join(sourceRoot, key + ".ts");+ let moduleKey = key;+ if (!fs.existsSync(file)) {+ file = path.join(sourceRoot, key, "index.ts");+ moduleKey += "/index";+ }+ assert.ok(path.resolve(file).startsWith(path.resolve(sourceRoot) + path.sep));+ const output = ts.transpileModule(fs.readFileSync(file, "utf8"), {+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},+ }).outputText;+ const exports = {};+ cache.set(key, exports);+ new Function("require", "exports", output)(dependency => load(dependency, path.posix.dirname(moduleKey)), exports);+ return exports;+ };+ load("ai/skills/manager").openSkillManager();+ await tick();+ await tick();+ const dialog = window.siyuan.dialogs[0];+ const manager = dialog.element.querySelector(".skill-manager");+ assert.ok(manager);+ await new Promise(resolve => setTimeout(resolve, 180));+ assert.equal(dialog.element.classList.contains("mobile-bottom-sheet-dialog"), mobile);+ const container = dialog.element.querySelector(".b3-dialog__container");+ if (mobile) {+ const bounds = container.getBoundingClientRect();+ assert.ok(bounds.top > 0, "the mobile sheet leaves space above its handle");+ assert.ok(bounds.bottom <= window.innerHeight + 1, "the mobile sheet fits in the viewport");+ assert.equal(getComputedStyle(manager.querySelector(".skill-manager__editor")).display, "none");+ }+ assert.equal(Boolean(manager.querySelector('[data-action="open"]')), mode === "desktop");+ if (capture) {+ await require("electron").ipcRenderer.invoke("skill-manager-capture", `${mode}-${window.innerWidth}-list`);+ }+ const button = action => manager.querySelector(`[data-action="${action}"]`);+ assert.equal(getComputedStyle(button("back")).display === "none", !mobile);+ const choose = async file => {+ const row = Array.from(manager.querySelectorAll("li[data-path]")).find(item => item.dataset.path === file);+ assert.ok(row, file);+ row.querySelector(".skill-manager__file").click();+ await tick();+ await tick();+ };+ await choose("directory-id");+ const files = manager.querySelector(".skill-manager__files");+ files.scrollTop = 35;+ const previousScroll = files.scrollTop;+ assert.ok(previousScroll > 0, "the file list scrolls independently");+ await choose("directory-id/SKILL.md");+ const source = manager.querySelector(".skill-manager__source");+ assert.equal(source.value, original.replace(/\r\n/g, "\n"));+ assert.ok(source.getBoundingClientRect().height > 120, "the source editor has usable height");+ if (mobile) {+ assert.equal(getComputedStyle(manager.querySelector(".skill-manager__sidebar")).display, "none");+ viewport.height = 360;+ viewport.dispatchEvent(new Event("resize"));+ await tick();+ const bounds = container.getBoundingClientRect();+ assert.ok(bounds.bottom <= 361, "the drawer stays above the keyboard");+ assert.ok(source.getBoundingClientRect().height > 60, "the keyboard leaves usable source space");+ assert.ok(button("save").getBoundingClientRect().bottom <= bounds.bottom, "save stays within the drawer");+ viewport.height = window.innerHeight;+ viewport.dispatchEvent(new Event("resize"));+ await tick();+ }+ if (capture) {+ await require("electron").ipcRenderer.invoke("skill-manager-capture", `${mode}-${window.innerWidth}-editor`);+ }+ assert.equal(button("rename").disabled, true);+ assert.equal(button("remove").disabled, true);+ const setSource = text => {+ source.value = text;+ source.dispatchEvent(new Event("input", {bubbles: true}));+ };+ const edited = source.value.replace("Original", "Updated");+ setSource(edited);+ button("save").click();+ await tick();+ await tick();+ const write = requests.find(request => request.action === "write");+ assert.equal(write.path, "directory-id/SKILL.md");+ assert.equal(write.revision, "revision-1");+ assert.equal(write.content, edited.replace(/\n/g, "\r\n"));+ assert.equal(button("save").disabled, true);++ conflict = true;+ setSource(edited + "Unsaved");+ button("save").click();+ await tick();+ await tick();+ assert.equal(source.value, edited + "Unsaved");+ assert.equal(button("save").disabled, false);++ const cancelConfirm = async () => {+ const prompt = window.siyuan.dialogs[window.siyuan.dialogs.length - 1];+ assert.notEqual(prompt, dialog);+ assert.equal(prompt.element.classList.contains("mobile-bottom-sheet-dialog"), mobile);+ prompt.element.querySelector('[data-action="cancel"]').click();+ await tick();+ };+ const acceptConfirm = async () => {+ const prompt = window.siyuan.dialogs[window.siyuan.dialogs.length - 1];+ assert.notEqual(prompt, dialog);+ prompt.element.querySelector('[data-action="confirm"]').click();+ await tick();+ await tick();+ };+ if (mobile) {+ assert.equal(manager.classList.contains("skill-manager--editing"), true);+ button("back").click();+ await cancelConfirm();+ assert.equal(manager.classList.contains("skill-manager--editing"), true);+ assert.equal(source.value, edited + "Unsaved");+ button("back").click();+ await acceptConfirm();+ assert.equal(manager.classList.contains("skill-manager--editing"), false);+ assert.equal(source.value, edited);+ assert.equal(files.scrollTop, previousScroll);+ await choose("directory-id/SKILL.md");+ setSource(edited + "Unsaved");+ }+ dialog.destroy();+ await cancelConfirm();+ assert.ok(dialog.element.isConnected);+ assert.equal(source.value, edited + "Unsaved");+ dialog.destroy();+ await acceptConfirm();+ assert.equal(dialog.element.isConnected, false);+ assert.equal(window.siyuan.dialogs.length, 0);++ load("ai/skills/manager").openSkillManager();+ await tick();+ await tick();+ const next = window.siyuan.dialogs[0];+ const nextManager = next.element.querySelector(".skill-manager");+ nextManager.querySelector('[data-path="directory-id"] .skill-manager__file').click();+ await tick();+ await tick();+ nextManager.querySelector('[data-path="directory-id/image.png"] .skill-manager__file').click();+ await tick();+ await tick();+ assert.equal(nextManager.querySelector('[data-action="save"]').disabled, true);+ assert.equal(nextManager.querySelector('[data-action="rename"]').disabled, true);+ assert.equal(nextManager.querySelector('[data-action="remove"]').disabled, true);+ if (mode === "desktop") {+ nextManager.querySelector('[data-action="open"]').click();+ assert.equal(opened[0][0], "D:/workspace/data/storage/ai/agent/skills/directory-id/image.png");+ }+ nextManager.querySelector('[data-action="newSkill"]').click();+ await tick();+ const prompt = window.siyuan.dialogs[window.siyuan.dialogs.length - 1];+ assert.notEqual(prompt, next);+ assert.equal(prompt.element.classList.contains("mobile-bottom-sheet-dialog"), mobile);+ prompt.element.querySelector("[data-input-cancel]").click();+ await tick();+ next.destroy();+ await tick();+ assert.equal(window.siyuan.dialogs.length, 0);+};++if (process.versions.electron && process.type === "browser") {+ const {app, BrowserWindow, ipcMain} = require("electron");+ app.setPath("userData", process.argv[2]);+ app.whenReady().then(async () => {+ const win = new BrowserWindow({show: false, webPreferences: {+ nodeIntegration: true, contextIsolation: false, backgroundThrottling: false, offscreen: true,+ }});+ let code = 0;+ try {+ const captureDirectory = process.env.SIYUAN_SKILL_MANAGER_CAPTURE_DIR;+ if (captureDirectory) {+ fs.mkdirSync(captureDirectory, {recursive: true});+ ipcMain.handle("skill-manager-capture", async (_event, stage) => {+ assert.match(stage, /^[a-z]+-\d+-(list|editor)$/);+ await new Promise(resolve => setTimeout(resolve, 200));+ const screenshot = await win.webContents.capturePage();+ fs.writeFileSync(path.join(captureDirectory, `${stage}.png`), screenshot.toPNG());+ });+ }+ const sass = require("sass");+ const styles = {};+ for (const name of ["base", "mobile"]) {+ styles[name] = sass.compile(path.join(__dirname, `../src/assets/scss/${name}.scss`), {+ logger: {warn() {}, debug() {}},+ }).css;+ }+ for (const [mode, width, height] of [["desktop", 1100, 844], ["browser", 1100, 844],+ ["remote", 1100, 844], ["mobile", 390, 844], ["mobile", 320, 640]]) {+ win.setContentSize(width, height);+ await win.loadURL("data:text/html,<html><body></body></html>");+ await win.webContents.insertCSS(styles[mode === "mobile" ? "mobile" : "base"] ++ ":root {--b3-font-size: 16px; --b3-font-family: sans-serif; --b3-font-family-code: monospace; --mobile-top-safe-area: 0px; --b3-theme-surface: #f6f6f6; --b3-theme-background: #fff; --b3-theme-on-background: #222; --b3-theme-on-surface: #666; --b3-border-color: #ddd; --b3-theme-surface-lighter: #ddd; --b3-border-radius: 4px; --b3-border-radius-b: 8px; --b3-theme-primary: #3573f0;}");+ await win.webContents.executeJavaScript(`(${runCases.toString()})(${JSON.stringify(path.join(__dirname, ".."))}, ${JSON.stringify(mode)}, ${Boolean(captureDirectory)})`);+ }+ } catch (error) {+ console.error(error);+ code = 1;+ } finally {+ win.destroy();+ app.exit(code);+ }+ });+} else {+ const {test} = require("node:test");+ const {execFile} = require("node:child_process");+ const {promisify} = require("node:util");+ test("skill manager preserves source and drafts across conflicts, dialogs and mobile navigation", async () => {+ const profile = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-skill-manager-"));+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ await promisify(execFile)(require("electron"), [__filename, profile], {env, windowsHide: true, timeout: 60000});+ } finally {+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));+ fs.rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});+ }+ });+}diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.mdindex 0c53d34cb4..cadd8f92b1 100644--- a/docs/API-CONTRACTS.md+++ b/docs/API-CONTRACTS.md@@ -52,6 +52,8 @@ Attribute-view contracts declare table, gallery, and kanban results separately aAI contracts retain provider configuration, model discovery and matching, confirmation decisions, session extensions, and numeric and omission semantics. Editor and agent streams declare their actual SSE events; disconnection closes upstream requests, and stream lifetimes remain within the request. OAuth pages retain their media types, HTTP statuses, and security headers. Session permission notifications use `WithAfterWrite` to preserve response-before-broadcast ordering. Arbitrary JSON remains limited to protocol extension fields and tool results.+`/api/ai/agent/manageSkills` uses strict string fields and administrator/read-only admission for workspace skill files. Relative paths identify physical directories independently of frontmatter names. Markdown reads and writes preserve raw UTF-8 source; directory and resource reads return content-based revisions without source text. Existing mutations require the current revision, share a critical section with legacy skill mutations and installation, and notify synchronization after success. Path traversal, platform aliases, links, stale revisions, and individual renaming or deletion of non-Markdown resources or root `SKILL.md` are rejected. `TestAISkillManagementContract`, `TestAPIContractAISkillManagement`, and `TestSkillManagement` cover request types, actual HTTP responses, authorization, raw content, concurrent saves, and filesystem boundaries. Run `go test -tags "fts5 sqlcipher" ./apicontract/... ./api ./util -run 'Test(AISkillManagementContract|APIContractAISkillManagement|SkillManagement|RouteCoverage)' -count=1`; the full kernel CI suite below includes all of these regressions.+Setting contracts retain partial configuration merging, existing defaults, case-insensitive struct fields, explicit null values, JSON number normalization, and parser error messages. Keyboard shortcuts and cloud authentication results declare their fixed fields while preserving their protocol-defined JSON extensions. Cloud-user admission still precedes body reads for non-administrators, and two-factor authentication keeps cloud error codes and extension fields. Frontend callers normalize persisted display settings at the same existing boundaries.Document-tree contracts retain conditional parameter validation, path and sorting semantics, omitted callbacks, pagination defaults, and document response variants. Publish authentication preserves HTTP 429 and `Retry-After` through explicitly declared additional error statuses. Publish and encrypted-notebook admission remain before deferred field validation, and document leases cover response serialization.diff --git a/docs/API-CONTRACTS.zh-CN.md b/docs/API-CONTRACTS.zh-CN.mdindex c08376009a..e259a53bc3 100644--- a/docs/API-CONTRACTS.zh-CN.md+++ b/docs/API-CONTRACTS.zh-CN.md@@ -52,6 +52,8 @@AI 契约保留供应商配置、模型发现与匹配、确认结果、会话扩展字段,以及数值和省略语义。编辑器和智能体流声明实际 SSE 事件,断开连接时关闭上游请求,流生命周期仍位于请求内部。OAuth 页面保留媒体类型、HTTP 状态和安全响应头。会话权限通知使用 `WithAfterWrite`,保留先响应再广播的顺序。任意 JSON 仅用于协议扩展字段和工具结果。+`/api/ai/agent/manageSkills` 使用严格字符串字段,并通过管理员和只读检查管理工作空间技能文件。相对路径标识实际目录,与文件头中的技能名称无关。Markdown 读写保留 UTF-8 原文;目录和资源读取只返回基于内容的版本,不返回正文。修改已有文件必须提供当前版本,与旧技能修改接口和安装共享临界区,成功后通知同步。路径穿越、平台别名、链接、过期版本,以及单独重命名或删除非 Markdown 资源、根 `SKILL.md` 的请求均被拒绝。`TestAISkillManagementContract`、`TestAPIContractAISkillManagement` 和 `TestSkillManagement` 覆盖请求类型、实际 HTTP 响应、权限、原文、并发保存和文件系统边界。运行 `go test -tags "fts5 sqlcipher" ./apicontract/... ./api ./util -run 'Test(AISkillManagementContract|APIContractAISkillManagement|SkillManagement|RouteCoverage)' -count=1`;下方完整内核 CI 测试包含这些回归用例。+设置契约保留局部配置合并、既有默认值、结构字段大小写兼容、显式 null、JSON 数字归一化及解析错误消息。快捷键与云端认证结果声明固定字段,同时保留协议定义的 JSON 扩展。非管理员查询云用户时仍先执行准入判断再读取请求体;双因素认证保留云端错误码与扩展字段。前端继续在既有边界规范化持久化的显示设置。文档树契约保留条件参数校验、路径与排序语义、回调省略规则、分页默认值及文档响应变体。发布认证通过显式声明的额外错误状态保留 HTTP 429 和 `Retry-After`。发布及加密笔记本准入仍先于延迟字段校验,文档租约覆盖响应序列化阶段。diff --git a/docs/SKILL-MANAGER.md b/docs/SKILL-MANAGER.mdnew file mode 100644index 0000000000..29654a1272--- /dev/null+++ b/docs/SKILL-MANAGER.md@@ -0,0 +1,39 @@+# Skill manager++[简体中文](SKILL-MANAGER.zh-CN.md)++Open Workspace skills in the Skills group under Settings - Artificial Intelligence. The manager edits skills stored in the current workspace at `data/storage/ai/agent/skills/<directory>/SKILL.md`. External skills from `~/.agents/skills` remain in the adjacent read-only list, where they can be enabled individually.++## Managing files++Search the file list and select `SKILL.md` or a bundled `.md` file to edit its Markdown source. Editable source files must be valid UTF-8 and at most 8 MiB. Save writes the source back to the selected path without converting it into a SiYuan document or regenerating its YAML frontmatter. Files with consistent CRLF line endings retain that format; editing a file with mixed line endings normalizes them to LF. Leaving a file unmodified or discarding changes preserves its original source. Unsaved changes require confirmation before they are discarded.++Create a skill to add a directory containing `SKILL.md`. Inside a skill, create Markdown files and folders, rename files or folders within their current parent, and delete Markdown files or folders. A skill's root `SKILL.md` cannot be renamed or deleted on its own; delete the containing skill to remove it. Renaming a skill directory does not change the independent `name` field in its frontmatter.++Other resource files appear in the list but cannot be edited, renamed, or deleted individually in the manager. A local desktop client can open their file location for management with other applications. Deleting a folder also deletes every resource inside it, including files that the manager cannot edit, and cannot be undone through the manager.++On mobile, the manager opens in a bottom drawer. Selecting a file opens its editor; returning to the list preserves the list's scroll position.++## File identity and concurrent changes++Operations use paths relative to the workspace's skills directory. A skill's frontmatter `name` is not its file identity: names may differ from directory names, and duplicate names do not hide files from the manager. Existing skill discovery and precedence rules remain unchanged.++Reading a file or folder returns a revision. Updating, renaming, or deleting an existing item requires that revision, and the operation is rejected if the item has changed. A conflict leaves the current on-disk contents intact; preserve your draft and reload the item before deciding how to merge the changes. The manager does not provide a force-overwrite operation.++The management interface rejects paths through symbolic links, paths outside the skills directory, and ambiguous Windows names. This does not change the agent's existing ability to load supported linked skills.++## HTTP API++`POST /api/ai/agent/manageSkills` uses the standard API response envelope and requires an authenticated administrator in a writable workspace. Requests contain `action` and, depending on the action, `path`, `target`, `content`, and `revision`. Paths use `/` separators and are relative to `data/storage/ai/agent/skills`.++| Action | Behavior |+| --- | --- |+| `list` | Return the file tree as `entries`, with `path`, `isDir`, and `editable` for each entry |+| `read` | Return the item's `revision`, plus original `content` for editable Markdown files |+| `create` | Create a top-level skill directory and its `SKILL.md` |+| `mkdir` | Create a folder inside a skill |+| `write` | Write a Markdown file inside a skill; an existing file requires its current `revision`, and a new file uses an empty revision |+| `move` | Rename an item to `target` within the same parent, using its current `revision` |+| `remove` | Delete an item using its current `revision` |++The root `SKILL.md`, non-Markdown files, symbolic links, and folder deletion follow the restrictions described above. A rejected revision or invalid operation returns an error instead of changing the item. Existing name-based skill APIs remain available for compatibility; management clients should use relative paths through this endpoint.diff --git a/docs/SKILL-MANAGER.zh-CN.md b/docs/SKILL-MANAGER.zh-CN.mdnew file mode 100644index 0000000000..b4585c6b22--- /dev/null+++ b/docs/SKILL-MANAGER.zh-CN.md@@ -0,0 +1,39 @@+# 技能管理++[English](SKILL-MANAGER.md)++在设置 - 人工智能的技能分组中打开工作空间技能,即可管理当前工作空间 `data/storage/ai/agent/skills/<目录>/SKILL.md` 中的技能。来自 `~/.agents/skills` 的外部技能保留在相邻的只读列表中,可以逐个启用。++## 管理文件++搜索文件列表,选择 `SKILL.md` 或技能附带的 `.md` 文件,即可编辑 Markdown 源码。可编辑的源码文件必须采用有效的 UTF-8 编码,且不超过 8 MiB。保存时直接写回所选路径,不转换为思源文档,也不重新生成 YAML 前置元数据。编辑器保留统一的 CRLF 换行格式;编辑混合换行的文件后,换行符会统一为 LF。未修改文件或放弃更改时保留原文。放弃未保存的更改前需要确认。++新建技能会创建包含 `SKILL.md` 的目录。在技能内部,可以新建 Markdown 文件和文件夹,在当前父目录内重命名文件或文件夹,以及删除 Markdown 文件或文件夹。技能根目录中的 `SKILL.md` 不能单独重命名或删除;如需移除技能,应删除整个技能目录。重命名技能目录不会修改前置元数据中独立的 `name` 字段。++其他资源文件会显示在列表中,但不能在管理界面内单独编辑、重命名或删除。本地桌面端可以打开文件位置,再使用其他应用管理这些资源。删除文件夹也会删除其中的全部资源,包括管理界面无法编辑的文件,且无法通过技能管理撤销。++移动端通过底部抽屉展示技能管理。选择文件后进入编辑页面,返回列表时保留列表滚动位置。++## 文件标识与并发修改++操作通过相对于工作空间技能目录的路径定位文件。前置元数据中的 `name` 不作为文件标识:名称可以不同于目录名,重名也不会使文件在管理列表中隐藏。现有技能发现和优先级规则保持不变。++读取文件或文件夹会返回修订号。更新、重命名或删除已有项目时必须提交该修订号;如果项目已经变化,操作会被拒绝。发生冲突时,磁盘上的当前内容保持不变;请保留编辑草稿,重新加载项目后再决定如何合并更改。管理界面不提供强制覆盖操作。++管理接口拒绝经过符号链接的路径、技能目录之外的路径以及存在歧义的 Windows 名称。这不会改变智能体现有的链接技能加载能力。++## HTTP API++`POST /api/ai/agent/manageSkills` 使用标准 API 响应结构,要求调用者已通过身份验证、具有管理员权限,且工作空间不处于只读状态。请求包含 `action`,并根据操作提供 `path`、`target`、`content` 和 `revision`。路径使用 `/` 分隔,相对于 `data/storage/ai/agent/skills`。++| 操作 | 行为 |+| --- | --- |+| `list` | 通过 `entries` 返回文件树,每项包含 `path`、`isDir` 和 `editable` |+| `read` | 返回项目的 `revision`,可编辑的 Markdown 文件另返回原始 `content` |+| `create` | 新建顶层技能目录及其 `SKILL.md` |+| `mkdir` | 在技能内部新建文件夹 |+| `write` | 写入技能内部的 Markdown 文件;已有文件必须提供当前 `revision`,新文件使用空修订号 |+| `move` | 在同一父目录内将项目重命名为 `target`,并提供当前 `revision` |+| `remove` | 删除项目,并提供当前 `revision` |++根目录中的 `SKILL.md`、非 Markdown 文件、符号链接以及文件夹删除遵循前述限制。修订号不匹配或操作无效时返回错误,不修改目标项目。现有按名称操作的技能 API 保留兼容,管理客户端应通过此接口使用相对路径。diff --git a/kernel/api/contract_skill_manage_test.go b/kernel/api/contract_skill_manage_test.gonew file mode 100644index 0000000000..33cd782c73--- /dev/null+++ b/kernel/api/contract_skill_manage_test.go@@ -0,0 +1,133 @@+package api++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAPIContractAISkillManagement(t *testing.T) {+ aiContractConfiguration(t)+ model.Conf.Sync = conf.NewSync()+ engine := gin.New()+ engine.POST("/api/ai/agent/manageSkills", manageSkills)+ call := func(body string, code int) apicontract.AISkillFileData {+ t.Helper()+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/ai/agent/manageSkills", strings.NewReader(body)))+ requireAPIContract(t, "POST", "/api/ai/agent/manageSkills", recorder)+ var result struct {+ Code int `json:"code"`+ Data apicontract.AISkillFileData `json:"data"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil || result.Code != code {+ t.Fatalf("request %s: %s %v", body, recorder.Body.String(), err)+ }+ return result.Data+ }+ list := call(`{"action":"list"}`, 0)+ if list.Entries == nil || len(*list.Entries) != 0 {+ t.Fatalf("empty list must contain an empty entries array: %+v", list)+ }+ created := call(`{"action":"create","path":"directory","content":"---\r\nname: display-name\r\n---\r\nOriginal\r\n"}`, 0)+ if created.Content == nil || created.Revision == "" {+ t.Fatalf("missing created source: %+v", created)+ }+ read := call(`{"action":"read","path":"directory/SKILL.md"}`, 0)+ if read.Content == nil || *read.Content != *created.Content || read.Revision != created.Revision {+ t.Fatalf("raw source changed: %+v", read)+ }+ call(`{"action":"write","path":"directory/SKILL.md","content":"overwritten","revision":"stale"}`, -1)+ call(`{"action":"write","path":"directory/SKILL.md","content":""}`, -1)+ call(`{"action":"read","path":"../outside.md"}`, -1)+ call(`{"action":null}`, -1)+ call(`{"action":"read","path":true}`, -1)+ call(`{"action":"unknown"}`, -1)+ call(`{`, -1)+ encoded, err := json.Marshal(apicontract.AISkillFileRequest{Action: "write", Path: "directory/SKILL.md", Content: "", Revision: read.Revision})+ if err != nil {+ t.Fatal(err)+ }+ written := call(string(encoded), 0)+ read = call(`{"action":"read","path":"directory/SKILL.md"}`, 0)+ if read.Content == nil || *read.Content != "" || written.Revision != read.Revision {+ t.Fatalf("empty content omitted or revision incorrect: %+v", read)+ }+ call(`{"action":"mkdir","path":"directory/references"}`, 0)+ call(`{"action":"write","path":"directory/references/reference.md","content":"reference"}`, 0)+ resource := filepath.Join(util.SkillsDir(), "directory", "asset.bin")+ if err = os.WriteFile(resource, []byte{0, 255}, 0644); err != nil {+ t.Fatal(err)+ }+ asset := call(`{"action":"read","path":"directory/asset.bin"}`, 0)+ if asset.Content != nil || asset.Revision == "" {+ t.Fatalf("asset content or revision incorrect: %+v", asset)+ }+ directory := call(`{"action":"read","path":"directory"}`, 0)+ if directory.Content != nil || directory.Revision == "" {+ t.Fatalf("directory content or revision incorrect: %+v", directory)+ }+ encoded, err = json.Marshal(apicontract.AISkillFileRequest{Action: "move", Path: "directory", Target: "renamed", Revision: directory.Revision})+ if err != nil {+ t.Fatal(err)+ }+ call(string(encoded), 0)+ directory = call(`{"action":"read","path":"renamed"}`, 0)+ encoded, err = json.Marshal(apicontract.AISkillFileRequest{Action: "remove", Path: "renamed", Revision: directory.Revision})+ if err != nil {+ t.Fatal(err)+ }+ call(string(encoded), 0)+ if _, err = os.Stat(filepath.Join(util.SkillsDir(), "renamed")); !os.IsNotExist(err) {+ t.Fatalf("removed skill is still present: %v", err)+ }+}++func TestAPIContractAISkillManagementAuthorization(t *testing.T) {+ aiContractConfiguration(t)+ previousReadonly := util.ReadOnly+ t.Cleanup(func() { util.ReadOnly = previousReadonly })+ for _, test := range []struct {+ name string+ role model.Role+ readonly bool+ status int+ }{+ {"reader", model.RoleReader, false, http.StatusForbidden},+ {"editor", model.RoleEditor, false, http.StatusForbidden},+ {"readonly", model.RoleAdministrator, true, http.StatusOK},+ } {+ t.Run(test.name, func(t *testing.T) {+ util.ReadOnly = test.readonly+ engine := gin.New()+ engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, test.role); c.Next() })+ ServeAPI(engine)+ request := httptest.NewRequest("POST", "/api/ai/agent/manageSkills", nil)+ request.Body = aiUnreadBody{t: t}+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, request)+ if recorder.Code != test.status {+ t.Fatalf("authorization changed: %d %s", recorder.Code, recorder.Body.String())+ }+ if test.readonly {+ requireAPIContract(t, "POST", "/api/ai/agent/manageSkills", recorder)+ if !strings.Contains(recorder.Body.String(), `"code":-1`) {+ t.Fatalf("read-only request reached handler: %s", recorder.Body.String())+ }+ }+ if _, err := os.Stat(util.SkillsDir()); !os.IsNotExist(err) {+ t.Fatalf("denied request modified workspace: %v", err)+ }+ })+ }+}diff --git a/kernel/api/router.go b/kernel/api/router.goindex 6931f309b1..32cece964c 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -664,6 +664,7 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/ai/agent/saveSession", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, saveSession)ginServer.Handle("POST", "/api/ai/agent/removeSession", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, removeSession)ginServer.Handle("POST", "/api/ai/agent/lsSkills", model.CheckAuth, model.CheckAdminRole, lsSkills)+ ginServer.Handle("POST", "/api/ai/agent/manageSkills", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, manageSkills)ginServer.Handle("POST", "/api/ai/agent/lsUserSkills", model.CheckAuth, model.CheckAdminRole, lsUserSkills)ginServer.Handle("POST", "/api/ai/agent/getSkill", model.CheckAuth, model.CheckAdminRole, getSkill)ginServer.Handle("POST", "/api/ai/agent/saveSkill", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, saveSkill)diff --git a/kernel/api/skill_manage.go b/kernel/api/skill_manage.gonew file mode 100644index 0000000000..6868325d98--- /dev/null+++ b/kernel/api/skill_manage.go@@ -0,0 +1,37 @@+package api++import (+ "path/filepath"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++var manageSkills = contractHandler(apicontract.AIManageSkills, manageSkillsContract)++func manageSkillsContract(c *gin.Context, request apicontract.AISkillFileRequest) apicontract.Response[apicontract.AISkillFileData] {+ data, err := util.ManageSkillFiles(util.SkillFileRequest{+ Action: request.Action, Path: request.Path, Target: request.Target, Content: request.Content, Revision: request.Revision,+ })+ if err != nil {+ return apicontract.Failure[apicontract.AISkillFileData](-1, util.EscapeHTML(err.Error()))+ }+ ret := apicontract.AISkillFileData{Content: data.Content, Revision: data.Revision}+ if data.Entries != nil {+ entries := make([]apicontract.AISkillFileEntry, 0, len(data.Entries))+ for _, entry := range data.Entries {+ entries = append(entries, apicontract.AISkillFileEntry{Path: entry.Path, IsDir: entry.IsDir, Editable: entry.Editable})+ }+ ret.Entries = &entries+ }+ if request.Action != "list" && request.Action != "read" {+ changed := []string{filepath.Join(util.SkillsDir(), filepath.FromSlash(request.Path))}+ if request.Action == "move" {+ changed = append(changed, filepath.Join(util.SkillsDir(), filepath.FromSlash(request.Target)))+ }+ model.IncSyncIfNeeded(changed...)+ }+ return apicontract.Success(ret)+}diff --git a/kernel/apicontract/ai_skill_manage.go b/kernel/apicontract/ai_skill_manage.gonew file mode 100644index 0000000000..760c8cb333--- /dev/null+++ b/kernel/apicontract/ai_skill_manage.go@@ -0,0 +1,22 @@+package apicontract++// AISkillFileRequest 使用工作空间技能目录内的相对路径,保留 Markdown 原文和版本。+type AISkillFileRequest struct {+ Action string `json:"action"`+ Path string `json:"path" api:"optional"`+ Target string `json:"target" api:"optional"`+ Content string `json:"content" api:"optional"`+ Revision string `json:"revision" api:"optional"`+}++type AISkillFileEntry struct {+ Path string `json:"path"`+ IsDir bool `json:"isDir"`+ Editable bool `json:"editable"`+}++type AISkillFileData struct {+ Entries *[]AISkillFileEntry `json:"entries,omitempty"`+ Content *string `json:"content,omitempty"`+ Revision string `json:"revision,omitempty"`+}diff --git a/kernel/apicontract/ai_skill_manage_test.go b/kernel/apicontract/ai_skill_manage_test.gonew file mode 100644index 0000000000..9136ce9e98--- /dev/null+++ b/kernel/apicontract/ai_skill_manage_test.go@@ -0,0 +1,19 @@+package apicontract++import (+ "strings"+ "testing"+)++func TestAISkillManagementContract(t *testing.T) {+ for _, body := range []string{``, `{}`, `{"action":null}`, `{"action":false}`, `{"action":"read","path":null}`, `{"action":"write","content":123}`, `{"action":"remove","revision":false}`} {+ if _, err := AIManageSkills.Decode(strings.NewReader(body)); err == nil {+ t.Fatalf("accepted invalid request %s", body)+ }+ }+ for _, body := range []string{`{"action":"list"}`, `{"action":"write","path":"skill/a.md","content":"","revision":""}`, `{"action":"move","path":"a","target":"b","revision":"hash"}`} {+ if _, err := AIManageSkills.Decode(strings.NewReader(body)); err != nil {+ t.Fatalf("rejected valid request %s: %v", body, err)+ }+ }+}diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex 8f73311200..0421ee15ee 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -940,6 +940,7 @@ var AIGetSkill = define[AISkillNameRequest, AISkillData]("getSkill", "/api/ai/agvar AISaveSkill = define[AISkillSaveRequest, Null]("saveSkill", "/api/ai/agent/saveSkill", StructJSONBody, ResponseOptions{}, "POST")var AIRemoveSkill = define[AISkillNameRequest, Null]("removeSkill", "/api/ai/agent/removeSkill", StructJSONBody, ResponseOptions{}, "POST")var AIRenameSkill = define[AISkillRenameRequest, Null]("renameSkill", "/api/ai/agent/renameSkill", StructJSONBody, ResponseOptions{}, "POST")+var AIManageSkills = define[AISkillFileRequest, AISkillFileData]("manageSkills", "/api/ai/agent/manageSkills", JSONBody, ResponseOptions{}, "POST")var AIEditorChat = define[AIEditorChatRequest, Null]("aiEditorChat", "/api/ai/editor/chat", StructJSONBody, aiEditorSSEOptions(), "POST")var AIAgentChat = define[AIAgentChatRequest, Null]("agentChat", "/api/ai/agent/chat", StructJSONBody, aiAgentSSEOptions(), "POST")diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex 42c25afbe4..9636271161 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -5037,6 +5037,75 @@],"additionalProperties": false},+ "AISkillFileData": {+ "type": "object",+ "properties": {+ "content": {+ "type": "string"+ },+ "entries": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "$ref": "#/$defs/AISkillFileEntry"+ }+ },+ {+ "type": "null"+ }+ ]+ },+ "revision": {+ "type": "string"+ }+ },+ "additionalProperties": false+ },+ "AISkillFileEntry": {+ "type": "object",+ "properties": {+ "editable": {+ "type": "boolean"+ },+ "isDir": {+ "type": "boolean"+ },+ "path": {+ "type": "string"+ }+ },+ "required": [+ "editable",+ "isDir",+ "path"+ ],+ "additionalProperties": false+ },+ "AISkillFileRequestInput": {+ "type": "object",+ "properties": {+ "action": {+ "type": "string"+ },+ "content": {+ "type": "string"+ },+ "path": {+ "type": "string"+ },+ "revision": {+ "type": "string"+ },+ "target": {+ "type": "string"+ }+ },+ "required": [+ "action"+ ],+ "additionalProperties": false+ },"AISkillInfo": {"type": "object","properties": {@@ -109510,6 +109579,81 @@]}},+ {+ "method": "POST",+ "path": "/api/ai/agent/manageSkills",+ "handler": "manageSkills",+ "body": "json",+ "request": {+ "$ref": "#/$defs/AISkillFileRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/AISkillFileData"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },{"method": "POST","path": "/api/ai/agent/question",diff --git a/kernel/util/skill.go b/kernel/util/skill.goindex 3583c1a81f..977949989c 100644--- a/kernel/util/skill.go+++ b/kernel/util/skill.go@@ -419,6 +419,8 @@ func ReadSkill(name string, enabledUserSkills []string) (string, error) {}func SaveSkill(name, content string) error {+ skillManagementLock.Lock()+ defer skillManagementLock.Unlock()if err := validateSkillName(name); err != nil {return err}@@ -435,6 +437,8 @@ func SaveSkill(name, content string) error {}func RemoveSkill(name string) error {+ skillManagementLock.Lock()+ defer skillManagementLock.Unlock()if err := validateSkillName(name); err != nil {return err}@@ -450,6 +454,8 @@ func RemoveSkill(name string) error {}func RenameSkill(oldName, newName string) error {+ skillManagementLock.Lock()+ defer skillManagementLock.Unlock()if err := validateSkillName(oldName); err != nil {return err}@@ -788,6 +794,8 @@ func findSkillDirsRecursive(dir, root string) []string {// installSkillDirs 把若干相对 root 的 skill 目录落地到 SkillsDir()func installSkillDirs(relDirs []string, root string) (*InstallSkillResult, error) {+ skillManagementLock.Lock()+ defer skillManagementLock.Unlock()result := &InstallSkillResult{}for _, rel := range relDirs {srcDir := filepath.Join(root, rel)diff --git a/kernel/util/skill_manage.go b/kernel/util/skill_manage.gonew file mode 100644index 0000000000..86f8c186c4--- /dev/null+++ b/kernel/util/skill_manage.go@@ -0,0 +1,359 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+// Licensed under the GNU Affero General Public License, version 3 or later.++package util++import (+ "crypto/sha256"+ "errors"+ "fmt"+ "io"+ "io/fs"+ "os"+ "path"+ "path/filepath"+ "strings"+ "sync"+ "unicode"+ "unicode/utf8"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/filelock"+)++const maxManagedSkillSourceSize = 8 * 1024 * 1024++var skillManagementLock sync.Mutex++type SkillFileRequest struct {+ Action string+ Path string+ Target string+ Content string+ Revision string+}++type SkillFileEntry struct {+ Path string+ IsDir bool+ Editable bool+}++type SkillFileData struct {+ Entries []SkillFileEntry+ Content *string+ Revision string+}++// 管理操作使用真实的相对路径,不使用技能正文中的名称作为文件标识。+func validateManagedSkillPath(p string) error {+ if p == "" || !fs.ValidPath(p) || strings.ContainsAny(p, "\\:") {+ return errors.New("invalid skill path")+ }+ for _, part := range strings.Split(p, "/") {+ if strings.HasPrefix(part, ".") || strings.TrimSpace(part) != part || strings.HasSuffix(part, ".") ||+ strings.ContainsAny(part, "<>\"|?*~") || strings.ContainsFunc(part, unicode.IsControl) {+ return errors.New("invalid skill path component")+ }+ device := strings.ToUpper(strings.TrimRight(strings.SplitN(part, ".", 2)[0], " ."))+ if device == "CON" || device == "PRN" || device == "AUX" || device == "NUL" || device == "CONIN$" || device == "CONOUT$" {+ return errors.New("reserved skill file name")+ }+ if strings.HasPrefix(device, "COM") || strings.HasPrefix(device, "LPT") {+ number := strings.TrimPrefix(strings.TrimPrefix(device, "COM"), "LPT")+ if len([]rune(number)) == 1 && strings.ContainsAny(number, "0123456789¹²³") {+ return errors.New("reserved skill file name")+ }+ }+ }+ return nil+}++// 从工作空间目录逐层打开根目录,拒绝把管理操作重定向到链接目标。+func openManagedSkillsRoot() (*os.Root, error) {+ workspace, err := os.OpenRoot(DataDir)+ if err != nil {+ return nil, err+ }+ defer workspace.Close()+ for _, p := range []string{"storage", "storage/ai", "storage/ai/agent", "storage/ai/agent/skills"} {+ if err = workspace.Mkdir(p, 0755); err != nil && !errors.Is(err, os.ErrExist) {+ return nil, err+ }+ info, statErr := workspace.Lstat(p)+ if statErr != nil {+ return nil, statErr+ }+ if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {+ return nil, errors.New("skill storage is not a regular directory")+ }+ }+ return workspace.OpenRoot("storage/ai/agent/skills")+}++func checkManagedSkillPath(root *os.Root, p string) error {+ if err := validateManagedSkillPath(p); err != nil {+ return err+ }+ parts := strings.Split(p, "/")+ for i := range parts {+ info, err := root.Lstat(strings.Join(parts[:i+1], "/"))+ if errors.Is(err, os.ErrNotExist) && i == len(parts)-1 {+ return nil+ }+ if err != nil {+ return err+ }+ if info.Mode()&os.ModeSymlink != 0 || (!info.IsDir() && !info.Mode().IsRegular()) {+ return errors.New("skill path is not a regular file or directory")+ }+ }+ return nil+}++func isManagedSkillMarkdown(p string) bool {+ return strings.Contains(p, "/") && strings.EqualFold(path.Ext(p), ".md")+}++func isManagedSkillManifest(p string) bool {+ return strings.Count(p, "/") == 1 && strings.EqualFold(path.Base(p), "SKILL.md")+}++// 目录版本包含每个资源的内容哈希,保持大小和修改时间不变的外部编辑也会产生冲突。+func managedSkillRevision(root *os.Root, p string) (string, error) {+ h := sha256.New()+ err := fs.WalkDir(root.FS(), p, func(name string, entry fs.DirEntry, walkErr error) error {+ if walkErr != nil {+ return walkErr+ }+ info, err := entry.Info()+ if err != nil {+ return err+ }+ if info.Mode()&os.ModeSymlink != 0 || (!info.IsDir() && !info.Mode().IsRegular()) {+ return errors.New("skill directory contains a link or special file")+ }+ if info.IsDir() {+ fmt.Fprintf(h, "directory\x00%s\x00", name)+ return nil+ }+ file, err := root.Open(name)+ if err != nil {+ return err+ }+ hash := sha256.New()+ _, copyErr := io.Copy(hash, file)+ closeErr := file.Close()+ if copyErr != nil {+ return copyErr+ }+ if closeErr != nil {+ return closeErr+ }+ if name == p {+ h = hash+ } else {+ fmt.Fprintf(h, "file\x00%s\x00%x\x00", name, hash.Sum(nil))+ }+ return nil+ })+ return fmt.Sprintf("%x", h.Sum(nil)), err+}++func readManagedSkillSource(root *os.Root, p string) (string, error) {+ file, err := root.Open(p)+ if err != nil {+ return "", err+ }+ defer file.Close()+ info, err := file.Stat()+ if err != nil {+ return "", err+ }+ if !info.Mode().IsRegular() || info.Size() > maxManagedSkillSourceSize {+ return "", errors.New("invalid or oversized skill source")+ }+ content, err := io.ReadAll(io.LimitReader(file, maxManagedSkillSourceSize+1))+ if err != nil {+ return "", err+ }+ if len(content) > maxManagedSkillSourceSize || !utf8.Valid(content) {+ return "", errors.New("skill source must be UTF-8 and at most 8 MiB")+ }+ return string(content), nil+}++// 写入临时文件并同步后替换,发生写入错误时保留原文及其换行和元数据。+func writeManagedSkillSource(root *os.Root, p, content string, create bool, revision string) error {+ if len(content) > maxManagedSkillSourceSize || !utf8.ValidString(content) {+ return errors.New("skill source must be UTF-8 and at most 8 MiB")+ }+ target := p+ if !create {+ target = path.Join(path.Dir(p), ".skill-"+ast.NewNodeID())+ }+ file, err := root.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)+ if err != nil {+ return err+ }+ complete := false+ defer func() {+ if !complete || !create {+ root.Remove(target)+ }+ }()+ _, err = file.WriteString(content)+ if err == nil {+ err = file.Sync()+ }+ closeErr := file.Close()+ if err != nil {+ return err+ }+ if closeErr != nil {+ return closeErr+ }+ if !create {+ // 临时文件落盘后重新校验,避免覆盖此期间由外部编辑器保存的内容。+ if err = checkManagedSkillPath(root, p); err != nil {+ return err+ }+ currentRevision, revisionErr := managedSkillRevision(root, p)+ if revisionErr != nil {+ return revisionErr+ }+ if revision == "" || revision != currentRevision {+ return errors.New("skill changed; reload it before saving, renaming or deleting")+ }+ if err = root.Rename(target, p); err != nil {+ return err+ }+ }+ complete = true+ return nil+}++func ManageSkillFiles(request SkillFileRequest) (SkillFileData, error) {+ skillManagementLock.Lock()+ defer skillManagementLock.Unlock()+ ret := SkillFileData{}+ switch request.Action {+ case "list", "read", "write", "create", "mkdir", "move", "remove":+ default:+ return ret, errors.New("unsupported skill operation")+ }+ root, err := openManagedSkillsRoot()+ if err != nil {+ return ret, err+ }+ defer root.Close()+ if request.Action == "list" {+ ret.Entries = []SkillFileEntry{}+ err = fs.WalkDir(root.FS(), ".", func(p string, entry fs.DirEntry, walkErr error) error {+ if walkErr != nil || p == "." {+ return walkErr+ }+ // 未解析或被同名技能遮蔽的目录也保留在列表中,链接只展示而不跟随。+ editable := entry.Type().IsRegular() && isManagedSkillMarkdown(p) && validateManagedSkillPath(p) == nil+ ret.Entries = append(ret.Entries, SkillFileEntry{Path: p, IsDir: entry.IsDir(), Editable: editable})+ return nil+ })+ return ret, err+ }+ if err = checkManagedSkillPath(root, request.Path); err != nil {+ return ret, err+ }+ abs := filepath.Join(root.Name(), filepath.FromSlash(request.Path))+ filelock.Lock(abs)+ defer filelock.Unlock(abs)+ info, statErr := root.Lstat(request.Path)+ if request.Action == "create" {+ if strings.Contains(request.Path, "/") || !errors.Is(statErr, os.ErrNotExist) {+ return ret, errors.New("skill directory already exists or is invalid")+ }+ content := request.Content+ if content == "" {+ content = "---\nname: " + request.Path + "\ndescription: \n---\n\n"+ }+ tmp := ".skill-" + ast.NewNodeID()+ if err = root.Mkdir(tmp, 0755); err != nil {+ return ret, err+ }+ defer root.RemoveAll(tmp)+ if err = writeManagedSkillSource(root, path.Join(tmp, "SKILL.md"), content, true, ""); err != nil {+ return ret, err+ }+ if err = root.Rename(tmp, request.Path); err != nil {+ return ret, err+ }+ ret.Content = &content+ ret.Revision = fmt.Sprintf("%x", sha256.Sum256([]byte(content)))+ return ret, nil+ }+ if request.Action == "mkdir" {+ if !strings.Contains(request.Path, "/") {+ return ret, errors.New("create a skill before creating its subdirectories")+ }+ return ret, root.Mkdir(request.Path, 0755)+ }+ if statErr != nil && !(request.Action == "write" && request.Revision == "" && errors.Is(statErr, os.ErrNotExist)) {+ return ret, statErr+ }+ if request.Action == "read" {+ if !info.IsDir() && isManagedSkillMarkdown(request.Path) {+ content, readErr := readManagedSkillSource(root, request.Path)+ if readErr != nil {+ return ret, readErr+ }+ ret.Content = &content+ ret.Revision = fmt.Sprintf("%x", sha256.Sum256([]byte(content)))+ return ret, nil+ }+ ret.Revision, err = managedSkillRevision(root, request.Path)+ return ret, err+ }+ if (info == nil || !info.IsDir()) && !isManagedSkillMarkdown(request.Path) {+ return ret, errors.New("only Markdown files inside a skill can be edited")+ }+ if (request.Action == "move" || request.Action == "remove") && isManagedSkillManifest(request.Path) {+ return ret, errors.New("rename or delete the skill directory instead of SKILL.md")+ }+ if info != nil {+ revision, revisionErr := managedSkillRevision(root, request.Path)+ if revisionErr != nil {+ return ret, revisionErr+ }+ if request.Revision == "" || request.Revision != revision {+ return ret, errors.New("skill changed; reload it before saving, renaming or deleting")+ }+ }+ switch request.Action {+ case "write":+ if info != nil && info.IsDir() {+ return ret, errors.New("cannot write a skill directory")+ }+ if err = writeManagedSkillSource(root, request.Path, request.Content, info == nil, request.Revision); err != nil {+ return ret, err+ }+ ret.Revision = fmt.Sprintf("%x", sha256.Sum256([]byte(request.Content)))+ return ret, nil+ case "move":+ if err = checkManagedSkillPath(root, request.Target); err != nil {+ return ret, err+ }+ if path.Dir(request.Path) != path.Dir(request.Target) || (!info.IsDir() && !isManagedSkillMarkdown(request.Target)) {+ return ret, errors.New("skills and Markdown files can only be renamed in the same directory")+ }+ if _, err = root.Lstat(request.Target); !errors.Is(err, os.ErrNotExist) {+ return ret, errors.New("skill destination already exists or is inaccessible")+ }+ return ret, root.Rename(request.Path, request.Target)+ case "remove":+ if info.IsDir() {+ return ret, root.RemoveAll(request.Path)+ }+ return ret, root.Remove(request.Path)+ }+ return ret, errors.New("unsupported skill operation")+}diff --git a/kernel/util/skill_manage_test.go b/kernel/util/skill_manage_test.gonew file mode 100644index 0000000000..d2d61c65a3--- /dev/null+++ b/kernel/util/skill_manage_test.go@@ -0,0 +1,243 @@+package util++import (+ "bytes"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "testing"+)++func managedSkillTestWorkspace(t *testing.T) {+ t.Helper()+ previous := DataDir+ DataDir = t.TempDir()+ t.Cleanup(func() { DataDir = previous })+}++func requireManagedSkill(t *testing.T, request SkillFileRequest) SkillFileData {+ t.Helper()+ data, err := ManageSkillFiles(request)+ if err != nil {+ t.Fatalf("%+v: %v", request, err)+ }+ return data+}++func TestSkillManagementRawFiles(t *testing.T) {+ managedSkillTestWorkspace(t)+ content := "---\r\nname: display-name\r\ndescription: example\r\ncustom: [one, two]\r\n---\r\n\r\nOriginal\r\n"+ requireManagedSkill(t, SkillFileRequest{Action: "create", Path: "actual-directory", Content: content})+ requireManagedSkill(t, SkillFileRequest{Action: "create", Path: "shadowed", Content: content})+ if err := os.Mkdir(filepath.Join(SkillsDir(), "incomplete"), 0755); err != nil {+ t.Fatal(err)+ }+ requireManagedSkill(t, SkillFileRequest{Action: "mkdir", Path: "actual-directory/references"})+ requireManagedSkill(t, SkillFileRequest{Action: "write", Path: "actual-directory/references/readme.md", Content: "reference\r\n"})+ resourcePath := filepath.Join(SkillsDir(), "actual-directory", "resource.bin")+ resource := []byte{0, 1, 2, 255}+ if err := os.WriteFile(resourcePath, resource, 0644); err != nil {+ t.Fatal(err)+ }+ entries := requireManagedSkill(t, SkillFileRequest{Action: "list"}).Entries+ wanted := map[string]bool{"actual-directory": false, "shadowed": false, "incomplete": false, "actual-directory/SKILL.md": true, "actual-directory/resource.bin": false, "actual-directory/references/readme.md": true}+ for _, entry := range entries {+ if editable, ok := wanted[entry.Path]; ok {+ if editable != entry.Editable {+ t.Fatalf("wrong editability: %+v", entry)+ }+ delete(wanted, entry.Path)+ }+ }+ if len(wanted) != 0 {+ t.Fatalf("missing invalid or shadowed skills: %v", wanted)+ }+ read := requireManagedSkill(t, SkillFileRequest{Action: "read", Path: "actual-directory/SKILL.md"})+ if read.Content == nil || *read.Content != content {+ t.Fatalf("source changed: %+v", read)+ }+ updated := strings.Replace(content, "Original", "Modified", 1)+ requireManagedSkill(t, SkillFileRequest{Action: "write", Path: "actual-directory/SKILL.md", Content: updated, Revision: read.Revision})+ if _, err := os.Stat(filepath.Join(SkillsDir(), "display-name")); !os.IsNotExist(err) {+ t.Fatalf("frontmatter name created another skill: %v", err)+ }+ actual, err := os.ReadFile(filepath.Join(SkillsDir(), "actual-directory", "SKILL.md"))+ if err != nil || string(actual) != updated {+ t.Fatalf("raw source changed: %q %v", actual, err)+ }+ actual, err = os.ReadFile(resourcePath)+ if err != nil || !bytes.Equal(actual, resource) {+ t.Fatalf("resource changed: %v %v", actual, err)+ }+ resourceRead := requireManagedSkill(t, SkillFileRequest{Action: "read", Path: "actual-directory/resource.bin"})+ if resourceRead.Content != nil || resourceRead.Revision == "" {+ t.Fatalf("resource exposed content or lacks revision: %+v", resourceRead)+ }+ for _, action := range []string{"write", "move", "remove"} {+ if _, err = ManageSkillFiles(SkillFileRequest{Action: action, Path: "actual-directory/resource.bin", Target: "actual-directory/resource.md", Content: "overwrite", Revision: resourceRead.Revision}); err == nil {+ t.Fatalf("resource permits %s", action)+ }+ }+ read = requireManagedSkill(t, SkillFileRequest{Action: "read", Path: "actual-directory/SKILL.md"})+ for _, action := range []string{"move", "remove"} {+ if _, err = ManageSkillFiles(SkillFileRequest{Action: action, Path: "actual-directory/SKILL.md", Target: "actual-directory/renamed.md", Revision: read.Revision}); err == nil {+ t.Fatalf("manifest permits %s", action)+ }+ }+ directory := requireManagedSkill(t, SkillFileRequest{Action: "read", Path: "actual-directory"})+ requireManagedSkill(t, SkillFileRequest{Action: "move", Path: "actual-directory", Target: "renamed", Revision: directory.Revision})+ directory = requireManagedSkill(t, SkillFileRequest{Action: "read", Path: "renamed"})+ requireManagedSkill(t, SkillFileRequest{Action: "remove", Path: "renamed", Revision: directory.Revision})+ if _, err = os.Stat(filepath.Join(SkillsDir(), "renamed")); !os.IsNotExist(err) {+ t.Fatalf("skill directory not removed: %v", err)+ }+}++func TestSkillManagementRevisionConflicts(t *testing.T) {+ managedSkillTestWorkspace(t)+ requireManagedSkill(t, SkillFileRequest{Action: "create", Path: "skill", Content: "first"})+ read := requireManagedSkill(t, SkillFileRequest{Action: "read", Path: "skill/SKILL.md"})+ var wg sync.WaitGroup+ results := make(chan error, 2)+ for _, content := range []string{"second", "third"} {+ wg.Go(func() {+ _, err := ManageSkillFiles(SkillFileRequest{Action: "write", Path: "skill/SKILL.md", Content: content, Revision: read.Revision})+ results <- err+ })+ }+ wg.Wait()+ close(results)+ successes := 0+ for err := range results {+ if err == nil {+ successes+++ }+ }+ if successes != 1 {+ t.Fatalf("concurrent writes succeeded %d times", successes)+ }+ read = requireManagedSkill(t, SkillFileRequest{Action: "read", Path: "skill/SKILL.md"})+ if err := SaveSkill("skill", "legacy API update"); err != nil {+ t.Fatal(err)+ }+ if _, err := ManageSkillFiles(SkillFileRequest{Action: "write", Path: "skill/SKILL.md", Content: "lost update", Revision: read.Revision}); err == nil {+ t.Fatal("legacy API update was overwritten")+ }+ resourcePath := filepath.Join(SkillsDir(), "skill", "resource.bin")+ if err := os.WriteFile(resourcePath, []byte("old"), 0644); err != nil {+ t.Fatal(err)+ }+ info, err := os.Stat(resourcePath)+ if err != nil {+ t.Fatal(err)+ }+ directory := requireManagedSkill(t, SkillFileRequest{Action: "read", Path: "skill"})+ if err = os.WriteFile(resourcePath, []byte("new"), 0644); err != nil {+ t.Fatal(err)+ }+ if err = os.Chtimes(resourcePath, info.ModTime(), info.ModTime()); err != nil {+ t.Fatal(err)+ }+ for _, action := range []string{"move", "remove"} {+ if _, err = ManageSkillFiles(SkillFileRequest{Action: action, Path: "skill", Target: "renamed", Revision: directory.Revision}); err == nil {+ t.Fatalf("directory %s ignored a resource content change", action)+ }+ }+ actual, err := os.ReadFile(resourcePath)+ if err != nil || string(actual) != "new" {+ t.Fatalf("conflicting operation changed resource: %q %v", actual, err)+ }+}++func TestSkillManagementPathBoundaries(t *testing.T) {+ managedSkillTestWorkspace(t)+ requireManagedSkill(t, SkillFileRequest{Action: "create", Path: "skill"})+ for _, p := range []string{"", ".", "..", "../escape", "/absolute", "C:/escape", "skill\\SKILL.md", "skill/../escape.md", "skill//a.md", "skill/a:stream.md", "skill/CON.md", "skill/COM¹.md", "skill/CONIN$", "skill/a. ", "skill/a.", "skill/.hidden.md", "skill/SKILL~1.MD", "skill/\x00.md"} {+ if _, err := ManageSkillFiles(SkillFileRequest{Action: "write", Path: p, Content: "outside"}); err == nil {+ t.Fatalf("accepted invalid path %q", p)+ }+ }+ for _, request := range []SkillFileRequest{+ {Action: "write", Path: "loose.md"},+ {Action: "mkdir", Path: "loose"},+ {Action: "create", Path: "skill/nested"},+ {Action: "create", Path: "skill"},+ } {+ if _, err := ManageSkillFiles(request); err == nil {+ t.Fatalf("accepted invalid operation %+v", request)+ }+ }+ requireManagedSkill(t, SkillFileRequest{Action: "mkdir", Path: "skill/sub"})+ requireManagedSkill(t, SkillFileRequest{Action: "write", Path: "skill/extra.md", Content: "original"})+ read := requireManagedSkill(t, SkillFileRequest{Action: "read", Path: "skill/extra.md"})+ for _, target := range []string{"skill/sub/extra.md", "skill/file.txt", "../outside.md", "skill/SKILL.md"} {+ if _, err := ManageSkillFiles(SkillFileRequest{Action: "move", Path: "skill/extra.md", Target: target, Revision: read.Revision}); err == nil {+ t.Fatalf("accepted invalid move target %q", target)+ }+ }+ if _, err := ManageSkillFiles(SkillFileRequest{Action: "write", Path: "skill/extra.md", Content: strings.Repeat("x", maxManagedSkillSourceSize+1), Revision: read.Revision}); err == nil {+ t.Fatal("accepted oversized write")+ }+ actual := requireManagedSkill(t, SkillFileRequest{Action: "read", Path: "skill/extra.md"})+ if *actual.Content != "original" {+ t.Fatal("invalid operation changed original")+ }+}++func TestSkillManagementLinks(t *testing.T) {+ managedSkillTestWorkspace(t)+ requireManagedSkill(t, SkillFileRequest{Action: "create", Path: "skill"})+ outside := t.TempDir()+ outsideFile := filepath.Join(outside, "private.md")+ if err := os.WriteFile(outsideFile, []byte("private"), 0644); err != nil {+ t.Fatal(err)+ }+ if err := os.Symlink(outside, filepath.Join(SkillsDir(), "skill", "linked")); err != nil {+ t.Skipf("symbolic links unavailable: %v", err)+ }+ for _, request := range []SkillFileRequest{+ {Action: "read", Path: "skill/linked/private.md"},+ {Action: "write", Path: "skill/linked/private.md", Content: "overwrite"},+ {Action: "read", Path: "skill"},+ {Action: "remove", Path: "skill", Revision: "ignored"},+ } {+ if _, err := ManageSkillFiles(request); err == nil {+ t.Fatalf("accepted linked operation %+v", request)+ }+ }+ entries := requireManagedSkill(t, SkillFileRequest{Action: "list"}).Entries+ for _, entry := range entries {+ if entry.Path == "skill/linked/private.md" || (entry.Path == "skill/linked" && entry.Editable) {+ t.Fatalf("list followed link: %+v", entry)+ }+ }+ actual, err := os.ReadFile(outsideFile)+ if err != nil || string(actual) != "private" {+ t.Fatalf("outside content changed: %q %v", actual, err)+ }+}++func TestSkillManagementCommitConflict(t *testing.T) {+ managedSkillTestWorkspace(t)+ created := requireManagedSkill(t, SkillFileRequest{Action: "create", Path: "skill", Content: "original"})+ root, err := openManagedSkillsRoot()+ if err != nil {+ t.Fatal(err)+ }+ defer root.Close()+ if err = os.WriteFile(filepath.Join(SkillsDir(), "skill", "SKILL.md"), []byte("external edit"), 0644); err != nil {+ t.Fatal(err)+ }+ if err = writeManagedSkillSource(root, "skill/SKILL.md", "stale editor", false, created.Revision); err == nil {+ t.Fatal("commit overwrote an external edit")+ }+ actual, err := root.ReadFile("skill/SKILL.md")+ if err != nil || string(actual) != "external edit" {+ t.Fatalf("external edit changed: %q %v", actual, err)+ }+ entries, err := os.ReadDir(filepath.Join(SkillsDir(), "skill"))+ if err != nil || len(entries) != 1 || entries[0].Name() != "SKILL.md" {+ t.Fatalf("failed save retained a temporary file: %v %v", entries, err)+ }+}