π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π¨ chore: add GatewayStreamNotifier.sendToolExecute (#13765)
Arvin Xub36c5a2f1b7a
diff --git a/src/server/modules/AgentRuntime/GatewayStreamNotifier.ts b/src/server/modules/AgentRuntime/GatewayStreamNotifier.tsindex 4d1b59acfdd..a2130bbf5c7 100644--- a/src/server/modules/AgentRuntime/GatewayStreamNotifier.ts+++ b/src/server/modules/AgentRuntime/GatewayStreamNotifier.ts@@ -1,6 +1,8 @@import debug from 'debug';import urlJoin from 'url-join';+import type { ToolExecuteData } from '@/libs/agent-stream/types';+import {getDefaultReasonDetail,type StreamChunkData,@@ -106,6 +108,17 @@ export class GatewayStreamNotifier implements IStreamEventManager {return result;}+ /**+ * Request the client to execute a tool via Agent Gateway β WebSocket.+ * Unlike the other push methods this is NOT fire-and-forget: callers rely+ * on the promise outcome to decide whether to block-await a result or+ * fall back to the interrupt-resume path. Rejects on HTTP error / timeout.+ */+ async sendToolExecute(operationId: string, data: ToolExecuteData): Promise<void> {+ log('sendToolExecute operation=%s toolCallId=%s', operationId, data.toolCallId);+ await this.httpPostAwait('/api/operations/tool-execute', { data, operationId });+ }+// βββ Read / subscribe methods: delegate directly to inner βββasync subscribeStreamEvents(@@ -139,6 +152,35 @@ export class GatewayStreamNotifier implements IStreamEventManager {this.httpPost('/api/operations/push-event', { event, operationId }).catch(() => {});}+ /**+ * POST that surfaces errors back to the caller (no swallow). Used for+ * request-response style pushes like tool_execute where the caller needs+ * to know whether the gateway accepted the request.+ */+ private async httpPostAwait(path: string, body: Record<string, unknown>): Promise<void> {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), POST_TIMEOUT);++ try {+ const res = await fetch(urlJoin(this.gatewayUrl, path), {+ body: JSON.stringify(body),+ headers: {+ 'Authorization': `Bearer ${this.serviceToken}`,+ 'Content-Type': 'application/json',+ },+ method: 'POST',+ signal: controller.signal,+ });++ if (!res.ok) {+ const text = await res.text().catch(() => '');+ throw new Error(`Gateway ${path} returned ${res.status}: ${text}`);+ }+ } finally {+ clearTimeout(timer);+ }+ }+private async httpPost(path: string, body: Record<string, unknown>): Promise<void> {if (this.inflight >= MAX_INFLIGHT) {log('Gateway %s dropped: max inflight (%d) reached', path, MAX_INFLIGHT);diff --git a/src/server/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/src/server/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.tsindex e61cc032c89..6c0d9fe9c7a 100644--- a/src/server/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts+++ b/src/server/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts@@ -372,4 +372,57 @@ describe('GatewayStreamNotifier', () => {expect(url).not.toContain('//api');});});++ describe('sendToolExecute', () => {+ const toolExecuteData = {+ apiName: 'readFile',+ arguments: '{"path":"/tmp/x"}',+ executionTimeoutMs: 30_000,+ identifier: 'local-system',+ toolCallId: 'call-1',+ };++ beforeEach(() => {+ // Earlier tests in this file install hanging mockImplementations that+ // clearAllMocks doesn't reset β restore the default behavior here.+ mockFetch.mockReset();+ mockFetch.mockResolvedValue({ ok: true, text: () => Promise.resolve('') });+ });++ it('POSTs to /api/operations/tool-execute with the expected payload', async () => {+ await notifier.sendToolExecute('op-1', toolExecuteData);++ const calls = mockFetch.mock.calls.filter((c: any[]) =>+ String(c[0]).includes('/api/operations/tool-execute'),+ );+ expect(calls).toHaveLength(1);++ const [url, init] = calls[0];+ expect(url).toBe(`${gatewayUrl}/api/operations/tool-execute`);+ expect(init.method).toBe('POST');+ expect(init.headers.Authorization).toBe(`Bearer ${serviceToken}`);+ expect(JSON.parse(init.body)).toEqual({+ data: toolExecuteData,+ operationId: 'op-1',+ });+ });++ it('rejects when the gateway returns a non-ok status', async () => {+ mockFetch.mockResolvedValueOnce({+ ok: false,+ status: 502,+ text: () => Promise.resolve('bad gateway'),+ });++ await expect(notifier.sendToolExecute('op-1', toolExecuteData)).rejects.toThrow(/502/);+ });++ it('rejects when fetch throws (network / timeout)', async () => {+ mockFetch.mockRejectedValueOnce(new Error('network down'));++ await expect(notifier.sendToolExecute('op-1', toolExecuteData)).rejects.toThrow(+ 'network down',+ );+ });+ });});diff --git a/src/server/modules/AgentRuntime/types.ts b/src/server/modules/AgentRuntime/types.tsindex ecc0706fe53..cdfc12b714d 100644--- a/src/server/modules/AgentRuntime/types.ts+++ b/src/server/modules/AgentRuntime/types.ts@@ -1,5 +1,7 @@import { type AgentState } from '@lobechat/agent-runtime';+import type { ToolExecuteData } from '@/libs/agent-stream/types';+import { type AgentOperationMetadata, type StepResult } from './AgentStateManager';import { type StreamChunkData, type StreamEvent } from './StreamEventManager';@@ -145,6 +147,14 @@ export interface IStreamEventManager {event: Omit<StreamEvent, 'operationId' | 'timestamp'>,) => Promise<string>;+ /**+ * Optional: dispatch a tool execution request to the client via Agent Gateway.+ * Rejects if the gateway is unavailable β callers decide their fallback path.+ * Only present on implementations that speak to a live gateway (not on the+ * in-memory / Redis-only managers).+ */+ sendToolExecute?: (operationId: string, data: ToolExecuteData) => Promise<void>;+/*** Subscribe to stream events (for SSE endpoint)*/