Compare commits

...

570 Commits

Author SHA1 Message Date
suyao
2cd7f91fff fix: update zod import to use namespace import 2025-10-14 15:33:57 +08:00
suyao
ad7a043fb3 revert type 2025-10-14 15:12:43 +08:00
suyao
7db628702d Merge branch 'main' into feat/mcp-runjs 2025-10-14 15:09:42 +08:00
beyondkmp
866e8e8734 fix: guard webview search against destroyed webviews (#10704)
* 🐛 fix: guard webview search against destroyed webviews

* delete code

* delete code
2025-10-14 14:04:57 +08:00
George·Dong
80e1784777 chore(ci): switch Claude action to custom endpoint (#10701) 2025-10-14 01:23:34 +08:00
亢奋猫
0d760ffa2e feat: add AgentSettingsTab component and integrate into HomeTabs (#10668)
- Introduced the AgentSettingsTab component for managing agent settings.
- Integrated AgentSettingsTab into HomeTabs, allowing access to agent settings based on the active session or topic.
- Updated AgentEssentialSettings to conditionally render the ModelSetting based on props.
- Adjusted styles in various components for consistency and improved layout.
2025-10-13 22:34:27 +08:00
Pleasure1234
88f7e6a854 fix: add esbuild and update tar-fs dependency (#10671)
Added 'esbuild' with version ^0.25.0 and updated 'tar-fs' to ^2.1.4 in package.json. This also updates related entries in yarn.lock to ensure compatibility and resolve dependency issues.
2025-10-13 21:44:31 +08:00
kangfenmao
de37e2355d chore: update @ai-sdk/google to version 2.0.20 and add corresponding patch
- Updated the @ai-sdk/google dependency to version 2.0.20 in package.json.
- Added a new patch file for the updated version to address specific changes in the library.
2025-10-13 21:00:25 +08:00
Chen Tao
f27b04c5b0 fix: support gemini-2.5-image-flash (#10683) 2025-10-13 17:39:08 +08:00
defi-failure
a02b8f4609 chore: update SiliconFlow logo (#10684) 2025-10-13 16:57:20 +08:00
beyondkmp
7b90dfb46c fix: intercept webview keyboard shortcuts for search functionality (#10641)
* feat: intercept webview keyboard shortcuts for search functionality

Implemented keyboard shortcut interception in webview to enable search functionality (Ctrl/Cmd+F) and navigation (Enter/Escape) within mini app pages. Previously, these shortcuts were consumed by the webview content and not propagated to the host application.

Changes:
- Added Webview_SearchHotkey IPC channel for forwarding keyboard events
- Implemented before-input-event handler in WebviewService to intercept Ctrl/Cmd+F, Escape, and Enter
- Extended preload API with onFindShortcut callback for webview shortcut events
- Updated WebviewSearch component to handle shortcuts from both window and webview
- Added comprehensive test coverage for webview shortcut handling

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* fix lint

* refactor: improve webview hotkey initialization and error handling

Refactored webview keyboard shortcut handler for better code organization and reliability.

Changes:
- Extracted keyboard handler logic into reusable attachKeyboardHandler function
- Added initWebviewHotkeys() to initialize handlers for existing webviews on startup
- Integrated initialization in main app entry point
- Added explanatory comment for event.preventDefault() behavior
- Added warning log when webContentsId is unavailable in WebviewSearch

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: add WebviewKeyEvent type and update related components

- Introduced WebviewKeyEvent type to standardize keyboard event handling for webviews.
- Updated preload index to utilize the new WebviewKeyEvent type in the onFindShortcut callback.
- Refactored WebviewSearch component and its tests to accommodate the new type, enhancing type safety and clarity.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

* fix lint

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-12 18:45:37 +08:00
Pleasure1234
26a9dba01a fix: claude-translator.yml (#10588)
* Update claude-translator.yml

* Update claude-translator.yml
2025-10-12 18:20:34 +08:00
SuYao
a176814ad1 fix: update ESLint configuration and dependencies, replace zod import… (#10645)
fix: update ESLint configuration and dependencies, replace zod import style
2025-10-12 17:15:52 +08:00
George·Dong
ea51439aac feat(reasoning): add special handling for Grok 4 fast models & qwen3-omni/qwen3-vl (#10367)
* feat(reasoning): add special handling for Grok 4 fast models

* feat(models): add grok4_fast model and refine grok reasoning

* feat(reasoning): unify Grok reasoning handling and XAI params

* feat(models): Grok/qwen handling and XAI

* feat(models): recognize qwen3-vl thinking models and add sizes

* fix(reasoning): reasoning enabled for QwenAlwaysThink models

* feat(reasoning): enable reasoning for Grok 4 Fast models

* fix(reasoning): rename and correct Grok 4 Fast model checks

* fix: adjust Grok-4 Fast reasoning detection for OpenRouter

* fix(reasoning): exclude non-reasoning models from reasoning detection
2025-10-12 11:34:16 +08:00
Chen Tao
162e33f478 fix: remove LRU for websearch rag (#10631) 2025-10-12 00:01:35 +08:00
kangfenmao
ee4c310725 feat: update migration logic and increment version for store
- Incremented version in the store configuration from 161 to 162.
- Updated migration logic to handle new provider integration and state adjustments.
- Removed deprecated migration logic for version 161.
2025-10-11 16:17:00 +08:00
kangfenmao
a000ff2a1a fix: adjust overflow properties in MessageGroup component
- Changed overflow properties in the GridContainer styled component to improve layout handling. Overflow is now set to hidden for vertical alignment.
2025-10-11 16:07:49 +08:00
kangfenmao
2f9576b2ae feat: remove some minapp and update related configurations
- Introduced new app icon for Stepfun.
- Updated minapps configuration to include Stepfun with its logo and URL.
- Removed Yuewen app from configurations and translations.
- Updated translations for multiple languages to reflect the addition of Stepfun and removal of Yuewen.
- Incremented version in the store configuration and added migration logic for new provider integration.
2025-10-11 16:07:49 +08:00
kangfenmao
92554dd398 chore: update @ai-sdk/google to version 2.0.17 and add corresponding patch 2025-10-11 16:07:49 +08:00
defi-failure
9473ddc762 feature: unified assistant tab (#10590)
* feature: unified assistant tab

* refactor(TagGroup): make TagsContainer component internal by removing export

* refactor(components): migrate styled-components to cn utility classes

Replace styled-components with cn utility classes from @heroui/react for better maintainability and performance

* refactor(AssistantsTab): split AssistantsTab into smaller hooks and components

* fix: click agent item should jump to topic tab

* feat: add AddButton component and refactor usage across tabs

- Introduced a new AddButton component for consistent UI across different tabs.
- Replaced existing button implementations with AddButton in Sessions, Topics, and UnifiedAddButton components.
- Removed unnecessary margin from AssistantsTab's container for improved layout.

---------

Co-authored-by: icarus <eurfelux@gmail.com>
Co-authored-by: kangfenmao <kangfenmao@qq.com>
2025-10-11 16:07:35 +08:00
SuYao
5f469a71f3 fix: update ai-sdk dependencies to latest versions (#10643) 2025-10-11 15:53:30 +08:00
defi-failure
87bac60afc fix: long dir breaks edit agent layout (#10644) 2025-10-11 14:47:45 +08:00
SuYao
704339e835 fix: increase tool call maxCount (#10642) 2025-10-11 14:21:18 +08:00
ABucket
c8ab7180ba fix: Provider icons are not displayed after selecting SiliconFlow in the "images" page (#10620) 2025-10-11 12:48:26 +08:00
ABucket
11757546c3 fix: Quick Assistant fails to correctly inject variables in prompts (#10617) 2025-10-11 12:45:25 +08:00
ABucket
420b9ec2f2 fix: AI_TypeValidationError when calling Ling-1T model (#10622) 2025-10-11 12:45:00 +08:00
beyondkmp
1c73271e33 fix: support gpt-5-codex for github copilot (#10587)
* fix: support gpt-5-codex for github copilot

- Added patch for @ai-sdk/openai to version 2.0.42 in package.json and yarn.lock.
- Updated editor version for Copilot from v1.97.2 to v1.104.1 in OpenAIBaseClient and providerConfig.
- Enhanced provider configuration to support new model options for Copilot.

* fix: streamline Copilot header management

- Replaced individual header assignments for Copilot with centralized constants in OpenAIBaseClient and providerConfig.
- Enhanced provider configuration to conditionally set response mode for Copilot models, improving routing logic.

* update aisdk

* delete patch

* 🤖 chore: integrate Copilot SDK provider

* use a plugin

* udpate dependency

* fix: remove unused Copilot default headers from OpenAIBaseClient

- Eliminated the import and usage of COPILOT_DEFAULT_HEADERS to streamline header management in the OpenAIBaseClient class.

* update yarn

* fix lint

* format code

* feat: enhance web search tool types in webSearchPlugin

- Added type normalization for web search tools to improve type safety and clarity.
- Updated WebSearchToolInputSchema and WebSearchToolOutputSchema to use normalized types for better consistency across the plugin.
2025-10-11 10:18:09 +08:00
ABucket
acdbe6b9ed feat: allow right click to create note and folder (#10523)
* feat: allow right click to create note and folder

* fix: duplicate menu for notes or folder

* fix: create notes in folder when a folder is selected
2025-10-10 16:58:14 +01:00
beyondkmp
6c201228d9 feat: support search in mini app page (#10609)
*  feat: add webview find-in-page overlay

* 🐛 fix: reset webview search on tab change

* fix clear search issue

* 🐛 fix: rebind webview search events

* 🐛 fix: disable spellcheck in search input

* fix spellcheck

* 🐛 fix: webview search can now reopen after closing

Fixed an issue where the search overlay couldn't be reopened after closing.
The openSearch callback was unnecessarily depending on webviewRef.current,
causing event listener rebinding issues. Removed the redundant webviewRef
check as isWebviewReady is sufficient to ensure webview readiness.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Payne Fu <payne@Paynes-Mac-mini.rcoffice.ringcentral.com>
Co-authored-by: Payne Fu <payne@Paynes-MBP.rcoffice.ringcentral.com>
Co-authored-by: Claude <noreply@anthropic.com>
2025-10-10 07:00:45 -07:00
Tristan Zhang
73b2a375ad fix: insert reasoning block before the content block (#10545)
fix: always insert reasoning block before the content block
2025-10-09 22:32:13 +08:00
Chen Tao
89bb830b60 fix: knowledge base not delete and websearch rag error (#10595)
* fix: knowledge base not  delete

* fix: websearch rag error

* chore: add comment
2025-10-09 22:29:52 +08:00
Tristan Zhang
2399db4944 fix: adding multiple keys to the zhipu model service is not detected properly (#10583) 2025-10-09 20:40:46 +08:00
beyondkmp
62774b34d3 feat: add updating dialog in render (#10569)
* feat: replace update dialog handling with quit and install functionality

* refactor: remove App_ShowUpdateDialog and implement App_QuitAndInstall in IpcChannel
* update ipc.ts to handle quit and install action
* modify AppUpdater to include quitAndInstall method
* adjust preload index to invoke new quit and install action
* enhance AboutSettings to manage update dialog state and trigger quit and install

* fix(AboutSettings): handle null update info in update dialog state management

* fix(UpdateDialog): improve error handling during update installation and enhance release notes processing

* fix(AppUpdater): remove redundant assignment of releaseInfo after update download

* fix(IpcChannel): remove UpdateDownloadedCancelled enum value

* format code

* fix(UpdateDialog): enhance installation process with loading state and error handling

* update i18n

* fix(i18n): Auto update translations for PR #10569

* feat(UpdateAppButton): integrate UpdateDialog and update button functionality for better user experience

* fix(UpdateDialog): update installation handler to support async operation and ensure modal closes after installation

* refactor(AppUpdater.test): remove deprecated formatReleaseNotes tests to streamline test suite

* refactor(update-dialog): simplify dialog close handling

Replace onOpenChange with onClose prop to directly handle dialog closing
Remove redundant handleClose function and simplify button onPress handler

---------

Co-authored-by: GitHub Action <action@github.com>
Co-authored-by: icarus <eurfelux@gmail.com>
2025-10-09 15:58:24 +08:00
Tristan Zhang
654f19eaa9 fix: change the url for qwen (#10584) 2025-10-09 13:37:07 +08:00
Tristan Zhang
ce642f17d9 fix: layout for antrophic api tips (#10579)
* fix: layout for antrophic api tips

* lint
2025-10-09 13:20:40 +08:00
fullex
d7bcd5a20e Merge pull request #10096 from CherryHQ/feat/agents-new
feat: agents implemention
2025-10-09 10:07:18 +08:00
suyao
27903e7d9d fix 2025-10-09 09:42:04 +08:00
suyao
a8c0d0a684 fix 2025-10-09 09:10:04 +08:00
suyao
5e33c89fe7 Merge branch 'main' into feat/agents-new 2025-10-09 09:06:06 +08:00
suyao
44d2cb345f return 2025-10-09 08:50:46 +08:00
suyao
49eec68434 done 2025-10-09 08:46:07 +08:00
icarus
d5ae3e6edc Merge branch 'main' of github.com:CherryHQ/cherry-studio into feat/mcp-runjs 2025-10-09 00:27:30 +08:00
icarus
6eedcc29ba feat(i18n): add untranslated strings for multiple languages
Add placeholder strings marked with "[to be translated]" in Japanese, Russian, Portuguese, Greek, Spanish and French translation files. These include new message placeholders and auto-rename functionality for notes.
2025-10-09 00:20:39 +08:00
Tristan Zhang
42849e4586 feat: support export image for notes (#10559)
* feat: support export image for notes

* feat: extract functions
2025-10-08 23:32:32 +08:00
suyao
71d35eddf7 Add JavaScript execution safety limits and improve error handling
- Add 1MB code size limit to prevent memory issues
- Improve timeout error handling with proper cleanup logging
- Remove host environment exposure and fix file descriptor leaks in worker
2025-10-08 07:11:39 +08:00
suyao
9f1c8f2c17 fix: more accurate 2025-10-08 07:08:19 +08:00
suyao
651e9a529e Add JavaScript execution support to code blocks
- Register new IPC channel and handler for JavaScript code execution
- Extend code block execution to support JavaScript, TypeScript, and JS languages
- Add JavaScript service with sandboxed execution using quickJs
- Update UI to show JavaScript execution option alongside Python
2025-10-08 07:07:13 +08:00
suyao
f68f6e9896 chore: i18n 2025-10-08 06:56:21 +08:00
suyao
2dcc68da87 chore: yarn lock 2025-10-08 06:54:14 +08:00
suyao
1db259cd3e Add JavaScript MCP server with QuickJS WASM sandbox execution
- Implement JsServer MCP server with `run_javascript_code` tool for secure code execution
- Add JsService worker management with timeout handling and error formatting
- Include QuickJS WASM binary and integrate with WASI for sandboxed execution
- Update UI with i18n support and JSON result formatting improvements
2025-10-08 06:48:14 +08:00
Vaayne
68b37e66e9 ⬆️ chore: upgrade electron from 37.4.0 to 37.6.0 2025-10-07 14:36:03 +08:00
Vaayne
d6e7ed81ee Merge remote-tracking branch 'origin/main' into feat/agents-new
# Conflicts:
#	src/renderer/src/pages/home/Tabs/TopicsTab.tsx
#	yarn.lock
2025-10-07 14:33:41 +08:00
Vaayne
d4c6131fa3 Merge remote-tracking branch 'origin/main' into feat/agents-new
# Conflicts:
#	package.json
#	src/renderer/src/aiCore/chunk/AiSdkToChunkAdapter.ts
2025-10-07 12:30:18 +08:00
Vaayne
53046460ec fix(ClaudeCodeService): update environment variables to use modelInfo provider details 2025-09-30 23:53:10 +08:00
Vaayne
538291c03f ♻️ refactor: consolidate Claude Code system message handling and streaming logic
- Unify buildClaudeCodeSystemMessage implementation in shared package
- Refactor MessagesService to provide comprehensive message processing API
- Extract streaming logic, error handling, and header preparation into service methods
- Remove duplicate anthropic config from renderer, use shared implementation
- Update ClaudeCodeService to use append mode for custom instructions
- Improve type safety and request validation in message processing
2025-09-30 23:33:41 +08:00
icarus
142ad9e41e refactor(Assistants): move add assistant button inside container div
Improve layout structure by moving the button inside the same container as other elements for better visual grouping
2025-09-30 21:14:48 +08:00
Vaayne
7250ce3514 fix(CodeToolsService): update package name for Claude Code SDK 2025-09-30 18:55:17 +08:00
Vaayne
02cf012671 fix(ProcessTransport): replace spawn with fork for Node.js process handling 2025-09-30 18:50:02 +08:00
Vaayne
65ac3181a8 feat: add anthropicApiHost to CherryAI and New-API providers 2025-09-30 18:25:51 +08:00
Vaayne
998e54246f 🔖 chore: bump version to 1.7.0-alpha.4 2025-09-30 18:16:15 +08:00
Vaayne
fcd8f7a26e 🐛 fix: update i18n translations, UI components, and provider configuration
- Add error.open_path translation across multiple locales (zh-tw, el-gr, es-es, fr-fr, ja-jp, pt-pt, ru-ru)
- Remove avatarProps from AgentLabel in AgentSettingsPopup
- Add ovms provider to SystemProviderIds
2025-09-30 18:15:08 +08:00
Vaayne
b991afd69a fix(claude): streamline systemPrompt and settingSources initialization 2025-09-30 18:05:32 +08:00
Vaayne
d9d8bae2d6 Merge remote-tracking branch 'origin/main' into feat/agents-new 2025-09-30 18:03:35 +08:00
Vaayne
422ba52093 ⬆️ chore: migrate from Claude Code SDK to Claude Agent SDK v0.1.1
- Replace @anthropic-ai/claude-code with @anthropic-ai/claude-agent-sdk@0.1.1
- Update all import statements across 4 files
- Migrate patch for Electron compatibility (fork vs spawn)
- Handle breaking changes: replace appendSystemPrompt with systemPrompt preset
- Add settingSources configuration for filesystem settings
- Update vendor path in build scripts
- Update package name mapping in CodeToolsService
2025-09-30 17:54:02 +08:00
Vaayne
51630f95fd ♻️ refactor(agents): improve error handling and logging in agent services 2025-09-30 17:17:56 +08:00
Vaayne
ac1cab60a3 fix(cache): reduce cache TTL from 1 minute to 10 seconds for quicker updates 2025-09-29 23:24:36 +08:00
Vaayne
759f8518b2 fix(logger): enhance cache check for available providers 2025-09-29 23:02:05 +08:00
icarus
7bd6c92f43 refactor(agent): rename getAgentDefaultAvatar to getAgentTypeAvatar for clarity
Simplify avatar handling by removing default avatar logic and always using emoji icons
2025-09-29 21:04:31 +08:00
icarus
ff705d99b3 refactor(AvatarSetting): simplify avatar selection by removing radio options
Remove radio group selection for avatar type and only keep emoji picker
Clean up unused imports and code related to the removed functionality
2025-09-29 21:00:42 +08:00
icarus
7ec17dc771 style(ChatNavbar): adjust AgentLabel styling for better consistency 2025-09-29 20:17:41 +08:00
icarus
35883e8601 fix(i18n): update error message for failed path opening 2025-09-29 19:59:51 +08:00
icarus
48b7bdb9ba feat(file): improve error handling for openPath operation
Add error message translation and proper error propagation when opening a file path fails
2025-09-29 19:53:32 +08:00
icarus
d2d5b4370c feat(ChatNavbar): make path info tag clickable to open file location
Add onClick handler to InfoTag component to open file location when clicked
2025-09-29 19:36:13 +08:00
icarus
27c31d6e0c feat(file): add showInFolder IPC channel to reveal files in explorer
Implement functionality to show files/folders in system explorer through IPC. Includes channel definition, preload API, main handler, and error handling for non-existent paths.
2025-09-29 19:36:05 +08:00
Vaayne
37b3c08baa ♻️ refactor: improve async processing and error handling in ClaudeCodeService 2025-09-29 17:14:13 +08:00
Vaayne
d8c3f601df ♻️ refactor: correct include filter path for Claude code ripgrep 2025-09-29 16:18:12 +08:00
Vaayne
cff9068359 ♻️ refactor: standardize string quotes and improve logging in Anthropic integration 2025-09-29 14:42:50 +08:00
Vaayne
cc871b7a72 ♻️ refactor: enhance logging and provider handling for Anthropic integration 2025-09-29 14:38:41 +08:00
Vaayne
5b98ef5b3d ♻️ refactor: update import paths for message handling module 2025-09-29 13:12:06 +08:00
Vaayne
3428d15299 ♻️ refactor: centralize agent stream timeouts 2025-09-29 13:06:47 +08:00
Vaayne
9ea3f0842c 📝 docs: refresh AI assistant guidelines 2025-09-29 11:12:56 +08:00
Vaayne
90242e2285 fix: exclude proxy environment variables from login shell environment 2025-09-29 11:05:05 +08:00
Vaayne
1616345261 Bump version to 1.7.0-alpha.3 2025-09-29 09:51:40 +08:00
GitHub Action
0b818477ac fix(i18n): Auto update translations for PR #10096 2025-09-28 15:35:27 +00:00
Vaayne
027d6ea2b2 Merge remote-tracking branch 'origin/main' into feat/agents-new 2025-09-28 23:34:33 +08:00
icarus
8712e26c74 chore: bump version to 1.7.0-alpha.2 2025-09-28 19:41:12 +08:00
icarus
0c652e0ac4 fix: handle missing tool case in ChooseTool component 2025-09-28 19:40:31 +08:00
icarus
3a3a5e6c8b Revert "chore: bump version to 1.7.0-alpha.2"
This reverts commit 1b7596ebe1.
2025-09-28 19:40:24 +08:00
icarus
1b7596ebe1 chore: bump version to 1.7.0-alpha.2 2025-09-28 19:34:05 +08:00
MyPrototypeWhat
e95219f2ec refactor(tools): streamline tool selection and enhance unknown tool handling
- Introduced a new utility function to determine if a tool is an agent tool, simplifying the tool selection logic in MessageTool.
- Refactored MessageAgentTools to improve rendering logic and added an UnknownToolRenderer for better handling of unrecognized tools.
- Updated BashOutputTool to remove unnecessary Card components, enhancing layout consistency.
- Improved overall code clarity and maintainability by reducing redundancy and adhering to existing patterns.
2025-09-28 19:00:35 +08:00
icarus
965d7d3008 feat(i18n): add "unknown" translation placeholder to multiple locales
Add "[to be translated]:Unknown" placeholder for the "unknown" key in various language files to mark it for future translation.
2025-09-28 15:21:44 +08:00
icarus
128385bfe0 style(Inputbar): format code 2025-09-28 15:04:21 +08:00
icarus
cfdeb124b9 Merge branch 'main' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-28 15:03:36 +08:00
icarus
8deaa6e4f6 feat(chat-navbar): improve agent selection UI with breadcrumbs and horizontal scroll
Add Breadcrumbs and HorizontalScrollContainer components to enhance agent selection UI. Remove redundant agent name display since it's now shown in the breadcrumb chip. Improve layout with better overflow handling and responsive design.
2025-09-28 14:59:04 +08:00
icarus
b8a84f62ac style(ui): improve layout and text overflow handling in agent components
- Add max-width to agent name tag in ChatNavbar
- Adjust header padding in AgentSettingsPopup
- Replace span with Ellipsis component for agent names to handle overflow
2025-09-28 14:17:04 +08:00
icarus
cb922b67ad feat(i18n): add unknown translation key 2025-09-28 12:29:20 +08:00
icarus
b0213742f4 refactor(ChatNavbar): extract InfoTag component and add agent name display
- Extract repeated div styling into reusable InfoTag component
- Add agent name to the info items display
- Replace inline styles with tailwind classes for consistency
2025-09-28 12:29:03 +08:00
icarus
90264f6ec9 feat(MessageHeader): add agent name display for assistant messages in agent view 2025-09-28 12:22:58 +08:00
icarus
1ef6de1869 style(AgentSettings): change chip color from secondary to default for consistency 2025-09-28 12:21:42 +08:00
icarus
e4ad5084cf feat(theme): add hero UI primary color variants
Add multiple shades of the primary color for hero UI components to support better visual hierarchy and theming flexibility
2025-09-28 12:18:58 +08:00
icarus
0ef2725dfd style(AgentSettings): change ShieldAlert icon color to danger-600 for better visibility 2025-09-28 12:04:58 +08:00
icarus
4bd492f498 fix(AgentSettings): correct agent name display logic in AgentLabel 2025-09-28 11:55:53 +08:00
Vaayne
ef7433c823 🌐 fix(i18n): add missing 'common.selected' translation key across all locales
- Add 'selected' key to common section in all language files (en-us, zh-cn, zh-tw, el-gr, es-es, fr-fr, ja-jp, pt-pt, ru-ru)
- Fix CLAUDE.md documentation to use correct 'yarn sync:i18n' command
- Resolve '[to be translated]' placeholders with proper localized translations
- Ensure consistency across all supported languages

Fixes missing i18n key error: [I18N] Missing key: common.selected
2025-09-28 11:02:05 +08:00
Vaayne
b6765b48b5 Refactor translation files: Update agent terminology to assistant, remove MCP server references, and enhance permission mode descriptions across multiple languages (es-es, fr-fr, ja-jp, pt-pt, ru-ru). 2025-09-28 10:18:59 +08:00
icarus
7c45e42602 fix(assistants): add ts-ignore for ts2589 errors in state updates 2025-09-27 18:59:16 +08:00
icarus
57a40f84b9 Merge branch 'main' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-27 18:32:11 +08:00
icarus
e737f71932 feat(i18n): add unnamed translation and use in session creation
Add "unnamed" translation in both zh-cn and en-us locales
Use the translation as default name when creating new sessions
2025-09-27 18:28:08 +08:00
icarus
9ec6e5f771 fix(ui): add delay and closeDelay props to Tooltip in SessionItem
Improve user experience by adding a small delay before showing tooltip and removing the close delay
2025-09-27 18:24:13 +08:00
icarus
4647688613 fix(SessionItem): prevent event propagation when clicking delete
Stop click event propagation to avoid unintended parent component interactions when deleting a session
2025-09-27 18:10:08 +08:00
icarus
bc0f283278 fix(sessions): reset topic fulfilled state when switching sessions
Reset the topic fulfilled state when switching between sessions to ensure proper state management. Also remove redundant state update from SessionItem's onPress handler.
2025-09-27 18:09:43 +08:00
icarus
aadadf8353 fix(session): remove redundant fulfilled dispatch and add loading indicators
Remove the redundant dispatch of setTopicFulfilled in messageThunk since it's now handled in SessionItem. Add visual indicators for pending and fulfilled states in SessionItem to improve user feedback.
2025-09-27 18:03:42 +08:00
icarus
d0a0685fc1 fix(agent): update error message for empty accessible paths 2025-09-27 17:39:03 +08:00
icarus
ba7d5f53e5 feat(i18n): add anthropic api host translations and permission mode fields
Add new translation fields for Anthropic API host configuration and permission mode settings in both zh-cn and en-us locales
2025-09-27 17:36:25 +08:00
icarus
86dde5dc0f feat(agents): improve error handling and form validation in agent management
- Add getErrorMessage utility for consistent error message formatting
- Enhance addAgent to return Result type for better error handling
- Add disallowEmptySelection to form dropdowns
- Reset loading state on errors in AgentModal
2025-09-27 17:32:19 +08:00
icarus
a5ceceeca3 refactor(SessionItem): replace delete button as a div to avoid nested button 2025-09-27 17:17:39 +08:00
icarus
fcfda90d5a Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-27 17:02:34 +08:00
icarus
2ccfde1ba4 feat(agent): add emoji avatar support and refactor avatar handling
- Rename getAgentAvatar to getAgentDefaultAvatar for clarity
- Add EmojiAvatarWithPicker component for emoji selection
- Update AgentLabel to support both default and emoji avatars
- Add AvatarSetting component for avatar configuration
- Modify agent configuration schema to support emoji avatars
2025-09-27 17:02:29 +08:00
Vaayne
ae1c1409e1 feat(ChatNavbar): add session workspace metadata display in navbar 2025-09-27 16:53:49 +08:00
icarus
b46237296e style: change no-unused-vars rule from error to warn 2025-09-27 15:52:03 +08:00
icarus
8c06d2f706 refactor(AgentSettings): remove unused ModelSetting component 2025-09-27 15:27:20 +08:00
icarus
1b705edb06 feat(model-selection): add model type filtering to exclude embedding/rerank/image models
Add modelFilter parameter to SelectApiModelPopup to exclude embedding, rerank and text-to-image models from selection. This ensures only appropriate models are shown based on agent type requirements.
2025-09-27 15:11:16 +08:00
icarus
42435e8f76 refactor(agent): update useUpdateAgent hook and related components
- Refactor useUpdateAgent to return both updateAgent and updateModel functions
- Update all components using useUpdateAgent to use the new hook structure
- Improve model selection by reusing SelectAgentModelButton component
- Add pagination support to useApiModels hook
2025-09-27 15:05:26 +08:00
icarus
3111979bb4 feat(components): replace spans with Ellipsis for model labels
Use Ellipsis component to handle text overflow in model labels for better readability
2025-09-27 14:27:19 +08:00
icarus
56580e3fac Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-27 14:19:06 +08:00
icarus
7084b8d429 style(AgentItem): add background color to session count chip 2025-09-27 14:19:00 +08:00
icarus
8b0e8506c2 feat(SessionItem): add confirmation for session deletion with keyboard shortcut
Add a confirmation step before deleting a session, including a tooltip showing the keyboard shortcut. Uses a timer to automatically cancel the confirmation after 3 seconds.
2025-09-27 14:17:43 +08:00
Vaayne
4d133d59ea feat: enhance Anthropic API support for compatible providers
- Add support for anthropicApiHost configuration in providers
- Improve model filtering for Anthropic-compatible providers
- Add isAnthropicModel function to validate Anthropic models
- Update ClaudeCode service to support compatible providers
- Enhance logging and error handling in API routes
- Fix model transformation and validation logic
2025-09-27 14:10:47 +08:00
Vaayne
35b885798b Add Anthropic API Host support for compatible providers
- Add `anthropicApiHost` field to Provider type - Update provider config
and migration to set Anthropic endpoints - Add UI for configuring
Anthropic API Host in provider settings - Update SDK client logic to use
Anthropic API Host when available - Add i18n strings for Anthropic API
Host configuration
2025-09-27 14:10:47 +08:00
Vaayne
ae9e12b276 feat: add slash command functionality to agent services 2025-09-27 14:10:47 +08:00
Vaayne
8018ac1a97 feat(agent): add optional avatar and slash_commands to AgentConfigurationSchema 2025-09-27 14:10:47 +08:00
icarus
f429e3fc01 style(ui): move lucide icon color rule and add warning icon to caution text
Move the lucide icon color rule into the media query block for consistency.
Add AlertTriangleIcon to caution text in AgentModal for better visual warning.
2025-09-27 13:55:01 +08:00
icarus
6c63146556 refactor(SessionItem): replace className with isActive prop for better readability
Use isActive prop instead of className to control active state styling
Add dynamic background color based on topicPosition setting
2025-09-27 13:46:26 +08:00
icarus
29242154d0 feat(AgentItem): add session count chip for active agents
Display active session count as a chip next to agent name when agent is active
2025-09-27 13:38:21 +08:00
icarus
ccc5e830d7 refactor(Sessions): remove unused index parameter and delay from animation
Simplify animation by removing unused index parameter and delay calculation
2025-09-27 13:27:10 +08:00
Phantom
adf10f6ea1 style(settings): remove unnecessary padding from ContentContainer (#10379) 2025-09-27 10:04:34 +08:00
Zhaokun
26a6ff871f feat: improve content protection during file operations (#10378)
* feat: improve content protection during file operations

- Add validation for knowledge base configuration before saving
- Enhance error handling for note content reading
- Implement content backup and restoration during file rename
- Add content verification after rename operations
- Improve user feedback with specific error messages

* fix: format check

---------

Co-authored-by: 自由的世界人 <3196812536@qq.com>
2025-09-27 10:04:34 +08:00
MyPrototypeWhat
d1e85f964d fix(websearch): handle blocked domains conditionally in web search (#10374)
fix(websearch): handle blocked domains conditionally in web search configurations

- Updated the handling of blocked domains in both Google Vertex and Anthropic web search configurations to only include them if they are present, improving robustness and preventing unnecessary parameters from being passed.
2025-09-27 10:04:34 +08:00
kangfenmao
8d041438fd chore: remove cherryin provider references and update versioning
- Commented out all references to the 'cherryin' provider in configuration files.
- Updated the version in the persisted reducer from 157 to 158.
- Added migration logic to remove 'cherryin' from the state during version 158 migration.
2025-09-27 10:04:34 +08:00
Zhaokun
c6dc1810e9 Fix slash newline (#10305)
* Fix slash menu Shift+Enter newline

* fix: enable Shift+Enter newline in rich editor with slash commands

Fixed an issue where users couldn't create new lines using Shift+Enter when
slash command menu (/foo) was active. The problem was caused by globa
keyboard event handlers intercepting all Enter key variants.

Changes:
 - Allow Shift+Enter to pass through QuickPanel event handling
 - Add Shift+Enter detection in CommandListPopover to return false
 - Implement fallback Shift+Enter handling in command suggestion render
 - Remove unused import in AppUpdater.ts
 - Convert Chinese comments to English in QuickPanel
- Add test coverage for command suggestion functionality

---------

Co-authored-by: Zhaokun Zhang <zhaokunzhang@Zhaokuns-Air.lan>
2025-09-27 10:02:40 +08:00
Vaayne
fa394576bb Refine agent permissions UI & translations 2025-09-26 17:36:46 +08:00
Vaayne
5c1ac376e6 fix(AgentConfigurationSchema): update default max_turns to 100 2025-09-26 16:32:12 +08:00
icarus
88e77aa116 Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-26 14:41:07 +08:00
icarus
4e9340f551 fix(useAgents): add missing dependencies to useCallback hook 2025-09-26 14:41:01 +08:00
kangfenmao
0648a1f567 refactor(assistants): rename agents to assistants and update related components
- Updated references from 'agents' to 'assistants' across various components and hooks.
- Changed i18n keys to reflect the new terminology for better clarity.
- Removed the deprecated agents slice and integrated its functionality into the assistants slice.
- Adjusted UI components to align with the new naming conventions for assistant presets.
2025-09-26 14:37:12 +08:00
icarus
4b1f7db506 fix(AgentSessionInputbar): add agent model to dependency array
Ensure the component re-renders when agent model changes to maintain consistency with session data
2025-09-26 14:33:35 +08:00
icarus
0be2177937 fix(chat): handle agent and session state changes properly
update activeAgentId type to allow null and reset state when deleting agent
add validation for missing agent/session in UI components
2025-09-26 14:31:56 +08:00
icarus
c52cc5a94f style(sessions): update styling and add scrollbar props to DynamicVirtualList
- Change class name from agents-tab to sessions-tab and add flex layout
- Add overflowX hidden and autoHideScrollbar props to DynamicVirtualList
2025-09-26 14:01:16 +08:00
icarus
947695fdc7 feat(sessions): replace manual list with virtual list for better performance 2025-09-26 13:54:27 +08:00
icarus
75296babe3 style(SessionsTab): adjust overflow styling for cleaner appearance 2025-09-26 13:54:22 +08:00
icarus
c9381d672e style(SessionsTab): adjust overflow styling for better scroll behavior 2025-09-26 13:50:44 +08:00
icarus
67fa5df611 style(SessionsTab): add overflow-auto to improve scroll behavior 2025-09-26 13:49:56 +08:00
icarus
122e4a10d0 refactor(api): improve session messages path handling by returning object with base and withId
Simplify deleteSessionMessage implementation by using the new paths object structure
2025-09-26 05:44:23 +08:00
icarus
b82b16b5f6 style(ui): update button hover background color to use CSS variable
Consistent hover state styling across components by using --color-list-item variable instead of accent color
2025-09-26 05:01:06 +08:00
icarus
ebdd90b235 feat(SessionsTab): add animation and styling based on topic and navbar position
Add motion animation and conditional border styling to SessionsTab component based on topicPosition and navbarPosition settings
2025-09-26 04:57:25 +08:00
icarus
5c8e06ed94 style(components): update button styling in AgentItem and SessionItem
- Change hover background color and add shadow in AgentItem
- Use cn utility for className in SessionItem
- Update height and background color for active state in SessionItem
2025-09-26 04:37:30 +08:00
icarus
f4e4586fbc refactor(SelectAgentModelButton): replace styled-components with tailwind classes
Simplify component styling by removing styled-components in favor of tailwind utility classes
2025-09-26 04:11:48 +08:00
icarus
fab1d29c83 fix: prevent model update when same model is selected 2025-09-26 04:06:17 +08:00
icarus
de9cb2fbdb feat(model-selection): add api model selection support for agents
- Introduce SelectAgentModelButton component for agent model selection
- Add SelectApiModelPopup for displaying and selecting API models
- Implement apiModelAdapter to convert API models to adapted format
- Add model filtering by agent type in agentSession utils
- Update model select components to use new API model selection
2025-09-26 04:04:23 +08:00
icarus
a419aed404 refactor(animations): simplify motion animations in SessionsTab and Sessions components
Remove redundant motion animations and streamline transition properties to improve code maintainability
2025-09-26 01:42:31 +08:00
icarus
cb47e8decd feat(Settings): Extract the reusable parts from AgentSettings for use in SessionSettings 2025-09-26 01:22:28 +08:00
icarus
3c4bb72a82 refactor(AgentSettings): extract styled components to shared module
Move styled components from AgentSettingsPopup to shared.tsx to improve code reusability and maintainability
2025-09-26 00:13:13 +08:00
icarus
cab79ef185 refactor(AgentSettings): move popup component to separate file for better organization 2025-09-26 00:11:24 +08:00
icarus
a87c06aab8 fix(home-tabs): prevent settings tab when active topic is session
Add useEffect to automatically switch to topic tab when active topic is session and tab is settings to avoid invalid state
2025-09-25 23:45:13 +08:00
icarus
c19659daa5 Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-25 23:38:50 +08:00
icarus
bafde1c518 refactor(agent-settings): rename advance to advanced in settings components and types
Update component and type names from 'advance' to 'advanced' for consistency and correct spelling. This includes renaming the file and all related references in the codebase.
2025-09-25 23:38:29 +08:00
Vaayne
45961d2eda Merge remote-tracking branch 'origin/main' into feat/agents-new 2025-09-25 23:35:29 +08:00
Vaayne
e1a0dd6810 feat(timeout): implement extendMessagesTimeout middleware and set server timeouts 2025-09-25 23:33:33 +08:00
Vaayne
a1d14b9292 feat(claudecode): enhance streaming transform flow 2025-09-25 23:33:33 +08:00
Vaayne
a7d6065b08 refactor(routes): streamline provider-specific messages route setup 2025-09-25 23:33:33 +08:00
Vaayne
5dbd38721f refactor(messages): remove debug logging and enhance streaming response handling 2025-09-25 23:33:33 +08:00
Vaayne
39fcc04d78 refactor(logging): improve logging messages for clarity and consistency
- Updated logging statements across various modules to provide more structured and detailed information.
- Changed log levels from info to debug for less critical messages to reduce log clutter.
- Enhanced error logging to include relevant context such as agentId, sessionId, and model details.
- Standardized log messages to follow a consistent format, improving readability and maintainability.
2025-09-25 23:33:33 +08:00
icarus
5c7784622e fix(AgentEssentialSettings): handle undefined name and description states
Ensure proper handling of undefined values for agent name and description by making state types optional. Also update the updateName function to handle optional name input.
2025-09-25 23:21:11 +08:00
kangfenmao
3088887e57 Merge branch 'main' into feat/agents-new 2025-09-25 15:02:52 +08:00
icarus
14f14b75b0 fix(home-tabs): correct conditional rendering of topic and settings tabs
Ensure tabs are only shown when isTopicView is true and simplify the tab labels by removing conditional rendering
2025-09-24 19:24:36 +08:00
icarus
77351b7691 refactor(home-tabs): improve tab view logic readability
Extract topic view check into separate variable for clarity
Rename canShowSettingsTab to shouldShowSettingsTab for better semantics
2025-09-24 19:21:40 +08:00
icarus
b28fadd02f feat(AgentSettings): add description field to agent essential settings 2025-09-24 18:49:51 +08:00
icarus
63fa70863c refactor(AgentSessionInputbar): use agent model instead of session model for consistency
Use agent's model information instead of session's to maintain consistency across the application. The model ID format changed from "sessionId:modelId" to "provider:modelId" and the model object is now constructed using the actual model details from the agent.
2025-09-24 18:41:51 +08:00
icarus
11a76ae90f fix(AgentModal): improve modal layout and fix description field position
Adjust modal height and overflow behavior
Move description textarea below prompt field for better logical flow
2025-09-24 18:27:26 +08:00
suyao
1973e4d290 refactor: remove unnecessary type declaration for request body in message processing 2025-09-24 15:35:22 +08:00
Vaayne
7a169c424d refactor: update logging in message processing to use debug level and improve clarity 2025-09-24 14:23:06 +08:00
beyondkmp
69bcb0e13e format code 2025-09-24 13:54:27 +08:00
beyondkmp
54386bf624 reduce app size 2025-09-24 13:30:15 +08:00
beyondkmp
fe6e65f263 format code 2025-09-24 12:59:00 +08:00
beyondkmp
f05b884646 use fork instead of spawn 2025-09-24 11:08:43 +08:00
icarus
8e163b8f17 Merge branch 'main' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-24 03:28:54 +08:00
icarus
caebaf5d46 chore: add tailwindCSS class attributes to vscode settings 2025-09-24 03:21:19 +08:00
icarus
6950b6f1e7 feat(session-item): add in-place editing for session names
- Implement double-click to edit session names directly in the list
- Add loading state during save operation
- Update useInPlaceEdit hook to support async operations and saving state
- Adjust styling to accommodate new edit input field
2025-09-24 03:21:00 +08:00
icarus
0e35224787 refactor(SessionModal): remove unused model selection code and related imports
clean up unused model selection logic and dependencies that are no longer needed in the session modal component
2025-09-24 02:17:43 +08:00
icarus
e5a84a2e84 Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-24 02:14:57 +08:00
Vaayne
09da7113a0 refactor: disable debug logging for SDK message transformation 2025-09-23 23:53:07 +08:00
Vaayne
e6e43dbcca feat: conditionally render settings tab based on session view 2025-09-23 23:35:41 +08:00
Vaayne
e02f826707 refactor: update API configuration handling and improve logging level 2025-09-23 22:51:53 +08:00
Vaayne
781b01ee17 feat: refactor shell environment handling and move to utils 2025-09-23 22:36:14 +08:00
icarus
1f1086ed7b style(AgentAdvanceSettings): adjust width styling for maxTurns input 2025-09-23 22:28:42 +08:00
icarus
0a80fc5517 refactor(hooks): improve scroll position hook with timer utility
- Replace setTimeout with useTimer utility for better cleanup
- Add throttleWait parameter for configurable scroll throttling
- Update documentation to reflect changes
2025-09-23 22:20:35 +08:00
beyondkmp
6d8edc95d9 fix spawn no node error 2025-09-23 21:34:51 +08:00
beyondkmp
a54b49cc30 fix app unpack error 2025-09-23 20:31:40 +08:00
suyao
d1b339f71d fix: 修复代码格式和简化错误处理逻辑 2025-09-23 19:03:54 +08:00
MyPrototypeWhat
a3c638946e feat(tools): enhance type definitions for agent tools
- Added detailed JSDoc comments for clarity on tool input types, including ReadToolInput, TaskToolInput, BashToolInput, and others.
- Introduced new input types such as ListMcpResourcesToolInput and ReadMcpResourceToolInput to expand functionality.
- Improved existing types to ensure better documentation and usability for developers.
2025-09-23 18:02:44 +08:00
suyao
a0193451a9 feat: 更新会话列表查询,按更新时间降序排序 2025-09-23 17:54:48 +08:00
suyao
ede2b75cd0 feat: 移除特性标志相关代码,简化消息存储逻辑 2025-09-23 17:40:29 +08:00
suyao
34ab01e0a1 Merge branch 'feat/agents-new' of https://github.com/CherryHQ/cherry-studio into feat/agents-new 2025-09-23 17:34:47 +08:00
suyao
b493172090 feat: 添加提取会话ID的功能并更新消息发送逻辑 2025-09-23 17:34:23 +08:00
Vaayne
6bcd941cc6 feat: Implement delete message functionality and validation in session messages 2025-09-23 16:08:52 +08:00
Vaayne
98ebfd12b3 refactor: Improve logging and error handling in MCPApiService and ClaudeCodeService 2025-09-23 16:08:52 +08:00
MyPrototypeWhat
305a454ffd feat(tools): add new agent tools for enhanced functionality
- Introduced new tools: EditTool, MultiEditTool, BashOutputTool, NotebookEditTool, and ExitPlanModeTool.
- Updated MessageTool to support new tool types.
- Enhanced ReadTool to handle output as an array of text outputs.
- Improved type definitions to accommodate new tools and their inputs/outputs.
2025-09-23 14:47:58 +08:00
GitHub Action
dfc593f2e1 fix(i18n): Auto update translations for PR #10096 2025-09-23 06:05:52 +00:00
icarus
b50203f85d Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-23 14:04:54 +08:00
icarus
e2a0792e2d feat(AgentToolingSettings): improve modal styling and accessibility
- Add text color classes to modal title and list items for better visibility
- Apply background and border styling to modal content
- Use modal hook pattern for consistency
2025-09-23 14:03:13 +08:00
icarus
b7d97cca69 style(AgentToolingSettings): improve warning message layout and search input width 2025-09-23 13:36:15 +08:00
suyao
7cdc80c3e2 Merge branch 'feat/agents-new' of https://github.com/CherryHQ/cherry-studio into feat/agents-new 2025-09-23 13:25:27 +08:00
GitHub Action
59b6cbc23c fix(i18n): Auto update translations for PR #10096 2025-09-23 04:32:42 +00:00
Vaayne
21c436d900 refactor: Clean up JSON structure and improve readability in locale files 2025-09-23 12:23:10 +08:00
icarus
87f3628b49 Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-23 12:19:53 +08:00
icarus
27b315bcca style(AgentSection): add margin bottom to agents tab container 2025-09-23 12:19:47 +08:00
Vaayne
1ec81f9e75 Merge remote-tracking branch 'origin/feat/agents-new' into feat/agents-new 2025-09-23 12:16:58 +08:00
Vaayne
087e757f9f feat: Refactor agent settings and introduce tooling permissions
- Translated and reorganized Russian language JSON for tooling and permissions.
- Removed deprecated MCP and tool settings components.
- Introduced new AgentToolingSettings component to manage tooling permissions and MCP servers.
- Updated AgentSettings index to reflect new tooling settings structure.
- Enhanced agent configuration schema to include permission modes with default values.
2025-09-23 11:59:43 +08:00
icarus
ce955e3ee9 refactor(AgentEssentialSettings): replace antd Select with custom Select component
The antd Select component was replaced with a custom Select component from @heroui/react to improve consistency with the design system. This change also simplifies the model selection logic by removing the need for manual option mapping.
2025-09-23 11:45:36 +08:00
icarus
4ddada4de8 refactor(AgentToolSettings): wrap Alert component in div for better structure
Improve component structure by wrapping Alert in a div element to maintain consistent layout and styling
2025-09-23 11:19:00 +08:00
icarus
164386a337 Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-23 11:15:44 +08:00
icarus
d4d2510834 feat(agent): add AllowedToolsSelect component and integrate into forms
extract tool selection logic into reusable component to reduce code duplication and improve maintainability
2025-09-23 11:13:11 +08:00
GitHub Action
46a5ea88f3 fix(i18n): Auto update translations for PR #10096 2025-09-23 02:35:34 +00:00
Vaayne
7ca9dcd2fb ♻️ refactor: improve agent tool approval UI with dedicated settings tab
- Move tool selection from essential settings to dedicated "Pre-approved tools" tab
- Update terminology from "Allowed tools" to "Pre-approved tools" for clarity
- Add new AgentToolSettings component with enhanced card-based layout
- Include warning alert about pre-approved tools bypassing review
- Update all language files with new terminology and translation keys
- Add i18n sync guidance to CLAUDE.md development commands
2025-09-23 10:31:41 +08:00
Vaayne
9c679ede20 feat(agent): add advanced configuration settings 2025-09-23 10:31:41 +08:00
Vaayne
60c85b651f feat: add MCP server support for agents
- Add MCP server configuration UI for agent settings
- Update agent and session forms to include MCP server selection
- Fix MCP API service logging and tools handling
- Add Chinese localization for MCP settings
- Update type definitions to support MCP server arrays

This enables agents to use MCP (Model Control Protocol) servers
as additional tools and capabilities in their execution context.
2025-09-23 10:31:40 +08:00
icarus
73895b5f4b feat(agents): enhance model handling with filters and styling
- Add filter support to useApiModel hook for provider-specific models
- Improve ApiModelLabel with customizable classNames for styling
- Update ChatNavbar to use filtered models for agents
2025-09-23 10:30:53 +08:00
icarus
3e2acde9e2 feat(SessionModal): add multiline support for tools selection
Enable multiline display for the tools selection dropdown to improve visibility when multiple tools are selected
2025-09-23 10:19:24 +08:00
suyao
a1d8f3eb0f Implement InputbarTools registry system for tool management
- Add ToolDefinition interface and registry mechanism with dependency injection
- Create InputbarToolsProvider for shared state management (files, mentionedModels, etc.)
- Migrate existing tools to registry-based definitions and simplify component props
2025-09-23 06:15:33 +08:00
suyao
0aba7bad31 Remove TODO file after completing agents service refactor
- Delete obsolete TODO.md tracking interface-level refactor tasks
- All major refactor items marked as completed except regression tests
- File removal reflects transition from planning to implementation phase
2025-09-23 06:11:06 +08:00
suyao
75660766db feat: 将日志级别从 info 更改为 silly,以增强调试信息的详细程度 2025-09-23 06:06:29 +08:00
suyao
53a6c70eca feat: 添加条件渲染以隐藏假助手的设置组,优化用户界面 2025-09-23 06:04:25 +08:00
suyao
da18ff3d48 feat: 优化工具名称和描述的样式,增强可读性;添加 TopicType 支持到导出测试 2025-09-23 05:49:08 +08:00
suyao
4a671a9bc2 feat: 添加输入框统一计划文档,定义配置层和共享UI组件的任务 2025-09-23 05:37:45 +08:00
suyao
ae1839ac33 feat: 添加代理会话初始化钩子并在相关组件中使用 2025-09-23 05:19:00 +08:00
suyao
56dbe6b050 feat: 添加消息菜单栏配置和按钮渲染逻辑 2025-09-23 05:05:31 +08:00
suyao
f5a41e9c78 feat: add agent session renaming functionality based on message summary 2025-09-23 04:10:37 +08:00
suyao
f65149af19 Merge branch 'feat/agents-new' of https://github.com/CherryHQ/cherry-studio into feat/agents-new 2025-09-23 03:38:00 +08:00
suyao
affef443b6 feat: improve block merging logic in message updates 2025-09-23 03:36:04 +08:00
suyao
e40e1d0b36 feat: refactor message persistence and block update logic for agent sessions 2025-09-23 03:18:17 +08:00
Vaayne
14638b7470 feat: add tool selection functionality for agents and sessions
Add comprehensive tool management UI allowing users to select which tools are pre-approved for agents and sessions. Includes multi-select dropdowns with tool descriptions, proper validation, and internationalization support across 10+ languages.

- Add tool selection UI to AgentModal, SessionModal, and AgentEssentialSettings
- Extend BaseAgentForm and related types with allowed_tools field
- Implement tool validation and filtering logic
- Add i18n support for tool selection labels and descriptions
- Include visual chip-based display for selected tools
2025-09-23 00:21:27 +08:00
Vaayne
b4a92cecc8 feat: enhance agent creation and session management with automatic session provisioning 2025-09-23 00:21:27 +08:00
Vaayne
49e4667410 fix: resolve lint findings in renderer 2025-09-23 00:21:27 +08:00
Vaayne
5d26bf15a3 fix: stabilize tool streaming typings 2025-09-23 00:21:27 +08:00
MyPrototypeWhat
7631d9d730 feat(Tools): add WebFetchTool and update tool rendering logic
- Introduced WebFetchTool for fetching web content with specified prompts and URLs.
- Updated MessageTool to include WebFetch in the tool rendering options.
- Enhanced BashTool and TaskTool to improve display of input and output information.
- Refactored GenericTools for better parameter display and consistency across tools.
- Adjusted types to include WebFetchTool input and output definitions.
2025-09-22 23:47:51 +08:00
suyao
91b4d806cd chore: remove docs 2025-09-22 23:15:11 +08:00
suyao
1b8bb568b1 Merge branch 'refactor/agent-assistant-unified' into feat/agents-new 2025-09-22 23:14:46 +08:00
suyao
18da9a19fd chore: remove docs 2025-09-22 23:12:46 +08:00
suyao
7fdae0173c Implement file reference count cleanup with deleteIfZero support
- Update DexieMessageDataSource to delete files when count reaches zero and deleteIfZero is true
- Add deleteIfZero parameter to MessageDataSource interface and all implementations
- Modify updateFileCountV2 thunk to pass deleteIfZero parameter through DbService
2025-09-22 23:12:08 +08:00
suyao
c872707791 Remove TODO.md and update DbService file count interface
- Delete TODO.md as the unified data layer implementation is complete
- Remove unsupported deleteIfZero parameter from updateFileCountV2 call
2025-09-22 23:08:08 +08:00
suyao
a0cab3341e Refactor message loading in useSession hook to use centralized thunk
- Replace manual message loading logic with loadTopicMessagesThunk for better caching
- Remove unused imports and local state management
- Simplify useEffect dependencies and loading flow
2025-09-22 23:05:33 +08:00
suyao
035001f841 Ensure session messages are properly restored when switching sessions
- Add Redux selector to check for existing messages in store
- Always reload messages to Redux when session data is available
- Add effect to restore messages when component mounts if missing from Redux
2025-09-22 22:53:57 +08:00
suyao
f533c1a2ca Refactor agent session messages to use shared hook and implement batch deletion
- Replace manual Redux logic with `useTopicMessages` hook for consistent message loading behavior
- Add `deleteMessages` method to message data sources with proper block and file cleanup
- Update `DbService` to delegate batch deletion to appropriate data source implementations
2025-09-22 22:50:45 +08:00
suyao
e5aa58722c Optimize agent message streaming with throttled persistence
- Prevent unnecessary message reloads by checking existing messages before loading session messages
- Implement LRU cache and throttled persistence for streaming agent messages to reduce backend load
- Add streaming state detection and proper cleanup for complete messages to improve performance
2025-09-22 22:29:03 +08:00
suyao
8645fe4ab1 Remove persistExchange functionality and simplify agent session handling
- Delete persistExchange method from all data sources and DbService
- Remove unused Topic import and MessageExchange type dependencies
- Simplify agent session existence check to validate sessionId directly
- Make getRawTopic required in MessageDataSource interface
2025-09-22 22:03:47 +08:00
suyao
15f216b050 Implement agent session message persistence and streaming state management
- Add comprehensive solution documentation for status persistence and streaming state
- Implement message update functionality in AgentMessageDataSource for agent sessions
- Remove redundant persistAgentExchange logic to eliminate duplicate saves
- Streamline message persistence flow to use appendMessage and updateMessageAndBlocks consistently
2025-09-22 21:46:40 +08:00
suyao
b4df5bbb13 Fix agent session message persistence by saving messages immediately
- Modify AgentMessageDataSource.appendMessage to save messages to backend immediately instead of waiting for response completion
- Add proper error handling and logging for message persistence operations
- Create comprehensive test documentation covering V2 database service scenarios
2025-09-22 21:06:16 +08:00
suyao
a17a198912 Add V2 database service integration with feature flag support
- Integrate V2 implementations for message operations (save, update, delete, clear) with feature flag control
- Add topic creation fallback in DexieMessageDataSource when loading non-existent topics
- Create integration status documentation tracking completed and pending V2 migrations
- Update Topic type to include TopicType enum for proper topic classification
2025-09-22 20:40:53 +08:00
MyPrototypeWhat
939782ac4e refactor(Tools): replace MCPToolResponse with NormalToolResponse in m… (#10303)
* refactor(Tools): replace MCPToolResponse with NormalToolResponse in message tools and add new agent tools

- Updated MessageKnowledgeSearch, MessageMemorySearch, and MessageWebSearch components to use NormalToolResponse.
- Refactored MessageTool to handle NormalToolResponse and simplified tool rendering logic.
- Introduced new agent tools: BashTool, GlobTool, GrepTool, ReadTool, SearchTool, TaskTool, and TodoWriteTool with corresponding types and renderers.
- Enhanced type safety by updating tool response types in the codebase.

* fix(i18n): Auto update translations for PR #10303

* chunk type

* refactor(migration): renumber migration steps after removing step 155

Remove unused migration step 155 and renumber subsequent steps to maintain sequence

* fix(store): prevent mutation of assistant presets by using spread operator

* fix(store): ignore ts-2589 false positives and refactor preset updates

Refactor assistant preset updates to use forEach instead of map for consistency
Add ts-ignore comments for TypeScript false positives in store operations

* Fix tool result handling and session creation flow

- Populate toolName in tool-result chunks from contentBlockState
- Add onSessionCreated callback to SessionModal for post-creation actions
- Return created session from useSessions hook and update SWR cache optimistically

* Fix toolName reference in ClaudeCode message transformation

- Correctly reference toolName from contentBlockState using blockKey instead of block.tool_use_id
- Ensure proper tool result chunk generation when handling assistant messages
- Maintain consistent data structure for tool call processing

* Fix toolName reference and add stream event logging

- Correct toolName lookup to use tool_use_id instead of blockKey in tool-result chunks
- Add debug logging for stream event handling
- Update contentBlockState key to use event.content_block.id for tool_use events

* Add debug logging for message content blocks

- Log each content block when processing user or assistant messages
- Maintain existing switch case logic for text block handling
- Improve debugging visibility for multi-block message processing

* get toolName

* chore: bump version to 1.7.0-alpha.1

* fix(getSdkClient): add authToken to anthropic client initialization for claude code

* Update transform.ts

* Refactor logging levels in transform.ts and adjust JSON body parser configuration in app.ts

* refactor(sessions): simplify session creation by removing modal and using direct button

The SessionModal component was removed and replaced with a direct button click handler that creates a session using the agent data. Also added error handling to display an alert when session fetching fails.

* feat(agents): add api server check and warning for agent features

- Add api server enabled check in multiple components
- Show warning alert when api server is disabled
- Add dismissable warning in AgentSection
- Disable send button when api server is disabled
- Add iknow state to store dismissed warnings

* feat(i18n): add warning message for enabling API server

Add warning message in multiple languages to inform users they need to enable API server to use agent features

* feat(sessions): make session creation async and set active session

Dispatch active session id after successful creation to ensure UI reflects current state

* feat(sessions): add session waiting state and improve deletion handling

- Add sessionWaiting state to track updating/deleting sessions
- Extract updateSession logic into separate hook
- Improve session deletion with waiting state and fallback session selection
- Disable session items during deletion to prevent duplicate actions

* feat(i18n): add error message for last session deletion

Add error message to prevent deletion of the last session in all supported languages

* fix(i18n): Auto update translations for PR #10096

* fix(i18n): Auto update translations for PR #10096

* feat(tools): add WriteTool and update tool rendering logic

- Introduced WriteTool for handling file writing operations.
- Updated MessageAgentTools to include the new WriteTool in the tool renderers.
- Refactored existing tools to streamline rendering and improve code clarity.
- Enhanced BashTool and TaskTool to better display input and output information.

---------

Co-authored-by: GitHub Action <action@github.com>
Co-authored-by: suyao <sy20010504@gmail.com>
Co-authored-by: icarus <eurfelux@gmail.com>
Co-authored-by: Vaayne <liu.vaayne@gmail.com>
2025-09-22 19:53:10 +08:00
suyao
7e369bef00 Merge branch 'feat/agents-new' into refactor/agent-assistant-unified 2025-09-22 19:45:23 +08:00
suyao
c3adcf663f Merge branch 'feat/agents-new' of https://github.com/CherryHQ/cherry-studio into feat/agents-new 2025-09-22 19:24:54 +08:00
suyao
373b2fcd78 feat: abort 2025-09-22 19:24:20 +08:00
GitHub Action
c9d1e30f8b fix(i18n): Auto update translations for PR #10096 2025-09-22 10:49:01 +00:00
icarus
761b57a834 Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-22 18:48:17 +08:00
icarus
632871b2f8 feat(i18n): add error message for last session deletion
Add error message to prevent deletion of the last session in all supported languages
2025-09-22 18:48:11 +08:00
icarus
52f00f08f2 feat(sessions): add session waiting state and improve deletion handling
- Add sessionWaiting state to track updating/deleting sessions
- Extract updateSession logic into separate hook
- Improve session deletion with waiting state and fallback session selection
- Disable session items during deletion to prevent duplicate actions
2025-09-22 18:47:24 +08:00
suyao
1d5761b1fd WIP 2025-09-22 18:32:19 +08:00
icarus
42dbc6555c feat(sessions): make session creation async and set active session
Dispatch active session id after successful creation to ensure UI reflects current state
2025-09-22 17:55:21 +08:00
GitHub Action
b237d9d38d fix(i18n): Auto update translations for PR #10096 2025-09-22 09:50:47 +00:00
icarus
1e9a811065 feat(i18n): add warning message for enabling API server
Add warning message in multiple languages to inform users they need to enable API server to use agent features
2025-09-22 17:49:55 +08:00
icarus
3c12f9052e feat(agents): add api server check and warning for agent features
- Add api server enabled check in multiple components
- Show warning alert when api server is disabled
- Add dismissable warning in AgentSection
- Disable send button when api server is disabled
- Add iknow state to store dismissed warnings
2025-09-22 17:48:05 +08:00
icarus
9425437480 refactor(sessions): simplify session creation by removing modal and using direct button
The SessionModal component was removed and replaced with a direct button click handler that creates a session using the agent data. Also added error handling to display an alert when session fetching fails.
2025-09-22 17:14:58 +08:00
Vaayne
2385fba695 Refactor logging levels in transform.ts and adjust JSON body parser configuration in app.ts 2025-09-22 16:32:32 +08:00
suyao
634c478e18 Update transform.ts 2025-09-22 16:11:19 +08:00
suyao
335bf47dbd Merge branch 'feat/agents-new' of https://github.com/CherryHQ/cherry-studio into feat/agents-new 2025-09-22 16:02:20 +08:00
suyao
23c4117d6f get toolName 2025-09-22 16:01:58 +08:00
suyao
4a5d3b31ab Add debug logging for message content blocks
- Log each content block when processing user or assistant messages
- Maintain existing switch case logic for text block handling
- Improve debugging visibility for multi-block message processing
2025-09-22 15:21:59 +08:00
suyao
17a27f0d55 Fix toolName reference and add stream event logging
- Correct toolName lookup to use tool_use_id instead of blockKey in tool-result chunks
- Add debug logging for stream event handling
- Update contentBlockState key to use event.content_block.id for tool_use events
2025-09-22 15:18:24 +08:00
suyao
8fbb93b0bf Fix toolName reference in ClaudeCode message transformation
- Correctly reference toolName from contentBlockState using blockKey instead of block.tool_use_id
- Ensure proper tool result chunk generation when handling assistant messages
- Maintain consistent data structure for tool call processing
2025-09-22 15:09:34 +08:00
suyao
e09cd6b6d7 Fix tool result handling and session creation flow
- Populate toolName in tool-result chunks from contentBlockState
- Add onSessionCreated callback to SessionModal for post-creation actions
- Return created session from useSessions hook and update SWR cache optimistically
2025-09-22 15:05:03 +08:00
Vaayne
26ac9e3c2e fix(getSdkClient): add authToken to anthropic client initialization for claude code 2025-09-22 15:02:53 +08:00
icarus
958edc0017 chore: bump version to 1.7.0-alpha.1 2025-09-22 14:44:21 +08:00
suyao
efa54f3435 Merge branch 'feat/agents-new' of https://github.com/CherryHQ/cherry-studio into feat/agents-new 2025-09-22 14:42:41 +08:00
icarus
88a2cd6659 Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-22 14:41:30 +08:00
icarus
4e26291a61 fix(store): ignore ts-2589 false positives and refactor preset updates
Refactor assistant preset updates to use forEach instead of map for consistency
Add ts-ignore comments for TypeScript false positives in store operations
2025-09-22 14:41:22 +08:00
icarus
f25142e597 fix(store): prevent mutation of assistant presets by using spread operator 2025-09-22 14:31:35 +08:00
GitHub Action
462fc84240 fix(i18n): Auto update translations for PR #10096 2025-09-22 06:29:28 +00:00
icarus
c97ad627d1 refactor(migration): renumber migration steps after removing step 155
Remove unused migration step 155 and renumber subsequent steps to maintain sequence
2025-09-22 14:28:40 +08:00
suyao
36307abc30 Merge branch 'feat/agents-new' of https://github.com/CherryHQ/cherry-studio into feat/agents-new 2025-09-22 14:11:10 +08:00
GitHub Action
8d3dbcb5f8 fix(i18n): Auto update translations for PR #10096 2025-09-22 06:08:24 +00:00
icarus
9d9ae7ba4e feat(i18n): add error messages for agent operations
Add error messages for agent get/list operations and restructure accessible paths validation messages
2025-09-22 14:04:37 +08:00
icarus
d682045655 refactor(AgentSettings): remove unused agentModel variable and TODO comment 2025-09-22 14:02:44 +08:00
icarus
381397ed31 style(AgentSettings): remove overflow-y scroll and adjust overflow settings
Update overflow behavior in settings components to use auto instead of scroll
and add right padding to prevent content clipping
2025-09-22 13:59:05 +08:00
icarus
4484f39525 feat(agent): enhance agent settings with accessible paths management
- Add UI for managing accessible paths in agent settings
- Improve error handling and loading states in agent components
- Update type definitions for better type safety
- Remove outdated comments and fix styling issues
2025-09-22 13:56:09 +08:00
icarus
82c08128b6 refactor(useModels): merge default filter with provided filter
Use lodash merge to combine provided filter with default values
2025-09-22 12:28:03 +08:00
icarus
8cd40a471e refactor(agent): replace agent type label map with switch statement
Simplify agent type label handling by replacing the map with a direct switch statement. Also update related type references and array type assertions for consistency.
2025-09-22 12:14:45 +08:00
icarus
bd6428d473 refactor(AgentSettings): extract modal content into separate component for better readability 2025-09-22 11:22:57 +08:00
Vaayne
d7960140dc feat(claudecode): add allowedTools to session configuration in invoke method 2025-09-22 09:55:26 +08:00
icarus
d7052b547f refactor(agents): remove unused agent entities and related code
Clean up agents store by removing deprecated AgentEntity-related code that is no longer used. This simplifies the store structure as we're moving away from redux.
2025-09-22 00:34:29 +08:00
icarus
6aaef9b7be docs: remove completed TODO comment from Sessions component 2025-09-22 00:21:45 +08:00
icarus
b246676257 chore(AgentEssentialSettings): add todo comment for future enhancements 2025-09-22 00:19:25 +08:00
icarus
0e4b1820e7 Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-22 00:16:25 +08:00
icarus
1833092998 fix(useAgent): handle fake agent id to prevent unnecessary API calls 2025-09-22 00:16:19 +08:00
GitHub Action
00717126e5 fix(i18n): Auto update translations for PR #10096 2025-09-21 16:07:26 +00:00
icarus
3816076464 refactor(i18n): reorganize translation keys and add new entries
- Move 'label' from agent type to root type section
- Add new prompt settings and type-related translations
- Update Chinese translations for consistency
2025-09-22 00:06:18 +08:00
icarus
710592b053 refactor(agents): rename useModels to useApiModels and extract model label component
Extract ModelLabel component into standalone ApiModelLabel and rename useModels hook to useApiModels for better clarity. Update all references to use the new names. This improves code organization and maintainability.
2025-09-22 00:04:15 +08:00
icarus
828c22310d feat(AgentSettings): add model selection to agent essential settings
Add model selection dropdown to agent settings and update agent model on change
2025-09-21 23:39:06 +08:00
icarus
f45b744318 feat(AgentSettings): add model selection to essential settings
- Make model prop optional in ModelAvatar component
- Ensure models array always returns an array in useModels hook
- Export SelectorProps type for reuse
- Add getProviderNameById utility function
- Introduce ModelLabel component for displaying model info
- Update AgentEssentialSettings to include model selection dropdown
2025-09-21 23:31:13 +08:00
icarus
f49d3791b6 refactor(AgentSettings): restructure settings components for better reusability
- Replace SettingsInline with more flexible SettingsItem component
- Add SettingsContainer for consistent layout
- Remove redundant styled components in favor of shared components
2025-09-21 22:41:09 +08:00
icarus
ea62294bd8 refactor(agent-settings): extract shared components and improve styling
- Move common components (AgentLabel, SettingsTitle, SettingsInline) to shared file
- Update CSS to use @layer base for better organization
- Fix agent type label translation key in AgentModal
- Add agent type label utility function
2025-09-21 22:16:15 +08:00
icarus
bfe2e87f59 feat(agent-settings): add prompt settings tab and refactor essential settings
- Introduce new AgentPromptSettings component for managing agent prompts
- Move prompt-related functionality from AgentEssentialSettings to new component
- Add avatar display to essential settings
- Improve layout structure and styling for both settings components
2025-09-21 21:27:39 +08:00
suyao
6f6944d003 chunk type 2025-09-21 20:14:05 +08:00
GitHub Action
4216ffd0da fix(i18n): Auto update translations for PR #10096 2025-09-21 09:26:30 +00:00
Vaayne
a32fad06a0 Merge remote-tracking branch 'origin/main' into feat/agents-new 2025-09-21 17:25:02 +08:00
Vaayne
1a49972583 ♻️ refactor: standardize tool management and API responses
- Rename built_in_tools field to tools for consistency
- Add type field to Tool schema (builtin/mcp/custom)
- Consolidate tool handling in BaseService with listMcpTools method
- Remove unused CreateSessionResponse and related schemas
- Clean up unused imports and dead code in session handlers
- Unify agent and session tool resolution logic
2025-09-21 17:23:04 +08:00
Vaayne
a09c52424f 💄 style: format code with yarn format 2025-09-21 16:44:54 +08:00
Vaayne
b869869e26 feat: implement comprehensive Claude Code OAuth integration and API enhancements
- Add shared Anthropic utilities package with OAuth and API key client creation
- Implement provider-specific message routing alongside existing v1 API
- Enhance authentication middleware with priority handling (API key > Bearer token)
- Add comprehensive auth middleware test suite with timing attack protection
- Update session handling and message transformation for Claude Code integration
- Improve error handling and validation across message processing pipeline
- Standardize import formatting and code structure across affected modules

This establishes the foundation for Claude Code OAuth authentication while maintaining
backward compatibility with existing API key authentication methods.
2025-09-21 16:42:46 +08:00
Vaayne
c3b2af5a15 refactor: streamline session handling and enhance message transformation 2025-09-21 00:31:04 +08:00
Vaayne
01ffd4c4ca refactor(ClaudeCodeService): remove unused anthropicService import and update oauth handling 2025-09-20 23:26:37 +08:00
Vaayne
a5d4a01ad8 feat: support claude code oauth and api key 2025-09-20 23:21:17 +08:00
icarus
4d266fddb1 fix(AgentEssentialSettings): prevent unnecessary updates when name unchanged 2025-09-20 21:37:54 +08:00
icarus
20dd4794b0 refactor(AgentSettings): remove redundant toast notification after save 2025-09-20 21:35:37 +08:00
icarus
7b96900726 refactor(agents): extract update agent logic into separate hook
Move update agent functionality from useAgent and useAgents hooks into a dedicated useUpdateAgent hook to improve code organization and maintainability
2025-09-20 21:31:44 +08:00
icarus
043a4fb5ca docs(i18n): translate essential settings to chinese 2025-09-20 21:18:21 +08:00
icarus
82e144be4c feat(i18n): add accessible paths translations and settings entry
Add translations for accessible paths section in session settings across multiple languages
Move accessible_paths object to consistent location in JSON structure
Add placeholder for essential settings in all language files
2025-09-20 21:13:00 +08:00
icarus
9b22e1671f refactor(agent-settings): replace agent modal with dedicated settings popup
Move agent editing functionality from inline modal to a dedicated settings popup component for better maintainability and separation of concerns. The new implementation provides a more structured settings interface with essential agent configuration options.
2025-09-20 21:11:58 +08:00
icarus
7999149901 style(Assistants): adjust button width and formatting for consistency 2025-09-20 20:28:26 +08:00
icarus
c70a5d63aa refactor(home/Tabs): replace redux state with local state for active tab
Simplify tab state management by using useState instead of redux
Remove unused imports and clean up useEffect dependencies
2025-09-20 20:24:24 +08:00
icarus
d1067bb6b3 refactor(home/tabs): reorganize components and implement topic/session switching
- Move Assistants and Agents components to dedicated folders
- Split TopicsTab into separate Topics and SessionsTab components
- Add activeTopicOrSession state handling in runtime store
- Update tab switching logic to support both topics and sessions
- Clean up and optimize component imports and exports
2025-09-20 20:18:31 +08:00
icarus
b43b4b581e refactor(home/Tabs): restructure tabs components and add section names
- Split AssistantsTab into separate components (Assistants and Agents)
- Add SectionName component for better UI organization
- Remove unused tabs ('agents' and 'sessions') from chat type
- Clean up imports and type definitions
2025-09-20 19:44:20 +08:00
suyao
55645a75cc merge it 2025-09-20 17:27:43 +08:00
suyao
86a2780e2c Add initial chunk emission for agent response processing
- Emit `ChunkType.LLM_RESPONSE_CREATED` event to mirror assistant behavior
- Ensure UI reflects pending state immediately during response processing
- Maintain consistency with existing stream processing callback structure
2025-09-20 16:58:24 +08:00
SuYao
36f86ff2b9 Refactor/agent align (#10276)
* Refactor agent streaming from EventEmitter to ReadableStream

Replaced EventEmitter-based agent streaming with ReadableStream for
better compatibility with AI SDK patterns. Modified
SessionMessageService to return stream/completion pair instead of event
emitter, updated HTTP handlers to use stream pumping, and added IPC
contract for renderer-side message persistence.

* Add accessible paths management to agent configuration

Move accessible paths functionality from session modal to agent modal,
add validation requiring at least one path, and update form handling to
inherit agent paths in sessions.

* Add provider_name field to model objects and improve display

- Add provider_name field to ApiModel schema and transformation logic
- Update model options to include providerName for better display
- Improve provider label fallback chain in model transformation
- Fix agent hook to use proper SWR key and conditional fetching
- Enhance option rendering with better truncation and provider display

* fix(i18n): Auto update translations for PR #10276

* Optimize chat components with memoization and shared layout

- Wrap `SessionMessages` and `SessionInputBar` in `useMemo` to prevent unnecessary re-renders
- Refactor `AgentSessionMessages` to use shared layout components and message grouping
- Extract common styled components to `shared.tsx` for reuse across message components

* Add smooth animations to SessionsTab and Sessions components

- Replace static conditional rendering with Framer Motion animations for no-agent and session states
- Animate session list items with staggered entrance and exit transitions
- Add loading spinner animation with fade effect
- Apply motion to session creation button with delayed entrance

* Add loading state with spinner and i18n support to SessionsTab

- Replace static "No active agent" message with a spinner and loading text
- Integrate react-i18next for translation of loading message
- Adjust animation timing and styling for smoother loading state transition

* Support API models with provider_name field in getModelName

- Add ApiModel type import and update function signature to accept ApiModel
- Return formatted name using provider_name field for API models
- Maintain backward compatibility for legacy models by looking up provider in store

* Simplify provider display name logic and add debug logging

- Replace complex fallback chain for provider display name with direct provider name access
- Add console.log for model debugging in getModelName function

* Extract model name from session model string

- Use split and pop to isolate the model name after the colon
- Fall back to the full model string if no colon is present
- Maintain provider and group identifiers for model object consistency

* Improve model name resolution for agent sessions

- Extract actual model ID from session model string and resolve model details
- Use resolved model name, provider, and group when available instead of defaults
- Remove redundant API model handling in getModelName function

* Set default active agent and session on load

- Automatically select first agent if none active after loading
- Automatically select first session per agent if none active after loading
- Prevent empty selection states in UI components

---------

Co-authored-by: GitHub Action <action@github.com>
2025-09-20 16:56:53 +08:00
suyao
d960a42d6e Set default active agent and session on load
- Automatically select first agent if none active after loading
- Automatically select first session per agent if none active after loading
- Prevent empty selection states in UI components
2025-09-20 16:41:15 +08:00
suyao
3ae1b3d4cb Improve model name resolution for agent sessions
- Extract actual model ID from session model string and resolve model details
- Use resolved model name, provider, and group when available instead of defaults
- Remove redundant API model handling in getModelName function
2025-09-20 16:33:56 +08:00
suyao
1c045231c8 Extract model name from session model string
- Use split and pop to isolate the model name after the colon
- Fall back to the full model string if no colon is present
- Maintain provider and group identifiers for model object consistency
2025-09-20 16:28:16 +08:00
suyao
282aa6e81a Simplify provider display name logic and add debug logging
- Replace complex fallback chain for provider display name with direct provider name access
- Add console.log for model debugging in getModelName function
2025-09-20 16:23:37 +08:00
suyao
117e390cf1 Support API models with provider_name field in getModelName
- Add ApiModel type import and update function signature to accept ApiModel
- Return formatted name using provider_name field for API models
- Maintain backward compatibility for legacy models by looking up provider in store
2025-09-20 16:05:18 +08:00
suyao
34b05a138b Add loading state with spinner and i18n support to SessionsTab
- Replace static "No active agent" message with a spinner and loading text
- Integrate react-i18next for translation of loading message
- Adjust animation timing and styling for smoother loading state transition
2025-09-20 15:58:33 +08:00
suyao
6c233fef9f Add smooth animations to SessionsTab and Sessions components
- Replace static conditional rendering with Framer Motion animations for no-agent and session states
- Animate session list items with staggered entrance and exit transitions
- Add loading spinner animation with fade effect
- Apply motion to session creation button with delayed entrance
2025-09-20 15:55:42 +08:00
suyao
1c813aa6c3 Merge branch 'refactor/agent-align' of https://github.com/CherryHQ/cherry-studio into refactor/agent-align 2025-09-20 15:52:32 +08:00
suyao
dd5592ddbb Optimize chat components with memoization and shared layout
- Wrap `SessionMessages` and `SessionInputBar` in `useMemo` to prevent unnecessary re-renders
- Refactor `AgentSessionMessages` to use shared layout components and message grouping
- Extract common styled components to `shared.tsx` for reuse across message components
2025-09-20 15:49:40 +08:00
GitHub Action
6e9d8a1747 fix(i18n): Auto update translations for PR #10276 2025-09-20 07:24:06 +00:00
suyao
cee78c6610 Add provider_name field to model objects and improve display
- Add provider_name field to ApiModel schema and transformation logic
- Update model options to include providerName for better display
- Improve provider label fallback chain in model transformation
- Fix agent hook to use proper SWR key and conditional fetching
- Enhance option rendering with better truncation and provider display
2025-09-20 15:19:11 +08:00
suyao
0b2dfbb88f Add accessible paths management to agent configuration
Move accessible paths functionality from session modal to agent modal,
add validation requiring at least one path, and update form handling to
inherit agent paths in sessions.
2025-09-20 14:53:08 +08:00
suyao
1fd44a68b0 Refactor agent streaming from EventEmitter to ReadableStream
Replaced EventEmitter-based agent streaming with ReadableStream for
better compatibility with AI SDK patterns. Modified
SessionMessageService to return stream/completion pair instead of event
emitter, updated HTTP handlers to use stream pumping, and added IPC
contract for renderer-side message persistence.
2025-09-20 13:31:29 +08:00
icarus
fcacc50fdc Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-20 00:53:55 +08:00
icarus
009b58c9c3 feat(i18n): add error message for failed session retrieval 2025-09-20 00:53:49 +08:00
icarus
77c64cf868 refactor(hooks): improve error handling in useSessions hook
- Remove redundant agentId checks as they're handled by the API client
- Add consistent error formatting using formatErrorMessageWithPrefix
- Update error messages for all session operations
2025-09-20 00:52:39 +08:00
icarus
f5acddbfeb refactor(agent): extract shared components and improve model handling
- Extract common option components to shared.tsx for reuse
- Make useModels filter parameter optional
- Update SessionModal to use real model data from API
2025-09-20 00:48:17 +08:00
icarus
ae35d689ec feat(AgentModal): add dynamic model options from API
Fetch model options from API instead of using mocked data
Display provider label for model options
2025-09-20 00:32:51 +08:00
icarus
825b5e1be4 refactor(error-handling): move error formatting functions to error utils
Consolidate error formatting functions (formatAgentServerError and formatAxiosError) into error.ts utility file to improve code organization and maintainability
2025-09-20 00:32:43 +08:00
Vaayne
17df1db120 ♻️ refactor: simplify streaming message lifecycle management
- Remove unused persistence tracking variables in message handler
- Simplify finalizeResponse logic by removing unnecessary checks
- Change 'finish' event type to 'complete' for consistency
- Add debug logging for streaming events
- Clean up dead code and improve readability
2025-09-20 00:14:02 +08:00
Vaayne
d56521260c ️ perf: add caching layer for MCP servers and providers data access
- Extract getServersFromRedux to shared utility getMCPServersFromRedux
- Implement 5-minute TTL cache for MCP servers and providers
- Reduce redundant Redux store queries in API server
- Improve response times for frequently accessed data
2025-09-20 00:13:26 +08:00
icarus
8efafc6ba9 feat(hooks): add useModels hook for fetching agent models 2025-09-19 23:51:46 +08:00
icarus
f35987a9a9 refactor(api): rename modelsPath to getModelsPath for consistency
Align method naming with other path getter methods in the class for better code maintainability and consistency
2025-09-19 23:50:04 +08:00
icarus
c7ec55c69a refactor(types): rename ApiModelsRequest to ApiModelsFilter for clarity
Update type name and related imports to better reflect its purpose as a filter type rather than a request type
2025-09-19 23:48:58 +08:00
icarus
c77d7dff78 feat(api): add models endpoint to agent client and type response
Add new models endpoint to AgentApiClient with query parameter support
Ensure type safety by adding ApiModelsResponse type and schema validation
2025-09-19 23:43:20 +08:00
Vaayne
b282e4d729 feat: implement robust AbortController for Claude Code agent streams
- Add AbortController support to agent service interface and implementations
- Enhance client disconnect detection with multiple HTTP event listeners (req.close, req.aborted, res.close)
- Implement proper abort error handling in ClaudeCodeService with 'cancelled' event type
- Add comprehensive documentation explaining SSE disconnect detection behavior
- Clean up stream interfaces by removing unused properties and simplifying event structure
- Extend timeout from 5 to 10 minutes for longer-running agent tasks
- Ensure proper resource cleanup and prevent orphaned processes on client disconnect

This enables reliable cancellation of long-running Claude Code processes when clients
disconnect unexpectedly (browser tab close, curl Ctrl+C, network issues, etc.)
2025-09-19 23:42:46 +08:00
Vaayne
c426876d0d feat(transform): refactor message handling to unify user and assistant processing 2025-09-19 22:36:19 +08:00
Vaayne
027ef17a2e feat(agents): enhance ClaudeCodeService to support MCP configurations and additional directories 2025-09-19 21:51:33 +08:00
Vaayne
f0ac74dccf feat(agents): enhance error messages for agent and session operations; update accessible paths handling 2025-09-19 20:20:20 +08:00
Vaayne
d6468f33c5 feat(agents): implement model validation for agent and session creation/updating 2025-09-19 20:20:20 +08:00
Vaayne
1515f511a1 feat(agents): refactor agent invocation to use session object and enhance error handling 2025-09-19 20:20:20 +08:00
Vaayne
1c2211aefb feat(agents): add ensurePathsExist method to validate and create accessible paths 2025-09-19 20:20:20 +08:00
Vaayne
49f9dff9da feat(models): update models filtering to use providerType and enhance API schemas 2025-09-19 20:20:19 +08:00
icarus
92ba1e4fc3 fix(SessionMessageService): stringify user message content to ensure proper formatting 2025-09-19 17:54:25 +08:00
icarus
7060aab33d fix: reverse message order and fix mutation revalidation
Reverse message display order for better UX and prevent unnecessary revalidation during message creation
2025-09-19 17:52:17 +08:00
icarus
0cce8220ce Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-19 17:46:32 +08:00
icarus
1722d9f435 feat(i18n): add error message for failed message creation
Add "create_message" error translation in multiple language files
2025-09-19 17:44:58 +08:00
icarus
078fd57eb5 fix(agent): update message id and improve content handling
- Change default message id from -1 to 77777 in useSession
- Remove schema validation for session response temporarily
- Add proper content parsing for agent session messages
2025-09-19 17:44:08 +08:00
icarus
4bd6087dc0 feat(chat): add agent session inputbar component
Implement input bar for agent sessions with message sending functionality
2025-09-19 17:39:24 +08:00
icarus
e45231376c feat(useSession): add optimistic updates for message creation
Implement optimistic UI updates when creating new messages to improve perceived performance. The changes include cloning the current session data, adding a draft message immediately, and handling rollback on error.
2025-09-19 17:39:04 +08:00
icarus
01c7e509fd feat(hooks): add createSessionMessage to useSession hook
Expose new function to create messages for agent sessions and automatically refresh session data
2025-09-19 17:01:47 +08:00
icarus
5ddf9683b4 feat(chat): add session messages view and active state tracking
Implement agent session messages display component and track active topic/session state
Add AgentSessionMessages component and integrate with chat view
Update topic and session selection to set active state in store
2025-09-19 16:39:02 +08:00
Vaayne
d91df12dbc feat(models): refactor models service to use new API models schema and types 2025-09-19 16:36:11 +08:00
icarus
64e3de9ada feat(chat): add activeTopicOrSession state to track current view
Add new state field and action to track whether the user is viewing topics or sessions in the chat interface. This enables proper UI state management when switching between views.
2025-09-19 16:27:50 +08:00
Vaayne
2cf2f04a70 feat(chat): enhance chat completion error handling and streaming support
feat(messages): improve message validation and add streaming support
feat(tests): add HTTP tests for chat and message endpoints
2025-09-19 16:16:33 +08:00
Vaayne
73380d76df feat(models): enhance models endpoint with filtering and pagination support 2025-09-19 16:16:33 +08:00
Vaayne
38076babcf feat(messages): add messages route and service for handling Anthropic messages 2025-09-19 16:16:33 +08:00
icarus
00cc410dcc refactor(SessionItem): remove confirmation modal for delete action
Simplify delete flow by removing the confirmation modal and directly calling onDelete
2025-09-19 15:59:18 +08:00
icarus
7fc676bbc3 fix(useSession): provide default empty array for messages when undefined
Make messages field optional in GetAgentSessionResponseSchema to match actual API behavior and prevent potential undefined access
2025-09-19 15:56:09 +08:00
icarus
798126d39c feat(session): add session modal component to session item
Implement session modal for editing session details, using existing disclosure hooks
2025-09-19 15:46:52 +08:00
icarus
874d74cf6e feat(chat): add tab state management to redux store
Move tab state from component local state to redux store for better state management across components
2025-09-19 15:43:39 +08:00
icarus
d73834e7f6 feat(i18n): add session add/edit translation keys
Add new translation keys for session add/edit functionality in multiple languages
2025-09-19 15:28:11 +08:00
icarus
cb3afaceab refactor(agent): consolidate agent update logic into useAgents hook 2025-09-19 15:27:23 +08:00
icarus
fc0ba5d0d5 feat(hooks): add useSession hook for managing agent sessions 2025-09-19 15:27:10 +08:00
icarus
7ce4fc50ea refactor(hooks): remove unused useUpdateAgent hook 2025-09-19 15:24:39 +08:00
icarus
b5ef8a93ca refactor(useAgent): simplify mutate call in agent update
The previous implementation unnecessarily spread the previous state when only the result is needed. This simplifies the mutation logic while maintaining the same behavior.
2025-09-19 15:24:33 +08:00
icarus
8ead4e9c0f feat(sessions): add session creation modal and improve session item styling
- Implement SessionModal component for creating/editing sessions
- Replace Button wrapper with fragment in SessionItem for cleaner styling
- Add translation support and proper form handling for session creation
2025-09-19 15:21:27 +08:00
icarus
432d84cda5 refactor(sessions): simplify session update API by using form object
Remove redundant sessionId parameter from updateSession methods since it's already included in the UpdateSessionForm. This makes the API more consistent and reduces potential for mismatched IDs.
2025-09-19 15:08:53 +08:00
icarus
d3378dcf78 refactor(types): use inferred type for CreateSessionRequest 2025-09-19 14:56:50 +08:00
icarus
f0724af2aa refactor(agent-modal): move AgentModal component to agent subdirectory
Restructure the component organization by moving AgentModal.tsx into a dedicated agent subdirectory under Popups. This improves maintainability by grouping related agent components together.

Update all import paths to reflect the new location. The component functionality remains unchanged.
2025-09-19 14:55:26 +08:00
icarus
f127150ea1 feat(sessions): implement session management ui and state
- Rename Container to ButtonContainer for consistency
- Add activeSessionId state to track active sessions per agent
- Implement Sessions and SessionItem components with loading state
- Add session selection and deletion functionality
2025-09-19 14:54:04 +08:00
icarus
b3ef6d4534 feat(i18n): add error messages for session operations
Add error messages for session deletion and update failures in all supported languages. Also include a generic delete failure message.
2025-09-19 14:09:05 +08:00
icarus
1ce791d517 feat(AgentsTab): add loading spinner for agents list
Show spinner while agents are loading to improve user experience
2025-09-19 14:07:56 +08:00
icarus
3d561ad8e3 refactor(sessions): extract sessions component and update hook to use agentId
Move sessions rendering logic to a separate component and modify useSessions hook to work with agentId instead of full agent entity. This improves code organization and simplifies the hook interface.
2025-09-19 14:07:23 +08:00
icarus
14509d1077 feat(hooks): add useAgent hook for managing agent state and updates 2025-09-19 14:07:03 +08:00
icarus
a424e3a039 feat(agents): add success toast notifications for agent operations 2025-09-19 13:32:16 +08:00
icarus
eaa5ec5545 refactor(agents): remove unused useRemoveAgent hook and use deleteAgent from useAgents 2025-09-19 13:30:50 +08:00
icarus
5850e5da66 refactor(AgentItem): simplify component structure and remove unused logger
- Remove Button wrapper from AgentLabel component
- Replace div container with Button component for better semantics
- Clean up unused logger service and related click handler
2025-09-19 13:28:36 +08:00
icarus
eb3ff6f570 fix(agents): convert null values to undefined in database responses
Ensure type consistency by converting null values from database to undefined as specified in type definitions
2025-09-19 13:14:20 +08:00
icarus
ae9c78e643 Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-19 12:58:21 +08:00
icarus
445528aff7 refactor(agent): replace interface with zod schema for message request
Add createMessage method to AgentApiClient to handle posting messages to sessions
2025-09-19 12:58:14 +08:00
Vaayne
d13c25444c feat(agents, sessions): enhance agent and session schemas with detailed properties and CRUD API documentation 2025-09-19 12:56:20 +08:00
Vaayne
5386716ebe feat(session messages): enhance session message persistence with improved error handling and completion notifications 2025-09-19 12:56:20 +08:00
Vaayne
da3cd62486 feat(sessions): update session creation and update requests with new session details 2025-09-19 12:56:20 +08:00
Vaayne
d8b47e30c4 feat(session messages): implement user message persistence and retrieve last agent session ID 2025-09-19 12:56:20 +08:00
icarus
1c19e529ac Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-19 12:51:08 +08:00
Vaayne
514b60f704 feat(agents, sessions): implement replace functionality for agent and session updates 2025-09-19 11:13:05 +08:00
Vaayne
df1d4cd62b refactor(sessions): update getSession and related methods to include agentId parameter 2025-09-19 10:41:26 +08:00
Vaayne
4839b91cef chore(docs): remove session tracking protocol from AI Assistant Guide 2025-09-19 10:27:09 +08:00
Vaayne
5048d6987d refactor(validators): migrate validation logic to Zod for agents and sessions 2025-09-19 10:27:02 +08:00
icarus
809736dd33 feat(sessions): add update session functionality
Introduce UpdateSessionResponse type and schema to support session updates. Implement update session methods across client, service, and handler layers to enable session modifications.
2025-09-18 22:58:49 +08:00
icarus
369cc37071 feat(sessions): add delete session functionality to agent api and hook
Implement session deletion by adding deleteSession method to AgentApiClient and corresponding hook in useSessions. This enables removing sessions from the UI with proper error handling and cache invalidation.
2025-09-18 22:52:46 +08:00
icarus
d0b64dabc2 fix(agents): correct agent update and retrieval logic
Fix mutation logic to use result.id instead of form.id for consistency
Make getAgent async and update cache with fetched agent data
2025-09-18 22:51:02 +08:00
icarus
02d2838424 fix(agent): add response validation for ID mismatches
Add checks to ensure response IDs match expected values in agent API calls
2025-09-18 22:50:05 +08:00
icarus
4c4039283f fix(useSessions): correct session fetching logic to use API call
Previously the getSession hook was only searching local data. Now it properly fetches from the API and updates the cache. This ensures data consistency when sessions are modified elsewhere.
2025-09-18 22:46:24 +08:00
icarus
77df6fd58e feat(sessions): add getSession method to retrieve specific session
Implement session retrieval functionality in both hook and API client to enable fetching individual sessions by ID
2025-09-18 22:37:02 +08:00
icarus
100801821f fix(agents): update agents list response structure to match API
Align frontend and backend types for agents list response. The API now returns paginated data with limit/offset and renamed 'agents' field to 'data' for consistency. Update related type definitions and usage across the codebase.
2025-09-18 22:26:54 +08:00
icarus
2201ebbb88 feat(i18n): add error messages for agent and session operations
Add error messages for agent deletion, update, and session creation operations
Add "no response" error message for all supported languages
2025-09-18 22:21:27 +08:00
icarus
9810f01330 feat(sessions): add create session functionality to agent api and hook
Implement session creation in the agent API client and expose it through the useSessions hook. The hook now provides a createSession method that updates the session list upon successful creation.
2025-09-18 22:19:52 +08:00
icarus
7b428be93d feat(types): add session form interfaces for agent operations
Add BaseSessionForm, CreateSessionForm and UpdateSessionForm interfaces to support session management functionality
2025-09-18 22:10:53 +08:00
icarus
a4c2ed5328 fix(api): update error handling to match new error structure
The AgentServerError schema was updated to nest error properties under an 'error' object. This commit aligns the error formatting function with the new schema structure.
2025-09-18 22:02:42 +08:00
icarus
934cc0dd33 refactor(useAgents): simplify agent data structure and mutations
Remove unnecessary nesting of agents array in SWR response and simplify mutation logic to work directly with the array
2025-09-18 22:00:25 +08:00
icarus
da61500e34 feat(hooks): add useSessions hook for agent session management 2025-09-18 21:57:18 +08:00
icarus
db2042800b feat(agent): add listSessions method to AgentApiClient
Implement session listing functionality for agents by adding the listSessions method. This enables retrieving all sessions associated with a specific agent.
2025-09-18 21:50:14 +08:00
icarus
08772741e6 feat(agent-sessions): add schema and type for listing agent sessions
Add ListAgentSessionsResponseSchema and type to support paginated session listing
2025-09-18 21:49:02 +08:00
icarus
f5f542911f feat(sessions): add CreateSessionResponse type for better type safety
Introduce CreateSessionResponse type and schema to clearly define the return type of session creation operations. This improves type safety and consistency across the codebase when handling session responses.
2025-09-18 21:43:06 +08:00
icarus
3b5b1986e6 feat(hooks): add getAgent function to useAgents hook 2025-09-18 21:34:25 +08:00
icarus
3b0995c8ef feat(agents): add deleteAgent hook to useAgents
Implement agent deletion functionality with optimistic updates and error handling
2025-09-18 21:22:20 +08:00
icarus
34c95ca787 feat(agents): add update agent functionality and error message
Add updateAgent method to useAgents hook and update agent API client
2025-09-18 21:20:58 +08:00
icarus
a4c2a1d435 feat(i18n): add new translation keys for agent errors and session management
Add "failed" error message for agent addition and implement session-related translations including delete confirmation and labels
2025-09-18 20:49:04 +08:00
icarus
e4f0743e2f fix(api): replace Axios constructor with axios.create for better defaults
Using axios.create() provides better default configuration and error handling compared to the Axios constructor
2025-09-18 20:47:53 +08:00
icarus
7632efda88 fix(api): handle ZodError in processError and formatErrorMessage
Add explicit handling of ZodError in processError to return the error directly and in formatErrorMessage to use formatZodError for better error reporting
2025-09-18 20:40:30 +08:00
icarus
ab90eb2aab refactor(AgentModal): replace useAddAgent with useAgents hook 2025-09-18 20:29:04 +08:00
icarus
4c5bed0b1f fix(agents): add http protocol to agent client base url 2025-09-18 20:28:08 +08:00
icarus
302331043a refactor(agent): add error logging in agent api client
Use logger service to log errors when processing API requests
2025-09-18 20:25:40 +08:00
icarus
09f5e7af8c feat(agents): implement add agent functionality in useAgents hook
Add createAgent method to useAgents hook and remove unused useAddAgent hook
Use formatErrorMessageWithPrefix for better error handling
2025-09-18 20:25:28 +08:00
icarus
664304241a feat(i18n): make base locale configurable via env var
Add support for BASE_LOCALE environment variable to override default locale
Add file existence check for base locale file in auto-translate script
Update npm scripts to load .env for i18n commands
2025-09-18 19:31:24 +08:00
icarus
27f98b02a6 feat(sessions): add sessions tab with basic functionality and translations
- Create new SessionsTab component with mock data
- Add session item component with context menu for edit/delete
- Include session tab in main navigation
- Add English translations for session-related strings
2025-09-18 19:26:25 +08:00
icarus
af6a3c87d6 fix(AgentItem): add missing onPress dependency to useCallback
Ensure the callback is updated when onPress prop changes to avoid stale closures
2025-09-18 19:17:10 +08:00
icarus
d1819274bb Revert "feat(agent): add name field to AgentSessionEntitySchema"
This reverts commit 8058ed21b3.
2025-09-18 19:13:24 +08:00
icarus
8058ed21b3 feat(agent): add name field to AgentSessionEntitySchema
Add name field to agent session schema to support session naming functionality
2025-09-18 19:11:52 +08:00
icarus
eaf302bb40 Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-18 19:04:14 +08:00
icarus
3405b7e429 refactor(ui): rename agents to assistantPresets for consistency
Update route paths, i18n keys and tab identifiers to use 'assistantPresets' instead of 'agents'
Add new agents tab component while maintaining backward compatibility
2025-09-18 19:04:05 +08:00
icarus
2fc1df8793 refactor(ui): remove unused UI elements and commented code
clean up UI by removing unused text spans and commented out code
remove unused timer functionality from AgentModal
2025-09-18 19:00:41 +08:00
icarus
ec82eb2881 build: add @types alias to electron vite config 2025-09-18 18:52:36 +08:00
icarus
1c978e0684 feat(agents): add agent selection functionality
- Replace onTagClick with onPress handler in AgentItem
- Add active agent state management in AgentsTab
- Wrap AgentItem content in Button for better interaction
2025-09-18 18:47:37 +08:00
icarus
e938e1572c feat(chat): add activeAgentId to track current agent state
Add activeAgentId field to chat state to track which agent is currently active. This enables UI to reflect the active agent state and handle agent-specific interactions.
2025-09-18 18:43:10 +08:00
icarus
9a7681c5c8 refactor(agent): update agent form types and mutation hooks
- Add proper type definitions for AddAgentForm and UpdateAgentForm
- Split agent mutation hooks into separate files
- Update AgentModal to use new form types and hooks
- Remove redundant fields from form submissions
2025-09-18 18:39:02 +08:00
icarus
259f2157f6 refactor(agent): split AgentForm into BaseAgentForm and specific types
Improve type safety by separating AgentForm into BaseAgentForm for shared fields and specific types for add/update operations. This better reflects the actual usage patterns in the API client and modal components.
2025-09-18 18:21:52 +08:00
icarus
21ce139df0 refactor(agents): replace unimplemented mutation with simple function
Replace the placeholder mutation implementation in useUpdateAgent hook with a simpler function that shows a toast notification. This removes the unnecessary query client usage for an unimplemented feature.
2025-09-18 18:10:53 +08:00
icarus
71536d6ef5 refactor(agents): replace useMutation with simple function in useAddAgent
The mutation logic was removed and replaced with a simple function that shows a toast message. This is a temporary solution until the actual API implementation is ready.
2025-09-18 18:09:58 +08:00
icarus
ef1a035701 feat: add AgentsTab component for managing agents 2025-09-18 18:08:59 +08:00
icarus
2b76c326ee refactor(agents): replace useMutation with simpler implementation in useRemoveAgent 2025-09-18 18:08:45 +08:00
icarus
64ee5c528b fix(useAgents): use right agents data 2025-09-18 18:08:40 +08:00
icarus
136d343c18 refactor(hooks): replace redux with swr in useAgents hook
Simplify agents management by using SWR for data fetching instead of redux store operations
2025-09-18 18:05:55 +08:00
icarus
0b1b9a913f feat(hooks): add useAgentClient hook for agent API client initialization 2025-09-18 18:02:05 +08:00
icarus
cb0833a915 refactor(api): centralize agent and session paths for better maintainability
Add path builder methods to avoid hardcoding URLs and improve consistency
2025-09-18 17:58:53 +08:00
Vaayne
984c28d4be refactor(SessionMessageService): remove unused PermissionMode import 2025-09-18 17:51:45 +08:00
Vaayne
49add96dc0 feat(database): add agent_session_id to session_messages table and update related services 2025-09-18 17:46:05 +08:00
icarus
db58762a13 refactor(AssistantsTab): remove agent-related code and imports 2025-09-18 17:40:12 +08:00
icarus
6e89d0037f Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-18 17:12:10 +08:00
icarus
e1ab17387c build: add swr dependency for data fetching 2025-09-18 17:11:56 +08:00
icarus
54de2341bd refactor(agents): remove draggable functionality and simplify agent list rendering
Remove unused agent management hooks and replace DraggableList with simple map
Add cursor-pointer style to AgentItem for better UX
2025-09-18 16:24:27 +08:00
beyondkmp
b131f0c48c pack optimization 2025-09-18 15:25:16 +08:00
Vaayne
9e4b792fc3 🐛 fix: resolve duplicate migration key '156' to '157' 2025-09-18 14:54:45 +08:00
Vaayne
7abd5da57d ♻️ refactor: replace ClaudeCodeService child process with SDK query
- Replace process spawning with @anthropic-ai/claude-code SDK query function
- Remove complex process management, stdout/stderr parsing, and JSON buffering
- Directly iterate over typed SDKMessages from AsyncGenerator
- Simplify error handling and completion logic
- Maintain full compatibility with existing SessionMessageService interface
- Eliminate ~130 lines of process management code
- Improve reliability by removing JSON parsing edge cases
2025-09-18 14:54:45 +08:00
icarus
be7399b3c4 Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-18 14:49:18 +08:00
icarus
8d92b515ab feat(agent): return updated agent data from updateAgent method
Add response parsing and return type to updateAgent to provide updated agent data to callers
2025-09-18 14:35:57 +08:00
icarus
524098d6d3 feat(agent): add error processing utility and update agent method
Introduce processError utility to handle axios errors consistently
Add updateAgent method to support partial updates of agent data
2025-09-18 14:34:05 +08:00
icarus
42fa2d94be feat(api): add formatAxiosError utility for handling axios errors 2025-09-18 14:33:45 +08:00
icarus
a65b30f3a1 chore: update vscode settings for i18n configuration
Remove display language setting and clean up comments
2025-09-18 14:33:10 +08:00
icarus
f1991b356b feat(agent): add get and delete agent methods with error handling
Implement getAgent and deleteAgent methods in AgentClient with proper error handling
Add formatAgentServerError utility for consistent error messages
2025-09-18 14:20:48 +08:00
beyondkmp
352c23180a add patch for sdk to run cli in electron 2025-09-18 14:11:05 +08:00
icarus
825c376c5c feat(agent): add create agent endpoint to agent client 2025-09-18 14:08:31 +08:00
icarus
231a923c9d feat(types): add AgentForm type and move from component to types file
Centralize the AgentForm type definition in the types file for better maintainability and reuse across components
2025-09-18 14:03:10 +08:00
icarus
dbf01652f8 feat(agent): add avatar support for agent items
Implement getAgentAvatar function to provide avatar images based on agent type. Update AgentItem component to display agent-specific avatars instead of generic ones.
2025-09-18 13:59:37 +08:00
icarus
842a6cb178 style(AssistantsTab): reorder tailwind classes for consistency 2025-09-18 13:54:59 +08:00
icarus
d56c526709 feat(api): add AgentClient class for listing agents
Implement a new API client class to handle agent listing operations with proper error handling and validation
2025-09-18 13:48:57 +08:00
icarus
70a68bef27 Revert "feat(types): add DeleteAgentResponse type and update AgentService"
This reverts commit 219844cb74.
2025-09-18 13:31:23 +08:00
icarus
f9b49ffde6 Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-18 13:28:36 +08:00
icarus
a264fd42e4 feat(types): add AgentServerError schema for error handling 2025-09-18 13:26:51 +08:00
icarus
219844cb74 feat(types): add DeleteAgentResponse type and update AgentService
Update AgentService to use DeleteAgentResponse type instead of boolean for better type safety
2025-09-18 13:24:00 +08:00
icarus
230205d210 feat(types): add UpdateAgentResponse type and schema
Update agent service to use new response type for consistency
2025-09-18 13:21:37 +08:00
icarus
f9fb0f9125 feat(agent): add ListAgentsResponse type and update service
Add ListAgentsResponse schema and type to handle agent listing responses
Update AgentService to use the new type for listAgents method
2025-09-18 13:19:57 +08:00
icarus
0f777e357d refactor(types): convert GetAgentSessionResponse interface to zod schema
Improve type safety by using zod schema definition and inference instead of manual interface
2025-09-18 13:17:32 +08:00
icarus
5c578c191b refactor(types): convert AgentSessionMessageEntity interface to zod schema
Replace interface with zod schema for better type safety and validation
2025-09-18 13:15:58 +08:00
icarus
7a4952f773 refactor(types): convert AgentSessionEntity interface to zod schema
Use zod schema for better type safety and validation capabilities
2025-09-18 13:01:57 +08:00
icarus
71a1daddef refactor(types): reorder CreateAgentResponse and its schema
Place schema definition before type alias for better readability and consistency
2025-09-18 13:00:41 +08:00
icarus
0a82955e91 refactor(types): replace GetAgentResponse interface with zod schema
Use zod schema for better type safety and validation
2025-09-18 12:59:49 +08:00
icarus
62d2da3815 refactor(types): convert Tool interface to zod schema
Use zod schema for better type safety and validation capabilities
2025-09-18 12:58:56 +08:00
icarus
84aab66aa6 refactor(types): add CreateAgentResponseSchema for consistency 2025-09-18 12:56:29 +08:00
icarus
2d0d599ac8 refactor(types): convert AgentEntity interface to zod schema
Use zod schema for better runtime validation and type safety
2025-09-18 12:55:01 +08:00
icarus
dca6be45b0 refactor(types): replace hardcoded agent type check with zod schema
Use zod schema validation for type safety and maintainability instead of manual array checking
2025-09-18 12:52:58 +08:00
icarus
5a71807cc9 feat(types): add CreateAgentResponse type and update AgentService return type 2025-09-18 12:50:42 +08:00
icarus
0d0ab4dcf5 refactor(types): convert AgentBase interface to zod schema
This change improves type safety and validation by replacing the TypeScript interface with a zod schema definition. The schema provides runtime validation while maintaining the same type inference capabilities.
2025-09-18 12:49:17 +08:00
icarus
ac3da51890 refactor(types): replace AgentConfiguration interface with zod schema
Use zod schema for better type safety and validation capabilities
2025-09-18 12:46:45 +08:00
icarus
9ea361f7e8 refactor(types): migrate PermissionMode to zod schema for type safety 2025-09-18 12:45:00 +08:00
icarus
cc6160892a refactor(types): reorganize agent type interfaces for better clarity
Move API DTO interfaces to a dedicated section at the bottom of the file to improve code organization and maintainability
2025-09-18 12:42:01 +08:00
Vaayne
49eed449c3 refactor: Remove outdated validation and planning documents for agents service 2025-09-18 12:02:11 +08:00
Vaayne
8ada7ffaf6 Merge remote-tracking branch 'origin/main' into feat/agents-new 2025-09-18 11:51:34 +08:00
Vaayne
e7c37231e0 feat: Enhance message handling with user message persistence and improved stream management 2025-09-18 00:30:43 +08:00
Vaayne
c196a02c95 feat: Implement database migration system and update agent/session handling 2025-09-17 14:59:08 +08:00
Vaayne
d1ff8591a6 refactor: Rename message stream handler and update session creation logic 2025-09-17 14:10:10 +08:00
LiuVaayne
219d162e1a feat: Add automatic database migration system for agents service (#10215)
* feat: Add automatic database migration system for agents service

- Add migrations tracking schema with version, tag, and timestamp
- Implement MigrationService to automatically run pending migrations
- Integrate migration check into BaseService initialization
- Read migration files from drizzle/ directory and journal.json
- Track applied migrations to prevent re-execution
- Ensure database is always at latest version on service startup

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>

* refactor: Improve migration logging and enhance database path configuration

* chore: harden migration bootstrap flow

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Happy <yesreply@happy.engineering>
2025-09-17 12:08:59 +08:00
Vaayne
669f60273c rewrite agents schema and types 2025-09-16 23:55:31 +08:00
Vaayne
697f7d1946 refactor: Update session tracking documentation for clarity and consistency 2025-09-16 22:06:41 +08:00
Vaayne
e4d04f8346 refactor: Remove unused variable linting directive in useUpdateAgent hook 2025-09-16 18:13:37 +08:00
Vaayne
c37af25525 Merge remote-tracking branch 'origin/main' into feat/agents-new 2025-09-16 18:08:14 +08:00
Vaayne
ea90c6c9cb feat: Enhance message handling by adding raw message metadata to assistant, stream, system, and result handlers 2025-09-16 17:57:40 +08:00
Vaayne
58dbb514e0 feat: Implement Claude Code service with streaming support and tool integration
- Added `aisdk-stream-protocel.md` to document text and data stream protocols.
- Created `ClaudeCodeService` for invoking and streaming responses from the Claude Code CLI.
- Introduced built-in tools for Claude Code, including Bash, Edit, and WebFetch.
- Developed transformation functions to convert Claude Code messages to AI SDK format.
- Enhanced OCR utility with delayed loading of the Sharp module.
- Updated agent types and session message structures to accommodate new features.
- Modified API tests to reflect changes in session creation and message streaming.
- Upgraded `uuid` package to version 13.0.0 for improved UUID generation.
2025-09-16 15:12:03 +08:00
Vaayne
a8e2df6bed feat: add electron-reload for development auto-restart
- Install electron-reload package for automatic app reloading during development
- Configure electron-reload in main process with development-only activation
- Enable automatic restart when source files change during yarn dev
- Use hardResetMethod: 'exit' for clean app restarts
2025-09-15 21:25:42 +08:00
Vaayne
2f74becb31 feat(dependencies): add @anthropic-ai/claude-code package for enhanced functionality 2025-09-15 19:59:47 +08:00
Vaayne
b31ac74f96 refactor: remove obsolete claude-code files and update logger imports 2025-09-15 19:59:15 +08:00
Vaayne
54b4e6a80b feat(agents): implement Drizzle ORM for database management and schema synchronization 2025-09-15 12:01:29 +08:00
Vaayne
079d2c3cb3 feat(docs): update CLAUDE.md to enhance AI assistant guidelines and add session tracking details 2025-09-15 11:34:19 +08:00
Vaayne
911f9d8bc9 feat(agents): update README for migration commands and remove obsolete database module documentation 2025-09-15 09:39:47 +08:00
Vaayne
f90bda861f feat(agents): add automatic database schema synchronization
- Add schemaSyncer.ts with Drizzle Kit push integration
- Integrate auto schema sync into BaseService.initialize()
- Database schema now automatically updates on agent service startup
- Users no longer need manual migration commands
- Ensures schema consistency across app updates

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
2025-09-14 23:07:54 +08:00
Vaayne
71ed94de31 docs: streamline CLAUDE.md and add session tracking
- Reduce file size by 53% while keeping essential info
- Add session tracking requirements for plan mode
- Add Must Follow Rules section with conditional ast-grep usage
- Consolidate architecture to multi-file concepts only

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
2025-09-14 22:30:04 +08:00
GitHub Action
dc16cf2aa7 fix(i18n): Auto update translations for PR #10096 2025-09-14 09:12:20 +00:00
Vaayne
be12898b7b feat(claude-code): initialize project with Bun setup, including configuration files and example code 2025-09-14 17:09:37 +08:00
Vaayne
3fc92e093b feat(sessions): add session message creation endpoint and update session details 2025-09-14 17:09:32 +08:00
Vaayne
b6187ad637 feat(sessions): include session messages in session retrieval response 2025-09-14 17:09:19 +08:00
Vaayne
ca8ac9911e feat(i18n): add translations for agent and assistant features in multiple languages 2025-09-14 16:31:52 +08:00
Vaayne
95a1e210b6 Refactor: Remove sessions route and related validation logic
- Deleted the sessions route file, consolidating session management logic.
- Removed validation middleware and error handling for session operations.
- Updated the SessionMessageService to improve query formatting for retrieving session messages.
2025-09-14 16:31:15 +08:00
icarus
b55f419a95 Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-14 12:58:21 +08:00
icarus
8953961a51 feat(i18n): add plural forms for agent and assistant labels
Add singular and plural forms for "agent" and "assistant" labels in both English and Chinese locales
Display plural labels in AssistantsTab component
2025-09-14 12:53:57 +08:00
Vaayne
8836663c35 🧪 test: add HTTP test files for agents and sessions APIs
- Add agents.http with comprehensive API endpoint tests
- Add sessions.http for session management testing
- Include authentication setup and request examples
- Support testing of CRUD operations for both agents and sessions

These files enable easy API testing and validation during development.
2025-09-14 10:17:45 +08:00
Vaayne
aaba77c360 feat: add comprehensive PUT/PATCH support for agents and sessions APIs
- Add PATCH method to agents API for partial updates alongside existing PUT
- Add PUT method to sessions API for complete replacement alongside existing PATCH
- Update API documentation with clear PUT vs PATCH usage examples
- Refactor session status updates to use standard PATCH endpoint
- Ensure both methods use same validation middleware for consistency
- Add comprehensive Swagger documentation for new endpoints

This provides REST-compliant update operations where:
- PUT: Complete resource replacement (idempotent)
- PATCH: Partial resource updates (only specified fields)

Both agents and sessions now support flexible update patterns for different use cases.
2025-09-14 10:17:45 +08:00
icarus
532bad8eb7 refactor(agents): migrate agent hooks to react-query and reorganize structure
- Replace redux-based agent management with react-query hooks
- Move agent-related hooks to dedicated agents directory
- Add useAddAgent, useRemoveAgent, and useUpdateAgent hooks
- Update imports to reflect new hook locations
- Keep redux store temporarily for backward compatibility
2025-09-14 09:51:00 +08:00
icarus
e5b43c8176 Merge branch 'feat/agents-new' of github.com:CherryHQ/cherry-studio into feat/agents-new 2025-09-14 09:21:18 +08:00
icarus
5f9c2d7f6a feat(agents): add edit functionality and update translations
- Refactor AddAgentModal into AgentModal to support both add and edit operations
- Add edit button to AgentItem with corresponding modal functionality
- Update translations for edit and update success messages
2025-09-14 09:16:04 +08:00
Vaayne
568257e7b6 docs(agents): add comprehensive UI integration guide for Agent API
- Document migration from Redux to database-backed API architecture
- Provide complete API reference for agents, sessions, and messages
- Include TypeScript interfaces and practical implementation examples
- Cover message streaming integration with AI SDK compatibility
- Add error handling patterns and best practices
- Include step-by-step migration guide from existing Redux implementation

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
2025-09-14 08:25:51 +08:00
icarus
df31629c5f refactor(AgentItem): replace antd dropdown with custom context menu component
The antd dropdown component was replaced with a custom context menu implementation to improve consistency with the application's UI components and remove dependency on antd. The functionality remains the same but is now implemented using the custom context menu component.
2025-09-14 07:24:57 +08:00
icarus
e6dc8619d9 feat(ui): add context menu component using radix-ui
Implement a comprehensive context menu component with submenus, checkboxes, radio items, and separators. The component is built using @radix-ui/react-context-menu and includes proper styling and accessibility features.

Add required dependencies and update yarn.lock accordingly.
2025-09-14 07:17:53 +08:00
icarus
9a71a01b66 feat(agents): add agent management with delete confirmation
- Add agent deletion confirmation dialog with translations
- Implement agent list display and drag-and-drop functionality
- Include avatar support for agent types
- Add success message for agent deletion
2025-09-14 06:43:24 +08:00
icarus
941a6666e6 feat(agents): implement add agent functionality and migration
- Add migration for new agents structure (version 155)
- Enable addAgent call in AddAgentModal
- Update dependencies array with addAgent
- Replace TODO comment with FIXME for model type issue
2025-09-14 05:59:08 +08:00
icarus
1bf63865a8 Merge branch 'main' into feat/agents-new 2025-09-14 05:57:24 +08:00
icarus
ba41d8021f docs(AddAgentModal): add comment explaining modal button pattern
Add explanatory comment for combining Button and Modal components in Hero UI pattern to clarify focus management requirements
2025-09-14 04:44:53 +08:00
icarus
1e919a908f refactor(agent-popup): replace AddAgentPopup with AddAgentModal component
- Remove deprecated AddAgentPopup implementation
- Implement new AddAgentModal component with improved UI using Button component
- Update related imports and usage in AssistantsTab
- Clean up unused styles and code
2025-09-14 04:39:14 +08:00
icarus
702612e3f9 feat(agent): implement AddAgentPopup
- Add isAgentType function to validate agent type strings
- Update i18n files with new agent type validation messages
- Add common validation error messages and success notifications
2025-09-14 03:59:21 +08:00
icarus
fa380619ce chore: update vscode i18n settings and comments
Clean up i18n-related settings in vscode config by commenting out display language and fixing comment alignment
2025-09-14 03:56:02 +08:00
icarus
a30b2e2cb2 refactor(utils): move getClaudeSupportedProviders to utils/provider
Improve code organization by moving provider-related utility function to dedicated utils file
2025-09-14 03:18:44 +08:00
icarus
ae0cee9ef4 style: change outline property to outline-style for better clarity 2025-09-14 01:50:38 +08:00
icarus
dc9fb381f7 feat(agent): implement add agent popup functionality
add new AddAgentPopup component with type selection
move agent-related translations to dedicated section
update UI to use new popup instead of placeholder toast
2025-09-14 01:39:35 +08:00
icarus
943fccf655 refactor(useAgents): simplify addAgent_ by accepting complete agent entity 2025-09-14 00:15:45 +08:00
icarus
e0d2d44f35 feat(config): add default agent configuration constants
Add DEFAULT_AGENT_CONFIG and DEFAULT_CLAUDE_CODE_CONFIG constants to define base agent configurations. These will serve as templates for future agent configurations.
2025-09-14 00:13:22 +08:00
icarus
5a6413f356 feat(hooks): add useAgents hook for managing agent state
Implement a custom hook to handle agent CRUD operations in the store
2025-09-14 00:12:50 +08:00
icarus
f3ef4c77f5 feat(agents): add CRUD operations for agents in store
Add setAgents, addAgent, removeAgent and updateAgent actions to manage agents in the store. The updateAgent action uses lodash's mergeWith to handle array references properly and includes error logging when agent is not found.
2025-09-14 00:00:07 +08:00
icarus
751e391db6 refactor(assistant-presets): rename agents to assistant presets and update related components
- Rename agents to assistant presets across the codebase
- Update components, hooks, and pages to reflect the new naming
- Add new components for managing assistant presets
- Improve localization and grouping of presets
- Maintain existing functionality while updating the UI
2025-09-13 23:16:22 +08:00
icarus
3e04c9493f refactor(agents): rename agents to presets and add new agents array
The old 'agents' array was actually storing presets, so it's renamed for clarity. Added new 'agentsNew' array for actual agent entities in preparation for autonomous agent feature.
2025-09-13 22:52:10 +08:00
icarus
6b0a1a42ad refactor(types): rename Agent type to AssistantPreset for clarity
The type was renamed to better reflect its purpose as a preset configuration for assistants rather than representing an active agent. This change improves code readability and maintainability by using more accurate terminology throughout the codebase.
2025-09-13 22:43:26 +08:00
icarus
ee82b23886 feat(chat): add agent creation button with placeholder implementation
Add a new button for creating agents in the chat interface. The button is currently a placeholder with a "Not implemented" toast message. Includes necessary i18n translations and component props.
2025-09-13 21:49:24 +08:00
Vaayne
0d2dc2c257 🏗️ refactor: migrate agents service from custom migrations to Drizzle ORM
- Replace custom migration system with modern Drizzle ORM implementation
- Add drizzle-orm and drizzle-kit dependencies for type-safe database operations
- Refactor BaseService to use Drizzle client with full type safety
- Create schema definitions in /database/schema/ using Drizzle patterns
- Remove legacy migration files, queries, and migrator classes
- Add comprehensive documentation for new Drizzle-based architecture
- Maintain backward compatibility in service layer APIs
- Simplify database operations with modern ORM patterns

This migration eliminates custom SQL generation in favor of a proven,
type-safe ORM solution that provides better developer experience and
maintainability.
2025-09-13 19:51:16 +08:00
Vaayne
c785be82dd ♻️ refactor: rename SessionLog to SessionMessage for semantic clarity
- Rename SessionLogEntity → SessionMessageEntity type definition
- Rename SessionLogService → SessionMessageService with all methods
- Rename API routes /logs → /messages for better REST semantics
- Update database queries and service layer naming
- Update all Swagger documentation and validation middleware
- Maintain backward compatibility in database schema

This improves code readability by using more accurate terminology
for conversational message data rather than generic "log" naming.
2025-09-13 12:06:02 +08:00
Vaayne
a4bb82a02d 📝 docs: update validation and refactoring documentation for agents service 2025-09-12 18:00:33 +08:00
Vaayne
e8c94f3584 Merge remote-tracking branch 'origin/main' into feat/agents-new 2025-09-12 17:56:10 +08:00
Vaayne
d123eec476 ♻️ refactor: eliminate database schema redundancy + add comprehensive documentation
Refactor database to migration-only approach and add complete documentation

### Database Architecture Improvements:
- **Remove redundant schema files**: Eliminated duplicate table/index definitions
- **Single source of truth**: Migration files now exclusively define database schema
- **Simplified maintenance**: No more sync issues between schema files and migrations

### Files Removed:
- `database/schema/tables.ts` - Redundant table definitions
- `database/schema/indexes.ts` - Redundant index definitions

### Files Updated:
- `database/schema/index.ts` - Now only exports migration utilities
- `database/index.ts` - Simplified exports, removed redundant schema references
- `BaseService.ts` - Updated documentation for migration-only approach
- `migrator.ts` - Enhanced documentation and clarity

### Documentation Added:
- **`database/README.md`** - Comprehensive 400+ line guide covering:
  - Architecture overview and migration-only approach
  - Complete directory structure explanation
  - Migration system lifecycle with diagrams
  - Query organization and API reference
  - Development workflow and best practices
  - Troubleshooting guide and examples

### Benefits:
-  Eliminated redundancy between schema and migration files
-  Reduced maintenance overhead and potential sync issues
-  Established single source of truth for database schema
-  Added comprehensive documentation for team development
-  Maintained full backward compatibility
-  All tests continue to pass (1420/1420)

The database system now follows industry best practices with migrations as the sole
schema definition method, while providing complete documentation for developers.
2025-09-12 17:54:12 +08:00
Vaayne
002a443281 🏗️ refactor: restructure agents service with migration system and modular architecture
BREAKING CHANGE: Major refactoring of agents service structure
- Split monolithic db.ts into focused query modules (agent, session, sessionLog)
- Implement comprehensive migration system with transaction support
- Reorganize services into dedicated services/ subdirectory
- Add production-ready schema versioning with rollback capability

### New Architecture:
- database/migrations/: Version-controlled schema evolution
- database/queries/: Entity-specific CRUD operations
- database/schema/: Table and index definitions
- services/: Business logic layer (AgentService, SessionService, SessionLogService)

### Key Features:
-  Migration system with atomic transactions and checksums
-  Modular query organization by entity type
-  Backward compatibility maintained for existing code
-  Production-ready rollback support
-  Comprehensive validation and testing

### Benefits:
- Single responsibility: Each file handles one specific concern
- Better maintainability: Easy to locate and modify entity-specific code
- Team-friendly: Reduced merge conflicts with smaller focused files
- Scalable: Simple to add new entities without cluttering existing code
- Production-ready: Safe schema evolution with migration tracking

All existing functionality preserved. Comprehensive testing completed (1420 tests pass).
2025-09-12 17:31:30 +08:00
Vaayne
64f3d08d4e ♻️ refactor: split AgentService into focused service modules
- **BaseService**: Shared database connection and JSON serialization utilities
- **AgentService**: Agent management operations (CRUD for agents)
- **SessionService**: Session management operations (CRUD for sessions)
- **SessionLogService**: Session log management operations (CRUD for session logs)

Updated API routes to use appropriate services:
- sessions.ts now uses SessionService for session operations
- session-logs.ts now uses SessionLogService and SessionService as needed
- Maintains backward compatibility with existing API endpoints

Benefits:
- Single Responsibility Principle - each service has a clear focus
- Better code organization and maintainability
- Easier testing and debugging
- Improved separation of concerns
- Shared database infrastructure via BaseService

All TypeScript compilation and build checks pass.
2025-09-12 16:25:50 +08:00
Vaayne
9c956a30ea feat: initialize AgentService in ApiServer and improve ID generation logic 2025-09-12 16:04:04 +08:00
Vaayne
5eaa90a7a2 feat: implement comprehensive CRUD APIs for agent management with type support 2025-09-12 15:27:36 +08:00
Vaayne
e3f5033bc4 chore: add express-validator dependency
Add express-validator for API request validation and data sanitization
in agent management endpoints.
2025-09-11 14:35:54 +08:00
Vaayne
2ec3b20b23 🚀 feat: add comprehensive REST API for agent management
Implement full REST API with Express routes for agents, sessions, and logs:
- CRUD operations for agents with validation and OpenAPI documentation
- Session management with nested resource endpoints
- Hierarchical logging system with bulk operations support
- Request validation using express-validator
- Proper error handling and structured responses
2025-09-11 14:35:34 +08:00
Vaayne
d26d02babc feat: implement AgentService for autonomous agent management
Add comprehensive agent service with full CRUD operations, session management,
and structured logging capabilities. Includes database operations for agents,
sessions, and hierarchical log entries with proper type definitions.
2025-09-11 14:35:14 +08:00
Vaayne
675671688b 📝 docs: add ast-grep tool guidance to CLAUDE.md
Add guidance to use ast-grep for code pattern searches when available,
improving development workflow documentation.
2025-09-11 14:34:55 +08:00
Vaayne
bcdd48615d 🗃️ feat: implement comprehensive agent database schema and queries
- Add complete SQL schema for agents, sessions, and session_logs tables
- Implement CRUD operations for all agent-related entities
- Add SessionLogEntity type with hierarchical logging support
- Include proper indexes and foreign key constraints for performance
- Support agent configuration inheritance in sessions via COALESCE
- Add metadata field for extensible session log tracking
2025-09-11 13:10:31 +08:00
Vaayne
1f974558f8 feat: enhance agent and session entity types with additional properties 2025-09-11 12:28:43 +08:00
Vaayne
0f1ad59e58 feat: add agent and session entity types 2025-09-11 10:00:29 +08:00
337 changed files with 28948 additions and 4494 deletions

View File

@@ -16,10 +16,13 @@ on:
jobs:
translate:
if: |
(github.event_name == 'issues') ||
(github.event_name == 'issue_comment' && github.event.sender.type != 'Bot') ||
(github.event_name == 'pull_request_review' && github.event.sender.type != 'Bot') ||
(github.event_name == 'pull_request_review_comment' && github.event.sender.type != 'Bot')
(github.event_name == 'issues')
|| (github.event_name == 'issue_comment' && github.event.sender.type != 'Bot')
|| (
(github.event_name == 'pull_request_review' || github.event_name == 'pull_request_review_comment')
&& github.event.sender.type != 'Bot'
&& github.event.pull_request.head.repo.fork == false
)
runs-on: ubuntu-latest
permissions:
contents: read
@@ -42,7 +45,7 @@ jobs:
# See: https://github.com/anthropics/claude-code-action/blob/main/docs/security.md
github_token: ${{ secrets.TOKEN_GITHUB_WRITE }}
allowed_non_write_users: "*"
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
anthropic_api_key: ${{ secrets.CLAUDE_TRANSLATOR_APIKEY }}
claude_args: "--allowed-tools Bash(gh issue:*),Bash(gh api:repos/*/issues:*),Bash(gh api:repos/*/pulls/*/reviews/*),Bash(gh api:repos/*/pulls/comments/*)"
prompt: |
你是一个多语言翻译助手。你需要响应 GitHub Webhooks 中的以下四种事件:
@@ -105,3 +108,5 @@ jobs:
使用以下命令获取完整信息:
gh issue view ${{ github.event.issue.number }} --json title,body,comments
env:
ANTHROPIC_BASE_URL: ${{ secrets.CLAUDE_TRANSLATOR_BASEURL }}

2
.gitignore vendored
View File

@@ -71,3 +71,5 @@ playwright-report
test-results
YOUR_MEMORY_FILE_PATH
.sessions/

View File

@@ -117,7 +117,7 @@
"no-unused-expressions": "off", // this rule disallow us to use expression to call function, like `condition && fn()`
"no-unused-labels": "error",
"no-unused-private-class-members": "error",
"no-unused-vars": ["error", { "caughtErrors": "none" }],
"no-unused-vars": ["warn", { "caughtErrors": "none" }],
"no-useless-backreference": "error",
"no-useless-catch": "error",
"no-useless-escape": "error",

10
.vscode/settings.json vendored
View File

@@ -34,10 +34,10 @@
"*.css": "tailwindcss"
},
"files.eol": "\n",
"i18n-ally.displayLanguage": "zh-cn",
// "i18n-ally.displayLanguage": "zh-cn", // 界面显示语言
"i18n-ally.enabledFrameworks": ["react-i18next", "i18next"],
"i18n-ally.enabledParsers": ["ts", "js", "json"], // 解析语言
"i18n-ally.fullReloadOnChanged": true, // 界面显示语言
"i18n-ally.fullReloadOnChanged": true,
"i18n-ally.keystyle": "nested", // 翻译路径格式
"i18n-ally.localesPaths": ["src/renderer/src/i18n/locales"],
// "i18n-ally.namespace": true, // 开启命名空间
@@ -47,5 +47,9 @@
"search.exclude": {
"**/dist/**": true,
".yarn/releases/**": true
}
},
"tailwindCSS.classAttributes": [
"className",
"classNames",
]
}

View File

@@ -1,8 +1,8 @@
diff --git a/dist/index.mjs b/dist/index.mjs
index 110f37ec18c98b1d55ae2b73cc716194e6f9094d..17e109b7778cbebb904f1919e768d21a2833d965 100644
index 69ab1599c76801dc1167551b6fa283dded123466..f0af43bba7ad1196fe05338817e65b4ebda40955 100644
--- a/dist/index.mjs
+++ b/dist/index.mjs
@@ -448,7 +448,7 @@ function convertToGoogleGenerativeAIMessages(prompt, options) {
@@ -477,7 +477,7 @@ function convertToGoogleGenerativeAIMessages(prompt, options) {
// src/get-model-path.ts
function getModelPath(modelId) {

View File

@@ -0,0 +1,31 @@
diff --git a/sdk.mjs b/sdk.mjs
index 461e9a2ba246778261108a682762ffcf26f7224e..44bd667d9f591969d36a105ba5eb8b478c738dd8 100644
--- a/sdk.mjs
+++ b/sdk.mjs
@@ -6215,7 +6215,7 @@ function createAbortController(maxListeners = DEFAULT_MAX_LISTENERS) {
}
// ../src/transport/ProcessTransport.ts
-import { spawn } from "child_process";
+import { fork } from "child_process";
import { createInterface } from "readline";
// ../src/utils/fsOperations.ts
@@ -6473,14 +6473,11 @@ class ProcessTransport {
const errorMessage = isNativeBinary(pathToClaudeCodeExecutable) ? `Claude Code native binary not found at ${pathToClaudeCodeExecutable}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.` : `Claude Code executable not found at ${pathToClaudeCodeExecutable}. Is options.pathToClaudeCodeExecutable set?`;
throw new ReferenceError(errorMessage);
}
- const isNative = isNativeBinary(pathToClaudeCodeExecutable);
- const spawnCommand = isNative ? pathToClaudeCodeExecutable : executable;
- const spawnArgs = isNative ? args : [...executableArgs, pathToClaudeCodeExecutable, ...args];
- this.logForDebugging(isNative ? `Spawning Claude Code native binary: ${pathToClaudeCodeExecutable} ${args.join(" ")}` : `Spawning Claude Code process: ${executable} ${[...executableArgs, pathToClaudeCodeExecutable, ...args].join(" ")}`);
+ this.logForDebugging(`Forking Claude Code Node.js process: ${pathToClaudeCodeExecutable} ${args.join(" ")}`);
const stderrMode = env.DEBUG || stderr ? "pipe" : "ignore";
- this.child = spawn(spawnCommand, spawnArgs, {
+ this.child = fork(pathToClaudeCodeExecutable, args, {
cwd,
- stdio: ["pipe", "pipe", stderrMode],
+ stdio: stderrMode === "pipe" ? ["pipe", "pipe", "pipe", "ipc"] : ["pipe", "pipe", "ignore", "ipc"],
signal: this.abortController.signal,
env
});

1
AGENTS.md Symbolic link
View File

@@ -0,0 +1 @@
CLAUDE.md

152
CLAUDE.md
View File

@@ -1,127 +1,51 @@
# CLAUDE.md
# AI Assistant Guide
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
This file provides guidance to AI coding assistants when working with code in this repository. Adherence to these guidelines is crucial for maintaining code quality and consistency.
## Guiding Principles (MUST FOLLOW)
- **Keep it clear**: Write code that is easy to read, maintain, and explain.
- **Match the house style**: Reuse existing patterns, naming, and conventions.
- **Search smart**: Prefer `ast-grep` for semantic queries; fall back to `rg`/`grep` when needed.
- **Build with HeroUI**: Use HeroUI for every new UI component; never add `antd` or `styled-components`.
- **Log centrally**: Route all logging through `loggerService` with the right context—no `console.log`.
- **Research via subagent**: Lean on `subagent` for external docs, APIs, news, and references.
- **Seek review**: Ask a human developer to review substantial changes before merging.
- **Commit in rhythm**: Keep commits small, conventional, and emoji-tagged.
## Development Commands
### Environment Setup
- **Install**: `yarn install` - Install all project dependencies
- **Development**: `yarn dev` - Runs Electron app in development mode with hot reload
- **Debug**: `yarn debug` - Starts with debugging enabled, use `chrome://inspect` to attach debugger
- **Build Check**: `yarn build:check` - **REQUIRED** before commits (lint + test + typecheck)
- If having i18n sort issues, run `yarn sync:i18n` first to sync template
- If having formatting issues, run `yarn format` first
- **Test**: `yarn test` - Run all tests (Vitest) across main and renderer processes
- **Single Test**:
- `yarn test:main` - Run tests for main process only
- `yarn test:renderer` - Run tests for renderer process only
- **Lint**: `yarn lint` - Fix linting issues and run TypeScript type checking
- **Format**: `yarn format` - Auto-format code using Biome
- **Prerequisites**: Node.js v22.x.x or higher, Yarn 4.9.1
- **Setup Yarn**: `corepack enable && corepack prepare yarn@4.9.1 --activate`
- **Install Dependencies**: `yarn install`
- **Add New Dependencies**: `yarn add -D` for renderer-specific dependencies, `yarn add` for others.
## Project Architecture
### Development
### Electron Structure
- **Main Process** (`src/main/`): Node.js backend with services (MCP, Knowledge, Storage, etc.)
- **Renderer Process** (`src/renderer/`): React UI with Redux state management
- **Preload Scripts** (`src/preload/`): Secure IPC bridge
- **Start Development**: `yarn dev` - Runs Electron app in development mode
- **Debug Mode**: `yarn debug` - Starts with debugging enabled, use chrome://inspect
### Testing & Quality
- **Run Tests**: `yarn test` - Runs all tests (Vitest)
- **Run E2E Tests**: `yarn test:e2e` - Playwright end-to-end tests
- **Type Check**: `yarn typecheck` - Checks TypeScript for both node and web
- **Lint**: `yarn lint` - ESLint with auto-fix
- **Format**: `yarn format` - Biome formatting
### Build & Release
- **Build**: `yarn build` - Builds for production (includes typecheck)
- **Platform-specific builds**:
- Windows: `yarn build:win`
- macOS: `yarn build:mac`
- Linux: `yarn build:linux`
## Architecture Overview
### Electron Multi-Process Architecture
- **Main Process** (`src/main/`): Node.js backend handling system integration, file operations, and services
- **Renderer Process** (`src/renderer/`): React-based UI running in Chromium
- **Preload Scripts** (`src/preload/`): Secure bridge between main and renderer processes
### Key Architectural Components
#### Main Process Services (`src/main/services/`)
- **MCPService**: Model Context Protocol server management
- **KnowledgeService**: Document processing and knowledge base management
- **FileStorage/S3Storage/WebDav**: Multiple storage backends
- **WindowService**: Multi-window management (main, mini, selection windows)
- **ProxyManager**: Network proxy handling
- **SearchService**: Full-text search capabilities
#### AI Core (`src/renderer/src/aiCore/`)
- **Middleware System**: Composable pipeline for AI request processing
- **Client Factory**: Supports multiple AI providers (OpenAI, Anthropic, Gemini, etc.)
- **Stream Processing**: Real-time response handling
#### State Management (`src/renderer/src/store/`)
- **Redux Toolkit**: Centralized state management
- **Persistent Storage**: Redux-persist for data persistence
- **Thunks**: Async actions for complex operations
#### Knowledge Management
- **Embeddings**: Vector search with multiple providers (OpenAI, Voyage, etc.)
- **OCR**: Document text extraction (system OCR, Doc2x, Mineru)
- **Preprocessing**: Document preparation pipeline
- **Loaders**: Support for various file formats (PDF, DOCX, EPUB, etc.)
### Build System
- **Electron-Vite**: Development and build tooling (v4.0.0)
- **Rolldown-Vite**: Using experimental rolldown-vite instead of standard vite
- **Workspaces**: Monorepo structure with `packages/` directory
- **Multiple Entry Points**: Main app, mini window, selection toolbar
- **Styled Components**: CSS-in-JS styling with SWC optimization
### Testing Strategy
- **Vitest**: Unit and integration testing
- **Playwright**: End-to-end testing
- **Component Testing**: React Testing Library
- **Coverage**: Available via `yarn test:coverage`
### Key Patterns
- **IPC Communication**: Secure main-renderer communication via preload scripts
- **Service Layer**: Clear separation between UI and business logic
- **Plugin Architecture**: Extensible via MCP servers and middleware
- **Multi-language Support**: i18n with dynamic loading
- **Theme System**: Light/dark themes with custom CSS variables
### UI Design
The project is in the process of migrating from antd & styled-components to HeroUI. Please use HeroUI to build UI components. The use of antd and styled-components is prohibited.
HeroUI Docs: https://www.heroui.com/docs/guide/introduction
## Logging Standards
### Usage
### Key Components
- **AI Core** (`src/renderer/src/aiCore/`): Middleware pipeline for multiple AI providers.
- **Services** (`src/main/services/`): MCPService, KnowledgeService, WindowService, etc.
- **Build System**: Electron-Vite with experimental rolldown-vite, yarn workspaces.
- **State Management**: Redux Toolkit (`src/renderer/src/store/`) for predictable state.
- **UI Components**: HeroUI (`@heroui/*`) for all new UI elements.
### Logging
```typescript
// Main process
import { loggerService } from '@logger'
const logger = loggerService.withContext('moduleName')
// Renderer process (set window source first)
loggerService.initWindowSource('windowName')
const logger = loggerService.withContext('moduleName')
// Logging
// Renderer: loggerService.initWindowSource('windowName') first
logger.info('message', CONTEXT)
logger.error('message', new Error('error'), CONTEXT)
```
### Log Levels (highest to lowest)
- `error` - Critical errors causing crash/unusable functionality
- `warn` - Potential issues that don't affect core functionality
- `info` - Application lifecycle and key user actions
- `verbose` - Detailed flow information for feature tracing
- `debug` - Development diagnostic info (not for production)
- `silly` - Extreme debugging, low-level information

View File

@@ -88,6 +88,7 @@ export default defineConfig({
alias: {
'@renderer': resolve('src/renderer/src'),
'@shared': resolve('packages/shared'),
'@types': resolve('src/renderer/src/types'),
'@logger': resolve('src/renderer/src/services/LoggerService'),
'@mcp-trace/trace-core': resolve('packages/mcp-trace/trace-core'),
'@mcp-trace/trace-web': resolve('packages/mcp-trace/trace-web'),

View File

@@ -2,6 +2,7 @@ import tseslint from '@electron-toolkit/eslint-config-ts'
import eslint from '@eslint/js'
import eslintReact from '@eslint-react/eslint-plugin'
import { defineConfig } from 'eslint/config'
import importZod from 'eslint-plugin-import-zod'
import oxlint from 'eslint-plugin-oxlint'
import reactHooks from 'eslint-plugin-react-hooks'
import simpleImportSort from 'eslint-plugin-simple-import-sort'
@@ -15,7 +16,8 @@ export default defineConfig([
{
plugins: {
'simple-import-sort': simpleImportSort,
'unused-imports': unusedImports
'unused-imports': unusedImports,
'import-zod': importZod
},
rules: {
'@typescript-eslint/explicit-function-return-type': 'off',
@@ -25,6 +27,7 @@ export default defineConfig([
'simple-import-sort/exports': 'error',
'unused-imports/no-unused-imports': 'error',
'@eslint-react/no-prop-types': 'error',
'import-zod/prefer-zod-namespace': 'error'
}
},
// Configuration for ensuring compatibility with the original ESLint(8.x) rules

View File

@@ -1,6 +1,6 @@
{
"name": "CherryStudio",
"version": "1.6.3",
"version": "1.7.0-alpha.5",
"private": true,
"description": "A powerful AI assistant for producer.",
"main": "./out/main/index.js",
@@ -43,15 +43,18 @@
"release": "node scripts/version.js",
"publish": "yarn build:check && yarn release patch push",
"pulish:artifacts": "cd packages/artifacts && npm publish && cd -",
"generate:agents": "yarn workspace @cherry-studio/database agents",
"agents:generate": "NODE_ENV='development' drizzle-kit generate --config src/main/services/agents/drizzle.config.ts",
"agents:push": "NODE_ENV='development' drizzle-kit push --config src/main/services/agents/drizzle.config.ts",
"agents:studio": "NODE_ENV='development' drizzle-kit studio --config src/main/services/agents/drizzle.config.ts",
"agents:drop": "NODE_ENV='development' drizzle-kit drop --config src/main/services/agents/drizzle.config.ts",
"generate:icons": "electron-icon-builder --input=./build/logo.png --output=build",
"analyze:renderer": "VISUALIZER_RENDERER=true yarn build",
"analyze:main": "VISUALIZER_MAIN=true yarn build",
"typecheck": "concurrently -n \"node,web\" -c \"cyan,magenta\" \"npm run typecheck:node\" \"npm run typecheck:web\"",
"typecheck:node": "tsgo --noEmit -p tsconfig.node.json --composite false",
"typecheck:web": "tsgo --noEmit -p tsconfig.web.json --composite false",
"check:i18n": "tsx scripts/check-i18n.ts",
"sync:i18n": "tsx scripts/sync-i18n.ts",
"check:i18n": "dotenv -e .env -- tsx scripts/check-i18n.ts",
"sync:i18n": "dotenv -e .env -- tsx scripts/sync-i18n.ts",
"update:i18n": "dotenv -e .env -- tsx scripts/update-i18n.ts",
"auto:i18n": "dotenv -e .env -- tsx scripts/auto-translate-i18n.ts",
"update:languages": "tsx scripts/update-languages.ts",
@@ -65,7 +68,7 @@
"test:e2e": "yarn playwright test",
"test:lint": "oxlint --deny-warnings && eslint . --ext .js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --cache",
"test:scripts": "vitest scripts",
"lint": "oxlint --fix && eslint . --ext .js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --cache && yarn typecheck && yarn check:i18n",
"lint": "oxlint --fix && eslint . --ext .js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --cache && yarn typecheck && yarn check:i18n && yarn format:check",
"format": "biome format --write && biome lint --write",
"format:check": "biome format && biome lint",
"prepare": "git config blame.ignoreRevsFile .git-blame-ignore-revs && husky",
@@ -75,11 +78,11 @@
"release:aicore": "yarn workspace @cherrystudio/ai-core version patch --immediate && yarn workspace @cherrystudio/ai-core npm publish --access public"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "patch:@anthropic-ai/claude-agent-sdk@npm%3A0.1.1#~/.yarn/patches/@anthropic-ai-claude-agent-sdk-npm-0.1.1-d937b73fed.patch",
"@libsql/client": "0.14.0",
"@libsql/win32-x64-msvc": "^0.4.7",
"@napi-rs/system-ocr": "patch:@napi-rs/system-ocr@npm%3A1.0.2#~/.yarn/patches/@napi-rs-system-ocr-npm-1.0.2-59e7a78e8b.patch",
"@strongtz/win32-arm64-msvc": "^0.4.7",
"express": "^5.1.0",
"font-list": "^2.0.0",
"graceful-fs": "^4.2.11",
"jsdom": "26.1.0",
@@ -89,7 +92,6 @@
"selection-hook": "^1.0.12",
"sharp": "^0.34.3",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.1",
"tesseract.js": "patch:tesseract.js@npm%3A6.0.1#~/.yarn/patches/tesseract.js-npm-6.0.1-2562a7e46d.patch",
"turndown": "7.2.0"
},
@@ -97,10 +99,10 @@
"@agentic/exa": "^7.3.3",
"@agentic/searxng": "^7.3.3",
"@agentic/tavily": "^7.3.3",
"@ai-sdk/amazon-bedrock": "^3.0.29",
"@ai-sdk/google-vertex": "^3.0.33",
"@ai-sdk/mistral": "^2.0.17",
"@ai-sdk/perplexity": "^2.0.11",
"@ai-sdk/amazon-bedrock": "^3.0.35",
"@ai-sdk/google-vertex": "^3.0.40",
"@ai-sdk/mistral": "^2.0.19",
"@ai-sdk/perplexity": "^2.0.13",
"@ant-design/v5-patch-for-react-19": "^1.0.3",
"@anthropic-ai/sdk": "^0.41.0",
"@anthropic-ai/vertex-sdk": "patch:@anthropic-ai/vertex-sdk@npm%3A0.11.4#~/.yarn/patches/@anthropic-ai-vertex-sdk-npm-0.11.4-c19cb41edb.patch",
@@ -150,7 +152,9 @@
"@opentelemetry/sdk-trace-base": "^2.0.0",
"@opentelemetry/sdk-trace-node": "^2.0.0",
"@opentelemetry/sdk-trace-web": "^2.0.0",
"@opeoginni/github-copilot-openai-compatible": "0.1.18",
"@playwright/test": "^1.52.0",
"@radix-ui/react-context-menu": "^2.2.16",
"@reduxjs/toolkit": "^2.2.5",
"@shikijs/markdown-it": "^3.12.0",
"@swc/plugin-styled-components": "^8.0.4",
@@ -202,6 +206,7 @@
"@types/swagger-ui-express": "^4.1.8",
"@types/tinycolor2": "^1",
"@types/turndown": "^5.0.5",
"@types/uuid": "^10.0.0",
"@types/word-extractor": "^1",
"@typescript/native-preview": "latest",
"@uiw/codemirror-extensions-langs": "^4.25.1",
@@ -215,7 +220,7 @@
"@viz-js/lang-dot": "^1.0.5",
"@viz-js/viz": "^3.14.0",
"@xyflow/react": "^12.4.4",
"ai": "^5.0.59",
"ai": "^5.0.68",
"antd": "patch:antd@npm%3A5.27.0#~/.yarn/patches/antd-npm-5.27.0-aa91c36546.patch",
"archiver": "^7.0.1",
"async-mutex": "^0.5.0",
@@ -238,9 +243,12 @@
"docx": "^9.0.2",
"dompurify": "^3.2.6",
"dotenv-cli": "^7.4.2",
"drizzle-kit": "^0.31.4",
"drizzle-orm": "^0.44.5",
"electron": "37.6.0",
"electron-builder": "26.0.15",
"electron-devtools-installer": "^3.2.0",
"electron-reload": "^2.0.0-alpha.1",
"electron-store": "^8.2.0",
"electron-updater": "6.6.4",
"electron-vite": "4.0.0",
@@ -249,10 +257,13 @@
"emoji-picker-element": "^1.22.1",
"epub": "patch:epub@npm%3A1.3.0#~/.yarn/patches/epub-npm-1.3.0-8325494ffe.patch",
"eslint": "^9.22.0",
"eslint-plugin-import-zod": "^1.2.0",
"eslint-plugin-oxlint": "^1.15.0",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-simple-import-sort": "^12.1.1",
"eslint-plugin-unused-imports": "^4.1.4",
"express": "^5.1.0",
"express-validator": "^7.2.1",
"fast-diff": "^1.3.0",
"fast-xml-parser": "^5.2.0",
"fetch-socks": "1.3.2",
@@ -285,7 +296,7 @@
"notion-helper": "^1.3.22",
"npx-scope-finder": "^1.2.0",
"openai": "patch:openai@npm%3A5.12.2#~/.yarn/patches/openai-npm-5.12.2-30b075401c.patch",
"oxlint": "^1.15.0",
"oxlint": "^1.22.0",
"oxlint-tsgolint": "^0.2.0",
"p-queue": "^8.1.0",
"pdf-lib": "^1.17.1",
@@ -325,6 +336,8 @@
"string-width": "^7.2.0",
"striptags": "^3.2.0",
"styled-components": "^6.1.11",
"swagger-ui-express": "^5.0.1",
"swr": "^2.3.6",
"tailwindcss": "^4.1.13",
"tar": "^7.4.3",
"tiny-pinyin": "^1.3.2",
@@ -335,7 +348,7 @@
"typescript": "~5.8.2",
"undici": "6.21.2",
"unified": "^11.0.5",
"uuid": "^10.0.0",
"uuid": "^13.0.0",
"vite": "npm:rolldown-vite@latest",
"vitest": "^3.2.4",
"webdav": "^5.8.0",
@@ -359,6 +372,7 @@
"app-builder-lib@npm:26.0.13": "patch:app-builder-lib@npm%3A26.0.13#~/.yarn/patches/app-builder-lib-npm-26.0.13-a064c9e1d0.patch",
"app-builder-lib@npm:26.0.15": "patch:app-builder-lib@npm%3A26.0.15#~/.yarn/patches/app-builder-lib-npm-26.0.15-360e5b0476.patch",
"atomically@npm:^1.7.0": "patch:atomically@npm%3A1.7.0#~/.yarn/patches/atomically-npm-1.7.0-e742e5293b.patch",
"esbuild": "^0.25.0",
"file-stream-rotator@npm:^0.6.1": "patch:file-stream-rotator@npm%3A0.6.1#~/.yarn/patches/file-stream-rotator-npm-0.6.1-eab45fb13d.patch",
"libsql@npm:^0.4.4": "patch:libsql@npm%3A0.4.7#~/.yarn/patches/libsql-npm-0.4.7-444e260fb1.patch",
"node-abi": "4.12.0",
@@ -366,10 +380,11 @@
"openai@npm:^4.87.3": "patch:openai@npm%3A5.12.2#~/.yarn/patches/openai-npm-5.12.2-30b075401c.patch",
"pdf-parse@npm:1.1.1": "patch:pdf-parse@npm%3A1.1.1#~/.yarn/patches/pdf-parse-npm-1.1.1-04a6109b2a.patch",
"pkce-challenge@npm:^4.1.0": "patch:pkce-challenge@npm%3A4.1.0#~/.yarn/patches/pkce-challenge-npm-4.1.0-fbc51695a3.patch",
"tar-fs": "^2.1.4",
"undici": "6.21.2",
"vite": "npm:rolldown-vite@latest",
"tesseract.js@npm:*": "patch:tesseract.js@npm%3A6.0.1#~/.yarn/patches/tesseract.js-npm-6.0.1-2562a7e46d.patch",
"@ai-sdk/google@npm:2.0.14": "patch:@ai-sdk/google@npm%3A2.0.14#~/.yarn/patches/@ai-sdk-google-npm-2.0.14-376d8b03cc.patch"
"@ai-sdk/google@npm:2.0.20": "patch:@ai-sdk/google@npm%3A2.0.20#~/.yarn/patches/@ai-sdk-google-npm-2.0.20-b9102f9d54.patch"
},
"packageManager": "yarn@4.9.1",
"lint-staged": {

View File

@@ -36,14 +36,14 @@
"ai": "^5.0.26"
},
"dependencies": {
"@ai-sdk/anthropic": "^2.0.22",
"@ai-sdk/azure": "^2.0.42",
"@ai-sdk/deepseek": "^1.0.20",
"@ai-sdk/openai": "^2.0.42",
"@ai-sdk/openai-compatible": "^1.0.19",
"@ai-sdk/anthropic": "^2.0.27",
"@ai-sdk/azure": "^2.0.49",
"@ai-sdk/deepseek": "^1.0.23",
"@ai-sdk/openai": "^2.0.48",
"@ai-sdk/openai-compatible": "^1.0.22",
"@ai-sdk/provider": "^2.0.0",
"@ai-sdk/provider-utils": "^3.0.10",
"@ai-sdk/xai": "^2.0.23",
"@ai-sdk/provider-utils": "^3.0.12",
"@ai-sdk/xai": "^2.0.26",
"zod": "^4.1.5"
},
"devDependencies": {

View File

@@ -1,7 +1,7 @@
import { anthropic } from '@ai-sdk/anthropic'
import { google } from '@ai-sdk/google'
import { openai } from '@ai-sdk/openai'
import { InferToolInput, InferToolOutput } from 'ai'
import { InferToolInput, InferToolOutput, type Tool } from 'ai'
import { ProviderOptionsMap } from '../../../options/types'
import { OpenRouterSearchConfig } from './openrouter'
@@ -15,6 +15,13 @@ export type AnthropicSearchConfig = NonNullable<Parameters<typeof anthropic.tool
export type GoogleSearchConfig = NonNullable<Parameters<typeof google.tools.googleSearch>[0]>
export type XAISearchConfig = NonNullable<ProviderOptionsMap['xai']['searchParameters']>
type NormalizeTool<T> = T extends Tool<infer INPUT, infer OUTPUT> ? Tool<INPUT, OUTPUT> : Tool<any, any>
type AnthropicWebSearchTool = NormalizeTool<ReturnType<typeof anthropic.tools.webSearch_20250305>>
type OpenAIWebSearchTool = NormalizeTool<ReturnType<typeof openai.tools.webSearch>>
type OpenAIChatWebSearchTool = NormalizeTool<ReturnType<typeof openai.tools.webSearchPreview>>
type GoogleWebSearchTool = NormalizeTool<ReturnType<typeof google.tools.googleSearch>>
/**
* 插件初始化时接收的完整配置对象
*
@@ -59,7 +66,7 @@ export const DEFAULT_WEB_SEARCH_CONFIG: WebSearchPluginConfig = {
export type WebSearchToolOutputSchema = {
// Anthropic 工具 - 手动定义
anthropic: InferToolOutput<ReturnType<typeof anthropic.tools.webSearch_20250305>>
anthropic: InferToolOutput<AnthropicWebSearchTool>
// OpenAI 工具 - 基于实际输出
// TODO: 上游定义不规范,是unknown
@@ -82,8 +89,8 @@ export type WebSearchToolOutputSchema = {
}
export type WebSearchToolInputSchema = {
anthropic: InferToolInput<ReturnType<typeof anthropic.tools.webSearch_20250305>>
openai: InferToolInput<ReturnType<typeof openai.tools.webSearch>>
google: InferToolInput<ReturnType<typeof google.tools.googleSearch>>
'openai-chat': InferToolInput<ReturnType<typeof openai.tools.webSearchPreview>>
anthropic: InferToolInput<AnthropicWebSearchTool>
openai: InferToolInput<OpenAIWebSearchTool>
google: InferToolInput<GoogleWebSearchTool>
'openai-chat': InferToolInput<OpenAIChatWebSearchTool>
}

View File

@@ -13,7 +13,7 @@ import { LanguageModelV2 } from '@ai-sdk/provider'
import { createXai } from '@ai-sdk/xai'
import { createOpenRouter } from '@openrouter/ai-sdk-provider'
import { customProvider, Provider } from 'ai'
import { z } from 'zod'
import * as z from 'zod'
/**
* 基础 Provider IDs

View File

@@ -5,8 +5,8 @@ export enum IpcChannel {
App_SetLanguage = 'app:set-language',
App_SetEnableSpellCheck = 'app:set-enable-spell-check',
App_SetSpellCheckLanguages = 'app:set-spell-check-languages',
App_ShowUpdateDialog = 'app:show-update-dialog',
App_CheckForUpdate = 'app:check-for-update',
App_QuitAndInstall = 'app:quit-and-install',
App_Reload = 'app:reload',
App_Quit = 'app:quit',
App_Info = 'app:info',
@@ -53,6 +53,7 @@ export enum IpcChannel {
Webview_SetOpenLinkExternal = 'webview:set-open-link-external',
Webview_SetSpellCheckEnabled = 'webview:set-spell-check-enabled',
Webview_SearchHotkey = 'webview:search-hotkey',
// Open
Open_Path = 'open:path',
@@ -91,6 +92,13 @@ export enum IpcChannel {
// Python
Python_Execute = 'python:execute',
// agent messages
AgentMessage_PersistExchange = 'agent-message:persist-exchange',
AgentMessage_GetHistory = 'agent-message:get-history',
// JavaScript
Js_Execute = 'js:execute',
//copilot
Copilot_GetAuthMessage = 'copilot:get-auth-message',
Copilot_GetCopilotToken = 'copilot:get-copilot-token',
@@ -184,6 +192,7 @@ export enum IpcChannel {
File_ValidateNotesDirectory = 'file:validateNotesDirectory',
File_StartWatcher = 'file:startWatcher',
File_StopWatcher = 'file:stopWatcher',
File_ShowInFolder = 'file:showInFolder',
// file service
FileService_Upload = 'file-service:upload',
@@ -229,7 +238,6 @@ export enum IpcChannel {
// events
BackupProgress = 'backup-progress',
ThemeUpdated = 'theme:updated',
UpdateDownloadedCancelled = 'update-downloaded-cancelled',
RestoreProgress = 'restore-progress',
UpdateError = 'update-error',
UpdateAvailable = 'update-available',

View File

@@ -0,0 +1,12 @@
import type { SDKMessage } from '@anthropic-ai/claude-agent-sdk'
import type { ContentBlockParam } from '@anthropic-ai/sdk/resources/messages'
export type ClaudeCodeRawValue =
| {
type: string
session_id: string
slash_commands: string[]
tools: string[]
raw: Extract<SDKMessage, { type: 'system' }>
}
| ContentBlockParam

View File

@@ -0,0 +1,170 @@
/**
* @fileoverview Shared Anthropic AI client utilities for Cherry Studio
*
* This module provides functions for creating Anthropic SDK clients with different
* authentication methods (OAuth, API key) and building Claude Code system messages.
* It supports both standard Anthropic API and Anthropic Vertex AI endpoints.
*
* This shared module can be used by both main and renderer processes.
*/
import Anthropic from '@anthropic-ai/sdk'
import { TextBlockParam } from '@anthropic-ai/sdk/resources'
import { loggerService } from '@logger'
import { Provider } from '@types'
import type { ModelMessage } from 'ai'
const logger = loggerService.withContext('anthropic-sdk')
const defaultClaudeCodeSystemPrompt = `You are Claude Code, Anthropic's official CLI for Claude.`
const defaultClaudeCodeSystem: Array<TextBlockParam> = [
{
type: 'text',
text: defaultClaudeCodeSystemPrompt
}
]
/**
* Creates and configures an Anthropic SDK client based on the provider configuration.
*
* This function supports two authentication methods:
* 1. OAuth: Uses OAuth tokens passed as parameter
* 2. API Key: Uses traditional API key authentication
*
* For OAuth authentication, it includes Claude Code specific headers and beta features.
* For API key authentication, it uses the provider's configuration with custom headers.
*
* @param provider - The provider configuration containing authentication details
* @param oauthToken - Optional OAuth token for OAuth authentication
* @returns An initialized Anthropic or AnthropicVertex client
* @throws Error when OAuth token is not available for OAuth authentication
*
* @example
* ```typescript
* // OAuth authentication
* const oauthProvider = { authType: 'oauth' };
* const oauthClient = getSdkClient(oauthProvider, 'oauth-token-here');
*
* // API key authentication
* const apiKeyProvider = {
* authType: 'apikey',
* apiKey: 'your-api-key',
* apiHost: 'https://api.anthropic.com'
* };
* const apiKeyClient = getSdkClient(apiKeyProvider);
* ```
*/
export function getSdkClient(
provider: Provider,
oauthToken?: string | null,
extraHeaders?: Record<string, string | string[]>
): Anthropic {
if (provider.authType === 'oauth') {
if (!oauthToken) {
throw new Error('OAuth token is not available')
}
return new Anthropic({
authToken: oauthToken,
baseURL: 'https://api.anthropic.com',
dangerouslyAllowBrowser: true,
defaultHeaders: {
'Content-Type': 'application/json',
'anthropic-version': '2023-06-01',
'anthropic-beta':
'oauth-2025-04-20,claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14',
'anthropic-dangerous-direct-browser-access': 'true',
'user-agent': 'claude-cli/1.0.118 (external, sdk-ts)',
'x-app': 'cli',
'x-stainless-retry-count': '0',
'x-stainless-timeout': '600',
'x-stainless-lang': 'js',
'x-stainless-package-version': '0.60.0',
'x-stainless-os': 'MacOS',
'x-stainless-arch': 'arm64',
'x-stainless-runtime': 'node',
'x-stainless-runtime-version': 'v22.18.0',
...extraHeaders
}
})
}
const baseURL =
provider.type === 'anthropic'
? provider.apiHost
: (provider.anthropicApiHost && provider.anthropicApiHost.trim()) || provider.apiHost
logger.debug('Anthropic API baseURL', { baseURL, providerId: provider.id })
if (provider.id === 'aihubmix') {
return new Anthropic({
apiKey: provider.apiKey,
baseURL,
dangerouslyAllowBrowser: true,
defaultHeaders: {
'anthropic-beta': 'output-128k-2025-02-19',
'APP-Code': 'MLTG2087',
...provider.extra_headers,
...extraHeaders
}
})
}
return new Anthropic({
apiKey: provider.apiKey,
authToken: provider.apiKey,
baseURL,
dangerouslyAllowBrowser: true,
defaultHeaders: {
'anthropic-beta': 'output-128k-2025-02-19',
...provider.extra_headers
}
})
}
/**
* Builds and prepends the Claude Code system message to user-provided system messages.
*
* This function ensures that all interactions with Claude include the official Claude Code
* system prompt, which identifies the assistant as "Claude Code, Anthropic's official CLI for Claude."
*
* The function handles three cases:
* 1. No system message provided: Returns only the default Claude Code system message
* 2. String system message: Converts to array format and prepends Claude Code message
* 3. Array system message: Checks if Claude Code message exists and prepends if missing
*
* @param system - Optional user-provided system message (string or TextBlockParam array)
* @returns Combined system message with Claude Code prompt prepended
*
* ```
*/
export function buildClaudeCodeSystemMessage(system?: string | Array<TextBlockParam>): Array<TextBlockParam> {
if (!system) {
return defaultClaudeCodeSystem
}
if (typeof system === 'string') {
if (system.trim() === defaultClaudeCodeSystemPrompt || system.trim() === '') {
return defaultClaudeCodeSystem
} else {
return [...defaultClaudeCodeSystem, { type: 'text', text: system }]
}
}
if (Array.isArray(system)) {
const firstSystem = system[0]
if (firstSystem.type === 'text' && firstSystem.text.trim() === defaultClaudeCodeSystemPrompt) {
return system
} else {
return [...defaultClaudeCodeSystem, ...system]
}
}
return defaultClaudeCodeSystem
}
export function buildClaudeCodeSystemModelMessage(system?: string | Array<TextBlockParam>): Array<ModelMessage> {
const textBlocks = buildClaudeCodeSystemMessage(system)
return textBlocks.map((block) => ({
role: 'system',
content: block.text
}))
}

View File

@@ -22,3 +22,12 @@ export type MCPProgressEvent = {
callId: string
progress: number // 0-1 range
}
export type WebviewKeyEvent = {
webviewId: number
key: string
control: boolean
meta: boolean
shift: boolean
alt: boolean
}

View File

@@ -0,0 +1,53 @@
--> statement-breakpoint
CREATE TABLE `migrations` (
`version` integer PRIMARY KEY NOT NULL,
`tag` text NOT NULL,
`executed_at` integer NOT NULL
);
CREATE TABLE `agents` (
`id` text PRIMARY KEY NOT NULL,
`type` text NOT NULL,
`name` text NOT NULL,
`description` text,
`accessible_paths` text,
`instructions` text,
`model` text NOT NULL,
`plan_model` text,
`small_model` text,
`mcps` text,
`allowed_tools` text,
`configuration` text,
`created_at` text NOT NULL,
`updated_at` text NOT NULL
);
--> statement-breakpoint
CREATE TABLE `sessions` (
`id` text PRIMARY KEY NOT NULL,
`agent_type` text NOT NULL,
`agent_id` text NOT NULL,
`name` text NOT NULL,
`description` text,
`accessible_paths` text,
`instructions` text,
`model` text NOT NULL,
`plan_model` text,
`small_model` text,
`mcps` text,
`allowed_tools` text,
`configuration` text,
`created_at` text NOT NULL,
`updated_at` text NOT NULL
);
--> statement-breakpoint
CREATE TABLE `session_messages` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`session_id` text NOT NULL,
`role` text NOT NULL,
`content` text NOT NULL,
`metadata` text,
`created_at` text NOT NULL,
`updated_at` text NOT NULL
);

View File

@@ -0,0 +1 @@
ALTER TABLE `session_messages` ADD `agent_session_id` text DEFAULT '';

View File

@@ -0,0 +1,331 @@
{
"version": "6",
"dialect": "sqlite",
"id": "35efb412-0230-4767-9c76-7b7c4d40369f",
"prevId": "00000000-0000-0000-0000-000000000000",
"tables": {
"agents": {
"name": "agents",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"type": {
"name": "type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"description": {
"name": "description",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"accessible_paths": {
"name": "accessible_paths",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"instructions": {
"name": "instructions",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"model": {
"name": "model",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"plan_model": {
"name": "plan_model",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"small_model": {
"name": "small_model",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"mcps": {
"name": "mcps",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"allowed_tools": {
"name": "allowed_tools",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"configuration": {
"name": "configuration",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"session_messages": {
"name": "session_messages",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"session_id": {
"name": "session_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"role": {
"name": "role",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"content": {
"name": "content",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"metadata": {
"name": "metadata",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"migrations": {
"name": "migrations",
"columns": {
"version": {
"name": "version",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"tag": {
"name": "tag",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"executed_at": {
"name": "executed_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"sessions": {
"name": "sessions",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"agent_type": {
"name": "agent_type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"agent_id": {
"name": "agent_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"description": {
"name": "description",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"accessible_paths": {
"name": "accessible_paths",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"instructions": {
"name": "instructions",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"model": {
"name": "model",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"plan_model": {
"name": "plan_model",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"small_model": {
"name": "small_model",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"mcps": {
"name": "mcps",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"allowed_tools": {
"name": "allowed_tools",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"configuration": {
"name": "configuration",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}

View File

@@ -0,0 +1,339 @@
{
"version": "6",
"dialect": "sqlite",
"id": "dabab6db-a2cd-4e96-b06e-6cb87d445a87",
"prevId": "35efb412-0230-4767-9c76-7b7c4d40369f",
"tables": {
"agents": {
"name": "agents",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"type": {
"name": "type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"description": {
"name": "description",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"accessible_paths": {
"name": "accessible_paths",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"instructions": {
"name": "instructions",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"model": {
"name": "model",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"plan_model": {
"name": "plan_model",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"small_model": {
"name": "small_model",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"mcps": {
"name": "mcps",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"allowed_tools": {
"name": "allowed_tools",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"configuration": {
"name": "configuration",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"session_messages": {
"name": "session_messages",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"session_id": {
"name": "session_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"role": {
"name": "role",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"content": {
"name": "content",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"agent_session_id": {
"name": "agent_session_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": "''"
},
"metadata": {
"name": "metadata",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"migrations": {
"name": "migrations",
"columns": {
"version": {
"name": "version",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"tag": {
"name": "tag",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"executed_at": {
"name": "executed_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"sessions": {
"name": "sessions",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"agent_type": {
"name": "agent_type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"agent_id": {
"name": "agent_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"description": {
"name": "description",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"accessible_paths": {
"name": "accessible_paths",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"instructions": {
"name": "instructions",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"model": {
"name": "model",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"plan_model": {
"name": "plan_model",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"small_model": {
"name": "small_model",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"mcps": {
"name": "mcps",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"allowed_tools": {
"name": "allowed_tools",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"configuration": {
"name": "configuration",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}

View File

@@ -0,0 +1,20 @@
{
"version": "7",
"dialect": "sqlite",
"entries": [
{
"idx": 0,
"version": "6",
"when": 1758091173882,
"tag": "0000_confused_wendigo",
"breakpoints": true
},
{
"idx": 1,
"version": "6",
"when": 1758187378775,
"tag": "0001_woozy_captain_flint",
"breakpoints": true
}
]
}

Binary file not shown.

View File

@@ -9,8 +9,9 @@ import * as path from 'path'
const localesDir = path.join(__dirname, '../src/renderer/src/i18n/locales')
const translateDir = path.join(__dirname, '../src/renderer/src/i18n/translate')
const baseLocale = 'zh-cn'
const baseLocale = process.env.BASE_LOCALE ?? 'zh-cn'
const baseFileName = `${baseLocale}.json`
const baseLocalePath = path.join(__dirname, '../src/renderer/src/i18n/locales', baseFileName)
type I18NValue = string | { [key: string]: I18NValue }
type I18N = { [key: string]: I18NValue }
@@ -105,6 +106,9 @@ const translateRecursively = async (originObj: I18N, systemPrompt: string): Prom
}
const main = async () => {
if (!fs.existsSync(baseLocalePath)) {
throw new Error(`${baseLocalePath} not found.`)
}
const localeFiles = fs
.readdirSync(localesDir)
.filter((file) => file.endsWith('.json') && file !== baseFileName)

View File

@@ -35,6 +35,9 @@ const allX64 = {
'@napi-rs/system-ocr-win32-x64-msvc': '1.0.2'
}
const claudeCodeVenderPath = '@anthropic-ai/claude-agent-sdk/vendor'
const claudeCodeVenders = ['arm64-darwin', 'arm64-linux', 'x64-darwin', 'x64-linux', 'x64-win32']
const platformToArch = {
mac: 'darwin',
windows: 'win32',
@@ -46,9 +49,6 @@ exports.default = async function (context) {
const archType = arch === Arch.arm64 ? 'arm64' : 'x64'
const platform = context.packager.platform.name
const arm64Filters = Object.keys(allArm64).map((f) => '!node_modules/' + f + '/**')
const x64Filters = Object.keys(allX64).map((f) => '!node_modules/' + f + '/*')
const downloadPackages = async (packages) => {
console.log('downloading packages ......')
const downloadPromises = []
@@ -67,25 +67,39 @@ exports.default = async function (context) {
await Promise.all(downloadPromises)
}
const changeFilters = async (packages, filtersToExclude, filtersToInclude) => {
await downloadPackages(packages)
const changeFilters = async (filtersToExclude, filtersToInclude) => {
// remove filters for the target architecture (allow inclusion)
let filters = context.packager.config.files[0].filter
filters = filters.filter((filter) => !filtersToInclude.includes(filter))
// add filters for other architectures (exclude them)
filters.push(...filtersToExclude)
context.packager.config.files[0].filter = filters
}
if (arch === Arch.arm64) {
await changeFilters(allArm64, x64Filters, arm64Filters)
return
}
await downloadPackages(arch === Arch.arm64 ? allArm64 : allX64)
if (arch === Arch.x64) {
await changeFilters(allX64, arm64Filters, x64Filters)
return
const arm64Filters = Object.keys(allArm64).map((f) => '!node_modules/' + f + '/**')
const x64Filters = Object.keys(allX64).map((f) => '!node_modules/' + f + '/*')
const excludeClaudeCodeRipgrepFilters = claudeCodeVenders
.filter((f) => f !== `${archType}-${platformToArch[platform]}`)
.map((f) => '!node_modules/' + claudeCodeVenderPath + '/ripgrep/' + f + '/**')
const excludeClaudeCodeJBPlutins = ['!node_modules/' + claudeCodeVenderPath + '/' + 'claude-code-jetbrains-plugin']
const includeClaudeCodeFilters = [
'!node_modules/' + claudeCodeVenderPath + '/ripgrep/' + `${archType}-${platformToArch[platform]}/**`
]
if (arch === Arch.arm64) {
await changeFilters(
[...x64Filters, ...excludeClaudeCodeRipgrepFilters, ...excludeClaudeCodeJBPlutins],
[...arm64Filters, ...includeClaudeCodeFilters]
)
} else {
await changeFilters(
[...arm64Filters, ...excludeClaudeCodeRipgrepFilters, ...excludeClaudeCodeJBPlutins],
[...x64Filters, ...includeClaudeCodeFilters]
)
}
}

View File

@@ -4,7 +4,7 @@ import * as path from 'path'
import { sortedObjectByKeys } from './sort'
const translationsDir = path.join(__dirname, '../src/renderer/src/i18n/locales')
const baseLocale = 'zh-cn'
const baseLocale = process.env.BASE_LOCALE ?? 'zh-cn'
const baseFileName = `${baseLocale}.json`
const baseFilePath = path.join(translationsDir, baseFileName)

View File

@@ -5,7 +5,7 @@ import { sortedObjectByKeys } from './sort'
const localesDir = path.join(__dirname, '../src/renderer/src/i18n/locales')
const translateDir = path.join(__dirname, '../src/renderer/src/i18n/translate')
const baseLocale = 'zh-cn'
const baseLocale = process.env.BASE_LOCALE ?? 'zh-cn'
const baseFileName = `${baseLocale}.json`
const baseFilePath = path.join(localesDir, baseFileName)

View File

@@ -3,23 +3,42 @@ import cors from 'cors'
import express from 'express'
import { v4 as uuidv4 } from 'uuid'
import { LONG_POLL_TIMEOUT_MS } from './config/timeouts'
import { authMiddleware } from './middleware/auth'
import { errorHandler } from './middleware/error'
import { setupOpenAPIDocumentation } from './middleware/openapi'
import { agentsRoutes } from './routes/agents'
import { chatRoutes } from './routes/chat'
import { mcpRoutes } from './routes/mcp'
import { messagesProviderRoutes, messagesRoutes } from './routes/messages'
import { modelsRoutes } from './routes/models'
const logger = loggerService.withContext('ApiServer')
const extendMessagesTimeout: express.RequestHandler = (req, res, next) => {
req.setTimeout(LONG_POLL_TIMEOUT_MS)
res.setTimeout(LONG_POLL_TIMEOUT_MS)
next()
}
const app = express()
app.use(
express.json({
limit: '50mb'
})
)
// Global middleware
app.use((req, res, next) => {
const start = Date.now()
res.on('finish', () => {
const duration = Date.now() - start
logger.info(`${req.method} ${req.path} - ${res.statusCode} - ${duration}ms`)
logger.info('API request completed', {
method: req.method,
path: req.path,
statusCode: res.statusCode,
durationMs: duration
})
})
next()
})
@@ -101,27 +120,28 @@ app.get('/', (_req, res) => {
name: 'Cherry Studio API',
version: '1.0.0',
endpoints: {
health: 'GET /health',
models: 'GET /v1/models',
chat: 'POST /v1/chat/completions',
mcp: 'GET /v1/mcps'
health: 'GET /health'
}
})
})
// Setup OpenAPI documentation before protected routes so docs remain public
setupOpenAPIDocumentation(app)
// Provider-specific messages route requires authentication
app.use('/:provider/v1/messages', authMiddleware, extendMessagesTimeout, messagesProviderRoutes)
// API v1 routes with auth
const apiRouter = express.Router()
apiRouter.use(authMiddleware)
apiRouter.use(express.json())
// Mount routes
apiRouter.use('/chat', chatRoutes)
apiRouter.use('/mcps', mcpRoutes)
apiRouter.use('/messages', extendMessagesTimeout, messagesRoutes)
apiRouter.use('/models', modelsRoutes)
apiRouter.use('/agents', agentsRoutes)
app.use('/v1', apiRouter)
// Setup OpenAPI documentation
setupOpenAPIDocumentation(app)
// Error handling (must be last)
app.use(errorHandler)

View File

@@ -36,7 +36,7 @@ class ConfigManager {
}
return this._config
} catch (error: any) {
logger.warn('Failed to load config from Redux, using defaults:', error)
logger.warn('Failed to load config from Redux, using defaults', { error })
this._config = {
enabled: false,
port: defaultPort,

View File

@@ -0,0 +1,3 @@
export const LONG_POLL_TIMEOUT_MS = 120 * 60_000 // 120 minutes
export const MESSAGE_STREAM_TIMEOUT_MS = LONG_POLL_TIMEOUT_MS

View File

@@ -0,0 +1,368 @@
import type { NextFunction, Request, Response } from 'express'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { config } from '../../config'
import { authMiddleware } from '../auth'
// Mock the config module
vi.mock('../../config', () => ({
config: {
get: vi.fn()
}
}))
// Mock the logger
vi.mock('@logger', () => ({
loggerService: {
withContext: vi.fn(() => ({
debug: vi.fn()
}))
}
}))
const mockConfig = config as any
describe('authMiddleware', () => {
let req: Partial<Request>
let res: Partial<Response>
let next: NextFunction
let jsonMock: ReturnType<typeof vi.fn>
let statusMock: ReturnType<typeof vi.fn>
beforeEach(() => {
jsonMock = vi.fn()
statusMock = vi.fn(() => ({ json: jsonMock }))
req = {
header: vi.fn()
}
res = {
status: statusMock
}
next = vi.fn()
vi.clearAllMocks()
})
describe('Missing credentials', () => {
it('should return 401 when both auth headers are missing', async () => {
;(req.header as any).mockReturnValue('')
await authMiddleware(req as Request, res as Response, next)
expect(statusMock).toHaveBeenCalledWith(401)
expect(jsonMock).toHaveBeenCalledWith({ error: 'Unauthorized: missing credentials' })
expect(next).not.toHaveBeenCalled()
})
it('should return 401 when both auth headers are empty strings', async () => {
;(req.header as any).mockImplementation((header: string) => {
if (header === 'authorization') return ''
if (header === 'x-api-key') return ''
return ''
})
await authMiddleware(req as Request, res as Response, next)
expect(statusMock).toHaveBeenCalledWith(401)
expect(jsonMock).toHaveBeenCalledWith({ error: 'Unauthorized: missing credentials' })
expect(next).not.toHaveBeenCalled()
})
})
describe('Server configuration', () => {
it('should return 403 when API key is not configured', async () => {
;(req.header as any).mockImplementation((header: string) => {
if (header === 'x-api-key') return 'some-key'
return ''
})
mockConfig.get.mockResolvedValue({ apiKey: '' })
await authMiddleware(req as Request, res as Response, next)
expect(statusMock).toHaveBeenCalledWith(403)
expect(jsonMock).toHaveBeenCalledWith({ error: 'Forbidden' })
expect(next).not.toHaveBeenCalled()
})
it('should return 403 when API key is null', async () => {
;(req.header as any).mockImplementation((header: string) => {
if (header === 'x-api-key') return 'some-key'
return ''
})
mockConfig.get.mockResolvedValue({ apiKey: null })
await authMiddleware(req as Request, res as Response, next)
expect(statusMock).toHaveBeenCalledWith(403)
expect(jsonMock).toHaveBeenCalledWith({ error: 'Forbidden' })
expect(next).not.toHaveBeenCalled()
})
})
describe('API Key authentication (priority)', () => {
const validApiKey = 'valid-api-key-123'
beforeEach(() => {
mockConfig.get.mockResolvedValue({ apiKey: validApiKey })
})
it('should authenticate successfully with valid API key', async () => {
;(req.header as any).mockImplementation((header: string) => {
if (header === 'x-api-key') return validApiKey
return ''
})
await authMiddleware(req as Request, res as Response, next)
expect(next).toHaveBeenCalled()
expect(statusMock).not.toHaveBeenCalled()
})
it('should return 403 with invalid API key', async () => {
;(req.header as any).mockImplementation((header: string) => {
if (header === 'x-api-key') return 'invalid-key'
return ''
})
await authMiddleware(req as Request, res as Response, next)
expect(statusMock).toHaveBeenCalledWith(403)
expect(jsonMock).toHaveBeenCalledWith({ error: 'Forbidden' })
expect(next).not.toHaveBeenCalled()
})
it('should return 401 with empty API key', async () => {
;(req.header as any).mockImplementation((header: string) => {
if (header === 'x-api-key') return ' '
return ''
})
await authMiddleware(req as Request, res as Response, next)
expect(statusMock).toHaveBeenCalledWith(401)
expect(jsonMock).toHaveBeenCalledWith({ error: 'Unauthorized: empty x-api-key' })
expect(next).not.toHaveBeenCalled()
})
it('should handle API key with whitespace', async () => {
;(req.header as any).mockImplementation((header: string) => {
if (header === 'x-api-key') return ` ${validApiKey} `
return ''
})
await authMiddleware(req as Request, res as Response, next)
expect(next).toHaveBeenCalled()
expect(statusMock).not.toHaveBeenCalled()
})
it('should prioritize API key over Bearer token when both are present', async () => {
;(req.header as any).mockImplementation((header: string) => {
if (header === 'x-api-key') return validApiKey
if (header === 'authorization') return 'Bearer invalid-token'
return ''
})
await authMiddleware(req as Request, res as Response, next)
expect(next).toHaveBeenCalled()
expect(statusMock).not.toHaveBeenCalled()
})
it('should return 403 when API key is invalid even if Bearer token is valid', async () => {
;(req.header as any).mockImplementation((header: string) => {
if (header === 'x-api-key') return 'invalid-key'
if (header === 'authorization') return `Bearer ${validApiKey}`
return ''
})
await authMiddleware(req as Request, res as Response, next)
expect(statusMock).toHaveBeenCalledWith(403)
expect(jsonMock).toHaveBeenCalledWith({ error: 'Forbidden' })
expect(next).not.toHaveBeenCalled()
})
})
describe('Bearer token authentication (fallback)', () => {
const validApiKey = 'valid-api-key-123'
beforeEach(() => {
mockConfig.get.mockResolvedValue({ apiKey: validApiKey })
})
it('should authenticate successfully with valid Bearer token when no API key', async () => {
;(req.header as any).mockImplementation((header: string) => {
if (header === 'authorization') return `Bearer ${validApiKey}`
return ''
})
await authMiddleware(req as Request, res as Response, next)
expect(next).toHaveBeenCalled()
expect(statusMock).not.toHaveBeenCalled()
})
it('should return 403 with invalid Bearer token', async () => {
;(req.header as any).mockImplementation((header: string) => {
if (header === 'authorization') return 'Bearer invalid-token'
return ''
})
await authMiddleware(req as Request, res as Response, next)
expect(statusMock).toHaveBeenCalledWith(403)
expect(jsonMock).toHaveBeenCalledWith({ error: 'Forbidden' })
expect(next).not.toHaveBeenCalled()
})
it('should return 401 with malformed authorization header', async () => {
;(req.header as any).mockImplementation((header: string) => {
if (header === 'authorization') return 'Basic sometoken'
return ''
})
await authMiddleware(req as Request, res as Response, next)
expect(statusMock).toHaveBeenCalledWith(401)
expect(jsonMock).toHaveBeenCalledWith({ error: 'Unauthorized: invalid authorization format' })
expect(next).not.toHaveBeenCalled()
})
it('should return 401 with Bearer without space', async () => {
;(req.header as any).mockImplementation((header: string) => {
if (header === 'authorization') return 'Bearer'
return ''
})
await authMiddleware(req as Request, res as Response, next)
expect(statusMock).toHaveBeenCalledWith(401)
expect(jsonMock).toHaveBeenCalledWith({ error: 'Unauthorized: invalid authorization format' })
expect(next).not.toHaveBeenCalled()
})
it('should handle Bearer token with only trailing spaces (edge case)', async () => {
;(req.header as any).mockImplementation((header: string) => {
if (header === 'authorization') return 'Bearer ' // This will be trimmed to "Bearer" and fail format check
return ''
})
await authMiddleware(req as Request, res as Response, next)
expect(statusMock).toHaveBeenCalledWith(401)
expect(jsonMock).toHaveBeenCalledWith({ error: 'Unauthorized: invalid authorization format' })
expect(next).not.toHaveBeenCalled()
})
it('should handle Bearer token with case insensitive prefix', async () => {
;(req.header as any).mockImplementation((header: string) => {
if (header === 'authorization') return `bearer ${validApiKey}`
return ''
})
await authMiddleware(req as Request, res as Response, next)
expect(next).toHaveBeenCalled()
expect(statusMock).not.toHaveBeenCalled()
})
it('should handle Bearer token with whitespace', async () => {
;(req.header as any).mockImplementation((header: string) => {
if (header === 'authorization') return ` Bearer ${validApiKey} `
return ''
})
await authMiddleware(req as Request, res as Response, next)
expect(next).toHaveBeenCalled()
expect(statusMock).not.toHaveBeenCalled()
})
})
describe('Edge cases', () => {
const validApiKey = 'valid-api-key-123'
beforeEach(() => {
mockConfig.get.mockResolvedValue({ apiKey: validApiKey })
})
it('should handle config.get() rejection', async () => {
;(req.header as any).mockImplementation((header: string) => {
if (header === 'x-api-key') return validApiKey
return ''
})
mockConfig.get.mockRejectedValue(new Error('Config error'))
await expect(authMiddleware(req as Request, res as Response, next)).rejects.toThrow('Config error')
})
it('should use timing-safe comparison for different length tokens', async () => {
;(req.header as any).mockImplementation((header: string) => {
if (header === 'x-api-key') return 'short'
return ''
})
await authMiddleware(req as Request, res as Response, next)
expect(statusMock).toHaveBeenCalledWith(403)
expect(jsonMock).toHaveBeenCalledWith({ error: 'Forbidden' })
expect(next).not.toHaveBeenCalled()
})
it('should return 401 when neither credential format is valid', async () => {
;(req.header as any).mockImplementation((header: string) => {
if (header === 'authorization') return 'Invalid format'
return ''
})
await authMiddleware(req as Request, res as Response, next)
expect(statusMock).toHaveBeenCalledWith(401)
expect(jsonMock).toHaveBeenCalledWith({ error: 'Unauthorized: invalid authorization format' })
expect(next).not.toHaveBeenCalled()
})
})
describe('Timing attack protection', () => {
const validApiKey = 'valid-api-key-123'
beforeEach(() => {
mockConfig.get.mockResolvedValue({ apiKey: validApiKey })
})
it('should handle similar length but different API keys securely', async () => {
const similarKey = 'valid-api-key-124' // Same length, different last char
;(req.header as any).mockImplementation((header: string) => {
if (header === 'x-api-key') return similarKey
return ''
})
await authMiddleware(req as Request, res as Response, next)
expect(statusMock).toHaveBeenCalledWith(403)
expect(jsonMock).toHaveBeenCalledWith({ error: 'Forbidden' })
expect(next).not.toHaveBeenCalled()
})
it('should handle similar length but different Bearer tokens securely', async () => {
const similarKey = 'valid-api-key-124' // Same length, different last char
;(req.header as any).mockImplementation((header: string) => {
if (header === 'authorization') return `Bearer ${similarKey}`
return ''
})
await authMiddleware(req as Request, res as Response, next)
expect(statusMock).toHaveBeenCalledWith(403)
expect(jsonMock).toHaveBeenCalledWith({ error: 'Forbidden' })
expect(next).not.toHaveBeenCalled()
})
})
})

View File

@@ -3,8 +3,17 @@ import { NextFunction, Request, Response } from 'express'
import { config } from '../config'
const isValidToken = (token: string, apiKey: string): boolean => {
if (token.length !== apiKey.length) {
return false
}
const tokenBuf = Buffer.from(token)
const keyBuf = Buffer.from(apiKey)
return crypto.timingSafeEqual(tokenBuf, keyBuf)
}
export const authMiddleware = async (req: Request, res: Response, next: NextFunction) => {
const auth = req.header('Authorization') || ''
const auth = req.header('authorization') || ''
const xApiKey = req.header('x-api-key') || ''
// Fast rejection if neither credential header provided
@@ -12,51 +21,46 @@ export const authMiddleware = async (req: Request, res: Response, next: NextFunc
return res.status(401).json({ error: 'Unauthorized: missing credentials' })
}
let token: string | undefined
// Prefer Bearer if wellformed
if (auth) {
const trimmed = auth.trim()
const bearerPrefix = /^Bearer\s+/i
if (bearerPrefix.test(trimmed)) {
const candidate = trimmed.replace(bearerPrefix, '').trim()
if (!candidate) {
return res.status(401).json({ error: 'Unauthorized: empty bearer token' })
}
token = candidate
}
}
// Fallback to x-api-key if token still not resolved
if (!token && xApiKey) {
if (!xApiKey.trim()) {
return res.status(401).json({ error: 'Unauthorized: empty x-api-key' })
}
token = xApiKey.trim()
}
if (!token) {
// At this point we had at least one header, but none yielded a usable token
return res.status(401).json({ error: 'Unauthorized: invalid credentials format' })
}
const { apiKey } = await config.get()
if (!apiKey) {
// If server not configured, treat as forbidden (or could be 500). Choose 403 to avoid leaking config state.
return res.status(403).json({ error: 'Forbidden' })
}
// Timing-safe compare when lengths match, else immediate forbidden
if (token.length !== apiKey.length) {
return res.status(403).json({ error: 'Forbidden' })
// Check API key first (priority)
if (xApiKey) {
const trimmedApiKey = xApiKey.trim()
if (!trimmedApiKey) {
return res.status(401).json({ error: 'Unauthorized: empty x-api-key' })
}
if (isValidToken(trimmedApiKey, apiKey)) {
return next()
} else {
return res.status(403).json({ error: 'Forbidden' })
}
}
const tokenBuf = Buffer.from(token)
const keyBuf = Buffer.from(apiKey)
if (!crypto.timingSafeEqual(tokenBuf, keyBuf)) {
return res.status(403).json({ error: 'Forbidden' })
// Fallback to Bearer token
if (auth) {
const trimmed = auth.trim()
const bearerPrefix = /^Bearer\s+/i
if (!bearerPrefix.test(trimmed)) {
return res.status(401).json({ error: 'Unauthorized: invalid authorization format' })
}
const token = trimmed.replace(bearerPrefix, '').trim()
if (!token) {
return res.status(401).json({ error: 'Unauthorized: empty bearer token' })
}
if (isValidToken(token, apiKey)) {
return next()
} else {
return res.status(403).json({ error: 'Forbidden' })
}
}
return next()
return res.status(401).json({ error: 'Unauthorized: invalid credentials format' })
}

View File

@@ -6,7 +6,7 @@ const logger = loggerService.withContext('ApiServerErrorHandler')
// oxlint-disable-next-line @typescript-eslint/no-unused-vars
export const errorHandler = (err: Error, _req: Request, res: Response, _next: NextFunction) => {
logger.error('API Server Error:', err)
logger.error('API server error', { error: err })
// Don't expose internal errors in production
const isDev = process.env.NODE_ENV === 'development'

View File

@@ -197,10 +197,11 @@ export function setupOpenAPIDocumentation(app: Express) {
})
)
logger.info('OpenAPI documentation setup complete')
logger.info('Documentation available at /api-docs')
logger.info('OpenAPI spec available at /api-docs.json')
logger.info('OpenAPI documentation ready', {
docsPath: '/api-docs',
specPath: '/api-docs.json'
})
} catch (error) {
logger.error('Failed to setup OpenAPI documentation:', error as Error)
logger.error('Failed to setup OpenAPI documentation', { error })
}
}

View File

@@ -0,0 +1,567 @@
import { loggerService } from '@logger'
import { AgentModelValidationError, agentService, sessionService } from '@main/services/agents'
import { ListAgentsResponse, type ReplaceAgentRequest, type UpdateAgentRequest } from '@types'
import { Request, Response } from 'express'
import type { ValidationRequest } from '../validators/zodValidator'
const logger = loggerService.withContext('ApiServerAgentsHandlers')
const modelValidationErrorBody = (error: AgentModelValidationError) => ({
error: {
message: `Invalid ${error.context.field}: ${error.detail.message}`,
type: 'invalid_request_error',
code: error.detail.code
}
})
/**
* @swagger
* /v1/agents:
* post:
* summary: Create a new agent
* description: Creates a new autonomous agent with the specified configuration and automatically
* provisions an initial session that mirrors the agent's settings.
* tags: [Agents]
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/CreateAgentRequest'
* responses:
* 201:
* description: Agent created successfully
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/AgentEntity'
* 400:
* description: Validation error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Internal server error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export const createAgent = async (req: Request, res: Response): Promise<Response> => {
try {
logger.debug('Creating agent')
logger.debug('Agent payload', { body: req.body })
const agent = await agentService.createAgent(req.body)
try {
logger.info('Agent created', { agentId: agent.id })
logger.debug('Creating default session for agent', { agentId: agent.id })
await sessionService.createSession(agent.id, {})
logger.info('Default session created for agent', { agentId: agent.id })
return res.status(201).json(agent)
} catch (sessionError: any) {
logger.error('Failed to create default session for new agent, rolling back agent creation', {
agentId: agent.id,
error: sessionError
})
try {
await agentService.deleteAgent(agent.id)
} catch (rollbackError: any) {
logger.error('Failed to roll back agent after session creation failure', {
agentId: agent.id,
error: rollbackError
})
}
return res.status(500).json({
error: {
message: `Failed to create default session for agent: ${sessionError.message}`,
type: 'internal_error',
code: 'agent_session_creation_failed'
}
})
}
} catch (error: any) {
if (error instanceof AgentModelValidationError) {
logger.warn('Agent model validation error during create', {
agentType: error.context.agentType,
field: error.context.field,
model: error.context.model,
detail: error.detail
})
return res.status(400).json(modelValidationErrorBody(error))
}
logger.error('Error creating agent', { error })
return res.status(500).json({
error: {
message: `Failed to create agent: ${error.message}`,
type: 'internal_error',
code: 'agent_creation_failed'
}
})
}
}
/**
* @swagger
* /v1/agents:
* get:
* summary: List all agents
* description: Retrieves a paginated list of all agents
* tags: [Agents]
* parameters:
* - in: query
* name: limit
* schema:
* type: integer
* minimum: 1
* maximum: 100
* default: 20
* description: Number of agents to return
* - in: query
* name: offset
* schema:
* type: integer
* minimum: 0
* default: 0
* description: Number of agents to skip
* responses:
* 200:
* description: List of agents
* content:
* application/json:
* schema:
* type: object
* properties:
* data:
* type: array
* items:
* $ref: '#/components/schemas/AgentEntity'
* total:
* type: integer
* description: Total number of agents
* limit:
* type: integer
* description: Number of agents returned
* offset:
* type: integer
* description: Number of agents skipped
* 400:
* description: Validation error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Internal server error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export const listAgents = async (req: Request, res: Response): Promise<Response> => {
try {
const limit = req.query.limit ? parseInt(req.query.limit as string) : 20
const offset = req.query.offset ? parseInt(req.query.offset as string) : 0
logger.debug('Listing agents', { limit, offset })
const result = await agentService.listAgents({ limit, offset })
logger.info('Agents listed', {
returned: result.agents.length,
total: result.total,
limit,
offset
})
return res.json({
data: result.agents,
total: result.total,
limit,
offset
} satisfies ListAgentsResponse)
} catch (error: any) {
logger.error('Error listing agents', { error })
return res.status(500).json({
error: {
message: 'Failed to list agents',
type: 'internal_error',
code: 'agent_list_failed'
}
})
}
}
/**
* @swagger
* /v1/agents/{agentId}:
* get:
* summary: Get agent by ID
* description: Retrieves a specific agent by its ID
* tags: [Agents]
* parameters:
* - in: path
* name: agentId
* required: true
* schema:
* type: string
* description: Agent ID
* responses:
* 200:
* description: Agent details
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/AgentEntity'
* 404:
* description: Agent not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Internal server error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export const getAgent = async (req: Request, res: Response): Promise<Response> => {
try {
const { agentId } = req.params
logger.debug('Getting agent', { agentId })
const agent = await agentService.getAgent(agentId)
if (!agent) {
logger.warn('Agent not found', { agentId })
return res.status(404).json({
error: {
message: 'Agent not found',
type: 'not_found',
code: 'agent_not_found'
}
})
}
logger.info('Agent retrieved', { agentId })
return res.json(agent)
} catch (error: any) {
logger.error('Error getting agent', { error, agentId: req.params.agentId })
return res.status(500).json({
error: {
message: 'Failed to get agent',
type: 'internal_error',
code: 'agent_get_failed'
}
})
}
}
/**
* @swagger
* /v1/agents/{agentId}:
* put:
* summary: Update agent
* description: Updates an existing agent with the provided data
* tags: [Agents]
* parameters:
* - in: path
* name: agentId
* required: true
* schema:
* type: string
* description: Agent ID
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/CreateAgentRequest'
* responses:
* 200:
* description: Agent updated successfully
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/AgentEntity'
* 400:
* description: Validation error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Agent not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Internal server error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export const updateAgent = async (req: Request, res: Response): Promise<Response> => {
const { agentId } = req.params
try {
logger.debug('Updating agent', { agentId })
logger.debug('Replace payload', { body: req.body })
const { validatedBody } = req as ValidationRequest
const replacePayload = (validatedBody ?? {}) as ReplaceAgentRequest
const agent = await agentService.updateAgent(agentId, replacePayload, { replace: true })
if (!agent) {
logger.warn('Agent not found for update', { agentId })
return res.status(404).json({
error: {
message: 'Agent not found',
type: 'not_found',
code: 'agent_not_found'
}
})
}
logger.info('Agent updated', { agentId })
return res.json(agent)
} catch (error: any) {
if (error instanceof AgentModelValidationError) {
logger.warn('Agent model validation error during update', {
agentId,
agentType: error.context.agentType,
field: error.context.field,
model: error.context.model,
detail: error.detail
})
return res.status(400).json(modelValidationErrorBody(error))
}
logger.error('Error updating agent', { error, agentId })
return res.status(500).json({
error: {
message: 'Failed to update agent: ' + error.message,
type: 'internal_error',
code: 'agent_update_failed'
}
})
}
}
/**
* @swagger
* /v1/agents/{agentId}:
* patch:
* summary: Partially update agent
* description: Partially updates an existing agent with only the provided fields
* tags: [Agents]
* parameters:
* - in: path
* name: agentId
* required: true
* schema:
* type: string
* description: Agent ID
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* name:
* type: string
* description: Agent name
* description:
* type: string
* description: Agent description
* avatar:
* type: string
* description: Agent avatar URL
* instructions:
* type: string
* description: System prompt/instructions
* model:
* type: string
* description: Main model ID
* plan_model:
* type: string
* description: Optional planning model ID
* small_model:
* type: string
* description: Optional small/fast model ID
* tools:
* type: array
* items:
* type: string
* description: Tools
* mcps:
* type: array
* items:
* type: string
* description: MCP tool IDs
* knowledges:
* type: array
* items:
* type: string
* description: Knowledge base IDs
* configuration:
* type: object
* description: Extensible settings
* accessible_paths:
* type: array
* items:
* type: string
* description: Accessible directory paths
* permission_mode:
* type: string
* enum: [readOnly, acceptEdits, bypassPermissions]
* description: Permission mode
* max_steps:
* type: integer
* description: Maximum steps the agent can take
* description: Only include the fields you want to update
* responses:
* 200:
* description: Agent updated successfully
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/AgentEntity'
* 400:
* description: Validation error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 404:
* description: Agent not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Internal server error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export const patchAgent = async (req: Request, res: Response): Promise<Response> => {
const { agentId } = req.params
try {
logger.debug('Partially updating agent', { agentId })
logger.debug('Patch payload', { body: req.body })
const { validatedBody } = req as ValidationRequest
const updatePayload = (validatedBody ?? {}) as UpdateAgentRequest
const agent = await agentService.updateAgent(agentId, updatePayload)
if (!agent) {
logger.warn('Agent not found for partial update', { agentId })
return res.status(404).json({
error: {
message: 'Agent not found',
type: 'not_found',
code: 'agent_not_found'
}
})
}
logger.info('Agent patched', { agentId })
return res.json(agent)
} catch (error: any) {
if (error instanceof AgentModelValidationError) {
logger.warn('Agent model validation error during partial update', {
agentId,
agentType: error.context.agentType,
field: error.context.field,
model: error.context.model,
detail: error.detail
})
return res.status(400).json(modelValidationErrorBody(error))
}
logger.error('Error partially updating agent', { error, agentId })
return res.status(500).json({
error: {
message: `Failed to partially update agent: ${error.message}`,
type: 'internal_error',
code: 'agent_patch_failed'
}
})
}
}
/**
* @swagger
* /v1/agents/{agentId}:
* delete:
* summary: Delete agent
* description: Deletes an agent and all associated sessions and logs
* tags: [Agents]
* parameters:
* - in: path
* name: agentId
* required: true
* schema:
* type: string
* description: Agent ID
* responses:
* 204:
* description: Agent deleted successfully
* 404:
* description: Agent not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Internal server error
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
export const deleteAgent = async (req: Request, res: Response): Promise<Response> => {
try {
const { agentId } = req.params
logger.debug('Deleting agent', { agentId })
const deleted = await agentService.deleteAgent(agentId)
if (!deleted) {
logger.warn('Agent not found for deletion', { agentId })
return res.status(404).json({
error: {
message: 'Agent not found',
type: 'not_found',
code: 'agent_not_found'
}
})
}
logger.info('Agent deleted', { agentId })
return res.status(204).send()
} catch (error: any) {
logger.error('Error deleting agent', { error, agentId: req.params.agentId })
return res.status(500).json({
error: {
message: 'Failed to delete agent',
type: 'internal_error',
code: 'agent_delete_failed'
}
})
}
}

View File

@@ -0,0 +1,3 @@
export * as agentHandlers from './agents'
export * as messageHandlers from './messages'
export * as sessionHandlers from './sessions'

View File

@@ -0,0 +1,317 @@
import { loggerService } from '@logger'
import { MESSAGE_STREAM_TIMEOUT_MS } from '@main/apiServer/config/timeouts'
import { createStreamAbortController, STREAM_TIMEOUT_REASON } from '@main/apiServer/utils/createStreamAbortController'
import { agentService, sessionMessageService, sessionService } from '@main/services/agents'
import { Request, Response } from 'express'
const logger = loggerService.withContext('ApiServerMessagesHandlers')
// Helper function to verify agent and session exist and belong together
const verifyAgentAndSession = async (agentId: string, sessionId: string) => {
const agentExists = await agentService.agentExists(agentId)
if (!agentExists) {
throw { status: 404, code: 'agent_not_found', message: 'Agent not found' }
}
const session = await sessionService.getSession(agentId, sessionId)
if (!session) {
throw { status: 404, code: 'session_not_found', message: 'Session not found' }
}
if (session.agent_id !== agentId) {
throw { status: 404, code: 'session_not_found', message: 'Session not found for this agent' }
}
return session
}
export const createMessage = async (req: Request, res: Response): Promise<void> => {
let clearAbortTimeout: (() => void) | undefined
try {
const { agentId, sessionId } = req.params
const session = await verifyAgentAndSession(agentId, sessionId)
const messageData = req.body
logger.info('Creating streaming message', { agentId, sessionId })
logger.debug('Streaming message payload', { messageData })
// Set SSE headers
res.setHeader('Content-Type', 'text/event-stream')
res.setHeader('Cache-Control', 'no-cache')
res.setHeader('Connection', 'keep-alive')
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Headers', 'Cache-Control')
const {
abortController,
registerAbortHandler,
clearAbortTimeout: helperClearAbortTimeout
} = createStreamAbortController({
timeoutMs: MESSAGE_STREAM_TIMEOUT_MS
})
clearAbortTimeout = helperClearAbortTimeout
const { stream, completion } = await sessionMessageService.createSessionMessage(
session,
messageData,
abortController
)
const reader = stream.getReader()
// Track stream lifecycle so we keep the SSE connection open until persistence finishes
let responseEnded = false
let streamFinished = false
const cleanupAbortTimeout = () => {
clearAbortTimeout?.()
}
const finalizeResponse = () => {
if (responseEnded) {
return
}
if (!streamFinished) {
return
}
responseEnded = true
cleanupAbortTimeout()
try {
// res.write('data: {"type":"finish"}\n\n')
res.write('data: [DONE]\n\n')
} catch (writeError) {
logger.error('Error writing final sentinel to SSE stream', { error: writeError as Error })
}
res.end()
}
/**
* Client Disconnect Detection for Server-Sent Events (SSE)
*
* We monitor multiple HTTP events to reliably detect when a client disconnects
* from the streaming response. This is crucial for:
* - Aborting long-running Claude Code processes
* - Cleaning up resources and preventing memory leaks
* - Avoiding orphaned processes
*
* Event Priority & Behavior:
* 1. res.on('close') - Most common for SSE client disconnects (browser tab close, curl Ctrl+C)
* 2. req.on('aborted') - Explicit request abortion
* 3. req.on('close') - Request object closure (less common with SSE)
*
* When any disconnect event fires, we:
* - Abort the Claude Code SDK process via abortController
* - Clean up event listeners to prevent memory leaks
* - Mark the response as ended to prevent further writes
*/
registerAbortHandler((abortReason) => {
cleanupAbortTimeout()
if (responseEnded) return
responseEnded = true
if (abortReason === STREAM_TIMEOUT_REASON) {
logger.error('Streaming message timeout', { agentId, sessionId })
try {
res.write(
`data: ${JSON.stringify({
type: 'error',
error: {
message: 'Stream timeout',
type: 'timeout_error',
code: 'stream_timeout'
}
})}\n\n`
)
} catch (writeError) {
logger.error('Error writing timeout to SSE stream', { error: writeError })
}
} else if (abortReason === 'Client disconnected') {
logger.info('Streaming client disconnected', { agentId, sessionId })
} else {
logger.warn('Streaming aborted', { agentId, sessionId, reason: abortReason })
}
reader.cancel(abortReason ?? 'stream aborted').catch(() => {})
if (!res.headersSent) {
res.setHeader('Content-Type', 'text/event-stream')
res.setHeader('Cache-Control', 'no-cache')
res.setHeader('Connection', 'keep-alive')
}
if (!res.writableEnded) {
res.end()
}
})
const handleDisconnect = () => {
if (abortController.signal.aborted) return
abortController.abort('Client disconnected')
}
req.on('close', handleDisconnect)
req.on('aborted', handleDisconnect)
res.on('close', handleDisconnect)
const pumpStream = async () => {
try {
while (!responseEnded) {
const { done, value } = await reader.read()
if (done) {
break
}
res.write(`data: ${JSON.stringify(value)}\n\n`)
}
streamFinished = true
finalizeResponse()
} catch (error) {
if (responseEnded) return
logger.error('Error reading agent stream', { error })
try {
res.write(
`data: ${JSON.stringify({
type: 'error',
error: {
message: (error as Error).message || 'Stream processing error',
type: 'stream_error',
code: 'stream_processing_failed'
}
})}\n\n`
)
} catch (writeError) {
logger.error('Error writing stream error to SSE', { error: writeError })
}
responseEnded = true
cleanupAbortTimeout()
res.end()
}
}
pumpStream().catch((error) => {
logger.error('Pump stream failure', { error })
})
completion
.then(() => {
streamFinished = true
finalizeResponse()
})
.catch((error) => {
if (responseEnded) return
logger.error('Streaming message error', { agentId, sessionId, error })
try {
res.write(
`data: ${JSON.stringify({
type: 'error',
error: {
message: (error as { message?: string })?.message || 'Stream processing error',
type: 'stream_error',
code: 'stream_processing_failed'
}
})}\n\n`
)
} catch (writeError) {
logger.error('Error writing completion error to SSE stream', { error: writeError })
}
responseEnded = true
cleanupAbortTimeout()
res.end()
})
// Clear timeout when response ends
res.on('close', cleanupAbortTimeout)
res.on('finish', cleanupAbortTimeout)
} catch (error: any) {
clearAbortTimeout?.()
logger.error('Error in streaming message handler', {
error,
agentId: req.params.agentId,
sessionId: req.params.sessionId
})
// Send error as SSE if possible
if (!res.headersSent) {
res.setHeader('Content-Type', 'text/event-stream')
res.setHeader('Cache-Control', 'no-cache')
res.setHeader('Connection', 'keep-alive')
}
try {
const errorResponse = {
type: 'error',
error: {
message: error.status ? error.message : 'Failed to create streaming message',
type: error.status ? 'not_found' : 'internal_error',
code: error.status ? error.code : 'stream_creation_failed'
}
}
res.write(`data: ${JSON.stringify(errorResponse)}\n\n`)
} catch (writeError) {
logger.error('Error writing initial error to SSE stream', { error: writeError })
}
res.end()
}
}
export const deleteMessage = async (req: Request, res: Response): Promise<Response> => {
try {
const { agentId, sessionId, messageId: messageIdParam } = req.params
const messageId = Number(messageIdParam)
await verifyAgentAndSession(agentId, sessionId)
const deleted = await sessionMessageService.deleteSessionMessage(sessionId, messageId)
if (!deleted) {
logger.warn('Session message not found', { agentId, sessionId, messageId })
return res.status(404).json({
error: {
message: 'Message not found for this session',
type: 'not_found',
code: 'session_message_not_found'
}
})
}
logger.info('Session message deleted', { agentId, sessionId, messageId })
return res.status(204).send()
} catch (error: any) {
if (error?.status === 404) {
logger.warn('Delete message failed - missing resource', {
agentId: req.params.agentId,
sessionId: req.params.sessionId,
messageId: req.params.messageId,
error
})
return res.status(404).json({
error: {
message: error.message,
type: 'not_found',
code: error.code ?? 'session_message_not_found'
}
})
}
logger.error('Error deleting session message', {
error,
agentId: req.params.agentId,
sessionId: req.params.sessionId,
messageId: Number(req.params.messageId)
})
return res.status(500).json({
error: {
message: 'Failed to delete session message',
type: 'internal_error',
code: 'session_message_delete_failed'
}
})
}
}

View File

@@ -0,0 +1,366 @@
import { loggerService } from '@logger'
import { AgentModelValidationError, sessionMessageService, sessionService } from '@main/services/agents'
import { ListAgentSessionsResponse, type ReplaceSessionRequest, UpdateSessionResponse } from '@types'
import { Request, Response } from 'express'
import type { ValidationRequest } from '../validators/zodValidator'
const logger = loggerService.withContext('ApiServerSessionsHandlers')
const modelValidationErrorBody = (error: AgentModelValidationError) => ({
error: {
message: `Invalid ${error.context.field}: ${error.detail.message}`,
type: 'invalid_request_error',
code: error.detail.code
}
})
export const createSession = async (req: Request, res: Response): Promise<Response> => {
const { agentId } = req.params
try {
const sessionData = req.body
logger.debug('Creating new session', { agentId })
logger.debug('Session payload', { sessionData })
const session = await sessionService.createSession(agentId, sessionData)
logger.info('Session created', { agentId, sessionId: session?.id })
return res.status(201).json(session)
} catch (error: any) {
if (error instanceof AgentModelValidationError) {
logger.warn('Session model validation error during create', {
agentId,
agentType: error.context.agentType,
field: error.context.field,
model: error.context.model,
detail: error.detail
})
return res.status(400).json(modelValidationErrorBody(error))
}
logger.error('Error creating session', { error, agentId })
return res.status(500).json({
error: {
message: `Failed to create session: ${error.message}`,
type: 'internal_error',
code: 'session_creation_failed'
}
})
}
}
export const listSessions = async (req: Request, res: Response): Promise<Response> => {
const { agentId } = req.params
try {
const limit = req.query.limit ? parseInt(req.query.limit as string) : 20
const offset = req.query.offset ? parseInt(req.query.offset as string) : 0
const status = req.query.status as any
logger.debug('Listing agent sessions', { agentId, limit, offset, status })
const result = await sessionService.listSessions(agentId, { limit, offset })
logger.info('Agent sessions listed', {
agentId,
returned: result.sessions.length,
total: result.total,
limit,
offset
})
return res.json({
data: result.sessions,
total: result.total,
limit,
offset
})
} catch (error: any) {
logger.error('Error listing sessions', { error, agentId })
return res.status(500).json({
error: {
message: 'Failed to list sessions',
type: 'internal_error',
code: 'session_list_failed'
}
})
}
}
export const getSession = async (req: Request, res: Response): Promise<Response> => {
try {
const { agentId, sessionId } = req.params
logger.debug('Getting session', { agentId, sessionId })
const session = await sessionService.getSession(agentId, sessionId)
if (!session) {
logger.warn('Session not found', { agentId, sessionId })
return res.status(404).json({
error: {
message: 'Session not found',
type: 'not_found',
code: 'session_not_found'
}
})
}
// // Verify session belongs to the agent
// logger.warn(`Session ${sessionId} does not belong to agent ${agentId}`)
// return res.status(404).json({
// error: {
// message: 'Session not found for this agent',
// type: 'not_found',
// code: 'session_not_found'
// }
// })
// }
// Fetch session messages
logger.debug('Fetching session messages', { sessionId })
const { messages } = await sessionMessageService.listSessionMessages(sessionId)
// Add messages to session
const sessionWithMessages = {
...session,
messages: messages
}
logger.info('Session retrieved', { agentId, sessionId, messageCount: messages.length })
return res.json(sessionWithMessages)
} catch (error: any) {
logger.error('Error getting session', { error, agentId: req.params.agentId, sessionId: req.params.sessionId })
return res.status(500).json({
error: {
message: 'Failed to get session',
type: 'internal_error',
code: 'session_get_failed'
}
})
}
}
export const updateSession = async (req: Request, res: Response): Promise<Response> => {
const { agentId, sessionId } = req.params
try {
logger.debug('Updating session', { agentId, sessionId })
logger.debug('Replace payload', { body: req.body })
// First check if session exists and belongs to agent
const existingSession = await sessionService.getSession(agentId, sessionId)
if (!existingSession || existingSession.agent_id !== agentId) {
logger.warn('Session not found for update', { agentId, sessionId })
return res.status(404).json({
error: {
message: 'Session not found for this agent',
type: 'not_found',
code: 'session_not_found'
}
})
}
const { validatedBody } = req as ValidationRequest
const replacePayload = (validatedBody ?? {}) as ReplaceSessionRequest
const session = await sessionService.updateSession(agentId, sessionId, replacePayload)
if (!session) {
logger.warn('Session missing during update', { agentId, sessionId })
return res.status(404).json({
error: {
message: 'Session not found',
type: 'not_found',
code: 'session_not_found'
}
})
}
logger.info('Session updated', { agentId, sessionId })
return res.json(session satisfies UpdateSessionResponse)
} catch (error: any) {
if (error instanceof AgentModelValidationError) {
logger.warn('Session model validation error during update', {
agentId,
sessionId,
agentType: error.context.agentType,
field: error.context.field,
model: error.context.model,
detail: error.detail
})
return res.status(400).json(modelValidationErrorBody(error))
}
logger.error('Error updating session', { error, agentId, sessionId })
return res.status(500).json({
error: {
message: `Failed to update session: ${error.message}`,
type: 'internal_error',
code: 'session_update_failed'
}
})
}
}
export const patchSession = async (req: Request, res: Response): Promise<Response> => {
const { agentId, sessionId } = req.params
try {
logger.debug('Patching session', { agentId, sessionId })
logger.debug('Patch payload', { body: req.body })
// First check if session exists and belongs to agent
const existingSession = await sessionService.getSession(agentId, sessionId)
if (!existingSession || existingSession.agent_id !== agentId) {
logger.warn('Session not found for patch', { agentId, sessionId })
return res.status(404).json({
error: {
message: 'Session not found for this agent',
type: 'not_found',
code: 'session_not_found'
}
})
}
const updateSession = { ...existingSession, ...req.body }
const session = await sessionService.updateSession(agentId, sessionId, updateSession)
if (!session) {
logger.warn('Session missing while patching', { agentId, sessionId })
return res.status(404).json({
error: {
message: 'Session not found',
type: 'not_found',
code: 'session_not_found'
}
})
}
logger.info('Session patched', { agentId, sessionId })
return res.json(session)
} catch (error: any) {
if (error instanceof AgentModelValidationError) {
logger.warn('Session model validation error during patch', {
agentId,
sessionId,
agentType: error.context.agentType,
field: error.context.field,
model: error.context.model,
detail: error.detail
})
return res.status(400).json(modelValidationErrorBody(error))
}
logger.error('Error patching session', { error, agentId, sessionId })
return res.status(500).json({
error: {
message: `Failed to patch session, ${error.message}`,
type: 'internal_error',
code: 'session_patch_failed'
}
})
}
}
export const deleteSession = async (req: Request, res: Response): Promise<Response> => {
try {
const { agentId, sessionId } = req.params
logger.debug('Deleting session', { agentId, sessionId })
// First check if session exists and belongs to agent
const existingSession = await sessionService.getSession(agentId, sessionId)
if (!existingSession || existingSession.agent_id !== agentId) {
logger.warn('Session not found for deletion', { agentId, sessionId })
return res.status(404).json({
error: {
message: 'Session not found for this agent',
type: 'not_found',
code: 'session_not_found'
}
})
}
const deleted = await sessionService.deleteSession(agentId, sessionId)
if (!deleted) {
logger.warn('Session missing during delete', { agentId, sessionId })
return res.status(404).json({
error: {
message: 'Session not found',
type: 'not_found',
code: 'session_not_found'
}
})
}
logger.info('Session deleted', { agentId, sessionId })
const { total } = await sessionService.listSessions(agentId, { limit: 1 })
if (total === 0) {
logger.info('No remaining sessions, creating default', { agentId })
try {
const fallbackSession = await sessionService.createSession(agentId, {})
logger.info('Default session created after delete', {
agentId,
sessionId: fallbackSession?.id
})
} catch (recoveryError: any) {
logger.error('Failed to recreate session after deleting last session', {
agentId,
error: recoveryError
})
return res.status(500).json({
error: {
message: `Failed to recreate session after deletion: ${recoveryError.message}`,
type: 'internal_error',
code: 'session_recovery_failed'
}
})
}
}
return res.status(204).send()
} catch (error: any) {
logger.error('Error deleting session', { error, agentId: req.params.agentId, sessionId: req.params.sessionId })
return res.status(500).json({
error: {
message: 'Failed to delete session',
type: 'internal_error',
code: 'session_delete_failed'
}
})
}
}
// Convenience endpoints for sessions without agent context
export const listAllSessions = async (req: Request, res: Response): Promise<Response> => {
try {
const limit = req.query.limit ? parseInt(req.query.limit as string) : 20
const offset = req.query.offset ? parseInt(req.query.offset as string) : 0
const status = req.query.status as any
logger.debug('Listing all sessions', { limit, offset, status })
const result = await sessionService.listSessions(undefined, { limit, offset })
logger.info('Sessions listed', {
returned: result.sessions.length,
total: result.total,
limit,
offset
})
return res.json({
data: result.sessions,
total: result.total,
limit,
offset
} satisfies ListAgentSessionsResponse)
} catch (error: any) {
logger.error('Error listing all sessions', { error })
return res.status(500).json({
error: {
message: 'Failed to list sessions',
type: 'internal_error',
code: 'session_list_failed'
}
})
}
}

View File

@@ -0,0 +1,965 @@
import express from 'express'
import { agentHandlers, messageHandlers, sessionHandlers } from './handlers'
import { checkAgentExists, handleValidationErrors } from './middleware'
import {
validateAgent,
validateAgentId,
validateAgentReplace,
validateAgentUpdate,
validatePagination,
validateSession,
validateSessionId,
validateSessionMessage,
validateSessionMessageId,
validateSessionReplace,
validateSessionUpdate
} from './validators'
// Create main agents router
const agentsRouter = express.Router()
/**
* @swagger
* components:
* schemas:
* PermissionMode:
* type: string
* enum: [default, acceptEdits, bypassPermissions, plan]
* description: Permission mode for agent operations
*
* AgentType:
* type: string
* enum: [claude-code]
* description: Type of agent
*
* AgentConfiguration:
* type: object
* properties:
* permission_mode:
* $ref: '#/components/schemas/PermissionMode'
* default: default
* max_turns:
* type: integer
* default: 10
* description: Maximum number of interaction turns
* additionalProperties: true
*
* AgentBase:
* type: object
* properties:
* name:
* type: string
* description: Agent name
* description:
* type: string
* description: Agent description
* accessible_paths:
* type: array
* items:
* type: string
* description: Array of directory paths the agent can access
* instructions:
* type: string
* description: System prompt/instructions
* model:
* type: string
* description: Main model ID
* plan_model:
* type: string
* description: Optional planning model ID
* small_model:
* type: string
* description: Optional small/fast model ID
* mcps:
* type: array
* items:
* type: string
* description: Array of MCP tool IDs
* allowed_tools:
* type: array
* items:
* type: string
* description: Array of allowed tool IDs (whitelist)
* configuration:
* $ref: '#/components/schemas/AgentConfiguration'
* required:
* - model
* - accessible_paths
*
* AgentEntity:
* allOf:
* - $ref: '#/components/schemas/AgentBase'
* - type: object
* properties:
* id:
* type: string
* description: Unique agent identifier
* type:
* $ref: '#/components/schemas/AgentType'
* created_at:
* type: string
* format: date-time
* description: ISO timestamp of creation
* updated_at:
* type: string
* format: date-time
* description: ISO timestamp of last update
* required:
* - id
* - type
* - created_at
* - updated_at
* CreateAgentRequest:
* allOf:
* - $ref: '#/components/schemas/AgentBase'
* - type: object
* properties:
* type:
* $ref: '#/components/schemas/AgentType'
* name:
* type: string
* minLength: 1
* description: Agent name (required)
* model:
* type: string
* minLength: 1
* description: Main model ID (required)
* required:
* - type
* - name
* - model
*
* UpdateAgentRequest:
* type: object
* properties:
* name:
* type: string
* description: Agent name
* description:
* type: string
* description: Agent description
* accessible_paths:
* type: array
* items:
* type: string
* description: Array of directory paths the agent can access
* instructions:
* type: string
* description: System prompt/instructions
* model:
* type: string
* description: Main model ID
* plan_model:
* type: string
* description: Optional planning model ID
* small_model:
* type: string
* description: Optional small/fast model ID
* mcps:
* type: array
* items:
* type: string
* description: Array of MCP tool IDs
* allowed_tools:
* type: array
* items:
* type: string
* description: Array of allowed tool IDs (whitelist)
* configuration:
* $ref: '#/components/schemas/AgentConfiguration'
* description: Partial update - all fields are optional
*
* ReplaceAgentRequest:
* $ref: '#/components/schemas/AgentBase'
*
* SessionEntity:
* allOf:
* - $ref: '#/components/schemas/AgentBase'
* - type: object
* properties:
* id:
* type: string
* description: Unique session identifier
* agent_id:
* type: string
* description: Primary agent ID for the session
* agent_type:
* $ref: '#/components/schemas/AgentType'
* created_at:
* type: string
* format: date-time
* description: ISO timestamp of creation
* updated_at:
* type: string
* format: date-time
* description: ISO timestamp of last update
* required:
* - id
* - agent_id
* - agent_type
* - created_at
* - updated_at
*
* CreateSessionRequest:
* allOf:
* - $ref: '#/components/schemas/AgentBase'
* - type: object
* properties:
* model:
* type: string
* minLength: 1
* description: Main model ID (required)
* required:
* - model
*
* UpdateSessionRequest:
* type: object
* properties:
* name:
* type: string
* description: Session name
* description:
* type: string
* description: Session description
* accessible_paths:
* type: array
* items:
* type: string
* description: Array of directory paths the agent can access
* instructions:
* type: string
* description: System prompt/instructions
* model:
* type: string
* description: Main model ID
* plan_model:
* type: string
* description: Optional planning model ID
* small_model:
* type: string
* description: Optional small/fast model ID
* mcps:
* type: array
* items:
* type: string
* description: Array of MCP tool IDs
* allowed_tools:
* type: array
* items:
* type: string
* description: Array of allowed tool IDs (whitelist)
* configuration:
* $ref: '#/components/schemas/AgentConfiguration'
* description: Partial update - all fields are optional
*
* ReplaceSessionRequest:
* allOf:
* - $ref: '#/components/schemas/AgentBase'
* - type: object
* properties:
* model:
* type: string
* minLength: 1
* description: Main model ID (required)
* required:
* - model
*
* CreateSessionMessageRequest:
* type: object
* properties:
* content:
* type: string
* minLength: 1
* description: Message content
* required:
* - content
*
* PaginationQuery:
* type: object
* properties:
* limit:
* type: integer
* minimum: 1
* maximum: 100
* default: 20
* description: Number of items to return
* offset:
* type: integer
* minimum: 0
* default: 0
* description: Number of items to skip
* status:
* type: string
* enum: [idle, running, completed, failed, stopped]
* description: Filter by session status
*
* ListAgentsResponse:
* type: object
* properties:
* agents:
* type: array
* items:
* $ref: '#/components/schemas/AgentEntity'
* total:
* type: integer
* description: Total number of agents
* limit:
* type: integer
* description: Number of items returned
* offset:
* type: integer
* description: Number of items skipped
* required:
* - agents
* - total
* - limit
* - offset
*
* ListSessionsResponse:
* type: object
* properties:
* sessions:
* type: array
* items:
* $ref: '#/components/schemas/SessionEntity'
* total:
* type: integer
* description: Total number of sessions
* limit:
* type: integer
* description: Number of items returned
* offset:
* type: integer
* description: Number of items skipped
* required:
* - sessions
* - total
* - limit
* - offset
*
* ErrorResponse:
* type: object
* properties:
* error:
* type: object
* properties:
* message:
* type: string
* description: Error message
* type:
* type: string
* description: Error type
* code:
* type: string
* description: Error code
* required:
* - message
* - type
* - code
* required:
* - error
*/
/**
* @swagger
* /agents:
* post:
* summary: Create a new agent
* tags: [Agents]
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/CreateAgentRequest'
* responses:
* 201:
* description: Agent created successfully
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/AgentEntity'
* 400:
* description: Invalid request body
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
*/
// Agent CRUD routes
agentsRouter.post('/', validateAgent, handleValidationErrors, agentHandlers.createAgent)
/**
* @swagger
* /agents:
* get:
* summary: List all agents with pagination
* tags: [Agents]
* parameters:
* - in: query
* name: limit
* schema:
* type: integer
* minimum: 1
* maximum: 100
* default: 20
* description: Number of agents to return
* - in: query
* name: offset
* schema:
* type: integer
* minimum: 0
* default: 0
* description: Number of agents to skip
* - in: query
* name: status
* schema:
* type: string
* enum: [idle, running, completed, failed, stopped]
* description: Filter by agent status
* responses:
* 200:
* description: List of agents
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ListAgentsResponse'
*/
agentsRouter.get('/', validatePagination, handleValidationErrors, agentHandlers.listAgents)
/**
* @swagger
* /agents/{agentId}:
* get:
* summary: Get agent by ID
* tags: [Agents]
* parameters:
* - in: path
* name: agentId
* required: true
* schema:
* type: string
* description: Agent ID
* responses:
* 200:
* description: Agent details
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/AgentEntity'
* 404:
* description: Agent not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
*/
agentsRouter.get('/:agentId', validateAgentId, handleValidationErrors, agentHandlers.getAgent)
/**
* @swagger
* /agents/{agentId}:
* put:
* summary: Replace agent (full update)
* tags: [Agents]
* parameters:
* - in: path
* name: agentId
* required: true
* schema:
* type: string
* description: Agent ID
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ReplaceAgentRequest'
* responses:
* 200:
* description: Agent updated successfully
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/AgentEntity'
* 400:
* description: Invalid request body
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
* 404:
* description: Agent not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
*/
agentsRouter.put('/:agentId', validateAgentId, validateAgentReplace, handleValidationErrors, agentHandlers.updateAgent)
/**
* @swagger
* /agents/{agentId}:
* patch:
* summary: Update agent (partial update)
* tags: [Agents]
* parameters:
* - in: path
* name: agentId
* required: true
* schema:
* type: string
* description: Agent ID
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/UpdateAgentRequest'
* responses:
* 200:
* description: Agent updated successfully
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/AgentEntity'
* 400:
* description: Invalid request body
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
* 404:
* description: Agent not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
*/
agentsRouter.patch('/:agentId', validateAgentId, validateAgentUpdate, handleValidationErrors, agentHandlers.patchAgent)
/**
* @swagger
* /agents/{agentId}:
* delete:
* summary: Delete agent
* tags: [Agents]
* parameters:
* - in: path
* name: agentId
* required: true
* schema:
* type: string
* description: Agent ID
* responses:
* 204:
* description: Agent deleted successfully
* 404:
* description: Agent not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
*/
agentsRouter.delete('/:agentId', validateAgentId, handleValidationErrors, agentHandlers.deleteAgent)
// Create sessions router with agent context
const createSessionsRouter = (): express.Router => {
const sessionsRouter = express.Router({ mergeParams: true })
// Session CRUD routes (nested under agent)
/**
* @swagger
* /agents/{agentId}/sessions:
* post:
* summary: Create a new session for an agent
* tags: [Sessions]
* parameters:
* - in: path
* name: agentId
* required: true
* schema:
* type: string
* description: Agent ID
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/CreateSessionRequest'
* responses:
* 201:
* description: Session created successfully
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SessionEntity'
* 400:
* description: Invalid request body
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
* 404:
* description: Agent not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
*/
sessionsRouter.post('/', validateSession, handleValidationErrors, sessionHandlers.createSession)
/**
* @swagger
* /agents/{agentId}/sessions:
* get:
* summary: List sessions for an agent
* tags: [Sessions]
* parameters:
* - in: path
* name: agentId
* required: true
* schema:
* type: string
* description: Agent ID
* - in: query
* name: limit
* schema:
* type: integer
* minimum: 1
* maximum: 100
* default: 20
* description: Number of sessions to return
* - in: query
* name: offset
* schema:
* type: integer
* minimum: 0
* default: 0
* description: Number of sessions to skip
* - in: query
* name: status
* schema:
* type: string
* enum: [idle, running, completed, failed, stopped]
* description: Filter by session status
* responses:
* 200:
* description: List of sessions
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ListSessionsResponse'
* 404:
* description: Agent not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
*/
sessionsRouter.get('/', validatePagination, handleValidationErrors, sessionHandlers.listSessions)
/**
* @swagger
* /agents/{agentId}/sessions/{sessionId}:
* get:
* summary: Get session by ID
* tags: [Sessions]
* parameters:
* - in: path
* name: agentId
* required: true
* schema:
* type: string
* description: Agent ID
* - in: path
* name: sessionId
* required: true
* schema:
* type: string
* description: Session ID
* responses:
* 200:
* description: Session details
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SessionEntity'
* 404:
* description: Agent or session not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
*/
sessionsRouter.get('/:sessionId', validateSessionId, handleValidationErrors, sessionHandlers.getSession)
/**
* @swagger
* /agents/{agentId}/sessions/{sessionId}:
* put:
* summary: Replace session (full update)
* tags: [Sessions]
* parameters:
* - in: path
* name: agentId
* required: true
* schema:
* type: string
* description: Agent ID
* - in: path
* name: sessionId
* required: true
* schema:
* type: string
* description: Session ID
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ReplaceSessionRequest'
* responses:
* 200:
* description: Session updated successfully
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SessionEntity'
* 400:
* description: Invalid request body
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
* 404:
* description: Agent or session not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
*/
sessionsRouter.put(
'/:sessionId',
validateSessionId,
validateSessionReplace,
handleValidationErrors,
sessionHandlers.updateSession
)
/**
* @swagger
* /agents/{agentId}/sessions/{sessionId}:
* patch:
* summary: Update session (partial update)
* tags: [Sessions]
* parameters:
* - in: path
* name: agentId
* required: true
* schema:
* type: string
* description: Agent ID
* - in: path
* name: sessionId
* required: true
* schema:
* type: string
* description: Session ID
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/UpdateSessionRequest'
* responses:
* 200:
* description: Session updated successfully
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/SessionEntity'
* 400:
* description: Invalid request body
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
* 404:
* description: Agent or session not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
*/
sessionsRouter.patch(
'/:sessionId',
validateSessionId,
validateSessionUpdate,
handleValidationErrors,
sessionHandlers.patchSession
)
/**
* @swagger
* /agents/{agentId}/sessions/{sessionId}:
* delete:
* summary: Delete session
* tags: [Sessions]
* parameters:
* - in: path
* name: agentId
* required: true
* schema:
* type: string
* description: Agent ID
* - in: path
* name: sessionId
* required: true
* schema:
* type: string
* description: Session ID
* responses:
* 204:
* description: Session deleted successfully
* 404:
* description: Agent or session not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
*/
sessionsRouter.delete('/:sessionId', validateSessionId, handleValidationErrors, sessionHandlers.deleteSession)
return sessionsRouter
}
// Create messages router with agent and session context
const createMessagesRouter = (): express.Router => {
const messagesRouter = express.Router({ mergeParams: true })
// Message CRUD routes (nested under agent/session)
/**
* @swagger
* /agents/{agentId}/sessions/{sessionId}/messages:
* post:
* summary: Create a new message in a session
* tags: [Messages]
* parameters:
* - in: path
* name: agentId
* required: true
* schema:
* type: string
* description: Agent ID
* - in: path
* name: sessionId
* required: true
* schema:
* type: string
* description: Session ID
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/CreateSessionMessageRequest'
* responses:
* 201:
* description: Message created successfully
* content:
* application/json:
* schema:
* type: object
* properties:
* id:
* type: number
* description: Message ID
* session_id:
* type: string
* description: Session ID
* role:
* type: string
* enum: [assistant, user, system, tool]
* description: Message role
* content:
* type: object
* description: Message content (AI SDK format)
* agent_session_id:
* type: string
* description: Agent session ID for resuming
* metadata:
* type: object
* description: Additional metadata
* created_at:
* type: string
* format: date-time
* updated_at:
* type: string
* format: date-time
* 400:
* description: Invalid request body
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
* 404:
* description: Agent or session not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
*/
messagesRouter.post('/', validateSessionMessage, handleValidationErrors, messageHandlers.createMessage)
/**
* @swagger
* /agents/{agentId}/sessions/{sessionId}/messages/{messageId}:
* delete:
* summary: Delete a message from a session
* tags: [Messages]
* parameters:
* - in: path
* name: agentId
* required: true
* schema:
* type: string
* description: Agent ID
* - in: path
* name: sessionId
* required: true
* schema:
* type: string
* description: Session ID
* - in: path
* name: messageId
* required: true
* schema:
* type: integer
* description: Message ID
* responses:
* 204:
* description: Message deleted successfully
* 404:
* description: Agent, session, or message not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/ErrorResponse'
*/
messagesRouter.delete('/:messageId', validateSessionMessageId, handleValidationErrors, messageHandlers.deleteMessage)
return messagesRouter
}
// Mount nested resources with clear hierarchy
const sessionsRouter = createSessionsRouter()
const messagesRouter = createMessagesRouter()
// Mount sessions under specific agent
agentsRouter.use('/:agentId/sessions', validateAgentId, checkAgentExists, handleValidationErrors, sessionsRouter)
// Mount messages under specific agent/session
agentsRouter.use(
'/:agentId/sessions/:sessionId/messages',
validateAgentId,
validateSessionId,
handleValidationErrors,
messagesRouter
)
// Export main router and convenience router
export const agentsRoutes = agentsRouter

View File

@@ -0,0 +1,44 @@
import { Request, Response } from 'express'
import { agentService } from '../../../../services/agents'
import { loggerService } from '../../../../services/LoggerService'
const logger = loggerService.withContext('ApiServerMiddleware')
// Since Zod validators handle their own errors, this is now a pass-through
export const handleValidationErrors = (_req: Request, _res: Response, next: any): void => {
next()
}
// Middleware to check if agent exists
export const checkAgentExists = async (req: Request, res: Response, next: any): Promise<void> => {
try {
const { agentId } = req.params
const exists = await agentService.agentExists(agentId)
if (!exists) {
res.status(404).json({
error: {
message: 'Agent not found',
type: 'not_found',
code: 'agent_not_found'
}
})
return
}
next()
} catch (error) {
logger.error('Error checking agent existence', {
error: error as Error,
agentId: req.params.agentId
})
res.status(500).json({
error: {
message: 'Failed to validate agent',
type: 'internal_error',
code: 'agent_validation_failed'
}
})
}
}

View File

@@ -0,0 +1 @@
export * from './common'

View File

@@ -0,0 +1,24 @@
import {
AgentIdParamSchema,
CreateAgentRequestSchema,
ReplaceAgentRequestSchema,
UpdateAgentRequestSchema
} from '@types'
import { createZodValidator } from './zodValidator'
export const validateAgent = createZodValidator({
body: CreateAgentRequestSchema
})
export const validateAgentReplace = createZodValidator({
body: ReplaceAgentRequestSchema
})
export const validateAgentUpdate = createZodValidator({
body: UpdateAgentRequestSchema
})
export const validateAgentId = createZodValidator({
params: AgentIdParamSchema
})

View File

@@ -0,0 +1,7 @@
import { PaginationQuerySchema } from '@types'
import { createZodValidator } from './zodValidator'
export const validatePagination = createZodValidator({
query: PaginationQuerySchema
})

View File

@@ -0,0 +1,4 @@
export * from './agents'
export * from './common'
export * from './messages'
export * from './sessions'

View File

@@ -0,0 +1,11 @@
import { CreateSessionMessageRequestSchema, SessionMessageIdParamSchema } from '@types'
import { createZodValidator } from './zodValidator'
export const validateSessionMessage = createZodValidator({
body: CreateSessionMessageRequestSchema
})
export const validateSessionMessageId = createZodValidator({
params: SessionMessageIdParamSchema
})

View File

@@ -0,0 +1,24 @@
import {
CreateSessionRequestSchema,
ReplaceSessionRequestSchema,
SessionIdParamSchema,
UpdateSessionRequestSchema
} from '@types'
import { createZodValidator } from './zodValidator'
export const validateSession = createZodValidator({
body: CreateSessionRequestSchema
})
export const validateSessionReplace = createZodValidator({
body: ReplaceSessionRequestSchema
})
export const validateSessionUpdate = createZodValidator({
body: UpdateSessionRequestSchema
})
export const validateSessionId = createZodValidator({
params: SessionIdParamSchema
})

View File

@@ -0,0 +1,68 @@
import { NextFunction, Request, Response } from 'express'
import { ZodError, ZodType } from 'zod'
export interface ValidationRequest extends Request {
validatedBody?: any
validatedParams?: any
validatedQuery?: any
}
export interface ZodValidationConfig {
body?: ZodType
params?: ZodType
query?: ZodType
}
export const createZodValidator = (config: ZodValidationConfig) => {
return (req: ValidationRequest, res: Response, next: NextFunction): void => {
try {
if (config.body && req.body) {
req.validatedBody = config.body.parse(req.body)
}
if (config.params && req.params) {
req.validatedParams = config.params.parse(req.params)
}
if (config.query && req.query) {
req.validatedQuery = config.query.parse(req.query)
}
next()
} catch (error) {
if (error instanceof ZodError) {
const validationErrors = error.issues.map((err) => ({
type: 'field',
value: err.input,
msg: err.message,
path: err.path.map((p) => String(p)).join('.'),
location: getLocationFromPath(err.path, config)
}))
res.status(400).json({
error: {
message: 'Validation failed',
type: 'validation_error',
details: validationErrors
}
})
return
}
res.status(500).json({
error: {
message: 'Internal validation error',
type: 'internal_error',
code: 'validation_processing_failed'
}
})
}
}
}
function getLocationFromPath(path: (string | number | symbol)[], config: ZodValidationConfig): string {
if (config.body && path.length > 0) return 'body'
if (config.params && path.length > 0) return 'params'
if (config.query && path.length > 0) return 'query'
return 'unknown'
}

View File

@@ -1,15 +1,105 @@
import express, { Request, Response } from 'express'
import OpenAI from 'openai'
import { ChatCompletionCreateParams } from 'openai/resources'
import { loggerService } from '../../services/LoggerService'
import { chatCompletionService } from '../services/chat-completion'
import { validateModelId } from '../utils'
import {
ChatCompletionModelError,
chatCompletionService,
ChatCompletionValidationError
} from '../services/chat-completion'
const logger = loggerService.withContext('ApiServerChatRoutes')
const router = express.Router()
interface ErrorResponseBody {
error: {
message: string
type: string
code: string
}
}
const mapChatCompletionError = (error: unknown): { status: number; body: ErrorResponseBody } => {
if (error instanceof ChatCompletionValidationError) {
logger.warn('Chat completion validation error', {
errors: error.errors
})
return {
status: 400,
body: {
error: {
message: error.errors.join('; '),
type: 'invalid_request_error',
code: 'validation_failed'
}
}
}
}
if (error instanceof ChatCompletionModelError) {
logger.warn('Chat completion model error', error.error)
return {
status: 400,
body: {
error: {
message: error.error.message,
type: 'invalid_request_error',
code: error.error.code
}
}
}
}
if (error instanceof Error) {
let statusCode = 500
let errorType = 'server_error'
let errorCode = 'internal_error'
if (error.message.includes('API key') || error.message.includes('authentication')) {
statusCode = 401
errorType = 'authentication_error'
errorCode = 'invalid_api_key'
} else if (error.message.includes('rate limit') || error.message.includes('quota')) {
statusCode = 429
errorType = 'rate_limit_error'
errorCode = 'rate_limit_exceeded'
} else if (error.message.includes('timeout') || error.message.includes('connection')) {
statusCode = 502
errorType = 'server_error'
errorCode = 'upstream_error'
}
logger.error('Chat completion error', { error })
return {
status: statusCode,
body: {
error: {
message: error.message || 'Internal server error',
type: errorType,
code: errorCode
}
}
}
}
logger.error('Chat completion unknown error', { error })
return {
status: 500,
body: {
error: {
message: 'Internal server error',
type: 'server_error',
code: 'internal_error'
}
}
}
}
/**
* @swagger
* /v1/chat/completions:
@@ -60,7 +150,7 @@ const router = express.Router()
* type: integer
* total_tokens:
* type: integer
* text/plain:
* text/event-stream:
* schema:
* type: string
* description: Server-sent events stream (when stream=true)
@@ -103,72 +193,31 @@ router.post('/completions', async (req: Request, res: Response) => {
})
}
logger.info('Chat completion request:', {
logger.debug('Chat completion request', {
model: request.model,
messageCount: request.messages?.length || 0,
stream: request.stream,
temperature: request.temperature
})
// Validate request
const validation = chatCompletionService.validateRequest(request)
if (!validation.isValid) {
return res.status(400).json({
error: {
message: validation.errors.join('; '),
type: 'invalid_request_error',
code: 'validation_failed'
}
})
}
const isStreaming = !!request.stream
// Validate model ID and get provider
const modelValidation = await validateModelId(request.model)
if (!modelValidation.valid) {
const error = modelValidation.error!
logger.warn(`Model validation failed for '${request.model}':`, error)
return res.status(400).json({
error: {
message: error.message,
type: 'invalid_request_error',
code: error.code
}
})
}
if (isStreaming) {
const { stream } = await chatCompletionService.processStreamingCompletion(request)
const provider = modelValidation.provider!
const modelId = modelValidation.modelId!
logger.info('Model validation successful:', {
provider: provider.id,
providerType: provider.type,
modelId: modelId,
fullModelId: request.model
})
// Create OpenAI client
const client = new OpenAI({
baseURL: provider.apiHost,
apiKey: provider.apiKey
})
request.model = modelId
// Handle streaming
if (request.stream) {
const streamResponse = await client.chat.completions.create(request)
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.setHeader('Cache-Control', 'no-cache')
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8')
res.setHeader('Cache-Control', 'no-cache, no-transform')
res.setHeader('Connection', 'keep-alive')
res.setHeader('X-Accel-Buffering', 'no')
res.flushHeaders()
try {
for await (const chunk of streamResponse as any) {
for await (const chunk of stream) {
res.write(`data: ${JSON.stringify(chunk)}\n\n`)
}
res.write('data: [DONE]\n\n')
res.end()
} catch (streamError: any) {
logger.error('Stream error:', streamError)
logger.error('Stream error', { error: streamError })
res.write(
`data: ${JSON.stringify({
error: {
@@ -178,47 +227,17 @@ router.post('/completions', async (req: Request, res: Response) => {
}
})}\n\n`
)
} finally {
res.end()
}
return
}
// Handle non-streaming
const response = await client.chat.completions.create(request)
const { response } = await chatCompletionService.processCompletion(request)
return res.json(response)
} catch (error: any) {
logger.error('Chat completion error:', error)
let statusCode = 500
let errorType = 'server_error'
let errorCode = 'internal_error'
let errorMessage = 'Internal server error'
if (error instanceof Error) {
errorMessage = error.message
if (error.message.includes('API key') || error.message.includes('authentication')) {
statusCode = 401
errorType = 'authentication_error'
errorCode = 'invalid_api_key'
} else if (error.message.includes('rate limit') || error.message.includes('quota')) {
statusCode = 429
errorType = 'rate_limit_error'
errorCode = 'rate_limit_exceeded'
} else if (error.message.includes('timeout') || error.message.includes('connection')) {
statusCode = 502
errorType = 'server_error'
errorCode = 'upstream_error'
}
}
return res.status(statusCode).json({
error: {
message: errorMessage,
type: errorType,
code: errorCode
}
})
} catch (error: unknown) {
const { status, body } = mapChatCompletionError(error)
return res.status(status).json(body)
}
})

View File

@@ -43,14 +43,14 @@ const router = express.Router()
*/
router.get('/', async (req: Request, res: Response) => {
try {
logger.info('Get all MCP servers request received')
logger.debug('Listing MCP servers')
const servers = await mcpApiService.getAllServers(req)
return res.json({
success: true,
data: servers
})
} catch (error: any) {
logger.error('Error fetching MCP servers:', error)
logger.error('Error fetching MCP servers', { error })
return res.status(503).json({
success: false,
error: {
@@ -103,10 +103,12 @@ router.get('/', async (req: Request, res: Response) => {
*/
router.get('/:server_id', async (req: Request, res: Response) => {
try {
logger.info('Get MCP server info request received')
logger.debug('Get MCP server info request received', {
serverId: req.params.server_id
})
const server = await mcpApiService.getServerInfo(req.params.server_id)
if (!server) {
logger.warn('MCP server not found')
logger.warn('MCP server not found', { serverId: req.params.server_id })
return res.status(404).json({
success: false,
error: {
@@ -121,7 +123,7 @@ router.get('/:server_id', async (req: Request, res: Response) => {
data: server
})
} catch (error: any) {
logger.error('Error fetching MCP server info:', error)
logger.error('Error fetching MCP server info', { error, serverId: req.params.server_id })
return res.status(503).json({
success: false,
error: {
@@ -137,7 +139,7 @@ router.get('/:server_id', async (req: Request, res: Response) => {
router.all('/:server_id/mcp', async (req: Request, res: Response) => {
const server = await mcpApiService.getServerById(req.params.server_id)
if (!server) {
logger.warn('MCP server not found')
logger.warn('MCP server not found', { serverId: req.params.server_id })
return res.status(404).json({
success: false,
error: {

View File

@@ -0,0 +1,403 @@
import { MessageCreateParams } from '@anthropic-ai/sdk/resources'
import { loggerService } from '@logger'
import { Provider } from '@types'
import express, { Request, Response } from 'express'
import { messagesService } from '../services/messages'
import { getProviderById, validateModelId } from '../utils'
const logger = loggerService.withContext('ApiServerMessagesRoutes')
const router = express.Router()
const providerRouter = express.Router({ mergeParams: true })
// Helper function for basic request validation
async function validateRequestBody(req: Request): Promise<{ valid: boolean; error?: any }> {
const request: MessageCreateParams = req.body
if (!request) {
return {
valid: false,
error: {
type: 'error',
error: {
type: 'invalid_request_error',
message: 'Request body is required'
}
}
}
}
return { valid: true }
}
interface HandleMessageProcessingOptions {
req: Request
res: Response
provider: Provider
request: MessageCreateParams
modelId?: string
}
async function handleMessageProcessing({
req,
res,
provider,
request,
modelId
}: HandleMessageProcessingOptions): Promise<void> {
try {
const validation = messagesService.validateRequest(request)
if (!validation.isValid) {
res.status(400).json({
type: 'error',
error: {
type: 'invalid_request_error',
message: validation.errors.join('; ')
}
})
return
}
const extraHeaders = messagesService.prepareHeaders(req.headers)
const { client, anthropicRequest } = await messagesService.processMessage({
provider,
request,
extraHeaders,
modelId
})
if (request.stream) {
await messagesService.handleStreaming(client, anthropicRequest, { response: res }, provider)
return
}
const response = await client.messages.create(anthropicRequest)
res.json(response)
} catch (error: any) {
logger.error('Message processing error', { error })
const { statusCode, errorResponse } = messagesService.transformError(error)
res.status(statusCode).json(errorResponse)
}
}
/**
* @swagger
* /v1/messages:
* post:
* summary: Create message
* description: Create a message response using Anthropic's API format
* tags: [Messages]
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - model
* - max_tokens
* - messages
* properties:
* model:
* type: string
* description: Model ID in format "provider:model_id"
* example: "my-anthropic:claude-3-5-sonnet-20241022"
* max_tokens:
* type: integer
* minimum: 1
* description: Maximum number of tokens to generate
* example: 1024
* messages:
* type: array
* items:
* type: object
* properties:
* role:
* type: string
* enum: [user, assistant]
* content:
* oneOf:
* - type: string
* - type: array
* system:
* type: string
* description: System message
* temperature:
* type: number
* minimum: 0
* maximum: 1
* description: Sampling temperature
* top_p:
* type: number
* minimum: 0
* maximum: 1
* description: Nucleus sampling
* top_k:
* type: integer
* minimum: 0
* description: Top-k sampling
* stream:
* type: boolean
* description: Whether to stream the response
* tools:
* type: array
* description: Available tools for the model
* responses:
* 200:
* description: Message response
* content:
* application/json:
* schema:
* type: object
* properties:
* id:
* type: string
* type:
* type: string
* example: message
* role:
* type: string
* example: assistant
* content:
* type: array
* items:
* type: object
* model:
* type: string
* stop_reason:
* type: string
* stop_sequence:
* type: string
* usage:
* type: object
* properties:
* input_tokens:
* type: integer
* output_tokens:
* type: integer
* text/event-stream:
* schema:
* type: string
* description: Server-sent events stream (when stream=true)
* 400:
* description: Bad request
* content:
* application/json:
* schema:
* type: object
* properties:
* type:
* type: string
* example: error
* error:
* type: object
* properties:
* type:
* type: string
* message:
* type: string
* 401:
* description: Unauthorized
* 429:
* description: Rate limit exceeded
* 500:
* description: Internal server error
*/
router.post('/', async (req: Request, res: Response) => {
// Validate request body
const bodyValidation = await validateRequestBody(req)
if (!bodyValidation.valid) {
return res.status(400).json(bodyValidation.error)
}
try {
const request: MessageCreateParams = req.body
// Validate model ID and get provider
const modelValidation = await validateModelId(request.model)
if (!modelValidation.valid) {
const error = modelValidation.error!
logger.warn('Model validation failed', {
model: request.model,
error
})
return res.status(400).json({
type: 'error',
error: {
type: 'invalid_request_error',
message: error.message
}
})
}
const provider = modelValidation.provider!
const modelId = modelValidation.modelId!
return handleMessageProcessing({ req, res, provider, request, modelId })
} catch (error: any) {
logger.error('Message processing error', { error })
const { statusCode, errorResponse } = messagesService.transformError(error)
return res.status(statusCode).json(errorResponse)
}
})
/**
* @swagger
* /{provider_id}/v1/messages:
* post:
* summary: Create message with provider in path
* description: Create a message response using provider ID from URL path
* tags: [Messages]
* parameters:
* - in: path
* name: provider_id
* required: true
* schema:
* type: string
* description: Provider ID (e.g., "my-anthropic")
* example: "my-anthropic"
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required:
* - model
* - max_tokens
* - messages
* properties:
* model:
* type: string
* description: Model ID without provider prefix
* example: "claude-3-5-sonnet-20241022"
* max_tokens:
* type: integer
* minimum: 1
* description: Maximum number of tokens to generate
* example: 1024
* messages:
* type: array
* items:
* type: object
* properties:
* role:
* type: string
* enum: [user, assistant]
* content:
* oneOf:
* - type: string
* - type: array
* system:
* type: string
* description: System message
* temperature:
* type: number
* minimum: 0
* maximum: 1
* description: Sampling temperature
* top_p:
* type: number
* minimum: 0
* maximum: 1
* description: Nucleus sampling
* top_k:
* type: integer
* minimum: 0
* description: Top-k sampling
* stream:
* type: boolean
* description: Whether to stream the response
* tools:
* type: array
* description: Available tools for the model
* responses:
* 200:
* description: Message response
* content:
* application/json:
* schema:
* type: object
* properties:
* id:
* type: string
* type:
* type: string
* example: message
* role:
* type: string
* example: assistant
* content:
* type: array
* items:
* type: object
* model:
* type: string
* stop_reason:
* type: string
* stop_sequence:
* type: string
* usage:
* type: object
* properties:
* input_tokens:
* type: integer
* output_tokens:
* type: integer
* text/event-stream:
* schema:
* type: string
* description: Server-sent events stream (when stream=true)
* 400:
* description: Bad request
* 401:
* description: Unauthorized
* 429:
* description: Rate limit exceeded
* 500:
* description: Internal server error
*/
providerRouter.post('/', async (req: Request, res: Response) => {
// Validate request body
const bodyValidation = await validateRequestBody(req)
if (!bodyValidation.valid) {
return res.status(400).json(bodyValidation.error)
}
try {
const providerId = req.params.provider
if (!providerId) {
return res.status(400).json({
type: 'error',
error: {
type: 'invalid_request_error',
message: 'Provider ID is required in URL path'
}
})
}
// Get provider directly by ID from URL path
const provider = await getProviderById(providerId)
if (!provider) {
return res.status(400).json({
type: 'error',
error: {
type: 'invalid_request_error',
message: `Provider '${providerId}' not found or not enabled`
}
})
}
const request: MessageCreateParams = req.body
return handleMessageProcessing({ req, res, provider, request })
} catch (error: any) {
logger.error('Message processing error', { error })
const { statusCode, errorResponse } = messagesService.transformError(error)
return res.status(statusCode).json(errorResponse)
}
})
export { providerRouter as messagesProviderRoutes, router as messagesRoutes }

View File

@@ -1,73 +1,124 @@
import { ApiModelsFilterSchema, ApiModelsResponse } from '@types'
import express, { Request, Response } from 'express'
import { loggerService } from '../../services/LoggerService'
import { chatCompletionService } from '../services/chat-completion'
import { modelsService } from '../services/models'
const logger = loggerService.withContext('ApiServerModelsRoutes')
const router = express.Router()
const router = express
.Router()
/**
* @swagger
* /v1/models:
* get:
* summary: List available models
* description: Returns a list of available AI models from all configured providers
* tags: [Models]
* responses:
* 200:
* description: List of available models
* content:
* application/json:
* schema:
* type: object
* properties:
* object:
* type: string
* example: list
* data:
* type: array
* items:
* $ref: '#/components/schemas/Model'
* 503:
* description: Service unavailable
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
router.get('/', async (_req: Request, res: Response) => {
try {
logger.info('Models list request received')
/**
* @swagger
* /v1/models:
* get:
* summary: List available models
* description: Returns a list of available AI models from all configured providers with optional filtering
* tags: [Models]
* parameters:
* - in: query
* name: providerType
* schema:
* type: string
* enum: [openai, openai-response, anthropic, gemini]
* description: Filter models by provider type
* - in: query
* name: offset
* schema:
* type: integer
* minimum: 0
* default: 0
* description: Pagination offset
* - in: query
* name: limit
* schema:
* type: integer
* minimum: 1
* description: Maximum number of models to return
* responses:
* 200:
* description: List of available models
* content:
* application/json:
* schema:
* type: object
* properties:
* object:
* type: string
* example: list
* data:
* type: array
* items:
* $ref: '#/components/schemas/Model'
* total:
* type: integer
* description: Total number of models (when using pagination)
* offset:
* type: integer
* description: Current offset (when using pagination)
* limit:
* type: integer
* description: Current limit (when using pagination)
* 400:
* description: Invalid query parameters
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 503:
* description: Service unavailable
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
.get('/', async (req: Request, res: Response) => {
try {
logger.debug('Models list request received', { query: req.query })
const models = await chatCompletionService.getModels()
// Validate query parameters using Zod schema
const filterResult = ApiModelsFilterSchema.safeParse(req.query)
if (models.length === 0) {
logger.warn(
'No models available from providers. This may be because no OpenAI providers are configured or enabled.'
)
}
logger.info(`Returning ${models.length} models (OpenAI providers only)`)
logger.debug(
'Model IDs:',
models.map((m) => m.id)
)
return res.json({
object: 'list',
data: models
})
} catch (error: any) {
logger.error('Error fetching models:', error)
return res.status(503).json({
error: {
message: 'Failed to retrieve models from available providers',
type: 'service_unavailable',
code: 'models_unavailable'
if (!filterResult.success) {
logger.warn('Invalid model query parameters', { issues: filterResult.error.issues })
return res.status(400).json({
error: {
message: 'Invalid query parameters',
type: 'invalid_request_error',
code: 'invalid_parameters',
details: filterResult.error.issues.map((issue) => ({
field: issue.path.join('.'),
message: issue.message
}))
}
})
}
})
}
})
const filter = filterResult.data
const response = await modelsService.getModels(filter)
if (response.data.length === 0) {
logger.warn('No models available from providers', { filter })
}
logger.info('Models response ready', {
filter,
total: response.total,
modelIds: response.data.map((m) => m.id)
})
return res.json(response satisfies ApiModelsResponse)
} catch (error: any) {
logger.error('Error fetching models', { error })
return res.status(503).json({
error: {
message: 'Failed to retrieve models from available providers',
type: 'service_unavailable',
code: 'models_unavailable'
}
})
}
})
export { router as modelsRoutes }

View File

@@ -1,11 +1,16 @@
import { createServer } from 'node:http'
import { agentService } from '../services/agents'
import { loggerService } from '../services/LoggerService'
import { app } from './app'
import { config } from './config'
const logger = loggerService.withContext('ApiServer')
const GLOBAL_REQUEST_TIMEOUT_MS = 5 * 60_000
const GLOBAL_HEADERS_TIMEOUT_MS = GLOBAL_REQUEST_TIMEOUT_MS + 5_000
const GLOBAL_KEEPALIVE_TIMEOUT_MS = 60_000
export class ApiServer {
private server: ReturnType<typeof createServer> | null = null
@@ -16,16 +21,21 @@ export class ApiServer {
}
// Load config
const { port, host, apiKey } = await config.load()
const { port, host } = await config.load()
// Initialize AgentService
logger.info('Initializing AgentService')
await agentService.initialize()
logger.info('AgentService initialized')
// Create server with Express app
this.server = createServer(app)
this.applyServerTimeouts(this.server)
// Start server
return new Promise((resolve, reject) => {
this.server!.listen(port, host, () => {
logger.info(`API Server started at http://${host}:${port}`)
logger.info(`API Key: ${apiKey}`)
logger.info('API server started', { host, port })
resolve()
})
@@ -33,12 +43,19 @@ export class ApiServer {
})
}
private applyServerTimeouts(server: ReturnType<typeof createServer>): void {
server.requestTimeout = GLOBAL_REQUEST_TIMEOUT_MS
server.headersTimeout = Math.max(GLOBAL_HEADERS_TIMEOUT_MS, server.requestTimeout + 1_000)
server.keepAliveTimeout = GLOBAL_KEEPALIVE_TIMEOUT_MS
server.setTimeout(0)
}
async stop(): Promise<void> {
if (!this.server) return
return new Promise((resolve) => {
this.server!.close(() => {
logger.info('API Server stopped')
logger.info('API server stopped')
this.server = null
resolve()
})
@@ -56,7 +73,7 @@ export class ApiServer {
const isListening = this.server?.listening || false
const result = hasServer && isListening
logger.debug('isRunning check:', { hasServer, isListening, result })
logger.debug('isRunning check', { hasServer, isListening, result })
return result
}

View File

@@ -1,83 +1,132 @@
import { Provider } from '@types'
import OpenAI from 'openai'
import { ChatCompletionCreateParams } from 'openai/resources'
import { ChatCompletionCreateParams, ChatCompletionCreateParamsStreaming } from 'openai/resources'
import { loggerService } from '../../services/LoggerService'
import {
getProviderByModel,
getRealProviderModel,
listAllAvailableModels,
OpenAICompatibleModel,
transformModelToOpenAI,
validateProvider
} from '../utils'
import { ModelValidationError, validateModelId } from '../utils'
const logger = loggerService.withContext('ChatCompletionService')
export interface ModelData extends OpenAICompatibleModel {
provider_id: string
model_id: string
name: string
}
export interface ValidationResult {
isValid: boolean
errors: string[]
}
export class ChatCompletionValidationError extends Error {
constructor(public readonly errors: string[]) {
super(`Request validation failed: ${errors.join('; ')}`)
this.name = 'ChatCompletionValidationError'
}
}
export class ChatCompletionModelError extends Error {
constructor(public readonly error: ModelValidationError) {
super(`Model validation failed: ${error.message}`)
this.name = 'ChatCompletionModelError'
}
}
export type PrepareRequestResult =
| { status: 'validation_error'; errors: string[] }
| { status: 'model_error'; error: ModelValidationError }
| {
status: 'ok'
provider: Provider
modelId: string
client: OpenAI
providerRequest: ChatCompletionCreateParams
}
export class ChatCompletionService {
async getModels(): Promise<ModelData[]> {
try {
logger.info('Getting available models from providers')
async resolveProviderContext(
model: string
): Promise<
{ ok: false; error: ModelValidationError } | { ok: true; provider: Provider; modelId: string; client: OpenAI }
> {
const modelValidation = await validateModelId(model)
if (!modelValidation.valid) {
return {
ok: false,
error: modelValidation.error!
}
}
const models = await listAllAvailableModels()
const provider = modelValidation.provider!
// Use Map to deduplicate models by their full ID (provider:model_id)
const uniqueModels = new Map<string, ModelData>()
for (const model of models) {
const openAIModel = transformModelToOpenAI(model)
const fullModelId = openAIModel.id // This is already in format "provider:model_id"
// Only add if not already present (first occurrence wins)
if (!uniqueModels.has(fullModelId)) {
uniqueModels.set(fullModelId, {
...openAIModel,
provider_id: model.provider,
model_id: model.id,
name: model.name
})
} else {
logger.debug(`Skipping duplicate model: ${fullModelId}`)
if (provider.type !== 'openai') {
return {
ok: false,
error: {
type: 'unsupported_provider_type',
message: `Provider '${provider.id}' of type '${provider.type}' is not supported for OpenAI chat completions`,
code: 'unsupported_provider_type'
}
}
}
const modelData = Array.from(uniqueModels.values())
const modelId = modelValidation.modelId!
logger.info(`Successfully retrieved ${modelData.length} unique models from ${models.length} total models`)
const client = new OpenAI({
baseURL: provider.apiHost,
apiKey: provider.apiKey
})
if (models.length > modelData.length) {
logger.debug(`Filtered out ${models.length - modelData.length} duplicate models`)
return {
ok: true,
provider,
modelId,
client
}
}
async prepareRequest(request: ChatCompletionCreateParams, stream: boolean): Promise<PrepareRequestResult> {
const requestValidation = this.validateRequest(request)
if (!requestValidation.isValid) {
return {
status: 'validation_error',
errors: requestValidation.errors
}
}
return modelData
} catch (error: any) {
logger.error('Error getting models:', error)
return []
const providerContext = await this.resolveProviderContext(request.model!)
if (!providerContext.ok) {
return {
status: 'model_error',
error: providerContext.error
}
}
const { provider, modelId, client } = providerContext
logger.debug('Model validation successful', {
provider: provider.id,
providerType: provider.type,
modelId,
fullModelId: request.model
})
return {
status: 'ok',
provider,
modelId,
client,
providerRequest: stream
? {
...request,
model: modelId,
stream: true as const
}
: {
...request,
model: modelId,
stream: false as const
}
}
}
validateRequest(request: ChatCompletionCreateParams): ValidationResult {
const errors: string[] = []
// Validate model
if (!request.model) {
errors.push('Model is required')
} else if (typeof request.model !== 'string') {
errors.push('Model must be a string')
} else if (!request.model.includes(':')) {
errors.push('Model must be in format "provider:model_id"')
}
// Validate messages
if (!request.messages) {
errors.push('Messages array is required')
@@ -98,17 +147,6 @@ export class ChatCompletionService {
}
// Validate optional parameters
if (request.temperature !== undefined) {
if (typeof request.temperature !== 'number' || request.temperature < 0 || request.temperature > 2) {
errors.push('Temperature must be a number between 0 and 2')
}
}
if (request.max_tokens !== undefined) {
if (typeof request.max_tokens !== 'number' || request.max_tokens < 1) {
errors.push('max_tokens must be a positive number')
}
}
return {
isValid: errors.length === 0,
@@ -116,48 +154,30 @@ export class ChatCompletionService {
}
}
async processCompletion(request: ChatCompletionCreateParams): Promise<OpenAI.Chat.Completions.ChatCompletion> {
async processCompletion(request: ChatCompletionCreateParams): Promise<{
provider: Provider
modelId: string
response: OpenAI.Chat.Completions.ChatCompletion
}> {
try {
logger.info('Processing chat completion request:', {
logger.debug('Processing chat completion request', {
model: request.model,
messageCount: request.messages.length,
stream: request.stream
})
// Validate request
const validation = this.validateRequest(request)
if (!validation.isValid) {
throw new Error(`Request validation failed: ${validation.errors.join(', ')}`)
const preparation = await this.prepareRequest(request, false)
if (preparation.status === 'validation_error') {
throw new ChatCompletionValidationError(preparation.errors)
}
// Get provider for the model
const provider = await getProviderByModel(request.model!)
if (!provider) {
throw new Error(`Provider not found for model: ${request.model}`)
if (preparation.status === 'model_error') {
throw new ChatCompletionModelError(preparation.error)
}
// Validate provider
if (!validateProvider(provider)) {
throw new Error(`Provider validation failed for: ${provider.id}`)
}
const { provider, modelId, client, providerRequest } = preparation
// Extract model ID from the full model string
const modelId = getRealProviderModel(request.model)
// Create OpenAI client for the provider
const client = new OpenAI({
baseURL: provider.apiHost,
apiKey: provider.apiKey
})
// Prepare request with the actual model ID
const providerRequest = {
...request,
model: modelId,
stream: false
}
logger.debug('Sending request to provider:', {
logger.debug('Sending request to provider', {
provider: provider.id,
model: modelId,
apiHost: provider.apiHost
@@ -165,71 +185,71 @@ export class ChatCompletionService {
const response = (await client.chat.completions.create(providerRequest)) as OpenAI.Chat.Completions.ChatCompletion
logger.info('Successfully processed chat completion')
return response
logger.info('Chat completion processed', {
modelId,
provider: provider.id
})
return {
provider,
modelId,
response
}
} catch (error: any) {
logger.error('Error processing chat completion:', error)
logger.error('Error processing chat completion', {
error,
model: request.model
})
throw error
}
}
async *processStreamingCompletion(
request: ChatCompletionCreateParams
): AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk> {
async processStreamingCompletion(request: ChatCompletionCreateParams): Promise<{
provider: Provider
modelId: string
stream: AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>
}> {
try {
logger.info('Processing streaming chat completion request:', {
logger.debug('Processing streaming chat completion request', {
model: request.model,
messageCount: request.messages.length
})
// Validate request
const validation = this.validateRequest(request)
if (!validation.isValid) {
throw new Error(`Request validation failed: ${validation.errors.join(', ')}`)
const preparation = await this.prepareRequest(request, true)
if (preparation.status === 'validation_error') {
throw new ChatCompletionValidationError(preparation.errors)
}
// Get provider for the model
const provider = await getProviderByModel(request.model!)
if (!provider) {
throw new Error(`Provider not found for model: ${request.model}`)
if (preparation.status === 'model_error') {
throw new ChatCompletionModelError(preparation.error)
}
// Validate provider
if (!validateProvider(provider)) {
throw new Error(`Provider validation failed for: ${provider.id}`)
}
const { provider, modelId, client, providerRequest } = preparation
// Extract model ID from the full model string
const modelId = getRealProviderModel(request.model)
// Create OpenAI client for the provider
const client = new OpenAI({
baseURL: provider.apiHost,
apiKey: provider.apiKey
})
// Prepare streaming request
const streamingRequest = {
...request,
model: modelId,
stream: true as const
}
logger.debug('Sending streaming request to provider:', {
logger.debug('Sending streaming request to provider', {
provider: provider.id,
model: modelId,
apiHost: provider.apiHost
})
const stream = await client.chat.completions.create(streamingRequest)
const streamRequest = providerRequest as ChatCompletionCreateParamsStreaming
const stream = (await client.chat.completions.create(
streamRequest
)) as AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>
for await (const chunk of stream) {
yield chunk
logger.info('Streaming chat completion started', {
modelId,
provider: provider.id
})
return {
provider,
modelId,
stream
}
logger.info('Successfully completed streaming chat completion')
} catch (error: any) {
logger.error('Error processing streaming chat completion:', error)
logger.error('Error processing streaming chat completion', {
error,
model: request.model
})
throw error
}
}

View File

@@ -13,8 +13,7 @@ import { Request, Response } from 'express'
import { IncomingMessage, ServerResponse } from 'http'
import { loggerService } from '../../services/LoggerService'
import { reduxService } from '../../services/ReduxService'
import { getMcpServerById } from '../utils/mcp'
import { getMcpServerById, getMCPServersFromRedux } from '../utils/mcp'
const logger = loggerService.withContext('MCPApiService')
const transports: Record<string, StreamableHTTPServerTransport> = {}
@@ -50,42 +49,18 @@ class MCPApiService extends EventEmitter {
constructor() {
super()
this.initMcpServer()
logger.silly('MCPApiService initialized')
logger.debug('MCPApiService initialized')
}
private initMcpServer() {
this.transport.onmessage = this.onMessage
}
/**
* Get servers directly from Redux store
*/
private async getServersFromRedux(): Promise<MCPServer[]> {
try {
logger.silly('Getting servers from Redux store')
// Try to get from cache first (faster)
const cachedServers = reduxService.selectSync<MCPServer[]>('state.mcp.servers')
if (cachedServers && Array.isArray(cachedServers)) {
logger.silly(`Found ${cachedServers.length} servers in Redux cache`)
return cachedServers
}
// If cache is not available, get fresh data
const servers = await reduxService.select<MCPServer[]>('state.mcp.servers')
logger.silly(`Fetched ${servers?.length || 0} servers from Redux store`)
return servers || []
} catch (error: any) {
logger.error('Failed to get servers from Redux:', error)
return []
}
}
// get all activated servers
async getAllServers(req: Request): Promise<McpServersResp> {
try {
const servers = await this.getServersFromRedux()
logger.silly(`Returning ${servers.length} servers`)
const servers = await getMCPServersFromRedux()
logger.debug('Returning servers from Redux', { count: servers.length })
const resp: McpServersResp = {
servers: {}
}
@@ -102,7 +77,7 @@ class MCPApiService extends EventEmitter {
}
return resp
} catch (error: any) {
logger.error('Failed to get all servers:', error)
logger.error('Failed to get all servers', { error })
throw new Error('Failed to retrieve servers')
}
}
@@ -110,87 +85,47 @@ class MCPApiService extends EventEmitter {
// get server by id
async getServerById(id: string): Promise<MCPServer | null> {
try {
logger.silly(`getServerById called with id: ${id}`)
const servers = await this.getServersFromRedux()
logger.debug('getServerById called', { id })
const servers = await getMCPServersFromRedux()
const server = servers.find((s) => s.id === id)
if (!server) {
logger.warn(`Server with id ${id} not found`)
logger.warn('Server not found', { id })
return null
}
logger.silly(`Returning server with id ${id}`)
logger.debug('Returning server', { id })
return server
} catch (error: any) {
logger.error(`Failed to get server with id ${id}:`, error)
logger.error('Failed to get server', { id, error })
throw new Error('Failed to retrieve server')
}
}
async getServerInfo(id: string): Promise<any> {
try {
logger.silly(`getServerInfo called with id: ${id}`)
const server = await this.getServerById(id)
if (!server) {
logger.warn(`Server with id ${id} not found`)
logger.warn('Server not found while fetching info', { id })
return null
}
logger.silly(`Returning server info for id ${id}`)
const client = await mcpService.initClient(server)
const tools = await client.listTools()
logger.info(`Server with id ${id} info:`, { tools: JSON.stringify(tools) })
// const [version, tools, prompts, resources] = await Promise.all([
// () => {
// try {
// return client.getServerVersion()
// } catch (error) {
// logger.error(`Failed to get server version for id ${id}:`, { error: error })
// return '1.0.0'
// }
// },
// (() => {
// try {
// return client.listTools()
// } catch (error) {
// logger.error(`Failed to list tools for id ${id}:`, { error: error })
// return []
// }
// })(),
// (() => {
// try {
// return client.listPrompts()
// } catch (error) {
// logger.error(`Failed to list prompts for id ${id}:`, { error: error })
// return []
// }
// })(),
// (() => {
// try {
// return client.listResources()
// } catch (error) {
// logger.error(`Failed to list resources for id ${id}:`, { error: error })
// return []
// }
// })()
// ])
return {
id: server.id,
name: server.name,
type: server.type,
description: server.description,
tools
tools: tools.tools
}
} catch (error: any) {
logger.error(`Failed to get server info with id ${id}:`, error)
logger.error('Failed to get server info', { id, error })
throw new Error('Failed to retrieve server info')
}
}
async handleRequest(req: Request, res: Response, server: MCPServer) {
const sessionId = req.headers['mcp-session-id'] as string | undefined
logger.silly(`Handling request for server with sessionId ${sessionId}`)
logger.debug('Handling MCP request', { sessionId, serverId: server.id })
let transport: StreamableHTTPServerTransport
if (sessionId && transports[sessionId]) {
transport = transports[sessionId]
@@ -203,7 +138,7 @@ class MCPApiService extends EventEmitter {
})
transport.onclose = () => {
logger.info(`Transport for sessionId ${sessionId} closed`)
logger.info('Transport closed', { sessionId })
if (transport.sessionId) {
delete transports[transport.sessionId]
}
@@ -238,12 +173,15 @@ class MCPApiService extends EventEmitter {
}
}
logger.info(`Request body`, { rawBody: req.body, messages: JSON.stringify(messages) })
logger.debug('Dispatching MCP request', {
sessionId: transport.sessionId ?? sessionId,
messageCount: messages.length
})
await transport.handleRequest(req as IncomingMessage, res as ServerResponse, messages)
}
private onMessage(message: JSONRPCMessage, extra?: MessageExtraInfo) {
logger.info(`Received message: ${JSON.stringify(message)}`, extra)
logger.debug('Received MCP message', { message, extra })
// Handle message here
}
}

View File

@@ -0,0 +1,321 @@
import Anthropic from '@anthropic-ai/sdk'
import { MessageCreateParams, MessageStreamEvent } from '@anthropic-ai/sdk/resources'
import { loggerService } from '@logger'
import anthropicService from '@main/services/AnthropicService'
import { buildClaudeCodeSystemMessage, getSdkClient } from '@shared/anthropic'
import { Provider } from '@types'
import { Response } from 'express'
const logger = loggerService.withContext('MessagesService')
const EXCLUDED_FORWARD_HEADERS: ReadonlySet<string> = new Set([
'host',
'x-api-key',
'authorization',
'sentry-trace',
'baggage',
'content-length',
'connection'
])
export interface ValidationResult {
isValid: boolean
errors: string[]
}
export interface ErrorResponse {
type: 'error'
error: {
type: string
message: string
requestId?: string
}
}
export interface StreamConfig {
response: Response
onChunk?: (chunk: MessageStreamEvent) => void
onError?: (error: any) => void
onComplete?: () => void
}
export interface ProcessMessageOptions {
provider: Provider
request: MessageCreateParams
extraHeaders?: Record<string, string | string[]>
modelId?: string
}
export interface ProcessMessageResult {
client: Anthropic
anthropicRequest: MessageCreateParams
}
export class MessagesService {
validateRequest(request: MessageCreateParams): ValidationResult {
// TODO: Implement comprehensive request validation
const errors: string[] = []
if (!request.model || typeof request.model !== 'string') {
errors.push('Model is required')
}
if (typeof request.max_tokens !== 'number' || !Number.isFinite(request.max_tokens) || request.max_tokens < 1) {
errors.push('max_tokens is required and must be a positive number')
}
if (!request.messages || !Array.isArray(request.messages) || request.messages.length === 0) {
errors.push('messages is required and must be a non-empty array')
} else {
request.messages.forEach((message, index) => {
if (!message || typeof message !== 'object') {
errors.push(`messages[${index}] must be an object`)
return
}
if (!('role' in message) || typeof message.role !== 'string' || message.role.trim().length === 0) {
errors.push(`messages[${index}].role is required`)
}
const content: unknown = message.content
if (content === undefined || content === null) {
errors.push(`messages[${index}].content is required`)
return
}
if (typeof content === 'string' && content.trim().length === 0) {
errors.push(`messages[${index}].content cannot be empty`)
} else if (Array.isArray(content) && content.length === 0) {
errors.push(`messages[${index}].content must include at least one item when using an array`)
}
})
}
return {
isValid: errors.length === 0,
errors
}
}
async getClient(provider: Provider, extraHeaders?: Record<string, string | string[]>): Promise<Anthropic> {
// Create Anthropic client for the provider
if (provider.authType === 'oauth') {
const oauthToken = await anthropicService.getValidAccessToken()
return getSdkClient(provider, oauthToken, extraHeaders)
}
return getSdkClient(provider, null, extraHeaders)
}
prepareHeaders(headers: Record<string, string | string[] | undefined>): Record<string, string | string[]> {
const extraHeaders: Record<string, string | string[]> = {}
for (const [key, value] of Object.entries(headers)) {
if (value === undefined) {
continue
}
const normalizedKey = key.toLowerCase()
if (EXCLUDED_FORWARD_HEADERS.has(normalizedKey)) {
continue
}
extraHeaders[normalizedKey] = value
}
return extraHeaders
}
createAnthropicRequest(request: MessageCreateParams, provider: Provider, modelId?: string): MessageCreateParams {
const anthropicRequest: MessageCreateParams = {
...request,
stream: !!request.stream
}
// Override model if provided
if (modelId) {
anthropicRequest.model = modelId
}
// Add Claude Code system message for OAuth providers
if (provider.type === 'anthropic' && provider.authType === 'oauth') {
anthropicRequest.system = buildClaudeCodeSystemMessage(request.system)
}
return anthropicRequest
}
async handleStreaming(
client: Anthropic,
request: MessageCreateParams,
config: StreamConfig,
provider: Provider
): Promise<void> {
const { response, onChunk, onError, onComplete } = config
// Set streaming headers
response.setHeader('Content-Type', 'text/event-stream; charset=utf-8')
response.setHeader('Cache-Control', 'no-cache, no-transform')
response.setHeader('Connection', 'keep-alive')
response.setHeader('X-Accel-Buffering', 'no')
response.flushHeaders()
const flushableResponse = response as Response & { flush?: () => void }
const flushStream = () => {
if (typeof flushableResponse.flush !== 'function') {
return
}
try {
flushableResponse.flush()
} catch (flushError: unknown) {
logger.warn('Failed to flush streaming response', { error: flushError })
}
}
const writeSse = (eventType: string | undefined, payload: unknown) => {
if (response.writableEnded || response.destroyed) {
return
}
if (eventType) {
response.write(`event: ${eventType}\n`)
}
const data = typeof payload === 'string' ? payload : JSON.stringify(payload)
response.write(`data: ${data}\n\n`)
flushStream()
}
try {
const stream = client.messages.stream(request)
for await (const chunk of stream) {
if (response.writableEnded || response.destroyed) {
logger.warn('Streaming response ended before stream completion', {
provider: provider.id,
model: request.model
})
break
}
writeSse(chunk.type, chunk)
if (onChunk) {
onChunk(chunk)
}
}
writeSse(undefined, '[DONE]')
if (onComplete) {
onComplete()
}
} catch (streamError: any) {
logger.error('Stream error', {
error: streamError,
provider: provider.id,
model: request.model,
apiHost: provider.apiHost,
anthropicApiHost: provider.anthropicApiHost
})
writeSse(undefined, {
type: 'error',
error: {
type: 'api_error',
message: 'Stream processing error'
}
})
if (onError) {
onError(streamError)
}
} finally {
if (!response.writableEnded) {
response.end()
}
}
}
transformError(error: any): { statusCode: number; errorResponse: ErrorResponse } {
let statusCode = 500
let errorType = 'api_error'
let errorMessage = 'Internal server error'
const anthropicStatus = typeof error?.status === 'number' ? error.status : undefined
const anthropicError = error?.error
if (anthropicStatus) {
statusCode = anthropicStatus
}
if (anthropicError?.type) {
errorType = anthropicError.type
}
if (anthropicError?.message) {
errorMessage = anthropicError.message
} else if (error instanceof Error && error.message) {
errorMessage = error.message
}
// Infer error type from message if not from Anthropic API
if (!anthropicStatus && error instanceof Error) {
const errorMessageText = error.message ?? ''
if (errorMessageText.includes('API key') || errorMessageText.includes('authentication')) {
statusCode = 401
errorType = 'authentication_error'
} else if (errorMessageText.includes('rate limit') || errorMessageText.includes('quota')) {
statusCode = 429
errorType = 'rate_limit_error'
} else if (errorMessageText.includes('timeout') || errorMessageText.includes('connection')) {
statusCode = 502
errorType = 'api_error'
} else if (errorMessageText.includes('validation') || errorMessageText.includes('invalid')) {
statusCode = 400
errorType = 'invalid_request_error'
}
}
const safeErrorMessage =
typeof errorMessage === 'string' && errorMessage.length > 0 ? errorMessage : 'Internal server error'
return {
statusCode,
errorResponse: {
type: 'error',
error: {
type: errorType,
message: safeErrorMessage,
requestId: error?.request_id
}
}
}
}
async processMessage(options: ProcessMessageOptions): Promise<ProcessMessageResult> {
const { provider, request, extraHeaders, modelId } = options
const client = await this.getClient(provider, extraHeaders)
const anthropicRequest = this.createAnthropicRequest(request, provider, modelId)
const messageCount = Array.isArray(request.messages) ? request.messages.length : 0
logger.info('Processing anthropic messages request', {
provider: provider.id,
apiHost: provider.apiHost,
anthropicApiHost: provider.anthropicApiHost,
model: anthropicRequest.model,
stream: !!anthropicRequest.stream,
// systemPrompt: JSON.stringify(!!request.system),
// messages: JSON.stringify(request.messages),
messageCount,
toolCount: Array.isArray(request.tools) ? request.tools.length : 0
})
// Return client and request for route layer to handle streaming/non-streaming
return {
client,
anthropicRequest
}
}
}
// Export singleton instance
export const messagesService = new MessagesService()

View File

@@ -0,0 +1,108 @@
import { ApiModel, ApiModelsFilter, ApiModelsResponse } from '../../../renderer/src/types/apiModels'
import { loggerService } from '../../services/LoggerService'
import { getAvailableProviders, listAllAvailableModels, transformModelToOpenAI } from '../utils'
const logger = loggerService.withContext('ModelsService')
// Re-export for backward compatibility
export type ModelsFilter = ApiModelsFilter
export class ModelsService {
async getModels(filter: ModelsFilter): Promise<ApiModelsResponse> {
try {
logger.debug('Getting available models from providers', { filter })
let providers = await getAvailableProviders()
if (filter.providerType === 'anthropic') {
providers = providers.filter(
(p) => p.type === 'anthropic' || (p.anthropicApiHost !== undefined && p.anthropicApiHost.trim() !== '')
)
}
const models = await listAllAvailableModels(providers)
// Use Map to deduplicate models by their full ID (provider:model_id)
const uniqueModels = new Map<string, ApiModel>()
for (const model of models) {
const provider = providers.find((p) => p.id === model.provider)
logger.debug(`Processing model ${model.id} from provider ${model.provider}`, {
isAnthropicModel: provider?.isAnthropicModel
})
if (
!provider ||
(filter.providerType === 'anthropic' && provider.isAnthropicModel && !provider.isAnthropicModel(model))
) {
continue
}
// Special case: For "aihubmix", it should be covered by above condition, but just in case
if (provider.id === 'aihubmix' && filter.providerType === 'anthropic' && !model.id.includes('claude')) {
continue
}
const openAIModel = transformModelToOpenAI(model, provider)
const fullModelId = openAIModel.id // This is already in format "provider:model_id"
// Only add if not already present (first occurrence wins)
if (!uniqueModels.has(fullModelId)) {
uniqueModels.set(fullModelId, openAIModel)
} else {
logger.debug(`Skipping duplicate model: ${fullModelId}`)
}
}
let modelData = Array.from(uniqueModels.values())
const total = modelData.length
// Apply pagination
const offset = filter?.offset || 0
const limit = filter?.limit
if (limit !== undefined) {
modelData = modelData.slice(offset, offset + limit)
logger.debug(
`Applied pagination: offset=${offset}, limit=${limit}, showing ${modelData.length} of ${total} models`
)
} else if (offset > 0) {
modelData = modelData.slice(offset)
logger.debug(`Applied offset: offset=${offset}, showing ${modelData.length} of ${total} models`)
}
logger.info('Models retrieved', {
returned: modelData.length,
discovered: models.length,
filter
})
if (models.length > total) {
logger.debug(`Filtered out ${models.length - total} models after deduplication and filtering`)
}
const response: ApiModelsResponse = {
object: 'list',
data: modelData
}
// Add pagination metadata if applicable
if (filter?.limit !== undefined || filter?.offset !== undefined) {
response.total = total
response.offset = offset
if (filter?.limit !== undefined) {
response.limit = filter.limit
}
}
return response
} catch (error: any) {
logger.error('Error getting models', { error, filter })
return {
object: 'list',
data: []
}
}
}
}
// Export singleton instance
export const modelsService = new ModelsService()

View File

@@ -0,0 +1,64 @@
export type StreamAbortHandler = (reason: unknown) => void
export interface StreamAbortController {
abortController: AbortController
registerAbortHandler: (handler: StreamAbortHandler) => void
clearAbortTimeout: () => void
}
export const STREAM_TIMEOUT_REASON = 'stream timeout'
interface CreateStreamAbortControllerOptions {
timeoutMs: number
}
export const createStreamAbortController = (options: CreateStreamAbortControllerOptions): StreamAbortController => {
const { timeoutMs } = options
const abortController = new AbortController()
const signal = abortController.signal
let timeoutId: NodeJS.Timeout | undefined
let abortHandler: StreamAbortHandler | undefined
const clearAbortTimeout = () => {
if (!timeoutId) {
return
}
clearTimeout(timeoutId)
timeoutId = undefined
}
const handleAbort = () => {
clearAbortTimeout()
if (!abortHandler) {
return
}
abortHandler(signal.reason)
}
signal.addEventListener('abort', handleAbort, { once: true })
const registerAbortHandler = (handler: StreamAbortHandler) => {
abortHandler = handler
if (signal.aborted) {
abortHandler(signal.reason)
}
}
if (timeoutMs > 0) {
timeoutId = setTimeout(() => {
if (!signal.aborted) {
abortController.abort(STREAM_TIMEOUT_REASON)
}
}, timeoutMs)
}
return {
abortController,
registerAbortHandler,
clearAbortTimeout
}
}

View File

@@ -1,46 +1,60 @@
import { CacheService } from '@main/services/CacheService'
import { loggerService } from '@main/services/LoggerService'
import { reduxService } from '@main/services/ReduxService'
import { Model, Provider } from '@types'
import { ApiModel, Model, Provider } from '@types'
const logger = loggerService.withContext('ApiServerUtils')
// OpenAI compatible model format
export interface OpenAICompatibleModel {
id: string
object: 'model'
created: number
owned_by: string
provider?: string
provider_model_id?: string
}
// Cache configuration
const PROVIDERS_CACHE_KEY = 'api-server:providers'
const PROVIDERS_CACHE_TTL = 10 * 1000 // 10 seconds
export async function getAvailableProviders(): Promise<Provider[]> {
try {
// Wait for store to be ready before accessing providers
// Try to get from cache first (faster)
const cachedSupportedProviders = CacheService.get<Provider[]>(PROVIDERS_CACHE_KEY)
if (cachedSupportedProviders && cachedSupportedProviders.length > 0) {
logger.debug('Providers resolved from cache', {
count: cachedSupportedProviders.length
})
return cachedSupportedProviders
}
// If cache is not available, get fresh data from Redux
const providers = await reduxService.select('state.llm.providers')
if (!providers || !Array.isArray(providers)) {
logger.warn('No providers found in Redux store, returning empty array')
logger.warn('No providers found in Redux store')
return []
}
// Only support OpenAI type providers for API server
const openAIProviders = providers.filter((p: Provider) => p.enabled && p.type === 'openai')
// Support OpenAI and Anthropic type providers for API server
const supportedProviders = providers.filter(
(p: Provider) => p.enabled && (p.type === 'openai' || p.type === 'anthropic')
)
logger.info(`Filtered to ${openAIProviders.length} OpenAI providers from ${providers.length} total providers`)
// Cache the filtered results
CacheService.set(PROVIDERS_CACHE_KEY, supportedProviders, PROVIDERS_CACHE_TTL)
return openAIProviders
logger.info('Providers filtered', {
supported: supportedProviders.length,
total: providers.length
})
return supportedProviders
} catch (error: any) {
logger.error('Failed to get providers from Redux store:', error)
logger.error('Failed to get providers from Redux store', { error })
return []
}
}
export async function listAllAvailableModels(): Promise<Model[]> {
export async function listAllAvailableModels(providers?: Provider[]): Promise<Model[]> {
try {
const providers = await getAvailableProviders()
if (!providers) {
providers = await getAvailableProviders()
}
return providers.map((p: Provider) => p.models || []).flat()
} catch (error: any) {
logger.error('Failed to list available models:', error)
logger.error('Failed to list available models', { error })
return []
}
}
@@ -48,15 +62,13 @@ export async function listAllAvailableModels(): Promise<Model[]> {
export async function getProviderByModel(model: string): Promise<Provider | undefined> {
try {
if (!model || typeof model !== 'string') {
logger.warn(`Invalid model parameter: ${model}`)
logger.warn('Invalid model parameter', { model })
return undefined
}
// Validate model format first
if (!model.includes(':')) {
logger.warn(
`Invalid model format, must contain ':' separator. Expected format "provider:model_id", got: ${model}`
)
logger.warn('Invalid model format missing separator', { model })
return undefined
}
@@ -64,7 +76,7 @@ export async function getProviderByModel(model: string): Promise<Provider | unde
const modelInfo = model.split(':')
if (modelInfo.length < 2 || modelInfo[0].length === 0 || modelInfo[1].length === 0) {
logger.warn(`Invalid model format, expected "provider:model_id" with non-empty parts, got: ${model}`)
logger.warn('Invalid model format with empty parts', { model })
return undefined
}
@@ -72,16 +84,17 @@ export async function getProviderByModel(model: string): Promise<Provider | unde
const provider = providers.find((p: Provider) => p.id === providerId)
if (!provider) {
logger.warn(
`Provider '${providerId}' not found or not enabled. Available providers: ${providers.map((p) => p.id).join(', ')}`
)
logger.warn('Provider not found for model', {
providerId,
available: providers.map((p) => p.id)
})
return undefined
}
logger.debug(`Found provider '${providerId}' for model: ${model}`)
logger.debug('Provider resolved for model', { providerId, model })
return provider
} catch (error: any) {
logger.error('Failed to get provider by model:', error)
logger.error('Failed to get provider by model', { error, model })
return undefined
}
}
@@ -96,9 +109,12 @@ export interface ModelValidationError {
code: string
}
export async function validateModelId(
model: string
): Promise<{ valid: boolean; error?: ModelValidationError; provider?: Provider; modelId?: string }> {
export async function validateModelId(model: string): Promise<{
valid: boolean
error?: ModelValidationError
provider?: Provider
modelId?: string
}> {
try {
if (!model || typeof model !== 'string') {
return {
@@ -169,7 +185,7 @@ export async function validateModelId(
modelId
}
} catch (error: any) {
logger.error('Error validating model ID:', error)
logger.error('Error validating model ID', { error, model })
return {
valid: false,
error: {
@@ -181,17 +197,47 @@ export async function validateModelId(
}
}
export function transformModelToOpenAI(model: Model): OpenAICompatibleModel {
export function transformModelToOpenAI(model: Model, provider?: Provider): ApiModel {
const providerDisplayName = provider?.name
return {
id: `${model.provider}:${model.id}`,
object: 'model',
name: model.name,
created: Math.floor(Date.now() / 1000),
owned_by: model.owned_by || model.provider,
owned_by: model.owned_by || providerDisplayName || model.provider,
provider: model.provider,
provider_name: providerDisplayName,
provider_type: provider?.type,
provider_model_id: model.id
}
}
export async function getProviderById(providerId: string): Promise<Provider | undefined> {
try {
if (!providerId || typeof providerId !== 'string') {
logger.warn('Invalid provider ID parameter', { providerId })
return undefined
}
const providers = await getAvailableProviders()
const provider = providers.find((p: Provider) => p.id === providerId)
if (!provider) {
logger.warn('Provider not found by ID', {
providerId,
available: providers.map((p) => p.id)
})
return undefined
}
logger.debug('Provider found by ID', { providerId })
return provider
} catch (error: any) {
logger.error('Failed to get provider by ID', { error, providerId })
return undefined
}
}
export function validateProvider(provider: Provider): boolean {
try {
if (!provider) {
@@ -200,7 +246,7 @@ export function validateProvider(provider: Provider): boolean {
// Check required fields
if (!provider.id || !provider.type || !provider.apiKey || !provider.apiHost) {
logger.warn('Provider missing required fields:', {
logger.warn('Provider missing required fields', {
id: !!provider.id,
type: !!provider.type,
apiKey: !!provider.apiKey,
@@ -211,21 +257,25 @@ export function validateProvider(provider: Provider): boolean {
// Check if provider is enabled
if (!provider.enabled) {
logger.debug(`Provider is disabled: ${provider.id}`)
logger.debug('Provider is disabled', { providerId: provider.id })
return false
}
// Only support OpenAI type providers
if (provider.type !== 'openai') {
logger.debug(
`Provider type '${provider.type}' not supported, only 'openai' type is currently supported: ${provider.id}`
)
// Support OpenAI and Anthropic type providers
if (provider.type !== 'openai' && provider.type !== 'anthropic') {
logger.debug('Provider type not supported', {
providerId: provider.id,
providerType: provider.type
})
return false
}
return true
} catch (error: any) {
logger.error('Error validating provider:', error)
logger.error('Error validating provider', {
error,
providerId: provider?.id
})
return false
}
}

View File

@@ -1,3 +1,4 @@
import { CacheService } from '@main/services/CacheService'
import mcpService from '@main/services/MCPService'
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
import { CallToolRequestSchema, ListToolsRequestSchema, ListToolsResult } from '@modelcontextprotocol/sdk/types.js'
@@ -8,6 +9,10 @@ import { reduxService } from '../../services/ReduxService'
const logger = loggerService.withContext('MCPApiService')
// Cache configuration
const MCP_SERVERS_CACHE_KEY = 'api-server:mcp-servers'
const MCP_SERVERS_CACHE_TTL = 5 * 60 * 1000 // 5 minutes
const cachedServers: Record<string, Server> = {}
async function handleListToolsRequest(request: any, extra: any): Promise<ListToolsResult> {
@@ -33,20 +38,35 @@ async function handleCallToolRequest(request: any, extra: any): Promise<any> {
}
async function getMcpServerConfigById(id: string): Promise<MCPServer | undefined> {
const servers = await getServersFromRedux()
const servers = await getMCPServersFromRedux()
return servers.find((s) => s.id === id || s.name === id)
}
/**
* Get servers directly from Redux store
*/
async function getServersFromRedux(): Promise<MCPServer[]> {
export async function getMCPServersFromRedux(): Promise<MCPServer[]> {
try {
logger.debug('Getting servers from Redux store')
// Try to get from cache first (faster)
const cachedServers = CacheService.get<MCPServer[]>(MCP_SERVERS_CACHE_KEY)
if (cachedServers) {
logger.debug('MCP servers resolved from cache', { count: cachedServers.length })
return cachedServers
}
// If cache is not available, get fresh data from Redux
const servers = await reduxService.select<MCPServer[]>('state.mcp.servers')
logger.silly(`Fetched ${servers?.length || 0} servers from Redux store`)
return servers || []
const serverList = servers || []
// Cache the results
CacheService.set(MCP_SERVERS_CACHE_KEY, serverList, MCP_SERVERS_CACHE_TTL)
logger.debug('Fetched servers from Redux store', { count: serverList.length })
return serverList
} catch (error: any) {
logger.error('Failed to get servers from Redux:', error)
logger.error('Failed to get servers from Redux', { error })
return []
}
}
@@ -54,7 +74,7 @@ async function getServersFromRedux(): Promise<MCPServer[]> {
export async function getMcpServerById(id: string): Promise<Server> {
const server = cachedServers[id]
if (!server) {
const servers = await getServersFromRedux()
const servers = await getMCPServersFromRedux()
const mcpServer = servers.find((s) => s.id === id || s.name === id)
if (!mcpServer) {
throw new Error(`Server not found: ${id}`)
@@ -71,6 +91,6 @@ export async function getMcpServerById(id: string): Promise<Server> {
cachedServers[id] = newServer
return newServer
}
logger.silly('getMcpServer ', { server: server })
logger.debug('Returning cached MCP server', { id, hasHandlers: Boolean(server) })
return server
}

View File

@@ -10,9 +10,13 @@ import { electronApp, optimizer } from '@electron-toolkit/utils'
import { replaceDevtoolsFont } from '@main/utils/windowUtil'
import { app } from 'electron'
import installExtension, { REACT_DEVELOPER_TOOLS, REDUX_DEVTOOLS } from 'electron-devtools-installer'
import { isDev, isLinux, isWin } from './constant'
import process from 'node:process'
import { registerIpc } from './ipc'
import { agentService } from './services/agents'
import { apiServerService } from './services/ApiServerService'
import { configManager } from './services/ConfigManager'
import mcpService from './services/MCPService'
import { nodeTraceService } from './services/NodeTraceService'
@@ -26,8 +30,7 @@ import selectionService, { initSelectionService } from './services/SelectionServ
import { registerShortcuts } from './services/ShortcutService'
import { TrayService } from './services/TrayService'
import { windowService } from './services/WindowService'
import process from 'node:process'
import { apiServerService } from './services/ApiServerService'
import { initWebviewHotkeys } from './services/WebviewService'
const logger = loggerService.withContext('MainEntry')
@@ -106,6 +109,7 @@ if (!app.requestSingleInstanceLock()) {
// Some APIs can only be used after this event occurs.
app.whenReady().then(async () => {
initWebviewHotkeys()
// Set app user model id for windows
electronApp.setAppUserModelId(import.meta.env.VITE_MAIN_BUNDLE_ID || 'com.kangfenmao.CherryStudio')
@@ -147,6 +151,14 @@ if (!app.requestSingleInstanceLock()) {
//start selection assistant service
initSelectionService()
// Initialize Agent Service
try {
await agentService.initialize()
logger.info('Agent service initialized successfully')
} catch (error: any) {
logger.error('Failed to initialize Agent service:', error)
}
// Start API server if enabled
try {
const config = await apiServerService.getCurrentConfig()

View File

@@ -11,11 +11,21 @@ import { handleZoomFactor } from '@main/utils/zoom'
import { SpanEntity, TokenUsage } from '@mcp-trace/trace-core'
import { MIN_WINDOW_HEIGHT, MIN_WINDOW_WIDTH, UpgradeChannel } from '@shared/config/constant'
import { IpcChannel } from '@shared/IpcChannel'
import { FileMetadata, Notification, OcrProvider, Provider, Shortcut, SupportedOcrFile, ThemeMode } from '@types'
import {
AgentPersistedMessage,
FileMetadata,
Notification,
OcrProvider,
Provider,
Shortcut,
SupportedOcrFile,
ThemeMode
} from '@types'
import checkDiskSpace from 'check-disk-space'
import { BrowserWindow, dialog, ipcMain, ProxyConfig, session, shell, systemPreferences, webContents } from 'electron'
import fontList from 'font-list'
import { agentMessageRepository } from './services/agents/database'
import { apiServerService } from './services/ApiServerService'
import appService from './services/AppService'
import AppUpdater from './services/AppUpdater'
@@ -27,6 +37,7 @@ import DxtService from './services/DxtService'
import { ExportService } from './services/ExportService'
import { fileStorage as fileManager } from './services/FileStorage'
import FileService from './services/FileSystemService'
import { jsService } from './services/JsService'
import KnowledgeService from './services/KnowledgeService'
import mcpService from './services/MCPService'
import MemoryService from './services/memory/MemoryService'
@@ -132,7 +143,7 @@ export function registerIpc(mainWindow: BrowserWindow, app: Electron.App) {
ipcMain.handle(IpcChannel.Open_Website, (_, url: string) => shell.openExternal(url))
// Update
ipcMain.handle(IpcChannel.App_ShowUpdateDialog, () => appUpdater.showUpdateDialog(mainWindow))
ipcMain.handle(IpcChannel.App_QuitAndInstall, () => appUpdater.quitAndInstall())
// language
ipcMain.handle(IpcChannel.App_SetLanguage, (_, language) => {
@@ -202,6 +213,27 @@ export function registerIpc(mainWindow: BrowserWindow, app: Electron.App) {
}
})
ipcMain.handle(IpcChannel.AgentMessage_PersistExchange, async (_event, payload) => {
try {
return await agentMessageRepository.persistExchange(payload)
} catch (error) {
logger.error('Failed to persist agent session messages', error as Error)
throw error
}
})
ipcMain.handle(
IpcChannel.AgentMessage_GetHistory,
async (_event, { sessionId }: { sessionId: string }): Promise<AgentPersistedMessage[]> => {
try {
return await agentMessageRepository.getSessionHistory(sessionId)
} catch (error) {
logger.error('Failed to get agent session history', error as Error)
throw error
}
}
)
//only for mac
if (isMac) {
ipcMain.handle(IpcChannel.App_MacIsProcessTrusted, (): boolean => {
@@ -498,6 +530,7 @@ export function registerIpc(mainWindow: BrowserWindow, app: Electron.App) {
ipcMain.handle(IpcChannel.File_ValidateNotesDirectory, fileManager.validateNotesDirectory.bind(fileManager))
ipcMain.handle(IpcChannel.File_StartWatcher, fileManager.startFileWatcher.bind(fileManager))
ipcMain.handle(IpcChannel.File_StopWatcher, fileManager.stopFileWatcher.bind(fileManager))
ipcMain.handle(IpcChannel.File_ShowInFolder, fileManager.showInFolder.bind(fileManager))
// file service
ipcMain.handle(IpcChannel.FileService_Upload, async (_, provider: Provider, file: FileMetadata) => {
@@ -709,6 +742,11 @@ export function registerIpc(mainWindow: BrowserWindow, app: Electron.App) {
}
)
// Register JavaScript execution handler
ipcMain.handle(IpcChannel.Js_Execute, async (_, code: string, timeout?: number) => {
return await jsService.executeScript(code, { timeout })
})
ipcMain.handle(IpcChannel.App_IsBinaryExist, (_, name: string) => isBinaryExists(name))
ipcMain.handle(IpcChannel.App_GetBinaryPath, (_, name: string) => getBinaryPath(name))
ipcMain.handle(IpcChannel.App_InstallUvBinary, () => runInstallScript('install-uv.js'))
@@ -754,7 +792,6 @@ export function registerIpc(mainWindow: BrowserWindow, app: Electron.App) {
ipcMain.handle(IpcChannel.Webview_SetOpenLinkExternal, (_, webviewId: number, isExternal: boolean) =>
setOpenLinkExternal(webviewId, isExternal)
)
ipcMain.handle(IpcChannel.Webview_SetSpellCheckEnabled, (_, webviewId: number, isEnable: boolean) => {
const webview = webContents.fromId(webviewId)
if (!webview) return

View File

@@ -3,7 +3,7 @@ import { loggerService } from '@logger'
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'
import { net } from 'electron'
import { z } from 'zod'
import * as z from 'zod'
const logger = loggerService.withContext('DifyKnowledgeServer')

View File

@@ -6,6 +6,7 @@ import BraveSearchServer from './brave-search'
import DifyKnowledgeServer from './dify-knowledge'
import FetchServer from './fetch'
import FileSystemServer from './filesystem'
import JsServer from './js'
import MemoryServer from './memory'
import PythonServer from './python'
import ThinkingServer from './sequentialthinking'
@@ -42,6 +43,9 @@ export function createInMemoryMCPServer(
case BuiltinMCPServerNames.python: {
return new PythonServer().server
}
case BuiltinMCPServerNames.js: {
return new JsServer().server
}
default:
throw new Error(`Unknown in-memory MCP server: ${name}`)
}

View File

@@ -5,7 +5,7 @@ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprot
import { net } from 'electron'
import { JSDOM } from 'jsdom'
import TurndownService from 'turndown'
import { z } from 'zod'
import * as z from 'zod'
export const RequestPayloadSchema = z.object({
url: z.url(),

View File

@@ -8,7 +8,7 @@ import fs from 'fs/promises'
import { minimatch } from 'minimatch'
import os from 'os'
import path from 'path'
import { z } from 'zod'
import * as z from 'zod'
const logger = loggerService.withContext('MCP:FileSystemServer')

139
src/main/mcpServers/js.ts Normal file
View File

@@ -0,0 +1,139 @@
// port from https://github.com/jlucaso1/mcp-javascript-sandbox
import { loggerService } from '@logger'
import { jsService } from '@main/services/JsService'
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types'
import * as z from 'zod'
const TOOL_NAME = 'run_javascript_code'
const DEFAULT_TIMEOUT = 60_000
export const RequestPayloadSchema = z.object({
javascript_code: z.string().min(1).describe('The JavaScript code to execute in the sandbox.'),
timeout: z
.number()
.int()
.positive()
.max(5 * 60_000)
.optional()
.describe('Execution timeout in milliseconds (default 60000, max 300000).')
})
const logger = loggerService.withContext('MCPServer:JavaScript')
function formatExecutionResult(result: {
stdout: string
stderr: string
error?: string | undefined
exitCode: number
}) {
let combinedOutput = ''
if (result.stdout) {
combinedOutput += result.stdout
}
if (result.stderr) {
combinedOutput += `--- stderr ---\n${result.stderr}\n--- stderr ---\n`
}
if (result.error) {
combinedOutput += `--- Execution Error ---\n${result.error}\n--- Execution Error ---\n`
}
const isError = Boolean(result.error) || Boolean(result.stderr?.trim()) || result.exitCode !== 0
return {
combinedOutput: combinedOutput.trim(),
isError
}
}
class JsServer {
public server: Server
constructor() {
this.server = new Server(
{
name: 'MCP QuickJS Runner',
version: '1.0.0',
description: 'An MCP server that provides a tool to execute JavaScript code in a QuickJS WASM sandbox.'
},
{
capabilities: {
resources: {},
tools: {}
}
}
)
this.setupHandlers()
}
private setupHandlers() {
this.server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: TOOL_NAME,
description:
'Executes the provided JavaScript code in a secure WASM sandbox (QuickJS). Returns stdout and stderr. Non-zero exit code indicates an error.',
inputSchema: z.toJSONSchema(RequestPayloadSchema)
}
]
}
})
this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params
if (name !== TOOL_NAME) {
return {
content: [{ type: 'text', text: `Tool not found: ${name}` }],
isError: true
}
}
const parseResult = RequestPayloadSchema.safeParse(args)
if (!parseResult.success) {
return {
content: [{ type: 'text', text: `Invalid arguments: ${parseResult.error.message}` }],
isError: true
}
}
const { javascript_code, timeout } = parseResult.data
try {
logger.debug('Executing JavaScript code via JsService')
const result = await jsService.executeScript(javascript_code, {
timeout: timeout ?? DEFAULT_TIMEOUT
})
const { combinedOutput, isError } = formatExecutionResult(result)
return {
content: [
{
type: 'text',
text: combinedOutput
}
],
isError
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
logger.error(`JavaScript execution failed: ${message}`)
return {
content: [
{
type: 'text',
text: `Server error during tool execution: ${message}`
}
],
isError: true
}
}
})
}
}
export default JsServer

View File

@@ -1,17 +1,15 @@
import { loggerService } from '@logger'
import { isWin } from '@main/constant'
import { getIpCountry } from '@main/utils/ipService'
import { locales } from '@main/utils/locales'
import { generateUserAgent } from '@main/utils/systemInfo'
import { FeedUrl, UpgradeChannel } from '@shared/config/constant'
import { IpcChannel } from '@shared/IpcChannel'
import { CancellationToken, UpdateInfo } from 'builder-util-runtime'
import { app, BrowserWindow, dialog, net } from 'electron'
import { app, net } from 'electron'
import { AppUpdater as _AppUpdater, autoUpdater, Logger, NsisUpdater, UpdateCheckResult } from 'electron-updater'
import path from 'path'
import semver from 'semver'
import icon from '../../../build/icon.png?asset'
import { configManager } from './ConfigManager'
import { windowService } from './WindowService'
@@ -26,7 +24,6 @@ const LANG_MARKERS = {
export default class AppUpdater {
autoUpdater: _AppUpdater = autoUpdater
private releaseInfo: UpdateInfo | undefined
private cancellationToken: CancellationToken = new CancellationToken()
private updateCheckResult: UpdateCheckResult | null = null
@@ -66,7 +63,6 @@ export default class AppUpdater {
autoUpdater.on('update-downloaded', (releaseInfo: UpdateInfo) => {
const processedReleaseInfo = this.processReleaseInfo(releaseInfo)
windowService.getMainWindow()?.webContents.send(IpcChannel.UpdateDownloaded, processedReleaseInfo)
this.releaseInfo = processedReleaseInfo
logger.info('update downloaded', processedReleaseInfo)
})
@@ -247,37 +243,9 @@ export default class AppUpdater {
}
}
public async showUpdateDialog(mainWindow: BrowserWindow) {
if (!this.releaseInfo) {
return
}
const locale = locales[configManager.getLanguage()]
const { update: updateLocale } = locale.translation
let detail = this.formatReleaseNotes(this.releaseInfo.releaseNotes)
if (detail === '') {
detail = updateLocale.noReleaseNotes
}
dialog
.showMessageBox({
type: 'info',
title: updateLocale.title,
icon,
message: updateLocale.message.replace('{{version}}', this.releaseInfo.version),
detail,
buttons: [updateLocale.later, updateLocale.install],
defaultId: 1,
cancelId: 0
})
.then(({ response }) => {
if (response === 1) {
app.isQuitting = true
setImmediate(() => autoUpdater.quitAndInstall())
} else {
mainWindow.webContents.send(IpcChannel.UpdateDownloadedCancelled)
}
})
public quitAndInstall() {
app.isQuitting = true
setImmediate(() => autoUpdater.quitAndInstall())
}
/**
@@ -349,38 +317,9 @@ export default class AppUpdater {
return processedInfo
}
/**
* Format release notes for display
* @param releaseNotes - Release notes in various formats
* @returns Formatted string for display
*/
private formatReleaseNotes(releaseNotes: string | ReleaseNoteInfo[] | null | undefined): string {
if (!releaseNotes) {
return ''
}
if (typeof releaseNotes === 'string') {
// Check if it contains multi-language markers
if (this.hasMultiLanguageMarkers(releaseNotes)) {
return this.parseMultiLangReleaseNotes(releaseNotes)
}
return releaseNotes
}
if (Array.isArray(releaseNotes)) {
return releaseNotes.map((note) => note.note).join('\n')
}
return ''
}
}
interface GithubReleaseInfo {
draft: boolean
prerelease: boolean
tag_name: string
}
interface ReleaseNoteInfo {
readonly version: string
readonly note: string | null
}

View File

@@ -725,7 +725,10 @@ class FileStorage {
}
public openPath = async (_: Electron.IpcMainInvokeEvent, path: string): Promise<void> => {
shell.openPath(path).catch((err) => logger.error('[IPC - Error] Failed to open file:', err))
const resolved = await shell.openPath(path)
if (resolved !== '') {
throw new Error(resolved)
}
}
/**
@@ -1229,6 +1232,19 @@ class FileStorage {
return false
}
}
public showInFolder = async (_: Electron.IpcMainInvokeEvent, path: string): Promise<void> => {
if (!fs.existsSync(path)) {
const msg = `File or folder does not exist: ${path}`
logger.error(msg)
throw new Error(msg)
}
try {
shell.showItemInFolder(path)
} catch (error) {
logger.error('Failed to show item in folder:', error as Error)
}
}
}
export const fileStorage = new FileStorage()

View File

@@ -0,0 +1,115 @@
import { loggerService } from '@logger'
import type { JsExecutionResult } from './workers/JsWorker'
// oxlint-disable-next-line default
import createJsWorker from './workers/JsWorker?nodeWorker'
interface ExecuteScriptOptions {
timeout?: number
}
type WorkerResponse =
| {
success: true
result: JsExecutionResult
}
| {
success: false
error: string
}
const DEFAULT_TIMEOUT = 60_000
const logger = loggerService.withContext('JsService')
export class JsService {
private static instance: JsService | null = null
private constructor() {}
public static getInstance(): JsService {
if (!JsService.instance) {
JsService.instance = new JsService()
}
return JsService.instance
}
public async executeScript(code: string, options: ExecuteScriptOptions = {}): Promise<JsExecutionResult> {
const { timeout = DEFAULT_TIMEOUT } = options
if (!code || typeof code !== 'string') {
throw new Error('JavaScript code must be a non-empty string')
}
// Limit code size to 1MB to prevent memory issues
const MAX_CODE_SIZE = 1_000_000
if (code.length > MAX_CODE_SIZE) {
throw new Error(`JavaScript code exceeds maximum size of ${MAX_CODE_SIZE / 1_000_000}MB`)
}
return new Promise<JsExecutionResult>((resolve, reject) => {
const worker = createJsWorker({
workerData: { code },
argv: [],
trackUnmanagedFds: false
})
let settled = false
let timeoutId: NodeJS.Timeout | null = null
const cleanup = async () => {
if (timeoutId) {
clearTimeout(timeoutId)
timeoutId = null
}
try {
await worker.terminate()
} catch {
// ignore termination errors
}
}
const settleSuccess = async (result: JsExecutionResult) => {
if (settled) return
settled = true
await cleanup()
resolve(result)
}
const settleError = async (error: Error) => {
if (settled) return
settled = true
await cleanup()
reject(error)
}
worker.once('message', async (message: WorkerResponse) => {
if (message.success) {
await settleSuccess(message.result)
} else {
await settleError(new Error(message.error))
}
})
worker.once('error', async (error) => {
logger.error(`JsWorker error: ${error instanceof Error ? error.message : String(error)}`)
await settleError(error instanceof Error ? error : new Error(String(error)))
})
worker.once('exit', async (exitCode) => {
if (!settled && exitCode !== 0) {
await settleError(new Error(`JsWorker exited with code ${exitCode}`))
}
})
timeoutId = setTimeout(() => {
logger.warn(`JavaScript execution timed out after ${timeout}ms`)
settleError(new Error('JavaScript execution timed out')).catch((err) => {
logger.error('Error during timeout cleanup:', err instanceof Error ? err : new Error(String(err)))
})
}, timeout)
})
}
}
export const jsService = JsService.getInstance()

View File

@@ -29,7 +29,7 @@ import Reranker from '@main/knowledge/reranker/Reranker'
import { fileStorage } from '@main/services/FileStorage'
import { windowService } from '@main/services/WindowService'
import { getDataPath } from '@main/utils'
import { getAllFiles } from '@main/utils/file'
import { getAllFiles, sanitizeFilename } from '@main/utils/file'
import { TraceMethod } from '@mcp-trace/trace-core'
import { MB } from '@shared/config/constant'
import type { LoaderReturn } from '@shared/config/types'
@@ -147,11 +147,16 @@ class KnowledgeService {
}
}
private getDbPath = (id: string): string => {
// 消除网络搜索requestI d中的特殊字符
return path.join(this.storageDir, sanitizeFilename(id, '_'))
}
/**
* Delete knowledge base file
*/
private deleteKnowledgeFile = (id: string): boolean => {
const dbPath = path.join(this.storageDir, id)
const dbPath = this.getDbPath(id)
if (fs.existsSync(dbPath)) {
try {
fs.rmSync(dbPath, { recursive: true })
@@ -244,7 +249,8 @@ class KnowledgeService {
dimensions
})
try {
const libSqlDb = new LibSqlDb({ path: path.join(this.storageDir, id) })
const dbPath = this.getDbPath(id)
const libSqlDb = new LibSqlDb({ path: dbPath })
// Save database instance for later closing
this.dbInstances.set(id, libSqlDb)

View File

@@ -7,6 +7,7 @@ import { createInMemoryMCPServer } from '@main/mcpServers/factory'
import { makeSureDirExists, removeEnvProxy } from '@main/utils'
import { buildFunctionCallToolName } from '@main/utils/mcp'
import { getBinaryName, getBinaryPath } from '@main/utils/process'
import getLoginShellEnvironment from '@main/utils/shell-env'
import { TraceMethod, withSpanFunc } from '@mcp-trace/trace-core'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { SSEClientTransport, SSEClientTransportOptions } from '@modelcontextprotocol/sdk/client/sse.js'
@@ -43,14 +44,12 @@ import {
} from '@types'
import { app, net } from 'electron'
import { EventEmitter } from 'events'
import { memoize } from 'lodash'
import { v4 as uuidv4 } from 'uuid'
import { CacheService } from './CacheService'
import DxtService from './DxtService'
import { CallBackServer } from './mcp/oauth/callback'
import { McpOAuthClientProvider } from './mcp/oauth/provider'
import getLoginShellEnvironment from './mcp/shell-env'
import { windowService } from './WindowService'
// Generic type for caching wrapped functions
@@ -335,7 +334,7 @@ class McpService {
getServerLogger(server).debug(`Starting server`, { command: cmd, args })
// Logger.info(`[MCP] Environment variables for server:`, server.env)
const loginShellEnv = await this.getLoginShellEnv()
const loginShellEnv = await getLoginShellEnvironment()
// Bun not support proxy https://github.com/oven-sh/bun/issues/16812
if (cmd.includes('bun')) {
@@ -878,20 +877,6 @@ class McpService {
return await cachedGetResource(server, uri)
}
private getLoginShellEnv = memoize(async (): Promise<Record<string, string>> => {
try {
const loginEnv = await getLoginShellEnvironment()
const pathSeparator = process.platform === 'win32' ? ';' : ':'
const cherryBinPath = path.join(os.homedir(), '.cherrystudio', 'bin')
loginEnv.PATH = `${loginEnv.PATH}${pathSeparator}${cherryBinPath}`
logger.debug('Successfully fetched login shell environment variables:')
return loginEnv
} catch (error) {
logger.error('Failed to fetch login shell environment variables:', error as Error)
return {}
}
})
// 实现 abortTool 方法
public async abortTool(_: Electron.IpcMainInvokeEvent, callId: string) {
const activeToolCall = this.activeToolCalls.get(callId)

View File

@@ -1,4 +1,5 @@
import { session, shell, webContents } from 'electron'
import { IpcChannel } from '@shared/IpcChannel'
import { app, session, shell, webContents } from 'electron'
/**
* init the useragent of the webview session
@@ -36,3 +37,61 @@ export function setOpenLinkExternal(webviewId: number, isExternal: boolean) {
}
})
}
const attachKeyboardHandler = (contents: Electron.WebContents) => {
if (contents.getType?.() !== 'webview') {
return
}
const handleBeforeInput = (event: Electron.Event, input: Electron.Input) => {
if (!input) {
return
}
const key = input.key?.toLowerCase()
if (!key) {
return
}
const isFindShortcut = (input.control || input.meta) && key === 'f'
const isEscape = key === 'escape'
const isEnter = key === 'enter'
if (!isFindShortcut && !isEscape && !isEnter) {
return
}
// Prevent default to override the guest page's native find dialog
// and keep shortcuts routed to our custom search overlay
event.preventDefault()
const host = contents.hostWebContents
if (!host || host.isDestroyed()) {
return
}
host.send(IpcChannel.Webview_SearchHotkey, {
webviewId: contents.id,
key,
control: Boolean(input.control),
meta: Boolean(input.meta),
shift: Boolean(input.shift),
alt: Boolean(input.alt)
})
}
contents.on('before-input-event', handleBeforeInput)
contents.once('destroyed', () => {
contents.removeListener('before-input-event', handleBeforeInput)
})
}
export function initWebviewHotkeys() {
webContents.getAllWebContents().forEach((contents) => {
if (contents.isDestroyed()) return
attachKeyboardHandler(contents)
})
app.on('web-contents-created', (_, contents) => {
attachKeyboardHandler(contents)
})
}

View File

@@ -274,46 +274,4 @@ describe('AppUpdater', () => {
expect(result.releaseNotes).toBeNull()
})
})
describe('formatReleaseNotes', () => {
it('should format string release notes with markers', () => {
vi.mocked(configManager.getLanguage).mockReturnValue('en-US')
const notes = `<!--LANG:en-->English<!--LANG:zh-CN-->中文<!--LANG:END-->`
const result = (appUpdater as any).formatReleaseNotes(notes)
expect(result).toBe('English')
})
it('should format string release notes without markers', () => {
const notes = 'Simple notes'
const result = (appUpdater as any).formatReleaseNotes(notes)
expect(result).toBe('Simple notes')
})
it('should format array release notes', () => {
const notes = [
{ version: '1.0.0', note: 'Note 1' },
{ version: '1.0.1', note: 'Note 2' }
]
const result = (appUpdater as any).formatReleaseNotes(notes)
expect(result).toBe('Note 1\nNote 2')
})
it('should handle null release notes', () => {
const result = (appUpdater as any).formatReleaseNotes(null)
expect(result).toBe('')
})
it('should handle undefined release notes', () => {
const result = (appUpdater as any).formatReleaseNotes(undefined)
expect(result).toBe('')
})
})
})

View File

@@ -0,0 +1,336 @@
import { type Client, createClient } from '@libsql/client'
import { loggerService } from '@logger'
import { mcpApiService } from '@main/apiServer/services/mcp'
import { ModelValidationError, validateModelId } from '@main/apiServer/utils'
import { AgentType, MCPTool, objectKeys, SlashCommand, Tool } from '@types'
import { drizzle, type LibSQLDatabase } from 'drizzle-orm/libsql'
import fs from 'fs'
import path from 'path'
import { MigrationService } from './database/MigrationService'
import * as schema from './database/schema'
import { dbPath } from './drizzle.config'
import { AgentModelField, AgentModelValidationError } from './errors'
import { builtinSlashCommands } from './services/claudecode/commands'
import { builtinTools } from './services/claudecode/tools'
const logger = loggerService.withContext('BaseService')
/**
* Base service class providing shared database connection and utilities
* for all agent-related services.
*
* Features:
* - Programmatic schema management (no CLI dependencies)
* - Automatic table creation and migration
* - Schema version tracking and compatibility checks
* - Transaction-based operations for safety
* - Development vs production mode handling
* - Connection retry logic with exponential backoff
*/
export abstract class BaseService {
protected static client: Client | null = null
protected static db: LibSQLDatabase<typeof schema> | null = null
protected static isInitialized = false
protected static initializationPromise: Promise<void> | null = null
protected jsonFields: string[] = ['tools', 'mcps', 'configuration', 'accessible_paths', 'allowed_tools']
/**
* Initialize database with retry logic and proper error handling
*/
protected static async initialize(): Promise<void> {
// Return existing initialization if in progress
if (BaseService.initializationPromise) {
return BaseService.initializationPromise
}
if (BaseService.isInitialized) {
return
}
BaseService.initializationPromise = BaseService.performInitialization()
return BaseService.initializationPromise
}
public async listMcpTools(agentType: AgentType, ids?: string[]): Promise<Tool[]> {
const tools: Tool[] = []
if (agentType === 'claude-code') {
tools.push(...builtinTools)
}
if (ids && ids.length > 0) {
for (const id of ids) {
try {
const server = await mcpApiService.getServerInfo(id)
if (server) {
server.tools.forEach((tool: MCPTool) => {
tools.push({
id: `mcp_${id}_${tool.name}`,
name: tool.name,
type: 'mcp',
description: tool.description || '',
requirePermissions: true
})
})
}
} catch (error) {
logger.warn('Failed to list MCP tools', {
id,
error: error as Error
})
}
}
}
return tools
}
public async listSlashCommands(agentType: AgentType): Promise<SlashCommand[]> {
if (agentType === 'claude-code') {
return builtinSlashCommands
}
return []
}
private static async performInitialization(): Promise<void> {
const maxRetries = 3
let lastError: Error
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
logger.info(`Initializing Agent database at: ${dbPath} (attempt ${attempt}/${maxRetries})`)
// Ensure the database directory exists
const dbDir = path.dirname(dbPath)
if (!fs.existsSync(dbDir)) {
logger.info(`Creating database directory: ${dbDir}`)
fs.mkdirSync(dbDir, { recursive: true })
}
BaseService.client = createClient({
url: `file:${dbPath}`
})
BaseService.db = drizzle(BaseService.client, { schema })
// Run database migrations
const migrationService = new MigrationService(BaseService.db, BaseService.client)
await migrationService.runMigrations()
BaseService.isInitialized = true
logger.info('Agent database initialized successfully')
return
} catch (error) {
lastError = error as Error
logger.warn(`Database initialization attempt ${attempt} failed:`, lastError)
// Clean up on failure
if (BaseService.client) {
try {
BaseService.client.close()
} catch (closeError) {
logger.warn('Failed to close client during cleanup:', closeError as Error)
}
}
BaseService.client = null
BaseService.db = null
// Wait before retrying (exponential backoff)
if (attempt < maxRetries) {
const delay = Math.pow(2, attempt) * 1000 // 2s, 4s, 8s
logger.info(`Retrying in ${delay}ms...`)
await new Promise((resolve) => setTimeout(resolve, delay))
}
}
}
// All retries failed
BaseService.initializationPromise = null
logger.error('Failed to initialize Agent database after all retries:', lastError!)
throw lastError!
}
protected ensureInitialized(): void {
if (!BaseService.isInitialized || !BaseService.db || !BaseService.client) {
throw new Error('Database not initialized. Call initialize() first.')
}
}
protected get database(): LibSQLDatabase<typeof schema> {
this.ensureInitialized()
return BaseService.db!
}
protected get rawClient(): Client {
this.ensureInitialized()
return BaseService.client!
}
protected serializeJsonFields(data: any): any {
const serialized = { ...data }
for (const field of this.jsonFields) {
if (serialized[field] !== undefined) {
serialized[field] =
Array.isArray(serialized[field]) || typeof serialized[field] === 'object'
? JSON.stringify(serialized[field])
: serialized[field]
}
}
return serialized
}
protected deserializeJsonFields(data: any): any {
if (!data) return data
const deserialized = { ...data }
for (const field of this.jsonFields) {
if (deserialized[field] && typeof deserialized[field] === 'string') {
try {
deserialized[field] = JSON.parse(deserialized[field])
} catch (error) {
logger.warn(`Failed to parse JSON field ${field}:`, error as Error)
}
}
}
// convert null from db to undefined to satisfy type definition
for (const key of objectKeys(data)) {
if (deserialized[key] === null) {
deserialized[key] = undefined
}
}
return deserialized
}
/**
* Validate, normalize, and ensure filesystem access for a set of absolute paths.
*
* - Requires every entry to be an absolute path and throws if not.
* - Normalizes each path and deduplicates while preserving order.
* - Creates missing directories (or parent directories for file-like paths).
*/
protected ensurePathsExist(paths?: string[]): string[] {
if (!paths?.length) {
return []
}
const sanitizedPaths: string[] = []
const seenPaths = new Set<string>()
for (const rawPath of paths) {
if (!rawPath) {
continue
}
if (!path.isAbsolute(rawPath)) {
throw new Error(`Accessible path must be absolute: ${rawPath}`)
}
// Normalize to provide consistent values to downstream consumers.
const resolvedPath = path.normalize(rawPath)
let stats: fs.Stats | null = null
try {
// Attempt to stat the path to understand whether it already exists and if it is a file.
if (fs.existsSync(resolvedPath)) {
stats = fs.statSync(resolvedPath)
}
} catch (error) {
logger.warn('Failed to inspect accessible path', {
path: rawPath,
error: error instanceof Error ? error.message : String(error)
})
}
const looksLikeFile =
(stats && stats.isFile()) || (!stats && path.extname(resolvedPath) !== '' && !resolvedPath.endsWith(path.sep))
// For file-like targets create the parent directory; otherwise ensure the directory itself.
const directoryToEnsure = looksLikeFile ? path.dirname(resolvedPath) : resolvedPath
if (!fs.existsSync(directoryToEnsure)) {
try {
fs.mkdirSync(directoryToEnsure, { recursive: true })
} catch (error) {
logger.error('Failed to create accessible path directory', {
path: directoryToEnsure,
error: error instanceof Error ? error.message : String(error)
})
throw error
}
}
// Preserve the first occurrence only to avoid duplicates while keeping caller order stable.
if (!seenPaths.has(resolvedPath)) {
seenPaths.add(resolvedPath)
sanitizedPaths.push(resolvedPath)
}
}
return sanitizedPaths
}
/**
* Force re-initialization (for development/testing)
*/
protected async validateAgentModels(
agentType: AgentType,
models: Partial<Record<AgentModelField, string | undefined>>
): Promise<void> {
const entries = Object.entries(models) as [AgentModelField, string | undefined][]
if (entries.length === 0) {
return
}
for (const [field, rawValue] of entries) {
if (rawValue === undefined || rawValue === null) {
continue
}
const modelValue = rawValue
const validation = await validateModelId(modelValue)
if (!validation.valid || !validation.provider) {
const detail: ModelValidationError = validation.error ?? {
type: 'invalid_format',
message: 'Unknown model validation error',
code: 'validation_error'
}
throw new AgentModelValidationError({ agentType, field, model: modelValue }, detail)
}
if (!validation.provider.apiKey) {
throw new AgentModelValidationError(
{ agentType, field, model: modelValue },
{
type: 'invalid_format',
message: `Provider '${validation.provider.id}' is missing an API key`,
code: 'provider_api_key_missing'
}
)
}
}
}
static async reinitialize(): Promise<void> {
BaseService.isInitialized = false
BaseService.initializationPromise = null
if (BaseService.client) {
try {
BaseService.client.close()
} catch (error) {
logger.warn('Failed to close client during reinitialize:', error as Error)
}
}
BaseService.client = null
BaseService.db = null
await BaseService.initialize()
}
}

View File

@@ -0,0 +1,81 @@
# Agents Service
Simplified Drizzle ORM implementation for agent and session management in Cherry Studio.
## Features
- **Native Drizzle migrations** - Uses built-in migrate() function
- **Zero CLI dependencies** in production
- **Auto-initialization** with retry logic
- **Full TypeScript** type safety
- **Model validation** to ensure models exist and provider configuration matches the agent type
## Schema
- `agents.schema.ts` - Agent definitions
- `sessions.schema.ts` - Session and message tables
- `migrations.schema.ts` - Migration tracking
## Usage
```typescript
import { agentService } from './services'
// Create agent - fully typed
const agent = await agentService.createAgent({
type: 'custom',
name: 'My Agent',
model: 'anthropic:claude-3-5-sonnet-20241022'
})
```
## Model Validation
- Model identifiers must use the `provider:model_id` format (for example `anthropic:claude-3-5-sonnet-20241022`).
- `model`, `plan_model`, and `small_model` are validated against the configured providers before the database is touched.
- Invalid configurations return a `400 invalid_request_error` response and the create/update operation is aborted.
## Development Commands
```bash
# Apply schema changes
yarn agents:generate
# Quick development sync
yarn agents:push
# Database tools
yarn agents:studio # Open Drizzle Studio
yarn agents:health # Health check
yarn agents:drop # Reset database
```
## Workflow
1. **Edit schema** in `/database/schema/`
2. **Generate migration** with `yarn agents:generate`
3. **Test changes** with `yarn agents:health`
4. **Deploy** - migrations apply automatically
## Services
- `AgentService` - Agent CRUD operations
- `SessionService` - Session management
- `SessionMessageService` - Message logging
- `BaseService` - Database utilities
- `schemaSyncer` - Migration handler
## Troubleshooting
```bash
# Check status
yarn agents:health
# Apply migrations
yarn agents:migrate
# Reset completely
yarn agents:reset --yes
```
The simplified migration system reduced complexity from 463 to ~30 lines while maintaining all functionality through Drizzle's native migration system.

View File

@@ -0,0 +1,161 @@
import { type Client } from '@libsql/client'
import { loggerService } from '@logger'
import { getResourcePath } from '@main/utils'
import { type LibSQLDatabase } from 'drizzle-orm/libsql'
import fs from 'fs'
import path from 'path'
import * as schema from './schema'
import { migrations, type NewMigration } from './schema/migrations.schema'
const logger = loggerService.withContext('MigrationService')
interface MigrationJournal {
version: string
dialect: string
entries: Array<{
idx: number
version: string
when: number
tag: string
breakpoints: boolean
}>
}
export class MigrationService {
private db: LibSQLDatabase<typeof schema>
private client: Client
private migrationDir: string
constructor(db: LibSQLDatabase<typeof schema>, client: Client) {
this.db = db
this.client = client
this.migrationDir = path.join(getResourcePath(), 'database', 'drizzle')
}
async runMigrations(): Promise<void> {
try {
logger.info('Starting migration check...')
const hasMigrationsTable = await this.migrationsTableExists()
if (!hasMigrationsTable) {
logger.info('Migrations table not found; assuming fresh database state')
}
// Read migration journal
const journal = await this.readMigrationJournal()
if (!journal.entries.length) {
logger.info('No migrations found in journal')
return
}
// Get applied migrations
const appliedMigrations = hasMigrationsTable ? await this.getAppliedMigrations() : []
const appliedVersions = new Set(appliedMigrations.map((m) => Number(m.version)))
const latestAppliedVersion = appliedMigrations.reduce(
(max, migration) => Math.max(max, Number(migration.version)),
0
)
const latestJournalVersion = journal.entries.reduce((max, entry) => Math.max(max, entry.idx), 0)
logger.info(`Latest applied migration: v${latestAppliedVersion}, latest available: v${latestJournalVersion}`)
// Find pending migrations (compare journal idx with stored version, which is the same value)
const pendingMigrations = journal.entries
.filter((entry) => !appliedVersions.has(entry.idx))
.sort((a, b) => a.idx - b.idx)
if (pendingMigrations.length === 0) {
logger.info('Database is up to date')
return
}
logger.info(`Found ${pendingMigrations.length} pending migrations`)
// Execute pending migrations
for (const migration of pendingMigrations) {
await this.executeMigration(migration)
}
logger.info('All migrations completed successfully')
} catch (error) {
logger.error('Migration failed:', { error })
throw error
}
}
private async migrationsTableExists(): Promise<boolean> {
try {
const table = await this.client.execute(`SELECT name FROM sqlite_master WHERE type='table' AND name='migrations'`)
return table.rows.length > 0
} catch (error) {
logger.error('Failed to check migrations table status:', { error })
throw error
}
}
private async readMigrationJournal(): Promise<MigrationJournal> {
const journalPath = path.join(this.migrationDir, 'meta', '_journal.json')
if (!fs.existsSync(journalPath)) {
logger.warn('Migration journal not found:', { journalPath })
return { version: '7', dialect: 'sqlite', entries: [] }
}
try {
const journalContent = fs.readFileSync(journalPath, 'utf-8')
return JSON.parse(journalContent)
} catch (error) {
logger.error('Failed to read migration journal:', { error })
throw error
}
}
private async getAppliedMigrations(): Promise<schema.Migration[]> {
try {
return await this.db.select().from(migrations)
} catch (error) {
// This should not happen since we ensure the table exists in runMigrations()
logger.error('Failed to query applied migrations:', { error })
throw error
}
}
private async executeMigration(migration: MigrationJournal['entries'][0]): Promise<void> {
const sqlFilePath = path.join(this.migrationDir, `${migration.tag}.sql`)
if (!fs.existsSync(sqlFilePath)) {
throw new Error(`Migration SQL file not found: ${sqlFilePath}`)
}
try {
logger.info(`Executing migration ${migration.tag}...`)
const startTime = Date.now()
// Read and execute SQL
const sqlContent = fs.readFileSync(sqlFilePath, 'utf-8')
await this.client.executeMultiple(sqlContent)
// Record migration as applied (store journal idx as version for tracking)
const newMigration: NewMigration = {
version: migration.idx,
tag: migration.tag,
executedAt: Date.now()
}
if (!(await this.migrationsTableExists())) {
throw new Error('Migrations table missing after executing migration; cannot record progress')
}
await this.db.insert(migrations).values(newMigration)
const executionTime = Date.now() - startTime
logger.info(`Migration ${migration.tag} completed in ${executionTime}ms`)
} catch (error) {
logger.error(`Migration ${migration.tag} failed:`, { error })
throw error
}
}
}

View File

@@ -0,0 +1,14 @@
/**
* Database Module
*
* This module provides centralized access to Drizzle ORM schemas
* for type-safe database operations.
*
* Schema evolution is handled by Drizzle Kit migrations.
*/
// Drizzle ORM schemas
export * from './schema'
// Repository helpers
export * from './sessionMessageRepository'

View File

@@ -0,0 +1,35 @@
/**
* Drizzle ORM schema for agents table
*/
import { index, sqliteTable, text } from 'drizzle-orm/sqlite-core'
export const agentsTable = sqliteTable('agents', {
id: text('id').primaryKey(),
type: text('type').notNull(),
name: text('name').notNull(),
description: text('description'),
accessible_paths: text('accessible_paths'), // JSON array of directory paths the agent can access
instructions: text('instructions'),
model: text('model').notNull(), // Main model ID (required)
plan_model: text('plan_model'), // Optional plan/thinking model ID
small_model: text('small_model'), // Optional small/fast model ID
mcps: text('mcps'), // JSON array of MCP tool IDs
allowed_tools: text('allowed_tools'), // JSON array of allowed tool IDs (whitelist)
configuration: text('configuration'), // JSON, extensible settings
created_at: text('created_at').notNull(),
updated_at: text('updated_at').notNull()
})
// Indexes for agents table
export const agentsNameIdx = index('idx_agents_name').on(agentsTable.name)
export const agentsTypeIdx = index('idx_agents_type').on(agentsTable.type)
export const agentsCreatedAtIdx = index('idx_agents_created_at').on(agentsTable.created_at)
export type AgentRow = typeof agentsTable.$inferSelect
export type InsertAgentRow = typeof agentsTable.$inferInsert

View File

@@ -0,0 +1,8 @@
/**
* Drizzle ORM schema exports
*/
export * from './agents.schema'
export * from './messages.schema'
export * from './migrations.schema'
export * from './sessions.schema'

View File

@@ -0,0 +1,30 @@
import { foreignKey, index, integer, sqliteTable, text } from 'drizzle-orm/sqlite-core'
import { sessionsTable } from './sessions.schema'
// session_messages table to log all messages, thoughts, actions, observations in a session
export const sessionMessagesTable = sqliteTable('session_messages', {
id: integer('id').primaryKey({ autoIncrement: true }),
session_id: text('session_id').notNull(),
role: text('role').notNull(), // 'user', 'agent', 'system', 'tool'
content: text('content').notNull(), // JSON structured data
agent_session_id: text('agent_session_id').default(''),
metadata: text('metadata'), // JSON metadata (optional)
created_at: text('created_at').notNull(),
updated_at: text('updated_at').notNull()
})
// Indexes for session_messages table
export const sessionMessagesSessionIdIdx = index('idx_session_messages_session_id').on(sessionMessagesTable.session_id)
export const sessionMessagesCreatedAtIdx = index('idx_session_messages_created_at').on(sessionMessagesTable.created_at)
export const sessionMessagesUpdatedAtIdx = index('idx_session_messages_updated_at').on(sessionMessagesTable.updated_at)
// Foreign keys for session_messages table
export const sessionMessagesFkSession = foreignKey({
columns: [sessionMessagesTable.session_id],
foreignColumns: [sessionsTable.id],
name: 'fk_session_messages_session_id'
}).onDelete('cascade')
export type SessionMessageRow = typeof sessionMessagesTable.$inferSelect
export type InsertSessionMessageRow = typeof sessionMessagesTable.$inferInsert

View File

@@ -0,0 +1,14 @@
/**
* Migration tracking schema
*/
import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core'
export const migrations = sqliteTable('migrations', {
version: integer('version').primaryKey(),
tag: text('tag').notNull(),
executedAt: integer('executed_at').notNull()
})
export type Migration = typeof migrations.$inferSelect
export type NewMigration = typeof migrations.$inferInsert

View File

@@ -0,0 +1,45 @@
/**
* Drizzle ORM schema for sessions and session_logs tables
*/
import { foreignKey, index, sqliteTable, text } from 'drizzle-orm/sqlite-core'
import { agentsTable } from './agents.schema'
export const sessionsTable = sqliteTable('sessions', {
id: text('id').primaryKey(),
agent_type: text('agent_type').notNull(),
agent_id: text('agent_id').notNull(), // Primary agent ID for the session
name: text('name').notNull(),
description: text('description'),
accessible_paths: text('accessible_paths'), // JSON array of directory paths the agent can access
instructions: text('instructions'),
model: text('model').notNull(), // Main model ID (required)
plan_model: text('plan_model'), // Optional plan/thinking model ID
small_model: text('small_model'), // Optional small/fast model ID
mcps: text('mcps'), // JSON array of MCP tool IDs
allowed_tools: text('allowed_tools'), // JSON array of allowed tool IDs (whitelist)
configuration: text('configuration'), // JSON, extensible settings
created_at: text('created_at').notNull(),
updated_at: text('updated_at').notNull()
})
// Foreign keys for sessions table
export const sessionsFkAgent = foreignKey({
columns: [sessionsTable.agent_id],
foreignColumns: [agentsTable.id],
name: 'fk_session_agent_id'
}).onDelete('cascade')
// Indexes for sessions table
export const sessionsCreatedAtIdx = index('idx_sessions_created_at').on(sessionsTable.created_at)
export const sessionsMainAgentIdIdx = index('idx_sessions_agent_id').on(sessionsTable.agent_id)
export const sessionsModelIdx = index('idx_sessions_model').on(sessionsTable.model)
export type SessionRow = typeof sessionsTable.$inferSelect
export type InsertSessionRow = typeof sessionsTable.$inferInsert

View File

@@ -0,0 +1,257 @@
import { loggerService } from '@logger'
import type {
AgentMessageAssistantPersistPayload,
AgentMessagePersistExchangePayload,
AgentMessagePersistExchangeResult,
AgentMessageUserPersistPayload,
AgentPersistedMessage,
AgentSessionMessageEntity
} from '@types'
import { and, asc, eq } from 'drizzle-orm'
import { BaseService } from '../BaseService'
import type { InsertSessionMessageRow, SessionMessageRow } from './schema'
import { sessionMessagesTable } from './schema'
const logger = loggerService.withContext('AgentMessageRepository')
type TxClient = any
export type PersistUserMessageParams = AgentMessageUserPersistPayload & {
sessionId: string
agentSessionId?: string
tx?: TxClient
}
export type PersistAssistantMessageParams = AgentMessageAssistantPersistPayload & {
sessionId: string
agentSessionId: string
tx?: TxClient
}
type PersistExchangeParams = AgentMessagePersistExchangePayload & {
tx?: TxClient
}
type PersistExchangeResult = AgentMessagePersistExchangeResult
class AgentMessageRepository extends BaseService {
private static instance: AgentMessageRepository | null = null
static getInstance(): AgentMessageRepository {
if (!AgentMessageRepository.instance) {
AgentMessageRepository.instance = new AgentMessageRepository()
}
return AgentMessageRepository.instance
}
private serializeMessage(payload: AgentPersistedMessage): string {
return JSON.stringify(payload)
}
private serializeMetadata(metadata?: Record<string, unknown>): string | undefined {
if (!metadata) {
return undefined
}
try {
return JSON.stringify(metadata)
} catch (error) {
logger.warn('Failed to serialize session message metadata', error as Error)
return undefined
}
}
private deserialize(row: any): AgentSessionMessageEntity {
if (!row) return row
const deserialized = { ...row }
if (typeof deserialized.content === 'string') {
try {
deserialized.content = JSON.parse(deserialized.content)
} catch (error) {
logger.warn('Failed to parse session message content JSON', error as Error)
}
}
if (typeof deserialized.metadata === 'string') {
try {
deserialized.metadata = JSON.parse(deserialized.metadata)
} catch (error) {
logger.warn('Failed to parse session message metadata JSON', error as Error)
}
}
return deserialized
}
private getWriter(tx?: TxClient): TxClient {
return tx ?? this.database
}
private async findExistingMessageRow(
writer: TxClient,
sessionId: string,
role: string,
messageId: string
): Promise<SessionMessageRow | null> {
const candidateRows: SessionMessageRow[] = await writer
.select()
.from(sessionMessagesTable)
.where(and(eq(sessionMessagesTable.session_id, sessionId), eq(sessionMessagesTable.role, role)))
.orderBy(asc(sessionMessagesTable.created_at))
for (const row of candidateRows) {
if (!row?.content) continue
try {
const parsed = JSON.parse(row.content) as AgentPersistedMessage | undefined
if (parsed?.message?.id === messageId) {
return row
}
} catch (error) {
logger.warn('Failed to parse session message content JSON during lookup', error as Error)
}
}
return null
}
private async upsertMessage(
params: PersistUserMessageParams | PersistAssistantMessageParams
): Promise<AgentSessionMessageEntity> {
await AgentMessageRepository.initialize()
this.ensureInitialized()
const { sessionId, agentSessionId = '', payload, metadata, createdAt, tx } = params
if (!payload?.message?.role) {
throw new Error('Message payload missing role')
}
if (!payload.message.id) {
throw new Error('Message payload missing id')
}
const writer = this.getWriter(tx)
const now = createdAt ?? payload.message.createdAt ?? new Date().toISOString()
const serializedPayload = this.serializeMessage(payload)
const serializedMetadata = this.serializeMetadata(metadata)
const existingRow = await this.findExistingMessageRow(writer, sessionId, payload.message.role, payload.message.id)
if (existingRow) {
const metadataToPersist = serializedMetadata ?? existingRow.metadata ?? undefined
const agentSessionToPersist = agentSessionId || existingRow.agent_session_id || ''
await writer
.update(sessionMessagesTable)
.set({
content: serializedPayload,
metadata: metadataToPersist,
agent_session_id: agentSessionToPersist,
updated_at: now
})
.where(eq(sessionMessagesTable.id, existingRow.id))
return this.deserialize({
...existingRow,
content: serializedPayload,
metadata: metadataToPersist,
agent_session_id: agentSessionToPersist,
updated_at: now
})
}
const insertData: InsertSessionMessageRow = {
session_id: sessionId,
role: payload.message.role,
content: serializedPayload,
agent_session_id: agentSessionId,
metadata: serializedMetadata,
created_at: now,
updated_at: now
}
const [saved] = await writer.insert(sessionMessagesTable).values(insertData).returning()
return this.deserialize(saved)
}
async persistUserMessage(params: PersistUserMessageParams): Promise<AgentSessionMessageEntity> {
return this.upsertMessage({ ...params, agentSessionId: params.agentSessionId ?? '' })
}
async persistAssistantMessage(params: PersistAssistantMessageParams): Promise<AgentSessionMessageEntity> {
return this.upsertMessage(params)
}
async persistExchange(params: PersistExchangeParams): Promise<PersistExchangeResult> {
await AgentMessageRepository.initialize()
this.ensureInitialized()
const { sessionId, agentSessionId, user, assistant } = params
const result = await this.database.transaction(async (tx) => {
const exchangeResult: PersistExchangeResult = {}
if (user?.payload) {
exchangeResult.userMessage = await this.persistUserMessage({
sessionId,
agentSessionId,
payload: user.payload,
metadata: user.metadata,
createdAt: user.createdAt,
tx
})
}
if (assistant?.payload) {
exchangeResult.assistantMessage = await this.persistAssistantMessage({
sessionId,
agentSessionId,
payload: assistant.payload,
metadata: assistant.metadata,
createdAt: assistant.createdAt,
tx
})
}
return exchangeResult
})
return result
}
async getSessionHistory(sessionId: string): Promise<AgentPersistedMessage[]> {
await AgentMessageRepository.initialize()
this.ensureInitialized()
try {
const rows = await this.database
.select()
.from(sessionMessagesTable)
.where(eq(sessionMessagesTable.session_id, sessionId))
.orderBy(asc(sessionMessagesTable.created_at))
const messages: AgentPersistedMessage[] = []
for (const row of rows) {
const deserialized = this.deserialize(row)
if (deserialized?.content) {
messages.push(deserialized.content as AgentPersistedMessage)
}
}
logger.info(`Loaded ${messages.length} messages for session ${sessionId}`)
return messages
} catch (error) {
logger.error('Failed to load session history', error as Error)
throw error
}
}
}
export const agentMessageRepository = AgentMessageRepository.getInstance()

View File

@@ -0,0 +1,31 @@
/**
* Drizzle Kit configuration for agents database
*/
import os from 'node:os'
import path from 'node:path'
import { defineConfig } from 'drizzle-kit'
import { app } from 'electron'
function getDbPath() {
if (process.env.NODE_ENV === 'development') {
return path.join(os.homedir(), '.cherrystudio', 'data', 'agents.db')
}
return path.join(app.getPath('userData'), 'agents.db')
}
const resolvedDbPath = getDbPath()
export const dbPath = resolvedDbPath
export default defineConfig({
dialect: 'sqlite',
schema: './src/main/services/agents/database/schema/index.ts',
out: './resources/database/drizzle',
dbCredentials: {
url: `file:${resolvedDbPath}`
},
verbose: true,
strict: true
})

View File

@@ -0,0 +1,22 @@
import { ModelValidationError } from '@main/apiServer/utils'
import { AgentType } from '@types'
export type AgentModelField = 'model' | 'plan_model' | 'small_model'
export interface AgentModelValidationContext {
agentType: AgentType
field: AgentModelField
model?: string
}
export class AgentModelValidationError extends Error {
readonly context: AgentModelValidationContext
readonly detail: ModelValidationError
constructor(context: AgentModelValidationContext, detail: ModelValidationError) {
super(`Validation failed for ${context.agentType}.${context.field}: ${detail.message}`)
this.name = 'AgentModelValidationError'
this.context = context
this.detail = detail
}
}

View File

@@ -0,0 +1,25 @@
/**
* Agents Service Module
*
* This module provides a complete autonomous agent management system with:
* - Agent lifecycle management (CRUD operations)
* - Session handling with conversation history
* - Comprehensive logging and audit trails
* - Database operations with Drizzle ORM and migration support
* - RESTful API endpoints for external integration
*/
// === Core Services ===
// Main service classes and singleton instances
export * from './services'
// === Error Types ===
export { type AgentModelField, AgentModelValidationError } from './errors'
// === Base Infrastructure ===
// Shared database utilities and base service class
export { BaseService } from './BaseService'
// === Database Layer ===
// Drizzle ORM schemas, migrations, and database utilities
export * as Database from './database'

View File

@@ -0,0 +1,31 @@
// Agent-agnostic streaming interface
// This interface should be implemented by all agent services
import { EventEmitter } from 'node:events'
import { GetAgentSessionResponse } from '@types'
import type { TextStreamPart } from 'ai'
// Generic agent stream event that works with any agent type
export interface AgentStreamEvent {
type: 'chunk' | 'error' | 'complete' | 'cancelled'
chunk?: TextStreamPart<any> // Standard AI SDK chunk for UI consumption
error?: Error
}
// Agent stream interface that all agents should implement
export interface AgentStream extends EventEmitter {
emit(event: 'data', data: AgentStreamEvent): boolean
on(event: 'data', listener: (data: AgentStreamEvent) => void): this
once(event: 'data', listener: (data: AgentStreamEvent) => void): this
}
// Base agent service interface
export interface AgentServiceInterface {
invoke(
prompt: string,
session: GetAgentSessionResponse,
abortController: AbortController,
lastAgentSessionId?: string
): Promise<AgentStream>
}

View File

@@ -0,0 +1,195 @@
import path from 'node:path'
import { getDataPath } from '@main/utils'
import {
AgentBaseSchema,
AgentEntity,
CreateAgentRequest,
CreateAgentResponse,
GetAgentResponse,
ListOptions,
UpdateAgentRequest,
UpdateAgentResponse
} from '@types'
import { count, eq } from 'drizzle-orm'
import { BaseService } from '../BaseService'
import { type AgentRow, agentsTable, type InsertAgentRow } from '../database/schema'
import { AgentModelField } from '../errors'
export class AgentService extends BaseService {
private static instance: AgentService | null = null
private readonly modelFields: AgentModelField[] = ['model', 'plan_model', 'small_model']
static getInstance(): AgentService {
if (!AgentService.instance) {
AgentService.instance = new AgentService()
}
return AgentService.instance
}
async initialize(): Promise<void> {
await BaseService.initialize()
}
// Agent Methods
async createAgent(req: CreateAgentRequest): Promise<CreateAgentResponse> {
this.ensureInitialized()
const id = `agent_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`
const now = new Date().toISOString()
if (!req.accessible_paths || req.accessible_paths.length === 0) {
const defaultPath = path.join(getDataPath(), 'agents', id)
req.accessible_paths = [defaultPath]
}
if (req.accessible_paths !== undefined) {
req.accessible_paths = this.ensurePathsExist(req.accessible_paths)
}
await this.validateAgentModels(req.type, {
model: req.model,
plan_model: req.plan_model,
small_model: req.small_model
})
const serializedReq = this.serializeJsonFields(req)
const insertData: InsertAgentRow = {
id,
type: req.type,
name: req.name || 'New Agent',
description: req.description,
instructions: req.instructions || 'You are a helpful assistant.',
model: req.model,
plan_model: req.plan_model,
small_model: req.small_model,
configuration: serializedReq.configuration,
accessible_paths: serializedReq.accessible_paths,
created_at: now,
updated_at: now
}
await this.database.insert(agentsTable).values(insertData)
const result = await this.database.select().from(agentsTable).where(eq(agentsTable.id, id)).limit(1)
if (!result[0]) {
throw new Error('Failed to create agent')
}
const agent = this.deserializeJsonFields(result[0]) as AgentEntity
return agent
}
async getAgent(id: string): Promise<GetAgentResponse | null> {
this.ensureInitialized()
const result = await this.database.select().from(agentsTable).where(eq(agentsTable.id, id)).limit(1)
if (!result[0]) {
return null
}
const agent = this.deserializeJsonFields(result[0]) as GetAgentResponse
agent.tools = await this.listMcpTools(agent.type, agent.mcps)
return agent
}
async listAgents(options: ListOptions = {}): Promise<{ agents: AgentEntity[]; total: number }> {
this.ensureInitialized() // Build query with pagination
const totalResult = await this.database.select({ count: count() }).from(agentsTable)
const baseQuery = this.database.select().from(agentsTable).orderBy(agentsTable.created_at)
const result =
options.limit !== undefined
? options.offset !== undefined
? await baseQuery.limit(options.limit).offset(options.offset)
: await baseQuery.limit(options.limit)
: await baseQuery
const agents = result.map((row) => this.deserializeJsonFields(row)) as GetAgentResponse[]
for (const agent of agents) {
agent.tools = await this.listMcpTools(agent.type, agent.mcps)
}
return { agents, total: totalResult[0].count }
}
async updateAgent(
id: string,
updates: UpdateAgentRequest,
options: { replace?: boolean } = {}
): Promise<UpdateAgentResponse | null> {
this.ensureInitialized()
// Check if agent exists
const existing = await this.getAgent(id)
if (!existing) {
return null
}
const now = new Date().toISOString()
if (updates.accessible_paths !== undefined) {
updates.accessible_paths = this.ensurePathsExist(updates.accessible_paths)
}
const modelUpdates: Partial<Record<AgentModelField, string | undefined>> = {}
for (const field of this.modelFields) {
if (Object.prototype.hasOwnProperty.call(updates, field)) {
modelUpdates[field] = updates[field as keyof UpdateAgentRequest] as string | undefined
}
}
if (Object.keys(modelUpdates).length > 0) {
await this.validateAgentModels(existing.type, modelUpdates)
}
const serializedUpdates = this.serializeJsonFields(updates)
const updateData: Partial<AgentRow> = {
updated_at: now
}
const replaceableFields = Object.keys(AgentBaseSchema.shape) as (keyof AgentRow)[]
const shouldReplace = options.replace ?? false
for (const field of replaceableFields) {
if (shouldReplace || Object.prototype.hasOwnProperty.call(serializedUpdates, field)) {
if (Object.prototype.hasOwnProperty.call(serializedUpdates, field)) {
const value = serializedUpdates[field as keyof typeof serializedUpdates]
;(updateData as Record<string, unknown>)[field] = value ?? null
} else if (shouldReplace) {
;(updateData as Record<string, unknown>)[field] = null
}
}
}
await this.database.update(agentsTable).set(updateData).where(eq(agentsTable.id, id))
return await this.getAgent(id)
}
async deleteAgent(id: string): Promise<boolean> {
this.ensureInitialized()
const result = await this.database.delete(agentsTable).where(eq(agentsTable.id, id))
return result.rowsAffected > 0
}
async agentExists(id: string): Promise<boolean> {
this.ensureInitialized()
const result = await this.database
.select({ id: agentsTable.id })
.from(agentsTable)
.where(eq(agentsTable.id, id))
.limit(1)
return result.length > 0
}
}
export const agentService = AgentService.getInstance()

View File

@@ -0,0 +1,321 @@
import { loggerService } from '@logger'
import type {
AgentSessionMessageEntity,
CreateSessionMessageRequest,
GetAgentSessionResponse,
ListOptions
} from '@types'
import { TextStreamPart } from 'ai'
import { and, desc, eq, not } from 'drizzle-orm'
import { BaseService } from '../BaseService'
import { sessionMessagesTable } from '../database/schema'
import { AgentStreamEvent } from '../interfaces/AgentStreamInterface'
import ClaudeCodeService from './claudecode'
const logger = loggerService.withContext('SessionMessageService')
type SessionStreamResult = {
stream: ReadableStream<TextStreamPart<Record<string, any>>>
completion: Promise<{
userMessage?: AgentSessionMessageEntity
assistantMessage?: AgentSessionMessageEntity
}>
}
// Ensure errors emitted through SSE are serializable
function serializeError(error: unknown): { message: string; name?: string; stack?: string } {
if (error instanceof Error) {
return {
message: error.message,
name: error.name,
stack: error.stack
}
}
if (typeof error === 'string') {
return { message: error }
}
return {
message: 'Unknown error'
}
}
class TextStreamAccumulator {
private textBuffer = ''
private totalText = ''
private readonly toolCalls = new Map<string, { toolName?: string; input?: unknown }>()
private readonly toolResults = new Map<string, unknown>()
add(part: TextStreamPart<Record<string, any>>): void {
switch (part.type) {
case 'text-start':
this.textBuffer = ''
break
case 'text-delta':
if (part.text) {
this.textBuffer += part.text
}
break
case 'text-end': {
const blockText = (part.providerMetadata?.text?.value as string | undefined) ?? this.textBuffer
if (blockText) {
this.totalText += blockText
}
this.textBuffer = ''
break
}
case 'tool-call':
if (part.toolCallId) {
const legacyPart = part as typeof part & {
args?: unknown
providerMetadata?: { raw?: { input?: unknown } }
}
this.toolCalls.set(part.toolCallId, {
toolName: part.toolName,
input: part.input ?? legacyPart.args ?? legacyPart.providerMetadata?.raw?.input
})
}
break
case 'tool-result':
if (part.toolCallId) {
const legacyPart = part as typeof part & {
result?: unknown
providerMetadata?: { raw?: unknown }
}
this.toolResults.set(part.toolCallId, part.output ?? legacyPart.result ?? legacyPart.providerMetadata?.raw)
}
break
default:
break
}
}
}
export class SessionMessageService extends BaseService {
private static instance: SessionMessageService | null = null
private cc: ClaudeCodeService = new ClaudeCodeService()
static getInstance(): SessionMessageService {
if (!SessionMessageService.instance) {
SessionMessageService.instance = new SessionMessageService()
}
return SessionMessageService.instance
}
async initialize(): Promise<void> {
await BaseService.initialize()
}
async sessionMessageExists(id: number): Promise<boolean> {
this.ensureInitialized()
const result = await this.database
.select({ id: sessionMessagesTable.id })
.from(sessionMessagesTable)
.where(eq(sessionMessagesTable.id, id))
.limit(1)
return result.length > 0
}
async listSessionMessages(
sessionId: string,
options: ListOptions = {}
): Promise<{ messages: AgentSessionMessageEntity[] }> {
this.ensureInitialized()
// Get messages with pagination
const baseQuery = this.database
.select()
.from(sessionMessagesTable)
.where(eq(sessionMessagesTable.session_id, sessionId))
.orderBy(sessionMessagesTable.created_at)
const result =
options.limit !== undefined
? options.offset !== undefined
? await baseQuery.limit(options.limit).offset(options.offset)
: await baseQuery.limit(options.limit)
: await baseQuery
const messages = result.map((row) => this.deserializeSessionMessage(row)) as AgentSessionMessageEntity[]
return { messages }
}
async deleteSessionMessage(sessionId: string, messageId: number): Promise<boolean> {
this.ensureInitialized()
const result = await this.database
.delete(sessionMessagesTable)
.where(and(eq(sessionMessagesTable.id, messageId), eq(sessionMessagesTable.session_id, sessionId)))
return result.rowsAffected > 0
}
async createSessionMessage(
session: GetAgentSessionResponse,
messageData: CreateSessionMessageRequest,
abortController: AbortController
): Promise<SessionStreamResult> {
this.ensureInitialized()
return await this.startSessionMessageStream(session, messageData, abortController)
}
private async startSessionMessageStream(
session: GetAgentSessionResponse,
req: CreateSessionMessageRequest,
abortController: AbortController
): Promise<SessionStreamResult> {
const agentSessionId = await this.getLastAgentSessionId(session.id)
logger.debug('Session Message stream message data:', { message: req, session_id: agentSessionId })
if (session.agent_type !== 'claude-code') {
// TODO: Implement support for other agent types
logger.error('Unsupported agent type for streaming:', { agent_type: session.agent_type })
throw new Error('Unsupported agent type for streaming')
}
const claudeStream = await this.cc.invoke(req.content, session, abortController, agentSessionId)
const accumulator = new TextStreamAccumulator()
let resolveCompletion!: (value: {
userMessage?: AgentSessionMessageEntity
assistantMessage?: AgentSessionMessageEntity
}) => void
let rejectCompletion!: (reason?: unknown) => void
const completion = new Promise<{
userMessage?: AgentSessionMessageEntity
assistantMessage?: AgentSessionMessageEntity
}>((resolve, reject) => {
resolveCompletion = resolve
rejectCompletion = reject
})
let finished = false
const cleanup = () => {
if (finished) return
finished = true
claudeStream.removeAllListeners()
}
const stream = new ReadableStream<TextStreamPart<Record<string, any>>>({
start: (controller) => {
claudeStream.on('data', async (event: AgentStreamEvent) => {
if (finished) return
try {
switch (event.type) {
case 'chunk': {
const chunk = event.chunk as TextStreamPart<Record<string, any>> | undefined
if (!chunk) {
logger.warn('Received agent chunk event without chunk payload')
return
}
accumulator.add(chunk)
controller.enqueue(chunk)
break
}
case 'error': {
const stderrMessage = (event as any)?.data?.stderr as string | undefined
const underlyingError = event.error ?? (stderrMessage ? new Error(stderrMessage) : undefined)
cleanup()
const streamError = underlyingError ?? new Error('Stream error')
controller.error(streamError)
rejectCompletion(serializeError(streamError))
break
}
case 'complete': {
cleanup()
controller.close()
resolveCompletion({})
break
}
case 'cancelled': {
cleanup()
controller.close()
resolveCompletion({})
break
}
default:
logger.warn('Unknown event type from Claude Code service:', {
type: event.type
})
break
}
} catch (error) {
cleanup()
controller.error(error)
rejectCompletion(serializeError(error))
}
})
},
cancel: (reason) => {
cleanup()
abortController.abort(typeof reason === 'string' ? reason : 'stream cancelled')
resolveCompletion({})
}
})
return { stream, completion }
}
private async getLastAgentSessionId(sessionId: string): Promise<string> {
this.ensureInitialized()
try {
const result = await this.database
.select({ agent_session_id: sessionMessagesTable.agent_session_id })
.from(sessionMessagesTable)
.where(and(eq(sessionMessagesTable.session_id, sessionId), not(eq(sessionMessagesTable.agent_session_id, ''))))
.orderBy(desc(sessionMessagesTable.created_at))
.limit(1)
logger.silly('Last agent session ID result:', { agentSessionId: result[0]?.agent_session_id, sessionId })
return result[0]?.agent_session_id || ''
} catch (error) {
logger.error('Failed to get last agent session ID', {
sessionId,
error
})
return ''
}
}
private deserializeSessionMessage(data: any): AgentSessionMessageEntity {
if (!data) return data
const deserialized = { ...data }
// Parse content JSON
if (deserialized.content && typeof deserialized.content === 'string') {
try {
deserialized.content = JSON.parse(deserialized.content)
} catch (error) {
logger.warn(`Failed to parse content JSON:`, error as Error)
}
}
// Parse metadata JSON
if (deserialized.metadata && typeof deserialized.metadata === 'string') {
try {
deserialized.metadata = JSON.parse(deserialized.metadata)
} catch (error) {
logger.warn(`Failed to parse metadata JSON:`, error as Error)
}
}
return deserialized
}
}
export const sessionMessageService = SessionMessageService.getInstance()

View File

@@ -0,0 +1,235 @@
import {
AgentBaseSchema,
type AgentEntity,
type AgentSessionEntity,
type CreateSessionRequest,
type GetAgentSessionResponse,
type ListOptions,
type UpdateSessionRequest,
UpdateSessionResponse
} from '@types'
import { and, count, desc, eq, type SQL } from 'drizzle-orm'
import { BaseService } from '../BaseService'
import { agentsTable, type InsertSessionRow, type SessionRow, sessionsTable } from '../database/schema'
import { AgentModelField } from '../errors'
export class SessionService extends BaseService {
private static instance: SessionService | null = null
private readonly modelFields: AgentModelField[] = ['model', 'plan_model', 'small_model']
static getInstance(): SessionService {
if (!SessionService.instance) {
SessionService.instance = new SessionService()
}
return SessionService.instance
}
async initialize(): Promise<void> {
await BaseService.initialize()
}
async createSession(
agentId: string,
req: Partial<CreateSessionRequest> = {}
): Promise<GetAgentSessionResponse | null> {
this.ensureInitialized()
// Validate agent exists - we'll need to import AgentService for this check
// For now, we'll skip this validation to avoid circular dependencies
// The database foreign key constraint will handle this
const agents = await this.database.select().from(agentsTable).where(eq(agentsTable.id, agentId)).limit(1)
if (!agents[0]) {
throw new Error('Agent not found')
}
const agent = this.deserializeJsonFields(agents[0]) as AgentEntity
const id = `session_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`
const now = new Date().toISOString()
// inherit configuration from agent by default, can be overridden by sessionData
const sessionData: Partial<CreateSessionRequest> = {
...agent,
...req
}
await this.validateAgentModels(agent.type, {
model: sessionData.model,
plan_model: sessionData.plan_model,
small_model: sessionData.small_model
})
if (sessionData.accessible_paths !== undefined) {
sessionData.accessible_paths = this.ensurePathsExist(sessionData.accessible_paths)
}
const serializedData = this.serializeJsonFields(sessionData)
const insertData: InsertSessionRow = {
id,
agent_id: agentId,
agent_type: agent.type,
name: serializedData.name || null,
description: serializedData.description || null,
accessible_paths: serializedData.accessible_paths || null,
instructions: serializedData.instructions || null,
model: serializedData.model || null,
plan_model: serializedData.plan_model || null,
small_model: serializedData.small_model || null,
mcps: serializedData.mcps || null,
configuration: serializedData.configuration || null,
created_at: now,
updated_at: now
}
await this.database.insert(sessionsTable).values(insertData)
const result = await this.database.select().from(sessionsTable).where(eq(sessionsTable.id, id)).limit(1)
if (!result[0]) {
throw new Error('Failed to create session')
}
const session = this.deserializeJsonFields(result[0])
return await this.getSession(agentId, session.id)
}
async getSession(agentId: string, id: string): Promise<GetAgentSessionResponse | null> {
this.ensureInitialized()
const result = await this.database
.select()
.from(sessionsTable)
.where(and(eq(sessionsTable.id, id), eq(sessionsTable.agent_id, agentId)))
.limit(1)
if (!result[0]) {
return null
}
const session = this.deserializeJsonFields(result[0]) as GetAgentSessionResponse
session.tools = await this.listMcpTools(session.agent_type, session.mcps)
session.slash_commands = await this.listSlashCommands(session.agent_type)
return session
}
async listSessions(
agentId?: string,
options: ListOptions = {}
): Promise<{ sessions: AgentSessionEntity[]; total: number }> {
this.ensureInitialized()
// Build where conditions
const whereConditions: SQL[] = []
if (agentId) {
whereConditions.push(eq(sessionsTable.agent_id, agentId))
}
const whereClause =
whereConditions.length > 1
? and(...whereConditions)
: whereConditions.length === 1
? whereConditions[0]
: undefined
// Get total count
const totalResult = await this.database.select({ count: count() }).from(sessionsTable).where(whereClause)
const total = totalResult[0].count
// Build list query with pagination - sort by updated_at descending (latest first)
const baseQuery = this.database
.select()
.from(sessionsTable)
.where(whereClause)
.orderBy(desc(sessionsTable.updated_at))
const result =
options.limit !== undefined
? options.offset !== undefined
? await baseQuery.limit(options.limit).offset(options.offset)
: await baseQuery.limit(options.limit)
: await baseQuery
const sessions = result.map((row) => this.deserializeJsonFields(row)) as GetAgentSessionResponse[]
return { sessions, total }
}
async updateSession(
agentId: string,
id: string,
updates: UpdateSessionRequest
): Promise<UpdateSessionResponse | null> {
this.ensureInitialized()
// Check if session exists
const existing = await this.getSession(agentId, id)
if (!existing) {
return null
}
// Validate agent exists if changing main_agent_id
// We'll skip this validation for now to avoid circular dependencies
const now = new Date().toISOString()
if (updates.accessible_paths !== undefined) {
updates.accessible_paths = this.ensurePathsExist(updates.accessible_paths)
}
const modelUpdates: Partial<Record<AgentModelField, string | undefined>> = {}
for (const field of this.modelFields) {
if (Object.prototype.hasOwnProperty.call(updates, field)) {
modelUpdates[field] = updates[field as keyof UpdateSessionRequest] as string | undefined
}
}
if (Object.keys(modelUpdates).length > 0) {
await this.validateAgentModels(existing.agent_type, modelUpdates)
}
const serializedUpdates = this.serializeJsonFields(updates)
const updateData: Partial<SessionRow> = {
updated_at: now
}
const replaceableFields = Object.keys(AgentBaseSchema.shape) as (keyof SessionRow)[]
for (const field of replaceableFields) {
if (Object.prototype.hasOwnProperty.call(serializedUpdates, field)) {
const value = serializedUpdates[field as keyof typeof serializedUpdates]
;(updateData as Record<string, unknown>)[field] = value ?? null
}
}
await this.database.update(sessionsTable).set(updateData).where(eq(sessionsTable.id, id))
return await this.getSession(agentId, id)
}
async deleteSession(agentId: string, id: string): Promise<boolean> {
this.ensureInitialized()
const result = await this.database
.delete(sessionsTable)
.where(and(eq(sessionsTable.id, id), eq(sessionsTable.agent_id, agentId)))
return result.rowsAffected > 0
}
async sessionExists(agentId: string, id: string): Promise<boolean> {
this.ensureInitialized()
const result = await this.database
.select({ id: sessionsTable.id })
.from(sessionsTable)
.where(and(eq(sessionsTable.id, id), eq(sessionsTable.agent_id, agentId)))
.limit(1)
return result.length > 0
}
}
export const sessionService = SessionService.getInstance()

View File

@@ -0,0 +1,290 @@
import type { SDKMessage } from '@anthropic-ai/claude-agent-sdk'
import { describe, expect, it } from 'vitest'
import { ClaudeStreamState, transformSDKMessageToStreamParts } from '../transform'
const baseStreamMetadata = {
parent_tool_use_id: null,
session_id: 'session-123'
}
const uuid = (n: number) => `00000000-0000-0000-0000-${n.toString().padStart(12, '0')}`
describe('Claude → AiSDK transform', () => {
it('handles tool call streaming lifecycle', () => {
const state = new ClaudeStreamState()
const parts: ReturnType<typeof transformSDKMessageToStreamParts>[number][] = []
const messages: SDKMessage[] = [
{
...baseStreamMetadata,
type: 'stream_event',
uuid: uuid(1),
event: {
type: 'message_start',
message: {
id: 'msg-start',
type: 'message',
role: 'assistant',
model: 'claude-test',
content: [],
stop_reason: null,
stop_sequence: null,
usage: {}
}
}
} as unknown as SDKMessage,
{
...baseStreamMetadata,
type: 'stream_event',
uuid: uuid(2),
event: {
type: 'content_block_start',
index: 0,
content_block: {
type: 'tool_use',
id: 'tool-1',
name: 'Bash',
input: {}
}
}
} as unknown as SDKMessage,
{
...baseStreamMetadata,
type: 'stream_event',
uuid: uuid(3),
event: {
type: 'content_block_delta',
index: 0,
delta: {
type: 'input_json_delta',
partial_json: '{"command":"ls"}'
}
}
} as unknown as SDKMessage,
{
...baseStreamMetadata,
type: 'assistant',
uuid: uuid(4),
message: {
id: 'msg-tool',
type: 'message',
role: 'assistant',
model: 'claude-test',
content: [
{
type: 'tool_use',
id: 'tool-1',
name: 'Bash',
input: {
command: 'ls'
}
}
],
stop_reason: 'tool_use',
stop_sequence: null,
usage: {
input_tokens: 1,
output_tokens: 0
}
}
} as unknown as SDKMessage,
{
...baseStreamMetadata,
type: 'stream_event',
uuid: uuid(5),
event: {
type: 'content_block_stop',
index: 0
}
} as unknown as SDKMessage,
{
...baseStreamMetadata,
type: 'stream_event',
uuid: uuid(6),
event: {
type: 'message_delta',
delta: {
stop_reason: 'tool_use',
stop_sequence: null
},
usage: {
input_tokens: 1,
output_tokens: 5
}
}
} as unknown as SDKMessage,
{
...baseStreamMetadata,
type: 'stream_event',
uuid: uuid(7),
event: {
type: 'message_stop'
}
} as unknown as SDKMessage,
{
...baseStreamMetadata,
type: 'user',
uuid: uuid(8),
message: {
role: 'user',
content: [
{
type: 'tool_result',
tool_use_id: 'tool-1',
content: 'ok',
is_error: false
}
]
}
} as SDKMessage
]
for (const message of messages) {
const transformed = transformSDKMessageToStreamParts(message, state)
for (const part of transformed) {
parts.push(part)
}
}
const types = parts.map((part) => part.type)
expect(types).toEqual([
'start-step',
'tool-input-start',
'tool-input-delta',
'tool-call',
'tool-input-end',
'finish-step',
'tool-result'
])
const finishStep = parts.find((part) => part.type === 'finish-step') as Extract<
(typeof parts)[number],
{ type: 'finish-step' }
>
expect(finishStep.finishReason).toBe('tool-calls')
expect(finishStep.usage).toEqual({ inputTokens: 1, outputTokens: 5, totalTokens: 6 })
const toolResult = parts.find((part) => part.type === 'tool-result') as Extract<
(typeof parts)[number],
{ type: 'tool-result' }
>
expect(toolResult.toolCallId).toBe('tool-1')
expect(toolResult.toolName).toBe('Bash')
expect(toolResult.input).toEqual({ command: 'ls' })
expect(toolResult.output).toBe('ok')
})
it('handles streaming text completion', () => {
const state = new ClaudeStreamState()
const parts: ReturnType<typeof transformSDKMessageToStreamParts>[number][] = []
const messages: SDKMessage[] = [
{
...baseStreamMetadata,
type: 'stream_event',
uuid: uuid(9),
event: {
type: 'message_start',
message: {
id: 'msg-text',
type: 'message',
role: 'assistant',
model: 'claude-text',
content: [],
stop_reason: null,
stop_sequence: null,
usage: {}
}
}
} as unknown as SDKMessage,
{
...baseStreamMetadata,
type: 'stream_event',
uuid: uuid(10),
event: {
type: 'content_block_start',
index: 0,
content_block: {
type: 'text',
text: ''
}
}
} as unknown as SDKMessage,
{
...baseStreamMetadata,
type: 'stream_event',
uuid: uuid(11),
event: {
type: 'content_block_delta',
index: 0,
delta: {
type: 'text_delta',
text: 'Hello'
}
}
} as unknown as SDKMessage,
{
...baseStreamMetadata,
type: 'stream_event',
uuid: uuid(12),
event: {
type: 'content_block_delta',
index: 0,
delta: {
type: 'text_delta',
text: ' world'
}
}
} as unknown as SDKMessage,
{
...baseStreamMetadata,
type: 'stream_event',
uuid: uuid(13),
event: {
type: 'content_block_stop',
index: 0
}
} as unknown as SDKMessage,
{
...baseStreamMetadata,
type: 'stream_event',
uuid: uuid(14),
event: {
type: 'message_delta',
delta: {
stop_reason: 'end_turn',
stop_sequence: null
},
usage: {
input_tokens: 2,
output_tokens: 4
}
}
} as unknown as SDKMessage,
{
...baseStreamMetadata,
type: 'stream_event',
uuid: uuid(15),
event: {
type: 'message_stop'
}
} as SDKMessage
]
for (const message of messages) {
const transformed = transformSDKMessageToStreamParts(message, state)
parts.push(...transformed)
}
const types = parts.map((part) => part.type)
expect(types).toEqual(['start-step', 'text-start', 'text-delta', 'text-delta', 'text-end', 'finish-step'])
const finishStep = parts.find((part) => part.type === 'finish-step') as Extract<
(typeof parts)[number],
{ type: 'finish-step' }
>
expect(finishStep.finishReason).toBe('stop')
expect(finishStep.usage).toEqual({ inputTokens: 2, outputTokens: 4, totalTokens: 6 })
})
})

View File

@@ -0,0 +1,241 @@
/**
* Lightweight state container shared by the Claude → AiSDK transformer. Anthropic does not send
* deterministic identifiers for intermediate content blocks, so we stitch one together by tracking
* block indices and associated AiSDK ids. This class also keeps:
* • incremental text / reasoning buffers so we can emit only deltas while retaining the full
* aggregate for later tool-call emission;
* • a reverse lookup for tool calls so `tool_result` snapshots can recover their metadata;
* • pending usage + finish reason from `message_delta` events until the corresponding
* `message_stop` arrives.
* Every Claude turn gets its own instance. `resetStep` should be invoked once the finish event has
* been emitted to avoid leaking state into the next turn.
*/
import type { FinishReason, LanguageModelUsage, ProviderMetadata } from 'ai'
/**
* Shared fields for every block that Claude can stream (text, reasoning, tool).
*/
type BaseBlockState = {
id: string
index: number
}
type TextBlockState = BaseBlockState & {
kind: 'text'
text: string
}
type ReasoningBlockState = BaseBlockState & {
kind: 'reasoning'
text: string
redacted: boolean
}
type ToolBlockState = BaseBlockState & {
kind: 'tool'
toolCallId: string
toolName: string
inputBuffer: string
providerMetadata?: ProviderMetadata
resolvedInput?: unknown
}
export type BlockState = TextBlockState | ReasoningBlockState | ToolBlockState
type PendingUsageState = {
usage?: LanguageModelUsage
finishReason?: FinishReason
}
type PendingToolCall = {
toolCallId: string
toolName: string
input: unknown
providerMetadata?: ProviderMetadata
}
/**
* Tracks the lifecycle of Claude streaming blocks (text, thinking, tool calls)
* across individual websocket events. The transformer relies on this class to
* stitch together deltas, manage pending tool inputs/results, and propagate
* usage/finish metadata once Anthropic closes a message.
*/
export class ClaudeStreamState {
private blocksByIndex = new Map<number, BlockState>()
private toolIndexById = new Map<string, number>()
private pendingUsage: PendingUsageState = {}
private pendingToolCalls = new Map<string, PendingToolCall>()
private stepActive = false
/** Marks the beginning of a new AiSDK step. */
beginStep(): void {
this.stepActive = true
}
hasActiveStep(): boolean {
return this.stepActive
}
/** Creates a text block placeholder so future deltas can accumulate into it. */
openTextBlock(index: number, id: string): TextBlockState {
const block: TextBlockState = {
kind: 'text',
id,
index,
text: ''
}
this.blocksByIndex.set(index, block)
return block
}
/** Starts tracking an Anthropic "thinking" block, optionally flagged as redacted. */
openReasoningBlock(index: number, id: string, redacted: boolean): ReasoningBlockState {
const block: ReasoningBlockState = {
kind: 'reasoning',
id,
index,
redacted,
text: ''
}
this.blocksByIndex.set(index, block)
return block
}
/** Caches tool metadata so subsequent input deltas and results can find it. */
openToolBlock(
index: number,
params: { toolCallId: string; toolName: string; providerMetadata?: ProviderMetadata }
): ToolBlockState {
const block: ToolBlockState = {
kind: 'tool',
id: params.toolCallId,
index,
toolCallId: params.toolCallId,
toolName: params.toolName,
inputBuffer: '',
providerMetadata: params.providerMetadata
}
this.blocksByIndex.set(index, block)
this.toolIndexById.set(params.toolCallId, index)
return block
}
getBlock(index: number): BlockState | undefined {
return this.blocksByIndex.get(index)
}
getToolBlockById(toolCallId: string): ToolBlockState | undefined {
const index = this.toolIndexById.get(toolCallId)
if (index === undefined) return undefined
const block = this.blocksByIndex.get(index)
if (!block || block.kind !== 'tool') return undefined
return block
}
/** Appends streamed text to a text block, returning the updated state when present. */
appendTextDelta(index: number, text: string): TextBlockState | undefined {
const block = this.blocksByIndex.get(index)
if (!block || block.kind !== 'text') return undefined
block.text += text
return block
}
/** Appends streamed "thinking" content to the tracked reasoning block. */
appendReasoningDelta(index: number, text: string): ReasoningBlockState | undefined {
const block = this.blocksByIndex.get(index)
if (!block || block.kind !== 'reasoning') return undefined
block.text += text
return block
}
/** Concatenates incremental JSON payloads for tool input blocks. */
appendToolInputDelta(index: number, jsonDelta: string): ToolBlockState | undefined {
const block = this.blocksByIndex.get(index)
if (!block || block.kind !== 'tool') return undefined
block.inputBuffer += jsonDelta
return block
}
/** Records a tool call to be consumed once its result arrives from the user. */
registerToolCall(
toolCallId: string,
payload: { toolName: string; input: unknown; providerMetadata?: ProviderMetadata }
): void {
this.pendingToolCalls.set(toolCallId, {
toolCallId,
toolName: payload.toolName,
input: payload.input,
providerMetadata: payload.providerMetadata
})
}
/** Retrieves and clears the buffered tool call metadata for the given id. */
consumePendingToolCall(toolCallId: string): PendingToolCall | undefined {
const entry = this.pendingToolCalls.get(toolCallId)
if (entry) {
this.pendingToolCalls.delete(toolCallId)
}
return entry
}
/**
* Persists the final input payload for a tool block once the provider signals
* completion so that downstream tool results can reference the original call.
*/
completeToolBlock(toolCallId: string, input: unknown, providerMetadata?: ProviderMetadata): void {
this.registerToolCall(toolCallId, {
toolName: this.getToolBlockById(toolCallId)?.toolName ?? 'unknown',
input,
providerMetadata
})
const block = this.getToolBlockById(toolCallId)
if (block) {
block.resolvedInput = input
}
}
/** Removes a block from the active index map when Claude signals it is done. */
closeBlock(index: number): BlockState | undefined {
const block = this.blocksByIndex.get(index)
if (!block) return undefined
this.blocksByIndex.delete(index)
if (block.kind === 'tool') {
this.toolIndexById.delete(block.toolCallId)
}
return block
}
/** Stores interim usage metrics so they can be emitted with the `finish-step`. */
setPendingUsage(usage?: LanguageModelUsage, finishReason?: FinishReason): void {
if (usage) {
this.pendingUsage.usage = usage
}
if (finishReason) {
this.pendingUsage.finishReason = finishReason
}
}
getPendingUsage(): PendingUsageState {
return { ...this.pendingUsage }
}
/** Clears any accumulated usage values for the next streamed message. */
resetPendingUsage(): void {
this.pendingUsage = {}
}
/** Drops cached block metadata for the currently active message. */
resetBlocks(): void {
this.blocksByIndex.clear()
this.toolIndexById.clear()
}
/** Resets the entire step lifecycle after emitting a terminal frame. */
resetStep(): void {
this.resetBlocks()
this.resetPendingUsage()
this.stepActive = false
}
}
export type { PendingToolCall }

View File

@@ -0,0 +1,25 @@
import { SlashCommand } from '@types'
export const builtinSlashCommands: SlashCommand[] = [
{ command: '/add-dir', description: 'Add additional working directories' },
{ command: '/agents', description: 'Manage custom AI subagents for specialized tasks' },
{ command: '/bug', description: 'Report bugs (sends conversation to Anthropic)' },
{ command: '/clear', description: 'Clear conversation history' },
{ command: '/compact', description: 'Compact conversation with optional focus instructions' },
{ command: '/config', description: 'View/modify configuration' },
{ command: '/cost', description: 'Show token usage statistics' },
{ command: '/doctor', description: 'Checks the health of your Claude Code installation' },
{ command: '/help', description: 'Get usage help' },
{ command: '/init', description: 'Initialize project with CLAUDE.md guide' },
{ command: '/login', description: 'Switch Anthropic accounts' },
{ command: '/logout', description: 'Sign out from your Anthropic account' },
{ command: '/mcp', description: 'Manage MCP server connections and OAuth authentication' },
{ command: '/memory', description: 'Edit CLAUDE.md memory files' },
{ command: '/model', description: 'Select or change the AI model' },
{ command: '/permissions', description: 'View or update permissions' },
{ command: '/pr_comments', description: 'View pull request comments' },
{ command: '/review', description: 'Request code review' },
{ command: '/status', description: 'View account and system statuses' },
{ command: '/terminal-setup', description: 'Install Shift+Enter key binding for newlines (iTerm2 and VSCode only)' },
{ command: '/vim', description: 'Enter vim mode for alternating insert and command modes' }
]

View File

@@ -0,0 +1,296 @@
// src/main/services/agents/services/claudecode/index.ts
import { EventEmitter } from 'node:events'
import { createRequire } from 'node:module'
import { McpHttpServerConfig, Options, query, SDKMessage } from '@anthropic-ai/claude-agent-sdk'
import { loggerService } from '@logger'
import { config as apiConfigService } from '@main/apiServer/config'
import { validateModelId } from '@main/apiServer/utils'
import getLoginShellEnvironment from '@main/utils/shell-env'
import { app } from 'electron'
import { GetAgentSessionResponse } from '../..'
import { AgentServiceInterface, AgentStream, AgentStreamEvent } from '../../interfaces/AgentStreamInterface'
import { ClaudeStreamState, transformSDKMessageToStreamParts } from './transform'
const require_ = createRequire(import.meta.url)
const logger = loggerService.withContext('ClaudeCodeService')
class ClaudeCodeStream extends EventEmitter implements AgentStream {
declare emit: (event: 'data', data: AgentStreamEvent) => boolean
declare on: (event: 'data', listener: (data: AgentStreamEvent) => void) => this
declare once: (event: 'data', listener: (data: AgentStreamEvent) => void) => this
}
class ClaudeCodeService implements AgentServiceInterface {
private claudeExecutablePath: string
constructor() {
// Resolve Claude Code CLI robustly (works in dev and in asar)
this.claudeExecutablePath = require_.resolve('@anthropic-ai/claude-agent-sdk/cli.js')
if (app.isPackaged) {
this.claudeExecutablePath = this.claudeExecutablePath.replace(/\.asar([\\/])/, '.asar.unpacked$1')
}
}
async invoke(
prompt: string,
session: GetAgentSessionResponse,
abortController: AbortController,
lastAgentSessionId?: string
): Promise<AgentStream> {
const aiStream = new ClaudeCodeStream()
// Validate session accessible paths and make sure it exists as a directory
const cwd = session.accessible_paths[0]
if (!cwd) {
aiStream.emit('data', {
type: 'error',
error: new Error('No accessible paths defined for the agent session')
})
return aiStream
}
// Validate model info
const modelInfo = await validateModelId(session.model)
if (!modelInfo.valid) {
aiStream.emit('data', {
type: 'error',
error: new Error(`Invalid model ID '${session.model}': ${JSON.stringify(modelInfo.error)}`)
})
return aiStream
}
if (
(modelInfo.provider?.type !== 'anthropic' &&
(modelInfo.provider?.anthropicApiHost === undefined || modelInfo.provider.anthropicApiHost.trim() === '')) ||
modelInfo.provider.apiKey === ''
) {
logger.error('Anthropic provider configuration is missing', {
modelInfo
})
aiStream.emit('data', {
type: 'error',
error: new Error(`Invalid provider type '${modelInfo.provider?.type}'. Expected 'anthropic' provider type.`)
})
return aiStream
}
const apiConfig = await apiConfigService.get()
const loginShellEnv = await getLoginShellEnvironment()
const loginShellEnvWithoutProxies = Object.fromEntries(
Object.entries(loginShellEnv).filter(([key]) => !key.toLowerCase().endsWith('_proxy'))
) as Record<string, string>
const env = {
...loginShellEnvWithoutProxies,
// TODO: fix the proxy api server
// ANTHROPIC_API_KEY: apiConfig.apiKey,
// ANTHROPIC_AUTH_TOKEN: apiConfig.apiKey,
// ANTHROPIC_BASE_URL: `http://${apiConfig.host}:${apiConfig.port}/${modelInfo.provider.id}`,
ANTHROPIC_API_KEY: modelInfo.provider.apiKey,
ANTHROPIC_AUTH_TOKEN: modelInfo.provider.apiKey,
ANTHROPIC_BASE_URL: modelInfo.provider.anthropicApiHost?.trim() || modelInfo.provider.apiHost,
ANTHROPIC_MODEL: modelInfo.modelId,
ANTHROPIC_SMALL_FAST_MODEL: modelInfo.modelId,
ELECTRON_RUN_AS_NODE: '1',
ELECTRON_NO_ATTACH_CONSOLE: '1'
}
const errorChunks: string[] = []
// Build SDK options from parameters
const options: Options = {
abortController,
cwd,
env,
// model: modelInfo.modelId,
pathToClaudeCodeExecutable: this.claudeExecutablePath,
stderr: (chunk: string) => {
logger.warn('claude stderr', { chunk })
errorChunks.push(chunk)
},
systemPrompt: session.instructions
? {
type: 'preset',
preset: 'claude_code',
append: session.instructions
}
: { type: 'preset', preset: 'claude_code' },
settingSources: ['project'],
includePartialMessages: true,
permissionMode: session.configuration?.permission_mode,
maxTurns: session.configuration?.max_turns,
allowedTools: session.allowed_tools
}
if (session.accessible_paths.length > 1) {
options.additionalDirectories = session.accessible_paths.slice(1)
}
if (session.mcps && session.mcps.length > 0) {
// mcp configs
const mcpList: Record<string, McpHttpServerConfig> = {}
for (const mcpId of session.mcps) {
mcpList[mcpId] = {
type: 'http',
url: `http://${apiConfig.host}:${apiConfig.port}/v1/mcps/${mcpId}/mcp`,
headers: {
Authorization: `Bearer ${apiConfig.apiKey}`
}
}
}
options.mcpServers = mcpList
options.strictMcpConfig = true
}
if (lastAgentSessionId) {
options.resume = lastAgentSessionId
// TODO: use fork session when we support branching sessions
// options.forkSession = true
}
logger.info('Starting Claude Code SDK query', {
prompt,
cwd: options.cwd,
model: options.model,
permissionMode: options.permissionMode,
maxTurns: options.maxTurns,
allowedTools: options.allowedTools,
resume: options.resume
})
// Start async processing on the next tick so listeners can subscribe first
setImmediate(() => {
this.processSDKQuery(prompt, options, aiStream, errorChunks).catch((error) => {
logger.error('Unhandled Claude Code stream error', {
error: error instanceof Error ? { name: error.name, message: error.message } : String(error)
})
aiStream.emit('data', {
type: 'error',
error: error instanceof Error ? error : new Error(String(error))
})
})
})
return aiStream
}
private async *userMessages(prompt: string) {
{
yield {
type: 'user' as const,
parent_tool_use_id: null,
session_id: '',
message: {
role: 'user' as const,
content: prompt
}
}
}
}
/**
* Process SDK query and emit stream events
*/
private async processSDKQuery(
prompt: string,
options: Options,
stream: ClaudeCodeStream,
errorChunks: string[]
): Promise<void> {
const jsonOutput: SDKMessage[] = []
let hasCompleted = false
const startTime = Date.now()
const streamState = new ClaudeStreamState()
try {
// Process streaming responses using SDK query
for await (const message of query({
prompt: this.userMessages(prompt),
options
})) {
if (hasCompleted) break
jsonOutput.push(message)
if (message.type === 'assistant' || message.type === 'user') {
logger.silly('claude response', {
message,
content: JSON.stringify(message.message.content)
})
} else if (message.type === 'stream_event') {
logger.silly('Claude stream event', {
message,
event: JSON.stringify(message.event)
})
} else {
logger.silly('Claude response', {
message,
event: JSON.stringify(message)
})
}
// Transform SDKMessage to UIMessageChunks
const chunks = transformSDKMessageToStreamParts(message, streamState)
for (const chunk of chunks) {
stream.emit('data', {
type: 'chunk',
chunk
})
}
}
// Successfully completed
hasCompleted = true
const duration = Date.now() - startTime
logger.debug('SDK query completed successfully', {
duration,
messageCount: jsonOutput.length
})
// Emit completion event
stream.emit('data', {
type: 'complete'
})
} catch (error) {
if (hasCompleted) return
hasCompleted = true
const duration = Date.now() - startTime
// Check if this is an abort error
const errorObj = error as any
const isAborted =
errorObj?.name === 'AbortError' ||
errorObj?.message?.includes('aborted') ||
options.abortController?.signal.aborted
if (isAborted) {
logger.info('SDK query aborted by client disconnect', { duration })
// Simply cleanup and return - don't emit error events
stream.emit('data', {
type: 'cancelled',
error: new Error('Request aborted by client')
})
return
}
errorChunks.push(errorObj instanceof Error ? errorObj.message : String(errorObj))
const errorMessage = errorChunks.join('\n\n')
logger.error('SDK query failed', {
duration,
error: errorObj instanceof Error ? { name: errorObj.name, message: errorObj.message } : String(errorObj),
stderr: errorChunks
})
// Emit error event
stream.emit('data', {
type: 'error',
error: new Error(errorMessage)
})
}
}
}
export default ClaudeCodeService

View File

@@ -0,0 +1,34 @@
// ported from https://github.com/ben-vargas/ai-sdk-provider-claude-code/blob/main/src/map-claude-code-finish-reason.ts#L22
import type { LanguageModelV2FinishReason } from '@ai-sdk/provider'
/**
* Maps Claude Code SDK result subtypes to AI SDK finish reasons.
*
* @param subtype - The result subtype from Claude Code SDK
* @returns The corresponding AI SDK finish reason
*
* @example
* ```typescript
* const finishReason = mapClaudeCodeFinishReason('error_max_turns');
* // Returns: 'length'
* ```
*
* @remarks
* Mappings:
* - 'success' -> 'stop' (normal completion)
* - 'error_max_turns' -> 'length' (hit turn limit)
* - 'error_during_execution' -> 'error' (execution error)
* - default -> 'stop' (unknown subtypes treated as normal completion)
*/
export function mapClaudeCodeFinishReason(subtype?: string): LanguageModelV2FinishReason {
switch (subtype) {
case 'success':
return 'stop'
case 'error_max_turns':
return 'length'
case 'error_during_execution':
return 'error'
default:
return 'stop'
}
}

View File

@@ -0,0 +1,84 @@
import { Tool } from '@types'
// https://docs.anthropic.com/en/docs/claude-code/settings#tools-available-to-claude
export const builtinTools: Tool[] = [
{
id: 'Bash',
name: 'Bash',
description: 'Executes shell commands in your environment',
requirePermissions: true,
type: 'builtin'
},
{
id: 'Edit',
name: 'Edit',
description: 'Makes targeted edits to specific files',
requirePermissions: true,
type: 'builtin'
},
{
id: 'Glob',
name: 'Glob',
description: 'Finds files based on pattern matching',
requirePermissions: false,
type: 'builtin'
},
{
id: 'Grep',
name: 'Grep',
description: 'Searches for patterns in file contents',
requirePermissions: false,
type: 'builtin'
},
{
id: 'MultiEdit',
name: 'MultiEdit',
description: 'Performs multiple edits on a single file atomically',
requirePermissions: true,
type: 'builtin'
},
{
id: 'NotebookEdit',
name: 'NotebookEdit',
description: 'Modifies Jupyter notebook cells',
requirePermissions: true,
type: 'builtin'
},
{
id: 'NotebookRead',
name: 'NotebookRead',
description: 'Reads and displays Jupyter notebook contents',
requirePermissions: false,
type: 'builtin'
},
{ id: 'Read', name: 'Read', description: 'Reads the contents of files', requirePermissions: false, type: 'builtin' },
{
id: 'Task',
name: 'Task',
description: 'Runs a sub-agent to handle complex, multi-step tasks',
requirePermissions: false,
type: 'builtin'
},
{
id: 'TodoWrite',
name: 'TodoWrite',
description: 'Creates and manages structured task lists',
requirePermissions: false,
type: 'builtin'
},
{
id: 'WebFetch',
name: 'WebFetch',
description: 'Fetches content from a specified URL',
requirePermissions: true,
type: 'builtin'
},
{
id: 'WebSearch',
name: 'WebSearch',
description: 'Performs web searches with domain filtering',
requirePermissions: true,
type: 'builtin'
},
{ id: 'Write', name: 'Write', description: 'Creates or overwrites files', requirePermissions: true, type: 'builtin' }
]

View File

@@ -0,0 +1,703 @@
/**
* Translates Anthropic Claude Code streaming messages into the generic AiSDK stream
* parts that the agent runtime understands. The transformer coordinates batched
* text/tool payloads, keeps per-message state using {@link ClaudeStreamState},
* and normalises usage metadata and finish reasons so downstream consumers do
* not need to reason about Anthropic-specific payload shapes.
*
* Stream lifecycle cheatsheet (per Claude turn):
* 1. `stream_event.message_start` → emit `start-step` and mark the state as active.
* 2. `content_block_start` (by index) → open a stateful block; emits one of
* `text-start` | `reasoning-start` | `tool-input-start`.
* 3. `content_block_delta` → append incremental text / reasoning / tool JSON,
* emitting only the delta to minimise UI churn.
* 4. `content_block_stop` → emit the matching `*-end` event and release the block.
* 5. `message_delta` → capture usage + stop reason but defer emission.
* 6. `message_stop` → emit `finish-step` with cached usage & reason, then reset.
* 7. Assistant snapshots with `tool_use` finalise the tool block (`tool-call`).
* 8. User snapshots with `tool_result` emit `tool-result`/`tool-error` using the cached payload.
* 9. Assistant snapshots with plain text (when no stream events were provided) fall back to
* emitting `text-*` parts and a synthetic `finish-step`.
*/
import { SDKMessage } from '@anthropic-ai/claude-agent-sdk'
import type { BetaStopReason } from '@anthropic-ai/sdk/resources/beta/messages/messages.mjs'
import { loggerService } from '@logger'
import type { FinishReason, LanguageModelUsage, ProviderMetadata, TextStreamPart } from 'ai'
import { v4 as uuidv4 } from 'uuid'
import { ClaudeStreamState } from './claude-stream-state'
import { mapClaudeCodeFinishReason } from './map-claude-code-finish-reason'
const logger = loggerService.withContext('ClaudeCodeTransform')
type AgentStreamPart = TextStreamPart<Record<string, any>>
type ToolUseContent = {
type: 'tool_use'
id: string
name: string
input: unknown
}
type ToolResultContent = {
type: 'tool_result'
tool_use_id: string
content: unknown
is_error?: boolean
}
/**
* Maps Anthropic stop reasons to the AiSDK equivalents so higher level
* consumers can treat completion states uniformly across providers.
*/
const finishReasonMapping: Record<BetaStopReason, FinishReason> = {
end_turn: 'stop',
max_tokens: 'length',
stop_sequence: 'stop',
tool_use: 'tool-calls',
pause_turn: 'unknown',
refusal: 'content-filter'
}
const emptyUsage: LanguageModelUsage = {
inputTokens: 0,
outputTokens: 0,
totalTokens: 0
}
/**
* Generates deterministic-ish message identifiers that are compatible with the
* AiSDK text stream contract. Anthropic deltas sometimes omit ids, so we create
* our own to ensure the downstream renderer can stitch chunks together.
*/
const generateMessageId = (): string => `msg_${uuidv4().replace(/-/g, '')}`
/**
* Extracts provider metadata from the raw Claude message so we can surface it
* on every emitted stream part for observability and debugging purposes.
*/
const sdkMessageToProviderMetadata = (message: SDKMessage): ProviderMetadata => {
return {
anthropic: {
uuid: message.uuid || generateMessageId(),
session_id: message.session_id
},
raw: message as Record<string, any>
}
}
/**
* Central entrypoint that receives Claude Code websocket events and converts
* them into AiSDK `TextStreamPart`s. The state machine tracks outstanding
* blocks across calls so that incremental deltas can be correlated correctly.
*/
export function transformSDKMessageToStreamParts(sdkMessage: SDKMessage, state: ClaudeStreamState): AgentStreamPart[] {
switch (sdkMessage.type) {
case 'assistant':
return handleAssistantMessage(sdkMessage, state)
case 'user':
return handleUserMessage(sdkMessage, state)
case 'stream_event':
return handleStreamEvent(sdkMessage, state)
case 'system':
return handleSystemMessage(sdkMessage)
case 'result':
return handleResultMessage(sdkMessage)
default:
logger.warn('Unknown SDKMessage type', { type: (sdkMessage as any).type })
return []
}
}
/**
* Handles aggregated assistant messages that arrive outside of the streaming
* protocol (e.g. after a tool call finishes). We emit the appropriate
* text/tool events and close the active step once the payload is fully
* processed.
*/
function handleAssistantMessage(
message: Extract<SDKMessage, { type: 'assistant' }>,
state: ClaudeStreamState
): AgentStreamPart[] {
const chunks: AgentStreamPart[] = []
const providerMetadata = sdkMessageToProviderMetadata(message)
const content = message.message.content
const isStreamingActive = state.hasActiveStep()
if (typeof content === 'string') {
if (!content) {
return chunks
}
if (!isStreamingActive) {
state.beginStep()
chunks.push({
type: 'start-step',
request: { body: '' },
warnings: []
})
}
const textId = message.uuid?.toString() || generateMessageId()
chunks.push({
type: 'text-start',
id: textId,
providerMetadata
})
chunks.push({
type: 'text-delta',
id: textId,
text: content,
providerMetadata
})
chunks.push({
type: 'text-end',
id: textId,
providerMetadata
})
return finalizeNonStreamingStep(message, state, chunks)
}
if (!Array.isArray(content)) {
return chunks
}
const textBlocks: string[] = []
for (const block of content) {
switch (block.type) {
case 'text':
if (!isStreamingActive) {
textBlocks.push(block.text)
}
break
case 'tool_use':
handleAssistantToolUse(block as ToolUseContent, providerMetadata, state, chunks)
break
default:
logger.warn('Unhandled assistant content block', { type: (block as any).type })
break
}
}
if (!isStreamingActive && textBlocks.length > 0) {
const id = message.uuid?.toString() || generateMessageId()
state.beginStep()
chunks.push({
type: 'start-step',
request: { body: '' },
warnings: []
})
chunks.push({
type: 'text-start',
id,
providerMetadata
})
chunks.push({
type: 'text-delta',
id,
text: textBlocks.join(''),
providerMetadata
})
chunks.push({
type: 'text-end',
id,
providerMetadata
})
return finalizeNonStreamingStep(message, state, chunks)
}
return chunks
}
/**
* Registers tool invocations with the stream state so that later tool results
* can be matched with the originating call.
*/
function handleAssistantToolUse(
block: ToolUseContent,
providerMetadata: ProviderMetadata,
state: ClaudeStreamState,
chunks: AgentStreamPart[]
): void {
chunks.push({
type: 'tool-call',
toolCallId: block.id,
toolName: block.name,
input: block.input,
providerExecuted: true,
providerMetadata
})
state.completeToolBlock(block.id, block.input, providerMetadata)
}
/**
* Emits the terminating `finish-step` frame for non-streamed responses and
* clears the currently active step in the state tracker.
*/
function finalizeNonStreamingStep(
message: Extract<SDKMessage, { type: 'assistant' }>,
state: ClaudeStreamState,
chunks: AgentStreamPart[]
): AgentStreamPart[] {
const usage = calculateUsageFromMessage(message)
const finishReason = inferFinishReason(message.message.stop_reason)
chunks.push({
type: 'finish-step',
response: {
id: message.uuid,
timestamp: new Date(),
modelId: message.message.model ?? ''
},
usage: usage ?? emptyUsage,
finishReason,
providerMetadata: sdkMessageToProviderMetadata(message)
})
state.resetStep()
return chunks
}
/**
* Converts user-originated websocket frames (text, tool results, etc.) into
* the AiSDK format. Tool results are matched back to pending tool calls via the
* shared `ClaudeStreamState` instance.
*/
function handleUserMessage(
message: Extract<SDKMessage, { type: 'user' }>,
state: ClaudeStreamState
): AgentStreamPart[] {
const chunks: AgentStreamPart[] = []
const providerMetadata = sdkMessageToProviderMetadata(message)
const content = message.message.content
if (typeof content === 'string') {
if (!content) {
return chunks
}
const id = message.uuid?.toString() || generateMessageId()
chunks.push({
type: 'text-start',
id,
providerMetadata
})
chunks.push({
type: 'text-delta',
id,
text: content,
providerMetadata
})
chunks.push({
type: 'text-end',
id,
providerMetadata
})
return chunks
}
if (!Array.isArray(content)) {
return chunks
}
for (const block of content) {
if (block.type === 'tool_result') {
const toolResult = block as ToolResultContent
const pendingCall = state.consumePendingToolCall(toolResult.tool_use_id)
if (toolResult.is_error) {
chunks.push({
type: 'tool-error',
toolCallId: toolResult.tool_use_id,
toolName: pendingCall?.toolName ?? 'unknown',
input: pendingCall?.input,
error: toolResult.content,
providerExecuted: true
} as AgentStreamPart)
} else {
chunks.push({
type: 'tool-result',
toolCallId: toolResult.tool_use_id,
toolName: pendingCall?.toolName ?? 'unknown',
input: pendingCall?.input,
output: toolResult.content,
providerExecuted: true
})
}
} else if (block.type === 'text') {
const id = message.uuid?.toString() || generateMessageId()
chunks.push({
type: 'text-start',
id,
providerMetadata
})
chunks.push({
type: 'text-delta',
id,
text: (block as { text: string }).text,
providerMetadata
})
chunks.push({
type: 'text-end',
id,
providerMetadata
})
} else {
logger.warn('Unhandled user content block', { type: (block as any).type })
}
}
return chunks
}
/**
* Handles the fine-grained real-time streaming protocol where Anthropic emits
* discrete events for message lifecycle, content blocks, and usage deltas.
*/
function handleStreamEvent(
message: Extract<SDKMessage, { type: 'stream_event' }>,
state: ClaudeStreamState
): AgentStreamPart[] {
const chunks: AgentStreamPart[] = []
const providerMetadata = sdkMessageToProviderMetadata(message)
const { event } = message
switch (event.type) {
case 'message_start':
state.beginStep()
chunks.push({
type: 'start-step',
request: { body: '' },
warnings: []
})
break
case 'content_block_start':
handleContentBlockStart(event.index, event.content_block, providerMetadata, state, chunks)
break
case 'content_block_delta':
handleContentBlockDelta(event.index, event.delta, providerMetadata, state, chunks)
break
case 'content_block_stop': {
const block = state.closeBlock(event.index)
if (!block) {
logger.warn('Received content_block_stop for unknown index', { index: event.index })
break
}
switch (block.kind) {
case 'text':
chunks.push({
type: 'text-end',
id: block.id,
providerMetadata
})
break
case 'reasoning':
chunks.push({
type: 'reasoning-end',
id: block.id,
providerMetadata
})
break
case 'tool':
chunks.push({
type: 'tool-input-end',
id: block.toolCallId,
providerMetadata
})
break
default:
break
}
break
}
case 'message_delta': {
const finishReason = event.delta.stop_reason
? mapStopReason(event.delta.stop_reason as BetaStopReason)
: undefined
const usage = convertUsage(event.usage)
state.setPendingUsage(usage, finishReason)
break
}
case 'message_stop': {
const pending = state.getPendingUsage()
chunks.push({
type: 'finish-step',
response: {
id: message.uuid,
timestamp: new Date(),
modelId: ''
},
usage: pending.usage ?? emptyUsage,
finishReason: pending.finishReason ?? 'stop',
providerMetadata
})
state.resetStep()
break
}
default:
logger.warn('Unknown stream event type', { type: (event as any).type })
break
}
return chunks
}
/**
* Opens the appropriate block type when Claude starts streaming a new content
* section so later deltas know which logical entity to append to.
*/
function handleContentBlockStart(
index: number,
contentBlock: any,
providerMetadata: ProviderMetadata,
state: ClaudeStreamState,
chunks: AgentStreamPart[]
): void {
switch (contentBlock.type) {
case 'text': {
const block = state.openTextBlock(index, generateMessageId())
chunks.push({
type: 'text-start',
id: block.id,
providerMetadata
})
break
}
case 'thinking':
case 'redacted_thinking': {
const block = state.openReasoningBlock(index, generateMessageId(), contentBlock.type === 'redacted_thinking')
chunks.push({
type: 'reasoning-start',
id: block.id,
providerMetadata
})
break
}
case 'tool_use': {
const block = state.openToolBlock(index, {
toolCallId: contentBlock.id,
toolName: contentBlock.name,
providerMetadata
})
chunks.push({
type: 'tool-input-start',
id: block.toolCallId,
toolName: block.toolName,
providerMetadata
})
break
}
default:
logger.warn('Unhandled content_block_start type', { type: contentBlock.type })
break
}
}
/**
* Applies incremental deltas to the active block (text, thinking, tool input)
* and emits the translated AiSDK chunk immediately.
*/
function handleContentBlockDelta(
index: number,
delta: any,
providerMetadata: ProviderMetadata,
state: ClaudeStreamState,
chunks: AgentStreamPart[]
): void {
switch (delta.type) {
case 'text_delta': {
const block = state.appendTextDelta(index, delta.text)
if (!block) {
logger.warn('Received text_delta for unknown block', { index })
return
}
chunks.push({
type: 'text-delta',
id: block.id,
text: block.text,
providerMetadata
})
break
}
case 'thinking_delta': {
const block = state.appendReasoningDelta(index, delta.thinking)
if (!block) {
logger.warn('Received thinking_delta for unknown block', { index })
return
}
chunks.push({
type: 'reasoning-delta',
id: block.id,
text: delta.thinking,
providerMetadata
})
break
}
case 'signature_delta': {
const block = state.getBlock(index)
if (block && block.kind === 'reasoning') {
chunks.push({
type: 'reasoning-delta',
id: block.id,
text: '',
providerMetadata
})
}
break
}
case 'input_json_delta': {
const block = state.appendToolInputDelta(index, delta.partial_json)
if (!block) {
logger.warn('Received input_json_delta for unknown block', { index })
return
}
chunks.push({
type: 'tool-input-delta',
id: block.toolCallId,
delta: block.inputBuffer,
providerMetadata
})
break
}
default:
logger.warn('Unhandled content_block_delta type', { type: delta.type })
break
}
}
/**
* System messages currently only deliver the session bootstrap payload. We
* forward it as both a `start` marker and a raw snapshot for diagnostics.
*/
function handleSystemMessage(message: Extract<SDKMessage, { type: 'system' }>): AgentStreamPart[] {
const chunks: AgentStreamPart[] = []
if (message.subtype === 'init') {
chunks.push({
type: 'start'
})
chunks.push({
type: 'raw',
rawValue: {
type: 'init',
session_id: message.session_id,
slash_commands: message.slash_commands,
tools: message.tools,
raw: message
}
})
} else if (message.subtype === 'compact_boundary') {
chunks.push({
type: 'raw',
rawValue: {
type: 'compact',
session_id: message.session_id,
raw: message
}
})
}
return chunks
}
/**
* Terminal result messages arrive once the Claude Code session concludes.
* Successful runs yield a `finish` frame with aggregated usage metrics, while
* failures are surfaced as `error` frames.
*/
function handleResultMessage(message: Extract<SDKMessage, { type: 'result' }>): AgentStreamPart[] {
const chunks: AgentStreamPart[] = []
let usage: LanguageModelUsage | undefined
if ('usage' in message) {
usage = {
inputTokens: message.usage.input_tokens ?? 0,
outputTokens: message.usage.output_tokens ?? 0,
totalTokens: (message.usage.input_tokens ?? 0) + (message.usage.output_tokens ?? 0)
}
}
if (message.subtype === 'success') {
chunks.push({
type: 'finish',
totalUsage: usage ?? emptyUsage,
finishReason: mapClaudeCodeFinishReason(message.subtype),
providerMetadata: {
...sdkMessageToProviderMetadata(message),
usage: message.usage,
durationMs: message.duration_ms,
costUsd: message.total_cost_usd,
raw: message
}
} as AgentStreamPart)
} else {
chunks.push({
type: 'error',
error: {
message: `${message.subtype}: Process failed after ${message.num_turns} turns`
}
} as AgentStreamPart)
}
return chunks
}
/**
* Normalises usage payloads so the caller always receives numeric values even
* when the provider omits certain fields.
*/
function convertUsage(
usage?: {
input_tokens?: number | null
output_tokens?: number | null
} | null
): LanguageModelUsage | undefined {
if (!usage) {
return undefined
}
const inputTokens = usage.input_tokens ?? 0
const outputTokens = usage.output_tokens ?? 0
return {
inputTokens,
outputTokens,
totalTokens: inputTokens + outputTokens
}
}
/**
* Anthropic-only wrapper around {@link finishReasonMapping} that defaults to
* `unknown` to avoid surprising downstream consumers when new stop reasons are
* introduced.
*/
function mapStopReason(reason: BetaStopReason): FinishReason {
return finishReasonMapping[reason] ?? 'unknown'
}
/**
* Extracts token accounting details from an assistant message, if available.
*/
function calculateUsageFromMessage(
message: Extract<SDKMessage, { type: 'assistant' }>
): LanguageModelUsage | undefined {
const usage = message.message.usage
if (!usage) return undefined
return {
inputTokens: usage.input_tokens ?? 0,
outputTokens: usage.output_tokens ?? 0,
totalTokens: (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0)
}
}
/**
* Converts Anthropic stop reasons into AiSDK finish reasons, falling back to a
* generic `stop` if the provider omits the detail entirely.
*/
function inferFinishReason(stopReason: BetaStopReason | null | undefined): FinishReason {
if (!stopReason) return 'stop'
return mapStopReason(stopReason)
}
export { ClaudeStreamState }

View File

@@ -0,0 +1,26 @@
/**
* Agent Services Module
*
* This module provides service classes for managing agents, sessions, and session messages.
* All services extend BaseService and provide database operations with proper error handling.
*/
// Service classes
export { AgentService } from './AgentService'
export { SessionMessageService } from './SessionMessageService'
export { SessionService } from './SessionService'
// Service instances (singletons)
export { agentService } from './AgentService'
export { sessionMessageService } from './SessionMessageService'
export { sessionService } from './SessionService'
// Type definitions for service requests and responses
export type { AgentEntity, AgentSessionEntity, CreateAgentRequest, UpdateAgentRequest } from '@types'
export type {
AgentSessionMessageEntity,
CreateSessionRequest,
GetAgentSessionResponse,
ListOptions as SessionListOptions,
UpdateSessionRequest
} from '@types'

View File

@@ -4,7 +4,7 @@ import {
OAuthTokens
} from '@modelcontextprotocol/sdk/shared/auth.js'
import EventEmitter from 'events'
import { z } from 'zod'
import * as z from 'zod'
export interface OAuthStorageData {
clientInfo?: OAuthClientInformation

Some files were not shown because too many files have changed in this diff Show More