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: 透传用户面user_id/group_id/bot_id运行时上下文
u010240195278f12520996
diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.jsonindex 0d4f5a14bd..7daf22e9d1 100644--- a/jiuwenswarm/channels/web/frontend/package.json+++ b/jiuwenswarm/channels/web/frontend/package.json@@ -21,6 +21,7 @@"test:stream-delta-batcher": "tsc src/services/streamDeltaBatcher.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/stream-delta-batcher --skipLibCheck --noEmitOnError && node --test tests/streamDeltaBatcher.test.mjs","test:file-download-dedup": "tsc src/utils/fileDownloadDedup.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/file-download-dedup --skipLibCheck --noEmitOnError && node --test tests/fileDownloadDedup.test.mjs","test:web-http-client": "tsc src/services/webHttpClient.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/web-http-client --skipLibCheck --noEmitOnError && node --test tests/webHttpClient.test.mjs",+ "test:runtime-scope": "tsc src/services/runtimeScope.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/runtime-scope --skipLibCheck --noEmitOnError && node --test tests/runtimeScope.test.mjs","test:chat-store-streaming": "esbuild src/stores/chatStore.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/chat-store-streaming/chatStore.mjs --define:import.meta.env.DEV=false && node --test tests/chatStoreStreaming.test.mjs","test:settle-historical-tool-executions": "esbuild src/stores/chatStore.ts --bundle --platform=node --format=esm --outfile=node_modules/.cache/chat-store-streaming/chatStore.mjs --define:import.meta.env.DEV=false && node --test tests/settleHistoricalToolExecutions.test.mjs","test:history-pagination": "tsc src/features/historyPagination.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/history-pagination --skipLibCheck --noEmitOnError && node --test tests/historyPagination.test.mjs",diff --git a/jiuwenswarm/channels/web/frontend/src/services/runtimeScope.ts b/jiuwenswarm/channels/web/frontend/src/services/runtimeScope.tsnew file mode 100644index 0000000000..f4cf7ded84--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/services/runtimeScope.ts@@ -0,0 +1,71 @@+export interface RuntimeScope {+ userId?: string;+ groupId?: string;+ botId?: string;+}++function pickString(value: unknown): string | undefined {+ if (typeof value !== 'string') {+ return undefined;+ }+ const normalized = value.trim();+ return normalized || undefined;+}++function pickQueryValue(query: URLSearchParams, key: string): string | undefined {+ const value = query.get(key)?.trim();+ return value || undefined;+}++/**+ * Read the runtime routing scope supplied by the embedding shell.+ *+ * The values are transport context rather than business form fields. They are+ * intentionally kept in memory and are not written to localStorage or+ * sessionStorage. Authentication and authorization remain the responsibility+ * of the outer shell and server-side access control.+ */+export function parseRuntimeScope(search: string): RuntimeScope {+ const query = new URLSearchParams(search);+ return {+ userId: pickQueryValue(query, 'user_id'),+ groupId: pickQueryValue(query, 'group_id'),+ botId: pickQueryValue(query, 'bot_id'),+ };+}++export function getRuntimeScope(): RuntimeScope {+ if (typeof window === 'undefined') {+ return {};+ }+ return parseRuntimeScope(window.location.search);+}++/** Add the current runtime scope to a WebSocket handshake query. */+export function appendRuntimeScopeQuery(+ query: URLSearchParams,+ scope: RuntimeScope = getRuntimeScope()+): URLSearchParams {+ if (scope.userId) query.set('user_id', scope.userId);+ if (scope.groupId) query.set('group_id', scope.groupId);+ if (scope.botId) query.set('bot_id', scope.botId);+ return query;+}++/** Build HTTP routing headers without adding the scope to a business payload. */+export function buildRuntimeIdentityHeaders(+ requestId: string,+ params: Record<string, unknown>,+ scope: RuntimeScope = getRuntimeScope()+): Record<string, string> {+ const headers: Record<string, string> = { 'X-Request-Id': requestId };+ const userId = scope.userId ?? pickString(params.user_id);+ const groupId = scope.groupId ?? pickString(params.group_id);+ const botId = scope.botId ?? pickString(params.bot_id);+ const sessionId = pickString(params.session_id);+ if (userId) headers['X-User-Id'] = userId;+ if (groupId) headers['X-Group-Id'] = groupId;+ if (botId) headers['X-Bot-Id'] = botId;+ if (sessionId) headers['X-Session-Id'] = sessionId;+ return headers;+}diff --git a/jiuwenswarm/channels/web/frontend/src/services/webClient.ts b/jiuwenswarm/channels/web/frontend/src/services/webClient.tsindex a8ac950130..5c540d6e5c 100644--- a/jiuwenswarm/channels/web/frontend/src/services/webClient.ts+++ b/jiuwenswarm/channels/web/frontend/src/services/webClient.ts@@ -12,6 +12,7 @@ import { getWebTransport, getWsBase } from '../utils/env';import i18n from '../i18n';import { GoalRecord } from '../types/goal';import { WebHttpClient } from './webHttpClient';+import { appendRuntimeScopeQuery } from './runtimeScope';type EventHandler = (event: WsEvent) => void;type TypedEventHandler<TPayload> = (event: WsEvent & { payload: TPayload }) => void;@@ -518,6 +519,7 @@ class WebClient {if (options.apiBase) params.set('api_base', options.apiBase);if (options.model) params.set('model', options.model);if (options.projectDir) params.set('project_dir', options.projectDir);+ appendRuntimeScopeQuery(params);const query = params.toString();const target = `${base}${path}`;return query ? `${target}?${query}` : target;diff --git a/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts b/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.tsindex be7872e196..291a0414c7 100644--- a/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts+++ b/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts@@ -11,6 +11,7 @@ import {} from '../types';import { getGatewayHttpBase } from '../utils/env';import i18n from '../i18n';+import { buildRuntimeIdentityHeaders } from './runtimeScope';type EventHandler = (event: WsEvent) => void;type TypedEventHandler<TPayload> = (event: WsEvent & { payload: TPayload }) => void;@@ -23,13 +24,6 @@ function isRecord(value: unknown): value is Record<string, unknown> {return Boolean(value) && typeof value === 'object' && !Array.isArray(value);}-function pickHeaderString(value: unknown): string | undefined {- if (typeof value === 'string' && value.trim()) {- return value;- }- return undefined;-}-type HttpVerb = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';type RestKind = 'unary' | 'sse' | 'history-stream';@@ -778,16 +772,7 @@ export class WebHttpClient {requestId: string,params: Record<string, unknown>): Record<string, string> {- const headers: Record<string, string> = { 'X-Request-Id': requestId };- const userId = pickHeaderString(params.user_id);- const groupId = pickHeaderString(params.group_id);- const botId = pickHeaderString(params.bot_id);- const sessionId = pickHeaderString(params.session_id);- if (userId) headers['X-User-Id'] = userId;- if (groupId) headers['X-Group-Id'] = groupId;- if (botId) headers['X-Bot-Id'] = botId;- if (sessionId) headers['X-Session-Id'] = sessionId;- return headers;+ return buildRuntimeIdentityHeaders(requestId, params);}private dispatchEvent(event: WsEvent): void {diff --git a/jiuwenswarm/channels/web/frontend/tests/runtimeScope.test.mjs b/jiuwenswarm/channels/web/frontend/tests/runtimeScope.test.mjsnew file mode 100644index 0000000000..9130a8af3a--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/tests/runtimeScope.test.mjs@@ -0,0 +1,53 @@+import assert from 'node:assert/strict';+import test from 'node:test';++import {+ appendRuntimeScopeQuery,+ buildRuntimeIdentityHeaders,+ parseRuntimeScope,+} from '../node_modules/.cache/runtime-scope/services/runtimeScope.js';++test('runtime scope is parsed and added to websocket query', () => {+ const scope = parseRuntimeScope('?user_id=%20u1%20&group_id=g1&bot_id=b1&ignored=x');+ assert.deepEqual(scope, { userId: 'u1', groupId: 'g1', botId: 'b1' });+ const query = appendRuntimeScopeQuery(new URLSearchParams('provider=p'), scope);+ assert.equal(query.toString(), 'provider=p&user_id=u1&group_id=g1&bot_id=b1');+});++test('runtime scope takes precedence in HTTP identity headers', () => {+ assert.deepEqual(+ buildRuntimeIdentityHeaders(+ 'req-1',+ {+ user_id: 'payload-user',+ group_id: 'payload-group',+ bot_id: 'payload-bot',+ session_id: 'session-1',+ },+ { userId: 'u1', groupId: 'g1', botId: 'b1' }+ ),+ {+ 'X-Request-Id': 'req-1',+ 'X-User-Id': 'u1',+ 'X-Group-Id': 'g1',+ 'X-Bot-Id': 'b1',+ 'X-Session-Id': 'session-1',+ }+ );+});++test('missing runtime scope keeps legacy payload fallback', () => {+ assert.deepEqual(+ buildRuntimeIdentityHeaders(+ 'req-2',+ { user_id: 'u2', group_id: 'g2', bot_id: 'b2' },+ {}+ ),+ {+ 'X-Request-Id': 'req-2',+ 'X-User-Id': 'u2',+ 'X-Group-Id': 'g2',+ 'X-Bot-Id': 'b2',+ }+ );+});diff --git a/jiuwenswarm/common/e2a/agent_compat.py b/jiuwenswarm/common/e2a/agent_compat.pyindex deb31c21b2..adebce4507 100644--- a/jiuwenswarm/common/e2a/agent_compat.py+++ b/jiuwenswarm/common/e2a/agent_compat.py@@ -6,10 +6,10 @@ from __future__ import annotationsimport loggingfrom datetime import datetime-from typing import Anyfrom jiuwenswarm.common.e2a.gateway_normalize import E2A_INTERNAL_CONTEXT_KEYfrom jiuwenswarm.common.e2a.models import E2AEnvelope+from jiuwenswarm.common.request_identity import bind_web_routing_identityfrom jiuwenswarm.common.schema.agent import AgentRequestfrom jiuwenswarm.common.schema.message import ReqMethod@@ -42,7 +42,12 @@ def e2a_to_agent_request(env: E2AEnvelope) -> AgentRequest:if env.chat_id and "group_id" not in ctx:ctx.setdefault("group_id", env.chat_id)params = dict(env.params or {})- if env.user_id and "user_id" not in params:+ if env.channel == "web":+ # Web routing identity belongs to the trusted transport context rather+ # than the business payload. Bind it here so every Agent handler sees+ # the same values for WebSocket and HTTP/SSE requests.+ params = bind_web_routing_identity(params, ctx, override=True)+ elif env.user_id and "user_id" not in params:params["user_id"] = env.user_idmetadata = ctx if ctx else Nonemethod_str = env.methoddiff --git a/jiuwenswarm/common/request_identity.py b/jiuwenswarm/common/request_identity.pynew file mode 100644index 0000000000..82bec39663--- /dev/null+++ b/jiuwenswarm/common/request_identity.py@@ -0,0 +1,73 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Transport-level Web request identity helpers.++The Web shell supplies ``user_id/group_id/bot_id`` outside business payloads:+WebSocket uses its handshake query and HTTP uses trusted identity headers. This+module normalizes the resulting Gateway metadata without assigning any+authentication or authorization meaning to those routing values.+"""++from __future__ import annotations++from collections.abc import Mapping+from typing import Any++WEB_ROUTING_ID_FIELDS = ("user_id", "group_id", "bot_id")+++def _identity_value(value: Any) -> str | None:+ if isinstance(value, (list, tuple)):+ value = value[0] if value else None+ if value is None:+ return None+ text = str(value).strip()+ return text or None+++def web_routing_identity(metadata: Mapping[str, Any] | None) -> dict[str, str]:+ """Extract routing IDs from Gateway Web metadata.++ Direct metadata values take precedence over the preserved handshake/header+ query. This makes the already-resolved connection ``user_id`` authoritative.+ """++ if not isinstance(metadata, Mapping):+ return {}+ query = metadata.get("query")+ query_mapping = query if isinstance(query, Mapping) else {}+ identity: dict[str, str] = {}+ for field in WEB_ROUTING_ID_FIELDS:+ value = _identity_value(metadata.get(field)) or _identity_value(+ query_mapping.get(field)+ )+ if value:+ identity[field] = value+ return identity+++def bind_web_routing_identity(+ params: Mapping[str, Any] | None,+ metadata: Mapping[str, Any] | None,+ *,+ override: bool = True,+) -> dict[str, Any]:+ """Return a copy of ``params`` with Web transport routing IDs bound.++ ``override=True`` is appropriate at a trusted transport boundary: payload+ fields cannot impersonate the connection/header routing scope. Callers that+ only need a compatibility fallback may opt into ``override=False``.+ """++ result = dict(params or {})+ for field, value in web_routing_identity(metadata).items():+ if override or field not in result:+ result[field] = value+ return result+++__all__ = (+ "WEB_ROUTING_ID_FIELDS",+ "bind_web_routing_identity",+ "web_routing_identity",+)diff --git a/jiuwenswarm/gateway/channel_manager/web/invoke.py b/jiuwenswarm/gateway/channel_manager/web/invoke.pyindex 186284cda5..0c269e9b79 100644--- a/jiuwenswarm/gateway/channel_manager/web/invoke.py+++ b/jiuwenswarm/gateway/channel_manager/web/invoke.py@@ -8,10 +8,16 @@ import inspectimport loggingfrom typing import Any+from jiuwenswarm.common.request_identity import bind_web_routing_identityfrom jiuwenswarm.common.schema.message import Messagelogger = logging.getLogger(__name__)+# These methods are handled inside Gateway and therefore do not pass through+# AgentServer's E2A normalization. Bind the same routing identity that HTTP+# mapped routes already expose so WebSocket and HTTP have identical behavior.+_LOCAL_ROUTING_IDENTITY_PREFIXES = ("cron.", "skills.enterprise.")+async def dispatch_web_request(channel: Any,@@ -35,11 +41,23 @@ async def dispatch_web_request()handler = channel.rpc.method_handlers.get(method)+ handler_params = params+ if method.startswith(_LOCAL_ROUTING_IDENTITY_PREFIXES):+ handler_params = bind_web_routing_identity(+ params,+ user_message.metadata,+ override=True,+ )handler_already_called = Falseif method in _HANDLER_BEFORE_CALLBACK_METHODS and handler is not None:handler_already_called = await channel.rpc.invoke_method_handler(_MethodHandlerInvocation(- outbound, method, request_id, params, session_id, handler,+ outbound,+ method,+ request_id,+ handler_params,+ session_id,+ handler,),)if not handler_already_called:@@ -65,7 +83,12 @@ async def dispatch_web_request(if handler is not None:await channel.rpc.invoke_method_handler(_MethodHandlerInvocation(- outbound, method, request_id, params, session_id, handler,+ outbound,+ method,+ request_id,+ handler_params,+ session_id,+ handler,),)else:diff --git a/tests/unit_tests/channel/test_web_channel_user_id.py b/tests/unit_tests/channel/test_web_channel_user_id.pyindex 7d5dfa1098..937a7e78de 100644--- a/tests/unit_tests/channel/test_web_channel_user_id.py+++ b/tests/unit_tests/channel/test_web_channel_user_id.py@@ -200,6 +200,70 @@ async def test_web_channel_handle_raw_message_uses_connection_user_id():assert seen[0].metadata.get("user_id") == "alice"+async def test_web_channel_local_tenant_handler_uses_handshake_scope():+ channel = WebChannel(WebChannelConfig(enabled=True), RobotMessageRouter())+ ws = FakeWebSocket(query_user_id="alice")+ seen_params: list[dict[str, Any]] = []++ async def handler(_ws, _req_id, params, _session_id):+ seen_params.append(params)++ channel.register_method("cron.job.list", handler)+ await channel._handle_raw_message(+ ws,+ json.dumps(+ {+ "type": "req",+ "id": "req-scope",+ "method": "cron.job.list",+ "params": {"user_id": "payload-user"},+ }+ ),+ {+ "user_id": ["alice"],+ "group_id": ["group-1"],+ "bot_id": ["bot-1"],+ },+ )+ await channel.unregister_ws(ws)++ assert seen_params == [+ {+ "user_id": "alice",+ "group_id": "group-1",+ "bot_id": "bot-1",+ }+ ]+++async def test_web_channel_runtime_scope_does_not_replace_business_bot_id():+ channel = WebChannel(WebChannelConfig(enabled=True), RobotMessageRouter())+ ws = FakeWebSocket(query_user_id="alice")+ seen_params: list[dict[str, Any]] = []++ async def handler(_ws, _req_id, params, _session_id):+ seen_params.append(params)++ channel.register_method("channel.wecom.set_conf", handler)+ await channel._handle_raw_message(+ ws,+ json.dumps(+ {+ "type": "req",+ "id": "req-business-bot",+ "method": "channel.wecom.set_conf",+ "params": {"bot_id": "wecom-business-bot"},+ }+ ),+ {"user_id": ["alice"], "group_id": ["group-1"], "bot_id": ["runtime-bot"]},+ )+ await channel.unregister_ws(ws)++ assert seen_params == [{"bot_id": "wecom-business-bot"}]++@pytest.mark.asyncioasync def test_web_channel_handle_raw_message_ignores_params_user_id():channel = WebChannel(WebChannelConfig(enabled=True), RobotMessageRouter())diff --git a/tests/unit_tests/e2a/test_gateway_normalize.py b/tests/unit_tests/e2a/test_gateway_normalize.pyindex ba4e7988b5..43c4b61662 100644--- a/tests/unit_tests/e2a/test_gateway_normalize.py+++ b/tests/unit_tests/e2a/test_gateway_normalize.py@@ -115,6 +115,7 @@ def test_officeclaw_e2a_tenant_ids_reach_extract_ids():assert service_id == "default"assert workspace_key == "default"+def test_e2a_to_agent_request_roundtrip():msg = Message(id="r2",@@ -136,6 +137,37 @@ def test_e2a_to_agent_request_roundtrip():assert req.metadata == {"wecom_req_id": "abc"}+def test_web_transport_scope_is_bound_to_agent_params():+ env = E2AEnvelope.from_dict(+ {+ "request_id": "web-scope",+ "channel_id": "web",+ "session_id": "s1",+ "user_id": "resolved-user",+ "method": "chat.send",+ "params": {+ "content": "hello",+ "user_id": "payload-user",+ "group_id": "payload-group",+ },+ "metadata": {+ "query": {+ "user_id": ["query-user"],+ "group_id": ["group-1"],+ "bot_id": ["bot-1"],+ }+ },+ }+ )++ req = e2a_to_agent_request(env)++ assert req.params["user_id"] == "resolved-user"+ assert req.params["group_id"] == "group-1"+ assert req.params["bot_id"] == "bot-1"+ assert req.params["content"] == "hello"++def test_message_to_e2a_or_fallback_preserves_user_id():msg = Message(id="r-user",