myagent-ai 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (486) hide show
  1. package/Dockerfile +30 -0
  2. package/README.md +333 -0
  3. package/agents/__init__.py +6 -0
  4. package/agents/__pycache__/main_agent.cpython-312.pyc +0 -0
  5. package/agents/base.py +115 -0
  6. package/agents/main_agent.py +695 -0
  7. package/agents/memory_agent.py +313 -0
  8. package/agents/tool_agent.py +248 -0
  9. package/chatbot/__init__.py +5 -0
  10. package/chatbot/base.py +124 -0
  11. package/chatbot/discord_bot.py +146 -0
  12. package/chatbot/feishu_bot.py +548 -0
  13. package/chatbot/manager.py +164 -0
  14. package/chatbot/qq_bot.py +189 -0
  15. package/chatbot/telegram_bot.py +167 -0
  16. package/chatbot/wechat_bot.py +558 -0
  17. package/communication/__init__.py +66 -0
  18. package/communication/channel.py +576 -0
  19. package/communication/crypto.py +347 -0
  20. package/communication/manager.py +397 -0
  21. package/communication/peer.py +156 -0
  22. package/config.py +464 -0
  23. package/core/__init__.py +10 -0
  24. package/core/config_broadcast.py +276 -0
  25. package/core/llm.py +878 -0
  26. package/core/logger.py +241 -0
  27. package/core/task_queue.py +362 -0
  28. package/core/utils.py +184 -0
  29. package/executor/__init__.py +4 -0
  30. package/executor/__pycache__/engine.cpython-312.pyc +0 -0
  31. package/executor/engine.py +1215 -0
  32. package/groups/__init__.py +15 -0
  33. package/groups/manager.py +724 -0
  34. package/knowledge/__init__.py +4 -0
  35. package/knowledge/rag.py +444 -0
  36. package/main.py +801 -0
  37. package/memory/__init__.py +4 -0
  38. package/memory/manager.py +840 -0
  39. package/organization/__init__.py +4 -0
  40. package/organization/manager.py +350 -0
  41. package/package.json +58 -0
  42. package/requirements.txt +59 -0
  43. package/setup.py +40 -0
  44. package/skills/ASR/LICENSE.txt +21 -0
  45. package/skills/ASR/SKILL.md +580 -0
  46. package/skills/ASR/scripts/asr.ts +27 -0
  47. package/skills/LLM/LICENSE.txt +21 -0
  48. package/skills/LLM/SKILL.md +856 -0
  49. package/skills/LLM/scripts/chat.ts +32 -0
  50. package/skills/TTS/LICENSE.txt +21 -0
  51. package/skills/TTS/SKILL.md +735 -0
  52. package/skills/TTS/tts.ts +25 -0
  53. package/skills/VLM/LICENSE.txt +21 -0
  54. package/skills/VLM/SKILL.md +588 -0
  55. package/skills/VLM/scripts/vlm.ts +57 -0
  56. package/skills/__init__.py +5 -0
  57. package/skills/agent-browser/SKILL.md +328 -0
  58. package/skills/ai-news-collectors/SKILL.md +157 -0
  59. package/skills/ai-news-collectors/_meta.json +6 -0
  60. package/skills/ai-news-collectors/references/sources.md +128 -0
  61. package/skills/aminer-open-academic/SKILL.md +312 -0
  62. package/skills/aminer-open-academic/_meta.json +6 -0
  63. package/skills/aminer-open-academic/evals/evals.json +46 -0
  64. package/skills/aminer-open-academic/references/api-catalog.md +1032 -0
  65. package/skills/aminer-open-academic/scripts/__pycache__/aminer_client.cpython-312.pyc +0 -0
  66. package/skills/aminer-open-academic/scripts/aminer_client.py +875 -0
  67. package/skills/auto-target-tracker/SKILL.md +317 -0
  68. package/skills/base.py +147 -0
  69. package/skills/blog-writer/2024-02-17-radical-transparency-sales.md +35 -0
  70. package/skills/blog-writer/2024-02-17-raycast-spotlight-superpowers.md +33 -0
  71. package/skills/blog-writer/2024-02-17-short-form-content-marketing.md +47 -0
  72. package/skills/blog-writer/2024-02-17-typing-speed-benefits.md +33 -0
  73. package/skills/blog-writer/2024-03-14-effective-ai-prompts.md +55 -0
  74. package/skills/blog-writer/2024-11-08-ai-revolutionizing-entry-level-sales.md +43 -0
  75. package/skills/blog-writer/2025-11-12-why-ai-art-is-useless.md +49 -0
  76. package/skills/blog-writer/README.md +2 -0
  77. package/skills/blog-writer/SKILL.md +158 -0
  78. package/skills/blog-writer/__pycache__/manage_examples.cpython-312.pyc +0 -0
  79. package/skills/blog-writer/_meta.json +6 -0
  80. package/skills/blog-writer/manage_examples.py +90 -0
  81. package/skills/blog-writer/style-guide.md +160 -0
  82. package/skills/browser_skill.py +146 -0
  83. package/skills/coding-agent/SKILL.md +120 -0
  84. package/skills/coding-agent/_meta.json +6 -0
  85. package/skills/coding-agent/criteria.md +48 -0
  86. package/skills/coding-agent/execution.md +42 -0
  87. package/skills/coding-agent/memory-template.md +38 -0
  88. package/skills/coding-agent/planning.md +31 -0
  89. package/skills/coding-agent/state.md +60 -0
  90. package/skills/coding-agent/verification.md +39 -0
  91. package/skills/content-strategy/SKILL.md +181 -0
  92. package/skills/content-strategy/_meta.json +6 -0
  93. package/skills/contentanalysis/ExtractWisdom/SKILL.md +229 -0
  94. package/skills/contentanalysis/ExtractWisdom/Workflows/Extract.md +60 -0
  95. package/skills/contentanalysis/SKILL.md +14 -0
  96. package/skills/docx/CHANGELOG.md +85 -0
  97. package/skills/docx/LICENSE.txt +30 -0
  98. package/skills/docx/SKILL.md +455 -0
  99. package/skills/docx/docx-js.md +681 -0
  100. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-chart.xsd +1499 -0
  101. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd +146 -0
  102. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd +1085 -0
  103. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd +11 -0
  104. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-main.xsd +3081 -0
  105. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-picture.xsd +23 -0
  106. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd +185 -0
  107. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd +287 -0
  108. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/pml.xsd +1676 -0
  109. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd +28 -0
  110. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd +144 -0
  111. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd +174 -0
  112. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd +25 -0
  113. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd +18 -0
  114. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd +59 -0
  115. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd +56 -0
  116. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd +195 -0
  117. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-math.xsd +582 -0
  118. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd +25 -0
  119. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/sml.xsd +4439 -0
  120. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/vml-main.xsd +570 -0
  121. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd +509 -0
  122. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd +12 -0
  123. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd +108 -0
  124. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd +96 -0
  125. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/wml.xsd +3646 -0
  126. package/skills/docx/ooxml/schemas/ISO-IEC29500-4_2016/xml.xsd +116 -0
  127. package/skills/docx/ooxml/schemas/ecma/fouth-edition/opc-contentTypes.xsd +42 -0
  128. package/skills/docx/ooxml/schemas/ecma/fouth-edition/opc-coreProperties.xsd +50 -0
  129. package/skills/docx/ooxml/schemas/ecma/fouth-edition/opc-digSig.xsd +49 -0
  130. package/skills/docx/ooxml/schemas/ecma/fouth-edition/opc-relationships.xsd +33 -0
  131. package/skills/docx/ooxml/schemas/mce/mc.xsd +75 -0
  132. package/skills/docx/ooxml/schemas/microsoft/wml-2010.xsd +560 -0
  133. package/skills/docx/ooxml/schemas/microsoft/wml-2012.xsd +67 -0
  134. package/skills/docx/ooxml/schemas/microsoft/wml-2018.xsd +14 -0
  135. package/skills/docx/ooxml/schemas/microsoft/wml-cex-2018.xsd +20 -0
  136. package/skills/docx/ooxml/schemas/microsoft/wml-cid-2016.xsd +13 -0
  137. package/skills/docx/ooxml/schemas/microsoft/wml-sdtdatahash-2020.xsd +4 -0
  138. package/skills/docx/ooxml/schemas/microsoft/wml-symex-2015.xsd +8 -0
  139. package/skills/docx/ooxml/scripts/__pycache__/pack.cpython-312.pyc +0 -0
  140. package/skills/docx/ooxml/scripts/__pycache__/unpack.cpython-312.pyc +0 -0
  141. package/skills/docx/ooxml/scripts/__pycache__/validate.cpython-312.pyc +0 -0
  142. package/skills/docx/ooxml/scripts/pack.py +159 -0
  143. package/skills/docx/ooxml/scripts/unpack.py +29 -0
  144. package/skills/docx/ooxml/scripts/validate.py +69 -0
  145. package/skills/docx/ooxml/scripts/validation/__init__.py +15 -0
  146. package/skills/docx/ooxml/scripts/validation/__pycache__/__init__.cpython-312.pyc +0 -0
  147. package/skills/docx/ooxml/scripts/validation/__pycache__/base.cpython-312.pyc +0 -0
  148. package/skills/docx/ooxml/scripts/validation/__pycache__/docx.cpython-312.pyc +0 -0
  149. package/skills/docx/ooxml/scripts/validation/__pycache__/pptx.cpython-312.pyc +0 -0
  150. package/skills/docx/ooxml/scripts/validation/__pycache__/redlining.cpython-312.pyc +0 -0
  151. package/skills/docx/ooxml/scripts/validation/base.py +951 -0
  152. package/skills/docx/ooxml/scripts/validation/docx.py +274 -0
  153. package/skills/docx/ooxml/scripts/validation/pptx.py +315 -0
  154. package/skills/docx/ooxml/scripts/validation/redlining.py +279 -0
  155. package/skills/docx/ooxml.md +615 -0
  156. package/skills/docx/scripts/__init__.py +1 -0
  157. package/skills/docx/scripts/__pycache__/__init__.cpython-312.pyc +0 -0
  158. package/skills/docx/scripts/__pycache__/add_toc_placeholders.cpython-312.pyc +0 -0
  159. package/skills/docx/scripts/__pycache__/document.cpython-312.pyc +0 -0
  160. package/skills/docx/scripts/__pycache__/utilities.cpython-312.pyc +0 -0
  161. package/skills/docx/scripts/add_toc_placeholders.py +220 -0
  162. package/skills/docx/scripts/document.py +1302 -0
  163. package/skills/docx/scripts/templates/comments.xml +3 -0
  164. package/skills/docx/scripts/templates/commentsExtended.xml +3 -0
  165. package/skills/docx/scripts/templates/commentsExtensible.xml +3 -0
  166. package/skills/docx/scripts/templates/commentsIds.xml +3 -0
  167. package/skills/docx/scripts/templates/people.xml +3 -0
  168. package/skills/docx/scripts/utilities.py +374 -0
  169. package/skills/dream-interpreter/SKILL.md +88 -0
  170. package/skills/dream-interpreter/assets/example_asset.txt +24 -0
  171. package/skills/dream-interpreter/references/api_reference.md +34 -0
  172. package/skills/dream-interpreter/references/interpretation-guide.md +83 -0
  173. package/skills/dream-interpreter/references/output-schema.md +65 -0
  174. package/skills/dream-interpreter/references/questioning-strategy.md +62 -0
  175. package/skills/dream-interpreter/references/visual-mapping.md +81 -0
  176. package/skills/dream-interpreter/scripts/__pycache__/example.cpython-312.pyc +0 -0
  177. package/skills/dream-interpreter/scripts/example.py +19 -0
  178. package/skills/dream-interpreter/skill.json +7 -0
  179. package/skills/file_skill.py +246 -0
  180. package/skills/finance/Finance_API_Doc.md +445 -0
  181. package/skills/finance/SKILL.md +53 -0
  182. package/skills/fullstack-dev/SKILL.md +205 -0
  183. package/skills/get-fortune-analysis/SKILL.md +370 -0
  184. package/skills/get-fortune-analysis/lunar_python.py +91 -0
  185. package/skills/gift-evaluator/SKILL.md +83 -0
  186. package/skills/gift-evaluator/__pycache__/html_tools.cpython-312.pyc +0 -0
  187. package/skills/gift-evaluator/html_tools.py +268 -0
  188. package/skills/image-edit/LICENSE.txt +21 -0
  189. package/skills/image-edit/SKILL.md +896 -0
  190. package/skills/image-edit/scripts/image-edit.ts +36 -0
  191. package/skills/image-generation/LICENSE.txt +21 -0
  192. package/skills/image-generation/SKILL.md +583 -0
  193. package/skills/image-generation/scripts/image-generation.ts +28 -0
  194. package/skills/image-understand/LICENSE.txt +21 -0
  195. package/skills/image-understand/SKILL.md +855 -0
  196. package/skills/image-understand/scripts/image-understand.ts +41 -0
  197. package/skills/interview-designer/README.md +70 -0
  198. package/skills/interview-designer/SKILL.md +53 -0
  199. package/skills/interview-designer/_meta.json +6 -0
  200. package/skills/interview-designer/references/design_rationale.md +43 -0
  201. package/skills/interview-designer/templates/interview_guide_template.md +62 -0
  202. package/skills/market-research-reports/SKILL.md +901 -0
  203. package/skills/market-research-reports/assets/FORMATTING_GUIDE.md +428 -0
  204. package/skills/market-research-reports/assets/market_report_template.tex +1380 -0
  205. package/skills/market-research-reports/assets/market_research.sty +564 -0
  206. package/skills/market-research-reports/references/data_analysis_patterns.md +548 -0
  207. package/skills/market-research-reports/references/report_structure_guide.md +999 -0
  208. package/skills/market-research-reports/references/visual_generation_guide.md +1077 -0
  209. package/skills/market-research-reports/scripts/__pycache__/generate_market_visuals.cpython-312.pyc +0 -0
  210. package/skills/market-research-reports/scripts/generate_market_visuals.py +529 -0
  211. package/skills/marketing-mode/README.md +49 -0
  212. package/skills/marketing-mode/SKILL.md +693 -0
  213. package/skills/marketing-mode/_meta.json +6 -0
  214. package/skills/marketing-mode/mode-prompt.md +39 -0
  215. package/skills/marketing-mode/skill.json +51 -0
  216. package/skills/mindfulness-meditation/SKILL.md +65 -0
  217. package/skills/mindfulness-meditation/_meta.json +6 -0
  218. package/skills/multi-search-engine/CHANGELOG.md +15 -0
  219. package/skills/multi-search-engine/CHANNELLOG.md +48 -0
  220. package/skills/multi-search-engine/SKILL.md +78 -0
  221. package/skills/multi-search-engine/_meta.json +6 -0
  222. package/skills/multi-search-engine/config.json +14 -0
  223. package/skills/multi-search-engine/metadata.json +7 -0
  224. package/skills/multi-search-engine/references/international-search.md +651 -0
  225. package/skills/pdf/LICENSE.txt +30 -0
  226. package/skills/pdf/SKILL.md +1534 -0
  227. package/skills/pdf/forms.md +205 -0
  228. package/skills/pdf/reference.md +765 -0
  229. package/skills/pdf/scripts/__pycache__/add_zai_metadata.cpython-312.pyc +0 -0
  230. package/skills/pdf/scripts/__pycache__/check_bounding_boxes.cpython-312.pyc +0 -0
  231. package/skills/pdf/scripts/__pycache__/check_bounding_boxes_test.cpython-312.pyc +0 -0
  232. package/skills/pdf/scripts/__pycache__/check_fillable_fields.cpython-312.pyc +0 -0
  233. package/skills/pdf/scripts/__pycache__/convert_pdf_to_images.cpython-312.pyc +0 -0
  234. package/skills/pdf/scripts/__pycache__/create_validation_image.cpython-312.pyc +0 -0
  235. package/skills/pdf/scripts/__pycache__/extract_form_field_info.cpython-312.pyc +0 -0
  236. package/skills/pdf/scripts/__pycache__/fill_fillable_fields.cpython-312.pyc +0 -0
  237. package/skills/pdf/scripts/__pycache__/fill_pdf_form_with_annotations.cpython-312.pyc +0 -0
  238. package/skills/pdf/scripts/__pycache__/sanitize_code.cpython-312.pyc +0 -0
  239. package/skills/pdf/scripts/add_zai_metadata.py +172 -0
  240. package/skills/pdf/scripts/check_bounding_boxes.py +70 -0
  241. package/skills/pdf/scripts/check_bounding_boxes_test.py +226 -0
  242. package/skills/pdf/scripts/check_fillable_fields.py +12 -0
  243. package/skills/pdf/scripts/convert_pdf_to_images.py +35 -0
  244. package/skills/pdf/scripts/create_validation_image.py +41 -0
  245. package/skills/pdf/scripts/extract_form_field_info.py +152 -0
  246. package/skills/pdf/scripts/fill_fillable_fields.py +114 -0
  247. package/skills/pdf/scripts/fill_pdf_form_with_annotations.py +108 -0
  248. package/skills/pdf/scripts/sanitize_code.py +110 -0
  249. package/skills/podcast-generate/LICENSE.txt +21 -0
  250. package/skills/podcast-generate/SKILL.md +198 -0
  251. package/skills/podcast-generate/generate.ts +661 -0
  252. package/skills/podcast-generate/package.json +30 -0
  253. package/skills/podcast-generate/readme.md +177 -0
  254. package/skills/podcast-generate/test_data/segments.jsonl +3 -0
  255. package/skills/podcast-generate/tsconfig.json +26 -0
  256. package/skills/pptx/LICENSE.txt +30 -0
  257. package/skills/pptx/SKILL.md +507 -0
  258. package/skills/pptx/html2pptx.md +625 -0
  259. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-chart.xsd +1499 -0
  260. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd +146 -0
  261. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd +1085 -0
  262. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd +11 -0
  263. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-main.xsd +3081 -0
  264. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-picture.xsd +23 -0
  265. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd +185 -0
  266. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd +287 -0
  267. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/pml.xsd +1676 -0
  268. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd +28 -0
  269. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd +144 -0
  270. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd +174 -0
  271. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd +25 -0
  272. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd +18 -0
  273. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd +59 -0
  274. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd +56 -0
  275. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd +195 -0
  276. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-math.xsd +582 -0
  277. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd +25 -0
  278. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/sml.xsd +4439 -0
  279. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/vml-main.xsd +570 -0
  280. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd +509 -0
  281. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd +12 -0
  282. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd +108 -0
  283. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd +96 -0
  284. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/wml.xsd +3646 -0
  285. package/skills/pptx/ooxml/schemas/ISO-IEC29500-4_2016/xml.xsd +116 -0
  286. package/skills/pptx/ooxml/schemas/ecma/fouth-edition/opc-contentTypes.xsd +42 -0
  287. package/skills/pptx/ooxml/schemas/ecma/fouth-edition/opc-coreProperties.xsd +50 -0
  288. package/skills/pptx/ooxml/schemas/ecma/fouth-edition/opc-digSig.xsd +49 -0
  289. package/skills/pptx/ooxml/schemas/ecma/fouth-edition/opc-relationships.xsd +33 -0
  290. package/skills/pptx/ooxml/schemas/mce/mc.xsd +75 -0
  291. package/skills/pptx/ooxml/schemas/microsoft/wml-2010.xsd +560 -0
  292. package/skills/pptx/ooxml/schemas/microsoft/wml-2012.xsd +67 -0
  293. package/skills/pptx/ooxml/schemas/microsoft/wml-2018.xsd +14 -0
  294. package/skills/pptx/ooxml/schemas/microsoft/wml-cex-2018.xsd +20 -0
  295. package/skills/pptx/ooxml/schemas/microsoft/wml-cid-2016.xsd +13 -0
  296. package/skills/pptx/ooxml/schemas/microsoft/wml-sdtdatahash-2020.xsd +4 -0
  297. package/skills/pptx/ooxml/schemas/microsoft/wml-symex-2015.xsd +8 -0
  298. package/skills/pptx/ooxml/scripts/__pycache__/pack.cpython-312.pyc +0 -0
  299. package/skills/pptx/ooxml/scripts/__pycache__/unpack.cpython-312.pyc +0 -0
  300. package/skills/pptx/ooxml/scripts/__pycache__/validate.cpython-312.pyc +0 -0
  301. package/skills/pptx/ooxml/scripts/pack.py +159 -0
  302. package/skills/pptx/ooxml/scripts/unpack.py +29 -0
  303. package/skills/pptx/ooxml/scripts/validate.py +69 -0
  304. package/skills/pptx/ooxml/scripts/validation/__init__.py +15 -0
  305. package/skills/pptx/ooxml/scripts/validation/__pycache__/__init__.cpython-312.pyc +0 -0
  306. package/skills/pptx/ooxml/scripts/validation/__pycache__/base.cpython-312.pyc +0 -0
  307. package/skills/pptx/ooxml/scripts/validation/__pycache__/docx.cpython-312.pyc +0 -0
  308. package/skills/pptx/ooxml/scripts/validation/__pycache__/pptx.cpython-312.pyc +0 -0
  309. package/skills/pptx/ooxml/scripts/validation/__pycache__/redlining.cpython-312.pyc +0 -0
  310. package/skills/pptx/ooxml/scripts/validation/base.py +951 -0
  311. package/skills/pptx/ooxml/scripts/validation/docx.py +274 -0
  312. package/skills/pptx/ooxml/scripts/validation/pptx.py +315 -0
  313. package/skills/pptx/ooxml/scripts/validation/redlining.py +279 -0
  314. package/skills/pptx/ooxml.md +427 -0
  315. package/skills/pptx/scripts/__pycache__/inventory.cpython-312.pyc +0 -0
  316. package/skills/pptx/scripts/__pycache__/inventory.cpython-313.pyc +0 -0
  317. package/skills/pptx/scripts/__pycache__/rearrange.cpython-312.pyc +0 -0
  318. package/skills/pptx/scripts/__pycache__/replace.cpython-312.pyc +0 -0
  319. package/skills/pptx/scripts/__pycache__/thumbnail.cpython-312.pyc +0 -0
  320. package/skills/pptx/scripts/html2pptx.js +1044 -0
  321. package/skills/pptx/scripts/inventory.py +1020 -0
  322. package/skills/pptx/scripts/rearrange.py +231 -0
  323. package/skills/pptx/scripts/replace.py +385 -0
  324. package/skills/pptx/scripts/thumbnail.py +450 -0
  325. package/skills/qingyan-research/SKILL.md +294 -0
  326. package/skills/qingyan-research/__pycache__/generate_html.cpython-312.pyc +0 -0
  327. package/skills/qingyan-research/generate_html.py +33 -0
  328. package/skills/registry.py +344 -0
  329. package/skills/search_skill.py +228 -0
  330. package/skills/seo-content-writer/SKILL.md +661 -0
  331. package/skills/seo-content-writer/_meta.json +6 -0
  332. package/skills/seo-content-writer/references/content-structure-templates.md +875 -0
  333. package/skills/seo-content-writer/references/title-formulas.md +339 -0
  334. package/skills/skill-creator/LICENSE.txt +202 -0
  335. package/skills/skill-creator/SKILL.md +485 -0
  336. package/skills/skill-creator/agents/analyzer.md +274 -0
  337. package/skills/skill-creator/agents/comparator.md +202 -0
  338. package/skills/skill-creator/agents/grader.md +223 -0
  339. package/skills/skill-creator/assets/eval_review.html +146 -0
  340. package/skills/skill-creator/eval-viewer/__pycache__/generate_review.cpython-312.pyc +0 -0
  341. package/skills/skill-creator/eval-viewer/generate_review.py +471 -0
  342. package/skills/skill-creator/eval-viewer/viewer.html +1325 -0
  343. package/skills/skill-creator/references/schemas.md +430 -0
  344. package/skills/skill-creator/scripts/__init__.py +0 -0
  345. package/skills/skill-creator/scripts/__pycache__/__init__.cpython-312.pyc +0 -0
  346. package/skills/skill-creator/scripts/__pycache__/aggregate_benchmark.cpython-312.pyc +0 -0
  347. package/skills/skill-creator/scripts/__pycache__/generate_report.cpython-312.pyc +0 -0
  348. package/skills/skill-creator/scripts/__pycache__/improve_description.cpython-312.pyc +0 -0
  349. package/skills/skill-creator/scripts/__pycache__/package_skill.cpython-312.pyc +0 -0
  350. package/skills/skill-creator/scripts/__pycache__/quick_validate.cpython-312.pyc +0 -0
  351. package/skills/skill-creator/scripts/__pycache__/run_eval.cpython-312.pyc +0 -0
  352. package/skills/skill-creator/scripts/__pycache__/run_loop.cpython-312.pyc +0 -0
  353. package/skills/skill-creator/scripts/__pycache__/utils.cpython-312.pyc +0 -0
  354. package/skills/skill-creator/scripts/aggregate_benchmark.py +401 -0
  355. package/skills/skill-creator/scripts/generate_report.py +326 -0
  356. package/skills/skill-creator/scripts/improve_description.py +236 -0
  357. package/skills/skill-creator/scripts/package_skill.py +136 -0
  358. package/skills/skill-creator/scripts/quick_validate.py +103 -0
  359. package/skills/skill-creator/scripts/run_eval.py +310 -0
  360. package/skills/skill-creator/scripts/run_loop.py +328 -0
  361. package/skills/skill-creator/scripts/utils.py +47 -0
  362. package/skills/skill-finder-cn/SKILL.md +66 -0
  363. package/skills/skill-finder-cn/_meta.json +6 -0
  364. package/skills/skill-finder-cn/package.json +5 -0
  365. package/skills/skill-finder-cn/scripts/search.sh +15 -0
  366. package/skills/skill-vetter/SKILL.md +137 -0
  367. package/skills/stock-analysis-skill/SKILL.md +156 -0
  368. package/skills/stock-analysis-skill/package.json +21 -0
  369. package/skills/stock-analysis-skill/src/analyzer.ts +264 -0
  370. package/skills/stock-analysis-skill/src/dataFetcher.ts +130 -0
  371. package/skills/stock-analysis-skill/src/dividend.ts +226 -0
  372. package/skills/stock-analysis-skill/src/index.ts +327 -0
  373. package/skills/stock-analysis-skill/src/rumorScanner.ts +200 -0
  374. package/skills/stock-analysis-skill/src/types.ts +167 -0
  375. package/skills/stock-analysis-skill/src/watchlist.ts +292 -0
  376. package/skills/stock-analysis-skill/tsconfig.json +15 -0
  377. package/skills/storyboard-manager/SKILL.md +532 -0
  378. package/skills/storyboard-manager/index.js +9 -0
  379. package/skills/storyboard-manager/package.json +11 -0
  380. package/skills/storyboard-manager/references/character_development.md +232 -0
  381. package/skills/storyboard-manager/references/story_structures.md +148 -0
  382. package/skills/storyboard-manager/scripts/__pycache__/consistency_checker.cpython-312.pyc +0 -0
  383. package/skills/storyboard-manager/scripts/__pycache__/timeline_tracker.cpython-312.pyc +0 -0
  384. package/skills/storyboard-manager/scripts/consistency_checker.py +391 -0
  385. package/skills/storyboard-manager/scripts/timeline_tracker.py +352 -0
  386. package/skills/system_skill.py +249 -0
  387. package/skills/ui-ux-pro-max/SKILL.md +43 -0
  388. package/skills/ui-ux-pro-max/_meta.json +6 -0
  389. package/skills/ui-ux-pro-max/assets/data/charts.csv +26 -0
  390. package/skills/ui-ux-pro-max/assets/data/colors.csv +97 -0
  391. package/skills/ui-ux-pro-max/assets/data/icons.csv +101 -0
  392. package/skills/ui-ux-pro-max/assets/data/landing.csv +31 -0
  393. package/skills/ui-ux-pro-max/assets/data/products.csv +97 -0
  394. package/skills/ui-ux-pro-max/assets/data/react-performance.csv +45 -0
  395. package/skills/ui-ux-pro-max/assets/data/stacks/astro.csv +54 -0
  396. package/skills/ui-ux-pro-max/assets/data/stacks/flutter.csv +53 -0
  397. package/skills/ui-ux-pro-max/assets/data/stacks/html-tailwind.csv +56 -0
  398. package/skills/ui-ux-pro-max/assets/data/stacks/jetpack-compose.csv +53 -0
  399. package/skills/ui-ux-pro-max/assets/data/stacks/nextjs.csv +53 -0
  400. package/skills/ui-ux-pro-max/assets/data/stacks/nuxt-ui.csv +51 -0
  401. package/skills/ui-ux-pro-max/assets/data/stacks/nuxtjs.csv +59 -0
  402. package/skills/ui-ux-pro-max/assets/data/stacks/react-native.csv +52 -0
  403. package/skills/ui-ux-pro-max/assets/data/stacks/react.csv +54 -0
  404. package/skills/ui-ux-pro-max/assets/data/stacks/shadcn.csv +61 -0
  405. package/skills/ui-ux-pro-max/assets/data/stacks/svelte.csv +54 -0
  406. package/skills/ui-ux-pro-max/assets/data/stacks/swiftui.csv +51 -0
  407. package/skills/ui-ux-pro-max/assets/data/stacks/vue.csv +50 -0
  408. package/skills/ui-ux-pro-max/assets/data/styles.csv +68 -0
  409. package/skills/ui-ux-pro-max/assets/data/typography.csv +58 -0
  410. package/skills/ui-ux-pro-max/assets/data/ui-reasoning.csv +101 -0
  411. package/skills/ui-ux-pro-max/assets/data/ux-guidelines.csv +100 -0
  412. package/skills/ui-ux-pro-max/assets/data/web-interface.csv +31 -0
  413. package/skills/ui-ux-pro-max/data/charts.csv +26 -0
  414. package/skills/ui-ux-pro-max/data/colors.csv +97 -0
  415. package/skills/ui-ux-pro-max/data/icons.csv +101 -0
  416. package/skills/ui-ux-pro-max/data/landing.csv +31 -0
  417. package/skills/ui-ux-pro-max/data/products.csv +97 -0
  418. package/skills/ui-ux-pro-max/data/react-performance.csv +45 -0
  419. package/skills/ui-ux-pro-max/data/stacks/astro.csv +54 -0
  420. package/skills/ui-ux-pro-max/data/stacks/flutter.csv +53 -0
  421. package/skills/ui-ux-pro-max/data/stacks/html-tailwind.csv +56 -0
  422. package/skills/ui-ux-pro-max/data/stacks/jetpack-compose.csv +53 -0
  423. package/skills/ui-ux-pro-max/data/stacks/nextjs.csv +53 -0
  424. package/skills/ui-ux-pro-max/data/stacks/nuxt-ui.csv +51 -0
  425. package/skills/ui-ux-pro-max/data/stacks/nuxtjs.csv +59 -0
  426. package/skills/ui-ux-pro-max/data/stacks/react-native.csv +52 -0
  427. package/skills/ui-ux-pro-max/data/stacks/react.csv +54 -0
  428. package/skills/ui-ux-pro-max/data/stacks/shadcn.csv +61 -0
  429. package/skills/ui-ux-pro-max/data/stacks/svelte.csv +54 -0
  430. package/skills/ui-ux-pro-max/data/stacks/swiftui.csv +51 -0
  431. package/skills/ui-ux-pro-max/data/stacks/vue.csv +50 -0
  432. package/skills/ui-ux-pro-max/data/styles.csv +68 -0
  433. package/skills/ui-ux-pro-max/data/typography.csv +58 -0
  434. package/skills/ui-ux-pro-max/data/ui-reasoning.csv +101 -0
  435. package/skills/ui-ux-pro-max/data/ux-guidelines.csv +100 -0
  436. package/skills/ui-ux-pro-max/data/web-interface.csv +31 -0
  437. package/skills/ui-ux-pro-max/references/upstream-README.md +488 -0
  438. package/skills/ui-ux-pro-max/references/upstream-skill-content.md +288 -0
  439. package/skills/ui-ux-pro-max/scripts/__init__.py +0 -0
  440. package/skills/ui-ux-pro-max/scripts/__pycache__/__init__.cpython-312.pyc +0 -0
  441. package/skills/ui-ux-pro-max/scripts/__pycache__/core.cpython-312.pyc +0 -0
  442. package/skills/ui-ux-pro-max/scripts/__pycache__/design_system.cpython-312.pyc +0 -0
  443. package/skills/ui-ux-pro-max/scripts/__pycache__/search.cpython-312.pyc +0 -0
  444. package/skills/ui-ux-pro-max/scripts/core.py +253 -0
  445. package/skills/ui-ux-pro-max/scripts/design_system.py +1071 -0
  446. package/skills/ui-ux-pro-max/scripts/search.py +111 -0
  447. package/skills/video-generation/LICENSE.txt +21 -0
  448. package/skills/video-generation/SKILL.md +1082 -0
  449. package/skills/video-generation/scripts/video.ts +168 -0
  450. package/skills/video-understand/LICENSE.txt +21 -0
  451. package/skills/video-understand/SKILL.md +916 -0
  452. package/skills/video-understand/scripts/video-understand.ts +41 -0
  453. package/skills/visual-design-foundations/SKILL.md +318 -0
  454. package/skills/visual-design-foundations/references/color-systems.md +417 -0
  455. package/skills/visual-design-foundations/references/spacing-iconography.md +425 -0
  456. package/skills/visual-design-foundations/references/typography-systems.md +432 -0
  457. package/skills/web-reader/LICENSE.txt +21 -0
  458. package/skills/web-reader/SKILL.md +1140 -0
  459. package/skills/web-reader/scripts/web-reader.ts +37 -0
  460. package/skills/web-search/LICENSE.txt +21 -0
  461. package/skills/web-search/SKILL.md +912 -0
  462. package/skills/web-search/scripts/web_search.ts +44 -0
  463. package/skills/web-shader-extractor/SKILL.md +145 -0
  464. package/skills/web-shader-extractor/references/config-extraction.md +50 -0
  465. package/skills/web-shader-extractor/references/encoded-definitions.md +53 -0
  466. package/skills/web-shader-extractor/references/extraction-workflow.md +61 -0
  467. package/skills/web-shader-extractor/references/porting-strategy.md +164 -0
  468. package/skills/web-shader-extractor/references/shader-injection.md +126 -0
  469. package/skills/web-shader-extractor/references/shaders-com.md +190 -0
  470. package/skills/web-shader-extractor/references/tech-signatures.md +54 -0
  471. package/skills/web-shader-extractor/references/tsl-extraction.md +41 -0
  472. package/skills/web-shader-extractor/references/unicorn-studio.md +353 -0
  473. package/skills/web-shader-extractor/scripts/fetch-rendered-dom.mjs +153 -0
  474. package/skills/web-shader-extractor/scripts/scan-bundle.sh +76 -0
  475. package/skills/writing-plans/SKILL.md +116 -0
  476. package/skills/writing-plans/_meta.json +6 -0
  477. package/skills/xlsx/LICENSE.txt +30 -0
  478. package/skills/xlsx/SKILL.md +496 -0
  479. package/skills/xlsx/__pycache__/recalc.cpython-312.pyc +0 -0
  480. package/skills/xlsx/recalc.py +178 -0
  481. package/start.sh +36 -0
  482. package/web/__init__.py +1 -0
  483. package/web/__pycache__/api_server.cpython-312.pyc +0 -0
  484. package/web/api_server.py +2043 -0
  485. package/web/ui/chat.html +3235 -0
  486. package/web/ui/index.html +458 -0
@@ -0,0 +1,840 @@
1
+ """
2
+ memory/manager.py - 记忆管理器
3
+ ================================
4
+ 基于 SQLite 的三层记忆系统:
5
+ - 短期记忆 (short_term): 当前对话上下文,自动淘汰旧消息
6
+ - 工作记忆 (working): 任务进度、执行步骤、中间结果
7
+ - 长期记忆 (long_term): 用户偏好、技能经验、历史任务总结
8
+
9
+ 所有记忆通过 session_id 隔离,支持跨会话检索。
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import math
15
+ import re
16
+ import sqlite3
17
+ import time
18
+ import threading
19
+ from collections import Counter, defaultdict
20
+ from dataclasses import dataclass, field, asdict
21
+ from datetime import datetime, timezone
22
+ from typing import Any, Dict, List, Optional, Tuple
23
+
24
+ from core.logger import get_logger
25
+ from core.utils import generate_id, timestamp, truncate_str
26
+
27
+ logger = get_logger("myagent.memory")
28
+
29
+
30
+ # ==============================================================================
31
+ # 数据模型
32
+ # ==============================================================================
33
+
34
+ @dataclass
35
+ class MemoryEntry:
36
+ """记忆条目"""
37
+ id: str = field(default_factory=lambda: generate_id("mem"))
38
+ session_id: str = "default"
39
+ category: str = "short_term" # short_term | working | long_term
40
+ key: str = "" # 检索键/标签
41
+ content: str = "" # 记忆内容
42
+ summary: str = "" # 摘要(长期记忆用)
43
+ role: str = "" # 对话角色: user | assistant | system | tool
44
+ metadata: Dict[str, Any] = field(default_factory=dict)
45
+ importance: float = 0.5 # 重要性 0~1
46
+ access_count: int = 0 # 访问次数
47
+ created_at: str = field(default_factory=timestamp)
48
+ updated_at: str = field(default_factory=timestamp)
49
+ expires_at: str = "" # 过期时间(空=永不过期)
50
+
51
+ def to_dict(self) -> dict:
52
+ d = asdict(self)
53
+ # metadata 序列化
54
+ d["metadata"] = json.dumps(self.metadata, ensure_ascii=False)
55
+ return d
56
+
57
+ @classmethod
58
+ def from_row(cls, row: sqlite3.Row) -> "MemoryEntry":
59
+ meta = row["metadata"]
60
+ if isinstance(meta, str):
61
+ try:
62
+ meta = json.loads(meta)
63
+ except json.JSONDecodeError:
64
+ meta = {}
65
+ return cls(
66
+ id=row["id"],
67
+ session_id=row["session_id"],
68
+ category=row["category"],
69
+ key=row["key"],
70
+ content=row["content"],
71
+ summary=row["summary"],
72
+ role=row["role"],
73
+ metadata=meta,
74
+ importance=row["importance"],
75
+ access_count=row["access_count"],
76
+ created_at=row["created_at"],
77
+ updated_at=row["updated_at"],
78
+ expires_at=dict(row).get("expires_at", ""),
79
+ )
80
+
81
+
82
+ # ==============================================================================
83
+ # 记忆管理器
84
+ # ==============================================================================
85
+
86
+ class MemoryManager:
87
+ """
88
+ 三层记忆管理器。
89
+
90
+ 使用示例:
91
+ mm = MemoryManager(db_path="~/.myagent/data/memory.db")
92
+ mm.initialize()
93
+
94
+ # 写入短期记忆
95
+ mm.add_short_term("session_1", "user", "帮我创建一个Python项目")
96
+ mm.add_short_term("session_1", "assistant", "好的,正在创建...")
97
+
98
+ # 查询对话历史
99
+ history = mm.get_conversation("session_1")
100
+
101
+ # 写入工作记忆
102
+ mm.add_working("session_1", "task_progress", "步骤2/5: 已创建目录结构")
103
+
104
+ # 写入长期记忆
105
+ mm.add_long_term("user_prefs", "coding_style", "偏好使用Python, TypeScript")
106
+
107
+ # 语义搜索
108
+ results = mm.search("Python项目", category="long_term")
109
+ """
110
+
111
+ def __init__(self, db_path: str = ""):
112
+ self.db_path = db_path
113
+ self._local = threading.local()
114
+ self._initialized = False
115
+
116
+ def _get_conn(self) -> sqlite3.Connection:
117
+ """获取线程本地的数据库连接"""
118
+ if not hasattr(self._local, "conn") or self._local.conn is None:
119
+ self._local.conn = sqlite3.connect(
120
+ self.db_path,
121
+ check_same_thread=False,
122
+ timeout=10,
123
+ )
124
+ self._local.conn.row_factory = sqlite3.Row
125
+ self._local.conn.execute("PRAGMA journal_mode=WAL")
126
+ self._local.conn.execute("PRAGMA synchronous=NORMAL")
127
+ return self._local.conn
128
+
129
+ def initialize(self):
130
+ """初始化数据库表结构"""
131
+ conn = self._get_conn()
132
+ conn.executescript("""
133
+ CREATE TABLE IF NOT EXISTS memories (
134
+ id TEXT PRIMARY KEY,
135
+ session_id TEXT NOT NULL,
136
+ category TEXT NOT NULL,
137
+ key TEXT DEFAULT '',
138
+ content TEXT DEFAULT '',
139
+ summary TEXT DEFAULT '',
140
+ role TEXT DEFAULT '',
141
+ metadata TEXT DEFAULT '{}',
142
+ importance REAL DEFAULT 0.5,
143
+ access_count INTEGER DEFAULT 0,
144
+ created_at TEXT NOT NULL,
145
+ updated_at TEXT NOT NULL,
146
+ expires_at TEXT DEFAULT ''
147
+ );
148
+
149
+ CREATE INDEX IF NOT EXISTS idx_session ON memories(session_id);
150
+ CREATE INDEX IF NOT EXISTS idx_category ON memories(category);
151
+ CREATE INDEX IF NOT EXISTS idx_key ON memories(key);
152
+ CREATE INDEX IF NOT EXISTS idx_session_category ON memories(session_id, category);
153
+ CREATE INDEX IF NOT EXISTS idx_importance ON memories(importance DESC);
154
+ """)
155
+ conn.commit()
156
+ self._initialized = True
157
+ logger.info(f"记忆系统已初始化 (db={self.db_path})")
158
+
159
+ def close(self):
160
+ """关闭数据库连接"""
161
+ if hasattr(self._local, "conn") and self._local.conn:
162
+ self._local.conn.close()
163
+ self._local.conn = None
164
+
165
+ # ==========================================================================
166
+ # 基础 CRUD
167
+ # ==========================================================================
168
+
169
+ def _insert(self, entry: MemoryEntry) -> str:
170
+ """插入记忆条目"""
171
+ conn = self._get_conn()
172
+ entry.updated_at = timestamp()
173
+ try:
174
+ conn.execute(
175
+ """INSERT OR REPLACE INTO memories
176
+ (id, session_id, category, key, content, summary, role,
177
+ metadata, importance, access_count, created_at, updated_at, expires_at)
178
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
179
+ (
180
+ entry.id, entry.session_id, entry.category, entry.key,
181
+ entry.content, entry.summary, entry.role,
182
+ json.dumps(entry.metadata, ensure_ascii=False),
183
+ entry.importance, entry.access_count,
184
+ entry.created_at, entry.updated_at, entry.expires_at,
185
+ ),
186
+ )
187
+ conn.commit()
188
+ return entry.id
189
+ except Exception as e:
190
+ logger.error(f"记忆写入失败: {e}")
191
+ raise
192
+
193
+ def _query(
194
+ self,
195
+ session_id: str = "",
196
+ category: str = "",
197
+ key: str = "",
198
+ role: str = "",
199
+ limit: int = 100,
200
+ order_by: str = "created_at ASC",
201
+ ) -> List[MemoryEntry]:
202
+ """查询记忆条目"""
203
+ conn = self._get_conn()
204
+ conditions = []
205
+ params: list = []
206
+
207
+ if session_id:
208
+ conditions.append("session_id = ?")
209
+ params.append(session_id)
210
+ if category:
211
+ conditions.append("category = ?")
212
+ params.append(category)
213
+ if key:
214
+ conditions.append("key = ?")
215
+ params.append(key)
216
+ if role:
217
+ conditions.append("role = ?")
218
+ params.append(role)
219
+
220
+ # 过滤已过期的
221
+ conditions.append("(expires_at = '' OR expires_at > ?)")
222
+ params.append(timestamp())
223
+
224
+ where = " AND ".join(conditions) if conditions else "1=1"
225
+ sql = f"SELECT * FROM memories WHERE {where} ORDER BY {order_by} LIMIT ?"
226
+ params.append(limit)
227
+
228
+ rows = conn.execute(sql, params).fetchall()
229
+ return [MemoryEntry.from_row(row) for row in rows]
230
+
231
+ def _delete(self, session_id: str, category: str = "", older_than: str = "") -> int:
232
+ """删除记忆条目,返回删除数量"""
233
+ conn = self._get_conn()
234
+ conditions = ["session_id = ?"]
235
+ params: list = [session_id]
236
+
237
+ if category:
238
+ conditions.append("category = ?")
239
+ params.append(category)
240
+ if older_than:
241
+ conditions.append("created_at < ?")
242
+ params.append(older_than)
243
+
244
+ where = " AND ".join(conditions)
245
+ cursor = conn.execute(f"DELETE FROM memories WHERE {where}", params)
246
+ conn.commit()
247
+ return cursor.rowcount
248
+
249
+ def _update_content(self, memory_id: str, content: str, **updates):
250
+ """更新记忆内容"""
251
+ conn = self._get_conn()
252
+ sets = ["content = ?", "updated_at = ?"]
253
+ params: list = [content, timestamp()]
254
+
255
+ for key, val in updates.items():
256
+ if key in ("summary", "key", "importance", "metadata", "access_count", "expires_at"):
257
+ sets.append(f"{key} = ?")
258
+ if key == "metadata":
259
+ params.append(json.dumps(val, ensure_ascii=False))
260
+ else:
261
+ params.append(val)
262
+
263
+ params.append(memory_id)
264
+ conn.execute(f"UPDATE memories SET {', '.join(sets)} WHERE id = ?", params)
265
+ conn.commit()
266
+
267
+ # ==========================================================================
268
+ # 短期记忆 (对话上下文)
269
+ # ==========================================================================
270
+
271
+ def add_short_term(
272
+ self,
273
+ session_id: str,
274
+ role: str,
275
+ content: str,
276
+ key: str = "",
277
+ importance: float = 0.5,
278
+ ) -> str:
279
+ """
280
+ 添加短期记忆(对话消息)。
281
+
282
+ Args:
283
+ session_id: 会话ID
284
+ role: 角色 (user/assistant/system/tool)
285
+ content: 消息内容
286
+ key: 检索标签
287
+ importance: 重要性权重
288
+ """
289
+ entry = MemoryEntry(
290
+ session_id=session_id,
291
+ category="short_term",
292
+ role=role,
293
+ content=truncate_str(content, 50000),
294
+ key=key,
295
+ importance=importance,
296
+ )
297
+ return self._insert(entry)
298
+
299
+ def get_conversation(
300
+ self,
301
+ session_id: str,
302
+ limit: int = 50,
303
+ include_roles: Optional[List[str]] = None,
304
+ ) -> List[MemoryEntry]:
305
+ """获取对话历史"""
306
+ entries = self._query(
307
+ session_id=session_id,
308
+ category="short_term",
309
+ limit=limit,
310
+ order_by="created_at ASC",
311
+ )
312
+ if include_roles:
313
+ entries = [e for e in entries if e.role in include_roles]
314
+ return entries
315
+
316
+ def get_conversation_text(
317
+ self,
318
+ session_id: str,
319
+ limit: int = 50,
320
+ ) -> str:
321
+ """获取对话历史文本(供 LLM 使用)"""
322
+ entries = self.get_conversation(session_id, limit)
323
+ lines = []
324
+ for e in entries:
325
+ label = e.role.upper()
326
+ if e.role == "user":
327
+ label = "用户"
328
+ elif e.role == "assistant":
329
+ label = "助手"
330
+ elif e.role == "system":
331
+ label = "系统"
332
+ elif e.role == "tool":
333
+ label = "工具"
334
+ lines.append(f"[{label}] {e.content}")
335
+ return "\n".join(lines)
336
+
337
+ def clear_conversation(self, session_id: str) -> int:
338
+ """清空会话对话历史"""
339
+ return self._delete(session_id, category="short_term")
340
+
341
+ def prune_conversation(self, session_id: str, max_messages: int = 50) -> int:
342
+ """修剪对话历史,保留最近 N 条"""
343
+ entries = self.get_conversation(session_id, limit=1000)
344
+ if len(entries) <= max_messages:
345
+ return 0
346
+ # 删除最旧的
347
+ to_remove = entries[:-max_messages]
348
+ conn = self._get_conn()
349
+ ids = [e.id for e in to_remove]
350
+ placeholders = ",".join("?" * len(ids))
351
+ cursor = conn.execute(f"DELETE FROM memories WHERE id IN ({placeholders})", ids)
352
+ conn.commit()
353
+ logger.debug(f"修剪对话历史: 删除 {len(ids)} 条 (session={session_id})")
354
+ return len(ids)
355
+
356
+ # ==========================================================================
357
+ # 工作记忆 (任务进度)
358
+ # ==========================================================================
359
+
360
+ def add_working(
361
+ self,
362
+ session_id: str,
363
+ key: str,
364
+ content: str,
365
+ metadata: Optional[Dict] = None,
366
+ ) -> str:
367
+ """
368
+ 添加工作记忆(任务进度)。
369
+
370
+ Args:
371
+ session_id: 会话ID
372
+ key: 进度键(如 "task_progress", "step_result", "error_log")
373
+ content: 进度内容
374
+ metadata: 附加数据
375
+ """
376
+ entry = MemoryEntry(
377
+ session_id=session_id,
378
+ category="working",
379
+ key=key,
380
+ content=truncate_str(content, 30000),
381
+ metadata=metadata or {},
382
+ importance=0.7,
383
+ )
384
+ return self._insert(entry)
385
+
386
+ def get_working(
387
+ self,
388
+ session_id: str,
389
+ key: str = "",
390
+ ) -> List[MemoryEntry]:
391
+ """获取工作记忆"""
392
+ return self._query(
393
+ session_id=session_id,
394
+ category="working",
395
+ key=key,
396
+ order_by="created_at DESC",
397
+ )
398
+
399
+ def update_working(self, memory_id: str, content: str, **updates):
400
+ """更新工作记忆"""
401
+ self._update_content(memory_id, content, **updates)
402
+
403
+ def clear_working(self, session_id: str) -> int:
404
+ """清空工作记忆"""
405
+ return self._delete(session_id, category="working")
406
+
407
+ # ==========================================================================
408
+ # 长期记忆 (持久知识)
409
+ # ==========================================================================
410
+
411
+ def add_long_term(
412
+ self,
413
+ session_id: str = "global",
414
+ key: str = "",
415
+ content: str = "",
416
+ summary: str = "",
417
+ importance: float = 0.7,
418
+ metadata: Optional[Dict] = None,
419
+ ) -> str:
420
+ """
421
+ 添加长期记忆。
422
+
423
+ Args:
424
+ session_id: 全局使用 "global"
425
+ key: 知识分类(如 "user_prefs", "skill_experience", "task_summary")
426
+ content: 详细内容
427
+ summary: 简要摘要
428
+ importance: 重要性(越高越不容易被淘汰)
429
+ """
430
+ entry = MemoryEntry(
431
+ session_id=session_id,
432
+ category="long_term",
433
+ key=key,
434
+ content=truncate_str(content, 50000),
435
+ summary=summary,
436
+ importance=importance,
437
+ metadata=metadata or {},
438
+ )
439
+ return self._insert(entry)
440
+
441
+ def get_long_term(
442
+ self,
443
+ session_id: str = "global",
444
+ key: str = "",
445
+ limit: int = 50,
446
+ ) -> List[MemoryEntry]:
447
+ """获取长期记忆"""
448
+ return self._query(
449
+ session_id=session_id,
450
+ category="long_term",
451
+ key=key,
452
+ limit=limit,
453
+ order_by="importance DESC, created_at DESC",
454
+ )
455
+
456
+ def get_preferences(self, session_id: str = "global") -> List[MemoryEntry]:
457
+ """获取用户偏好"""
458
+ return self.get_long_term(session_id, key="user_pref")
459
+
460
+ def get_experience(self, session_id: str = "global") -> List[MemoryEntry]:
461
+ """获取技能经验"""
462
+ return self.get_long_term(session_id, key="skill_experience")
463
+
464
+ def get_task_summaries(self, session_id: str = "global") -> List[MemoryEntry]:
465
+ """获取历史任务总结"""
466
+ return self.get_long_term(session_id, key="task_summary")
467
+
468
+ # ==========================================================================
469
+ # 记忆搜索
470
+ # ==========================================================================
471
+
472
+ # ==========================================================================
473
+ # TF-IDF 语义搜索 (无外部依赖)
474
+ # ==========================================================================
475
+
476
+ @staticmethod
477
+ def _tokenize(text: str) -> List[str]:
478
+ """
479
+ 中文分词(简单实现:单字+双字组合)+ 英文词提取。
480
+
481
+ 对中文文本提取单字和相邻双字作为 token,
482
+ 对英文文本按空格和标点分词并转小写。
483
+ """
484
+ if not text:
485
+ return []
486
+
487
+ tokens: List[str] = []
488
+ # 提取中文连续片段
489
+ chinese_segments = re.findall(r'[\u4e00-\u9fff]+', text)
490
+ for seg in chinese_segments:
491
+ # 单字
492
+ tokens.extend(list(seg))
493
+ # 双字组合
494
+ for i in range(len(seg) - 1):
495
+ tokens.append(seg[i:i + 2])
496
+
497
+ # 提取英文/数字单词
498
+ english_words = re.findall(r'[a-zA-Z0-9]+', text.lower())
499
+ tokens.extend(english_words)
500
+
501
+ return tokens
502
+
503
+ @staticmethod
504
+ def _compute_tf(tokens: List[str]) -> Counter:
505
+ """计算词频 (Term Frequency)"""
506
+ return Counter(tokens)
507
+
508
+ @classmethod
509
+ def _compute_tfidf(
510
+ cls,
511
+ query: str,
512
+ documents: List[Tuple[str, str]], # [(id, text), ...]
513
+ ) -> Dict[str, float]:
514
+ """
515
+ 计算 TF-IDF 相似度得分。
516
+
517
+ Args:
518
+ query: 查询文本
519
+ documents: 文档列表 [(doc_id, text), ...]
520
+
521
+ Returns:
522
+ {doc_id: tfidf_score} 按得分降序排列
523
+ """
524
+ if not documents or not query:
525
+ return {}
526
+
527
+ query_tokens = cls._tokenize(query)
528
+ if not query_tokens:
529
+ return {}
530
+
531
+ # 文档数量
532
+ n_docs = len(documents)
533
+
534
+ # 计算每个文档的 TF
535
+ doc_tfs: Dict[str, Counter] = {}
536
+ for doc_id, text in documents:
537
+ doc_tfs[doc_id] = cls._compute_tf(cls._tokenize(text))
538
+
539
+ # 计算 IDF: log(N / (1 + df)) df=包含该词的文档数
540
+ doc_freq: Counter = Counter()
541
+ for doc_id, tf in doc_tfs.items():
542
+ for token in set(tf.keys()):
543
+ doc_freq[token] += 1
544
+
545
+ idf: Dict[str, float] = {}
546
+ for token, df in doc_freq.items():
547
+ idf[token] = math.log((n_docs + 1) / (1 + df)) + 1
548
+
549
+ # 查询的 TF
550
+ query_tf = cls._compute_tf(query_tokens)
551
+
552
+ # 计算每个文档与查询的余弦相似度
553
+ scores: Dict[str, float] = {}
554
+ all_tokens = set(query_tf.keys())
555
+ for doc_id, tf in doc_tfs.items():
556
+ all_tokens.update(tf.keys())
557
+
558
+ # 计算查询向量的模
559
+ query_norm = math.sqrt(
560
+ sum((query_tf.get(t, 0) * idf.get(t, 0)) ** 2 for t in query_tf)
561
+ )
562
+ if query_norm == 0:
563
+ return {}
564
+
565
+ # 计算每个文档与查询的余弦相似度
566
+ for doc_id in doc_tfs:
567
+ doc_tf = doc_tfs[doc_id]
568
+ dot_product = 0.0
569
+ for token in query_tf:
570
+ if token in doc_tf:
571
+ dot_product += (query_tf[token] * idf.get(token, 0)) * \
572
+ (doc_tf[token] * idf.get(token, 0))
573
+
574
+ doc_norm = math.sqrt(
575
+ sum((doc_tf.get(t, 0) * idf.get(t, 0)) ** 2 for t in doc_tf)
576
+ ) if doc_tf else 0
577
+
578
+ if doc_norm > 0:
579
+ scores[doc_id] = dot_product / (query_norm * doc_norm)
580
+ else:
581
+ scores[doc_id] = 0.0
582
+
583
+ return dict(sorted(scores.items(), key=lambda x: x[1], reverse=True))
584
+
585
+ def search(
586
+ self,
587
+ query: str,
588
+ session_id: str = "",
589
+ category: str = "",
590
+ limit: int = 10,
591
+ mode: str = "hybrid",
592
+ ) -> List[MemoryEntry]:
593
+ """
594
+ 搜索记忆。
595
+
596
+ 支持三种搜索模式:
597
+ - "keyword": 传统 LIKE 关键词匹配(快速)
598
+ - "semantic": TF-IDF 语义搜索(理解语义相似性)
599
+ - "hybrid": 混合搜索(默认)= 0.4 * keyword_score + 0.6 * tfidf_score
600
+
601
+ Args:
602
+ query: 搜索查询
603
+ session_id: 会话 ID(空=所有会话)
604
+ category: 记忆类别(空=所有类别)
605
+ limit: 返回数量
606
+ mode: 搜索模式 "keyword" | "semantic" | "hybrid"
607
+ """
608
+ conn = self._get_conn()
609
+ conditions = ["1=1"]
610
+ params: list = []
611
+
612
+ if session_id:
613
+ conditions.append("session_id = ?")
614
+ params.append(session_id)
615
+ if category:
616
+ conditions.append("category = ?")
617
+ params.append(category)
618
+
619
+ # 过滤过期
620
+ conditions.append("(expires_at = '' OR expires_at > ?)")
621
+ params.append(timestamp())
622
+
623
+ where = " AND ".join(conditions)
624
+
625
+ if mode == "keyword":
626
+ return self._search_keyword(conn, query, where, params, limit)
627
+ elif mode == "semantic":
628
+ return self._search_semantic(conn, query, where, params, limit)
629
+ else:
630
+ # 混合模式:取两种搜索结果的加权和
631
+ keyword_results = self._search_keyword(conn, query, where, params, limit * 2)
632
+ semantic_results = self._search_semantic(conn, query, where, params, limit * 2)
633
+
634
+ # 合并评分
635
+ combined: Dict[str, Tuple[MemoryEntry, float]] = {}
636
+ for i, entry in enumerate(keyword_results):
637
+ score = 1.0 - (i / max(len(keyword_results), 1))
638
+ combined[entry.id] = (entry, score * 0.4)
639
+
640
+ for i, entry in enumerate(semantic_results):
641
+ score = 1.0 - (i / max(len(semantic_results), 1))
642
+ if entry.id in combined:
643
+ combined[entry.id] = (entry, combined[entry.id][1] + score * 0.6)
644
+ else:
645
+ combined[entry.id] = (entry, score * 0.6)
646
+
647
+ # 按综合得分排序
648
+ sorted_results = sorted(
649
+ combined.values(),
650
+ key=lambda x: x[1],
651
+ reverse=True,
652
+ )
653
+
654
+ # 更新访问计数
655
+ for entry, _ in sorted_results[:limit]:
656
+ conn.execute(
657
+ "UPDATE memories SET access_count = access_count + 1 WHERE id = ?",
658
+ (entry.id,),
659
+ )
660
+ conn.commit()
661
+
662
+ return [entry for entry, _ in sorted_results[:limit]]
663
+
664
+ def _search_keyword(
665
+ self,
666
+ conn: sqlite3.Connection,
667
+ query: str,
668
+ where: str,
669
+ params: list,
670
+ limit: int,
671
+ ) -> List[MemoryEntry]:
672
+ """关键词 LIKE 搜索"""
673
+ like_pattern = f"%{query}%"
674
+ conditions = f"{where} AND (content LIKE ? OR summary LIKE ? OR key LIKE ?)"
675
+ search_params = params + [like_pattern, like_pattern, like_pattern]
676
+
677
+ sql = f"""
678
+ SELECT * FROM memories WHERE {conditions}
679
+ ORDER BY importance DESC, access_count DESC
680
+ LIMIT ?
681
+ """
682
+ search_params.append(limit)
683
+ rows = conn.execute(sql, search_params).fetchall()
684
+
685
+ for row in rows:
686
+ conn.execute(
687
+ "UPDATE memories SET access_count = access_count + 1 WHERE id = ?",
688
+ (row["id"],),
689
+ )
690
+ conn.commit()
691
+
692
+ return [MemoryEntry.from_row(row) for row in rows]
693
+
694
+ def _search_semantic(
695
+ self,
696
+ conn: sqlite3.Connection,
697
+ query: str,
698
+ where: str,
699
+ params: list,
700
+ limit: int,
701
+ ) -> List[MemoryEntry]:
702
+ """TF-IDF 语义搜索"""
703
+ # 先取一批候选文档
704
+ candidate_sql = f"SELECT * FROM memories WHERE {where} ORDER BY created_at DESC LIMIT 200"
705
+ rows = conn.execute(candidate_sql, params).fetchall()
706
+
707
+ if not rows:
708
+ return []
709
+
710
+ # 构建文档列表(content + summary + key 混合文本)
711
+ documents = []
712
+ row_map: Dict[str, sqlite3.Row] = {}
713
+ for row in rows:
714
+ doc_id = row["id"]
715
+ text = f"{row['content']} {row['summary']} {row['key']}"
716
+ documents.append((doc_id, text))
717
+ row_map[doc_id] = row
718
+
719
+ # 计算 TF-IDF 得分
720
+ scores = self._compute_tfidf(query, documents)
721
+
722
+ # 按得分排序,取 top N
723
+ top_ids = list(scores.keys())[:limit]
724
+ result = [MemoryEntry.from_row(row_map[doc_id]) for doc_id in top_ids if doc_id in row_map]
725
+
726
+ # 更新访问计数
727
+ for entry in result:
728
+ conn.execute(
729
+ "UPDATE memories SET access_count = access_count + 1 WHERE id = ?",
730
+ (entry.id,),
731
+ )
732
+ conn.commit()
733
+
734
+ return result
735
+
736
+ def search_across_sessions(
737
+ self,
738
+ query: str,
739
+ category: str = "",
740
+ limit: int = 20,
741
+ mode: str = "hybrid",
742
+ ) -> List[MemoryEntry]:
743
+ """跨会话搜索"""
744
+ return self.search(query, session_id="", category=category, limit=limit, mode=mode)
745
+
746
+ # ==========================================================================
747
+ # 记忆总结与维护
748
+ # ==========================================================================
749
+
750
+ def get_recent_for_summary(self, session_id: str, count: int = 20) -> List[MemoryEntry]:
751
+ """获取最近的对话用于总结"""
752
+ return self.get_conversation(session_id, limit=count)
753
+
754
+ def save_summary(
755
+ self,
756
+ session_id: str,
757
+ summary: str,
758
+ original_count: int = 0,
759
+ ) -> str:
760
+ """保存对话总结为长期记忆"""
761
+ return self.add_long_term(
762
+ session_id=session_id,
763
+ key="conversation_summary",
764
+ content=summary,
765
+ summary=summary[:500],
766
+ importance=0.6,
767
+ metadata={"original_message_count": original_count},
768
+ )
769
+
770
+ def get_error_patterns(self, session_id: str = "global", limit: int = 20) -> List[MemoryEntry]:
771
+ """获取历史错误模式(用于避免重复犯错)"""
772
+ return self._query(
773
+ session_id=session_id,
774
+ category="long_term",
775
+ key="error_pattern",
776
+ limit=limit,
777
+ order_by="importance DESC",
778
+ )
779
+
780
+ def record_error_pattern(
781
+ self,
782
+ error: str,
783
+ fix: str = "",
784
+ session_id: str = "global",
785
+ ):
786
+ """记录错误模式及修复方案"""
787
+ self.add_long_term(
788
+ session_id=session_id,
789
+ key="error_pattern",
790
+ content=f"错误: {error}\n修复: {fix}",
791
+ summary=f"错误: {truncate_str(error, 200)} | 修复: {truncate_str(fix, 200)}",
792
+ importance=0.8,
793
+ )
794
+
795
+ # ==========================================================================
796
+ # 统计与管理
797
+ # ==========================================================================
798
+
799
+ def get_stats(self) -> Dict[str, Any]:
800
+ """获取记忆系统统计"""
801
+ conn = self._get_conn()
802
+ stats = {}
803
+ for cat in ("short_term", "working", "long_term"):
804
+ row = conn.execute(
805
+ "SELECT COUNT(*) as cnt FROM memories WHERE category = ?", (cat,)
806
+ ).fetchone()
807
+ stats[f"{cat}_count"] = row["cnt"]
808
+
809
+ total = conn.execute("SELECT COUNT(*) as cnt FROM memories").fetchone()
810
+ stats["total_count"] = total["cnt"]
811
+
812
+ sessions = conn.execute(
813
+ "SELECT COUNT(DISTINCT session_id) as cnt FROM memories"
814
+ ).fetchone()
815
+ stats["session_count"] = sessions["cnt"]
816
+
817
+ return stats
818
+
819
+ def cleanup_expired(self) -> int:
820
+ """清理过期记忆"""
821
+ conn = self._get_conn()
822
+ now = timestamp()
823
+ cursor = conn.execute(
824
+ "DELETE FROM memories WHERE expires_at != '' AND expires_at < ?",
825
+ (now,),
826
+ )
827
+ conn.commit()
828
+ count = cursor.rowcount
829
+ if count > 0:
830
+ logger.info(f"清理过期记忆: {count} 条")
831
+ return count
832
+
833
+ def export_session(self, session_id: str) -> Dict[str, Any]:
834
+ """导出会话所有记忆"""
835
+ entries = self._query(session_id=session_id, limit=10000)
836
+ return {
837
+ "session_id": session_id,
838
+ "exported_at": timestamp(),
839
+ "memories": [asdict(e) for e in entries],
840
+ }