JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat: e2a refactor
douran4b034ce07431
diff --git a/docs/en/E2A-protocol.md b/docs/en/E2A-protocol.mdnew file mode 100644index 0000000000..bf7bf4e909--- /dev/null+++ b/docs/en/E2A-protocol.md@@ -0,0 +1,389 @@+# E2A (Everything-to-Agent) Protocol++> **Implementation**: `jiuwenclaw/e2a/` (`models.py`, `adapters.py`, `constants.py`, `__init__.py`). **Version**: `E2A_PROTOCOL_VERSION` (default `1.0`). **On conflict**: treat the dataclass fields in `models.py` as the source of truth and update this document accordingly. Requests: `E2AEnvelope`; responses: `E2AResponse`.+> **中文版**:[../zh/E2A-protocol.md](../zh/E2A-protocol.md)++---++## 0. Document layout and single source of truth++| Location | Role |+|----------|------|+| **docs/zh/E2A-protocol.md** | Same specification in Chinese |+| **docs/en/E2A-protocol.md** (this file) | Normative description, pitfalls, examples (English) |+| `jiuwenclaw/e2a/models.py` | Request `E2AEnvelope`, response `E2AResponse`, nested types; `from_dict` / `to_dict` |+| `jiuwenclaw/e2a/constants.py` | **`E2A_SOURCE_PROTOCOL_*`**, **`E2A_RESPONSE_KINDS`**, **`E2A_RESPONSE_STATUS_*`**, ACP method names and SessionUpdate strings (runtime: use tuples in code) |+| `jiuwenclaw/e2a/adapters.py` | ACP / A2A → E2A; E2A → ACP JSON-RPC; **`E2AResponse` → ACP / A2A projections** (§8) |+| `jiuwenclaw/e2a/__init__.py` | Public exports |+| `jiuwenclaw/e2a/ACP-reference.md` / `A2A-reference.md` | External protocol notes; **not** normative for E2A |++---++## 1. Scope and boundaries++- Payloads sent to AgentServer **after Gateway normalization** are expressed as E2A. Raw channel fields are **mapped at the Gateway edge** into normalized fields (`user_id`, `message_id`, `params`, etc.); the full channel JSON is **not** required to be the E2A primary path.+- **`channel_context`**: optional; transitional or residual keys that do not fit normalized fields; `from_dict` may migrate legacy `metadata` for compatibility.+- E2A **does not** specify the transport (WebSocket, HTTP, etc.).++---++## 2. Pitfall: two meanings of `method` (required reading)++The same field **`method`** means different things by origin. It is **not** two different fields; do not confuse it with `request_id` / `message_id`.++| Origin | Typical `method` values | Notes |+|--------|-------------------------|-------|+| **Gateway → AgentServer** | `chat.send`, `history.get`, `chat.interrupt`, … | In-project RPC names; **not** enumerated in `constants.ACP_CLIENT_TO_AGENT_METHODS` |+| **ACP via `envelope_from_acp_jsonrpc`** | `session/prompt`, `initialize`, … | Same as JSON-RPC `method`; full list: **`constants.ACP_CLIENT_TO_AGENT_METHODS`** |+| **Internal special** | `null` | e.g. heartbeat with no RPC-style operation name |++**Export to ACP**: `envelope_to_acp_jsonrpc_call` only uses `merge_params_to_acp_prompt` to fill `prompt` from **`params`** when `method == "session/prompt"`. If `method` is `chat.send`, you must **map explicitly** in an adapter to ACP’s `session/prompt` and `params`; otherwise the JSON-RPC is invalid for a pure ACP peer.++---++## 3. Relationship to ACP and A2A (summary)++| Aspect | ACP | A2A | E2A (internal) |+|--------|-----|-----|----------------|+| Role | JSON-RPC session | Task / Message / Card | Unified envelope; externals **adapt in** |+| `method` | JSON-RPC method | Abstract op (binding maps) | See **§2** |+| Extension | `_meta` | `metadata` | Gateway uses normalized fields; `a2a_metadata` / `acp_meta` for interop only |++---++## 4. `E2AEnvelope` field reference++### 4.1 Core and correlation++| Field | Type | Description |+|-------|------|-------------|+| `protocol_version` | string | Default `1.0` |+| `request_id` | string / null | Primary Gateway↔AgentServer id (stream chunks align on this) |+| `jsonrpc_id` | string / number / null | JSON-RPC `id` when ingested from ACP |+| `correlation_id` | string / null | Tracing; distinct from `request_id` |+| `task_id` / `context_id` | string / null | A2A alignment |+| `session_id` | string / null | Session |+| `message_id` | string / null | Platform or A2A message id; do not conflate with `request_id` |+| `is_stream` | boolean | Streamed response or not |++### 4.2 `provenance` (`E2AProvenance`)++| Field | Description |+|-------|-------------|+| `source_protocol` | `e2a` / `acp` / `a2a` (see `E2A_SOURCE_PROTOCOL_*`) |+| `converter` / `converted_at` / `details` | Converter id, time, hints (e.g. `jsonrpc_method`) |++Hand-built defaults use `source_protocol` = `e2a`. Legacy `binding` migrates to `provenance.details.migrated_from_binding`.++### 4.3 Time, identity, ingress++| Field | Description |+|-------|-------------|+| `timestamp` | **Normative**: RFC 3339 UTC string; `from_dict` may accept float/int epoch seconds |+| `identity_origin` | `system` / `user` / `agent` / `service` |+| `channel` | Ingress name; **use `channel` only**. `from_dict` may read `channel_id` |+| `user_id` / `source_agent_id` | User or upstream agent |++`timestamp` (business time) ≠ `provenance.converted_at` (E2A conversion time).++### 4.4 `method`, `params`, bridging++| Field | Description |+|-------|-------------|+| `method` | See **§2**; `from_dict` may read `req_method` |+| **`params`** | **Single business-parameter dict** (aligned with JSON-RPC `params`): options, user text, multimodal blocks, attachments **all** go here; **do not** use a top-level `payload` (see table below) |+| `ext_method` | Real name when `method == "ext"` |+| `session_update_kind` | For ACP `session/update` bridge; values match `constants.ACP_SESSION_UPDATE_KINDS` |+| `expected_output_modes` | A2A `acceptedOutputModes` |++**Common `params` keys** (extend as needed; names below cooperate with ACP bridging):++| Key | Purpose |+|-----|---------|+| `prompt` | Use as-is when already an ACP ContentBlock array (`merge_params_to_acp_prompt` does not overwrite) |+| `content_blocks` | JSON array isomorphic to ACP `Vec<ContentBlock>`; when `method==session/prompt` and no `prompt`, can map to `prompt` |+| `text` / `content` / `query` | Plain user text; if no `prompt`/`content_blocks`, first non-empty string becomes a single `text` block |+| `files` / `attachments` | Attachment lists; elements follow **`E2AFileRef`** (`uri` required) |+| Others | e.g. `mode`, `page_idx`, heartbeat text—extend per Gateway RPC |++### 4.5 `auth` and extension slots++| Field | Description |+|-------|-------------|+| `auth` | `E2AAuth`: credential references, etc. |+| `channel_context` | Optional overflow / legacy `metadata`; see **§1** |+| `a2a_metadata` | **A2A interop only** (adapter arg `metadata` maps here—not Gateway `metadata`) |+| `acp_meta` | Merged into `params._meta` by `merge_params_to_acp_prompt` (§7) |++---++## 5. Nested types (summary)++- **`E2AFileRef`**: recommended attachment element (`uri` required; `name`, `mime_type`, `size`, `_meta` optional); usually in **`params.files`** or **`params.attachments`**.+- **`E2AAuth`**: `method_id`, `bearer_token`, `api_key_ref`, `credential_ref`, `extra_headers`, `_meta`++---++## 6. ACP strings in `constants.py` (bridge reference)++For ACP bridging and doc cross-check only; **at runtime** use tuples in `jiuwenclaw.e2a.constants`:++- **`ACP_CLIENT_TO_AGENT_METHODS`**: client → Agent JSON-RPC method names+- **`ACP_AGENT_TO_CLIENT_METHODS`**, **`ACP_NOTIFICATION_NAMES`**: downstream / notifications+- **`ACP_SESSION_UPDATE_KINDS`**: values for `session_update_kind`+- **`E2A_RESPONSE_KINDS`**, **`E2A_RESPONSE_STATUS_*`**, **`E2A_A2A_STREAM_BRANCHES`**: response `response_kind` / `status` / `a2a.stream_event.branch` (see **§12**)++**Gateway RPC** names (`chat.send`, etc.) are project-defined and **not** in those tuples.++---++## 7. `merge_params_to_acp_prompt`++Python: `jiuwenclaw.e2a.merge_params_to_acp_prompt(envelope)`.++If and only if **`method == "session/prompt"`**:++1. If `params` already has `prompt`, do not overwrite.+2. Else if `params.content_blocks` is a non-empty array, use as `prompt`.+3. Else if any of `params.text`, `params.content`, `params.query` is a non-empty string, build `{ "type": "text", "text": "..." }` as `prompt`.+4. If the envelope has `session_id` and `params` lacks `session_id`, set it.+5. Merge `envelope.acp_meta` into `params._meta`.++For any other `method`, return a shallow copy of `params`.++---++## 8. Adapters (`adapters.py`)++| Function | Role |+|----------|------|+| `envelope_from_acp_jsonrpc` | ACP JSON-RPC → E2A; `provenance.source_protocol=acp`; `method` is ACP method |+| `envelope_from_a2a_send_message` | A2A SendMessage semantics → E2A; adapter **`metadata`** → **`a2a_metadata`** (A2A-only, not Gateway `metadata`) |+| `envelope_to_acp_jsonrpc_call` | E2A → JSON-RPC call shape; does not change `provenance` |+| `e2a_response_to_acp_jsonrpc_response` | **`E2AResponse`** → one JSON-RPC **response** object (`result` or `error`); returns `None` if not applicable |+| `e2a_response_to_a2a_stream_payload` | **`E2AResponse`** (`a2a.stream_event`) → A2A **`StreamResponse`**-shaped JSON (exactly one branch); returns `None` if not applicable |++---++## 9. Serialization and compatibility keys++- `E2AEnvelope.to_dict()` / `from_dict(data)`+- **Read compatibility**: `channel_id`→`channel`, `req_method`→`method`, `metadata`→`channel_context` (only if `channel_context` empty), `binding`→`provenance` (above)+- **Optional**: if top-level legacy **`payload`** (object) exists, keys are **merged into `params`** without overwriting existing `params` keys; **new protocol must not** send top-level `payload`.++---++## 10. Mapping from `AgentRequest`++| AgentRequest | E2AEnvelope |+|--------------|-------------|+| `request_id` | `request_id` |+| `channel_id` | `channel` |+| `session_id` | `session_id` |+| `req_method` | `method` |+| `params` | `params` |+| `is_stream` | `is_stream` |+| `timestamp` (float) | `timestamp` (string, auto-normalized) |+| `metadata` | Target: map to normalized fields; compat: `from_dict`→`channel_context` |++---++## 11. Examples (JSON shapes)++### 11.1 After Gateway normalization → AgentServer (chat, streaming)++```json+{+ "protocol_version": "1.0",+ "request_id": "req_abc_01",+ "session_id": "sess_xyz",+ "channel": "web",+ "method": "chat.send",+ "is_stream": true,+ "timestamp": "2026-03-28T12:00:00+00:00",+ "identity_origin": "user",+ "user_id": "u_001",+ "params": {+ "content": "Hello",+ "mode": "plan",+ "query": "Hello"+ },+ "provenance": {+ "source_protocol": "e2a"+ }+}+```++`channel_context` may be omitted (or `{}` when serialized empty).++### 11.2 Legacy `AgentRequest` shape (readable by `from_dict`)++```json+{+ "request_id": "req_legacy_1",+ "channel_id": "feishu",+ "session_id": "sess_feishu_1",+ "req_method": "chat.send",+ "is_stream": true,+ "timestamp": 1774524781.15,+ "params": {+ "content": "List desktop files",+ "mode": "plan",+ "query": "List desktop files"+ },+ "metadata": {+ "feishu_open_id": "ou_xxx",+ "message_id": "om_xxx"+ }+}+```++After parse: `channel`=`feishu`, `method`=`chat.send`, `timestamp` normalized to RFC 3339; if not mapped elsewhere, `metadata` lands in `channel_context` (migration). **Target state**: Gateway should map `feishu_open_id` into `user_id` / `message_id`, etc., and minimize `channel_context`.++### 11.3 ACP ingress (illustrative; built by `envelope_from_acp_jsonrpc`)++- `method` = `"session/prompt"`+- `jsonrpc_id` = `42`+- `params` = `{ "session_id": "s1", "prompt": [...] }`+- `provenance.source_protocol` = `"acp"`, `details` includes `jsonrpc_method`, etc.++### 11.4 Exported ACP JSON-RPC (`envelope_to_acp_jsonrpc_call` shape)++```json+{+ "jsonrpc": "2.0",+ "id": 42,+ "method": "session/prompt",+ "params": {+ "session_id": "s1",+ "prompt": [{"type": "text", "text": "hi"}]+ }+}+```++`merge_params_to_acp_prompt` only fills `prompt` from `content_blocks` or `text`/`content`/`query` when envelope `method == "session/prompt"` and `params` has no `prompt` yet.++### 11.5 `session/prompt` + multimodal (all in `params`)++```json+{+ "method": "session/prompt",+ "session_id": "s1",+ "jsonrpc_id": 1,+ "params": {+ "content_blocks": [+ {"type": "text", "text": "Describe this image"},+ {"type": "image", "mime_type": "image/png", "data": "<base64 omitted>"}+ ]+ }+}+```++After `merge_params_to_acp_prompt`, `params` gains a `prompt` equivalent to `content_blocks` if there was no `prompt` before.++---++## 12. E2A response protocol (`E2AResponse`)++Every outbound record from Agent → Gateway → client (including each streaming frame) is expressed as **`E2AResponse`**, symmetric with **`E2AEnvelope`** (`snake_case`, RFC 3339 `timestamp`, reuse **`E2AProvenance`**).++### 12.1 Three layers++| Layer | Name | Role |+|-------|------|------|+| **L1** | Response envelope | Correlation ids, ordering, stream end, status, provenance |+| **L2** | Discriminated payload | **`response_kind`** + **`body`** (shape constrained by kind) |+| **L3** | `projections` (optional) | Under `acp` / `a2a`, pre-built wire JSON for interop—**auxiliary only**; consumers **must not** treat L3 as the sole source of truth |++### 12.2 `is_final` and `status`++- **`is_final`**: `true` means **no further** `E2AResponse` records for the same **`request_id`**. This is **not** “success”; a failed final frame may still have `is_final: true`.+- **`status`**: one of **`constants.E2A_RESPONSE_STATUS_*`** (`succeeded` / `failed` / `in_progress`). When **`status == failed`**, **`response_kind`** should be **`e2a.error`** (see **§12.6** if `acp.jsonrpc_error` is also used).++### 12.3 Invariants++- For one **`request_id`**, **`sequence`** starts at **0** and strictly increases (0, 1, 2, …).+- Normal completion: **exactly one** record has **`is_final: true`**.+- Abnormal cases (disconnect, crash): an `is_final` frame may be missing; use timeouts and connection state—this spec does not require a synthetic final frame.++### 12.4 L1: envelope fields++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| `protocol_version` | string | yes | Same as request; default `1.0` |+| `response_id` | string | yes | Unique id for this record (UUID recommended) |+| `request_id` | string | yes | Echo request; stream chunk alignment |+| `sequence` | integer | yes | Per-`request_id`, starting at 0 |+| `is_final` | boolean | yes | `true` on the last frame |+| `status` | string | yes | `succeeded` / `failed` / `in_progress` |+| `response_kind` | string | yes | See **§12.5**; runtime: **`constants.E2A_RESPONSE_KINDS`** |+| `timestamp` | string | yes | RFC 3339 UTC; when this record was produced |+| `provenance` | object | yes | **`E2AProvenance`** (same shape as requests) |+| `body` | object | yes | L2 payload |+| `jsonrpc_id` | string / number / null | no | Echo ACP JSON-RPC `id` |+| `correlation_id` | string | no | Tracing |+| `task_id` / `context_id` / `session_id` / `message_id` | string | no | Same meaning as on the request envelope |+| `is_stream` | boolean | no | Whether the originating request was streaming |+| `identity_origin` | string | no | Often **`agent`** for agent-originated responses |+| `channel` / `user_id` / `source_agent_id` | same as request | no | Echo |+| `method` | string / null | no | Echo request `method` (including heartbeat `null`) |+| `metadata` | object | no | **Channel/business** key-value map; aligns with legacy **`AgentResponse.metadata`**; on **protocol conversion failure**, may hold fallback data. **AgentServer→Gateway WebSocket** uses **`constants.E2A_WIRE_LEGACY_AGENT_RESPONSE_KEY`** / **`E2A_WIRE_LEGACY_AGENT_CHUNK_KEY`** for full legacy JSON blobs; use channel-prefixed keys for app metadata |+| `projections` | object | no | L3: optional `acp`, `a2a` keys |+| `channel_context` / `a2a_metadata` / `acp_meta` | object | no | Same spillover slots as request; **distinct from `metadata`**—`a2a_metadata` / `acp_meta` are ACP/A2A interop only; `metadata` is general business and fallback |++### 12.5 L2: `response_kind` and `body`++Runtime list: **`constants.E2A_RESPONSE_KINDS`**; **`body`** is a **dict**. Normative summary:++| `response_kind` | `body` highlights |+|-----------------|-------------------|+| `e2a.complete` | **`result`**: business outcome (mirror the “single `params` dict” philosophy for requests) |+| `e2a.chunk` | **`delta_kind`**: `text` / `reasoning` / `tool` / `custom`; **`delta`**: string or structured object; optional **`mime_type`** |+| `e2a.error` | **`code`**, **`message`**, **`details`**; optional **`external`**: `{ "protocol": "acp"|"a2a", "type": string, "payload": object }` |+| `acp.session_update` | ACP `session/update` notification payload; **`sessionUpdate`** aligns with **`ACP_SESSION_UPDATE_KINDS`** |+| `acp.prompt_result` | JSON-RPC **`result`** for `session/prompt` (e.g. `stop_reason`, optional `usage`, `_meta`) |+| `acp.jsonrpc_error` | JSON-RPC **`error`** semantics: `code`, `message`, optional `data` (prefer **`e2a.error`** as the canonical failure kind; use this for ACP-edge projection if needed) |+| `a2a.task` | A2A **`Task`** JSON (**snake_case** keys aligned with `spec/a2a.proto`) |+| `a2a.message` | A2A **`Message`** JSON (same) |+| `a2a.stream_event` | **`branch`**: `task` / `message` / `status_update` / `artifact_update` (**`E2A_A2A_STREAM_BRANCHES`**); **`payload`**: branch object |+| `ext` | **`ext_method`** + **`params`** (symmetric to request `ext`) |++**Recommendation**: internally prefer **`e2a.complete`** / **`e2a.chunk`** / **`e2a.error`**; build **`acp.*`** / **`a2a.*`** or **`projections`** at the edge.++### 12.6 Mapping to ACP / A2A (summary)++- **ACP**: JSON-RPC response from **`jsonrpc_id`** + **`acp.prompt_result`** (`result`) or **`e2a.error`** / **`acp.jsonrpc_error`** (`error`); **`acp.session_update`** maps to **`session/update`** **`params`**. See **`e2a_response_to_acp_jsonrpc_response`** (§8).+- **A2A**: **`a2a.stream_event`** matches **`StreamResponse`** branches; **`e2a_response_to_a2a_stream_payload`** emits one event. **`a2a.task`** / **`a2a.message`** match SendMessage outcomes.++### 12.7 Logging (e.g. `E:\logs`)++- One line per **`E2AResponse`** JSON; sort/replay by **`sequence`**.+- Minimum keys: **`request_id`**, **`response_id`**, **`sequence`**, **`is_final`**, **`response_kind`**, **`timestamp`**.+- Do not log secrets (`bearer_token`, sensitive model output). Large **`body`** may later use **`body_ref`** (not defined in this version).++### 12.8 Example: two chunks + final++```json+{"protocol_version":"1.0","response_id":"r1","request_id":"req_1","sequence":0,"is_final":false,"status":"in_progress","response_kind":"e2a.chunk","timestamp":"2026-03-29T12:00:00+00:00","provenance":{"source_protocol":"e2a"},"body":{"delta_kind":"text","delta":"Hello"}}+```++```json+{"protocol_version":"1.0","response_id":"r2","request_id":"req_1","sequence":1,"is_final":false,"status":"in_progress","response_kind":"e2a.chunk","timestamp":"2026-03-29T12:00:01+00:00","provenance":{"source_protocol":"e2a"},"body":{"delta_kind":"text","delta":" world"}}+```++```json+{"protocol_version":"1.0","response_id":"r3","request_id":"req_1","sequence":2,"is_final":true,"status":"succeeded","response_kind":"e2a.complete","timestamp":"2026-03-29T12:00:02+00:00","provenance":{"source_protocol":"e2a"},"body":{"result":{"content":"Hello world"}}}+```++Cross-reference: request log normalization in **`E2A-AgentRequest-log-migration.md`**; response logging can adopt the same single-line JSON convention later.++---++## 13. Security notes++- Prefer `credential_ref` / `api_key_ref` and ticket exchange at the Gateway; do not log full `bearer_token`.+- Use TLS and least privilege across trust boundaries.++---++*Maintained in sync with `jiuwenclaw/e2a/models.py` (`E2AEnvelope`, `E2AResponse`).*diff --git a/docs/en/README.md b/docs/en/README.mdindex fa62ac3aa4..77b4fd4ad5 100644--- a/docs/en/README.md+++ b/docs/en/README.md@@ -3,6 +3,7 @@This section collects common usage notes and feature documentation for JiuwenClaw.- Install and run from scratch: [Quick start](Quickstart.md)+- Unified Gateway↔Agent request envelope (E2A): [E2A protocol](E2A-protocol.md)([中文版](../zh/E2A-protocol.md))- Model and system configuration: [Configuration](Configuration.md)- Topic guides: use the table of contents or start from:- [Channels](Channels.md)diff --git a/docs/en/SUMMARY.md b/docs/en/SUMMARY.mdindex c48b0cab15..b1be135386 100644--- a/docs/en/SUMMARY.md+++ b/docs/en/SUMMARY.md@@ -1,6 +1,7 @@# Summary- [Quick start](Quickstart.md)+- [E2A protocol (Gateway↔Agent)](E2A-protocol.md)- [Configuration](Configuration.md)- [User guide](README.md)- [Channels](Channels.md)diff --git a/docs/zh/E2A-protocol.md b/docs/zh/E2A-protocol.mdnew file mode 100644index 0000000000..528b0ea71f--- /dev/null+++ b/docs/zh/E2A-protocol.md@@ -0,0 +1,389 @@+# E2A(Everything-to-Agent)协议说明++> **实现**:`jiuwenclaw/e2a/`(`models.py`、`adapters.py`、`constants.py`、`__init__.py`)。**版本**:`E2A_PROTOCOL_VERSION`(默认 `1.0`)。**冲突时**:以 `models.py` 中 dataclass 字段为最终实现源,并回头修正本文。请求:`E2AEnvelope`;响应:`E2AResponse`。+> **English**:[../en/E2A-protocol.md](../en/E2A-protocol.md)++---++## 0. 文档位置与单一真源++| 位置 | 角色 |+|------|------|+| **docs/zh/E2A-protocol.md**(本文,中文) | 规范说明、易混点、示例 |+| **docs/en/E2A-protocol.md** | 同上,英文版 |+| `jiuwenclaw/e2a/models.py` | 请求 `E2AEnvelope`、响应 `E2AResponse` 与子结构;`from_dict` / `to_dict` |+| `jiuwenclaw/e2a/constants.py` | **`E2A_SOURCE_PROTOCOL_*`**、**`E2A_RESPONSE_KINDS`**、**`E2A_RESPONSE_STATUS_*`**、ACP 方法名与 SessionUpdate 字符串(运行时以元组为准) |+| `jiuwenclaw/e2a/adapters.py` | ACP / A2A → E2A;E2A → ACP JSON-RPC;**`E2AResponse` → ACP / A2A 投影**(见 §8) |+| `jiuwenclaw/e2a/__init__.py` | 对外导出 |+| `jiuwenclaw/e2a/ACP-reference.md` / `A2A-reference.md` | 外部协议阅读笔记,**非** E2A 规范性来源 |++---++## 1. 定位与边界++- **经 Gateway 规范化之后**发往 AgentServer 的载荷,用 E2A 表达;通道原始字段在 **Gateway 入口映射**到规范化字段(`user_id`、`message_id`、`params` 等),**不要求**把整包 channel JSON 当作 E2A 主路径。+- **`channel_context`**:可选;仅过渡或无法落入规范化字段的残余键;`from_dict` 可将旧 `metadata` 迁入以兼容历史。+- E2A **不规定**传输层(WebSocket、HTTP 等)。++---++## 2. 易混点:`method` 的两种含义(必读)++同一字段 **`method`** 在不同来源下含义不同,**不是**两套字段,也**不要**与 `request_id` / `message_id` 混用。++| 来源 | `method` 典型取值 | 说明 |+|------|-------------------|------|+| **网关 → AgentServer** | `chat.send`、`history.get`、`chat.interrupt`、… | 项目内 RPC 名;**不在** `constants.ACP_CLIENT_TO_AGENT_METHODS` 中枚举 |+| **ACP 经 `envelope_from_acp_jsonrpc` 转入** | `session/prompt`、`initialize`、… | 与 JSON-RPC `method` 一致;完整列表以 **`constants.ACP_CLIENT_TO_AGENT_METHODS`** 为准 |+| **内部特殊** | `null` | 例如心跳等无 RPC 枚举的场景 |++**出口转 ACP**:`envelope_to_acp_jsonrpc_call` 仅在 `method == "session/prompt"` 时经 `merge_params_to_acp_prompt` 从 **`params`** 补全 `prompt`;若当前 `method` 为 `chat.send`,需**另行**在业务适配层映射为 ACP 的 `session/prompt` 与 `params`,否则生成的 JSON-RPC 对纯 ACP 端无效。++---++## 3. 与 ACP、A2A 的关系(摘要)++| 维度 | ACP | A2A | E2A(对内) |+|------|-----|-----|-------------|+| 角色 | JSON-RPC 会话 | Task / Message / Card | 统一信封;外部经适配器**转入** |+| `method` | JSON-RPC method | 抽象操作(绑定层映射) | 见 **§2** |+| 扩展 | `_meta` | `metadata` | 网关用规范化字段;`a2a_metadata` / `acp_meta` 仅互操作 |++---++## 4. `E2AEnvelope` 字段表++### 4.1 基础与关联++| 字段 | 类型 | 说明 |+|------|------|------|+| `protocol_version` | string | 默认 `1.0` |+| `request_id` | string / null | 网关↔AgentServer 主 id(流式 chunk 对齐) |+| `jsonrpc_id` | string / number / null | ACP 转入时的 JSON-RPC `id` |+| `correlation_id` | string / null | 追踪链,与 `request_id` 分工不同 |+| `task_id` / `context_id` | string / null | A2A 对齐 |+| `session_id` | string / null | 会话 |+| `message_id` | string / null | 平台或 A2A 消息 id;语义勿与 `request_id` 混 |+| `is_stream` | boolean | 是否流式响应 |++### 4.2 `provenance`(`E2AProvenance`)++| 字段 | 说明 |+|------|------|+| `source_protocol` | `e2a` / `acp` / `a2a`(常量见 `E2A_SOURCE_PROTOCOL_*`) |+| `converter` / `converted_at` / `details` | 转换组件、时间、线索(如 `jsonrpc_method`) |++手工构造且未改默认时 `source_protocol` 为 `e2a`。旧字段 `binding` 会迁入 `provenance.details.migrated_from_binding`(兼容)。++### 4.3 时间、身份、入口++| 字段 | 说明 |+|------|------|+| `timestamp` | **规范**:RFC 3339 UTC 字符串;`from_dict` 可接受 float/int 纪元秒并规范化 |+| `identity_origin` | `system` / `user` / `agent` / `service` |+| `channel` | 入口名;**只写 `channel`**。`from_dict` 可读 `channel_id` |+| `user_id` / `source_agent_id` | 用户或上游 Agent |++`timestamp`(业务时刻)≠ `provenance.converted_at`(转入 E2A 时刻)。++### 4.4 `method`、`params`、桥接++| 字段 | 说明 |+|------|------|+| `method` | 见 **§2**;`from_dict` 可读 `req_method` |+| **`params`** | **唯一业务参数字典**(与 JSON-RPC `params` 对齐):RPC 选项、用户正文、多模态块、附件等**全部**放在此对象内,**不再**使用顶层 `payload`(见下表约定) |+| `ext_method` | `method == "ext"` 时的真实名 |+| `session_update_kind` | 桥接 ACP `session/update` 时,与 `constants.ACP_SESSION_UPDATE_KINDS` 一致 |+| `expected_output_modes` | A2A `acceptedOutputModes` |++**`params` 常用键约定**(可按业务扩展,以下为与 ACP 桥接协作的推荐名):++| 键 | 用途 |+|----|------|+| `prompt` | 已是 ACP ContentBlock 数组时直接使用(`merge_params_to_acp_prompt` 不覆盖) |+| `content_blocks` | 与 ACP `Vec<ContentBlock>` 同构的 JSON 数组;在 `method==session/prompt` 且无 `prompt` 时可映射为 `prompt` |+| `text` / `content` / `query` | 纯文本用户输入;无 `prompt`/`content_blocks` 时取第一个非空字符串生成单条 `text` block |+| `files` / `attachments` | 附件列表,元素形状见 **`E2AFileRef`**(`uri` 必填) |+| 其他 | 如 `mode`、`page_idx`、心跳文案等,随网关 RPC 自由扩展 |++### 4.5 `auth`、扩展槽++| 字段 | 说明 |+|------|------|+| `auth` | `E2AAuth`:凭据引用等 |+| `channel_context` | 可选溢出 / 旧 `metadata` 兼容,见 **§1** |+| `a2a_metadata` | **仅** A2A 互操作(与适配器参数名 `metadata` 对应) |+| `acp_meta` | 在 `merge_params_to_acp_prompt` 中合并入 `params._meta`(见 §7) |++---++## 5. 子结构(摘要)++- **`E2AFileRef`**:附件元素推荐形状(`uri` 必填;`name`、`mime_type`、`size`、`_meta` 可选);通常出现在 **`params.files`** 或 **`params.attachments`** 数组中。+- **`E2AAuth`**:`method_id`、`bearer_token`、`api_key_ref`、`credential_ref`、`extra_headers`、`_meta`++---++## 6. `constants.py` 中的 ACP 字符串(桥接参考)++以下**仅**用于 ACP 桥接或文档对照,**运行时**以 `jiuwenclaw.e2a.constants` 中元组为准:++- **`ACP_CLIENT_TO_AGENT_METHODS`**:客户端 → Agent 的 JSON-RPC method 名+- **`ACP_AGENT_TO_CLIENT_METHODS`**、**`ACP_NOTIFICATION_NAMES`**:下行 / 通知+- **`ACP_SESSION_UPDATE_KINDS`**:`session_update_kind` 取值+- **`E2A_RESPONSE_KINDS`**、**`E2A_RESPONSE_STATUS_*`**、**`E2A_A2A_STREAM_BRANCHES`**:响应 `response_kind` / `status` / `a2a.stream_event.branch`(见 **§12**)++**网关 RPC**(`chat.send` 等)由项目自行约定,**不**放在上述元组中。++---++## 7. `merge_params_to_acp_prompt`++Python:`jiuwenclaw.e2a.merge_params_to_acp_prompt(envelope)`。++当且仅当 **`method == "session/prompt"`** 时:++1. 若 `params` 已有 `prompt`,不覆盖。+2. 否则若 `params.content_blocks` 为非空数组,用作 `prompt`。+3. 否则若 `params.text`、`params.content`、`params.query` 中有非空字符串,生成单条 `{ "type": "text", "text": "..." }` 作为 `prompt`。+4. 若信封有 `session_id` 且 `params` 无 `session_id`,则写入。+5. 将 `envelope.acp_meta` 合并进 `params._meta`。++其他 `method` 直接返回 `params` 的浅拷贝。++---++## 8. 适配器(`adapters.py`)++| 函数 | 作用 |+|------|------|+| `envelope_from_acp_jsonrpc` | ACP JSON-RPC → E2A,`provenance.source_protocol=acp`,`method` 为 ACP method |+| `envelope_from_a2a_send_message` | A2A SendMessage 语义 → E2A;参数 **`metadata`** 写入 **`a2a_metadata`**(A2A 专用,不是网关 `metadata`) |+| `envelope_to_acp_jsonrpc_call` | E2A → JSON-RPC 描述;不修改 `provenance` |+| `e2a_response_to_acp_jsonrpc_response` | **`E2AResponse`** → 单条 JSON-RPC **响应**对象(`result` 或 `error`);不适用时返回 `None` |+| `e2a_response_to_a2a_stream_payload` | **`E2AResponse`**(`a2a.stream_event`)→ A2A **`StreamResponse`** 形 JSON(四选一);不适用时返回 `None` |++---++## 9. 序列化与兼容键++- `E2AEnvelope.to_dict()` / `from_dict(data)`+- **只读兼容**:`channel_id`→`channel`,`req_method`→`method`,`metadata`→`channel_context`(仅当 `channel_context` 为空),`binding`→`provenance`(见上)+- **可选**:若 JSON 顶层仍存在旧键 **`payload`**(对象),其键会**合并进 `params`**(不覆盖 `params` 已有键),便于极少数遗留载荷;**新协议不应再发顶层 `payload`**。++---++## 10. 替代 `AgentRequest` 的字段对应++| AgentRequest | E2AEnvelope |+|--------------|-------------|+| `request_id` | `request_id` |+| `channel_id` | `channel` |+| `session_id` | `session_id` |+| `req_method` | `method` |+| `params` | `params` |+| `is_stream` | `is_stream` |+| `timestamp`(float) | `timestamp`(字符串,自动规范化) |+| `metadata` | 目标态:映射进规范化字段;兼容:`from_dict`→`channel_context` |++---++## 11. 示例(JSON 形状)++### 11.1 网关规范化后 → AgentServer(聊天,流式)++```json+{+ "protocol_version": "1.0",+ "request_id": "req_abc_01",+ "session_id": "sess_xyz",+ "channel": "web",+ "method": "chat.send",+ "is_stream": true,+ "timestamp": "2026-03-28T12:00:00+00:00",+ "identity_origin": "user",+ "user_id": "u_001",+ "params": {+ "content": "你好",+ "mode": "plan",+ "query": "你好"+ },+ "provenance": {+ "source_protocol": "e2a"+ }+}+```++`channel_context` 可省略(空对象序列化时可不出现或 `{}`)。++### 11.2 旧 `AgentRequest` 形状(`from_dict` 可读)++```json+{+ "request_id": "req_legacy_1",+ "channel_id": "feishu",+ "session_id": "sess_feishu_1",+ "req_method": "chat.send",+ "is_stream": true,+ "timestamp": 1774524781.15,+ "params": {+ "content": "查桌面文件",+ "mode": "plan",+ "query": "查桌面文件"+ },+ "metadata": {+ "feishu_open_id": "ou_xxx",+ "message_id": "om_xxx"+ }+}+```++解析后:`channel`=`feishu`,`method`=`chat.send`,`timestamp` 变为 RFC 3339 字符串;若未单独映射,`metadata` 会进入 `channel_context`(迁移期)。**目标态**应在 Gateway 把 `feishu_open_id` 等写入 `user_id` / `message_id` 等,并尽量清空 `channel_context`。++### 11.3 ACP 转入(逻辑示例,由 `envelope_from_acp_jsonrpc` 构造)++- `method` = `"session/prompt"`+- `jsonrpc_id` = `42`+- `params` = `{ "session_id": "s1", "prompt": [...] }`+- `provenance.source_protocol` = `"acp"`,`details` 含 `jsonrpc_method` 等++### 11.4 导出 ACP JSON-RPC(`envelope_to_acp_jsonrpc_call` 输出形状)++```json+{+ "jsonrpc": "2.0",+ "id": 42,+ "method": "session/prompt",+ "params": {+ "session_id": "s1",+ "prompt": [{"type": "text", "text": "hi"}]+ }+}+```++仅当信封 `method == "session/prompt"` 且 `params` 中尚无 `prompt` 时,`merge_params_to_acp_prompt` 才会根据 `content_blocks` 或 `text`/`content`/`query` 补全 `prompt`。++### 11.5 `session/prompt` + 多模态(全在 `params`)++```json+{+ "method": "session/prompt",+ "session_id": "s1",+ "jsonrpc_id": 1,+ "params": {+ "content_blocks": [+ {"type": "text", "text": "请描述这张图"},+ {"type": "image", "mime_type": "image/png", "data": "<base64 omitted>"}+ ]+ }+}+```++经 `merge_params_to_acp_prompt` 后,`params` 会多出与 `content_blocks` 等价的 `prompt`(若原本无 `prompt`)。++---++## 12. E2A 响应协议(`E2AResponse`)++Agent → 网关 → 客户端的**每一条**出站记录(含流式多帧)使用 **`E2AResponse`** 表达,与 **`E2AEnvelope`** 字段命名对称(`snake_case`、RFC 3339 `timestamp`、复用 **`E2AProvenance`**)。++### 12.1 三层结构++| 层级 | 名称 | 说明 |+|------|------|------|+| **L1** | 响应信封 | 关联 id、顺序、流结束、状态、出处 |+| **L2** | 判别载荷 | **`response_kind`** + **`body`**(由 kind 约束) |+| **L3** | `projections`(可选) | `acp` / `a2a` 键下存放已组装的对外协议 JSON,**仅辅助**;业务解析**不得**依赖 L3 作为唯一真源 |++### 12.2 `is_final` 与 `status`++- **`is_final`**:`true` 表示同一 **`request_id`** 下**不再**会有后续 **`E2AResponse`** 记录。仅表示传输序列结束,**不**表示业务一定成功(失败帧也可 `is_final: true`)。+- **`status`**:取 **`constants.E2A_RESPONSE_STATUS_*`**(`succeeded` / `failed` / `in_progress`)。当 **`status == failed`** 时,**`response_kind`** 应为 **`e2a.error`**(若同时使用 `acp.jsonrpc_error` 作投影,以本文 **§12.6** 为准)。++### 12.3 不变量(规范)++- 同一 **`request_id`**:**`sequence`** 从 **0** 起严格递增(0, 1, 2, …)。+- 正常结束:**恰好一条**记录的 **`is_final`** 为 **`true`**。+- 异常(对端断连、进程崩溃):可能**无法**发送 `is_final: true`;实现上应通过超时与连接状态补偿,本文不强制「必须补发结束帧」。++### 12.4 L1:信封字段表++| 字段 | 类型 | 必填 | 说明 |+|------|------|------|------|+| `protocol_version` | string | 是 | 与请求一致;默认 `1.0` |+| `response_id` | string | 是 | 本记录唯一 id(建议 UUID) |+| `request_id` | string | 是 | 回显请求;流式 chunk 对齐 |+| `sequence` | integer | 是 | 同 `request_id` 下从 0 递增 |+| `is_final` | boolean | 是 | 最后一帧为 `true` |+| `status` | string | 是 | `succeeded` / `failed` / `in_progress` |+| `response_kind` | string | 是 | 见 **§12.5**;运行时以 **`constants.E2A_RESPONSE_KINDS`** 为准 |+| `timestamp` | string | 是 | RFC 3339 UTC;本记录生成时刻 |+| `provenance` | object | 是 | **`E2AProvenance`**(与请求相同结构) |+| `body` | object | 是 | L2 载荷 |+| `jsonrpc_id` | string / number / null | 否 | 回显 ACP JSON-RPC `id` |+| `correlation_id` | string | 否 | 分布式追踪 |+| `task_id` / `context_id` / `session_id` / `message_id` | string | 否 | 与请求信封同义 |+| `is_stream` | boolean | 否 | 是否对应流式请求(回显或推断) |+| `identity_origin` | string | 否 | 默认倾向 **`agent`**(响应来自 Agent) |+| `channel` / `user_id` / `source_agent_id` | 同请求 | 否 | 回显 |+| `method` | string / null | 否 | 回显请求的 `method`(含心跳 `null`) |+| `metadata` | object | 否 | **通道/业务自定义**键值字典;与旧版 **`AgentResponse.metadata`** 对齐;**协议转换失败**时可临时写入兜底。**AgentServer→Gateway WebSocket** 整包旧 JSON 使用 **`constants.E2A_WIRE_LEGACY_AGENT_RESPONSE_KEY`** / **`E2A_WIRE_LEGACY_AGENT_CHUNK_KEY`**(`_e2a_wire_legacy_*`),与业务自定义键建议用通道前缀区分 |+| `projections` | object | 否 | L3:`acp`、`a2a` 可选键,值为任意 JSON |+| `channel_context` / `a2a_metadata` / `acp_meta` | object | 否 | 与请求对称的溢出槽;**注意**:与 **`metadata`** 分工不同——`a2a_metadata` / `acp_meta` 仅 ACP/A2A 互操作,`metadata` 为通用业务与兜底 |++### 12.5 L2:`response_kind` 与 `body` 要点++运行时以 **`constants.E2A_RESPONSE_KINDS`** 为准;`body` 为 **dict**,下列为规范性说明。++| `response_kind` | `body` 要点 |+|-----------------|-------------|+| `e2a.complete` | **`result`**:业务结果对象(与请求的 **`params`** 哲学对称,避免无关键散落 L1) |+| `e2a.chunk` | **`delta_kind`**:`text` / `reasoning` / `tool` / `custom`;**`delta`**:字符串或结构化对象;可选 **`mime_type`** |+| `e2a.error` | **`code`**、**`message`**、**`details`**;可选 **`external`**:`{ "protocol": "acp"\|"a2a", "type": string, "payload": object }` |+| `acp.session_update` | 贴近 ACP `session/update` 通知负载;**`sessionUpdate`** 等字段与 **`ACP_SESSION_UPDATE_KINDS`** 对齐 |+| `acp.prompt_result` | 对应 `session/prompt` 的 JSON-RPC **`result`**(如 `stop_reason`、可选 `usage`、`_meta`) |+| `acp.jsonrpc_error` | 等价 JSON-RPC **`error`** 语义:`code`、`message`、可选 `data`(与 **`e2a.error`** 并存时:**内核**以 **`e2a.error`** 表达失败;**`acp.jsonrpc_error`** 可作 L3 或专用 kind 仅供 ACP 边界) |+| `a2a.task` | A2A **`Task`** 形对象;JSON 键名与官方 proto 的 JSON 映射一致(**snake_case**,与 `spec/a2a.proto` 字段对应) |+| `a2a.message` | A2A **`Message`** 形对象(同上) |+| `a2a.stream_event` | **`branch`**:`task` / `message` / `status_update` / `artifact_update`(常量 **`E2A_A2A_STREAM_BRANCHES`**);**`payload`**:对应分支对象 |+| `ext` | **`ext_method`** + **`params`**(与请求 `ext` 对称) |++**推荐策略**:网关 / AgentServer **内部**优先使用 **`e2a.complete`** / **`e2a.chunk`** / **`e2a.error`**;在出口适配层生成 **`acp.*`** / **`a2a.*`** 或写入 **`projections`**。++### 12.6 与 ACP / A2A 的映射(摘要)++- **ACP**:JSON-RPC 响应由 **`jsonrpc_id`** + **`acp.prompt_result`**(`result`)或 **`e2a.error`** / **`acp.jsonrpc_error`**(`error`)映射;**`acp.session_update`** 对应 **`session/update`** 通知的 **`params`**。详见 **`e2a_response_to_acp_jsonrpc_response`**(§8)。+- **A2A**:**`a2a.stream_event`** 与 **`StreamResponse`** 四分支一一对应;**`e2a_response_to_a2a_stream_payload`** 产出单事件 JSON。 **`a2a.task`** / **`a2a.message`** 对应 SendMessage 两种返回。++### 12.7 日志建议(如 `E:\logs`)++- **一行一条**完整 **`E2AResponse`** JSON,便于检索与按 **`sequence`** 重放。+- 每条至少含 **`request_id`**、**`response_id`**、**`sequence`**、**`is_final`**、**`response_kind`**、**`timestamp`**。+- 勿记录 **`bearer_token`**、完整模型输出中的敏感内容;大 **`body`** 可将来扩展 **`body_ref`**(本版未定义)。++### 12.8 示例:流式两帧 + 结束帧++```json+{"protocol_version":"1.0","response_id":"r1","request_id":"req_1","sequence":0,"is_final":false,"status":"in_progress","response_kind":"e2a.chunk","timestamp":"2026-03-29T12:00:00+00:00","provenance":{"source_protocol":"e2a"},"body":{"delta_kind":"text","delta":"你好"}}+```++```json+{"protocol_version":"1.0","response_id":"r2","request_id":"req_1","sequence":1,"is_final":false,"status":"in_progress","response_kind":"e2a.chunk","timestamp":"2026-03-29T12:00:01+00:00","provenance":{"source_protocol":"e2a"},"body":{"delta_kind":"text","delta":"世界"}}+```++```json+{"protocol_version":"1.0","response_id":"r3","request_id":"req_1","sequence":2,"is_final":true,"status":"succeeded","response_kind":"e2a.complete","timestamp":"2026-03-29T12:00:02+00:00","provenance":{"source_protocol":"e2a"},"body":{"result":{"content":"你好世界"}}}+```++与 **`E2A-AgentRequest-log-migration.md`** 中的请求日志收编可对照:响应侧将来可同样约定统一前缀与单行 JSON。++---++## 13. 安全建议++- 优先 `credential_ref` / `api_key_ref`,由网关换票;日志勿完整打印 `bearer_token`。+- 跨域使用 TLS 与最小权限。++---++*本文与 `jiuwenclaw/e2a/models.py`(`E2AEnvelope`、`E2AResponse`)同步维护。*diff --git a/docs/zh/README.md b/docs/zh/README.mdindex e97449ce7e..26a25dd2bf 100644--- a/docs/zh/README.md+++ b/docs/zh/README.md@@ -3,6 +3,7 @@这里汇总 JiuwenClaw 的常用使用说明与功能文档。- 从零开始安装与启动:见 [快速开始](Quickstart.md)+- Gateway 与 AgentServer 统一请求信封(E2A):见 [E2A 协议](E2A-protocol.md)([English](../en/E2A-protocol.md))- 配置模型与系统参数:见 [配置说明](配置信息.md)- 各功能专题文档:见左侧目录或直接从下列入口开始:- [频道](频道.md)diff --git a/docs/zh/SUMMARY.md b/docs/zh/SUMMARY.mdindex 1ec7cce028..3be9dd23bf 100644--- a/docs/zh/SUMMARY.md+++ b/docs/zh/SUMMARY.md@@ -1,6 +1,7 @@# Summary- [快速开始](Quickstart.md)+- [E2A 协议(Gateway↔Agent)](E2A-protocol.md)- [配置说明](配置信息.md)- [使用指南](README.md)- [频道](频道.md)diff --git a/jiuwenclaw/agentserver/agent_ws_server.py b/jiuwenclaw/agentserver/agent_ws_server.pyindex fa933f9fca..ba2f9450ad 100644--- a/jiuwenclaw/agentserver/agent_ws_server.py+++ b/jiuwenclaw/agentserver/agent_ws_server.py@@ -8,11 +8,22 @@ import loggingimport asyncioimport jsonimport math-from dataclasses import asdictfrom pathlib import Pathfrom typing import Any, ClassVarfrom jiuwenclaw.utils import get_agent_sessions_dir, get_config_file+from jiuwenclaw.e2a.agent_compat import e2a_to_agent_request+from jiuwenclaw.e2a.gateway_normalize import (+ E2A_FALLBACK_FAILED_KEY,+ E2A_INTERNAL_CONTEXT_KEY,+ E2A_LEGACY_AGENT_REQUEST_KEY,+)+from jiuwenclaw.e2a.models import E2AEnvelope+from jiuwenclaw.e2a.wire_codec import (+ encode_agent_chunk_for_wire,+ encode_agent_response_for_wire,+ encode_json_parse_error_wire,+)from jiuwenclaw.schema.agent import AgentRequest, AgentResponse, AgentResponseChunk@@ -39,25 +50,16 @@ def _payload_to_request(data: dict[str, Any]) -> AgentRequest:)-def _response_to_payload(resp: AgentResponse) -> dict[str, Any]:- """将 AgentResponse 转为 JSON 载荷."""- return asdict(resp)---def _chunk_to_payload(chunk: AgentResponseChunk) -> dict[str, Any]:- """将 AgentResponseChunk 转为 JSON 载荷."""- return asdict(chunk)--class AgentWebSocketServer:"""Gateway 与 AgentServer 之间的 WebSocket 服务端(单例).监听来自 Gateway (WebSocketAgentServerClient) 的连接,按协议约定处理请求:- - 收到 JSON 载荷,字段为 AgentRequest(含 is_stream)- - is_stream=False:调用 IAgentServer.process_message(),返回一条完整 AgentResponse JSON- - is_stream=True:调用 IAgentServer.process_message_stream(),逐条返回 AgentResponseChunk JSON+ - 收到 JSON:E2AEnvelope(或过渡期 legacy + 兜底信封)+ - is_stream=False:``process_message`` → 一条 **E2AResponse** JSON(``jiuwenclaw.e2a.wire_codec``)+ - is_stream=True:逐条 **E2AResponse** JSON(chunk/complete/error)+ - 例外:首帧 ``connection.ack`` 仍为 ``type/event`` 事件帧- 支持 send_push:AgentServer 主动向 Gateway 推送消息(需 Gateway 预注册 agent-push 队列)。+ 支持 send_push:推送帧亦为 E2AResponse 线格式(由 chunk 编码)。"""_instance: ClassVar[AgentWebSocketServer | None] = None@@ -212,17 +214,43 @@ class AgentWebSocketServer:try:data = json.loads(raw)except json.JSONDecodeError as e:- error_payload = {- "request_id": "",- "channel_id": "",- "ok": False,- "payload": {"error": f"JSON 解析失败: {e}"},- }+ wire = encode_json_parse_error_wire(+ request_id="",+ channel_id="",+ message=f"JSON 解析失败: {e}",+ )async with send_lock:- await ws.send(json.dumps(error_payload, ensure_ascii=False))+ await ws.send(json.dumps(wire, ensure_ascii=False))return- request = _payload_to_request(data)+ try:+ env = E2AEnvelope.from_dict(data)+ except Exception as parse_err:+ logger.warning(+ "[AgentWebSocketServer] E2A from_dict 失败,按旧载荷解析: %s",+ parse_err,+ )+ request = _payload_to_request(data)+ else:+ jw = (env.channel_context or {}).get(E2A_INTERNAL_CONTEXT_KEY)+ if isinstance(jw, dict) and jw.get(E2A_FALLBACK_FAILED_KEY):+ legacy = jw.get(E2A_LEGACY_AGENT_REQUEST_KEY)+ logger.warning(+ "[E2A][fallback] using legacy_agent_request request_id=%s",+ env.request_id,+ )+ if not isinstance(legacy, dict):+ raise ValueError("legacy_agent_request missing or not a dict")+ request = _payload_to_request(legacy)+ else:+ logger.info(+ "[E2A][in] request_id=%s channel=%s method=%s is_stream=%s",+ env.request_id,+ env.channel,+ env.method,+ env.is_stream,+ )+ request = e2a_to_agent_request(env)logger.info("[AgentWebSocketServer] 收到请求: request_id=%s channel_id=%s is_stream=%s",@@ -268,30 +296,35 @@ class AgentWebSocketServer:ok=False,payload={"error": str(e)},)+ wire = encode_agent_response_for_wire(+ error_resp, response_id=request.request_id+ )async with send_lock:- await ws.send(- json.dumps(_response_to_payload(error_resp), ensure_ascii=False)- )+ await ws.send(json.dumps(wire, ensure_ascii=False))async def _handle_unary(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:- """非流式处理:调用 process_message,返回一条完整 AgentResponse."""+ """非流式处理:调用 process_message,返回一条 E2AResponse 线 JSON。"""resp = await self._agent.process_message(request)- payload = _response_to_payload(resp)+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)async with send_lock:- await ws.send(json.dumps(payload, ensure_ascii=False))+ await ws.send(json.dumps(wire, ensure_ascii=False))logger.info("[AgentWebSocketServer] 非流式响应已发送: request_id=%s",request.request_id,)async def _handle_stream(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:- """流式处理:调用 process_message_stream,逐条发送 AgentResponseChunk."""+ """流式处理:调用 process_message_stream,逐条发送 E2AResponse 线 JSON。"""chunk_count = 0async for chunk in self._agent.process_message_stream(request):chunk_count += 1- payload = _chunk_to_payload(chunk)+ wire = encode_agent_chunk_for_wire(+ chunk,+ response_id=request.request_id,+ sequence=chunk_count - 1,+ )async with send_lock:- await ws.send(json.dumps(payload, ensure_ascii=False))+ await ws.send(json.dumps(wire, ensure_ascii=False))logger.info("[AgentWebSocketServer] 流式响应已发送: request_id=%s 共 %s 个 chunk",request.request_id,@@ -317,8 +350,9 @@ class AgentWebSocketServer:ok=True,payload=data,)+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)async with send_lock:- await ws.send(json.dumps(_response_to_payload(resp), ensure_ascii=False))+ await ws.send(json.dumps(wire, ensure_ascii=False))async def _handle_history_get_stream(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:params = request.params if isinstance(request.params, dict) else {}@@ -335,15 +369,20 @@ class AgentWebSocketServer:},is_complete=True,)+ wire = encode_agent_chunk_for_wire(+ err_chunk,+ response_id=request.request_id,+ sequence=0,+ )async with send_lock:- await ws.send(json.dumps(_chunk_to_payload(err_chunk), ensure_ascii=False))+ await ws.send(json.dumps(wire, ensure_ascii=False))returnmessages = data.get("messages", [])total_pages = data.get("total_pages")page = data.get("page_idx")if isinstance(messages, list):- for item in messages:+ for seq, item in enumerate(messages):chunk = AgentResponseChunk(request_id=request.request_id,channel_id=request.channel_id,@@ -355,8 +394,13 @@ class AgentWebSocketServer:},is_complete=False,)+ wire = encode_agent_chunk_for_wire(+ chunk,+ response_id=request.request_id,+ sequence=seq,+ )async with send_lock:- await ws.send(json.dumps(_chunk_to_payload(chunk), ensure_ascii=False))+ await ws.send(json.dumps(wire, ensure_ascii=False))done_chunk = AgentResponseChunk(request_id=request.request_id,@@ -369,8 +413,14 @@ class AgentWebSocketServer:},is_complete=True,)+ done_seq = len(messages) if isinstance(messages, list) else 0+ wire_done = encode_agent_chunk_for_wire(+ done_chunk,+ response_id=request.request_id,+ sequence=done_seq,+ )async with send_lock:- await ws.send(json.dumps(_chunk_to_payload(done_chunk), ensure_ascii=False))+ await ws.send(json.dumps(wire_done, ensure_ascii=False))async def _handle_browser_start(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:"""启动浏览器并返回执行结果(returncode)。"""@@ -394,8 +444,9 @@ class AgentWebSocketServer:payload={"error": str(e)},)+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)async with send_lock:- await ws.send(json.dumps(_response_to_payload(resp), ensure_ascii=False))+ await ws.send(json.dumps(wire, ensure_ascii=False))async def _handle_browser_runtime_restart(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:try:@@ -417,8 +468,9 @@ class AgentWebSocketServer:payload={"error": str(e)},)+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)async with send_lock:- await ws.send(json.dumps(_response_to_payload(resp), ensure_ascii=False))+ await ws.send(json.dumps(wire, ensure_ascii=False))async def _handle_config_cache_clear(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:try:@@ -440,8 +492,9 @@ class AgentWebSocketServer:payload={"error": str(e)},)+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)async with send_lock:- await ws.send(json.dumps(_response_to_payload(resp), ensure_ascii=False))+ await ws.send(json.dumps(wire, ensure_ascii=False))async def _handle_agent_reload_config(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:try:@@ -461,8 +514,9 @@ class AgentWebSocketServer:payload={"error": str(e)},)+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)async with send_lock:- await ws.send(json.dumps(_response_to_payload(resp), ensure_ascii=False))+ await ws.send(json.dumps(wire, ensure_ascii=False))async def send_push(self, msg) -> None:"""AgentServer 主动向 Gateway 推送消息。@@ -477,10 +531,21 @@ class AgentWebSocketServer:returntry:+ chunk = AgentResponseChunk(+ request_id=str(msg.get("request_id", "")),+ channel_id=str(msg.get("channel_id", "")),+ payload=msg.get("payload"),+ is_complete=bool(msg.get("is_complete", False)),+ )+ wire = encode_agent_chunk_for_wire(+ chunk,+ response_id=str(msg.get("request_id", "")),+ sequence=0,+ )async with self._current_send_lock:- await self._current_ws.send(json.dumps(msg, ensure_ascii=False))+ await self._current_ws.send(json.dumps(wire, ensure_ascii=False))logger.info(- "[AgentWebSocketServer] send_push 已发送: channel_id=%s",+ "[AgentWebSocketServer] send_push 已发送(E2A wire): channel_id=%s",msg["channel_id"],)except Exception as e:diff --git a/jiuwenclaw/app.py b/jiuwenclaw/app.pyindex b386c439c7..96c25b98ee 100644--- a/jiuwenclaw/app.py+++ b/jiuwenclaw/app.py@@ -186,15 +186,15 @@ async def _clear_agent_config_cache(agent_client=None) -> None:"""写回 config.yaml 后清除 agent 侧配置缓存,使下次读取时得到最新文件内容。"""try:if agent_client is not None:- from jiuwenclaw.schema.agent import AgentRequest+ from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fieldsfrom jiuwenclaw.schema.message import ReqMethodimport uuid- req = AgentRequest(+ env = e2a_from_agent_fields(request_id=f"cfg-cache-clear-{uuid.uuid4().hex[:8]}",channel_id="",req_method=ReqMethod.CONFIG_CACHE_CLEAR,)- await agent_client.send_request(req)+ await agent_client.send_request(env)else:get_config()except Exception: # noqa: BLE001@@ -1503,23 +1503,24 @@ async def _run() -> None:"VISION_PROVIDER", "VISION_MODEL_NAME", "VISION_API_BASE", "VISION_API_KEY",}try:- from jiuwenclaw.schema.agent import AgentRequest+ from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fields+ from jiuwenclaw.schema.message import ReqMethodimport uuid- reload_req = AgentRequest(+ reload_env = e2a_from_agent_fields(request_id=f"agent-reload-{uuid.uuid4().hex[:8]}",channel_id="",req_method=ReqMethod.AGENT_RELOAD_CONFIG,)- await client.send_request(reload_req)+ await client.send_request(reload_env)if updated_env_keys and (browser_runtime_keys & set(updated_env_keys)):- restart_req = AgentRequest(+ restart_env = e2a_from_agent_fields(request_id=f"browser-restart-{uuid.uuid4().hex[:8]}",channel_id="",req_method=ReqMethod.BROWSER_RUNTIME_RESTART,)- await client.send_request(restart_req)+ await client.send_request(restart_env)return Trueexcept Exception as e: # noqa: BLE001logger.warning("[App] 配置热更新失败,将延迟重启: %s", e)@@ -1694,6 +1695,8 @@ async def _run() -> None:allow_from=feishu_conf.get("allow_from") or [],enable_streaming=bool(feishu_conf.get("enable_streaming", True)),chat_id=str(feishu_conf.get("chat_id") or "").strip(),+ last_chat_id=str(feishu_conf.get("last_chat_id") or "").strip(),+ last_open_id=str(feishu_conf.get("last_open_id") or "").strip(),)feishu_channel = FeishuChannel(feishu_config, _DummyBus())channel_manager.register_channel(feishu_channel)@@ -1742,6 +1745,8 @@ async def _run() -> None:chat_id=str(bot_conf.get("chat_id") or "").strip(),channel_id=channel_id,bot_key=bot_key,+ last_chat_id=str(bot_conf.get("last_chat_id") or "").strip(),+ last_open_id=str(bot_conf.get("last_open_id") or "").strip(),)channel = FeishuChannel(feishu_config, _DummyBus())channel_manager.register_channel(channel)diff --git a/jiuwenclaw/app_gateway.py b/jiuwenclaw/app_gateway.pyindex d1156ffa25..c2bb3a821b 100644--- a/jiuwenclaw/app_gateway.py+++ b/jiuwenclaw/app_gateway.py@@ -363,6 +363,8 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: stallow_from=feishu_conf.get("allow_from") or [],enable_streaming=bool(feishu_conf.get("enable_streaming", True)),chat_id=str(feishu_conf.get("chat_id") or "").strip(),+ last_chat_id=str(feishu_conf.get("last_chat_id") or "").strip(),+ last_open_id=str(feishu_conf.get("last_open_id") or "").strip(),)feishu_channel = FeishuChannel(feishu_config, _DummyBus())channel_manager.register_channel(feishu_channel)@@ -412,6 +414,8 @@ async def _run(agent_server_url: str, web_host: str, web_port: int, web_path: stchat_id=str(bot_conf.get("chat_id") or "").strip(),channel_id=channel_id,bot_key=bot_key,+ last_chat_id=str(bot_conf.get("last_chat_id") or "").strip(),+ last_open_id=str(bot_conf.get("last_open_id") or "").strip(),)channel = FeishuChannel(feishu_config, _DummyBus())channel_manager.register_channel(channel)diff --git a/jiuwenclaw/channel/feishu.py b/jiuwenclaw/channel/feishu.pyindex 78f545e16b..b18270ba8f 100644--- a/jiuwenclaw/channel/feishu.py+++ b/jiuwenclaw/channel/feishu.py@@ -42,6 +42,9 @@ class FeishuConfig(BaseModel):chat_id: str = "" # 可选:固定推送目标 chat_id(群聊 oc_xxx 或个人 open_id)channel_id: str = "feishu" # ChannelManager 路由键,支持多实例bot_key: str = "" # 企业飞书多 bot 配置键(仅 feishu_enterprise 使用)+ # 收消息时写入 config.yaml,用于无 metadata 时的回发兜底(与 session_id 解耦)+ last_chat_id: str = ""+ last_open_id: str = ""# 文件处理配置max_download_size: int = 100 * 1024 * 1024 # 最大下载文件大小(默认100MB)@@ -883,6 +886,17 @@ class FeishuChannel(BaseChannel):receive_id = cfg_chat_idid_type = "chat_id" if cfg_chat_id.startswith("oc_") else "open_id"+ # 2b) 最近一次会话(收消息时写入 config / 内存),避免 supplement 等路径丢 metadata 后误用 session_id+ if not receive_id:+ last_cid = str(getattr(self.config, "last_chat_id", "") or "").strip()+ last_oid = str(getattr(self.config, "last_open_id", "") or "").strip()+ if last_cid:+ receive_id = last_cid+ id_type = "chat_id" if last_cid.startswith("oc_") else "open_id"+ elif last_oid:+ receive_id = last_oid+ id_type = "open_id"+# 3) 仍然没有,则回退到 session_id / id(兼容旧逻辑)if not receive_id:receive_id = getattr(msg, "session_id", None) or msg.id or ""@@ -1261,6 +1275,16 @@ class FeishuChannel(BaseChannel):# 不影响正常收消息pass+ # 内存同步 last_*:无 metadata 的回发兜底立即生效,不必等通道重启从 yaml 加载+ lc = str(getattr(message, "chat_id", None) or "").strip()+ lo = str(open_id or "").strip()+ try:+ self.config = self.config.model_copy(+ update={"last_chat_id": lc, "last_open_id": lo},+ )+ except Exception:+ pass+# 构建消息参数params = {"content": content, "query": content}if file_info:diff --git a/jiuwenclaw/e2a/__init__.py b/jiuwenclaw/e2a/__init__.pynew file mode 100644index 0000000000..f1e74a4175--- /dev/null+++ b/jiuwenclaw/e2a/__init__.py@@ -0,0 +1,138 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""E2A(Everything-to-Agent):统一信封;ACP / A2A 等经转换进入 E2A,并由 provenance 记录出处。++协议说明(中英):仓库 ``docs/zh/E2A-protocol.md``、``docs/en/E2A-protocol.md``。+"""++from jiuwenclaw.e2a.adapters import (+ e2a_response_to_a2a_stream_payload,+ e2a_response_to_acp_jsonrpc_response,+ envelope_from_a2a_send_message,+ envelope_from_acp_jsonrpc,+ envelope_to_acp_jsonrpc_call,+)+from jiuwenclaw.e2a.constants import (+ ACP_AGENT_TO_CLIENT_METHODS,+ ACP_CLIENT_TO_AGENT_METHODS,+ ACP_NOTIFICATION_NAMES,+ ACP_SESSION_UPDATE_KINDS,+ E2A_A2A_STREAM_BRANCHES,+ E2A_RESPONSE_KINDS,+ E2A_WIRE_LEGACY_AGENT_CHUNK_KEY,+ E2A_WIRE_LEGACY_AGENT_RESPONSE_KEY,+ E2A_RESPONSE_KIND_ACP_JSONRPC_ERROR,+ E2A_RESPONSE_KIND_ACP_PROMPT_RESULT,+ E2A_RESPONSE_KIND_ACP_SESSION_UPDATE,+ E2A_RESPONSE_KIND_A2A_MESSAGE,+ E2A_RESPONSE_KIND_A2A_STREAM_EVENT,+ E2A_RESPONSE_KIND_A2A_TASK,+ E2A_RESPONSE_KIND_E2A_CHUNK,+ E2A_RESPONSE_KIND_E2A_COMPLETE,+ E2A_RESPONSE_KIND_E2A_ERROR,+ E2A_RESPONSE_KIND_EXT,+ E2A_RESPONSE_STATUS_FAILED,+ E2A_RESPONSE_STATUS_IN_PROGRESS,+ E2A_RESPONSE_STATUS_SUCCEEDED,+ E2A_SOURCE_PROTOCOL_A2A,+ E2A_SOURCE_PROTOCOL_ACP,+ E2A_SOURCE_PROTOCOL_E2A,+)+from jiuwenclaw.e2a.agent_compat import e2a_to_agent_request+from jiuwenclaw.e2a.gateway_normalize import (+ E2A_FALLBACK_FAILED_KEY,+ E2A_INTERNAL_CONTEXT_KEY,+ E2A_LEGACY_AGENT_REQUEST_KEY,+ MAX_LEGACY_AGENT_REQUEST_JSON_BYTES,+ build_fallback_e2a,+ channel_context_for_channel_reply,+ e2a_from_agent_fields,+ e2a_response_from_agent_chunk,+ e2a_response_from_agent_response,+ e2a_response_to_agent_chunk,+ e2a_response_to_agent_response,+ message_to_e2a,+ message_to_e2a_or_fallback,+ message_to_legacy_agent_dict,+)+from jiuwenclaw.e2a.wire_codec import (+ encode_agent_chunk_for_wire,+ encode_agent_response_for_wire,+ encode_json_parse_error_wire,+ is_e2a_response_wire_dict,+ parse_agent_server_wire_chunk,+ parse_agent_server_wire_unary,+)+from jiuwenclaw.e2a.models import (+ E2A_PROTOCOL_VERSION,+ E2AAuth,+ E2AEnvelope,+ E2AFileRef,+ E2AProvenance,+ E2AResponse,+ IdentityOrigin,+ merge_params_to_acp_prompt,+ utc_now_iso,+)++__all__ = [+ "ACP_AGENT_TO_CLIENT_METHODS",+ "ACP_CLIENT_TO_AGENT_METHODS",+ "ACP_NOTIFICATION_NAMES",+ "ACP_SESSION_UPDATE_KINDS",+ "E2A_A2A_STREAM_BRANCHES",+ "E2A_PROTOCOL_VERSION",+ "E2A_RESPONSE_KINDS",+ "E2A_RESPONSE_KIND_ACP_JSONRPC_ERROR",+ "E2A_RESPONSE_KIND_ACP_PROMPT_RESULT",+ "E2A_RESPONSE_KIND_ACP_SESSION_UPDATE",+ "E2A_RESPONSE_KIND_A2A_MESSAGE",+ "E2A_RESPONSE_KIND_A2A_STREAM_EVENT",+ "E2A_RESPONSE_KIND_A2A_TASK",+ "E2A_RESPONSE_KIND_E2A_CHUNK",+ "E2A_RESPONSE_KIND_E2A_COMPLETE",+ "E2A_RESPONSE_KIND_E2A_ERROR",+ "E2A_RESPONSE_KIND_EXT",+ "E2A_WIRE_LEGACY_AGENT_CHUNK_KEY",+ "E2A_WIRE_LEGACY_AGENT_RESPONSE_KEY",+ "E2A_RESPONSE_STATUS_FAILED",+ "E2A_RESPONSE_STATUS_IN_PROGRESS",+ "E2A_RESPONSE_STATUS_SUCCEEDED",+ "E2A_SOURCE_PROTOCOL_A2A",+ "E2A_SOURCE_PROTOCOL_ACP",+ "E2A_SOURCE_PROTOCOL_E2A",+ "E2AAuth",+ "E2AEnvelope",+ "E2AFileRef",+ "E2AProvenance",+ "E2AResponse",+ "IdentityOrigin",+ "e2a_response_to_a2a_stream_payload",+ "e2a_response_to_acp_jsonrpc_response",+ "envelope_from_a2a_send_message",+ "envelope_from_acp_jsonrpc",+ "envelope_to_acp_jsonrpc_call",+ "merge_params_to_acp_prompt",+ "utc_now_iso",+ "e2a_to_agent_request",+ "E2A_FALLBACK_FAILED_KEY",+ "E2A_INTERNAL_CONTEXT_KEY",+ "E2A_LEGACY_AGENT_REQUEST_KEY",+ "MAX_LEGACY_AGENT_REQUEST_JSON_BYTES",+ "build_fallback_e2a",+ "channel_context_for_channel_reply",+ "e2a_from_agent_fields",+ "e2a_response_from_agent_chunk",+ "e2a_response_from_agent_response",+ "e2a_response_to_agent_chunk",+ "e2a_response_to_agent_response",+ "encode_agent_chunk_for_wire",+ "encode_agent_response_for_wire",+ "encode_json_parse_error_wire",+ "is_e2a_response_wire_dict",+ "parse_agent_server_wire_chunk",+ "parse_agent_server_wire_unary",+ "message_to_e2a",+ "message_to_e2a_or_fallback",+ "message_to_legacy_agent_dict",+]diff --git a/jiuwenclaw/e2a/adapters.py b/jiuwenclaw/e2a/adapters.pynew file mode 100644index 0000000000..481d63b187--- /dev/null+++ b/jiuwenclaw/e2a/adapters.py@@ -0,0 +1,224 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""+将 ACP JSON-RPC、A2A SendMessage 等外部形态转换为 E2A,并写入 provenance。++``envelope_from_a2a_send_message`` 的参数 ``metadata`` 仅对应 E2A 的 ``a2a_metadata``(A2A 规范侧),+与网关通道上的 ``metadata`` / ``channel_context`` 无关。++``e2a_response_to_acp_jsonrpc_response`` / ``e2a_response_to_a2a_stream_payload`` 将 ``E2AResponse`` 投影为+外协议形状;不适用时返回 ``None``(见 ``docs/zh/E2A-protocol.md`` §8、§12)。+"""+++from __future__ import annotations++from typing import Any++from jiuwenclaw.e2a.constants import (+ E2A_A2A_STREAM_BRANCHES,+ E2A_RESPONSE_KIND_ACP_JSONRPC_ERROR,+ E2A_RESPONSE_KIND_ACP_PROMPT_RESULT,+ E2A_RESPONSE_KIND_A2A_STREAM_EVENT,+ E2A_RESPONSE_KIND_E2A_ERROR,+ E2A_SOURCE_PROTOCOL_ACP,+ E2A_SOURCE_PROTOCOL_A2A,+)+from jiuwenclaw.e2a.models import (+ E2AEnvelope,+ E2AProvenance,+ E2AResponse,+ IdentityOrigin,+ merge_params_to_acp_prompt,+ utc_now_iso,+)++_CONVERTER_ACP = "jiuwenclaw.e2a.adapters:envelope_from_acp_jsonrpc"+_CONVERTER_A2A = "jiuwenclaw.e2a.adapters:envelope_from_a2a_send_message"+++def envelope_from_acp_jsonrpc(+ method: str,+ params: dict[str, Any] | None = None,+ *,+ jsonrpc_id: str | int | None = None,+ session_id: str | None = None,+ channel: str | None = None,+ identity_origin: IdentityOrigin = IdentityOrigin.USER,+ converter: str | None = None,+ extra_provenance_details: dict[str, Any] | None = None,+) -> E2AEnvelope:+ """由 ACP JSON-RPC 调用构造 E2A;provenance 标明来源为 acp。"""+ p = dict(params or {})+ sid = session_id or p.get("session_id")+ details: dict[str, Any] = {+ "kind": "jsonrpc_request",+ "jsonrpc_method": method,+ }+ if jsonrpc_id is not None:+ details["jsonrpc_id"] = jsonrpc_id+ if extra_provenance_details:+ details.update(extra_provenance_details)+ return E2AEnvelope(+ provenance=E2AProvenance(+ source_protocol=E2A_SOURCE_PROTOCOL_ACP,+ converter=converter or _CONVERTER_ACP,+ converted_at=utc_now_iso(),+ details=details,+ ),+ jsonrpc_id=jsonrpc_id,+ method=method,+ params=p,+ session_id=sid if isinstance(sid, str) else None,+ channel=channel,+ identity_origin=identity_origin,+ )+++def envelope_from_a2a_send_message(+ *,+ task_id: str | None,+ context_id: str | None,+ message_body: dict[str, Any],+ metadata: dict[str, Any] | None = None,+ configuration: dict[str, Any] | None = None,+ channel: str | None = None,+ identity_origin: IdentityOrigin = IdentityOrigin.USER,+ converter: str | None = None,+ extra_provenance_details: dict[str, Any] | None = None,+) -> E2AEnvelope:+ """+ 将 A2A SendMessage 语义转为 E2A;provenance 标明来源为 a2a。++ 默认 method 为 ``session/prompt``,完整 message/configuration 保留在 params 与 a2a_metadata。+ """+ meta = dict(metadata or {})+ accepted: list[str] = []+ if configuration:+ acc = configuration.get("acceptedOutputModes")+ if isinstance(acc, list):+ accepted = [str(x) for x in acc]+ details: dict[str, Any] = {+ "kind": "a2a_send_message",+ "abstract_operation": "SendMessage",+ }+ if extra_provenance_details:+ details.update(extra_provenance_details)+ return E2AEnvelope(+ provenance=E2AProvenance(+ source_protocol=E2A_SOURCE_PROTOCOL_A2A,+ converter=converter or _CONVERTER_A2A,+ converted_at=utc_now_iso(),+ details=details,+ ),+ method="session/prompt",+ task_id=task_id,+ context_id=context_id,+ channel=channel,+ identity_origin=identity_origin,+ expected_output_modes=accepted,+ params={"message": message_body, "configuration": configuration or {}},+ a2a_metadata=meta,+ )+++def envelope_to_acp_jsonrpc_call(envelope: E2AEnvelope) -> dict[str, Any]:+ """+ 将信封转为 JSON-RPC 风格单条调用描述(日志或下游 ACP 端点)。++ 若 ``envelope.method`` 为网关 RPC(如 ``chat.send``),输出中的 ``method`` 对纯 ACP 端可能无效,+ 需在业务层先映射为 ACP method(如 ``session/prompt``)再发送。+ """+ method = envelope.ext_method if envelope.method == "ext" and envelope.ext_method else envelope.method+ params = merge_params_to_acp_prompt(envelope) if envelope.method == "session/prompt" else dict(envelope.params)+ return {+ "jsonrpc": "2.0",+ "id": envelope.jsonrpc_id,+ "method": method,+ "params": params,+ }+++def e2a_response_to_acp_jsonrpc_response(response: E2AResponse) -> dict[str, Any] | None:+ """+ 将 ``E2AResponse`` 转为单条 JSON-RPC 2.0 **响应**对象(仅 ``result`` 或 ``error``,无 ``method``)。++ 优先使用 ``projections.acp``:若为已组装的完整响应(含 ``jsonrpc`` 与 ``result``/``error``),原样返回副本。+ 否则按 ``response_kind`` 从 ``body`` 构造:++ - ``acp.prompt_result`` → ``result`` = ``body``+ - ``acp.jsonrpc_error`` → ``error`` = ``body``(须含 JSON-RPC 所需字段)+ - ``e2a.error`` → ``error``:``code`` 非 int 时用 ``-32603``,字符串码写入 ``data.e2a_code``+ """+ proj = response.projections.get("acp") if isinstance(response.projections, dict) else None+ if isinstance(proj, dict) and proj.get("jsonrpc") == "2.0":+ if "result" in proj or "error" in proj:+ out = dict(proj)+ out.setdefault("id", response.jsonrpc_id)+ return out++ rpc_id = response.jsonrpc_id+ kind = response.response_kind+ body = dict(response.body or {})++ if kind == E2A_RESPONSE_KIND_ACP_PROMPT_RESULT:+ return {"jsonrpc": "2.0", "id": rpc_id, "result": body}++ if kind == E2A_RESPONSE_KIND_ACP_JSONRPC_ERROR:+ return {"jsonrpc": "2.0", "id": rpc_id, "error": body}++ if kind == E2A_RESPONSE_KIND_E2A_ERROR:+ code_raw = body.get("code")+ code = code_raw if isinstance(code_raw, int) else -32603+ message = str(body.get("message") or "")+ data: dict[str, Any] = {}+ det = body.get("details")+ if det is not None:+ data["details"] = det+ ext = body.get("external")+ if ext is not None:+ data["external"] = ext+ if code_raw is not None and not isinstance(code_raw, int):+ data["e2a_code"] = code_raw+ err: dict[str, Any] = {"code": code, "message": message}+ if data:+ err["data"] = data+ return {"jsonrpc": "2.0", "id": rpc_id, "error": err}++ return None+++def e2a_response_to_a2a_stream_payload(response: E2AResponse) -> dict[str, Any] | None:+ """+ 将 ``response_kind == \"a2a.stream_event\"`` 的 ``E2AResponse`` 转为 A2A ``StreamResponse`` 形 JSON:++ 外层键为 ``task`` / ``message`` / ``statusUpdate`` / ``artifactUpdate`` 之一(与常见 JSON 绑定一致)。++ 若 ``projections.a2a`` 已为四选一单键对象,则原样返回副本。+ ``body.branch`` 须为 ``E2A_A2A_STREAM_BRANCHES`` 之一;``body.payload`` 为对应分支对象。+ """+ if response.response_kind != E2A_RESPONSE_KIND_A2A_STREAM_EVENT:+ return None++ proj = response.projections.get("a2a") if isinstance(response.projections, dict) else None+ if isinstance(proj, dict) and len(proj) == 1:+ key = next(iter(proj))+ if key in ("task", "message", "statusUpdate", "artifactUpdate"):+ return dict(proj)++ body = dict(response.body or {})+ branch = body.get("branch")+ payload = body.get("payload")+ if branch not in E2A_A2A_STREAM_BRANCHES or not isinstance(payload, dict):+ return None++ key_map = {+ "task": "task",+ "message": "message",+ "status_update": "statusUpdate",+ "artifact_update": "artifactUpdate",+ }+ outer = key_map.get(branch)+ if outer is None:+ return None+ return {outer: payload}diff --git a/jiuwenclaw/e2a/agent_compat.py b/jiuwenclaw/e2a/agent_compat.pynew file mode 100644index 0000000000..a6cfee0f9b--- /dev/null+++ b/jiuwenclaw/e2a/agent_compat.py@@ -0,0 +1,63 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""AgentServer:E2AEnvelope → 现有 AgentRequest(第一阶段);不得与 normalize_failed 兜底同时使用。"""++from __future__ import annotations++import logging+from datetime import datetime+from typing import Any++from jiuwenclaw.e2a.gateway_normalize import E2A_INTERNAL_CONTEXT_KEY+from jiuwenclaw.e2a.models import E2AEnvelope+from jiuwenclaw.schema.agent import AgentRequest+from jiuwenclaw.schema.message import ReqMethod++logger = logging.getLogger(__name__)+++def _e2a_timestamp_to_float(ts: str | None) -> float:+ if not ts:+ return 0.0+ try:+ s = ts.replace("Z", "+00:00") if ts.endswith("Z") else ts+ return datetime.fromisoformat(s).timestamp()+ except Exception:+ return 0.0+++def e2a_to_agent_request(env: E2AEnvelope) -> AgentRequest:+ """+ 将规范化成功的 E2A 转为 AgentRequest。++ 若 envelope 含 Gateway 兜底标记,须由调用方先分支处理 legacy,勿调用本函数。+ """+ ctx = dict(env.channel_context or {})+ internal = ctx.pop(E2A_INTERNAL_CONTEXT_KEY, None)+ if isinstance(internal, dict) and internal.get("normalize_failed"):+ raise RuntimeError("e2a_to_agent_request called on fallback envelope; use legacy path")++ metadata = ctx if ctx else None+ method_str = env.method+ req_method: ReqMethod | None = None+ if method_str:+ try:+ req_method = ReqMethod(method_str)+ except ValueError:+ logger.error(+ "[E2A][compat] unknown E2A method=%r request_id=%s",+ method_str,+ env.request_id,+ )+ raise++ return AgentRequest(+ request_id=env.request_id or "",+ channel_id=env.channel or "",+ session_id=env.session_id,+ req_method=req_method,+ params=dict(env.params or {}),+ is_stream=bool(env.is_stream),+ timestamp=_e2a_timestamp_to_float(env.timestamp),+ metadata=metadata,+ )diff --git a/jiuwenclaw/e2a/constants.py b/jiuwenclaw/e2a/constants.pynew file mode 100644index 0000000000..bd5eac16b9--- /dev/null+++ b/jiuwenclaw/e2a/constants.py@@ -0,0 +1,103 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""E2A 出处常量与 ACP 方法名 / SessionUpdate 判别式(与 `ACP-reference.md` 一致)。"""++# E2A provenance.source_protocol 约定(可扩展)+E2A_SOURCE_PROTOCOL_E2A = "e2a"+E2A_SOURCE_PROTOCOL_ACP = "acp"+E2A_SOURCE_PROTOCOL_A2A = "a2a"++# E2AResponse.status(与 docs/zh/E2A-protocol.md §12 一致)+E2A_RESPONSE_STATUS_SUCCEEDED = "succeeded"+E2A_RESPONSE_STATUS_FAILED = "failed"+E2A_RESPONSE_STATUS_IN_PROGRESS = "in_progress"++# E2AResponse.response_kind:具名常量(代码中请用下列符号,避免与元组漂移)+E2A_RESPONSE_KIND_E2A_COMPLETE = "e2a.complete"+E2A_RESPONSE_KIND_E2A_CHUNK = "e2a.chunk"+E2A_RESPONSE_KIND_E2A_ERROR = "e2a.error"+E2A_RESPONSE_KIND_ACP_SESSION_UPDATE = "acp.session_update"+E2A_RESPONSE_KIND_ACP_PROMPT_RESULT = "acp.prompt_result"+E2A_RESPONSE_KIND_ACP_JSONRPC_ERROR = "acp.jsonrpc_error"+E2A_RESPONSE_KIND_A2A_TASK = "a2a.task"+E2A_RESPONSE_KIND_A2A_MESSAGE = "a2a.message"+E2A_RESPONSE_KIND_A2A_STREAM_EVENT = "a2a.stream_event"+E2A_RESPONSE_KIND_EXT = "ext"++# 运行时以本元组为准(与 docs §12 一致)+E2A_RESPONSE_KINDS: tuple[str, ...] = (+ E2A_RESPONSE_KIND_E2A_COMPLETE,+ E2A_RESPONSE_KIND_E2A_CHUNK,+ E2A_RESPONSE_KIND_E2A_ERROR,+ E2A_RESPONSE_KIND_ACP_SESSION_UPDATE,+ E2A_RESPONSE_KIND_ACP_PROMPT_RESULT,+ E2A_RESPONSE_KIND_ACP_JSONRPC_ERROR,+ E2A_RESPONSE_KIND_A2A_TASK,+ E2A_RESPONSE_KIND_A2A_MESSAGE,+ E2A_RESPONSE_KIND_A2A_STREAM_EVENT,+ E2A_RESPONSE_KIND_EXT,+)++# a2a.stream_event.body.branch → A2A StreamResponse oneof(JSON 键用 snake_case)+E2A_A2A_STREAM_BRANCHES: tuple[str, ...] = (+ "task",+ "message",+ "status_update",+ "artifact_update",+)++# 客户端 → Agent(JSON-RPC method 名)+ACP_CLIENT_TO_AGENT_METHODS: tuple[str, ...] = (+ "initialize",+ "authenticate",+ "session/new",+ "session/load",+ "session/list",+ "session/set_mode",+ "session/set_config_option",+ "session/prompt",+ "session/set_model",+ "session/fork",+ "session/resume",+ "session/close",+ "logout",+)++# Agent → 客户端(供下行事件或桥接时使用)+ACP_AGENT_TO_CLIENT_METHODS: tuple[str, ...] = (+ "session/update",+ "session/request_permission",+ "fs/read_text_file",+ "fs/write_text_file",+ "terminal/create",+ "terminal/output",+ "terminal/release",+ "terminal/wait_for_exit",+ "terminal/kill",+ "session/elicitation",+)++ACP_NOTIFICATION_NAMES: tuple[str, ...] = (+ "session/cancel",+ "session/update",+ "session/elicitation/complete",+)++# session/update 内 SessionUpdate.sessionUpdate 取值+# AgentServer → Gateway WebSocket:编码失败时整包旧 JSON 写入 E2AResponse.metadata 的键(勿与业务键冲突)+E2A_WIRE_LEGACY_AGENT_RESPONSE_KEY = "_e2a_wire_legacy_agent_response"+E2A_WIRE_LEGACY_AGENT_CHUNK_KEY = "_e2a_wire_legacy_agent_chunk"++ACP_SESSION_UPDATE_KINDS: tuple[str, ...] = (+ "user_message_chunk",+ "agent_message_chunk",+ "agent_thought_chunk",+ "tool_call",+ "tool_call_update",+ "plan",+ "available_commands_update",+ "current_mode_update",+ "config_option_update",+ "session_info_update",+ "usage_update",+)diff --git a/jiuwenclaw/e2a/gateway_normalize.py b/jiuwenclaw/e2a/gateway_normalize.pynew file mode 100644index 0000000000..6082d8719e--- /dev/null+++ b/jiuwenclaw/e2a/gateway_normalize.py@@ -0,0 +1,503 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Gateway:Channel Message / 类 Agent 请求字段 → E2AEnvelope;AgentResponse/Chunk → E2AResponse;规范化失败时构造兜底信封。"""++from __future__ import annotations++import json+import logging+from typing import TYPE_CHECKING, Any++from jiuwenclaw.e2a.constants import (+ E2A_RESPONSE_KIND_E2A_CHUNK,+ E2A_RESPONSE_KIND_E2A_COMPLETE,+ E2A_RESPONSE_KIND_E2A_ERROR,+ E2A_RESPONSE_STATUS_FAILED,+ E2A_RESPONSE_STATUS_IN_PROGRESS,+ E2A_RESPONSE_STATUS_SUCCEEDED,+ E2A_SOURCE_PROTOCOL_E2A,+)+from jiuwenclaw.e2a.models import (+ E2AEnvelope,+ E2A_PROTOCOL_VERSION,+ E2AProvenance,+ E2AResponse,+ IdentityOrigin,+ utc_now_iso,+)++if TYPE_CHECKING:+ from jiuwenclaw.schema.agent import AgentResponse, AgentResponseChunk+ from jiuwenclaw.schema.message import Message, ReqMethod++logger = logging.getLogger(__name__)++# 与 E2A-AgentRequest-log-migration.md §7.4 一致;通道业务勿占用此前缀。+E2A_INTERNAL_CONTEXT_KEY = "_jiuwenclaw"+E2A_FALLBACK_FAILED_KEY = "normalize_failed"+E2A_LEGACY_AGENT_REQUEST_KEY = "legacy_agent_request"+MAX_LEGACY_AGENT_REQUEST_JSON_BYTES = 512_000+++def message_to_legacy_agent_dict(msg: "Message") -> dict[str, Any]:+ """从 Message 生成与历史 WebSocket 一致的 dict(用于兜底 legacy_agent_request)。"""+ rm = msg.req_method+ rm_val: str | None+ if rm is None:+ rm_val = None+ elif hasattr(rm, "value"):+ rm_val = str(rm.value)+ else:+ rm_val = str(rm)+ out: dict[str, Any] = {+ "request_id": msg.id,+ "channel_id": msg.channel_id,+ "session_id": msg.session_id,+ "req_method": rm_val,+ "params": dict(msg.params or {}),+ "is_stream": bool(msg.is_stream),+ "timestamp": float(msg.timestamp),+ }+ if msg.metadata:+ out["metadata"] = dict(msg.metadata)+ return out+++def _legacy_payload_within_limit(legacy: dict[str, Any]) -> dict[str, Any]:+ try:+ raw = json.dumps(legacy, ensure_ascii=False, default=str)+ except Exception:+ return {+ "request_id": str(legacy.get("request_id", "")),+ "channel_id": str(legacy.get("channel_id", "")),+ "session_id": legacy.get("session_id"),+ "req_method": None,+ "params": {"_e2a_fallback_error": "legacy not json-serializable"},+ "is_stream": False,+ "timestamp": 0.0,+ }+ if len(raw.encode("utf-8")) <= MAX_LEGACY_AGENT_REQUEST_JSON_BYTES:+ return legacy+ logger.error(+ "[E2A][fallback] legacy_agent_request exceeds %s bytes, stripping params",+ MAX_LEGACY_AGENT_REQUEST_JSON_BYTES,+ )+ slim = {**legacy, "params": {"_e2a_fallback_error": "legacy payload too large"}}+ return slim+++def build_fallback_e2a(legacy: dict[str, Any]) -> E2AEnvelope:+ """规范化失败时仍发 E2A 形状:在 channel_context 内携带 legacy 快照。"""+ legacy = _legacy_payload_within_limit(dict(legacy))+ rid = str(legacy.get("request_id") or "")+ internal = {+ E2A_FALLBACK_FAILED_KEY: True,+ E2A_LEGACY_AGENT_REQUEST_KEY: legacy,+ }+ cc: dict[str, Any] = {E2A_INTERNAL_CONTEXT_KEY: internal}+ return E2AEnvelope(+ protocol_version=E2A_PROTOCOL_VERSION,+ request_id=rid or None,+ channel=str(legacy.get("channel_id") or "") or None,+ session_id=legacy.get("session_id"),+ method=None,+ params={},+ is_stream=bool(legacy.get("is_stream", False)),+ channel_context=cc,+ )+++def message_to_e2a(msg: "Message") -> E2AEnvelope:+ """Message → E2AEnvelope(不经兜底)。"""+ d: dict[str, Any] = {+ "request_id": msg.id,+ "channel_id": msg.channel_id,+ "session_id": msg.session_id,+ "params": dict(msg.params or {}),+ "is_stream": bool(msg.is_stream),+ "timestamp": msg.timestamp,+ }+ if msg.req_method is not None:+ d["method"] = msg.req_method.value+ if msg.metadata:+ d["metadata"] = dict(msg.metadata)+ return E2AEnvelope.from_dict(d)+++def message_to_e2a_or_fallback(msg: "Message") -> E2AEnvelope:+ """Message → E2A;失败或校验不通过则 build_fallback_e2a。"""+ try:+ env = message_to_e2a(msg)+ if not (env.request_id and str(env.request_id).strip()):+ raise ValueError("empty request_id")+ if env.params is not None and not isinstance(env.params, dict):+ raise ValueError("params must be dict")+ logger.info(+ "[E2A][norm] request_id=%s channel=%s method=%s is_stream=%s params_keys=%s",+ env.request_id,+ env.channel,+ env.method,+ env.is_stream,+ list((env.params or {}).keys())[:32],+ )+ return env+ except Exception as e:+ legacy = message_to_legacy_agent_dict(msg)+ logger.warning(+ "[E2A][fallback] normalize failed request_id=%s err=%s",+ getattr(msg, "id", ""),+ e,+ )+ return build_fallback_e2a(legacy)+++def e2a_from_agent_fields(+ *,+ request_id: str,+ channel_id: str = "",+ session_id: str | None = None,+ req_method: "ReqMethod | str | None" = None,+ params: dict[str, Any] | None = None,+ is_stream: bool = False,+ timestamp: float = 0.0,+ metadata: dict[str, Any] | None = None,+) -> E2AEnvelope:+ """由与 AgentRequest 相同的字段构造 E2A(heartbeat / cron / app 管理请求等)。"""+ d: dict[str, Any] = {+ "request_id": request_id,+ "channel_id": channel_id,+ "session_id": session_id,+ "params": dict(params or {}),+ "is_stream": is_stream,+ "timestamp": timestamp,+ }+ if req_method is not None:+ if hasattr(req_method, "value"):+ d["method"] = req_method.value+ else:+ d["method"] = str(req_method)+ if metadata:+ d["metadata"] = dict(metadata)+ return E2AEnvelope.from_dict(d)+++def channel_context_for_channel_reply(env: E2AEnvelope) -> dict[str, Any] | None:+ """供流式 chunk 回传到 Channel:去掉内部 _jiuwenclaw,保留 trace 与业务 metadata。"""+ ctx = dict(env.channel_context or {})+ ctx.pop(E2A_INTERNAL_CONTEXT_KEY, None)+ return ctx if ctx else None+++def e2a_response_from_agent_response(+ resp: "AgentResponse",+ *,+ response_id: str,+ sequence: int = 0,+ timestamp: str | None = None,+) -> E2AResponse:+ """+ 将 ``AgentResponse``(与 ``E:\\logs`` 中 ``AgentResponse: {...}`` 同形)规范为 ``E2AResponse``。++ 非流式完整响应恒为 ``is_final=True``、``sequence`` 默认 0。+ """+ from jiuwenclaw.schema.agent import AgentResponse as AgentResponseCls++ if not isinstance(resp, AgentResponseCls):+ raise TypeError("resp must be AgentResponse")++ ts = timestamp or utc_now_iso()+ prov = E2AProvenance(+ source_protocol=E2A_SOURCE_PROTOCOL_E2A,+ converter="jiuwenclaw.e2a.gateway_normalize:e2a_response_from_agent_response",+ converted_at=ts,+ details={"kind": "legacy_agent_response", "ok": bool(resp.ok)},+ )+ meta = dict(resp.metadata) if resp.metadata else {}++ if resp.ok:+ body: dict[str, Any] = {"result": dict(resp.payload) if resp.payload else {}}+ status = E2A_RESPONSE_STATUS_SUCCEEDED+ kind = E2A_RESPONSE_KIND_E2A_COMPLETE+ else:+ pl = dict(resp.payload) if resp.payload else {}+ err = pl.get("error", pl.get("message", "Agent error"))+ body = {+ "code": "E2A.AGENT_ERROR",+ "message": str(err),+ "details": pl,+ }+ status = E2A_RESPONSE_STATUS_FAILED+ kind = E2A_RESPONSE_KIND_E2A_ERROR++ return E2AResponse(+ protocol_version=E2A_PROTOCOL_VERSION,+ response_id=response_id,+ request_id=resp.request_id,+ sequence=sequence,+ is_final=True,+ status=status,+ response_kind=kind,+ timestamp=ts,+ provenance=prov,+ body=body,+ channel=resp.channel_id or None,+ metadata=meta,+ identity_origin=IdentityOrigin.AGENT,+ is_stream=False,+ )+++def e2a_response_from_agent_chunk(+ chunk: "AgentResponseChunk",+ *,+ response_id: str,+ sequence: int,+ is_stream: bool = True,+ timestamp: str | None = None,+) -> E2AResponse:+ """+ 将 ``AgentResponseChunk``(与 ``E:\\logs`` 中 ``AgentResponseChunk: {...}`` 同形)规范为 ``E2AResponse``。++ - 中间帧:``e2a.chunk``,``status=in_progress``,``is_final=False``。+ - 终止帧(如 ``payload == {\"is_complete\": true}``):``e2a.complete``。+ - ``chat.delta``:按 ``source_chunk_type`` 映射 ``body.delta_kind``(``llm_reasoning`` → ``reasoning``)。+ """+ from jiuwenclaw.schema.agent import AgentResponseChunk as AgentResponseChunkCls++ if not isinstance(chunk, AgentResponseChunkCls):+ raise TypeError("chunk must be AgentResponseChunk")++ ts = timestamp or utc_now_iso()+ prov = E2AProvenance(+ source_protocol=E2A_SOURCE_PROTOCOL_E2A,+ converter="jiuwenclaw.e2a.gateway_normalize:e2a_response_from_agent_chunk",+ converted_at=ts,+ details={"kind": "legacy_agent_response_chunk", "is_complete": chunk.is_complete},+ )+ pl = dict(chunk.payload) if chunk.payload else {}++ if chunk.is_complete and pl == {"is_complete": True}:+ return E2AResponse(+ protocol_version=E2A_PROTOCOL_VERSION,+ response_id=response_id,+ request_id=chunk.request_id,+ sequence=sequence,+ is_final=True,+ status=E2A_RESPONSE_STATUS_SUCCEEDED,+ response_kind=E2A_RESPONSE_KIND_E2A_COMPLETE,+ timestamp=ts,+ provenance=prov,+ body={"result": {}},+ channel=chunk.channel_id or None,+ identity_origin=IdentityOrigin.AGENT,+ is_stream=is_stream,+ )++ if chunk.is_complete and pl.get("event_type") == "chat.error":+ return E2AResponse(+ protocol_version=E2A_PROTOCOL_VERSION,+ response_id=response_id,+ request_id=chunk.request_id,+ sequence=sequence,+ is_final=True,+ status=E2A_RESPONSE_STATUS_FAILED,+ response_kind=E2A_RESPONSE_KIND_E2A_ERROR,+ timestamp=ts,+ provenance=prov,+ body={+ "code": "chat.error",+ "message": str(pl.get("error", "")),+ "details": pl,+ },+ channel=chunk.channel_id or None,+ identity_origin=IdentityOrigin.AGENT,+ is_stream=is_stream,+ )++ if chunk.is_complete:+ return E2AResponse(+ protocol_version=E2A_PROTOCOL_VERSION,+ response_id=response_id,+ request_id=chunk.request_id,+ sequence=sequence,+ is_final=True,+ status=E2A_RESPONSE_STATUS_SUCCEEDED,+ response_kind=E2A_RESPONSE_KIND_E2A_COMPLETE,+ timestamp=ts,+ provenance=prov,+ body={"result": pl},+ channel=chunk.channel_id or None,+ identity_origin=IdentityOrigin.AGENT,+ is_stream=is_stream,+ )++ event_type = pl.get("event_type")+ if event_type == "chat.delta":+ sct = pl.get("source_chunk_type")+ delta_kind = "reasoning" if sct == "llm_reasoning" else "text"+ body_chunk: dict[str, Any] = {+ "delta_kind": delta_kind,+ "delta": pl.get("content", ""),+ "event_type": event_type,+ "source_chunk_type": sct,+ }+ else:+ body_chunk = {+ "delta_kind": "custom",+ "delta": pl,+ "event_type": event_type,+ }++ return E2AResponse(+ protocol_version=E2A_PROTOCOL_VERSION,+ response_id=response_id,+ request_id=chunk.request_id,+ sequence=sequence,+ is_final=False,+ status=E2A_RESPONSE_STATUS_IN_PROGRESS,+ response_kind=E2A_RESPONSE_KIND_E2A_CHUNK,+ timestamp=ts,+ provenance=prov,+ body=body_chunk,+ channel=chunk.channel_id or None,+ identity_origin=IdentityOrigin.AGENT,+ is_stream=is_stream,+ )+++def e2a_response_to_agent_response(e2a: E2AResponse) -> "AgentResponse":+ """+ ``E2AResponse`` → 非流式 ``AgentResponse``(与 ``e2a_response_from_agent_response`` 对仗)。++ 仅处理网关 unary 常见 ``response_kind``:``e2a.complete``、``e2a.error``;其它 kind 抛 ``ValueError``。+ """+ from jiuwenclaw.schema.agent import AgentResponse++ rid = str(e2a.request_id or "")+ ch = str(e2a.channel or "")+ meta = dict(e2a.metadata) if e2a.metadata else None+ kind = e2a.response_kind+ body = dict(e2a.body or {})++ if kind == E2A_RESPONSE_KIND_E2A_COMPLETE and e2a.status == E2A_RESPONSE_STATUS_SUCCEEDED:+ res = body.get("result")+ pl = dict(res) if isinstance(res, dict) else {}+ return AgentResponse(+ request_id=rid,+ channel_id=ch,+ ok=True,+ payload=pl,+ metadata=meta,+ )++ if kind == E2A_RESPONSE_KIND_E2A_ERROR or e2a.status == E2A_RESPONSE_STATUS_FAILED:+ details = body.get("details")+ if isinstance(details, dict):+ pl = dict(details)+ else:+ pl = {+ "error": body.get("message", "Agent error"),+ "code": body.get("code"),+ }+ return AgentResponse(+ request_id=rid,+ channel_id=ch,+ ok=False,+ payload=pl,+ metadata=meta,+ )++ raise ValueError(+ f"e2a_response_to_agent_response: unsupported response_kind={kind!r} status={e2a.status!r}"+ )+++def e2a_response_to_agent_chunk(e2a: E2AResponse) -> "AgentResponseChunk":+ """+ ``E2AResponse`` → ``AgentResponseChunk``(与 ``e2a_response_from_agent_chunk`` 对仗)。++ 覆盖:流式 ``e2a.chunk``、终止 ``e2a.complete`` / ``e2a.error``(含 ``chat.error`` 形 ``details``)。+ """+ from jiuwenclaw.schema.agent import AgentResponseChunk++ rid = str(e2a.request_id or "")+ ch = str(e2a.channel or "")+ body = dict(e2a.body or {})+ kind = e2a.response_kind++ if kind == E2A_RESPONSE_KIND_E2A_COMPLETE and e2a.is_final:+ res = body.get("result")++ def _empty_complete_marker(b: dict[str, Any], r: Any) -> bool:+ if b == {"result": {}}:+ return True+ if not isinstance(r, dict) or r:+ return False+ return list(b.keys()) == ["result"]++ if _empty_complete_marker(body, res):+ return AgentResponseChunk(+ request_id=rid,+ channel_id=ch,+ payload={"is_complete": True},+ is_complete=True,+ )+ pl = dict(res) if isinstance(res, dict) else {}+ return AgentResponseChunk(+ request_id=rid,+ channel_id=ch,+ payload=pl,+ is_complete=True,+ )++ if kind == E2A_RESPONSE_KIND_E2A_ERROR and e2a.is_final:+ det = body.get("details")+ pl = dict(det) if isinstance(det, dict) else dict(body)+ return AgentResponseChunk(+ request_id=rid,+ channel_id=ch,+ payload=pl,+ is_complete=True,+ )++ if kind == E2A_RESPONSE_KIND_E2A_CHUNK and not e2a.is_final:+ dk = body.get("delta_kind")+ et = body.get("event_type")+ delta = body.get("delta")+ sct_in = body.get("source_chunk_type")++ if et == "chat.delta" or dk in ("text", "reasoning"):+ sct = "llm_reasoning" if dk == "reasoning" else sct_in+ pl: dict[str, Any] = {+ "event_type": "chat.delta",+ "content": delta if delta is not None else "",+ }+ if sct is not None:+ pl["source_chunk_type"] = sct+ return AgentResponseChunk(+ request_id=rid,+ channel_id=ch,+ payload=pl,+ is_complete=False,+ )++ if isinstance(delta, dict):+ pl2 = dict(delta)+ else:+ pl2 = {}+ if et is not None:+ pl2["event_type"] = et+ if delta is not None:+ pl2["content"] = delta+ if et is not None and "event_type" not in pl2:+ pl2["event_type"] = et+ return AgentResponseChunk(+ request_id=rid,+ channel_id=ch,+ payload=pl2,+ is_complete=False,+ )++ raise ValueError(+ f"e2a_response_to_agent_chunk: unsupported response_kind={kind!r} is_final={e2a.is_final!r}"+ )diff --git a/jiuwenclaw/e2a/models.py b/jiuwenclaw/e2a/models.pynew file mode 100644index 0000000000..292d55250f--- /dev/null+++ b/jiuwenclaw/e2a/models.py@@ -0,0 +1,473 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""+E2A 数据模型:请求信封 ``E2AEnvelope``、响应 ``E2AResponse`` 与子结构。++完整约定、易混点与 JSON 示例见仓库 ``docs/zh/E2A-protocol.md``(``docs/en/E2A-protocol.md``)。字段以本模块 dataclass 为准。+"""++from __future__ import annotations++from dataclasses import dataclass, field, fields+from datetime import datetime, timezone+from enum import Enum+from typing import Any++from jiuwenclaw.e2a.constants import (+ E2A_RESPONSE_STATUS_IN_PROGRESS,+ E2A_SOURCE_PROTOCOL_A2A,+ E2A_SOURCE_PROTOCOL_ACP,+ E2A_SOURCE_PROTOCOL_E2A,+)+++E2A_PROTOCOL_VERSION = "1.0"+++def utc_now_iso() -> str:+ """当前 UTC 时刻的 RFC 3339 字符串(``provenance.converted_at``、响应 ``timestamp`` 缺省等)。"""++ return datetime.now(timezone.utc).isoformat()+++class IdentityOrigin(str, Enum):+ """身份来源:谁触发了本次对 Agent 的请求。"""++ SYSTEM = "system"+ USER = "user"+ AGENT = "agent"+ SERVICE = "service"+++@dataclass+class E2AProvenance:+ """+ 记录 E2A 信封的出处。++ - E2A 为统一载体:ACP、A2A 等消息经转换后均应落在此结构中。+ - ``source_protocol`` 标明**进入 E2A 之前**所依据的主要协议或「原生 E2A」。+ - ``converter`` / ``converted_at`` / ``details`` 标明由谁、何时、从何种具体调用转换而来。+ """++ source_protocol: str = E2A_SOURCE_PROTOCOL_E2A+ converter: str | None = None+ converted_at: str | None = None+ details: dict[str, Any] = field(default_factory=dict)+++@dataclass+class E2AFileRef:+ """文件引用(用于 ``params.files`` / ``params.attachments`` 等元素,对齐 MCP/A2A 常见形态)。"""++ uri: str+ name: str | None = None+ mime_type: str | None = None+ size: int | None = None+ _meta: dict[str, Any] = field(default_factory=dict)+++@dataclass+class E2AAuth:+ """+ 身份鉴权信息(按需填充)。++ 建议:生产环境用 credential_ref / oauth 等间接引用,由网关在受控环境换票。+ """++ method_id: str | None = None+ bearer_token: str | None = None+ api_key_ref: str | None = None+ credential_ref: str | None = None+ extra_headers: dict[str, str] = field(default_factory=dict)+ _meta: dict[str, Any] = field(default_factory=dict)+++@dataclass+class E2AEnvelope:+ """+ E2A 统一信封:单结构兼容多协议入口,由网关或适配层解析后调用 Agent。++ 基础字段:+ - protocol_version:E2A 载荷版本。+ - provenance:出处(原生 e2a 或由 acp / a2a 等转换)。+ - request_id:网关↔AgentServer 主请求 id(流式 chunk 关联)。+ - jsonrpc_id / correlation_id:JSON-RPC id、分布式追踪等(可与 request_id 并存)。+ - task_id / context_id / session_id / message_id:对齐 A2A / ACP 侧概念。+ - is_stream:是否流式响应。++ 事件语义:+ - method:**网关 RPC**(如 ``chat.send``)或 ACP 转入时的 JSON-RPC method;``ext`` + ``ext_method`` 用于自定义。+ - **params**:**唯一业务参数字典**(JSON-RPC params、用户正文、``content_blocks``、附件列表等均放此处,见仓库 ``docs/zh/E2A-protocol.md``)。++ 通道与互操作:+ - channel_context:**可选溢出**;主路径上通道侧信息应在**网关入口**映射为规范化字段。+ - a2a_metadata / acp_meta:与 A2A/ACP 互操作时使用。+ """++ # --- 基础 / 关联 ---+ protocol_version: str = E2A_PROTOCOL_VERSION+ provenance: E2AProvenance = field(default_factory=E2AProvenance)+ request_id: str | None = None+ jsonrpc_id: str | int | None = None+ correlation_id: str | None = None+ task_id: str | None = None+ context_id: str | None = None+ session_id: str | None = None+ message_id: str | None = None++ # --- 时间戳:规范为 RFC 3339 UTC 字符串;from_dict 可将历史 float 纪元秒规范化 ---+ timestamp: str | None = None++ # --- 身份与入口 ---+ identity_origin: IdentityOrigin = IdentityOrigin.USER+ channel: str | None = None+ user_id: str | None = None+ source_agent_id: str | None = None++ # --- 网关 RPC(原 req_method);ACP 转入时同字段承载 JSON-RPC method ---+ method: str | None = None+ params: dict[str, Any] = field(default_factory=dict)+ ext_method: str | None = None+ session_update_kind: str | None = None+ is_stream: bool = False++ # --- 期望输出(对齐 A2A acceptedOutputModes)---+ expected_output_modes: list[str] = field(default_factory=list)++ # --- 鉴权 ---+ auth: E2AAuth | None = None++ # --- 扩展槽 ---+ channel_context: dict[str, Any] = field(default_factory=dict)+ a2a_metadata: dict[str, Any] = field(default_factory=dict)+ acp_meta: dict[str, Any] = field(default_factory=dict)++ def ensure_timestamp(self) -> None:+ """若未设置 timestamp,则填当前 UTC ISO8601。"""+ if self.timestamp is None:+ self.timestamp = utc_now_iso()++ def to_dict(self) -> dict[str, Any]:+ """序列化为 JSON 友好 dict(枚举转为值)。"""+ d = _dataclass_to_json_dict(self)+ return d++ @classmethod+ def from_dict(cls, data: dict[str, Any]) -> E2AEnvelope:+ return _envelope_from_dict(data)+++@dataclass+class E2AResponse:+ """+ E2A 统一响应:每条出站记录(含流式多帧)一条实例;与 ``E2AEnvelope`` 对称。++ 分层语义见 ``docs/zh/E2A-protocol.md`` / ``docs/en/E2A-protocol.md`` §12;``response_kind`` 取值以+ ``constants.E2A_RESPONSE_KINDS`` 为准。++ ``metadata``:通道/业务自定义键值;兼容旧版 ``AgentResponse.metadata``;协议转换失败时可临时写入兜底信息+ (如原始片段、错误说明),与 ``a2a_metadata`` / ``acp_meta`` 分工不同。+ """++ protocol_version: str = E2A_PROTOCOL_VERSION+ response_id: str | None = None+ request_id: str | None = None+ sequence: int = 0+ is_final: bool = False+ status: str = E2A_RESPONSE_STATUS_IN_PROGRESS+ response_kind: str = ""+ timestamp: str | None = None+ provenance: E2AProvenance = field(default_factory=E2AProvenance)+ body: dict[str, Any] = field(default_factory=dict)++ jsonrpc_id: str | int | None = None+ correlation_id: str | None = None+ task_id: str | None = None+ context_id: str | None = None+ session_id: str | None = None+ message_id: str | None = None+ is_stream: bool = False+ identity_origin: IdentityOrigin = IdentityOrigin.AGENT+ channel: str | None = None+ user_id: str | None = None+ source_agent_id: str | None = None+ method: str | None = None++ projections: dict[str, Any] = field(default_factory=dict)+ channel_context: dict[str, Any] = field(default_factory=dict)+ metadata: dict[str, Any] = field(default_factory=dict)+ a2a_metadata: dict[str, Any] = field(default_factory=dict)+ acp_meta: dict[str, Any] = field(default_factory=dict)++ def ensure_timestamp(self) -> None:+ """若未设置 timestamp,则填当前 UTC ISO8601。"""+ if self.timestamp is None:+ self.timestamp = utc_now_iso()++ def to_dict(self) -> dict[str, Any]:+ """序列化为 JSON 友好 dict(枚举转为值)。"""+ return _dataclass_to_json_dict(self)++ @classmethod+ def from_dict(cls, data: dict[str, Any]) -> E2AResponse:+ return _e2a_response_from_dict(data)+++def _enum_value(obj: Any) -> Any:+ if isinstance(obj, Enum):+ return obj.value+ return obj+++def _dataclass_to_json_dict(obj: Any) -> dict[str, Any]:+ if hasattr(obj, "__dataclass_fields__"):+ out: dict[str, Any] = {}+ for f in fields(obj):+ v = getattr(obj, f.name)+ if v is None and f.name.startswith("_"):+ continue+ key = f.name+ if isinstance(v, Enum):+ out[key] = v.value+ elif hasattr(v, "__dataclass_fields__"):+ out[key] = _dataclass_to_json_dict(v)+ elif isinstance(v, list):+ out[key] = [+ _dataclass_to_json_dict(x)+ if hasattr(x, "__dataclass_fields__")+ else _enum_value(x)+ for x in v+ ]+ elif isinstance(v, dict):+ out[key] = {+ k: _dataclass_to_json_dict(x)+ if hasattr(x, "__dataclass_fields__")+ else x+ for k, x in v.items()+ }+ else:+ out[key] = v+ return out+ return obj+++def _provenance_from_dict(raw: Any) -> E2AProvenance:+ if raw is None:+ return E2AProvenance()+ if isinstance(raw, E2AProvenance):+ return raw+ if not isinstance(raw, dict):+ return E2AProvenance()+ return E2AProvenance(+ source_protocol=str(raw.get("source_protocol", E2A_SOURCE_PROTOCOL_E2A)),+ converter=raw.get("converter"),+ converted_at=raw.get("converted_at"),+ details=dict(raw.get("details") or {}),+ )+++def _normalize_timestamp_value(raw: Any) -> str | None:+ """规范为 RFC 3339 UTC 字符串;接受 str 或历史 float/int 纪元秒。"""+ if raw is None:+ return None+ if isinstance(raw, str):+ return raw+ if isinstance(raw, (int, float)):+ return datetime.fromtimestamp(float(raw), tz=timezone.utc).isoformat()+ return str(raw)+++def _migrate_legacy_binding(data: dict[str, Any], prov: E2AProvenance) -> E2AProvenance:+ """旧版 ``binding`` 字段迁入 provenance.details,避免丢失信息。"""+ legacy = data.get("binding")+ if legacy is None or prov.details.get("migrated_from_binding") is not None:+ return prov+ if isinstance(legacy, dict) and "value" in legacy:+ legacy = legacy["value"]+ legacy_s = str(legacy) if legacy is not None else ""+ d = dict(prov.details)+ d["migrated_from_binding"] = legacy_s+ sp = prov.source_protocol+ if sp == E2A_SOURCE_PROTOCOL_E2A:+ if legacy_s == E2A_SOURCE_PROTOCOL_ACP:+ sp = E2A_SOURCE_PROTOCOL_ACP+ elif legacy_s == E2A_SOURCE_PROTOCOL_A2A:+ sp = E2A_SOURCE_PROTOCOL_A2A+ elif legacy_s in ("internal", "hybrid"):+ sp = E2A_SOURCE_PROTOCOL_E2A+ return E2AProvenance(+ source_protocol=sp,+ converter=prov.converter,+ converted_at=prov.converted_at,+ details=d,+ )+++def _params_with_optional_legacy_payload(data: dict[str, Any]) -> dict[str, Any]:+ """+ 以 ``params`` 为真源;若存在顶层 ``payload`` 对象,将其键合并进 params(不覆盖已有键)。+ """+ p = dict(data.get("params") or {})+ raw = data.get("payload")+ if not isinstance(raw, dict) or not raw:+ return p+ for k, v in raw.items():+ if k in p:+ continue+ if v is None:+ continue+ if v == [] or v == {}:+ continue+ p[k] = v+ return p+++def _envelope_from_dict(data: dict[str, Any]) -> E2AEnvelope:+ prov = _provenance_from_dict(data.get("provenance"))+ prov = _migrate_legacy_binding(data, prov)++ origin = data.get("identity_origin", IdentityOrigin.USER.value)+ if isinstance(origin, str):+ origin = IdentityOrigin(origin)++ params = _params_with_optional_legacy_payload(data)++ auth_raw = data.get("auth")+ auth: E2AAuth | None+ if auth_raw is None:+ auth = None+ elif isinstance(auth_raw, E2AAuth):+ auth = auth_raw+ else:+ auth = E2AAuth(+ method_id=auth_raw.get("method_id"),+ bearer_token=auth_raw.get("bearer_token"),+ api_key_ref=auth_raw.get("api_key_ref"),+ credential_ref=auth_raw.get("credential_ref"),+ extra_headers=dict(auth_raw.get("extra_headers") or {}),+ _meta=dict(auth_raw.get("_meta") or {}),+ )++ channel_context = dict(data.get("channel_context") or {})+ if not channel_context and isinstance(data.get("metadata"), dict):+ channel_context = dict(data["metadata"])++ ch = data.get("channel")+ if ch is None:+ ch = data.get("channel_id")++ raw_method = data.get("method")+ if raw_method is None and "req_method" in data:+ rm = data["req_method"]+ if isinstance(rm, str):+ raw_method = rm+ elif hasattr(rm, "value"):+ raw_method = str(rm.value)++ return E2AEnvelope(+ protocol_version=data.get("protocol_version", E2A_PROTOCOL_VERSION),+ provenance=prov,+ request_id=data.get("request_id"),+ jsonrpc_id=data.get("jsonrpc_id"),+ correlation_id=data.get("correlation_id"),+ task_id=data.get("task_id"),+ context_id=data.get("context_id"),+ session_id=data.get("session_id"),+ message_id=data.get("message_id"),+ timestamp=_normalize_timestamp_value(data.get("timestamp")),+ identity_origin=origin,+ channel=ch,+ user_id=data.get("user_id"),+ source_agent_id=data.get("source_agent_id"),+ method=raw_method,+ params=params,+ ext_method=data.get("ext_method"),+ session_update_kind=data.get("session_update_kind"),+ is_stream=bool(data.get("is_stream", False)),+ expected_output_modes=list(data.get("expected_output_modes") or []),+ auth=auth,+ channel_context=channel_context,+ a2a_metadata=dict(data.get("a2a_metadata") or {}),+ acp_meta=dict(data.get("acp_meta") or {}),+ )+++def _e2a_response_from_dict(data: dict[str, Any]) -> E2AResponse:+ prov = _provenance_from_dict(data.get("provenance"))++ origin = data.get("identity_origin", IdentityOrigin.AGENT.value)+ if isinstance(origin, str):+ origin = IdentityOrigin(origin)++ seq_raw = data.get("sequence", 0)+ try:+ sequence = int(seq_raw) # type: ignore[arg-type]+ except (TypeError, ValueError):+ sequence = 0++ ch = data.get("channel")+ if ch is None:+ ch = data.get("channel_id")++ return E2AResponse(+ protocol_version=data.get("protocol_version", E2A_PROTOCOL_VERSION),+ response_id=data.get("response_id"),+ request_id=data.get("request_id"),+ sequence=sequence,+ is_final=bool(data.get("is_final", False)),+ status=str(data.get("status", E2A_RESPONSE_STATUS_IN_PROGRESS)),+ response_kind=str(data.get("response_kind") or ""),+ timestamp=_normalize_timestamp_value(data.get("timestamp")),+ provenance=prov,+ body=dict(data.get("body") or {}),+ jsonrpc_id=data.get("jsonrpc_id"),+ correlation_id=data.get("correlation_id"),+ task_id=data.get("task_id"),+ context_id=data.get("context_id"),+ session_id=data.get("session_id"),+ message_id=data.get("message_id"),+ is_stream=bool(data.get("is_stream", False)),+ identity_origin=origin,+ channel=ch,+ user_id=data.get("user_id"),+ source_agent_id=data.get("source_agent_id"),+ method=data.get("method"),+ projections=dict(data.get("projections") or {}),+ channel_context=dict(data.get("channel_context") or {}),+ metadata=dict(data.get("metadata") or {}),+ a2a_metadata=dict(data.get("a2a_metadata") or {}),+ acp_meta=dict(data.get("acp_meta") or {}),+ )+++def merge_params_to_acp_prompt(envelope: E2AEnvelope) -> dict[str, Any]:+ """+ 当 ``method == "session/prompt"`` 时,从 ``envelope.params`` 补全 ACP 所需 ``prompt``,返回新参数字典。++ 优先级:+ 1. 已有 ``params.prompt`` 则不修改。+ 2. 否则若有 ``params.content_blocks``(非空 list),用作 ``prompt``。+ 3. 否则用 ``params.text``、``params.content``、``params.query`` 中第一个非空字符串生成单条 text ContentBlock。++ 随后按需补 ``session_id``、``params._meta``(来自 ``envelope.acp_meta``)。+ """+ p = dict(envelope.params)+ if envelope.method != "session/prompt":+ return p+ if "prompt" in p:+ return p+ blocks: list[dict[str, Any]] = []+ cb = p.get("content_blocks")+ if isinstance(cb, list) and cb:+ blocks.extend(cb)+ else:+ text = p.get("text") or p.get("content") or p.get("query")+ if isinstance(text, str) and text:+ blocks.append({"type": "text", "text": text})+ if blocks:+ p["prompt"] = blocks+ if envelope.session_id and "session_id" not in p:+ p["session_id"] = envelope.session_id+ if envelope.acp_meta:+ p.setdefault("_meta", {}).update(envelope.acp_meta)+ return pdiff --git a/jiuwenclaw/e2a/wire_codec.py b/jiuwenclaw/e2a/wire_codec.pynew file mode 100644index 0000000000..7758b710f3--- /dev/null+++ b/jiuwenclaw/e2a/wire_codec.py@@ -0,0 +1,424 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""AgentServer ↔ Gateway WebSocket:E2AResponse 线编码 / 解码与 legacy 兜底。"""++from __future__ import annotations++import logging+from dataclasses import asdict+from typing import Any++from jiuwenclaw.e2a.constants import (+ E2A_RESPONSE_KIND_E2A_ERROR,+ E2A_RESPONSE_STATUS_FAILED,+ E2A_WIRE_LEGACY_AGENT_CHUNK_KEY,+ E2A_WIRE_LEGACY_AGENT_RESPONSE_KEY,+)+from jiuwenclaw.e2a.gateway_normalize import (+ e2a_response_from_agent_chunk,+ e2a_response_from_agent_response,+ e2a_response_to_agent_chunk,+ e2a_response_to_agent_response,+)+from jiuwenclaw.e2a.constants import E2A_SOURCE_PROTOCOL_E2A+from jiuwenclaw.e2a.models import (+ E2A_PROTOCOL_VERSION,+ E2AProvenance,+ E2AResponse,+ IdentityOrigin,+ utc_now_iso,+)+from jiuwenclaw.schema.agent import AgentResponse, AgentResponseChunk++logger = logging.getLogger(__name__)+++def _raw_dict_to_agent_response(data: dict[str, Any]) -> AgentResponse:+ return AgentResponse(+ request_id=str(data["request_id"]),+ channel_id=str(data.get("channel_id", "")),+ ok=bool(data.get("ok", True)),+ payload=data.get("payload"),+ metadata=data.get("metadata"),+ )+++def _raw_dict_to_agent_chunk(data: dict[str, Any]) -> AgentResponseChunk:+ return AgentResponseChunk(+ request_id=str(data["request_id"]),+ channel_id=str(data.get("channel_id", "")),+ payload=data.get("payload"),+ is_complete=bool(data.get("is_complete", False)),+ )+++def is_e2a_response_wire_dict(data: dict[str, Any]) -> bool:+ """判别 JSON 对象是否为 E2A 响应线格式(与 ``E2AEnvelope`` 区分:须含非空 ``response_kind``)。"""+ if not isinstance(data, dict) or data.get("type") == "event":+ return False+ if data.get("protocol_version") != E2A_PROTOCOL_VERSION:+ return False+ rk = data.get("response_kind")+ return isinstance(rk, str) and bool(rk.strip())+++def _deprecated_unary_shape(data: dict[str, Any]) -> bool:+ return (+ isinstance(data, dict)+ and "request_id" in data+ and "channel_id" in data+ and "ok" in data+ and not is_e2a_response_wire_dict(data)+ )+++def _deprecated_chunk_shape(data: dict[str, Any]) -> bool:+ return (+ isinstance(data, dict)+ and "request_id" in data+ and "channel_id" in data+ and "is_complete" in data+ and "payload" in data+ and "ok" not in data+ and not is_e2a_response_wire_dict(data)+ )+++def parse_agent_server_wire_unary(data: dict[str, Any]) -> AgentResponse:+ """将一条非流式 WebSocket JSON 解析为 ``AgentResponse``。"""+ rid = str(data.get("request_id", ""))+ if is_e2a_response_wire_dict(data):+ try:+ e2a = E2AResponse.from_dict(dict(data))+ except Exception as e:+ logger.exception(+ "[E2A][wire][in][FAIL] stage=from_dict unary request_id=%s err=%s",+ rid,+ e,+ )+ raise+ meta = dict(e2a.metadata or {})+ legacy = meta.get(E2A_WIRE_LEGACY_AGENT_RESPONSE_KEY)+ if legacy is not None and isinstance(legacy, dict):+ logger.warning(+ "[E2A][wire][in][fallback] unary request_id=%s response_id=%s legacy_key=%s json_bytes≈%s",+ rid,+ e2a.response_id,+ E2A_WIRE_LEGACY_AGENT_RESPONSE_KEY,+ len(str(legacy).encode("utf-8", errors="replace")),+ )+ return _raw_dict_to_agent_response(legacy)+ try:+ out = e2a_response_to_agent_response(e2a)+ logger.debug(+ "[E2A][wire][in] unary request_id=%s response_kind=%s",+ rid,+ e2a.response_kind,+ )+ return out+ except Exception as e:+ logger.exception(+ "[E2A][wire][in][FAIL] stage=inverse unary request_id=%s response_kind=%s err=%s",+ rid,+ e2a.response_kind,+ e,+ )+ legacy_inv = meta.get(E2A_WIRE_LEGACY_AGENT_RESPONSE_KEY)+ if isinstance(legacy_inv, dict):+ logger.warning(+ "[E2A][wire][in][fallback] unary inverse failed, using legacy blob request_id=%s",+ rid,+ )+ return _raw_dict_to_agent_response(legacy_inv)+ raise++ if _deprecated_unary_shape(data):+ logger.warning(+ "[E2A][wire][in][deprecated_legacy_shape] unary request_id=%s keys=%s",+ rid,+ list(data.keys())[:24],+ )+ return _raw_dict_to_agent_response(data)++ raise ValueError(f"parse_agent_server_wire_unary: unrecognized wire shape keys={list(data.keys())[:32]}")+++def parse_agent_server_wire_chunk(data: dict[str, Any]) -> AgentResponseChunk:+ """将一条流式 WebSocket JSON 解析为 ``AgentResponseChunk``。"""+ rid = str(data.get("request_id", ""))+ if is_e2a_response_wire_dict(data):+ try:+ e2a = E2AResponse.from_dict(dict(data))+ except Exception as e:+ logger.exception(+ "[E2A][wire][in][FAIL] stage=from_dict chunk request_id=%s err=%s",+ rid,+ e,+ )+ raise+ meta = dict(e2a.metadata or {})+ legacy = meta.get(E2A_WIRE_LEGACY_AGENT_CHUNK_KEY)+ if legacy is not None and isinstance(legacy, dict):+ logger.warning(+ "[E2A][wire][in][fallback] chunk request_id=%s response_id=%s legacy_key=%s json_bytes≈%s",+ rid,+ e2a.response_id,+ E2A_WIRE_LEGACY_AGENT_CHUNK_KEY,+ len(str(legacy).encode("utf-8", errors="replace")),+ )+ return _raw_dict_to_agent_chunk(legacy)+ try:+ out = e2a_response_to_agent_chunk(e2a)+ logger.debug(+ "[E2A][wire][in] chunk request_id=%s response_kind=%s is_final=%s",+ rid,+ e2a.response_kind,+ e2a.is_final,+ )+ return out+ except Exception as e:+ logger.exception(+ "[E2A][wire][in][FAIL] stage=inverse chunk request_id=%s response_kind=%s is_final=%s err=%s",+ rid,+ e2a.response_kind,+ e2a.is_final,+ e,+ )+ legacy_inv = meta.get(E2A_WIRE_LEGACY_AGENT_CHUNK_KEY)+ if isinstance(legacy_inv, dict):+ logger.warning(+ "[E2A][wire][in][fallback] chunk inverse failed, using legacy blob request_id=%s",+ rid,+ )+ return _raw_dict_to_agent_chunk(legacy_inv)+ raise++ if _deprecated_chunk_shape(data):+ logger.warning(+ "[E2A][wire][in][deprecated_legacy_shape] chunk request_id=%s keys=%s",+ rid,+ list(data.keys())[:24],+ )+ return _raw_dict_to_agent_chunk(data)++ raise ValueError(f"parse_agent_server_wire_chunk: unrecognized wire shape keys={list(data.keys())[:32]}")+++def encode_agent_response_for_wire(+ resp: AgentResponse,+ *,+ response_id: str,+ sequence: int = 0,+) -> dict[str, Any]:+ """``AgentResponse`` → E2A 线 dict;失败时 ``metadata`` 塞入整包 legacy 并记日志。"""+ rid = resp.request_id+ try:+ e2a = e2a_response_from_agent_response(+ resp, response_id=response_id, sequence=sequence+ )+ try:+ wire = e2a.to_dict()+ except Exception as te:+ logger.exception(+ "[E2A][wire][out][FAIL] stage=to_dict unary request_id=%s response_id=%s err=%s legacy_stashed=true",+ rid,+ response_id,+ te,+ )+ return _fallback_wire_unary_from_legacy(+ asdict(resp), response_id=response_id, sequence=sequence, exc=te+ )+ logger.info(+ "[E2A][wire][out] unary request_id=%s response_id=%s response_kind=%s legacy_stashed=false",+ rid,+ response_id,+ e2a.response_kind,+ )+ return wire+ except Exception as e:+ logger.exception(+ "[E2A][wire][out][FAIL] stage=encode unary request_id=%s response_id=%s err=%s legacy_stashed=true",+ rid,+ response_id,+ e,+ )+ return _fallback_wire_unary_from_legacy(+ asdict(resp), response_id=response_id, sequence=sequence, exc=e+ )+++def encode_agent_chunk_for_wire(+ chunk: AgentResponseChunk,+ *,+ response_id: str,+ sequence: int,+ is_stream: bool = True,+) -> dict[str, Any]:+ """``AgentResponseChunk`` → E2A 线 dict;失败时 ``metadata`` 塞入整包 legacy。"""+ rid = chunk.request_id+ try:+ e2a = e2a_response_from_agent_chunk(+ chunk,+ response_id=response_id,+ sequence=sequence,+ is_stream=is_stream,+ )+ try:+ wire = e2a.to_dict()+ except Exception as te:+ logger.exception(+ (+ "[E2A][wire][out][FAIL] stage=to_dict chunk request_id=%s response_id=%s "+ "seq=%s err=%s legacy_stashed=true"+ ),+ rid,+ response_id,+ sequence,+ te,+ )+ return _fallback_wire_chunk_from_legacy(+ asdict(chunk),+ response_id=response_id,+ sequence=sequence,+ exc=te,+ is_stream=is_stream,+ )+ logger.info(+ (+ "[E2A][wire][out] chunk request_id=%s response_id=%s seq=%s response_kind=%s "+ "is_final=%s legacy_stashed=false"+ ),+ rid,+ response_id,+ sequence,+ e2a.response_kind,+ e2a.is_final,+ )+ return wire+ except Exception as e:+ logger.exception(+ "[E2A][wire][out][FAIL] stage=encode chunk request_id=%s response_id=%s seq=%s err=%s legacy_stashed=true",+ rid,+ response_id,+ sequence,+ e,+ )+ return _fallback_wire_chunk_from_legacy(+ asdict(chunk),+ response_id=response_id,+ sequence=sequence,+ exc=e,+ is_stream=is_stream,+ )+++def _fallback_wire_unary_from_legacy(+ legacy: dict[str, Any],+ *,+ response_id: str,+ sequence: int,+ exc: BaseException,+) -> dict[str, Any]:+ ts = utc_now_iso()+ prov = E2AProvenance(+ source_protocol=E2A_SOURCE_PROTOCOL_E2A,+ converter="jiuwenclaw.e2a.wire_codec:_fallback_wire_unary_from_legacy",+ converted_at=ts,+ details={"error": str(exc), "kind": "wire_encode_fallback"},+ )+ e2a = E2AResponse(+ protocol_version=E2A_PROTOCOL_VERSION,+ response_id=response_id,+ request_id=str(legacy.get("request_id", "")),+ sequence=sequence,+ is_final=True,+ status=E2A_RESPONSE_STATUS_FAILED,+ response_kind=E2A_RESPONSE_KIND_E2A_ERROR,+ timestamp=ts,+ provenance=prov,+ body={+ "code": "E2A.WIRE_ENCODE_ERROR",+ "message": "Failed to encode AgentResponse as E2A; see metadata legacy blob",+ "details": {"error": str(exc)},+ },+ channel=str(legacy.get("channel_id") or "") or None,+ metadata={E2A_WIRE_LEGACY_AGENT_RESPONSE_KEY: legacy},+ identity_origin=IdentityOrigin.AGENT,+ is_stream=False,+ )+ return e2a.to_dict()+++def _fallback_wire_chunk_from_legacy(+ legacy: dict[str, Any],+ *,+ response_id: str,+ sequence: int,+ exc: BaseException,+ is_stream: bool,+) -> dict[str, Any]:+ ts = utc_now_iso()+ prov = E2AProvenance(+ source_protocol=E2A_SOURCE_PROTOCOL_E2A,+ converter="jiuwenclaw.e2a.wire_codec:_fallback_wire_chunk_from_legacy",+ converted_at=ts,+ details={"error": str(exc), "kind": "wire_encode_chunk_fallback"},+ )+ e2a = E2AResponse(+ protocol_version=E2A_PROTOCOL_VERSION,+ response_id=response_id,+ request_id=str(legacy.get("request_id", "")),+ sequence=sequence,+ is_final=bool(legacy.get("is_complete", False)),+ status=E2A_RESPONSE_STATUS_FAILED,+ response_kind=E2A_RESPONSE_KIND_E2A_ERROR,+ timestamp=ts,+ provenance=prov,+ body={+ "code": "E2A.WIRE_ENCODE_ERROR",+ "message": "Failed to encode AgentResponseChunk as E2A; see metadata legacy blob",+ "details": {"error": str(exc)},+ },+ channel=str(legacy.get("channel_id") or "") or None,+ metadata={E2A_WIRE_LEGACY_AGENT_CHUNK_KEY: legacy},+ identity_origin=IdentityOrigin.AGENT,+ is_stream=is_stream,+ )+ return e2a.to_dict()+++def encode_json_parse_error_wire(+ *,+ request_id: str,+ channel_id: str,+ message: str,+ response_id: str = "",+) -> dict[str, Any]:+ """入站 JSON 无法解析时发送的单帧 E2A 形错误(无 legacy blob)。"""+ ts = utc_now_iso()+ rid_out = response_id or (request_id or "invalid-json")+ e2a = E2AResponse(+ protocol_version=E2A_PROTOCOL_VERSION,+ response_id=rid_out,+ request_id=request_id or None,+ sequence=0,+ is_final=True,+ status=E2A_RESPONSE_STATUS_FAILED,+ response_kind=E2A_RESPONSE_KIND_E2A_ERROR,+ timestamp=ts,+ provenance=E2AProvenance(+ source_protocol=E2A_SOURCE_PROTOCOL_E2A,+ converter="jiuwenclaw.e2a.wire_codec:encode_json_parse_error_wire",+ converted_at=ts,+ details={"kind": "json_parse_error"},+ ),+ body={+ "code": "E2A.INVALID_JSON",+ "message": message,+ "details": {},+ },+ channel=channel_id or None,+ identity_origin=IdentityOrigin.AGENT,+ is_stream=False,+ )+ return e2a.to_dict()diff --git a/jiuwenclaw/gateway/agent_client.py b/jiuwenclaw/gateway/agent_client.pyindex 52ad4b8fa5..dc9d38098a 100644--- a/jiuwenclaw/gateway/agent_client.py+++ b/jiuwenclaw/gateway/agent_client.py@@ -11,7 +11,12 @@ from abc import ABC, abstractmethodfrom dataclasses import asdictfrom typing import Any, AsyncIterator-from jiuwenclaw.schema.agent import AgentRequest, AgentResponse, AgentResponseChunk+from jiuwenclaw.e2a.models import E2AEnvelope+from jiuwenclaw.e2a.wire_codec import (+ parse_agent_server_wire_chunk,+ parse_agent_server_wire_unary,+)+from jiuwenclaw.schema.agent import AgentResponse, AgentResponseChunklogger = logging.getLogger(__name__)@@ -39,46 +44,21 @@ class AgentServerClient(ABC):...@abstractmethod- async def send_request(self, request: AgentRequest) -> AgentResponse:- """发送请求,等待完整响应."""+ async def send_request(self, envelope: E2AEnvelope) -> AgentResponse:+ """发送 E2A 信封,等待完整响应."""...@abstractmethodasync def send_request_stream(- self, request: AgentRequest+ self, envelope: E2AEnvelope) -> AsyncIterator[AgentResponseChunk]:- """发送请求,流式接收响应."""+ """发送 E2A 信封,流式接收响应."""...-def _request_to_payload(request: AgentRequest) -> dict[str, Any]:- """将 AgentRequest 转为 WebSocket 发送的 JSON 载荷."""- payload = asdict(request)- # req_method 是 Enum,需要转为字符串值- if payload.get("req_method") is not None:- payload["req_method"] = payload["req_method"].value- return payload---def _payload_to_response(data: dict[str, Any]) -> AgentResponse:- """将服务端返回的 JSON 转为 AgentResponse."""- return AgentResponse(- request_id=data["request_id"],- channel_id=data["channel_id"],- ok=data.get("ok", True),- payload=data.get("payload"),- metadata=data.get("metadata"),- )---def _payload_to_chunk(data: dict[str, Any]) -> AgentResponseChunk:- """将服务端返回的 JSON 转为 AgentResponseChunk."""- return AgentResponseChunk(- request_id=data["request_id"],- channel_id=data["channel_id"],- payload=data.get("payload"),- is_complete=data.get("is_complete", False),- )+def _e2a_to_wire(envelope: E2AEnvelope) -> dict[str, Any]:+ """E2AEnvelope → WebSocket JSON(与 AgentServer from_dict 对齐)。"""+ return envelope.to_dict()class WebSocketAgentServerClient(AgentServerClient):@@ -86,9 +66,9 @@ class WebSocketAgentServerClient(AgentServerClient):基于 websockets 的 AgentServer WebSocket 客户端实现。协议约定:- - 发送:JSON 对象,字段为 AgentRequest 的键(含 is_stream)。- - 接收(非流式):一条 JSON 对象,对应 AgentResponse。- - 接收(流式):多条 JSON 对象,对应 AgentResponseChunk,最后一条 is_complete=True。+ - 发送:JSON 对象为 E2AEnvelope.to_dict()(含 protocol_version、method、channel、params、is_stream 等)。+ - 接收(非流式):一条 **E2AResponse** 线 JSON(或过渡期 legacy AgentResponse 形),解析为 AgentResponse。+ - 接收(流式):多条 E2AResponse 线 JSON(或 legacy chunk),解析为 AgentResponseChunk。"""def __init__(self, *, ping_interval: float | None = 30.0, ping_timeout: float | None = 300.0) -> None:@@ -208,47 +188,69 @@ class WebSocketAgentServerClient(AgentServerClient):if self._ws is None:raise RuntimeError("未连接 AgentServer,请先调用 connect(uri)")- async def send_request(self, request: AgentRequest) -> AgentResponse:+ async def send_request(self, envelope: E2AEnvelope) -> AgentResponse:self._ensure_connected()- logger.info("[WebSocketAgentServerClient] 发送请求(非流式) AgentRequest: %s", _to_json(asdict(request)))+ rid = envelope.request_id or ""+ logger.info(+ "[E2A][out][nostream] request_id=%s channel=%s method=%s is_stream=%s",+ rid,+ envelope.channel,+ envelope.method,+ envelope.is_stream,+ )+ logger.debug(+ "[WebSocketAgentServerClient] 发送请求(非流式) E2A: %s",+ _to_json(envelope.to_dict()),+ )# 创建该请求的消息队列queue = asyncio.Queue()- self._message_queues[request.request_id] = queue+ self._message_queues[rid] = queuetry:# 发送请求async with self._lock:- payload = _request_to_payload(request)+ payload = _e2a_to_wire(envelope)logger.info("[WebSocketAgentServerClient] 发送请求(非流式) payload: %s", _to_json(payload))await self._ws.send(json.dumps(payload, ensure_ascii=False))# 从队列中接收响应data = await queue.get()logger.info("[WebSocketAgentServerClient] 收到响应(非流式) raw: %s", json.dumps(data, ensure_ascii=False))- resp = _payload_to_response(data)+ resp = parse_agent_server_wire_unary(data)logger.info("[WebSocketAgentServerClient] 收到完整响应 AgentResponse: %s", _to_json(asdict(resp)))return respfinally:# 清理队列- if request.request_id in self._message_queues:- del self._message_queues[request.request_id]+ if rid in self._message_queues:+ del self._message_queues[rid]async def send_request_stream(- self, request: AgentRequest+ self, envelope: E2AEnvelope) -> AsyncIterator[AgentResponseChunk]:self._ensure_connected()- request.is_stream = True- logger.info("[WebSocketAgentServerClient] 发送请求(流式) AgentRequest: %s", _to_json(asdict(request)))+ envelope.is_stream = True+ rid = envelope.request_id or ""+ logger.info(+ "[E2A][out][stream] request_id=%s channel=%s method=%s is_stream=%s",+ rid,+ envelope.channel,+ envelope.method,+ envelope.is_stream,+ )+ logger.debug(+ "[WebSocketAgentServerClient] 发送请求(流式) E2A: %s",+ _to_json(envelope.to_dict()),+ )# 创建该请求的消息队列queue = asyncio.Queue()- self._message_queues[request.request_id] = queue+ self._message_queues[rid] = queuetry:# 发送请求async with self._lock:- payload = _request_to_payload(request)+ payload = _e2a_to_wire(envelope)logger.info("[WebSocketAgentServerClient] 发送请求(流式) payload: %s", _to_json(payload))await self._ws.send(json.dumps(payload, ensure_ascii=False))@@ -257,7 +259,7 @@ class WebSocketAgentServerClient(AgentServerClient):while True:data = await queue.get()logger.info("[WebSocketAgentServerClient] 收到流式事件 raw: %s", json.dumps(data, ensure_ascii=False))- chunk = _payload_to_chunk(data)+ chunk = parse_agent_server_wire_chunk(data)chunk_count += 1logger.info("[WebSocketAgentServerClient] 收到流式 chunk #%s AgentResponseChunk: %s",@@ -266,14 +268,14 @@ class WebSocketAgentServerClient(AgentServerClient):yield chunkif chunk.is_complete:break- logger.info("[WebSocketAgentServerClient] 流式响应结束: request_id=%s 共 %s 个 chunk", request.request_id, chunk_count)+ logger.info("[WebSocketAgentServerClient] 流式响应结束: request_id=%s 共 %s 个 chunk", rid, chunk_count)except asyncio.CancelledError:- logger.info("[WebSocketAgentServerClient] 流式接收被取消: request_id=%s", request.request_id)+ logger.info("[WebSocketAgentServerClient] 流式接收被取消: request_id=%s", rid)raisefinally:# 清理队列- if request.request_id in self._message_queues:- del self._message_queues[request.request_id]+ if rid in self._message_queues:+ del self._message_queues[rid]# ---------------------------------------------------------------------------@@ -283,40 +285,50 @@ class WebSocketAgentServerClient(AgentServerClient):async def mock_agent_server_handler(ws: Any) -> None:"""- 协议兼容的 Mock AgentServer 处理函数:根据 is_stream 回一条完整响应或多条 chunk;- 同一连接可处理多请求。可与 websockets.serve(..., host, port) 一起使用。+ 协议兼容的 Mock AgentServer:按 is_stream 回 E2AResponse 线 JSON(与生产 AgentServer 一致)。"""import websockets++ from jiuwenclaw.e2a.wire_codec import (+ encode_agent_chunk_for_wire,+ encode_agent_response_for_wire,+ )+try:while True:raw = await ws.recv()data = json.loads(raw)req_id = data.get("request_id", "")- ch_id = data.get("channel_id", "")+ ch_id = data.get("channel") or data.get("channel_id", "")params = data.get("params", {})is_stream = data.get("is_stream", False)params_str = json.dumps(params, ensure_ascii=False) if isinstance(params, dict) else str(params)if is_stream:- # 流式:发 3 个 chunk,最后 is_complete=Truefor i, part in enumerate(["流式-1 ", "流式-2 ", "流式-3(完)"]):- chunk = {- "request_id": req_id,- "channel_id": ch_id,- "payload": {"content": part},- "is_complete": i == 2,- }- await ws.send(json.dumps(chunk, ensure_ascii=False))+ chunk = AgentResponseChunk(+ request_id=req_id,+ channel_id=ch_id,+ payload={"content": part},+ is_complete=i == 2,+ )+ wire = encode_agent_chunk_for_wire(+ chunk, response_id=req_id, sequence=i+ )+ await ws.send(json.dumps(wire, ensure_ascii=False))else:- # 非流式:一条完整响应- resp = {- "request_id": req_id,- "channel_id": ch_id,- "ok": True,- "payload": {"content": f"Echo: {params_str}"},- "metadata": data.get("metadata"),- }- await ws.send(json.dumps(resp, ensure_ascii=False))+ meta = data.get("metadata") or data.get("channel_context")+ if meta is not None and not isinstance(meta, dict):+ meta = None+ resp = AgentResponse(+ request_id=req_id,+ channel_id=ch_id,+ ok=True,+ payload={"content": f"Echo: {params_str}"},+ metadata=dict(meta) if isinstance(meta, dict) else None,+ )+ wire = encode_agent_response_for_wire(resp, response_id=req_id)+ await ws.send(json.dumps(wire, ensure_ascii=False))except websockets.exceptions.ConnectionClosed:passexcept Exception as e:@@ -349,6 +361,8 @@ async def run_mock_agent_server(async def _run_verification() -> None:"""用内存 Mock 服务端验证 WebSocketAgentServerClient 的 connect/send_request/send_request_stream."""+ from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fields+port = 18765uri = f"ws://127.0.0.1:{port}"server = await run_mock_agent_server("127.0.0.1", port)@@ -359,7 +373,7 @@ async def _run_verification() -> None:await client.connect(uri)# 1. 非流式请求- req1 = AgentRequest(+ req1 = e2a_from_agent_fields(request_id="req-1",channel_id="ch-1",session_id="sess-1",@@ -372,7 +386,7 @@ async def _run_verification() -> None:logger.info("[main] 非流式验证通过: payload=%s", resp1.payload)# 2. 流式请求- req2 = AgentRequest(+ req2 = e2a_from_agent_fields(request_id="req-2",channel_id="ch-1",session_id="sess-1",diff --git a/jiuwenclaw/gateway/cron/scheduler.py b/jiuwenclaw/gateway/cron/scheduler.pyindex ba8afc847f..aff88180cc 100644--- a/jiuwenclaw/gateway/cron/scheduler.py+++ b/jiuwenclaw/gateway/cron/scheduler.py@@ -13,7 +13,7 @@ from jiuwenclaw.gateway.agent_client import AgentServerClientfrom jiuwenclaw.gateway.cron.models import CronJob, CronRunStatefrom jiuwenclaw.gateway.cron.store import CronJobStorefrom jiuwenclaw.gateway.message_handler import MessageHandler-from jiuwenclaw.schema.agent import AgentRequest+from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fieldsfrom jiuwenclaw.schema.message import EventType, Message, ReqMethodlogger = logging.getLogger(__name__)@@ -252,7 +252,7 @@ class CronSchedulerService:state.started_at = self._now_fn()try:ts = format(int(time.time() * 1000), "x")- req = AgentRequest(+ envelope = e2a_from_agent_fields(request_id=f"cron-{run_id}",channel_id="__cron__",session_id=f"cron_{ts}_{job.id}",@@ -272,7 +272,7 @@ class CronSchedulerService:timestamp=self._now_fn(),metadata={"cron": {"job_id": job.id, "run_id": run_id}},)- resp = await self._agent_client.send_request(req)+ resp = await self._agent_client.send_request(envelope)text = _extract_text_from_agent_payload(resp.payload)if not text:text = "[cron] 任务完成,但未返回可展示文本"diff --git a/jiuwenclaw/gateway/heartbeat.py b/jiuwenclaw/gateway/heartbeat.pyindex d9c9a5cef4..443a2759c2 100644--- a/jiuwenclaw/gateway/heartbeat.py+++ b/jiuwenclaw/gateway/heartbeat.py@@ -164,8 +164,8 @@ class GatewayHeartbeatService(IHeartbeat):logger.exception("Gateway heartbeat loop error: %s", e)async def _tick(self) -> None:- """执行一次探活:构造 AgentRequest 发往 AgentServer,不向 Channel 下发."""- from jiuwenclaw.schema.agent import AgentRequest+ """执行一次探活:构造 E2A 发往 AgentServer,不向 Channel 下发."""+ from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fields# 若当前时间不在 active_hours 配置范围内,则跳过本次心跳if not self._is_active_now():@@ -177,7 +177,7 @@ class GatewayHeartbeatService(IHeartbeat):request_id = f"heartbeat-{time.monotonic_ns()}"session_id = f"heartbeat_{time.monotonic_ns()}"- request = AgentRequest(+ envelope = e2a_from_agent_fields(request_id=request_id,channel_id=self._config.channel_id,session_id=session_id,@@ -186,11 +186,11 @@ class GatewayHeartbeatService(IHeartbeat):try:if self._config.timeout_seconds is not None and self._config.timeout_seconds > 0:resp = await asyncio.wait_for(- self._agent_client.send_request(request),+ self._agent_client.send_request(envelope),timeout=self._config.timeout_seconds,)else:- resp = await self._agent_client.send_request(request)+ resp = await self._agent_client.send_request(envelope)self._last_tick_at = time.time()self._last_tick_ok = Truepayload = resp.payload if isinstance(resp.payload, dict) else {}diff --git a/jiuwenclaw/gateway/message_handler.py b/jiuwenclaw/gateway/message_handler.pyindex 3216d9466b..d2295ab352 100644--- a/jiuwenclaw/gateway/message_handler.py+++ b/jiuwenclaw/gateway/message_handler.py@@ -29,8 +29,9 @@ class ChannelControlState:session_id: str | None = Nonemode: ChannelMode = ChannelMode.PLANif TYPE_CHECKING:+ from jiuwenclaw.e2a.models import E2AEnvelopefrom jiuwenclaw.gateway.agent_client import AgentServerClient- from jiuwenclaw.schema.agent import AgentRequest, AgentResponse, AgentResponseChunk+ from jiuwenclaw.schema.agent import AgentResponse, AgentResponseChunkfrom jiuwenclaw.schema.message import Message@@ -42,6 +43,10 @@ class MessageHandler(ABC):- _user_messages:Channel 发来的消息,由内部转发循环消费并调用 agent_client.send_request- _robot_messages:AgentServer 的响应,由 ChannelManager 消费并派发到对应 Channel+ AgentServer 经 WebSocket 下行 **E2AResponse** 线 JSON;``WebSocketAgentServerClient`` 内+ (``jiuwenclaw.e2a.wire_codec``)解析并还原为 ``AgentResponse`` / ``AgentResponseChunk``,+ 本类仍通过 ``_response_to_message`` / ``_chunk_to_message`` 转为 ``Message`` 供 Channel 消费。+单例模式:全局仅存在一个 MessageHandler 实例,可通过 MessageHandler(client) 或MessageHandler.get_instance(client) 获取。"""@@ -231,7 +236,7 @@ class MessageHandler(ABC):await self.publish_robot_messages(msg)def _handle_channel_control(self, msg: "Message") -> bool:- """处理 \new_session / \mode 指令.+ r"""处理 \new_session / \mode 指令.Returns:True: 该消息是控制指令,已处理完毕,不需要转发给 Agent。@@ -332,7 +337,7 @@ class MessageHandler(ABC):elif state.session_id:msg.session_id = state.session_id- # 将 mode 写入 params,后续 AgentRequest 会从 params["mode"] 里读取+ # 将 mode 写入 params,后续 E2A / Agent 侧从 params["mode"] 读取if msg.params is None:msg.params = {}if isinstance(msg.params, dict):@@ -387,19 +392,10 @@ class MessageHandler(ABC):return None@staticmethod- def _message_to_request(msg: "Message") -> "AgentRequest":- from jiuwenclaw.schema.agent import AgentRequest+ def message_to_e2a(msg: "Message") -> "E2AEnvelope":+ from jiuwenclaw.e2a.gateway_normalize import message_to_e2a_or_fallback- return AgentRequest(- request_id=msg.id,- channel_id=msg.channel_id,- session_id=msg.session_id,- req_method=msg.req_method,- params=msg.params,- is_stream=msg.is_stream,- timestamp=msg.timestamp,- metadata=msg.metadata,- )+ return message_to_e2a_or_fallback(msg)@staticmethod@@ -502,7 +498,7 @@ class MessageHandler(ABC):)@staticmethod- def _non_stream_rpc_may_run_parallel(req: "AgentRequest") -> bool:+ def _non_stream_rpc_may_run_parallel(env: "E2AEnvelope") -> bool:"""可与其它非流式 RPC 并发,不阻塞 _forward_loop。网关队列否则串行 await Agent,慢请求(如 SkillNet 搜索)会堵住后续的 skills.list 刷新。@@ -510,22 +506,22 @@ class MessageHandler(ABC):"""from jiuwenclaw.schema.message import ReqMethod- m = req.req_method- if m is None:+ m = env.method+ if not m:return Falsereturn m not in (- ReqMethod.CHAT_SEND,- ReqMethod.CHAT_RESUME,- ReqMethod.CHAT_CANCEL,- ReqMethod.CHAT_ANSWER,+ ReqMethod.CHAT_SEND.value,+ ReqMethod.CHAT_RESUME.value,+ ReqMethod.CHAT_CANCEL.value,+ ReqMethod.CHAT_ANSWER.value,)- async def _process_non_stream_request(self, msg: "Message", req: "AgentRequest") -> None:+ async def _process_non_stream_request(self, msg: "Message", env: "E2AEnvelope") -> None:"""执行单次非流式 Agent 请求并将结果写入 robot_messages(供串行或后台任务复用)。"""try:- resp = await self._agent_client.send_request(req)+ resp = await self._agent_client.send_request(env)out = self._response_to_message(- resp, session_id=msg.session_id, request_metadata=req.metadata+ resp, session_id=msg.session_id, request_metadata=msg.metadata)await self.publish_robot_messages(out)logger.info(@@ -601,8 +597,9 @@ class MessageHandler(ABC):# 3. 发送 supplement intent 到 AgentServer(取消任务但保留 todo)# 用 await 确保 agent 侧先完成取消再启动新任务- from jiuwenclaw.schema.agent import AgentRequest as _AgentReq- supplement_req = _AgentReq(+ from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fields++ supplement_env = e2a_from_agent_fields(request_id=f"supplement_{int(time.time() * 1000):x}",channel_id=msg.channel_id,session_id=msg.session_id,@@ -612,7 +609,7 @@ class MessageHandler(ABC):timestamp=time.time(),)try:- await self._send_interrupt_to_agent(supplement_req)+ await self._send_interrupt_to_agent(supplement_env)except Exception:pass # 即使失败也继续启动新任务@@ -620,6 +617,7 @@ class MessageHandler(ABC):from jiuwenclaw.schema.message import Messagenew_req_id = f"req_{int(time.time() * 1000):x}_{msg.id}"+ sup_meta = dict(msg.metadata) if msg.metadata else Nonenew_msg = Message(id=new_req_id,type="req",@@ -634,6 +632,11 @@ class MessageHandler(ABC):ok=True,req_method=ReqMethod.CHAT_SEND,is_stream=True,+ provider=msg.provider,+ chat_id=msg.chat_id,+ user_id=msg.user_id,+ bot_id=msg.bot_id,+ metadata=sup_meta,)self._user_messages.put_nowait(new_msg)logger.info(@@ -654,13 +657,13 @@ class MessageHandler(ABC):rid, msg.channel_id, sid, "cancel",)# Fire-and-forget: 发送取消请求到 AgentServer- req = self._message_to_request(msg)- asyncio.create_task(self._send_interrupt_to_agent(req))+ env_interrupt = self.message_to_e2a(msg)+ asyncio.create_task(self._send_interrupt_to_agent(env_interrupt))elif intent in ("pause", "resume"):# 暂停/恢复:不取消流式任务,转发给 AgentServer 处理 ReAct 循环- req = self._message_to_request(msg)- asyncio.create_task(self._send_interrupt_to_agent(req))+ env_interrupt = self.message_to_e2a(msg)+ asyncio.create_task(self._send_interrupt_to_agent(env_interrupt))# 通知前端状态变更await self._send_interrupt_result_notification(msg.id, msg.channel_id, msg.session_id, intent,@@ -672,30 +675,31 @@ class MessageHandler(ABC):"[MessageHandler] 从 user_messages 取出,发往 AgentServer: id=%s channel_id=%s is_stream=%s",msg.id, msg.channel_id, msg.is_stream,)- req = self._message_to_request(msg)+ env = self.message_to_e2a(msg)+ stream_rid = env.request_id or msg.idtry:- if req.is_stream:+ if env.is_stream:# 流式处理:启动后台任务,支持多任务并发# 通知前端新任务开始处理await self._send_processing_status(- req.request_id, msg.session_id, msg.channel_id, is_processing=True,+ stream_rid, msg.session_id, msg.channel_id, is_processing=True,)task = asyncio.create_task(- self._process_stream(req, msg.session_id)+ self.process_stream(env, msg.session_id, msg.metadata))- self._stream_tasks[req.request_id] = task- self._stream_sessions[req.request_id] = msg.session_id+ self._stream_tasks[stream_rid] = task+ self._stream_sessions[stream_rid] = msg.session_idlogger.info("[MessageHandler] Stream 任务已启动(后台运行): request_id=%s channel_id=%s 当前并发=%d",- req.request_id, req.channel_id, len(self._stream_tasks),+ stream_rid, msg.channel_id, len(self._stream_tasks),)# 不 await,让流式任务在后台运行,_forward_loop 继续处理下一个消息- elif self._non_stream_rpc_may_run_parallel(req):+ elif self._non_stream_rpc_may_run_parallel(env):# 非流式且非聊天:后台执行,避免慢 RPC(如 SkillNet)阻塞队列中的其它请求- method_label = req.req_method.value if req.req_method else "none"+ method_label = env.method or "none"asyncio.create_task(- self._process_non_stream_request(msg, req),- name=f"gw-nonstr-{method_label}-{req.request_id[:24]}",+ self._process_non_stream_request(msg, env),+ name=f"gw-nonstr-{method_label}-{stream_rid[:24]}",)logger.info("[MessageHandler] 非流式 RPC 已后台执行: id=%s method=%s",@@ -703,7 +707,7 @@ class MessageHandler(ABC):method_label,)else:- await self._process_non_stream_request(msg, req)+ await self._process_non_stream_request(msg, env)except Exception as e:logger.exception("AgentServer send_request failed for %s: %s", msg.id, e)err_msg = self._build_error_out_message(msg, e)@@ -715,15 +719,23 @@ class MessageHandler(ABC):except asyncio.CancelledError:break- async def _process_stream(self, req: "AgentRequest", session_id: str | None) -> None:+ async def process_stream(+ self,+ env: "E2AEnvelope",+ session_id: str | None,+ request_metadata: dict[str, Any] | None,+ ) -> None:"""处理流式请求,逐个 chunk 写入 robot_messages.这个方法被包装为 Task,在后台运行,可以被随时取消。+ 遥测可通过替换类上的 ``process_stream`` 进行打点。"""+ rid = env.request_id or ""+ channel_id = env.channel or ""cancelled = Falsehas_processing_status_false = False # 追踪 AgentServer 是否已发送 processing_status=falsetry:- async for chunk in self._agent_client.send_request_stream(req):+ async for chunk in self._agent_client.send_request_stream(env):# 跳过终止 chunk(仅作为流结束信号,不含实际数据)if chunk.is_complete and not chunk.payload:logger.debug(@@ -740,7 +752,7 @@ class MessageHandler(ABC):has_processing_status_false = Trueout = self._chunk_to_message(- chunk, session_id=session_id, metadata=req.metadata+ chunk, session_id=session_id, metadata=request_metadata)await self.publish_robot_messages(out)logger.debug(@@ -749,28 +761,28 @@ class MessageHandler(ABC):)logger.info("[MessageHandler] Stream 正常完成: request_id=%s",- req.request_id,+ rid,)except asyncio.CancelledError:cancelled = Truelogger.info("[MessageHandler] Stream 被取消: request_id=%s",- req.request_id,+ rid,)raise # 重新抛出,让调用者知道任务被取消finally:# 清理状态- self._stream_tasks.pop(req.request_id, None)- self._stream_sessions.pop(req.request_id, None)+ self._stream_tasks.pop(rid, None)+ self._stream_sessions.pop(rid, None)logger.debug("[MessageHandler] Stream 任务状态已清理: request_id=%s",- req.request_id,+ rid,)# 所有流式任务正常结束后,通知前端全部处理完成# 只有当 AgentServer 没有发送过 processing_status=false 时才发送if not cancelled and not self._stream_tasks and not has_processing_status_false:await self._send_processing_status(- req.request_id, session_id, req.channel_id, is_processing=False,+ rid, session_id, channel_id, is_processing=False,)logger.info("[MessageHandler] 所有流式任务已完成,已发送 is_processing=false: session_id=%s",@@ -809,10 +821,10 @@ class MessageHandler(ABC):request_id,)- async def _send_interrupt_to_agent(self, req: "AgentRequest") -> None:+ async def _send_interrupt_to_agent(self, env: "E2AEnvelope") -> None:"""Fire-and-forget: 发送中断请求到 AgentServer,不阻塞转发循环."""try:- resp = await self._agent_client.send_request(req)+ resp = await self._agent_client.send_request(env)logger.info("[MessageHandler] AgentServer 中断响应(已丢弃): request_id=%s ok=%s",resp.request_id, resp.ok,diff --git a/jiuwenclaw/telemetry/instrumentors/entry.py b/jiuwenclaw/telemetry/instrumentors/entry.pyindex 4611cd4399..4eaf7e20ed 100644--- a/jiuwenclaw/telemetry/instrumentors/entry.py+++ b/jiuwenclaw/telemetry/instrumentors/entry.py@@ -1,10 +1,11 @@# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.-"""Instrumentor for MessageHandler._process_stream — ENTRY span."""+"""Instrumentor for MessageHandler.process_stream — ENTRY span."""from __future__ import annotationsimport time+from typing import Anyfrom opentelemetry import tracefrom opentelemetry.trace import StatusCode@@ -30,46 +31,48 @@ def instrument_entry() -> None:logger.debug("[Telemetry] MessageHandler not available, skipping entry instrumentor")return- _original_process_stream = MessageHandler._process_stream- _original_message_to_request = MessageHandler._message_to_request+ _original_process_stream = MessageHandler.process_stream+ _original_message_to_e2a = MessageHandler.message_to_e2a@staticmethod- def _traced_message_to_request(msg):- request = _original_message_to_request(msg)- # Inject W3C TraceContext into request.metadata for cross-WebSocket propagation- if request.metadata is None:- request.metadata = {}- inject_trace_context(request.metadata)- return request+ def _traced_message_to_e2a(msg):+ envelope = _original_message_to_e2a(msg)+ # Inject W3C TraceContext into E2A channel_context for cross-WebSocket propagation+ inject_trace_context(envelope.channel_context)- async def _traced_process_stream(self, req, session_id):+ return envelope++ async def _traced_process_stream(+ self,+ env,+ session_id,+ request_metadata: dict[str, Any] | None = None,+ ):with _tracer.start_as_current_span("channel.request",attributes={- JIUWENCLAW_CHANNEL_ID: req.channel_id or "",+ JIUWENCLAW_CHANNEL_ID: env.channel or "",JIUWENCLAW_SESSION_ID: session_id or "",- JIUWENCLAW_REQUEST_ID: req.request_id or "",+ JIUWENCLAW_REQUEST_ID: env.request_id or "",GEN_AI_SPAN_TYPE: "workflow",},) as span:# Re-inject after span is created so the correct trace_id is propagated- if req.metadata is None:- req.metadata = {}- inject_trace_context(req.metadata)+ inject_trace_context(env.channel_context)- request_count.add(1, {JIUWENCLAW_CHANNEL_ID: req.channel_id or ""})+ request_count.add(1, {JIUWENCLAW_CHANNEL_ID: env.channel or ""})start = time.monotonic()try:- await _original_process_stream(self, req, session_id)+ await _original_process_stream(self, env, session_id, request_metadata)span.set_status(StatusCode.OK)except Exception as exc:span.set_status(StatusCode.ERROR, str(exc)[:256])span.record_exception(exc)- request_error_count.add(1, {JIUWENCLAW_CHANNEL_ID: req.channel_id or ""})+ request_error_count.add(1, {JIUWENCLAW_CHANNEL_ID: env.channel or ""})raisefinally:duration = time.monotonic() - start- request_duration.record(duration, {JIUWENCLAW_CHANNEL_ID: req.channel_id or ""})+ request_duration.record(duration, {JIUWENCLAW_CHANNEL_ID: env.channel or ""})- MessageHandler._message_to_request = _traced_message_to_request- MessageHandler._process_stream = _traced_process_stream+ MessageHandler.message_to_e2a = _traced_message_to_e2a+ MessageHandler.process_stream = _traced_process_streamdiff --git a/jiuwenclaw/web/src/App.tsx b/jiuwenclaw/web/src/App.tsxindex 50d0178758..f96f51a3dd 100644--- a/jiuwenclaw/web/src/App.tsx+++ b/jiuwenclaw/web/src/App.tsx@@ -19,6 +19,7 @@ import { ChannelsPanel } from './components/ChannelsPanel';import { BrowserPanel } from './components/BrowserPanel';import { UpdatePanel } from './components/UpdatePanel';import { StatusBar } from './components/StatusBar';+import { FEATURE_APP_UPDATER_UI } from './featureFlags';import { HeartbeatMessageModal } from './features/HeartbeatMessageModal';import {beginHistoryRestore,@@ -249,6 +250,12 @@ function AppContent() {setConfigInitialExpandGroup(null);}}, [activeNav]);++ useEffect(() => {+ if (!FEATURE_APP_UPDATER_UI && activeNav === 'updatepanel') {+ setActiveNav('chat');+ }+ }, [activeNav]);const restartAutoCloseTimerRef = useRef<number | null>(null);const newSessionToastTimerRef = useRef<number | null>(null);const heartbeatToastTimerRef = useRef<number | null>(null);@@ -259,9 +266,13 @@ function AppContent() {totalPages: number;} | null>(null);const [historyLoadingMore, setHistoryLoadingMore] = useState(false);+ /** 仅用于强制重跑「首屏 history」effect:从会话列表恢复时若 sessionId 未变,也要重新拉 history 并恢复 historyPagerMeta */+ const [historyBootstrapKey, setHistoryBootstrapKey] = useState(0);const sessionIdRef = useRef(sessionId);const historyRestoreHandleRef = useRef<HistoryRestoreHandle | null>(null);const historyPageHandleRef = useRef<HistoryRestoreHandle | null>(null);+ /** 为 true 表示刚从「会话列表」恢复;history 为空时在 useEffect 的 onEmpty 中提示一次 */+ const historyRestoreFromPanelHintRef = useRef(false);const disposeInFlightHistoryHandles = useCallback(() => {historyRestoreHandleRef.current?.dispose();@@ -360,7 +371,7 @@ function AppContent() {}, [request, t]);useEffect(() => {- if (!isConnected || startupUpdateCheckRef.current) {+ if (!FEATURE_APP_UPDATER_UI || !isConnected || startupUpdateCheckRef.current) {return;}startupUpdateCheckRef.current = true;@@ -515,6 +526,7 @@ function AppContent() {if (sessionIdRef.current !== sessionId) {return;}+ historyRestoreFromPanelHintRef.current = false;clearMessages();messages.forEach((message) => addMessage(message));setHistoryPagerMeta({@@ -534,6 +546,15 @@ function AppContent() {loadedPages: 1,totalPages: emptyTotalPages ?? 1,});+ if (historyRestoreFromPanelHintRef.current) {+ historyRestoreFromPanelHintRef.current = false;+ addMessage({+ id: `history-restore-empty-${Date.now()}`,+ role: 'system',+ content: t('sessions.restoreEmpty'),+ timestamp: new Date().toISOString(),+ });+ }historyRestoreHandleRef.current = null;},onToolReplay: (items) => {@@ -583,6 +604,7 @@ function AppContent() {page_idx: 1,});} catch (error) {+ historyRestoreFromPanelHintRef.current = false;restoreHandle.dispose();historyRestoreHandleRef.current = null;setHistoryPagerMeta(null);@@ -600,7 +622,19 @@ function AppContent() {}}})();- }, [isConnected, sessionId, request, t, addMessage, addToolCall, addToolResult, clearMessages, clearSubtasks, disposeInFlightHistoryHandles]);+ }, [+ isConnected,+ sessionId,+ historyBootstrapKey,+ request,+ t,+ addMessage,+ addToolCall,+ addToolResult,+ clearMessages,+ clearSubtasks,+ disposeInFlightHistoryHandles,+ ]);// 新建会话:立即生成可用的 session_id,避免停留在 'new' 导致无法发送消息const handleNewSession = useCallback(async () => {@@ -789,7 +823,7 @@ function AppContent() {]);const handleRestoreSession = useCallback(- async (targetSessionId: string) => {+ (targetSessionId: string) => {if (!targetSessionId.startsWith('sess_')) return;disposeInFlightHistoryHandles();@@ -801,118 +835,29 @@ function AppContent() {clearMessages();clearTodos();clearSubtasks();+ historyRestoreFromPanelHintRef.current = true;setSessionId(targetSessionId);setCurrentSession(null);storeSessionId(targetSessionId);setActiveNav('chat');-- const restoreHandle = beginHistoryRestore({- sessionId: targetSessionId,- onReady: (messages, totalPages) => {- if (sessionIdRef.current !== targetSessionId) {- return;- }- messages.forEach((message) => addMessage(message));- setHistoryPagerMeta({- loadedPages: 1,- totalPages: totalPages ?? 1,- });- queueMicrotask(() => {- historyRestoreHandleRef.current = null;- });- },- onEmpty: (emptyTotalPages) => {- if (sessionIdRef.current !== targetSessionId) {- return;- }- setHistoryPagerMeta({- loadedPages: 1,- totalPages: emptyTotalPages ?? 1,- });- addMessage({- id: `history-restore-empty-${Date.now()}`,- role: 'system',- content: t('sessions.restoreEmpty'),- timestamp: new Date().toISOString(),- });- historyRestoreHandleRef.current = null;- },- onToolReplay: (items) => {- if (sessionIdRef.current !== targetSessionId) {- return;- }- for (const item of items) {- if (item.kind === 'tool_call') {- const n = normalizeToolCallPayload(item.payload);- addToolCall(- {- id: n.id,- name: n.name,- arguments: n.arguments,- description: n.description,- formatted_args: n.formatted_args,- },- { startedAt: item.at }- );- } else {- const n = normalizeToolResultPayload(item.payload);- addToolResult(- {- toolName: n.toolName,- result: n.result,- success: n.success,- toolCallId: n.toolCallId,- summary: n.summary,- },- { updatedAt: item.at }- );- }- }- },- onError: (message) => {- console.warn('[history.restore]', message);- },- });- historyRestoreHandleRef.current = restoreHandle;-- try {- await request(HISTORY_GET_METHOD, {- session_id: targetSessionId,- page_idx: 1,- });- } catch (error) {- restoreHandle.dispose();- historyRestoreHandleRef.current = null;- setHistoryPagerMeta(null);- console.error('Failed to restore history:', error);- if (sessionIdRef.current === targetSessionId) {- addMessage({- id: `history-restore-failed-${Date.now()}`,- role: 'system',- content: t('sessions.errors.restoreFailed', { sessionId: targetSessionId }),- timestamp: new Date().toISOString(),- });- }- }+ // 历史加载只由下方 useEffect 发起一次。若 sessionId 与当前相同,须 bump key 才会重跑 effect,+ // 否则 historyPagerMeta 会停在 null,无法向上滚动加载更早分页。+ setHistoryBootstrapKey((k) => k + 1);+ // 勿在此处再 beginHistoryRestore + history.get:会与 effect 并发双份 history.get,消息重复。},[- addMessage,- addToolCall,- addToolResult,clearMessages,clearSubtasks,clearTodos,disposeInFlightHistoryHandles,- request,setActiveNav,setCurrentSession,- setHistoryPagerMeta,setHistoryLoadingMore,+ setHistoryPagerMeta,setPaused,setProcessing,setSessionId,setThinking,- t,]);@@ -982,7 +927,7 @@ function AppContent() {{activeNav === 'chat' && (<>- <div className="flex-1 flex overflow-hidden">+ <div className="flex-1 flex min-h-0 overflow-hidden">{/* Chat Panel */}<div className="flex-1 flex flex-col min-w-0 min-h-0"><div className="flex-1 min-h-0">@@ -1064,7 +1009,7 @@ function AppContent() {<BrowserPanel isConnected={isConnected} request={request} /></div>)}- {activeNav === 'updatepanel' && (+ {FEATURE_APP_UPDATER_UI && activeNav === 'updatepanel' && (<div className="app-section"><UpdatePanel isConnected={isConnected} request={request} /></div>diff --git a/jiuwenclaw/web/src/components/ChatPanel/index.tsx b/jiuwenclaw/web/src/components/ChatPanel/index.tsxindex 6a234b54d2..11dcdb7c43 100644--- a/jiuwenclaw/web/src/components/ChatPanel/index.tsx+++ b/jiuwenclaw/web/src/components/ChatPanel/index.tsx@@ -127,8 +127,11 @@ export function ChatPanel({);return (- <div className="flex flex-col h-full" data-testid="chat-panel">- <div ref={scrollContainerRef} className="flex-1 overflow-y-auto px-3 py-4">+ <div className="flex flex-col h-full min-h-0" data-testid="chat-panel">+ <div+ ref={scrollContainerRef}+ className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden px-3 py-4"+ >{historyPager && messages.length > 0 ? (<HistoryPagerBarloadedPages={historyPager.loadedPages}diff --git a/jiuwenclaw/web/src/components/SessionSidebar/index.tsx b/jiuwenclaw/web/src/components/SessionSidebar/index.tsxindex 72c48d5867..217dd87c72 100644--- a/jiuwenclaw/web/src/components/SessionSidebar/index.tsx+++ b/jiuwenclaw/web/src/components/SessionSidebar/index.tsx@@ -5,6 +5,7 @@*/import { useTranslation } from 'react-i18next';+import { FEATURE_APP_UPDATER_UI } from '../../featureFlags';import { OffloadFilesWidget } from './OffloadFilesWidget';import './SessionSidebar.css';@@ -135,16 +136,18 @@ export function SessionSidebar({</svg>{t('nav.logs')}</button>- <button- onClick={() => onNavigate('updatepanel')}- className={`nav-item w-full ${activeNav === 'updatepanel' ? 'active' : ''}`}- >- <svg className="w-4 h-4 nav-item__icon" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={1.5}>- <path strokeLinecap="round" strokeLinejoin="round" d="M12 16.5V3.75m0 0L7.5 8.25M12 3.75l4.5 4.5" />- <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 15.75v1.5A2.25 2.25 0 006 19.5h12a2.25 2.25 0 002.25-2.25v-1.5" />- </svg>- {t('nav.update')}- </button>+ {FEATURE_APP_UPDATER_UI && (+ <button+ onClick={() => onNavigate('updatepanel')}+ className={`nav-item w-full ${activeNav === 'updatepanel' ? 'active' : ''}`}+ >+ <svg className="w-4 h-4 nav-item__icon" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={1.5}>+ <path strokeLinecap="round" strokeLinejoin="round" d="M12 16.5V3.75m0 0L7.5 8.25M12 3.75l4.5 4.5" />+ <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 15.75v1.5A2.25 2.25 0 006 19.5h12a2.25 2.25 0 002.25-2.25v-1.5" />+ </svg>+ {t('nav.update')}+ </button>+ )}</div><div className="flex-1" />diff --git a/tests/unit_tests/e2a/test_gateway_normalize.py b/tests/unit_tests/e2a/test_gateway_normalize.pynew file mode 100644index 0000000000..488aade097--- /dev/null+++ b/tests/unit_tests/e2a/test_gateway_normalize.py@@ -0,0 +1,89 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++import time++from jiuwenclaw.e2a.agent_compat import e2a_to_agent_request+from jiuwenclaw.e2a.gateway_normalize import (+ E2A_FALLBACK_FAILED_KEY,+ E2A_INTERNAL_CONTEXT_KEY,+ E2A_LEGACY_AGENT_REQUEST_KEY,+ build_fallback_e2a,+ channel_context_for_channel_reply,+ e2a_from_agent_fields,+ message_to_e2a_or_fallback,+ message_to_legacy_agent_dict,+)+from jiuwenclaw.schema.message import Message, ReqMethod+++def test_message_to_e2a_or_fallback_basic():+ msg = Message(+ id="r1",+ type="req",+ channel_id="web",+ session_id="s1",+ params={"query": "hi"},+ timestamp=time.time(),+ ok=True,+ req_method=ReqMethod.CHAT_SEND,+ is_stream=False,+ metadata={"method": "chat.send", "query": {}},+ )+ env = message_to_e2a_or_fallback(msg)+ assert env.request_id == "r1"+ assert env.channel == "web"+ assert env.method == "chat.send"+ assert env.params == {"query": "hi"}+ assert env.channel_context.get("method") == "chat.send"+++def test_e2a_to_agent_request_roundtrip():+ msg = Message(+ id="r2",+ type="req",+ channel_id="wecom",+ session_id="s2",+ params={"content": "x"},+ timestamp=time.time(),+ ok=True,+ req_method=ReqMethod.CHAT_SEND,+ is_stream=True,+ metadata={"wecom_req_id": "abc"},+ )+ env = message_to_e2a_or_fallback(msg)+ req = e2a_to_agent_request(env)+ assert req.request_id == "r2"+ assert req.channel_id == "wecom"+ assert req.req_method == ReqMethod.CHAT_SEND+ assert req.metadata == {"wecom_req_id": "abc"}+++def test_channel_context_for_channel_reply_strips_internal():+ env = e2a_from_agent_fields(+ request_id="x",+ channel_id="web",+ metadata={"a": 1},+ )+ env.channel_context[E2A_INTERNAL_CONTEXT_KEY] = {E2A_FALLBACK_FAILED_KEY: True}+ out = channel_context_for_channel_reply(env)+ assert out == {"a": 1}+ assert E2A_INTERNAL_CONTEXT_KEY not in out+++def test_build_fallback_and_legacy_keys():+ legacy = message_to_legacy_agent_dict(+ Message(+ id="fb",+ type="req",+ channel_id="web",+ session_id="s",+ params={"k": 1},+ timestamp=1.0,+ ok=True,+ req_method=ReqMethod.HISTORY_GET,+ )+ )+ env = build_fallback_e2a(legacy)+ inner = env.channel_context[E2A_INTERNAL_CONTEXT_KEY]+ assert inner[E2A_FALLBACK_FAILED_KEY] is True+ assert inner[E2A_LEGACY_AGENT_REQUEST_KEY]["req_method"] == "history.get"diff --git a/tests/unit_tests/e2a/test_wire_codec.py b/tests/unit_tests/e2a/test_wire_codec.pynew file mode 100644index 0000000000..ce73f97ae3--- /dev/null+++ b/tests/unit_tests/e2a/test_wire_codec.py@@ -0,0 +1,179 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""E2A WebSocket 线编码 / 解码与 round-trip。"""++from __future__ import annotations++from dataclasses import asdict++import pytest++from jiuwenclaw.e2a.constants import E2A_WIRE_LEGACY_AGENT_RESPONSE_KEY+from jiuwenclaw.e2a.gateway_normalize import (+ e2a_response_from_agent_chunk,+ e2a_response_from_agent_response,+ e2a_response_to_agent_chunk,+ e2a_response_to_agent_response,+)+from jiuwenclaw.e2a.wire_codec import (+ encode_agent_chunk_for_wire,+ encode_agent_response_for_wire,+ parse_agent_server_wire_chunk,+ parse_agent_server_wire_unary,+)+from jiuwenclaw.schema.agent import AgentResponse, AgentResponseChunk+++def test_roundtrip_unary_ok() -> None:+ orig = AgentResponse(+ request_id="r1",+ channel_id="c1",+ ok=True,+ payload={"a": 1},+ metadata={"m": 2},+ )+ wire = encode_agent_response_for_wire(orig, response_id="r1")+ back = parse_agent_server_wire_unary(wire)+ assert back.request_id == orig.request_id+ assert back.channel_id == orig.channel_id+ assert back.ok is True+ assert back.payload == orig.payload+ assert back.metadata == orig.metadata+++def test_roundtrip_unary_error() -> None:+ orig = AgentResponse(+ request_id="r2",+ channel_id="c2",+ ok=False,+ payload={"error": "x", "code": 9},+ )+ wire = encode_agent_response_for_wire(orig, response_id="r2")+ back = parse_agent_server_wire_unary(wire)+ assert back.ok is False+ assert back.payload == orig.payload+++def test_roundtrip_chunk_sentinel_complete() -> None:+ orig = AgentResponseChunk(+ request_id="s1",+ channel_id="c",+ payload={"is_complete": True},+ is_complete=True,+ )+ wire = encode_agent_chunk_for_wire(orig, response_id="s1", sequence=0)+ back = parse_agent_server_wire_chunk(wire)+ assert back.is_complete is True+ assert back.payload == {"is_complete": True}+++def test_roundtrip_chunk_chat_delta() -> None:+ orig = AgentResponseChunk(+ request_id="s2",+ channel_id="c",+ payload={+ "event_type": "chat.delta",+ "content": "hi",+ "source_chunk_type": "llm_reasoning",+ },+ is_complete=False,+ )+ wire = encode_agent_chunk_for_wire(orig, response_id="s2", sequence=1)+ back = parse_agent_server_wire_chunk(wire)+ assert back.is_complete is False+ assert back.payload.get("event_type") == "chat.delta"+ assert back.payload.get("content") == "hi"+ assert back.payload.get("source_chunk_type") == "llm_reasoning"+++def test_roundtrip_chunk_custom_event() -> None:+ orig = AgentResponseChunk(+ request_id="s3",+ channel_id="c",+ payload={"event_type": "history.message", "message": {"id": 1}},+ is_complete=False,+ )+ wire = encode_agent_chunk_for_wire(orig, response_id="s3", sequence=0)+ back = parse_agent_server_wire_chunk(wire)+ assert back.payload.get("event_type") == "history.message"+ assert back.payload.get("message") == {"id": 1}+++def test_roundtrip_chunk_chat_error() -> None:+ orig = AgentResponseChunk(+ request_id="s4",+ channel_id="c",+ payload={"event_type": "chat.error", "error": "boom"},+ is_complete=True,+ )+ wire = encode_agent_chunk_for_wire(orig, response_id="s4", sequence=2)+ back = parse_agent_server_wire_chunk(wire)+ assert back.is_complete is True+ assert back.payload.get("event_type") == "chat.error"+ assert back.payload.get("error") == "boom"+++def test_deprecated_legacy_unary_dict() -> None:+ d = {+ "request_id": "old",+ "channel_id": "ch",+ "ok": True,+ "payload": {"x": 1},+ }+ back = parse_agent_server_wire_unary(d)+ assert back.request_id == "old"+ assert back.payload == {"x": 1}+++def test_deprecated_legacy_chunk_dict() -> None:+ d = {+ "request_id": "oldc",+ "channel_id": "ch",+ "payload": {"content": "z"},+ "is_complete": False,+ }+ back = parse_agent_server_wire_chunk(d)+ assert back.request_id == "oldc"+ assert back.payload == {"content": "z"}+++def test_parse_unary_prefers_metadata_legacy_blob() -> None:+ legacy = asdict(+ AgentResponse(+ request_id="blob",+ channel_id="c",+ ok=True,+ payload={"recovered": True},+ )+ )+ e2a = e2a_response_from_agent_response(+ AgentResponse(+ request_id="blob",+ channel_id="c",+ ok=False,+ payload={"error": "wire"},+ ),+ response_id="blob",+ )+ meta = dict(e2a.metadata or {})+ meta[E2A_WIRE_LEGACY_AGENT_RESPONSE_KEY] = legacy+ e2a.metadata = meta+ wire = e2a.to_dict()+ back = parse_agent_server_wire_unary(wire)+ assert back.ok is True+ assert back.payload == {"recovered": True}+++def test_inverse_raises_for_chunk_shape_on_unary_parser() -> None:+ chunk_wire = encode_agent_chunk_for_wire(+ AgentResponseChunk(+ request_id="u",+ channel_id="c",+ payload={"content": "x"},+ is_complete=False,+ ),+ response_id="u",+ sequence=0,+ )+ with pytest.raises(ValueError):+ parse_agent_server_wire_unary(chunk_wire)diff --git a/tests/unit_tests/telemetry/test_telemetry_regression.py b/tests/unit_tests/telemetry/test_telemetry_regression.pyindex ce81e6950d..e70525f7f6 100644--- a/tests/unit_tests/telemetry/test_telemetry_regression.py+++ b/tests/unit_tests/telemetry/test_telemetry_regression.py@@ -74,21 +74,12 @@ def _build_fake_gateway_modules() -> dict[str, types.ModuleType]:class MessageHandler:@staticmethod- def _message_to_request(msg):- from jiuwenclaw.schema.agent import AgentRequest-- return AgentRequest(- request_id=msg.id,- channel_id=msg.channel_id,- session_id=msg.session_id,- req_method=msg.req_method,- params=msg.params,- is_stream=msg.is_stream,- timestamp=msg.timestamp,- metadata=msg.metadata,- )+ def message_to_e2a(msg):+ from jiuwenclaw.e2a.gateway_normalize import message_to_e2a_or_fallback++ return message_to_e2a_or_fallback(msg)- async def _process_stream(self, req, session_id):+ async def process_stream(self, env, session_id, request_metadata=None):return Nonemessage_handler_module.MessageHandler = MessageHandler@@ -255,14 +246,14 @@ def _patched_regression_modules():class TestTelemetryRegression:@staticmethod- def test_entry_message_to_request_preserves_fields_and_existing_metadata():+ def test_entry_message_to_e2a_preserves_fields_and_existing_channel_context():with _patched_regression_modules():from jiuwenclaw.gateway.message_handler import MessageHandlerfrom jiuwenclaw.schema.message import Message, ReqMethodfrom jiuwenclaw.telemetry.instrumentors.entry import instrument_entry- original_process_stream = MessageHandler._process_stream- original_message_to_request = MessageHandler._message_to_request+ original_process_stream = MessageHandler.process_stream+ original_message_to_e2a = MessageHandler.message_to_e2atry:with patch(@@ -284,17 +275,17 @@ class TestTelemetryRegression:metadata={"source": "ui"},)- req = MessageHandler._message_to_request(msg)+ env = MessageHandler.message_to_e2a(msg)- assert req.request_id == "req_001"- assert req.channel_id == "web"- assert req.session_id == "sess_001"- assert req.params == {"query": "hello"}- assert req.metadata["source"] == "ui"- assert req.metadata["traceparent"] == "test-trace"+ assert env.request_id == "req_001"+ assert env.channel == "web"+ assert env.session_id == "sess_001"+ assert env.params == {"query": "hello"}+ assert env.channel_context["source"] == "ui"+ assert env.channel_context["traceparent"] == "test-trace"finally:- MessageHandler._process_stream = original_process_stream- MessageHandler._message_to_request = original_message_to_request+ MessageHandler.process_stream = original_process_stream+ MessageHandler.message_to_e2a = original_message_to_e2a@staticmethoddef test_agent_stream_wrapper_preserves_chunk_sequence():diff --git a/uv.lock b/uv.lockindex f1bfc46642..199ff4e562 100644--- a/uv.lock+++ b/uv.lock@@ -1471,7 +1471,7 @@ requires-dist = [{ name = "ruamel-yaml", specifier = ">=0.18.0" },{ name = "skillnet-ai", specifier = "==0.0.16" },{ name = "websockets", specifier = ">=12.0" },- { name = "wecom-aibot-sdk", specifier = ">=1.0.0" },+ { name = "wecom-aibot-sdk", specifier = ">=1.0.5" },]provides-extras = ["desktop", "dev"]@@ -4340,16 +4340,16 @@ wheels = [[[package]]name = "wecom-aibot-sdk"-version = "1.0.3"+version = "1.0.6"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "cryptography" },{ name = "httpx" },{ name = "websockets" },]-sdist = { url = "https://files.pythonhosted.org/packages/aa/57/08f0f012a585a1e34b4d903376e9f7610f965dadec995202371883834d1f/wecom_aibot_sdk-1.0.3.tar.gz", hash = "sha256:5f81394c85e7f1d7c8de33aecf705768800509a12d3a0e571c2e7d97bf1961ad", size = 39777, upload-time = "2026-03-16T11:07:11.032Z" }+sdist = { url = "https://files.pythonhosted.org/packages/89/0a/38a399d70731070e990edcdf335842c844ee08b4ba7b5cb88acfae294016/wecom_aibot_sdk-1.0.6.tar.gz", hash = "sha256:16dfc5c7c35fc51708788a4dccacc6ce1137343f03e255cd33037abd6b309803", size = 61502, upload-time = "2026-03-27T16:01:16.986Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/2e/1e/686df5a8e689c5c9af5dc9b1f50cfbb51aa26c2e75ad535cc530e121db97/wecom_aibot_sdk-1.0.3-py3-none-any.whl", hash = "sha256:cd1724307c342bab8c5c652b04b3ab743d1b6542831f8847e8a893eb29db8cab", size = 21512, upload-time = "2026-03-16T11:07:09.365Z" },+ { url = "https://files.pythonhosted.org/packages/bb/5b/d489b9a1308665d7577b36f2deb3af30045831f57dce06c9b3574b16ba57/wecom_aibot_sdk-1.0.6-py3-none-any.whl", hash = "sha256:9f4fed218d9dedc6df07b326eb2884f20220b851881c5731b111d4e4fbe7a609", size = 27609, upload-time = "2026-03-27T16:01:15.528Z" },][[package]]