Skip to content

🤯 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.

🐛 fix(agent-runtime): Redis 事件流只保留最新一份 tools_calling 快照 (#22603)

Mocha922570284c6e
diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
index 1b9d2f42a84..08e21b51c5e 100644
--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
@@ -235,6 +235,11 @@ export class GatewayStreamNotifier implements IStreamEventManager {
return result;
}
+ /** Storage-only: clients already received the removed entries live. */
+ async deleteStreamEvents(operationId: string, eventIds: string[]): Promise<void> {
+ return this.inner.deleteStreamEvents(operationId, eventIds);
+ }
+
async publishStreamChunk(
operationId: string,
stepIndex: number,
diff --git a/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts b/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts
index 8ca3dfbc638..46c9156aed6 100644
--- a/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts
+++ b/apps/server/src/modules/AgentRuntime/InMemoryStreamEventManager.ts
@@ -1,6 +1,7 @@
import debug from 'debug';
import {
+ compareStreamIds,
type StreamChunkData,
type StreamEvent,
stripFinalStateInEventData,
@@ -97,6 +98,16 @@ export class InMemoryStreamEventManager implements IStreamEventManager {
return eventId;
}
+ async deleteStreamEvents(operationId: string, eventIds: string[]): Promise<void> {
+ const stream = this.streams.get(operationId);
+ if (!stream || eventIds.length === 0) return;
+ const ids = new Set(eventIds);
+ this.streams.set(
+ operationId,
+ stream.filter((event) => !event.id || !ids.has(event.id)),
+ );
+ }
+
async publishStreamChunk(
operationId: string,
stepIndex: number,
@@ -156,19 +167,35 @@ export class InMemoryStreamEventManager implements IStreamEventManager {
async getStreamHistoryPage(operationId: string, cursor = '0', limit = 200) {
this.evictExpiredStreams();
const stream = this.streams.get(operationId);
- const index = cursor === '0' ? -1 : (stream?.findIndex((event) => event.id === cursor) ?? -1);
- if (!stream || (cursor !== '0' && index < 0) || stream[0]?.type !== 'agent_runtime_init') {
- return { available: false, events: [], hasMore: false, nextCursor: cursor };
- }
- const events = stream.slice(index + 1, index + 1 + limit);
+ const unavailable = { available: false, events: [], hasMore: false, nextCursor: cursor };
+ if (!stream || stream[0]?.type !== 'agent_runtime_init') return unavailable;
+ if (cursor === '0') return this.historyPage(stream, 0, limit, cursor);
+
+ const exact = stream.findIndex((event) => event.id === cursor);
+ if (exact >= 0) return this.historyPage(stream, exact + 1, limit, cursor);
+
+ // Mirror the Redis manager: a cursor removed by `deleteStreamEvents` sits
+ // after the init with a newer event following it; anything else is lost.
+ if (compareStreamIds(stream[0].id!, cursor) >= 0) return unavailable;
+ const next = this.indexAfter(stream, cursor);
+ return next < 0 ? unavailable : this.historyPage(stream, next, limit, cursor);
+ }
+
+ private historyPage(stream: StreamEvent[], start: number, limit: number, cursor: string) {
+ const events = stream.slice(start, start + limit);
return {
available: true,
events,
- hasMore: stream.length > index + 1 + limit,
+ hasMore: stream.length > start + limit,
nextCursor: events.at(-1)?.id ?? cursor,
};
}
+ /** Index of the first event newer than `cursor`, or -1. */
+ private indexAfter(stream: StreamEvent[], cursor: string): number {
+ return stream.findIndex((event) => !!event.id && compareStreamIds(event.id, cursor) > 0);
+ }
+
/**
* Single bounded read — the long-poll primitive (see `IStreamEventManager`).
* The in-memory manager is non-blocking: it returns immediately with whatever
@@ -188,8 +215,10 @@ export class InMemoryStreamEventManager implements IStreamEventManager {
return { events: [], lastEventId: stream.at(-1)?.id ?? '0' };
}
- const idx = stream.findIndex((e) => e.id === lastEventId);
- const events = idx >= 0 ? stream.slice(idx + 1) : stream.slice();
+ // Like XREAD: everything newer than the cursor, even if the cursor's own
+ // event was removed by `deleteStreamEvents`.
+ const idx = this.indexAfter(stream, lastEventId);
+ const events = idx >= 0 ? stream.slice(idx) : [];
return { events, lastEventId: events.at(-1)?.id ?? lastEventId };
}
diff --git a/apps/server/src/modules/AgentRuntime/StreamEventManager.ts b/apps/server/src/modules/AgentRuntime/StreamEventManager.ts
index 2792f88062b..c86abc98a94 100644
--- a/apps/server/src/modules/AgentRuntime/StreamEventManager.ts
+++ b/apps/server/src/modules/AgentRuntime/StreamEventManager.ts
@@ -171,6 +171,23 @@ export interface StreamChunkData {
toolsCalling?: ChatToolPayload[];
}
+const STREAM_ID = /^(\d+)(?:-(\d+))?$/;
+
+/**
+ * Order two Redis stream ids (`<ms>-<seq>`): negative when `a` is older,
+ * positive when newer, `NaN` when either is not a stream id (client-supplied
+ * cursors are untrusted), so every `< 0` / `> 0` check fails closed.
+ */
+export const compareStreamIds = (a: string, b: string): number => {
+ const ma = STREAM_ID.exec(a);
+ const mb = STREAM_ID.exec(b);
+ if (!ma || !mb) return Number.NaN;
+ const ms = BigInt(ma[1]) - BigInt(mb[1]);
+ if (ms !== 0n) return ms < 0n ? -1 : 1;
+ const seq = BigInt(ma[2] ?? '0') - BigInt(mb[2] ?? '0');
+ return seq === 0n ? 0 : seq < 0n ? -1 : 1;
+};
+
/** Decode one Redis stream entry (`[id, [field, value, ...]]`) into a `StreamEvent`. */
const parseStreamEntry = (id: string, fields: string[]): StreamEvent => {
const eventData: any = {};
@@ -291,6 +308,11 @@ export class StreamEventManager {
}
}
+ async deleteStreamEvents(operationId: string, eventIds: string[]): Promise<void> {
+ if (eventIds.length === 0) return;
+ await this.redis.xdel(`${this.STREAM_PREFIX}:${operationId}`, ...eventIds);
+ }
+
/**
* Publish stream content chunk
*/
@@ -496,9 +518,22 @@ export class StreamEventManager {
): Promise<StreamHistoryPage> {
const key = `${this.STREAM_PREFIX}:${operationId}`;
const unavailable = { available: false, events: [], hasMore: false, nextCursor: cursor };
+ let cursorRemoved = false;
if (cursor !== '0') {
const previous = await this.redis.xrange(key, cursor, cursor, 'COUNT', 1);
- if (previous.length === 0) return unavailable;
+ if (previous.length === 0) {
+ // A missing cursor is either lost history (expired stream, legacy
+ // trimmed prefix) or a superseded snapshot removed by
+ // `deleteStreamEvents`. Removal only happens mid-stream: the stream
+ // still starts at its init and a newer entry follows the cursor.
+ const [first] = await this.redis.xrange(key, '-', '+', 'COUNT', 1);
+ const anchored =
+ !!first &&
+ parseStreamEntry(first[0], first[1]).type === 'agent_runtime_init' &&
+ compareStreamIds(first[0], cursor) < 0;
+ if (!anchored) return unavailable;
+ cursorRemoved = true;
+ }
}
const rows = await this.redis.xrange(
key,
@@ -507,6 +542,7 @@ export class StreamEventManager {
'COUNT',
limit + 1,
);
+ if (cursorRemoved && rows.length === 0) return unavailable;
const events = rows.slice(0, limit).map(([id, fields]) => parseStreamEntry(id, fields));
// Legacy streams may already have been trimmed before this deployment.
if (cursor === '0' && events[0]?.type !== 'agent_runtime_init') return unavailable;
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.deleteStreamEvents.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.deleteStreamEvents.test.ts
new file mode 100644
index 00000000000..1c5e2fbf48e
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.deleteStreamEvents.test.ts
@@ -0,0 +1,26 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { GatewayStreamNotifier } from '../GatewayStreamNotifier';
+import { createMockInner } from '../testUtils';
+
+const mockFetch = vi.fn().mockResolvedValue({ ok: true, text: () => Promise.resolve('') });
+vi.stubGlobal('fetch', mockFetch);
+
+describe('GatewayStreamNotifier.deleteStreamEvents', () => {
+ let inner: ReturnType<typeof createMockInner>;
+ let notifier: GatewayStreamNotifier;
+
+ beforeEach(() => {
+ mockFetch.mockClear();
+ inner = createMockInner();
+ notifier = new GatewayStreamNotifier(inner, 'https://gateway.test.com', 'test-token');
+ });
+
+ // Removal only trims stored history; clients already received the entries live.
+ it('delegates to inner without pushing to the gateway', async () => {
+ await notifier.deleteStreamEvents('op-1', ['1-0']);
+
+ expect(inner.calls.deleteStreamEvents).toEqual([['op-1', ['1-0']]]);
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/InMemoryStreamEventManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/InMemoryStreamEventManager.test.ts
index 2622bfe176b..1e7cf8541ab 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/InMemoryStreamEventManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/InMemoryStreamEventManager.test.ts
@@ -45,6 +45,40 @@ describe('InMemoryStreamEventManager', () => {
});
});
+ describe('deleteStreamEvents', () => {
+ it('removes only the given events', async () => {
+ const first = await manager.publishStreamChunk('op-1', 0, {
+ chunkType: 'text',
+ content: 'a',
+ });
+ const second = await manager.publishStreamChunk('op-1', 0, {
+ chunkType: 'text',
+ content: 'b',
+ });
+
+ await manager.deleteStreamEvents('op-1', [first]);
+
+ expect(manager.getAllEvents('op-1').map((event) => event.id)).toEqual([second]);
+ });
+
+ it('keeps a removed event usable as a read cursor', async () => {
+ await manager.publishAgentRuntimeInit('op-1', {});
+ const removed = await manager.publishStreamChunk('op-1', 0, {
+ chunkType: 'text',
+ content: 'a',
+ });
+ const next = await manager.publishStreamChunk('op-1', 0, { chunkType: 'text', content: 'b' });
+ await manager.deleteStreamEvents('op-1', [removed]);
+
+ const page = await manager.getStreamHistoryPage('op-1', removed);
+ expect(page.available).toBe(true);
+ expect(page.events.map((event) => event.id)).toEqual([next]);
+
+ const read = await manager.readEventsOnce('op-1', removed);
+ expect(read.events.map((event) => event.id)).toEqual([next]);
+ });
+ });
+
describe('readEventsOnce', () => {
it("returns nothing but a tail cursor for '$' (from-now semantics)", async () => {
await manager.publishStreamEvent('op-1', {
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts
index 6e26240b9c6..8ae22bad523 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/StreamEventManager.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
import {
+ compareStreamIds,
getDefaultReasonDetail,
StreamEventManager,
stripFinalStateInEventData,
@@ -25,6 +26,7 @@ const mockRedis = {
keys: vi.fn(),
quit: vi.fn(),
xadd: vi.fn(),
+ xdel: vi.fn(),
xread: vi.fn(),
xrevrange: vi.fn(),
xrange: vi.fn(),
@@ -42,6 +44,34 @@ describe('StreamEventManager', () => {
streamManager = new StreamEventManager();
});
+ describe('compareStreamIds', () => {
+ it('orders by milliseconds, then sequence', () => {
+ expect(compareStreamIds('9-5', '10-0')).toBeLessThan(0);
+ expect(compareStreamIds('10-2', '10-10')).toBeLessThan(0);
+ expect(compareStreamIds('10-1', '10-1')).toBe(0);
+ expect(compareStreamIds('11', '10-99')).toBeGreaterThan(0);
+ });
+
+ it('fails closed for a cursor that is not a stream id', () => {
+ expect(compareStreamIds('missing', '1-0')).toBeNaN();
+ expect(compareStreamIds('1-0', '1-x')).toBeNaN();
+ });
+ });
+
+ describe('deleteStreamEvents', () => {
+ it('removes the given entries from the operation stream', async () => {
+ await streamManager.deleteStreamEvents('op-1', ['1-0', '2-0']);
+
+ expect(mockRedis.xdel).toHaveBeenCalledWith('agent_runtime_stream:op-1', '1-0', '2-0');
+ });
+
+ it('skips the round trip when there is nothing to delete', async () => {
+ await streamManager.deleteStreamEvents('op-1', []);
+
+ expect(mockRedis.xdel).not.toHaveBeenCalled();
+ });
+ });
+
describe('publishAgentRuntimeInit', () => {
it('should publish agent runtime init event with correct data', async () => {
const operationId = 'test-operation-id';
@@ -111,10 +141,43 @@ describe('StreamEventManager', () => {
expect((await streamManager.getStreamHistoryPage('op-1')).available).toBe(false);
mockRedis.xrange.mockResolvedValueOnce([]);
expect((await streamManager.getStreamHistoryPage('op-1')).available).toBe(false);
- mockRedis.xrange.mockResolvedValueOnce([]);
+ // Missing cursor on an expired stream: no entry, and no init to anchor it.
+ mockRedis.xrange.mockResolvedValueOnce([]).mockResolvedValueOnce([]);
expect((await streamManager.getStreamHistoryPage('op-1', '1-0')).available).toBe(false);
});
+ // A superseded `tools_calling` snapshot is removed after a newer entry lands,
+ // so a follower whose cursor was that snapshot must keep paging, not fail.
+ it('continues after a cursor whose snapshot was removed mid-stream', async () => {
+ mockRedis.xrange
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([row('1-0', 'agent_runtime_init')])
+ .mockResolvedValueOnce([row('4-0', 'stream_chunk')]);
+
+ const page = await streamManager.getStreamHistoryPage('op-1', '3-0', 2);
+
+ expect(page).toMatchObject({ available: true, hasMore: false, nextCursor: '4-0' });
+ expect(page.events.map((event) => event.id)).toEqual(['4-0']);
+ });
+
+ it('fails closed for a missing cursor with nothing after it or no init before it', async () => {
+ mockRedis.xrange
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([row('1-0', 'agent_runtime_init')])
+ .mockResolvedValueOnce([]);
+ expect((await streamManager.getStreamHistoryPage('op-1', '3-0')).available).toBe(false);
+
+ mockRedis.xrange
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([row('5-0', 'agent_runtime_init')]);
+ expect((await streamManager.getStreamHistoryPage('op-1', '3-0')).available).toBe(false);
+
+ mockRedis.xrange
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([row('1-0', 'stream_chunk')]);
+ expect((await streamManager.getStreamHistoryPage('op-1', '3-0')).available).toBe(false);
+ });
+
it('propagates Redis errors instead of reporting an empty successful history', async () => {
mockRedis.xrange.mockRejectedValueOnce(new Error('Redis unavailable'));
await expect(streamManager.getStreamHistoryPage('op-1')).rejects.toThrow('Redis unavailable');
diff --git a/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmStreamSink.test.ts b/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmStreamSink.test.ts
index ad9a3895c45..44f3b49a3be 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmStreamSink.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmStreamSink.test.ts
@@ -10,16 +10,18 @@ const toolCall = (args: string): ChatToolPayload[] =>
[{ apiName: 'write', arguments: args, id: 'call_1', identifier: 'fs', type: 'default' }] as any;
const createSink = () => {
- const publishStreamChunk = vi.fn().mockResolvedValue('1-0');
+ let seq = 0;
+ const publishStreamChunk = vi.fn().mockImplementation(async () => `${++seq}-0`);
+ const deleteStreamEvents = vi.fn().mockResolvedValue(undefined);
const ctx = {
operationId: 'op-1',
stepIndex: 0,
- streamManager: { publishStreamChunk },
+ streamManager: { deleteStreamEvents, publishStreamChunk },
} as unknown as RuntimeExecutorContext;
const sink = new ServerCallLlmStreamSink({ ctx, events: [], operationLogId: 'op-1:0' });
- return { publishStreamChunk, sink };
+ return { deleteStreamEvents, publishStreamChunk, sink };
};
/** The payload the Nth `publishStreamChunk` call carried. */
@@ -120,3 +122,66 @@ describe('ServerCallLlmStreamSink tools_calling throttle', () => {
expect(publishedArgs(publishStreamChunk, 1)).toBe('complete');
});
});
+
+// The throttle bounds how OFTEN a snapshot is stored, not how many: a slow model
+// writing a 30 KB tool argument for minutes still stored one ever-growing copy
+// per window, so a single call filled tens of MB of Redis (quadratic in the
+// argument length) until the stream's TTL expired.
+describe('ServerCallLlmStreamSink tools_calling stream retention', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('removes the superseded snapshot once a newer one is stored', async () => {
+ const { deleteStreamEvents, publishStreamChunk, sink } = createSink();
+
+ sink.queueToolsCalling(toolCall('a'));
+ await vi.advanceTimersByTimeAsync(THROTTLE_INTERVAL);
+ expect(deleteStreamEvents).not.toHaveBeenCalled();
+
+ sink.queueToolsCalling(toolCall('ab'));
+ await vi.advanceTimersByTimeAsync(THROTTLE_INTERVAL);
+ sink.queueToolsCalling(toolCall('abc'));
+ await sink.flushToolsCallingBuffer();
+
+ expect(publishStreamChunk).toHaveBeenCalledTimes(3);
+ expect(deleteStreamEvents.mock.calls).toEqual([
+ ['op-1', ['1-0']],
+ ['op-1', ['2-0']],
+ ]);
+ });
+
+ it('keeps the stored snapshot when the newer publish fails', async () => {
+ const { deleteStreamEvents, publishStreamChunk, sink } = createSink();
+
+ sink.queueToolsCalling(toolCall('a'));
+ await vi.advanceTimersByTimeAsync(THROTTLE_INTERVAL);
+
+ publishStreamChunk.mockRejectedValueOnce(new Error('redis down'));
+ sink.queueToolsCalling(toolCall('ab'));
+ await vi.advanceTimersByTimeAsync(THROTTLE_INTERVAL);
+
+ // Nothing newer landed, so '1-0' is still the only replayable snapshot.
+ expect(deleteStreamEvents).not.toHaveBeenCalled();
+
+ await sink.flushToolsCallingBuffer();
+
+ expect(deleteStreamEvents.mock.calls).toEqual([['op-1', ['1-0']]]);
+ });
+
+ it('does not fail the stream when removing a superseded snapshot fails', async () => {
+ const { deleteStreamEvents, publishStreamChunk, sink } = createSink();
+ deleteStreamEvents.mockRejectedValueOnce(new Error('xdel failed'));
+
+ sink.queueToolsCalling(toolCall('a'));
+ await sink.flushToolsCallingBuffer();
+ sink.queueToolsCalling(toolCall('ab'));
+
+ await expect(sink.flushToolsCallingBuffer()).resolves.toBeUndefined();
+ expect(publishStreamChunk).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmStreamSink.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmStreamSink.ts
index 2496f1bdb96..f2d0f84c5b4 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmStreamSink.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmStreamSink.ts
@@ -68,6 +68,14 @@ export class ServerCallLlmStreamSink {
private readonly stepIndex: number;
private textBuffer = '';
private textBufferTimer: NodeJS.Timeout | null = null;
+ /**
+ * Stream entry id of the last stored `tools_calling` snapshot. Each snapshot
+ * is the WHOLE call list, so once a newer one is stored the older entry is
+ * dead weight: replay applies snapshots as full replaces and only the newest
+ * matters. Without removing it the stream keeps one ever-growing copy per
+ * throttle window (quadratic in the argument length) until the stream's TTL.
+ */
+ private storedToolsCallingEventId: string | undefined;
/** In-flight `tools_calling` publish; settles rather than rejects. */
private toolsCallingFlush: Promise<void> | null = null;
/** Latest un-published `tools_calling` snapshot; `undefined` once flushed. */
@@ -197,7 +205,8 @@ export class ServerCallLlmStreamSink {
this.toolsCallingFlush = joinable;
try {
- await publish;
+ const eventId = await publish;
+ await this.removeSupersededToolsCalling(eventId);
timing(
'[%s] flushToolsCallingBuffer published at %d, took %dms, calls: %d',
this.operationLogId,
@@ -217,6 +226,20 @@ export class ServerCallLlmStreamSink {
}
}
+ private async removeSupersededToolsCalling(eventId: string | undefined) {
+ const superseded = this.storedToolsCallingEventId;
+ this.storedToolsCallingEventId = eventId;
+ if (!superseded || !eventId) return;
+
+ try {
+ await this.streamManager.deleteStreamEvents(this.operationId, [superseded]);
+ } catch (error) {
+ // Storage hygiene only: the newer snapshot is already stored and pushed,
+ // and the stream's TTL still bounds the leftover entry.
+ log(`[${this.operationLogId}] failed to remove superseded tools_calling:`, error);
+ }
+ }
+
clearBuffers() {
if (this.textBufferTimer) {
clearTimeout(this.textBufferTimer);
diff --git a/apps/server/src/modules/AgentRuntime/testUtils.ts b/apps/server/src/modules/AgentRuntime/testUtils.ts
index 122e146c5e5..6a33b6f7158 100644
--- a/apps/server/src/modules/AgentRuntime/testUtils.ts
+++ b/apps/server/src/modules/AgentRuntime/testUtils.ts
@@ -15,6 +15,7 @@ export function createMockInner(): IStreamEventManager & { calls: Record<string,
return {
calls,
cleanupOperation: track('cleanupOperation') as any,
+ deleteStreamEvents: track('deleteStreamEvents') as any,
disconnect: track('disconnect') as any,
getActiveOperationsCount: track('getActiveOperationsCount') as any,
getStreamHistory: track('getStreamHistory') as any,
diff --git a/apps/server/src/modules/AgentRuntime/types.ts b/apps/server/src/modules/AgentRuntime/types.ts
index 60dc2bf1018..508c24cbc33 100644
--- a/apps/server/src/modules/AgentRuntime/types.ts
+++ b/apps/server/src/modules/AgentRuntime/types.ts
@@ -203,6 +203,14 @@ export interface IStreamEventManager {
/** Optional: end a one-shot relay channel's gateway session. */
closeLlmRelayChannel?: (channel: string) => Promise<void>;
+ /**
+ * Remove entries from an operation's stream. Used to drop a snapshot chunk
+ * once a newer one supersedes it, so a stream retains one copy instead of
+ * every intermediate version. Live consumers are unaffected: they already
+ * received the removed entries.
+ */
+ deleteStreamEvents: (operationId: string, eventIds: string[]) => Promise<void>;
+
/**
* Close connections
*/