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 ChatGPT account sign-in for the agent https://github.com/siyuan-note/siyuan/issues/20109
Danielf1528e0e4d1a
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex fd051ed7fc..57156c7b5b 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "إضافة حساب",+ "chatGPTCallbackTip": "عُد إلى SiYuan لعرض نتيجة تسجيل الدخول",+ "chatGPTAccount": "حساب ChatGPT",+ "chatGPTConnect": "المتابعة باستخدام ChatGPT",+ "chatGPTPlanUsageTip": "استخدم النماذج والحصة المتاحة لحسابك في ChatGPT؛ لا يلزم مفتاح API",+ "chatGPTSignInPendingTip": "أكمل تسجيل الدخول في المتصفح، ثم عُد إلى SiYuan",+ "chatGPTRemoteTip": "للنواة البعيدة، سجّل الدخول إلى SiYuan على جهازك، ثم صدّر الحساب واستورده هنا",+ "chatGPTTransferTip": "استخدم كلمة مرور من 12 حرفًا على الأقل؛ ينقل التصدير هذه الجلسة ويسجّل خروجها على هذا الجهاز",+ "chatGPTUsage": "عرض استخدام ChatGPT",+ "chatGPTRevokeFailed": "تم تسجيل الخروج محليًا، لكن لم يتم تأكيد الإلغاء البعيد. افصل SiYuan في إعدادات ChatGPT.","mobileLayoutSaveError": "تعذّر حفظ تخطيط الجوال. يُرجى المحاولة مرة أخرى.","ocrThresholdSettings": "عتبات التعرف","ocrReasoningEffortTip": "يتبع الإعداد الافتراضي سلوك النموذج؛ يعطل خيار بدون التفكير أو يقلله حسب دعم المزود والنموذج",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex b035a8c4f2..4a3fc7b792 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "Konto hinzufügen",+ "chatGPTCallbackTip": "Kehren Sie zu SiYuan zurück, um das Anmeldeergebnis zu sehen",+ "chatGPTAccount": "ChatGPT-Konto",+ "chatGPTConnect": "Mit ChatGPT fortfahren",+ "chatGPTPlanUsageTip": "Verwenden Sie die Modelle und das Kontingent Ihres ChatGPT-Kontos; ein API-Schlüssel ist nicht erforderlich",+ "chatGPTSignInPendingTip": "Schließen Sie die Anmeldung im Browser ab und kehren Sie zu SiYuan zurück",+ "chatGPTRemoteTip": "Melden Sie sich bei einem entfernten Kernel zunächst in SiYuan auf Ihrem Gerät an, exportieren Sie das Konto und importieren Sie es hier",+ "chatGPTTransferTip": "Verwenden Sie ein Passwort mit mindestens 12 Zeichen; der Export überträgt die Sitzung und meldet sie auf diesem Gerät ab",+ "chatGPTUsage": "ChatGPT-Nutzung anzeigen",+ "chatGPTRevokeFailed": "Lokal abgemeldet, aber der entfernte Widerruf wurde nicht bestätigt. Trennen Sie SiYuan in den ChatGPT-Einstellungen.","mobileLayoutSaveError": "Das mobile Layout konnte nicht gespeichert werden. Bitte erneut versuchen.","ocrThresholdSettings": "Erkennungsschwellen","ocrReasoningEffortTip": "Standard folgt dem Modellverhalten; Keine deaktiviert oder minimiert das Denken, abhängig von Anbieter und Modell",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 63fddeeebf..d44c9f7c40 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "Add account",+ "chatGPTCallbackTip": "Return to SiYuan to view the sign-in result",+ "chatGPTAccount": "ChatGPT account",+ "chatGPTConnect": "Continue with ChatGPT",+ "chatGPTPlanUsageTip": "Use the models and allowance available to your ChatGPT account; no API key is required",+ "chatGPTSignInPendingTip": "Complete sign-in in your browser, then return to SiYuan",+ "chatGPTRemoteTip": "For a remote kernel, sign in with SiYuan on your device, export the account, and import it here",+ "chatGPTTransferTip": "Use a password of at least 12 characters; exporting transfers this session and signs it out on this device",+ "chatGPTUsage": "View ChatGPT usage",+ "chatGPTRevokeFailed": "Signed out locally, but remote revocation was not confirmed. Disconnect SiYuan in ChatGPT settings.","mobileLayoutSaveError": "Could not save the mobile layout. Please try again.","ocrThresholdSettings": "Recognition thresholds","ocrReasoningEffortTip": "Default follows model behavior; None disables or minimizes thinking, depending on provider and model support",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 7a239cf187..e8a946bb65 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "Añadir cuenta",+ "chatGPTCallbackTip": "Vuelva a SiYuan para ver el resultado del inicio de sesión",+ "chatGPTAccount": "Cuenta de ChatGPT",+ "chatGPTConnect": "Continuar con ChatGPT",+ "chatGPTPlanUsageTip": "Use los modelos y la cuota disponibles para su cuenta de ChatGPT; no se necesita una clave API",+ "chatGPTSignInPendingTip": "Complete el inicio de sesión en el navegador y vuelva a SiYuan",+ "chatGPTRemoteTip": "Para un núcleo remoto, inicie sesión en SiYuan en su dispositivo, exporte la cuenta e impórtela aquí",+ "chatGPTTransferTip": "Use una contraseña de al menos 12 caracteres; la exportación transfiere esta sesión y la cierra en este dispositivo",+ "chatGPTUsage": "Ver el uso de ChatGPT",+ "chatGPTRevokeFailed": "Se cerró la sesión localmente, pero no se confirmó la revocación remota. Desconecte SiYuan en la configuración de ChatGPT.","mobileLayoutSaveError": "No se pudo guardar el diseño móvil. Inténtalo de nuevo.","ocrThresholdSettings": "Umbrales de reconocimiento","ocrReasoningEffortTip": "Predeterminado sigue el comportamiento del modelo; Ninguno desactiva o minimiza el razonamiento según el proveedor y el modelo",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex f3985ac4dc..d5dcc4f9c4 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "Ajouter un compte",+ "chatGPTCallbackTip": "Revenez à SiYuan pour voir le résultat de la connexion",+ "chatGPTAccount": "Compte ChatGPT",+ "chatGPTConnect": "Continuer avec ChatGPT",+ "chatGPTPlanUsageTip": "Utilisez les modèles et le quota disponibles pour votre compte ChatGPT ; aucune clé API n’est requise",+ "chatGPTSignInPendingTip": "Terminez la connexion dans votre navigateur, puis revenez à SiYuan",+ "chatGPTRemoteTip": "Pour un noyau distant, connectez-vous à SiYuan sur votre appareil, exportez le compte et importez-le ici",+ "chatGPTTransferTip": "Utilisez un mot de passe d’au moins 12 caractères ; l’export transfère cette session et la déconnecte sur cet appareil",+ "chatGPTUsage": "Voir l’utilisation de ChatGPT",+ "chatGPTRevokeFailed": "Déconnexion locale effectuée, mais la révocation distante n’a pas été confirmée. Déconnectez SiYuan dans les paramètres de ChatGPT.","mobileLayoutSaveError": "Impossible d'enregistrer la disposition mobile. Veuillez réessayer.","ocrThresholdSettings": "Seuils de reconnaissance","ocrReasoningEffortTip": "Par défaut suit le comportement du modèle ; Aucun désactive ou minimise le raisonnement selon le fournisseur et le modèle",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 2e87d5f18b..6d54d1a51f 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "הוסף חשבון",+ "chatGPTCallbackTip": "חזור ל-SiYuan כדי לראות את תוצאת הכניסה",+ "chatGPTAccount": "חשבון ChatGPT",+ "chatGPTConnect": "המשך עם ChatGPT",+ "chatGPTPlanUsageTip": "השתמש במודלים ובמכסה הזמינים לחשבון ChatGPT שלך; אין צורך במפתח API",+ "chatGPTSignInPendingTip": "השלם את הכניסה בדפדפן ולאחר מכן חזור ל-SiYuan",+ "chatGPTRemoteTip": "לליבה מרוחקת, היכנס ל-SiYuan במכשיר שלך, ייצא את החשבון וייבא אותו כאן",+ "chatGPTTransferTip": "השתמש בסיסמה בת 12 תווים לפחות; הייצוא מעביר את ההפעלה ומנתק אותה במכשיר זה",+ "chatGPTUsage": "הצג שימוש ב-ChatGPT",+ "chatGPTRevokeFailed": "היציאה המקומית הושלמה, אך הביטול המרוחק לא אושר. נתק את SiYuan בהגדרות ChatGPT.","mobileLayoutSaveError": "לא ניתן לשמור את העיצוב לנייד. יש לנסות שוב.","ocrThresholdSettings": "ספי זיהוי","ocrReasoningEffortTip": "ברירת המחדל פועלת לפי התנהגות המודל; ללא מכבה או מצמצם את החשיבה בהתאם לתמיכת הספק והמודל",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex ae05438b7e..a0eaa8bbde 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "खाता जोड़ें",+ "chatGPTCallbackTip": "साइन इन का परिणाम देखने के लिए SiYuan पर लौटें",+ "chatGPTAccount": "ChatGPT खाता",+ "chatGPTConnect": "ChatGPT के साथ जारी रखें",+ "chatGPTPlanUsageTip": "अपने ChatGPT खाते के उपलब्ध मॉडल और उपयोग सीमा का उपयोग करें; API कुंजी आवश्यक नहीं है",+ "chatGPTSignInPendingTip": "ब्राउज़र में साइन इन पूरा करें, फिर SiYuan पर लौटें",+ "chatGPTRemoteTip": "दूरस्थ कर्नेल के लिए अपने डिवाइस पर SiYuan में साइन इन करें, खाता निर्यात करें और यहाँ आयात करें",+ "chatGPTTransferTip": "कम से कम 12 वर्णों वाला पासवर्ड उपयोग करें; निर्यात इस सत्र को स्थानांतरित करता है और इस डिवाइस से साइन आउट करता है",+ "chatGPTUsage": "ChatGPT उपयोग देखें",+ "chatGPTRevokeFailed": "स्थानीय रूप से साइन आउट हो गया, लेकिन दूरस्थ निरस्तीकरण की पुष्टि नहीं हुई। ChatGPT सेटिंग में SiYuan को डिस्कनेक्ट करें।","mobileLayoutSaveError": "मोबाइल लेआउट सहेजा नहीं जा सका। कृपया फिर से प्रयास करें।","ocrThresholdSettings": "पहचान की सीमाएँ","ocrReasoningEffortTip": "डिफ़ॉल्ट मॉडल के व्यवहार का पालन करता है; कोई नहीं विकल्प प्रदाता और मॉडल के समर्थन के अनुसार सोच को बंद या न्यूनतम करता है",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex c37adec252..b8bc56a025 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "Tambahkan akun",+ "chatGPTCallbackTip": "Kembali ke SiYuan untuk melihat hasil login",+ "chatGPTAccount": "Akun ChatGPT",+ "chatGPTConnect": "Lanjutkan dengan ChatGPT",+ "chatGPTPlanUsageTip": "Gunakan model dan kuota yang tersedia untuk akun ChatGPT Anda; kunci API tidak diperlukan",+ "chatGPTSignInPendingTip": "Selesaikan login di peramban, lalu kembali ke SiYuan",+ "chatGPTRemoteTip": "Untuk kernel jarak jauh, masuk ke SiYuan di perangkat Anda, ekspor akun, lalu impor di sini",+ "chatGPTTransferTip": "Gunakan kata sandi minimal 12 karakter; ekspor memindahkan sesi ini dan mengeluarkannya dari perangkat ini",+ "chatGPTUsage": "Lihat penggunaan ChatGPT",+ "chatGPTRevokeFailed": "Sesi lokal telah keluar, tetapi pencabutan jarak jauh belum dikonfirmasi. Putuskan SiYuan di pengaturan ChatGPT.","mobileLayoutSaveError": "Tidak dapat menyimpan tata letak seluler. Silakan coba lagi.","ocrThresholdSettings": "Ambang pengenalan","ocrReasoningEffortTip": "Default mengikuti perilaku model; Tidak ada menonaktifkan atau meminimalkan pemikiran sesuai dukungan penyedia dan model",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 37747032ed..e7a12a8702 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "Aggiungi account",+ "chatGPTCallbackTip": "Torna a SiYuan per vedere il risultato dell’accesso",+ "chatGPTAccount": "Account ChatGPT",+ "chatGPTConnect": "Continua con ChatGPT",+ "chatGPTPlanUsageTip": "Usa i modelli e la quota disponibili per il tuo account ChatGPT; non è necessaria una chiave API",+ "chatGPTSignInPendingTip": "Completa l’accesso nel browser, quindi torna a SiYuan",+ "chatGPTRemoteTip": "Per un kernel remoto, accedi a SiYuan sul tuo dispositivo, esporta l’account e importalo qui",+ "chatGPTTransferTip": "Usa una password di almeno 12 caratteri; l’esportazione trasferisce la sessione e la disconnette su questo dispositivo",+ "chatGPTUsage": "Visualizza l’utilizzo di ChatGPT",+ "chatGPTRevokeFailed": "Disconnessione locale completata, ma la revoca remota non è stata confermata. Disconnetti SiYuan nelle impostazioni di ChatGPT.","mobileLayoutSaveError": "Impossibile salvare il layout mobile. Riprova.","ocrThresholdSettings": "Soglie di riconoscimento","ocrReasoningEffortTip": "Predefinito segue il comportamento del modello; Nessuno disattiva o riduce al minimo il ragionamento secondo il provider e il modello",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 7b6553060e..793b6e4a12 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "アカウントを追加",+ "chatGPTCallbackTip": "思源に戻ってログイン結果を確認してください",+ "chatGPTAccount": "ChatGPT アカウント",+ "chatGPTConnect": "ChatGPT で続行",+ "chatGPTPlanUsageTip": "ChatGPT アカウントで利用できるモデルとプランの利用枠を使用します。API キーは不要です",+ "chatGPTSignInPendingTip": "ブラウザーでログインを完了してから、思源に戻ってください",+ "chatGPTRemoteTip": "リモートカーネルに接続する場合は、端末の思源でログインしてアカウントをエクスポートし、ここでインポートしてください",+ "chatGPTTransferTip": "12 文字以上のパスワードを使用してください。エクスポートするとセッションが移行され、この端末ではログアウトします",+ "chatGPTUsage": "ChatGPT の使用量を確認",+ "chatGPTRevokeFailed": "端末ではログアウトしましたが、リモートでの取り消しは確認できませんでした。ChatGPT の設定で思源の接続を解除してください。","mobileLayoutSaveError": "モバイル端末のレイアウトを保存できませんでした。もう一度お試しください。","ocrThresholdSettings": "認識のしきい値","ocrReasoningEffortTip": "デフォルトはモデルの動作に従います。「なし」は思考を無効化または最小化しますが、対応状況はプロバイダーとモデルによって異なります",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 533c10fa8c..b26fcfc122 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "계정 추가",+ "chatGPTCallbackTip": "SiYuan으로 돌아와 로그인 결과를 확인하세요",+ "chatGPTAccount": "ChatGPT 계정",+ "chatGPTConnect": "ChatGPT로 계속",+ "chatGPTPlanUsageTip": "ChatGPT 계정에서 이용할 수 있는 모델과 요금제 한도를 사용합니다. API 키는 필요하지 않습니다",+ "chatGPTSignInPendingTip": "브라우저에서 로그인을 완료한 후 SiYuan으로 돌아오세요",+ "chatGPTRemoteTip": "원격 커널은 기기의 SiYuan에서 로그인하고 계정을 내보낸 다음 여기서 가져오세요",+ "chatGPTTransferTip": "12자 이상의 비밀번호를 사용하세요. 내보내면 이 세션이 이전되고 이 기기에서는 로그아웃됩니다",+ "chatGPTUsage": "ChatGPT 사용량 보기",+ "chatGPTRevokeFailed": "기기에서는 로그아웃했지만 원격 취소는 확인되지 않았습니다. ChatGPT 설정에서 SiYuan 연결을 해제하세요.","mobileLayoutSaveError": "모바일 레이아웃을 저장하지 못했습니다. 다시 시도해 주세요.","ocrThresholdSettings": "인식 임계값","ocrReasoningEffortTip": "기본값은 모델 동작을 따릅니다. 없음은 사고를 끄거나 최소화하며, 지원 여부는 공급자와 모델에 따라 다릅니다",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 0815771604..4122e8e8d7 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "Account toevoegen",+ "chatGPTCallbackTip": "Keer terug naar SiYuan om het resultaat van de aanmelding te bekijken",+ "chatGPTAccount": "ChatGPT-account",+ "chatGPTConnect": "Doorgaan met ChatGPT",+ "chatGPTPlanUsageTip": "Gebruik de modellen en het tegoed van uw ChatGPT-account; een API-sleutel is niet nodig",+ "chatGPTSignInPendingTip": "Voltooi de aanmelding in uw browser en keer terug naar SiYuan",+ "chatGPTRemoteTip": "Meld u voor een externe kernel aan bij SiYuan op uw apparaat, exporteer het account en importeer het hier",+ "chatGPTTransferTip": "Gebruik een wachtwoord van minstens 12 tekens; exporteren draagt deze sessie over en meldt deze op dit apparaat af",+ "chatGPTUsage": "ChatGPT-gebruik bekijken",+ "chatGPTRevokeFailed": "Lokaal afgemeld, maar intrekking op afstand is niet bevestigd. Verbreek de verbinding met SiYuan in de ChatGPT-instellingen.","mobileLayoutSaveError": "De mobiele indeling kon niet worden opgeslagen. Probeer het opnieuw.","ocrThresholdSettings": "Herkenningsdrempels","ocrReasoningEffortTip": "Standaard volgt het modelgedrag; Geen schakelt denken uit of beperkt het tot een minimum, afhankelijk van de aanbieder en het model",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 2b4dbe3562..aa742458ce 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "Dodaj konto",+ "chatGPTCallbackTip": "Wróć do SiYuan, aby zobaczyć wynik logowania",+ "chatGPTAccount": "Konto ChatGPT",+ "chatGPTConnect": "Kontynuuj z ChatGPT",+ "chatGPTPlanUsageTip": "Korzystaj z modeli i limitu dostępnych dla konta ChatGPT; klucz API nie jest wymagany",+ "chatGPTSignInPendingTip": "Dokończ logowanie w przeglądarce, a następnie wróć do SiYuan",+ "chatGPTRemoteTip": "Dla zdalnego jądra zaloguj się do SiYuan na swoim urządzeniu, wyeksportuj konto i zaimportuj je tutaj",+ "chatGPTTransferTip": "Użyj hasła z co najmniej 12 znakami; eksport przenosi sesję i wylogowuje ją na tym urządzeniu",+ "chatGPTUsage": "Wyświetl użycie ChatGPT",+ "chatGPTRevokeFailed": "Wylogowano lokalnie, ale zdalne unieważnienie nie zostało potwierdzone. Odłącz SiYuan w ustawieniach ChatGPT.","mobileLayoutSaveError": "Nie udało się zapisać układu mobilnego. Spróbuj ponownie.","ocrThresholdSettings": "Progi rozpoznawania","ocrReasoningEffortTip": "Domyślne zachowuje działanie modelu; Brak wyłącza lub minimalizuje rozumowanie zależnie od obsługi przez dostawcę i model",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 3ec2abadd6..ab5e920d86 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "Adicionar conta",+ "chatGPTCallbackTip": "Volte ao SiYuan para ver o resultado do login",+ "chatGPTAccount": "Conta do ChatGPT",+ "chatGPTConnect": "Continuar com ChatGPT",+ "chatGPTPlanUsageTip": "Use os modelos e a cota disponíveis na sua conta do ChatGPT; não é necessária uma chave de API",+ "chatGPTSignInPendingTip": "Conclua o login no navegador e volte ao SiYuan",+ "chatGPTRemoteTip": "Para um kernel remoto, entre no SiYuan no seu dispositivo, exporte a conta e importe-a aqui",+ "chatGPTTransferTip": "Use uma senha com pelo menos 12 caracteres; a exportação transfere esta sessão e a encerra neste dispositivo",+ "chatGPTUsage": "Ver uso do ChatGPT",+ "chatGPTRevokeFailed": "A sessão local foi encerrada, mas a revogação remota não foi confirmada. Desconecte o SiYuan nas configurações do ChatGPT.","mobileLayoutSaveError": "Não foi possível salvar o layout móvel. Tente novamente.","ocrThresholdSettings": "Limiares de reconhecimento","ocrReasoningEffortTip": "Padrão segue o comportamento do modelo; Nenhum desativa ou minimiza o raciocínio conforme o suporte do provedor e do modelo",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 8e9a482f67..34be9afcd2 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "Добавить аккаунт",+ "chatGPTCallbackTip": "Вернитесь в SiYuan, чтобы увидеть результат входа",+ "chatGPTAccount": "Аккаунт ChatGPT",+ "chatGPTConnect": "Продолжить с ChatGPT",+ "chatGPTPlanUsageTip": "Используйте модели и лимит, доступные вашему аккаунту ChatGPT; ключ API не требуется",+ "chatGPTSignInPendingTip": "Завершите вход в браузере, затем вернитесь в SiYuan",+ "chatGPTRemoteTip": "Для удалённого ядра войдите в SiYuan на своём устройстве, экспортируйте аккаунт и импортируйте его здесь",+ "chatGPTTransferTip": "Используйте пароль длиной не менее 12 символов; экспорт переносит сеанс и завершает его на этом устройстве",+ "chatGPTUsage": "Посмотреть использование ChatGPT",+ "chatGPTRevokeFailed": "Локальный выход выполнен, но удалённый отзыв не подтверждён. Отключите SiYuan в настройках ChatGPT.","mobileLayoutSaveError": "Не удалось сохранить мобильный макет. Повторите попытку.","ocrThresholdSettings": "Пороги распознавания","ocrReasoningEffortTip": "По умолчанию используется поведение модели; Нет отключает или минимизирует рассуждения в зависимости от провайдера и модели",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 558dfe794c..44096282e5 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "Pridať účet",+ "chatGPTCallbackTip": "Vráťte sa do SiYuan a zobrazte výsledok prihlásenia",+ "chatGPTAccount": "Účet ChatGPT",+ "chatGPTConnect": "Pokračovať cez ChatGPT",+ "chatGPTPlanUsageTip": "Použite modely a limit dostupné pre váš účet ChatGPT; kľúč API nie je potrebný",+ "chatGPTSignInPendingTip": "Dokončite prihlásenie v prehliadači a potom sa vráťte do SiYuan",+ "chatGPTRemoteTip": "Pri vzdialenom jadre sa prihláste do SiYuan na svojom zariadení, exportujte účet a importujte ho tu",+ "chatGPTTransferTip": "Použite heslo s aspoň 12 znakmi; export prenesie túto reláciu a odhlási ju na tomto zariadení",+ "chatGPTUsage": "Zobraziť využitie ChatGPT",+ "chatGPTRevokeFailed": "Lokálne odhlásenie bolo dokončené, ale vzdialené zrušenie nebolo potvrdené. Odpojte SiYuan v nastaveniach ChatGPT.","mobileLayoutSaveError": "Mobilné rozloženie sa nepodarilo uložiť. Skúste to znova.","ocrThresholdSettings": "Prahy rozpoznávania","ocrReasoningEffortTip": "Predvolené používa správanie modelu; Žiadne vypne alebo minimalizuje uvažovanie podľa podpory poskytovateľa a modelu",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex f1a6631813..7511a582f1 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "Додај налог",+ "chatGPTCallbackTip": "Вратите се у SiYuan да видите резултат пријављивања",+ "chatGPTAccount": "ChatGPT налог",+ "chatGPTConnect": "Настави са ChatGPT",+ "chatGPTPlanUsageTip": "Користите моделе и квоту доступне вашем ChatGPT налогу; API кључ није потребан",+ "chatGPTSignInPendingTip": "Завршите пријављивање у прегледачу, па се вратите у SiYuan",+ "chatGPTRemoteTip": "За удаљено језгро пријавите се у SiYuan на свом уређају, извезите налог и увезите га овде",+ "chatGPTTransferTip": "Користите лозинку од најмање 12 знакова; извоз преноси ову сесију и одјављује је на овом уређају",+ "chatGPTUsage": "Прикажи употребу ChatGPT",+ "chatGPTRevokeFailed": "Локална одјава је завршена, али удаљени опозив није потврђен. Искључите SiYuan у подешавањима ChatGPT.","mobileLayoutSaveError": "Nije moguće sačuvati mobilni raspored. Pokušajte ponovo.","ocrThresholdSettings": "Прагови препознавања","ocrReasoningEffortTip": "Подразумевано прати понашање модела; Без искључује или своди размишљање на минимум у зависности од подршке добављача и модела",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 6d1ac695d9..b429928c64 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "เพิ่มบัญชี",+ "chatGPTCallbackTip": "กลับไปที่ SiYuan เพื่อดูผลการเข้าสู่ระบบ",+ "chatGPTAccount": "บัญชี ChatGPT",+ "chatGPTConnect": "ดำเนินการต่อด้วย ChatGPT",+ "chatGPTPlanUsageTip": "ใช้โมเดลและโควตาที่บัญชี ChatGPT ของคุณมี ไม่ต้องใช้คีย์ API",+ "chatGPTSignInPendingTip": "เข้าสู่ระบบในเบราว์เซอร์ให้เสร็จ แล้วกลับมาที่ SiYuan",+ "chatGPTRemoteTip": "สำหรับเคอร์เนลระยะไกล ให้เข้าสู่ระบบ SiYuan บนอุปกรณ์ของคุณ ส่งออกบัญชี แล้วนำเข้าที่นี่",+ "chatGPTTransferTip": "ใช้รหัสผ่านอย่างน้อย 12 อักขระ การส่งออกจะย้ายเซสชันนี้และออกจากระบบบนอุปกรณ์นี้",+ "chatGPTUsage": "ดูการใช้งาน ChatGPT",+ "chatGPTRevokeFailed": "ออกจากระบบในอุปกรณ์แล้ว แต่ยังยืนยันการเพิกถอนระยะไกลไม่ได้ โปรดยกเลิกการเชื่อมต่อ SiYuan ในการตั้งค่า ChatGPT","mobileLayoutSaveError": "ไม่สามารถบันทึกเค้าโครงบนมือถือได้ โปรดลองอีกครั้ง","ocrThresholdSettings": "เกณฑ์การรู้จำ","ocrReasoningEffortTip": "ค่าเริ่มต้นใช้พฤติกรรมของโมเดล ส่วนไม่มีจะปิดหรือลดการคิดให้เหลือน้อยที่สุดตามการรองรับของผู้ให้บริการและโมเดล",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 35081be83a..aff1e31ed4 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "Hesap ekle",+ "chatGPTCallbackTip": "Oturum açma sonucunu görmek için SiYuan’a dönün",+ "chatGPTAccount": "ChatGPT hesabı",+ "chatGPTConnect": "ChatGPT ile devam et",+ "chatGPTPlanUsageTip": "ChatGPT hesabınızın kullanabildiği modelleri ve kotayı kullanın; API anahtarı gerekmez",+ "chatGPTSignInPendingTip": "Tarayıcınızda oturum açmayı tamamlayın, ardından SiYuan’a dönün",+ "chatGPTRemoteTip": "Uzak çekirdek için cihazınızdaki SiYuan’da oturum açın, hesabı dışa aktarın ve buraya içe aktarın",+ "chatGPTTransferTip": "En az 12 karakterlik bir parola kullanın; dışa aktarma bu oturumu taşır ve bu cihazda oturumu kapatır",+ "chatGPTUsage": "ChatGPT kullanımını görüntüle",+ "chatGPTRevokeFailed": "Yerel oturum kapatıldı ancak uzaktan iptal doğrulanamadı. ChatGPT ayarlarında SiYuan bağlantısını kesin.","mobileLayoutSaveError": "Mobil düzen kaydedilemedi. Lütfen tekrar deneyin.","ocrThresholdSettings": "Tanıma eşikleri","ocrReasoningEffortTip": "Varsayılan, model davranışını izler; Yok, sağlayıcı ve model desteğine göre düşünmeyi kapatır veya en aza indirir",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 22568b76fa..ffb31c75fe 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "Додати обліковий запис",+ "chatGPTCallbackTip": "Поверніться до SiYuan, щоб переглянути результат входу",+ "chatGPTAccount": "Обліковий запис ChatGPT",+ "chatGPTConnect": "Продовжити з ChatGPT",+ "chatGPTPlanUsageTip": "Використовуйте моделі й ліміт, доступні вашому обліковому запису ChatGPT; ключ API не потрібен",+ "chatGPTSignInPendingTip": "Завершіть вхід у браузері, потім поверніться до SiYuan",+ "chatGPTRemoteTip": "Для віддаленого ядра ввійдіть у SiYuan на своєму пристрої, експортуйте обліковий запис та імпортуйте його тут",+ "chatGPTTransferTip": "Використовуйте пароль щонайменше з 12 символів; експорт переносить сеанс і завершує його на цьому пристрої",+ "chatGPTUsage": "Переглянути використання ChatGPT",+ "chatGPTRevokeFailed": "Локальний вихід виконано, але віддалене відкликання не підтверджено. Від’єднайте SiYuan у налаштуваннях ChatGPT.","mobileLayoutSaveError": "Не вдалося зберегти мобільний макет. Спробуйте ще раз.","ocrThresholdSettings": "Пороги розпізнавання","ocrReasoningEffortTip": "За замовчуванням використовується поведінка моделі; Немає вимикає або мінімізує міркування залежно від підтримки провайдера та моделі",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 95d683a7ec..1060e5f50e 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "添加账户",+ "chatGPTCallbackTip": "请返回思源查看登录结果",+ "chatGPTAccount": "ChatGPT 账户",+ "chatGPTConnect": "使用 ChatGPT 继续",+ "chatGPTPlanUsageTip": "使用 ChatGPT 账户可用的模型和套餐额度,无需 API 密钥",+ "chatGPTSignInPendingTip": "请在浏览器中完成登录,然后返回思源",+ "chatGPTRemoteTip": "连接远程内核时,请先在本机思源登录并导出账户,再在此处导入",+ "chatGPTTransferTip": "请使用至少 12 个字符的密码;导出将转移此会话,并在本机退出该会话",+ "chatGPTUsage": "查看 ChatGPT 用量",+ "chatGPTRevokeFailed": "已在本机退出,但未能确认远程撤销成功。请在 ChatGPT 设置中断开思源连接。","mobileLayoutSaveError": "移动端布局保存失败,请重试。","ocrThresholdSettings": "识别阈值","ocrReasoningEffortTip": "默认沿用模型行为;无表示关闭或尽量减少思考,是否支持取决于提供商和模型",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex fc8b65a107..72b9875f24 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,14 @@{+ "chatGPTAddAccount": "新增帳戶",+ "chatGPTCallbackTip": "請返回思源檢視登入結果",+ "chatGPTAccount": "ChatGPT 帳戶",+ "chatGPTConnect": "使用 ChatGPT 繼續",+ "chatGPTPlanUsageTip": "使用 ChatGPT 帳戶可用的模型和方案額度,無需 API 金鑰",+ "chatGPTSignInPendingTip": "請在瀏覽器中完成登入,然後返回思源",+ "chatGPTRemoteTip": "連線至遠端核心時,請先在本機思源登入並匯出帳戶,再在此處匯入",+ "chatGPTTransferTip": "請使用至少 12 個字元的密碼;匯出將轉移此工作階段,並在本機登出該工作階段",+ "chatGPTUsage": "檢視 ChatGPT 用量",+ "chatGPTRevokeFailed": "已在本機登出,但未能確認遠端撤銷成功。請在 ChatGPT 設定中中斷思源連線。","mobileLayoutSaveError": "行動端佈局儲存失敗,請重試。","ocrThresholdSettings": "辨識閾值","ocrReasoningEffortTip": "預設沿用模型行為;無表示關閉或盡量減少思考,是否支援取決於提供商和模型",diff --git a/app/src/config/index.ts b/app/src/config/index.tsindex 6fd8720602..a22833aa0d 100644--- a/app/src/config/index.ts+++ b/app/src/config/index.ts@@ -17,6 +17,7 @@ import {isBazaarAvailable} from "../util/bazaarAvailability";import {getSettingTabDefs} from "./setting/tabs";import {clearAccessTabElement} from "./tabs/accessRuntime";import {clearSyncTabElement} from "./tabs/syncRuntime";+import {openChatGPTProvider} from "./tabs/ai/aiProviderUi";import type {TSettingTab} from "./setting/tabs";import type {App} from "../index";import {unmountAssetsTab} from "./assets";@@ -129,7 +130,7 @@ export const openPluginSetting = (app: App) => {/// #endif};-export const openSetting = (app: App, tab?: TSettingTab) => {+export const openSetting = (app: App, tab?: TSettingTab, aiProvider?: "chatgpt") => {if (tab === "bazaar" && !isBazaarAvailable()) {return;}@@ -138,10 +139,11 @@ export const openSetting = (app: App, tab?: TSettingTab) => {}/// #if MOBILEopenMobileSetting(app, tab);+ if (aiProvider === "chatgpt") { openChatGPTProvider(); }/// #else/// #if !BROWSERif (!isSettingsWindow() && getSettingsWindowMode() === 1) {- void openNativeSettings(app, {tab});+ void openNativeSettings(app, aiProvider ? {tab, aiProvider} : {tab});return;}/// #endif@@ -149,10 +151,13 @@ export const openSetting = (app: App, tab?: TSettingTab) => {const dialog = window.siyuan.dialogs.find(item => item.element.getAttribute("data-key") === Constants.DIALOG_SETTING);if (dialog) {switchSettingTab(dialog.element, app, tab || "editor");+ if (aiProvider === "chatgpt") { openChatGPTProvider(); }return dialog;}}- return openSettingDialog(app, tab);+ const dialog = openSettingDialog(app, tab);+ if (aiProvider === "chatgpt") { openChatGPTProvider(); }+ return dialog;/// #endif};diff --git a/app/src/config/setting/nativeWindow.ts b/app/src/config/setting/nativeWindow.tsindex 6f65ec0f42..02a7ccb476 100644--- a/app/src/config/setting/nativeWindow.ts+++ b/app/src/config/setting/nativeWindow.ts@@ -20,6 +20,7 @@ import type {TSettingTab} from "./tabs";export interface ISettingsCommand {tab?: TSettingTab;+ aiProvider?: "chatgpt";readme?: {type: TBazaarType; from: "bazaar" | "downloaded"; resource: IBazaarItem};}diff --git a/app/src/config/setting/window.ts b/app/src/config/setting/window.tsindex 52efd93aaf..f51e36f13d 100644--- a/app/src/config/setting/window.ts+++ b/app/src/config/setting/window.ts@@ -104,11 +104,15 @@ const initialize = async () => {const url = new URL(location.href);url.searchParams.set("tab", next.tab);history.replaceState(null, "", url);- if (next.tab === "assets") {+ if (next.tab === "assets" || next.aiProvider === "chatgpt") {await mounted;if (!isActive()) return;}}+ if (next.tab === "ai" && next.aiProvider === "chatgpt") {+ const {openChatGPTProvider} = await import("../tabs/ai/aiProviderUi");+ if (isActive()) { openChatGPTProvider(); }+ }if (next.readme) {const {type, from, resource} = next.readme;await withMountedBazaar(({bazaar, renderReadme}) => {diff --git a/app/src/config/setting/windowMode.test.ts b/app/src/config/setting/windowMode.test.tsindex 5ee01b2511..3044c1ee54 100644--- a/app/src/config/setting/windowMode.test.ts+++ b/app/src/config/setting/windowMode.test.ts@@ -22,7 +22,7 @@ const fixture = (browser = false, mobile = false) => {{BROWSER: browser, MOBILE: mobile}, false, true), ScriptTarget.ES2021, true);const declarations = index.statements.filter(statement => isVariableStatement(statement) &&statement.declarationList.declarations.some(item => ["openSetting", "openBazaarReadme"].includes(item.name.getText(index))));- const entry = {} as {openSetting: (app: unknown, tab?: string) => void;+ const entry = {} as {openSetting: (app: unknown, tab?: string, aiProvider?: "chatgpt") => void;openBazaarReadme: (app: unknown, type: string, name: string, from: string) => Promise<void>};let native = false;runInNewContext(transpileModule(declarations.map(item => item.getText(index)).join("\n"), {compilerOptions}).outputText, {@@ -31,6 +31,7 @@ const fixture = (browser = false, mobile = false) => {openNativeSettings: (...args: unknown[]) => calls.push(["native", ...args]),openSettingDialog: (...args: unknown[]) => calls.push(["dialog", ...args]),openMobileSetting: (...args: unknown[]) => calls.push(["mobile", ...args]),+ openChatGPTProvider: () => calls.push(["chatgpt"]),window: {siyuan: {dialogs: [{element: {getAttribute: () => "settings"}}], config: {bazaar: {trust: true}}}},Constants: {DIALOG_SETTING: "settings"}, switchSettingTab: (...args: unknown[]) => calls.push(["switch", ...args]),fetchSyncPost: async () => ({code: 0, data: {packages: [{name: "plugin"}]}}),@@ -75,3 +76,16 @@ test("browser and mobile keep their own settings UI regardless of the native preassert.equal(f.calls[0][0], expected);}});++test("ChatGPT navigation reaches the native settings command and dialog entry", () => {+ const f = fixture();+ f.entry.openSetting({}, "ai", "chatgpt");+ assert.equal(JSON.stringify(f.calls[0][2]), JSON.stringify({tab: "ai", aiProvider: "chatgpt"}));+ f.calls.length = 0;+ f.storage.mode = 0;+ f.entry.openSetting({}, "ai", "chatgpt");+ assert.deepEqual(f.calls.map(item => item[0]), ["dialog", "chatgpt"]);+ const mobile = fixture(true, true);+ mobile.entry.openSetting({}, "ai", "chatgpt");+ assert.deepEqual(mobile.calls.map(item => item[0]), ["mobile", "chatgpt"]);+});diff --git a/app/src/config/tabs/ai/aiProviderPresets.test.ts b/app/src/config/tabs/ai/aiProviderPresets.test.tsindex 06c416358b..4b2a6e33e9 100644--- a/app/src/config/tabs/ai/aiProviderPresets.test.ts+++ b/app/src/config/tabs/ai/aiProviderPresets.test.ts@@ -16,8 +16,11 @@ describe("AI provider presets", () => {assert.equal(findProviderPreset("https://api.minimaxi.com/v1"), undefined);});- it("defaults only the OpenAI preset to Responses", () => {+ it("defaults OpenAI and ChatGPT account presets to Responses", () => {assert.equal(getDefaultProviderProtocol("openai"), "openai-responses");+ assert.equal(getDefaultProviderProtocol("chatgpt"), "openai-responses");+ assert.equal(PROVIDER_PRESETS.find(item => item.id === "chatgpt")?.authType, "chatgpt");+ assert.equal(findProviderPreset("https://api.openai.com/v1")?.id, "openai");assert.equal(getDefaultProviderProtocol("deepseek"), "openai");assert.equal(getDefaultProviderProtocol("custom"), "openai");});diff --git a/app/src/config/tabs/ai/aiProviderPresets.ts b/app/src/config/tabs/ai/aiProviderPresets.tsindex 48dee4a7ac..0ae7efabe2 100644--- a/app/src/config/tabs/ai/aiProviderPresets.ts+++ b/app/src/config/tabs/ai/aiProviderPresets.ts@@ -10,10 +10,12 @@ export interface IProviderPreset {responsesSupport: AIResponsesSupport;region?: "china" | "international";icon?: string;+ authType?: "chatgpt";}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: "chatgpt", name: "ChatGPT", baseURL: "https://api.openai.com/v1", authType: "chatgpt", 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", icon: "/stage/images/ai-providers/anthropic.svg"},{id: "deepseek", name: "DeepSeek", baseURL: "https://api.deepseek.com", category: "official", responsesSupport: "supported",@@ -83,4 +85,4 @@ export const getResponsesSupport = (baseURL: string): AIResponsesSupport =>findProviderPreset(baseURL)?.responsesSupport || "experimental";export const getDefaultProviderProtocol = (presetId: string) =>- presetId === "anthropic" ? "anthropic-messages" : presetId === "openai" ? "openai-responses" : "openai";+ presetId === "anthropic" ? "anthropic-messages" : ["openai", "chatgpt"].includes(presetId) ? "openai-responses" : "openai";diff --git a/app/src/config/tabs/ai/aiProviderUi.ts b/app/src/config/tabs/ai/aiProviderUi.tsindex 49754ded8f..d5ef941149 100644--- a/app/src/config/tabs/ai/aiProviderUi.ts+++ b/app/src/config/tabs/ai/aiProviderUi.ts@@ -10,6 +10,7 @@ import {upDownHint} from "../../../util/upDownHint";import {moveModelItem} from "./aiModelOrder";import {hasProviderHeaderAuth, parseProviderHeaders} from "./aiProviderHeaders";import {getModelTestMessage} from "./aiModelTestResult";+import {genChatGPTAccountHTML, mountChatGPTAccount} from "./chatGPTAccount";import {findProviderPreset,getDefaultProviderProtocol,@@ -39,9 +40,11 @@ const escapeHTML = (value: string) => escapeHtmlTextAndAttr(value ?? "");const cloneProvider = (provider: Config.IProvider): Config.IProvider =>JSON.parse(JSON.stringify(provider)) as Config.IProvider;-const findPreset = (provider: Config.IProvider) => findProviderPreset(provider.baseURL);+const findPreset = (provider: Config.IProvider) => provider.authType === "chatgpt"+ ? PROVIDER_PRESETS.find(preset => preset.id === "chatgpt") : findProviderPreset(provider.baseURL);const requiresAPIKey = (provider: Config.IProvider) => {+ if (provider.authType === "chatgpt") { return false; }const preset = findPreset(provider);return preset?.category === "official" || preset?.category === "aggregator";};@@ -198,12 +201,13 @@ const openProviderCatalog = (root: HTMLElement) => {displayName: preset.name,baseURL: preset.baseURL,apiKey: "",+ authType: preset.authType,protocol: getDefaultProviderProtocol(preset.id),requestTimeout: 120,models: [],};const description = preset.baseURL- ? escapeHTML(preset.baseURL)+ ? escapeHTML(preset.authType === "chatgpt" ? window.siyuan.languages.chatGPTAccount : preset.baseURL): window.siyuan.languages.apiBaseURLTip;return `<div class="b3-card" data-preset-id="${preset.id}"><div class="b3-card__img">${getProviderAvatarHTML(provider, preset)}</div>@@ -267,7 +271,7 @@ const renderDraftModels = (container: HTMLElement, models: Config.IModel[], avai</div>`).join("");};-const openAvailableModelMenu = (modelInput: HTMLInputElement, models: string[]) => {+const openAvailableModelMenu = (modelInput: HTMLInputElement, models: string[], displayNames: Record<string, string> = {}) => {const menu = new Menu();menu.addItem({iconHTML: "",@@ -277,7 +281,7 @@ const openAvailableModelMenu = (modelInput: HTMLInputElement, models: string[])<div class="fn__hr"></div><div class="b3-list fn__flex-1 b3-list--background">${models.map((model) => `<div class="b3-list-item b3-list-item--narrow" data-model="${escapeHTML(model)}">- <span class="b3-list-item__text">${escapeHTML(model)}</span>+ <span class="b3-list-item__text">${escapeHTML(displayNames[model] || model)}</span>${model === modelInput.value ? '<svg class="b3-menu__checked"><use xlink:href="#iconSelect"></use></svg>' : ""}</div>`).join("")}<div class="b3-list--empty fn__none" data-type="empty">${window.siyuan.languages.emptyContent}</div>@@ -357,6 +361,20 @@ const showTestResult = (data: AIModelTestData) => {);};+export const openChatGPTProvider = () => {+ const open = () => {+ const root = document.querySelector<HTMLElement>("#aiProviderCardsBlock");+ if (!root || root.closest(".fn__none")) { return false; }+ const existing = window.siyuan.config.ai.providers.find(provider => provider.authType === "chatgpt");+ openProviderDetail(root.parentElement, existing?.id, PROVIDER_PRESETS.find(preset => preset.id === "chatgpt"));+ return true;+ };+ if (open()) { return; }+ const observer = new MutationObserver(() => { if (open()) { observer.disconnect(); } });+ observer.observe(document.body, {subtree: true, childList: true, attributes: true, attributeFilter: ["class"]});+ window.setTimeout(() => observer.disconnect(), 5000);+};+const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IProviderPreset) => {const existing = providerId? window.siyuan.config.ai.providers.find((provider) => provider.id === providerId)@@ -370,6 +388,7 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPrdisplayName: preset?.name || "",baseURL: preset?.baseURL || "",apiKey: "",+ authType: preset?.authType,protocol: getDefaultProviderProtocol(preset?.id || "custom"),requestTimeout: 120,models: [],@@ -388,6 +407,7 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPr<div class="config-group"><div class="config-title">${window.siyuan.languages.aiProviderSettings}</div><div class="config-items">+ ${draft.authType === "chatgpt" ? genChatGPTAccountHTML() : ""}<label class="fn__flex b3-label config-item">${genConfigItemMainHtml(window.siyuan.languages.customDisplayName)}<span class="fn__space"></span>@@ -455,6 +475,7 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPrbindPasswordIconaToggle(view, "aiProviderDetailApiKey");const headersInput = view.querySelector<HTMLTextAreaElement>("[data-type='providerHeaders']");const validateHeaders = () => {+ if (draft.authType === "chatgpt") { delete draft.headers; return true; }const headers = parseProviderHeaders(headersInput.value);if (headers === null) {headersInput.focus();@@ -473,6 +494,7 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPrconst fetchModelsButton = view.querySelector<HTMLButtonElement>("[data-action='fetchModels']");const confirmButton = view.querySelector<HTMLButtonElement>("[data-action='confirm']");let availableModels: string[] = [];+ let availableModelDisplayNames: Record<string, string> = {};let availableModelContextLengths: Record<string, number> = {};let hasFetchedModels = false;let fetchingModels = false;@@ -491,6 +513,10 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPr: window.siyuan.languages.experimentalFeature;};const validateAPIKey = () => {+ if (draft.authType === "chatgpt" && !draft.accountID) {+ showMessage(window.siyuan.languages.chatGPTConnect);+ return false;+ }if (!validateHeaders()) {return false;}@@ -504,7 +530,7 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPrconst getAvailableModelContextLength = (name: string) =>availableModelContextLengths[name] || availableModelContextLengths[name.toLowerCase()] || 0;const updateModelActionButtons = () => {- const disabled = fetchingModels || !draft.baseURL.trim();+ const disabled = fetchingModels || !draft.baseURL.trim() || (draft.authType === "chatgpt" && !draft.accountID);addModelButton.disabled = disabled;fetchModelsButton.disabled = disabled;};@@ -622,7 +648,7 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPr}modelInput.focus();if (availableModels.length > 0) {- openAvailableModelMenu(modelInput, availableModels);+ openAvailableModelMenu(modelInput, availableModels, availableModelDisplayNames);}};@@ -640,18 +666,20 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPr}hasFetchedModels = true;fetchingModels = true;+ const requestedAccountID = draft.accountID;const icon = fetchModelsButton.querySelector<SVGSVGElement>(".b3-button__icon");updateModelActionButtons();confirmButton.disabled = true;icon?.classList.add("fn__rotate");fetchPost("/api/ai/listModels", {providerConfig: draft}, (response) => {- if (!view.isConnected) {+ if (!view.isConnected || draft.accountID !== requestedAccountID) {return;}if (response.code !== 0) {return;}const data = response.data;+ availableModelDisplayNames = data.displayNames || {};const responseModels: unknown[] = Array.isArray(data.models) ? data.models : [];const models = responseModels.filter((name): name is string => typeof name === "string" && name.trim() !== "")@@ -676,7 +704,8 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPr);return;}- availableModels = [...new Set(models)].sort((first, second) => first.localeCompare(second));+ availableModels = [...new Set(models)];+ if (draft.authType !== "chatgpt") { availableModels.sort((first, second) => first.localeCompare(second)); }draft.models.forEach((model) => {const contextLength = getAvailableModelContextLength(model.name);if (contextLength > 0) {@@ -688,7 +717,7 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPrid: "",enabled: true,name: availableModels[0],- displayName: "",+ displayName: data.displayNames?.[availableModels[0]] || "",};const contextLength = getAvailableModelContextLength(model.name);if (contextLength > 0) {@@ -711,10 +740,24 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPrupdateModelActionButtons();confirmButton.disabled = false;icon?.classList.remove("fn__rotate");- onFinished?.();+ if (draft.authType === "chatgpt" && draft.accountID !== requestedAccountID) {+ if (draft.accountID) { fetchModels(); }+ } else { onFinished?.(); }});};+ if (draft.authType === "chatgpt") {+ for (const selector of ["[data-provider-field='baseURL']", "[data-provider-field='apiKey']",+ "[data-provider-field='protocol']", "[data-type='providerHeaders']"]) {+ view.querySelector(selector)?.closest(".config-item")?.classList.add("fn__none");+ }+ mountChatGPTAccount(view, draft, ready => {+ updateModelActionButtons();+ renderDraftModels(modelsContainer, draft.models, availableModels);+ if (ready && draft.models.length === 0 && !fetchingModels) { fetchModels(); }+ });+ }+const leaveDetail = () => {removeProviderView(root, view);};@@ -757,8 +800,15 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPr: 0;return;}+ const previousName = draft.models[modelIndex].name;draft.models[modelIndex][modelField] = target.value;if (modelField === "name") {+ const model = draft.models[modelIndex];+ if (!model.displayName || model.displayName === availableModelDisplayNames[previousName]) {+ model.displayName = availableModelDisplayNames[target.value] || "";+ const displayInput = target.closest("[data-model-index]")?.querySelector<HTMLInputElement>("[data-model-field='displayName']");+ if (displayInput) { displayInput.value = model.displayName; }+ }const contextLength = getAvailableModelContextLength(target.value);if (contextLength > 0) {draft.models[modelIndex].contextLength = contextLength;@@ -795,7 +845,7 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPrreturn;}event.preventDefault();- openAvailableModelMenu(target, availableModels);+ openAvailableModelMenu(target, availableModels, availableModelDisplayNames);});view.addEventListener("click", (event) => {@@ -826,7 +876,7 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPr}const modelIndex = Number(actionElement.closest<HTMLElement>("[data-model-index]")?.dataset.modelIndex);if (action === "selectModel" && availableModels.length > 0) {- openAvailableModelMenu(actionElement as HTMLInputElement, availableModels);+ openAvailableModelMenu(actionElement as HTMLInputElement, availableModels, availableModelDisplayNames);return;}if (action === "deleteModel" && draft.models[modelIndex]) {@@ -934,8 +984,8 @@ export const mountProviderCards = (root: HTMLElement) => {});};-const getEnabledModelGroups = () => window.siyuan.config.ai.providers- .filter((provider) => provider.enabled)+const getEnabledModelGroups = (group?: ModelPickerGroup) => window.siyuan.config.ai.providers+ .filter((provider) => provider.enabled && (group !== "imageGeneration" || provider.authType !== "chatgpt")).map((provider) => ({provider,models: provider.models.filter((model) => model.enabled),@@ -946,7 +996,7 @@ const getFirstEnabledModelId = () => getEnabledModelGroups()[0]?.models[0]?.id |const getSelectedModelId = (group: ModelPickerGroup) => {const savedModelId = window.siyuan.config.ai[group].modelId;- const valid = getEnabledModelGroups().some((item) => item.models.some((model) => model.id === savedModelId));+ const valid = getEnabledModelGroups(group).some((item) => item.models.some((model) => model.id === savedModelId));if (valid || group === "imageGeneration") {return valid ? savedModelId : "";}@@ -976,10 +1026,10 @@ const setGroupedModelPickerLabel = (element: GroupedModelPickerElement, label: s}};-const updateGroupedModelPicker = (element: GroupedModelPickerElement, selectedModelId: string) => {+const updateGroupedModelPicker = (element: GroupedModelPickerElement, selectedModelId: string, group: ModelPickerGroup) => {element.dataset.modelId = selectedModelId;setGroupedModelPickerLabel(element, getModelPickerLabel(selectedModelId));- element.disabled = getEnabledModelGroups().length === 0;+ element.disabled = getEnabledModelGroups(group).length === 0;};const getGroupedModelMenuId = (group: ModelPickerGroup, options?: IGroupedModelPickerOptions) =>@@ -1001,7 +1051,7 @@ const openGroupedModelMenu = (if (element.disabled) {return;}- const modelGroups = getEnabledModelGroups();+ const modelGroups = getEnabledModelGroups(group);const selectedModelId = options.getSelectedModelId ? options.getSelectedModelId() : getSelectedModelId(group);const menu = new Menu(getGroupedModelMenuId(group, options));if (menu.isOpen) {@@ -1060,7 +1110,7 @@ const syncGroupedModelPickers = (root: HTMLElement) => {if (!input) {return;}- updateGroupedModelPicker(input, getSelectedModelId(group));+ updateGroupedModelPicker(input, getSelectedModelId(group), group);});};@@ -1074,7 +1124,7 @@ export const genGroupedModelPickerHtml = (group: ModelPickerGroup): string => {desc = window.siyuan.languages.aiImageGenerationTip;}const selectedModelId = getSelectedModelId(group);- const disabled = getEnabledModelGroups().length === 0 ? " disabled" : "";+ const disabled = getEnabledModelGroups(group).length === 0 ? " disabled" : "";const modelLabel = getModelPickerLabel(selectedModelId);return `<div class="fn__flex b3-label config-item" id="aiModelPickerBlock-${group}" data-type="aiModelPicker" data-name="${group}">${genConfigItemMainHtml(window.siyuan.languages.defaultModel, desc)}@@ -1096,6 +1146,7 @@ export const mountGroupedModelPicker = (const update = () => updateGroupedModelPicker(element,options.getSelectedModelId ? options.getSelectedModelId() : getSelectedModelId(group),+ group,);const openMenu = () => openGroupedModelMenu(root, element, group, options, update);update();diff --git a/app/src/config/tabs/ai/aiUi.ts b/app/src/config/tabs/ai/aiUi.tsindex d36d7c9d55..4fae236bcd 100644--- a/app/src/config/tabs/ai/aiUi.ts+++ b/app/src/config/tabs/ai/aiUi.ts@@ -15,6 +15,9 @@ import {shell} from "electron";type ModelPickerGroup = "editing" | "agent" | "imageGeneration";export const getProvidersBlockKeywords = (): string[] => [+ "ChatGPT",+ window.siyuan.languages.chatGPTAccount,+ window.siyuan.languages.chatGPTConnect,window.siyuan.languages.apiKeyRequired,window.siyuan.languages.apiProvider,"Chat Completions",diff --git a/app/src/config/tabs/ai/chatGPTAccount.test.ts b/app/src/config/tabs/ai/chatGPTAccount.test.tsnew file mode 100644index 0000000000..560e092996--- /dev/null+++ b/app/src/config/tabs/ai/chatGPTAccount.test.ts@@ -0,0 +1,123 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import test from "node:test";+import {runInNewContext} from "node:vm";+import {transpileModule, ModuleKind} from "typescript";++class Control {+ value = "";+ innerHTML = "";+ textContent = "";+ disabled = false;+ isConnected = true;+ files: Array<{size: number; text: () => Promise<string>}> = [];+ dataset: Record<string, string> = {};+ listeners = new Map<string, (event: {target: Control}) => void | Promise<void>>();+ classes = new Set<string>();+ classList = {toggle: (name: string, force: boolean) => { if (force) { this.classes.add(name); } else { this.classes.delete(name); } }};+ addEventListener(name: string, handler: (event: {target: Control}) => void | Promise<void>) { this.listeners.set(name, handler); }+ closest() { return this; }+ focus() {}+ click() {}+}++const fixture = (remote = false) => {+ const controls: Record<string, Control> = {};+ for (const name of ["account", "password", "file", "status", "login", "add", "logout", "usage", "cancel", "export", "import"]) {+ controls[name] = new Control();+ controls[name].dataset.chatgpt = name;+ }+ const root = new Control();+ const buttons = ["login", "add", "logout", "usage", "cancel", "export", "import"].map(name => controls[name]);+ Object.assign(root, {+ querySelector: (selector: string) => controls[selector.match(/data-chatgpt='([^']+)'/)![1]],+ querySelectorAll: () => buttons,+ });+ const view = {isConnected: true, querySelector: () => root};+ const calls: Array<{path: string; body: unknown}> = [];+ const timers = new Map<number, () => void>();+ let observerCallback: () => void;+ const browserWindow = {opener: {}, location: {href: "about:blank"}, close: () => {}};+ const profiles = [{id: "account-one", email: "[email protected]", name: "", connected: true, sharing: true}];+ const namespace: Record<string, unknown> = {};+ let pendingStatus: (response: unknown) => void;+ let loginCount = 0;+ const source = readFileSync("src/config/tabs/ai/chatGPTAccount.ts", "utf8");+ runInNewContext(transpileModule(source, {compilerOptions: {module: ModuleKind.CommonJS}}).outputText, {+ exports: namespace,+ require: (name: string) => {+ if (name.endsWith("util/fetch")) {+ return {fetchPost: async (path: string, body: unknown, callback?: (response: unknown) => void) => {+ calls.push({path, body});+ if (path.endsWith("accounts")) { callback?.({code: 0, data: profiles}); }+ if (path.endsWith("start")) { callback?.({code: 0, data: {id: "attempt-" + (++loginCount), url: "https://auth.openai.com/authorize"}}); }+ if (path.endsWith("status")) { pendingStatus = callback!; }+ }};+ }+ if (name.endsWith("util/escape")) { return {escapeHtmlTextAndAttr: (value: string) => value}; }+ if (name.endsWith("util/hostCapabilities")) { return {getHostCapabilities: () => ({remoteKernel: remote})}; }+ if (name.endsWith("util/compatibility")) { return {isInMobileApp: () => false, saveExportFile: async () => ({status: "success"})}; }+ if (name.endsWith("editor/openLink")) { return {openByMobile: () => {}}; }+ if (name.endsWith("dialog/message")) { return {showMessage: () => {}}; }+ if (name.endsWith("render/fragments")) { return {genConfigItemMainHtml: () => ""}; }+ if (name === "electron") { return {shell: {openExternal: async () => {}}}; }+ throw new Error(name);+ },+ location: {hostname: remote ? "notes.example.com" : "127.0.0.1"},+ MutationObserver: class { constructor(callback: () => void) { observerCallback = callback; } observe() {} disconnect() {} },+ window: {+ siyuan: {languages: {mcpStatusConnected: "Connected", chatGPTConnect: "Continue", chatGPTRemoteTip: "Import on remote"}},+ setTimeout: (callback: () => void) => { const id = timers.size + 1; timers.set(id, callback); return id; },+ clearTimeout: (id: number) => { timers.delete(id); },+ open: () => browserWindow,+ },+ document: {body: {}},+ });+ const draft = {authType: "chatgpt", accountID: "", models: [{name: "previous-model"}]};+ const ready: boolean[] = [];+ const mount = namespace.mountChatGPTAccount as (root: unknown, draft: unknown, onChange: (ready: boolean) => void) => void;+ mount(view, draft, value => ready.push(value));+ return {+ controls, root, view, draft, calls, timers, ready, browserWindow,+ remove: () => { view.isConnected = false; observerCallback(); },+ finish: (response: unknown) => pendingStatus(response),+ };+};++test("remote account settings offer import and retain account selection", async () => {+ const f = fixture(true);+ await Promise.resolve();+ assert.equal(f.controls.login.disabled, true);+ assert.equal(f.controls.add.disabled, true);+ assert.equal(f.controls.import.disabled, false);+ f.controls.account.value = "account-one";+ await f.controls.account.listeners.get("change")!({target: f.controls.account});+ assert.equal(f.draft.accountID, "account-one");+ assert.equal(f.draft.models.length, 0);+ assert.equal(f.ready.at(-1), true);+});++test("closing account settings cancels login and ignores a late callback", async () => {+ const f = fixture();+ await Promise.resolve();+ await f.root.listeners.get("click")!({target: f.controls.login});+ assert.equal(f.browserWindow.location.href, "https://auth.openai.com/authorize");+ assert.equal(f.controls.cancel.disabled, false);+ for (const callback of [...f.timers.values()]) { callback(); }+ f.remove();+ assert.ok(f.calls.some(call => call.path.endsWith("cancel")));+ f.finish({code: 0, data: {state: "completed", accountID: "account-one"}});+ assert.equal(f.draft.accountID, "");+});++test("an old login result cannot replace a newer login attempt", async () => {+ const f = fixture();+ await Promise.resolve();+ await f.root.listeners.get("click")!({target: f.controls.login});+ for (const callback of [...f.timers.values()]) { callback(); }+ await f.root.listeners.get("click")!({target: f.controls.cancel});+ await f.root.listeners.get("click")!({target: f.controls.login});+ assert.equal(f.calls.filter(call => call.path.endsWith("start")).length, 2);+ f.finish({code: 0, data: {state: "completed", accountID: "account-one"}});+ assert.equal(f.draft.accountID, "");+});diff --git a/app/src/config/tabs/ai/chatGPTAccount.ts b/app/src/config/tabs/ai/chatGPTAccount.tsnew file mode 100644index 0000000000..7260284bf4--- /dev/null+++ b/app/src/config/tabs/ai/chatGPTAccount.ts@@ -0,0 +1,202 @@+import {fetchPost} from "../../../util/fetch";+import type {ChatGPTAccount} from "../../../types/api";+import {escapeHtmlTextAndAttr} from "../../../util/escape";+import {showMessage} from "../../../dialog/message";+import {genConfigItemMainHtml} from "../../render/fragments";+import {openByMobile} from "../../../editor/openLink";+import {isInMobileApp, saveExportFile} from "../../../protyle/util/compatibility";+import {getHostCapabilities} from "../../../util/hostCapabilities";+/// #if !BROWSER+import {shell} from "electron";+/// #endif++const openExternal = (url: string) => {+ /// #if !BROWSER+ void shell.openExternal(url);+ /// #else+ openByMobile(url);+ /// #endif+};++export const genChatGPTAccountHTML = () => {+ const L = window.siyuan.languages;+ return `<div class="b3-label config-item" data-type="chatGPTAccount">+ ${genConfigItemMainHtml(L.chatGPTAccount, L.chatGPTPlanUsageTip)}+ <div class="fn__hr"></div>+ <select class="b3-select fn__block" data-chatgpt="account" aria-label="${L.chatGPTAccount}"></select>+ <div class="fn__hr"></div>+ <div class="fn__flex fn__flex-wrap">+ <button class="b3-button" data-chatgpt="login">${L.chatGPTConnect}</button>+ <span class="fn__space"></span>+ <button class="b3-button b3-button--outline" data-chatgpt="add">${L.chatGPTAddAccount}</button>+ <span class="fn__space"></span>+ <button class="b3-button b3-button--outline" data-chatgpt="logout">${L.logout}</button>+ <span class="fn__space"></span>+ <button class="b3-button b3-button--outline" data-chatgpt="usage">${L.chatGPTUsage}</button>+ <span class="fn__space"></span>+ <button class="b3-button b3-button--cancel fn__none" data-chatgpt="cancel">${L.cancel}</button>+ </div>+ <div class="fn__hr"></div>+ <div class="ft__on-surface" data-chatgpt="status"></div>+ <div class="fn__hr"></div>+ <div class="ft__on-surface">${L.chatGPTRemoteTip}</div>+ <div class="fn__hr"></div>+ <label class="fn__flex">${L.password}<span class="fn__space"></span><input class="b3-text-field fn__flex-1" data-chatgpt="password" type="password" minlength="12" autocomplete="new-password"></label>+ <div class="fn__hr"></div>+ <div class="ft__on-surface">${L.chatGPTTransferTip}</div>+ <div class="fn__hr"></div>+ <div class="fn__flex fn__flex-wrap">+ <button class="b3-button b3-button--outline" data-chatgpt="export">${L.export}</button>+ <span class="fn__space"></span>+ <button class="b3-button b3-button--outline" data-chatgpt="import">${L.import}</button>+ <input class="fn__none" data-chatgpt="file" type="file" accept=".json">+ </div>+ </div>`;+};++export const mountChatGPTAccount = (view: HTMLElement, draft: Config.IProvider, onChange: (ready: boolean) => void) => {+ const root = view.querySelector<HTMLElement>("[data-type='chatGPTAccount']");+ const localKernel = !getHostCapabilities().remoteKernel && ["localhost", "127.0.0.1", "[::1]"].includes(location.hostname);+ const picker = root.querySelector<HTMLSelectElement>("[data-chatgpt='account']");+ const password = root.querySelector<HTMLInputElement>("[data-chatgpt='password']");+ const fileInput = root.querySelector<HTMLInputElement>("[data-chatgpt='file']");+ const status = root.querySelector<HTMLElement>("[data-chatgpt='status']");+ const L = window.siyuan.languages;+ let profiles: ChatGPTAccount[] = [];+ let attemptID = "";+ let busy = false;+ let exportedFile = "";+ let timer: number;+ let disposed = false;+ const update = () => {+ const selected = profiles.find(item => item.id === draft.accountID);+ picker.innerHTML = `<option value="">${escapeHtmlTextAndAttr(L.chatGPTConnect)}</option>` + profiles.map(item =>+ `<option value="${escapeHtmlTextAndAttr(item.id)}">${escapeHtmlTextAndAttr((item.email || item.name || "ChatGPT") + " (" + item.id.slice(-8) + ")")}</option>`).join("");+ picker.value = draft.accountID || "";+ picker.disabled = busy || !!attemptID;+ root.querySelectorAll<HTMLButtonElement>("button").forEach(button => {+ button.disabled = busy || !!attemptID;+ });+ const cancel = root.querySelector<HTMLButtonElement>("[data-chatgpt='cancel']");+ cancel.classList.toggle("fn__none", !attemptID);+ cancel.disabled = busy;+ root.querySelector<HTMLButtonElement>("[data-chatgpt='logout']").disabled ||= !selected?.connected;+ root.querySelector<HTMLButtonElement>("[data-chatgpt='export']").disabled ||= !selected?.connected && !exportedFile;+ for (const action of ["login", "add"]) {+ root.querySelector<HTMLButtonElement>(`[data-chatgpt='${action}']`).disabled ||= !localKernel;+ }+ status.textContent = attemptID ? L.chatGPTSignInPendingTip : selected?.sharing ? L.mcpStatusConnected :+ localKernel ? L.chatGPTConnect : L.chatGPTRemoteTip;+ onChange(!!selected?.sharing && !busy && !attemptID);+ };+ const load = async () => {+ await fetchPost("/api/ai/chatgpt/accounts", undefined, response => {+ if (!disposed && response.code === 0) { profiles = response.data; update(); }+ });+ };+ const stop = () => {+ window.clearTimeout(timer);+ const id = attemptID;+ attemptID = "";+ if (id) { void fetchPost("/api/ai/chatgpt/cancel", {id}); }+ };+ const observer = new MutationObserver(() => {+ if (!view.isConnected) { disposed = true; stop(); observer.disconnect(); }+ });+ observer.observe(document.body, {childList: true, subtree: true});+ const poll = async (): Promise<void> => {+ if (disposed || !attemptID) { return; }+ const id = attemptID;+ await fetchPost("/api/ai/chatgpt/status", {id}, async response => {+ if (disposed || attemptID !== id) { return; }+ if (response.code !== 0) { stop(); update(); return; }+ if (response.data.state === "completed") {+ draft.accountID = response.data.accountID;+ attemptID = "";+ draft.models = [];+ await load();+ } else if (response.data.state === "failed") {+ attemptID = "";+ update();+ showMessage(escapeHtmlTextAndAttr(response.data.error), undefined, "error");+ }+ });+ if (attemptID === id && !disposed) { timer = window.setTimeout((): void => { void poll(); }, 1000); }+ };+ picker.addEventListener("change", () => {+ draft.accountID = picker.value;+ draft.models = [];+ exportedFile = "";+ update();+ });+ const transferPassword = () => {+ if (Array.from(password.value).length < 12) {+ password.focus(); showMessage(L.chatGPTTransferTip); return "";+ }+ return password.value;+ };+ root.addEventListener("click", async event => {+ const button = (event.target as HTMLElement).closest<HTMLButtonElement>("button[data-chatgpt]");+ if (!button || button.disabled) { return; }+ const action = button.dataset.chatgpt;+ if (action === "usage") { openExternal("https://chatgpt.com/settings/usage"); return; }+ if (action === "cancel") { stop(); update(); return; }+ if (action === "import") { if (transferPassword()) { fileInput.click(); } return; }+ let authorizationWindow: Window;+ /// #if BROWSER+ if ((action === "login" || action === "add") && !isInMobileApp()) {+ authorizationWindow = window.open("about:blank", "_blank");+ if (authorizationWindow) { authorizationWindow.opener = null; }+ }+ /// #endif+ busy = true;+ update();+ try {+ if (action === "login" || action === "add") {+ const registered = profiles.some(item => item.id === draft.accountID);+ await fetchPost("/api/ai/chatgpt/start", {accountID: action === "add" || !registered ? "" : draft.accountID}, response => {+ if (response.code !== 0) { return; }+ if (disposed) { void fetchPost("/api/ai/chatgpt/cancel", {id: response.data.id}); return; }+ attemptID = response.data.id;+ if (authorizationWindow) { authorizationWindow.location.href = response.data.url; }+ else { openExternal(response.data.url); }+ timer = window.setTimeout((): void => { void poll(); }, 1000);+ });+ } else if (action === "logout") {+ await fetchPost("/api/ai/chatgpt/logout", {accountID: draft.accountID}, response => {+ if (response.code === 0 && !response.data.revoked) { showMessage(L.chatGPTRevokeFailed); }+ });+ await load();+ } else if (action === "export") {+ if (!exportedFile) {+ const secret = transferPassword();+ if (!secret) { return; }+ await fetchPost("/api/ai/chatgpt/export", {accountID: draft.accountID, password: secret}, response => {+ if (response.code === 0) { exportedFile = response.data.file; }+ });+ password.value = "";+ await load();+ }+ if (exportedFile) { await saveExportFile(exportedFile); }+ }+ } finally {+ if (authorizationWindow && !attemptID) { authorizationWindow.close(); }+ busy = false;+ if (!disposed) { update(); }+ }+ });+ fileInput.addEventListener("change", async () => {+ const file = fileInput.files?.[0];+ const secret = transferPassword();+ if (!file || !secret) { return; }+ if (file.size > 1024 * 1024) { showMessage(L.chatGPTRemoteTip, undefined, "error"); return; }+ busy = true; update();+ try {+ await fetchPost("/api/ai/chatgpt/import", {password: secret, data: await file.text()}, response => {+ if (!disposed && response.code === 0) { draft.accountID = response.data.id; draft.models = []; }+ });+ await load();+ } finally { password.value = ""; fileInput.value = ""; busy = false; if (!disposed) { update(); } }+ });+ void load();+};diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.tsindex 0719ee5d01..2f5dc065af 100644--- a/app/src/layout/dock/agent/AgentChat.ts+++ b/app/src/layout/dock/agent/AgentChat.ts@@ -614,6 +614,8 @@ export class AgentChat extends Model {const existing = window.siyuan.dialogs.find(d => d.element.querySelector(".config__tab-container"));if (!existing) {openSetting(this.app, "ai");+ } else {+ existing.element.querySelector<HTMLElement>(".config__tab-scroll [data-name='ai']")?.click();}}@@ -810,6 +812,16 @@ export class AgentChat extends Model {this.openAiSetting();});}+ this.messagesContainer.querySelector("[data-type='go-chatgpt']")?.addEventListener("click", async () => {+ if (this.host.openAiSetting || window.siyuan.dialogs.some(dialog => dialog.element.querySelector(".config__tab-container"))) {+ await this.openAiSetting();+ const {openChatGPTProvider} = await import("../../../config/tabs/ai/aiProviderUi");+ openChatGPTProvider();+ } else {+ const {openSetting} = await import("../../../config");+ openSetting(this.app, "ai", "chatgpt");+ }+ });return;}const examples = this.messagesContainer.querySelectorAll(".agent-welcome__example");diff --git a/app/src/layout/dock/agent/AgentMessageRenderer.ts b/app/src/layout/dock/agent/AgentMessageRenderer.tsindex 5b55c3b9f2..23bb41f5cb 100644--- a/app/src/layout/dock/agent/AgentMessageRenderer.ts+++ b/app/src/layout/dock/agent/AgentMessageRenderer.ts@@ -59,6 +59,7 @@ export const renderWelcomeHTML = (hasModel = true): string => {'<div class="agent-welcome__no-model-title">' + (L.agentNoModel || "No model configured") + "</div>" +'<div class="agent-welcome__no-model-tip">' + L.agentNoModelTip + "</div>" +'<button class="b3-button agent-welcome__go-setting" data-type="go-ai-setting">' + (L.agentGoToSetting || "Go to Settings") + "</button>" ++ '<div class="fn__hr"></div><button class="b3-button b3-button--outline" data-type="go-chatgpt">' + L.chatGPTConnect + "</button>" +"</div>" +"</div>";}diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex fdd50af62c..a62667302e 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -70,7 +70,7 @@ export type AIModelRequestInput = { "model": string; "provider"?: string | null;export type AIModelTestData = { "available": Array<string> | null; "matched": boolean; "msg"?: string; };-export type AIModelsData = { "contextLengths": Record<string, number> | null; "models": Array<string> | null; "msg"?: string; };+export type AIModelsData = { "contextLengths": Record<string, number> | null; "displayNames"?: Record<string, string>; "models": Array<string> | null; "msg"?: string; };export type AINativeContent = { "blocks": Array<JSONValue> | null; "protocol": string; "version": number; };@@ -774,6 +774,20 @@ export type ChangeMasterPasswordRequestInput = { "newPassword": string; "oldPassexport type ChangeSortNotebookRequestInput = { "notebooks": Array<string>; };+export type ChatGPTAccount = { "connected": boolean; "email": string; "id": string; "name": string; "sharing": boolean; };++export type ChatGPTAccountRequestInput = { "accountID"?: string; };++export type ChatGPTLogin = { "id": string; "url": string; };++export type ChatGPTLoginRequestInput = { "id": string; };++export type ChatGPTLoginStatus = { "accountID": string; "error": string; "state": string; };++export type ChatGPTLogoutResult = { "revoked": boolean; };++export type ChatGPTTransferRequestInput = { "accountID"?: string; "data"?: string; "password": string; };+export type CheckActivationCodeRequestInput = { "data": string; };export type CheckBlockRefRequestInput = { "deletedIDs"?: Array<string>; "exactIDs"?: Array<string>; "id"?: string | null; "ids"?: Array<string>; "notebook"?: string | null; "paths"?: Array<string>; "scope"?: string; };@@ -2012,9 +2026,9 @@ export type SettingPetalDisabledData = { "dataChangePlugins": Array<string> | nuexport type SettingPetalDisabledRequestInput = { "petalDisabled": boolean; };-export type SettingProvider = { "apiKey": string; "baseURL": string; "displayName"?: string; "enabled": boolean; "headers"?: Record<string, string>; "id": string; "models": Array<SettingModel | null> | null; "protocol"?: string; "requestTimeout": number; };+export type SettingProvider = { "accountID"?: string; "apiKey": string; "authType"?: string; "baseURL": string; "displayName"?: string; "enabled": boolean; "headers"?: Record<string, string>; "id": string; "models": Array<SettingModel | null> | null; "protocol"?: string; "requestTimeout": number; };-export type SettingProviderInput = { "apiKey"?: string | null; "baseURL"?: string | null; "displayName"?: string | null; "enabled"?: boolean | null; "headers"?: Record<string, string> | null; "id"?: string | null; "models"?: Array<SettingModelInput | null> | null; "protocol"?: string | null; "requestTimeout"?: number | null; };+export type SettingProviderInput = { "accountID"?: string | null; "apiKey"?: string | null; "authType"?: string | null; "baseURL"?: string | null; "displayName"?: string | null; "enabled"?: boolean | null; "headers"?: Record<string, string> | null; "id"?: string | null; "models"?: Array<SettingModelInput | null> | null; "protocol"?: string | null; "requestTimeout"?: number | null; };export type SettingPublish = { "auth": SettingBasicAuth | null; "enable": boolean; "port": number; };@@ -2739,6 +2753,41 @@ export interface APIPOSTRoutes {response: { "code": 0; "data": string; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };body: "json";};+ "/api/ai/chatgpt/accounts": {+ request: EmptyRequestInput;+ response: { "code": 0; "data": Array<ChatGPTAccount>; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "none";+ };+ "/api/ai/chatgpt/cancel": {+ request: ChatGPTLoginRequestInput;+ response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };+ "/api/ai/chatgpt/export": {+ request: ChatGPTTransferRequestInput;+ response: { "code": 0; "data": ExportFileData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };+ "/api/ai/chatgpt/import": {+ request: ChatGPTTransferRequestInput;+ response: { "code": 0; "data": ChatGPTAccount; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };+ "/api/ai/chatgpt/logout": {+ request: ChatGPTAccountRequestInput;+ response: { "code": 0; "data": ChatGPTLogoutResult; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };+ "/api/ai/chatgpt/start": {+ request: ChatGPTAccountRequestInput;+ response: { "code": 0; "data": ChatGPTLogin; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };+ "/api/ai/chatgpt/status": {+ request: ChatGPTLoginRequestInput;+ response: { "code": 0; "data": ChatGPTLoginStatus; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };"/api/ai/editor/chat": {request: AIEditorChatRequestInput;response: string | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.tsindex 54f7d65b90..91cfc2d96a 100644--- a/app/src/types/config.d.ts+++ b/app/src/types/config.d.ts@@ -243,6 +243,9 @@ declare namespace Config {* AI provider configuration*/export interface IProvider {+ /** 账户认证只保存本机账户引用;省略时使用 API Key */+ authType?: string;+ accountID?: string;headers?: Record<string, string>;id: string;enabled: boolean;diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex 024d83c53c..e0c4a7bf9c 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -37,6 +37,7 @@ import ("github.com/siyuan-note/logging""github.com/sashabaranov/go-openai"+ "github.com/siyuan-note/siyuan/kernel/chatgpt""github.com/siyuan-note/siyuan/kernel/conf"mcpclient "github.com/siyuan-note/siyuan/kernel/mcp/client"mcptools "github.com/siyuan-note/siyuan/kernel/mcp/tools"@@ -802,7 +803,7 @@ func AgentChat(ctx context.Context, client *util.AIClient, protocol, model, imag}nativeResponsesCompaction := util.IsOpenAIResponsesProtocol(protocol) &&- util.SupportsOpenAIResponsesCompaction(ctx)+ util.SupportsOpenAIResponsesCompaction(ctx) && !client.ChatGPT// 原生 compact 无法限制输出长度,覆盖所有已完成轮次,避免 opaque window 返回后仍超出预算。selectedCandidateIndex := len(candidates) - 1if !nativeResponsesCompaction {@@ -2697,10 +2698,20 @@ func classifyRetry(err error) string {if errors.Is(err, errModelRequestTimeout) || errors.Is(err, errModelStreamIdleTimeout) || errors.Is(err, context.DeadlineExceeded) {return "timeout"}+ var subscriptionErr *chatgpt.RequestError+ if errors.As(err, &subscriptionErr) {+ if subscriptionErr.Status >= 500 {+ return "server_error"+ }+ return "fatal"+ }var apiErr *openai.APIErrorif errors.As(err, &apiErr) {code := strings.ToLower(strings.TrimSpace(fmt.Sprint(apiErr.Code)))+ if code == "subscription_sharing_usage_limit_exceeded" {+ return "fatal"+ }switch {case strings.Contains(code, "rate_limit"):return "rate_limit"diff --git a/kernel/agent/stream_timeout_test.go b/kernel/agent/stream_timeout_test.goindex 77496fab0b..815082e67d 100644--- a/kernel/agent/stream_timeout_test.go+++ b/kernel/agent/stream_timeout_test.go@@ -123,6 +123,7 @@ func TestClassifyRetryResponsesErrors(t *testing.T) {}{{code: "invalid_request_error", want: "fatal"},{code: "rate_limit_exceeded", want: "rate_limit"},+ {code: "subscription_sharing_usage_limit_exceeded", want: "fatal"},{code: "server_error", want: "server_error"},}for _, test := range tests {diff --git a/kernel/api/agent.go b/kernel/api/agent.goindex 7a45df9b48..bc85218046 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.NewAIClientWithModel(selectedProvider.APIKey, selectedProvider.BaseURL, selectedModel.Name, model.ResolveAIProviderHeaders(selectedProvider))+ client := model.NewAIProviderClient(selectedProvider, selectedModel.Name)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.NewAIClientWithModel(selectedProvider.APIKey, selectedProvider.BaseURL, selectedModel.Name, model.ResolveAIProviderHeaders(selectedProvider))+ client := model.NewAIProviderClient(selectedProvider, selectedModel.Name)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 5c5d4124fc..dfe489fe9f 100644--- a/kernel/api/ai.go+++ b/kernel/api/ai.go@@ -17,14 +17,17 @@package apiimport (+ "context""errors""net/http""strings"+ "time""github.com/88250/gulu""github.com/gin-gonic/gin""github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/chatgpt""github.com/siyuan-note/siyuan/kernel/conf"mcpclient "github.com/siyuan-note/siyuan/kernel/mcp/client""github.com/siyuan-note/siyuan/kernel/model"@@ -234,8 +237,14 @@ func testModelContract(c *gin.Context, req apicontract.AIModelRequest) apicontrareturn contractFailure[apicontract.AIModelTestData](ret)}- available, matched, err := util.TestModel(- provider.APIKey, provider.BaseURL, provider.Protocol, req.Model, provider.RequestTimeout, model.ResolveAIProviderHeaders(provider))+ var available []string+ var matched bool+ if provider.AuthType == "chatgpt" {+ available, matched, err = testChatGPTModel(c.Request.Context(), provider, req.Model)+ } else {+ available, matched, err = util.TestModel(+ provider.APIKey, provider.BaseURL, provider.Protocol, req.Model, provider.RequestTimeout, model.ResolveAIProviderHeaders(provider))+ }// 可用模型清单裁剪到前 50 条,避免响应体过大if 50 < len(available) {available = available[:50]@@ -325,7 +334,20 @@ func listModelsContract(c *gin.Context, req apicontract.AIProviderRequest) apicoreturn contractFailure[apicontract.AIModelsData](ret)}- metadata, err := util.ListProviderModels(provider.APIKey, provider.BaseURL, provider.Protocol, provider.RequestTimeout, model.ResolveAIProviderHeaders(provider))+ var metadata []util.AvailableModel+ displayNames := map[string]string{}+ if provider.AuthType == "chatgpt" {+ var catalog []chatgpt.Model+ ctx, cancel := context.WithTimeout(c.Request.Context(), time.Duration(provider.RequestTimeout)*time.Second)+ defer cancel()+ catalog, err = util.ChatGPTService().Models(ctx, provider.AccountID)+ for _, item := range catalog {+ metadata = append(metadata, util.AvailableModel{ID: item.ID})+ displayNames[item.ID] = item.DisplayName+ }+ } else {+ 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 {@@ -336,7 +358,7 @@ func listModelsContract(c *gin.Context, req apicontract.AIProviderRequest) apico}}}- result := apicontract.AIModelsData{Models: models, ContextLengths: contextLengths}+ result := apicontract.AIModelsData{Models: models, ContextLengths: contextLengths, DisplayNames: displayNames}if nil != err {message := err.Error()result.Msg = &messagediff --git a/kernel/api/ai_disabled_test.go b/kernel/api/ai_disabled_test.goindex be0dfe2468..9a72b321b8 100644--- a/kernel/api/ai_disabled_test.go+++ b/kernel/api/ai_disabled_test.go@@ -36,6 +36,13 @@ func TestAPIContractAIDisabled(t *testing.T) {"/api/ai/testRerankModel": testRerankModel,"/api/ai/testDecisionModel": testDecisionModel,"/api/ai/listModels": listModels,+ "/api/ai/chatgpt/accounts": chatGPTAccounts,+ "/api/ai/chatgpt/start": chatGPTStart,+ "/api/ai/chatgpt/status": chatGPTStatus,+ "/api/ai/chatgpt/cancel": chatGPTCancel,+ "/api/ai/chatgpt/logout": chatGPTLogout,+ "/api/ai/chatgpt/import": chatGPTImport,+ "/api/ai/chatgpt/export": chatGPTExport,"/api/ai/mcpOAuthAuthorize": mcpOAuthAuthorize,"/api/ai/reindexEmbedding": reindexEmbedding,"/api/ai/agent/saveSession": saveSession,diff --git a/kernel/api/chatgpt.go b/kernel/api/chatgpt.gonew file mode 100644index 0000000000..baa642baad--- /dev/null+++ b/kernel/api/chatgpt.go@@ -0,0 +1,145 @@+package api++import (+ "context"+ "errors"+ "io"+ "os"+ "path/filepath"+ "time"++ "github.com/88250/gulu"+ "github.com/gin-gonic/gin"+ "github.com/sashabaranov/go-openai"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/chatgpt"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func chatGPTAccountValue(profile chatgpt.Profile) apicontract.ChatGPTAccount {+ return apicontract.ChatGPTAccount{ID: profile.ID, Email: profile.Email, Name: profile.Name, Connected: profile.Connected, Sharing: profile.Sharing}+}++func chatGPTNoCache(c *gin.Context) {+ c.Header("Cache-Control", "no-store")+ c.Header("Pragma", "no-cache")+}++var chatGPTAccounts = contractHandler(apicontract.ChatGPTAccounts, chatGPTAccountsContract)++func chatGPTAccountsContract(c *gin.Context, _ apicontract.EmptyRequest) apicontract.Response[[]apicontract.ChatGPTAccount] {+ chatGPTNoCache(c)+ profiles, err := util.ChatGPTService().Profiles(c.Request.Context())+ if err != nil {+ return apicontract.Failure[[]apicontract.ChatGPTAccount](-1, err.Error())+ }+ result := make([]apicontract.ChatGPTAccount, 0, len(profiles))+ for _, p := range profiles {+ result = append(result, chatGPTAccountValue(p))+ }+ return apicontract.Success(result)+}++var chatGPTStart = contractHandler(apicontract.ChatGPTStart, chatGPTStartContract)++func chatGPTStartContract(c *gin.Context, req apicontract.ChatGPTAccountRequest) apicontract.Response[apicontract.ChatGPTLogin] {+ chatGPTNoCache(c)+ login, err := util.ChatGPTService().Start(c.Request.Context(), req.AccountID, util.I18nTerm(model.Conf.Lang, "chatGPTCallbackTip"))+ if err != nil {+ return apicontract.Failure[apicontract.ChatGPTLogin](-1, err.Error())+ }+ return apicontract.Success(apicontract.ChatGPTLogin{ID: login.ID, URL: login.URL})+}++var chatGPTStatus = contractHandler(apicontract.ChatGPTStatus, chatGPTStatusContract)++func chatGPTStatusContract(c *gin.Context, req apicontract.ChatGPTLoginRequest) apicontract.Response[apicontract.ChatGPTLoginStatus] {+ chatGPTNoCache(c)+ status, err := util.ChatGPTService().Status(req.ID)+ if err != nil {+ return apicontract.Failure[apicontract.ChatGPTLoginStatus](-1, err.Error())+ }+ return apicontract.Success(apicontract.ChatGPTLoginStatus{State: status.State, AccountID: status.AccountID, Error: status.Error})+}++var chatGPTCancel = contractHandler(apicontract.ChatGPTCancel, chatGPTCancelContract)++func chatGPTCancelContract(c *gin.Context, req apicontract.ChatGPTLoginRequest) apicontract.Response[apicontract.Null] {+ util.ChatGPTService().Cancel(req.ID)+ return apicontract.Success(apicontract.Null{})+}++var chatGPTLogout = contractHandler(apicontract.ChatGPTLogout, chatGPTLogoutContract)++func chatGPTLogoutContract(c *gin.Context, req apicontract.ChatGPTAccountRequest) apicontract.Response[apicontract.ChatGPTLogoutResult] {+ chatGPTNoCache(c)+ revoked, err := util.ChatGPTService().Logout(c.Request.Context(), req.AccountID)+ if err != nil {+ return apicontract.Failure[apicontract.ChatGPTLogoutResult](-1, err.Error())+ }+ return apicontract.Success(apicontract.ChatGPTLogoutResult{Revoked: revoked})+}++var chatGPTExport = contractHandler(apicontract.ChatGPTExport, chatGPTExportContract)++func chatGPTExportContract(c *gin.Context, req apicontract.ChatGPTTransferRequest) apicontract.Response[apicontract.ExportFileData] {+ chatGPTNoCache(c)+ name := "chatgpt-" + gulu.Rand.String(16) + ".siyuan-chatgpt.json"+ dir := filepath.Join(util.TempDir, "export")+ _, err := util.ChatGPTService().Export(c.Request.Context(), req.AccountID, req.Password, func(data string) error {+ if err := os.MkdirAll(dir, 0700); err != nil {+ return err+ }+ return os.WriteFile(filepath.Join(dir, name), []byte(data), 0600)+ })+ if err != nil {+ return apicontract.Failure[apicontract.ExportFileData](-1, err.Error())+ }+ return apicontract.Success(apicontract.ExportFileData{File: "/export/" + name})+}++var chatGPTImport = contractHandler(apicontract.ChatGPTImport, chatGPTImportContract)++func chatGPTImportContract(c *gin.Context, req apicontract.ChatGPTTransferRequest) apicontract.Response[apicontract.ChatGPTAccount] {+ chatGPTNoCache(c)+ profile, err := util.ChatGPTService().Import(c.Request.Context(), req.Data, req.Password)+ if err != nil {+ return apicontract.Failure[apicontract.ChatGPTAccount](-1, err.Error())+ }+ return apicontract.Success(chatGPTAccountValue(profile))+}++func testChatGPTModel(ctx context.Context, provider *conf.Provider, name string) (available []string, matched bool, err error) {+ timeout := provider.RequestTimeout+ if timeout < 1 {+ timeout = 30+ }+ ctx, cancel := context.WithTimeout(ctx, time.Duration(timeout)*time.Second)+ defer cancel()+ models, err := util.ChatGPTService().Models(ctx, provider.AccountID)+ if err != nil {+ return []string{}, false, err+ }+ for _, m := range models {+ available = append(available, m.ID)+ }+ client := util.NewChatGPTClient(provider.AccountID)+ ctx = util.ContextWithOpenAIResponsesBaseURL(ctx, chatgpt.Resource)+ stream, err := util.CreateOpenAICompletionStream(ctx, client, util.OpenAIProtocolResponses,+ openai.ChatCompletionRequest{Model: name, Messages: []openai.ChatCompletionMessage{{Role: "user", Content: "Say OK"}}}, nil)+ if err != nil {+ return available, false, err+ }+ defer stream.Close()+ for {+ _, err = stream.Recv()+ if errors.Is(err, io.EOF) {+ return available, true, nil+ }+ if err != nil {+ return available, false, err+ }+ }+}diff --git a/kernel/api/chatgpt_test.go b/kernel/api/chatgpt_test.gonew file mode 100644index 0000000000..f64180a4f6--- /dev/null+++ b/kernel/api/chatgpt_test.go@@ -0,0 +1,99 @@+package api++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAPIContractChatGPTAccountLifecycle(t *testing.T) {+ aiContractConfiguration(t)+ oldHome := util.HomeDir+ util.HomeDir = t.TempDir()+ t.Cleanup(func() { util.HomeDir = oldHome })+ engine := gin.New()+ bundle, err := apicontract.BuildBundle()+ if err != nil {+ t.Fatal(err)+ }+ engine.POST("/api/ai/chatgpt/accounts", chatGPTAccounts)+ engine.POST("/api/ai/chatgpt/start", chatGPTStart)+ engine.POST("/api/ai/chatgpt/status", chatGPTStatus)+ engine.POST("/api/ai/chatgpt/cancel", chatGPTCancel)+ engine.POST("/api/ai/chatgpt/import", chatGPTImport)+ engine.POST("/api/ai/chatgpt/export", chatGPTExport)+ engine.POST("/api/ai/chatgpt/logout", chatGPTLogout)+ request := func(path, body string) map[string]json.RawMessage {+ w := httptest.NewRecorder()+ engine.ServeHTTP(w, httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)))+ if err := bundle.ValidateHTTPResponse("POST", path, w.Code, w.Header().Get("Content-Type"), w.Body.Bytes()); err != nil {+ t.Fatal(err)+ }+ var result map[string]json.RawMessage+ if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil {+ t.Fatal(err)+ }+ return result+ }+ accounts := request("/api/ai/chatgpt/accounts", "")+ if string(accounts["data"]) != "[]" {+ t.Fatalf("accounts: %s", accounts["data"])+ }+ result := request("/api/ai/chatgpt/start", `{}`)+ var login apicontract.ChatGPTLogin+ json.Unmarshal(result["data"], &login)+ if login.ID == "" || !strings.HasPrefix(login.URL, "https://auth.openai.com/") {+ t.Fatal("invalid login")+ }+ body, _ := json.Marshal(apicontract.ChatGPTLoginRequest{ID: login.ID})+ t.Cleanup(func() { util.ChatGPTService().Cancel(login.ID) })+ request("/api/ai/chatgpt/status", string(body))+ request("/api/ai/chatgpt/cancel", string(body))+ for _, path := range []string{"import", "export", "logout"} {+ result = request("/api/ai/chatgpt/"+path, `{"accountID":"missing","password":"short","data":"{}"}`)+ if string(result["code"]) != "-1" {+ t.Fatalf("invalid %s accepted", path)+ }+ }+}++func TestAPIContractChatGPTAuthorizationBeforeBody(t *testing.T) {+ aiContractConfiguration(t)+ oldHome, oldReadonly := util.HomeDir, util.ReadOnly+ util.HomeDir = t.TempDir()+ t.Cleanup(func() { util.HomeDir = oldHome; util.ReadOnly = oldReadonly })+ for _, role := range []model.Role{model.RoleReader, model.RoleEditor, model.RoleAdministrator} {+ util.ReadOnly = role == model.RoleAdministrator+ engine := gin.New()+ engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, role); c.Next() })+ ServeAPI(engine)+ paths := []string{"start", "cancel", "logout", "export", "import"}+ if role != model.RoleAdministrator {+ paths = append(paths, "accounts", "status")+ }+ for _, path := range paths {+ request := httptest.NewRequest("POST", "/api/ai/chatgpt/"+path, nil)+ request.Body = aiUnreadBody{t: t}+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, request)+ if role != model.RoleAdministrator && recorder.Code != 403 {+ t.Fatalf("non-admin request accepted: %s", path)+ }+ if role == model.RoleAdministrator && !strings.Contains(recorder.Body.String(), `"code":-1`) {+ t.Fatalf("read-only request accepted: %s", path)+ }+ }+ }+ if _, err := os.Stat(filepath.Join(util.HomeDir, ".config", "siyuan", "chatgpt")); !os.IsNotExist(err) {+ t.Fatal("denied request created credentials")+ }+}diff --git a/kernel/api/router.go b/kernel/api/router.goindex a41651997c..4fdcd02b45 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -679,6 +679,13 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/ai/testRerankModel", model.CheckAuth, model.CheckAdminRole, testRerankModel)ginServer.Handle("POST", "/api/ai/testDecisionModel", model.CheckAuth, model.CheckAdminRole, testDecisionModel)ginServer.Handle("POST", "/api/ai/listModels", model.CheckAuth, model.CheckAdminRole, listModels)+ ginServer.Handle("POST", "/api/ai/chatgpt/accounts", model.CheckAuth, model.CheckAdminRole, chatGPTAccounts)+ ginServer.Handle("POST", "/api/ai/chatgpt/start", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, chatGPTStart)+ ginServer.Handle("POST", "/api/ai/chatgpt/status", model.CheckAuth, model.CheckAdminRole, chatGPTStatus)+ ginServer.Handle("POST", "/api/ai/chatgpt/cancel", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, chatGPTCancel)+ ginServer.Handle("POST", "/api/ai/chatgpt/logout", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, chatGPTLogout)+ ginServer.Handle("POST", "/api/ai/chatgpt/export", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, chatGPTExport)+ ginServer.Handle("POST", "/api/ai/chatgpt/import", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, chatGPTImport)ginServer.Handle("POST", "/api/ai/embeddingStat", model.CheckAuth, model.CheckAdminRole, embeddingStat)ginServer.Handle("POST", "/api/ai/mcpStatus", model.CheckAuth, model.CheckAdminRole, mcpStatus)ginServer.Handle("POST", "/api/ai/mcpEnvironmentVariables", model.CheckAuth, model.CheckAdminRole, mcpEnvironmentVariables)diff --git a/kernel/api/setting_contract.go b/kernel/api/setting_contract.goindex a01ad87b25..a68017ad0e 100644--- a/kernel/api/setting_contract.go+++ b/kernel/api/setting_contract.go@@ -216,6 +216,8 @@ func settingProviderPayload(value *conf.Provider) *apicontract.SettingProvider {return nil}result := &apicontract.SettingProvider{}+ result.AuthType = value.AuthType+ result.AccountID = value.AccountIDresult.Headers = value.Headersresult.ID = value.IDresult.DisplayName = value.DisplayNamediff --git a/kernel/apicontract/ai.go b/kernel/apicontract/ai.goindex b5e5df1aee..caf006fb78 100644--- a/kernel/apicontract/ai.go+++ b/kernel/apicontract/ai.go@@ -199,9 +199,10 @@ type AIDecisionTestData struct {Msg *string `json:"msg,omitempty"`}type AIModelsData struct {- Models []string `json:"models"`- ContextLengths map[string]int `json:"contextLengths"`- Msg *string `json:"msg,omitempty"`+ DisplayNames map[string]string `json:"displayNames,omitempty"`+ Models []string `json:"models"`+ ContextLengths map[string]int `json:"contextLengths"`+ Msg *string `json:"msg,omitempty"`}type AIMCPEnvironmentData struct {Names []string `json:"names"`diff --git a/kernel/apicontract/chatgpt.go b/kernel/apicontract/chatgpt.gonew file mode 100644index 0000000000..e1e47c773c--- /dev/null+++ b/kernel/apicontract/chatgpt.go@@ -0,0 +1,38 @@+package apicontract++type ChatGPTAccountRequest struct {+ AccountID string `json:"accountID" api:"optional"`+}++type ChatGPTLoginRequest struct {+ ID string `json:"id"`+}++type ChatGPTTransferRequest struct {+ AccountID string `json:"accountID" api:"optional"`+ Password string `json:"password"`+ Data string `json:"data" api:"optional"`+}++type ChatGPTAccount struct {+ ID string `json:"id"`+ Email string `json:"email"`+ Name string `json:"name"`+ Connected bool `json:"connected"`+ Sharing bool `json:"sharing"`+}++type ChatGPTLogin struct {+ ID string `json:"id"`+ URL string `json:"url"`+}++type ChatGPTLoginStatus struct {+ State string `json:"state"`+ AccountID string `json:"accountID"`+ Error string `json:"error"`+}++type ChatGPTLogoutResult struct {+ Revoked bool `json:"revoked"`+}diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex 8ec7cc1ce1..bca085ecbb 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -1007,6 +1007,24 @@ var AITestEmbeddingModel = define[EmptyRequest, AIEmbeddingTestData]("testEmbeddvar AITestRerankModel = define[EmptyRequest, AIRerankTestData]("testRerankModel", "/api/ai/testRerankModel", NoBody, ResponseOptions{}, "POST")var AITestDecisionModel = define[EmptyRequest, AIDecisionTestData]("testDecisionModel", "/api/ai/testDecisionModel", NoBody, ResponseOptions{}, "POST")var AIListModels = define[AIProviderRequest, AIModelsData]("listModels", "/api/ai/listModels", JSONBody, ResponseOptions{}, "POST")++// 套餐授权接口仅供已鉴权管理员使用,遵守 AI 禁用开关及只读限制。+// 账户列表只返回身份及连接状态;令牌保存在主机私有目录,配置仅保存账户 ID。+var ChatGPTAccounts = define[EmptyRequest, []ChatGPTAccount]("chatGPTAccounts", "/api/ai/chatgpt/accounts", NoBody, ResponseOptions{NonNullable: true}, "POST")++// 登录地址可能包含身份提示,客户端不得记录;回调使用独立的 IPv4 回环监听器。+var ChatGPTStart = define[ChatGPTAccountRequest, ChatGPTLogin]("chatGPTStart", "/api/ai/chatgpt/start", JSONBody, ResponseOptions{}, "POST")+var ChatGPTStatus = define[ChatGPTLoginRequest, ChatGPTLoginStatus]("chatGPTStatus", "/api/ai/chatgpt/status", JSONBody, ResponseOptions{}, "POST")+var ChatGPTCancel = define[ChatGPTLoginRequest, Null]("chatGPTCancel", "/api/ai/chatgpt/cancel", JSONBody, ResponseOptions{}, "POST")++// 退出清除本地令牌并保留账户映射;revoked 表示远程撤销是否确认成功。+var ChatGPTLogout = define[ChatGPTAccountRequest, ChatGPTLogoutResult]("chatGPTLogout", "/api/ai/chatgpt/logout", JSONBody, ResponseOptions{}, "POST")++// 导出使用至少 12 个字符的密码,先写入带版本的认证加密文件,再停止源主机刷新。+var ChatGPTExport = define[ChatGPTTransferRequest, ExportFileData]("chatGPTExport", "/api/ai/chatgpt/export", JSONBody, ResponseOptions{}, "POST")++// 导入限制为 1 MiB,认证文件和账户身份后续期;失败保留账户及目标主机标识。+var ChatGPTImport = define[ChatGPTTransferRequest, ChatGPTAccount]("chatGPTImport", "/api/ai/chatgpt/import", JSONBody, ResponseOptions{}, "POST")var AIGetEmbeddingStat = define[EmptyRequest, *AIEmbeddingStat]("embeddingStat", "/api/ai/embeddingStat", NoBody, ResponseOptions{}, "POST")var AIGetMCPStatus = define[EmptyRequest, []AIMCPStatus]("mcpStatus", "/api/ai/mcpStatus", NoBody, ResponseOptions{}, "POST")var AIGetMCPEnvironment = define[EmptyRequest, AIMCPEnvironmentData]("mcpEnvironmentVariables", "/api/ai/mcpEnvironmentVariables", NoBody, ResponseOptions{}, "POST")diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex 5263e5c14e..ee27ec8784 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -1435,6 +1435,12 @@}]},+ "displayNames": {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ },"models": {"anyOf": [{@@ -19802,6 +19808,121 @@],"additionalProperties": false},+ "ChatGPTAccount": {+ "type": "object",+ "properties": {+ "connected": {+ "type": "boolean"+ },+ "email": {+ "type": "string"+ },+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "sharing": {+ "type": "boolean"+ }+ },+ "required": [+ "connected",+ "email",+ "id",+ "name",+ "sharing"+ ],+ "additionalProperties": false+ },+ "ChatGPTAccountRequestInput": {+ "type": "object",+ "properties": {+ "accountID": {+ "type": "string"+ }+ },+ "additionalProperties": false+ },+ "ChatGPTLogin": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "url": {+ "type": "string"+ }+ },+ "required": [+ "id",+ "url"+ ],+ "additionalProperties": false+ },+ "ChatGPTLoginRequestInput": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ],+ "additionalProperties": false+ },+ "ChatGPTLoginStatus": {+ "type": "object",+ "properties": {+ "accountID": {+ "type": "string"+ },+ "error": {+ "type": "string"+ },+ "state": {+ "type": "string"+ }+ },+ "required": [+ "accountID",+ "error",+ "state"+ ],+ "additionalProperties": false+ },+ "ChatGPTLogoutResult": {+ "type": "object",+ "properties": {+ "revoked": {+ "type": "boolean"+ }+ },+ "required": [+ "revoked"+ ],+ "additionalProperties": false+ },+ "ChatGPTTransferRequestInput": {+ "type": "object",+ "properties": {+ "accountID": {+ "type": "string"+ },+ "data": {+ "type": "string"+ },+ "password": {+ "type": "string"+ }+ },+ "required": [+ "password"+ ],+ "additionalProperties": false+ },"CheckActivationCodeRequestInput": {"type": "object","properties": {@@ -46365,9 +46486,15 @@"SettingProvider": {"type": "object","properties": {+ "accountID": {+ "type": "string"+ },"apiKey": {"type": "string"},+ "authType": {+ "type": "string"+ },"baseURL": {"type": "string"},@@ -46426,6 +46553,16 @@"SettingProviderInput": {"type": "object","properties": {+ "accountID": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },"apiKey": {"anyOf": [{@@ -46436,6 +46573,16 @@}]},+ "authType": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },"baseURL": {"anyOf": [{@@ -118170,11 +118317,393 @@},{"method": "POST",- "path": "/api/ai/agent/manageSkills",- "handler": "manageSkills",- "body": "json",+ "path": "/api/ai/agent/manageSkills",+ "handler": "manageSkills",+ "body": "json",+ "request": {+ "$ref": "#/$defs/AISkillFileRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/AISkillFileData"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/ai/agent/question",+ "handler": "agentChatQuestion",+ "body": "structJSON",+ "request": {+ "$ref": "#/$defs/AIQuestionRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "null"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ },+ "additionalErrorStatuses": [+ 409+ ]+ },+ {+ "method": "POST",+ "path": "/api/ai/agent/removeSession",+ "handler": "removeSession",+ "body": "structJSON",+ "request": {+ "$ref": "#/$defs/AISessionIDRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "null"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ },+ "additionalErrorStatuses": [+ 409,+ 500+ ]+ },+ {+ "method": "POST",+ "path": "/api/ai/agent/removeSkill",+ "handler": "removeSkill",+ "body": "structJSON",+ "request": {+ "$ref": "#/$defs/AISkillNameRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "null"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/ai/agent/renameSkill",+ "handler": "renameSkill",+ "body": "structJSON",+ "request": {+ "$ref": "#/$defs/AISkillRenameRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "null"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/ai/agent/saveSession",+ "handler": "saveSession",+ "body": "structJSON","request": {- "$ref": "#/$defs/AISkillFileRequestInput"+ "$ref": "#/$defs/AISessionExtensionAISessionFieldsInput"},"response": {"anyOf": [@@ -118188,7 +118717,7 @@]},"data": {- "$ref": "#/$defs/AISkillFileData"+ "$ref": "#/$defs/AISessionSaveData"},"msg": {"type": "string"@@ -118226,6 +118755,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/AISessionSaveData"}]},@@ -118241,15 +118773,20 @@"additionalProperties": true}]- }+ },+ "additionalErrorStatuses": [+ 400,+ 409,+ 500+ ]},{"method": "POST",- "path": "/api/ai/agent/question",- "handler": "agentChatQuestion",+ "path": "/api/ai/agent/saveSkill",+ "handler": "saveSkill","body": "structJSON","request": {- "$ref": "#/$defs/AIQuestionRequestInput"+ "$ref": "#/$defs/AISkillSaveRequestInput"},"response": {"anyOf": [@@ -118316,18 +118853,15 @@"additionalProperties": true}]- },- "additionalErrorStatuses": [- 409- ]+ }},{"method": "POST",- "path": "/api/ai/agent/removeSession",- "handler": "removeSession",- "body": "structJSON",+ "path": "/api/ai/agent/setInstructions",+ "handler": "setAgentInstructions",+ "body": "json","request": {- "$ref": "#/$defs/AISessionIDRequestInput"+ "$ref": "#/$defs/AIAgentInstructionsSaveRequestInput"},"response": {"anyOf": [@@ -118341,7 +118875,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/AIAgentInstructionsData"},"msg": {"type": "string"@@ -118394,19 +118928,15 @@"additionalProperties": true}]- },- "additionalErrorStatuses": [- 409,- 500- ]+ }},{"method": "POST",- "path": "/api/ai/agent/removeSkill",- "handler": "removeSkill",+ "path": "/api/ai/agent/setPermission",+ "handler": "setAgentSessionPermission","body": "structJSON","request": {- "$ref": "#/$defs/AISkillNameRequestInput"+ "$ref": "#/$defs/AIPermissionRequestInput"},"response": {"anyOf": [@@ -118420,7 +118950,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/AIPermissionData"},"msg": {"type": "string"@@ -118477,11 +119007,11 @@},{"method": "POST",- "path": "/api/ai/agent/renameSkill",- "handler": "renameSkill",+ "path": "/api/ai/agent/title",+ "handler": "agentChatTitle","body": "structJSON","request": {- "$ref": "#/$defs/AISkillRenameRequestInput"+ "$ref": "#/$defs/AITitleRequestInput"},"response": {"anyOf": [@@ -118495,7 +119025,7 @@]},"data": {- "type": "null"+ "type": "string"},"msg": {"type": "string"@@ -118552,11 +119082,11 @@},{"method": "POST",- "path": "/api/ai/agent/saveSession",- "handler": "saveSession",- "body": "structJSON",+ "path": "/api/ai/chatGPT",+ "handler": "chatGPT",+ "body": "json","request": {- "$ref": "#/$defs/AISessionExtensionAISessionFieldsInput"+ "$ref": "#/$defs/AIMessageRequestInput"},"response": {"anyOf": [@@ -118570,7 +119100,7 @@]},"data": {- "$ref": "#/$defs/AISessionSaveData"+ "type": "string"},"msg": {"type": "string"@@ -118608,9 +119138,81 @@},{"type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/ai/chatGPTWithAction",+ "handler": "chatGPTWithAction",+ "body": "json",+ "request": {+ "$ref": "#/$defs/AIActionRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "string"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false},{- "$ref": "#/$defs/AISessionSaveData"+ "type": "null"}]},@@ -118626,20 +119228,93 @@"additionalProperties": true}]+ }+ },+ {+ "method": "POST",+ "path": "/api/ai/chatgpt/accounts",+ "handler": "chatGPTAccounts",+ "body": "none",+ "request": {+ "$ref": "#/$defs/EmptyRequestInput"},- "additionalErrorStatuses": [- 400,- 409,- 500- ]+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/ChatGPTAccount"+ }+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }},{"method": "POST",- "path": "/api/ai/agent/saveSkill",- "handler": "saveSkill",- "body": "structJSON",+ "path": "/api/ai/chatgpt/cancel",+ "handler": "chatGPTCancel",+ "body": "json","request": {- "$ref": "#/$defs/AISkillSaveRequestInput"+ "$ref": "#/$defs/ChatGPTLoginRequestInput"},"response": {"anyOf": [@@ -118710,11 +119385,11 @@},{"method": "POST",- "path": "/api/ai/agent/setInstructions",- "handler": "setAgentInstructions",+ "path": "/api/ai/chatgpt/export",+ "handler": "chatGPTExport","body": "json","request": {- "$ref": "#/$defs/AIAgentInstructionsSaveRequestInput"+ "$ref": "#/$defs/ChatGPTTransferRequestInput"},"response": {"anyOf": [@@ -118728,7 +119403,7 @@]},"data": {- "$ref": "#/$defs/AIAgentInstructionsData"+ "$ref": "#/$defs/ExportFileData"},"msg": {"type": "string"@@ -118785,11 +119460,11 @@},{"method": "POST",- "path": "/api/ai/agent/setPermission",- "handler": "setAgentSessionPermission",- "body": "structJSON",+ "path": "/api/ai/chatgpt/import",+ "handler": "chatGPTImport",+ "body": "json","request": {- "$ref": "#/$defs/AIPermissionRequestInput"+ "$ref": "#/$defs/ChatGPTTransferRequestInput"},"response": {"anyOf": [@@ -118803,7 +119478,7 @@]},"data": {- "$ref": "#/$defs/AIPermissionData"+ "$ref": "#/$defs/ChatGPTAccount"},"msg": {"type": "string"@@ -118860,11 +119535,11 @@},{"method": "POST",- "path": "/api/ai/agent/title",- "handler": "agentChatTitle",- "body": "structJSON",+ "path": "/api/ai/chatgpt/logout",+ "handler": "chatGPTLogout",+ "body": "json","request": {- "$ref": "#/$defs/AITitleRequestInput"+ "$ref": "#/$defs/ChatGPTAccountRequestInput"},"response": {"anyOf": [@@ -118878,7 +119553,7 @@]},"data": {- "type": "string"+ "$ref": "#/$defs/ChatGPTLogoutResult"},"msg": {"type": "string"@@ -118935,11 +119610,11 @@},{"method": "POST",- "path": "/api/ai/chatGPT",- "handler": "chatGPT",+ "path": "/api/ai/chatgpt/start",+ "handler": "chatGPTStart","body": "json","request": {- "$ref": "#/$defs/AIMessageRequestInput"+ "$ref": "#/$defs/ChatGPTAccountRequestInput"},"response": {"anyOf": [@@ -118953,7 +119628,7 @@]},"data": {- "type": "string"+ "$ref": "#/$defs/ChatGPTLogin"},"msg": {"type": "string"@@ -119010,11 +119685,11 @@},{"method": "POST",- "path": "/api/ai/chatGPTWithAction",- "handler": "chatGPTWithAction",+ "path": "/api/ai/chatgpt/status",+ "handler": "chatGPTStatus","body": "json","request": {- "$ref": "#/$defs/AIActionRequestInput"+ "$ref": "#/$defs/ChatGPTLoginRequestInput"},"response": {"anyOf": [@@ -119028,7 +119703,7 @@]},"data": {- "type": "string"+ "$ref": "#/$defs/ChatGPTLoginStatus"},"msg": {"type": "string"diff --git a/kernel/apicontract/setting.go b/kernel/apicontract/setting.goindex c180267f85..c043120866 100644--- a/kernel/apicontract/setting.go+++ b/kernel/apicontract/setting.go@@ -120,6 +120,9 @@ type SettingImageGeneration struct {}type SettingProvider struct {+ // 套餐认证固定使用公开 Responses API;账户引用不包含令牌,省略时保留 API Key 认证。+ AuthType string `json:"authType,omitempty" api:"optional,nullable"`+ AccountID string `json:"accountID,omitempty" api:"optional,nullable"`Headers map[string]string `json:"headers,omitempty" api:"optional,nullable"`ID string `json:"id" api:"optional,nullable"`DisplayName string `json:"displayName,omitempty" api:"optional,nullable"`diff --git a/kernel/chatgpt/inference.go b/kernel/chatgpt/inference.gonew file mode 100644index 0000000000..e63f2cf3ca--- /dev/null+++ b/kernel/chatgpt/inference.go@@ -0,0 +1,143 @@+package chatgpt++import (+ "context"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "sync"+)++type activeRequest struct{ cancel context.CancelFunc }+type accountResponseBody struct {+ io.ReadCloser+ once sync.Once+ release func()+}++func (b *accountResponseBody) Close() error {+ err := b.ReadCloser.Close()+ b.once.Do(b.release)+ return err+}++func (s *Service) stopRequests(id string) {+ s.mu.Lock()+ defer s.mu.Unlock()+ s.blocked[id] = true+ for request := range s.requests[id] {+ request.cancel()+ }+}++func (s *Service) resumeRequests(id string) { s.mu.Lock(); delete(s.blocked, id); s.mu.Unlock() }++// Do 只向公开套餐接口发送凭证,鉴权失败最多刷新一次,额度错误不切换计费方式。+func (s *Service) Do(request *http.Request, accountID string) (*http.Response, error) {+ endpoint := request.URL.String()+ if (request.Method != "POST" || endpoint != s.resource+"/responses") &&+ (request.Method != "GET" || endpoint != s.resource+"/models") {+ return nil, errors.New("unsupported ChatGPT plan route")+ }+ ctx, cancel := context.WithCancel(request.Context())+ active := &activeRequest{cancel: cancel}+ s.mu.Lock()+ if s.blocked[accountID] {+ s.mu.Unlock()+ cancel()+ return nil, errors.New("sign in to ChatGPT again")+ }+ if s.requests[accountID] == nil {+ s.requests[accountID] = map[*activeRequest]bool{}+ }+ s.requests[accountID][active] = true+ s.mu.Unlock()+ release := func() {+ cancel()+ s.mu.Lock()+ delete(s.requests[accountID], active)+ s.mu.Unlock()+ }+ returned := false+ defer func() {+ if !returned {+ release()+ }+ }()+ for attempt := 0; attempt < 2; attempt++ {+ token, err := s.Token(ctx, accountID, attempt != 0)+ if err != nil {+ return nil, err+ }+ clone := request.Clone(ctx)+ clone.Header.Set("Authorization", "Bearer "+token)+ if attempt > 0 && request.Body != nil {+ if request.GetBody == nil {+ return nil, errors.New("ChatGPT request cannot be replayed after token renewal")+ }+ clone.Body, err = request.GetBody()+ if err != nil {+ return nil, err+ }+ }+ response, err := s.http.Do(clone)+ if err != nil {+ if ctx.Err() != nil {+ return nil, ctx.Err()+ }+ return nil, errors.New("ChatGPT connection failed")+ }+ if response.StatusCode != 401 || attempt != 0 {+ response.Body = &accountResponseBody{ReadCloser: response.Body, release: release}+ returned = true+ return response, nil+ }+ response.Body.Close()+ }+ return nil, errors.New("sign in to ChatGPT again")+}++type Model struct {+ ID string+ DisplayName string+}++func (s *Service) Models(ctx context.Context, id string) ([]Model, error) {+ req, err := http.NewRequestWithContext(ctx, "GET", s.resource+"/models", nil)+ if err != nil {+ return nil, err+ }+ response, err := s.Do(req, id)+ if err != nil {+ return nil, err+ }+ defer response.Body.Close()+ data, err := io.ReadAll(io.LimitReader(response.Body, 4*1024*1024+1))+ if err != nil || len(data) > 4*1024*1024 {+ return nil, errors.New("invalid ChatGPT model catalog")+ }+ if response.StatusCode < 200 || response.StatusCode >= 300 {+ return nil, responseError(response, data)+ }+ var payload struct {+ Models []struct {+ Slug string `json:"slug"`+ DisplayName string `json:"display_name"`+ Visibility string `json:"visibility"`+ } `json:"models"`+ }+ if err = json.Unmarshal(data, &payload); err != nil || payload.Models == nil {+ return nil, errors.New("invalid ChatGPT model catalog")+ }+ models := []Model{}+ seen := map[string]bool{}+ for _, m := range payload.Models {+ if m.Visibility != "list" || m.Slug == "" || seen[m.Slug] {+ continue+ }+ seen[m.Slug] = true+ models = append(models, Model{ID: m.Slug, DisplayName: m.DisplayName})+ }+ return models, nil+}diff --git a/kernel/chatgpt/oauth.go b/kernel/chatgpt/oauth.gonew file mode 100644index 0000000000..8dd488939f--- /dev/null+++ b/kernel/chatgpt/oauth.go@@ -0,0 +1,482 @@+package chatgpt++import (+ "context"+ "crypto/sha256"+ "crypto/subtle"+ "encoding/base64"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net"+ "net/http"+ "net/url"+ "strings"+ "time"++ "github.com/go-jose/go-jose/v4"+ josejwt "github.com/go-jose/go-jose/v4/jwt"+)++type Login struct {+ ID string `json:"id"`+ URL string `json:"url"`+}++type LoginStatus struct {+ State string `json:"state"`+ AccountID string `json:"accountID"`+ Error string `json:"error"`+}++type attempt struct {+ state, nonce, verifier, redirect string+ account *Account+ status LoginStatus+ consumed bool+ server *http.Server+ cancel context.CancelFunc+}++type tokenResponse struct {+ AccessToken string `json:"access_token"`+ RefreshToken string `json:"refresh_token"`+ IDToken string `json:"id_token"`+ TokenType string `json:"token_type"`+ Scope *string `json:"scope"`+ ExpiresIn int64 `json:"expires_in"`+}++type identity struct {+ josejwt.Claims+ Email string `json:"email"`+ Name string `json:"name"`+ Nonce string `json:"nonce"`+}++type discovery struct {+ Issuer string `json:"issuer"`+ JWKS string `json:"jwks_uri"`+ Revocation string `json:"revocation_endpoint"`+}++type RequestError struct {+ Status int+ Code, Message, RequestID string+}++func (e *RequestError) Error() string {+ return fmt.Sprintf("ChatGPT HTTP %d: %s (%s) [%s]", e.Status, e.Message, e.Code, e.RequestID)+}++func newHTTPClient() *http.Client {+ return &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}+}++func (s *Service) readJSON(ctx context.Context, method, endpoint, body string, result any) error {+ requestCtx, cancel := context.WithTimeout(ctx, 30*time.Second)+ defer cancel()+ req, err := http.NewRequestWithContext(requestCtx, method, endpoint, strings.NewReader(body))+ if err != nil {+ return err+ }+ if body != "" {+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")+ }+ response, err := s.http.Do(req)+ if err != nil {+ if requestCtx.Err() != nil {+ return requestCtx.Err()+ }+ return errors.New("ChatGPT connection failed")+ }+ defer response.Body.Close()+ data, err := io.ReadAll(io.LimitReader(response.Body, 1024*1024+1))+ if err != nil || len(data) > 1024*1024 {+ return errors.New("invalid ChatGPT response")+ }+ if response.StatusCode < 200 || response.StatusCode >= 300 {+ return responseError(response, data)+ }+ if result == nil {+ return nil+ }+ return json.Unmarshal(data, result)+}++func responseError(response *http.Response, data []byte) error {+ var body struct {+ Error json.RawMessage `json:"error"`+ Description string `json:"error_description"`+ Detail string `json:"detail"`+ }+ _ = json.Unmarshal(data, &body)+ var code string+ var structured struct {+ Code string `json:"code"`+ Message string `json:"message"`+ }+ if json.Unmarshal(body.Error, &code) != nil {+ _ = json.Unmarshal(body.Error, &structured)+ code = structured.Code+ }+ message := structured.Message+ if message == "" {+ message = body.Description+ }+ if message == "" {+ message = body.Detail+ }+ return &RequestError{Status: response.StatusCode, Code: code, Message: message, RequestID: response.Header.Get("X-Request-ID")}+}++func (s *Service) metadata(ctx context.Context) (d discovery, err error) {+ err = s.readJSON(ctx, "GET", s.issuer+"/.well-known/openid-configuration", "", &d)+ if err == nil && (d.Issuer != s.issuer || !s.identityEndpoint(d.JWKS)) {+ err = errors.New("invalid ChatGPT issuer metadata")+ }+ return+}++func (s *Service) identityEndpoint(endpoint string) bool {+ u, err := url.Parse(endpoint)+ issuer, _ := url.Parse(s.issuer)+ return err == nil && u.Scheme == issuer.Scheme && u.Host == issuer.Host && u.User == nil && u.Fragment == ""+}++func (s *Service) verifyIdentity(ctx context.Context, token, clientID, nonce string, retained bool) (claims identity, err error) {+ d, err := s.metadata(ctx)+ if err != nil {+ return+ }+ var keys jose.JSONWebKeySet+ if err = s.readJSON(ctx, "GET", d.JWKS, "", &keys); err != nil {+ return+ }+ signed, err := josejwt.ParseSigned(token, []jose.SignatureAlgorithm{jose.RS256})+ if err != nil {+ return+ }+ if err = signed.Claims(&keys, &claims); err != nil {+ return+ }+ if claims.Issuer != s.issuer || !claims.Audience.Contains(clientID) || claims.Subject == "" || claims.Expiry == nil || claims.IssuedAt == nil {+ return claims, errors.New("invalid ChatGPT account identity")+ }+ if !retained {+ if err = claims.ValidateWithLeeway(josejwt.Expected{Issuer: s.issuer, Time: time.Now()}, time.Minute); err != nil {+ return+ }+ }+ if nonce != "" && subtle.ConstantTimeCompare([]byte(claims.Nonce), []byte(nonce)) != 1 {+ return claims, errors.New("ChatGPT authorization nonce mismatch")+ }+ return+}++func (s *Service) Start(ctx context.Context, accountID string, messages ...string) (login Login, err error) {+ var hostID string+ var selected *Account+ err = s.withStore(ctx, func(store *diskStore) error {+ hostID = store.HostID+ if accountID != "" {+ a, err := findAccount(store, accountID)+ if err != nil {+ return err+ }+ copy := *a+ selected = ©+ }+ return nil+ })+ if err != nil {+ return+ }+ listener, err := net.Listen("tcp4", "127.0.0.1:0")+ if err != nil {+ return login, errors.New("unable to start ChatGPT loopback callback")+ }+ authCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)+ a := &attempt{state: randomText(32), nonce: randomText(32), verifier: randomText(32), account: selected,+ redirect: "http://" + listener.Addr().String() + "/auth/callback", status: LoginStatus{State: "pending"}, cancel: cancel}+ login.ID = randomText(32)+ challenge := sha256.Sum256([]byte(a.verifier))+ q := url.Values{"client_id": {"dynamic_agent_client"}, "agent_name_hint": {"SiYuan"}, "ext_agent_host_id": {hostID},+ "response_type": {"code"}, "redirect_uri": {a.redirect}, "scope": {"openid profile email offline_access resource.invoke " + permission},+ "resource": {s.resource}, "state": {a.state}, "nonce": {a.nonce}, "code_challenge_method": {"S256"},+ "code_challenge": {base64.RawURLEncoding.EncodeToString(challenge[:])}}+ if selected != nil {+ q.Set("client_id", selected.ClientID)+ q.Del("agent_name_hint")+ if selected.IDToken != "" {+ q.Set("id_token_hint", selected.IDToken)+ }+ if selected.Email != "" {+ q.Set("login_hint", selected.Email)+ }+ if !profile(selected).Sharing {+ q.Set("prompt", "consent")+ }+ }+ login.URL = s.issuer + "/api/accounts/authorize?" + q.Encode()+ a.server = &http.Server{ReadHeaderTimeout: 5 * time.Second, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Cache-Control", "no-store")+ w.Header().Set("Referrer-Policy", "no-referrer")+ if r.Method != "GET" || r.URL.Path != "/auth/callback" {+ w.WriteHeader(404)+ return+ }+ values := r.URL.Query()+ for _, key := range []string{"state", "code", "client_id", "error"} {+ if len(values[key]) > 1 {+ w.WriteHeader(400)+ return+ }+ }+ if subtle.ConstantTimeCompare([]byte(values.Get("state")), []byte(a.state)) != 1 {+ w.WriteHeader(400)+ return+ }+ s.mu.Lock()+ if a.consumed || a.status.State != "pending" {+ s.mu.Unlock()+ w.WriteHeader(409)+ return+ }+ a.consumed = true+ s.mu.Unlock()+ result, completeErr := s.complete(authCtx, a, values)+ s.mu.Lock()+ if completeErr != nil {+ a.status = LoginStatus{State: "failed", Error: completeErr.Error()}+ } else {+ a.status = LoginStatus{State: "completed", AccountID: result.ClientID}+ }+ s.mu.Unlock()+ w.Header().Set("Content-Type", "text/plain; charset=utf-8")+ message := "SiYuan"+ if len(messages) > 0 {+ message = messages[0]+ }+ _, _ = w.Write([]byte(message))+ cancel()+ })}+ s.mu.Lock()+ pending := 0+ for _, old := range s.attempts {+ if old.status.State == "pending" {+ pending+++ }+ }+ if pending >= 8 {+ s.mu.Unlock()+ listener.Close()+ cancel()+ return login, errors.New("too many pending ChatGPT sign-ins")+ }+ s.attempts[login.ID] = a+ s.mu.Unlock()+ go a.server.Serve(listener)+ go func() {+ <-authCtx.Done()+ shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), time.Second)+ defer shutdownCancel()+ _ = a.server.Shutdown(shutdownCtx)+ s.mu.Lock()+ if a.status.State == "pending" {+ a.status = LoginStatus{State: "failed", Error: "ChatGPT sign-in expired or was cancelled"}+ }+ s.mu.Unlock()+ time.AfterFunc(10*time.Minute, func() { s.mu.Lock(); delete(s.attempts, login.ID); s.mu.Unlock() })+ }()+ return+}++func (s *Service) Status(id string) (LoginStatus, error) {+ s.mu.Lock()+ defer s.mu.Unlock()+ if a := s.attempts[id]; a != nil {+ return a.status, nil+ }+ return LoginStatus{}, errors.New("ChatGPT sign-in attempt not found")+}++func (s *Service) Cancel(id string) {+ s.mu.Lock()+ defer s.mu.Unlock()+ if a := s.attempts[id]; a != nil {+ a.cancel()+ }+}++func (s *Service) complete(ctx context.Context, a *attempt, values url.Values) (*Account, error) {+ if values.Get("error") != "" {+ return nil, errors.New("ChatGPT authorization was declined")+ }+ clientID := values.Get("client_id")+ if a.account != nil {+ if clientID != "" && clientID != a.account.ClientID {+ return nil, errors.New("ChatGPT registration mismatch")+ }+ clientID = a.account.ClientID+ }+ if clientID == "" || clientID == "dynamic_agent_client" || values.Get("code") == "" {+ return nil, errors.New("invalid ChatGPT registration callback")+ }+ // 签发的注册 ID 在换码失败后仍可复用,未校验的账户不会成为已连接账户。+ if err := s.withStore(ctx, func(store *diskStore) error {+ if _, err := findAccount(store, clientID); err != nil {+ store.Accounts = append(store.Accounts, &Account{ClientID: clientID})+ }+ return nil+ }); err != nil {+ return nil, err+ }+ form := url.Values{"grant_type": {"authorization_code"}, "client_id": {clientID}, "code": {values.Get("code")},+ "code_verifier": {a.verifier}, "redirect_uri": {a.redirect}, "resource": {s.resource}}+ var tokens tokenResponse+ if err := s.readJSON(ctx, "POST", s.issuer+"/api/accounts/oauth/token", form.Encode(), &tokens); err != nil {+ return nil, err+ }+ claims, err := s.verifyIdentity(ctx, tokens.IDToken, clientID, a.nonce, false)+ if err != nil {+ return nil, errors.New("ChatGPT ID token validation failed")+ }+ if a.account != nil && a.account.Subject != "" && a.account.Subject != claims.Subject {+ return nil, errors.New("ChatGPT account identity mismatch")+ }+ result := &Account{ClientID: clientID, Subject: claims.Subject, Email: claims.Email, Name: claims.Name}+ if err = applyTokens(result, tokens); err != nil {+ return nil, err+ }+ err = s.withStore(ctx, func(store *diskStore) error {+ old, err := findAccount(store, clientID)+ if err != nil {+ return err+ }+ if old.Subject != "" && old.Subject != result.Subject {+ return errors.New("ChatGPT account identity mismatch")+ }+ *old = *result+ return nil+ })+ if err == nil {+ s.resumeRequests(clientID)+ }+ return result, err+}++func applyTokens(a *Account, tokens tokenResponse) error {+ if tokens.AccessToken == "" || !strings.EqualFold(tokens.TokenType, "Bearer") || tokens.ExpiresIn <= 0 || tokens.ExpiresIn > 86400 {+ return errors.New("invalid ChatGPT token response")+ }+ a.AccessToken = tokens.AccessToken+ if tokens.RefreshToken != "" {+ a.RefreshToken = tokens.RefreshToken+ }+ if tokens.IDToken != "" {+ a.IDToken = tokens.IDToken+ }+ if tokens.Scope != nil {+ a.Scopes = strings.Fields(*tokens.Scope)+ }+ a.ExpiresAt = time.Now().Add(time.Duration(tokens.ExpiresIn) * time.Second).Unix()+ return nil+}++func (s *Service) refresh(ctx context.Context, a *Account) error {+ if a.RefreshToken == "" {+ return errors.New("sign in to ChatGPT again")+ }+ var tokens tokenResponse+ form := url.Values{"grant_type": {"refresh_token"}, "client_id": {a.ClientID}, "refresh_token": {a.RefreshToken}, "resource": {s.resource}}+ if err := s.readJSON(ctx, "POST", s.issuer+"/api/accounts/oauth/token", form.Encode(), &tokens); err != nil {+ var requestErr *RequestError+ if errors.As(err, &requestErr) {+ switch requestErr.Code {+ case "invalid_grant", "invalid_refresh_token", "token_expired", "refresh_token_expired", "refresh_token_invalidated", "refresh_token_reused":+ clearTokens(a)+ }+ }+ return err+ }+ if tokens.IDToken != "" {+ claims, err := s.verifyIdentity(ctx, tokens.IDToken, a.ClientID, "", false)+ if err != nil || claims.Subject != a.Subject {+ return errors.New("ChatGPT account identity mismatch")+ }+ }+ return applyTokens(a, tokens)+}++func (s *Service) Token(ctx context.Context, id string, force bool) (token string, err error) {+ var requestErr error+ err = s.withStore(ctx, func(store *diskStore) error {+ a, err := findAccount(store, id)+ if err != nil {+ return err+ }+ if a.AccessToken == "" {+ return errors.New("sign in to ChatGPT again")+ }+ if !profile(a).Sharing {+ requestErr = errors.New("ChatGPT plan usage was not authorized")+ return nil+ }+ if force || a.ExpiresAt <= time.Now().Add(time.Minute).Unix() {+ requestErr = s.refresh(ctx, a)+ }+ if requestErr != nil {+ return nil+ }+ if !profile(a).Sharing {+ requestErr = errors.New("ChatGPT plan usage was not authorized")+ return nil+ }+ token = a.AccessToken+ return nil+ })+ if err == nil {+ err = requestErr+ }+ return+}++func (s *Service) Logout(ctx context.Context, id string) (revoked bool, err error) {+ s.stopRequests(id)+ err = s.withStore(ctx, func(store *diskStore) error {+ a, err := findAccount(store, id)+ if err != nil {+ return err+ }+ if a.RefreshToken == "" {+ revoked = true+ } else {+ d, metadataErr := s.metadata(ctx)+ if metadataErr == nil && s.identityEndpoint(d.Revocation) {+ form := url.Values{"token": {a.RefreshToken}, "token_type_hint": {"refresh_token"}, "client_id": {a.ClientID}}+ for i := 0; i < 2; i++ {+ if s.readJSON(ctx, "POST", d.Revocation, form.Encode(), nil) == nil {+ revoked = true+ break+ }+ if ctx.Err() != nil {+ break+ }+ if i == 0 {+ timer := time.NewTimer(250 * time.Millisecond)+ select {+ case <-timer.C:+ case <-ctx.Done():+ timer.Stop()+ }+ }+ }+ }+ }+ clearTokens(a)+ return nil+ })+ return+}diff --git a/kernel/chatgpt/oauth_test.go b/kernel/chatgpt/oauth_test.gonew file mode 100644index 0000000000..154db6f6d3--- /dev/null+++ b/kernel/chatgpt/oauth_test.go@@ -0,0 +1,341 @@+package chatgpt++import (+ "context"+ "crypto/rand"+ "crypto/rsa"+ "crypto/sha256"+ "encoding/base64"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "net/http/httptest"+ "net/url"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/go-jose/go-jose/v4"+ josejwt "github.com/go-jose/go-jose/v4/jwt"+)++type fixture struct {+ service *Service+ server *httptest.Server+ nonce, challenge, subject, refreshError string+ refreshes atomic.Int32+}++func newFixture(t *testing.T) *fixture {+ t.Helper()+ f := &fixture{subject: "user-1"}+ key, err := rsa.GenerateKey(rand.Reader, 2048)+ if err != nil {+ t.Fatal(err)+ }+ signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: key}, (&jose.SignerOptions{}).WithHeader("kid", "test-key"))+ if err != nil {+ t.Fatal(err)+ }+ f.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ switch r.URL.Path {+ case "/.well-known/openid-configuration":+ json.NewEncoder(w).Encode(discovery{Issuer: f.server.URL, JWKS: f.server.URL + "/jwks", Revocation: f.server.URL + "/revoke"})+ case "/jwks":+ json.NewEncoder(w).Encode(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{Key: &key.PublicKey, KeyID: "test-key", Algorithm: "RS256", Use: "sig"}}})+ case "/api/accounts/oauth/token":+ r.ParseForm()+ if r.Form.Get("client_id") != "oaiapp_test" || r.Form.Get("resource") != f.server.URL+"/v1" {+ t.Error("wrong token registration or resource")+ }+ if r.Form.Get("grant_type") == "authorization_code" {+ hash := sha256.Sum256([]byte(r.Form.Get("code_verifier")))+ if base64.RawURLEncoding.EncodeToString(hash[:]) != f.challenge {+ t.Error("PKCE verifier mismatch")+ }+ } else {+ f.refreshes.Add(1)+ if f.refreshError != "" {+ w.WriteHeader(400)+ json.NewEncoder(w).Encode(map[string]string{"error": f.refreshError})+ return+ }+ }+ claims := identity{Claims: josejwt.Claims{Issuer: f.server.URL, Subject: f.subject, Audience: josejwt.Audience{"oaiapp_test"},+ Expiry: josejwt.NewNumericDate(time.Now().Add(time.Hour)), IssuedAt: josejwt.NewNumericDate(time.Now())}, Email: "[email protected]", Nonce: f.nonce}+ token, err := josejwt.Signed(signer).Claims(claims).Serialize()+ if err != nil {+ t.Error(err)+ }+ scope := "openid offline_access resource.invoke " + permission+ json.NewEncoder(w).Encode(tokenResponse{AccessToken: "access-secret", RefreshToken: "refresh-secret", IDToken: token, TokenType: "Bearer", Scope: &scope, ExpiresIn: 3600})+ case "/v1/models":+ if r.Header.Get("Authorization") != "Bearer access-secret" {+ t.Error("missing bearer credential")+ }+ io.WriteString(w, `{"models":[{"slug":"model-a","display_name":"Model A","visibility":"list"},{"slug":"hidden","visibility":"hide"},{"slug":"model-b","display_name":"Model B","visibility":"list"}]}`)+ case "/revoke":+ w.WriteHeader(200)+ default:+ w.WriteHeader(404)+ }+ }))+ f.service = Open(t.TempDir())+ f.service.issuer = f.server.URL+ f.service.resource = f.server.URL + "/v1"+ t.Cleanup(f.server.Close)+ return f+}++func (f *fixture) login(t *testing.T, accountID string) Login {+ t.Helper()+ login, err := f.service.Start(context.Background(), accountID)+ if err != nil {+ t.Fatal(err)+ }+ u, _ := url.Parse(login.URL)+ f.nonce, f.challenge = u.Query().Get("nonce"), u.Query().Get("code_challenge")+ if u.Query().Get("ext_agent_host_id") == "" || u.Query().Get("code_challenge_method") != "S256" {+ t.Fatal("missing host or PKCE")+ }+ t.Cleanup(func() { f.service.Cancel(login.ID) })+ return login+}++func (f *fixture) callback(t *testing.T, login Login, state string) int {+ t.Helper()+ u, _ := url.Parse(login.URL)+ q := url.Values{"code": {"code"}, "state": {state}, "client_id": {"oaiapp_test"}}+ response, err := http.Get(u.Query().Get("redirect_uri") + "?" + q.Encode())+ if err != nil {+ t.Fatal(err)+ }+ response.Body.Close()+ return response.StatusCode+}++func TestChatGPTSignInIdentityAndEncryptedStore(t *testing.T) {+ f := newFixture(t)+ login := f.login(t, "")+ u, _ := url.Parse(login.URL)+ if u.Query().Get("client_id") != "dynamic_agent_client" || u.Query().Get("agent_name_hint") != "SiYuan" {+ t.Fatal("wrong dynamic registration")+ }+ if status := f.callback(t, login, "wrong-state"); status != 400 {+ t.Fatalf("wrong-state status = %d", status)+ }+ if status, _ := f.service.Status(login.ID); status.State != "pending" {+ t.Fatal("invalid callback consumed attempt")+ }+ f.callback(t, login, u.Query().Get("state"))+ status, _ := f.service.Status(login.ID)+ if status.State != "completed" || status.AccountID != "oaiapp_test" {+ t.Fatalf("status: %+v", status)+ }+ profiles, err := f.service.Profiles(context.Background())+ if err != nil || len(profiles) != 1 || !profiles[0].Sharing {+ t.Fatalf("profiles: %+v %v", profiles, err)+ }+ data, _ := os.ReadFile(filepath.Join(f.service.dir, "accounts"))+ if strings.Contains(string(data), "secret") || strings.Contains(string(data), "[email protected]") {+ t.Fatal("credentials written in plaintext")+ }+ models, err := f.service.Models(context.Background(), "oaiapp_test")+ if err != nil || len(models) != 2 || models[0].DisplayName != "Model A" {+ t.Fatalf("models: %+v %v", models, err)+ }+ returning := f.login(t, "oaiapp_test")+ u, _ = url.Parse(returning.URL)+ if u.Query().Get("client_id") != "oaiapp_test" || u.Query().Get("agent_name_hint") != "" || u.Query().Get("id_token_hint") == "" {+ t.Fatal("registration not reused")+ }+ f.subject = "different-user"+ f.callback(t, returning, u.Query().Get("state"))+ status, _ = f.service.Status(returning.ID)+ if status.State != "failed" {+ t.Fatal("account mismatch accepted")+ }+ profiles, _ = f.service.Profiles(context.Background())+ if !profiles[0].Connected {+ t.Fatal("failed reauthorization replaced credentials")+ }+}++func TestChatGPTRefreshAcrossServicesAndTerminalFailure(t *testing.T) {+ f := newFixture(t)+ login := f.login(t, "")+ u, _ := url.Parse(login.URL)+ f.callback(t, login, u.Query().Get("state"))+ err := f.service.withStore(context.Background(), func(store *diskStore) error { store.Accounts[0].ExpiresAt = 0; return nil })+ if err != nil {+ t.Fatal(err)+ }+ other := Open(f.service.dir)+ other.issuer, other.resource = f.service.issuer, f.service.resource+ var wg sync.WaitGroup+ for _, s := range []*Service{f.service, other} {+ wg.Go(func() {+ token, err := s.Token(context.Background(), "oaiapp_test", false)+ if err != nil || token == "" {+ t.Errorf("token: %s %v", token, err)+ }+ })+ }+ wg.Wait()+ if f.refreshes.Load() != 1 {+ t.Fatalf("refreshes: %d", f.refreshes.Load())+ }+ f.refreshError = "invalid_grant"+ if _, err = f.service.Token(context.Background(), "oaiapp_test", true); err == nil {+ t.Fatal("terminal refresh accepted")+ }+ profiles, _ := f.service.Profiles(context.Background())+ if profiles[0].Connected {+ t.Fatal("unusable token was retained")+ }+}++func TestChatGPTTransferPreservesHostAndAuthenticatesFile(t *testing.T) {+ f := newFixture(t)+ login := f.login(t, "")+ u, _ := url.Parse(login.URL)+ f.callback(t, login, u.Query().Get("state"))+ if _, err := f.service.Export(context.Background(), "oaiapp_test", "long-password-123", func(string) error { return os.ErrPermission }); err == nil {+ t.Fatal("failed export publication accepted")+ }+ profiles, _ := f.service.Profiles(context.Background())+ if !profiles[0].Connected {+ t.Fatal("failed export removed source session")+ }+ data, err := f.service.Export(context.Background(), "oaiapp_test", "long-password-123", nil)+ if err != nil {+ t.Fatal(err)+ }+ profiles, _ = f.service.Profiles(context.Background())+ if profiles[0].Connected || strings.Contains(data, "secret") {+ t.Fatal("export did not transfer protected session")+ }+ destination := Open(t.TempDir())+ destination.issuer, destination.resource = f.service.issuer, f.service.resource+ var host string+ destination.withStore(context.Background(), func(store *diskStore) error { host = store.HostID; return nil })+ if _, err = destination.Import(context.Background(), data, "wrong-password-123"); err == nil {+ t.Fatal("incorrect password accepted")+ }+ var damaged transfer+ json.Unmarshal([]byte(data), &damaged)+ damaged.Data[len(damaged.Data)-1] ^= 1+ encoded, _ := json.Marshal(damaged)+ if _, err = destination.Import(context.Background(), string(encoded), "long-password-123"); err == nil {+ t.Fatal("damaged transfer accepted")+ }+ result, err := destination.Import(context.Background(), data, "long-password-123")+ if err != nil || !result.Sharing {+ t.Fatalf("import: %+v %v", result, err)+ }+ destination.withStore(context.Background(), func(store *diskStore) error {+ if store.HostID != host {+ t.Error("import replaced host ID")+ }+ return nil+ })+ request, _ := http.NewRequest("GET", "https://untrusted.example/models", nil)+ if _, err = destination.Do(request, "oaiapp_test"); err == nil {+ t.Fatal("credentials sent to an untrusted endpoint")+ }+ revoked, err := destination.Logout(context.Background(), "oaiapp_test")+ if err != nil || !revoked {+ t.Fatalf("logout: %v %v", revoked, err)+ }+ profiles, _ = destination.Profiles(context.Background())+ if profiles[0].Connected {+ t.Fatal("logout retained credentials")+ }+}++func TestChatGPTCorruptionPreservesOriginal(t *testing.T) {+ s := Open(t.TempDir())+ if _, err := s.Profiles(context.Background()); err != nil {+ t.Fatal(err)+ }+ path := filepath.Join(s.dir, "accounts")+ data, _ := os.ReadFile(path)+ data[len(data)-1] ^= 1+ if err := os.WriteFile(path, data, 0600); err != nil {+ t.Fatal(err)+ }+ if _, err := s.Profiles(context.Background()); err == nil {+ t.Fatal("corrupted credentials accepted")+ }+ current, _ := os.ReadFile(path)+ if string(current) != string(data) {+ t.Fatal("corrupted credentials overwritten")+ }+}++func TestChatGPTRejectedNoncePreservesRegistration(t *testing.T) {+ f := newFixture(t)+ login := f.login(t, "")+ u, _ := url.Parse(login.URL)+ f.nonce = "invalid-nonce"+ f.callback(t, login, u.Query().Get("state"))+ status, _ := f.service.Status(login.ID)+ if status.State != "failed" {+ t.Fatal("wrong nonce accepted")+ }+ profiles, _ := f.service.Profiles(context.Background())+ if len(profiles) != 1 || profiles[0].Connected || profiles[0].ID != "oaiapp_test" {+ t.Fatal("registration or credentials changed")+ }+}++type blockingHTTP struct {+ base HTTPClient+ started chan struct{}+}++func (h *blockingHTTP) Do(r *http.Request) (*http.Response, error) {+ if strings.HasSuffix(r.URL.Path, "/responses") {+ close(h.started)+ <-r.Context().Done()+ return nil, r.Context().Err()+ }+ return h.base.Do(r)+}++func TestChatGPTLogoutCancelsActiveRequest(t *testing.T) {+ f := newFixture(t)+ login := f.login(t, "")+ u, _ := url.Parse(login.URL)+ f.callback(t, login, u.Query().Get("state"))+ client := &blockingHTTP{base: f.service.http, started: make(chan struct{})}+ f.service.http = client+ done := make(chan error, 1)+ go func() {+ r, _ := http.NewRequest("POST", f.service.resource+"/responses", strings.NewReader(`{}`))+ _, err := f.service.Do(r, "oaiapp_test")+ done <- err+ }()+ select {+ case <-client.started:+ case <-time.After(5 * time.Second):+ t.Fatal("request not started")+ }+ if _, err := f.service.Logout(context.Background(), "oaiapp_test"); err != nil {+ t.Fatal(err)+ }+ select {+ case err := <-done:+ if !errors.Is(err, context.Canceled) {+ t.Fatalf("request error: %v", err)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("logout left request running")+ }+}diff --git a/kernel/chatgpt/store.go b/kernel/chatgpt/store.gonew file mode 100644index 0000000000..24f270d108--- /dev/null+++ b/kernel/chatgpt/store.go@@ -0,0 +1,349 @@+// 包 chatgpt 管理 ChatGPT 套餐授权,凭证与工作空间数据分开保存。+package chatgpt++import (+ "context"+ "crypto/aes"+ "crypto/cipher"+ "crypto/rand"+ "crypto/sha256"+ "encoding/base64"+ "encoding/json"+ "errors"+ "fmt"+ "net/http"+ "os"+ "path/filepath"+ "slices"+ "sync"+ "time"+ "unicode/utf8"++ "github.com/gofrs/flock"+ "golang.org/x/crypto/pbkdf2"+)++const Issuer = "https://auth.openai.com"+const Resource = "https://api.openai.com/v1"+const permission = "chatgpt.tokens.use.direct"++type Account struct {+ ClientID string `json:"client_id"`+ Subject string `json:"subject"`+ Email string `json:"email,omitempty"`+ Name string `json:"name,omitempty"`+ AccessToken string `json:"access_token,omitempty"`+ RefreshToken string `json:"refresh_token,omitempty"`+ IDToken string `json:"id_token,omitempty"`+ Scopes []string `json:"scopes,omitempty"`+ ExpiresAt int64 `json:"expires_at"`+}++type Profile struct {+ ID string `json:"id"`+ Email string `json:"email"`+ Name string `json:"name"`+ Connected bool `json:"connected"`+ Sharing bool `json:"sharing"`+}++type diskStore struct {+ Version int `json:"version"`+ HostID string `json:"hostID"`+ Accounts []*Account `json:"accounts"`+}++type Service struct {+ dir string+ mu sync.Mutex+ attempts map[string]*attempt+ http HTTPClient+ issuer string+ resource string+ requests map[string]map[*activeRequest]bool+ blocked map[string]bool+}++type HTTPClient interface {+ Do(*http.Request) (*http.Response, error)+}++// Open 只定位主机私有目录,首次操作时才创建凭证文件。+func Open(dir string, clients ...HTTPClient) *Service {+ client := HTTPClient(newHTTPClient())+ if len(clients) > 0 {+ client = clients[0]+ }+ return &Service{dir: dir, attempts: map[string]*attempt{}, http: client, issuer: Issuer, resource: Resource,+ requests: map[string]map[*activeRequest]bool{}, blocked: map[string]bool{}}+}++func randomText(size int) string {+ value := make([]byte, size)+ if _, err := rand.Read(value); err != nil {+ panic(err)+ }+ return base64.RawURLEncoding.EncodeToString(value)+}++func atomicWrite(path string, data []byte) error {+ f, err := os.CreateTemp(filepath.Dir(path), ".chatgpt-*")+ if err != nil {+ return err+ }+ name := f.Name()+ defer os.Remove(name)+ if err = f.Chmod(0600); err == nil {+ _, err = f.Write(data)+ }+ if err == nil {+ err = f.Sync()+ }+ closeErr := f.Close()+ if err != nil {+ return err+ }+ if closeErr != nil {+ return closeErr+ }+ return os.Rename(name, path)+}++func seal(key, plain []byte, aad string) ([]byte, error) {+ block, err := aes.NewCipher(key)+ if err != nil {+ return nil, err+ }+ gcm, err := cipher.NewGCM(block)+ if err != nil {+ return nil, err+ }+ nonce := make([]byte, gcm.NonceSize())+ if _, err = rand.Read(nonce); err != nil {+ return nil, err+ }+ return gcm.Seal(nonce, nonce, plain, []byte(aad)), nil+}++func unseal(key, data []byte, aad string) ([]byte, error) {+ block, err := aes.NewCipher(key)+ if err != nil {+ return nil, err+ }+ gcm, err := cipher.NewGCM(block)+ if err != nil {+ return nil, err+ }+ if len(data) < gcm.NonceSize() {+ return nil, errors.New("invalid encrypted ChatGPT account")+ }+ return gcm.Open(nil, data[:gcm.NonceSize()], data[gcm.NonceSize():], []byte(aad))+}++// withStore 在进程间加锁后重新读取凭证,轮换令牌与到期信息一同写入。+func (s *Service) withStore(ctx context.Context, update func(*diskStore) error) error {+ if err := os.MkdirAll(s.dir, 0700); err != nil {+ return err+ }+ lock := flock.New(filepath.Join(s.dir, "accounts.lock"))+ locked, err := lock.TryLockContext(ctx, 50*time.Millisecond)+ if err != nil {+ return err+ }+ if !locked {+ return ctx.Err()+ }+ defer lock.Unlock()+ keyPath := filepath.Join(s.dir, "key")+ key, err := os.ReadFile(keyPath)+ if os.IsNotExist(err) {+ if _, statErr := os.Stat(filepath.Join(s.dir, "accounts")); !os.IsNotExist(statErr) {+ return errors.New("ChatGPT credential key is missing; preserve the credential files")+ }+ key = make([]byte, 32)+ if _, err = rand.Read(key); err != nil {+ return err+ }+ err = atomicWrite(keyPath, key)+ }+ if err != nil {+ return err+ }+ store := &diskStore{Version: 1, HostID: "urn:uuid:" + randomUUID(), Accounts: []*Account{}}+ data, err := os.ReadFile(filepath.Join(s.dir, "accounts"))+ if err == nil {+ plain, decryptErr := unseal(key, data, "siyuan-chatgpt-store-v1")+ if decryptErr != nil {+ return errors.New("ChatGPT credential authentication failed; preserve the credential files")+ }+ if err = json.Unmarshal(plain, store); err != nil {+ return err+ }+ if store.Version != 1 || store.HostID == "" {+ return errors.New("unsupported ChatGPT credential format")+ }+ } else if !os.IsNotExist(err) {+ return err+ }+ if err = update(store); err != nil {+ return err+ }+ plain, err := json.Marshal(store)+ if err != nil {+ return err+ }+ data, err = seal(key, plain, "siyuan-chatgpt-store-v1")+ if err != nil {+ return err+ }+ return atomicWrite(filepath.Join(s.dir, "accounts"), data)+}++func randomUUID() string {+ var b [16]byte+ if _, err := rand.Read(b[:]); err != nil {+ panic(err)+ }+ b[6] = (b[6] & 15) | 64+ b[8] = (b[8] & 63) | 128+ return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10], b[10:])+}++func findAccount(store *diskStore, id string) (*Account, error) {+ for _, a := range store.Accounts {+ if a.ClientID == id {+ return a, nil+ }+ }+ return nil, errors.New("ChatGPT account is not registered")+}++func profile(a *Account) Profile {+ return Profile{ID: a.ClientID, Email: a.Email, Name: a.Name, Connected: a.AccessToken != "",+ Sharing: a.AccessToken != "" && slices.Contains(a.Scopes, permission)}+}++func (s *Service) Profiles(ctx context.Context) (ret []Profile, err error) {+ ret = []Profile{}+ err = s.withStore(ctx, func(store *diskStore) error {+ for _, a := range store.Accounts {+ ret = append(ret, profile(a))+ }+ return nil+ })+ return+}++type transfer struct {+ Version int `json:"version"`+ Salt []byte `json:"salt"`+ Data []byte `json:"data"`+}++// Export 将可续期会话转交给目标主机,保留本机账户映射并停止本机后续刷新。+func (s *Service) Export(ctx context.Context, id, password string, publish func(string) error) (result string, err error) {+ if utf8.RuneCountInString(password) < 12 {+ return "", errors.New("account transfer password must contain at least 12 characters")+ }+ s.stopRequests(id)+ defer func() {+ if err != nil {+ s.resumeRequests(id)+ }+ }()+ err = s.withStore(ctx, func(store *diskStore) error {+ a, err := findAccount(store, id)+ if err != nil {+ return err+ }+ if a.RefreshToken == "" {+ return errors.New("sign in to ChatGPT before transferring this account")+ }+ plain, err := json.Marshal(a)+ if err != nil {+ return err+ }+ bundle := transfer{Version: 1, Salt: make([]byte, 32)}+ if _, err = rand.Read(bundle.Salt); err != nil {+ return err+ }+ key := pbkdf2.Key([]byte(password), bundle.Salt, 600000, 32, sha256.New)+ bundle.Data, err = seal(key, plain, "siyuan-chatgpt-transfer-v1")+ if err != nil {+ return err+ }+ encoded, err := json.Marshal(bundle)+ if err != nil {+ return err+ }+ result = string(encoded)+ if publish != nil {+ if err = publish(result); err != nil {+ return err+ }+ }+ clearTokens(a)+ return nil+ })+ return+}++// Import 认证导入文件并校验注册身份,目标主机始终保留自己的主机标识。+func (s *Service) Import(ctx context.Context, data, password string) (result Profile, err error) {+ if utf8.RuneCountInString(password) < 12 || len(data) > 1024*1024 {+ return result, errors.New("invalid ChatGPT account transfer")+ }+ var bundle transfer+ if err = json.Unmarshal([]byte(data), &bundle); err != nil {+ return+ }+ if bundle.Version != 1 || len(bundle.Salt) != 32 {+ return result, errors.New("unsupported ChatGPT account transfer format")+ }+ key := pbkdf2.Key([]byte(password), bundle.Salt, 600000, 32, sha256.New)+ plain, err := unseal(key, bundle.Data, "siyuan-chatgpt-transfer-v1")+ if err != nil {+ return result, errors.New("ChatGPT account transfer authentication failed")+ }+ var account Account+ if err = json.Unmarshal(plain, &account); err != nil {+ return+ }+ if account.ClientID == "" || account.ClientID == "dynamic_agent_client" || account.Subject == "" || account.RefreshToken == "" {+ return result, errors.New("invalid ChatGPT account registration")+ }+ identity, err := s.verifyIdentity(ctx, account.IDToken, account.ClientID, "", true)+ if err != nil || identity.Subject != account.Subject {+ return result, errors.New("ChatGPT account identity mismatch")+ }+ err = s.withStore(ctx, func(store *diskStore) error {+ if err := s.refresh(ctx, &account); err != nil {+ return err+ }+ for i, a := range store.Accounts {+ if a.ClientID == account.ClientID {+ if a.Subject != "" && a.Subject != account.Subject {+ return errors.New("ChatGPT account identity mismatch")+ }+ store.Accounts[i] = &account+ result = profile(&account)+ return nil+ }+ }+ store.Accounts = append(store.Accounts, &account)+ result = profile(&account)+ return nil+ })+ if err == nil {+ s.resumeRequests(result.ID)+ }+ return+}++func clearTokens(a *Account) {+ a.AccessToken = ""+ a.RefreshToken = ""+ a.IDToken = ""+ a.Scopes = nil+ a.ExpiresAt = 0+}diff --git a/kernel/conf/ai.go b/kernel/conf/ai.goindex b280d99b48..35759ff1db 100644--- a/kernel/conf/ai.go+++ b/kernel/conf/ai.go@@ -149,6 +149,8 @@ type Rerank struct {}type Provider struct {+ AuthType string `json:"authType,omitempty"`+ AccountID string `json:"accountID,omitempty"`Headers map[string]string `json:"headers,omitempty"`ID string `json:"id"`DisplayName string `json:"displayName,omitempty"`@@ -467,7 +469,11 @@ func (ai *AI) GetImageGenerationModel() (*Provider, *Model) {if ai.ImageGeneration == nil || ai.ImageGeneration.ModelID == "" {return nil, nil}- return ai.GetModel(ai.ImageGeneration.ModelID)+ provider, model := ai.GetModel(ai.ImageGeneration.ModelID)+ if provider != nil && provider.AuthType == "chatgpt" {+ return nil, nil+ }+ return provider, model}// ReconcileModelIDs 校正各使用场景引用的模型,并将旧版名称引用转换为模型 ID。@@ -629,6 +635,12 @@ func (ai *AI) Normalize() {}p.DisplayName = strings.TrimSpace(p.DisplayName)p.APIKey = strings.TrimSpace(p.APIKey)+ if p.AuthType == "chatgpt" {+ p.APIKey = ""+ p.BaseURL = "https://api.openai.com/v1"+ p.Protocol = util.OpenAIProtocolResponses+ p.Headers = nil+ }p.Protocol = strings.ToLower(strings.TrimSpace(p.Protocol))if p.Protocol == "" {p.Protocol = util.OpenAIProtocolChatCompletionsdiff --git a/kernel/conf/ai_chatgpt_test.go b/kernel/conf/ai_chatgpt_test.gonew file mode 100644index 0000000000..49cd58bb32--- /dev/null+++ b/kernel/conf/ai_chatgpt_test.go@@ -0,0 +1,21 @@+package conf++import (+ "testing"+)++func TestChatGPTProviderNormalization(t *testing.T) {+ ai := NewAI()+ ai.Providers = []*Provider{{AuthType: "chatgpt", AccountID: "account", Enabled: true, APIKey: "must-not-be-used",+ BaseURL: "https://untrusted.example/v1", Protocol: "openai", Headers: map[string]string{"Authorization": "untrusted"}}}+ ai.Providers[0].Models = []*Model{{ID: "model", Name: "model", Enabled: true}}+ ai.Normalize()+ p := ai.Providers[0]+ if p.APIKey != "" || p.BaseURL != "https://api.openai.com/v1" || p.Protocol != "openai-responses" || len(p.Headers) != 0 || p.AccountID != "account" {+ t.Fatalf("wrong subscription provider: %+v", p)+ }+ ai.ImageGeneration.ModelID = "model"+ if provider, _ := ai.GetImageGenerationModel(); provider != nil {+ t.Fatal("subscription model offered for image generation")+ }+}diff --git a/kernel/model/ai.go b/kernel/model/ai.goindex a800db3d52..32c2b68c22 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.NewAIClientWithModel(prov.APIKey, prov.BaseURL, m.Name, ResolveAIProviderHeaders(prov))+ client := NewAIProviderClient(prov, m.Name)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.NewAIClientWithModel(prov.APIKey, prov.BaseURL, m.Name, ResolveAIProviderHeaders(prov)),+ c: NewAIProviderClient(prov, m.Name),apiBaseURL: prov.BaseURL,m: m,protocol: prov.Protocol,diff --git a/kernel/model/ai_client.go b/kernel/model/ai_client.gonew file mode 100644index 0000000000..ce1aa032ea--- /dev/null+++ b/kernel/model/ai_client.go@@ -0,0 +1,14 @@+package model++import (+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// NewAIProviderClient 按认证方式创建生成客户端,账户凭证不进入提供商配置。+func NewAIProviderClient(provider *conf.Provider, model string) *util.AIClient {+ if provider.AuthType == "chatgpt" {+ return util.NewChatGPTClient(provider.AccountID)+ }+ return util.NewAIClientWithModel(provider.APIKey, provider.BaseURL, model, ResolveAIProviderHeaders(provider))+}diff --git a/kernel/model/ocr_ai.go b/kernel/model/ocr_ai.goindex df3aec00e9..c0d4624cef 100644--- a/kernel/model/ocr_ai.go+++ b/kernel/model/ocr_ai.go@@ -103,7 +103,7 @@ func aiOCRAsset(ctx context.Context, path string, value conf.OCR, automatic booldefer cancel()}ctx = util.ContextWithOpenAIResponsesBaseURL(ctx, provider.BaseURL)- client := util.NewAIClientWithModel(provider.APIKey, provider.BaseURL, model.Name, ResolveAIProviderHeaders(provider))+ client := NewAIProviderClient(provider, model.Name)response, err := util.CreateOpenAICompletion(ctx, client, protocol, request, nil)if err != nil {return "", errdiff --git a/kernel/util/ai_client.go b/kernel/util/ai_client.goindex b2434efaea..866532a57f 100644--- a/kernel/util/ai_client.go+++ b/kernel/util/ai_client.go@@ -16,6 +16,7 @@ type AIClient struct {*openai.ClientbaseURL stringanthropicHTTP *http.Client+ ChatGPT bool}// AIMessageContent 保存供应商原生内容,显示文本与恢复上下文分别使用各自的表示。diff --git a/kernel/util/chatgpt.go b/kernel/util/chatgpt.gonew file mode 100644index 0000000000..817a1bba40--- /dev/null+++ b/kernel/util/chatgpt.go@@ -0,0 +1,112 @@+package util++import (+ "bytes"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "path/filepath"+ "sync"++ "github.com/sashabaranov/go-openai"+ "github.com/siyuan-note/httpclient"+ "github.com/siyuan-note/siyuan/kernel/chatgpt"+)++var chatGPTServices sync.Map++// ChatGPTService 按主机配置目录保存账户,移动端复用 BootMobile 配置的私有 HomeDir。+func ChatGPTService() *chatgpt.Service {+ dir := filepath.Join(HomeDir, ".config", "siyuan", "chatgpt")+ client := httpclient.NewUserAgentClient(nil)+ client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }+ service, _ := chatGPTServices.LoadOrStore(dir, chatgpt.Open(dir, client))+ return service.(*chatgpt.Service)+}++type chatGPTTransport struct {+ accountID string+ service *chatgpt.Service+}++// NewChatGPTClient 使用可刷新账户凭证,并固定公开套餐端点及请求能力。+func NewChatGPTClient(accountID string) *AIClient {+ config := openai.DefaultConfig("")+ config.BaseURL = chatgpt.Resource+ config.HTTPClient = &chatGPTTransport{accountID: accountID, service: ChatGPTService()}+ return &AIClient{Client: openai.NewClientWithConfig(config), baseURL: chatgpt.Resource, ChatGPT: true}+}++func (t *chatGPTTransport) Do(request *http.Request) (*http.Response, error) {+ if request.URL.String() != chatgpt.Resource+"/responses" || request.Method != "POST" {+ return nil, errors.New("unsupported ChatGPT plan route")+ }+ data, err := io.ReadAll(io.LimitReader(request.Body, 32*1024*1024+1))+ request.Body.Close()+ if err != nil || len(data) > 32*1024*1024 {+ return nil, errors.New("invalid ChatGPT inference request")+ }+ data, err = chatGPTRequestBody(data)+ if err != nil {+ return nil, err+ }+ clone := request.Clone(request.Context())+ clone.Body = io.NopCloser(bytes.NewReader(data))+ clone.ContentLength = int64(len(data))+ clone.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(data)), nil }+ return t.service.Do(clone, t.accountID)+}++func chatGPTRequestBody(data []byte) ([]byte, error) {+ var body map[string]json.RawMessage+ if err := json.Unmarshal(data, &body); err != nil {+ return nil, err+ }+ for _, key := range []string{"background", "conversation", "max_output_tokens", "max_tool_calls", "metadata", "moderation",+ "multi_agent", "prompt", "prompt_cache_retention", "safety_identifier", "temperature", "top_logprobs", "top_p", "truncation", "user", "previous_response_id"} {+ delete(body, key)+ }+ body["store"] = json.RawMessage("false")+ body["stream"] = json.RawMessage("true")+ var input []map[string]json.RawMessage+ if err := json.Unmarshal(body["input"], &input); err != nil || input == nil {+ return nil, errors.New("ChatGPT input must contain the conversation history")+ }+ for _, item := range input {+ if string(item["role"]) == `"system"` {+ item["role"] = json.RawMessage(`"developer"`)+ }+ if string(item["type"]) == `"function_call"` {+ item["namespace"] = json.RawMessage(`"siyuan"`)+ }+ }+ body["input"], _ = json.Marshal(input)+ var tools []json.RawMessage+ if raw, exists := body["tools"]; exists {+ if err := json.Unmarshal(raw, &tools); err != nil {+ return nil, err+ }+ if len(tools) > 0 {+ for _, rawTool := range tools {+ var tool struct {+ Type string `json:"type"`+ }+ if err := json.Unmarshal(rawTool, &tool); err != nil {+ return nil, err+ }+ if tool.Type != "function" && tool.Type != "custom" {+ return nil, errors.New("unsupported ChatGPT plan tool")+ }+ }+ body["tools"], _ = json.Marshal([]struct {+ Type string `json:"type"`+ Name string `json:"name"`+ Tools []json.RawMessage `json:"tools"`+ }{+ {Type: "namespace", Name: "siyuan", Tools: tools},+ })+ }+ }+ return json.Marshal(body)+}diff --git a/kernel/util/chatgpt_test.go b/kernel/util/chatgpt_test.gonew file mode 100644index 0000000000..8c9967d549--- /dev/null+++ b/kernel/util/chatgpt_test.go@@ -0,0 +1,83 @@+package util++import (+ "context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/sashabaranov/go-openai"+)++func TestChatGPTRequestCapabilitiesAndToolReplay(t *testing.T) {+ data, err := chatGPTRequestBody([]byte(`{"model":"model","input":[{"type":"message","role":"system","content":"rules"},{"type":"function_call","call_id":"c","name":"query","arguments":"{}"},{"type":"function_call_output","call_id":"c","output":"ok"}],"tools":[{"type":"function","name":"query","parameters":{"type":"object"}}],"temperature":1,"top_p":0.5,"max_output_tokens":100,"user":"user","previous_response_id":"response"}`))+ if err != nil {+ t.Fatal(err)+ }+ var body map[string]any+ json.Unmarshal(data, &body)+ for _, field := range []string{"temperature", "top_p", "max_output_tokens", "user", "previous_response_id"} {+ if _, exists := body[field]; exists {+ t.Fatalf("unsupported field: %s", field)+ }+ }+ if body["stream"] != true || body["store"] != false {+ t.Fatal("wrong subscription transport")+ }+ input := body["input"].([]any)+ if input[0].(map[string]any)["role"] != "developer" || input[1].(map[string]any)["namespace"] != "siyuan" {+ t.Fatal("input not adapted")+ }+ tool := body["tools"].([]any)[0].(map[string]any)+ if tool["type"] != "namespace" || tool["name"] != "siyuan" {+ t.Fatal("tools not namespaced")+ }+ if _, err = chatGPTRequestBody([]byte(`{"input":[],"tools":[{"type":"image_generation"}]}`)); err == nil {+ t.Fatal("unsupported hosted tool accepted")+ }+}++func TestChatGPTCompletionUsesStreamAndRejectsIncomplete(t *testing.T) {+ for _, terminal := range []string{"completed", "incomplete", "failed", "disconnected"} {+ t.Run(terminal, func(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var body map[string]any+ json.NewDecoder(r.Body).Decode(&body)+ if body["stream"] != true {+ t.Error("nonstream subscription request")+ }+ w.Header().Set("Content-Type", "text/event-stream")+ io.WriteString(w, "data: {\"type\":\"response.output_text.delta\",\"delta\":\"Title\"}\n\n")+ if terminal == "disconnected" {+ return+ }+ io.WriteString(w, "data: {\"type\":\"response."+terminal+"\",\"response\":{\"id\":\"resp\",\"status\":\""+terminal+"\",\"model\":\"model\",\"output\":[{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"Title\"}]}]}}\n\n")+ }))+ defer server.Close()+ client := NewAIClientWithModel("test", server.URL, "model")+ client.ChatGPT = true+ response, err := CreateOpenAICompletion(context.Background(), client, OpenAIProtocolResponses,+ openai.ChatCompletionRequest{Model: "model", Messages: []openai.ChatCompletionMessage{{Role: "user", Content: "title"}}}, nil)+ if terminal == "completed" {+ if err != nil || response.Choices[0].Message.Content != "Title" {+ t.Fatalf("completion: %+v %v", response, err)+ }+ } else if err == nil {+ t.Fatal("unfinished response accepted")+ }+ })+ }+}++func TestChatGPTTransportRejectsNonPublicRoutes(t *testing.T) {+ transport := &chatGPTTransport{}+ for _, endpoint := range []string{"https://api.openai.com/v1/responses/compact", "https://chatgpt.com/backend-api/codex/responses", "https://untrusted.example/responses"} {+ request, _ := http.NewRequest("POST", endpoint, strings.NewReader("{}"))+ if _, err := transport.Do(request); err == nil {+ t.Fatal("untrusted endpoint accepted")+ }+ }+}diff --git a/kernel/util/openai_completion.go b/kernel/util/openai_completion.goindex 2cfcf516de..e3fa9dd4e8 100644--- a/kernel/util/openai_completion.go+++ b/kernel/util/openai_completion.go@@ -100,6 +100,7 @@ type OpenAICompletionStream struct {responseContent strings.BuilderresponseToolCalls map[int]openai.ToolCallresponsesDone bool+ chatGPT bool}func CreateOpenAICompletionStream(ctx context.Context, client *AIClient, protocol string,@@ -129,6 +130,7 @@ func CreateOpenAICompletionStream(ctx context.Context, client *AIClient, protocobreak}return &OpenAICompletionStream{+ chatGPT: client.ChatGPT,responses: stream,responseToolCalls: map[int]openai.ToolCall{},}, nil@@ -136,6 +138,33 @@ func CreateOpenAICompletionStream(ctx context.Context, client *AIClient, protocofunc CreateOpenAICompletion(ctx context.Context, client *AIClient, protocol string,request openai.ChatCompletionRequest, responseInput []any) (openai.ChatCompletionResponse, error) {+ if client.ChatGPT {+ stream, err := CreateOpenAICompletionStream(ctx, client, protocol, request, responseInput)+ if err != nil {+ return openai.ChatCompletionResponse{}, err+ }+ defer stream.Close()+ var completed openai.ChatCompletionResponse+ var text strings.Builder+ for {+ chunk, recvErr := stream.Recv()+ if errors.Is(recvErr, io.EOF) {+ break+ }+ if recvErr != nil {+ return completed, recvErr+ }+ completed.ID, completed.Model = chunk.ID, chunk.Model+ if chunk.Usage != nil {+ completed.Usage = *chunk.Usage+ }+ for _, choice := range chunk.Choices {+ text.WriteString(choice.Delta.Content)+ }+ }+ completed.Choices = []openai.ChatCompletionChoice{{Message: openai.ChatCompletionMessage{Role: "assistant", Content: text.String()}, FinishReason: openai.FinishReasonStop}}+ return completed, nil+ }if IsAnthropicMessagesProtocol(protocol) {return createAnthropicCompletion(ctx, client, request)}@@ -578,6 +607,9 @@ func (stream *OpenAICompletionStream) Recv() (openai.ChatCompletionStreamResponsif event.Response == nil {return openai.ChatCompletionStreamResponse{}, errors.New("response stream terminal event is missing response")}+ if stream.chatGPT && (event.Type != openai.ResponseStreamEventCompleted || event.Response.Status != openai.ResponseStatusCompleted) {+ return openai.ChatCompletionStreamResponse{}, errors.New("ChatGPT response did not complete")+ }if err = stream.queueResponseTerminal(*event.Response); err != nil {return openai.ChatCompletionStreamResponse{}, err}