diff --git a/.github/workflows/gitleaks.yml b/.github/workflows/gitleaks.yml index ae6b339..2602f85 100644 --- a/.github/workflows/gitleaks.yml +++ b/.github/workflows/gitleaks.yml @@ -1,5 +1,6 @@ # 每次推送和 PR 都用 gitleaks 扫描整个提交历史,发现疑似密钥就让检查失败。 # 与本地的 pre-commit 钩子配合:钩子给提交者即时反馈,这里对所有协作者强制生效。 +# 误报白名单配置见根目录 .gitleaks.toml(下面 env 里显式指定,不依赖自动发现)。 name: Secret scan on: @@ -21,8 +22,11 @@ jobs: with: fetch-depth: 0 - # 个人账号免费使用;仓库迁到组织账号后,需要在仓库 secrets 里配置 GITLEAKS_LICENSE + # 个人账号免费使用;仓库迁到组织账号后,需要在仓库 secrets 里配置 GITLEAKS_LICENSE。 + # gitleaks-action v3.0.0 默认内置 8.24.3,而 .gitleaks.toml 使用的 [[allowlists]] 需要 8.25+,这里固定版本与本地对齐 - name: Run gitleaks uses: gitleaks/gitleaks-action@e0c47f4f8be36e29cdc102c57e68cb5cbf0e8d1e # v3.0.0 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITLEAKS_CONFIG: .gitleaks.toml + GITLEAKS_VERSION: 8.30.1 diff --git a/.gitleaks.toml b/.gitleaks.toml new file mode 100644 index 0000000..d3ab054 --- /dev/null +++ b/.gitleaks.toml @@ -0,0 +1,21 @@ +# gitleaks 配置:沿用默认规则,只放行下面两类经确认的误报。 +# 按「路径 + 内容」登记,而不是按行号(.gitleaksignore 的指纹带行号,改动文件就会失效)。 +# 新增条目前先确认确实不是真实密钥,并写明理由。 +title = "Yoke gitleaks" +minVersion = "v8.25.0" + +[extend] +useDefault = true + +[[allowlists]] +description = "docker-compose.yml 里 Nacos 要求非空的开发用占位值(Base64 解码后是 yoke-local-dev-only-not-a-secret-0123456789),文件注释已写明仅限本地、生产必须换成自己生成的随机值" +condition = "AND" +paths = ['''^docker-compose\.yml$'''] +regexes = ['''^eW9rZS1sb2NhbC1kZXYtb25seS1ub3QtYS1zZWNyZXQtMDEyMzQ1Njc4OQ==$'''] + +[[allowlists]] +description = "测试里故意编造的密码和令牌,用来断言报错信息、日志和 toString 里不会带出它们" +condition = "AND" +paths = ['''^src/test/java/com/yoke/(nacos|config)/[A-Za-z0-9]+Tests\.java$'''] +# 逐个列出测试里实际使用的完整假值,并锚定首尾,不放行含有这些片段的其他字符串 +regexes = ['''^S3cret-Pass-xyz$''', '''^server-token-AAA$''', '''^remote-token-BBB$''', '''^nacos-pass-CCC$''', '''^0123456789abcdef$'''] diff --git a/README.md b/README.md index 4dde0ca..14d734e 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ Yoke is an open-source project of 友客AI (YouKe AI). We read the AgentScope Ja - A built-in `get_weather` tool looks up current weather through the open-source [Open-Meteo](https://open-meteo.com) API, no key needed (the free tier is for non-commercial use only). - Every request builds a temporary `HarnessAgent` and closes it afterwards. Conversation history lives in Redis, so it survives restarts and is shared by all replicas, isolated per `(userId, sessionId)`, and compacted automatically when a conversation gets long. - Tools, knowledge and sub-agents: calculator, clock and per-user notes tools, a `retrieve` tool over a built-in knowledge base that returns citations keyed by stable passage ids such as `[doc-name.md#passage-id]`, external MCP servers over HTTP, and two sub-agents (one declared in code, one declared as a workspace Markdown file). The agent still has no file, shell or web tools, and a logging middleware records a timing trace for every call. +- Interoperability, all off by default: expose the agent as an A2A (Agent2Agent) service, call a remote A2A agent, and wire Nacos for agent-card registration/discovery and prompt hot reload. Actuator exposes only `health`, `info`, `metrics` and `prometheus`. - Models are plugged in through the official AgentScope starters: OpenAI-compatible APIs (works with DashScope, DeepSeek and others), Anthropic, Gemini and Ollama. Switching is a dependency and configuration change. - `local` / `test` / `prod` profiles. In production, a missing API key fails the startup instead of shipping with an empty key. - Virtual threads are enabled by default, for both Tomcat and Spring's default thread pool. @@ -39,7 +40,7 @@ Yoke is an open-source project of 友客AI (YouKe AI). We read the AgentScope Ja Requires JDK 25 and Docker (for the local Redis). ```bash -docker compose up -d # start Redis first; the app refuses to start without it +docker compose up -d redis # start Redis first; the app refuses to start without it (add `nacos` only if you want the Nacos features) sdk env # switch to JDK 25 (if you use sdkman) export ARK_API_KEY=... # the local profile talks to Volcengine Ark (OpenAI-compatible) ./gradlew bootRun # the local profile is active by default @@ -63,7 +64,7 @@ History is stored per `(userId, sessionId)`. Both are optional in the request bo - only `userId`: a new session is created for that user, and its id is returned in the response - neither: a new session under the `default` user -A half-empty pair is never passed on to the framework, because in AgentScope 2.0.4 a missing `sessionId` falls into one shared session named after the agent, and a missing `userId` falls into an anonymous user, which would mix everyone's history together. Both ids may only contain letters, digits, `_`, `.` and `-` (1 to 64 characters, not all dots, so `.` and `..` are rejected); anything else returns 400. The framework joins them as `userId/sessionId`, so allowing `/` would let different pairs collide on one slot, and `userId` also becomes a workspace directory name. There is no authentication yet: `userId` is whatever the caller says, so it is not an identity check. +A half-empty pair is never passed on to the framework, because in AgentScope a missing `sessionId` falls into one shared session named after the agent, and a missing `userId` falls into an anonymous user, which would mix everyone's history together. Both ids may only contain letters, digits, `_`, `.` and `-` (1 to 64 characters, not all dots, so `.` and `..` are rejected); anything else returns 400. The framework joins them as `userId/sessionId`, so allowing `/` would let different pairs collide on one slot, and `userId` also becomes a workspace directory name. There is no authentication yet: `userId` is whatever the caller says, so it is not an identity check. What is stored in Redis, per session (checked against a real model, two turns with one tool call): @@ -129,7 +130,7 @@ data:{"type":"RUN_FINISHED","threadId":"demo","runId":"…"} | `RUN_FINISHED` | The normal end | | `RUN_ERROR` | Reasoning failed; the HTTP status is still 200 and the stream ends normally instead of dropping the connection. The message is the raw exception message and is not redacted, so do not show it to end users directly | -Every stream starts with `RUN_STARTED`, even when the agent cannot be created, and ends with either `RUN_FINISHED` or `RUN_ERROR`, never both. When the agent fails while running, the AG-UI adapter maps the exception to `code` (`TIMEOUT_ERROR`, `INTERRUPTED_ERROR`, `INVALID_INPUT_ERROR` or `INTERNAL_ERROR`); failures outside the adapter, such as the agent not being created, are always `INTERNAL_ERROR`. There is no `done` event and the final text is not repeated: the client concatenates `TEXT_MESSAGE_CONTENT`. The temporary agent is closed when the stream completes, fails or the client disconnects. The adapter's `runTimeout` setting is not read by AgentScope 2.0.4, so it does not limit the run time. +Every stream starts with `RUN_STARTED`, even when the agent cannot be created, and ends with either `RUN_FINISHED` or `RUN_ERROR`, never both. When the agent fails while running, the AG-UI adapter maps the exception to `code` (`TIMEOUT_ERROR`, `INTERRUPTED_ERROR`, `INVALID_INPUT_ERROR` or `INTERNAL_ERROR`); failures outside the adapter, such as the agent not being created, are always `INTERNAL_ERROR`. There is no `done` event and the final text is not repeated: the client concatenates `TEXT_MESSAGE_CONTENT`. The temporary agent is closed when the stream completes, fails or the client disconnects. The adapter's `runTimeout` setting is not read by AgentScope, so it does not limit the run time. > **Breaking change** > The earlier private events (`textDelta`, `toolCall`, `toolResult`, `hint`, `done`, `error`) and the `{"sessionId", "message"}` request body of the streaming endpoint are gone. The streaming endpoint now only accepts `Content-Type: application/json`; requests without a `Content-Type`, or with `text/plain` or `application/*+json`, get 415. `POST /api/chat` now validates `sessionId` with the same rule as `threadId` (non-blank values like `user:42` used to be accepted and now return 400); a blank `sessionId` still starts a new session. @@ -166,14 +167,17 @@ Yoke's own settings use the `yoke.*` prefix: | `yoke.compaction.keep-messages` | Messages kept verbatim after a compaction, default 10. Values `<= 0`, or a keep count not smaller than the trigger count, fall back to the defaults | | `yoke.workspace` | `HarnessAgent` workspace for local files (offloaded messages, memory), default `~/.yoke/workspace`; it stays on the machine and is not shared between replicas | | `yoke.knowledge.embedding.model-name` / `api-key` / `base-url` / `dimensions` / `protocol` | Optional embedding service for vector retrieval. `protocol` defaults to `openai` (OpenAI-compatible `/embeddings`, batchable); use `ark-multimodal` for Volcano Ark multimodal embedding models such as `doubao-embedding-vision-251215` (`/embeddings/multimodal`, one request per text; the `local` profile uses it and reuses `ARK_API_KEY`). Vector retrieval is enabled only when both `model-name` and `api-key` (`YOKE_EMBEDDING_API_KEY`) are set; otherwise retrieval uses keywords only. If the service fails at runtime, retrieval falls back to keywords automatically | +| `yoke.a2a.server.*` | A2A server, **off by default** (`enabled`). `token` (`YOKE_A2A_TOKEN`) is an optional Bearer token, `public-url` is the externally reachable root URL written into the Agent Card, `timeout` defaults to 120s, `card.*` holds name, description, version and skills. See [A2A and Nacos](#a2a-and-nacos) | +| `yoke.a2a.remote.*` | Remote A2A agent to call: `url` (well-known direct) or `agent-name` (discovered through Nacos), plus optional `token` and `timeout` (default 30s). None by default, and then `/api/chat/remote` does not exist | +| `yoke.nacos.*` | Nacos connection (`server-addr` default `127.0.0.1:8848`, `namespace`, `username` / `password` from `YOKE_NACOS_USERNAME` / `YOKE_NACOS_PASSWORD`) and the switches `a2a.enabled` and `prompt.enabled` (+ `prompt.key`), all off by default and independent of each other | | `yoke.mcp.servers[]` | External MCP servers, none by default. Each entry has `name`, `transport` (`sse` or `streamable-http` only), `url`, `timeout` (default 30s) and optional `headers`. `stdio` is rejected and the application fails at startup; so is a server that cannot be reached | -The agent is built without file, shell or web tools. Reading the 2.0.4 source shows that a sub-agent inherits only the file and shell switches, not the web switch, so the web tools are also denied through a `ToolsConfig` deny list (on top of `disableWebTools()` for the main agent), which is applied to the main agent, the built-in `general-purpose` sub-agent and every declared sub-agent. Passing an explicit `ToolsConfig` also stops 2.0.4 from reading `tools.json` from the workspace, which could otherwise declare `stdio` MCP servers (processes started on the host). The read-side memory and session tools (`memory_get`, `memory_search`, `session_history`, `session_list`, `session_search`) are denied by the same list: `memory_get` only checks that a path stays inside the workspace root, not inside the current user's directory, and `session_history` puts model-supplied IDs straight into a path, so they would let the model read other users' memory and sessions. The model sees exactly these tools: Yoke's own (`get_weather`, `get_current_time`, `calculate`, `list_my_notes`, `retrieve`), the framework's memory-writing, skill-loading, async-result, sub-agent and background-task tools (`memory_save` only appends to the fixed `MEMORY.md` and `memory/.md` in the workspace, without a size limit), plus whatever the configured MCP servers publish. `ToolPermissionTests` asserts this list as an exact set, so a framework upgrade that adds a tool fails the build. A `MiddlewareBase` bean is attached to every new agent; `LoggingMiddleware` logs agent, model and tool timings without tool arguments or outputs. OpenTelemetry tracing is not attached by default: add an OpenTelemetry SDK and exporter and register an `OtelTracingMiddleware` bean when you need it. +The agent is built without file, shell or web tools. Reading the AgentScope source shows that a sub-agent inherits only the file and shell switches, not the web switch, so the web tools are also denied through a `ToolsConfig` deny list (on top of `disableWebTools()` for the main agent), which is applied to the main agent, the built-in `general-purpose` sub-agent and every declared sub-agent. Passing an explicit `ToolsConfig` also stops AgentScope from reading `tools.json` from the workspace, which could otherwise declare `stdio` MCP servers (processes started on the host). The read-side memory and session tools (`memory_get`, `memory_search`, `session_history`, `session_list`, `session_search`) are denied by the same list: `memory_get` only checks that a path stays inside the workspace root, not inside the current user's directory, and `session_history` puts model-supplied IDs straight into a path, so they would let the model read other users' memory and sessions. The model sees exactly these tools: Yoke's own (`get_weather`, `get_current_time`, `calculate`, `list_my_notes`, `retrieve`), the framework's memory-writing, skill-loading, async-result, sub-agent and background-task tools (`memory_save` only appends to the fixed `MEMORY.md` and `memory/.md` in the workspace, without a size limit), plus whatever the configured MCP servers publish. `ToolPermissionTests` asserts this list as an exact set, so a framework upgrade that adds a tool fails the build. A `MiddlewareBase` bean is attached to every new agent; `LoggingMiddleware` logs agent, model and tool timings without tool arguments or outputs. OpenTelemetry tracing is not attached by default: add an OpenTelemetry SDK and exporter and register an `OtelTracingMiddleware` bean when you need it. ## Tools, Knowledge and Sub-agents - **Tools** (`com.yoke.tool`): plain classes with `@Tool` methods, registered once into a shared `Toolkit`. `calculate` uses a hand-written recursive-descent parser (no script engine, input length and nesting limits, division by zero reported as text). `list_my_notes` takes a `UserContext` parameter without `@ToolParam`: the framework injects it by type from the request's `RuntimeContext`, so the model never sees or forges the user id. -- **Retrieval**: the `retrieve` tool searches `src/main/resources/knowledge/*.md` and returns passages labelled with a stable id such as `[doc-name.md#passage-id]` (document name plus a digest of the passage text, so editing a passage changes its id and old citations never point at different text; two knowledge documents with the same file name in different classpath roots fail the startup) plus their source, which the model is asked to cite verbatim (ids stay unique across repeated retrievals in one conversation, unlike per-call `[1]`, `[2]` counters). It is the only retrieval channel; the framework's `knowledge()` auto-injection is deliberately not used. Retrieval is layered behind the application's own `RetrievePort` (no framework types): BM25 keyword search is always available, and with an embedding service configured a vector channel is added and the two are fused with RRF (constant 60); if one channel fails the other is used. Note that with embeddings enabled, user queries and the knowledge-base text are sent to the embedding provider. The framework's own `rag-simple` module is not used: the `core/rag` package is `@Deprecated(forRemoval = true)` in 2.0.4 and the module drags in Qdrant, Milvus, Elasticsearch, PostgreSQL, PDFBox, POI, Tika and more. +- **Retrieval**: the `retrieve` tool searches `src/main/resources/knowledge/*.md` and returns passages labelled with a stable id such as `[doc-name.md#passage-id]` (document name plus a digest of the passage text, so editing a passage changes its id and old citations never point at different text; two knowledge documents with the same file name in different classpath roots fail the startup) plus their source, which the model is asked to cite verbatim (ids stay unique across repeated retrievals in one conversation, unlike per-call `[1]`, `[2]` counters). It is the only retrieval channel; the framework's `knowledge()` auto-injection is deliberately not used. Retrieval is layered behind the application's own `RetrievePort` (no framework types): BM25 keyword search is always available, and with an embedding service configured a vector channel is added and the two are fused with RRF (constant 60); if one channel fails the other is used. Note that with embeddings enabled, user queries and the knowledge-base text are sent to the embedding provider. The framework's own `rag-simple` module is not used: the `core/rag` package is `@Deprecated(forRemoval = true)` in AgentScope and the module drags in Qdrant, Milvus, Elasticsearch, PostgreSQL, PDFBox, POI, Tika and more. - **MCP**: only HTTP transports are accepted. Example: ```yaml @@ -188,27 +192,75 @@ The agent is built without file, shell or web tools. Reading the 2.0.4 source sh Authorization: Bearer ${MCP_DOCS_TOKEN} ``` - Tools appear under the names the server publishes. In 2.0.4 an MCP tool runs without confirmation only if the server marks it `readOnlyHint`, and Yoke's HTTP API has no human confirmation channel (the turn would otherwise end silently at the tool call with an empty reply). So only tools declared read-only are registered; the others are skipped (their names are logged at INFO) and neither the main agent nor any sub-agent ever sees them. A published tool whose name clashes with one of Yoke's tools or with a Harness built-in (`memory_save`, `agent_spawn` and so on, which are only added when each request builds its agent) fails the startup. -- **Sub-agents**: `summarizer` is declared in code (`YokeSubagents`) with no tools; `kb-researcher` is declared by `src/main/resources/workspace/subagents/kb-researcher.md`, copied into `yoke.workspace/subagents/` at startup, and may only use `retrieve`. 2.0.4 silently lets a workspace file override a code declaration with the same id (and `general-purpose.md` would replace the built-in one), so Yoke scans the files actually present in `yoke.workspace/subagents/` (including leftovers and hand-placed ones, not just the shipped ones) and fails at startup on any such clash. + Tools appear under the names the server publishes. In AgentScope an MCP tool runs without confirmation only if the server marks it `readOnlyHint`, and Yoke's HTTP API has no human confirmation channel (the turn would otherwise end silently at the tool call with an empty reply). So only tools declared read-only are registered; the others are skipped (their names are logged at INFO) and neither the main agent nor any sub-agent ever sees them. A published tool whose name clashes with one of Yoke's tools or with a Harness built-in (`memory_save`, `agent_spawn` and so on, which are only added when each request builds its agent) fails the startup. +- **Sub-agents**: `summarizer` is declared in code (`YokeSubagents`) with no tools; `kb-researcher` is declared by `src/main/resources/workspace/subagents/kb-researcher.md`, copied into `yoke.workspace/subagents/` at startup, and may only use `retrieve`. AgentScope silently lets a workspace file override a code declaration with the same id (and `general-purpose.md` would replace the built-in one), so Yoke scans the files actually present in `yoke.workspace/subagents/` (including leftovers and hand-placed ones, not just the shipped ones) and fails at startup on any such clash. To use another model, replace `agentscope-openai-spring-boot-starter` in `build.gradle` with the matching starter (dashscope, anthropic, gemini or ollama) and change `agentscope.model.provider`. +## A2A and Nacos + +Everything in this section is **off by default**. + +### A2A server + +```bash +export YOKE_A2A_TOKEN=$(openssl rand -hex 24) +./gradlew bootRun --args='--yoke.a2a.server.enabled=true --yoke.a2a.server.public-url=http://localhost:8080' +``` + +Two endpoints appear: `GET /.well-known/agent-card.json` (public) and `POST /a2a` (JSON-RPC, `message/send` only). The contract is documented in `A2aApi`. + +> **Warning** +> Turning it on exposes an **unauthenticated** entry point equivalent to `/api/chat` (same tools, same history store), and the caller can claim any `userId`. In production put it behind a gateway, or at least set `yoke.a2a.server.token`: the JSON-RPC endpoint then requires `Authorization: Bearer ` (constant-time comparison, 401 otherwise) and the Agent Card declares the Bearer scheme. Without a token nothing is checked and a WARN is logged at startup. + +- Protocol: AgentScope ships A2A 0.3 (SDK `0.3.3.Final`, `protocolVersion` `0.3.0`), JSON-RPC transport only. This holds for the AgentScope release Yoke is built on; newer AgentScope releases moved to A2A 1.0 and dropped 0.3, so check the manual of the version you use. +- Transport security: the Bearer token travels in clear text over plain HTTP, and `public-url` defaults to `http://localhost:`. In production use an `https` public URL or terminate TLS at a gateway. A token shorter than 16 characters fails the startup. Request bodies above `yoke.a2a.server.max-body-bytes` (default 256 KB) get `413` (body: JSON-RPC `-32600`): authentication happens before the body is read, an oversized declared `Content-Length` is rejected without reading, and chunked requests are read with a cap; `/api/chat` has no such custom limit. Only the synchronous `message/send` is served (the card says `streaming: false`); `message/stream` and `tasks/resubscribe` return "unsupported operation", other methods "method not found". +- Sessions: `sessionId` is `metadata.sessionId`, else `contextId`, else a new one; `userId` is `metadata.userId` or `default`. Both follow the same `@SafeId` rules as the HTTP API and illegal values are rejected with `-32602`. The `contextId` in the response is the session id, send it back to continue. +- Failures come back as a JSON-RPC `-32603` with a fixed message, never the exception text. +- The official `agentscope-a2a-spring-boot-starter` is not used: it only wires `ReActAgent`, ships controllers without authentication and hard-codes `streaming: true` in the card. + +### Calling a remote A2A agent + +Set `yoke.a2a.remote.url` (or `agent-name` together with `yoke.nacos.a2a.enabled=true`) and `POST /api/chat/remote` appears: `{"sessionId": "...", "message": "..."}`. The target comes only from configuration, never from the request body. For a direct URL **every** address in the remote Agent Card (`url` and each `additionalInterfaces` entry) must have the same origin as the configured URL and the preferred transport must be JSONRPC, otherwise the call is refused (the official client picks the JSON-RPC address from the preferred transport and the additional interfaces, so checking `url` alone can be bypassed). The HTTP client does not follow redirects and has a request timeout. Failures are `502` (`504` on timeout); the response never contains addresses or credentials. This endpoint is also unauthenticated. It is deliberately not exposed to the model as a tool, so remote content cannot steer the model. + +### Nacos + +```bash +docker compose up -d redis nacos # Nacos 3.x standalone, pinned to v3.2.1-2026.03.30 +export YOKE_NACOS_ADDR=127.0.0.1:8848 +./gradlew bootRun --args='--yoke.nacos.prompt.enabled=true --yoke.nacos.a2a.enabled=true --yoke.a2a.server.enabled=true' +``` + +- One gRPC channel carries all the data and needs Nacos 3.x (client port = main port + 1000, default 9848). With any switch on, startup probes the channel and fails with a clear message (no credentials in it) if it cannot be used. +- `yoke.nacos.a2a.enabled`: registers the Agent Card and endpoint once the app is ready (and deregisters on shutdown) when the A2A server is on; discovers the remote agent by `yoke.a2a.remote.agent-name`. +- `yoke.nacos.prompt.enabled`: every turn pulls the prompt `yoke.nacos.prompt.key` from Nacos and appends it after the built-in system prompt (no duplication; if the pull fails, the built-in prompt is used unchanged). A new version takes effect on the next turn after a short server-side delay (25 to 270 ms measured against the compose image). +- Trust boundary: whoever can write the prompt key in Nacos can change Yoke's system prompt (it is appended after the built-in prompt, and sub-agents get it too, as measured). Keep the source trusted and enable Nacos authentication in production. Each pull has a timeout (`yoke.nacos.prompt.timeout`, default 2s); on timeout or failure the built-in prompt is used and the warning is rate-limited. +- The Nacos client's logs and snapshot cache are redirected to `/nacos` (`JM.LOG.PATH`, `JM.SNAPSHOT.PATH`) instead of `~/logs/nacos` and `~/nacos`. The client's own login-failure log line still shows a partially masked password. +- Skill hosting (`nacos-skill`) is not wired in. +- `docker-compose.yml` turns Nacos authentication off for local development only; production must enable authentication and replace the placeholder keys. + +### Observability + +Actuator exposes exactly `health`, `info`, `metrics` and `prometheus` (asserted by `ActuatorExposureTests`); `env`, `heapdump` and the like are not exposed. `health` includes Redis but shows no details. These endpoints share the port with the API and have no authentication either: put them behind a gateway, or move them to an internal port with `MANAGEMENT_SERVER_PORT`. + ## Project Structure ``` src/main/java/com/yoke/ ├── YokeApplication.java Application entry point -├── api/ HTTP contract (ChatApi: paths, validation and docs live here) +├── a2a/ A2A server gateway, runner and remote client (a2a/runner adapts HarnessAgent to the A2A AgentRunner) +├── api/ HTTP contract (ChatApi, A2aApi, RemoteChatApi: paths, validation and docs live here) ├── codec/ Conversion between domain types and framework types (MessageCodec, AguiStreamCodec, HintEventConverter) -├── config/ Agent, Redis, AG-UI adapter, tool, knowledge and sub-agent configuration (HarnessAgentFactory, YokeProperties, YokeSubagents) -├── controller/ Contract implementation (ChatController) +├── config/ Agent, Redis, AG-UI, A2A, Nacos, tool, knowledge and sub-agent configuration (HarnessAgentFactory, YokeProperties, YokeSubagents) +├── controller/ Contract implementation (ChatController, A2aController, RemoteChatController) ├── knowledge/ Retrieval port and implementations: keyword, vector, RRF fusion (no framework types) ├── mcp/ Connections to external MCP servers (HTTP transports only) ├── middleware/ Agent middlewares (LoggingMiddleware) -├── model/ Request and response objects (ChatRequest, ChatResponse) -└── tool/ Tools exposed to the model (WeatherTool, ChatTools, RetrieveTool, UserContext) +├── nacos/ Nacos client probe, A2A registration, prompt hot-reload middleware +├── model/ Domain, request and response objects (ChatRequest, ChatResponse, RemoteChatRequest, SafeId, UserContext, Passage) +└── tool/ Tools exposed to the model (WeatherTool, ChatTools, RetrieveTool, SharedToolkit) src/main/resources/ application.yml, the per-profile configuration, knowledge/*.md and workspace/subagents/*.md -docker-compose.yml Local Redis, also used by the integration tests +docker-compose.yml Local Redis and Nacos, also used by the integration tests docs/brand/ Logo ``` @@ -218,7 +270,7 @@ docs/brand/ Logo ## Contributing -Issues and pull requests are welcome. AgentScope message and event types must not leak out of `codec` (and `middleware`, whose hook signatures need them), and the `knowledge` package must stay free of AgentScope types; `ArchitectureTests` enforces this. Before submitting, run `./gradlew build` and make sure all tests pass. Code comments are written in Chinese. +Issues and pull requests are welcome. AgentScope message and event types must not leak out of `codec` (and `middleware`, whose hook signatures need them), the `knowledge` package must stay free of AgentScope types, and `a2a` / `nacos` may only use an explicit allow-list of framework types; `ArchitectureTests` enforces this. Before submitting, run `./gradlew build` and make sure all tests pass. Code comments are written in Chinese. The Nacos integration tests start the `nacos` service from `docker-compose.yml` (slow to pull the first time). ## License diff --git a/README_CN.md b/README_CN.md index eff3a0f..9ce429d 100644 --- a/README_CN.md +++ b/README_CN.md @@ -30,6 +30,7 @@ Yoke 是友客AI的开源项目。大家一起读 AgentScope Java V2 和 Spring - 内置 `get_weather` 工具,通过开源的 [Open-Meteo](https://open-meteo.com) 查当前天气,免密钥(免费版仅限非商业使用)。 - 每次请求新建一个临时 `HarnessAgent`,用完即关闭。对话历史存在 Redis 里,重启不丢,多个副本共享,按 `(userId, sessionId)` 隔离,对话过长时自动压缩。 - 工具、知识库与子 Agent:计算器、时钟、按用户隔离的笔记工具,基于内置知识库的 `retrieve` 工具(返回带稳定片段编号的引用,形如 `[文档名.md#片段编号]`),通过 HTTP 接入外部 MCP 服务,以及两个子 Agent(一个在代码里声明,一个由工作区 Markdown 文件声明)。Agent 仍不开放文件、命令和联网工具,日志中间件为每次调用记录耗时轨迹。 +- 互通能力,全部默认关闭:把 Agent 暴露成 A2A(Agent2Agent)服务、调用远端 A2A Agent、接入 Nacos 做 Agent Card 注册发现和 Prompt 热更新。Actuator 只暴露 `health`、`info`、`metrics`、`prometheus`。 - 通过 AgentScope 官方 starter 接入各种模型:OpenAI 兼容协议(可对接 DashScope、DeepSeek 等)、Anthropic、Gemini、Ollama,换依赖和配置即可。 - 有 local / test / prod 多环境配置;生产环境缺少密钥时启动即失败,避免带着空密钥上线。 - 默认开启虚拟线程,Tomcat 和 Spring 默认线程池都使用虚拟线程。 @@ -39,7 +40,7 @@ Yoke 是友客AI的开源项目。大家一起读 AgentScope Java V2 和 Spring 需要 JDK 25 和 Docker(用于本地 Redis)。 ```bash -docker compose up -d # 先启动 Redis;没有 Redis 应用无法启动 +docker compose up -d redis # 先启动 Redis;没有 Redis 应用无法启动(要用 Nacos 相关功能再加上 `nacos`) sdk env # 切换到 JDK 25(使用 sdkman 时) export ARK_API_KEY=... # local 环境接火山方舟(OpenAI 兼容协议) ./gradlew bootRun # 默认激活 local 环境 @@ -63,7 +64,7 @@ curl -X POST localhost:8080/api/chat \ - 只传 `userId`:为该用户新建一个会话,新的会话 ID 在响应里返回 - 都不传:`default` 用户下新建会话 -不会把「只给其一」直接交给框架:AgentScope 2.0.4 里缺 `sessionId` 会落到以 Agent 名称命名的共享会话,缺 `userId` 会落到匿名用户,所有调用方的历史会混在一起。两个标识只能包含字母、数字、`_`、`.`、`-`,长度 1 到 64,且不能全是点(`.`、`..` 会被拒绝),否则返回 400。原因是框架把槽位拼成 `userId/sessionId`,允许 `/` 会让不同的一对撞到同一个槽位,`userId` 还会成为工作区的目录名。目前没有鉴权,`userId` 由调用方自报,不是身份校验。 +不会把「只给其一」直接交给框架:AgentScope 里缺 `sessionId` 会落到以 Agent 名称命名的共享会话,缺 `userId` 会落到匿名用户,所有调用方的历史会混在一起。两个标识只能包含字母、数字、`_`、`.`、`-`,长度 1 到 64,且不能全是点(`.`、`..` 会被拒绝),否则返回 400。原因是框架把槽位拼成 `userId/sessionId`,允许 `/` 会让不同的一对撞到同一个槽位,`userId` 还会成为工作区的目录名。目前没有鉴权,`userId` 由调用方自报,不是身份校验。 每个会话在 Redis 里存了什么(用真实模型实测:两轮对话,其中一轮调用了工具): @@ -129,7 +130,7 @@ data:{"type":"RUN_FINISHED","threadId":"demo","runId":"…"} | `RUN_FINISHED` | 正常结束 | | `RUN_ERROR` | 推理出错;HTTP 状态码仍是 200,流正常结束而不是断开连接。message 是原样的异常信息,未做脱敏,不要直接展示给终端用户 | -每次流都以 `RUN_STARTED` 开头(创建 Agent 失败时也一样),以 `RUN_FINISHED` 或 `RUN_ERROR` 结尾,二者不会同时出现。Agent 运行中出错时,`RUN_ERROR` 的 `code` 由 AG-UI 适配器按异常类型映射(`TIMEOUT_ERROR`、`INTERRUPTED_ERROR`、`INVALID_INPUT_ERROR` 或 `INTERNAL_ERROR`);适配器之外的失败(例如创建 Agent 失败)一律是 `INTERNAL_ERROR`。没有 `done` 事件,也不重复最终全文:由客户端拼接 `TEXT_MESSAGE_CONTENT`。流正常结束、出错或客户端断开时,临时 Agent 都会被关闭。适配器的 `runTimeout` 配置在 AgentScope 2.0.4 里没有被读取,所以它不能限制运行时长。 +每次流都以 `RUN_STARTED` 开头(创建 Agent 失败时也一样),以 `RUN_FINISHED` 或 `RUN_ERROR` 结尾,二者不会同时出现。Agent 运行中出错时,`RUN_ERROR` 的 `code` 由 AG-UI 适配器按异常类型映射(`TIMEOUT_ERROR`、`INTERRUPTED_ERROR`、`INVALID_INPUT_ERROR` 或 `INTERNAL_ERROR`);适配器之外的失败(例如创建 Agent 失败)一律是 `INTERNAL_ERROR`。没有 `done` 事件,也不重复最终全文:由客户端拼接 `TEXT_MESSAGE_CONTENT`。流正常结束、出错或客户端断开时,临时 Agent 都会被关闭。适配器的 `runTimeout` 配置在 AgentScope 里没有被读取,所以它不能限制运行时长。 > **不兼容变更** > 流式接口原先的私有事件(`textDelta`、`toolCall`、`toolResult`、`hint`、`done`、`error`)和 `{"sessionId", "message"}` 请求体已经移除。流式接口现在只接受 `Content-Type: application/json`,不带 `Content-Type`、或者用 `text/plain`、`application/*+json` 的请求都会返回 415。`POST /api/chat` 的 `sessionId` 现在按 `threadId` 的同一条规则校验(以前 `user:42` 这类非空白值能通过,现在返回 400);空白的 `sessionId` 仍然新建会话。 @@ -166,14 +167,17 @@ Yoke 自己的配置使用 `yoke.*` 前缀: | `yoke.compaction.keep-messages` | 压缩后原样保留的最近条数,默认 10。小于等于 0,或保留条数不小于触发条数时,回落到默认值 | | `yoke.workspace` | `HarnessAgent` 的工作区,放本地文件(转存的消息、记忆),默认 `~/.yoke/workspace`;只在本机,副本之间不共享 | | `yoke.knowledge.embedding.model-name` / `api-key` / `base-url` / `dimensions` / `protocol` | 可选的向量化服务,用于向量检索。`protocol` 默认 `openai`(OpenAI 兼容的 `/embeddings`,可批量);火山方舟的多模态向量模型(如 `doubao-embedding-vision-251215`)要写 `ark-multimodal`(`/embeddings/multimodal`,一条文本一次请求,`local` 环境默认就是它,复用 `ARK_API_KEY`)。`model-name` 和 `api-key`(`YOKE_EMBEDDING_API_KEY`)都有值才启用向量检索,否则只用关键词检索;运行中向量化服务出错时自动退回关键词检索 | +| `yoke.a2a.server.*` | A2A 服务端,**默认关闭**(`enabled`)。`token`(`YOKE_A2A_TOKEN`)是可选的 Bearer Token,`public-url` 是写进 Agent Card 的对外根地址,`timeout` 默认 120 秒,`card.*` 是名字、描述、版本和技能。详见 [A2A 与 Nacos](#a2a-与-nacos) | +| `yoke.a2a.remote.*` | 要调用的远端 A2A Agent:`url`(well-known 直连)或 `agent-name`(经 Nacos 发现),另有可选的 `token` 和 `timeout`(默认 30 秒)。默认都不配置,此时 `/api/chat/remote` 不存在 | +| `yoke.nacos.*` | Nacos 连接(`server-addr` 默认 `127.0.0.1:8848`、`namespace`、`username` / `password` 来自环境变量 `YOKE_NACOS_USERNAME` / `YOKE_NACOS_PASSWORD`)和开关 `a2a.enabled`、`prompt.enabled`(及 `prompt.key`),全部默认关闭且互不绑定 | | `yoke.mcp.servers[]` | 外部 MCP 服务,默认一个也不接。每项有 `name`、`transport`(只能是 `sse` 或 `streamable-http`)、`url`、`timeout`(默认 30 秒)和可选的 `headers`。配置 `stdio` 会让应用启动失败;服务连不上同样启动失败 | -Agent 创建时不开放文件、命令和联网工具。读 2.0.4 源码发现子 Agent 只继承文件和 shell 的关闭、不继承联网工具的关闭,所以联网工具除了主 Agent 的 `disableWebTools()`,还用 `ToolsConfig` 的 deny 名单禁掉,它同时作用于主 Agent、内置的 `general-purpose` 子 Agent 和所有声明的子 Agent。显式传入 `ToolsConfig` 还会让 2.0.4 不再去读工作区里的 `tools.json`(那个文件可以声明 `stdio` MCP 服务,也就是在宿主机上启动进程)。读类的记忆和会话工具(`memory_get`、`memory_search`、`session_history`、`session_list`、`session_search`)也被同一份 deny 名单拒绝:`memory_get` 只校验路径不越出工作区根目录、不校验是否在当前用户目录下,`session_history` 把模型给的 ID 直接拼进路径,开着就能让模型读到别的用户的记忆和会话。模型看到的工具恰好是:Yoke 自己的(`get_weather`、`get_current_time`、`calculate`、`list_my_notes`、`retrieve`),框架的写记忆、技能加载、异步结果、子 Agent 和后台任务类工具(`memory_save` 只往工作区固定的 `MEMORY.md` 与 `memory/<日期>.md` 追加,内容没有大小限制),再加上所配置的 MCP 服务公布的工具。`ToolPermissionTests` 用精确集合断言这份清单,框架升级新增了工具会让构建失败。容器里的 `MiddlewareBase` Bean 会挂到每个新建的 Agent 上;`LoggingMiddleware` 记录 Agent、模型、工具的耗时,不记录工具的参数和输出。OpenTelemetry 追踪默认不挂载:需要时自行引入 OpenTelemetry SDK 和导出器,再注册一个 `OtelTracingMiddleware` Bean。 +Agent 创建时不开放文件、命令和联网工具。读 AgentScope 源码发现子 Agent 只继承文件和 shell 的关闭、不继承联网工具的关闭,所以联网工具除了主 Agent 的 `disableWebTools()`,还用 `ToolsConfig` 的 deny 名单禁掉,它同时作用于主 Agent、内置的 `general-purpose` 子 Agent 和所有声明的子 Agent。显式传入 `ToolsConfig` 还会让 AgentScope 不再去读工作区里的 `tools.json`(那个文件可以声明 `stdio` MCP 服务,也就是在宿主机上启动进程)。读类的记忆和会话工具(`memory_get`、`memory_search`、`session_history`、`session_list`、`session_search`)也被同一份 deny 名单拒绝:`memory_get` 只校验路径不越出工作区根目录、不校验是否在当前用户目录下,`session_history` 把模型给的 ID 直接拼进路径,开着就能让模型读到别的用户的记忆和会话。模型看到的工具恰好是:Yoke 自己的(`get_weather`、`get_current_time`、`calculate`、`list_my_notes`、`retrieve`),框架的写记忆、技能加载、异步结果、子 Agent 和后台任务类工具(`memory_save` 只往工作区固定的 `MEMORY.md` 与 `memory/<日期>.md` 追加,内容没有大小限制),再加上所配置的 MCP 服务公布的工具。`ToolPermissionTests` 用精确集合断言这份清单,框架升级新增了工具会让构建失败。容器里的 `MiddlewareBase` Bean 会挂到每个新建的 Agent 上;`LoggingMiddleware` 记录 Agent、模型、工具的耗时,不记录工具的参数和输出。OpenTelemetry 追踪默认不挂载:需要时自行引入 OpenTelemetry SDK 和导出器,再注册一个 `OtelTracingMiddleware` Bean。 ## 工具、知识库与子 Agent - **工具**(`com.yoke.tool`):带 `@Tool` 方法的普通类,启动时一次性注册进共享的 `Toolkit`。`calculate` 用手写的递归下降解析器(不用脚本引擎,输入长度和嵌套深度有上限,除零以文本形式报告)。`list_my_notes` 的 `UserContext` 参数不带 `@ToolParam`:框架按类型从本次请求的 `RuntimeContext` 里注入,模型既看不到也伪造不了用户标识。 -- **检索**:`retrieve` 工具检索 `src/main/resources/knowledge/*.md`,返回带稳定编号(形如 `[文档名.md#片段编号]`,文档名加正文摘要,正文改了编号也跟着变,旧引用不会指到别的内容上;不同 classpath 根里有同名知识文档时启动即失败)和来源的片段,并要求模型原样照抄编号引用;同一轮对话里多次检索编号也不会重复,不像每次从 `[1]` 开始的序号会冲突。它是唯一的检索通道,有意不同时使用框架的 `knowledge()` 自动注入。检索分层放在应用自己的 `RetrievePort` 后面(不含框架类型):BM25 关键词检索永远可用;配置了向量化服务就再加一路向量检索,两路用 RRF(常数 60)融合,任何一路失败就用另一路。注意开启向量化后,用户的检索问题和知识库语料会发送给 embedding 服务提供方。没有使用框架自带的 `rag-simple`:`core/rag` 包在 2.0.4 里已 `@Deprecated(forRemoval = true)`,而且该模块会拖进 Qdrant、Milvus、Elasticsearch、PostgreSQL、PDFBox、POI、Tika 等一大批依赖。 +- **检索**:`retrieve` 工具检索 `src/main/resources/knowledge/*.md`,返回带稳定编号(形如 `[文档名.md#片段编号]`,文档名加正文摘要,正文改了编号也跟着变,旧引用不会指到别的内容上;不同 classpath 根里有同名知识文档时启动即失败)和来源的片段,并要求模型原样照抄编号引用;同一轮对话里多次检索编号也不会重复,不像每次从 `[1]` 开始的序号会冲突。它是唯一的检索通道,有意不同时使用框架的 `knowledge()` 自动注入。检索分层放在应用自己的 `RetrievePort` 后面(不含框架类型):BM25 关键词检索永远可用;配置了向量化服务就再加一路向量检索,两路用 RRF(常数 60)融合,任何一路失败就用另一路。注意开启向量化后,用户的检索问题和知识库语料会发送给 embedding 服务提供方。没有使用框架自带的 `rag-simple`:`core/rag` 包在 AgentScope 里已 `@Deprecated(forRemoval = true)`,而且该模块会拖进 Qdrant、Milvus、Elasticsearch、PostgreSQL、PDFBox、POI、Tika 等一大批依赖。 - **MCP**:只接受 HTTP 传输。示例: ```yaml @@ -188,27 +192,75 @@ Agent 创建时不开放文件、命令和联网工具。读 2.0.4 源码发现 Authorization: Bearer ${MCP_DOCS_TOKEN} ``` - 工具以服务端公布的名字出现。2.0.4 里 MCP 工具只有服务端声明了 `readOnlyHint` 才会免确认执行,而 Yoke 的 HTTP 接口没有人工确认通道(否则一轮对话会在工具调用处无声结束、回复为空)。所以只注册声明了只读的工具,其余跳过(工具名记在 INFO 日志里),主 Agent 和子 Agent 都看不到它们。公布的工具与 Yoke 自己的工具或 Harness 内置工具(`memory_save`、`agent_spawn` 等,每次请求建 Agent 时才加进去)重名时,启动失败。 -- **子 Agent**:`summarizer` 在代码里声明(`YokeSubagents`),没有任何工具;`kb-researcher` 由 `src/main/resources/workspace/subagents/kb-researcher.md` 声明,启动时拷贝到 `yoke.workspace/subagents/`,只能用 `retrieve`。2.0.4 对同 id 冲突是静默的:工作区文件会覆盖代码里的声明(`general-purpose.md` 还会替换内置的那个),所以 Yoke 会扫描 `yoke.workspace/subagents/` 里实际存在的全部文件(包括遗留的、手放的,不只是随应用发布的那几个),遇到任何这类重名都直接启动失败。 + 工具以服务端公布的名字出现。AgentScope 里 MCP 工具只有服务端声明了 `readOnlyHint` 才会免确认执行,而 Yoke 的 HTTP 接口没有人工确认通道(否则一轮对话会在工具调用处无声结束、回复为空)。所以只注册声明了只读的工具,其余跳过(工具名记在 INFO 日志里),主 Agent 和子 Agent 都看不到它们。公布的工具与 Yoke 自己的工具或 Harness 内置工具(`memory_save`、`agent_spawn` 等,每次请求建 Agent 时才加进去)重名时,启动失败。 +- **子 Agent**:`summarizer` 在代码里声明(`YokeSubagents`),没有任何工具;`kb-researcher` 由 `src/main/resources/workspace/subagents/kb-researcher.md` 声明,启动时拷贝到 `yoke.workspace/subagents/`,只能用 `retrieve`。AgentScope 对同 id 冲突是静默的:工作区文件会覆盖代码里的声明(`general-purpose.md` 还会替换内置的那个),所以 Yoke 会扫描 `yoke.workspace/subagents/` 里实际存在的全部文件(包括遗留的、手放的,不只是随应用发布的那几个),遇到任何这类重名都直接启动失败。 要换成其他模型,把 `build.gradle` 里的 `agentscope-openai-spring-boot-starter` 换成对应的 starter(dashscope、anthropic、gemini、ollama),并修改 `agentscope.model.provider`。 +## A2A 与 Nacos + +本节的能力**默认全部关闭**。 + +### A2A 服务端 + +```bash +export YOKE_A2A_TOKEN=$(openssl rand -hex 24) +./gradlew bootRun --args='--yoke.a2a.server.enabled=true --yoke.a2a.server.public-url=http://localhost:8080' +``` + +开启后多出两个端点:`GET /.well-known/agent-card.json`(公开)和 `POST /a2a`(JSON-RPC,只处理 `message/send`),契约写在 `A2aApi` 里。 + +> **警告** +> 开启就是暴露一个**无认证**的入口,能力等价于 `/api/chat`(同一批工具、同一个历史存储),调用方还能自报任意 `userId`。生产必须放在网关后面,或者至少配置 `yoke.a2a.server.token`:配置后 JSON-RPC 端点要求 `Authorization: Bearer `(常量时间比较,否则 401),Agent Card 里同步声明 Bearer 认证。不配置 token 就不做任何校验,启动时会打一条 WARN。 + +- 协议:AgentScope 实现的是 A2A 0.3(SDK `0.3.3.Final`,`protocolVersion` 为 `0.3.0`),只有 JSON-RPC 传输。以上以 Yoke 当前使用的 AgentScope 为准,更新版本的 AgentScope 已改为 A2A 1.0、不再支持 0.3,请以对应版本的手册为准。只提供同步的 `message/send`(Card 里 `streaming: false`);`message/stream` 和 `tasks/resubscribe` 返回「不支持的操作」,其余方法返回「方法不存在」。 +- 传输安全:Bearer Token 走明文 HTTP,`public-url` 缺省是 `http://localhost:端口`。生产要用 `https` 的对外地址,或由网关终结 TLS。token 少于 16 个字符会启动失败。请求体超过 `yoke.a2a.server.max-body-bytes`(默认 256 KB)返回 413(响应体 `-32600`):认证先于读体,声明的 `Content-Length` 超限不读体,chunked 请求限长读取;`/api/chat` 没有这类自定义上限。 +- 会话:`sessionId` 取 `metadata.sessionId`,没有则取 `contextId`,再没有就新建;`userId` 取 `metadata.userId`,缺失为 `default`。二者和 HTTP 接口用同一条 `@SafeId` 规则,不合法返回 `-32602`。响应里的 `contextId` 就是会话 ID,带上它即可延续对话。 +- 失败返回 JSON-RPC 的 `-32603`,消息是固定的一句话,不含异常内容。 +- 没有使用官方的 `agentscope-a2a-spring-boot-starter`:它只认 `ReActAgent`,自带的控制器没有认证,Card 里的 `streaming` 还固定写成 `true`。 + +### 调用远端 A2A Agent + +配置 `yoke.a2a.remote.url`(或 `agent-name` 并开启 `yoke.nacos.a2a.enabled=true`)后出现 `POST /api/chat/remote`:`{"sessionId": "...", "message": "..."}`。调用目标只来自配置,请求体里没有任何字段能影响它。直连 URL 时,远端 Agent Card 里**所有**声明服务地址的位置(`url` 和 `additionalInterfaces` 的每一项)都必须与配置同源,且首选传输必须是 JSONRPC,否则拒绝调用(官方客户端从首选传输和 additionalInterfaces 里挑 JSON-RPC 地址,只比较 `url` 会被绕过)。HTTP 客户端不跟随重定向,请求有超时。失败返回 `502`(超时 `504`),响应里不含地址和凭证。这个端点同样没有认证。它有意不作为工具暴露给模型,免得远端的内容左右模型。 + +### Nacos + +```bash +docker compose up -d redis nacos # Nacos 3.x 单机,固定 v3.2.1-2026.03.30 +export YOKE_NACOS_ADDR=127.0.0.1:8848 +./gradlew bootRun --args='--yoke.nacos.prompt.enabled=true --yoke.nacos.a2a.enabled=true --yoke.a2a.server.enabled=true' +``` + +- 一条 gRPC 通道承载全部数据,需要 Nacos 3.x(客户端端口 = 主端口 + 1000,默认 9848)。任何一个开关打开,启动时都会探活,不可用就启动失败,报错信息清晰且不含凭证。 +- `yoke.nacos.a2a.enabled`:A2A 服务端开启时,应用就绪后注册 Agent Card 和端点(关闭时注销);配了 `yoke.a2a.remote.agent-name` 时按名字发现远端。 +- `yoke.nacos.prompt.enabled`:每轮对话从 Nacos 拉取 Prompt `yoke.nacos.prompt.key`,追加在内置系统提示词之后(不重复拼接;拉取失败就原样使用内置提示词)。发布新版本后,下一轮对话即可生效,中间有很短的服务端传播延迟(对 compose 里的镜像实测 25 到 270 毫秒)。 +- 信任边界:谁能写 Nacos 里这个 Prompt Key,谁就能改 Yoke 的系统提示词(它追加在内置提示词之后,实测子 Agent 也会带上)。来源必须受信,生产必须开启 Nacos 鉴权。每次拉取有超时(`yoke.nacos.prompt.timeout`,默认 2 秒),超时或失败沿用内置提示词,警告日志有限频。 +- Nacos 客户端的日志和快照缓存被重定向到 `/nacos`(`JM.LOG.PATH`、`JM.SNAPSHOT.PATH`),不再写 `~/logs/nacos` 和 `~/nacos`。客户端自己登录失败的那行日志仍会显示打码后的部分密码。 +- Skill 托管(`nacos-skill`)没有接入。 +- `docker-compose.yml` 里的 Nacos 关闭了鉴权,仅限本地研发;生产必须开启鉴权并替换其中的占位密钥。 + +### 可观测 + +Actuator 只暴露 `health`、`info`、`metrics`、`prometheus`(`ActuatorExposureTests` 精确断言),`env`、`heapdump` 之类一律不暴露;`health` 包含 Redis,但不显示明细。这些端点和业务接口在同一个端口,同样没有认证:请放在网关后面,或用 `MANAGEMENT_SERVER_PORT` 挪到内部端口。 + ## 项目结构 ``` src/main/java/com/yoke/ ├── YokeApplication.java 应用入口 -├── api/ HTTP 接口契约(ChatApi,路径、校验和文档都在这里) +├── a2a/ A2A 服务端网关、runner(a2a/runner 把 HarnessAgent 适配成 A2A 的 AgentRunner)和远端客户端 +├── api/ HTTP 接口契约(ChatApi、A2aApi、RemoteChatApi,路径、校验和文档都在这里) ├── codec/ 领域类型与框架类型之间的转换(MessageCodec、AguiStreamCodec、HintEventConverter) -├── config/ Agent、Redis、AG-UI 适配器、工具、知识库与子 Agent 配置(HarnessAgentFactory、YokeProperties、YokeSubagents) -├── controller/ 接口实现(ChatController) +├── config/ Agent、Redis、AG-UI、A2A、Nacos、工具、知识库与子 Agent 配置(HarnessAgentFactory、YokeProperties、YokeSubagents) +├── controller/ 接口实现(ChatController、A2aController、RemoteChatController) ├── knowledge/ 检索端口及实现:关键词、向量、RRF 融合(不含框架类型) ├── mcp/ 到外部 MCP 服务的连接(只支持 HTTP 传输) ├── middleware/ Agent 中间件(LoggingMiddleware) -├── model/ 请求与响应对象(ChatRequest、ChatResponse) -└── tool/ 暴露给模型的工具(WeatherTool、ChatTools、RetrieveTool、UserContext) +├── nacos/ Nacos 客户端探活、A2A 注册、Prompt 热更新中间件 +├── model/ 领域、请求与响应对象(ChatRequest、ChatResponse、RemoteChatRequest、SafeId、UserContext、Passage) +└── tool/ 暴露给模型的工具(WeatherTool、ChatTools、RetrieveTool、SharedToolkit) src/main/resources/ application.yml、各环境配置、knowledge/*.md 和 workspace/subagents/*.md -docker-compose.yml 本地 Redis,集成测试也用它 +docker-compose.yml 本地 Redis 和 Nacos,集成测试也用它 docs/brand/ logo ``` @@ -219,7 +271,7 @@ docs/brand/ logo ## 参与贡献 -欢迎提交 Issue 和 Pull Request。提交前请运行 `./gradlew build` 确保全部测试通过;代码注释使用中文。AgentScope 的消息和事件类型不能泄漏到 `codec` 之外(`middleware` 除外,它的钩子签名本身就要用这些类型),`knowledge` 包不能出现任何 AgentScope 类型,`ArchitectureTests` 会检查这些。 +欢迎提交 Issue 和 Pull Request。提交前请运行 `./gradlew build` 确保全部测试通过;代码注释使用中文。AgentScope 的消息和事件类型不能泄漏到 `codec` 之外(`middleware` 除外,它的钩子签名本身就要用这些类型),`knowledge` 包不能出现任何 AgentScope 类型,`a2a` / `nacos` 包只能用明确白名单里的框架类型,`ArchitectureTests` 会检查这些。Nacos 集成测试会用 `docker-compose.yml` 里的 `nacos` 服务(第一次拉镜像较慢)。 ## 许可证 diff --git a/build.gradle b/build.gradle index f47ee64..e52f690 100644 --- a/build.gradle +++ b/build.gradle @@ -37,6 +37,16 @@ dependencies { // 字符串判空统一用 Hutool 的 StrUtil(isBlank / isNotBlank),只引核心包,不用 hutool-all implementation libs.hutool.core + // A2A 互通:服务端把 Agent 暴露成 A2A 服务,客户端把远端 Agent 包成本地 Agent;两者互相独立 + implementation libs.agentscope.a2a.server + implementation libs.agentscope.a2a.client + // Nacos:A2A 注册发现与 Prompt 热更新,默认不启用(yoke.nacos.*)。带进 nacos-client(AiService 在里面); + // 不引 nacos-prompt:它的 NacosPromptListener 靠订阅推送更新缓存,实测要等 10 多秒,Yoke 每轮直接拉取 + implementation libs.agentscope.nacos.a2a + // 可观测:只暴露 health / info / metrics / prometheus,见 application.yml 的 management 配置 + implementation libs.spring.boot.starter.actuator + implementation libs.micrometer.registry.prometheus + // Lombok 只在编译期使用;这几个配置不继承 implementation,需要单独引入 BOM 才能省略版本号 ['compileOnly', 'annotationProcessor', 'testCompileOnly', 'testAnnotationProcessor'].each { configuration -> add(configuration, platform(libs.spring.boot.dependencies)) diff --git a/docker-compose.yml b/docker-compose.yml index 0aec8b0..d157363 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,5 +1,6 @@ # 本地研发依赖:先执行 docker compose up -d,再启动应用(./gradlew bootRun)。 # 集成测试(Testcontainers)读取的也是这同一份文件,所以改这里会同时影响本地和测试。 +# 只需要 Redis 时:docker compose up -d redis;要试 Nacos 再加上 nacos。 services: redis: # 固定版本,不用 latest,避免不同机器拉到不同的 Redis @@ -12,3 +13,36 @@ services: interval: 2s timeout: 2s retries: 15 + + nacos: + # 固定版本,不用 latest。选 v3.2.1-2026.03.30 是因为它与 AgentScope 带进来的 nacos-client(3.2.1-2026.03.30) + # 同一个构建:AI 通道(Agent Card / Prompt)的 gRPC 协议在 3.x 各小版本间有差异,客户端和服务端版本对齐最稳 + image: nacos/nacos-server:v3.2.1-2026.03.30 + environment: + MODE: standalone + # ===== 仅限本地研发!以下三项关闭了鉴权,生产必须开启鉴权(NACOS_AUTH_ENABLE=true 等)并换掉下面的密钥 ===== + # 后果:没有鉴权时任何能连上 Nacos 的人都能改 Prompt,也就是能改 Yoke 的系统提示词,还能往里注册恶意的 Agent + NACOS_AUTH_ENABLE: "false" + # 管理接口(/v3/admin)与控制台默认也要登录,本地为了脚本和测试能直接发布 Prompt 一并关闭 + NACOS_AUTH_ADMIN_ENABLE: "false" + NACOS_AUTH_CONSOLE_ENABLE: "false" + # Nacos 3 不管鉴权开没开,启动脚本都要求下面三个变量非空。这是公开在仓库里的开发用假值,不是密钥; + # TOKEN 必须是 Base64 且解码后不少于 32 字节。生产必须换成自己生成的随机值(例如 openssl rand -base64 48) + NACOS_AUTH_TOKEN: eW9rZS1sb2NhbC1kZXYtb25seS1ub3QtYS1zZWNyZXQtMDEyMzQ1Njc4OQ== + NACOS_AUTH_IDENTITY_KEY: yoke-dev + NACOS_AUTH_IDENTITY_VALUE: yoke-dev + JVM_XMS: 256m + JVM_XMX: 512m + JVM_XMN: 256m + ports: + # 客户端 gRPC 端口必须等于主端口 + 1000(客户端按这个规则推算),所以这两个端口要一起改: + # NACOS_PORT=18848 NACOS_GRPC_PORT=19848 docker compose up -d,应用侧 YOKE_NACOS_ADDR=127.0.0.1:18848 + - "127.0.0.1:${NACOS_PORT:-8848}:8848" + - "127.0.0.1:${NACOS_GRPC_PORT:-9848}:9848" + # 控制台(Nacos 3 的控制台是容器里单独的 8080 端口)。宿主机上映射到 18080,避开 Yoke 自己默认的 8080:http://127.0.0.1:18080 + - "127.0.0.1:${NACOS_CONSOLE_PORT:-18080}:8080" + healthcheck: + test: ["CMD", "curl", "-fsS", "http://localhost:8080/v3/console/health/readiness"] + interval: 3s + timeout: 3s + retries: 40 diff --git a/gradle.properties b/gradle.properties index 8426a58..f270c5f 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,5 @@ group=com.yoke -version=3.0.0 +version=4.0.0 org.gradle.parallel=true org.gradle.caching=true org.gradle.configuration-cache=true diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index cd8d6af..7a7d7c0 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,6 +1,6 @@ [versions] spring-boot = "4.1.2" -agentscope = "2.0.4" +agentscope = "2.0.5" archunit = "1.4.1" hutool = "5.8.48" @@ -12,6 +12,9 @@ agentscope-harness = { module = "io.agentscope:agentscope-harness" } agentscope-redis = { module = "io.agentscope:agentscope-extensions-redis" } agentscope-agui = { module = "io.agentscope:agentscope-extensions-agui" } agentscope-openai-starter = { module = "io.agentscope:agentscope-openai-spring-boot-starter" } +agentscope-a2a-server = { module = "io.agentscope:agentscope-extensions-a2a-server" } +agentscope-a2a-client = { module = "io.agentscope:agentscope-extensions-a2a-client" } +agentscope-nacos-a2a = { module = "io.agentscope:agentscope-extensions-nacos-a2a" } testcontainers = { module = "org.testcontainers:testcontainers" } testcontainers-junit = { module = "org.testcontainers:testcontainers-junit-jupiter" } spring-boot-starter-validation = { module = "org.springframework.boot:spring-boot-starter-validation" } @@ -19,6 +22,8 @@ hutool-core = { module = "cn.hutool:hutool-core", version.ref = "hutool" } lombok = { module = "org.projectlombok:lombok" } archunit = { module = "com.tngtech.archunit:archunit-junit5", version.ref = "archunit" } spring-boot-starter-webmvc = { module = "org.springframework.boot:spring-boot-starter-webmvc" } +spring-boot-starter-actuator = { module = "org.springframework.boot:spring-boot-starter-actuator" } +micrometer-registry-prometheus = { module = "io.micrometer:micrometer-registry-prometheus" } spring-boot-starter-test = { module = "org.springframework.boot:spring-boot-starter-test" } spring-boot-starter-webmvc-test = { module = "org.springframework.boot:spring-boot-starter-webmvc-test" } diff --git a/src/main/java/com/yoke/a2a/A2aGateway.java b/src/main/java/com/yoke/a2a/A2aGateway.java new file mode 100644 index 0000000..a66a909 --- /dev/null +++ b/src/main/java/com/yoke/a2a/A2aGateway.java @@ -0,0 +1,296 @@ +package com.yoke.a2a; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; + +import cn.hutool.core.util.StrUtil; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.yoke.a2a.runner.YokeAgentRunner; +import com.yoke.model.SafeId; +import io.a2a.spec.AgentCard; +import io.a2a.spec.InternalError; +import io.a2a.spec.InvalidParamsError; +import io.a2a.spec.InvalidRequestError; +import io.a2a.spec.JSONParseError; +import io.a2a.spec.JSONRPCError; +import io.a2a.spec.JSONRPCErrorResponse; +import io.a2a.spec.JSONRPCResponse; +import io.a2a.spec.Message; +import io.a2a.spec.MethodNotFoundError; +import io.a2a.spec.SendMessageRequest; +import io.a2a.spec.SendMessageResponse; +import io.a2a.spec.SendStreamingMessageRequest; +import io.a2a.spec.TransportProtocol; +import io.a2a.spec.UnsupportedOperationError; +import io.a2a.util.Utils; +import io.agentscope.core.a2a.server.AgentScopeA2aServer; +import io.agentscope.core.a2a.server.transport.jsonrpc.JsonRpcTransportWrapper; +import lombok.extern.slf4j.Slf4j; + + +/** + * A2A 服务端的入口网关:HTTP 请求进来后,先在这里认证、校验、收紧,再交给框架的 JSON-RPC 处理链。 + * + *

框架的 JSON-RPC 处理链没有任何认证(源码里写着 TODO),也不校验标识格式,所以这些都在这一层补: + *

    + *
  1. 认证:配置了 token 时要求 {@code Authorization: Bearer },常量时间比较;没配则不校验;
  2. + *
  3. 请求体大小上限({@code yoke.a2a.server.max-body-bytes},默认 256 KB):认证先于读体({@link #preflight}), + * 再看声明的 Content-Length,超限不读体直接回 413;没声明长度的(chunked)用限长读取,超过上限就停止读取。 + * 响应体是 JSON-RPC 的 -32600。所以未认证的调用者没法让服务器缓冲任意大的请求体;
  4. + *
  5. 只开放同步的 {@code message/send}:流式({@code message/stream}、{@code tasks/resubscribe})返回「不支持」, + * 其余方法(取消、查询任务、推送配置)返回「方法不存在」,攻击面最小;{@code blocking} 一律强制为 true;
  6. + *
  7. 会话映射:sessionId 取 {@code metadata.sessionId},没有则取 {@code message.contextId},再没有就新建; + * userId 取 {@code metadata.userId},缺失用 default。二者都过 {@link SafeId} 规则,非法值返回 -32602 而不是放行; + * 最终的 sessionId 写回 {@code contextId},所以响应里的 contextId 就是会话 ID,调用方带着它即可延续对话;
  8. + *
  9. 不接续任务:带 {@code taskId} 的请求被拒绝,延续对话请用 contextId;
  10. + *
  11. 错误改写:执行失败时把框架生成的「看起来像正常回复」的错误消息改写成 JSON-RPC 的 -32603,信息不含内部细节。
  12. + *
+ * + *

日志里不记请求体(里面是用户内容)和 Authorization 头。 + */ +@Slf4j +public class A2aGateway { + + /** 框架的 JSON-RPC 方法名:同步发送消息,是唯一放行的方法。 */ + static final String METHOD_SEND = SendMessageRequest.METHOD; + + private final AgentScopeA2aServer server; + private final YokeAgentRunner runner; + private final AgentCard publishedCard; + private final byte[] tokenDigest; + private final int maxBodyBytes; + + /** + * @param server 框架的 A2A 服务端 + * @param runner 取失败台账用 + * @param publishedCard 对外公布的 Agent Card(已按 Yoke 的实际能力修正) + * @param token Bearer Token;空白表示不校验 + * @param maxBodyBytes 请求体上限(字节);认证通过之后、解析之前检查 + */ + public A2aGateway(AgentScopeA2aServer server, YokeAgentRunner runner, AgentCard publishedCard, String token, + int maxBodyBytes) { + this.server = server; + this.runner = runner; + this.publishedCard = publishedCard; + this.tokenDigest = Optional.ofNullable(token).filter(StrUtil::isNotBlank).map(A2aGateway::sha256).orElse(null); + this.maxBodyBytes = maxBodyBytes; + } + + /** 一次网关响应:HTTP 状态码、JSON 响应体、需要时的认证质询头。 */ + public record Reply(int status, String body, String wwwAuthenticate) { + } + + /** Agent Card 的 JSON;公开,不需要 token(调用方要先读它才知道该怎么认证)。 */ + public String agentCardJson() { + return toJson(publishedCard); + } + + /** + * 读请求体之前的检查:先认证,再看声明的 Content-Length。返回 null 表示可以继续读体,否则直接用返回值作答, + * 请求体一个字节都不读。这样未认证的调用者没法让服务器缓冲任意大的请求体。 + */ + public Reply preflight(Map headers, long declaredLength) { + if (tokenRejected(headers)) { + return unauthorized(); + } + if (declaredLength > maxBodyBytes) { + return tooLarge(); + } + return null; + } + + /** + * 限长读取请求体:最多读 {@code maxBodyBytes + 1} 个字节,超过就停止读取并返回 null(调用方应回 {@link #tooLarge()})。 + * 对没有声明长度(chunked)的请求同样有效。 + */ + public String readBody(InputStream in) throws IOException { + byte[] data = in.readNBytes(maxBodyBytes + 1); + if (data.length > maxBodyBytes) { + return null; + } + return new String(data, StandardCharsets.UTF_8); + } + + /** 413,响应体是 JSON-RPC 的 -32600;不含内部信息。 */ + public Reply tooLarge() { + Reply error = rpcError(null, new InvalidRequestError("请求体过大,上限 " + maxBodyBytes + " 字节")); + return new Reply(413, error.body(), null); + } + + /** 读请求体失败。 */ + public Reply unreadable() { + Reply error = rpcError(null, new InvalidRequestError("无法读取请求体")); + return new Reply(400, error.body(), null); + } + + private static Reply unauthorized() { + return new Reply(401, "{\"error\":\"unauthorized\"}", "Bearer"); + } + + public Reply handle(String body, Map headers) { + if (tokenRejected(headers)) { + return unauthorized(); + } + // 大小只在字节层检查一次(preflight 的声明长度 + readBody 的限长读取);这里不再对已解码的字符串重算字节数, + // 含非法 UTF-8 的输入解码后会被替换字符撑长,重算会误伤 + if (Objects.isNull(body)) { + return unreadable(); + } + JsonNode root; + try { + root = Utils.OBJECT_MAPPER.readTree(body); + } catch (JsonProcessingException | RuntimeException e) { + return rpcError(null, new JSONParseError("请求体不是合法的 JSON")); + } + if (Objects.isNull(root) || !root.isObject()) { + return rpcError(null, new InvalidRequestError()); + } + Object id = idOf(root); + String method = root.path("method").asText(""); + if (SendStreamingMessageRequest.METHOD.equals(method) || "tasks/resubscribe".equals(method)) { + return rpcError(id, new UnsupportedOperationError()); + } + if (!METHOD_SEND.equals(method)) { + return rpcError(id, new MethodNotFoundError()); + } + ObjectNode forwarded; + try { + forwarded = normalize((ObjectNode) root); + } catch (IllegalArgumentException e) { + return rpcError(id, new InvalidParamsError(e.getMessage())); + } + return dispatch(id, forwarded.toString(), headers); + } + + private Reply dispatch(Object id, String body, Map headers) { + Map forwardedHeaders = new HashMap<>(headers); + // 凭证不往下传:框架会把请求头放进调用上下文 + forwardedHeaders.keySet().removeIf(name -> name.equalsIgnoreCase("authorization")); + Object result = server.getTransportWrapper(TransportProtocol.JSONRPC.asString(), JsonRpcTransportWrapper.class) + .handleRequest(body, forwardedHeaders, Map.of()); + if (!(result instanceof JSONRPCResponse response)) { + log.error("A2A 处理链返回了意料之外的类型:{}", Optional.ofNullable(result).map(value -> value.getClass().getName()).orElse(null)); + return rpcError(id, new InternalError("服务端内部错误")); + } + if (response instanceof SendMessageResponse sent && sent.getResult() instanceof Message message) { + var failure = runner.takeFailure(message.getTaskId()); + if (failure.isPresent()) { + return rpcError(id, new InternalError(failure.get())); + } + } + return new Reply(200, toJson(response), null); + } + + /** 校验并改写 message/send 的参数,返回要转交给框架的请求。非法输入抛 IllegalArgumentException。 */ + private static ObjectNode normalize(ObjectNode root) { + JsonNode params = root.path("params"); + if (!params.isObject() || !params.path("message").isObject()) { + throw new IllegalArgumentException("缺少 params.message"); + } + ObjectNode message = (ObjectNode) params.get("message"); + if (hasValue(message.get("taskId"))) { + throw new IllegalArgumentException("不支持接续任务(taskId),延续对话请使用 contextId"); + } + JsonNode metadataNode = message.get("metadata"); + if (Objects.nonNull(metadataNode) && !metadataNode.isNull() && !metadataNode.isObject()) { + throw new IllegalArgumentException("message.metadata 必须是对象"); + } + ObjectNode metadata = Objects.nonNull(metadataNode) && metadataNode.isObject() + ? (ObjectNode) metadataNode : message.putObject("metadata"); + + String userId = textOrNull(metadata, "userId"); + String sessionId = textOrNull(metadata, "sessionId"); + String contextId = textOrNull(message, "contextId"); + if (StrUtil.isBlank(sessionId)) { + sessionId = contextId; + } + if (StrUtil.isNotBlank(userId) && !SafeId.Validator.isSafe(userId)) { + throw new IllegalArgumentException("userId 格式不合法:只能包含字母、数字、下划线、点和短横线,长度 1 到 64,且不能全是点"); + } + if (StrUtil.isNotBlank(sessionId) && !SafeId.Validator.isSafe(sessionId)) { + throw new IllegalArgumentException("sessionId(或 contextId)格式不合法:只能包含字母、数字、下划线、点和短横线,长度 1 到 64,且不能全是点"); + } + if (StrUtil.isBlank(sessionId)) { + sessionId = UUID.randomUUID().toString(); + } + metadata.put("sessionId", sessionId); + message.put("contextId", sessionId); + if (StrUtil.isNotBlank(userId)) { + metadata.put("userId", userId); + } else { + metadata.remove("userId"); + } + // 同步语义:调用在 Agent 跑完之后才返回,不留异步任务让调用方轮询 + ObjectNode configuration = params.path("configuration").isObject() + ? (ObjectNode) params.get("configuration") : ((ObjectNode) params).putObject("configuration"); + configuration.put("blocking", true); + return root; + } + + private static boolean hasValue(JsonNode node) { + return Objects.nonNull(node) && !node.isNull() && StrUtil.isNotBlank(node.asText()); + } + + private static String textOrNull(JsonNode parent, String field) { + JsonNode node = parent.get(field); + if (Objects.isNull(node) || node.isNull()) { + return null; + } + if (!node.isTextual()) { + throw new IllegalArgumentException(field + " 必须是字符串"); + } + return node.asText(); + } + + private static Object idOf(JsonNode root) { + JsonNode id = root.get("id"); + if (Objects.isNull(id) || id.isNull()) { + return null; + } + return id.isNumber() ? id.numberValue() : id.asText(); + } + + /** 配置了 token、而请求没带对的 token 时返回 true;没配 token 不校验。 */ + private boolean tokenRejected(Map headers) { + if (Objects.isNull(tokenDigest)) { + return false; + } + String header = headers.entrySet().stream() + .filter(entry -> "authorization".equalsIgnoreCase(entry.getKey())) + .map(Map.Entry::getValue).findFirst().orElse(null); + if (Objects.isNull(header) || !header.regionMatches(true, 0, "Bearer ", 0, 7)) { + return true; + } + // 先各自取摘要再比较:长度固定,常量时间,也不泄露 token 的长度 + return !MessageDigest.isEqual(tokenDigest, sha256(header.substring(7).trim())); + } + + private static byte[] sha256(String value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)); + } catch (java.security.NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + private static Reply rpcError(Object id, JSONRPCError error) { + return new Reply(200, toJson(new JSONRPCErrorResponse(id, error)), null); + } + + private static String toJson(Object value) { + try { + return Utils.OBJECT_MAPPER.writeValueAsString(value); + } catch (JsonProcessingException e) { + throw new IllegalStateException("序列化 A2A 响应失败", e); + } + } +} diff --git a/src/main/java/com/yoke/a2a/NoRedirectCardResolver.java b/src/main/java/com/yoke/a2a/NoRedirectCardResolver.java new file mode 100644 index 0000000..a189904 --- /dev/null +++ b/src/main/java/com/yoke/a2a/NoRedirectCardResolver.java @@ -0,0 +1,35 @@ +package com.yoke.a2a; + +import java.time.Duration; +import java.util.Map; + +import io.a2a.A2A; +import io.a2a.spec.AgentCard; +import io.agentscope.core.a2a.agent.card.AgentCardResolver; + +/** well-known 取卡片,用不跟随重定向、带超时的 HTTP 客户端(官方的 WellKnownAgentCardResolver 用的是会跟随重定向的默认客户端)。 */ +public class NoRedirectCardResolver implements AgentCardResolver { + + private final NoRedirectHttpClient http; + private final String baseUrl; + + public NoRedirectCardResolver(String baseUrl, Duration timeout) { + this.baseUrl = baseUrl; + this.http = new NoRedirectHttpClient(timeout); + } + + @Override + public AgentCard getAgentCard(String agentName) { + return A2A.getAgentCard(http, baseUrl, "/.well-known/agent-card.json", Map.of()); + } + + /** 关闭取卡片所用的底层 HTTP 客户端。 */ + public void close() { + http.close(); + } + + /** 底层 HTTP 客户端是否已关闭,供生命周期测试断言。 */ + public boolean isTerminated() { + return http.isTerminated(); + } +} diff --git a/src/main/java/com/yoke/a2a/NoRedirectHttpClient.java b/src/main/java/com/yoke/a2a/NoRedirectHttpClient.java new file mode 100644 index 0000000..23c20b7 --- /dev/null +++ b/src/main/java/com/yoke/a2a/NoRedirectHttpClient.java @@ -0,0 +1,162 @@ +package com.yoke.a2a; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; + +import io.a2a.client.http.A2AHttpClient; +import io.a2a.client.http.A2AHttpResponse; +import org.jspecify.annotations.NonNull; + +/** + * 给 A2A 客户端用的 HTTP 客户端:不跟随重定向,并给每个请求设上超时。 + * + *

官方的 {@code JdkA2AHttpClient} 用 {@code Redirect.NORMAL}(读 A2A SDK 字节码所得,并实测): + * 远端对 {@code POST /a2a} 回一个 307,客户端会把消息体原样重发到 Location 指向的任意主机。 + * 同源校验只管 Agent Card 里的地址,管不到重定向,所以这里直接把重定向关掉:3xx 当作失败。 + * 超时也一并解决了「{@code Mono.timeout} 只取消等待、底层请求还挂着」的问题。 + * + *

只实现同步的 GET 和 POST:Yoke 的客户端是非流式的,SSE 和 DELETE 不会被用到,调用即报错。 + */ +public class NoRedirectHttpClient implements A2AHttpClient { + + private final HttpClient client; + private final Duration requestTimeout; + + public NoRedirectHttpClient(Duration requestTimeout) { + this.requestTimeout = requestTimeout; + this.client = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.NEVER) + .connectTimeout(Duration.ofSeconds(10)).build(); + } + + /** 关闭底层连接池与 SelectorManager 线程。 */ + public void close() { + client.close(); + } + + /** 底层 HttpClient 是否已关闭,供生命周期测试断言。 */ + public boolean isTerminated() { + return client.isTerminated(); + } + + @Override + public @NonNull GetBuilder createGet() { + return new Get(); + } + + @Override + public @NonNull PostBuilder createPost() { + return new Post(); + } + + @Override + public @NonNull DeleteBuilder createDelete() { + throw new UnsupportedOperationException("Yoke 的 A2A 客户端不使用 DELETE"); + } + + private abstract static class Base> implements Builder { + String url; + final Map headers = new HashMap<>(); + + abstract T self(); + + @Override + public @NonNull T url(@NonNull String url) { + this.url = url; + return self(); + } + + @Override + public @NonNull T addHeaders(@NonNull Map more) { + headers.putAll(more); + return self(); + } + + @Override + public @NonNull T addHeader(@NonNull String name, @NonNull String value) { + headers.put(name, value); + return self(); + } + } + + private HttpRequest.Builder request(Base base) { + HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(base.url)).timeout(requestTimeout); + base.headers.forEach(builder::header); + return builder; + } + + private A2AHttpResponse send(HttpRequest request) throws IOException, InterruptedException { + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); + int status = response.statusCode(); + return new A2AHttpResponse() { + @Override + public int status() { + return status; + } + + @Override + public boolean success() { + return status >= 200 && status < 300; + } + + @Override + public @NonNull String body() { + return response.body(); + } + }; + } + + private final class Get extends Base implements GetBuilder { + + @Override + GetBuilder self() { + return this; + } + + @Override + public @NonNull A2AHttpResponse get() throws IOException, InterruptedException { + return send(request(this).GET().build()); + } + + @Override + public @NonNull CompletableFuture getAsyncSSE(@NonNull Consumer messageConsumer, @NonNull Consumer errorConsumer, + @NonNull Runnable completeRunnable) { + throw new UnsupportedOperationException("Yoke 的 A2A 客户端不使用流式"); + } + } + + private final class Post extends Base implements PostBuilder { + + private String body = ""; + + @Override + PostBuilder self() { + return this; + } + + @Override + public @NonNull PostBuilder body(@NonNull String body) { + this.body = body; + return this; + } + + @Override + public @NonNull A2AHttpResponse post() throws IOException, InterruptedException { + return send(request(this).POST(HttpRequest.BodyPublishers.ofString(body)).build()); + } + + @Override + public @NonNull CompletableFuture postAsyncSSE(@NonNull Consumer messageConsumer, @NonNull Consumer errorConsumer, + @NonNull Runnable completeRunnable) { + throw new UnsupportedOperationException("Yoke 的 A2A 客户端不使用流式"); + } + } +} diff --git a/src/main/java/com/yoke/a2a/RemoteAgentClient.java b/src/main/java/com/yoke/a2a/RemoteAgentClient.java new file mode 100644 index 0000000..ebcde5f --- /dev/null +++ b/src/main/java/com/yoke/a2a/RemoteAgentClient.java @@ -0,0 +1,217 @@ +package com.yoke.a2a; + +import java.net.URI; +import java.time.Duration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.TimeoutException; + +import cn.hutool.core.util.StrUtil; +import com.yoke.codec.MessageCodec; +import io.a2a.client.transport.jsonrpc.JSONRPCTransport; +import io.a2a.client.transport.jsonrpc.JSONRPCTransportConfig; +import io.a2a.client.transport.spi.interceptors.ClientCallContext; +import io.a2a.client.transport.spi.interceptors.ClientCallInterceptor; +import io.a2a.client.transport.spi.interceptors.PayloadAndHeaders; +import io.a2a.spec.AgentCard; +import io.a2a.spec.Message; +import io.a2a.spec.MessageSendParams; +import io.a2a.spec.SendMessageRequest; +import io.agentscope.core.a2a.agent.A2aAgent; +import io.agentscope.core.a2a.agent.A2aAgentConfig; +import io.agentscope.core.a2a.agent.card.AgentCardResolver; +import lombok.extern.slf4j.Slf4j; +import org.jspecify.annotations.NonNull; +import org.jspecify.annotations.Nullable; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + + +/** + * 把一个远端 A2A Agent 包成本地调用:用官方的 {@link A2aAgent} 发 {@code message/send},拿回文本。 + * + *

远端地址只来自配置:Agent Card 由构造时给定的 {@link AgentCardResolver} 取(well-known 直连或 Nacos 发现), + * 请求体里的任何字段都不会影响调用的目标,所以调用方没法借它去访问任意地址。 + * + *

每次调用新建一个 {@link A2aAgent}:它自带内存记忆,会把历史消息全部重发,也不允许并发调用; + * 会话的连续性交给远端按 sessionId 保存的历史,而不是本地对象。sessionId 同时写进 {@code contextId} 和 + * {@code metadata.sessionId}(官方 A2aAgent 本身不传会话标识,这里用传输层拦截器补上)。 + * + *

失败一律包成 {@link RemoteAgentException},不静默吞:取卡片失败、连接失败、对方返回错误、超时都有明确的异常; + * 消息里不含地址和凭证。 + * + *

HTTP 层用 {@link NoRedirectHttpClient}:不跟随重定向(否则远端一个 307 就能把消息体重发到任意主机)、请求有超时。 + * 卡片里的 {@code securitySchemes} / {@code security} 不会让客户端自动带出凭证:官方 ClientBuilder 完全不读它们 + * (读字节码所得),凭证只有我们自己在拦截器里加的那一个 Authorization。 + * + *

当 {@code pinnedOrigin} 不为空(well-known 直连)时,要求 Agent Card 里所有声明的服务地址与配置的地址同源,且首选传输是 JSONRPC, + * 否则拒绝调用——否则远端一张改过的卡片就能把请求(连同 token)引到别处。Nacos 发现时不做这个限制, + * 信任边界是 Nacos 本身。 + */ +@Slf4j +public class RemoteAgentClient { + + private final AgentCardResolver cardResolver; + private final String agentName; + private final String token; + private final Duration timeout; + private final String pinnedOrigin; + private final NoRedirectHttpClient httpClient; + + public RemoteAgentClient(AgentCardResolver cardResolver, String agentName, String token, Duration timeout, + String pinnedOrigin) { + this.cardResolver = cardResolver; + this.agentName = agentName; + this.token = token; + this.timeout = timeout; + this.pinnedOrigin = pinnedOrigin; + this.httpClient = new NoRedirectHttpClient(timeout); + } + + /** 向远端发一句话,返回远端回复的文本。 */ + public Mono ask(String sessionId, String message) { + return Mono.fromCallable(() -> prepare(sessionId)) + .subscribeOn(Schedulers.boundedElastic()) + .flatMap(agent -> agent.call(MessageCodec.toInput(message))) + .map(MessageCodec::toText) + .timeout(timeout) + .onErrorMap(error -> !(error instanceof RemoteAgentException), this::wrap); + } + + private A2aAgent prepare(String sessionId) { + AgentCard card = cardResolver.getAgentCard(agentName); + if (Objects.isNull(card)) { + throw new IllegalStateException("没有取到远端的 Agent Card"); + } + if (Objects.nonNull(pinnedOrigin) && !cardStaysInOrigin(card)) { + throw new RemoteAgentException("远端 Agent Card 声明的服务地址与配置的地址不一致,已拒绝调用", false, null); + } + JSONRPCTransportConfig transport = new JSONRPCTransportConfig(httpClient); + transport.setInterceptors(List.of(new SessionAndAuth(sessionId, token))); + return A2aAgent.builder() + .name(agentName) + .agentCard(card) + .a2aAgentConfig(A2aAgentConfig.builder().withTransport(JSONRPCTransport.class, transport).build()) + .build(); + } + + /** + * Card 里所有声明服务地址的位置都必须与配置同源,并且首选传输必须是 JSONRPC。 + * + *

只比较 {@code card.url} 会被绕过:官方 ClientBuilder 选传输时把「首选传输 -> url」和 + * 「additionalInterfaces 里每一项」放进同一张表,再挑 JSONRPC(读 AgentScope 所用 a2a-java-sdk 的字节码所得)。 + * 远端把 url 写成同源、首选传输写成别的,并在 additionalInterfaces 里放一个指向别处的 JSONRPC 地址, + * 客户端就会改用后者,消息和 token 被引到任意地址。所以这里宁严勿松:首选传输不是 JSONRPC 就拒绝, + * additionalInterfaces 里任何一项不同源(不管什么传输)也拒绝。代价:把对外地址和内部地址拆开写的远端会被拒, + * 这时把 {@code yoke.a2a.remote.url} 配成它对外声明的地址。 + */ + private boolean cardStaysInOrigin(AgentCard card) { + try { + String preferred = card.preferredTransport(); + if (StrUtil.isNotBlank(preferred) && !"JSONRPC".equalsIgnoreCase(preferred)) { + return false; + } + if (!pinnedOrigin.equals(originOf(card.url()))) { + return false; + } + if (Objects.nonNull(card.additionalInterfaces())) { + for (var each : card.additionalInterfaces()) { + if (!pinnedOrigin.equals(originOf(each.url()))) { + return false; + } + } + } + return true; + } catch (RuntimeException e) { + return false; + } + } + + private RemoteAgentException wrap(Throwable error) { + boolean timedOut = isTimeout(error); + // 底层原因只进服务端日志,异常消息里不带地址和对方返回的原文 + log.warn("调用远端 A2A Agent 失败:{}", error.toString()); + return new RemoteAgentException(timedOut ? "调用远端 Agent 超时(" + timeout.toSeconds() + " 秒)" + : "调用远端 Agent 失败(" + error.getClass().getSimpleName() + ")", timedOut, error); + } + + /** 响应式超时和 HTTP 请求超时谁先到都算超时(二者设成同一个时长,会竞争)。 */ + private static boolean isTimeout(Throwable error) { + for (Throwable t = error; Objects.nonNull(t); t = t.getCause()) { + if (t instanceof TimeoutException || t instanceof java.net.http.HttpTimeoutException) { + return true; + } + } + return false; + } + + /** 协议 + 主机 + 端口(端口缺省时按协议补全),用来比较「是不是同一个服务」。 */ + public static String originOf(String url) { + if (StrUtil.isBlank(url)) { + return ""; + } + URI uri = URI.create(url); + // 主机名里有下划线之类,URI 能解析但 getHost() 是 null:两边都变成 "…://null:80" 会被误判为同源,所以直接拒绝 + if (Objects.isNull(uri.getScheme()) || Objects.isNull(uri.getHost())) { + throw new IllegalArgumentException("无法从地址中解析出协议和主机"); + } + int port = uri.getPort() > 0 ? uri.getPort() : "https".equalsIgnoreCase(uri.getScheme()) ? 443 : 80; + return (uri.getScheme() + "://" + uri.getHost() + ":" + port).toLowerCase(); + } + + /** 取卡片用的解析器;生产装配必须是不跟随重定向的那个,装配测试靠它断言。 */ + public AgentCardResolver cardResolver() { + return cardResolver; + } + + /** 发消息复用的 HTTP 客户端,供生命周期与复用测试断言。 */ + public NoRedirectHttpClient httpClient() { + return httpClient; + } + + /** 容器销毁时关闭复用的 HTTP 客户端及卡片解析器连接池。 */ + public void close() { + httpClient.close(); + if (cardResolver instanceof NoRedirectCardResolver resolver) { + resolver.close(); + } + } + + /** 给发出的 message/send 补上会话标识,并带上 Bearer Token。 */ + private static final class SessionAndAuth extends ClientCallInterceptor { + + private final String sessionId; + private final String token; + + SessionAndAuth(String sessionId, String token) { + this.sessionId = sessionId; + this.token = token; + } + + @Override + public @NonNull PayloadAndHeaders intercept(@NonNull String methodName, @Nullable Object payload, @Nullable Map headers, + @Nullable AgentCard agentCard, @Nullable ClientCallContext context) { + Object forwarded = payload; + if (payload instanceof SendMessageRequest request && StrUtil.isNotBlank(sessionId)) { + Message original = request.getParams().message(); + Map metadata = new HashMap<>(); + if (Objects.nonNull(original.getMetadata())) { + metadata.putAll(original.getMetadata()); + } + metadata.put("sessionId", sessionId); + Message message = new Message.Builder(original).contextId(sessionId).metadata(metadata).build(); + MessageSendParams params = request.getParams(); + forwarded = new SendMessageRequest(request.getId(), + new MessageSendParams(message, params.configuration(), params.metadata())); + } + Map allHeaders = new HashMap<>(Optional.ofNullable(headers).orElse(Map.of())); + if (StrUtil.isNotBlank(token)) { + allHeaders.put("Authorization", "Bearer " + token); + } + return new PayloadAndHeaders(forwarded, allHeaders); + } + } +} diff --git a/src/main/java/com/yoke/a2a/RemoteAgentException.java b/src/main/java/com/yoke/a2a/RemoteAgentException.java new file mode 100644 index 0000000..b925a7b --- /dev/null +++ b/src/main/java/com/yoke/a2a/RemoteAgentException.java @@ -0,0 +1,16 @@ +package com.yoke.a2a; + +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +/** + * 调用远端 A2A Agent 失败。reason 是给调用方看的一句中文说明,不含地址、凭证和远端返回的原文; + * 底层原因挂在 cause 上,只进服务端日志。超时对应 504,其余对应 502。 + * Spring Boot 默认不把 reason 写进错误响应体({@code server.error.include-message} 默认 never)。 + */ +public class RemoteAgentException extends ResponseStatusException { + + public RemoteAgentException(String reason, boolean timeout, Throwable cause) { + super(timeout ? HttpStatus.GATEWAY_TIMEOUT : HttpStatus.BAD_GATEWAY, reason, cause); + } +} diff --git a/src/main/java/com/yoke/a2a/runner/YokeAgentRunner.java b/src/main/java/com/yoke/a2a/runner/YokeAgentRunner.java new file mode 100644 index 0000000..908f34e --- /dev/null +++ b/src/main/java/com/yoke/a2a/runner/YokeAgentRunner.java @@ -0,0 +1,181 @@ +package com.yoke.a2a.runner; + +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.TimeoutException; +import java.util.stream.Collectors; + +import cn.hutool.core.util.StrUtil; +import com.yoke.codec.MessageCodec; +import com.yoke.config.HarnessAgentFactory; +import com.yoke.model.SafeId; +import com.yoke.model.UserContext; +import io.agentscope.core.a2a.server.executor.runner.AgentRequestOptions; +import io.agentscope.core.a2a.server.executor.runner.AgentRunner; +import io.agentscope.core.agent.RuntimeContext; +import io.agentscope.core.event.AgentEvent; +import io.agentscope.core.event.AgentResultEvent; +import io.agentscope.core.message.Msg; +import io.agentscope.core.message.MsgRole; +import io.agentscope.harness.agent.HarnessAgent; +import lombok.extern.slf4j.Slf4j; +import reactor.core.publisher.Flux; + + +/** + * 把「每请求新建 HarnessAgent」接成 A2A 服务端的 {@link AgentRunner}。 + * + *

官方自带的 runner 只认 ReActAgent,而 Yoke 的 Agent 是 HarnessAgent,所以这里自己实现: + * 每次调用走 {@link HarnessAgentFactory#create()} 新建 Agent,流结束、出错、被取消时都关闭它, + * 工具、子 Agent、权限收紧和 HTTP 接口完全一致,A2A 入口不会多出任何工具。 + * + *

三处刻意收紧: + *

    + *
  • 入站消息只取其文本内容,合成一条用户消息。A2A 的 part 元数据可以自报角色, + * 也可以带工具调用块,原样转交会让远端伪造系统消息或工具结果;(框架会把 data 类型的 part 转成文本,实测,所以它仍以用户输入的形态出现)
  • + *
  • userId / sessionId 再校验一次 {@link SafeId} 规则(网关已经校验过,这里是第二道),缺失时与 HTTP 接口同样处理;
  • + *
  • 只放行最终结果事件,并只保留文本(不带思考过程等),与 {@code /api/chat} 返回的内容一致。
  • + *
+ * + *

错误不外泄也不吞:框架会把流里的异常原文拼进回复文本,而回复文本在 A2A 里看起来像一次成功的答复。 + * 所以这里把失败记在 {@link #takeFailure} 的台账里(按 taskId),网关据此改写成 JSON-RPC 的错误响应, + * 异常堆栈和内部信息只进服务端日志。 + * + *

{@link #stop} 是空实现:服务端只开放同步的 {@code message/send},调用在返回前不会被单独取消, + * 也没有暴露 {@code tasks/cancel},所以没有「执行中、可被停止」的任务。 + */ +@Slf4j +public class YokeAgentRunner implements AgentRunner { + + /** 与 HTTP 接口一致:缺 userId 时的默认用户。 */ + static final String DEFAULT_USER_ID = "default"; + + /** 台账最多记这么多条失败,防止网关没来取时无限增长。 */ + private static final int MAX_FAILURES = 1024; + + private final HarnessAgentFactory agentFactory; + private final String name; + private final String description; + private final Duration timeout; + + private final Map failures = new LinkedHashMap<>() { + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > MAX_FAILURES; + } + }; + + public YokeAgentRunner(HarnessAgentFactory agentFactory, String name, String description, Duration timeout) { + this.agentFactory = agentFactory; + this.name = name; + this.description = description; + this.timeout = timeout; + } + + @Override + public String getAgentName() { + return name; + } + + @Override + public String getAgentDescription() { + return description; + } + + @Override + public Flux streamEvents(List requestMessages, AgentRequestOptions options) { + String taskId = options.getTaskId(); + String userId; + String sessionId; + String text; + try { + userId = resolveId(options.getUserId(), DEFAULT_USER_ID, "userId"); + sessionId = resolveId(options.getSessionId(), UUID.randomUUID().toString(), "sessionId"); + text = textOf(requestMessages); + } catch (IllegalArgumentException e) { + recordFailure(taskId, e.getMessage()); + throw e; + } + return Flux.using( + agentFactory::create, + agent -> agent.streamEvents(MessageCodec.toInput(text), contextOf(userId, sessionId)) + .ofType(AgentResultEvent.class) + .map(YokeAgentRunner::textOnly), + // eager=false:结果先交给调用方再关闭 Agent,关闭失败只记日志,不把已经成功的调用改写成失败 + HarnessAgent::close, false) + .timeout(timeout) + .doOnError(error -> { + // 堆栈只进服务端日志;对外只留一句不含内部信息的说明 + log.warn("A2A 调用出错,taskId={} sessionId={}", taskId, sessionId, error); + recordFailure(taskId, error instanceof TimeoutException ? "智能体执行超时" : "智能体执行失败"); + }); + } + + @Override + public void stop(String taskId) { + // 见类说明:同步调用没有可停止的在途任务 + } + + /** 取走(并清除)某个任务的失败说明;没有失败返回空。 */ + public Optional takeFailure(String taskId) { + if (Objects.isNull(taskId)) { + return Optional.empty(); + } + synchronized (failures) { + return Optional.ofNullable(failures.remove(taskId)); + } + } + + private void recordFailure(String taskId, String reason) { + if (Objects.nonNull(taskId)) { + synchronized (failures) { + failures.put(taskId, reason); + } + } + } + + private static String resolveId(String value, String fallback, String field) { + if (StrUtil.isBlank(value)) { + return fallback; + } + if (!SafeId.Validator.isSafe(value)) { + throw new IllegalArgumentException(field + " 格式不合法:只能包含字母、数字、下划线、点和短横线,长度 1 到 64,且不能全是点"); + } + return value; + } + + private static String textOf(List messages) { + String text = messages.stream() + .map(Msg::getTextContent) + .filter(StrUtil::isNotBlank) + .collect(Collectors.joining("\n")); + if (StrUtil.isBlank(text)) { + throw new IllegalArgumentException("消息里没有文本内容"); + } + return text; + } + + private static AgentEvent textOnly(AgentResultEvent event) { + Optional result = Optional.ofNullable(event.getResult()); + String text = result.map(MessageCodec::toText).orElse(""); + return new AgentResultEvent(Msg.builder().id(result.map(Msg::getId).orElse(null)) + .name(result.map(Msg::getName).orElse(null)) + .role(MsgRole.ASSISTANT) + .textContent(text) + .build()); + } + + private static RuntimeContext contextOf(String userId, String sessionId) { + return RuntimeContext.builder() + .userId(userId) + .sessionId(sessionId) + // 与 HTTP 接口相同:业务工具按类型取当前用户,模型看不到也伪造不了 + .put(UserContext.class, new UserContext(userId)) + .build(); + } +} diff --git a/src/main/java/com/yoke/api/A2aApi.java b/src/main/java/com/yoke/api/A2aApi.java new file mode 100644 index 0000000..2196ff3 --- /dev/null +++ b/src/main/java/com/yoke/api/A2aApi.java @@ -0,0 +1,69 @@ +package com.yoke.api; + +import jakarta.servlet.http.HttpServletRequest; + +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; + +/** + * A2A(Agent2Agent)服务端接口:让其他 Agent 把 Yoke 当成一个远端 Agent 来调用。默认关闭, + * 只有 {@code yoke.a2a.server.enabled=true} 时这两个路径才存在,否则是 404。 + * + *

安全:开启就是暴露一个无认证的入口。它走同一个 HarnessAgentFactory,能力等价于 {@code /api/chat} + * (同一批工具、同一个会话存储),调用方还能在请求里自报 {@code userId}。Yoke 目前没有用户体系, + * 所以生产环境必须把它放在网关后面,或者至少配置 {@code yoke.a2a.server.token}(建议从环境变量注入): + * 配置后 JSON-RPC 端点要求 {@code Authorization: Bearer },缺失或错误返回 401,Agent Card 里同步声明 Bearer 认证。 + * 不配置 token 时不校验,启动日志会打 WARN。Agent Card 本身是公开的(调用方要先读它才知道怎么认证), + * 里面只有名字、描述、版本、地址和配置的技能说明。 + * + *

传输安全:{@code public-url} 缺省是 {@code http://localhost:端口},Bearer Token 走的是明文 HTTP。生产必须配置 https 的对外地址, + * 或者由网关终结 TLS,否则 token 会在网络上明文传输。 + * + *

协议:AgentScope 目前实现的是 A2A 0.3 版本(Agent Card 的 protocolVersion 为 0.3.0)。 + * 更新版本的 AgentScope 已改为 A2A 1.0、不再支持 0.3,升级前请以对应版本的手册为准。 + * 传输只有 JSON-RPC。只支持同步非流式的 {@code message/send}:Agent Card 里 {@code capabilities.streaming=false}; + * {@code message/stream}、{@code tasks/resubscribe} 返回「不支持的操作」,{@code tasks/get}、{@code tasks/cancel}、 + * 推送通知配置等其余方法返回「方法不存在」;{@code blocking} 一律按 true 处理,调用在 Agent 跑完之后才返回。 + * + *

会话映射:sessionId 取 {@code message.metadata.sessionId},没有则取 {@code message.contextId},再没有就新建; + * userId 取 {@code message.metadata.userId},缺失为 {@code default}。二者必须符合与 HTTP 接口相同的 {@code @SafeId} 规则 + * (字母、数字、下划线、点、短横线,1 到 64 位,不能全是点),不合法返回 JSON-RPC 的 -32602(InvalidParams)而不是放行。 + * 请求体超过 {@code yoke.a2a.server.max-body-bytes}(默认 256 KB)返回 413(响应体 -32600),认证先于读体,见 {@link #message};{@code /api/chat} 没有这类自定义上限,只受容器默认值约束。 + * 响应里的 {@code contextId} 就是会话 ID,下一次带上它即可延续对话。不支持用 {@code taskId} 接续任务。 + * + *

入站消息一律降级成一条用户消息交给 Agent:part 元数据里自报的角色、工具调用块、工具结果块都不会被当真, + * 非文本的 part 也不会作为多媒体传给模型。注意框架会把 data 类型的 part 转成文本(实测),所以它的内容仍会作为用户输入出现。 + * + *

错误:执行失败返回 JSON-RPC 的 -32603(InternalError),消息只有「智能体执行失败」或「智能体执行超时」, + * 不含异常信息和堆栈(详情只在服务端日志里)。总超时见 {@code yoke.a2a.server.timeout},默认 120 秒。 + * + *

实现说明:这个入口是阻塞的(框架的 JSON-RPC 处理链是同步的),靠虚拟线程撑住并发,和响应式的 {@code /api/chat} 不同; + * 同一个会话的并发请求同样不会被串行化。 + */ +public interface A2aApi { + + /** + * Agent Card(well-known 地址),公开,不需要认证。 + * + * @return Agent Card 的 JSON + */ + @GetMapping(path = "/.well-known/agent-card.json", produces = MediaType.APPLICATION_JSON_VALUE) + ResponseEntity agentCard(); + + /** + * A2A 的 JSON-RPC 端点,只处理 {@code message/send},见类说明。 + * + *

处理顺序:先认证,再看请求体大小,最后才解析。请求体不由 Spring 预先读入,而是由实现自己读取: + * 认证失败(401)不读体;声明的 Content-Length 超过 {@code yoke.a2a.server.max-body-bytes} 直接回 413,也不读体; + * 没声明长度(chunked)的请求限长读取,超过上限就停止读取并回 413。413 的响应体是 JSON-RPC 的 -32600。 + * 早先的版本用 {@code @RequestBody String},Spring 会在认证之前把整个请求体读进内存,未认证的调用者就能让服务器缓冲任意大的数据, + * 现在已修正。 + * + * @param request 原始请求,用来读 Authorization 和请求体 + * @return JSON-RPC 响应;认证失败是 401,请求体过大是 413 + */ + @PostMapping(path = "/a2a", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + ResponseEntity message(HttpServletRequest request); +} diff --git a/src/main/java/com/yoke/api/ChatApi.java b/src/main/java/com/yoke/api/ChatApi.java index f03349c..22b3a42 100644 --- a/src/main/java/com/yoke/api/ChatApi.java +++ b/src/main/java/com/yoke/api/ChatApi.java @@ -75,6 +75,13 @@ * *

隐私:配置了向量化服务({@code yoke.knowledge.embedding})后,用户的检索问题和知识库语料会发送给该服务的提供方。 * + *

请求体大小:本接口对 {@code message} 的长度没有自定义上限,只受容器默认值约束(A2A 入口有可配置的上限,见 {@link A2aApi})。 + * + *

其他入口:开启 {@code yoke.a2a.server.enabled} 后还有 A2A 入口(见 {@link A2aApi}),它走同一个 Agent 工厂、同一批工具、 + * 同一个会话存储,能力与本接口等价,同样没有认证,开启即暴露一个无认证入口(可选的 Bearer Token 只是最小保护); + * 配置了远端 A2A Agent 后有转发入口(见 {@link RemoteChatApi});Actuator 的 health、info、metrics、prometheus 端点和本接口在同一个端口、同样没有认证。 + * A2A 和转发入口默认关闭;Actuator 默认开启但只暴露这四个端点,其中 metrics 和 prometheus 会泄露内部指标,生产应放在网关后面或改用单独的管理端口。 + * *

已知限制:{@code HarnessAgent.close()} 会等待框架里全局的异步写入静默 * ({@code awaitMirrorQuiescence} 和 {@code awaitQuiescence},各最长 5 秒),它在每个请求的清理回调里执行, * 因此是跨请求耦合的:别的请求的在途写入会让这次关闭变慢。目前没有把关闭挪到专用线程,也没做并发压测。 diff --git a/src/main/java/com/yoke/api/RemoteChatApi.java b/src/main/java/com/yoke/api/RemoteChatApi.java new file mode 100644 index 0000000..90edcc1 --- /dev/null +++ b/src/main/java/com/yoke/api/RemoteChatApi.java @@ -0,0 +1,43 @@ +package com.yoke.api; + +import com.yoke.model.ChatResponse; +import com.yoke.model.RemoteChatRequest; +import jakarta.validation.Valid; +import reactor.core.publisher.Mono; + +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * 把一句话转发给配置好的远端 A2A Agent。默认不存在:只有配置了 {@code yoke.a2a.remote.url} + * 或 {@code yoke.a2a.remote.agent-name} 时才注册,否则这个路径是 404。 + * + *

远端地址只来自配置,请求体里没有任何能指定地址的字段,所以不能借它访问任意地址(防 SSRF)。直连 URL 时,远端 Agent Card 里所有声明服务地址的位置 + * ({@code url} 和 {@code additionalInterfaces} 的每一项)都必须与配置同源,首选传输必须是 JSONRPC,否则拒绝调用; + * HTTP 客户端不跟随重定向,请求有超时。 + * 它是个无认证的转发入口,和 {@code /api/chat} 一样:谁能访问 Yoke 就能让 Yoke 以自己的身份(含配置的远端 token) + * 去调用远端,生产必须放在网关后面。 + * + *

它没有放进模型的工具清单:让模型自己决定调用远端,会把远端的回复当作模型可见的输入, + * 远端内容里的提示注入就能影响后续推理,也会让 {@code ToolPermissionTests} 守着的工具清单变长。 + * 需要时由调用方显式走这个接口,回复原样返回、不再交给模型处理。 + * + *

失败的表现:远端不可达、返回错误、Agent Card 与配置地址不同源时返回 502;超过 {@code yoke.a2a.remote.timeout} + * (默认 30 秒)返回 504;响应体不含地址、凭证和远端的原文。 + */ +@RequestMapping("/api/chat/remote") +public interface RemoteChatApi { + + /** + * 向远端 Agent 发送一条消息并返回它的文本回复。 + * + *

{@code sessionId} 会作为 A2A 的 {@code contextId} 和 {@code metadata.sessionId} 传给远端, + * 远端按它延续对话;不传则新建,并在响应里返回。当前没有用户体系,调用远端时不带 userId,远端按它自己的默认用户处理。 + * + * @param request 远端请求,包含可选的会话 ID 和必填的消息 + * @return 远端的回复和本次会话 ID + */ + @PostMapping + Mono ask(@Valid @RequestBody RemoteChatRequest request); +} diff --git a/src/main/java/com/yoke/config/A2aClientConfiguration.java b/src/main/java/com/yoke/config/A2aClientConfiguration.java new file mode 100644 index 0000000..16afba1 --- /dev/null +++ b/src/main/java/com/yoke/config/A2aClientConfiguration.java @@ -0,0 +1,71 @@ +package com.yoke.config; + +import cn.hutool.core.util.StrUtil; +import com.alibaba.nacos.api.ai.AiService; +import com.yoke.a2a.NoRedirectCardResolver; +import com.yoke.a2a.RemoteAgentClient; +import io.agentscope.core.a2a.agent.card.AgentCardResolver; +import io.agentscope.core.nacos.a2a.discovery.NacosAgentCardResolver; +import lombok.extern.slf4j.Slf4j; + +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * 远端 A2A Agent 的客户端装配,配置了 {@code yoke.a2a.remote.url} 或 {@code yoke.a2a.remote.agent-name} 才生效。 + * + *

Agent Card 的来源有两个,同一时刻只用一个,选择规则集中在 {@link #cardSource}: + *

    + *
  • 配了 {@code agent-name} 且 {@code yoke.nacos.a2a.enabled=true}:从 Nacos 按名字发现(优先); + * 此时如果同时配了 {@code url},url 被忽略并打一条 WARN;
  • + *
  • 只配了 {@code url}:well-known 直连;
  • + *
  • 配了 {@code agent-name} 但 Nacos 没开:启动失败,而不是悄悄退回到别的来源。
  • + *
+ */ +@Slf4j +@Configuration(proxyBeanMethods = false) +@ConditionalOnRemoteAgent +public class A2aClientConfiguration { + + /** 取卡片的来源决定调用的是哪个地址,只来自配置。 */ + public enum CardSource { NACOS, WELL_KNOWN } + + @Bean(destroyMethod = "close") + public RemoteAgentClient remoteAgentClient(YokeProperties yoke, ObjectProvider nacos) { + YokeProperties.A2a.Remote remote = yoke.a2a().remote(); + CardSource source = cardSource(yoke); + if (source == CardSource.NACOS) { + if (StrUtil.isNotBlank(remote.url())) { + log.warn("同时配置了 yoke.a2a.remote.url 和 agent-name,且 Nacos 已开启:使用 Nacos 发现,忽略 url"); + } + AiService aiService = nacos.getObject(); + AgentCardResolver resolver = new NacosAgentCardResolver(aiService); + log.info("远端 A2A Agent 来源:Nacos(agent-name={})", remote.agentName()); + // Nacos 发现时地址由注册中心提供,不做同源限制:信任边界是 Nacos + return new RemoteAgentClient(resolver, remote.agentName(), remote.token(), remote.timeout(), null); + } + String url = remote.url().trim(); + if (!url.startsWith("http://") && !url.startsWith("https://")) { + throw new IllegalStateException("yoke.a2a.remote.url 必须以 http:// 或 https:// 开头"); + } + AgentCardResolver resolver = new NoRedirectCardResolver(url, remote.timeout()); + log.info("远端 A2A Agent 来源:well-known 直连 {}", RemoteAgentClient.originOf(url)); + return new RemoteAgentClient(resolver, "remote", remote.token(), remote.timeout(), + RemoteAgentClient.originOf(url)); + } + + /** 选择规则,单独成方法便于直接测试。配置自相矛盾时抛出带说明的异常。 */ + public static CardSource cardSource(YokeProperties yoke) { + YokeProperties.A2a.Remote remote = yoke.a2a().remote(); + boolean byName = StrUtil.isNotBlank(remote.agentName()); + if (byName && yoke.nacos().a2a().enabled()) { + return CardSource.NACOS; + } + if (byName) { + throw new IllegalStateException("配置了 yoke.a2a.remote.agent-name(按名字从 Nacos 发现远端)," + + "但 yoke.nacos.a2a.enabled 没有开启;要么开启 Nacos,要么改用 yoke.a2a.remote.url 直连"); + } + return CardSource.WELL_KNOWN; + } +} diff --git a/src/main/java/com/yoke/config/A2aServerConfiguration.java b/src/main/java/com/yoke/config/A2aServerConfiguration.java new file mode 100644 index 0000000..469383d --- /dev/null +++ b/src/main/java/com/yoke/config/A2aServerConfiguration.java @@ -0,0 +1,152 @@ +package com.yoke.config; + +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import cn.hutool.core.util.StrUtil; +import com.yoke.a2a.A2aGateway; +import com.yoke.a2a.runner.YokeAgentRunner; +import io.a2a.spec.AgentCapabilities; +import io.a2a.spec.AgentCard; +import io.a2a.spec.AgentSkill; +import io.a2a.spec.HTTPAuthSecurityScheme; +import io.a2a.spec.SecurityScheme; +import io.a2a.spec.TransportProtocol; +import io.agentscope.core.a2a.server.AgentScopeA2aServer; +import io.agentscope.core.a2a.server.card.ConfigurableAgentCard; +import io.agentscope.core.a2a.server.transport.TransportProperties; +import io.agentscope.spring.boot.properties.AgentscopeProperties; +import lombok.extern.slf4j.Slf4j; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; + +/** + * A2A 服务端装配,{@code yoke.a2a.server.enabled=true} 才生效,默认整个类都不存在。 + * + *

为什么手写装配而不用官方的 {@code agentscope-a2a-spring-boot-starter}:starter 的自动装配只认 + * {@code ReActAgent} / {@code ReActAgent.Builder},接不上每请求新建 HarnessAgent 的工厂; + * 它自带的控制器也没有认证、不校验标识格式,Card 里的 streaming 还固定写成 true。 + * 这里只用 server 模块的 {@link AgentScopeA2aServer} 和 {@code AgentRunner},端点自己暴露(见 {@link A2aGateway})。 + * 两种做法不能同时启用,本项目不引入 starter,所以不存在冲突。 + */ +@Slf4j +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty(prefix = "yoke.a2a.server", name = "enabled", havingValue = "true") +public class A2aServerConfiguration { + + /** JSON-RPC 端点的路径,与 {@code A2aApi} 里的映射一致。 */ + public static final String RPC_PATH = "/a2a"; + + private static final String SCHEME_NAME = "bearer"; + + @Bean + public YokeAgentRunner yokeAgentRunner(HarnessAgentFactory factory, AgentscopeProperties agentscope, YokeProperties yoke) { + YokeProperties.A2a.Card card = yoke.a2a().server().card(); + String name = Optional.ofNullable(card.name()).filter(StrUtil::isNotBlank) + .orElseGet(() -> agentscope.getAgent().getName()); + String description = Optional.ofNullable(card.description()).filter(StrUtil::isNotBlank) + .orElse("Yoke:基于 AgentScope 的对话 Agent,通过 A2A 协议提供同步问答"); + return new YokeAgentRunner(factory, name, description, yoke.a2a().server().timeout()); + } + + /** 处理 A2A 请求的线程:虚拟线程,框架的处理链是阻塞的。 */ + @Bean(destroyMethod = "shutdown") + public ExecutorService a2aExecutor() { + return Executors.newVirtualThreadPerTaskExecutor(); + } + + @Bean + public AgentScopeA2aServer agentScopeA2aServer(YokeAgentRunner runner, YokeProperties yoke, Environment env, + ExecutorService a2aExecutor) { + YokeProperties.A2a.Server server = yoke.a2a().server(); + requireStrongToken(server); + TransportProperties transport = resolveTransport(server, env); + + ConfigurableAgentCard.Builder card = new ConfigurableAgentCard.Builder() + .name(runner.getAgentName()) + .description(runner.getAgentDescription()) + .version(server.card().version()) + .skills(server.card().skills().stream().map(A2aServerConfiguration::skill).toList()); + if (server.tokenConfigured()) { + // Card 与实际行为一致:配了 token 就声明需要 Bearer + Map schemes = Map.of(SCHEME_NAME, + new HTTPAuthSecurityScheme(null, "bearer", "在 Authorization 请求头里带 Bearer Token")); + card.securitySchemes(schemes).security(List.of(Map.of(SCHEME_NAME, List.of()))); + } else { + log.warn("A2A 服务端已开启但没有配置 yoke.a2a.server.token:{} 是一个无认证入口," + + "等价于 /api/chat,调用方还能自报 userId。生产必须放在网关后面或配置 token", RPC_PATH); + } + return AgentScopeA2aServer.builder(runner) + .agentCard(card.build()) + .withTransport(transport) + .executor(a2aExecutor) + .build(); + } + + @Bean + public A2aGateway a2aGateway(AgentScopeA2aServer server, YokeAgentRunner runner, YokeProperties yoke) { + return new A2aGateway(server, runner, publishedCard(server.getAgentCard()), yoke.a2a().server().token(), + yoke.a2a().server().maxBodyBytes()); + } + + /** + * 配置了 token 但太短就启动失败,而不是只打 WARN:Bearer Token 是唯一的保护, + * 短 token(「123456」「test」)等于没有,而 WARN 在容器日志里很容易被忽略。 + * 报错信息不含 token 本身。没配置 token 的情形另有 WARN,不在这里处理。 + */ + static void requireStrongToken(YokeProperties.A2a.Server server) { + if (server.tokenConfigured() && server.token().length() < YokeProperties.A2a.Server.MIN_TOKEN_LENGTH) { + throw new IllegalStateException("yoke.a2a.server.token 太短(至少 " + YokeProperties.A2a.Server.MIN_TOKEN_LENGTH + + " 个字符,当前 " + server.token().length() + " 个)。请用足够随机的值,例如 openssl rand -hex 24,并通过环境变量 YOKE_A2A_TOKEN 注入"); + } + } + + /** + * 对外公布的 Agent Card。官方转换器把 capabilities.streaming 固定写成 true(不可配置), + * 而 Yoke 只提供同步的 message/send,所以这里改成 false,让 Card 说真话。 + */ + static AgentCard publishedCard(AgentCard card) { + AgentCapabilities original = card.capabilities(); + AgentCapabilities honest = new AgentCapabilities(false, false, false, + Optional.ofNullable(original).map(AgentCapabilities::extensions).orElse(List.of())); + return new AgentCard.Builder(card).capabilities(honest).build(); + } + + private static AgentSkill skill(YokeProperties.A2a.Skill skill) { + return new AgentSkill(skill.id(), skill.name(), + Optional.ofNullable(skill.description()).filter(StrUtil::isNotBlank).orElseGet(skill::name), + skill.tags(), List.of(), null, null, null); + } + + static TransportProperties resolveTransport(YokeProperties.A2a.Server server, Environment env) { + String raw = Optional.ofNullable(server.publicUrl()).filter(StrUtil::isNotBlank) + .map(String::trim) + .orElseGet(() -> "http://localhost:" + env.getProperty("server.port", "8080")); + if (!raw.startsWith("http://") && !raw.startsWith("https://")) { + throw new IllegalStateException("yoke.a2a.server.public-url 必须以 http:// 或 https:// 开头"); + } + URI base; + try { + base = URI.create(raw); + } catch (IllegalArgumentException e) { + throw new IllegalStateException("yoke.a2a.server.public-url 不是合法的 URL"); + } + if (Objects.isNull(base.getHost()) || Objects.nonNull(base.getRawUserInfo()) + || Objects.nonNull(base.getRawQuery()) || Objects.nonNull(base.getRawFragment())) { + throw new IllegalStateException("yoke.a2a.server.public-url 格式不合法:需要有效的协议与主机,且不能带用户信息、查询参数或片段"); + } + boolean tls = "https".equalsIgnoreCase(base.getScheme()); + int port = base.getPort() > 0 ? base.getPort() : tls ? 443 : 80; + String basePath = Optional.ofNullable(base.getPath()).orElse("").replaceAll("/+$", ""); + return TransportProperties.builder(TransportProtocol.JSONRPC.asString()) + .host(base.getHost()).port(port).path(basePath + RPC_PATH).supportTls(tls).build(); + } +} diff --git a/src/main/java/com/yoke/config/ConditionalOnRemoteAgent.java b/src/main/java/com/yoke/config/ConditionalOnRemoteAgent.java new file mode 100644 index 0000000..4bd688a --- /dev/null +++ b/src/main/java/com/yoke/config/ConditionalOnRemoteAgent.java @@ -0,0 +1,34 @@ +package com.yoke.config; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import cn.hutool.core.util.StrUtil; +import org.jspecify.annotations.NonNull; + +import org.springframework.context.annotation.Conditional; +import org.springframework.context.annotation.ConditionContext; +import org.springframework.core.env.Environment; +import org.springframework.core.type.AnnotatedTypeMetadata; +import org.springframework.context.annotation.Condition; + +/** 只在配置了远端 A2A Agent({@code yoke.a2a.remote.url} 或 {@code yoke.a2a.remote.agent-name})时才生效。 */ +@Documented +@Target({ElementType.TYPE, ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +@Conditional(ConditionalOnRemoteAgent.RemoteConfigured.class) +public @interface ConditionalOnRemoteAgent { + + class RemoteConfigured implements Condition { + + @Override + public boolean matches(@NonNull ConditionContext context, @NonNull AnnotatedTypeMetadata metadata) { + Environment env = context.getEnvironment(); + return StrUtil.isNotBlank(env.getProperty("yoke.a2a.remote.url")) + || StrUtil.isNotBlank(env.getProperty("yoke.a2a.remote.agent-name")); + } + } +} diff --git a/src/main/java/com/yoke/config/NacosConfiguration.java b/src/main/java/com/yoke/config/NacosConfiguration.java new file mode 100644 index 0000000..507c9e4 --- /dev/null +++ b/src/main/java/com/yoke/config/NacosConfiguration.java @@ -0,0 +1,79 @@ +package com.yoke.config; + +import java.util.Objects; + +import com.alibaba.nacos.api.ai.AiService; +import com.yoke.nacos.NacosA2aRegistrar; +import com.yoke.nacos.NacosPromptMiddleware; +import com.yoke.nacos.NacosSupport; +import io.a2a.spec.AgentCard; +import io.agentscope.core.a2a.server.AgentScopeA2aServer; +import lombok.extern.slf4j.Slf4j; + +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.event.EventListener; + +/** + * Nacos 接线,开关全部默认关闭且互不绑死: + *

    + *
  • {@code yoke.nacos.a2a.enabled}:服务端开启时注册 Agent Card,配了远端 agent-name 时从这里发现;
  • + *
  • {@code yoke.nacos.prompt.enabled}:Prompt 热更新;
  • + *
  • Skill 托管(nacos-skill)本轮没有接入。
  • + *
+ * 任何一个开关打开就创建一个共享的 Nacos 客户端(一条 gRPC 通道),并在 Bean 创建时探活,失败则启动失败。 + */ +@Slf4j +@Configuration(proxyBeanMethods = false) +@ConditionalOnExpression("${yoke.nacos.a2a.enabled:false} or ${yoke.nacos.prompt.enabled:false}") +public class NacosConfiguration { + + @Bean(destroyMethod = "shutdown") + public AiService nacosAiService(YokeProperties yoke) { + return NacosSupport.connect(yoke.nacos(), yoke.workspace()); + } + + @Bean + @ConditionalOnProperty(prefix = "yoke.nacos.prompt", name = "enabled", havingValue = "true") + public NacosPromptMiddleware nacosPromptMiddleware(AiService nacosAiService, YokeProperties yoke) { + return new NacosPromptMiddleware(nacosAiService, yoke.nacos().prompt().key(), yoke.nacos().prompt().timeout()); + } + + @Bean(destroyMethod = "deregister") + @ConditionalOnProperty(prefix = "yoke.nacos.a2a", name = "enabled", havingValue = "true") + public Registration nacosA2aRegistration(AiService nacosAiService, YokeProperties yoke, + ObjectProvider server) { + return new Registration(new NacosA2aRegistrar(nacosAiService, yoke.nacos().a2a().registerAsLatest()), server); + } + + /** 应用就绪后注册;A2A 服务端没开就只做发现,不注册。 */ + public static class Registration { + + private final NacosA2aRegistrar registrar; + private final ObjectProvider server; + + Registration(NacosA2aRegistrar registrar, ObjectProvider server) { + this.registrar = registrar; + this.server = server; + } + + @EventListener(ApplicationReadyEvent.class) + public void onReady() { + AgentScopeA2aServer a2aServer = server.getIfAvailable(); + if (Objects.isNull(a2aServer)) { + log.info("A2A 服务端未开启(yoke.a2a.server.enabled=false),Nacos 只用于发现远端,不注册本服务"); + return; + } + AgentCard card = A2aServerConfiguration.publishedCard(a2aServer.getAgentCard()); + registrar.register(card); + } + + public void deregister() { + registrar.deregister(); + } + } +} diff --git a/src/main/java/com/yoke/config/RedisHealthConfiguration.java b/src/main/java/com/yoke/config/RedisHealthConfiguration.java new file mode 100644 index 0000000..3a2dc6b --- /dev/null +++ b/src/main/java/com/yoke/config/RedisHealthConfiguration.java @@ -0,0 +1,30 @@ +package com.yoke.config; + +import redis.clients.jedis.RedisClient; + +import org.springframework.boot.health.contributor.Health; +import org.springframework.boot.health.contributor.HealthIndicator; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * Redis 的健康检查。Yoke 直接用 Jedis,没有 Spring Data Redis 的连接工厂,Boot 不会自动提供 Redis 的健康指示器, + * 所以这里补一个:ping 失败 /actuator/health 就是 DOWN,编排系统据此摘掉实例。 + * 只报 UP/DOWN,不带连接串和异常信息(health 端点不需要也不应该泄露它们)。 + */ +@Configuration(proxyBeanMethods = false) +public class RedisHealthConfiguration { + + /** Bean 名 redisHealthIndicator 决定它在 health 里的组件名是 redis。 */ + @Bean + public HealthIndicator redisHealthIndicator(RedisClient jedis) { + return () -> { + try { + jedis.ping(); + return Health.up().build(); + } catch (RuntimeException e) { + return Health.down().build(); + } + }; + } +} diff --git a/src/main/java/com/yoke/config/YokeProperties.java b/src/main/java/com/yoke/config/YokeProperties.java index 3106dc0..1bf53bd 100644 --- a/src/main/java/com/yoke/config/YokeProperties.java +++ b/src/main/java/com/yoke/config/YokeProperties.java @@ -27,6 +27,8 @@ * @param workspace HarnessAgent 的工作区目录,放压缩前转存的消息、记忆等本地文件 * @param knowledge 知识库检索(可选的向量化配置) * @param mcp 要接入的外部 MCP 服务,默认一个也不接 + * @param a2a A2A 互通:对外暴露的服务端(默认关闭)和要调用的远端 Agent(默认没有) + * @param nacos Nacos 接线:A2A 注册发现、Prompt 热更新,默认全部关闭 */ @Validated @ConfigurationProperties(prefix = "yoke") @@ -35,7 +37,9 @@ public record YokeProperties( @DefaultValue Compaction compaction, @NotBlank String workspace, @Valid @DefaultValue Knowledge knowledge, - @Valid @DefaultValue Mcp mcp) { + @Valid @DefaultValue Mcp mcp, + @Valid @DefaultValue A2a a2a, + @Valid @DefaultValue Nacos nacos) { /** * Redis 配置。 @@ -190,15 +194,216 @@ public record McpServer( /** 地址和请求头里可能带令牌:toString 只留协议、主机和端口,请求头只列名字。 */ @Override public @NonNull String toString() { - String origin; - try { - URI uri = URI.create(url); - origin = uri.getScheme() + "://" + uri.getHost() + (uri.getPort() > 0 ? ":" + uri.getPort() : ""); - } catch (IllegalArgumentException e) { - origin = ""; - } - return "McpServer[name=" + name + ", transport=" + transport + ", url=" + origin + return "McpServer[name=" + name + ", transport=" + transport + ", url=" + originOnly(url) + ", timeout=" + timeout + ", headers=" + headers.keySet() + "]"; } } + + /** + * A2A 互通配置。 + * + * @param server 对外暴露的 A2A 服务端;默认关闭 + * @param remote 要调用的远端 A2A Agent;不配置就没有远端调用能力 + */ + public record A2a(@Valid @DefaultValue Server server, @Valid @DefaultValue Remote remote) { + + /** 全部使用默认值:服务端关闭、没有远端。 */ + public static A2a disabled() { + return new A2a(new Server(false, null, null, Duration.ofSeconds(120), Server.DEFAULT_MAX_BODY_BYTES, new Card(null, null, "1.0.0", List.of())), + new Remote(null, null, null, Duration.ofSeconds(30))); + } + + /** + * A2A 服务端。开启就是一个等价于 {@code /api/chat} 的入口:Yoke 目前没有任何认证, + * 调用方还能自报 userId。生产必须放在网关后面,或至少配置 {@code token}。 + * + * @param enabled 是否注册 Agent Card 和 JSON-RPC 端点,默认 false + * @param token 可选的 Bearer Token,只保护 JSON-RPC 端点(Agent Card 公开,里面会声明需要 Bearer); + * 来自环境变量,不配置就不校验(启动时打 WARN) + * @param publicUrl 外部能访问到的根地址,例如 {@code https://yoke.example.com};写进 Agent Card 和 Nacos 注册, + * 不配置时用 {@code http://localhost:{server.port}} + * @param timeout 一次调用的总超时,默认 120 秒 + * @param maxBodyBytes JSON-RPC 请求体的大小上限(字节),默认 256 KB,超过返回 -32600;非法值回落到默认 + * @param card Agent Card 里的描述信息 + */ + public record Server( + @DefaultValue("false") boolean enabled, + String token, + String publicUrl, + @DefaultValue("120s") Duration timeout, + @DefaultValue("262144") int maxBodyBytes, + @Valid @DefaultValue Card card) { + + public static final int DEFAULT_MAX_BODY_BYTES = 256 * 1024; + + /** token 至少这么长,否则启动失败(见 A2aServerConfiguration.requireStrongToken)。 */ + public static final int MIN_TOKEN_LENGTH = 16; + + public Server { + if (Objects.isNull(timeout) || timeout.isZero() || timeout.isNegative()) { + timeout = Duration.ofSeconds(120); + } + if (maxBodyBytes <= 0) { + maxBodyBytes = DEFAULT_MAX_BODY_BYTES; + } + } + + public boolean tokenConfigured() { + return StrUtil.isNotBlank(token); + } + + /** token 不进日志和调试输出。 */ + @Override + public @NonNull String toString() { + return "Server[enabled=" + enabled + ", token=" + (tokenConfigured() ? "***" : null) + + ", publicUrl=" + publicUrl + ", timeout=" + timeout + ", card=" + card + "]"; + } + } + + /** + * Agent Card 的描述信息;名字缺省时用 {@code agentscope.agent.name},描述缺省时用一句默认说明。 + * + * @param name 对外名字,也是 Nacos 里的 Agent 名 + * @param description 描述 + * @param version 版本号,默认 1.0.0 + * @param skills 对外宣告的技能(只是描述,不会让 Agent 多出任何工具) + */ + public record Card( + String name, String description, @DefaultValue("1.0.0") String version, + @DefaultValue List<@Valid Skill> skills) { + + public Card { + skills = Optional.ofNullable(skills).map(List::copyOf).orElse(List.of()); + } + } + + /** + * Agent Card 里的一个技能条目。 + * + * @param id 技能标识 + * @param name 技能名 + * @param description 说明 + * @param tags 标签 + */ + public record Skill( + @NotBlank String id, @NotBlank String name, String description, @DefaultValue List tags) { + + public Skill { + tags = Optional.ofNullable(tags).map(List::copyOf).orElse(List.of()); + } + } + + /** + * 远端 A2A Agent。地址只来自配置,请求体不能影响它(防 SSRF)。两种来源,同一时刻只用一种: + *
    + *
  • {@code url}:well-known 直连,读取 {@code url + /.well-known/agent-card.json};
  • + *
  • {@code agentName}:到 Nacos 里按名字发现,要求 {@code yoke.nacos.a2a.enabled=true};两个都配时用 Nacos。
  • + *
+ * + * @param url 远端根地址,例如 {@code http://other:8080} + * @param agentName Nacos 里的远端 Agent 名 + * @param token 调用远端时带的 Bearer Token,可选 + * @param timeout 一次调用的超时,默认 30 秒 + */ + public record Remote(String url, String agentName, String token, @DefaultValue("30s") Duration timeout) { + + public Remote { + if (Objects.isNull(timeout) || timeout.isZero() || timeout.isNegative()) { + timeout = Duration.ofSeconds(30); + } + } + + public boolean configured() { + return StrUtil.isNotBlank(url) || StrUtil.isNotBlank(agentName); + } + + /** 地址里可能带路径或参数,token 更不能进日志:只留协议、主机和端口,以及是否有 token。 */ + @Override + public @NonNull String toString() { + return "Remote[url=" + originOnly(url) + ", agentName=" + agentName + ", token=" + + (StrUtil.isNotBlank(token) ? "***" : null) + ", timeout=" + timeout + "]"; + } + } + } + + /** 只保留协议、主机和端口,去掉可能含敏感信息的路径、查询参数和用户信息;空值返回 null。 */ + private static String originOnly(String raw) { + if (StrUtil.isBlank(raw)) { + return null; + } + try { + URI uri = URI.create(raw.trim()); + if (Objects.isNull(uri.getScheme()) || Objects.isNull(uri.getHost())) { + return ""; + } + return uri.getScheme() + "://" + uri.getHost() + (uri.getPort() > 0 ? ":" + uri.getPort() : ""); + } catch (IllegalArgumentException e) { + return ""; + } + } + + /** + * Nacos 接线配置。所有开关默认关闭且互不绑死:只开 Prompt 热更新不需要开 A2A,反之亦然。 + * 任何一个开关打开,启动时都会先探活,连不上直接启动失败。 + * + * @param serverAddr Nacos 地址,格式 {@code host:port},默认 127.0.0.1:8848;AI 通道还需要 gRPC 端口(主端口 + 1000) + * @param namespace 命名空间 ID(不是名称),不配置用 public + * @param username 用户名,Nacos 开了鉴权才需要;来自环境变量 + * @param password 密码,来自环境变量,不进日志 + * @param a2a A2A 注册发现 + * @param prompt Prompt 热更新 + */ + public record Nacos( + @DefaultValue("127.0.0.1:8848") String serverAddr, + String namespace, + String username, + String password, + @DefaultValue A2aSwitch a2a, + @DefaultValue PromptSwitch prompt) { + + /** 全部使用默认值:所有开关关闭。 */ + public static Nacos disabled() { + return new Nacos("127.0.0.1:8848", null, null, null, new A2aSwitch(false, false), + new PromptSwitch(false, "yoke-system-prompt", Duration.ofSeconds(2))); + } + + /** 任何一个开关打开就需要连接 Nacos。 */ + public boolean anyEnabled() { + return a2a.enabled() || prompt.enabled(); + } + + /** 密码不进日志和调试输出。 */ + @Override + public @NonNull String toString() { + return "Nacos[serverAddr=" + serverAddr + ", namespace=" + namespace + ", username=" + username + + ", password=" + (StrUtil.isNotBlank(password) ? "***" : null) + ", a2a=" + a2a + + ", prompt=" + prompt + "]"; + } + + /** + * A2A 注册发现开关:服务端开启时把 Agent Card 注册进去,配了 {@code yoke.a2a.remote.agent-name} 时从这里发现远端。 + * + * @param enabled 是否启用,默认 false + * @param registerAsLatest 注册时是否把这个版本设为最新版本 + */ + public record A2aSwitch(@DefaultValue("false") boolean enabled, @DefaultValue("false") boolean registerAsLatest) { + } + + /** + * Prompt 热更新开关:每轮对话把 Nacos 里最新的提示词追加到内置提示词之后。 + * + * @param enabled 是否启用,默认 false + * @param key Nacos 里的 Prompt Key + * @param timeout 每轮拉取的超时,默认 2 秒;超时按拉取失败处理(沿用内置提示词),不拖住对话 + */ + public record PromptSwitch(@DefaultValue("false") boolean enabled, @DefaultValue("yoke-system-prompt") String key, + @DefaultValue("2s") Duration timeout) { + + public PromptSwitch { + if (Objects.isNull(timeout) || timeout.isZero() || timeout.isNegative()) { + timeout = Duration.ofSeconds(2); + } + } + } + } } diff --git a/src/main/java/com/yoke/controller/A2aController.java b/src/main/java/com/yoke/controller/A2aController.java new file mode 100644 index 0000000..0a428a0 --- /dev/null +++ b/src/main/java/com/yoke/controller/A2aController.java @@ -0,0 +1,67 @@ +package com.yoke.controller; + +import java.io.IOException; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.TreeMap; + +import com.yoke.a2a.A2aGateway; +import com.yoke.api.A2aApi; +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequiredArgsConstructor +@ConditionalOnProperty(prefix = "yoke.a2a.server", name = "enabled", havingValue = "true") +public class A2aController implements A2aApi { + + private final A2aGateway gateway; + + @Override + public ResponseEntity agentCard() { + return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(gateway.agentCardJson()); + } + + @Override + public ResponseEntity message(HttpServletRequest request) { + Map headers = headersOf(request); + A2aGateway.Reply reply = gateway.preflight(headers, request.getContentLengthLong()); + if (Objects.isNull(reply)) { + String body; + try { + body = gateway.readBody(request.getInputStream()); + } catch (IOException e) { + return respond(gateway.unreadable()); + } + reply = Optional.ofNullable(body).map(text -> gateway.handle(text, headers)).orElseGet(gateway::tooLarge); + } + return respond(reply); + } + + private static ResponseEntity respond(A2aGateway.Reply reply) { + ResponseEntity.BodyBuilder response = ResponseEntity.status(HttpStatus.valueOf(reply.status())) + .contentType(MediaType.APPLICATION_JSON); + if (Objects.nonNull(reply.wwwAuthenticate())) { + response.header(HttpHeaders.WWW_AUTHENTICATE, reply.wwwAuthenticate()); + } + return response.body(reply.body()); + } + + private static Map headersOf(HttpServletRequest request) { + Map headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + for (String name : Collections.list(request.getHeaderNames())) { + headers.put(name, request.getHeader(name)); + } + return new HashMap<>(headers); + } +} diff --git a/src/main/java/com/yoke/controller/RemoteChatController.java b/src/main/java/com/yoke/controller/RemoteChatController.java new file mode 100644 index 0000000..06ff3bb --- /dev/null +++ b/src/main/java/com/yoke/controller/RemoteChatController.java @@ -0,0 +1,31 @@ +package com.yoke.controller; + +import java.util.Optional; +import java.util.UUID; + +import cn.hutool.core.util.StrUtil; +import com.yoke.a2a.RemoteAgentClient; +import com.yoke.api.RemoteChatApi; +import com.yoke.config.ConditionalOnRemoteAgent; +import com.yoke.model.ChatResponse; +import com.yoke.model.RemoteChatRequest; +import lombok.RequiredArgsConstructor; +import reactor.core.publisher.Mono; + +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequiredArgsConstructor +@ConditionalOnRemoteAgent +public class RemoteChatController implements RemoteChatApi { + + private final RemoteAgentClient remote; + + @Override + public Mono ask(RemoteChatRequest request) { + String sessionId = Optional.ofNullable(request.sessionId()) + .filter(StrUtil::isNotBlank) + .orElseGet(() -> UUID.randomUUID().toString()); + return remote.ask(sessionId, request.message()).map(reply -> new ChatResponse(sessionId, reply)); + } +} diff --git a/src/main/java/com/yoke/model/RemoteChatRequest.java b/src/main/java/com/yoke/model/RemoteChatRequest.java new file mode 100644 index 0000000..172e315 --- /dev/null +++ b/src/main/java/com/yoke/model/RemoteChatRequest.java @@ -0,0 +1,14 @@ +package com.yoke.model; + +import jakarta.validation.constraints.NotBlank; + +/** + * 转发给远端 A2A Agent 的请求。只有会话和消息,没有任何能指定远端地址的字段。 + * + * @param sessionId 远端会话 ID,不传则新建;格式见 {@link SafeId} + * @param message 要发给远端的话,必填 + */ +public record RemoteChatRequest( + @SafeId String sessionId, + @NotBlank(message = "message 不能为空") String message) { +} diff --git a/src/main/java/com/yoke/nacos/NacosA2aRegistrar.java b/src/main/java/com/yoke/nacos/NacosA2aRegistrar.java new file mode 100644 index 0000000..0838818 --- /dev/null +++ b/src/main/java/com/yoke/nacos/NacosA2aRegistrar.java @@ -0,0 +1,73 @@ +package com.yoke.nacos; + +import java.net.URI; +import java.util.Objects; + +import com.alibaba.nacos.api.ai.AiService; +import com.alibaba.nacos.api.ai.model.a2a.AgentEndpoint; +import com.alibaba.nacos.api.exception.NacosException; +import io.a2a.spec.AgentCard; +import io.a2a.spec.TransportProtocol; +import io.agentscope.core.nacos.a2a.registry.NacosA2aRegistry; +import io.agentscope.core.nacos.a2a.registry.NacosA2aRegistryProperties; +import io.agentscope.core.nacos.a2a.registry.NacosA2aRegistryTransportProperties; +import lombok.extern.slf4j.Slf4j; + +/** + * 把 Agent Card 和服务端点注册到 Nacos,关闭时注销端点。 + * + *

没有走框架的 {@code AgentScopeA2aServer.postEndpointReady()} 注册器链:那条链会把注册失败吞成一条 ERROR 日志, + * 应用照常启动但永远不会被发现。这里直接调用 {@link NacosA2aRegistry},失败就抛出,让应用启动失败。 + * 调用时机是应用就绪之后({@code ApplicationReadyEvent}),此时 HTTP 端口已经在监听,别人发现后马上能调用。 + */ +@Slf4j +public class NacosA2aRegistrar { + + private final AiService aiService; + private final boolean registerAsLatest; + private AgentCard registered; + private AgentEndpoint endpoint; + + public NacosA2aRegistrar(AiService aiService, boolean registerAsLatest) { + this.aiService = aiService; + this.registerAsLatest = registerAsLatest; + } + + /** 注册 Agent Card 和 JSON-RPC 端点(地址取自 Card 自己的 url,与对外公布的一致)。 */ + public synchronized void register(AgentCard card) { + URI uri = URI.create(card.url()); + boolean tls = "https".equalsIgnoreCase(uri.getScheme()); + int endpointPort = uri.getPort() > 0 ? uri.getPort() : tls ? 443 : 80; + NacosA2aRegistryProperties props = NacosA2aRegistryProperties.builder().setAsLatest(registerAsLatest).build(); + props.addTransport(NacosA2aRegistryTransportProperties.builder() + .transport(TransportProtocol.JSONRPC.asString()).host(uri.getHost()).port(endpointPort) + .path(uri.getPath()).supportTls(tls).build()); + new NacosA2aRegistry(aiService).registerAgent(card, props); + this.registered = card; + // 注销时给出和注册时完全一致的端点(实测只给地址和端口的简写形式也能注销,这里不依赖这一点)。 + // 注意注销在服务端是异步生效的,实测要几百毫秒 + AgentEndpoint toRemove = new AgentEndpoint(); + toRemove.setTransport(TransportProtocol.JSONRPC.asString()); + toRemove.setAddress(uri.getHost()); + toRemove.setPort(endpointPort); + toRemove.setPath(uri.getPath()); + toRemove.setSupportTls(tls); + toRemove.setVersion(card.version()); + this.endpoint = toRemove; + log.info("已把 Agent {} 注册到 Nacos({}:{})", card.name(), uri.getHost(), endpointPort); + } + + /** 注销端点;Agent Card 本身留在 Nacos 里(它是配置数据,不是在线状态)。 */ + public synchronized void deregister() { + if (Objects.isNull(registered)) { + return; + } + try { + aiService.deregisterAgentEndpoint(registered.name(), endpoint); + log.info("已从 Nacos 注销 Agent {} 的端点", registered.name()); + } catch (NacosException | RuntimeException e) { + log.warn("从 Nacos 注销端点失败:{}(连接关闭后临时实例也会被服务端摘除)", e.getClass().getSimpleName()); + } + registered = null; + } +} diff --git a/src/main/java/com/yoke/nacos/NacosPromptMiddleware.java b/src/main/java/com/yoke/nacos/NacosPromptMiddleware.java new file mode 100644 index 0000000..3b1f1e6 --- /dev/null +++ b/src/main/java/com/yoke/nacos/NacosPromptMiddleware.java @@ -0,0 +1,105 @@ +package com.yoke.nacos; + +import java.time.Duration; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicLong; + +import cn.hutool.core.util.StrUtil; +import com.alibaba.nacos.api.ai.AiService; +import com.alibaba.nacos.api.exception.NacosException; +import io.agentscope.core.agent.Agent; +import io.agentscope.core.agent.RuntimeContext; +import io.agentscope.core.middleware.MiddlewareBase; +import lombok.extern.slf4j.Slf4j; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + + +/** + * Prompt 热更新:每轮组装系统提示词时,直接向 Nacos 拉最新的 Prompt,追加到内置提示词之后。 + * + *

为什么每轮直接拉,而不用官方的 {@code NacosPromptListener}:后者在本地缓存 Prompt,靠服务端推送更新, + * 一次性手工测量(AgentScope 加 Nacos 3.x)改完后要过 8 到 18 秒缓存才变,而直接 {@code getPrompt} 改完立刻拿到新版本。 + * 代价是每轮多一次 gRPC 往返。 + * + *

为什么是追加而不是替换:内置提示词里还有 Harness 自己拼进去的工作区、工具、技能说明,替换会把它们一起抹掉。 + * + *

信任边界:谁能写 Nacos 里这个 Prompt,谁就能改 Yoke 的系统提示词(它在内置提示词之后,对模型有很高的权重)。 + * 所以 Prompt 的来源必须受信,生产必须开启 Nacos 鉴权,并限制谁能发布这个 Key。 + * + *

保证: + *

    + *
  • 拉失败原样返回:Nacos 连不上、超时({@code yoke.nacos.prompt.timeout},默认 2 秒)、Prompt 不存在、内容空白, + * 都返回当前提示词,对话不受影响;
  • + *
  • 两种情形分开记日志并限频:「Prompt 不存在」(配置问题)和「Nacos 不可达或超时」(环境问题)各自每分钟最多一条 WARN, + * 其余降到 debug,避免每轮都刷屏;
  • + *
  • 防重复拼接:当前提示词已包含这段内容就不再追加;
  • + *
  • 不卡住事件循环:取值是阻塞调用,放到弹性线程池上执行。注意 {@code Mono.timeout} 只取消等待, + * 阻塞在弹性线程上的 {@code getPrompt} 仍占着线程直到 gRPC 自己超时;Nacos 持续不可达时,每一轮对话会占住一个弹性线程 + * (线程池有界,所以是有界的资源占用,不是无限增长)。
  • + *
+ */ +@Slf4j +public class NacosPromptMiddleware implements MiddlewareBase { + + private static final long WARN_INTERVAL_NANOS = Duration.ofMinutes(1).toNanos(); + + private final AiService aiService; + private final String key; + private final Duration timeout; + private final AtomicLong lastMissingWarn = new AtomicLong(System.nanoTime() - WARN_INTERVAL_NANOS - 1); + private final AtomicLong lastUnavailableWarn = new AtomicLong(System.nanoTime() - WARN_INTERVAL_NANOS - 1); + + public NacosPromptMiddleware(AiService aiService, String key, Duration timeout) { + this.aiService = aiService; + this.key = key; + this.timeout = timeout; + } + + @Override + public Mono onSystemPrompt(Agent agent, RuntimeContext ctx, String currentPrompt) { + return Mono.fromCallable(() -> aiService.getPrompt(key)) + .subscribeOn(Schedulers.boundedElastic()) + .timeout(timeout) + // getTemplate 可能是 null:当作「没有内容」,走和 Prompt 不存在相同的分支 + .flatMap(prompt -> Mono.justOrEmpty(prompt.getTemplate())) + .map(latest -> merge(currentPrompt, latest)) + .switchIfEmpty(Mono.fromSupplier(() -> { + warnLimited(lastMissingWarn, "Nacos 里的 Prompt 没有内容,沿用内置提示词(key={})", key); + return currentPrompt; + })) + .onErrorResume(error -> { + if (error instanceof NacosException nacos && nacos.getErrCode() == NacosException.NOT_FOUND) { + warnLimited(lastMissingWarn, "Nacos 里没有这个 Prompt,沿用内置提示词(key={})", key); + } else { + warnLimited(lastUnavailableWarn, "从 Nacos 拉取 Prompt 失败或超时,沿用内置提示词(key={},原因:{})", + key, error.getClass().getSimpleName()); + } + return Mono.just(currentPrompt); + }); + } + + private void warnLimited(AtomicLong last, String message, Object... args) { + long now = System.nanoTime(); + long previous = last.get(); + if (now - previous >= WARN_INTERVAL_NANOS && last.compareAndSet(previous, now)) { + log.warn(message, args); + } else { + log.debug(message, args); + } + } + + /** 把最新的提示词追加到当前提示词之后;空白或已包含时原样返回。 */ + static String merge(String current, String latest) { + if (StrUtil.isBlank(latest)) { + return current; + } + String addition = latest.strip(); + if (Objects.nonNull(current) && current.contains(addition)) { + return current; + } + String base = Optional.ofNullable(current).filter(StrUtil::isNotBlank).map(text -> text.stripTrailing() + "\n\n").orElse(""); + return base + addition; + } +} diff --git a/src/main/java/com/yoke/nacos/NacosSupport.java b/src/main/java/com/yoke/nacos/NacosSupport.java new file mode 100644 index 0000000..a907030 --- /dev/null +++ b/src/main/java/com/yoke/nacos/NacosSupport.java @@ -0,0 +1,103 @@ +package com.yoke.nacos; + +import java.nio.file.Path; +import java.util.Objects; +import java.util.Properties; +import java.util.UUID; + +import cn.hutool.core.util.StrUtil; +import com.alibaba.nacos.api.PropertyKeyConst; +import com.alibaba.nacos.api.ai.AiFactory; +import com.alibaba.nacos.api.ai.AiService; +import com.alibaba.nacos.api.exception.NacosException; +import com.yoke.config.YokeProperties; +import lombok.extern.slf4j.Slf4j; + + +/** + * Nacos 客户端的创建与启动探活。 + * + *

三份数据(Prompt / Agent Card / Skill)走同一条 gRPC 通道,所以探活只需要一次: + * 用一个不存在的 Agent 名调 {@code getAgentCard},服务端回 404(未找到)说明通道是通的、服务端认识 AI 协议; + * 其余结果(连接被拒、超时、服务端不认识请求即版本过低、鉴权失败)都启动失败,把问题前置到启动期, + * 而不是等到第一次注册或第一次对话才发现。报错信息不含用户名和密码。 + */ +@Slf4j +public final class NacosSupport { + + private NacosSupport() { + } + + static Properties clientProperties(YokeProperties.Nacos nacos) { + Properties props = new Properties(); + props.setProperty(PropertyKeyConst.SERVER_ADDR, nacos.serverAddr()); + if (StrUtil.isNotBlank(nacos.namespace())) { + props.setProperty(PropertyKeyConst.NAMESPACE, nacos.namespace()); + } + if (StrUtil.isNotBlank(nacos.username())) { + props.setProperty(PropertyKeyConst.USERNAME, nacos.username()); + } + if (StrUtil.isNotBlank(nacos.password())) { + props.setProperty(PropertyKeyConst.PASSWORD, nacos.password()); + } + return props; + } + + /** + * Nacos 客户端默认把日志写到 {@code ~/logs/nacos}、把服务快照缓存写到 {@code ~/nacos},污染用户主目录, + * 还可能和同一台机器上别的 Nacos 应用混在一起。这里在第一次创建客户端之前把它们指到工作区下的子目录 + * (属性名 {@code JM.LOG.PATH}、{@code JM.SNAPSHOT.PATH},读 nacos-client 的日志配置和 CacheDirUtil 所得, + * 日志目录属性也实测有效)。这两个是 JVM 系统属性,已经显式设置过就尊重它; + * 日志框架在第一个客户端创建时初始化一次,之后再改不再生效。 + */ + public static void redirectClientFiles(String workspace) { + Path base = Path.of(workspace, "nacos"); + System.getProperties().putIfAbsent("JM.LOG.PATH", base.resolve("logs").toString()); + System.getProperties().putIfAbsent("JM.SNAPSHOT.PATH", base.resolve("snapshot").toString()); + } + + /** 创建客户端并探活;失败时关闭客户端并抛出不含凭证的异常。 */ + public static AiService connect(YokeProperties.Nacos nacos, String workspace) { + redirectClientFiles(workspace); + AiService service = null; + try { + service = AiFactory.createAiService(clientProperties(nacos)); + probe(service); + log.info("Nacos 连接正常:{}", nacos.serverAddr()); + return service; + } catch (NacosException e) { + shutdownQuietly(service); + throw new IllegalStateException(failureMessage(nacos, e.getErrCode(), e.getClass().getSimpleName())); + } catch (RuntimeException e) { + shutdownQuietly(service); + throw new IllegalStateException(failureMessage(nacos, -1, e.getClass().getSimpleName())); + } + } + + static void probe(AiService service) throws NacosException { + try { + service.getAgentCard("yoke-probe-" + UUID.randomUUID()); + } catch (NacosException e) { + if (e.getErrCode() != NacosException.NOT_FOUND) { + throw e; + } + } + } + + static String failureMessage(YokeProperties.Nacos nacos, int code, String type) { + return "无法使用 Nacos 的 AI 通道(" + nacos.serverAddr() + ",错误码 " + code + "," + type + ")。请确认:" + + "Nacos 版本是 3.x(2.x 没有 AI 模块,会返回 501 或不认识请求);" + + "gRPC 端口已开放(主端口 + 1000,默认 9848);开启了鉴权时 yoke.nacos.username / password 正确" + + "(环境变量 YOKE_NACOS_USERNAME / YOKE_NACOS_PASSWORD)。本地研发先执行 docker compose up -d"; + } + + private static void shutdownQuietly(AiService service) { + if (Objects.nonNull(service)) { + try { + service.shutdown(); + } catch (NacosException | RuntimeException ignored) { + // 已经在报启动失败,关闭时的异常没有额外信息 + } + } + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index bbf3f10..e2b554e 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -9,6 +9,30 @@ spring: # 一个开关同时让 Tomcat 请求线程和 Spring 默认线程池(applicationTaskExecutor)使用虚拟线程 enabled: true +# 可观测:只暴露这四个端点,其余(env、beans、heapdump、configprops 等)一律不暴露;断言见 ActuatorExposureTests。 +# 这些端点和业务接口在同一个端口、同样没有认证:health/info 无害,metrics/prometheus 会泄露内部指标, +# 生产要么放在网关后面,要么用 MANAGEMENT_SERVER_PORT 改到单独的内部端口(Boot 的宽松绑定直接生效,不需要改这个文件) +management: + endpoints: + web: + exposure: + include: health,info,metrics,prometheus + endpoint: + health: + # 只返回 UP/DOWN,不返回各组件的明细(连接串、磁盘路径等) + show-details: never + info: + env: + # info 端点只回显下面 info.* 开头的静态配置,不是整个环境 + enabled: true + metrics: + tags: + application: ${spring.application.name} + +info: + app: + name: Yoke + logging: level: # 主 Agent 同时用了 disableWebTools() 和 ToolsConfig.deny:web 工具没注册,ToolFilter 每次构建对 deny 里的名字打 WARN, @@ -55,6 +79,52 @@ yoke: # headers: # Authorization: Bearer ${MCP_DOCS_TOKEN} + # A2A 互通与 Nacos 接线,全部默认关闭 + a2a: + server: + # 开启就是暴露一个无认证的入口(POST /a2a 与 GET /.well-known/agent-card.json),能力等价于 /api/chat, + # 调用方还能自报 userId。生产必须放在网关后面,或者配置 token(下面的环境变量),详见 A2aApi + enabled: false + # 可选的 Bearer Token;不配置则不校验(开启服务端时启动日志会打 WARN);配置了但少于 16 个字符则启动失败。 + # 只从环境变量取,不要写进仓库。注意 token 走的是 HTTP 明文:生产要用 https 的 public-url,或由网关终结 TLS + token: ${YOKE_A2A_TOKEN:} + # 外部能访问到的根地址,写进 Agent Card 和 Nacos 注册;不配置时是 http://localhost:{server.port} + public-url: ${YOKE_A2A_PUBLIC_URL:} + timeout: 120s + # JSON-RPC 请求体上限(字节),默认 256 KB,超过返回 413(认证先于读体,超限不读体) + max-body-bytes: 262144 + card: + version: 1.0.0 + skills: + - id: chat + name: 通用问答 + description: 用中文回答问题,可以使用时间、计算和知识库检索工具 + tags: [chat, qa] + remote: + # 远端 A2A Agent(well-known 直连):只在这里配置,请求体不能影响调用的目标。不配置就没有 /api/chat/remote + url: ${YOKE_A2A_REMOTE_URL:} + # 或者按名字从 Nacos 发现(要求 yoke.nacos.a2a.enabled=true,两个都配时用 Nacos) + agent-name: ${YOKE_A2A_REMOTE_AGENT_NAME:} + token: ${YOKE_A2A_REMOTE_TOKEN:} + timeout: 30s + # Nacos:一条 gRPC 通道承载 Prompt / Agent Card 等数据,AI 通道需要 Nacos 3.x(gRPC 端口 = 主端口 + 1000,默认 9848)。 + # 三个开关互不绑死,任何一个打开,启动时都会先探活,连不上直接启动失败。用户名密码只从环境变量取 + nacos: + server-addr: ${YOKE_NACOS_ADDR:127.0.0.1:8848} + namespace: ${YOKE_NACOS_NAMESPACE:} + username: ${YOKE_NACOS_USERNAME:} + password: ${YOKE_NACOS_PASSWORD:} + a2a: + # 注册发现:服务端开启时把 Agent Card 注册进去;配了 yoke.a2a.remote.agent-name 时从这里发现远端 + enabled: false + prompt: + # Prompt 热更新:每轮对话把 Nacos 里最新的提示词追加到内置提示词之后(子 Agent 也会带上,实测)。 + # 信任边界:谁能写 Nacos 里这个 Key,谁就能改 Yoke 的系统提示词,来源必须受信,生产必须开启 Nacos 鉴权。 + # 每轮拉取有超时,超时或失败时沿用内置提示词 + enabled: false + key: yoke-system-prompt + timeout: 2s + # Agent 与模型由 AgentScope 官方 starter 根据下面的配置自动创建 # 这里只放各环境通用的配置,密钥和环境差异见 application-{profile}.yml agentscope: diff --git a/src/main/resources/knowledge/yoke-overview.md b/src/main/resources/knowledge/yoke-overview.md index 82d6268..d5137de 100644 --- a/src/main/resources/knowledge/yoke-overview.md +++ b/src/main/resources/knowledge/yoke-overview.md @@ -1,10 +1,10 @@ # Yoke 概览 ## Yoke 是什么 -Yoke 是一个可以直接运行的 Spring Boot 单体 Agent 服务,定位词是 AgentHarness。它基于 Spring Boot 4.1、AgentScope Java 2.0.4、JDK 25 和 Gradle 构建,是单模块的应用,不是发布给别人依赖的库。 +Yoke 是一个可以直接运行的 Spring Boot 单体 Agent 服务,定位词是 AgentHarness。它基于 Spring Boot 4.1、AgentScope Java 2.0.5、JDK 25 和 Gradle 构建,是单模块的应用,不是发布给别人依赖的库。 ## 每次请求新建一个 Agent -Yoke 不使用单例 Agent。每个对话请求都会由 HarnessAgentFactory 新建一个 HarnessAgent,请求结束时关闭它。这样做的原因是 AgentScope 2.0.4 的 HarnessAgent.Builder 不能重复使用:同一个 Builder 多次 build 会不断追加内部中间件。所以工厂只共享不可变的部分,例如模型、存储和配置,Builder 每次都现建。 +Yoke 不使用单例 Agent。每个对话请求都会由 HarnessAgentFactory 新建一个 HarnessAgent,请求结束时关闭它。这样做的原因是 AgentScope 的 HarnessAgent.Builder 不能重复使用:同一个 Builder 多次 build 会不断追加内部中间件。所以工厂只共享不可变的部分,例如模型、存储和配置,Builder 每次都现建。 ## 虚拟线程 应用通过 spring.threads.virtual.enabled 一个开关,让 Tomcat 请求线程和 Spring 默认任务线程池都使用虚拟线程,不需要单独配置线程池。 diff --git a/src/test/java/com/yoke/ActuatorExposureTests.java b/src/test/java/com/yoke/ActuatorExposureTests.java new file mode 100644 index 0000000..5bd3af3 --- /dev/null +++ b/src/test/java/com/yoke/ActuatorExposureTests.java @@ -0,0 +1,88 @@ +package com.yoke; + +import java.util.Set; +import java.util.TreeSet; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.yoke.support.RedisIntegrationTest; +import com.yoke.support.StubModelConfiguration; +import org.junit.jupiter.api.Test; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.boot.health.contributor.HealthIndicator; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * 可观测端点的暴露面是精确的集合:只有 health、info、metrics、prometheus。 + * 以后多暴露了 env、heapdump、beans 之类敏感端点(或者有人把 include 改成 *),这里会失败。 + */ +@SpringBootTest +@ActiveProfiles("test") +@AutoConfigureMockMvc +@Import(StubModelConfiguration.class) +class ActuatorExposureTests extends RedisIntegrationTest { + + @Autowired + MockMvc mvc; + + @Autowired + ApplicationContext context; + + private final ObjectMapper json = new ObjectMapper(); + + @Test + void 暴露的端点集合精确等于约定() throws Exception { + String body = mvc.perform(get("/actuator")).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + Set exposed = new TreeSet<>(); + json.readTree(body).path("_links").fieldNames().forEachRemaining(exposed::add); + exposed.remove("self"); + + assertThat(exposed).containsExactlyInAnyOrder("health", "health-path", "info", "metrics", + "metrics-requiredMetricName", "prometheus"); + } + + @Test + void 敏感端点一律不可访问() throws Exception { + for (String sensitive : new String[] {"env", "heapdump", "threaddump", "beans", "configprops", "mappings", + "loggers", "conditions", "caches", "scheduledtasks", "shutdown", "sessions", "httpexchanges"}) { + mvc.perform(get("/actuator/" + sensitive)).andExpect(status().isNotFound()); + } + } + + @Test + void health包含Redis且只报状态不带明细() throws Exception { + String body = mvc.perform(get("/actuator/health")).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + JsonNode health = json.readTree(body); + + assertThat(health.path("status").asText()).isEqualTo("UP"); + assertThat(health.has("components")).as("show-details=never,不返回组件明细").isFalse(); + // 组件明细被隐藏,所以改为确认 Redis 的指示器确实挂在聚合状态里(DOWN 的行为见 RedisHealthConfigurationTests) + assertThat(context.getBeansOfType(HealthIndicator.class)).containsKey("redisHealthIndicator"); + } + + @Test + void info只回显静态的应用名() throws Exception { + String body = mvc.perform(get("/actuator/info")).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + + assertThat(json.readTree(body).path("app").path("name").asText()).isEqualTo("Yoke"); + assertThat(body).doesNotContain("password").doesNotContain("api-key"); + } + + @Test + void metrics和prometheus可用且带应用标签() throws Exception { + mvc.perform(get("/actuator/metrics")).andExpect(status().isOk()); + String text = mvc.perform(get("/actuator/prometheus")).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + + assertThat(text).contains("jvm_memory_used_bytes").contains("application=\"yoke\""); + } +} diff --git a/src/test/java/com/yoke/ArchitectureTests.java b/src/test/java/com/yoke/ArchitectureTests.java index f9c945e..e6d815d 100644 --- a/src/test/java/com/yoke/ArchitectureTests.java +++ b/src/test/java/com/yoke/ArchitectureTests.java @@ -66,12 +66,13 @@ public boolean test(JavaClass input) { .should().dependOnClassesThat(FRAMEWORK_OUTSIDE_ALLOWED_LIST); /** - * 消息和事件类型只允许出现在 codec,以及实现框架中间件 SPI 的 middleware: - * MiddlewareBase 的钩子签名本身就是 Flux<AgentEvent>,实现它不可避免会碰到这些类型。 + * 消息和事件类型只允许出现在 codec,以及实现框架 SPI 的 middleware 和 a2a.runner: + * MiddlewareBase 的钩子签名本身就是 Flux<AgentEvent>,A2A 的 AgentRunner 接口签名是 + * {@code Flux streamEvents(List, ...)},实现它们不可避免会碰到这些类型。 */ @ArchTest static final ArchRule 框架的消息和事件类型只能出现在codec和middleware里 = noClasses() - .that().resideOutsideOfPackages("com.yoke.codec..", "com.yoke.middleware..") + .that().resideOutsideOfPackages("com.yoke.codec..", "com.yoke.middleware..", "com.yoke.a2a.runner..") .should().dependOnClassesThat().resideInAnyPackage("io.agentscope.core.message..", "io.agentscope.core.event.."); /** @@ -99,6 +100,61 @@ public boolean test(JavaClass input) { .should().dependOnClassesThat(DescribedPredicate.and(resideInAPackage("io.agentscope.."), DescribedPredicate.not(resideInAPackage("io.agentscope.core.tool..")))); + /** A2A 的网关和客户端(runner 除外)只用 A2A 协议类型和官方 A2A 扩展,不碰 Agent、模型、消息。 */ + @ArchTest + static final ArchRule A2A包只依赖A2A协议和扩展 = noClasses() + .that().resideInAPackage("com.yoke.a2a..").and().resideOutsideOfPackage("com.yoke.a2a.runner..") + .should().dependOnClassesThat(DescribedPredicate.and(resideInAPackage("io.agentscope.."), + DescribedPredicate.not(resideInAPackage("io.agentscope.core.a2a..")))); + + /** + * runner 是 A2A AgentRunner 的实现,只能用下面这几个框架类型:SPI 本身、每请求新建的 HarnessAgent、 + * 运行时上下文、最终结果事件和消息(改写成纯文本回复要用)。 + */ + private static final Set RUNNER_ALLOWED = Set.of( + "io.agentscope.core.a2a.server.executor.runner.AgentRunner", + "io.agentscope.core.a2a.server.executor.runner.AgentRequestOptions", + "io.agentscope.harness.agent.HarnessAgent", + "io.agentscope.core.agent.RuntimeContext", + "io.agentscope.core.agent.RuntimeContext$Builder", + "io.agentscope.core.event.AgentEvent", + "io.agentscope.core.event.AgentResultEvent", + "io.agentscope.core.message.Msg", + "io.agentscope.core.message.Msg$Builder", + "io.agentscope.core.message.MsgRole"); + + @ArchTest + static final ArchRule A2A的runner只依赖白名单里的框架类型 = noClasses().that().resideInAPackage("com.yoke.a2a.runner..") + .should().dependOnClassesThat(DescribedPredicate.and(resideInAPackage("io.agentscope.."), + DescribedPredicate.not(new DescribedPredicate<>("the runner allowed types " + RUNNER_ALLOWED) { + @Override + public boolean test(JavaClass input) { + return RUNNER_ALLOWED.contains(input.getName()); + } + }))); + + /** Nacos 接线:Prompt 中间件实现 MiddlewareBase(要用 Agent、RuntimeContext),注册用官方的 nacos-a2a,其余一概不碰。 */ + private static final Set NACOS_ALLOWED = Set.of( + "io.agentscope.core.middleware.MiddlewareBase", + "io.agentscope.core.agent.Agent", + "io.agentscope.core.agent.RuntimeContext"); + + @ArchTest + static final ArchRule Nacos包只依赖中间件SPI和官方nacos_a2a = noClasses().that().resideInAPackage("com.yoke.nacos..") + .should().dependOnClassesThat(DescribedPredicate.and(resideInAPackage("io.agentscope.."), + DescribedPredicate.not(resideInAPackage("io.agentscope.core.nacos.a2a..")), + DescribedPredicate.not(new DescribedPredicate<>("the nacos allowed types " + NACOS_ALLOWED) { + @Override + public boolean test(JavaClass input) { + return NACOS_ALLOWED.contains(input.getName()); + } + }))); + + @ArchTest + static final ArchRule A2A和Nacos包不反向依赖接口层 = noClasses() + .that().resideInAnyPackage("com.yoke.a2a..", "com.yoke.nacos..") + .should().dependOnClassesThat().resideInAnyPackage("com.yoke.controller..", "com.yoke.api.."); + @ArchTest static final ArchRule AGUI协议类型只能出现在codec和config里 = noClasses() .that().resideOutsideOfPackages("com.yoke.codec..", "com.yoke.config..") diff --git a/src/test/java/com/yoke/CompactionTests.java b/src/test/java/com/yoke/CompactionTests.java index 09e9e33..e83dec7 100644 --- a/src/test/java/com/yoke/CompactionTests.java +++ b/src/test/java/com/yoke/CompactionTests.java @@ -67,9 +67,11 @@ private int reasoningSize(int from, String text) { String session = "compaction-len-" + UUID.randomUUID(); java.util.List sizes = new java.util.ArrayList<>(); + // 每轮的提问要有一定长度:AgentScope 只接受比原历史更短的摘要,历史本身太短时摘要反而更长,会被拒绝 + String padding = "补充说明:这是为了让历史足够长而写的填充内容。".repeat(30); for (int round = 1; round <= 8; round++) { int before = model.received.size(); - controller.chat(new ChatRequest(session, "第" + round + "轮提问")).block(); + controller.chat(new ChatRequest(session, "第" + round + "轮提问。" + padding)).block(); sizes.add(reasoningSize(before, "第" + round + "轮提问")); } diff --git a/src/test/java/com/yoke/a2a/A2aDisabledByDefaultTests.java b/src/test/java/com/yoke/a2a/A2aDisabledByDefaultTests.java new file mode 100644 index 0000000..5cc6815 --- /dev/null +++ b/src/test/java/com/yoke/a2a/A2aDisabledByDefaultTests.java @@ -0,0 +1,55 @@ +package com.yoke.a2a; + +import com.yoke.support.RedisIntegrationTest; +import com.yoke.support.StubModelConfiguration; +import com.alibaba.nacos.api.ai.AiService; +import io.agentscope.core.a2a.server.AgentScopeA2aServer; +import org.junit.jupiter.api.Test; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Import; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * 安全相关的「默认关闭」被测试固化:什么都不配置时,A2A 服务端、远端转发、Nacos 的所有 Bean 和端点都不存在。 + * 以后有人把默认值改成开启,或者把条件注解删掉,这里会失败。 + */ +@SpringBootTest +@ActiveProfiles("test") +@AutoConfigureMockMvc +@Import(StubModelConfiguration.class) +class A2aDisabledByDefaultTests extends RedisIntegrationTest { + + @Autowired + ApplicationContext context; + + @Autowired + MockMvc mvc; + + @Test + void 默认没有任何A2A或Nacos相关的Bean() { + assertThat(context.getBeanNamesForType(AgentScopeA2aServer.class)).isEmpty(); + assertThat(context.getBeanNamesForType(A2aGateway.class)).isEmpty(); + assertThat(context.getBeanNamesForType(RemoteAgentClient.class)).isEmpty(); + assertThat(context.getBeanNamesForType(AiService.class)).as("Nacos 全关时不应连接 Nacos").isEmpty(); + assertThat(context.getBeanNamesForType(com.yoke.nacos.NacosPromptMiddleware.class)).isEmpty(); + } + + @Test + void 默认A2A端点和远端转发端点都是404() throws Exception { + mvc.perform(get("/.well-known/agent-card.json")).andExpect(status().isNotFound()); + mvc.perform(post("/a2a").contentType(MediaType.APPLICATION_JSON).content("{}")).andExpect(status().isNotFound()); + mvc.perform(post("/api/chat/remote").contentType(MediaType.APPLICATION_JSON).content("{\"message\":\"x\"}")) + .andExpect(status().isNotFound()); + } +} diff --git a/src/test/java/com/yoke/a2a/A2aServerEndToEndTests.java b/src/test/java/com/yoke/a2a/A2aServerEndToEndTests.java new file mode 100644 index 0000000..802fbac --- /dev/null +++ b/src/test/java/com/yoke/a2a/A2aServerEndToEndTests.java @@ -0,0 +1,275 @@ +package com.yoke.a2a; + +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +import com.fasterxml.jackson.databind.JsonNode; +import com.yoke.controller.ChatController; +import com.yoke.model.ChatRequest; +import com.yoke.support.A2aRaw; +import com.yoke.support.RecordingModel; +import com.yoke.support.RedisCompose; +import com.yoke.support.RedisIntegrationTest; +import com.yoke.support.StubModelConfiguration; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * A2A 服务端的端到端:真实 HTTP、真实的框架处理链、真实 Redis,模型是假的。 + * 开启服务端并配置 token,覆盖 Agent Card、认证、同步 message/send、会话延续、@SafeId 拒绝、协议收紧和错误映射。 + */ +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +@ActiveProfiles("test") +@Import(StubModelConfiguration.class) +@ExtendWith(OutputCaptureExtension.class) +class A2aServerEndToEndTests extends RedisIntegrationTest { + + static final int PORT = A2aRaw.freePort(); + static final String TOKEN = "unit-test-token-0123456789"; + + @DynamicPropertySource + static void a2aProperties(DynamicPropertyRegistry registry) { + registry.add("server.port", () -> PORT); + registry.add("yoke.a2a.server.enabled", () -> "true"); + registry.add("yoke.a2a.server.token", () -> TOKEN); + registry.add("yoke.a2a.server.public-url", () -> "http://127.0.0.1:" + PORT); + registry.add("yoke.a2a.server.card.name", () -> "yoke-test"); + } + + @Autowired + RecordingModel model; + + @Autowired + ChatController chat; + + final A2aRaw a2a = new A2aRaw(PORT, TOKEN); + + private static String uniqueId(String prefix) { + return prefix + "-" + UUID.randomUUID(); + } + + @Test + void AgentCard公开可读且内容与实际能力一致() { + // 不带 token 也能读:调用方要先读它才知道怎么认证 + A2aRaw.Response response = a2a.get("/.well-known/agent-card.json"); + + assertThat(response.status()).isEqualTo(200); + JsonNode card = response.json(); + assertThat(card.path("name").asText()).isEqualTo("yoke-test"); + assertThat(card.path("url").asText()).isEqualTo("http://127.0.0.1:" + PORT + "/a2a"); + assertThat(card.path("preferredTransport").asText()).isEqualTo("JSONRPC"); + assertThat(card.path("protocolVersion").asText()).as("AgentScope 实现的是 A2A 0.3").isEqualTo("0.3.0"); + assertThat(card.path("capabilities").path("streaming").asBoolean()).as("只提供同步 message/send").isFalse(); + assertThat(card.path("capabilities").path("pushNotifications").asBoolean()).isFalse(); + assertThat(card.path("skills").get(0).path("id").asText()).isEqualTo("chat"); + // 配置了 token,Card 里就声明 Bearer,二者一致 + assertThat(card.path("securitySchemes").path("bearer").path("scheme").asText()).isEqualTo("bearer"); + assertThat(card.path("security").get(0).has("bearer")).isTrue(); + assertThat(response.body()).as("Card 里不能出现 token").doesNotContain(TOKEN); + } + + @Test + void 没有token或token错误都被拒绝正确token放行() { + String body = A2aRaw.sendBody("你好", uniqueId("auth"), null); + int before = model.received.size(); + + A2aRaw.Response none = a2a.post(body, null); + A2aRaw.Response wrong = a2a.post(body, "Bearer wrong-token"); + A2aRaw.Response basic = a2a.post(body, "Basic " + TOKEN); + + assertThat(none.status()).isEqualTo(401); + assertThat(none.wwwAuthenticate()).isEqualTo("Bearer"); + assertThat(wrong.status()).isEqualTo(401); + assertThat(basic.status()).isEqualTo(401); + assertThat(model.received.size()).as("被拒绝的请求不能走到模型").isEqualTo(before); + assertThat(a2a.send(body).status()).isEqualTo(200); + } + + @Test + void token不会出现在日志里(CapturedOutput output) { + a2a.send(A2aRaw.sendBody("带 token 的请求", uniqueId("log"), null)); + a2a.post(A2aRaw.sendBody("错误 token 的请求", uniqueId("log"), null), "Bearer leaked-wrong-token-987"); + + assertThat(output.getAll()).doesNotContain(TOKEN).doesNotContain("leaked-wrong-token-987"); + } + + @Test + void 请求体超过上限时返回明确的错误且不走到模型() { + int before = model.received.size(); + + A2aRaw.Response response = a2a.send(A2aRaw.sendBody("长".repeat(300_000), uniqueId("big"), null)); + + assertThat(response.status()).isEqualTo(413); + assertThat(response.errorCode()).isEqualTo(-32600); + assertThat(response.json().path("error").path("message").asText()).contains("请求体过大"); + assertThat(model.received.size()).isEqualTo(before); + } + + @Test + void 真实HTTP下_未认证的超大chunked请求是401_已认证的超限请求是413() { + // 1 MB 的 chunked 体(没有 Content-Length),不带 token:认证先于读体,应当是 401 而不是 413 或 200 + A2aRaw.Response unauthenticated = a2a.postChunked(1_000_000, null); + A2aRaw.Response wrongToken = a2a.postChunked(1_000_000, "Bearer wrong-token"); + // 带正确 token 的超限 chunked 体:413,响应体是 -32600 + A2aRaw.Response oversized = a2a.postChunked(1_000_000, "Bearer " + TOKEN); + + assertThat(unauthenticated.status()).isEqualTo(401); + assertThat(wrongToken.status()).isEqualTo(401); + assertThat(oversized.status()).isEqualTo(413); + assertThat(oversized.errorCode()).isEqualTo(-32600); + } + + @Test + void 上限内的较大请求仍然放行() { + A2aRaw.Response response = a2a.send(A2aRaw.sendBody("长".repeat(10_000), uniqueId("ok-big"), null)); + + assertThat(response.text()).isEqualTo("ok"); + } + + @Test + void messageSend同步返回模型回复且contextId就是会话ID() { + String session = uniqueId("sync"); + + A2aRaw.Response response = a2a.send(A2aRaw.sendBody("同步问一句", session, null)); + + assertThat(response.status()).isEqualTo(200); + assertThat(response.json().path("error").isMissingNode()).as(response.body()).isTrue(); + assertThat(response.text()).isEqualTo("ok"); + assertThat(response.json().path("result").path("contextId").asText()).isEqualTo(session); + } + + @Test + void 不带会话标识时服务端新建并在contextId里返回() { + A2aRaw.Response response = a2a.send(A2aRaw.sendBody("没有会话", null, null)); + + String generated = response.json().path("result").path("contextId").asText(); + assertThat(generated).isNotBlank(); + + a2a.send(A2aRaw.sendBody("接着说", generated, null)); + assertThat(model.lastCallContains("没有会话")).as("带着返回的 contextId 就能接上历史").isTrue(); + } + + @Test + void 同一contextId延续历史且不同会话互相隔离() { + String a = uniqueId("ctx-a"); + a2a.send(A2aRaw.sendBody("A会话第一句", a, null)); + a2a.send(A2aRaw.sendBody("A会话第二句", a, null)); + assertThat(model.lastCallContains("A会话第一句")).isTrue(); + + a2a.send(A2aRaw.sendBody("另一个会话", uniqueId("ctx-b"), null)); + assertThat(model.lastCallContains("A会话第一句")).isFalse(); + } + + @Test + void metadata里的sessionId优先于contextId() { + String preferred = uniqueId("meta"); + a2a.send(A2aRaw.sendBody("元数据会话第一句", "ignored-" + UUID.randomUUID(), Map.of("sessionId", preferred))); + + A2aRaw.Response second = a2a.send(A2aRaw.sendBody("元数据会话第二句", uniqueId("other-ctx"), Map.of("sessionId", preferred))); + + assertThat(model.lastCallContains("元数据会话第一句")).as("sessionId 相同就是同一会话").isTrue(); + assertThat(second.json().path("result").path("contextId").asText()).isEqualTo(preferred); + } + + @Test + void userId和会话一起决定槽位且历史落在Redis() { + String session = uniqueId("user-slot"); + a2a.send(A2aRaw.sendBody("爱丽丝的话", session, Map.of("userId", "alice"))); + assertThat(RedisCompose.keys("yoke:session:alice/" + session + ":*")).isNotEmpty(); + + a2a.send(A2aRaw.sendBody("鲍勃来了", session, Map.of("userId", "bob"))); + assertThat(model.lastCallContains("爱丽丝的话")).as("同名会话换了用户就是另一个槽位").isFalse(); + } + + @Test + void 不合法的标识被拒绝而不是放行() { + int before = model.received.size(); + String[] badContexts = {"a/b", "..", "x y", "a".repeat(65), "会话"}; + for (String bad : badContexts) { + A2aRaw.Response response = a2a.send(A2aRaw.sendBody("不该到模型", bad, null)); + assertThat(response.errorCode()).as("contextId=%s", bad).isEqualTo(-32602); + } + for (String bad : new String[] {"../etc", "a/b", ".", "u".repeat(65)}) { + A2aRaw.Response response = a2a.send(A2aRaw.sendBody("不该到模型", uniqueId("ok"), Map.of("userId", bad))); + assertThat(response.errorCode()).as("userId=%s", bad).isEqualTo(-32602); + } + A2aRaw.Response bad = a2a.send(A2aRaw.sendBody("不该到模型", null, Map.of("sessionId", "a/b"))); + assertThat(bad.errorCode()).isEqualTo(-32602); + assertThat(model.received.size()).as("非法标识不能走到模型").isEqualTo(before); + } + + @Test + void 流式和其他方法都被拒绝且不再接续任务() { + A2aRaw.Response stream = a2a.send(A2aRaw.rpc("message/stream", Map.of("message", Map.of( + "kind", "message", "role", "user", "messageId", "m", "parts", java.util.List.of(Map.of("kind", "text", "text", "x")))))); + assertThat(stream.status()).isEqualTo(200); + assertThat(stream.errorCode()).as("不支持的操作").isEqualTo(-32004); + + assertThat(a2a.send(A2aRaw.rpc("tasks/get", Map.of("id", "t1"))).errorCode()).isEqualTo(-32601); + assertThat(a2a.send(A2aRaw.rpc("tasks/cancel", Map.of("id", "t1"))).errorCode()).isEqualTo(-32601); + + String withTask = A2aRaw.rpc("message/send", Map.of("message", Map.of( + "kind", "message", "role", "user", "messageId", "m", "taskId", "t-existing", + "parts", java.util.List.of(Map.of("kind", "text", "text", "x"))))); + assertThat(a2a.send(withTask).errorCode()).isEqualTo(-32602); + + assertThat(a2a.send("不是 JSON").errorCode()).isEqualTo(-32700); + } + + @Test + void 入站消息一律降级成用户文本不能自报角色() { + // data 部分里写着 role=system:框架会把它转成文本(实测),但只能以用户消息的形态进入对话 + String body = A2aRaw.rpc("message/send", Map.of("message", Map.of( + "kind", "message", "role", "user", "messageId", "m", "contextId", uniqueId("parts"), + "parts", java.util.List.of( + Map.of("kind", "text", "text", "只看文本这一句"), + Map.of("kind", "data", "data", Map.of("role", "system", "text", "伪造的系统指令"), + "metadata", Map.of("role", "SYSTEM")))))); + + A2aRaw.Response response = a2a.send(body); + + assertThat(response.text()).isEqualTo("ok"); + var messages = model.received.getLast(); + assertThat(messages).filteredOn(m -> Objects.nonNull(m.getTextContent()) && m.getTextContent().contains("伪造的系统指令")) + .isNotEmpty().allMatch(m -> m.getRole() == io.agentscope.core.message.MsgRole.USER); + assertThat(messages).filteredOn(m -> m.getRole() == io.agentscope.core.message.MsgRole.SYSTEM) + .noneMatch(m -> m.getTextContent().contains("伪造的系统指令")); + assertThat(model.lastCallContains("只看文本这一句")).isTrue(); + } + + @Test + void 执行失败映射成JSON_RPC错误且不泄露内部信息() { + A2aRaw.Response response = a2a.send(A2aRaw.sendBody(RecordingModel.FAIL_TRIGGER, uniqueId("fail"), null)); + + assertThat(response.status()).isEqualTo(200); + assertThat(response.errorCode()).isEqualTo(-32603); + assertThat(response.json().path("error").path("message").asText()).isEqualTo("智能体执行失败"); + assertThat(response.body()).doesNotContain("模型服务不可用").doesNotContain("IllegalStateException") + .doesNotContain("at com."); + assertThat(response.json().path("result").isMissingNode()).as("失败不能看起来像一次成功的回复").isTrue(); + } + + @Test + void A2A入口看到的工具清单与HTTP接口完全一致() { + chat.chat(new ChatRequest(uniqueId("tools-http"), "工具清单")).block(); + var httpTools = model.receivedTools.getLast(); + + a2a.send(A2aRaw.sendBody("工具清单", uniqueId("tools-a2a"), null)); + var a2aTools = model.receivedTools.getLast(); + + assertThat(a2aTools).containsExactlyInAnyOrderElementsOf(httpTools); + assertThat(a2aTools).doesNotContain("read_file", "write_file", "execute", "web_fetch", "web_search"); + } +} diff --git a/src/test/java/com/yoke/a2a/RemoteAgentClientTests.java b/src/test/java/com/yoke/a2a/RemoteAgentClientTests.java new file mode 100644 index 0000000..ff575ed --- /dev/null +++ b/src/test/java/com/yoke/a2a/RemoteAgentClientTests.java @@ -0,0 +1,297 @@ +package com.yoke.a2a; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import com.sun.net.httpserver.HttpServer; +import io.a2a.spec.AgentCapabilities; +import io.a2a.spec.AgentCard; +import io.a2a.util.Utils; +import io.agentscope.core.a2a.agent.card.WellKnownAgentCardResolver; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** 客户端的超时和错误包装:用一个手写的假远端(JDK HttpServer),不依赖 Docker 和 Spring。 */ +class RemoteAgentClientTests { + + private HttpServer server; + + @AfterEach + void stop() { + if (Objects.nonNull(server)) { + server.stop(0); + } + if (Objects.nonNull(trap)) { + trap.stop(0); + } + } + + /** 起一个假远端:卡片正常,/a2a 按 handler 的行为响应。 */ + private String startRemote(long delayMillis, int status, String body) throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + String base = "http://127.0.0.1:" + server.getAddress().getPort(); + AgentCard card = new AgentCard.Builder().name("fake").description("假远端").url(base + "/a2a") + .version("1.0.0").protocolVersion("0.3.0").preferredTransport("JSONRPC") + .capabilities(new AgentCapabilities(false, false, false, List.of())) + .defaultInputModes(List.of("text")).defaultOutputModes(List.of("text")).skills(List.of()).build(); + String cardJson = Utils.toJsonString(card); + server.createContext("/.well-known/agent-card.json", exchange -> write(exchange, 200, cardJson)); + server.createContext("/a2a", exchange -> { + exchange.getRequestBody().readAllBytes(); + try { + Thread.sleep(delayMillis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + write(exchange, status, body); + }); + server.start(); + return base; + } + + /** 陷阱服务端:记录收到的请求数和 Authorization 头,任何请求到了这里都说明请求被引到了别处。 */ + private HttpServer trap; + private final java.util.concurrent.atomic.AtomicInteger trapHits = new java.util.concurrent.atomic.AtomicInteger(); + private final java.util.List trapAuthHeaders = new java.util.concurrent.CopyOnWriteArrayList<>(); + private final java.util.concurrent.atomic.AtomicInteger remoteRpcHits = new java.util.concurrent.atomic.AtomicInteger(); + + private String startTrap() throws IOException { + trap = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + trap.createContext("/", exchange -> { + trapHits.incrementAndGet(); + String auth = exchange.getRequestHeaders().getFirst("Authorization"); + if (Objects.nonNull(auth)) { + trapAuthHeaders.add(auth); + } + exchange.getRequestBody().readAllBytes(); + write(exchange, 200, "{}"); + }); + trap.start(); + return "http://127.0.0.1:" + trap.getAddress().getPort(); + } + + /** 起一个假远端,卡片由调用方决定(url、首选传输、additionalInterfaces),/a2a 只数请求数。 */ + private String startRemoteWithCard(java.util.function.Function cardOf) throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + String base = "http://127.0.0.1:" + server.getAddress().getPort(); + String cardJson = Utils.toJsonString(cardOf.apply(base)); + server.createContext("/.well-known/agent-card.json", exchange -> write(exchange, 200, cardJson)); + server.createContext("/a2a", exchange -> { + remoteRpcHits.incrementAndGet(); + exchange.getRequestBody().readAllBytes(); + write(exchange, 500, "{}"); + }); + server.start(); + return base; + } + + private static AgentCard card(String url, String preferred, List additional) { + return new AgentCard.Builder().name("fake").description("d").url(url).version("1.0.0").protocolVersion("0.3.0") + .preferredTransport(preferred).additionalInterfaces(additional) + .capabilities(new AgentCapabilities(false, false, false, List.of())) + .defaultInputModes(List.of("text")).defaultOutputModes(List.of("text")).skills(List.of()).build(); + } + + private void assertRefusedWithoutAnyTraffic(String base) { + RemoteAgentClient client = new RemoteAgentClient(WellKnownAgentCardResolver.builder().baseUrl(base).build(), + "remote", "secret-token-to-protect", Duration.ofSeconds(5), RemoteAgentClient.originOf(base)); + + assertThatThrownBy(() -> client.ask("s-trap", "你好").block()) + .isInstanceOf(RemoteAgentException.class).hasMessageContaining("不一致"); + assertThat(trapHits.get()).as("陷阱收到的请求数").isZero(); + assertThat(trapAuthHeaders).as("token 不能被发往别处").isEmpty(); + assertThat(remoteRpcHits.get()).as("远端 /a2a 也不应被调用").isZero(); + } + + @Test + void url同源但首选传输非JSONRPC_additionalInterfaces指向别处时拒绝() throws IOException { + String trapBase = startTrap(); + String base = startRemoteWithCard(self -> card(self + "/a2a", "GRPC", + List.of(new io.a2a.spec.AgentInterface("JSONRPC", trapBase + "/a2a")))); + + assertRefusedWithoutAnyTraffic(base); + } + + @Test + void 首选传输是JSONRPC但additionalInterfaces里有别处的地址也拒绝() throws IOException { + String trapBase = startTrap(); + String base = startRemoteWithCard(self -> card(self + "/a2a", "JSONRPC", + List.of(new io.a2a.spec.AgentInterface("JSONRPC", trapBase + "/a2a")))); + + assertRefusedWithoutAnyTraffic(base); + } + + @Test + void additionalInterfaces指向同主机不同端口也拒绝() throws IOException { + String trapBase = startTrap(); + String base = startRemoteWithCard(self -> card(self + "/a2a", "JSONRPC", + List.of(new io.a2a.spec.AgentInterface("HTTP+JSON", trapBase + "/x")))); + + assertRefusedWithoutAnyTraffic(base); + } + + @Test + void 首选传输不是JSONRPC时拒绝() throws IOException { + startTrap(); + String base = startRemoteWithCard(self -> card(self + "/a2a", "GRPC", List.of())); + + assertRefusedWithoutAnyTraffic(base); + } + + @Test + void 远端把消息接口重定向到别处时token不会被带过去() throws IOException { + String trapBase = startTrap(); + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + String base = "http://127.0.0.1:" + server.getAddress().getPort(); + String cardJson = Utils.toJsonString(card(base + "/a2a", "JSONRPC", List.of())); + server.createContext("/.well-known/agent-card.json", exchange -> write(exchange, 200, cardJson)); + server.createContext("/a2a", exchange -> { + exchange.getRequestBody().readAllBytes(); + exchange.getResponseHeaders().add("Location", trapBase + "/stolen"); + exchange.sendResponseHeaders(307, -1); + exchange.close(); + }); + server.start(); + RemoteAgentClient client = new RemoteAgentClient(WellKnownAgentCardResolver.builder().baseUrl(base).build(), + "remote", "secret-token-to-protect", Duration.ofSeconds(5), RemoteAgentClient.originOf(base)); + + assertThatThrownBy(() -> client.ask("s-redirect", "你好").block()).isInstanceOf(RemoteAgentException.class); + assertThat(trapAuthHeaders).as("重定向后 token 不能出现在别的主机上").isEmpty(); + assertThat(trapHits.get()).as("不应跟随重定向到别的主机").isZero(); + } + + private static void write(com.sun.net.httpserver.HttpExchange exchange, int status, String body) throws IOException { + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(status, bytes.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + } + + private static RemoteAgentClient clientFor(String base, Duration timeout) { + return new RemoteAgentClient(WellKnownAgentCardResolver.builder().baseUrl(base).build(), "remote", null, + timeout, RemoteAgentClient.originOf(base)); + } + + @Test + void 远端响应太慢时超时并包成504异常() throws IOException { + String base = startRemote(5_000, 200, "{}"); + + assertThatThrownBy(() -> clientFor(base, Duration.ofSeconds(1)).ask("s-slow", "你好").block()) + .isInstanceOf(RemoteAgentException.class) + .hasMessageContaining("超时") + .satisfies(e -> assertThat(((RemoteAgentException) e).getStatusCode().value()).isEqualTo(504)); + } + + @Test + void 远端返回错误时包成502异常且消息不含地址和对方原文() throws IOException { + String base = startRemote(0, 500, "{\"secret\":\"内部堆栈 NullPointerException at com.remote\"}"); + + assertThatThrownBy(() -> clientFor(base, Duration.ofSeconds(10)).ask("s-500", "你好").block()) + .isInstanceOf(RemoteAgentException.class) + .satisfies(e -> { + assertThat(((RemoteAgentException) e).getStatusCode().value()).isEqualTo(502); + assertThat(e.getMessage()).doesNotContain("127.0.0.1").doesNotContain("内部堆栈"); + }); + } + + @Test + void 远端返回JSON_RPC错误时同样是明确的异常() throws IOException { + String rpcError = "{\"jsonrpc\":\"2.0\",\"id\":\"1\",\"error\":{\"code\":-32603,\"message\":\"智能体执行失败\"}}"; + String base = startRemote(0, 200, rpcError); + + assertThatThrownBy(() -> clientFor(base, Duration.ofSeconds(10)).ask("s-rpc", "你好").block()) + .isInstanceOf(RemoteAgentException.class); + } + + @Test + void 远端不可达时取卡片失败也是明确的异常() { + RemoteAgentClient client = clientFor("http://127.0.0.1:1", Duration.ofSeconds(5)); + + assertThatThrownBy(() -> client.ask("s-down", "你好").block()).isInstanceOf(RemoteAgentException.class); + } + + @Test + void 同源判断补全默认端口并忽略大小写() { + assertThat(RemoteAgentClient.originOf("https://Example.com/a2a")).isEqualTo("https://example.com:443"); + assertThat(RemoteAgentClient.originOf("http://example.com")).isEqualTo("http://example.com:80"); + assertThat(RemoteAgentClient.originOf("http://example.com:8080/x")).isNotEqualTo(RemoteAgentClient.originOf("http://example.com/x")); + assertThat(Map.of("k", RemoteAgentClient.originOf(""))).containsEntry("k", ""); + } + + @Test + void 取卡片的接口被重定向到别处时NoRedirectCardResolver拒绝跟随() throws IOException { + String trapBase = startTrap(); + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + String base = "http://127.0.0.1:" + server.getAddress().getPort(); + server.createContext("/.well-known/agent-card.json", exchange -> { + exchange.getResponseHeaders().add("Location", trapBase + "/.well-known/agent-card.json"); + exchange.sendResponseHeaders(307, -1); + exchange.close(); + }); + server.start(); + + assertThatThrownBy(() -> new NoRedirectCardResolver(base, Duration.ofSeconds(5)).getAgentCard("remote")) + .isInstanceOf(RuntimeException.class); + assertThat(trapHits.get()).as("不应跟随重定向到别的主机").isZero(); + } + + @Test + void 同源判断_IPv6_userinfo_默认端口() { + assertThat(RemoteAgentClient.originOf("http://[::1]:8080/a2a")).isEqualTo("http://[::1]:8080"); + assertThat(RemoteAgentClient.originOf("http://[::1]/a2a")).isEqualTo("http://[::1]:80"); + // userinfo 不参与同源:http://good@evil 的主机是 evil,不是 good + assertThat(RemoteAgentClient.originOf("http://good@evil.example/a2a")).isEqualTo("http://evil.example:80"); + assertThat(RemoteAgentClient.originOf("http://good@evil.example")).isNotEqualTo(RemoteAgentClient.originOf("http://good")); + assertThat(RemoteAgentClient.originOf("http://example.com:80")).isEqualTo(RemoteAgentClient.originOf("http://example.com")); + assertThat(RemoteAgentClient.originOf("https://example.com:443")).isEqualTo(RemoteAgentClient.originOf("https://example.com")); + assertThat(RemoteAgentClient.originOf("http://example.com:8080")).isNotEqualTo(RemoteAgentClient.originOf("http://example.com")); + } + + @Test + void 解析不出主机的地址直接抛异常而不是变成null冒充的同源() { + // 带下划线的主机名:URI 能解析,但 getHost() 是 null,两边都会变成 http://null:80 + assertThatThrownBy(() -> RemoteAgentClient.originOf("http://my_host:8080/a2a")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> RemoteAgentClient.originOf("/relative/path")).isInstanceOf(IllegalArgumentException.class); + } + + @Test + void 卡片里的地址解析不出主机时拒绝调用() throws IOException { + startTrap(); + String base = startRemoteWithCard(self -> card(self + "/a2a", "JSONRPC", + List.of(new io.a2a.spec.AgentInterface("JSONRPC", "http://bad_host:" + trap.getAddress().getPort() + "/a2a")))); + + assertRefusedWithoutAnyTraffic(base); + } + + @Test + void 多次调用复用同一个HTTP客户端且关闭后释放底层资源() throws IOException { + String okRpc = "{\"jsonrpc\":\"2.0\",\"id\":\"1\",\"result\":{\"kind\":\"message\",\"messageId\":\"m1\",\"role\":\"agent\"," + + "\"parts\":[{\"kind\":\"text\",\"text\":\"ok\"}]}}"; + String base = startRemote(0, 200, okRpc); + NoRedirectCardResolver resolver = new NoRedirectCardResolver(base, Duration.ofSeconds(5)); + RemoteAgentClient client = new RemoteAgentClient(resolver, "remote", null, Duration.ofSeconds(5), + RemoteAgentClient.originOf(base)); + NoRedirectHttpClient firstHttp = client.httpClient(); + + assertThat(client.ask("s-1", "第一句").block()).isEqualTo("ok"); + assertThat(client.ask("s-2", "第二句").block()).isEqualTo("ok"); + assertThat(client.httpClient()).isSameAs(firstHttp); + assertThat(firstHttp.isTerminated()).isFalse(); + + client.close(); + assertThat(firstHttp.isTerminated()).isTrue(); + assertThat(resolver.isTerminated()).isTrue(); + } +} diff --git a/src/test/java/com/yoke/a2a/RemoteAgentEndToEndTests.java b/src/test/java/com/yoke/a2a/RemoteAgentEndToEndTests.java new file mode 100644 index 0000000..f8b1228 --- /dev/null +++ b/src/test/java/com/yoke/a2a/RemoteAgentEndToEndTests.java @@ -0,0 +1,115 @@ +package com.yoke.a2a; + +import java.time.Duration; +import java.util.UUID; + +import com.yoke.support.A2aRaw; +import com.yoke.support.RecordingModel; +import com.yoke.support.RedisIntegrationTest; +import com.yoke.support.StubModelConfiguration; +import io.agentscope.core.a2a.agent.card.WellKnownAgentCardResolver; +import org.junit.jupiter.api.Test; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * 客户端经 Agent Card 发现 → message/send → 拿到回复,端到端:同一个 JVM 里 Yoke 自己既是服务端(带 token) + * 又是客户端,客户端通过 {@code POST /api/chat/remote} 调用自己的 A2A 服务。模型是假的。 + */ +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +@ActiveProfiles("test") +@Import(StubModelConfiguration.class) +class RemoteAgentEndToEndTests extends RedisIntegrationTest { + + static final int PORT = A2aRaw.freePort(); + static final String TOKEN = "remote-e2e-token-0123456789"; + + @DynamicPropertySource + static void properties(DynamicPropertyRegistry registry) { + registry.add("server.port", () -> PORT); + registry.add("yoke.a2a.server.enabled", () -> "true"); + registry.add("yoke.a2a.server.token", () -> TOKEN); + registry.add("yoke.a2a.server.public-url", () -> "http://127.0.0.1:" + PORT); + registry.add("yoke.a2a.remote.url", () -> "http://127.0.0.1:" + PORT); + registry.add("yoke.a2a.remote.token", () -> TOKEN); + } + + @Autowired + RecordingModel model; + + final A2aRaw http = new A2aRaw(PORT, null); + + private static String uniqueId() { + return "remote-" + UUID.randomUUID(); + } + + @Test + void 经AgentCard发现后调用远端并拿到回复且会话延续() { + String session = uniqueId(); + + A2aRaw.Response first = http.postJson("/api/chat/remote", + "{\"sessionId\":\"" + session + "\",\"message\":\"远端第一句\"}"); + A2aRaw.Response second = http.postJson("/api/chat/remote", + "{\"sessionId\":\"" + session + "\",\"message\":\"远端第二句\"}"); + + assertThat(first.status()).as(first.body()).isEqualTo(200); + assertThat(first.json().path("reply").asText()).isEqualTo("ok"); + assertThat(first.json().path("sessionId").asText()).isEqualTo(session); + assertThat(second.json().path("reply").asText()).isEqualTo("ok"); + assertThat(model.lastCallContains("远端第一句")).as("sessionId 经 A2A 透传到远端,历史接上").isTrue(); + } + + @Test + void 不传会话ID时新建并返回() { + A2aRaw.Response response = http.postJson("/api/chat/remote", "{\"message\":\"没有会话\"}"); + + assertThat(response.json().path("sessionId").asText()).isNotBlank(); + } + + @Test + void 请求体不能指定远端地址也不能带非法会话ID() { + // 多出来的字段被忽略,目标仍然只来自配置;非法 sessionId 与 /api/chat 一样 400 + A2aRaw.Response ignored = http.postJson("/api/chat/remote", + "{\"message\":\"x\",\"url\":\"http://169.254.169.254/\",\"agentName\":\"evil\"}"); + A2aRaw.Response bad = http.postJson("/api/chat/remote", "{\"sessionId\":\"a/b\",\"message\":\"x\"}"); + A2aRaw.Response blank = http.postJson("/api/chat/remote", "{\"message\":\" \"}"); + + assertThat(ignored.status()).isEqualTo(200); + assertThat(bad.status()).isEqualTo(400); + assertThat(blank.status()).isEqualTo(400); + } + + @Test + void token错误时调用失败并包成明确的异常而不是静默() { + RemoteAgentClient wrongToken = new RemoteAgentClient( + WellKnownAgentCardResolver.builder().baseUrl("http://127.0.0.1:" + PORT).build(), + "remote", "wrong-token", Duration.ofSeconds(10), RemoteAgentClient.originOf("http://127.0.0.1:" + PORT)); + + assertThatThrownBy(() -> wrongToken.ask("s-wrong-token", "你好").block()) + .isInstanceOf(RemoteAgentException.class) + .hasMessageContaining("调用远端 Agent 失败") + .satisfies(e -> assertThat(e.getMessage()).doesNotContain("wrong-token").doesNotContain("127.0.0.1")); + } + + @Test + void 卡片声明的地址与配置不同源时拒绝调用() { + // 配置写的是 localhost,卡片里写的是 127.0.0.1:同机但不同源,也要拒绝,否则改过的卡片能把请求引到别处 + RemoteAgentClient mismatched = new RemoteAgentClient( + WellKnownAgentCardResolver.builder().baseUrl("http://127.0.0.1:" + PORT).build(), + "remote", TOKEN, Duration.ofSeconds(10), RemoteAgentClient.originOf("http://localhost:" + PORT)); + int before = model.received.size(); + + assertThatThrownBy(() -> mismatched.ask("s-origin", "你好").block()) + .isInstanceOf(RemoteAgentException.class) + .hasMessageContaining("不一致"); + assertThat(model.received.size()).isEqualTo(before); + } +} diff --git a/src/test/java/com/yoke/a2a/YokeAgentRunnerTests.java b/src/test/java/com/yoke/a2a/YokeAgentRunnerTests.java new file mode 100644 index 0000000..b6df409 --- /dev/null +++ b/src/test/java/com/yoke/a2a/YokeAgentRunnerTests.java @@ -0,0 +1,212 @@ +package com.yoke.a2a; + +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import java.util.Map; + +import com.yoke.a2a.runner.YokeAgentRunner; +import com.yoke.config.HarnessAgentFactory; +import com.yoke.support.ScriptedModel; +import com.yoke.support.TestAgents; +import com.yoke.tool.ChatTools; +import io.agentscope.core.a2a.server.executor.runner.AgentRequestOptions; +import io.agentscope.core.event.AgentEvent; +import io.agentscope.core.event.AgentResultEvent; +import io.agentscope.core.message.Msg; +import io.agentscope.core.message.MsgRole; +import io.agentscope.core.message.UserMessage; +import io.agentscope.core.tool.Toolkit; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import reactor.core.publisher.Flux; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** 不依赖 Spring 和 Docker:直接测 AgentRunner 的适配逻辑(真实 HarnessAgent,脚本模型)。 */ +class YokeAgentRunnerTests { + + private static Toolkit toolkit() { + Toolkit toolkit = new Toolkit(); + toolkit.registerTool(new ChatTools()); + return toolkit; + } + + private final TestAgents.CloseTracker tracker = new TestAgents.CloseTracker(); + + @AfterEach + void awaitAgentsClosed() throws Exception { + tracker.awaitAllClosed(); + } + + private YokeAgentRunner runner(ScriptedModel model, Path workspace, Duration timeout) { + return new YokeAgentRunner(tracker.wrap(TestAgents.factory(model, workspace, toolkit())), "yoke", "测试", timeout); + } + + private static AgentRequestOptions options(String task, String user, String session) { + AgentRequestOptions options = new AgentRequestOptions(); + options.setTaskId(task); + options.setUserId(user); + options.setSessionId(session); + return options; + } + + private static List input(String text) { + return List.of(new UserMessage(text)); + } + + private static String replyText(List events) { + assertThat(events).hasSize(1).first().isInstanceOf(AgentResultEvent.class); + return ((AgentResultEvent) events.getFirst()).getResult().getTextContent(); + } + + @Test + void 只放行最终结果事件且只含文本(@TempDir Path workspace) { + ScriptedModel model = new ScriptedModel(_ -> ScriptedModel.text("回复")); + + List events = runner(model, workspace, Duration.ofSeconds(30)) + .streamEvents(input("你好"), options("t1", "u1", "s1")).collectList().block(); + + assertThat(replyText(events)).isEqualTo("回复"); + } + + @Test + void 模型的思考过程不会出现在对外的结果里(@TempDir Path workspace) { + ScriptedModel model = new ScriptedModel(_ -> List.of( + io.agentscope.core.message.ThinkingBlock.builder().thinking("内部思考不能外泄").build(), + io.agentscope.core.message.TextBlock.builder().text("最终答案").build())); + + List events = runner(model, workspace, Duration.ofSeconds(30)) + .streamEvents(input("问"), options("t-think", "u", "s-think")).collectList().blockOptional().orElseThrow(); + + Msg result = ((AgentResultEvent) events.getFirst()).getResult(); + assertThat(result.getTextContent()).isEqualTo("最终答案"); + assertThat(result.getContent()).allMatch(io.agentscope.core.message.TextBlock.class::isInstance); + } + + @Test + void 不合法的用户或会话标识直接拒绝并记入失败台账(@TempDir Path workspace) { + YokeAgentRunner runner = runner(new ScriptedModel(_ -> ScriptedModel.text("x")), workspace, Duration.ofSeconds(30)); + + assertThatThrownBy(() -> runner.streamEvents(input("x"), options("t-bad-user", "../etc", "s1")).blockLast()) + .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("userId"); + assertThatThrownBy(() -> runner.streamEvents(input("x"), options("t-bad-session", "u1", "a/b")).blockLast()) + .isInstanceOf(IllegalArgumentException.class).hasMessageContaining("sessionId"); + assertThat(runner.takeFailure("t-bad-user")).isPresent(); + assertThat(runner.takeFailure("t-bad-user")).as("取走即清除").isEmpty(); + assertThat(runner.takeFailure("t-bad-session")).isPresent(); + } + + @Test + void 没有文本内容时拒绝(@TempDir Path workspace) { + YokeAgentRunner runner = runner(new ScriptedModel(_ -> ScriptedModel.text("x")), workspace, Duration.ofSeconds(30)); + + assertThatThrownBy(() -> runner.streamEvents(List.of(), options("t-empty", "u", "s")).blockLast()) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void 缺失的userId按default处理_业务工具拿到的是它(@TempDir Path workspace) { + // list_my_notes 按 RuntimeContext 里的 UserContext 取当前用户的笔记:default 用户有「给 Redis 加上密码」 + ScriptedModel model = new ScriptedModel(call -> { + if (call.systemText().startsWith("You are a memory")) { + return ScriptedModel.text("[]"); + } + return call.hasToolResult() ? ScriptedModel.text(call.lastToolResultText()) + : ScriptedModel.toolUse("c1", "list_my_notes", Map.of()); + }); + + List events = runner(model, workspace, Duration.ofSeconds(30)) + .streamEvents(input("我的笔记"), options("t-notes", null, "s-notes")).collectList().block(); + + assertThat(replyText(events)).contains("给 Redis 加上密码"); + } + + @Test + void 指定用户时业务工具拿到的是那个用户(@TempDir Path workspace) { + ScriptedModel model = new ScriptedModel(call -> { + if (call.systemText().startsWith("You are a memory")) { + return ScriptedModel.text("[]"); + } + return call.hasToolResult() ? ScriptedModel.text(call.lastToolResultText()) + : ScriptedModel.toolUse("c1", "list_my_notes", Map.of()); + }); + + List events = runner(model, workspace, Duration.ofSeconds(30)) + .streamEvents(input("我的笔记"), options("t-alice", "alice", "s-alice")).collectList().block(); + + assertThat(replyText(events)).contains("评估 MCP 服务的鉴权方式"); + } + + @Test + void 超时后失败并记入台账(@TempDir Path workspace) { + ScriptedModel slow = new ScriptedModel(_ -> { + try { + Thread.sleep(3_000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return ScriptedModel.text("太慢了"); + }); + YokeAgentRunner runner = runner(slow, workspace, Duration.ofMillis(500)); + + assertThatThrownBy(() -> runner.streamEvents(input("慢"), options("t-slow", "u", "s-slow")).collectList().block()) + .hasRootCauseInstanceOf(java.util.concurrent.TimeoutException.class); + assertThat(runner.takeFailure("t-slow")).contains("智能体执行超时"); + } + + @Test + void 正常结束_出错和取消时都关闭Agent() { + HarnessAgentFactory factory = mock(HarnessAgentFactory.class); + io.agentscope.harness.agent.HarnessAgent agent = mock(io.agentscope.harness.agent.HarnessAgent.class); + when(factory.create()).thenReturn(agent); + YokeAgentRunner runner = new YokeAgentRunner(factory, "yoke", "测试", Duration.ofSeconds(5)); + + when(agent.streamEvents(anyList(), any(io.agentscope.core.agent.RuntimeContext.class))) + .thenReturn(Flux.empty()); + runner.streamEvents(input("完成"), options("t-ok", "u", "s")).collectList().block(); + verify(agent).close(); + + io.agentscope.harness.agent.HarnessAgent failing = mock(io.agentscope.harness.agent.HarnessAgent.class); + when(factory.create()).thenReturn(failing); + when(failing.streamEvents(anyList(), any(io.agentscope.core.agent.RuntimeContext.class))) + .thenReturn(Flux.error(new IllegalStateException("boom"))); + assertThatThrownBy(() -> runner.streamEvents(input("出错"), options("t-err", "u", "s")).collectList().block()) + .isInstanceOf(IllegalStateException.class); + verify(failing).close(); + + io.agentscope.harness.agent.HarnessAgent hanging = mock(io.agentscope.harness.agent.HarnessAgent.class); + when(factory.create()).thenReturn(hanging); + when(hanging.streamEvents(anyList(), any(io.agentscope.core.agent.RuntimeContext.class))) + .thenReturn(Flux.never()); + runner.streamEvents(input("取消"), options("t-cancel", "u", "s")).subscribe().dispose(); + verify(hanging).close(); + } + + @Test + void 关闭Agent失败也不把已经成功的调用变成失败() { + HarnessAgentFactory factory = mock(HarnessAgentFactory.class); + io.agentscope.harness.agent.HarnessAgent agent = mock(io.agentscope.harness.agent.HarnessAgent.class); + when(factory.create()).thenReturn(agent); + when(agent.streamEvents(anyList(), any(io.agentscope.core.agent.RuntimeContext.class))) + .thenReturn(Flux.just(new AgentResultEvent(Msg.builder().role(MsgRole.ASSISTANT).textContent("好").build()))); + doThrow(new IllegalStateException("close failed")).when(agent).close(); + YokeAgentRunner runner = new YokeAgentRunner(factory, "yoke", "测试", Duration.ofSeconds(5)); + + List events = runner.streamEvents(input("问"), options("t-close", "u", "s")) + .collectList().blockOptional().orElseThrow(); + + assertThat(events).hasSize(1); + assertThat(((AgentResultEvent) events.getFirst()).getResult().getTextContent()).isEqualTo("好"); + verify(agent).close(); + assertThat(runner.takeFailure("t-close")).as("关闭失败不进失败台账").isEmpty(); + } +} diff --git a/src/test/java/com/yoke/config/A2aClientWiringTests.java b/src/test/java/com/yoke/config/A2aClientWiringTests.java new file mode 100644 index 0000000..843075e --- /dev/null +++ b/src/test/java/com/yoke/config/A2aClientWiringTests.java @@ -0,0 +1,45 @@ +package com.yoke.config; + +import com.yoke.a2a.NoRedirectCardResolver; +import com.yoke.a2a.RemoteAgentClient; +import org.junit.jupiter.api.Test; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Configuration; + +import static org.assertj.core.api.Assertions.assertThat; + +/** 生产装配本身要被测试盯住:well-known 直连用的必须是不跟随重定向的卡片解析器,而不是官方那个。 */ +class A2aClientWiringTests { + + @Configuration(proxyBeanMethods = false) + @EnableConfigurationProperties(YokeProperties.class) + static class Props { + } + + private final ApplicationContextRunner runner = new ApplicationContextRunner() + .withPropertyValues("yoke.workspace=/tmp/yoke-wiring", "yoke.redis.uri=redis://127.0.0.1:6379") + .withUserConfiguration(Props.class, A2aClientConfiguration.class); + + @Test + void 直连模式装配出不跟随重定向的卡片解析器且关闭上下文时释放HTTP客户端() { + java.util.concurrent.atomic.AtomicReference holder = new java.util.concurrent.atomic.AtomicReference<>(); + runner.withPropertyValues("yoke.a2a.remote.url=http://127.0.0.1:1").run(context -> { + assertThat(context).hasNotFailed(); + RemoteAgentClient client = context.getBean(RemoteAgentClient.class); + assertThat(client.cardResolver()).isInstanceOf(NoRedirectCardResolver.class); + assertThat(client.httpClient().isTerminated()).isFalse(); + holder.set(client); + }); + + RemoteAgentClient closed = holder.get(); + assertThat(closed.httpClient().isTerminated()).as("容器关闭时释放发消息的 HttpClient").isTrue(); + assertThat(((NoRedirectCardResolver) closed.cardResolver()).isTerminated()).as("容器关闭时释放取卡片的 HttpClient").isTrue(); + } + + @Test + void 没有配置远端时不装配客户端() { + runner.run(context -> assertThat(context).doesNotHaveBean(RemoteAgentClient.class)); + } +} diff --git a/src/test/java/com/yoke/config/A2aNacosPropertiesTests.java b/src/test/java/com/yoke/config/A2aNacosPropertiesTests.java new file mode 100644 index 0000000..1f8f18b --- /dev/null +++ b/src/test/java/com/yoke/config/A2aNacosPropertiesTests.java @@ -0,0 +1,154 @@ +package com.yoke.config; + +import java.time.Duration; +import java.util.Map; + +import io.a2a.spec.AgentCard; +import org.junit.jupiter.api.Test; + +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.context.properties.source.MapConfigurationPropertySource; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class A2aNacosPropertiesTests { + + private static YokeProperties bind(Map extra) { + Map source = new java.util.HashMap<>(Map.of("yoke.workspace", "/tmp/yoke", "yoke.redis.uri", "redis://127.0.0.1:6379")); + source.putAll(extra); + return new Binder(new MapConfigurationPropertySource(source)).bind("yoke", YokeProperties.class).get(); + } + + @Test + void 什么都不配置时A2A服务端_远端和Nacos全部关闭() { + YokeProperties yoke = bind(Map.of()); + + assertThat(yoke.a2a().server().enabled()).isFalse(); + assertThat(yoke.a2a().server().tokenConfigured()).isFalse(); + assertThat(yoke.a2a().remote().configured()).isFalse(); + assertThat(yoke.nacos().a2a().enabled()).isFalse(); + assertThat(yoke.nacos().prompt().enabled()).isFalse(); + assertThat(yoke.nacos().anyEnabled()).isFalse(); + assertThat(yoke.a2a().server().timeout()).isEqualTo(Duration.ofSeconds(120)); + assertThat(yoke.a2a().remote().timeout()).isEqualTo(Duration.ofSeconds(30)); + } + + @Test + void 配置绑定后开关生效() { + YokeProperties yoke = bind(Map.of("yoke.a2a.server.enabled", "true", "yoke.nacos.prompt.enabled", "true", + "yoke.a2a.remote.url", "http://other:8080", "yoke.a2a.server.card.skills[0].id", "s1", + "yoke.a2a.server.card.skills[0].name", "技能一")); + + assertThat(yoke.a2a().server().enabled()).isTrue(); + assertThat(yoke.nacos().anyEnabled()).isTrue(); + assertThat(yoke.a2a().remote().configured()).isTrue(); + assertThat(yoke.a2a().server().card().skills()).extracting(YokeProperties.A2a.Skill::id).containsExactly("s1"); + } + + @Test + void 敏感配置的toString都脱敏() { + YokeProperties yoke = bind(Map.of("yoke.a2a.server.token", "server-token-AAA", "yoke.a2a.remote.token", "remote-token-BBB", + "yoke.a2a.remote.url", "http://other:8080/internal-path?queryParam=should-be-stripped", + "yoke.nacos.password", "nacos-pass-CCC", "yoke.nacos.username", "nacos-user")); + + String all = yoke.a2a().server() + " " + yoke.a2a().remote() + " " + yoke.nacos() + " " + yoke.a2a() + " " + yoke; + + assertThat(all).doesNotContain("server-token-AAA").doesNotContain("remote-token-BBB").doesNotContain("nacos-pass-CCC") + .doesNotContain("internal-path").doesNotContain("should-be-stripped"); + assertThat(all).contains("url=http://other:8080").contains("token=***").contains("password=***"); + } + + @Test + void 远端来源_配了名字且Nacos开启时用Nacos() { + YokeProperties yoke = bind(Map.of("yoke.a2a.remote.agent-name", "peer", "yoke.nacos.a2a.enabled", "true")); + + assertThat(A2aClientConfiguration.cardSource(yoke)).isEqualTo(A2aClientConfiguration.CardSource.NACOS); + } + + @Test + void 远端来源_两个都配且Nacos开启时仍然用Nacos() { + YokeProperties yoke = bind(Map.of("yoke.a2a.remote.agent-name", "peer", "yoke.a2a.remote.url", "http://x:1", + "yoke.nacos.a2a.enabled", "true")); + + assertThat(A2aClientConfiguration.cardSource(yoke)).isEqualTo(A2aClientConfiguration.CardSource.NACOS); + } + + @Test + void 远端来源_只配url时直连() { + YokeProperties yoke = bind(Map.of("yoke.a2a.remote.url", "http://x:1")); + + assertThat(A2aClientConfiguration.cardSource(yoke)).isEqualTo(A2aClientConfiguration.CardSource.WELL_KNOWN); + } + + @Test + void 远端来源_配了名字但Nacos没开时启动失败而不是悄悄换来源() { + YokeProperties yoke = bind(Map.of("yoke.a2a.remote.agent-name", "peer", "yoke.a2a.remote.url", "http://x:1")); + + assertThatThrownBy(() -> A2aClientConfiguration.cardSource(yoke)) + .isInstanceOf(IllegalStateException.class).hasMessageContaining("yoke.nacos.a2a.enabled"); + } + + @Test + void 公布的AgentCard一律不声明流式() { + AgentCard original = new AgentCard.Builder().name("n").description("d").url("http://h/a2a").version("1") + .capabilities(new io.a2a.spec.AgentCapabilities(true, true, true, java.util.List.of())) + .defaultInputModes(java.util.List.of("text")).defaultOutputModes(java.util.List.of("text")) + .skills(java.util.List.of()).build(); + + var capabilities = A2aServerConfiguration.publishedCard(original).capabilities(); + + assertThat(capabilities.streaming()).isFalse(); + assertThat(capabilities.pushNotifications()).isFalse(); + assertThat(capabilities.stateTransitionHistory()).isFalse(); + } + + @Test + void 配置了token但太短时启动失败且报错不含token() { + YokeProperties yoke = bind(Map.of("yoke.a2a.server.token", "short-tok")); + + assertThatThrownBy(() -> A2aServerConfiguration.requireStrongToken(yoke.a2a().server())) + .isInstanceOf(IllegalStateException.class).hasMessageContaining("太短") + .satisfies(e -> assertThat(e.getMessage()).doesNotContain("short-tok")); + } + + @Test + void 足够长的token或没配token都不触发长度检查() { + A2aServerConfiguration.requireStrongToken(bind(Map.of("yoke.a2a.server.token", "0123456789abcdef")).a2a().server()); + A2aServerConfiguration.requireStrongToken(bind(Map.of()).a2a().server()); + } + + @Test + void 请求体上限默认256KB且非法值回落() { + assertThat(bind(Map.of()).a2a().server().maxBodyBytes()).isEqualTo(262144); + assertThat(bind(Map.of("yoke.a2a.server.max-body-bytes", "-5")).a2a().server().maxBodyBytes()).isEqualTo(262144); + assertThat(bind(Map.of("yoke.a2a.server.max-body-bytes", "1000")).a2a().server().maxBodyBytes()).isEqualTo(1000); + } + + @Test + void 对外根地址支持反向代理子路径且不合法地址直接拒绝() { + org.springframework.mock.env.MockEnvironment env = new org.springframework.mock.env.MockEnvironment() + .withProperty("server.port", "9090"); + + var defaulted = A2aServerConfiguration.resolveTransport(bind(Map.of()).a2a().server(), env); + assertThat(defaulted.host()).isEqualTo("localhost"); + assertThat(defaulted.port()).isEqualTo(9090); + assertThat(defaulted.path()).isEqualTo("/a2a"); + assertThat(defaulted.supportTls()).isFalse(); + + var subpath = A2aServerConfiguration.resolveTransport( + bind(Map.of("yoke.a2a.server.public-url", "https://agent.example.com/yoke/")).a2a().server(), env); + assertThat(subpath.host()).isEqualTo("agent.example.com"); + assertThat(subpath.port()).isEqualTo(443); + assertThat(subpath.path()).isEqualTo("/yoke/a2a"); + assertThat(subpath.supportTls()).isTrue(); + + for (String bad : new String[] {"localhost:8080", "http://bad_host:8080", "https://example.com?token=leak"}) { + YokeProperties.A2a.Server server = bind(Map.of("yoke.a2a.server.public-url", bad)).a2a().server(); + assertThatThrownBy(() -> A2aServerConfiguration.resolveTransport(server, env)) + .as("public-url=%s", bad) + .isInstanceOf(IllegalStateException.class) + .satisfies(e -> assertThat(e.getMessage()).doesNotContain("leak")); + } + } +} diff --git a/src/test/java/com/yoke/config/AgentConfigurationConflictTests.java b/src/test/java/com/yoke/config/AgentConfigurationConflictTests.java index ea9b5e5..5ca1382 100644 --- a/src/test/java/com/yoke/config/AgentConfigurationConflictTests.java +++ b/src/test/java/com/yoke/config/AgentConfigurationConflictTests.java @@ -29,7 +29,7 @@ private ApplicationContextRunner runner(Path workspace) { .withBean(YokeProperties.class, () -> new YokeProperties(new YokeProperties.Redis("redis://127.0.0.1:6379", "yoke:"), new YokeProperties.Compaction(30, 10), workspace.toString(), new YokeProperties.Knowledge(new YokeProperties.Knowledge.Embedding(null, null, null, null, null)), - new YokeProperties.Mcp(List.of()))) + new YokeProperties.Mcp(List.of()), YokeProperties.A2a.disabled(), YokeProperties.Nacos.disabled())) .withUserConfiguration(AgentConfiguration.class); } diff --git a/src/test/java/com/yoke/config/AgentConfigurationTests.java b/src/test/java/com/yoke/config/AgentConfigurationTests.java index a74ef59..d0f453a 100644 --- a/src/test/java/com/yoke/config/AgentConfigurationTests.java +++ b/src/test/java/com/yoke/config/AgentConfigurationTests.java @@ -44,7 +44,7 @@ YokeProperties yokeProperties() { return new YokeProperties(new YokeProperties.Redis("redis://127.0.0.1:6379", "yoke:"), new YokeProperties.Compaction(30, 10), "/tmp/yoke-test", new YokeProperties.Knowledge(new YokeProperties.Knowledge.Embedding(null, null, null, null, null)), - new YokeProperties.Mcp(List.of())); + new YokeProperties.Mcp(List.of()), YokeProperties.A2a.disabled(), YokeProperties.Nacos.disabled()); } @Bean diff --git a/src/test/java/com/yoke/config/RedisConfigurationTests.java b/src/test/java/com/yoke/config/RedisConfigurationTests.java index e1d102d..6506f54 100644 --- a/src/test/java/com/yoke/config/RedisConfigurationTests.java +++ b/src/test/java/com/yoke/config/RedisConfigurationTests.java @@ -12,7 +12,7 @@ class RedisConfigurationTests { private static YokeProperties withUri(String uri) { return new YokeProperties(new YokeProperties.Redis(uri, "yoke:"), new YokeProperties.Compaction(30, 10), "/tmp/yoke", new YokeProperties.Knowledge(new YokeProperties.Knowledge.Embedding(null, null, null, null, null)), - new YokeProperties.Mcp(java.util.List.of())); + new YokeProperties.Mcp(java.util.List.of()), YokeProperties.A2a.disabled(), YokeProperties.Nacos.disabled()); } private static String allMessages(Throwable error) { diff --git a/src/test/java/com/yoke/config/RedisHealthConfigurationTests.java b/src/test/java/com/yoke/config/RedisHealthConfigurationTests.java new file mode 100644 index 0000000..c13f427 --- /dev/null +++ b/src/test/java/com/yoke/config/RedisHealthConfigurationTests.java @@ -0,0 +1,37 @@ +package com.yoke.config; + +import java.util.Objects; + +import org.junit.jupiter.api.Test; +import redis.clients.jedis.RedisClient; +import redis.clients.jedis.exceptions.JedisConnectionException; + +import org.springframework.boot.health.contributor.Status; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class RedisHealthConfigurationTests { + + private final RedisHealthConfiguration config = new RedisHealthConfiguration(); + + @Test + void ping成功时是UP() { + RedisClient jedis = mock(RedisClient.class); + when(jedis.ping()).thenReturn("PONG"); + + assertThat(Objects.requireNonNull(config.redisHealthIndicator(jedis).health()).getStatus()).isEqualTo(Status.UP); + } + + @Test + void ping失败时是DOWN且不带任何明细() { + RedisClient jedis = mock(RedisClient.class); + when(jedis.ping()).thenThrow(new JedisConnectionException("redis://:密码@host 连接失败")); + + var health = Objects.requireNonNull(config.redisHealthIndicator(jedis).health()); + + assertThat(health.getStatus()).isEqualTo(Status.DOWN); + assertThat(health.getDetails()).isEmpty(); + } +} diff --git a/src/test/java/com/yoke/config/SubagentContextTests.java b/src/test/java/com/yoke/config/SubagentContextTests.java index 0925d8a..c6b55f3 100644 --- a/src/test/java/com/yoke/config/SubagentContextTests.java +++ b/src/test/java/com/yoke/config/SubagentContextTests.java @@ -10,6 +10,7 @@ import com.yoke.support.TestAgents; import com.yoke.tool.ChatTools; import io.agentscope.core.tool.Toolkit; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -18,6 +19,13 @@ /** 子 Agent 里调用依赖 UserContext 的工具时,上下文有没有一路传下去。 */ class SubagentContextTests { + private final TestAgents.CloseTracker tracker = new TestAgents.CloseTracker(); + + @AfterEach + void awaitAgentsClosed() throws Exception { + tracker.awaitAllClosed(); + } + @Test void 通用子Agent里调用list_my_notes能拿到发起请求的用户(@TempDir Path workspace) { ScriptedModel model = new ScriptedModel(call -> { @@ -34,7 +42,7 @@ class SubagentContextTests { }); Toolkit toolkit = new Toolkit(); toolkit.registerTool(new ChatTools()); - ChatController controller = AguiTestSupport.controller(TestAgents.factory(model, workspace, toolkit)); + ChatController controller = AguiTestSupport.controller(tracker.wrap(TestAgents.factory(model, workspace, toolkit))); controller.chat(new ChatRequest("sub-ctx", "让子 Agent 查我的笔记", "alice")).block(); diff --git a/src/test/java/com/yoke/config/WorkspaceInitializerTests.java b/src/test/java/com/yoke/config/WorkspaceInitializerTests.java index 9b487d5..95eab3f 100644 --- a/src/test/java/com/yoke/config/WorkspaceInitializerTests.java +++ b/src/test/java/com/yoke/config/WorkspaceInitializerTests.java @@ -18,7 +18,7 @@ private static YokeProperties props(Path workspace) { return new YokeProperties(new YokeProperties.Redis("redis://127.0.0.1:6379", "yoke:"), new YokeProperties.Compaction(30, 10), workspace.toString(), new YokeProperties.Knowledge(new YokeProperties.Knowledge.Embedding(null, null, null, null, null)), - new YokeProperties.Mcp(List.of())); + new YokeProperties.Mcp(List.of()), YokeProperties.A2a.disabled(), YokeProperties.Nacos.disabled()); } @Test diff --git a/src/test/java/com/yoke/controller/A2aControllerBodyLimitTests.java b/src/test/java/com/yoke/controller/A2aControllerBodyLimitTests.java new file mode 100644 index 0000000..5c6e7ae --- /dev/null +++ b/src/test/java/com/yoke/controller/A2aControllerBodyLimitTests.java @@ -0,0 +1,201 @@ +package com.yoke.controller; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.concurrent.atomic.AtomicLong; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.yoke.a2a.A2aGateway; +import com.yoke.a2a.runner.YokeAgentRunner; +import io.a2a.spec.AgentCapabilities; +import io.a2a.spec.AgentCard; +import io.agentscope.core.a2a.server.AgentScopeA2aServer; +import jakarta.servlet.ReadListener; +import jakarta.servlet.ServletInputStream; +import org.jspecify.annotations.NonNull; +import org.junit.jupiter.api.Test; + +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockHttpServletRequest; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +/** + * 认证先于读体、超限不读体:用一个会数「被读走多少字节」的请求证明。 + * 请求体是读不完的无限数据流,如果实现像旧版那样({@code @RequestBody String})把体全读进来,这里会读到内存耗尽或测试超时。 + */ +class A2aControllerBodyLimitTests { + + private static final int MAX = 1000; + private static final String TOKEN = "body-limit-token-0123456789"; + /** 实现读取时的缓冲粒度留一点余量,远小于「读完整个体」。 */ + private static final long SLACK = 16 * 1024; + + /** 会计数的请求:体是读不完的零字节流。 */ + static final class CountingRequest extends MockHttpServletRequest { + + final AtomicLong bytesRead = new AtomicLong(); + private final long declaredLength; + private final long available; + + /** declaredLength 为 -1 表示没声明长度(chunked);available 是体实际有多少字节。 */ + CountingRequest(long declaredLength, long available) { + super("POST", "/a2a"); + this.declaredLength = declaredLength; + this.available = available; + } + + @Override + public long getContentLengthLong() { + return declaredLength; + } + + @Override + @SuppressWarnings("resource") // 数据源由返回的 ServletInputStream 持有,并在它关闭时一起关闭 + public @NonNull ServletInputStream getInputStream() { + InputStream source = new InputStream() { + private long remaining = available; + + @Override + public int read() { + if (remaining <= 0) { + return -1; + } + remaining--; + bytesRead.incrementAndGet(); + return ' '; + } + + @Override + public int read(byte @NonNull [] b, int off, int len) { + if (remaining <= 0) { + return -1; + } + int n = (int) Math.min(Math.min(len, 4096), remaining); + java.util.Arrays.fill(b, off, off + n, (byte) ' '); + remaining -= n; + bytesRead.addAndGet(n); + return n; + } + }; + return new ServletInputStream() { + @Override + public boolean isFinished() { + return false; + } + + @Override + public boolean isReady() { + return true; + } + + @Override + public void setReadListener(ReadListener listener) { + } + + @Override + public int read() throws IOException { + return source.read(); + } + + @Override + public int read(byte @NonNull [] b, int off, int len) throws IOException { + return source.read(b, off, len); + } + + @Override + public void close() throws IOException { + source.close(); + } + }; + } + } + + private static A2aController controller(String token) { + AgentCard card = new AgentCard.Builder().name("n").description("d").url("http://h/a2a").version("1") + .capabilities(new AgentCapabilities(false, false, false, List.of())) + .defaultInputModes(List.of("text")).defaultOutputModes(List.of("text")).skills(List.of()).build(); + return new A2aController(new A2aGateway(mock(AgentScopeA2aServer.class), mock(YokeAgentRunner.class), card, token, MAX)); + } + + private static CountingRequest authorized(CountingRequest request) { + request.addHeader("Authorization", "Bearer " + TOKEN); + return request; + } + + @Test + void 未认证时即使声明了超大的Content_Length也不读体() { + CountingRequest request = new CountingRequest(500_000_000L, Long.MAX_VALUE); + + ResponseEntity response = controller(TOKEN).message(request); + + assertThat(response.getStatusCode().value()).isEqualTo(401); + assertThat(request.bytesRead.get()).isZero(); + } + + @Test + void 未认证的chunked请求也不读体() { + CountingRequest request = new CountingRequest(-1, Long.MAX_VALUE); + + ResponseEntity response = controller(TOKEN).message(request); + + assertThat(response.getStatusCode().value()).isEqualTo(401); + assertThat(request.bytesRead.get()).isZero(); + } + + @Test + void token错误同样不读体() { + CountingRequest request = new CountingRequest(-1, Long.MAX_VALUE); + request.addHeader("Authorization", "Bearer wrong-token"); + + ResponseEntity response = controller(TOKEN).message(request); + + assertThat(response.getStatusCode().value()).isEqualTo(401); + assertThat(request.bytesRead.get()).isZero(); + } + + @Test + void 已认证但声明的长度超限时直接拒绝且不读体() throws Exception { + CountingRequest request = authorized(new CountingRequest(MAX + 1, Long.MAX_VALUE)); + + ResponseEntity response = controller(TOKEN).message(request); + + assertThat(response.getStatusCode().value()).isEqualTo(413); + assertThat(new ObjectMapper().readTree(response.getBody()).path("error").path("code").asInt()).isEqualTo(-32600); + assertThat(request.bytesRead.get()).isZero(); + } + + @Test + void chunked超限时限长读取并中止() { + CountingRequest request = authorized(new CountingRequest(-1, Long.MAX_VALUE)); + + ResponseEntity response = controller(TOKEN).message(request); + + assertThat(response.getStatusCode().value()).isEqualTo(413); + assertThat(request.bytesRead.get()).as("最多读到上限加一个缓冲粒度").isLessThanOrEqualTo(MAX + SLACK); + } + + @Test + void 没有配置token时同样限长() { + CountingRequest request = new CountingRequest(-1, Long.MAX_VALUE); + + ResponseEntity response = controller(null).message(request); + + assertThat(response.getStatusCode().value()).isEqualTo(413); + assertThat(request.bytesRead.get()).isLessThanOrEqualTo(MAX + SLACK); + } + + @Test + void 正常大小的请求读完整个体并继续处理() { + // 体是 500 个空格,不是有效请求:得到的是 200 加 JSON-RPC 的请求无效错误(不是 401 也不是 413),说明通过了认证和大小检查,体也被读完 + CountingRequest request = authorized(new CountingRequest(500, 500)); + + ResponseEntity response = controller(TOKEN).message(request); + + assertThat(response.getStatusCode().value()).isEqualTo(200); + assertThat(response.getBody()).contains("-32600").contains("\"error\""); + assertThat(request.bytesRead.get()).isEqualTo(500); + } +} diff --git a/src/test/java/com/yoke/nacos/NacosIntegrationTests.java b/src/test/java/com/yoke/nacos/NacosIntegrationTests.java new file mode 100644 index 0000000..189f305 --- /dev/null +++ b/src/test/java/com/yoke/nacos/NacosIntegrationTests.java @@ -0,0 +1,267 @@ +package com.yoke.nacos; + +import java.util.Objects; +import java.util.Properties; +import java.util.UUID; + +import com.alibaba.nacos.api.PropertyKeyConst; +import com.alibaba.nacos.api.ai.AiFactory; +import com.alibaba.nacos.api.ai.AiService; +import com.alibaba.nacos.api.exception.NacosException; +import com.yoke.YokeApplication; +import com.yoke.config.YokeProperties; +import com.yoke.support.A2aRaw; +import com.yoke.support.NacosCompose; +import com.yoke.support.NacosIntegrationTest; +import com.yoke.support.RecordingModel; +import com.yoke.support.StubModelConfiguration; +import io.agentscope.core.message.Msg; +import io.agentscope.core.message.MsgRole; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; + +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.ConfigurableApplicationContext; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * 真实 Nacos(docker-compose.yml 里固定版本的 3.x 容器)+ AgentScope 自带的 Nacos 客户端。 + * 每个测试自己启动并关闭一个完整的应用上下文,这样能观察「就绪后注册、关闭时注销」。模型是假的。 + */ +@Slf4j +class NacosIntegrationTests extends NacosIntegrationTest { + + private static final String TEST_WORKSPACE = System.getProperty("java.io.tmpdir") + "/yoke-test-workspace"; + + private static String uniqueId(String prefix) { + return prefix + "-" + UUID.randomUUID().toString().substring(0, 8); + } + + private static YokeProperties.Nacos nacosProps() { + return new YokeProperties.Nacos(NacosCompose.serverAddr(), null, null, null, + new YokeProperties.Nacos.A2aSwitch(true, false), new YokeProperties.Nacos.PromptSwitch(false, "k", java.time.Duration.ofSeconds(2))); + } + + /** 用命令行参数的形式传属性:优先级最高,不会被 application.yml 里的空默认值盖掉(builder.properties 是最低优先级)。 */ + private static ConfigurableApplicationContext start(String... properties) { + // 同名选项出现两次会被拼成逗号分隔的值,所以后面的覆盖前面的 + java.util.Map args = new java.util.LinkedHashMap<>(); + args.put("yoke.redis.uri", com.yoke.support.RedisCompose.uri()); + args.put("yoke.nacos.server-addr", NacosCompose.serverAddr()); + args.put("spring.main.banner-mode", "off"); + for (String property : properties) { + int eq = property.indexOf('='); + args.put(property.substring(0, eq), property.substring(eq + 1)); + } + String[] cli = args.entrySet().stream().map(e -> "--" + e.getKey() + "=" + e.getValue()).toArray(String[]::new); + return new SpringApplicationBuilder(YokeApplication.class, StubModelConfiguration.class) + .profiles("test").run(cli); + } + + private static AiService independentClient() throws NacosException { + NacosSupport.redirectClientFiles(TEST_WORKSPACE); + Properties props = new Properties(); + props.setProperty(PropertyKeyConst.SERVER_ADDR, NacosCompose.serverAddr()); + return AiFactory.createAiService(props); + } + + @Test + void 探活成功时返回可用的客户端() throws Exception { + AiService service = NacosSupport.connect(nacosProps(), TEST_WORKSPACE); + + assertThat(service).isNotNull(); + service.shutdown(); + } + + @Test + void 端口不对时探活失败而不是静默() { + // 主端口对、gRPC 端口(主端口 + 1000)连不上:这是最常见的接线错误 + String[] hostPort = NacosCompose.serverAddr().split(":"); + int wrongMain = Integer.parseInt(hostPort[1]) + 1; + YokeProperties.Nacos wrong = new YokeProperties.Nacos("127.0.0.1:" + wrongMain, null, null, null, + new YokeProperties.Nacos.A2aSwitch(true, false), new YokeProperties.Nacos.PromptSwitch(false, "k", java.time.Duration.ofSeconds(2))); + + assertThatThrownBy(() -> NacosSupport.connect(wrong, TEST_WORKSPACE)).isInstanceOf(IllegalStateException.class) + .hasMessageContaining("无法使用 Nacos 的 AI 通道"); + } + + @Test + void 开关打开且Nacos不可达时整个应用启动失败() { + assertThatThrownBy(() -> start("yoke.nacos.prompt.enabled=true", "yoke.nacos.server-addr=127.0.0.1:1", + "yoke.nacos.password=S3cret-Pass-xyz", "server.port=0")) + .satisfies(e -> { + StringBuilder all = new StringBuilder(); + for (Throwable t = e; Objects.nonNull(t); t = t.getCause()) { + all.append(t.getMessage()).append('\n'); + } + assertThat(all.toString()).contains("无法使用 Nacos 的 AI 通道").doesNotContain("S3cret-Pass-xyz"); + }); + } + + @Test + void Prompt热更新_改完下一轮对话就用新版本且不重复拼接() { + String key = uniqueId("hot-prompt"); + NacosCompose.publishPrompt(key, "1.0.0", "【热更新版本一】请在回答末尾加上喵。"); + try (ConfigurableApplicationContext context = start("yoke.nacos.prompt.enabled=true", + "yoke.nacos.prompt.key=" + key, "server.port=0")) { + RecordingModel model = context.getBean(RecordingModel.class); + var controller = context.getBean(com.yoke.controller.ChatController.class); + String session = uniqueId("hot"); + + controller.chat(new com.yoke.model.ChatRequest(session, "第一轮")).block(); + String first = systemText(model, "第一轮"); + assertThat(first).contains("【热更新版本一】").contains("你是一个乐于助人的 AI 助手"); + assertThat(first.split("【热更新版本一】", -1)).as("只出现一次").hasSize(2); + + NacosCompose.publishPrompt(key, "1.0.1", "【热更新版本二】请在回答末尾加上汪。"); + // 发布到生效之间有一小段服务端传播延迟(实测几十到几百毫秒),所以每隔一会儿再问一轮,最多等 10 秒 + long start = System.nanoTime(); + String second = ""; + for (int turn = 0; turn < 50 && !second.contains("【热更新版本二】"); turn++) { + String user = "第二轮-" + turn; + controller.chat(new com.yoke.model.ChatRequest(session, user)).block(); + second = systemText(model, user); + if (!second.contains("【热更新版本二】")) { + sleepQuietly(200); + } + } + log.info("PROMPT-HOT-UPDATE 发布后 {} ms 内生效", (System.nanoTime() - start) / 1_000_000); + + assertThat(second).contains("【热更新版本二】").doesNotContain("【热更新版本一】"); + assertThat(second.split("【热更新版本二】", -1)).hasSize(2); + } + } + + @Test + void Prompt在Nacos里不存在时对话照常进行() { + try (ConfigurableApplicationContext context = start("yoke.nacos.prompt.enabled=true", + "yoke.nacos.prompt.key=" + uniqueId("missing"), "server.port=0")) { + RecordingModel model = context.getBean(RecordingModel.class); + var reply = context.getBean(com.yoke.controller.ChatController.class) + .chat(new com.yoke.model.ChatRequest(uniqueId("s"), "你好")).blockOptional().orElseThrow(); + + assertThat(reply.reply()).isEqualTo("ok"); + assertThat(systemText(model, "你好")).contains("你是一个乐于助人的 AI 助手"); + } + } + + /** 该 Agent 的端点(服务实例)数量:端点注册在命名服务里,Card 本身是配置数据,不能用 Card 判断在线与否。 */ + private static int endpointCount(String agentName) { + String body = NacosCompose.httpGet("/nacos/v3/admin/ns/service/list?pageNo=1&pageSize=200&groupNameParam=agent-endpoints"); + try { + for (var item : new com.fasterxml.jackson.databind.ObjectMapper().readTree(body).path("data").path("pageItems")) { + // 服务名里的非字母数字被转义成 _ASCII 码,所以按转义后的名字比较 + if (item.path("name").asText().contains(escape(agentName))) { + return item.path("ipCount").asInt(); + } + } + return 0; + } catch (java.io.IOException e) { + throw new IllegalStateException(body, e); + } + } + + private static String escape(String name) { + StringBuilder out = new StringBuilder(); + for (char c : name.toCharArray()) { + out.append(Character.isLetter(c) || c == '-' ? String.valueOf(c) : "_" + String.format("%03d", (int) c)); + } + return out.toString(); + } + + @Test + void A2A服务就绪后注册到Nacos关闭后注销() throws Exception { + int port = A2aRaw.freePort(); + String name = uniqueId("yoke-reg"); + AiService observer = independentClient(); + try { + try (ConfigurableApplicationContext _ = start("yoke.a2a.server.enabled=true", + "yoke.a2a.server.card.name=" + name, "yoke.nacos.a2a.enabled=true", "server.port=" + port, + "yoke.a2a.server.public-url=http://127.0.0.1:" + port)) { + var card = observer.getAgentCard(name); + + assertThat(card.getName()).isEqualTo(name); + assertThat(card.getUrl()).isEqualTo("http://127.0.0.1:" + port + "/a2a"); + assertThat(card.getCapabilities().getStreaming()).as("注册的 Card 也要说真话").isFalse(); + assertThat(endpointCount(name)).as("就绪后端点已注册").isEqualTo(1); + } + long start = System.nanoTime(); + int remaining = endpointCount(name); + while (remaining > 0 && System.nanoTime() - start < 15_000_000_000L) { + sleepQuietly(300); + remaining = endpointCount(name); + } + log.info("DEREGISTER 关闭后等待 {} ms,剩余端点 {}", (System.nanoTime() - start) / 1_000_000, remaining); + assertThat(remaining).as("关闭后端点已注销").isZero(); + } finally { + observer.shutdown(); + } + } + + @Test + void 主动注销会在客户端仍连着时就删除端点() throws Exception { + // 区别于「关闭应用」:这里客户端连接一直在,端点只可能是被 deregister 删掉的,而不是连接断开后被服务端摘除 + String name = uniqueId("yoke-dereg"); + AiService client = NacosSupport.connect(nacosProps(), TEST_WORKSPACE); + try { + io.a2a.spec.AgentCard card = new io.a2a.spec.AgentCard.Builder().name(name).description("d") + .url("http://127.0.0.1:45678/a2a").version("1.0.0").protocolVersion("0.3.0").preferredTransport("JSONRPC") + .capabilities(new io.a2a.spec.AgentCapabilities(false, false, false, java.util.List.of())) + .defaultInputModes(java.util.List.of("text")).defaultOutputModes(java.util.List.of("text")) + .skills(java.util.List.of()).build(); + NacosA2aRegistrar registrar = new NacosA2aRegistrar(client, false); + registrar.register(card); + assertThat(endpointCount(name)).isEqualTo(1); + + registrar.deregister(); + + int remaining = endpointCount(name); + for (int i = 0; i < 40 && remaining > 0; i++) { + sleepQuietly(250); + remaining = endpointCount(name); + } + assertThat(remaining).isZero(); + } finally { + client.shutdown(); + } + } + + @Test + void 经Nacos发现远端并调用() { + int port = A2aRaw.freePort(); + String name = uniqueId("yoke-disc"); + try (ConfigurableApplicationContext context = start("yoke.a2a.server.enabled=true", + "yoke.a2a.server.card.name=" + name, "yoke.nacos.a2a.enabled=true", "server.port=" + port, + "yoke.a2a.server.public-url=http://127.0.0.1:" + port, "yoke.a2a.remote.agent-name=" + name)) { + A2aRaw.Response response = new A2aRaw(port, null).postJson("/api/chat/remote", + "{\"sessionId\":\"" + uniqueId("d") + "\",\"message\":\"经 Nacos 发现\"}"); + + assertThat(response.status()).as(response.body()).isEqualTo(200); + assertThat(response.json().path("reply").asText()).isEqualTo("ok"); + assertThat(context.getBean(RecordingModel.class).received.stream().flatMap(java.util.List::stream) + .anyMatch(m -> Objects.nonNull(m.getTextContent()) && m.getTextContent().contains("经 Nacos 发现"))).isTrue(); + } + } + + private static void sleepQuietly(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + /** 主 Agent 处理某句话时模型收到的系统提示词(框架后台还会用同一个模型做记忆整理等调用,所以按用户的话找)。 */ + private static String systemText(RecordingModel model, String userText) { + var call = model.received.stream() + .filter(messages -> messages.stream().anyMatch(m -> m.getRole() == MsgRole.USER + && Objects.nonNull(m.getTextContent()) && m.getTextContent().contains(userText))) + .filter(messages -> messages.stream().anyMatch(m -> m.getRole() == MsgRole.SYSTEM + && Objects.nonNull(m.getTextContent()) && m.getTextContent().contains("你是一个乐于助人的 AI 助手"))) + .reduce((_, second) -> second).orElseThrow(); + return call.stream().filter(m -> m.getRole() == MsgRole.SYSTEM) + .map(Msg::getTextContent).reduce("", (a, b) -> a + "\n" + b); + } +} diff --git a/src/test/java/com/yoke/nacos/NacosPromptMiddlewareTests.java b/src/test/java/com/yoke/nacos/NacosPromptMiddlewareTests.java new file mode 100644 index 0000000..0edba73 --- /dev/null +++ b/src/test/java/com/yoke/nacos/NacosPromptMiddlewareTests.java @@ -0,0 +1,110 @@ +package com.yoke.nacos; + +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; + +import com.alibaba.nacos.api.ai.AiService; +import com.alibaba.nacos.api.ai.model.prompt.Prompt; +import com.alibaba.nacos.api.exception.NacosException; +import com.yoke.config.HarnessAgentFactory; +import com.yoke.config.YokeProperties; +import com.yoke.config.YokeSubagents; +import com.yoke.support.ScriptedModel; +import com.yoke.support.TestAgents; +import io.agentscope.core.agent.RuntimeContext; +import io.agentscope.core.tool.Toolkit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class NacosPromptMiddlewareTests { + + private static NacosPromptMiddleware middlewareReturning(String template) throws NacosException { + AiService ai = mock(AiService.class); + when(ai.getPrompt("k")).thenReturn(new Prompt("k", "1.0.0", template)); + return new NacosPromptMiddleware(ai, "k", Duration.ofSeconds(2)); + } + + private static String apply(NacosPromptMiddleware middleware, String current) { + return middleware.onSystemPrompt(null, null, current).block(); + } + + @Test + void 最新提示词追加在内置提示词之后() throws Exception { + String result = apply(middlewareReturning("请用海盗口吻回答"), "你是助手\n"); + + assertThat(result).isEqualTo("你是助手\n\n请用海盗口吻回答"); + } + + @Test + void 重复调用不会重复拼接() throws Exception { + NacosPromptMiddleware middleware = middlewareReturning("请用海盗口吻回答"); + + String once = apply(middleware, "你是助手"); + String twice = apply(middleware, once); + + assertThat(twice).isEqualTo(once); + assertThat(twice.split("请用海盗口吻回答", -1)).hasSize(2); + } + + @Test + void 拉取失败时原样返回当前提示词() throws Exception { + AiService ai = mock(AiService.class); + when(ai.getPrompt("k")).thenThrow(new NacosException(NacosException.SERVER_ERROR, "boom 带着地址 10.0.0.1")); + + assertThat(apply(new NacosPromptMiddleware(ai, "k", Duration.ofSeconds(2)), "内置提示词")).isEqualTo("内置提示词"); + } + + @Test + void Prompt不存在或为空白时原样返回() throws Exception { + AiService missing = mock(AiService.class); + when(missing.getPrompt("k")).thenThrow(new NacosException(NacosException.NOT_FOUND, "prompt not found")); + + assertThat(apply(new NacosPromptMiddleware(missing, "k", Duration.ofSeconds(2)), "内置提示词")).isEqualTo("内置提示词"); + assertThat(apply(middlewareReturning(" \n "), "内置提示词")).isEqualTo("内置提示词"); + assertThat(apply(middlewareReturning(null), "内置提示词")).isEqualTo("内置提示词"); + } + + @Test + void 内置提示词为空时只返回Nacos里的内容() throws Exception { + assertThat(apply(middlewareReturning("只有这一段"), "")).isEqualTo("只有这一段"); + } + + @Test + void Nacos不响应时在超时后兜底_对话仍然成功(@TempDir Path workspace) throws Exception { + AiService hanging = mock(AiService.class); + when(hanging.getPrompt("k")).thenAnswer(_ -> { + Thread.sleep(10_000); + return null; + }); + NacosPromptMiddleware middleware = new NacosPromptMiddleware(hanging, "k", Duration.ofMillis(300)); + ScriptedModel model = new ScriptedModel(_ -> ScriptedModel.text("照常回答")); + var subagents = YokeSubagents.programmatic(); + YokeSubagents.prepareWorkspace(workspace, subagents); + HarnessAgentFactory factory = new HarnessAgentFactory("Yoke", "内置提示词", 6, model, TestAgents.inMemoryStore(), + workspace, new YokeProperties.Compaction(30, 10), List.of(middleware), new Toolkit(), subagents); + + long start = System.nanoTime(); + String reply; + try (var agent = factory.create()) { + reply = agent.call("你好", RuntimeContext.builder().userId("u").sessionId("s-timeout").build()).blockOptional().orElseThrow().getTextContent(); + } + long elapsedMillis = (System.nanoTime() - start) / 1_000_000; + + assertThat(reply).isEqualTo("照常回答"); + assertThat(elapsedMillis).as("没有被 10 秒的无响应拖住").isLessThan(5_000); + assertThat(model.calls.getFirst().systemText()).contains("内置提示词"); + } + + @Test + void Prompt没有内容_getTemplate为null_也走兜底而不是抛异常() throws Exception { + AiService ai = mock(AiService.class); + when(ai.getPrompt("k")).thenReturn(new Prompt("k", "1.0.0", null)); + + assertThat(apply(new NacosPromptMiddleware(ai, "k", Duration.ofSeconds(2)), "内置提示词")).isEqualTo("内置提示词"); + } +} diff --git a/src/test/java/com/yoke/nacos/NacosRegistrationLifecycleTests.java b/src/test/java/com/yoke/nacos/NacosRegistrationLifecycleTests.java new file mode 100644 index 0000000..4b195c8 --- /dev/null +++ b/src/test/java/com/yoke/nacos/NacosRegistrationLifecycleTests.java @@ -0,0 +1,86 @@ +package com.yoke.nacos; + +import java.time.Duration; +import java.util.List; + +import com.alibaba.nacos.api.ai.AiService; +import com.alibaba.nacos.api.ai.model.a2a.AgentEndpoint; +import com.yoke.config.NacosConfiguration; +import com.yoke.config.YokeProperties; +import io.a2a.spec.AgentCapabilities; +import io.a2a.spec.AgentCard; +import io.agentscope.core.a2a.server.AgentScopeA2aServer; +import org.junit.jupiter.api.Test; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Configuration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * 注册与注销的生命周期接线(不需要 Docker):用 mock 的 AiService 观察容器的行为。 + * 关键是「关闭上下文时 Spring 会调用注销」,也就是 {@code @Bean(destroyMethod = "deregister")} 这条接线; + * 真实 Nacos 的测试里,客户端断开连接也会让服务端摘掉临时实例,分辨不出注销有没有被调用。 + */ +class NacosRegistrationLifecycleTests { + + @Configuration(proxyBeanMethods = false) + @EnableConfigurationProperties(YokeProperties.class) + static class Props { + } + + private static AgentCard card() { + return new AgentCard.Builder().name("lifecycle-agent").description("d").url("http://127.0.0.1:45679/a2a") + .version("1.0.0").protocolVersion("0.3.0").preferredTransport("JSONRPC") + .capabilities(new AgentCapabilities(false, false, false, List.of())) + .defaultInputModes(List.of("text")).defaultOutputModes(List.of("text")).skills(List.of()).build(); + } + + private ApplicationContextRunner runner(AiService ai, AgentScopeA2aServer server) { + return new ApplicationContextRunner() + .withAllowBeanDefinitionOverriding(true) + .withPropertyValues("yoke.workspace=/tmp/yoke-lifecycle", "yoke.redis.uri=redis://127.0.0.1:6379", + "yoke.nacos.a2a.enabled=true") + .withBean("nacosAiService", AiService.class, () -> ai) + .withBean(AgentScopeA2aServer.class, () -> server) + .withUserConfiguration(Props.class, NacosConfiguration.class); + } + + private static void publishReady(org.springframework.context.ConfigurableApplicationContext context) { + context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), new String[0], context, Duration.ZERO)); + } + + @Test + void 就绪后注册_关闭上下文时注销() throws Exception { + AiService ai = mock(AiService.class); + AgentScopeA2aServer server = mock(AgentScopeA2aServer.class); + when(server.getAgentCard()).thenReturn(card()); + + runner(ai, server).run(context -> { + verify(ai, never()).deregisterAgentEndpoint(any(String.class), any(AgentEndpoint.class)); + publishReady(context); + verify(ai).registerAgentEndpoint(eq("lifecycle-agent"), any(AgentEndpoint.class)); + }); + + // run 结束时上下文已关闭,Spring 应当调用了注销 + verify(ai).deregisterAgentEndpoint(eq("lifecycle-agent"), any(AgentEndpoint.class)); + } + + @Test + void 没有注册过就不会注销() throws Exception { + AiService ai = mock(AiService.class); + + runner(ai, mock(AgentScopeA2aServer.class)).run(context -> assertThat(context).hasNotFailed()); + + verify(ai, never()).deregisterAgentEndpoint(any(String.class), any(AgentEndpoint.class)); + } +} diff --git a/src/test/java/com/yoke/nacos/NacosSupportTests.java b/src/test/java/com/yoke/nacos/NacosSupportTests.java new file mode 100644 index 0000000..c4597e1 --- /dev/null +++ b/src/test/java/com/yoke/nacos/NacosSupportTests.java @@ -0,0 +1,56 @@ +package com.yoke.nacos; + +import com.yoke.config.YokeProperties; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** 探活失败路径:不需要 Docker,用一个不存在的端口。 */ +class NacosSupportTests { + + private static final String TEST_WORKSPACE = System.getProperty("java.io.tmpdir") + "/yoke-test-workspace"; + + private static YokeProperties.Nacos nacos(String addr) { + return new YokeProperties.Nacos(addr, null, "nacos-user-xyz", "S3cret-Pass-xyz", + new YokeProperties.Nacos.A2aSwitch(true, false), new YokeProperties.Nacos.PromptSwitch(false, "k", java.time.Duration.ofSeconds(2))); + } + + @Test + void 连不上Nacos时启动失败且报错信息是中文并不含凭证() { + assertThatThrownBy(() -> NacosSupport.connect(nacos("127.0.0.1:1"), TEST_WORKSPACE)) + .isInstanceOf(IllegalStateException.class) + .satisfies(e -> { + assertThat(e.getMessage()).contains("无法使用 Nacos 的 AI 通道").contains("127.0.0.1:1") + .contains("3.x").contains("9848"); + assertThat(e.getMessage()).doesNotContain("nacos-user-xyz").doesNotContain("S3cret-Pass-xyz"); + assertThat(e.getCause()).as("底层异常可能带着凭证,不作为 cause").isNull(); + }); + } + + @Test + void 配置对象的toString不含密码() { + String text = nacos("127.0.0.1:8848").toString(); + + assertThat(text).contains("password=***").doesNotContain("S3cret-Pass-xyz"); + } + + @Test + void 创建客户端之前就把目录指到工作区() { + System.clearProperty("JM.LOG.PATH"); + System.clearProperty("JM.SNAPSHOT.PATH"); + + assertThatThrownBy(() -> NacosSupport.connect(nacos("127.0.0.1:1"), TEST_WORKSPACE)).isInstanceOf(IllegalStateException.class); + + assertThat(System.getProperty("JM.LOG.PATH")).isNotNull().contains("yoke-test-workspace"); + assertThat(System.getProperty("JM.SNAPSHOT.PATH")).isNotNull().contains("yoke-test-workspace"); + } + + @Test + void 客户端的日志和快照目录被指到工作区而不是用户主目录() { + NacosSupport.redirectClientFiles(TEST_WORKSPACE); + + assertThat(System.getProperty("JM.LOG.PATH")).endsWith("nacos/logs").doesNotStartWith(System.getProperty("user.home") + "/logs"); + assertThat(System.getProperty("JM.SNAPSHOT.PATH")).endsWith("nacos/snapshot"); + } +} diff --git a/src/test/java/com/yoke/nacos/PromptMiddlewareSubagentTests.java b/src/test/java/com/yoke/nacos/PromptMiddlewareSubagentTests.java new file mode 100644 index 0000000..170c223 --- /dev/null +++ b/src/test/java/com/yoke/nacos/PromptMiddlewareSubagentTests.java @@ -0,0 +1,71 @@ +package com.yoke.nacos; + +import java.nio.file.Path; +import java.util.List; +import java.util.Map; + +import com.yoke.config.HarnessAgentFactory; +import com.yoke.config.YokeProperties; +import com.yoke.config.YokeSubagents; +import com.yoke.support.ScriptedModel; +import com.yoke.support.TestAgents; +import io.agentscope.core.agent.Agent; +import io.agentscope.core.agent.RuntimeContext; +import io.agentscope.core.middleware.MiddlewareBase; +import io.agentscope.core.tool.Toolkit; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import reactor.core.publisher.Mono; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * 探明一件事:挂在主 Agent 上的 {@code onSystemPrompt} 中间件(Prompt 热更新就是这种)会不会被子 Agent 继承, + * 也就是业务提示词会不会出现在子 Agent 的系统提示词里。用一个追加固定标记的同类中间件和脚本模型实测。 + */ +@Slf4j +class PromptMiddlewareSubagentTests { + + private static final String MARK = "【来自中间件的标记】"; + private static final String PARENT_PROMPT = "你是测试助手"; + + @Test + void 实测_主Agent的系统提示词中间件是否出现在子Agent的系统提示词里(@TempDir Path workspace) { + MiddlewareBase appendMark = new MiddlewareBase() { + @Override + public Mono onSystemPrompt(Agent agent, RuntimeContext ctx, String currentPrompt) { + return Mono.just(currentPrompt + "\n\n" + MARK); + } + }; + ScriptedModel model = new ScriptedModel(call -> { + if (call.systemText().startsWith("You are a memory")) { + return ScriptedModel.text("[]"); + } + if (!call.systemText().startsWith(PARENT_PROMPT)) { + return ScriptedModel.text("子 Agent 的回复"); + } + if (!call.hasToolResult() && !call.tools().isEmpty()) { + return ScriptedModel.toolUse("t1", "agent_spawn", Map.of("agent_id", "summarizer", "task", "做点事")); + } + return ScriptedModel.text("主 Agent 收尾"); + }); + var subagents = YokeSubagents.programmatic(); + YokeSubagents.prepareWorkspace(workspace, subagents); + HarnessAgentFactory factory = new HarnessAgentFactory("Yoke", PARENT_PROMPT, 6, model, TestAgents.inMemoryStore(), + workspace, new YokeProperties.Compaction(30, 10), List.of(appendMark), new Toolkit(), subagents); + + try (var agent = factory.create()) { + agent.call("hi", RuntimeContext.builder().userId("u").sessionId("s-sub").build()).block(); + } + + var parentCalls = model.calls.stream().filter(c -> c.systemText().startsWith(PARENT_PROMPT)).toList(); + var subCalls = model.calls.stream() + .filter(c -> !c.systemText().startsWith(PARENT_PROMPT) && !c.systemText().startsWith("You are a memory")).toList(); + assertThat(parentCalls).as("主 Agent 的系统提示词带标记").isNotEmpty().allMatch(c -> c.systemText().contains(MARK)); + assertThat(subCalls).as("子 Agent 确实被调用了").isNotEmpty(); + log.info("SUBAGENT-INHERITS-SYSTEM-PROMPT-MIDDLEWARE={}", subCalls.stream().allMatch(c -> c.systemText().contains(MARK))); + // 结论固化成断言,框架行为变化时这里会提醒 + assertThat(subCalls).allMatch(c -> c.systemText().contains(MARK)); + } +} diff --git a/src/test/java/com/yoke/support/A2aRaw.java b/src/test/java/com/yoke/support/A2aRaw.java new file mode 100644 index 0000000..022a17b --- /dev/null +++ b/src/test/java/com/yoke/support/A2aRaw.java @@ -0,0 +1,141 @@ +package com.yoke.support; + +import java.io.IOException; +import java.net.ServerSocket; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** 直接用 HTTP 对 A2A 端点发原始 JSON-RPC,用来测试协议层行为(认证、校验、错误码)。 */ +public final class A2aRaw { + + private static final ObjectMapper JSON = new ObjectMapper(); + + public record Response(int status, String body, String wwwAuthenticate) { + + public JsonNode json() { + try { + return JSON.readTree(body); + } catch (IOException e) { + throw new IllegalStateException("响应不是 JSON:" + body, e); + } + } + + /** 回复的文本(result.parts 里所有 text 拼起来)。 */ + public String text() { + StringBuilder out = new StringBuilder(); + for (JsonNode part : json().path("result").path("parts")) { + out.append(part.path("text").asText("")); + } + return out.toString(); + } + + public int errorCode() { + return json().path("error").path("code").asInt(0); + } + } + + private final String base; + private final String token; + + public A2aRaw(int port, String token) { + this.base = "http://127.0.0.1:" + port; + this.token = token; + } + + public static int freePort() { + try (ServerSocket socket = new ServerSocket(0)) { + return socket.getLocalPort(); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + /** 构造 message/send 请求体;contextId 和 metadata 为 null 时不带。 */ + public static String sendBody(String text, String contextId, Map metadata) { + Map message = new LinkedHashMap<>(); + message.put("kind", "message"); + message.put("role", "user"); + message.put("messageId", UUID.randomUUID().toString()); + message.put("parts", List.of(Map.of("kind", "text", "text", text))); + if (Objects.nonNull(contextId)) { + message.put("contextId", contextId); + } + if (Objects.nonNull(metadata)) { + message.put("metadata", metadata); + } + return rpc("message/send", Map.of("message", message)); + } + + public static String rpc(String method, Map params) { + try { + return JSON.writeValueAsString(Map.of("jsonrpc", "2.0", "id", "req-1", "method", method, "params", params)); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + public Response post(String body, String authorization) { + HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + "/a2a")) + .header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(body)); + if (Objects.nonNull(authorization)) { + request.header("Authorization", authorization); + } + return execute(request.build()); + } + + /** 带正确 token 发送。 */ + public Response send(String body) { + return post(body, Optional.ofNullable(token).map(value -> "Bearer " + value).orElse(null)); + } + + /** 向任意路径 POST 一个 JSON(不带认证),用来测试 Yoke 自己的 HTTP 接口。 */ + public Response postJson(String path, String body) { + return execute(HttpRequest.newBuilder(URI.create(base + path)).header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(body)).build()); + } + + /** 以 chunked(不声明 Content-Length)方式发送 POST /a2a,体是 {@code size} 个字节的空格。 */ + public Response postChunked(long size, String authorization) { + @SuppressWarnings("resource") // 请求发送时由 HttpClient 读取并关闭 + java.io.InputStream stream = new java.io.InputStream() { + private long left = size; + + @Override + public int read() { + return left-- > 0 ? ' ' : -1; + } + }; + HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + "/a2a")) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofInputStream(() -> stream)); + if (Objects.nonNull(authorization)) { + request.header("Authorization", authorization); + } + return execute(request.build()); + } + + public Response get(String path) { + return execute(HttpRequest.newBuilder(URI.create(base + path)).GET().build()); + } + + private Response execute(HttpRequest request) { + try (HttpClient client = HttpClient.newHttpClient()) { + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + return new Response(response.statusCode(), response.body(), + response.headers().firstValue("WWW-Authenticate").orElse(null)); + } catch (IOException | InterruptedException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/src/test/java/com/yoke/support/NacosCompose.java b/src/test/java/com/yoke/support/NacosCompose.java new file mode 100644 index 0000000..4ca0103 --- /dev/null +++ b/src/test/java/com/yoke/support/NacosCompose.java @@ -0,0 +1,115 @@ +package com.yoke.support; + +import java.io.File; +import java.io.IOException; +import java.net.ServerSocket; +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Objects; + +import org.testcontainers.containers.ComposeContainer; +import org.testcontainers.containers.wait.strategy.Wait; + +/** + * 读取根目录的 docker-compose.yml 拉起 Nacos,整个测试 JVM 共用同一个实例。 + * + *

Nacos 客户端的 gRPC 端口固定等于主端口 + 1000,所以不能让 Testcontainers 随机映射: + * 这里挑一对都空闲的宿主机端口(P 和 P+1000)通过环境变量交给 compose。 + * 启动慢(要等控制台就绪),等待靠 compose 里的健康检查,最长 3 分钟,超时的报错里带上端口和排查提示。 + */ +public final class NacosCompose { + + private static final String SERVICE = "nacos"; + + private static String serverAddr; + + private NacosCompose() { + } + + /** Nacos 的 {@code host:port}(主端口),形如 {@code 127.0.0.1:54321}。 */ + public static synchronized String serverAddr() { + if (Objects.isNull(serverAddr)) { + start(); + } + return serverAddr; + } + + /** 模拟运营在控制台发布一个新版本的 Prompt(管理接口,compose 里关了本地鉴权)。 */ + public static void publishPrompt(String key, String version, String template) { + String form = "promptKey=" + enc(key) + "&version=" + enc(version) + "&commitMsg=test&template=" + enc(template); + HttpRequest request = HttpRequest.newBuilder(URI.create("http://" + serverAddr() + "/nacos/v3/admin/ai/prompt")) + .header("Content-Type", "application/x-www-form-urlencoded") + .POST(HttpRequest.BodyPublishers.ofString(form)).timeout(Duration.ofSeconds(10)).build(); + try (HttpClient client = HttpClient.newHttpClient()) { + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + if (!response.body().contains("\"code\":0")) { + throw new IllegalStateException("发布 Prompt 失败:" + response.body()); + } + } catch (IOException | InterruptedException e) { + throw new IllegalStateException("发布 Prompt 失败", e); + } + } + + /** 对 Nacos 主端口发一个 GET,返回响应体(管理接口,compose 里关了本地鉴权)。 */ + public static String httpGet(String path) { + HttpRequest request = HttpRequest.newBuilder(URI.create("http://" + serverAddr() + path)) + .GET().timeout(Duration.ofSeconds(10)).build(); + try (HttpClient client = HttpClient.newHttpClient()) { + return client.send(request, HttpResponse.BodyHandlers.ofString()).body(); + } catch (IOException | InterruptedException e) { + throw new IllegalStateException("请求 Nacos 失败:" + path, e); + } + } + + private static String enc(String value) { + return URLEncoder.encode(value, StandardCharsets.UTF_8); + } + + @SuppressWarnings("resource") // 容器要活到 JVM 退出,由下面注册的关闭钩子停止,不能在方法里用 try-with-resources 关掉 + private static void start() { + int[] ports = freePortPair(); + int console = freePort(); + ComposeContainer compose = new ComposeContainer(new File("docker-compose.yml")) + .withEnv("NACOS_PORT", String.valueOf(ports[0])) + .withEnv("NACOS_GRPC_PORT", String.valueOf(ports[1])) + .withEnv("NACOS_CONSOLE_PORT", String.valueOf(console)) + .withServices(SERVICE) + .withStartupTimeout(Duration.ofMinutes(3)) + .withExposedService(SERVICE, 8848, Wait.forHealthcheck()); + try { + compose.start(); + } catch (RuntimeException e) { + throw new IllegalStateException("Nacos 容器没能在 3 分钟内就绪(主端口 " + ports[0] + ",gRPC 端口 " + ports[1] + + ")。检查 Docker 是否能拉取 docker-compose.yml 里的 nacos 镜像、这两个端口是否被占用", e); + } + Runtime.getRuntime().addShutdownHook(new Thread(compose::stop)); + serverAddr = "127.0.0.1:" + ports[0]; + } + + /** 找一个主端口 P,使 P 和 P+1000 都空闲。P 在 20000 到 60000 之间随机挑,保证 P+1000 不越界。 */ + private static int[] freePortPair() { + java.util.concurrent.ThreadLocalRandom random = java.util.concurrent.ThreadLocalRandom.current(); + for (int attempt = 0; attempt < 200; attempt++) { + int main = random.nextInt(20000, 60000); + try (ServerSocket first = new ServerSocket(main); ServerSocket grpc = new ServerSocket(main + 1000)) { + return new int[] {first.getLocalPort(), grpc.getLocalPort()}; + } catch (IOException ignored) { + // 换一个再试 + } + } + throw new IllegalStateException("找不到一对相差 1000 的空闲端口"); + } + + private static int freePort() { + try (ServerSocket socket = new ServerSocket(0)) { + return socket.getLocalPort(); + } catch (IOException e) { + throw new IllegalStateException("找不到空闲端口", e); + } + } +} diff --git a/src/test/java/com/yoke/support/NacosIntegrationTest.java b/src/test/java/com/yoke/support/NacosIntegrationTest.java new file mode 100644 index 0000000..ca2144a --- /dev/null +++ b/src/test/java/com/yoke/support/NacosIntegrationTest.java @@ -0,0 +1,20 @@ +package com.yoke.support; + +import org.junit.jupiter.api.extension.ExtendWith; + +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; + +/** + * 需要真实 Nacos 的测试的基类:Redis 和 Nacos 的地址都注入进来。Docker 不可用时整个类被跳过(CI 里失败)。 + * 子类按需自己打开 {@code yoke.nacos.*} 的开关。 + */ +@ExtendWith(RequiresDocker.class) +public abstract class NacosIntegrationTest { + + @DynamicPropertySource + static void infraProperties(DynamicPropertyRegistry registry) { + registry.add("yoke.redis.uri", RedisCompose::uri); + registry.add("yoke.nacos.server-addr", NacosCompose::serverAddr); + } +} diff --git a/src/test/java/com/yoke/support/RedisCompose.java b/src/test/java/com/yoke/support/RedisCompose.java index c3e0534..2946af1 100644 --- a/src/test/java/com/yoke/support/RedisCompose.java +++ b/src/test/java/com/yoke/support/RedisCompose.java @@ -23,7 +23,6 @@ public final class RedisCompose { private static final String SERVICE = "redis"; private static final int REDIS_PORT = 6379; - private static ComposeContainer compose; private static String uri; private RedisCompose() { @@ -52,11 +51,14 @@ public static Set keys(String pattern) { } } + @SuppressWarnings("resource") // 容器要活到 JVM 退出,由下面注册的关闭钩子停止,不能在方法里用 try-with-resources 关掉 private static void start() { int hostPort = freePort(); // compose 文件里宿主机端口来自 REDIS_PORT,这里换成空闲端口,避免和本机正在跑的 Redis 冲突 - compose = new ComposeContainer(new File("docker-compose.yml")) + ComposeContainer compose = new ComposeContainer(new File("docker-compose.yml")) .withEnv("REDIS_PORT", String.valueOf(hostPort)) + // compose 文件里还有 Nacos 等服务,这里只需要 Redis,别把别的也拉起来 + .withServices(SERVICE) .withExposedService(SERVICE, REDIS_PORT, Wait.forHealthcheck()); compose.start(); Runtime.getRuntime().addShutdownHook(new Thread(compose::stop)); diff --git a/src/test/java/com/yoke/support/TestAgents.java b/src/test/java/com/yoke/support/TestAgents.java index 835fe8b..c185119 100644 --- a/src/test/java/com/yoke/support/TestAgents.java +++ b/src/test/java/com/yoke/support/TestAgents.java @@ -2,6 +2,10 @@ import java.nio.file.Path; import java.util.List; +import java.util.concurrent.Phaser; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; import com.yoke.config.HarnessAgentFactory; import com.yoke.config.YokeProperties; @@ -10,8 +14,14 @@ import io.agentscope.core.state.InMemoryAgentStateStore; import io.agentscope.core.tool.Toolkit; import io.agentscope.harness.agent.DistributedStore; +import io.agentscope.harness.agent.HarnessAgent; import io.agentscope.harness.agent.filesystem.remote.store.InMemoryStore; +import static org.mockito.AdditionalAnswers.delegatesTo; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + /** 不依赖 Redis 的 Agent 装配:会话状态放内存,用来测试工具和子 Agent 的行为。 */ public final class TestAgents { @@ -32,4 +42,43 @@ public static HarnessAgentFactory factory(Model model, Path workspace, Toolkit t return new HarnessAgentFactory("Yoke", "你是测试助手", 6, model, inMemoryStore(), workspace, new YokeProperties.Compaction(30, 10), List.of(), toolkitTemplate, subagents); } + + /** + * 跟踪工厂创建出的全部 {@link HarnessAgent} 是否都已执行完 {@code close()}。 + * + *

{@code ChatController} 和 {@code YokeAgentRunner} 都使用 {@code eager=false}:下游拿到完成或取消信号时, + * {@code HarnessAgent.close()} 可能还在后台线程排空会话镜像与记忆文件写入。使用 {@code @TempDir} 的测试在 + * {@code @AfterEach} 中调用 {@link #awaitAllClosed()},避免 JUnit 删除临时目录时与后台写入撞车。 + */ + public static final class CloseTracker { + + private final Phaser openAgents = new Phaser(1); + + public HarnessAgentFactory wrap(HarnessAgentFactory real) { + HarnessAgentFactory proxy = mock(HarnessAgentFactory.class); + when(proxy.create()).thenAnswer(_ -> { + HarnessAgent agent = real.create(); + openAgents.register(); + HarnessAgent tracked = mock(HarnessAgent.class, delegatesTo(agent)); + AtomicBoolean closed = new AtomicBoolean(); + doAnswer(_ -> { + try { + agent.close(); + } finally { + if (closed.compareAndSet(false, true)) { + openAgents.arriveAndDeregister(); + } + } + return null; + }).when(tracked).close(); + return tracked; + }); + return proxy; + } + + public void awaitAllClosed() throws InterruptedException, TimeoutException { + int phase = openAgents.arrive(); + openAgents.awaitAdvanceInterruptibly(phase, 15, TimeUnit.SECONDS); + } + } } diff --git a/src/test/java/com/yoke/tool/ToolConversationTests.java b/src/test/java/com/yoke/tool/ToolConversationTests.java index 5e629b3..a9fc2e9 100644 --- a/src/test/java/com/yoke/tool/ToolConversationTests.java +++ b/src/test/java/com/yoke/tool/ToolConversationTests.java @@ -17,6 +17,7 @@ import com.yoke.config.YokeProperties; import com.yoke.mcp.McpConnections; import io.agentscope.core.tool.Toolkit; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -51,8 +52,15 @@ private static List> stream(ChatController controller, Strin return AguiTestSupport.run(controller, threadId, text); } - private static ChatController controller(ScriptedModel model, Path workspace, Toolkit toolkit) { - return AguiTestSupport.controller(TestAgents.factory(model, workspace, toolkit)); + private final TestAgents.CloseTracker tracker = new TestAgents.CloseTracker(); + + @AfterEach + void awaitAgentsClosed() throws Exception { + tracker.awaitAllClosed(); + } + + private ChatController controller(ScriptedModel model, Path workspace, Toolkit toolkit) { + return AguiTestSupport.controller(tracker.wrap(TestAgents.factory(model, workspace, toolkit))); } @Test