mirror of
https://github.com/AstrBotDevs/AstrBot
synced 2026-07-17 01:49:15 +08:00
* Add legacy session waiter compatibility * Expand legacy astrbot package compatibility * Tighten external legacy plugin compatibility smoke tests * Consolidate controlled legacy facade compatibility * docs: clarify compat package boundaries * test: align runtime fixtures with maintained samples * fix: preserve unicode sample fixtures in runtime tests * Implement legacy hook and tool compat runtime * Refactor legacy runtime execution boundary * 增强旧版兼容性,添加多个旧路径入口和相关功能 * 增强旧版兼容性,添加适配器边界的启动和关闭钩子支持 * Refactor legacy API and LLM compatibility logic - Moved legacy LLM and tool compatibility logic from `_legacy_api.py` to a new module `_legacy_llm.py` for better organization and separation of concerns. - Updated `_legacy_api.py` to import necessary components from `_legacy_llm.py`, removing redundant code. - Enhanced database client functionality by adding support for batch read/write operations and change event subscriptions. - Improved documentation in the database client and capability router to reflect new features. - Refined environment management process in the loader to better handle plugin grouping and virtual environment management. * 补充插件分组环境测试覆盖 * feat: Enhance CLI and testing capabilities - Added a new script entry point `astrbot-sdk` in `pyproject.toml`. - Introduced `has_waiter` method in `SessionWaiterManager` to check for existing waiters. - Updated `cli.py` to improve error handling and added context to error messages. - Implemented local development support in `cli.py` with a new `dev` command for running plugins against a mock core. - Created a new testing module `astrbot_sdk.testing` with utilities for local development and plugin testing. - Added comprehensive tests for the new testing module and CLI commands. - Improved compatibility and error messaging for plugin loading failures. * feat: 添加插件初始化、验证和构建命令,增强 CLI 功能 * feat: add platform client documentation and examples - Introduced platform client documentation in `docs/v4/clients/platform.md` detailing methods for sending messages, images, and managing group members. - Added example plugins for LLM chat and database functionalities in `docs/v4/examples/README.md`, `docs/v4/examples/llm-chat/README.md`, and `docs/v4/examples/database/README.md`. - Enhanced quickstart guide with links to new documentation and example plugins. - Implemented runtime contract tests to ensure compatibility of public capabilities and hooks. * Refactor legacy runtime handling and improve plugin loading - Updated `handler_dispatcher.py` to streamline legacy runtime preparation and dispatching results. - Enhanced `loader.py` to simplify legacy plugin detection and manifest building. - Added tests for new HTTPClient and MetadataClient functionalities. - Introduced tests for legacy context metadata methods and legacy loader helpers. - Improved legacy runtime tests to cover new functionality and edge cases. * refactor: 更新兼容层和导入路径,优化文档描述 * Support grouped plugin workers in shared environments - add group metadata driven worker startup for shared env plans - track per-plugin handler and capability ownership inside grouped workers - update runtime and smoke tests for grouped worker session behavior * Add v4 compat layer and legacy shims - Introduce private v4 compatibility surface using _legacy_api.py, _legacy_runtime.py, _legacy_loader.py plus new _legacy_context.py and _legacy_star.py to centralize legacy adapters while keeping public APIs thin. - Extend InitializeOutput to carry protocol_version for negotiated protocol, enabling runtime to adapt to the chosen v4 version. - Add lightweight legacy support for Star/Context via new LegacyStar and LegacyContext shims and expose legacy API through the aggregate _legacy_api entry point. - Ensure legacy loader preserves class declaration order by iterating module.__dict__ instead of relying on alphabetical sorting. - Add tests: protocol_version handling in InitializeOutput, legacy main component order preservation, and embedded-newline framing in transport tests. * Add architecture doc and refine API compat - Add PROJECT_ARCHITECTURE.md documenting architecture, compat surface, and testing notes. - Update astrbot_sdk.api.__init__ to clarify it is a compatibility implementation layer, not a simple facade, and list migration targets. - Normalize platform in AstrMessageEvent.to_payload to emit a string id by using get_platform_id(). * Potential fix for pull request finding Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> * delete old sdk * delete old sdk (#7) Co-authored-by: whatevertogo <whatevertogo@users.noreply.github.com> * feat(cli): normalize plugin init skeletons Add interactive plugin init prompts and normalize generated plugin names to the astrbot_plugin_ convention. Update CLI tests for the new skeleton layout and ignore generated plugin directories in git and coverage tooling. Also include related runtime logging adjustments from the current worktree. * Create lint.yml * Update lint.yml * clean it * feat: Enhance handler and capability dispatchers with improved error handling - Updated HandlerDispatcher to raise TypeError for uninjectable required parameters, logging errors appropriately. - Refactored CapabilityDispatcher to raise TypeError for missing required parameters during capability execution. - Renamed _load_plugin_config to load_plugin_config for clarity and consistency. - Introduced _sync_plugin_registry method in SupervisorRuntime to manage plugin capabilities more effectively. - Enhanced capability registration logic to handle naming conflicts with better logging and automatic renaming. - Added tests for handler and capability dispatchers to ensure proper error handling and functionality. - Implemented new HTTP and metadata capabilities with corresponding tests for registration and retrieval. - Improved MemoryClient methods with additional tests for save_with_ttl, get_many, delete_many, and stats. - Added tests for the testing module to ensure proper import and functionality of PluginHarness. * feat: 更新 SDK 描述,重构插件调用上下文,移除插件 ID 传递,增强能力路由和 HTTP 客户端的插件身份管理 * refactor: 更新文档和代码注释,优化兼容性描述,增强可读性 * feat: 添加插件热重载功能,支持文件变更时自动重新加载插件 * feat: 增强错误处理,添加上下文信息,优化插件组件加载和参数注入校验 * feat: 添加 hello_plugin 示例,包含插件结构、命令处理和测试用例 * refactor: 删除过时的架构文档、变更日志和兼容矩阵文件 * refactor: 更新兼容层弃用通知,优化文档结构和可读性 * refactor: 更新项目架构文档,增强能力客户端和执行边界的描述,移除兼容层设计章节 * feat(errors): Enhance AstrBotError with detailed documentation and examples feat(events): Expand MessageEvent with reply capabilities and detailed docstrings fix(loader): Ensure plugin path is correctly managed in sys.path feat(star): Improve Star class documentation and lifecycle method descriptions feat(testing): Add plugin metadata handling in MockContext and enhance PluginHarness feat(hello): Refactor HelloPlugin to utilize new reply methods and structured capabilities test(decorators): Add tests for input/output model support in provide_capability test(events): Implement tests for reply_image and reply_chain methods in MessageEvent test(http): Validate API registration with capability handler references and error handling test(tests): Enhance tests for plugin harness and directory handling in dev commands * feat(runtime): add configurable msgpack wire codec support * fix(runtime): align msgpack framing with transport defaults * fix(runtime): preserve json transport compatibility * fix(cli): scope worker wire codec option * feat: 添加 AGENTS.md 文档,描述 v4 架构约束和开发命令 refactor: 更新 HandlerDispatcher 和 WorkerSession,增强参数处理和结果汇总逻辑 * fix(test): 更新 init_plugin 测试以匹配新的目录命名规范 CLI 的 _normalize_init_plugin_name 函数现在自动添加 astrbot_plugin_ 前缀, 测试期望的目录名从 demo_plugin 更新为 astrbot_plugin_demo_plugin。 * Refactor worker initialization and remove unused codec parameters; add schedule and session waiter modules - Simplified `GroupWorkerRuntime` and `PluginWorkerRuntime` constructors by removing the codec parameter and related logic. - Introduced `schedule.py` to define `ScheduleContext` for managing scheduled tasks with a clear structure and payload handling. - Added `session_waiter.py` for session-based conversational flow management, including `SessionController` and `SessionWaiterManager` for handling multi-turn dialogues. - Enhanced testing utilities in `testing.py` by removing unused classes and streamlining the structure. - Created `types.py` to introduce `GreedyStr` for improved command parameter parsing. * feat: 添加 LLM 工具管理和会话级别状态管理能力 - 新增 llm/ 模块,包含 LLMToolSpec、ProviderRequest、AgentSpec 等实体 - 新增 LLMToolManager 用于管理 LLM 工具注册和激活状态 - 新增 SessionPluginManager 用于会话级别的插件启用状态管理 - 新增 SessionServiceManager 用于会话级别的 LLM/TTS 服务状态管理 - 新增 RegistryClient 用于查询 handler 元数据和设置白名单 - 扩展 CapabilityRouter 内置能力,支持 session.* 和 registry.* 命名空间 - 增强描述符和装饰器以支持新的 trigger 类型 * feat: 大幅增强 SDK 核心功能和文档 新增模块: - clients/files.py: 文件上传/下载客户端 - clients/managers.py: 会话/LLM/Provider 管理器 - clients/provider.py: LLM Provider 客户端 - conversation.py: 对话上下文管理 - plugin_kv.py: 插件 KV 存储辅助 - runtime/limiter.py: 限流器 - star_tools.py: Star 工具函数 - docs/: 完整的 SDK 使用文档 (01-05) 功能增强: - Context 大幅扩展,增加 reply/send_image/typing 等便捷方法 - 装饰器增强,支持 on_llm_request/on_provider_request 等 - 内置 schemas 扩展,覆盖更多 capability 定义 - capability_router_builtins 大幅扩展内置能力实现 - handler_dispatcher 增强参数注入和错误处理 - Star 基类增加生命周期钩子和工具方法 * Add comprehensive API documentation for types and utilities in AstrBot SDK - Introduced `types.md` detailing type aliases, generics, and Pydantic models used in the SDK. - Added `utils.md` covering utility classes and functions including CancelToken, MessageSession, command groups, and session management. - Included usage examples and detailed descriptions for each component to enhance developer understanding and ease of use. * feat: 添加高级方法和辅助函数文档,增强消息组件和事件处理功能 * feat: 增强过滤器类型和能力路由文档,添加 Provider 和会话管理功能 * change location * delete no need thing * delete again * feat: add Star plugin base class and StarTools utility class - Introduced `Star` class as a base for v4 native plugins, providing lifecycle methods and context management. - Added `StarTools` class for accessing runtime context and managing LLM tools. - Implemented `PluginHarness` for local development and testing of plugins, allowing for message dispatching and lifecycle management. - Created `GreedyStr` type for enhanced command parameter parsing, enabling the capture of remaining command text as a single argument. - Added testing utilities and mock capabilities for plugin development. * delete: remove hello_plugin example and its related files * Remove obsolete test files for testing module, top-level modules, transport, and wire codecs - Deleted `test_testing_module.py` as it is no longer needed. - Removed `test_top_level_modules.py` which had no content. - Eliminated `test_transport.py` due to redundancy. - Cleared out `test_wire_codecs.py` as part of the cleanup. * fix(runtime): avoid creating Star instance in on_error fallback * fix(runtime): avoid virtual dispatch in Star.on_error fallback * refactor(runtime): unify command matching logic (#25) * refactor(testing): share command matching with handler dispatcher * fix:添加公共函数文件 * fix: simplify register_task completion handling (#27) * fix: simplify register_task completion handling Remove duplicated cancellation logging in Context.register_task while keeping Future inputs compatible with asyncio.create_task semantics. Add regression coverage for coroutine, Future, cancellation, and failure paths. * fix: prioritize local src in tests_v4 Ensure tests_v4 always imports the working tree package by moving src to sys.path[0] even when another checkout or installed copy is already present. * chore: sync subtree from AstrBot * feat: replay non-sdk changes on clean sdk subtree baseline * feat(sdk): add merged provider config capability support Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai> * feat(sdk): add merged provider config bridge and client Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai> * feat(sdk): add merged provider config capability support Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai> * fix(sdk): tighten bridge cast typing Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai> * feat(sdk): add merged provider config bridge and client Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai> * test(sdk): cover merged provider config parity Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai> * feat: 完善 memory 向量检索与索引统计 (#28) Co-authored-by: united_pooh <united_pooh@outlook.com> * feat(tests): 添加测试用例以验证 register_task 的行为并更新测试运行说明 * Merge commit 'e45bade147ff44b43860ecff12067309e59c151a' into feat/sdk-integration * Squashed 'astrbot-sdk/' changes from 7dda6077..85342f1485342f14feat(tests): 添加测试用例以验证 register_task 的行为并更新测试运行说明fdffc09bMerge pull request #26 from united-pooh/fix/fix-star-on-error-fallback3b09747cfeat: 完善 memory 向量检索与索引统计 (#28)665c9c69fix(runtime): avoid virtual dispatch in Star.on_error fallback200559a5fix(runtime): avoid creating Star instance in on_error fallback git-subtree-dir: astrbot-sdk git-subtree-split:85342f149b* feat(tests): 添加测试用例以验证平台和消息类型过滤器的冲突处理 * docs: remove redundant testing instructions from AGENTS.md * docs: remove redundant testing instructions from AGENTS.md * docs: remove redundant testing instructions from AGENTS.md * Merge commit '5ac9401852ddb46f337da6bcc0f9b66eed265da9' into feat/sdk-integration * Squashed 'astrbot-sdk/' changes from 85342f14..09beabeb09beabebfeat(tests): 添加测试用例以验证平台和消息类型过滤器的冲突处理 git-subtree-dir: astrbot-sdk git-subtree-split:09beabeb62* feat: enhance SDK plugin configuration handling and logging * feat: enhance SDK plugin configuration handling and logging * feat: enhance SDK plugin configuration handling and logging * feat: 增强装饰器功能,添加会话命令支持及相关权限和限流装饰器 * feat: 增强装饰器功能,添加会话命令支持及相关权限和限流装饰器 * feat: 增强装饰器功能,添加会话命令支持及相关权限和限流装饰器 * feat: 更新文档以反映SDK负载的JSON可序列化要求和延迟导入设计约束 * feat: add conversation.get_current capability and related schemas - Introduced CONVERSATION_GET_CURRENT_INPUT_SCHEMA and CONVERSATION_GET_CURRENT_OUTPUT_SCHEMA for handling current conversation requests. - Implemented _conversation_get_current method in BuiltinCapabilityRouterMixin to manage current conversation retrieval and creation. - Registered the new capability in CoreCapabilityBridge. - Enhanced HandlerDispatcher to inject provider request, LLM response, and event result payloads into the event handling process. - Updated tests to validate the new functionality and ensure proper payload handling. * feat: add conversation.get_current capability and related schemas - Introduced CONVERSATION_GET_CURRENT_INPUT_SCHEMA and CONVERSATION_GET_CURRENT_OUTPUT_SCHEMA for handling current conversation requests. - Implemented _conversation_get_current method in BuiltinCapabilityRouterMixin to manage current conversation retrieval and creation. - Registered the new capability in CoreCapabilityBridge. - Enhanced HandlerDispatcher to inject provider request, LLM response, and event result payloads into the event handling process. - Updated tests to validate the new functionality and ensure proper payload handling. * feat: add conversation.get_current capability and related schemas - Introduced CONVERSATION_GET_CURRENT_INPUT_SCHEMA and CONVERSATION_GET_CURRENT_OUTPUT_SCHEMA for handling current conversation requests. - Implemented _conversation_get_current method in BuiltinCapabilityRouterMixin to manage current conversation retrieval and creation. - Registered the new capability in CoreCapabilityBridge. - Enhanced HandlerDispatcher to inject provider request, LLM response, and event result payloads into the event handling process. - Updated tests to validate the new functionality and ensure proper payload handling. * Refactor tool call handling in SdkPluginBridge - Introduced a dictionary to map tool call IDs to tool names for better clarity and efficiency. - Enhanced the extraction of tool call information from raw results, ensuring compatibility with both dictionary and object formats. - Updated the logic to retrieve tool names based on tool call IDs, improving the robustness of the tool calls result processing. * Refactor tool call handling in SdkPluginBridge - Introduced a dictionary to map tool call IDs to tool names for better clarity and efficiency. - Enhanced the extraction of tool call information from raw results, ensuring compatibility with both dictionary and object formats. - Updated the logic to retrieve tool names based on tool call IDs, improving the robustness of the tool calls result processing. * Refactor tool call handling in SdkPluginBridge - Introduced a dictionary to map tool call IDs to tool names for better clarity and efficiency. - Enhanced the extraction of tool call information from raw results, ensuring compatibility with both dictionary and object formats. - Updated the logic to retrieve tool names based on tool call IDs, improving the robustness of the tool calls result processing. * feat: add session and system capabilities for plugin management and event handling - Implemented SessionCapabilityMixin with methods to manage session-level plugin states and handlers. - Added SystemCapabilityMixin to handle system-level functionalities including file management, event handling, and dynamic command registration. - Introduced methods for enabling/disabling plugins, filtering handlers, and managing LLM and TTS service states. - Registered various system capabilities for data directory access, HTML rendering, and event streaming. * feat: add session and system capabilities for plugin management and event handling - Implemented SessionCapabilityMixin with methods to manage session-level plugin states and handlers. - Added SystemCapabilityMixin to handle system-level functionalities including file management, event handling, and dynamic command registration. - Introduced methods for enabling/disabling plugins, filtering handlers, and managing LLM and TTS service states. - Registered various system capabilities for data directory access, HTML rendering, and event streaming. * Squashed 'astrbot-sdk/' changes from 09beabeb..3204c9db3204c9dbMerge sdk-remote dev into feat/sdk-integration3a2d715eRefactor tool call handling in SdkPluginBridgeed1b9665feat: add conversation.get_current capability and related schemase74123bbfeat: 增强装饰器功能,添加会话命令支持及相关权限和限流装饰器bb361cf9feat: 增强装饰器功能,添加会话命令支持及相关权限和限流装饰器c6237f52Merge sdk-remote/dev into astrbot-sdk subtreee12029fffeat: enhance SDK plugin configuration handling and logging5e54bbb3feat: enhance SDK plugin configuration handling and loggingf48e2041Merge commit '5ac9401852ddb46f337da6bcc0f9b66eed265da9' into feat/sdk-integration619672e6Merge commit '5ac9401852ddb46f337da6bcc0f9b66eed265da9' into feat/sdk-integrationd5a3796ddocs: remove redundant testing instructions from AGENTS.md323e3f4ddocs: remove redundant testing instructions from AGENTS.mdf8438a7bMerge commit 'e45bade147ff44b43860ecff12067309e59c151a' into feat/sdk-integration96d1df85Merge commit 'e45bade147ff44b43860ecff12067309e59c151a' into feat/sdk-integrationf8a7e253feat(sdk): add merged provider config bridge and client752dc6cffeat(sdk): add merged provider config capability support git-subtree-dir: astrbot-sdk git-subtree-split:3204c9db9f* Implement feature X to enhance user experience and optimize performance * Implement feature X to enhance user experience and optimize performance * chore(sdk): stop tracking uv.lock * feat(sdk): add merged provider config capability support Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai> * feat(sdk): add merged provider config bridge and client Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai> * feat(tests): 添加测试用例以验证 register_task 的行为并更新测试运行说明 * feat(tests): 添加测试用例以验证平台和消息类型过滤器的冲突处理 * docs: remove redundant testing instructions from AGENTS.md * feat: enhance SDK plugin configuration handling and logging * feat: 增强装饰器功能,添加会话命令支持及相关权限和限流装饰器 * feat: add conversation.get_current capability and related schemas - Introduced CONVERSATION_GET_CURRENT_INPUT_SCHEMA and CONVERSATION_GET_CURRENT_OUTPUT_SCHEMA for handling current conversation requests. - Implemented _conversation_get_current method in BuiltinCapabilityRouterMixin to manage current conversation retrieval and creation. - Registered the new capability in CoreCapabilityBridge. - Enhanced HandlerDispatcher to inject provider request, LLM response, and event result payloads into the event handling process. - Updated tests to validate the new functionality and ensure proper payload handling. * Refactor tool call handling in SdkPluginBridge - Introduced a dictionary to map tool call IDs to tool names for better clarity and efficiency. - Enhanced the extraction of tool call information from raw results, ensuring compatibility with both dictionary and object formats. - Updated the logic to retrieve tool names based on tool call IDs, improving the robustness of the tool calls result processing. * feat: add session and system capabilities for plugin management and event handling - Implemented SessionCapabilityMixin with methods to manage session-level plugin states and handlers. - Added SystemCapabilityMixin to handle system-level functionalities including file management, event handling, and dynamic command registration. - Introduced methods for enabling/disabling plugins, filtering handlers, and managing LLM and TTS service states. - Registered various system capabilities for data directory access, HTML rendering, and event streaming. * fix(runtime): avoid creating Star instance in on_error fallback * fix(runtime): avoid virtual dispatch in Star.on_error fallback * feat: refactor injected parameter handling and introduce is_framework_injected_parameter utility * Squashed 'astrbot-sdk/' changes from 027c15b4..d078e510d078e510feat: refactor injected parameter handling and introduce is_framework_injected_parameter utility461f7276Merge branch 'dev' of https://github.com/united-pooh/astrbot-sdk into dev5ead59c4fix(runtime): avoid virtual dispatch in Star.on_error fallbackd2382858fix(runtime): avoid creating Star instance in on_error fallbacke961e361feat: add session and system capabilities for plugin management and event handling5a46321aRefactor tool call handling in SdkPluginBridge47698448feat: add conversation.get_current capability and related schemas9b35bec8feat: 增强装饰器功能,添加会话命令支持及相关权限和限流装饰器48a20240feat: enhance SDK plugin configuration handling and loggingcb593a53docs: remove redundant testing instructions from AGENTS.mdf4942076feat(tests): 添加测试用例以验证平台和消息类型过滤器的冲突处理b0f8b2d6feat(tests): 添加测试用例以验证 register_task 的行为并更新测试运行说明6e417c6dfeat(sdk): add merged provider config bridge and client659eabcefeat(sdk): add merged provider config capability support REVERT:027c15b4Implement feature X to enhance user experience and optimize performance REVERT:c272661fchore: pull sdk subtree from dev (resolve delete/modify conflict) REVERT:0a2a3592feat: add session and system capabilities for plugin management and event handling REVERT:3204c9dbMerge sdk-remote dev into feat/sdk-integration REVERT:36443f1dRefactor tool call handling in SdkPluginBridge REVERT:3a2d715eRefactor tool call handling in SdkPluginBridge REVERT:b93c2c2bfeat: add conversation.get_current capability and related schemas REVERT:ed1b9665feat: add conversation.get_current capability and related schemas REVERT:e74123bbfeat: 增强装饰器功能,添加会话命令支持及相关权限和限流装饰器 REVERT:bb361cf9feat: 增强装饰器功能,添加会话命令支持及相关权限和限流装饰器 REVERT:c6237f52Merge sdk-remote/dev into astrbot-sdk subtree REVERT:e12029fffeat: enhance SDK plugin configuration handling and logging REVERT:5e54bbb3feat: enhance SDK plugin configuration handling and logging REVERT:f48e2041Merge commit '5ac9401852ddb46f337da6bcc0f9b66eed265da9' into feat/sdk-integration REVERT:619672e6Merge commit '5ac9401852ddb46f337da6bcc0f9b66eed265da9' into feat/sdk-integration REVERT:d5a3796ddocs: remove redundant testing instructions from AGENTS.md REVERT:323e3f4ddocs: remove redundant testing instructions from AGENTS.md REVERT:f8438a7bMerge commit 'e45bade147ff44b43860ecff12067309e59c151a' into feat/sdk-integration REVERT:96d1df85Merge commit 'e45bade147ff44b43860ecff12067309e59c151a' into feat/sdk-integration REVERT:f8a7e253feat(sdk): add merged provider config bridge and client REVERT:752dc6cffeat(sdk): add merged provider config capability support git-subtree-dir: astrbot-sdk git-subtree-split:d078e51051* refactor: reorganize imports and enhance type hints in sdk_bridge modules * refactor: update import paths to use Path for better compatibility * refactor(injection): centralize legacy injected parameter filtering * fix(testing): use public session waiter probe in PluginHarness * docs: add TODO for documentation content in _command_model.py * feat: add memory management capabilities to CoreCapabilityBridge and implement unit tests * feat: enhance memory search functionality and improve metadata retrieval in SDK * feat: add memory management attributes and typed provider method to CapabilityMixinHost * Implement feature X to enhance user experience and optimize performance * Refactor memory utility functions and enhance memory capability mixin - Added new utility functions for memory management in _memory_utils.py. - Refactored memory capability mixin methods to utilize the new utility functions for better readability and maintainability. - Updated PROJECT_ARCHITECTURE.md to reflect changes in documentation and structure. * Squashed 'astrbot-sdk/' changes from d078e510..208bc591208bc591Merge pull request #30 from united-pooh/refactor/unify-legacy-injected-paramsd86534a2docs: add TODO for documentation content in _command_model.py090724a7refactor(injection): centralize legacy injected parameter filtering git-subtree-dir: astrbot-sdk git-subtree-split:208bc591dd* Initial plan * docs: fix path, Python version, and client API table in PROJECT_ARCHITECTURE.md Co-authored-by: whatevertogo <149563971+whatevertogo@users.noreply.github.com> * Squashed 'astrbot-sdk/' changes from 208bc591..ad5e8d13ad5e8d13Merge pull request #37 from united-pooh/sdk/whatevertogo5751701fMerge pull request #38 from united-pooh/copilot/sub-pr-37e21acba5docs: fix path, Python version, and client API table in PROJECT_ARCHITECTURE.mdee67cab4Initial plan7d921570Refactor memory utility functions and enhance memory capability mixin git-subtree-dir: astrbot-sdk git-subtree-split:ad5e8d1397* docs: fix TODO comment formatting in _command_model.py * 集成SDK命令候选项,优化Telegram和Discord平台适配器的命令收集逻辑 * 删除AI女友插件的单元测试文件 * 更新文档,添加Telegram和Discord原生命令菜单的注册说明 * Squashed 'astrbot-sdk/' changes from ad5e8d13..5003da585003da58Merge pull request #40 from united-pooh/sdk/whatevertogob5084c44Merge branch 'sdk/whatevertogo' of https://github.com/united-pooh/astrbot-sdk into sdk/whatevertogo7559edf7docs: fix TODO comment formatting in _command_model.py git-subtree-dir: astrbot-sdk git-subtree-split:5003da58f5* fix(testing): route session waiter followups through dispatcher (#33) * fix(testing): route session waiter followups through dispatcher * fix(testing): preserve waiter context and completion state * fix(runtime): preserve session waiter plugin identity * fix(runtime): scope session waiters by plugin * fix(testing): isolate waiter replacement and followup drains * fix(runtime): normalize waiter routing inputs * fix(cli): route protocol stdout at command entry (#41) * 添加内存后端支持,优化插件内存管理逻辑 * feat(memory): enhance memory schemas and add namespace support - Updated MEMORY_SEARCH_INPUT_SCHEMA to include `namespace` and `include_descendants`. - Modified MEMORY_SEARCH_OUTPUT_SCHEMA to allow nullable `namespace`. - Added `namespace` to MEMORY_GET_INPUT_SCHEMA, MEMORY_DELETE_INPUT_SCHEMA, MEMORY_SAVE_WITH_TTL_INPUT_SCHEMA, MEMORY_GET_MANY_INPUT_SCHEMA, and MEMORY_DELETE_MANY_INPUT_SCHEMA. - Enhanced MEMORY_STATS_INPUT_SCHEMA to support `namespace` and `include_descendants`. - Updated MEMORY_GET_OUTPUT_SCHEMA and MEMORY_STATS_OUTPUT_SCHEMA to include `namespace` and `namespace_count`. - Introduced `_memory_backends` in CapabilityRouterHost and CapabilityRouterBridgeBase for better memory management. - Refactored MemoryCapabilityMixin to utilize memory backends for plugin-specific memory operations. - Improved memory search functionality to respect namespaces and include descendants based on input parameters. - Added tests to validate memory operations across different namespaces and ensure persistence across restarts. - Implemented error handling in the handler dispatcher to manage exceptions gracefully. * fix: guard session_waiter blocking usage * fix(runtime): preserve request-scoped system event overlays * test(runtime): lock peer initialization and transport failure semantics * test(loader): cover plugin reload and import isolation regressions * refactor(supervisor): clarify plugin registry sync phases * test(clients): cover provider lifecycle regressions * feat(cli): improve astr init defaults * feat(plugin): add plugin ID validation and data directory resolution - Implemented `validate_plugin_id` to ensure safe plugin identifiers. - Added `resolve_plugin_data_dir` to resolve plugin data directories securely. - Updated memory and system capabilities to utilize new plugin ID validation. - Refactored session waiter management to simplify plugin ID handling. - Enhanced tests for plugin ID validation and data directory resolution. * fix(cli): exit cleanly on init abort * feat(memory): enhance namespace handling and add tests for memory client * feat(agent): add tool status message handling and improve SDK command integration * Refactor SDK structure for backward compatibility - Moved message result and session classes to internal modules while preserving legacy import paths for compatibility. - Updated imports across the SDK to reflect the new internal structure. - Enhanced session waiter management to support multiple plugins and improve error handling. - Added tests to ensure LLM tool registration and session waiter functionality align with dispatcher expectations. - Cleaned up code and improved documentation for clarity and maintainability. * 增强异步下载功能,更新组件导入方式,并添加相关测试用例 * 添加任务重入锁以支持会话等待器的嵌套清理,并更新相关测试用例以验证后续消息的序列化处理 * 添加 .astrbot_sdk_testing 到 .gitignore 文件 * Add unit tests for provider management and tool capabilities - Introduced new test suite for provider platform management in `test_sdk_provider_platform_management.py`, covering scenarios for merged provider configurations, reserved plugin checks, and provider management functionalities. - Added tests for tool capabilities and provider queries in `test_sdk_provider_tool_platform_capabilities.py`, validating interactions with LLM tools and specialized proxies. - Removed obsolete `test_sdk_transport.py` as it contained outdated tests for transport layer functionality. * 添加多个模块和测试用例,增强SDK功能并支持单元测试 * fix(bridge): add missing capability registrations for db/memory/http/metadata Register methods for db, memory, http, and metadata capabilities exist in BasicCapabilityMixin but were never called in CoreCapabilityBridge.__init__. This caused SDK plugins using ctx.memory, ctx.db, ctx.http to fail with "LookupError: capability not found". * feat(kb): enhance knowledge base capabilities with document management and serialization * 添加知识库文档管理功能,包括文档上传、列表、获取、删除和刷新能力,更新相关的能力路由和协议模式 * feat(conversation): add ability to unset conversation persona and update related methods * 添加对话管理和元数据管理功能,包括清空对话人格和保存插件配置的能力 * feat(conversation): add test for unsetting conversation persona and verify state * feat(plugin): add save_plugin_config method and related tests for plugin configuration persistence * 优化插件配置保存方法的代码格式 * feat(sdk): enhance handler metadata with descriptions, priority, kind, and admin requirements * 添加描述、优先级和其他元数据到处理程序元数据和描述符中,优化相关功能 * feat(sdk): enhance SDK integration with local extras handling and message payloads * 添加对 MessageEvent 的额外字段支持,优化事件处理器的参数注入,增强 SDK 本地临时数据的管理能力 * 增强插件日志记录功能,添加控制台输出格式化和路径标签支持,新增单元测试以验证日志格式 * feat: Enhance command and tool management in dashboard - Refactor CommandRoute to utilize AstrBotCoreLifecycle for improved command handling. - Introduce command_key for commands to streamline toggling, renaming, and permission updates. - Implement support for SDK commands in the dashboard, marking them as read-only. - Update ToolTable and CommandTable components to use new command_key and tool_key properties. - Add runtime_kind and plugin_id to tools for better management. - Enhance API tests to cover SDK commands and tools, ensuring proper functionality and error handling. - Update localization files to include new messages related to SDK commands. * 优化插件日志记录和能力代理模块,增强异常处理,确保优先级参数为整数 * feat: 增强LLM能力,添加聊天提供者协议和异常处理,更新单元测试以验证提供者有效性 * feat: Implement SDK skill management capabilities - Added SkillCapabilityMixin to handle skill registration, unregistration, and listing. - Integrated skill management into the CoreCapabilityBridge. - Enhanced SkillManager to support SDK-registered skills, including loading, saving, and syncing skills. - Updated computer_client to utilize SkillManager for skill synchronization with sandboxes. - Refactored skill export functionality in SkillsRoute to accommodate new skill management structure. - Introduced tests for SDK skill registration, unregistration, and syncing to ensure functionality. - Improved skill handling in the dashboard and test suite to reflect changes in skill management. * 添加技能注册功能,包含技能注册、注销和列出能力的实现,增强插件能力管理 * 删除CLAUDE.md文档,移除过时的已知问题描述 * 删除 AGENTS.md 文档,移除过时的架构约束和开发命令说明 * 更新测试用例,修复插件发现失败时的错误信息,确保使用正确的运行时字段 * 修复错误处理和权限检查,新增单元测试以验证功能 * format * 增强命名空间管理,优化数据库操作,添加 HTTP 路由验证,新增并发隔离测试,完善命令模型解析单元测试 * 增强 HTTP 路由功能,添加 HTTP 方法注销逻辑的单元测试 * 格式化日志输出,优化批量插入时无内容提供的调试信息 * fix: add uv dependency for plugin environment groups * 删除代码审查文档 CODE_REVIEW_ISSUES.md * 添加消息历史管理功能,包括消息记录的增删查改,完善相关能力混合类和测试用例 * 实现 SDK 消息历史管理功能,包括记录的增删查改操作 * Add unit tests for MCP contract and capabilities in SDK - Implemented `_mcp_contract.py` to test local MCP server functionalities including listing, enabling, and disabling servers. - Created `test_sdk_mcp_capabilities.py` to cover various aspects of the CoreCapabilityBridge and SdkPluginBridge, including session management and global MCP server operations. - Introduced fake classes to simulate MCP server behavior and manage tool configurations for testing. - Ensured comprehensive coverage of MCP session lifecycle, including opening, listing tools, calling tools, and closing sessions. * feat(mcp): Implement local and global MCP server management capabilities - Added MCP management client to the context for local/global MCP service management. - Introduced decorators to acknowledge global MCP risk for plugins. - Defined schemas for MCP server operations including get, list, enable, disable, and session management. - Created MCP capability mixin to handle local and global MCP server operations. - Enhanced provider capabilities to include active local MCP tool names. - Updated capability router to support MCP functionalities and maintain session state. - Added tests for MCP functionalities, ensuring proper behavior and risk acknowledgment. --------- Co-authored-by: whatevertogo <149563971+whatevertogo@users.noreply.github.com> Co-authored-by: whatevertogo <whatevertogo@users.noreply.github.com> Co-authored-by: letr <letr007@foxmail.com> Co-authored-by: united_pooh <united_pooh@outlook.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Co-authored-by: united_pooh <united_pooh@icloud.com> Co-authored-by: Lishiling <m18384519631@163.com> Co-authored-by: Li-shi-ling <114913764+Li-shi-ling@users.noreply.github.com> Co-authored-by: letr <123731298+letr007@users.noreply.github.com> Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: catDforD <3276453835@qq.com> Co-authored-by: united_pooh <united_pooh@MBP-F6H6T2CYVV-2219.local>
1992 lines
72 KiB
Python
1992 lines
72 KiB
Python
import asyncio
|
|
import threading
|
|
from collections.abc import Awaitable, Callable, Sequence
|
|
from datetime import datetime, timedelta, timezone
|
|
from typing import Any, TypeVar, cast
|
|
|
|
from sqlalchemy import CursorResult, Row
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlmodel import col, delete, desc, func, or_, select, text, update
|
|
|
|
from astrbot.core.db import BaseDatabase
|
|
from astrbot.core.db.po import (
|
|
ApiKey,
|
|
Attachment,
|
|
ChatUIProject,
|
|
CommandConfig,
|
|
CommandConflict,
|
|
ConversationV2,
|
|
CronJob,
|
|
Persona,
|
|
PersonaFolder,
|
|
PlatformMessageHistory,
|
|
PlatformSession,
|
|
PlatformStat,
|
|
Preference,
|
|
SessionProjectRelation,
|
|
SQLModel,
|
|
)
|
|
from astrbot.core.db.po import (
|
|
Platform as DeprecatedPlatformStat,
|
|
)
|
|
from astrbot.core.db.po import (
|
|
Stats as DeprecatedStats,
|
|
)
|
|
from astrbot.core.sentinels import NOT_GIVEN
|
|
|
|
TxResult = TypeVar("TxResult")
|
|
CRON_FIELD_NOT_SET = object()
|
|
|
|
|
|
class SQLiteDatabase(BaseDatabase):
|
|
def __init__(self, db_path: str) -> None:
|
|
self.db_path = db_path
|
|
self.DATABASE_URL = f"sqlite+aiosqlite:///{db_path}"
|
|
self.inited = False
|
|
super().__init__()
|
|
|
|
async def initialize(self) -> None:
|
|
"""Initialize the database by creating tables if they do not exist."""
|
|
async with self.engine.begin() as conn:
|
|
await conn.run_sync(SQLModel.metadata.create_all)
|
|
await conn.execute(text("PRAGMA journal_mode=WAL"))
|
|
await conn.execute(text("PRAGMA synchronous=NORMAL"))
|
|
await conn.execute(text("PRAGMA cache_size=20000"))
|
|
await conn.execute(text("PRAGMA temp_store=MEMORY"))
|
|
await conn.execute(text("PRAGMA mmap_size=134217728"))
|
|
await conn.execute(text("PRAGMA optimize"))
|
|
# 确保 personas 表有 folder_id、sort_order、skills 列(前向兼容)
|
|
await self._ensure_persona_folder_columns(conn)
|
|
await self._ensure_persona_skills_column(conn)
|
|
await self._ensure_persona_custom_error_message_column(conn)
|
|
await conn.commit()
|
|
|
|
async def _ensure_persona_folder_columns(self, conn) -> None:
|
|
"""确保 personas 表有 folder_id 和 sort_order 列。
|
|
|
|
这是为了支持旧版数据库的平滑升级。新版数据库通过 SQLModel
|
|
的 metadata.create_all 自动创建这些列。
|
|
"""
|
|
result = await conn.execute(text("PRAGMA table_info(personas)"))
|
|
columns = {row[1] for row in result.fetchall()}
|
|
|
|
if "folder_id" not in columns:
|
|
await conn.execute(
|
|
text(
|
|
"ALTER TABLE personas ADD COLUMN folder_id VARCHAR(36) DEFAULT NULL"
|
|
)
|
|
)
|
|
if "sort_order" not in columns:
|
|
await conn.execute(
|
|
text("ALTER TABLE personas ADD COLUMN sort_order INTEGER DEFAULT 0")
|
|
)
|
|
|
|
async def _ensure_persona_skills_column(self, conn) -> None:
|
|
"""确保 personas 表有 skills 列。
|
|
|
|
这是为了支持旧版数据库的平滑升级。新版数据库通过 SQLModel
|
|
的 metadata.create_all 自动创建这些列。
|
|
"""
|
|
result = await conn.execute(text("PRAGMA table_info(personas)"))
|
|
columns = {row[1] for row in result.fetchall()}
|
|
|
|
if "skills" not in columns:
|
|
await conn.execute(text("ALTER TABLE personas ADD COLUMN skills JSON"))
|
|
|
|
async def _ensure_persona_custom_error_message_column(self, conn) -> None:
|
|
"""确保 personas 表有 custom_error_message 列。"""
|
|
result = await conn.execute(text("PRAGMA table_info(personas)"))
|
|
columns = {row[1] for row in result.fetchall()}
|
|
|
|
if "custom_error_message" not in columns:
|
|
await conn.execute(
|
|
text("ALTER TABLE personas ADD COLUMN custom_error_message TEXT")
|
|
)
|
|
|
|
# ====
|
|
# Platform Statistics
|
|
# ====
|
|
|
|
async def insert_platform_stats(
|
|
self,
|
|
platform_id,
|
|
platform_type,
|
|
count=1,
|
|
timestamp=None,
|
|
) -> None:
|
|
"""Insert a new platform statistic record."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
if timestamp is None:
|
|
timestamp = datetime.now().replace(
|
|
minute=0,
|
|
second=0,
|
|
microsecond=0,
|
|
)
|
|
current_hour = timestamp
|
|
await session.execute(
|
|
text("""
|
|
INSERT INTO platform_stats (timestamp, platform_id, platform_type, count)
|
|
VALUES (:timestamp, :platform_id, :platform_type, :count)
|
|
ON CONFLICT(timestamp, platform_id, platform_type) DO UPDATE SET
|
|
count = platform_stats.count + EXCLUDED.count
|
|
"""),
|
|
{
|
|
"timestamp": current_hour,
|
|
"platform_id": platform_id,
|
|
"platform_type": platform_type,
|
|
"count": count,
|
|
},
|
|
)
|
|
|
|
async def count_platform_stats(self) -> int:
|
|
"""Count the number of platform statistics records."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
result = await session.execute(
|
|
select(func.count(col(PlatformStat.platform_id))).select_from(
|
|
PlatformStat,
|
|
),
|
|
)
|
|
count = result.scalar_one_or_none()
|
|
return count if count is not None else 0
|
|
|
|
async def get_platform_stats(self, offset_sec: int = 86400) -> list[PlatformStat]:
|
|
"""Get platform statistics within the specified offset in seconds and group by platform_id."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
now = datetime.now()
|
|
start_time = now - timedelta(seconds=offset_sec)
|
|
result = await session.execute(
|
|
text("""
|
|
SELECT * FROM platform_stats
|
|
WHERE timestamp >= :start_time
|
|
GROUP BY platform_id
|
|
ORDER BY timestamp DESC
|
|
"""),
|
|
{"start_time": start_time},
|
|
)
|
|
return list(result.scalars().all())
|
|
|
|
# ====
|
|
# Conversation Management
|
|
# ====
|
|
|
|
async def get_conversations(self, user_id=None, platform_id=None):
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
query = select(ConversationV2)
|
|
|
|
if user_id:
|
|
query = query.where(ConversationV2.user_id == user_id)
|
|
if platform_id:
|
|
query = query.where(ConversationV2.platform_id == platform_id)
|
|
# order by
|
|
query = query.order_by(desc(ConversationV2.created_at))
|
|
result = await session.execute(query)
|
|
|
|
return result.scalars().all()
|
|
|
|
async def get_conversation_by_id(self, cid):
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
query = select(ConversationV2).where(ConversationV2.conversation_id == cid)
|
|
result = await session.execute(query)
|
|
return result.scalar_one_or_none()
|
|
|
|
async def get_all_conversations(self, page=1, page_size=20):
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
offset = (page - 1) * page_size
|
|
result = await session.execute(
|
|
select(ConversationV2)
|
|
.order_by(desc(ConversationV2.created_at))
|
|
.offset(offset)
|
|
.limit(page_size),
|
|
)
|
|
return result.scalars().all()
|
|
|
|
async def get_filtered_conversations(
|
|
self,
|
|
page=1,
|
|
page_size=20,
|
|
platform_ids=None,
|
|
search_query="",
|
|
**kwargs,
|
|
):
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
# Build the base query with filters
|
|
base_query = select(ConversationV2)
|
|
|
|
if platform_ids:
|
|
base_query = base_query.where(
|
|
col(ConversationV2.platform_id).in_(platform_ids),
|
|
)
|
|
if search_query:
|
|
search_query = search_query.encode("unicode_escape").decode("utf-8")
|
|
base_query = base_query.where(
|
|
or_(
|
|
col(ConversationV2.title).ilike(f"%{search_query}%"),
|
|
col(ConversationV2.content).ilike(f"%{search_query}%"),
|
|
col(ConversationV2.user_id).ilike(f"%{search_query}%"),
|
|
col(ConversationV2.conversation_id).ilike(f"%{search_query}%"),
|
|
),
|
|
)
|
|
if "message_types" in kwargs and len(kwargs["message_types"]) > 0:
|
|
for msg_type in kwargs["message_types"]:
|
|
base_query = base_query.where(
|
|
col(ConversationV2.user_id).ilike(f"%:{msg_type}:%"),
|
|
)
|
|
if "platforms" in kwargs and len(kwargs["platforms"]) > 0:
|
|
base_query = base_query.where(
|
|
col(ConversationV2.platform_id).in_(kwargs["platforms"]),
|
|
)
|
|
|
|
# Get total count matching the filters
|
|
count_query = select(func.count()).select_from(base_query.subquery())
|
|
total_count = await session.execute(count_query)
|
|
total = total_count.scalar_one()
|
|
|
|
# Get paginated results
|
|
offset = (page - 1) * page_size
|
|
result_query = (
|
|
base_query.order_by(desc(ConversationV2.created_at))
|
|
.offset(offset)
|
|
.limit(page_size)
|
|
)
|
|
result = await session.execute(result_query)
|
|
conversations = result.scalars().all()
|
|
|
|
return conversations, total
|
|
|
|
async def create_conversation(
|
|
self,
|
|
user_id,
|
|
platform_id,
|
|
content=None,
|
|
title=None,
|
|
persona_id=None,
|
|
cid=None,
|
|
created_at=None,
|
|
updated_at=None,
|
|
):
|
|
kwargs = {}
|
|
if cid:
|
|
kwargs["conversation_id"] = cid
|
|
if created_at:
|
|
kwargs["created_at"] = created_at
|
|
if updated_at:
|
|
kwargs["updated_at"] = updated_at
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
new_conversation = ConversationV2(
|
|
user_id=user_id,
|
|
content=content or [],
|
|
platform_id=platform_id,
|
|
title=title,
|
|
persona_id=persona_id,
|
|
**kwargs,
|
|
)
|
|
session.add(new_conversation)
|
|
return new_conversation
|
|
|
|
async def update_conversation(
|
|
self,
|
|
cid,
|
|
title=None,
|
|
persona_id=None,
|
|
clear_persona: bool = False,
|
|
content=None,
|
|
token_usage=None,
|
|
):
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
query = update(ConversationV2).where(
|
|
col(ConversationV2.conversation_id) == cid,
|
|
)
|
|
values = {}
|
|
if title is not None:
|
|
values["title"] = title
|
|
if clear_persona:
|
|
values["persona_id"] = None
|
|
elif persona_id is not None:
|
|
values["persona_id"] = persona_id
|
|
if content is not None:
|
|
values["content"] = content
|
|
if token_usage is not None:
|
|
values["token_usage"] = token_usage
|
|
if not values:
|
|
return None
|
|
query = query.values(**values)
|
|
await session.execute(query)
|
|
return await self.get_conversation_by_id(cid)
|
|
|
|
async def delete_conversation(self, cid) -> None:
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
await session.execute(
|
|
delete(ConversationV2).where(
|
|
col(ConversationV2.conversation_id) == cid,
|
|
),
|
|
)
|
|
|
|
async def delete_conversations_by_user_id(self, user_id: str) -> None:
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
await session.execute(
|
|
delete(ConversationV2).where(
|
|
col(ConversationV2.user_id) == user_id
|
|
),
|
|
)
|
|
|
|
async def get_session_conversations(
|
|
self,
|
|
page=1,
|
|
page_size=20,
|
|
search_query=None,
|
|
platform=None,
|
|
) -> tuple[list[dict], int]:
|
|
"""Get paginated session conversations with joined conversation and persona details."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
offset = (page - 1) * page_size
|
|
|
|
base_query = (
|
|
select(
|
|
col(Preference.scope_id).label("session_id"),
|
|
func.json_extract(Preference.value, "$.val").label(
|
|
"conversation_id",
|
|
), # type: ignore
|
|
col(ConversationV2.persona_id).label("persona_id"),
|
|
col(ConversationV2.title).label("title"),
|
|
col(Persona.persona_id).label("persona_name"),
|
|
)
|
|
.select_from(Preference)
|
|
.outerjoin(
|
|
ConversationV2,
|
|
func.json_extract(Preference.value, "$.val")
|
|
== ConversationV2.conversation_id,
|
|
)
|
|
.outerjoin(
|
|
Persona,
|
|
col(ConversationV2.persona_id) == Persona.persona_id,
|
|
)
|
|
.where(Preference.scope == "umo", Preference.key == "sel_conv_id")
|
|
)
|
|
|
|
# 搜索筛选
|
|
if search_query:
|
|
search_pattern = f"%{search_query}%"
|
|
base_query = base_query.where(
|
|
or_(
|
|
col(Preference.scope_id).ilike(search_pattern),
|
|
col(ConversationV2.title).ilike(search_pattern),
|
|
col(Persona.persona_id).ilike(search_pattern),
|
|
),
|
|
)
|
|
|
|
# 平台筛选
|
|
if platform:
|
|
platform_pattern = f"{platform}:%"
|
|
base_query = base_query.where(
|
|
col(Preference.scope_id).like(platform_pattern),
|
|
)
|
|
|
|
# 排序
|
|
base_query = base_query.order_by(Preference.scope_id)
|
|
|
|
# 分页结果
|
|
result_query = base_query.offset(offset).limit(page_size)
|
|
result = await session.execute(result_query)
|
|
rows = result.fetchall()
|
|
|
|
# 查询总数(应用相同的筛选条件)
|
|
count_base_query = (
|
|
select(func.count(col(Preference.scope_id)))
|
|
.select_from(Preference)
|
|
.outerjoin(
|
|
ConversationV2,
|
|
func.json_extract(Preference.value, "$.val")
|
|
== ConversationV2.conversation_id,
|
|
)
|
|
.outerjoin(
|
|
Persona,
|
|
col(ConversationV2.persona_id) == Persona.persona_id,
|
|
)
|
|
.where(Preference.scope == "umo", Preference.key == "sel_conv_id")
|
|
)
|
|
|
|
# 应用相同的搜索和平台筛选条件到计数查询
|
|
if search_query:
|
|
search_pattern = f"%{search_query}%"
|
|
count_base_query = count_base_query.where(
|
|
or_(
|
|
col(Preference.scope_id).ilike(search_pattern),
|
|
col(ConversationV2.title).ilike(search_pattern),
|
|
col(Persona.persona_id).ilike(search_pattern),
|
|
),
|
|
)
|
|
|
|
if platform:
|
|
platform_pattern = f"{platform}:%"
|
|
count_base_query = count_base_query.where(
|
|
col(Preference.scope_id).like(platform_pattern),
|
|
)
|
|
|
|
total_result = await session.execute(count_base_query)
|
|
total = total_result.scalar() or 0
|
|
|
|
sessions_data = [
|
|
{
|
|
"session_id": row.session_id,
|
|
"conversation_id": row.conversation_id,
|
|
"persona_id": row.persona_id,
|
|
"title": row.title,
|
|
"persona_name": row.persona_name,
|
|
}
|
|
for row in rows
|
|
]
|
|
return sessions_data, total
|
|
|
|
async def insert_platform_message_history(
|
|
self,
|
|
platform_id,
|
|
user_id,
|
|
content,
|
|
sender_id=None,
|
|
sender_name=None,
|
|
):
|
|
"""Insert a new platform message history record."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
new_history = PlatformMessageHistory(
|
|
platform_id=platform_id,
|
|
user_id=user_id,
|
|
content=content,
|
|
sender_id=sender_id,
|
|
sender_name=sender_name,
|
|
)
|
|
session.add(new_history)
|
|
return new_history
|
|
|
|
async def delete_platform_message_offset(
|
|
self,
|
|
platform_id,
|
|
user_id,
|
|
offset_sec=86400,
|
|
) -> None:
|
|
"""Delete platform message history records newer than the specified offset."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
now = datetime.now()
|
|
cutoff_time = now - timedelta(seconds=offset_sec)
|
|
await session.execute(
|
|
delete(PlatformMessageHistory).where(
|
|
col(PlatformMessageHistory.platform_id) == platform_id,
|
|
col(PlatformMessageHistory.user_id) == user_id,
|
|
col(PlatformMessageHistory.created_at) >= cutoff_time,
|
|
),
|
|
)
|
|
|
|
async def get_platform_message_history(
|
|
self,
|
|
platform_id,
|
|
user_id,
|
|
page=1,
|
|
page_size=20,
|
|
):
|
|
"""Get platform message history records."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
offset = (page - 1) * page_size
|
|
query = (
|
|
select(PlatformMessageHistory)
|
|
.where(
|
|
PlatformMessageHistory.platform_id == platform_id,
|
|
PlatformMessageHistory.user_id == user_id,
|
|
)
|
|
.order_by(desc(PlatformMessageHistory.created_at))
|
|
)
|
|
result = await session.execute(query.offset(offset).limit(page_size))
|
|
return result.scalars().all()
|
|
|
|
async def list_sdk_platform_message_history(
|
|
self,
|
|
platform_id,
|
|
user_id,
|
|
cursor_id=None,
|
|
limit=50,
|
|
include_total=False,
|
|
):
|
|
"""List SDK message history records ordered by descending id."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
query = (
|
|
select(PlatformMessageHistory)
|
|
.where(
|
|
PlatformMessageHistory.platform_id == platform_id,
|
|
PlatformMessageHistory.user_id == user_id,
|
|
)
|
|
.order_by(desc(PlatformMessageHistory.id))
|
|
)
|
|
if cursor_id is not None:
|
|
query = query.where(PlatformMessageHistory.id < cursor_id)
|
|
result = await session.execute(query.limit(limit))
|
|
total: int | None = None
|
|
if include_total:
|
|
total_query = (
|
|
select(func.count())
|
|
.select_from(PlatformMessageHistory)
|
|
.where(
|
|
PlatformMessageHistory.platform_id == platform_id,
|
|
PlatformMessageHistory.user_id == user_id,
|
|
)
|
|
)
|
|
total_result = await session.execute(total_query)
|
|
total = int(total_result.scalar() or 0)
|
|
return list(result.scalars().all()), total
|
|
|
|
async def delete_platform_message_before(
|
|
self,
|
|
platform_id,
|
|
user_id,
|
|
before,
|
|
) -> int:
|
|
"""Delete platform message history records strictly older than the boundary."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
result = await session.execute(
|
|
delete(PlatformMessageHistory).where(
|
|
col(PlatformMessageHistory.platform_id) == platform_id,
|
|
col(PlatformMessageHistory.user_id) == user_id,
|
|
col(PlatformMessageHistory.created_at) < before,
|
|
),
|
|
)
|
|
return int(result.rowcount or 0)
|
|
|
|
async def delete_platform_message_after(
|
|
self,
|
|
platform_id,
|
|
user_id,
|
|
after,
|
|
) -> int:
|
|
"""Delete platform message history records strictly newer than the boundary."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
result = await session.execute(
|
|
delete(PlatformMessageHistory).where(
|
|
col(PlatformMessageHistory.platform_id) == platform_id,
|
|
col(PlatformMessageHistory.user_id) == user_id,
|
|
col(PlatformMessageHistory.created_at) > after,
|
|
),
|
|
)
|
|
return int(result.rowcount or 0)
|
|
|
|
async def delete_all_platform_message_history(
|
|
self,
|
|
platform_id,
|
|
user_id,
|
|
) -> int:
|
|
"""Delete all platform message history records for a specific user."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
result = await session.execute(
|
|
delete(PlatformMessageHistory).where(
|
|
col(PlatformMessageHistory.platform_id) == platform_id,
|
|
col(PlatformMessageHistory.user_id) == user_id,
|
|
),
|
|
)
|
|
return int(result.rowcount or 0)
|
|
|
|
async def find_platform_message_history_by_idempotency_key(
|
|
self,
|
|
platform_id,
|
|
user_id,
|
|
idempotency_key,
|
|
) -> PlatformMessageHistory | None:
|
|
"""Find a SDK message history record by its idempotency key."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
query = (
|
|
select(PlatformMessageHistory)
|
|
.where(
|
|
PlatformMessageHistory.platform_id == platform_id,
|
|
PlatformMessageHistory.user_id == user_id,
|
|
func.json_extract(
|
|
PlatformMessageHistory.content, "$.idempotency_key"
|
|
)
|
|
== str(idempotency_key),
|
|
)
|
|
.order_by(desc(PlatformMessageHistory.id))
|
|
)
|
|
result = await session.execute(query.limit(1))
|
|
return result.scalar_one_or_none()
|
|
|
|
async def get_platform_message_history_by_id(
|
|
self, message_id: int
|
|
) -> PlatformMessageHistory | None:
|
|
"""Get a platform message history record by its ID."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
query = select(PlatformMessageHistory).where(
|
|
PlatformMessageHistory.id == message_id
|
|
)
|
|
result = await session.execute(query)
|
|
return result.scalar_one_or_none()
|
|
|
|
async def insert_attachment(self, path, type, mime_type):
|
|
"""Insert a new attachment record."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
new_attachment = Attachment(
|
|
path=path,
|
|
type=type,
|
|
mime_type=mime_type,
|
|
)
|
|
session.add(new_attachment)
|
|
return new_attachment
|
|
|
|
async def get_attachment_by_id(self, attachment_id):
|
|
"""Get an attachment by its ID."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
query = select(Attachment).where(Attachment.attachment_id == attachment_id)
|
|
result = await session.execute(query)
|
|
return result.scalar_one_or_none()
|
|
|
|
async def get_attachments(self, attachment_ids: list[str]) -> list:
|
|
"""Get multiple attachments by their IDs."""
|
|
if not attachment_ids:
|
|
return []
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
query = select(Attachment).where(
|
|
col(Attachment.attachment_id).in_(attachment_ids)
|
|
)
|
|
result = await session.execute(query)
|
|
return list(result.scalars().all())
|
|
|
|
async def delete_attachment(self, attachment_id: str) -> bool:
|
|
"""Delete an attachment by its ID.
|
|
|
|
Returns True if the attachment was deleted, False if it was not found.
|
|
"""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
query = delete(Attachment).where(
|
|
col(Attachment.attachment_id) == attachment_id
|
|
)
|
|
result = cast(CursorResult, await session.execute(query))
|
|
return result.rowcount > 0
|
|
|
|
async def delete_attachments(self, attachment_ids: list[str]) -> int:
|
|
"""Delete multiple attachments by their IDs.
|
|
|
|
Returns the number of attachments deleted.
|
|
"""
|
|
if not attachment_ids:
|
|
return 0
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
query = delete(Attachment).where(
|
|
col(Attachment.attachment_id).in_(attachment_ids)
|
|
)
|
|
result = cast(CursorResult, await session.execute(query))
|
|
return result.rowcount
|
|
|
|
async def create_api_key(
|
|
self,
|
|
name: str,
|
|
key_hash: str,
|
|
key_prefix: str,
|
|
scopes: list[str] | None,
|
|
created_by: str,
|
|
expires_at: datetime | None = None,
|
|
) -> ApiKey:
|
|
"""Create a new API key record."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
api_key = ApiKey(
|
|
name=name,
|
|
key_hash=key_hash,
|
|
key_prefix=key_prefix,
|
|
scopes=scopes,
|
|
created_by=created_by,
|
|
expires_at=expires_at,
|
|
)
|
|
session.add(api_key)
|
|
await session.flush()
|
|
await session.refresh(api_key)
|
|
return api_key
|
|
|
|
async def list_api_keys(self) -> list[ApiKey]:
|
|
"""List all API keys."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
result = await session.execute(
|
|
select(ApiKey).order_by(desc(ApiKey.created_at))
|
|
)
|
|
return list(result.scalars().all())
|
|
|
|
async def get_api_key_by_id(self, key_id: str) -> ApiKey | None:
|
|
"""Get an API key by key_id."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
result = await session.execute(
|
|
select(ApiKey).where(ApiKey.key_id == key_id)
|
|
)
|
|
return result.scalar_one_or_none()
|
|
|
|
async def get_active_api_key_by_hash(self, key_hash: str) -> ApiKey | None:
|
|
"""Get an active API key by hash (not revoked, not expired)."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
now = datetime.now(timezone.utc)
|
|
query = select(ApiKey).where(
|
|
ApiKey.key_hash == key_hash,
|
|
col(ApiKey.revoked_at).is_(None),
|
|
or_(col(ApiKey.expires_at).is_(None), col(ApiKey.expires_at) > now),
|
|
)
|
|
result = await session.execute(query)
|
|
return result.scalar_one_or_none()
|
|
|
|
async def touch_api_key(self, key_id: str) -> None:
|
|
"""Update last_used_at of an API key."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
await session.execute(
|
|
update(ApiKey)
|
|
.where(col(ApiKey.key_id) == key_id)
|
|
.values(last_used_at=datetime.now(timezone.utc)),
|
|
)
|
|
|
|
async def revoke_api_key(self, key_id: str) -> bool:
|
|
"""Revoke an API key."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
query = (
|
|
update(ApiKey)
|
|
.where(col(ApiKey.key_id) == key_id)
|
|
.values(revoked_at=datetime.now(timezone.utc))
|
|
)
|
|
result = cast(CursorResult, await session.execute(query))
|
|
return result.rowcount > 0
|
|
|
|
async def delete_api_key(self, key_id: str) -> bool:
|
|
"""Delete an API key."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
result = cast(
|
|
CursorResult,
|
|
await session.execute(
|
|
delete(ApiKey).where(col(ApiKey.key_id) == key_id)
|
|
),
|
|
)
|
|
return result.rowcount > 0
|
|
|
|
async def insert_persona(
|
|
self,
|
|
persona_id,
|
|
system_prompt,
|
|
begin_dialogs=None,
|
|
tools=None,
|
|
skills=None,
|
|
custom_error_message=None,
|
|
folder_id=None,
|
|
sort_order=0,
|
|
):
|
|
"""Insert a new persona record."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
new_persona = Persona(
|
|
persona_id=persona_id,
|
|
system_prompt=system_prompt,
|
|
begin_dialogs=begin_dialogs or [],
|
|
tools=tools,
|
|
skills=skills,
|
|
custom_error_message=custom_error_message,
|
|
folder_id=folder_id,
|
|
sort_order=sort_order,
|
|
)
|
|
session.add(new_persona)
|
|
await session.flush()
|
|
await session.refresh(new_persona)
|
|
return new_persona
|
|
|
|
async def get_persona_by_id(self, persona_id):
|
|
"""Get a persona by its ID."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
query = select(Persona).where(Persona.persona_id == persona_id)
|
|
result = await session.execute(query)
|
|
return result.scalar_one_or_none()
|
|
|
|
async def get_personas(self):
|
|
"""Get all personas for a specific bot."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
query = select(Persona)
|
|
result = await session.execute(query)
|
|
return result.scalars().all()
|
|
|
|
async def update_persona(
|
|
self,
|
|
persona_id,
|
|
system_prompt=None,
|
|
begin_dialogs=None,
|
|
tools=NOT_GIVEN,
|
|
skills=NOT_GIVEN,
|
|
custom_error_message=NOT_GIVEN,
|
|
):
|
|
"""Update a persona's system prompt or begin dialogs."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
query = update(Persona).where(col(Persona.persona_id) == persona_id)
|
|
values = {}
|
|
if system_prompt is not None:
|
|
values["system_prompt"] = system_prompt
|
|
if begin_dialogs is not None:
|
|
values["begin_dialogs"] = begin_dialogs
|
|
if tools is not NOT_GIVEN:
|
|
values["tools"] = tools
|
|
if skills is not NOT_GIVEN:
|
|
values["skills"] = skills
|
|
if custom_error_message is not NOT_GIVEN:
|
|
values["custom_error_message"] = custom_error_message
|
|
if not values:
|
|
return None
|
|
query = query.values(**values)
|
|
await session.execute(query)
|
|
return await self.get_persona_by_id(persona_id)
|
|
|
|
async def delete_persona(self, persona_id) -> None:
|
|
"""Delete a persona by its ID."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
await session.execute(
|
|
delete(Persona).where(col(Persona.persona_id) == persona_id),
|
|
)
|
|
|
|
# ====
|
|
# Persona Folder Management
|
|
# ====
|
|
|
|
async def insert_persona_folder(
|
|
self,
|
|
name: str,
|
|
parent_id: str | None = None,
|
|
description: str | None = None,
|
|
sort_order: int = 0,
|
|
) -> PersonaFolder:
|
|
"""Insert a new persona folder."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
new_folder = PersonaFolder(
|
|
name=name,
|
|
parent_id=parent_id,
|
|
description=description,
|
|
sort_order=sort_order,
|
|
)
|
|
session.add(new_folder)
|
|
await session.flush()
|
|
await session.refresh(new_folder)
|
|
return new_folder
|
|
|
|
async def get_persona_folder_by_id(self, folder_id: str) -> PersonaFolder | None:
|
|
"""Get a persona folder by its folder_id."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
query = select(PersonaFolder).where(PersonaFolder.folder_id == folder_id)
|
|
result = await session.execute(query)
|
|
return result.scalar_one_or_none()
|
|
|
|
async def get_persona_folders(
|
|
self, parent_id: str | None = None
|
|
) -> list[PersonaFolder]:
|
|
"""Get all persona folders, optionally filtered by parent_id.
|
|
|
|
Args:
|
|
parent_id: If None, returns root folders only. If specified, returns
|
|
children of that folder.
|
|
"""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
if parent_id is None:
|
|
# Get root folders (parent_id is NULL)
|
|
query = (
|
|
select(PersonaFolder)
|
|
.where(col(PersonaFolder.parent_id).is_(None))
|
|
.order_by(col(PersonaFolder.sort_order), col(PersonaFolder.name))
|
|
)
|
|
else:
|
|
query = (
|
|
select(PersonaFolder)
|
|
.where(PersonaFolder.parent_id == parent_id)
|
|
.order_by(col(PersonaFolder.sort_order), col(PersonaFolder.name))
|
|
)
|
|
result = await session.execute(query)
|
|
return list(result.scalars().all())
|
|
|
|
async def get_all_persona_folders(self) -> list[PersonaFolder]:
|
|
"""Get all persona folders."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
query = select(PersonaFolder).order_by(
|
|
col(PersonaFolder.sort_order), col(PersonaFolder.name)
|
|
)
|
|
result = await session.execute(query)
|
|
return list(result.scalars().all())
|
|
|
|
async def update_persona_folder(
|
|
self,
|
|
folder_id: str,
|
|
name: str | None = None,
|
|
parent_id: Any = NOT_GIVEN,
|
|
description: Any = NOT_GIVEN,
|
|
sort_order: int | None = None,
|
|
) -> PersonaFolder | None:
|
|
"""Update a persona folder."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
query = update(PersonaFolder).where(
|
|
col(PersonaFolder.folder_id) == folder_id
|
|
)
|
|
values: dict[str, Any] = {}
|
|
if name is not None:
|
|
values["name"] = name
|
|
if parent_id is not NOT_GIVEN:
|
|
values["parent_id"] = parent_id
|
|
if description is not NOT_GIVEN:
|
|
values["description"] = description
|
|
if sort_order is not None:
|
|
values["sort_order"] = sort_order
|
|
if not values:
|
|
return None
|
|
query = query.values(**values)
|
|
await session.execute(query)
|
|
return await self.get_persona_folder_by_id(folder_id)
|
|
|
|
async def delete_persona_folder(self, folder_id: str) -> None:
|
|
"""Delete a persona folder by its folder_id.
|
|
|
|
Note: This will also set folder_id to NULL for all personas in this folder,
|
|
moving them to the root directory.
|
|
"""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
# Move personas to root directory
|
|
await session.execute(
|
|
update(Persona)
|
|
.where(col(Persona.folder_id) == folder_id)
|
|
.values(folder_id=None)
|
|
)
|
|
# Delete the folder
|
|
await session.execute(
|
|
delete(PersonaFolder).where(
|
|
col(PersonaFolder.folder_id) == folder_id
|
|
),
|
|
)
|
|
|
|
async def move_persona_to_folder(
|
|
self, persona_id: str, folder_id: str | None
|
|
) -> Persona | None:
|
|
"""Move a persona to a folder (or root if folder_id is None)."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
await session.execute(
|
|
update(Persona)
|
|
.where(col(Persona.persona_id) == persona_id)
|
|
.values(folder_id=folder_id)
|
|
)
|
|
return await self.get_persona_by_id(persona_id)
|
|
|
|
async def get_personas_by_folder(
|
|
self, folder_id: str | None = None
|
|
) -> list[Persona]:
|
|
"""Get all personas in a specific folder.
|
|
|
|
Args:
|
|
folder_id: If None, returns personas in root directory.
|
|
"""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
if folder_id is None:
|
|
query = (
|
|
select(Persona)
|
|
.where(col(Persona.folder_id).is_(None))
|
|
.order_by(col(Persona.sort_order), col(Persona.persona_id))
|
|
)
|
|
else:
|
|
query = (
|
|
select(Persona)
|
|
.where(Persona.folder_id == folder_id)
|
|
.order_by(col(Persona.sort_order), col(Persona.persona_id))
|
|
)
|
|
result = await session.execute(query)
|
|
return list(result.scalars().all())
|
|
|
|
async def batch_update_sort_order(
|
|
self,
|
|
items: list[dict],
|
|
) -> None:
|
|
"""Batch update sort_order for personas and/or folders.
|
|
|
|
Args:
|
|
items: List of dicts with keys:
|
|
- id: The persona_id or folder_id
|
|
- type: Either "persona" or "folder"
|
|
- sort_order: The new sort_order value
|
|
"""
|
|
if not items:
|
|
return
|
|
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
for item in items:
|
|
item_id = item.get("id")
|
|
item_type = item.get("type")
|
|
sort_order = item.get("sort_order")
|
|
|
|
if item_id is None or item_type is None or sort_order is None:
|
|
continue
|
|
|
|
if item_type == "persona":
|
|
await session.execute(
|
|
update(Persona)
|
|
.where(col(Persona.persona_id) == item_id)
|
|
.values(sort_order=sort_order)
|
|
)
|
|
elif item_type == "folder":
|
|
await session.execute(
|
|
update(PersonaFolder)
|
|
.where(col(PersonaFolder.folder_id) == item_id)
|
|
.values(sort_order=sort_order)
|
|
)
|
|
|
|
async def insert_preference_or_update(self, scope, scope_id, key, value):
|
|
"""Insert a new preference record or update if it exists."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
query = select(Preference).where(
|
|
Preference.scope == scope,
|
|
Preference.scope_id == scope_id,
|
|
Preference.key == key,
|
|
)
|
|
result = await session.execute(query)
|
|
existing_preference = result.scalar_one_or_none()
|
|
if existing_preference:
|
|
existing_preference.value = value
|
|
else:
|
|
new_preference = Preference(
|
|
scope=scope,
|
|
scope_id=scope_id,
|
|
key=key,
|
|
value=value,
|
|
)
|
|
session.add(new_preference)
|
|
return existing_preference or new_preference
|
|
|
|
async def get_preference(self, scope, scope_id, key):
|
|
"""Get a preference by key."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
query = select(Preference).where(
|
|
Preference.scope == scope,
|
|
Preference.scope_id == scope_id,
|
|
Preference.key == key,
|
|
)
|
|
result = await session.execute(query)
|
|
return result.scalar_one_or_none()
|
|
|
|
async def get_preferences(self, scope, scope_id=None, key=None):
|
|
"""Get all preferences for a specific scope ID or key."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
query = select(Preference).where(Preference.scope == scope)
|
|
if scope_id is not None:
|
|
query = query.where(Preference.scope_id == scope_id)
|
|
if key is not None:
|
|
query = query.where(Preference.key == key)
|
|
result = await session.execute(query)
|
|
return result.scalars().all()
|
|
|
|
async def remove_preference(self, scope, scope_id, key) -> None:
|
|
"""Remove a preference by scope ID and key."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
await session.execute(
|
|
delete(Preference).where(
|
|
col(Preference.scope) == scope,
|
|
col(Preference.scope_id) == scope_id,
|
|
col(Preference.key) == key,
|
|
),
|
|
)
|
|
await session.commit()
|
|
|
|
async def clear_preferences(self, scope, scope_id) -> None:
|
|
"""Clear all preferences for a specific scope ID."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
await session.execute(
|
|
delete(Preference).where(
|
|
col(Preference.scope) == scope,
|
|
col(Preference.scope_id) == scope_id,
|
|
),
|
|
)
|
|
await session.commit()
|
|
|
|
# ====
|
|
# Command Configuration & Conflict Tracking
|
|
# ====
|
|
|
|
async def _run_in_tx(
|
|
self,
|
|
fn: Callable[[AsyncSession], Awaitable[TxResult]],
|
|
) -> TxResult:
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
return await fn(session)
|
|
|
|
@staticmethod
|
|
def _apply_updates(model, **updates) -> None:
|
|
for field, value in updates.items():
|
|
if value is not None:
|
|
setattr(model, field, value)
|
|
|
|
@staticmethod
|
|
def _new_command_config(
|
|
handler_full_name: str,
|
|
plugin_name: str,
|
|
module_path: str,
|
|
original_command: str,
|
|
*,
|
|
resolved_command: str | None = None,
|
|
enabled: bool | None = None,
|
|
keep_original_alias: bool | None = None,
|
|
conflict_key: str | None = None,
|
|
resolution_strategy: str | None = None,
|
|
note: str | None = None,
|
|
extra_data: dict | None = None,
|
|
auto_managed: bool | None = None,
|
|
) -> CommandConfig:
|
|
return CommandConfig(
|
|
handler_full_name=handler_full_name,
|
|
plugin_name=plugin_name,
|
|
module_path=module_path,
|
|
original_command=original_command,
|
|
resolved_command=resolved_command,
|
|
enabled=True if enabled is None else enabled,
|
|
keep_original_alias=False
|
|
if keep_original_alias is None
|
|
else keep_original_alias,
|
|
conflict_key=conflict_key or original_command,
|
|
resolution_strategy=resolution_strategy,
|
|
note=note,
|
|
extra_data=extra_data,
|
|
auto_managed=bool(auto_managed),
|
|
)
|
|
|
|
@staticmethod
|
|
def _new_command_conflict(
|
|
conflict_key: str,
|
|
handler_full_name: str,
|
|
plugin_name: str,
|
|
*,
|
|
status: str | None = None,
|
|
resolution: str | None = None,
|
|
resolved_command: str | None = None,
|
|
note: str | None = None,
|
|
extra_data: dict | None = None,
|
|
auto_generated: bool | None = None,
|
|
) -> CommandConflict:
|
|
return CommandConflict(
|
|
conflict_key=conflict_key,
|
|
handler_full_name=handler_full_name,
|
|
plugin_name=plugin_name,
|
|
status=status or "pending",
|
|
resolution=resolution,
|
|
resolved_command=resolved_command,
|
|
note=note,
|
|
extra_data=extra_data,
|
|
auto_generated=bool(auto_generated),
|
|
)
|
|
|
|
async def get_command_configs(self) -> list[CommandConfig]:
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
result = await session.execute(select(CommandConfig))
|
|
return list(result.scalars().all())
|
|
|
|
async def get_command_config(
|
|
self,
|
|
handler_full_name: str,
|
|
) -> CommandConfig | None:
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
return await session.get(CommandConfig, handler_full_name)
|
|
|
|
async def upsert_command_config(
|
|
self,
|
|
handler_full_name: str,
|
|
plugin_name: str,
|
|
module_path: str,
|
|
original_command: str,
|
|
*,
|
|
resolved_command: str | None = None,
|
|
enabled: bool | None = None,
|
|
keep_original_alias: bool | None = None,
|
|
conflict_key: str | None = None,
|
|
resolution_strategy: str | None = None,
|
|
note: str | None = None,
|
|
extra_data: dict | None = None,
|
|
auto_managed: bool | None = None,
|
|
) -> CommandConfig:
|
|
async def _op(session: AsyncSession) -> CommandConfig:
|
|
config = await session.get(CommandConfig, handler_full_name)
|
|
if not config:
|
|
config = self._new_command_config(
|
|
handler_full_name,
|
|
plugin_name,
|
|
module_path,
|
|
original_command,
|
|
resolved_command=resolved_command,
|
|
enabled=enabled,
|
|
keep_original_alias=keep_original_alias,
|
|
conflict_key=conflict_key,
|
|
resolution_strategy=resolution_strategy,
|
|
note=note,
|
|
extra_data=extra_data,
|
|
auto_managed=auto_managed,
|
|
)
|
|
session.add(config)
|
|
else:
|
|
self._apply_updates(
|
|
config,
|
|
plugin_name=plugin_name,
|
|
module_path=module_path,
|
|
original_command=original_command,
|
|
resolved_command=resolved_command,
|
|
enabled=enabled,
|
|
keep_original_alias=keep_original_alias,
|
|
conflict_key=conflict_key,
|
|
resolution_strategy=resolution_strategy,
|
|
note=note,
|
|
extra_data=extra_data,
|
|
auto_managed=auto_managed,
|
|
)
|
|
await session.flush()
|
|
await session.refresh(config)
|
|
return config
|
|
|
|
return await self._run_in_tx(_op)
|
|
|
|
async def delete_command_config(self, handler_full_name: str) -> None:
|
|
await self.delete_command_configs([handler_full_name])
|
|
|
|
async def delete_command_configs(self, handler_full_names: list[str]) -> None:
|
|
if not handler_full_names:
|
|
return
|
|
|
|
async def _op(session: AsyncSession) -> None:
|
|
await session.execute(
|
|
delete(CommandConfig).where(
|
|
col(CommandConfig.handler_full_name).in_(handler_full_names),
|
|
),
|
|
)
|
|
|
|
await self._run_in_tx(_op)
|
|
|
|
async def list_command_conflicts(
|
|
self,
|
|
status: str | None = None,
|
|
) -> list[CommandConflict]:
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
query = select(CommandConflict)
|
|
if status:
|
|
query = query.where(CommandConflict.status == status)
|
|
result = await session.execute(query)
|
|
return list(result.scalars().all())
|
|
|
|
async def upsert_command_conflict(
|
|
self,
|
|
conflict_key: str,
|
|
handler_full_name: str,
|
|
plugin_name: str,
|
|
*,
|
|
status: str | None = None,
|
|
resolution: str | None = None,
|
|
resolved_command: str | None = None,
|
|
note: str | None = None,
|
|
extra_data: dict | None = None,
|
|
auto_generated: bool | None = None,
|
|
) -> CommandConflict:
|
|
async def _op(session: AsyncSession) -> CommandConflict:
|
|
result = await session.execute(
|
|
select(CommandConflict).where(
|
|
CommandConflict.conflict_key == conflict_key,
|
|
CommandConflict.handler_full_name == handler_full_name,
|
|
),
|
|
)
|
|
record = result.scalar_one_or_none()
|
|
if not record:
|
|
record = self._new_command_conflict(
|
|
conflict_key,
|
|
handler_full_name,
|
|
plugin_name,
|
|
status=status,
|
|
resolution=resolution,
|
|
resolved_command=resolved_command,
|
|
note=note,
|
|
extra_data=extra_data,
|
|
auto_generated=auto_generated,
|
|
)
|
|
session.add(record)
|
|
else:
|
|
self._apply_updates(
|
|
record,
|
|
plugin_name=plugin_name,
|
|
status=status,
|
|
resolution=resolution,
|
|
resolved_command=resolved_command,
|
|
note=note,
|
|
extra_data=extra_data,
|
|
auto_generated=auto_generated,
|
|
)
|
|
await session.flush()
|
|
await session.refresh(record)
|
|
return record
|
|
|
|
return await self._run_in_tx(_op)
|
|
|
|
async def delete_command_conflicts(self, ids: list[int]) -> None:
|
|
if not ids:
|
|
return
|
|
|
|
async def _op(session: AsyncSession) -> None:
|
|
await session.execute(
|
|
delete(CommandConflict).where(col(CommandConflict.id).in_(ids)),
|
|
)
|
|
|
|
await self._run_in_tx(_op)
|
|
|
|
# ====
|
|
# Deprecated Methods
|
|
# ====
|
|
|
|
def get_base_stats(self, offset_sec=86400):
|
|
"""Get base statistics within the specified offset in seconds."""
|
|
|
|
async def _inner():
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
now = datetime.now()
|
|
start_time = now - timedelta(seconds=offset_sec)
|
|
result = await session.execute(
|
|
select(PlatformStat).where(PlatformStat.timestamp >= start_time),
|
|
)
|
|
all_datas = result.scalars().all()
|
|
deprecated_stats = DeprecatedStats()
|
|
for data in all_datas:
|
|
deprecated_stats.platform.append(
|
|
DeprecatedPlatformStat(
|
|
name=data.platform_id,
|
|
count=data.count,
|
|
timestamp=int(data.timestamp.timestamp()),
|
|
),
|
|
)
|
|
return deprecated_stats
|
|
|
|
result = None
|
|
|
|
def runner() -> None:
|
|
nonlocal result
|
|
result = asyncio.run(_inner())
|
|
|
|
t = threading.Thread(target=runner)
|
|
t.start()
|
|
t.join()
|
|
return result
|
|
|
|
def get_total_message_count(self):
|
|
"""Get the total message count from platform statistics."""
|
|
|
|
async def _inner():
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
result = await session.execute(
|
|
select(func.sum(PlatformStat.count)).select_from(PlatformStat),
|
|
)
|
|
total_count = result.scalar_one_or_none()
|
|
return total_count if total_count is not None else 0
|
|
|
|
result = None
|
|
|
|
def runner() -> None:
|
|
nonlocal result
|
|
result = asyncio.run(_inner())
|
|
|
|
t = threading.Thread(target=runner)
|
|
t.start()
|
|
t.join()
|
|
return result
|
|
|
|
def get_grouped_base_stats(self, offset_sec=86400):
|
|
# group by platform_id
|
|
async def _inner():
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
now = datetime.now()
|
|
start_time = now - timedelta(seconds=offset_sec)
|
|
result = await session.execute(
|
|
select(PlatformStat.platform_id, func.sum(PlatformStat.count))
|
|
.where(PlatformStat.timestamp >= start_time)
|
|
.group_by(PlatformStat.platform_id),
|
|
)
|
|
grouped_stats = result.all()
|
|
deprecated_stats = DeprecatedStats()
|
|
for platform_id, count in grouped_stats:
|
|
deprecated_stats.platform.append(
|
|
DeprecatedPlatformStat(
|
|
name=platform_id,
|
|
count=count,
|
|
timestamp=int(start_time.timestamp()),
|
|
),
|
|
)
|
|
return deprecated_stats
|
|
|
|
result = None
|
|
|
|
def runner() -> None:
|
|
nonlocal result
|
|
result = asyncio.run(_inner())
|
|
|
|
t = threading.Thread(target=runner)
|
|
t.start()
|
|
t.join()
|
|
return result
|
|
|
|
# ====
|
|
# Platform Session Management
|
|
# ====
|
|
|
|
async def create_platform_session(
|
|
self,
|
|
creator: str,
|
|
platform_id: str = "webchat",
|
|
session_id: str | None = None,
|
|
display_name: str | None = None,
|
|
is_group: int = 0,
|
|
) -> PlatformSession:
|
|
"""Create a new Platform session."""
|
|
kwargs = {}
|
|
if session_id:
|
|
kwargs["session_id"] = session_id
|
|
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
new_session = PlatformSession(
|
|
creator=creator,
|
|
platform_id=platform_id,
|
|
display_name=display_name,
|
|
is_group=is_group,
|
|
**kwargs,
|
|
)
|
|
session.add(new_session)
|
|
await session.flush()
|
|
await session.refresh(new_session)
|
|
return new_session
|
|
|
|
async def get_platform_session_by_id(
|
|
self, session_id: str
|
|
) -> PlatformSession | None:
|
|
"""Get a Platform session by its ID."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
query = select(PlatformSession).where(
|
|
PlatformSession.session_id == session_id,
|
|
)
|
|
result = await session.execute(query)
|
|
return result.scalar_one_or_none()
|
|
|
|
async def get_platform_sessions_by_ids(
|
|
self, session_ids: list[str]
|
|
) -> list[PlatformSession]:
|
|
"""Get platform sessions by IDs."""
|
|
if not session_ids:
|
|
return []
|
|
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
query = select(PlatformSession).where(
|
|
col(PlatformSession.session_id).in_(session_ids)
|
|
)
|
|
result = await session.execute(query)
|
|
return list(result.scalars().all())
|
|
|
|
async def get_platform_sessions_by_creator(
|
|
self,
|
|
creator: str,
|
|
platform_id: str | None = None,
|
|
page: int = 1,
|
|
page_size: int = 20,
|
|
) -> list[dict]:
|
|
"""Get all Platform sessions for a specific creator (username) and optionally platform.
|
|
|
|
Returns a list of dicts containing session info and project info (if session belongs to a project).
|
|
"""
|
|
(
|
|
sessions_with_projects,
|
|
_,
|
|
) = await self.get_platform_sessions_by_creator_paginated(
|
|
creator=creator,
|
|
platform_id=platform_id,
|
|
page=page,
|
|
page_size=page_size,
|
|
exclude_project_sessions=False,
|
|
)
|
|
return sessions_with_projects
|
|
|
|
@staticmethod
|
|
def _build_platform_sessions_query(
|
|
creator: str,
|
|
platform_id: str | None = None,
|
|
exclude_project_sessions: bool = False,
|
|
):
|
|
query = (
|
|
select(
|
|
PlatformSession,
|
|
col(ChatUIProject.project_id),
|
|
col(ChatUIProject.title).label("project_title"),
|
|
col(ChatUIProject.emoji).label("project_emoji"),
|
|
)
|
|
.outerjoin(
|
|
SessionProjectRelation,
|
|
col(PlatformSession.session_id)
|
|
== col(SessionProjectRelation.session_id),
|
|
)
|
|
.outerjoin(
|
|
ChatUIProject,
|
|
col(SessionProjectRelation.project_id) == col(ChatUIProject.project_id),
|
|
)
|
|
.where(col(PlatformSession.creator) == creator)
|
|
)
|
|
|
|
if platform_id:
|
|
query = query.where(PlatformSession.platform_id == platform_id)
|
|
if exclude_project_sessions:
|
|
query = query.where(col(ChatUIProject.project_id).is_(None))
|
|
|
|
return query
|
|
|
|
@staticmethod
|
|
def _rows_to_session_dicts(rows: Sequence[Row[tuple]]) -> list[dict]:
|
|
sessions_with_projects = []
|
|
for row in rows:
|
|
platform_session = row[0]
|
|
project_id = row[1]
|
|
project_title = row[2]
|
|
project_emoji = row[3]
|
|
|
|
session_dict = {
|
|
"session": platform_session,
|
|
"project_id": project_id,
|
|
"project_title": project_title,
|
|
"project_emoji": project_emoji,
|
|
}
|
|
sessions_with_projects.append(session_dict)
|
|
|
|
return sessions_with_projects
|
|
|
|
async def get_platform_sessions_by_creator_paginated(
|
|
self,
|
|
creator: str,
|
|
platform_id: str | None = None,
|
|
page: int = 1,
|
|
page_size: int = 20,
|
|
exclude_project_sessions: bool = False,
|
|
) -> tuple[list[dict], int]:
|
|
"""Get paginated Platform sessions for a creator with total count."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
offset = (page - 1) * page_size
|
|
|
|
base_query = self._build_platform_sessions_query(
|
|
creator=creator,
|
|
platform_id=platform_id,
|
|
exclude_project_sessions=exclude_project_sessions,
|
|
)
|
|
|
|
total_result = await session.execute(
|
|
select(func.count()).select_from(base_query.subquery())
|
|
)
|
|
total = int(total_result.scalar_one() or 0)
|
|
|
|
result_query = (
|
|
base_query.order_by(desc(PlatformSession.updated_at))
|
|
.offset(offset)
|
|
.limit(page_size)
|
|
)
|
|
result = await session.execute(result_query)
|
|
|
|
sessions_with_projects = self._rows_to_session_dicts(result.all())
|
|
return sessions_with_projects, total
|
|
|
|
async def update_platform_session(
|
|
self,
|
|
session_id: str,
|
|
display_name: str | None = None,
|
|
) -> None:
|
|
"""Update a Platform session's updated_at timestamp and optionally display_name."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
values: dict[str, Any] = {"updated_at": datetime.now(timezone.utc)}
|
|
if display_name is not None:
|
|
values["display_name"] = display_name
|
|
|
|
await session.execute(
|
|
update(PlatformSession)
|
|
.where(col(PlatformSession.session_id) == session_id)
|
|
.values(**values),
|
|
)
|
|
|
|
async def delete_platform_session(self, session_id: str) -> None:
|
|
"""Delete a Platform session by its ID."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
await session.execute(
|
|
delete(PlatformSession).where(
|
|
col(PlatformSession.session_id) == session_id,
|
|
),
|
|
)
|
|
|
|
# ====
|
|
# ChatUI Project Management
|
|
# ====
|
|
|
|
async def create_chatui_project(
|
|
self,
|
|
creator: str,
|
|
title: str,
|
|
emoji: str | None = "📁",
|
|
description: str | None = None,
|
|
) -> ChatUIProject:
|
|
"""Create a new ChatUI project."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
project = ChatUIProject(
|
|
creator=creator,
|
|
title=title,
|
|
emoji=emoji,
|
|
description=description,
|
|
)
|
|
session.add(project)
|
|
await session.flush()
|
|
await session.refresh(project)
|
|
return project
|
|
|
|
async def get_chatui_project_by_id(self, project_id: str) -> ChatUIProject | None:
|
|
"""Get a ChatUI project by its ID."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
result = await session.execute(
|
|
select(ChatUIProject).where(
|
|
col(ChatUIProject.project_id) == project_id,
|
|
),
|
|
)
|
|
return result.scalar_one_or_none()
|
|
|
|
async def get_chatui_projects_by_creator(
|
|
self,
|
|
creator: str,
|
|
page: int = 1,
|
|
page_size: int = 100,
|
|
) -> list[ChatUIProject]:
|
|
"""Get all ChatUI projects for a specific creator."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
offset = (page - 1) * page_size
|
|
result = await session.execute(
|
|
select(ChatUIProject)
|
|
.where(col(ChatUIProject.creator) == creator)
|
|
.order_by(desc(ChatUIProject.updated_at))
|
|
.limit(page_size)
|
|
.offset(offset),
|
|
)
|
|
return list(result.scalars().all())
|
|
|
|
async def update_chatui_project(
|
|
self,
|
|
project_id: str,
|
|
title: str | None = None,
|
|
emoji: str | None = None,
|
|
description: str | None = None,
|
|
) -> None:
|
|
"""Update a ChatUI project."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
values: dict[str, Any] = {"updated_at": datetime.now(timezone.utc)}
|
|
if title is not None:
|
|
values["title"] = title
|
|
if emoji is not None:
|
|
values["emoji"] = emoji
|
|
if description is not None:
|
|
values["description"] = description
|
|
|
|
await session.execute(
|
|
update(ChatUIProject)
|
|
.where(col(ChatUIProject.project_id) == project_id)
|
|
.values(**values),
|
|
)
|
|
|
|
async def delete_chatui_project(self, project_id: str) -> None:
|
|
"""Delete a ChatUI project by its ID."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
# First remove all session relations
|
|
await session.execute(
|
|
delete(SessionProjectRelation).where(
|
|
col(SessionProjectRelation.project_id) == project_id,
|
|
),
|
|
)
|
|
# Then delete the project
|
|
await session.execute(
|
|
delete(ChatUIProject).where(
|
|
col(ChatUIProject.project_id) == project_id,
|
|
),
|
|
)
|
|
|
|
async def add_session_to_project(
|
|
self,
|
|
session_id: str,
|
|
project_id: str,
|
|
) -> SessionProjectRelation:
|
|
"""Add a session to a project."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
# First remove existing relation if any
|
|
await session.execute(
|
|
delete(SessionProjectRelation).where(
|
|
col(SessionProjectRelation.session_id) == session_id,
|
|
),
|
|
)
|
|
# Then create new relation
|
|
relation = SessionProjectRelation(
|
|
session_id=session_id,
|
|
project_id=project_id,
|
|
)
|
|
session.add(relation)
|
|
await session.flush()
|
|
await session.refresh(relation)
|
|
return relation
|
|
|
|
async def remove_session_from_project(self, session_id: str) -> None:
|
|
"""Remove a session from its project."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
await session.execute(
|
|
delete(SessionProjectRelation).where(
|
|
col(SessionProjectRelation.session_id) == session_id,
|
|
),
|
|
)
|
|
|
|
async def get_project_sessions(
|
|
self,
|
|
project_id: str,
|
|
page: int = 1,
|
|
page_size: int = 100,
|
|
) -> list[PlatformSession]:
|
|
"""Get all sessions in a project."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
offset = (page - 1) * page_size
|
|
result = await session.execute(
|
|
select(PlatformSession)
|
|
.join(
|
|
SessionProjectRelation,
|
|
col(PlatformSession.session_id)
|
|
== col(SessionProjectRelation.session_id),
|
|
)
|
|
.where(col(SessionProjectRelation.project_id) == project_id)
|
|
.order_by(desc(PlatformSession.updated_at))
|
|
.limit(page_size)
|
|
.offset(offset),
|
|
)
|
|
return list(result.scalars().all())
|
|
|
|
async def get_project_by_session(
|
|
self, session_id: str, creator: str
|
|
) -> ChatUIProject | None:
|
|
"""Get the project that a session belongs to."""
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
result = await session.execute(
|
|
select(ChatUIProject)
|
|
.join(
|
|
SessionProjectRelation,
|
|
col(ChatUIProject.project_id)
|
|
== col(SessionProjectRelation.project_id),
|
|
)
|
|
.where(
|
|
col(SessionProjectRelation.session_id) == session_id,
|
|
col(ChatUIProject.creator) == creator,
|
|
),
|
|
)
|
|
return result.scalar_one_or_none()
|
|
|
|
# ====
|
|
# Cron Job Management
|
|
# ====
|
|
|
|
async def create_cron_job(
|
|
self,
|
|
name: str,
|
|
job_type: str,
|
|
cron_expression: str | None,
|
|
*,
|
|
timezone: str | None = None,
|
|
payload: dict | None = None,
|
|
description: str | None = None,
|
|
enabled: bool = True,
|
|
persistent: bool = True,
|
|
run_once: bool = False,
|
|
status: str | None = None,
|
|
job_id: str | None = None,
|
|
) -> CronJob:
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
job = CronJob(
|
|
name=name,
|
|
job_type=job_type,
|
|
cron_expression=cron_expression,
|
|
timezone=timezone,
|
|
payload=payload or {},
|
|
description=description,
|
|
enabled=enabled,
|
|
persistent=persistent,
|
|
run_once=run_once,
|
|
status=status or "scheduled",
|
|
)
|
|
if job_id:
|
|
job.job_id = job_id
|
|
session.add(job)
|
|
await session.flush()
|
|
await session.refresh(job)
|
|
return job
|
|
|
|
async def update_cron_job(
|
|
self,
|
|
job_id: str,
|
|
*,
|
|
name: str | None | object = CRON_FIELD_NOT_SET,
|
|
cron_expression: str | None | object = CRON_FIELD_NOT_SET,
|
|
timezone: str | None | object = CRON_FIELD_NOT_SET,
|
|
payload: dict | None | object = CRON_FIELD_NOT_SET,
|
|
description: str | None | object = CRON_FIELD_NOT_SET,
|
|
enabled: bool | None | object = CRON_FIELD_NOT_SET,
|
|
persistent: bool | None | object = CRON_FIELD_NOT_SET,
|
|
run_once: bool | None | object = CRON_FIELD_NOT_SET,
|
|
status: str | None | object = CRON_FIELD_NOT_SET,
|
|
next_run_time: datetime | None | object = CRON_FIELD_NOT_SET,
|
|
last_run_at: datetime | None | object = CRON_FIELD_NOT_SET,
|
|
last_error: str | None | object = CRON_FIELD_NOT_SET,
|
|
) -> CronJob | None:
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
updates: dict = {}
|
|
for key, val in {
|
|
"name": name,
|
|
"cron_expression": cron_expression,
|
|
"timezone": timezone,
|
|
"payload": payload,
|
|
"description": description,
|
|
"enabled": enabled,
|
|
"persistent": persistent,
|
|
"run_once": run_once,
|
|
"status": status,
|
|
"next_run_time": next_run_time,
|
|
"last_run_at": last_run_at,
|
|
"last_error": last_error,
|
|
}.items():
|
|
if val is CRON_FIELD_NOT_SET:
|
|
continue
|
|
updates[key] = val
|
|
|
|
stmt = (
|
|
update(CronJob)
|
|
.where(col(CronJob.job_id) == job_id)
|
|
.values(**updates)
|
|
.execution_options(synchronize_session="fetch")
|
|
)
|
|
await session.execute(stmt)
|
|
result = await session.execute(
|
|
select(CronJob).where(col(CronJob.job_id) == job_id)
|
|
)
|
|
return result.scalar_one_or_none()
|
|
|
|
async def delete_cron_job(self, job_id: str) -> None:
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
async with session.begin():
|
|
await session.execute(
|
|
delete(CronJob).where(col(CronJob.job_id) == job_id)
|
|
)
|
|
|
|
async def get_cron_job(self, job_id: str) -> CronJob | None:
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
result = await session.execute(
|
|
select(CronJob).where(col(CronJob.job_id) == job_id)
|
|
)
|
|
return result.scalar_one_or_none()
|
|
|
|
async def list_cron_jobs(self, job_type: str | None = None) -> list[CronJob]:
|
|
async with self.get_db() as session:
|
|
session: AsyncSession
|
|
query = select(CronJob)
|
|
if job_type:
|
|
query = query.where(col(CronJob.job_type) == job_type)
|
|
query = query.order_by(desc(CronJob.created_at))
|
|
result = await session.execute(query)
|
|
return list(result.scalars().all())
|