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 Anthropic Messages API https://github.com/siyuan-note/siyuan/issues/17845
Daniel882db7270d96
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 99870a4b50..c7c1d483ea 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "واجهة Anthropic Messages","encryptedAssetExternalOpenTip": "سيتم فتح نسخة مؤقتة مفكوك تشفيرها. لن تُحفظ التغييرات في المرفق الأصلي. قد تُحذف النسخة عند قفل دفتر الملاحظات. للاحتفاظ بالتغييرات، احفظ الملف في موقع آخر.","linuxInputMethod": "وضع توافق طرق الإدخال في Linux","linuxInputMethodTip": "استخدام X11/XWayland لتحسين توافق طرق الإدخال؛ قد يؤثر على تحجيم العرض، وينطبق على جميع مساحات العمل على هذا الجهاز، ويسري بعد إغلاق SiYuan بالكامل وإعادة تشغيله",@@ -1499,7 +1500,7 @@"apiVersion": "إصدار API","apiVersionTip": "مطلوب فقط عند استخدام خدمة Azure OpenAI","apiProvider": "موفر API",- "apiProviderTip": "يمكن استخدام الموفرين المتوافقين مع واجهة Chat Completions API أو Responses API (مثل DeepSeek وKimi وMiniMax)",+ "apiProviderTip": "اختر نوع واجهة API الذي يدعمه كل مزود","skip": "تخطى","nextRound": "الجولة التالية","save": "حفظ",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex a00717dc88..f1f4fb639f 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "Anthropic Messages API","encryptedAssetExternalOpenTip": "Es wird eine temporäre entschlüsselte Kopie geöffnet. Änderungen werden nicht im ursprünglichen Anhang gespeichert. Die Kopie kann beim Sperren des Notizbuchs gelöscht werden. Speichern Sie die Datei an einem anderen Ort, um Ihre Änderungen zu behalten.","linuxInputMethod": "Linux-Eingabemethoden-Kompatibilitätsmodus","linuxInputMethodTip": "X11/XWayland zur Verbesserung der Eingabemethoden-Kompatibilität verwenden; kann die Anzeigeskalierung beeinflussen, gilt für alle Arbeitsbereiche auf diesem Gerät und wird nach vollständigem Beenden und Neustarten von SiYuan wirksam",@@ -1499,7 +1500,7 @@"apiVersion": "API-Version","apiVersionTip": "Nur erforderlich, wenn der Azure OpenAI-Dienst verwendet wird.","apiProvider": "API-Anbieter",- "apiProviderTip": "Anbieter, die mit der Chat Completions API oder der Responses API kompatibel sind (z. B. DeepSeek, Kimi, MiniMax), können verwendet werden",+ "apiProviderTip": "Wählen Sie für jeden Anbieter den unterstützten API-Typ aus","skip": "Überspringen","nextRound": "Nächste Runde","save": "Speichern",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 7906eff571..5e2e0debb2 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "Anthropic Messages API","encryptedAssetExternalOpenTip": "This will open a temporary decrypted copy. Changes will not be saved to the original attachment. The copy may be cleaned up when the notebook is locked. To keep your changes, save the file to another location.","linuxInputMethod": "Linux input method compatibility mode","linuxInputMethodTip": "Use X11/XWayland to address input method issues; may affect display scaling, applies to all workspaces on this device, and takes effect after fully quitting and restarting SiYuan",@@ -1499,7 +1500,7 @@"apiVersion": "API version","apiVersionTip": "Only required when using the Azure OpenAI service","apiProvider": "API Provider",- "apiProviderTip": "Providers compatible with the Chat Completions API or the Responses API (e.g., DeepSeek, Kimi, MiniMax) are supported",+ "apiProviderTip": "Select the API type supported by each provider","skip": "Skip","nextRound": "Next round","save": "Save",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 3a3813510c..eff77ddf2e 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "API de mensajes de Anthropic","encryptedAssetExternalOpenTip": "Se abrirá una copia temporal descifrada. Los cambios no se guardarán en el archivo adjunto original. La copia puede eliminarse al bloquear el cuaderno. Para conservar los cambios, guarde el archivo en otra ubicación.","linuxInputMethod": "Modo de compatibilidad de métodos de entrada de Linux","linuxInputMethodTip": "Usar X11/XWayland para mejorar la compatibilidad de los métodos de entrada; puede afectar al escalado, se aplica a todos los espacios de trabajo de este dispositivo y requiere cerrar completamente y reiniciar SiYuan",@@ -1499,7 +1500,7 @@"apiVersion": "Versión API","apiVersionTip": "Sólo es necesario cuando se utiliza el servicio Azure OpenAI","apiProvider": "API proveedor",- "apiProviderTip": "Los proveedores compatibles con la API de Chat Completions o la API de Responses (p. ej., DeepSeek, Kimi, MiniMax) pueden utilizarse",+ "apiProviderTip": "Seleccione el tipo de API compatible con cada proveedor","skip": "Omitir","nextRound": "Siguiente ronda","save": "Guardar",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex 97dff66817..ec3e9adcaa 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "API Messages d’Anthropic","encryptedAssetExternalOpenTip": "Une copie temporaire déchiffrée va être ouverte. Les modifications ne seront pas enregistrées dans la pièce jointe d’origine. La copie peut être supprimée lors du verrouillage du carnet. Pour conserver vos modifications, enregistrez le fichier à un autre emplacement.","linuxInputMethod": "Mode de compatibilité des méthodes de saisie Linux","linuxInputMethodTip": "Utiliser X11/XWayland pour améliorer la compatibilité des méthodes de saisie ; peut affecter la mise à l’échelle, s’applique à tous les espaces de travail de cet appareil et prend effet après avoir complètement quitté puis redémarré SiYuan",@@ -1499,7 +1500,7 @@"apiVersion": "Version API","apiVersionTip": "Requis uniquement lors de l'utilisation du service Azure OpenAI","apiProvider": "API du fournisseur",- "apiProviderTip": "Les fournisseurs compatibles avec l'API Chat Completions ou l'API Responses (ex. DeepSeek, Kimi, MiniMax) peuvent être utilisés",+ "apiProviderTip": "Sélectionnez le type d’API pris en charge par chaque fournisseur","skip": "Passer","nextRound": "Prochain tour","save": "Sauvegarder",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 7e4e8d5132..f191055e9c 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "API ההודעות של Anthropic","encryptedAssetExternalOpenTip": "ייפתח עותק זמני מפוענח. השינויים לא יישמרו בקובץ המצורף המקורי. העותק עשוי להימחק בעת נעילת המחברת. כדי לשמור את השינויים, יש לשמור את הקובץ במיקום אחר.","linuxInputMethod": "מצב תאימות לשיטות קלט ב־Linux","linuxInputMethodTip": "שימוש ב־X11/XWayland לשיפור תאימות שיטות הקלט; עשוי להשפיע על קנה המידה של התצוגה, חל על כל סביבות העבודה במכשיר זה ונכנס לתוקף לאחר סגירה מלאה והפעלה מחדש של SiYuan",@@ -1499,7 +1500,7 @@"apiVersion": "גרסת API","apiVersionTip": "נדרש רק כשמשתמשים בשירות Azure OpenAI","apiProvider": "ספק API",- "apiProviderTip": "ניתן להשתמש בספקים התואמים ל-Chat Completions API או Responses API (למשל DeepSeek, Kimi, MiniMax)",+ "apiProviderTip": "בחרו את סוג ה־API הנתמך על ידי כל ספק","skip": "דלג","nextRound": "סיבוב הבא","save": "שמור",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 8b877cbf5b..a972aa5d6a 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "Anthropic Messages एपीआई","encryptedAssetExternalOpenTip": "एक अस्थायी डिक्रिप्ट की गई प्रतिलिपि खुलेगी। बदलाव मूल संलग्नक में सहेजे नहीं जाएँगे। नोटबुक लॉक होने पर यह प्रतिलिपि हटाई जा सकती है। बदलाव बनाए रखने के लिए फ़ाइल को किसी अन्य स्थान पर सहेजें।","linuxInputMethod": "Linux इनपुट विधि संगतता मोड","linuxInputMethodTip": "इनपुट विधि की संगतता सुधारने के लिए X11/XWayland का उपयोग करें; इससे स्क्रीन स्केलिंग प्रभावित हो सकती है, यह इस डिवाइस के सभी कार्यस्थानों पर लागू होता है और SiYuan को पूरी तरह बंद करके दोबारा शुरू करने के बाद प्रभावी होता है",@@ -1499,7 +1500,7 @@"apiVersion": "API संस्करण","apiVersionTip": "केवल Azure OpenAI सेवा का उपयोग करते समय आवश्यक","apiProvider": "API प्रदाता",- "apiProviderTip": "Chat Completions API या Responses API के साथ संगत प्रदाताओं (जैसे DeepSeek, Kimi, MiniMax) का उपयोग किया जा सकता है",+ "apiProviderTip": "हर प्रदाता द्वारा समर्थित एपीआई प्रकार चुनें","skip": "छोड़ें","nextRound": "अगला दौर","save": "सहेजें",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 3ebc1dde41..d8592e5e2d 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "API Pesan Anthropic","encryptedAssetExternalOpenTip": "Salinan sementara yang telah didekripsi akan dibuka. Perubahan tidak akan disimpan ke lampiran asli. Salinan dapat dihapus saat buku catatan dikunci. Untuk mempertahankan perubahan, simpan berkas ke lokasi lain.","linuxInputMethod": "Mode kompatibilitas metode masukan Linux","linuxInputMethodTip": "Gunakan X11/XWayland untuk meningkatkan kompatibilitas metode masukan; dapat memengaruhi skala tampilan, berlaku untuk semua ruang kerja di perangkat ini, dan aktif setelah SiYuan ditutup sepenuhnya lalu dimulai ulang",@@ -1499,7 +1500,7 @@"apiVersion": "Versi API","apiVersionTip": "Hanya diperlukan saat menggunakan layanan Azure OpenAI","apiProvider": "Penyedia API",- "apiProviderTip": "Penyedia yang kompatibel dengan API Chat Completions atau API Responses (mis., DeepSeek, Kimi, MiniMax) dapat digunakan",+ "apiProviderTip": "Pilih jenis API yang didukung oleh setiap penyedia","skip": "Lewati","nextRound": "Putaran berikutnya","save": "Simpan",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex a2445fc55a..d94f10d377 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "API Messaggi di Anthropic","encryptedAssetExternalOpenTip": "Verrà aperta una copia temporanea decrittografata. Le modifiche non verranno salvate nell’allegato originale. La copia potrebbe essere eliminata quando il quaderno viene bloccato. Per conservare le modifiche, salvare il file in un’altra posizione.","linuxInputMethod": "Modalità di compatibilità dei metodi di input Linux","linuxInputMethodTip": "Usa X11/XWayland per migliorare la compatibilità dei metodi di input; può influire sul ridimensionamento, si applica a tutti gli spazi di lavoro su questo dispositivo e richiede la chiusura completa e il riavvio di SiYuan",@@ -1499,7 +1500,7 @@"apiVersion": "Versione API","apiVersionTip": "Necessario solo quando si utilizza il servizio Azure OpenAI","apiProvider": "Provider API",- "apiProviderTip": "I provider compatibili con l'API Chat Completions o l'API Responses (es. DeepSeek, Kimi, MiniMax) possono essere utilizzati",+ "apiProviderTip": "Seleziona il tipo di API supportato da ciascun fornitore","skip": "Salta","nextRound": "Prossimo turno","save": "Salva",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 0ba3a45a0e..0bd7bddd0c 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "Anthropic Messages API","encryptedAssetExternalOpenTip": "一時的に復号したコピーを開きます。変更は元の添付ファイルには保存されません。ノートブックをロックすると、コピーが削除される場合があります。変更を保持するには、別の場所に保存してください。","linuxInputMethod": "Linux 入力メソッド互換モード","linuxInputMethodTip": "X11/XWayland を使用して入力メソッドの互換性を改善します。表示倍率に影響する場合があります。この端末のすべてのワークスペースに適用され、SiYuan を完全に終了して再起動すると有効になります",@@ -1499,7 +1500,7 @@"apiVersion": "API バージョン","apiVersionTip": "Azure OpenAI サービスを使用する場合にのみ必要です","apiProvider": "API プロバイダー",- "apiProviderTip": "Chat Completions API または Responses API と互換性のあるプロバイダー(DeepSeek、Kimi、MiniMax など)を利用できます",+ "apiProviderTip": "各プロバイダーがサポートする API タイプを選択してください","skip": "スキップ","nextRound": "次のラウンド","save": "保存",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex cce759ad32..1c41ef8892 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "Anthropic Messages API","encryptedAssetExternalOpenTip": "임시로 복호화된 사본을 엽니다. 변경 사항은 원본 첨부 파일에 저장되지 않습니다. 노트북을 잠그면 사본이 삭제될 수 있습니다. 변경 사항을 유지하려면 파일을 다른 위치에 저장하세요.","linuxInputMethod": "Linux 입력기 호환 모드","linuxInputMethodTip": "X11/XWayland를 사용하여 입력기 호환성을 개선합니다. 화면 배율에 영향을 줄 수 있으며 이 기기의 모든 작업 공간에 적용됩니다. SiYuan을 완전히 종료한 후 다시 시작하면 적용됩니다",@@ -1499,7 +1500,7 @@"apiVersion": "API 버전","apiVersionTip": "Azure OpenAI 서비스를 사용할 때만 필요합니다","apiProvider": "API 제공자",- "apiProviderTip": "Chat Completions API 또는 Responses API와 호환되는 제공자(예: DeepSeek, Kimi, MiniMax)를 사용할 수 있습니다",+ "apiProviderTip": "각 제공업체에서 지원하는 API 유형을 선택하세요","skip": "건너뛰기","nextRound": "다음 라운드","save": "저장",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex e07ccac3a7..0482748fc6 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "Anthropic Messages-API","encryptedAssetExternalOpenTip": "Er wordt een tijdelijke ontsleutelde kopie geopend. Wijzigingen worden niet opgeslagen in de oorspronkelijke bijlage. De kopie kan worden verwijderd wanneer het notitieboek wordt vergrendeld. Sla het bestand op een andere locatie op om uw wijzigingen te behouden.","linuxInputMethod": "Compatibiliteitsmodus voor Linux-invoermethoden","linuxInputMethodTip": "Gebruik X11/XWayland om de compatibiliteit van invoermethoden te verbeteren; kan de beeldschermschaal beïnvloeden, geldt voor alle werkruimten op dit apparaat en wordt actief nadat SiYuan volledig is afgesloten en opnieuw gestart",@@ -1499,7 +1500,7 @@"apiVersion": "API-versie","apiVersionTip": "Alleen nodig voor Azure OpenAI","apiProvider": "API-provider",- "apiProviderTip": "Providers die compatibel zijn met de Chat Completions API of de Responses API (bijv. DeepSeek, Kimi, MiniMax) kunnen worden gebruikt",+ "apiProviderTip": "Selecteer het API-type dat door elke provider wordt ondersteund","skip": "Overslaan","nextRound": "Volgende ronde","save": "Opslaan",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 39e11d870a..7a3284f53a 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "API wiadomości Anthropic","encryptedAssetExternalOpenTip": "Zostanie otwarta tymczasowa odszyfrowana kopia. Zmiany nie zostaną zapisane w oryginalnym załączniku. Kopia może zostać usunięta po zablokowaniu notatnika. Aby zachować zmiany, zapisz plik w innym miejscu.","linuxInputMethod": "Tryb zgodności metod wprowadzania w systemie Linux","linuxInputMethodTip": "Używaj X11/XWayland, aby poprawić zgodność metod wprowadzania; może wpływać na skalowanie ekranu, dotyczy wszystkich przestrzeni roboczych na tym urządzeniu i wymaga całkowitego zamknięcia oraz ponownego uruchomienia SiYuan",@@ -1499,7 +1500,7 @@"apiVersion": "Wersja API","apiVersionTip": "Wymagane tylko podczas korzystania z usługi Azure OpenAI","apiProvider": "Dostawca API",- "apiProviderTip": "Dostawcy zgodni z API Chat Completions lub API Responses (np. DeepSeek, Kimi, MiniMax) mogą być używani",+ "apiProviderTip": "Wybierz typ API obsługiwany przez każdego dostawcę","skip": "Pomiń","nextRound": "Następna runda","save": "Zapisz",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 3b790300e7..28114d0da6 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "API de mensagens da Anthropic","encryptedAssetExternalOpenTip": "Será aberta uma cópia temporária descriptografada. As alterações não serão salvas no anexo original. A cópia poderá ser removida quando o caderno for bloqueado. Para manter as alterações, salve o arquivo em outro local.","linuxInputMethod": "Modo de compatibilidade dos métodos de entrada do Linux","linuxInputMethodTip": "Usar X11/XWayland para melhorar a compatibilidade dos métodos de entrada; pode afetar a escala da tela, aplica-se a todos os espaços de trabalho neste dispositivo e exige encerrar completamente e reiniciar o SiYuan",@@ -1499,7 +1500,7 @@"apiVersion": "Versão da API","apiVersionTip": "Obrigatório apenas ao usar o serviço Azure OpenAI","apiProvider": "Provedor da API",- "apiProviderTip": "Provedores compatíveis com a API Chat Completions ou a API Responses (ex. DeepSeek, Kimi, MiniMax) podem ser usados",+ "apiProviderTip": "Selecione o tipo de API compatível com cada provedor","skip": "Pular","nextRound": "Próxima rodada","save": "Salvar",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 8d93ad5078..12ee293557 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "API сообщений Anthropic","encryptedAssetExternalOpenTip": "Будет открыта временная расшифрованная копия. Изменения не сохранятся в исходном вложении. При блокировке блокнота копия может быть удалена. Чтобы сохранить изменения, сохраните файл в другом месте.","linuxInputMethod": "Режим совместимости методов ввода Linux","linuxInputMethodTip": "Использовать X11/XWayland для улучшения совместимости методов ввода; может влиять на масштабирование экрана, применяется ко всем рабочим пространствам на этом устройстве и вступает в силу после полного закрытия и перезапуска SiYuan",@@ -1499,7 +1500,7 @@"apiVersion": "Версия API","apiVersionTip": "Требуется только при использовании службы Azure OpenAI","apiProvider": "Поставщик API",- "apiProviderTip": "Поставщики, совместимые с Chat Completions API или Responses API (например, DeepSeek, Kimi, MiniMax), могут использоваться",+ "apiProviderTip": "Выберите тип API, поддерживаемый каждым провайдером","skip": "Пропустить","nextRound": "Следующий круг","save": "Сохранить",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 1f92a8b96a..f729d24094 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "API správ Anthropic","encryptedAssetExternalOpenTip": "Otvorí sa dočasná dešifrovaná kópia. Zmeny sa neuložia do pôvodnej prílohy. Kópia môže byť odstránená pri uzamknutí zápisníka. Ak chcete zachovať zmeny, uložte súbor na iné miesto.","linuxInputMethod": "Režim kompatibility vstupných metód systému Linux","linuxInputMethodTip": "Použiť X11/XWayland na zlepšenie kompatibility vstupných metód; môže ovplyvniť mierku zobrazenia, platí pre všetky pracovné priestory na tomto zariadení a prejaví sa po úplnom ukončení a opätovnom spustení SiYuan",@@ -1499,7 +1500,7 @@"apiVersion": "Verzia API","apiVersionTip": "Vyžadované len pre Azure OpenAI","apiProvider": "Poskytovateľ API",- "apiProviderTip": "Poskytovatelia kompatibilní s Chat Completions API alebo Responses API (napr. DeepSeek, Kimi, MiniMax) môžu byť použité",+ "apiProviderTip": "Vyberte typ API podporovaný jednotlivými poskytovateľmi","skip": "Preskočiť","nextRound": "Ďalšie kolo","save": "Uložiť",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex ec4c17049b..e5c6b10920 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "Anthropic API за поруке","encryptedAssetExternalOpenTip": "Отвориће се привремена дешифрована копија. Измене неће бити сачуване у оригиналном прилогу. Копија може бити обрисана када се бележница закључа. Да бисте задржали измене, сачувајте датотеку на другом месту.","linuxInputMethod": "Режим компатибилности метода уноса за Linux","linuxInputMethodTip": "Користи X11/XWayland за бољу компатибилност метода уноса; може утицати на скалирање приказа, важи за све радне просторе на овом уређају и примењује се након потпуног затварања и поновног покретања SiYuan-а",@@ -1499,7 +1500,7 @@"apiVersion": "Verzija API-ja","apiVersionTip": "Potrebno samo pri korišćenju Azure OpenAI usluge","apiProvider": "API provajder",- "apiProviderTip": "Podržani su provajderi kompatibilni sa Chat Completions API-jem ili Responses API-jem (na primer DeepSeek, Kimi, MiniMax)",+ "apiProviderTip": "Изаберите тип API-ја који подржава сваки добављач","skip": "Preskoči","nextRound": "Sledeći krug","save": "Sačuvaj",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 257079e9a5..073faaa241 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "API ข้อความ Anthropic","encryptedAssetExternalOpenTip": "จะเปิดสำเนาชั่วคราวที่ถอดรหัสแล้ว การเปลี่ยนแปลงจะไม่ถูกบันทึกลงในไฟล์แนบต้นฉบับ สำเนาอาจถูกลบเมื่อล็อกสมุดบันทึก หากต้องการเก็บการเปลี่ยนแปลงไว้ โปรดบันทึกไฟล์ไปยังตำแหน่งอื่น","linuxInputMethod": "โหมดความเข้ากันได้ของวิธีป้อนข้อมูลบน Linux","linuxInputMethodTip": "ใช้ X11/XWayland เพื่อปรับปรุงความเข้ากันได้ของวิธีป้อนข้อมูล อาจส่งผลต่อการปรับขนาดหน้าจอ มีผลกับพื้นที่ทำงานทั้งหมดบนอุปกรณ์นี้ และมีผลหลังจากปิด SiYuan อย่างสมบูรณ์แล้วเปิดใหม่",@@ -1499,7 +1500,7 @@"apiVersion": "เวอร์ชัน API","apiVersionTip": "เฉพาะ Azure OpenAI","apiProvider": "ผู้ให้ API",- "apiProviderTip": "สามารถใช้ผู้ให้บริการที่รองรับ Chat Completions API หรือ Responses API (เช่น DeepSeek, Kimi, MiniMax) ได้",+ "apiProviderTip": "เลือกประเภท API ที่ผู้ให้บริการแต่ละรายรองรับ","skip": "ข้าม","nextRound": "รอบถัดไป","save": "บันทึก",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex cbbb490b34..e64b0af1f0 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "Anthropic Mesajlar API’si","encryptedAssetExternalOpenTip": "Geçici olarak şifresi çözülmüş bir kopya açılacak. Değişiklikler özgün eke kaydedilmeyecek. Not defteri kilitlendiğinde kopya silinebilir. Değişikliklerinizi korumak için dosyayı başka bir konuma kaydedin.","linuxInputMethod": "Linux giriş yöntemi uyumluluk modu","linuxInputMethodTip": "Giriş yöntemi uyumluluğunu iyileştirmek için X11/XWayland kullanır; ekran ölçeklendirmesini etkileyebilir, bu cihazdaki tüm çalışma alanlarına uygulanır ve SiYuan tamamen kapatılıp yeniden başlatıldığında etkinleşir",@@ -1499,7 +1500,7 @@"apiVersion": "API sürümü","apiVersionTip": "Yalnızca Azure OpenAI hizmeti kullanıldığında gereklidir","apiProvider": "API Sağlayıcısı",- "apiProviderTip": "Chat Completions API veya Responses API ile uyumlu sağlayıcılar (örn. DeepSeek, Kimi, MiniMax) kullanılabilir",+ "apiProviderTip": "Her sağlayıcının desteklediği API türünü seçin","skip": "Geç","nextRound": "Sonraki tur","save": "Kaydet",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex ce32b5bf19..dbeb849a42 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "API повідомлень Anthropic","encryptedAssetExternalOpenTip": "Буде відкрито тимчасову розшифровану копію. Зміни не збережуться у вихідному вкладенні. Після блокування записника копію може бути видалено. Щоб зберегти зміни, збережіть файл в іншому місці.","linuxInputMethod": "Режим сумісності методів введення Linux","linuxInputMethodTip": "Використовувати X11/XWayland для покращення сумісності методів введення; може впливати на масштабування екрана, застосовується до всіх робочих просторів на цьому пристрої та набуває чинності після повного закриття й перезапуску SiYuan",@@ -1499,7 +1500,7 @@"apiVersion": "Версія API","apiVersionTip": "Потрібно лише при використанні Azure OpenAI","apiProvider": "Провайдер API",- "apiProviderTip": "Постачальники, сумісні з Chat Completions API або Responses API (напр. DeepSeek, Kimi, MiniMax), можуть використовуватися",+ "apiProviderTip": "Виберіть тип API, який підтримує кожен постачальник","skip": "Пропустити","nextRound": "Наступний раунд","save": "Зберегти",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex beec00bdef..43bd7139a2 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "Anthropic Messages 接口","encryptedAssetExternalOpenTip": "将打开临时解密副本,修改不会保存到原附件。锁定笔记本后副本可能被清理,如需保留修改,请另存到其他位置。","linuxInputMethod": "Linux 输入法兼容模式","linuxInputMethodTip": "通过 X11/XWayland 改善输入法兼容性,可能影响显示缩放,作用于本机所有工作空间,完全退出并重新启动思源后生效",@@ -1499,7 +1500,7 @@"apiVersion": "API 版本","apiVersionTip": "仅在使用 Azure OpenAI 服务时需要设置","apiProvider": "API 提供商",- "apiProviderTip": "兼容 Chat Completions API 或 Responses API 接口的提供商(如 DeepSeek、Kimi、MiniMax)均可使用",+ "apiProviderTip": "为每个提供商选择其支持的 API 类型","skip": "跳过","nextRound": "下一轮","save": "保存",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex a3ff21f943..f9765ccf10 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,5 @@{+ "apiTypeAnthropicMessages": "Anthropic Messages 介面","encryptedAssetExternalOpenTip": "將開啟暫時解密的副本,修改不會儲存至原附件。鎖定筆記本後副本可能會被清除,如需保留修改,請另存至其他位置。","linuxInputMethod": "Linux 輸入法相容模式","linuxInputMethodTip": "透過 X11/XWayland 改善輸入法相容性,可能影響顯示縮放,套用至本機所有工作空間,完全結束並重新啟動思源後生效",@@ -1499,7 +1500,7 @@"apiVersion": "API 版本","apiVersionTip": "僅在使用 Azure OpenAI 服務時需要設定","apiProvider": "API 提供商",- "apiProviderTip": "相容 Chat Completions API 或 Responses API 介面的提供商(如 DeepSeek、Kimi、MiniMax)均可使用",+ "apiProviderTip": "為每個供應商選擇其支援的 API 類型","skip": "跳過","nextRound": "下一輪","save": "保存",diff --git a/app/src/config/tabs/ai/aiProviderPresets.test.ts b/app/src/config/tabs/ai/aiProviderPresets.test.tsindex cc4f1bd26e..2342b96951 100644--- a/app/src/config/tabs/ai/aiProviderPresets.test.ts+++ b/app/src/config/tabs/ai/aiProviderPresets.test.ts@@ -21,6 +21,14 @@ describe("AI provider presets", () => {assert.equal(getDefaultProviderProtocol("custom"), "openai");});+ it("selects Messages for the Anthropic preset without changing custom provider defaults", () => {+ assert.equal(getDefaultProviderProtocol("anthropic"), "anthropic-messages");+ assert.equal(findProviderPreset("https://api.anthropic.com/v1/")?.id, "anthropic");+ assert.equal(getResponsesSupport("https://api.anthropic.com/v1"), "unsupported");+ assert.equal(getDefaultProviderProtocol("custom"), "openai");+ assert.equal(getDefaultProviderProtocol("openai"), "openai-responses");+ });+it("reports known and custom Responses compatibility", () => {assert.equal(getResponsesSupport("https://api.deepseek.com"), "supported");assert.equal(getResponsesSupport("https://open.bigmodel.cn/api/paas/v4"), "unsupported");diff --git a/app/src/config/tabs/ai/aiProviderPresets.ts b/app/src/config/tabs/ai/aiProviderPresets.tsindex 1d0189ab24..c03a782661 100644--- a/app/src/config/tabs/ai/aiProviderPresets.ts+++ b/app/src/config/tabs/ai/aiProviderPresets.ts@@ -13,6 +13,7 @@ export interface IProviderPreset {export const PROVIDER_PRESETS: IProviderPreset[] = [{id: "openai", name: "OpenAI", baseURL: "https://api.openai.com/v1", category: "official", responsesSupport: "supported", icon: "/stage/images/ai-providers/openai.svg"},+ {id: "anthropic", name: "Anthropic", baseURL: "https://api.anthropic.com/v1", category: "official", responsesSupport: "unsupported"},{id: "deepseek", name: "DeepSeek", baseURL: "https://api.deepseek.com", category: "official", responsesSupport: "supported", icon: "/stage/images/ai-providers/deepseek.svg"},{id: "moonshot", name: "Moonshot AI", baseURL: "https://api.moonshot.cn/v1", category: "official", responsesSupport: "experimental", icon: "/stage/images/ai-providers/moonshot.svg"},{id: "minimax", name: "MiniMax", baseURL: "https://api.minimax.io/v1", category: "official", responsesSupport: "experimental", region: "international", icon: "/stage/images/ai-providers/minimax.svg"},@@ -41,4 +42,4 @@ export const getResponsesSupport = (baseURL: string): AIResponsesSupport =>findProviderPreset(baseURL)?.responsesSupport || "experimental";export const getDefaultProviderProtocol = (presetId: string) =>- presetId === "openai" ? "openai-responses" : "openai";+ presetId === "anthropic" ? "anthropic-messages" : presetId === "openai" ? "openai-responses" : "openai";diff --git a/app/src/config/tabs/ai/aiProviderUi.ts b/app/src/config/tabs/ai/aiProviderUi.tsindex 2b31538900..3f8ecc7c96 100644--- a/app/src/config/tabs/ai/aiProviderUi.ts+++ b/app/src/config/tabs/ai/aiProviderUi.ts@@ -129,7 +129,7 @@ const createProviderView = (root: HTMLElement, backLabel: string, stacked = falsexport const genProviderCardsHtml = (): string => `<div class="b3-label config-item" id="aiProviderCardsBlock"><div class="fn__flex">- ${genConfigItemMainHtml(window.siyuan.languages.openAICompatibleProvider, window.siyuan.languages.apiProviderTip)}+ ${genConfigItemMainHtml(window.siyuan.languages.apiProvider, window.siyuan.languages.apiProviderTip)}<span class="fn__space"></span><button class="b3-button b3-button--outline fn__flex-center fn__size200" data-action="addProvider"><svg class="b3-button__icon"><use xlink:href="#iconAdd"></use></svg>@@ -409,6 +409,7 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPr<select class="b3-select fn__flex-center fn__size200" data-provider-field="protocol"><option value="openai"${draft.protocol === "openai" ? " selected" : ""}>Chat Completions API</option><option value="openai-responses"${draft.protocol === "openai-responses" ? " selected" : ""}>Responses API</option>+ <option value="anthropic-messages"${draft.protocol === "anthropic-messages" ? " selected" : ""}>${window.siyuan.languages.apiTypeAnthropicMessages}</option></select></label><label class="fn__flex b3-label config-item">diff --git a/app/src/config/tabs/ai/aiUi.ts b/app/src/config/tabs/ai/aiUi.tsindex a6d3f9fdbd..c845400383 100644--- a/app/src/config/tabs/ai/aiUi.ts+++ b/app/src/config/tabs/ai/aiUi.ts@@ -17,7 +17,7 @@ type ModelPickerGroup = "editing" | "agent" | "imageGeneration";export const getProvidersBlockKeywords = (): string[] => [window.siyuan.languages.apiKeyRequired,window.siyuan.languages.apiProvider,- window.siyuan.languages.openAICompatibleProvider,+ window.siyuan.languages.apiTypeAnthropicMessages,window.siyuan.languages.apiProviderTip,window.siyuan.languages.aiProviderOfficial,window.siyuan.languages.aiProviderAggregator,diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.tsindex 525de4689b..3c57a53ffc 100644--- a/app/src/layout/dock/agent/AgentChat.ts+++ b/app/src/layout/dock/agent/AgentChat.ts@@ -107,6 +107,7 @@ type SessionEntry =type: "assistant";content?: string;reasoningContent?: string;+ nativeContent?: {protocol: string; version: number; blocks: Array<Record<string, unknown>>};responseOutput?: Array<Record<string, unknown>>;responseOutputTokens?: number;roundID?: string;diff --git a/app/src/layout/dock/agent/SessionStore.ts b/app/src/layout/dock/agent/SessionStore.tsindex f6f88b240f..47aa09ab15 100644--- a/app/src/layout/dock/agent/SessionStore.ts+++ b/app/src/layout/dock/agent/SessionStore.ts@@ -80,6 +80,7 @@ export interface AgentSession {toolCalls?: Array<{name: string; result?: string}>}>;reasoningContent?: string;+ nativeContent?: {protocol: string; version: number; blocks: Array<Record<string, unknown>>};responseOutput?: Array<Record<string, unknown>>;responseOutputTokens?: number;roundID?: string;diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 4e07196d12..7a92b1cedc 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -12,9 +12,9 @@ export type AIAgentGoogleToolCallProviderData = { "thoughtSignature"?: string; }export type AIAgentGoogleToolCallProviderDataInput = { "thoughtSignature"?: string | null; };-export type AIAgentMessage = { "content": string; "editorContext"?: AIEditorContext; "entryID"?: string; "reasoningContent"?: string; "references"?: Array<AIReference>; "responseOutput"?: Array<JSONValue>; "responseOutputTokens"?: number; "role": string; "roundID"?: string; "toolCalls"?: Array<AIAgentToolCall>; };+export type AIAgentMessage = { "content": string; "editorContext"?: AIEditorContext; "entryID"?: string; "nativeContent"?: AINativeContent; "reasoningContent"?: string; "references"?: Array<AIReference>; "responseOutput"?: Array<JSONValue>; "responseOutputTokens"?: number; "role": string; "roundID"?: string; "toolCalls"?: Array<AIAgentToolCall>; };-export type AIAgentMessageInput = { "content"?: string | null; "editorContext"?: AIEditorContextInput | null; "entryID"?: string | null; "reasoningContent"?: string | null; "references"?: Array<AIReferenceInput> | null; "responseOutput"?: Array<JSONValue> | null; "responseOutputTokens"?: number | null; "role"?: string | null; "roundID"?: string | null; "toolCalls"?: Array<AIAgentToolCallInput> | null; };+export type AIAgentMessageInput = { "content"?: string | null; "editorContext"?: AIEditorContextInput | null; "entryID"?: string | null; "nativeContent"?: AINativeContentInput | null; "reasoningContent"?: string | null; "references"?: Array<AIReferenceInput> | null; "responseOutput"?: Array<JSONValue> | null; "responseOutputTokens"?: number | null; "role"?: string | null; "roundID"?: string | null; "toolCalls"?: Array<AIAgentToolCallInput> | null; };export type AIAgentToolCall = { "arguments": { [key: string]: JSONValue } | null; "argumentsJSON"?: string; "attachments"?: Array<AIAgentAttachment>; "id"?: string; "name": string; "providerData"?: AIAgentToolCallProviderData; "result"?: string; "state"?: string; };@@ -66,6 +66,10 @@ export type AIModelTestData = { "available": Array<string> | null; "matched": boexport type AIModelsData = { "contextLengths": Record<string, number> | null; "models": Array<string> | null; "msg"?: string; };+export type AINativeContent = { "blocks": Array<JSONValue> | null; "protocol": string; "version": number; };++export type AINativeContentInput = { "blocks": Array<JSONValue>; "protocol": string; "version": number; };+export type AIPermissionData = { "permissionMode": string; };export type AIPermissionRequestInput = { "permissionMode"?: string | null; "sessionID"?: string | null; };@@ -108,9 +112,9 @@ export type AISSETurn = { "turnID": string; };export type AISSEUsage = { "cachedTokens": number; "completionTokens": number; "contextLimit": number; "lastPromptTokens": number; "promptTokens": number; "tokenBreakdown": Record<string, number> | null; };-export type AISessionEntry = { "answers"?: Array<string>; "args"?: { [key: string]: JSONValue }; "blockHTML"?: string; "completionTokens"?: number; "confirmID"?: string; "content"?: string; "duration"?: number; "editorContext"?: AIEditorContext; "id"?: string; "name"?: string; "promptTokens"?: number; "questionID"?: string; "questions"?: Array<{ [key: string]: JSONValue } | null>; "reasoningContent"?: string; "references"?: Array<AIReference>; "responseOutput"?: Array<JSONValue>; "responseOutputTokens"?: number; "roundID"?: string; "snapshotID"?: string; "status"?: string; "steps"?: Array<AISessionEntryStep>; "timestamp"?: number; "toolCalls"?: Array<AIAgentToolCall>; "type": string; };+export type AISessionEntry = { "answers"?: Array<string>; "args"?: { [key: string]: JSONValue }; "blockHTML"?: string; "completionTokens"?: number; "confirmID"?: string; "content"?: string; "duration"?: number; "editorContext"?: AIEditorContext; "id"?: string; "name"?: string; "nativeContent"?: AINativeContent; "promptTokens"?: number; "questionID"?: string; "questions"?: Array<{ [key: string]: JSONValue } | null>; "reasoningContent"?: string; "references"?: Array<AIReference>; "responseOutput"?: Array<JSONValue>; "responseOutputTokens"?: number; "roundID"?: string; "snapshotID"?: string; "status"?: string; "steps"?: Array<AISessionEntryStep>; "timestamp"?: number; "toolCalls"?: Array<AIAgentToolCall>; "type": string; };-export type AISessionEntryInput = { "answers"?: Array<string> | null; "args"?: { [key: string]: JSONValue } | null; "blockHTML"?: string | null; "completionTokens"?: number | null; "confirmID"?: string | null; "content"?: string | null; "duration"?: number | null; "editorContext"?: AIEditorContextInput | null; "id"?: string | null; "name"?: string | null; "promptTokens"?: number | null; "questionID"?: string | null; "questions"?: Array<{ [key: string]: JSONValue } | null> | null; "reasoningContent"?: string | null; "references"?: Array<AIReferenceInput> | null; "responseOutput"?: Array<JSONValue> | null; "responseOutputTokens"?: number | null; "roundID"?: string | null; "snapshotID"?: string | null; "status"?: string | null; "steps"?: Array<AISessionEntryStepInput> | null; "timestamp"?: number | null; "toolCalls"?: Array<AIAgentToolCallInput> | null; "type"?: string | null; };+export type AISessionEntryInput = { "answers"?: Array<string> | null; "args"?: { [key: string]: JSONValue } | null; "blockHTML"?: string | null; "completionTokens"?: number | null; "confirmID"?: string | null; "content"?: string | null; "duration"?: number | null; "editorContext"?: AIEditorContextInput | null; "id"?: string | null; "name"?: string | null; "nativeContent"?: AINativeContentInput | null; "promptTokens"?: number | null; "questionID"?: string | null; "questions"?: Array<{ [key: string]: JSONValue } | null> | null; "reasoningContent"?: string | null; "references"?: Array<AIReferenceInput> | null; "responseOutput"?: Array<JSONValue> | null; "responseOutputTokens"?: number | null; "roundID"?: string | null; "snapshotID"?: string | null; "status"?: string | null; "steps"?: Array<AISessionEntryStepInput> | null; "timestamp"?: number | null; "toolCalls"?: Array<AIAgentToolCallInput> | null; "type"?: string | null; };export type AISessionEntryStep = { "content"?: string; "reasoning": string; "reasoningContent"?: string; "roundID"?: string; "toolCallIDs"?: Array<string>; "toolNames"?: Array<string>; };@@ -124,9 +128,9 @@ export type AISessionExtensionAIAgentGoogleToolCallProviderData = ({ "thoughtSigexport type AISessionExtensionAIAgentGoogleToolCallProviderDataInput = ({ "thoughtSignature"?: string | null; } & { [key: string]: JSONValue });-export type AISessionExtensionAIAgentMessage = ({ "content"?: string | null; "editorContext"?: AISessionExtensionAIEditorContext | null; "entryID"?: string | null; "reasoningContent"?: string | null; "references"?: Array<AISessionExtensionAIReference> | null; "responseOutput"?: Array<JSONValue> | null; "responseOutputTokens"?: number | null; "role"?: string | null; "roundID"?: string | null; "toolCalls"?: Array<AISessionExtensionAIAgentToolCall> | null; } & { [key: string]: JSONValue });+export type AISessionExtensionAIAgentMessage = ({ "content"?: string | null; "editorContext"?: AISessionExtensionAIEditorContext | null; "entryID"?: string | null; "nativeContent"?: AISessionExtensionAINativeContent | null; "reasoningContent"?: string | null; "references"?: Array<AISessionExtensionAIReference> | null; "responseOutput"?: Array<JSONValue> | null; "responseOutputTokens"?: number | null; "role"?: string | null; "roundID"?: string | null; "toolCalls"?: Array<AISessionExtensionAIAgentToolCall> | null; } & { [key: string]: JSONValue });-export type AISessionExtensionAIAgentMessageInput = ({ "content"?: string | null; "editorContext"?: AISessionExtensionAIEditorContextInput | null; "entryID"?: string | null; "reasoningContent"?: string | null; "references"?: Array<AISessionExtensionAIReferenceInput> | null; "responseOutput"?: Array<JSONValue> | null; "responseOutputTokens"?: number | null; "role"?: string | null; "roundID"?: string | null; "toolCalls"?: Array<AISessionExtensionAIAgentToolCallInput> | null; } & { [key: string]: JSONValue });+export type AISessionExtensionAIAgentMessageInput = ({ "content"?: string | null; "editorContext"?: AISessionExtensionAIEditorContextInput | null; "entryID"?: string | null; "nativeContent"?: AISessionExtensionAINativeContentInput | null; "reasoningContent"?: string | null; "references"?: Array<AISessionExtensionAIReferenceInput> | null; "responseOutput"?: Array<JSONValue> | null; "responseOutputTokens"?: number | null; "role"?: string | null; "roundID"?: string | null; "toolCalls"?: Array<AISessionExtensionAIAgentToolCallInput> | null; } & { [key: string]: JSONValue });export type AISessionExtensionAIAgentToolCall = ({ "arguments"?: { [key: string]: JSONValue } | null; "argumentsJSON"?: string | null; "attachments"?: Array<AISessionExtensionAIAgentAttachment> | null; "id"?: string | null; "name"?: string | null; "providerData"?: AISessionExtensionAIAgentToolCallProviderData | null; "result"?: string | null; "state"?: string | null; } & { [key: string]: JSONValue });@@ -140,13 +144,17 @@ export type AISessionExtensionAIEditorContext = ({ "activeDocID"?: string | nullexport type AISessionExtensionAIEditorContextInput = ({ "activeDocID"?: string | null; "activeDocTitle"?: string | null; "focusedBlockID"?: string | null; "notebookID"?: string | null; "selectedBlockIDs"?: Array<string> | null; "visibleBlockIDs"?: Array<string> | null; } & { [key: string]: JSONValue });+export type AISessionExtensionAINativeContent = ({ "blocks"?: Array<JSONValue> | null; "protocol"?: string | null; "version"?: number | null; } & { [key: string]: JSONValue });++export type AISessionExtensionAINativeContentInput = ({ "blocks"?: Array<JSONValue> | null; "protocol"?: string | null; "version"?: number | null; } & { [key: string]: JSONValue });+export type AISessionExtensionAIReference = ({ "id"?: string | null; "title"?: string | null; } & { [key: string]: JSONValue });export type AISessionExtensionAIReferenceInput = ({ "id"?: string | null; "title"?: string | null; } & { [key: string]: JSONValue });-export type AISessionExtensionAISessionEntry = ({ "answers"?: Array<string> | null; "args"?: { [key: string]: JSONValue } | null; "blockHTML"?: string | null; "completionTokens"?: number | null; "confirmID"?: string | null; "content"?: string | null; "duration"?: number | null; "editorContext"?: AISessionExtensionAIEditorContext | null; "id"?: string | null; "name"?: string | null; "promptTokens"?: number | null; "questionID"?: string | null; "questions"?: Array<{ [key: string]: JSONValue } | null> | null; "reasoningContent"?: string | null; "references"?: Array<AISessionExtensionAIReference> | null; "responseOutput"?: Array<JSONValue> | null; "responseOutputTokens"?: number | null; "roundID"?: string | null; "snapshotID"?: string | null; "status"?: string | null; "steps"?: Array<AISessionExtensionAISessionEntryStep> | null; "timestamp"?: number | null; "toolCalls"?: Array<AISessionExtensionAIAgentToolCall> | null; "type"?: string | null; } & { [key: string]: JSONValue });+export type AISessionExtensionAISessionEntry = ({ "answers"?: Array<string> | null; "args"?: { [key: string]: JSONValue } | null; "blockHTML"?: string | null; "completionTokens"?: number | null; "confirmID"?: string | null; "content"?: string | null; "duration"?: number | null; "editorContext"?: AISessionExtensionAIEditorContext | null; "id"?: string | null; "name"?: string | null; "nativeContent"?: AISessionExtensionAINativeContent | null; "promptTokens"?: number | null; "questionID"?: string | null; "questions"?: Array<{ [key: string]: JSONValue } | null> | null; "reasoningContent"?: string | null; "references"?: Array<AISessionExtensionAIReference> | null; "responseOutput"?: Array<JSONValue> | null; "responseOutputTokens"?: number | null; "roundID"?: string | null; "snapshotID"?: string | null; "status"?: string | null; "steps"?: Array<AISessionExtensionAISessionEntryStep> | null; "timestamp"?: number | null; "toolCalls"?: Array<AISessionExtensionAIAgentToolCall> | null; "type"?: string | null; } & { [key: string]: JSONValue });-export type AISessionExtensionAISessionEntryInput = ({ "answers"?: Array<string> | null; "args"?: { [key: string]: JSONValue } | null; "blockHTML"?: string | null; "completionTokens"?: number | null; "confirmID"?: string | null; "content"?: string | null; "duration"?: number | null; "editorContext"?: AISessionExtensionAIEditorContextInput | null; "id"?: string | null; "name"?: string | null; "promptTokens"?: number | null; "questionID"?: string | null; "questions"?: Array<{ [key: string]: JSONValue } | null> | null; "reasoningContent"?: string | null; "references"?: Array<AISessionExtensionAIReferenceInput> | null; "responseOutput"?: Array<JSONValue> | null; "responseOutputTokens"?: number | null; "roundID"?: string | null; "snapshotID"?: string | null; "status"?: string | null; "steps"?: Array<AISessionExtensionAISessionEntryStepInput> | null; "timestamp"?: number | null; "toolCalls"?: Array<AISessionExtensionAIAgentToolCallInput> | null; "type"?: string | null; } & { [key: string]: JSONValue });+export type AISessionExtensionAISessionEntryInput = ({ "answers"?: Array<string> | null; "args"?: { [key: string]: JSONValue } | null; "blockHTML"?: string | null; "completionTokens"?: number | null; "confirmID"?: string | null; "content"?: string | null; "duration"?: number | null; "editorContext"?: AISessionExtensionAIEditorContextInput | null; "id"?: string | null; "name"?: string | null; "nativeContent"?: AISessionExtensionAINativeContentInput | null; "promptTokens"?: number | null; "questionID"?: string | null; "questions"?: Array<{ [key: string]: JSONValue } | null> | null; "reasoningContent"?: string | null; "references"?: Array<AISessionExtensionAIReferenceInput> | null; "responseOutput"?: Array<JSONValue> | null; "responseOutputTokens"?: number | null; "roundID"?: string | null; "snapshotID"?: string | null; "status"?: string | null; "steps"?: Array<AISessionExtensionAISessionEntryStepInput> | null; "timestamp"?: number | null; "toolCalls"?: Array<AISessionExtensionAIAgentToolCallInput> | null; "type"?: string | null; } & { [key: string]: JSONValue });export type AISessionExtensionAISessionEntryStep = ({ "content"?: string | null; "reasoning"?: string | null; "reasoningContent"?: string | null; "roundID"?: string | null; "toolCallIDs"?: Array<string> | null; "toolNames"?: Array<string> | null; } & { [key: string]: JSONValue });diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.tsindex 2642ac9c03..6c1669b1e5 100644--- a/app/src/types/config.d.ts+++ b/app/src/types/config.d.ts@@ -229,6 +229,7 @@ declare namespace Config {enabled: boolean;displayName?: string;baseURL: string;+ /** 生成协议:openai、openai-responses 或 anthropic-messages;省略时使用 openai */protocol?: string;apiKey: string;requestTimeout: number;diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.mdindex 41e38da343..212bacf6ab 100644--- a/docs/API-CONTRACTS.md+++ b/docs/API-CONTRACTS.md@@ -54,6 +54,8 @@ Attribute-view contracts declare table, gallery, and kanban results separately aAI contracts retain provider configuration, model discovery and matching, confirmation decisions, session extensions, and numeric and omission semantics. Editor and agent streams declare their actual SSE events; disconnection closes upstream requests, and stream lifetimes remain within the request. OAuth pages retain their media types, HTTP statuses, and security headers. Session permission notifications use `WithAfterWrite` to preserve response-before-broadcast ordering. Arbitrary JSON remains limited to protocol extension fields and tool results.+AI providers accept `anthropic-messages` alongside `openai` and `openai-responses`; omitted protocols retain the Chat Completions default. Native Messages calls cover model discovery, model tests, editor generation, agent tools, titles, and summary compaction. An automatic output limit uses 4096 tokens because Messages requires `max_tokens`. Assistant entries may carry `nativeContent` with a protocol, version, and opaque content blocks; version 1 preserves Anthropic thinking signatures and block ordering across runtime recovery and session commits. Other protocols project the visible conversation without sending these native blocks. Unknown native versions fail before sending a Messages request, retaining the original session. Stream usage is emitted once after `message_stop`, and incomplete tool responses cannot reach tool execution. `TestAnthropic*` and `TestAPIContractAnthropic*` run in the full kernel CI suite; run the affected subset with `go test -tags "fts5 sqlcipher" ./conf ./util ./agent ./api ./apicontract/... -run 'Test(Anthropic|APIContractAnthropic|APIContractAI|AIInput|AISession|RouteCoverage)' -count=1`, plus `go test ./apicontract/...`. The existing frontend test discovery includes `aiProviderPresets.test.ts`.+`/api/ai/agent/manageSkills` uses strict string fields and administrator/read-only admission for workspace skill files. Relative paths identify physical directories independently of frontmatter names, including ordinary dot-prefixed names. Reads and writes support UTF-8 text up to 8 MiB regardless of extension and preserve source bytes. Directory and resource reads retain content-based revisions; non-editable contents omit `content` and add an optional `readOnlyReason` (`binary`, `encoding`, or `tooLarge`). The read response, rather than a stale list entry, determines editor availability. Existing mutations revalidate content and require the current revision, share a critical section with legacy skill mutations and installation, and notify synchronization after success. Path traversal, platform aliases, links, stale revisions, and individual modification of unsupported contents or renaming/deletion of root `SKILL.md` are rejected. `TestAISkillManagementContract`, `TestAPIContractAISkillManagement`, and `TestSkillManagement` cover request types, actual HTTP responses, authorization, raw content, text classification, hidden paths, concurrent saves, and filesystem boundaries. Run `go test -tags "fts5 sqlcipher" ./apicontract/... ./api ./util -run 'Test(AISkillManagementContract|APIContractAISkillManagement|SkillManagement|RouteCoverage)' -count=1`; the full kernel CI suite below includes all of these regressions.Setting contracts retain partial configuration merging, existing defaults, case-insensitive struct fields, explicit null values, JSON number normalization, and parser error messages. Keyboard shortcuts and cloud authentication results declare their fixed fields while preserving their protocol-defined JSON extensions. Cloud-user admission still precedes body reads for non-administrators, and two-factor authentication keeps cloud error codes and extension fields. Frontend callers normalize persisted display settings at the same existing boundaries.diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex a16938963e..8181d2a26a 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -380,16 +380,17 @@ type AgentEvent struct {}type AgentMessage struct {- Role string `json:"role"`- Content string `json:"content"`- ReasoningContent string `json:"reasoningContent,omitempty"`- ResponseOutput []json.RawMessage `json:"responseOutput,omitempty"`- ResponseOutputTokens int `json:"responseOutputTokens,omitempty"`- RoundID string `json:"roundID,omitempty"`- References []Reference `json:"references,omitempty"`- EditorContext *EditorContext `json:"editorContext,omitempty"`- ToolCalls []AgentToolCall `json:"toolCalls,omitempty"`- EntryID string `json:"entryID,omitempty"`+ Role string `json:"role"`+ Content string `json:"content"`+ ReasoningContent string `json:"reasoningContent,omitempty"`+ NativeContent *util.AIMessageContent `json:"nativeContent,omitempty"`+ ResponseOutput []json.RawMessage `json:"responseOutput,omitempty"`+ ResponseOutputTokens int `json:"responseOutputTokens,omitempty"`+ RoundID string `json:"roundID,omitempty"`+ References []Reference `json:"references,omitempty"`+ EditorContext *EditorContext `json:"editorContext,omitempty"`+ ToolCalls []AgentToolCall `json:"toolCalls,omitempty"`+ EntryID string `json:"entryID,omitempty"`}type AgentToolCall struct {@@ -463,30 +464,31 @@ func newAgentUserMessage(content, entryID string, references []Reference, editor// SessionEntry 与前端 SessionStore.ts 中 entries 元素一一对应,// 是会话持久化的唯一数据源(不再单独持久化 messages)。type SessionEntry struct {- ID string `json:"id,omitempty"`- Type string `json:"type"` // user|thinking|assistant|confirm|snapshot|rollback- Content string `json:"content,omitempty"`- References []Reference `json:"references,omitempty"`- EditorContext *EditorContext `json:"editorContext,omitempty"`- BlockHTML string `json:"blockHTML,omitempty"` // 仅 user,用于保留发送框的 BlockDOM 展示结构- Steps []SessionEntryStep `json:"steps,omitempty"` // 仅 thinking- ToolCalls []AgentToolCall `json:"toolCalls,omitempty"` // 仅 assistant- Duration float64 `json:"duration,omitempty"` // 秒(thinking/assistant 均可能带)- PromptTokens int `json:"promptTokens,omitempty"` // 仅 assistant- CompletionTok int `json:"completionTokens,omitempty"`- Timestamp int64 `json:"timestamp,omitempty"`- ReasoningCont string `json:"reasoningContent,omitempty"`- ResponseOutput []json.RawMessage `json:"responseOutput,omitempty"`- ResponseOutputTokens int `json:"responseOutputTokens,omitempty"`- RoundID string `json:"roundID,omitempty"`- Name string `json:"name,omitempty"`- Args map[string]any `json:"args,omitempty"`- ConfirmID string `json:"confirmID,omitempty"`- Status string `json:"status,omitempty"`- QuestionID string `json:"questionID,omitempty"`- Questions []map[string]any `json:"questions,omitempty"`- Answers []string `json:"answers,omitempty"`- SnapshotID string `json:"snapshotID,omitempty"`+ ID string `json:"id,omitempty"`+ Type string `json:"type"` // user|thinking|assistant|confirm|snapshot|rollback+ Content string `json:"content,omitempty"`+ References []Reference `json:"references,omitempty"`+ EditorContext *EditorContext `json:"editorContext,omitempty"`+ BlockHTML string `json:"blockHTML,omitempty"` // 仅 user,用于保留发送框的 BlockDOM 展示结构+ Steps []SessionEntryStep `json:"steps,omitempty"` // 仅 thinking+ ToolCalls []AgentToolCall `json:"toolCalls,omitempty"` // 仅 assistant+ Duration float64 `json:"duration,omitempty"` // 秒(thinking/assistant 均可能带)+ PromptTokens int `json:"promptTokens,omitempty"` // 仅 assistant+ CompletionTok int `json:"completionTokens,omitempty"`+ Timestamp int64 `json:"timestamp,omitempty"`+ ReasoningCont string `json:"reasoningContent,omitempty"`+ NativeContent *util.AIMessageContent `json:"nativeContent,omitempty"`+ ResponseOutput []json.RawMessage `json:"responseOutput,omitempty"`+ ResponseOutputTokens int `json:"responseOutputTokens,omitempty"`+ RoundID string `json:"roundID,omitempty"`+ Name string `json:"name,omitempty"`+ Args map[string]any `json:"args,omitempty"`+ ConfirmID string `json:"confirmID,omitempty"`+ Status string `json:"status,omitempty"`+ QuestionID string `json:"questionID,omitempty"`+ Questions []map[string]any `json:"questions,omitempty"`+ Answers []string `json:"answers,omitempty"`+ SnapshotID string `json:"snapshotID,omitempty"`}// SessionEntryStep 描述一次思考步骤。工具调用只保留名字与调用 ID 列表,过程正文保存在 Content,@@ -521,7 +523,7 @@ type agentCheckpoint struct {LastCommittedTurnID string `json:"lastCommittedTurnID,omitempty"`}-func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imageCapabilityKey string, contextLimit int,+func AgentChat(ctx context.Context, client *util.AIClient, protocol, 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,@@ -956,7 +958,7 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imag}}stream, firstResp, roundCancel, requestMessages, imageDowngraded, imageUnsupportedDetected, streamErr :=- createProtocolImageCompatibleStream(util.ContextWithGeminiThoughtSummaries(ctx), client, protocol, req,+ createProtocolImageCompatibleStream(contextWithNativeContents(util.ContextWithGeminiThoughtSummaries(ctx), checkpointMsgs), client, protocol, req,responseInput, imageCapabilityKey,imageInputDisabled, maxRetries, requestTimeout, streamIdleTimeout, delayForCategory, ch)if imageUnsupportedDetected {@@ -1120,6 +1122,7 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imag}}+ nativeContent := stream.NativeContent()responseOutput := stream.ResponseOutput()if len(responseOutput) == 0 {responseOutputTokens = 0@@ -1154,6 +1157,7 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imagRole: "assistant",Content: contentBuilder.String(),ReasoningContent: reasoningBuilder.String(),+ NativeContent: nativeContent,ResponseOutput: responseOutput,ResponseOutputTokens: responseOutputTokens,RoundID: roundID,@@ -1520,11 +1524,12 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imag}content := contentBuilder.String()- if content != "" || reasoningBuilder.Len() > 0 || len(responseOutput) > 0 {+ if content != "" || reasoningBuilder.Len() > 0 || len(responseOutput) > 0 || nativeContent != nil {checkpointMsgs = append(checkpointMsgs, AgentMessage{Role: "assistant",Content: content,ReasoningContent: reasoningBuilder.String(),+ NativeContent: nativeContent,ResponseOutput: responseOutput,ResponseOutputTokens: responseOutputTokens,RoundID: roundID,@@ -1559,7 +1564,7 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imagreturn ch}-func GenerateTitle(client *openai.Client, apiBaseURL, protocol, model, userMsg, language string) string {+func GenerateTitle(client *util.AIClient, apiBaseURL, protocol, model, userMsg, language string) string {const (initialMaxCompletionTokens = 50fallbackMaxCompletionTokens = 512@@ -2220,6 +2225,7 @@ func entriesToAgentMessages(entries []SessionEntry) []AgentMessage {Role: "assistant",Content: e.Content,ReasoningContent: e.ReasoningCont,+ NativeContent: util.CloneAIMessageContent(e.NativeContent),ResponseOutput: util.CloneOpenAIResponseOutput(e.ResponseOutput),ResponseOutputTokens: e.ResponseOutputTokens,RoundID: e.RoundID,@@ -2240,6 +2246,16 @@ func entriesToAgentMessages(entries []SessionEntry) []AgentMessage {return msgs}+func contextWithNativeContents(ctx context.Context, messages []AgentMessage) context.Context {+ var contents []*util.AIMessageContent+ for _, message := range messages {+ if message.Role == "assistant" {+ contents = append(contents, message.NativeContent)+ }+ }+ return util.ContextWithAIMessageContents(ctx, contents)+}+func restoreGeminiThoughtSignatures(state *util.GeminiThoughtSignatureState, messages []AgentMessage) {for _, message := range messages {for _, toolCall := range message.ToolCalls {@@ -2499,6 +2515,7 @@ func agentMessagesToEntries(msgs []AgentMessage) []SessionEntry {Type: "assistant",Content: m.Content,ReasoningCont: m.ReasoningContent,+ NativeContent: util.CloneAIMessageContent(m.NativeContent),ResponseOutput: util.CloneOpenAIResponseOutput(m.ResponseOutput),ResponseOutputTokens: m.ResponseOutputTokens,RoundID: m.RoundID,@@ -2515,14 +2532,14 @@ var (errModelStreamIdleTimeout = errors.New("model stream idle timeout"))-func createStreamWithRetry(ctx context.Context, client *openai.Client, req openai.ChatCompletionRequest, maxRetries int,+func createStreamWithRetry(ctx context.Context, client *util.AIClient, req openai.ChatCompletionRequest, maxRetries int,requestTimeout, streamIdleTimeout time.Duration, retryDelay func(string, int) time.Duration,ch chan<- AgentEvent) (*util.OpenAICompletionStream, openai.ChatCompletionStreamResponse, context.CancelFunc, error) {return createProtocolStreamWithRetry(ctx, client, util.OpenAIProtocolChatCompletions, req, nil, maxRetries,requestTimeout, streamIdleTimeout, retryDelay, ch)}-func createProtocolStreamWithRetry(ctx context.Context, client *openai.Client, protocol string,+func createProtocolStreamWithRetry(ctx context.Context, client *util.AIClient, protocol string,req openai.ChatCompletionRequest, responseInput []any, maxRetries int, requestTimeout, streamIdleTimeout time.Duration,retryDelay func(string, int) time.Duration,ch chan<- AgentEvent) (*util.OpenAICompletionStream, openai.ChatCompletionStreamResponse, context.CancelFunc, error) {@@ -2563,7 +2580,7 @@ func createProtocolStreamWithRetry(ctx context.Context, client *openai.Client, pif err == nil {for {firstResp, firstErr := recvStreamWithIdleTimeout(stream, streamIdleTimeout, streamCancel)- if firstErr != nil || !util.IsOpenAIResponsesProtocol(protocol) || len(firstResp.Choices) > 0 ||+ if firstErr != nil || (!util.IsOpenAIResponsesProtocol(protocol) && !util.IsAnthropicMessagesProtocol(protocol)) || len(firstResp.Choices) > 0 ||firstResp.Usage != nil {if firstErr == nil || errors.Is(firstErr, io.EOF) {return stream, firstResp, streamCancel, nil@@ -2636,7 +2653,7 @@ func classifyRetry(err error) string {return "rate_limit"case strings.Contains(code, "timeout"):return "timeout"- case code == "server_error" || code == "internal_error":+ case code == "server_error" || code == "internal_error" || code == "overloaded_error" || code == "api_error":return "server_error"}switch apiErr.HTTPStatusCode {@@ -2644,7 +2661,7 @@ func classifyRetry(err error) string {return "rate_limit"case 408:return "timeout"- case 500, 502, 503, 504:+ case 500, 502, 503, 504, 529:return "server_error"default:if apiErr.HTTPStatusCode >= 400 {diff --git a/kernel/agent/anthropic_test.go b/kernel/agent/anthropic_test.gonew file mode 100644index 0000000000..84819c876d--- /dev/null+++ b/kernel/agent/anthropic_test.go@@ -0,0 +1,337 @@+package agent++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync/atomic"+ "testing"+ "time"++ "github.com/sashabaranov/go-openai"+ kernelConf "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/mcp/tools"+ kernelModel "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func writeAnthropicAgentResponse(t *testing.T, w http.ResponseWriter, signature, text, tool string, complete bool) {+ t.Helper()+ flusher := prepareTestStream(t, w)+ write := func(event any) {+ data, _ := json.Marshal(event)+ _, _ = fmt.Fprintf(w, "data: %s\n\n", data)+ flusher.Flush()+ }+ write(map[string]any{"type": "message_start", "message": map[string]any{+ "id": "msg", "content": []any{}, "usage": map[string]int{"input_tokens": 10, "output_tokens": 1},+ }})+ blocks := []map[string]any{{"type": "thinking", "thinking": "reasoning", "signature": signature}}+ if tool != "" {+ blocks = append(blocks, map[string]any{"type": "tool_use", "id": "native_tool", "name": tool,+ "input": map[string]string{"action": "list"}})+ } else {+ blocks = append(blocks, map[string]any{"type": "text", "text": text})+ }+ for index, block := range blocks {+ write(map[string]any{"type": "content_block_start", "index": index, "content_block": block})+ write(map[string]any{"type": "content_block_stop", "index": index})+ }+ if complete {+ reason := "end_turn"+ if tool != "" {+ reason = "tool_use"+ }+ write(map[string]any{"type": "message_delta", "delta": map[string]string{"stop_reason": reason}, "usage": map[string]int{"output_tokens": 5}})+ write(map[string]any{"type": "message_stop"})+ }+}++func TestAnthropicAgentToolHistoryRecovery(t *testing.T) {+ for _, interrupted := range []bool{false, true} {+ t.Run(fmt.Sprintf("interrupted=%v", interrupted), func(t *testing.T) {+ useTestDataDir(t)+ previous := kernelModel.Conf+ kernelModel.Conf = kernelModel.NewAppConf()+ kernelModel.Conf.AI = kernelConf.NewAI()+ kernelModel.Conf.AI.MCP = nil+ kernelModel.Conf.Variables = kernelConf.NewVariables()+ t.Cleanup(func() { kernelModel.Conf = previous })+ const toolName = "test_anthropic_history"+ var executions atomic.Int32+ tools.SetTool(toolName, &tools.Tool{Name: toolName, Source: "native", ReadOnlyHint: true,+ InputSchema: tools.ToolSchema{Type: "object", Properties: map[string]tools.Property{"action": {Type: "string"}}},+ ActionEffects: map[string]tools.ToolEffects{"list": {LocalRead: true}},+ Handler: func(map[string]any) (tools.CallToolResult, error) {+ executions.Add(1)+ return tools.CallToolResult{Content: []tools.ContentItem{{Type: "text", Text: "found"}}}, nil+ }})+ t.Cleanup(func() { tools.RemoveTool(toolName) })+ _, err := SaveSession(marshalSession(t, map[string]any{"id": testSessionID, "title": "native",+ "createdAt": 1, "updatedAt": 1, "entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "use tool"}}}))+ if err != nil {+ t.Fatal(err)+ }+ var requests atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/v1/messages" {+ t.Errorf("unexpected path %s", r.URL.Path)+ }+ var payload map[string]json.RawMessage+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {+ t.Error(err)+ }+ n := requests.Add(1)+ if n >= 2 {+ for _, want := range []string{"signature-tool", "tool_result", "native_tool", "found"} {+ if !strings.Contains(string(payload["messages"]), want) {+ t.Errorf("native context missing %s: %s", want, payload["messages"])+ }+ }+ }+ if n == 1 {+ writeAnthropicAgentResponse(t, w, "signature-tool", "", toolName, true)+ } else if n == 2 && interrupted {+ writeAnthropicAgentResponse(t, w, "signature-incomplete", "partial", "", false)+ } else {+ if n == 3 && !interrupted && !strings.Contains(string(payload["messages"]), "signature-final") {+ t.Error("committed final thinking was not restored")+ }+ writeAnthropicAgentResponse(t, w, "signature-final", "answer", "", true)+ }+ }))+ defer server.Close()+ client := util.NewAIClientWithModel("key", server.URL+"/v1", "test")+ run := func(userID string, revision int64, message string, wantError bool) string {+ t.Helper()+ turnID, failed := "", false+ for event := range AgentChat(context.Background(), client, util.AnthropicProtocolMessages, "test", "", 0,+ testSessionID, userID, revision, message, nil, "English", nil, EditorContext{}, nil, false,+ time.Second, 0, "", time.Second, time.Second) {+ if event.Type == "turn" {+ turnID = event.TurnID+ }+ if event.Type == "error" {+ failed = true+ }+ }+ if failed != wantError || turnID == "" {+ t.Fatalf("turn failed=%v, want %v; id=%q", failed, wantError, turnID)+ }+ return turnID+ }+ turnID := run("user-1", 1, "use tool", interrupted)+ recovered, err := GetSession(testSessionID)+ if err != nil {+ t.Fatal(err)+ }+ recovered["expectedRevision"], recovered["commitTurnID"] = int64(1), turnID+ revision, canonical, err := SaveSessionState(marshalSession(t, recovered))+ if err != nil || revision != 2 {+ t.Fatalf("commit failed: %d %v", revision, err)+ }+ data, _ := json.Marshal(canonical)+ if !strings.Contains(string(data), "signature-tool") || (!interrupted && !strings.Contains(string(data), "signature-final")) {+ t.Fatalf("native blocks were lost during persistence: %s", data)+ }+ if interrupted && strings.Contains(string(data), "signature-incomplete") {+ t.Fatal("incomplete native content was committed")+ }+ canonical["entries"] = append(canonical["entries"].([]any), map[string]any{"id": "user-2", "type": "user", "content": "continue"})+ canonical["expectedRevision"] = int64(2)+ if _, err = SaveSession(marshalSession(t, canonical)); err != nil {+ t.Fatal(err)+ }+ run("user-2", 3, "continue", false)+ if executions.Load() != 1 || requests.Load() != 3 {+ t.Fatalf("tool was repeated: calls=%d requests=%d", executions.Load(), requests.Load())+ }+ })+ }+}++func TestAnthropicTitleAndCompaction(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var payload map[string]json.RawMessage+ _ = json.NewDecoder(r.Body).Decode(&payload)+ if r.URL.Path != "/v1/messages" || len(payload["system"]) == 0 {+ t.Errorf("unexpected native summary request: %s %s", r.URL.Path, payload["system"])+ }+ if string(payload["stream"]) == "true" {+ writeAnthropicAgentResponse(t, w, "summary-signature", "summary", "", true)+ } else {+ _, _ = fmt.Fprint(w, `{"content":[{"type":"text","text":"Native title"}],"stop_reason":"end_turn","usage":{}}`)+ }+ }))+ defer server.Close()+ client := util.NewAIClientWithModel("", server.URL, "test")+ if title := GenerateTitle(client, server.URL, util.AnthropicProtocolMessages, "test", "hello", "en"); title != "Native title" {+ t.Fatalf("unexpected title %q", title)+ }+ summary, input, output, err := createProtocolCompactionSummary(context.Background(), client, util.AnthropicProtocolMessages,+ "test", "history", 1024, 0, time.Second, time.Second, make(chan AgentEvent, 8))+ if err != nil || summary != "summary" || input != 10 || output != 5 {+ t.Fatalf("unexpected summary %q %d %d %v", summary, input, output, err)+ }+ content := &util.AIMessageContent{Protocol: util.AnthropicProtocolMessages, Version: 1,+ Blocks: []json.RawMessage{json.RawMessage(`{"type":"thinking","thinking":"visible","signature":"opaque"}`)}}+ messages := []AgentMessage{{Role: "assistant", Content: "answer", NativeContent: content}}+ source, err := buildCompactionSource("", messages)+ if err != nil || strings.Contains(source, "opaque") || messages[0].NativeContent == nil {+ t.Fatalf("compaction changed native history or included opaque data: %s %v", source, err)+ }+ for _, protocol := range []string{util.OpenAIProtocolChatCompletions, util.OpenAIProtocolResponses} {+ if runtimeCompactionMatchesProtocol(&runtimeCompaction{Protocol: util.AnthropicProtocolMessages}, protocol) {+ t.Fatal("native compaction was reused for a different protocol")+ }+ }+}++func TestAnthropicStreamRetryBeforeOutput(t *testing.T) {+ var requests atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if requests.Add(1) == 1 {+ w.Header().Set("Content-Type", "text/event-stream")+ _, _ = fmt.Fprint(w, "data: {\"type\":\"message_start\",\"message\":{\"content\":[]}}\n\n"++ "data: {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"busy\"}}\n\n")+ return+ }+ writeAnthropicAgentResponse(t, w, "signature", "answer", "", true)+ }))+ defer server.Close()+ stream, _, cancel, err := createProtocolStreamWithRetry(context.Background(), util.NewAIClientWithModel("", server.URL, "test"),+ util.AnthropicProtocolMessages, openai.ChatCompletionRequest{Model: "test", Messages: []openai.ChatCompletionMessage{{Role: "user", Content: "hello"}}},+ nil, 1, time.Second, time.Second, noRetryDelay, make(chan AgentEvent, 8))+ if err != nil {+ t.Fatal(err)+ }+ defer stream.Close()+ defer cancel()+ if requests.Load() != 2 || classifyRetry(&openai.APIError{HTTPStatusCode: 529}) != "server_error" {+ t.Fatal("Anthropic overload was not retried")+ }+}++func nativeHistoryContent(signature, text string) *util.AIMessageContent {+ thinking, _ := json.Marshal(map[string]string{"type": "thinking", "thinking": "reason", "signature": signature})+ content, _ := json.Marshal(map[string]string{"type": "text", "text": text})+ return &util.AIMessageContent{Protocol: util.AnthropicProtocolMessages, Version: 1,+ Blocks: []json.RawMessage{thinking, content}}+}++func TestAnthropicCompactionPreservesRecentNativeHistory(t *testing.T) {+ setupCompactionAgentTest(t)+ entries := []SessionEntry{+ {ID: "user-1", Type: "user", Content: "old task"},+ {ID: "assistant-1", Type: "assistant", Content: strings.Repeat("old result ", 12000)},+ {ID: "user-2", Type: "user", Content: "recent task"},+ {ID: "assistant-2", Type: "assistant", Content: "recent answer", NativeContent: nativeHistoryContent("recent-signature", "recent answer")},+ {ID: "user-3", Type: "user", Content: "continue"},+ }+ if _, err := SaveSession(marshalSession(t, map[string]any{"id": testSessionID, "title": "compact", "entries": entries})); err != nil {+ t.Fatal(err)+ }+ capabilities := currentCapabilitiesForTest(t)+ checkpoint := entriesToAgentMessages(entries)+ full := estimateProtocolRequestTokens("test", util.AnthropicProtocolMessages, checkpointMessagesToOpenAI(checkpoint, "English", nil), checkpoint, nil, capabilities.definitions)+ recent := entriesToAgentMessages(entries[2:])+ base := estimateProtocolRequestTokens("test", util.AnthropicProtocolMessages, checkpointMessagesToOpenAI(recent, "English", nil), recent, nil, capabilities.definitions)+ limit := compactionTestContextLimit(t, full, base)+ var requests atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var request map[string]json.RawMessage+ _ = json.NewDecoder(r.Body).Decode(&request)+ if requests.Add(1) == 1 {+ if strings.Contains(string(request["messages"]), "recent-signature") {+ t.Error("summary received opaque signatures")+ }+ writeAnthropicAgentResponse(t, w, "summary-signature", "old task summarized", "", true)+ } else {+ if !strings.Contains(string(request["messages"]), "recent-signature") ||+ !strings.Contains(string(request["system"]), "old task summarized") {+ t.Errorf("compaction lost native history or summary: %+v", request)+ }+ writeAnthropicAgentResponse(t, w, "answer-signature", "done", "", true)+ }+ }))+ defer server.Close()+ for event := range AgentChat(context.Background(), util.NewAIClientWithModel("", server.URL, "test"), util.AnthropicProtocolMessages,+ "test", "", limit, testSessionID, "user-3", 1, "continue", nil, "English", nil, EditorContext{}, nil, false,+ time.Second, 0, "", time.Second, time.Second) {+ if event.Type == "error" {+ t.Fatalf("native compaction failed: %s", event.Error)+ }+ }+ runtime, err := loadRuntimeState(testSessionID)+ if err != nil || requests.Load() != 2 || runtime.Compaction == nil || runtime.Compaction.CoveredEntryCount != 2 ||+ !validRuntimeCompaction(entries, runtime.Compaction) {+ t.Fatalf("unexpected compaction: %+v %v requests=%d", runtime, err, requests.Load())+ }+}++func TestAnthropicRegenerateUsesEditedHistory(t *testing.T) {+ setupCompactionAgentTest(t)+ entries := []SessionEntry{+ {ID: "user-1", Type: "user", Content: "first"},+ {ID: "assistant-1", Type: "assistant", Content: "first answer", NativeContent: nativeHistoryContent("retained-signature", "first answer")},+ {ID: "user-2", Type: "user", Content: "obsolete prompt"},+ {ID: "assistant-2", Type: "assistant", Content: "obsolete answer", NativeContent: nativeHistoryContent("obsolete-signature", "obsolete answer")},+ }+ if _, err := SaveSession(marshalSession(t, map[string]any{"id": testSessionID, "title": "regenerate", "entries": entries})); err != nil {+ t.Fatal(err)+ }+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var request map[string]json.RawMessage+ _ = json.NewDecoder(r.Body).Decode(&request)+ messages := string(request["messages"])+ if !strings.Contains(messages, "retained-signature") || !strings.Contains(messages, "edited prompt") || strings.Contains(messages, "obsolete") {+ t.Errorf("regeneration did not project edited native history: %s", messages)+ }+ writeAnthropicAgentResponse(t, w, "new-signature", "new answer", "", true)+ }))+ defer server.Close()+ for event := range AgentChat(context.Background(), util.NewAIClientWithModel("", server.URL, "test"), util.AnthropicProtocolMessages,+ "test", "", 0, testSessionID, "user-2", 1, "edited prompt", nil, "English", nil, EditorContext{}, nil, true,+ time.Second, 0, "", time.Second, time.Second) {+ if event.Type == "error" {+ t.Fatalf("native regeneration failed: %s", event.Error)+ }+ }+}++func TestAnthropicIncompleteToolDoesNotExecute(t *testing.T) {+ setupCompactionAgentTest(t)+ const toolName = "test_anthropic_incomplete"+ var executed atomic.Int32+ tools.SetTool(toolName, &tools.Tool{Name: toolName, Source: "native", ReadOnlyHint: true,+ InputSchema: tools.ToolSchema{Type: "object", Properties: map[string]tools.Property{"action": {Type: "string"}}},+ ActionEffects: map[string]tools.ToolEffects{"list": {LocalRead: true}},+ Handler: func(map[string]any) (tools.CallToolResult, error) {+ executed.Add(1)+ return tools.CallToolResult{}, nil+ }})+ t.Cleanup(func() { tools.RemoveTool(toolName) })+ if _, err := SaveSession(marshalSession(t, map[string]any{"id": testSessionID, "entries": []SessionEntry{+ {ID: "user-1", Type: "user", Content: "use tool"},+ }})); err != nil {+ t.Fatal(err)+ }+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ writeAnthropicAgentResponse(t, w, "signature", "", toolName, false)+ }))+ defer server.Close()+ failed := false+ for event := range AgentChat(context.Background(), util.NewAIClientWithModel("", server.URL, "test"), util.AnthropicProtocolMessages,+ "test", "", 0, testSessionID, "user-1", 1, "use tool", nil, "English", nil, EditorContext{}, nil, false,+ time.Second, 2, "", time.Second, time.Second) {+ if event.Type == "error" {+ failed = true+ }+ }+ if !failed || executed.Load() != 0 {+ t.Fatalf("incomplete response executed a tool: failed=%v executions=%d", failed, executed.Load())+ }+}diff --git a/kernel/agent/assistant_context_test.go b/kernel/agent/assistant_context_test.goindex 3adc34ac48..73646cbebf 100644--- a/kernel/agent/assistant_context_test.go+++ b/kernel/agent/assistant_context_test.go@@ -476,11 +476,11 @@ func TestAgentChatRestoresCompleteAssistantContextAfterCommit(t *testing.T) {}}-func newTestGeminiOpenAIClient(serverURL string) *openai.Client {+func newTestGeminiOpenAIClient(serverURL string) *util.AIClient {config := openai.DefaultConfig("test-key")config.BaseURL = serverURL + "/v1"config.HTTPClient = util.WrapGeminiThoughtSignatureTransport(http.DefaultClient)- return openai.NewClientWithConfig(config)+ return &util.AIClient{Client: openai.NewClientWithConfig(config)}}func assertGeminiThoughtSignatureInRequest(t *testing.T, body []byte, callID, want string) {diff --git a/kernel/agent/attachments.go b/kernel/agent/attachments.goindex 8818422683..970f0e3030 100644--- a/kernel/agent/attachments.go+++ b/kernel/agent/attachments.go@@ -355,7 +355,7 @@ func containsAny(value string, candidates ...string) bool {// createImageCompatibleStream 在上游明确拒绝图片且尚未产生输出时,使用纯文本请求投影兼容重试一次。func createImageCompatibleStream(ctx context.Context,- client *openai.Client,+ client *util.AIClient,req openai.ChatCompletionRequest,capabilityKey string,forceDowngrade bool,@@ -379,7 +379,7 @@ func createImageCompatibleStream(func createProtocolImageCompatibleStream(ctx context.Context,- client *openai.Client,+ client *util.AIClient,protocol string,req openai.ChatCompletionRequest,responseInput func(downgradeImages bool) []any,diff --git a/kernel/agent/compaction.go b/kernel/agent/compaction.goindex 9422dde143..705655b92a 100644--- a/kernel/agent/compaction.go+++ b/kernel/agent/compaction.go@@ -99,6 +99,9 @@ func runtimeCompactionMatchesProtocol(compaction *runtimeCompaction, protocol stif compaction == nil {return false}+ if util.IsAnthropicMessagesProtocol(compaction.Protocol) || util.IsAnthropicMessagesProtocol(protocol) {+ return util.IsAnthropicMessagesProtocol(compaction.Protocol) && util.IsAnthropicMessagesProtocol(protocol)+ }return util.IsOpenAIResponsesProtocol(compaction.Protocol) == util.IsOpenAIResponsesProtocol(protocol)}@@ -157,6 +160,11 @@ func checkpointMessagesAfterCompaction(entries []SessionEntry, coveredEntryCount}func buildCompactionSource(previousSummary string, messages []AgentMessage) (string, error) {+ messages = append([]AgentMessage(nil), messages...)+ for i := range messages {+ // 摘要只读取可见历史,原生签名随未压缩轮次保留,不进入摘要提示。+ messages[i].NativeContent = nil+ }data, err := json.Marshal(messages)if err != nil {return "", err@@ -181,13 +189,13 @@ func compactionSummaryMessages(source string) []openai.ChatCompletionMessage {}}-func createCompactionSummary(ctx context.Context, client *openai.Client, model, source string, maxTokens, maxRetries int,+func createCompactionSummary(ctx context.Context, client *util.AIClient, model, source string, maxTokens, maxRetries int,requestTimeout, streamIdleTimeout time.Duration, ch chan<- AgentEvent) (summary string, promptTokens, completionTokens int, err error) {return createProtocolCompactionSummary(ctx, client, util.OpenAIProtocolChatCompletions, model, source, maxTokens,maxRetries, requestTimeout, streamIdleTimeout, ch)}-func createProtocolCompactionSummary(ctx context.Context, client *openai.Client, protocol, model, source string,+func createProtocolCompactionSummary(ctx context.Context, client *util.AIClient, protocol, model, source string,maxTokens, maxRetries int, requestTimeout, streamIdleTimeout time.Duration,ch chan<- AgentEvent) (summary string, promptTokens, completionTokens int, err error) {if maxTokens < compactionSummaryMinTokens {@@ -242,7 +250,7 @@ func createProtocolCompactionSummary(ctx context.Context, client *openai.Client,return summary, promptTokens, completionTokens, nil}-func createResponseCompaction(ctx context.Context, client *openai.Client, request openai.ChatCompletionRequest,+func createResponseCompaction(ctx context.Context, client *util.AIClient, request openai.ChatCompletionRequest,responseInput []any, maxRetries int, requestTimeout time.Duration,ch chan<- AgentEvent) (output []json.RawMessage, promptTokens, completionTokens int, err error) {if maxRetries < 0 {diff --git a/kernel/agent/runtime.go b/kernel/agent/runtime.goindex 0b29f279fd..09451f90a8 100644--- a/kernel/agent/runtime.go+++ b/kernel/agent/runtime.go@@ -496,6 +496,9 @@ func applyRuntimeTurnToSessionLocked(session map[string]any, turn *agentRuntimeTif message.ReasoningContent != "" {entry["reasoningContent"] = message.ReasoningContent}+ if message.NativeContent != nil {+ entry["nativeContent"] = message.NativeContent+ }if len(message.ResponseOutput) > 0 {entry["responseOutput"] = message.ResponseOutput}diff --git a/kernel/agent/stream_timeout_test.go b/kernel/agent/stream_timeout_test.goindex fd8c04a02d..77496fab0b 100644--- a/kernel/agent/stream_timeout_test.go+++ b/kernel/agent/stream_timeout_test.go@@ -22,6 +22,7 @@ import (openai "github.com/sashabaranov/go-openai"kernelConf "github.com/siyuan-note/siyuan/kernel/conf"kernelModel "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util")func TestStreamIdleTimeoutResetsAfterEachChunk(t *testing.T) {@@ -386,10 +387,10 @@ func TestCreateStreamAcceptsEmptySuccessfulResponse(t *testing.T) {}}-func newTestOpenAIClient(serverURL string) *openai.Client {+func newTestOpenAIClient(serverURL string) *util.AIClient {config := openai.DefaultConfig("test-key")config.BaseURL = serverURL + "/v1"- return openai.NewClientWithConfig(config)+ return &util.AIClient{Client: openai.NewClientWithConfig(config)}}func testChatRequest() openai.ChatCompletionRequest {diff --git a/kernel/agent/title_test.go b/kernel/agent/title_test.goindex 93901fb6eb..f02ecd62a3 100644--- a/kernel/agent/title_test.go+++ b/kernel/agent/title_test.go@@ -37,7 +37,7 @@ func TestGenerateTitleDisablesReasoningWithinOutputBudget(t *testing.T) {}))defer server.Close()- title := GenerateTitle(util.NewOpenAIClientWithModel("test", server.URL+"/v1", "test-model"), server.URL+"/v1",+ title := GenerateTitle(util.NewAIClientWithModel("test", server.URL+"/v1", "test-model"), server.URL+"/v1",util.OpenAIProtocolChatCompletions, "test-model", "Investigate reasoning output", "en")if title != "Reasoning Compatibility" {t.Fatalf("title = %q", title)@@ -67,7 +67,7 @@ func TestGenerateTitleRetriesWithoutReasoningForLegacyEndpoint(t *testing.T) {}))defer server.Close()- title := GenerateTitle(util.NewOpenAIClientWithModel("test", server.URL+"/v1", "test-model"), server.URL+"/v1",+ title := GenerateTitle(util.NewAIClientWithModel("test", server.URL+"/v1", "test-model"), server.URL+"/v1",util.OpenAIProtocolChatCompletions, "test-model", "Investigate legacy endpoint", "en")if title != "Legacy Endpoint" || len(requests) != 2 {t.Fatalf("title = %q, requests = %d", title, len(requests))@@ -101,7 +101,7 @@ func TestGenerateTitleRetriesWithoutReasoningForResponsesEndpoint(t *testing.T)}))defer server.Close()- title := GenerateTitle(util.NewOpenAIClientWithModel("test", server.URL+"/v1", "test-model"), server.URL+"/v1",+ title := GenerateTitle(util.NewAIClientWithModel("test", server.URL+"/v1", "test-model"), server.URL+"/v1",util.OpenAIProtocolResponses, "test-model", "Investigate Responses endpoint", "en")if title != "Responses Endpoint" || len(requests) != 2 {t.Fatalf("title = %q, requests = %d", title, len(requests))@@ -133,7 +133,7 @@ func TestGenerateTitleRetriesWhenReasoningExhaustsInitialBudget(t *testing.T) {}))defer server.Close()- title := GenerateTitle(util.NewOpenAIClientWithModel("test", server.URL+"/v1", "test-model"), server.URL+"/v1",+ title := GenerateTitle(util.NewAIClientWithModel("test", server.URL+"/v1", "test-model"), server.URL+"/v1",util.OpenAIProtocolChatCompletions, "test-model", "Investigate title token budget", "en")if title != "Reasoning Budget" || len(requests) != 2 {t.Fatalf("title = %q, requests = %d", title, len(requests))@@ -153,7 +153,7 @@ func TestGenerateTitleDoesNotRetryUnrelatedProviderError(t *testing.T) {}))defer server.Close()- title := GenerateTitle(util.NewOpenAIClientWithModel("test", server.URL+"/v1", "test-model"), server.URL+"/v1",+ title := GenerateTitle(util.NewAIClientWithModel("test", server.URL+"/v1", "test-model"), server.URL+"/v1",util.OpenAIProtocolChatCompletions, "test-model", "Investigate provider failure", "en")if title != "Investigate provider failure" || requests != 1 {t.Fatalf("title = %q, requests = %d", title, requests)@@ -170,7 +170,7 @@ func TestGenerateTitleDoesNotRetryReasoningErrorFromUnavailableProvider(t *testi}))defer server.Close()- title := GenerateTitle(util.NewOpenAIClientWithModel("test", server.URL+"/v1", "test-model"), server.URL+"/v1",+ title := GenerateTitle(util.NewAIClientWithModel("test", server.URL+"/v1", "test-model"), server.URL+"/v1",util.OpenAIProtocolChatCompletions, "test-model", "Investigate provider failure", "en")if title != "Investigate provider failure" || requests != 1 {t.Fatalf("title = %q, requests = %d", title, requests)diff --git a/kernel/agent/tokens.go b/kernel/agent/tokens.goindex 5dc7248327..c925d8c30d 100644--- a/kernel/agent/tokens.go+++ b/kernel/agent/tokens.go@@ -272,6 +272,25 @@ func estimateChatRequestTokens(model string, messages []openai.ChatCompletionMesfunc estimateProtocolRequestTokens(model, protocol string, messages []openai.ChatCompletionMessage,checkpointMessages []AgentMessage, compaction *runtimeCompaction, tools []openai.Tool) int {total := estimateChatRequestTokens(model, messages, tools)+ if util.IsAnthropicMessagesProtocol(protocol) {+ counter, _ := getTokenCounter(model)+ for _, message := range checkpointMessages {+ if message.NativeContent != nil && util.IsAnthropicMessagesProtocol(message.NativeContent.Protocol) {+ // 只补计原生签名及结构开销,避免重复计算可见文本和工具参数。+ visible := counter.count(message.Content) + counter.count(message.ReasoningContent)+ for _, call := range message.ToolCalls {+ arguments := call.ArgumentsJSON+ if arguments == "" {+ data, _ := json.Marshal(call.Arguments)+ arguments = string(data)+ }+ visible += counter.count(call.Name) + counter.count(arguments)+ }+ total += max(responseOutputTokenCost(model, message.NativeContent.Blocks, 0)-visible, 0)+ }+ }+ return total+ }if !util.IsOpenAIResponsesProtocol(protocol) {return total}diff --git a/kernel/api/agent.go b/kernel/api/agent.goindex ffe9a314e7..7a45df9b48 100644--- a/kernel/api/agent.go+++ b/kernel/api/agent.go@@ -81,7 +81,7 @@ func agentChatContract(c *gin.Context, request apicontract.AIAgentChatRequest) aret.Msg = model.Conf.Language(193)return contractFailure[apicontract.Null](ret)}- client := util.NewOpenAIClientWithModel(selectedProvider.APIKey, selectedProvider.BaseURL, selectedModel.Name, model.ResolveAIProviderHeaders(selectedProvider))+ client := util.NewAIClientWithModel(selectedProvider.APIKey, selectedProvider.BaseURL, selectedModel.Name, model.ResolveAIProviderHeaders(selectedProvider))confirmTimeout := resolveAgentConfirmTimeout(model.Conf.AI.Agent.ConfirmTimeout)maxRetries := model.Conf.AI.Agent.MaxRetries@@ -328,7 +328,7 @@ func agentChatTitleContract(c *gin.Context, req apicontract.AITitleRequest) apicret.Msg = "no AI provider configured"return contractFailure[string](ret)}- client := util.NewOpenAIClientWithModel(selectedProvider.APIKey, selectedProvider.BaseURL, selectedModel.Name, model.ResolveAIProviderHeaders(selectedProvider))+ client := util.NewAIClientWithModel(selectedProvider.APIKey, selectedProvider.BaseURL, selectedModel.Name, model.ResolveAIProviderHeaders(selectedProvider))title := agent.GenerateTitle(client, selectedProvider.BaseURL, selectedProvider.Protocol, selectedModel.Name,req.Message, req.Language)diff --git a/kernel/api/ai.go b/kernel/api/ai.goindex 2555985feb..5c5d4124fc 100644--- a/kernel/api/ai.go+++ b/kernel/api/ai.go@@ -325,7 +325,7 @@ func listModelsContract(c *gin.Context, req apicontract.AIProviderRequest) apicoreturn contractFailure[apicontract.AIModelsData](ret)}- metadata, err := util.ListAvailableModelsWithContext(provider.APIKey, provider.BaseURL, provider.RequestTimeout, model.ResolveAIProviderHeaders(provider))+ metadata, err := util.ListProviderModels(provider.APIKey, provider.BaseURL, provider.Protocol, provider.RequestTimeout, model.ResolveAIProviderHeaders(provider))models := make([]string, 0, len(metadata))contextLengths := map[string]int{}for _, item := range metadata {diff --git a/kernel/api/contract_anthropic_test.go b/kernel/api/contract_anthropic_test.gonew file mode 100644index 0000000000..8df2291ca7--- /dev/null+++ b/kernel/api/contract_anthropic_test.go@@ -0,0 +1,136 @@+package api++import (+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAPIContractAnthropicGenerationAndModels(t *testing.T) {+ aiContractConfiguration(t)+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Header.Get("x-api-key") != "key" || r.Header.Get("anthropic-version") == "" || r.Header.Get("X-Custom") != "configured" {+ t.Errorf("provider headers missing: %v", r.Header)+ }+ if r.URL.Path == "/v1/models" {+ _, _ = fmt.Fprint(w, `{"data":[{"id":"test","max_input_tokens":200000}],"has_more":false}`)+ return+ }+ if r.URL.Path != "/v1/messages" {+ t.Errorf("unexpected upstream path: %s", r.URL.Path)+ }+ var request struct {+ Stream bool `json:"stream"`+ }+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil {+ t.Error(err)+ }+ if !request.Stream {+ _, _ = fmt.Fprint(w, `{"content":[{"type":"text","text":"answer"}],"stop_reason":"end_turn","usage":{}}`)+ return+ }+ w.Header().Set("Content-Type", "text/event-stream")+ for _, event := range []string{+ `{"type":"message_start","message":{"content":[],"usage":{"input_tokens":3,"output_tokens":1}}}`,+ `{"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"reason","signature":"signed"}}`,+ `{"type":"content_block_stop","index":0}`,+ `{"type":"content_block_start","index":1,"content_block":{"type":"text","text":"answer"}}`,+ `{"type":"content_block_stop","index":1}`,+ `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}`,+ `{"type":"message_stop"}`,+ } {+ _, _ = fmt.Fprintf(w, "data: %s\n\n", event)+ }+ }))+ defer upstream.Close()+ provider := &conf.Provider{ID: "provider", Enabled: true, BaseURL: upstream.URL + "/v1",+ Protocol: util.AnthropicProtocolMessages, APIKey: "key", RequestTimeout: 5,+ Headers: map[string]string{"X-Custom": "configured"}, Models: []*conf.Model{{ID: "model", Name: "test", Enabled: true}}}+ model.Conf.AI.Providers = []*conf.Provider{provider}+ model.Conf.AI.Editing.ModelID = "model"+ engine := gin.New()+ engine.POST("/api/ai/editor/chat", aiEditorChat)+ engine.POST("/api/ai/chatGPT", chatGPT)+ engine.POST("/api/ai/listModels", listModels)+ engine.POST("/api/ai/testModel", testModel)+ bundle, err := apicontract.BuildBundle()+ if err != nil {+ t.Fatal(err)+ }+ for _, tc := range []struct {+ path string+ body any+ want string+ }{+ {"/api/ai/listModels", map[string]any{"provider": "provider"}, `"test"`},+ {"/api/ai/testModel", map[string]any{"providerConfig": provider, "model": "test"}, `"matched":true`},+ {"/api/ai/chatGPT", map[string]any{"msg": "hello"}, "answer"},+ {"/api/ai/editor/chat", map[string]any{"taskID": "task", "input": "hello"}, "event:done"},+ } {+ t.Run(tc.path, func(t *testing.T) {+ body, _ := json.Marshal(tc.body)+ request := httptest.NewRequest("POST", tc.path, strings.NewReader(string(body)))+ request.Header.Set("Content-Type", "application/json")+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, request)+ if recorder.Code != 200 || !strings.Contains(recorder.Body.String(), tc.want) {+ t.Fatalf("unexpected response %d %s", recorder.Code, recorder.Body.String())+ }+ if err := bundle.ValidateHTTPResponse("POST", tc.path, recorder.Code, recorder.Header().Get("Content-Type"), recorder.Body.Bytes()); err != nil {+ t.Fatal(err)+ }+ if tc.path == "/api/ai/editor/chat" {+ for _, frame := range strings.Split(strings.TrimSpace(recorder.Body.String()), "\n\n") {+ lines := strings.SplitN(frame, "\n", 2)+ if len(lines) != 2 {+ t.Fatalf("invalid SSE frame: %s", frame)+ }+ if err := bundle.ValidateSSEEvent("POST", tc.path, strings.TrimPrefix(lines[0], "event:"), []byte(strings.TrimPrefix(lines[1], "data:"))); err != nil {+ t.Fatal(err)+ }+ }+ if !strings.Contains(recorder.Body.String(), "event:reasoning") || strings.Contains(recorder.Body.String(), "signed") {+ t.Fatal("editor reasoning projection exposed a signature or omitted reasoning")+ }+ }+ })+ }+}++func TestAPIContractAnthropicSessionContent(t *testing.T) {+ aiContractConfiguration(t)+ engine := gin.New()+ engine.POST("/api/ai/agent/saveSession", saveSession)+ engine.POST("/api/ai/agent/getSession", getSession)+ bundle, err := apicontract.BuildBundle()+ if err != nil {+ t.Fatal(err)+ }+ for _, tc := range []struct{ path, body string }{+ {"/api/ai/agent/saveSession", `{"id":"20260918000000-abcdefg","entries":[{"type":"assistant","content":"answer","nativeContent":{"protocol":"anthropic-messages","version":1,"blocks":[{"type":"thinking","thinking":"reason","signature":"opaque"},{"type":"text","text":"answer"}]}}]}`},+ {"/api/ai/agent/getSession", `{"id":"20260918000000-abcdefg"}`},+ } {+ request := httptest.NewRequest("POST", tc.path, strings.NewReader(tc.body))+ request.Header.Set("X-SiYuan-Agent-Checkpoint", "2")+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, request)+ if recorder.Code != 200 || !strings.Contains(recorder.Body.String(), `"code":0`) {+ t.Fatalf("unexpected session response: %s", recorder.Body.String())+ }+ if err := bundle.ValidateHTTPResponse("POST", tc.path, recorder.Code, recorder.Header().Get("Content-Type"), recorder.Body.Bytes()); err != nil {+ t.Fatal(err)+ }+ if tc.path == "/api/ai/agent/getSession" && !strings.Contains(recorder.Body.String(), `"signature":"opaque"`) {+ t.Fatalf("native content was not preserved: %s", recorder.Body.String())+ }+ }+}diff --git a/kernel/apicontract/ai_agent.go b/kernel/apicontract/ai_agent.goindex 79261c57b9..a08d5fd346 100644--- a/kernel/apicontract/ai_agent.go+++ b/kernel/apicontract/ai_agent.go@@ -67,6 +67,7 @@ type AISessionEntry struct {CompletionTok int `json:"completionTokens,omitempty" api:"optional,nullable"`Timestamp int64 `json:"timestamp,omitempty" api:"optional,nullable"`ReasoningCont string `json:"reasoningContent,omitempty" api:"optional,nullable"`+ NativeContent *AINativeContent `json:"nativeContent,omitempty" api:"optional,nullable"`ResponseOutput []JSONValue `json:"responseOutput,omitempty" api:"optional,nullable"`ResponseOutputTokens int `json:"responseOutputTokens,omitempty" api:"optional,nullable"`RoundID string `json:"roundID,omitempty" api:"optional,nullable"`@@ -84,6 +85,7 @@ type AIAgentMessage struct {Role string `json:"role" api:"optional,nullable"`Content string `json:"content" api:"optional,nullable"`ReasoningContent string `json:"reasoningContent,omitempty" api:"optional,nullable"`+ NativeContent *AINativeContent `json:"nativeContent,omitempty" api:"optional,nullable"`ResponseOutput []JSONValue `json:"responseOutput,omitempty" api:"optional,nullable"`ResponseOutputTokens int `json:"responseOutputTokens,omitempty" api:"optional,nullable"`RoundID string `json:"roundID,omitempty" api:"optional,nullable"`@@ -231,3 +233,10 @@ func aiAgentSSEOptions() ResponseOptions {options.AdditionalErrorStatuses = []int{409}return options}++// AINativeContent 保留供应商定义的原生内容块,协议和版本用于选择兼容的上下文读取方式。+type AINativeContent struct {+ Protocol string `json:"protocol"`+ Version int `json:"version"`+ Blocks []JSONValue `json:"blocks"`+}diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex a270c06cf1..a4c03f3043 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -297,6 +297,9 @@"entryID": {"type": "string"},+ "nativeContent": {+ "$ref": "#/$defs/AINativeContent"+ },"reasoningContent": {"type": "string"},@@ -367,6 +370,16 @@}]},+ "nativeContent": {+ "anyOf": [+ {+ "$ref": "#/$defs/AINativeContentInput"+ },+ {+ "type": "null"+ }+ ]+ },"reasoningContent": {"anyOf": [{@@ -1398,6 +1411,59 @@],"additionalProperties": false},+ "AINativeContent": {+ "type": "object",+ "properties": {+ "blocks": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "$ref": "#/$defs/JSONValue"+ }+ },+ {+ "type": "null"+ }+ ]+ },+ "protocol": {+ "type": "string"+ },+ "version": {+ "type": "integer"+ }+ },+ "required": [+ "blocks",+ "protocol",+ "version"+ ],+ "additionalProperties": false+ },+ "AINativeContentInput": {+ "type": "object",+ "properties": {+ "blocks": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/JSONValue"+ }+ },+ "protocol": {+ "type": "string"+ },+ "version": {+ "type": "integer"+ }+ },+ "required": [+ "blocks",+ "protocol",+ "version"+ ],+ "additionalProperties": false+ },"AIPermissionData": {"type": "object","properties": {@@ -1901,6 +1967,9 @@"name": {"type": "string"},+ "nativeContent": {+ "$ref": "#/$defs/AINativeContent"+ },"promptTokens": {"type": "integer"},@@ -2083,6 +2152,16 @@}]},+ "nativeContent": {+ "anyOf": [+ {+ "$ref": "#/$defs/AINativeContentInput"+ },+ {+ "type": "null"+ }+ ]+ },"promptTokens": {"anyOf": [{@@ -2581,6 +2660,16 @@}]},+ "nativeContent": {+ "anyOf": [+ {+ "$ref": "#/$defs/AISessionExtensionAINativeContent"+ },+ {+ "type": "null"+ }+ ]+ },"reasoningContent": {"anyOf": [{@@ -2698,6 +2787,16 @@}]},+ "nativeContent": {+ "anyOf": [+ {+ "$ref": "#/$defs/AISessionExtensionAINativeContentInput"+ },+ {+ "type": "null"+ }+ ]+ },"reasoningContent": {"anyOf": [{@@ -3154,6 +3253,88 @@"$ref": "#/$defs/JSONValue"}},+ "AISessionExtensionAINativeContent": {+ "type": "object",+ "properties": {+ "blocks": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "$ref": "#/$defs/JSONValue"+ }+ },+ {+ "type": "null"+ }+ ]+ },+ "protocol": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "version": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "additionalProperties": {+ "$ref": "#/$defs/JSONValue"+ }+ },+ "AISessionExtensionAINativeContentInput": {+ "type": "object",+ "properties": {+ "blocks": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "$ref": "#/$defs/JSONValue"+ }+ },+ {+ "type": "null"+ }+ ]+ },+ "protocol": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "version": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "additionalProperties": {+ "$ref": "#/$defs/JSONValue"+ }+ },"AISessionExtensionAIReference": {"type": "object","properties": {@@ -3319,6 +3500,16 @@}]},+ "nativeContent": {+ "anyOf": [+ {+ "$ref": "#/$defs/AISessionExtensionAINativeContent"+ },+ {+ "type": "null"+ }+ ]+ },"promptTokens": {"anyOf": [{@@ -3598,6 +3789,16 @@}]},+ "nativeContent": {+ "anyOf": [+ {+ "$ref": "#/$defs/AISessionExtensionAINativeContentInput"+ },+ {+ "type": "null"+ }+ ]+ },"promptTokens": {"anyOf": [{diff --git a/kernel/conf/ai.go b/kernel/conf/ai.goindex f8ce12bea0..fe7d571170 100644--- a/kernel/conf/ai.go+++ b/kernel/conf/ai.go@@ -604,6 +604,9 @@ func (ai *AI) Normalize() {p.BaseURL = strings.TrimSpace(p.BaseURL)if "" == p.BaseURL {p.BaseURL = "https://api.openai.com/v1"+ if util.IsAnthropicMessagesProtocol(p.Protocol) {+ p.BaseURL = "https://api.anthropic.com/v1"+ }}p.DisplayName = strings.TrimSpace(p.DisplayName)p.APIKey = strings.TrimSpace(p.APIKey)diff --git a/kernel/conf/ai_anthropic_test.go b/kernel/conf/ai_anthropic_test.gonew file mode 100644index 0000000000..e233fd28d1--- /dev/null+++ b/kernel/conf/ai_anthropic_test.go@@ -0,0 +1,20 @@+package conf++import "testing"++func TestAnthropicProviderDefaultsPreserveExistingProtocols(t *testing.T) {+ ai := NewAI()+ ai.Providers = []*Provider{+ {Enabled: true, Protocol: " ANTHROPIC-MESSAGES "},+ {Enabled: true},+ {Enabled: true, Protocol: "openai-responses", BaseURL: "https://example.com/v1"},+ }+ ai.Normalize()+ if ai.Providers[0].Protocol != "anthropic-messages" || ai.Providers[0].BaseURL != "https://api.anthropic.com/v1" {+ t.Fatalf("unexpected Messages defaults: %+v", ai.Providers[0])+ }+ if ai.Providers[1].Protocol != "openai" || ai.Providers[1].BaseURL != "https://api.openai.com/v1" ||+ ai.Providers[2].Protocol != "openai-responses" || ai.Providers[2].BaseURL != "https://example.com/v1" {+ t.Fatal("existing provider defaults changed")+ }+}diff --git a/kernel/model/ai.go b/kernel/model/ai.goindex e436937025..a800db3d52 100644--- a/kernel/model/ai.go+++ b/kernel/model/ai.go@@ -187,7 +187,7 @@ func NewAIEditorChatStream(ctx context.Context, ids []string, input, action stristreamCtx = util.ContextWithOpenAIResponsesBaseURL(streamCtx, prov.BaseURL)requestTimeout := time.Duration(prov.RequestTimeout) * time.SecondrequestTimer, requestTimerDone := startAIEditorCancelTimer(requestTimeout, cancel)- client := util.NewOpenAIClientWithModel(prov.APIKey, prov.BaseURL, m.Name, ResolveAIProviderHeaders(prov))+ client := util.NewAIClientWithModel(prov.APIKey, prov.BaseURL, m.Name, ResolveAIProviderHeaders(prov))completionStream, err := util.CreateOpenAICompletionStream(streamCtx, client, prov.Protocol, req, nil)requestTimedOut := stopAIEditorCancelTimer(requestTimer, requestTimerDone)if requestTimedOut {@@ -260,7 +260,7 @@ func chatGPTComplete(msg string, contextMsgs []string, cloud bool) (ret string,gpt = &CloudGPT{}} else {gpt = &OpenAIGPT{- c: util.NewOpenAIClientWithModel(prov.APIKey, prov.BaseURL, m.Name, ResolveAIProviderHeaders(prov)),+ c: util.NewAIClientWithModel(prov.APIKey, prov.BaseURL, m.Name, ResolveAIProviderHeaders(prov)),apiBaseURL: prov.BaseURL,m: m,protocol: prov.Protocol,@@ -344,7 +344,7 @@ type GPT interface {}type OpenAIGPT struct {- c *openai.Client+ c *util.AIClientapiBaseURL stringm *conf.Modelprotocol stringdiff --git a/kernel/util/ai_client.go b/kernel/util/ai_client.gonew file mode 100644index 0000000000..b2434efaea--- /dev/null+++ b/kernel/util/ai_client.go@@ -0,0 +1,51 @@+package util++import (+ "context"+ "encoding/json"+ "net/http"+ "strings"++ "github.com/sashabaranov/go-openai"+)++const AnthropicProtocolMessages = "anthropic-messages"++// AIClient 共享生成调用的连接配置,按协议选择独立的请求适配器。+type AIClient struct {+ *openai.Client+ baseURL string+ anthropicHTTP *http.Client+}++// AIMessageContent 保存供应商原生内容,显示文本与恢复上下文分别使用各自的表示。+type AIMessageContent struct {+ Protocol string `json:"protocol"`+ Version int `json:"version"`+ Blocks []json.RawMessage `json:"blocks"`+}++func CloneAIMessageContent(content *AIMessageContent) *AIMessageContent {+ if content == nil {+ return nil+ }+ ret := *content+ ret.Blocks = CloneOpenAIResponseOutput(content.Blocks)+ return &ret+}++func IsAnthropicMessagesProtocol(protocol string) bool {+ return strings.EqualFold(strings.TrimSpace(protocol), AnthropicProtocolMessages)+}++type aiMessageContentContextKey struct{}++// ContextWithAIMessageContents 按助手消息顺序附加原生内容,图片降级不会改变消息对应关系。+func ContextWithAIMessageContents(ctx context.Context, contents []*AIMessageContent) context.Context {+ return context.WithValue(ctx, aiMessageContentContextKey{}, contents)+}++func aiMessageContents(ctx context.Context) []*AIMessageContent {+ contents, _ := ctx.Value(aiMessageContentContextKey{}).([]*AIMessageContent)+ return contents+}diff --git a/kernel/util/anthropic.go b/kernel/util/anthropic.gonew file mode 100644index 0000000000..f3428077f5--- /dev/null+++ b/kernel/util/anthropic.go@@ -0,0 +1,531 @@+package util++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "reflect"+ "strings"++ "github.com/sashabaranov/go-openai"+)++const anthropicContentVersion = 1++type anthropicMessage struct {+ Role string `json:"role"`+ Content []json.RawMessage `json:"content"`+}++type anthropicRequest struct {+ Model string `json:"model"`+ MaxTokens int `json:"max_tokens"`+ Messages []anthropicMessage `json:"messages"`+ System []json.RawMessage `json:"system,omitempty"`+ Stream bool `json:"stream,omitempty"`+ Temperature *float32 `json:"temperature,omitempty"`+ Tools []anthropicTool `json:"tools,omitempty"`+ ToolChoice any `json:"tool_choice,omitempty"`+ Thinking *anthropicThinking `json:"thinking,omitempty"`+ OutputConfig map[string]string `json:"output_config,omitempty"`+ Stop []string `json:"stop_sequences,omitempty"`+}++type anthropicTool struct {+ Name string `json:"name"`+ Description string `json:"description,omitempty"`+ InputSchema any `json:"input_schema"`+}++type anthropicThinking struct {+ Type string `json:"type"`+ BudgetTokens int `json:"budget_tokens,omitempty"`+}++type anthropicUsage struct {+ InputTokens int `json:"input_tokens"`+ OutputTokens int `json:"output_tokens"`+ CacheCreationTokens int `json:"cache_creation_input_tokens"`+ CacheReadTokens int `json:"cache_read_input_tokens"`+}++func (u anthropicUsage) chatUsage() openai.Usage {+ input := u.InputTokens + u.CacheCreationTokens + u.CacheReadTokens+ return openai.Usage{PromptTokens: input, CompletionTokens: u.OutputTokens, TotalTokens: input + u.OutputTokens,+ PromptTokensDetails: &openai.PromptTokensDetails{CachedTokens: u.CacheReadTokens}}+}++func newAnthropicHTTPClient(apiKey, baseURL string, headers ...map[string]string) *http.Client {+ merged := http.Header{}+ merged.Set("anthropic-version", "2023-06-01")+ if apiKey != "" {+ merged.Set("x-api-key", apiKey)+ }+ if len(headers) > 0 {+ if ValidateAIProviderHeaders(headers[0]) != nil {+ return newAIProviderHTTPClient(baseURL, headers...)+ }+ for key, value := range headers[0] {+ merged.Set(key, value)+ }+ }+ values := map[string]string{}+ for key := range merged {+ values[key] = merged.Get(key)+ }+ // 默认凭据也由源站限制的传输层注入,重定向不会把密钥带到其他站点。+ return newAIProviderHTTPClient(baseURL, values)+}++func anthropicEndpoint(baseURL, resource string) (string, error) {+ endpoint, err := url.Parse(strings.TrimSpace(baseURL))+ if err != nil || endpoint.Host == "" || (endpoint.Scheme != "http" && endpoint.Scheme != "https") {+ return "", errors.New("invalid Anthropic API base URL")+ }+ endpoint.Path = strings.TrimRight(endpoint.Path, "/")+ if endpoint.Path == "" {+ endpoint.Path = "/v1"+ }+ endpoint.Path += "/" + resource+ return endpoint.String(), nil+}++func (c *AIClient) anthropicRequest(ctx context.Context, method, resource string, payload any) (*http.Response, error) {+ if c.anthropicHTTP == nil {+ return nil, errors.New("Anthropic client is missing connection settings")+ }+ endpoint, err := anthropicEndpoint(c.baseURL, resource)+ if err != nil {+ return nil, err+ }+ var body io.Reader+ if payload != nil {+ data, marshalErr := json.Marshal(payload)+ if marshalErr != nil {+ return nil, marshalErr+ }+ body = bytes.NewReader(data)+ }+ req, err := http.NewRequestWithContext(ctx, method, endpoint, body)+ if err != nil {+ return nil, err+ }+ req.Header.Set("Content-Type", "application/json")+ resp, err := c.anthropicHTTP.Do(req)+ if err != nil {+ return nil, err+ }+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ defer resp.Body.Close()+ data, _ := io.ReadAll(io.LimitReader(resp.Body, 64*1024))+ return nil, anthropicError(data, resp.StatusCode)+ }+ return resp, nil+}++func anthropicError(data []byte, status int) error {+ var envelope struct {+ Error struct {+ Type string `json:"type"`+ Message string `json:"message"`+ } `json:"error"`+ }+ _ = json.Unmarshal(data, &envelope)+ if envelope.Error.Message == "" {+ envelope.Error.Message = fmt.Sprintf("Anthropic API request failed (HTTP %d)", status)+ }+ return &openai.APIError{HTTPStatusCode: status, Type: envelope.Error.Type,+ Code: envelope.Error.Type, Message: envelope.Error.Message}+}++func anthropicJSON(value any) json.RawMessage {+ data, _ := json.Marshal(value)+ return data+}++func anthropicText(text string) json.RawMessage {+ return anthropicJSON(struct {+ Type string `json:"type"`+ Text string `json:"text"`+ }{"text", text})+}++func buildAnthropicRequest(ctx context.Context, request openai.ChatCompletionRequest) (ret anthropicRequest, err error) {+ ret.Model, ret.Stream = request.Model, request.Stream+ ret.MaxTokens = request.MaxCompletionTokens+ if ret.MaxTokens <= 0 {+ ret.MaxTokens = request.MaxTokens+ }+ if ret.MaxTokens <= 0 {+ // Messages 必须指定输出上限,配置为自动时使用保守的默认预算。+ ret.MaxTokens = 4096+ }+ temperature := max(float32(0), min(float32(1), request.Temperature))+ ret.Temperature = &temperature+ if anthropicFixedSampling(request.Model) {+ ret.Temperature = nil+ }+ ret.Stop = request.Stop+ if err = configureAnthropicThinking(&ret, request.ReasoningEffort); err != nil {+ return+ }+ for _, tool := range request.Tools {+ if tool.Type != openai.ToolTypeFunction || tool.Function == nil {+ return ret, errors.New("Anthropic Messages only supports function tools in this client")+ }+ ret.Tools = append(ret.Tools, anthropicTool{tool.Function.Name, tool.Function.Description, tool.Function.Parameters})+ }+ if request.ToolChoice != nil {+ switch choice := request.ToolChoice.(type) {+ case string:+ kind := choice+ if kind == "required" {+ kind = "any"+ }+ ret.ToolChoice = map[string]string{"type": kind}+ case openai.ToolChoice:+ ret.ToolChoice = map[string]string{"type": "tool", "name": choice.Function.Name}+ default:+ return ret, errors.New("unsupported Anthropic tool choice")+ }+ }+ native := aiMessageContents(ctx)+ assistantIndex := 0+ for _, message := range request.Messages {+ if message.Role == openai.ChatMessageRoleSystem || message.Role == "developer" {+ if message.Content != "" {+ if len(ret.Messages) == 0 {+ ret.System = append(ret.System, anthropicText(message.Content))+ } else {+ ret.appendMessage("user", []json.RawMessage{anthropicText(message.Content)})+ }+ }+ continue+ }+ blocks, blockErr := anthropicMessageBlocks(message)+ if blockErr != nil {+ return ret, blockErr+ }+ role := message.Role+ if role == openai.ChatMessageRoleTool {+ role = "user"+ }+ if role == "assistant" {+ if assistantIndex < len(native) && native[assistantIndex] != nil &&+ IsAnthropicMessagesProtocol(native[assistantIndex].Protocol) {+ content := native[assistantIndex]+ if content.Version != anthropicContentVersion {+ return ret, errors.New("unsupported Anthropic conversation content version")+ }+ if err = validateAnthropicHistory(content.Blocks, message.ToolCalls); err != nil {+ return ret, err+ }+ blocks = CloneOpenAIResponseOutput(content.Blocks)+ }+ assistantIndex+++ }+ if role != "assistant" && role != "user" {+ return ret, fmt.Errorf("unsupported Anthropic message role %q", role)+ }+ if len(blocks) == 0 {+ blocks = []json.RawMessage{anthropicText(" ")}+ }+ ret.appendMessage(role, blocks)+ }+ return ret, validateAnthropicToolResults(ret.Messages)+}++func (r *anthropicRequest) appendMessage(role string, blocks []json.RawMessage) {+ if len(r.Messages) > 0 && r.Messages[len(r.Messages)-1].Role == role {+ r.Messages[len(r.Messages)-1].Content = append(r.Messages[len(r.Messages)-1].Content, blocks...)+ } else {+ r.Messages = append(r.Messages, anthropicMessage{role, blocks})+ }+}++func configureAnthropicThinking(request *anthropicRequest, effort string) error {+ effort = strings.ToLower(strings.TrimSpace(effort))+ if effort == "" {+ return nil+ }+ if effort == "none" {+ model := strings.ToLower(request.Model)+ if strings.Contains(model, "claude-mythos") || strings.Contains(model, "claude-fable") {+ request.Thinking = &anthropicThinking{Type: "adaptive"}+ request.OutputConfig = map[string]string{"effort": "low"}+ } else {+ request.Thinking = &anthropicThinking{Type: "disabled"}+ }+ return nil+ }+ budgets := map[string]int{"low": 1024, "medium": 4096, "high": 8192, "xhigh": 16384, "max": 32768}+ budget, ok := budgets[effort]+ if !ok {+ return fmt.Errorf("unsupported Anthropic reasoning effort %q", effort)+ }+ model := strings.ToLower(request.Model)+ if anthropicLegacyThinking(model) {+ // 思考预算包含在输出上限中,为可见回答保留至少一半预算。+ budget = min(budget, request.MaxTokens/2)+ if budget < 1024 {+ return errors.New("Anthropic thinking requires an output token limit of at least 2048")+ }+ request.Thinking = &anthropicThinking{Type: "enabled", BudgetTokens: budget}+ } else {+ if effort == "xhigh" && (strings.Contains(model, "claude-opus-4-6") || strings.Contains(model, "claude-sonnet-4-6")) {+ effort = "max"+ }+ request.Thinking = &anthropicThinking{Type: "adaptive"}+ request.OutputConfig = map[string]string{"effort": effort}+ }+ request.Temperature = nil+ return nil+}++func anthropicLegacyThinking(model string) bool {+ model = strings.ToLower(model)+ for _, prefix := range []string{"claude-3-7", "claude-sonnet-4-5", "claude-opus-4-5", "claude-haiku-4-5",+ "claude-opus-4-1", "claude-sonnet-4-202", "claude-opus-4-202"} {+ if strings.Contains(model, prefix) {+ return true+ }+ }+ return model == "claude-sonnet-4" || model == "claude-opus-4"+}++func anthropicFixedSampling(model string) bool {+ model = strings.ToLower(model)+ return strings.Contains(model, "claude-") && !anthropicLegacyThinking(model) &&+ !strings.Contains(model, "claude-3") && !strings.Contains(model, "claude-opus-4-6") &&+ !strings.Contains(model, "claude-sonnet-4-6")+}++func anthropicMessageBlocks(message openai.ChatCompletionMessage) ([]json.RawMessage, error) {+ if message.Role == openai.ChatMessageRoleTool {+ return []json.RawMessage{anthropicJSON(map[string]any{+ "type": "tool_result", "tool_use_id": message.ToolCallID, "content": message.Content,+ })}, nil+ }+ var blocks []json.RawMessage+ if message.Content != "" {+ blocks = append(blocks, anthropicText(message.Content))+ }+ for _, part := range message.MultiContent {+ switch part.Type {+ case openai.ChatMessagePartTypeText:+ blocks = append(blocks, anthropicText(part.Text))+ case openai.ChatMessagePartTypeImageURL:+ if part.ImageURL == nil {+ return nil, errors.New("missing Anthropic image source")+ }+ source := map[string]string{"type": "url", "url": part.ImageURL.URL}+ if strings.HasPrefix(part.ImageURL.URL, "data:") {+ meta, data, ok := strings.Cut(strings.TrimPrefix(part.ImageURL.URL, "data:"), ";base64,")+ if !ok || data == "" || (meta != "image/png" && meta != "image/jpeg" && meta != "image/gif" && meta != "image/webp") {+ return nil, errors.New("unsupported Anthropic image data URL")+ }+ source = map[string]string{"type": "base64", "media_type": meta, "data": data}+ }+ blocks = append(blocks, anthropicJSON(map[string]any{"type": "image", "source": source}))+ default:+ return nil, errors.New("unsupported Anthropic input content")+ }+ }+ for _, call := range message.ToolCalls {+ input := json.RawMessage(call.Function.Arguments)+ if !validAnthropicToolInput(input) || call.ID == "" || call.Function.Name == "" {+ return nil, errors.New("invalid Anthropic tool call in conversation")+ }+ blocks = append(blocks, anthropicJSON(map[string]any{+ "type": "tool_use", "id": call.ID, "name": call.Function.Name, "input": input,+ }))+ }+ return blocks, nil+}++func validAnthropicToolInput(input json.RawMessage) bool {+ input = bytes.TrimSpace(input)+ return len(input) > 0 && input[0] == '{' && json.Valid(input)+}++type anthropicContentBlock struct {+ Type string `json:"type"`+ Text string `json:"text"`+ Thinking string `json:"thinking"`+ Signature string `json:"signature"`+ Data string `json:"data"`+ ID string `json:"id"`+ Name string `json:"name"`+ Input json.RawMessage `json:"input"`+ ToolUseID string `json:"tool_use_id"`+}++func validateAnthropicHistory(blocks []json.RawMessage, calls []openai.ToolCall) error {+ if len(blocks) == 0 {+ return errors.New("empty Anthropic conversation content")+ }+ callIndex := 0+ callIDs := map[string]bool{}+ for _, raw := range blocks {+ var block anthropicContentBlock+ if json.Unmarshal(raw, &block) != nil {+ return errors.New("invalid Anthropic conversation content")+ }+ switch block.Type {+ case "text":+ case "thinking":+ if block.Signature == "" {+ return errors.New("Anthropic thinking signature is missing")+ }+ case "redacted_thinking":+ if block.Data == "" {+ return errors.New("Anthropic redacted thinking is missing")+ }+ case "tool_use":+ if block.ID == "" || block.Name == "" || callIDs[block.ID] || !validAnthropicToolInput(block.Input) || callIndex >= len(calls) ||+ block.ID != calls[callIndex].ID || block.Name != calls[callIndex].Function.Name {+ return errors.New("Anthropic conversation tool calls do not match native content")+ }+ callIDs[block.ID] = true+ if !equalAnthropicToolInput(block.Input, []byte(calls[callIndex].Function.Arguments)) {+ return errors.New("Anthropic conversation tool arguments do not match native content")+ }+ callIndex+++ default:+ return fmt.Errorf("unsupported Anthropic content block %q", block.Type)+ }+ }+ if callIndex != len(calls) {+ return errors.New("Anthropic conversation is missing native tool calls")+ }+ return nil+}++func equalAnthropicToolInput(native, projected []byte) bool {+ // 会话序列化可能调整对象键顺序,比较结构时保留数字精度和原生内容本身。+ decode := func(data []byte) (value any, err error) {+ if !validAnthropicToolInput(data) {+ return nil, errors.New("invalid Anthropic tool input")+ }+ decoder := json.NewDecoder(bytes.NewReader(data))+ decoder.UseNumber()+ err = decoder.Decode(&value)+ return+ }+ nativeValue, nativeErr := decode(native)+ projectedValue, projectedErr := decode(projected)+ return nativeErr == nil && projectedErr == nil && reflect.DeepEqual(nativeValue, projectedValue)+}++func validateAnthropicToolResults(messages []anthropicMessage) error {+ pending := map[string]bool{}+ for _, message := range messages {+ for _, raw := range message.Content {+ var block anthropicContentBlock+ if err := json.Unmarshal(raw, &block); err != nil {+ return err+ }+ if block.Type == "tool_result" {+ if message.Role != "user" || !pending[block.ToolUseID] {+ return errors.New("Anthropic tool result has no matching tool call")+ }+ delete(pending, block.ToolUseID)+ } else if message.Role == "user" && len(pending) > 0 {+ return errors.New("Anthropic tool results must precede other user content")+ } else if block.Type == "tool_use" {+ if message.Role != "assistant" || pending[block.ID] {+ return errors.New("invalid Anthropic tool call order")+ }+ pending[block.ID] = true+ }+ }+ }+ if len(pending) > 0 {+ return errors.New("Anthropic conversation is missing tool results")+ }+ return nil+}++type anthropicResponse struct {+ ID string `json:"id"`+ Model string `json:"model"`+ Content []json.RawMessage `json:"content"`+ StopReason string `json:"stop_reason"`+ Usage anthropicUsage `json:"usage"`+}++func anthropicCompletion(response anthropicResponse) (openai.ChatCompletionResponse, error) {+ message := openai.ChatCompletionMessage{Role: "assistant"}+ for i, raw := range response.Content {+ var block anthropicContentBlock+ if err := json.Unmarshal(raw, &block); err != nil {+ return openai.ChatCompletionResponse{}, err+ }+ switch block.Type {+ case "text":+ message.Content += block.Text+ case "thinking":+ message.ReasoningContent += block.Thinking+ case "tool_use":+ index := i+ message.ToolCalls = append(message.ToolCalls, openai.ToolCall{Index: &index, ID: block.ID,+ Type: openai.ToolTypeFunction, Function: openai.FunctionCall{Name: block.Name, Arguments: string(block.Input)}})+ }+ }+ if len(response.Content) > 0 {+ if err := validateAnthropicHistory(response.Content, message.ToolCalls); err != nil {+ return openai.ChatCompletionResponse{}, err+ }+ }+ finish, err := anthropicFinishReason(response.StopReason, len(message.ToolCalls) > 0)+ if err != nil {+ return openai.ChatCompletionResponse{}, err+ }+ return openai.ChatCompletionResponse{ID: response.ID, Model: response.Model, Object: "chat.completion",+ Choices: []openai.ChatCompletionChoice{{Index: 0, Message: message, FinishReason: finish}},+ Usage: response.Usage.chatUsage()}, nil+}++func anthropicFinishReason(reason string, tools bool) (openai.FinishReason, error) {+ if tools && reason != "tool_use" {+ return "", errors.New("Anthropic response ended with incomplete tool use")+ }+ switch reason {+ case "end_turn", "stop_sequence":+ return openai.FinishReasonStop, nil+ case "tool_use":+ if !tools {+ return "", errors.New("Anthropic tool_use stop reason has no tool calls")+ }+ return openai.FinishReasonToolCalls, nil+ case "max_tokens":+ return openai.FinishReasonLength, nil+ case "refusal":+ return openai.FinishReasonContentFilter, nil+ default:+ return "", fmt.Errorf("unsupported Anthropic stop reason %q", reason)+ }+}++func createAnthropicCompletion(ctx context.Context, client *AIClient, request openai.ChatCompletionRequest) (openai.ChatCompletionResponse, error) {+ request.Stream = false+ payload, err := buildAnthropicRequest(ctx, request)+ if err != nil {+ return openai.ChatCompletionResponse{}, err+ }+ resp, err := client.anthropicRequest(ctx, http.MethodPost, "messages", payload)+ if err != nil {+ return openai.ChatCompletionResponse{}, err+ }+ defer resp.Body.Close()+ var response anthropicResponse+ if err = json.NewDecoder(io.LimitReader(resp.Body, 32*1024*1024)).Decode(&response); err != nil {+ return openai.ChatCompletionResponse{}, err+ }+ return anthropicCompletion(response)+}diff --git a/kernel/util/anthropic_models.go b/kernel/util/anthropic_models.gonew file mode 100644index 0000000000..78b894ded9--- /dev/null+++ b/kernel/util/anthropic_models.go@@ -0,0 +1,94 @@+package util++import (+ "context"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "net/url"+ "strings"+ "time"+)++// ListProviderModels 按提供商协议读取模型清单,保持通用接口的返回结构。+func ListProviderModels(apiKey, baseURL, protocol string, timeout int, headers ...map[string]string) ([]AvailableModel, error) {+ if !IsAnthropicMessagesProtocol(protocol) {+ return ListAvailableModelsWithContext(apiKey, baseURL, timeout, headers...)+ }+ if timeout < 1 {+ timeout = 30+ }+ ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)+ defer cancel()+ return listAnthropicModels(ctx, NewAIClientWithModel(apiKey, baseURL, "", headers...))+}++func listAnthropicModels(ctx context.Context, client *AIClient) ([]AvailableModel, error) {+ var models []AvailableModel+ cursor := ""+ seen := map[string]bool{}+ cursors := map[string]bool{}+ for {+ endpoint, err := anthropicEndpoint(client.baseURL, "models")+ if err != nil {+ return nil, err+ }+ parsed, _ := url.Parse(endpoint)+ query := parsed.Query()+ query.Set("limit", "1000")+ if cursor != "" {+ query.Set("after_id", cursor)+ }+ parsed.RawQuery = query.Encode()+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, parsed.String(), nil)+ if err != nil {+ return nil, err+ }+ resp, err := client.anthropicHTTP.Do(req)+ if err != nil {+ return nil, err+ }+ page, err := readAnthropicModelsPage(resp)+ if err != nil {+ return nil, err+ }+ for _, item := range page.Data {+ id := strings.TrimSpace(item.ID)+ if id == "" || seen[id] {+ continue+ }+ seen[id] = true+ models = append(models, AvailableModel{ID: id,+ ContextLength: firstValidModelContextLength(item.MaxInputTokens, item.ContextLength)})+ }+ if !page.HasMore {+ return models, nil+ }+ if page.LastID == "" || cursors[page.LastID] || len(models) > 100000 {+ return nil, errors.New("invalid Anthropic model pagination")+ }+ cursors[page.LastID] = true+ cursor = page.LastID+ }+}++type anthropicModelsPage struct {+ Data []struct {+ ID string `json:"id"`+ MaxInputTokens json.RawMessage `json:"max_input_tokens"`+ ContextLength json.RawMessage `json:"context_length"`+ } `json:"data"`+ HasMore bool `json:"has_more"`+ LastID string `json:"last_id"`+}++func readAnthropicModelsPage(response *http.Response) (page anthropicModelsPage, err error) {+ defer response.Body.Close()+ if response.StatusCode < 200 || response.StatusCode >= 300 {+ data, _ := io.ReadAll(io.LimitReader(response.Body, 64*1024))+ return page, anthropicError(data, response.StatusCode)+ }+ err = json.NewDecoder(io.LimitReader(response.Body, 32*1024*1024)).Decode(&page)+ return+}diff --git a/kernel/util/anthropic_stream.go b/kernel/util/anthropic_stream.gonew file mode 100644index 0000000000..9c5c643fd1--- /dev/null+++ b/kernel/util/anthropic_stream.go@@ -0,0 +1,242 @@+package util++import (+ "bufio"+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "strings"++ "github.com/sashabaranov/go-openai"+)++type anthropicStream struct {+ body io.ReadCloser+ scanner *bufio.Scanner+ response anthropicResponse+ block map[string]json.RawMessage+ blockType string+ blockIndex int+ arguments strings.Builder+ text strings.Builder+ thinking strings.Builder+ signature strings.Builder+ started bool+ done bool+ content *AIMessageContent+}++func createAnthropicStream(ctx context.Context, client *AIClient, request openai.ChatCompletionRequest) (*OpenAICompletionStream, error) {+ request.Stream = true+ payload, err := buildAnthropicRequest(ctx, request)+ if err != nil {+ return nil, err+ }+ response, err := client.anthropicRequest(ctx, http.MethodPost, "messages", payload)+ if err != nil {+ return nil, err+ }+ scanner := bufio.NewScanner(response.Body)+ scanner.Buffer(make([]byte, 64*1024), 32*1024*1024)+ return &OpenAICompletionStream{anthropic: &anthropicStream{body: response.Body, scanner: scanner}}, nil+}++// readEvent 读取完整 SSE 事件,保留多行 data,并让心跳返回上层重置空闲计时器。+func (s *anthropicStream) readEvent() ([]byte, error) {+ var data bytes.Buffer+ for s.scanner.Scan() {+ line := strings.TrimSuffix(s.scanner.Text(), "\r")+ if line == "" {+ return bytes.TrimSuffix(data.Bytes(), []byte("\n")), nil+ }+ if strings.HasPrefix(line, "data:") {+ data.WriteString(strings.TrimPrefix(strings.TrimPrefix(line, "data:"), " "))+ data.WriteByte('\n')+ if data.Len() > 32*1024*1024 {+ return nil, errors.New("Anthropic stream event is too large")+ }+ }+ }+ if err := s.scanner.Err(); err != nil {+ return nil, err+ }+ return nil, errors.New("Anthropic stream ended before message_stop")+}++func (s *anthropicStream) recv() (openai.ChatCompletionStreamResponse, error) {+ ret := openai.ChatCompletionStreamResponse{Object: "chat.completion.chunk", ID: s.response.ID, Model: s.response.Model}+ if s.done {+ return ret, io.EOF+ }+ data, err := s.readEvent()+ if err != nil || len(data) == 0 {+ return ret, err+ }+ var event struct {+ Type string `json:"type"`+ Index int `json:"index"`+ Message *anthropicResponse `json:"message"`+ ContentBlock map[string]json.RawMessage `json:"content_block"`+ Delta struct {+ Type string `json:"type"`+ Text string `json:"text"`+ Thinking string `json:"thinking"`+ Signature string `json:"signature"`+ PartialJSON string `json:"partial_json"`+ StopReason string `json:"stop_reason"`+ } `json:"delta"`+ Usage json.RawMessage `json:"usage"`+ }+ if err = json.Unmarshal(data, &event); err != nil {+ return ret, fmt.Errorf("invalid Anthropic stream event: %w", err)+ }+ delta := openai.ChatCompletionStreamChoiceDelta{}+ switch event.Type {+ case "error":+ return ret, anthropicError(data, 0)+ case "message_start":+ if s.started || event.Message == nil || len(event.Message.Content) != 0 {+ return ret, errors.New("invalid Anthropic message_start")+ }+ s.started = true+ s.response = *event.Message+ case "content_block_start":+ if !s.started || s.block != nil || event.ContentBlock == nil || event.Index != len(s.response.Content) {+ return ret, errors.New("invalid Anthropic content block order")+ }+ s.block, s.blockIndex = event.ContentBlock, event.Index+ s.arguments.Reset()+ s.text.Reset()+ s.thinking.Reset()+ s.signature.Reset()+ if json.Unmarshal(s.block["type"], &s.blockType) != nil {+ return ret, errors.New("missing Anthropic content block type")+ }+ switch s.blockType {+ case "text":+ _ = json.Unmarshal(s.block["text"], &delta.Content)+ s.text.WriteString(delta.Content)+ case "thinking":+ _ = json.Unmarshal(s.block["thinking"], &delta.ReasoningContent)+ s.thinking.WriteString(delta.ReasoningContent)+ var signature string+ _ = json.Unmarshal(s.block["signature"], &signature)+ s.signature.WriteString(signature)+ case "tool_use":+ call := openai.ToolCall{Index: &event.Index, Type: openai.ToolTypeFunction}+ _ = json.Unmarshal(s.block["id"], &call.ID)+ _ = json.Unmarshal(s.block["name"], &call.Function.Name)+ if call.ID == "" || call.Function.Name == "" {+ return ret, errors.New("incomplete Anthropic tool call identity")+ }+ delta.ToolCalls = []openai.ToolCall{call}+ case "redacted_thinking":+ default:+ return ret, fmt.Errorf("unsupported Anthropic content block %q", s.blockType)+ }+ case "content_block_delta":+ if s.block == nil || event.Index != s.blockIndex {+ return ret, errors.New("Anthropic content delta has no matching block")+ }+ switch event.Delta.Type {+ case "text_delta":+ if s.blockType != "text" {+ return ret, errors.New("Anthropic text delta has an incompatible block")+ }+ s.appendString("text", event.Delta.Text)+ delta.Content = event.Delta.Text+ case "thinking_delta":+ if s.blockType != "thinking" {+ return ret, errors.New("Anthropic thinking delta has an incompatible block")+ }+ s.appendString("thinking", event.Delta.Thinking)+ delta.ReasoningContent = event.Delta.Thinking+ case "signature_delta":+ if s.blockType != "thinking" {+ return ret, errors.New("Anthropic signature delta has an incompatible block")+ }+ s.appendString("signature", event.Delta.Signature)+ case "input_json_delta":+ if s.blockType != "tool_use" {+ return ret, errors.New("Anthropic input delta has an incompatible block")+ }+ s.arguments.WriteString(event.Delta.PartialJSON)+ if s.arguments.Len() > 32*1024*1024 {+ return ret, errors.New("Anthropic tool input is too large")+ }+ delta.ToolCalls = []openai.ToolCall{{Index: &event.Index,+ Function: openai.FunctionCall{Arguments: event.Delta.PartialJSON}}}+ }+ case "content_block_stop":+ if s.block == nil || event.Index != s.blockIndex {+ return ret, errors.New("Anthropic content stop has no matching block")+ }+ if s.blockType == "text" {+ s.block["text"] = anthropicJSON(s.text.String())+ } else if s.blockType == "thinking" {+ s.block["thinking"] = anthropicJSON(s.thinking.String())+ s.block["signature"] = anthropicJSON(s.signature.String())+ }+ if s.blockType == "tool_use" {+ if s.arguments.Len() > 0 {+ s.block["input"] = json.RawMessage(s.arguments.String())+ } else {+ delta.ToolCalls = []openai.ToolCall{{Index: &event.Index,+ Function: openai.FunctionCall{Arguments: string(s.block["input"])}}}+ }+ if !validAnthropicToolInput(s.block["input"]) {+ return ret, errors.New("Anthropic tool input is not a complete JSON object")+ }+ }+ s.response.Content = append(s.response.Content, anthropicJSON(s.block))+ s.block = nil+ case "message_delta":+ if !s.started || s.block != nil {+ return ret, errors.New("invalid Anthropic message_delta order")+ }+ if event.Delta.StopReason != "" {+ s.response.StopReason = event.Delta.StopReason+ }+ if len(event.Usage) > 0 && string(event.Usage) != "null" {+ // 用量字段为累计值,未出现的字段保留 message_start 中的值。+ if err = json.Unmarshal(event.Usage, &s.response.Usage); err != nil {+ return ret, err+ }+ }+ case "message_stop":+ if !s.started || s.block != nil {+ return ret, errors.New("Anthropic message stopped with an incomplete content block")+ }+ completion, completionErr := anthropicCompletion(s.response)+ if completionErr != nil {+ return ret, completionErr+ }+ s.done = true+ if len(s.response.Content) > 0 {+ s.content = &AIMessageContent{Protocol: AnthropicProtocolMessages, Version: anthropicContentVersion,+ Blocks: CloneOpenAIResponseOutput(s.response.Content)}+ }+ ret.Usage = &completion.Usage+ ret.Choices = []openai.ChatCompletionStreamChoice{{Index: 0, FinishReason: completion.Choices[0].FinishReason}}+ return ret, nil+ }+ if delta.Content != "" || delta.ReasoningContent != "" || len(delta.ToolCalls) > 0 {+ ret.Choices = []openai.ChatCompletionStreamChoice{{Index: 0, Delta: delta}}+ }+ return ret, nil+}++func (s *anthropicStream) appendString(field, value string) {+ switch field {+ case "text":+ s.text.WriteString(value)+ case "thinking":+ s.thinking.WriteString(value)+ case "signature":+ s.signature.WriteString(value)+ }+}diff --git a/kernel/util/anthropic_test.go b/kernel/util/anthropic_test.gonew file mode 100644index 0000000000..a0ad70e290--- /dev/null+++ b/kernel/util/anthropic_test.go@@ -0,0 +1,385 @@+package util++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "reflect"+ "strings"+ "testing"+ "time"++ "github.com/sashabaranov/go-openai"+)++func writeAnthropicEvents(w http.ResponseWriter, events ...string) {+ w.Header().Set("Content-Type", "text/event-stream")+ for _, event := range events {+ _, _ = fmt.Fprintf(w, "data: %s\n\n", event)+ if flusher, ok := w.(http.Flusher); ok {+ flusher.Flush()+ }+ }+}++var anthropicToolEvents = []string{+ `{"type":"message_start","message":{"id":"msg_1","model":"test","content":[],"usage":{"input_tokens":11,"output_tokens":1,"cache_creation_input_tokens":3,"cache_read_input_tokens":7}}}`,+ `{"type":"ping"}`,+ `{"type":"future_event"}`,+ `{"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}}`,+ `{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"Think"}}`,+ `{"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"signed-"}}`,+ `{"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"opaque"}}`,+ `{"type":"content_block_stop","index":0}`,+ `{"type":"content_block_start","index":1,"content_block":{"type":"redacted_thinking","data":"opaque-data"}}`,+ `{"type":"content_block_stop","index":1}`,+ `{"type":"content_block_start","index":2,"content_block":{"type":"text","text":""}}`,+ `{"type":"content_block_delta","index":2,"delta":{"type":"text_delta","text":"Checking"}}`,+ `{"type":"content_block_stop","index":2}`,+ `{"type":"content_block_start","index":3,"content_block":{"type":"tool_use","id":"tool_1","name":"lookup","input":{}}}`,+ `{"type":"content_block_delta","index":3,"delta":{"type":"input_json_delta","partial_json":"{\"q\":"}}`,+ `{"type":"content_block_delta","index":3,"delta":{"type":"input_json_delta","partial_json":"\"hello\"}"}}`,+ `{"type":"content_block_stop","index":3}`,+ `{"type":"content_block_start","index":4,"content_block":{"type":"tool_use","id":"tool_2","name":"list","input":{}}}`,+ `{"type":"content_block_stop","index":4}`,+ `{"type":"message_delta","delta":{"stop_reason":null},"usage":{"output_tokens":5}}`,+ `{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":9}}`,+ `{"type":"message_stop"}`,+}++func TestAnthropicStreamAndNativeHistory(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/gateway/v1/messages" || r.Header.Get("x-api-key") != "override-key" ||+ r.Header.Get("anthropic-version") != "2023-06-01" || r.Header.Get("X-Custom") != "custom" {+ t.Errorf("unexpected request path or headers: %s %v", r.URL.Path, r.Header)+ }+ var request anthropicRequest+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil {+ t.Error(err)+ }+ if !request.Stream || request.MaxTokens != 4096 || request.Model != "test" {+ t.Errorf("unexpected request: %+v", request)+ }+ writeAnthropicEvents(w, anthropicToolEvents...)+ }))+ defer server.Close()+ client := NewAIClientWithModel("key", server.URL+"/gateway/v1", "test", map[string]string{+ "X-Api-Key": "override-key", "X-Custom": "custom",+ })+ stream, err := CreateOpenAICompletionStream(context.Background(), client, AnthropicProtocolMessages,+ openai.ChatCompletionRequest{Model: "test", Messages: []openai.ChatCompletionMessage{{Role: "user", Content: "hello"}}}, nil)+ if err != nil {+ t.Fatal(err)+ }+ defer stream.Close()+ var text, thinking string+ calls := map[int]openai.ToolCall{}+ var usages []openai.Usage+ for {+ part, receiveErr := stream.Recv()+ if errors.Is(receiveErr, io.EOF) {+ break+ }+ if receiveErr != nil {+ t.Fatal(receiveErr)+ }+ if part.Usage != nil {+ usages = append(usages, *part.Usage)+ }+ for _, choice := range part.Choices {+ text += choice.Delta.Content+ thinking += choice.Delta.ReasoningContent+ for _, delta := range choice.Delta.ToolCalls {+ call := calls[*delta.Index]+ if delta.ID != "" {+ call.ID = delta.ID+ }+ call.Function.Name += delta.Function.Name+ call.Function.Arguments += delta.Function.Arguments+ calls[*delta.Index] = call+ }+ }+ }+ if text != "Checking" || thinking != "Think" || len(calls) != 2 ||+ calls[3].Function.Arguments != `{"q":"hello"}` || calls[4].Function.Arguments != `{}` {+ t.Fatalf("unexpected stream projection: %s %s %+v", text, thinking, calls)+ }+ if len(usages) != 1 || usages[0].PromptTokens != 21 || usages[0].CompletionTokens != 9 ||+ usages[0].TotalTokens != 30 || usages[0].PromptTokensDetails.CachedTokens != 7 {+ t.Fatalf("cumulative usage was not merged: %+v", usages)+ }+ native := stream.NativeContent()+ if native == nil || len(native.Blocks) != 5 || !strings.Contains(string(native.Blocks[0]), "signed-opaque") {+ t.Fatalf("missing native thinking: %+v", native)+ }+ persisted, _ := json.Marshal(native)+ var restored AIMessageContent+ if err = json.Unmarshal(persisted, &restored); err != nil {+ t.Fatal(err)+ }+ request := openai.ChatCompletionRequest{Model: "test", Messages: []openai.ChatCompletionMessage{+ {Role: "system", Content: "instructions"},+ {Role: "user", Content: "hello"},+ {Role: "assistant", Content: text, ToolCalls: []openai.ToolCall{calls[3], calls[4]}},+ {Role: "tool", ToolCallID: "tool_1", Content: "found"},+ {Role: "tool", ToolCallID: "tool_2", Content: "listed"},+ }}+ payload, err := buildAnthropicRequest(ContextWithAIMessageContents(context.Background(), []*AIMessageContent{&restored}), request)+ if err != nil {+ t.Fatal(err)+ }+ if len(payload.Messages) != 3 || len(payload.Messages[2].Content) != 2 ||+ !reflect.DeepEqual(payload.Messages[1].Content, restored.Blocks) {+ t.Fatalf("native history or grouped tool results changed: %+v", payload.Messages)+ }+ copy := stream.NativeContent()+ copy.Blocks[0][0] = 'x'+ if !json.Valid(stream.NativeContent().Blocks[0]) {+ t.Fatal("native content was not cloned")+ }+}++func TestAnthropicMessagesImagesAndThinking(t *testing.T) {+ request := openai.ChatCompletionRequest{Model: "claude-sonnet-4-6", MaxCompletionTokens: 8192,+ Temperature: 1.7, ReasoningEffort: "medium", Messages: []openai.ChatCompletionMessage{+ {Role: "system", Content: "system"}, {Role: "system", Content: "summary"},+ {Role: "user", MultiContent: []openai.ChatMessagePart{+ {Type: openai.ChatMessagePartTypeText, Text: "look"},+ {Type: openai.ChatMessagePartTypeImageURL, ImageURL: &openai.ChatMessageImageURL{URL: "data:image/png;base64,aGVsbG8="}},+ {Type: openai.ChatMessagePartTypeImageURL, ImageURL: &openai.ChatMessageImageURL{URL: "https://example.com/image.png"}},+ }},+ }, Tools: []openai.Tool{{Type: openai.ToolTypeFunction, Function: &openai.FunctionDefinition{+ Name: "search", Parameters: map[string]any{"type": "object"},+ }}}}+ payload, err := buildAnthropicRequest(context.Background(), request)+ if err != nil {+ t.Fatal(err)+ }+ if len(payload.System) != 2 || len(payload.Messages[0].Content) != 3 || payload.Thinking.Type != "adaptive" ||+ payload.OutputConfig["effort"] != "medium" || payload.Temperature != nil || len(payload.Tools) != 1 {+ t.Fatalf("unexpected native request: %+v", payload)+ }+ data, _ := json.Marshal(payload)+ for _, expected := range []string{`"media_type":"image/png"`, `"type":"url"`, `"input_schema"`, `"max_tokens":8192`} {+ if !strings.Contains(string(data), expected) {+ t.Errorf("missing %s: %s", expected, data)+ }+ }+ for _, forbidden := range []string{"reasoning_effort", "max_completion_tokens", "stream_options", "image_url"} {+ if strings.Contains(string(data), forbidden) {+ t.Errorf("OpenAI field leaked into native request: %s", forbidden)+ }+ }+ request.Model = "claude-sonnet-4-5"+ payload, err = buildAnthropicRequest(context.Background(), request)+ if err != nil || payload.Thinking.Type != "enabled" || payload.Thinking.BudgetTokens != 4096 {+ t.Fatalf("legacy thinking: %+v %v", payload, err)+ }+ request.ReasoningEffort = "none"+ payload, err = buildAnthropicRequest(context.Background(), request)+ if err != nil || payload.Thinking.Type != "disabled" || *payload.Temperature != 1 {+ t.Fatalf("disabled thinking: %+v %v", payload, err)+ }+}++func TestAnthropicIncompleteStreams(t *testing.T) {+ for _, tc := range []struct {+ name string+ events []string+ }{+ {"empty", nil},+ {"missing stop", anthropicToolEvents[:len(anthropicToolEvents)-1]},+ {"missing block stop", append(append([]string(nil), anthropicToolEvents[:16]...), `{"type":"message_stop"}`)},+ {"truncated tools", append(append([]string(nil), anthropicToolEvents[:19]...),+ `{"type":"message_delta","delta":{"stop_reason":"max_tokens"}}`, `{"type":"message_stop"}`)},+ {"malformed input", []string{anthropicToolEvents[0],+ `{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"a","name":"search","input":{}}}`,+ `{"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{"}}`,+ `{"type":"content_block_stop","index":0}`}},+ {"unsigned thinking", []string{anthropicToolEvents[0], anthropicToolEvents[3], anthropicToolEvents[4], anthropicToolEvents[7],+ `{"type":"message_delta","delta":{"stop_reason":"end_turn"}}`, `{"type":"message_stop"}`}},+ } {+ t.Run(tc.name, func(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ writeAnthropicEvents(w, tc.events...)+ }))+ defer server.Close()+ stream, err := createAnthropicStream(context.Background(), NewAIClientWithModel("", server.URL, "test"),+ openai.ChatCompletionRequest{Model: "test", Messages: []openai.ChatCompletionMessage{{Role: "user", Content: "test"}}})+ if err != nil {+ t.Fatal(err)+ }+ defer stream.Close()+ for i := 0; i < 100; i++ {+ _, err = stream.Recv()+ if err != nil {+ break+ }+ }+ if err == nil || errors.Is(err, io.EOF) || stream.NativeContent() != nil {+ t.Fatalf("incomplete stream was accepted: %v", err)+ }+ })+ }+}++func TestAnthropicNonStreamingAndErrors(t *testing.T) {+ for _, status := range []int{200, 401, 429, 529} {+ t.Run(fmt.Sprint(status), func(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(status)+ if status != 200 {+ _, _ = fmt.Fprint(w, `{"type":"error","error":{"type":"overloaded_error","message":"try later"}}`)+ return+ }+ _, _ = fmt.Fprint(w, `{"id":"msg","model":"test","content":[{"type":"text","text":"title"}],"stop_reason":"end_turn","usage":{"input_tokens":5,"output_tokens":2}}`)+ }))+ defer server.Close()+ response, err := CreateOpenAICompletion(context.Background(), NewAIClientWithModel("", server.URL, "test"),+ AnthropicProtocolMessages, openai.ChatCompletionRequest{Model: "test", Messages: []openai.ChatCompletionMessage{{Role: "user", Content: "title"}}}, nil)+ if status == 200 {+ if err != nil || response.Choices[0].Message.Content != "title" || response.Usage.TotalTokens != 7 {+ t.Fatalf("unexpected completion: %+v %v", response, err)+ }+ } else {+ var apiErr *openai.APIError+ if !errors.As(err, &apiErr) || apiErr.HTTPStatusCode != status || apiErr.Message != "try later" {+ t.Fatalf("unexpected error: %v", err)+ }+ }+ })+ }+}++func TestAnthropicModelsPagination(t *testing.T) {+ calls := 0+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ calls+++ if r.URL.Path != "/v1/models" || r.Header.Get("x-api-key") != "key" || r.Header.Get("anthropic-version") == "" {+ t.Errorf("unexpected model request: %s %v", r.URL.Path, r.Header)+ }+ if r.URL.Query().Get("after_id") == "" {+ _, _ = fmt.Fprint(w, `{"data":[{"id":"first","max_input_tokens":200000}],"has_more":true,"last_id":"first"}`)+ } else {+ if r.URL.Query().Get("after_id") != "first" {+ t.Error("unexpected cursor")+ }+ _, _ = fmt.Fprint(w, `{"data":[{"id":"second","max_input_tokens":null}],"has_more":false,"last_id":"second"}`)+ }+ }))+ defer server.Close()+ models, err := ListProviderModels("key", server.URL, AnthropicProtocolMessages, 5)+ if err != nil || calls != 2 || len(models) != 2 || models[0].ContextLength != 200000 || models[1].ContextLength != 0 {+ t.Fatalf("unexpected model list: %+v %v", models, err)+ }+}++func TestAnthropicCancellationAndCredentialRedirect(t *testing.T) {+ t.Run("cancel", func(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ writeAnthropicEvents(w, anthropicToolEvents[0])+ <-r.Context().Done()+ }))+ defer server.Close()+ ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)+ defer cancel()+ stream, err := createAnthropicStream(ctx, NewAIClientWithModel("", server.URL, "test"), openai.ChatCompletionRequest{+ Model: "test", Messages: []openai.ChatCompletionMessage{{Role: "user", Content: "hello"}},+ })+ if err != nil {+ t.Fatal(err)+ }+ defer stream.Close()+ _, _ = stream.Recv()+ _, err = stream.Recv()+ if err == nil || ctx.Err() == nil {+ t.Fatalf("stream was not canceled: %v", err)+ }+ })+ t.Run("redirect", func(t *testing.T) {+ target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Header.Get("x-api-key") != "" || r.Header.Get("X-Secret") != "" {+ t.Error("provider credentials crossed origins")+ }+ _, _ = fmt.Fprint(w, `{"data":[],"has_more":false}`)+ }))+ defer target.Close()+ origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ http.Redirect(w, r, target.URL, http.StatusTemporaryRedirect)+ }))+ defer origin.Close()+ _, err := ListProviderModels("key", origin.URL, AnthropicProtocolMessages, 5, map[string]string{"X-Secret": "private"})+ if err != nil {+ t.Fatal(err)+ }+ })+}++func TestAnthropicNativeVersionAndProtocolProjection(t *testing.T) {+ native := &AIMessageContent{Protocol: AnthropicProtocolMessages, Version: 99,+ Blocks: []json.RawMessage{json.RawMessage(`{"type":"text","text":"native"}`)}}+ request := openai.ChatCompletionRequest{Model: "test", Messages: []openai.ChatCompletionMessage{+ {Role: "user", Content: "hello"}, {Role: "assistant", Content: "answer"}, {Role: "user", Content: "continue"},+ }}+ ctx := ContextWithAIMessageContents(context.Background(), []*AIMessageContent{native})+ if _, err := buildAnthropicRequest(ctx, request); err == nil || !strings.Contains(err.Error(), "version") || native.Version != 99 {+ t.Fatalf("unknown native format was not preserved: %v", err)+ }+ for _, protocol := range []string{OpenAIProtocolChatCompletions, OpenAIProtocolResponses} {+ t.Run(protocol, func(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ data, _ := io.ReadAll(r.Body)+ if strings.Contains(string(data), "native") || !strings.Contains(string(data), "answer") {+ t.Errorf("native metadata crossed protocols or visible history was lost: %s", data)+ }+ if protocol == OpenAIProtocolChatCompletions {+ _, _ = fmt.Fprint(w, `{"choices":[{"message":{"role":"assistant","content":"done"},"finish_reason":"stop"}]}`)+ } else {+ _, _ = fmt.Fprint(w, `{"status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"done"}]}]}`)+ }+ }))+ defer server.Close()+ response, err := CreateOpenAICompletion(ctx, NewAIClientWithModel("", server.URL, "test"), protocol, request, nil)+ if err != nil || len(response.Choices) != 1 || response.Choices[0].Message.Content != "done" {+ t.Fatalf("cross-protocol completion failed: %+v %v", response, err)+ }+ })+ }+}++func TestAnthropicRestoredToolArguments(t *testing.T) {+ const nativeBlock = `{"type":"tool_use","id":"call","name":"lookup","input":{"nested":{"z":9007199254740993,"a":"value"},"first":true}}`+ for _, tc := range []struct {+ name string+ arguments string+ valid bool+ }{+ {"reordered", `{"first":true,"nested":{"a":"value","z":9007199254740993}}`, true},+ {"escaped", `{"first":true,"nested":{"a":"\u0076alue","z":9007199254740993}}`, true},+ {"rounded number", `{"first":true,"nested":{"a":"value","z":9007199254740992}}`, false},+ {"changed value", `{"first":false,"nested":{"a":"value","z":9007199254740993}}`, false},+ {"invalid JSON", `{"first":true} {}`, false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ native := &AIMessageContent{Protocol: AnthropicProtocolMessages, Version: 1,+ Blocks: []json.RawMessage{json.RawMessage(nativeBlock)}}+ request := openai.ChatCompletionRequest{Model: "test", Messages: []openai.ChatCompletionMessage{+ {Role: "user", Content: "lookup"},+ {Role: "assistant", ToolCalls: []openai.ToolCall{{ID: "call", Type: openai.ToolTypeFunction,+ Function: openai.FunctionCall{Name: "lookup", Arguments: tc.arguments}}}},+ {Role: "tool", ToolCallID: "call", Content: "found"},+ }}+ payload, err := buildAnthropicRequest(ContextWithAIMessageContents(context.Background(), []*AIMessageContent{native}), request)+ if (err == nil) != tc.valid {+ t.Fatalf("unexpected history validation: %v", err)+ }+ if tc.valid && string(payload.Messages[1].Content[0]) != nativeBlock {+ t.Fatal("native block changed during comparison")+ }+ })+ }+}diff --git a/kernel/util/openai.go b/kernel/util/openai.goindex 963b646c8d..25c69fdbe8 100644--- a/kernel/util/openai.go+++ b/kernel/util/openai.go@@ -81,7 +81,7 @@ type OpenAIImageAdapter struct {timeout time.Duration}-func ChatGPT(msg string, contextMsgs []string, c *openai.Client, apiBaseURL, protocol, model string, maxTokens int,+func ChatGPT(msg string, contextMsgs []string, c *AIClient, apiBaseURL, protocol, model string, maxTokens int,temperature float64, timeout int) (ret string, stop bool, err error) {var reqMsgs []openai.ChatCompletionMessage@@ -216,9 +216,9 @@ func (t *extraBodyTransport) Do(req *http.Request) (*http.Response, error) {return t.base.Do(req)}-// NewOpenAIClientWithModel 创建 OpenAI client,并按模型与端点启用兼容适配。+// NewAIClientWithModel 创建生成客户端,并按模型与端点启用协议适配。// 模型请求统一启用思考字段适配,命中清单的模型会注入额外参数,官方 Gemini 端点会保留工具调用签名。-func NewOpenAIClientWithModel(apiKey, apiBaseURL, model string, headers ...map[string]string) *openai.Client {+func NewAIClientWithModel(apiKey, apiBaseURL, model string, headers ...map[string]string) *AIClient {extra := ExtraBodyForModel(model)geminiThoughtSignatures := isGoogleGeminiOpenAICompatibleEndpoint(apiBaseURL, model)config := openai.DefaultConfig(apiKey)@@ -232,7 +232,8 @@ func NewOpenAIClientWithModel(apiKey, apiBaseURL, model string, headers ...map[s}transport = &reasoningResponseTransport{base: transport}config.HTTPClient = transport- return openai.NewClientWithConfig(config)+ return &AIClient{Client: openai.NewClientWithConfig(config), baseURL: apiBaseURL,+ anthropicHTTP: newAnthropicHTTPClient(apiKey, apiBaseURL, headers...)}}// TestModel 测试模型可用性。先调用 ListModels(GET /v1/models)拉取可用模型清单,@@ -243,19 +244,33 @@ func TestModel(apiKey, apiBaseURL, protocol, model string, timeout int, headersif 1 > timeout {timeout = 30}- client := NewOpenAIClientWithModel(apiKey, apiBaseURL, model, headers...)+ client := NewAIClientWithModel(apiKey, apiBaseURL, model, headers...)ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)defer cancel()ctx = ContextWithOpenAIResponsesBaseURL(ctx, apiBaseURL)// 优先校验模型是否在可用清单中- list, listErr := client.ListModels(ctx)+ var availableIDs []string+ var listErr error+ if IsAnthropicMessagesProtocol(protocol) {+ var models []AvailableModel+ models, listErr = listAnthropicModels(ctx, client)+ for _, m := range models {+ availableIDs = append(availableIDs, m.ID)+ }+ } else {+ list, err := client.ListModels(ctx)+ listErr = err+ for _, m := range list.Models {+ availableIDs = append(availableIDs, m.ID)+ }+ }if nil == listErr {model = strings.TrimSpace(model)target := strings.ToLower(model)- for _, m := range list.Models {- available = append(available, m.ID)- if strings.ToLower(m.ID) == target {+ for _, id := range availableIDs {+ available = append(available, id)+ if strings.ToLower(id) == target {matched = true}}@@ -274,7 +289,7 @@ func TestModel(apiKey, apiBaseURL, protocol, model string, timeout int, headersMaxCompletionTokens: 1,Temperature: 1,}- if IsOpenAIResponsesProtocol(protocol) {+ if IsOpenAIResponsesProtocol(protocol) || IsAnthropicMessagesProtocol(protocol) {request.Stream = truevar stream *OpenAICompletionStreamstream, err = CreateOpenAICompletionStream(ctx, client, protocol, request, nil)@@ -863,7 +878,7 @@ func NewOpenAIImageAdapter(apiKey, apiBaseURL, model string, timeout int, headerif timeout < 1 {timeout = 30}- client := NewOpenAIClientWithModel(apiKey, apiBaseURL, model, headers...)+ client := NewAIClientWithModel(apiKey, apiBaseURL, model, headers...).Clientif isMiniMaxImageEndpoint(apiBaseURL) {config := openai.DefaultConfig(apiKey)config.BaseURL = apiBaseURLdiff --git a/kernel/util/openai_completion.go b/kernel/util/openai_completion.goindex b747bbd459..d7c6f694f7 100644--- a/kernel/util/openai_completion.go+++ b/kernel/util/openai_completion.go@@ -88,9 +88,10 @@ func IsOpenAIResponsesProtocol(protocol string) bool {return strings.EqualFold(strings.TrimSpace(protocol), OpenAIProtocolResponses)}-// OpenAICompletionStream 将 Chat Completions 与 Responses 的流式输出统一为 Chat 增量,+// OpenAICompletionStream 将各生成协议的流式输出统一为 Chat 增量,// 让现有上层渲染、重试和工具执行逻辑保持一致。type OpenAICompletionStream struct {+ anthropic *anthropicStreamchat *openai.ChatCompletionStreamresponses *openai.ResponseStreampending []openai.ChatCompletionStreamResponse@@ -100,8 +101,11 @@ type OpenAICompletionStream struct {responsesDone bool}-func CreateOpenAICompletionStream(ctx context.Context, client *openai.Client, protocol string,+func CreateOpenAICompletionStream(ctx context.Context, client *AIClient, protocol string,request openai.ChatCompletionRequest, responseInput []any) (*OpenAICompletionStream, error) {+ if IsAnthropicMessagesProtocol(protocol) {+ return createAnthropicStream(ctx, client, request)+ }if !IsOpenAIResponsesProtocol(protocol) {stream, err := client.CreateChatCompletionStream(ctx, request)if err != nil {@@ -120,8 +124,11 @@ func CreateOpenAICompletionStream(ctx context.Context, client *openai.Client, pr}, nil}-func CreateOpenAICompletion(ctx context.Context, client *openai.Client, protocol string,+func CreateOpenAICompletion(ctx context.Context, client *AIClient, protocol string,request openai.ChatCompletionRequest, responseInput []any) (openai.ChatCompletionResponse, error) {+ if IsAnthropicMessagesProtocol(protocol) {+ return createAnthropicCompletion(ctx, client, request)+ }if !IsOpenAIResponsesProtocol(protocol) {return client.CreateChatCompletion(ctx, request)}@@ -135,7 +142,7 @@ func CreateOpenAICompletion(ctx context.Context, client *openai.Client, protocolreturn responseToChatCompletion(response), nil}-func CompactOpenAIResponse(ctx context.Context, client *openai.Client, request openai.ChatCompletionRequest,+func CompactOpenAIResponse(ctx context.Context, client *AIClient, request openai.ChatCompletionRequest,responseInput []any) ([]json.RawMessage, *openai.ResponseUsage, error) {responseRequest := openai.CompactResponseRequest{Model: request.Model,@@ -439,6 +446,9 @@ func responseUsageToChat(usage *openai.ResponseUsage) openai.Usage {}func (stream *OpenAICompletionStream) Recv() (openai.ChatCompletionStreamResponse, error) {+ if stream.anthropic != nil {+ return stream.anthropic.recv()+ }if stream.chat != nil {return stream.chat.Recv()}@@ -712,6 +722,9 @@ func (stream *OpenAICompletionStream) ResponseOutput() []json.RawMessage {}func (stream *OpenAICompletionStream) Close() {+ if stream.anthropic != nil {+ stream.anthropic.body.Close()+ }if stream.chat != nil {stream.chat.Close()}@@ -719,3 +732,10 @@ func (stream *OpenAICompletionStream) Close() {stream.responses.Close()}}++func (stream *OpenAICompletionStream) NativeContent() *AIMessageContent {+ if stream.anthropic == nil {+ return nil+ }+ return CloneAIMessageContent(stream.anthropic.content)+}diff --git a/kernel/util/openai_completion_test.go b/kernel/util/openai_completion_test.goindex 5428b8ec5b..b08b044a92 100644--- a/kernel/util/openai_completion_test.go+++ b/kernel/util/openai_completion_test.go@@ -57,7 +57,7 @@ func TestOpenAIResponsesStreamPreservesOutput(t *testing.T) {config := openai.DefaultConfig("test")config.BaseURL = server.URL + "/v1"- client := openai.NewClientWithConfig(config)+ client := &AIClient{Client: openai.NewClientWithConfig(config)}request := openai.ChatCompletionRequest{Model: "gpt-test",Messages: []openai.ChatCompletionMessage{{Role: openai.ChatMessageRoleUser, Content: "hello"}},@@ -190,7 +190,7 @@ func TestOpenAIResponsesStreamRequiresTerminalEvent(t *testing.T) {config := openai.DefaultConfig("test")config.BaseURL = server.URL + "/v1"- stream, err := CreateOpenAICompletionStream(context.Background(), openai.NewClientWithConfig(config),+ stream, err := CreateOpenAICompletionStream(context.Background(), &AIClient{Client: openai.NewClientWithConfig(config)},OpenAIProtocolResponses, openai.ChatCompletionRequest{Model: "gpt-test"}, nil)if err != nil {t.Fatal(err)@@ -216,7 +216,7 @@ func TestOpenAIResponsesStreamReturnsTypedError(t *testing.T) {config := openai.DefaultConfig("test")config.BaseURL = server.URL + "/v1"- stream, err := CreateOpenAICompletionStream(context.Background(), openai.NewClientWithConfig(config),+ stream, err := CreateOpenAICompletionStream(context.Background(), &AIClient{Client: openai.NewClientWithConfig(config)},OpenAIProtocolResponses, openai.ChatCompletionRequest{Model: "gpt-test"}, nil)if err != nil {t.Fatal(err)@@ -250,7 +250,7 @@ func TestOpenAIResponsesStreamRejectsIncompleteFunctionCall(t *testing.T) {config := openai.DefaultConfig("test")config.BaseURL = server.URL + "/v1"- stream, err := CreateOpenAICompletionStream(context.Background(), openai.NewClientWithConfig(config),+ stream, err := CreateOpenAICompletionStream(context.Background(), &AIClient{Client: openai.NewClientWithConfig(config)},OpenAIProtocolResponses, openai.ChatCompletionRequest{Model: "gpt-test"}, nil)if err != nil {t.Fatal(err)@@ -304,7 +304,7 @@ func TestOpenAIResponsesNonStreamFailure(t *testing.T) {config := openai.DefaultConfig("test")config.BaseURL = server.URL + "/v1"- _, err := CreateOpenAICompletion(context.Background(), openai.NewClientWithConfig(config),+ _, err := CreateOpenAICompletion(context.Background(), &AIClient{Client: openai.NewClientWithConfig(config)},OpenAIProtocolResponses, openai.ChatCompletionRequest{Model: "gpt-test"}, nil)if err == nil || !strings.Contains(err.Error(), "generation failed") {t.Fatalf("unexpected failed response error: %v", err)diff --git a/kernel/util/openai_gemini.go b/kernel/util/openai_gemini.goindex 9a1c69ec67..e847ff42ec 100644--- a/kernel/util/openai_gemini.go+++ b/kernel/util/openai_gemini.go@@ -130,7 +130,7 @@ func isGoogleGeminiOpenAICompatibleEndpoint(apiBaseURL, model string) bool {}// WrapGeminiThoughtSignatureTransport 为 Google OpenAI 兼容端点补充工具调用签名往返支持。-// 该函数导出仅用于 Agent 集成测试构造本地上游,生产代码通过 NewOpenAIClientWithModel 使用。+// 该函数导出仅用于 Agent 集成测试构造本地上游,生产代码通过 NewAIClientWithModel 使用。func WrapGeminiThoughtSignatureTransport(base openai.HTTPDoer) openai.HTTPDoer {return &geminiThoughtSignatureTransport{base: base}}diff --git a/kernel/util/openai_headers_test.go b/kernel/util/openai_headers_test.goindex c8fcba7c00..d23aa98f1a 100644--- a/kernel/util/openai_headers_test.go+++ b/kernel/util/openai_headers_test.go@@ -67,7 +67,7 @@ func TestAIProviderHeadersStreamingAndImages(t *testing.T) {}))defer server.Close()headers := map[string]string{"X-Route": "original"}- client := NewOpenAIClientWithModel("key", server.URL+"/v1", "MiniMax-M3", headers)+ client := NewAIClientWithModel("key", server.URL+"/v1", "MiniMax-M3", headers)headers["X-Route"] = "changed"stream, err := CreateOpenAICompletionStream(context.Background(), client, protocol, openai.ChatCompletionRequest{Model: "MiniMax-M3", Messages: []openai.ChatCompletionMessage{{Role: "user", Content: "hi"}},