@allbluecn/web-app 0.27.16 → 0.27.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +43 -32
- package/src/__tests__/integration/harness-conformance.test.ts +164 -0
- package/src/__tests__/integration/harness-log-store.test.ts +436 -0
- package/src/__tests__/integration/harness-media.test.ts +195 -0
- package/src/__tests__/integration/harness-prisma-host.test.ts +219 -0
- package/src/__tests__/integration/harness-session-metadata.test.ts +244 -0
- package/src/__tests__/security/ai/destructive-tool-approval.test.ts +18 -10
- package/src/__tests__/security/ai/prompt-injection.test.ts +3 -2
- package/src/__tests__/security/ai/sandbox-tool-bridge.test.ts +0 -1
- package/src/__tests__/setup.ts +19 -0
- package/src/components/agents/__tests__/agent-bindings-tab.test.tsx +1 -1
- package/src/components/ai/__tests__/ai-prompt-input-attach.test.tsx +5 -3
- package/src/components/ai/__tests__/chat-thread-id-stability.test.tsx +3 -0
- package/src/components/ai/ai-prompt-input/index.tsx +2 -2
- package/src/components/ai/global-harness-sidebar/global-sidebar-connection.tsx +126 -0
- package/src/components/ai/global-harness-sidebar/global-sidebar-context.tsx +438 -0
- package/src/components/ai/global-harness-sidebar/index.tsx +65 -308
- package/src/components/billing/subscription-provider.tsx +3 -2
- package/src/components/design/canvas/document/types.ts +5 -1
- package/src/components/design/editor/collaboration/design-agent-panel.tsx +1 -0
- package/src/components/devtools/devtools-panel.tsx +7 -15
- package/src/components/devtools/unified-devtools.tsx +46 -0
- package/src/components/harness/__tests__/attachment-policy.test.ts +22 -9
- package/src/components/harness/__tests__/composer-draft.test.ts +78 -1
- package/src/components/harness/__tests__/composer-keymap.test.ts +228 -0
- package/src/components/harness/__tests__/composer-paste.test.tsx +109 -0
- package/src/components/harness/__tests__/composer-prefill.test.ts +2 -2
- package/src/components/harness/__tests__/composer-primary-button.test.tsx +205 -0
- package/src/components/harness/__tests__/composer-send.test.tsx +141 -22
- package/src/components/harness/__tests__/composer-takeover.test.tsx +221 -0
- package/src/components/harness/__tests__/gallery-behavior.test.tsx +1 -4
- package/src/components/harness/__tests__/harness-workbench-first-send.test.tsx +125 -10
- package/src/components/harness/__tests__/harness-workbench-mount.test.ts +4 -2
- package/src/components/harness/__tests__/mention-kbid.test.ts +94 -0
- package/src/components/harness/__tests__/submit-machine.test.ts +14 -2
- package/src/components/harness/__tests__/takeover.test.ts +74 -0
- package/src/components/harness/__tests__/use-attachments.test.tsx +185 -0
- package/src/components/harness/ai-chat-history/types.ts +2 -2
- package/src/components/harness/chat-ui.tsx +65 -2
- package/src/components/harness/composer/attachments/attachment-policy.ts +8 -18
- package/src/components/harness/composer/attachments/attachment-tray.tsx +72 -28
- package/src/components/harness/composer/attachments/use-attachments.ts +149 -96
- package/src/components/harness/composer/composer-editor.tsx +127 -25
- package/src/components/harness/composer/composer-keymap.ts +98 -0
- package/src/components/harness/composer/composer-primary-button.tsx +124 -0
- package/src/components/harness/composer/harness-composer.tsx +242 -112
- package/src/components/harness/composer/harness-engine-control.tsx +6 -6
- package/src/components/harness/composer/mention/mention-suggestion-menu.tsx +29 -6
- package/src/components/harness/composer/plus-menu.tsx +100 -0
- package/src/components/harness/composer/submit-machine.ts +12 -4
- package/src/components/harness/composer/takeover.ts +64 -0
- package/src/components/harness/harness-chat-slots.ts +2 -2
- package/src/components/harness/harness-workbench-page.tsx +150 -613
- package/src/components/harness/interrupt-approval.tsx +59 -4
- package/src/components/harness/local-agent/__tests__/agent-tool-card.test.tsx +2 -2
- package/src/components/harness/local-agent/agent-tool-card.tsx +1 -1
- package/src/components/harness/session/__tests__/client-session.test.tsx +154 -0
- package/src/components/harness/session/__tests__/use-harness-chat-adapter.test.ts +187 -0
- package/src/components/harness/session/client-tools-dispatcher.tsx +82 -0
- package/src/components/harness/session/harness-session-appchat.tsx +126 -0
- package/src/components/harness/session/use-harness-chat-adapter.ts +299 -0
- package/src/components/harness/session/use-harness-session.ts +96 -0
- package/src/components/harness/session/view-message-adapter.tsx +174 -0
- package/src/components/harness/workbench/workbench-connection.tsx +165 -0
- package/src/components/harness/workbench/workbench-context.tsx +847 -0
- package/src/components/settings/ai/local-agent-panel.tsx +3 -19
- package/src/components/shared-kit/list-kit/display/__tests__/dropdown.test.tsx +0 -1
- package/src/components/story/ai/__tests__/use-story-ai-model.test.tsx +9 -6
- package/src/components/story/ai/model-types.ts +4 -4
- package/src/components/story/ai/split-dialog.tsx +15 -42
- package/src/components/story/ai/story-ai-panel.tsx +18 -25
- package/src/components/story/ai/use-story-ai-model.ts +5 -26
- package/src/components/story/display/__tests__/display-dropdown.test.tsx +0 -1
- package/src/components/story/inline-editors/labels-editor.tsx +1 -0
- package/src/components/tiptap/__tests__/ai-extension.test.ts +182 -87
- package/src/components/tiptap/extensions/ai-extension.ts +94 -140
- package/src/components/tiptap/node/mention-extension.ts +4 -0
- package/src/components/tiptap/ui/ai-menu/ai-menu.tsx +70 -52
- package/src/design-engine/ai/__tests__/ai.test.ts +133 -0
- package/src/lib/__tests__/harness-gate.test.ts +47 -0
- package/src/lib/__tests__/provider-router.test.ts +0 -3
- package/src/lib/ai/__tests__/story-ai-stream.test.ts +317 -1
- package/src/lib/ai/__tests__/story-prompt.test.ts +2 -2
- package/src/lib/ai/__tests__/tiptap-stream.test.ts +287 -0
- package/src/lib/ai/story-ai-stream.ts +149 -16
- package/src/lib/ai/tiptap-stream.ts +212 -0
- package/src/lib/changelog/sdk-versions.ts +8 -8
- package/src/lib/harness/blob-url.ts +39 -0
- package/src/lib/harness-gate.ts +28 -0
- package/src/lib/queries/local-agents.ts +1 -1
- package/src/paraglide/messages/_index.js +186 -79
- package/src/paraglide/messages/en.js +60 -25
- package/src/paraglide/messages/zh.js +60 -25
- package/src/routeTree.gen.ts +21 -0
- package/src/routes/api/design/prototype/__tests__/route.test.ts +168 -297
- package/src/routes/api/design/prototype/route.ts +65 -259
- package/src/routes/api/generate/__tests__/media.test.ts +70 -85
- package/src/routes/api/generate/media.ts +49 -91
- package/src/routes/api/harness/$.ts +90 -0
- package/src/routes/api/mcp/bugs.ts +6 -5
- package/src/routes/server/__tests__/ai-stream.test.ts +206 -0
- package/src/routes/server/ai-stream.ts +68 -76
- package/src/server/__tests__/agent-crud.test.ts +31 -0
- package/src/server/__tests__/chat-agent-resolve.test.ts +18 -0
- package/src/server/__tests__/chat-list-messages.test.ts +30 -2
- package/src/server/__tests__/entitlements.test.ts +24 -21
- package/src/server/__tests__/sandbox-entitlement.test.ts +5 -6
- package/src/server/__tests__/task-executor.test.ts +33 -22
- package/src/server/agents/__tests__/agent-registry.test.ts +183 -0
- package/src/server/agents/__tests__/agent-stream.test.ts +163 -0
- package/src/server/agents/__tests__/design.server.test.ts +769 -0
- package/src/server/agents/__tests__/gates.server.test.ts +125 -0
- package/src/server/agents/__tests__/knowledge-index.server.test.ts +246 -0
- package/src/server/agents/__tests__/knowledge.server.test.ts +678 -0
- package/src/server/agents/__tests__/media.server.test.ts +309 -0
- package/src/server/agents/__tests__/registry-user-agent.test.ts +228 -0
- package/src/server/agents/__tests__/runtime-subagents.test.ts +225 -0
- package/src/server/agents/__tests__/story.server.test.ts +451 -0
- package/src/server/agents/__tests__/tiptap.server.test.ts +334 -0
- package/src/server/agents/bug-task.server.ts +115 -0
- package/src/server/agents/context.server.ts +31 -0
- package/src/server/agents/design-stream.server.ts +325 -0
- package/src/server/agents/design.server.ts +337 -0
- package/src/server/agents/gates.server.ts +78 -0
- package/src/server/agents/knowledge.server.ts +667 -0
- package/src/server/agents/label-suggest.server.ts +119 -0
- package/src/server/agents/media.server.ts +341 -0
- package/src/server/agents/registry.server.ts +234 -0
- package/src/server/agents/runtime.server.ts +389 -0
- package/src/server/agents/story.server.ts +414 -0
- package/src/server/agents/testcase-generate.server.ts +106 -0
- package/src/server/agents/testcase.server.ts +195 -0
- package/src/server/agents/tiptap.server.ts +198 -0
- package/src/server/agents/translation.server.ts +62 -0
- package/src/server/agents/types.server.ts +99 -0
- package/src/server/ai-gateway/__tests__/adapter-has-ai-key.test.ts +109 -0
- package/src/server/ai-gateway/__tests__/agent-runtime.test.ts +78 -87
- package/src/server/ai-gateway/__tests__/attachment-deref.test.ts +406 -0
- package/src/server/ai-gateway/__tests__/chat-handler-als-identity.test.ts +181 -0
- package/src/server/ai-gateway/__tests__/chat-handler-overrides-model.test.ts +93 -0
- package/src/server/ai-gateway/__tests__/chat-handler-prompt-key.test.ts +11 -7
- package/src/server/ai-gateway/__tests__/chat-prompt-key-drift.test.ts +5 -1
- package/src/server/ai-gateway/__tests__/chat-stream-builder-code-mode.test.ts +12 -0
- package/src/server/ai-gateway/__tests__/chat-stream-builder-memory.test.ts +12 -0
- package/src/server/ai-gateway/__tests__/chat-stream-builder-sandbox.test.ts +17 -2
- package/src/server/ai-gateway/__tests__/chat-stream-builder-skills.test.ts +14 -2
- package/src/server/ai-gateway/__tests__/chat-stream-builder-subagents.test.ts +326 -0
- package/src/server/ai-gateway/__tests__/code-mode-integration-smoke.test.ts +29 -8
- package/src/server/ai-gateway/__tests__/knowledge-scope.test.ts +47 -101
- package/src/server/ai-gateway/__tests__/knowledge-search-fence.test.ts +105 -47
- package/src/server/ai-gateway/__tests__/local-agent-adapter.test.ts +2 -2
- package/src/server/ai-gateway/__tests__/media-transcription-persist.test.ts +21 -4
- package/src/server/ai-gateway/__tests__/message-store.test.ts +12 -0
- package/src/server/ai-gateway/__tests__/rerank.test.ts +31 -5
- package/src/server/ai-gateway/__tests__/retry-duplication-regression.test.ts +224 -0
- package/src/server/ai-gateway/__tests__/runtime.test.ts +0 -3
- package/src/server/ai-gateway/__tests__/story-ai-local.test.ts +2 -2
- package/src/server/ai-gateway/__tests__/tool-error-sanitize.test.ts +7 -6
- package/src/server/ai-gateway/__tests__/tool-pool-sentinel.test.ts +104 -0
- package/src/server/ai-gateway/__tests__/tool-registry.test.ts +0 -1
- package/src/server/ai-gateway/__tests__/tools-authorization.test.ts +141 -67
- package/src/server/ai-gateway/__tests__/tools-select.test.ts +28 -29
- package/src/server/ai-gateway/adapter.ts +33 -6
- package/src/server/ai-gateway/chat-handler.ts +117 -119
- package/src/server/ai-gateway/chat-stream-builder.ts +32 -9
- package/src/server/ai-gateway/chat-subagents.server.ts +82 -0
- package/src/server/ai-gateway/durability/reaper-driver.ts +4 -1
- package/src/server/ai-gateway/embedding.ts +6 -2
- package/src/server/ai-gateway/index.ts +3 -4
- package/src/server/ai-gateway/kb/__tests__/provider-config.test.ts +276 -0
- package/src/server/ai-gateway/kb/provider-config.ts +196 -0
- package/src/server/ai-gateway/local-agent-adapter.ts +17 -18
- package/src/server/ai-gateway/media/__tests__/adapters.spec.ts +72 -0
- package/src/server/ai-gateway/media/__tests__/generation.spec.ts +9 -2
- package/src/server/ai-gateway/media/__tests__/metering.spec.ts +242 -0
- package/src/server/ai-gateway/media/__tests__/provider-config.spec.ts +99 -0
- package/src/server/ai-gateway/media/adapters.ts +15 -4
- package/src/server/ai-gateway/media/index.ts +202 -86
- package/src/server/ai-gateway/media/provider-config.ts +76 -0
- package/src/server/ai-gateway/middlewares/attachment-deref.ts +266 -0
- package/src/server/ai-gateway/middlewares/index.ts +12 -0
- package/src/server/ai-gateway/middlewares/usage-log.ts +7 -2
- package/src/server/ai-gateway/persistence/message-store.ts +30 -1
- package/src/server/ai-gateway/ports.ts +8 -17
- package/src/server/ai-gateway/remote-forward.ts +104 -0
- package/src/server/ai-gateway/rerank.ts +27 -3
- package/src/server/ai-gateway/runs/agent-runtime.ts +58 -43
- package/src/server/ai-gateway/runs/biz-keys.ts +19 -24
- package/src/server/ai-gateway/runs/resolve-overrides.ts +7 -0
- package/src/server/ai-gateway/runs/user-agent.ts +7 -5
- package/src/server/ai-gateway/sandbox/tool-bridge.ts +6 -6
- package/src/server/ai-gateway/story-handler.ts +52 -112
- package/src/server/ai-gateway/tools/__tests__/knowledge-search-tool.test.ts +95 -0
- package/src/server/ai-gateway/tools/definitions.ts +4 -1
- package/src/server/ai-gateway/tools/index.ts +2 -1
- package/src/server/ai-gateway/tools/keys.ts +0 -1
- package/src/server/ai-gateway/tools/knowledge-scope.ts +24 -12
- package/src/server/ai-gateway/tools/registry.ts +0 -2
- package/src/server/ai-gateway/tools/select.ts +16 -15
- package/src/server/ai-gateway/tools/server.ts +73 -145
- package/src/server/ai-gateway/tools.ts +1 -1
- package/src/server/ai-gateway/types.ts +3 -2
- package/src/server/ai-gateway/unified-router.ts +39 -9
- package/src/server/ai-ports.ts +3 -28
- package/src/server/ai-task/executor.ts +20 -12
- package/src/server/bug-report/__tests__/repro-runner.test.ts +41 -29
- package/src/server/bug-report/repro-runner.ts +15 -21
- package/src/server/collab/__tests__/reindex-endpoint.test.ts +11 -0
- package/src/server/collab/__tests__/write-guard-sdk.test.ts +4 -19
- package/src/server/collab/reindex-endpoint.ts +3 -2
- package/src/server/harness/__tests__/access-trusted-context.test.ts +189 -0
- package/src/server/harness/__tests__/agents-assembly.test.ts +65 -0
- package/src/server/harness/__tests__/compaction.server.test.ts +39 -0
- package/src/server/harness/__tests__/credentials.server.test.ts +92 -0
- package/src/server/harness/__tests__/engine-assembly.test.ts +107 -0
- package/src/server/harness/__tests__/gate.server.test.ts +52 -0
- package/src/server/harness/__tests__/git-probe.test.ts +89 -0
- package/src/server/harness/__tests__/workspace-permissions.test.ts +160 -0
- package/src/server/harness/access.server.ts +73 -0
- package/src/server/harness/compaction.server.ts +77 -0
- package/src/server/harness/credentials.server.ts +72 -0
- package/src/server/harness/define.server.ts +213 -0
- package/src/server/harness/gate.server.ts +35 -0
- package/src/server/harness/git-probe.server.ts +76 -0
- package/src/server/harness/host-user.types.ts +11 -0
- package/src/server/harness/host.server.ts +139 -0
- package/src/server/harness/model-catalog.server.ts +56 -0
- package/src/server/harness/permission-mode.server.ts +62 -0
- package/src/server/harness/persistence/artifact-store.server.ts +112 -0
- package/src/server/harness/persistence/blob-store.server.ts +225 -0
- package/src/server/harness/persistence/log-store.server.ts +588 -0
- package/src/server/harness/persistence/log-write-params.ts +15 -0
- package/src/server/harness/persistence/metadata-store.server.ts +80 -0
- package/src/server/harness/persistence/prisma-persistence.server.ts +56 -0
- package/src/server/harness/persistence/session-index-store.server.ts +237 -0
- package/src/server/harness/tool-identity.server.ts +44 -0
- package/src/server/harness/trusted-context.server.ts +86 -0
- package/src/server/harness/web-tools.server.ts +81 -0
- package/src/server/harness/workspace-binder.server.ts +53 -0
- package/src/server/knowledge/__tests__/knowledge-index-core.test.ts +438 -0
- package/src/server/knowledge/__tests__/reindex-guard.test.ts +99 -0
- package/src/server/knowledge/__tests__/search-scope.test.ts +98 -0
- package/src/server/knowledge/knowledge-helpers.ts +0 -7
- package/src/server/knowledge/knowledge-index-utils.ts +193 -69
- package/src/server/knowledge/reindex-guard.ts +24 -0
- package/src/server/knowledge/search-scope.ts +90 -0
- package/src/server/lib/rate-limit.ts +12 -0
- package/src/server/mcp/__tests__/mcp-server.test.ts +382 -0
- package/src/server/mcp/__tests__/tools.test.ts +65 -167
- package/src/server/mcp/mcp-server.ts +261 -0
- package/src/server/mcp/tool-errors.ts +12 -8
- package/src/server/mcp/tools.ts +113 -56
- package/src/server/serverFns/__tests__/knowledge-breadcrumb.test.ts +1 -1
- package/src/server/serverFns/__tests__/knowledge-delete.test.ts +2 -2
- package/src/server/serverFns/__tests__/knowledge-index.test.ts +98 -144
- package/src/server/serverFns/__tests__/knowledge-kb-projects.test.ts +0 -1
- package/src/server/serverFns/__tests__/knowledge-readable-kb.test.ts +1 -1
- package/src/server/serverFns/__tests__/knowledge-search.test.ts +146 -42
- package/src/server/serverFns/__tests__/ownership-merge.test.ts +11 -5
- package/src/server/serverFns/__tests__/update-document-guard.test.ts +18 -2
- package/src/server/serverFns/agents/agent-crud.ts +4 -2
- package/src/server/serverFns/blob-upload.ts +7 -1
- package/src/server/serverFns/chat/conversations.ts +29 -9
- package/src/server/serverFns/chat/list-messages.ts +31 -6
- package/src/server/serverFns/design/ai/fill-annotation.ts +9 -17
- package/src/server/serverFns/design/ai/local-agents.ts +7 -7
- package/src/server/serverFns/harness/__tests__/attach-to-kb.spec.ts +4 -4
- package/src/server/serverFns/harness/__tests__/gallery.spec.ts +73 -12
- package/src/server/serverFns/harness/__tests__/media-prototype.spec.ts +5 -4
- package/src/server/serverFns/harness/__tests__/media.spec.ts +37 -29
- package/src/server/serverFns/harness/attach-to-kb.ts +2 -1
- package/src/server/serverFns/harness/gallery.ts +26 -28
- package/src/server/serverFns/harness/media.ts +48 -105
- package/src/server/serverFns/knowledge-index.ts +22 -65
- package/src/server/serverFns/knowledge.ts +14 -136
- package/src/server/serverFns/story/__tests__/label-suggest-fn.test.ts +102 -37
- package/src/server/serverFns/story/story-crud/label-suggest.ts +12 -2
- package/src/server/serverFns/testcase/__tests__/automation.test.ts +45 -36
- package/src/server/serverFns/testcase/__tests__/generation.test.ts +213 -65
- package/src/server/serverFns/testcase/__tests__/testgen-output.test.ts +38 -21
- package/src/server/serverFns/testcase/automation.ts +17 -26
- package/src/server/serverFns/testcase/generation.ts +60 -83
- package/src/server/serverFns/translation.ts +8 -18
- package/src/server/testcase/__tests__/auto-bug.test.ts +10 -4
- package/src/server/testcase/__tests__/builtin-executor.test.ts +37 -25
- package/src/server/testcase/__tests__/exec-pool.test.ts +17 -37
- package/src/server/testcase/__tests__/triage.test.ts +46 -29
- package/src/server/testcase/builtin-executor.ts +56 -100
- package/src/server/testcase/triage.ts +21 -30
- package/src/shared/design/board.ts +26 -0
- package/src/components/harness/composer/use-composer-submit.ts +0 -82
- package/src/lib/ai/__tests__/story-jsonl.test.ts +0 -198
- package/src/lib/ai/story-jsonl.ts +0 -154
- package/src/server/__tests__/rag.test.ts +0 -139
- package/src/server/ai-gateway/__tests__/delegate-task.test.ts +0 -121
- package/src/server/ai-gateway/tools/delegate-task.ts +0 -111
- package/src/server/mcp/__tests__/json-rpc.test.ts +0 -496
- package/src/server/mcp/json-rpc.ts +0 -178
- package/src/server/mcp/protocol.ts +0 -364
- package/src/server/rag.ts +0 -58
- package/src/server/story/story-crud/label-suggest-core.ts +0 -98
- package/src/shared/design-ai/__tests__/ndjson.test.ts +0 -317
- package/src/shared/design-ai/ndjson.ts +0 -137
|
@@ -1,178 +0,0 @@
|
|
|
1
|
-
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
-
// AllBlue - 理想之海
|
|
3
|
-
// Copyright (C) 2026 AllBlue Contributors
|
|
4
|
-
//
|
|
5
|
-
// This program is free software: you can redistribute it and/or modify
|
|
6
|
-
// it under the terms of the GNU Affero General Public License as published by
|
|
7
|
-
// the Free Software Foundation, either version 3 of the License, or
|
|
8
|
-
// (at your option) any later version.
|
|
9
|
-
//
|
|
10
|
-
// This program is distributed in the hope that it will be useful,
|
|
11
|
-
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
12
|
-
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
13
|
-
// GNU Affero General Public License for more details.
|
|
14
|
-
//
|
|
15
|
-
// You should have received a copy of the GNU Affero General Public License
|
|
16
|
-
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
17
|
-
|
|
18
|
-
// 手写 JSON-RPC 2.0 通用层(任务 20,规格 §10.1)。零依赖、零 IO:
|
|
19
|
-
// body 解析(batch 数组支持)+ 结构校验 + 错误码 + 响应构造。
|
|
20
|
-
// 不引入 @modelcontextprotocol/sdk(其 peer zod ^3 与项目 zod 4 冲突),
|
|
21
|
-
// 无状态子集自实现成本低于依赖治理成本。MCP 语义(initialize 协商、
|
|
22
|
-
// 方法分发、HTTP 状态映射)在 ./protocol.ts。
|
|
23
|
-
|
|
24
|
-
// ── JSON-RPC 2.0 错误码(规范保留段)──
|
|
25
|
-
export const ERR_PARSE_ERROR = -32700;
|
|
26
|
-
export const ERR_INVALID_REQUEST = -32600;
|
|
27
|
-
export const ERR_METHOD_NOT_FOUND = -32601;
|
|
28
|
-
export const ERR_INVALID_PARAMS = -32602;
|
|
29
|
-
export const ERR_INTERNAL_ERROR = -32603;
|
|
30
|
-
|
|
31
|
-
export const JSONRPC_VERSION = "2.0";
|
|
32
|
-
|
|
33
|
-
export type JsonRpcId = string | number | null;
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* 单条 JSON-RPC 消息。`id` 缺省即 notification(规范:无 id 成员 = 通知,
|
|
37
|
-
* 服务端不得回复);`id: null` 是合法请求 id(虽然规范不建议)。
|
|
38
|
-
*/
|
|
39
|
-
export interface JsonRpcMessage {
|
|
40
|
-
id?: JsonRpcId;
|
|
41
|
-
method: string;
|
|
42
|
-
params?: Record<string, unknown> | unknown[];
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export interface JsonRpcErrorObject {
|
|
46
|
-
code: number;
|
|
47
|
-
message: string;
|
|
48
|
-
data?: unknown;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
export interface JsonRpcSuccessResponse {
|
|
52
|
-
jsonrpc: "2.0";
|
|
53
|
-
id: JsonRpcId;
|
|
54
|
-
result: unknown;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
export interface JsonRpcErrorResponse {
|
|
58
|
-
jsonrpc: "2.0";
|
|
59
|
-
id: JsonRpcId;
|
|
60
|
-
error: JsonRpcErrorObject;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
export type JsonRpcResponse = JsonRpcSuccessResponse | JsonRpcErrorResponse;
|
|
64
|
-
|
|
65
|
-
export function jsonRpcSuccess(id: JsonRpcId, result: unknown): JsonRpcSuccessResponse {
|
|
66
|
-
return { jsonrpc: JSONRPC_VERSION, id, result };
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
export function jsonRpcError(
|
|
70
|
-
id: JsonRpcId,
|
|
71
|
-
code: number,
|
|
72
|
-
message: string,
|
|
73
|
-
data?: unknown,
|
|
74
|
-
): JsonRpcErrorResponse {
|
|
75
|
-
return {
|
|
76
|
-
jsonrpc: JSONRPC_VERSION,
|
|
77
|
-
id,
|
|
78
|
-
error: { code, message, ...(data !== undefined ? { data } : {}) },
|
|
79
|
-
};
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
export function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
83
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* 结构校验失败时错误响应可用的 id:能确定就用原 id(string/number/null),
|
|
88
|
-
* 不能确定一律 null(规范:invalid request 时 id 无法确定则为 null)。
|
|
89
|
-
*/
|
|
90
|
-
function extractId(raw: unknown): JsonRpcId {
|
|
91
|
-
if (!isPlainObject(raw) || !("id" in raw)) return null;
|
|
92
|
-
const id = raw.id;
|
|
93
|
-
if (typeof id === "string" || typeof id === "number" || id === null) return id;
|
|
94
|
-
return null;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/** 单条消息校验:非法 → { valid: false, id };合法 → 归一化消息 */
|
|
98
|
-
export type MessageEntry =
|
|
99
|
-
| { valid: true; message: JsonRpcMessage }
|
|
100
|
-
| { valid: false; id: JsonRpcId };
|
|
101
|
-
|
|
102
|
-
const hasStructuredParams = (value: unknown): boolean =>
|
|
103
|
-
Array.isArray(value) || isPlainObject(value);
|
|
104
|
-
|
|
105
|
-
export function validateJsonRpcMessage(raw: unknown): MessageEntry {
|
|
106
|
-
const id = extractId(raw);
|
|
107
|
-
if (!isPlainObject(raw)) return { valid: false, id };
|
|
108
|
-
if (raw.jsonrpc !== JSONRPC_VERSION) return { valid: false, id };
|
|
109
|
-
if (typeof raw.method !== "string") return { valid: false, id };
|
|
110
|
-
// id 成员存在但类型非法(规范仅允许 string | number | null,审计 🟡):
|
|
111
|
-
// 归一为 Invalid Request 而非静默当 notification/请求处理——旧行为
|
|
112
|
-
// `{id: true}` 会被当请求并以 id:null 回包,客户端无法匹配
|
|
113
|
-
if (
|
|
114
|
-
"id" in raw &&
|
|
115
|
-
raw.id !== undefined &&
|
|
116
|
-
typeof raw.id !== "string" &&
|
|
117
|
-
typeof raw.id !== "number" &&
|
|
118
|
-
raw.id !== null
|
|
119
|
-
) {
|
|
120
|
-
return { valid: false, id };
|
|
121
|
-
}
|
|
122
|
-
// params 存在时必须是结构化类型(by-name 对象 / by-position 数组)
|
|
123
|
-
if (raw.params !== undefined && raw.params !== null && !hasStructuredParams(raw.params)) {
|
|
124
|
-
return { valid: false, id };
|
|
125
|
-
}
|
|
126
|
-
const isNotification = raw.id === undefined;
|
|
127
|
-
return {
|
|
128
|
-
valid: true,
|
|
129
|
-
message: {
|
|
130
|
-
method: raw.method,
|
|
131
|
-
...(isNotification ? {} : { id: id as JsonRpcId }),
|
|
132
|
-
...(raw.params !== undefined ? { params: raw.params as Record<string, unknown> | unknown[] } : {}),
|
|
133
|
-
},
|
|
134
|
-
};
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
/** body 解析结果:顶层结构失败(-32700/-32600)或逐条目归一化 */
|
|
138
|
-
export type JsonRpcPayloadParse =
|
|
139
|
-
| { ok: false; code: number; message: string }
|
|
140
|
-
| { ok: true; isBatch: false; entry: MessageEntry }
|
|
141
|
-
| { ok: true; isBatch: true; entries: MessageEntry[] };
|
|
142
|
-
|
|
143
|
-
/**
|
|
144
|
-
* 解析原始 body 文本为 JSON-RPC 消息集(batch 数组支持,规范 2025-03-26 基础集)。
|
|
145
|
-
* - JSON 语法失败 → -32700
|
|
146
|
-
* - 顶层既非对象也非数组 / 空数组 batch → -32600
|
|
147
|
-
* - batch 元素逐条校验,非法元素保留位置以生成对应错误响应条目
|
|
148
|
-
*/
|
|
149
|
-
export function parseJsonRpcPayload(rawText: string): JsonRpcPayloadParse {
|
|
150
|
-
let raw: unknown;
|
|
151
|
-
try {
|
|
152
|
-
raw = JSON.parse(rawText);
|
|
153
|
-
} catch {
|
|
154
|
-
return {
|
|
155
|
-
ok: false,
|
|
156
|
-
code: ERR_PARSE_ERROR,
|
|
157
|
-
message: "Parse error: request body is not valid JSON",
|
|
158
|
-
};
|
|
159
|
-
}
|
|
160
|
-
if (Array.isArray(raw)) {
|
|
161
|
-
if (raw.length === 0) {
|
|
162
|
-
return {
|
|
163
|
-
ok: false,
|
|
164
|
-
code: ERR_INVALID_REQUEST,
|
|
165
|
-
message: "Invalid Request: batch array must not be empty",
|
|
166
|
-
};
|
|
167
|
-
}
|
|
168
|
-
return { ok: true, isBatch: true, entries: raw.map(validateJsonRpcMessage) };
|
|
169
|
-
}
|
|
170
|
-
if (!isPlainObject(raw)) {
|
|
171
|
-
return {
|
|
172
|
-
ok: false,
|
|
173
|
-
code: ERR_INVALID_REQUEST,
|
|
174
|
-
message: "Invalid Request: body must be a JSON-RPC object or batch array",
|
|
175
|
-
};
|
|
176
|
-
}
|
|
177
|
-
return { ok: true, isBatch: false, entry: validateJsonRpcMessage(raw) };
|
|
178
|
-
}
|
|
@@ -1,364 +0,0 @@
|
|
|
1
|
-
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
-
// AllBlue - 理想之海
|
|
3
|
-
// Copyright (C) 2026 AllBlue Contributors
|
|
4
|
-
//
|
|
5
|
-
// This program is free software: you can redistribute it and/or modify
|
|
6
|
-
// it under the terms of the GNU Affero General Public License as published by
|
|
7
|
-
// the Free Software Foundation, either version 3 of the License, or
|
|
8
|
-
// (at your option) any later version.
|
|
9
|
-
//
|
|
10
|
-
// This program is distributed in the hope that it will be useful,
|
|
11
|
-
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
12
|
-
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
13
|
-
// GNU Affero General Public License for more details.
|
|
14
|
-
//
|
|
15
|
-
// You should have received a copy of the GNU Affero General Public License
|
|
16
|
-
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
17
|
-
|
|
18
|
-
// MCP Streamable HTTP 无状态模式协议层(任务 20,规格 §10.1;任务 24 扩 scope 分流):
|
|
19
|
-
// Bearer 鉴权(scope=bug.mcp | test.exec,§8.1 一个 token 只见自己 scope 的 tools)
|
|
20
|
-
// → 限流(120 次/分)→ handleMcpRequest 纯函数(initialize 版本协商 / notifications
|
|
21
|
-
// 202 / ping / tools:list+call 分发表)。不发放 Mcp-Session-Id(无状态);GET SSE
|
|
22
|
-
// 流由路由层 405 拒绝。路由层薄壳(routes/api/mcp/bugs.ts)只做 handler 委托。
|
|
23
|
-
import { prisma } from "@allbluecn/database";
|
|
24
|
-
import { getClientIp } from "@allbluecn/kernel";
|
|
25
|
-
import {
|
|
26
|
-
ERR_INTERNAL_ERROR,
|
|
27
|
-
ERR_INVALID_PARAMS,
|
|
28
|
-
ERR_INVALID_REQUEST,
|
|
29
|
-
ERR_METHOD_NOT_FOUND,
|
|
30
|
-
isPlainObject,
|
|
31
|
-
jsonRpcError,
|
|
32
|
-
jsonRpcSuccess,
|
|
33
|
-
parseJsonRpcPayload,
|
|
34
|
-
type JsonRpcId,
|
|
35
|
-
type JsonRpcMessage,
|
|
36
|
-
type JsonRpcResponse,
|
|
37
|
-
type MessageEntry,
|
|
38
|
-
} from "./json-rpc";
|
|
39
|
-
import { hashToken, isValidTokenFormat } from "@/server/bug-report/tokens";
|
|
40
|
-
import { checkRateLimit } from "@/server/lib/rate-limit";
|
|
41
|
-
import { McpProtocolError } from "./tool-errors";
|
|
42
|
-
import { BUG_MCP_TOOLS, TEST_MCP_TOOLS } from "./tools";
|
|
43
|
-
|
|
44
|
-
// ── 协议常量(§10.1 权威:支持集协商,默认回 2025-03-26)──
|
|
45
|
-
export const SUPPORTED_PROTOCOL_VERSIONS = [
|
|
46
|
-
"2024-11-05",
|
|
47
|
-
"2025-03-26",
|
|
48
|
-
"2025-06-18",
|
|
49
|
-
] as const;
|
|
50
|
-
export const DEFAULT_PROTOCOL_VERSION = "2025-03-26";
|
|
51
|
-
export const MCP_SERVER_INFO = { name: "allblue-bugs", version: "1.0.0" } as const;
|
|
52
|
-
export const MCP_RATE_LIMIT = { max: 120, windowMs: 60_000 } as const;
|
|
53
|
-
// 审计 🟠:batch 放大防护——单 POST batch 条数上限(超限 400 整批拒绝,
|
|
54
|
-
// MCP 规范亦建议拒绝超大 batch),限流按 batch 内消息条数计权
|
|
55
|
-
export const MCP_MAX_BATCH_SIZE = 20;
|
|
56
|
-
// 审计 🟡:请求体上限(自托管无平台 body 上限兜底;1MB 已远超合法 MCP 载荷)
|
|
57
|
-
export const MCP_MAX_BODY_BYTES = 1024 * 1024;
|
|
58
|
-
// 审计 🟡:鉴权前置 per-IP 桶——格式合法的随机 token 可无限触发哈希+唯一索引
|
|
59
|
-
// 查询;与 token 桶同阈值,正常单 token 客户端不受影响
|
|
60
|
-
export const MCP_AUTH_IP_RATE_LIMIT = { max: 120, windowMs: 60_000 } as const;
|
|
61
|
-
|
|
62
|
-
// 服务端自定义错误码(JSON-RPC 规范保留段 -32000..-32099)
|
|
63
|
-
export const CODE_UNAUTHORIZED = -32000;
|
|
64
|
-
export const CODE_RATE_LIMITED = -32001;
|
|
65
|
-
// 任务 24 test 域工具级协议错误(定义于 tool-errors.ts,re-export 供消费方单点导入)
|
|
66
|
-
export { CODE_EXEC_CLAIM_CONFLICT, CODE_EXEC_REPORT_REJECTED } from "./tool-errors";
|
|
67
|
-
|
|
68
|
-
/** token scope → 可见工具表(§8.1:一个 token 只见自己 scope 的 tools) */
|
|
69
|
-
export const TOOLS_BY_SCOPE: Record<string, readonly McpToolDefinition[]> = {
|
|
70
|
-
"bug.mcp": BUG_MCP_TOOLS,
|
|
71
|
-
"test.exec": TEST_MCP_TOOLS,
|
|
72
|
-
};
|
|
73
|
-
|
|
74
|
-
// ── 请求上下文:鉴权结果 + 工具分发表由调用方注入(bug 域六工具 | test 域四工具按 scope)──
|
|
75
|
-
export interface McpAuthContext {
|
|
76
|
-
/** token 绑定项目:工具内一切操作的数据边界(越权访问他项目 BUG 返回工具级错误) */
|
|
77
|
-
projectId: string;
|
|
78
|
-
tokenId: string;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/** 工具返回 MCP content(§10.2);一般错误以 isError: true 表达,test 域两类契约错误(-32001/-32002)例外走 JSON-RPC error */
|
|
82
|
-
export interface McpToolCallResult {
|
|
83
|
-
content: { type: "text"; text: string }[];
|
|
84
|
-
isError?: boolean;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
export interface McpToolDefinition {
|
|
88
|
-
name: string;
|
|
89
|
-
description: string;
|
|
90
|
-
/** 任务 21 用 zod 4 z.toJSONSchema() 生成 */
|
|
91
|
-
inputSchema: Record<string, unknown>;
|
|
92
|
-
handler: (
|
|
93
|
-
args: Record<string, unknown>,
|
|
94
|
-
ctx: McpRequestContext,
|
|
95
|
-
) => Promise<McpToolCallResult>;
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
export interface McpRequestContext {
|
|
99
|
-
auth: McpAuthContext;
|
|
100
|
-
tools: readonly McpToolDefinition[];
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/** 工具分发表(任务 21 bug 域六工具;任务 24 test 域四工具见 TEST_MCP_TOOLS,按 §8.1 scope 分流) */
|
|
104
|
-
export { BUG_MCP_TOOLS } from "./tools";
|
|
105
|
-
|
|
106
|
-
/** 版本协商:请求版本 ∈ 支持集回显,否则回默认 2025-03-26 */
|
|
107
|
-
export function negotiateProtocolVersion(requested: unknown): string {
|
|
108
|
-
const supported = SUPPORTED_PROTOCOL_VERSIONS as readonly string[];
|
|
109
|
-
return typeof requested === "string" && supported.includes(requested)
|
|
110
|
-
? requested
|
|
111
|
-
: DEFAULT_PROTOCOL_VERSION;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
// ── HTTP 响应助手 ──
|
|
115
|
-
const jsonRpcHttpResponse = (status: number, body: unknown) =>
|
|
116
|
-
new Response(JSON.stringify(body), {
|
|
117
|
-
status,
|
|
118
|
-
headers: { "Content-Type": "application/json" },
|
|
119
|
-
});
|
|
120
|
-
|
|
121
|
-
const unauthorizedResponse = (message: string) =>
|
|
122
|
-
new Response(JSON.stringify(jsonRpcError(null, CODE_UNAUTHORIZED, message)), {
|
|
123
|
-
status: 401,
|
|
124
|
-
headers: {
|
|
125
|
-
"Content-Type": "application/json",
|
|
126
|
-
"WWW-Authenticate": 'Bearer realm="allblue-mcp", scope="bug.mcp test.exec"',
|
|
127
|
-
},
|
|
128
|
-
});
|
|
129
|
-
|
|
130
|
-
/**
|
|
131
|
-
* GET 处理(§10.1 权威约束项):无状态模式不提供 GET SSE 流,
|
|
132
|
-
* 按 MCP 规范 2025-03-26 以 405 拒绝并声明可用方法。
|
|
133
|
-
* 独立导出以便路由层委托与单测直接断言(路由薄壳零逻辑)。
|
|
134
|
-
*/
|
|
135
|
-
export function handleMcpGetRequest(): Response {
|
|
136
|
-
return new Response(null, {
|
|
137
|
-
status: 405,
|
|
138
|
-
headers: { Allow: "POST, OPTIONS" },
|
|
139
|
-
});
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
// ── 方法分发(协议核心,纯函数——副作用只可能来自任务 21 的工具 handler)──
|
|
143
|
-
async function dispatchRequest(
|
|
144
|
-
message: JsonRpcMessage,
|
|
145
|
-
ctx: McpRequestContext,
|
|
146
|
-
): Promise<JsonRpcResponse> {
|
|
147
|
-
const id = message.id as JsonRpcId;
|
|
148
|
-
try {
|
|
149
|
-
switch (message.method) {
|
|
150
|
-
case "initialize":
|
|
151
|
-
return handleInitialize(id, message.params);
|
|
152
|
-
case "ping":
|
|
153
|
-
return jsonRpcSuccess(id, {});
|
|
154
|
-
case "tools/list":
|
|
155
|
-
return jsonRpcSuccess(id, {
|
|
156
|
-
tools: ctx.tools.map((tool) => ({
|
|
157
|
-
name: tool.name,
|
|
158
|
-
description: tool.description,
|
|
159
|
-
inputSchema: tool.inputSchema,
|
|
160
|
-
})),
|
|
161
|
-
});
|
|
162
|
-
case "tools/call":
|
|
163
|
-
return await handleToolCall(id, message.params, ctx);
|
|
164
|
-
default:
|
|
165
|
-
return jsonRpcError(id, ERR_METHOD_NOT_FOUND, `Method not found: ${message.method}`);
|
|
166
|
-
}
|
|
167
|
-
} catch (error) {
|
|
168
|
-
console.error("[bug-mcp] request dispatch failed:", error);
|
|
169
|
-
return jsonRpcError(id, ERR_INTERNAL_ERROR, "Internal error");
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
function handleInitialize(
|
|
174
|
-
id: JsonRpcId,
|
|
175
|
-
params: JsonRpcMessage["params"],
|
|
176
|
-
): JsonRpcResponse {
|
|
177
|
-
if (!isPlainObject(params) || typeof params.protocolVersion !== "string") {
|
|
178
|
-
return jsonRpcError(
|
|
179
|
-
id,
|
|
180
|
-
ERR_INVALID_PARAMS,
|
|
181
|
-
"initialize requires params.protocolVersion (string)",
|
|
182
|
-
);
|
|
183
|
-
}
|
|
184
|
-
// 宽容解析:capabilities/clientInfo 规范要求必填,但服务端不消费,缺失不拒
|
|
185
|
-
return jsonRpcSuccess(id, {
|
|
186
|
-
protocolVersion: negotiateProtocolVersion(params.protocolVersion),
|
|
187
|
-
capabilities: { tools: { listChanged: false } },
|
|
188
|
-
serverInfo: { ...MCP_SERVER_INFO },
|
|
189
|
-
});
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
async function handleToolCall(
|
|
193
|
-
id: JsonRpcId,
|
|
194
|
-
params: JsonRpcMessage["params"],
|
|
195
|
-
ctx: McpRequestContext,
|
|
196
|
-
): Promise<JsonRpcResponse> {
|
|
197
|
-
if (!isPlainObject(params) || typeof params.name !== "string") {
|
|
198
|
-
return jsonRpcError(id, ERR_INVALID_PARAMS, "tools/call requires params.name (string)");
|
|
199
|
-
}
|
|
200
|
-
const tool = ctx.tools.find((candidate) => candidate.name === params.name);
|
|
201
|
-
if (!tool) {
|
|
202
|
-
return jsonRpcError(id, ERR_INVALID_PARAMS, `Unknown tool: ${params.name}`);
|
|
203
|
-
}
|
|
204
|
-
const args = isPlainObject(params.arguments) ? params.arguments : {};
|
|
205
|
-
try {
|
|
206
|
-
const result = await tool.handler(args, ctx);
|
|
207
|
-
return jsonRpcSuccess(id, {
|
|
208
|
-
content: result.content,
|
|
209
|
-
...(result.isError ? { isError: true } : {}),
|
|
210
|
-
});
|
|
211
|
-
} catch (error) {
|
|
212
|
-
// 工具级协议错误(任务 24:claim 冲突 -32001 / 非活跃 report -32002):
|
|
213
|
-
// 以 JSON-RPC error 响应表达(规格 §8.2 钉死),非 isError 工具结果
|
|
214
|
-
if (error instanceof McpProtocolError) {
|
|
215
|
-
return jsonRpcError(id, error.code, error.message, error.data);
|
|
216
|
-
}
|
|
217
|
-
throw error; // 交由 dispatchRequest 兜底为 ERR_INTERNAL_ERROR
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
/**
|
|
222
|
-
* JSON-RPC 协议核心(纯函数,ctx 注入鉴权结果与工具表):
|
|
223
|
-
* - 单请求 → 200 单响应;单 notification / 纯 notification batch → 202 空响应
|
|
224
|
-
* - batch 含请求 → 200 响应数组(notification 无条目,元素错误逐位保留)
|
|
225
|
-
* - 结构性失败(-32700/-32600)→ 400 单错误对象
|
|
226
|
-
*/
|
|
227
|
-
export async function handleMcpRequest(
|
|
228
|
-
rawBody: string,
|
|
229
|
-
ctx: McpRequestContext,
|
|
230
|
-
): Promise<Response> {
|
|
231
|
-
const payload = parseJsonRpcPayload(rawBody);
|
|
232
|
-
if (!payload.ok) {
|
|
233
|
-
return jsonRpcHttpResponse(
|
|
234
|
-
400,
|
|
235
|
-
jsonRpcError(null, payload.code, payload.message),
|
|
236
|
-
);
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
const respondToEntry = async (entry: MessageEntry): Promise<Response> => {
|
|
240
|
-
if (!entry.valid) {
|
|
241
|
-
return jsonRpcHttpResponse(
|
|
242
|
-
400,
|
|
243
|
-
jsonRpcError(entry.id, ERR_INVALID_REQUEST, "Invalid Request"),
|
|
244
|
-
);
|
|
245
|
-
}
|
|
246
|
-
if (entry.message.id === undefined) {
|
|
247
|
-
// notification(含 notifications/initialized 等全部 notifications/*):
|
|
248
|
-
// 规范要求服务端不得回复,Streamable HTTP 语义为 202 Accepted 空响应
|
|
249
|
-
return new Response(null, { status: 202 });
|
|
250
|
-
}
|
|
251
|
-
return jsonRpcHttpResponse(200, await dispatchRequest(entry.message, ctx));
|
|
252
|
-
};
|
|
253
|
-
|
|
254
|
-
if (!payload.isBatch) {
|
|
255
|
-
return respondToEntry(payload.entry);
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
// 审计 🟠:超大 batch 整批拒绝(handleMcpPost 已按条数计权限流,此处是
|
|
259
|
-
// 契约层兜底——直接调用本函数的测试/内部路径同样受限)
|
|
260
|
-
if (payload.entries.length > MCP_MAX_BATCH_SIZE) {
|
|
261
|
-
return jsonRpcHttpResponse(
|
|
262
|
-
400,
|
|
263
|
-
jsonRpcError(
|
|
264
|
-
null,
|
|
265
|
-
ERR_INVALID_REQUEST,
|
|
266
|
-
`Invalid Request: batch size ${payload.entries.length} exceeds limit ${MCP_MAX_BATCH_SIZE}`,
|
|
267
|
-
),
|
|
268
|
-
);
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
const responses: JsonRpcResponse[] = [];
|
|
272
|
-
for (const entry of payload.entries) {
|
|
273
|
-
if (!entry.valid) {
|
|
274
|
-
responses.push(jsonRpcError(entry.id, ERR_INVALID_REQUEST, "Invalid Request"));
|
|
275
|
-
continue;
|
|
276
|
-
}
|
|
277
|
-
if (entry.message.id === undefined) continue; // notification 不产生响应条目
|
|
278
|
-
responses.push(await dispatchRequest(entry.message, ctx));
|
|
279
|
-
}
|
|
280
|
-
if (responses.length === 0) {
|
|
281
|
-
return new Response(null, { status: 202 }); // 纯 notification batch
|
|
282
|
-
}
|
|
283
|
-
return jsonRpcHttpResponse(200, responses);
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
/**
|
|
287
|
-
* POST 入口完整处理链:Bearer 鉴权(ProjectAccessToken,scope=bug.mcp|test.exec、
|
|
288
|
-
* 未吊销)→ 限流(按 tokenHash 120 次/60 秒)→ 协议层。鉴权/限流失败是 401/429
|
|
289
|
-
* JSON-RPC error 响应而非异常(MCP 客户端按协议消费错误体)。
|
|
290
|
-
* scope 分流(§8.1):TOOLS_BY_SCOPE 决定该 token 可见的 tools 子集,
|
|
291
|
-
* 未登记 scope(如 bug.report/bug.collect)不授予 MCP 访问。
|
|
292
|
-
*/
|
|
293
|
-
export async function handleMcpPost(request: Request): Promise<Response> {
|
|
294
|
-
// ── 鉴权前置 per-IP 限流(审计 🟡):格式合法的随机 token 在查库被拒之前
|
|
295
|
-
// 先被 per-IP 桶拦下,DB 哈希+唯一索引查询不再无上限;阈值与 token 桶一致,
|
|
296
|
-
// 正常单 token 客户端不受影响 ──
|
|
297
|
-
const ipLimit = checkRateLimit(
|
|
298
|
-
`bug-mcp-auth:${getClientIp(request) ?? "unknown"}`,
|
|
299
|
-
{ ...MCP_AUTH_IP_RATE_LIMIT },
|
|
300
|
-
);
|
|
301
|
-
if (!ipLimit.allowed) {
|
|
302
|
-
return new Response(
|
|
303
|
-
JSON.stringify(jsonRpcError(null, CODE_RATE_LIMITED, "Rate limit exceeded")),
|
|
304
|
-
{ status: 429, headers: { "Content-Type": "application/json" } },
|
|
305
|
-
);
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
// ── 鉴权:Authorization: Bearer <token>(X-Bug-Key 的 Bearer 版口径)──
|
|
309
|
-
const authHeader = request.headers.get("authorization") ?? "";
|
|
310
|
-
const bearer = /^Bearer\s+(.+)$/i.exec(authHeader)?.[1]?.trim() ?? "";
|
|
311
|
-
if (!bearer || !isValidTokenFormat(bearer)) {
|
|
312
|
-
return unauthorizedResponse("Unauthorized: missing or malformed bearer token");
|
|
313
|
-
}
|
|
314
|
-
const token = await prisma.projectAccessToken.findUnique({
|
|
315
|
-
where: { tokenHash: hashToken(bearer) },
|
|
316
|
-
});
|
|
317
|
-
if (!token) return unauthorizedResponse("Unauthorized: invalid token");
|
|
318
|
-
if (token.revokedAt) return unauthorizedResponse("Unauthorized: token revoked");
|
|
319
|
-
const scopeTools = TOOLS_BY_SCOPE[token.scope];
|
|
320
|
-
if (!scopeTools) {
|
|
321
|
-
return unauthorizedResponse("Unauthorized: token scope does not grant MCP access");
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
const rawBody = await request.text();
|
|
325
|
-
// ── 请求体上限(审计 🟡):自托管部署无平台 body 上限兜底 ──
|
|
326
|
-
if (Buffer.byteLength(rawBody) > MCP_MAX_BODY_BYTES) {
|
|
327
|
-
return jsonRpcHttpResponse(
|
|
328
|
-
413,
|
|
329
|
-
jsonRpcError(null, ERR_INVALID_REQUEST, "Invalid Request: payload too large"),
|
|
330
|
-
);
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
// ── 限流(审计 🟠:按消息条数计权而非按 POST 计 1 次——单 POST 塞数千条
|
|
334
|
-
// tools/call 原本只耗 1 个配额,120 次/分钟被批量放大数万倍)──
|
|
335
|
-
const probe = parseJsonRpcPayload(rawBody);
|
|
336
|
-
const weight = probe.ok ? (probe.isBatch ? probe.entries.length : 1) : 1;
|
|
337
|
-
const limit = checkRateLimit(`bug-mcp:${token.tokenHash}`, { ...MCP_RATE_LIMIT }, weight);
|
|
338
|
-
if (!limit.allowed) {
|
|
339
|
-
return new Response(
|
|
340
|
-
JSON.stringify(
|
|
341
|
-
jsonRpcError(null, CODE_RATE_LIMITED, "Rate limit exceeded", {
|
|
342
|
-
retryAfterMs: limit.retryAfterMs,
|
|
343
|
-
}),
|
|
344
|
-
),
|
|
345
|
-
{
|
|
346
|
-
status: 429,
|
|
347
|
-
headers: {
|
|
348
|
-
"Content-Type": "application/json",
|
|
349
|
-
"Retry-After": String(Math.ceil(limit.retryAfterMs / 1000)),
|
|
350
|
-
},
|
|
351
|
-
},
|
|
352
|
-
);
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
// ── lastUsedAt:fire-and-forget,不阻塞响应(照 report-handler 口径)──
|
|
356
|
-
void prisma.projectAccessToken
|
|
357
|
-
.update({ where: { id: token.id }, data: { lastUsedAt: new Date() } })
|
|
358
|
-
.catch(() => {});
|
|
359
|
-
|
|
360
|
-
return handleMcpRequest(rawBody, {
|
|
361
|
-
auth: { projectId: token.projectId, tokenId: token.id },
|
|
362
|
-
tools: scopeTools,
|
|
363
|
-
});
|
|
364
|
-
}
|
package/src/server/rag.ts
DELETED
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
-
// AllBlue - 理想之海
|
|
3
|
-
// Copyright (C) 2026 AllBlue Contributors
|
|
4
|
-
//
|
|
5
|
-
// This program is free software: you can redistribute it and/or modify
|
|
6
|
-
// it under the terms of the GNU Affero General Public License as published by
|
|
7
|
-
// the Free Software Foundation, either version 3 of the License, or
|
|
8
|
-
// (at your option) any later version.
|
|
9
|
-
//
|
|
10
|
-
// This program is distributed in the hope that it will be useful,
|
|
11
|
-
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
12
|
-
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
13
|
-
// GNU Affero General Public License for more details.
|
|
14
|
-
//
|
|
15
|
-
// ⚠ SERVER-ONLY:本模块经 @/server/ai-gateway 挂入 prisma 链,禁止客户端组件 import
|
|
16
|
-
// (原置于 src/lib 同构目录,客户端误引即把服务端依赖拉进浏览器 bundle,审计 🟡 迁出)。
|
|
17
|
-
// You should have received a copy of the GNU Affero General Public License
|
|
18
|
-
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
19
|
-
|
|
20
|
-
import {
|
|
21
|
-
generateEmbedding,
|
|
22
|
-
chunkText,
|
|
23
|
-
rerankCandidates,
|
|
24
|
-
RECALL_MULTIPLIER,
|
|
25
|
-
} from "@/server/ai-gateway"
|
|
26
|
-
import { getVectorStore } from "@/lib/vector-store"
|
|
27
|
-
|
|
28
|
-
export async function indexDocument(
|
|
29
|
-
docId: string,
|
|
30
|
-
content: string,
|
|
31
|
-
table = "design_embeddings",
|
|
32
|
-
aiOpts?: { apiKey?: string; baseUrl?: string }
|
|
33
|
-
): Promise<void> {
|
|
34
|
-
const store = await getVectorStore()
|
|
35
|
-
const chunks = chunkText(content)
|
|
36
|
-
for (let i = 0; i < chunks.length; i++) {
|
|
37
|
-
const embedding = await generateEmbedding(chunks[i], aiOpts)
|
|
38
|
-
await store.insertEmbedding(table, `${docId}-${i}`, chunks[i], embedding, {
|
|
39
|
-
designPageId: docId,
|
|
40
|
-
chunkIndex: i,
|
|
41
|
-
})
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export async function ragSearch(
|
|
46
|
-
query: string,
|
|
47
|
-
table = "design_embeddings",
|
|
48
|
-
limit = 5,
|
|
49
|
-
aiOpts?: { apiKey?: string; baseUrl?: string },
|
|
50
|
-
whereColumn?: string,
|
|
51
|
-
whereValue?: string | string[]
|
|
52
|
-
): Promise<{ id: string; content: string; similarity: number }[]> {
|
|
53
|
-
const store = await getVectorStore()
|
|
54
|
-
const embedding = await generateEmbedding(query, aiOpts)
|
|
55
|
-
const rows = await store.searchByVector(embedding, table, limit * RECALL_MULTIPLIER, whereColumn, whereValue)
|
|
56
|
-
const reranked = await rerankCandidates(query, rows, limit, aiOpts)
|
|
57
|
-
return (reranked ?? rows).slice(0, limit)
|
|
58
|
-
}
|
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
-
// AllBlue - 理想之海
|
|
3
|
-
// Copyright (C) 2026 AllBlue Contributors
|
|
4
|
-
//
|
|
5
|
-
// This program is free software: you can redistribute it and/or modify
|
|
6
|
-
// it under the terms of the GNU Affero General Public License as published by
|
|
7
|
-
// the Free Software Foundation, either version 3 of the License, or
|
|
8
|
-
// (at your option) any later version.
|
|
9
|
-
//
|
|
10
|
-
// This program is distributed in the hope that it will be useful,
|
|
11
|
-
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
12
|
-
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
13
|
-
// GNU Affero General Public License for more details.
|
|
14
|
-
//
|
|
15
|
-
// You should have received a copy of the GNU Affero General Public License
|
|
16
|
-
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
17
|
-
|
|
18
|
-
import { getPrisma } from "@allbluecn/database/get-prisma"
|
|
19
|
-
import {
|
|
20
|
-
hasAiKey,
|
|
21
|
-
runChatAsAgent,
|
|
22
|
-
buildLabelSuggestUserMessage,
|
|
23
|
-
parseLabelSuggestions,
|
|
24
|
-
} from "@/server/ai-gateway"
|
|
25
|
-
import { z } from "zod"
|
|
26
|
-
|
|
27
|
-
const labelSuggestOutputSchema = z.object({
|
|
28
|
-
existing: z.array(z.string()),
|
|
29
|
-
new: z.array(z.string()),
|
|
30
|
-
})
|
|
31
|
-
|
|
32
|
-
const MAX_LABELS_IN_PROMPT = 100
|
|
33
|
-
|
|
34
|
-
export interface SuggestLabelsInput {
|
|
35
|
-
name: string
|
|
36
|
-
description?: string
|
|
37
|
-
currentLabelNames?: string[]
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export interface SuggestLabelsResult {
|
|
41
|
-
existingLabels: { id: string; name: string; color: string }[]
|
|
42
|
-
newNames: string[]
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export async function suggestLabelsCore(
|
|
46
|
-
input: SuggestLabelsInput,
|
|
47
|
-
userId: string,
|
|
48
|
-
): Promise<SuggestLabelsResult> {
|
|
49
|
-
if (!(await hasAiKey(userId))) {
|
|
50
|
-
throw new Error("AI 未配置,请先前往 AI 设置页配置 API Key")
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
const prisma = await getPrisma()
|
|
54
|
-
const allLabels = await prisma.label.findMany({
|
|
55
|
-
select: { id: true, name: true, color: true },
|
|
56
|
-
orderBy: { name: "asc" },
|
|
57
|
-
})
|
|
58
|
-
|
|
59
|
-
let candidates = allLabels
|
|
60
|
-
if (allLabels.length > MAX_LABELS_IN_PROMPT) {
|
|
61
|
-
const usage = await prisma.storyLabel.groupBy({
|
|
62
|
-
by: ["labelId"],
|
|
63
|
-
_count: { _all: true },
|
|
64
|
-
orderBy: { _count: { labelId: "desc" } },
|
|
65
|
-
take: MAX_LABELS_IN_PROMPT,
|
|
66
|
-
})
|
|
67
|
-
const topIds = new Set(usage.map((u) => u.labelId))
|
|
68
|
-
candidates = allLabels.filter((l) => topIds.has(l.id))
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
const names = candidates.map((l) => l.name)
|
|
72
|
-
const raw = await runChatAsAgent(
|
|
73
|
-
"label.suggest",
|
|
74
|
-
[{ role: "user", content: buildLabelSuggestUserMessage(input) }],
|
|
75
|
-
{
|
|
76
|
-
userId,
|
|
77
|
-
temperature: 0.2,
|
|
78
|
-
promptVars: {
|
|
79
|
-
availableLabels: names.length > 0 ? names.join("、") : "(暂无)",
|
|
80
|
-
},
|
|
81
|
-
outputSchema: labelSuggestOutputSchema,
|
|
82
|
-
},
|
|
83
|
-
)
|
|
84
|
-
|
|
85
|
-
const parsed = parseLabelSuggestions(raw, names)
|
|
86
|
-
const byName = new Map(candidates.map((l) => [l.name, l]))
|
|
87
|
-
const existingLabels: { id: string; name: string; color: string }[] = []
|
|
88
|
-
const unmatchedNames: string[] = []
|
|
89
|
-
for (const n of parsed.existing) {
|
|
90
|
-
const l = byName.get(n)
|
|
91
|
-
if (l) existingLabels.push(l)
|
|
92
|
-
else unmatchedNames.push(n)
|
|
93
|
-
}
|
|
94
|
-
return {
|
|
95
|
-
existingLabels,
|
|
96
|
-
newNames: [...parsed.newNames, ...unmatchedNames],
|
|
97
|
-
}
|
|
98
|
-
}
|