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 configuring Agent capabilities https://github.com/siyuan-note/siyuan/issues/18638
Daniela798512dcc1c
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex ad7b42da5f..a9cad86dbe 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "اختر القدرات المتاحة لـ Agent؛ كل تعريف مفعّل يزيد استخدام token",+ "agentCapabilitiesSearch": "البحث في أسماء القدرات أو أوصافها",+ "agentCapabilitiesOnlySelected": "المحددة فقط",+ "agentCapabilitiesAutoApprove": "موافقة تلقائية",+ "agentCapabilitiesAutoApproveTip": "يمكن ضبط الموافقة التلقائية بشكل منفصل لكل قدرة وإجراء",+ "agentCapabilitiesActions": "الإجراءات",+ "agentCapabilitiesSelected": "المحدد: ${selected}/${total}",+ "agentCapabilities": "قدرات Agent",+ "agentCapabilitiesTip": "التحكم في القدرات التي يمكن لـ Agent اكتشافها واستدعاؤها",+ "agentCapabilitiesEnableAll": "تمكين الكل",+ "agentCapabilitiesDisableAll": "تعطيل الكل",+ "agentCapabilitiesBackend": "الواجهة الخلفية",+ "agentCapabilitiesFrontend": "الواجهة الأمامية",+ "agentCapabilitiesBuiltin": "مدمجة",+ "agentCapabilitiesPlugins": "الإضافات",+ "agentCapabilitiesMcp": "خدمات MCP",+ "agentCapabilitiesUnavailable": "غير متاحة حاليًا","insertHTMLFile": "تضمين ملف HTML","dragHTMLFileToIframe": "تضمين ملفات HTML المسحوبة","dragHTMLFileToIframeTip": "تضمين ملفات HTML ككتل IFrame عند سحبها إلى المحرر",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 91a151b775..74ef6b42d3 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "Wählen Sie die für den Agent verfügbaren Funktionen; jede aktivierte Definition erhöht den token-Verbrauch",+ "agentCapabilitiesSearch": "Funktionsnamen oder Beschreibungen durchsuchen",+ "agentCapabilitiesOnlySelected": "Nur ausgewählte",+ "agentCapabilitiesAutoApprove": "Automatisch genehmigen",+ "agentCapabilitiesAutoApproveTip": "Die automatische Genehmigung kann für jede Funktion und Aktion getrennt festgelegt werden",+ "agentCapabilitiesActions": "Aktionen",+ "agentCapabilitiesSelected": "Ausgewählt: ${selected}/${total}",+ "agentCapabilities": "Agent-Funktionen",+ "agentCapabilitiesTip": "Steuert, welche Funktionen der Agent erkennen und aufrufen kann",+ "agentCapabilitiesEnableAll": "Alle aktivieren",+ "agentCapabilitiesDisableAll": "Alle deaktivieren",+ "agentCapabilitiesBackend": "Backend",+ "agentCapabilitiesFrontend": "Frontend",+ "agentCapabilitiesBuiltin": "Integriert",+ "agentCapabilitiesPlugins": "Plugins",+ "agentCapabilitiesMcp": "MCP-Dienste",+ "agentCapabilitiesUnavailable": "Derzeit nicht verfügbar","insertHTMLFile": "HTML-Datei einbetten","dragHTMLFileToIframe": "Gezogene HTML-Dateien einbetten","dragHTMLFileToIframeTip": "HTML-Dateien beim Ziehen in den Editor als IFrame-Blöcke einbetten",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 6eb62ccebf..e139673d14 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "Choose the capabilities available to the Agent; each enabled definition increases token usage",+ "agentCapabilitiesSearch": "Search capability names or descriptions",+ "agentCapabilitiesOnlySelected": "Selected only",+ "agentCapabilitiesAutoApprove": "Auto approve",+ "agentCapabilitiesAutoApproveTip": "Auto approval can be configured separately for each capability and action",+ "agentCapabilitiesActions": "Actions",+ "agentCapabilitiesSelected": "Selected: ${selected}/${total}",+ "agentCapabilities": "Agent capabilities",+ "agentCapabilitiesTip": "Control which capabilities the Agent can discover and invoke",+ "agentCapabilitiesEnableAll": "Enable all",+ "agentCapabilitiesDisableAll": "Disable all",+ "agentCapabilitiesBackend": "Backend",+ "agentCapabilitiesFrontend": "Frontend",+ "agentCapabilitiesBuiltin": "Built-in",+ "agentCapabilitiesPlugins": "Plugins",+ "agentCapabilitiesMcp": "MCP services",+ "agentCapabilitiesUnavailable": "Currently unavailable","insertHTMLFile": "Embed HTML file","dragHTMLFileToIframe": "Embed dragged HTML files","dragHTMLFileToIframeTip": "Embed HTML files as IFrame blocks when dragging them into the editor",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 9bb616e6a9..e4b6e17136 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "Elige las capacidades disponibles para el Agent; cada definición activada aumenta el uso de token",+ "agentCapabilitiesSearch": "Buscar nombres o descripciones de capacidades",+ "agentCapabilitiesOnlySelected": "Solo seleccionadas",+ "agentCapabilitiesAutoApprove": "Aprobar automáticamente",+ "agentCapabilitiesAutoApproveTip": "La aprobación automática puede configurarse por separado para cada capacidad y acción",+ "agentCapabilitiesActions": "Acciones",+ "agentCapabilitiesSelected": "Seleccionadas: ${selected}/${total}",+ "agentCapabilities": "Capacidades del Agent",+ "agentCapabilitiesTip": "Controla qué capacidades puede descubrir e invocar el Agent",+ "agentCapabilitiesEnableAll": "Activar todo",+ "agentCapabilitiesDisableAll": "Desactivar todo",+ "agentCapabilitiesBackend": "Backend",+ "agentCapabilitiesFrontend": "Frontend",+ "agentCapabilitiesBuiltin": "Integradas",+ "agentCapabilitiesPlugins": "Complementos",+ "agentCapabilitiesMcp": "Servicios MCP",+ "agentCapabilitiesUnavailable": "No disponibles actualmente","insertHTMLFile": "Incrustar archivo HTML","dragHTMLFileToIframe": "Incrustar archivos HTML arrastrados","dragHTMLFileToIframeTip": "Incrustar archivos HTML como bloques IFrame al arrastrarlos al editor",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex 32c2f01162..ca71b923ad 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "Choisissez les capacités accessibles à l’Agent ; chaque définition activée augmente l’utilisation de token",+ "agentCapabilitiesSearch": "Rechercher des noms ou descriptions de capacités",+ "agentCapabilitiesOnlySelected": "Sélectionnées uniquement",+ "agentCapabilitiesAutoApprove": "Approbation automatique",+ "agentCapabilitiesAutoApproveTip": "L’approbation automatique peut être définie séparément pour chaque capacité et action",+ "agentCapabilitiesActions": "Actions",+ "agentCapabilitiesSelected": "Sélectionnées : ${selected}/${total}",+ "agentCapabilities": "Capacités de l’Agent",+ "agentCapabilitiesTip": "Contrôler les capacités que l’Agent peut découvrir et appeler",+ "agentCapabilitiesEnableAll": "Tout activer",+ "agentCapabilitiesDisableAll": "Tout désactiver",+ "agentCapabilitiesBackend": "Backend",+ "agentCapabilitiesFrontend": "Frontend",+ "agentCapabilitiesBuiltin": "Intégrées",+ "agentCapabilitiesPlugins": "Extensions",+ "agentCapabilitiesMcp": "Services MCP",+ "agentCapabilitiesUnavailable": "Actuellement indisponibles","insertHTMLFile": "Intégrer un fichier HTML","dragHTMLFileToIframe": "Intégrer les fichiers HTML déposés","dragHTMLFileToIframeTip": "Intégrer les fichiers HTML en tant que blocs IFrame lors de leur dépôt dans l’éditeur",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 3ddbe0eeba..90d9a9d3e6 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "בחירת היכולות הזמינות ל-Agent; כל הגדרה מופעלת מגדילה את השימוש ב-token",+ "agentCapabilitiesSearch": "חיפוש בשמות או בתיאורי יכולות",+ "agentCapabilitiesOnlySelected": "רק נבחרות",+ "agentCapabilitiesAutoApprove": "אישור אוטומטי",+ "agentCapabilitiesAutoApproveTip": "ניתן להגדיר אישור אוטומטי בנפרד לכל יכולת ופעולה",+ "agentCapabilitiesActions": "פעולות",+ "agentCapabilitiesSelected": "נבחרו: ${selected}/${total}",+ "agentCapabilities": "יכולות Agent",+ "agentCapabilitiesTip": "שליטה ביכולות ש-Agent יכול לגלות ולהפעיל",+ "agentCapabilitiesEnableAll": "הפעלת הכול",+ "agentCapabilitiesDisableAll": "השבתת הכול",+ "agentCapabilitiesBackend": "צד שרת",+ "agentCapabilitiesFrontend": "צד לקוח",+ "agentCapabilitiesBuiltin": "מובנות",+ "agentCapabilitiesPlugins": "תוספים",+ "agentCapabilitiesMcp": "שירותי MCP",+ "agentCapabilitiesUnavailable": "לא זמינות כעת","insertHTMLFile": "הטמעת קובץ HTML","dragHTMLFileToIframe": "הטמעת קובצי HTML שנגררו","dragHTMLFileToIframeTip": "הטמעת קובצי HTML כבלוקי IFrame בעת גרירתם לעורך",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 9dce9ca77f..055848e347 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "Agent के लिए उपलब्ध क्षमताएँ चुनें; हर सक्षम परिभाषा token उपयोग बढ़ाती है",+ "agentCapabilitiesSearch": "क्षमता के नाम या विवरण खोजें",+ "agentCapabilitiesOnlySelected": "केवल चयनित",+ "agentCapabilitiesAutoApprove": "स्वचालित स्वीकृति",+ "agentCapabilitiesAutoApproveTip": "हर क्षमता और क्रिया के लिए स्वचालित स्वीकृति अलग से तय की जा सकती है",+ "agentCapabilitiesActions": "क्रियाएँ",+ "agentCapabilitiesSelected": "चयनित: ${selected}/${total}",+ "agentCapabilities": "Agent क्षमताएँ",+ "agentCapabilitiesTip": "नियंत्रित करें कि Agent किन क्षमताओं को खोज और चला सकता है",+ "agentCapabilitiesEnableAll": "सभी सक्षम करें",+ "agentCapabilitiesDisableAll": "सभी अक्षम करें",+ "agentCapabilitiesBackend": "बैकएंड",+ "agentCapabilitiesFrontend": "फ्रंटएंड",+ "agentCapabilitiesBuiltin": "अंतर्निहित",+ "agentCapabilitiesPlugins": "प्लगइन",+ "agentCapabilitiesMcp": "MCP सेवाएँ",+ "agentCapabilitiesUnavailable": "अभी अनुपलब्ध","insertHTMLFile": "HTML फ़ाइल एम्बेड करें","dragHTMLFileToIframe": "खींची गई HTML फ़ाइलें एम्बेड करें","dragHTMLFileToIframeTip": "HTML फ़ाइलों को संपादक में खींचते समय IFrame ब्लॉक के रूप में एम्बेड करें",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 1c5df9b07b..41d419862f 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "Pilih kemampuan yang tersedia untuk Agent; setiap definisi aktif meningkatkan penggunaan token",+ "agentCapabilitiesSearch": "Cari nama atau deskripsi kemampuan",+ "agentCapabilitiesOnlySelected": "Hanya yang dipilih",+ "agentCapabilitiesAutoApprove": "Setujui otomatis",+ "agentCapabilitiesAutoApproveTip": "Persetujuan otomatis dapat diatur terpisah untuk setiap kemampuan dan tindakan",+ "agentCapabilitiesActions": "Tindakan",+ "agentCapabilitiesSelected": "Dipilih: ${selected}/${total}",+ "agentCapabilities": "Kemampuan Agent",+ "agentCapabilitiesTip": "Kontrol kemampuan yang dapat ditemukan dan dipanggil oleh Agent",+ "agentCapabilitiesEnableAll": "Aktifkan semua",+ "agentCapabilitiesDisableAll": "Nonaktifkan semua",+ "agentCapabilitiesBackend": "Backend",+ "agentCapabilitiesFrontend": "Frontend",+ "agentCapabilitiesBuiltin": "Bawaan",+ "agentCapabilitiesPlugins": "Plugin",+ "agentCapabilitiesMcp": "Layanan MCP",+ "agentCapabilitiesUnavailable": "Saat ini tidak tersedia","insertHTMLFile": "Sematkan berkas HTML","dragHTMLFileToIframe": "Sematkan berkas HTML yang diseret","dragHTMLFileToIframeTip": "Sematkan berkas HTML sebagai blok IFrame saat diseret ke editor",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex b9ef45edd0..885fda4a69 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "Scegli le funzionalità disponibili per l’Agent; ogni definizione abilitata aumenta l’uso di token",+ "agentCapabilitiesSearch": "Cerca nomi o descrizioni delle funzionalità",+ "agentCapabilitiesOnlySelected": "Solo selezionate",+ "agentCapabilitiesAutoApprove": "Approva automaticamente",+ "agentCapabilitiesAutoApproveTip": "L’approvazione automatica può essere configurata separatamente per ogni funzionalità e azione",+ "agentCapabilitiesActions": "Azioni",+ "agentCapabilitiesSelected": "Selezionate: ${selected}/${total}",+ "agentCapabilities": "Funzionalità dell’Agent",+ "agentCapabilitiesTip": "Controlla quali funzionalità l’Agent può rilevare e richiamare",+ "agentCapabilitiesEnableAll": "Abilita tutto",+ "agentCapabilitiesDisableAll": "Disabilita tutto",+ "agentCapabilitiesBackend": "Backend",+ "agentCapabilitiesFrontend": "Frontend",+ "agentCapabilitiesBuiltin": "Integrate",+ "agentCapabilitiesPlugins": "Plugin",+ "agentCapabilitiesMcp": "Servizi MCP",+ "agentCapabilitiesUnavailable": "Attualmente non disponibili","insertHTMLFile": "Incorpora file HTML","dragHTMLFileToIframe": "Incorpora i file HTML trascinati","dragHTMLFileToIframeTip": "Incorpora i file HTML come blocchi IFrame quando vengono trascinati nell’editor",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex bec88bf9b0..493dadf76a 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "Agent が使用できる機能を選択します。有効な定義ごとに token 使用量が増えます",+ "agentCapabilitiesSearch": "機能名または説明を検索",+ "agentCapabilitiesOnlySelected": "選択済みのみ",+ "agentCapabilitiesAutoApprove": "自動承認",+ "agentCapabilitiesAutoApproveTip": "機能と操作ごとに自動承認を個別に設定できます",+ "agentCapabilitiesActions": "操作",+ "agentCapabilitiesSelected": "選択済み:${selected}/${total}",+ "agentCapabilities": "Agent 機能",+ "agentCapabilitiesTip": "Agent が検出して呼び出せる機能を制御します",+ "agentCapabilitiesEnableAll": "すべて有効",+ "agentCapabilitiesDisableAll": "すべて無効",+ "agentCapabilitiesBackend": "バックエンド",+ "agentCapabilitiesFrontend": "フロントエンド",+ "agentCapabilitiesBuiltin": "組み込み",+ "agentCapabilitiesPlugins": "プラグイン",+ "agentCapabilitiesMcp": "MCP サービス",+ "agentCapabilitiesUnavailable": "現在利用不可","insertHTMLFile": "HTML ファイルを埋め込む","dragHTMLFileToIframe": "ドラッグした HTML ファイルを埋め込む","dragHTMLFileToIframeTip": "HTML ファイルをエディターにドラッグしたときに IFrame ブロックとして埋め込む",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 41c4a95765..65407ab5d0 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "Agent가 사용할 수 있는 기능을 선택하세요. 활성화된 정의마다 token 사용량이 늘어납니다",+ "agentCapabilitiesSearch": "기능 이름 또는 설명 검색",+ "agentCapabilitiesOnlySelected": "선택 항목만",+ "agentCapabilitiesAutoApprove": "자동 승인",+ "agentCapabilitiesAutoApproveTip": "각 기능과 작업별로 자동 승인을 따로 설정할 수 있습니다",+ "agentCapabilitiesActions": "작업",+ "agentCapabilitiesSelected": "선택됨: ${selected}/${total}",+ "agentCapabilities": "Agent 기능",+ "agentCapabilitiesTip": "Agent가 검색하고 호출할 수 있는 기능을 제어합니다",+ "agentCapabilitiesEnableAll": "모두 활성화",+ "agentCapabilitiesDisableAll": "모두 비활성화",+ "agentCapabilitiesBackend": "백엔드",+ "agentCapabilitiesFrontend": "프런트엔드",+ "agentCapabilitiesBuiltin": "내장",+ "agentCapabilitiesPlugins": "플러그인",+ "agentCapabilitiesMcp": "MCP 서비스",+ "agentCapabilitiesUnavailable": "현재 사용할 수 없음","insertHTMLFile": "HTML 파일 임베드","dragHTMLFileToIframe": "드래그한 HTML 파일 임베드","dragHTMLFileToIframeTip": "HTML 파일을 편집기로 드래그할 때 IFrame 블록으로 임베드",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex eb3cd9f4a7..1a86b341d3 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "Kies de mogelijkheden die de Agent mag gebruiken; elke ingeschakelde definitie verhoogt het token-gebruik",+ "agentCapabilitiesSearch": "Zoek op naam of beschrijving van mogelijkheden",+ "agentCapabilitiesOnlySelected": "Alleen geselecteerde",+ "agentCapabilitiesAutoApprove": "Automatisch goedkeuren",+ "agentCapabilitiesAutoApproveTip": "Automatische goedkeuring kan per mogelijkheid en actie worden ingesteld",+ "agentCapabilitiesActions": "Acties",+ "agentCapabilitiesSelected": "Geselecteerd: ${selected}/${total}",+ "agentCapabilities": "Agent-mogelijkheden",+ "agentCapabilitiesTip": "Bepaal welke mogelijkheden de Agent kan ontdekken en aanroepen",+ "agentCapabilitiesEnableAll": "Alles inschakelen",+ "agentCapabilitiesDisableAll": "Alles uitschakelen",+ "agentCapabilitiesBackend": "Backend",+ "agentCapabilitiesFrontend": "Frontend",+ "agentCapabilitiesBuiltin": "Ingebouwd",+ "agentCapabilitiesPlugins": "Plugins",+ "agentCapabilitiesMcp": "MCP-diensten",+ "agentCapabilitiesUnavailable": "Momenteel niet beschikbaar","insertHTMLFile": "HTML-bestand insluiten","dragHTMLFileToIframe": "Gesleepte HTML-bestanden insluiten","dragHTMLFileToIframeTip": "HTML-bestanden als IFrame-blokken insluiten wanneer ze naar de editor worden gesleept",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex e1f19cb732..a644a0e75a 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "Wybierz możliwości dostępne dla Agent; każda włączona definicja zwiększa użycie token",+ "agentCapabilitiesSearch": "Szukaj nazw lub opisów możliwości",+ "agentCapabilitiesOnlySelected": "Tylko wybrane",+ "agentCapabilitiesAutoApprove": "Zatwierdzaj automatycznie",+ "agentCapabilitiesAutoApproveTip": "Automatyczne zatwierdzanie można ustawić osobno dla każdej możliwości i działania",+ "agentCapabilitiesActions": "Działania",+ "agentCapabilitiesSelected": "Wybrano: ${selected}/${total}",+ "agentCapabilities": "Możliwości Agent",+ "agentCapabilitiesTip": "Kontroluj możliwości, które Agent może wykrywać i wywoływać",+ "agentCapabilitiesEnableAll": "Włącz wszystko",+ "agentCapabilitiesDisableAll": "Wyłącz wszystko",+ "agentCapabilitiesBackend": "Backend",+ "agentCapabilitiesFrontend": "Frontend",+ "agentCapabilitiesBuiltin": "Wbudowane",+ "agentCapabilitiesPlugins": "Wtyczki",+ "agentCapabilitiesMcp": "Usługi MCP",+ "agentCapabilitiesUnavailable": "Obecnie niedostępne","insertHTMLFile": "Osadź plik HTML","dragHTMLFileToIframe": "Osadzaj przeciągane pliki HTML","dragHTMLFileToIframeTip": "Osadzaj pliki HTML jako bloki IFrame podczas przeciągania ich do edytora",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex d683353321..00cb53bea4 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "Escolha os recursos disponíveis para o Agent; cada definição ativada aumenta o uso de token",+ "agentCapabilitiesSearch": "Pesquisar nomes ou descrições de recursos",+ "agentCapabilitiesOnlySelected": "Somente selecionados",+ "agentCapabilitiesAutoApprove": "Aprovar automaticamente",+ "agentCapabilitiesAutoApproveTip": "A aprovação automática pode ser configurada separadamente para cada recurso e ação",+ "agentCapabilitiesActions": "Ações",+ "agentCapabilitiesSelected": "Selecionados: ${selected}/${total}",+ "agentCapabilities": "Recursos do Agent",+ "agentCapabilitiesTip": "Controle quais recursos o Agent pode descobrir e invocar",+ "agentCapabilitiesEnableAll": "Ativar tudo",+ "agentCapabilitiesDisableAll": "Desativar tudo",+ "agentCapabilitiesBackend": "Backend",+ "agentCapabilitiesFrontend": "Frontend",+ "agentCapabilitiesBuiltin": "Integrados",+ "agentCapabilitiesPlugins": "Plugins",+ "agentCapabilitiesMcp": "Serviços MCP",+ "agentCapabilitiesUnavailable": "Indisponíveis no momento","insertHTMLFile": "Incorporar arquivo HTML","dragHTMLFileToIframe": "Incorporar arquivos HTML arrastados","dragHTMLFileToIframeTip": "Incorporar arquivos HTML como blocos IFrame ao arrastá-los para o editor",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex b5ab965700..8ba370abd5 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "Выберите доступные Agent возможности; каждое включённое определение увеличивает расход token",+ "agentCapabilitiesSearch": "Поиск по названию или описанию возможности",+ "agentCapabilitiesOnlySelected": "Только выбранные",+ "agentCapabilitiesAutoApprove": "Одобрять автоматически",+ "agentCapabilitiesAutoApproveTip": "Автоматическое одобрение можно настроить отдельно для каждой возможности и действия",+ "agentCapabilitiesActions": "Действия",+ "agentCapabilitiesSelected": "Выбрано: ${selected}/${total}",+ "agentCapabilities": "Возможности Agent",+ "agentCapabilitiesTip": "Управление возможностями, которые Agent может обнаруживать и вызывать",+ "agentCapabilitiesEnableAll": "Включить все",+ "agentCapabilitiesDisableAll": "Отключить все",+ "agentCapabilitiesBackend": "Бэкенд",+ "agentCapabilitiesFrontend": "Фронтенд",+ "agentCapabilitiesBuiltin": "Встроенные",+ "agentCapabilitiesPlugins": "Плагины",+ "agentCapabilitiesMcp": "Сервисы MCP",+ "agentCapabilitiesUnavailable": "Сейчас недоступны","insertHTMLFile": "Встроить HTML-файл","dragHTMLFileToIframe": "Встраивать перетаскиваемые HTML-файлы","dragHTMLFileToIframeTip": "Встраивать HTML-файлы как блоки IFrame при перетаскивании в редактор",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 80ae36119a..0824c9f9b0 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "Vyberte možnosti dostupné pre Agenta; každá povolená definícia zvyšuje spotrebu token",+ "agentCapabilitiesSearch": "Hľadať názvy alebo popisy možností",+ "agentCapabilitiesOnlySelected": "Len vybrané",+ "agentCapabilitiesAutoApprove": "Automaticky schváliť",+ "agentCapabilitiesAutoApproveTip": "Automatické schválenie možno nastaviť osobitne pre každú možnosť a akciu",+ "agentCapabilitiesActions": "Akcie",+ "agentCapabilitiesSelected": "Vybrané: ${selected}/${total}",+ "agentCapabilities": "Možnosti Agenta",+ "agentCapabilitiesTip": "Určuje možnosti, ktoré môže Agent objaviť a volať",+ "agentCapabilitiesEnableAll": "Povoliť všetko",+ "agentCapabilitiesDisableAll": "Zakázať všetko",+ "agentCapabilitiesBackend": "Backend",+ "agentCapabilitiesFrontend": "Frontend",+ "agentCapabilitiesBuiltin": "Vstavané",+ "agentCapabilitiesPlugins": "Pluginy",+ "agentCapabilitiesMcp": "Služby MCP",+ "agentCapabilitiesUnavailable": "Momentálne nedostupné","insertHTMLFile": "Vložiť súbor HTML","dragHTMLFileToIframe": "Vkladať presunuté súbory HTML","dragHTMLFileToIframeTip": "Vkladať súbory HTML ako bloky IFrame pri ich presunutí do editora",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex ec3ef7c7b5..d85c058bcc 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "เลือกความสามารถที่ Agent ใช้ได้ โดยทุกข้อกำหนดที่เปิดใช้จะเพิ่มการใช้ token",+ "agentCapabilitiesSearch": "ค้นหาชื่อหรือคำอธิบายความสามารถ",+ "agentCapabilitiesOnlySelected": "เฉพาะที่เลือก",+ "agentCapabilitiesAutoApprove": "อนุมัติอัตโนมัติ",+ "agentCapabilitiesAutoApproveTip": "ตั้งค่าการอนุมัติอัตโนมัติแยกตามความสามารถและการดำเนินการได้",+ "agentCapabilitiesActions": "การดำเนินการ",+ "agentCapabilitiesSelected": "เลือกแล้ว: ${selected}/${total}",+ "agentCapabilities": "ความสามารถของ Agent",+ "agentCapabilitiesTip": "ควบคุมความสามารถที่ Agent สามารถค้นพบและเรียกใช้ได้",+ "agentCapabilitiesEnableAll": "เปิดใช้ทั้งหมด",+ "agentCapabilitiesDisableAll": "ปิดใช้ทั้งหมด",+ "agentCapabilitiesBackend": "แบ็กเอนด์",+ "agentCapabilitiesFrontend": "ฟรอนต์เอนด์",+ "agentCapabilitiesBuiltin": "ในตัว",+ "agentCapabilitiesPlugins": "ปลั๊กอิน",+ "agentCapabilitiesMcp": "บริการ MCP",+ "agentCapabilitiesUnavailable": "ไม่พร้อมใช้งานในขณะนี้","insertHTMLFile": "ฝังไฟล์ HTML","dragHTMLFileToIframe": "ฝังไฟล์ HTML ที่ลากมา","dragHTMLFileToIframeTip": "ฝังไฟล์ HTML เป็นบล็อก IFrame เมื่อลากไฟล์เข้าสู่ตัวแก้ไข",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex ce4433a21d..73a7b4f18a 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "Agent'ın kullanabileceği yetenekleri seçin; etkin her tanım token kullanımını artırır",+ "agentCapabilitiesSearch": "Yetenek adı veya açıklaması ara",+ "agentCapabilitiesOnlySelected": "Yalnızca seçilenler",+ "agentCapabilitiesAutoApprove": "Otomatik onayla",+ "agentCapabilitiesAutoApproveTip": "Otomatik onay her yetenek ve eylem için ayrı ayrı ayarlanabilir",+ "agentCapabilitiesActions": "Eylemler",+ "agentCapabilitiesSelected": "Seçilen: ${selected}/${total}",+ "agentCapabilities": "Agent yetenekleri",+ "agentCapabilitiesTip": "Agent'ın keşfedip çağırabileceği yetenekleri denetleyin",+ "agentCapabilitiesEnableAll": "Tümünü etkinleştir",+ "agentCapabilitiesDisableAll": "Tümünü devre dışı bırak",+ "agentCapabilitiesBackend": "Arka uç",+ "agentCapabilitiesFrontend": "Ön uç",+ "agentCapabilitiesBuiltin": "Yerleşik",+ "agentCapabilitiesPlugins": "Eklentiler",+ "agentCapabilitiesMcp": "MCP hizmetleri",+ "agentCapabilitiesUnavailable": "Şu anda kullanılamıyor","insertHTMLFile": "HTML dosyası göm","dragHTMLFileToIframe": "Sürüklenen HTML dosyalarını göm","dragHTMLFileToIframeTip": "HTML dosyalarını düzenleyiciye sürüklerken IFrame blokları olarak göm",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 93ff476c55..3dcf7e3f31 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "Виберіть доступні Agent можливості; кожне ввімкнене визначення збільшує використання token",+ "agentCapabilitiesSearch": "Пошук за назвою або описом можливості",+ "agentCapabilitiesOnlySelected": "Лише вибрані",+ "agentCapabilitiesAutoApprove": "Схвалювати автоматично",+ "agentCapabilitiesAutoApproveTip": "Автоматичне схвалення можна налаштувати окремо для кожної можливості та дії",+ "agentCapabilitiesActions": "Дії",+ "agentCapabilitiesSelected": "Вибрано: ${selected}/${total}",+ "agentCapabilities": "Можливості Agent",+ "agentCapabilitiesTip": "Керування можливостями, які Agent може знаходити та викликати",+ "agentCapabilitiesEnableAll": "Увімкнути все",+ "agentCapabilitiesDisableAll": "Вимкнути все",+ "agentCapabilitiesBackend": "Бекенд",+ "agentCapabilitiesFrontend": "Фронтенд",+ "agentCapabilitiesBuiltin": "Вбудовані",+ "agentCapabilitiesPlugins": "Плагіни",+ "agentCapabilitiesMcp": "Сервіси MCP",+ "agentCapabilitiesUnavailable": "Наразі недоступні","insertHTMLFile": "Вбудувати HTML-файл","dragHTMLFileToIframe": "Вбудовувати перетягнуті HTML-файли","dragHTMLFileToIframeTip": "Вбудовувати HTML-файли як блоки IFrame під час перетягування до редактора",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 55bf525609..a9cb021bd8 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "选择 Agent 可以使用的能力;每个已启用的定义都会增加 token 用量",+ "agentCapabilitiesSearch": "搜索能力名称或描述",+ "agentCapabilitiesOnlySelected": "仅看已选",+ "agentCapabilitiesAutoApprove": "自动批准",+ "agentCapabilitiesAutoApproveTip": "可以为每个能力及其操作单独设置是否自动批准",+ "agentCapabilitiesActions": "操作",+ "agentCapabilitiesSelected": "已选择:${selected}/${total}",+ "agentCapabilities": "Agent 能力",+ "agentCapabilitiesTip": "控制 Agent 可以发现和调用的能力",+ "agentCapabilitiesEnableAll": "全部启用",+ "agentCapabilitiesDisableAll": "全部禁用",+ "agentCapabilitiesBackend": "后端",+ "agentCapabilitiesFrontend": "前端",+ "agentCapabilitiesBuiltin": "内置",+ "agentCapabilitiesPlugins": "插件",+ "agentCapabilitiesMcp": "MCP 服务",+ "agentCapabilitiesUnavailable": "当前不可用","insertHTMLFile": "嵌入 HTML 文件","dragHTMLFileToIframe": "嵌入拖拽的 HTML 文件","dragHTMLFileToIframeTip": "将拖拽到编辑器中的 HTML 文件嵌入为 IFrame 块",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 3a663c76cb..d8bb3a30ff 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,21 @@{+ "agentCapabilitiesDialogTip": "選擇 Agent 可以使用的能力;每個已啟用的定義都會增加 token 用量",+ "agentCapabilitiesSearch": "搜尋能力名稱或描述",+ "agentCapabilitiesOnlySelected": "僅看已選",+ "agentCapabilitiesAutoApprove": "自動核准",+ "agentCapabilitiesAutoApproveTip": "可以為每個能力及其操作分別設定是否自動核准",+ "agentCapabilitiesActions": "操作",+ "agentCapabilitiesSelected": "已選擇:${selected}/${total}",+ "agentCapabilities": "Agent 能力",+ "agentCapabilitiesTip": "控制 Agent 可以發現及呼叫的能力",+ "agentCapabilitiesEnableAll": "全部啟用",+ "agentCapabilitiesDisableAll": "全部停用",+ "agentCapabilitiesBackend": "後端",+ "agentCapabilitiesFrontend": "前端",+ "agentCapabilitiesBuiltin": "內建",+ "agentCapabilitiesPlugins": "外掛程式",+ "agentCapabilitiesMcp": "MCP 服務",+ "agentCapabilitiesUnavailable": "目前無法使用","insertHTMLFile": "嵌入 HTML 檔案","dragHTMLFileToIframe": "嵌入拖曳的 HTML 檔案","dragHTMLFileToIframeTip": "將拖曳到編輯器中的 HTML 檔案嵌入為 IFrame 區塊",diff --git a/app/src/config/tabs/ai/aiCapabilityUi.ts b/app/src/config/tabs/ai/aiCapabilityUi.tsnew file mode 100644index 0000000000..026983465c--- /dev/null+++ b/app/src/config/tabs/ai/aiCapabilityUi.ts@@ -0,0 +1,404 @@+import {Dialog} from "../../../dialog";+import {escapeAttr, escapeHtml} from "../../../util/escape";+import {fetchPost} from "../../../util/fetch";+import {isMobile} from "../../../util/functions";+import {listCapabilityManifests} from "../../../layout/dock/agent/frontendCapabilities";+import {aiConfigApi} from "./aiRuntime";++type CapabilityDecision = "allow" | "deny";+type ApprovalDecision = "allow" | "confirm";++const escapeAttribute = (value: string) => escapeAttr(escapeHtml(value));++interface ICapabilityActionInfo {+ name: string;+ effects?: {+ localRead?: boolean;+ localWrite?: boolean;+ dataEgress?: boolean;+ externalCost?: boolean;+ };+}++interface ICapabilityInfo {+ id: string;+ name: string;+ title?: string;+ description: string;+ source: "native" | "plugin" | "mcp";+ ownerId?: string;+ ownerName?: string;+ runtime: "kernel" | "plugin-worker" | "mcp" | "browser";+ enabled: boolean;+ available: boolean;+ actions?: ICapabilityActionInfo[];+}++const getCapabilityPolicy = (): Config.IAgent["capabilityPolicy"] =>+ window.siyuan.config.ai.agent.capabilityPolicy || {default: "allow", overrides: {}};++const getApprovalPolicy = (): Config.IAgent["approvalPolicy"] =>+ window.siyuan.config.ai.agent.approvalPolicy || {default: "confirm", overrides: {}};++const isCapabilityAllowed = (id: string, policy = getCapabilityPolicy()) =>+ (policy.overrides[id] || policy.default) === "allow";++const isCapabilityAutoApproved = (id: string, action = "", policy = getApprovalPolicy()) => {+ const override = policy.overrides[id];+ return (override?.actions[action] || override?.default || policy.default) === "allow";+};++const getGroupLabel = (capability: ICapabilityInfo) => {+ const runtime = capability.runtime === "browser"+ ? window.siyuan.languages.agentCapabilitiesFrontend+ : window.siyuan.languages.agentCapabilitiesBackend;+ let source = window.siyuan.languages.agentCapabilitiesBuiltin;+ if (capability.source === "plugin") {+ source = window.siyuan.languages.agentCapabilitiesPlugins;+ } else if (capability.source === "mcp") {+ source = window.siyuan.languages.agentCapabilitiesMcp;+ }+ const owner = capability.ownerName || capability.ownerId;+ return owner ? `${runtime} · ${source} · ${owner}` : `${runtime} · ${source}`;+};++const getManifestActions = (capability: ReturnType<typeof listCapabilityManifests>[number]): ICapabilityActionInfo[] => {+ const names = new Set(Object.keys(capability.actionEffects || {}));+ const properties = capability.inputSchema.properties as Record<string, unknown> | undefined;+ const action = properties?.action as {enum?: unknown[]} | undefined;+ action?.enum?.forEach((value) => {+ if (typeof value === "string" && value) {+ names.add(value);+ }+ });+ return Array.from(names).sort().map((name) => ({name, effects: capability.actionEffects?.[name] || capability.effects}));+};++const getAllCapabilities = (backend: ICapabilityInfo[]): ICapabilityInfo[] => {+ const frontend = listCapabilityManifests().map((capability): ICapabilityInfo => ({+ id: capability.id,+ name: capability.id.split("/").at(-1) || capability.id,+ title: capability.title,+ description: capability.description,+ source: capability.source,+ ownerId: capability.ownerId,+ ownerName: capability.ownerName,+ runtime: "browser",+ enabled: isCapabilityAllowed(capability.id),+ available: true,+ actions: getManifestActions(capability),+ }));+ return [...backend, ...frontend].sort((a, b) => {+ const group = getGroupLabel(a).localeCompare(getGroupLabel(b));+ return group || a.id.localeCompare(b.id);+ });+};++const addUnavailableCapabilities = (capabilities: ICapabilityInfo[]) => {+ const knownIDs = new Set(capabilities.map((capability) => capability.id));+ const configuredIDs = new Set([+ ...Object.keys(getCapabilityPolicy().overrides),+ ...Object.keys(getApprovalPolicy().overrides),+ ]);+ configuredIDs.forEach((id) => {+ if (!knownIDs.has(id)) {+ capabilities.push({+ id,+ name: id,+ description: "",+ source: "native",+ runtime: "kernel",+ enabled: isCapabilityAllowed(id),+ available: false,+ actions: [],+ });+ }+ });+};++const saveCapabilityPolicy = (policy: Config.IAgent["capabilityPolicy"], onApplied: () => void) => {+ aiConfigApi.patch("agent.capabilityPolicy", policy, onApplied);+};++const saveApprovalPolicy = (policy: Config.IAgent["approvalPolicy"], onApplied: () => void) => {+ aiConfigApi.patch("agent.approvalPolicy", policy, onApplied);+};++const setCapabilitiesDecision = (ids: string[], decision: CapabilityDecision, onApplied: () => void) => {+ const policy = getCapabilityPolicy();+ const overrides = {...policy.overrides};+ ids.forEach((id) => {+ if (decision === policy.default) {+ delete overrides[id];+ } else {+ overrides[id] = decision;+ }+ });+ saveCapabilityPolicy({...policy, overrides}, onApplied);+};++const setCapabilityApproval = (id: string, decision: ApprovalDecision, onApplied: () => void) => {+ const policy = getApprovalPolicy();+ const overrides = {...policy.overrides};+ if (decision === policy.default) {+ delete overrides[id];+ } else {+ overrides[id] = {default: decision, actions: {}};+ }+ saveApprovalPolicy({...policy, overrides}, onApplied);+};++const setCapabilityActionApproval = (id: string, action: string, decision: ApprovalDecision,+ onApplied: () => void) => {+ const policy = getApprovalPolicy();+ const overrides = {...policy.overrides};+ const current = overrides[id];+ const capabilityDefault = current?.default || policy.default;+ const actions = {...current?.actions};+ if (decision === capabilityDefault) {+ delete actions[action];+ } else {+ actions[action] = decision;+ }+ if (!current?.default && Object.keys(actions).length === 0) {+ delete overrides[id];+ } else {+ overrides[id] = {default: current?.default || "", actions};+ }+ saveApprovalPolicy({...policy, overrides}, onApplied);+};++const capabilityMatches = (capability: ICapabilityInfo, query: string) => {+ if (!query) {+ return true;+ }+ return [+ capability.title,+ capability.name,+ capability.id,+ capability.description,+ getGroupLabel(capability),+ ...(capability.actions || []).map((action) => action.name),+ ].some((value) => value?.toLocaleLowerCase().includes(query));+};++const openAgentCapabilityDialog = (settingRoot: HTMLElement, capabilities: ICapabilityInfo[]) => {+ const expanded = new Set<string>();+ let query = "";+ let onlySelected = false;+ const dialog = new Dialog({+ title: window.siyuan.languages.agentCapabilities,+ width: isMobile() ? "96vw" : "min(900px, 90vw)",+ height: isMobile() ? "90vh" : "min(820px, 86vh)",+ content: `<div class="b3-dialog__content" style="height:100%;box-sizing:border-box;display:flex;flex-direction:column;overflow:hidden;">+ <div class="b3-label b3-label--inner" style="flex-shrink:0;">${window.siyuan.languages.agentCapabilitiesDialogTip}</div>+ <div class="fn__hr"></div>+ <div class="fn__flex" style="flex-shrink:0;align-items:center;">+ <div class="fn__flex-1" style="position:relative;">+ <svg class="b3-form__icon-icon"><use xlink:href="#iconSearch"></use></svg>+ <input class="b3-text-field b3-form__icon-input fn__block" data-type="searchAgentCapabilities" placeholder="${escapeAttribute(window.siyuan.languages.agentCapabilitiesSearch)}">+ </div>+ <span class="fn__space"></span>+ <label class="fn__flex-center"><input class="b3-switch" data-type="onlySelectedAgentCapabilities" type="checkbox"><span class="fn__space--small"></span>${window.siyuan.languages.agentCapabilitiesOnlySelected}</label>+ </div>+ <div class="fn__hr"></div>+ <div class="fn__flex" style="flex-shrink:0;">+ <button class="b3-button b3-button--outline" data-type="enableAllAgentCapabilities">${window.siyuan.languages.agentCapabilitiesEnableAll}</button>+ <span class="fn__space"></span>+ <button class="b3-button b3-button--outline" data-type="disableAllAgentCapabilities">${window.siyuan.languages.agentCapabilitiesDisableAll}</button>+ </div>+ <div class="fn__hr"></div>+ <div class="fn__flex-1" data-type="agentCapabilityList" style="min-height:0;overflow:auto;"></div>+ <div class="fn__hr"></div>+ <div class="fn__flex b3-label__text" style="flex-shrink:0;align-items:center;">+ <span class="fn__flex-1">${window.siyuan.languages.agentCapabilitiesAutoApproveTip}</span>+ <span data-type="agentCapabilitySelectedCount"></span>+ </div>+</div>`,+ });++ const render = () => {+ const list = dialog.element.querySelector<HTMLElement>("[data-type='agentCapabilityList']");+ const count = dialog.element.querySelector<HTMLElement>("[data-type='agentCapabilitySelectedCount']");+ if (!list || !count) {+ return;+ }+ const normalizedQuery = query.trim().toLocaleLowerCase();+ const visible = capabilities.filter((capability) =>+ (!onlySelected || isCapabilityAllowed(capability.id)) && capabilityMatches(capability, normalizedQuery));+ const groups = new Map<string, ICapabilityInfo[]>();+ visible.forEach((capability) => {+ const label = capability.available+ ? getGroupLabel(capability)+ : window.siyuan.languages.agentCapabilitiesUnavailable;+ const items = groups.get(label) || [];+ items.push(capability);+ groups.set(label, items);+ });+ list.innerHTML = Array.from(groups.entries()).map(([label, items], groupIndex) => {+ const groupEnabled = items.every((capability) => isCapabilityAllowed(capability.id));+ return `<details open data-capability-group="${groupIndex}">+ <summary class="fn__flex" style="cursor:pointer;padding:8px 4px;align-items:center;">+ <span class="fn__flex-1">${escapeHtml(label)} (${items.length})</span>+ <button class="b3-button b3-button--outline" data-type="toggleAgentCapabilityGroup" data-group-index="${groupIndex}">${groupEnabled ? window.siyuan.languages.agentCapabilitiesDisableAll : window.siyuan.languages.selectAll}</button>+ </summary>+ <div class="b3-list b3-list--border b3-list--background">+ ${items.map((capability) => {+ const actions = capability.actions || [];+ const opened = expanded.has(capability.id);+ const actionSummary = actions.length > 0+ ? `<span class="b3-label__text" style="display:block;">${window.siyuan.languages.agentCapabilitiesActions}: ${escapeHtml(actions.map((action) => action.name).join(", "))}</span>`+ : "";+ return `<div data-capability-id="${escapeAttribute(capability.id)}">+ <div class="b3-list-item b3-list-item--narrow" style="height:auto;align-items:flex-start;padding-top:10px;padding-bottom:10px;">+ <input data-type="toggleAgentCapability" type="checkbox"${isCapabilityAllowed(capability.id) ? " checked" : ""}>+ <span class="fn__space"></span>+ <span class="fn__flex-1" style="min-width:0;">+ <span class="b3-list-item__text" style="display:block;">${escapeHtml(capability.title || capability.name)}</span>+ ${capability.description ? `<span class="b3-label__text" style="display:block;">${escapeHtml(capability.description)}</span>` : ""}+ ${actionSummary}+ <span class="b3-list-item__meta" style="display:block;overflow:hidden;text-overflow:ellipsis;">${escapeHtml(capability.id)}</span>+ </span>+ <span class="fn__space"></span>+ <label class="fn__flex-center"><input class="b3-switch" data-type="toggleAgentCapabilityApproval" type="checkbox"${isCapabilityAutoApproved(capability.id) ? " checked" : ""}><span class="fn__space--small"></span>${window.siyuan.languages.agentCapabilitiesAutoApprove}</label>+ ${actions.length > 0 ? `<button class="b3-list-item__action" data-type="toggleAgentCapabilityActions" aria-label="${escapeAttribute(window.siyuan.languages.agentCapabilitiesActions)}"><svg style="transform:rotate(${opened ? "90deg" : "0"});"><use xlink:href="#iconRight"></use></svg></button>` : ""}+ </div>+ ${actions.length > 0 && opened ? `<div style="padding:0 12px 8px 42px;">${actions.map((action) => `<label class="fn__flex b3-label__text" style="padding:5px 0;align-items:center;">+ <span class="fn__flex-1"><code>${escapeHtml(action.name)}</code></span>+ <input class="b3-switch" data-type="toggleAgentCapabilityActionApproval" data-capability-action="${escapeAttribute(action.name)}" type="checkbox"${isCapabilityAutoApproved(capability.id, action.name) ? " checked" : ""}>+ </label>`).join("")}</div>` : ""}+</div>`;+ }).join("")}+ </div>+</details>`;+ }).join("");+ const selected = capabilities.filter((capability) => isCapabilityAllowed(capability.id)).length;+ count.textContent = window.siyuan.languages.agentCapabilitiesSelected+ .replace("${selected}", String(selected)).replace("${total}", String(capabilities.length));++ const groupEntries = Array.from(groups.values());+ list.querySelectorAll<HTMLElement>("[data-type='toggleAgentCapabilityGroup']").forEach((button) => {+ button.addEventListener("click", (event) => {+ event.preventDefault();+ event.stopPropagation();+ const items = groupEntries[Number(button.dataset.groupIndex)] || [];+ const decision = items.every((capability) => isCapabilityAllowed(capability.id)) ? "deny" : "allow";+ setCapabilitiesDecision(items.map((capability) => capability.id), decision, onPolicyApplied);+ });+ });+ };++ const onPolicyApplied = () => {+ render();+ refreshCapabilitySummary(settingRoot, capabilities);+ };++ dialog.element.querySelector<HTMLInputElement>("[data-type='searchAgentCapabilities']")?.addEventListener("input", (event) => {+ query = (event.target as HTMLInputElement).value;+ render();+ });+ dialog.element.querySelector<HTMLInputElement>("[data-type='onlySelectedAgentCapabilities']")?.addEventListener("change", (event) => {+ onlySelected = (event.target as HTMLInputElement).checked;+ render();+ });+ dialog.element.addEventListener("change", (event) => {+ const input = event.target as HTMLInputElement;+ const type = input.dataset.type;+ const id = input.closest<HTMLElement>("[data-capability-id]")?.dataset.capabilityId;+ if (!id) {+ return;+ }+ if (type === "toggleAgentCapability") {+ setCapabilitiesDecision([id], input.checked ? "allow" : "deny", onPolicyApplied);+ } else if (type === "toggleAgentCapabilityApproval") {+ setCapabilityApproval(id, input.checked ? "allow" : "confirm", onPolicyApplied);+ } else if (type === "toggleAgentCapabilityActionApproval") {+ const action = input.dataset.capabilityAction;+ if (action !== undefined) {+ setCapabilityActionApproval(id, action, input.checked ? "allow" : "confirm", onPolicyApplied);+ }+ }+ });+ dialog.element.addEventListener("click", (event) => {+ const target = (event.target as HTMLElement).closest<HTMLElement>("[data-type]");+ if (!target) {+ return;+ }+ if (target.dataset.type === "enableAllAgentCapabilities") {+ saveCapabilityPolicy({default: "allow", overrides: {}}, onPolicyApplied);+ } else if (target.dataset.type === "disableAllAgentCapabilities") {+ saveCapabilityPolicy({default: "deny", overrides: {}}, onPolicyApplied);+ } else if (target.dataset.type === "toggleAgentCapabilityActions") {+ const id = target.closest<HTMLElement>("[data-capability-id]")?.dataset.capabilityId;+ if (id) {+ if (expanded.has(id)) {+ expanded.delete(id);+ } else {+ expanded.add(id);+ }+ render();+ }+ }+ });+ render();+ dialog.element.querySelector<HTMLInputElement>("[data-type='searchAgentCapabilities']")?.focus();+ refreshCapabilitySummary(settingRoot, capabilities);+};++const loadCapabilities = (callback: (capabilities: ICapabilityInfo[]) => void) => {+ fetchPost("/api/ai/agent/lsCapabilities", {}, (response) => {+ const capabilities = getAllCapabilities((response.data || []) as ICapabilityInfo[]);+ addUnavailableCapabilities(capabilities);+ callback(capabilities);+ });+};++const refreshCapabilitySummary = (root: HTMLElement, loaded?: ICapabilityInfo[]) => {+ const update = (capabilities: ICapabilityInfo[]) => {+ const summary = root.querySelector<HTMLElement>("[data-type='agentCapabilitySummary']");+ if (!summary) {+ return;+ }+ const selected = capabilities.filter((capability) => isCapabilityAllowed(capability.id)).length;+ summary.textContent = window.siyuan.languages.agentCapabilitiesSelected+ .replace("${selected}", String(selected)).replace("${total}", String(capabilities.length));+ };+ if (loaded) {+ update(loaded);+ } else {+ loadCapabilities(update);+ }+};++export const getAgentCapabilityKeywords = (): string[] => [+ window.siyuan.languages.agentCapabilities,+ window.siyuan.languages.agentCapabilitiesTip,+ window.siyuan.languages.agentCapabilitiesBackend,+ window.siyuan.languages.agentCapabilitiesFrontend,+ window.siyuan.languages.agentCapabilitiesPlugins,+ window.siyuan.languages.agentCapabilitiesMcp,+ window.siyuan.languages.agentCapabilitiesAutoApprove,+];++export const genAgentCapabilityHtml = (): string => `<div class="b3-label config-item" id="aiAgentCapabilities">+ <div class="fn__flex">+ <div class="fn__flex-1">+ <div class="config-name">${window.siyuan.languages.agentCapabilities}</div>+ <div class="b3-label__text">${window.siyuan.languages.agentCapabilitiesTip}</div>+ <div class="b3-label__text" data-type="agentCapabilitySummary"></div>+ </div>+ <span class="fn__space"></span>+ <button class="b3-button b3-button--outline fn__flex-center" data-type="configureAgentCapabilities">${window.siyuan.languages.config}</button>+ </div>+</div>`;++export const mountAgentCapabilityBlock = (root: HTMLElement) => {+ const block = root.querySelector<HTMLElement>("#aiAgentCapabilities");+ if (!block) {+ return;+ }+ refreshCapabilitySummary(root);+ block.querySelector("[data-type='configureAgentCapabilities']")?.addEventListener("click", () => {+ loadCapabilities((capabilities) => openAgentCapabilityDialog(root, capabilities));+ });+};diff --git a/app/src/config/tabs/ai/aiTab.ts b/app/src/config/tabs/ai/aiTab.tsindex a0a36740bc..db5c489822 100644--- a/app/src/config/tabs/ai/aiTab.ts+++ b/app/src/config/tabs/ai/aiTab.ts@@ -20,6 +20,11 @@ import {genGroupedModelPickerHtml,mountGroupedModelPicker,} from "./aiProviderUi";+import {+ genAgentCapabilityHtml,+ getAgentCapabilityKeywords,+ mountAgentCapabilityBlock,+} from "./aiCapabilityUi";const registerAiProvidersGroup = (tab: SettingTabBuilder) => {const group = tab.group("providers", window.siyuan.languages.apiProvider);@@ -121,6 +126,17 @@ const registerAiAgentGroup = (tab: SettingTabBuilder) => {});};+const registerAiAgentCapabilitiesGroup = (tab: SettingTabBuilder) => {+ const group = tab.group("agentCapabilities", window.siyuan.languages.agentCapabilities);++ group.slot({+ key: "agentCapabilities",+ keywords: getAgentCapabilityKeywords(),+ html: genAgentCapabilityHtml,+ afterMount: mountAgentCapabilityBlock,+ });+};+const registerAiImageGenerationGroup = (tab: SettingTabBuilder) => {const groupId = "imageGeneration";const group = tab.group(groupId, window.siyuan.languages.aiImageGeneration);@@ -257,6 +273,7 @@ export const registerAiTab = (tab: SettingTabBuilder) => {registerAiProvidersGroup(tab);registerAiEditingGroup(tab);registerAiAgentGroup(tab);+ registerAiAgentCapabilitiesGroup(tab);registerAiImageGenerationGroup(tab);registerAiMcpGroup(tab);// TODO: add skills group?diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.tsindex 0cfe05b776..bb7fa060fc 100644--- a/app/src/layout/dock/agent/AgentChat.ts+++ b/app/src/layout/dock/agent/AgentChat.ts@@ -5,8 +5,7 @@ import {genUUID} from "../../../util/genID";import {mountComposer, type AgentComposerData} from "./AgentComposer";import {disabledWYSIWYG} from "../../../protyle/util/disabledWYSIWYG";import {getAllEditor} from "../../getAll";-import "./frontendActions";-import {listActions, lookupAction} from "./frontendActions";+import {isCapabilityEnabled, listCapabilityManifests, lookupCapability} from "./frontendCapabilities";import {AgentPermissionMode, AgentSession, SessionStore} from "./SessionStore";import {AgentSessionPanel} from "./AgentSessionPanel";import {updateHotkeyAfterTip} from "../../../protyle/util/compatibility";@@ -1718,7 +1717,7 @@ export class AgentChat extends Model {const blockHTML = sendData.blockHTML;const refs = sendData.references;const editorContext = this.captureEditorContext();- const pluginActions = this.getPluginActions();+ const frontendCapabilities = listCapabilityManifests();if (!text || this.isStreaming || this.modelOptions.length === 0) {return;}@@ -1795,7 +1794,7 @@ export class AgentChat extends Model {this.selectedReasoningEffort,undefined,editorContext,- pluginActions,+ frontendCapabilities,userEntryId,SessionStore.getRevision(this.sessionId),);@@ -1932,12 +1931,6 @@ export class AgentChat extends Model {/// #endif}- private getPluginActions() {- return listActions()- .filter(action => action.name.startsWith("plugin__") && action.description)- .map(action => ({name: action.name, description: action.description as string}));- }-private readEditorContext(editor: {protyle: {block?: { id?: string; rootID?: string };@@ -2101,8 +2094,8 @@ export class AgentChat extends Model {this.appendSnapshotInfo(event.snapshotID, snapshotEntryId);}break;- case "frontend_tool_call":- this.handleFrontendToolCall(event.callID, event.arguments);+ case "browser_capability_call":+ this.handleBrowserCapabilityCall(event.callID, event.capabilityID, event.generation, event.arguments);break;}} catch (e) {@@ -2875,7 +2868,7 @@ export class AgentChat extends Model {const lastUserText = lastUserEntry.content;const editorContext = this.captureEditorContext();lastUserEntry.editorContext = editorContext;- const pluginActions = this.getPluginActions();+ const frontendCapabilities = listCapabilityManifests();this.abortController = new AbortController();const requestSessionId = this.sessionId;await fetchAgentSSE(@@ -2904,7 +2897,7 @@ export class AgentChat extends Model {this.selectedReasoningEffort,true,editorContext,- pluginActions,+ frontendCapabilities,lastUserEntry.id,SessionStore.getRevision(this.sessionId),editedData?.blockHTML,@@ -3414,43 +3407,51 @@ export class AgentChat extends Model {return true;}- private async handleFrontendToolCall(callID: string, args: Record<string, unknown>) {- // Resolve the action name ("frontend" tool calls carry the action in args.action).- const action = (args.action as string | undefined) || "";- const handler = lookupAction(action);- if (!handler) {- await this.postFrontendResult(callID, `Unknown frontend action: ${action}`, true);+ private async handleBrowserCapabilityCall(callID: string, capabilityID: string, generation: number,+ args: Record<string, unknown>) {+ const capability = lookupCapability(capabilityID, generation);+ if (!capability || !isCapabilityEnabled(capabilityID)) {+ await this.postBrowserCapabilityResult(+ callID, `Browser capability is unavailable: ${capabilityID}`, undefined, false, true,+ );return;}try {- const outcome = await handler.handler(args, this.app);+ const outcome = await capability.handler(args, this.app);const result = outcome.result || "";const error = outcome.error || "";- await this.postFrontendResult(callID, error ? error : result, !!error);+ await this.postBrowserCapabilityResult(+ callID,+ error ? error : result,+ outcome.structuredContent,+ Object.prototype.hasOwnProperty.call(outcome, "structuredContent"),+ !!error,+ );} catch (e) {- await this.postFrontendResult(callID, `Frontend action threw: ${(e as Error).message}`, true);+ await this.postBrowserCapabilityResult(callID, `Browser capability threw: ${(e as Error).message}`, undefined, false, true);}}- private async postFrontendResult(callID: string, result: string, isError: boolean) {+ private async postBrowserCapabilityResult(callID: string, result: string, structuredContent: unknown,+ structuredContentSet: boolean, isError: boolean) {for (let attempt = 0; attempt < 3; attempt++) {try {- const resp = await fetch("/api/ai/agent/frontendToolResult", {+ const resp = await fetch("/api/ai/agent/browserCapabilityResult", {method: "POST",headers: {"Content-Type": "application/json"},- body: JSON.stringify({callID, result, isError}),+ body: JSON.stringify({callID, result, structuredContent, structuredContentSet, isError}),});const response = await resp.json() as {code?: number};if (resp.ok && response?.code === 0) {return;}if (resp.status === 409) {- console.error("agent frontend result expired:", callID);+ console.error("agent browser capability result expired:", callID);return;}} catch (e) {if (attempt === 2) {- console.error("agent frontend result request error:", e);+ console.error("agent browser capability result request error:", e);}}await new Promise((resolve) => window.setTimeout(resolve, 200 * (attempt + 1)));diff --git a/app/src/layout/dock/agent/agentSSE.ts b/app/src/layout/dock/agent/agentSSE.tsindex 5c31aa0b2f..c0c4a483a3 100644--- a/app/src/layout/dock/agent/agentSSE.ts+++ b/app/src/layout/dock/agent/agentSSE.ts@@ -69,9 +69,11 @@ export type ISSEResult = {type: "permission";permissionMode: "confirm" | "allowSession";} | {- type: "frontend_tool_call";+ type: "browser_capability_call";callID: string;name: string;+ capabilityID: string;+ generation: number;arguments: Record<string, unknown>;};@@ -108,7 +110,19 @@ export async function fetchAgentSSE(reasoningEffort?: string,regenerate?: boolean,editorContext?: IEditorContext,- pluginActions?: Array<{name: string; description: string}>,+ frontendCapabilities?: Array<{+ id: string;+ title?: string;+ description: string;+ inputSchema: Record<string, unknown>;+ outputSchema?: Record<string, unknown>;+ effects?: IToolEffects;+ actionEffects?: Record<string, IToolEffects>;+ source: "native" | "plugin";+ ownerId?: string;+ ownerName?: string;+ generation: number;+ }>,userEntryID?: string,contentRevision?: number,blockHTML?: string,@@ -132,7 +146,7 @@ export async function fetchAgentSSE(if (reasoningEffort) { body.reasoningEffort = reasoningEffort; }if (regenerate) { body.regenerate = regenerate; }if (editorContext) { body.editorContext = editorContext; }- if (pluginActions && pluginActions.length > 0) { body.pluginActions = pluginActions; }+ if (frontendCapabilities && frontendCapabilities.length > 0) { body.frontendCapabilities = frontendCapabilities; }if (userEntryID) { body.userEntryID = userEntryID; }if (typeof contentRevision === "number") { body.contentRevision = contentRevision; }if (blockHTML !== undefined) { body.blockHTML = blockHTML; }@@ -336,11 +350,13 @@ function buildSSEResult(event: string, data: Record<string, unknown>): ISSEResulsnapshotID: data.snapshotID as string,roundID: data.roundID as string || undefined,};- case "frontend_tool_call":+ case "browser_capability_call":return {- type: "frontend_tool_call",+ type: "browser_capability_call",callID: data.callID as string,name: data.name as string,+ capabilityID: data.capabilityID as string,+ generation: data.generation as number,arguments: (data.arguments || {}) as Record<string, unknown>,};default:diff --git a/app/src/layout/dock/agent/frontendActions.ts b/app/src/layout/dock/agent/frontendCapabilities.tssimilarity index 56%rename from app/src/layout/dock/agent/frontendActions.tsrename to app/src/layout/dock/agent/frontendCapabilities.tsindex 4511c48c3f..7076fda633 100644--- a/app/src/layout/dock/agent/frontendActions.ts+++ b/app/src/layout/dock/agent/frontendCapabilities.ts@@ -16,54 +16,100 @@import type {App} from "../../../index";-export interface IAction {- name: string;- description?: string;- handler: (args: Record<string, unknown>, app: App) => Promise<{result?: string; error?: string}>;+// 浏览器能力只在当前应用实例中执行,内核持有声明和本轮不可变的调用映射。++export interface IAgentCapabilityEffects {+ localRead?: boolean;+ localWrite?: boolean;+ dataEgress?: boolean;+ externalCost?: boolean;}-// Centralized action registry. Data structure is a registry so that plugins can register their-// own frontend actions in a future version (via Plugin.addAction() -> registerAction). The first-// version only loads built-in actions, but the lookup layer is already registry-shaped, so adding-// plugin support later requires zero changes to the dispatch path.-//-// IMPORTANT: this module must NOT have any top-level value imports beyond the registry itself.-// The built-in actions below pull in config/editor/search modules that participate in import-// cycles with the layout/plugin graph, so they are loaded lazily via dynamic import() inside the-// handlers (which are async). This keeps `import {lookupAction}` cycle-free.-const actionRegistry = new Map<string, IAction>();--export const registerAction = (a: IAction) => {- actionRegistry.set(a.name, a);+export interface IAgentCapability {+ id: string;+ title?: string;+ description: string;+ inputSchema: Record<string, unknown>;+ outputSchema?: Record<string, unknown>;+ effects?: IAgentCapabilityEffects;+ actionEffects?: Record<string, IAgentCapabilityEffects>;+ source: "native" | "plugin";+ ownerId?: string;+ ownerName?: string;+ generation?: number;+ handler: (args: Record<string, unknown>, app: App) => Promise<{+ result?: string;+ structuredContent?: unknown;+ error?: string;+ }>;+}++export type IAgentCapabilityManifest = Omit<IAgentCapability, "handler"> & {generation: number};++const capabilityRegistry = new Map<string, IAgentCapabilityManifest & Pick<IAgentCapability, "handler">>();+let capabilityGeneration = 0;++export const registerCapability = (capability: IAgentCapability) => {+ capabilityGeneration++;+ capabilityRegistry.set(capability.id, {...capability, generation: capabilityGeneration});+ return capabilityGeneration;+};++export const lookupCapability = (id: string, generation?: number): IAgentCapability | undefined => {+ const capability = capabilityRegistry.get(id);+ if (!capability || generation !== undefined && capability.generation !== generation) {+ return undefined;+ }+ return capability;};-export const lookupAction = (name: string): IAction | undefined => actionRegistry.get(name);+export const isCapabilityEnabled = (id: string): boolean => {+ const policy = window.siyuan.config.ai.agent.capabilityPolicy;+ if (!policy) {+ return true;+ }+ return (policy.overrides[id] || policy.default) === "allow";+};-export const listActions = (): IAction[] => Array.from(actionRegistry.values());+export const listCapabilityManifests = (): IAgentCapabilityManifest[] => Array.from(capabilityRegistry.values()).map((capability) => ({+ id: capability.id,+ title: capability.title,+ description: capability.description,+ inputSchema: capability.inputSchema,+ outputSchema: capability.outputSchema,+ effects: capability.effects,+ actionEffects: capability.actionEffects,+ source: capability.source,+ ownerId: capability.ownerId,+ ownerName: capability.ownerName,+ generation: capability.generation,+}));-export const unregisterAction = (name: string) => {- actionRegistry.delete(name);+export const unregisterCapability = (id: string, generation?: number) => {+ if (generation !== undefined && capabilityRegistry.get(id)?.generation !== generation) {+ return;+ }+ capabilityRegistry.delete(id);};/// #if !MOBILE-registerAction({- name: "open_setting",+registerCapability({+ id: "native/frontend/open_setting",+ title: "Open settings",+ description: "Open SiYuan settings and optionally filter settings by a search query.",+ inputSchema: {type: "object", properties: {query: {type: "string"}}, additionalProperties: false},+ source: "native",handler: async (args, app) => {const query = (args.query as string | undefined)?.trim();const {openSetting} = await import("../../../config");- // openSetting() has a quirk: if a settings dialog already exists, it DESTROYS it and- // returns the destroyed dialog (the splice from window.siyuan.dialogs is deferred via- // setTimeout, so it can't be detected synchronously). To guarantee the panel is visible- // after this call, check first: if one is already open, reuse it; otherwise open fresh.+ // 已有设置对话框时复用该实例,避免 openSetting() 销毁现有实例后返回待销毁的对象。const existing = window.siyuan.dialogs.find(d => d.element.querySelector(".config__tab-container"));let dialog = existing;if (!dialog) {dialog = openSetting(app);}if (query) {- // The settings panel has a built-in search box (wired by initConfigSearch in- // config/index.ts). Fill it and dispatch an "input" event to trigger live filtering,- // which surfaces matching config items.+ // 填充设置面板的内置搜索框并触发实时筛选。const input = dialog.element.querySelector(".config__side .b3-text-field") as HTMLInputElement;if (input) {input.value = query;@@ -75,15 +121,19 @@ registerAction({},});-registerAction({- name: "focus_block",+registerCapability({+ id: "native/frontend/focus_block",+ title: "Focus block",+ description: "Scroll a block already loaded in an editor into view and highlight it.",+ inputSchema: {type: "object", properties: {id: {type: "string"}}, required: ["id"], additionalProperties: false},+ source: "native",handler: async (args) => {const id = args.id as string | undefined;if (!id) {return {error: "missing required argument: id"};}const {getAllEditor} = await import("../../getAll");- // Find the editor whose document contains this block, then scroll it into view.+ // 找到包含目标块的编辑器并滚动到该块。let blockEl: HTMLElement | null = null;for (const editor of getAllEditor()) {const el = editor.protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`) as HTMLElement | null;@@ -96,15 +146,19 @@ registerAction({return {error: `Block ${id} is not loaded in any open editor. Use open_document to open it first.`};}blockEl.scrollIntoView({behavior: "smooth", block: "center"});- // Briefly highlight the block so the user can spot it.+ // 短暂高亮目标块以便用户定位。blockEl.classList.add("protyle-wysiwyg--hl");setTimeout(() => blockEl?.classList.remove("protyle-wysiwyg--hl"), 2000);return {result: `Focused block ${id} in the active editor.`};},});-registerAction({- name: "open_document",+registerCapability({+ id: "native/frontend/open_document",+ title: "Open document",+ description: "Open a SiYuan document by its block ID in the current app.",+ inputSchema: {type: "object", properties: {id: {type: "string"}}, required: ["id"], additionalProperties: false},+ source: "native",handler: async (args, app) => {const id = args.id as string | undefined;if (!id) {@@ -123,8 +177,12 @@ registerAction({},});-registerAction({- name: "open_search",+registerCapability({+ id: "native/frontend/open_search",+ title: "Open search",+ description: "Open the SiYuan search interface and optionally fill in a query.",+ inputSchema: {type: "object", properties: {query: {type: "string"}}, additionalProperties: false},+ source: "native",handler: async (args, app) => {const query = (args.query as string | undefined)?.trim();const [{openSearch}, {Constants}] = await Promise.all([@@ -136,8 +194,12 @@ registerAction({},});/// #else-registerAction({- name: "open_setting",+registerCapability({+ id: "native/frontend/open_setting",+ title: "Open settings",+ description: "Open SiYuan settings and optionally provide a search query.",+ inputSchema: {type: "object", properties: {query: {type: "string"}}, additionalProperties: false},+ source: "native",handler: async (args, app) => {const query = (args.query as string | undefined)?.trim();const [{hideMobileAgent, reopenMobileAgent}, {openMobileSetting}] = await Promise.all([@@ -150,8 +212,12 @@ registerAction({},});-registerAction({- name: "focus_block",+registerCapability({+ id: "native/frontend/focus_block",+ title: "Focus block",+ description: "Scroll a block already loaded in the current editor into view and highlight it.",+ inputSchema: {type: "object", properties: {id: {type: "string"}}, required: ["id"], additionalProperties: false},+ source: "native",handler: async (args) => {const id = args.id as string | undefined;if (!id) {@@ -174,8 +240,12 @@ registerAction({},});-registerAction({- name: "open_document",+registerCapability({+ id: "native/frontend/open_document",+ title: "Open document",+ description: "Open a SiYuan document by its block ID in the mobile app.",+ inputSchema: {type: "object", properties: {id: {type: "string"}}, required: ["id"], additionalProperties: false},+ source: "native",handler: async (args, app) => {const id = args.id as string | undefined;if (!id) {@@ -196,8 +266,12 @@ registerAction({},});-registerAction({- name: "open_search",+registerCapability({+ id: "native/frontend/open_search",+ title: "Open search",+ description: "Open the SiYuan mobile search interface and optionally fill in a query.",+ inputSchema: {type: "object", properties: {query: {type: "string"}}, additionalProperties: false},+ source: "native",handler: async (args, app) => {const query = (args.query as string | undefined)?.trim();const [{popSearch}, {hideMobileAgent}] = await Promise.all([diff --git a/app/src/plugin/index.ts b/app/src/plugin/index.tsindex 575dc765f6..8efbfb29aa 100644--- a/app/src/plugin/index.ts+++ b/app/src/plugin/index.ts@@ -23,7 +23,7 @@ import {uninstall} from "./uninstall";import {addPluginDock, afterLoadPlugin, loadPlugins} from "./loader";import {normalizeStoragePath} from "../util/pathName";import {Kernel} from "./kernel";-import {registerAction} from "../layout/dock/agent/frontendActions";+import {IAgentCapabilityEffects, registerCapability} from "../layout/dock/agent/frontendCapabilities";export class Plugin {private app: App;@@ -52,9 +52,7 @@ export class Plugin {public setting: Setting;public statusBarIcons: Element[] = [];public commands: ICommand[] = [];- // Full names of agent actions this plugin registered (plugin__<name>__<action>), tracked- // so they can be unregistered on uninstall.- public agentActions: string[] = [];+ public agentCapabilities: Array<{id: string; generation: number}> = [];public models: {/// #if !MOBILE[key: string]: (options: { tab: Tab, data: any }) => Custom@@ -435,17 +433,42 @@ export class Plugin {return found ? found.value : "";}- public addAgentAction(options: {+ public addAgentCapability(options: {name: string,+ title?: string,description: string,- handler: (args: Record<string, unknown>, app: App) => Promise<{result?: string; error?: string}>+ inputSchema: Record<string, unknown>,+ outputSchema?: Record<string, unknown>,+ effects?: IAgentCapabilityEffects,+ actionEffects?: Record<string, IAgentCapabilityEffects>,+ handler: (args: Record<string, unknown>, app: App) => Promise<{+ result?: string;+ structuredContent?: unknown;+ error?: string;+ }>}): string {- const fullName = "plugin__" + this.name + "__" + options.name;- if (!this.agentActions.includes(fullName)) {- registerAction({name: fullName, description: options.description, handler: options.handler});- this.agentActions.push(fullName);+ const name = options.name.trim();+ if (!name || !options.description.trim()) {+ throw new Error("Agent capability name and description are required");}- return fullName;+ const id = "plugin/frontend/" + encodeURIComponent(this.name) + "/" + encodeURIComponent(name);+ if (!this.agentCapabilities.some((capability) => capability.id === id)) {+ const generation = registerCapability({+ id,+ title: options.title,+ description: options.description,+ inputSchema: options.inputSchema,+ outputSchema: options.outputSchema,+ effects: options.effects,+ actionEffects: options.actionEffects,+ source: "plugin",+ ownerId: this.name,+ ownerName: this.displayName || this.name,+ handler: options.handler,+ });+ this.agentCapabilities.push({id, generation});+ }+ return id;}public addDock(options: {diff --git a/app/src/plugin/uninstall.ts b/app/src/plugin/uninstall.tsindex 1a79180c9d..d704b7decb 100644--- a/app/src/plugin/uninstall.ts+++ b/app/src/plugin/uninstall.ts@@ -11,7 +11,7 @@ import {ipcRenderer} from "electron";import {Constants} from "../constants";import {setStorageVal} from "../protyle/util/compatibility";import {getAllEditor} from "../layout/getAll";-import {unregisterAction} from "../layout/dock/agent/frontendActions";+import {unregisterCapability} from "../layout/dock/agent/frontendCapabilities";export const uninstall = (app: App, name: string, isReload: boolean) => {app.plugins.find((plugin: Plugin, index) => {@@ -57,8 +57,8 @@ export const uninstall = (app: App, name: string, isReload: boolean) => {plugin.topBarIcons.splice(i, 1);i--;}- // rm agent actions- plugin.agentActions.forEach(name => unregisterAction(name));+ // 移除插件注册的 Agent 能力+ plugin.agentCapabilities.forEach((capability) => unregisterCapability(capability.id, capability.generation));/// #if !MOBILE// rm statusBarplugin.statusBarIcons.forEach(item => {diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.tsindex 39a4ec1419..3c07005278 100644--- a/app/src/types/config.d.ts+++ b/app/src/types/config.d.ts@@ -172,6 +172,17 @@ declare namespace Config {temperature: number;maxCompletionTokens: number;maxToolCallRounds: number;+ capabilityPolicy: {+ default: "allow" | "deny";+ overrides: Record<string, "allow" | "deny">;+ };+ approvalPolicy: {+ default: "confirm" | "allow";+ overrides: Record<string, {+ default: "" | "confirm" | "allow";+ actions: Record<string, "confirm" | "allow">;+ }>;+ };}/**diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex ac0f00424c..ea244dd239 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -65,7 +65,8 @@ const systemPrompt = `You are a SiYuan AI assistant. You help users manage their- HTML components: asset.create_html writes HTML content as an asset and inserts a sandboxed IFrame block in one operation. Prefer self-contained HTML; only use remote resources when the user requests them.## Response Guidelines-- Reply in the language configured in SiYuan's appearance settings. When mentioning documents/blocks the user can open, format them as markdown links: [title](siyuan://blocks/<blockID>). Only use block IDs actually returned by a tool call (block.get/get_children/breadcrumb/batch_get/search); never fabricate IDs. For general mentions without a specific block, plain text is fine.+- Reply in the language configured in SiYuan's appearance settings.+- When mentioning documents/blocks the user can open, format them as markdown links: [title](siyuan://blocks/<blockID>). Only use block IDs actually returned by a tool call (block.get/get_children/breadcrumb/batch_get/search); never fabricate IDs. For general mentions without a specific block, plain text is fine.- Be concise: summarize rather than repeat large content.- For choices (which notebook/document/action), use the question tool — never a plain text list.- Use markdown; for code blocks always specify the language (e.g. python, go); use $...$ for inline and $...$ for block formulas.@@ -253,26 +254,33 @@ func AnswerQuestion(id string, answers []string) bool {}}-// frontendCallResult 承载浏览器返回的前端工具执行结果。-type frontendCallResult struct {- result string- isError bool+// browserCapabilityResult 承载浏览器返回的前端能力执行结果。+type browserCapabilityResult struct {+ result string+ structuredContent any+ structuredContentSet bool+ isError bool}-var frontendCallChannelsMu sync.Mutex-var frontendCallChannels = make(map[string]chan frontendCallResult)+var browserCapabilityChannelsMu sync.Mutex+var browserCapabilityChannels = make(map[string]chan browserCapabilityResult)-// FrontendToolResult 由 API 在浏览器回传前端工具结果时调用,用于解除 Agent 的等待。-func FrontendToolResult(callID string, result string, isError bool) bool {- frontendCallChannelsMu.Lock()- defer frontendCallChannelsMu.Unlock()- ch, ok := frontendCallChannels[callID]+// BrowserCapabilityResult 由 API 在浏览器回传前端能力结果时调用,用于解除 Agent 的等待。+func BrowserCapabilityResult(callID string, result string, structuredContent any, structuredContentSet, isError bool) bool {+ browserCapabilityChannelsMu.Lock()+ defer browserCapabilityChannelsMu.Unlock()+ ch, ok := browserCapabilityChannels[callID]if !ok {return false}select {- case ch <- frontendCallResult{result: result, isError: isError}:- delete(frontendCallChannels, callID)+ case ch <- browserCapabilityResult{+ result: result,+ structuredContent: structuredContent,+ structuredContentSet: structuredContentSet,+ isError: isError,+ }:+ delete(browserCapabilityChannels, callID)return truedefault:return false@@ -326,6 +334,8 @@ type AgentEvent struct {TurnID stringPermissionMode stringEffects mcptools.ToolEffects+ CapabilityID string+ Generation uint64}type AgentMessage struct {@@ -398,15 +408,6 @@ func newAgentUserMessage(content, entryID string, references []Reference, editor}}-// PluginAction describes a frontend action registered by a plugin (via Plugin.addAction()).-// The frontend serializes the list of currently-registered plugin actions into each chat-// request, and the backend injects them into the system prompt so the LLM can discover and-// invoke them. Structurally identical to EditorContext: browser-owned state, refreshed per message.-type PluginAction struct {- Name string `json:"name"` // full name: plugin__<pluginName>__<actionName>- Description string `json:"description"` // purpose description for the LLM-}-// SessionEntry 与前端 SessionStore.ts 中 entries 元素一一对应,// 是会话持久化的唯一数据源(不再单独持久化 messages)。type SessionEntry struct {@@ -466,7 +467,7 @@ type agentCheckpoint struct {LastCommittedTurnID string `json:"lastCommittedTurnID,omitempty"`}-func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilityKey string, contextLimit int, sessionID string, userEntryID string, contentRevision int64, userMessage string, userBlockHTML *string, language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction, regenerate bool, confirmTimeout time.Duration, maxRetries int, reasoningEffort string, requestTimeout, streamIdleTimeout time.Duration) <-chan AgentEvent {+func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilityKey string, contextLimit int, sessionID string, userEntryID string, contentRevision int64, userMessage string, userBlockHTML *string, language string, references []Reference, editorCtx EditorContext, frontendCapabilities []FrontendCapability, regenerate bool, confirmTimeout time.Duration, maxRetries int, reasoningEffort string, requestTimeout, streamIdleTimeout time.Duration) <-chan AgentEvent {ch := make(chan AgentEvent, 256)go func() {@@ -498,7 +499,17 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilit// 在此统一解析一次,后续 checkpoint 与消息重建均使用解析后的值,保证全链路一致。userMessage = kernelModel.Conf.Variables.Resolve(userMessage)- tools := convertMCPToolsToOpenAI()+ capabilityContext := capabilityAccessContext{+ SessionID: sessionID,+ NotebookID: editorCtx.NotebookID,+ DocumentID: editorCtx.ActiveDocID,+ }+ capabilities, capabilityErr := buildCapabilitySet(frontendCapabilities, capabilityContext)+ if capabilityErr != nil {+ sendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: capabilityErr.Error()})+ return+ }+ tools := capabilities.definitionsvar messages []openai.ChatCompletionMessagevar checkpointMsgs []AgentMessagevar sessionEntries []SessionEntry@@ -582,14 +593,14 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitcurrentUserEntry.BlockHTML = *userBlockHTML}}- messages = checkpointMessagesToOpenAIWithSummary(checkpointMsgs, language, pluginActions, compaction)+ messages = checkpointMessagesToOpenAIWithSummary(checkpointMsgs, language, capabilities, compaction)}}}if messages == nil {checkpointMsgs = []AgentMessage{newAgentUserMessage(userMessage, userEntryID, references, editorCtx)}- messages = buildInitialMessages(userMessage, language, references, editorCtx, pluginActions)+ messages = buildInitialMessages(userMessage, language, references, editorCtx, capabilities)}turnBaseIndex := len(checkpointMsgs)@@ -720,7 +731,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitselectedCandidateIndex := sort.Search(len(candidates), func(i int) bool {candidate := candidates[i]candidateCheckpointMsgs := checkpointMessagesAfterCompaction(sessionEntries, candidate, tail)- candidateMessages := checkpointMessagesToOpenAIWithSummary(candidateCheckpointMsgs, language, pluginActions, nil)+ candidateMessages := checkpointMessagesToOpenAIWithSummary(candidateCheckpointMsgs, language, capabilities, nil)candidateMessages, _ = projectImageMessages(candidateMessages)baseTokens := estimateChatRequestTokens(model, candidateMessages, requestTools)return compactionSummaryMinTokens <= inputBudget-baseTokens-compactionSummaryOverhead@@ -731,7 +742,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitselectedEntryCount := candidates[selectedCandidateIndex]selectedCheckpointMsgs := checkpointMessagesAfterCompaction(sessionEntries, selectedEntryCount, tail)selectedMessages := checkpointMessagesToOpenAIWithSummary(- selectedCheckpointMsgs, language, pluginActions, nil)+ selectedCheckpointMsgs, language, capabilities, nil)estimatedSelectedMessages, _ := projectImageMessages(selectedMessages)baseTokens := estimateChatRequestTokens(model, estimatedSelectedMessages, requestTools)summaryMaxTokens := min(@@ -762,7 +773,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitreturn false, fmt.Errorf("%w: build runtime state: %v", errContextCannotBeCompacted, err)}nextMessages := checkpointMessagesToOpenAIWithSummary(- selectedCheckpointMsgs, language, pluginActions, nextCompaction)+ selectedCheckpointMsgs, language, capabilities, nextCompaction)estimatedNextMessages, _ := projectImageMessages(nextMessages)if estimateChatRequestTokens(model, estimatedNextMessages, requestTools) > inputBudget {return false, fmt.Errorf("%w: compacted context still exceeds the input budget", errContextCannotBeCompacted)@@ -791,10 +802,24 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilit}modelRound++- requestTools := tools+ roundCapabilities, capabilityErr := buildCapabilitySet(frontendCapabilities, capabilityContext)+ if capabilityErr != nil {+ if !saveTurn("interrupted") {+ return+ }+ sendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: capabilityErr.Error()})+ return+ }+ requestTools := roundCapabilities.definitionsif maxRounds > 0 && toolCallRounds >= maxRounds {// 工具调用达到上限后仍允许模型完成一次最终回答,但不再提供工具定义。requestTools = nil+ roundCapabilities = &capabilitySet{registrations: map[string]*capabilityRegistration{}}+ }+ capabilities = roundCapabilities+ tools = requestTools+ if len(messages) > 0 && messages[0].Role == openai.ChatMessageRoleSystem {+ messages[0].Content = buildSystemPrompt(language, roundCapabilities)}_, compactErr := compactContext(requestTools, false)@@ -1020,6 +1045,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitfor i, tc := range aggregatedToolCalls {args := parsedArgs[i]+ registration := roundCapabilities.registration(tc.Function.Name)action := ""if a, ok := args["action"]; ok {action, _ = a.(string)@@ -1033,17 +1059,18 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitArguments: args,})- _, _, toolInputErr := validateToolCallInput(ctx, tc.Function.Name, args)+ toolInputErr := validateCapabilityCall(ctx, registration, args)if toolInputErr == nil && !permissionController.allowSession.Load() &&- needsConfirm(tc.Function.Name, action, nil) {+ needsCapabilityConfirm(registration, action, args, nil) {confirmID := fmt.Sprintf("%s_%s_%d", turn.TurnID, tc.ID, i)ch2 := make(chan confirmResult, 1)confirmChannelsMu.Lock()confirmChannels[confirmID] = &confirmWaiter{sessionID: sessionID, ch: ch2}confirmChannelsMu.Unlock()- effects, _ := mcptools.GetTool(tc.Function.Name).EffectsFor(action)+ effects := capabilityEffects(registration, action)sendCriticalEvent(ctx, ch, AgentEvent{Type: "confirm", Name: tc.Function.Name, Arguments: args, ConfirmID: confirmID, Effects: effects,+ CapabilityID: registration.ID,})var rejectionMsg stringvar result confirmResult@@ -1153,8 +1180,12 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitreturndefault:}+ if toolInputErr == nil {+ // 用户确认期间能力可能被禁用、卸载或重新注册,快照和执行前必须复核同一份注册。+ toolInputErr = validateCapabilityCall(ctx, registration, args)+ }- if toolInputErr == nil && !snapshotCreated && needsLocalSnapshot(tc.Function.Name, action) {+ if toolInputErr == nil && !snapshotCreated && needsCapabilitySnapshot(registration, action) {id, err := kernelModel.IndexRepo("AI agent auto snapshot")if err != nil {logging.LogErrorf("agent auto snapshot failed: %s", err)@@ -1205,18 +1236,20 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitsendCriticalEvent(ctx, ch, AgentEvent{Type: "snapshot", RoundID: roundID, SnapshotID: id})}- // 工具执行前先持久化“即将执行”状态。若落盘失败则禁止执行,避免外部写操作已经发生,- // 但恢复层没有任何记录可用于阻止自动重试。- checkpointMsgs[assistantIdx].ToolCalls[i].State = "executing"- if !saveTurn("running") {- return- }- select {- case <-ctx.Done():- skipRemainingTools(i, "Operation cancelled")- saveTurn("interrupted")- return- default:+ if toolInputErr == nil {+ // 工具执行前先持久化“即将执行”状态。若落盘失败则禁止执行,避免外部写操作已经发生,+ // 但恢复层没有任何记录可用于阻止自动重试。+ checkpointMsgs[assistantIdx].ToolCalls[i].State = "executing"+ if !saveTurn("running") {+ return+ }+ select {+ case <-ctx.Done():+ skipRemainingTools(i, "Operation cancelled")+ saveTurn("interrupted")+ return+ default:+ }}var resultStr stringvar modelAttachments []mcptools.ModelAttachment@@ -1227,11 +1260,13 @@ func AgentChat(ctx context.Context, client *openai.Client, model, imageCapabilitisErr = true} else if tc.Function.Name == "question" {resultStr = handleQuestion(ctx, tc.Function.Arguments, ch, 5*time.Minute)- } else if tc.Function.Name == "frontend" {- resultStr, executionUnknown = handleFrontendTool(ctx, tc, ch, confirmTimeout)- isErr = executionUnknown+ } else if registration.isBrowser() {+ executed := handleBrowserCapability(ctx, tc, registration, ch, confirmTimeout)+ resultStr = executed.Text+ isErr = executed.IsError+ executionUnknown = executed.ExecutionUnknown} else {- executed := executeTool(ctx, tc, sessionID)+ executed := executeCapability(ctx, tc, sessionID, registration)resultStr = executed.TextmodelAttachments = executed.ModelAttachmentsisErr = executed.IsError@@ -1428,9 +1463,47 @@ var safeNativeToolActions = map[string]map[string]bool{"export": {"html": true, "preview": true,},- "frontend": {- "open_setting": true, "focus_block": true, "open_document": true, "open_search": true,- },+}++func capabilityEffects(registration *capabilityRegistration, action string) mcptools.ToolEffects {+ if registration == nil {+ return mcptools.ToolEffects{}+ }+ if registration.isBrowser() {+ effects, _ := registration.browserEffectsFor(action)+ return effects+ }+ effects, _ := registration.Tool.EffectsFor(action)+ return effects+}++func needsCapabilityConfirm(registration *capabilityRegistration, action string, args map[string]any,+ alwaysAllow map[string]bool) bool {+ if registration == nil {+ return false+ }+ if alwaysAllow["*"] || alwaysAllow[registration.ID] || alwaysAllow[registration.ModelName+"::"+action] {+ return false+ }+ if capabilityAutoApproved(registration, action, args) {+ return false+ }+ if registration.isBrowser() {+ effects, declared := registration.browserEffectsFor(action)+ if effects.LocalWrite || effects.DataEgress || effects.ExternalCost {+ return true+ }+ // 插件声明的浏览器能力不默认信任;只有显式的只读效果声明才能免确认。+ return registration.Source != "native" && !declared+ }+ return needsConfirm(registration.ModelName, action, alwaysAllow)+}++func needsCapabilitySnapshot(registration *capabilityRegistration, action string) bool {+ if registration == nil || registration.isBrowser() {+ return false+ }+ return needsLocalSnapshot(registration.ModelName, action)}func needsConfirm(toolName string, action string, alwaysAllow map[string]bool) bool {@@ -1488,7 +1561,7 @@ func needsLocalSnapshot(toolName, action string) bool {if toolName == "import" && action == "md" {actionSafe = false}- if safeWholeTools[toolName] || actionSafe || toolName == "frontend" || (toolName == "repo" && action == "create") {+ if safeWholeTools[toolName] || actionSafe || (toolName == "repo" && action == "create") {return false}if tool == nil {@@ -1585,75 +1658,104 @@ func finishConfirmWait(confirmID string, ch chan confirmResult) (confirmResult,}}-// handleFrontendTool 通过 SSE 把前端工具操作发送到浏览器,并等待浏览器回传结果。-func handleFrontendTool(ctx context.Context, tc openai.ToolCall, ch chan<- AgentEvent, timeout time.Duration) (string, bool) {+// handleBrowserCapability 通过 SSE 把前端能力调用发送到浏览器,并等待浏览器回传结果。+func handleBrowserCapability(ctx context.Context, tc openai.ToolCall, registration *capabilityRegistration,+ ch chan<- AgentEvent, timeout time.Duration) executedToolResult {+ if !capabilityStillExecutable(registration, parseToolArgs(tc.Function.Arguments)) {+ return executedToolResult{Text: "Browser capability is disabled or no longer available.", IsError: true}+ }args := parseToolArgs(tc.Function.Arguments)callID := ast.NewNodeID()- ch2 := make(chan frontendCallResult, 1)- frontendCallChannelsMu.Lock()- frontendCallChannels[callID] = ch2- frontendCallChannelsMu.Unlock()+ ch2 := make(chan browserCapabilityResult, 1)+ browserCapabilityChannelsMu.Lock()+ browserCapabilityChannels[callID] = ch2+ browserCapabilityChannelsMu.Unlock()sendCriticalEvent(ctx, ch, AgentEvent{- Type: "frontend_tool_call",- CallID: callID,- Name: tc.Function.Name,- Arguments: args,+ Type: "browser_capability_call",+ CallID: callID,+ Name: tc.Function.Name,+ CapabilityID: registration.ID,+ Generation: registration.Generation,+ Arguments: args,})- var fr frontendCallResult+ var result browserCapabilityResultselect {- case fr = <-ch2:+ case result = <-ch2:case <-ctx.Done():- if acceptedResult, accepted := finishFrontendWait(callID, ch2); accepted {- fr = acceptedResult+ if acceptedResult, accepted := finishBrowserCapabilityWait(callID, ch2); accepted {+ result = acceptedResult} else {- return "Frontend action was interrupted; execution result is unknown and must not be retried automatically.", true+ return executedToolResult{+ Text: "Browser capability was interrupted; execution result is unknown and must not be retried automatically.",+ IsError: true,+ ExecutionUnknown: true,+ }}case <-time.After(timeout):- if acceptedResult, accepted := finishFrontendWait(callID, ch2); accepted {- fr = acceptedResult+ if acceptedResult, accepted := finishBrowserCapabilityWait(callID, ch2); accepted {+ result = acceptedResult} else {- return "Frontend action timed out; execution result is unknown and must not be retried automatically.", true+ return executedToolResult{+ Text: "Browser capability timed out; execution result is unknown and must not be retried automatically.",+ IsError: true,+ ExecutionUnknown: true,+ }}}- frontendCallChannelsMu.Lock()- delete(frontendCallChannels, callID)- frontendCallChannelsMu.Unlock()+ browserCapabilityChannelsMu.Lock()+ delete(browserCapabilityChannels, callID)+ browserCapabilityChannelsMu.Unlock()- if fr.isError {- return "Frontend action failed: " + fr.result, false+ toolResult := mcptools.CallToolResult{+ StructuredContent: result.structuredContent,+ StructuredContentSet: result.structuredContentSet,+ IsError: result.isError,+ }+ if result.result != "" {+ toolResult.Content = []mcptools.ContentItem{{Type: "text", Text: result.result}}+ }+ if err := registration.Validator.ValidateOutputContext(ctx, toolResult); err != nil {+ return executedToolResult{+ Text: "Invalid browser capability output after execution; execution result may have side effects and must not be retried automatically: " + err.Error(),+ IsError: true,+ ExecutionUnknown: true,+ }+ }+ if result.isError {+ return executedToolResult{Text: "Browser capability failed: " + resultToString(toolResult), IsError: true}}- return fr.result, false+ return executedToolResult{Text: resultToString(toolResult)}}-func finishFrontendWait(callID string, ch chan frontendCallResult) (frontendCallResult, bool) {- frontendCallChannelsMu.Lock()- registered, exists := frontendCallChannels[callID]+func finishBrowserCapabilityWait(callID string, ch chan browserCapabilityResult) (browserCapabilityResult, bool) {+ browserCapabilityChannelsMu.Lock()+ registered, exists := browserCapabilityChannels[callID]pending := exists && registered == chif pending {- delete(frontendCallChannels, callID)+ delete(browserCapabilityChannels, callID)}- frontendCallChannelsMu.Unlock()+ browserCapabilityChannelsMu.Unlock()if pending {- return frontendCallResult{}, false+ return browserCapabilityResult{}, false}select {case result := <-ch:return result, truedefault:- return frontendCallResult{}, false+ return browserCapabilityResult{}, false}}-func buildSystemPrompt(language string, pluginActions []PluginAction) string {+func buildSystemPrompt(language string, capabilities *capabilitySet) string {if kernelModel.Conf != nil && kernelModel.Conf.Appearance != nil && kernelModel.Conf.Appearance.Lang != "" {language = kernelModel.Conf.Appearance.Lang}var sb strings.Builder- sb.WriteString(systemPrompt)+ sb.WriteString(filterSystemPromptByCapabilities(systemPrompt, capabilities))sb.WriteString("\n\n<env>\nWorkspace: ")sb.WriteString(util.WorkspaceDir)sb.WriteString("\nVersion: ")@@ -1665,7 +1767,7 @@ func buildSystemPrompt(language string, pluginActions []PluginAction) string {sb.WriteString("\n</env>")skills := util.DiscoverSkills()- if len(skills) > 0 {+ if capabilities.hasModelName("skill") && len(skills) > 0 {sb.WriteString("\n\n<available_skills>\n")for _, s := range skills {sb.WriteString(" <skill>\n")@@ -1681,37 +1783,25 @@ func buildSystemPrompt(language string, pluginActions []PluginAction) string {sb.WriteString("Use the skill tool to load a skill when a task matches its description.")}- if len(pluginActions) > 0 {- pluginActions = append([]PluginAction(nil), pluginActions...)- sort.Slice(pluginActions, func(i, j int) bool {- return pluginActions[i].Name < pluginActions[j].Name- })- sb.WriteString("\n\n<plugin_actions>\n")- sb.WriteString("The following frontend actions were registered by plugins. Invoke them via the \"frontend\" tool with action set to the full name shown below.\n")- for _, a := range pluginActions {- sb.WriteString("- ")- sb.WriteString(a.Name)- sb.WriteString(": ")- sb.WriteString(a.Description)- sb.WriteString("\n")- }- sb.WriteString("</plugin_actions>")+ if capabilities.hasModelName("skill") {+ sb.WriteString("\n\n")+ sb.WriteString("## Skill Management\n")+ sb.WriteString("Use the skill tool to manage reusable skills: \"save\" (create/update; provide name + SKILL.md content with YAML frontmatter ---\\nname: ...\\ndescription: ...\\n--- and markdown body), \"install\" (download & install a skill from a remote source — pass url; accepts 'owner/repo' shorthand like Tencent/WeChatReading, a full GitHub URL, a raw SKILL.md URL, or a release zip URL; installed globally), \"remove\", \"rename\" (name + new_name), \"list\". When the user says \"install xxx skill\" or pastes a command like \"npx skills add owner/repo -g\", extract the owner/repo and call skill.install.")}- sb.WriteString("\n\n")- sb.WriteString("## Skill Management\n")- sb.WriteString("Use the skill tool to manage reusable skills: \"save\" (create/update; provide name + SKILL.md content with YAML frontmatter ---\\nname: ...\\ndescription: ...\\n--- and markdown body), \"install\" (download & install a skill from a remote source — pass url; accepts 'owner/repo' shorthand like Tencent/WeChatReading, a full GitHub URL, a raw SKILL.md URL, or a release zip URL; installed globally), \"remove\", \"rename\" (name + new_name), \"list\". When the user says \"install xxx skill\" or pastes a command like \"npx skills add owner/repo -g\", extract the owner/repo and call skill.install.")-sb.WriteString("\n\nReply in ")sb.WriteString(util.I18nTerm(language, "_label"))sb.WriteString(".")- sb.WriteString("\n\nIn the language configured in SiYuan's appearance settings, a daily note is called: ")- sb.WriteString(util.I18nTerm(language, "dailyNote"))- sb.WriteString(". When the user asks to write or create this, use dailynote.create, not document.create.")+ if capabilities.hasModelName("dailynote") {+ sb.WriteString("\n\nIn the language configured in SiYuan's appearance settings, a daily note is called: ")+ sb.WriteString(util.I18nTerm(language, "dailyNote"))+ sb.WriteString(". When the user asks to write or create this, use dailynote.create, not document.create.")+ }return sb.String()}-func buildUserMessageContent(userMessage string, references []Reference, editorCtx *EditorContext) string {+func buildUserMessageContent(userMessage string, references []Reference, editorCtx *EditorContext,+ capabilities *capabilitySet) string {if len(references) == 0 && editorCtx == nil {return userMessage}@@ -1727,7 +1817,9 @@ func buildUserMessageContent(userMessage string, references []Reference, editorCsb.WriteString(ref.ID)sb.WriteString(")\n")}- sb.WriteString("Use the block tools to fetch their actual content before responding.\n")+ if capabilities == nil || capabilities.hasModelName("block") {+ sb.WriteString("Use the block tools to fetch their actual content before responding.\n")+ }}if editorCtx != nil {sb.WriteString("<editor_context>\n")@@ -1789,7 +1881,9 @@ func buildUserMessageContent(userMessage string, references []Reference, editorCsb.WriteString("\n")}}- sb.WriteString("Use the block tools (e.g. block with action \"get\") to fetch actual content before responding.")+ if capabilities == nil || capabilities.hasModelName("block") {+ sb.WriteString("Use the block tools (e.g. block with action \"get\") to fetch actual content before responding.")+ }sb.WriteString("\n</editor_context>")}sb.WriteString("\n</turn_context>\n\n")@@ -1797,10 +1891,10 @@ func buildUserMessageContent(userMessage string, references []Reference, editorCreturn sb.String()}-func buildInitialMessages(userMessage string, language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction) []openai.ChatCompletionMessage {+func buildInitialMessages(userMessage string, language string, references []Reference, editorCtx EditorContext, capabilities *capabilitySet) []openai.ChatCompletionMessage {return []openai.ChatCompletionMessage{- {Role: openai.ChatMessageRoleSystem, Content: buildSystemPrompt(language, pluginActions)},- {Role: openai.ChatMessageRoleUser, Content: buildUserMessageContent(userMessage, references, cloneEditorContext(editorCtx))},+ {Role: openai.ChatMessageRoleSystem, Content: buildSystemPrompt(language, capabilities)},+ {Role: openai.ChatMessageRoleUser, Content: buildUserMessageContent(userMessage, references, cloneEditorContext(editorCtx), capabilities)},}}@@ -1899,13 +1993,13 @@ func entriesToAgentMessages(entries []SessionEntry) []AgentMessage {return msgs}-func checkpointMessagesToOpenAI(checkpointMsgs []AgentMessage, language string, pluginActions []PluginAction) []openai.ChatCompletionMessage {- return checkpointMessagesToOpenAIWithSummary(checkpointMsgs, language, pluginActions, nil)+func checkpointMessagesToOpenAI(checkpointMsgs []AgentMessage, language string, capabilities *capabilitySet) []openai.ChatCompletionMessage {+ return checkpointMessagesToOpenAIWithSummary(checkpointMsgs, language, capabilities, nil)}-func checkpointMessagesToOpenAIWithSummary(checkpointMsgs []AgentMessage, language string, pluginActions []PluginAction, compaction *runtimeCompaction) []openai.ChatCompletionMessage {+func checkpointMessagesToOpenAIWithSummary(checkpointMsgs []AgentMessage, language string, capabilities *capabilitySet, compaction *runtimeCompaction) []openai.ChatCompletionMessage {msgs := []openai.ChatCompletionMessage{- {Role: openai.ChatMessageRoleSystem, Content: buildSystemPrompt(language, pluginActions)},+ {Role: openai.ChatMessageRoleSystem, Content: buildSystemPrompt(language, capabilities)},}if compaction != nil && strings.TrimSpace(compaction.Summary) != "" {msgs = append(msgs, openai.ChatCompletionMessage{@@ -1932,7 +2026,7 @@ func checkpointMessagesToOpenAIWithSummary(checkpointMsgs []AgentMessage, languacm := &checkpointMsgs[cmi]switch cm.Role {case "user":- content := buildUserMessageContent(cm.Content, cm.References, cm.EditorContext)+ content := buildUserMessageContent(cm.Content, cm.References, cm.EditorContext, capabilities)if content == "" {content = " "}diff --git a/kernel/agent/capability.go b/kernel/agent/capability.gonew file mode 100644index 0000000000..c8bfabf87d--- /dev/null+++ b/kernel/agent/capability.go@@ -0,0 +1,444 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.++package agent++import (+ "crypto/sha256"+ "fmt"+ "sort"+ "strings"+ "unicode"++ "github.com/sashabaranov/go-openai"+ "github.com/siyuan-note/siyuan/kernel/mcp/tools"+ kernelModel "github.com/siyuan-note/siyuan/kernel/model"+)++const maxCapabilityModelNameLen = 64++// FrontendCapability 描述当前浏览器实例可执行的 Agent 能力。处理函数保留在浏览器中,+// 内核只接收声明并在执行时通过 SSE 将调用分发回发起会话的实例。+type FrontendCapability struct {+ ID string `json:"id"`+ Title string `json:"title,omitempty"`+ Description string `json:"description"`+ InputSchema tools.ToolSchema `json:"inputSchema"`+ OutputSchema *tools.ToolSchema `json:"outputSchema,omitempty"`+ Source string `json:"source"`+ OwnerID string `json:"ownerId,omitempty"`+ OwnerName string `json:"ownerName,omitempty"`+ Effects *tools.ToolEffects `json:"effects,omitempty"`+ ActionEffects map[string]tools.ToolEffects `json:"actionEffects,omitempty"`+ Generation uint64 `json:"generation"`+}++type CapabilityInfo struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Title string `json:"title,omitempty"`+ Description string `json:"description"`+ Source string `json:"source"`+ OwnerID string `json:"ownerId,omitempty"`+ OwnerName string `json:"ownerName,omitempty"`+ Runtime string `json:"runtime"`+ Effects tools.ToolEffects `json:"effects,omitempty"`+ Enabled bool `json:"enabled"`+ Available bool `json:"available"`+ Actions []CapabilityActionInfo `json:"actions,omitempty"`+}++type CapabilityActionInfo struct {+ Name string `json:"name"`+ Effects tools.ToolEffects `json:"effects,omitempty"`+}++type capabilityRegistration struct {+ ID string+ ModelName string+ Title string+ Description string+ Source string+ OwnerID string+ OwnerName string+ Runtime string+ Effects tools.ToolEffects+ EffectsDeclared bool+ ActionEffects map[string]tools.ToolEffects+ Generation uint64+ Tool *tools.Tool+ Validator *tools.ToolValidator+ InputSchema tools.ToolSchema+ OutputSchema *tools.ToolSchema+ AccessContext capabilityAccessContext+}++// capabilityAccessContext 保留授权决策所需的稳定上下文,后续可在不改变调用链的前提下增加笔记本级规则。+type capabilityAccessContext struct {+ SessionID string+ NotebookID string+ DocumentID string+ Arguments map[string]any+}++type capabilityAuthorizer interface {+ Allows(id string, context capabilityAccessContext) bool+}++type configCapabilityAuthorizer struct{}++func (configCapabilityAuthorizer) Allows(id string, _ capabilityAccessContext) bool {+ if kernelModel.Conf == nil || kernelModel.Conf.AI == nil || kernelModel.Conf.AI.Agent == nil {+ return true+ }+ return kernelModel.Conf.AI.Agent.CapabilityPolicy.Allows(id)+}++var currentCapabilityAuthorizer capabilityAuthorizer = configCapabilityAuthorizer{}++type capabilityApprover interface {+ AutoApproves(id, action string, context capabilityAccessContext) bool+}++type configCapabilityApprover struct{}++func (configCapabilityApprover) AutoApproves(id, action string, _ capabilityAccessContext) bool {+ if kernelModel.Conf == nil || kernelModel.Conf.AI == nil || kernelModel.Conf.AI.Agent == nil {+ return false+ }+ return kernelModel.Conf.AI.Agent.ApprovalPolicy.AutoApproves(id, action)+}++var currentCapabilityApprover capabilityApprover = configCapabilityApprover{}++func capabilityAutoApproved(registration *capabilityRegistration, action string, args map[string]any) bool {+ if registration == nil {+ return false+ }+ accessContext := registration.AccessContext+ accessContext.Arguments = args+ return currentCapabilityApprover.AutoApproves(registration.ID, action, accessContext)+}++func (registration *capabilityRegistration) isBrowser() bool {+ return registration != nil && registration.Runtime == "browser"+}++func (registration *capabilityRegistration) browserEffectsFor(action string) (tools.ToolEffects, bool) {+ if registration == nil || !registration.isBrowser() {+ return tools.ToolEffects{}, false+ }+ if effects, ok := registration.ActionEffects[action]; ok {+ return effects, true+ }+ return registration.Effects, registration.EffectsDeclared+}++type capabilitySet struct {+ definitions []openai.Tool+ registrations map[string]*capabilityRegistration+ ids map[string]*capabilityRegistration+}++func (set *capabilitySet) registration(modelName string) *capabilityRegistration {+ if set == nil {+ return nil+ }+ return set.registrations[modelName]+}++func (set *capabilitySet) hasModelName(modelName string) bool {+ return set != nil && set.registrations[modelName] != nil+}++func filterSystemPromptByCapabilities(prompt string, set *capabilitySet) string {+ if set == nil {+ return prompt+ }+ allTools := tools.GetAllTools()+ lines := strings.Split(prompt, "\n")+ filtered := make([]string, 0, len(lines))+ for _, line := range lines {+ allowed := true+ for _, tool := range allTools {+ if set.hasModelName(tool.Name) {+ continue+ }+ if strings.Contains(line, tool.Name+".") ||+ strings.Contains(line, tool.Name+" tool") ||+ strings.Contains(line, tool.Name+" tools") ||+ strings.Contains(line, "\""+tool.Name+"\"") {+ allowed = false+ break+ }+ }+ if allowed {+ filtered = append(filtered, line)+ }+ }+ return strings.Join(filtered, "\n")+}++func capabilityIDForTool(tool *tools.Tool) string {+ if tool == nil {+ return ""+ }+ if tool.CapabilityID != "" {+ return tool.CapabilityID+ }+ source := tool.Source+ if source == "" {+ source = "native"+ }+ if tool.OwnerID != "" {+ return tools.BuildCapabilityID(source, "backend", tool.OwnerID, tool.Name)+ }+ return tools.BuildCapabilityID(source, "backend", tool.Name)+}++func capabilityAllowed(id string, context capabilityAccessContext) bool {+ return currentCapabilityAuthorizer.Allows(id, context)+}++func buildCapabilitySet(frontendCapabilities []FrontendCapability, accessContext capabilityAccessContext) (*capabilitySet, error) {+ set := &capabilitySet{+ registrations: map[string]*capabilityRegistration{},+ ids: map[string]*capabilityRegistration{},+ }+ for _, tool := range tools.GetAllTools() {+ id := capabilityIDForTool(tool)+ if id == "" || !capabilityAllowed(id, accessContext) {+ continue+ }+ registered, validator := tools.LookupToolWithValidator(tool.Name)+ if registered != tool || validator == nil {+ continue+ }+ runtime := tool.Runtime+ if runtime == "" {+ runtime = "kernel"+ }+ source := tool.Source+ if source == "" {+ source = "native"+ }+ registration := &capabilityRegistration{+ ID: id,+ ModelName: tool.Name,+ Title: tool.Title,+ Description: tool.Description,+ Source: source,+ OwnerID: tool.OwnerID,+ OwnerName: tool.OwnerName,+ Runtime: runtime,+ Tool: tool,+ Validator: validator,+ InputSchema: tool.InputSchema,+ OutputSchema: tool.OutputSchema,+ AccessContext: accessContext,+ }+ if err := set.add(registration); err != nil {+ return nil, err+ }+ }++ for _, frontend := range frontendCapabilities {+ if !validFrontendCapabilityID(frontend.ID) {+ return nil, fmt.Errorf("invalid frontend capability ID: %s", frontend.ID)+ }+ if strings.TrimSpace(frontend.Description) == "" {+ return nil, fmt.Errorf("frontend capability description is required: %s", frontend.ID)+ }+ if !capabilityAllowed(frontend.ID, accessContext) {+ continue+ }+ validationTool := &tools.Tool{+ Name: frontendCapabilityModelName(frontend.ID),+ Description: frontend.Description,+ InputSchema: frontend.InputSchema,+ OutputSchema: frontend.OutputSchema,+ }+ validator, err := tools.CompileToolValidator(validationTool)+ if err != nil {+ return nil, fmt.Errorf("invalid frontend capability [%s]: %w", frontend.ID, err)+ }+ source := "native"+ if strings.HasPrefix(frontend.ID, "plugin/frontend/") {+ source = "plugin"+ }+ effects := tools.ToolEffects{}+ if frontend.Effects != nil {+ effects = *frontend.Effects+ }+ registration := &capabilityRegistration{+ ID: frontend.ID,+ ModelName: validationTool.Name,+ Title: frontend.Title,+ Description: frontend.Description,+ Source: source,+ OwnerID: frontend.OwnerID,+ OwnerName: frontend.OwnerName,+ Runtime: "browser",+ Effects: effects,+ EffectsDeclared: frontend.Effects != nil,+ ActionEffects: frontend.ActionEffects,+ Generation: frontend.Generation,+ Validator: validator,+ InputSchema: frontend.InputSchema,+ OutputSchema: frontend.OutputSchema,+ AccessContext: accessContext,+ }+ if err := set.add(registration); err != nil {+ return nil, err+ }+ }++ sort.Slice(set.definitions, func(i, j int) bool {+ return set.definitions[i].Function.Name < set.definitions[j].Function.Name+ })+ return set, nil+}++func (set *capabilitySet) add(registration *capabilityRegistration) error {+ if set.registrations == nil {+ set.registrations = map[string]*capabilityRegistration{}+ }+ if set.ids == nil {+ set.ids = map[string]*capabilityRegistration{}+ }+ if previous := set.ids[registration.ID]; previous != nil {+ return fmt.Errorf("capability ID collision [%s]: %s and %s",+ registration.ID, previous.ModelName, registration.ModelName)+ }+ if previous := set.registrations[registration.ModelName]; previous != nil {+ return fmt.Errorf("capability model name collision [%s]: %s and %s",+ registration.ModelName, previous.ID, registration.ID)+ }+ set.ids[registration.ID] = registration+ set.registrations[registration.ModelName] = registration+ set.definitions = append(set.definitions, openai.Tool{+ Type: openai.ToolTypeFunction,+ Function: &openai.FunctionDefinition{+ Name: registration.ModelName,+ Description: registration.Description,+ Parameters: convertSchema(registration.InputSchema),+ },+ })+ return nil+}++func validFrontendCapabilityID(id string) bool {+ if len(id) > 512 {+ return false+ }+ parts := strings.Split(id, "/")+ if len(parts) == 3 {+ return parts[0] == "native" && parts[1] == "frontend" && parts[2] != ""+ }+ if len(parts) == 4 {+ return parts[0] == "plugin" && parts[1] == "frontend" && parts[2] != "" && parts[3] != ""+ }+ return false+}++func frontendCapabilityModelName(id string) string {+ var builder strings.Builder+ builder.WriteString("frontend__")+ for _, char := range id {+ if char <= unicode.MaxASCII && (unicode.IsLetter(char) || unicode.IsDigit(char) || char == '_' || char == '-') {+ builder.WriteRune(char)+ } else {+ builder.WriteByte('_')+ }+ }+ hash := sha256.Sum256([]byte(id))+ suffix := fmt.Sprintf("__%x", hash[:6])+ name := builder.String()+ if len(name) > maxCapabilityModelNameLen-len(suffix) {+ name = name[:maxCapabilityModelNameLen-len(suffix)]+ }+ return name + suffix+}++func ListBackendCapabilities() []CapabilityInfo {+ allTools := tools.GetAllTools()+ result := make([]CapabilityInfo, 0, len(allTools))+ for _, tool := range allTools {+ source := tool.Source+ if source == "" {+ source = "native"+ }+ runtime := tool.Runtime+ if runtime == "" {+ runtime = "kernel"+ }+ id := capabilityIDForTool(tool)+ actions := capabilityActionsForTool(tool)+ effects, _ := tool.EffectsFor("")+ result = append(result, CapabilityInfo{+ ID: id,+ Name: tool.Name,+ Title: tool.Title,+ Description: tool.Description,+ Source: source,+ OwnerID: tool.OwnerID,+ OwnerName: tool.OwnerName,+ Runtime: runtime,+ Effects: effects,+ Enabled: capabilityAllowed(id, capabilityAccessContext{}),+ Available: true,+ Actions: actions,+ })+ }+ sort.Slice(result, func(i, j int) bool {+ return result[i].ID < result[j].ID+ })+ return result+}++func capabilityActionsForTool(tool *tools.Tool) []CapabilityActionInfo {+ if tool == nil {+ return nil+ }+ names := map[string]bool{}+ if action, ok := tool.InputSchema.Properties["action"]; ok {+ for _, name := range action.Enum {+ if name != "" {+ names[name] = true+ }+ }+ }+ for name := range tool.ActionEffects {+ if name != "" {+ names[name] = true+ }+ }+ result := make([]CapabilityActionInfo, 0, len(names))+ for name := range names {+ effects, _ := tool.EffectsFor(name)+ result = append(result, CapabilityActionInfo{Name: name, Effects: effects})+ }+ sort.Slice(result, func(i, j int) bool { return result[i].Name < result[j].Name })+ return result+}++func capabilityStillExecutable(registration *capabilityRegistration, args map[string]any) bool {+ if registration == nil {+ return false+ }+ accessContext := registration.AccessContext+ accessContext.Arguments = args+ if !capabilityAllowed(registration.ID, accessContext) {+ return false+ }+ if registration.isBrowser() {+ return true+ }+ current, validator := tools.LookupToolWithValidator(registration.ModelName)+ return current != nil && current == registration.Tool && validator == registration.Validator+}diff --git a/kernel/agent/capability_test.go b/kernel/agent/capability_test.gonew file mode 100644index 0000000000..35e85bd84b--- /dev/null+++ b/kernel/agent/capability_test.go@@ -0,0 +1,106 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.++package agent++import (+ "testing"++ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/mcp/tools"+ kernelModel "github.com/siyuan-note/siyuan/kernel/model"+)++func TestFrontendCapabilityModelNamesAreStableAndDistinct(t *testing.T) {+ first := frontendCapabilityModelName("plugin/frontend/example/a/b")+ second := frontendCapabilityModelName("plugin/frontend/example/a_b")+ if first == second {+ t.Fatalf("different capability IDs produced the same model name: %s", first)+ }+ if first != frontendCapabilityModelName("plugin/frontend/example/a/b") {+ t.Fatal("capability model name is not stable")+ }+ if len(first) > maxCapabilityModelNameLen || len(second) > maxCapabilityModelNameLen {+ t.Fatal("capability model name exceeds the provider limit")+ }+}++func TestCapabilityPolicyControlsExposureAndExecution(t *testing.T) {+ const toolName = "test_capability_policy_tool"+ const backendID = "native/backend/test_capability_policy_tool"+ const frontendID = "native/frontend/test_capability_policy"++ originalConf := kernelModel.Conf+ kernelModel.Conf = kernelModel.NewAppConf()+ kernelModel.Conf.AI = conf.NewAI()+ kernelModel.Conf.AI.Agent.CapabilityPolicy = &conf.CapabilityPolicy{+ Default: "deny",+ Overrides: map[string]string{+ backendID: "allow",+ frontendID: "allow",+ },+ }+ t.Cleanup(func() { kernelModel.Conf = originalConf })++ tool := &tools.Tool{+ Name: toolName,+ CapabilityID: backendID,+ Description: "Test capability policy",+ InputSchema: tools.ToolSchema{Type: "object"},+ Handler: func(args map[string]any) (tools.CallToolResult, error) {+ return tools.CallToolResult{}, nil+ },+ }+ if err := tools.SetTool(toolName, tool); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { tools.RemoveTool(toolName) })++ set, err := buildCapabilitySet([]FrontendCapability{{+ ID: frontendID,+ Description: "Test browser capability",+ InputSchema: tools.ToolSchema{Type: "object"},+ Source: "native",+ Generation: 1,+ }}, capabilityAccessContext{SessionID: "test-session", NotebookID: "test-notebook"})+ if err != nil {+ t.Fatal(err)+ }+ backendRegistration := set.registration(toolName)+ if backendRegistration == nil {+ t.Fatal("allowed backend capability was not exposed")+ }+ frontendRegistration := set.registration(frontendCapabilityModelName(frontendID))+ if frontendRegistration == nil {+ t.Fatal("allowed browser capability was not exposed")+ }+ kernelModel.Conf.AI.Agent.ApprovalPolicy.Overrides[backendID] = &conf.CapabilityApproval{+ Default: "allow",+ Actions: map[string]string{"write": "confirm"},+ }+ if needsCapabilityConfirm(backendRegistration, "delete", nil, nil) {+ t.Fatal("capability auto approval was not applied")+ }+ if !needsCapabilityConfirm(backendRegistration, "write", nil, nil) {+ t.Fatal("action confirmation override was not applied")+ }++ kernelModel.Conf.AI.Agent.CapabilityPolicy.Overrides[backendID] = "deny"+ kernelModel.Conf.AI.Agent.CapabilityPolicy.Overrides[frontendID] = "deny"+ if capabilityStillExecutable(backendRegistration, nil) || capabilityStillExecutable(frontendRegistration, nil) {+ t.Fatal("disabled capability remained executable from an earlier model round")+ }++ set, err = buildCapabilitySet(nil, capabilityAccessContext{})+ if err != nil {+ t.Fatal(err)+ }+ if set.registration(toolName) != nil {+ t.Fatal("disabled backend capability remained exposed")+ }+}diff --git a/kernel/agent/compaction_test.go b/kernel/agent/compaction_test.goindex f41e324091..beb7b97316 100644--- a/kernel/agent/compaction_test.go+++ b/kernel/agent/compaction_test.go@@ -36,6 +36,15 @@ func setupCompactionAgentTest(t *testing.T) {t.Cleanup(func() { kernelModel.Conf = originalConf })}+func currentCapabilitiesForTest(t *testing.T) *capabilitySet {+ t.Helper()+ capabilities, err := buildCapabilitySet(nil, capabilityAccessContext{})+ if err != nil {+ t.Fatal(err)+ }+ return capabilities+}+func compactionTestContextLimit(t *testing.T, fullTokens, compactedBaseTokens int) int {t.Helper()targetBudget := fullTokens - 512@@ -249,7 +258,7 @@ func TestAgentChatCompactsBeforeSendingOversizedContext(t *testing.T) {}checkpoint := entriesToAgentMessages(entries)- requestTools := convertMCPToolsToOpenAI()+ requestTools := currentCapabilitiesForTest(t).definitionsfullTokens := estimateChatRequestTokens("test-model", checkpointMessagesToOpenAI(checkpoint, "English", nil), requestTools)recentTokens := estimateChatRequestTokens(@@ -342,7 +351,7 @@ func TestAgentChatRegenerateCompactionUsesTruncatedEditedHistory(t *testing.T) {regenerateCheckpoint := entriesToAgentMessages(entries[:2])regenerateCheckpoint = append(regenerateCheckpoint,newAgentUserMessage(editedTarget, "user-2", nil, EditorContext{}))- requestTools := convertMCPToolsToOpenAI()+ requestTools := currentCapabilitiesForTest(t).definitionsfullTokens := estimateChatRequestTokens("test-model", checkpointMessagesToOpenAI(regenerateCheckpoint, "English", nil), requestTools)recentTokens := estimateChatRequestTokens(@@ -435,7 +444,7 @@ func TestAgentChatRetriesOverflowAfterProactiveCompaction(t *testing.T) {t.Fatal(err)}- requestTools := convertMCPToolsToOpenAI()+ requestTools := currentCapabilitiesForTest(t).definitionsfullTokens := estimateChatRequestTokens("test-model", checkpointMessagesToOpenAI(entriesToAgentMessages(entries), "English", nil), requestTools)afterFirstTokens := estimateChatRequestTokens(diff --git a/kernel/agent/prompt_test.go b/kernel/agent/prompt_test.goindex ae1d2088f1..5627058524 100644--- a/kernel/agent/prompt_test.go+++ b/kernel/agent/prompt_test.go@@ -56,19 +56,11 @@ func TestSystemPromptDocumentsBlockReferenceSyntax(t *testing.T) {}}-func TestSystemPromptSortsPluginActions(t *testing.T) {- actions := []PluginAction{- {Name: "plugin__z__run", Description: "Run Z"},- {Name: "plugin__a__run", Description: "Run A"},- }-- forward := buildSystemPrompt("English", actions)- reversed := buildSystemPrompt("English", []PluginAction{actions[1], actions[0]})- if forward != reversed {- t.Fatal("plugin action order changed the system prompt")- }- if strings.Index(forward, actions[1].Name) > strings.Index(forward, actions[0].Name) {- t.Fatalf("plugin actions are not sorted in system prompt: %q", forward)+func TestSystemPromptOmitsUnavailableSkillInstructions(t *testing.T) {+ capabilities := &capabilitySet{registrations: map[string]*capabilityRegistration{}}+ prompt := buildSystemPrompt("English", capabilities)+ if strings.Contains(prompt, "<available_skills>") || strings.Contains(prompt, "Skill Management") {+ t.Fatalf("unavailable skill instructions leaked into system prompt: %q", prompt)}}diff --git a/kernel/agent/tools.go b/kernel/agent/tools.goindex 37e79fc012..29722b7cd1 100644--- a/kernel/agent/tools.go+++ b/kernel/agent/tools.go@@ -28,22 +28,6 @@ import (kernelModel "github.com/siyuan-note/siyuan/kernel/model")-func convertMCPToolsToOpenAI() []openai.Tool {- allTools := tools.GetAllTools()- result := make([]openai.Tool, 0, len(allTools))- for _, t := range allTools {- result = append(result, openai.Tool{- Type: openai.ToolTypeFunction,- Function: &openai.FunctionDefinition{- Name: t.Name,- Description: t.Description,- Parameters: convertSchema(t.InputSchema),- },- })- }- return result-}-type executedToolResult struct {Text stringModelAttachments []tools.ModelAttachment@@ -69,13 +53,53 @@ func validateToolCallInput(ctx context.Context, toolName string, args map[stringreturn t, validator, nil}+func validateCapabilityCall(ctx context.Context, registration *capabilityRegistration, args map[string]any) error {+ if registration == nil {+ return fmt.Errorf("capability was not exposed in this model round")+ }+ if !capabilityStillExecutable(registration, args) {+ return fmt.Errorf("capability is disabled or no longer available: %s", registration.ID)+ }+ if ctx.Err() != nil {+ return fmt.Errorf("capability execution was cancelled before it started")+ }+ if registration.Validator == nil {+ return fmt.Errorf("capability validator unavailable: %s", registration.ID)+ }+ if err := registration.Validator.ValidateInputContext(ctx, args); err != nil {+ return fmt.Errorf("invalid capability arguments: %w", err)+ }+ if !registration.isBrowser() &&+ (registration.Tool == nil || registration.Tool.ContextHandler == nil && registration.Tool.Handler == nil) {+ return fmt.Errorf("capability handler unavailable: %s", registration.ID)+ }+ return nil+}+// executeTool 执行单次工具调用。func executeTool(ctx context.Context, tc openai.ToolCall, sessionID string) executedToolResult {+ tool, validator := tools.LookupToolWithValidator(tc.Function.Name)+ if tool == nil {+ return executedToolResult{Text: "unknown tool: " + tc.Function.Name, IsError: true}+ }+ return executeCapability(ctx, tc, sessionID, &capabilityRegistration{+ ID: capabilityIDForTool(tool),+ ModelName: tool.Name,+ Source: tool.Source,+ Runtime: tool.Runtime,+ Tool: tool,+ Validator: validator,+ })+}++func executeCapability(ctx context.Context, tc openai.ToolCall, sessionID string,+ registration *capabilityRegistration) executedToolResult {args := parseToolArgs(tc.Function.Arguments)- t, validator, err := validateToolCallInput(ctx, tc.Function.Name, args)- if err != nil {+ if err := validateCapabilityCall(ctx, registration, args); err != nil {return executedToolResult{Text: err.Error(), IsError: true}}+ t := registration.Tool+ validator := registration.Validator// _sessionID 和 _toolCallID 是原生工具专用的内部字段,用于关联会话状态和实现幂等操作。// 仅注入给原生工具;MCP/插件工具的参数会原样转发给外部服务端,// 严格校验(additionalProperties:false)的服务端(如 Flomo MCP)会因这个多余字段报错。diff --git a/kernel/agent/tools_test.go b/kernel/agent/tools_test.goindex 5fb7d21253..86cdb78a0b 100644--- a/kernel/agent/tools_test.go+++ b/kernel/agent/tools_test.go@@ -21,6 +21,7 @@ import ("encoding/json""strings""testing"+ "time""github.com/sashabaranov/go-openai""github.com/siyuan-note/siyuan/kernel/mcp/tools"@@ -291,14 +292,32 @@ func TestQueryToolActionEffects(t *testing.T) {}}-func TestNativeReadOnlyToolActions(t *testing.T) {- for _, action := range []string{"open_setting", "focus_block", "open_document", "open_search"} {- if needsConfirm("frontend", action, nil) || needsLocalSnapshot("frontend", action) {- t.Errorf("built-in frontend action %q must not require confirmation or create a snapshot", action)- }+func TestBrowserCapabilityEffects(t *testing.T) {+ native := &capabilityRegistration{ID: "native/frontend/open_search", ModelName: "frontend__open_search", Source: "native", Runtime: "browser"}+ if needsCapabilityConfirm(native, "", nil, nil) || needsCapabilitySnapshot(native, "") {+ t.Fatal("built-in browser capability must not require confirmation or create a snapshot")+ }+ pluginUnknown := &capabilityRegistration{ID: "plugin/frontend/example/run", ModelName: "frontend__plugin_run", Source: "plugin", Runtime: "browser"}+ if !needsCapabilityConfirm(pluginUnknown, "", nil, nil) {+ t.Fatal("plugin browser capability with unknown effects must require confirmation")+ }+ pluginRead := &capabilityRegistration{ID: "plugin/frontend/example/read", ModelName: "frontend__plugin_read", Source: "plugin", Runtime: "browser", Effects: tools.ToolEffects{LocalRead: true}, EffectsDeclared: true}+ if needsCapabilityConfirm(pluginRead, "", nil, nil) {+ t.Fatal("plugin browser capability declared local-read-only must not require confirmation")+ }+ pluginActions := &capabilityRegistration{+ ID: "plugin/frontend/example/actions", ModelName: "frontend__plugin_actions", Source: "plugin", Runtime: "browser",+ ActionEffects: map[string]tools.ToolEffects{+ "read": {LocalRead: true},+ "write": {LocalWrite: true},+ },+ }+ if needsCapabilityConfirm(pluginActions, "read", nil, nil) {+ t.Fatal("plugin browser action with explicit read effects must not require confirmation")}- if !needsConfirm("frontend", "plugin__example__write", nil) {- t.Fatal("plugin frontend actions with unknown effects must require confirmation")+ if !needsCapabilityConfirm(pluginActions, "write", nil, nil) ||+ !needsCapabilityConfirm(pluginActions, "unknown", nil, nil) {+ t.Fatal("plugin browser write or undeclared action must require confirmation")}for _, action := range []string{"html", "preview"} {if needsConfirm("export", action, nil) || needsLocalSnapshot("export", action) {@@ -335,7 +354,7 @@ func TestConfirmSessionAcceptsResponseOnce(t *testing.T) {}}-func TestQuestionAndFrontendResultsAreAcceptedOnce(t *testing.T) {+func TestQuestionAndBrowserCapabilityResultsAreAcceptedOnce(t *testing.T) {const questionID = "test-question"questionCh := make(chan QuestionAnswer, 1)questionChannelsMu.Lock()@@ -348,16 +367,17 @@ func TestQuestionAndFrontendResultsAreAcceptedOnce(t *testing.T) {t.Fatalf("unexpected question answer: %#v", answer)}- const callID = "test-frontend-call"- frontendCh := make(chan frontendCallResult, 1)- frontendCallChannelsMu.Lock()- frontendCallChannels[callID] = frontendCh- frontendCallChannelsMu.Unlock()- if !FrontendToolResult(callID, "result", false) || FrontendToolResult(callID, "duplicate", false) {- t.Fatal("frontend result was not accepted exactly once")+ const callID = "test-browser-capability-call"+ capabilityCh := make(chan browserCapabilityResult, 1)+ browserCapabilityChannelsMu.Lock()+ browserCapabilityChannels[callID] = capabilityCh+ browserCapabilityChannelsMu.Unlock()+ if !BrowserCapabilityResult(callID, "result", nil, false, false) ||+ BrowserCapabilityResult(callID, "duplicate", nil, false, false) {+ t.Fatal("browser capability result was not accepted exactly once")}- if result := <-frontendCh; result.result != "result" || result.isError {- t.Fatalf("unexpected frontend result: %#v", result)+ if result := <-capabilityCh; result.result != "result" || result.isError {+ t.Fatalf("unexpected browser capability result: %#v", result)}}@@ -375,17 +395,60 @@ func TestWaitCompletionKeepsConcurrentlyAcceptedResults(t *testing.T) {t.Fatalf("accepted question answer was lost: %#v, accepted=%v", answer, accepted)}- const callID = "test-frontend-timeout-race"- frontendCh := make(chan frontendCallResult, 1)- frontendCallChannelsMu.Lock()- frontendCallChannels[callID] = frontendCh- frontendCallChannelsMu.Unlock()- if !FrontendToolResult(callID, "accepted", false) {- t.Fatal("frontend result was rejected")+ const callID = "test-browser-capability-timeout-race"+ capabilityCh := make(chan browserCapabilityResult, 1)+ browserCapabilityChannelsMu.Lock()+ browserCapabilityChannels[callID] = capabilityCh+ browserCapabilityChannelsMu.Unlock()+ if !BrowserCapabilityResult(callID, "accepted", nil, false, false) {+ t.Fatal("browser capability result was rejected")}- result, accepted := finishFrontendWait(callID, frontendCh)+ result, accepted := finishBrowserCapabilityWait(callID, capabilityCh)if !accepted || result.result != "accepted" || result.isError {- t.Fatalf("accepted frontend result was lost: %#v, accepted=%v", result, accepted)+ t.Fatalf("accepted browser capability result was lost: %#v, accepted=%v", result, accepted)+ }+}++func TestBrowserCapabilityValidatesStructuredOutput(t *testing.T) {+ validationTool := &tools.Tool{+ Name: "test_browser_capability_output",+ Description: "Test browser capability output",+ InputSchema: tools.ToolSchema{Type: "object"},+ OutputSchema: &tools.ToolSchema{+ Type: "object",+ Properties: map[string]tools.Property{+ "value": {Type: "string"},+ },+ Required: []string{"value"},+ },+ }+ validator, err := tools.CompileToolValidator(validationTool)+ if err != nil {+ t.Fatal(err)+ }+ registration := &capabilityRegistration{+ ID: "native/frontend/test_output",+ ModelName: validationTool.Name,+ Runtime: "browser",+ Validator: validator,+ }+ events := make(chan AgentEvent, 1)+ resultCh := make(chan executedToolResult, 1)+ go func() {+ resultCh <- handleBrowserCapability(context.Background(), openai.ToolCall{+ Function: openai.FunctionCall{Name: validationTool.Name, Arguments: `{}`},+ }, registration, events, time.Second)+ }()+ event := <-events+ if event.Type != "browser_capability_call" {+ t.Fatalf("unexpected event: %#v", event)+ }+ if !BrowserCapabilityResult(event.CallID, "", map[string]any{"value": 1}, true, false) {+ t.Fatal("browser capability result was rejected")+ }+ result := <-resultCh+ if !result.IsError || !result.ExecutionUnknown {+ t.Fatalf("invalid structured output was accepted: %#v", result)}}diff --git a/kernel/api/agent.go b/kernel/api/agent.goindex 5fa41bdda3..4e21300bd0 100644--- a/kernel/api/agent.go+++ b/kernel/api/agent.go@@ -35,18 +35,18 @@ import ()type agentChatReq struct {- SessionID string `json:"sessionID"`- UserEntryID string `json:"userEntryID"`- ContentRevision *int64 `json:"contentRevision"`- Message string `json:"message"`- BlockHTML *string `json:"blockHTML"`- Language string `json:"language"`- References []agent.Reference `json:"references"`- EditorContext agent.EditorContext `json:"editorContext"`- PluginActions []agent.PluginAction `json:"pluginActions"`- Model string `json:"model,omitempty"`- Regenerate bool `json:"regenerate"`- ReasoningEffort string `json:"reasoningEffort,omitempty"`+ SessionID string `json:"sessionID"`+ UserEntryID string `json:"userEntryID"`+ ContentRevision *int64 `json:"contentRevision"`+ Message string `json:"message"`+ BlockHTML *string `json:"blockHTML"`+ Language string `json:"language"`+ References []agent.Reference `json:"references"`+ EditorContext agent.EditorContext `json:"editorContext"`+ FrontendCapabilities []agent.FrontendCapability `json:"frontendCapabilities"`+ Model string `json:"model,omitempty"`+ Regenerate bool `json:"regenerate"`+ ReasoningEffort string `json:"reasoningEffort,omitempty"`}type runningSession struct {@@ -138,7 +138,7 @@ func agentChat(c *gin.Context) {contextLimit := agent.ResolveModelContextLimit(selectedModel.Name, selectedModel.ContextLength)imageCapabilityKey := fmt.Sprintf("%s\x00%s\x00%s\x00%s\x00%s",selectedProvider.ID, selectedModel.ID, selectedProvider.BaseURL, selectedProvider.Protocol, selectedModel.Name)- eventCh := agent.AgentChat(ctx, client, selectedModel.Name, imageCapabilityKey, contextLimit, req.SessionID, req.UserEntryID, contentRevision, req.Message, req.BlockHTML, req.Language, req.References, req.EditorContext, req.PluginActions, req.Regenerate, confirmTimeout, maxRetries, req.ReasoningEffort, requestTimeout, streamIdleTimeout)+ eventCh := agent.AgentChat(ctx, client, selectedModel.Name, imageCapabilityKey, contextLimit, req.SessionID, req.UserEntryID, contentRevision, req.Message, req.BlockHTML, req.Language, req.References, req.EditorContext, req.FrontendCapabilities, req.Regenerate, confirmTimeout, maxRetries, req.ReasoningEffort, requestTimeout, streamIdleTimeout)defer cancel()streamClosed := falsedefer func() {@@ -323,14 +323,16 @@ func agentChatQuestion(c *gin.Context) {c.JSON(http.StatusOK, ret)}-type agentFrontendResultReq struct {- CallID string `json:"callID"`- Result string `json:"result"`- IsError bool `json:"isError"`+type agentBrowserCapabilityResultReq struct {+ CallID string `json:"callID"`+ Result string `json:"result"`+ StructuredContent any `json:"structuredContent"`+ StructuredContentSet bool `json:"structuredContentSet"`+ IsError bool `json:"isError"`}-func agentChatFrontendResult(c *gin.Context) {- req := &agentFrontendResultReq{}+func agentChatBrowserCapabilityResult(c *gin.Context) {+ req := &agentBrowserCapabilityResultReq{}if err := c.ShouldBindJSON(req); err != nil {ret := gulu.Ret.NewResult()ret.Code = -1@@ -339,15 +341,21 @@ func agentChatFrontendResult(c *gin.Context) {return}ret := gulu.Ret.NewResult()- if !agent.FrontendToolResult(req.CallID, req.Result, req.IsError) {+ if !agent.BrowserCapabilityResult(req.CallID, req.Result, req.StructuredContent, req.StructuredContentSet, req.IsError) {ret.Code = -1- ret.Msg = "agent frontend tool call expired"+ ret.Msg = "agent browser capability call expired"c.JSON(http.StatusConflict, ret)return}c.JSON(http.StatusOK, ret)}+func lsAgentCapabilities(c *gin.Context) {+ ret := gulu.Ret.NewResult()+ ret.Data = agent.ListBackendCapabilities()+ c.JSON(http.StatusOK, ret)+}+type agentTitleReq struct {Message string `json:"message"`Model string `json:"model"`@@ -725,11 +733,13 @@ func writeSSE(c *gin.Context, event agent.AgentEvent) error {"questionID": event.QuestionID,"arguments": event.Arguments,})- case "frontend_tool_call":- return writeSSEEvent(c, "frontend_tool_call", map[string]any{- "callID": event.CallID,- "name": event.Name,- "arguments": event.Arguments,+ case "browser_capability_call":+ return writeSSEEvent(c, "browser_capability_call", map[string]any{+ "callID": event.CallID,+ "name": event.Name,+ "capabilityID": event.CapabilityID,+ "generation": event.Generation,+ "arguments": event.Arguments,})case "snapshot":return writeSSEEvent(c, "snapshot", map[string]string{diff --git a/kernel/api/router.go b/kernel/api/router.goindex aa97b9e9b5..210c08ad4e 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -615,7 +615,8 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/ai/agent/confirm", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, agentChatConfirm)ginServer.Handle("POST", "/api/ai/agent/setPermission", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setAgentSessionPermission)ginServer.Handle("POST", "/api/ai/agent/question", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, agentChatQuestion)- ginServer.Handle("POST", "/api/ai/agent/frontendToolResult", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, agentChatFrontendResult)+ ginServer.Handle("POST", "/api/ai/agent/browserCapabilityResult", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, agentChatBrowserCapabilityResult)+ ginServer.Handle("POST", "/api/ai/agent/lsCapabilities", model.CheckAuth, model.CheckAdminRole, lsAgentCapabilities)ginServer.Handle("POST", "/api/ai/agent/title", model.CheckAuth, model.CheckAdminRole, agentChatTitle)ginServer.Handle("POST", "/api/ai/agent/lsSessions", model.CheckAuth, model.CheckAdminRole, lsSessions)ginServer.Handle("POST", "/api/ai/agent/getSession", model.CheckAuth, model.CheckAdminRole, getSession)diff --git a/kernel/conf/ai.go b/kernel/conf/ai.goindex 1c1899b471..a7057fea10 100644--- a/kernel/conf/ai.go+++ b/kernel/conf/ai.go@@ -39,14 +39,31 @@ type AI struct {}type Agent struct {- ModelID string `json:"modelId"`- SessionTimeout int `json:"sessionTimeout"`- StreamIdleTimeout int `json:"streamIdleTimeout"`- ConfirmTimeout int `json:"confirmTimeout"`- MaxRetries int `json:"maxRetries"`- Temperature float64 `json:"temperature"`- MaxCompletionTokens int `json:"maxCompletionTokens"`- MaxToolCallRounds int `json:"maxToolCallRounds"`+ ModelID string `json:"modelId"`+ SessionTimeout int `json:"sessionTimeout"`+ StreamIdleTimeout int `json:"streamIdleTimeout"`+ ConfirmTimeout int `json:"confirmTimeout"`+ MaxRetries int `json:"maxRetries"`+ Temperature float64 `json:"temperature"`+ MaxCompletionTokens int `json:"maxCompletionTokens"`+ MaxToolCallRounds int `json:"maxToolCallRounds"`+ CapabilityPolicy *CapabilityPolicy `json:"capabilityPolicy"`+ ApprovalPolicy *ApprovalPolicy `json:"approvalPolicy"`+}++type CapabilityPolicy struct {+ Default string `json:"default"`+ Overrides map[string]string `json:"overrides"`+}++type ApprovalPolicy struct {+ Default string `json:"default"`+ Overrides map[string]*CapabilityApproval `json:"overrides"`+}++type CapabilityApproval struct {+ Default string `json:"default"`+ Actions map[string]string `json:"actions"`}// Editing holds behavior parameters used by the in-editor chat scenario. They@@ -147,7 +164,48 @@ func defaultAgent() *Agent {Temperature: 1.0,MaxCompletionTokens: 0,MaxToolCallRounds: 64,+ CapabilityPolicy: defaultCapabilityPolicy(),+ ApprovalPolicy: defaultApprovalPolicy(),+ }+}++func defaultApprovalPolicy() *ApprovalPolicy {+ return &ApprovalPolicy{+ Default: "confirm",+ Overrides: map[string]*CapabilityApproval{},+ }+}++func defaultCapabilityPolicy() *CapabilityPolicy {+ return &CapabilityPolicy{+ Default: "allow",+ Overrides: map[string]string{},+ }+}++func (policy *CapabilityPolicy) Allows(id string) bool {+ if policy == nil {+ return true+ }+ if decision := policy.Overrides[id]; decision != "" {+ return decision == "allow"+ }+ return policy.Default != "deny"+}++func (policy *ApprovalPolicy) AutoApproves(id, action string) bool {+ if policy == nil {+ return false}+ if override := policy.Overrides[id]; override != nil {+ if decision := override.Actions[action]; decision != "" {+ return decision == "allow"+ }+ if override.Default != "" {+ return override.Default == "allow"+ }+ }+ return policy.Default == "allow"}func defaultEditing() *Editing {@@ -405,6 +463,26 @@ func (ai *AI) Normalize() {if ai.Agent == nil {ai.Agent = defaultAgent()} else {+ if ai.Agent.CapabilityPolicy == nil {+ ai.Agent.CapabilityPolicy = defaultCapabilityPolicy()+ } else {+ if ai.Agent.CapabilityPolicy.Default != "deny" {+ ai.Agent.CapabilityPolicy.Default = "allow"+ }+ if ai.Agent.CapabilityPolicy.Overrides == nil {+ ai.Agent.CapabilityPolicy.Overrides = map[string]string{}+ }+ for id, decision := range ai.Agent.CapabilityPolicy.Overrides {+ if id == "" || decision != "allow" && decision != "deny" {+ delete(ai.Agent.CapabilityPolicy.Overrides, id)+ }+ }+ }+ if ai.Agent.ApprovalPolicy == nil {+ ai.Agent.ApprovalPolicy = defaultApprovalPolicy()+ } else {+ normalizeApprovalPolicy(ai.Agent.ApprovalPolicy)+ }if ai.Agent.SessionTimeout < 0 {ai.Agent.SessionTimeout = 0} else if ai.Agent.SessionTimeout > 3600 {@@ -531,6 +609,35 @@ func (ai *AI) Normalize() {}}+func normalizeApprovalPolicy(policy *ApprovalPolicy) {+ if policy.Default != "allow" {+ policy.Default = "confirm"+ }+ if policy.Overrides == nil {+ policy.Overrides = map[string]*CapabilityApproval{}+ }+ for id, override := range policy.Overrides {+ if id == "" || override == nil {+ delete(policy.Overrides, id)+ continue+ }+ if override.Default != "allow" && override.Default != "confirm" {+ override.Default = ""+ }+ if override.Actions == nil {+ override.Actions = map[string]string{}+ }+ for action, decision := range override.Actions {+ if decision != "allow" && decision != "confirm" {+ delete(override.Actions, action)+ }+ }+ if override.Default == "" && len(override.Actions) == 0 {+ delete(policy.Overrides, id)+ }+ }+}+func (ai *AI) DecryptAPIKeys() {for _, p := range ai.Providers {if p == nil || p.APIKey == "" {diff --git a/kernel/conf/ai_capability_test.go b/kernel/conf/ai_capability_test.gonew file mode 100644index 0000000000..18a49c32fa--- /dev/null+++ b/kernel/conf/ai_capability_test.go@@ -0,0 +1,78 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.++package conf++import "testing"++func TestCapabilityPolicyNormalizeAndAllows(t *testing.T) {+ ai := NewAI()+ ai.Agent.CapabilityPolicy = &CapabilityPolicy{+ Default: "invalid",+ Overrides: map[string]string{+ "native/backend/read": "deny",+ "native/backend/write": "allow",+ "native/backend/bad": "invalid",+ "": "deny",+ },+ }+ ai.Normalize()++ policy := ai.Agent.CapabilityPolicy+ if policy.Default != "allow" {+ t.Fatalf("invalid default was not normalized: %s", policy.Default)+ }+ if policy.Allows("native/backend/read") {+ t.Fatal("deny override was ignored")+ }+ if !policy.Allows("native/backend/write") || !policy.Allows("native/backend/other") {+ t.Fatal("allow decisions were ignored")+ }+ if _, exists := policy.Overrides["native/backend/bad"]; exists {+ t.Fatal("invalid override was not removed")+ }+ if _, exists := policy.Overrides[""]; exists {+ t.Fatal("empty capability ID was not removed")+ }+}++func TestApprovalPolicyNormalizeAndAutoApproves(t *testing.T) {+ ai := NewAI()+ ai.Agent.ApprovalPolicy = &ApprovalPolicy{+ Default: "invalid",+ Overrides: map[string]*CapabilityApproval{+ "native/backend/block": {+ Default: "allow",+ Actions: map[string]string{"remove": "confirm", "bad": "invalid"},+ },+ "native/backend/empty": {},+ "": {Default: "allow"},+ },+ }+ ai.Normalize()++ policy := ai.Agent.ApprovalPolicy+ if policy.Default != "confirm" {+ t.Fatalf("invalid approval default was not normalized: %s", policy.Default)+ }+ if !policy.AutoApproves("native/backend/block", "get") {+ t.Fatal("capability auto approval was ignored")+ }+ if policy.AutoApproves("native/backend/block", "remove") {+ t.Fatal("action confirmation override was ignored")+ }+ if _, exists := policy.Overrides["native/backend/empty"]; exists {+ t.Fatal("empty approval override was not removed")+ }+ if _, exists := policy.Overrides[""]; exists {+ t.Fatal("empty approval capability ID was not removed")+ }+ if _, exists := policy.Overrides["native/backend/block"].Actions["bad"]; exists {+ t.Fatal("invalid action approval was not removed")+ }+}diff --git a/kernel/mcp/client/mcp.go b/kernel/mcp/client/mcp.goindex 2775b144ad..8554af9566 100644--- a/kernel/mcp/client/mcp.go+++ b/kernel/mcp/client/mcp.go@@ -299,7 +299,11 @@ func connectOneServer(ctx context.Context, server conf.MCPServer, interactive boDescription: desc,InputSchema: convertMCPSchema(tool.InputSchema),OutputSchema: outputSchema,+ CapabilityID: tools.BuildCapabilityID("mcp", "backend", server.ID, tool.Name),Source: "mcp",+ OwnerID: server.ID,+ OwnerName: server.Name,+ Runtime: "mcp",ReadOnlyHint: readOnlyHint,EffectScope: tools.EffectScopeExternal,Handler: func(args map[string]any) (tools.CallToolResult, error) {@@ -375,13 +379,19 @@ func sanitizedServerNameCollision(server conf.MCPServer) bool {func mcpToolName(server conf.MCPServer, toolName string, collision bool) string {name := "mcp_" + sanitize(server.Name) + "_" + sanitize(toolName)- if !collision {+ if !collision && len(name) <= maxMCPToolNameLen {return name}hash := sha256.Sum256([]byte(server.ID + "\x00" + toolName))- return fmt.Sprintf("%s_%x", name, hash[:6])+ suffix := fmt.Sprintf("_%x", hash[:6])+ if len(name) > maxMCPToolNameLen-len(suffix) {+ name = name[:maxMCPToolNameLen-len(suffix)]+ }+ return name + suffix}+const maxMCPToolNameLen = 64+func registerMCPToolsForContext(ctx context.Context, registeredTools map[string]*tools.Tool) bool {generation, ok := ctx.Value(mcpGenerationContextKey{}).(uint64)mcpMu.Lock()diff --git a/kernel/mcp/client/mcp_test.go b/kernel/mcp/client/mcp_test.goindex d3cf14e4ea..bdcc5d628b 100644--- a/kernel/mcp/client/mcp_test.go+++ b/kernel/mcp/client/mcp_test.go@@ -20,6 +20,7 @@ import ("context""encoding/json""errors"+ "strings""testing""time"@@ -190,6 +191,10 @@ func TestMCPToolNameDisambiguatesSanitizedCollisions(t *testing.T) {if name := mcpToolName(serverA, "read_item", false); name != "mcp_name_with_space_read_item" {t.Fatalf("unexpected ordinary MCP tool name: %q", name)}+ longName := mcpToolName(serverA, strings.Repeat("long tool name ", 10), false)+ if len(longName) > maxMCPToolNameLen {+ t.Fatalf("MCP tool name exceeds provider limit: %d", len(longName))+ }}func TestOAuthRetryFailureRequiresAuthenticationError(t *testing.T) {diff --git a/kernel/mcp/tools/frontend.go b/kernel/mcp/tools/frontend.godeleted file mode 100644index 27c8cb9269..0000000000--- a/kernel/mcp/tools/frontend.go+++ /dev/null@@ -1,48 +0,0 @@-// SiYuan - From thought to insight, with agents-// Copyright (c) 2020-present, b3log.org-//-// This program is free software: you can redistribute it and/or modify-// it under the terms of the GNU Affero General Public License as published by-// the Free Software Foundation, either version 3 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU Affero General Public License for more details.-//-// You should have received a copy of the GNU Affero General Public License-// along with this program. If not, see <https://www.gnu.org/licenses/>.--package tools--// FrontendTool exposes UI actions (open settings, focus block, open document, open search) to-// the agent. The Handler is a fallback stub: in the agent loop, "frontend" tool calls are-// special-cased and dispatched to agent.handleFrontendTool, which streams the action to the-// browser over SSE and blocks until the browser responds. The stub exists only so that-// convertMCPToolsToOpenAI() lists this tool for the LLM.-var FrontendTool = &Tool{- Name: "frontend",- Description: "Frontend/UI actions in the SiYuan editor (run in the browser; may change what the user sees). Actions: open_setting(query?), focus_block(id), open_document(id), open_search(query?). Plugins may register more — see <plugin_actions> and invoke by full name (e.g. plugin__myplugin__myaction).",- InputSchema: ToolSchema{- Type: "object",- Properties: map[string]Property{- "action": {Type: "string", Description: "Operation"},- "id": {Type: "string", Description: "Block or document ID (for focus_block and open_document)"},- "query": {Type: "string", Description: "Search keyword (for open_setting to locate a config item, for open_search to pre-fill the search box)"},- },- Required: []string{"action"},- },- Handler: frontendHandler,-}--func init() {- register(FrontendTool)-}--func frontendHandler(args map[string]any) (CallToolResult, error) {- return CallToolResult{- Content: []ContentItem{{Type: "text", Text: "frontend actions are only available in the interactive agent chat (not via direct tool invocation)"}},- IsError: true,- }, nil-}diff --git a/kernel/mcp/tools/register.go b/kernel/mcp/tools/register.goindex 0df7320d0b..2ed40def8d 100644--- a/kernel/mcp/tools/register.go+++ b/kernel/mcp/tools/register.go@@ -150,6 +150,12 @@ func register(t *Tool) {if t.Source == "" {t.Source = "native"}+ if t.CapabilityID == "" {+ t.CapabilityID = BuildCapabilityID("native", "backend", t.Name)+ }+ if t.Runtime == "" {+ t.Runtime = "kernel"+ }attachEncryptedBoxLeaseResolver(t)if err := SetTool(t.Name, t); err != nil {panic(fmt.Sprintf("register MCP tool [%s]: %v", t.Name, err))diff --git a/kernel/mcp/tools/register_test.go b/kernel/mcp/tools/register_test.goindex f953b95e4d..8a1b63cb38 100644--- a/kernel/mcp/tools/register_test.go+++ b/kernel/mcp/tools/register_test.go@@ -27,6 +27,30 @@ func TestGetAllToolsSorted(t *testing.T) {}}+func TestBuildCapabilityIDKeepsSegmentsDistinct(t *testing.T) {+ first := BuildCapabilityID("plugin", "backend", "example/plugin", "a/b")+ second := BuildCapabilityID("plugin", "backend", "example_plugin", "a_b")+ if first == second {+ t.Fatalf("different capability segments produced the same ID: %s", first)+ }+ if first != BuildCapabilityID("plugin", "backend", "example/plugin", "a/b") {+ t.Fatal("capability ID is not stable")+ }+}++func TestToolEffectsForFallsBackToCapabilityDefault(t *testing.T) {+ tool := &Tool{ActionEffects: map[string]ToolEffects{+ "": {LocalRead: true},+ "write": {LocalWrite: true},+ }}+ if effects, ok := tool.EffectsFor("read"); !ok || !effects.LocalRead {+ t.Fatal("capability-level effects were not used as the action fallback")+ }+ if effects, ok := tool.EffectsFor("write"); !ok || !effects.LocalWrite || effects.LocalRead {+ t.Fatal("action effects did not override capability-level effects")+ }+}+func TestObserveRegistry(t *testing.T) {const name = "registry_observer_test"RemoveTool(name)diff --git a/kernel/mcp/tools/types.go b/kernel/mcp/tools/types.goindex 482de6014a..ecfc44e727 100644--- a/kernel/mcp/tools/types.go+++ b/kernel/mcp/tools/types.go@@ -19,8 +19,19 @@ package toolsimport ("context""encoding/json"+ "net/url"+ "strings")+// BuildCapabilityID 构造由来源、执行侧和提供方局部名称组成的稳定能力 ID。+func BuildCapabilityID(source, side string, segments ...string) string {+ parts := []string{url.PathEscape(source), url.PathEscape(side)}+ for _, segment := range segments {+ parts = append(parts, url.PathEscape(segment))+ }+ return strings.Join(parts, "/")+}+const (EffectScopeLocal = "local"EffectScopeExternal = "external"@@ -34,9 +45,16 @@ type Tool struct {Description string `json:"description"`InputSchema ToolSchema `json:"inputSchema"`OutputSchema *ToolSchema `json:"outputSchema,omitempty"`+ // CapabilityID 是 Agent 能力策略使用的稳定标识,不随模型函数名或显示标题变化。+ CapabilityID string `json:"capabilityId,omitempty"`// Source 标记工具来源:"native"(SiYuan 内置)、"plugin"(插件注册)、"mcp"(外部 MCP 服务)。// 用于 token 分类统计按来源拆分。空值按 "native" 处理(兼容旧调用方)。Source string `json:"source,omitempty"`+ // OwnerID 和 OwnerName 标识提供能力的插件或 MCP 服务,内置能力留空。+ OwnerID string `json:"ownerId,omitempty"`+ OwnerName string `json:"ownerName,omitempty"`+ // Runtime 描述执行位置:kernel、plugin-worker 或 mcp。+ Runtime string `json:"runtime,omitempty"`// ReadOnlyHint 仅在外部工具明确声明只读时为 true;未声明时按可能写入处理并要求确认。ReadOnlyHint bool `json:"readOnlyHint,omitempty"`// EffectScope 描述写操作影响范围,用于判断本地数据仓库快照是否具有回滚价值。@@ -61,6 +79,9 @@ func (t *Tool) EffectsFor(action string) (ToolEffects, bool) {return ToolEffects{}, false}effects, ok := t.ActionEffects[action]+ if !ok && action != "" {+ effects, ok = t.ActionEffects[""]+ }return effects, ok}diff --git a/kernel/plugin/api_agent.go b/kernel/plugin/api_agent.gonew file mode 100644index 0000000000..623baf9c50--- /dev/null+++ b/kernel/plugin/api_agent.go@@ -0,0 +1,308 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package plugin++import (+ "crypto/sha256"+ "encoding/json"+ "fmt"+ "strings"++ "github.com/dop251/goja"+ "github.com/samber/lo"+ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/mcp/tools"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// pluginCapabilityModelName 构造内核插件能力向模型暴露的函数名。+func pluginCapabilityModelName(pluginName, capabilityName string) string {+ name := fmt.Sprintf("plugin__%s__%s", util.SanitizeName(pluginName), util.SanitizeName(capabilityName))+ hash := sha256.Sum256([]byte(pluginName + "\x00" + capabilityName))+ suffix := fmt.Sprintf("__%x", hash[:6])+ if len(name) > maxCapabilityModelNameLen-len(suffix) {+ name = name[:maxCapabilityModelNameLen-len(suffix)]+ }+ return name + suffix+}++const maxCapabilityModelNameLen = 64++// injectAgent 将 siyuan.agent 注入插件 JS 沙箱。+func injectAgent(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err error) {+ defer func() {+ if r := recover(); r != nil {+ err = fmt.Errorf("injectAgent: %v", r)+ }+ }()++ agentAPI := rt.NewObject()++ // siyuan.agent.registerCapability(name, config, handler) 返回 Promise<IRegisteredCapability>。+ lo.Must0(agentAPI.Set("registerCapability", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {+ promise, resolve, reject := rt.NewPromise()++ var name string+ var title string+ var description string+ var effects *tools.ToolEffects+ var actionEffects map[string]tools.ToolEffects+ var inputSchema *tools.ToolSchema+ var outputSchema *tools.ToolSchema+ var handler goja.Callable++ argErr := func() (err error) {+ if len(call.Arguments) < 3 {+ err = fmt.Errorf("registerCapability requires 3 arguments: name, config, handler")+ return+ } else {+ if s := call.Argument(0); goja.IsString(s) {+ name = strings.TrimSpace(s.String())+ if name == "" {+ err = fmt.Errorf("capability name must not be empty")+ return+ }+ } else {+ err = fmt.Errorf("first argument must be a tool name string")+ return+ }++ if c := call.Argument(1); isJsValueNotNull(c) {+ configObj := c.ToObject(rt)+ if configObj != nil {+ if titleValue := configObj.Get("title"); goja.IsString(titleValue) {+ title = titleValue.String()+ }+ if descriptionValue := configObj.Get("description"); goja.IsString(descriptionValue) {+ description = strings.TrimSpace(descriptionValue.String())+ if description == "" {+ err = fmt.Errorf("config.description must not be empty")+ return+ }+ } else {+ err = fmt.Errorf("config.description is required and must be a string")+ return+ }+ if inputSchemaValue := configObj.Get("inputSchema"); isJsValueNotNull(inputSchemaValue) {+ if inputSchema, err = jsCapabilitySchemaToGoSchema(rt, inputSchemaValue); err != nil {+ return+ }+ } else {+ err = fmt.Errorf("config.inputSchema is required")+ return+ }+ if outputSchemaValue := configObj.Get("outputSchema"); isJsValueNotNull(outputSchemaValue) {+ if outputSchema, err = jsCapabilitySchemaToGoSchema(rt, outputSchemaValue); err != nil {+ return+ }+ }+ if effectsValue := configObj.Get("effects"); isJsValueNotNull(effectsValue) {+ if effects, err = jsCapabilityEffectsToGoEffects(rt, effectsValue); err != nil {+ return+ }+ }+ if actionEffectsValue := configObj.Get("actionEffects"); isJsValueNotNull(actionEffectsValue) {+ if actionEffects, err = jsCapabilityActionEffectsToGoEffects(rt, actionEffectsValue); err != nil {+ return+ }+ }+ }+ } else {+ err = fmt.Errorf("second argument must be a config object")+ return+ }+ if fn, ok := goja.AssertFunction(call.Argument(2)); ok {+ handler = fn+ } else {+ err = fmt.Errorf("third argument must be a handler function")+ return+ }+ return+ }+ }()++ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {+ if argErr != nil {+ err = argErr+ return+ }++ fullToolName := pluginCapabilityModelName(p.Name, name)+ declaredActionEffects := make(map[string]tools.ToolEffects, len(actionEffects)+1)+ for action, actionEffect := range actionEffects {+ declaredActionEffects[action] = actionEffect+ }+ if effects != nil {+ declaredActionEffects[""] = *effects+ }+ if len(declaredActionEffects) == 0 {+ declaredActionEffects = nil+ }++ tool := &tools.Tool{+ Name: fullToolName,+ Title: title,+ Description: description,+ InputSchema: *inputSchema,+ OutputSchema: outputSchema,+ CapabilityID: tools.BuildCapabilityID("plugin", "backend", p.Name, name),+ Source: "plugin",+ OwnerID: p.Name,+ OwnerName: p.Name,+ Runtime: "plugin-worker",+ EffectScope: tools.EffectScopeUnknown,+ ActionEffects: declaredActionEffects,+ Handler: func(args map[string]any) (tools.CallToolResult, error) {+ return p.invokeAgentCapability(handler, args)+ },+ }++ if err = p.registerAgentCapability(name, tool); err != nil {+ return+ }++ result = map[string]any{+ "id": tool.CapabilityID,+ "name": fullToolName,+ "title": title,+ "description": description,+ "effects": effects,+ "actionEffects": actionEffects,+ "inputSchema": inputSchema,+ "outputSchema": outputSchema,+ }+ return+ }, func(rt *goja.Runtime, result any, err error) {+ if lo.IsNil(err) {+ if resolveErr := resolve(result); resolveErr != nil {+ logging.LogErrorf("[plugin:%s] siyuan.agent.registerCapability resolve: %v", p.Name, resolveErr)+ }+ } else {+ if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {+ logging.LogErrorf("[plugin:%s] siyuan.agent.registerCapability reject: %v", p.Name, rejectErr)+ }+ }+ })+ if runErr != nil {+ logging.LogErrorf("[plugin:%s] siyuan.agent.registerCapability worker run: %v", p.Name, runErr)+ if rejectErr := reject(rt.NewGoError(runErr)); rejectErr != nil {+ logging.LogErrorf("[plugin:%s] siyuan.agent.registerCapability reject on run error: %v", p.Name, rejectErr)+ }+ }++ return rt.ToValue(promise)+ })))++ // siyuan.agent.unregisterCapability(name) 返回 Promise<void>。+ lo.Must0(agentAPI.Set("unregisterCapability", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {+ promise, resolve, reject := rt.NewPromise()++ var argErr error+ var toolName string++ if len(call.Arguments) < 1 {+ argErr = fmt.Errorf("unregisterCapability requires 1 argument: name")+ } else if s := call.Argument(0); goja.IsString(s) {+ toolName = s.String()+ } else {+ argErr = fmt.Errorf("first argument must be a tool name string")+ }++ if argErr != nil {+ _ = reject(rt.NewGoError(argErr))+ return rt.ToValue(promise)+ }++ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {+ p.unregisterAgentCapability(toolName)+ return+ }, func(workerRT *goja.Runtime, result any, err error) {+ if lo.IsNil(err) {+ if resolveErr := resolve(result); resolveErr != nil {+ logging.LogErrorf("[plugin:%s] siyuan.agent.unregisterCapability resolve: %v", p.Name, resolveErr)+ }+ } else {+ if rejectErr := reject(workerRT.NewGoError(err)); rejectErr != nil {+ logging.LogErrorf("[plugin:%s] siyuan.agent.unregisterCapability reject: %v", p.Name, rejectErr)+ }+ }+ })+ if runErr != nil {+ logging.LogErrorf("[plugin:%s] siyuan.agent.unregisterCapability worker run: %v", p.Name, runErr)+ if rejectErr := reject(rt.NewGoError(runErr)); rejectErr != nil {+ logging.LogErrorf("[plugin:%s] siyuan.agent.unregisterCapability reject on run error: %v", p.Name, rejectErr)+ }+ }++ return rt.ToValue(promise)+ })))++ lo.Must0(ObjectFreeze(rt, agentAPI))+ lo.Must0(siyuan.Set("agent", agentAPI))+ return+}++// jsCapabilitySchemaToGoSchema 将 JavaScript 能力 Schema 转换为 Go ToolSchema。+func jsCapabilitySchemaToGoSchema(rt *goja.Runtime, value goja.Value) (toolSchema *tools.ToolSchema, err error) {+ schemaJson, marshalErr := value.ToObject(rt).MarshalJSON()+ if marshalErr != nil {+ err = fmt.Errorf("failed to serialize inputSchema: %v", marshalErr)+ return+ }++ schema := &tools.ToolSchema{}+ unmarshalErr := json.Unmarshal(schemaJson, schema)+ if unmarshalErr != nil {+ err = fmt.Errorf("invalid json schema: %v", unmarshalErr)+ return+ }++ toolSchema = schema+ return+}++func jsCapabilityEffectsToGoEffects(rt *goja.Runtime, value goja.Value) (*tools.ToolEffects, error) {+ effects := &tools.ToolEffects{}+ if err := unmarshalCapabilityJSON(rt, value, effects, "effects"); err != nil {+ return nil, err+ }+ return effects, nil+}++func jsCapabilityActionEffectsToGoEffects(rt *goja.Runtime, value goja.Value) (map[string]tools.ToolEffects, error) {+ actionEffects := map[string]tools.ToolEffects{}+ if err := unmarshalCapabilityJSON(rt, value, &actionEffects, "actionEffects"); err != nil {+ return nil, err+ }+ for action := range actionEffects {+ if strings.TrimSpace(action) == "" {+ return nil, fmt.Errorf("config.actionEffects contains an empty action")+ }+ }+ return actionEffects, nil+}++func unmarshalCapabilityJSON(rt *goja.Runtime, value goja.Value, target any, field string) error {+ jsonValue, err := value.ToObject(rt).MarshalJSON()+ if err != nil {+ return fmt.Errorf("failed to serialize config.%s: %v", field, err)+ }+ if err = json.Unmarshal(jsonValue, target); err != nil {+ return fmt.Errorf("invalid config.%s: %v", field, err)+ }+ return nil+}diff --git a/kernel/plugin/api_agent_test.go b/kernel/plugin/api_agent_test.gonew file mode 100644index 0000000000..12f5730e73--- /dev/null+++ b/kernel/plugin/api_agent_test.go@@ -0,0 +1,91 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package plugin++import (+ "testing"++ "github.com/dop251/goja"+ "github.com/dop251/goja_nodejs/eventloop"+ "github.com/siyuan-note/siyuan/kernel/mcp/tools"+ "github.com/siyuan-note/siyuan/kernel/model"+)++func TestRegisterAgentCapabilityEffects(t *testing.T) {+ p := &KernelPlugin{Petal: &model.Petal{Name: "test-agent-capability-effects"}}+ loop := eventloop.NewEventLoop()+ p.worker.Start(loop)+ t.Cleanup(p.Clear)++ var scriptErr error+ loop.Run(func(rt *goja.Runtime) {+ siyuan := rt.NewObject()+ if err := injectAgent(p, rt, siyuan); err != nil {+ scriptErr = err+ return+ }+ if err := rt.Set("siyuan", siyuan); err != nil {+ scriptErr = err+ return+ }+ _, scriptErr = rt.RunString(`+ siyuan.agent.registerCapability("default", {+ description: "Default effects",+ inputSchema: {type: "object"},+ effects: {localRead: true}+ }, (input) => input);+ siyuan.agent.registerCapability("actions", {+ description: "Action effects",+ inputSchema: {type: "object", properties: {action: {type: "string", enum: ["read", "write"]}}},+ actionEffects: {read: {localRead: true}, write: {localWrite: true}}+ }, (input) => input);+ `)+ })+ if scriptErr != nil {+ t.Fatalf("register Agent capabilities failed: %v", scriptErr)+ }++ defaultTool := tools.GetTool(pluginCapabilityModelName(p.Name, "default"))+ if defaultTool == nil {+ t.Fatal("capability with default effects was not registered")+ }+ if effects, ok := defaultTool.EffectsFor(""); !ok || !effects.LocalRead {+ t.Fatal("capability-level effects were not registered")+ }++ actionTool := tools.GetTool(pluginCapabilityModelName(p.Name, "actions"))+ if actionTool == nil {+ t.Fatal("capability with action effects was not registered")+ }+ if effects, ok := actionTool.EffectsFor("write"); !ok || !effects.LocalWrite {+ t.Fatal("action effects were not registered")+ }+}++func TestPluginCapabilityModelNameIsStableAndDistinct(t *testing.T) {+ first := pluginCapabilityModelName("example/plugin", "a/b")+ second := pluginCapabilityModelName("example_plugin", "a_b")+ if first == second {+ t.Fatalf("different plugin capabilities produced the same model name: %s", first)+ }+ if first != pluginCapabilityModelName("example/plugin", "a/b") {+ t.Fatal("plugin capability model name is not stable")+ }+ if len(first) > maxCapabilityModelNameLen || len(second) > maxCapabilityModelNameLen {+ t.Fatal("plugin capability model name exceeds the provider limit")+ }+}diff --git a/kernel/plugin/api_mcp.go b/kernel/plugin/api_mcp.godeleted file mode 100644index c01384a46f..0000000000--- a/kernel/plugin/api_mcp.go+++ /dev/null@@ -1,239 +0,0 @@-// SiYuan - From thought to insight, with agents-// Copyright (c) 2020-present, b3log.org-//-// This program is free software: you can redistribute it and/or modify-// it under the terms of the GNU Affero General Public License as published by-// the Free Software Foundation, either version 3 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU Affero General Public License for more details.-//-// You should have received a copy of the GNU Affero General Public License-// along with this program. If not, see <https://www.gnu.org/licenses/>.--package plugin--import (- "encoding/json"- "fmt"-- "github.com/dop251/goja"- "github.com/samber/lo"- "github.com/siyuan-note/logging"- "github.com/siyuan-note/siyuan/kernel/mcp/tools"- "github.com/siyuan-note/siyuan/kernel/util"-)--// pluginToolName builds the fully-qualified MCP tool name for a plugin-local tool name.-// Pattern: plugin__<sanitized-plugin>__<sanitized-tool>-func pluginToolName(pluginName, toolName string) string {- return fmt.Sprintf("plugin__%s__%s", util.SanitizeName(pluginName), util.SanitizeName(toolName))-}--// injectMcp adds siyuan.mcp to the plugin JS sandbox.-func injectMcp(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err error) {- defer func() {- if r := recover(); r != nil {- err = fmt.Errorf("injectMcp: %v", r)- }- }()-- mcp := rt.NewObject()-- // siyuan.mcp.registerTool(name, config, handler) → Promise<IRegisteredTool>- lo.Must0(mcp.Set("registerTool", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {- promise, resolve, reject := rt.NewPromise()-- var name string- var title string- var description string- var readOnlyHint bool- var inputSchema *tools.ToolSchema- var outputSchema *tools.ToolSchema- var handler goja.Callable-- argErr := func() (err error) {- if len(call.Arguments) < 3 {- err = fmt.Errorf("registerTool requires 3 arguments: name, config, handler")- return- } else {- if s := call.Argument(0); goja.IsString(s) {- name = s.String()- } else {- err = fmt.Errorf("first argument must be a tool name string")- return- }-- if c := call.Argument(1); isJsValueNotNull(c) {- configObj := c.ToObject(rt)- if configObj != nil {- if titleValue := configObj.Get("title"); goja.IsString(titleValue) {- title = titleValue.String()- }- if descriptionValue := configObj.Get("description"); goja.IsString(descriptionValue) {- description = descriptionValue.String()- } else {- err = fmt.Errorf("config.description is required and must be a string")- return- }- if inputSchemaValue := configObj.Get("inputSchema"); isJsValueNotNull(inputSchemaValue) {- if inputSchema, err = jsSchemaToGoSchema(rt, inputSchemaValue); err != nil {- return- }- } else {- err = fmt.Errorf("config.inputSchema is required")- return- }- if outputSchemaValue := configObj.Get("outputSchema"); isJsValueNotNull(outputSchemaValue) {- if outputSchema, err = jsSchemaToGoSchema(rt, outputSchemaValue); err != nil {- return- }- }- if readOnlyValue := configObj.Get("readOnly"); isJsValueNotNull(readOnlyValue) {- var ok bool- if readOnlyHint, ok = readOnlyValue.Export().(bool); !ok {- err = fmt.Errorf("config.readOnly must be a boolean")- return- }- }- }- } else {- err = fmt.Errorf("second argument must be a config object")- return- }- if fn, ok := goja.AssertFunction(call.Argument(2)); ok {- handler = fn- } else {- err = fmt.Errorf("third argument must be a handler function")- return- }- return- }- }()-- runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {- if argErr != nil {- err = argErr- return- }-- fullToolName := pluginToolName(p.Name, name)-- tool := &tools.Tool{- Name: fullToolName,- Title: title,- Description: description,- InputSchema: *inputSchema,- OutputSchema: outputSchema,- Source: "plugin",- ReadOnlyHint: readOnlyHint,- EffectScope: tools.EffectScopeUnknown,- Handler: func(args map[string]any) (tools.CallToolResult, error) {- return p.invokeMcpTool(handler, args)- },- }-- if err = p.registerMcpTool(name, tool); err != nil {- return- }-- result = map[string]any{- "name": fullToolName,- "title": title,- "description": description,- "readOnly": readOnlyHint,- "inputSchema": inputSchema,- "outputSchema": outputSchema,- }- return- }, func(rt *goja.Runtime, result any, err error) {- if lo.IsNil(err) {- if resolveErr := resolve(result); resolveErr != nil {- logging.LogErrorf("[plugin:%s] siyuan.mcp.registerTool resolve: %v", p.Name, resolveErr)- }- } else {- if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {- logging.LogErrorf("[plugin:%s] siyuan.mcp.registerTool reject: %v", p.Name, rejectErr)- }- }- })- if runErr != nil {- logging.LogErrorf("[plugin:%s] siyuan.mcp.registerTool worker run: %v", p.Name, runErr)- if rejectErr := reject(rt.NewGoError(runErr)); rejectErr != nil {- logging.LogErrorf("[plugin:%s] siyuan.mcp.registerTool reject on run error: %v", p.Name, rejectErr)- }- }-- return rt.ToValue(promise)- })))-- // siyuan.mcp.unregisterTool(name) → Promise<void>- lo.Must0(mcp.Set("unregisterTool", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {- promise, resolve, reject := rt.NewPromise()-- var argErr error- var toolName string-- if len(call.Arguments) < 1 {- argErr = fmt.Errorf("unregisterTool requires 1 argument: name")- } else if s := call.Argument(0); goja.IsString(s) {- toolName = s.String()- } else {- argErr = fmt.Errorf("first argument must be a tool name string")- }-- if argErr != nil {- _ = reject(rt.NewGoError(argErr))- return rt.ToValue(promise)- }-- runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {- p.unregisterMcpTool(toolName)- return- }, func(workerRT *goja.Runtime, result any, err error) {- if lo.IsNil(err) {- if resolveErr := resolve(result); resolveErr != nil {- logging.LogErrorf("[plugin:%s] siyuan.mcp.unregisterTool resolve: %v", p.Name, resolveErr)- }- } else {- if rejectErr := reject(workerRT.NewGoError(err)); rejectErr != nil {- logging.LogErrorf("[plugin:%s] siyuan.mcp.unregisterTool reject: %v", p.Name, rejectErr)- }- }- })- if runErr != nil {- logging.LogErrorf("[plugin:%s] siyuan.mcp.unregisterTool worker run: %v", p.Name, runErr)- if rejectErr := reject(rt.NewGoError(runErr)); rejectErr != nil {- logging.LogErrorf("[plugin:%s] siyuan.mcp.unregisterTool reject on run error: %v", p.Name, rejectErr)- }- }-- return rt.ToValue(promise)- })))-- lo.Must0(ObjectFreeze(rt, mcp))- lo.Must0(siyuan.Set("mcp", mcp))- return-}--// jsSchemaToGoSchema converts a JavaScript value representing a tool schema into a Go ToolSchema struct.-func jsSchemaToGoSchema(rt *goja.Runtime, value goja.Value) (toolSchema *tools.ToolSchema, err error) {- schemaJson, marshalErr := value.ToObject(rt).MarshalJSON()- if marshalErr != nil {- err = fmt.Errorf("failed to serialize inputSchema: %v", marshalErr)- return- }-- schema := &tools.ToolSchema{}- unmarshalErr := json.Unmarshal(schemaJson, schema)- if unmarshalErr != nil {- err = fmt.Errorf("invalid json schema: %v", unmarshalErr)- return- }-- toolSchema = schema- return-}diff --git a/kernel/plugin/api_mcp_test.go b/kernel/plugin/api_mcp_test.godeleted file mode 100644index d64fa2d54f..0000000000--- a/kernel/plugin/api_mcp_test.go+++ /dev/null@@ -1,76 +0,0 @@-// SiYuan - From thought to insight, with agents-// Copyright (c) 2020-present, b3log.org-//-// This program is free software: you can redistribute it and/or modify-// it under the terms of the GNU Affero General Public License as published by-// the Free Software Foundation, either version 3 of the License, or-// (at your option) any later version.-//-// This program is distributed in the hope that it will be useful,-// but WITHOUT ANY WARRANTY; without even the implied warranty of-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the-// GNU Affero General Public License for more details.-//-// You should have received a copy of the GNU Affero General Public License-// along with this program. If not, see <https://www.gnu.org/licenses/>.--package plugin--import (- "testing"-- "github.com/dop251/goja"- "github.com/dop251/goja_nodejs/eventloop"- "github.com/siyuan-note/siyuan/kernel/mcp/tools"- "github.com/siyuan-note/siyuan/kernel/model"-)--func TestRegisterMcpToolOptionalReadOnly(t *testing.T) {- p := &KernelPlugin{Petal: &model.Petal{Name: "test-plugin-optional-read-only"}}- loop := eventloop.NewEventLoop()- p.worker.Start(loop)- t.Cleanup(p.Clear)-- var scriptErr error- loop.Run(func(rt *goja.Runtime) {- siyuan := rt.NewObject()- if err := injectMcp(p, rt, siyuan); err != nil {- scriptErr = err- return- }- if err := rt.Set("siyuan", siyuan); err != nil {- scriptErr = err- return- }- _, scriptErr = rt.RunString(`- siyuan.mcp.registerTool("default", {- description: "Default mutability",- inputSchema: {type: "object"}- }, (input) => input);- siyuan.mcp.registerTool("read-only", {- description: "Read-only tool",- inputSchema: {type: "object"},- readOnly: true- }, (input) => input);- `)- })- if scriptErr != nil {- t.Fatalf("register MCP tools failed: %v", scriptErr)- }-- defaultTool := tools.GetTool(pluginToolName(p.Name, "default"))- if defaultTool == nil {- t.Fatal("tool without readOnly was not registered")- }- if defaultTool.ReadOnlyHint {- t.Fatal("tool without readOnly must default to writable")- }-- readOnlyTool := tools.GetTool(pluginToolName(p.Name, "read-only"))- if readOnlyTool == nil {- t.Fatal("tool with readOnly was not registered")- }- if !readOnlyTool.ReadOnlyHint {- t.Fatal("tool with readOnly=true must be marked read-only")- }-}diff --git a/kernel/plugin/plugin.go b/kernel/plugin/plugin.goindex ca6526c93e..7c0180bd9c 100644--- a/kernel/plugin/plugin.go+++ b/kernel/plugin/plugin.go@@ -113,8 +113,8 @@ type KernelPlugin struct {bus EventBus.Bus // Event bus for plugin events and RPC request/response dispatch- rpcMethods sync.Map // string -> *RpcMethod, registered JSON-RPC methods- mcpTools sync.Map // string -> *tools.Tool, fully-qualified MCP tool names registered by this plugin+ rpcMethods sync.Map // string -> *RpcMethod, registered JSON-RPC methods+ agentCapabilities sync.Map // string -> *tools.Tool, Agent capabilities registered by this pluginsocketsMu sync.RWMutex // mutex for gwsSockets mapsockets map[*gws.Conn]bool // tracked gws WebSocket connections (true: RPC server, false: regular)@@ -162,18 +162,17 @@ func (p *KernelPlugin) State() PluginState {return PluginState(p.state.Load())}-// Clear removes all registered MCP tools and RPC methods for this plugin.-// Called on plugin stop to prevent residue in global registries.+// Clear 移除插件注册的所有 Agent 能力和 RPC 方法,避免插件停止后在全局注册表中残留。func (p *KernelPlugin) Clear() {p.rpcMethods.Clear()- p.mcpTools.Range(func(_, value any) bool {+ p.agentCapabilities.Range(func(_, value any) bool {if tool, ok := value.(*tools.Tool); ok {- tools.RemoveTool(tool.Name)+ tools.RemoveToolIf(tool.Name, tool)}return true})- p.mcpTools.Clear()+ p.agentCapabilities.Clear()}// updateState updates the plugin state atomically and pushes the new state to the frontend via util.PushKernelPluginState.@@ -372,27 +371,27 @@ func (p *KernelPlugin) unbindRpcMethod(name string) error {return nil}-// registerMcpTool registers a tool to the global MCP registry with a plugin-specific prefix, and tracks it for cleanup on plugin stop.-func (p *KernelPlugin) registerMcpTool(name string, tool *tools.Tool) error {+// registerAgentCapability 在共享注册表中注册能力,并跟踪该能力以便插件停止时清理。+func (p *KernelPlugin) registerAgentCapability(name string, tool *tools.Tool) error {if err := tools.SetTool(tool.Name, tool); err != nil {return err}- p.mcpTools.Store(name, tool)+ p.agentCapabilities.Store(name, tool)return nil}-// unregisterMcpTool removes a tool from the global MCP registry and the plugin's tracking map.-func (p *KernelPlugin) unregisterMcpTool(name string) error {- if value, loaded := p.mcpTools.LoadAndDelete(name); loaded {+// unregisterAgentCapability 从共享注册表和插件跟踪表中移除能力。+func (p *KernelPlugin) unregisterAgentCapability(name string) error {+ if value, loaded := p.agentCapabilities.LoadAndDelete(name); loaded {if tool, ok := value.(*tools.Tool); ok {- tools.RemoveTool(tool.Name)+ tools.RemoveToolIf(tool.Name, tool)}}return nil}-// invokeMcpTool calls a JS handler registered via siyuan.mcp.registerTool and returns the CallToolResult.-func (p *KernelPlugin) invokeMcpTool(handler goja.Callable, args map[string]any) (tools.CallToolResult, error) {+// invokeAgentCapability 调用通过 siyuan.agent.registerCapability 注册的 JS 处理函数并返回结果。+func (p *KernelPlugin) invokeAgentCapability(handler goja.Callable, args map[string]any) (tools.CallToolResult, error) {if p.State() != PluginStateRunning {return tools.CallToolResult{IsError: true,diff --git a/kernel/plugin/sandbox.go b/kernel/plugin/sandbox.goindex f174486414..edaa6599c1 100644--- a/kernel/plugin/sandbox.go+++ b/kernel/plugin/sandbox.go@@ -109,7 +109,7 @@ func EnableSiyuanModule(p *KernelPlugin, rt *goja.Runtime) (err error) {lo.Must0(injectLogger(p, rt, siyuan))lo.Must0(injectStorage(p, rt, siyuan))lo.Must0(injectRpc(p, rt, siyuan))- lo.Must0(injectMcp(p, rt, siyuan))+ lo.Must0(injectAgent(p, rt, siyuan))lo.Must0(injectClient(p, rt, siyuan))lo.Must0(injectServer(p, rt, siyuan))lo.Must0(injectSecretsVars(p, rt, siyuan))