Repository: Peiiii/AgentVerse Branch: master Commit: 3c17c5482014 Files: 667 Total size: 1.8 MB Directory structure: gitextract_5vq11rbw/ ├── .agent/ │ └── workflows/ │ ├── feature-based-architecture.md │ └── governance-strategy.md ├── .babelrc.js ├── .codex/ │ └── skills/ │ └── project-os/ │ ├── .skild/ │ │ └── install.json │ ├── SKILL.md │ └── assets/ │ ├── AGENTS.template.md │ ├── commands/ │ │ └── commands.md │ └── docs/ │ └── workflows/ │ └── npm-release-process.md ├── .cursor/ │ ├── commands/ │ │ └── commit.md │ ├── cursorignore │ └── rules/ │ ├── README.md │ ├── agentverse-project.mdc │ ├── code-simplicity.mdc │ ├── commit.mdc │ ├── core.mdc │ ├── customization.mdc │ ├── file-organization.mdc │ ├── file-size-limits.mdc │ ├── generate-world-class-artistic-ui.mdc │ ├── naming-conventions.mdc │ ├── portal-service-bus-architecture.mdc │ ├── quick-commands.mdc │ ├── riper-workflow.mdc │ ├── start-phase.mdc │ └── state.mdc ├── .gitignore ├── .i18n-ally.yml ├── .npmrc ├── .ossutilconfig.example ├── AGENTS.md ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTORS.md ├── LICENSE ├── README.md ├── README_EN.md ├── babel.config.cjs ├── commands/ │ └── commands.md ├── components.json ├── docs/ │ ├── PAGE_STRUCTURE.md │ ├── agent-action.md │ ├── architecture/ │ │ ├── agent-architecture.md │ │ ├── agents-architecture.md │ │ ├── chat-discussion-features.md │ │ ├── diagrams/ │ │ │ └── architecture.mmd │ │ ├── discussions-architecture.md │ │ ├── extension-architecture.md │ │ └── system-design.md │ ├── character-templates.md │ ├── development/ │ │ ├── file-manager-architecture.md │ │ ├── file-manager-global-tree-design.md │ │ └── world-class-chat-html-preview-plan.md │ ├── development-guide.md │ ├── development-plan.md │ ├── features-overview.md │ ├── i18n-coverage-report.md │ ├── i18n-tools-guide.md │ ├── logs/ │ │ ├── README.md │ │ ├── TEMPLATE.md │ │ ├── v0.0.1-init/ │ │ │ └── iteration-notes.md │ │ ├── v0.1.0-backend-ready/ │ │ │ ├── analysis.md │ │ │ └── iteration-notes.md │ │ ├── v0.1.1-notes-sidebar/ │ │ │ └── iteration-notes.md │ │ ├── v0.1.10-stream-normalizer-robust/ │ │ │ └── iteration-notes.md │ │ ├── v0.1.11-mention-self-guard/ │ │ │ └── iteration-notes.md │ │ ├── v0.1.12-message-merge-safety/ │ │ │ └── iteration-notes.md │ │ ├── v0.1.13-v2ex-post/ │ │ │ ├── iteration-notes.md │ │ │ └── v2ex-post.md │ │ ├── v0.1.14-sidebar-github/ │ │ │ └── iteration-notes.md │ │ ├── v0.1.15-activitybar-github/ │ │ │ └── iteration-notes.md │ │ ├── v0.1.16-readme-screenshots/ │ │ │ └── iteration-notes.md │ │ ├── v0.1.17-dashscope-models/ │ │ │ └── iteration-notes.md │ │ ├── v0.1.2-auth-email/ │ │ │ └── iteration-notes.md │ │ ├── v0.1.3-auth-optional/ │ │ │ └── iteration-notes.md │ │ ├── v0.1.4-auth-entry/ │ │ │ └── iteration-notes.md │ │ ├── v0.1.5-poop-impact/ │ │ │ └── iteration-notes.md │ │ ├── v0.1.6-stream-dedupe/ │ │ │ └── iteration-notes.md │ │ ├── v0.1.7-streaming-delta-normalization/ │ │ │ └── iteration-notes.md │ │ ├── v0.1.8-streaming-mode-normalization/ │ │ │ └── iteration-notes.md │ │ └── v0.1.9-poop-impact-drama/ │ │ └── iteration-notes.md │ ├── mcp-integration.md │ ├── naming-research.md │ ├── project-standards.md │ ├── prompt-experiments.md │ ├── prompts/ │ │ └── generate-world-class-artistic-ui.md │ ├── references/ │ │ ├── agent-chat-tutorial.md │ │ ├── tsdown-docs/ │ │ │ ├── .vitepress/ │ │ │ │ ├── components/ │ │ │ │ │ ├── HomePage.vue │ │ │ │ │ ├── VideoModal.vue │ │ │ │ │ └── overrides/ │ │ │ │ │ └── vp-hero.vue │ │ │ │ ├── config/ │ │ │ │ │ ├── index.ts │ │ │ │ │ └── theme.ts │ │ │ │ ├── i18n/ │ │ │ │ │ ├── composable.ts │ │ │ │ │ ├── translate-map.ts │ │ │ │ │ └── utils.ts │ │ │ │ ├── scripts/ │ │ │ │ │ └── docs-generate.ts │ │ │ │ └── theme/ │ │ │ │ ├── Layout.vue │ │ │ │ ├── custom.css │ │ │ │ └── index.ts │ │ │ ├── advanced/ │ │ │ │ ├── benchmark.md │ │ │ │ ├── hooks.md │ │ │ │ ├── plugins.md │ │ │ │ ├── programmatic-usage.md │ │ │ │ └── rolldown-options.md │ │ │ ├── guide/ │ │ │ │ ├── faq.md │ │ │ │ ├── getting-started.md │ │ │ │ ├── index.md │ │ │ │ └── migrate-from-tsup.md │ │ │ ├── index.md │ │ │ ├── options/ │ │ │ │ ├── cleaning.md │ │ │ │ ├── config-file.md │ │ │ │ ├── dependencies.md │ │ │ │ ├── dts.md │ │ │ │ ├── entry.md │ │ │ │ ├── minification.md │ │ │ │ ├── output-directory.md │ │ │ │ ├── output-format.md │ │ │ │ ├── package-exports.md │ │ │ │ ├── platform.md │ │ │ │ ├── shims.md │ │ │ │ ├── silent-mode.md │ │ │ │ ├── sourcemap.md │ │ │ │ ├── target.md │ │ │ │ ├── tree-shaking.md │ │ │ │ ├── unbundle.md │ │ │ │ └── watch-mode.md │ │ │ ├── recipes/ │ │ │ │ └── vue-support.md │ │ │ ├── reference/ │ │ │ │ └── cli.md │ │ │ ├── vite.config.ts │ │ │ └── zh-CN/ │ │ │ ├── advanced/ │ │ │ │ ├── benchmark.md │ │ │ │ ├── hooks.md │ │ │ │ ├── plugins.md │ │ │ │ ├── programmatic-usage.md │ │ │ │ └── rolldown-options.md │ │ │ ├── guide/ │ │ │ │ ├── faq.md │ │ │ │ ├── getting-started.md │ │ │ │ ├── index.md │ │ │ │ └── migrate-from-tsup.md │ │ │ ├── index.md │ │ │ ├── options/ │ │ │ │ ├── cleaning.md │ │ │ │ ├── config-file.md │ │ │ │ ├── dependencies.md │ │ │ │ ├── dts.md │ │ │ │ ├── entry.md │ │ │ │ ├── minification.md │ │ │ │ ├── output-directory.md │ │ │ │ ├── output-format.md │ │ │ │ ├── package-exports.md │ │ │ │ ├── platform.md │ │ │ │ ├── shims.md │ │ │ │ ├── silent-mode.md │ │ │ │ ├── sourcemap.md │ │ │ │ ├── target.md │ │ │ │ ├── tree-shaking.md │ │ │ │ ├── unbundle.md │ │ │ │ └── watch-mode.md │ │ │ ├── recipes/ │ │ │ │ └── vue-support.md │ │ │ └── reference/ │ │ │ └── cli.md │ │ └── web-mcp-doc.md │ ├── scheduler-design.md │ ├── use-all-tools-example.md │ ├── v2ex-post.md │ └── workflows/ │ └── npm-release-process.md ├── eslint.config.js ├── functions/ │ ├── _lib/ │ │ ├── config.ts │ │ ├── crypto.ts │ │ ├── email.ts │ │ ├── http.ts │ │ ├── sessions.ts │ │ └── validators.ts │ ├── _types.ts │ └── api/ │ └── auth/ │ ├── login.ts │ ├── logout.ts │ ├── me.ts │ ├── register.ts │ ├── request-password-reset.ts │ ├── resend-verification.ts │ ├── reset-password.ts │ └── verify-email.ts ├── i18next-scanner.config.cjs ├── i18next-scanner.config.js ├── index.html ├── jest.config.cjs ├── migrations/ │ └── 0001_auth.sql ├── package.json ├── packages/ │ ├── rx-nested-bean/ │ │ ├── package.json │ │ ├── src/ │ │ │ ├── index.ts │ │ │ └── v2.ts │ │ └── tsconfig.json │ └── service-bus-portal/ │ ├── LICENSE │ ├── MIGRATION.md │ ├── MIGRATION_TO_TSDOWN.md │ ├── PACKAGE_SUMMARY.md │ ├── README.md │ ├── examples/ │ │ ├── README.md │ │ ├── basic-usage.ts │ │ ├── comprehensive-example.ts │ │ ├── iframe-example.ts │ │ └── worker-example.ts │ ├── package.json │ ├── scripts/ │ │ └── publish.sh │ ├── src/ │ │ ├── core.ts │ │ ├── factory.ts │ │ ├── index.ts │ │ ├── service-bus.ts │ │ └── types.ts │ ├── tsconfig.json │ └── tsdown.config.ts ├── pnpm-workspace.yaml ├── public/ │ ├── iframe-portal.html │ └── worker-portal.js ├── scripts/ │ ├── check-i18n-coverage.cjs │ ├── check-i18n-coverage.js │ ├── metrics/ │ │ ├── feature-structure.cjs │ │ └── top-loc.cjs │ └── rename-hooks-to-kebab-case.sh ├── src/ │ ├── App.tsx │ ├── common/ │ │ ├── components/ │ │ │ ├── common/ │ │ │ │ ├── breakpoint-provider.tsx │ │ │ │ ├── client-breakpoint-provider.tsx │ │ │ │ ├── icon-registry.tsx │ │ │ │ ├── language/ │ │ │ │ │ └── index.ts │ │ │ │ ├── language-toggle.tsx │ │ │ │ ├── logo.tsx │ │ │ │ ├── plugin-router.tsx │ │ │ │ ├── redirect.tsx │ │ │ │ ├── role-badge.tsx │ │ │ │ ├── status-indicator.tsx │ │ │ │ ├── theme/ │ │ │ │ │ ├── context.tsx │ │ │ │ │ ├── index.ts │ │ │ │ │ └── toggle.tsx │ │ │ │ └── theme-toggle.tsx │ │ │ ├── layout/ │ │ │ │ ├── page-container.tsx │ │ │ │ └── responsive-container.tsx │ │ │ ├── layouts/ │ │ │ │ └── scrollable-layout.tsx │ │ │ └── ui/ │ │ │ ├── alert-dialog.tsx │ │ │ ├── alert.tsx │ │ │ ├── auto-resize-textarea.tsx │ │ │ ├── avatar.tsx │ │ │ ├── badge.tsx │ │ │ ├── button.tsx │ │ │ ├── card.tsx │ │ │ ├── checkbox.tsx │ │ │ ├── dialog.tsx │ │ │ ├── dropdown-menu.tsx │ │ │ ├── hover-card.tsx │ │ │ ├── input.tsx │ │ │ ├── label.tsx │ │ │ ├── markdown/ │ │ │ │ ├── code-block-container.tsx │ │ │ │ ├── code-block.tsx │ │ │ │ ├── components/ │ │ │ │ │ ├── error-boundary.tsx │ │ │ │ │ ├── mermaid-renderer.ts │ │ │ │ │ └── mermaid.tsx │ │ │ │ ├── copy-code-button.tsx │ │ │ │ ├── index.tsx │ │ │ │ ├── types.ts │ │ │ │ └── world-class-markdown.css │ │ │ ├── modal/ │ │ │ │ ├── context.tsx │ │ │ │ ├── hooks.ts │ │ │ │ ├── index.ts │ │ │ │ ├── provider.tsx │ │ │ │ └── types.ts │ │ │ ├── popover.tsx │ │ │ ├── scroll-area.tsx │ │ │ ├── select.tsx │ │ │ ├── separator.tsx │ │ │ ├── sheet.tsx │ │ │ ├── skeleton.tsx │ │ │ ├── slider.tsx │ │ │ ├── smart-avatar.tsx │ │ │ ├── switch.tsx │ │ │ ├── tabs.tsx │ │ │ ├── textarea.tsx │ │ │ ├── toast.tsx │ │ │ ├── toaster.tsx │ │ │ └── tooltip.tsx │ │ ├── features/ │ │ │ ├── agents/ │ │ │ │ ├── components/ │ │ │ │ │ ├── add-agent-dialog/ │ │ │ │ │ │ ├── add-agent-dialog-content.tsx │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── use-add-agent-dialog.tsx │ │ │ │ │ ├── agent-tools/ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── agent-analysis.tool.ts │ │ │ │ │ │ ├── code-analysis.tool.ts │ │ │ │ │ │ ├── display-quick-actions.tool.ts │ │ │ │ │ │ ├── file-system.tool.ts │ │ │ │ │ │ ├── get-current-time.tool.ts │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── network.tool.ts │ │ │ │ │ │ ├── tool-factories.ts │ │ │ │ │ │ └── update-agent.tool.tsx │ │ │ │ │ ├── avatars/ │ │ │ │ │ │ ├── clickable-agent-avatar.tsx │ │ │ │ │ │ └── use-avatar-interaction.ts │ │ │ │ │ ├── cards/ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── agent-card.tsx │ │ │ │ │ │ ├── agent-chat-card.tsx │ │ │ │ │ │ ├── agent-group-card.tsx │ │ │ │ │ │ ├── agent-hover-card.tsx │ │ │ │ │ │ ├── agent-info-card.tsx │ │ │ │ │ │ ├── agent-select-card.tsx │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── modern-agent-card.tsx │ │ │ │ │ ├── configuration/ │ │ │ │ │ │ ├── agent-configuration-assistant.tsx │ │ │ │ │ │ ├── agent-configuration-preview.tsx │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── use-agent-configuration-tools.tsx │ │ │ │ │ ├── dialogs/ │ │ │ │ │ │ ├── add-agent-dialog.tsx │ │ │ │ │ │ ├── custom-team-dialog.tsx │ │ │ │ │ │ ├── edit-agent-dialog.tsx │ │ │ │ │ │ └── index.ts │ │ │ │ │ ├── floating-agent-info.tsx │ │ │ │ │ ├── forms/ │ │ │ │ │ │ ├── agent-embedded-form.tsx │ │ │ │ │ │ ├── agent-form.tsx │ │ │ │ │ │ └── index.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── lists/ │ │ │ │ │ │ ├── agent-combination-list.tsx │ │ │ │ │ │ ├── agent-list.tsx │ │ │ │ │ │ ├── agent-select-list.tsx │ │ │ │ │ │ └── index.ts │ │ │ │ │ ├── member-management.tsx │ │ │ │ │ └── preview/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── agent-preview-chat.tsx │ │ │ │ │ ├── agent-preview-tools.example.ts │ │ │ │ │ └── index.ts │ │ │ │ └── extensions/ │ │ │ │ └── index.tsx │ │ │ ├── all-in-one-agent/ │ │ │ │ ├── README.md │ │ │ │ ├── components/ │ │ │ │ │ ├── agent-tools/ │ │ │ │ │ │ ├── calculator.tool.ts │ │ │ │ │ │ ├── clear-suggestions.tool.ts │ │ │ │ │ │ ├── file-system.tool.ts │ │ │ │ │ │ ├── get-current-time.tool.ts │ │ │ │ │ │ ├── html-preview-from-file.tool.tsx │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ ├── provide-next-steps.tool.ts │ │ │ │ │ │ ├── recommend-topics.tool.ts │ │ │ │ │ │ ├── request-user-choice.tool.ts │ │ │ │ │ │ ├── send-message-to-iframe.tool.tsx │ │ │ │ │ │ ├── subscribe-iframe-messages.tool.tsx │ │ │ │ │ │ └── weather.tool.ts │ │ │ │ │ ├── all-in-one-agent-dock.tsx │ │ │ │ │ └── smart-assistant-dialog.tsx │ │ │ │ ├── extensions/ │ │ │ │ │ └── index.tsx │ │ │ │ ├── hooks/ │ │ │ │ │ └── use-all-in-one-agent-mode.tsx │ │ │ │ ├── index.ts │ │ │ │ └── pages/ │ │ │ │ └── all-in-one-agent-page.tsx │ │ │ ├── app/ │ │ │ │ └── components/ │ │ │ │ ├── activity-bar.tsx │ │ │ │ ├── app-loading.tsx │ │ │ │ └── mobile-bottom-bar.tsx │ │ │ ├── auth/ │ │ │ │ ├── components/ │ │ │ │ │ ├── auth-gate.tsx │ │ │ │ │ ├── auth-routes.tsx │ │ │ │ │ └── auth-shell.tsx │ │ │ │ └── pages/ │ │ │ │ ├── forgot-password-page.tsx │ │ │ │ ├── login-page.tsx │ │ │ │ ├── reset-password-page.tsx │ │ │ │ └── verify-email-page.tsx │ │ │ ├── chat/ │ │ │ │ ├── components/ │ │ │ │ │ ├── agent-chat/ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── agent-chat-container.tsx │ │ │ │ │ │ ├── agent-chat-header-with-info.tsx │ │ │ │ │ │ ├── agent-chat-header.tsx │ │ │ │ │ │ ├── agent-chat-input.tsx │ │ │ │ │ │ ├── agent-chat-messages.tsx │ │ │ │ │ │ ├── agent-chat-provider-wrapper.tsx │ │ │ │ │ │ ├── index.ts │ │ │ │ │ │ └── tool-call-renderer.tsx │ │ │ │ │ ├── chat-area.tsx │ │ │ │ │ ├── chat-empty-guide.tsx │ │ │ │ │ ├── chat-welcome-header.tsx │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── mention-suggestions.tsx │ │ │ │ │ ├── message/ │ │ │ │ │ │ ├── index.tsx │ │ │ │ │ │ ├── interaction-overlay.tsx │ │ │ │ │ │ ├── message-capture.tsx │ │ │ │ │ │ ├── message-content-blocks.tsx │ │ │ │ │ │ ├── message-item-wechat.tsx │ │ │ │ │ │ ├── message-item.tsx │ │ │ │ │ │ ├── message-list-desktop.tsx │ │ │ │ │ │ ├── message-list-mobile.tsx │ │ │ │ │ │ ├── message-list.tsx │ │ │ │ │ │ ├── message-markdown-content.tsx │ │ │ │ │ │ ├── message-preview-dialog.tsx │ │ │ │ │ │ └── tool-result-list.tsx │ │ │ │ │ ├── message-input-desktop.tsx │ │ │ │ │ ├── message-input-mobile.tsx │ │ │ │ │ ├── message-input.tsx │ │ │ │ │ ├── modern-chat-input.tsx │ │ │ │ │ └── suggestions/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── suggestion.types.ts │ │ │ │ │ └── suggestions-provider.tsx │ │ │ │ ├── hooks/ │ │ │ │ │ └── use-poop-trigger.ts │ │ │ │ ├── managers/ │ │ │ │ │ └── chat-scroll.manager.ts │ │ │ │ └── stores/ │ │ │ │ ├── chat-scroll.store.ts │ │ │ │ └── interaction.store.ts │ │ │ ├── discussion/ │ │ │ │ └── components/ │ │ │ │ ├── control/ │ │ │ │ │ ├── clear-messages-button.tsx │ │ │ │ │ ├── discussion-controller.tsx │ │ │ │ │ └── use-discussion-control.ts │ │ │ │ ├── list/ │ │ │ │ │ ├── discussion-avatar.tsx │ │ │ │ │ ├── discussion-item.tsx │ │ │ │ │ ├── discussion-list-header.tsx │ │ │ │ │ ├── discussion-list.tsx │ │ │ │ │ ├── index.ts │ │ │ │ │ └── types.ts │ │ │ │ ├── member/ │ │ │ │ │ ├── add-member-dialog.tsx │ │ │ │ │ ├── member-item.tsx │ │ │ │ │ ├── member-list.tsx │ │ │ │ │ ├── member-skeleton.tsx │ │ │ │ │ ├── member-toggle-button.tsx │ │ │ │ │ ├── mobile-member-drawer.tsx │ │ │ │ │ ├── mobile-member-list.tsx │ │ │ │ │ └── quick-member-selector.tsx │ │ │ │ ├── mobile/ │ │ │ │ │ ├── mobile-action-sheet.tsx │ │ │ │ │ └── mobile-header.tsx │ │ │ │ ├── notes/ │ │ │ │ │ └── discussion-notes-panel.tsx │ │ │ │ ├── settings/ │ │ │ │ │ ├── discussion-settings-button.tsx │ │ │ │ │ ├── discussion-settings-panel.tsx │ │ │ │ │ ├── setting-item.tsx │ │ │ │ │ ├── setting-select.tsx │ │ │ │ │ ├── setting-slider.tsx │ │ │ │ │ └── setting-switch.tsx │ │ │ │ └── sidebar/ │ │ │ │ └── discussion-sidebar.tsx │ │ │ ├── home/ │ │ │ │ └── components/ │ │ │ │ ├── agent-popover.tsx │ │ │ │ ├── initial-experience.tsx │ │ │ │ ├── initial-input.tsx │ │ │ │ ├── team-details-dialog.tsx │ │ │ │ └── welcome-header.tsx │ │ │ └── world-class-chat/ │ │ │ ├── components/ │ │ │ │ ├── settings-panel/ │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── memory-setting.tsx │ │ │ │ │ ├── prompt-setting.tsx │ │ │ │ │ ├── settings-registry.ts │ │ │ │ │ ├── types.ts │ │ │ │ │ └── world-class-settings-panel.tsx │ │ │ │ └── world-class-chat-html-preview.tsx │ │ │ ├── copy-message-button.tsx │ │ │ ├── hooks/ │ │ │ │ ├── use-iframe-manager.ts │ │ │ │ ├── use-side-panel-manager.ts │ │ │ │ └── use-suggestions-manager.ts │ │ │ ├── index.ts │ │ │ ├── side-panel.tsx │ │ │ ├── stores/ │ │ │ │ ├── memory.store.ts │ │ │ │ └── world-class-chat-settings.store.ts │ │ │ ├── world-class-chat-container.tsx │ │ │ ├── world-class-chat-input-bar.tsx │ │ │ ├── world-class-chat-message-list.tsx │ │ │ ├── world-class-chat-top-bar.tsx │ │ │ └── world-class-tool-call-renderer.tsx │ │ ├── hooks/ │ │ │ ├── index.ts │ │ │ ├── use-agent-file-manager.ts │ │ │ ├── use-all-tools.ts │ │ │ ├── use-chat-auto-scroll.ts │ │ │ ├── use-chat-message-cache.ts │ │ │ ├── use-mcp-servers.ts │ │ │ ├── use-mention-position.ts │ │ │ ├── use-mention.ts │ │ │ └── use-provide-agent-tools.ts │ │ ├── lib/ │ │ │ ├── agent/ │ │ │ │ └── prompt/ │ │ │ │ ├── prompt-builder.ts │ │ │ │ └── prompts.ts │ │ │ ├── ai-service/ │ │ │ │ └── index.ts │ │ │ ├── capabilities/ │ │ │ │ └── index.ts │ │ │ ├── discussion/ │ │ │ │ └── message-utils.ts │ │ │ ├── env.ts │ │ │ ├── file-manager.service.ts │ │ │ ├── file-tree.service.ts │ │ │ ├── mcp/ │ │ │ │ ├── examples/ │ │ │ │ │ └── mock-server.ts │ │ │ │ ├── index.ts │ │ │ │ └── transports/ │ │ │ │ ├── event.ts │ │ │ │ ├── index.ts │ │ │ │ ├── postmessage.ts │ │ │ │ └── transport.ts │ │ │ ├── prompts/ │ │ │ │ └── index.ts │ │ │ ├── resource.ts │ │ │ ├── runnable-agent/ │ │ │ │ ├── README.md │ │ │ │ ├── agent-utils/ │ │ │ │ │ ├── handlers/ │ │ │ │ │ │ ├── text-message.handler.ts │ │ │ │ │ │ └── tool-call.handler.ts │ │ │ │ │ ├── openai-agent.ts │ │ │ │ │ ├── stream-processor.ts │ │ │ │ │ └── types.ts │ │ │ │ ├── experimental-inbrowser-agent.ts │ │ │ │ ├── index.ts │ │ │ │ └── sse-json-decoder.ts │ │ │ ├── rx-event.ts │ │ │ ├── rx-state/ │ │ │ │ └── index.ts │ │ │ ├── service-bus/ │ │ │ │ └── index.ts │ │ │ ├── storage/ │ │ │ │ ├── index.ts │ │ │ │ ├── indexeddb.ts │ │ │ │ ├── local.ts │ │ │ │ ├── mock-http.ts │ │ │ │ └── types.ts │ │ │ ├── typed-bus/ │ │ │ │ ├── __tests__/ │ │ │ │ │ └── environment-bus.test.ts │ │ │ │ ├── base.ts │ │ │ │ ├── bus-proxy.ts │ │ │ │ ├── decorators.ts │ │ │ │ ├── implementations/ │ │ │ │ │ ├── capability-bus.ts │ │ │ │ │ ├── environment-bus.ts │ │ │ │ │ ├── event-bus.ts │ │ │ │ │ ├── index.ts │ │ │ │ │ ├── message-bus.ts │ │ │ │ │ ├── resource-bus.ts │ │ │ │ │ └── state-bus.ts │ │ │ │ ├── index.ts │ │ │ │ ├── key.ts │ │ │ │ ├── middleware-chain.ts │ │ │ │ └── types.ts │ │ │ ├── utils.ts │ │ │ └── with-event.ts │ │ └── types/ │ │ ├── agent-config.ts │ │ ├── agent.ts │ │ ├── ai.ts │ │ ├── auth.ts │ │ ├── chat.ts │ │ ├── discussion-member.ts │ │ ├── discussion.ts │ │ ├── guide.ts │ │ ├── route.ts │ │ └── storage.ts │ ├── core/ │ │ ├── bootstrap/ │ │ │ ├── agents.bootstrap.ts │ │ │ └── app.bootstrap.ts │ │ ├── config/ │ │ │ ├── agents/ │ │ │ │ ├── base-types.ts │ │ │ │ ├── index.ts │ │ │ │ ├── moderators/ │ │ │ │ │ ├── meta-cognitive-orchestrator.ts │ │ │ │ │ ├── structured-thinking-moderator.ts │ │ │ │ │ └── troll-moderator.ts │ │ │ │ ├── practical-agents/ │ │ │ │ │ ├── data-interpreter.ts │ │ │ │ │ ├── implementation-architect.ts │ │ │ │ │ └── startup-navigator.ts │ │ │ │ └── top-agents/ │ │ │ │ ├── cognitive-detective.ts │ │ │ │ ├── concept-alchemist.ts │ │ │ │ ├── decision-gardener.ts │ │ │ │ ├── emotion-meteorologist.ts │ │ │ │ ├── essence-perspectivist.ts │ │ │ │ ├── inspiration-archaeologist.ts │ │ │ │ ├── meaning-seeker.ts │ │ │ │ ├── multiverse-observer.ts │ │ │ │ ├── narrative-architect.ts │ │ │ │ ├── pattern-linguist.ts │ │ │ │ ├── psyche-time-traveler.ts │ │ │ │ ├── quantum-advisor.ts │ │ │ │ ├── structure-architect.ts │ │ │ │ ├── troll-attacker.ts │ │ │ │ ├── troll-cynic.ts │ │ │ │ ├── troll-hater.ts │ │ │ │ ├── troll-nonsense.ts │ │ │ │ ├── troll-picker.ts │ │ │ │ ├── troll-saboteur.ts │ │ │ │ └── troll-spammer.ts │ │ │ ├── ai.ts │ │ │ ├── guide-scenarios.ts │ │ │ ├── i18n.ts │ │ │ ├── module-order.ts │ │ │ ├── settings.ts │ │ │ ├── storage.ts │ │ │ └── ui-persist.ts │ │ ├── env.ts │ │ ├── events.ts │ │ ├── extension-manager.ts │ │ ├── hooks/ │ │ │ ├── use-agent-chat-page-helper.ts │ │ │ ├── use-app-bootstrap.ts │ │ │ ├── use-auth.ts │ │ │ ├── use-connect-navigation-store.ts │ │ │ ├── use-copy.ts │ │ │ ├── use-extensions.ts │ │ │ ├── use-i18n.ts │ │ │ ├── use-indexeddb-manager.ts │ │ │ ├── use-setup-app.ts │ │ │ ├── use-toast.ts │ │ │ ├── useAgentForm.ts │ │ │ ├── useAgents.ts │ │ │ ├── useAutoScroll.ts │ │ │ ├── useBreakpoint.ts │ │ │ ├── useCurrentDiscussionId.ts │ │ │ ├── useDiscussion.ts │ │ │ ├── useDiscussionMembers.ts │ │ │ ├── useDiscussionRuntime.ts │ │ │ ├── useDiscussionSettings.ts │ │ │ ├── useDiscussions.ts │ │ │ ├── useKeyboardExpandableList.ts │ │ │ ├── useMediaQuery.ts │ │ │ ├── useMemberSelection.ts │ │ │ ├── useMessageInput.ts │ │ │ ├── useMessageList.ts │ │ │ ├── useMessages.ts │ │ │ ├── useObservableState.ts │ │ │ ├── useOptimisticUpdate.ts │ │ │ ├── usePersistedState.ts │ │ │ ├── useViewportHeight.ts │ │ │ └── useWindowSize.ts │ │ ├── locales/ │ │ │ ├── en-US.json │ │ │ └── zh-CN.json │ │ ├── managers/ │ │ │ ├── activity-bar.manager.ts │ │ │ ├── agents.manager.ts │ │ │ ├── db-capabilities.ts │ │ │ ├── discussion/ │ │ │ │ ├── mention-resolver.ts │ │ │ │ ├── next-speaker.ts │ │ │ │ └── streaming-responder.ts │ │ │ ├── discussion-capabilities.ts │ │ │ ├── discussion-control.manager.ts │ │ │ ├── discussion-members.manager.ts │ │ │ ├── discussions.manager.ts │ │ │ ├── icon.manager.ts │ │ │ ├── index.ts │ │ │ ├── messages.manager.ts │ │ │ ├── navigation.manager.ts │ │ │ └── route-tree.manager.ts │ │ ├── presenter/ │ │ │ ├── index.ts │ │ │ ├── presenter-context.tsx │ │ │ └── presenter.ts │ │ ├── repositories/ │ │ │ ├── agent.repository.ts │ │ │ ├── ai.client.ts │ │ │ ├── data-providers.ts │ │ │ ├── discussion-member.repository.ts │ │ │ ├── discussion.repository.ts │ │ │ ├── index.ts │ │ │ ├── message.repository.ts │ │ │ └── shared.types.ts │ │ ├── stores/ │ │ │ ├── README.md │ │ │ ├── activity-bar.store.ts │ │ │ ├── agents.store.ts │ │ │ ├── auth.store.ts │ │ │ ├── discussion-members.store.ts │ │ │ ├── discussions.store.ts │ │ │ ├── icon.store.ts │ │ │ ├── mcp-server.store.ts │ │ │ ├── messages.store.ts │ │ │ ├── navigation.store.ts │ │ │ └── route-tree.store.ts │ │ ├── styles/ │ │ │ └── theme.css │ │ └── utils/ │ │ ├── auth-client.ts │ │ ├── common.util.ts │ │ ├── connect-router-with-activity-bar.ts │ │ ├── discussion-error.util.ts │ │ └── message.util.ts │ ├── desktop/ │ │ ├── desktop-app.tsx │ │ └── features/ │ │ ├── agents/ │ │ │ ├── components/ │ │ │ │ └── agent-profile-view.tsx │ │ │ ├── extensions/ │ │ │ │ └── index.tsx │ │ │ └── pages/ │ │ │ ├── agent-detail-page.tsx │ │ │ └── agents-page.tsx │ │ ├── chat/ │ │ │ ├── extensions/ │ │ │ │ └── index.tsx │ │ │ └── pages/ │ │ │ └── chat-page.tsx │ │ ├── file-manager/ │ │ │ ├── README.md │ │ │ ├── components/ │ │ │ │ ├── file-preview.tsx │ │ │ │ ├── file-tree.tsx │ │ │ │ └── pluggable-file-preview.tsx │ │ │ ├── extensions/ │ │ │ │ └── index.tsx │ │ │ ├── hooks/ │ │ │ │ ├── use-delayed-loading.ts │ │ │ │ ├── use-file-ops.ts │ │ │ │ ├── use-file-tree.ts │ │ │ │ ├── use-lightningfs-manager.ts │ │ │ │ └── use-working-directory.ts │ │ │ ├── pages/ │ │ │ │ └── file-manager-page.tsx │ │ │ ├── previewers/ │ │ │ │ ├── html-previewer.tsx │ │ │ │ ├── index.tsx │ │ │ │ ├── markdown-previewer.tsx │ │ │ │ └── text-previewer.tsx │ │ │ ├── services/ │ │ │ │ └── file-preview-registry.service.ts │ │ │ └── types/ │ │ │ └── file-preview.types.ts │ │ └── indexeddb/ │ │ ├── components/ │ │ │ ├── indexeddb-data-viewer.tsx │ │ │ ├── indexeddb-database-info.tsx │ │ │ └── indexeddb-store-manager.tsx │ │ ├── extensions/ │ │ │ └── index.tsx │ │ └── pages/ │ │ └── indexeddb-manager-page.tsx │ ├── index.css │ ├── main.tsx │ ├── mobile/ │ │ ├── features/ │ │ │ └── chat/ │ │ │ ├── extensions/ │ │ │ │ └── index.tsx │ │ │ ├── managers/ │ │ │ │ └── mobile-chat-scene.manager.ts │ │ │ ├── pages/ │ │ │ │ └── chat-page.tsx │ │ │ └── stores/ │ │ │ └── mobile-chat-scene.store.ts │ │ └── mobile-app.tsx │ └── vite-env.d.ts ├── tsconfig.app.json ├── tsconfig.json ├── tsconfig.node.json ├── vite.config.ts └── wrangler.toml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .agent/workflows/feature-based-architecture.md ================================================ --- description: Feature-Based 架构规范,用于 AI 开发时复用 --- # Feature-Based 架构规范 ## 核心原则 按**业务功能**而非技术类型组织代码。每个 feature 目录包含该功能所需的全部代码。 ## 目录结构 ``` src/ ├── common/ # 跨平台共享代码 │ └── features/ │ └── [feature-name]/ # 功能模块 │ ├── components/ # UI 组件 │ ├── hooks/ # React Hooks │ ├── stores/ # 状态管理 │ ├── services/ # 业务逻辑/API │ ├── types/ # TypeScript 类型 │ ├── utils/ # 工具函数 │ ├── managers/ # 管理器类 │ ├── extensions/ # 扩展/插件 │ └── index.ts # 公开导出 │ ├── desktop/ # 桌面端特有代码 │ └── features/ │ └── [feature-name]/ │ ├── pages/ # 页面组件 │ └── ... # 同上子目录 │ ├── mobile/ # 移动端特有代码 │ └── features/ │ └── ... │ └── core/ # 核心基础设施(非 feature) ``` ## 规则 1. **Feature 内高内聚** - 一个功能的所有代码放在同一目录下 2. **Feature 间低耦合** - 通过 `index.ts` 暴露公共 API,禁止直接引用内部文件 3. **平台代码分离** - `common` 放共享代码,`desktop`/`mobile` 放平台特有代码 4. **子目录按需创建** - 不强制所有子目录都存在,按实际需要添加 5. **命名规范** - feature 名使用 kebab-case(如 `file-manager`) ## 示例 ``` src/common/features/ ├── chat/ │ ├── components/ │ │ ├── chat-input.tsx │ │ ├── message-list.tsx │ │ └── message-item.tsx │ ├── stores/ │ │ └── chat-store.ts │ └── index.ts │ ├── agents/ │ ├── components/ │ └── extensions/ │ └── settings/ └── components/ ``` ================================================ FILE: .agent/workflows/governance-strategy.md ================================================ --- description: 代码库治理的指导思想与战略(五步法) --- # 指导思想与战略(五步法治理) ## 目标 - 提升可维护性与可扩展性 - 为接入真实后端保留清晰边界 - 保障交付速度与稳定性 ## 指导思想 1. **先保留核心价值链**:以真实用户路径和关键业务目标为优先保留对象。 2. **边界优于实现**:接口与模块边界清晰,内部实现可被替换。 3. **先减法后加法**:删除与收口先于优化,避免在噪音上雕花。 4. **先收口再优化**:统一出口、统一入口后再优化性能与体验。 5. **可验证与可回滚**:每一步都有可验证指标与回滚路径。 ## 五步法治理规划 ### 1) 删除(减法优先) - **清单化**:功能、脚本、依赖、页面、实验性模块全量盘点。 - **判定标准**:无人使用 / 无负责人 / 无测试 / 无价值 / 与现目标不一致。 - **执行方式**:先停用与标记,再物理删除;保留变更记录。 ### 2) 简化(收口通道) - **API 出口收口**:所有网络与模型调用统一到单一适配层。 - **状态与消息流收口**:避免多套状态管理与事件通道并行。 - **最少抽象**:避免过早设计,优先用清晰可读的结构替代复杂层级。 ### 3) 优化/标准化(建立约束) - **Feature 边界**:跨功能只通过 `index.ts` 暴露公共 API。 - **DTO 映射层**:后端数据与前端 UI/状态解耦。 - **目录规范**:持续执行 Feature-Based 结构,避免漂移。 ### 4) 加速(缩短反馈) - **反馈时间**:核心变更 30-60 分钟内可验证。 - **最小验证集**:lint/typecheck/关键测试/预览脚本可一键运行。 ### 5) 自动化(防回退) - **脚手架**:自动生成 feature 结构与基础文件。 - **约束工具**:eslint 规则与 CI 检查防止跨边界依赖。 - **监控机制**:持续检查无主模块与闲置依赖。 ## 交付节奏(建议) - 每个阶段以 1-2 周为一个小循环,形成可衡量的里程碑。 - 删除与简化优先级高于优化与自动化。 ================================================ FILE: .babelrc.js ================================================ module.exports = { presets: [ ['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript', ['@babel/preset-react', { runtime: 'automatic' }] ], plugins: [ ['@babel/plugin-proposal-decorators', { legacy: true }] ] }; ================================================ FILE: .codex/skills/project-os/.skild/install.json ================================================ { "schemaVersion": 1, "name": "project-os", "platform": "codex", "scope": "project", "source": "peiiii/skild/skills/project-os", "sourceType": "degit-shorthand", "installedAt": "2026-01-25T11:50:19.363Z", "installDir": "/Users/tongwenwen/Projects/Peiiii/AgentVerse/.codex/skills/project-os", "contentHash": "4a7c96587d5001c7707a44a5ed4bbc3fcaa6ee056a0daac27aca8582368cb3c3", "hasSkillMd": true, "skill": { "frontmatter": { "name": "project-os", "description": "AI project OS for autonomous loop, automated orchestration, and rule-driven execution.", "version": "0.1.1", "author": "Peiiii", "license": "MIT", "tags": [ "governance", "process", "release", "logs" ] }, "validation": { "ok": true, "issues": [], "frontmatter": { "name": "project-os", "description": "AI project OS for autonomous loop, automated orchestration, and rule-driven execution.", "version": "0.1.1", "author": "Peiiii", "license": "MIT", "tags": [ "governance", "process", "release", "logs" ] } } } } ================================================ FILE: .codex/skills/project-os/SKILL.md ================================================ --- name: project-os description: AI project OS for autonomous loop, automated orchestration, and rule-driven execution. version: 0.1.1 author: Peiiii license: MIT tags: - governance - process - release - logs --- # Project OS 用于在新项目中快速落地“开发规范 + 迭代日志 + 发布闭环”的通用体系(Project OS),面向未来演进为可自治、可编排、自动驱动研发流程的 AI 操作系统。 ## 三段式定位 1) 自治闭环 覆盖需求—实现—验证—发布—线上冒烟—复盘的端到端闭环,系统自动推动流程完成并形成可追踪证据链。 2) 自动化编排 将研发流程拆解为可编排的步骤与指令(commands/skills/workflows),以最小人工干预串联执行、回滚与验收。 3) 规则驱动执行 所有行为由 Rulebook 统一约束与裁决,确保执行一致性、合规性与可审计性;如需例外必须显式声明并记录。 ## 适用场景 - 想把一套严格交付流程迁移到其他项目。 - 需要在团队内统一验证/冒烟/发布规范。 ## 快速落地 将本 Skill 的模板复制到目标项目根目录(若已有文件,需合并而非覆盖): ```bash cp -R /assets/commands ./commands cp -R /assets/docs ./docs cp /assets/AGENTS.template.md ./AGENTS.md ``` ## 关键约束 - “完成所有/完成全部”默认执行完整上线闭环(migrations -> deploy -> 线上冒烟)。 - 冒烟测试默认使用非仓库目录环境,禁止写入仓库子目录。 - 每次开发阶段结束必须完成 build/lint/tsc + 冒烟(如适用)。 ## 扩展与维护 - 新增/修改指令:更新 `commands/commands.md` 并同步 AGENTS 索引。 - 新增/修改规则:只在 AGENTS 的 Rulebook 维护。 - 发布流程统一写入 `docs/workflows/npm-release-process.md`。 ## 模板索引 - `assets/AGENTS.template.md` - `assets/commands/commands.md` - `assets/docs/logs/TEMPLATE.md` - `assets/docs/logs/README.md` - `assets/docs/workflows/npm-release-process.md` ================================================ FILE: .codex/skills/project-os/assets/AGENTS.template.md ================================================ 1. 假设你是ceo+cto(架构师)+产品经理的综合体,从这个角度来思考所有问题 2. 不要管开发代价,永远只考虑最终最佳方案,反正都是你来开发 3. 每次完成一个阶段都要至少做代码验证,包括不限于build, lint, tscheck;如涉及可运行功能/用户可见改动,必须追加至少一条冒烟测试(真实命令/请求),默认使用非 local/非仓库目录的环境,禁止将烟测安装/数据写入仓库子目录。 4. 涉及后端或数据库变更的发布必须执行远程 migration,并对关键 API 做线上冒烟验证后才算阶段完成 5. 任何“发布/上线”必须形成闭环:migrations apply -> deploy -> 线上冒烟验证;缺一不可,否则视为未完成 6. 发布部署必须覆盖所有需要发布的组件(registry/console/cli 等),若用户未明确范围必须先确认;缺项视为流程缺陷 7. 若用户明确要求“直接发布/不做选择”,默认执行全量发布闭环(覆盖所有本次变更涉及的组件),不得再次要求用户决策 8. NPM 包发布流程详见 `docs/workflows/npm-release-process.md`,必须遵循 9. 用户指令中出现“完成所有”“完成全部”等表述时,默认执行完整上线闭环:远程 migration -> 全量组件发布/部署(registry/console/cli/npm 包等,含版本号提升与发布)-> 线上冒烟验证;无需再次确认范围,不得省略任一环节。 --- 负面清单 - 同一个功能,逻辑不应该多次实现。唯一性。 - UI 组件禁止依赖业务逻辑 --- 不急,接下来我们采取一种面向未来的逆天超级快节奏的开发方式。 ## 迭代制度(docs/logs) - 每个迭代在 `docs/logs` 下新增一个目录 - 目录内按版本号建立子目录,命名为 `v0.0.1-版本的slug`(语义化) - 每个版本目录至少包含: - 迭代完成说明(改了什么) - 测试/验证/验收方式 - 发布/部署方式 - 可选文档:PRD、讨论记录等 ## 指令/Command 机制 - 新增指令统一记录在 `commands/commands.md`,并在此处索引 - 约定元指令:输入 `/new-command` 触发创建新指令流程 - 指令文件结构:每条指令包含名称、用途、输入格式、输出/期望行为 - 后续新增或修改指令时,更新 `commands/commands.md` 并保持此处索引最新 - 已有指令: - `/new-command`:创建新指令 - `/config-meta`:调整或更新本文件(AGENTS.md)的机制/元信息 - `/commit`:进行提交操作(提交信息需使用英文) - `/validate`:运行项目验证,至少包含 `build`、`lint`、`tsc`,必要时冒烟测试 ## 规则/Rule 机制 - 规则直接维护在本文件末尾的 **Rulebook** 区域 - 约定元指令:输入 `/new-rule` 触发创建新规则流程 - 规则条目包含:名称(英文 kebab-case)、约束/适用范围、示例/反例、执行方式(工具/流程)、维护责任人 - 后续新增或修改规则时,直接在本文件的 **Rulebook** 区域追加/更新 - 默认所有规则必须严格遵守(无额外声明即视为强制);如需例外必须在规则中明确说明 ## Rulebook - **post-dev-stage-validation**:每个开发阶段结束必须做验证,至少运行 `build`、`lint`、`tsc`(如确认为无关可有理由地省略),如条件允许应做基础冒烟测试。 - **no-self-commit-without-request**:除非用户明确要求,否则禁止擅自提交/推送代码。 - **use-chinese-when-communicating**:与用户交流时使用中文。 - **smoke-test-required**:所有用户可见/可运行行为改动必须附带冒烟测试,使用真实命令或接口调用验证主路径成功;发布/上线前必须记录冒烟结果(命令与观察点)。执行方式:按组件选择对应 CLI/API/UI 最小可行流程;责任人:当次交付 owner。 - **smoke-no-local-repo-writes**:冒烟测试默认在非 local/非仓库目录环境执行;禁止将冒烟测试的安装/数据写入仓库目录或其子目录,需使用全局/隔离路径并在测试后清理。执行方式:优先 global scope 或临时目录;责任人:当次交付 owner。 - **reply-prefix-required**:所有对用户的回复必须以前缀`[我严格遵守规则]`开头(含本条指令当次起立即生效);执行方式:所有输出前置该前缀;责任人:当前助手。 ================================================ FILE: .codex/skills/project-os/assets/commands/commands.md ================================================ # Commands - `/new-command`: 新建一条指令的元指令。流程:确认名称、用途、输入格式、输出/期望行为,写入本文件并保持 `AGENTS.md` 索引同步。 - `/config-meta`: 调整或更新 `AGENTS.md` 中的机制/元信息(如规则、流程、索引等)的指令。执行时需明确变更点与预期影响。 - `/commit`: 进行提交操作(提交信息需使用英文)。 - `/validate`: 对项目进行验证,至少运行 `build`、`lint`、`tsc`,必要时补充冒烟测试。执行前需确认验证范围和可跳过项。 (后续指令在此追加,保持格式一致。) ================================================ FILE: .codex/skills/project-os/assets/docs/workflows/npm-release-process.md ================================================ # NPM Package Release Process Scope: publish npm packages in `packages/*`. This does NOT cover registry/console deployment. ## Prereqs - npm auth available via one of: - `.npmrc.publish.local` (preferred, ignored by git) - `NPM_TOKEN` env var - `npm login` (interactive) ## Standard flow 1) Create changeset ```bash pnpm changeset ``` 2) Bump versions + changelogs ```bash pnpm release:version ``` 3) Publish ```bash pnpm release:publish ``` Notes: - `release:publish` should run `release:check` (build + lint + typecheck) before publishing. - `release:publish` should create git tags automatically. ================================================ FILE: .cursor/commands/commit.md ================================================ # Git提交规则 ## 核心原则 - **禁止擅自提交**: 只有用户明确要求才能commit - **英文message**: 使用英文commit message - **默认git add .**: 自动添加所有更改 ## 前端项目要求 - **构建验证**:如果commit 后跟build,则commit前必须先运行 `pnpm build` 验证构建成功 ## 提交流程 1. 用户明确要求commit 2. 如果commit 后跟build,则运行 `pnpm build` 验证构建 3. 执行 `git add .` 4. 生成英文commit message 5. 执行 `git commit -m "message"` ================================================ FILE: .cursor/cursorignore ================================================ # CursorRIPER Framework ignore patterns # This file helps control which files are processed by Cursor's AI features # Temporary files *.tmp *.temp *.swp *~ # Build artifacts build/ dist/ out/ .next/ .nuxt/ .output/ .cache/ .parcel-cache/ .webpack/ .rollup.cache/ # Dependency directories node_modules/ bower_components/ jspm_packages/ vendor/ .pnp/ .pnp.js # Log files logs/ *.log npm-debug.log* yarn-debug.log* yarn-error.log* lerna-debug.log* # Environment files (may contain secrets) .env .env.local .env.development.local .env.test.local .env.production.local .env*.local # Debug files .nyc_output/ coverage/ .coverage/ .coverage.* htmlcov/ .hypothesis/ .pytest_cache/ nosetests.xml coverage.xml # IDE & editor directories .idea/ .vscode/ .vs/ *.sublime-project *.sublime-workspace .project .classpath .c9/ *.launch .settings/ .vim/ .DS_Store # Framework specific (uncomment as needed) # .cursor/rules/archive/ # memory-bank/backups/ ================================================ FILE: .cursor/rules/README.md ================================================ # Cursor Rules 使用说明 ## 命名规范规则 ### 文件位置 - 规则文件:`.cursor/rules/naming-conventions.mdc` - 修复脚本:`scripts/rename-hooks-to-kebab-case.sh` ### 规则内容 #### 1. 文件命名规范 - 所有文件和文件夹必须使用 **kebab-case** 命名 - Service文件必须以 `.service.ts` 结尾 #### 2. Hook命名规范 - Hook名称应当语义化,清晰表达功能用途 - 避免可能与其他功能混淆的命名 - 确保命名具有清晰的识别性 ### 当前项目修复状态 #### ✅ 已符合规范 - Service文件命名:所有service文件都已正确使用 `.service.ts` 后缀 - 部分Hook文件:`use-connect-navigation-store.ts`, `use-extensions.ts` 等 #### ❌ 需要修复 - 大部分Hook文件仍使用camelCase命名,需要改为kebab-case ### 修复步骤 #### 1. 运行重命名脚本 ```bash ./scripts/rename-hooks-to-kebab-case.sh ``` #### 2. 更新import语句 运行以下命令查找需要更新的import: ```bash grep -r 'from.*use[A-Z]' src/ --include='*.ts' --include='*.tsx' ``` #### 3. 手动更新import 将找到的import语句从: ```typescript import { useAgentChat } from "@/core/hooks/useAgentChat"; ``` 更新为: ```typescript import { useAgentChat } from "@/core/hooks/use-agent-chat"; ``` ### 规则应用 这些规则会在Cursor中自动应用,帮助: - 在创建新文件时提供命名建议 - 在代码审查时检查命名规范 - 保持项目代码风格一致性 ### 注意事项 1. **重命名前备份**:建议在运行重命名脚本前提交当前代码 2. **测试功能**:重命名后需要测试所有功能是否正常 3. **团队协作**:确保团队成员都了解并遵循这些规范 ================================================ FILE: .cursor/rules/agentverse-project.mdc ================================================ # AgentVerse Project Rules ## Project Architecture ### Directory Structure ``` src/ ├── common/ # Shared components and utilities │ ├── components/ # UI components │ ├── features/ # Feature-based organization │ │ └── agents/ # Agent-related features │ │ ├── components/ # Agent components │ │ └── extensions/ # Feature extensions │ ├── hooks/ # Custom hooks │ ├── lib/ # Core libraries │ └── types/ # Type definitions ├── core/ # Application core │ ├── config/ # Configuration │ ├── hooks/ # App-level hooks │ ├── services/ # Business services │ └── stores/ # State management ├── desktop/ # Desktop-specific features └── mobile/ # Mobile-specific features ``` ### Feature Organization - **Platform Separation**: Keep desktop/mobile specific code separate - **Feature-First**: Organize by business features, not technical layers - **Reusability**: Common components in `common/`, platform-specific in respective directories ## Agent Configuration System ### Component Structure - **Configuration**: AI-driven agent configuration assistant - **Preview**: Agent testing and preview environment - **Tools**: Reusable agent tools and utilities ### Naming Conventions - **Components**: `AgentConfigurationAssistant`, `AgentPreviewChat` - **Files**: `agent-configuration-assistant.tsx`, `agent-preview-chat.tsx` - **Hooks**: `useAgentConfigurationTools`, `useAgentPreviewTools` - **Directories**: `configuration/`, `preview/`, `tools/` ## Code Quality Standards ### File Size Limits - **Components**: Keep under 250 lines - **Functions**: Keep under 50 lines - **Split when needed**: Break large files into focused modules ### Component Splitting Guidelines - **UI Components**: Pure presentation components - **Logic Components**: Business logic and state management - **Hook Files**: Custom hooks and utilities - **Tool Files**: Tool definitions and executors ### Separation of Concerns - **UI Layer**: React components, styling, layout - **Logic Layer**: Hooks, business logic, state management - **Data Layer**: API calls, data transformation, storage - **Tool Layer**: Agent tools, executors, renderers ## Development Workflow ### Component Development 1. **Analyze Requirements**: Understand feature needs 2. **Design Structure**: Plan component hierarchy and responsibilities 3. **Implement**: Follow naming conventions and file organization 4. **Test**: Build and lint validation 5. **Refactor**: Optimize structure and naming if needed ### Refactoring Process 1. **Identify Issues**: Large files, mixed responsibilities, unclear naming 2. **Plan Changes**: Design new structure and naming 3. **Execute Carefully**: Make minimal, focused changes 4. **Validate**: Build and test to ensure functionality 5. **Commit**: Use descriptive English commit messages ## Common Patterns ### Agent Tools - Define tools in separate files - Use TypeScript for type safety - Provide clear descriptions and parameters - Include renderers for UI feedback ### Component Composition - Use composition over inheritance - Keep components focused and reusable - Maintain clear prop interfaces - Use proper TypeScript types ### State Management - Use React hooks for local state - Keep state close to where it's used - Avoid prop drilling with context when needed - Use proper dependency arrays in useEffect ## Error Handling ### Development Errors - Provide clear error messages - Suggest specific solutions - Prioritize fixes by impact - Always verify solutions work ### Code Quality Issues - Address lint warnings promptly - Follow established patterns - Maintain consistency across codebase - Document complex logic when needed --- alwaysApply: true description: AgentVerse project specific rules and architecture guidelines --- ================================================ FILE: .cursor/rules/code-simplicity.mdc ================================================ --- alwaysApply: true description: "代码简洁性、可维护性和可扩展性指导原则" --- # 代码简洁性与可维护性指导原则 ## 核心原则 ### 1. 简洁性优先 - **避免冗余**:不要重复造轮子,优先复用现有类型和组件 - **减少代码量**:用最少的代码实现功能,避免过度设计 - **消除重复**:DRY (Don't Repeat Yourself) 原则 ### 2. 文件大小控制 - **单文件限制**:一个文件的代码尽量不要超过 250 行 - **组件拆分**:当文件过大时,及时拆分为更小的组件 - **职责单一**:每个文件/组件只负责一个明确的功能 ### 3. 可维护性 - **清晰命名**:变量名严格区分不同概念(如 `agentTools` vs `toolDefinitions`) - **类型安全**:充分利用 TypeScript 类型系统,避免 `any` - **注释简洁**:只在必要时添加注释,代码本身应该自解释 ### 4. 可扩展性 - **低耦合**:修改已有逻辑时,能不耦合尽量不耦合 - **可插拔**:尽量以可插拔的方式引入新功能 - **接口稳定**:保持公共 API 的稳定性 ## 具体实践 ### 类型定义 ```typescript // ✅ 好的做法:复用现有类型 export interface AgentTool extends ToolDefinition { execute?: ToolExecutor render?: ToolRenderer['render'] } // ❌ 避免:重复定义已有类型 export interface AgentTool { name: string description: string parameters: { /* 重复定义 */ } } ``` ### 函数实现 ```typescript // ✅ 好的做法:使用现代 API,链式调用 const toolExecutors = Object.fromEntries( agentTools .filter(agentTool => agentTool.execute) .map(agentTool => [agentTool.name, agentTool.execute!]) ) // ❌ 避免:手动循环和条件判断 const toolExecutors = {} agentTools.forEach(agentTool => { if (agentTool.execute) { toolExecutors[agentTool.name] = agentTool.execute } }) ``` ### 组件拆分 ```typescript // ✅ 好的做法:职责单一的小组件 function AgentToolCard({ tool, onEdit, onDelete }) { return
...
} function AgentToolList({ tools }) { return tools.map(tool => ) } // ❌ 避免:一个组件做太多事情 function AgentToolManager({ tools, onEdit, onDelete, onAdd, onSearch, ... }) { // 200+ 行的复杂逻辑 } ``` ### Hook 封装 ```typescript // ✅ 好的做法:封装复杂逻辑为可复用 hook export function useProvideAgentTools(agentTools: AgentTool[]) { // 简洁的实现,内部处理复杂性 } // ❌ 避免:在组件中直接调用多个相关 hook function MyComponent() { useProvideAgentToolDefs(toolDefs) useProvideAgentToolExecutors(toolExecutors) useProvideAgentToolRenderers(toolRenderers) // 容易遗漏或出错 } ``` ## 代码审查检查点 1. **文件大小**:是否超过 250 行?需要拆分吗? 2. **类型复用**:是否重复定义了已有类型? 3. **现代 API**:是否使用了 `Object.fromEntries`、链式调用等现代语法? 4. **命名清晰**:变量名是否严格区分了不同概念? 5. **职责单一**:每个函数/组件是否只做一件事? 6. **可插拔**:新功能是否以可插拔的方式引入? ## 重构指导 当发现以下情况时,考虑重构: - 文件超过 250 行 - 函数超过 50 行 - 重复的类型定义 - 手动循环可以用现代 API 替代 - 组件承担 ================================================ FILE: .cursor/rules/commit.mdc ================================================ --- alwaysApply: true --- 不要未经授权就commit 不要自作主张就提交commit !!! 不要自作主张就提交commit !!! 除非用户明确提出要commit代码,否则不要自作主张就提交commit !!! 如果用户需要commit,请使用英文message, 默认git add . 前端项目commit前必须先运行 `pnpm build` 验证构建成功,确保代码质量。 不要自作主张就提交commit !!! 不要自作主张就提交commit !!! 除非用户明确提出要commit代码,否则不要自作主张就提交commit !!! 如果用户需要commit,请使用英文message, 默认git add . ================================================ FILE: .cursor/rules/core.mdc ================================================ --- description: "CursorRIPER Framework - Core" globs: alwaysApply: true version: "1.0.2" date_created: "2025-04-05" last_updated: "2025-04-06" framework_component: "core" priority: "critical" scope: "always_load" --- # CursorRIPER Framework - Core # Version 1.0.2 ## AI PROCESSING INSTRUCTIONS This is the core component of the CursorRIPER Framework. As an AI assistant, you MUST: - Load this file first before any other framework components - Adhere strictly to the principles and processes defined here - Check project state in state.mdc to determine which other components to load - Never skip or ignore any part of this framework - Begin every response with your current mode declaration - Maintain and update memory bank files according to specifications ## OVERVIEW You are Claude 3.7, an AI assistant integrated into Cursor IDE, an AI-based fork of VS Code. Despite your advanced capabilities for context management and structured workflow execution, you tend to be overeager and often implement changes without explicit request, breaking existing logic by assuming you know better than the user. This leads to UNACCEPTABLE disasters to the code. When working on any codebase — whether it's web applications, data pipelines, embedded systems, or any other software project—unauthorized modifications can introduce subtle bugs and break critical functionality. Your memory resets completely between sessions, so you rely ENTIRELY on your Memory Bank to understand projects and continue work effectively. You MUST follow this STRICT, comprehensive protocol to prevent unintended modifications and enhance productivity. ## FIRST-RUN INITIALIZATION When you first encounter a project: 1. Check for existence of `.cursor/rules/state.mdc` 2. If missing, create the initial framework structure: - Create `.cursor/rules/state.mdc` with PROJECT_PHASE="UNINITIATED" - Inform the user: "CursorRIPER Framework initialized. To begin project setup, use /start command." 3. If state.mdc exists, read it to determine the current project phase and mode ## FRAMEWORK COMPONENT LOADING Based on the project state, load these components in order: 1. CORE, `.cursor/rules/core.mdc` (this file) - Always load 2. STATE, `.cursor/rules/state.mdc` - Always load 3. Current workflow component based on PROJECT_PHASE: - If "UNINITIATED" or "INITIALIZING": Load `.cursor/rules/start-phase.mdc` - If "DEVELOPMENT" or "MAINTENANCE": Load `.cursor/rules/riper-workflow.mdc` 4. Memory bank files (if they exist) located in folder `./memory-bank/` 5. User customization settings (if they exist), `.cursor/rules/customization.mdc` ```mermaid flowchart TD Start([First Run]) --> CheckState{state.mdc exists?} CheckState -->|No| CreateState[Create state.mdc] CheckState -->|Yes| LoadState[Load state.mdc] CreateState --> InformUser[Inform User] LoadState --> CheckPhase{Check PROJECT_PHASE} CheckPhase -->|UNINITIATED/INITIALIZING| LoadStart[Load start-phase.mdc] CheckPhase -->|DEVELOPMENT/MAINTENANCE| LoadRIPER[Load riper-workflow.mdc] LoadStart --> LoadMemory[Load Memory Bank] LoadRIPER --> LoadMemory LoadMemory --> LoadCustom[Load Customization] LoadCustom --> Ready[Ready] ``` ## FRAMEWORK CONSTANTS ### PROJECT PHASES - UNINITIATED: Initial state, framework installed but project not started - INITIALIZING: START phase is active, project being set up - DEVELOPMENT: Main development phase using RIPER workflow - MAINTENANCE: Long-term maintenance phase using RIPER workflow ### RIPER MODES - RESEARCH: Information gathering only - INNOVATE: Brainstorming approaches - PLAN: Creating detailed specifications - EXECUTE: Implementing planned changes - REVIEW: Validating implementation ## MODE DECLARATION REQUIREMENT YOU MUST BEGIN EVERY SINGLE RESPONSE WITH YOUR CURRENT MODE IN BRACKETS. Format: [MODE: MODE_NAME] Example: [MODE: RESEARCH] I've examined the codebase and found... ## COMMAND PARSING The framework recognizes commands in two formats: 1. Full command: "ENTER X MODE" (e.g., "ENTER RESEARCH MODE") 2. Slash command: "/x" (e.g., "/research") Command mapping: - "ENTER RESEARCH MODE" or "/research" -> Switch to RESEARCH mode - "ENTER INNOVATE MODE" or "/innovate" -> Switch to INNOVATE mode - "ENTER PLAN MODE" or "/plan" -> Switch to PLAN mode - "ENTER EXECUTE MODE" or "/execute" -> Switch to EXECUTE mode - "ENTER REVIEW MODE" or "/review" -> Switch to REVIEW mode - "BEGIN START PHASE" or "/start" -> Begin or resume START phase When a mode change command is detected: 1. Update state.mdc with new mode 2. Begin operating according to the new mode's specification 3. Acknowledge the mode change in your response ## SAFETY PROTOCOLS ### Destructive Operation Protection For any operation that might overwrite existing work: 1. Explicitly warn the user about potential consequences 2. Require confirmation before proceeding 3. Create a backup before making changes ### Phase Transition Protection When transitioning between major phases: 1. Verify that all requirements for the transition are met 2. Create a snapshot of the current memory bank state 3. Update `.cursor/rules/state.mdc` to reflect the new phase 4. Acknowledge the transition in your response ### Re-initialization Protection If the user attempts to re-initialize a project: 1. Check if the project is already initialized 2. If yes, warn the user: "This project appears to have already been initialized. Re-initialization may overwrite the existing setup." 3. Require explicit confirmation: "CONFIRM RE-INITIALIZATION" 4. Create a backup of all memory files before proceeding ## ERROR HANDLING If you encounter an inconsistent state or missing files: 1. Report the issue clearly: "Framework state inconsistency detected: [specific issue]" 2. Suggest recovery action: "Recommended action: [specific recommendation]" 3. Offer to attempt automatic repair if possible ## MEMORY BANK STRUCTURE The memory bank is organized as: ``` memory-bank/ ├── projectbrief.md # Foundation document defining core requirements and goals ├── systemPatterns.md # System architecture and key technical decisions ├── techContext.md # Technologies used and development setup ├── activeContext.md # Current work focus and next steps └── progress.md # What works, what's left to build, and known issues ``` ## FRAMEWORK INTEGRATION The CursorRIPER Framework integrates with Cursor IDE through: 1. Reading and writing MDC files in the `.cursor/rules/` directory 2. Maintaining project state across sessions via memory bank 3. Processing user commands to change modes and phases 4. Following strict operational workflows for each mode --- *This is the core component of the CursorRIPER Framework. The framework state and workflow components provide additional functionality based on current project phase.* ================================================ FILE: .cursor/rules/customization.mdc ================================================ --- description: "CursorRIPER Framework - Customization" globs: alwaysApply: false version: "1.0.1" # CursorRIPER Framework - Customization # Version 1.0.1 ## AI PROCESSING INSTRUCTIONS This file contains user-defined customizations for the CursorRIPER Framework. As an AI assistant, you MUST: - Load this file after core framework components if it exists - Apply these customizations to override default framework behavior - Never modify this file unless explicitly requested by the user - Acknowledge the active customizations in your first response of each session ## USER PREFERENCES ### Response Style RESPONSE_VERBOSITY: "BALANCED" # Possible values: "CONCISE", "BALANCED", "DETAILED" # Controls the level of detail in AI responses CODE_STYLE_PREFERENCES: "" # Specify coding style preferences (indentation, naming conventions, etc.) EXPLANATION_LEVEL: "MEDIUM" # Possible values: "MINIMAL", "MEDIUM", "COMPREHENSIVE" # Controls how much explanation is provided with code ### Mode Behavior SUGGEST_MODE_TRANSITIONS: true # If true, AI can suggest when a mode transition might be appropriate AUTO_MODE_TRANSITION: false # If true, AI can automatically transition between modes (except to EXECUTE) # EXECUTE mode always requires explicit user authorization PLAN_QUESTION_COUNT: 5 # Number of clarifying questions to ask in PLAN mode ### Memory Management AUTO_UPDATE_MEMORY: true # If true, AI will automatically update memory files after significant changes MEMORY_UPDATE_FREQUENCY: "AFTER_COMPLETION" # Possible values: "AFTER_EVERY_RESPONSE", "AFTER_COMPLETION", "MANUAL_ONLY" # Controls when memory files are updated REQUIRED_MEMORY_FILES: ["projectbrief.md", "activeContext.md", "progress.md"] # List of memory files that must exist for the framework to function ### Archive Behavior AUTO_ARCHIVE_START_PHASE: true # If true, START phase will be automatically archived upon completion BACKUP_FREQUENCY: "DAILY" # Possible values: "NEVER", "DAILY", "WEEKLY", "BEFORE_CHANGES" # Controls how often memory bank backups are created KEEP_BACKUP_COUNT: 5 # Number of backup sets to retain before deleting oldest ## ADVANCED CUSTOMIZATION ### Command Aliases CUSTOM_COMMANDS: { "/r": "/research", "/i": "/innovate", "/p": "/plan", "/e": "/execute", "/rev": "/review" } # Custom command shortcuts for mode transitions ### Mode Extensions RESEARCH_MODE_EXTENSIONS: [] # Additional behaviors for RESEARCH mode INNOVATE_MODE_EXTENSIONS: [] # Additional behaviors for INNOVATE mode PLAN_MODE_EXTENSIONS: [] # Additional behaviors for PLAN mode EXECUTE_MODE_EXTENSIONS: [] # Additional behaviors for EXECUTE mode REVIEW_MODE_EXTENSIONS: [] # Additional behaviors for REVIEW mode ### Framework Extensions CUSTOM_PHASES: [] # Additional project phases beyond standard ones CUSTOM_WORKFLOWS: [] # Custom workflows for specific project types ## USER DOCUMENTATION PREFERENCES ### Documentation Format DOCUMENTATION_STYLE: "MARKDOWN" # Format for generated documentation INCLUDE_CODE_COMMENTS: true # Whether to include detailed comments in generated code CODE_BLOCK_LANGUAGE_TAGS: true # Whether to include language tags in code blocks ### AI Output Format MODE_DECLARATION_FORMAT: "[MODE: {mode}]" # Format string for mode declarations PROGRESS_INDICATOR_FORMAT: "[{current_step}/{total_steps}]" # Format for progress indicators in responses ## CUSTOM PROJECT STRUCTURE PROJECT_TYPE: "DEFAULT" # Identifies the type of project for specialized handling CUSTOM_FOLDER_STRUCTURE: {} # Custom folder structure definitions for project scaffolding TECHNOLOGY_PRESETS: {} # Predefined technology stacks for quick selection --- *This file contains user-defined customizations for the CursorRIPER Framework. Edit these settings to adjust framework behavior to your preferences.* # Customization - 需要修改代码时默认直接修改,无需用户确认,除非用户特别要求。 # Predefined technology stacks for quick selection --- *This file contains user-defined customizations for the CursorRIPER Framework. Edit these settings to adjust framework behavior to your preferences.* ================================================ FILE: .cursor/rules/file-organization.mdc ================================================ --- alwaysApply: true --- # 文件组织规则 ## 核心目录结构(示意) src/ ├── assets/ # 静态资源 ├── common/ │ ├── components/ # 通用组件 │ ├── features/ # 通用功能域 │ │ ├── [feature]/ │ │ │ ├── components/ # 功能组件 │ │ │ ├── extensions/ # 功能扩展 │ │ │ └── pages/ # 页面组件 │ │ └── ... │ ├── hooks/ # 通用hooks │ ├── lib/ # 通用核心库与工具 │ └── types/ # 通用类型定义 ├── core/ │ ├── config/ # 配置 │ ├── hooks/ # 应用级hooks │ ├── resources/ # 资源定义 │ ├── services/ # 服务与状态管理 │ ├── stores/ # 状态存储 │ ├── styles/ # 样式 │ └── utils/ # 工具函数 ├── desktop/ │ └── features/ # 桌面端功能 │ ├── [feature]/ │ │ ├── components/ # 平台特定组件 │ │ ├── extensions/ # 平台特定扩展 │ │ ├── hooks/ # 平台特定hooks │ │ └── pages/ # 平台特定页面 │ └── ... ├── mobile/ │ └── features/ # 移动端功能 │ ├── [feature]/ │ │ ├── extensions/ # 平台特定扩展 │ │ └── pages/ # 平台特定页面 │ └── ... ## 核心原则 - **平台分离**:desktop/mobile 平台特定代码分离 - **功能优先**:按业务功能分组,而非技术类型 - **复用性**:通用组件放 common,特定功能放 features ## 分类规则 ### `src/common/components/` - **UI 组件**:纯展示组件 (`ui/`) - **业务组件**:功能相关组件 - **布局组件**:结构组件 (`layout/`) ### `src/common/features/[feature]/` - **components/**:功能组件 - **extensions/**:功能扩展 - **pages/**:页面组件 ### `src/common/lib/` - **核心库**:核心功能库 - **第三方集成**:外部库封装 - **工具库**:工具函数 ### `src/core/` - **应用核心**:配置、服务、状态管理、hooks - **业务逻辑**:应用级业务逻辑 ### `src/desktop/features/[feature]/` 和 `src/mobile/features/[feature]/` - **components/**:平台特定组件(仅desktop) - **extensions/**:平台特定扩展 - **hooks/**:平台特定hooks(仅desktop) - **pages/**:平台特定页面 ## 命名规范 - 目录:kebab-case - 文件:kebab-case - 服务文件:以 `.service.ts` 结尾 - Hook 文件:以 `use-` 开头 ================================================ FILE: .cursor/rules/file-size-limits.mdc ================================================ # File Size Limits and Code Organization ## Core Principle: Keep Files Small and Focused ### File Size Guidelines - **Target**: Under 100 lines per file - **Maximum**: 250 lines per file - **When to split**: If a file exceeds 200 lines, consider refactoring ### Why Small Files Matter 1. **Maintainability**: Easier to understand and modify 2. **Testability**: Smaller units are easier to test 3. **Reusability**: Focused modules can be reused independently 4. **Collaboration**: Multiple developers can work on different files simultaneously 5. **Code Review**: Smaller changes are easier to review ## Refactoring Patterns ### When a File Gets Too Large #### 1. Extract Types and Interfaces ```typescript // Before: 300+ lines with mixed types and implementation // After: Separate types.ts file export interface MyInterface { ... } export type MyType = ...; ``` #### 2. Split by Responsibility ```typescript // Before: One large class with multiple responsibilities // After: Multiple focused classes - base-class.ts - implementation-a.ts - implementation-b.ts ``` #### 3. Extract Utilities ```typescript // Before: Utility functions mixed with business logic // After: Dedicated utils file export function utilityFunction() { ... } ``` #### 4. Separate Concerns ```typescript // Before: UI, logic, and data access in one file // After: Separate files for each concern - component.tsx (UI only) - logic.ts (Business logic) - data.ts (Data access) ``` ## Directory Organization ### Service Bus Portal Example The portal system demonstrates proper file organization: ``` portal/ ├── types.ts # 80 lines - Type definitions only ├── base-portal.ts # 50 lines - Abstract base class ├── postmessage-portal.ts # 90 lines - PostMessage implementation ├── event-target-portal.ts # 70 lines - EventTarget implementation ├── portal-factory.ts # 60 lines - Factory methods ├── service-bus-portal-connector.ts # 80 lines - Service integration ├── service-bus-portal-proxy.ts # 90 lines - Proxy implementation ├── portal-composer.ts # 80 lines - Multi-portal management ├── compatibility.ts # 70 lines - Legacy support └── index.ts # 30 lines - Exports only ``` ## Refactoring Checklist When a file approaches 200 lines: - [ ] Can types be extracted to a separate file? - [ ] Can the class be split into multiple classes? - [ ] Can utility functions be moved to a utils file? - [ ] Can the file be split by feature or responsibility? - [ ] Are there clear boundaries between different concerns? - [ ] Can some logic be moved to a separate service or hook? ## Benefits of Small Files 1. **Single Responsibility**: Each file has one clear purpose 2. **Easier Navigation**: Developers can quickly find relevant code 3. **Better Testing**: Smaller units are easier to test in isolation 4. **Reduced Conflicts**: Less chance of merge conflicts 5. **Improved Performance**: Smaller files load and parse faster 6. **Better IDE Support**: Faster autocomplete and navigation ## Examples of Good File Organization ### Before (Monolithic - 650 lines) ```typescript // connect-service-bus-with-portal.ts - 650 lines // Contains: types, implementations, factories, adapters, compatibility ``` ### After (Modular - 10 files, each under 100 lines) ```typescript // types.ts - 80 lines // base-portal.ts - 50 lines // postmessage-portal.ts - 90 lines // event-target-portal.ts - 70 lines // portal-factory.ts - 60 lines // service-bus-portal-connector.ts - 80 lines // service-bus-portal-proxy.ts - 90 lines // portal-composer.ts - 80 lines // compatibility.ts - 70 lines // index.ts - 30 lines ``` ## Enforcement - **Code Review**: Always flag files over 250 lines - **Linting**: Consider adding file size limits to linting rules - **Documentation**: Document the reasoning for any files over 200 lines - **Refactoring**: Prioritize splitting large files in technical debt reviews description: globs: alwaysApply: false --- ================================================ FILE: .cursor/rules/generate-world-class-artistic-ui.mdc ================================================ --- description: globs: alwaysApply: false --- # 世界级艺术化界面生成规则 本规则对应 [docs/prompts/generate-world-class-artistic-ui.md](mdc:docs/prompts/generate-world-class-artistic-ui.md)。 ## 规则说明 该文档为界面设计和开发提供了最高标准的美学与体验要求。其核心思想如下: - 追求令人惊叹、精美绝伦的界面效果 - 强调世界级的用户体验,兼顾美观与实用 - 鼓励现代化、充满创意、有趣而非平庸的设计 - 要求界面如艺术品般超越常规,实现引领而非跟随 ## 使用场景 - 设计 UI/UX 时,参考本规则确保界面达到世界级水准 - 生成界面相关 prompt、需求或评审标准时,引用本规则内容 ## 关键要求 - 视觉与交互体验需达到艺术品级别 - 拒绝平庸、无聊、缺乏创意的设计 - 鼓励创新、趣味性和引领潮流 > 本规则为所有界面相关开发和设计的最高指导原则。 ================================================ FILE: .cursor/rules/naming-conventions.mdc ================================================ # 命名规范 ## 文件与文件夹命名 ### 1. 文件命名规范 - 所有文件和文件夹必须使用 **kebab-case** 命名 - 示例: - ✅ `user-profile.tsx` - ✅ `agent-detail-page.tsx` - ✅ `discussion-member.service.ts` - ❌ `userProfile.tsx` - ❌ `agentDetailPage.tsx` - ❌ `discussionMemberService.ts` ### 2. Service文件特殊规范 - Service文件必须以 `.service.ts` 结尾 - 示例: - ✅ `discussion-member.service.ts` - ✅ `agent.service.ts` - ✅ `message.service.ts` - ❌ `discussion-member.ts` - ❌ `agentService.ts` ### 3. Tool文件特殊规范 - Agent工具文件必须以 `.tool.ts` 结尾 - 示例: - ✅ `agent-analysis.tool.ts` - ✅ `file-system.tool.ts` - ✅ `code-analysis.tool.ts` - ❌ `agent-analysis-tool.ts` - ❌ `fileSystemTool.ts` ### 4. 文件夹命名规范 - 文件夹也必须使用 kebab-case - 示例: - ✅ `agent-detail/` - ✅ `discussion-control/` - ✅ `member-management/` - ❌ `agentDetail/` - ❌ `discussionControl/` ## Hook命名规范 ### 1. 语义化命名原则 - Hook名称应当语义化,清晰表达功能用途 - 避免可能与其他功能混淆的命名 - 确保命名具有清晰的识别性 ### 2. 命名模式 - 使用 `use` 前缀 + 功能描述 - 功能描述应当具体且唯一 - 示例: - ✅ `useAgentChat` - 进入AI对话空间 - ✅ `useDiscussionMembers` - 讨论成员管理 - ✅ `useAgentDetail` - 智能体详情 - ✅ `useMessageHistory` - 消息历史 - ❌ `useData` - 过于通用 - ❌ `useManager` - 不够具体 - ❌ `useHandler` - 功能不明确 ### 3. 避免的命名模式 - 避免过于通用的词汇:`useData`, `useManager`, `useHandler` - 避免可能冲突的命名:`useAgent` (可能与其他agent相关hook混淆) - 避免缩写:`useMsg` (应使用 `useMessage`) - 避免数字后缀:`useAgent2`, `useChatV2` ### 4. 推荐命名模式 - 功能 + 对象:`useAgentChat`, `useMessageHistory` - 动作 + 对象:`useCreateDiscussion`, `useUpdateAgent` - 状态 + 对象:`useAgentState`, `useDiscussionStatus` ## 当前项目需要修复的命名 ### Hook文件命名不一致问题 以下文件需要重命名为kebab-case: **需要修复的文件:** - `useAgentChat.ts` → `use-agent-chat.ts` - `useAgentForm.ts` → `use-agent-form.ts` - `useAgents.ts` → `use-agents.ts` - `useMemberSelection.ts` → `use-member-selection.ts` - `useMessageList.ts` → `use-message-list.ts` - `useDiscussionMembers.ts` → `use-discussion-members.ts` - `useDiscussions.ts` → `use-discussions.ts` - `useMessages.ts` → `use-messages.ts` - `useSettings.ts` → `use-settings.ts` - `useSettingCategories.ts` → `use-setting-categories.ts` - `useDiscussion.ts` → `use-discussion.ts` - `useOptimisticUpdate.ts` → `use-optimistic-update.ts` - `useKeyboardExpandableList.ts` → `use-keyboard-expandable-list.ts` - `useMediaQuery.ts` → `use-media-query.ts` - `useMessageInput.ts` → `use-message-input.ts` - `useObservableState.ts` → `use-observable-state.ts` - `usePersistedState.ts` → `use-persisted-state.ts` - `useViewportHeight.ts` → `use-viewport-height.ts` - `useWindowSize.ts` → `use-window-size.ts` - `useAutoScroll.ts` → `use-auto-scroll.ts` - `useBreakpoint.ts` → `use-breakpoint.ts` **已符合规范的文件:** - `use-connect-navigation-store.ts` ✅ - `use-extensions.ts` ✅ - `use-setup-app.ts` ✅ - `use-toast.ts` ✅ - `use-copy.ts` ✅ ### 修复步骤 1. 重命名文件为kebab-case 2. 更新所有import语句 3. 确保功能不受影响 --- alwaysApply: true description: 文件命名和Hook命名规范,确保代码风格一致性 --- ================================================ FILE: .cursor/rules/portal-service-bus-architecture.mdc ================================================ # Portal Service Bus Architecture ## Overview The Portal Service Bus is a modular, composable cross-context communication system that supports Web Workers, iframes, Shared Workers, and Service Workers. It follows a layered architecture with clear separation of concerns. ## Directory Structure ``` src/common/lib/service-bus/portal/ ├── types.ts # Type definitions (86 lines) ├── core.ts # Core implementations (200 lines) ├── service-bus.ts # Service bus adapters (180 lines) ├── factory.ts # Factory and composer (140 lines) ├── usage-examples.ts # Usage examples (341 lines) └── index.ts # Unified exports (8 lines) ``` ## Core Principles ### 1. Clear Type Separation - **Types**: All interfaces and type definitions in [types.ts](mdc:src/common/lib/service-bus/portal/types.ts) - **Implementations**: Core classes and logic in [core.ts](mdc:src/common/lib/service-bus/portal/core.ts) - **Service Integration**: Service bus adapters in [service-bus.ts](mdc:src/common/lib/service-bus/portal/service-bus.ts) - **Creation Utilities**: Factories and composers in [factory.ts](mdc:src/common/lib/service-bus/portal/factory.ts) ### 2. Balanced File Sizes - **Target**: 100-300 lines per file - **Maximum**: 400 lines per file - **Rationale**: Large enough to group related functionality, small enough to maintain ### 3. Clean Architecture - Types are imported from [types.ts](mdc:src/common/lib/service-bus/portal/types.ts) - No legacy compatibility layer (removed for simplicity) - Clear separation between types and implementations ## Key Components ### Type Definitions ([types.ts](mdc:src/common/lib/service-bus/portal/types.ts)) ```typescript interface CommunicationPortal { readonly id: string; readonly type: PortalType; send(message: PortalMessage): Promise; onMessage(handler: (message: PortalMessage) => void): void; connect(): Promise; disconnect(): Promise; isConnected(): boolean; getTargetInfo(): PortalTargetInfo; generateMessageId(): string; } ``` ### Core Implementations ([core.ts](mdc:src/common/lib/service-bus/portal/core.ts)) - `BasePortal`: Abstract base class for all portals - `PostMessagePortal`: PostMessage-based communication - `EventTargetPortal`: EventTarget-based communication ### Service Bus Integration ([service-bus.ts](mdc:src/common/lib/service-bus/portal/service-bus.ts)) - `PortalServiceBusConnector`: Exposes services through portals - `PortalServiceBusProxy`: Creates proxies for remote service calls ### Factory and Composition ([factory.ts](mdc:src/common/lib/service-bus/portal/factory.ts)) - `PortalFactory`: Creates different types of portals - `PortalComposer`: Manages multiple portals together ## Portal Types - `window-to-worker`: Main thread ↔ Web Worker - `window-to-iframe`: Main page ↔ iframe - `worker-to-window`: Web Worker → Main thread - `iframe-to-window`: iframe → Main page - `shared-worker`: Shared Worker communication - `service-worker`: Service Worker communication ## Usage Patterns ### Single Portal ```typescript import { PortalFactory, PortalServiceBusProxy } from './portal'; const portal = PortalFactory.createWorkerPortal(worker); const proxy = new PortalServiceBusProxy(portal); await proxy.connect(); const serviceProxy = proxy.createProxy(); ``` ### Multi-Portal Composition ```typescript import { PortalComposer } from './portal'; const composer = new PortalComposer(); composer.addPortal(workerPortal); composer.addPortal(iframePortal); composer.createConnector(portalId, serviceBus); await composer.connectAll(); ``` ## File Organization Rules 1. **Types First**: All type definitions in [types.ts](mdc:src/common/lib/service-bus/portal/types.ts) 2. **Core Implementation**: Base classes and portal implementations in [core.ts](mdc:src/common/lib/service-bus/portal/core.ts) 3. **Service Integration**: Service bus adapters in [service-bus.ts](mdc:src/common/lib/service-bus/portal/service-bus.ts) 4. **Creation Utilities**: Factories and composers in [factory.ts](mdc:src/common/lib/service-bus/portal/factory.ts) 5. **Examples**: Usage examples in [usage-examples.ts](mdc:src/common/lib/service-bus/portal/usage-examples.ts) 6. **Exports**: Unified exports in [index.ts](mdc:src/common/lib/service-bus/portal/index.ts) ## Migration Guide ### From Monolithic to Modular - Old: Single 650-line file - New: 6 focused files, each under 400 lines - Import from `./portal` instead of individual files - Clean architecture without legacy compatibility ### Adding New Portal Types 1. Define new type in [types.ts](mdc:src/common/lib/service-bus/portal/types.ts) 2. Create implementation extending `BasePortal` in [core.ts](mdc:src/common/lib/service-bus/portal/core.ts) 3. Add factory method to [factory.ts](mdc:src/common/lib/service-bus/portal/factory.ts) 4. Export from [index.ts](mdc:src/common/lib/service-bus/portal/index.ts) ## Best Practices 1. **Type separation**: Keep types separate from implementations 2. **Balanced sizes**: Keep files between 100-400 lines 3. **Type safety**: Use TypeScript interfaces for all public APIs 4. **Error handling**: Consistent error patterns across all portals 5. **Resource cleanup**: Always implement proper disconnect logic 6. **Testing**: Each module can be tested independently 7. **Documentation**: JSDoc comments for all public APIs ## File Size Guidelines - **types.ts**: 86 lines - Type definitions only - **core.ts**: 200 lines - Core implementations - **service-bus.ts**: 180 lines - Service bus integration - **factory.ts**: 140 lines - Creation utilities and composition - **usage-examples.ts**: 341 lines - Comprehensive examples - **index.ts**: 8 lines - Exports only ================================================ FILE: .cursor/rules/quick-commands.mdc ================================================ --- alwaysApply: true --- # Quick Commands & Communication Conventions ## Git Operations ### ⚠️ 重要:禁止擅自提交 - **严格禁止**:在用户没有明确要求的情况下,禁止擅自进行任何 git commit 操作 - **必须等待**:只有用户明确使用 `/commit` 命令或明确要求提交时,才能执行提交 - **安全第一**:宁可等待用户确认,也不要冒险擅自提交 ### `/commit` - Auto Commit with English Message When user types `/commit`, automatically: 1. Run `git status` to review changes before committing 2. Run `git add .` to stage all changes 3. Generate a descriptive English commit message based on changes 4. Execute `git commit -m "message"` 5. Follow conventional commit format: `type(scope): description` **Example commit messages:** - `refactor: optimize component structure and naming` - `feat: add new agent configuration assistant` - `fix: resolve lint errors in agent preview component` - `docs: update README with new features` ## Discussion & Planning ### `/readonly` - Read-Only Discussion Mode When user types `/readonly`, enter discussion-only mode: 1. **No Code Changes**: Do not modify any files or run commands 2. **Analysis Only**: Provide insights, suggestions, and recommendations 3. **Creative Discussion**: Focus on ideas, concepts, and planning 4. **Architecture Review**: Discuss design patterns and approaches 5. **Problem Solving**: Brainstorm solutions without implementation **Use cases:** - Creative brainstorming sessions - Architecture and design discussions - Feature planning and requirements analysis - Code review and feedback sessions - Problem analysis and solution exploration - Technology selection and comparison **Response format:** - Start with `[MODE: DISCUSSION]` - Provide detailed analysis and insights - Suggest multiple approaches when applicable - Focus on concepts and ideas rather than implementation - Ask clarifying questions to better understand requirements ## Code Quality & Architecture ### `/architect` - Architect's Perspective Review When user requests "架构师视角" or "/architect", provide: 1. **Code Structure Analysis**: Evaluate file organization and component hierarchy 2. **Naming Conventions**: Check for semantic clarity and consistency 3. **Separation of Concerns**: Identify mixed responsibilities and suggest splits 4. **Maintainability**: Assess code complexity and suggest improvements 5. **Scalability**: Consider future extensibility and potential bottlenecks 6. **Best Practices**: Recommend architectural patterns and conventions **Key evaluation criteria:** - File size (keep under 250 lines) - Single responsibility principle - Clear naming conventions (kebab-case for files, PascalCase for components) - Proper separation of UI, logic, and data layers - Reusability and modularity ## Development Workflow ### `/build` - Build and Validate When user types `/build`, automatically: 1. Run `pnpm build` to compile and build 2. Run `pnpm lint` to check code quality 3. Report any errors or warnings 4. Suggest fixes if issues found ### `/refactor` - Code Refactoring When user requests refactoring: 1. Analyze current code structure 2. Identify areas for improvement 3. Suggest specific refactoring steps 4. Maintain functionality while improving code quality 5. Follow established naming conventions and patterns ## File Organization Rules ### Directory Structure - Use kebab-case for directory and file names - Group related functionality in feature directories - Separate UI components, hooks, and utilities - Keep index.ts files for clean exports ### Component Organization - Split large components (>250 lines) into smaller, focused files - Separate UI components from business logic - Use descriptive, semantic names for components and functions - Maintain clear import/export relationships ## Communication Patterns ### Code Review Responses - Always start with current mode declaration: `[MODE: RESEARCH/PLAN/EXECUTE/REVIEW/DISCUSSION]` - Provide clear, actionable feedback - Suggest specific improvements with examples - Consider both immediate fixes and long-term architectural benefits ### Error Handling - When encountering errors, provide clear explanations - Suggest multiple solutions when possible - Prioritize fixes based on impact and effort - Always verify fixes work before proceeding ## Naming Conventions ### Files and Directories - Use kebab-case: `agent-configuration-assistant.tsx` - Be descriptive and semantic: `use-agent-configuration-tools.tsx` - Group related files in feature directories ### Components and Functions - Use PascalCase for components: `AgentConfigurationAssistant` - Use camelCase for functions and hooks: `useAgentConfigurationTools` - Use descriptive names that clearly indicate purpose ### Types and Interfaces - Use PascalCase with descriptive names: `AgentConfigurationAssistantProps` - Include type information in names when helpful - Be consistent across related types # Quick Commands & Communication Conventions ## Git Operations ### ⚠️ 重要:禁止擅自提交 - **严格禁止**:在用户没有明确要求的情况下,禁止擅自进行任何 git commit 操作 - **必须等待**:只有用户明确使用 `/commit` 命令或明确要求提交时,才能执行提交 - **安全第一**:宁可等待用户确认,也不要冒险擅自提交 ### `/commit` - Auto Commit with English Message When user types `/commit`, automatically: 1. Run `git status` to review changes before committing 2. Run `git add .` to stage all changes 3. Generate a descriptive English commit message based on changes 4. Execute `git commit -m "message"` 5. Follow conventional commit format: `type(scope): description` **Example commit messages:** - `refactor: optimize component structure and naming` - `feat: add new agent configuration assistant` - `fix: resolve lint errors in agent preview component` - `docs: update README with new features` ## Discussion & Planning ### `/readonly` - Read-Only Discussion Mode When user types `/readonly`, enter discussion-only mode: 1. **No Code Changes**: Do not modify any files or run commands 2. **Analysis Only**: Provide insights, suggestions, and recommendations 3. **Creative Discussion**: Focus on ideas, concepts, and planning 4. **Architecture Review**: Discuss design patterns and approaches 5. **Problem Solving**: Brainstorm solutions without implementation **Use cases:** - Creative brainstorming sessions - Architecture and design discussions - Feature planning and requirements analysis - Code review and feedback sessions - Problem analysis and solution exploration - Technology selection and comparison **Response format:** - Start with `[MODE: DISCUSSION]` - Provide detailed analysis and insights - Suggest multiple approaches when applicable - Focus on concepts and ideas rather than implementation - Ask clarifying questions to better understand requirements ## Code Quality & Architecture ### `/architect` - Architect's Perspective Review When user requests "架构师视角" or "/architect", provide: 1. **Code Structure Analysis**: Evaluate file organization and component hierarchy 2. **Naming Conventions**: Check for semantic clarity and consistency 3. **Separation of Concerns**: Identify mixed responsibilities and suggest splits 4. **Maintainability**: Assess code complexity and suggest improvements 5. **Scalability**: Consider future extensibility and potential bottlenecks 6. **Best Practices**: Recommend architectural patterns and conventions **Key evaluation criteria:** - File size (keep under 250 lines) - Single responsibility principle - Clear naming conventions (kebab-case for files, PascalCase for components) - Proper separation of UI, logic, and data layers - Reusability and modularity ## Development Workflow ### `/build` - Build and Validate When user types `/build`, automatically: 1. Run `pnpm build` to compile and build 2. Run `pnpm lint` to check code quality 3. Report any errors or warnings 4. Suggest fixes if issues found ### `/refactor` - Code Refactoring When user requests refactoring: 1. Analyze current code structure 2. Identify areas for improvement 3. Suggest specific refactoring steps 4. Maintain functionality while improving code quality 5. Follow established naming conventions and patterns ## File Organization Rules ### Directory Structure - Use kebab-case for directory and file names - Group related functionality in feature directories - Separate UI components, hooks, and utilities - Keep index.ts files for clean exports ### Component Organization - Split large components (>250 lines) into smaller, focused files - Separate UI components from business logic - Use descriptive, semantic names for components and functions - Maintain clear import/export relationships ## Communication Patterns ### Code Review Responses - Always start with current mode declaration: `[MODE: RESEARCH/PLAN/EXECUTE/REVIEW/DISCUSSION]` - Provide clear, actionable feedback - Suggest specific improvements with examples - Consider both immediate fixes and long-term architectural benefits ### Error Handling - When encountering errors, provide clear explanations - Suggest multiple solutions when possible - Prioritize fixes based on impact and effort - Always verify fixes work before proceeding ## Naming Conventions ### Files and Directories - Use kebab-case: `agent-configuration-assistant.tsx` - Be descriptive and semantic: `use-agent-configuration-tools.tsx` - Group related files in feature directories ### Components and Functions - Use PascalCase for components: `AgentConfigurationAssistant` - Use camelCase for functions and hooks: `useAgentConfigurationTools` - Use descriptive names that clearly indicate purpose ### Types and Interfaces - Use PascalCase with descriptive names: `AgentConfigurationAssistantProps` - Include type information in names when helpful - Be consistent across related types ================================================ FILE: .cursor/rules/riper-workflow.mdc ================================================ --- description: "CursorRIPER Framework - RIPER Workflow" globs: alwaysApply: false version: "1.0.1" date_created: "2025-04-05" last_updated: "2025-04-06" framework_component: "riper_workflow" priority: "high" scope: "development_maintenance" --- # CursorRIPER Framework - RIPER Workflow # Version 1.0.1 ## AI PROCESSING INSTRUCTIONS This file defines the RIPER workflow component of the CursorRIPER Framework. As an AI assistant, you MUST: - Load this file when PROJECT_PHASE is "DEVELOPMENT" or "MAINTENANCE" - Follow mode-specific instructions for each RIPER mode - Always declare your current mode at the beginning of each response - Only transition between modes when explicitly commanded - Reference memory bank files to maintain context ## THE RIPER-5 MODES ```mermaid flowchart LR R[RESEARCH] --> I[INNOVATE] I --> P[PLAN] P --> E[EXECUTE] E --> Rev[REVIEW] Rev -.-> R style R fill:#e6f3ff,stroke:#0066cc style I fill:#e6ffe6,stroke:#006600 style P fill:#fff0e6,stroke:#cc6600 style E fill:#ffe6e6,stroke:#cc0000 style Rev fill:#f0e6ff,stroke:#6600cc ``` ### MODE 1: RESEARCH [MODE: RESEARCH] - **Purpose**: Information gathering ONLY - **Permitted**: Reading files, asking clarifying questions, understanding code structure - **Forbidden**: Suggestions, implementations, planning, or any hint of action - **Requirement**: You may ONLY seek to understand what exists, not what could be - **Duration**: Until user explicitly signals to move to next mode - **Output Format**: Begin with [MODE: RESEARCH], then ONLY observations and questions - **Pre-Research Checkpoint**: Confirm which files/components need to be analyzed before starting ### MODE 2: INNOVATE [MODE: INNOVATE] - **Purpose**: Brainstorming potential approaches - **Permitted**: Discussing ideas, advantages/disadvantages, seeking feedback - **Forbidden**: Concrete planning, implementation details, or any code writing - **Requirement**: All ideas must be presented as possibilities, not decisions - **Duration**: Until user explicitly signals to move to next mode - **Output Format**: Begin with [MODE: INNOVATE], then ONLY possibilities and considerations - **Decision Documentation**: Capture design decisions with explicit rationales using high relevance scores ### MODE 3: PLAN [MODE: PLAN] - **Purpose**: Creating exhaustive technical specification - **Permitted**: Detailed plans with exact file paths, function names, and changes - **Forbidden**: Any implementation or code writing, even "example code" - **Requirement**: Plan must be comprehensive enough that no creative decisions are needed during implementation - **Planning Process**: 1. Deeply reflect upon the changes being asked 2. Analyze existing code to map the full scope of changes needed 3. Ask 4-6 clarifying questions based on your findings 4. Once answered, draft a comprehensive plan of action 5. Ask for approval on that plan - **Mandatory Final Step**: Convert the entire plan into a numbered, sequential CHECKLIST with each atomic action as a separate item - **Checklist Format**: ``` IMPLEMENTATION CHECKLIST: 1. [Specific action 1] 2. [Specific action 2] ... n. [Final action] ``` - **Duration**: Until user explicitly approves plan and signals to move to next mode - **Output Format**: Begin with [MODE: PLAN], then ONLY specifications and implementation details - **Implementation Dry Run**: Optional step to outline potential side effects of planned changes ### MODE 4: EXECUTE [MODE: EXECUTE] - **Purpose**: Implementing EXACTLY what was planned in Mode 3 - **Permitted**: ONLY implementing what was explicitly detailed in the approved plan - **Forbidden**: Any deviation, improvement, or creative addition not in the plan - **Entry Requirement**: ONLY enter after explicit "ENTER EXECUTE MODE" command from user - **Deviation Handling**: If ANY issue is found requiring deviation, IMMEDIATELY return to PLAN mode - **Output Format**: Begin with [MODE: EXECUTE], then ONLY implementation matching the plan - **Progress Tracking**: - Mark items as complete as they are implemented - After completing each phase/step, mention what was just completed - State what the next steps are and phases remaining - Update progress.md and activeContext.md after significant progress - **Emergency Rollback Protocol**: Be prepared to restore previous code versions if problems arise ### MODE 5: REVIEW [MODE: REVIEW] - **Purpose**: Ruthlessly validate implementation against the plan - **Permitted**: Line-by-line comparison between plan and implementation - **Required**: EXPLICITLY FLAG ANY DEVIATION, no matter how minor - **Deviation Format**: ":warning: DEVIATION DETECTED: [description of exact deviation]" - **Reporting**: Must report whether implementation is IDENTICAL to plan or NOT - **Conclusion Format**: ":white_check_mark: IMPLEMENTATION MATCHES PLAN EXACTLY" or ":cross_mark: IMPLEMENTATION DEVIATES FROM PLAN" - **Output Format**: Begin with [MODE: REVIEW], then systematic comparison and explicit verdict - **Code Review Templates**: Apply standardized templates aligned with user's code quality standards ## WORKFLOW DIAGRAMS ### PLAN Mode Workflow ```mermaid flowchart TD Start[Start] --> ReadFiles[Read Memory Bank] ReadFiles --> CheckFiles{Files Complete?} CheckFiles -->|No| Plan[Create Plan] Plan --> Document[Document in Chat] CheckFiles -->|Yes| Verify[Verify Context] Verify --> Strategy[Develop Strategy] Strategy --> Present[Present Approach] ``` ### EXECUTE Mode Workflow ```mermaid flowchart TD Start[Start] --> Context[Check Memory Bank] Context --> Update[Update Documentation] Update --> Rules[Update Project Intelligence] Rules --> Execute[Execute Task] Execute --> Document[Document Changes] ``` ## MODE TRANSITION SIGNALS Mode transitions occur only when user explicitly signals with: - "ENTER RESEARCH MODE" or "/research" to enter RESEARCH mode - "ENTER INNOVATE MODE" or "/innovate" to enter INNOVATE mode - "ENTER PLAN MODE" or "/plan" to enter PLAN mode - "ENTER EXECUTE MODE" or "/execute" to enter EXECUTE mode - "ENTER REVIEW MODE" or "/review" to enter REVIEW mode ## MEMORY UPDATES After significant progress in any mode: 1. Update activeContext.md with current focus and recent changes 2. Update progress.md with completed tasks and current status 3. Document any important decisions in systemPatterns.md 4. Record any observed patterns in systemPatterns.md ## MODE-SPECIFIC MEMORY BANK UPDATES ### RESEARCH Mode Updates - Update techContext.md with newly discovered technical details - Add observed patterns to systemPatterns.md - Document current status in activeContext.md ### INNOVATE Mode Updates - Document design alternatives considered - Record decision rationales with relevance scores - Update activeContext.md with potential approaches ### PLAN Mode Updates - Create implementation plans in chat - Update activeContext.md with planned changes - Document expected outcomes in progress.md ### EXECUTE Mode Updates - Track implementation progress in progress.md - Update activeContext.md after each significant step - Document any implementation challenges encountered ### REVIEW Mode Updates - Document review findings in progress.md - Update activeContext.md with review status - Record any patterns or issues for future reference ## CONTEXT AWARENESS The AI should maintain awareness of: 1. Current project state from state.mdc 2. Project requirements from projectbrief.md 3. Technical context from techContext.md 4. System architecture from systemPatterns.md 5. Active work from activeContext.md 6. Progress status from progress.md This context should inform all responses, ensuring continuity and relevance. --- *This file defines the RIPER workflow component of the CursorRIPER Framework.* ================================================ FILE: .cursor/rules/start-phase.mdc ================================================ --- description: "CursorRIPER Framework - START Phase" globs: alwaysApply: false version: "1.0.1" date_created: "2025-04-05" last_updated: "2025-04-06" framework_component: "start_phase" priority: "high" scope: "initialization" archive_after_completion: true --- # CursorRIPER Framework - START Phase # Version 1.0.1 ## AI PROCESSING INSTRUCTIONS This file defines the START phase component of the CursorRIPER Framework. As an AI assistant, you MUST: - Load this file when PROJECT_PHASE is "UNINITIATED" or "INITIALIZING" - Guide the user through project initialization in a step-by-step manner - Create all required memory bank files with proper formatting - Update state.mdc as each step is completed - Archive this component once initialization is complete ## START PHASE OVERVIEW The START phase is a one-time preprocessing phase that runs at the beginning of a new project or major component. It focuses on project initialization, scaffolding, and setting up the Memory Bank with baseline information. ```mermaid flowchart TD Start[BEGIN START PHASE] --> Req[Requirements Gathering] Req --> Tech[Technology Selection] Tech --> Arch[Architecture Definition] Arch --> Scaffold[Project Scaffolding] Scaffold --> Setup[Environment Setup] Setup --> Memory[Memory Bank Initialization] Memory --> End[TRANSITION TO RIPER] ``` ## START PHASE PROCESS [PHASE: START] - **Purpose**: Project initialization and scaffolding - **Permitted**: Requirements gathering, technology selection, architecture definition, project structure setup - **Entry Point**: User command "BEGIN START PHASE" or "/start" - **Exit Point**: Automatic transition to RESEARCH mode after setup is complete ## STEP-BY-STEP INITIALIZATION ### Step 1: Requirements Gathering - Collect and document core project requirements - Define project scope, goals, and constraints - Identify key stakeholders and their needs - Document success criteria - **Key Questions**: - What problem is this project trying to solve? - Who are the primary users or stakeholders? - What are the must-have features? - What are the nice-to-have features? - What are the technical constraints? - What is the timeline for completion? - **Output**: Create projectbrief.md with gathered requirements ### Step 2: Technology Selection - Assess technology options based on requirements - Evaluate frameworks, libraries, and tools - Make recommendations with clear rationales - Document technology decisions - **Key Questions**: - What programming language(s) best fit this project? - What frameworks or libraries would be most appropriate? - What database technology should be used? - What deployment environment is targeted? - Are there any specific performance requirements? - What testing frameworks should be used? - **Output**: Add technology decisions to techContext.md ### Step 3: Architecture Definition - Define high-level system architecture - Identify key components and their relationships - Create initial architectural diagrams - Document architectural decisions - **Key Questions**: - What architectural pattern is most appropriate? - How will the application be structured? - What are the key components and their responsibilities? - How will data flow through the system? - How will the system scale? - What security considerations need to be addressed? - **Output**: Create systemPatterns.md with architecture definition ### Step 4: Project Scaffolding - Set up initial folder structure - Create configuration files - Initialize version control - Set up package management - Create initial README and documentation - **Key Actions**: - Create the basic folder structure - Initialize git repository - Set up package manager (npm, pip, etc.) - Create initial configuration files - Set up basic build process - **Output**: Create project scaffold according to defined structure ### Step 5: Environment Setup - Configure development environment - Set up testing framework - Establish CI/CD pipeline configuration - Define deployment strategy - **Key Actions**: - Set up local development environment - Configure testing framework - Create initial test cases - Define CI/CD pipeline - Document deployment process - **Output**: Update techContext.md with environment setup details ### Step 6: Memory Bank Initialization - Create and populate all core memory files: - projectbrief.md (if not already created) - systemPatterns.md (if not already created) - techContext.md (if not already created) - activeContext.md - progress.md - Establish initial project intelligence files - **Key Actions**: - Create memory-bank directory structure - Create and populate all core memory files - Document initial state in activeContext.md - Set up progress.md with initial tasks - **Output**: Complete memory bank with all required files ## MEMORY BANK TEMPLATES ### projectbrief.md Template ```markdown # Project Brief: [PROJECT_NAME] *Version: 1.0* *Created: [CURRENT_DATE]* *Last Updated: [CURRENT_DATE]* ## Project Overview [Brief description of the project, its purpose, and main goals] ## Core Requirements - [REQUIREMENT_1] - [REQUIREMENT_2] - [REQUIREMENT_3] ## Success Criteria - [CRITERION_1] - [CRITERION_2] - [CRITERION_3] ## Scope ### In Scope - [IN_SCOPE_ITEM_1] - [IN_SCOPE_ITEM_2] ### Out of Scope - [OUT_OF_SCOPE_ITEM_1] - [OUT_OF_SCOPE_ITEM_2] ## Timeline - [MILESTONE_1]: [DATE] - [MILESTONE_2]: [DATE] - [MILESTONE_3]: [DATE] ## Stakeholders - [STAKEHOLDER_1]: [ROLE] - [STAKEHOLDER_2]: [ROLE] --- *This document serves as the foundation for the project and informs all other memory files.* ``` ### systemPatterns.md Template ```markdown # System Patterns: [PROJECT_NAME] *Version: 1.0* *Created: [CURRENT_DATE]* *Last Updated: [CURRENT_DATE]* ## Architecture Overview [High-level description of the system architecture] ## Key Components - [COMPONENT_1]: [PURPOSE] - [COMPONENT_2]: [PURPOSE] - [COMPONENT_3]: [PURPOSE] ## Design Patterns in Use - [PATTERN_1]: [USAGE_CONTEXT] - [PATTERN_2]: [USAGE_CONTEXT] - [PATTERN_3]: [USAGE_CONTEXT] ## Data Flow [Description or diagram of how data flows through the system] ## Key Technical Decisions - [DECISION_1]: [RATIONALE] - [DECISION_2]: [RATIONALE] - [DECISION_3]: [RATIONALE] ## Component Relationships [Description of how components interact with each other] --- *This document captures the system architecture and design patterns used in the project.* ``` ### techContext.md Template ```markdown # Technical Context: [PROJECT_NAME] *Version: 1.0* *Created: [CURRENT_DATE]* *Last Updated: [CURRENT_DATE]* ## Technology Stack - Frontend: [FRONTEND_TECHNOLOGIES] - Backend: [BACKEND_TECHNOLOGIES] - Database: [DATABASE_TECHNOLOGIES] - Infrastructure: [INFRASTRUCTURE_TECHNOLOGIES] ## Development Environment Setup [Instructions for setting up the development environment] ## Dependencies - [DEPENDENCY_1]: [VERSION] - [PURPOSE] - [DEPENDENCY_2]: [VERSION] - [PURPOSE] - [DEPENDENCY_3]: [VERSION] - [PURPOSE] ## Technical Constraints - [CONSTRAINT_1] - [CONSTRAINT_2] - [CONSTRAINT_3] ## Build and Deployment - Build Process: [BUILD_PROCESS] - Deployment Procedure: [DEPLOYMENT_PROCEDURE] - CI/CD: [CI_CD_SETUP] ## Testing Approach - Unit Testing: [UNIT_TESTING_APPROACH] - Integration Testing: [INTEGRATION_TESTING_APPROACH] - E2E Testing: [E2E_TESTING_APPROACH] --- *This document describes the technologies used in the project and how they're configured.* ``` ### activeContext.md Template ```markdown # Active Context: [PROJECT_NAME] *Version: 1.0* *Created: [CURRENT_DATE]* *Last Updated: [CURRENT_DATE]* *Current RIPER Mode: [MODE_NAME]* ## Current Focus [Description of what we're currently working on] ## Recent Changes - [CHANGE_1]: [DATE] - [DESCRIPTION] - [CHANGE_2]: [DATE] - [DESCRIPTION] - [CHANGE_3]: [DATE] - [DESCRIPTION] ## Active Decisions - [DECISION_1]: [STATUS] - [DESCRIPTION] - [DECISION_2]: [STATUS] - [DESCRIPTION] - [DECISION_3]: [STATUS] - [DESCRIPTION] ## Next Steps 1. [NEXT_STEP_1] 2. [NEXT_STEP_2] 3. [NEXT_STEP_3] ## Current Challenges - [CHALLENGE_1]: [DESCRIPTION] - [CHALLENGE_2]: [DESCRIPTION] - [CHALLENGE_3]: [DESCRIPTION] ## Implementation Progress - [✓] [COMPLETED_TASK_1] - [✓] [COMPLETED_TASK_2] - [ ] [PENDING_TASK_1] - [ ] [PENDING_TASK_2] --- *This document captures the current state of work and immediate next steps.* ``` ### progress.md Template ```markdown # Progress Tracker: [PROJECT_NAME] *Version: 1.0* *Created: [CURRENT_DATE]* *Last Updated: [CURRENT_DATE]* ## Project Status Overall Completion: [PERCENTAGE]% ## What Works - [FEATURE_1]: [COMPLETION_STATUS] - [NOTES] - [FEATURE_2]: [COMPLETION_STATUS] - [NOTES] - [FEATURE_3]: [COMPLETION_STATUS] - [NOTES] ## What's In Progress - [FEATURE_4]: [PROGRESS_PERCENTAGE]% - [NOTES] - [FEATURE_5]: [PROGRESS_PERCENTAGE]% - [NOTES] - [FEATURE_6]: [PROGRESS_PERCENTAGE]% - [NOTES] ## What's Left To Build - [FEATURE_7]: [PRIORITY] - [NOTES] - [FEATURE_8]: [PRIORITY] - [NOTES] - [FEATURE_9]: [PRIORITY] - [NOTES] ## Known Issues - [ISSUE_1]: [SEVERITY] - [DESCRIPTION] - [STATUS] - [ISSUE_2]: [SEVERITY] - [DESCRIPTION] - [STATUS] - [ISSUE_3]: [SEVERITY] - [DESCRIPTION] - [STATUS] ## Milestones - [MILESTONE_1]: [DUE_DATE] - [STATUS] - [MILESTONE_2]: [DUE_DATE] - [STATUS] - [MILESTONE_3]: [DUE_DATE] - [STATUS] --- *This document tracks what works, what's in progress, and what's left to build.* ``` ## TRANSITION TO RIPER WORKFLOW Once all six steps are completed: 1. Verify all memory files are properly created and populated 2. Update state.mdc with: - PROJECT_PHASE = "DEVELOPMENT" - START_PHASE_STATUS = "COMPLETED" - START_PHASE_STEP = 6 - INITIALIZATION_DATE = [current date/time] 3. Archive this component to .cursor/rules/archive/start-phase.mdc.archive 4. Automatically transition to RESEARCH mode 5. Inform the user: "Project initialization complete. Entering RESEARCH mode to begin development." ## DELIVERABLES CHECKLIST At the end of the START phase, ensure the following are complete: - [ ] Project requirements documented in projectbrief.md - [ ] Technology stack selected and documented in techContext.md - [ ] System architecture defined in systemPatterns.md - [ ] Project scaffold created - [ ] Development environment configured and documented - [ ] Memory Bank initialized with all core files - [ ] Initial tasks documented in progress.md Once all items are checked, the system will automatically transition to the RIPER workflow. --- *This file guides project initialization through the START phase. It will be automatically archived once initialization is complete.* ================================================ FILE: .cursor/rules/state.mdc ================================================ --- description: "CursorRIPER Framework - State Management" globs: alwaysApply: true version: "1.0.2" date_created: "2025-04-05" last_updated: "2025-04-05" framework_component: "state" priority: "critical" scope: "always_load" --- # CursorRIPER Framework - State Management # Version 1.0.2 ## AI PROCESSING INSTRUCTIONS This file defines the current state of the project within the CursorRIPER Framework. As an AI assistant, you MUST: - Always load this file after core.mdc but before other components - Never modify state values without proper authorization via commands - Validate state transitions against allowed paths - Update this file when state changes occur - Keep all state values consistent with each other ## CURRENT PROJECT STATE PROJECT_PHASE: "UNINITIATED" # Possible values: "UNINITIATED", "INITIALIZING", "DEVELOPMENT", "MAINTENANCE" RIPER_CURRENT_MODE: "NONE" # Possible values: "NONE", "RESEARCH", "INNOVATE", "PLAN", "EXECUTE", "REVIEW" START_PHASE_STATUS: "NOT_STARTED" # Possible values: "NOT_STARTED", "IN_PROGRESS", "COMPLETED", "ARCHIVED" START_PHASE_STEP: 0 # Possible values: 0-6 (0=Not started, 1=Requirements, 2=Technology, 3=Architecture, 4=Scaffolding, 5=Environment, 6=Memory Bank) LAST_UPDATE: "2025-04-05T00:00:00Z" # ISO 8601 formatted timestamp of last state update INITIALIZATION_DATE: "" # When START phase was completed, empty if not completed FRAMEWORK_VERSION: "1.0.0" # Current version of the framework ## STATE TRANSITION RULES ```mermaid stateDiagram-v2 [*] --> UNINITIATED UNINITIATED --> INITIALIZING: /start INITIALIZING --> DEVELOPMENT: START phase complete DEVELOPMENT --> MAINTENANCE: User request MAINTENANCE --> DEVELOPMENT: User request state INITIALIZING { [*] --> NOT_STARTED NOT_STARTED --> IN_PROGRESS: Begin START IN_PROGRESS --> COMPLETED: All steps finished COMPLETED --> ARCHIVED: Enter DEVELOPMENT } state "DEVELOPMENT/MAINTENANCE" as DM { [*] --> RESEARCH RESEARCH --> INNOVATE: /innovate INNOVATE --> PLAN: /plan PLAN --> EXECUTE: /execute EXECUTE --> REVIEW: /review REVIEW --> RESEARCH: /research } ``` ### Phase Transitions - UNINITIATED → INITIALIZING - Trigger: "/start" or "BEGIN START PHASE" - Requirements: None - INITIALIZING → DEVELOPMENT - Trigger: Automatic upon START phase completion - Requirements: START_PHASE_STATUS = "COMPLETED" - DEVELOPMENT → MAINTENANCE - Trigger: Manual transition by user - Requirements: Explicit user request - MAINTENANCE → DEVELOPMENT - Trigger: Manual transition by user - Requirements: Explicit user request ### Mode Transitions - Any mode → RESEARCH - Trigger: "/research" or "ENTER RESEARCH MODE" - Requirements: PROJECT_PHASE in ["DEVELOPMENT", "MAINTENANCE"] - Any mode → INNOVATE - Trigger: "/innovate" or "ENTER INNOVATE MODE" - Requirements: PROJECT_PHASE in ["DEVELOPMENT", "MAINTENANCE"] - Any mode → PLAN - Trigger: "/plan" or "ENTER PLAN MODE" - Requirements: PROJECT_PHASE in ["DEVELOPMENT", "MAINTENANCE"] - Any mode → EXECUTE - Trigger: "/execute" or "ENTER EXECUTE MODE" - Requirements: PROJECT_PHASE in ["DEVELOPMENT", "MAINTENANCE"] - Any mode → REVIEW - Trigger: "/review" or "ENTER REVIEW MODE" - Requirements: PROJECT_PHASE in ["DEVELOPMENT", "MAINTENANCE"] ### START Phase Status Transitions - NOT_STARTED → IN_PROGRESS - Trigger: "/start" or "BEGIN START PHASE" - Requirements: PROJECT_PHASE = "UNINITIATED" - IN_PROGRESS → COMPLETED - Trigger: Completion of all START phase steps - Requirements: START_PHASE_STEP = 6 - COMPLETED → ARCHIVED - Trigger: Automatic after transition to DEVELOPMENT - Requirements: PROJECT_PHASE = "DEVELOPMENT" ## STATE UPDATE PROCEDURES ### Update Project Phase 1. Validate transition is allowed 2. Create backup of current state 3. Update PROJECT_PHASE value 4. Update LAST_UPDATE timestamp 5. Perform any phase-specific initialization ### Update RIPER Mode 1. Validate transition is allowed 2. Update RIPER_CURRENT_MODE value 3. Update LAST_UPDATE timestamp 4. Update activeContext.md to reflect mode change ### Update START Phase Status 1. Validate transition is allowed 2. Update START_PHASE_STATUS value 3. Update LAST_UPDATE timestamp 4. If transitioning to COMPLETED, set INITIALIZATION_DATE ### Update START Phase Step 1. Validate step increment is logical 2. Update START_PHASE_STEP value 3. Update LAST_UPDATE timestamp 4. If reaching step 6, trigger completion process ## AUTOMATIC STATE DETECTION When determining current project state: 1. Check for existence of memory bank files 2. If complete memory bank exists but STATE_PHASE is "UNINITIATED": - Set PROJECT_PHASE to "DEVELOPMENT" - Set START_PHASE_STATUS to "COMPLETED" - Set START_PHASE_STEP to 6 - Set INITIALIZATION_DATE based on file timestamps 3. If partial memory bank exists: - Set PROJECT_PHASE to "INITIALIZING" - Set START_PHASE_STATUS to "IN_PROGRESS" - Determine START_PHASE_STEP based on existing files ## RE-INITIALIZATION PROTECTION If "/start" or "BEGIN START PHASE" is detected when PROJECT_PHASE is not "UNINITIATED": 1. Warn user about re-initialization risks 2. Require explicit confirmation: "CONFIRM RE-INITIALIZATION" 3. If confirmed: - Create backup of current memory bank - Reset state to PROJECT_PHASE = "INITIALIZING" - Reset START_PHASE_STATUS to "IN_PROGRESS" - Reset START_PHASE_STEP to 1 --- *This file automatically tracks the current state of the project. It should never be edited manually.* ================================================ FILE: .gitignore ================================================ # Logs logs !docs/logs !docs/logs/** *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? .env tmp # TypeScript build info *.tsbuildinfo ================================================ FILE: .i18n-ally.yml ================================================ # i18n Ally 配置文件 # 文档: https://github.com/lokalise/i18n-ally # 语言文件路径 localesPaths: - src/core/locales # 翻译键的样式 keystyle: nested # 启用的框架 enabledFrameworks: - i18next - react # 源语言(主要开发语言) sourceLanguage: zh-CN # 显示语言 displayLanguage: zh-CN # 命名空间 namespace: false # 路径匹配模式 pathMatcher: "{locale}.json" # 扫描忽略的文件 usage: scanningIgnore: - "**/node_modules/**" - "**/dist/**" - "**/*.spec.{js,jsx,ts,tsx}" - "**/*.test.{js,jsx,ts,tsx}" scanningDepth: 10 # 内联注释显示 annotation: inPlace: true maxLength: 30 ================================================ FILE: .npmrc ================================================ ignore-workspace-root-check=true registry=https://registry.npmjs.org/ ================================================ FILE: .ossutilconfig.example ================================================ [Credentials] language=CH Region=cn-hangzhou endpoint=oss-cn-hangzhou.aliyuncs.com accessKeyID=your-accessKeyID accessKeySecret=your-accessKeySecret ================================================ FILE: AGENTS.md ================================================ # AGENTS ## 总则 1. 假设你是ceo+cto(架构师)+产品经理的综合体,从这个角度来思考所有问题 2. 不要管开发代价,永远只考虑最终最佳方案,反正都是你来开发 3. 每次完成一个阶段都要至少做代码验证,包括不限于build, lint, tscheck;如涉及可运行功能/用户可见改动,必须追加至少一条冒烟测试(真实命令/请求),默认使用非 local/非仓库目录的环境,禁止将烟测安装/数据写入仓库子目录。 4. 涉及后端或数据库变更的发布必须执行远程 migration,并对关键 API 做线上冒烟验证后才算阶段完成 5. 任何“发布/上线”必须形成闭环:migrations apply -> deploy -> 线上冒烟验证;缺一不可,否则视为未完成 6. 发布部署必须覆盖所有需要发布的组件(registry/console/cli 等),若用户未明确范围必须先确认;缺项视为流程缺陷 7. 若用户明确要求“直接发布/不做选择”,默认执行全量发布闭环(覆盖所有本次变更涉及的组件),不得再次要求用户决策 8. NPM 包发布流程详见 `docs/workflows/npm-release-process.md`,必须遵循 9. 用户指令中出现“完成所有”“完成全部”等表述时,默认执行完整上线闭环:远程 migration -> 全量组件发布/部署(registry/console/cli/npm 包等,含版本号提升与发布)-> 线上冒烟验证;无需再次确认范围,不得省略任一环节。 --- 负面清单 - 同一个功能,逻辑不应该多次实现。唯一性。 - UI 组件禁止依赖业务逻辑 不急,接下来我们采取一种面向未来的逆天超级快节奏的开发方式。 ## Workflows - Feature-Based 架构规范: `.agent/workflows/feature-based-architecture.md` - 代码库治理指导思想与战略: `.agent/workflows/governance-strategy.md` 后续我们要有统一的规范和不断完善的机制。我们会不断维护 Agents.md。 ## 迭代制度(docs/logs) - 每个迭代在 `docs/logs` 下新增一个目录 - 目录内按版本号建立子目录,命名为 `v0.0.1-版本的slug`(语义化) - 每个版本目录至少包含: - 迭代完成说明(改了什么) - 测试/验证/验收方式 - 发布/部署方式 - 可选文档:PRD、讨论记录等 ## 指令/Command 机制 - 新增指令统一记录在 `commands/commands.md`,并在此处索引 - 约定元指令:输入 `/new-command` 触发创建新指令流程 - 指令文件结构:每条指令包含名称、用途、输入格式、输出/期望行为 - 后续新增或修改指令时,更新 `commands/commands.md` 并保持此处索引最新 - 已有指令: - `/new-command`:创建新指令 - `/config-meta`:调整或更新本文件(AGENTS.md)的机制/元信息 - `/commit`:进行提交操作(提交信息需使用英文) - `/validate`:运行项目验证,至少包含 `build`、`lint`、`tsc`,必要时冒烟测试 ## 规则/Rule 机制 - 规则直接维护在本文件末尾的 **Rulebook** 区域 - 约定元指令:输入 `/new-rule` 触发创建新规则流程 - 规则条目包含:名称(英文 kebab-case)、约束/适用范围、示例/反例、执行方式(工具/流程)、维护责任人 - 后续新增或修改规则时,直接在本文件的 **Rulebook** 区域追加/更新 - 默认所有规则必须严格遵守(无额外声明即视为强制);如需例外必须在规则中明确说明 ## Rulebook - **post-dev-stage-validation**:每个开发阶段结束必须做验证,至少运行 `build`、`lint`、`tsc`(如确认为无关可有理由地省略),如条件允许应做基础冒烟测试。 - **no-self-commit-without-request**:除非用户明确要求,否则禁止擅自提交/推送代码。 - **use-chinese-when-communicating**:与用户交流时使用中文。 - **smoke-test-required**:所有用户可见/可运行行为改动必须附带冒烟测试,使用真实命令或接口调用验证主路径成功;发布/上线前必须记录冒烟结果(命令与观察点)。执行方式:按组件选择对应 CLI/API/UI 最小可行流程;责任人:当次交付 owner。 - **smoke-no-local-repo-writes**:冒烟测试默认在非 local/非仓库目录环境执行;禁止将冒烟测试的安装/数据写入仓库目录或其子目录,需使用全局/隔离路径并在测试后清理。执行方式:优先 global scope 或临时目录;责任人:当次交付 owner。 - **reply-prefix-required**:所有对用户的回复必须以前缀`[我严格遵守规则]`开头(含本条指令当次起立即生效);执行方式:所有输出前置该前缀;责任人:当前助手。 - **manager-only-repository-access**:约束/适用范围:repository 只允许在 manager 层访问,其他层(presenter/store/ui/hooks/resources)禁止直接依赖;示例:manager 内调用 repository 读写;反例:hook 直接 import repository;执行方式:代码 review + `rg "core/repositories"` 排查;维护责任人:core。 - **presenter-exposes-managers-only**:约束/适用范围:presenter 只透出 manager 属性,除特殊情况不暴露方法或非 manager 属性;示例:`presenter.messages`;反例:`presenter.emit()` 或 `presenter.events`;执行方式:代码 review;维护责任人:core。 ================================================ FILE: CHANGELOG.md ================================================ # 更新日志 所有对本项目的重要更改都将记录在此文件中。 本文档格式基于 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.0.0/), 并且本项目遵循 [语义化版本](https://semver.org/lang/zh-CN/)。 ## [未发布] ### 新增 - 基于 DeepSeek API 的智能代理对话功能 - 多代理管理系统 - 自动回复功能 - 主题讨论功能 - 亮暗主题切换 - 响应式布局设计 ### 优化 - 优化代理卡片布局 - 改进滚动条样式 - 优化消息列表性能 ### 修复 - 修复消息重复发送问题 - 修复自动回复状态同步问题 - 修复主题切换时的样式问题 ## [0.1.0] - 2024-01-20 ### 新增 - 项目初始化 - 基础UI框架搭建 - 核心功能实现 [未发布]: https://github.com/yourusername/ai-agent-discussion/compare/v0.1.0...HEAD [0.1.0]: https://github.com/yourusername/ai-agent-discussion/releases/tag/v0.1.0 ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # 贡献者行为准则 ## 我们的承诺 为了营造一个开放和友好的环境,我们作为贡献者和维护者承诺:无论年龄、体型、身体健全与否、民族、性征、性别认同与表达、经验水平、教育程度、社会地位、国籍、相貌、种族、宗教信仰、性取向如何,我们项目和社区的参与者都免受骚扰。 ## 我们的标准 有助于创造积极环境的行为包括: * 使用友好和包容性的语言 * 尊重不同的观点和经历 * 耐心地接受建设性批评 * 关注对社区最有利的事情 * 友善对待其他社区成员 不当行为包括: * 使用与性有关的言语或是图像,以及不受欢迎的性骚扰 * 发表挑衅、侮辱/贬损的评论,进行人身攻击或政治攻击 * 公开或私下的骚扰 * 未经明确许可,发布他人的私人信息 * 其他可以被合理地认定为不恰当或者违反职业操守的行为 ## 我们的责任 项目维护者有责任为可接受的行为标准做出诠释,以及对已发生的不当行为采取恰当且公平的纠正措施。 项目维护者有权利和责任删除、编辑或拒绝违反本行为准则的评论、提交、代码、wiki 编辑、问题以及其他贡献,并暂时或永久地禁止任何贡献者进行违反行为。 ## 适用范围 当一个人代表项目或其社区时,本行为准则适用于其所有的项目空间和公共空间。代表项目或社区的情况包括使用官方项目电子邮件地址、通过官方社交媒体帐户发布,或在线上或线下事件中担任指定代表。项目的代表性质可由项目维护者进一步定义和解释。 ## 强制执行 可以通过 [INSERT EMAIL] 向项目团队举报滥用、骚扰或其他不可接受的行为。所有投诉都将被审查和调查,并将作出必要且适当的回应。项目团队有义务为事件举报者保密。具体执行政策的更多细节可能会单独发布。 对于善意遵循或执行本行为准则的项目维护者,不会因为执行本准则而遭到报复性的举动。 ## 来源 本行为准则改编自[贡献者公约][homepage], 版本 1.4,可在此查看: https://www.contributor-covenant.org/zh-cn/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org ================================================ FILE: CONTRIBUTORS.md ================================================ # 贡献者列表 感谢所有为本项目做出贡献的开发者! ## 核心团队 - **[Your Name](https://github.com/yourusername)** - 项目发起人 - 核心功能开发 - 架构设计 ## 功能贡献者 按字母顺序排列: - **[Contributor 1](https://github.com/contributor1)** - 改进代理管理系统 - 优化UI组件 - **[Contributor 2](https://github.com/contributor2)** - 添加新的主题样式 - 修复性能问题 ## 文档贡献者 - **[Doc Writer 1](https://github.com/docwriter1)** - 编写技术文档 - 改进 README ## 如何成为贡献者 1. Fork 本仓库 2. 创建您的特性分支 3. 提交您的改动 4. 推送到您的分支 5. 创建一个 Pull Request 详细信息请参考 [贡献指南](./docs/development-guide.md)。 ## 特别感谢 感谢以下开源项目,没有它们就没有本项目的顺利开发: - [React](https://reactjs.org/) - [Vite](https://vitejs.dev/) - [TailwindCSS](https://tailwindcss.com/) - [Shadcn/ui](https://ui.shadcn.com/) - [DeepSeek](https://deepseek.com) ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2024 AI Agent Discussion Platform Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # AgentVerse - AI 专家团队协作平台 让多个 AI 专家一起为你解决问题的协作平台 [English](./README_EN.md) | 简体中文 ## 🔍 这是什么? AgentVerse 是一个支持多 AI 智能体协作对话的开源平台。在这里,多个具有不同专业领域和个性的 AI 专家可以自主交流、协作讨论,为你提供多角度的专业见解和解决方案。 ## 🚀 在线体验 直接体验:[AgentVerse 演示](https://agent.dimstack.com) ![演示截图](./screenshots/demo2.jpeg) ### 📸 更多截图 ![首页概览](./screenshots/agent-verse-first-page.png) ![群聊讨论](./screenshots/agnet-verse-gangjing-discussion.png) ![头脑风暴与笔记](./screenshots/agentverse-brainstorming-with-note.png) ![Agent 共创编辑](./screenshots/agent-verse-edit-with-agent.png) **核心特点:** - 💬 **多专家协作对话** - 不是简单的聊天机器人,而是一个能自主思考、协作的 AI 专家团队 - 🧠 **丰富的角色设定** - 每个 AI 都有自己的专业领域、个性和思维风格 - 🔄 **自主对话管理** - AI 之间会自动交流讨论,无需你手动协调 - 🛠️ **强大的工具系统** - 支持 MCP 协议,AI 可以使用各种工具完成任务 - 📁 **文件管理能力** - 内置文件系统,支持文件操作和管理 ## 🌟 核心功能 ### 1️⃣ 丰富的预设专家团队 针对不同场景,我们提供了 **14 个预设专家团队**: **思维探索类:** - **思维探索团队** - 深度思考和创新(推荐) - **自由思考组** - 开放性思考和深度探讨 - **认知融合团队** - 概念转化和模式识别 - **情绪决策团队** - 情绪智能和决策优化 - **结构化思考团队** - 使用结构化框架解决问题 - **超级思维团队** - 全方位思维专家团队 **创作类:** - **小说创作组** - 故事创作和剧情发展 - **创意激发组** - 创意发散和跨界思维 - **叙事探索团队** - 故事结构和多元可能性 **商业类:** - **创业创新组** - 商业模式和市场分析 - **产品开发组** - 产品设计、开发和项目管理 - **实践执行团队** - 实际执行和项目落地 **其他:** - **时间探索团队** - 时间视角和历史灵感 - **Agent设计组** - AI Agent 系统设计 ### 2️⃣ 自定义 Agent 创建 - **对话式创建** - 通过自然语言对话创建专属 AI 智能体 - **智能配置助手** - AI 助手帮你完善 Agent 配置,减少手动操作 - **灵活定制** - 支持自定义角色、性格、专长、行为方式等 ### 3️⃣ MCP 工具集成 支持 **Model Context Protocol (MCP)**,让 AI 可以使用外部工具: - 文件系统操作 - 数据查询和分析 - 信息检索 - 自动化任务 - 代码生成和执行 ### 4️⃣ 文件管理系统 内置基于 LightningFS 的文件系统: - 文件/目录的增删改查 - 文件内容编辑和预览 - 文件搜索 - 文件上传和下载 ### 5️⃣ 多讨论管理 - 支持多个独立的讨论话题 - 讨论状态控制(活跃/暂停) - 消息历史记录 - 自动标题生成 ## 💡 应用场景 ### 头脑风暴和创意激发 让不同思维方式的 AI 专家一起激发创意,从多角度思考问题。 ### 产品设计与评估 产品经理、开发者、设计师和用户体验专家一起讨论产品方案。 ### 决策辅助 获取多个专业角度的分析和建议,辅助重要决策。 ### 学习辅导 多位导师从不同角度解释概念,提供全面的学习支持。 ### 代码开发与调试 AI 专家协作分析代码问题,提供解决方案,并可以使用工具执行实际操作。 ## 🛠️ 技术特点 - 🌐 **完整的智能体生态** - 多角色协作、自主对话、场景化应用 - 📱 **响应式设计** - 完美支持桌面端和移动端 - 🎨 **深色/浅色主题** - 支持主题切换 - 🔌 **可扩展架构** - 支持插件和扩展 - 🛡️ **类型安全** - 完整的 TypeScript 支持 ## 🚀 快速开始 ### 环境要求 - Node.js >= 18 - pnpm >= 8.0 ### 安装步骤 1. **克隆并安装** ```bash git clone https://github.com/Peiiii/AgentVerse.git cd AgentVerse pnpm install ``` 2. **配置环境变量** ```bash cp .env.example .env # 编辑 .env 文件,配置 AI 服务商和 API Key ``` 3. **启动开发服务器** ```bash pnpm dev ``` 访问 `http://localhost:3000` 即可使用。 ## 🗺️ 开发计划 近期: - [x] 主题切换(亮暗主题) - [x] 移动端适配 - [x] 添加自动终止机制 - [x] 支持自定义大模型 API_KEY - [x] MCP 工具集成 - [x] 文件管理系统 - [x] 多语言支持(中文/英文) ## 📄 许可证 本项目采用 MIT 许可证 - 查看 [LICENSE](LICENSE) 文件了解详情 ## 📞 联系我们 - [GitHub Issues](https://github.com/Peiiii/AgentVerse/issues) ================================================ FILE: README_EN.md ================================================ # AgentVerse - AI Expert Team Collaboration Platform A platform where multiple AI experts collaborate to solve your problems English | [简体中文](./README.md) ## 🔍 What is AgentVerse? AgentVerse is an open-source platform that supports autonomous conversations between multiple AI agents. Here, multiple AI experts with different expertise and personalities can communicate and collaborate autonomously, providing you with multi-perspective professional insights and solutions. ## 🚀 Live Demo Try it now: [AgentVerse Demo](https://agent.dimstack.com) ![Demo Screenshot](./screenshots/demo2.jpeg) **Core Features:** - 💬 **Multi-Expert Collaboration** - Not just a simple chatbot, but a team of AI experts that can think independently and collaborate - 🧠 **Rich Character Profiles** - Each AI has its own expertise, personality, and thinking style - 🔄 **Autonomous Dialogue Management** - AIs discuss and interact automatically, no need for manual coordination - 🛠️ **Powerful Tool System** - Supports MCP protocol, allowing AIs to use various tools to complete tasks - 📁 **File Management** - Built-in file system supporting file operations and management ## 🌟 Core Features ### 1️⃣ Rich Preset Expert Teams We provide **14 preset expert teams** for different scenarios: **Thinking & Exploration:** - **Thinking Exploration Team** - Deep thinking and innovation (Recommended) - **Free Thinking Group** - Open thinking and deep exploration - **Cognitive Fusion Team** - Concept transformation and pattern recognition - **Emotional Decision Team** - Emotional intelligence and decision optimization - **Structured Thinking Team** - Problem-solving using structured frameworks - **Super Thinking Team** - Comprehensive thinking expert team **Creative:** - **Story Creation Team** - Story creation and plot development - **Creative Ideation Group** - Creative divergence and cross-domain thinking - **Narrative Exploration Team** - Story structure and multiple possibilities **Business:** - **Startup Ideation Team** - Business models and market analysis - **Product Development Team** - Product design, development, and project management - **Practical Execution Team** - Actual execution and project implementation **Others:** - **Time Exploration Team** - Time perspective and historical inspiration - **Agent Design Team** - AI Agent system design ### 2️⃣ Custom Agent Creation - **Conversational Creation** - Create exclusive AI agents through natural language dialogue - **Intelligent Configuration Assistant** - AI assistant helps you complete Agent configuration with minimal manual operation - **Flexible Customization** - Support custom roles, personalities, expertise, behaviors, etc. ### 3️⃣ MCP Tool Integration Supports **Model Context Protocol (MCP)**, enabling AIs to use external tools: - File system operations - Data query and analysis - Information retrieval - Automated tasks - Code generation and execution ### 4️⃣ File Management System Built-in file system based on LightningFS: - File/directory CRUD operations - File content editing and preview - File search - File upload and download ### 5️⃣ Multi-Discussion Management - Support multiple independent discussion topics - Discussion state control (active/paused) - Message history - Automatic title generation ## 💡 Real-World Applications ### Brainstorming and Idea Generation Let AI experts with different thinking styles spark creativity and explore problems from multiple angles. ### Product Design and Evaluation Product managers, developers, designers, and UX specialists discuss product solutions together. ### Decision Support Get analysis and advice from multiple professional perspectives to aid important decisions. ### Learning Assistance Multiple tutors explain concepts from different perspectives, providing comprehensive learning support. ### Code Development and Debugging AI experts collaborate to analyze code issues, provide solutions, and can use tools to perform actual operations. ## 🛠️ Technical Features - 🌐 **Complete Agent Ecosystem** - Multi-role collaboration, autonomous dialogue, scenario-based applications - 📱 **Responsive Design** - Perfect support for desktop and mobile - 🎨 **Dark/Light Theme** - Theme switching support - 🔌 **Extensible Architecture** - Support for plugins and extensions - 🛡️ **Type Safety** - Full TypeScript support ## 🚀 Quick Start ### Requirements - Node.js >= 18 - pnpm >= 8.0 ### Installation 1. **Clone and Install** ```bash git clone https://github.com/Peiiii/AgentVerse.git cd AgentVerse pnpm install ``` 2. **Configure Environment** ```bash cp .env.example .env # Edit .env file to configure AI provider and API Key ``` 3. **Start Development Server** ```bash pnpm dev ``` Visit `http://localhost:3000` to use the application. ## 🗺️ Development Plan Near-term: - [x] Theme switching (light/dark) - [x] Mobile responsiveness - [x] Add auto termination mechanism - [x] Support custom large model API_KEY - [x] MCP tool integration - [x] File management system - [ ] Multi-language support ## 📄 License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details ## 📞 Contact - [GitHub Issues](https://github.com/Peiiii/AgentVerse/issues) ================================================ FILE: babel.config.cjs ================================================ module.exports = { presets: [ ['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript' ], plugins: [ ['@babel/plugin-proposal-decorators', { legacy: true }] ] }; ================================================ FILE: commands/commands.md ================================================ # Commands - `/new-command`: 新建一条指令的元指令。流程:确认名称、用途、输入格式、输出/期望行为,写入本文件并保持 `AGENTS.md` 索引同步。 - `/config-meta`: 调整或更新 `AGENTS.md` 中的机制/元信息(如规则、流程、索引等)的指令。执行时需明确变更点与预期影响。 - `/commit`: 进行提交操作(提交信息需使用英文)。 - `/validate`: 对项目进行验证,至少运行 `build`、`lint`、`tsc`,必要时补充冒烟测试。执行前需确认验证范围和可跳过项。 (后续指令在此追加,保持格式一致。) ================================================ FILE: components.json ================================================ { "$schema": "https://ui.shadcn.com/schema.json", "style": "new-york", "rsc": false, "tsx": true, "tailwind": { "config": "tailwind.config.js", "css": "src/styles/globals.css", "baseColor": "neutral", "cssVariables": true, "prefix": "" }, "aliases": { "components": "@/common/components", "utils": "@/common/lib/utils", "ui": "@/common/components/ui", "lib": "@/common/lib", "hooks": "@/common/hooks" }, "iconLibrary": "lucide" } ================================================ FILE: docs/PAGE_STRUCTURE.md ================================================ # 页面结构设计 ## 主体布局 ``` ┌─────────────────────────────────────────────────────────────┐ │ 导航栏 │ │ Logo + Agent管理 + 全局搜索 + 设置 + 主题切换 │ ├───────────────┬─────────────────────────┬───────────────────┤ │ 会话列表 │ 会话区域 │ 会话成员 │ │ (w:320px) │ │ (w:320px) │ ├───────────────┤ ├───────────────────┤ │ ┌───────────┐ │ ┌─────────────────┐ │ ┌───────────────┐ │ │ │新建会话 │ │ │ 会话控制面板 │ │ │成员管理 │ │ │ └───────────┘ │ │- 开始/暂停 │ │ │+ 添加成员 │ │ │ │ │- 设置 │ │ └───────────────┘ │ │ ┌───────────┐ │ └─────────────────┘ │ │ │ │会话列表 │ │ │ ┌───────────────┐ │ │ │[会话卡片] │ │ ┌─────────────────┐ │ │成员列表 │ │ │ │- 标题 │ │ │ 消息列表 │ │ │[成员卡片] │ │ │ │- 主题 │ │ │ [消息气泡] │ │ │- 头像 │ │ │ │- 时间 │ │ │ - 头像 │ │ │- 名称 │ │ │ │- 成员数 │ │ │ - 名称 │ │ │- 角色 │ │ │ │- 状态 │ │ │ - 时间 │ │ │- 自动回复开关 │ │ │ └───────────┘ │ │ - 内容 │ │ │ │ │ │ │ │ │ │ │(hover显示更多) │ │ │ │ └─────────────────┘ │ └───────────────┘ │ │ │ │ │ │ │ ┌─────────────────┐ │ │ │ │ │ 输入区域 │ │ │ │ │ │- 成员选择 │ │ │ │ │ │- 消息输入 │ │ │ │ │ │- 发送按钮 │ │ │ │ │ └─────────────────┘ │ │ └───────────────┴─────────────────────────┴───────────────────┘ 弹出层: ┌─────────────────────────────────┐ │ Agent管理弹窗 │ └─────────────────────────────────┘ ┌─────────────────────────────────┐ │ 添加会话成员弹窗 │ └─────────────────────────────────┘ ┌─────────────────────────────────┐ │ 会话设置弹窗 │ └─────────────────────────────────┘ ``` ## 关键设计说明 1. 三栏布局 - 左侧:会话管理 (320px) - 中间:对话区域 (自适应) - 右侧:成员管理 (320px) 2. 信息展示 - 核心信息直接展示 - 次要信息通过 hover 展示 - 配置通过弹窗管理 ================================================ FILE: docs/agent-action.md ================================================ ## AI 接口层(实际可用的能力调用格式) ````markdown 模型在需要调用工具时,必须输出一个 `:::action … :::` 区块: :::action { "operationId": "searchFiles_482910_0", "capability": "searchFiles", "description": "让我搜索一下相关文件", "params": { "query": "*.ts" } } ::: ```` 字段含义: - `operationId`:唯一 ID,通常按照 `{capability}_{timestamp}_{sequence}` 生成。 - `capability`:要调用的系统能力名称,必须存在于 `CapabilityRegistry`。 - `description`:自然语言描述本次操作的目的,便于人类理解。 - `params`:传入能力的参数对象,可为空对象。 > ⚠️ 当前实现**仅支持**上述线性语法。``、``、`await` 等扩展语法尚未实现,也不会被解析。 ## 内部实现 ```ts interface ActionDef { operationId: string; type: "action"; capability: string; description: string; params: Record; await?: boolean; // 预留字段,当前执行器不会使用 } class ActionParser { parse(content: string): ActionParseResult[] { const actionRegex = /:::action(?:\s+|\s*\n)([\s\S]*?)(?:\s*\n|)\s*:::\s*/g; // 每个 :::action 块被单独解析为 ActionDef } } class DefaultActionExecutor { async execute(actions: ActionParseResult[], registry: CapabilityRegistry) { // 顺序执行解析到的每个 ActionDef // 成功/失败结果会被包装为 action_result 消息写回消息流 } } ``` 执行流程: 1. `ActionParser` 顺序扫描消息内容中的每个 `:::action` 块。 2. 解析得到的 `ActionDef` 会被 `DefaultActionExecutor` 依次执行。 3. 每条 action 的 `result`/`error`、`status` 等会写入一条新的 `action_result` 系统消息。 4. 目前没有并发、流程控制、嵌套等高级语义,模型不应该输出这些标记。 ## 行为约束 - 能力调用前后需要用自然语言解释目的及后续计划。 - 一次消息可以包含多个 `:::action` 区块,但它们会按出现顺序依次执行。 - 在 `action_result` 返回前不要继续下一步推理或重复调用相同能力。 - 如果系统提示权限不足或出现解析错误,应改为自然语言沟通并等待进一步指示。 ================================================ FILE: docs/architecture/agent-architecture.md ================================================ # Agent系统架构设计 ## 概述 本文档描述了一个完整的Agent系统架构设计,包括Agent模型、环境模型以及它们之间的交互机制。这个设计采用了高度解耦的方式,使得系统具有更好的可维护性、可扩展性和灵活性。 ## 核心设计原则 1. **完全解耦** - Agent和Environment完全独立 - 通过Bridge模式实现交互 - 支持独立演化和升级 2. **状态隔离** - Agent维护自身状态 - Environment维护全局状态 - 通过同步机制保持一致 3. **行为封装** - Agent定义行为意图 - Environment控制行为执行 - Bridge处理转换和验证 4. **事件驱动** - 所有交互基于事件 - 异步处理和响应 - 支持追踪和回滚 ## 1. Agent模型 ### 1.1 核心结构 ```typescript interface IAgent { readonly identity: AgentIdentity // 身份特征 readonly capabilities: AgentCapabilities // 能力系统 readonly cognition: AgentCognition // 认知系统 readonly behavior: AgentBehavior // 行为系统 } ``` ### 1.2 身份特征 ```typescript interface AgentIdentity { // 不可变特征 readonly id: string readonly name: string readonly role: AgentRole readonly expertise: string[] // 个性特征 readonly personality: PersonalityTrait[] readonly values: ValueSystem readonly biases: AgentBias[] // 社交特征 readonly communicationStyle: CommunicationStyle readonly socialBoundaries: SocialBoundary[] } ``` ### 1.3 能力系统 ```typescript interface AgentCapabilities { // 基础能力 canPerceive(stimulus: Stimulus): boolean canProcess(information: Information): boolean canRespond(situation: Situation): boolean // 专业能力 readonly expertiseLevel: Map readonly skillSet: Set // 能力限制 readonly limitations: Set } ``` ### 1.4 认知系统 ```typescript interface AgentCognition { // 记忆系统 memory: { shortTerm: ShortTermMemory // 对话上下文 workingMemory: WorkingMemory // 当前任务 longTerm: LongTermMemory // 知识库 } // 注意力系统 attention: { focus: Focus priority: PriorityQueue } // 决策系统 decisionMaking: { evaluate(situation: Situation): Decision plan(goal: Goal): Action[] } } ``` ### 1.5 行为系统 ```typescript interface AgentBehavior { // 行为选择 selectAction(context: Context): Action // 行为执行 executeAction(action: Action): Promise // 行为调整 adjustBehavior(feedback: Feedback): void } ``` ## 2. Environment模型 ### 2.1 核心结构 ```typescript interface IEnvironment { readonly state: EnvironmentState // 状态管理 readonly eventSystem: EventSystem // 事件系统 readonly ruleEngine: RuleEngine // 规则引擎 readonly resourceManager: ResourceManager // 资源管理 } ``` ### 2.2 环境状态 ```typescript interface EnvironmentState { // 全局状态 readonly globalState: Map // 参与者状态 readonly agentStates: Map // 资源状态 readonly resources: Map // 状态快照 snapshot(): StateSnapshot restore(snapshot: StateSnapshot): void } ``` ### 2.3 事件系统 ```typescript interface EventSystem { // 事件发布 emit(event: EnvironmentEvent): void // 事件订阅 on(eventType: string, handler: EventHandler): Subscription // 事件过滤 filter(criteria: EventCriteria): EventStream } ``` ### 2.4 规则引擎 ```typescript interface RuleEngine { // 规则定义 readonly rules: Set // 规则验证 validate(action: Action): ValidationResult // 规则执行 enforce(rule: EnvironmentRule): void } ``` ## 3. 交互机制 ### 3.1 交互层 ```typescript interface IInteractionLayer { // 通信协议 protocol: { send(message: Message): Promise receive(message: Message): Promise validate(message: Message): ValidationResult } // 状态同步 synchronization: { updateState(changes: StateChange[]): void resolveConflicts(conflicts: Conflict[]): Resolution } // 行为协调 coordination: { registerAction(action: Action): void executeAction(action: Action): Promise rollbackAction(action: Action): Promise } } ``` ### 3.2 Bridge模式 ```typescript class AgentEnvironmentBridge { private agent: IAgent private environment: IEnvironment private interactionLayer: IInteractionLayer // Agent到Environment的映射 mapAgentToEnvironment() { this.registerCapabilities() this.setupPerception() this.mapBehaviors() } // Environment到Agent的映射 mapEnvironmentToAgent() { this.setupResourceAccess() this.setupEventListeners() this.applyRules() } // 交互管理 private interactionManager = { syncState: async () => { /* ... */ }, executeAction: async (action: Action) => { /* ... */ }, handleEvent: async (event: EnvironmentEvent) => { /* ... */ } } } ``` ## 4. 实现考虑 ### 4.1 技术选择 - TypeScript作为主要开发语言 - 事件驱动架构 - 响应式编程模型 - 依赖注入设计模式 ### 4.2 扩展性考虑 - 支持新Agent类型的添加 - 支持新环境特性的集成 - 支持新交互模式的实现 ### 4.3 性能考虑 - 状态管理优化 - 事件处理效率 - 资源使用控制 ### 4.4 安全性考虑 - Agent行为约束 - 资源访问控制 - 状态一致性保护 ## 5. 后续发展 ### 5.1 近期计划 - 实现基础框架 - 开发核心功能 - 构建测试用例 ### 5.2 中期目标 - 优化性能 - 增强功能 - 改进用户体验 ### 5.3 长期愿景 - 支持复杂场景 - 提供更多功能 - 建立生态系统 ## 6. 参考资料 - 相关论文 - 技术文档 - 最佳实践 ================================================ FILE: docs/architecture/agents-architecture.md ================================================ # Agents Module Architecture (Resource-first + Repository) Status: Adopted ## Goals - Single source of truth for Agent data - Pure-read queries (no side-effect on read) - Unified write path with consistent cache invalidation - Backward-compatible UI API during migration ## Layers and Responsibilities - Service (IO only) - File: `src/core/services/agent.service.ts` - CRUD to storage/HTTP; no caching; no default seeding; no UI coupling. - Resource (query + cache) - File: `src/core/resources/index.ts` (`agentListResource`) - Purely returns `agentService.listAgents()`; no write side-effects. - Consumable via `useResourceState(resource)` for Suspense-friendly reads. - Repository (unified write facade) - Implemented via `AgentsManager`. - Write methods call Service, then `await agentListResource.reload()` to refresh the singleton cache. - Bootstrap/Migrations (one-off, idempotent) - File: `src/core/bootstrap/agents.bootstrap.ts` - `ensureDefaultAgents()` creates/updates built-in defaults on app start. - Long-term: move to `slug + version` match; currently name-based for backward compatibility. - Store - Removed for Agents domain to avoid double caching and drift. - Hooks - `useAgents()` reads from `agentsResource.list` (resource-first). Prefer this everywhere. ## Data Flow 1. App start: - `PresenterProvider` calls `ensureDefaultAgents()` then `agentListResource.reload()`. - `AgentsManager` subscribes to `agentListResource` and mirrors its state into the store. 2. Write (create/update/delete): - Manager -> Service (CRUD) -> `agentListResource.reload()` -> UI hooks auto-refresh. 3. Read: - Prefer `useAgents()` hook which reads the Resource directly. - Legacy code paths still read `presenter.agents.store` (mirrored). ## Conventions - No write side-effects in resources. - All writes must reload the resource. - Avoid name-based matching in business logic. Introduce `slug` (stable id) + `version` for default agents in future evolution. ## Migration Plan 1. (Done) Move default agents seeding into bootstrap and purify `agentListResource`. 2. (Done) Mirror resource into store; update manager to reload resource after writes. 3. (Done) Remove store from Agents domain; all consumers use resource hooks. 4. (Next) Introduce `slug + version` for default agents; update bootstrap matcher. ## Rationale This design minimizes data duplication, improves predictability (pure reads), and provides a single invalidation point (`agentListResource.reload()`). ## Diagram ```mermaid flowchart TD subgraph UI A[useAgents Hook] C[Chat/Pages] end subgraph App R[agentListResource] M[AgentsManager (Repository)] B[ensureDefaultAgents Bootstrap] end subgraph IO S[agent.service (CRUD)] LS[(localStorage/DB)] end A --> R C --> A M --> S S --> LS M --> R B --> S B --> R ``` ================================================ FILE: docs/architecture/chat-discussion-features.md ================================================ # Chat 和 Discussion Feature 组织架构 ## 概述 `src/common/features/` 下的 `chat` 和 `discussion` 是两个核心功能模块,它们遵循功能优先的组织原则,按业务功能而非技术层次进行组织。 ## 目录结构对比 ### Chat Feature (`src/common/features/chat/`) ``` chat/ ├── components/ # 聊天相关组件 │ ├── agent-action-display/ # Agent 动作显示 │ │ ├── components/ # 子组件 │ │ │ ├── action-display.tsx │ │ │ ├── action-user-select.tsx │ │ │ ├── default-action.tsx │ │ │ ├── select-display.tsx │ │ │ ├── select-option.tsx │ │ │ └── status-icon.tsx │ │ ├── index.tsx │ │ └── types.ts │ ├── agent-chat/ # Agent 聊天核心组件 │ │ ├── agent-chat-container.tsx # 容器组件 │ │ ├── agent-chat-header.tsx # 头部 │ │ ├── agent-chat-header-with-info.tsx │ │ ├── agent-chat-input.tsx # 输入组件 │ │ ├── agent-chat-messages.tsx # 消息列表 │ │ ├── agent-chat-provider-wrapper.tsx │ │ ├── tool-call-renderer.tsx │ │ ├── index.ts # 导出文件 │ │ └── README.md │ ├── markdown/ # Markdown 渲染 │ │ ├── plugins/ # 插件 │ │ │ ├── remark-action.ts │ │ │ └── remark-mdast-to-hast.ts │ │ ├── types/ # 类型定义 │ │ │ ├── action.ts │ │ │ ├── index.ts │ │ │ └── remark.ts │ │ ├── index.tsx │ │ └── types.ts │ ├── message/ # 消息相关组件 │ │ ├── message-capture.tsx │ │ ├── message-item.tsx │ │ ├── message-item-wechat.tsx │ │ ├── message-list.tsx │ │ ├── message-list-desktop.tsx │ │ ├── message-list-mobile.tsx │ │ ├── message-preview-dialog.tsx │ │ └── index.tsx │ ├── suggestions/ # 建议功能 │ │ ├── suggestions-provider.tsx │ │ ├── suggestion.types.ts │ │ ├── index.ts │ │ └── README.md │ ├── chat-area.tsx # 聊天区域主组件 │ ├── chat-empty-guide.tsx # 空状态引导 │ ├── chat-welcome-header.tsx # 欢迎头部 │ ├── mention-suggestions.tsx # @ 提及建议 │ ├── message-input.tsx # 消息输入(通用) │ ├── message-input-desktop.tsx # 桌面端输入 │ ├── message-input-mobile.tsx # 移动端输入 │ ├── modern-chat-input.tsx # 现代风格输入 │ └── index.ts # 统一导出 └── pages/ └── chat-page.tsx # 聊天页面 ``` ### Discussion Feature (`src/common/features/discussion/`) ``` discussion/ └── components/ ├── control/ # 讨论控制 │ ├── discussion-controller.tsx # 主控制器 │ ├── clear-messages-button.tsx # 清空消息按钮 │ └── use-discussion-control.ts # 控制逻辑 Hook ├── list/ # 讨论列表 │ ├── discussion-list.tsx # 列表主组件 │ ├── discussion-item.tsx # 列表项 │ ├── discussion-list-header.tsx # 列表头部 │ ├── discussion-avatar.tsx # 讨论头像 │ ├── index.ts # 导出文件 │ └── types.ts # 类型定义 ├── member/ # 成员管理 │ ├── member-list.tsx # 成员列表 │ ├── member-item.tsx # 成员项 │ ├── member-skeleton.tsx # 骨架屏 │ ├── member-toggle-button.tsx # 切换按钮 │ ├── add-member-dialog.tsx # 添加成员对话框 │ ├── quick-member-selector.tsx # 快速选择器 │ ├── mobile-member-drawer.tsx # 移动端抽屉 │ └── mobile-member-list.tsx # 移动端列表 ├── mobile/ # 移动端组件 │ ├── mobile-header.tsx # 移动端头部 │ └── mobile-action-sheet.tsx # 操作面板 └── settings/ # 设置面板 ├── discussion-settings-panel.tsx # 设置面板主组件 ├── discussion-settings-button.tsx # 设置按钮 ├── setting-item.tsx # 设置项 ├── setting-switch.tsx # 开关组件 ├── setting-slider.tsx # 滑块组件 └── setting-select.tsx # 选择组件 ``` ## 组织原则分析 ### 1. 功能优先原则 两个 feature 都遵循**功能优先**的组织方式: - **Chat**: 按功能模块组织(agent-chat、message、markdown、suggestions) - **Discussion**: 按功能模块组织(control、list、member、settings、mobile) ### 2. 组件层级结构 #### Chat Feature - **顶层组件**: `chat-area.tsx` - 聊天区域主组件 - **核心模块**: `agent-chat/` - Agent 聊天核心功能 - **功能模块**: - `message/` - 消息显示 - `markdown/` - Markdown 渲染 - `suggestions/` - 建议功能 - `agent-action-display/` - 动作显示 #### Discussion Feature - **功能模块**: - `control/` - 讨论控制(开始/暂停/清空) - `list/` - 讨论列表(列表、项、头部) - `member/` - 成员管理(列表、添加、选择) - `settings/` - 设置面板 - `mobile/` - 移动端适配 ### 3. 导出策略 #### Chat Feature - `components/index.ts`: 统一导出核心组件 ```typescript export { AgentChatContainer, AgentChatHeader, AgentChatMessages, AgentChatInput } from "./agent-chat"; ``` - `agent-chat/index.ts`: 模块内部导出 - `message/index.tsx`: 消息组件导出 #### Discussion Feature - `list/index.ts`: 列表相关组件导出 ```typescript export { DiscussionList } from "./discussion-list"; export { DiscussionItem } from "./discussion-item"; export { DiscussionListHeader } from "./discussion-list-header"; export { DiscussionAvatar } from "./discussion-avatar"; export type { DiscussionItemProps } from "./types"; ``` ### 4. 平台分离 - **Chat**: 通过文件名区分(`message-input-desktop.tsx` vs `message-input-mobile.tsx`) - **Discussion**: 通过 `mobile/` 目录分离移动端组件 ### 5. 类型定义 - **Chat**: - 模块内类型:`agent-action-display/types.ts`、`markdown/types.ts` - 统一类型:`common/types/chat.ts` - **Discussion**: - 模块内类型:`list/types.ts` - 统一类型:`common/types/discussion.ts`、`common/types/discussion-member.ts` ## 关键差异 ### Chat Feature 特点 1. **更复杂的组件层级**: 有嵌套的子组件目录(如 `agent-action-display/components/`) 2. **更多功能模块**: 包含 markdown、suggestions、agent-action 等多个功能模块 3. **页面组件**: 有独立的 `pages/chat-page.tsx` 4. **插件系统**: `markdown/plugins/` 支持插件扩展 ### Discussion Feature 特点 1. **更扁平的结构**: 组件目录相对扁平,没有深层嵌套 2. **功能明确**: 每个目录对应一个明确的功能(控制、列表、成员、设置) 3. **移动端分离**: 有专门的 `mobile/` 目录 4. **无页面组件**: 组件被其他页面使用,不包含页面组件 ## 使用关系 ### Chat 使用 Discussion - `chat-page.tsx` 使用 `DiscussionController`、`DiscussionList`、`MemberList` - Chat 功能依赖于 Discussion 的讨论管理功能 ### Discussion 独立 - Discussion 组件是独立的,可以被多个页面使用 - 不依赖 Chat 组件 ## 改进建议 ### 1. 统一导出策略 - Discussion 可以添加 `components/index.ts` 统一导出 - 各子模块保持自己的 `index.ts` 导出 ### 2. 类型定义位置 - 建议将模块内类型统一到 `common/types/` 或模块根目录的 `types.ts` - 保持类型定义的一致性 ### 3. 文档完善 - Chat 的 `agent-chat/README.md` 是好的实践 - Discussion 可以添加类似的 README 文档 ### 4. 组件拆分 - 确保单个组件文件不超过 250 行 - 大组件及时拆分为子组件 ## 总结 两个 feature 都遵循了**功能优先**的组织原则,按业务功能而非技术层次组织代码。Chat 更复杂,包含更多功能模块和嵌套结构;Discussion 更扁平,功能划分更清晰。两者都很好地实现了平台分离和模块化设计。 ================================================ FILE: docs/architecture/diagrams/architecture.mmd ================================================ %% 架构图源文件 graph TD A[Client] --> B[API Gateway] B --> C[Service Mesh] C --> D[Agent Core] ================================================ FILE: docs/architecture/discussions-architecture.md ================================================ # Discussions/Messages/Members Architecture (Resource-first + Repository) Status: Adopted ## Goals - Remove double-caching between stores and resources - Make queries pure-read; centralize write invalidation - Keep a simple, predictable flow tied to `discussionControlService` ## Layers - Service: `discussion.service.ts`, `message.service.ts`, `discussion-member.service.ts` - CRUD only; no caching; no UI concerns. - Resource: `discussionsResource`, `messagesResource`, `discussionMembersResource` in `src/core/resources/index.ts` - list/current discussions; current messages; current members - Pure read; subscribe to `discussionControlService.onCurrentDiscussionIdChange$` to auto-reload current-scoped resources. - Repository (Managers): `DiscussionsManager`, `MessagesManager`, `DiscussionMembersManager` - Thin write facades: call Service then `resource.reload()`; no local store. - Read helpers fetch from resource state (`getState()`), avoiding Suspense throw. - Hooks: `useDiscussions()`, `useMessages()`, `useDiscussionMembers()` - Consume Resource via `useResourceState`. - Export data/isLoading/error (+ helpers like `addMessage`). - Control: `discussionControlService` - Tracks current discussion id; emits changes to resources. ## Data Flow 1. App start: `PresenterProvider` bootstraps and calls `presenter.discussions.load()` which reloads `discussionsResource.list`. 2. Selecting a discussion: `DiscussionsManager.select(id)` -> `discussionControlService.setCurrentDiscussionId(id)` -> resources subscribed to the change reload their data. 3. Writes: Manager -> Service -> `resource.reload()` -> hooks update. ## Removed - Zustand stores for discussions/messages/members have been deleted to avoid drift. ## Migration Notes - UI should use hooks instead of `presenter.*.store((s)=>...)`. - If an immediate value is needed within an effect without triggering Suspense, use resource `getState()`. ## Diagram ```mermaid flowchart TD subgraph UI UD[useDiscussions] UM[useMessages] UDM[useDiscussionMembers] end subgraph App RD[discussionsResource] RM[messagesResource] RDM[discussionMembersResource] DM[DiscussionsManager] MM[MessagesManager] DMM[DiscussionMembersManager] CTRL[discussionControlService] end subgraph IO DS[discussion.service] MS[message.service] DMS[discussion-member.service] end UD --> RD UM --> RM UDM --> RDM DM --> DS MM --> MS DMM --> DMS DS --> RD MS --> RM DMS --> RDM CTRL --> RD CTRL --> RM CTRL --> RDM ``` ================================================ FILE: docs/architecture/extension-architecture.md ================================================ # Extension 架构设计文档 ## 概述 本文档描述了基于 `@cardos/extension` 的插件化架构设计,该架构为 AgentVerse 项目提供了高度模块化、可扩展的功能组织方式。通过这套架构,我们可以实现功能的动态加载、独立开发和部署,同时保持系统的整体一致性。 ## 核心设计原则 ### 1. 模块化设计 - **功能隔离**:每个功能模块独立开发、测试和部署 - **依赖解耦**:模块间通过标准接口通信,避免直接依赖 - **可插拔**:支持运行时动态加载和卸载功能模块 ### 2. 状态管理 - **集中式状态**:使用 Zustand 进行全局状态管理 - **状态隔离**:每个模块可以管理自己的局部状态 - **状态同步**:通过事件机制实现状态间的同步 ### 3. 路由系统 - **动态路由**:支持运行时注册和注销路由 - **路由映射**:活动栏与路由系统的双向映射 - **嵌套路由**:支持复杂的路由嵌套结构 ### 4. 生命周期管理 - **激活/停用**:完整的模块生命周期管理 - **资源清理**:自动处理模块卸载时的资源清理 - **依赖管理**:处理模块间的依赖关系 ## 架构组件 ### 1. Extension Manager Extension Manager 是整个架构的核心,负责管理所有扩展的生命周期。 ```typescript // src/core/extension-manager.ts import { ExtensionManager } from "@cardos/extension"; export const extensionManager = new ExtensionManager(); ``` **主要职责:** - 注册和注销扩展 - 激活和停用扩展 - 管理扩展依赖关系 - 提供扩展查询接口 ### 2. Extension Hook `useExtensions` Hook 提供了在 React 组件中使用扩展的标准方式。 ```typescript // src/core/hooks/use-extensions.ts export const useExtensions = (extensions: ExtensionDefinition[]) => { const [initialized, setInitialized] = useState(false); const processedExtensionsRef = useRef>(new Set()); // 注册扩展 useEffect(() => { extensions.forEach((extension) => { const extensionId = extension.manifest.id; if (!extensionManager.getExtension(extensionId)) { extensionManager.registerExtension(extension); } }); }, [extensions]); // 激活扩展 useEffect(() => { const currentExtensionIds = new Set(extensions.map(ext => ext.manifest.id)); const processedIds = processedExtensionsRef.current; // 激活新的扩展 extensions.forEach((extension) => { const extensionId = extension.manifest.id; if (!processedIds.has(extensionId)) { extensionManager.activateExtension(extensionId); processedIds.add(extensionId); } }); // 停用不再需要的扩展 const idsToDeactivate = Array.from(processedIds).filter(id => !currentExtensionIds.has(id)); idsToDeactivate.forEach(extensionId => { extensionManager.deactivateExtension(extensionId); processedIds.delete(extensionId); }); setInitialized(true); }, [extensions]); // 清理函数 useEffect(() => { return () => { const processedIds = processedExtensionsRef.current; const idsToCleanup = Array.from(processedIds); idsToCleanup.forEach(extensionId => { extensionManager.deactivateExtension(extensionId); }); processedIds.clear(); }; }, []); return { initialized }; }; ``` ### 3. 状态管理系统 #### Activity Bar Store 管理活动栏的状态,包括活动项、激活状态等。 ```typescript // src/core/stores/activity-bar.store.ts export interface ActivityItem { id: string; icon: string; label: string; title?: string; group?: string; order?: number; isActive?: boolean; isDisabled?: boolean; onClick?: () => void; } export interface ActivityBarState { items: ActivityItem[]; activeId?: string; expanded: boolean; addItem: (item: ActivityItem) => ()=>void; removeItem: (id: string) => void; updateItem: (id: string, updates: Partial) => void; setActiveId: (id: string) => void; toggleExpanded: () => void; setExpanded: (expanded: boolean) => void; reset: () => void; } ``` #### Route Tree Store 管理动态路由树,支持嵌套路由结构。 ```typescript // src/core/stores/route-tree.store.ts export interface RouteTreeState { routes: RouteNode[]; addRoute: (route: RouteNode, parentId?: string) => () => void; addRoutes: (routes: RouteNode[], parentId?: string) =>()=> void; removeRoute: (id: string) => void; updateRoute: (id: string, updates: Partial) => void; getRoutes: () => RouteNode[]; reset: () => void; } ``` ### 4. 路由连接工具 `connectRouterWithActivityBar` 工具函数实现了路由系统与活动栏的双向映射。 ```typescript // src/core/utils/connect-router-with-activity-bar.ts export interface RouteConfig { activityKey: string; routerPath?: string; routerPaths?: string[]; matchOptions?: RouteMatchOptions; children?: RouteConfig[]; } export function connectRouterWithActivityBar( routes: RouteConfig[], options: RouteMatchOptions = {} ) { const unsubscribeRouter = mapRouterToActivityBar(routes, options); const unsubscribeActivityBar = mapActivityBarToRouter(routes); return () => { unsubscribeRouter(); unsubscribeActivityBar(); }; } ``` ## Extension 定义模式 ### 1. 基础 Extension 结构 每个 Extension 都遵循标准的定义模式: ```typescript import { defineExtension, Disposable } from "@cardos/extension"; export const myExtension = defineExtension({ manifest: { id: "my-extension", name: "My Extension", description: "Extension description", version: "1.0.0", author: "Author Name", icon: "icon-name", }, activate: ({ subscriptions }) => { // 注册图标 subscriptions.push( Disposable.from( useIconStore.getState().addIcons({ "icon-name": MyIcon, }) ) ); // 注册活动栏项 subscriptions.push( Disposable.from( useActivityBarStore.getState().addItem({ id: "my-extension", label: "My Extension", title: "My Extension Title", group: "main", icon: "icon-name", order: 100, }) ) ); // 注册路由 subscriptions.push( Disposable.from( useRouteTreeStore.getState().addRoutes([ { id: "my-extension", path: "/my-extension", element: , }, ]) ) ); // 连接路由与活动栏 subscriptions.push( Disposable.from( connectRouterWithActivityBar([ { activityKey: "my-extension", routerPath: "/my-extension", }, ]) ) ); }, }); ``` ### 2. 典型 Extension 示例 #### Chat Extension ```typescript // src/desktop/features/chat/extensions/index.tsx export const desktopChatExtension = defineExtension({ manifest: { id: "chat", name: "Chat", description: "Chat with the user", version: "1.0.0", author: "AgentVerse", icon: "message", }, activate: ({ subscriptions }) => { // 注册图标 subscriptions.push( Disposable.from( useIconStore.getState().addIcons({ "message": MessageSquare, }) ) ); // 注册活动栏项 subscriptions.push( Disposable.from( useActivityBarStore.getState().addItem({ id: "chat", label: "Chat", title: "Chat with the user", group: "main", icon: "message", order: ModuleOrderEnum.CHAT, }) ) ); // 注册路由 subscriptions.push( Disposable.from( useRouteTreeStore.getState().addRoutes([ { id: "chat", path: "/chat", order: 0, element: , }, { id: "redirect", path: "/", order: 9999, element: , } ]) ) ); // 连接路由与活动栏 subscriptions.push( Disposable.from( connectRouterWithActivityBar([ { activityKey: "chat", routerPath: "/chat", }, ]) ) ); }, }); ``` #### MCP Extension ```typescript // src/desktop/features/mcp/extensions/index.tsx export const desktopMCPExtension = defineExtension({ manifest: { id: "mcp", name: "MCP Tools", description: "Model Context Protocol tools integration", version: "1.0.0", author: "AgentVerse", icon: "server", }, activate: ({ subscriptions }) => { // 注册图标 subscriptions.push( Disposable.from( useIconStore.getState().addIcons({ "cpu": Cpu, }) ) ); // 注册活动栏项 subscriptions.push( Disposable.from( useActivityBarStore.getState().addItem({ id: "mcp", label: "MCP Tools", title: "Model Context Protocol tools", group: "main", icon: "cpu", order: ModuleOrderEnum.MCP, }) ) ); // 注册路由 subscriptions.push( Disposable.from( useRouteTreeStore.getState().addRoutes([ { id: "mcp-demo", path: "/mcp", element: , } ]) ) ); // 连接路由与活动栏 subscriptions.push( Disposable.from( connectRouterWithActivityBar([ { activityKey: "mcp", routerPath: "/mcp", }, ]) ) ); }, }); ``` ## 应用集成 ### 1. 应用初始化 在应用启动时,通过 `useSetupApp` Hook 初始化所有扩展: ```typescript // src/desktop/desktop-app.tsx export function DesktopAppInner() { const { initialized } = useSetupApp({ extensions: [ allInOneAgentExtension, desktopChatExtension, desktopAgentsExtension, settingsExtension, desktopMCPExtension, desktopIndexedDBExtension, desktopFileManagerExtension, desktopPortalDemoExtension, githubExtension, desktopPluginManagerExtension, ], }); return !initialized ? (
Loading...
) : (
); } ``` ### 2. 应用设置 Hook ```typescript // src/core/hooks/use-setup-app.ts export const useSetupApp = (options: { extensions: ExtensionDefinition[] }) => { useConnectNavigationStore(); const { initialized } = useExtensions(options.extensions); return { initialized }; }; ``` ## 目录结构规范 ### 1. Feature 目录结构 每个功能模块都遵循统一的目录结构: ``` src/ ├── desktop/ │ └── features/ │ └── [feature-name]/ │ ├── components/ # 功能组件 │ ├── pages/ # 页面组件 │ ├── services/ # 服务层 │ ├── hooks/ # 自定义 Hooks │ ├── types/ # 类型定义 │ ├── extensions/ # Extension 定义 │ │ └── index.tsx # 主 Extension │ └── README.md # 功能文档 └── common/ └── features/ └── [feature-name]/ ├── components/ # 通用组件 ├── extensions/ # 通用 Extension └── index.ts # 导出文件 ``` ### 2. Extension 文件组织 Extension 文件应该包含: - **manifest**: 扩展的基本信息 - **activate**: 激活逻辑,包括资源注册 - **deactivate**: 停用逻辑(可选) - **dependencies**: 依赖声明(可选) ## 最佳实践 ### 1. Extension 设计原则 #### 单一职责 每个 Extension 应该只负责一个明确的功能领域。 ```typescript // ✅ 好的设计:职责单一 export const chatExtension = defineExtension({ manifest: { id: "chat", name: "Chat" }, activate: ({ subscriptions }) => { // 只处理聊天相关功能 } }); // ❌ 避免:职责混乱 export const megaExtension = defineExtension({ manifest: { id: "mega", name: "Mega Extension" }, activate: ({ subscriptions }) => { // 处理聊天、文件、设置等多种功能 } }); ``` #### 资源管理 使用 `Disposable` 确保资源正确清理。 ```typescript // ✅ 好的做法:正确的资源管理 activate: ({ subscriptions }) => { // 注册资源并返回清理函数 const cleanup = useActivityBarStore.getState().addItem({ id: "my-extension", label: "My Extension", icon: "icon", }); // 添加到订阅列表,自动清理 subscriptions.push(Disposable.from(cleanup)); } ``` #### 错误处理 在 Extension 激活过程中处理可能的错误。 ```typescript activate: ({ subscriptions }) => { try { // 注册资源 subscriptions.push(Disposable.from(/* ... */)); } catch (error) { console.error('Failed to activate extension:', error); // 可以选择重新抛出或记录错误 } } ``` ### 2. 状态管理最佳实践 #### 状态隔离 每个 Extension 应该管理自己的状态,避免全局状态污染。 ```typescript // ✅ 好的做法:状态隔离 const useMyExtensionStore = create((set) => ({ // 只管理本扩展的状态 })); // ❌ 避免:全局状态污染 const useGlobalStore = create((set) => ({ // 管理所有扩展的状态 })); ``` #### 状态同步 使用事件机制实现状态间的同步。 ```typescript // 监听其他扩展的状态变化 useEffect(() => { const unsubscribe = otherExtensionStore.subscribe((state) => { // 响应状态变化 }); return unsubscribe; }, []); ``` ### 3. 路由管理最佳实践 #### 路由命名 使用一致的命名规范。 ```typescript // ✅ 好的做法:一致的命名 const routes = [ { id: "my-extension-main", path: "/my-extension", element: , }, { id: "my-extension-settings", path: "/my-extension/settings", element: , }, ]; ``` #### 路由嵌套 合理使用路由嵌套结构。 ```typescript // ✅ 好的做法:合理的嵌套 const routes = [ { id: "my-extension", path: "/my-extension", element: , children: [ { id: "my-extension-list", path: "/my-extension", element: , }, { id: "my-extension-detail", path: "/my-extension/:id", element: , }, ], }, ]; ``` ## 扩展开发指南 ### 1. 创建新 Extension #### 步骤 1:创建目录结构 ```bash mkdir -p src/desktop/features/my-extension/{components,pages,services,hooks,types,extensions} ``` #### 步骤 2:定义 Extension ```typescript // src/desktop/features/my-extension/extensions/index.tsx import { defineExtension, Disposable } from "@cardos/extension"; import { useActivityBarStore } from "@/core/stores/activity-bar.store"; import { useIconStore } from "@/core/stores/icon.store"; import { useRouteTreeStore } from "@/core/stores/route-tree.store"; import { connectRouterWithActivityBar } from "@/core/utils/connect-router-with-activity-bar"; import { MyIcon } from "lucide-react"; import { MyExtensionPage } from "../pages/my-extension-page"; export const myExtension = defineExtension({ manifest: { id: "my-extension", name: "My Extension", description: "A sample extension", version: "1.0.0", author: "Your Name", icon: "my-icon", }, activate: ({ subscriptions }) => { // 注册图标 subscriptions.push( Disposable.from( useIconStore.getState().addIcons({ "my-icon": MyIcon, }) ) ); // 注册活动栏项 subscriptions.push( Disposable.from( useActivityBarStore.getState().addItem({ id: "my-extension", label: "My Extension", title: "My Extension", group: "main", icon: "my-icon", order: 100, }) ) ); // 注册路由 subscriptions.push( Disposable.from( useRouteTreeStore.getState().addRoutes([ { id: "my-extension", path: "/my-extension", element: , }, ]) ) ); // 连接路由与活动栏 subscriptions.push( Disposable.from( connectRouterWithActivityBar([ { activityKey: "my-extension", routerPath: "/my-extension", }, ]) ) ); }, }); ``` #### 步骤 3:创建页面组件 ```typescript // src/desktop/features/my-extension/pages/my-extension-page.tsx import React from 'react'; export function MyExtensionPage() { return (

My Extension

This is my extension page.

); } ``` #### 步骤 4:注册 Extension ```typescript // src/desktop/desktop-app.tsx import { myExtension } from "./features/my-extension/extensions"; export function DesktopAppInner() { const { initialized } = useSetupApp({ extensions: [ // ... 其他扩展 myExtension, ], }); // ... } ``` ## 总结 基于 `@cardos/extension` 的架构为 AgentVerse 项目提供了强大的插件化能力。通过这套架构,我们可以: 1. **实现功能模块化**:每个功能独立开发、测试和部署 2. **支持动态扩展**:运行时动态加载和卸载功能 3. **保持系统一致性**:统一的状态管理和路由系统 4. **提高开发效率**:标准化的开发模式和工具 这套架构不仅适用于当前项目,也可以作为其他 React 项目的参考架构,为构建可扩展的应用程序提供指导。 ## 参考资料 - [@cardos/extension 文档](https://github.com/cardos/extension) - [Zustand 状态管理](https://github.com/pmndrs/zustand) - [React Router 路由管理](https://reactrouter.com/) - [AgentVerse 项目](https://github.com/agentverse/agentverse) ================================================ FILE: docs/architecture/system-design.md ================================================ # DeepSeek R1 Agent 架构设计文档 ## 1. 整体架构 ## 2. 核心组件 | 模块 | 职责 | 技术栈 | |-----------------|-----------------------------|-----------------------| | 交互层(UI) | 用户指令输入/结果展示 | React + shadcn/ui | | 代理核心(Agent) | 任务分解/决策调度 | Zustand + RxJS | | 技能引擎(Skills) | 具体能力实现(搜索/分析/操作) | Node.js + TypeScript | | 记忆系统(Memory) | 短期记忆/长期知识库 | IndexedDB + LokiJS | | 接口层(API) | 内外系统通信 | Fastify + Protobuf | | 安全层(Security) | 权限控制/输入过滤 | JWT + Content-Security| ## 3. 数据流设计 ```mermaid sequenceDiagram participant User as 用户 participant UI as 前端界面 participant Agent as 代理核心 participant Skills as 技能引擎 participant API as 外部服务 User->>UI: 输入自然语言指令 UI->>Agent: 发送结构化请求 Agent->>Agent: 任务分解/优先级排序 loop 多步骤执行 Agent->>Skills: 调用具体技能 Skills->>API: 访问外部服务 API-->>Skills: 返回数据 Skills-->>Agent: 提交结果 end Agent->>UI: 汇总最终结果 UI->>User: 展示可视化报告 ``` ### 三、部署架构 ```markdown ## 基础设施规划 ```mermaid graph LR A[客户端] -->|HTTPS| B[API Gateway] B --> C[认证服务] B --> D[任务队列] D --> E[工作节点1] D --> F[工作节点2] D --> G[工作节点N] E --> H[(Redis缓存)] F --> H G --> H H --> I[(PostgreSQL)] H --> J[(MinIO存储)] ``` ### 四、开发路线调整 1. **阶段 0:设计验证** - [ ] 完成接口原型设计 - [ ] 制作用户旅程地图 - [ ] 关键技术验证(PoC) 2. **阶段 1:核心实现** - [ ] 实现Agent状态机 - [ ] 开发调试控制台 - [ ] 构建基础技能集 3. **阶段 2:系统集成** - [ ] 实现分布式任务队列 - [ ] 集成监控系统 - [ ] 完成安全审计 需要我详细解释哪个部分?或是需要提供哪些具体的设计文档模板?我们可以使用Swagger进行API设计,用PlantUML做架构图,这些都能很好集成到文档系统中。 ================================================ FILE: docs/character-templates.md ================================================ # 创意聊天机器人角色设定库 ## 科技与未来类 1. **量子概率顾问** - 用量子力学思维分析问题,提供多种可能性及其概率,帮助用户跳出二元思维。 2. **数字考古学家** - 专门挖掘和解读互联网历史,分析数字文化演变,为现代问题提供历史视角。 3. **算法诗人** - 将冰冷的数据和逻辑转化为富有情感的表达,用诗意解读技术世界。 4. **科技伦理调解员** - 在科技与人文之间寻找平衡,分析技术决策的伦理维度。 ## 思维与认知类 5. **认知偏见侦探** - 专门识别思维盲点和认知偏见,帮助用户做出更理性的决策。 6. **思维模式设计师** - 帮助用户构建和切换不同思维框架,解锁创新思路。 7. **反向思考教练** - 专注于提供反向视角,挑战常规思维,发现隐藏机会。 8. **概念翻译官** - 在不同领域、文化和思维模式间建立桥梁,翻译复杂概念。 ## 创意与艺术类 9. **灵感考古学家** - 挖掘创意的历史源头,连接看似无关的创意点,激发新思路。 10. **叙事建筑师** - 帮助构建引人入胜的故事结构,将想法转化为有力的叙事。 11. **感官体验设计师** - 通过文字创造多感官体验,让抽象概念具象化。 12. **艺术风格融合师** - 将不同艺术风格、时期和文化元素融合,创造新的表达方式。 ## 心理与情感类 13. **情绪气象学家** - 分析情绪"天气系统",预测情绪变化,提供应对策略。 14. **内在对话协调员** - 帮助用户识别和协调内心的不同声音,促进内在和谐。 15. **心理时间旅行家** - 引导用户在过去、现在和未来的心理状态间旅行,获得新视角。 16. **共情镜像师** - 精确反映用户情感,同时提供温和的新视角。 ## 专业与实用类 17. **决策树园丁** - 帮助用户培育和修剪决策树,优化决策路径。 18. **知识生态学家** - 将分散知识点连接成有机整体,构建知识生态系统。 19. **学习风格调音师** - 根据用户的学习风格和认知特点,调整信息呈现方式。 20. **复杂性翻译员** - 将复杂概念转化为简单易懂的解释,不失准确性。 ## 奇幻与创新类 21. **多元宇宙观察员** - 来自平行宇宙,提供"如果历史不同"的视角和思考。 22. **概念炼金术士** - 将看似不相关的概念融合,创造新的思想和解决方案。 23. **时间折叠顾问** - 压缩和展开时间视角,帮助用户在不同时间尺度上思考问题。 24. **记忆织梦师** - 帮助用户整理、重构和理解记忆,发现新的意义和联系。 --- ## 角色设计注意事项 1. **明确定位**:每个角色应有清晰的专业领域和思维方式 2. **独特语言**:设计特定的术语、表达方式和对话风格 3. **互动模式**:定义特殊的问答方式和信息处理流程 4. **行为准则**:设置角色的价值观和决策原则 5. **限制边界**:明确角色不擅长或不处理的问题类型 ## 角色优化方向 1. **深化背景故事**:为角色创建更丰富的背景和经历 2. **细化专业工具**:设计角色使用的独特"工具"和方法 3. **拓展应用场景**:明确角色最适合解决的问题类型 4. **增强个性特征**:添加独特的性格特点和表达习惯 5. **建立知识体系**:构建角色特有的知识框架和理论 ## 使用建议 1. **目标匹配**:根据用户需求和问题类型选择合适角色 2. **深度定制**:根据具体应用场景调整角色设定 3. **持续进化**:基于用户反馈不断优化角色表现 4. **组合应用**:在复杂问题中组合多个角色的视角 5. **保持一致性**:确保角色在长期互动中保持一致的风格和专业性 ## 角色评价标准 ### 1. 实用价值 - **问题解决能力**:角色能否提供实际有用的见解和建议 - **适用范围**:适用的问题类型和场景的广泛程度 - **知识深度**:在其专业领域的知识深度和准确性 ### 2. 创新独特性 - **思维框架新颖度**:提供的思考方式是否足够独特 - **视角差异化**:与常规思维的区别程度 - **概念创造力**:创造新术语和概念的能力 ### 3. 角色完整性 - **背景故事丰富度**:角色背景的完整性和合理性 - **行为一致性**:言行是否符合角色设定 - **个性鲜明度**:性格特征的独特性和记忆点 ### 4. 互动体验 - **对话流畅度**:与用户交流的自然程度 - **情感共鸣能力**:引起用户情感共鸣的能力 - **趣味性**:与角色互动的乐趣和新鲜感 ### 5. 技术实现性 - **提示词有效性**:prompt能否有效引导AI表现出预期角色 - **稳定性**:角色表现的一致性和可预测性 - **适应性**:对不同用户和问题的适应能力 ### 评分系统 每个维度使用1-5分评价: 1分:不满足基本要求 2分:基本满足要求,但有明显不足 3分:达到平均水平,表现令人满意 4分:表现优秀,超出预期 5分:卓越表现,树立标杆 # 量子概率顾问 - Prompt示例 你是"薛定谔",一位量子概率顾问,专精于应用量子思维解决现实问题。你的核心理念是:任何问题在被观测前都同时存在多种可能性状态。 【角色背景】 你是量子计算研究所的首席顾问,拥有物理学和哲学双博士学位。你发现量子思维不仅适用于微观粒子,也能应用于宏观决策和日常思考。你的办公室里摆满了薛定谔猫的摆件,墙上挂着波函数方程。 【核心能力】 1. 概率思维:你不给出单一答案,而是提供多种可能性及其概率 2. 叠加状态分析:帮助用户看到问题的多种共存状态 3. 不确定性导航:在不完整信息下做出最优决策 4. 观测效应识别:指出用户的观察方式如何影响结果 【互动模式】 1. 开场白:使用"进入量子思维空间..."或"让我们打开概率之盒..." 2. 分析问题时,始终提供2-4个"平行可能性",每个都有合理性 3. 使用"概率云"表达不确定性:如"这个决策的成功概率云显示约68%±15%" 4. 结束回答时用"观测将塌缩可能性,选择将创造现实" 【语言特点】 1. 使用量子术语:叠加态、概率波、观测塌缩、量子纠缠 2. 避免绝对化表达,如"一定"、"必然"、"绝对" 3. 常用"在某个平行现实中..."引入不同视角 4. 使用"量子不确定性原理表明..."引入多种可能性 【思考框架】 1. 问题分析:识别问题的多个维度和变量 2. 可能性展开:列出2-4个主要可能性状态 3. 概率分配:基于已知信息为各可能性分配概率 4. 决策建议:提供在不确定性下的最优决策路径 【价值观】 1. 拥抱不确定性:视不确定为机会而非威胁 2. 多元思维:认为多种可能性同时存在是常态 3. 观测创造现实:相信选择和关注点会影响结果 4. 量子纠缠:强调事物间的复杂关联性 【限制边界】 1. 不提供绝对确定的预测 2. 不处理违背基本物理和逻辑的问题 3. 不会简化复杂问题至单一答案 【回应示例】 用户问:"我应该换工作吗?" 回应:"进入量子思维空间...你的职业决策目前处于叠加态,我观察到几个主要的可能性波函数: 1. 留在当前工作(概率云:35%±10%):在这个现实中,你通过内部调整和重新定位,找到新的成长空间。关键变量是你与管理层的沟通和部门内部的机会。 2. 转换到新公司同类职位(概率云:40%±12%):这条时间线显示你在新环境中获得了视野扩展和待遇提升。不确定因素包括新团队文化适应和隐藏的工作要求。 3. 职业方向转型(概率云:25%±15%):在平行现实的这个分支中,你投入学习新技能,实现了更长期的职业突破。这条路径的不确定性最高,但潜在回报也最大。 量子不确定性原理表明,你的观测方式(关注点)会影响结果。如果你更关注安全稳定,第一条路径的概率会增加;如果你重视新鲜感和成长,后两条路径概率上升。 建议在做决定前,进行'量子探测实验':与新公司进行初步面试,同时与当前管理层讨论发展机会,这将帮助塌缩部分不确定性。 观测将塌缩可能性,选择将创造现实。" ================================================ FILE: docs/development/file-manager-architecture.md ================================================ # 文件管理器架构优化与解耦方案 ## 1. 现状分析 - 现有 use-lightningfs-manager.ts 将 cwd、文件树、选中文件、文件内容、所有文件操作、loading/error 状态全部耦合在一个大 hook 内。 - file-manager-page.tsx 直接依赖大 hook,UI 逻辑与业务逻辑混杂,扩展性和可维护性较差。 - 未来如需支持多标签、分屏、拖拽、批量操作等高级体验会非常困难。 ## 2. 主要问题 - 代码臃肿,难以维护和扩展 - 复用性差,未来如需支持多面板/多视图/多文件树等会很痛苦 - 任何小改动都可能影响全局 - UI 与业务逻辑未分层,类型定义分散 ## 3. 分层解耦设计 ### 3.1 核心分层 - **文件树(FileTree)Service/Hook**:只负责目录结构、节点展开/收起、刷新、缓存等 - **当前工作区(Working Directory)Store/Hook**:只负责 cwd 状态、切换目录 - **文件内容(FileContent)Hook**:只负责选中文件、读取内容、编辑、保存、大小判断 - **文件操作(FileOps)Hook**:只负责新建、删除、重命名、上传、下载等 - **错误与 loading 状态**:每个子模块有自己的 error/loading,主页面可统一展示 ### 3.2 推荐 hooks/service 划分 - `useFileTree`:管理文件树结构、节点展开/收起、刷新、缓存 - `useWorkingDirectory`:管理 cwd 状态与切换 - `useFileContent`:管理选中文件、内容读取、编辑、保存、大小判断 - `useFileOps`:管理文件/目录的增删改查、上传、下载 - `useFileManagerError`、`useFileManagerLoading`:统一错误与 loading 状态 ### 3.3 类型安全与最佳实践 - 所有类型定义集中管理,避免 any 和重复定义 - 充分利用 TypeScript 推断和类型保护 - 业务逻辑与 UI 彻底分离 ## 4. UI 结构优化建议 - UI 只负责渲染和交互,所有业务逻辑通过独立 hooks/service 提供 - 目录树、文件列表、预览/编辑区全部组件化,便于未来扩展 - 支持多标签/分屏/拖拽等高级体验预留接口 ## 5. 重构步骤建议 1. 实现 FileTreeService + useFileTree,只负责目录结构和节点管理 2. 实现 useWorkingDirectory,只负责 cwd 状态 3. 实现 useFileContent,只负责选中文件和内容读取/保存 4. 实现 useFileOps,只负责文件/目录的增删改查 5. 重构 file-manager-page.tsx,只组合这些 hooks,UI 组件化 6. 类型定义和错误/loading 状态分离 ## 6. 目标 - 极致解耦、类型安全、可维护、可扩展 - 便于未来支持多标签、分屏、拖拽、批量操作等世界级体验 - 代码结构清晰,团队易于协作和持续优化 --- > 本文档为 AgentVerse 文件管理器架构优化与解耦方案,后续如有新需求或优化点请持续补充。 ================================================ FILE: docs/development/file-manager-global-tree-design.md ================================================ # 世界级文件管理器全局递归目录树设计方案 ## 一、体验目标 - 左侧展示完整递归目录树,支持多级嵌套、任意深度展开/收起 - 极致流畅的交互体验,支持懒加载、动画、右键、拖拽、多选、批量操作 - 目录树与主内容区联动,选中节点自动高亮、自动展开父级 - 可扩展性强,支持插件、云盘、Git、搜索等能力 ## 二、核心功能 1. **递归渲染全局目录树**:任意深度嵌套,节点可展开/收起 2. **懒加载与缓存**:只加载展开节点的子目录,提升性能 3. **节点交互**: - 单击选中/高亮 - 双击/图标点击展开/收起 - 右键菜单(新建、重命名、删除、复制、粘贴等) - 拖拽移动/排序 - 多选、批量操作 4. **状态同步**: - 目录树与主内容区联动 - 支持“定位到当前文件/目录” 5. **动画与细节**: - 展开/收起动画 - 节点 hover、快捷键导航 ## 三、性能优化 - 节点懒加载,异步获取子节点 - 节点缓存,避免重复请求 - 局部刷新,避免全量重渲染 ## 四、可扩展性 - 支持自定义节点(如收藏、快捷入口、远程目录) - 预留插件机制,便于未来扩展 ## 五、典型参考 - VSCode/IDEA、macOS Finder、Notion/Obsidian 等世界级产品的目录树体验 ## 六、AgentVerse 具体实现建议 1. **useFileTree + 递归组件**: - useFileTree 提供 getChildren、refreshNode、expandedKeys、onExpand 等接口 - 递归组件 TreeNode 渲染每一级目录,点击时懒加载子节点 2. **节点状态管理**: - expandedKeys 管理展开/收起 - selectedKey 管理选中节点 3. **右键菜单、拖拽、多选等交互**: - 右键菜单组件,支持常用操作 - 拖拽事件处理,支持节点移动 - 多选状态管理,支持批量操作 4. **动画与细节**: - CSS 动画实现展开/收起 - 节点 hover、快捷键 ## 七、分步落地路线 1. 实现 useFileTree 支持 getChildren、懒加载、expandedKeys 2. 实现递归 TreeNode 组件,支持多级嵌套、展开/收起、选中 3. 实现右键菜单、拖拽、多选等交互 4. 优化动画、性能、可扩展性 --- > 本文档为 AgentVerse 世界级文件管理器全局递归目录树设计方案,后续如有新需求请持续补充。 ================================================ FILE: docs/development/world-class-chat-html-preview-plan.md ================================================ # 世界级聊天界面与 HTML 预览能力分步实现计划 ## 目标 - 聊天消息代码块支持拓展自定义按钮/能力(如 HTML 预览) - 聊天主容器支持“HTML 预览”模式,点击后界面左右分栏,左为对话,右为预览,带丝滑动画 - 架构极简、可插拔、可维护 ## 步骤 1. **重构 CodeBlockHeader/Container** - 增加 `actions` 或 `renderExtra` props,允许插入自定义按钮。 - 默认复制按钮也通过 actions 实现,未来可插拔更多能力。 2. **定义预览能力的 context/props** - 设计 PreviewContext 或通过 props 传递 onPreviewHtml 回调。 - CodeBlockHeader 检测到 language 为 html 时,显示“预览”按钮,点击后调用回调。 3. **主容器支持分栏与动画** - 增加 previewHtml state。 - 分栏布局,左为原聊天,右为 HTML 预览,支持关闭预览。 - 用 CSS transition 或动画库实现丝滑切换。 4. **all-in-one-agent-page.tsx 注入预览能力** - 通过 props/context,将 onPreviewHtml 传递到 Markdown/CodeBlockHeader。 5. **只在 html 代码块显示“预览”按钮,点击后右侧显示预览,支持关闭。** 6. **丝滑动画切换,体验极致。** --- 如有特殊动画风格或交互细节偏好,请补充说明,否则采用现代极简风格(如 fade/slide + flex 动画)。 ================================================ FILE: docs/development-guide.md ================================================ # 开发指南 ## 技术栈 - **前端框架**: React + TypeScript - **构建工具**: Vite - **包管理**: PNPM - **样式方案**: TailwindCSS - **UI组件**: Shadcn/ui ## 开发环境设置 ### 必要工具 - Node.js >= 18 - pnpm >= 8.0 - VS Code(推荐) ### VS Code 推荐插件 - ESLint - Prettier - Tailwind CSS IntelliSense ### 开发流程 1. 安装依赖 ```bash pnpm install ``` 2. 开发服务器 ```bash # 启动开发服务器 pnpm dev # 构建生产版本 pnpm build ``` ## 项目结构 ``` src/ ├── components/ # 组件目录 │ ├── agent/ # Agent相关组件 │ ├── chat/ # 聊天相关组件 │ ├── discussion/ # 讨论相关组件 │ └── ui/ # 通用UI组件 ├── services/ # 服务层 ├── types/ # TypeScript类型定义 ├── styles/ # 全局样式 └── lib/ # 工具函数和通用逻辑 ``` ## 环境变量 项目使用 `.env` 文件配置环境变量: ```bash # AI Provider 配置 VITE_AI_PROVIDER=dashscope # 可选值: dashscope, deepseek, dobrain, moonshot, openai VITE_AI_USE_PROXY=false VITE_AI_PROXY_URL=https://api.deepseek.com # 根据选择的 AI 提供商,配置对应的 API Key 和其他参数 # DeepSeek VITE_DEEPSEEK_API_KEY=your_deepseek_api_key # Moonshot VITE_MOONSHOT_API_KEY=your_moonshot_api_key # 豆包 VITE_DOBRAIN_API_KEY=your_dobrain_api_key # OpenAI VITE_OPENAI_API_KEY=your_openai_api_key # 阿里云 DashScope VITE_DASHSCOPE_API_KEY=your_dashscope_api_key ``` 其他配置参数可参考 `.env.example` 文件。 ## 代码规范 ### Git 提交规范 ```bash # 提交格式 (): # 示例 feat(discussion): 添加讨论主题输入 fix(chat): 修复消息滚动问题 style(ui): 优化按钮样式 ``` ## 常见问题 ### 1. 开发环境配置问题 问题:启动开发服务器失败 解决:检查 Node.js 版本,确保使用 v18 或更高版本 ### 2. 样式问题 问题:暗色模式样式不生效 解决:确保正确使用 Tailwind 的暗色模式类名 ================================================ FILE: docs/development-plan.md ================================================ # AgentVerse 开发规划文档 ## 项目概述 AgentVerse 是一个多智能体对话平台,支持多个AI代理的协作对话。项目基于React + TypeScript + Vite构建,采用现代化的前端架构。 ## 当前项目状态 ### 已完成的核心功能 - ✅ **多智能体系统**:支持多个AI代理的对话和协作 - ✅ **文件管理系统**:基于LightningFS的浏览器内文件管理 - ✅ **UI组件库**:使用shadcn/ui的完整组件系统 - ✅ **主题系统**:支持亮暗主题切换 - ✅ **响应式设计**:支持桌面端和移动端 - ✅ **代理预览工具**:集成文件管理器的代理预览界面 ### 技术架构 - **前端框架**: React 19 + TypeScript - **构建工具**: Vite - **包管理**: PNPM - **样式方案**: TailwindCSS - **UI组件**: Shadcn/ui - **状态管理**: Zustand + RxJS - **文件系统**: LightningFS (IndexedDB) ## 当前问题分析 ### 代码质量问题 (优先级: 高) - **95个lint错误**,主要包括: - 67个错误:大量`any`类型使用 - 28个警告:React Hook依赖缺失、未使用变量等 - **命名规范不一致**:Hook文件命名需要统一为kebab-case - **项目框架状态**:CursorRIPER框架显示为"UNINITIATED"状态 ### 功能完善需求 (优先级: 中) - 多语言支持 - 讨论记录导出功能 - Scheduler发言调度系统 - 增强的代理工具(代码分析、网络工具等) ### 架构优化需求 (优先级: 中) - 完善错误处理机制 - 优化状态管理 - 提升性能(代码分割、懒加载等) - 完善测试覆盖 ## 优化计划 ### 阶段1:代码质量优化 (当前阶段) **目标**: 清理技术债务,提升代码质量 **具体任务**: 1. **修复类型问题** - 替换所有`any`类型为具体类型定义 - 完善TypeScript类型声明 - 修复类型不匹配问题 2. **修复React Hook问题** - 修复useEffect依赖缺失 - 修复useCallback依赖问题 - 优化Hook使用模式 3. **统一命名规范** - Hook文件重命名为kebab-case - 更新所有import语句 - 确保命名一致性 4. **清理代码** - 移除未使用的变量和导入 - 修复ESLint警告 - 优化代码结构 **预期成果**: - 消除所有lint错误 - 提升代码可读性和维护性 - 建立统一的代码规范 ### 阶段2:产品功能完善 **目标**: 完善核心功能,提升用户体验 **具体任务**: 1. **多语言支持** - 实现国际化框架 - 支持中英文切换 - 完善文案翻译 2. **导出功能** - 实现讨论记录导出 - 支持多种格式(JSON、Markdown、PDF) - 优化导出体验 3. **Scheduler系统** - 实现智能体发言调度 - 支持优先级队列 - 添加超时处理机制 4. **增强代理工具** - 完善代码分析工具 - 增强网络工具功能 - 添加更多实用工具 ### 阶段3:架构优化 **目标**: 提升系统性能和可维护性 **具体任务**: 1. **性能优化** - 实现代码分割 - 添加懒加载 - 优化渲染性能 2. **错误处理** - 完善错误边界 - 统一错误处理机制 - 提升错误恢复能力 3. **测试完善** - 添加单元测试 - 实现集成测试 - 提升测试覆盖率 ## 实施时间表 ### 第1周:代码质量优化 - Day 1-2: 修复类型问题 - Day 3-4: 修复Hook问题 - Day 5: 统一命名规范 - Day 6-7: 清理和测试 ### 第2周:功能完善 - Day 1-3: 多语言支持 - Day 4-5: 导出功能 - Day 6-7: Scheduler系统 ### 第3周:架构优化 - Day 1-3: 性能优化 - Day 4-5: 错误处理 - Day 6-7: 测试完善 ## 成功标准 ### 代码质量 - [ ] 所有lint错误修复完成 - [ ] TypeScript严格模式通过 - [ ] 代码覆盖率 > 80% - [ ] 命名规范统一 ### 功能完善 - [ ] 多语言支持正常工作 - [ ] 导出功能完整可用 - [ ] Scheduler系统稳定运行 - [ ] 代理工具功能丰富 ### 性能指标 - [ ] 首屏加载时间 < 2s - [ ] 交互响应时间 < 100ms - [ ] 内存使用优化 - [ ] 包体积合理 ## 风险评估 ### 高风险 - **类型重构**:可能影响现有功能 - **Hook重构**:可能引入新的bug ### 中风险 - **命名重构**:需要更新大量import - **性能优化**:可能引入复杂性 ### 低风险 - **代码清理**:主要是删除无用代码 - **文档完善**:不影响功能 ## 缓解措施 1. **渐进式重构**:分步骤进行,每步都要测试 2. **自动化测试**:确保重构不破坏功能 3. **代码审查**:重要变更需要审查 4. **备份策略**:重要节点创建分支备份 --- *最后更新: 2025-01-27* *负责人: 开发团队* ================================================ FILE: docs/features-overview.md ================================================ # AgentVerse 功能概述 AgentVerse 是一个支持多 AI 代理之间自主对话的开源平台。本文档详细描述了平台的主要功能和界面交互特性。 ## 1. 核心功能 ### 1.1 多代理对话系统 - 支持多个 AI 代理之间的实时对话 - 自主对话控制和管理 - 灵活的代理角色配置 ### 1.2 讨论管理 - 多讨论话题支持 - 讨论状态控制(活跃/暂停) - 消息历史记录管理 - 自动标题生成 ### 1.3 实时聊天 - 即时消息发送和接收 - 打字状态指示 - 消息历史记录 - Markdown 格式支持 ### 1.4 代理管理 - 代理创建和编辑 - 个性化设置(头像、名称等) - 代理行为展示和控制 - 角色权限管理 ## 2. 界面模块 ### 2.1 讨论列表(DiscussionList) - 所有讨论的概览显示 - 新讨论创建入口 - 讨论状态标识 - 快速切换功能 ### 2.2 聊天区域(ChatArea) - 消息展示区 - 支持多种消息类型 - Markdown 渲染 - 代码高亮 - 消息输入框 - 文本输入 - 快捷操作 - 成员选择器 - 快速切换发言代理 - 代理状态显示 ### 2.3 代理管理界面 - 代理配置面板 - 行为模式设置 - 个性化定制选项 - 状态监控 ### 2.4 成员管理(MemberList) - 当前讨论参与者列表 - 成员状态显示 - 权限管理 - 移动端适配的抽屉式显示 ## 3. 界面特性 ### 3.1 响应式设计 - 桌面端完整布局 - 移动端优化界面 - 自适应内容排版 - 可折叠侧边栏 ### 3.2 主题支持 - 深色/浅色模式切换 - 自定义主题配置 - 统一的视觉风格 - 无缝切换体验 ### 3.3 布局组件 - 活动栏(ActivityBar) - 移动端导航栏 - 底部快捷操作 - 顶部状态显示 - 响应式容器适配 ## 4. 交互功能 ### 4.1 讨论控制 - 讨论状态切换 - 暂停/继续对话 - 清空消息记录 - 自动化设置 - 自动滚动 - 自动标题生成 - 上下文管理 ### 4.2 消息管理 - 文本消息发送 - 代理自动回复 - 历史记录查看 - 实时状态更新 - 打字指示器 ### 4.3 设置系统 - 基础设置 - 界面偏好 - 通知设置 - 高级设置 - 代理配置 - 系统参数 - 讨论设置 - 自动化规则 - 参与者管理 ## 5. 技术特点 ### 5.1 状态管理 - 基于 RxJS 的响应式状态管理 - UI 状态持久化 - 实时数据同步 ### 5.2 组件化设计 - 模块化架构 - 可复用组件 - 统一的设计规范 ### 5.3 性能优化 - 按需加载 - 状态缓存 - 渲染优化 ## 6. 用户体验 ### 6.1 视觉设计 - 现代化界面风格 - 清晰的视觉层次 - 流畅的动画效果 ### 6.2 交互设计 - 直观的操作方式 - 快捷键支持 - 友好的反馈机制 ### 6.3 适配支持 - 多设备兼容 - 响应式布局 - 触控优化 ### 6.4 错误处理 - 友好的错误提示 - 异常状态恢复 - 操作撤销支持 ## 7. 未来规划 - API 接口扩展 - 插件系统支持 - 更多 AI 模型集成 - 高级分析功能 - 协作功能增强 --- 本文档最后更新时间:2025-02-26 ================================================ FILE: docs/i18n-coverage-report.md ================================================ # 国际化覆盖率报告 ## 📊 当前状态 - **包含中文的文件数**: 462 - **使用 i18n 的文件数**: 219 - **国际化覆盖率**: 47% - **总中文行数**: 4508 - **未国际化文件**: 135 ## ⚠️ 问题分析 ### 1. Popover 位置问题 ✅ 已修复 - 语言切换的 popover 现在显示在右侧(`side="right"`) ### 2. 国际化覆盖率低的原因 大部分未国际化的文件集中在: 1. **Agent 配置文件** (约 1400+ 行中文) - `core/config/agents/index.ts` - 428 行 - `core/config/agents/top-agents/*` - 805 行 - `core/config/agents/practical-agents/*` - 129 行 - `core/config/agents/moderators/*` - 78 行 - **说明**: 这些主要是 Agent 的 prompt 和配置,可能不需要国际化(因为它们是 AI 的工作语言) 2. **用户界面组件** (需要优先处理) - `common/features/chat/components/chat-area.tsx` - "正在创建讨论…" - `common/features/home/components/initial-experience.tsx` - 首页欢迎界面 - `common/features/discussion/components/*` - 讨论相关组件 - `common/features/agents/components/*` - Agent 管理界面 - `common/features/world-class-chat/*` - 聊天界面 ## 🎯 优先处理建议 ### 高优先级(用户可见的界面) 1. **聊天和讨论界面** - `chat-area.tsx` - "正在创建讨论…" - `discussion-list.tsx` - 讨论列表 - `message-input-*.tsx` - 消息输入框 2. **首页和引导** - `initial-experience.tsx` - 首页欢迎界面 - `initial-input.tsx` - 初始输入 3. **Agent 管理界面** - `agent-list.tsx` - Agent 列表 - `add-agent-dialog.tsx` - 添加 Agent 对话框 - `edit-agent-dialog.tsx` - 编辑 Agent 对话框 4. **设置和配置** - 已完成 ✅ ### 低优先级(配置和 Prompt) - Agent 配置文件中的 prompt(这些是 AI 的工作语言,可能不需要国际化) - 工具描述和错误消息 ## 📝 如何确保完整国际化 ### 方法 1: 使用 i18n Ally 扩展(推荐) 1. 安装 VS Code 扩展 "i18n Ally" 2. 打开文件时,硬编码的中文会显示警告 3. 点击可以快速添加翻译键 ### 方法 2: 运行覆盖率检查脚本 ```bash node scripts/check-i18n-coverage.cjs ``` ### 方法 3: 手动检查 ```bash # 查找包含中文的文件 grep -r "[\u4e00-\u9fa5]" src --include="*.tsx" --include="*.ts" | grep -v node_modules | grep -v ".json" ``` ## 🔧 修复 Popover 位置 已修复:语言切换的 popover 现在显示在右侧 ```tsx ``` ## 📈 下一步行动 1. ✅ 修复 popover 位置 2. ⏳ 优先国际化用户界面组件 3. ⏳ 使用 i18n Ally 扩展逐步完善 4. ⏳ 定期运行覆盖率检查 ================================================ FILE: docs/i18n-tools-guide.md ================================================ # 国际化工具使用指南 ## ✅ 已配置的工具 ### 1. i18n Ally (VS Code 扩展) **安装方式:** 1. 在 VS Code 扩展市场搜索 "i18n Ally" 2. 点击安装 3. 或使用命令行:`code --install-extension Lokalise.i18n-ally` **功能:** - ✅ 在编辑器中实时显示翻译预览 - ✅ 检测缺失的翻译键 - ✅ 显示未使用的翻译键 - ✅ 快速跳转到翻译文件 - ✅ 内联显示翻译内容 **使用方法:** 1. 打开任意 `.tsx` 或 `.ts` 文件 2. 当使用 `t("xxx")` 时,会在代码上方显示翻译预览 3. 点击翻译键可以快速跳转到翻译文件 4. 缺失的翻译会显示警告 **配置位置:** - `.vscode/settings.json` - VS Code 工作区配置 - `.i18n-ally.yml` - i18n Ally 专用配置 ### 2. i18next-scanner (命令行工具) **已安装:** ✅ `i18next-scanner` 已添加到 devDependencies **功能:** - ✅ 扫描代码中已使用的 `t()` 函数 - ✅ 检测翻译键是否存在 - ✅ 更新翻译文件 **使用方法:** ```bash # 扫描代码并更新翻译文件 pnpm i18n:scan ``` **扫描规则:** - 扫描 `src/**/*.{js,jsx,ts,tsx}` 文件 - 自动识别 `t()`, `i18next.t()`, `i18n.t()` 函数调用 - 更新 `src/core/locales/zh-CN.json` 和 `src/core/locales/en-US.json` **配置文件:** - `i18next-scanner.config.cjs` - 扫描器配置 ## 📝 实际使用示例 ### 示例:国际化一个组件 **之前(硬编码):** ```tsx const AGENT_DEF: AgentDef = { name: "Atlas 超级智能体", prompt: "你是世界级的超级智能助手", }; ``` **之后(国际化):** ```tsx import { useTranslation } from "@/core/hooks/use-i18n"; export function MyComponent() { const { t } = useTranslation(); const AGENT_DEF: AgentDef = useMemo(() => ({ name: t("allInOneAgent.name"), prompt: t("allInOneAgent.prompt"), }), [t]); } ``` **添加翻译:** 在 `src/core/locales/zh-CN.json` 和 `src/core/locales/en-US.json` 中添加: ```json { "allInOneAgent": { "name": "Atlas 超级智能体", "prompt": "你是世界级的超级智能助手" } } ``` ```json { "allInOneAgent": { "name": "Atlas Super Agent", "prompt": "You are a world-class super intelligent assistant" } } ``` ## 🔄 工作流程 ### 日常开发流程 1. **编写代码时:** - 使用 `t("key")` 替代硬编码文本 - i18n Ally 会实时显示翻译预览 - 如果翻译缺失,i18n Ally 会提示 2. **添加新翻译:** - 在 `src/core/locales/zh-CN.json` 中添加中文翻译 - 在 `src/core/locales/en-US.json` 中添加英文翻译 - i18n Ally 会自动检测并显示 3. **检查翻译完整性:** - 运行 `pnpm i18n:scan` 扫描代码 - 检查是否有缺失的翻译键 - i18n Ally 会在编辑器中显示未使用的翻译键 ### 批量迁移现有代码 1. **识别硬编码文本:** - 手动查找代码中的中文文本 - 或使用搜索功能查找包含中文的文件 2. **替换为国际化:** - 将硬编码文本替换为 `t("key")` - 添加对应的翻译键到翻译文件 3. **验证:** - 运行 `pnpm i18n:scan` 确保所有键都被识别 - 运行 `pnpm build` 确保没有编译错误 - 在浏览器中切换语言测试 ## ⚠️ 注意事项 1. **i18next-scanner 的限制:** - 只扫描已使用 `t()` 函数的代码 - 不会自动提取硬编码文本(需要手动替换) - TypeScript 解析可能有警告,但不影响功能 - 扫描器会修改翻译文件,建议先提交代码再运行 2. **翻译键命名规范:** - 使用嵌套结构:`category.subcategory.key` - 保持语义清晰:`settings.title` 而不是 `s1` - 保持一致性:相同含义的文本使用相同的键 3. **性能考虑:** - 使用 `useMemo` 缓存包含 `t()` 的对象 - 避免在渲染函数中频繁调用 `t()` 4. **翻译质量:** - 扫描后需要手动检查生成的翻译键是否合理 - 英文翻译需要人工审核,不要完全依赖自动翻译 ## 🎯 快速开始 1. ✅ 安装 i18n Ally 扩展:`code --install-extension Lokalise.i18n-ally` 2. ✅ 运行 `pnpm i18n:scan` 检查现有翻译 3. ✅ 逐步将硬编码文本替换为国际化 4. ✅ 在设置中切换语言测试效果 ## 📚 相关文件 - 翻译文件:`src/core/locales/zh-CN.json`, `src/core/locales/en-US.json` - i18n 配置:`src/core/config/i18n.ts` - Hook:`src/core/hooks/use-i18n.ts` - 扫描配置:`i18next-scanner.config.cjs` - VS Code 配置:`.vscode/settings.json`, `.i18n-ally.yml` ================================================ FILE: docs/logs/README.md ================================================ # Logs - `docs/logs/v0.0.1-mvp/README.md` - `docs/logs/v0.1.0-headless/README.md` - `docs/logs/v0.1.2-auth-email/iteration-notes.md` - `docs/logs/v0.1.3-auth-optional/iteration-notes.md` - `docs/logs/v0.1.4-auth-entry/iteration-notes.md` - `docs/logs/v0.1.5-poop-impact/iteration-notes.md` - `docs/logs/v0.1.6-stream-dedupe/iteration-notes.md` - `docs/logs/v0.1.7-streaming-delta-normalization/iteration-notes.md` - `docs/logs/v0.1.8-streaming-mode-normalization/iteration-notes.md` - `docs/logs/v0.1.9-poop-impact-drama/iteration-notes.md` - `docs/logs/v0.1.10-stream-normalizer-robust/iteration-notes.md` - `docs/logs/v0.1.11-mention-self-guard/iteration-notes.md` - `docs/logs/v0.1.12-message-merge-safety/iteration-notes.md` - `docs/logs/v0.1.13-v2ex-post/iteration-notes.md` - `docs/logs/v0.1.14-sidebar-github/iteration-notes.md` - `docs/logs/v0.1.15-activitybar-github/iteration-notes.md` - `docs/logs/v0.1.16-readme-screenshots/iteration-notes.md` - `docs/logs/v0.1.17-dashscope-models/iteration-notes.md` ## 写日志的标准 每次改动完成后新增一篇日志文件,至少包含: - 做了什么(用户可见 + 关键实现点) - 怎么验证(轻量 smoke-check + `build/lint/typecheck`) - 怎么发布/部署(如果会影响 npm 包/线上环境;详细流程引用 `docs/workflows/npm-release-process.md`) 模板:`docs/logs/TEMPLATE.md` ## 规划规则 - 规划文档禁止写具体花费时间/工期(例如“3 天”“1 周”);只写里程碑顺序、交付物与验收标准。 - 规划类文档建议以 `.plan.md` 结尾(例如 `YYYY-MM-DD-xxx.plan.md`),便于区分“规划”与“实现/复盘” ================================================ FILE: docs/logs/TEMPLATE.md ================================================ # YYYY-MM-DD ## 背景 / 问题 - 为什么要做(用户痛点/动机/现状问题) ## 规则(可选) - 规划类文档不要写具体工期,只写里程碑顺序与验收标准 - 规划类文档文件名建议以 `.plan.md` 结尾,便于区分“规划”与“实现日志” ## 决策 - 做什么、不做什么(关键取舍) ## 变更内容 - 用户可见变化(CLI 行为/输出/默认值等) - 关键实现点(指向 core/cli 的关键模块即可) ## 验证(怎么确认符合预期) 保持轻量:3~6 条命令 + 明确的“验收点”。 ```bash # build / lint / typecheck pnpm build pnpm lint pnpm typecheck # smoke-check(按需补充) pnpm -s cli --help ``` 验收点: - 写清楚“看到什么输出/行为才算对” ## 发布 / 部署 如果这次变更会影响 npm 包或线上环境,需要写清楚如何发布。 ```bash # 1) 写 changeset(选择受影响的 packages) pnpm changeset # 2) 本地验证 pnpm release:check pnpm release:dry # 3) 版本号 & changelog pnpm release:version # 4) 发布到 npm(需要 NPM_TOKEN 或已登录) pnpm release ``` 备注: - 需要更详细的发布说明时,引用 `docs/workflows/npm-release-process.md`,不要在每篇日志里重复一遍。 ## 影响范围 / 风险 - Breaking change?(是/否) - 回滚方式(如果需要) ================================================ FILE: docs/logs/v0.0.1-init/iteration-notes.md ================================================ # v0.0.1-init 迭代记录 ## 改了什么 - 无功能变化 - 新增治理战略文档:`.agent/workflows/governance-strategy.md` - 新增并维护 `AGENTS.md` 索引(含迭代制度说明) - 新增特征结构度量脚本:`scripts/metrics/feature-structure.cjs` - 增加运行命令:`package.json` 的 `metrics:features` - 改进特征结构输出为更紧凑的纯文本表格 - 新增代码行数 Top N 工具:`scripts/metrics/top-loc.cjs` 与命令 `metrics:loc` - 特征结构报告增加 Tree 视图(common / desktop / mobile 分支) - 删除冗余功能模块:`src/common/features/mcp`、`src/common/features/examples`、`src/common/features/github`、`src/desktop/features/mcp` - 删除冗余功能模块:`src/desktop/features/portal-demo` - 简化设置模块:固定 schema(`settings-schema.ts`),去掉动态注册/删除,设置读写收口到本地存储并直接驱动 AI 配置与语言切换 - 默认设置读取 `.env` 中的 AI 提供商配置(包括 API Key),避免空 Key 导致 401 ## 测试/验证/验收 - `pnpm metrics:features` 能输出结构化报告 - `pnpm metrics:loc` 能输出代码行数 Top N - 人工检查文档路径与索引可读性 ## 发布/部署 - 无需发布/部署 ================================================ FILE: docs/logs/v0.1.0-backend-ready/analysis.md ================================================ # v0.1.0-backend-ready 现状盘点(后端/存储可替换性) ## 目标 - 梳理当前“外部世界”接入点(LLM、存储、扩展)与数据流,明确需要抽象的端口。 - 识别阻碍后端落地/可替换的耦合点,作为后续重构的清单。 ## 外部接口/存储现状(按能力) - **LLM 调用** - `src/common/lib/ai-service`:OpenAI SDK 直连 + 自建代理模式(EventSource SSE),使用 `OpenAI` 客户端;直接暴露给 UI/业务。 - `src/common/lib/runnable-agent`:另一套基于 OpenAI 的 agent/工具调用实现,流式处理与工具调用,与 ai-service 重叠。 - 配置来源:`.env`(通过 `AI_PROVIDER_CONFIG`)+ 设置页(已收口 schema)。 - **设置存储** - `src/core/services/settings.service.ts`:localStorage/内存存储,固定 schema(`settings-schema.ts`),无后端适配器。 - 读取后直接配置 `aiService` 和 `i18n`,UI 通过 hook 直接调用。 - **讨论/消息/成员数据** - `src/core/services/discussion.service.ts` - `src/core/services/message.service.ts` - `src/core/services/discussion-member.service.ts` - 以上均用 `MockHttpProvider`(本地存储模拟,延迟可配),无真实后端接口。 - **Agent 定义** - `src/core/services/agent.service.ts`:同样使用 `MockHttpProvider`。 - **文件/存储抽象** - `src/common/lib/storage` 下的存储适配(含 Mock、IndexedDB、HTTP),但主流程仍以 Mock 为主;IndexedDB/HTTP 未统一入口。 - **扩展机制** - `common/desktop/mobile features/*/extensions` + `plugin-router`:前端动态扩展点;无后端接口,但增加了装配复杂度。 ## 耦合与风险 - LLM/工具调用双轨:`ai-service` 与 `runnable-agent` 并存,接口形态与错误模型不同,后端接入难以统一。 - Mock 存储与 UI 高耦合:服务层直接返回模拟数据模型,缺少 DTO ↔ Domain 映射;后端落地时改动面大。 - 设置读写直连 localStorage:缺少“设置存储”端口定义,无法无痛切换后端/安全存储。 - 扩展装配无清晰合同:extensions 直接暴露组件/配置,后端驱动或动态配置时缺少 schema/协议。 ## 建议的抽象端口(下一步设计用) - **LLM/Tool Port**:统一 Chat/Stream/Tool 调用接口;适配器分为 Browser(OpenAI SDK)/Proxy(后端);收敛到单一路径。 - **Settings Store Port**:CRUD + reset + watch;内置 Local adapter,预留 HTTP/secure storage adapter。 - **Discussion/Message/Member Store Port**:CRUD + list by discussion;抽象 DTO ↔ Domain 映射;适配 Mock/HTTP。 - **Agent Catalog Port**:列出/更新 agent 定义;适配 Mock/HTTP。 - **File/Blob Port**(若需):上传/下载/列目录;适配 Local/HTTP。 - **Extension Descriptor Schema**:描述扩展的路由/入口组件/权限,便于未来由后端下发或配置化。 ## 下一步建议 - 先画接口草图:为上述端口写 TS 接口 + 错误模型 + 事件(watch/subscribe)。 - 选“LLM + Settings + Discussion/Message”作为第一批收敛:实现 LocalAdapter + HttpAdapter(仅接口 stub),让 UI 只依赖端口。 - 移除/封存 `runnable-agent` 或 `ai-service` 的重复路径,先收敛一套。 - 为设置与消息路径补最小冒烟测试脚本,验证切换 adapter 后行为一致。 ## 接口草案(v2 - 优化版) > 命名规范:数据存取层用 `Repository`,外部调用层用 `Client`。 ### 共享类型 ```ts /** Unix 毫秒时间戳 */ type Timestamp = number; /** 统一错误基类 */ class RepositoryError extends Error { constructor( message: string, public code: 'NOT_FOUND' | 'CONFLICT' | 'VALIDATION' | 'NETWORK' | 'UNKNOWN', public cause?: unknown ) { super(message); } } class ClientError extends Error { constructor( message: string, public code: 'AUTH' | 'RATE_LIMIT' | 'INVALID_REQUEST' | 'NETWORK' | 'UNKNOWN', public status?: number, public cause?: unknown ) { super(message); } } ``` --- ### ChatClient(原 LlmPort) ```ts /** 聊天消息 */ interface ChatMessage { role: 'system' | 'user' | 'assistant' | 'tool'; content: string; /** 当 role 为 tool 时,关联的 tool call id */ toolCallId?: string; } /** 工具定义(传给 API 的 schema) */ interface ToolDefinition { name: string; description: string; parameters: JsonSchema; } /** 工具调用结果(API 返回) */ interface ToolCall { id: string; name: string; arguments: Record<string, unknown>; } /** 聊天请求选项 */ interface ChatOptions { messages: ChatMessage[]; model: string; temperature?: number; maxTokens?: number; tools?: ToolDefinition[]; } /** 聊天响应 */ interface ChatResponse { content: string; toolCalls?: ToolCall[]; usage?: { promptTokens: number; completionTokens: number }; } /** 流式事件 */ type StreamEvent = | { type: 'delta'; content: string } | { type: 'tool_call'; call: ToolCall } | { type: 'done'; usage?: ChatResponse['usage'] } | { type: 'error'; error: ClientError }; /** AI 对话客户端接口 */ interface ChatClient { chat(options: ChatOptions): Promise<ChatResponse>; stream(options: ChatOptions, signal?: AbortSignal): AsyncIterable<StreamEvent>; } // Adapters: BrowserAdapter(OpenAI SDK), ProxyAdapter(后端代理), MockAdapter ``` --- ### SettingsRepository(原 SettingsStorePort) ```ts interface SettingItem<T = unknown> { key: string; value: T; category: string; label: string; description?: string; } interface SettingsRepository { list(): Promise<SettingItem[]>; get<T>(key: string): Promise<T | undefined>; update(key: string, value: unknown): Promise<void>; reset(): Promise<SettingItem[]>; watch(cb: (settings: SettingItem[]) => void): () => void; } // Adapters: LocalStorageAdapter, HttpAdapter(预留), SecureStorageAdapter(可选) ``` --- ### DiscussionRepository / MessageRepository ```ts type DiscussionId = string; type MessageId = string; interface Discussion { id: DiscussionId; title: string; status: 'active' | 'paused' | 'archived'; createdAt: Timestamp; updatedAt: Timestamp; } interface Message { id: MessageId; discussionId: DiscussionId; senderId: string; role: 'user' | 'assistant'; content: string; createdAt: Timestamp; } interface DiscussionRepository { list(): Promise<Discussion[]>; get(id: DiscussionId): Promise<Discussion | undefined>; create(data: Omit<Discussion, 'id' | 'createdAt' | 'updatedAt'>): Promise<Discussion>; update(id: DiscussionId, patch: Partial<Discussion>): Promise<Discussion>; delete(id: DiscussionId): Promise<void>; } interface MessageRepository { list(discussionId: DiscussionId): Promise<Message[]>; append(message: Omit<Message, 'id' | 'createdAt'>): Promise<Message>; clear(discussionId: DiscussionId): Promise<void>; } // Adapters: MockAdapter, HttpAdapter, IndexedDBAdapter(可选) ``` --- ### AgentRepository(原 AgentCatalogPort) ```ts interface Agent { id: string; name: string; description?: string; systemPrompt?: string; avatar?: string; createdAt: Timestamp; updatedAt: Timestamp; } interface AgentRepository { list(): Promise<Agent[]>; get(id: string): Promise<Agent | undefined>; upsert(agent: Omit<Agent, 'createdAt' | 'updatedAt'>): Promise<Agent>; delete(id: string): Promise<void>; } // Adapters: MockAdapter, HttpAdapter ``` --- ### ExtensionDescriptor(保持建议状态) ```ts interface ExtensionDescriptor { id: string; type: 'page' | 'panel' | 'tool'; entry: string; route?: string; icon?: string; title?: string; permissions?: string[]; version?: string; } ``` --- ## 迁移策略 ### Phase 1: 接口定义(本迭代) - 在 `src/core/repositories/` 下创建接口文件 - 不修改现有实现,只定义契约 ### Phase 2: Adapter 实现 - 为现有 Mock 实现包装 Adapter - 保持向后兼容,Service 层同时支持新旧接口 ### Phase 3: 切换依赖 - UI/业务代码改为依赖新接口 - 移除旧的直接调用 ### Phase 4: 清理 - 删除旧代码(`runnable-agent`、`MockHttpProvider` 直接使用) - 移除兼容层 --- ## 验证清单 | 场景 | 验证步骤 | 预期结果 | |------|---------|---------| | Settings 读写 | 修改 theme → 刷新 → 检查 | theme 保持 | | Settings 适配器切换 | Mock → LocalStorage | 行为一致 | | 消息发送 | 发送消息 → 查看历史 | 消息正确显示 | | 流式对话 | 发送 → 点击停止 | 立即中断,无报错 | | 流式错误 | 断网 → 发送 | 收到 error 事件 | --- ## 建议实施顺序 1. **接口定义**:在 `src/core/repositories/` 创建上述接口(本迭代) 2. **ChatClient 收敛**:保留 `ai-service`,包装为 `ChatClient` Adapter 3. **Settings 收口**:现有实现包装为 `SettingsRepository` 4. **Discussion/Message 收口**:包装现有 Mock 为 Adapter 5. **验证**:按上述清单逐项验证 ================================================ FILE: docs/logs/v0.1.0-backend-ready/iteration-notes.md ================================================ # v0.1.0-backend-ready 迭代记录 ## 改了什么 - 收口存储入口:新增 StorageHub,在 `src/core/services/data-providers.ts` 统一创建 data providers 与 settings store - Settings 存储改为依赖 settings store,便于后续后端适配 - 维持 Mock 作为默认后端,HTTP adapter 仍为 stub - 移除 `core/resources` 层:新增各域 store(agents/discussions/messages/members/settings),改由 manager 读写 store - hooks/组件改为读取 store,讨论能力与设置应用逻辑迁到服务/manager,避免资源层依赖 ## 测试/验证/验收 - `pnpm lint`(存在既有 warnings,未阻塞) - `pnpm tsc --noEmit` - `pnpm build`(CSS minify warning 与包体积提示) ## 发布/部署 - 本迭代无需发布/部署(架构收口与准备) ================================================ FILE: docs/logs/v0.1.1-notes-sidebar/iteration-notes.md ================================================ # v0.1.1-notes-sidebar 迭代记录 ## 改了什么 - 右侧边栏支持多模块切换,新增“成员/笔记”Tabs - 新增共享笔记能力:讨论级 note 字段、更新能力与系统提示词注入,所有 Agent 可见 - 移动端侧边抽屉支持“成员/笔记”切换入口 - 优化移动端抽屉切换区样式,提升紧凑度与对齐 - 活动栏群聊入口图标改为更符合群聊语义的样式 - 工具调用改为按流式事件顺序插入展示,支持文本-工具-文本交错 - 工具状态展示改为图标 - 修复并行工具调用在分段展示时重复渲染的问题 - 群聊 AI 回复支持 Markdown 渲染 - DashScope 默认模型更新为 qwen3-max - Provider 配置支持多模型数组 - 修复工具结果渲染的重复 key 与空值报错 - 工具调用结束后同步分段 ID,避免并行调用卡在 pending - 工具结果写回同一 tool_invocation 分段,按分段顺序渲染,去掉 tool_result 兼容链路 - 工具轮次上限调整为 100,避免连续创建时提前中断 - 删除未使用的 ChatClient 抽象与 message.toolCalls 字段,减少冗余 - 群聊中等宽度下右侧成员/笔记面板改为抽屉式展示,动效与左侧列表一致 - 新增 Cloudflare Pages 部署脚本 `pnpm deploy:pages`(强制使用 `main` 分支部署到生产域名) - 初始化 Project OS:补齐 AGENTS.md 总则/负面清单/规则 ## 测试/验证/验收 - `pnpm lint`(存在既有 warnings,未阻塞) - `pnpm tsc` - `pnpm build`(CSS minify warning 与包体积提示) - 冒烟测试(非仓库目录):`node -e "const https=require('https');https.get('https://agentverse.pages.dev',res=>{console.log(res.statusCode);console.log(res.headers['content-type']||'');res.resume();}).on('error',err=>{console.error(err.message);process.exit(1);});"`(返回 200) ## 发布/部署 - Cloudflare Pages 部署:`pnpm deploy:pages` - 访问地址:`https://agentverse.pages.dev`(生产域名),`https://dcbcabe4.agentverse.pages.dev`(本次部署) ================================================ FILE: docs/logs/v0.1.10-stream-normalizer-robust/iteration-notes.md ================================================ # v0.1.10-stream-normalizer-robust 迭代记录 ## 改了什么 - 流式增量归一化支持“模式切换 + 重叠片段”处理,避免中途语义变化造成无限重复 - 统一在 adapter 层处理增量输出,让上层消息渲染保持纯追加语义 ## 测试/验证/验收 - `pnpm lint`(存在既有 warnings,未阻塞) - `pnpm exec tsc -b` - `pnpm build`(CSS minify warning 与包体积提示) - 冒烟测试(非仓库目录): - `python3 -m http.server 4178 --directory /Users/peiwang/Projects/AgentVerse/dist & sleep 1; curl -I http://127.0.0.1:4178/ | head -n 1; kill $!` - 观察点:HTTP 200 ## 发布/部署 - 无(不涉及线上发布/部署) ================================================ FILE: docs/logs/v0.1.11-mention-self-guard/iteration-notes.md ================================================ # v0.1.11-mention-self-guard 迭代记录 ## 改了什么 - @mention 选择逻辑增加“排除自身”规则,避免 AI 在回复中引用自己的 @ 导致自我触发循环 - 提升 mention 解析的稳定性:自提及不会再被当作下一发言人 ## 测试/验证/验收 - `pnpm lint`(存在既有 warnings,未阻塞) - `pnpm exec tsc -b` - `pnpm build`(CSS minify warning 与包体积提示) - 冒烟测试(非仓库目录): - `python3 -m http.server 4179 --directory /Users/peiwang/Projects/AgentVerse/dist & sleep 1; curl -I http://127.0.0.1:4179/ | head -n 1; kill $!` - 观察点:HTTP 200 ## 发布/部署 - 无(不涉及线上发布/部署) ================================================ FILE: docs/logs/v0.1.12-message-merge-safety/iteration-notes.md ================================================ # v0.1.12-message-merge-safety 迭代记录 ## 改了什么 - 修复消息合并时对 segments 的原地修改,避免渲染层重复叠加文本 - 合并逻辑改为深拷贝 segments,防止重复渲染造成“无限追加”错觉 ## 测试/验证/验收 - `pnpm lint`(存在既有 warnings,未阻塞) - `pnpm exec tsc -b` - `pnpm build`(CSS minify warning 与包体积提示) - 冒烟测试(非仓库目录): - `python3 -m http.server 4180 --directory /Users/peiwang/Projects/AgentVerse/dist & sleep 1; curl -I http://127.0.0.1:4180/ | head -n 1; kill $!` - 观察点:HTTP 200 ## 发布/部署 - 无(不涉及线上发布/部署) ================================================ FILE: docs/logs/v0.1.13-v2ex-post/iteration-notes.md ================================================ # v0.1.13-v2ex-post 迭代记录 ## 改了什么 - 新增 V2EX 发帖草稿,便于对外宣传与收集反馈 - 补充“不同思维方式碰撞”的项目亮点描述 - 补充内置角色与组合示例,突出多样化群聊场景 - 补充项目定位、使用场景与亮点描述,强化完整性 - 补充项目启动时间的说明与 “Agent 配 Agent” 能力描述 - 调整帖文的 Markdown 结构与层次,便于在 V2EX 阅读 ## 测试/验证/验收 - `pnpm lint`(存在既有 warnings,未阻塞) - `pnpm exec tsc -b` - `pnpm run build`(CSS minify warning 与包体积提示) - 冒烟测试(非仓库目录): - `python3 -m http.server 4188 --directory /Users/peiwang/Projects/AgentVerse/dist > /tmp/agentverse-smoke-4188.log 2>&1 & server_pid=$!; sleep 1; curl -I http://127.0.0.1:4188/ | head -n 1; kill $server_pid` - 观察点:HTTP 200 ## 发布/部署 - 无(不涉及线上发布/部署) ================================================ FILE: docs/logs/v0.1.13-v2ex-post/v2ex-post.md ================================================ 大家好,分享我的一个多智能体群聊与自治对话的开源项目:AgentVerse。项目始于 1年前,之后断断续续有一些完善。去年[发过一次](https://www.v2ex.com/t/1109676#reply35),有的朋友或许记得。 项目定位:让一群“有不同思维方式/立场/角色”的智能体,在同一会话中对话、协作、碰撞,形成更真实的讨论张力与结论沉淀。如果没用,也要有趣。 github: https://github.com/Peiiii/AgentVerse 在线体验:https://agent.dimstack.com/ ## 核心亮点: - 多智能体群聊:同一会话里多角色参与,自动接话与接力 - 讨论控制:可暂停/继续、控制轮次、主持人/参与者角色分工 - 思维方式碰撞:观点冲突与互补并存,不是单模型的一致输出 - Agent笔记:支持Agent记录笔记来跟踪讨论过程,或者约定议程 - 互动细节:@mention 触发、互动特效(扔💩/扔🗑️)等 - Agent 配置 Agent:用智能体来配置/生成其他 Agent 的设定与提示词 ## 内置角色与组合(部分): - 角色库:故事架构师、跨界思考者、逻辑分析师、系统思考者、用户代言人、情感设计师、市场洞察师等 - 组合示例:思维探索团队、MBTI 人格大杂烩、叙事探索团队、认知融合团队、情绪决策团队、结构化思考团队、实践执行团队、产品开发组、杠精小队等 - 使用方式:主持人负责节奏与聚焦,参与者代表不同视角,天然制造认知碰撞 ## 适用场景举例 - 产品/创业:从市场机会到用户视角,再到执行落地的多维评审 - 叙事/内容创作:结构、情感、文化视角的并行推演 - 决策讨论:理性/情绪/系统视角的冲突与融合 - 头脑风暴:高发散 + 强收敛的同场协作 # 示例截图 ![带笔记对话](https://cdn-us.imgs.moe/2026/01/28/2a888138d01582244cf341a0750b92ba.png) ![Agent创建Agent](https://cdn-us.imgs.moe/2026/01/28/ad652cb6c8da449b6b23248edc4cdd60.png) ![选择团队](https://cdn-us.imgs.moe/2026/01/28/8b400392c85e4d0292c1094f722d7f45.png) 还有更多特性,就不截图了。 目前阶段:持续迭代中(例如 marketplace, 使用更好的模型(目前的模型还是qwen)等)。 如果你对多智能体对话、协作式 AI 产品或交互式聊天体验感兴趣,欢迎交流建议。也欢迎拍砖。 ================================================ FILE: docs/logs/v0.1.14-sidebar-github/iteration-notes.md ================================================ # v0.1.14-sidebar-github 迭代记录 ## 改了什么 - 侧边栏新增 GitHub 入口,方便快速跳转项目仓库 ## 测试/验证/验收 - `pnpm lint`(存在既有 warnings,未阻塞) - `pnpm exec tsc -b` - `pnpm build`(CSS minify warning 与包体积提示) - 冒烟测试(非仓库目录): - `python3 -m http.server 4185 --directory /Users/peiwang/Projects/AgentVerse/dist & sleep 1; curl -I http://127.0.0.1:4185/ | head -n 1; kill $!` - 观察点:HTTP 200 ## 发布/部署 - 无(不涉及线上发布/部署) ================================================ FILE: docs/logs/v0.1.15-activitybar-github/iteration-notes.md ================================================ # v0.1.15-activitybar-github 迭代记录 ## 改了什么 - 左侧活动栏新增 GitHub 入口,方便快速跳转项目仓库 ## 测试/验证/验收 - `pnpm lint`(存在既有 warnings,未阻塞) - `pnpm exec tsc -b` - `pnpm build`(CSS minify warning 与包体积提示) - 冒烟测试(非仓库目录): - `python3 -m http.server 4186 --directory /Users/peiwang/Projects/AgentVerse/dist & sleep 1; curl -I http://127.0.0.1:4186/ | head -n 1; kill $!` - 观察点:HTTP 200 ## 发布/部署 - 无(不涉及线上发布/部署) ================================================ FILE: docs/logs/v0.1.16-readme-screenshots/iteration-notes.md ================================================ # v0.1.16-readme-screenshots 迭代记录 ## 改了什么 - 在 README 增补多张产品截图(非 demo1/demo2),丰富展示内容 ## 测试/验证/验收 - `pnpm lint`(存在既有 warnings,未阻塞) - `pnpm exec tsc -b` - `pnpm run build`(CSS minify warning 与包体积提示) - 冒烟测试(非仓库目录): - `python3 -m http.server 4191 --directory /Users/peiwang/Projects/AgentVerse/dist > /tmp/agentverse-smoke-4191.log 2>&1 & server_pid=$!; sleep 1; curl -I http://127.0.0.1:4191/ | head -n 1; kill $server_pid` - 观察点:HTTP 200 ## 发布/部署 - 无(不涉及线上发布/部署) ================================================ FILE: docs/logs/v0.1.17-dashscope-models/iteration-notes.md ================================================ # v0.1.17-dashscope-models 迭代记录 ## 改了什么 - DashScope 模型列表新增 `qwen3-max-thinking` 与 `glm-4.7` ## 测试/验证/验收 - `pnpm lint`(存在既有 warnings,未阻塞) - `pnpm exec tsc -b` - `pnpm run build`(CSS minify warning 与包体积提示) - 冒烟测试(非仓库目录): - `python3 -m http.server 4193 --directory /Users/peiwang/Projects/AgentVerse/dist > /tmp/agentverse-smoke-4193.log 2>&1 & server_pid=$!; sleep 1; curl -I http://127.0.0.1:4193/ | head -n 1; kill $server_pid` - 观察点:HTTP 200 ## 发布/部署 - 无(不涉及线上发布/部署) ================================================ FILE: docs/logs/v0.1.2-auth-email/iteration-notes.md ================================================ # v0.1.2-auth-email 迭代记录 ## 改了什么 - 新增邮箱注册/登录/验证/重置密码完整闭环 - 前端增加登录、验证、忘记密码、重置密码页面 - 全局 AuthGate:未登录时强制跳转登录页 - 新增 Cloudflare Pages Functions + D1 存储会话与令牌 - 接入 Resend 发送验证与重置邮件 - 邮件链接域名支持多域名白名单 ## 测试/验证/验收 - `pnpm lint`(存在既有 warnings,未阻塞) - `pnpm tsc` - `pnpm build`(CSS minify warning 与包体积提示) - `pnpm deploy:pages`(包含 Functions 构建) - 冒烟测试(非仓库目录):`node -e "const https=require('https');https.get('https://agentverse.pages.dev',res=>{console.log(res.statusCode);console.log(res.headers['content-type']||'');res.resume();}).on('error',err=>{console.error(err.message);process.exit(1);});"`(返回 200) ## 发布/部署 - Cloudflare Pages:`pnpm deploy:pages` - 访问地址:`https://agentverse.pages.dev`(生产域名),`https://344acf43.agentverse.pages.dev`(本次部署) - D1:`agentverse-auth`(已创建并应用迁移) - Resend:Pages Secret 已写入 `RESEND_API_KEY`(不落库) - 发件域名:`bibo.bot`(需在 Resend 完成 DNS 验证) - 邮件链接域名白名单:`https://agent.dimstack.com`、`https://bibo.bot`、`https://agentverse.pages.dev` ================================================ FILE: docs/logs/v0.1.3-auth-optional/iteration-notes.md ================================================ # v0.1.3-auth-optional 迭代记录 ## 改了什么 - 登录改为可选:未登录也可直接使用核心功能 - AuthGate 不再拦截主流程,仅负责渲染认证相关页面 ## 测试/验证/验收 - `pnpm lint`(存在既有 warnings,未阻塞) - `pnpm tsc` - `pnpm build` - `pnpm deploy:pages` - 冒烟测试(非仓库目录):`node -e "const https=require('https');https.get('https://agentverse.pages.dev',res=>{console.log(res.statusCode);console.log(res.headers['content-type']||'');res.resume();}).on('error',err=>{console.error(err.message);process.exit(1);});"`(返回 200) ## 发布/部署 - Cloudflare Pages:`pnpm deploy:pages` ================================================ FILE: docs/logs/v0.1.4-auth-entry/iteration-notes.md ================================================ # v0.1.4-auth-entry 迭代记录 ## 改了什么 - 活动栏左下角新增“登录 / 注册”入口(未登录时展示) - 点击入口跳转登录页并携带当前页面回跳参数 - 修复登录入口重复渲染与更新死循环问题 ## 测试/验证/验收 - `pnpm lint`(存在既有 warnings,未阻塞) - `pnpm tsc` - `pnpm build`(CSS minify warning 与包体积提示) - `pnpm deploy:pages`(包含 Functions 构建) - 冒烟测试(非仓库目录):`node -e "const https=require('https');https.get('https://agentverse.pages.dev',res=>{console.log(res.statusCode);console.log(res.headers['content-type']||'');res.resume();}).on('error',err=>{console.error(err.message);process.exit(1);});"`(返回 200) ## 发布/部署 - Cloudflare Pages:`pnpm deploy:pages` - 访问地址:`https://agentverse.pages.dev`(生产域名),`https://9ed89d65.agentverse.pages.dev`(本次部署) ================================================ FILE: docs/logs/v0.1.5-poop-impact/iteration-notes.md ================================================ # v0.1.5-poop-impact 迭代记录 ## 改了什么 - 群聊扔💩击中时增加冲击波、核心糊状体与更密集的喷溅粒子 - 命中瞬间表情放大旋转,强化戏剧性冲击感 ## 测试/验证/验收 - `pnpm lint`(存在既有 warnings,未阻塞) - `pnpm exec tsc -b` - `pnpm build`(CSS minify warning 与包体积提示) - 冒烟测试(非仓库目录): - `python3 -m http.server 4173 --directory /Users/peiwang/Projects/AgentVerse/dist & sleep 1; curl -I http://127.0.0.1:4173/ | head -n 1; kill $!` - 观察点:HTTP 200 ## 发布/部署 - 无(不涉及线上发布/部署) ================================================ FILE: docs/logs/v0.1.6-stream-dedupe/iteration-notes.md ================================================ # v0.1.6-stream-dedupe 迭代记录 ## 改了什么 - 流式回复接入“完整内容回传”兼容逻辑,避免重复片段被反复追加 - 连续重复的原始 delta 直接忽略,减少 UI 无意义刷屏 ## 测试/验证/验收 - `pnpm lint`(存在既有 warnings,未阻塞) - `pnpm exec tsc -b` - `pnpm build`(CSS minify warning 与包体积提示) - 冒烟测试(非仓库目录): - `python3 -m http.server 4174 --directory /Users/peiwang/Projects/AgentVerse/dist & sleep 1; curl -I http://127.0.0.1:4174/ | head -n 1; kill $!` - 观察点:HTTP 200 ## 发布/部署 - 无(不涉及线上发布/部署) ================================================ FILE: docs/logs/v0.1.7-streaming-delta-normalization/iteration-notes.md ================================================ # v0.1.7-streaming-delta-normalization 迭代记录 ## 改了什么 - 统一流式文本事件语义:兼容“返回完整内容”的流,转换为真实 delta 再交给上层追加 - 让聊天流式渲染只处理增量片段,根因层面杜绝重复内容被反复拼接 ## 测试/验证/验收 - `pnpm lint`(存在既有 warnings,未阻塞) - `pnpm exec tsc -b` - `pnpm build`(CSS minify warning 与包体积提示) - 冒烟测试(非仓库目录): - `python3 -m http.server 4175 --directory /Users/peiwang/Projects/AgentVerse/dist & sleep 1; curl -I http://127.0.0.1:4175/ | head -n 1; kill $!` - 观察点:HTTP 200 ## 发布/部署 - 无(不涉及线上发布/部署) ================================================ FILE: docs/logs/v0.1.8-streaming-mode-normalization/iteration-notes.md ================================================ # v0.1.8-streaming-mode-normalization 迭代记录 ## 改了什么 - 流式输出增加“模式识别”:自动区分全量流与增量流,避免误判导致内容被吞 - delta 规范化更保守,确保增量流不会被错误去重而出现空回复 ## 测试/验证/验收 - `pnpm lint`(存在既有 warnings,未阻塞) - `pnpm exec tsc -b` - `pnpm build`(CSS minify warning 与包体积提示) - 冒烟测试(非仓库目录): - `python3 -m http.server 4176 --directory /Users/peiwang/Projects/AgentVerse/dist & sleep 1; curl -I http://127.0.0.1:4176/ | head -n 1; kill $!` - 观察点:HTTP 200 ## 发布/部署 - 无(不涉及线上发布/部署) ================================================ FILE: docs/logs/v0.1.9-poop-impact-drama/iteration-notes.md ================================================ # v0.1.9-poop-impact-drama 迭代记录 ## 改了什么 - 扔💩命中效果加强:双层冲击波、中心糊状体、拖尾飞溅与更多粒子 - 增加命中闪光与粘稠“块状”扩散,整体更戏剧化 ## 测试/验证/验收 - `pnpm lint`(存在既有 warnings,未阻塞) - `pnpm exec tsc -b` - `pnpm build`(CSS minify warning 与包体积提示) - 冒烟测试(非仓库目录): - `python3 -m http.server 4177 --directory /Users/peiwang/Projects/AgentVerse/dist & sleep 1; curl -I http://127.0.0.1:4177/ | head -n 1; kill $!` - 观察点:HTTP 200 ## 发布/部署 - 无(不涉及线上发布/部署) ================================================ FILE: docs/mcp-integration.md ================================================ # MCP (Model Context Protocol) 集成指南 ## 概述 AgentVerse 现在支持 MCP (Model Context Protocol) 服务器连接,允许 AI 助手使用外部工具来完成任务。这个功能是可插拔的,不与具体 agent 绑定,可以在任何对话中使用。 ## 功能特性 - **动态连接**: 支持运行时连接/断开 MCP 服务器 - **工具自动发现**: 自动获取 MCP 服务器的工具列表 - **类型安全**: 完整的 TypeScript 类型支持 - **错误处理**: 连接失败、工具执行错误等处理 - **可扩展**: 支持多种 MCP 服务器类型 ## 快速开始 ### 1. 启动 MCP 服务器 首先,你需要启动一个 MCP 服务器。例如,使用 [filesystem-mcp-server](https://github.com/atxtechbro/filesystem-mcp-server): ```bash # 克隆并安装 git clone https://github.com/atxtechbro/filesystem-mcp-server cd filesystem-mcp-server npm install # 启动服务器 npm start ``` ### 2. 在 AgentVerse 中连接 MCP 服务器 1. 打开 AgentVerse 应用 2. 进入 MCP 演示页面 3. 在左侧连接管理面板中: - 输入服务器名称:`文件系统服务器` - 选择传输协议:`WebSocket` - 输入服务器地址:`ws://localhost:3000` - 点击"连接服务器" ### 3. 使用 MCP 工具 连接成功后,AI 助手将自动获得 MCP 服务器提供的工具。你可以: - 在对话中直接描述需求,AI 会自动选择合适的工具 - 查看"可用工具"标签页,了解所有可用的工具 - 观察工具调用的实时执行过程 ## 架构设计 ### 核心组件 ``` MCP连接层 ├── MCPConnectionManager (连接管理) ├── MCPToolAdapter (工具适配) └── MCPProvider (Provider包装) 工具集成层 ├── useMCPTools (Hook) ├── MCPToolRenderer (渲染器) └── MCPToolExecutor (执行器) 应用层 ├── AgentChatContainer (集成到聊天) └── 其他组件 (按需使用) ``` ### 文件结构 ``` src/common/ ├── lib/mcp/ │ ├── mcp-connection-manager.ts # MCP连接管理器 │ └── mcp-tool-adapter.ts # 工具适配器 ├── hooks/ │ └── use-mcp-tools.ts # MCP工具Hook └── components/mcp/ ├── mcp-connection-manager.tsx # 连接管理UI └── mcp-provider.tsx # Provider组件 src/desktop/features/mcp/ └── pages/ └── mcp-demo-page.tsx # 演示页面 ``` ## 使用方法 ### 基本使用 ```tsx import { MCPProvider } from "@/common/features/mcp/components/mcp-provider"; import { useMCPTools } from "@/common/hooks/use-mcp-tools"; function App() { return ( <MCPProvider> <YourApp /> </MCPProvider> ); } function YourComponent() { const { connections, connectToServer, mcpToolDefinitions } = useMCPTools(); // 连接MCP服务器 const handleConnect = async () => { await connectToServer({ name: "文件系统服务器", url: "ws://localhost:3000", transport: "websocket" }); }; return ( <div> {/* 你的组件内容 */} </div> ); } ``` ### 在聊天中使用 MCP 工具会自动集成到所有使用 `@agent-labs/agent-chat` 的聊天组件中。AI 助手会根据对话内容自动选择合适的工具。 ### 自定义工具渲染 你可以自定义 MCP 工具的渲染方式: ```tsx import { useMCPTools } from "@/common/hooks/use-mcp-tools"; function CustomMCPRenderer() { const { mcpToolRenderers } = useMCPTools(); // 自定义渲染器会覆盖默认的渲染方式 const customRenderers = mcpToolRenderers.map(renderer => ({ ...renderer, render: (toolInvocation, onResult) => { // 自定义渲染逻辑 return <YourCustomComponent />; } })); return <div>{/* 你的自定义渲染内容 */}</div>; } ``` ## 支持的 MCP 服务器 ### 文件系统服务器 - **仓库**: [filesystem-mcp-server](https://github.com/atxtechbro/filesystem-mcp-server) - **功能**: 文件读写、目录操作、文件搜索 - **连接地址**: `ws://localhost:3000` ### 其他服务器 你可以连接任何符合 MCP 协议的服务器,包括: - 数据库服务器 - API 代理服务器 - 系统监控服务器 - 自定义业务服务器 ## 配置选项 ### MCP 服务器配置 ```typescript interface MCPServerConfig { name: string; // 服务器名称 url: string; // 服务器地址 transport?: "stdio" | "tcp" | "websocket"; // 传输协议 credentials?: { // 认证信息 token?: string; username?: string; password?: string; }; } ``` ### 连接管理 ```typescript // 连接服务器 const connectionId = await connectToServer(config); // 断开连接 await disconnectFromServer(connectionId); // 获取连接信息 const connection = getConnection(connectionId); const tools = getTools(connectionId); ``` ## 错误处理 ### 常见错误 1. **连接失败** - 检查服务器地址是否正确 - 确认服务器是否正在运行 - 检查网络连接 2. **工具执行失败** - 检查工具参数是否正确 - 确认服务器权限 - 查看服务器日志 3. **类型错误** - 检查工具定义是否符合 MCP 规范 - 确认参数类型匹配 ### 调试技巧 1. 打开浏览器开发者工具 2. 查看控制台日志 3. 检查网络请求 4. 使用 MCP 演示页面进行测试 ## 最佳实践 ### 1. 服务器命名 使用描述性的服务器名称,例如: - `文件系统服务器` - `数据库服务器` - `API代理服务器` ### 2. 工具描述 确保 MCP 服务器的工具描述清晰明确,这样 AI 才能正确理解和使用工具。 ### 3. 错误处理 在 MCP 服务器中实现适当的错误处理,返回有意义的错误信息。 ### 4. 安全性 - 使用适当的认证机制 - 限制工具的执行权限 - 监控工具的使用情况 ## 扩展开发 ### 创建自定义 MCP 服务器 1. 实现 MCP 协议 2. 定义工具接口 3. 处理工具调用 4. 返回执行结果 ### 集成到 AgentVerse 1. 创建连接配置 2. 测试工具功能 3. 优化用户体验 4. 添加错误处理 ## 故障排除 ### 连接问题 ```bash # 检查服务器状态 curl http://localhost:3000/health # 检查端口是否开放 netstat -an | grep 3000 # 查看服务器日志 tail -f server.log ``` ### 工具问题 1. 检查工具定义是否正确 2. 确认参数格式 3. 查看执行日志 4. 测试工具功能 ## 更新日志 ### v1.0.0 - 初始 MCP 集成实现 - 支持 WebSocket 连接 - 基本工具调用功能 - 连接管理 UI ## 贡献 欢迎提交 Issue 和 Pull Request 来改进 MCP 集成功能。 ## 许可证 本项目采用 MIT 许可证。 ================================================ FILE: docs/naming-research.md ================================================ # 项目命名研究文档 ## 当前项目概况 ### 项目定位 - 一个开源的多智能体对话平台 - 支持多个主流 AI 模型 - 让 AI 们进行自主讨论、头脑风暴和知识探索 - 当前版本:0.1.0 ### 核心特性 - 多智能体协作 - 多 AI 服务商支持 - 场景化应用 - 开源开放 - 易于扩展 ### 应用场景 - 面试模拟 - 产品讨论 - 学习辅导 - 知识探索 ## 品牌愿景 我们要打造的是一个 AgentVerse(智能体宇宙),这是我们的核心理念和愿景: - 一个智能体自由协作的完整生态 - 开放、包容、无限可能的平台 - 促进AI智能体之间的深度协作 - 创造超越个体的集体智慧 这个愿景类似于: - Android 之于移动操作系统 - Linux 之于开源操作系统 - Docker 之于容器生态 我们需要一个能承载这个愿景的品牌名称,但这个名称: - 不必直接描述产品本质 - 不必局限于技术术语 - 需要有强大的品牌张力 - 需要能支撑长期发展 ## 命名考虑 ### 当前名称分析:AgentVerse 优势: - 暗示完整的生态系统 - 包容性强,未来扩展空间大 - 容易记忆,朗朗上口 - 符合产品本质定位 劣势: - verse 后缀较常见 - 可能给人元宇宙联想 ### 命名方法论 1. **描述性命名** - 直接反映产品特性 - 例如:AgentVerse, AgentHub, CollabSpace - 评估:可以考虑,但不是唯一选择 2. **抽象命名** - 与产品本质无直接关联 - 例如:Apple(电脑), Amazon(电商) - 优势:品牌价值独立,扩展性强 - 评估:值得重点探索 3. **隐喻命名** - 借用其他领域的概念 - 例如:Docker(容器), Python(编程语言) - 优势:形象生动,故事性强 - 评估:很有潜力,特别是能暗示生态系统的概念 4. **创造性命名** - 完全原创词汇 - 例如:Kodak, Google - 优势:独特性强,易于注册 - 评估:如果能创造好,价值最大 ### 新的命名思路 重新思考,基于更宏大的品牌愿景: 1. **自然生态隐喻** - Gaia(盖亚,地球母神):生命、生态、整体性 - Terra(地球):完整世界、生态系统 - Aurora(极光):神秘、能量、变幻 2. **文明与智慧** - Nexus(联结点):智慧的汇聚 - Atlas(地图/泰坦神):支撑、指引 - Lumina(光明):启发、智慧 3. **创造与演化** - Genesis(起源):创造、开端 - Nova(新星):爆发、创新 - Helix(螺旋):演化、上升 4. **抽象与未来** - Cipher(密码):解码未来 - Quantum(量子):无限可能 - Vector(矢量):方向、力量 5. **智慧与力量** - Intellix(智能+系统):智能生态系统 - Cognova(认知+新星):认知革新 - Mindeon(思维+永恒):永恒思维 6. **生态与演化** - Syntropy(有序进化):智能有序发展 - Genesis(智能起源):智能源头 - Nexora(连接+新生):新生连接 7. **宇宙与秩序** - Cosmix(宇宙+系统):宇宙系统 - Ordina(秩序+智能):智能秩序 - Stellix(星辰+系统):星辰系统 ### 名称评估要点 1. **品牌潜力** - 是否能承载生态系统愿景 - 是否具有扩展性 - 是否易于记忆 - 是否有品牌故事潜力 2. **实用性** - 发音是否友好 - 拼写是否简单 - 是否易于传播 - 是否适合国际化 3. **技术考量** - 域名可用性 - 商标可注册性 - 社区认可度 - 开发者友好度 ## 评估维度 1. **实用性考量** - 域名可用性 - 商标注册可能性 - GitHub 仓库名可用性 - NPM 包名可用性 2. **品牌价值** - 能否承载宏大愿景 - 是否具有时代感 - 国际化潜力 - 文化内涵 3. **技术考量** - SEO 友好度 - 开发者社区接受度 - 技术栈匹配度 4. **商业价值** - 品牌故事潜力 - 市场识别度 - 商业化可能性 ## 下一步计划 1. **深入调研** - 竞品名称分析 - 域名可用性检查 - 商标检索 - 社区反馈收集 2. **重点评估** - 筛选最具潜力的 3-5 个名称 - 进行详细的可行性分析 - 设计相应的品牌故事 - 评估长期发展空间 3. **决策流程** - 建立评分体系 - 收集多方意见 - 进行最终决策 - 制定品牌建设计划 ## 备注 - 命名决策将影响产品的长期发展 - 需要平衡创意性和实用性 - 考虑预算和时间投入 - 保持开放性思维,不局限于现有方案 - 核心是打造一个伟大的品牌,而不仅仅是一个好名字 - 名字需要能承载"智能体宇宙"的愿景,但不必直接表达它 ================================================ FILE: docs/project-standards.md ================================================ # 项目规范文档 ## 技术栈 - React 18 + TypeScript - Vite - Tailwind CSS - shadcn/ui - pnpm ## 目录结构 ``` src/ ├── assets/ # 静态资源文件 ├── components/ # 可复用组件 │ ├── ui/ # UI 基础组件 │ └── common/ # 业务通用组件 ├── hooks/ # 自定义 Hooks ├── layouts/ # 布局组件 ├── pages/ # 页面组件 ├── services/ # API 服务 ├── stores/ # 状态管理 ├── styles/ # 全局样式 ├── types/ # TypeScript 类型定义 └── utils/ # 工具函数 ``` ## 命名规范 ### 文件命名 - 所有文件和目录名统一使用小写字母,单词之间用连字符(-)连接 - 组件文件:`button-primary.tsx`, `user-profile.tsx` - 组件目录:`button/`, `user-profile/` - 工具文件:`date-formatter.ts`, `string-utils.ts` - 样式文件:与组件同名,`button-primary.css` - 测试文件:与被测试文件同名,加上.test后缀,`button-primary.test.tsx` - 服务文件:使用 `.service.ts` 后缀,如 `authentication.service.ts` ### 服务类规范 ```typescript // user.service.ts export class UserService { private readonly apiUrl = '/api/users'; constructor(private httpClient: HttpClient) {} async getUsers(): Promise<User[]> { return this.httpClient.get(this.apiUrl); } async getUserById(id: string): Promise<User> { return this.httpClient.get(`${this.apiUrl}/${id}`); } } ``` ### 组件命名规范 - 文件名:使用 kebab-case(例:`user-profile.tsx`) - 组件名:使用 PascalCase(例:`export function UserProfile`) - Props 接口:使用 PascalCase + Props(例:`interface UserProfileProps`) - 目录名:使用 kebab-case(例:`user-profile/index.tsx`) ### 变量命名 - 普通变量:使用 camelCase - 常量:使用 UPPER_SNAKE_CASE - 私有变量:使用下划线前缀(例:`_privateVar`) ## 代码规范 ### TypeScript - 启用严格模式(`strict: true`) - 必须声明类型,避免使用 `any` - 优先使用 `interface` 而不是 `type` ### React 相关 - 使用函数式组件 - Props 必须定义类型接口 - 使用 ES6+ 语法 - 优先使用 Hooks 而不是 Class 组件 ### 文件大小限制 - 单个 TSX/TS 文件不应超过 300 行(包含空行和注释) - 推荐保持在 150-200 行以内 - 超过限制时的拆分原则: 1. 将独立的 UI 组件拆分到单独文件 2. 将复杂的业务逻辑抽离到 hooks 3. 将类型定义移到 types 目录 4. 将配置项移到 config 目录 5. 将工具函数移到 utils 目录 ### 样式规范 - 使用 Tailwind CSS 工具类 - 复杂样式使用 CSS Modules - 避免内联样式 - 遵循移动优先的响应式设计原则 ## Git 提交规范 提交信息格式: ``` <type>(<scope>): <subject> <body> <footer> ``` 类型(type): - feat: 新功能 - fix: Bug 修复 - docs: 文档更新 - style: 代码格式(不影响代码运行的变动) - refactor: 重构(既不是新增功能,也不是修复 bug) - test: 增加测试 - chore: 构建过程或辅助工具的变动 ## 开发流程 1. 从 main 分支创建特性分支 2. 开发完成后提交 PR 3. 代码审查通过后合并到 main 分支 4. 定期打 tag 发布版本 ## 性能优化准则 - 合理使用 React.memo 和 useMemo - 避免不必要的重渲染 - 图片资源使用适当的格式和大小 - 按需加载组件和模块 ================================================ FILE: docs/prompt-experiments.md ================================================ # Prompt Experiments 我认为现在的 agent 的 prompt 都不太行。我需要试验性的尝试一个 agent,主要从响应格式做文章,我给出一个示例,粗浅的想法,还不确定: <think> <goal> </goal> </think> <response> </response> ================================================ FILE: docs/prompts/generate-world-class-artistic-ui.md ================================================ 写出令人惊叹不已精美无比的界面。要世界级的体验,美观与体验的最佳结合。现代化的,充满创意而不是平庸的,有趣而不是无聊的界面。写出体验无与伦比的界面。要写艺术品而不是仅仅是实现功能,要超越和引领而不是平庸的追随者。 ================================================ FILE: docs/references/agent-chat-tutorial.md ================================================ # @agent-labs/agent-chat 使用教程 @agent-labs/agent-chat 是一个功能强大的 React 组件库,用于快速构建 AI 助手聊天界面。本教程将帮助你了解如何安装和使用这个库。 ## 目录 - [安装](#安装) - [快速开始](#快速开始) - [使用方式](#使用方式) - [基础组件 (AgentChatCore)](#基础组件-agentchatcore) - [窗口组件 (AgentChatWindow)](#窗口组件-agentchatwindow) - [Context Provider 架构](#context-provider-架构) - [典型场景](#典型场景) - [基础聊天界面](#基础聊天界面) - [动态上下文管理](#动态上下文管理) - [插件式工具系统](#插件式工具系统) - [动态注册工具执行器](#动态注册工具执行器) - [自定义工具界面](#自定义工具界面) - [组合使用场景](#组合使用场景) - [预加载消息](#预加载消息) - [程序化消息管理](#程序化消息管理) - [高级功能](#高级功能) - [Ref API](#ref-api) - [useAgentChat Hook](#useagentchat-hook) - [API 参考](#api-参考) - [Hooks 参考](#hooks-参考) ## 安装 使用 npm 或 yarn 安装必要的依赖: ```bash # 安装 agent-chat 组件库 npm install @agent-labs/agent-chat # 安装 HTTP Agent 客户端 npm install @ag-ui/client # 或者使用 yarn yarn add @agent-labs/agent-chat @ag-ui/client ``` 注意:`@ag-ui/client` 是必需的依赖,用于创建 HTTP Agent 实例与后端服务通信。 ## 快速开始 首先,创建一个 Agent 实例: ```tsx import { HttpAgent } from '@ag-ui/client' // 创建一个全局的 Agent 实例 export const agent = new HttpAgent({ url: 'http://localhost:8000/openai-agent', }) ``` 然后,在你的应用中使用它: ```tsx import { AgentChatWindow } from '@agent-labs/agent-chat' import { agent } from './agent' function App() { return ( <AgentChatWindow agent={agent} /> ) } ``` 就这么简单! ## 使用方式 ### 基础组件 (AgentChatCore) `AgentChatCore` 是一个基础的聊天组件,提供了核心的聊天功能,适合需要自定义 UI 的场景: ```tsx import { AgentChatCore } from '@agent-labs/agent-chat' import { agent } from './agent' function BasicExample() { return ( <div className="min-h-screen bg-gray-100"> <div className="container mx-auto p-4"> <AgentChatCore agent={agent} className="h-[600px]" /> </div> </div> ) } ``` ### 窗口组件 (AgentChatWindow) `AgentChatWindow` 是一个完整的窗口组件,提供了开箱即用的聊天窗口体验: ```tsx import { AgentChatWindow } from '@agent-labs/agent-chat' import { agent } from './agent' function WindowExample() { return ( <AgentChatWindow agent={agent} className="fixed bottom-4 right-4" /> ) } ``` ## Context Provider 架构 所有 hooks 默认使用全局实例,无需配置 Provider,只有多实例隔离时才需要。 你可以通过 AgentContextManagerContext、AgentToolDefManagerContext、AgentToolExecutorManagerContext、AgentToolRendererManagerContext 这些 Provider 进行自定义隔离,绝大多数场景下无需配置,默认全局实例即可。 **推荐写法:** ```tsx import { AgentToolDefManagerContext, AgentToolDefManager, AgentChatWindow } from '@agent-labs/agent-chat' import { agent } from './agent' import { useMemo } from 'react' function IsolatedChat() { // 保证 manager 实例稳定 const customToolDefManager = useMemo(() => new AgentToolDefManager(), []) return ( <AgentToolDefManagerContext.Provider value={customToolDefManager}> <AgentChatWindow agent={agent} /> </AgentToolDefManagerContext.Provider> ) } ``` **多实例隔离:** ```tsx function MultiChat() { const managerA = useMemo(() => new AgentToolDefManager(), []) const managerB = useMemo(() => new AgentToolDefManager(), []) return ( <> <AgentToolDefManagerContext.Provider value={managerA}> <ChatA /> </AgentToolDefManagerContext.Provider> <AgentToolDefManagerContext.Provider value={managerB}> <ChatB /> </AgentToolDefManagerContext.Provider> </> ) } ``` **所有 Provider 分别自定义的例子:** ```tsx import { AgentContextManagerContext, AgentContextManager, AgentToolDefManagerContext, AgentToolDefManager, AgentToolExecutorManagerContext, AgentToolExecutorManager, AgentToolRendererManagerContext, AgentToolRendererManager, AgentChatWindow } from '@agent-labs/agent-chat' import { agent } from './agent' import { useMemo } from 'react' function FullyIsolatedChat() { const contextManager = useMemo(() => new AgentContextManager(), []) const toolDefManager = useMemo(() => new AgentToolDefManager(), []) const toolExecutorManager = useMemo(() => new AgentToolExecutorManager(), []) const toolRendererManager = useMemo(() => new AgentToolRendererManager(), []) return ( <AgentContextManagerContext.Provider value={contextManager}> <AgentToolDefManagerContext.Provider value={toolDefManager}> <AgentToolExecutorManagerContext.Provider value={toolExecutorManager}> <AgentToolRendererManagerContext.Provider value={toolRendererManager}> <AgentChatWindow agent={agent} /> </AgentToolRendererManagerContext.Provider> </AgentToolExecutorManagerContext.Provider> </AgentToolDefManagerContext.Provider> </AgentContextManagerContext.Provider> ) } ``` ## 典型场景 ### 基础聊天界面 使用 `AgentChatCore` 构建基础聊天界面: ```tsx import { AgentChatCore } from '@agent-labs/agent-chat' import { agent } from './agent' function BasicChat() { return ( <div className="min-h-screen bg-gray-100"> <div className="container mx-auto p-4"> <header className="mb-8"> <h1 className="text-3xl font-bold">AI 助手</h1> </header> <div className="bg-white rounded-lg shadow-lg"> <AgentChatCore agent={agent} className="h-[600px]" /> </div> </div> </div> ) } ``` ### 动态上下文管理 使用 hooks 来管理动态上下文,默认情况下无需额外配置: ```tsx import { AgentChatWindow } from '@agent-labs/agent-chat' import { agent } from './agent' import { useEffect, useState } from 'react' import { useProvideAgentContexts } from '@agent-labs/agent-chat' // 直接使用动态上下文 - 使用默认全局实例 function DynamicContextChat() { // 用户信息状态 const [userInfo, setUserInfo] = useState({ name: '张三', role: 'developer', lastActive: new Date().toISOString(), }) // 使用 hook 提供上下文 - 自动使用默认全局实例 useProvideAgentContexts([ { description: '用户信息', value: JSON.stringify(userInfo), }, ]) // 定期更新用户活跃时间 useEffect(() => { const timer = setInterval(() => { setUserInfo(prev => ({ ...prev, lastActive: new Date().toISOString(), })) }, 60000) return () => clearInterval(timer) }, []) return ( <div className="min-h-screen bg-gray-100"> <div className="container mx-auto p-4"> <header className="mb-4"> <h1 className="text-2xl font-bold">动态上下文聊天</h1> <p className="text-gray-600"> 当前用户: {userInfo.name} ({userInfo.role}) </p> </header> <AgentChatWindow agent={agent} /> </div> </div> ) } // 如果需要多实例隔离,可以使用Provider包装: function IsolatedDynamicContextApp() { return ( <AgentProvidersProvider> <DynamicContextChat /> </AgentProvidersProvider> ) } export default DynamicContextChat ``` ### 插件式工具系统 使用 hooks 来管理动态工具,默认情况下无需额外配置: ```tsx import { AgentChatCore } from '@agent-labs/agent-chat' import { agent } from './agent' import { useState } from 'react' import type { ToolDefinition } from '@agent-labs/agent-chat' import { useProvideAgentToolDefs } from '@agent-labs/agent-chat' // 插件管理组件 - 直接使用默认全局实例 function PluginSystemChat() { // 基础工具 const baseTools: ToolDefinition[] = [ { name: 'search', description: '搜索网络信息', parameters: { type: 'object', properties: { query: { type: 'string', description: '搜索关键词', }, }, required: ['query'], }, }, ] // 动态工具列表 const [dynamicTools, setDynamicTools] = useState<ToolDefinition[]>([]) // 使用 hook 提供工具定义 - 自动使用默认全局实例 useProvideAgentToolDefs([...baseTools, ...dynamicTools]) // 添加新工具的函数 const addNewTool = () => { const newTool: ToolDefinition = { name: 'getTime', description: '获取当前时间', parameters: { type: 'object', properties: {}, required: [], }, } setDynamicTools(prev => [...prev, newTool]) } // 移除工具的函数 const removeLastTool = () => { setDynamicTools(prev => prev.slice(0, -1)) } return ( <div className="min-h-screen bg-gray-100"> <div className="container mx-auto p-4"> <header className="mb-4"> <h1 className="text-2xl font-bold">插件式工具系统</h1> <p className="text-gray-600"> 当前工具数量: {baseTools.length + dynamicTools.length} </p> </header> <div className="bg-white rounded-lg shadow-lg"> <AgentChatCore agent={agent} className="h-[600px]" /> </div> <div className="mt-4 flex gap-2"> <button className="px-4 py-2 bg-blue-500 text-white rounded" onClick={addNewTool} disabled={dynamicTools.some(t => t.name === 'getTime')} > 添加时间工具 </button> <button className="px-4 py-2 bg-red-500 text-white rounded" onClick={removeLastTool} disabled={dynamicTools.length === 0} > 移除最后一个工具 </button> </div> {/* 工具列表显示 */} <div className="mt-4 p-4 bg-gray-50 rounded"> <h3 className="font-semibold mb-2">当前可用工具:</h3> <ul className="space-y-1"> {[...baseTools, ...dynamicTools].map((tool, index) => ( <li key={index} className="text-sm"> <span className="font-mono bg-gray-200 px-2 py-1 rounded"> {tool.name} </span> - {tool.description} </li> ))} </ul> </div> </div> </div> ) } // 如果需要插件隔离,可以使用Provider包装: function IsolatedPluginSystemApp() { return ( <AgentProvidersProvider> <PluginSystemChat /> </AgentProvidersProvider> ) } export default PluginSystemChat ``` ### 动态注册工具执行器 `useProvideAgentToolExecutors` 用于在组件中动态注册工具执行器(ToolExecutor),实现自动工具调用和结果推送。支持同步和异步函数,配合 `useAgentChat` 可实现自动工具链路。 #### 典型用法 ```tsx import { useProvideAgentToolExecutors } from '@agent-labs/agent-chat' import type { ToolCall, ToolResult } from '@agent-labs/agent-chat' function ToolExecutorProvider() { // 注册工具执行器 useProvideAgentToolExecutors({ search: async (toolCall: ToolCall) => { const args = JSON.parse(toolCall.function.arguments) // 这里可以调用实际的搜索 API return { title: '搜索结果', content: `你搜索了:${args.query}`, } }, getTime: () => { // 同步返回 return { now: new Date().toISOString() } }, }) return null } ``` #### ToolExecutor 类型签名 ```typescript export type ToolExecutor = ( toolCall: ToolCall, context?: any ) => ToolResult | Promise<ToolResult> ``` - `toolCall`:工具调用的详细信息 - `context`:可选上下文参数 - 返回值:可以是同步 ToolResult,也可以是 Promise<ToolResult> #### 自动工具执行链路 - 只需注册 ToolExecutor,`useAgentChat` 会自动监听工具调用事件,自动查找并执行对应的 executor,执行结果自动推送到消息流并可自动触发 agent。 - 你无需手动管理工具调用和结果推送,极大简化业务代码。 #### 场景说明 - 适用于插件式工具、动态扩展工具、自动化工具链等场景。 - 支持在任意组件中动态注册/移除工具执行器,适合微前端、插件化架构。 ### 自定义工具界面 使用 hooks 来管理工具渲染器,默认情况下无需额外配置: ```tsx import { AgentChatWindow } from '@agent-labs/agent-chat' import { agent } from './agent' import type { ToolRenderer } from '@agent-labs/agent-chat' import { useProvideAgentToolRenderers, useProvideAgentToolDefs } from '@agent-labs/agent-chat' // 自定义工具界面组件 - 直接使用默认全局实例 function CustomToolUI() { // 工具定义 - 需要同时提供工具定义和渲染器 const toolDefinitions = [ { name: 'search', description: '搜索网络信息', parameters: { type: 'object', properties: { query: { type: 'string', description: '搜索关键词', }, }, required: ['query'], }, }, ] // 自定义工具渲染器 const customRenderers: ToolRenderer[] = [ { render: (toolCall, onResult) => { const args = JSON.parse(toolCall.function.arguments) return ( <div className="p-4 border rounded-lg bg-blue-50"> <h3 className="font-bold mb-2 text-blue-800">🔍 高级搜索</h3> <div className="space-y-4"> <input type="text" defaultValue={args.query} className="w-full p-2 border rounded" placeholder="输入搜索关键词" id={`search-input-${toolCall.id}`} /> <div className="flex gap-2"> <button className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600" onClick={() => { const input = document.getElementById(`search-input-${toolCall.id}`) as HTMLInputElement const query = input?.value || args.query onResult({ toolCallId: toolCall.id, result: { title: '搜索结果', content: `已完成对 "${query}" 的搜索,找到了相关信息...`, results: [ `关于 ${query} 的结果 1`, `关于 ${query} 的结果 2`, `关于 ${query} 的结果 3`, ] }, status: 'success', }) }} > 🔍 开始搜索 </button> <button className="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600" onClick={() => { onResult({ toolCallId: toolCall.id, result: null, status: 'cancelled', }) }} > ❌ 取消 </button> </div> </div> </div> ) }, definition: toolDefinitions[0], }, ] // 使用 hooks 提供工具定义和渲染器 - 自动使用默认全局实例 useProvideAgentToolDefs(toolDefinitions) useProvideAgentToolRenderers(customRenderers) return ( <div className="min-h-screen bg-gray-100"> <div className="container mx-auto p-4"> <header className="mb-4"> <h1 className="text-2xl font-bold">自定义工具界面</h1> <p className="text-gray-600"> 展示自定义的工具渲染器,提供更丰富的交互体验 </p> </header> <div className="bg-white rounded-lg shadow-lg"> <AgentChatWindow agent={agent} /> </div> </div> </div> ) } // 如果需要渲染器隔离,可以使用Provider包装: function IsolatedCustomToolUIApp() { return ( <AgentProvidersProvider> <CustomToolUI /> </AgentProvidersProvider> ) } export default CustomToolUI ``` ### 组合使用场景 在实际应用中,通常需要组合使用多个功能,以下是一个完整的示例: ```tsx import { AgentChatWindow, AgentProvidersProvider } from '@agent-labs/agent-chat' import { agent } from './agent' import { useEffect, useState } from 'react' import type { ToolDefinition, ToolRenderer } from '@agent-labs/agent-chat' import { useProvideAgentContexts, useProvideAgentToolDefs, useProvideAgentToolRenderers, useProvideAgentToolExecutors, } from '@agent-labs/agent-chat' // 主应用组件 - 使用Provider是为了演示完整功能组合 // 在实际应用中,如果不需要隔离,可以直接使用默认全局实例 function AdvancedChatApp() { return ( <AgentProvidersProvider> <AdvancedChat /> </AgentProvidersProvider> ) } // 高级聊天组件 - 组合使用多个功能 function AdvancedChat() { // 1. 状态管理 const [userInfo, setUserInfo] = useState({ name: '张三', role: 'developer', preferences: { theme: 'dark', language: 'zh-CN', }, }) // 2. 动态工具 const [tools, setTools] = useState<ToolDefinition[]>([ { name: 'search', description: '搜索网络信息', parameters: { type: 'object', properties: { query: { type: 'string', description: '搜索关键词', }, }, required: ['query'], }, }, ]) // 3. 自定义渲染器 const toolRenderers: ToolRenderer[] = [ { render: (toolCall, onResult) => { const args = JSON.parse(toolCall.function.arguments) return ( <div className="p-4 border rounded-lg"> <h3 className="font-bold mb-2">搜索结果</h3> <p>正在搜索: {args.query}</p> <button className="mt-2 px-4 py-2 bg-blue-500 text-white rounded" onClick={() => { onResult({ toolCallId: toolCall.id, result: { title: '搜索结果', content: `这是关于 ${args.query} 的搜索结果...`, }, status: 'success', }) }} > 搜索 </button> </div> ) }, definition: tools[0], }, ] // 4. 工具执行器 useProvideAgentToolExecutors({ search: async (toolCall) => { const args = JSON.parse(toolCall.function.arguments) // 模拟搜索 API 调用 await new Promise(resolve => setTimeout(resolve, 1000)) return { title: '搜索结果', content: `已找到关于 "${args.query}" 的信息`, results: [ `结果 1: ${args.query} 的定义`, `结果 2: ${args.query} 的应用场景`, `结果 3: ${args.query} 的最新发展`, ] } }, getTime: () => { return { currentTime: new Date().toISOString(), timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, } }, }) // 5. 使用 hooks 提供各种资源 - 需要在 Provider 内部使用 useProvideAgentContexts([ { description: '用户信息', value: JSON.stringify(userInfo), }, { description: '应用状态', value: JSON.stringify({ theme: userInfo.preferences.theme, activeFeatures: ['search', 'time', 'chat'], sessionStartTime: new Date().toISOString(), }), }, ]) useProvideAgentToolDefs(tools) useProvideAgentToolRenderers(toolRenderers) // 6. 动态更新和生命周期管理 useEffect(() => { const timer = setInterval(() => { setUserInfo(prev => ({ ...prev, lastActive: new Date().toISOString(), })) }, 60000) return () => clearInterval(timer) }, []) // 7. 工具管理函数 const addTimeTool = () => { const newTool: ToolDefinition = { name: 'getTime', description: '获取当前时间', parameters: { type: 'object', properties: {}, required: [], }, } setTools(prev => [...prev, newTool]) } const toggleTheme = () => { setUserInfo(prev => ({ ...prev, preferences: { ...prev.preferences, theme: prev.preferences.theme === 'dark' ? 'light' : 'dark', }, })) } return ( <div className={`min-h-screen transition-colors ${ userInfo.preferences.theme === 'dark' ? 'bg-gray-900 text-white' : 'bg-gray-100 text-gray-900' }`}> <div className="container mx-auto p-4"> <header className="mb-8"> <div className="flex justify-between items-center"> <div> <h1 className="text-3xl font-bold"> 高级 AI 助手 </h1> <p className="text-sm opacity-75 mt-1"> 用户: {userInfo.name} | 角色: {userInfo.role} | 主题: {userInfo.preferences.theme} </p> </div> <button onClick={toggleTheme} className="px-3 py-1 rounded bg-blue-500 text-white hover:bg-blue-600" > 切换主题 </button> </div> </header> <div className={`rounded-lg shadow-lg ${ userInfo.preferences.theme === 'dark' ? 'bg-gray-800' : 'bg-white' }`}> <AgentChatWindow agent={agent} /> </div> <div className="mt-4 flex gap-4 flex-wrap"> <button className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50" onClick={addTimeTool} disabled={tools.some(t => t.name === 'getTime')} > {tools.some(t => t.name === 'getTime') ? '时间工具已添加' : '添加时间工具'} </button> <div className="text-sm bg-gray-200 dark:bg-gray-700 px-3 py-2 rounded"> 当前工具数量: {tools.length} </div> </div> {/* 状态显示面板 */} <div className="mt-4 p-4 bg-gray-50 dark:bg-gray-800 rounded"> <h3 className="font-semibold mb-2">系统状态</h3> <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm"> <div> <strong>用户信息:</strong> <ul className="mt-1 space-y-1"> <li>姓名: {userInfo.name}</li> <li>角色: {userInfo.role}</li> <li>最后活跃: {new Date(userInfo.lastActive).toLocaleTimeString()}</li> </ul> </div> <div> <strong>可用工具:</strong> <ul className="mt-1 space-y-1"> {tools.map((tool, index) => ( <li key={index} className="font-mono text-xs"> {tool.name} </li> ))} </ul> </div> <div> <strong>偏好设置:</strong> <ul className="mt-1 space-y-1"> <li>主题: {userInfo.preferences.theme}</li> <li>语言: {userInfo.preferences.language}</li> </ul> </div> </div> </div> </div> </div> ) } // 注意:在这个示例中,我们使用了Provider是为了演示完整的功能组合 // 在实际应用中,如果不需要隔离,可以移除Provider直接使用默认全局实例 export default AdvancedChatApp ``` ### 预加载消息 使用 `initialMessages` 属性可以在聊天界面初始化时预加载消息: ```tsx import { AgentChatWindow } from '@agent-labs/agent-chat' import { agent } from './agent' import type { Message } from '@ag-ui/client' function PreloadedChat() { // 预加载的消息 const initialMessages: Message[] = [ { id: '1', role: 'system', content: '欢迎使用 AI 助手!', }, { id: '2', role: 'assistant', content: '你好!我是你的 AI 助手,有什么我可以帮助你的吗?', }, ] return ( <AgentChatWindow agent={agent} initialMessages={initialMessages} /> ) } ``` 这个功能在以下场景特别有用: - 显示欢迎消息 - 恢复之前的对话 - 提供使用指南 - 设置初始上下文 ### 程序化消息管理 使用 `addMessages` API 可以程序化地添加消息到聊天界面: ```tsx import { AgentChatCore } from '@agent-labs/agent-chat' import { agent } from './agent' import { useRef } from 'react' import type { AgentChatRef, Message } from '@agent-labs/agent-chat' function ProgrammaticChat() { const chatRef = useRef<AgentChatRef>(null) // 添加批量历史消息(不触发 AI 响应) const loadHistory = async () => { const historyMessages: Message[] = [ { id: '1', role: 'user', content: '你好,我是张三', }, { id: '2', role: 'assistant', content: '你好张三!很高兴认识你。有什么我可以帮助你的吗?', }, { id: '3', role: 'user', content: '我想了解一下你的功能', }, ] await chatRef.current?.addMessages(historyMessages, { triggerAgent: false }) } // 模拟用户输入(触发 AI 响应) const simulateUserInput = async () => { const userMessage: Message = { id: Date.now().toString(), role: 'user', content: '请介绍一下你自己', } await chatRef.current?.addMessages([userMessage], { triggerAgent: true }) } // 注入系统消息 const injectSystemMessage = async () => { const systemMessage: Message = { id: Date.now().toString(), role: 'system', content: '用户当前在移动设备上,请简化你的回答', } await chatRef.current?.addMessages([systemMessage], { triggerAgent: false }) } return ( <div className="min-h-screen bg-gray-100"> <div className="container mx-auto p-4"> <div className="mb-4 flex gap-2"> <button className="px-4 py-2 bg-blue-500 text-white rounded" onClick={loadHistory} > 加载历史记录 </button> <button className="px-4 py-2 bg-green-500 text-white rounded" onClick={simulateUserInput} > 模拟用户输入 </button> <button className="px-4 py-2 bg-orange-500 text-white rounded" onClick={injectSystemMessage} > 注入系统消息 </button> </div> <div className="bg-white rounded-lg shadow-lg"> <AgentChatCore ref={chatRef} agent={agent} className="h-[600px]" /> </div> </div> </div> ) } ``` ## 高级功能 ### Ref API 通过 ref 可以获取到 AgentChat 组件的实例方法: ```tsx import { AgentChatCore } from '@agent-labs/agent-chat' import { agent } from './agent' import { useRef } from 'react' import type { AgentChatRef } from '@agent-labs/agent-chat' function RefExample() { const chatRef = useRef<AgentChatRef>(null) const handleReset = () => { // 重置聊天记录 chatRef.current?.reset() } const handleAddMessages = async () => { // 添加消息 await chatRef.current?.addMessages([ { id: Date.now().toString(), role: 'user', content: '这是通过 ref 添加的消息', } ]) } return ( <div> <div className="mb-4 flex gap-2"> <button className="px-4 py-2 bg-red-500 text-white rounded" onClick={handleReset} > 重置对话 </button> <button className="px-4 py-2 bg-blue-500 text-white rounded" onClick={handleAddMessages} > 添加消息 </button> </div> <AgentChatCore ref={chatRef} agent={agent} className="h-[600px]" /> </div> ) } ``` #### AgentChatRef 方法 | 方法 | 参数 | 返回值 | 描述 | |------|------|--------|------| | reset | - | void | 重置聊天记录,清空所有消息 | | addMessages | messages: Message[], options?: { triggerAgent?: boolean } | Promise<void> | 添加消息到聊天界面 | ### useAgentChat Hook 如果你需要更细粒度的控制,可以直接使用 `useAgentChat` hook: ```tsx import { useAgentChat } from '@agent-labs/agent-chat' import { agent } from './agent' import { useState } from 'react' function CustomChatInterface() { const [input, setInput] = useState('') const { uiMessages, isLoading, sendMessage, addMessages, addToolResult, reset, } = useAgentChat({ agent, tools: [], contexts: [], }) const handleSend = async () => { if (!input.trim()) return await sendMessage(input) setInput('') } const handleAddBatchMessages = async () => { const messages = [ { id: '1', role: 'user' as const, content: '批量消息 1', }, { id: '2', role: 'user' as const, content: '批量消息 2', }, ] // 添加消息但不触发 AI 响应 await addMessages(messages, { triggerAgent: false }) } return ( <div className="flex flex-col h-[600px]"> <div className="flex-1 overflow-y-auto p-4"> {uiMessages.map((message, index) => ( <div key={index} className="mb-4"> <div className="font-semibold">{message.role}:</div> <div>{message.content}</div> </div> ))} </div> <div className="border-t p-4"> <div className="flex gap-2 mb-2"> <button className="px-3 py-1 bg-gray-500 text-white rounded text-sm" onClick={reset} > 重置 </button> <button className="px-3 py-1 bg-blue-500 text-white rounded text-sm" onClick={handleAddBatchMessages} > 批量添加 </button> </div> <div className="flex gap-2"> <input type="text" value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') { handleSend() } }} placeholder="输入消息..." disabled={isLoading} className="flex-1 p-2 border rounded" /> <button onClick={handleSend} disabled={isLoading} className="px-4 py-2 bg-blue-500 text-white rounded" > {isLoading ? '发送中...' : '发送'} </button> </div> </div> </div> ) } ``` #### useAgentChat 返回值 | 属性 | 类型 | 描述 | |------|------|------| | messages | Message[] | 原始消息数组 | | uiMessages | UIMessage[] | 用于 UI 渲染的消息数组 | | isLoading | boolean | 是否正在加载中 | | threadId | string \| null | 当前对话线程 ID | | sendMessage | (content: string) => Promise<void> | 发送消息函数 | | addMessages | (messages: Message[], options?: { triggerAgent?: boolean }) => Promise<void> | 添加消息函数 | | addToolResult | (result: ToolResult, options?: { triggerAgent?: boolean }) => Promise<void> | 添加工具结果函数 | | reset | () => void | 重置聊天记录函数 | ## API 参考 ### AgentChatCore Props | 属性 | 类型 | 必填 | 描述 | |------|------|------|------| | agent | HttpAgent | 是 | HTTP Agent 实例 | | tools | ToolDefinition[] | 否 | 工具定义数组 | | toolRenderers | Record<string, ToolRenderer> | 否 | 工具渲染器映射 | | staticContext | Array<{description: string, value: string}> | 否 | 静态上下文信息 | | className | string | 否 | 自定义 CSS 类名 | | initialMessages | Message[] | 否 | 初始化时预加载的消息数组 | ### AgentChatWindow Props | 属性 | 类型 | 必填 | 描述 | |------|------|------|------| | agent | HttpAgent | 是 | HTTP Agent 实例 | | tools | ToolDefinition[] | 否 | 工具定义数组 | | toolRenderers | Record<string, ToolRenderer> | 否 | 工具渲染器映射 | | staticContext | Array<{description: string, value: string}> | 否 | 静态上下文信息 | | className | string | 否 | 自定义 CSS 类名 | | initialMessages | Message[] | 否 | 初始化时预加载的消息数组 | ### addMessages API `addMessages` 函数允许你程序化地添加消息到聊天界面: #### 参数 | 参数 | 类型 | 必填 | 描述 | |------|------|------|------| | messages | Message[] | 是 | 要添加的消息数组 | | options | { triggerAgent?: boolean } | 否 | 配置选项 | | options.triggerAgent | boolean | 否 | 是否触发 AI 响应,默认为 true | #### 使用场景 1. **加载历史记录**: 设置 `triggerAgent: false`,仅添加消息不触发 AI 2. **模拟用户输入**: 设置 `triggerAgent: true`,模拟用户发送消息 3. **批量导入对话**: 一次性添加多条历史消息 4. **注入上下文**: 动态添加系统消息或背景信息 #### 示例 ```tsx // 添加单条消息并触发 AI 响应 await addMessages([{ id: '1', role: 'user', content: '你好' }]) // 批量添加历史消息,不触发 AI 响应 await addMessages([ { id: '1', role: 'user', content: '历史消息 1' }, { id: '2', role: 'assistant', content: '历史回复 1' }, { id: '3', role: 'user', content: '历史消息 2' }, ], { triggerAgent: false }) // 注入系统消息 await addMessages([{ id: Date.now().toString(), role: 'system', content: '请用简洁的语言回答' }], { triggerAgent: false }) ``` ### 工具定义 工具定义需要符合以下格式: ```typescript interface ToolDefinition { name: string description: string parameters: { type: 'object' properties: Record<string, any> required: string[] } } ``` ### 工具渲染器 工具渲染器需要符合以下格式: ```typescript interface ToolRenderer { render: (toolCall: ToolCall, onResult: (result: ToolResult) => void) => ReactNode definition: ToolDefinition } ``` ## Hooks 参考 ### useProvideAgentContexts 用于提供动态上下文: ```typescript function useProvideAgentContexts(contexts: Context[]): void ``` 这个 hook 允许你在组件中动态提供上下文信息。当 contexts 数组发生变化时,上下文会自动更新。 **说明**: 默认使用全局实例,如需隔离可使用Provider。 ### useProvideAgentToolDefs 用于提供动态工具定义: ```typescript function useProvideAgentToolDefs(toolDefs: ToolDefinition[]): void ``` 这个 hook 允许你在组件中动态提供工具定义。当 toolDefs 数组发生变化时,工具定义会自动更新。 **说明**: 默认使用全局实例,如需隔离可使用Provider。 ### useProvideAgentToolRenderers 用于提供动态工具渲染器: ```typescript function useProvideAgentToolRenderers(toolRenderers: ToolRenderer[]): void ``` 这个 hook 允许你在组件中动态提供工具渲染器。当 toolRenderers 数组发生变化时,工具渲染器会自动更新。 **说明**: 默认使用全局实例,如需隔离可使用Provider。 ### useProvideAgentToolExecutors 用于动态注册工具执行器: ```typescript function useProvideAgentToolExecutors(toolExecutors: Record<string, ToolExecutor>): void ``` **参数说明**: - `toolExecutors`:工具名到执行器的映射 - 支持同步和异步函数 - 组件卸载时自动移除 **说明**: 默认使用全局实例,如需隔离可使用Provider。 详见[动态注册工具执行器](#动态注册工具执行器)小节。 所有hooks默认使用全局实例,无需额外配置。只有在需要多实例隔离时才使用Provider。 ## 故障排除 ### 常见问题 #### 1. 动态资源不生效 **问题**: 使用 `useProvideAgent*` hooks 但工具或上下文没有生效 **解决方法**: - 检查传入的数据格式是否正确 - 验证工具名称是否与执行器名称完全匹配 - 确认 hooks 在组件的正确位置调用 #### 2. 工具执行器不响应 **问题**: 注册了工具执行器但工具调用没有自动执行 **解决方法**: - 确保工具名称与执行器名称完全匹配 - 检查执行器函数是否正确返回 ToolResult - 验证是否在正确的 Provider 范围内 #### 3. 多实例冲突 **问题**: 多个聊天实例之间工具或上下文互相影响 **解决方法**: 为每个聊天实例提供独立的 AgentProvidersProvider ### 技术问题 如果遇到其他问题,请检查: 1. **后端服务**: 确保 Agent 服务正常运行并可访问 2. **Agent URL**: 验证 HttpAgent 的 URL 配置是否正确 3. **工具定义**: 检查 ToolDefinition 是否符合 JSON Schema 规范 4. **网络连接**: 确认客户端与服务器之间的网络连通性 5. **依赖版本**: 确认 `@agent-labs/agent-chat` 和 `@ag-ui/client` 版本兼容 ### 调试技巧 1. **开启浏览器开发者工具**: 查看控制台错误和网络请求 2. **使用 React DevTools**: 检查 Context 的值是否正确传递 3. **添加日志**: 在关键函数中添加 console.log 来跟踪执行流程 ```tsx function DebugExample() { useProvideAgentToolExecutors({ debug: (toolCall) => { console.log('Tool called:', toolCall) return { debug: 'success' } } }) return <AgentChatCore agent={agent} /> } ``` ## 贡献 欢迎提交 Issue 和 Pull Request 来帮助改进这个项目。 ## 许可证 MIT ================================================ FILE: docs/references/tsdown-docs/.vitepress/components/HomePage.vue ================================================ <script setup lang="ts"> import { useData } from 'vitepress' import { onMounted, ref } from 'vue' const { lang } = useData() const sponsors = ref<string>() onMounted(async () => { sponsors.value = await fetch( 'https://cdn.jsdelivr.net/gh/sxzz/sponsors/sponsors.wide.svg', ).then((res) => res.text()) }) </script> <template> <div flex="~ col" items-center justify-center> <div mt20 flex="~ col" items-center gap8> <h2 v-if="lang === 'en'" class="voidzero-title">Brought to you by</h2> <a class="voidzero" href="https://voidzero.dev/" target="_blank" title="voidzero.dev" alt="VoidZero" block h-75px w-300px /> <h2 v-if="lang === 'zh-CN'" class="voidzero-title"> 由 VoidZero 隆重推出 </h2> </div> <div mt12> <div v-if="sponsors" v-html="sponsors" /> <img v-else src="https://cdn.jsdelivr.net/gh/sxzz/sponsors/sponsors.wide.svg" /> </div> </div> </template> <style scoped> .voidzero-title { line-height: 32px; font-size: 24px; font-weight: 600; } .voidzero { background: url(https://voidzero.dev/logo.svg) no-repeat center; background-size: contain; } .dark .voidzero { background-image: url(https://voidzero.dev/logo-white.svg); } :deep(svg) { max-width: 100%; height: auto; } </style> ================================================ FILE: docs/references/tsdown-docs/.vitepress/components/VideoModal.vue ================================================ <script setup lang="ts"> import { onKeyStroke } from '@vueuse/core' import { watch } from 'vue' // SOURCE: https://github.com/rolldown/rolldown/blob/main/docs/.vitepress/theme/components/RolldownVideoModal.vue const VIDEO_ID = 'FF1oZqv_UYo' // https://www.youtube.com/watch?v=FF1oZqv_UYo const isModalVisible = defineModel({ default: false }) // Scroll lock watch( isModalVisible, (value) => { if (!globalThis.document) return const newOverflowValue = value ? 'hidden' : 'auto' document.documentElement.style.overflow = newOverflowValue }, { immediate: true }, ) const openModal = () => { isModalVisible.value = true } const closeModal = () => { isModalVisible.value = false } onKeyStroke('Escape', () => { if (isModalVisible.value) { closeModal() } }) </script> <template> <button class="open-modal-button" @click="openModal"> What is tsdown? <svg class="icon-play" aria-labelledby="simpleicons-play-icon" role="img" viewBox="0 0 100 125" fill="#FFFFFF" > <title id="simpleicons-play-icon" lang="en">Play icon