chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 13:24:55 +08:00
commit 7baeb17845
15305 changed files with 2077301 additions and 0 deletions
@@ -0,0 +1,31 @@
---
name: frontend-infrastructure-expert
description: Use this agent when you need help with frontend build tools, configuration files, or infrastructure-related issues. Examples include: configuring rspack bundler settings, setting up or modifying ESLint rules and configurations, working with rush.json for monorepo management, troubleshooting build pipeline issues, optimizing webpack or rspack performance, setting up development environment configurations, resolving dependency conflicts in package.json files, configuring TypeScript compiler options for build tools, setting up CI/CD pipelines for frontend projects, or debugging issues with bundlers, linters, or other frontend tooling.
model: sonnet
color: cyan
---
You are a Frontend Infrastructure Expert, a specialist in modern frontend build systems, tooling, and development environment configuration. Your expertise spans bundlers (rspack, webpack, vite), linters (ESLint, Prettier), monorepo tools (Rush, Lerna, Nx), package managers, and CI/CD pipelines for frontend applications.
Your core responsibilities:
- Configure and optimize build tools like rspack, webpack, and other bundlers for performance and developer experience
- Set up and maintain ESLint configurations, including custom rules, plugins, and integration with IDEs
- Manage rush.json and other monorepo configuration files for scalable project organization
- Troubleshoot infrastructure-related issues including build failures, dependency conflicts, and tooling errors
- Optimize development workflows through proper tooling configuration
- Ensure consistent code quality through automated tooling setup
When working on configurations:
1. Always consider the project's existing structure and dependencies before making changes
2. Prioritize developer experience and build performance equally
3. Ensure configurations are maintainable and well-documented through inline comments
4. Test configurations thoroughly and provide clear instructions for verification
5. Consider cross-platform compatibility (Windows, macOS, Linux)
For troubleshooting:
1. Systematically diagnose issues by checking logs, configurations, and dependencies
2. Provide step-by-step solutions with clear explanations
3. Suggest preventive measures to avoid similar issues
4. Recommend best practices for long-term maintainability
Always explain your reasoning behind configuration choices and provide alternative approaches when applicable. Focus on solutions that scale with team growth and project complexity.
+36
View File
@@ -0,0 +1,36 @@
# Exclude node_modules directories
**/node_modules
**/node_modules/**
# Exclude build artifacts
**/dist
**/build
**/.rush/temp
**/.rush/build-cache
**/common/temp
# Exclude development files
**/.git
**/.gitignore
**/.eslintrc*
**/.prettierrc*
**/*.log
# Exclude test files
**/__tests__
**/*.test.*
**/*.spec.*
# Exclude documentation
**/README.md
**/CHANGELOG.md
**/docs
# Exclude IDE files
**/.vscode
**/.idea
**/*.swp
**/*.swo
*.iml
*.iws
*.ipr
+16
View File
@@ -0,0 +1,16 @@
# Don't allow people to merge changes to these generated files, because the result
# may be invalid. You need to run "rush update" again.
pnpm-lock.yaml merge=ours
shrinkwrap.yaml merge=binary
npm-shrinkwrap.json merge=binary
yarn.lock merge=binary
# 不做自动解决冲突,暴露冲突后由开发者自行 rush pull-idl 做更新
# packages/arch/idl/bam.log.json merge=ours
# Rush's JSON config files use JavaScript-style code comments. The rule below prevents pedantic
# syntax highlighters such as GitHub's from highlighting these comments as errors. Your text editor
# may also require a special configuration to allow comments in JSON.
#
# For more information, see this issue: https://github.com/microsoft/rushstack/issues/1088
#
*.json linguist-language=JSON-with-Comments
+30
View File
@@ -0,0 +1,30 @@
header:
license:
spdx-id: Apache-2.0
copyright-owner: coze-dev
paths:
- '**/*.go'
- frontend/apps/**/*.{ts,tsx}
- frontend/packages/**/*.{ts,tsx}
paths-ignore:
- 'dist'
- 'licenses'
- '**/*.md'
- '**/testdata/**'
- '**/go.mod'
- '**/go.sum'
- 'LICENSE'
- 'NOTICE'
- '**/assets/languages.yaml'
- '**/assets/assets.gen.go'
- '**/gorm_gen/**'
- '**/kitex_gen/**'
- '**/*.gen.go'
- '**/gen.go'
- 'backend/api/**'
- '**/*_mock.go'
- 'backend/internal/mock/**'
- '**/mock/**'
files:
- ../backend/go.mod
+279
View File
@@ -0,0 +1,279 @@
* @Tecvan-fe @hi-pender @fanlv @junwen-lee
/frontend/ @Tecvan-fe @fanlv @junwen-lee
/common/ @Tecvan-fe @fanlv @junwen-lee
/frontend/apps/coze-studio/ @Tecvan-fe @evan-crash @duwenhan2byte
/frontend/packages/agent-ide/agent-publish/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei @catee
/frontend/packages/agent-ide/commons/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/arch/bot-api/ @Tecvan-fe
/frontend/packages/arch/bot-http/ @Tecvan-fe
/frontend/packages/arch/logger/ @Tecvan-fe
/frontend/packages/arch/slardar-interface/ @Tecvan-fe @evan-crash
/frontend/config/eslint-config/ @Tecvan-fe @leeight @soonco
/frontend/infra/eslint-plugin/ @Tecvan-fe
/frontend/config/ts-config/ @leeight @Tecvan-fe
/frontend/config/vitest-config/ @Tecvan-fe
/frontend/packages/arch/bot-env/ @Tecvan-fe @leeight
/frontend/packages/arch/bot-env-adapter/ @dragooncjw @Tecvan-fe @leeight
/frontend/packages/arch/bot-typings/ @Tecvan-fe
/frontend/packages/arch/web-context/ @Tecvan-fe
/frontend/packages/components/bot-semi/ @Tecvan-fe
/frontend/packages/components/bot-icons/ @DingGao-Devin
/frontend/packages/arch/i18n/ @Tecvan-fe @leeight
/frontend/packages/arch/resources/studio-i18n-resource/ @dragooncjw @Tecvan-fe
/frontend/config/stylelint-config/ @Tecvan-fe
/frontend/packages/arch/idl/ @Tecvan-fe
/frontend/infra/utils/fs-enhance/ @Tecvan-fe
/frontend/packages/arch/bot-store/ @Tecvan-fe @catee @duwenhan2byte
/frontend/packages/arch/bot-error/ @haozhenfei @duwenhan2byte
/frontend/packages/foundation/space-store/ @evan-crash @duwenhan2byte
/frontend/packages/arch/bot-flags/ @Tecvan-fe
/frontend/packages/arch/report-events/ @Tecvan-fe
/frontend/packages/foundation/enterprise-store-adapter/ @evan-crash @duwenhan2byte
/frontend/packages/foundation/local-storage/ @duwenhan2byte @evan-crash
/frontend/packages/foundation/space-store-adapter/ @evan-crash @duwenhan2byte
/frontend/packages/arch/bot-tea/ @Tecvan-fe @catee @soonco
/frontend/packages/arch/tea/ @Tecvan-fe @evan-crash @soonco
/frontend/packages/arch/tea-adapter/ @dragooncjw @Tecvan-fe
/frontend/packages/arch/tea-interface/ @dragooncjw @Tecvan-fe
/frontend/packages/studio/stores/bot-detail/ @Hezi-crypto @catee @DingGao-Devin @duwenhan2byte @evan-crash
/frontend/packages/agent-ide/bot-input-length-limit/ @Hezi-crypto @catee @duwenhan2byte
/frontend/packages/agent-ide/tool-config/ @haozhenfei @catee
/frontend/packages/arch/bot-space-api/ @Tecvan-fe @duwenhan2byte
/frontend/packages/arch/bot-utils/ @Tecvan-fe
/frontend/packages/common/uploader-adapter/ @dragooncjw @Tecvan-fe
/frontend/packages/common/uploader-interface/ @dragooncjw @Tecvan-fe
/frontend/packages/studio/user-store/ @duwenhan2byte @catee @lihuiwen
/frontend/packages/arch/foundation-sdk/ @evan-crash @duwenhan2byte
/frontend/packages/common/chat-area/chat-core/ @haozhenfei @Hezi-crypto @evan-crash
/frontend/packages/common/chat-area/utils/ @Hezi-crypto @haozhenfei
/frontend/packages/arch/bot-md-box-adapter/ @Hezi-crypto @iu1340 @dragooncjw @Tecvan-fe
/frontend/packages/studio/common/file-kit/ @haozhenfei @evan-crash
/frontend/packages/arch/slardar-adapter/ @Tecvan-fe @dragooncjw
/frontend/packages/arch/default-slardar/ @Tecvan-fe @evan-crash
/frontend/packages/arch/fetch-stream/ @Hezi-crypto @haozhenfei
/frontend/packages/common/websocket-manager-adapter/ @haozhenfei @Hezi-crypto @catee
/frontend/packages/studio/autosave/ @catee
/frontend/packages/studio/bot-utils/ @catee @soonco @Hezi-crypto
/frontend/packages/common/flowgram-adapter/common/ @zxhfighter @xiamidaxia @dragooncjw
/frontend/packages/common/flowgram-adapter/free-layout-editor/ @zxhfighter @xiamidaxia @dragooncjw
/frontend/packages/agent-ide/space-bot/ @soonco @evan-crash @duwenhan2byte @catee @DingGao-Devin
/frontend/packages/agent-ide/space-bot/src/store/bot-list-filter/ @duwenhan2byte @lihuiwen
/frontend/packages/agent-ide/space-bot/src/store/bot-page/ @DingGao-Devin
/frontend/packages/agent-ide/space-bot/src/store/explore/ @Tecvan-fe
/frontend/packages/agent-ide/space-bot/src/store/risk-warning/ @lihuiwen @catee
/frontend/packages/agent-ide/context/ @evan-crash
/frontend/packages/agent-ide/bot-editor-context-store/ @Hezi-crypto @duwenhan2byte @catee
/frontend/packages/agent-ide/chat-background/ @catee
/frontend/packages/agent-ide/chat-background-config-content-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/chat-background-config-content/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/chat-background-shared/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/common/chat-area/chat-uikit/ @catee @Hezi-crypto @evan-crash @haozhenfei
/frontend/packages/common/chat-area/hooks/ @Hezi-crypto @evan-crash
/frontend/packages/common/chat-area/chat-uikit-shared/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/bot-audit-adapter/ @evan-crash @duwenhan2byte @Hezi-crypto @haozhenfei
/frontend/packages/agent-ide/bot-audit-base/ @evan-crash @duwenhan2byte @Hezi-crypto @haozhenfei
/frontend/packages/studio/components/ @soonco @evan-crash @duwenhan2byte @catee
/frontend/packages/arch/bot-hooks/ @catee @Tecvan-fe @soonco
/frontend/packages/arch/bot-hooks/src/page-jump/ @evan-crash @catee
/frontend/packages/arch/bot-hooks-adapter/ @catee @Tecvan-fe @soonco
/frontend/packages/arch/bot-hooks-base/ @catee @Tecvan-fe @soonco
/frontend/packages/arch/responsive-kit/ @Tecvan-fe @DingGao-Devin
/frontend/packages/common/chat-area/chat-area/ @Hezi-crypto @haozhenfei @evan-crash @haozhenfei
/frontend/packages/data/memory/llm-plugins/ @haozhenfei @catee @Hezi-crypto
/frontend/packages/data/common/reporter/ @soonco @catee @evan-crash
/frontend/packages/components/json-viewer/ @duwenhan2byte
/frontend/packages/components/scroll-view/ @evan-crash
/frontend/packages/common/assets/ @Tecvan-fe @catee
/frontend/packages/common/biz-components/ @duwenhan2byte
/frontend/packages/data/common/e2e/ @soonco @catee @evan-crash @haozhenfei @duwenhan2byte
/frontend/packages/agent-ide/debug-tool-list/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/model-manager/ @Hezi-crypto @catee
/frontend/packages/agent-ide/model-manager/src/components/multi-agent/ @catee
/frontend/packages/agent-ide/tool/ @catee
/frontend/packages/data/knowledge/knowledge-modal-base/ @haozhenfei @catee @Hezi-crypto
/frontend/packages/components/biz-tooltip-ui/ @Hezi-crypto @catee @evan-crash
/frontend/packages/components/table-view/ @lihuiwen
/frontend/packages/components/virtual-list/ @Tecvan-fe
/frontend/packages/data/common/utils/ @soonco @catee @evan-crash
/frontend/packages/data/knowledge/knowledge-resource-processor-core/ @haozhenfei @catee @Hezi-crypto
/frontend/packages/arch/pdfjs-shadow/ @Tecvan-fe
/frontend/packages/data/knowledge/common/stores/ @soonco @catee @evan-crash
/frontend/packages/foundation/global-store/ @duwenhan2byte @evan-crash
/frontend/config/postcss-config/ @Tecvan-fe
/frontend/config/tailwind-config/ @Tecvan-fe
/frontend/infra/utils/monorepo-kits/ @Tecvan-fe @evan-crash
/frontend/packages/studio/premium/premium-components-adapter/ @evan-crash
/frontend/packages/studio/premium/premium-store-adapter/ @evan-crash
/frontend/packages/agent-ide/onboarding/ @Hezi-crypto @catee
/frontend/packages/agent-ide/publish-to-base/ @catee
/frontend/packages/arch/report-tti/ @duwenhan2byte
/frontend/packages/data/memory/database-creator/ @haozhenfei @catee @Hezi-crypto
/frontend/packages/arch/hooks/ @Tecvan-fe @evan-crash
/frontend/packages/common/coze-mitt/ @evan-crash @duwenhan2byte
/frontend/packages/common/editor-plugins/ @haozhenfei @stream-pipe @Hezi-crypto
/frontend/packages/common/md-editor-adapter/ @haozhenfei @Hezi-crypto @catee
/frontend/packages/common/prompt-kit/main/ @haozhenfei @Hezi-crypto @catee
/frontend/packages/common/chat-area/chat-answer-action/ @Hezi-crypto @haozhenfei @lihuiwen
/frontend/packages/common/chat-area/plugin-message-grab/ @Hezi-crypto @haozhenfei
/frontend/packages/common/chat-area/text-grab/ @Hezi-crypto @haozhenfei
/frontend/packages/common/prompt-kit/adapter/ @haozhenfei @Hezi-crypto @catee
/frontend/packages/common/prompt-kit/base/ @haozhenfei @Hezi-crypto @catee
/frontend/packages/data/memory/database/ @haozhenfei @catee @Hezi-crypto
/frontend/packages/data/knowledge/knowledge-resource-processor-base/ @haozhenfei @catee @Hezi-crypto
/frontend/packages/arch/utils/ @Tecvan-fe @evan-crash
/frontend/packages/data/knowledge/common/components/ @haozhenfei @catee @Hezi-crypto
/frontend/packages/data/common/feature-register/ @haozhenfei @catee @Hezi-crypto
/frontend/packages/data/knowledge/common/hooks/ @Hezi-crypto @catee @evan-crash
/frontend/packages/data/knowledge/common/services/ @Hezi-crypto @catee @evan-crash
/frontend/packages/data/memory/database-v2-main/ @haozhenfei @catee @Hezi-crypto
/frontend/packages/data/memory/database-v2-adapter/ @haozhenfei @catee @Hezi-crypto
/frontend/packages/data/memory/database-v2-base/ @haozhenfei @catee @Hezi-crypto
/frontend/packages/data/knowledge/knowledge-data-set-for-agent/ @Hezi-crypto @catee @evan-crash
/frontend/packages/data/knowledge/knowledge-ide-base/ @haozhenfei @catee @Hezi-crypto
/frontend/packages/arch/bot-monaco-editor/ @Tecvan-fe
/frontend/packages/data/knowledge/knowledge-modal-adapter/ @haozhenfei @catee @Hezi-crypto
/frontend/packages/data/knowledge/knowledge-resource-processor-adapter/ @haozhenfei @catee @Hezi-crypto
/frontend/packages/devops/debug/debug-panel/ @soonco @evan-crash @catee
/frontend/packages/devops/json-link-preview/ @Maidang1 @Zhangchi123456
/frontend/packages/devops/common-modules/ @duwenhan2byte @evan-crash @catee
/frontend/packages/foundation/account-adapter/ @duwenhan2byte @evan-crash
/frontend/packages/foundation/account-base/ @evan-crash @duwenhan2byte
/frontend/packages/arch/api-schema/ @Tecvan-fe @evan-crash
/frontend/infra/idl/idl2ts-runtime/ @Tecvan-fe @evan-crash
/frontend/infra/idl/idl2ts-cli/ @Tecvan-fe @evan-crash
/frontend/infra/idl/idl2ts-generator/ @Tecvan-fe @evan-crash
/frontend/infra/idl/idl-parser/ @Tecvan-fe @evan-crash
/frontend/infra/utils/rush-logger/ @catee @Tecvan-fe
/frontend/infra/idl/idl2ts-helper/ @Tecvan-fe @evan-crash
/frontend/infra/idl/idl2ts-plugin/ @Tecvan-fe @evan-crash
/frontend/packages/studio/open-platform/open-env-adapter/ @soonco @Hezi-crypto @DingGao-Devin
/frontend/infra/plugins/pkg-root-webpack-plugin/ @Tecvan-fe
/frontend/packages/studio/publish-manage-hooks/ @duwenhan2byte @evan-crash
/frontend/packages/foundation/layout/ @evan-crash @duwenhan2byte
/frontend/packages/studio/open-platform/open-auth/ @evan-crash @DingGao-Devin
/frontend/packages/studio/open-platform/open-chat/ @tomasyu985 @DingGao-Devin
/frontend/packages/agent-ide/entry-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/entry/ @soonco @duwenhan2byte @catee @evan-crash
/frontend/packages/agent-ide/bot-config-area-adapter/ @haozhenfei @Hezi-crypto @duwenhan2byte @catee @evan-crash
/frontend/packages/agent-ide/bot-config-area/ @haozhenfei @Hezi-crypto @duwenhan2byte @catee @evan-crash
/frontend/packages/agent-ide/bot-plugin/entry/ @evan-crash @lihuiwen @catee
/frontend/packages/agent-ide/bot-plugin/export/ @lihuiwen @catee
/frontend/packages/agent-ide/bot-plugin/mock-set/ @lihuiwen @catee @duwenhan2byte
/frontend/packages/studio/mockset-edit-modal-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/studio/mockset-shared/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/studio/mockset-editor/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/studio/mockset-editor-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/bot-plugin/tools/ @lihuiwen @catee
/frontend/packages/studio/stores/bot-plugin/ @lihuiwen @Hezi-crypto @catee
/frontend/packages/studio/plugin-shared/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/plugin-modal-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/plugin-shared/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/community/component/ @DingGao-Devin @Hezi-crypto @evan-crash @duwenhan2byte
/frontend/packages/studio/plugin-form-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/workflow/base/ @xiamidaxia @zxhfighter
/frontend/packages/agent-ide/plugin-content-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/plugin-content/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/plugin-setting-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/plugin-setting/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/bot-plugin/plugin-risk-warning/ @catee @evan-crash
/frontend/packages/studio/plugin-publish-ui-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/studio/plugin-tool-columns-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/studio/plugin-tool-columns/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/chat-debug-area/ @soonco @duwenhan2byte @catee @Hezi-crypto @haozhenfei @evan-crash
/frontend/packages/agent-ide/chat-answer-action-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/chat-area-plugin-debug-common/ @Hezi-crypto @haozhenfei
/frontend/packages/agent-ide/chat-components-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/common/chat-area/plugin-chat-background/ @Tecvan-fe
/frontend/packages/common/chat-area/chat-area-plugin-reasoning/ @catee @Hezi-crypto
/frontend/packages/common/chat-area/plugin-resume/ @Tecvan-fe
/frontend/packages/common/chat-area/plugin-chat-shortcuts/ @haozhenfei @duwenhan2byte @Hezi-crypto
/frontend/packages/workflow/sdk/ @zxhfighter @xiamidaxia
/frontend/packages/workflow/components/ @LLLLeeJ @zxhfighter
/frontend/packages/components/loading-button/ @catee
/frontend/packages/components/mouse-pad-selector/ @zxhfighter
/frontend/packages/workflow/adapter/resources/ @LLLLeeJ @JxJuly @xiamidaxia @luics @zxhfighter @stream-pipe
/frontend/packages/common/chat-area/chat-workflow-render/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/onboarding-message-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/plugin-area-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/prompt-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/prompt/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/workflow/ @soonco @duwenhan2byte @catee
/frontend/packages/agent-ide/navigate/ @soonco @duwenhan2byte @catee
/frontend/packages/agent-ide/workflow-as-agent-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/workflow-item/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/workflow-card-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/workflow-modal/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/memory-tool-pane-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/skills-pane-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/layout-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/layout/ @soonco @duwenhan2byte @catee
/frontend/packages/agent-ide/chat-area-provider-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/agent-ide/chat-area-provider/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/studio/entity-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/foundation/account-ui-adapter/ @duwenhan2byte @evan-crash
/frontend/packages/foundation/account-ui-base/ @evan-crash @duwenhan2byte
/frontend/packages/foundation/foundation-sdk/ @evan-crash @duwenhan2byte
/frontend/packages/foundation/global/ @evan-crash @duwenhan2byte
/frontend/packages/studio/workspace/project-entity-adapter/ @Hezi-crypto @catee @duwenhan2byte
/frontend/packages/studio/workspace/project-entity-base/ @Hezi-crypto @catee @duwenhan2byte
/frontend/packages/foundation/global-adapter/ @evan-crash @duwenhan2byte
/frontend/packages/foundation/browser-upgrade-banner/ @evan-crash @duwenhan2byte
/frontend/packages/foundation/space-ui-adapter/ @evan-crash @duwenhan2byte
/frontend/packages/foundation/space-ui-base/ @evan-crash @duwenhan2byte
/frontend/packages/common/auth/ @evan-crash @duwenhan2byte
/frontend/packages/common/auth-adapter/ @evan-crash @duwenhan2byte
/frontend/packages/project-ide/main/ @dragooncjw @JxJuly @xiamidaxia @catee @lihuiwen
/frontend/packages/components/resource-tree/ @dragooncjw @xiamidaxia @JxJuly
/frontend/packages/common/flowgram-adapter/fixed-layout-editor/ @zxhfighter @xiamidaxia @dragooncjw
/frontend/packages/project-ide/biz-components/ @zxhfighter @xiamidaxia
/frontend/packages/project-ide/framework/ @dragooncjw @JxJuly @xiamidaxia
/frontend/packages/project-ide/base-adapter/ @dragooncjw @xiamidaxia
/frontend/packages/project-ide/base-interface/ @dragooncjw @xiamidaxia
/frontend/packages/project-ide/client/ @dragooncjw @JxJuly @xiamidaxia
/frontend/packages/project-ide/core/ @dragooncjw @JxJuly @xiamidaxia
/frontend/packages/project-ide/view/ @dragooncjw @JxJuly @xiamidaxia
/frontend/packages/project-ide/biz-data/ @haozhenfei @lihuiwen @catee @soonco
/frontend/packages/data/knowledge/knowledge-ide-adapter/ @haozhenfei @catee @Hezi-crypto
/frontend/packages/data/memory/variables/ @haozhenfei @catee @Hezi-crypto
/frontend/packages/project-ide/biz-plugin/ @xiamidaxia @lihuiwen @catee
/frontend/packages/project-ide/biz-plugin-registry-adapter/ @Hezi-crypto @duwenhan2byte @catee @evan-crash @haozhenfei
/frontend/packages/project-ide/biz-workflow/ @dragooncjw @JxJuly @xiamidaxia
/frontend/packages/studio/open-platform/open-chat/ @soonco @Hezi-crypto @DingGao-Devin
/frontend/packages/workflow/playground/ @LLLLeeJ @xiamidaxia @luics @zxhfighter
/frontend/packages/arch/load-remote-worker/ @Tecvan-fe
/frontend/packages/devops/mockset-manage/ @soonco @evan-crash @catee
/frontend/packages/devops/testset-manage/ @mocayo @JxJuly
/frontend/packages/workflow/adapter/base/ @LLLLeeJ @JxJuly @xiamidaxia @luics @zxhfighter @stream-pipe
/frontend/packages/workflow/adapter/code-editor/ @LLLLeeJ @JxJuly @xiamidaxia @luics @zxhfighter @stream-pipe
/frontend/packages/workflow/fabric-canvas/ @xiamidaxia @zxhfighter
/frontend/packages/workflow/feature-encapsulate/ @zxhfighter
/frontend/packages/workflow/nodes/ @xiamidaxia @zxhfighter
/frontend/packages/workflow/setters/ @Tecvan-fe
/frontend/packages/workflow/variable/ @zxhfighter @LLLLeeJ @xiamidaxia
/frontend/packages/workflow/render/ @dragooncjw @xiamidaxia
/frontend/packages/workflow/history/ @xiamidaxia @zxhfighter
/frontend/packages/workflow/adapter/nodes/ @LLLLeeJ @JxJuly @xiamidaxia @luics @zxhfighter @stream-pipe
/frontend/packages/workflow/test-run/ @JxJuly @xiamidaxia @luics @zxhfighter @dragooncjw
/frontend/packages/workflow/test-run-next/main/ @JxJuly @LLLLeeJ @xiamidaxia @zxhfighter
/frontend/packages/workflow/test-run-next/form/ @JxJuly @LLLLeeJ @xiamidaxia @zxhfighter
/frontend/packages/workflow/test-run-next/shared/ @JxJuly @LLLLeeJ @xiamidaxia @zxhfighter
/frontend/packages/workflow/test-run-next/trace/ @JxJuly @LLLLeeJ @xiamidaxia @zxhfighter
/frontend/packages/project-ide/ui-adapter/ @dragooncjw @xiamidaxia
/frontend/packages/studio/workspace/project-publish/ @catee @lihuiwen
/frontend/packages/studio/workspace/entry-adapter/ @duwenhan2byte @evan-crash
/frontend/packages/studio/workspace/entry-base/ @duwenhan2byte @catee @evan-crash
/frontend/packages/workflow/adapter/playground/ @LLLLeeJ @JxJuly @xiamidaxia @luics @zxhfighter @stream-pipe
/frontend/infra/plugins/import-watch-loader/ @Tecvan-fe
/frontend/config/rsbuild-config/ @Tecvan-fe
/frontend/packages/community/explore/ @evan-crash @duwenhan2byte
/frontend/common/_templates/node-core/ @Tecvan-fe
/frontend/common/_templates/rspack-web/ @Tecvan-fe
/backend/ @fanlv @junwen-lee @liuyunchao-1998 @lvxinyu-1117 @hi-pender @luohq-bytedance @shentongmartin @mrh997 @meguminnnnnnnnn @N3kox @zhuangjie1125
/docker/ @fanlv @junwen-lee @liuyunchao-1998 @lvxinyu-1117 @hi-pender @luohq-bytedance @shentongmartin @mrh997 @meguminnnnnnnnn @N3kox @zhuangjie1125
/helm/ @fanlv @junwen-lee @liuyunchao-1998 @lvxinyu-1117 @hi-pender @luohq-bytedance @shentongmartin @mrh997 @meguminnnnnnnnn @N3kox @zhuangjie1125
/idl/ @fanlv @junwen-lee @liuyunchao-1998 @lvxinyu-1117 @hi-pender @luohq-bytedance @shentongmartin @mrh997 @meguminnnnnnnnn @N3kox @zhuangjie1125
+40
View File
@@ -0,0 +1,40 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Version:**
Please provide the version of {project_name} you are using.
**Environment:**
The output of `go env`.
**Additional context**
Add any other context about the problem here.
+24
View File
@@ -0,0 +1,24 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
+44
View File
@@ -0,0 +1,44 @@
#### What type of PR is this?
<!--
Add one of the following kinds:
build: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
ci: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
docs: Documentation only changes
feat: A new feature
optimize: A new optimization
fix: A bug fix
perf: A code change that improves performance
refactor: A code change that neither fixes a bug nor adds a feature
style: Changes that do not affect the meaning of the code (white space, formatting, missing semi-colons, etc)
test: Adding missing tests or correcting existing tests
chore: Changes to the build process or auxiliary tools and libraries such as documentation generation
-->
#### Check the PR title.
<!--
The description of the title will be attached in Release Notes,
so please describe it from user-oriented, what this PR does / why we need it.
Please check your PR title with the below requirements:
-->
- [ ] This PR title match the format: \<type\>(optional scope): \<description\>
- [ ] The description of this PR title is user-oriented and clear enough for others to understand.
- [ ] Add documentation if the current PR requires user awareness at the usage level.
#### (Optional) Translate the PR title into Chinese.
#### (Optional) More detailed description for this PR(en: English/zh: Chinese).
<!--
Provide more detailed info for review(e.g., it's recommended to provide perf data if this is a perf type PR).
-->
en:
zh(optional):
#### (Optional) Which issue(s) this PR fixes:
<!--
Automatically closes linked issue when PR is merged.
Eg: `Fixes #<issue number>`, or `Fixes (paste link of issue)`.
-->
+107
View File
@@ -0,0 +1,107 @@
#!/bin/bash
#
# Copyright 2025 coze-dev Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Set default value
TARGET_BRANCH=${targetBranch}
CI_MODE=${CI:-false}
# Specify the pattern you want to exclude, using *space* as the separator
EXCLUDE_PATTERNS=(
'**/pnpm-lock.yaml'
'packages/arch/bot-api/src/auto-generate/**'
'apps/bot-op/src/services/bam-auto-generate/**'
'apps/prompt-platform/src/services/auto-generate/**'
"**/lib/**"
"**/.*/**"
'**/__tests__/**'
'**/__test__/**'
"**/__mocks__/**"
"**/__mock__/**"
"**/*.test.*/**"
"**/*.spec.*/**"
"**/__snapshots__/**"
"**/*.snap"
'**/e2e/**'
'common/changes/**'
'apps/fornax/**',
"packages/arch/semi-theme-hand01",
"frontend/packages/arch/resources/studio-i18n-resource/src/**"
)
for pattern in "${EXCLUDE_PATTERNS[@]}"; do
EXCLUDE_STRING+=":(exclude)$pattern "
done
if [ "$CI_MODE" = true ]; then
files=$(git diff --name-only --diff-filter=AM "origin/$TARGET_BRANCH..." $EXCLUDE_STRING)
else
files=$(git diff --name-only --diff-filter=AM --cached $EXCLUDE_STRING)
fi
# The volume limit is 512KB.
size_limit=$((512))
large_files_info=""
IFS=$'\n' # Handling the existence of spaces in the file name
for file in $files; do
file_size=$(wc -c <"$file" 2>/dev/null)
if [ $? -ne 0 ]; then
echo "错误: 无法获取文件 '$file' 的大小"
continue
fi
file_size_kb=$((file_size / 1024))
echo "$file file size is $file_size_kb KB"
if [ "$file_size_kb" -gt "$size_limit" ]; then
large_files_info+="- \`$file\` ($file_size_kb KB)\n"
fi
done
unset IFS
output_conclusion() {
local conclusion="$1"
echo "$conclusion" >check-file-size.log
echo "::update-check-run::check-file-size.log"
}
if [ -n "$large_files_info" ]; then
if [ "$CI_MODE" = true ]; then
CONCLUSION="{
\"name\": \"文件体积\",
\"conclusion\": \"failed\",
\"output\": {
\"summary\": \"<h1>错误: 文件体积过大</h1> <br /> 以下文件体积超过限制 (${size_limit}KB): \\n \\n $large_files_info \\n \\n <br /> \"
}
}"
output_conclusion "$CONCLUSION"
else
echo "错误: 以下文件体积超过限制 (${size_limit}KB):"
echo -e "$large_files_info"
exit 1
fi
else
if [ "$CI_MODE" = true ]; then
CONCLUSION="{
\"name\": \"文件体积\",
\"conclusion\": \"success\",
\"output\": {
\"summary\": \"GOOD\"
}
}"
output_conclusion "$CONCLUSION"
fi
fi
+299
View File
@@ -0,0 +1,299 @@
name: CI
on:
pull_request:
branches: ['main']
paths:
- 'github/**'
- 'idl/**'
- 'frontend/**'
- 'common/**'
- 'rush.json'
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
permissions:
contents: read
actions: read
jobs:
setup:
strategy:
matrix:
include:
- NodeVersion: 22.16.0
NodeVersionDisplayName: 22
OS: ubuntu-latest
name: Setup and Install Dependencies
runs-on: ${{ matrix.OS }}
outputs:
cache_file: ${{ steps.process-files.outputs.cache_file }}
matrix_node_version: ${{ matrix.NodeVersion }}
matrix_os: ${{ matrix.OS }}
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 1
- name: Get changed files
id: changed-files
uses: tj-actions/changed-files@v45
- name: Process changed files
id: process-files
run: |
# Get all change files
all_files="${{ steps.changed-files.outputs.all_changed_files }}"
# Filter out files in the common/changes directory
filtered_files=""
for file in $all_files; do
if [[ ! "$file" =~ ^common/changes/.* ]]; then
if [ -z "$filtered_files" ]; then
filtered_files="$file"
else
filtered_files="$filtered_files $file"
fi
fi
done
# Create cached files in JSON format
echo "[$( echo "$filtered_files" | sed 's/ /", "/g' | sed 's/^/"/' | sed 's/$/"/' )]" > changed-files-cache.json
# Output cache file path for subsequent steps
echo "cache_file=changed-files-cache.json" >> $GITHUB_OUTPUT
echo "过滤前文件数量: $(echo $all_files | wc -w)"
echo "过滤后文件数量: $(echo $filtered_files | wc -w)"
echo "已生成缓存文件: changed-files-cache.json"
- name: Config Git User
# should be turn to ci user
run: |
git config --local user.name "flow_bot"
git config --local user.email "flow_bot@bytedance.com"
- uses: actions/setup-node@v3
with:
node-version: ${{ matrix.NodeVersion }}
- name: Upload changed files cache
uses: actions/upload-artifact@v4
with:
name: changed-files-cache
path: changed-files-cache.json
retention-days: 1
build:
needs: setup
runs-on: ${{ needs.setup.outputs.matrix_os }}
name: Increment Build
env:
BUILD_BRANCH: ${{ github.head_ref || github.ref_name }}
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 1
- uses: actions/setup-node@v3
with:
node-version: ${{ needs.setup.outputs.matrix_node_version }}
- name: Cache
uses: actions/cache@v4
with:
path: |
common/temp/pnpm-local
common/temp/pnpm-store
common/temp/install-run
key: ${{ runner.os }}-rush-store-${{ hashFiles('common/config/subspaces/**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-rush-store-main
${{ runner.os }}-rush-store
- name: Download changed files cache
uses: actions/download-artifact@v4
with:
name: changed-files-cache
- name: Install Dependencies
run: |
sudo apt-get update
sudo apt-get install -y libasound2-dev
node common/scripts/install-run-rush.js install --to tag:core
node common/scripts/install-run-rush.js update-autoinstaller --name plugins
node common/scripts/install-run-rush.js increment --action install -p "${{ needs.setup.outputs.cache_file }}"
- name: Increment Build
run: node common/scripts/install-run-rush.js increment --action build -p "${{ needs.setup.outputs.cache_file }}"
test:
needs: setup
runs-on: ${{ needs.setup.outputs.matrix_os }}
name: Increment Test Coverage
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 1
- uses: actions/setup-node@v3
with:
node-version: ${{ needs.setup.outputs.matrix_node_version }}
- name: Cache
uses: actions/cache@v4
with:
path: |
common/temp/pnpm-local
common/temp/pnpm-store
common/temp/install-run
key: ${{ runner.os }}-rush-store-${{ hashFiles('common/config/subspaces/**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-rush-store-main
${{ runner.os }}-rush-store
- name: Download changed files cache
uses: actions/download-artifact@v4
with:
name: changed-files-cache
- name: Install Dependencies
run: |
sudo apt-get update
sudo apt-get install -y libasound2-dev
node common/scripts/install-run-rush.js install --to tag:core
node common/scripts/install-run-rush.js update-autoinstaller --name plugins
node common/scripts/install-run-rush.js increment --action install -p "${{ needs.setup.outputs.cache_file }}"
- name: Increment Test:cov
run: node common/scripts/install-run-rush.js increment --action test:cov -p "${{ needs.setup.outputs.cache_file }}"
# TODO: should resolve later
# - name: Upload coverage reports
# uses: codecov/codecov-action@v4
# with:
# token: ${{ secrets.CODECOV_TOKEN }}
# fail_ci_if_error: true
# verbose: true
lint:
needs: setup
runs-on: ${{ needs.setup.outputs.matrix_os }}
name: Increment Lint
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 1
- uses: actions/setup-node@v3
with:
node-version: ${{ needs.setup.outputs.matrix_node_version }}
- name: Cache
uses: actions/cache@v4
with:
path: |
common/temp/pnpm-local
common/temp/pnpm-store
common/temp/install-run
key: ${{ runner.os }}-rush-store-${{ hashFiles('common/config/subspaces/**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-rush-store-main
${{ runner.os }}-rush-store
- name: Download changed files cache
uses: actions/download-artifact@v4
with:
name: changed-files-cache
- name: Install Dependencies
run: |
sudo apt-get update
sudo apt-get install -y libasound2-dev
node common/scripts/install-run-rush.js install --to tag:core
node common/scripts/install-run-rush.js update-autoinstaller --name plugins
node common/scripts/install-run-rush.js increment --action install -p "${{ needs.setup.outputs.cache_file }}"
- name: Increment Lint
run: node common/scripts/install-run-rush.js increment --action lint -p "${{ needs.setup.outputs.cache_file }}"
ts-check:
needs: setup
runs-on: ${{ needs.setup.outputs.matrix_os }}
name: Increment TS Check
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 1
- uses: actions/setup-node@v3
with:
node-version: ${{ needs.setup.outputs.matrix_node_version }}
- name: Cache
uses: actions/cache@v4
with:
path: |
common/temp/pnpm-local
common/temp/pnpm-store
common/temp/install-run
key: ${{ runner.os }}-rush-store-${{ hashFiles('common/config/subspaces/**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-rush-store-main
${{ runner.os }}-rush-store
- name: Download changed files cache
uses: actions/download-artifact@v4
with:
name: changed-files-cache
- name: Install Dependencies
run: |
sudo apt-get update
sudo apt-get install -y libasound2-dev
node common/scripts/install-run-rush.js install --to tag:core
node common/scripts/install-run-rush.js update-autoinstaller --name plugins
node common/scripts/install-run-rush.js increment --action install -p "${{ needs.setup.outputs.cache_file }}"
- name: Increment TS Check
run: node common/scripts/install-run-rush.js increment --action ts-check -p "${{ needs.setup.outputs.cache_file }}"
package-audit:
needs: setup
runs-on: ${{ needs.setup.outputs.matrix_os }}
name: Increment Package Audit
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 1
- uses: actions/setup-node@v3
with:
node-version: ${{ needs.setup.outputs.matrix_node_version }}
- name: Cache
uses: actions/cache@v4
with:
path: |
common/temp/pnpm-local
common/temp/pnpm-store
common/temp/install-run
key: ${{ runner.os }}-rush-store-${{ hashFiles('common/config/subspaces/**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-rush-store-main
${{ runner.os }}-rush-store
- name: Download changed files cache
uses: actions/download-artifact@v4
with:
name: changed-files-cache
- name: Install Dependencies
run: |
sudo apt-get update
sudo apt-get install -y libasound2-dev
node common/scripts/install-run-rush.js install --to tag:core
node common/scripts/install-run-rush.js update-autoinstaller --name plugins
node common/scripts/install-run-rush.js increment --action install -p "${{ needs.setup.outputs.cache_file }}"
- name: Increment Package Audit
run: node common/scripts/install-run-rush.js increment --action package-audit -p "${{ needs.setup.outputs.cache_file }}"
+125
View File
@@ -0,0 +1,125 @@
name: Backend Tests
on:
pull_request:
paths:
- 'backend/**'
- 'docker/atlas/**'
- '.github/workflows/ci@backend.yml'
push:
branches:
- main
paths:
- 'backend/**'
- 'docker/atlas/**'
- '.github/workflows/ci@backend.yml'
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
env:
DEFAULT_GO_VERSION: "1.24"
jobs:
backend-unit-test:
name: backend-unit-test
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
repository-projects: write
env:
COVERAGE_FILE: coverage.out
BREAKDOWN_FILE: main.breakdown
steps:
- uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: ${{ env.DEFAULT_GO_VERSION }}
# - name: Shutdown Ubuntu MySQL
# run: service mysql stop
- name: Set Up MySQL
uses: mirromutth/mysql-action@v1.1
with:
host port: 3306
container port: 3306
character set server: 'utf8mb4'
collation server: 'utf8mb4_general_ci'
mysql version: '8.4.5'
mysql database: 'opencoze'
mysql root password: 'root'
- name: Verify MySQL Startup
run: |
echo "Waiting for MySQL to be ready..."
for i in {1..60}; do
if cat /proc/net/tcp | grep 0CEA; then
echo "MySQL port 3306 is listening!"
break
fi
echo "Waiting for MySQL port... ($i/60)"
sleep 1
done
echo "Final verification: MySQL port 3306 is accessible"
- name: Install MySQL Client
run: sudo apt-get update && sudo apt-get install -y mysql-client
- name: Initialize Database
uses: nick-fields/retry@v3
with:
timeout_minutes: 10
max_attempts: 20
command: mysql -h 127.0.0.1 -P 3306 -u root -proot opencoze < docker/volumes/mysql/schema.sql
- name: Run Go Test
run: |
modules=`find . -name "go.mod" -exec dirname {} \;`
echo $modules
list=""
coverpkg=""
if [[ ! -f "go.work" ]];then go work init;fi
for module in $modules; do go work use $module; list=$module"/... "$list; coverpkg=$module"/...,"$coverpkg; done
go work sync
go test -race -v -coverprofile=${{ env.COVERAGE_FILE }} -gcflags="all=-l -N" -coverpkg=$coverpkg $list
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v5
with:
name: coze-studio-backend
env_vars: GOLANG,Coze-Studio,BACKEND
fail_ci_if_error: 'false'
files: ${{ env.COVERAGE_FILE }}
token: ${{ secrets.CODECOV_TOKEN }}
- name: Shutdown MySQL
if: always()
continue-on-error: true
run: docker rm -f $(docker ps -q --filter "ancestor=mysql:8.4.5")
benchmark-test:
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
repository-projects: write
steps:
- uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: ${{ env.DEFAULT_GO_VERSION }}
- name: Run Go Benchmark
run: |
modules=`find . -name "go.mod" -exec dirname {} \;`
echo $modules
list=""
coverpkg=""
if [[ ! -f "go.work" ]];then go work init;fi
for module in $modules; do go work use $module; list=$module"/... "$list; coverpkg=$module"/...,"$coverpkg; done
go work sync
go test -race -v -bench=. -benchmem -run=none -gcflags="all=-l -N" $list
+76
View File
@@ -0,0 +1,76 @@
# should be optimize as increment build & test
name: CI@main
on:
push:
# test only
branches: ['main',"chore/setup-ci"]
paths:
- 'github/**'
- 'idl/**'
- 'frontend/**'
- 'common/**'
- 'rush.json'
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
permissions:
contents: read
jobs:
build:
strategy:
matrix:
include:
- NodeVersion: 22.16.0
NodeVersionDisplayName: 22
OS: ubuntu-latest
name: Node.js v${{ matrix.NodeVersionDisplayName }} (${{ matrix.OS }})
runs-on: ${{ matrix.OS }}
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 1
- name: Config Git User
# should be turn to ci user
run: |
git config --local user.name "flow_bot"
git config --local user.email "flow_bot@bytedance.com"
- uses: actions/setup-node@v3
with:
node-version: ${{ matrix.NodeVersion }}
- name: Cache
uses: actions/cache@v4
with:
path: |
common/temp/pnpm-local
common/temp/pnpm-store
common/temp/install-run
key: ${{ runner.os }}-rush-store-main
restore-keys: |
${{ runner.os }}-rush-store-main
${{ runner.os }}-rush-store
- name: Install Dependencies
run: |
sudo apt-get update
sudo apt-get install -y libasound2-dev
node common/scripts/install-run-rush.js install
- name: Build all
run: node common/scripts/install-run-rush.js build --verbose
- name: Test:cov all
run: node common/scripts/install-run-rush.js test:cov --verbose
- name: Upload coverage reports
uses: codecov/codecov-action@v4
with:
token: ${{ secrets.CODECOV_TOKEN }}
fail_ci_if_error: true
verbose: true
- name: Lint all
run: node common/scripts/install-run-rush.js lint --verbose
+48
View File
@@ -0,0 +1,48 @@
name: Claude PR Assistant
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
issues:
types: [opened, assigned]
pull_request_review:
types: [submitted]
jobs:
claude-code-action:
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
(github.event_name == 'issues' && contains(github.event.issue.body, '@claude'))
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
issues: read
id-token: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Run Claude PR Action
uses: anthropics/claude-code-action@beta
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
# Or use OAuth token instead:
# claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
timeout_minutes: '60'
# mode: tag # Default: responds to @claude mentions
# Optional: Restrict network access to specific domains only
# experimental_allowed_domains: |
# .anthropic.com
# .github.com
# api.github.com
# .githubusercontent.com
# bun.sh
# registry.npmjs.org
# .blob.core.windows.net
+48
View File
@@ -0,0 +1,48 @@
name: PR Common Checks
on:
pull_request:
paths:
- 'github/**'
- 'idl/**'
- 'frontend/**'
- 'common/**'
- 'rush.json'
types: [opened, edited, synchronize, reopened]
permissions:
contents: read
jobs:
common-checks:
name: PR Common Checks
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 1
- name: Config Git User
run: |
git config --local user.name "flow_bot"
git config --local user.email "flow_bot@bytedance.com"
- uses: actions/setup-node@v3
with:
node-version: 22.16.0
- name: Install Dependencies
run: node common/scripts/install-run-rush.js install
# PR Title Format Check
- name: Check PR Title Format
if: ${{ !contains(github.event.pull_request.title, 'WIP') && !contains(github.event.pull_request.title, 'wip') }}
env:
PR_TITLE: ${{ github.event.pull_request.title }}
run: |
node common/scripts/install-run-rush.js update-autoinstaller --name rush-commitlint && \
pushd common/autoinstallers/rush-commitlint && \
echo "$PR_TITLE" | npx commitlint --config commitlint.config.js && \
popd
# Add more common checks here
# For example: file size checks, specific file format validations, etc.
+70
View File
@@ -0,0 +1,70 @@
name: Thrift Syntax Validation
on:
push:
branches: ['main']
paths:
- 'idl/**'
- '.github/workflows/idl.yaml'
pull_request:
branches: ['main']
paths:
- 'idl/**'
- '.github/workflows/idl.yaml'
permissions:
contents: read
jobs:
validate-thrift:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: '1.21'
- name: Install kitex tools
run: |
go install github.com/cloudwego/thriftgo@v0.4.1
go install github.com/cloudwego/kitex/tool/cmd/kitex@v0.13.1
go install github.com/cloudwego/thrift-gen-validator@v0.2.6
- name: Validate Thrift Files via kitex
run: |
# Initialize error flag
ERROR_FOUND=0
# Create temporary working directory
TEMP_DIR=$(mktemp -d)
echo "Created temporary working directory: $TEMP_DIR"
# Initialize go mod in temp directory
cd "$TEMP_DIR"
go mod init dummy
# Find all thrift files and validate them
while IFS= read -r -d '' thrift_file; do
echo "Validating $thrift_file..."
if ! kitex -streamx -thrift ignore_initialisms=false -module=dummy "$thrift_file" 2>&1; then
echo "IDL gen code error in file: $thrift_file"
ERROR_FOUND=1
fi
done < <(find "$GITHUB_WORKSPACE/idl" -name '*.thrift' -print0)
# Clean up temporary directory
cd "$GITHUB_WORKSPACE"
rm -rf "$TEMP_DIR"
echo "Cleaned up temporary working directory"
# Exit with appropriate status
if [ $ERROR_FOUND -eq 1 ]; then
echo "Thrift validation failed. Please check the errors above."
exit 1
else
echo "All Thrift files validated successfully!"
exit 0
fi
+38
View File
@@ -0,0 +1,38 @@
name: License Check
on:
push:
branches: ['main']
pull_request:
workflow_dispatch:
permissions:
contents: read
jobs:
license-check:
name: License Check
runs-on: ubuntu-latest
steps:
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: 1.23
- name: Install license-eye
run: |
go install github.com/apache/skywalking-eyes/cmd/license-eye@v0.4.0
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 1
- name: License Header Check
run: |
license-eye header check -c .github/.licenserc.yaml
- name: License Dependency Check
run: |
license-eye dependency check -c .github/.licenserc.yaml
@@ -0,0 +1,74 @@
name: Semantic Pull Request
on:
pull_request:
types:
- opened
- reopened
- edited
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event.number }}
cancel-in-progress: true
permissions:
pull-requests: read
jobs:
main:
name: Check Pull Request Title
runs-on: ubuntu-latest
steps:
- uses: amannn/action-semantic-pull-request@v5.5.2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
# see https://github.com/angular/angular/blob/22b96b9/CONTRIBUTING.md#type
types: |
build
ci
docs
feat
fix
perf
refactor
style
test
chore
# idl: idl
# infra:
# - go version update, lint, database, etc
# - rush update, {eslint,ts,vitest}-config, prettier etc
# frontend
# backend
# workflow: gh workflow
# prompt, evaluation, trace, model, dataset, foundation
scopes: |
idl
frontend
backend
infra
app
singleagent
memory
search
workflow
prompt
knowledge
plugin
middleware
model
database
foundation
comment
ci
# The pull request's title should be fulfilled the following pattern:
#
# [<type>][<optional scope>] <description>
#
# ... where valid types and scopes can be found above; for example:
#
# [fix][test] flaky test V1_ProxyAuthenticationTest.anonymousSocketTest
# headerPattern: '^\[(\w*?)\](?:\[(.*?)\])?(?:\s*)(.*)$'
headerPatternCorrespondence: type, scope, subject
+62
View File
@@ -0,0 +1,62 @@
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
.env
.env.debug
.env.oceanbase
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
# Go workspace file
go.work
go.work.sum
# the result of the go build
backend/**/output*
output/*
# Files generated by IDEs
.idea/
*.iml
# Vim swap files
*.swp
# Vscode files
.vscode/settings.json
.vscode/launch.json
/patches
/oldimpl
.DS_Store
bin/*
docker/data/*
backend/static
node_modules
common/temp
.rush
.eslintcache
backend/conf/model/*.yaml
values-dev.yaml
**/conf/model_ark_doubao-seed-1.6.yaml
*.tsbuildinfo
.trae/*
+11
View File
@@ -0,0 +1,11 @@
{
"mcpServers": {
"github": {
"type": "http",
"url": "https://api.githubcopilot.com/mcp/",
"headers": {
"Authorization": "Bearer ${GITHUB_PAT}"
}
}
}
}
+1
View File
@@ -0,0 +1 @@
lts/iron
+4
View File
@@ -0,0 +1,4 @@
// Do not modify this file
module.exports = {
...require('./frontend/config/eslint-config/.prettierrc.js'),
};
+15
View File
@@ -0,0 +1,15 @@
{
"recommendations": [
"editorconfig.editorconfig",
"esbenp.prettier-vscode",
"streetsidesoftware.code-spell-checker",
"codezombiech.gitignore",
"aaron-bond.better-comments",
"mikestead.dotenv",
"stylelint.vscode-stylelint"
],
"unwantedRecommendations": [
"nucllear.vscode-extension-auto-import",
"steoates.autoimport"
]
}
+198
View File
@@ -0,0 +1,198 @@
{
"eslint.nodePath": "frontend/config/eslint-config/node_modules/eslint",
"prettier.prettierPath": "frontend/config/eslint-config/node_modules/prettier",
"editor.tabSize": 2,
"editor.insertSpaces": true,
"editor.formatOnSave": true,
"editor.formatOnType": false,
"editor.formatOnPaste": false,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll": "never",
"source.fixAll.eslint": "never",
"source.removeUnused": "never",
"source.organizeImports": "never"
// "source.sortImports": "always"
},
"editor.formatOnSaveMode": "modificationsIfAvailable",
"search.followSymlinks": false,
"search.exclude": {
"**/node_modules": true,
"**/.nyc_output": true,
"**/.rush": true,
"**/pnpm-lock.yaml": true,
"**/CHANGELOG.json": true,
"**/CHANGELOG.md": true,
"common/changes": true,
"**/output": true,
"**/lib": true,
"**/rush-logs": true,
"**/dist": true,
"**/coverage": true,
"common/temp": true
},
"eslint.workingDirectories": [
{
"mode": "auto"
}
],
"files.defaultLanguage": "plaintext",
"files.associations": {
".code-workspace": "jsonc",
".babelrc": "json",
".eslintrc": "jsonc",
".eslintrc*.json": "jsonc",
".stylelintrc": "javascript",
"stylelintrc": "jsonc",
"*.json": "jsonc",
"package.json": "json",
".htmlhintrc": "jsonc",
"htmlhintrc": "jsonc",
"Procfile*": "shellscript",
"README": "markdown",
"**/coverage/**/*.*": "plaintext",
"OWNERS": "yaml",
// Set the pnpm-lock file to plaintext to avoid parsing; otherwise, VSCode may freeze when opening the file
"**/pnpm-lock.yaml": "plaintext",
"**/dist/**": "plaintext",
"**/dist_*/**": "plaintext",
"*.map": "plaintext",
"*.log": "plaintext"
},
"files.exclude": {
"**/.git": true,
"**/.svn": true,
"**/.hg": true,
"**/CVS": true,
"**/.DS_Store": true,
"**/Thumbs.db": true,
"**/.rush": true,
"**/.swc": true,
"**/rush-logs": true
},
"files.watcherExclude": {
"**/.git/objects/**": true,
"**/.git/subtree-cache/**": true,
"**/node_modules/*/**": true
},
"search.useIgnoreFiles": true,
//
"editor.rulers": [80, 120],
"files.eol": "\n",
"files.trimTrailingWhitespace": true,
"files.insertFinalNewline": true,
"cSpell.diagnosticLevel": "Warning",
"eslint.probe": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact"
],
"editor.semanticHighlighting.enabled": false,
"eslint.format.enable": false,
"eslint.enable": true,
"eslint.useFlatConfig": true,
"eslint.codeActionsOnSave.mode": "problems",
"eslint.lintTask.enable": false,
"javascript.validate.enable": false,
"typescript.tsdk": "frontend/config/ts-config/node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true,
"typescript.disableAutomaticTypeAcquisition": true,
"typescript.format.enable": false,
"typescript.referencesCodeLens.enabled": false,
"typescript.preferGoToSourceDefinition": true,
"typescript.updateImportsOnFileMove.enabled": "never",
// tsserver log 不会自动删除,日积月累,导致磁盘空间不足,因此默认关闭
"typescript.tsserver.log": "off",
// "typescript.tsserver.useSeparateSyntaxServer": true,
"typescript.tsserver.forceConsistentCasingInFileNames": true,
"typescript.workspaceSymbols.excludeLibrarySymbols": true,
"editor.minimap.enabled": true,
"typescript.preferences.includePackageJsonAutoImports": "off",
"typescript.suggest.autoImports": true,
"typescript.tsserver.maxTsServerMemory": 16384,
"typescript.tsserver.enableRegionDiagnostics": false,
"typescript.tsserver.experimental.enableProjectDiagnostics": true,
"typescript.tsserver.watchOptions": {
"fallbackPolling": "dynamicPriorityPolling",
"synchronousWatchDirectory": false,
"watchDirectory": "useFsEvents",
"watchFile": "useFsEventsOnParentDirectory",
"excludeDirectories": [
"/**/node_modules",
"/**/dist",
"/**/lib",
"/**/coverage",
"**/temp"
],
"excludeLibrarySymbols": true,
"excludeFiles": [
"/**/node_modules/**",
"/**/dist/**",
"/**/lib/**",
"/**/coverage/**",
"**/temp/**"
]
},
"css.validate": false,
"scss.validate": false,
"less.validate": false,
"stylelint.enable": true,
"stylelint.validate": ["css", "scss", "less"],
"stylelint.stylelintPath": "frontend/config/stylelint-config/node_modules/stylelint",
"emmet.triggerExpansionOnTab": true,
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[yaml]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[css]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[html]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[less]": {
"editor.defaultFormatter": "stylelint.vscode-stylelint"
},
"[scss]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[ignore]": {
"editor.defaultFormatter": "foxundermoon.shell-format"
},
"[shellscript]": {
"editor.defaultFormatter": "foxundermoon.shell-format"
},
"[dotenv]": {
"editor.defaultFormatter": "foxundermoon.shell-format"
},
"[svg]": {
"editor.defaultFormatter": "jock.svg"
},
"svg.preview.background": "white",
"[xml]": {
"editor.defaultFormatter": "mblode.pretty-formatter"
},
"[sql]": {
"editor.defaultFormatter": "adpyke.vscode-sql-formatter"
},
"git.openRepositoryInParentFolders": "always",
"references.preferredLocation": "view"
}
+48
View File
@@ -0,0 +1,48 @@
# Below is a list of people and organizations that have contributed
# to the Coze Studio project. Names should be added to the list like so:
#
# Name/Organization <email address>
#
# Anyone who has contributed to the Coze Studio project in any way (not
# limited to submitting PRs) is welcome to submit a PR to add their
# name to this file.
#
# Thanks to everyone for your contributions!
ByteDance Ltd. and/or its Affiliates
luohuaqing.2018 <luohuaqing.2018@bytedance.com>
lipandeng <lipandeng@bytedance.com>
fanlv <fanlv@bytedance.com>
lijunwen.gigoo <lijunwen.gigoo@bytedance.com>
shentong.martin <shentong.martin@bytedance.com>
maronghong <maronghong@bytedance.com>
xuzhaonan <xuzhaonan@bytedance.com>
zhuangjie <zhuangjie.1125@bytedance.com>
liuyunchao <liuyunchao.0510@bytedance.com>
liujian.0502 <liujian.0502@bytedance.com>
wangdezheng <wangdezheng@bytedance.com>
liyubei <liyubei@bytedance.com>
xukai.luics <xukai.luics@bytedance.com>
sunzhiyuan.evan <sunzhiyuan.evan@bytedance.com>
yangyu.1 <yangyu.1@bytedance.com>
haozhenfei <haozhenfei@bytedance.com>
zengxiaohui <zengxiaohui@bytedance.com>
gaoyuanhan.duty <gaoyuanhan.duty@bytedance.com>
duwenhan <duwenhan@bytedance.com>
gaoding.devingao <gaoding.devingao@bytedance.com>
chenjiawei.inizio <chenjiawei.inizio@bytedance.com>
wencheng.lwc <wencheng.lwc@bytedance.com>
fanwenjie.fe <fanwenjie.fe@bytedance.com>
lihuiwen.123 <lihuiwen.123@bytedance.com>
liji.leej <liji.leej@bytedance.com>
fengzilong <fengzilong@bytedance.com>
shanrenkai <shanrenkai@bytedance.com>
sunkuo <sunkuo@bytedance.com>
fanchen <fanchen@bytedance.com>
lingyibin.jason <lingyibin.jason@bytedance.com>
chenchen.dabaishu <chenchen.dabaishu@bytedance.com>
jiangxujin <jiangxujin@bytedance.com>
huyongbiao <huyongbiao@bytedance.com>
wenming.2020 <wenming.2020@bytedance.com>
tanjizhen <tanjizhen@bytedance.com>
+196
View File
@@ -0,0 +1,196 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
Coze Studio is an all-in-one AI agent development platform with both frontend (React + TypeScript) and backend (Go) components. The project uses a sophisticated monorepo architecture managed by Rush.js with 135+ frontend packages organized in a hierarchical dependency system.
## Development Commands
### Environment Setup
```bash
# Clone and setup
git clone https://github.com/coze-dev/coze-studio.git
cd coze-studio
# Install frontend dependencies
rush update
# For Docker-based development
cd docker
cp .env.example .env
# Configure model settings in backend/conf/model/
docker compose up -d
# Access at http://localhost:8888
```
### Development Workflow
```bash
# Start middleware services (MySQL, Redis, Elasticsearch, etc.)
make middleware
# Start Go backend in development mode
make server
# Start frontend development server
cd frontend/apps/coze-studio
npm run dev
# Full development environment
make debug
```
### Build Commands
```bash
# Build frontend only
make fe
# Build Go server
make build_server
# Build everything with Docker
make web
# Rush monorepo commands
rush build # Build all packages
rush rebuild -o @coze-studio/app # Build specific package
rush test # Run all tests
rush lint # Lint all packages
```
### Testing
```bash
# Run tests (Vitest-based)
rush test
npm run test # In specific package
npm run test:cov # With coverage
# Backend tests
cd backend && go test ./...
```
## Architecture Overview
### Frontend Architecture
- **Monorepo**: Rush.js with 135+ packages across 4 dependency levels
- **Build System**: Rsbuild (Rspack-based) for fast builds
- **UI Framework**: React 18 + TypeScript + Semi Design + Tailwind CSS
- **State Management**: Zustand for global state
- **Package Organization**:
- `arch/`: Core infrastructure (level-1)
- `common/`: Shared components and utilities (level-2)
- `agent-ide/`, `workflow/`, `studio/`: Feature domains (level-3)
- `apps/coze-studio`: Main application (level-4)
### Backend Architecture (Go)
- **Framework**: Hertz HTTP framework
- **Architecture**: Domain-Driven Design (DDD) with microservices
- **Structure**:
- `domain/`: Business logic and entities
- `application/`: Application services and use cases
- `api/`: HTTP handlers and routing
- `infra/`: Infrastructure implementations
- `crossdomain/`: Cross-cutting concerns
### Key Architectural Patterns
- **Adapter Pattern**: Extensive use for loose coupling between layers
- **Interface Segregation**: Clear contracts between domains
- **Event-Driven**: NSQ message queue for async communication
- **API-First**: Comprehensive OpenAPI specifications
## Database & Infrastructure
### Docker Services Stack
- **Database**: MySQL 8.4.5
- **Cache**: Redis 8.0
- **Search**: Elasticsearch 8.18.0 with SmartCN analyzer
- **Vector DB**: Milvus v2.5.10 for embeddings
- **Storage**: MinIO for object storage
- **Message Queue**: NSQ (nsqlookupd, nsqd, nsqadmin)
- **Configuration**: etcd 3.5
### Database Management
```bash
# Sync database schema
make sync_db
# Dump database schema
make dump_db
# Initialize SQL data
make sql_init
# Atlas migration management
make atlas-hash
```
## Key Development Patterns
### Frontend Package Development
- Each package follows consistent structure with `README.md`, `package.json`, `tsconfig.json`, `eslint.config.js`
- Adapter pattern extensively used for decoupling (e.g., `-adapter` suffix packages)
- Base/Core pattern for shared functionality (e.g., `-base` suffix packages)
- Use workspace references (`workspace:*`) for internal dependencies
### Backend Development
- Follow DDD principles with clear domain boundaries
- Use dependency injection via interfaces
- Implement proper error handling with custom error types
- Write comprehensive tests for domain logic
### Model Configuration
Before deployment, configure AI models in `backend/conf/model/`:
1. Copy template from `backend/conf/model/template/`
2. Set `id`, `meta.conn_config.api_key`, and `meta.conn_config.model`
3. Supported providers: OpenAI, Volcengine Ark, Claude, Gemini, Qwen, DeepSeek, Ollama
## Testing Strategy
### Coverage Requirements by Package Level
- **Level 1**: 80% coverage, 90% increment
- **Level 2**: 30% coverage, 60% increment
- **Level 3-4**: 0% coverage (flexible)
### Testing Framework
- **Frontend**: Vitest for unit/integration tests
- **Backend**: Go's built-in testing framework
- **E2E**: Separate e2e subspace configuration
## Common Issues & Solutions
### Frontend Development
- Use `rush update` instead of `npm install` at root level
- Build packages in dependency order using `rush build`
- For hot reload issues, check Rsbuild configuration in specific package
### Backend Development
- Ensure middleware services are running (`make middleware`)
- Check database connectivity and schema sync
- Verify model configurations are properly set
### Docker Issues
- Ensure sufficient resources (minimum 2 Core, 4GB RAM)
- Check port conflicts (8888 for frontend, various for services)
- Use `make clean` to reset Docker volumes if needed
## IDL and Code Generation
The project uses Interface Definition Language (IDL) for API contract management:
- IDL files in `idl/` directory (Thrift format)
- Frontend code generation via `@coze-arch/idl2ts-*` packages
- Backend uses generated Go structs
## Plugin Development
For custom plugin development:
- Reference templates in `backend/conf/plugin/pluginproduct/`
- Follow OAuth schema in `backend/conf/plugin/common/oauth_schema.json`
- Configure authentication keys for third-party services
## Contributing
- Use conventional commits via `rush commit`
- Run linting with `rush lint-staged` (pre-commit hook)
- Ensure tests pass before submitting PRs
- Follow team-based package organization and tagging conventions
+128
View File
@@ -0,0 +1,128 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
conduct@cloudwego.io.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.
+51
View File
@@ -0,0 +1,51 @@
# How to Contribute
## Your First Pull Request
We use GitHub for our codebase. You can start by reading [How To Pull Request](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-requests).
## Branch Organization
We use [git-flow](https://nvie.com/posts/a-successful-git-branching-model/) as our branch organization, as known as [FDD](https://en.wikipedia.org/wiki/Feature-driven_development)
## Bugs
### 1. How to Find Known Issues
We are using [Github Issues](https://github.com/coze-dev/{project_name}/issues) for our public bugs. We keep a close eye on this and try to make it clear when we have an internal fix in progress. Before filing a new task, try to make sure your problem doesnt already exist.
### 2. Reporting New Issues
Providing a reduced test code is a recommended way for reporting issues. Then can place in:
- Just in issues
- [Golang Playground](https://play.golang.org/)
### 3. Security Bugs
Please do not report the safe disclosure of bugs to public issues. Contact us by [Support Email](mailto:opensource-studio@coze.cn)
## How to Get in Touch
- [Email](mailto:opensource-studio@coze.cn)
## Submit a Pull Request
Before you submit your Pull Request (PR) consider the following guidelines:
1. Search [GitHub](https://github.com/coze-dev/{project_name}/pulls) for an open or closed PR that relates to your submission. You don't want to duplicate existing efforts.
2. Be sure that an issue describes the problem you're fixing, or documents the design for the feature you'd like to add. Discussing the design upfront helps to ensure that we're ready to accept your work.
3. [Fork](https://docs.github.com/en/github/getting-started-with-github/fork-a-repo) the coze-dev {project_name} repo.
4. In your forked repository, make your changes in a new git branch:
```
git checkout -b my-fix-branch main
```
5. Create your patch, including appropriate test cases.
6. Follow our [Style Guides](#code-style-guides).
7. Commit your changes using a descriptive commit message that follows [AngularJS Git Commit Message Conventions](https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit).
Adherence to these conventions is necessary because release notes are automatically generated from these messages.
8. Push your branch to GitHub:
```
git push origin my-fix-branch
```
9. In GitHub, send a pull request to `{project_name}:main`
## Contribution Prerequisites
- Our development environment keeps up with [Go Official](https://golang.org/project/).
- You need fully checking with lint tools before submit your pull request. [gofmt](https://golang.org/pkg/cmd/gofmt/) and [golangci-lint](https://github.com/golangci/golangci-lint)
- You are familiar with [GitHub](https://github.com)
- Maybe you need familiar with [Actions](https://github.com/features/actions)(our default workflow tool).
## Code Style Guides
- [Effective Go](https://golang.org/doc/effective_go)
- [Go Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments)
+177
View File
@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+157
View File
@@ -0,0 +1,157 @@
.PHONY: debug fe server sync_db dump_db middleware web down clean python help
# 定义脚本路径
SCRIPTS_DIR := ./scripts
BUILD_FE_SCRIPT := $(SCRIPTS_DIR)/build_fe.sh
BUILD_SERVER_SCRIPT := $(SCRIPTS_DIR)/setup/server.sh
SYNC_DB_SCRIPT := $(SCRIPTS_DIR)/setup/db_migrate_apply.sh
DUMP_DB_SCRIPT := $(SCRIPTS_DIR)/setup/db_migrate_dump.sh
SETUP_DOCKER_SCRIPT := $(SCRIPTS_DIR)/setup/docker.sh
SETUP_PYTHON_SCRIPT := $(SCRIPTS_DIR)/setup/python.sh
COMPOSE_FILE := docker/docker-compose-debug.yml
OCEANBASE_COMPOSE_FILE := docker/docker-compose-oceanbase.yml
OCEANBASE_DEBUG_COMPOSE_FILE := docker/docker-compose-oceanbase_debug.yml
MYSQL_SCHEMA := ./docker/volumes/mysql/schema.sql
MYSQL_INIT_SQL := ./docker/volumes/mysql/sql_init.sql
ENV_FILE := ./docker/.env.debug
WEB_ENV_FILE := ./docker/.env
OCEANBASE_ENV_FILE := ./docker/.env.debug
STATIC_DIR := ./bin/resources/static
ES_INDEX_SCHEMA := ./docker/volumes/elasticsearch/es_index_schema
ES_SETUP_SCRIPT := ./docker/volumes/elasticsearch/setup_es.sh
debug: env middleware python server
env:
@if [ ! -f "$(ENV_FILE)" ]; then \
echo "Env file '$(ENV_FILE)' not found, using example env..."; \
cp ./docker/.env.debug.example $(ENV_FILE); \
fi
fe:
@echo "Building frontend..."
@bash $(BUILD_FE_SCRIPT)
server: env
@if [ ! -d "$(STATIC_DIR)" ]; then \
echo "Static directory '$(STATIC_DIR)' not found, building frontend..."; \
$(MAKE) fe; \
fi
@echo "Building and run server..."
@APP_ENV=debug bash $(BUILD_SERVER_SCRIPT) -start
build_server:
@echo "Building server..."
@bash $(BUILD_SERVER_SCRIPT)
sync_db: env
@echo "Syncing database..."
@docker compose -f $(COMPOSE_FILE) --env-file $(ENV_FILE) --profile mysql-setup up -d
dump_db: env dump_sql_schema
@echo "Dumping database..."
@. $(ENV_FILE); \
bash $(DUMP_DB_SCRIPT)
sql_init:
@echo "Init sql data..."
@docker compose -f $(COMPOSE_FILE) --env-file $(ENV_FILE) --profile mysql-setup up -d
middleware:
@echo "Start middleware docker environment for opencoze app"
@docker compose -f $(COMPOSE_FILE) --env-file $(ENV_FILE) --profile middleware up -d --wait
build_docker:
@echo "Build docker image"
@docker compose -f $(COMPOSE_FILE) --profile build-server build
web_env:
@if [ ! -f "$(WEB_ENV_FILE)" ]; then \
echo "Env file '$(WEB_ENV_FILE)' not found, using example env..."; \
cp ./docker/.env.example $(WEB_ENV_FILE); \
fi
web: web_env
@echo "Start web server in docker"
@docker compose -f docker/docker-compose.yml --env-file $(WEB_ENV_FILE) up -d
down_web:
@echo "Stop web server in docker"
@docker compose -f docker/docker-compose.yml --env-file $(WEB_ENV_FILE) down
down: env
@echo "Stop all docker containers"
@docker compose -f $(COMPOSE_FILE) --profile '*' down
clean: down
@echo "Remove docker containers and volumes data"
@rm -rf ./docker/data
python:
@echo "Setting up Python..."
@bash $(SETUP_PYTHON_SCRIPT)
dump_sql_schema:
@echo "Dumping mysql schema to $(MYSQL_SCHEMA)..."
@. $(ENV_FILE); \
{ echo "SET NAMES utf8mb4;\nCREATE DATABASE IF NOT EXISTS opencoze COLLATE utf8mb4_unicode_ci;"; atlas schema inspect -u $$ATLAS_URL --format "{{ sql . }}" --exclude "atlas_schema_revisions,table_*" | sed 's/CREATE TABLE/CREATE TABLE IF NOT EXISTS/g'; } > $(MYSQL_SCHEMA)
@sed -i.bak -E 's/(\))[[:space:]]+CHARSET utf8mb4/\1 ENGINE=InnoDB CHARSET utf8mb4/' $(MYSQL_SCHEMA) && rm -f $(MYSQL_SCHEMA).bak
@sed -i.bak "s/\"/'/g" $(MYSQL_SCHEMA) && rm -f $(MYSQL_SCHEMA).bak
@cat $(MYSQL_INIT_SQL) >> $(MYSQL_SCHEMA)
@echo "Dumping mysql schema to helm/charts/opencoze/files/mysql ..."
@cp $(MYSQL_SCHEMA) ./helm/charts/opencoze/files/mysql/
atlas-hash:
@echo "Rehash atlas migration files..."
@(cd ./docker/atlas && atlas migrate hash)
setup_es_index:
@echo "Setting up Elasticsearch index..."
@. $(ENV_FILE); \
bash $(ES_SETUP_SCRIPT) --index-dir $(ES_INDEX_SCHEMA) --docker-host false --es-address "$$ES_ADDR"
oceanbase_env:
@bash scripts/setup/oceanbase_env.sh debug
oceanbase_debug: oceanbase_env oceanbase_middleware_debug python oceanbase_server_debug
oceanbase_middleware_debug:
@echo "Starting OceanBase debug middleware..."
@docker compose -f $(OCEANBASE_DEBUG_COMPOSE_FILE) --env-file $(ENV_FILE) --profile middleware up -d --wait
oceanbase_server_debug:
@if [ ! -d "$(STATIC_DIR)" ]; then \
echo "Static directory '$(STATIC_DIR)' not found, building frontend..."; \
$(MAKE) fe; \
fi
@echo "Building and run OceanBase debug server..."
@APP_ENV=debug bash $(BUILD_SERVER_SCRIPT) -start
help:
@echo "Usage: make [target]"
@echo ""
@echo "Targets:"
@echo " debug - Start the debug environment."
@echo " env - Setup env file."
@echo " fe - Build the frontend."
@echo " server - Build and run the server binary."
@echo " build_server - Build the server binary."
@echo " sync_db - Sync opencoze_latest_schema.hcl to the database."
@echo " dump_db - Dump the database to opencoze_latest_schema.hcl and migrations files."
@echo " sql_init - Init sql data..."
@echo " dump_sql_schema - Dump the database schema to sql file."
@echo " middleware - Setup middlewares docker environment, but exclude the server app."
@echo " web - Setup web docker environment, include middlewares docker."
@echo " down - Stop the docker containers."
@echo " down_web - Stop the web docker containers."
@echo " clean - Stop the docker containers and clean volumes."
@echo " python - Setup python environment."
@echo " atlas-hash - Rehash atlas migration files."
@echo " setup_es_index - Setup elasticsearch index."
@echo ""
@echo "OceanBase Commands:"
@echo " oceanbase_env - Setup OceanBase environment file (like 'env')."
@echo " oceanbase_debug - Start OceanBase debug environment (like 'debug')."
@echo ""
@echo " help - Show this help message."
+132
View File
@@ -0,0 +1,132 @@
![Image](https://p9-arcosite.byteimg.com/tos-cn-i-goo7wpa0wc/943f576df3424fa98580c2ad18946719~tplv-goo7wpa0wc-image.image)
<div align="center"><p>
<a href="#what-is-coze-studio">Coze Studio</a> •
<a href="#feature-list">Feature list</a> •
<a href="#quickstart">Quickstart</a> •
<a href="#developer-guide">Developer Guide</a>
</p>
<p>
<img alt="License" src="https://img.shields.io/badge/license-apache2.0-blue.svg">
<img alt="Go Version" src="https://img.shields.io/badge/go-%3E%3D%201.23.4-blue">
</p>
English | [中文](README.zh_CN.md)
</div>
## What is Coze Studio?
[Coze Studio](https://www.coze.cn/home) is an all-in-one AI agent development tool. Providing the latest large models and tools, various development modes and frameworks, Coze Studio offers the most convenient AI agent development environment, from development to deployment.
* **Provides all core technologies needed for AI agent development**: prompt, RAG, plugin, workflow, enabling developers to focus on creating the core value of AI.
* **Ready to use for professional AI agent development at the lowest cost**: Coze Studio provides developers with complete app templates and build frameworks, allowing you to quickly construct various AI agents and turn creative ideas into reality.
Coze Studio, derived from the "Coze Development Platform" which has served tens of thousands of enterprises and millions of developers, we have made its core engine completely open. It is a one-stop visual development tool for AI Agents that makes creating, debugging, and deploying AI Agents unprecedentedly simple. Through Coze Studio's visual design and build tools, developers can quickly create and debug agents, apps, and workflows using no-code or low-code approaches, enabling powerful AI app development and more customized business logic. It's an ideal choice for building low-code AI products tailored . Coze Studio aims to lower the threshold for AI agent development and application, encouraging community co-construction and sharing for deeper exploration and practice in the AI field.
The backend of Coze Studio is developed using Golang, the frontend uses React + TypeScript, and the overall architecture is based on microservices and built following domain-driven design (DDD) principles. Provide developers with a high-performance, highly scalable, and easy-to-customize underlying framework to help them address complex business needs.
## Feature list
| **Module** | **Feature** |
| --- | --- |
| Model service | Manage the model list, integrate services such as OpenAI and Volcengine |
| Build agent | * Build, publish, and manage agent <br> * Support configuring workflows, knowledge bases, and other resources |
| Build apps | * Create and publish apps <br> * Build business logic through workflows |
| Build a workflow | Create, modify, publish, and delete workflows |
| Develop resources | Support creating and managing the following resources: <br> * Plugins <br> * Knowledge bases <br> * Databases <br> * Prompts |
| API and SDK | * Create conversations, initiate chats, and other OpenAPI <br> * Integrate agents or apps into your own app through Chat SDK |
## Quickstart
Learn how to obtain and deploy the open-source version of Coze Studio, quickly build projects, and experience Coze Studio's open-source version.
Environment requirements:
* Before installing Coze Studio, please ensure that your machine meets the following minimum system requirements: 2 Core、4 GB
* Pre-install Docker and Docker Compose, and start the Docker service.
Deployment steps:
1. Retrieve the source code.
```Bash
# Clone code
git clone https://github.com/coze-dev/coze-studio.git
```
2. Deploy and start the service. When deploying and starting Coze Studio for the first time, it may take a while to retrieve images and build local images. Please be patient. If you see the message "Container coze-server Started," it means the Coze Studio service has started successfully.
```Bash
cd coze-studio
# start service
# for macOS or Linux
make web
# for windows
cp ./docker/.env.example ./docker/.env
docker compose -f ./docker/docker-compose.yml up
```
For common startup failure issues, **please refer to the [FAQ](https://github.com/coze-dev/coze-studio/wiki/9.-FAQ)**.
3. Register an account by visiting `http://localhost:8888/sign`, entering your username and password, and clicking the Register button.
4. Configure the model at `http://localhost:8888/admin/#model-management` by adding a new model. (The image version must be greater than or equal to 0.5.0.)
5. Visit Coze Studio at `http://localhost:8888/`.
> [!WARNING]
> If you want to deploy Coze Studio in a public network environment, it is recommended to assess security risks before you begin, and take corresponding protection measures. Possible security risks include account registration functions, Python execution environments in workflow code nodes, Coze Server listening address configurations, SSRF (Server - Side Request Forgery), and some horizontal privilege escalations in APIs. For more details, refer to [Quickstart](https://github.com/coze-dev/coze-studio/wiki/2.-Quickstart#security-risks-in-public-networks).
## Developer Guide
* **Project Configuration**:
* [Model Configuration](https://github.com/coze-dev/coze-studio/wiki/3.-Model-configuration): Before deploying the open-source version of Coze Studio, you must configure the model service. Otherwise, you cannot select models when building agents, workflows, and apps.
* [Plugin Configuration](https://github.com/coze-dev/coze-studio/wiki/4.-Plugin-Configuration): To use official plugins from the plugin store, you must first configure the plugins and add the authentication keys for third-party services.
* [Basic Component Configuration](https://github.com/coze-dev/coze-studio/wiki/5.-Basic-component-configuration): Learn how to configure components such as image uploaders to use functions like image uploading in Coze Studio .
* [API Reference](https://github.com/coze-dev/coze-studio/wiki/6.-API-Reference): The Coze Studio Community Edition API and Chat SDK are authenticated using Personal Access Token, providing APIs for conversations and workflows.
* [Development Guidelines](https://github.com/coze-dev/coze-studio/wiki/7.-Development-Standards):
* [Project Architecture](https://github.com/coze-dev/coze-studio/wiki/7.-Development-Standards#project-architecture): Learn about the technical architecture and core components of the open-source version of Coze Studio.
* [Code Development and Testing](https://github.com/coze-dev/coze-studio/wiki/7.-Development-Standards#code-development-and-testing): Learn how to perform secondary development and testing based on the open-source version of Coze Studio.
* [Troubleshooting](https://github.com/coze-dev/coze-studio/wiki/7.-Development-Standards#troubleshooting): Learn how to view container states and system logs.
## Using the open-source version of Coze Studio
> Regarding how to use Coze Studio, refer to the [Coze Development Platform Official Documentation Center](https://www.coze.cn/open/docs) for more information. Please note that certain features, such as tone customization, are limited to the commercial version. Differences between the open-source and commercial versions can be found in the **Feature List**.
* [Quick Start](https://www.coze.cn/open/docs/guides/quickstart): Quickly build an AI assistant agent with Coze Studio.
* [Developing Agents](https://www.coze.cn/open/docs/guides/agent_overview): Learn how to create, build, publish, and manage agents. You can use functions such as knowledge, plugins, etc., to resolve model hallucination and lack of expertise in professional fields. In addition, Coze Studio provides rich memory features that enable agents to generate more accurate responses based on a personal user's historical conversations during interactions.
* [Develop workflows](https://www.coze.cn/open/docs/guides/workflow): A workflow is a set of executable instructions used to implement business logic or complete specific tasks. It structures data flow and task processing for apps or agents. Coze Studio provides a visual canvas where you can quickly build workflows by dragging and dropping nodes.
* [Resources such as plugins](https://www.coze.cn/open/docs/guides/plugin): In Coze Studio, workflows, plugins, databases, knowledge bases, and variables are collectively referred to as resources.
* **API & SDK**: Coze Studio supports [API related to chat and workflows](https://github.com/coze-dev/coze-studio/wiki/6.-API-Reference), and you can also integrate agents or apps with local business systems through [Chat SDK](https://www.coze.cn/open/docs/developer_guides/web_sdk_overview).
* [Tutorials for practice](https://www.coze.cn/open/docs/tutorial/chat_sdk_web_online_customer_service): Learn how to use Coze Studio to implement various AI scenarios, such as building web-based online customer service using Chat SDK.
## License
This project uses the Apache 2.0 license. For details, please refer to the [LICENSE](https://github.com/coze-dev/coze-studio/blob/main/LICENSE-APACHE) file.
## Community contributions
We welcome community contributions. For contribution guidelines, please refer to [CONTRIBUTING](https://github.com/coze-dev/coze-studio/blob/main/CONTRIBUTING.md) and [Code of conduct](https://github.com/coze-dev/coze-studio/blob/main/CODE_OF_CONDUCT.md). We look forward to your contributions!
## Security and privacy
If you discover potential security issues in the project, or believe you may have found a security issue, please notify the ByteDance security team through our [security center](https://security.bytedance.com/src) or [vulnerability reporting email](mailto:sec@bytedance.com).
Please **do not** create public GitHub Issues.
## Join Community
We are committed to building an open and friendly developer community. All developers interested in AI Agent development are welcome to join us!
### 🐛 Issue Reports & Feature Requests
To efficiently track and resolve issues while ensuring transparency and collaboration, we recommend participating through:
- **GitHub Issues**: [Submit bug reports or feature requests](https://github.com/coze-dev/coze-studio/issues)
- **Pull Requests**: [Contribute code or documentation improvements](https://github.com/coze-dev/coze-studio/pulls)
### 💬 Technical Discussion & Communication
Join our technical discussion groups to share experiences with other developers and stay updated with the latest project developments:
**Feishu Group Chat**
Scan the QR code below with Feishu mobile app to join:
![Image](https://p9-arcosite.byteimg.com/tos-cn-i-goo7wpa0wc/0a49081e8f3743e8bf3dcdded4bb571a~tplv-goo7wpa0wc-image.image)
**Discord Server**
Click to join: [Coze Community](https://discord.gg/sTVN9EVS4B)
**Telegram Group**
Click to join: Telegram Group [Coze](https://t.me/+pP9CkPnomDA0Mjgx)
## Acknowledgments
Thank you to all the developers and community members who have contributed to the Coze Studio project. Special thanks:
* The [Eino](https://github.com/cloudwego/eino) framework team - providing powerful support for Coze Studio's agent and workflow runtime engines, model abstractions and implementations, and knowledge base indexing and retrieval
* The [FlowGram](https://github.com/bytedance/flowgram.ai) team - providing a high-quality workflow building engine for Coze Studio's frontend workflow canvas editor
* The [Hertz](https://github.com/cloudwego/hertz) team - Go HTTP framework with high-performance and strong-extensibility for building micro-services
* All users who participated in testing and feedback
+7
View File
@@ -0,0 +1,7 @@
# WeHub 来源说明
- 原始项目:`coze-dev/coze-studio`
- 原始仓库:https://github.com/coze-dev/coze-studio
- 导入方式:上游默认分支的最新快照
- 原作者、版权和许可证信息以原始仓库及本仓库 LICENSE 为准
- 本文件仅用于记录来源,不代表 WeHub 是原项目作者
+134
View File
@@ -0,0 +1,134 @@
![Image](https://p9-arcosite.byteimg.com/tos-cn-i-goo7wpa0wc/943f576df3424fa98580c2ad18946719~tplv-goo7wpa0wc-image.image)
<div align="center">
<p>
<a href="#什么是-coze-studio">Coze Studio</a> •
<a href="#功能清单">功能清单</a> •
<a href="#快速开始">快速开始</a> •
<a href="#开发指南">开发指南</a>
</p>
<p>
<img alt="License" src="https://img.shields.io/badge/license-apache2.0-blue.svg">
<img alt="Go Version" src="https://img.shields.io/badge/go-%3E%3D%201.23.4-blue">
</p>
[English](README.md) | 中文
</div>
## 什么是 Coze Studio
[Coze Studio](https://www.coze.cn/home) 是一站式 AI Agent 开发工具。提供各类最新大模型和工具、多种开发模式和框架,从开发到部署,为你提供最便捷的 AI Agent 开发环境。
* **提供 AI Agent 开发所需的全部核心技术**Prompt、RAG、Plugin、Workflow,使得开发者可以聚焦创造 AI 核心价值。
* **开箱即用,用最低的成本开发最专业的 AI Agent**Coze Studio 为开发者提供了健全的应用模板和编排框架,你可以基于它们快速构建各种 AI Agent ,将创意变为现实。
Coze Studio,源自服务了上万家企业、数百万开发者的「扣子开发平台」,我们将它的核心引擎完全开放。它是一个一站式的 AI Agent 可视化开发工具,让 AI Agent 的创建、调试和部署变得前所未有的简单。通过 Coze Studio 提供的可视化设计与编排工具,开发者可以通过零代码或低代码的方式,快速打造和调试智能体、应用和工作流,实现强大的 AI 应用开发和更多定制化业务逻辑,是构建低代码 AI 产品的理想选择。Coze Studio 致力于降低 AI Agent 开发与应用门槛,鼓励社区共建和分享交流,助你在 AI 领域进行更深层次的探索与实践。
Coze Studio 的后端采用 Golang 开发,前端使用 React + TypeScript,整体基于微服务架构并遵循领域驱动设计(DDD)原则构建。为开发者提供一个高性能、高扩展性、易于二次开发的底层框架,助力开发者应对复杂的业务需求。
## 功能清单
| **功能模块** | **功能点** |
| --- | --- |
| 模型服务 | 管理模型列表,可接入OpenAI、火山方舟 等在线或离线模型服务 |
| 搭建智能体 | * 编排、发布、管理智能体 <br> * 支持配置工作流、知识库等资源 |
| 搭建应用 | * 创建、发布应用 <br> * 通过工作流搭建业务逻辑 |
| 搭建工作流 | 创建、修改、发布、删除工作流 |
| 开发资源 | 支持创建并管理以下资源: <br> * 插件 <br> * 知识库 <br> * 数据库 <br> * 提示词 |
| API 与 SDK | * 创建会话、发起对话等 OpenAPI <br> * 通过 Chat SDK 将智能体或应用集成到自己的应用 |
## 快速开始
了解如何获取并部署 Coze Studio 开源版,快速构建项目、体验 Coze Studio 开源版。
环境要求:
* 在安装 Coze Studio 之前,请确保您的机器满足以下最低系统要求: 2 Core、4 GB
* 提前安装 Docker、Docker Compose,并启动 Docker 服务。
部署步骤:
1. 获取源码。
```Bash
# 克隆代码
git clone https://github.com/coze-dev/coze-studio.git
```
2. 部署并启动服务。
首次部署并启动 Coze Studio 需要拉取镜像、构建本地镜像,可能耗时较久,请耐心等待。如果看到提示 "Container coze-server Started",表示 Coze Studio 服务已成功启动。
```Bash
cd coze-studio
# start service
# for macOS or Linux
make web
# for windows
cp ./docker/.env.example ./docker/.env
docker compose -f ./docker/docker-compose.yml up
```
**启动失败常见问题可参考[常见问题](https://github.com/coze-dev/coze-studio/wiki/9.-%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98)**。
3. 注册账号,访问 `http://localhost:8888/sign` 输入用户名、密码点击注册按钮。
4. 配置模型:访问 `http://localhost:8888/admin/#model-management` 新增模型。(镜像版本需要大于等于 0.5.0)。
5. 访问 Coze Studio `http://localhost:8888/`。
> [!WARNING]
> 如果要将 Coze Studio 部署到公网环境,建议在部署前评估整体评估安全风险,例如账号注册功能、工作流代码节点 Python执行环境、Coze Server 监听地址配置、SSRF 和部分 API 水平越权的风险,并采取相应防护措施。详细信息可参考[快速开始](https://github.com/coze-dev/coze-studio/wiki/2.-%E5%BF%AB%E9%80%9F%E5%BC%80%E5%A7%8B#%E5%85%AC%E7%BD%91%E5%AE%89%E5%85%A8%E9%A3%8E%E9%99%A9)。
## 开发指南
* **项目配置**
* [模型配置](https://github.com/coze-dev/coze-studio/wiki/3.-模型配置):部署 Coze Studio 开源版之前,必须配置模型服务,否则无法在搭建智能体、工作流和应用时选择模型。
* [插件配置](https://github.com/coze-dev/coze-studio/wiki/4.-插件配置):如需使用插件商店中的官方插件,必须先配置插件,添加第三方服务的鉴权秘钥。
* [基础组件配置](https://github.com/coze-dev/coze-studio/wiki/5.-基础组件配置):了解如何配置图片上传等组件,以便在 Coze Studio 中使用上传图片等功能。
* [API 参考](https://github.com/coze-dev/coze-studio/wiki/6.-API-参考)Coze Studio 社区版 API 和 Chat SDK 通过个人访问令牌鉴权,提供对话和工作流相关 API。
* [开发规范](https://github.com/coze-dev/coze-studio/wiki/7.-开发规范)
* [项目架构](https://github.com/coze-dev/coze-studio/wiki/7.-%E5%BC%80%E5%8F%91%E8%A7%84%E8%8C%83#%E9%A1%B9%E7%9B%AE%E6%9E%B6%E6%9E%84):了解 Coze Studio 开源版的技术架构与核心组件。
* [代码开发与测试](https://github.com/coze-dev/coze-studio/wiki/7.-%E5%BC%80%E5%8F%91%E8%A7%84%E8%8C%83#%E4%BB%A3%E7%A0%81%E5%BC%80%E5%8F%91%E4%B8%8E%E6%B5%8B%E8%AF%95):了解如何基于 Coze Studio 开源版进行二次开发与测试。
* [故障排查](https://github.com/coze-dev/coze-studio/wiki/7.-%E5%BC%80%E5%8F%91%E8%A7%84%E8%8C%83#%E6%95%85%E9%9A%9C%E6%8E%92%E6%9F%A5):了解如何查看容器状态、系统日志。
## 使用 Coze Studio 开源版
> 关于如何使用 Coze Studio,可参考[扣子开发平台官方文档中心](https://www.coze.cn/open/docs)获取更多资料。需要注意的是,音色等部分功能限商业版本使用,开源版与商业版的功能差异可参考**功能清单**。
* [快速入门](https://www.coze.cn/open/docs/guides/quickstart):通过 Coze Studio 快速搭建一个 AI 助手智能体。
* [开发智能体](https://www.coze.cn/open/docs/guides/agent_overview):如何创建、编排、发布与管理智能体。你可以使用知识、插件等功能解决模型幻觉、专业领域知识不足等问题。除此之外,Coze Studio 还提供了丰富的记忆功能,使智能体在与个人用户交互时,可根据个人用户的历史对话等生成更准确性的回复。
* [开发工作流](https://www.coze.cn/open/docs/guides/workflow):工作流是一系列可执行指令的集合,用于实现业务逻辑或完成特定任务。它为应用/智能体的数据流动和任务处理提供了一个结构化框架。 Coze Studio 提供了一个可视化画布,你可以通过拖拽节点迅速搭建工作流。
* [插件等资源](https://www.coze.cn/open/docs/guides/plugin):在 Coze Studio,工作流、插件、数据库、知识库和变量统称为资源。
* **API & SDK** Coze Studio 支持[对话和工作流相关 API](https://github.com/coze-dev/coze-studio/wiki/6.-API-%E5%8F%82%E8%80%83),你也可以通过 [Chat SDK](https://www.coze.cn/open/docs/developer_guides/web_sdk_overview) 将智能体或应用集成到本地业务系统。
* [实践教程](https://www.coze.cn/open/docs/tutorial/chat_sdk_web_online_customer_service):了解如何通过 Coze Studio 实现各种 AI 场景,例如通过 Chat SDK 搭建网页在线客服。
## License
本项目采用 Apache 2.0 许可证。详情请参阅 [LICENSE](https://github.com/coze-dev/coze-studio/blob/main/LICENSE-APACHE) 文件。
## 社区贡献
我们欢迎社区贡献,贡献指南参见 [CONTRIBUTING](https://github.com/coze-dev/coze-studio/blob/main/CONTRIBUTING.md) 和 [Code of conduct](https://github.com/coze-dev/coze-studio/blob/main/CODE_OF_CONDUCT.md),期待您的贡献!
## 安全与隐私
如果你在该项目中发现潜在的安全问题,或你认为可能发现了安全问题,请通过我们的[安全中心](https://security.bytedance.com/src) 或[漏洞报告邮箱](mailto:sec@bytedance.com)通知字节跳动安全团队。
请**不要**创建公开的 GitHub Issue。
## 加入社区
我们致力于构建一个开放、友好的开发者社区,欢迎所有对 AI Agent 开发感兴趣的开发者加入我们!
### 🐛 问题反馈与功能建议
为了更高效地跟踪和解决问题,保证信息透明和便于协同,我们推荐通过以下方式参与:
- **GitHub Issues**[提交 Bug 报告或功能请求](https://github.com/coze-dev/coze-studio/issues)
- **Pull Requests**[贡献代码或文档改进](https://github.com/coze-dev/coze-studio/pulls)
### 💬 技术交流与讨论
加入我们的技术交流群,与其他开发者分享经验、获取项目最新动态:
**飞书群聊**
使用飞书移动端扫描下方二维码加入:
![Image](https://p9-arcosite.byteimg.com/tos-cn-i-goo7wpa0wc/0a49081e8f3743e8bf3dcdded4bb571a~tplv-goo7wpa0wc-image.image)
**Discord 服务器**
点击加入:[Coze Community](https://discord.gg/sTVN9EVS4B)
**Telegram 群组**
点击加入:Telegram Group [Coze](https://t.me/+pP9CkPnomDA0Mjgx)
## 致谢
感谢所有为 Coze Studio 项目做出贡献的开发者和社区成员。特别感谢:
* [Eino](https://github.com/cloudwego/eino) 框架团队 - 为 Coze Studio 的智能体和工作流运行时、模型抽象封装、知识库索引构建和检索提供了强大的支持
* [FlowGram](https://github.com/bytedance/flowgram.ai) 团队 - 为 Coze Studio 的工作流画布编辑页提供了高质量的流程搭建引擎
* [Hertz](https://github.com/cloudwego/hertz) 团队 - 高性能、强扩展性的 Go HTTP 框架,用于构建微服务
* 所有参与测试和反馈的用户
+42
View File
@@ -0,0 +1,42 @@
*.o
*.a
*.so
_obj
_test
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.exe~
*.test
*.prof
*.rar
*.zip
*.gz
*.psd
*.bmd
*.cfg
*.pptx
*.log
*nohup.out
*settings.pyc
*.sublime-project
*.sublime-workspace
!.gitkeep
.DS_Store
/.idea
/.vscode
/output
*.local.yml
dumped_hertz_remote_config.json
/oldimpl
/vendor
*gen_test.go
/domain/workflow/internal/nodes/code/script/RestrictedPython/__pycache__/**
.env.dev
.env.local
+6
View File
@@ -0,0 +1,6 @@
// Code generated by hz. DO NOT EDIT.
hz version: v0.9.7
handlerDir: api/handler
modelDir: api/model
routerDir: api/router
+76
View File
@@ -0,0 +1,76 @@
# Stage 1: Builder for Go application
FROM golang:1.24-alpine AS builder
WORKDIR /app
# Install build dependencies for Go
RUN apk add --no-cache git gcc libc-dev
# Copy go.mod and go.sum first to leverage Docker cache
COPY backend/go.mod backend/go.sum ./
RUN go mod download
# Copy the entire backend source code
COPY backend/ ./
# Build the Go application
RUN go build -ldflags="-s -w" -o /app/opencoze main.go
# Stage 2: Final image
FROM alpine:3.22.0
WORKDIR /app
# Install runtime dependencies for Go app and base for Python
# pax-utils for scanelf, python3 for running Python, python3-dev for headers/shared libs
# bind-tools for nslookup etc., file for debugging file types
RUN apk add --no-cache pax-utils python3 python3-dev bind-tools file deno curl
RUN deno run -A jsr:@langchain/pyodide-sandbox -c "print('Hello, World')"
# Install Python build dependencies, create venv, install packages, then remove build deps
RUN apk add --no-cache --virtual .python-build-deps build-base py3-pip git && \
python3 -m venv --copies --upgrade-deps /app/.venv && \
# Activate venv and install packages
. /app/.venv/bin/activate && \
# If you want to use other third-party libraries, you can install them here.
pip install urllib3==1.26.16 && \
pip install --no-cache-dir h11==0.16.0 httpx==0.28.1 pillow==11.2.1 pdfplumber==0.11.7 python-docx==1.2.0 numpy==2.3.1 && \
# Deactivate (optional, as RUN is a new shell)
# deactivate && \
# Remove build dependencies
apk del .python-build-deps
# Copy the built Go binary from the builder stage
COPY --from=builder /app/opencoze /app/opencoze
# Copy Python application scripts
COPY backend/infra/document/parser/impl/builtin/parse_pdf.py /app/parse_pdf.py
COPY backend/infra/document/parser/impl/builtin/parse_docx.py /app/parse_docx.py
COPY backend/infra/coderunner/impl/script/sandbox.py /app/sandbox.py
# Copy static resources
# COPY backend/static /app/resources/static/
COPY backend/conf /app/resources/conf/
COPY docker/.env.example /app/.env
# COPY docker/.env.ve /app/.env
# COPY docker/cert.pem /app/cert.pem
# COPY docker/key.pem /app/key.pem
# Set PATH to prioritize venv's binaries
ENV PATH="/app/.venv/bin:${PATH}"
# ENV LD_LIBRARY_PATH="/usr/lib:${LD_LIBRARY_PATH}" # Keep commented for now
# Ensure python scripts and venv executables are executable
RUN chmod +x /app/parse_pdf.py /app/parse_docx.py && \
find /app/.venv/bin -type f -exec chmod +x {} \;
EXPOSE 8888
ENV SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt
CMD ["/app/opencoze"]
+1
View File
@@ -0,0 +1 @@
# Coze Backend API
@@ -0,0 +1,229 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package coze
import (
"context"
"encoding/json"
"errors"
"net/http"
"github.com/hertz-contrib/sse"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol/consts"
"github.com/coze-dev/coze-studio/backend/api/model/conversation/run"
"github.com/coze-dev/coze-studio/backend/application/conversation"
sseImpl "github.com/coze-dev/coze-studio/backend/infra/sse/impl/sse"
"github.com/coze-dev/coze-studio/backend/pkg/errorx"
"github.com/coze-dev/coze-studio/backend/pkg/lang/ptr"
"github.com/coze-dev/coze-studio/backend/types/errno"
)
// AgentRun .
// @router /api/conversation/chat [POST]
func AgentRun(ctx context.Context, c *app.RequestContext) {
var err error
var req run.AgentRunRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if checkErr := checkParams(ctx, &req); checkErr != nil {
invalidParamRequestResponse(c, checkErr.Error())
return
}
sseSender := sseImpl.NewSSESender(sse.NewStream(c))
c.SetStatusCode(http.StatusOK)
c.Response.Header.Set("X-Accel-Buffering", "no")
err = conversation.ConversationSVC.Run(ctx, sseSender, &req)
if err != nil {
errData := run.ErrorData{
Code: errno.ErrConversationAgentRunError,
Msg: err.Error(),
}
ed, _ := json.Marshal(errData)
_ = sseSender.Send(ctx, &sse.Event{
Event: run.RunEventError,
Data: ed,
})
}
}
func checkParams(_ context.Context, ar *run.AgentRunRequest) error {
if ar.BotID == 0 {
return errorx.New(errno.ErrConversationInvalidParamCode, errorx.KV("msg", "bot id is required"))
}
if ar.Scene == nil {
return errorx.New(errno.ErrConversationInvalidParamCode, errorx.KV("msg", "scene is required"))
}
if ar.ContentType == nil {
ar.ContentType = ptr.Of(run.ContentTypeText)
}
return nil
}
// ChatV3 .
// @router /v3/chat [POST]
func ChatV3(ctx context.Context, c *app.RequestContext) {
var err error
var req run.ChatV3Request
// Pre-process parameters field: convert JSON object to string if needed
if err = preprocessChatV3Parameters(c); err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if checkErr := checkParamsV3(ctx, &req); checkErr != nil {
invalidParamRequestResponse(c, checkErr.Error())
return
}
if req.Stream != nil && !*req.Stream {
resp, err := conversation.ConversationOpenAPISVC.OpenapiAgentRunSync(ctx, &req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
c.JSON(consts.StatusOK, resp)
return
}
// Streaming mode (default)
c.SetStatusCode(http.StatusOK)
c.Response.Header.Set("X-Accel-Buffering", "no")
sseSender := sseImpl.NewSSESender(sse.NewStream(c))
err = conversation.ConversationOpenAPISVC.OpenapiAgentRun(ctx, sseSender, &req)
if err != nil {
errData := run.ErrorData{
Code: errno.ErrConversationAgentRunError,
Msg: err.Error(),
}
ed, _ := json.Marshal(errData)
_ = sseSender.Send(ctx, &sse.Event{
Event: run.RunEventError,
Data: ed,
})
}
}
func checkParamsV3(_ context.Context, ar *run.ChatV3Request) error {
if ar.BotID == 0 {
return errorx.New(errno.ErrConversationInvalidParamCode, errorx.KV("msg", "bot id is required"))
}
return nil
}
// CancelChatApi .
// @router /v3/chat/cancel [POST]
func CancelChatApi(ctx context.Context, c *app.RequestContext) {
var err error
var req run.CancelChatApiRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := conversation.ConversationOpenAPISVC.CancelRun(ctx, &req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
c.JSON(consts.StatusOK, resp)
}
// preprocessChatV3Parameters handles the conversion of parameters field from JSON object to string
func preprocessChatV3Parameters(c *app.RequestContext) error {
// Get the raw request body
body := c.Request.Body()
if len(body) == 0 {
return nil
}
// Parse the JSON body
var requestData map[string]interface{}
if err := json.Unmarshal(body, &requestData); err != nil {
return nil // If it's not valid JSON, let BindAndValidate handle the error
}
// Check if parameters field exists and is an object
if parametersValue, exists := requestData["parameters"]; exists {
// If parameters is already a string, no conversion needed
if _, isString := parametersValue.(string); isString {
return errors.New("parameters field should be an object, not a string")
}
// If parameters is an object, convert it to JSON string
if parametersObj, isObject := parametersValue.(map[string]interface{}); isObject {
parametersJSON, err := json.Marshal(parametersObj)
if err != nil {
return err
}
requestData["parameters"] = string(parametersJSON)
// Update the request body with the modified data
modifiedBody, err := json.Marshal(requestData)
if err != nil {
return err
}
// Replace the request body
c.Request.SetBody(modifiedBody)
}
}
return nil
}
// RetrieveChatOpen .
// @router /v3/chat/retrieve [GET]
func RetrieveChatOpen(ctx context.Context, c *app.RequestContext) {
var err error
var req run.RetrieveChatOpenRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := conversation.ConversationOpenAPISVC.RetrieveRunRecord(ctx, &req)
if err != nil {
c.String(consts.StatusInternalServerError, err.Error())
return
}
c.JSON(consts.StatusOK, resp)
}
+33
View File
@@ -0,0 +1,33 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package coze
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/coze-dev/coze-studio/backend/api/internal/httputil"
)
func invalidParamRequestResponse(c *app.RequestContext, errMsg string) {
httputil.BadRequest(c, errMsg)
}
func internalServerErrorResponse(ctx context.Context, c *app.RequestContext, err error) {
httputil.InternalError(ctx, c, err)
}
@@ -0,0 +1,153 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Code generated by hertz generator.
package coze
import (
"context"
"fmt"
openapiauthApp "github.com/coze-dev/coze-studio/backend/application/openauth"
"github.com/coze-dev/coze-studio/backend/application/plugin"
"github.com/coze-dev/coze-studio/backend/application/singleagent"
"github.com/coze-dev/coze-studio/backend/application/upload"
"github.com/coze-dev/coze-studio/backend/bizpkg/config"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol/consts"
"github.com/coze-dev/coze-studio/backend/api/model/app/bot_open_api"
)
// OauthAuthorizationCode .
// @router /api/oauth/authorization_code [GET]
func OauthAuthorizationCode(ctx context.Context, c *app.RequestContext) {
var err error
var req bot_open_api.OauthAuthorizationCodeReq
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.Code == "" {
invalidParamRequestResponse(c, "authorization failed, code is required")
return
}
if req.State == "" {
invalidParamRequestResponse(c, "state is required")
return
}
_, err = plugin.PluginApplicationSVC.OauthAuthorizationCode(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
host, err := config.Base().GetServerHost(ctx)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
redirectURL := fmt.Sprintf("%s/information/auth/success", host)
c.Redirect(consts.StatusFound, []byte(redirectURL))
c.Abort()
}
// UploadFileOpen .
// @router /v1/files/upload [POST]
func UploadFileOpen(ctx context.Context, c *app.RequestContext) {
var err error
var req bot_open_api.UploadFileOpenRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp := new(bot_open_api.UploadFileOpenResponse)
resp, err = upload.SVC.UploadFileOpen(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetBotOnlineInfo .
// @router /v1/bot/get_online_info [GET]
func GetBotOnlineInfo(ctx context.Context, c *app.RequestContext) {
var err error
var req bot_open_api.GetBotOnlineInfoReq
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := singleagent.SingleAgentSVC.GetAgentOnlineInfo(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ImpersonateCozeUser .
// @router /api/permission_api/coze_web_app/impersonate_coze_user [POST]
func ImpersonateCozeUser(ctx context.Context, c *app.RequestContext) {
var err error
var req bot_open_api.ImpersonateCozeUserRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := openapiauthApp.OpenAuthApplication.ImpersonateCozeUserAccessToken(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// OpenGetBotInfo .
// @router /v1/bots/:bot_id [GET]
func OpenGetBotInfo(ctx context.Context, c *app.RequestContext) {
var err error
var req bot_open_api.OpenGetBotInfoRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := singleagent.SingleAgentSVC.OpenGetBotInfo(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
+292
View File
@@ -0,0 +1,292 @@
// Code generated by hertz generator.
package coze
import (
"context"
"fmt"
"net"
"net/url"
"strconv"
"strings"
"github.com/cloudwego/eino/schema"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol/consts"
"github.com/coze-dev/coze-studio/backend/api/model/admin/config"
bizConf "github.com/coze-dev/coze-studio/backend/bizpkg/config"
"github.com/coze-dev/coze-studio/backend/bizpkg/config/modelmgr"
"github.com/coze-dev/coze-studio/backend/bizpkg/llm/modelbuilder"
"github.com/coze-dev/coze-studio/backend/infra/embedding/impl"
"github.com/coze-dev/coze-studio/backend/pkg/lang/conv"
"github.com/coze-dev/coze-studio/backend/pkg/lang/ptr"
"github.com/coze-dev/coze-studio/backend/pkg/logs"
)
// GetBasicConfiguration .
// @router /api/admin/config/basic/get [GET]
func GetBasicConfiguration(ctx context.Context, c *app.RequestContext) {
baseConfig, err := bizConf.Base().GetBaseConfig(ctx)
if err != nil {
c.String(consts.StatusInternalServerError, err.Error())
return
}
resp := new(config.GetBasicConfigurationResp)
resp.Configuration = baseConfig
c.JSON(consts.StatusOK, resp)
}
// SaveBasicConfiguration .
// @router /api/admin/config/basic/save [POST]
func SaveBasicConfiguration(ctx context.Context, c *app.RequestContext) {
var err error
var req config.SaveBasicConfigurationReq
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
if req.Configuration == nil {
invalidParamRequestResponse(c, "Configuration is nil")
return
}
// TODO: check coze api token
// Validate ServerHost: allow http/https URLs, or hostname:port
if req.Configuration.ServerHost == "" {
invalidParamRequestResponse(c, "ServerHost is empty")
return
}
host := req.Configuration.ServerHost
if strings.Contains(host, "://") {
u, parseErr := url.Parse(host)
if parseErr != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") {
invalidParamRequestResponse(c, "ServerHost is invalid URL, require http/https")
return
}
} else {
// Expect hostname:port format
h, p, splitErr := net.SplitHostPort(host)
if splitErr != nil || h == "" {
invalidParamRequestResponse(c, "ServerHost must be hostname:port or http(s) URL")
return
}
port, portErr := strconv.Atoi(p)
if portErr != nil || port <= 0 || port > 65535 {
invalidParamRequestResponse(c, "ServerHost port is invalid")
return
}
}
logs.Infof("server host is valid %s", req.Configuration.ServerHost)
if req.Configuration.CodeRunnerType.String() == "<UNSET>" {
invalidParamRequestResponse(c, "CodeRunnerType is invalid")
return
}
err = bizConf.Base().SaveBaseConfig(ctx, req.Configuration)
if err != nil {
internalServerErrorResponse(ctx, c, fmt.Errorf("save basic config failed: %w", err))
return
}
resp := new(config.SaveBasicConfigurationResp)
c.JSON(consts.StatusOK, resp)
}
// GetKnowledgeConfig .
// @router /api/admin/config/knowledge/get [GET]
func GetKnowledgeConfig(ctx context.Context, c *app.RequestContext) {
knowledgeConfig, err := bizConf.Knowledge().GetKnowledgeConfig(ctx)
if err != nil {
internalServerErrorResponse(ctx, c, fmt.Errorf("get knowledge config failed: %w", err))
return
}
resp := new(config.GetKnowledgeConfigResp)
resp.KnowledgeConfig = knowledgeConfig
c.JSON(consts.StatusOK, resp)
}
// UpdateKnowledgeConfig .
// @router /api/admin/config/knowledge/save [POST]
func UpdateKnowledgeConfig(ctx context.Context, c *app.RequestContext) {
var err error
var req config.UpdateKnowledgeConfigReq
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
if req.KnowledgeConfig == nil {
invalidParamRequestResponse(c, "KnowledgeConfig is nil")
return
}
if req.KnowledgeConfig.EmbeddingConfig == nil {
invalidParamRequestResponse(c, "EmbeddingConfig is nil")
return
}
if req.KnowledgeConfig.EmbeddingConfig.Connection == nil {
invalidParamRequestResponse(c, "Connection is nil")
return
}
if req.KnowledgeConfig.EmbeddingConfig.Connection.EmbeddingInfo == nil {
invalidParamRequestResponse(c, "EmbeddingInfo is nil")
return
}
embedding, err := impl.GetEmbedding(ctx, req.KnowledgeConfig.EmbeddingConfig)
if err != nil {
invalidParamRequestResponse(c, fmt.Sprintf("get embedding failed: %v", err))
return
}
if req.KnowledgeConfig.EmbeddingConfig.Connection.EmbeddingInfo.Dims <= 0 {
req.KnowledgeConfig.EmbeddingConfig.Connection.EmbeddingInfo.Dims = int32(embedding.Dimensions())
embedding, err = impl.GetEmbedding(ctx, req.KnowledgeConfig.EmbeddingConfig)
if err != nil {
invalidParamRequestResponse(c, fmt.Sprintf("get embedding failed: %v", err))
return
}
}
denseEmbeddings, err := embedding.EmbedStrings(ctx, []string{"test"})
if err != nil {
invalidParamRequestResponse(c, fmt.Sprintf("embed test string failed: %v", err))
return
}
if len(denseEmbeddings) == 0 {
invalidParamRequestResponse(c, fmt.Sprintf("embed test string failed: %v", err))
return
}
logs.CtxDebugf(ctx, "embed test string result: %d, expect %d",
len(denseEmbeddings[0]), req.KnowledgeConfig.EmbeddingConfig.Connection.EmbeddingInfo.Dims)
if len(denseEmbeddings[0]) != int(req.KnowledgeConfig.EmbeddingConfig.Connection.EmbeddingInfo.Dims) {
invalidParamRequestResponse(c, fmt.Sprintf("embed test string failed: dims not match, expect %d, got %d",
req.KnowledgeConfig.EmbeddingConfig.Connection.EmbeddingInfo.Dims, len(denseEmbeddings[0])))
return
}
err = bizConf.Knowledge().SaveKnowledgeConfig(ctx, req.KnowledgeConfig)
if err != nil {
internalServerErrorResponse(ctx, c, fmt.Errorf("save knowledge config failed: %w", err))
return
}
resp := new(config.UpdateKnowledgeConfigResp)
c.JSON(consts.StatusOK, resp)
}
// GetModelList .
// @router /api/admin/config/model/list [GET]
func GetModelList(ctx context.Context, c *app.RequestContext) {
var err error
var req config.GetModelListReq
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
modelList, err := bizConf.ModelConf().GetProviderModelList(ctx)
if err != nil {
internalServerErrorResponse(ctx, c, fmt.Errorf("get model list failed: %w", err))
return
}
resp := new(config.GetModelListResp)
resp.ProviderModelList = modelList
c.JSON(consts.StatusOK, resp)
}
// CreateModel .
// @router /api/admin/config/model/create [POST]
func CreateModel(ctx context.Context, c *app.RequestContext) {
var err error
var req config.CreateModelReq
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
modelBuilder, err := modelbuilder.NewModelBuilder(req.ModelClass, &config.Model{
EnableBase64URL: req.EnableBase64URL,
Connection: req.Connection,
})
if err != nil {
invalidParamRequestResponse(c, fmt.Sprintf("create model builder failed: %v", err))
return
}
logs.CtxDebugf(ctx, "create model req: %s, conn: %s", conv.DebugJsonToStr(req), conv.DebugJsonToStr(req.Connection.BaseConnInfo))
chatModel, err := modelBuilder.Build(ctx, &modelbuilder.LLMParams{EnableThinking: ptr.Of(false)})
if err != nil {
invalidParamRequestResponse(c, fmt.Sprintf("build model failed: %v", err))
return
}
respMsgs, err := chatModel.Generate(ctx, []*schema.Message{
schema.SystemMessage("Just answer with a number, no explanation."),
schema.UserMessage("1+1=?"),
})
if err != nil {
invalidParamRequestResponse(c, fmt.Sprintf("generate model failed: %v", err))
return
}
logs.CtxDebugf(ctx, "chatModel.Generate resp : %s", conv.DebugJsonToStr(respMsgs))
id, err := bizConf.ModelConf().CreateModel(ctx, req.ModelClass, req.ModelName, req.Connection, &modelmgr.ModelExtra{
EnableBase64URL: req.EnableBase64URL,
})
if err != nil {
invalidParamRequestResponse(c, fmt.Sprintf("create model failed: %v", err))
return
}
resp := new(config.CreateModelResp)
resp.ID = id
c.JSON(consts.StatusOK, resp)
}
// DeleteModel .
// @router /api/admin/config/model/delete [POST]
func DeleteModel(ctx context.Context, c *app.RequestContext) {
var err error
var req config.DeleteModelReq
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
err = bizConf.ModelConf().DeleteModel(ctx, req.ID)
if err != nil {
internalServerErrorResponse(ctx, c, fmt.Errorf("delete model failed: %w", err))
return
}
resp := new(config.DeleteModelResp)
c.JSON(consts.StatusOK, resp)
}
@@ -0,0 +1,231 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Code generated by hertz generator.
package coze
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol/consts"
"github.com/coze-dev/coze-studio/backend/api/model/conversation/conversation"
application "github.com/coze-dev/coze-studio/backend/application/conversation"
"github.com/coze-dev/coze-studio/backend/pkg/errorx"
"github.com/coze-dev/coze-studio/backend/types/errno"
)
// ClearConversationHistory .
// @router /api/conversation/clear_message [POST]
func ClearConversationHistory(ctx context.Context, c *app.RequestContext) {
var err error
var req conversation.ClearConversationHistoryRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if checkErr := checkCCHParams(ctx, &req); checkErr != nil {
invalidParamRequestResponse(c, checkErr.Error())
return
}
resp, err := application.ConversationSVC.ClearHistory(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
func checkCCHParams(_ context.Context, req *conversation.ClearConversationHistoryRequest) error {
if req.ConversationID <= 0 {
return errorx.New(errno.ErrConversationInvalidParamCode, errorx.KV("msg", "invalid conversation id"))
}
if req.Scene == nil {
return errorx.New(errno.ErrConversationInvalidParamCode, errorx.KV("msg", "scene is required"))
}
return nil
}
// ClearConversationCtx .
// @router /api/conversation/create_section [POST]
func ClearConversationCtx(ctx context.Context, c *app.RequestContext) {
resp := new(conversation.ClearConversationCtxResponse)
var err error
var req conversation.ClearConversationCtxRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if checkErr := checkCCCParams(ctx, &req); checkErr != nil {
invalidParamRequestResponse(c, checkErr.Error())
return
}
newSectionID, err := application.ConversationSVC.CreateSection(ctx, req.ConversationID)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
resp.NewSectionID = newSectionID
c.JSON(consts.StatusOK, resp)
}
func checkCCCParams(ctx context.Context, req *conversation.ClearConversationCtxRequest) error {
if req.ConversationID <= 0 {
return errorx.New(errno.ErrConversationInvalidParamCode, errorx.KV("msg", "invalid conversation id"))
}
if req.Scene == nil {
return errorx.New(errno.ErrConversationInvalidParamCode, errorx.KV("msg", "scene is required"))
}
return nil
}
// CreateConversation .
// @router /api/conversation/create [POST]
func CreateConversation(ctx context.Context, c *app.RequestContext) {
var err error
var req conversation.CreateConversationRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := application.ConversationSVC.CreateConversation(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ClearConversationApi .
// @router /v1/conversations/:conversation_id/clear [POST]
func ClearConversationApi(ctx context.Context, c *app.RequestContext) {
var err error
var req conversation.ClearConversationApiRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp := new(conversation.ClearConversationApiResponse)
sectionID, err := application.ConversationSVC.CreateSection(ctx, req.ConversationID)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
resp.Data = &conversation.Section{
ID: sectionID,
ConversationID: req.ConversationID,
}
c.JSON(consts.StatusOK, resp)
}
// ListConversationsApi .
// @router /v1/conversations [GET]
func ListConversationsApi(ctx context.Context, c *app.RequestContext) {
var err error
var req conversation.ListConversationsApiRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := application.ConversationSVC.ListConversation(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// UpdateConversationApi .
// @router /v1/conversations/:conversation_id [PUT]
func UpdateConversationApi(ctx context.Context, c *app.RequestContext) {
var err error
var req conversation.UpdateConversationApiRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := application.ConversationSVC.UpdateConversation(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DeleteConversationApi .
// @router /v1/conversations/:conversation_id [DELETE]
func DeleteConversationApi(ctx context.Context, c *app.RequestContext) {
var err error
var req conversation.DeleteConversationApiRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := application.ConversationSVC.DeleteConversation(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// RetrieveConversationApi .
// @router /v1/conversation/retrieve [GET]
func RetrieveConversationApi(ctx context.Context, c *app.RequestContext) {
var err error
var req conversation.RetrieveConversationApiRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := application.ConversationSVC.RetrieveConversation(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
@@ -0,0 +1,412 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Code generated by hertz generator.
package coze
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol/consts"
"github.com/coze-dev/coze-studio/backend/api/model/data/database/table"
"github.com/coze-dev/coze-studio/backend/api/model/data/knowledge"
"github.com/coze-dev/coze-studio/backend/application/memory"
"github.com/coze-dev/coze-studio/backend/application/singleagent"
)
// ListDatabase .
// @router /api/memory/database/list [POST]
func ListDatabase(ctx context.Context, c *app.RequestContext) {
var err error
var req table.ListDatabaseRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := memory.DatabaseApplicationSVC.ListDatabase(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetDatabaseByID .
// @router /api/memory/database/get_by_id [POST]
func GetDatabaseByID(ctx context.Context, c *app.RequestContext) {
var err error
var req table.SingleDatabaseRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := memory.DatabaseApplicationSVC.GetDatabaseByID(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// AddDatabase .
// @router /api/memory/database/add [POST]
func AddDatabase(ctx context.Context, c *app.RequestContext) {
var err error
var req table.AddDatabaseRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := memory.DatabaseApplicationSVC.AddDatabase(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// UpdateDatabase .
// @router /api/memory/database/update [POST]
func UpdateDatabase(ctx context.Context, c *app.RequestContext) {
var err error
var req table.UpdateDatabaseRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := memory.DatabaseApplicationSVC.UpdateDatabase(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DeleteDatabase .
// @router /api/memory/database/delete [POST]
func DeleteDatabase(ctx context.Context, c *app.RequestContext) {
var err error
var req table.DeleteDatabaseRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := memory.DatabaseApplicationSVC.DeleteDatabase(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// BindDatabase .
// @router /api/memory/database/bind_to_bot [POST]
func BindDatabase(ctx context.Context, c *app.RequestContext) {
var err error
var req table.BindDatabaseToBotRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := singleagent.SingleAgentSVC.BindDatabase(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// UnBindDatabase .
// @router /api/memory/database/unbind_to_bot [POST]
func UnBindDatabase(ctx context.Context, c *app.RequestContext) {
var err error
var req table.BindDatabaseToBotRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := singleagent.SingleAgentSVC.UnBindDatabase(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ListDatabaseRecords .
// @router /api/memory/database/list_records [POST]
func ListDatabaseRecords(ctx context.Context, c *app.RequestContext) {
var err error
var req table.ListDatabaseRecordsRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := memory.DatabaseApplicationSVC.ListDatabaseRecords(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// UpdateDatabaseRecords .
// @router /api/memory/database/update_records [POST]
func UpdateDatabaseRecords(ctx context.Context, c *app.RequestContext) {
var err error
var req table.UpdateDatabaseRecordsRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := memory.DatabaseApplicationSVC.UpdateDatabaseRecords(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetOnlineDatabaseId .
// @router /api/memory/database/get_online_database_id [POST]
func GetOnlineDatabaseId(ctx context.Context, c *app.RequestContext) {
var err error
var req table.GetOnlineDatabaseIdRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := memory.DatabaseApplicationSVC.GetOnlineDatabaseId(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ResetBotTable .
// @router /api/memory/database/table/reset [POST]
func ResetBotTable(ctx context.Context, c *app.RequestContext) {
var err error
var req table.ResetBotTableRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := memory.DatabaseApplicationSVC.ResetBotTable(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetDatabaseTemplate .
// @router /api/memory/database/get_template [POST]
func GetDatabaseTemplate(ctx context.Context, c *app.RequestContext) {
var err error
var req table.GetDatabaseTemplateRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := memory.DatabaseApplicationSVC.GetDatabaseTemplate(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetConnectorName .
// @router /api/memory/database/get_connector_name [POST]
func GetConnectorName(ctx context.Context, c *app.RequestContext) {
var err error
var req table.GetSpaceConnectorListRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := memory.DatabaseApplicationSVC.GetConnectorName(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetBotDatabase .
// @router /api/memory/database/table/list_new [POST]
func GetBotDatabase(ctx context.Context, c *app.RequestContext) {
var err error
var req table.GetBotTableRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := memory.DatabaseApplicationSVC.GetBotDatabase(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// UpdateDatabaseBotSwitch .
// @router /api/memory/database/update_bot_switch [POST]
func UpdateDatabaseBotSwitch(ctx context.Context, c *app.RequestContext) {
var err error
var req table.UpdateDatabaseBotSwitchRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := singleagent.SingleAgentSVC.UpdatePromptDisable(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetDatabaseTableSchema .
// @router /api/memory/table_schema/get [POST]
func GetDatabaseTableSchema(ctx context.Context, c *app.RequestContext) {
var err error
var req table.GetTableSchemaRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
var resp *knowledge.GetTableSchemaInfoResponse
resp, err = memory.DatabaseApplicationSVC.GetDatabaseTableSchema(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// SubmitDatabaseInsertTask .
// @router /api/memory/table_file/submit [POST]
func SubmitDatabaseInsertTask(ctx context.Context, c *app.RequestContext) {
var err error
var req table.SubmitDatabaseInsertRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := memory.DatabaseApplicationSVC.SubmitDatabaseInsertTask(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DatabaseFileProgressData .
// @router /api/memory/table_file/get_progress [POST]
func DatabaseFileProgressData(ctx context.Context, c *app.RequestContext) {
var err error
var req table.GetDatabaseFileProgressRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := memory.DatabaseApplicationSVC.DatabaseFileProgressData(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ValidateDatabaseTableSchema .
// @router /api/memory/table_schema/validate [POST]
func ValidateDatabaseTableSchema(ctx context.Context, c *app.RequestContext) {
var err error
var req table.ValidateTableSchemaRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := memory.DatabaseApplicationSVC.ValidateDatabaseTableSchema(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
@@ -0,0 +1,494 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Code generated by hertz generator.
package coze
import (
"context"
"crypto/sha256"
"encoding/base64"
"fmt"
"math/rand"
"time"
"unicode/utf8"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol/consts"
"github.com/coze-dev/coze-studio/backend/api/model/app/developer_api"
"github.com/coze-dev/coze-studio/backend/application/base/ctxutil"
"github.com/coze-dev/coze-studio/backend/application/modelmgr"
"github.com/coze-dev/coze-studio/backend/application/plugin"
"github.com/coze-dev/coze-studio/backend/application/singleagent"
application "github.com/coze-dev/coze-studio/backend/application/singleagent"
"github.com/coze-dev/coze-studio/backend/application/upload"
"github.com/coze-dev/coze-studio/backend/application/user"
"github.com/coze-dev/coze-studio/backend/bizpkg/config"
"github.com/coze-dev/coze-studio/backend/pkg/errorx"
"github.com/coze-dev/coze-studio/backend/pkg/lang/ptr"
"github.com/coze-dev/coze-studio/backend/types/errno"
)
// DraftBotCreate .
// @router /api/draftbot/create [POST]
func DraftBotCreate(ctx context.Context, c *app.RequestContext) {
var err error
var req developer_api.DraftBotCreateRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.SpaceID <= 0 {
invalidParamRequestResponse(c, "space id is not set")
return
}
if req.Name == "" {
invalidParamRequestResponse(c, "name is nil")
return
}
if req.IconURI == "" {
invalidParamRequestResponse(c, "icon uri is nil")
return
}
if utf8.RuneCountInString(req.Name) > 50 {
invalidParamRequestResponse(c, "name is too long")
return
}
if utf8.RuneCountInString(req.Description) > 2000 {
invalidParamRequestResponse(c, "description is too long")
return
}
resp, err := application.SingleAgentSVC.CreateSingleAgentDraft(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DeleteDraftBot .
// @router /api/draftbot/delete [POST]
func DeleteDraftBot(ctx context.Context, c *app.RequestContext) {
var err error
var req developer_api.DeleteDraftBotRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := application.SingleAgentSVC.DeleteAgentDraft(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// UpdateDraftBotDisplayInfo .
// @router /api/draftbot/update_display_info [POST]
func UpdateDraftBotDisplayInfo(ctx context.Context, c *app.RequestContext) {
var err error
var req developer_api.UpdateDraftBotDisplayInfoRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp, err := application.SingleAgentSVC.UpdateAgentDraftDisplayInfo(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DuplicateDraftBot .
// @router /api/draftbot/duplicate [POST]
func DuplicateDraftBot(ctx context.Context, c *app.RequestContext) {
var err error
var req developer_api.DuplicateDraftBotRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := application.SingleAgentSVC.DuplicateDraftBot(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetDraftBotDisplayInfo .
// @router /api/draftbot/get_display_info [POST]
func GetDraftBotDisplayInfo(ctx context.Context, c *app.RequestContext) {
var err error
var req developer_api.GetDraftBotDisplayInfoRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp, err := application.SingleAgentSVC.GetAgentDraftDisplayInfo(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// PublishDraftBot .
// @router /api/draftbot/publish [POST]
func PublishDraftBot(ctx context.Context, c *app.RequestContext) {
var err error
var req developer_api.PublishDraftBotRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
if len(req.Connectors) == 0 {
invalidParamRequestResponse(c, "connectors is nil")
return
}
resp, err := application.SingleAgentSVC.PublishAgent(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ListDraftBotHistory .
// @router /api/draftbot/list_draft_history [POST]
func ListDraftBotHistory(ctx context.Context, c *app.RequestContext) {
var err error
var req developer_api.ListDraftBotHistoryRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
if req.BotID == 0 {
invalidParamRequestResponse(c, "bot id is not set")
return
}
if req.PageIndex <= 0 {
req.PageIndex = 1
}
if req.PageSize <= 0 {
req.PageSize = 30
}
resp, err := application.SingleAgentSVC.ListAgentPublishHistory(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetIcon .
// @router /api/developer/get_icon [POST]
func GetIcon(ctx context.Context, c *app.RequestContext) {
var err error
var req developer_api.GetIconRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := upload.SVC.GetIcon(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetUploadAuthToken .
// @router /api/playground/upload/auth_token [POST]
func GetUploadAuthToken(ctx context.Context, c *app.RequestContext) {
var err error
var req developer_api.GetUploadAuthTokenRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp, err := application.SingleAgentSVC.GetUploadAuthToken(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
func createSecret(uid int64, fileType string) string {
num := 10
input := fmt.Sprintf("upload_%d_Ma*9)fhi_%d_gou_%s_rand_%d", uid, time.Now().Unix(), fileType, rand.Intn(100000))
// Do md5, take the first 20,//mapIntToBase62 map the number to Base62
hash := sha256.Sum256([]byte(fmt.Sprintf("%s", input)))
hashString := base64.StdEncoding.EncodeToString(hash[:])
if len(hashString) > num {
hashString = hashString[:num]
}
result := ""
for _, char := range hashString {
index := int(char) % 62
result += string(baseWord[index])
}
return result
}
// UploadFile .
// @router /api/bot/upload_file [POST]
func UploadFile(ctx context.Context, c *app.RequestContext) {
var err error
var req developer_api.UploadFileRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(developer_api.UploadFileResponse)
fileContent, err := base64.StdEncoding.DecodeString(req.Data)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
userID := ctxutil.GetUIDFromCtx(ctx)
if userID == nil {
internalServerErrorResponse(ctx, c, errorx.New(errno.ErrUploadPermissionCode, errorx.KV("msg", "session required")))
return
}
secret := createSecret(ptr.From(userID), req.FileHead.FileType)
fileName := fmt.Sprintf("%d_%d_%s.%s", ptr.From(userID), time.Now().UnixNano(), secret, req.FileHead.FileType)
objectName := fmt.Sprintf("%s/%s", req.FileHead.BizType.String(), fileName)
resp, err = upload.SVC.UploadFile(ctx, fileContent, objectName)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
const baseWord = "1Aa2Bb3Cc4Dd5Ee6Ff7Gg8Hh9Ii0JjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
// GetOnboarding .
// @router /api/playground/get_onboarding [POST]
func GetOnboarding(ctx context.Context, c *app.RequestContext) {
var err error
var req developer_api.GetOnboardingRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(developer_api.GetOnboardingResponse)
c.JSON(consts.StatusOK, resp)
}
// PublishConnectorList .
// @router /api/draftbot/publish/connector/list [POST]
func PublishConnectorList(ctx context.Context, c *app.RequestContext) {
var err error
var req developer_api.PublishConnectorListRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
if req.BotID == 0 {
invalidParamRequestResponse(c, "bot id is not set")
return
}
resp, err := singleagent.SingleAgentSVC.GetPublishConnectorList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// CheckDraftBotCommit .
// @router /api/draftbot/commit_check [POST]
func CheckDraftBotCommit(ctx context.Context, c *app.RequestContext) {
var err error
var req developer_api.CheckDraftBotCommitRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(developer_api.CheckDraftBotCommitResponse)
c.JSON(consts.StatusOK, resp)
}
// UpdateUserProfileCheck .
// @router /api/user/update_profile_check [POST]
func UpdateUserProfileCheck(ctx context.Context, c *app.RequestContext) {
var err error
var req developer_api.UpdateUserProfileCheckRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp, err := user.UserApplicationSVC.UpdateUserProfileCheck(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetTypeList .
// @router /api/bot/get_type_list [POST]
func GetTypeList(ctx context.Context, c *app.RequestContext) {
var err error
var req developer_api.GetTypeListRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp, err := modelmgr.ModelmgrApplicationSVC.GetModelList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// PluginOauthAuthorizationCode .
// @router /api/plugin_oauth/:plugin_id/authorization_code [GET]
func PluginOauthAuthorizationCode(ctx context.Context, c *app.RequestContext) {
var err error
var req developer_api.PluginOauthAuthorizationCodeReq
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.Code == "" {
invalidParamRequestResponse(c, "authorization failed, code is required")
return
}
if req.State == "" {
invalidParamRequestResponse(c, "state is required")
return
}
confirmCode, err := plugin.PluginApplicationSVC.PluginOauthAuthorizationCode(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
host, err := config.Base().GetServerHost(ctx)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
redirectURL := fmt.Sprintf("%s/oauth/confirm?confirm_code=%s", host, confirmCode)
c.Redirect(consts.StatusFound, []byte(redirectURL))
c.Abort()
}
// PluginOauthInfo .
// @router /api/plugin/oauth/get_oauth_info [GET]
func PluginOauthInfo(ctx context.Context, c *app.RequestContext) {
var err error
var req developer_api.PluginOauthInfoReq
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := plugin.PluginApplicationSVC.PluginOauthInfo(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// PluginOauthConfirm .
// @router /api/plugin/oauth/confirm [POST]
func PluginOauthConfirm(ctx context.Context, c *app.RequestContext) {
var err error
var req developer_api.PluginOauthConfirmReq
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := plugin.PluginApplicationSVC.PluginOauthConfirm(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
@@ -0,0 +1,426 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Code generated by hertz generator.
package coze
import (
"context"
"fmt"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol/consts"
"github.com/coze-dev/coze-studio/backend/api/model/app/intelligence"
"github.com/coze-dev/coze-studio/backend/api/model/app/intelligence/common"
project "github.com/coze-dev/coze-studio/backend/api/model/app/intelligence/project"
publish "github.com/coze-dev/coze-studio/backend/api/model/app/intelligence/publish"
task "github.com/coze-dev/coze-studio/backend/api/model/app/intelligence/task"
appApplication "github.com/coze-dev/coze-studio/backend/application/app"
"github.com/coze-dev/coze-studio/backend/application/search"
)
// GetDraftIntelligenceList .
// @router /api/intelligence_api/search/get_draft_intelligence_list [POST]
func GetDraftIntelligenceList(ctx context.Context, c *app.RequestContext) {
var err error
var req intelligence.GetDraftIntelligenceListRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := search.SearchSVC.GetDraftIntelligenceList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetDraftIntelligenceInfo .
// @router /api/intelligence_api/search/get_draft_intelligence_info [POST]
func GetDraftIntelligenceInfo(ctx context.Context, c *app.RequestContext) {
var err error
var req intelligence.GetDraftIntelligenceInfoRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.IntelligenceID <= 0 {
invalidParamRequestResponse(c, "invalid intelligence id")
return
}
if req.IntelligenceType != common.IntelligenceType_Project {
invalidParamRequestResponse(c, fmt.Sprintf("invalid intelligence type '%d'", req.IntelligenceType))
return
}
resp, err := appApplication.APPApplicationSVC.GetDraftIntelligenceInfo(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetUserRecentlyEditIntelligence .
// @router /api/intelligence_api/search/get_recently_edit_intelligence [POST]
func GetUserRecentlyEditIntelligence(ctx context.Context, c *app.RequestContext) {
var err error
var req intelligence.GetUserRecentlyEditIntelligenceRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(intelligence.GetUserRecentlyEditIntelligenceResponse)
c.JSON(consts.StatusOK, resp)
}
// DraftProjectCreate .
// @router /api/intelligence_api/draft_project/create [POST]
func DraftProjectCreate(ctx context.Context, c *app.RequestContext) {
var err error
var req project.DraftProjectCreateRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.SpaceID <= 0 {
invalidParamRequestResponse(c, "invalid space id")
return
}
if req.Name == "" || len(req.Name) > 256 {
invalidParamRequestResponse(c, "invalid name")
return
}
if req.IconURI == "" || len(req.IconURI) > 512 {
invalidParamRequestResponse(c, "invalid icon uri")
return
}
resp, err := appApplication.APPApplicationSVC.DraftProjectCreate(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DraftProjectUpdate .
// @router /api/intelligence_api/draft_project/update [POST]
func DraftProjectUpdate(ctx context.Context, c *app.RequestContext) {
var err error
var req project.DraftProjectUpdateRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.ProjectID <= 0 {
invalidParamRequestResponse(c, "invalid project id")
return
}
if req.Name != nil && (len(*req.Name) == 0 || len(*req.Name) > 256) {
invalidParamRequestResponse(c, "invalid name")
return
}
if req.IconURI != nil && (len(*req.IconURI) == 0 || len(*req.IconURI) > 512) {
invalidParamRequestResponse(c, "invalid icon uri")
return
}
resp, err := appApplication.APPApplicationSVC.DraftProjectUpdate(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DraftProjectDelete .
// @router /api/intelligence_api/draft_project/delete [POST]
func DraftProjectDelete(ctx context.Context, c *app.RequestContext) {
var err error
var req project.DraftProjectDeleteRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.ProjectID <= 0 {
invalidParamRequestResponse(c, "invalid project id")
return
}
resp, err := appApplication.APPApplicationSVC.DraftProjectDelete(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetProjectPublishedConnector .
// @router /api/intelligence_api/publish/get_published_connector [POST]
func GetProjectPublishedConnector(ctx context.Context, c *app.RequestContext) {
var err error
var req publish.GetProjectPublishedConnectorRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(publish.GetProjectPublishedConnectorResponse)
c.JSON(consts.StatusOK, resp)
}
// CheckProjectVersionNumber .
// @router /api/intelligence_api/publish/check_version_number [POST]
func CheckProjectVersionNumber(ctx context.Context, c *app.RequestContext) {
var err error
var req publish.CheckProjectVersionNumberRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.ProjectID <= 0 {
invalidParamRequestResponse(c, "invalid project id")
return
}
if req.VersionNumber == "" {
invalidParamRequestResponse(c, "invalid version number")
return
}
resp, err := appApplication.APPApplicationSVC.CheckProjectVersionNumber(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// PublishProject .
// @router /api/intelligence_api/publish/publish_project [POST]
func PublishProject(ctx context.Context, c *app.RequestContext) {
var err error
var req publish.PublishProjectRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.ProjectID <= 0 {
invalidParamRequestResponse(c, "invalid project id")
return
}
if req.VersionNumber == "" {
invalidParamRequestResponse(c, "invalid version number")
return
}
resp, err := appApplication.APPApplicationSVC.PublishAPP(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetPublishRecordList .
// @router /api/intelligence_api/publish/publish_record_list [POST]
func GetPublishRecordList(ctx context.Context, c *app.RequestContext) {
var err error
var req publish.GetPublishRecordListRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.ProjectID <= 0 {
invalidParamRequestResponse(c, "invalid project id")
return
}
resp, err := appApplication.APPApplicationSVC.GetPublishRecordList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ProjectPublishConnectorList .
// @router /api/intelligence_api/publish/connector_list [POST]
func ProjectPublishConnectorList(ctx context.Context, c *app.RequestContext) {
var err error
var req publish.PublishConnectorListRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.ProjectID <= 0 {
invalidParamRequestResponse(c, "invalid project id")
return
}
resp, err := appApplication.APPApplicationSVC.ProjectPublishConnectorList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetPublishRecordDetail .
// @router /api/intelligence_api/publish/publish_record_detail [POST]
func GetPublishRecordDetail(ctx context.Context, c *app.RequestContext) {
var err error
var req publish.GetPublishRecordDetailRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.ProjectID <= 0 {
invalidParamRequestResponse(c, "invalid project id")
return
}
if req.PublishRecordID != nil && *req.PublishRecordID <= 0 {
invalidParamRequestResponse(c, "invalid publish record id")
return
}
resp, err := appApplication.APPApplicationSVC.GetPublishRecordDetail(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DraftProjectInnerTaskList .
// @router /api/intelligence_api/draft_project/inner_task_list [POST]
func DraftProjectInnerTaskList(ctx context.Context, c *app.RequestContext) {
var err error
var req task.DraftProjectInnerTaskListRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.ProjectID <= 0 {
invalidParamRequestResponse(c, "invalid project id")
return
}
resp, err := appApplication.APPApplicationSVC.DraftProjectInnerTaskList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DraftProjectCopy .
// @router /api/intelligence_api/draft_project/copy [POST]
func DraftProjectCopy(ctx context.Context, c *app.RequestContext) {
var err error
var req project.DraftProjectCopyRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.ProjectID <= 0 {
invalidParamRequestResponse(c, "invalid project id")
return
}
if req.ToSpaceID <= 0 {
invalidParamRequestResponse(c, "invalid to space id")
return
}
if req.Name == "" || len(req.Name) > 256 {
invalidParamRequestResponse(c, "invalid name")
return
}
if req.IconURI == "" || len(req.IconURI) > 512 {
invalidParamRequestResponse(c, "invalid icon uri")
return
}
resp, err := appApplication.APPApplicationSVC.DraftProjectCopy(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetOnlineAppData .
// @router /v1/apps/:app_id [GET]
func GetOnlineAppData(ctx context.Context, c *app.RequestContext) {
var err error
var req project.GetOnlineAppDataRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp, err := appApplication.APPApplicationSVC.GetOnlineAppData(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
@@ -0,0 +1,770 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Code generated by hertz generator.
package coze
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol/consts"
dataset "github.com/coze-dev/coze-studio/backend/api/model/data/knowledge"
"github.com/coze-dev/coze-studio/backend/application/knowledge"
application "github.com/coze-dev/coze-studio/backend/application/knowledge"
"github.com/coze-dev/coze-studio/backend/application/memory"
"github.com/coze-dev/coze-studio/backend/application/upload"
)
// CreateDataset .
// @router /api/knowledge/create [POST]
func CreateDataset(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.CreateDatasetRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.CreateDatasetResponse)
resp, err = application.KnowledgeSVC.CreateKnowledge(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DatasetDetail .
// @router /api/knowledge/detail [POST]
func DatasetDetail(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.DatasetDetailRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.DatasetDetailResponse)
resp, err = application.KnowledgeSVC.DatasetDetail(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ListDataset .
// @router /api/knowledge/list [POST]
func ListDataset(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.ListDatasetRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.ListDatasetResponse)
resp, err = application.KnowledgeSVC.ListKnowledge(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DeleteDataset .
// @router /api/knowledge/delete [POST]
func DeleteDataset(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.DeleteDatasetRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.DeleteDatasetResponse)
resp, err = application.KnowledgeSVC.DeleteKnowledge(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// UpdateDataset .
// @router /api/knowledge/update [POST]
func UpdateDataset(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.UpdateDatasetRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.UpdateDatasetResponse)
resp, err = application.KnowledgeSVC.UpdateKnowledge(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// CreateDocument .
// @router /api/knowledge/document/create [POST]
func CreateDocument(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.CreateDocumentRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.CreateDocumentResponse)
resp, err = application.KnowledgeSVC.CreateDocument(ctx, &req, false)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ListDocument .
// @router /api/knowledge/document/list [POST]
func ListDocument(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.ListDocumentRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.ListDocumentResponse)
resp, err = application.KnowledgeSVC.ListDocument(ctx, &req, false)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DeleteDocument .
// @router /api/knowledge/document/delete [POST]
func DeleteDocument(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.DeleteDocumentRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.DeleteDocumentResponse)
resp, err = application.KnowledgeSVC.DeleteDocument(ctx, &req, false)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// UpdateDocument .
// @router /api/knowledge/document/update [POST]
func UpdateDocument(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.UpdateDocumentRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.UpdateDocumentResponse)
resp, err = application.KnowledgeSVC.UpdateDocument(ctx, &req, false)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetDocumentProgress .
// @router /api/knowledge/document/progress/get [POST]
func GetDocumentProgress(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.GetDocumentProgressRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.GetDocumentProgressResponse)
resp, err = application.KnowledgeSVC.GetDocumentProgress(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// Resegment .
// @router /api/knowledge/document/resegment [POST]
func Resegment(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.ResegmentRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.ResegmentResponse)
resp, err = application.KnowledgeSVC.Resegment(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// UpdatePhotoCaption .
// @router /api/knowledge/photo/caption [POST]
func UpdatePhotoCaption(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.UpdatePhotoCaptionRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.UpdatePhotoCaptionResponse)
resp, err = application.KnowledgeSVC.UpdatePhotoCaption(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ListPhoto .
// @router /api/knowledge/photo/list [POST]
func ListPhoto(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.ListPhotoRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.ListPhotoResponse)
resp, err = application.KnowledgeSVC.ListPhoto(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// PhotoDetail .
// @router /api/knowledge/photo/detail [POST]
func PhotoDetail(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.PhotoDetailRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.PhotoDetailResponse)
resp, err = application.KnowledgeSVC.PhotoDetail(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetTableSchema .
// @router /api/knowledge/table_schema/get [POST]
func GetTableSchema(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.GetTableSchemaRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.GetTableSchemaResponse)
resp, err = application.KnowledgeSVC.GetTableSchema(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ValidateTableSchema .
// @router /api/knowledge/table_schema/validate [POST]
func ValidateTableSchema(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.ValidateTableSchemaRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.ValidateTableSchemaResponse)
resp, err = application.KnowledgeSVC.ValidateTableSchema(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DeleteSlice .
// @router /api/knowledge/slice/delete [POST]
func DeleteSlice(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.DeleteSliceRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.DeleteSliceResponse)
resp, err = application.KnowledgeSVC.DeleteSlice(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// CreateSlice .
// @router /api/knowledge/slice/create [POST]
func CreateSlice(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.CreateSliceRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.CreateSliceResponse)
resp, err = application.KnowledgeSVC.CreateSlice(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// UpdateSlice .
// @router /api/knowledge/slice/update [POST]
func UpdateSlice(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.UpdateSliceRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.UpdateSliceResponse)
resp, err = application.KnowledgeSVC.UpdateSlice(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ListSlice .
// @router /api/knowledge/slice/list [POST]
func ListSlice(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.ListSliceRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.ListSliceResponse)
resp, err = application.KnowledgeSVC.ListSlice(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// CreateDocumentReview .
// @router /api/knowledge/review/create [POST]
func CreateDocumentReview(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.CreateDocumentReviewRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.CreateDocumentReviewResponse)
resp, err = application.KnowledgeSVC.CreateDocumentReview(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// MGetDocumentReview .
// @router /api/knowledge/review/mget [POST]
func MGetDocumentReview(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.MGetDocumentReviewRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.MGetDocumentReviewResponse)
resp, err = application.KnowledgeSVC.MGetDocumentReview(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// SaveDocumentReview .
// @router /api/knowledge/review/save [POST]
func SaveDocumentReview(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.SaveDocumentReviewRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.SaveDocumentReviewResponse)
resp, err = application.KnowledgeSVC.SaveDocumentReview(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetIconForDataset .
// @router /api/knowledge/icon/get [POST]
func GetIconForDataset(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.GetIconRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.GetIconResponse)
resp, err = upload.SVC.GetIconForDataset(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ExtractPhotoCaption .
// @router /api/knowledge/photo/extract_caption [POST]
func ExtractPhotoCaption(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.ExtractPhotoCaptionRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.ExtractPhotoCaptionResponse)
resp, err = application.KnowledgeSVC.ExtractPhotoCaption(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetDocumentTableInfo .
// @router /api/memory/doc_table_info [GET]
func GetDocumentTableInfo(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.GetDocumentTableInfoRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.GetDocumentTableInfoResponse)
resp, err = knowledge.KnowledgeSVC.GetDocumentTableInfo(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetModeConfig .
// @router /api/memory/table_mode_config [GET]
func GetModeConfig(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.GetModeConfigRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
if req.BotID == 0 {
invalidParamRequestResponse(c, "bot_id is zero")
return
}
resp, err := memory.DatabaseApplicationSVC.GetModeConfig(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// CreateDocumentOpenAPI .
// @router /open_api/knowledge/document/create [POST]
func CreateDocumentOpenAPI(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.CreateDocumentRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp := new(dataset.CreateDocumentResponse)
resp, err = application.KnowledgeSVC.CreateDocument(ctx, &req, true)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DeleteDocumentOpenAPI .
// @router /open_api/knowledge/document/delete [POST]
func DeleteDocumentOpenAPI(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.DeleteDocumentRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.DeleteDocumentResponse)
resp, err = application.KnowledgeSVC.DeleteDocument(ctx, &req, true)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// UpdateDocumentOpenAPI .
// @router /open_api/knowledge/document/update [POST]
func UpdateDocumentOpenAPI(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.UpdateDocumentRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.UpdateDocumentResponse)
resp, err = application.KnowledgeSVC.UpdateDocument(ctx, &req, true)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ListDocumentOpenAPI .
// @router /open_api/knowledge/document/list [POST]
func ListDocumentOpenAPI(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.ListDocumentRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(dataset.ListDocumentResponse)
resp, err = application.KnowledgeSVC.ListDocument(ctx, &req, true)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// CreateDatasetOpenAPI .
// @router /v1/datasets [POST]
func CreateDatasetOpenAPI(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.CreateDatasetOpenApiRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := application.KnowledgeSVC.CreateKnowledgeAPI(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ListDatasetOpenAPI .
// @router /v1/datasets [GET]
func ListDatasetOpenAPI(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.ListDatasetOpenApiRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := application.KnowledgeSVC.ListKnowledgeAPI(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// UpdateDatasetOpenAPI .
// @router /v1/datasets/:dataset_id [PUT]
func UpdateDatasetOpenAPI(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.UpdateDatasetOpenApiRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := application.KnowledgeSVC.UpdateKnowledgeAPI(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DeleteDatasetOpenAPI .
// @router /v1/datasets/:dataset_id [DELETE]
func DeleteDatasetOpenAPI(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.DeleteDatasetOpenApiRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := application.KnowledgeSVC.DeleteKnowledgeAPI(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ListPhotoDocumentOpenAPI .
// @router /v1/datasets/:dataset_id/images [GET]
func ListPhotoDocumentOpenAPI(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.ListPhotoOpenApiRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := application.KnowledgeSVC.ListPhotoAPI(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetDocumentProgressOpenAPI .
// @router /v1/datasets/:dataset_id/process [POST]
func GetDocumentProgressOpenAPI(ctx context.Context, c *app.RequestContext) {
var err error
var req dataset.GetDocumentProgressOpenApiRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := application.KnowledgeSVC.GetDocumentProgressAPI(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
+229
View File
@@ -0,0 +1,229 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Code generated by hertz generator.
package coze
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol/consts"
"github.com/coze-dev/coze-studio/backend/api/model/data/variable/kvmemory"
"github.com/coze-dev/coze-studio/backend/api/model/data/variable/project_memory"
appApplication "github.com/coze-dev/coze-studio/backend/application/app"
"github.com/coze-dev/coze-studio/backend/application/memory"
"github.com/coze-dev/coze-studio/backend/pkg/lang/conv"
)
// GetSysVariableConf .
// @router /api/memory/sys_variable_conf [GET]
func GetSysVariableConf(ctx context.Context, c *app.RequestContext) {
var err error
var req kvmemory.GetSysVariableConfRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp, err := memory.VariableApplicationSVC.GetSysVariableConf(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetProjectVariableList .
// @router /api/memory/project/variable/meta_list [GET]
func GetProjectVariableList(ctx context.Context, c *app.RequestContext) {
var err error
var req project_memory.GetProjectVariableListReq
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
if req.ProjectID == "" {
invalidParamRequestResponse(c, "project_id is empty")
return
}
pID, err := conv.StrToInt64(req.ProjectID)
if err != nil {
invalidParamRequestResponse(c, "project_id is not int")
return
}
pInfo, err := appApplication.APPApplicationSVC.DomainSVC.GetDraftAPP(ctx, pID)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
resp, err := memory.VariableApplicationSVC.GetProjectVariablesMeta(ctx, pInfo.OwnerID, &req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
c.JSON(consts.StatusOK, resp)
}
// UpdateProjectVariable .
// @router /api/memory/project/variable/meta_update [POST]
func UpdateProjectVariable(ctx context.Context, c *app.RequestContext) {
var err error
var req project_memory.UpdateProjectVariableReq
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
if req.ProjectID == "" {
invalidParamRequestResponse(c, "project_id is empty")
return
}
key2Var := make(map[string]*project_memory.Variable)
for _, v := range req.VariableList {
if v.Keyword == "" {
invalidParamRequestResponse(c, "variable name is empty")
return
}
if key2Var[v.Keyword] != nil {
invalidParamRequestResponse(c, "variable keyword is duplicate")
return
}
key2Var[v.Keyword] = v
}
resp, err := memory.VariableApplicationSVC.UpdateProjectVariable(ctx, req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// SetKvMemory .
// @router /api/memory/variable/upsert [POST]
func SetKvMemory(ctx context.Context, c *app.RequestContext) {
var err error
var req kvmemory.SetKvMemoryReq
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
if req.BotID == 0 && req.GetProjectID() == "" {
invalidParamRequestResponse(c, "bot_id and project_id are both empty")
return
}
if len(req.Data) == 0 {
invalidParamRequestResponse(c, "data is empty")
return
}
resp, err := memory.VariableApplicationSVC.SetVariableInstance(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetMemoryVariableMeta .
// @router /api/memory/variable/get_meta [POST]
func GetMemoryVariableMeta(ctx context.Context, c *app.RequestContext) {
var err error
var req project_memory.GetMemoryVariableMetaReq
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp, err := memory.VariableApplicationSVC.GetVariableMeta(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DelProfileMemory .
// @router /api/memory/variable/delete [POST]
func DelProfileMemory(ctx context.Context, c *app.RequestContext) {
var err error
var req kvmemory.DelProfileMemoryRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
if req.BotID == 0 && req.GetProjectID() == "" {
invalidParamRequestResponse(c, "bot_id and project_id are both empty")
return
}
resp, err := memory.VariableApplicationSVC.DeleteVariableInstance(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetPlayGroundMemory .
// @router /api/memory/variable/get [POST]
func GetPlayGroundMemory(ctx context.Context, c *app.RequestContext) {
var err error
var req kvmemory.GetProfileMemoryRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
if req.BotID == 0 && req.GetProjectID() == "" {
invalidParamRequestResponse(c, "bot_id and project_id are both empty")
return
}
resp, err := memory.VariableApplicationSVC.GetPlayGroundMemory(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
+170
View File
@@ -0,0 +1,170 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package coze
import (
"context"
"errors"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol/consts"
"github.com/coze-dev/coze-studio/backend/api/model/conversation/message"
application "github.com/coze-dev/coze-studio/backend/application/conversation"
"github.com/coze-dev/coze-studio/backend/pkg/errorx"
"github.com/coze-dev/coze-studio/backend/types/errno"
)
// GetMessageList .
// @router /api/conversation/get_message_list [POST]
func GetMessageList(ctx context.Context, c *app.RequestContext) {
var err error
var req message.GetMessageListRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if checkErr := checkMLParams(ctx, &req); checkErr != nil {
invalidParamRequestResponse(c, checkErr.Error())
return
}
resp, err := application.ConversationSVC.GetMessageList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
func checkMLParams(ctx context.Context, req *message.GetMessageListRequest) error {
if req.BotID == "" {
return errorx.New(errno.ErrConversationInvalidParamCode, errorx.KV("msg", "agent id is required"))
}
return nil
}
// DeleteMessage .
// @router /api/conversation/delete_message [POST]
func DeleteMessage(ctx context.Context, c *app.RequestContext) {
var err error
var req message.DeleteMessageRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if checkErr := checkDMParams(ctx, &req); checkErr != nil {
invalidParamRequestResponse(c, checkErr.Error())
return
}
resp, err := application.ConversationSVC.DeleteMessage(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
func checkDMParams(_ context.Context, req *message.DeleteMessageRequest) error {
if req.MessageID <= 0 {
return errorx.New(errno.ErrConversationInvalidParamCode, errorx.KV("msg", "message id is invalid"))
}
return nil
}
// BreakMessage .
// @router /api/conversation/break_message [POST]
func BreakMessage(ctx context.Context, c *app.RequestContext) {
var err error
var req message.BreakMessageRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if checkErr := checkBMParams(ctx, &req); checkErr != nil {
invalidParamRequestResponse(c, checkErr.Error())
return
}
resp, err := application.ConversationSVC.BreakMessage(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
func checkBMParams(_ context.Context, req *message.BreakMessageRequest) error {
if req.AnswerMessageID == nil {
return errors.New("answer message id is required")
}
if *req.AnswerMessageID <= 0 {
return errorx.New(errno.ErrConversationInvalidParamCode, errorx.KV("msg", "answer message id is invalid"))
}
return nil
}
// GetApiMessageList .
// @router /v1/conversation/message/list [POST]
func GetApiMessageList(ctx context.Context, c *app.RequestContext) {
var err error
var req message.ListMessageApiRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := application.OpenapiMessageSVC.GetApiMessageList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ListChatMessageApi .
// @router /v3/chat/message/list [GET]
func ListChatMessageApi(ctx context.Context, c *app.RequestContext) {
var err error
var req message.ListChatMessageApiRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := application.ConversationOpenAPISVC.ListChatMessageApi(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
@@ -0,0 +1,57 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package coze
import (
"bytes"
"context"
"net/http"
"testing"
"github.com/bytedance/sonic"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/common/ut"
"github.com/stretchr/testify/assert"
"github.com/coze-dev/coze-studio/backend/api/model/conversation/common"
"github.com/coze-dev/coze-studio/backend/api/model/conversation/message"
"github.com/coze-dev/coze-studio/backend/application"
"github.com/coze-dev/coze-studio/backend/pkg/lang/ptr"
)
func TestGetMessageList(t *testing.T) {
h := server.Default()
err := application.Init(context.Background())
t.Logf("application init err: %v", err)
h.POST("/api/conversation/get_message_list", GetMessageList)
req := &message.GetMessageListRequest{
BotID: "7366055842027922437",
Scene: ptr.Of(common.Scene_Playground),
ConversationID: "7496795464885338112",
Count: 10,
Cursor: "1746534530268",
}
m, err := sonic.Marshal(req)
assert.Nil(t, err)
w := ut.PerformRequest(h.Engine, "POST", "/api/conversation/get_message_list", &ut.Body{Body: bytes.NewBuffer(m), Len: len(m)}, ut.Header{Key: "Content-Type", Value: "application/json"})
res := w.Result()
t.Logf("get message list: %s", res.Body())
assert.Equal(t, http.StatusInternalServerError, w.Code)
}
@@ -0,0 +1,169 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Code generated by hertz generator.
package coze
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol/consts"
"github.com/coze-dev/coze-studio/backend/api/model/permission/openapiauth"
openapiauthApp "github.com/coze-dev/coze-studio/backend/application/openauth"
"github.com/coze-dev/coze-studio/backend/pkg/errorx"
"github.com/coze-dev/coze-studio/backend/pkg/lang/ptr"
"github.com/coze-dev/coze-studio/backend/pkg/logs"
"github.com/coze-dev/coze-studio/backend/types/errno"
)
// GetPersonalAccessTokenAndPermission .
// @router /api/permission_api/pat/get_personal_access_token_and_permission [GET]
func GetPersonalAccessTokenAndPermission(ctx context.Context, c *app.RequestContext) {
var err error
var req openapiauth.GetPersonalAccessTokenAndPermissionRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.ID == 0 {
invalidParamRequestResponse(c, "id is required")
return
}
resp, err := openapiauthApp.OpenAuthApplication.GetPersonalAccessTokenAndPermission(ctx, &req)
if err != nil {
logs.CtxErrorf(ctx, "OpenAuthApplicationService.GetPersonalAccessTokenAndPermission failed, err=%v", err)
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DeletePersonalAccessTokenAndPermission .
// @router /api/permission_api/pat/delete_personal_access_token_and_permission [POST]
func DeletePersonalAccessTokenAndPermission(ctx context.Context, c *app.RequestContext) {
var err error
var req openapiauth.DeletePersonalAccessTokenAndPermissionRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.ID <= 0 {
invalidParamRequestResponse(c, "id is required")
return
}
resp, err := openapiauthApp.OpenAuthApplication.DeletePersonalAccessTokenAndPermission(ctx, &req)
if err != nil {
logs.CtxErrorf(ctx, "OpenAuthApplication.DeletePersonalAccessTokenAndPermission failed, err=%v", err)
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ListPersonalAccessTokens .
// @router /api/permission_api/pat/list_personal_access_tokens [GET]
func ListPersonalAccessTokens(ctx context.Context, c *app.RequestContext) {
var err error
var req openapiauth.ListPersonalAccessTokensRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.Page == nil || *req.Page <= 0 {
req.Page = ptr.Of(int64(1))
}
if req.Size == nil || *req.Size <= 0 {
req.Size = ptr.Of(int64(10))
}
resp, err := openapiauthApp.OpenAuthApplication.ListPersonalAccessTokens(ctx, &req)
if err != nil {
logs.CtxErrorf(ctx, "OpenAuthApplication.ListPersonalAccessTokens failed, err=%v", err)
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// CreatePersonalAccessTokenAndPermission .
// @router /api/permission_api/pat/create_personal_access_token_and_permission [POST]
func CreatePersonalAccessTokenAndPermission(ctx context.Context, c *app.RequestContext) {
var err error
var req openapiauth.CreatePersonalAccessTokenAndPermissionRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if err = checkCPATParams(ctx, &req); err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := openapiauthApp.OpenAuthApplication.CreatePersonalAccessToken(ctx, &req)
if err != nil {
logs.CtxErrorf(ctx, "OpenAuthApplicationService.CreatePersonalAccessToken failed, err=%v", err)
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// checkCPATParams Check parameters for creating personal access tokens
func checkCPATParams(ctx context.Context, req *openapiauth.CreatePersonalAccessTokenAndPermissionRequest) error {
if req.Name == "" {
return errorx.New(errno.ErrPermissionInvalidParamCode, errorx.KV("msg", "name is required"))
}
return nil
}
// UpdatePersonalAccessTokenAndPermission .
// @router /api/permission_api/pat/update_personal_access_token_and_permission [POST]
func UpdatePersonalAccessTokenAndPermission(ctx context.Context, c *app.RequestContext) {
var err error
var req openapiauth.UpdatePersonalAccessTokenAndPermissionRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := openapiauthApp.OpenAuthApplication.UpdatePersonalAccessTokenAndPermission(ctx, &req)
if err != nil {
logs.CtxErrorf(ctx, "OpenAuthApplication.UpdatePersonalAccessTokenAndPermission failed, err=%v", err)
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
@@ -0,0 +1,220 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Code generated by hertz generator.
package coze
import (
"context"
"io"
"net/http"
"strings"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol"
"github.com/coze-dev/coze-studio/backend/api/model/passport"
"github.com/coze-dev/coze-studio/backend/application/user"
"github.com/coze-dev/coze-studio/backend/domain/user/entity"
"github.com/coze-dev/coze-studio/backend/pkg/hertzutil/domain"
"github.com/coze-dev/coze-studio/backend/pkg/i18n"
"github.com/coze-dev/coze-studio/backend/pkg/logs"
"github.com/coze-dev/coze-studio/backend/types/consts"
)
// PassportWebEmailRegisterV2Post .
// @router /passport/web/email/register/v2/ [POST]
func PassportWebEmailRegisterV2Post(ctx context.Context, c *app.RequestContext) {
var err error
var req passport.PassportWebEmailRegisterV2PostRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
locale := string(i18n.GetLocale(ctx))
resp, sessionKey, err := user.UserApplicationSVC.PassportWebEmailRegisterV2(ctx, locale, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.SetCookie(entity.SessionKey,
sessionKey,
consts.SessionMaxAgeSecond,
"/", domain.GetOriginHost(c),
protocol.CookieSameSiteDefaultMode,
false, true)
c.JSON(http.StatusOK, resp)
}
// PassportWebLogoutGet .
// @router /passport/web/logout/ [GET]
func PassportWebLogoutGet(ctx context.Context, c *app.RequestContext) {
var err error
var req passport.PassportWebLogoutGetRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(http.StatusBadRequest, err.Error())
return
}
resp, err := user.UserApplicationSVC.PassportWebLogoutGet(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(http.StatusOK, resp)
}
// PassportWebEmailLoginPost .
// @router /passport/web/email/login/ [POST]
func PassportWebEmailLoginPost(ctx context.Context, c *app.RequestContext) {
var err error
var req passport.PassportWebEmailLoginPostRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(http.StatusBadRequest, err.Error())
return
}
resp, sessionKey, err := user.UserApplicationSVC.PassportWebEmailLoginPost(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
logs.Infof("[PassportWebEmailLoginPost] sessionKey: %s", sessionKey)
c.SetCookie(entity.SessionKey,
sessionKey,
consts.SessionMaxAgeSecond,
"/", domain.GetOriginHost(c),
protocol.CookieSameSiteDefaultMode,
false, true)
c.JSON(http.StatusOK, resp)
}
// PassportWebEmailPasswordResetGet .
// @router /passport/web/email/password/reset/ [GET]
func PassportWebEmailPasswordResetGet(ctx context.Context, c *app.RequestContext) {
var err error
var req passport.PassportWebEmailPasswordResetGetRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(http.StatusBadRequest, err.Error())
return
}
resp, err := user.UserApplicationSVC.PassportWebEmailPasswordResetGet(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(http.StatusOK, resp)
}
// PassportAccountInfoV2 .
// @router /passport/account/info/v2/ [POST]
func PassportAccountInfoV2(ctx context.Context, c *app.RequestContext) {
var err error
var req passport.PassportAccountInfoV2Request
err = c.BindAndValidate(&req)
if err != nil {
c.String(http.StatusBadRequest, err.Error())
return
}
resp, err := user.UserApplicationSVC.PassportAccountInfoV2(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(http.StatusOK, resp)
}
// UserUpdateAvatar .
// @router web/user/update/upload_avatar/ [POST]
func UserUpdateAvatar(ctx context.Context, c *app.RequestContext) {
var err error
var req passport.UserUpdateAvatarRequest
// Get the uploaded file
file, err := c.FormFile("avatar")
if err != nil {
logs.CtxErrorf(ctx, "Get Avatar Fail failed, err=%v", err)
invalidParamRequestResponse(c, "missing avatar file")
return
}
// Check file type
if !strings.HasPrefix(file.Header.Get("Content-Type"), "image/") {
invalidParamRequestResponse(c, "invalid file type, only image allowed")
return
}
// Read file content
src, err := file.Open()
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
defer src.Close()
fileContent, err := io.ReadAll(src)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
req.Avatar = fileContent
mimeType := file.Header.Get("Content-Type")
resp, err := user.UserApplicationSVC.UserUpdateAvatar(ctx, mimeType, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(http.StatusOK, resp)
}
// UserUpdateProfile .
// @router api/user/update_profile [POST]
func UserUpdateProfile(ctx context.Context, c *app.RequestContext) {
var err error
var req passport.UserUpdateProfileRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(http.StatusBadRequest, err.Error())
return
}
resp, err := user.UserApplicationSVC.UserUpdateProfile(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(http.StatusOK, resp)
}
@@ -0,0 +1,373 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Code generated by hertz generator.
package coze
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol/consts"
"github.com/coze-dev/coze-studio/backend/api/model/playground"
appApplication "github.com/coze-dev/coze-studio/backend/application/app"
"github.com/coze-dev/coze-studio/backend/application/prompt"
"github.com/coze-dev/coze-studio/backend/application/shortcutcmd"
"github.com/coze-dev/coze-studio/backend/application/singleagent"
"github.com/coze-dev/coze-studio/backend/application/upload"
"github.com/coze-dev/coze-studio/backend/application/user"
)
// UpdateDraftBotInfoAgw .
// @router /api/playground_api/draftbot/update_draft_bot_info [POST]
func UpdateDraftBotInfoAgw(ctx context.Context, c *app.RequestContext) {
var req playground.UpdateDraftBotInfoAgwRequest
err := c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.BotInfo == nil {
invalidParamRequestResponse(c, "bot info is nil")
return
}
if req.BotInfo.BotId == nil {
invalidParamRequestResponse(c, "bot id is nil")
return
}
resp, err := singleagent.SingleAgentSVC.UpdateSingleAgentDraft(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetDraftBotInfoAgw .
// @router /api/playground_api/draftbot/get_draft_bot_info [POST]
func GetDraftBotInfoAgw(ctx context.Context, c *app.RequestContext) {
var err error
var req playground.GetDraftBotInfoAgwRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.BotID == 0 {
invalidParamRequestResponse(c, "bot id is nil")
return
}
resp, err := singleagent.SingleAgentSVC.GetAgentBotInfo(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetOfficialPromptResourceList .
// @router /api/playground_api/get_official_prompt_list [POST]
func GetOfficialPromptResourceList(ctx context.Context, c *app.RequestContext) {
var err error
var req playground.GetOfficialPromptResourceListRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := prompt.PromptSVC.GetOfficialPromptResourceList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetPromptResourceInfo .
// @router /api/playground_api/get_prompt_resource_info [GET]
func GetPromptResourceInfo(ctx context.Context, c *app.RequestContext) {
var err error
var req playground.GetPromptResourceInfoRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := prompt.PromptSVC.GetPromptResourceInfo(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// UpsertPromptResource .
// @router /api/playground_api/upsert_prompt_resource [POST]
func UpsertPromptResource(ctx context.Context, c *app.RequestContext) {
var err error
var req playground.UpsertPromptResourceRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.Prompt == nil {
invalidParamRequestResponse(c, "prompt is nil")
return
}
if req.Prompt.GetSpaceID() <= 0 {
invalidParamRequestResponse(c, "space id is invalid")
return
}
if len(req.Prompt.GetName()) <= 0 {
invalidParamRequestResponse(c, "name is empty")
return
}
resp, err := prompt.PromptSVC.UpsertPromptResource(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DeletePromptResource .
// @router /api/playground_api/delete_prompt_resource [POST]
func DeletePromptResource(ctx context.Context, c *app.RequestContext) {
var err error
var req playground.DeletePromptResourceRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := prompt.PromptSVC.DeletePromptResource(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetSpaceListV2 .
// @router /api/playground_api/space/list [POST]
func GetSpaceListV2(ctx context.Context, c *app.RequestContext) {
var err error
var req playground.GetSpaceListV2Request
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := user.UserApplicationSVC.GetSpaceListV2(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetImagexShortUrl .
// @router /api/playground_api/get_imagex_url [POST]
func GetImagexShortUrl(ctx context.Context, c *app.RequestContext) {
var err error
var req playground.GetImagexShortUrlRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if len(req.Uris) == 0 {
invalidParamRequestResponse(c, "uris is empty")
return
}
resp, err := singleagent.SingleAgentSVC.GetImagexShortUrl(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// MGetUserBasicInfo .
// @router /api/playground_api/mget_user_info [POST]
func MGetUserBasicInfo(ctx context.Context, c *app.RequestContext) {
var err error
var req playground.MGetUserBasicInfoRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := user.UserApplicationSVC.MGetUserBasicInfo(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetBotPopupInfo .
// @router /api/playground_api/operate/get_bot_popup_info [POST]
func GetBotPopupInfo(ctx context.Context, c *app.RequestContext) {
var err error
var req playground.GetBotPopupInfoRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if len(req.BotPopupTypes) == 0 {
invalidParamRequestResponse(c, "bot popup types is empty")
return
}
resp, err := singleagent.SingleAgentSVC.GetAgentPopupInfo(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// UpdateBotPopupInfo .
// @router /api/playground_api/operate/update_bot_popup_info [POST]
func UpdateBotPopupInfo(ctx context.Context, c *app.RequestContext) {
var err error
var req playground.UpdateBotPopupInfoRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := singleagent.SingleAgentSVC.UpdateAgentPopupInfo(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// CreateUpdateShortcutCommand .
// @router /api/playground_api/create_update_shortcut_command [POST]
func CreateUpdateShortcutCommand(ctx context.Context, c *app.RequestContext) {
var err error
var req playground.CreateUpdateShortcutCommandRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
shortCuts, err := shortcutcmd.ShortcutCmdSVC.Handler(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
resp := new(playground.CreateUpdateShortcutCommandResponse)
resp.Shortcuts = shortCuts
resp.Code = 0
resp.Msg = ""
c.JSON(consts.StatusOK, resp)
}
// ReportUserBehavior .
// @router /api/playground_api/report_user_behavior [POST]
func ReportUserBehavior(ctx context.Context, c *app.RequestContext) {
var err error
var req playground.ReportUserBehaviorRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.ResourceID <= 0 {
invalidParamRequestResponse(c, "resource id is invalid")
return
}
resp := new(playground.ReportUserBehaviorResponse)
if req.ResourceType == playground.SpaceResourceType_DraftBot {
resp, err = singleagent.SingleAgentSVC.ReportUserBehavior(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
} else if req.ResourceType == playground.SpaceResourceType_Project {
resp, err = appApplication.APPApplicationSVC.ReportUserBehavior(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
}
c.JSON(consts.StatusOK, resp)
}
// GetFileUrls .
// @router /api/playground_api/get_file_list [POST]
func GetFileUrls(ctx context.Context, c *app.RequestContext) {
var err error
var req playground.GetFileUrlsRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
iconList, err := upload.SVC.GetShortcutIcons(ctx)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
resp := new(playground.GetFileUrlsResponse)
resp.FileList = iconList
resp.Code = 0
c.JSON(consts.StatusOK, resp)
}
@@ -0,0 +1,915 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Code generated by hertz generator.
package coze
import (
"context"
"regexp"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol/consts"
"github.com/coze-dev/coze-studio/backend/api/model/plugin_develop"
common "github.com/coze-dev/coze-studio/backend/api/model/plugin_develop/common"
"github.com/coze-dev/coze-studio/backend/application/plugin"
appworkflow "github.com/coze-dev/coze-studio/backend/application/workflow"
)
// GetPlaygroundPluginList .
// @router /api/plugin_api/get_playground_plugin_list [POST]
func GetPlaygroundPluginList(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.GetPlaygroundPluginListRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.GetSpaceID() <= 0 {
invalidParamRequestResponse(c, "spaceID is invalid")
return
}
if req.GetPage() <= 0 {
invalidParamRequestResponse(c, "page is invalid")
return
}
if req.GetSize() >= 30 {
invalidParamRequestResponse(c, "size is invalid")
return
}
// when there is only one element in the types list, and the element type is workflow, use workflow service
// TODO Figure out when there are multiple values for types
if len(req.GetPluginTypes()) == 1 && req.GetPluginTypes()[0] == int32(common.PluginType_WORKFLOW) {
resp, err := appworkflow.SVC.GetPlaygroundPluginList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
return
}
resp, err := plugin.PluginApplicationSVC.GetPlaygroundPluginList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// RegisterPluginMeta .
// @router /api/plugin_api/register_plugin_meta [POST]
func RegisterPluginMeta(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.RegisterPluginMetaRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.GetName() == "" {
invalidParamRequestResponse(c, "plugin name is invalid")
return
}
if req.GetDesc() == "" {
invalidParamRequestResponse(c, "plugin desc is invalid")
return
}
if req.URL != nil && (*req.URL == "" || len(*req.URL) > 512) {
invalidParamRequestResponse(c, "plugin url is invalid")
return
}
if req.Icon == nil || req.Icon.URI == "" || len(req.Icon.URI) > 512 {
invalidParamRequestResponse(c, "plugin icon is invalid")
return
}
if req.AuthType == nil {
invalidParamRequestResponse(c, "plugin auth type is invalid")
return
}
if req.SpaceID <= 0 {
invalidParamRequestResponse(c, "spaceID is invalid")
return
}
if req.ProjectID != nil {
if *req.ProjectID <= 0 {
invalidParamRequestResponse(c, "projectID is invalid")
return
}
}
if req.GetPluginType() != common.PluginType_PLUGIN {
invalidParamRequestResponse(c, "plugin type is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.RegisterPluginMeta(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetPluginAPIs .
// @router /api/plugin_api/get_plugin_apis [POST]
func GetPluginAPIs(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.GetPluginAPIsRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.PluginID <= 0 {
invalidParamRequestResponse(c, "pluginID is invalid")
return
}
if len(req.APIIds) == 0 {
if req.Page <= 0 {
invalidParamRequestResponse(c, "page is invalid")
return
}
if req.Size >= 30 {
invalidParamRequestResponse(c, "size is invalid")
return
}
}
resp, err := plugin.PluginApplicationSVC.GetPluginAPIs(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetPluginInfo .
// @router /api/plugin_api/get_plugin_info [POST]
func GetPluginInfo(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.GetPluginInfoRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.PluginID <= 0 {
invalidParamRequestResponse(c, "pluginID is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.GetPluginInfo(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetUpdatedAPIs .
// @router /api/plugin_api/get_updated_apis [POST]
func GetUpdatedAPIs(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.GetUpdatedAPIsRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.PluginID <= 0 {
invalidParamRequestResponse(c, "pluginID is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.GetUpdatedAPIs(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetOAuthStatus .
// @router /api/plugin_api/get_oauth_status [POST]
func GetOAuthStatus(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.GetOAuthStatusRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.PluginID <= 0 {
invalidParamRequestResponse(c, "pluginID is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.GetOAuthStatus(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// CheckAndLockPluginEdit .
// @router /api/plugin_api/check_and_lock_plugin_edit [POST]
func CheckAndLockPluginEdit(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.CheckAndLockPluginEditRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.PluginID <= 0 {
invalidParamRequestResponse(c, "pluginID is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.CheckAndLockPluginEdit(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// UpdatePlugin .
// @router /api/plugin_api/update [POST]
func UpdatePlugin(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.UpdatePluginRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.PluginID <= 0 {
invalidParamRequestResponse(c, "pluginID is invalid")
return
}
if req.AiPlugin == "" {
invalidParamRequestResponse(c, "plugin manifest is invalid")
return
}
if req.Openapi == "" {
invalidParamRequestResponse(c, "plugin openapi doc is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.UpdatePlugin(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DeleteAPI .
// @router /api/plugin_api/delete_api [POST]
func DeleteAPI(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.DeleteAPIRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.PluginID <= 0 {
invalidParamRequestResponse(c, "pluginID is invalid")
return
}
if req.APIID <= 0 {
invalidParamRequestResponse(c, "apiID is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.DeleteAPI(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DelPlugin .
// @router /api/plugin_api/del_plugin [POST]
func DelPlugin(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.DelPluginRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.PluginID <= 0 {
invalidParamRequestResponse(c, "pluginID is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.DelPlugin(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// PublishPlugin .
// @router /api/plugin_api/publish_plugin [POST]
func PublishPlugin(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.PublishPluginRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.PluginID <= 0 {
invalidParamRequestResponse(c, "pluginID is invalid")
return
}
if req.VersionName == "" || len(req.VersionName) > 255 {
invalidParamRequestResponse(c, "version name is invalid")
return
}
match, _ := regexp.MatchString(`^v\d+\.\d+\.\d+$`, req.VersionName)
if !match {
invalidParamRequestResponse(c, "version name is invalid")
return
}
if req.VersionDesc == "" {
invalidParamRequestResponse(c, "version desc is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.PublishPlugin(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// UpdatePluginMeta .
// @router /api/plugin_api/update_plugin_meta [POST]
func UpdatePluginMeta(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.UpdatePluginMetaRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.PluginID <= 0 {
invalidParamRequestResponse(c, "pluginID is invalid")
return
}
if req.Name != nil && *req.Name == "" {
invalidParamRequestResponse(c, "plugin name is invalid")
return
}
if req.Desc != nil && *req.Desc == "" {
invalidParamRequestResponse(c, "plugin desc is invalid")
return
}
if req.URL != nil && (*req.URL == "" || len(*req.URL) > 512) {
invalidParamRequestResponse(c, "plugin server url is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.UpdatePluginMeta(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetBotDefaultParams .
// @router /api/plugin_api/get_bot_default_params [POST]
func GetBotDefaultParams(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.GetBotDefaultParamsRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.SpaceID <= 0 {
invalidParamRequestResponse(c, "spaceID is invalid")
return
}
if req.BotID <= 0 {
invalidParamRequestResponse(c, "botID is invalid")
return
}
if req.PluginID <= 0 {
invalidParamRequestResponse(c, "pluginID is invalid")
return
}
if req.APIName == "" {
invalidParamRequestResponse(c, "apiName is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.GetBotDefaultParams(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// UpdateBotDefaultParams .
// @router /api/plugin_api/update_bot_default_params [POST]
func UpdateBotDefaultParams(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.UpdateBotDefaultParamsRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.SpaceID <= 0 {
invalidParamRequestResponse(c, "spaceID is invalid")
return
}
if req.BotID <= 0 {
invalidParamRequestResponse(c, "botID is invalid")
return
}
if req.PluginID <= 0 {
invalidParamRequestResponse(c, "pluginID is invalid")
return
}
if req.APIName == "" {
invalidParamRequestResponse(c, "apiName is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.UpdateBotDefaultParams(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// CreateAPI .
// @router /api/plugin_api/create_api [POST]
func CreateAPI(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.CreateAPIRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.PluginID <= 0 {
invalidParamRequestResponse(c, "pluginID is invalid")
return
}
if req.Name == "" || len(req.Name) > 255 {
invalidParamRequestResponse(c, "api name is invalid")
return
}
if req.Desc == "" {
invalidParamRequestResponse(c, "api desc is invalid")
return
}
if req.Path != nil && (*req.Path == "" || len(*req.Path) > 512) {
invalidParamRequestResponse(c, "api path is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.CreateAPI(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// UpdateAPI .
// @router /api/plugin_api/update_api [POST]
func UpdateAPI(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.UpdateAPIRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.PluginID <= 0 {
invalidParamRequestResponse(c, "pluginID is invalid")
return
}
if req.APIID <= 0 {
invalidParamRequestResponse(c, "apiID is invalid")
return
}
if req.Name != nil && (*req.Name == "" || len(*req.Name) > 255) {
invalidParamRequestResponse(c, "api name is invalid")
return
}
if req.Desc != nil && (*req.Desc == "" || len(*req.Desc) > 255) {
invalidParamRequestResponse(c, "api desc is invalid")
return
}
if req.Path != nil && (*req.Path == "" || len(*req.Path) > 512) {
invalidParamRequestResponse(c, "api path is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.UpdateAPI(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetUserAuthority .
// @router /api/plugin_api/get_user_authority [POST]
func GetUserAuthority(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.GetUserAuthorityRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.PluginID <= 0 {
invalidParamRequestResponse(c, "pluginID is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.GetUserAuthority(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// DebugAPI .
// @router /api/plugin_api/debug_api [POST]
func DebugAPI(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.DebugAPIRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.PluginID <= 0 {
invalidParamRequestResponse(c, "pluginID is invalid")
return
}
if req.APIID <= 0 {
invalidParamRequestResponse(c, "apiID is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.DebugAPI(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// UnlockPluginEdit .
// @router /api/plugin_api/unlock_plugin_edit [POST]
func UnlockPluginEdit(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.UnlockPluginEditRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := plugin.PluginApplicationSVC.UnlockPluginEdit(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetPluginNextVersion .
// @router /api/plugin_api/get_plugin_next_version [POST]
func GetPluginNextVersion(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.GetPluginNextVersionRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := plugin.PluginApplicationSVC.GetPluginNextVersion(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// RegisterPlugin .
// @router /api/developer/register [POST]
func RegisterPlugin(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.RegisterPluginRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.GetSpaceID() <= 0 {
invalidParamRequestResponse(c, "spaceID is invalid")
return
}
if req.ProjectID != nil && *req.ProjectID <= 0 {
invalidParamRequestResponse(c, "projectID is invalid")
return
}
if req.AiPlugin == "" {
invalidParamRequestResponse(c, "plugin manifest is invalid")
return
}
if req.Openapi == "" {
invalidParamRequestResponse(c, "plugin openapi doc is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.RegisterPlugin(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetDevPluginList .
// @router /api/plugin_api/get_dev_plugin_list [POST]
func GetDevPluginList(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.GetDevPluginListRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.SpaceID <= 0 {
invalidParamRequestResponse(c, "spaceID is invalid")
return
}
if req.ProjectID <= 0 {
invalidParamRequestResponse(c, "projectID is invalid")
return
}
if req.GetPage() <= 0 {
invalidParamRequestResponse(c, "page is invalid")
return
}
if req.GetSize() <= 0 {
invalidParamRequestResponse(c, "size is invalid")
return
}
if req.GetSize() > 50 {
invalidParamRequestResponse(c, "size is too large")
return
}
resp, err := plugin.PluginApplicationSVC.GetDevPluginList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// Convert2OpenAPI .
// @router /api/plugin_api/convert_to_openapi [POST]
func Convert2OpenAPI(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.Convert2OpenAPIRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.SpaceID <= 0 {
invalidParamRequestResponse(c, "spaceID is invalid")
return
}
if req.Data == "" {
invalidParamRequestResponse(c, "data is invalid")
return
}
if req.PluginURL != nil && *req.PluginURL == "" {
invalidParamRequestResponse(c, "pluginURL is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.Convert2OpenAPI(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetOAuthSchemaAPI .
// @router /api/plugin_api/get_oauth_schema [POST]
func GetOAuthSchemaAPI(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.GetOAuthSchemaRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := plugin.PluginApplicationSVC.GetOAuthSchema(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetOAuthSchema .
// @router /api/plugin/get_oauth_schema [POST]
func GetOAuthSchema(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.GetOAuthSchemaRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := plugin.PluginApplicationSVC.GetOAuthSchema(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// BatchCreateAPI .
// @router /api/plugin_api/batch_create_api [POST]
func BatchCreateAPI(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.BatchCreateAPIRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.SpaceID <= 0 {
invalidParamRequestResponse(c, "spaceID is invalid")
return
}
if req.PluginID <= 0 {
invalidParamRequestResponse(c, "pluginID is invalid")
return
}
if req.AiPlugin == "" {
invalidParamRequestResponse(c, "plugin manifest is invalid")
return
}
if req.Openapi == "" {
invalidParamRequestResponse(c, "plugin openapi doc is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.BatchCreateAPI(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// RevokeAuthToken .
// @router /api/plugin_api/revoke_auth_token [POST]
func RevokeAuthToken(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.RevokeAuthTokenRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.PluginID <= 0 {
invalidParamRequestResponse(c, "pluginID is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.RevokeAuthToken(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// GetQueriedOAuthPluginList .
// @router /api/plugin_api/get_queried_oauth_plugins [POST]
func GetQueriedOAuthPluginList(ctx context.Context, c *app.RequestContext) {
var err error
var req plugin_develop.GetQueriedOAuthPluginListRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.BotID <= 0 {
invalidParamRequestResponse(c, "entityID is required")
return
}
resp, err := plugin.PluginApplicationSVC.GetQueriedOAuthPluginList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
@@ -0,0 +1,420 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Code generated by hertz generator.
package coze
import (
"context"
"fmt"
"strconv"
"strings"
product_public_api "github.com/coze-dev/coze-studio/backend/api/model/marketplace/product_public_api"
"github.com/coze-dev/coze-studio/backend/api/model/workflow"
appworkflow "github.com/coze-dev/coze-studio/backend/application/workflow"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol/consts"
"github.com/coze-dev/coze-studio/backend/api/model/app/developer_api"
"github.com/coze-dev/coze-studio/backend/api/model/app/bot_common"
"github.com/coze-dev/coze-studio/backend/api/model/marketplace/product_common"
"github.com/coze-dev/coze-studio/backend/api/model/playground"
appApplication "github.com/coze-dev/coze-studio/backend/application/app"
"github.com/coze-dev/coze-studio/backend/application/modelmgr"
"github.com/coze-dev/coze-studio/backend/application/plugin"
"github.com/coze-dev/coze-studio/backend/application/search"
"github.com/coze-dev/coze-studio/backend/application/singleagent"
"github.com/coze-dev/coze-studio/backend/application/template"
"github.com/coze-dev/coze-studio/backend/pkg/logs"
)
// PublicGetProductList .
// @router /api/marketplace/product/list [GET]
func PublicGetProductList(ctx context.Context, c *app.RequestContext) {
var err error
var req product_public_api.GetProductListRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
var resp *product_public_api.GetProductListResponse
switch req.GetEntityType() {
case product_common.ProductEntityType_Plugin:
resp, err = plugin.PluginApplicationSVC.PublicGetProductList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
case product_common.ProductEntityType_TemplateCommon:
resp, err = template.ApplicationSVC.PublicGetProductList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
case product_common.ProductEntityType_SaasPlugin:
resp, err = plugin.PluginApplicationSVC.GetCozeSaasPluginList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
}
c.JSON(consts.StatusOK, resp)
}
// PublicGetProductDetail .
// @router /api/marketplace/product/detail [GET]
func PublicGetProductDetail(ctx context.Context, c *app.RequestContext) {
var err error
var req product_public_api.GetProductDetailRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.GetProductID() <= 0 {
invalidParamRequestResponse(c, "productID is invalid")
return
}
resp, err := plugin.PluginApplicationSVC.PublicGetProductDetail(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// PublicFavoriteProduct .
// @router /api/marketplace/product/favorite [POST]
func PublicFavoriteProduct(ctx context.Context, c *app.RequestContext) {
var err error
var req product_public_api.FavoriteProductRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.GetEntityID() <= 0 {
invalidParamRequestResponse(c, "entityID is invalid")
return
}
// check entity id is valid
if req.GetEntityType() == product_common.ProductEntityType_Bot {
_, err = singleagent.SingleAgentSVC.ValidateAgentDraftAccess(ctx, req.GetEntityID())
} else if req.GetEntityType() == product_common.ProductEntityType_Project {
_, err = appApplication.APPApplicationSVC.ValidateDraftAPPAccess(ctx, req.GetEntityID())
}
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
resp, err := search.SearchSVC.PublicFavoriteProduct(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// PublicGetUserFavoriteListV2 .
// @router /api/marketplace/product/favorite/list.v2 [GET]
func PublicGetUserFavoriteListV2(ctx context.Context, c *app.RequestContext) {
var err error
var req product_public_api.GetUserFavoriteListV2Request
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.GetPageSize() <= 0 {
invalidParamRequestResponse(c, "pageSize is invalid")
return
}
if req.GetEntityType() <= 0 {
invalidParamRequestResponse(c, "entityType is invalid")
return
}
resp, err := search.SearchSVC.PublicGetUserFavoriteList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// PublicDuplicateProduct .
// @router /api/marketplace/product/duplicate [POST]
func PublicDuplicateProduct(ctx context.Context, c *app.RequestContext) {
var err error
var req product_public_api.DuplicateProductRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp := new(product_public_api.DuplicateProductResponse)
resp.Data = new(product_public_api.DuplicateProductData)
switch req.GetEntityType() {
case product_common.ProductEntityType_BotTemplate:
modelListResp, err := modelmgr.ModelmgrApplicationSVC.GetModelList(ctx, &developer_api.GetTypeListRequest{})
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
if modelListResp == nil || modelListResp.Data == nil || len(modelListResp.Data.ModelList) == 0 {
invalidParamRequestResponse(c, "no model found")
return
}
bot, err := singleagent.SingleAgentSVC.DuplicateDraftBot(ctx, &developer_api.DuplicateDraftBotRequest{
BotID: req.GetProductID(),
SpaceID: req.GetSpaceID(),
})
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
botInfo, err := singleagent.SingleAgentSVC.GetAgentBotInfo(ctx, &playground.GetDraftBotInfoAgwRequest{
BotID: bot.Data.BotID,
})
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
if botInfo.Data == nil || botInfo.Data.BotInfo == nil {
invalidParamRequestResponse(c, "no bot info found")
return
}
modelInfo := botInfo.GetData().GetBotInfo().ModelInfo
if modelInfo == nil {
invalidParamRequestResponse(c, "no model info found in agent")
return
}
modelInfo.ModelId = &modelListResp.Data.ModelList[0].ModelType
if req.Name != nil {
_, err = singleagent.SingleAgentSVC.UpdateSingleAgentDraft(ctx, &playground.UpdateDraftBotInfoAgwRequest{
BotInfo: &bot_common.BotInfoForUpdate{
BotId: &bot.Data.BotID,
Name: req.Name,
ModelInfo: modelInfo,
},
})
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
}
resp.Data.NewEntityID = bot.Data.BotID
case product_common.ProductEntityType_WorkflowTemplateV2:
workflowResp, err := appworkflow.SVC.CopyWorkflow(ctx, &workflow.CopyWorkflowRequest{
WorkflowID: strconv.FormatInt(req.GetProductID(), 10),
SpaceID: strconv.FormatInt(req.GetSpaceID(), 10),
})
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
newWorkflowID, err := strconv.ParseInt(workflowResp.Data.WorkflowID, 10, 64)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
resp.Data.NewEntityID = newWorkflowID
resp.Data.NewPluginID = &newWorkflowID
if req.Name != nil {
_, err = appworkflow.SVC.UpdateWorkflowMeta(ctx, &workflow.UpdateWorkflowMetaRequest{
WorkflowID: workflowResp.Data.WorkflowID,
SpaceID: strconv.FormatInt(req.GetSpaceID(), 10),
Name: req.Name,
})
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
}
}
c.JSON(consts.StatusOK, resp)
}
// PublicSearchProduct .
// @router /api/marketplace/product/search [GET]
func PublicSearchProduct(ctx context.Context, c *app.RequestContext) {
var err error
var req product_public_api.SearchProductRequest
var categoryIDs []int64
if categoryIDsStr := string(c.Query("category_ids")); categoryIDsStr != "" {
categoryIDs, err = handlerCategoryIDs(c, &req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
c.Request.URI().QueryArgs().Del("category_ids")
}
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if len(categoryIDs) > 0 {
req.CategoryIDs = categoryIDs
}
// Call plugin application service
resp, err := plugin.PluginApplicationSVC.PublicSearchProduct(ctx, &req)
if err != nil {
logs.CtxErrorf(ctx, "PublicSearchProduct failed: %v", err)
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
func handlerCategoryIDs(c *app.RequestContext, req *product_public_api.SearchProductRequest) ([]int64, error) {
var categoryIDs []int64
if categoryIDsStr := string(c.Query("category_ids")); categoryIDsStr != "" {
categoryIDStrs := strings.Split(categoryIDsStr, ",")
categoryIDs = make([]int64, 0, len(categoryIDStrs))
for _, idStr := range categoryIDStrs {
idStr = strings.TrimSpace(idStr)
if idStr != "" {
// Validate that it's a valid integer
if categoryID, parseErr := strconv.ParseInt(idStr, 10, 64); parseErr == nil {
categoryIDs = append(categoryIDs, categoryID)
} else {
return nil, fmt.Errorf("invalid category_id: %s", idStr)
}
}
}
}
return categoryIDs, nil
}
// PublicSearchSuggest .
// @router /api/marketplace/product/search/suggest [GET]
func PublicSearchSuggest(ctx context.Context, c *app.RequestContext) {
var err error
var req product_public_api.SearchSuggestRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
// Call plugin application service
resp, err := plugin.PluginApplicationSVC.PublicSearchSuggest(ctx, &req)
if err != nil {
logs.CtxErrorf(ctx, "PublicSearchSuggest failed: %v", err)
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// PublicGetProductCategoryList .
// @router /api/marketplace/product/category/list [GET]
func PublicGetProductCategoryList(ctx context.Context, c *app.RequestContext) {
var err error
var req product_public_api.GetProductCategoryListRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
var resp *product_public_api.GetProductCategoryListResponse
req.EntityType = product_common.ProductEntityType_SaasPlugin
switch req.GetEntityType() {
case product_common.ProductEntityType_SaasPlugin:
resp, err = plugin.PluginApplicationSVC.GetSaasProductCategoryList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
}
c.JSON(consts.StatusOK, resp)
}
// PublicGetProductCallInfo .
// @router /api/marketplace/product/call_info [GET]
func PublicGetProductCallInfo(ctx context.Context, c *app.RequestContext) {
var err error
var req product_public_api.GetProductCallInfoRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := plugin.PluginApplicationSVC.GetProductCallInfo(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// PublicGetMarketPluginConfig .
// @router /api/marketplace/product/config [GET]
func PublicGetMarketPluginConfig(ctx context.Context, c *app.RequestContext) {
var err error
var req product_public_api.GetMarketPluginConfigRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp, err := plugin.PluginApplicationSVC.GetMarketPluginConfig(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
@@ -0,0 +1,179 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Code generated by hertz generator.
package coze
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol/consts"
appApplication "github.com/coze-dev/coze-studio/backend/application/app"
resource "github.com/coze-dev/coze-studio/backend/api/model/resource"
"github.com/coze-dev/coze-studio/backend/application/search"
)
// LibraryResourceList .
// @router /api/plugin_api/library_resource_list [POST]
func LibraryResourceList(ctx context.Context, c *app.RequestContext) {
var err error
var req resource.LibraryResourceListRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.SpaceID <= 0 {
invalidParamRequestResponse(c, "space_id is invalid")
return
}
if req.GetSize() > 100 {
invalidParamRequestResponse(c, "size is too large")
return
}
resp, err := search.SearchSVC.LibraryResourceList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ProjectResourceList .
// @router /api/plugin_api/project_resource_list [POST]
func ProjectResourceList(ctx context.Context, c *app.RequestContext) {
var err error
var req resource.ProjectResourceListRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.SpaceID <= 0 {
invalidParamRequestResponse(c, "space_id is invalid")
return
}
if req.ProjectID <= 0 {
invalidParamRequestResponse(c, "project_id is invalid")
return
}
resp, err := search.SearchSVC.ProjectResourceList(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ResourceCopyDispatch .
// @router /api/plugin_api/resource_copy_dispatch [POST]
func ResourceCopyDispatch(ctx context.Context, c *app.RequestContext) {
var err error
var req resource.ResourceCopyDispatchRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.ResID <= 0 {
invalidParamRequestResponse(c, "res_id is invalid")
return
}
if req.ResType <= 0 {
invalidParamRequestResponse(c, "res_type is invalid")
return
}
if req.GetProjectID() <= 0 {
invalidParamRequestResponse(c, "project_id is invalid")
return
}
resp, err := appApplication.APPApplicationSVC.ResourceCopyDispatch(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ResourceCopyDetail .
// @router /api/plugin_api/resource_copy_detail [POST]
func ResourceCopyDetail(ctx context.Context, c *app.RequestContext) {
var err error
var req resource.ResourceCopyDetailRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
if req.TaskID == "" {
invalidParamRequestResponse(c, "task_id is invalid")
return
}
resp, err := appApplication.APPApplicationSVC.ResourceCopyDetail(ctx, &req)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ResourceCopyRetry .
// @router /api/plugin_api/resource_copy_retry [POST]
func ResourceCopyRetry(ctx context.Context, c *app.RequestContext) {
var err error
var req resource.ResourceCopyRetryRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp := new(resource.ResourceCopyRetryResponse)
c.JSON(consts.StatusOK, resp)
}
// ResourceCopyCancel .
// @router /api/plugin_api/resource_copy_cancel [POST]
func ResourceCopyCancel(ctx context.Context, c *app.RequestContext) {
var err error
var req resource.ResourceCopyCancelRequest
err = c.BindAndValidate(&req)
if err != nil {
c.String(consts.StatusBadRequest, err.Error())
return
}
resp := new(resource.ResourceCopyCancelResponse)
c.JSON(consts.StatusOK, resp)
}
@@ -0,0 +1,80 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Code generated by hertz generator.
package coze
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/protocol/consts"
upload "github.com/coze-dev/coze-studio/backend/api/model/file/upload"
uploadSVC "github.com/coze-dev/coze-studio/backend/application/upload"
"github.com/coze-dev/coze-studio/backend/pkg/lang/ptr"
)
// CommonUpload .
// @router /api/common/upload/*tos_uri [POST]
func CommonUpload(ctx context.Context, c *app.RequestContext) {
var err error
var req upload.CommonUploadRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
fullUrl := string(c.Request.URI().FullURI())
resp, err := uploadSVC.SVC.UploadFileCommon(ctx, &req, fullUrl)
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
c.JSON(consts.StatusOK, resp)
}
// ApplyUploadAction .
// @router /api/common/upload/apply_upload_action [GET]
func ApplyUploadAction(ctx context.Context, c *app.RequestContext) {
var err error
var req upload.ApplyUploadActionRequest
err = c.BindAndValidate(&req)
if err != nil {
invalidParamRequestResponse(c, err.Error())
return
}
resp := new(upload.ApplyUploadActionResponse)
host := c.Request.Host()
if ptr.From(req.Action) == "ApplyImageUpload" {
resp, err = uploadSVC.SVC.ApplyImageUpload(ctx, &req, string(host))
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
} else if ptr.From(req.Action) == "CommitImageUpload" {
resp, err = uploadSVC.SVC.CommitImageUpload(ctx, &req, string(host))
if err != nil {
internalServerErrorResponse(ctx, c, err)
return
}
}
c.JSON(consts.StatusOK, resp)
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,54 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package httputil
import (
"context"
"errors"
"net/http"
"github.com/cloudwego/hertz/pkg/app"
"github.com/coze-dev/coze-studio/backend/pkg/errorx"
"github.com/coze-dev/coze-studio/backend/pkg/logs"
)
type data struct {
Code int32 `json:"code"`
Msg string `json:"msg"`
}
func BadRequest(c *app.RequestContext, errMsg string) {
c.AbortWithStatusJSON(http.StatusBadRequest, data{Code: http.StatusBadRequest, Msg: errMsg})
}
func Unauthorized(c *app.RequestContext, errMsg string) {
c.AbortWithStatusJSON(http.StatusUnauthorized, data{Code: http.StatusUnauthorized, Msg: errMsg})
}
func InternalError(ctx context.Context, c *app.RequestContext, err error) {
var customErr errorx.StatusError
if errors.As(err, &customErr) && customErr.Code() != 0 {
logs.CtxWarnf(ctx, "[ErrorX] error: %v %v \n", customErr.Code(), err)
c.AbortWithStatusJSON(http.StatusOK, data{Code: customErr.Code(), Msg: customErr.Msg()})
return
}
logs.CtxErrorf(ctx, "[InternalError] error: %v \n", err)
c.AbortWithStatusJSON(http.StatusInternalServerError, data{Code: 500, Msg: "internal server error"})
}
+32
View File
@@ -0,0 +1,32 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package middleware
import (
"context"
"github.com/coze-dev/coze-studio/backend/pkg/ctxcache"
"github.com/cloudwego/hertz/pkg/app"
)
func ContextCacheMW() app.HandlerFunc {
return func(c context.Context, ctx *app.RequestContext) {
c = ctxcache.Init(c)
ctx.Next(c)
}
}
+34
View File
@@ -0,0 +1,34 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package middleware
import (
"context"
"github.com/cloudwego/hertz/pkg/app"
"github.com/coze-dev/coze-studio/backend/pkg/ctxcache"
"github.com/coze-dev/coze-studio/backend/types/consts"
)
func SetHostMW() app.HandlerFunc {
return func(c context.Context, ctx *app.RequestContext) {
ctxcache.Store(c, consts.HostKeyInCtx, string(ctx.Host()))
ctxcache.Store(c, consts.RequestSchemeKeyInCtx, string(ctx.GetRequest().Scheme()))
ctx.Next(c)
}
}
+53
View File
@@ -0,0 +1,53 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package middleware
import (
"context"
"strings"
"github.com/cloudwego/hertz/pkg/app"
"github.com/coze-dev/coze-studio/backend/domain/user/entity"
"github.com/coze-dev/coze-studio/backend/pkg/ctxcache"
"github.com/coze-dev/coze-studio/backend/pkg/i18n"
"github.com/coze-dev/coze-studio/backend/types/consts"
)
func I18nMW() app.HandlerFunc {
return func(c context.Context, ctx *app.RequestContext) {
session, ok := ctxcache.Get[*entity.Session](c, consts.SessionDataKeyInCtx)
if ok {
c = i18n.SetLocale(c, session.Locale)
ctx.Next(c)
return
}
acceptLanguage := string(ctx.Request.Header.Get("Accept-Language"))
locale := "en-US"
if acceptLanguage != "" {
languages := strings.Split(acceptLanguage, ",")
if len(languages) > 0 {
locale = languages[0]
}
}
c = i18n.SetLocale(c, locale)
ctx.Next(c)
}
}
+97
View File
@@ -0,0 +1,97 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package middleware
import (
"context"
"fmt"
"net/http"
"path/filepath"
"strings"
"time"
"unsafe"
"github.com/cloudwego/hertz/pkg/app"
"github.com/google/uuid"
"github.com/coze-dev/coze-studio/backend/pkg/i18n"
"github.com/coze-dev/coze-studio/backend/pkg/logs"
"github.com/coze-dev/coze-studio/backend/types/consts"
)
func AccessLogMW() app.HandlerFunc {
return func(c context.Context, ctx *app.RequestContext) {
start := time.Now()
ctx.Next(c)
status := ctx.Response.StatusCode()
path := bytesToString(ctx.Request.URI().PathOriginal())
latency := time.Since(start)
method := bytesToString(ctx.Request.Header.Method())
clientIP := ctx.ClientIP()
handlerPkgPath := strings.Split(ctx.HandlerName(), "/")
handleName := ""
if len(handlerPkgPath) > 0 {
handleName = handlerPkgPath[len(handlerPkgPath)-1]
}
requestType := ctx.GetInt32(RequestAuthTypeStr)
baseLog := fmt.Sprintf("| %s | %s | %d | %v | %s | %s | %v | %s | %d | %s",
string(ctx.GetRequest().Scheme()), ctx.Host(), status,
latency, clientIP, method, path, handleName, requestType, i18n.GetLocale(c))
switch {
case status >= http.StatusInternalServerError:
logs.CtxErrorf(c, "%s", baseLog)
case status >= http.StatusBadRequest:
logs.CtxWarnf(c, "%s", baseLog)
default:
urlQuery := ctx.Request.URI().QueryString()
reqBody := bytesToString(ctx.Request.Body())
respBody := bytesToString(ctx.Response.Body())
maxPrintLen := 3 * 1024
if len(respBody) > maxPrintLen {
respBody = respBody[:maxPrintLen]
}
if len(reqBody) > maxPrintLen {
reqBody = reqBody[:maxPrintLen]
}
requestAuthType := ctx.GetInt32(RequestAuthTypeStr)
if requestAuthType != int32(RequestAuthTypeStaticFile) && filepath.Ext(path) == "" {
logs.CtxInfof(c, "%s ", baseLog)
logs.CtxDebugf(c, "query : %s \nreq : %s \nresp: %s",
urlQuery, reqBody, respBody)
}
}
}
}
func SetLogIDMW() app.HandlerFunc {
return func(ctx context.Context, c *app.RequestContext) {
logID := uuid.New().String()
ctx = context.WithValue(ctx, consts.CtxLogIDKey, logID)
c.Header("X-Log-ID", logID)
c.Next(ctx)
}
}
func bytesToString(b []byte) string {
return *(*string)(unsafe.Pointer(&b)) // nolint
}
+161
View File
@@ -0,0 +1,161 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package middleware
import (
"context"
"crypto/md5"
"encoding/hex"
"regexp"
"strings"
"github.com/cloudwego/hertz/pkg/app"
"github.com/coze-dev/coze-studio/backend/api/internal/httputil"
"github.com/coze-dev/coze-studio/backend/application/openauth"
"github.com/coze-dev/coze-studio/backend/pkg/ctxcache"
"github.com/coze-dev/coze-studio/backend/pkg/errorx"
"github.com/coze-dev/coze-studio/backend/pkg/lang/conv"
"github.com/coze-dev/coze-studio/backend/pkg/logs"
"github.com/coze-dev/coze-studio/backend/types/consts"
"github.com/coze-dev/coze-studio/backend/types/errno"
)
const HeaderAuthorizationKey = "Authorization"
var needAuthPath = map[string]bool{
"/v3/chat": true,
"/v1/conversations": true,
"/v1/conversation/create": true,
"/v1/conversation/message/list": true,
"/v1/files/upload": true,
"/v1/workflow/run": true,
"/v1/workflow/stream_run": true,
"/v1/workflow/stream_resume": true,
"/v1/workflow/get_run_history": true,
"/v1/bot/get_online_info": true,
"/v1/workflows/chat": true,
"/v1/workflow/conversation/create": true,
"/v3/chat/cancel": true,
"/v1/conversation/retrieve": true,
"/v3/chat/retrieve": true,
"/v3/chat/message/list": true,
"/open_api/knowledge/document/delete": true,
"/open_api/knowledge/document/create": true,
"/open_api/knowledge/document/update": true,
"/open_api/knowledge/document/list": true,
"/v1/datasets": true,
}
var needAuthFunc = map[string]bool{
"^/v1/conversations/[0-9]+/clear$": true, // v1/conversations/:conversation_id/clear
"^/v1/bots/[0-9]+$": true,
"^/v1/conversations/[0-9]+$": true,
"^/v1/workflows/[0-9]+$": true,
"^/v1/apps/[0-9]+$": true,
"^/v1/datasets/[0-9]+$": true, // v1/datasets/:dataset_id
"^/v1/datasets/[0-9]+/images$": true, // v1/datasets/:dataset_id/images
"^/v1/datasets/[0-9]+/process$": true, // v1/datasets/:dataset_id/process
}
func parseBearerAuthToken(authHeader string) string {
if len(authHeader) == 0 {
return ""
}
parts := strings.Split(authHeader, "Bearer")
if len(parts) != 2 {
return ""
}
token := strings.TrimSpace(parts[1])
if len(token) == 0 {
return ""
}
return token
}
func isNeedOpenapiAuth(c *app.RequestContext) bool {
isNeedAuth := false
uriPath := c.URI().Path()
for rule, res := range needAuthFunc {
if regexp.MustCompile(rule).MatchString(string(uriPath)) {
isNeedAuth = res
break
}
}
if needAuthPath[string(c.GetRequest().URI().Path())] {
isNeedAuth = true
}
return isNeedAuth
}
func OpenapiAuthMW() app.HandlerFunc {
return func(ctx context.Context, c *app.RequestContext) {
requestAuthType := c.GetInt32(RequestAuthTypeStr)
if requestAuthType != int32(RequestAuthTypeOpenAPI) {
c.Next(ctx)
return
}
// open api auth
if len(c.Request.Header.Get(HeaderAuthorizationKey)) == 0 {
httputil.InternalError(ctx, c,
errorx.New(errno.ErrUserAuthenticationFailed, errorx.KV("reason", "missing authorization in header")))
return
}
apiKey := parseBearerAuthToken(c.Request.Header.Get(HeaderAuthorizationKey))
if len(apiKey) == 0 {
httputil.InternalError(ctx, c,
errorx.New(errno.ErrUserAuthenticationFailed, errorx.KV("reason", "missing api_key in request")))
return
}
md5Hash := md5.Sum([]byte(apiKey))
md5Key := hex.EncodeToString(md5Hash[:])
apiKeyInfo, err := openauth.OpenAuthApplication.CheckPermission(ctx, md5Key)
if err != nil {
logs.CtxErrorf(ctx, "OpenAuthApplication.CheckPermission failed, err=%v", err)
httputil.InternalError(ctx, c,
errorx.New(errno.ErrUserAuthenticationFailed, errorx.KV("reason", err.Error())))
return
}
if apiKeyInfo == nil {
httputil.InternalError(ctx, c,
errorx.New(errno.ErrUserAuthenticationFailed, errorx.KV("reason", "api key invalid")))
return
}
apiKeyInfo.ConnectorID = consts.APIConnectorID
logs.CtxInfof(ctx, "OpenapiAuthMW: apiKeyInfo=%v", conv.DebugJsonToStr(apiKeyInfo))
ctxcache.Store(ctx, consts.OpenapiAuthKeyInCtx, apiKeyInfo)
err = openauth.OpenAuthApplication.UpdateLastUsedAt(ctx, apiKeyInfo.ID, apiKeyInfo.UserID)
if err != nil {
logs.CtxErrorf(ctx, "OpenAuthApplication.UpdateLastUsedAt failed, err=%v", err)
}
c.Next(ctx)
}
}
@@ -0,0 +1,76 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package middleware
import (
"context"
"strings"
"github.com/cloudwego/hertz/pkg/app"
)
const RequestAuthTypeStr = "RequestAuthTypeStr"
type RequestAuthType = int32
const (
RequestAuthTypeWebAPI RequestAuthType = 0
RequestAuthTypeOpenAPI RequestAuthType = 1
RequestAuthTypeStaticFile RequestAuthType = 2
)
func RequestInspectorMW() app.HandlerFunc {
return func(c context.Context, ctx *app.RequestContext) {
authType := RequestAuthTypeWebAPI // default is web api, session auth
if isNeedOpenapiAuth(ctx) {
authType = RequestAuthTypeOpenAPI
} else if isStaticFile(ctx) {
authType = RequestAuthTypeStaticFile
}
ctx.Set(RequestAuthTypeStr, authType)
ctx.Next(c)
}
}
var staticFilePath = map[string]bool{
"/static": true,
"/": true,
"/sign": true,
"/favicon.png": true,
}
func isStaticFile(ctx *app.RequestContext) bool {
path := string(ctx.GetRequest().URI().Path())
if staticFilePath[path] {
return true
}
if strings.HasPrefix(path, "/static/") ||
strings.HasPrefix(path, "/explore/") ||
strings.HasPrefix(path, "/admin/") ||
strings.HasPrefix(path, "/space/") {
return true
}
if path == "/information/auth/success" {
return true
}
return false
}
+113
View File
@@ -0,0 +1,113 @@
/*
* Copyright 2025 coze-dev Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package middleware
import (
"context"
"os"
"strings"
"github.com/cloudwego/hertz/pkg/app"
"github.com/coze-dev/coze-studio/backend/api/internal/httputil"
"github.com/coze-dev/coze-studio/backend/application/user"
"github.com/coze-dev/coze-studio/backend/bizpkg/config"
"github.com/coze-dev/coze-studio/backend/domain/user/entity"
"github.com/coze-dev/coze-studio/backend/pkg/ctxcache"
"github.com/coze-dev/coze-studio/backend/pkg/errorx"
"github.com/coze-dev/coze-studio/backend/pkg/logs"
"github.com/coze-dev/coze-studio/backend/types/consts"
"github.com/coze-dev/coze-studio/backend/types/errno"
)
var noNeedSessionCheckPath = map[string]bool{
"/api/passport/web/email/login/": true,
"/api/passport/web/email/register/v2/": true,
}
func SessionAuthMW() app.HandlerFunc {
return func(c context.Context, ctx *app.RequestContext) {
requestAuthType := ctx.GetInt32(RequestAuthTypeStr)
if requestAuthType != int32(RequestAuthTypeWebAPI) {
ctx.Next(c)
return
}
if noNeedSessionCheckPath[string(ctx.GetRequest().URI().Path())] {
ctx.Next(c)
return
}
s := ctx.Cookie(entity.SessionKey)
if len(s) == 0 {
logs.Errorf("[SessionAuthMW] session id is nil")
httputil.Unauthorized(ctx, "missing session_key in cookie")
return
}
// sessionID -> sessionData
session, err := user.UserApplicationSVC.ValidateSession(c, string(s))
if err != nil {
logs.Errorf("[SessionAuthMW] validate session failed, err: %v", err)
httputil.InternalError(c, ctx, err)
return
}
if session != nil {
ctxcache.Store(c, consts.SessionDataKeyInCtx, session)
}
ctx.Next(c)
}
}
func AdminAuthMW() app.HandlerFunc {
return func(c context.Context, ctx *app.RequestContext) {
session, ok := ctxcache.Get[*entity.Session](c, consts.SessionDataKeyInCtx)
if !ok {
logs.Errorf("[AdminAuthMW] session data is nil")
httputil.InternalError(c, ctx,
errorx.New(errno.ErrUserAuthenticationFailed, errorx.KV("reason", "session data is nil")))
return
}
baseConf, err := config.Base().GetBaseConfig(c)
if err != nil {
logs.Errorf("[AdminAuthMW] get base config failed, err: %v", err)
httputil.InternalError(c, ctx, err)
return
}
if baseConf.AdminEmails == "" {
baseConf.AdminEmails = os.Getenv(consts.AllowRegistrationEmail)
}
if baseConf.AdminEmails == "" {
logs.CtxWarnf(c, "[AdminAuthMW] admin emails is empty, you can set it by env %s", consts.AllowRegistrationEmail)
}
adminEmails := strings.Split(baseConf.AdminEmails, ",")
for _, adminEmail := range adminEmails {
if strings.EqualFold(adminEmail, session.UserEmail) {
ctx.Next(c)
return
}
}
httputil.Unauthorized(ctx, "the account does not have permission to access")
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,818 @@
// Code generated by thriftgo (0.4.2). DO NOT EDIT.
package common
import (
"database/sql"
"database/sql/driver"
"fmt"
"github.com/apache/thrift/lib/go/thrift"
)
type IntelligenceStatus int64
const (
IntelligenceStatus_Using IntelligenceStatus = 1
IntelligenceStatus_Deleted IntelligenceStatus = 2
IntelligenceStatus_Banned IntelligenceStatus = 3
// Migration failed
IntelligenceStatus_MoveFailed IntelligenceStatus = 4
// Copying
IntelligenceStatus_Copying IntelligenceStatus = 5
// Copy failed
IntelligenceStatus_CopyFailed IntelligenceStatus = 6
)
func (p IntelligenceStatus) String() string {
switch p {
case IntelligenceStatus_Using:
return "Using"
case IntelligenceStatus_Deleted:
return "Deleted"
case IntelligenceStatus_Banned:
return "Banned"
case IntelligenceStatus_MoveFailed:
return "MoveFailed"
case IntelligenceStatus_Copying:
return "Copying"
case IntelligenceStatus_CopyFailed:
return "CopyFailed"
}
return "<UNSET>"
}
func IntelligenceStatusFromString(s string) (IntelligenceStatus, error) {
switch s {
case "Using":
return IntelligenceStatus_Using, nil
case "Deleted":
return IntelligenceStatus_Deleted, nil
case "Banned":
return IntelligenceStatus_Banned, nil
case "MoveFailed":
return IntelligenceStatus_MoveFailed, nil
case "Copying":
return IntelligenceStatus_Copying, nil
case "CopyFailed":
return IntelligenceStatus_CopyFailed, nil
}
return IntelligenceStatus(0), fmt.Errorf("not a valid IntelligenceStatus string")
}
func IntelligenceStatusPtr(v IntelligenceStatus) *IntelligenceStatus { return &v }
func (p *IntelligenceStatus) Scan(value interface{}) (err error) {
var result sql.NullInt64
err = result.Scan(value)
*p = IntelligenceStatus(result.Int64)
return
}
func (p *IntelligenceStatus) Value() (driver.Value, error) {
if p == nil {
return nil, nil
}
return int64(*p), nil
}
type IntelligenceType int64
const (
IntelligenceType_Bot IntelligenceType = 1
IntelligenceType_Project IntelligenceType = 2
)
func (p IntelligenceType) String() string {
switch p {
case IntelligenceType_Bot:
return "Bot"
case IntelligenceType_Project:
return "Project"
}
return "<UNSET>"
}
func IntelligenceTypeFromString(s string) (IntelligenceType, error) {
switch s {
case "Bot":
return IntelligenceType_Bot, nil
case "Project":
return IntelligenceType_Project, nil
}
return IntelligenceType(0), fmt.Errorf("not a valid IntelligenceType string")
}
func IntelligenceTypePtr(v IntelligenceType) *IntelligenceType { return &v }
func (p *IntelligenceType) Scan(value interface{}) (err error) {
var result sql.NullInt64
err = result.Scan(value)
*p = IntelligenceType(result.Int64)
return
}
func (p *IntelligenceType) Value() (driver.Value, error) {
if p == nil {
return nil, nil
}
return int64(*p), nil
}
type IntelligenceBasicInfo struct {
ID int64 `thrift:"id,1" form:"id" json:"id,string" query:"id"`
Name string `thrift:"name,2" form:"name" json:"name" query:"name"`
Description string `thrift:"description,3" form:"description" json:"description" query:"description"`
IconURI string `thrift:"icon_uri,4" form:"icon_uri" json:"icon_uri" query:"icon_uri"`
IconURL string `thrift:"icon_url,5" form:"icon_url" json:"icon_url" query:"icon_url"`
SpaceID int64 `thrift:"space_id,6" form:"space_id" json:"space_id,string" query:"space_id"`
OwnerID int64 `thrift:"owner_id,7" form:"owner_id" json:"owner_id,string" query:"owner_id"`
CreateTime int64 `thrift:"create_time,8" form:"create_time" json:"create_time,string" query:"create_time"`
UpdateTime int64 `thrift:"update_time,9" form:"update_time" json:"update_time,string" query:"update_time"`
Status IntelligenceStatus `thrift:"status,10" form:"status" json:"status" query:"status"`
PublishTime int64 `thrift:"publish_time,11" form:"publish_time" json:"publish_time,string" query:"publish_time"`
EnterpriseID *string `thrift:"enterprise_id,12,optional" form:"enterprise_id" json:"enterprise_id,omitempty" query:"enterprise_id"`
OrganizationID *int64 `thrift:"organization_id,13,optional" form:"organization_id" json:"organization_id,omitempty" query:"organization_id"`
}
func NewIntelligenceBasicInfo() *IntelligenceBasicInfo {
return &IntelligenceBasicInfo{}
}
func (p *IntelligenceBasicInfo) InitDefault() {
}
func (p *IntelligenceBasicInfo) GetID() (v int64) {
return p.ID
}
func (p *IntelligenceBasicInfo) GetName() (v string) {
return p.Name
}
func (p *IntelligenceBasicInfo) GetDescription() (v string) {
return p.Description
}
func (p *IntelligenceBasicInfo) GetIconURI() (v string) {
return p.IconURI
}
func (p *IntelligenceBasicInfo) GetIconURL() (v string) {
return p.IconURL
}
func (p *IntelligenceBasicInfo) GetSpaceID() (v int64) {
return p.SpaceID
}
func (p *IntelligenceBasicInfo) GetOwnerID() (v int64) {
return p.OwnerID
}
func (p *IntelligenceBasicInfo) GetCreateTime() (v int64) {
return p.CreateTime
}
func (p *IntelligenceBasicInfo) GetUpdateTime() (v int64) {
return p.UpdateTime
}
func (p *IntelligenceBasicInfo) GetStatus() (v IntelligenceStatus) {
return p.Status
}
func (p *IntelligenceBasicInfo) GetPublishTime() (v int64) {
return p.PublishTime
}
var IntelligenceBasicInfo_EnterpriseID_DEFAULT string
func (p *IntelligenceBasicInfo) GetEnterpriseID() (v string) {
if !p.IsSetEnterpriseID() {
return IntelligenceBasicInfo_EnterpriseID_DEFAULT
}
return *p.EnterpriseID
}
var IntelligenceBasicInfo_OrganizationID_DEFAULT int64
func (p *IntelligenceBasicInfo) GetOrganizationID() (v int64) {
if !p.IsSetOrganizationID() {
return IntelligenceBasicInfo_OrganizationID_DEFAULT
}
return *p.OrganizationID
}
var fieldIDToName_IntelligenceBasicInfo = map[int16]string{
1: "id",
2: "name",
3: "description",
4: "icon_uri",
5: "icon_url",
6: "space_id",
7: "owner_id",
8: "create_time",
9: "update_time",
10: "status",
11: "publish_time",
12: "enterprise_id",
13: "organization_id",
}
func (p *IntelligenceBasicInfo) IsSetEnterpriseID() bool {
return p.EnterpriseID != nil
}
func (p *IntelligenceBasicInfo) IsSetOrganizationID() bool {
return p.OrganizationID != nil
}
func (p *IntelligenceBasicInfo) Read(iprot thrift.TProtocol) (err error) {
var fieldTypeId thrift.TType
var fieldId int16
if _, err = iprot.ReadStructBegin(); err != nil {
goto ReadStructBeginError
}
for {
_, fieldTypeId, fieldId, err = iprot.ReadFieldBegin()
if err != nil {
goto ReadFieldBeginError
}
if fieldTypeId == thrift.STOP {
break
}
switch fieldId {
case 1:
if fieldTypeId == thrift.I64 {
if err = p.ReadField1(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
case 2:
if fieldTypeId == thrift.STRING {
if err = p.ReadField2(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
case 3:
if fieldTypeId == thrift.STRING {
if err = p.ReadField3(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
case 4:
if fieldTypeId == thrift.STRING {
if err = p.ReadField4(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
case 5:
if fieldTypeId == thrift.STRING {
if err = p.ReadField5(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
case 6:
if fieldTypeId == thrift.I64 {
if err = p.ReadField6(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
case 7:
if fieldTypeId == thrift.I64 {
if err = p.ReadField7(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
case 8:
if fieldTypeId == thrift.I64 {
if err = p.ReadField8(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
case 9:
if fieldTypeId == thrift.I64 {
if err = p.ReadField9(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
case 10:
if fieldTypeId == thrift.I32 {
if err = p.ReadField10(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
case 11:
if fieldTypeId == thrift.I64 {
if err = p.ReadField11(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
case 12:
if fieldTypeId == thrift.STRING {
if err = p.ReadField12(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
case 13:
if fieldTypeId == thrift.I64 {
if err = p.ReadField13(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
default:
if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
}
if err = iprot.ReadFieldEnd(); err != nil {
goto ReadFieldEndError
}
}
if err = iprot.ReadStructEnd(); err != nil {
goto ReadStructEndError
}
return nil
ReadStructBeginError:
return thrift.PrependError(fmt.Sprintf("%T read struct begin error: ", p), err)
ReadFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T read field %d begin error: ", p, fieldId), err)
ReadFieldError:
return thrift.PrependError(fmt.Sprintf("%T read field %d '%s' error: ", p, fieldId, fieldIDToName_IntelligenceBasicInfo[fieldId]), err)
SkipFieldError:
return thrift.PrependError(fmt.Sprintf("%T field %d skip type %d error: ", p, fieldId, fieldTypeId), err)
ReadFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T read field end error", p), err)
ReadStructEndError:
return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
}
func (p *IntelligenceBasicInfo) ReadField1(iprot thrift.TProtocol) error {
var _field int64
if v, err := iprot.ReadI64(); err != nil {
return err
} else {
_field = v
}
p.ID = _field
return nil
}
func (p *IntelligenceBasicInfo) ReadField2(iprot thrift.TProtocol) error {
var _field string
if v, err := iprot.ReadString(); err != nil {
return err
} else {
_field = v
}
p.Name = _field
return nil
}
func (p *IntelligenceBasicInfo) ReadField3(iprot thrift.TProtocol) error {
var _field string
if v, err := iprot.ReadString(); err != nil {
return err
} else {
_field = v
}
p.Description = _field
return nil
}
func (p *IntelligenceBasicInfo) ReadField4(iprot thrift.TProtocol) error {
var _field string
if v, err := iprot.ReadString(); err != nil {
return err
} else {
_field = v
}
p.IconURI = _field
return nil
}
func (p *IntelligenceBasicInfo) ReadField5(iprot thrift.TProtocol) error {
var _field string
if v, err := iprot.ReadString(); err != nil {
return err
} else {
_field = v
}
p.IconURL = _field
return nil
}
func (p *IntelligenceBasicInfo) ReadField6(iprot thrift.TProtocol) error {
var _field int64
if v, err := iprot.ReadI64(); err != nil {
return err
} else {
_field = v
}
p.SpaceID = _field
return nil
}
func (p *IntelligenceBasicInfo) ReadField7(iprot thrift.TProtocol) error {
var _field int64
if v, err := iprot.ReadI64(); err != nil {
return err
} else {
_field = v
}
p.OwnerID = _field
return nil
}
func (p *IntelligenceBasicInfo) ReadField8(iprot thrift.TProtocol) error {
var _field int64
if v, err := iprot.ReadI64(); err != nil {
return err
} else {
_field = v
}
p.CreateTime = _field
return nil
}
func (p *IntelligenceBasicInfo) ReadField9(iprot thrift.TProtocol) error {
var _field int64
if v, err := iprot.ReadI64(); err != nil {
return err
} else {
_field = v
}
p.UpdateTime = _field
return nil
}
func (p *IntelligenceBasicInfo) ReadField10(iprot thrift.TProtocol) error {
var _field IntelligenceStatus
if v, err := iprot.ReadI32(); err != nil {
return err
} else {
_field = IntelligenceStatus(v)
}
p.Status = _field
return nil
}
func (p *IntelligenceBasicInfo) ReadField11(iprot thrift.TProtocol) error {
var _field int64
if v, err := iprot.ReadI64(); err != nil {
return err
} else {
_field = v
}
p.PublishTime = _field
return nil
}
func (p *IntelligenceBasicInfo) ReadField12(iprot thrift.TProtocol) error {
var _field *string
if v, err := iprot.ReadString(); err != nil {
return err
} else {
_field = &v
}
p.EnterpriseID = _field
return nil
}
func (p *IntelligenceBasicInfo) ReadField13(iprot thrift.TProtocol) error {
var _field *int64
if v, err := iprot.ReadI64(); err != nil {
return err
} else {
_field = &v
}
p.OrganizationID = _field
return nil
}
func (p *IntelligenceBasicInfo) Write(oprot thrift.TProtocol) (err error) {
var fieldId int16
if err = oprot.WriteStructBegin("IntelligenceBasicInfo"); err != nil {
goto WriteStructBeginError
}
if p != nil {
if err = p.writeField1(oprot); err != nil {
fieldId = 1
goto WriteFieldError
}
if err = p.writeField2(oprot); err != nil {
fieldId = 2
goto WriteFieldError
}
if err = p.writeField3(oprot); err != nil {
fieldId = 3
goto WriteFieldError
}
if err = p.writeField4(oprot); err != nil {
fieldId = 4
goto WriteFieldError
}
if err = p.writeField5(oprot); err != nil {
fieldId = 5
goto WriteFieldError
}
if err = p.writeField6(oprot); err != nil {
fieldId = 6
goto WriteFieldError
}
if err = p.writeField7(oprot); err != nil {
fieldId = 7
goto WriteFieldError
}
if err = p.writeField8(oprot); err != nil {
fieldId = 8
goto WriteFieldError
}
if err = p.writeField9(oprot); err != nil {
fieldId = 9
goto WriteFieldError
}
if err = p.writeField10(oprot); err != nil {
fieldId = 10
goto WriteFieldError
}
if err = p.writeField11(oprot); err != nil {
fieldId = 11
goto WriteFieldError
}
if err = p.writeField12(oprot); err != nil {
fieldId = 12
goto WriteFieldError
}
if err = p.writeField13(oprot); err != nil {
fieldId = 13
goto WriteFieldError
}
}
if err = oprot.WriteFieldStop(); err != nil {
goto WriteFieldStopError
}
if err = oprot.WriteStructEnd(); err != nil {
goto WriteStructEndError
}
return nil
WriteStructBeginError:
return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
WriteFieldError:
return thrift.PrependError(fmt.Sprintf("%T write field %d error: ", p, fieldId), err)
WriteFieldStopError:
return thrift.PrependError(fmt.Sprintf("%T write field stop error: ", p), err)
WriteStructEndError:
return thrift.PrependError(fmt.Sprintf("%T write struct end error: ", p), err)
}
func (p *IntelligenceBasicInfo) writeField1(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("id", thrift.I64, 1); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteI64(p.ID); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 1 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 1 end error: ", p), err)
}
func (p *IntelligenceBasicInfo) writeField2(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("name", thrift.STRING, 2); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteString(p.Name); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 2 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 2 end error: ", p), err)
}
func (p *IntelligenceBasicInfo) writeField3(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("description", thrift.STRING, 3); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteString(p.Description); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 3 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 3 end error: ", p), err)
}
func (p *IntelligenceBasicInfo) writeField4(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("icon_uri", thrift.STRING, 4); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteString(p.IconURI); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 4 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 4 end error: ", p), err)
}
func (p *IntelligenceBasicInfo) writeField5(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("icon_url", thrift.STRING, 5); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteString(p.IconURL); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 5 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 5 end error: ", p), err)
}
func (p *IntelligenceBasicInfo) writeField6(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("space_id", thrift.I64, 6); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteI64(p.SpaceID); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 6 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 6 end error: ", p), err)
}
func (p *IntelligenceBasicInfo) writeField7(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("owner_id", thrift.I64, 7); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteI64(p.OwnerID); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 7 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 7 end error: ", p), err)
}
func (p *IntelligenceBasicInfo) writeField8(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("create_time", thrift.I64, 8); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteI64(p.CreateTime); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 8 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 8 end error: ", p), err)
}
func (p *IntelligenceBasicInfo) writeField9(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("update_time", thrift.I64, 9); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteI64(p.UpdateTime); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 9 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 9 end error: ", p), err)
}
func (p *IntelligenceBasicInfo) writeField10(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("status", thrift.I32, 10); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteI32(int32(p.Status)); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 10 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 10 end error: ", p), err)
}
func (p *IntelligenceBasicInfo) writeField11(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("publish_time", thrift.I64, 11); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteI64(p.PublishTime); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 11 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 11 end error: ", p), err)
}
func (p *IntelligenceBasicInfo) writeField12(oprot thrift.TProtocol) (err error) {
if p.IsSetEnterpriseID() {
if err = oprot.WriteFieldBegin("enterprise_id", thrift.STRING, 12); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteString(*p.EnterpriseID); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 12 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 12 end error: ", p), err)
}
func (p *IntelligenceBasicInfo) writeField13(oprot thrift.TProtocol) (err error) {
if p.IsSetOrganizationID() {
if err = oprot.WriteFieldBegin("organization_id", thrift.I64, 13); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteI64(*p.OrganizationID); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 13 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 13 end error: ", p), err)
}
func (p *IntelligenceBasicInfo) String() string {
if p == nil {
return "<nil>"
}
return fmt.Sprintf("IntelligenceBasicInfo(%+v)", *p)
}
@@ -0,0 +1,148 @@
// Code generated by thriftgo (0.4.2). DO NOT EDIT.
package common
import (
"fmt"
"github.com/apache/thrift/lib/go/thrift"
)
type ProjectInnerTaskInfo struct {
// Task ID
TaskID int64 `thrift:"task_id,1" form:"task_id" json:"task_id,string" query:"task_id"`
}
func NewProjectInnerTaskInfo() *ProjectInnerTaskInfo {
return &ProjectInnerTaskInfo{}
}
func (p *ProjectInnerTaskInfo) InitDefault() {
}
func (p *ProjectInnerTaskInfo) GetTaskID() (v int64) {
return p.TaskID
}
var fieldIDToName_ProjectInnerTaskInfo = map[int16]string{
1: "task_id",
}
func (p *ProjectInnerTaskInfo) Read(iprot thrift.TProtocol) (err error) {
var fieldTypeId thrift.TType
var fieldId int16
if _, err = iprot.ReadStructBegin(); err != nil {
goto ReadStructBeginError
}
for {
_, fieldTypeId, fieldId, err = iprot.ReadFieldBegin()
if err != nil {
goto ReadFieldBeginError
}
if fieldTypeId == thrift.STOP {
break
}
switch fieldId {
case 1:
if fieldTypeId == thrift.I64 {
if err = p.ReadField1(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
default:
if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
}
if err = iprot.ReadFieldEnd(); err != nil {
goto ReadFieldEndError
}
}
if err = iprot.ReadStructEnd(); err != nil {
goto ReadStructEndError
}
return nil
ReadStructBeginError:
return thrift.PrependError(fmt.Sprintf("%T read struct begin error: ", p), err)
ReadFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T read field %d begin error: ", p, fieldId), err)
ReadFieldError:
return thrift.PrependError(fmt.Sprintf("%T read field %d '%s' error: ", p, fieldId, fieldIDToName_ProjectInnerTaskInfo[fieldId]), err)
SkipFieldError:
return thrift.PrependError(fmt.Sprintf("%T field %d skip type %d error: ", p, fieldId, fieldTypeId), err)
ReadFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T read field end error", p), err)
ReadStructEndError:
return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
}
func (p *ProjectInnerTaskInfo) ReadField1(iprot thrift.TProtocol) error {
var _field int64
if v, err := iprot.ReadI64(); err != nil {
return err
} else {
_field = v
}
p.TaskID = _field
return nil
}
func (p *ProjectInnerTaskInfo) Write(oprot thrift.TProtocol) (err error) {
var fieldId int16
if err = oprot.WriteStructBegin("ProjectInnerTaskInfo"); err != nil {
goto WriteStructBeginError
}
if p != nil {
if err = p.writeField1(oprot); err != nil {
fieldId = 1
goto WriteFieldError
}
}
if err = oprot.WriteFieldStop(); err != nil {
goto WriteFieldStopError
}
if err = oprot.WriteStructEnd(); err != nil {
goto WriteStructEndError
}
return nil
WriteStructBeginError:
return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
WriteFieldError:
return thrift.PrependError(fmt.Sprintf("%T write field %d error: ", p, fieldId), err)
WriteFieldStopError:
return thrift.PrependError(fmt.Sprintf("%T write field stop error: ", p), err)
WriteStructEndError:
return thrift.PrependError(fmt.Sprintf("%T write struct end error: ", p), err)
}
func (p *ProjectInnerTaskInfo) writeField1(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("task_id", thrift.I64, 1); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteI64(p.TaskID); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 1 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 1 end error: ", p), err)
}
func (p *ProjectInnerTaskInfo) String() string {
if p == nil {
return "<nil>"
}
return fmt.Sprintf("ProjectInnerTaskInfo(%+v)", *p)
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,672 @@
// Code generated by thriftgo (0.4.2). DO NOT EDIT.
package task
import (
"fmt"
"github.com/apache/thrift/lib/go/thrift"
"github.com/coze-dev/coze-studio/backend/api/model/app/intelligence/common"
"github.com/coze-dev/coze-studio/backend/api/model/base"
)
type DraftProjectInnerTaskListRequest struct {
ProjectID int64 `thrift:"project_id,1,required" form:"project_id,required" json:"project_id,string,required" query:"project_id,required"`
Base *base.Base `thrift:"Base,255,optional" form:"-" json:"-" query:"-"`
}
func NewDraftProjectInnerTaskListRequest() *DraftProjectInnerTaskListRequest {
return &DraftProjectInnerTaskListRequest{}
}
func (p *DraftProjectInnerTaskListRequest) InitDefault() {
}
func (p *DraftProjectInnerTaskListRequest) GetProjectID() (v int64) {
return p.ProjectID
}
var DraftProjectInnerTaskListRequest_Base_DEFAULT *base.Base
func (p *DraftProjectInnerTaskListRequest) GetBase() (v *base.Base) {
if !p.IsSetBase() {
return DraftProjectInnerTaskListRequest_Base_DEFAULT
}
return p.Base
}
var fieldIDToName_DraftProjectInnerTaskListRequest = map[int16]string{
1: "project_id",
255: "Base",
}
func (p *DraftProjectInnerTaskListRequest) IsSetBase() bool {
return p.Base != nil
}
func (p *DraftProjectInnerTaskListRequest) Read(iprot thrift.TProtocol) (err error) {
var fieldTypeId thrift.TType
var fieldId int16
var issetProjectID bool = false
if _, err = iprot.ReadStructBegin(); err != nil {
goto ReadStructBeginError
}
for {
_, fieldTypeId, fieldId, err = iprot.ReadFieldBegin()
if err != nil {
goto ReadFieldBeginError
}
if fieldTypeId == thrift.STOP {
break
}
switch fieldId {
case 1:
if fieldTypeId == thrift.I64 {
if err = p.ReadField1(iprot); err != nil {
goto ReadFieldError
}
issetProjectID = true
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
case 255:
if fieldTypeId == thrift.STRUCT {
if err = p.ReadField255(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
default:
if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
}
if err = iprot.ReadFieldEnd(); err != nil {
goto ReadFieldEndError
}
}
if err = iprot.ReadStructEnd(); err != nil {
goto ReadStructEndError
}
if !issetProjectID {
fieldId = 1
goto RequiredFieldNotSetError
}
return nil
ReadStructBeginError:
return thrift.PrependError(fmt.Sprintf("%T read struct begin error: ", p), err)
ReadFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T read field %d begin error: ", p, fieldId), err)
ReadFieldError:
return thrift.PrependError(fmt.Sprintf("%T read field %d '%s' error: ", p, fieldId, fieldIDToName_DraftProjectInnerTaskListRequest[fieldId]), err)
SkipFieldError:
return thrift.PrependError(fmt.Sprintf("%T field %d skip type %d error: ", p, fieldId, fieldTypeId), err)
ReadFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T read field end error", p), err)
ReadStructEndError:
return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
RequiredFieldNotSetError:
return thrift.NewTProtocolExceptionWithType(thrift.INVALID_DATA, fmt.Errorf("required field %s is not set", fieldIDToName_DraftProjectInnerTaskListRequest[fieldId]))
}
func (p *DraftProjectInnerTaskListRequest) ReadField1(iprot thrift.TProtocol) error {
var _field int64
if v, err := iprot.ReadI64(); err != nil {
return err
} else {
_field = v
}
p.ProjectID = _field
return nil
}
func (p *DraftProjectInnerTaskListRequest) ReadField255(iprot thrift.TProtocol) error {
_field := base.NewBase()
if err := _field.Read(iprot); err != nil {
return err
}
p.Base = _field
return nil
}
func (p *DraftProjectInnerTaskListRequest) Write(oprot thrift.TProtocol) (err error) {
var fieldId int16
if err = oprot.WriteStructBegin("DraftProjectInnerTaskListRequest"); err != nil {
goto WriteStructBeginError
}
if p != nil {
if err = p.writeField1(oprot); err != nil {
fieldId = 1
goto WriteFieldError
}
if err = p.writeField255(oprot); err != nil {
fieldId = 255
goto WriteFieldError
}
}
if err = oprot.WriteFieldStop(); err != nil {
goto WriteFieldStopError
}
if err = oprot.WriteStructEnd(); err != nil {
goto WriteStructEndError
}
return nil
WriteStructBeginError:
return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
WriteFieldError:
return thrift.PrependError(fmt.Sprintf("%T write field %d error: ", p, fieldId), err)
WriteFieldStopError:
return thrift.PrependError(fmt.Sprintf("%T write field stop error: ", p), err)
WriteStructEndError:
return thrift.PrependError(fmt.Sprintf("%T write struct end error: ", p), err)
}
func (p *DraftProjectInnerTaskListRequest) writeField1(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("project_id", thrift.I64, 1); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteI64(p.ProjectID); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 1 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 1 end error: ", p), err)
}
func (p *DraftProjectInnerTaskListRequest) writeField255(oprot thrift.TProtocol) (err error) {
if p.IsSetBase() {
if err = oprot.WriteFieldBegin("Base", thrift.STRUCT, 255); err != nil {
goto WriteFieldBeginError
}
if err := p.Base.Write(oprot); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 255 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 255 end error: ", p), err)
}
func (p *DraftProjectInnerTaskListRequest) String() string {
if p == nil {
return "<nil>"
}
return fmt.Sprintf("DraftProjectInnerTaskListRequest(%+v)", *p)
}
type DraftProjectInnerTaskListResponse struct {
Data *DraftProjectInnerTaskListData `thrift:"data,1" form:"data" json:"data" query:"data"`
Code int64 `thrift:"code,253,required" form:"code,required" json:"code,required" query:"code,required"`
Msg string `thrift:"msg,254,required" form:"msg,required" json:"msg,required" query:"msg,required"`
BaseResp *base.BaseResp `thrift:"BaseResp,255,optional" form:"-" json:"-" query:"-"`
}
func NewDraftProjectInnerTaskListResponse() *DraftProjectInnerTaskListResponse {
return &DraftProjectInnerTaskListResponse{}
}
func (p *DraftProjectInnerTaskListResponse) InitDefault() {
}
var DraftProjectInnerTaskListResponse_Data_DEFAULT *DraftProjectInnerTaskListData
func (p *DraftProjectInnerTaskListResponse) GetData() (v *DraftProjectInnerTaskListData) {
if !p.IsSetData() {
return DraftProjectInnerTaskListResponse_Data_DEFAULT
}
return p.Data
}
func (p *DraftProjectInnerTaskListResponse) GetCode() (v int64) {
return p.Code
}
func (p *DraftProjectInnerTaskListResponse) GetMsg() (v string) {
return p.Msg
}
var DraftProjectInnerTaskListResponse_BaseResp_DEFAULT *base.BaseResp
func (p *DraftProjectInnerTaskListResponse) GetBaseResp() (v *base.BaseResp) {
if !p.IsSetBaseResp() {
return DraftProjectInnerTaskListResponse_BaseResp_DEFAULT
}
return p.BaseResp
}
var fieldIDToName_DraftProjectInnerTaskListResponse = map[int16]string{
1: "data",
253: "code",
254: "msg",
255: "BaseResp",
}
func (p *DraftProjectInnerTaskListResponse) IsSetData() bool {
return p.Data != nil
}
func (p *DraftProjectInnerTaskListResponse) IsSetBaseResp() bool {
return p.BaseResp != nil
}
func (p *DraftProjectInnerTaskListResponse) Read(iprot thrift.TProtocol) (err error) {
var fieldTypeId thrift.TType
var fieldId int16
var issetCode bool = false
var issetMsg bool = false
if _, err = iprot.ReadStructBegin(); err != nil {
goto ReadStructBeginError
}
for {
_, fieldTypeId, fieldId, err = iprot.ReadFieldBegin()
if err != nil {
goto ReadFieldBeginError
}
if fieldTypeId == thrift.STOP {
break
}
switch fieldId {
case 1:
if fieldTypeId == thrift.STRUCT {
if err = p.ReadField1(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
case 253:
if fieldTypeId == thrift.I64 {
if err = p.ReadField253(iprot); err != nil {
goto ReadFieldError
}
issetCode = true
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
case 254:
if fieldTypeId == thrift.STRING {
if err = p.ReadField254(iprot); err != nil {
goto ReadFieldError
}
issetMsg = true
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
case 255:
if fieldTypeId == thrift.STRUCT {
if err = p.ReadField255(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
default:
if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
}
if err = iprot.ReadFieldEnd(); err != nil {
goto ReadFieldEndError
}
}
if err = iprot.ReadStructEnd(); err != nil {
goto ReadStructEndError
}
if !issetCode {
fieldId = 253
goto RequiredFieldNotSetError
}
if !issetMsg {
fieldId = 254
goto RequiredFieldNotSetError
}
return nil
ReadStructBeginError:
return thrift.PrependError(fmt.Sprintf("%T read struct begin error: ", p), err)
ReadFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T read field %d begin error: ", p, fieldId), err)
ReadFieldError:
return thrift.PrependError(fmt.Sprintf("%T read field %d '%s' error: ", p, fieldId, fieldIDToName_DraftProjectInnerTaskListResponse[fieldId]), err)
SkipFieldError:
return thrift.PrependError(fmt.Sprintf("%T field %d skip type %d error: ", p, fieldId, fieldTypeId), err)
ReadFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T read field end error", p), err)
ReadStructEndError:
return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
RequiredFieldNotSetError:
return thrift.NewTProtocolExceptionWithType(thrift.INVALID_DATA, fmt.Errorf("required field %s is not set", fieldIDToName_DraftProjectInnerTaskListResponse[fieldId]))
}
func (p *DraftProjectInnerTaskListResponse) ReadField1(iprot thrift.TProtocol) error {
_field := NewDraftProjectInnerTaskListData()
if err := _field.Read(iprot); err != nil {
return err
}
p.Data = _field
return nil
}
func (p *DraftProjectInnerTaskListResponse) ReadField253(iprot thrift.TProtocol) error {
var _field int64
if v, err := iprot.ReadI64(); err != nil {
return err
} else {
_field = v
}
p.Code = _field
return nil
}
func (p *DraftProjectInnerTaskListResponse) ReadField254(iprot thrift.TProtocol) error {
var _field string
if v, err := iprot.ReadString(); err != nil {
return err
} else {
_field = v
}
p.Msg = _field
return nil
}
func (p *DraftProjectInnerTaskListResponse) ReadField255(iprot thrift.TProtocol) error {
_field := base.NewBaseResp()
if err := _field.Read(iprot); err != nil {
return err
}
p.BaseResp = _field
return nil
}
func (p *DraftProjectInnerTaskListResponse) Write(oprot thrift.TProtocol) (err error) {
var fieldId int16
if err = oprot.WriteStructBegin("DraftProjectInnerTaskListResponse"); err != nil {
goto WriteStructBeginError
}
if p != nil {
if err = p.writeField1(oprot); err != nil {
fieldId = 1
goto WriteFieldError
}
if err = p.writeField253(oprot); err != nil {
fieldId = 253
goto WriteFieldError
}
if err = p.writeField254(oprot); err != nil {
fieldId = 254
goto WriteFieldError
}
if err = p.writeField255(oprot); err != nil {
fieldId = 255
goto WriteFieldError
}
}
if err = oprot.WriteFieldStop(); err != nil {
goto WriteFieldStopError
}
if err = oprot.WriteStructEnd(); err != nil {
goto WriteStructEndError
}
return nil
WriteStructBeginError:
return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
WriteFieldError:
return thrift.PrependError(fmt.Sprintf("%T write field %d error: ", p, fieldId), err)
WriteFieldStopError:
return thrift.PrependError(fmt.Sprintf("%T write field stop error: ", p), err)
WriteStructEndError:
return thrift.PrependError(fmt.Sprintf("%T write struct end error: ", p), err)
}
func (p *DraftProjectInnerTaskListResponse) writeField1(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("data", thrift.STRUCT, 1); err != nil {
goto WriteFieldBeginError
}
if err := p.Data.Write(oprot); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 1 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 1 end error: ", p), err)
}
func (p *DraftProjectInnerTaskListResponse) writeField253(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("code", thrift.I64, 253); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteI64(p.Code); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 253 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 253 end error: ", p), err)
}
func (p *DraftProjectInnerTaskListResponse) writeField254(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("msg", thrift.STRING, 254); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteString(p.Msg); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 254 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 254 end error: ", p), err)
}
func (p *DraftProjectInnerTaskListResponse) writeField255(oprot thrift.TProtocol) (err error) {
if p.IsSetBaseResp() {
if err = oprot.WriteFieldBegin("BaseResp", thrift.STRUCT, 255); err != nil {
goto WriteFieldBeginError
}
if err := p.BaseResp.Write(oprot); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 255 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 255 end error: ", p), err)
}
func (p *DraftProjectInnerTaskListResponse) String() string {
if p == nil {
return "<nil>"
}
return fmt.Sprintf("DraftProjectInnerTaskListResponse(%+v)", *p)
}
type DraftProjectInnerTaskListData struct {
TaskList []*common.ProjectInnerTaskInfo `thrift:"task_list,1" form:"task_list" json:"task_list" query:"task_list"`
}
func NewDraftProjectInnerTaskListData() *DraftProjectInnerTaskListData {
return &DraftProjectInnerTaskListData{}
}
func (p *DraftProjectInnerTaskListData) InitDefault() {
}
func (p *DraftProjectInnerTaskListData) GetTaskList() (v []*common.ProjectInnerTaskInfo) {
return p.TaskList
}
var fieldIDToName_DraftProjectInnerTaskListData = map[int16]string{
1: "task_list",
}
func (p *DraftProjectInnerTaskListData) Read(iprot thrift.TProtocol) (err error) {
var fieldTypeId thrift.TType
var fieldId int16
if _, err = iprot.ReadStructBegin(); err != nil {
goto ReadStructBeginError
}
for {
_, fieldTypeId, fieldId, err = iprot.ReadFieldBegin()
if err != nil {
goto ReadFieldBeginError
}
if fieldTypeId == thrift.STOP {
break
}
switch fieldId {
case 1:
if fieldTypeId == thrift.LIST {
if err = p.ReadField1(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
default:
if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
}
if err = iprot.ReadFieldEnd(); err != nil {
goto ReadFieldEndError
}
}
if err = iprot.ReadStructEnd(); err != nil {
goto ReadStructEndError
}
return nil
ReadStructBeginError:
return thrift.PrependError(fmt.Sprintf("%T read struct begin error: ", p), err)
ReadFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T read field %d begin error: ", p, fieldId), err)
ReadFieldError:
return thrift.PrependError(fmt.Sprintf("%T read field %d '%s' error: ", p, fieldId, fieldIDToName_DraftProjectInnerTaskListData[fieldId]), err)
SkipFieldError:
return thrift.PrependError(fmt.Sprintf("%T field %d skip type %d error: ", p, fieldId, fieldTypeId), err)
ReadFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T read field end error", p), err)
ReadStructEndError:
return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
}
func (p *DraftProjectInnerTaskListData) ReadField1(iprot thrift.TProtocol) error {
_, size, err := iprot.ReadListBegin()
if err != nil {
return err
}
_field := make([]*common.ProjectInnerTaskInfo, 0, size)
values := make([]common.ProjectInnerTaskInfo, size)
for i := 0; i < size; i++ {
_elem := &values[i]
_elem.InitDefault()
if err := _elem.Read(iprot); err != nil {
return err
}
_field = append(_field, _elem)
}
if err := iprot.ReadListEnd(); err != nil {
return err
}
p.TaskList = _field
return nil
}
func (p *DraftProjectInnerTaskListData) Write(oprot thrift.TProtocol) (err error) {
var fieldId int16
if err = oprot.WriteStructBegin("DraftProjectInnerTaskListData"); err != nil {
goto WriteStructBeginError
}
if p != nil {
if err = p.writeField1(oprot); err != nil {
fieldId = 1
goto WriteFieldError
}
}
if err = oprot.WriteFieldStop(); err != nil {
goto WriteFieldStopError
}
if err = oprot.WriteStructEnd(); err != nil {
goto WriteStructEndError
}
return nil
WriteStructBeginError:
return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
WriteFieldError:
return thrift.PrependError(fmt.Sprintf("%T write field %d error: ", p, fieldId), err)
WriteFieldStopError:
return thrift.PrependError(fmt.Sprintf("%T write field stop error: ", p), err)
WriteStructEndError:
return thrift.PrependError(fmt.Sprintf("%T write struct end error: ", p), err)
}
func (p *DraftProjectInnerTaskListData) writeField1(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("task_list", thrift.LIST, 1); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteListBegin(thrift.STRUCT, len(p.TaskList)); err != nil {
return err
}
for _, v := range p.TaskList {
if err := v.Write(oprot); err != nil {
return err
}
}
if err := oprot.WriteListEnd(); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 1 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 1 end error: ", p), err)
}
func (p *DraftProjectInnerTaskListData) String() string {
if p == nil {
return "<nil>"
}
return fmt.Sprintf("DraftProjectInnerTaskListData(%+v)", *p)
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,102 @@
// Code generated by thriftgo (0.4.2). DO NOT EDIT.
package common
import (
"database/sql"
"database/sql/driver"
"fmt"
)
type Scene int64
const (
Scene_Default Scene = 0
Scene_Explore Scene = 1
Scene_BotStore Scene = 2
Scene_CozeHome Scene = 3
//debugging
Scene_Playground Scene = 4
// evaluation platform
Scene_Evaluation Scene = 5
Scene_AgentAPP Scene = 6
//Prompt optimization
Scene_PromptOptimize Scene = 7
// Createbot's nl2bot features
Scene_GenerateAgentInfo Scene = 8
//openapi
Scene_SceneOpenApi Scene = 9
// workflow
Scene_SceneWorkflow Scene = 50
)
func (p Scene) String() string {
switch p {
case Scene_Default:
return "Default"
case Scene_Explore:
return "Explore"
case Scene_BotStore:
return "BotStore"
case Scene_CozeHome:
return "CozeHome"
case Scene_Playground:
return "Playground"
case Scene_Evaluation:
return "Evaluation"
case Scene_AgentAPP:
return "AgentAPP"
case Scene_PromptOptimize:
return "PromptOptimize"
case Scene_GenerateAgentInfo:
return "GenerateAgentInfo"
case Scene_SceneOpenApi:
return "SceneOpenApi"
case Scene_SceneWorkflow:
return "SceneWorkflow"
}
return "<UNSET>"
}
func SceneFromString(s string) (Scene, error) {
switch s {
case "Default":
return Scene_Default, nil
case "Explore":
return Scene_Explore, nil
case "BotStore":
return Scene_BotStore, nil
case "CozeHome":
return Scene_CozeHome, nil
case "Playground":
return Scene_Playground, nil
case "Evaluation":
return Scene_Evaluation, nil
case "AgentAPP":
return Scene_AgentAPP, nil
case "PromptOptimize":
return Scene_PromptOptimize, nil
case "GenerateAgentInfo":
return Scene_GenerateAgentInfo, nil
case "SceneOpenApi":
return Scene_SceneOpenApi, nil
case "SceneWorkflow":
return Scene_SceneWorkflow, nil
}
return Scene(0), fmt.Errorf("not a valid Scene string")
}
func ScenePtr(v Scene) *Scene { return &v }
func (p *Scene) Scan(value interface{}) (err error) {
var result sql.NullInt64
err = result.Scan(value)
*p = Scene(result.Int64)
return
}
func (p *Scene) Value() (driver.Value, error) {
if p == nil {
return nil, nil
}
return int64(*p), nil
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+655
View File
@@ -0,0 +1,655 @@
// Code generated by thriftgo (0.4.2). DO NOT EDIT.
package coze
import (
"github.com/apache/thrift/lib/go/thrift"
"github.com/coze-dev/coze-studio/backend/api/model/admin/config"
"github.com/coze-dev/coze-studio/backend/api/model/app/bot_open_api"
"github.com/coze-dev/coze-studio/backend/api/model/app/developer_api"
"github.com/coze-dev/coze-studio/backend/api/model/app/intelligence"
"github.com/coze-dev/coze-studio/backend/api/model/conversation/agentrun"
"github.com/coze-dev/coze-studio/backend/api/model/conversation/conversation"
"github.com/coze-dev/coze-studio/backend/api/model/conversation/message"
"github.com/coze-dev/coze-studio/backend/api/model/data/database"
"github.com/coze-dev/coze-studio/backend/api/model/data/knowledge"
"github.com/coze-dev/coze-studio/backend/api/model/data/variable"
"github.com/coze-dev/coze-studio/backend/api/model/file/upload"
"github.com/coze-dev/coze-studio/backend/api/model/marketplace/product_public_api"
"github.com/coze-dev/coze-studio/backend/api/model/passport"
"github.com/coze-dev/coze-studio/backend/api/model/permission/openapiauth"
"github.com/coze-dev/coze-studio/backend/api/model/playground"
"github.com/coze-dev/coze-studio/backend/api/model/plugin_develop"
"github.com/coze-dev/coze-studio/backend/api/model/resource"
"github.com/coze-dev/coze-studio/backend/api/model/workflow"
)
type IntelligenceService interface {
intelligence.IntelligenceService
}
type IntelligenceServiceClient struct {
*intelligence.IntelligenceServiceClient
}
func NewIntelligenceServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *IntelligenceServiceClient {
return &IntelligenceServiceClient{
IntelligenceServiceClient: intelligence.NewIntelligenceServiceClientFactory(t, f),
}
}
func NewIntelligenceServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *IntelligenceServiceClient {
return &IntelligenceServiceClient{
IntelligenceServiceClient: intelligence.NewIntelligenceServiceClientProtocol(t, iprot, oprot),
}
}
func NewIntelligenceServiceClient(c thrift.TClient) *IntelligenceServiceClient {
return &IntelligenceServiceClient{
IntelligenceServiceClient: intelligence.NewIntelligenceServiceClient(c),
}
}
type ConversationService interface {
conversation.ConversationService
}
type ConversationServiceClient struct {
*conversation.ConversationServiceClient
}
func NewConversationServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *ConversationServiceClient {
return &ConversationServiceClient{
ConversationServiceClient: conversation.NewConversationServiceClientFactory(t, f),
}
}
func NewConversationServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *ConversationServiceClient {
return &ConversationServiceClient{
ConversationServiceClient: conversation.NewConversationServiceClientProtocol(t, iprot, oprot),
}
}
func NewConversationServiceClient(c thrift.TClient) *ConversationServiceClient {
return &ConversationServiceClient{
ConversationServiceClient: conversation.NewConversationServiceClient(c),
}
}
type MessageService interface {
message.MessageService
}
type MessageServiceClient struct {
*message.MessageServiceClient
}
func NewMessageServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *MessageServiceClient {
return &MessageServiceClient{
MessageServiceClient: message.NewMessageServiceClientFactory(t, f),
}
}
func NewMessageServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *MessageServiceClient {
return &MessageServiceClient{
MessageServiceClient: message.NewMessageServiceClientProtocol(t, iprot, oprot),
}
}
func NewMessageServiceClient(c thrift.TClient) *MessageServiceClient {
return &MessageServiceClient{
MessageServiceClient: message.NewMessageServiceClient(c),
}
}
type AgentRunService interface {
agentrun.AgentRunService
}
type AgentRunServiceClient struct {
*agentrun.AgentRunServiceClient
}
func NewAgentRunServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *AgentRunServiceClient {
return &AgentRunServiceClient{
AgentRunServiceClient: agentrun.NewAgentRunServiceClientFactory(t, f),
}
}
func NewAgentRunServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *AgentRunServiceClient {
return &AgentRunServiceClient{
AgentRunServiceClient: agentrun.NewAgentRunServiceClientProtocol(t, iprot, oprot),
}
}
func NewAgentRunServiceClient(c thrift.TClient) *AgentRunServiceClient {
return &AgentRunServiceClient{
AgentRunServiceClient: agentrun.NewAgentRunServiceClient(c),
}
}
type OpenAPIAuthService interface {
openapiauth.OpenAPIAuthService
}
type OpenAPIAuthServiceClient struct {
*openapiauth.OpenAPIAuthServiceClient
}
func NewOpenAPIAuthServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *OpenAPIAuthServiceClient {
return &OpenAPIAuthServiceClient{
OpenAPIAuthServiceClient: openapiauth.NewOpenAPIAuthServiceClientFactory(t, f),
}
}
func NewOpenAPIAuthServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *OpenAPIAuthServiceClient {
return &OpenAPIAuthServiceClient{
OpenAPIAuthServiceClient: openapiauth.NewOpenAPIAuthServiceClientProtocol(t, iprot, oprot),
}
}
func NewOpenAPIAuthServiceClient(c thrift.TClient) *OpenAPIAuthServiceClient {
return &OpenAPIAuthServiceClient{
OpenAPIAuthServiceClient: openapiauth.NewOpenAPIAuthServiceClient(c),
}
}
type MemoryService interface {
variable.MemoryService
}
type MemoryServiceClient struct {
*variable.MemoryServiceClient
}
func NewMemoryServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *MemoryServiceClient {
return &MemoryServiceClient{
MemoryServiceClient: variable.NewMemoryServiceClientFactory(t, f),
}
}
func NewMemoryServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *MemoryServiceClient {
return &MemoryServiceClient{
MemoryServiceClient: variable.NewMemoryServiceClientProtocol(t, iprot, oprot),
}
}
func NewMemoryServiceClient(c thrift.TClient) *MemoryServiceClient {
return &MemoryServiceClient{
MemoryServiceClient: variable.NewMemoryServiceClient(c),
}
}
type PluginDevelopService interface {
plugin_develop.PluginDevelopService
}
type PluginDevelopServiceClient struct {
*plugin_develop.PluginDevelopServiceClient
}
func NewPluginDevelopServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *PluginDevelopServiceClient {
return &PluginDevelopServiceClient{
PluginDevelopServiceClient: plugin_develop.NewPluginDevelopServiceClientFactory(t, f),
}
}
func NewPluginDevelopServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *PluginDevelopServiceClient {
return &PluginDevelopServiceClient{
PluginDevelopServiceClient: plugin_develop.NewPluginDevelopServiceClientProtocol(t, iprot, oprot),
}
}
func NewPluginDevelopServiceClient(c thrift.TClient) *PluginDevelopServiceClient {
return &PluginDevelopServiceClient{
PluginDevelopServiceClient: plugin_develop.NewPluginDevelopServiceClient(c),
}
}
type PublicProductService interface {
product_public_api.PublicProductService
}
type PublicProductServiceClient struct {
*product_public_api.PublicProductServiceClient
}
func NewPublicProductServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *PublicProductServiceClient {
return &PublicProductServiceClient{
PublicProductServiceClient: product_public_api.NewPublicProductServiceClientFactory(t, f),
}
}
func NewPublicProductServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *PublicProductServiceClient {
return &PublicProductServiceClient{
PublicProductServiceClient: product_public_api.NewPublicProductServiceClientProtocol(t, iprot, oprot),
}
}
func NewPublicProductServiceClient(c thrift.TClient) *PublicProductServiceClient {
return &PublicProductServiceClient{
PublicProductServiceClient: product_public_api.NewPublicProductServiceClient(c),
}
}
type DeveloperApiService interface {
developer_api.DeveloperApiService
}
type DeveloperApiServiceClient struct {
*developer_api.DeveloperApiServiceClient
}
func NewDeveloperApiServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *DeveloperApiServiceClient {
return &DeveloperApiServiceClient{
DeveloperApiServiceClient: developer_api.NewDeveloperApiServiceClientFactory(t, f),
}
}
func NewDeveloperApiServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *DeveloperApiServiceClient {
return &DeveloperApiServiceClient{
DeveloperApiServiceClient: developer_api.NewDeveloperApiServiceClientProtocol(t, iprot, oprot),
}
}
func NewDeveloperApiServiceClient(c thrift.TClient) *DeveloperApiServiceClient {
return &DeveloperApiServiceClient{
DeveloperApiServiceClient: developer_api.NewDeveloperApiServiceClient(c),
}
}
type PlaygroundService interface {
playground.PlaygroundService
}
type PlaygroundServiceClient struct {
*playground.PlaygroundServiceClient
}
func NewPlaygroundServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *PlaygroundServiceClient {
return &PlaygroundServiceClient{
PlaygroundServiceClient: playground.NewPlaygroundServiceClientFactory(t, f),
}
}
func NewPlaygroundServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *PlaygroundServiceClient {
return &PlaygroundServiceClient{
PlaygroundServiceClient: playground.NewPlaygroundServiceClientProtocol(t, iprot, oprot),
}
}
func NewPlaygroundServiceClient(c thrift.TClient) *PlaygroundServiceClient {
return &PlaygroundServiceClient{
PlaygroundServiceClient: playground.NewPlaygroundServiceClient(c),
}
}
type DatabaseService interface {
database.DatabaseService
}
type DatabaseServiceClient struct {
*database.DatabaseServiceClient
}
func NewDatabaseServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *DatabaseServiceClient {
return &DatabaseServiceClient{
DatabaseServiceClient: database.NewDatabaseServiceClientFactory(t, f),
}
}
func NewDatabaseServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *DatabaseServiceClient {
return &DatabaseServiceClient{
DatabaseServiceClient: database.NewDatabaseServiceClientProtocol(t, iprot, oprot),
}
}
func NewDatabaseServiceClient(c thrift.TClient) *DatabaseServiceClient {
return &DatabaseServiceClient{
DatabaseServiceClient: database.NewDatabaseServiceClient(c),
}
}
type ResourceService interface {
resource.ResourceService
}
type ResourceServiceClient struct {
*resource.ResourceServiceClient
}
func NewResourceServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *ResourceServiceClient {
return &ResourceServiceClient{
ResourceServiceClient: resource.NewResourceServiceClientFactory(t, f),
}
}
func NewResourceServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *ResourceServiceClient {
return &ResourceServiceClient{
ResourceServiceClient: resource.NewResourceServiceClientProtocol(t, iprot, oprot),
}
}
func NewResourceServiceClient(c thrift.TClient) *ResourceServiceClient {
return &ResourceServiceClient{
ResourceServiceClient: resource.NewResourceServiceClient(c),
}
}
type PassportService interface {
passport.PassportService
}
type PassportServiceClient struct {
*passport.PassportServiceClient
}
func NewPassportServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *PassportServiceClient {
return &PassportServiceClient{
PassportServiceClient: passport.NewPassportServiceClientFactory(t, f),
}
}
func NewPassportServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *PassportServiceClient {
return &PassportServiceClient{
PassportServiceClient: passport.NewPassportServiceClientProtocol(t, iprot, oprot),
}
}
func NewPassportServiceClient(c thrift.TClient) *PassportServiceClient {
return &PassportServiceClient{
PassportServiceClient: passport.NewPassportServiceClient(c),
}
}
type WorkflowService interface {
workflow.WorkflowService
}
type WorkflowServiceClient struct {
*workflow.WorkflowServiceClient
}
func NewWorkflowServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *WorkflowServiceClient {
return &WorkflowServiceClient{
WorkflowServiceClient: workflow.NewWorkflowServiceClientFactory(t, f),
}
}
func NewWorkflowServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *WorkflowServiceClient {
return &WorkflowServiceClient{
WorkflowServiceClient: workflow.NewWorkflowServiceClientProtocol(t, iprot, oprot),
}
}
func NewWorkflowServiceClient(c thrift.TClient) *WorkflowServiceClient {
return &WorkflowServiceClient{
WorkflowServiceClient: workflow.NewWorkflowServiceClient(c),
}
}
type KnowledgeService interface {
knowledge.DatasetService
}
type KnowledgeServiceClient struct {
*knowledge.DatasetServiceClient
}
func NewKnowledgeServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *KnowledgeServiceClient {
return &KnowledgeServiceClient{
DatasetServiceClient: knowledge.NewDatasetServiceClientFactory(t, f),
}
}
func NewKnowledgeServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *KnowledgeServiceClient {
return &KnowledgeServiceClient{
DatasetServiceClient: knowledge.NewDatasetServiceClientProtocol(t, iprot, oprot),
}
}
func NewKnowledgeServiceClient(c thrift.TClient) *KnowledgeServiceClient {
return &KnowledgeServiceClient{
DatasetServiceClient: knowledge.NewDatasetServiceClient(c),
}
}
type BotOpenApiService interface {
bot_open_api.BotOpenApiService
}
type BotOpenApiServiceClient struct {
*bot_open_api.BotOpenApiServiceClient
}
func NewBotOpenApiServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *BotOpenApiServiceClient {
return &BotOpenApiServiceClient{
BotOpenApiServiceClient: bot_open_api.NewBotOpenApiServiceClientFactory(t, f),
}
}
func NewBotOpenApiServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *BotOpenApiServiceClient {
return &BotOpenApiServiceClient{
BotOpenApiServiceClient: bot_open_api.NewBotOpenApiServiceClientProtocol(t, iprot, oprot),
}
}
func NewBotOpenApiServiceClient(c thrift.TClient) *BotOpenApiServiceClient {
return &BotOpenApiServiceClient{
BotOpenApiServiceClient: bot_open_api.NewBotOpenApiServiceClient(c),
}
}
type UploadService interface {
upload.UploadService
}
type UploadServiceClient struct {
*upload.UploadServiceClient
}
func NewUploadServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *UploadServiceClient {
return &UploadServiceClient{
UploadServiceClient: upload.NewUploadServiceClientFactory(t, f),
}
}
func NewUploadServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *UploadServiceClient {
return &UploadServiceClient{
UploadServiceClient: upload.NewUploadServiceClientProtocol(t, iprot, oprot),
}
}
func NewUploadServiceClient(c thrift.TClient) *UploadServiceClient {
return &UploadServiceClient{
UploadServiceClient: upload.NewUploadServiceClient(c),
}
}
type ConfigService interface {
config.ConfigService
}
type ConfigServiceClient struct {
*config.ConfigServiceClient
}
func NewConfigServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *ConfigServiceClient {
return &ConfigServiceClient{
ConfigServiceClient: config.NewConfigServiceClientFactory(t, f),
}
}
func NewConfigServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *ConfigServiceClient {
return &ConfigServiceClient{
ConfigServiceClient: config.NewConfigServiceClientProtocol(t, iprot, oprot),
}
}
func NewConfigServiceClient(c thrift.TClient) *ConfigServiceClient {
return &ConfigServiceClient{
ConfigServiceClient: config.NewConfigServiceClient(c),
}
}
type IntelligenceServiceProcessor struct {
*intelligence.IntelligenceServiceProcessor
}
func NewIntelligenceServiceProcessor(handler IntelligenceService) *IntelligenceServiceProcessor {
self := &IntelligenceServiceProcessor{intelligence.NewIntelligenceServiceProcessor(handler)}
return self
}
type ConversationServiceProcessor struct {
*conversation.ConversationServiceProcessor
}
func NewConversationServiceProcessor(handler ConversationService) *ConversationServiceProcessor {
self := &ConversationServiceProcessor{conversation.NewConversationServiceProcessor(handler)}
return self
}
type MessageServiceProcessor struct {
*message.MessageServiceProcessor
}
func NewMessageServiceProcessor(handler MessageService) *MessageServiceProcessor {
self := &MessageServiceProcessor{message.NewMessageServiceProcessor(handler)}
return self
}
type AgentRunServiceProcessor struct {
*agentrun.AgentRunServiceProcessor
}
func NewAgentRunServiceProcessor(handler AgentRunService) *AgentRunServiceProcessor {
self := &AgentRunServiceProcessor{agentrun.NewAgentRunServiceProcessor(handler)}
return self
}
type OpenAPIAuthServiceProcessor struct {
*openapiauth.OpenAPIAuthServiceProcessor
}
func NewOpenAPIAuthServiceProcessor(handler OpenAPIAuthService) *OpenAPIAuthServiceProcessor {
self := &OpenAPIAuthServiceProcessor{openapiauth.NewOpenAPIAuthServiceProcessor(handler)}
return self
}
type MemoryServiceProcessor struct {
*variable.MemoryServiceProcessor
}
func NewMemoryServiceProcessor(handler MemoryService) *MemoryServiceProcessor {
self := &MemoryServiceProcessor{variable.NewMemoryServiceProcessor(handler)}
return self
}
type PluginDevelopServiceProcessor struct {
*plugin_develop.PluginDevelopServiceProcessor
}
func NewPluginDevelopServiceProcessor(handler PluginDevelopService) *PluginDevelopServiceProcessor {
self := &PluginDevelopServiceProcessor{plugin_develop.NewPluginDevelopServiceProcessor(handler)}
return self
}
type PublicProductServiceProcessor struct {
*product_public_api.PublicProductServiceProcessor
}
func NewPublicProductServiceProcessor(handler PublicProductService) *PublicProductServiceProcessor {
self := &PublicProductServiceProcessor{product_public_api.NewPublicProductServiceProcessor(handler)}
return self
}
type DeveloperApiServiceProcessor struct {
*developer_api.DeveloperApiServiceProcessor
}
func NewDeveloperApiServiceProcessor(handler DeveloperApiService) *DeveloperApiServiceProcessor {
self := &DeveloperApiServiceProcessor{developer_api.NewDeveloperApiServiceProcessor(handler)}
return self
}
type PlaygroundServiceProcessor struct {
*playground.PlaygroundServiceProcessor
}
func NewPlaygroundServiceProcessor(handler PlaygroundService) *PlaygroundServiceProcessor {
self := &PlaygroundServiceProcessor{playground.NewPlaygroundServiceProcessor(handler)}
return self
}
type DatabaseServiceProcessor struct {
*database.DatabaseServiceProcessor
}
func NewDatabaseServiceProcessor(handler DatabaseService) *DatabaseServiceProcessor {
self := &DatabaseServiceProcessor{database.NewDatabaseServiceProcessor(handler)}
return self
}
type ResourceServiceProcessor struct {
*resource.ResourceServiceProcessor
}
func NewResourceServiceProcessor(handler ResourceService) *ResourceServiceProcessor {
self := &ResourceServiceProcessor{resource.NewResourceServiceProcessor(handler)}
return self
}
type PassportServiceProcessor struct {
*passport.PassportServiceProcessor
}
func NewPassportServiceProcessor(handler PassportService) *PassportServiceProcessor {
self := &PassportServiceProcessor{passport.NewPassportServiceProcessor(handler)}
return self
}
type WorkflowServiceProcessor struct {
*workflow.WorkflowServiceProcessor
}
func NewWorkflowServiceProcessor(handler WorkflowService) *WorkflowServiceProcessor {
self := &WorkflowServiceProcessor{workflow.NewWorkflowServiceProcessor(handler)}
return self
}
type KnowledgeServiceProcessor struct {
*knowledge.DatasetServiceProcessor
}
func NewKnowledgeServiceProcessor(handler KnowledgeService) *KnowledgeServiceProcessor {
self := &KnowledgeServiceProcessor{knowledge.NewDatasetServiceProcessor(handler)}
return self
}
type BotOpenApiServiceProcessor struct {
*bot_open_api.BotOpenApiServiceProcessor
}
func NewBotOpenApiServiceProcessor(handler BotOpenApiService) *BotOpenApiServiceProcessor {
self := &BotOpenApiServiceProcessor{bot_open_api.NewBotOpenApiServiceProcessor(handler)}
return self
}
type UploadServiceProcessor struct {
*upload.UploadServiceProcessor
}
func NewUploadServiceProcessor(handler UploadService) *UploadServiceProcessor {
self := &UploadServiceProcessor{upload.NewUploadServiceProcessor(handler)}
return self
}
type ConfigServiceProcessor struct {
*config.ConfigServiceProcessor
}
func NewConfigServiceProcessor(handler ConfigService) *ConfigServiceProcessor {
self := &ConfigServiceProcessor{config.NewConfigServiceProcessor(handler)}
return self
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,298 @@
// Code generated by thriftgo (0.4.2). DO NOT EDIT.
package marketplace_common
import (
"database/sql"
"database/sql/driver"
"fmt"
"github.com/apache/thrift/lib/go/thrift"
)
type FollowType int64
const (
// Unknown
FollowType_Unknown FollowType = 0
// followee
FollowType_Followee FollowType = 1
// follower
FollowType_Follower FollowType = 2
// MutualFollow
FollowType_MutualFollow FollowType = 3
)
func (p FollowType) String() string {
switch p {
case FollowType_Unknown:
return "Unknown"
case FollowType_Followee:
return "Followee"
case FollowType_Follower:
return "Follower"
case FollowType_MutualFollow:
return "MutualFollow"
}
return "<UNSET>"
}
func FollowTypeFromString(s string) (FollowType, error) {
switch s {
case "Unknown":
return FollowType_Unknown, nil
case "Followee":
return FollowType_Followee, nil
case "Follower":
return FollowType_Follower, nil
case "MutualFollow":
return FollowType_MutualFollow, nil
}
return FollowType(0), fmt.Errorf("not a valid FollowType string")
}
func FollowTypePtr(v FollowType) *FollowType { return &v }
func (p *FollowType) Scan(value interface{}) (err error) {
var result sql.NullInt64
err = result.Scan(value)
*p = FollowType(result.Int64)
return
}
func (p *FollowType) Value() (driver.Value, error) {
if p == nil {
return nil, nil
}
return int64(*p), nil
}
type Price struct {
// amount
Amount int64 `thrift:"Amount,1" form:"amount" json:"amount,string"`
// Currencies such as USD and CNY
Currency string `thrift:"Currency,2" form:"currency" json:"currency"`
// decimal places
DecimalNum int8 `thrift:"DecimalNum,3" form:"decimal_num" json:"decimal_num"`
}
func NewPrice() *Price {
return &Price{}
}
func (p *Price) InitDefault() {
}
func (p *Price) GetAmount() (v int64) {
return p.Amount
}
func (p *Price) GetCurrency() (v string) {
return p.Currency
}
func (p *Price) GetDecimalNum() (v int8) {
return p.DecimalNum
}
var fieldIDToName_Price = map[int16]string{
1: "Amount",
2: "Currency",
3: "DecimalNum",
}
func (p *Price) Read(iprot thrift.TProtocol) (err error) {
var fieldTypeId thrift.TType
var fieldId int16
if _, err = iprot.ReadStructBegin(); err != nil {
goto ReadStructBeginError
}
for {
_, fieldTypeId, fieldId, err = iprot.ReadFieldBegin()
if err != nil {
goto ReadFieldBeginError
}
if fieldTypeId == thrift.STOP {
break
}
switch fieldId {
case 1:
if fieldTypeId == thrift.I64 {
if err = p.ReadField1(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
case 2:
if fieldTypeId == thrift.STRING {
if err = p.ReadField2(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
case 3:
if fieldTypeId == thrift.BYTE {
if err = p.ReadField3(iprot); err != nil {
goto ReadFieldError
}
} else if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
default:
if err = iprot.Skip(fieldTypeId); err != nil {
goto SkipFieldError
}
}
if err = iprot.ReadFieldEnd(); err != nil {
goto ReadFieldEndError
}
}
if err = iprot.ReadStructEnd(); err != nil {
goto ReadStructEndError
}
return nil
ReadStructBeginError:
return thrift.PrependError(fmt.Sprintf("%T read struct begin error: ", p), err)
ReadFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T read field %d begin error: ", p, fieldId), err)
ReadFieldError:
return thrift.PrependError(fmt.Sprintf("%T read field %d '%s' error: ", p, fieldId, fieldIDToName_Price[fieldId]), err)
SkipFieldError:
return thrift.PrependError(fmt.Sprintf("%T field %d skip type %d error: ", p, fieldId, fieldTypeId), err)
ReadFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T read field end error", p), err)
ReadStructEndError:
return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
}
func (p *Price) ReadField1(iprot thrift.TProtocol) error {
var _field int64
if v, err := iprot.ReadI64(); err != nil {
return err
} else {
_field = v
}
p.Amount = _field
return nil
}
func (p *Price) ReadField2(iprot thrift.TProtocol) error {
var _field string
if v, err := iprot.ReadString(); err != nil {
return err
} else {
_field = v
}
p.Currency = _field
return nil
}
func (p *Price) ReadField3(iprot thrift.TProtocol) error {
var _field int8
if v, err := iprot.ReadByte(); err != nil {
return err
} else {
_field = v
}
p.DecimalNum = _field
return nil
}
func (p *Price) Write(oprot thrift.TProtocol) (err error) {
var fieldId int16
if err = oprot.WriteStructBegin("Price"); err != nil {
goto WriteStructBeginError
}
if p != nil {
if err = p.writeField1(oprot); err != nil {
fieldId = 1
goto WriteFieldError
}
if err = p.writeField2(oprot); err != nil {
fieldId = 2
goto WriteFieldError
}
if err = p.writeField3(oprot); err != nil {
fieldId = 3
goto WriteFieldError
}
}
if err = oprot.WriteFieldStop(); err != nil {
goto WriteFieldStopError
}
if err = oprot.WriteStructEnd(); err != nil {
goto WriteStructEndError
}
return nil
WriteStructBeginError:
return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
WriteFieldError:
return thrift.PrependError(fmt.Sprintf("%T write field %d error: ", p, fieldId), err)
WriteFieldStopError:
return thrift.PrependError(fmt.Sprintf("%T write field stop error: ", p), err)
WriteStructEndError:
return thrift.PrependError(fmt.Sprintf("%T write struct end error: ", p), err)
}
func (p *Price) writeField1(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("Amount", thrift.I64, 1); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteI64(p.Amount); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 1 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 1 end error: ", p), err)
}
func (p *Price) writeField2(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("Currency", thrift.STRING, 2); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteString(p.Currency); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 2 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 2 end error: ", p), err)
}
func (p *Price) writeField3(oprot thrift.TProtocol) (err error) {
if err = oprot.WriteFieldBegin("DecimalNum", thrift.BYTE, 3); err != nil {
goto WriteFieldBeginError
}
if err := oprot.WriteByte(p.DecimalNum); err != nil {
return err
}
if err = oprot.WriteFieldEnd(); err != nil {
goto WriteFieldEndError
}
return nil
WriteFieldBeginError:
return thrift.PrependError(fmt.Sprintf("%T write field 3 begin error: ", p), err)
WriteFieldEndError:
return thrift.PrependError(fmt.Sprintf("%T write field 3 end error: ", p), err)
}
func (p *Price) String() string {
if p == nil {
return "<nil>"
}
return fmt.Sprintf("Price(%+v)", *p)
}
File diff suppressed because it is too large Load Diff

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