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(gateway): 南向增加可选 HTTP/SSE client,默认仍走 WebSocket
kyrie_irving11e717879a6926
diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.jsonindex 6ae1b6cd38..0d4f5a14bd 100644--- a/jiuwenswarm/channels/web/frontend/package.json+++ b/jiuwenswarm/channels/web/frontend/package.json@@ -20,6 +20,7 @@"test:xiaoyi-cron-target": "tsc src/components/CronPanel/xiaoyiCronTarget.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/xiaoyi-cron-target --skipLibCheck --noEmitOnError && node --test tests/xiaoyiCronTarget.test.mjs","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: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/webClient.ts b/jiuwenswarm/channels/web/frontend/src/services/webClient.tsindex e7488c175c..a8ac950130 100644--- a/jiuwenswarm/channels/web/frontend/src/services/webClient.ts+++ b/jiuwenswarm/channels/web/frontend/src/services/webClient.ts@@ -8,9 +8,10 @@ import {WsRequest,WsResponse,} from '../types';-import { getWsBase } from '../utils/env';+import { getWebTransport, getWsBase } from '../utils/env';import i18n from '../i18n';import { GoalRecord } from '../types/goal';+import { WebHttpClient } from './webHttpClient';type EventHandler = (event: WsEvent) => void;type TypedEventHandler<TPayload> = (event: WsEvent & { payload: TPayload }) => void;@@ -550,7 +551,8 @@ class WebClient {}}-export const webClient = new WebClient();+export const webClient =+ getWebTransport() === 'http' ? new WebHttpClient() : new WebClient();export async function webRequest<T = unknown>(method: string,diff --git a/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts b/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.tsnew file mode 100644index 0000000000..be7872e196--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/services/webHttpClient.ts@@ -0,0 +1,872 @@+/**+ * 北向 A2 HTTP/SSE 客户端(``VITE_WEB_TRANSPORT=http`` / ``a2``)。+ * 对外口与 WebClient 相同:connect / request / on。映射与泵流只发生在这里。+ */+import {+ WebConnectOptions,+ WebConnectionState,+ WebError,+ WebRequestOptions,+ WsEvent,+} from '../types';+import { getGatewayHttpBase } from '../utils/env';+import i18n from '../i18n';++type EventHandler = (event: WsEvent) => void;+type TypedEventHandler<TPayload> = (event: WsEvent & { payload: TPayload }) => void;+type StateHandler = (state: WebConnectionState) => void;++const MAX_RECONNECT_ATTEMPTS = 5;+const DEFAULT_TIMEOUT_MS = 15000;++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';++export class RestAssemblyError extends Error {+ readonly missing: string[];++ constructor(message: string, missing: string[] = []) {+ super(message);+ this.name = 'RestAssemblyError';+ this.missing = missing;+ }+}++interface AssembledWebRest {+ method: string;+ verb: HttpVerb;+ url: string;+ query: Record<string, string> | null;+ jsonBody: Record<string, unknown> | null;+ kind: RestKind;+}++interface RouteRow {+ verb: HttpVerb;+ path: string;+ kind: RestKind;+}++const ROUTES: Record<string, RouteRow> = {+ 'connection.status': { verb: 'GET', path: '/connection/status', kind: 'unary' },+ 'session.list': { verb: 'GET', path: '/sessions', kind: 'unary' },+ 'session.create': { verb: 'POST', path: '/sessions', kind: 'unary' },+ 'history.get': { verb: 'GET', path: '/sessions/{session_id}/history', kind: 'history-stream' },+ 'chat.send': { verb: 'POST', path: '/chat/completions', kind: 'sse' },+ 'chat.interrupt': { verb: 'POST', path: '/chat/{session_id}/actions/interrupt', kind: 'unary' },+ 'chat.user_answer': { verb: 'POST', path: '/chat/{session_id}/actions/answer', kind: 'unary' },+ 'config.get': { verb: 'GET', path: '/config', kind: 'unary' },+ 'models.list': { verb: 'GET', path: '/models', kind: 'unary' },+ 'locale.get_conf': { verb: 'GET', path: '/locale', kind: 'unary' },+ 'locale.set_conf': { verb: 'PUT', path: '/locale', kind: 'unary' },+ 'cron.job.list': { verb: 'GET', path: '/cron/jobs', kind: 'unary' },+ 'cron.job.get': { verb: 'GET', path: '/cron/jobs/{id}', kind: 'unary' },+ 'cron.job.update': { verb: 'PATCH', path: '/cron/jobs/{id}', kind: 'unary' },+ 'cron.job.delete': { verb: 'DELETE', path: '/cron/jobs/{id}', kind: 'unary' },+ 'cron.job.toggle': { verb: 'POST', path: '/cron/jobs/{id}/actions/toggle', kind: 'unary' },+ 'cron.job.preview': { verb: 'POST', path: '/cron/jobs/{id}/actions/preview', kind: 'unary' },+ 'cron.job.run_now': { verb: 'POST', path: '/cron/jobs/{id}/actions/run-now', kind: 'unary' },+ 'skills.enterprise.list': { verb: 'GET', path: '/skills/enterprise', kind: 'unary' },+ 'skills.enterprise.install': { verb: 'POST', path: '/skills/enterprise/actions/install', kind: 'unary' },+ 'skills.enterprise.uninstall': { verb: 'POST', path: '/skills/enterprise/actions/uninstall', kind: 'unary' },+ 'skills.marketplace.list': { verb: 'GET', path: '/skills/marketplace', kind: 'unary' },+ 'skills.marketplace.add': { verb: 'POST', path: '/skills/marketplace', kind: 'unary' },+ 'skills.marketplace.remove': { verb: 'POST', path: '/skills/marketplace/actions/remove', kind: 'unary' },+ 'skills.marketplace.toggle': { verb: 'POST', path: '/skills/marketplace/actions/toggle', kind: 'unary' },+ 'skills.clawhub.get_token': { verb: 'GET', path: '/skills/clawhub/token', kind: 'unary' },+ 'skills.clawhub.set_token': { verb: 'PUT', path: '/skills/clawhub/token', kind: 'unary' },+ 'skills.clawhub.search': { verb: 'GET', path: '/skills/clawhub/search', kind: 'unary' },+ 'skills.clawhub.download': { verb: 'POST', path: '/skills/clawhub/actions/download', kind: 'unary' },+ 'skills.skillnet.search': { verb: 'POST', path: '/skills/skillnet/actions/search', kind: 'unary' },+ 'skills.skillnet.install': { verb: 'POST', path: '/skills/skillnet/actions/install', kind: 'unary' },+ 'skills.skillnet.install_status': { verb: 'GET', path: '/skills/skillnet/install-status', kind: 'unary' },+ 'skills.skillnet.evaluate': { verb: 'POST', path: '/skills/skillnet/actions/evaluate', kind: 'unary' },+ 'skills.evolution.get': { verb: 'GET', path: '/skills/evolution', kind: 'unary' },+ 'skills.evolution.save': { verb: 'PUT', path: '/skills/evolution', kind: 'unary' },+};++const PATH_PLACEHOLDER = /\{([A-Za-z_][A-Za-z0-9_]*)\}/g;++export function lookupWebRestRoute(method: string): RouteRow | null {+ return ROUTES[method] ?? null;+}++function joinGatewayUrl(baseUrl: string, path: string): string {+ const base = baseUrl.replace(/\/+$/, '');+ const rel = path.startsWith('/') ? path : `/${path}`;+ return `${base}${rel}`;+}++function fillPath(+ template: string,+ params: Record<string, unknown>+): { path: string; used: Set<string> } {+ const used = new Set<string>();+ const missing: string[] = [];+ const path = template.replace(PATH_PLACEHOLDER, (_all, key: string) => {+ const value = params[key];+ if (value === undefined || value === null || String(value) === '') {+ missing.push(key);+ return _all;+ }+ used.add(key);+ return encodeURIComponent(String(value));+ });+ if (missing.length > 0) {+ throw new RestAssemblyError(`REST 路径缺占位符 ${missing.join(',')}: ${template}`, missing);+ }+ return { path, used };+}++function remainingParams(+ params: Record<string, unknown>,+ used: Set<string>+): Record<string, unknown> {+ const out: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(params)) {+ if (used.has(key) || value === undefined) {+ continue;+ }+ out[key] = value;+ }+ return out;+}++function queryValues(remaining: Record<string, unknown>): Record<string, string> | null {+ const query: Record<string, string> = {};+ for (const [key, value] of Object.entries(remaining)) {+ if (value === null) {+ continue;+ }+ if (typeof value === 'object') {+ query[key] = JSON.stringify(value);+ } else {+ query[key] = String(value);+ }+ }+ return Object.keys(query).length > 0 ? query : null;+}++function applyMethodBody(+ method: string,+ remaining: Record<string, unknown>+): Record<string, unknown> {+ if (method === 'chat.send') {+ const body: Record<string, unknown> = { ...remaining, enable_streaming: true };+ if (body.query == null && body.content != null) {+ body.query = body.content;+ } else if (body.content == null && body.query != null) {+ body.content = body.query;+ }+ return body;+ }+ return remaining;+}++export function assembleWebRest(+ method: string,+ params: Record<string, unknown> | undefined,+ baseUrl: string+): AssembledWebRest | null {+ const name = method.trim();+ if (!name) {+ throw new RestAssemblyError('method 为空,无法组装 REST');+ }+ const row = lookupWebRestRoute(name);+ if (!row) {+ return null;+ }+ const values = { ...(params ?? {}) };+ const { path, used } = fillPath(row.path, values);+ const remaining = applyMethodBody(name, remainingParams(values, used));+ const useQuery = row.verb === 'GET' || row.kind === 'history-stream';+ return {+ method: name,+ verb: row.verb,+ url: joinGatewayUrl(baseUrl, path),+ query: useQuery ? queryValues(remaining) : null,+ jsonBody: useQuery ? null : remaining,+ kind: row.kind,+ };+}++function appendQuery(url: string, query: Record<string, string> | null): string {+ if (!query) {+ return url;+ }+ const encoded = Object.entries(query)+ .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)+ .join('&');+ return encoded ? `${url}?${encoded}` : url;+}++interface UnaryOk {+ ok: true;+ payload: unknown;+ requestId?: string;+}++interface UnaryFail {+ ok: false;+ message: string;+ code?: string;+ requestId?: string;+}++type UnaryResult = UnaryOk | UnaryFail;++interface SseFrame {+ event?: string;+ data?: string;+ id?: string;+}++function errorFields(error: unknown): { message: string; code?: string } {+ if (typeof error === 'string' && error.trim()) {+ return { message: error };+ }+ if (isRecord(error)) {+ const message =+ typeof error.message === 'string' && error.message.trim()+ ? error.message+ : typeof error.error === 'string'+ ? error.error+ : 'request failed';+ const code = typeof error.code === 'string' ? error.code : undefined;+ return { message, code };+ }+ return { message: 'request failed' };+}++export function unwrapHttpUnary(input: unknown): UnaryResult {+ if (!isRecord(input)) {+ return { ok: false, message: 'empty http response', code: 'HTTP_ERROR' };+ }+ const requestId = typeof input.request_id === 'string' ? input.request_id : undefined;+ if (typeof input.ok === 'boolean') {+ if (input.ok) {+ const payload = input.data !== undefined ? input.data : input.payload;+ return { ok: true, payload: payload ?? {}, requestId };+ }+ const { message, code } = errorFields(input.error);+ return { ok: false, message, code, requestId };+ }+ if (input.agent_ready !== undefined) {+ return { ok: true, payload: input, requestId };+ }+ return { ok: false, message: 'invalid http envelope', code: 'HTTP_ERROR', requestId };+}++function parseSseBlock(block: string): SseFrame | null {+ const trimmed = block.replace(/^\uFEFF/, '').trimEnd();+ if (!trimmed) {+ return null;+ }+ const frame: SseFrame = {};+ for (const rawLine of trimmed.split(/\r?\n/)) {+ if (!rawLine || rawLine.startsWith(':')) {+ continue;+ }+ const idx = rawLine.indexOf(':');+ const field = idx === -1 ? rawLine : rawLine.slice(0, idx);+ let value = idx === -1 ? '' : rawLine.slice(idx + 1);+ if (value.startsWith(' ')) {+ value = value.slice(1);+ }+ if (field === 'event') {+ frame.event = value;+ } else if (field === 'data') {+ frame.data = frame.data === undefined ? value : `${frame.data}\n${value}`;+ } else if (field === 'id') {+ frame.id = value;+ }+ }+ if (frame.event === undefined && frame.data === undefined && frame.id === undefined) {+ return null;+ }+ return frame;+}++export function consumeSseBuffer(buffer: string): { frames: SseFrame[]; rest: string } {+ const parts = buffer.split(/\r?\n\r?\n/);+ const rest = parts.pop() ?? '';+ const frames: SseFrame[] = [];+ for (const part of parts) {+ const frame = parseSseBlock(part);+ if (frame) {+ frames.push(frame);+ }+ }+ return { frames, rest };+}++function payloadFromData(data: string | undefined): Record<string, unknown> {+ if (!data) {+ return {};+ }+ try {+ const parsed: unknown = JSON.parse(data);+ if (isRecord(parsed)) {+ if (isRecord(parsed.payload)) {+ return parsed.payload;+ }+ return parsed;+ }+ return { value: parsed };+ } catch {+ return { raw: data };+ }+}++export function sseFrameToWsEvent(frame: SseFrame): WsEvent | null {+ let eventName = frame.event?.trim() ?? '';+ const payload = payloadFromData(frame.data);+ if (!eventName && typeof payload.event === 'string') {+ eventName = payload.event;+ }+ if (!eventName) {+ return null;+ }+ return {+ type: 'event',+ event: eventName,+ payload,+ };+}++export function historyPageToEvents(page: unknown, sessionId?: string): WsEvent[] {+ if (!isRecord(page)) {+ return [];+ }+ const sid =+ (typeof page.session_id === 'string' && page.session_id) || sessionId || '';+ const events: WsEvent[] = [];+ const messages = Array.isArray(page.messages) ? page.messages : [];+ for (const message of messages) {+ events.push({+ type: 'event',+ event: 'history.message',+ payload: {+ session_id: sid,+ page_idx: page.page_idx,+ total_pages: page.total_pages,+ message,+ },+ });+ }+ events.push({+ type: 'event',+ event: 'history.message',+ payload: {+ session_id: sid,+ page_idx: page.page_idx,+ total_pages: page.total_pages,+ status: 'done',+ },+ });+ return events;+}++function isSseContentType(contentType: string | null | undefined): boolean {+ return Boolean(contentType && contentType.toLowerCase().includes('text/event-stream'));+}++function isChatSseTerminal(eventName: string): boolean {+ return eventName === 'chat.final' || eventName === 'chat.error';+}++function isHistorySseDone(payload: Record<string, unknown>): boolean {+ return typeof payload.status === 'string' && payload.status.trim().toLowerCase() === 'done';+}++export class WebHttpClient {+ private state: WebConnectionState = 'idle';+ private handlers = new Map<string, Set<EventHandler>>();+ private stateHandlers = new Set<StateHandler>();+ private inflight = new Map<string, AbortController>();+ private connectAbort: AbortController | null = null;+ private reconnectTimer: number | null = null;+ private reconnectAttempts = 0;+ private manualClose = false;+ private connectPromise: Promise<void> | null = null;+ private lastConnectOptions: WebConnectOptions = {};+ private requestSeq = 0;++ getState(): WebConnectionState {+ return this.state;+ }++ getInflightCount(): number {+ return this.inflight.size;+ }++ onStateChange(handler: StateHandler): () => void {+ this.stateHandlers.add(handler);+ return () => {+ this.stateHandlers.delete(handler);+ };+ }++ on<TPayload = Record<string, unknown>>(+ eventName: string,+ handler: TypedEventHandler<TPayload>+ ): () => void {+ const set = this.handlers.get(eventName) ?? new Set<EventHandler>();+ const eventHandler = handler as EventHandler;+ set.add(eventHandler);+ this.handlers.set(eventName, set);+ return () => {+ const target = this.handlers.get(eventName);+ if (!target) {+ return;+ }+ target.delete(eventHandler);+ if (target.size === 0) {+ this.handlers.delete(eventName);+ }+ };+ }++ async connect(options: WebConnectOptions = {}): Promise<void> {+ if (this.state === 'ready') {+ return;+ }+ if (this.connectPromise) {+ return this.connectPromise;+ }++ this.lastConnectOptions = options;+ this.manualClose = false;+ this.updateState(this.reconnectAttempts > 0 ? 'reconnecting' : 'connecting');++ this.connectPromise = this.openConnection();+ return this.connectPromise;+ }++ disconnect(_reason = 'User disconnect'): Promise<void> {+ this.manualClose = true;+ this.clearReconnectTimer();+ this.connectAbort?.abort();+ this.connectAbort = null;+ this.abortInflight();+ this.connectPromise = null;+ this.updateState('closed');+ return Promise.resolve();+ }++ async request<T = unknown>(+ method: string,+ params?: Record<string, unknown>,+ options: WebRequestOptions = {}+ ): Promise<T> {+ await this.ensureReady();+ if (this.state !== 'ready') {+ throw this.createWebError(+ i18n.t('network.connectionUnavailable'),+ 'WS_NOT_READY',+ undefined,+ true+ );+ }++ const requestId = this.generateRequestId();+ let assembled;+ try {+ assembled = assembleWebRest(method, params, getGatewayHttpBase());+ } catch (error) {+ if (error instanceof RestAssemblyError) {+ throw this.createWebError(error.message, 'BAD_REQUEST', requestId, false);+ }+ throw error;+ }+ if (!assembled) {+ throw this.createWebError(+ i18n.t('network.requestFailed'),+ 'METHOD_NOT_FOUND',+ requestId,+ false+ );+ }++ const controller = new AbortController();+ this.inflight.set(requestId, controller);+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;+ const timeoutId = window.setTimeout(() => {+ controller.abort();+ }, timeoutMs);++ const onAbort = () => {+ controller.abort();+ };+ if (options.signal) {+ if (options.signal.aborted) {+ window.clearTimeout(timeoutId);+ this.inflight.delete(requestId);+ throw this.createWebError(+ i18n.t('network.requestAborted'),+ 'REQUEST_ABORTED',+ requestId,+ false+ );+ }+ options.signal.addEventListener('abort', onAbort, { once: true });+ }++ try {+ const headers: Record<string, string> = {+ ...this.identityHeaders(requestId, params ?? {}),+ Accept: assembled.kind === 'unary' ? 'application/json' : 'text/event-stream',+ };+ if (assembled.jsonBody) {+ headers['Content-Type'] = 'application/json';+ }+ const response = await fetch(appendQuery(assembled.url, assembled.query), {+ method: assembled.verb,+ headers,+ body: assembled.jsonBody ? JSON.stringify(assembled.jsonBody) : undefined,+ signal: controller.signal,+ });+ window.clearTimeout(timeoutId);++ if (assembled.kind === 'sse' || assembled.kind === 'history-stream') {+ if (isSseContentType(response.headers.get('content-type'))) {+ if (!response.ok) {+ const unwrapped = unwrapHttpUnary(await this.readJson(response));+ throw this.createWebError(+ unwrapped.ok ? i18n.t('network.requestFailed') : unwrapped.message,+ unwrapped.ok ? 'HTTP_ERROR' : unwrapped.code,+ requestId,+ response.status >= 500+ );+ }+ const accepted = {+ accepted: true,+ session_id: typeof params?.session_id === 'string' ? params.session_id : undefined,+ ...(assembled.kind === 'history-stream' && params?.page_idx !== undefined+ ? { page_idx: params.page_idx }+ : {}),+ };+ void this.pumpSse(response, requestId, assembled.kind, controller);+ return accepted as T;+ }+ if (assembled.kind === 'history-stream') {+ const page = await this.readUnaryPayload(response, requestId);+ const sessionId = typeof params?.session_id === 'string' ? params.session_id : undefined;+ for (const event of historyPageToEvents(page, sessionId)) {+ this.dispatchEvent(event);+ }+ this.inflight.delete(requestId);+ return page as T;+ }+ }++ const payload = await this.readUnaryPayload(response, requestId);+ this.inflight.delete(requestId);+ return payload as T;+ } catch (error) {+ window.clearTimeout(timeoutId);+ this.inflight.delete(requestId);+ if (options.signal?.aborted) {+ if (assembled.kind === 'sse' && typeof params?.session_id === 'string') {+ void this.interruptChat(params.session_id, requestId);+ }+ throw this.createWebError(+ i18n.t('network.requestAborted'),+ 'REQUEST_ABORTED',+ requestId,+ false+ );+ }+ if (error instanceof DOMException && error.name === 'AbortError') {+ if (assembled.kind === 'sse' && typeof params?.session_id === 'string') {+ void this.interruptChat(params.session_id, requestId);+ }+ throw this.createWebError(+ i18n.t('network.requestTimeout'),+ 'REQUEST_TIMEOUT',+ requestId,+ true+ );+ }+ throw this.asWebError(error, requestId, true);+ } finally {+ options.signal?.removeEventListener('abort', onAbort);+ }+ }++ async sendFireAndForget(+ _method: string,+ _params?: Record<string, unknown>,+ _options: { isStream?: boolean } = {}+ ): Promise<void> {+ throw this.createWebError(+ i18n.t('network.requestFailed'),+ 'METHOD_NOT_FOUND',+ undefined,+ false+ );+ }++ private async ensureReady(): Promise<void> {+ if (this.state === 'ready') {+ return;+ }+ await this.connect(this.lastConnectOptions);+ }++ private async openConnection(): Promise<void> {+ const requestId = this.generateRequestId();+ this.connectAbort = new AbortController();+ const url = `${getGatewayHttpBase().replace(/\/+$/, '')}/connection/status`;+ try {+ const response = await fetch(url, {+ method: 'GET',+ headers: this.identityHeaders(requestId, {}),+ signal: this.connectAbort.signal,+ });+ const unwrapped = unwrapHttpUnary(await this.readJson(response));+ if (!unwrapped.ok) {+ throw this.createWebError(+ unwrapped.message,+ unwrapped.code ?? (response.status >= 500 ? 'HTTP_ERROR' : 'WS_ERROR'),+ unwrapped.requestId ?? requestId,+ response.status >= 500 || !response.ok+ );+ }+ this.reconnectAttempts = 0;+ this.updateState('ready');+ this.dispatchEvent({+ type: 'event',+ event: 'connection.ack',+ payload: isRecord(unwrapped.payload) ? { ...unwrapped.payload } : {},+ });+ } catch (error) {+ if (this.state !== 'ready') {+ this.updateState('closed');+ }+ if (!this.manualClose) {+ this.scheduleReconnect();+ }+ throw this.asWebError(error, requestId, true);+ } finally {+ this.connectAbort = null;+ this.connectPromise = null;+ }+ }++ private async pumpSse(+ response: Response,+ requestId: string,+ kind: 'sse' | 'history-stream',+ controller: AbortController+ ): Promise<void> {+ const reader = response.body?.getReader();+ if (!reader) {+ this.inflight.delete(requestId);+ return;+ }+ const decoder = new TextDecoder();+ let buffer = '';+ try {+ while (!controller.signal.aborted) {+ const { done, value } = await reader.read();+ if (done) {+ break;+ }+ buffer += decoder.decode(value, { stream: true });+ const consumed = consumeSseBuffer(buffer);+ buffer = consumed.rest;+ for (const frame of consumed.frames) {+ const event = sseFrameToWsEvent(frame);+ if (!event) {+ continue;+ }+ this.dispatchEvent(event);+ if (kind === 'sse' && isChatSseTerminal(event.event)) {+ await reader.cancel().catch(() => undefined);+ return;+ }+ if (kind === 'history-stream' && isHistorySseDone(event.payload)) {+ await reader.cancel().catch(() => undefined);+ return;+ }+ }+ }+ if (buffer.trim()) {+ for (const frame of consumeSseBuffer(`${buffer}\n\n`).frames) {+ const event = sseFrameToWsEvent(frame);+ if (event) {+ this.dispatchEvent(event);+ }+ }+ }+ } catch {+ // abort / 断流:hook 靠现有 on(chat.error) 或 inflight 归零+ } finally {+ this.inflight.delete(requestId);+ }+ }++ private async interruptChat(sessionId: string, requestId: string): Promise<void> {+ try {+ const assembled = assembleWebRest(+ 'chat.interrupt',+ { session_id: sessionId, intent: 'cancel' },+ getGatewayHttpBase()+ );+ if (!assembled) {+ return;+ }+ await fetch(appendQuery(assembled.url, assembled.query), {+ method: assembled.verb,+ headers: {+ ...this.identityHeaders(requestId, { session_id: sessionId }),+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify(assembled.jsonBody ?? { intent: 'cancel' }),+ });+ } catch {+ // 打断失败不掩盖本次 abort+ }+ }++ private async readUnaryPayload(response: Response, requestId: string): Promise<unknown> {+ const unwrapped = unwrapHttpUnary(await this.readJson(response));+ if (!unwrapped.ok) {+ throw this.createWebError(+ unwrapped.message,+ unwrapped.code ?? (response.status >= 500 ? 'HTTP_ERROR' : undefined),+ unwrapped.requestId ?? requestId,+ this.isRetriableCode(unwrapped.code) || response.status >= 500+ );+ }+ if (!response.ok && response.status >= 400 && response.status !== 201) {+ throw this.createWebError(+ i18n.t('network.requestFailed'),+ response.status >= 500 ? 'HTTP_ERROR' : 'BAD_REQUEST',+ requestId,+ response.status >= 500+ );+ }+ return unwrapped.payload;+ }++ private async readJson(response: Response): Promise<unknown> {+ const text = await response.text();+ if (!text.trim()) {+ return {};+ }+ try {+ return JSON.parse(text) as unknown;+ } catch {+ return { ok: false, error: { code: 'HTTP_ERROR', message: text.slice(0, 200) } };+ }+ }++ private identityHeaders(+ 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;+ }++ private dispatchEvent(event: WsEvent): void {+ const handlers = this.handlers.get(event.event);+ if (!handlers || handlers.size === 0) {+ return;+ }+ handlers.forEach((handler) => {+ handler(event);+ });+ }++ private scheduleReconnect(): void {+ this.clearReconnectTimer();+ this.reconnectAttempts += 1;+ this.updateState('reconnecting');+ const delay =+ this.reconnectAttempts <= MAX_RECONNECT_ATTEMPTS+ ? Math.min(1000 * 2 ** (this.reconnectAttempts - 1), 30000)+ : 2000;+ this.reconnectTimer = window.setTimeout(() => {+ void this.connect(this.lastConnectOptions);+ }, delay);+ }++ private clearReconnectTimer(): void {+ if (this.reconnectTimer !== null) {+ window.clearTimeout(this.reconnectTimer);+ this.reconnectTimer = null;+ }+ }++ private abortInflight(): void {+ this.inflight.forEach((controller) => {+ controller.abort();+ });+ this.inflight.clear();+ }++ private updateState(state: WebConnectionState): void {+ this.state = state;+ this.stateHandlers.forEach((handler) => {+ handler(state);+ });+ }++ private generateRequestId(): string {+ this.requestSeq += 1;+ return `req_${Date.now().toString(36)}_${this.requestSeq}`;+ }++ private createWebError(+ message: string,+ code?: string,+ requestId?: string,+ retriable = false+ ): WebError {+ const error = new Error(message) as WebError;+ error.code = code;+ error.requestId = requestId;+ error.retriable = retriable;+ return error;+ }++ private isRetriableCode(code?: string): boolean {+ return (+ code === 'REQUEST_TIMEOUT' ||+ code === 'WS_DISCONNECTED' ||+ code === 'WS_NOT_READY' ||+ code === 'HTTP_ERROR' ||+ code === 'SERVICE_UNAVAILABLE'+ );+ }++ private asWebError(error: unknown, requestId?: string, retriable = false): WebError {+ if (error instanceof Error && 'code' in error) {+ return error as WebError;+ }+ const message = error instanceof Error ? error.message : i18n.t('network.requestFailed');+ return this.createWebError(message, 'HTTP_ERROR', requestId, retriable);+ }+}diff --git a/jiuwenswarm/channels/web/frontend/src/utils/env.ts b/jiuwenswarm/channels/web/frontend/src/utils/env.tsindex 5efdfdb71e..f71d7f245b 100644--- a/jiuwenswarm/channels/web/frontend/src/utils/env.ts+++ b/jiuwenswarm/channels/web/frontend/src/utils/env.ts@@ -20,3 +20,31 @@ export function getWsBase(): string {if (!apiBase) return "";return apiBase.replace(/^http:/, "ws:").replace(/^https:/, "wss:");}++export type WebTransport = "websocket" | "http";++/** 构建期选定,运行时不探测。默认 websocket。`a2` 与 `http` 同义。 */+export function getWebTransport(): WebTransport {+ const raw = String(+ import.meta.env.VITE_WEB_TRANSPORT ?? import.meta.env.VITE_TRANSPORT ?? "websocket"+ )+ .trim()+ .toLowerCase();+ if (raw === "http" || raw === "a2") {+ return "http";+ }+ return "websocket";+}++/** Gateway A2 前缀,默认同源 `/api/v1`。不要和 H1 `/api/sessions` 混用。 */+export function getGatewayHttpBase(): string {+ const raw = import.meta.env.VITE_GATEWAY_HTTP_BASE ?? import.meta.env.VITE_WEB_HTTP_BASE;+ if (!raw) {+ return "/api/v1";+ }+ const normalized = normalizeBase(raw);+ if (normalized.endsWith("/api/v1")) {+ return normalized;+ }+ return `${normalized}/api/v1`;+}diff --git a/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts b/jiuwenswarm/channels/web/frontend/src/vite-env.d.tsindex 8a7f4382bd..a22b395301 100644--- a/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts+++ b/jiuwenswarm/channels/web/frontend/src/vite-env.d.ts@@ -4,6 +4,10 @@interface ImportMetaEnv {readonly VITE_API_BASE?: string;readonly VITE_WS_BASE?: string;+ readonly VITE_WEB_TRANSPORT?: string;+ readonly VITE_TRANSPORT?: string;+ readonly VITE_GATEWAY_HTTP_BASE?: string;+ readonly VITE_WEB_HTTP_BASE?: string;}interface ImportMeta {diff --git a/jiuwenswarm/channels/web/frontend/tests/webHttpClient.test.mjs b/jiuwenswarm/channels/web/frontend/tests/webHttpClient.test.mjsnew file mode 100644index 0000000000..a61d230fb4--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/tests/webHttpClient.test.mjs@@ -0,0 +1,366 @@+import assert from 'node:assert/strict';+import test from 'node:test';++import {+ assembleWebRest,+ consumeSseBuffer,+ historyPageToEvents,+ lookupWebRestRoute,+ RestAssemblyError,+ sseFrameToWsEvent,+ unwrapHttpUnary,+} from '../node_modules/.cache/web-http-client/services/webHttpClient.js';++const BASE = '/api/v1';++test('unknown method is null, no rpc fallback', () => {+ assert.equal(assembleWebRest('command.goal', { session_id: 's1' }, BASE), null);+ assert.equal(assembleWebRest('memory.compute', {}, BASE), null);+ assert.equal(assembleWebRest('files.list', { session_id: 's1' }, BASE), null);+ assert.equal(lookupWebRestRoute('tts.synthesize'), null);+});++test('session.list is GET query, not H1 /api/sessions', () => {+ const assembled = assembleWebRest('session.list', { limit: 20 }, BASE);+ assert.ok(assembled);+ assert.equal(assembled.verb, 'GET');+ assert.equal(assembled.url, '/api/v1/sessions');+ assert.deepEqual(assembled.query, { limit: '20' });+ assert.equal(assembled.jsonBody, null);+});++test('session.create keeps client session_id in body', () => {+ const assembled = assembleWebRest('session.create', { session_id: 'web_1' }, BASE);+ assert.ok(assembled);+ assert.equal(assembled.verb, 'POST');+ assert.deepEqual(assembled.jsonBody, { session_id: 'web_1' });+});++test('chat.send is completions SSE with query dual-write', () => {+ const assembled = assembleWebRest(+ 'chat.send',+ { session_id: 'sid', content: 'hi', mode: 'agent' },+ BASE+ );+ assert.ok(assembled);+ assert.equal(assembled.kind, 'sse');+ assert.equal(assembled.url, '/api/v1/chat/completions');+ assert.equal(assembled.jsonBody.enable_streaming, true);+ assert.equal(assembled.jsonBody.query, 'hi');+ assert.equal(assembled.jsonBody.content, 'hi');+});++test('interrupt and answer put session_id in path', () => {+ const interrupt = assembleWebRest(+ 'chat.interrupt',+ { session_id: 'sid', intent: 'cancel' },+ BASE+ );+ assert.ok(interrupt);+ assert.equal(interrupt.url, '/api/v1/chat/sid/actions/interrupt');+ assert.deepEqual(interrupt.jsonBody, { intent: 'cancel' });++ const answer = assembleWebRest(+ 'chat.user_answer',+ { session_id: 'sid', request_id: 'q1', answers: { a: 1 } },+ BASE+ );+ assert.ok(answer);+ assert.equal(answer.url, '/api/v1/chat/sid/actions/answer');+ assert.deepEqual(answer.jsonBody, { request_id: 'q1', answers: { a: 1 } });+});++test('missing path placeholder throws, no half url', () => {+ assert.throws(+ () => assembleWebRest('chat.interrupt', { intent: 'cancel' }, BASE),+ (error) => error instanceof RestAssemblyError && error.missing.includes('session_id')+ );+});++test('history.get uses /history with stream kind (Accept SSE)', () => {+ const assembled = assembleWebRest('history.get', { session_id: 'sid', page_idx: 2 }, BASE);+ assert.ok(assembled);+ assert.equal(assembled.kind, 'history-stream');+ assert.equal(assembled.url, '/api/v1/sessions/sid/history');+ assert.deepEqual(assembled.query, { page_idx: '2' });+});++test('cron update keeps patch object; marketplace remove is POST', () => {+ const update = assembleWebRest(+ 'cron.job.update',+ { id: 'job-1', patch: { enabled: false, name: 'n' }, session_id: 'sid' },+ BASE+ );+ assert.ok(update);+ assert.equal(update.verb, 'PATCH');+ assert.equal(update.url, '/api/v1/cron/jobs/job-1');+ assert.deepEqual(update.jsonBody, {+ patch: { enabled: false, name: 'n' },+ session_id: 'sid',+ });++ const remove = assembleWebRest(+ 'skills.marketplace.remove',+ { name: 'src', remove_cache: true, session_id: 'sid' },+ BASE+ );+ assert.ok(remove);+ assert.equal(remove.verb, 'POST');+ assert.equal(remove.url, '/api/v1/skills/marketplace/actions/remove');+});++test('skillnet search is POST actions/search', () => {+ const assembled = assembleWebRest(+ 'skills.skillnet.search',+ { q: 'foo', limit: 10, session_id: 'sid' },+ BASE+ );+ assert.ok(assembled);+ assert.equal(assembled.verb, 'POST');+ assert.equal(assembled.url, '/api/v1/skills/skillnet/actions/search');+});++test('unwrapHttpUnary reads data and error.code', () => {+ assert.deepEqual(unwrapHttpUnary({ ok: true, data: { jobs: [] } }), {+ ok: true,+ payload: { jobs: [] },+ requestId: undefined,+ });+ const fail = unwrapHttpUnary({+ ok: false,+ error: { code: 'NOT_FOUND', message: 'missing' },+ });+ assert.equal(fail.ok, false);+ if (!fail.ok) {+ assert.equal(fail.code, 'NOT_FOUND');+ assert.equal(fail.message, 'missing');+ }+});++test('sse frames keep A1 event names', () => {+ const { frames } = consumeSseBuffer(+ 'id: req_1\nevent: chat.delta\ndata: {"content":"a"}\n\n'+ );+ assert.equal(frames.length, 1);+ const event = sseFrameToWsEvent(frames[0]);+ assert.equal(event?.event, 'chat.delta');+ assert.equal(event?.payload.content, 'a');+});++test('history JSON page becomes history.message events plus done', () => {+ const events = historyPageToEvents(+ { session_id: 'sid', page_idx: 1, total_pages: 1, messages: [{ role: 'user', content: 'hi' }] },+ 'sid'+ );+ assert.equal(events.length, 2);+ assert.equal(events[0].event, 'history.message');+ assert.equal(events[1].payload.status, 'done');+});++const ENTERPRISE_ASSEMBLE = [+ ['connection.status', 'GET', '/api/v1/connection/status', {}, 'unary'],+ ['session.list', 'GET', '/api/v1/sessions', { limit: 20, offset: 0 }, 'unary'],+ ['session.create', 'POST', '/api/v1/sessions', { mode: 'agent' }, 'unary'],+ ['history.get', 'GET', '/api/v1/sessions/sid/history', { session_id: 'sid', page_idx: 1 }, 'history-stream'],+ ['chat.send', 'POST', '/api/v1/chat/completions', { session_id: 'sid', query: 'hi' }, 'sse'],+ ['chat.interrupt', 'POST', '/api/v1/chat/sid/actions/interrupt', { session_id: 'sid', intent: 'pause' }, 'unary'],+ ['chat.user_answer', 'POST', '/api/v1/chat/sid/actions/answer', { session_id: 'sid', request_id: 'q', answers: {} }, 'unary'],+ ['config.get', 'GET', '/api/v1/config', {}, 'unary'],+ ['models.list', 'GET', '/api/v1/models', {}, 'unary'],+ ['locale.get_conf', 'GET', '/api/v1/locale', {}, 'unary'],+ ['locale.set_conf', 'PUT', '/api/v1/locale', { preferred_language: 'zh' }, 'unary'],+ ['cron.job.list', 'GET', '/api/v1/cron/jobs', {}, 'unary'],+ ['cron.job.get', 'GET', '/api/v1/cron/jobs/job-1', { id: 'job-1' }, 'unary'],+ ['cron.job.update', 'PATCH', '/api/v1/cron/jobs/job-1', { id: 'job-1', patch: { name: 'n' } }, 'unary'],+ ['cron.job.delete', 'DELETE', '/api/v1/cron/jobs/job-1', { id: 'job-1' }, 'unary'],+ ['cron.job.toggle', 'POST', '/api/v1/cron/jobs/job-1/actions/toggle', { id: 'job-1', enabled: true }, 'unary'],+ ['cron.job.preview', 'POST', '/api/v1/cron/jobs/job-1/actions/preview', { id: 'job-1', count: 3 }, 'unary'],+ ['cron.job.run_now', 'POST', '/api/v1/cron/jobs/job-1/actions/run-now', { id: 'job-1' }, 'unary'],+ ['skills.enterprise.list', 'GET', '/api/v1/skills/enterprise', {}, 'unary'],+ ['skills.enterprise.install', 'POST', '/api/v1/skills/enterprise/actions/install', { url: 'http://x' }, 'unary'],+ ['skills.enterprise.uninstall', 'POST', '/api/v1/skills/enterprise/actions/uninstall', { name: 's' }, 'unary'],+ ['skills.marketplace.list', 'GET', '/api/v1/skills/marketplace', {}, 'unary'],+ ['skills.marketplace.add', 'POST', '/api/v1/skills/marketplace', { name: 'm', url: 'http://m' }, 'unary'],+ ['skills.marketplace.remove', 'POST', '/api/v1/skills/marketplace/actions/remove', { name: 'm' }, 'unary'],+ ['skills.marketplace.toggle', 'POST', '/api/v1/skills/marketplace/actions/toggle', { name: 'm', enabled: true }, 'unary'],+ ['skills.clawhub.get_token', 'GET', '/api/v1/skills/clawhub/token', {}, 'unary'],+ ['skills.clawhub.set_token', 'PUT', '/api/v1/skills/clawhub/token', { token: 't' }, 'unary'],+ ['skills.clawhub.search', 'GET', '/api/v1/skills/clawhub/search', { q: 'foo', limit: 5 }, 'unary'],+ ['skills.clawhub.download', 'POST', '/api/v1/skills/clawhub/actions/download', { slug: 'x' }, 'unary'],+ ['skills.skillnet.search', 'POST', '/api/v1/skills/skillnet/actions/search', { q: 'foo' }, 'unary'],+ ['skills.skillnet.install', 'POST', '/api/v1/skills/skillnet/actions/install', { url: 'http://s' }, 'unary'],+ ['skills.skillnet.install_status', 'GET', '/api/v1/skills/skillnet/install-status', { install_id: 'inst-1' }, 'unary'],+ ['skills.skillnet.evaluate', 'POST', '/api/v1/skills/skillnet/actions/evaluate', { url: 'http://s' }, 'unary'],+ ['skills.evolution.get', 'GET', '/api/v1/skills/evolution', { name: 'evo-1' }, 'unary'],+ ['skills.evolution.save', 'PUT', '/api/v1/skills/evolution', { name: 'evo-1', entries: [] }, 'unary'],+];++test('every enterprise mapped method assembles verb+url+kind', () => {+ assert.equal(ENTERPRISE_ASSEMBLE.length, 35);+ const seen = new Set();+ for (const [method, verb, url, params, kind] of ENTERPRISE_ASSEMBLE) {+ seen.add(method);+ const assembled = assembleWebRest(method, params, BASE);+ assert.ok(assembled, method);+ assert.equal(assembled.verb, verb, method);+ assert.equal(assembled.url, url, method);+ assert.equal(assembled.kind, kind, method);+ if (verb === 'GET' || kind === 'history-stream') {+ assert.equal(assembled.jsonBody, null, method);+ } else {+ assert.ok(assembled.jsonBody && typeof assembled.jsonBody === 'object', method);+ }+ }+ assert.equal(seen.size, ENTERPRISE_ASSEMBLE.length);+});++test('GET leftover params go to query; POST leftover stay in body; path keys stripped', () => {+ const listed = assembleWebRest('session.list', { limit: 10, offset: 2 }, BASE);+ assert.deepEqual(listed.query, { limit: '10', offset: '2' });++ const claw = assembleWebRest('skills.clawhub.search', { q: 'x', limit: 3, session_id: 'sid' }, BASE);+ assert.equal(claw.verb, 'GET');+ assert.deepEqual(claw.query, { q: 'x', limit: '3', session_id: 'sid' });+ assert.equal(claw.jsonBody, null);++ const status = assembleWebRest(+ 'skills.skillnet.install_status',+ { install_id: 'inst-1', session_id: 'sid' },+ BASE+ );+ assert.deepEqual(status.query, { install_id: 'inst-1', session_id: 'sid' });++ const evo = assembleWebRest('skills.evolution.get', { name: 'n1', session_id: 'sid' }, BASE);+ assert.deepEqual(evo.query, { name: 'n1', session_id: 'sid' });++ const interrupt = assembleWebRest(+ 'chat.interrupt',+ { session_id: 'sid', intent: 'cancel', new_input: 'more' },+ BASE+ );+ assert.equal(interrupt.jsonBody.session_id, undefined);+ assert.deepEqual(interrupt.jsonBody, { intent: 'cancel', new_input: 'more' });++ const cronGet = assembleWebRest('cron.job.get', { id: 'job-1', session_id: 'sid' }, BASE);+ assert.equal(cronGet.url, '/api/v1/cron/jobs/job-1');+ assert.deepEqual(cronGet.query, { session_id: 'sid' });+});++test('path placeholder missing or empty throws; special chars are encoded', () => {+ assert.throws(+ () => assembleWebRest('cron.job.delete', {}, BASE),+ (error) => error instanceof RestAssemblyError && error.missing.includes('id')+ );+ assert.throws(+ () => assembleWebRest('history.get', { session_id: '' }, BASE),+ (error) => error instanceof RestAssemblyError && error.missing.includes('session_id')+ );+ assert.throws(+ () => assembleWebRest(' ', {}, BASE),+ (error) => error instanceof RestAssemblyError+ );+ const encoded = assembleWebRest('history.get', { session_id: 'sid/a b' }, BASE);+ assert.equal(encoded.url, '/api/v1/sessions/sid%2Fa%20b/history');+});++test('chat.send dual-write and does not clobber both fields', () => {+ const fromQuery = assembleWebRest('chat.send', { session_id: 's', query: 'q' }, BASE);+ assert.equal(fromQuery.jsonBody.query, 'q');+ assert.equal(fromQuery.jsonBody.content, 'q');+ assert.equal(fromQuery.jsonBody.enable_streaming, true);++ const fromContent = assembleWebRest('chat.send', { session_id: 's', content: 'c' }, BASE);+ assert.equal(fromContent.jsonBody.query, 'c');+ assert.equal(fromContent.jsonBody.content, 'c');++ const both = assembleWebRest(+ 'chat.send',+ { session_id: 's', query: 'q', content: 'c' },+ BASE+ );+ assert.equal(both.jsonBody.query, 'q');+ assert.equal(both.jsonBody.content, 'c');+});++test('skills static prefixes are not /skills/{name}', () => {+ const prefixes = [+ ['skills.enterprise.list', '/api/v1/skills/enterprise'],+ ['skills.marketplace.list', '/api/v1/skills/marketplace'],+ ['skills.clawhub.get_token', '/api/v1/skills/clawhub/token'],+ ['skills.skillnet.search', '/api/v1/skills/skillnet/actions/search'],+ ['skills.evolution.get', '/api/v1/skills/evolution'],+ ];+ for (const [method, url] of prefixes) {+ const assembled = assembleWebRest(method, { name: 'would-be-skill', session_id: 'sid' }, BASE);+ assert.equal(assembled.url, url, method);+ assert.equal(assembled.url.includes('/skills/would-be-skill'), false, method);+ }+});++test('unmapped A2 and personal methods stay null', () => {+ const unmapped = [+ 'memory.compute',+ 'files.list',+ 'files.get',+ 'tts.synthesize',+ 'command.goal',+ 'session.delete',+ 'session.rename',+ 'cron.job.create',+ 'config.set',+ 'chat.resume',+ 'permissions.tools.get',+ 'harness.packages',+ 'skills.list',+ ];+ for (const method of unmapped) {+ assert.equal(assembleWebRest(method, { session_id: 's', id: '1', name: 'n' }, BASE), null, method);+ assert.equal(lookupWebRestRoute(method), null, method);+ }+});++test('base url already ending with /api/v1 is not doubled', () => {+ const assembled = assembleWebRest('config.get', {}, 'http://127.0.0.1:19002/api/v1');+ assert.equal(assembled.url, 'http://127.0.0.1:19002/api/v1/config');+});++test('unwrapHttpUnary covers envelope variants', () => {+ assert.equal(unwrapHttpUnary(null).ok, false);+ assert.equal(unwrapHttpUnary('x').ok, false);+ assert.deepEqual(unwrapHttpUnary({ ok: true, data: { a: 1 }, request_id: 'r1' }), {+ ok: true,+ payload: { a: 1 },+ requestId: 'r1',+ });+ assert.equal(unwrapHttpUnary({ ok: true }).payload !== undefined, true);+ const payloadFallback = unwrapHttpUnary({ ok: true, payload: { z: 1 } });+ assert.equal(payloadFallback.ok, true);+ assert.deepEqual(payloadFallback.payload, { z: 1 });+ const bare = unwrapHttpUnary({ agent_ready: true, protocol_version: '1.0' });+ assert.equal(bare.ok, true);+ const strErr = unwrapHttpUnary({ ok: false, error: 'boom' });+ assert.equal(strErr.ok, false);+ assert.equal(strErr.message, 'boom');+});++test('sse parser skips comments and keeps A1 names including history done', () => {+ const { frames } = consumeSseBuffer(+ [+ ': keepalive\n\n',+ 'id: r1\nevent: chat.delta\ndata: {"content":"a"}\n\n',+ 'event: history.message\ndata: {"status":"done","page_idx":1}\n\n',+ 'event: chat.final\ndata: {"content":"a"}\n\n',+ ].join('')+ );+ assert.equal(frames.length, 3);+ assert.equal(sseFrameToWsEvent(frames[0]).event, 'chat.delta');+ assert.equal(sseFrameToWsEvent(frames[1]).payload.status, 'done');+ assert.equal(sseFrameToWsEvent(frames[2]).event, 'chat.final');+});++test('empty history JSON page still emits done', () => {+ const events = historyPageToEvents({ messages: [], page_idx: 1, total_pages: 1 }, 'sid');+ assert.equal(events.length, 1);+ assert.equal(events[0].payload.status, 'done');+});+diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.pyindex d5c7586f46..d0551a19d5 100644--- a/jiuwenswarm/gateway/app_gateway.py+++ b/jiuwenswarm/gateway/app_gateway.py@@ -311,6 +311,31 @@ async def _connect_with_retry(backoff = min(backoff * 2, interval)+def _gateway_agent_client_type() -> str:+ """``gateway.agent_client.type``,缺省 websocket。不探测 Agent 开没开 HTTP。"""+ from jiuwenswarm.common.config import get_config++ try:+ full_cfg = get_config()+ gateway_cfg = full_cfg.get("gateway") if isinstance(full_cfg, dict) else {}+ agent_cfg = gateway_cfg.get("agent_client") if isinstance(gateway_cfg, dict) else {}+ if isinstance(agent_cfg, dict):+ return str(agent_cfg.get("type") or "websocket").strip().lower()+ except Exception: # noqa: BLE001+ pass+ return "websocket"+++def _default_agent_server_url() -> str:+ """未设 AGENT_SERVER_URL 时:type=http 默认 HTTP 口,否则 WS 口。"""+ host = os.getenv("AGENT_SERVER_HOST", "127.0.0.1")+ if _gateway_agent_client_type() == "http":+ port = os.getenv("AGENT_HTTP_PORT") or "8766"+ return f"http://{host}:{port}"+ port = os.getenv("AGENT_SERVER_PORT") or os.getenv("AGENT_PORT", "18092")+ return f"ws://{host}:{port}"++async def _connect_wrap_and_create_message_handler(client,*,@@ -321,14 +346,14 @@ async def _connect_wrap_and_create_message_handler():"""Connect the selected raw client before installing its telemetry proxy."""from jiuwenswarm.gateway.routing.agent_client import WebSocketAgentServerClient+ from jiuwenswarm.gateway.routing.http_agent_client import HttpSseAgentServerClientfrom jiuwenswarm.telemetry.gateway_client import wrap_gateway_agent_client- telemetry_target_uri = (- agent_server_url- if isinstance(client, WebSocketAgentServerClient)- else None+ needs_url_connect = isinstance(+ client, (WebSocketAgentServerClient, HttpSseAgentServerClient))- if isinstance(client, WebSocketAgentServerClient):+ telemetry_target_uri = agent_server_url if needs_url_connect else None+ if needs_url_connect:await _connect_with_retry(client,agent_server_url,@@ -1510,6 +1535,7 @@ async def _run_with_telemetry(from jiuwenswarm.common.cleanup import start_background_cleanupfrom jiuwenswarm.extensions.redis import init_gateway_redis_from_configfrom jiuwenswarm.gateway.routing.agent_client import WebSocketAgentServerClient+ from jiuwenswarm.gateway.routing.http_agent_client import HttpSseAgentServerClientfrom jiuwenswarm.gateway.channel_manager.channel_manager import ChannelManagerfrom jiuwenswarm.gateway.cron import CronTenantRegistryfrom jiuwenswarm.gateway.heartbeat.heartbeat import GatewayHeartbeatService, HeartbeatConfig@@ -1564,11 +1590,14 @@ async def _run_with_telemetry(max_retries = int(os.getenv("AGENT_CONNECT_RETRY", "20"))retry_interval = float(os.getenv("AGENT_CONNECT_RETRY_INTERVAL", "3"))- # 从扩展注册表获取 AgentServerClient(WebSocket 或 Yuanrong 等扩展实现)+ # 从扩展注册表获取 AgentServerClient(WebSocket / HTTP / Yuanrong 等扩展实现)agent_server_ext = extension_registry.get_agent_server_client_extension()if agent_server_ext is not None:logger.info("[App] using extension AgentServerClient: %s", agent_server_ext.metadata.name)client = agent_server_ext.get_client()+ elif _gateway_agent_client_type() == "http":+ logger.info("[App] using HttpSseAgentServerClient (gateway.agent_client.type=http)")+ client = HttpSseAgentServerClient()else:client = WebSocketAgentServerClient(ping_interval=20.0, ping_timeout=600.0)@@ -2878,7 +2907,7 @@ def main() -> None:"-u",default=None,metavar="URL",- help="AgentServer WebSocket URL (default: AGENT_SERVER_URL or ws://AGENT_SERVER_HOST:AGENT_SERVER_PORT).",+ help="AgentServer URL (default: AGENT_SERVER_URL, or type=http → http://host:8766, else ws://host:18092).",)parser.add_argument("--host",@@ -2921,12 +2950,10 @@ def main() -> None:# Error was already printed by parse_dotenv_early()raise SystemExit(1)- default_host = os.getenv("AGENT_SERVER_HOST", "127.0.0.1")- default_port = os.getenv("AGENT_SERVER_PORT") or os.getenv("AGENT_PORT", "18092")agent_server_url = (args.agent_server_urlor os.getenv("AGENT_SERVER_URL")- or f"ws://{default_host}:{default_port}"+ or _default_agent_server_url())web_host = args.host or os.getenv("WEB_HOST", "127.0.0.1")web_port = args.port or int(os.getenv("WEB_PORT", "19000"))diff --git a/jiuwenswarm/gateway/routing/agent_rest_map.py b/jiuwenswarm/gateway/routing/agent_rest_map.pynew file mode 100644index 0000000000..d5e7773b90--- /dev/null+++ b/jiuwenswarm/gateway/routing/agent_rest_map.py@@ -0,0 +1,331 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""E2A ``method`` → AgentServer REST(对照 ``docs/zh/Gateway-AgentServer-HTTP-REST组装.md``)。"""++from __future__ import annotations++import json+import logging+import re+from dataclasses import dataclass+from typing import Any, Mapping+from urllib.parse import quote, urljoin++from jiuwenswarm.common.e2a.models import E2AEnvelope++logger = logging.getLogger(__name__)++API_PREFIX = "/api/v1"+DEFAULT_HTTP_PORT = 8766++_PATH_PLACEHOLDER = re.compile(r"\{([A-Za-z_][A-Za-z0-9_]*)\}")+_WRITE_VERBS = frozenset({"POST", "PUT", "PATCH", "DELETE"})++# method → (verb, path relative to /api/v1). 特殊 chat.* / history stream 在 assemble 里处理。+# 键同时覆盖本仓 ReqMethod 与 Agent HTTP ROUTES 若有字符串漂移的别名。+_ROUTE_ROWS: tuple[tuple[str, str, str], ...] = (+ ("initialize", "POST", "/initialize"),+ ("session.list", "GET", "/sessions"),+ ("session.create", "POST", "/sessions"),+ ("session.rename", "PATCH", "/sessions/{session_id}"),+ ("session.delete", "DELETE", "/sessions/{session_id}"),+ ("session.switch", "POST", "/sessions/{session_id}/actions/switch"),+ ("session.fork", "POST", "/sessions/{session_id}/actions/fork"),+ ("session.rewind", "POST", "/sessions/{session_id}/actions/rewind"),+ ("session.rewind_and_restore", "POST", "/sessions/{session_id}/actions/rewind-restore"),+ ("session.rewind_compact", "POST", "/sessions/{session_id}/actions/rewind-compact"),+ ("session.rewind_context", "POST", "/sessions/{session_id}/actions/rewind-context"),+ ("session.restore_files", "POST", "/sessions/{session_id}/actions/restore-files"),+ ("history.get", "GET", "/sessions/{session_id}/history"),+ ("history.list_turns", "GET", "/sessions/{session_id}/turns"),+ ("chat.interrupt", "POST", "/chat/{session_id}/actions/interrupt"),+ ("chat.user_answer", "POST", "/chat/{session_id}/actions/answer"),+ ("command.session", "POST", "/sessions/{session_id}/commands"),+ ("command.compact", "POST", "/sessions/{session_id}/commands/compact"),+ ("command.compact_partial", "POST", "/sessions/{session_id}/commands/compact-partial"),+ ("command.model", "POST", "/sessions/{session_id}/commands/model"),+ ("command.mcp", "POST", "/sessions/{session_id}/commands/mcp"),+ ("command.sandbox", "POST", "/sessions/{session_id}/commands/sandbox"),+ ("command.btw", "POST", "/sessions/{session_id}/commands/btw"),+ ("command.add_dir", "POST", "/sessions/{session_id}/commands/add-dir"),+ ("command.chrome", "POST", "/sessions/{session_id}/commands/chrome"),+ ("command.context", "POST", "/sessions/{session_id}/commands/context"),+ ("command.recap", "POST", "/sessions/{session_id}/commands/recap"),+ ("command.diff", "POST", "/sessions/{session_id}/commands/diff"),+ ("command.simplify", "POST", "/sessions/{session_id}/commands/simplify"),+ ("command.resume", "POST", "/sessions/{session_id}/commands/resume"),+ ("command.workflows", "POST", "/sessions/{session_id}/commands/workflows"),+ ("command.goal", "POST", "/sessions/{session_id}/commands/goal"),+ ("command.status", "GET", "/sessions/{session_id}/commands/status"),+ ("agents.list", "GET", "/agents"),+ ("agents.create", "POST", "/agents"),+ ("agents.get", "GET", "/agents/{name}"),+ ("agents.update", "PUT", "/agents/{name}"),+ ("agents.delete", "DELETE", "/agents/{name}"),+ ("agents.enable", "POST", "/agents/{name}/actions/enable"),+ ("agents.disable", "POST", "/agents/{name}/actions/disable"),+ ("agents.tools.list", "GET", "/agents/{name}/tools"),+ ("agents.tools_list", "GET", "/agents/{name}/tools"),+ ("team.templates.list", "GET", "/teams/templates"),+ ("team.bindings.list", "GET", "/teams/bindings"),+ ("team.binding.create", "POST", "/teams/bindings"),+ ("team.binding.generate", "POST", "/teams/bindings/actions/generate"),+ ("team.session.bind", "POST", "/teams/{team_name}/sessions/{session_id}/bind"),+ ("team.snapshot", "GET", "/sessions/{session_id}/team/snapshot"),+ ("team.members.get", "GET", "/sessions/{session_id}/team/members"),+ ("team.history.get", "GET", "/sessions/{session_id}/team/history"),+ ("team.mq.publish", "POST", "/teams/mq/publish"),+ ("team.delete", "DELETE", "/teams/{team_name}"),+ ("skills.list", "GET", "/skills"),+ ("skills.installed", "GET", "/skills/installed"),+ ("skills.marketplace.list", "GET", "/skills/marketplace"),+ ("skills.marketplace.add", "POST", "/skills/marketplace"),+ ("skills.marketplace.remove", "DELETE", "/skills/marketplace/{name}"),+ ("skills.marketplace.toggle", "POST", "/skills/marketplace/{name}/actions/toggle"),+ ("skills.install", "POST", "/skills/install"),+ ("skills.import_local", "POST", "/skills/import-local"),+ ("skills.online.search", "POST", "/skills/online-search"),+ ("skills.online_search.search", "POST", "/skills/online-search"),+ ("skills.retrieval.status", "GET", "/skills/retrieval/status"),+ ("skills.retrieval.index_build", "POST", "/skills/retrieval/index-build"),+ ("skills.retrieval.index_cancel", "POST", "/skills/retrieval/index-cancel"),+ ("skills.retrieval.search", "GET", "/skills/retrieval/search"),+ ("skills.retrieval.tree", "GET", "/skills/retrieval/tree"),+ ("skills.evolution.get", "GET", "/skills/evolution"),+ ("skills.evolution.save", "PUT", "/skills/evolution"),+ ("skills.evolution.status", "GET", "/skills/{name}/evolution/status"),+ ("skills.evolution.archives", "GET", "/skills/evolution/archives"),+ ("skills.evolution.rollback", "POST", "/skills/evolution/actions/rollback"),+ ("skills.evolution.rebuild", "POST", "/skills/evolution/actions/rebuild"),+ ("skills.clawhub.get_token", "GET", "/skills/clawhub/token"),+ ("skills.clawhub.set_token", "PUT", "/skills/clawhub/token"),+ ("skills.clawhub.search", "GET", "/skills/clawhub/search"),+ ("skills.clawhub.download", "POST", "/skills/clawhub/actions/download"),+ ("skills.skillnet.search", "GET", "/skills/skillnet/search"),+ ("skills.skillnet.install", "POST", "/skills/skillnet/install"),+ ("skills.skillnet.install_status", "GET", "/skills/skillnet/install-status"),+ ("skills.skillnet.evaluate", "POST", "/skills/skillnet/actions/evaluate"),+ ("skills.teamskillshub.info", "GET", "/skills/teamskillshub/info"),+ ("skills.teamskillshub.search", "GET", "/skills/teamskillshub/search"),+ ("skills.teamskillshub.install", "POST", "/skills/teamskillshub/install"),+ ("skills.teamskillshub.init", "POST", "/skills/teamskillshub/actions/init"),+ ("skills.teamskillshub.validate", "POST", "/skills/teamskillshub/actions/validate"),+ ("skills.teamskillshub.pack", "POST", "/skills/teamskillshub/actions/pack"),+ ("skills.teamskillshub.publish", "POST", "/skills/teamskillshub/actions/publish"),+ ("skills.teamskillshub.delete", "POST", "/skills/teamskillshub/actions/delete"),+ ("skills.enterprise.install", "POST", "/skills/enterprise/install"),+ ("skills.enterprise.uninstall", "POST", "/skills/enterprise/actions/uninstall"),+ ("skills.get", "GET", "/skills/{name}"),+ ("skills.uninstall", "DELETE", "/skills/{name}"),+ ("skills.toggle", "POST", "/skills/{name}/actions/toggle"),+ ("extensions.list", "GET", "/extensions"),+ ("extensions.import", "POST", "/extensions"),+ ("extensions.delete", "DELETE", "/extensions/{name}"),+ ("extensions.toggle", "POST", "/extensions/{name}/actions/toggle"),+ ("hooks.list", "GET", "/hooks"),+ ("plugins.list", "GET", "/plugins"),+ ("plugins.install", "POST", "/plugins/install"),+ ("plugins.reload", "POST", "/plugins/actions/reload"),+ ("plugins.uninstall", "DELETE", "/plugins/{name}"),+ ("plugins.enable", "POST", "/plugins/{name}/actions/enable"),+ ("plugins.disable", "POST", "/plugins/{name}/actions/disable"),+ ("schedule.check_config", "GET", "/schedule/config"),+ ("schedule.update_config", "PATCH", "/schedule/config"),+ ("schedule.list", "GET", "/schedule/tasks"),+ ("schedule.create", "POST", "/schedule/tasks"),+ ("schedule.run", "POST", "/schedule/tasks/actions/run"),+ ("schedule.status", "GET", "/schedule/tasks/{task_id}"),+ ("schedule.logs", "GET", "/schedule/tasks/{task_id}/logs"),+ ("schedule.cancel", "POST", "/schedule/tasks/{task_id}/actions/cancel"),+ ("schedule.delete", "DELETE", "/schedule/tasks/{task_id}"),+ ("issue.watch_once", "POST", "/issues/actions/watch-once"),+ ("issue.state_list", "GET", "/issues/states"),+ ("issue.state.list", "GET", "/issues/states"),+ ("issue.matrix", "POST", "/issues/actions/matrix"),+ ("issue.delete", "DELETE", "/issues/{issue_id}"),+ ("harness.packages.get", "GET", "/harness/packages"),+ ("harness.packages.scan", "POST", "/harness/packages/scan"),+ ("harness.packages.import", "POST", "/harness/packages/import"),+ ("harness.packages.export", "POST", "/harness/packages/export"),+ ("harness.packages.activate", "POST", "/harness/packages/{name}/actions/activate"),+ ("harness.packages.deactivate", "POST", "/harness/packages/{name}/actions/deactivate"),+ ("harness.packages.delete", "DELETE", "/harness/packages/{name}"),+ ("permissions.enabled.get", "GET", "/permissions/enabled"),+ ("permissions.enabled.set", "PUT", "/permissions/enabled"),+ ("permissions.tools.get", "GET", "/permissions/tools"),+ ("permissions.tools.list", "GET", "/permissions/tools/list"),+ ("permissions.tools.set", "PUT", "/permissions/tools"),+ ("permissions.tools.update", "PATCH", "/permissions/tools"),+ ("permissions.tools.delete", "DELETE", "/permissions/tools/{rule_id}"),+ ("permissions.rules.get", "GET", "/permissions/rules"),+ ("permissions.rules.create", "POST", "/permissions/rules"),+ ("permissions.rules.update", "PATCH", "/permissions/rules/{rule_id}"),+ ("permissions.rules.delete", "DELETE", "/permissions/rules/{rule_id}"),+ ("permissions.approval_overrides.get", "GET", "/permissions/approval-overrides"),+ ("permissions.approval_overrides.delete", "DELETE", "/permissions/approval-overrides/{override_id}"),+ ("permissions.file_guard.workspace.rw_enabled.get", "GET", "/permissions/file-guard/workspace"),+ ("permissions.file_guard.workspace.rw_enabled.set", "PUT", "/permissions/file-guard/workspace"),+ ("config.cache_clear", "POST", "/config/actions/cache-clear"),+ ("agent.reload_config", "POST", "/config/actions/agent-reload"),+ ("sync_agents_configs", "POST", "/config/actions/sync-agents"),+ ("agent.prewarm_sync", "POST", "/config/actions/prewarm-sync"),+ ("agent.prewarm.sync", "POST", "/config/actions/prewarm-sync"),+ ("browser.runtime_restart", "POST", "/runtime/browser/actions/restart"),+ ("proactive.tick", "POST", "/proactive/actions/tick"),+ ("acp.tool_response", "POST", "/acp/tool-responses"),+ ("files.list", "GET", "/files"),+ ("files.get", "GET", "/files/content"),+ ("symphony.plan", "POST", "/symphony/actions/plan"),+ ("symphony.build_score", "POST", "/symphony/actions/build-score"),+ ("symphony.pause_build", "POST", "/symphony/actions/pause-build"),+ ("symphony.score_status", "GET", "/symphony/score-status"),+ ("symphony.graph", "GET", "/symphony/graph"),+ ("channel.feishu.get_conf", "GET", "/channels/feishu/config"),+ ("channel.feishu.set_conf", "PUT", "/channels/feishu/config"),+ ("channel.xiaoyi.get_conf", "GET", "/channels/xiaoyi/config"),+ ("channel.xiaoyi.set_conf", "PUT", "/channels/xiaoyi/config"),+ ("channel.telegram.get_conf", "GET", "/channels/telegram/config"),+ ("channel.telegram.set_conf", "PUT", "/channels/telegram/config"),+ ("channel.slack.get_conf", "GET", "/channels/slack/config"),+ ("channel.slack.set_conf", "PUT", "/channels/slack/config"),+ ("channel.dingtalk.get_conf", "GET", "/channels/dingtalk/config"),+ ("channel.dingtalk.set_conf", "PUT", "/channels/dingtalk/config"),+ ("channel.whatsapp.get_conf", "GET", "/channels/whatsapp/config"),+ ("channel.whatsapp.set_conf", "PUT", "/channels/whatsapp/config"),+ ("channel.wechat.get_conf", "GET", "/channels/wechat/config"),+ ("channel.wechat.set_conf", "PUT", "/channels/wechat/config"),+ ("channel.wechat.get_login_ui", "GET", "/channels/wechat/login-ui"),+ ("channel.wechat.unbind", "POST", "/channels/wechat/actions/unbind"),+ ("updater.get_status", "GET", "/updater/status"),+ ("updater.check", "POST", "/updater/actions/check"),+ ("updater.download", "POST", "/updater/actions/download"),+ ("updater.get_conf", "GET", "/updater/config"),+ ("updater.set_conf", "PUT", "/updater/config"),+ ("heartbeat.get_conf", "GET", "/heartbeat/config"),+ ("heartbeat.set_conf", "PUT", "/heartbeat/config"),+)++REST_ROUTES: dict[str, tuple[str, str]] = {method: (verb, path) for method, verb, path in _ROUTE_ROWS}+++class RestAssemblyError(ValueError):+ """REST 路径无法从信封拼出(缺 method / 缺路径占位符)。"""+++@dataclass(frozen=True)+class AssembledRestRequest:+ verb: str+ url: str+ headers: dict[str, str]+ json_body: dict[str, Any] | None+ query: dict[str, str] | None+ used_rpc_fallback: bool+++def normalize_agent_http_base(uri: str) -> str:+ """``http://host:8766`` 或已带 ``/api/v1`` → API 根(无末尾 /)。"""+ raw = (uri or "").strip().rstrip("/")+ if not raw:+ raise RestAssemblyError("AgentServer HTTP URL 为空")+ if raw.endswith(API_PREFIX):+ return raw+ return raw + API_PREFIX+++def identity_headers(envelope: E2AEnvelope, *, accept: str) -> dict[str, str]:+ headers = {+ "X-Request-Id": str(envelope.request_id or ""),+ "X-Channel-Id": str(envelope.channel or "web"),+ "Accept": accept,+ }+ session_id = envelope.session_id or (envelope.params or {}).get("session_id")+ if session_id:+ headers["X-Session-Id"] = str(session_id)+ if envelope.user_id:+ headers["X-User-Id"] = str(envelope.user_id)+ return headers+++def _lookup_route(method: str, *, is_stream: bool) -> tuple[str, str, bool]:+ if method in {"chat.send", "chat.resume"}:+ path = "/chat/completions" if method == "chat.send" else "/chat/resume"+ return "POST", path, False+ if method == "history.get" and is_stream:+ return "GET", "/sessions/{session_id}/history/stream", False+ found = REST_ROUTES.get(method)+ if found is not None:+ return found[0], found[1], False+ logger.warning("[AgentRestMap] method=%s 不在 REST 表,降级 POST /rpc/{method}", method)+ return "POST", f"/rpc/{quote(method, safe='.')}", True+++def _fill_path(template: str, values: Mapping[str, Any]) -> tuple[str, set[str]]:+ used: set[str] = set()+ missing: list[str] = []++ def _replace(match: re.Match[str]) -> str:+ key = match.group(1)+ if key not in values or values[key] is None or values[key] == "":+ missing.append(key)+ return match.group(0)+ used.add(key)+ return quote(str(values[key]), safe="")++ filled = _PATH_PLACEHOLDER.sub(_replace, template)+ if missing:+ raise RestAssemblyError(f"REST 路径缺占位符 {missing}: {template}")+ return filled, used+++def _remaining_params(params: Mapping[str, Any], used: set[str]) -> dict[str, Any]:+ out: dict[str, Any] = {}+ for key, value in params.items():+ if key in used or value is None:+ continue+ out[key] = value+ return out+++def _query_values(remaining: Mapping[str, Any]) -> dict[str, str]:+ query: dict[str, str] = {}+ for key, value in remaining.items():+ if isinstance(value, (dict, list)):+ query[key] = json.dumps(value, ensure_ascii=False, separators=(",", ":"))+ else:+ query[key] = str(value)+ return query+++def assemble_rest_request(envelope: E2AEnvelope, *, base_url: str) -> AssembledRestRequest:+ """信封 → 一条 REST/SSE 请求。body 只含 params,不含整封 E2A。"""+ method = str(envelope.method or "").strip()+ if not method:+ raise RestAssemblyError("envelope.method 为空,无法组装 REST")++ verb, template, rpc = _lookup_route(method, is_stream=bool(envelope.is_stream))+ values: dict[str, Any] = dict(envelope.params or {})+ if envelope.session_id and not values.get("session_id"):+ values["session_id"] = envelope.session_id++ filled, used = _fill_path(template, values)+ remaining = _remaining_params(values, used)+ api_root = normalize_agent_http_base(base_url)+ url = urljoin(api_root + "/", filled.lstrip("/"))++ accept = "text/event-stream" if envelope.is_stream else "application/json"+ headers = identity_headers(envelope, accept=accept)+ json_body: dict[str, Any] | None = None+ query: dict[str, str] | None = None+ if verb == "GET" or template.endswith("/history/stream"):+ query = _query_values(remaining) or None+ else:+ headers["Content-Type"] = "application/json"+ json_body = remaining+ return AssembledRestRequest(+ verb=verb,+ url=url,+ headers=headers,+ json_body=json_body,+ query=query,+ used_rpc_fallback=rpc,+ )diff --git a/jiuwenswarm/gateway/routing/http_agent_client.py b/jiuwenswarm/gateway/routing/http_agent_client.pynew file mode 100644index 0000000000..5011e25640--- /dev/null+++ b/jiuwenswarm/gateway/routing/http_agent_client.py@@ -0,0 +1,366 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""AgentServer HTTP/SSE 客户端(``gateway.agent_client.type=http``)。"""++from __future__ import annotations++import asyncio+import json+import logging+from collections.abc import AsyncIterator, Awaitable, Callable+from typing import Any+from urllib.parse import urlsplit++import httpx++from jiuwenswarm.common.e2a.constants import E2A_WIRE_SERVER_PUSH_KEY+from jiuwenswarm.common.e2a.models import E2AEnvelope+from jiuwenswarm.common.e2a.wire_codec import parse_agent_server_wire_chunk+from jiuwenswarm.common.schema.agent import AgentResponse, AgentResponseChunk+from jiuwenswarm.gateway.routing.agent_client import (+ AGENT_REQUEST_TIMEOUT_SECONDS,+ AgentServerClient,+)+from jiuwenswarm.gateway.routing.agent_rest_map import (+ assemble_rest_request,+ normalize_agent_http_base,+)++logger = logging.getLogger(__name__)++_CONNECT_TIMEOUT_SECONDS = 10.0+_PUSH_RETRY_SECONDS = 3.0+++def http_unary_to_agent_response(+ payload: dict[str, Any],+ *,+ channel_id: str,+ request_id: str,+) -> AgentResponse:+ """拆 Agent HTTP ``{ok, data, error}``,不要喂给 ``parse_agent_server_wire_unary``。"""+ rid = str(payload.get("request_id") or request_id)+ meta = payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {}+ ok = bool(payload.get("ok", False))+ if ok:+ data = payload.get("data")+ if isinstance(data, dict) and isinstance(data.get("result"), dict):+ pl: dict[str, Any] = dict(data["result"])+ elif isinstance(data, dict):+ pl = dict(data)+ elif data is None:+ pl = {}+ else:+ pl = {"content": data}+ return AgentResponse(+ request_id=rid,+ channel_id=channel_id,+ ok=True,+ payload=pl,+ metadata=meta or None,+ )++ err = payload.get("error") if isinstance(payload.get("error"), dict) else {}+ details = err.get("details") if isinstance(err.get("details"), dict) else {}+ code = err.get("code")+ if not code and isinstance(details, dict):+ code = details.get("code")+ pl = {"error": err.get("message"), "code": code}+ if isinstance(details, dict):+ for key, value in details.items():+ pl.setdefault(key, value)+ return AgentResponse(+ request_id=rid,+ channel_id=channel_id,+ ok=False,+ payload=pl,+ metadata=meta or None,+ )+++async def iter_sse_data_frames(response: httpx.Response) -> AsyncIterator[dict[str, Any]]:+ """解析 SSE:丢掉 ``: keepalive``,产出 ``data:`` JSON 对象。"""+ data_lines: list[str] = []++ def _flush() -> dict[str, Any] | None:+ nonlocal data_lines+ if not data_lines:+ return None+ raw = "\n".join(data_lines)+ data_lines = []+ try:+ parsed = json.loads(raw)+ except json.JSONDecodeError:+ logger.warning("[HttpSseAgentServerClient] SSE data 非 JSON,已丢弃")+ return None+ return parsed if isinstance(parsed, dict) else None++ async for line in response.aiter_lines():+ text = line.rstrip("\r")+ if text == "":+ frame = _flush()+ if frame is not None:+ yield frame+ continue+ if text.startswith(":"):+ continue+ if text.startswith("event:"):+ continue+ if text.startswith("data:"):+ data_lines.append(text[5:].lstrip())+ continue+ frame = _flush()+ if frame is not None:+ yield frame+++class HttpSseAgentServerClient(AgentServerClient):+ """按 REST 表发 HTTP;流式读 SSE;打断走另一条 POST,不与 SSE 共用锁。"""++ def __init__(+ self,+ *,+ timeout_s: float = AGENT_REQUEST_TIMEOUT_SECONDS,+ http_client: httpx.AsyncClient | None = None,+ ) -> None:+ self._timeout_s = float(timeout_s)+ self._http = http_client+ self._owns_http = http_client is None+ self._base_url: str | None = None+ self._api_root: str | None = None+ self._server_ready = False+ self._running = False+ self._on_server_push: Callable[[dict[str, Any]], Awaitable[None]] | None = None+ self._push_task: asyncio.Task[None] | None = None++ def set_or_update_server_config(+ self,+ *,+ config: dict[str, Any],+ env: dict[str, str] | None = None,+ ) -> None:+ return None++ def set_server_push_handler(+ self, handler: Callable[[dict[str, Any]], Awaitable[None]] | None+ ) -> None:+ self._on_server_push = handler+ if handler is not None and self._running and self._push_task is None:+ self._push_task = asyncio.create_task(self._push_loop(), name="agent-http-push")++ @property+ def server_ready(self) -> bool:+ return self._server_ready++ def _ensure_connected(self) -> httpx.AsyncClient:+ if self._http is None or not self._running or not self._api_root:+ raise RuntimeError("未连接 AgentServer HTTP,请先调用 connect(uri)")+ return self._http++ async def connect(self, uri: str) -> None:+ if self._running:+ await self.disconnect()+ scheme = (urlsplit(uri).scheme or "").lower()+ if scheme not in {"http", "https"}:+ raise RuntimeError(+ "gateway.agent_client.type=http 需要 AGENT_SERVER_URL 为 http(s)://… "+ f"(当前 {uri!r})。不要打 WS 口。Agent 须已开 http_server。"+ )+ self._base_url = uri.rstrip("/")+ self._api_root = normalize_agent_http_base(uri)+ if self._http is None:+ self._http = httpx.AsyncClient(+ timeout=httpx.Timeout(self._timeout_s, connect=_CONNECT_TIMEOUT_SECONDS),+ limits=httpx.Limits(max_connections=20, max_keepalive_connections=10),+ )+ self._owns_http = True+ health_url = f"{self._api_root}/health"+ logger.info("[HttpSseAgentServerClient] 正在连接: %s", health_url)+ response = await self._http.get(health_url, headers={"Accept": "application/json"})+ payload: dict[str, Any] = {}+ try:+ parsed = response.json()+ if isinstance(parsed, dict):+ payload = parsed+ except Exception: # noqa: BLE001+ payload = {}+ if response.status_code >= 400 or not payload.get("ok", False):+ raise RuntimeError(+ f"AgentServer HTTP health 失败: status={response.status_code} url={health_url} "+ "确认 Agent 已开 http_server.enabled / AGENT_HTTP_ENABLED"+ )+ self._server_ready = True+ self._running = True+ logger.info("[HttpSseAgentServerClient] health ok: %s", health_url)+ if self._on_server_push is not None and self._push_task is None:+ self._push_task = asyncio.create_task(self._push_loop(), name="agent-http-push")++ async def disconnect(self) -> None:+ self._running = False+ self._server_ready = False+ task = self._push_task+ self._push_task = None+ if task is not None:+ task.cancel()+ try:+ await task+ except (asyncio.CancelledError, Exception): # noqa: BLE001+ pass+ if self._owns_http and self._http is not None:+ await self._http.aclose()+ self._http = None+ self._base_url = None+ self._api_root = None+ logger.info("[HttpSseAgentServerClient] 已断开")++ async def send_request(self, envelope: E2AEnvelope) -> AgentResponse:+ http = self._ensure_connected()+ envelope.is_stream = False+ assembled = assemble_rest_request(envelope, base_url=self._api_root or "")+ channel_id = str(envelope.channel or "web")+ rid = str(envelope.request_id or "")+ logger.info(+ "[E2A][out][http][unary] request_id=%s method=%s %s %s rpc=%s",+ rid,+ envelope.method,+ assembled.verb,+ assembled.url,+ assembled.used_rpc_fallback,+ )+ response = await http.request(+ assembled.verb,+ assembled.url,+ headers=assembled.headers,+ json=assembled.json_body,+ params=assembled.query,+ )+ payload = _response_json(response, request_id=rid)+ return http_unary_to_agent_response(+ payload, channel_id=channel_id, request_id=rid+ )++ async def send_request_stream(+ self, envelope: E2AEnvelope+ ) -> AsyncIterator[AgentResponseChunk]:+ http = self._ensure_connected()+ envelope.is_stream = True+ assembled = assemble_rest_request(envelope, base_url=self._api_root or "")+ channel_id = str(envelope.channel or "web")+ rid = str(envelope.request_id or "")+ logger.info(+ "[E2A][out][http][stream] request_id=%s method=%s %s %s rpc=%s",+ rid,+ envelope.method,+ assembled.verb,+ assembled.url,+ assembled.used_rpc_fallback,+ )+ timeout = httpx.Timeout(None, connect=_CONNECT_TIMEOUT_SECONDS)+ async with http.stream(+ assembled.verb,+ assembled.url,+ headers=assembled.headers,+ json=assembled.json_body,+ params=assembled.query,+ timeout=timeout,+ ) as response:+ if response.status_code >= 400:+ body = await response.aread()+ payload = _bytes_json(body, request_id=rid)+ err = http_unary_to_agent_response(+ payload, channel_id=channel_id, request_id=rid+ )+ yield AgentResponseChunk(+ request_id=rid,+ channel_id=channel_id,+ payload=err.payload or {"error": "stream http error"},+ is_complete=True,+ metadata=err.metadata or {},+ )+ return+ async for frame in iter_sse_data_frames(response):+ try:+ chunk = parse_agent_server_wire_chunk(frame)+ except Exception:+ logger.exception(+ "[HttpSseAgentServerClient] SSE 帧无法按 E2A chunk 解析 request_id=%s",+ rid,+ )+ continue+ if not chunk.channel_id:+ chunk.channel_id = channel_id+ yield chunk++ async def _push_loop(self) -> None:+ while self._running and self._on_server_push is not None:+ api_root = self._api_root+ if not api_root:+ logger.warning(+ "[HttpSseAgentServerClient] events/stream 缺少 API 根路径,停止推送循环"+ )+ return+ url = f"{api_root}/events/stream"+ try:+ http = self._ensure_connected()+ timeout = httpx.Timeout(None, connect=_CONNECT_TIMEOUT_SECONDS)+ async with http.stream("GET", url, timeout=timeout) as response:+ response.raise_for_status()+ async for frame in iter_sse_data_frames(response):+ meta = frame.get("metadata")+ if not (isinstance(meta, dict) and meta.get(E2A_WIRE_SERVER_PUSH_KEY)):+ continue+ handler = self._on_server_push+ if handler is None:+ continue+ try:+ await handler(frame)+ except Exception:+ logger.exception("[HttpSseAgentServerClient] server_push 处理失败")+ except Exception as exc: # noqa: BLE001+ if not self._running:+ return+ logger.warning(+ "[HttpSseAgentServerClient] events/stream 断开,%.0fs 后重连: %s",+ _PUSH_RETRY_SECONDS,+ exc,+ )+ else:+ if not self._running:+ return+ logger.info(+ "[HttpSseAgentServerClient] events/stream 结束,%.0fs 后重连",+ _PUSH_RETRY_SECONDS,+ )+ await asyncio.sleep(_PUSH_RETRY_SECONDS)+++def _response_json(response: httpx.Response, *, request_id: str) -> dict[str, Any]:+ try:+ parsed = response.json()+ if isinstance(parsed, dict):+ return parsed+ except Exception: # noqa: BLE001+ pass+ return {+ "request_id": request_id,+ "ok": False,+ "error": {+ "code": "HTTP_ERROR",+ "message": f"status={response.status_code} non-json body",+ "details": {},+ },+ }+++def _bytes_json(body: bytes, *, request_id: str) -> dict[str, Any]:+ try:+ parsed = json.loads(body.decode("utf-8") or "{}")+ if isinstance(parsed, dict):+ return parsed+ except Exception: # noqa: BLE001+ pass+ return {+ "request_id": request_id,+ "ok": False,+ "error": {"code": "HTTP_ERROR", "message": "stream open failed", "details": {}},+ }diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yamlindex 69b98811fb..8065af0c11 100644--- a/jiuwenswarm/resources/config.yaml+++ b/jiuwenswarm/resources/config.yaml@@ -730,9 +730,10 @@ gateway:interval_seconds: ${GATEWAY_CONFIG_POLL_INTERVAL_SECONDS:-10}# AgentClient 配置 - Gateway 连接到 AgentServer 的方式- # type: websocket(默认) | yuanrong(直接函数调用) | agentos_router(AgentOS 扩展)+ # type: websocket(默认) | http(REST/SSE,须 Agent 已开 http_server) | yuanrong | agentos_router+ # http 不探测、不回退 WS;AGENT_SERVER_URL 用 http://host:8766,不要打 WS :18092。agent_client:- type: websocket # websocket | yuanrong | agentos_router+ type: websocket # websocket | http | yuanrong | agentos_router# yuanrong 函数模式配置下面参数frontend_endpoint:function_version_urn:diff --git a/tests/unit_tests/gateway/test_agent_rest_map.py b/tests/unit_tests/gateway/test_agent_rest_map.pynew file mode 100644index 0000000000..767665c102--- /dev/null+++ b/tests/unit_tests/gateway/test_agent_rest_map.py@@ -0,0 +1,331 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Gateway → Agent HTTP:method 查表、填路径、body/query、身份头、表外 RPC。"""++from __future__ import annotations++import json+from urllib.parse import quote, urlparse++import pytest++from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields+from jiuwenswarm.common.schema.message import ReqMethod+from jiuwenswarm.gateway.routing.agent_rest_map import (+ API_PREFIX,+ REST_ROUTES,+ RestAssemblyError,+ _PATH_PLACEHOLDER,+ assemble_rest_request,+ normalize_agent_http_base,+)++BASE = "http://127.0.0.1:8766"++PATH_SAMPLES: dict[str, str] = {+ "session_id": "sess_1",+ "name": "agent_a",+ "team_name": "team_a",+ "task_id": "task_1",+ "issue_id": "issue_1",+ "rule_id": "rule_1",+ "override_id": "ovr_1",+}++# 本仓 ReqMethod 有、REST 表没有:只允许走 POST /rpc/{method},禁止猜路径。+_RPC_ALLOWLIST = frozenset(+ {+ "chat.swarmflow_reply",+ "ssh.relay",+ "config.get",+ "config.set",+ "channel.get",+ "team.session.reset",+ "path.get",+ "path.set",+ "logging.set",+ "memory.compute",+ "tts.synthesize",+ "3rdagent.switch",+ "3rdagent.list",+ "skills.enterprise.list",+ }+)++_SPECIAL_METHODS = frozenset({"chat.send", "chat.resume"})+++def _env(+ method: str | ReqMethod,+ *,+ params: dict | None = None,+ session_id: str | None = "sess_1",+ is_stream: bool = False,+ user_id: str | None = "u1",+ request_id: str = "r1",+ channel_id: str = "web",+):+ return e2a_from_agent_fields(+ request_id=request_id,+ channel_id=channel_id,+ session_id=session_id,+ req_method=method,+ params=params,+ is_stream=is_stream,+ user_id=user_id,+ )+++def _params_for(path: str) -> dict:+ params = {key: PATH_SAMPLES[key] for key in _PATH_PLACEHOLDER.findall(path)}+ params["limit"] = 3+ return params+++ ("method", "verb", "path"),+ [(method, verb, path) for method, (verb, path) in REST_ROUTES.items()],+ ids=list(REST_ROUTES),+)+def test_every_rest_route_assembles(method: str, verb: str, path: str):+ assembled = assemble_rest_request(+ _env(method, params=_params_for(path)),+ base_url=BASE,+ )+ assert assembled.used_rpc_fallback is False+ assert assembled.verb == verb+ expected = f"{BASE}{API_PREFIX}" + path.format(+ **{k: quote(v, safe="") for k, v in PATH_SAMPLES.items() if f"{{{k}}}" in path}+ )+ assert assembled.url == expected+ used = set(_PATH_PLACEHOLDER.findall(path))+ remaining: dict = {"limit": 3}+ if "session_id" not in used:+ remaining["session_id"] = "sess_1"+ if verb == "GET":+ assert assembled.json_body is None+ assert assembled.query == {k: str(v) for k, v in remaining.items()}+ assert assembled.headers["Accept"] == "application/json"+ assert "Content-Type" not in assembled.headers+ else:+ assert assembled.query is None+ assert assembled.json_body == remaining+ assert assembled.headers["Content-Type"] == "application/json"+ for key in used:+ assert key not in assembled.json_body+ assert assembled.headers["X-Request-Id"] == "r1"+ assert assembled.headers["X-Channel-Id"] == "web"+ assert assembled.headers["X-Session-Id"] == "sess_1"+ assert assembled.headers["X-User-Id"] == "u1"+ if assembled.json_body is not None:+ assert "method" not in assembled.json_body+ assert "request_id" not in assembled.json_body+ assert "channel" not in assembled.json_body++[email protected]("req_method", list(ReqMethod), ids=lambda m: m.value)+def test_every_reqmethod_is_rest_or_documented_rpc(req_method: ReqMethod):+ method = req_method.value+ placeholders = REST_ROUTES.get(method, ("POST", ""))[1]+ assembled = assemble_rest_request(+ _env(method, params=_params_for(placeholders) if placeholders else dict(PATH_SAMPLES)),+ base_url=BASE,+ )+ if method in REST_ROUTES or method in _SPECIAL_METHODS:+ assert assembled.used_rpc_fallback is False, method+ return+ assert method in _RPC_ALLOWLIST, f"新增 method {method}:补 REST 表或写入 _RPC_ALLOWLIST"+ assert assembled.used_rpc_fallback is True+ assert assembled.verb == "POST"+ assert assembled.url.endswith(f"/rpc/{method}")+++def test_chat_send_and_resume_ignore_stream_flag_for_path():+ send_stream = assemble_rest_request(+ _env(ReqMethod.CHAT_SEND, params={"query": "hi"}, is_stream=True),+ base_url=BASE,+ )+ send_unary = assemble_rest_request(+ _env(ReqMethod.CHAT_SEND, params={"query": "hi"}, is_stream=False),+ base_url=BASE,+ )+ resume = assemble_rest_request(+ _env(ReqMethod.CHAT_RESUME, params={"query": "hi"}, is_stream=True),+ base_url=BASE,+ )+ assert send_stream.url.endswith("/chat/completions")+ assert send_unary.url.endswith("/chat/completions")+ assert send_stream.headers["Accept"] == "text/event-stream"+ assert send_unary.headers["Accept"] == "application/json"+ assert resume.url.endswith("/chat/resume")+ assert send_stream.used_rpc_fallback is False+++def test_history_get_stream_switches_path_unary_keeps_history():+ stream = assemble_rest_request(+ _env(ReqMethod.HISTORY_GET, params={"limit": 20}, is_stream=True),+ base_url=BASE,+ )+ unary = assemble_rest_request(+ _env(ReqMethod.HISTORY_GET, params={"limit": 20}, is_stream=False),+ base_url=BASE,+ )+ assert stream.verb == "GET"+ assert stream.url.endswith("/sessions/sess_1/history/stream")+ assert stream.query == {"limit": "20"}+ assert stream.json_body is None+ assert unary.url.endswith("/sessions/sess_1/history")+ assert "/stream" not in unary.url+++ ("alias", "canonical"),+ [+ ("agents.tools_list", "agents.tools.list"),+ ("agent.prewarm_sync", "agent.prewarm.sync"),+ ("issue.state_list", "issue.state.list"),+ ("skills.online.search", "skills.online_search.search"),+ ],+)+def test_method_aliases_share_path(alias: str, canonical: str):+ params = _params_for(REST_ROUTES[canonical][1])+ left = assemble_rest_request(_env(alias, params=params), base_url=BASE)+ right = assemble_rest_request(_env(canonical, params=params), base_url=BASE)+ assert left.verb == right.verb+ assert left.url == right.url+ assert left.used_rpc_fallback is False+ assert right.used_rpc_fallback is False+++def test_skills_static_names_are_not_skills_get():+ clawhub = assemble_rest_request(_env("skills.clawhub.get_token", params={}), base_url=BASE)+ get_named = assemble_rest_request(+ _env("skills.get", params={"name": "clawhub"}),+ base_url=BASE,+ )+ assert clawhub.url.endswith("/skills/clawhub/token")+ assert get_named.url.endswith("/skills/clawhub")+ assert clawhub.url != get_named.url+++def test_session_id_from_envelope_when_params_omit_it():+ assembled = assemble_rest_request(+ _env(ReqMethod.SESSION_RENAME, params={"title": "n"}, session_id="from-env"),+ base_url=BASE,+ )+ assert assembled.url.endswith("/sessions/from-env")+ assert assembled.json_body == {"title": "n"}+++def test_params_session_id_wins_over_envelope():+ assembled = assemble_rest_request(+ _env(+ ReqMethod.SESSION_RENAME,+ params={"session_id": "from-params", "title": "n"},+ session_id="from-env",+ ),+ base_url=BASE,+ )+ assert assembled.url.endswith("/sessions/from-params")+++def test_path_placeholder_is_percent_encoded():+ assembled = assemble_rest_request(+ _env(ReqMethod.SESSION_DELETE, params={}, session_id="sess/a b"),+ base_url=BASE,+ )+ assert assembled.url.endswith("/sessions/sess%2Fa%20b")+++def test_missing_path_placeholder_raises_and_does_not_emit_half_url():+ with pytest.raises(RestAssemblyError, match="session_id"):+ assemble_rest_request(+ _env(ReqMethod.SESSION_DELETE, params={}, session_id=None),+ base_url=BASE,+ )+++def test_team_bind_missing_one_of_two_placeholders_raises():+ with pytest.raises(RestAssemblyError, match="team_name"):+ assemble_rest_request(+ _env(+ ReqMethod.TEAM_SESSION_BIND,+ params={"session_id": "s1"},+ session_id="s1",+ ),+ base_url=BASE,+ )+++def test_empty_method_raises():+ env = e2a_from_agent_fields(+ request_id="r1",+ channel_id="web",+ req_method=None,+ params={},+ )+ with pytest.raises(RestAssemblyError, match="method"):+ assemble_rest_request(env, base_url=BASE)+++def test_unknown_method_rpc_keeps_dots_and_puts_remaining_in_body():+ assembled = assemble_rest_request(+ _env("file.transfer.start", params={"chunk": 1}, session_id="s1"),+ base_url=BASE,+ )+ assert assembled.used_rpc_fallback is True+ assert assembled.url.endswith("/rpc/file.transfer.start")+ assert assembled.json_body == {"chunk": 1, "session_id": "s1"}+++def test_get_nested_params_are_json_in_query():+ assembled = assemble_rest_request(+ _env(ReqMethod.SESSION_LIST, params={"filter": {"a": 1}, "tags": ["x"]}, session_id=None),+ base_url=BASE,+ )+ assert assembled.query is not None+ assert json.loads(assembled.query["filter"]) == {"a": 1}+ assert json.loads(assembled.query["tags"]) == ["x"]+++def test_none_params_are_dropped():+ assembled = assemble_rest_request(+ _env(ReqMethod.SESSION_CREATE, params={"title": "t", "hint": None}),+ base_url=BASE,+ )+ assert assembled.json_body == {"title": "t", "session_id": "sess_1"}+++def test_identity_headers_omit_optional_ids():+ assembled = assemble_rest_request(+ _env(ReqMethod.SESSION_LIST, params={}, session_id=None, user_id=None, channel_id=""),+ base_url=BASE,+ )+ assert assembled.headers["X-Channel-Id"] == "web"+ assert "X-Session-Id" not in assembled.headers+ assert "X-User-Id" not in assembled.headers+++def test_normalize_base_empty_raises():+ with pytest.raises(RestAssemblyError, match="空"):+ normalize_agent_http_base(" ")+++ ("raw", "expected"),+ [+ ("http://h:8766", "http://h:8766/api/v1"),+ ("http://h:8766/", "http://h:8766/api/v1"),+ ("http://h:8766/api/v1", "http://h:8766/api/v1"),+ ("http://h:8766/api/v1/", "http://h:8766/api/v1"),+ ("https://h:443/api/v1", "https://h:443/api/v1"),+ ],+)+def test_normalize_agent_http_base(raw: str, expected: str):+ assert normalize_agent_http_base(raw) == expected+++def test_assembled_url_keeps_api_prefix_segment():+ assembled = assemble_rest_request(_env(ReqMethod.SESSION_LIST, params={}), base_url=BASE)+ parsed = urlparse(assembled.url)+ assert parsed.path.startswith("/api/v1/")diff --git a/tests/unit_tests/gateway/test_http_agent_client.py b/tests/unit_tests/gateway/test_http_agent_client.pynew file mode 100644index 0000000000..3db02c76e8--- /dev/null+++ b/tests/unit_tests/gateway/test_http_agent_client.py@@ -0,0 +1,715 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++from __future__ import annotations++import asyncio+import json++import httpx+import pytest++from jiuwenswarm.common.e2a.constants import E2A_WIRE_SERVER_PUSH_KEY+from jiuwenswarm.common.e2a.gateway_normalize import e2a_from_agent_fields+from jiuwenswarm.common.e2a.wire_codec import encode_agent_chunk_for_wire+from jiuwenswarm.common.schema.agent import AgentResponseChunk+from jiuwenswarm.common.schema.message import ReqMethod+from jiuwenswarm.gateway.routing.agent_rest_map import (+ RestAssemblyError,+ assemble_rest_request,+)+from jiuwenswarm.gateway.routing.http_agent_client import (+ HttpSseAgentServerClient,+ http_unary_to_agent_response,+ iter_sse_data_frames,+)+++def test_assemble_chat_send_uses_completions_and_params_body_only():+ env = e2a_from_agent_fields(+ request_id="r1",+ channel_id="web",+ session_id="s1",+ req_method=ReqMethod.CHAT_SEND,+ params={"query": "hi", "session_id": "s1"},+ is_stream=True,+ user_id="u1",+ )+ assembled = assemble_rest_request(env, base_url="http://127.0.0.1:8766")+ assert assembled.verb == "POST"+ assert assembled.url == "http://127.0.0.1:8766/api/v1/chat/completions"+ assert assembled.json_body == {"query": "hi", "session_id": "s1"}+ assert assembled.headers["X-Request-Id"] == "r1"+ assert assembled.headers["X-Session-Id"] == "s1"+ assert assembled.headers["X-User-Id"] == "u1"+ assert assembled.headers["Accept"] == "text/event-stream"+ assert assembled.used_rpc_fallback is False+ assert assembled.json_body is not None+ assert "method" not in assembled.json_body+ assert "request_id" not in assembled.json_body+++def test_assemble_session_rename_fills_path_and_drops_used_keys():+ env = e2a_from_agent_fields(+ request_id="r2",+ channel_id="web",+ session_id="sess-9",+ req_method=ReqMethod.SESSION_RENAME,+ params={"title": "new"},+ is_stream=False,+ )+ assembled = assemble_rest_request(env, base_url="http://127.0.0.1:8766")+ assert assembled.verb == "PATCH"+ assert assembled.url == "http://127.0.0.1:8766/api/v1/sessions/sess-9"+ assert assembled.json_body == {"title": "new"}+++def test_assemble_history_stream_uses_stream_path_and_query():+ env = e2a_from_agent_fields(+ request_id="r3",+ channel_id="web",+ session_id="s1",+ req_method=ReqMethod.HISTORY_GET,+ params={"limit": 20},+ is_stream=True,+ )+ assembled = assemble_rest_request(env, base_url="http://127.0.0.1:8766")+ assert assembled.verb == "GET"+ assert assembled.url.endswith("/sessions/s1/history/stream")+ assert assembled.query == {"limit": "20"}+ assert assembled.json_body is None+++def test_assemble_unknown_method_falls_back_to_rpc():+ env = e2a_from_agent_fields(+ request_id="r4",+ channel_id="web",+ session_id="s1",+ req_method=ReqMethod.TEAM_SESSION_RESET,+ params={"hard": True},+ is_stream=False,+ )+ assembled = assemble_rest_request(env, base_url="http://127.0.0.1:8766")+ assert assembled.used_rpc_fallback is True+ assert assembled.url.endswith("/rpc/team.session.reset")+ assert assembled.json_body == {"hard": True, "session_id": "s1"}+++def test_assemble_missing_path_placeholder_raises():+ env = e2a_from_agent_fields(+ request_id="r5",+ channel_id="web",+ req_method=ReqMethod.AGENTS_GET,+ params={},+ is_stream=False,+ )+ with pytest.raises(RestAssemblyError):+ assemble_rest_request(env, base_url="http://127.0.0.1:8766")+++def test_http_unary_unwraps_data_result_and_error_details_code():+ ok = http_unary_to_agent_response(+ {+ "request_id": "r1",+ "ok": True,+ "data": {"result": {"title": "ok"}},+ "metadata": {"k": 1},+ },+ channel_id="web",+ request_id="fallback",+ )+ assert ok.ok is True+ assert ok.payload == {"title": "ok"}+ assert ok.metadata == {"k": 1}++ bad = http_unary_to_agent_response(+ {+ "request_id": "r2",+ "ok": False,+ "error": {+ "code": "E2A.AGENT_ERROR",+ "message": "Agent error",+ "details": {"code": "NOT_FOUND", "error": "missing"},+ },+ },+ channel_id="web",+ request_id="r2",+ )+ assert bad.ok is False+ assert bad.payload["code"] == "E2A.AGENT_ERROR"+ assert bad.payload["error"] == "Agent error"+++async def test_connect_rejects_websocket_url():+ client = HttpSseAgentServerClient()+ with pytest.raises(RuntimeError, match="http\\(s\\)"):+ await client.connect("ws://127.0.0.1:18092")+++def _sse_blob(wire: dict) -> bytes:+ return f"event: e2a.chunk\ndata: {json.dumps(wire, ensure_ascii=False)}\n\n".encode("utf-8")+++def _http_json(payload: dict) -> bytes:+ body = json.dumps(payload).encode("utf-8")+ return (+ f"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"+ f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n"+ ).encode("ascii") + body+++async def _start_interrupt_stub():+ interrupt_received = asyncio.Event()+ interrupt_paths: list[str] = []++ async def _handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:+ try:+ header = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), timeout=5)+ request_line = header.split(b"\r\n", 1)[0].decode("ascii", errors="replace")+ _method, path, *_rest = request_line.split(" ")+ content_length = 0+ for raw in header.split(b"\r\n"):+ if raw.lower().startswith(b"content-length:"):+ content_length = int(raw.split(b":", 1)[1].strip() or 0)+ if content_length:+ await reader.readexactly(content_length)++ if path.endswith("/health"):+ writer.write(+ _http_json({"ok": True, "data": {"status": "ready"}, "request_id": "h1"})+ )+ elif path.endswith("/actions/interrupt"):+ interrupt_paths.append(path)+ interrupt_received.set()+ writer.write(+ _http_json(+ {+ "request_id": "int-1",+ "ok": True,+ "data": {"accepted": True},+ "metadata": {},+ }+ )+ )+ elif path.endswith("/chat/completions"):+ delta = encode_agent_chunk_for_wire(+ AgentResponseChunk(+ request_id="chat-1",+ channel_id="web",+ payload={"content": "hi", "event_type": "chat.delta"},+ is_complete=False,+ ),+ response_id="chat-1",+ sequence=0,+ )+ done = encode_agent_chunk_for_wire(+ AgentResponseChunk(+ request_id="chat-1",+ channel_id="web",+ payload={"is_complete": True},+ is_complete=True,+ ),+ response_id="chat-1",+ sequence=1,+ )+ writer.write(+ b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n"+ b"Cache-Control: no-cache\r\nConnection: close\r\n\r\n"+ )+ writer.write(_sse_blob(delta))+ await writer.drain()+ await asyncio.wait_for(interrupt_received.wait(), timeout=5)+ writer.write(_sse_blob(done))+ else:+ writer.write(_http_json({"ok": False, "error": {"code": "NOT_FOUND"}}))+ await writer.drain()+ finally:+ writer.close()+ try:+ await writer.wait_closed()+ except Exception: # noqa: BLE001+ pass++ server = await asyncio.start_server(_handle, "127.0.0.1", 0)+ port = server.sockets[0].getsockname()[1]+ return server, port, interrupt_received, interrupt_paths+++async def test_interrupt_posts_while_sse_still_open():+ server, port, interrupt_received, interrupt_paths = await _start_interrupt_stub()+ base = f"http://127.0.0.1:{port}"+ client = HttpSseAgentServerClient()+ try:+ await client.connect(base)+ chat_env = e2a_from_agent_fields(+ request_id="chat-1",+ channel_id="web",+ session_id="sess-1",+ req_method=ReqMethod.CHAT_SEND,+ params={"query": "hi"},+ is_stream=True,+ )+ interrupt_env = e2a_from_agent_fields(+ request_id="int-1",+ channel_id="web",+ session_id="sess-1",+ req_method=ReqMethod.CHAT_CANCEL,+ params={"intent": "cancel"},+ is_stream=False,+ )+ chunks: list[AgentResponseChunk] = []+ async for chunk in client.send_request_stream(chat_env):+ chunks.append(chunk)+ if len(chunks) == 1:+ resp = await client.send_request(interrupt_env)+ assert resp.ok is True+ assert interrupt_received.is_set()+ assert interrupt_paths == ["/api/v1/chat/sess-1/actions/interrupt"]+ assert len(chunks) >= 2+ finally:+ await client.disconnect()+ server.close()+ await server.wait_closed()+++def test_default_agent_url_http_when_type_http(monkeypatch):+ monkeypatch.setenv("AGENT_SERVER_HOST", "127.0.0.1")+ monkeypatch.delenv("AGENT_HTTP_PORT", raising=False)+ monkeypatch.setattr(+ "jiuwenswarm.gateway.app_gateway._gateway_agent_client_type",+ lambda: "http",+ )+ from jiuwenswarm.gateway.app_gateway import _default_agent_server_url++ assert _default_agent_server_url() == "http://127.0.0.1:8766"+++def test_default_agent_url_http_honors_port_env(monkeypatch):+ monkeypatch.setenv("AGENT_SERVER_HOST", "10.0.0.2")+ monkeypatch.setenv("AGENT_HTTP_PORT", "9999")+ monkeypatch.setattr(+ "jiuwenswarm.gateway.app_gateway._gateway_agent_client_type",+ lambda: "http",+ )+ from jiuwenswarm.gateway.app_gateway import _default_agent_server_url++ assert _default_agent_server_url() == "http://10.0.0.2:9999"+++def test_default_agent_url_websocket_when_type_default(monkeypatch):+ monkeypatch.setenv("AGENT_SERVER_HOST", "127.0.0.1")+ monkeypatch.delenv("AGENT_SERVER_PORT", raising=False)+ monkeypatch.delenv("AGENT_PORT", raising=False)+ monkeypatch.setattr(+ "jiuwenswarm.gateway.app_gateway._gateway_agent_client_type",+ lambda: "websocket",+ )+ from jiuwenswarm.gateway.app_gateway import _default_agent_server_url++ assert _default_agent_server_url() == "ws://127.0.0.1:18092"+++ ("payload", "expect_ok", "expect_payload"),+ [+ (+ {"request_id": "r1", "ok": True, "data": {"result": {"title": "ok"}}},+ True,+ {"title": "ok"},+ ),+ (+ {"request_id": "r1", "ok": True, "data": {"sessions": []}},+ True,+ {"sessions": []},+ ),+ ({"request_id": "r1", "ok": True, "data": None}, True, {}),+ ({"request_id": "r1", "ok": True, "data": "hello"}, True, {"content": "hello"}),+ ({"ok": True}, True, {}),+ (+ {+ "request_id": "r2",+ "ok": False,+ "error": {"code": "NOT_FOUND", "message": "missing", "details": {"k": 1}},+ },+ False,+ {"error": "missing", "code": "NOT_FOUND", "k": 1},+ ),+ (+ {+ "ok": False,+ "error": {+ "message": "Agent error",+ "details": {"code": "E2A.AGENT_ERROR", "error": "inner"},+ },+ },+ False,+ {"error": "Agent error", "code": "E2A.AGENT_ERROR"},+ ),+ ({"ok": False}, False, {"error": None, "code": None}),+ ],+)+def test_http_unary_unwrap_shapes(payload, expect_ok, expect_payload):+ resp = http_unary_to_agent_response(payload, channel_id="web", request_id="fallback")+ assert resp.ok is expect_ok+ assert resp.channel_id == "web"+ for key, value in expect_payload.items():+ assert resp.payload.get(key) == value+ if payload.get("request_id"):+ assert resp.request_id == payload["request_id"]+ else:+ assert resp.request_id == "fallback"+++class _LineResponse:+ def __init__(self, text: str) -> None:+ self._text = text++ async def aiter_lines(self):+ for line in self._text.split("\n"):+ yield line+++async def test_iter_sse_skips_keepalive_event_and_bad_json():+ blob = (+ ": keepalive\n"+ "\n"+ "event: e2a.chunk\n"+ "data: not-json\n"+ "\n"+ "data: [1,2]\n"+ "\n"+ "data: {\"a\": 1}\n"+ "\n"+ "data: {\"ok\": true, \"n\": 2}\n"+ "\n"+ "data: {\"trail\": true}\n"+ )+ frames = [frame async for frame in iter_sse_data_frames(_LineResponse(blob))]+ assert frames == [{"a": 1}, {"ok": True, "n": 2}, {"trail": True}]+++async def test_iter_sse_joins_multiline_data():+ blob = "data: {\n" 'data: "ok": true\n' "data: }\n" "\n"+ frames = [frame async for frame in iter_sse_data_frames(_LineResponse(blob))]+ assert frames == [{"ok": True}]+++def _health_ok(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json={"ok": True, "data": {"status": "ready"}})+++def _chunk_wire(request_id: str, *, complete: bool, content: str = "hi") -> dict:+ return encode_agent_chunk_for_wire(+ AgentResponseChunk(+ request_id=request_id,+ channel_id="web",+ payload={"content": content, "event_type": "chat.delta"}+ if not complete+ else {"is_complete": True},+ is_complete=complete,+ ),+ response_id=request_id,+ sequence=1 if complete else 0,+ )+++async def _connected(handler) -> HttpSseAgentServerClient:+ http = httpx.AsyncClient(transport=httpx.MockTransport(handler))+ client = HttpSseAgentServerClient(http_client=http)+ await client.connect("http://127.0.0.1:8766")+ return client+++async def test_connect_rejects_wss_and_empty_scheme():+ client = HttpSseAgentServerClient()+ with pytest.raises(RuntimeError, match="http\\(s\\)"):+ await client.connect("wss://127.0.0.1:18092")+ with pytest.raises(RuntimeError, match="http\\(s\\)"):+ await client.connect("127.0.0.1:8766")+++ "health",+ [+ lambda _r: httpx.Response(503, json={"ok": False, "error": {"code": "DOWN"}}),+ lambda _r: httpx.Response(200, json={"ok": False, "data": {"status": "starting"}}),+ lambda _r: httpx.Response(200, json={"status": "ready"}),+ lambda _r: httpx.Response(200, content=b"not-json"),+ lambda _r: httpx.Response(200, json=["nope"]),+ ],+)+async def test_connect_health_failure_does_not_mark_ready(health):+ client = HttpSseAgentServerClient(+ http_client=httpx.AsyncClient(transport=httpx.MockTransport(health))+ )+ with pytest.raises(RuntimeError, match="health"):+ await client.connect("http://127.0.0.1:8766")+ assert client.server_ready is False+++async def test_connect_https_health_ok():+ client = await _connected(_health_ok)+ try:+ assert client.server_ready is True+ finally:+ await client.disconnect()+++async def test_send_before_connect_raises():+ client = HttpSseAgentServerClient()+ env = e2a_from_agent_fields(+ request_id="r1",+ channel_id="web",+ req_method=ReqMethod.SESSION_LIST,+ params={},+ )+ with pytest.raises(RuntimeError, match="未连接"):+ await client.send_request(env)+++async def test_send_request_unary_success_and_non_json():+ seen: list[httpx.Request] = []++ def handler(request: httpx.Request) -> httpx.Response:+ seen.append(request)+ if request.url.path.endswith("/health"):+ return _health_ok(request)+ if request.url.path.endswith("/sessions"):+ return httpx.Response(+ 200,+ json={+ "request_id": "t-list",+ "ok": True,+ "data": {"result": {"sessions": [{"id": "s1"}]}},+ "metadata": {"k": 1},+ },+ )+ return httpx.Response(200, content=b"<html>nope</html>")++ client = await _connected(handler)+ try:+ ok = await client.send_request(+ e2a_from_agent_fields(+ request_id="t-list",+ channel_id="web",+ session_id="s1",+ req_method=ReqMethod.SESSION_LIST,+ params={"limit": 3},+ is_stream=True,+ )+ )+ assert ok.ok is True+ assert ok.payload == {"sessions": [{"id": "s1"}]}+ assert ok.metadata == {"k": 1}+ list_req = [r for r in seen if r.url.path.endswith("/sessions")][0]+ assert list_req.method == "GET"+ assert list_req.headers["x-request-id"] == "t-list"+ assert list_req.headers["accept"] == "application/json"++ bad = await client.send_request(+ e2a_from_agent_fields(+ request_id="t-init",+ channel_id="web",+ req_method=ReqMethod.INITIALIZE,+ params={},+ )+ )+ assert bad.ok is False+ assert bad.payload["code"] == "HTTP_ERROR"+ finally:+ await client.disconnect()+++async def test_send_request_stream_yields_chunks_and_skips_garbage():+ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.path.endswith("/health"):+ return _health_ok(request)+ good = _chunk_wire("chat-1", complete=False)+ done = _chunk_wire("chat-1", complete=True)+ body = (+ b": keepalive\n\n"+ b"event: e2a.chunk\n"+ b"data: {not json}\n\n"+ + f"data: {json.dumps(good, ensure_ascii=False)}\n\n".encode("utf-8")+ + f"data: {json.dumps(done, ensure_ascii=False)}\n\n".encode("utf-8")+ )+ return httpx.Response(+ 200, headers={"content-type": "text/event-stream"}, content=body+ )++ client = await _connected(handler)+ try:+ chunks: list[AgentResponseChunk] = []+ async for chunk in client.send_request_stream(+ e2a_from_agent_fields(+ request_id="chat-1",+ channel_id="web",+ session_id="s1",+ req_method=ReqMethod.CHAT_SEND,+ params={"query": "hi"},+ )+ ):+ chunks.append(chunk)+ assert len(chunks) == 2+ assert chunks[0].is_complete is False+ assert chunks[-1].is_complete is True+ finally:+ await client.disconnect()+++async def test_send_request_stream_http_error_is_complete_chunk():+ def handler(request: httpx.Request) -> httpx.Response:+ if request.url.path.endswith("/health"):+ return _health_ok(request)+ return httpx.Response(+ 404,+ json={+ "request_id": "h1",+ "ok": False,+ "error": {"code": "NOT_FOUND", "message": "no session"},+ },+ )++ client = await _connected(handler)+ try:+ chunks = [+ chunk+ async for chunk in client.send_request_stream(+ e2a_from_agent_fields(+ request_id="h1",+ channel_id="web",+ session_id="s1",+ req_method=ReqMethod.HISTORY_GET,+ params={},+ is_stream=True,+ )+ )+ ]+ assert len(chunks) == 1+ assert chunks[0].is_complete is True+ assert chunks[0].payload["code"] == "NOT_FOUND"+ assert chunks[0].payload["error"] == "no session"+ finally:+ await client.disconnect()+++async def test_push_loop_only_forwards_server_push_frames():+ received: list[dict] = []+ got = asyncio.Event()+ stream_release = asyncio.Event()++ async def on_push(frame: dict) -> None:+ received.append(frame)+ got.set()++ async def _handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:+ try:+ header = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), timeout=5)+ request_line = header.split(b"\r\n", 1)[0].decode("ascii", errors="replace")+ _method, path, *_rest = request_line.split(" ")+ if path.endswith("/health"):+ writer.write(_http_json({"ok": True, "data": {"status": "ready"}}))+ await writer.drain()+ return+ if path.endswith("/events/stream"):+ noise = {"request_id": "n", "metadata": {}}+ push = {+ "request_id": "p1",+ "metadata": {E2A_WIRE_SERVER_PUSH_KEY: True},+ "body": {"event_type": "proactive_recommendation"},+ }+ writer.write(+ b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n"+ b"Cache-Control: no-cache\r\nConnection: keep-alive\r\n\r\n"+ )+ writer.write(_sse_blob(noise))+ writer.write(_sse_blob(push))+ await writer.drain()+ await stream_release.wait()+ return+ writer.write(_http_json({"ok": False, "error": {"code": "NOT_FOUND"}}))+ await writer.drain()+ finally:+ writer.close()+ try:+ await writer.wait_closed()+ except Exception: # noqa: BLE001+ pass++ server = await asyncio.start_server(_handle, "127.0.0.1", 0)+ port = server.sockets[0].getsockname()[1]+ client = HttpSseAgentServerClient()+ client.set_server_push_handler(on_push)+ try:+ await client.connect(f"http://127.0.0.1:{port}")+ await asyncio.wait_for(got.wait(), timeout=5)+ assert received[0]["request_id"] == "p1"+ assert E2A_WIRE_SERVER_PUSH_KEY in received[0]["metadata"]+ finally:+ stream_release.set()+ await client.disconnect()+ server.close()+ await server.wait_closed()+++async def test_push_loop_backs_off_after_clean_stream_end(monkeypatch):+ """Clean SSE EOF must share the reconnect sleep, or GET /events/stream hot-loops."""+ import jiuwenswarm.gateway.routing.http_agent_client as hac++ monkeypatch.setattr(hac, "_PUSH_RETRY_SECONDS", 0.2)+ stream_hits = 0++ async def on_push(_frame: dict) -> None:+ return None++ async def _handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:+ nonlocal stream_hits+ try:+ header = await asyncio.wait_for(reader.readuntil(b"\r\n\r\n"), timeout=5)+ request_line = header.split(b"\r\n", 1)[0].decode("ascii", errors="replace")+ _method, path, *_rest = request_line.split(" ")+ if path.endswith("/health"):+ writer.write(_http_json({"ok": True, "data": {"status": "ready"}}))+ await writer.drain()+ return+ if path.endswith("/events/stream"):+ stream_hits += 1+ writer.write(+ b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n"+ b"Cache-Control: no-cache\r\nConnection: close\r\n\r\n"+ )+ await writer.drain()+ return+ writer.write(_http_json({"ok": False, "error": {"code": "NOT_FOUND"}}))+ await writer.drain()+ finally:+ writer.close()+ try:+ await writer.wait_closed()+ except Exception: # noqa: BLE001+ pass++ server = await asyncio.start_server(_handle, "127.0.0.1", 0)+ port = server.sockets[0].getsockname()[1]+ client = HttpSseAgentServerClient()+ client.set_server_push_handler(on_push)+ try:+ await client.connect(f"http://127.0.0.1:{port}")+ await asyncio.sleep(0.55)+ assert 2 <= stream_hits <= 4, stream_hits+ finally:+ await client.disconnect()+ server.close()+ await server.wait_closed()