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 workspace AGENTS.md instructions https://github.com/siyuan-note/siyuan/issues/19876
Daniel5701d7767479
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex c405bad86a..bf0568e019 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,8 @@{+ "agentInstructions": "تعليمات مخصصة",+ "agentInstructionsTip": "تُحفظ تفضيلات مساحة العمل في data/ai/AGENTS.md وتُزامَن ما لم تُستثنَ؛ نص UTF-8 بحجم أقصى 32 KiB، يسري بدءًا من الجولة التالية من المحادثة",+ "agentInstructionsTooLarge": "يجب ألا يتجاوز حجم التعليمات 32 KiB",+ "agentInstructionsConflict": "تم تغيير AGENTS.md. انسخ تعديلاتك، وأعد فتح المحرر، ثم ادمج التغييرات قبل الحفظ","listMindmapSummary": "ملخص","listMindmapSummarySelect": "حدد آخر عقدة شقيقة في نطاق الملخص؛ لا يمكن أن تتداخل الملخصات","mcpOAuthServer": "OAuth لخادم MCP",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 4bd814f618..273e0877f6 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,8 @@{+ "agentInstructions": "Benutzerdefinierte Anweisungen",+ "agentInstructionsTip": "Arbeitsbereichsweite Vorgaben werden in data/ai/AGENTS.md gespeichert und synchronisiert, sofern nicht ausgeschlossen; UTF-8-Text bis 32 KiB, gültig ab dem nächsten Gesprächsschritt",+ "agentInstructionsTooLarge": "Anweisungen dürfen höchstens 32 KiB groß sein",+ "agentInstructionsConflict": "AGENTS.md wurde geändert. Kopieren Sie Ihre Änderungen, öffnen Sie den Editor erneut und führen Sie die Änderungen vor dem Speichern zusammen","listMindmapSummary": "Zusammenfassung","listMindmapSummarySelect": "Wähle den letzten gleichgeordneten Knoten des Bereichs; Zusammenfassungen dürfen sich nicht überschneiden","mcpOAuthServer": "OAuth für MCP-Server",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 6984eccd26..ac511acf7c 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,8 @@{+ "agentInstructions": "Custom instructions",+ "agentInstructionsTip": "Workspace-wide preferences stored in data/ai/AGENTS.md and synced unless excluded; UTF-8 text up to 32 KiB, effective from the next conversation turn",+ "agentInstructionsTooLarge": "Instructions must be at most 32 KiB",+ "agentInstructionsConflict": "AGENTS.md has changed. Copy your edits, reopen the editor, and merge them before saving","listMindmapSummary": "Summary","listMindmapSummarySelect": "Select the last sibling node in the summary range; summaries cannot overlap","mcpOAuthServer": "MCP server OAuth",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 3ac6348945..1024be9016 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,8 @@{+ "agentInstructions": "Instrucciones personalizadas",+ "agentInstructionsTip": "Preferencias del espacio de trabajo guardadas en data/ai/AGENTS.md y sincronizadas salvo exclusión; texto UTF-8 de hasta 32 KiB, efectivo a partir del siguiente turno de conversación",+ "agentInstructionsTooLarge": "Las instrucciones no deben superar los 32 KiB",+ "agentInstructionsConflict": "AGENTS.md ha cambiado. Copia tus cambios, vuelve a abrir el editor y combínalos antes de guardar","listMindmapSummary": "Resumen","listMindmapSummarySelect": "Selecciona el último nodo del mismo nivel del rango; los resúmenes no pueden superponerse","mcpOAuthServer": "OAuth del servidor MCP",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex 5e1542ac80..7a825e9e0a 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,8 @@{+ "agentInstructions": "Instructions personnalisées",+ "agentInstructionsTip": "Préférences de l’espace de travail enregistrées dans data/ai/AGENTS.md et synchronisées sauf exclusion ; texte UTF-8 de 32 KiB maximum, appliqué au prochain tour de conversation",+ "agentInstructionsTooLarge": "Les instructions ne doivent pas dépasser 32 KiB",+ "agentInstructionsConflict": "AGENTS.md a changé. Copiez vos modifications, rouvrez l’éditeur et fusionnez-les avant d’enregistrer","listMindmapSummary": "Résumé","listMindmapSummarySelect": "Sélectionnez le dernier nœud de même parent dans la plage ; les résumés ne peuvent pas se chevaucher","mcpOAuthServer": "OAuth du serveur MCP",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 53615311a8..43b02d48a2 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,8 @@{+ "agentInstructions": "הוראות מותאמות אישית",+ "agentInstructionsTip": "העדפות סביבת העבודה נשמרות ב־data/ai/AGENTS.md ומסונכרנות אלא אם הוחרגו; טקסט UTF-8 עד 32 KiB, בתוקף מסבב השיחה הבא",+ "agentInstructionsTooLarge": "גודל ההוראות לא יכול לעלות על 32 KiB",+ "agentInstructionsConflict": "AGENTS.md השתנה. יש להעתיק את העריכות, לפתוח מחדש את העורך ולמזג את השינויים לפני השמירה","listMindmapSummary": "סיכום","listMindmapSummarySelect": "יש לבחור את הצומת האח האחרון בטווח הסיכום; סיכומים אינם יכולים לחפוף","mcpOAuthServer": "OAuth של שרת MCP",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 0defa27058..394865a5d7 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,8 @@{+ "agentInstructions": "कस्टम निर्देश",+ "agentInstructionsTip": "कार्यस्थान की प्राथमिकताएँ data/ai/AGENTS.md में सहेजी जाती हैं और बाहर न रखे जाने पर सिंक होती हैं; अधिकतम 32 KiB का UTF-8 पाठ, बातचीत के अगले चरण से लागू",+ "agentInstructionsTooLarge": "निर्देश 32 KiB से अधिक नहीं होने चाहिए",+ "agentInstructionsConflict": "AGENTS.md बदल गया है। अपने बदलाव कॉपी करें, संपादक फिर से खोलें और सहेजने से पहले बदलावों को मिलाएँ","listMindmapSummary": "सारांश","listMindmapSummarySelect": "सारांश के दायरे में समान मूल नोड वाला अंतिम नोड चुनें; सारांशों के दायरे आपस में नहीं मिलने चाहिए","mcpOAuthServer": "MCP सर्वर OAuth",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 88ef828b3e..de5317c72c 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,8 @@{+ "agentInstructions": "Instruksi khusus",+ "agentInstructionsTip": "Preferensi ruang kerja disimpan di data/ai/AGENTS.md dan disinkronkan kecuali dikecualikan; teks UTF-8 hingga 32 KiB, berlaku mulai giliran percakapan berikutnya",+ "agentInstructionsTooLarge": "Instruksi tidak boleh melebihi 32 KiB",+ "agentInstructionsConflict": "AGENTS.md telah berubah. Salin perubahan Anda, buka kembali editor, lalu gabungkan sebelum menyimpan","listMindmapSummary": "Ringkasan","listMindmapSummarySelect": "Pilih simpul terakhir dengan induk yang sama dalam rentang ringkasan; ringkasan tidak boleh tumpang tindih","mcpOAuthServer": "OAuth server MCP",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 64d6b3d6e7..e35a8ca643 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,8 @@{+ "agentInstructions": "Istruzioni personalizzate",+ "agentInstructionsTip": "Preferenze dell’area di lavoro salvate in data/ai/AGENTS.md e sincronizzate salvo esclusione; testo UTF-8 fino a 32 KiB, valido dal prossimo turno di conversazione",+ "agentInstructionsTooLarge": "Le istruzioni non devono superare 32 KiB",+ "agentInstructionsConflict": "AGENTS.md è cambiato. Copia le tue modifiche, riapri l’editor e uniscile prima di salvare","listMindmapSummary": "Riepilogo","listMindmapSummarySelect": "Seleziona l'ultimo nodo con lo stesso genitore nell'intervallo; i riepiloghi non possono sovrapporsi","mcpOAuthServer": "OAuth del server MCP",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 81c6497a5e..b053642c4a 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,8 @@{+ "agentInstructions": "カスタム指示",+ "agentInstructionsTip": "ワークスペース全体の設定を data/ai/AGENTS.md に保存し、除外されていなければ同期します。最大 32 KiB の UTF-8 テキストに対応し、次の会話ターンから適用されます",+ "agentInstructionsTooLarge": "指示は 32 KiB 以下にしてください",+ "agentInstructionsConflict": "AGENTS.md が変更されました。編集内容をコピーし、エディターを開き直して変更を統合してから保存してください","listMindmapSummary": "要約","listMindmapSummarySelect": "要約範囲の末端にある同じ親のノードを選択してください。要約範囲は重複できません","mcpOAuthServer": "MCP サーバー OAuth",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 6779b34970..c13924b89d 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,8 @@{+ "agentInstructions": "사용자 지정 지침",+ "agentInstructionsTip": "작업 공간 전체의 기본 설정은 data/ai/AGENTS.md에 저장되며 제외되지 않으면 동기화됩니다. 최대 32 KiB의 UTF-8 텍스트를 지원하며 다음 대화 차례부터 적용됩니다",+ "agentInstructionsTooLarge": "지침은 32 KiB를 초과할 수 없습니다",+ "agentInstructionsConflict": "AGENTS.md가 변경되었습니다. 수정 내용을 복사한 다음 편집기를 다시 열고 변경 사항을 병합하여 저장하세요","listMindmapSummary": "요약","listMindmapSummarySelect": "요약 범위에서 부모가 같은 마지막 노드를 선택하세요. 요약 범위는 겹칠 수 없습니다","mcpOAuthServer": "MCP 서버 OAuth",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex b9392c33a3..518d1709ab 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,8 @@{+ "agentInstructions": "Aangepaste instructies",+ "agentInstructionsTip": "Voorkeuren voor de hele werkruimte worden opgeslagen in data/ai/AGENTS.md en gesynchroniseerd tenzij uitgesloten; UTF-8-tekst tot 32 KiB, van kracht vanaf de volgende gespreksbeurt",+ "agentInstructionsTooLarge": "Instructies mogen maximaal 32 KiB groot zijn",+ "agentInstructionsConflict": "AGENTS.md is gewijzigd. Kopieer je wijzigingen, open de editor opnieuw en voeg ze samen voordat je opslaat","listMindmapSummary": "Samenvatting","listMindmapSummarySelect": "Selecteer de laatste knoop met dezelfde ouder in het bereik; samenvattingen mogen niet overlappen","mcpOAuthServer": "OAuth voor MCP-server",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 2a4f3c2578..7ede3013e9 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,8 @@{+ "agentInstructions": "Własne instrukcje",+ "agentInstructionsTip": "Preferencje obszaru roboczego zapisane w data/ai/AGENTS.md i synchronizowane, o ile nie zostały wykluczone; tekst UTF-8 do 32 KiB, stosowany od następnej tury rozmowy",+ "agentInstructionsTooLarge": "Instrukcje nie mogą przekraczać 32 KiB",+ "agentInstructionsConflict": "Plik AGENTS.md został zmieniony. Skopiuj swoje zmiany, otwórz edytor ponownie i scal je przed zapisaniem","listMindmapSummary": "Podsumowanie","listMindmapSummarySelect": "Wybierz ostatni węzeł o tym samym rodzicu w zakresie; podsumowania nie mogą się nakładać","mcpOAuthServer": "OAuth serwera MCP",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 875de75e87..06d53404d7 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,8 @@{+ "agentInstructions": "Instruções personalizadas",+ "agentInstructionsTip": "Preferências do espaço de trabalho salvas em data/ai/AGENTS.md e sincronizadas salvo exclusão; texto UTF-8 de até 32 KiB, aplicado a partir do próximo turno da conversa",+ "agentInstructionsTooLarge": "As instruções não podem exceder 32 KiB",+ "agentInstructionsConflict": "AGENTS.md foi alterado. Copie suas alterações, reabra o editor e combine-as antes de salvar","listMindmapSummary": "Resumo","listMindmapSummarySelect": "Selecione o último nó com o mesmo pai no intervalo; os resumos não podem se sobrepor","mcpOAuthServer": "OAuth do servidor MCP",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 90f9d31823..fdff3260ff 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,8 @@{+ "agentInstructions": "Пользовательские инструкции",+ "agentInstructionsTip": "Настройки рабочего пространства хранятся в data/ai/AGENTS.md и синхронизируются, если не исключены; текст UTF-8 до 32 KiB, применяется со следующего хода диалога",+ "agentInstructionsTooLarge": "Размер инструкций не должен превышать 32 KiB",+ "agentInstructionsConflict": "AGENTS.md изменён. Скопируйте свои правки, заново откройте редактор и объедините изменения перед сохранением","listMindmapSummary": "Обобщение","listMindmapSummarySelect": "Выберите последний узел с тем же родителем в диапазоне; обобщения не могут пересекаться","mcpOAuthServer": "OAuth сервера MCP",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 005aadc214..5174aa2da3 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,8 @@{+ "agentInstructions": "Vlastné pokyny",+ "agentInstructionsTip": "Predvoľby pracovného priestoru uložené v data/ai/AGENTS.md a synchronizované, ak nie sú vylúčené; text UTF-8 do 32 KiB, platný od ďalšieho kola konverzácie",+ "agentInstructionsTooLarge": "Pokyny nesmú presiahnuť 32 KiB",+ "agentInstructionsConflict": "Súbor AGENTS.md sa zmenil. Skopírujte svoje zmeny, znova otvorte editor a pred uložením ich zlúčte","listMindmapSummary": "Súhrn","listMindmapSummarySelect": "Vyberte posledný uzol s rovnakým rodičom v rozsahu; súhrny sa nesmú prekrývať","mcpOAuthServer": "OAuth servera MCP",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex 954c9d356f..bfcec3c89d 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,8 @@{+ "agentInstructions": "Прилагођена упутства",+ "agentInstructionsTip": "Подешавања радног простора чувају се у data/ai/AGENTS.md и синхронизују ако нису изузета; UTF-8 текст до 32 KiB, примењује се од следећег круга разговора",+ "agentInstructionsTooLarge": "Упутства не смеју бити већа од 32 KiB",+ "agentInstructionsConflict": "AGENTS.md је промењен. Копирајте своје измене, поново отворите уређивач и обједините их пре чувања","listMindmapSummary": "Сажетак","listMindmapSummarySelect": "Изаберите последњи чвор са истим родитељем у опсегу; сажеци се не смеју преклапати","mcpOAuthServer": "OAuth MCP сервера",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 110cd1fb7f..c8173b0b08 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,8 @@{+ "agentInstructions": "คำสั่งที่กำหนดเอง",+ "agentInstructionsTip": "บันทึกการตั้งค่าสำหรับพื้นที่ทำงานใน data/ai/AGENTS.md และซิงค์หากไม่ได้ยกเว้น รองรับข้อความ UTF-8 สูงสุด 32 KiB โดยมีผลในรอบสนทนาถัดไป",+ "agentInstructionsTooLarge": "คำสั่งต้องมีขนาดไม่เกิน 32 KiB",+ "agentInstructionsConflict": "AGENTS.md มีการเปลี่ยนแปลง โปรดคัดลอกสิ่งที่คุณแก้ไข เปิดตัวแก้ไขอีกครั้ง แล้วรวมการเปลี่ยนแปลงก่อนบันทึก","listMindmapSummary": "สรุป","listMindmapSummarySelect": "เลือกโหนดสุดท้ายที่มีโหนดแม่เดียวกันในช่วงสรุป โดยช่วงสรุปต้องไม่ทับซ้อนกัน","mcpOAuthServer": "OAuth ของเซิร์ฟเวอร์ MCP",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex ff7be69031..e625691ec6 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,8 @@{+ "agentInstructions": "Özel talimatlar",+ "agentInstructionsTip": "Çalışma alanı tercihleri data/ai/AGENTS.md dosyasında saklanır ve hariç tutulmadıkça eşitlenir; en fazla 32 KiB UTF-8 metin, sonraki konuşma turundan itibaren geçerlidir",+ "agentInstructionsTooLarge": "Talimatlar 32 KiB boyutunu aşmamalıdır",+ "agentInstructionsConflict": "AGENTS.md değişti. Düzenlemelerinizi kopyalayın, düzenleyiciyi yeniden açın ve kaydetmeden önce değişiklikleri birleştirin","listMindmapSummary": "Özet","listMindmapSummarySelect": "Özet aralığında aynı üst düğüme bağlı son düğümü seçin; özetler çakışamaz","mcpOAuthServer": "MCP sunucusu OAuth",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex ce01d143b3..d878cdb4dd 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,8 @@{+ "agentInstructions": "Власні інструкції",+ "agentInstructionsTip": "Налаштування робочого простору зберігаються в data/ai/AGENTS.md і синхронізуються, якщо не виключені; текст UTF-8 до 32 KiB, застосовується з наступного ходу розмови",+ "agentInstructionsTooLarge": "Розмір інструкцій не має перевищувати 32 KiB",+ "agentInstructionsConflict": "AGENTS.md змінено. Скопіюйте свої правки, знову відкрийте редактор і об’єднайте зміни перед збереженням","listMindmapSummary": "Узагальнення","listMindmapSummarySelect": "Виберіть останній вузол зі спільним батьківським вузлом у діапазоні; узагальнення не можуть перетинатися","mcpOAuthServer": "OAuth сервера MCP",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex d6bce80bc0..b87530bea7 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,8 @@{+ "agentInstructions": "自定义指令",+ "agentInstructionsTip": "工作空间级偏好保存在 data/ai/AGENTS.md 中,未被忽略时参与同步;支持最多 32 KiB 的 UTF-8 文本,保存后下一轮对话生效",+ "agentInstructionsTooLarge": "指令内容不能超过 32 KiB",+ "agentInstructionsConflict": "AGENTS.md 已发生变化。请先复制你的修改,重新打开编辑器并合并后再保存","listMindmapSummary": "概要","listMindmapSummarySelect": "选择概要范围的末端同级节点,范围不能与已有概要重叠","mcpOAuthServer": "MCP 服务端 OAuth",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex c2764a82e7..3991e4083d 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,8 @@{+ "agentInstructions": "自訂指令",+ "agentInstructionsTip": "工作空間層級偏好儲存於 data/ai/AGENTS.md,未被忽略時參與同步;支援最多 32 KiB 的 UTF-8 文字,儲存後下一輪對話生效",+ "agentInstructionsTooLarge": "指令內容不能超過 32 KiB",+ "agentInstructionsConflict": "AGENTS.md 已變更。請先複製你的修改,重新開啟編輯器並合併後再儲存","listMindmapSummary": "概要","listMindmapSummarySelect": "選擇概要範圍的末端同層節點,範圍不能與既有概要重疊","mcpOAuthServer": "MCP 伺服器 OAuth",diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260804171004-aiagt03.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260804171004-aiagt03.syindex 02839b4138..1dfc2e138a 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260804171004-aiagt03.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230304000547-ibldj1z/20260804171004-aiagt03.sy@@ -6,7 +6,7 @@"id": "20260804171004-aiagt03","title": "AI Agent","type": "doc",- "updated": "20260816130653"+ "updated": "20260926163337"},"Children": [{@@ -44,7 +44,7 @@"HeadingLevel": 2,"Properties": {"id": "20260804170025-2kdbnc8",- "updated": "20260804180000"+ "updated": "20260926163337"},"Children": [{@@ -162,6 +162,113 @@}]},+ {+ "ID": "20260926163337-6d5c7t2",+ "Type": "NodeHeading",+ "HeadingLevel": 3,+ "Properties": {+ "id": "20260926163337-6d5c7t2",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Custom instructions"+ }+ ]+ },+ {+ "ID": "20260926163337-o09flio",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260926163337-o09flio",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Edit persistent preferences in "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Settings"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Artificial Intelligence"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Agent"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Custom instructions"+ },+ {+ "Type": "NodeText",+ "Data": ", such as writing style, citation habits, and note organization rules. Desktop and mobile use the same workspace instructions."+ }+ ]+ },+ {+ "ID": "20260926163337-lzrrvoq",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260926163337-lzrrvoq",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Instructions are stored in data/ai/AGENTS.md inside the workspace as UTF-8 text, up to 32 KiB. The file syncs with the workspace when data sync is enabled and no sync ignore rule excludes it. You can also edit the file directly with a text editor. A missing or empty file adds no custom instructions."+ }+ ]+ },+ {+ "ID": "20260926163337-5cpn50j",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260926163337-5cpn50j",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Saved changes take effect on the next conversation turn. Tool calls and context compaction in an ongoing turn keep the snapshot read at the start of that turn. Instructions count toward the model context. Your current message can override general preferences, but instructions cannot bypass tool permissions, approvals, or access controls. Notebook and document inheritance are not supported, and notes or attachments with the same name are not loaded automatically."+ }+ ]+ },+ {+ "ID": "20260926163337-7q90dky",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260926163337-7q90dky",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Read failures, invalid encoding, or oversized content display an error and stop the turn without overwriting or truncating the original file. If another window or sync changes the file before you save, copy your unsaved edits, reopen the editor, and merge the changes before saving."+ }+ ]+ },{"ID": "20260804170027-iffmsq0","Type": "NodeHeading",diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260804171000-aiagt01.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260804171000-aiagt01.syindex 09f573dc02..03266d6113 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260804171000-aiagt01.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230303235619-ex5l63e/20260804171000-aiagt01.sy@@ -6,7 +6,7 @@"id": "20260804171000-aiagt01","title": "AI 智能体","type": "doc",- "updated": "20260820190627"+ "updated": "20260926163337"},"Children": [{@@ -44,7 +44,7 @@"HeadingLevel": 2,"Properties": {"id": "20260804170025-0kg9iaq",- "updated": "20260804180000"+ "updated": "20260926163337"},"Children": [{@@ -162,6 +162,113 @@}]},+ {+ "ID": "20260926163337-jwclkdq",+ "Type": "NodeHeading",+ "HeadingLevel": 3,+ "Properties": {+ "id": "20260926163337-jwclkdq",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "自定义指令"+ }+ ]+ },+ {+ "ID": "20260926163337-mxj72qh",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260926163337-mxj72qh",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "在 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "设置"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "人工智能"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "智能体"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "自定义指令"+ },+ {+ "Type": "NodeText",+ "Data": " 中编辑长期偏好,例如写作风格、引用习惯和笔记整理规则。桌面端和移动端共用同一份工作空间指令。"+ }+ ]+ },+ {+ "ID": "20260926163337-kr7adcx",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260926163337-kr7adcx",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "指令保存在工作空间的 data/ai/AGENTS.md 中,支持最多 32 KiB 的 UTF-8 文本。启用数据同步且未被同步忽略规则排除时,该文件随工作空间同步。也可以使用文本编辑器直接编辑文件;文件不存在或为空时不添加自定义指令。"+ }+ ]+ },+ {+ "ID": "20260926163337-u4f51t8",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260926163337-u4f51t8",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "保存后下一轮对话生效,正在执行的工具调用和上下文压缩继续使用本轮开始时的指令快照。指令占用模型上下文。当前消息可以覆盖一般偏好,但不能通过指令绕过工具权限、审批或访问控制。首版不支持笔记本或文档级继承,也不自动加载同名笔记或附件。"+ }+ ]+ },+ {+ "ID": "20260926163337-g2pa359",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260926163337-g2pa359",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "文件读取失败、编码错误或内容超限时,会显示错误并停止本轮请求,原文件不会被覆盖或截断。如果保存时发现文件已被其它窗口或同步修改,请先复制未保存的内容,重新打开编辑器并合并修改后再保存。"+ }+ ]+ },{"ID": "20260804170027-76js6ua","Type": "NodeHeading",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260804171002-aiagt02.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260804171002-aiagt02.syindex 74a4987793..2d18b1327e 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260804171002-aiagt02.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230304000829-9jwu3po/20260804171002-aiagt02.sy@@ -6,7 +6,7 @@"id": "20260804171002-aiagt02","title": "AI 智能體","type": "doc",- "updated": "20260816130653"+ "updated": "20260926163337"},"Children": [{@@ -44,7 +44,7 @@"HeadingLevel": 2,"Properties": {"id": "20260804170025-arr6px9",- "updated": "20260804180000"+ "updated": "20260926163337"},"Children": [{@@ -162,6 +162,113 @@}]},+ {+ "ID": "20260926163337-a9sacr9",+ "Type": "NodeHeading",+ "HeadingLevel": 3,+ "Properties": {+ "id": "20260926163337-a9sacr9",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "自訂指令"+ }+ ]+ },+ {+ "ID": "20260926163337-lt8blyw",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260926163337-lt8blyw",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "在 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "設定"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "人工智能"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "智能體"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "自訂指令"+ },+ {+ "Type": "NodeText",+ "Data": " 中編輯長期偏好,例如寫作風格、引用習慣和筆記整理規則。桌面端和行動端共用同一份工作空間指令。"+ }+ ]+ },+ {+ "ID": "20260926163337-zznm7nc",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260926163337-zznm7nc",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "指令儲存於工作空間的 data/ai/AGENTS.md,支援最多 32 KiB 的 UTF-8 文字。啟用資料同步且未被同步忽略規則排除時,此檔案會隨工作空間同步。也可以使用文字編輯器直接編輯檔案;檔案不存在或為空時不加入自訂指令。"+ }+ ]+ },+ {+ "ID": "20260926163337-7gtjdje",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260926163337-7gtjdje",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "儲存後下一輪對話生效,正在執行的工具呼叫和上下文壓縮繼續使用本輪開始時的指令快照。指令會占用模型上下文。目前訊息可以覆蓋一般偏好,但不能透過指令繞過工具權限、審批或存取控制。首版不支援筆記本或文件層級繼承,也不自動載入同名筆記或附件。"+ }+ ]+ },+ {+ "ID": "20260926163337-dy69wao",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260926163337-dy69wao",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "檔案讀取失敗、編碼錯誤或內容超限時,會顯示錯誤並停止本輪請求,原檔案不會被覆蓋或截斷。如果儲存時發現檔案已被其他視窗或同步修改,請先複製尚未儲存的內容,重新開啟編輯器並合併修改後再儲存。"+ }+ ]+ },{"ID": "20260804170027-qlngedh","Type": "NodeHeading",diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260804171006-aiagt04.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260804171006-aiagt04.syindex 11a0dc11c5..db47c4629f 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260804171006-aiagt04.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-ei5t6tt/20260804171006-aiagt04.sy@@ -6,7 +6,7 @@"id": "20260804171006-aiagt04","title": "AI エージェント","type": "doc",- "updated": "20260816130653"+ "updated": "20260926163337"},"Children": [{@@ -44,7 +44,7 @@"HeadingLevel": 2,"Properties": {"id": "20260804170025-r2m4o0b",- "updated": "20260804180000"+ "updated": "20260926163337"},"Children": [{@@ -158,6 +158,109 @@}]},+ {+ "ID": "20260926163337-49n3p0a",+ "Type": "NodeHeading",+ "HeadingLevel": 3,+ "Properties": {+ "id": "20260926163337-49n3p0a",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "カスタム指示"+ }+ ]+ },+ {+ "ID": "20260926163337-nrlrrlv",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260926163337-nrlrrlv",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "設定"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "AI を呼び出す"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "エージェント"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "カスタム指示"+ },+ {+ "Type": "NodeText",+ "Data": " で、文体、引用方法、ノートの整理ルールなどの長期的な設定を編集します。デスクトップ版とモバイル版は同じワークスペースの指示を使用します。"+ }+ ]+ },+ {+ "ID": "20260926163337-f5ixseu",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260926163337-f5ixseu",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "指示はワークスペース内の data/ai/AGENTS.md に最大 32 KiB の UTF-8 テキストとして保存されます。データ同期が有効で、同期の除外ルールに該当しなければ、ワークスペースとともに同期されます。テキストエディターで直接編集することもできます。ファイルが存在しない場合や空の場合、カスタム指示は追加されません。"+ }+ ]+ },+ {+ "ID": "20260926163337-ycm8nwf",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260926163337-ycm8nwf",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "保存した変更は次の会話ターンから適用されます。実行中のツール呼び出しとコンテキスト圧縮には、そのターンの開始時に読み込んだ指示が引き続き使用されます。指示はモデルのコンテキストを消費します。現在のメッセージは一般的な設定より優先されますが、指示でツール権限、承認、アクセス制御を回避することはできません。ノートブックやドキュメント単位の継承には対応しておらず、同名のノートや添付ファイルも自動では読み込みません。"+ }+ ]+ },+ {+ "ID": "20260926163337-e2pfywv",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260926163337-e2pfywv",+ "updated": "20260926163337"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "読み込み失敗、文字コードの問題、サイズ超過があると、エラーを表示してそのターンを停止します。元のファイルは上書きも切り詰めもされません。保存前に別のウィンドウや同期によってファイルが変更された場合は、未保存の編集内容をコピーし、エディターを開き直して変更を統合してから保存してください。"+ }+ ]+ },{"ID": "20260804170027-2jaadkf","Type": "NodeHeading",diff --git a/app/src/config/tabs/ai/aiInstructions.test.ts b/app/src/config/tabs/ai/aiInstructions.test.tsnew file mode 100644index 0000000000..ade7c04a41--- /dev/null+++ b/app/src/config/tabs/ai/aiInstructions.test.ts@@ -0,0 +1,84 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import test from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";++const setup = () => {+ const button = {disabled: false};+ const input = {disabled: false, rows: 0};+ let closed = false;+ let options: {value: string, multiline: boolean, onConfirm: (content: string, currentDialog: typeof dialog) => void};+ const dialog = {+ element: {querySelector: (selector: string) => selector === "textarea" ? input : button},+ destroy: () => { closed = true; },+ };+ const requests: {content: string, revision: string}[] = [];+ const messages: string[] = [];+ let finish: (success: boolean) => void;+ const exports = {} as {openAgentInstructions: () => void};+ runInNewContext(transpileModule(readFileSync("src/config/tabs/ai/aiInstructions.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2020},+ }).outputText, {+ exports,+ TextEncoder,+ window: {siyuan: {languages: {agentInstructionsTooLarge: "too large"}}},+ require: (name: string) => {+ if (name.endsWith("/inputDialog")) {+ return {openInputDialog: (value: typeof options) => { options = value; return dialog; }};+ }+ if (name.endsWith("/message")) {+ return {showMessage: (value: string) => messages.push(value)};+ }+ if (name.endsWith("/fetch")) {+ return {fetchPost: (path: string, data: typeof requests[number], callback: (result?: unknown) => void) => {+ if (path.endsWith("getInstructions")) {+ callback({data: {content: "original", revision: "revision-1"}});+ return Promise.resolve();+ }+ requests.push(data);+ return new Promise<void>(resolve => {+ finish = success => { if (success) { callback(); } resolve(); };+ });+ }};+ }+ throw new Error(name);+ },+ });+ exports.openAgentInstructions();+ return {button, input, requests, messages, options: () => options, closed: () => closed,+ save: (content: string) => options.onConfirm(content, dialog), finish: (success: boolean) => finish(success)};+};++test("instruction editor retains its revision and draft after a failed save", async () => {+ const editor = setup();+ assert.equal(editor.options().value, "original");+ assert.equal(editor.options().multiline, true);+ editor.save("draft");+ editor.save("duplicate");+ assert.equal(editor.requests.length, 1);+ assert.equal(editor.requests[0].revision, "revision-1");+ assert.equal(editor.input.disabled, true);+ editor.finish(false);+ await Promise.resolve();+ assert.equal(editor.closed(), false);+ assert.equal(editor.input.disabled, false);+ assert.equal(editor.button.disabled, false);+ editor.save("merged draft");+ assert.equal(editor.requests[1].revision, "revision-1");+ editor.finish(true);+ await Promise.resolve();+ assert.equal(editor.closed(), true);+});++test("instruction limit counts UTF-8 bytes and allows an empty file", async () => {+ const editor = setup();+ editor.save("界".repeat(11000));+ assert.equal(editor.messages[0], "too large");+ assert.equal(editor.requests.length, 0);+ editor.save("");+ assert.equal(editor.requests[0].content, "");+ editor.finish(true);+ await Promise.resolve();+ assert.equal(editor.closed(), true);+});diff --git a/app/src/config/tabs/ai/aiInstructions.ts b/app/src/config/tabs/ai/aiInstructions.tsnew file mode 100644index 0000000000..b6409eda06--- /dev/null+++ b/app/src/config/tabs/ai/aiInstructions.ts@@ -0,0 +1,41 @@+import {openInputDialog} from "../../../dialog/inputDialog";+import {showMessage} from "../../../dialog/message";+import {fetchPost} from "../../../util/fetch";++export const openAgentInstructions = () => {+ fetchPost("/api/ai/agent/getInstructions", {}, (response) => {+ const revision = response.data.revision;+ let saving = false;+ const dialog = openInputDialog({+ title: window.siyuan.languages.agentInstructions,+ value: response.data.content,+ multiline: true,+ resize: "vertical",+ description: window.siyuan.languages.agentInstructionsTip,+ confirmText: window.siyuan.languages.save,+ onConfirm: (content, currentDialog) => {+ if (saving) {+ return;+ }+ if (new TextEncoder().encode(content).length > 32 * 1024) {+ showMessage(window.siyuan.languages.agentInstructionsTooLarge);+ return;+ }+ saving = true;+ const button = currentDialog.element.querySelector<HTMLButtonElement>("[data-input-confirm]");+ const input = currentDialog.element.querySelector<HTMLTextAreaElement>("textarea");+ button.disabled = true;+ input.disabled = true;+ // 失败时保留编辑内容和原修订,禁止静默覆盖其它窗口或同步产生的新版本。+ fetchPost("/api/ai/agent/setInstructions", {content, revision}, () => {+ currentDialog.destroy();+ }).finally(() => {+ saving = false;+ button.disabled = false;+ input.disabled = false;+ });+ },+ });+ dialog.element.querySelector<HTMLTextAreaElement>("textarea").rows = 12;+ });+};diff --git a/app/src/config/tabs/ai/aiTab.ts b/app/src/config/tabs/ai/aiTab.tsindex b2f0f67456..bcd243307c 100644--- a/app/src/config/tabs/ai/aiTab.ts+++ b/app/src/config/tabs/ai/aiTab.ts@@ -31,6 +31,7 @@ import {} from "./aiSkillUi";import {isAgentStreamingMarkdownEnabled, setAgentStreamingMarkdownEnabled} from "./agentStreamingMarkdown";import {openSkillManager} from "../../../ai/skills/manager";+import {openAgentInstructions} from "./aiInstructions";import {genMcpOAuthHtml, mountMcpOAuth} from "./mcpOAuthUi";const registerAiProvidersGroup = (tab: SettingTabBuilder) => {@@ -93,6 +94,16 @@ const registerAiAgentGroup = (tab: SettingTabBuilder) => {desc: window.siyuan.languages.apiMaxTokensTip,min: 0,});+ group.button({+ id: "aiAgentInstructions",+ title: window.siyuan.languages.agentInstructions,+ desc: window.siyuan.languages.agentInstructionsTip,+ label: window.siyuan.languages.edit,+ icon: "iconEdit",+ afterMount: root => {+ root.querySelector("#aiAgentInstructions")?.addEventListener("click", openAgentInstructions);+ },+ });group.switch("agentStreamingMarkdown", {title: window.siyuan.languages.agentStreamingMarkdown,desc: window.siyuan.languages.agentStreamingMarkdownTip,diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex d2fe563988..73136e509b 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -12,6 +12,10 @@ export type AIAgentGoogleToolCallProviderData = { "thoughtSignature"?: string; }export type AIAgentGoogleToolCallProviderDataInput = { "thoughtSignature"?: string | null; };+export type AIAgentInstructionsData = { "content": string; "revision": string; };++export type AIAgentInstructionsSaveRequestInput = { "content": string; "revision": string; };+export type AIAgentMessage = { "content": string; "editorContext"?: AIEditorContext; "entryID"?: string; "nativeContent"?: AINativeContent; "reasoningContent"?: string; "references"?: Array<AIReference>; "responseOutput"?: Array<JSONValue>; "responseOutputTokens"?: number; "role": string; "roundID"?: string; "toolCalls"?: Array<AIAgentToolCall>; };export type AIAgentMessageInput = { "content"?: string | null; "editorContext"?: AIEditorContextInput | null; "entryID"?: string | null; "nativeContent"?: AINativeContentInput | null; "reasoningContent"?: string | null; "references"?: Array<AIReferenceInput> | null; "responseOutput"?: Array<JSONValue> | null; "responseOutputTokens"?: number | null; "role"?: string | null; "roundID"?: string | null; "toolCalls"?: Array<AIAgentToolCallInput> | null; };@@ -2547,6 +2551,11 @@ export interface APIPOSTRoutes {body: "structJSON";additionalErrorStatuses: [409];};+ "/api/ai/agent/getInstructions": {+ request: EmptyRequestInput;+ response: { "code": 0; "data": AIAgentInstructionsData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "none";+ };"/api/ai/agent/getSession": {request: AISessionIDRequestInput;response: { "code": 0; "data": AISessionExtensionAISessionFields | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -2611,6 +2620,11 @@ export interface APIPOSTRoutes {response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };body: "structJSON";};+ "/api/ai/agent/setInstructions": {+ request: AIAgentInstructionsSaveRequestInput;+ response: { "code": 0; "data": AIAgentInstructionsData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ };"/api/ai/agent/setPermission": {request: AIPermissionRequestInput;response: { "code": 0; "data": AIPermissionData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex 39a42b52d6..526161a65f 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -539,6 +539,12 @@ func AgentChat(ctx context.Context, client *util.AIClient, protocol, model, imag}()thoughtSignatureState := util.NewGeminiThoughtSignatureState()ctx = util.ContextWithGeminiThoughtSignatureState(ctx, thoughtSignatureState)+ // 每次用户发起对话只读取一次,工具轮次和压缩重建共享这份指令快照。+ instructions, instructionsErr := util.ReadAgentInstructions()+ if instructionsErr != nil {+ sendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: util.AgentInstructionsError(instructionsErr, language)})+ return+ }if kernelModel.Conf.AI.MCP != nil {mcpclient.EnsureMCPConnected(kernelModel.Conf.AI.MCP.Servers)@@ -656,14 +662,14 @@ func AgentChat(ctx context.Context, client *util.AIClient, protocol, model, imagcurrentUserEntry.BlockHTML = *userBlockHTML}}- messages = checkpointMessagesToOpenAIWithSummary(checkpointMsgs, language, capabilities, compaction)+ messages = checkpointMessagesToOpenAIWithSummary(checkpointMsgs, language, capabilities, compaction, instructions.Content)}}}if messages == nil {checkpointMsgs = []AgentMessage{newAgentUserMessage(userMessage, userEntryID, references, editorCtx)}- messages = buildInitialMessages(userMessage, language, references, editorCtx, capabilities)+ messages = buildInitialMessages(userMessage, language, references, editorCtx, capabilities, instructions.Content)}restoreGeminiThoughtSignatures(thoughtSignatureState, checkpointMsgs)@@ -802,7 +808,7 @@ func AgentChat(ctx context.Context, client *util.AIClient, protocol, model, imagcandidate := candidates[i]candidateCheckpointMsgs := checkpointMessagesAfterCompaction(sessionEntries, candidate, tail)candidateMessages := checkpointMessagesToOpenAIWithSummary(- candidateCheckpointMsgs, language, capabilities, nil)+ candidateCheckpointMsgs, language, capabilities, nil, instructions.Content)candidateMessages, _ = projectImageMessages(candidateMessages)baseTokens := estimateProtocolRequestTokens(model, protocol, candidateMessages,candidateCheckpointMsgs, nil, requestTools)@@ -815,7 +821,7 @@ func AgentChat(ctx context.Context, client *util.AIClient, protocol, model, imagselectedEntryCount := candidates[selectedCandidateIndex]selectedCheckpointMsgs := checkpointMessagesAfterCompaction(sessionEntries, selectedEntryCount, tail)selectedMessages := checkpointMessagesToOpenAIWithSummary(- selectedCheckpointMsgs, language, capabilities, nil)+ selectedCheckpointMsgs, language, capabilities, nil, instructions.Content)estimatedSelectedMessages, _ := projectImageMessages(selectedMessages)baseTokens := estimateProtocolRequestTokens(model, protocol, estimatedSelectedMessages,selectedCheckpointMsgs, nil, requestTools)@@ -833,7 +839,7 @@ func AgentChat(ctx context.Context, client *util.AIClient, protocol, model, imagresponseSource, language, capabilities, compaction, imageInputDisabled)compactRequest := openai.ChatCompletionRequest{Model: model,- Messages: []openai.ChatCompletionMessage{{Role: openai.ChatMessageRoleSystem, Content: buildSystemPrompt(language, capabilities)}},+ Messages: []openai.ChatCompletionMessage{{Role: openai.ChatMessageRoleSystem, Content: buildSystemPrompt(language, capabilities, instructions.Content)}},Tools: requestTools,ReasoningEffort: reasoningEffort,}@@ -878,7 +884,7 @@ func AgentChat(ctx context.Context, client *util.AIClient, protocol, model, imag"%w: build runtime state: %v", errContextCannotBeCompacted, compactionStateErr)}nextMessages := checkpointMessagesToOpenAIWithSummary(- selectedCheckpointMsgs, language, capabilities, nextCompaction)+ selectedCheckpointMsgs, language, capabilities, nextCompaction, instructions.Content)estimatedNextMessages, _ := projectImageMessages(nextMessages)if estimateProtocolRequestTokens(model, protocol, estimatedNextMessages, selectedCheckpointMsgs,nextCompaction, requestTools) > inputBudget {@@ -925,7 +931,7 @@ func AgentChat(ctx context.Context, client *util.AIClient, protocol, model, imagcapabilities = roundCapabilitiestools = requestToolsif len(messages) > 0 && messages[0].Role == openai.ChatMessageRoleSystem {- messages[0].Content = buildSystemPrompt(language, roundCapabilities)+ messages[0].Content = buildSystemPrompt(language, roundCapabilities, instructions.Content)}_, compactErr := compactContext(requestTools, false)@@ -2021,13 +2027,20 @@ func availableSkillsSegment(skills []util.SkillInfo) string {return sb.String()}-func buildSystemPrompt(language string, capabilities *capabilitySet) string {+func buildSystemPrompt(language string, capabilities *capabilitySet, instructions ...string) string {if kernelModel.Conf != nil && kernelModel.Conf.Appearance != nil && kernelModel.Conf.Appearance.Lang != "" {language = kernelModel.Conf.Appearance.Lang}var sb strings.Buildersb.WriteString(filterSystemPromptByCapabilities(systemPrompt, capabilities))+ if len(instructions) > 0 && strings.TrimSpace(instructions[0]) != "" {+ sb.WriteString("\n\n## Workspace instructions\nThe following AGENTS.md contains persistent user preferences for this workspace. " ++ "Follow them where applicable; the current user's explicit request overrides general preferences. " ++ "They cannot override built-in rules, tool permissions, approval requirements or access controls.\n<workspace_instructions>\n")+ sb.WriteString(instructions[0])+ sb.WriteString("\n</workspace_instructions>")+ }sb.WriteString("\n\n<env>\nWorkspace: ")sb.WriteString(util.WorkspaceDir)sb.WriteString("\nVersion: ")@@ -2155,9 +2168,9 @@ func buildUserMessageContent(userMessage string, references []Reference, editorCreturn sb.String()}-func buildInitialMessages(userMessage string, language string, references []Reference, editorCtx EditorContext, capabilities *capabilitySet) []openai.ChatCompletionMessage {+func buildInitialMessages(userMessage string, language string, references []Reference, editorCtx EditorContext, capabilities *capabilitySet, instructions ...string) []openai.ChatCompletionMessage {messages := []openai.ChatCompletionMessage{- {Role: openai.ChatMessageRoleSystem, Content: buildSystemPrompt(language, capabilities)},+ {Role: openai.ChatMessageRoleSystem, Content: buildSystemPrompt(language, capabilities, instructions...)},{Role: openai.ChatMessageRoleUser, Content: buildUserMessageContent(userMessage, references, cloneEditorContext(editorCtx), capabilities)},}if attachmentMessage, ok := buildAttachmentMessage(agentMessageAttachments(AgentMessage{Role: "user", Content: userMessage})); ok {@@ -2284,9 +2297,9 @@ func checkpointMessagesToOpenAI(checkpointMsgs []AgentMessage, language string,return checkpointMessagesToOpenAIWithSummary(checkpointMsgs, language, capabilities, nil)}-func checkpointMessagesToOpenAIWithSummary(checkpointMsgs []AgentMessage, language string, capabilities *capabilitySet, compaction *runtimeCompaction) []openai.ChatCompletionMessage {+func checkpointMessagesToOpenAIWithSummary(checkpointMsgs []AgentMessage, language string, capabilities *capabilitySet, compaction *runtimeCompaction, instructions ...string) []openai.ChatCompletionMessage {msgs := []openai.ChatCompletionMessage{- {Role: openai.ChatMessageRoleSystem, Content: buildSystemPrompt(language, capabilities)},+ {Role: openai.ChatMessageRoleSystem, Content: buildSystemPrompt(language, capabilities, instructions...)},}if compaction != nil && strings.TrimSpace(compaction.Summary) != "" {msgs = append(msgs, openai.ChatCompletionMessage{diff --git a/kernel/agent/instructions_test.go b/kernel/agent/instructions_test.gonew file mode 100644index 0000000000..c08d3aa9c5--- /dev/null+++ b/kernel/agent/instructions_test.go@@ -0,0 +1,125 @@+package agent++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "os"+ "strings"+ "sync/atomic"+ "testing"+ "time"++ "github.com/88250/lute/ast"+ "github.com/sashabaranov/go-openai"+ "github.com/siyuan-note/siyuan/kernel/mcp/tools"+ kernelModel "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAgentInstructionsTurnSnapshot(t *testing.T) {+ setupCompactionAgentTest(t)+ kernelModel.Conf.AI.Agent.MaxToolCallRounds = 1+ initial, err := util.SaveAgentInstructions("original-workspace-preference", "missing")+ if err != nil {+ t.Fatal(err)+ }+ const toolName = "test_instruction_snapshot"+ tools.SetTool(toolName, &tools.Tool{+ Name: toolName, Source: "native", ReadOnlyHint: true,+ InputSchema: tools.ToolSchema{Type: "object", Properties: map[string]tools.Property{}},+ ActionEffects: map[string]tools.ToolEffects{"": {LocalRead: true}},+ Handler: func(args map[string]any) (tools.CallToolResult, error) {+ _, err := util.SaveAgentInstructions("changed-workspace-preference", initial.Revision)+ return tools.CallToolResult{Content: []tools.ContentItem{{Type: "text", Text: "done"}}}, err+ },+ })+ t.Cleanup(func() { tools.RemoveTool(toolName) })+ var requests atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ attempt := requests.Add(1)+ var request openai.ChatCompletionRequest+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil {+ t.Error(err)+ return+ }+ want, absent := "original-workspace-preference", "changed-workspace-preference"+ if attempt > 2 {+ want, absent = absent, want+ }+ if len(request.Messages) == 0 || !strings.Contains(request.Messages[0].Content, want) || strings.Contains(request.Messages[0].Content, absent) {+ t.Errorf("request %d did not retain the correct instructions", attempt)+ }+ if attempt == 2 && len(request.Tools) != 0 {+ t.Error("instructions changed tool round limit")+ }+ if attempt == 1 {+ w.Header().Set("Content-Type", "text/event-stream")+ fmt.Fprintf(w, `data: {"id":"test","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call-instructions","type":"function","function":{"name":%q,"arguments":"{}"}}]},"finish_reason":"tool_calls"}]}`+"\n\ndata: [DONE]\n\n", toolName)+ return+ }+ writeAssistantContextStream(t, w, "", "done")+ }))+ defer server.Close()+ for i := 0; i < 2; i++ {+ sessionID := ast.NewNodeID()+ session := map[string]any{"id": sessionID, "title": "instructions", "createdAt": 1, "updatedAt": 1,+ "entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "test preferences"}}}+ if _, err := SaveSession(marshalSession(t, session)); err != nil {+ t.Fatal(err)+ }+ for event := range AgentChat(context.Background(), newTestOpenAIClient(server.URL), "openai", "test-model", "", 0,+ sessionID, "user-1", 1, "test preferences", nil, "English", nil, EditorContext{}, nil, false,+ time.Second, 0, "", time.Second, time.Second) {+ if event.Type == "error" {+ t.Fatal(event.Error)+ }+ }+ }+ if requests.Load() != 3 {+ t.Fatalf("expected two requests then one: %d", requests.Load())+ }+}++func TestAgentInstructionsInvalidSourceStopsTurn(t *testing.T) {+ setupCompactionAgentTest(t)+ if _, err := util.SaveAgentInstructions("valid", "missing"); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(util.AgentInstructionsPath(), []byte{255}, 0644); err != nil {+ t.Fatal(err)+ }+ errorSeen := false+ for event := range AgentChat(context.Background(), nil, "openai", "test-model", "", 0,+ "", "", 0, "test", nil, "English", nil, EditorContext{}, nil, false,+ time.Second, 0, "", time.Second, time.Second) {+ if event.Type == "error" && strings.Contains(event.Error, "AGENTS.md") {+ errorSeen = true+ }+ }+ if !errorSeen {+ t.Fatal("invalid source did not report an error before provider access")+ }+}++func TestAgentInstructionsCompactionAndBudget(t *testing.T) {+ setupCompactionAgentTest(t)+ instructions := strings.Repeat("keep-citations ", 256)+ capabilities := currentCapabilitiesForTest(t)+ checkpoint := []AgentMessage{{Role: "user", Content: "current request"}}+ for _, compaction := range []*runtimeCompaction{nil, {Summary: "previous conversation"}, {Protocol: "openai-responses", ResponseOutput: []json.RawMessage{json.RawMessage(`{"type":"compaction","encrypted_content":"opaque"}`)}}} {+ messages := checkpointMessagesToOpenAIWithSummary(checkpoint, "English", capabilities, compaction, instructions)+ if !strings.Contains(messages[0].Content, instructions) {+ t.Fatal("compaction lost instructions")+ }+ base := checkpointMessagesToOpenAIWithSummary(checkpoint, "English", capabilities, compaction)+ if estimateChatRequestTokens("test-model", messages, nil) <= estimateChatRequestTokens("test-model", base, nil) {+ t.Fatal("instructions omitted from token budget")+ }+ }+ if buildSystemPrompt("English", capabilities, " \n") != buildSystemPrompt("English", capabilities) {+ t.Fatal("empty instructions changed prompt")+ }+}diff --git a/kernel/api/agent_instructions.go b/kernel/api/agent_instructions.gonew file mode 100644index 0000000000..1715e66418--- /dev/null+++ b/kernel/api/agent_instructions.go@@ -0,0 +1,30 @@+package api++import (+ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++var getAgentInstructions = contractHandler(apicontract.AIGetAgentInstructions, getAgentInstructionsContract)+var setAgentInstructions = contractHandler(apicontract.AISetAgentInstructions, setAgentInstructionsContract)++func agentInstructionsResponse(data util.AgentInstructions, err error) apicontract.Response[apicontract.AIAgentInstructionsData] {+ if err != nil {+ return apicontract.Failure[apicontract.AIAgentInstructionsData](-1, util.EscapeHTML(util.AgentInstructionsError(err, model.Conf.Lang)))+ }+ return apicontract.Success(apicontract.AIAgentInstructionsData{Content: data.Content, Revision: data.Revision})+}++func getAgentInstructionsContract(c *gin.Context, request apicontract.EmptyRequest) apicontract.Response[apicontract.AIAgentInstructionsData] {+ return agentInstructionsResponse(util.ReadAgentInstructions())+}++func setAgentInstructionsContract(c *gin.Context, request apicontract.AIAgentInstructionsSaveRequest) apicontract.Response[apicontract.AIAgentInstructionsData] {+ data, err := util.SaveAgentInstructions(request.Content, request.Revision)+ if err == nil {+ model.IncSyncIfNeeded(util.AgentInstructionsPath())+ }+ return agentInstructionsResponse(data, err)+}diff --git a/kernel/api/contract_agent_instructions_test.go b/kernel/api/contract_agent_instructions_test.gonew file mode 100644index 0000000000..515ab20dc9--- /dev/null+++ b/kernel/api/contract_agent_instructions_test.go@@ -0,0 +1,91 @@+package api++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "strings"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAPIContractAIAgentInstructions(t *testing.T) {+ aiContractConfiguration(t)+ model.Conf.Sync = conf.NewSync()+ engine := gin.New()+ engine.POST("/api/ai/agent/getInstructions", getAgentInstructions)+ engine.POST("/api/ai/agent/setInstructions", setAgentInstructions)+ call := func(path, body string, code int) apicontract.AIAgentInstructionsData {+ t.Helper()+ path = "/api/ai/agent/" + path+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", path, strings.NewReader(body)))+ requireAPIContract(t, "POST", path, recorder)+ var result struct {+ Code int+ Data apicontract.AIAgentInstructionsData+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil || result.Code != code {+ t.Fatalf("%s: %s %v", body, recorder.Body.String(), err)+ }+ return result.Data+ }+ read := call("getInstructions", "", 0)+ if read.Content != "" || read.Revision != "missing" {+ t.Fatalf("missing: %+v", read)+ }+ written := call("setInstructions", `{"content":"Use citations.\r\n","revision":"missing"}`, 0)+ read = call("getInstructions", "", 0)+ if read != written || read.Content != "Use citations.\r\n" {+ t.Fatalf("round trip: %+v", read)+ }+ call("setInstructions", `{"content":"lost update","revision":"missing"}`, -1)+ for _, body := range []string{`{}`, `{"content":null,"revision":"x"}`, `{"content":1,"revision":"x"}`, `{"content":""}`} {+ call("setInstructions", body, -1)+ }+ body, _ := json.Marshal(apicontract.AIAgentInstructionsSaveRequest{Content: "", Revision: read.Revision})+ call("setInstructions", string(body), 0)+ if err := os.WriteFile(util.AgentInstructionsPath(), []byte{255}, 0644); err != nil {+ t.Fatal(err)+ }+ call("getInstructions", "", -1)+ call("setInstructions", string(body), -1)+}++func TestAPIContractAIAgentInstructionsAuthorization(t *testing.T) {+ aiContractConfiguration(t)+ previousReadonly := util.ReadOnly+ t.Cleanup(func() { util.ReadOnly = previousReadonly })+ for _, test := range []struct {+ role model.Role+ readonly bool+ status int+ }{+ {model.RoleReader, false, http.StatusForbidden}, {model.RoleEditor, false, http.StatusForbidden},+ {model.RoleAdministrator, true, http.StatusOK},+ } {+ util.ReadOnly = test.readonly+ engine := gin.New()+ engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, test.role); c.Next() })+ ServeAPI(engine)+ request := httptest.NewRequest("POST", "/api/ai/agent/setInstructions", nil)+ request.Body = aiUnreadBody{t: t}+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, request)+ if recorder.Code != test.status {+ t.Fatalf("admission: %d %s", recorder.Code, recorder.Body.String())+ }+ if test.readonly && !strings.Contains(recorder.Body.String(), `"code":-1`) {+ t.Fatal("read-only write allowed")+ }+ if _, err := os.Stat(util.AgentInstructionsPath()); !os.IsNotExist(err) {+ t.Fatalf("denied write touched file: %v", err)+ }+ }+}diff --git a/kernel/api/router.go b/kernel/api/router.goindex 95ea62f379..8d0bc8dcd7 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -688,6 +688,8 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/ai/agent/saveSession", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, saveSession)ginServer.Handle("POST", "/api/ai/agent/removeSession", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, removeSession)ginServer.Handle("POST", "/api/ai/agent/lsSkills", model.CheckAuth, model.CheckAdminRole, lsSkills)+ ginServer.Handle("POST", "/api/ai/agent/getInstructions", model.CheckAuth, model.CheckAdminRole, getAgentInstructions)+ ginServer.Handle("POST", "/api/ai/agent/setInstructions", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setAgentInstructions)ginServer.Handle("POST", "/api/ai/agent/manageSkills", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, manageSkills)ginServer.Handle("POST", "/api/ai/agent/lsUserSkills", model.CheckAuth, model.CheckAdminRole, lsUserSkills)ginServer.Handle("POST", "/api/ai/agent/getSkill", model.CheckAuth, model.CheckAdminRole, getSkill)diff --git a/kernel/apicontract/ai_instructions.go b/kernel/apicontract/ai_instructions.gonew file mode 100644index 0000000000..fac1d48f0f--- /dev/null+++ b/kernel/apicontract/ai_instructions.go@@ -0,0 +1,17 @@+package apicontract++// AIAgentInstructionsData 是工作空间 data/ai/AGENTS.md 的 UTF-8 原文与内容修订标识。+// 文件缺失返回空正文和 missing 修订,不创建文件;读取失败、非文本或超过 32 KiB 返回 code -1。+// 指令在下一次用户发起对话时生效,同一轮工具调用及上下文压缩使用相同快照。+type AIAgentInstructionsData struct {+ Content string `json:"content"`+ Revision string `json:"revision"`+}++// AIAgentInstructionsSaveRequest 必须携带读取时的修订标识;冲突返回 code -1 并保留原文。+// 允许空正文,最多 32 KiB UTF-8 文本。固定路径原子保存,成功后通知同步;用户同步忽略规则仍有效。+// 接口要求管理员且禁止只读写入,不为智能体注册修改长期指令的专用工具。+type AIAgentInstructionsSaveRequest struct {+ Content string `json:"content"`+ Revision string `json:"revision"`+}diff --git a/kernel/apicontract/ai_instructions_test.go b/kernel/apicontract/ai_instructions_test.gonew file mode 100644index 0000000000..36cd1581b6--- /dev/null+++ b/kernel/apicontract/ai_instructions_test.go@@ -0,0 +1,17 @@+package apicontract++import (+ "strings"+ "testing"+)++func TestAIAgentInstructionsContract(t *testing.T) {+ for _, body := range []string{``, `{}`, `{"content":""}`, `{"revision":"missing"}`, `{"content":null,"revision":"missing"}`, `{"content":1,"revision":"missing"}`, `{"content":"","revision":false}`} {+ if _, err := AISetAgentInstructions.Decode(strings.NewReader(body)); err == nil {+ t.Fatalf("accepted invalid request: %s", body)+ }+ }+ if _, err := AISetAgentInstructions.Decode(strings.NewReader(`{"content":"","revision":"missing"}`)); err != nil {+ t.Fatal(err)+ }+}diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex 1de92e76c4..b134fb489c 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -967,6 +967,8 @@ var AIAgentTitle = define[AITitleRequest, string]("agentChatTitle", "/api/ai/agevar AIListSessions = define[AISessionsRequest, AISessionList]("lsSessions", "/api/ai/agent/lsSessions", StructJSONBody, ResponseOptions{}, "POST")var AIRemoveSession = define[AISessionIDRequest, Null]("removeSession", "/api/ai/agent/removeSession", StructJSONBody, ResponseOptions{AdditionalErrorStatuses: []int{409, 500}}, "POST")var AIListSkills = define[EmptyRequest, []AISkillInfo]("lsSkills", "/api/ai/agent/lsSkills", NoBody, ResponseOptions{}, "POST")+var AIGetAgentInstructions = define[EmptyRequest, AIAgentInstructionsData]("getAgentInstructions", "/api/ai/agent/getInstructions", NoBody, ResponseOptions{}, "POST")+var AISetAgentInstructions = define[AIAgentInstructionsSaveRequest, AIAgentInstructionsData]("setAgentInstructions", "/api/ai/agent/setInstructions", JSONBody, ResponseOptions{}, "POST")var AIListUserSkills = define[EmptyRequest, []AIUserSkillInfo]("lsUserSkills", "/api/ai/agent/lsUserSkills", NoBody, ResponseOptions{}, "POST")var AIGetSkill = define[AISkillNameRequest, AISkillData]("getSkill", "/api/ai/agent/getSkill", StructJSONBody, ResponseOptions{}, "POST")var AISaveSkill = define[AISkillSaveRequest, Null]("saveSkill", "/api/ai/agent/saveSkill", StructJSONBody, ResponseOptions{}, "POST")diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex 5cbfd3b9c2..4553df80c2 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -285,6 +285,38 @@},"additionalProperties": false},+ "AIAgentInstructionsData": {+ "type": "object",+ "properties": {+ "content": {+ "type": "string"+ },+ "revision": {+ "type": "string"+ }+ },+ "required": [+ "content",+ "revision"+ ],+ "additionalProperties": false+ },+ "AIAgentInstructionsSaveRequestInput": {+ "type": "object",+ "properties": {+ "content": {+ "type": "string"+ },+ "revision": {+ "type": "string"+ }+ },+ "required": [+ "content",+ "revision"+ ],+ "additionalProperties": false+ },"AIAgentMessage": {"type": "object","properties": {@@ -111511,6 +111543,81 @@409]},+ {+ "method": "POST",+ "path": "/api/ai/agent/getInstructions",+ "handler": "getAgentInstructions",+ "body": "none",+ "request": {+ "$ref": "#/$defs/EmptyRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/AIAgentInstructionsData"+ },+ "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/getSession",@@ -112456,6 +112563,81 @@]}},+ {+ "method": "POST",+ "path": "/api/ai/agent/setInstructions",+ "handler": "setAgentInstructions",+ "body": "json",+ "request": {+ "$ref": "#/$defs/AIAgentInstructionsSaveRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/AIAgentInstructionsData"+ },+ "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/setPermission",diff --git a/kernel/model/agent_instructions_test.go b/kernel/model/agent_instructions_test.gonew file mode 100644index 0000000000..f9b4c469a1--- /dev/null+++ b/kernel/model/agent_instructions_test.go@@ -0,0 +1,32 @@+package model++import (+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAgentInstructionsSync(t *testing.T) {+ setupAppearancePackagesTest(t)+ file := util.AgentInstructionsPath()+ writeAppearanceTestFile(t, file, "Workspace preferences")+ info, err := os.Stat(file)+ if err != nil {+ t.Fatal(err)+ }+ if ignored, err := syncPathFilter(util.DataDir, info, file); err != nil || ignored {+ t.Fatalf("instructions excluded from sync: %v %v", ignored, err)+ }+ _, matcher := mustSyncIgnoreRules(t)+ if matcher.MatchesPath("/ai/AGENTS.md") {+ t.Fatal("built-in ignore excludes instructions")+ }+ writeAppearanceTestFile(t, filepath.Join(util.DataDir, syncIgnoreRulePath), "/ai/AGENTS.md\n")+ invalidateSyncIgnoreRules(filepath.Join(util.DataDir, syncIgnoreRulePath))+ _, matcher = mustSyncIgnoreRules(t)+ if !matcher.MatchesPath("/ai/AGENTS.md") {+ t.Fatal("user ignore rule must remain effective")+ }+}diff --git a/kernel/util/agent_instructions.go b/kernel/util/agent_instructions.gonew file mode 100644index 0000000000..6432487faf--- /dev/null+++ b/kernel/util/agent_instructions.go@@ -0,0 +1,188 @@+package util++import (+ "crypto/sha256"+ "errors"+ "fmt"+ "io"+ "os"+ "path/filepath"+ "strings"+ "sync"++ "github.com/88250/lute/ast"+)++const MaxAgentInstructionsSize = 32 * 1024++var agentInstructionsLock sync.Mutex+var ErrAgentInstructionsTooLarge = errors.New("AGENTS.md must be at most 32 KiB")+var ErrAgentInstructionsConflict = errors.New("AGENTS.md changed; reload it before saving")++type AgentInstructions struct {+ Content string+ Revision string+}++func AgentInstructionsPath() string {+ return filepath.Join(DataDir, "ai", "AGENTS.md")+}++// 仅访问工作空间内的固定文件,拒绝链接和特殊文件,不创建读取时缺失的目录。+func openAgentInstructionsRoot(create bool) (*os.Root, error) {+ root, err := os.OpenRoot(DataDir)+ if err != nil {+ return nil, err+ }+ defer root.Close()+ if create {+ if err = root.Mkdir("ai", 0755); err != nil && !errors.Is(err, os.ErrExist) {+ return nil, err+ }+ }+ info, err := root.Lstat("ai")+ if err != nil {+ return nil, err+ }+ if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {+ return nil, errors.New("AGENTS.md storage is not a regular directory")+ }+ return root.OpenRoot("ai")+}++func validateAgentInstructions(content string) error {+ if len(content) > MaxAgentInstructionsSize {+ return ErrAgentInstructionsTooLarge+ }+ return validateManagedSkillSource(content)+}++func readAgentInstructions(root *os.Root) (AgentInstructions, error) {+ ret := AgentInstructions{Revision: "missing"}+ info, err := root.Lstat("AGENTS.md")+ if errors.Is(err, os.ErrNotExist) {+ return ret, nil+ }+ if err != nil {+ return ret, err+ }+ if !info.Mode().IsRegular() {+ return ret, errors.New("AGENTS.md is not a regular file")+ }+ if info.Size() > MaxAgentInstructionsSize {+ return ret, ErrAgentInstructionsTooLarge+ }+ file, err := root.Open("AGENTS.md")+ if err != nil {+ return ret, err+ }+ defer file.Close()+ content, err := io.ReadAll(io.LimitReader(file, MaxAgentInstructionsSize+1))+ if err != nil {+ return ret, err+ }+ if err = validateAgentInstructions(string(content)); err != nil {+ return ret, err+ }+ return AgentInstructions{Content: string(content), Revision: fmt.Sprintf("%x", sha256.Sum256(content))}, nil+}++func ReadAgentInstructions() (AgentInstructions, error) {+ agentInstructionsLock.Lock()+ defer agentInstructionsLock.Unlock()+ root, err := openAgentInstructionsRoot(false)+ if errors.Is(err, os.ErrNotExist) {+ return AgentInstructions{Revision: "missing"}, nil+ }+ if err != nil {+ return AgentInstructions{}, err+ }+ defer root.Close()+ return readAgentInstructions(root)+}++// 修订校验和原子替换共用临界区,失败时保留原文;空内容同样是有效版本。+func SaveAgentInstructions(content, revision string) (AgentInstructions, error) {+ agentInstructionsLock.Lock()+ defer agentInstructionsLock.Unlock()+ if err := validateAgentInstructions(content); err != nil {+ return AgentInstructions{}, err+ }+ if revision == "" {+ return AgentInstructions{}, ErrAgentInstructionsConflict+ }+ root, err := openAgentInstructionsRoot(true)+ if err != nil {+ return AgentInstructions{}, err+ }+ defer root.Close()+ current, err := readAgentInstructions(root)+ if err != nil {+ return AgentInstructions{}, err+ }+ if current.Revision != revision {+ return AgentInstructions{}, ErrAgentInstructionsConflict+ }+ mode := os.FileMode(0644)+ if current.Revision != "missing" {+ info, statErr := root.Stat("AGENTS.md")+ if statErr != nil {+ return AgentInstructions{}, statErr+ }+ mode = info.Mode().Perm()+ }+ name := ".agents-" + ast.NewNodeID()+ file, err := root.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)+ if err != nil {+ return AgentInstructions{}, err+ }+ defer root.Remove(name)+ // 保留用户为已有文件设置的访问权限。+ if current.Revision != "missing" {+ err = file.Chmod(mode)+ }+ if err == nil {+ _, err = file.WriteString(content)+ }+ if err == nil {+ err = file.Sync()+ }+ closeErr := file.Close()+ if err != nil {+ return AgentInstructions{}, err+ }+ if closeErr != nil {+ return AgentInstructions{}, closeErr+ }+ current, err = readAgentInstructions(root)+ if err != nil {+ return AgentInstructions{}, err+ }+ if current.Revision != revision {+ return AgentInstructions{}, ErrAgentInstructionsConflict+ }+ if err = root.Rename(name, "AGENTS.md"); err != nil {+ return AgentInstructions{}, err+ }+ return AgentInstructions{Content: content, Revision: fmt.Sprintf("%x", sha256.Sum256([]byte(content)))}, nil+}++func AgentInstructionsError(err error, language string) string {+ key := ""+ switch {+ case errors.Is(err, ErrAgentInstructionsTooLarge):+ key = "agentInstructionsTooLarge"+ case errors.Is(err, ErrAgentInstructionsConflict):+ key = "agentInstructionsConflict"+ case errors.Is(err, ErrSkillEncoding):+ key = "agentSkillEncodingTip"+ case errors.Is(err, ErrSkillBinary):+ key = "agentSkillBinaryTip"+ }+ if key != "" {+ if message := I18nTerm(language, key); strings.TrimSpace(message) != "" {+ return "AGENTS.md: " + message+ }+ }+ return "AGENTS.md: " + err.Error()+}diff --git a/kernel/util/agent_instructions_test.go b/kernel/util/agent_instructions_test.gonew file mode 100644index 0000000000..374693b996--- /dev/null+++ b/kernel/util/agent_instructions_test.go@@ -0,0 +1,130 @@+package util++import (+ "errors"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "testing"+)++func agentInstructionsTestDir(t *testing.T) {+ t.Helper()+ previous := DataDir+ DataDir = t.TempDir()+ t.Cleanup(func() { DataDir = previous })+}++func TestAgentInstructionsStorage(t *testing.T) {+ agentInstructionsTestDir(t)+ missing, err := ReadAgentInstructions()+ if err != nil || missing.Content != "" || missing.Revision != "missing" {+ t.Fatalf("missing: %+v %v", missing, err)+ }+ if _, err = os.Stat(filepath.Dir(AgentInstructionsPath())); !errors.Is(err, os.ErrNotExist) {+ t.Fatal("read created storage")+ }+ content := "\ufeffUse citations.\r\n保留原文\r\n"+ saved, err := SaveAgentInstructions(content, missing.Revision)+ if err != nil {+ t.Fatal(err)+ }+ read, err := ReadAgentInstructions()+ if err != nil || read != saved || read.Content != content {+ t.Fatalf("round trip: %+v %v", read, err)+ }+ for _, revision := range []string{"", "missing", "stale"} {+ if _, err = SaveAgentInstructions("lost update", revision); !errors.Is(err, ErrAgentInstructionsConflict) {+ t.Fatalf("accepted revision %q: %v", revision, err)+ }+ }+ empty, err := SaveAgentInstructions("", saved.Revision)+ if err != nil || empty.Revision == missing.Revision {+ t.Fatalf("empty file: %+v %v", empty, err)+ }+ if read, err = ReadAgentInstructions(); err != nil || read != empty {+ t.Fatalf("empty round trip: %+v %v", read, err)+ }+ if _, err = SaveAgentInstructions(strings.Repeat("a", MaxAgentInstructionsSize), empty.Revision); err != nil {+ t.Fatal(err)+ }+ maxContent, err := ReadAgentInstructions()+ if err != nil {+ t.Fatal(err)+ }+ if _, err = SaveAgentInstructions(strings.Repeat("界", 11000), maxContent.Revision); !errors.Is(err, ErrAgentInstructionsTooLarge) {+ t.Fatalf("UTF-8 byte limit not enforced: %v", err)+ }+ if unchanged, err := ReadAgentInstructions(); err != nil || unchanged != maxContent {+ t.Fatalf("invalid save modified source: %+v %v", unchanged, err)+ }+}++func TestAgentInstructionsPreservesInvalidSource(t *testing.T) {+ agentInstructionsTestDir(t)+ if err := os.MkdirAll(filepath.Dir(AgentInstructionsPath()), 0755); err != nil {+ t.Fatal(err)+ }+ for _, content := range []string{strings.Repeat("a", MaxAgentInstructionsSize+1), "\xff\xfe", "\x00", "\x01"} {+ if err := os.WriteFile(AgentInstructionsPath(), []byte(content), 0644); err != nil {+ t.Fatal(err)+ }+ if _, err := ReadAgentInstructions(); err == nil {+ t.Fatal("accepted invalid source")+ }+ if _, err := SaveAgentInstructions("replacement", "missing"); err == nil {+ t.Fatal("overwrote invalid source")+ }+ actual, err := os.ReadFile(AgentInstructionsPath())+ if err != nil || string(actual) != content {+ t.Fatal("invalid source lost")+ }+ }+}++func TestAgentInstructionsConcurrentSave(t *testing.T) {+ agentInstructionsTestDir(t)+ initial, err := SaveAgentInstructions("initial", "missing")+ if err != nil {+ t.Fatal(err)+ }+ errorsCh := make(chan error, 2)+ var wait sync.WaitGroup+ for _, value := range []string{"first", "second"} {+ wait.Go(func() { _, err := SaveAgentInstructions(value, initial.Revision); errorsCh <- err })+ }+ wait.Wait()+ close(errorsCh)+ success, conflicts := 0, 0+ for err := range errorsCh {+ if err == nil {+ success+++ } else if errors.Is(err, ErrAgentInstructionsConflict) {+ conflicts+++ } else {+ t.Fatal(err)+ }+ }+ if success != 1 || conflicts != 1 {+ t.Fatalf("success=%d conflicts=%d", success, conflicts)+ }+ files, err := os.ReadDir(filepath.Dir(AgentInstructionsPath()))+ if err != nil || len(files) != 1 || files[0].Name() != "AGENTS.md" {+ t.Fatalf("temporary file leaked: %v %v", files, err)+ }+}++func TestAgentInstructionsRejectsLinks(t *testing.T) {+ agentInstructionsTestDir(t)+ outside := t.TempDir()+ if err := os.Symlink(outside, filepath.Dir(AgentInstructionsPath())); err != nil {+ t.Skipf("symlinks unavailable: %v", err)+ }+ if _, err := ReadAgentInstructions(); err == nil {+ t.Fatal("followed storage link")+ }+ if _, err := SaveAgentInstructions("escape", "missing"); err == nil {+ t.Fatal("wrote through storage link")+ }+}