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: AI Agent https://github.com/siyuan-note/siyuan/issues/17797
Danield98767f7a3b4
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 2c63d73c5d..c8939a2a17 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,16 @@{+ "tokenUsage": "استخدام السياق",+ "tokenCatSystem": "موجه النظام",+ "tokenCatSkills": "المهارات",+ "tokenCatMessages": "الرسائل",+ "tokenCatNativeToolsDef": "تعريفات الأدوات الأصلية",+ "tokenCatPluginToolsDef": "تعريفات أدوات الإضافات",+ "tokenCatMcpToolsDef": "تعريفات أدوات MCP",+ "tokenCatNativeTool": "استدعاءات الأدوات الأصلية",+ "tokenCatPluginTool": "استدعاءات أدوات الإضافات",+ "tokenCatMcpTool": "استدعاءات أدوات MCP",+ "tokenCatOther": "أخرى",+ "tokenCatCached": "زيابات ذاكرة التخزين المؤقت","agentNoModel": "لم يتم تكوين أي نموذج","agentNoModelTip": "يرجى أولاً تكوين مزود ونموذج في الإعدادات - الذكاء الاصطناعي، ثم الدردشة مع الوكيل.","dragTip2Heading": "تحويل إلى عنوان",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 1edb83e952..25508735dc 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,16 @@{+ "tokenUsage": "Kontextnutzung",+ "tokenCatSystem": "Systemaufforderung",+ "tokenCatSkills": "Fähigkeiten",+ "tokenCatMessages": "Nachrichten",+ "tokenCatNativeToolsDef": "Native Tool-Defs",+ "tokenCatPluginToolsDef": "Plugin Tool-Defs",+ "tokenCatMcpToolsDef": "MCP Tool-Defs",+ "tokenCatNativeTool": "Native Tool-Aufrufe",+ "tokenCatPluginTool": "Plugin Tool-Aufrufe",+ "tokenCatMcpTool": "MCP Tool-Aufrufe",+ "tokenCatOther": "Sonstige",+ "tokenCatCached": "Cache-Treffer","agentNoModel": "Kein Modell konfiguriert","agentNoModelTip": "Bitte konfigurieren Sie zuerst einen Anbieter und ein Modell unter Einstellungen - KI, und chatten Sie dann mit dem Agenten.","dragTip2Heading": "In Überschrift umwandeln",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 07fd16cd99..21f7738ee9 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,16 @@{+ "tokenUsage": "Context Usage",+ "tokenCatSystem": "System Prompt",+ "tokenCatSkills": "Skills",+ "tokenCatMessages": "Messages",+ "tokenCatNativeToolsDef": "Native Tool Defs",+ "tokenCatPluginToolsDef": "Plugin Tool Defs",+ "tokenCatMcpToolsDef": "MCP Tool Defs",+ "tokenCatNativeTool": "Native Tool Calls",+ "tokenCatPluginTool": "Plugin Tool Calls",+ "tokenCatMcpTool": "MCP Tool Calls",+ "tokenCatOther": "Other",+ "tokenCatCached": "Cache Hits","agentNoModel": "No model configured","agentNoModelTip": "Please configure a provider and model in Settings - AI first, then chat with the agent.","dragTip2Heading": "Convert to heading",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 345d3f37d2..57703242cc 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,16 @@{+ "tokenUsage": "Uso de contexto",+ "tokenCatSystem": "Indicación del sistema",+ "tokenCatSkills": "Habilidades",+ "tokenCatMessages": "Mensajes",+ "tokenCatNativeToolsDef": "Defs. herramientas nativas",+ "tokenCatPluginToolsDef": "Defs. herramientas plugin",+ "tokenCatMcpToolsDef": "Defs. herramientas MCP",+ "tokenCatNativeTool": "Llamadas herramientas nativas",+ "tokenCatPluginTool": "Llamadas herramientas plugin",+ "tokenCatMcpTool": "Llamadas herramientas MCP",+ "tokenCatOther": "Otros",+ "tokenCatCached": "Aciertos caché","agentNoModel": "Sin modelo configurado","agentNoModelTip": "Configure primero un proveedor y un modelo en Ajustes - IA antes de chatear con el agente.","dragTip2Heading": "Convertir en encabezado",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex aefd7b1f63..0a36059c55 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,16 @@{+ "tokenUsage": "Usage du contexte",+ "tokenCatSystem": "Invite système",+ "tokenCatSkills": "Compétences",+ "tokenCatMessages": "Messages",+ "tokenCatNativeToolsDef": "Déf. outils natifs",+ "tokenCatPluginToolsDef": "Déf. outils plugin",+ "tokenCatMcpToolsDef": "Déf. outils MCP",+ "tokenCatNativeTool": "Appels outils natifs",+ "tokenCatPluginTool": "Appels outils plugin",+ "tokenCatMcpTool": "Appels outils MCP",+ "tokenCatOther": "Autre",+ "tokenCatCached": "Cache atteint","agentNoModel": "Aucun modèle configuré","agentNoModelTip": "Veuillez d'abord configurer un fournisseur et un modèle dans Paramètres - IA, puis discutez avec l'agent.","dragTip2Heading": "Convertir en titre",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex bdd6c6aba2..6299fa0a24 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,16 @@{+ "tokenUsage": "שימוש הקשר",+ "tokenCatSystem": "בקשת מערכת",+ "tokenCatSkills": "מיומנויות",+ "tokenCatMessages": "הודעות",+ "tokenCatNativeToolsDef": "הגדרות כלים מובנים",+ "tokenCatPluginToolsDef": "הגדרות כלים תוספים",+ "tokenCatMcpToolsDef": "הגדרות כלים MCP",+ "tokenCatNativeTool": "קריאות כלים מובנים",+ "tokenCatPluginTool": "קריאות כלים תוספים",+ "tokenCatMcpTool": "קריאות כלים MCP",+ "tokenCatOther": "אחר",+ "tokenCatCached": "פגיעות מטמון","agentNoModel": "לא מוגדר מודל","agentNoModelTip": "תחילה הגדר ספק ומודל בהגדרות - בינה מלאכותית, ולאחר מכן שוחח עם הסוכן.","dragTip2Heading": "הפוך לכותרת",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 9e551ad592..737d537493 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,16 @@{+ "tokenUsage": "संदर्भ उपयोग",+ "tokenCatSystem": "सिस्टम प्रॉम्प्ट",+ "tokenCatSkills": "कौशल",+ "tokenCatMessages": "संदेश",+ "tokenCatNativeToolsDef": "मूल टूल परिभाषाएं",+ "tokenCatPluginToolsDef": "प्लगइन टूल परिभाषाएं",+ "tokenCatMcpToolsDef": "MCP टूल परिभाषाएं",+ "tokenCatNativeTool": "मूल टूल कॉल",+ "tokenCatPluginTool": "प्लगइन टूल कॉल",+ "tokenCatMcpTool": "MCP टूल कॉल",+ "tokenCatOther": "अन्य",+ "tokenCatCached": "कैश हिट","agentNoModel": "कोई मॉडल कॉन्फ़िगर नहीं किया गया","agentNoModelTip": "कृपया पहले सेटिंग्स - एआई में प्रदाता और मॉडल कॉन्फ़िगर करें, फिर एजेंट से चैट करें।","dragTip2Heading": "शीर्षक में बदलें",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 13a62ee1ae..ae37bd2425 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,16 @@{+ "tokenUsage": "Penggunaan konteks",+ "tokenCatSystem": "Prompt sistem",+ "tokenCatSkills": "Keterampilan",+ "tokenCatMessages": "Pesan",+ "tokenCatNativeToolsDef": "Def. alat asli",+ "tokenCatPluginToolsDef": "Def. alat plugin",+ "tokenCatMcpToolsDef": "Def. alat MCP",+ "tokenCatNativeTool": "Panggilan alat asli",+ "tokenCatPluginTool": "Panggilan alat plugin",+ "tokenCatMcpTool": "Panggilan alat MCP",+ "tokenCatOther": "Lainnya",+ "tokenCatCached": "Cache hits","agentNoModel": "Tidak ada model yang dikonfigurasi","agentNoModelTip": "Silakan konfigurasikan penyedia dan model di Pengaturan - AI terlebih dahulu, lalu ngobrol dengan agen.","dragTip2Heading": "Ubah menjadi judul",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 6e494ffb41..06e531c761 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,16 @@{+ "tokenUsage": "Utilizzo contesto",+ "tokenCatSystem": "Prompt di sistema",+ "tokenCatSkills": "Competenze",+ "tokenCatMessages": "Messaggi",+ "tokenCatNativeToolsDef": "Def. strumenti nativi",+ "tokenCatPluginToolsDef": "Def. strumenti plugin",+ "tokenCatMcpToolsDef": "Def. strumenti MCP",+ "tokenCatNativeTool": "Chiamate strumenti nativi",+ "tokenCatPluginTool": "Chiamate strumenti plugin",+ "tokenCatMcpTool": "Chiamate strumenti MCP",+ "tokenCatOther": "Altro",+ "tokenCatCached": "Riscontri cache","agentNoModel": "Nessun modello configurato","agentNoModelTip": "Configura prima un provider e un modello in Impostazioni - IA, quindi conversa con l'agente.","dragTip2Heading": "Converti in intestazione",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 4cfcc7d77c..868ffc44e5 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,16 @@{+ "tokenUsage": "コンテキスト使用量",+ "tokenCatSystem": "システムプロンプト",+ "tokenCatSkills": "スキル",+ "tokenCatMessages": "メッセージ",+ "tokenCatNativeToolsDef": "ネイティブツール定義",+ "tokenCatPluginToolsDef": "プラグインツール定義",+ "tokenCatMcpToolsDef": "MCP ツール定義",+ "tokenCatNativeTool": "ネイティブツール呼び出し",+ "tokenCatPluginTool": "プラグインツール呼び出し",+ "tokenCatMcpTool": "MCP ツール呼び出し",+ "tokenCatOther": "その他",+ "tokenCatCached": "キャッシュヒット","agentNoModel": "モデルが設定されていません","agentNoModelTip": "先に 設定 - 人工知能 でプロバイダーとモデルを設定してから、エージェントと対話してください。","dragTip2Heading": "見出しに変換",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex faa309af3d..6d88ef9084 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,16 @@{+ "tokenUsage": "컨텍스트 사용량",+ "tokenCatSystem": "시스템 프롬프트",+ "tokenCatSkills": "스킬",+ "tokenCatMessages": "메시지",+ "tokenCatNativeToolsDef": "네이티브 도구 정의",+ "tokenCatPluginToolsDef": "플러그인 도구 정의",+ "tokenCatMcpToolsDef": "MCP 도구 정의",+ "tokenCatNativeTool": "네이티브 도구 호출",+ "tokenCatPluginTool": "플러그인 도구 호출",+ "tokenCatMcpTool": "MCP 도구 호출",+ "tokenCatOther": "기타",+ "tokenCatCached": "캐시 적중","agentNoModel": "모델이 구성되지 않음","agentNoModelTip": "먼저 설정 - 인공지능에서 제공자와 모델을 구성한 후 에이전트와 대화하세요.","dragTip2Heading": "제목으로 변환",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 4703d42d67..e53ebddfb6 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,16 @@{+ "tokenUsage": "Contextgebruik",+ "tokenCatSystem": "Systeemprompt",+ "tokenCatSkills": "Vaardigheden",+ "tokenCatMessages": "Berichten",+ "tokenCatNativeToolsDef": "Def. ingebouwde tools",+ "tokenCatPluginToolsDef": "Def. plugin tools",+ "tokenCatMcpToolsDef": "Def. MCP tools",+ "tokenCatNativeTool": "Aanroepen ingebouwde tools",+ "tokenCatPluginTool": "Aanroepen plugin tools",+ "tokenCatMcpTool": "Aanroepen MCP tools",+ "tokenCatOther": "Overige",+ "tokenCatCached": "Cache-treffers","agentNoModel": "Geen model geconfigureerd","agentNoModelTip": "Configureer eerst een provider en model in Instellingen - AI en chat dan met de agent.","dragTip2Heading": "Omzetten naar kop",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 8428ea93c5..853513952b 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,16 @@{+ "tokenUsage": "Użycie kontekstu",+ "tokenCatSystem": "Monit systemu",+ "tokenCatSkills": "Umiejętności",+ "tokenCatMessages": "Wiadomości",+ "tokenCatNativeToolsDef": "Def. narzędzi wbudowanych",+ "tokenCatPluginToolsDef": "Def. narzędzi wtyczek",+ "tokenCatMcpToolsDef": "Def. narzędzi MCP",+ "tokenCatNativeTool": "Wywołania narzędzi wbudowanych",+ "tokenCatPluginTool": "Wywołania narzędzi wtyczek",+ "tokenCatMcpTool": "Wywołania narzędzi MCP",+ "tokenCatOther": "Inne",+ "tokenCatCached": "Trafienia w cache","agentNoModel": "Brak skonfigurowanego modelu","agentNoModelTip": "Najpierw skonfiguruj dostawcę i model w Ustawienia - AI, a następnie porozmawiaj z agentem.","dragTip2Heading": "Zmień w nagłówek",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex c167faa9b4..5901d3a708 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,16 @@{+ "tokenUsage": "Uso de contexto",+ "tokenCatSystem": "Prompt do sistema",+ "tokenCatSkills": "Habilidades",+ "tokenCatMessages": "Mensagens",+ "tokenCatNativeToolsDef": "Defs. ferramentas nativas",+ "tokenCatPluginToolsDef": "Defs. ferramentas plugin",+ "tokenCatMcpToolsDef": "Defs. ferramentas MCP",+ "tokenCatNativeTool": "Chamadas ferramentas nativas",+ "tokenCatPluginTool": "Chamadas ferramentas plugin",+ "tokenCatMcpTool": "Chamadas ferramentas MCP",+ "tokenCatOther": "Outros",+ "tokenCatCached": "Acertos de cache","agentNoModel": "Nenhum modelo configurado","agentNoModelTip": "Configure primeiro um provedor e um modelo em Configurações - IA antes de conversar com o agente.","dragTip2Heading": "Converter em título",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex a10874d76c..92475e7719 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,16 @@{+ "tokenUsage": "Использование контекста",+ "tokenCatSystem": "Системный промпт",+ "tokenCatSkills": "Навыки",+ "tokenCatMessages": "Сообщения",+ "tokenCatNativeToolsDef": "Опред. встроенных инструментов",+ "tokenCatPluginToolsDef": "Опред. инструментов плагинов",+ "tokenCatMcpToolsDef": "Опред. инструментов MCP",+ "tokenCatNativeTool": "Вызовы встроенных инструментов",+ "tokenCatPluginTool": "Вызовы инструментов плагинов",+ "tokenCatMcpTool": "Вызовы инструментов MCP",+ "tokenCatOther": "Прочее",+ "tokenCatCached": "Попадания в кэш","agentNoModel": "Модель не настроена","agentNoModelTip": "Сначала настройте провайдера и модель в Настройки - ИИ, затем общайтесь с агентом.","dragTip2Heading": "Преобразовать в заголовок",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 21965c9bc1..2fd91bdb63 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,16 @@{+ "tokenUsage": "Využitie kontextu",+ "tokenCatSystem": "Systémová výzva",+ "tokenCatSkills": "Zručnosti",+ "tokenCatMessages": "Správy",+ "tokenCatNativeToolsDef": "Def. vstavaných nástrojov",+ "tokenCatPluginToolsDef": "Def. nástrojov pluginov",+ "tokenCatMcpToolsDef": "Def. MCP nástrojov",+ "tokenCatNativeTool": "Volania vstavaných nástrojov",+ "tokenCatPluginTool": "Volania nástrojov pluginov",+ "tokenCatMcpTool": "Volania MCP nástrojov",+ "tokenCatOther": "Ostatné",+ "tokenCatCached": "Zásahy vyrovnávacej pamäte","agentNoModel": "Nie je nakonfigurovaný žiadny model","agentNoModelTip": "Najprv nakonfigurujte poskytovateľa a model v Nastavenia - AI a potom konverzujte s agentom.","dragTip2Heading": "Zmeniť na nadpis",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex f91deecb9f..753e3b9722 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,16 @@{+ "tokenUsage": "การใช้บริบท",+ "tokenCatSystem": "พร้อมต์ระบบ",+ "tokenCatSkills": "ทักษะ",+ "tokenCatMessages": "ข้อความ",+ "tokenCatNativeToolsDef": "นิยามเครื่องมือดั้งเดิม",+ "tokenCatPluginToolsDef": "นิยามเครื่องมือปลั๊กอิน",+ "tokenCatMcpToolsDef": "นิยามเครื่องมือ MCP",+ "tokenCatNativeTool": "การเรียกเครื่องมือดั้งเดิม",+ "tokenCatPluginTool": "การเรียกเครื่องมือปลั๊กอิน",+ "tokenCatMcpTool": "การเรียกเครื่องมือ MCP",+ "tokenCatOther": "อื่น ๆ",+ "tokenCatCached": "แคชฮิต","agentNoModel": "ยังไม่ได้กำหนดค่าโมเดล","agentNoModelTip": "โปรดกำหนดค่าผู้ให้บริการและโมเดลใน การตั้งค่า - AI ก่อน จากนั้นคุยกับเอเจนต์","dragTip2Heading": "เปลี่ยนเป็นส่วนหัว",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex e34ff09192..ab2e10bdef 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,16 @@{+ "tokenUsage": "Bağlam kullanımı",+ "tokenCatSystem": "Sistem istemi",+ "tokenCatSkills": "Beceriler",+ "tokenCatMessages": "Mesajlar",+ "tokenCatNativeToolsDef": "Yerleşik araç tanımları",+ "tokenCatPluginToolsDef": "Eklenti araç tanımları",+ "tokenCatMcpToolsDef": "MCP araç tanımları",+ "tokenCatNativeTool": "Yerleşik araç çağrıları",+ "tokenCatPluginTool": "Eklenti araç çağrıları",+ "tokenCatMcpTool": "MCP araç çağrıları",+ "tokenCatOther": "Diğer",+ "tokenCatCached": "Önbellek isabetleri","agentNoModel": "Model yapılandırılmamış","agentNoModelTip": "Önce Ayarlar - Yapay Zeka bölümünde bir sağlayıcı ve model yapılandırın, ardından ajanla sohbet edin.","dragTip2Heading": "Başlığa dönüştür",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 0e8b7ad9fe..fb222a7bc9 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,16 @@{+ "tokenUsage": "Використання контексту",+ "tokenCatSystem": "Системний промпт",+ "tokenCatSkills": "Навички",+ "tokenCatMessages": "Повідомлення",+ "tokenCatNativeToolsDef": "Визн. вбудованих інструментів",+ "tokenCatPluginToolsDef": "Визн. інструментів плагінів",+ "tokenCatMcpToolsDef": "Визн. інструментів MCP",+ "tokenCatNativeTool": "Виклики вбудованих інструментів",+ "tokenCatPluginTool": "Виклики інструментів плагінів",+ "tokenCatMcpTool": "Виклики інструментів MCP",+ "tokenCatOther": "Інше",+ "tokenCatCached": "Попадання в кеш","agentNoModel": "Модель не налаштовано","agentNoModelTip": "Спочатку налаштуйте провайдера та модель у Налаштування - ШІ, потім спілкуйтеся з агентом.","dragTip2Heading": "Перетворити на заголовок",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex d37a14ade2..68e127a983 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,16 @@{+ "tokenUsage": "上下文用量",+ "tokenCatSystem": "系统提示",+ "tokenCatSkills": "技能",+ "tokenCatMessages": "对话消息",+ "tokenCatNativeToolsDef": "原生工具定义",+ "tokenCatPluginToolsDef": "插件工具定义",+ "tokenCatMcpToolsDef": "MCP 工具定义",+ "tokenCatNativeTool": "原生工具调用",+ "tokenCatPluginTool": "插件工具调用",+ "tokenCatMcpTool": "MCP 工具调用",+ "tokenCatOther": "其他",+ "tokenCatCached": "缓存命中","agentNoModel": "尚未配置 AI 模型","agentNoModelTip": "请先在 设置 - 人工智能 中配置提供商与模型,然后再来和智能体对话。","dragTip2Heading": "转换为标题",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 74f1a762a0..abeb92be7c 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,16 @@{+ "tokenUsage": "上下文用量",+ "tokenCatSystem": "系統提示",+ "tokenCatSkills": "技能",+ "tokenCatMessages": "對話訊息",+ "tokenCatNativeToolsDef": "原生工具定義",+ "tokenCatPluginToolsDef": "插件工具定義",+ "tokenCatMcpToolsDef": "MCP 工具定義",+ "tokenCatNativeTool": "原生工具呼叫",+ "tokenCatPluginTool": "插件工具呼叫",+ "tokenCatMcpTool": "MCP 工具呼叫",+ "tokenCatOther": "其他",+ "tokenCatCached": "快取命中","agentNoModel": "尚未配置 AI 模型","agentNoModelTip": "請先在 設定 - 人工智慧 中配置提供商與模型,然後再來和智能體對話。","dragTip2Heading": "轉換為標題",diff --git a/app/src/assets/scss/business/_agentChat.scss b/app/src/assets/scss/business/_agentChat.scssindex 7171ba3702..ed9fdd6794 100644--- a/app/src/assets/scss/business/_agentChat.scss+++ b/app/src/assets/scss/business/_agentChat.scss@@ -911,6 +911,56 @@ pre:hover .agent-chat__copy-wrap {pointer-events: none;}+// token 分类明细弹层:hover 底部 tokens 数字时弹出,复用 b3-menu 基础样式。+.agent-token-popup {+ position: fixed;+ min-width: 200px;+ max-width: 280px;+ padding: 8px 0;++ .b3-menu__items {+ display: flex;+ flex-direction: column;+ }+}++// 总数行(第一行):加粗,与其他分类区分。+.agent-token-popup__total {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 4px 14px;+ font-weight: 600;+ color: var(--b3-theme-on-background);+}++// 各分类行:两端对齐,左标签右百分比。+.agent-token-popup__row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 3px 14px;+ font-size: 13px;+ color: var(--b3-theme-on-surface);+}++.agent-token-popup__label {+ flex-shrink: 0;+}++.agent-token-popup__value {+ margin-left: 12px;+ flex-shrink: 0;+ color: var(--b3-theme-on-surface-light);+}++// 总数行与分类之间、分类与缓存命中之间的分隔线。+.agent-token-popup__divider {+ height: 1px;+ margin: 4px 10px;+ background: var(--b3-border-color);+}+.agent-session-popup {position: fixed;width: 280px;diff --git a/app/src/layout/dock/AgentChat.ts b/app/src/layout/dock/AgentChat.tsindex 761576f72e..2a70d4d447 100644--- a/app/src/layout/dock/AgentChat.ts+++ b/app/src/layout/dock/AgentChat.ts@@ -12,6 +12,7 @@ import {AgentSessionPanel} from "./AgentSessionPanel";import {getDockByType} from "../tabUtil";import {updateHotkeyAfterTip} from "../../protyle/util/compatibility";import {escapeAriaLabel, escapeHtml} from "../../util/escape";+import {setPosition} from "../../util/setPosition";import {fetchPost} from "../../util/fetch";import {confirmDialog} from "../../dialog/confirmDialog";import {showMessage} from "../../dialog/message";@@ -79,6 +80,11 @@ export class AgentChat extends Model {private currentContent = "";private fullContent = "";private contextTokens = 0;+ private contextTokenBreakdown: Record<string, number> = {};+ private contextCachedTokens = 0;+ private tokenPopup: HTMLElement | null = null;+ private tokenPopupShowTimer = 0;+ private tokenPopupHideTimer = 0;private sessionCreatedAt = 0;private requestStartTime = 0;private tokenDisplayEl: HTMLElement;@@ -468,6 +474,27 @@ export class AgentChat extends Model {}private bindEvents() {+ // hover 底部 tokens 数字弹出分类明细面板(移动端 click 触发)。+ this.tokenDisplayEl.addEventListener("mouseenter", () => {+ window.clearTimeout(this.tokenPopupHideTimer);+ this.tokenPopupShowTimer = window.setTimeout(() => {+ this.showTokenBreakdownPopup();+ }, 200);+ });+ this.tokenDisplayEl.addEventListener("mouseleave", () => {+ window.clearTimeout(this.tokenPopupShowTimer);+ this.tokenPopupHideTimer = window.setTimeout(() => {+ this.closeTokenBreakdownPopup();+ }, 300);+ });+ this.tokenDisplayEl.addEventListener("click", () => {+ // 移动端无 hover,click 直接切换 popup。+ if (this.tokenPopup) {+ this.closeTokenBreakdownPopup();+ } else {+ this.showTokenBreakdownPopup();+ }+ });this.sendBtn.addEventListener("click", (e: MouseEvent) => {e.stopPropagation();this.sendMessage();@@ -537,6 +564,8 @@ export class AgentChat extends Model {this.entries = this.buildEntriesFromSession(session);this.hasTitled = session.titled !== false;this.contextTokens = session.contextTokens ?? 0;+ this.contextTokenBreakdown = session.contextTokenBreakdown ?? {};+ this.contextCachedTokens = session.contextCachedTokens ?? 0;if (session.model) {this.applySessionModelIfValid(session.model);}@@ -569,6 +598,8 @@ export class AgentChat extends Model {titled: this.hasTitled,entries: this.entries.slice(),contextTokens: this.contextTokens,+ contextTokenBreakdown: this.contextTokenBreakdown,+ contextCachedTokens: this.contextCachedTokens,createdAt: this.sessionCreatedAt,updatedAt: Date.now(),messageHistory: this.composer?.getHistory() || [],@@ -699,6 +730,8 @@ export class AgentChat extends Model {this.hasTitled = session.titled !== false;this.sessionCreatedAt = session.createdAt || this.sessionCreatedAt;this.contextTokens = session.contextTokens ?? 0;+ this.contextTokenBreakdown = session.contextTokenBreakdown ?? {};+ this.contextCachedTokens = session.contextCachedTokens ?? 0;if (session.model) {this.applySessionModelIfValid(session.model);}@@ -767,6 +800,8 @@ export class AgentChat extends Model {this.currentContent = "";this.fullContent = "";this.contextTokens = session.contextTokens ?? 0;+ this.contextTokenBreakdown = session.contextTokenBreakdown ?? {};+ this.contextCachedTokens = session.contextCachedTokens ?? 0;if (session.model) {this.applySessionModelIfValid(session.model);}@@ -1038,6 +1073,8 @@ export class AgentChat extends Model {this.currentContent = "";this.fullContent = "";this.contextTokens = 0;+ this.contextTokenBreakdown = {};+ this.contextCachedTokens = 0;this.currentToolCalls = [];this.lastStepToolCount = 0;this.renderedToolNames = {};@@ -1337,7 +1374,7 @@ export class AgentChat extends Model {await this.finishResponse();break;case "usage":- this.appendUsage(event.lastPromptTokens);+ this.appendUsage(event.lastPromptTokens, event.tokenBreakdown, event.cachedTokens);break;case "error":this.flushTokenUpdate();@@ -2410,11 +2447,126 @@ export class AgentChat extends Model {}// 记录最近一轮的 prompt tokens(= 当前上下文已用),覆盖式更新而非累加。- private appendUsage(lastPromptTokens: number) {+ // 记录最近一轮的 prompt tokens(= 当前上下文已用)+ 分类明细 + 缓存命中,覆盖式更新而非累加。+ private appendUsage(lastPromptTokens: number, tokenBreakdown: Record<string, number>, cachedTokens: number) {this.contextTokens = lastPromptTokens;+ this.contextTokenBreakdown = tokenBreakdown;+ this.contextCachedTokens = cachedTokens;this.updateTokenDisplay();}+ // 弹出 token 分类明细面板。breakdown 全 0 时不弹(无内容可显示)。+ private showTokenBreakdownPopup() {+ if (!this.formatTokenBreakdown().length && this.contextCachedTokens === 0) {+ return;+ }+ this.closeTokenBreakdownPopup();+ const L = window.siyuan.languages;+ const popup = document.createElement("div");+ popup.className = "agent-token-popup b3-menu";+ let html = '<div class="b3-menu__items">';+ // 第一行:上下文用量(总数)。+ html += '<div class="agent-token-popup__total">' ++ '<span class="agent-token-popup__label">' + (L.tokenUsage || "Context Usage") + "</span>" ++ '<span class="agent-token-popup__value">' + this.formatTokenCount(this.contextTokens) + "</span>" ++ "</div>";+ // 分隔线。+ html += '<div class="agent-token-popup__divider"></div>';+ // 各分类(0 值跳过),百分比格式。+ for (const row of this.formatTokenBreakdown()) {+ html += '<div class="agent-token-popup__row">' ++ '<span class="agent-token-popup__label">' + escapeHtml(row.label) + "</span>" ++ '<span class="agent-token-popup__value">' + row.percent + "</span>" ++ "</div>";+ }+ // 缓存命中(独立维度,分隔线隔开,为 0 不显示)。+ if (this.contextCachedTokens > 0 && this.contextTokens > 0) {+ html += '<div class="agent-token-popup__divider"></div>';+ const cachedPercent = Math.round(this.contextCachedTokens / this.contextTokens * 100);+ html += '<div class="agent-token-popup__row">' ++ '<span class="agent-token-popup__label">' + (L.tokenCatCached || "Cache Hits") + "</span>" ++ '<span class="agent-token-popup__value">' + cachedPercent + "%</span>" ++ "</div>";+ }+ html += "</div>";+ popup.innerHTML = html;+ document.body.appendChild(popup);+ popup.style.zIndex = (++window.siyuan.zIndex).toString();+ // 定位在 tokens 数字上方。+ const rect = this.tokenDisplayEl.getBoundingClientRect();+ setPosition(popup, rect.left, rect.top, rect.height, rect.width);+ // popup 自身 hover 保持显示(鼠标移入时取消关闭计时,移出时关闭)。+ popup.addEventListener("mouseenter", () => {+ window.clearTimeout(this.tokenPopupHideTimer);+ });+ popup.addEventListener("mouseleave", () => {+ this.tokenPopupHideTimer = window.setTimeout(() => {+ this.closeTokenBreakdownPopup();+ }, 300);+ });+ // 点击外部/resize/ESC 关闭。+ popup.addEventListener("click", (e: MouseEvent) => {+ e.stopPropagation();+ });+ const onOutsideClick = () => {+ this.closeTokenBreakdownPopup();+ document.removeEventListener("click", onOutsideClick);+ };+ setTimeout(() => {+ document.addEventListener("click", onOutsideClick);+ }, 10);+ const onResize = () => {+ this.closeTokenBreakdownPopup();+ window.removeEventListener("resize", onResize);+ };+ window.addEventListener("resize", onResize);+ this.tokenPopup = popup;+ }++ private closeTokenBreakdownPopup() {+ if (this.tokenPopup) {+ this.tokenPopup.remove();+ this.tokenPopup = null;+ }+ }++ // 把 contextTokenBreakdown(后端估算的 9 类 + other)格式化为 [{label, percent}],跳过 0 值。+ // percent = 各类 token / contextTokens * 100(contextTokens 为 0 时显示 "-")。+ private formatTokenBreakdown(): Array<{ label: string; percent: string }> {+ const L = window.siyuan.languages;+ // 固定顺序展示(与后端 key 对应)。+ const order: Array<{ key: string; labelKey: string }> = [+ {key: "system", labelKey: "tokenCatSystem"},+ {key: "skills", labelKey: "tokenCatSkills"},+ {key: "messages", labelKey: "tokenCatMessages"},+ {key: "nativeToolsDef", labelKey: "tokenCatNativeToolsDef"},+ {key: "pluginToolsDef", labelKey: "tokenCatPluginToolsDef"},+ {key: "mcpToolsDef", labelKey: "tokenCatMcpToolsDef"},+ {key: "nativeTool", labelKey: "tokenCatNativeTool"},+ {key: "pluginTool", labelKey: "tokenCatPluginTool"},+ {key: "mcpTool", labelKey: "tokenCatMcpTool"},+ {key: "other", labelKey: "tokenCatOther"},+ ];+ const result: Array<{ label: string; percent: string }> = [];+ for (const item of order) {+ const tokens = this.contextTokenBreakdown[item.key] || 0;+ if (tokens <= 0) {+ continue;+ }+ const label = (L as Record<string, string>)[item.labelKey] || item.key;+ const percent = this.contextTokens > 0+ ? Math.round(tokens / this.contextTokens * 100) + "%"+ : "-";+ result.push({label, percent});+ }+ return result;+ }++ // token 数 k 格式化(>=1000 显示为 1.2k)。+ private formatTokenCount(n: number): string {+ return n >= 1000 ? (n / 1000).toFixed(1) + "k" : String(n);+ }+private clearThinking() {const items = this.messagesContainer.querySelectorAll(".agent-chat__msg--thinking:not(.agent-chat__msg--thinking-done)"diff --git a/app/src/layout/dock/SessionStore.ts b/app/src/layout/dock/SessionStore.tsindex 9b32677620..ad725b8721 100644--- a/app/src/layout/dock/SessionStore.ts+++ b/app/src/layout/dock/SessionStore.ts@@ -57,6 +57,8 @@ export interface AgentSession {completionTokens?: number;totalDuration?: number;contextTokens?: number;+ contextTokenBreakdown?: Record<string, number>;+ contextCachedTokens?: number;messageHistory?: string[];createdAt: number;updatedAt: number;diff --git a/app/src/util/agentSSE.ts b/app/src/util/agentSSE.tsindex ad68582af8..f1249218b0 100644--- a/app/src/util/agentSSE.ts+++ b/app/src/util/agentSSE.ts@@ -27,6 +27,8 @@ export type ISSEResult = {promptTokens: number;completionTokens: number;lastPromptTokens: number;+ tokenBreakdown: Record<string, number>;+ cachedTokens: number;} | {type: "retry";attempt: number;@@ -240,6 +242,8 @@ function buildSSEResult(event: string, data: Record<string, unknown>): ISSEResulpromptTokens: (data.promptTokens as number) || 0,completionTokens: (data.completionTokens as number) || 0,lastPromptTokens: (data.lastPromptTokens as number) || 0,+ tokenBreakdown: (data.tokenBreakdown as Record<string, number>) || {},+ cachedTokens: (data.cachedTokens as number) || 0,};case "retry":return {diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex 14f4d936df..6d4b645f03 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -218,6 +218,8 @@ type AgentEvent struct {PromptTokens intCompletionTokens intLastPromptTokens int+ TokenBreakdown map[string]int+ CachedTokens intRetryAttempt intRetryMax intSnapshotID string@@ -291,18 +293,21 @@ type SessionEntryStep struct {}type agentCheckpoint struct {- ID string `json:"id"`- Title string `json:"title"`- Titled bool `json:"titled"`- Entries []SessionEntry `json:"entries"`- PromptTokens int `json:"promptTokens"`- CompletionTokens int `json:"completionTokens"`- TotalDuration int64 `json:"totalDuration"`- CreatedAt int64 `json:"createdAt"`- UpdatedAt int64 `json:"updatedAt"`- MessageHistory []string `json:"messageHistory,omitempty"`- Snapshots []string `json:"snapshots,omitempty"`- AlwaysAllow bool `json:"alwaysAllow,omitempty"`+ ID string `json:"id"`+ Title string `json:"title"`+ Titled bool `json:"titled"`+ Entries []SessionEntry `json:"entries"`+ PromptTokens int `json:"promptTokens"`+ CompletionTokens int `json:"completionTokens"`+ TotalDuration int64 `json:"totalDuration"`+ CreatedAt int64 `json:"createdAt"`+ UpdatedAt int64 `json:"updatedAt"`+ MessageHistory []string `json:"messageHistory,omitempty"`+ Snapshots []string `json:"snapshots,omitempty"`+ AlwaysAllow bool `json:"alwaysAllow,omitempty"`+ ContextTokens int `json:"contextTokens,omitempty"`+ ContextTokenBreakdown map[string]int `json:"contextTokenBreakdown,omitempty"`+ ContextCachedTokens int `json:"contextCachedTokens,omitempty"`}func AgentChat(ctx context.Context, client *openai.Client, model string, sessionID string, userMessage string, language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction, regenerate bool, confirmTimeout time.Duration, maxRetries int) <-chan AgentEvent {@@ -324,7 +329,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, sessiontools := convertMCPToolsToOpenAI()var messages []openai.ChatCompletionMessagevar checkpointMsgs []AgentMessage- var totalPrompt, totalCompletion, lastPromptTokens int+ var totalPrompt, totalCompletion, lastPromptTokens, lastCachedTokens intstartTime := time.Now().UnixMilli()alwaysAllow := map[string]bool{}var doomLoop doomLoopTracker@@ -481,6 +486,11 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, sessiontotalCompletion += resp.Usage.CompletionTokens// 记录最后一次 stream 的 prompt tokens(= 当前上下文已用),供前端底部显示。lastPromptTokens = resp.Usage.PromptTokens+ // 补读缓存命中 tokens(OpenAI PromptTokensDetails.CachedTokens,精确值)。+ // 非 OpenAI 兼容提供商可能不返回该字段,nil 安全处理。+ if resp.Usage.PromptTokensDetails != nil {+ lastCachedTokens = resp.Usage.PromptTokensDetails.CachedTokens+ }}}@@ -722,12 +732,12 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, sessionReasoningContent: reasoningBuilder.String(),})- sendEvent(ch, AgentEvent{Type: "usage", PromptTokens: totalPrompt, CompletionTokens: totalCompletion, LastPromptTokens: lastPromptTokens})+ sendEvent(ch, AgentEvent{Type: "usage", PromptTokens: totalPrompt, CompletionTokens: totalCompletion, LastPromptTokens: lastPromptTokens, TokenBreakdown: computeBreakdownIfNeeded(model, messages, tools, lastPromptTokens), CachedTokens: lastCachedTokens})sendCriticalEvent(ctx, ch, AgentEvent{Type: "done"})return}- sendEvent(ch, AgentEvent{Type: "usage", PromptTokens: totalPrompt, CompletionTokens: totalCompletion, LastPromptTokens: lastPromptTokens})+ sendEvent(ch, AgentEvent{Type: "usage", PromptTokens: totalPrompt, CompletionTokens: totalCompletion, LastPromptTokens: lastPromptTokens, TokenBreakdown: computeBreakdownIfNeeded(model, messages, tools, lastPromptTokens), CachedTokens: lastCachedTokens})saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime, snapshotIDs, alwaysAllow)sendCriticalEvent(ctx, ch, AgentEvent{Type: "done"})}()@@ -1036,6 +1046,38 @@ func buildInitialMessages(userMessage string, language string, references []Refe}}+// skillsSegmentTokens 估算 system prompt 中 <available_skills> 段(含引导句)的 token 数。+// 该段在 buildSystemPrompt 内部拼成大字符串,这里独立重建同等内容计数,用于分类统计切出 skills 类。+func skillsSegmentTokens(counter *tokenCounter) int {+ if counter == nil {+ return 0+ }+ skills := util.DiscoverSkills()+ if len(skills) == 0 {+ return 0+ }+ var sb strings.Builder+ sb.WriteString("\n\n<available_skills>\n")+ for _, s := range skills {+ sb.WriteString(" <skill>\n <name>")+ sb.WriteString(s.Name)+ sb.WriteString("</name>\n <description>")+ sb.WriteString(s.Description)+ sb.WriteString("</description>\n </skill>\n")+ }+ sb.WriteString("</available_skills>\n\nUse the skill tool to load a skill when a task matches its description.")+ return counter.count(sb.String())+}++// computeBreakdownIfNeeded 计算 10 类 token 分类明细。counter 初始化失败时返回 nil(前端兜底)。+func computeBreakdownIfNeeded(model string, messages []openai.ChatCompletionMessage, tools []openai.Tool, realPromptTokens int) map[string]int {+ counter, err := getTokenCounter(model)+ if err != nil || counter == nil {+ return nil+ }+ return computeTokenBreakdown(counter, messages, tools, skillsSegmentTokens(counter), realPromptTokens)+}+func loadCheckpoint(sessionID string) *agentCheckpoint {if sessionID == "" || !isValidSessionID(sessionID) {return nil@@ -1227,6 +1269,18 @@ func saveCheckpoint(sessionID string, messages []AgentMessage, promptTokens int,if len(old.Snapshots) > 0 {cp.Snapshots = old.Snapshots}+ // 回填前端写入的上下文 token 统计字段,避免后端 checkpoint 擦除它们(双写覆盖修复)。+ // 后端 saveCheckpoint 在流式中途/结束都会触发,但这些统计值是 stream 结束时才由前端写入的,+ // 所以后端只保留磁盘已有值,不自行计算。+ if old.ContextTokens > 0 {+ cp.ContextTokens = old.ContextTokens+ }+ if len(old.ContextTokenBreakdown) > 0 {+ cp.ContextTokenBreakdown = old.ContextTokenBreakdown+ }+ if old.ContextCachedTokens > 0 {+ cp.ContextCachedTokens = old.ContextCachedTokens+ }}data, err := gulu.JSON.MarshalIndentJSON(cp, "", "\t")diff --git a/kernel/agent/tokens.go b/kernel/agent/tokens.gonew file mode 100644index 0000000000..b0fbf78ea3--- /dev/null+++ b/kernel/agent/tokens.go@@ -0,0 +1,217 @@+// SiYuan - Refactor your thinking+// 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 agent++import (+ "encoding/json"+ "sync"++ "github.com/pkoukk/tiktoken-go"+ loader "github.com/pkoukk/tiktoken-go-loader"+ "github.com/sashabaranov/go-openai"+ tools "github.com/siyuan-note/siyuan/kernel/mcp/tools"+)++// tokenCounter 用 tiktoken 对文本进行 BPE 分词计数。encoder 单例化避免重复加载编码表。+type tokenCounter struct {+ enc *tiktoken.Tiktoken+}++var (+ tokenCounterOnce sync.Once+ globalCounter *tokenCounter+ tokenCounterErr error+)++// getTokenCounter 懒初始化全局单例 counter。modelName 用于选编码(GPT-4o→o200k_base,+// 其他→cl100k_base),失败回退 cl100k_base。首次调用注册离线 BPE loader(embed 编码表),+// 避免 SiYuan 桌面端在离线/内网环境联网下载编码表失败。+func getTokenCounter(modelName string) (*tokenCounter, error) {+ tokenCounterOnce.Do(func() {+ tiktoken.SetBpeLoader(loader.NewOfflineLoader())+ enc, err := tiktoken.EncodingForModel(modelName)+ if err != nil {+ // 模型名未识别,回退到 cl100k_base(覆盖 GPT-3.5/4 系,最通用的编码)。+ enc, err = tiktoken.GetEncoding("cl100k_base")+ if err != nil {+ tokenCounterErr = err+ return+ }+ }+ globalCounter = &tokenCounter{enc: enc}+ })+ return globalCounter, tokenCounterErr+}++// count 返回 text 的 token 数。counter 为 nil 时回退到字符近似估算。+func (c *tokenCounter) count(text string) int {+ if c == nil || c.enc == nil {+ return estimateTokensByChars(text)+ }+ return len(c.enc.Encode(text, nil, nil))+}++// estimateTokensByChars 字符近似估算:中文按 ~1.5 字符/token,其他按 ~4 字符/token。+// 仅在 tiktoken 不可用时降级使用。+func estimateTokensByChars(text string) int {+ if text == "" {+ return 0+ }+ cjk := 0+ other := 0+ for _, r := range text {+ if r >= 0x4E00 && r <= 0x9FFF || r >= 0x3040 && r <= 0x30FF || r >= 0xAC00 && r <= 0xD7AF {+ cjk+++ } else {+ other+++ }+ }+ return cjk*2/3 + other/4+}++// toolSource 按工具注册时标记的 Source 字段判断来源(native/plugin/mcp)。+// 工具名无前缀区分(原生工具名是 block/document 等普通字符串),必须查 Tool.Source。+// 兼容兜底:plugin__ 前缀的旧工具名也识别为 plugin;查不到工具的按 mcp 处理。+func toolSource(name string) string {+ if t := tools.GetTool(name); t != nil {+ if t.Source != "" {+ return t.Source+ }+ }+ // 兜底:plugin__ 前缀(历史兼容,理论上 plugin 工具已标记 Source)。+ if len(name) > 8 && name[:8] == "plugin__" {+ return "plugin"+ }+ // 查不到工具(可能是已卸载的工具),按 mcp 归类(最少见的情况)。+ return "mcp"+}++// computeTokenBreakdown 按 10 个分类估算上下文 token 用量。+// messages:发给 LLM 的完整消息列表;tools:函数定义列表;skillsTokens:system prompt 中+// <available_skills> 段单独的 token 数;realPromptTokens:OpenAI 返回的真实 prompt tokens。+// 返回的 map 包含 system/skills/messages/nativeToolsDef/pluginToolsDef/mcpToolsDef/+// nativeTool/pluginTool/mcpTool/other 共 10 个 key,other = realPromptTokens - 前 9 类之和。+func computeTokenBreakdown(counter *tokenCounter, messages []openai.ChatCompletionMessage, tools []openai.Tool, skillsTokens, realPromptTokens int) map[string]int {+ breakdown := map[string]int{+ "system": 0,+ "skills": skillsTokens,+ "messages": 0,+ "nativeToolsDef": 0,+ "pluginToolsDef": 0,+ "mcpToolsDef": 0,+ "nativeTool": 0,+ "pluginTool": 0,+ "mcpTool": 0,+ "other": 0,+ }++ // 统计 messages:按 role 分类。system 类累加所有 system 消息(含 doom-loop 警告等运行时追加),+ // 最后减去 skillsTokens(skills 段单独成类)。+ // 按 OpenAI cookbook 公式补算 chat 格式的结构开销:每条消息 +4 token(role 标记 + 边界),+ // 整个对话 +3 token(priming)。这些结构开销计入对应类别的 token 数,减少 "其他" 残差。+ systemTotal := 0+ // tool 消息需通过 ToolCallID 关联回前一条 assistant 的 tool_call 拿工具名。+ // 维护 idToToolName 映射(assistant 带 tool_calls 时填充)。+ idToToolName := map[string]string{}+ const perMessageOverhead = 4 // 每条消息的结构 overhead(OpenAI chat 格式固定开销)+ for _, msg := range messages {+ switch msg.Role {+ case openai.ChatMessageRoleSystem:+ systemTotal += counter.count(msg.Content) + perMessageOverhead+ case openai.ChatMessageRoleUser:+ breakdown["messages"] += counter.count(msg.Content) + perMessageOverhead+ case openai.ChatMessageRoleAssistant:+ breakdown["messages"] += counter.count(msg.Content) + perMessageOverhead+ // 助手消息的推理内容(deepseek-reasoner 等)也计入对话消息。+ if msg.ReasoningContent != "" {+ breakdown["messages"] += counter.count(msg.ReasoningContent)+ }+ for _, tc := range msg.ToolCalls {+ name := tc.Function.Name+ idToToolName[tc.ID] = name+ // tool_call 的函数名 + 参数计入对应工具调用类。+ // 每个 tool_call 结构额外有 id/type/function 的 JSON 结构开销(约 7 token)。+ callTokens := counter.count(name) + counter.count(tc.Function.Arguments) + 7+ switch toolSource(name) {+ case "native":+ breakdown["nativeTool"] += callTokens+ case "plugin":+ breakdown["pluginTool"] += callTokens+ default:+ breakdown["mcpTool"] += callTokens+ }+ }+ case openai.ChatMessageRoleTool:+ // tool 结果按关联的工具名归类。+ name := idToToolName[msg.ToolCallID]+ resultTokens := counter.count(msg.Content) + perMessageOverhead+ switch toolSource(name) {+ case "native":+ breakdown["nativeTool"] += resultTokens+ case "plugin":+ breakdown["pluginTool"] += resultTokens+ default:+ breakdown["mcpTool"] += resultTokens+ }+ }+ }+ breakdown["system"] = systemTotal - skillsTokens+ if breakdown["system"] < 0 {+ breakdown["system"] = 0+ }++ // 统计 tools 定义(函数签名):序列化每个 Function 的 Name+Description+Parameters JSON 计数。+ // OpenAI 对每个 function 定义有固定结构开销(约 10 token:type/function 包装 + 字段名),+ // 予以补算以减少与真实计费的偏差。+ const perToolDefOverhead = 10+ for _, t := range tools {+ if t.Function == nil {+ continue+ }+ defText := t.Function.Name + " " + t.Function.Description+ if paramsJSON, err := json.Marshal(t.Function.Parameters); err == nil {+ defText += " " + string(paramsJSON)+ }+ defTokens := counter.count(defText) + perToolDefOverhead+ switch toolSource(t.Function.Name) {+ case "native":+ breakdown["nativeToolsDef"] += defTokens+ case "plugin":+ breakdown["pluginToolsDef"] += defTokens+ default:+ breakdown["mcpToolsDef"] += defTokens+ }+ }++ // OpenAI 对整个对话有固定 priming overhead(约 3 token),计入 messages 类。+ if len(messages) > 0 {+ breakdown["messages"] += 3+ }++ // "其他" = 真实总数 - 前 9 类估算之和(clamp≥0)。吸收剩余的估算误差。+ estimated := 0+ for k, v := range breakdown {+ if k == "other" {+ continue+ }+ estimated += v+ }+ if realPromptTokens > estimated {+ breakdown["other"] = realPromptTokens - estimated+ }+ return breakdown+}diff --git a/kernel/api/agent.go b/kernel/api/agent.goindex b47c1c56c8..e885d19111 100644--- a/kernel/api/agent.go+++ b/kernel/api/agent.go@@ -412,6 +412,8 @@ func writeSSE(c *gin.Context, event agent.AgentEvent) error {"promptTokens": event.PromptTokens,"completionTokens": event.CompletionTokens,"lastPromptTokens": event.LastPromptTokens,+ "tokenBreakdown": event.TokenBreakdown,+ "cachedTokens": event.CachedTokens,})case "done":return writeSSEEvent(c, "done", map[string]interface{}{})diff --git a/kernel/go.mod b/kernel/go.modindex ea5d47bbe4..f2976cec07 100644--- a/kernel/go.mod+++ b/kernel/go.mod@@ -95,6 +95,11 @@ require (gopkg.in/yaml.v3 v3.0.1)+require (+ github.com/pkoukk/tiktoken-go v0.1.8 // indirect+ github.com/pkoukk/tiktoken-go-loader v0.0.2 // indirect+)+require (dario.cat/mergo v1.0.2 // indirectdmitri.shuralyov.com/font/woff2 v0.0.0-20180220214647-957792cbbdab // indirectdiff --git a/kernel/go.sum b/kernel/go.sumindex 5d2ae8650e..86a5f687df 100644--- a/kernel/go.sum+++ b/kernel/go.sum@@ -343,6 +343,10 @@ github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=+github.com/pkoukk/tiktoken-go v0.1.8 h1:85ENo+3FpWgAACBaEUVp+lctuTcYUO7BtmfhlN/QTRo=+github.com/pkoukk/tiktoken-go v0.1.8/go.mod h1:9NiV+i9mJKGj1rYOT+njbv+ZwA/zJxYdewGl6qVatpg=+github.com/pkoukk/tiktoken-go-loader v0.0.2 h1:LUKws63GV3pVHwH1srkBplBv+7URgmOmhSkRxsIvsK4=+github.com/pkoukk/tiktoken-go-loader v0.0.2/go.mod h1:4mIkYyZooFlnenDlormIo6cd5wrlUKNr97wp9nGgEKo=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=diff --git a/kernel/mcp/client/mcp.go b/kernel/mcp/client/mcp.goindex 3786c3dcb6..7059267980 100644--- a/kernel/mcp/client/mcp.go+++ b/kernel/mcp/client/mcp.go@@ -121,6 +121,7 @@ func connectServers(servers []conf.MCPServer) []Connection {Name: name,Description: desc,InputSchema: convertMCPSchema(tool.InputSchema),+ Source: "mcp",Handler: mcpToolHandler(session, tool.Name, serverTimeout(server)),})registered++diff --git a/kernel/mcp/tools/register.go b/kernel/mcp/tools/register.goindex 44afc997ef..56f41fdb45 100644--- a/kernel/mcp/tools/register.go+++ b/kernel/mcp/tools/register.go@@ -80,5 +80,8 @@ func RemoveTool(name string) {}func register(t *Tool) {+ if t.Source == "" {+ t.Source = "native"+ }SetTool(t.Name, t)}diff --git a/kernel/mcp/tools/types.go b/kernel/mcp/tools/types.goindex 2ec1a04a5f..961cda19aa 100644--- a/kernel/mcp/tools/types.go+++ b/kernel/mcp/tools/types.go@@ -22,6 +22,9 @@ type Tool struct {Description string `json:"description"`InputSchema ToolSchema `json:"inputSchema"`OutputSchema *ToolSchema `json:"outputSchema,omitempty"`+ // Source 标记工具来源:"native"(SiYuan 内置)、"plugin"(插件注册)、"mcp"(外部 MCP 服务)。+ // 用于 token 分类统计按来源拆分。空值按 "native" 处理(兼容旧调用方)。+ Source string `json:"source,omitempty"`Handler func(args map[string]interface{}) (CallToolResult, error) `json:"-"`}diff --git a/kernel/plugin/api_mcp.go b/kernel/plugin/api_mcp.goindex 21c33c03bb..b355ea511a 100644--- a/kernel/plugin/api_mcp.go+++ b/kernel/plugin/api_mcp.go@@ -120,6 +120,7 @@ func injectMcp(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err erroDescription: description,InputSchema: *inputSchema,OutputSchema: outputSchema,+ Source: "plugin",Handler: func(args map[string]interface{}) (tools.CallToolResult, error) {return p.invokeMcpTool(handler, args)},