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.

✨ feat(agent-signal): added AgentSignalRuntime (#14170)

Nekod5315fe745b5
diff --git a/src/server/routers/lambda/agentSignal.test.ts b/src/server/routers/lambda/agentSignal.test.ts
new file mode 100644
index 00000000000..a5059a8d5f7
--- /dev/null
+++ b/src/server/routers/lambda/agentSignal.test.ts
@@ -0,0 +1,63 @@
+// @vitest-environment node
+import { TRPCError } from '@trpc/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createCallerFactory } from '@/libs/trpc/lambda';
+import { type AuthContext } from '@/libs/trpc/lambda/context';
+import { createContextInner } from '@/libs/trpc/lambda/context';
+
+import { agentSignalRouter } from './agentSignal';
+
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn().mockResolvedValue({}),
+}));
+
+vi.mock('@/server/services/agentSignal', () => ({
+ enqueueAgentSignalSourceEvent: vi
+ .fn()
+ .mockResolvedValue({ accepted: true, scopeKey: 'topic:topic-1', workflowRunId: 'wfr_1' }),
+}));
+
+const createCaller = createCallerFactory(agentSignalRouter);
+
+describe('agentSignalRouter', () => {
+ let ctx: AuthContext;
+ let router: ReturnType<typeof createCaller>;
+
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ ctx = await createContextInner({ userId: 'user-1' });
+ router = createCaller(ctx);
+ });
+
+ it('accepts client runtime events', async () => {
+ await expect(
+ router.emitSourceEvent({
+ payload: {
+ agentId: 'agent-1',
+ operationId: 'op-1',
+ parentMessageId: 'msg-1',
+ parentMessageType: 'user',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ },
+ sourceId: 'op-1:client:start',
+ sourceType: 'client.runtime.start',
+ }),
+ ).resolves.toEqual({ accepted: true, scopeKey: 'topic:topic-1', workflowRunId: 'wfr_1' });
+ });
+
+ it('rejects forged non-client source events', async () => {
+ await expect(
+ router.emitSourceEvent({
+ payload: {
+ message: 'remember this',
+ messageId: 'msg-1',
+ topicId: 'topic-1',
+ },
+ sourceId: 'msg-1',
+ sourceType: 'agent.user.message' as never,
+ }),
+ ).rejects.toBeInstanceOf(TRPCError);
+ });
+});
diff --git a/src/server/routers/lambda/agentSignal.ts b/src/server/routers/lambda/agentSignal.ts
new file mode 100644
index 00000000000..a034d8b6062
--- /dev/null
+++ b/src/server/routers/lambda/agentSignal.ts
@@ -0,0 +1,54 @@
+import debug from 'debug';
+import { z } from 'zod';
+
+import { authedProcedure, router } from '@/libs/trpc/lambda';
+import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';
+import {
+ AGENT_SIGNAL_CLIENT_SOURCE_TYPES,
+ type AgentSignalSourcePayloadMap,
+} from '@/server/services/agentSignal/sourceTypes';
+
+const log = debug('lobe-server:agent-signal:router');
+
+const agentSignalProcedure = authedProcedure;
+const clientSourceTypes = AGENT_SIGNAL_CLIENT_SOURCE_TYPES;
+
+type ClientSourceType = (typeof clientSourceTypes)[number];
+type ClientSourceEventInput = {
+ [TSourceType in ClientSourceType]: {
+ payload: AgentSignalSourcePayloadMap[TSourceType];
+ scopeKey?: string;
+ sourceId: string;
+ sourceType: TSourceType;
+ timestamp?: number;
+ };
+}[ClientSourceType];
+
+export const agentSignalRouter = router({
+ emitSourceEvent: agentSignalProcedure
+ .input(
+ z.object({
+ payload: z.record(z.string(), z.unknown()),
+ scopeKey: z.string().optional(),
+ sourceId: z.string(),
+ sourceType: z.enum(clientSourceTypes),
+ timestamp: z.number().optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ log('Received emitSourceEvent payload=%O', {
+ agentId: typeof input.payload.agentId === 'string' ? input.payload.agentId : undefined,
+ payload: input.payload,
+ scopeKey: input.scopeKey,
+ sourceId: input.sourceId,
+ sourceType: input.sourceType,
+ timestamp: input.timestamp,
+ userId: ctx.userId,
+ });
+
+ return enqueueAgentSignalSourceEvent(input as unknown as ClientSourceEventInput, {
+ agentId: typeof input.payload.agentId === 'string' ? input.payload.agentId : undefined,
+ userId: ctx.userId,
+ });
+ }),
+});
diff --git a/src/server/routers/lambda/index.ts b/src/server/routers/lambda/index.ts
index d1da6de1713..55b4f9e581c 100644
--- a/src/server/routers/lambda/index.ts
+++ b/src/server/routers/lambda/index.ts
@@ -16,6 +16,7 @@ import { agentEvalRouter } from './agentEval';
import { agentEvalExternalRouter } from './agentEvalExternal';
import { agentGroupRouter } from './agentGroup';
import { agentNotifyRouter } from './agentNotify';
+import { agentSignalRouter } from './agentSignal';
import { agentSkillsRouter } from './agentSkills';
import { aiAgentRouter } from './aiAgent';
import { aiChatRouter } from './aiChat';
@@ -72,6 +73,7 @@ export const lambdaRouter = router({
agentEval: agentEvalRouter,
agentEvalExternal: agentEvalExternalRouter,
agentSkills: agentSkillsRouter,
+ agentSignal: agentSignalRouter,
task: taskRouter,
brief: briefRouter,
aiAgent: aiAgentRouter,
diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.ts
index 7a910cb15b2..2c4d354a641 100644
--- a/src/server/services/agentRuntime/AgentRuntimeService.ts
+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts
@@ -19,6 +19,8 @@ import { AgentRuntimeCoordinator, createStreamEventManager } from '@/server/modu
import { type RuntimeExecutorContext } from '@/server/modules/AgentRuntime/RuntimeExecutors';
import { createRuntimeExecutors } from '@/server/modules/AgentRuntime/RuntimeExecutors';
import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';
+import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';
+import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observability/traceEvents';
import { mcpService } from '@/server/services/mcp';
import { QueueService } from '@/server/services/queue';
import { LocalQueueServiceImpl } from '@/server/services/queue/impls';
@@ -84,6 +86,19 @@ function formatErrorForState(error: unknown): ChatMessageError {
};
}
+const toAgentSignalSnapshotEvents = (
+ emission: Awaited<ReturnType<typeof emitAgentSignalSourceEvent>> | undefined,
+) => {
+ if (!emission || emission.deduped) return [];
+
+ return toAgentSignalTraceEvents({
+ actions: emission.orchestration.actions,
+ results: emission.orchestration.results,
+ signals: emission.orchestration.emittedSignals,
+ source: emission.source,
+ });
+};
+
export interface AgentRuntimeServiceOptions {
/**
* Custom agent factory. When provided, this function is called instead of
@@ -489,6 +504,8 @@ export class AgentRuntimeService {
const reason = this.determineCompletionReason(agentState);
+ await this.emitCompletionSignalEvents(operationId, agentState, reason);
+
// Dispatch completion hooks so consumers (e.g., bot local-mode promise) can finalize
await this.dispatchCompletionHooks(operationId, agentState, reason);
@@ -500,9 +517,32 @@ export class AgentRuntimeService {
};
}
+ let beforeStepSignalEvents: Array<{ [key: string]: unknown; type: string }> = [];
+
// Dispatch beforeStep hooks
try {
const beforeStepMetadata = agentState?.metadata || {};
+ const beforeStepSignalEmission = await emitAgentSignalSourceEvent(
+ {
+ payload: {
+ agentId: beforeStepMetadata?.agentId,
+ operationId,
+ serializedContext: undefined,
+ stepIndex,
+ topicId: beforeStepMetadata?.topicId,
+ turnCount: agentState?.stepCount || 0,
+ },
+ sourceId: `${operationId}:before:${stepIndex}`,
+ sourceType: 'runtime.before_step',
+ },
+ {
+ agentId: beforeStepMetadata?.agentId,
+ db: this.serverDB,
+ userId: beforeStepMetadata?.userId || this.userId,
+ },
+ { ignoreError: true },
+ );
+ beforeStepSignalEvents = toAgentSignalSnapshotEvents(beforeStepSignalEmission);
await hookDispatcher.dispatch(
operationId,
'beforeStep',
@@ -762,6 +802,8 @@ export class AgentRuntimeService {
totalTokens: totalTokensNum,
};
+ let afterStepSignalEvents: Array<{ [key: string]: unknown; type: string }> = [];
+
// Dispatch afterStep hooks (enriched with step presentation + tracking data)
try {
const metadata = stepResult.newState?.metadata || {};
@@ -770,6 +812,30 @@ export class AgentRuntimeService {
? Date.now() - new Date(stepResult.newState.createdAt).getTime()
: undefined;
const stepLabel = metadata?._stepLabel;
+
+ afterStepSignalEvents = toAgentSignalSnapshotEvents(
+ await emitAgentSignalSourceEvent(
+ {
+ payload: {
+ agentId: metadata?.agentId,
+ operationId,
+ serializedContext: undefined,
+ stepIndex,
+ topicId: metadata?.topicId,
+ turnCount: stepResult.newState?.stepCount || 0,
+ },
+ sourceId: `${operationId}:after:${stepIndex}`,
+ sourceType: 'runtime.after_step',
+ },
+ {
+ agentId: metadata?.agentId,
+ db: this.serverDB,
+ userId: metadata?.userId || this.userId,
+ },
+ { ignoreError: true },
+ ),
+ );
+
await hookDispatcher.dispatch(
operationId,
'afterStep',
@@ -837,27 +903,31 @@ export class AgentRuntimeService {
const messagesDelta = afterMessages.slice(prevMessages.length);
// Strip heavy/redundant data from events before persisting to snapshot
- const snapshotEvents = (stepResult.events as any[])
- ?.filter((e) => e.type !== 'llm_stream')
- .map((e) => {
- if (e.type === 'done' && e.finalState) {
- // Remove reconstructible fields from finalState:
- // - messages: from messagesBaseline + messagesDelta chain
- // - operationToolSet: from toolsetBaseline (step 0)
- // - toolManifestMap/tools/toolSourceMap: backward-compat copies of operationToolSet
- const {
- messages: _msgs,
- operationToolSet: _ots,
- toolManifestMap: _tmm,
- toolSourceMap: _tsm,
- tools: _tools,
- // activatedStepTools is kept since it's the cumulative record
- ...restState
- } = e.finalState;
- return { ...e, finalState: restState };
- }
- return e;
- });
+ const snapshotEvents = [
+ ...beforeStepSignalEvents,
+ ...((stepResult.events as any[])
+ ?.filter((e) => e.type !== 'llm_stream')
+ .map((e) => {
+ if (e.type === 'done' && e.finalState) {
+ // Remove reconstructible fields from finalState:
+ // - messages: from messagesBaseline + messagesDelta chain
+ // - operationToolSet: from toolsetBaseline (step 0)
+ // - toolManifestMap/tools/toolSourceMap: backward-compat copies of operationToolSet
+ const {
+ messages: _msgs,
+ operationToolSet: _ots,
+ toolManifestMap: _tmm,
+ toolSourceMap: _tsm,
+ tools: _tools,
+ // activatedStepTools is kept since it's the cumulative record
+ ...restState
+ } = e.finalState;
+ return { ...e, finalState: restState };
+ }
+ return e;
+ }) ?? []),
+ ...afterStepSignalEvents,
+ ];
// Strip toolResults from payload (already in step.toolsResult)
let snapshotPayload: unknown = currentContext?.payload;
@@ -969,7 +1039,13 @@ export class AgentRuntimeService {
if (!shouldContinue) {
const reason = this.determineCompletionReason(stepResult.newState);
- // Dispatch onComplete hooks
+ const completionSignalEvents = await this.emitCompletionSignalEvents(
+ operationId,
+ stepResult.newState,
+ reason,
+ );
+
+ // Dispatch completion hooks
await this.dispatchCompletionHooks(operationId, stepResult.newState, reason);
// Finalize tracing snapshot via injected snapshot store
@@ -978,6 +1054,14 @@ export class AgentRuntimeService {
const partial = await this.snapshotStore.loadPartial(operationId);
if (partial) {
+ if (completionSignalEvents.length > 0 && partial.steps?.length) {
+ const lastStep = partial.steps.at(-1);
+
+ if (lastStep) {
+ lastStep.events = [...(lastStep.events ?? []), ...completionSignalEvents];
+ }
+ }
+
const metadata = agentState?.metadata as any;
const snapshot = {
agentId: metadata?.agentId,
@@ -1087,6 +1171,8 @@ export class AgentRuntimeService {
log('[%s] Failed to save error state (infra may be down): %O', operationId, saveError);
}
+ await this.emitCompletionSignalEvents(operationId, finalStateWithError, 'error');
+
// Dispatch onComplete + onError hooks
await this.dispatchCompletionHooks(operationId, finalStateWithError, 'error');
@@ -1733,37 +1819,25 @@ export class AgentRuntimeService {
return { newState: state, nextContext: undefined };
}
- /**
- * Dispatch onComplete (and onError) hooks via HookDispatcher.
- * Fire-and-forget: errors are logged but never thrown.
- */
- private async dispatchCompletionHooks(
- operationId: string,
- state: any,
- reason: string,
- ): Promise<void> {
- try {
- const metadata = state?.metadata || {};
-
- // Extract last assistant content from state messages
- const lastAssistantContent = state?.messages
- ?.slice()
- .reverse()
- .find(
- (m: { content?: string; role: string }) => m.role === 'assistant' && m.content,
- )?.content;
+ private buildCompletionLifecycleEvent(operationId: string, state: any, reason: string) {
+ const metadata = state?.metadata || {};
+ const lastAssistantContent = state?.messages
+ ?.slice()
+ .reverse()
+ .find(
+ (m: { content?: string; role: string }) => m.role === 'assistant' && m.content,
+ )?.content;
+ const duration = state?.createdAt
+ ? Date.now() - new Date(state.createdAt).getTime()
+ : undefined;
- const duration = state?.createdAt
- ? Date.now() - new Date(state.createdAt).getTime()
- : undefined;
-
- const event = {
+ return {
+ event: {
agentId: metadata?.agentId || '',
cost: state?.cost?.total,
duration,
errorDetail: state?.error,
errorMessage: this.extractErrorMessage?.(state?.error) || String(state?.error || ''),
- // Full state available in local mode only (not serialized to webhooks)
finalState: state,
lastAssistantContent,
llmCalls: state?.usage?.llm?.apiCalls,
@@ -1775,18 +1849,86 @@ export class AgentRuntimeService {
topicId: metadata?.topicId,
totalTokens: state?.usage?.llm?.tokens?.total,
userId: metadata?.userId || this.userId,
- };
+ },
+ metadata,
+ };
+ }
+
+ /**
+ * Emits completion AgentSignal source events and returns compact snapshot events.
+ * Fire-and-forget: errors are logged but never thrown.
+ */
+ private async emitCompletionSignalEvents(
+ operationId: string,
+ state: any,
+ reason: string,
+ ): Promise<Array<{ [key: string]: unknown; type: string }>> {
+ try {
+ const { metadata } = this.buildCompletionLifecycleEvent(operationId, state, reason);
+ const completionSignalEmission =
+ reason === 'error'
+ ? await emitAgentSignalSourceEvent(
+ {
+ payload: {
+ agentId: metadata?.agentId,
+ errorMessage: this.extractErrorMessage?.(state?.error),
+ operationId,
+ reason,
+ serializedContext: undefined,
+ topicId: metadata?.topicId,
+ turnCount: state?.stepCount || 0,
+ },
+ sourceId: `${operationId}:complete:${reason}`,
+ sourceType: 'agent.execution.failed',
+ },
+ {
+ agentId: metadata?.agentId,
+ db: this.serverDB,
+ userId: metadata?.userId || this.userId,
+ },
+ { ignoreError: true },
+ )
+ : await emitAgentSignalSourceEvent(
+ {
+ payload: {
+ agentId: metadata?.agentId,
+ operationId,
+ serializedContext: undefined,
+ steps: state?.stepCount || 0,
+ topicId: metadata?.topicId,
+ turnCount: state?.stepCount || 0,
+ },
+ sourceId: `${operationId}:complete:${reason}`,
+ sourceType: 'agent.execution.completed',
+ },
+ {
+ agentId: metadata?.agentId,
+ db: this.serverDB,
+ userId: metadata?.userId || this.userId,
+ },
+ { ignoreError: true },
+ );
+
+ return toAgentSignalSnapshotEvents(completionSignalEmission);
+ } catch (error) {
+ log('[%s] Completion signal emission error (non-fatal): %O', operationId, error);
+ return [];
+ }
+ }
+
+ /**
+ * Dispatch onComplete (and onError) hooks via HookDispatcher.
+ * Fire-and-forget: errors are logged but never thrown.
+ */
+ private async dispatchCompletionHooks(operationId: string, state: any, reason: string) {
+ try {
+ const { event, metadata } = this.buildCompletionLifecycleEvent(operationId, state, reason);
- // Dispatch onComplete hooks
await hookDispatcher.dispatch(operationId, 'onComplete', event, metadata._hooks);
- // Also dispatch onError hooks if reason is error
if (reason === 'error') {
await hookDispatcher.dispatch(operationId, 'onError', event, metadata._hooks);
- // Persist error into the assistant message so the frontend can display it
- // after fetching messages from DB. Without this, the message stays with
- // placeholder content and no error indicator.
const assistantMessageId = metadata?.assistantMessageId;
if (assistantMessageId && state?.error) {
const errorMessage = this.extractErrorMessage(state.error) || String(state.error);
@@ -1807,11 +1949,10 @@ export class AgentRuntimeService {
}
}
}
-
- // Cleanup hooks after completion
- hookDispatcher.unregister(operationId);
} catch (error) {
log('[%s] Hook dispatch error (non-fatal): %O', operationId, error);
+ } finally {
+ hookDispatcher.unregister(operationId);
}
}
@@ -2029,6 +2170,7 @@ export class AgentRuntimeService {
// If stopped due to executeSync's maxSteps limit, need to manually dispatch onComplete hooks
// Note: If stopped due to state.maxSteps being reached, onComplete has already been called in executeStep
if (state.status !== 'done' && state.status !== 'error') {
+ await this.emitCompletionSignalEvents(operationId, state, 'max_steps');
await this.dispatchCompletionHooks(operationId, state, 'max_steps');
}
}
diff --git a/src/server/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts b/src/server/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts
new file mode 100644
index 00000000000..3b36e1ab1fe
--- /dev/null
+++ b/src/server/services/agentRuntime/__tests__/agentSignalHooks.integration.test.ts
@@ -0,0 +1,340 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from 'vitest';
+
+interface AgentSignalRedisTestGlobal {
+ __agentSignalRedisClient?: typeof mockRedis | null;
+}
+
+const mockRedis = {
+ del: vi.fn(),
+ expire: vi.fn(),
+ hgetall: vi.fn(),
+ hset: vi.fn(),
+ set: vi.fn(),
+};
+
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'http://localhost:3010' } }));
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(() => ({
+ create: vi.fn(),
+ update: vi.fn(),
+ })),
+}));
+vi.mock('@/server/modules/AgentRuntime', () => ({
+ AgentRuntimeCoordinator: vi.fn().mockImplementation(() => ({
+ createAgentOperation: vi.fn(),
+ getOperationMetadata: vi.fn(),
+ loadAgentState: vi.fn(),
+ releaseStepLock: vi.fn().mockResolvedValue(undefined),
+ saveAgentState: vi.fn(),
+ saveStepResult: vi.fn(),
+ tryClaimStep: vi.fn().mockResolvedValue(true),
+ })),
+ createStreamEventManager: vi.fn(() => ({
+ cleanupOperation: vi.fn(),
+ publishAgentRuntimeEnd: vi.fn(),
+ publishAgentRuntimeInit: vi.fn(),
+ publishStreamEvent: vi.fn(),
+ })),
+}));
+vi.mock('@/server/modules/AgentRuntime/RuntimeExecutors', () => ({
+ createRuntimeExecutors: vi.fn(() => ({})),
+}));
+vi.mock('@/server/services/mcp', () => ({ mcpService: {} }));
+vi.mock('@/server/services/queue', () => ({
+ QueueService: vi.fn().mockImplementation(() => ({
+ getImpl: vi.fn(() => ({})),
+ scheduleMessage: vi.fn(),
+ })),
+}));
+vi.mock('@/server/services/queue/impls', () => ({
+ LocalQueueServiceImpl: class {},
+ isQueueAgentRuntimeEnabled: vi.fn().mockReturnValue(false),
+}));
+vi.mock('@/server/services/agentSignal/featureGate', () => ({
+ isAgentSignalEnabledForUser: vi.fn().mockResolvedValue(true),
+}));
+vi.mock('@/server/services/toolExecution', () => ({
+ ToolExecutionService: vi.fn().mockImplementation(() => ({})),
+}));
+vi.mock('@/server/services/toolExecution/builtin', () => ({
+ BuiltinToolsExecutor: vi.fn().mockImplementation(() => ({})),
+}));
+vi.mock('@lobechat/builtin-tools/dynamicInterventionAudits', () => ({
+ dynamicInterventionAudits: [],
+}));
+
+describe('AgentRuntimeService Agent Signal hook integration', () => {
+ it(
+ 'emits source events for beforeStep and afterStep boundaries',
+ { timeout: 20_000 },
+ async () => {
+ (globalThis as AgentSignalRedisTestGlobal).__agentSignalRedisClient = mockRedis;
+ mockRedis.set.mockResolvedValue('OK');
+ mockRedis.del.mockResolvedValue(1);
+ mockRedis.hgetall.mockResolvedValue({});
+ mockRedis.hset.mockResolvedValue(1);
+ mockRedis.expire.mockResolvedValue(1);
+
+ const { AgentRuntimeService } = await import('../AgentRuntimeService');
+ const service = new AgentRuntimeService({} as any, 'user-1', { queueService: null });
+ const coordinator = (service as any).coordinator;
+
+ vi.spyOn(coordinator, 'loadAgentState').mockResolvedValue({
+ createdAt: new Date().toISOString(),
+ lastModified: new Date().toISOString(),
+ messages: [{ content: 'hello', role: 'user' }],
+ metadata: {
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ operationId: 'op-1',
+ status: 'running',
+ stepCount: 0,
+ usage: { llm: { tokens: { total: 10 } }, tools: { totalCalls: 0 } },
+ });
+
+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({
+ runtime: {
+ step: vi.fn().mockResolvedValue({
+ events: [{ result: { content: 'done' }, type: 'llm_result' }],
+ newState: {
+ createdAt: new Date().toISOString(),
+ metadata: {
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ messages: [
+ { content: 'hello', role: 'user' },
+ { content: 'done', role: 'assistant' },
+ ],
+ status: 'done',
+ stepCount: 1,
+ usage: { llm: { apiCalls: 1, tokens: { total: 10 } }, tools: { totalCalls: 0 } },
+ },
+ nextContext: undefined,
+ }),
+ },
+ });
+
+ await service.executeStep({
+ context: { phase: 'user_input' } as any,
+ operationId: 'op-1',
+ stepIndex: 0,
+ });
+
+ expect(mockRedis.set).toHaveBeenCalledWith(
+ expect.stringContaining('runtime.before_step'),
+ '1',
+ 'EX',
+ 300,
+ 'NX',
+ );
+ expect(mockRedis.set).toHaveBeenCalledWith(
+ expect.stringContaining('runtime.after_step'),
+ '1',
+ 'EX',
+ 300,
+ 'NX',
+ );
+ expect(mockRedis.hset).toHaveBeenCalledWith('agent-signal:window:topic:topic-1', {
+ eventCount: '1',
+ lastEventAt: expect.any(String),
+ lastEventId: expect.stringContaining('runtime.before_step'),
+ });
+ },
+ );
+
+ /**
+ * @example
+ * await service.executeStep({ context, operationId: 'op-1', stepIndex: 0 });
+ * expect(savedSnapshot.steps[0].events.some((event) => event.type === 'agent_signal.source')).toBe(true);
+ */
+ it('records agent signal trace events into snapshot steps', { timeout: 10_000 }, async () => {
+ (globalThis as AgentSignalRedisTestGlobal).__agentSignalRedisClient = mockRedis;
+ mockRedis.set.mockResolvedValue('OK');
+ mockRedis.del.mockResolvedValue(1);
+ mockRedis.hgetall.mockResolvedValue({});
+ mockRedis.hset.mockResolvedValue(1);
+ mockRedis.expire.mockResolvedValue(1);
+
+ let partialSnapshot: any = null;
+ let savedSnapshot: any = null;
+ const snapshotStore = {
+ loadPartial: vi.fn(async () => partialSnapshot),
+ removePartial: vi.fn(async () => {
+ partialSnapshot = null;
+ }),
+ save: vi.fn(async (snapshot) => {
+ savedSnapshot = snapshot;
+ }),
+ savePartial: vi.fn(async (_operationId, partial) => {
+ partialSnapshot = partial;
+ }),
+ };
+
+ const { AgentRuntimeService } = await import('../AgentRuntimeService');
+ const service = new AgentRuntimeService({} as any, 'user-1', {
+ queueService: null,
+ snapshotStore: snapshotStore as any,
+ });
+ const coordinator = (service as any).coordinator;
+
+ vi.spyOn(coordinator, 'loadAgentState').mockResolvedValue({
+ createdAt: new Date().toISOString(),
+ lastModified: new Date().toISOString(),
+ messages: [{ content: 'hello', role: 'user' }],
+ metadata: {
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ operationId: 'op-1',
+ status: 'running',
+ stepCount: 0,
+ usage: { llm: { tokens: { total: 10 } }, tools: { totalCalls: 0 } },
+ });
+
+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({
+ runtime: {
+ step: vi.fn().mockResolvedValue({
+ events: [{ result: { content: 'done' }, type: 'llm_result' }],
+ newState: {
+ createdAt: new Date().toISOString(),
+ metadata: {
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ messages: [
+ { content: 'hello', role: 'user' },
+ { content: 'done', role: 'assistant' },
+ ],
+ status: 'done',
+ stepCount: 1,
+ usage: { llm: { apiCalls: 1, tokens: { total: 10 } }, tools: { totalCalls: 0 } },
+ },
+ nextContext: undefined,
+ }),
+ },
+ });
+
+ await service.executeStep({
+ context: { phase: 'user_input' } as any,
+ operationId: 'op-1',
+ stepIndex: 0,
+ });
+
+ expect(savedSnapshot).toBeDefined();
+ expect(savedSnapshot.steps).toHaveLength(1);
+ expect(savedSnapshot.steps[0].events).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ type: 'agent_signal.source' }),
+ expect.objectContaining({
+ data: expect.objectContaining({ sourceId: 'op-1:complete:done' }),
+ type: 'agent_signal.source',
+ }),
+ ]),
+ );
+ });
+
+ /**
+ * @example
+ * await service.executeStep({ context, operationId: 'op-1', stepIndex: 0 });
+ * expect(savedSnapshot.steps[0].events.some((event) => event.type === 'agent_signal.result')).toBe(true);
+ */
+ it('keeps completion signal events even when completion hooks fail afterward', async () => {
+ (globalThis as AgentSignalRedisTestGlobal).__agentSignalRedisClient = mockRedis;
+ mockRedis.set.mockResolvedValue('OK');
+ mockRedis.del.mockResolvedValue(1);
+ mockRedis.hgetall.mockResolvedValue({});
+ mockRedis.hset.mockResolvedValue(1);
+ mockRedis.expire.mockResolvedValue(1);
+
+ let partialSnapshot: any = null;
+ let savedSnapshot: any = null;
+ const snapshotStore = {
+ loadPartial: vi.fn(async () => partialSnapshot),
+ removePartial: vi.fn(async () => {
+ partialSnapshot = null;
+ }),
+ save: vi.fn(async (snapshot) => {
+ savedSnapshot = snapshot;
+ }),
+ savePartial: vi.fn(async (_operationId, partial) => {
+ partialSnapshot = partial;
+ }),
+ };
+
+ const { hookDispatcher } = await import('../hooks');
+ const dispatchSpy = vi
+ .spyOn(hookDispatcher, 'dispatch')
+ .mockRejectedValueOnce(new Error('hook boom'));
+
+ const { AgentRuntimeService } = await import('../AgentRuntimeService');
+ const service = new AgentRuntimeService({} as any, 'user-1', {
+ queueService: null,
+ snapshotStore: snapshotStore as any,
+ });
+ const coordinator = (service as any).coordinator;
+
+ vi.spyOn(coordinator, 'loadAgentState').mockResolvedValue({
+ createdAt: new Date().toISOString(),
+ lastModified: new Date().toISOString(),
+ messages: [{ content: 'hello', role: 'user' }],
+ metadata: {
+ _hooks: ['serialized-hook'],
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ operationId: 'op-1',
+ status: 'running',
+ stepCount: 0,
+ usage: { llm: { tokens: { total: 10 } }, tools: { totalCalls: 0 } },
+ });
+
+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({
+ runtime: {
+ step: vi.fn().mockResolvedValue({
+ events: [{ result: { content: 'done' }, type: 'llm_result' }],
+ newState: {
+ createdAt: new Date().toISOString(),
+ metadata: {
+ _hooks: ['serialized-hook'],
+ agentId: 'agent-1',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ },
+ messages: [
+ { content: 'hello', role: 'user' },
+ { content: 'done', role: 'assistant' },
+ ],
+ status: 'done',
+ stepCount: 1,
+ usage: { llm: { apiCalls: 1, tokens: { total: 10 } }, tools: { totalCalls: 0 } },
+ },
+ nextContext: undefined,
+ }),
+ },
+ });
+
+ await service.executeStep({
+ context: { phase: 'user_input' } as any,
+ operationId: 'op-1',
+ stepIndex: 0,
+ });
+
+ expect(dispatchSpy).toHaveBeenCalled();
+ expect(savedSnapshot.steps[0].events).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ data: expect.objectContaining({ sourceId: 'op-1:complete:done' }),
+ type: 'agent_signal.source',
+ }),
+ ]),
+ );
+ });
+});
diff --git a/src/server/services/agentRuntime/__tests__/hooksIntegration.test.ts b/src/server/services/agentRuntime/__tests__/hooksIntegration.test.ts
index 62f5d618cac..0be42ece635 100644
--- a/src/server/services/agentRuntime/__tests__/hooksIntegration.test.ts
+++ b/src/server/services/agentRuntime/__tests__/hooksIntegration.test.ts
@@ -69,7 +69,7 @@ describe('Hooks integration — afterStep event carries step presentation data',
const coordinator = (service as any).coordinator;
// Simulate a running operation with afterStep hooks in metadata
- coordinator.loadAgentState.mockResolvedValue({
+ vi.spyOn(coordinator, 'loadAgentState').mockResolvedValue({
createdAt: new Date().toISOString(),
lastModified: new Date().toISOString(),
messages: [{ content: 'Hello', role: 'user' }],
@@ -170,7 +170,7 @@ describe('Hooks integration — afterStep event carries step presentation data',
const service = createService();
const coordinator = (service as any).coordinator;
- coordinator.loadAgentState.mockResolvedValue({
+ vi.spyOn(coordinator, 'loadAgentState').mockResolvedValue({
createdAt: new Date().toISOString(),
lastModified: new Date().toISOString(),
messages: [],
@@ -258,7 +258,7 @@ describe('Hooks integration — onComplete event for early-terminal states', ()
const service = createService();
const coordinator = (service as any).coordinator;
- coordinator.loadAgentState.mockResolvedValue({
+ vi.spyOn(coordinator, 'loadAgentState').mockResolvedValue({
createdAt: new Date().toISOString(),
lastModified: new Date().toISOString(),
messages: [
@@ -303,7 +303,7 @@ describe('Hooks integration — afterStep event is compatible with renderStepPro
const service = createService();
const coordinator = (service as any).coordinator;
- coordinator.loadAgentState.mockResolvedValue({
+ vi.spyOn(coordinator, 'loadAgentState').mockResolvedValue({
createdAt: new Date().toISOString(),
lastModified: new Date().toISOString(),
messages: [],
diff --git a/src/server/services/agentSignal/__tests__/index.integration.test.ts b/src/server/services/agentSignal/__tests__/index.integration.test.ts
new file mode 100644
index 00000000000..7edf97fc239
--- /dev/null
+++ b/src/server/services/agentSignal/__tests__/index.integration.test.ts
@@ -0,0 +1,240 @@
+// @vitest-environment node
+import type { Mock } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+interface LoadIndexIntegrationModuleOptions {
+ featureGateEnabled?: boolean;
+ mockEmitSourceEvent?: Mock;
+ mockProjectObservability?: Mock;
+ mockRuntimeFactory?: Mock;
+}
+
+const mockRedis = {
+ del: vi.fn(),
+ expire: vi.fn(),
+ hgetall: vi.fn(),
+ hset: vi.fn(),
+ set: vi.fn(),
+};
+
+/**
+ * Loads the Agent Signal service entrypoint with one test-scoped module graph.
+ *
+ * Use when:
+ * - Integration tests need different mock boundaries for `index.ts`
+ * - Each case must isolate import-time wiring without creating file-level mock pollution
+ *
+ * Expects:
+ * - Optional mocks are passed before the entrypoint import happens
+ *
+ * Returns:
+ * - The imported entrypoint plus the stable mocks used for assertions
+ */
+const loadIndexIntegrationModule = async (options: LoadIndexIntegrationModuleOptions = {}) => {
+ vi.resetModules();
+ vi.doUnmock('../featureGate');
+ vi.doUnmock('../observability/projector');
+ vi.doUnmock('../observability/store');
+ vi.doUnmock('../runtime/AgentSignalRuntime');
+ vi.doUnmock('../sources');
+ vi.doUnmock('@/server/services/agentDocuments');
+
+ const persistAgentSignalObservability = vi.fn().mockResolvedValue(undefined);
+ const isAgentSignalEnabledForUser = vi.fn().mockResolvedValue(options.featureGateEnabled ?? true);
+
+ vi.doMock('../featureGate', () => ({
+ isAgentSignalEnabledForUser,
+ }));
+ vi.doMock('../observability/store', () => ({
+ persistAgentSignalObservability,
+ }));
+
+ if (options.mockEmitSourceEvent) {
+ vi.doMock('../sources', () => ({
+ emitSourceEvent: options.mockEmitSourceEvent,
+ }));
+ }
+
+ if (options.mockRuntimeFactory) {
+ vi.doMock('../runtime/AgentSignalRuntime', () => ({
+ createAgentSignalRuntime: options.mockRuntimeFactory,
+ }));
+ }
+
+ if (options.mockProjectObservability) {
+ vi.doMock('../observability/projector', () => ({
+ projectAgentSignalObservability: options.mockProjectObservability,
+ }));
+ }
+
+ const module = await import('../index');
+
+ return {
+ ...module,
+ mocks: {
+ isAgentSignalEnabledForUser,
+ persistAgentSignalObservability,
+ },
+ };
+};
+
+afterEach(() => {
+ vi.clearAllMocks();
+ vi.resetModules();
+ (
+ globalThis as { __agentSignalRedisClient?: typeof mockRedis | undefined }
+ ).__agentSignalRedisClient = undefined;
+});
+
+describe('emitAgentSignalSourceEvent integration', () => {
+ it('returns early when the feature gate is disabled', async () => {
+ const emitSourceEvent = vi.fn();
+ const { emitAgentSignalSourceEvent } = await loadIndexIntegrationModule({
+ featureGateEnabled: false,
+ mockEmitSourceEvent: emitSourceEvent,
+ });
+
+ const result = await emitAgentSignalSourceEvent(
+ {
+ payload: { message: 'Remember this.', messageId: 'msg-disabled' },
+ scopeKey: 'topic:topic-1',
+ sourceId: 'eval-agent-signal-disabled',
+ sourceType: 'agent.user.message',
+ timestamp: 1_710_000_000_000,
+ },
+ {
+ agentId: 'agent-1',
+ db: {} as never,
+ userId: 'user-1',
+ },
+ );
+
+ expect(result).toBeUndefined();
+ expect(emitSourceEvent).not.toHaveBeenCalled();
+ });
+
+ it('orchestrates source emission through the runtime boundary', async () => {
+ const emitSourceEvent = vi.fn().mockResolvedValue({
+ deduped: false,
+ source: {
+ chain: { chainId: 'chain:eval', rootSourceId: 'eval-source' },
+ payload: {},
+ scopeKey: 'topic:topic-1',
+ sourceId: 'eval-source',
+ sourceType: 'agent.user.message',
+ timestamp: 1_710_000_000_000,
+ },
+ trigger: {
+ scopeKey: 'topic:topic-1',
+ token: 'trigger:eval-source',
+ windowEventCount: 1,
+ },
+ });
+ const emitNormalized = vi.fn().mockResolvedValue({
+ status: 'completed',
+ trace: {
+ actions: [],
+ results: [],
+ signals: [],
+ source: {
+ chain: { chainId: 'chain:eval', rootSourceId: 'eval-source' },
+ payload: {},
+ scopeKey: 'topic:topic-1',
+ sourceId: 'eval-source',
+ sourceType: 'agent.user.message',
+ timestamp: 1_710_000_000_000,
+ },
+ },
+ });
+ const createAgentSignalRuntime = vi.fn().mockReturnValue({
+ emitNormalized,
+ });
+ const projectAgentSignalObservability = vi.fn().mockReturnValue({
+ actions: [],
+ results: [],
+ signals: [],
+ source: {
+ chain: { chainId: 'chain:eval', rootSourceId: 'eval-source' },
+ payload: {},
+ scopeKey: 'topic:topic-1',
+ sourceId: 'eval-source',
+ sourceType: 'agent.user.message',
+ timestamp: 1_710_000_000_000,
+ },
+ });
+ const { emitAgentSignalSourceEvent, mocks } = await loadIndexIntegrationModule({
+ mockEmitSourceEvent: emitSourceEvent,
+ mockProjectObservability: projectAgentSignalObservability,
+ mockRuntimeFactory: createAgentSignalRuntime,
+ });
+
+ const result = await emitAgentSignalSourceEvent(
+ {
+ payload: { message: 'Remember this.', messageId: 'msg-runtime' },
+ scopeKey: 'topic:topic-1',
+ sourceId: 'eval-agent-signal-basic-memory-1710000000000',
+ sourceType: 'agent.user.message',
+ timestamp: 1_710_000_000_000,
+ },
+ {
+ agentId: 'agent-1',
+ db: {} as never,
+ userId: 'user-1',
+ },
+ );
+
+ expect(result).toBeDefined();
+ expect(result?.deduped).toBe(false);
+ expect(emitSourceEvent).toHaveBeenCalledTimes(1);
+ expect(emitNormalized).toHaveBeenCalledTimes(1);
+ expect(mocks.persistAgentSignalObservability).toHaveBeenCalledTimes(1);
+ });
+
+ it(
+ 'projects and persists observability for the real source-to-runtime path',
+ { timeout: 10_000 },
+ async () => {
+ (globalThis as { __agentSignalRedisClient?: typeof mockRedis }).__agentSignalRedisClient =
+ mockRedis;
+ mockRedis.set.mockResolvedValue('OK');
+ mockRedis.del.mockResolvedValue(1);
+ mockRedis.hgetall.mockResolvedValue({});
+ mockRedis.hset.mockResolvedValue(1);
+ mockRedis.expire.mockResolvedValue(1);
+
+ const { emitAgentSignalSourceEvent, mocks } = await loadIndexIntegrationModule();
+
+ const result = await emitAgentSignalSourceEvent(
+ {
+ payload: {
+ intents: ['memory'],
+ message: 'remember this',
+ messageId: 'msg_1',
+ },
+ sourceId: 'source_1',
+ sourceType: 'agent.user.message',
+ },
+ {
+ agentId: 'agent_1',
+ db: {} as never,
+ userId: 'user_1',
+ },
+ );
+
+ expect(result).toBeDefined();
+ expect(result?.deduped).toBe(false);
+
+ if (!result || result.deduped) {
+ throw new Error('unexpected dedupe');
+ }
+
+ expect(result.orchestration.observability.record.sourceType).toBe('agent.user.message');
+ expect(result.orchestration.observability.envelope.source.sourceId).toBe('source_1');
+ expect(mocks.persistAgentSignalObservability).toHaveBeenCalledWith(
+ expect.objectContaining({
+ record: expect.objectContaining({ sourceId: 'source_1' }),
+ }),
+ );
+ },
+ );
+});
diff --git a/src/server/services/agentSignal/__tests__/scopeKey.test.ts b/src/server/services/agentSignal/__tests__/scopeKey.test.ts
new file mode 100644
index 00000000000..6f83011166c
--- /dev/null
+++ b/src/server/services/agentSignal/__tests__/scopeKey.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveProducerScopeKey, resolveRuntimeScopeKey } from '../runtime/scope';
+
+describe('Agent Signal scope key resolution', () => {
+ it('prefers topic scope for producer input when topicId exists', () => {
+ expect(resolveProducerScopeKey({ topicId: 't1' })).toBe('topic:t1');
+ });
+
+ it('falls back to bot scope for producer input when topicId is missing', () => {
+ expect(
+ resolveProducerScopeKey({
+ applicationId: 'app',
+ platform: 'wechat',
+ platformThreadId: 'th1',
+ }),
+ ).toBe('bot:wechat:app:th1');
+ });
+
+ it('falls back to global scope for producer input when no routing identifiers exist', () => {
+ expect(resolveProducerScopeKey({})).toBe('fallback:global');
+ });
+
+ it('prefers semantic runtime scope ordering for runtime input', () => {
+ expect(
+ resolveRuntimeScopeKey({
+ agentId: 'agent-1',
+ botScopeKey: 'bot:wechat:app:thread-1',
+ taskId: 'task-1',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ }),
+ ).toBe('topic:topic-1');
+ });
+
+ it('falls back through bot, task, agent, then user scope for runtime input', () => {
+ expect(
+ resolveRuntimeScopeKey({
+ botScopeKey: 'bot:wechat:app:thread-1',
+ userId: 'user-1',
+ }),
+ ).toBe('bot:wechat:app:thread-1');
+ expect(
+ resolveRuntimeScopeKey({
+ taskId: 'task-1',
+ userId: 'user-1',
+ }),
+ ).toBe('task:task-1');
+ expect(
+ resolveRuntimeScopeKey({
+ agentId: 'agent-1',
+ userId: 'user-1',
+ }),
+ ).toBe('agent:agent-1:user:user-1');
+ expect(
+ resolveRuntimeScopeKey({
+ userId: 'user-1',
+ }),
+ ).toBe('user:user-1');
+ });
+});
diff --git a/src/server/services/agentSignal/constants.ts b/src/server/services/agentSignal/constants.ts
new file mode 100644
index 00000000000..8e71f9d5bad
--- /dev/null
+++ b/src/server/services/agentSignal/constants.ts
@@ -0,0 +1,27 @@
+/** Server-owned Redis key prefix for AgentSignal storage adapters. */
+export const AGENT_SIGNAL_PREFIX = 'agent-signal:';
+
+/** Server-owned Redis key builders for AgentSignal adapters. */
+export const AGENT_SIGNAL_KEYS = {
+ dedupe: (id: string) => `${AGENT_SIGNAL_PREFIX}dedupe:${id}`,
+ lock: (scopeKey: string) => `${AGENT_SIGNAL_PREFIX}lock:${scopeKey}`,
+ policy: (policyId: string, scopeKey: string) =>
+ `${AGENT_SIGNAL_PREFIX}policy:${policyId}:${scopeKey}`,
+ waypoint: (scopeKey: string) => `${AGENT_SIGNAL_PREFIX}waypoint:${scopeKey}`,
+ waypointEvents: (scopeKey: string) => `${AGENT_SIGNAL_PREFIX}waypoint:${scopeKey}:events`,
+ window: (scopeKey: string) => `${AGENT_SIGNAL_PREFIX}window:${scopeKey}`,
+} as const;
+
+/** Server-owned timing defaults for AgentSignal storage and generation. */
+export const AGENT_SIGNAL_DEFAULTS = {
+ generationLockTtlSeconds: 5,
+ runtimeGuardTtlSeconds: 3600,
+ runtimeWaypointTtlSeconds: 3600,
+ signalDedupeTtlSeconds: 300,
+ signalWindowTtlSeconds: 3600,
+} as const;
+
+/** Server-owned runtime backend identifiers. */
+export const AGENT_SIGNAL_RUNTIME_BACKENDS = {
+ memory: 'memory',
+} as const;
diff --git a/src/server/services/agentSignal/featureGate.ts b/src/server/services/agentSignal/featureGate.ts
new file mode 100644
index 00000000000..28403f588af
--- /dev/null
+++ b/src/server/services/agentSignal/featureGate.ts
@@ -0,0 +1,54 @@
+import type { UserPreference } from '@lobechat/types';
+
+import { UserModel } from '@/database/models/user';
+import type { LobeChatDatabase } from '@/database/type';
+import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';
+
+/**
+ * Resolves whether Agent Self-iteration should be exposed in Labs for the current user.
+ *
+ * Use when:
+ * - UI or server code needs to know whether the Agent Self-iteration Lab toggle should exist
+ * - RuntimeConfig-backed feature flags are the source of truth for rollout eligibility
+ *
+ * Expects:
+ * - `userId` belongs to the current authenticated user
+ *
+ * Returns:
+ * - `true` only when the Agent Self-iteration feature flag is enabled for the user
+ */
+export const canShowAgentSignalLab = async (userId: string) => {
+ const featureFlags = await getServerFeatureFlagsStateFromRuntimeConfig(userId);
+
+ return featureFlags.enableAgentSelfIteration === true;
+};
+
+/**
+ * Resolves whether Agent Signal execution is enabled for the current user.
+ *
+ * Use when:
+ * - A server entrypoint needs to decide whether Agent Signal may execute
+ * - Both rollout eligibility and user opt-in must be enforced together
+ *
+ * Expects:
+ * - `db` and `userId` point at the same authenticated user context
+ *
+ * Returns:
+ * - `true` only when the feature flag is enabled and the user enabled the Lab switch
+ */
+export const isAgentSignalEnabledForUser = async (db: LobeChatDatabase, userId: string) => {
+ try {
+ const [featureFlagEnabled, preference] = await Promise.all([
+ canShowAgentSignalLab(userId),
+ new UserModel(db, userId).getUserPreference(),
+ ]);
+
+ return featureFlagEnabled && isAgentSelfIterationLabEnabled(preference);
+ } catch {
+ return false;
+ }
+};
+
+const isAgentSelfIterationLabEnabled = (preference?: UserPreference) => {
+ return preference?.lab?.enableAgentSelfIteration === true;
+};
diff --git a/src/server/services/agentSignal/index.ts b/src/server/services/agentSignal/index.ts
new file mode 100644
index 00000000000..12fd7c085a1
--- /dev/null
+++ b/src/server/services/agentSignal/index.ts
@@ -0,0 +1,352 @@
+import type {
+ AgentSignalSource,
+ BaseAction,
+ BaseSignal,
+ DedupedSourceEventResult,
+ ExecutorResult,
+ GeneratedSourceEventResult,
+ SignalPlan,
+} from '@lobechat/agent-signal';
+import debug from 'debug';
+
+import { getServerDB } from '@/database/server';
+import type { LobeChatDatabase } from '@/database/type';
+import { AgentDocumentsService } from '@/server/services/agentDocuments';
+import { AgentSignalWorkflow } from '@/server/workflows/agentSignal';
+
+import { isAgentSignalEnabledForUser } from './featureGate';
+import { projectAgentSignalObservability } from './observability/projector';
+import { persistAgentSignalObservability } from './observability/store';
+import { createDefaultAgentSignalPolicies } from './policies/groups/default';
+import type { RuntimeGuardBackend } from './runtime/AgentSignalRuntime';
+import { createAgentSignalRuntime } from './runtime/AgentSignalRuntime';
+import { AgentSignalScopeKey } from './scopeKey';
+import type { EmitSourceEventInput } from './sources';
+import { emitSourceEvent } from './sources';
+import type {
+ AgentSignalSourcePayloadMap,
+ AgentSignalSourceType,
+ SourceAgentExecutionCompleted,
+ SourceAgentExecutionFailed,
+ SourceAgentUserMessage,
+ SourceBotMessageMerged,
+ SourceRuntimeAfterStep,
+ SourceRuntimeBeforeStep,
+} from './sourceTypes';
+import type { AgentSignalSourceEventStore } from './store/types';
+
+export { createAgentSignalRuntime } from './runtime/AgentSignalRuntime';
+
+const log = debug('lobe-server:agent-signal:service');
+
+export interface AgentSignalExecutionContext {
+ agentId?: string;
+ db: LobeChatDatabase;
+ userId: string;
+}
+
+type RuntimeProducerSourceType =
+ | SourceAgentExecutionCompleted['sourceType']
+ | SourceAgentExecutionFailed['sourceType']
+ | SourceRuntimeAfterStep['sourceType']
+ | SourceRuntimeBeforeStep['sourceType'];
+
+type AgentSignalSourcePayload<TSourceType extends AgentSignalSourceType> =
+ AgentSignalSourcePayloadMap[TSourceType];
+
+/** One producer-side source emission input. */
+export interface AgentSignalSourceEventInput<
+ TSourceType extends AgentSignalSourceType,
+> extends Omit<EmitSourceEventInput, 'payload' | 'scopeKey' | 'sourceType' | 'timestamp'> {
+ payload: AgentSignalSourcePayload<TSourceType>;
+ scopeKey?: string;
+ sourceType: TSourceType;
+ timestamp?: number;
+}
+
+/** One AgentSignal emission execution option set. */
+export interface AgentSignalEmitOptions {
+ ignoreError?: boolean;
+}
+
+/** One AgentSignal async handoff result. */
+export interface QueuedAgentSignalEmissionResult {
+ accepted: boolean;
+ scopeKey: string;
+ workflowRunId: string;
+}
+
+interface ExecuteAgentSignalSourceEventOptions extends AgentSignalEmitOptions {
+ runtimeGuardBackend?: RuntimeGuardBackend;
+ store?: AgentSignalSourceEventStore;
+}
+
+export type RuntimeAgentSignalSourceInput<TSourceType extends RuntimeProducerSourceType> =
+ AgentSignalSourceEventInput<TSourceType>;
+
+export type BotAgentSignalSourceInput = AgentSignalSourceEventInput<
+ SourceBotMessageMerged['sourceType']
+>;
+
+export type UserMessageAgentSignalSourceInput = AgentSignalSourceEventInput<
+ SourceAgentUserMessage['sourceType']
+>;
+
+export type AgentSignalSourceEnvelope = AgentSignalSourceEventInput<AgentSignalSourceType>;
+
+const createEmptyRuntimeTrace = (source: AgentSignalSource) => {
+ return {
+ actions: [] as BaseAction[],
+ results: [],
+ signals: [] as BaseSignal[],
+ source,
+ };
+};
+
+export interface AgentSignalEmissionOrchestration {
+ actions: BaseAction[];
+ emittedSignals: BaseSignal[];
+ observability: Awaited<ReturnType<typeof projectAgentSignalObservability>>;
+ plans: SignalPlan[];
+ results: ExecutorResult[];
+}
+
+export interface RuntimeBackedAgentSignalEmissionOrchestration extends AgentSignalEmissionOrchestration {
+ runtimeResult: Awaited<
+ ReturnType<Awaited<ReturnType<typeof createAgentSignalRuntime>>['emitNormalized']>
+ >;
+}
+
+export interface GeneratedAgentSignalEmissionResult {
+ deduped: false;
+ orchestration: AgentSignalEmissionOrchestration | RuntimeBackedAgentSignalEmissionOrchestration;
+ source: AgentSignalSource;
+ trigger: GeneratedSourceEventResult['trigger'];
+}
+
+const buildRuntimeOrchestrationResult = (
+ source: AgentSignalSource,
+ runtimeResult: Awaited<
+ ReturnType<Awaited<ReturnType<typeof createAgentSignalRuntime>>['emitNormalized']>
+ >,
+): RuntimeBackedAgentSignalEmissionOrchestration => {
+ const trace =
+ runtimeResult.status === 'completed' ? runtimeResult.trace : createEmptyRuntimeTrace(source);
+ const observability = projectAgentSignalObservability({
+ actions: trace.actions,
+ results: trace.results,
+ signals: trace.signals,
+ source: trace.source,
+ });
+
+ return {
+ actions: trace.actions,
+ emittedSignals: trace.signals,
+ observability,
+ plans: [],
+ results: trace.results,
+ runtimeResult,
+ };
+};
+
+const resolveSourceScopeKey = (payload: Record<string, unknown>) => {
+ return AgentSignalScopeKey.fromProducerInput({
+ applicationId: typeof payload.applicationId === 'string' ? payload.applicationId : undefined,
+ platform: typeof payload.platform === 'string' ? payload.platform : undefined,
+ platformThreadId:
+ typeof payload.platformThreadId === 'string' ? payload.platformThreadId : undefined,
+ topicId: typeof payload.topicId === 'string' ? payload.topicId : undefined,
+ });
+};
+
+const executeAgentSignalSourceEventCore = async <TSourceType extends AgentSignalSourceType>(
+ input: AgentSignalSourceEventInput<TSourceType>,
+ context: AgentSignalExecutionContext,
+ options: ExecuteAgentSignalSourceEventOptions = {},
+): Promise<DedupedSourceEventResult | GeneratedAgentSignalEmissionResult | undefined> => {
+ try {
+ const sourceEvent = {
+ payload: input.payload,
+ scopeKey: input.scopeKey ?? resolveSourceScopeKey(input.payload),
+ sourceId: input.sourceId,
+ sourceType: input.sourceType,
+ timestamp: input.timestamp ?? Date.now(),
+ };
+
+ const emission = await emitSourceEvent(
+ sourceEvent,
+ options.store ? { store: options.store } : undefined,
+ );
+ if (emission.deduped) return emission;
+
+ const runtime = await createAgentSignalRuntime({
+ guardBackend: options.runtimeGuardBackend,
+ policies: createDefaultAgentSignalPolicies({
+ agentDocument: {
+ service: new AgentDocumentsService(context.db, context.userId),
+ },
+ userMemory: {
+ db: context.db,
+ userId: context.userId,
+ },
+ }),
+ });
+ const runtimeResult = await runtime.emitNormalized(emission.source);
+ const orchestration = buildRuntimeOrchestrationResult(emission.source, runtimeResult);
+
+ await persistAgentSignalObservability(orchestration.observability);
+
+ return {
+ ...emission,
+ orchestration,
+ };
+ } catch (error) {
+ if (!options.ignoreError) throw error;
+
+ console.error('[AgentSignal] Failed to emit source event:', error);
+ return undefined;
+ }
+};
+
+/**
+ * Emits one source event into the AgentSignal pipeline and executes matching policies.
+ *
+ * Use when:
+ * - Server-owned event producers need the normal AgentSignal boundary
+ * - The caller should not control dedupe storage
+ *
+ * Expects:
+ * - `context` points at the same database/user pair used by downstream policy execution
+ *
+ * Call stack:
+ *
+ * emitAgentSignalSourceEvent
+ * -> {@link emitSourceEvent}
+ * -> {@link createAgentSignalRuntime}
+ *
+ * Returns:
+ * - A deduped result or a generated signal with orchestration details
+ */
+export const emitAgentSignalSourceEvent = async <TSourceType extends AgentSignalSourceType>(
+ input: AgentSignalSourceEventInput<TSourceType>,
+ context: AgentSignalExecutionContext,
+ options: AgentSignalEmitOptions = {},
+): Promise<DedupedSourceEventResult | GeneratedAgentSignalEmissionResult | undefined> => {
+ if (!(await isAgentSignalEnabledForUser(context.db, context.userId))) {
+ return undefined;
+ }
+
+ return executeAgentSignalSourceEventCore(input, context, options);
+};
+
+/**
+ * Executes one source event immediately inside the current server process.
+ *
+ * Use when:
+ * - A workflow worker or server-owned path already controls execution timing
+ * - The caller needs optional Redis-backed runtime guard persistence
+ *
+ * Expects:
+ * - `context` points at the same database/user pair used by downstream policy execution
+ *
+ * Returns:
+ * - A deduped result or a generated signal with orchestration details
+ */
+export const executeAgentSignalSourceEvent = async <TSourceType extends AgentSignalSourceType>(
+ input: AgentSignalSourceEventInput<TSourceType>,
+ context: AgentSignalExecutionContext,
+ options: ExecuteAgentSignalSourceEventOptions = {},
+): Promise<DedupedSourceEventResult | GeneratedAgentSignalEmissionResult | undefined> => {
+ if (!(await isAgentSignalEnabledForUser(context.db, context.userId))) {
+ return undefined;
+ }
+
+ return executeAgentSignalSourceEventCore(input, context, options);
+};
+
+/**
+ * Enqueues one source event for async AgentSignal execution through Upstash Workflow.
+ *
+ * Use when:
+ * - The caller should return quickly and let async policy execution happen out-of-band
+ * - The source event should still reuse the normal AgentSignal normalization boundary
+ *
+ * Expects:
+ * - Payload contains enough routing context to derive a stable scope key
+ *
+ * Returns:
+ * - The accepted workflow run identifier and normalized scope key
+ */
+export const enqueueAgentSignalSourceEvent = async <TSourceType extends AgentSignalSourceType>(
+ input: AgentSignalSourceEventInput<TSourceType>,
+ context: Pick<AgentSignalExecutionContext, 'agentId' | 'userId'>,
+): Promise<QueuedAgentSignalEmissionResult> => {
+ const db = await getServerDB();
+
+ if (!(await isAgentSignalEnabledForUser(db, context.userId))) {
+ return {
+ accepted: false,
+ scopeKey: input.scopeKey ?? resolveSourceScopeKey(input.payload),
+ workflowRunId: '',
+ };
+ }
+
+ const sourceEvent = {
+ payload: input.payload,
+ scopeKey: input.scopeKey ?? resolveSourceScopeKey(input.payload),
+ sourceId: input.sourceId,
+ sourceType: input.sourceType,
+ timestamp: input.timestamp ?? Date.now(),
+ };
+
+ log('Enqueueing source event payload=%O', {
+ agentId: context.agentId,
+ payload: sourceEvent.payload,
+ scopeKey: sourceEvent.scopeKey,
+ sourceId: sourceEvent.sourceId,
+ sourceType: sourceEvent.sourceType,
+ timestamp: sourceEvent.timestamp,
+ userId: context.userId,
+ });
+
+ const trigger = await AgentSignalWorkflow.triggerRun({
+ agentId: context.agentId,
+ sourceEvent,
+ userId: context.userId,
+ });
+
+ return {
+ accepted: true,
+ scopeKey: sourceEvent.scopeKey,
+ workflowRunId: trigger.workflowRunId,
+ };
+};
+
+/**
+ * Emits one source event using an injected store for eval and test coverage.
+ *
+ * Use when:
+ * - The caller needs the exact production orchestration path but with isolated in-memory dedupe state
+ * - Eval or test code must avoid ambient Redis dependencies
+ *
+ * Expects:
+ * - `store` implements the same contract as the Redis-backed source-event store
+ *
+ * Call stack:
+ *
+ * emitAgentSignalSourceEventWithStore
+ * -> {@link emitSourceEvent}
+ * -> {@link createAgentSignalRuntime}
+ *
+ * Returns:
+ * - The same result shape as {@link emitAgentSignalSourceEvent}
+ */
+export const emitAgentSignalSourceEventWithStore = async <
+ TSourceType extends AgentSignalSourceType,
+>(
+ input: AgentSignalSourceEventInput<TSourceType>,
+ context: AgentSignalExecutionContext,
+ store: AgentSignalSourceEventStore,
+): Promise<DedupedSourceEventResult | GeneratedAgentSignalEmissionResult | undefined> => {
+ return executeAgentSignalSourceEventCore(input, context, { store });
+};
diff --git a/src/server/services/agentSignal/observability/__tests__/projector.test.ts b/src/server/services/agentSignal/observability/__tests__/projector.test.ts
new file mode 100644
index 00000000000..4aa182dca59
--- /dev/null
+++ b/src/server/services/agentSignal/observability/__tests__/projector.test.ts
@@ -0,0 +1,70 @@
+import { describe, expect, it } from 'vitest';
+
+import type { AgentSignalTelemetryRecord, AgentSignalTraceEnvelope } from '../types';
+
+describe('AgentSignal observability contracts', () => {
+ /**
+ * @example
+ * const record = { summary: { totalSignals: 1 } } satisfies AgentSignalTelemetryRecord;
+ * expect(record.summary.totalSignals).toBe(1);
+ */
+ it('supports compact summary records with conclusion chains', () => {
+ const record: AgentSignalTelemetryRecord = {
+ chainId: 'chain_1',
+ conclusionChain: {
+ compressedSignals: {},
+ dominantPath: ['agent.user.message', 'signal.sample.accepted'],
+ },
+ createdAt: '2026-04-21T00:00:00.000Z',
+ id: 'telemetry_1',
+ rootSourceId: 'source_1',
+ scopeKey: 'topic:t1',
+ sourceId: 'source_1',
+ sourceType: 'agent.user.message',
+ summary: {
+ attemptBreakdown: {
+ failed: 0,
+ retriableFailures: 0,
+ skipped: 0,
+ succeeded: 1,
+ total: 1,
+ },
+ domains: ['sample'],
+ outcomes: ['accepted'],
+ statusBreakdown: { applied: 1, failed: 0, skipped: 0 },
+ totalActions: 1,
+ totalSignals: 1,
+ },
+ };
+
+ expect(record.summary.totalSignals).toBe(1);
+ });
+
+ /**
+ * @example
+ * const envelope = { edges: [{ relation: 'produced' }] } satisfies AgentSignalTraceEnvelope;
+ * expect(envelope.edges[0].relation).toBe('produced');
+ */
+ it('supports expanded trace envelopes with nodes and edges', () => {
+ const envelope: AgentSignalTraceEnvelope = {
+ actions: [],
+ chainId: 'chain_1',
+ edges: [{ from: 'source_1', relation: 'produced', to: 'signal_1' }],
+ handlerRuns: [],
+ rootSourceId: 'source_1',
+ results: [],
+ signals: [],
+ source: {
+ chain: { chainId: 'chain_1', rootSourceId: 'source_1' },
+ payload: { message: 'remember this', messageId: 'msg_1' },
+ scopeKey: 'topic:t1',
+ sourceId: 'source_1',
+ sourceType: 'agent.user.message',
+ timestamp: 1,
+ },
+ version: 1,
+ };
+
+ expect(envelope.edges[0].relation).toBe('produced');
+ });
+});
diff --git a/src/server/services/agentSignal/observability/__tests__/store.test.ts b/src/server/services/agentSignal/observability/__tests__/store.test.ts
new file mode 100644
index 00000000000..e93d4760b60
--- /dev/null
+++ b/src/server/services/agentSignal/observability/__tests__/store.test.ts
@@ -0,0 +1,237 @@
+import { describe, expect, it, vi } from 'vitest';
+
+const {
+ actionCounterAdd,
+ actionDurationRecord,
+ actionResultCounterAdd,
+ chainCounterAdd,
+ chainDurationRecord,
+ signalCounterAdd,
+ signalTransitionCounterAdd,
+ sourceCounterAdd,
+ spanAddEvent,
+ spanEnd,
+ spanSetAttribute,
+ startActiveSpan,
+} = vi.hoisted(() => {
+ const actionCounterAdd = vi.fn();
+ const actionDurationRecord = vi.fn();
+ const actionResultCounterAdd = vi.fn();
+ const chainCounterAdd = vi.fn();
+ const chainDurationRecord = vi.fn();
+ const signalCounterAdd = vi.fn();
+ const signalTransitionCounterAdd = vi.fn();
+ const sourceCounterAdd = vi.fn();
+ const spanAddEvent = vi.fn();
+ const spanEnd = vi.fn();
+ const spanSetAttribute = vi.fn();
+ const startActiveSpan = vi.fn(async (_name: string, _options: unknown, callback: any) => {
+ return callback({
+ addEvent: spanAddEvent,
+ end: spanEnd,
+ setAttribute: spanSetAttribute,
+ });
+ });
+
+ return {
+ actionCounterAdd,
+ actionDurationRecord,
+ actionResultCounterAdd,
+ chainCounterAdd,
+ chainDurationRecord,
+ signalCounterAdd,
+ signalTransitionCounterAdd,
+ sourceCounterAdd,
+ spanAddEvent,
+ spanEnd,
+ spanSetAttribute,
+ startActiveSpan,
+ };
+});
+
+vi.mock('@lobechat/observability-otel/modules/agent-signal', () => ({
+ actionCounter: { add: actionCounterAdd },
+ actionDurationHistogram: { record: actionDurationRecord },
+ actionResultCounter: { add: actionResultCounterAdd },
+ chainCounter: { add: chainCounterAdd },
+ chainDurationHistogram: { record: chainDurationRecord },
+ signalActionTransitionCounter: { add: signalTransitionCounterAdd },
+ signalCounter: { add: signalCounterAdd },
+ sourceCounter: { add: sourceCounterAdd },
+ tracer: {
+ startActiveSpan,
+ },
+}));
+
+describe('persistAgentSignalObservability', () => {
+ /**
+ * @example
+ * await persistAgentSignalObservability(projection);
+ * expect(spanAddEvent).toHaveBeenCalledWith('agent_signal.source', expect.any(Object), expect.any(Number));
+ */
+ it('emits OTEL span events and metrics for one projected chain', async () => {
+ const { persistAgentSignalObservability } = await import('../store');
+
+ await persistAgentSignalObservability({
+ envelope: {
+ actions: [
+ {
+ actionId: 'action_1',
+ actionType: 'action.sample.handle',
+ chain: { chainId: 'chain_1', parentNodeId: 'signal_1', rootSourceId: 'source_1' },
+ payload: { message: 'remember this' },
+ signal: {
+ signalId: 'signal_1',
+ signalType: 'signal.sample.accepted',
+ },
+ source: { sourceId: 'source_1', sourceType: 'agent.user.message' },
+ timestamp: 3,
+ },
+ ],
+ chainId: 'chain_1',
+ edges: [],
+ handlerRuns: [
+ {
+ attempt: { completedAt: 5, current: 1, startedAt: 4, status: 'succeeded' },
+ handlerType: 'action.sample.handle',
+ id: 'action_1:attempt:1',
+ inputRefIds: ['signal_1'],
+ outputRefIds: ['action_1:result'],
+ startedAt: '2026-04-22T00:00:00.000Z',
+ status: 'ok',
+ },
+ ],
+ metadata: { agentId: 'agent_1', operationId: 'op_1', scopeKey: 'topic:t1', topicId: 't1' },
+ rootSourceId: 'source_1',
+ results: [
+ {
+ actionId: 'action_1',
+ attempt: { completedAt: 5, current: 1, startedAt: 4, status: 'succeeded' },
+ status: 'applied',
+ },
+ ],
+ signals: [
+ {
+ chain: { chainId: 'chain_1', parentNodeId: 'source_1', rootSourceId: 'source_1' },
+ payload: { intents: ['memory'], message: 'remember this', messageId: 'msg_1' },
+ signalId: 'signal_1',
+ signalType: 'signal.sample.accepted',
+ source: { sourceId: 'source_1', sourceType: 'agent.user.message' },
+ timestamp: 2,
+ },
+ ],
+ source: {
+ chain: { chainId: 'chain_1', rootSourceId: 'source_1' },
+ payload: {
+ agentId: 'agent_1',
+ message: 'remember this',
+ messageId: 'msg_1',
+ topicId: 't1',
+ },
+ scopeKey: 'topic:t1',
+ sourceId: 'source_1',
+ sourceType: 'agent.user.message',
+ timestamp: 1,
+ },
+ traceId: 'trace_1',
+ version: 1,
+ },
+ record: {
+ agentId: 'agent_1',
+ chainId: 'chain_1',
+ conclusionChain: {
+ compressedSignals: {},
+ dominantPath: ['agent.user.message', 'signal.sample.accepted'],
+ },
+ createdAt: '2026-04-22T00:00:00.000Z',
+ finalActionId: 'action_1',
+ finalActionType: 'action.sample.handle',
+ finalStatus: 'applied',
+ id: 'telemetry_1',
+ operationId: 'op_1',
+ rootSourceId: 'source_1',
+ scopeKey: 'topic:t1',
+ sourceId: 'source_1',
+ sourceType: 'agent.user.message',
+ durationMs: 6,
+ summary: {
+ attemptBreakdown: {
+ failed: 0,
+ retriableFailures: 0,
+ skipped: 0,
+ succeeded: 1,
+ total: 1,
+ },
+ domains: ['sample'],
+ outcomes: ['accepted'],
+ statusBreakdown: { applied: 1, failed: 0, skipped: 0 },
+ totalActions: 1,
+ totalSignals: 1,
+ },
+ topicId: 't1',
+ },
+ });
+
+ expect(startActiveSpan).toHaveBeenCalledWith(
+ 'agent_signal.observe',
+ expect.objectContaining({
+ attributes: expect.objectContaining({
+ 'agent.signal.chain_id': 'chain_1',
+ 'agent.signal.source_type': 'agent.user.message',
+ }),
+ }),
+ expect.any(Function),
+ );
+ expect(spanAddEvent).toHaveBeenCalledWith(
+ 'agent_signal.source',
+ expect.objectContaining({
+ sourceId: 'source_1',
+ }),
+ 1,
+ );
+ expect(spanAddEvent).toHaveBeenCalledWith(
+ 'agent_signal.result',
+ expect.objectContaining({
+ actionId: 'action_1',
+ attemptCurrent: 1,
+ }),
+ 3,
+ );
+ expect(sourceCounterAdd).toHaveBeenCalledWith(1, {
+ 'agent.signal.source_type': 'agent.user.message',
+ });
+ expect(signalCounterAdd).toHaveBeenCalledWith(1, {
+ 'agent.signal.signal_domain': 'sample',
+ 'agent.signal.signal_outcome': 'accepted',
+ 'agent.signal.signal_type': 'signal.sample.accepted',
+ 'agent.signal.source_type': 'agent.user.message',
+ });
+ expect(actionCounterAdd).toHaveBeenCalledWith(1, {
+ 'agent.signal.action_type': 'action.sample.handle',
+ });
+ expect(actionResultCounterAdd).toHaveBeenCalledWith(1, {
+ 'agent.signal.action_type': 'action.sample.handle',
+ 'agent.signal.result_status': 'applied',
+ });
+ expect(signalTransitionCounterAdd).toHaveBeenCalledWith(1, {
+ 'agent.signal.action_type': 'action.sample.handle',
+ 'agent.signal.signal_domain': 'sample',
+ 'agent.signal.signal_outcome': 'accepted',
+ 'agent.signal.signal_type': 'signal.sample.accepted',
+ });
+ expect(chainCounterAdd).toHaveBeenCalledWith(1, {
+ 'agent.signal.final_status': 'applied',
+ 'agent.signal.source_type': 'agent.user.message',
+ });
+ expect(actionDurationRecord).toHaveBeenCalledWith(1, {
+ 'agent.signal.action_type': 'action.sample.handle',
+ 'agent.signal.result_status': 'applied',
+ });
+ expect(chainDurationRecord).toHaveBeenCalledWith(6, {
+ 'agent.signal.final_status': 'applied',
+ 'agent.signal.source_type': 'agent.user.message',
+ });
+ expect(spanSetAttribute).toHaveBeenCalledWith('agent.signal.total_attempts', 1);
+ expect(spanEnd).toHaveBeenCalled();
+ });
+});
diff --git a/src/server/services/agentSignal/observability/__tests__/traceEvents.test.ts b/src/server/services/agentSignal/observability/__tests__/traceEvents.test.ts
new file mode 100644
index 00000000000..57dcfc30d96
--- /dev/null
+++ b/src/server/services/agentSignal/observability/__tests__/traceEvents.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from 'vitest';
+
+import { toAgentSignalTraceEvents } from '../traceEvents';
+
+describe('toAgentSignalTraceEvents', () => {
+ /**
+ * @example
+ * const events = toAgentSignalTraceEvents({
+ * source,
+ * signals: [],
+ * actions: [action],
+ * results: [
+ * {
+ * actionId: 'a1',
+ * attempt: { current: 1, startedAt: 1, status: 'succeeded' },
+ * status: 'applied',
+ * },
+ * ],
+ * });
+ * expect(events.map((event) => event.type)).toEqual(['agent_signal.source', 'agent_signal.action', 'agent_signal.result']);
+ */
+ it('formats compact runtime events for tracing systems', () => {
+ const events = toAgentSignalTraceEvents({
+ actions: [
+ {
+ actionId: 'action_1',
+ actionType: 'action.sample.handle',
+ chain: { chainId: 'chain_1', parentNodeId: 'signal_1', rootSourceId: 'source_1' },
+ payload: { message: 'remember this' },
+ signal: {
+ signalId: 'signal_1',
+ signalType: 'signal.sample.accepted',
+ },
+ source: { sourceId: 'source_1', sourceType: 'agent.user.message' },
+ timestamp: 3,
+ },
+ ],
+ results: [
+ {
+ actionId: 'action_1',
+ attempt: { completedAt: 5, current: 1, startedAt: 4, status: 'succeeded' },
+ status: 'applied',
+ },
+ ],
+ signals: [],
+ source: {
+ chain: { chainId: 'chain_1', rootSourceId: 'source_1' },
+ payload: { message: 'remember this', messageId: 'msg_1' },
+ scopeKey: 'topic:t1',
+ sourceId: 'source_1',
+ sourceType: 'agent.user.message',
+ timestamp: 1,
+ },
+ });
+
+ expect(events.map((event) => event.type)).toEqual([
+ 'agent_signal.source',
+ 'agent_signal.action',
+ 'agent_signal.result',
+ ]);
+ expect(events.at(-1)?.data).toEqual(
+ expect.objectContaining({
+ attemptCurrent: 1,
+ attemptStatus: 'succeeded',
+ }),
+ );
+ });
+});
diff --git a/src/server/services/agentSignal/observability/projector.ts b/src/server/services/agentSignal/observability/projector.ts
new file mode 100644
index 00000000000..ffa5444f6cd
--- /dev/null
+++ b/src/server/services/agentSignal/observability/projector.ts
@@ -0,0 +1,218 @@
+import type {
+ AgentSignalSource,
+ BaseAction,
+ BaseSignal,
+ ExecutorResult,
+} from '@lobechat/agent-signal';
+
+import type {
+ AgentSignalObservabilityProjection,
+ AgentSignalObservabilityProjectionInput,
+ AgentSignalTelemetryRecord,
+ AgentSignalTraceEdge,
+ AgentSignalTraceHandlerRun,
+} from './types';
+
+const readStringField = (payload: Record<string, unknown>, key: string) => {
+ return typeof payload[key] === 'string' ? payload[key] : undefined;
+};
+
+const resolveSignalDomain = (signalType: string) => {
+ const segments = signalType.split('.');
+
+ return segments.length > 2 ? segments.slice(1, -1).join('.') : signalType;
+};
+
+const resolveSignalOutcome = (signalType: string) => {
+ return signalType.split('.').at(-1) ?? signalType;
+};
+
+const buildStatusBreakdown = (results: ExecutorResult[]) => ({
+ applied: results.filter((result) => result.status === 'applied').length,
+ failed: results.filter((result) => result.status === 'failed').length,
+ skipped: results.filter((result) => result.status === 'skipped').length,
+});
+
+const buildAttemptBreakdown = (results: ExecutorResult[]) => ({
+ failed: results.filter((result) => result.attempt.status === 'failed').length,
+ retriableFailures: results.filter(
+ (result) => result.status === 'failed' && result.error.retriable === true,
+ ).length,
+ skipped: results.filter((result) => result.attempt.status === 'skipped').length,
+ succeeded: results.filter((result) => result.attempt.status === 'succeeded').length,
+ total: results.length,
+});
+
+const buildTraceEdges = (
+ source: AgentSignalSource,
+ signals: BaseSignal[],
+ actions: BaseAction[],
+ results: ExecutorResult[],
+): AgentSignalTraceEdge[] => {
+ const edges: AgentSignalTraceEdge[] = [];
+
+ for (const signal of signals) {
+ edges.push({
+ from: signal.chain.parentNodeId ?? source.sourceId,
+ relation: 'produced',
+ to: signal.signalId,
+ });
+ }
+
+ for (const action of actions) {
+ edges.push({
+ from: action.chain.parentNodeId ?? action.signal.signalId,
+ relation: 'triggered',
+ to: action.actionId,
+ });
+ }
+
+ for (const result of results) {
+ edges.push({
+ from: result.actionId,
+ relation: 'resulted-in',
+ to: `${result.actionId}:result`,
+ });
+ }
+
+ return edges;
+};
+
+const buildCompressedSignals = (signals: BaseSignal[]) => {
+ const compressedSignals = new Map<
+ string,
+ {
+ outcomes: Record<string, number>;
+ total: number;
+ }
+ >();
+
+ for (const signal of signals) {
+ const domain = resolveSignalDomain(signal.signalType);
+ const outcome = resolveSignalOutcome(signal.signalType);
+ const current = compressedSignals.get(domain) ?? { outcomes: {}, total: 0 };
+
+ current.total += 1;
+ current.outcomes[outcome] = (current.outcomes[outcome] ?? 0) + 1;
+ compressedSignals.set(domain, current);
+ }
+
+ return Object.fromEntries(compressedSignals.entries());
+};
+
+const buildHandlerRuns = (
+ actions: BaseAction[],
+ results: ExecutorResult[],
+): AgentSignalTraceHandlerRun[] => {
+ return actions.flatMap((action) => {
+ const result = results.find((candidate) => candidate.actionId === action.actionId);
+ if (!result) return [];
+
+ const status: AgentSignalTraceHandlerRun['status'] =
+ result.status === 'failed' ? 'failed' : result.status === 'skipped' ? 'skipped' : 'ok';
+
+ return [
+ {
+ attempt: result.attempt,
+ durationMs:
+ result.attempt.completedAt !== undefined
+ ? result.attempt.completedAt - result.attempt.startedAt
+ : undefined,
+ error:
+ result.status === 'failed'
+ ? {
+ code: result.error.code,
+ message: result.error.message,
+ }
+ : undefined,
+ handlerType: action.actionType,
+ id: `${action.actionId}:attempt:${result.attempt.current}`,
+ inputRefIds: [action.signal.signalId],
+ outputRefIds: [`${action.actionId}:result`],
+ reasoning: result.detail,
+ startedAt: new Date(result.attempt.startedAt).toISOString(),
+ status,
+ },
+ ];
+ });
+};
+
+const buildTelemetryRecord = (
+ input: AgentSignalObservabilityProjectionInput,
+): AgentSignalTelemetryRecord => {
+ const { actions, results, signals, source } = input;
+ const chainId = source.chain.chainId ?? source.chain.rootSourceId;
+ const finalAction = actions.at(-1);
+ const finalResult = finalAction
+ ? results.find((result) => result.actionId === finalAction.actionId)
+ : undefined;
+ const signalDomains = [
+ ...new Set(signals.map((signal) => resolveSignalDomain(signal.signalType))),
+ ];
+ const signalOutcomes = signals.map((signal) => resolveSignalOutcome(signal.signalType));
+ const sourcePayload = source.payload as Record<string, unknown>;
+
+ return {
+ agentId: readStringField(sourcePayload, 'agentId'),
+ chainId,
+ conclusionChain: {
+ compressedSignals: buildCompressedSignals(signals),
+ dominantPath: [
+ source.sourceType,
+ ...signals.map((signal) => signal.signalType),
+ ...(finalAction ? [finalAction.actionType] : []),
+ ],
+ finalReason:
+ finalResult?.status === 'failed' ? finalResult.error.message : finalResult?.detail,
+ },
+ createdAt: new Date(source.timestamp).toISOString(),
+ finalActionId: finalAction?.actionId,
+ finalActionType: finalAction?.actionType,
+ finalStatus: finalResult?.status,
+ id: `agent-signal:${source.sourceId}`,
+ operationId: readStringField(sourcePayload, 'operationId'),
+ rootSourceId: source.chain.rootSourceId,
+ scopeKey: source.scopeKey,
+ sourceId: source.sourceId,
+ sourceType: source.sourceType,
+ summary: {
+ attemptBreakdown: buildAttemptBreakdown(results),
+ domains: signalDomains,
+ outcomes: signalOutcomes,
+ statusBreakdown: buildStatusBreakdown(results),
+ totalActions: actions.length,
+ totalSignals: signals.length,
+ },
+ topicId: readStringField(sourcePayload, 'topicId'),
+ };
+};
+
+/** Projects one AgentSignal chain into compact telemetry and expanded trace artifacts. */
+export const projectAgentSignalObservability = (
+ input: AgentSignalObservabilityProjectionInput,
+): AgentSignalObservabilityProjection => {
+ const { actions, results, signals, source } = input;
+ const sourcePayload = source.payload as Record<string, unknown>;
+
+ return {
+ envelope: {
+ actions,
+ chainId: source.chain.chainId ?? source.chain.rootSourceId,
+ edges: buildTraceEdges(source, signals, actions, results),
+ handlerRuns: buildHandlerRuns(actions, results),
+ metadata: {
+ agentId: readStringField(sourcePayload, 'agentId'),
+ operationId: readStringField(sourcePayload, 'operationId'),
+ scopeKey: source.scopeKey,
+ topicId: readStringField(sourcePayload, 'topicId'),
+ },
+ rootSourceId: source.chain.rootSourceId,
+ results,
+ signals,
+ source,
+ traceId: readStringField(sourcePayload, 'operationId'),
+ version: 1,
+ },
+ record: buildTelemetryRecord(input),
+ };
+};
diff --git a/src/server/services/agentSignal/observability/store.ts b/src/server/services/agentSignal/observability/store.ts
new file mode 100644
index 00000000000..995ea669d8e
--- /dev/null
+++ b/src/server/services/agentSignal/observability/store.ts
@@ -0,0 +1,147 @@
+import type { BaseAction, BaseSignal, ExecutorResult } from '@lobechat/agent-signal';
+import {
+ actionCounter,
+ actionDurationHistogram,
+ actionResultCounter,
+ chainCounter,
+ chainDurationHistogram,
+ signalActionTransitionCounter,
+ signalCounter,
+ sourceCounter,
+ tracer,
+} from '@lobechat/observability-otel/modules/agent-signal';
+
+import { toAgentSignalTraceEvents } from './traceEvents';
+import type { AgentSignalObservabilityProjection } from './types';
+
+const toAttributeRecord = (data: Record<string, unknown>) => {
+ return Object.fromEntries(
+ Object.entries(data).flatMap(([key, value]) => {
+ if (value === undefined) return [];
+ if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') {
+ return [[key, value]];
+ }
+
+ return [[key, JSON.stringify(value)]];
+ }),
+ );
+};
+
+const resolveSignalDomain = (signalType: string) => {
+ const segments = signalType.split('.');
+
+ return segments.length > 2 ? segments.slice(1, -1).join('.') : signalType;
+};
+
+const resolveSignalOutcome = (signalType: string) => {
+ return signalType.split('.').at(-1) ?? signalType;
+};
+
+const buildTraceAttributes = (input: AgentSignalObservabilityProjection) => ({
+ 'agent.signal.chain_id': input.record.chainId,
+ 'agent.signal.final_action_type': input.record.finalActionType ?? 'none',
+ 'agent.signal.final_status': input.record.finalStatus ?? 'none',
+ 'agent.signal.scope_key': input.record.scopeKey,
+ 'agent.signal.source_id': input.record.sourceId,
+ 'agent.signal.source_type': input.record.sourceType,
+ ...(input.record.agentId ? { 'agent.signal.agent_id': input.record.agentId } : undefined),
+ ...(input.record.operationId
+ ? { 'agent.signal.operation_id': input.record.operationId }
+ : undefined),
+ ...(input.record.topicId ? { 'agent.signal.topic_id': input.record.topicId } : undefined),
+});
+
+const buildChainMetricAttributes = (input: AgentSignalObservabilityProjection) => ({
+ 'agent.signal.final_status': input.record.finalStatus ?? 'none',
+ 'agent.signal.source_type': input.record.sourceType,
+});
+
+const buildSourceMetricAttributes = (input: AgentSignalObservabilityProjection) => ({
+ 'agent.signal.source_type': input.record.sourceType,
+});
+
+const buildSignalMetricAttributes = (signal: BaseSignal) => ({
+ 'agent.signal.signal_domain': resolveSignalDomain(signal.signalType),
+ 'agent.signal.signal_outcome': resolveSignalOutcome(signal.signalType),
+ 'agent.signal.signal_type': signal.signalType,
+ 'agent.signal.source_type': signal.source.sourceType,
+});
+
+const buildActionMetricAttributes = (action: BaseAction) => ({
+ 'agent.signal.action_type': action.actionType,
+});
+
+const buildActionResultMetricAttributes = (action: BaseAction, result: ExecutorResult) => ({
+ 'agent.signal.action_type': action.actionType,
+ 'agent.signal.result_status': result.status,
+});
+
+const buildTransitionMetricAttributes = (signal: BaseAction['signal'], action: BaseAction) => ({
+ 'agent.signal.action_type': action.actionType,
+ 'agent.signal.signal_domain': resolveSignalDomain(signal.signalType),
+ 'agent.signal.signal_outcome': resolveSignalOutcome(signal.signalType),
+ 'agent.signal.signal_type': signal.signalType,
+});
+
+/** Persists projected AgentSignal observability artifacts into the default telemetry pipeline. */
+export const persistAgentSignalObservability = async (
+ input: AgentSignalObservabilityProjection,
+): Promise<void> => {
+ const traceAttributes = buildTraceAttributes(input);
+
+ await tracer.startActiveSpan(
+ 'agent_signal.observe',
+ { attributes: traceAttributes },
+ async (span) => {
+ const traceEvents = toAgentSignalTraceEvents({
+ actions: input.envelope.actions,
+ results: input.envelope.results,
+ signals: input.envelope.signals,
+ source: input.envelope.source,
+ });
+
+ for (const event of traceEvents) {
+ span.addEvent(event.type, toAttributeRecord(event.data), event.timestamp);
+ }
+
+ span.setAttribute('agent.signal.total_signals', input.record.summary.totalSignals);
+ span.setAttribute('agent.signal.total_actions', input.record.summary.totalActions);
+ span.setAttribute('agent.signal.total_attempts', input.record.summary.attemptBreakdown.total);
+ span.end();
+ },
+ );
+
+ sourceCounter.add(1, buildSourceMetricAttributes(input));
+
+ for (const signal of input.envelope.signals) {
+ signalCounter.add(1, buildSignalMetricAttributes(signal));
+ }
+
+ for (const action of input.envelope.actions) {
+ actionCounter.add(1, buildActionMetricAttributes(action));
+ signalActionTransitionCounter.add(1, buildTransitionMetricAttributes(action.signal, action));
+ }
+
+ for (const result of input.envelope.results) {
+ const action = input.envelope.actions.find(
+ (candidate) => candidate.actionId === result.actionId,
+ );
+
+ if (!action) continue;
+
+ actionResultCounter.add(1, buildActionResultMetricAttributes(action, result));
+
+ if (typeof result.attempt.completedAt === 'number') {
+ actionDurationHistogram.record(
+ result.attempt.completedAt - result.attempt.startedAt,
+ buildActionResultMetricAttributes(action, result),
+ );
+ }
+ }
+
+ chainCounter.add(1, buildChainMetricAttributes(input));
+
+ if (typeof input.record.durationMs === 'number') {
+ chainDurationHistogram.record(input.record.durationMs, buildChainMetricAttributes(input));
+ }
+};
diff --git a/src/server/services/agentSignal/observability/traceEvents.ts b/src/server/services/agentSignal/observability/traceEvents.ts
new file mode 100644
index 00000000000..54f6247c144
--- /dev/null
+++ b/src/server/services/agentSignal/observability/traceEvents.ts
@@ -0,0 +1,77 @@
+import type {
+ AgentSignalSource,
+ BaseAction,
+ BaseSignal,
+ ExecutorResult,
+} from '@lobechat/agent-signal';
+
+export interface AgentSignalTraceEvent {
+ [key: string]: unknown;
+ data: Record<string, unknown>;
+ timestamp: number;
+ type:
+ | 'agent_signal.action'
+ | 'agent_signal.result'
+ | 'agent_signal.signal'
+ | 'agent_signal.source';
+}
+
+/** Formats AgentSignal nodes into compact tracing events. */
+export const toAgentSignalTraceEvents = (input: {
+ actions: BaseAction[];
+ results: ExecutorResult[];
+ signals: BaseSignal[];
+ source: AgentSignalSource;
+}): AgentSignalTraceEvent[] => {
+ const sourceEvent: AgentSignalTraceEvent = {
+ data: {
+ chainId: input.source.chain.chainId,
+ rootSourceId: input.source.chain.rootSourceId,
+ scopeKey: input.source.scopeKey,
+ sourceId: input.source.sourceId,
+ sourceType: input.source.sourceType,
+ },
+ timestamp: input.source.timestamp,
+ type: 'agent_signal.source',
+ };
+
+ const signalEvents: AgentSignalTraceEvent[] = input.signals.map((signal) => ({
+ data: {
+ parentNodeId: signal.chain.parentNodeId,
+ signalId: signal.signalId,
+ signalType: signal.signalType,
+ sourceId: signal.source.sourceId,
+ },
+ timestamp: signal.timestamp,
+ type: 'agent_signal.signal',
+ }));
+
+ const actionEvents: AgentSignalTraceEvent[] = input.actions.map((action) => ({
+ data: {
+ actionId: action.actionId,
+ actionType: action.actionType,
+ parentNodeId: action.chain.parentNodeId,
+ signalId: action.signal.signalId,
+ },
+ timestamp: action.timestamp,
+ type: 'agent_signal.action',
+ }));
+
+ const resultEvents: AgentSignalTraceEvent[] = input.results.map((result, index) => ({
+ data: {
+ actionId: result.actionId,
+ attemptCurrent: result.attempt.current,
+ attemptStatus: result.attempt.status,
+ detail: result.detail,
+ errorCode: result.status === 'failed' ? result.error.code : undefined,
+ runId: 'runId' in result.attempt ? result.attempt.runId : undefined,
+ status: result.status,
+ },
+ timestamp:
+ input.actions.find((action) => action.actionId === result.actionId)?.timestamp ??
+ input.source.timestamp + input.signals.length + input.actions.length + index + 1,
+ type: 'agent_signal.result',
+ }));
+
+ return [sourceEvent, ...signalEvents, ...actionEvents, ...resultEvents];
+};
diff --git a/src/server/services/agentSignal/observability/types.ts b/src/server/services/agentSignal/observability/types.ts
new file mode 100644
index 00000000000..fad0875465b
--- /dev/null
+++ b/src/server/services/agentSignal/observability/types.ts
@@ -0,0 +1,127 @@
+import type {
+ AgentSignalSource,
+ BaseAction,
+ BaseSignal,
+ ExecutorResult,
+} from '@lobechat/agent-signal';
+
+/** Describes the compact telemetry record for one AgentSignal chain. */
+export interface AgentSignalTelemetryRecord {
+ agentId?: string;
+ chainId: string;
+ conclusionChain: {
+ /** Squashed signal family and outcome summary for compact display and filtering. */
+ compressedSignals: Record<string, unknown>;
+ /** Dominant compact path from source to the most meaningful terminal action. */
+ dominantPath: string[];
+ /** Final reasoning summary for compact display. */
+ finalReason?: string;
+ };
+ createdAt: string;
+ durationMs?: number;
+ expandedRef?: {
+ /** External raw detail pointer, typically S3. */
+ s3Key?: string;
+ version: 1;
+ };
+ finalActionId?: string;
+ finalActionType?: string;
+ finalStatus?: 'applied' | 'failed' | 'skipped';
+ id: string;
+ operationId?: string;
+ peerAgentIds?: string[];
+ rootSourceId: string;
+ scopeKey: string;
+ sourceId: string;
+ sourceType: string;
+ summary: {
+ /** Attempt lifecycle summary across all executed actions in the chain. */
+ attemptBreakdown: {
+ failed: number;
+ retriableFailures: number;
+ skipped: number;
+ succeeded: number;
+ total: number;
+ };
+ /** Logical signal families that appeared in this chain. */
+ domains: string[];
+ /** Final or intermediate business outcomes that appeared in this chain. */
+ outcomes: string[];
+ statusBreakdown: {
+ applied: number;
+ failed: number;
+ skipped: number;
+ };
+ totalActions: number;
+ totalSignals: number;
+ };
+ topicId?: string;
+ traceId?: string;
+}
+
+/** Carries lightweight metadata copied into the raw trace envelope. */
+export interface AgentSignalTraceMetadata {
+ agentId?: string;
+ operationId?: string;
+ scopeKey?: string;
+ topicId?: string;
+}
+
+/** Describes one directed causal link between two AgentSignal trace nodes. */
+export interface AgentSignalTraceEdge {
+ from: string;
+ relation: 'linked' | 'produced' | 'resulted-in' | 'triggered';
+ to: string;
+}
+
+/** Describes one handler execution summary inside a trace envelope. */
+export interface AgentSignalTraceHandlerRun {
+ /** Attempt metadata for the leaf action execution. */
+ attempt?: ExecutorResult['attempt'];
+ durationMs?: number;
+ error?: {
+ code?: string;
+ message: string;
+ };
+ /** Handler or microagent family identifier. */
+ handlerType: string;
+ /** Handler execution record id. */
+ id: string;
+ /** Direct node refs that were consumed. */
+ inputRefIds: string[];
+ /** Direct node refs that were produced. */
+ outputRefIds: string[];
+ /** Optional lightweight reasoning summary for debugging. */
+ reasoning?: string;
+ startedAt: string;
+ status: 'failed' | 'ok' | 'skipped';
+}
+
+/** Describes the expanded raw chain detail used for replay and drilldown. */
+export interface AgentSignalTraceEnvelope {
+ actions: BaseAction[];
+ chainId: string;
+ edges: AgentSignalTraceEdge[];
+ handlerRuns: AgentSignalTraceHandlerRun[];
+ metadata?: AgentSignalTraceMetadata;
+ results: ExecutorResult[];
+ rootSourceId: string;
+ signals: BaseSignal[];
+ source: AgentSignalSource;
+ traceId?: string;
+ version: 1;
+}
+
+/** Carries the summary and detail views for one projected chain. */
+export interface AgentSignalObservabilityProjection {
+ envelope: AgentSignalTraceEnvelope;
+ record: AgentSignalTelemetryRecord;
+}
+
+/** Carries the runtime slice needed to project one AgentSignal chain. */
+export interface AgentSignalObservabilityProjectionInput {
+ actions: BaseAction[];
+ results: ExecutorResult[];
+ signals: BaseSignal[];
+ source: AgentSignalSource;
+}
diff --git a/src/server/services/agentSignal/policies/groups/default.ts b/src/server/services/agentSignal/policies/groups/default.ts
new file mode 100644
index 00000000000..8f167478999
--- /dev/null
+++ b/src/server/services/agentSignal/policies/groups/default.ts
@@ -0,0 +1,18 @@
+import type { AgentSignalMiddleware } from '../../runtime/middleware';
+
+export interface CreateDefaultAgentSignalPoliciesOptions {}
+
+/**
+ * Creates the default policy installers for one Phase 1 AgentSignal runtime.
+ *
+ * The default milestone bundle stays intentionally narrow:
+ * - `userFeedbackAnalysis` remains enabled for memory-targeted feedback planning
+ * - `nudge.memory` remains enabled as the threshold-based runtime policy
+ * - `selfReflectionAnalysis` is not part of the default runtime path for Phase 1
+ */
+export const createDefaultAgentSignalPolicies = (
+ options: CreateDefaultAgentSignalPoliciesOptions = {},
+): AgentSignalMiddleware[] => {
+ void options;
+ return [];
+};
diff --git a/src/server/services/agentSignal/runtime/AgentSignalRuntime.ts b/src/server/services/agentSignal/runtime/AgentSignalRuntime.ts
new file mode 100644
index 00000000000..0fdf9e632e3
--- /dev/null
+++ b/src/server/services/agentSignal/runtime/AgentSignalRuntime.ts
@@ -0,0 +1,356 @@
+import type { AgentSignalSource, BaseAction, BaseSignal } from '@lobechat/agent-signal';
+
+import {
+ AgentSignalScheduler,
+ type AgentSignalSchedulerHandler,
+ type AgentSignalSchedulerRegistry,
+ type AgentSignalSourceInput,
+} from './AgentSignalScheduler';
+import type {
+ AgentSignalRuntimeBackend,
+ RuntimeNextHop,
+ RuntimePendingClaim,
+ RuntimeWaypoint,
+} from './backend/types';
+import type { AgentSignalRuntimeConfig, ResolveAgentSignalRuntimeConfigOptions } from './config';
+import { resolveAgentSignalRuntimeConfig } from './config';
+import type { RuntimeBackend as ContextRuntimeBackend, RuntimeNode } from './context';
+import type { AgentSignalMiddleware, AgentSignalMiddlewareRegistries } from './middleware';
+import { createAgentSignalMiddlewareInstallContext } from './middleware';
+
+export type AgentSignalRuntimeHandler<TNode extends RuntimeNode = RuntimeNode> =
+ AgentSignalSchedulerHandler<TNode>;
+export type AgentSignalRuntimeRegistry<TNode extends RuntimeNode = RuntimeNode> =
+ AgentSignalSchedulerRegistry<TNode>;
+
+export interface RuntimeGuardState {
+ lastEventAt?: number;
+ startedAt?: number;
+}
+
+interface RuntimeWaypointState extends RuntimeWaypoint {
+ trigger?: RuntimeNode;
+}
+
+export interface RuntimeGuardBackend {
+ getGuardState: ContextRuntimeBackend['getGuardState'];
+ touchGuardState: ContextRuntimeBackend['touchGuardState'];
+}
+
+export interface AgentSignalRuntimeRegistries {
+ actionRegistry: AgentSignalSchedulerRegistry<BaseAction>;
+ signalRegistry: AgentSignalSchedulerRegistry<BaseSignal>;
+ sourceRegistry: AgentSignalSchedulerRegistry<AgentSignalSource>;
+}
+
+const createRuntimeRegistry = <
+ TNode extends RuntimeNode,
+>(): AgentSignalSchedulerRegistry<TNode> => {
+ const entries = new Map<string, Array<AgentSignalSchedulerHandler<TNode>>>();
+
+ return {
+ match(type) {
+ return [...(entries.get(type) ?? [])];
+ },
+ register(type, entry) {
+ const current = entries.get(type) ?? [];
+ current.push(entry);
+ entries.set(type, current);
+
+ return this;
+ },
+ };
+};
+
+const resolveRuntimeTrigger = (waypoint: RuntimeWaypointState): RuntimeNode | undefined => {
+ if (waypoint.pending) {
+ return waypoint.pending.source;
+ }
+
+ if (!waypoint.terminal) {
+ return waypoint.events[0];
+ }
+
+ const terminalIndex = waypoint.events.findIndex(
+ (event) => event.sourceId === waypoint.terminal?.sourceId,
+ );
+
+ if (terminalIndex === -1) {
+ return waypoint.events[0];
+ }
+
+ return waypoint.events[terminalIndex + 1];
+};
+
+const createEmptyRuntimeWaypoint = (scopeKey: string): RuntimeWaypointState => {
+ return {
+ events: [],
+ scopeKey,
+ };
+};
+
+const createInMemoryRuntimeGuardBackend = (): RuntimeGuardBackend => {
+ const guardState = new Map<string, RuntimeGuardState>();
+
+ return {
+ async getGuardState(scopeKey, lane) {
+ return guardState.get(`${scopeKey}:${lane}`) ?? {};
+ },
+ async touchGuardState(scopeKey, lane, now) {
+ const key = `${scopeKey}:${lane}`;
+ const current = guardState.get(key) ?? {};
+ const next = {
+ lastEventAt: now,
+ startedAt: current.startedAt ?? now,
+ } satisfies RuntimeGuardState;
+
+ guardState.set(key, next);
+
+ return next;
+ },
+ };
+};
+
+const createInMemoryDurableBackend = (): AgentSignalRuntimeBackend => {
+ const waypoints = new Map<string, RuntimeWaypointState>();
+
+ const readWaypoint = (scopeKey: string) => {
+ return waypoints.get(scopeKey) ?? createEmptyRuntimeWaypoint(scopeKey);
+ };
+
+ const writeWaypoint = (scopeKey: string, next: RuntimeWaypointState) => {
+ waypoints.set(scopeKey, next);
+ };
+
+ const findNextPendingSource = (waypoint: RuntimeWaypointState) => {
+ if (waypoint.pending) {
+ return waypoint.pending.source;
+ }
+
+ if (!waypoint.terminal) {
+ return waypoint.events[0];
+ }
+
+ const terminalIndex = waypoint.events.findIndex(
+ (event) => event.sourceId === waypoint.terminal?.sourceId,
+ );
+
+ if (terminalIndex === -1) {
+ return waypoint.events[0];
+ }
+
+ return waypoint.events[terminalIndex + 1];
+ };
+
+ return {
+ async appendToWaypoint(scopeKey, source) {
+ const current = readWaypoint(scopeKey);
+
+ writeWaypoint(scopeKey, {
+ ...current,
+ events: [...current.events, source],
+ });
+ },
+ async claimPending(scopeKey) {
+ const current = readWaypoint(scopeKey);
+ if (current.pending) {
+ return current.pending;
+ }
+
+ const source = findNextPendingSource(current);
+ if (!source) return null;
+
+ const pending: RuntimePendingClaim = {
+ scopeKey,
+ source,
+ status: 'pending',
+ };
+
+ writeWaypoint(scopeKey, {
+ ...current,
+ pending,
+ });
+
+ return pending;
+ },
+ async complete(input) {
+ const current = readWaypoint(input.scopeKey);
+ if (current.pending?.source.sourceId !== input.sourceId) {
+ return;
+ }
+
+ writeWaypoint(input.scopeKey, {
+ ...current,
+ pending: undefined,
+ terminal: {
+ completedAt: input.completedAt,
+ sourceId: input.sourceId,
+ status: 'completed',
+ },
+ });
+ },
+ async fail(input) {
+ const current = readWaypoint(input.scopeKey);
+ if (current.pending?.source.sourceId !== input.sourceId) {
+ return;
+ }
+
+ writeWaypoint(input.scopeKey, {
+ ...current,
+ pending: undefined,
+ terminal: {
+ error: input.error,
+ failedAt: input.failedAt,
+ sourceId: input.sourceId,
+ status: 'failed',
+ },
+ });
+ },
+ async loadWaypoint(scopeKey) {
+ return readWaypoint(scopeKey);
+ },
+ async scheduleNextHop(input: RuntimeNextHop) {
+ const current = readWaypoint(input.scopeKey);
+
+ writeWaypoint(input.scopeKey, {
+ ...current,
+ nextHop: input,
+ });
+ },
+ };
+};
+
+const createRuntimeHostBackend = (input: {
+ durableBackend: Pick<AgentSignalRuntimeBackend, 'appendToWaypoint' | 'loadWaypoint'>;
+ guardBackend?: RuntimeGuardBackend;
+}): ContextRuntimeBackend => {
+ const guardBackend = input.guardBackend ?? createInMemoryRuntimeGuardBackend();
+
+ return {
+ appendToWaypoint(scopeKey, source) {
+ return input.durableBackend.appendToWaypoint(scopeKey, source);
+ },
+ async getGuardState(scopeKey, lane) {
+ return guardBackend.getGuardState(scopeKey, lane);
+ },
+ async loadWaypoint(scopeKey) {
+ const waypoint = await input.durableBackend.loadWaypoint(scopeKey);
+
+ return {
+ trigger: resolveRuntimeTrigger(waypoint),
+ };
+ },
+ touchGuardState(scopeKey, lane, now) {
+ return guardBackend.touchGuardState(scopeKey, lane, now);
+ },
+ };
+};
+
+const createConfiguredDurableBackend = (
+ options: CreateAgentSignalRuntimeOptions,
+): {
+ durableBackend: AgentSignalRuntimeBackend;
+ runtimeConfig: AgentSignalRuntimeConfig;
+} => {
+ const runtimeConfig =
+ options.runtimeConfig ??
+ resolveAgentSignalRuntimeConfig(
+ options.runtimeConfigInput ?? {
+ enableAgentSignalRuntime: true,
+ enableDurableRuntime: false,
+ },
+ );
+
+ return {
+ durableBackend: options.durableBackend ?? createInMemoryDurableBackend(),
+ runtimeConfig,
+ };
+};
+
+export interface CreateAgentSignalRuntimeOptions {
+ backend?: ContextRuntimeBackend;
+ durableBackend?: AgentSignalRuntimeBackend;
+ guardBackend?: RuntimeGuardBackend;
+ policies?: AgentSignalMiddleware[];
+ runtimeConfig?: AgentSignalRuntimeConfig;
+ runtimeConfigInput?: ResolveAgentSignalRuntimeConfigOptions;
+}
+
+/**
+ * Default assembled runtime for Agent Signal.
+ *
+ * Call stack:
+ *
+ * createAgentSignalRuntime
+ * -> {@link resolveAgentSignalRuntimeConfig}
+ * -> AgentSignalMiddleware.install
+ * -> {@link AgentSignalScheduler}
+ */
+export class AgentSignalRuntime {
+ readonly actionRegistry: AgentSignalSchedulerRegistry<BaseAction>;
+ readonly backend: ContextRuntimeBackend;
+ readonly durableBackend: AgentSignalRuntimeBackend;
+ readonly runtimeConfig: AgentSignalRuntimeConfig;
+ readonly scheduler: AgentSignalScheduler;
+ readonly signalRegistry: AgentSignalSchedulerRegistry<BaseSignal>;
+ readonly sourceRegistry: AgentSignalSchedulerRegistry<AgentSignalSource>;
+
+ constructor(options: Omit<CreateAgentSignalRuntimeOptions, 'policies'> = {}) {
+ this.actionRegistry = createRuntimeRegistry<BaseAction>();
+ this.signalRegistry = createRuntimeRegistry<BaseSignal>();
+ this.sourceRegistry = createRuntimeRegistry<AgentSignalSource>();
+
+ const { durableBackend, runtimeConfig } = createConfiguredDurableBackend(options);
+ this.durableBackend = durableBackend;
+ this.runtimeConfig = runtimeConfig;
+ this.backend =
+ options.backend ??
+ createRuntimeHostBackend({
+ durableBackend,
+ guardBackend: options.guardBackend,
+ });
+
+ this.scheduler = new AgentSignalScheduler({
+ actionRegistry: this.actionRegistry,
+ backend: this.backend,
+ signalRegistry: this.signalRegistry,
+ sourceRegistry: this.sourceRegistry,
+ });
+ }
+
+ async installPolicies(policies: AgentSignalMiddleware[] = []) {
+ const context = createAgentSignalMiddlewareInstallContext(
+ this.getRegistries() satisfies AgentSignalMiddlewareRegistries,
+ );
+
+ for (const policy of policies) {
+ await policy.install(context);
+ }
+
+ return this;
+ }
+
+ getRegistries(): AgentSignalRuntimeRegistries {
+ return {
+ actionRegistry: this.actionRegistry,
+ signalRegistry: this.signalRegistry,
+ sourceRegistry: this.sourceRegistry,
+ };
+ }
+
+ emit(input: AgentSignalSourceInput) {
+ return this.scheduler.emit(input);
+ }
+
+ emitNormalized(source: AgentSignalSource) {
+ return this.scheduler.emitNormalized(source);
+ }
+}
+
+export const createAgentSignalRuntime = async (options: CreateAgentSignalRuntimeOptions = {}) => {
+ const runtime = new AgentSignalRuntime(options);
+
+ await runtime.installPolicies(options.policies);
+
+ return runtime;
+};
diff --git a/src/server/services/agentSignal/runtime/AgentSignalScheduler.ts b/src/server/services/agentSignal/runtime/AgentSignalScheduler.ts
new file mode 100644
index 00000000000..31a6d4c4757
--- /dev/null
+++ b/src/server/services/agentSignal/runtime/AgentSignalScheduler.ts
@@ -0,0 +1,307 @@
+import type {
+ AgentSignalScope,
+ AgentSignalSource,
+ BaseAction,
+ BaseSignal,
+ ExecutorResult,
+ RuntimeConcludeProcessorResult,
+ RuntimeProcessorResult,
+ RuntimeScheduleProcessorResult,
+ RuntimeWaitProcessorResult,
+} from '@lobechat/agent-signal';
+import { AGENT_SIGNAL_TYPES, createSource } from '@lobechat/agent-signal';
+
+import {
+ createRuntimeProcessorContext,
+ type RuntimeBackend,
+ type RuntimeNode,
+ type RuntimeProcessorContext,
+} from './context';
+import { resolveRuntimeScopeKey } from './scope';
+
+/** One generalized source emission accepted by {@link AgentSignalScheduler}. */
+export interface AgentSignalSourceInput {
+ payload: Record<string, unknown>;
+ scope: AgentSignalScope;
+ sourceId?: string;
+ sourceType: string;
+ timestamp?: number;
+}
+
+/** Runtime handler contract for one queueable semantic node. */
+export interface AgentSignalSchedulerHandler<TNode extends RuntimeNode = RuntimeNode> {
+ handle: (
+ input: TNode,
+ context: RuntimeProcessorContext,
+ ) => Promise<AgentSignalSchedulerHandlerResult | void> | AgentSignalSchedulerHandlerResult | void;
+ id: string;
+}
+
+/** Handler results accepted by the generalized runtime host. */
+export type AgentSignalSchedulerHandlerResult = ExecutorResult | RuntimeProcessorResult;
+
+/** Registry contract used by the generalized runtime host. */
+export interface AgentSignalSchedulerRegistry<TNode extends RuntimeNode = RuntimeNode> {
+ match: (type: string) => Array<AgentSignalSchedulerHandler<TNode>>;
+ register: (
+ type: string,
+ entry: AgentSignalSchedulerHandler<TNode>,
+ ) => AgentSignalSchedulerRegistry<TNode>;
+}
+
+/** Scheduler dependencies for the generalized runtime host. */
+export interface AgentSignalSchedulerDeps {
+ actionRegistry: AgentSignalSchedulerRegistry<BaseAction>;
+ backend: RuntimeBackend;
+ signalRegistry: AgentSignalSchedulerRegistry<BaseSignal>;
+ sourceRegistry: AgentSignalSchedulerRegistry<AgentSignalSource>;
+}
+
+/** Terminal result returned by the generalized runtime host. */
+export type AgentSignalSchedulerEmitResult =
+ | AgentSignalSchedulerCompletedResult
+ | RuntimeConcludeProcessorResult
+ | RuntimeScheduleProcessorResult
+ | RuntimeWaitProcessorResult;
+
+/** Trace captured during one completed runtime pass. */
+export interface AgentSignalSchedulerTrace {
+ actions: BaseAction[];
+ results: ExecutorResult[];
+ signals: BaseSignal[];
+ source: AgentSignalSource;
+}
+
+/**
+ * Completed runtime result including the captured execution trace.
+ */
+export interface AgentSignalSchedulerCompletedResult {
+ status: 'completed';
+ trace: AgentSignalSchedulerTrace;
+}
+
+const isSourceNode = (node: RuntimeNode): node is AgentSignalSource => {
+ return 'sourceId' in node;
+};
+
+const isSignalNode = (node: RuntimeNode): node is BaseSignal => {
+ return 'signalId' in node;
+};
+
+const isExecutorResult = (value: unknown): value is ExecutorResult => {
+ if (!value || typeof value !== 'object') return false;
+ if (!('status' in value) || !('actionId' in value)) return false;
+
+ return value.status === 'applied' || value.status === 'failed' || value.status === 'skipped';
+};
+
+const buildExecutionSignal = (action: BaseAction, result: ExecutorResult): BaseSignal => {
+ const baseSignal = {
+ chain: {
+ chainId: action.chain.chainId,
+ parentActionId: action.actionId,
+ parentNodeId: action.actionId,
+ rootSourceId: action.chain.rootSourceId,
+ },
+ signalId: `${action.actionId}:result`,
+ source: action.source,
+ timestamp: Date.now(),
+ };
+
+ if (result.status === 'failed') {
+ return {
+ ...baseSignal,
+ payload: {
+ actionId: action.actionId,
+ actionType: action.actionType,
+ attempt: result.attempt,
+ detail: result.detail,
+ error: result.error,
+ },
+ signalType: AGENT_SIGNAL_TYPES.actionFailed,
+ };
+ }
+
+ return {
+ ...baseSignal,
+ payload: {
+ actionId: action.actionId,
+ actionType: action.actionType,
+ attempt: result.attempt,
+ detail: result.detail,
+ },
+ signalType:
+ result.status === 'applied'
+ ? AGENT_SIGNAL_TYPES.actionApplied
+ : AGENT_SIGNAL_TYPES.actionSkipped,
+ };
+};
+
+/** Queue-driven scheduler for one already-assembled AgentSignal runtime. */
+export class AgentSignalScheduler {
+ constructor(private readonly deps: AgentSignalSchedulerDeps) {}
+
+ async emit(input: AgentSignalSourceInput): Promise<AgentSignalSchedulerEmitResult> {
+ const scopeKey = resolveRuntimeScopeKey(input.scope);
+ const source = createSource({
+ payload: input.payload,
+ scope: input.scope,
+ scopeKey,
+ sourceId: input.sourceId,
+ sourceType: input.sourceType,
+ timestamp: input.timestamp,
+ });
+
+ return this.processSource(source, scopeKey);
+ }
+
+ /** Processes one pre-normalized source node through the runtime host. */
+ async emitNormalized(source: AgentSignalSource): Promise<AgentSignalSchedulerEmitResult> {
+ return this.processSource(source, source.scopeKey);
+ }
+
+ private async processSource(
+ source: AgentSignalSource,
+ scopeKey: string,
+ ): Promise<AgentSignalSchedulerEmitResult> {
+ let terminalResult: AgentSignalSchedulerEmitResult | undefined;
+ const trace: AgentSignalSchedulerTrace = {
+ actions: [],
+ results: [],
+ signals: [],
+ source,
+ };
+
+ await this.deps.backend.appendToWaypoint(scopeKey, source);
+
+ const pending = await this.deps.backend.loadWaypoint(scopeKey);
+ const queue: RuntimeNode[] = [pending.trigger ?? source];
+
+ while (queue.length > 0) {
+ const node = queue.shift();
+ if (!node) continue;
+ this.captureNode(node, trace);
+ const runtimeResult = await this.dispatchNode(node, scopeKey, queue, trace);
+
+ if (runtimeResult && !terminalResult) {
+ terminalResult = runtimeResult;
+ }
+ }
+
+ return terminalResult ?? ({ status: 'completed', trace } as const);
+ }
+
+ private async applyResult(
+ node: RuntimeNode,
+ result: AgentSignalSchedulerHandlerResult | void,
+ queue: RuntimeNode[],
+ trace: AgentSignalSchedulerTrace,
+ ): Promise<AgentSignalSchedulerEmitResult | undefined> {
+ if (!result) return;
+ if (isExecutorResult(result)) {
+ if ('actionId' in node) {
+ trace.results.push(result);
+ queue.push(buildExecutionSignal(node, result));
+ }
+
+ return;
+ }
+
+ switch (result.status) {
+ case 'conclude':
+ case 'schedule':
+ case 'wait': {
+ return result;
+ }
+ case 'dispatch': {
+ if (result.signals) {
+ queue.push(...result.signals);
+ }
+
+ if (result.actions) {
+ queue.push(...result.actions);
+ }
+
+ return;
+ }
+ }
+ }
+
+ private captureNode(node: RuntimeNode, trace: AgentSignalSchedulerTrace) {
+ if (isSourceNode(node)) return;
+ if (isSignalNode(node)) {
+ trace.signals.push(node);
+ return;
+ }
+
+ trace.actions.push(node);
+ }
+
+ private resolveNodeTime(node: RuntimeNode) {
+ return 'timestamp' in node && typeof node.timestamp === 'number' ? node.timestamp : Date.now();
+ }
+
+ private async dispatchHandlers<TNode extends RuntimeNode>(
+ handlers: Array<AgentSignalSchedulerHandler<TNode>>,
+ node: TNode,
+ scopeKey: string,
+ queue: RuntimeNode[],
+ trace: AgentSignalSchedulerTrace,
+ ) {
+ let terminalResult: AgentSignalSchedulerEmitResult | undefined;
+ const now = this.resolveNodeTime(node);
+
+ for (const handler of handlers) {
+ const result = await handler.handle(
+ node,
+ createRuntimeProcessorContext({
+ backend: this.deps.backend,
+ now: () => now,
+ scopeKey,
+ }),
+ );
+ const runtimeResult = await this.applyResult(node, result, queue, trace);
+
+ if (runtimeResult && !terminalResult) {
+ terminalResult = runtimeResult;
+ }
+ }
+
+ return terminalResult;
+ }
+
+ private async dispatchNode(
+ node: RuntimeNode,
+ scopeKey: string,
+ queue: RuntimeNode[],
+ trace: AgentSignalSchedulerTrace,
+ ) {
+ if (isSourceNode(node)) {
+ return this.dispatchHandlers(
+ this.deps.sourceRegistry.match(node.sourceType),
+ node,
+ scopeKey,
+ queue,
+ trace,
+ );
+ }
+
+ if (isSignalNode(node)) {
+ return this.dispatchHandlers(
+ this.deps.signalRegistry.match(node.signalType),
+ node,
+ scopeKey,
+ queue,
+ trace,
+ );
+ }
+
+ return this.dispatchHandlers(
+ this.deps.actionRegistry.match(node.actionType),
+ node,
+ scopeKey,
+ queue,
+ trace,
+ );
+ }
+}
diff --git a/src/server/services/agentSignal/runtime/__tests__/AgentSignalRuntime.test.ts b/src/server/services/agentSignal/runtime/__tests__/AgentSignalRuntime.test.ts
new file mode 100644
index 00000000000..bf075b0dc98
--- /dev/null
+++ b/src/server/services/agentSignal/runtime/__tests__/AgentSignalRuntime.test.ts
@@ -0,0 +1,403 @@
+import type { AgentSignalSource, BaseAction, BaseSignal } from '@lobechat/agent-signal';
+import { createAction, createSignal } from '@lobechat/agent-signal';
+import { describe, expect, it } from 'vitest';
+
+import {
+ AgentSignalScheduler,
+ type AgentSignalSchedulerHandler,
+ type AgentSignalSchedulerRegistry,
+} from '../AgentSignalScheduler';
+import type { RuntimeBackend, RuntimeNode, RuntimeWaypoint } from '../context';
+
+interface TestGuardState {
+ lastEventAt?: number;
+ startedAt?: number;
+}
+
+const createRuntimeBackend = (): RuntimeBackend => {
+ const guardState = new Map<string, TestGuardState>();
+ const waypoints = new Map<string, RuntimeWaypoint>();
+
+ return {
+ async appendToWaypoint(scopeKey, source) {
+ waypoints.set(scopeKey, { trigger: source });
+ },
+ async getGuardState(scopeKey, lane) {
+ return guardState.get(`${scopeKey}:${lane}`) ?? {};
+ },
+ async loadWaypoint(scopeKey) {
+ return waypoints.get(scopeKey) ?? {};
+ },
+ async touchGuardState(scopeKey, lane, now) {
+ const key = `${scopeKey}:${lane}`;
+ const current = guardState.get(key) ?? {};
+ const next = {
+ lastEventAt: now,
+ startedAt: current.startedAt ?? now,
+ } satisfies TestGuardState;
+
+ guardState.set(key, next);
+
+ return next;
+ },
+ };
+};
+
+const createRuntimeRegistry = <
+ TNode extends RuntimeNode,
+>(): AgentSignalSchedulerRegistry<TNode> => {
+ const entries = new Map<string, Array<AgentSignalSchedulerHandler<TNode>>>();
+
+ return {
+ match(type) {
+ return [...(entries.get(type) ?? [])];
+ },
+ register(type, entry) {
+ const current = entries.get(type) ?? [];
+ current.push(entry);
+ entries.set(type, current);
+
+ return this;
+ },
+ };
+};
+
+describe('AgentSignalScheduler', () => {
+ /**
+ * @example
+ * const result = await runtime.emit({
+ * payload: { message: 'remember this' },
+ * scope: { agentId: 'agent-1', topicId: 'topic-1', userId: 'user-1' },
+ * sourceType: 'source.user.message',
+ * });
+ *
+ * expect(result.status).toBe('completed');
+ */
+ it('accepts one generalized emit(source) entry', async () => {
+ const backend = createRuntimeBackend();
+ const actionRegistry = createRuntimeRegistry<BaseAction>();
+ const signalRegistry = createRuntimeRegistry<BaseSignal>();
+ const sourceRegistry = createRuntimeRegistry<AgentSignalSource>();
+ const handled: string[] = [];
+
+ sourceRegistry.register('source.user.message', {
+ async handle(source, context) {
+ handled.push(`source:${String(source.sourceType)}:${context.scopeKey}`);
+
+ return {
+ signals: [
+ createSignal({
+ payload: { message: source.payload.message as string },
+ signalType: 'signal.memory.request',
+ source,
+ }),
+ ],
+ status: 'dispatch' as const,
+ };
+ },
+ id: 'source-handler',
+ });
+
+ signalRegistry.register('signal.memory.request', {
+ async handle(signal, context) {
+ handled.push(`signal:${String(signal.signalType)}:${context.scopeKey}`);
+
+ return {
+ actions: [
+ createAction({
+ actionType: 'action.memory.persist',
+ payload: { message: signal.payload.message as string },
+ signal,
+ }),
+ ],
+ status: 'dispatch' as const,
+ };
+ },
+ id: 'signal-handler',
+ });
+
+ actionRegistry.register('action.memory.persist', {
+ async handle(action, context) {
+ handled.push(`action:${String(action.actionType)}:${context.scopeKey}`);
+
+ expect(action.chain.rootSourceId).toContain('source:');
+ },
+ id: 'action-handler',
+ });
+
+ const runtime = new AgentSignalScheduler({
+ actionRegistry,
+ backend,
+ signalRegistry,
+ sourceRegistry,
+ });
+
+ const result = await runtime.emit({
+ payload: { message: 'remember this' },
+ scope: { agentId: 'agent-1', topicId: 'topic-1', userId: 'user-1' },
+ sourceType: 'source.user.message',
+ });
+
+ expect(result.status).toBe('completed');
+ expect(handled).toEqual([
+ 'source:source.user.message:topic:topic-1',
+ 'signal:signal.memory.request:topic:topic-1',
+ 'action:action.memory.persist:topic:topic-1',
+ ]);
+
+ await expect(backend.loadWaypoint('topic:topic-1')).resolves.toEqual(
+ expect.objectContaining({
+ trigger: expect.objectContaining({
+ scopeKey: 'topic:topic-1',
+ sourceType: 'source.user.message',
+ }),
+ }),
+ );
+ });
+
+ /**
+ * @example
+ * const result = await runtime.emit({
+ * payload: { message: 'remember this later' },
+ * scope: { topicId: 'topic-1', userId: 'user-1' },
+ * sourceType: 'source.user.message',
+ * });
+ *
+ * expect(result.status).toBe('wait');
+ */
+ it('returns terminal wait results instead of discarding them', async () => {
+ const backend = createRuntimeBackend();
+ const actionRegistry = createRuntimeRegistry<BaseAction>();
+ const signalRegistry = createRuntimeRegistry<BaseSignal>();
+ const sourceRegistry = createRuntimeRegistry<AgentSignalSource>();
+
+ sourceRegistry.register('source.user.message', {
+ async handle(_source, context) {
+ expect(context.scopeKey).toBe('topic:topic-1');
+
+ return {
+ pending: { lane: 'user-feedback' },
+ status: 'wait',
+ } as const;
+ },
+ id: 'source-handler',
+ });
+
+ const runtime = new AgentSignalScheduler({
+ actionRegistry,
+ backend,
+ signalRegistry,
+ sourceRegistry,
+ });
+
+ const result = await runtime.emit({
+ payload: { message: 'remember this later' },
+ scope: { topicId: 'topic-1', userId: 'user-1' },
+ sourceType: 'source.user.message',
+ });
+
+ expect(result).toEqual({
+ pending: { lane: 'user-feedback' },
+ status: 'wait',
+ });
+ });
+
+ /**
+ * @example
+ * const result = await runtime.emit({
+ * payload: { message: 'remember this later' },
+ * scope: { topicId: 'topic-1', userId: 'user-1' },
+ * sourceType: 'source.user.message',
+ * });
+ *
+ * expect(result.status).toBe('wait');
+ * expect(handled).toContain('signal:signal.memory.request:topic:topic-1');
+ */
+ it('drains already-queued work before returning a terminal result', async () => {
+ const backend = createRuntimeBackend();
+ const actionRegistry = createRuntimeRegistry<BaseAction>();
+ const signalRegistry = createRuntimeRegistry<BaseSignal>();
+ const sourceRegistry = createRuntimeRegistry<AgentSignalSource>();
+ const handled: string[] = [];
+
+ sourceRegistry.register('source.user.message', {
+ async handle(source, context) {
+ handled.push(`source:dispatch:${context.scopeKey}`);
+
+ return {
+ signals: [
+ createSignal({
+ payload: { message: source.payload.message as string },
+ signalType: 'signal.memory.request',
+ source,
+ }),
+ ],
+ status: 'dispatch',
+ } as const;
+ },
+ id: 'source-dispatch-handler',
+ });
+
+ sourceRegistry.register('source.user.message', {
+ async handle(_source, context) {
+ handled.push(`source:wait:${context.scopeKey}`);
+
+ return {
+ pending: { lane: 'user-feedback' },
+ status: 'wait',
+ } as const;
+ },
+ id: 'source-wait-handler',
+ });
+
+ signalRegistry.register('signal.memory.request', {
+ async handle(signal, context) {
+ handled.push(`signal:${signal.signalType}:${context.scopeKey}`);
+ },
+ id: 'signal-handler',
+ });
+
+ const runtime = new AgentSignalScheduler({
+ actionRegistry,
+ backend,
+ signalRegistry,
+ sourceRegistry,
+ });
+
+ const result = await runtime.emit({
+ payload: { message: 'remember this later' },
+ scope: { topicId: 'topic-1', userId: 'user-1' },
+ sourceType: 'source.user.message',
+ });
+
+ expect(result).toEqual({
+ pending: { lane: 'user-feedback' },
+ status: 'wait',
+ });
+ expect(handled).toEqual([
+ 'source:dispatch:topic:topic-1',
+ 'source:wait:topic:topic-1',
+ 'signal:signal.memory.request:topic:topic-1',
+ ]);
+ });
+
+ /**
+ * @example
+ * const result = await runtime.emit({
+ * payload: { message: 'remember this' },
+ * scope: { topicId: 'topic-1', userId: 'user-1' },
+ * sourceType: 'source.user.message',
+ * });
+ *
+ * expect(result.status).toBe('completed');
+ * expect(result.trace.results).toHaveLength(3);
+ */
+ it('bridges executor-style action results into trace results and action-result signals', async () => {
+ const backend = createRuntimeBackend();
+ const actionRegistry = createRuntimeRegistry<BaseAction>();
+ const signalRegistry = createRuntimeRegistry<BaseSignal>();
+ const sourceRegistry = createRuntimeRegistry<AgentSignalSource>();
+
+ sourceRegistry.register('source.user.message', {
+ async handle(source) {
+ return {
+ signals: [
+ createSignal({
+ payload: { message: source.payload.message as string },
+ signalType: 'signal.memory.request',
+ source,
+ }),
+ ],
+ status: 'dispatch',
+ } as const;
+ },
+ id: 'source-handler',
+ });
+
+ signalRegistry.register('signal.memory.request', {
+ async handle(signal) {
+ return {
+ actions: [
+ createAction({
+ actionType: 'action.memory.persist',
+ payload: { outcome: 'applied' },
+ signal,
+ }),
+ createAction({
+ actionType: 'action.memory.persist',
+ payload: { outcome: 'skipped' },
+ signal,
+ }),
+ createAction({
+ actionType: 'action.memory.persist',
+ payload: { outcome: 'failed' },
+ signal,
+ }),
+ ],
+ status: 'dispatch',
+ } as const;
+ },
+ id: 'signal-handler',
+ });
+
+ actionRegistry.register('action.memory.persist', {
+ async handle(action) {
+ const startedAt = 1_000;
+ const outcome = action.payload.outcome;
+
+ if (outcome === 'failed') {
+ return {
+ actionId: action.actionId,
+ attempt: { current: 1, startedAt, status: 'failed' },
+ error: { code: 'memory_failed', message: 'boom' },
+ status: 'failed',
+ } as const;
+ }
+
+ if (outcome === 'skipped') {
+ return {
+ actionId: action.actionId,
+ attempt: { current: 1, startedAt, status: 'skipped' },
+ status: 'skipped',
+ } as const;
+ }
+
+ return {
+ actionId: action.actionId,
+ attempt: { current: 1, startedAt, status: 'succeeded' },
+ status: 'applied',
+ } as const;
+ },
+ id: 'action-handler',
+ });
+
+ const runtime = new AgentSignalScheduler({
+ actionRegistry,
+ backend,
+ signalRegistry,
+ sourceRegistry,
+ });
+
+ const result = await runtime.emit({
+ payload: { message: 'remember this' },
+ scope: { topicId: 'topic-1', userId: 'user-1' },
+ sourceType: 'source.user.message',
+ });
+
+ expect(result.status).toBe('completed');
+ if (result.status !== 'completed') {
+ throw new Error('Expected completed runtime result');
+ }
+
+ expect(result.trace.results.map((entry) => entry.status)).toEqual([
+ 'applied',
+ 'skipped',
+ 'failed',
+ ]);
+ expect(
+ result.trace.signals
+ .map((signal) => signal.signalType)
+ .filter((type) => type.startsWith('signal.action.')),
+ ).toEqual(['signal.action.applied', 'signal.action.skipped', 'signal.action.failed']);
+ });
+});
diff --git a/src/server/services/agentSignal/runtime/__tests__/config.test.ts b/src/server/services/agentSignal/runtime/__tests__/config.test.ts
new file mode 100644
index 00000000000..c57cae8f7f4
--- /dev/null
+++ b/src/server/services/agentSignal/runtime/__tests__/config.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveAgentSignalRuntimeConfig } from '../config';
+
+describe('agent signal runtime config', () => {
+ /**
+ * @example
+ * const config = resolveAgentSignalRuntimeConfig({
+ * enableAgentSignalRuntime: false,
+ * enableDurableRuntime: false,
+ * });
+ *
+ * expect(config.runtimeEnabled).toBe(false);
+ */
+ it('disables runtime emission when the backend env flag is off', () => {
+ const config = resolveAgentSignalRuntimeConfig({
+ enableAgentSignalRuntime: false,
+ enableDurableRuntime: false,
+ });
+
+ expect(config).toEqual({
+ backend: 'memory',
+ durableRuntimeEnabled: false,
+ runtimeEnabled: false,
+ });
+ });
+
+ /**
+ * @example
+ * const config = resolveAgentSignalRuntimeConfig({
+ * enableAgentSignalRuntime: true,
+ * enableDurableRuntime: true,
+ * });
+ *
+ * expect(config.durableRuntimeEnabled).toBe(true);
+ */
+ it('requires both flags before durable runtime is enabled', () => {
+ expect(
+ resolveAgentSignalRuntimeConfig({
+ enableAgentSignalRuntime: true,
+ enableDurableRuntime: false,
+ }),
+ ).toEqual({
+ backend: 'memory',
+ durableRuntimeEnabled: false,
+ runtimeEnabled: true,
+ });
+
+ expect(
+ resolveAgentSignalRuntimeConfig({
+ enableAgentSignalRuntime: true,
+ enableDurableRuntime: true,
+ }),
+ ).toEqual({
+ backend: 'memory',
+ durableRuntimeEnabled: true,
+ runtimeEnabled: true,
+ });
+ });
+});
diff --git a/src/server/services/agentSignal/runtime/__tests__/createRuntime.test.ts b/src/server/services/agentSignal/runtime/__tests__/createRuntime.test.ts
new file mode 100644
index 00000000000..368b381444a
--- /dev/null
+++ b/src/server/services/agentSignal/runtime/__tests__/createRuntime.test.ts
@@ -0,0 +1,200 @@
+import { createAction, createSignal } from '@lobechat/agent-signal';
+import { describe, expect, it, vi } from 'vitest';
+
+const loadCreateRuntime = async () => {
+ vi.resetModules();
+
+ const [runtimeModule, middlewareModule] = await Promise.all([
+ import('../AgentSignalRuntime'),
+ import('../middleware'),
+ ]);
+
+ return {
+ createAgentSignalRuntime: runtimeModule.createAgentSignalRuntime,
+ defineActionHandler: middlewareModule.defineActionHandler,
+ defineAgentSignalHandlers: middlewareModule.defineAgentSignalHandlers,
+ defineSignalHandler: middlewareModule.defineSignalHandler,
+ defineSourceHandler: middlewareModule.defineSourceHandler,
+ };
+};
+
+describe('createAgentSignalRuntime', () => {
+ /**
+ * @example
+ * const runtime = await createAgentSignalRuntime({
+ * policies: [defineAgentSignalHandlers([...])],
+ * });
+ *
+ * const result = await runtime.emit(sourceInput);
+ * expect(result.status).toBe('completed');
+ */
+ it('installs middleware-defined source, signal, and action handlers', async () => {
+ const {
+ createAgentSignalRuntime,
+ defineActionHandler,
+ defineAgentSignalHandlers,
+ defineSignalHandler,
+ defineSourceHandler,
+ } = await loadCreateRuntime();
+ const handled: string[] = [];
+
+ const runtime = await createAgentSignalRuntime({
+ policies: [
+ defineAgentSignalHandlers([
+ defineSourceHandler('source.user.message', {
+ async handle(source, context) {
+ handled.push(`source:${context.scopeKey}`);
+
+ return {
+ signals: [
+ createSignal({
+ payload: { text: source.payload.text as string },
+ signalType: 'signal.memory.request',
+ source,
+ }),
+ ],
+ status: 'dispatch',
+ } as const;
+ },
+ id: 'test-source-handler',
+ }),
+ defineSignalHandler('signal.memory.request', {
+ async handle(signal, context) {
+ handled.push(`signal:${context.scopeKey}`);
+
+ return {
+ actions: [
+ createAction({
+ actionType: 'action.memory.persist',
+ payload: { text: signal.payload.text as string },
+ signal,
+ }),
+ ],
+ status: 'dispatch',
+ } as const;
+ },
+ id: 'test-signal-handler',
+ }),
+ defineActionHandler('action.memory.persist', {
+ async handle(action, context) {
+ handled.push(`action:${context.scopeKey}`);
+
+ return {
+ actionId: action.actionId,
+ attempt: { completedAt: 3, current: 1, startedAt: 1, status: 'succeeded' },
+ detail: action.payload.text as string,
+ status: 'applied',
+ } as const;
+ },
+ id: 'test-action-handler',
+ }),
+ ]),
+ ],
+ });
+
+ const result = await runtime.emit({
+ payload: { text: 'remember this' },
+ scope: {
+ topicId: 'topic_1',
+ userId: 'user_1',
+ },
+ sourceType: 'source.user.message',
+ timestamp: 1_710_000_000_000,
+ });
+
+ expect(result.status).toBe('completed');
+ if (result.status !== 'completed') throw new Error('expected completed runtime result');
+
+ expect(handled).toEqual([
+ 'source:topic:topic_1',
+ 'signal:topic:topic_1',
+ 'action:topic:topic_1',
+ ]);
+ expect(result.trace.actions.map((item) => item.actionType)).toEqual(['action.memory.persist']);
+ expect(result.trace.results.map((item) => item.status)).toEqual(['applied']);
+ });
+
+ /**
+ * @example
+ * const runtime = await createAgentSignalRuntime();
+ *
+ * expect(runtime.runtimeConfig.backend).toBe('memory');
+ */
+ it('defaults to the in-memory durable backend without requiring default policies', async () => {
+ const { createAgentSignalRuntime } = await loadCreateRuntime();
+ const runtime = await createAgentSignalRuntime();
+
+ expect(runtime.runtimeConfig).toEqual({
+ backend: 'memory',
+ durableRuntimeEnabled: false,
+ runtimeEnabled: true,
+ });
+ expect(typeof runtime.durableBackend.claimPending).toBe('function');
+ expect(typeof runtime.durableBackend.complete).toBe('function');
+ expect(typeof runtime.durableBackend.fail).toBe('function');
+ expect(typeof runtime.durableBackend.scheduleNextHop).toBe('function');
+ });
+
+ /**
+ * @example
+ * const runtime = await createAgentSignalRuntime({ policies: [] });
+ *
+ * const result = await runtime.emit(sourceInput);
+ * expect(result.status).toBe('completed');
+ */
+ it('still emits successfully when no policies are installed', async () => {
+ const { createAgentSignalRuntime } = await loadCreateRuntime();
+ const runtime = await createAgentSignalRuntime({ policies: [] });
+
+ const result = await runtime.emit({
+ payload: { text: 'hello' },
+ scope: {
+ topicId: 'topic_1',
+ userId: 'user_1',
+ },
+ sourceType: 'source.user.message',
+ timestamp: 1_710_000_000_100,
+ });
+
+ expect(result.status).toBe('completed');
+ if (result.status !== 'completed') throw new Error('expected completed runtime result');
+ expect(result.trace.actions).toEqual([]);
+ expect(result.trace.results).toEqual([]);
+ expect(result.trace.signals).toEqual([]);
+ });
+
+ /**
+ * @example
+ * const runtime = await createAgentSignalRuntime({ durableBackend, policies: [] });
+ *
+ * expect(runtime.durableBackend).toBe(durableBackend);
+ */
+ it('uses an injected durable backend when provided', async () => {
+ const { createAgentSignalRuntime } = await loadCreateRuntime();
+ const durableBackend = {
+ appendToWaypoint: vi.fn().mockResolvedValue(undefined),
+ claimPending: vi.fn().mockResolvedValue(null),
+ complete: vi.fn().mockResolvedValue(undefined),
+ fail: vi.fn().mockResolvedValue(undefined),
+ loadWaypoint: vi.fn().mockResolvedValue({ events: [], scopeKey: 'topic:1' }),
+ scheduleNextHop: vi.fn().mockResolvedValue(undefined),
+ };
+
+ const runtime = await createAgentSignalRuntime({
+ durableBackend,
+ policies: [],
+ });
+
+ expect(runtime.durableBackend).toBe(durableBackend);
+ await runtime.emit({
+ payload: { text: 'hello' },
+ scope: {
+ topicId: 'topic_1',
+ userId: 'user_1',
+ },
+ sourceType: 'source.user.message',
+ timestamp: 1_710_000_000_300,
+ });
+ expect(durableBackend.appendToWaypoint).toHaveBeenCalled();
+ });
+});
diff --git a/src/server/services/agentSignal/runtime/__tests__/guards.test.ts b/src/server/services/agentSignal/runtime/__tests__/guards.test.ts
new file mode 100644
index 00000000000..3aed412b030
--- /dev/null
+++ b/src/server/services/agentSignal/runtime/__tests__/guards.test.ts
@@ -0,0 +1,202 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { RuntimeBackend } from '../context';
+import { createRuntimeProcessorContext } from '../context';
+import { debounce, outerTimeout, throttle } from '../guards';
+
+interface TestGuardState {
+ lastEventAt?: number;
+ startedAt?: number;
+}
+
+const createRuntimeBackend = (): RuntimeBackend => {
+ const state = new Map<string, TestGuardState>();
+
+ return {
+ async appendToWaypoint() {},
+ async getGuardState(scopeKey: string, lane: string) {
+ return state.get(`${scopeKey}:${lane}`) ?? {};
+ },
+ async loadWaypoint() {
+ return {};
+ },
+ async touchGuardState(scopeKey: string, lane: string, now: number) {
+ const key = `${scopeKey}:${lane}`;
+ const current = state.get(key) ?? {};
+ const next = {
+ lastEventAt: now,
+ startedAt: current.startedAt ?? now,
+ } satisfies TestGuardState;
+
+ state.set(key, next);
+
+ return next;
+ },
+ };
+};
+
+describe('runtime timing guards', () => {
+ /**
+ * @example
+ * const first = await debounce(ctx, { lane: 'user-feedback', ms: 1500 });
+ * const second = await debounce(ctx, { lane: 'user-feedback', ms: 1500 });
+ *
+ * expect(first.ok).toBe(true);
+ * expect(second.wait().status).toBe('wait');
+ */
+ it('returns a wait result when debounce window is still active', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(1_000);
+
+ const ctx = createRuntimeProcessorContext({
+ backend: createRuntimeBackend(),
+ scopeKey: 'topic:topic-1',
+ });
+
+ const first = await debounce(ctx, { lane: 'user-feedback', ms: 1_500 });
+ const second = await debounce(ctx, { lane: 'user-feedback', ms: 1_500 });
+
+ expect(first.ok).toBe(true);
+ expect(second.ok).toBe(false);
+ expect(second.delayMs).toBe(1_500);
+ expect(second.wait().status).toBe('wait');
+
+ vi.useRealTimers();
+ });
+
+ /**
+ * @example
+ * const first = await debounce(ctx, { lane: 'user-feedback', ms: 1000 });
+ * vi.setSystemTime(1800);
+ * const second = await debounce(ctx, { lane: 'user-feedback', ms: 1000 });
+ * vi.setSystemTime(2600);
+ * const third = await debounce(ctx, { lane: 'user-feedback', ms: 1000 });
+ * vi.setSystemTime(3601);
+ * const fourth = await debounce(ctx, { lane: 'user-feedback', ms: 1000 });
+ *
+ * expect(second.delayMs).toBe(1000);
+ * expect(third.delayMs).toBe(1000);
+ * expect(fourth.ok).toBe(true);
+ */
+ it('extends the debounce quiet window after each incoming event', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(1_000);
+
+ const ctx = createRuntimeProcessorContext({
+ backend: createRuntimeBackend(),
+ scopeKey: 'topic:topic-1',
+ });
+
+ const first = await debounce(ctx, { lane: 'user-feedback', ms: 1_000 });
+
+ vi.setSystemTime(1_800);
+
+ const second = await debounce(ctx, { lane: 'user-feedback', ms: 1_000 });
+
+ vi.setSystemTime(2_600);
+
+ const third = await debounce(ctx, { lane: 'user-feedback', ms: 1_000 });
+
+ vi.setSystemTime(3_601);
+
+ const fourth = await debounce(ctx, { lane: 'user-feedback', ms: 1_000 });
+
+ expect(first.ok).toBe(true);
+ expect(second.ok).toBe(false);
+ expect(second.delayMs).toBe(1_000);
+ expect(third.ok).toBe(false);
+ expect(third.delayMs).toBe(1_000);
+ expect(fourth.ok).toBe(true);
+
+ vi.useRealTimers();
+ });
+
+ /**
+ * @example
+ * const first = await throttle(ctx, { lane: 'memory-write', ms: 500 });
+ * const second = await throttle(ctx, { lane: 'memory-write', ms: 500 });
+ *
+ * expect(first.ok).toBe(true);
+ * expect(second.reason).toBe('throttled');
+ */
+ it('keeps throttle state scoped to one runtime scope key', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(2_000);
+
+ const backend = createRuntimeBackend();
+ const firstScope = createRuntimeProcessorContext({ backend, scopeKey: 'topic:one' });
+ const secondScope = createRuntimeProcessorContext({ backend, scopeKey: 'topic:two' });
+
+ const first = await throttle(firstScope, { lane: 'memory-write', ms: 500 });
+ const second = await throttle(firstScope, { lane: 'memory-write', ms: 500 });
+ const isolated = await throttle(secondScope, { lane: 'memory-write', ms: 500 });
+
+ expect(first.ok).toBe(true);
+ expect(second.ok).toBe(false);
+ expect(second.reason).toBe('throttled');
+ expect(isolated.ok).toBe(true);
+
+ vi.useRealTimers();
+ });
+
+ /**
+ * @example
+ * const timeout = await outerTimeout(ctx, { lane: 'user-feedback', ms: 1000 });
+ * const debounceCheck = await debounce(ctx, { lane: 'user-feedback', ms: 1500 });
+ * const throttleCheck = await throttle(ctx, { lane: 'user-feedback', ms: 500 });
+ *
+ * expect(timeout.ok).toBe(true);
+ * expect(debounceCheck.ok).toBe(true);
+ * expect(throttleCheck.ok).toBe(true);
+ */
+ it('keeps timeout, debounce, and throttle state isolated for one outward lane', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(3_000);
+
+ const ctx = createRuntimeProcessorContext({
+ backend: createRuntimeBackend(),
+ scopeKey: 'topic:topic-1',
+ });
+
+ const timeout = await outerTimeout(ctx, { lane: 'user-feedback', ms: 15 * 60 * 1000 });
+ const debounceCheck = await debounce(ctx, { lane: 'user-feedback', ms: 1_500 });
+ const throttleCheck = await throttle(ctx, { lane: 'user-feedback', ms: 500 });
+
+ expect(timeout.ok).toBe(true);
+ expect(debounceCheck.ok).toBe(true);
+ expect(throttleCheck.ok).toBe(true);
+
+ vi.useRealTimers();
+ });
+
+ /**
+ * @example
+ * const first = await outerTimeout(ctx, { lane: 'workflow', ms: 1000 });
+ * vi.setSystemTime(6500);
+ * const second = await outerTimeout(ctx, { lane: 'workflow', ms: 1000 });
+ *
+ * expect(second.wait().status).toBe('conclude');
+ */
+ it('concludes once the outer timeout window has elapsed', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(5_000);
+
+ const ctx = createRuntimeProcessorContext({
+ backend: createRuntimeBackend(),
+ scopeKey: 'topic:topic-1',
+ });
+
+ const first = await outerTimeout(ctx, { lane: 'workflow', ms: 1_000 });
+
+ vi.setSystemTime(6_500);
+
+ const second = await outerTimeout(ctx, { lane: 'workflow', ms: 1_000 });
+
+ expect(first.ok).toBe(true);
+ expect(second.ok).toBe(false);
+ expect(second.reason).toBe('timed_out');
+ expect(second.wait().status).toBe('conclude');
+
+ vi.useRealTimers();
+ });
+});
diff --git a/src/server/services/agentSignal/runtime/backend/redisGuard.ts b/src/server/services/agentSignal/runtime/backend/redisGuard.ts
new file mode 100644
index 00000000000..e4ca362d859
--- /dev/null
+++ b/src/server/services/agentSignal/runtime/backend/redisGuard.ts
@@ -0,0 +1,68 @@
+import { AGENT_SIGNAL_DEFAULTS } from '../../constants';
+import { redisPolicyStateStore } from '../../store/adapters/redis/policyStateStore';
+import type { AgentSignalPolicyStateStore } from '../../store/types';
+import type { RuntimeGuardBackend, RuntimeGuardState } from '../AgentSignalRuntime';
+
+const RUNTIME_GUARD_POLICY_PREFIX = 'runtime-guard';
+
+const createRuntimeGuardPolicyId = (lane: string) => {
+ return `${RUNTIME_GUARD_POLICY_PREFIX}:${lane}`;
+};
+
+const fromPersistedGuardState = (value?: Record<string, string>): RuntimeGuardState => {
+ if (!value) return {};
+
+ return {
+ lastEventAt: typeof value.lastEventAt === 'string' ? Number(value.lastEventAt) : undefined,
+ startedAt: typeof value.startedAt === 'string' ? Number(value.startedAt) : undefined,
+ };
+};
+
+const toPersistedGuardState = (state: RuntimeGuardState): Record<string, string> => {
+ return {
+ ...(state.lastEventAt !== undefined && { lastEventAt: String(state.lastEventAt) }),
+ ...(state.startedAt !== undefined && { startedAt: String(state.startedAt) }),
+ };
+};
+
+/**
+ * Creates a Redis-backed runtime guard backend.
+ *
+ * Use when:
+ * - AgentSignal execution runs in separate Upstash workflow invocations
+ * - debounce/throttle/outer-timeout guards must survive process boundaries
+ *
+ * Expects:
+ * - `stateStore` persists small hash snapshots per lane and scope
+ *
+ * Returns:
+ * - A runtime guard backend compatible with {@link createAgentSignalRuntime}
+ */
+export const createRedisRuntimeGuardBackend = (
+ stateStore: AgentSignalPolicyStateStore = redisPolicyStateStore,
+): RuntimeGuardBackend => {
+ return {
+ async getGuardState(scopeKey, lane) {
+ return fromPersistedGuardState(
+ await stateStore.readPolicyState(createRuntimeGuardPolicyId(lane), scopeKey),
+ );
+ },
+ async touchGuardState(scopeKey, lane, now) {
+ const policyId = createRuntimeGuardPolicyId(lane);
+ const current = fromPersistedGuardState(await stateStore.readPolicyState(policyId, scopeKey));
+ const next = {
+ lastEventAt: now,
+ startedAt: current.startedAt ?? now,
+ } satisfies RuntimeGuardState;
+
+ await stateStore.writePolicyState(
+ policyId,
+ scopeKey,
+ toPersistedGuardState(next),
+ AGENT_SIGNAL_DEFAULTS.runtimeGuardTtlSeconds,
+ );
+
+ return next;
+ },
+ };
+};
diff --git a/src/server/services/agentSignal/runtime/backend/types.ts b/src/server/services/agentSignal/runtime/backend/types.ts
new file mode 100644
index 00000000000..b3830862f34
--- /dev/null
+++ b/src/server/services/agentSignal/runtime/backend/types.ts
@@ -0,0 +1,82 @@
+import type { AgentSignalSource, ExecutorError } from '@lobechat/agent-signal';
+
+/** Completed waypoint state for one runtime scope. */
+export interface RuntimeCompletedWaypointState {
+ completedAt?: number;
+ sourceId: string;
+ status: 'completed';
+}
+
+/** Failed waypoint state for one runtime scope. */
+export interface RuntimeFailedWaypointState {
+ error: ExecutorError;
+ failedAt?: number;
+ sourceId: string;
+ status: 'failed';
+}
+
+/** Terminal waypoint state for one runtime scope. */
+export type RuntimeTerminalState = RuntimeCompletedWaypointState | RuntimeFailedWaypointState;
+
+/** Pending source claim for one runtime scope. */
+export interface RuntimePendingClaim {
+ scopeKey: string;
+ source: AgentSignalSource;
+ status: 'pending';
+}
+
+/** Scheduled next-hop metadata for one runtime scope. */
+export interface RuntimeNextHop {
+ payload?: Record<string, unknown>;
+ runAt: number;
+ scopeKey: string;
+}
+
+/** Persisted waypoint snapshot for one runtime scope. */
+export interface RuntimeWaypoint {
+ events: AgentSignalSource[];
+ nextHop?: RuntimeNextHop;
+ pending?: RuntimePendingClaim;
+ scopeKey: string;
+ terminal?: RuntimeTerminalState;
+}
+
+/** Input for marking one source as completed. */
+export interface RuntimeCompletionInput {
+ completedAt?: number;
+ scopeKey: string;
+ sourceId: string;
+}
+
+/** Input for marking one source as failed. */
+export interface RuntimeFailureInput {
+ error: ExecutorError;
+ failedAt?: number;
+ scopeKey: string;
+ sourceId: string;
+}
+
+/** Runtime backend contract for durable waypoint processing. */
+export interface AgentSignalRuntimeBackend {
+ appendToWaypoint: (scopeKey: string, source: AgentSignalSource) => Promise<void>;
+ claimPending: (scopeKey: string) => Promise<RuntimePendingClaim | null>;
+ complete: (input: RuntimeCompletionInput) => Promise<void>;
+ fail: (input: RuntimeFailureInput) => Promise<void>;
+ loadWaypoint: (scopeKey: string) => Promise<RuntimeWaypoint>;
+ scheduleNextHop: (input: RuntimeNextHop) => Promise<void>;
+}
+
+/** Storage adapter used by durable AgentSignal runtime backends. */
+export interface AgentSignalRuntimeBackendStore {
+ append: (scopeKey: string, source: AgentSignalSource) => Promise<void>;
+ claim: (scopeKey: string) => Promise<RuntimePendingClaim | null>;
+ complete: (input: RuntimeCompletionInput) => Promise<void>;
+ fail: (input: RuntimeFailureInput) => Promise<void>;
+ load: (scopeKey: string) => Promise<RuntimeWaypoint>;
+ schedule?: (input: RuntimeNextHop) => Promise<void>;
+}
+
+/** Scheduling adapter used by durable AgentSignal runtime backends. */
+export interface AgentSignalRuntimeScheduler {
+ schedule: (input: RuntimeNextHop) => Promise<void>;
+}
diff --git a/src/server/services/agentSignal/runtime/config.ts b/src/server/services/agentSignal/runtime/config.ts
new file mode 100644
index 00000000000..2ec824d5109
--- /dev/null
+++ b/src/server/services/agentSignal/runtime/config.ts
@@ -0,0 +1,39 @@
+import { AGENT_SIGNAL_RUNTIME_BACKENDS } from '../constants';
+
+/** Inputs used to resolve the runtime backend configuration. */
+export interface ResolveAgentSignalRuntimeConfigOptions {
+ enableAgentSignalRuntime: boolean;
+ enableDurableRuntime: boolean;
+}
+
+/** Resolved configuration for the AgentSignal runtime host. */
+export interface AgentSignalRuntimeConfig {
+ backend: (typeof AGENT_SIGNAL_RUNTIME_BACKENDS)[keyof typeof AGENT_SIGNAL_RUNTIME_BACKENDS];
+ durableRuntimeEnabled: boolean;
+ runtimeEnabled: boolean;
+}
+
+/**
+ * Resolves the AgentSignal runtime configuration.
+ *
+ * Use when:
+ * - Callers need the normalized runtime feature flags
+ * - The runtime should always target the local in-memory backend surface
+ *
+ * Expects:
+ * - Feature flags are already parsed into booleans
+ *
+ * Returns:
+ * - A normalized config object with the memory backend selected
+ */
+export const resolveAgentSignalRuntimeConfig = (
+ input: ResolveAgentSignalRuntimeConfigOptions,
+): AgentSignalRuntimeConfig => {
+ const runtimeEnabled = input.enableAgentSignalRuntime;
+
+ return {
+ backend: AGENT_SIGNAL_RUNTIME_BACKENDS.memory,
+ durableRuntimeEnabled: runtimeEnabled && input.enableDurableRuntime,
+ runtimeEnabled,
+ };
+};
diff --git a/src/server/services/agentSignal/runtime/context.ts b/src/server/services/agentSignal/runtime/context.ts
new file mode 100644
index 00000000000..3d45dcd5328
--- /dev/null
+++ b/src/server/services/agentSignal/runtime/context.ts
@@ -0,0 +1,64 @@
+import type { AgentSignalSource, BaseAction, BaseSignal } from '@lobechat/agent-signal';
+
+/** One persisted guard lane inside a runtime scope. */
+export interface RuntimeGuardState {
+ lastEventAt?: number;
+ startedAt?: number;
+}
+
+/** Deferred work persisted for one runtime scope. */
+export interface RuntimeWaypoint {
+ trigger?: RuntimeNode;
+}
+
+/** Runtime node handled by the generalized runtime host. */
+export type RuntimeNode = AgentSignalSource | BaseAction | BaseSignal;
+
+/** Backend operations needed by the generalized runtime host. */
+export interface RuntimeBackend {
+ appendToWaypoint: (scopeKey: string, source: AgentSignalSource) => Promise<void>;
+ getGuardState: (scopeKey: string, lane: string) => Promise<RuntimeGuardState | undefined>;
+ loadWaypoint: (scopeKey: string) => Promise<RuntimeWaypoint>;
+ touchGuardState: (scopeKey: string, lane: string, now: number) => Promise<RuntimeGuardState>;
+}
+
+/** Scope-bound state helpers exposed to runtime handlers and guards. */
+export interface RuntimeScopedState {
+ getGuardState: (lane: string) => Promise<RuntimeGuardState>;
+ touchGuardState: (lane: string, now?: number) => Promise<RuntimeGuardState>;
+}
+
+/** Runtime handler context shared across one queue execution. */
+export interface RuntimeProcessorContext {
+ now: () => number;
+ runtimeState: RuntimeScopedState;
+ scopeKey: string;
+}
+
+/** Options for creating a scope-bound runtime processor context. */
+export interface CreateRuntimeProcessorContextOptions {
+ backend: Pick<RuntimeBackend, 'getGuardState' | 'touchGuardState'>;
+ now?: () => number;
+ scopeKey: string;
+}
+
+/** Creates one scope-bound runtime processor context. */
+export const createRuntimeProcessorContext = (
+ input: CreateRuntimeProcessorContextOptions,
+): RuntimeProcessorContext => {
+ const { backend, scopeKey } = input;
+ const now = input.now ?? (() => Date.now());
+
+ return {
+ now,
+ runtimeState: {
+ async getGuardState(lane) {
+ return (await backend.getGuardState(scopeKey, lane)) ?? {};
+ },
+ async touchGuardState(lane, currentTime = now()) {
+ return backend.touchGuardState(scopeKey, lane, currentTime);
+ },
+ },
+ scopeKey,
+ };
+};
diff --git a/src/server/services/agentSignal/runtime/guards.ts b/src/server/services/agentSignal/runtime/guards.ts
new file mode 100644
index 00000000000..41f4b4d759e
--- /dev/null
+++ b/src/server/services/agentSignal/runtime/guards.ts
@@ -0,0 +1,148 @@
+import type { RuntimeGuardResult, RuntimeProcessorResult } from '@lobechat/agent-signal';
+
+import type { RuntimeProcessorContext } from './context';
+
+/** Timing-guard input shared by the generalized runtime helpers. */
+export interface RuntimeTimingGuardInput {
+ lane: string;
+ ms: number;
+}
+
+type RuntimeTimingGuardPhase = 'debounce' | 'throttle' | 'outer-timeout';
+
+/**
+ * Derives one phase-specific storage key from the public lane name.
+ *
+ * Before:
+ * - `user-feedback`
+ *
+ * After:
+ * - `user-feedback::debounce`
+ */
+const createPhaseScopedLane = (lane: string, phase: RuntimeTimingGuardPhase): string => {
+ return `${lane}::${phase}`;
+};
+
+const createReadyResult = (): RuntimeGuardResult => {
+ return {
+ ok: true,
+ reason: 'ready',
+ wait: () => ({ status: 'wait' }),
+ };
+};
+
+const createWaitResult = (
+ input: RuntimeTimingGuardInput & {
+ delayMs: number;
+ reason: 'debounced' | 'throttled';
+ },
+): RuntimeGuardResult => {
+ return {
+ delayMs: input.delayMs,
+ ok: false,
+ reason: input.reason,
+ wait: () =>
+ ({
+ pending: { lane: input.lane, reason: input.reason },
+ status: 'wait',
+ }) satisfies RuntimeProcessorResult,
+ };
+};
+
+const createConcludeResult = (
+ input: RuntimeTimingGuardInput & {
+ elapsedMs: number;
+ reason: 'timed_out';
+ },
+): RuntimeGuardResult => {
+ return {
+ ok: false,
+ reason: input.reason,
+ wait: () =>
+ ({
+ concluded: {
+ elapsedMs: input.elapsedMs,
+ lane: input.lane,
+ reason: input.reason,
+ timeoutMs: input.ms,
+ },
+ status: 'conclude',
+ }) satisfies RuntimeProcessorResult,
+ };
+};
+
+/** Debounces one lane inside the current runtime scope. */
+export const debounce = async (
+ ctx: RuntimeProcessorContext,
+ input: RuntimeTimingGuardInput,
+): Promise<RuntimeGuardResult> => {
+ const lane = createPhaseScopedLane(input.lane, 'debounce');
+ const state = await ctx.runtimeState.getGuardState(lane);
+ const now = ctx.now();
+ const elapsed = now - (state.lastEventAt ?? 0);
+
+ if (state.lastEventAt && elapsed < input.ms) {
+ await ctx.runtimeState.touchGuardState(lane, now);
+
+ return createWaitResult({
+ ...input,
+ delayMs: input.ms,
+ reason: 'debounced',
+ });
+ }
+
+ await ctx.runtimeState.touchGuardState(lane, now);
+
+ return createReadyResult();
+};
+
+/** Throttles one lane inside the current runtime scope. */
+export const throttle = async (
+ ctx: RuntimeProcessorContext,
+ input: RuntimeTimingGuardInput,
+): Promise<RuntimeGuardResult> => {
+ const lane = createPhaseScopedLane(input.lane, 'throttle');
+ const state = await ctx.runtimeState.getGuardState(lane);
+ const now = ctx.now();
+ const elapsed = now - (state.lastEventAt ?? 0);
+
+ if (state.lastEventAt && elapsed < input.ms) {
+ return createWaitResult({
+ ...input,
+ delayMs: input.ms - elapsed,
+ reason: 'throttled',
+ });
+ }
+
+ await ctx.runtimeState.touchGuardState(lane, now);
+
+ return createReadyResult();
+};
+
+/** Enforces an outer timeout for one scoped lane. */
+export const outerTimeout = async (
+ ctx: RuntimeProcessorContext,
+ input: RuntimeTimingGuardInput,
+): Promise<RuntimeGuardResult> => {
+ const lane = createPhaseScopedLane(input.lane, 'outer-timeout');
+ const state = await ctx.runtimeState.getGuardState(lane);
+ const now = ctx.now();
+
+ if (typeof state.startedAt !== 'number') {
+ await ctx.runtimeState.touchGuardState(lane, now);
+
+ return createReadyResult();
+ }
+
+ const elapsed = now - state.startedAt;
+
+ if (elapsed >= input.ms) {
+ return createConcludeResult({
+ ...input,
+ elapsedMs: elapsed,
+ reason: 'timed_out',
+ });
+ }
+
+ return createReadyResult();
+};
diff --git a/src/server/services/agentSignal/runtime/middleware.ts b/src/server/services/agentSignal/runtime/middleware.ts
new file mode 100644
index 00000000000..38b44fe1162
--- /dev/null
+++ b/src/server/services/agentSignal/runtime/middleware.ts
@@ -0,0 +1,126 @@
+import type { AgentSignalSource, BaseAction, BaseSignal } from '@lobechat/agent-signal';
+
+import type {
+ AgentSignalSchedulerHandler,
+ AgentSignalSchedulerRegistry,
+} from './AgentSignalScheduler';
+
+export interface AgentSignalSourceHandlerDefinition {
+ handler: AgentSignalSchedulerHandler<AgentSignalSource>;
+ listen: string | string[];
+ type: 'source';
+}
+
+export interface AgentSignalSignalHandlerDefinition {
+ handler: AgentSignalSchedulerHandler<BaseSignal>;
+ listen: string | string[];
+ type: 'signal';
+}
+
+export interface AgentSignalActionHandlerDefinition {
+ handler: AgentSignalSchedulerHandler<BaseAction>;
+ listen: string | string[];
+ type: 'action';
+}
+
+export type AgentSignalHandlerDefinition =
+ | AgentSignalActionHandlerDefinition
+ | AgentSignalSignalHandlerDefinition
+ | AgentSignalSourceHandlerDefinition;
+
+export interface AgentSignalMiddlewareInstallContext {
+ handleAction: (handler: AgentSignalActionHandlerDefinition) => void;
+ handleSignal: (handler: AgentSignalSignalHandlerDefinition) => void;
+ handleSource: (handler: AgentSignalSourceHandlerDefinition) => void;
+}
+
+export interface AgentSignalMiddleware {
+ install: (context: AgentSignalMiddlewareInstallContext) => Promise<void> | void;
+}
+
+export interface AgentSignalMiddlewareRegistries {
+ actionRegistry: AgentSignalSchedulerRegistry<BaseAction>;
+ signalRegistry: AgentSignalSchedulerRegistry<BaseSignal>;
+ sourceRegistry: AgentSignalSchedulerRegistry<AgentSignalSource>;
+}
+
+const toListenArray = (listen: string | string[]) => {
+ return Array.isArray(listen) ? listen : [listen];
+};
+
+export const defineSourceHandler = (
+ listen: string | string[],
+ handler: AgentSignalSchedulerHandler<AgentSignalSource>,
+): AgentSignalSourceHandlerDefinition => {
+ return {
+ handler,
+ listen,
+ type: 'source',
+ };
+};
+
+export const defineSignalHandler = (
+ listen: string | string[],
+ handler: AgentSignalSchedulerHandler<BaseSignal>,
+): AgentSignalSignalHandlerDefinition => {
+ return {
+ handler,
+ listen,
+ type: 'signal',
+ };
+};
+
+export const defineActionHandler = (
+ listen: string | string[],
+ handler: AgentSignalSchedulerHandler<BaseAction>,
+): AgentSignalActionHandlerDefinition => {
+ return {
+ handler,
+ listen,
+ type: 'action',
+ };
+};
+
+export const defineAgentSignalHandlers = (
+ handlers: AgentSignalHandlerDefinition[],
+): AgentSignalMiddleware => {
+ return {
+ install(context) {
+ for (const handler of handlers) {
+ if (handler.type === 'source') {
+ context.handleSource(handler);
+ continue;
+ }
+
+ if (handler.type === 'signal') {
+ context.handleSignal(handler);
+ continue;
+ }
+
+ context.handleAction(handler);
+ }
+ },
+ };
+};
+
+export const createAgentSignalMiddlewareInstallContext = (
+ registries: AgentSignalMiddlewareRegistries,
+): AgentSignalMiddlewareInstallContext => {
+ return {
+ handleAction(handler) {
+ for (const listen of toListenArray(handler.listen)) {
+ registries.actionRegistry.register(listen, handler.handler);
+ }
+ },
+ handleSignal(handler) {
+ for (const listen of toListenArray(handler.listen)) {
+ registries.signalRegistry.register(listen, handler.handler);
+ }
+ },
+ handleSource(handler) {
+ for (const listen of toListenArray(handler.listen)) {
+ registries.sourceRegistry.register(listen, handler.handler);
+ }
+ },
+ };
+};
diff --git a/src/server/services/agentSignal/runtime/scope.ts b/src/server/services/agentSignal/runtime/scope.ts
new file mode 100644
index 00000000000..b89affbbc9c
--- /dev/null
+++ b/src/server/services/agentSignal/runtime/scope.ts
@@ -0,0 +1,23 @@
+import type { AgentSignalScope } from '@lobechat/agent-signal';
+
+import { type AgentSignalProducerScopeInput, AgentSignalScopeKey } from '../scopeKey';
+
+/** Resolves the canonical runtime scope key for one source scope. */
+export const resolveRuntimeScopeKey = (scope: AgentSignalScope) => {
+ return AgentSignalScopeKey.fromRuntimeScope(scope);
+};
+
+/**
+ * Resolves one stable scope key for producers that emit raw source envelopes.
+ *
+ * Before:
+ * - `{ topicId: 'topic-1' }`
+ * - `{ platform: 'wechat', applicationId: 'app', platformThreadId: 'thread-1' }`
+ *
+ * After:
+ * - `topic:topic-1`
+ * - `bot:wechat:app:thread-1`
+ */
+export const resolveProducerScopeKey = (input: AgentSignalProducerScopeInput) => {
+ return AgentSignalScopeKey.fromProducerInput(input);
+};
diff --git a/src/server/services/agentSignal/scopeKey.ts b/src/server/services/agentSignal/scopeKey.ts
new file mode 100644
index 00000000000..0816bedc993
--- /dev/null
+++ b/src/server/services/agentSignal/scopeKey.ts
@@ -0,0 +1,67 @@
+import type { AgentSignalScope } from '@lobechat/agent-signal';
+
+export interface AgentSignalBotScopeKeyInput {
+ applicationId: string;
+ platform: string;
+ platformThreadId: string;
+}
+
+export interface AgentSignalProducerScopeInput {
+ applicationId?: string;
+ platform?: string;
+ platformThreadId?: string;
+ topicId?: string;
+}
+
+export interface AgentSignalTaskScopeKeyInput {
+ taskId: string;
+}
+
+export interface AgentSignalTopicScopeKeyInput {
+ topicId: string;
+}
+
+export interface AgentSignalUserAgentScopeKeyInput {
+ agentId: string;
+ userId: string;
+}
+
+export interface AgentSignalUserScopeKeyInput {
+ userId: string;
+}
+
+const joinScopeKey = (prefix: string, ...parts: string[]) => `${prefix}:${parts.join(':')}`;
+
+/** Server-owned scope-key builders for the current AgentSignal routing model. */
+export const AgentSignalScopeKey = {
+ forAgentUser: (input: AgentSignalUserAgentScopeKeyInput) =>
+ joinScopeKey('agent', input.agentId, 'user', input.userId),
+ forBotThread: (input: AgentSignalBotScopeKeyInput) =>
+ joinScopeKey('bot', input.platform, input.applicationId, input.platformThreadId),
+ forTask: (input: AgentSignalTaskScopeKeyInput) => joinScopeKey('task', input.taskId),
+ forTopic: (input: AgentSignalTopicScopeKeyInput) => joinScopeKey('topic', input.topicId),
+ forUser: (input: AgentSignalUserScopeKeyInput) => joinScopeKey('user', input.userId),
+ fromProducerInput: (input: AgentSignalProducerScopeInput) => {
+ if (input.topicId) return AgentSignalScopeKey.forTopic({ topicId: input.topicId });
+
+ if (input.platform && input.applicationId && input.platformThreadId) {
+ return AgentSignalScopeKey.forBotThread({
+ applicationId: input.applicationId,
+ platform: input.platform,
+ platformThreadId: input.platformThreadId,
+ });
+ }
+
+ return 'fallback:global';
+ },
+ fromRuntimeScope: (scope: AgentSignalScope) => {
+ if (scope.topicId) return AgentSignalScopeKey.forTopic({ topicId: scope.topicId });
+ if (scope.botScopeKey) return scope.botScopeKey;
+ if (scope.taskId) return AgentSignalScopeKey.forTask({ taskId: scope.taskId });
+ if (scope.agentId) {
+ return AgentSignalScopeKey.forAgentUser({ agentId: scope.agentId, userId: scope.userId });
+ }
+
+ return AgentSignalScopeKey.forUser({ userId: scope.userId });
+ },
+} as const;
diff --git a/src/server/services/agentSignal/sourceTypes.ts b/src/server/services/agentSignal/sourceTypes.ts
new file mode 100644
index 00000000000..c1f94e0c060
--- /dev/null
+++ b/src/server/services/agentSignal/sourceTypes.ts
@@ -0,0 +1,194 @@
+import type { AgentSignalSource, BaseSource } from '@lobechat/agent-signal';
+
+/** Server-owned AgentSignal source type identifiers. */
+export const AGENT_SIGNAL_SOURCE_TYPES = {
+ agentExecutionCompleted: 'agent.execution.completed',
+ agentExecutionFailed: 'agent.execution.failed',
+ agentUserMessage: 'agent.user.message',
+ botMessageMerged: 'bot.message.merged',
+ clientGatewayError: 'client.gateway.error',
+ clientGatewayRuntimeEnd: 'client.gateway.runtime_end',
+ clientGatewayStepComplete: 'client.gateway.step_complete',
+ clientGatewayStreamStart: 'client.gateway.stream_start',
+ clientRuntimeComplete: 'client.runtime.complete',
+ clientRuntimeStart: 'client.runtime.start',
+ runtimeAfterStep: 'runtime.after_step',
+ runtimeBeforeStep: 'runtime.before_step',
+} as const;
+
+type ValueOf<TValue> = TValue[keyof TValue];
+
+/** Server-owned AgentSignal source type union. */
+export type AgentSignalSourceType = ValueOf<typeof AGENT_SIGNAL_SOURCE_TYPES>;
+
+/** Server-owned AgentSignal source payloads keyed by source type. */
+export interface AgentSignalSourcePayloadMap {
+ [AGENT_SIGNAL_SOURCE_TYPES.agentExecutionCompleted]: {
+ agentId?: string;
+ operationId: string;
+ serializedContext?: string;
+ steps: number;
+ topicId?: string;
+ turnCount?: number;
+ };
+ [AGENT_SIGNAL_SOURCE_TYPES.agentExecutionFailed]: {
+ agentId?: string;
+ errorMessage?: string;
+ operationId: string;
+ reason?: string;
+ serializedContext?: string;
+ topicId?: string;
+ turnCount?: number;
+ };
+ [AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage]: {
+ agentId?: string;
+ documentPayload?: Record<string, unknown>;
+ intents?: Array<'document' | 'memory' | 'persona' | 'prompt'>;
+ memoryPayload?: Record<string, unknown>;
+ message: string;
+ messageId: string;
+ serializedContext?: string;
+ threadId?: string;
+ topicId?: string;
+ trigger?: string;
+ };
+ [AGENT_SIGNAL_SOURCE_TYPES.botMessageMerged]: {
+ agentId?: string;
+ applicationId?: string;
+ message: string;
+ platform?: string;
+ platformThreadId?: string;
+ serializedContext?: string;
+ topicId?: string;
+ };
+ [AGENT_SIGNAL_SOURCE_TYPES.clientGatewayError]: {
+ agentId?: string;
+ errorMessage?: string;
+ operationId: string;
+ serializedContext?: string;
+ topicId?: string;
+ };
+ [AGENT_SIGNAL_SOURCE_TYPES.clientGatewayRuntimeEnd]: {
+ agentId?: string;
+ operationId: string;
+ serializedContext?: string;
+ topicId?: string;
+ };
+ [AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStepComplete]: {
+ agentId?: string;
+ operationId: string;
+ serializedContext?: string;
+ stepIndex: number;
+ topicId?: string;
+ };
+ [AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStreamStart]: {
+ agentId?: string;
+ operationId: string;
+ serializedContext?: string;
+ stepIndex: number;
+ topicId?: string;
+ };
+ [AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete]: {
+ agentId?: string;
+ operationId: string;
+ serializedContext?: string;
+ status?: string;
+ threadId?: string;
+ topicId?: string;
+ };
+ [AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart]: {
+ agentId?: string;
+ operationId: string;
+ parentMessageId?: string;
+ parentMessageType?: string;
+ serializedContext?: string;
+ threadId?: string;
+ topicId?: string;
+ };
+ [AGENT_SIGNAL_SOURCE_TYPES.runtimeAfterStep]: {
+ agentId?: string;
+ operationId: string;
+ serializedContext?: string;
+ stepIndex: number;
+ topicId?: string;
+ turnCount?: number;
+ };
+ [AGENT_SIGNAL_SOURCE_TYPES.runtimeBeforeStep]: {
+ agentId?: string;
+ operationId: string;
+ serializedContext?: string;
+ stepIndex: number;
+ topicId?: string;
+ turnCount?: number;
+ };
+}
+
+/** Server-owned AgentSignal source variant. */
+export type AgentSignalSourceVariant<
+ TSourceType extends AgentSignalSourceType = AgentSignalSourceType,
+> = BaseSource & {
+ payload: AgentSignalSourcePayloadMap[TSourceType];
+ sourceType: TSourceType;
+};
+
+/** Server-owned AgentSignal source union. */
+export type AgentSignalSourceVariants = {
+ [TSourceType in AgentSignalSourceType]: AgentSignalSourceVariant<TSourceType>;
+}[AgentSignalSourceType];
+
+/** Server-owned alias retained for user-message sources. */
+export type SourceAgentUserMessage = AgentSignalSourceVariant<'agent.user.message'>;
+
+/** Server-owned alias retained for execution-completed sources. */
+export type SourceAgentExecutionCompleted = AgentSignalSourceVariant<'agent.execution.completed'>;
+
+/** Server-owned alias retained for execution-failed sources. */
+export type SourceAgentExecutionFailed = AgentSignalSourceVariant<'agent.execution.failed'>;
+
+/** Server-owned alias retained for before-step runtime sources. */
+export type SourceRuntimeBeforeStep = AgentSignalSourceVariant<'runtime.before_step'>;
+
+/** Server-owned alias retained for after-step runtime sources. */
+export type SourceRuntimeAfterStep = AgentSignalSourceVariant<'runtime.after_step'>;
+
+/** Server-owned alias retained for merged bot-message sources. */
+export type SourceBotMessageMerged = AgentSignalSourceVariant<'bot.message.merged'>;
+
+/** Server-owned alias retained for client gateway stream-start sources. */
+export type SourceClientGatewayStreamStart =
+ AgentSignalSourceVariant<'client.gateway.stream_start'>;
+
+/** Server-owned alias retained for client gateway step-complete sources. */
+export type SourceClientGatewayStepComplete =
+ AgentSignalSourceVariant<'client.gateway.step_complete'>;
+
+/** Server-owned alias retained for client gateway runtime-end sources. */
+export type SourceClientGatewayRuntimeEnd = AgentSignalSourceVariant<'client.gateway.runtime_end'>;
+
+/** Server-owned alias retained for client gateway error sources. */
+export type SourceClientGatewayError = AgentSignalSourceVariant<'client.gateway.error'>;
+
+/** Server-owned alias retained for client runtime-start sources. */
+export type SourceClientRuntimeStart = AgentSignalSourceVariant<'client.runtime.start'>;
+
+/** Server-owned alias retained for client runtime-complete sources. */
+export type SourceClientRuntimeComplete = AgentSignalSourceVariant<'client.runtime.complete'>;
+
+/** Client-originated source types accepted by the authenticated browser edge. */
+export const AGENT_SIGNAL_CLIENT_SOURCE_TYPES = [
+ AGENT_SIGNAL_SOURCE_TYPES.clientGatewayError,
+ AGENT_SIGNAL_SOURCE_TYPES.clientGatewayRuntimeEnd,
+ AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStepComplete,
+ AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStreamStart,
+ AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete,
+ AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart,
+] as const satisfies readonly Extract<AgentSignalSourceType, `client.${string}`>[];
+
+/** Narrows one generic source node to the server-owned source catalog. */
+export const isAgentSignalKnownSource = (
+ source: AgentSignalSource,
+): source is AgentSignalSourceVariants => {
+ return Object.values(AGENT_SIGNAL_SOURCE_TYPES).includes(
+ source.sourceType as AgentSignalSourceType,
+ );
+};
diff --git a/src/server/services/agentSignal/sources/__tests__/index.test.ts b/src/server/services/agentSignal/sources/__tests__/index.test.ts
new file mode 100644
index 00000000000..518cc28f3fc
--- /dev/null
+++ b/src/server/services/agentSignal/sources/__tests__/index.test.ts
@@ -0,0 +1,62 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mockStore = {
+ acquireScopeLock: vi.fn(),
+ readWindow: vi.fn(),
+ releaseScopeLock: vi.fn(),
+ tryDedupe: vi.fn(),
+ writeWindow: vi.fn(),
+};
+
+describe('agent signal sources', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('normalizes source events into source nodes', async () => {
+ const { buildSource, emitSourceEvent } = await import('..');
+
+ mockStore.tryDedupe.mockResolvedValue(true);
+ mockStore.acquireScopeLock.mockResolvedValue(true);
+ mockStore.readWindow.mockResolvedValue({ eventCount: '1' });
+ mockStore.writeWindow.mockResolvedValue(undefined);
+ mockStore.releaseScopeLock.mockResolvedValue(undefined);
+
+ const builtSource = buildSource({
+ payload: { operationId: 'op-1', stepIndex: 1, turnCount: 2 },
+ scopeKey: 'topic:t1',
+ sourceId: 'source_1',
+ sourceType: 'runtime.after_step',
+ timestamp: 1710000000000,
+ });
+
+ expect(builtSource.sourceType).toBe('runtime.after_step');
+ expect(builtSource.chain).toEqual({
+ chainId: 'chain:source_1',
+ rootSourceId: 'source_1',
+ });
+
+ const result = await emitSourceEvent(
+ {
+ payload: { operationId: 'op-1', stepIndex: 1, turnCount: 2 },
+ scopeKey: 'topic:t1',
+ sourceId: 'source_1',
+ sourceType: 'runtime.after_step',
+ timestamp: 1710000000000,
+ },
+ { store: mockStore },
+ );
+
+ expect(result.deduped).toBe(false);
+
+ if (result.deduped) throw new Error('Expected generated source result');
+
+ expect(result.source.sourceType).toBe('runtime.after_step');
+ expect(result.source.chain).toEqual({
+ chainId: 'chain:source_1',
+ rootSourceId: 'source_1',
+ });
+ expect(result.trigger.windowEventCount).toBe(2);
+ });
+});
diff --git a/src/server/services/agentSignal/sources/buildSource.ts b/src/server/services/agentSignal/sources/buildSource.ts
new file mode 100644
index 00000000000..0014181ed41
--- /dev/null
+++ b/src/server/services/agentSignal/sources/buildSource.ts
@@ -0,0 +1,36 @@
+import type { AgentSignalSource } from '@lobechat/agent-signal';
+
+import { agentExecutionCompletedRenderer } from './renderers/agentExecutionCompleted';
+import { agentExecutionFailedRenderer } from './renderers/agentExecutionFailed';
+import { agentUserMessageRenderer } from './renderers/agentUserMessage';
+import { defaultSourceRenderer } from './renderers/defaultSource';
+import { runtimeAfterStepRenderer } from './renderers/runtimeAfterStep';
+import { runtimeBeforeStepRenderer } from './renderers/runtimeBeforeStep';
+import type { EmitSourceEventInput, SourceRenderer } from './types';
+
+const sourceRenderers = new Map<AgentSignalSource['sourceType'], SourceRenderer>([
+ [agentExecutionCompletedRenderer.sourceType, agentExecutionCompletedRenderer],
+ [agentExecutionFailedRenderer.sourceType, agentExecutionFailedRenderer],
+ [agentUserMessageRenderer.sourceType, agentUserMessageRenderer],
+ [runtimeAfterStepRenderer.sourceType, runtimeAfterStepRenderer],
+ [runtimeBeforeStepRenderer.sourceType, runtimeBeforeStepRenderer],
+]);
+
+/**
+ * Builds one normalized Agent Signal source from producer input.
+ *
+ * Use when:
+ * - Server producers hand over loosely-shaped payloads
+ * - The runtime needs one stable source envelope before dedupe/window handling
+ *
+ * Expects:
+ * - `input.sourceType` selects the matching renderer when one exists
+ *
+ * Returns:
+ * - A normalized {@link AgentSignalSource}
+ */
+export const buildSource = (input: EmitSourceEventInput): AgentSignalSource => {
+ const renderer = sourceRenderers.get(input.sourceType) ?? defaultSourceRenderer;
+
+ return renderer.render(input);
+};
diff --git a/src/server/services/agentSignal/sources/index.ts b/src/server/services/agentSignal/sources/index.ts
new file mode 100644
index 00000000000..f68370d4f22
--- /dev/null
+++ b/src/server/services/agentSignal/sources/index.ts
@@ -0,0 +1,79 @@
+import type { EmitSourceEventResult, SignalTriggerMetadata } from '@lobechat/agent-signal';
+
+import { AGENT_SIGNAL_DEFAULTS } from '../constants';
+import { redisSourceEventStore } from '../store/adapters/redis/sourceEventStore';
+import type { AgentSignalSourceEventStore } from '../store/types';
+import { buildSource } from './buildSource';
+import type { EmitSourceEventInput } from './types';
+
+/** Options for source-event generation. */
+export interface EmitSourceEventOptions {
+ store?: AgentSignalSourceEventStore;
+}
+
+const defaultSourceEventStore: AgentSignalSourceEventStore = redisSourceEventStore;
+
+const buildEventId = (input: EmitSourceEventInput) => {
+ return `${input.scopeKey}:${input.sourceType}:${input.sourceId}:${input.timestamp}`;
+};
+
+const buildTrigger = (
+ scopeKey: string,
+ eventId: string,
+ windowEventCount: number,
+): SignalTriggerMetadata => {
+ return {
+ scopeKey,
+ token: `trigger:${eventId}`,
+ windowEventCount,
+ };
+};
+
+export { buildSource } from './buildSource';
+export type { EmitSourceEventInput } from './types';
+
+export const emitSourceEvent = async (
+ input: EmitSourceEventInput,
+ options: EmitSourceEventOptions = {},
+): Promise<EmitSourceEventResult> => {
+ const store = options.store ?? defaultSourceEventStore;
+ const eventId = buildEventId(input);
+ const deduped = await store.tryDedupe(eventId, AGENT_SIGNAL_DEFAULTS.signalDedupeTtlSeconds);
+
+ if (!deduped) {
+ return { deduped: true, reason: 'duplicate' };
+ }
+
+ const locked = await store.acquireScopeLock(
+ input.scopeKey,
+ AGENT_SIGNAL_DEFAULTS.generationLockTtlSeconds,
+ );
+
+ if (!locked) {
+ return { deduped: true, reason: 'scope_locked' };
+ }
+
+ try {
+ const currentWindow = await store.readWindow(input.scopeKey);
+ const previousCount = Number(currentWindow?.eventCount ?? '0');
+ const nextCount = previousCount + 1;
+
+ await store.writeWindow(
+ input.scopeKey,
+ {
+ eventCount: String(nextCount),
+ lastEventAt: String(input.timestamp),
+ lastEventId: eventId,
+ },
+ AGENT_SIGNAL_DEFAULTS.signalWindowTtlSeconds,
+ );
+
+ return {
+ deduped: false,
+ source: buildSource(input),
+ trigger: buildTrigger(input.scopeKey, eventId, nextCount),
+ };
+ } finally {
+ await store.releaseScopeLock(input.scopeKey);
+ }
+};
diff --git a/src/server/services/agentSignal/sources/renderers/agentExecutionCompleted.ts b/src/server/services/agentSignal/sources/renderers/agentExecutionCompleted.ts
new file mode 100644
index 00000000000..dca77316c33
--- /dev/null
+++ b/src/server/services/agentSignal/sources/renderers/agentExecutionCompleted.ts
@@ -0,0 +1,30 @@
+import { AGENT_SIGNAL_SOURCE_TYPES } from '../../sourceTypes';
+import type { SourceRenderer } from '../types';
+import { createBaseSource } from './shared';
+
+export const agentExecutionCompletedRenderer = {
+ render(input) {
+ return {
+ ...createBaseSource(input),
+ payload: {
+ agentId: typeof input.payload.agentId === 'string' ? input.payload.agentId : undefined,
+ operationId: String(input.payload.operationId ?? input.sourceId),
+ serializedContext:
+ typeof input.payload.serializedContext === 'string'
+ ? input.payload.serializedContext
+ : undefined,
+ steps:
+ typeof input.payload.steps === 'number'
+ ? input.payload.steps
+ : typeof input.payload.stepCount === 'number'
+ ? input.payload.stepCount
+ : 0,
+ topicId: typeof input.payload.topicId === 'string' ? input.payload.topicId : undefined,
+ turnCount:
+ typeof input.payload.turnCount === 'number' ? input.payload.turnCount : undefined,
+ },
+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentExecutionCompleted,
+ };
+ },
+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentExecutionCompleted,
+} satisfies SourceRenderer;
diff --git a/src/server/services/agentSignal/sources/renderers/agentExecutionFailed.ts b/src/server/services/agentSignal/sources/renderers/agentExecutionFailed.ts
new file mode 100644
index 00000000000..7a88b7b7a5f
--- /dev/null
+++ b/src/server/services/agentSignal/sources/renderers/agentExecutionFailed.ts
@@ -0,0 +1,31 @@
+import { AGENT_SIGNAL_SOURCE_TYPES } from '../../sourceTypes';
+import type { SourceRenderer } from '../types';
+import { createBaseSource } from './shared';
+
+export const agentExecutionFailedRenderer = {
+ render(input) {
+ return {
+ ...createBaseSource(input),
+ payload: {
+ agentId: typeof input.payload.agentId === 'string' ? input.payload.agentId : undefined,
+ errorMessage:
+ typeof input.payload.errorMessage === 'string'
+ ? input.payload.errorMessage
+ : typeof input.payload.error === 'string'
+ ? input.payload.error
+ : undefined,
+ operationId: String(input.payload.operationId ?? input.sourceId),
+ reason: typeof input.payload.reason === 'string' ? input.payload.reason : undefined,
+ serializedContext:
+ typeof input.payload.serializedContext === 'string'
+ ? input.payload.serializedContext
+ : undefined,
+ topicId: typeof input.payload.topicId === 'string' ? input.payload.topicId : undefined,
+ turnCount:
+ typeof input.payload.turnCount === 'number' ? input.payload.turnCount : undefined,
+ },
+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentExecutionFailed,
+ };
+ },
+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentExecutionFailed,
+} satisfies SourceRenderer;
diff --git a/src/server/services/agentSignal/sources/renderers/agentUserMessage.ts b/src/server/services/agentSignal/sources/renderers/agentUserMessage.ts
new file mode 100644
index 00000000000..5fe0350ce23
--- /dev/null
+++ b/src/server/services/agentSignal/sources/renderers/agentUserMessage.ts
@@ -0,0 +1,52 @@
+import { AGENT_SIGNAL_SOURCE_TYPES } from '../../sourceTypes';
+import type { SourceRenderer } from '../types';
+import { createBaseSource } from './shared';
+
+export const agentUserMessageRenderer = {
+ render(input) {
+ return {
+ ...createBaseSource(input),
+ payload: {
+ agentId: typeof input.payload.agentId === 'string' ? input.payload.agentId : undefined,
+ documentPayload:
+ input.payload.documentPayload && typeof input.payload.documentPayload === 'object'
+ ? (input.payload.documentPayload as Record<string, unknown>)
+ : undefined,
+ intents: Array.isArray(input.payload.intents)
+ ? input.payload.intents.filter(
+ (intent): intent is 'document' | 'memory' | 'persona' | 'prompt' =>
+ intent === 'document' ||
+ intent === 'memory' ||
+ intent === 'persona' ||
+ intent === 'prompt',
+ )
+ : undefined,
+ memoryPayload:
+ input.payload.memoryPayload && typeof input.payload.memoryPayload === 'object'
+ ? (input.payload.memoryPayload as Record<string, unknown>)
+ : undefined,
+ message:
+ typeof input.payload.message === 'string'
+ ? input.payload.message
+ : typeof input.payload.prompt === 'string'
+ ? input.payload.prompt
+ : '',
+ messageId:
+ typeof input.payload.messageId === 'string'
+ ? input.payload.messageId
+ : typeof input.payload.userMessageId === 'string'
+ ? input.payload.userMessageId
+ : input.sourceId,
+ serializedContext:
+ typeof input.payload.serializedContext === 'string'
+ ? input.payload.serializedContext
+ : undefined,
+ threadId: typeof input.payload.threadId === 'string' ? input.payload.threadId : undefined,
+ topicId: typeof input.payload.topicId === 'string' ? input.payload.topicId : undefined,
+ trigger: typeof input.payload.trigger === 'string' ? input.payload.trigger : undefined,
+ },
+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage,
+ };
+ },
+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage,
+} satisfies SourceRenderer;
diff --git a/src/server/services/agentSignal/sources/renderers/defaultSource.ts b/src/server/services/agentSignal/sources/renderers/defaultSource.ts
new file mode 100644
index 00000000000..aa975fde5e8
--- /dev/null
+++ b/src/server/services/agentSignal/sources/renderers/defaultSource.ts
@@ -0,0 +1,14 @@
+import type { AgentSignalSource } from '@lobechat/agent-signal';
+
+import type { SourceRenderer } from '../types';
+import { createBaseSource } from './shared';
+
+export const defaultSourceRenderer = {
+ render(input) {
+ return {
+ ...createBaseSource(input),
+ sourceType: input.sourceType,
+ } as AgentSignalSource;
+ },
+ sourceType: '*' as AgentSignalSource['sourceType'],
+} satisfies SourceRenderer;
diff --git a/src/server/services/agentSignal/sources/renderers/runtimeAfterStep.ts b/src/server/services/agentSignal/sources/renderers/runtimeAfterStep.ts
new file mode 100644
index 00000000000..35c9a183a8f
--- /dev/null
+++ b/src/server/services/agentSignal/sources/renderers/runtimeAfterStep.ts
@@ -0,0 +1,25 @@
+import { AGENT_SIGNAL_SOURCE_TYPES } from '../../sourceTypes';
+import type { SourceRenderer } from '../types';
+import { createBaseSource } from './shared';
+
+export const runtimeAfterStepRenderer = {
+ render(input) {
+ return {
+ ...createBaseSource(input),
+ payload: {
+ agentId: typeof input.payload.agentId === 'string' ? input.payload.agentId : undefined,
+ operationId: String(input.payload.operationId ?? input.sourceId),
+ serializedContext:
+ typeof input.payload.serializedContext === 'string'
+ ? input.payload.serializedContext
+ : undefined,
+ stepIndex: typeof input.payload.stepIndex === 'number' ? input.payload.stepIndex : 0,
+ topicId: typeof input.payload.topicId === 'string' ? input.payload.topicId : undefined,
+ turnCount:
+ typeof input.payload.turnCount === 'number' ? input.payload.turnCount : undefined,
+ },
+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.runtimeAfterStep,
+ };
+ },
+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.runtimeAfterStep,
+} satisfies SourceRenderer;
diff --git a/src/server/services/agentSignal/sources/renderers/runtimeBeforeStep.ts b/src/server/services/agentSignal/sources/renderers/runtimeBeforeStep.ts
new file mode 100644
index 00000000000..d148ed8a352
--- /dev/null
+++ b/src/server/services/agentSignal/sources/renderers/runtimeBeforeStep.ts
@@ -0,0 +1,25 @@
+import { AGENT_SIGNAL_SOURCE_TYPES } from '../../sourceTypes';
+import type { SourceRenderer } from '../types';
+import { createBaseSource } from './shared';
+
+export const runtimeBeforeStepRenderer = {
+ render(input) {
+ return {
+ ...createBaseSource(input),
+ payload: {
+ agentId: typeof input.payload.agentId === 'string' ? input.payload.agentId : undefined,
+ operationId: String(input.payload.operationId ?? input.sourceId),
+ serializedContext:
+ typeof input.payload.serializedContext === 'string'
+ ? input.payload.serializedContext
+ : undefined,
+ stepIndex: typeof input.payload.stepIndex === 'number' ? input.payload.stepIndex : 0,
+ topicId: typeof input.payload.topicId === 'string' ? input.payload.topicId : undefined,
+ turnCount:
+ typeof input.payload.turnCount === 'number' ? input.payload.turnCount : undefined,
+ },
+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.runtimeBeforeStep,
+ };
+ },
+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.runtimeBeforeStep,
+} satisfies SourceRenderer;
diff --git a/src/server/services/agentSignal/sources/renderers/shared.ts b/src/server/services/agentSignal/sources/renderers/shared.ts
new file mode 100644
index 00000000000..2f48f575984
--- /dev/null
+++ b/src/server/services/agentSignal/sources/renderers/shared.ts
@@ -0,0 +1,16 @@
+import type { EmitSourceEventInput } from '../types';
+
+export const createChainRef = (sourceId: string) => ({
+ chainId: `chain:${sourceId}`,
+ rootSourceId: sourceId,
+});
+
+export const createBaseSource = (input: EmitSourceEventInput) => {
+ return {
+ chain: createChainRef(input.sourceId),
+ payload: input.payload,
+ scopeKey: input.scopeKey,
+ sourceId: input.sourceId,
+ timestamp: input.timestamp,
+ };
+};
diff --git a/src/server/services/agentSignal/sources/types.ts b/src/server/services/agentSignal/sources/types.ts
new file mode 100644
index 00000000000..9d679d8a267
--- /dev/null
+++ b/src/server/services/agentSignal/sources/types.ts
@@ -0,0 +1,14 @@
+import type { AgentSignalSource } from '@lobechat/agent-signal';
+
+export interface EmitSourceEventInput {
+ payload: Record<string, unknown>;
+ scopeKey: string;
+ sourceId: string;
+ sourceType: AgentSignalSource['sourceType'];
+ timestamp: number;
+}
+
+export interface SourceRenderer {
+ render: (input: EmitSourceEventInput) => AgentSignalSource;
+ sourceType: AgentSignalSource['sourceType'];
+}
diff --git a/src/server/services/agentSignal/store/__tests__/redisPolicyStateStore.test.ts b/src/server/services/agentSignal/store/__tests__/redisPolicyStateStore.test.ts
new file mode 100644
index 00000000000..f8f753e54c6
--- /dev/null
+++ b/src/server/services/agentSignal/store/__tests__/redisPolicyStateStore.test.ts
@@ -0,0 +1,59 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ type AgentSignalRedisTestGlobal,
+ hashes,
+ installStatefulRedisMock,
+ mockRedis,
+ resetRedisState,
+} from './redisTestUtils';
+
+const loadStore = async () => {
+ vi.resetModules();
+ (globalThis as AgentSignalRedisTestGlobal).__agentSignalRedisClient = mockRedis;
+
+ return import('../adapters/redis/policyStateStore');
+};
+
+describe('redis policy-state store', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetRedisState();
+ installStatefulRedisMock();
+ (globalThis as AgentSignalRedisTestGlobal).__agentSignalRedisClient = mockRedis;
+ });
+
+ it('reads and writes policy state as hash payload', async () => {
+ const store = await loadStore();
+
+ hashes.set('agent-signal:policy:sample.policy:topic:t1', { lastNudgedAt: '1000' });
+
+ await expect(store.readPolicyState('sample.policy', 'topic:t1')).resolves.toEqual({
+ lastNudgedAt: '1000',
+ });
+ await store.writePolicyState('sample.policy', 'topic:t1', { lastNudgedAt: '2000' }, 60);
+
+ expect(mockRedis.hset).toHaveBeenCalledWith('agent-signal:policy:sample.policy:topic:t1', {
+ lastNudgedAt: '2000',
+ });
+ });
+
+ it('returns undefined when hgetall returns an empty hash', async () => {
+ const store = await loadStore();
+
+ await expect(store.readPolicyState('sample.policy', 'topic:t1')).resolves.toBeUndefined();
+ });
+
+ it('treats writes as no-op when redis is unavailable', async () => {
+ const store = await loadStore();
+
+ (globalThis as AgentSignalRedisTestGlobal).__agentSignalRedisClient = null;
+
+ await expect(
+ store.writePolicyState('sample.policy', 'topic:t1', { eventCount: '1' }, 10),
+ ).resolves.toBeUndefined();
+ expect(mockRedis.hset).not.toHaveBeenCalled();
+ expect(mockRedis.expire).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/server/services/agentSignal/store/__tests__/redisRuntimeWaypointStore.test.ts b/src/server/services/agentSignal/store/__tests__/redisRuntimeWaypointStore.test.ts
new file mode 100644
index 00000000000..6fe8a75e28e
--- /dev/null
+++ b/src/server/services/agentSignal/store/__tests__/redisRuntimeWaypointStore.test.ts
@@ -0,0 +1,124 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ type AgentSignalRedisTestGlobal,
+ installStatefulRedisMock,
+ lastCasClient,
+ mockRedis,
+ queueExecConflict,
+ resetRedisState,
+ secondSource,
+ source,
+} from './redisTestUtils';
+
+const loadStore = async () => {
+ vi.resetModules();
+ (globalThis as AgentSignalRedisTestGlobal).__agentSignalRedisClient = mockRedis;
+
+ return import('../adapters/redis/runtimeWaypointStore');
+};
+
+describe('redis runtime-waypoint store', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetRedisState();
+ installStatefulRedisMock();
+ (globalThis as AgentSignalRedisTestGlobal).__agentSignalRedisClient = mockRedis;
+ });
+
+ it('keeps both events when appends happen concurrently on the same scope', async () => {
+ const store = await loadStore();
+
+ await Promise.all([store.append('topic:t1', source), store.append('topic:t1', secondSource)]);
+
+ await expect(store.load('topic:t1')).resolves.toEqual({
+ events: [source, secondSource],
+ nextHop: undefined,
+ pending: undefined,
+ scopeKey: 'topic:t1',
+ terminal: undefined,
+ });
+ });
+
+ it('retries claim after optimistic-lock invalidation on an isolated CAS client', async () => {
+ const store = await loadStore();
+
+ await store.append('topic:t1', source);
+ queueExecConflict();
+
+ await expect(store.claim('topic:t1')).resolves.toEqual({
+ scopeKey: 'topic:t1',
+ source,
+ status: 'pending',
+ });
+
+ expect(mockRedis.duplicate).toHaveBeenCalledTimes(1);
+ expect(lastCasClient()?.watch).toHaveBeenCalledWith(
+ 'agent-signal:waypoint:topic:t1',
+ 'agent-signal:waypoint:topic:t1:events',
+ );
+ expect(lastCasClient()?.quit).toHaveBeenCalledTimes(1);
+ });
+
+ it('ignores terminal transitions for a source that is not currently pending', async () => {
+ const store = await loadStore();
+
+ await store.append('topic:t1', source);
+ await store.append('topic:t1', secondSource);
+
+ await expect(store.claim('topic:t1')).resolves.toEqual({
+ scopeKey: 'topic:t1',
+ source,
+ status: 'pending',
+ });
+
+ await store.complete({
+ completedAt: 1_500,
+ scopeKey: 'topic:t1',
+ sourceId: secondSource.sourceId,
+ });
+
+ await expect(store.load('topic:t1')).resolves.toEqual({
+ events: [source, secondSource],
+ nextHop: undefined,
+ pending: {
+ scopeKey: 'topic:t1',
+ source,
+ status: 'pending',
+ },
+ scopeKey: 'topic:t1',
+ terminal: undefined,
+ });
+
+ await expect(store.claim('topic:t1')).resolves.toEqual({
+ scopeKey: 'topic:t1',
+ source,
+ status: 'pending',
+ });
+
+ await store.complete({
+ completedAt: 1_600,
+ scopeKey: 'topic:t1',
+ sourceId: source.sourceId,
+ });
+
+ await expect(store.claim('topic:t1')).resolves.toEqual({
+ scopeKey: 'topic:t1',
+ source: secondSource,
+ status: 'pending',
+ });
+ });
+
+ it('fails claim after exhausting optimistic-lock retries', async () => {
+ const store = await loadStore();
+
+ await store.append('topic:t1', source);
+ queueExecConflict(5);
+
+ await expect(store.claim('topic:t1')).rejects.toThrow(
+ 'Failed to claim waypoint for scope "topic:t1" after retrying',
+ );
+ expect(lastCasClient()?.quit).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/server/services/agentSignal/store/__tests__/redisSourceEventStore.test.ts b/src/server/services/agentSignal/store/__tests__/redisSourceEventStore.test.ts
new file mode 100644
index 00000000000..cf979654574
--- /dev/null
+++ b/src/server/services/agentSignal/store/__tests__/redisSourceEventStore.test.ts
@@ -0,0 +1,107 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ type AgentSignalRedisTestGlobal,
+ hashes,
+ installStatefulRedisMock,
+ mockRedis,
+ resetRedisState,
+} from './redisTestUtils';
+
+const loadStore = async () => {
+ vi.resetModules();
+ (globalThis as AgentSignalRedisTestGlobal).__agentSignalRedisClient = mockRedis;
+
+ return import('../adapters/redis/sourceEventStore');
+};
+
+describe('redis source-event store', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetRedisState();
+ installStatefulRedisMock();
+ (globalThis as AgentSignalRedisTestGlobal).__agentSignalRedisClient = mockRedis;
+ });
+
+ it('dedupe accepts first write and rejects duplicate', async () => {
+ const store = await loadStore();
+
+ mockRedis.set.mockResolvedValueOnce('OK').mockResolvedValueOnce(null);
+
+ await expect(store.tryDedupe('event_1', 60)).resolves.toBe(true);
+ await expect(store.tryDedupe('event_1', 60)).resolves.toBe(false);
+ expect(mockRedis.set).toHaveBeenNthCalledWith(
+ 1,
+ 'agent-signal:dedupe:event_1',
+ '1',
+ 'EX',
+ 60,
+ 'NX',
+ );
+ });
+
+ it('acquires and releases scope lock', async () => {
+ const store = await loadStore();
+
+ mockRedis.set.mockResolvedValueOnce('OK').mockResolvedValueOnce(null);
+
+ await expect(store.acquireScopeLock('topic:t1', 10)).resolves.toBe(true);
+ await expect(store.acquireScopeLock('topic:t1', 10)).resolves.toBe(false);
+ await store.releaseScopeLock('topic:t1');
+
+ expect(mockRedis.del).toHaveBeenCalledWith('agent-signal:lock:topic:t1');
+ });
+
+ it('reads and writes window state as hash payload', async () => {
+ const store = await loadStore();
+
+ hashes.set('agent-signal:window:topic:t1', { eventCount: '2', lastEventId: 'evt_2' });
+
+ await expect(store.readWindow('topic:t1')).resolves.toEqual({
+ eventCount: '2',
+ lastEventId: 'evt_2',
+ });
+ await store.writeWindow('topic:t1', { eventCount: '3' }, 300);
+
+ expect(mockRedis.hset).toHaveBeenCalledWith('agent-signal:window:topic:t1', {
+ eventCount: '3',
+ });
+ expect(mockRedis.expire).toHaveBeenCalledWith('agent-signal:window:topic:t1', 300);
+ });
+
+ it('returns undefined when hgetall returns an empty hash', async () => {
+ const store = await loadStore();
+
+ await expect(store.readWindow('topic:t1')).resolves.toBeUndefined();
+ });
+
+ it('returns false for dedupe and lock when redis is unavailable', async () => {
+ const store = await loadStore();
+
+ (globalThis as AgentSignalRedisTestGlobal).__agentSignalRedisClient = null;
+
+ await expect(store.tryDedupe('event_1', 60)).resolves.toBe(false);
+ await expect(store.acquireScopeLock('topic:t1', 60)).resolves.toBe(false);
+ });
+
+ it('treats writes as no-op when redis is unavailable', async () => {
+ const store = await loadStore();
+
+ (globalThis as AgentSignalRedisTestGlobal).__agentSignalRedisClient = null;
+
+ await expect(store.writeWindow('topic:t1', { eventCount: '1' }, 10)).resolves.toBeUndefined();
+ await expect(store.releaseScopeLock('topic:t1')).resolves.toBeUndefined();
+ expect(mockRedis.hset).not.toHaveBeenCalled();
+ expect(mockRedis.expire).not.toHaveBeenCalled();
+ });
+
+ it('skips empty hash writes', async () => {
+ const store = await loadStore();
+
+ await store.writeWindow('topic:t1', {}, 10);
+
+ expect(mockRedis.hset).not.toHaveBeenCalled();
+ expect(mockRedis.expire).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/server/services/agentSignal/store/__tests__/redisTestUtils.ts b/src/server/services/agentSignal/store/__tests__/redisTestUtils.ts
new file mode 100644
index 00000000000..5a6397a447f
--- /dev/null
+++ b/src/server/services/agentSignal/store/__tests__/redisTestUtils.ts
@@ -0,0 +1,188 @@
+import { createSource } from '@lobechat/agent-signal';
+import { vi } from 'vitest';
+
+export interface AgentSignalRedisTestGlobal {
+ __agentSignalRedisClient?: typeof mockRedis | null;
+}
+
+type HashState = Map<string, Record<string, string>>;
+type ListState = Map<string, string[]>;
+
+export const hashes: HashState = new Map();
+export const lists: ListState = new Map();
+
+const cloneHash = (value?: Record<string, string>) => {
+ return value ? { ...value } : {};
+};
+
+const getListSlice = (key: string, start: number, stop: number) => {
+ const current = [...(lists.get(key) ?? [])];
+ const normalizedStop = stop < 0 ? current.length + stop + 1 : stop + 1;
+
+ return current.slice(start, normalizedStop);
+};
+
+const applyHashWrite = (key: string, payload: Record<string, string>) => {
+ const current = hashes.get(key) ?? {};
+ hashes.set(key, { ...current, ...payload });
+};
+
+export const resetRedisState = () => {
+ hashes.clear();
+ lists.clear();
+};
+
+const queuedExecResults: Array<Array<readonly [null, 'OK']> | null | undefined> = [];
+
+const createMockRedisClient = () => {
+ return {
+ del: vi.fn(),
+ duplicate: vi.fn(),
+ expire: vi.fn(),
+ hdel: vi.fn(),
+ hgetall: vi.fn(),
+ hset: vi.fn(),
+ lrange: vi.fn(),
+ multi: vi.fn(),
+ quit: vi.fn(),
+ rpush: vi.fn(),
+ set: vi.fn(),
+ unwatch: vi.fn(),
+ watch: vi.fn(),
+ };
+};
+
+export const mockRedis = createMockRedisClient();
+const casClients: Array<typeof mockRedis> = [];
+
+const installRedisClientBehavior = (client: typeof mockRedis) => {
+ client.del.mockImplementation(async (key: string) => {
+ const removed = Number(hashes.delete(key)) + Number(lists.delete(key));
+ return removed;
+ });
+ client.expire.mockImplementation(async () => 1);
+ client.hdel.mockImplementation(async (key: string, ...fields: string[]) => {
+ const current = hashes.get(key) ?? {};
+
+ for (const field of fields) {
+ delete current[field];
+ }
+
+ hashes.set(key, current);
+
+ return fields.length;
+ });
+ client.hgetall.mockImplementation(async (key: string) => {
+ return cloneHash(hashes.get(key));
+ });
+ client.hset.mockImplementation(async (key: string, payload: Record<string, string>) => {
+ applyHashWrite(key, payload);
+ return Object.keys(payload).length;
+ });
+ client.lrange.mockImplementation(async (key: string, start: number, stop: number) => {
+ return getListSlice(key, start, stop);
+ });
+ client.rpush.mockImplementation(async (key: string, ...values: string[]) => {
+ const current = [...(lists.get(key) ?? []), ...values];
+ lists.set(key, current);
+
+ return current.length;
+ });
+ client.watch.mockImplementation(async () => 'OK');
+ client.unwatch.mockImplementation(async () => 'OK');
+ client.quit.mockImplementation(async () => 'OK');
+ client.multi.mockImplementation(() => {
+ const commands: Array<() => void> = [];
+
+ const chain = {
+ exec: vi.fn(async () => {
+ const queued = queuedExecResults.shift();
+
+ if (queued === null) {
+ return null;
+ }
+
+ for (const command of commands) {
+ command();
+ }
+
+ return queued ?? commands.map(() => [null, 'OK'] as const);
+ }),
+ expire(key: string, ttlSeconds: number) {
+ commands.push(() => {
+ void ttlSeconds;
+ });
+ commands.push(() => {
+ void key;
+ });
+ return chain;
+ },
+ hdel(key: string, ...fields: string[]) {
+ commands.push(() => {
+ const current = hashes.get(key) ?? {};
+
+ for (const field of fields) {
+ delete current[field];
+ }
+
+ hashes.set(key, current);
+ });
+ return chain;
+ },
+ hset(key: string, payload: Record<string, string>) {
+ commands.push(() => {
+ applyHashWrite(key, payload);
+ });
+ return chain;
+ },
+ rpush(key: string, value: string) {
+ commands.push(() => {
+ const current = [...(lists.get(key) ?? []), value];
+ lists.set(key, current);
+ });
+ return chain;
+ },
+ };
+
+ return chain;
+ });
+};
+
+export const installStatefulRedisMock = () => {
+ casClients.length = 0;
+ queuedExecResults.length = 0;
+ installRedisClientBehavior(mockRedis);
+ mockRedis.duplicate.mockImplementation(() => {
+ const client = createMockRedisClient();
+ installRedisClientBehavior(client);
+ casClients.push(client);
+
+ return client as never;
+ });
+};
+
+export const queueExecConflict = (count = 1) => {
+ for (let index = 0; index < count; index++) {
+ queuedExecResults.push(null);
+ }
+};
+
+export const lastCasClient = () => {
+ return casClients.at(-1);
+};
+
+export const source = createSource({
+ payload: { message: 'remember this' },
+ scope: { topicId: 'topic-1', userId: 'user-1' },
+ scopeKey: 'topic:topic-1',
+ sourceType: 'source.user.message',
+ timestamp: 1_000,
+});
+
+export const secondSource = createSource({
+ payload: { message: 'remember this next' },
+ scope: { topicId: 'topic-1', userId: 'user-1' },
+ scopeKey: 'topic:topic-1',
+ sourceType: 'source.user.message',
+ timestamp: 2_000,
+});
diff --git a/src/server/services/agentSignal/store/adapters/redis/policyStateStore.ts b/src/server/services/agentSignal/store/adapters/redis/policyStateStore.ts
new file mode 100644
index 00000000000..bad3f7609a4
--- /dev/null
+++ b/src/server/services/agentSignal/store/adapters/redis/policyStateStore.ts
@@ -0,0 +1,24 @@
+import { AGENT_SIGNAL_KEYS } from '../../../constants';
+import type { AgentSignalPolicyStateStore } from '../../types';
+import { readHash, writeHash } from './shared';
+
+/** Reads one persisted policy-state snapshot for a scope. */
+export const readPolicyState = async (policyId: string, scopeKey: string) => {
+ return readHash(AGENT_SIGNAL_KEYS.policy(policyId, scopeKey));
+};
+
+/** Writes one persisted policy-state snapshot for a scope. */
+export const writePolicyState = async (
+ policyId: string,
+ scopeKey: string,
+ data: Record<string, string>,
+ ttlSeconds: number,
+) => {
+ await writeHash(AGENT_SIGNAL_KEYS.policy(policyId, scopeKey), data, ttlSeconds);
+};
+
+/** Redis-backed policy-state store used by AgentSignal policies. */
+export const redisPolicyStateStore: AgentSignalPolicyStateStore = {
+ readPolicyState,
+ writePolicyState,
+};
diff --git a/src/server/services/agentSignal/store/adapters/redis/runtimeWaypointStore.ts b/src/server/services/agentSignal/store/adapters/redis/runtimeWaypointStore.ts
new file mode 100644
index 00000000000..7ec780bd2c2
--- /dev/null
+++ b/src/server/services/agentSignal/store/adapters/redis/runtimeWaypointStore.ts
@@ -0,0 +1,284 @@
+import { AGENT_SIGNAL_DEFAULTS, AGENT_SIGNAL_KEYS } from '../../../constants';
+import type {
+ AgentSignalRuntimeBackendStore,
+ RuntimeCompletionInput,
+ RuntimeFailureInput,
+ RuntimeNextHop,
+ RuntimePendingClaim,
+ RuntimeWaypoint,
+} from '../../../runtime/backend/types';
+import {
+ closeCasRedisClient,
+ getCasRedisClient,
+ getRedisClient,
+ parseJsonField,
+ readHash,
+ readHashFrom,
+} from './shared';
+
+/**
+ * Compare-and-set retries for waypoint hash transitions.
+ *
+ * The runtime only needs a lightweight guard against stale `claim` / `complete` / `fail`
+ * writes here. If contention remains after these retries, the caller can try again later.
+ */
+const WAYPOINT_MUTATION_MAX_RETRIES = 5;
+
+const parseWaypointEvents = (entries: string[]): RuntimeWaypoint['events'] => {
+ return entries.map((entry) => JSON.parse(entry) as RuntimeWaypoint['events'][number]);
+};
+
+const toWaypoint = (
+ scopeKey: string,
+ value: Record<string, string> | undefined,
+ eventEntries: string[],
+): RuntimeWaypoint => {
+ if (!value && eventEntries.length === 0) {
+ return {
+ events: [],
+ scopeKey,
+ };
+ }
+
+ return {
+ events: parseWaypointEvents(eventEntries),
+ nextHop: parseJsonField<NonNullable<RuntimeWaypoint['nextHop']>>(value?.nextHop),
+ pending: parseJsonField<RuntimePendingClaim>(value?.pending),
+ scopeKey: value?.scopeKey ?? scopeKey,
+ terminal: parseJsonField<NonNullable<RuntimeWaypoint['terminal']>>(value?.terminal),
+ };
+};
+
+const getWaypointKey = (scopeKey: string) => AGENT_SIGNAL_KEYS.waypoint(scopeKey);
+const getWaypointEventsKey = (scopeKey: string) => AGENT_SIGNAL_KEYS.waypointEvents(scopeKey);
+
+const readWaypointRecord = async (scopeKey: string) => {
+ const redis = getRedisClient();
+ if (!redis) {
+ return {
+ events: [],
+ scopeKey,
+ };
+ }
+
+ const [hash, eventEntries] = await Promise.all([
+ readHash(getWaypointKey(scopeKey)),
+ redis.lrange(getWaypointEventsKey(scopeKey), 0, -1),
+ ]);
+
+ return toWaypoint(scopeKey, hash, eventEntries);
+};
+
+const findNextPendingSource = (waypoint: RuntimeWaypoint) => {
+ if (waypoint.pending) {
+ return waypoint.pending.source;
+ }
+
+ if (!waypoint.terminal) {
+ return waypoint.events[0];
+ }
+
+ const terminalIndex = waypoint.events.findIndex(
+ (event) => event.sourceId === waypoint.terminal?.sourceId,
+ );
+
+ if (terminalIndex === -1) {
+ return waypoint.events[0];
+ }
+
+ return waypoint.events[terminalIndex + 1];
+};
+
+/** Appends one source to the durable waypoint for a scope. */
+export const append = async (scopeKey: string, source: RuntimePendingClaim['source']) => {
+ const redis = getRedisClient();
+ if (!redis) return;
+
+ const waypointKey = getWaypointKey(scopeKey);
+ const waypointEventsKey = getWaypointEventsKey(scopeKey);
+
+ await redis
+ .multi()
+ .rpush(waypointEventsKey, JSON.stringify(source))
+ .hset(waypointKey, { scopeKey })
+ .expire(waypointEventsKey, AGENT_SIGNAL_DEFAULTS.runtimeWaypointTtlSeconds)
+ .expire(waypointKey, AGENT_SIGNAL_DEFAULTS.runtimeWaypointTtlSeconds)
+ .exec();
+};
+
+/** Claims the next unprocessed source for one scope. */
+export const claim = async (scopeKey: string): Promise<RuntimePendingClaim | null> => {
+ const redis = getCasRedisClient();
+ if (!redis) return null;
+
+ const waypointKey = getWaypointKey(scopeKey);
+ const waypointEventsKey = getWaypointEventsKey(scopeKey);
+
+ try {
+ for (let attempt = 0; attempt < WAYPOINT_MUTATION_MAX_RETRIES; attempt++) {
+ await redis.watch(waypointKey, waypointEventsKey);
+
+ const [hash, eventEntries] = await Promise.all([
+ readHashFrom(redis, waypointKey),
+ redis.lrange(waypointEventsKey, 0, -1),
+ ]);
+ const waypoint = toWaypoint(scopeKey, hash, eventEntries);
+ const source = findNextPendingSource(waypoint);
+
+ if (!source) {
+ await redis.unwatch();
+ return null;
+ }
+
+ const pending = {
+ scopeKey,
+ source,
+ status: 'pending',
+ } as const;
+ const result = await redis
+ .multi()
+ .hset(waypointKey, {
+ pending: JSON.stringify(pending),
+ scopeKey,
+ })
+ .expire(waypointEventsKey, AGENT_SIGNAL_DEFAULTS.runtimeWaypointTtlSeconds)
+ .expire(waypointKey, AGENT_SIGNAL_DEFAULTS.runtimeWaypointTtlSeconds)
+ .exec();
+
+ if (result) {
+ return pending;
+ }
+ }
+
+ throw new Error(`Failed to claim waypoint for scope "${scopeKey}" after retrying`);
+ } finally {
+ await closeCasRedisClient(redis);
+ }
+};
+
+/** Marks one claimed source as completed. */
+export const complete = async (input: RuntimeCompletionInput) => {
+ const redis = getCasRedisClient();
+ if (!redis) return;
+
+ const waypointKey = getWaypointKey(input.scopeKey);
+ const waypointEventsKey = getWaypointEventsKey(input.scopeKey);
+
+ try {
+ for (let attempt = 0; attempt < WAYPOINT_MUTATION_MAX_RETRIES; attempt++) {
+ await redis.watch(waypointKey);
+
+ const hash = await readHashFrom(redis, waypointKey);
+ const pending = parseJsonField<RuntimePendingClaim>(hash?.pending);
+
+ if (pending?.source.sourceId !== input.sourceId) {
+ await redis.unwatch();
+ return;
+ }
+
+ const result = await redis
+ .multi()
+ .hdel(waypointKey, 'pending')
+ .hset(waypointKey, {
+ scopeKey: input.scopeKey,
+ terminal: JSON.stringify({
+ completedAt: input.completedAt,
+ sourceId: input.sourceId,
+ status: 'completed',
+ }),
+ })
+ .expire(waypointEventsKey, AGENT_SIGNAL_DEFAULTS.runtimeWaypointTtlSeconds)
+ .expire(waypointKey, AGENT_SIGNAL_DEFAULTS.runtimeWaypointTtlSeconds)
+ .exec();
+
+ if (result) {
+ return;
+ }
+ }
+
+ throw new Error(`Failed to complete waypoint for scope "${input.scopeKey}" after retrying`);
+ } finally {
+ await closeCasRedisClient(redis);
+ }
+};
+
+/** Marks one claimed source as failed. */
+export const fail = async (input: RuntimeFailureInput) => {
+ const redis = getCasRedisClient();
+ if (!redis) return;
+
+ const waypointKey = getWaypointKey(input.scopeKey);
+ const waypointEventsKey = getWaypointEventsKey(input.scopeKey);
+
+ try {
+ for (let attempt = 0; attempt < WAYPOINT_MUTATION_MAX_RETRIES; attempt++) {
+ await redis.watch(waypointKey);
+
+ const hash = await readHashFrom(redis, waypointKey);
+ const pending = parseJsonField<RuntimePendingClaim>(hash?.pending);
+
+ if (pending?.source.sourceId !== input.sourceId) {
+ await redis.unwatch();
+ return;
+ }
+
+ const result = await redis
+ .multi()
+ .hdel(waypointKey, 'pending')
+ .hset(waypointKey, {
+ scopeKey: input.scopeKey,
+ terminal: JSON.stringify({
+ error: input.error,
+ failedAt: input.failedAt,
+ sourceId: input.sourceId,
+ status: 'failed',
+ }),
+ })
+ .expire(waypointEventsKey, AGENT_SIGNAL_DEFAULTS.runtimeWaypointTtlSeconds)
+ .expire(waypointKey, AGENT_SIGNAL_DEFAULTS.runtimeWaypointTtlSeconds)
+ .exec();
+
+ if (result) {
+ return;
+ }
+ }
+
+ throw new Error(`Failed to fail waypoint for scope "${input.scopeKey}" after retrying`);
+ } finally {
+ await closeCasRedisClient(redis);
+ }
+};
+
+/** Loads the durable waypoint snapshot for one scope. */
+export const load = async (scopeKey: string): Promise<RuntimeWaypoint> => {
+ return readWaypointRecord(scopeKey);
+};
+
+/** Persists the next workflow-driven wake-up for one scope. */
+export const schedule = async (input: RuntimeNextHop) => {
+ const redis = getRedisClient();
+ if (!redis) return;
+
+ const waypointKey = getWaypointKey(input.scopeKey);
+ const waypointEventsKey = getWaypointEventsKey(input.scopeKey);
+
+ await redis
+ .multi()
+ .hset(waypointKey, {
+ nextHop: JSON.stringify(input),
+ scopeKey: input.scopeKey,
+ })
+ .expire(waypointEventsKey, AGENT_SIGNAL_DEFAULTS.runtimeWaypointTtlSeconds)
+ .expire(waypointKey, AGENT_SIGNAL_DEFAULTS.runtimeWaypointTtlSeconds)
+ .exec();
+};
+
+/** Redis-backed waypoint store used by workflow-backed runtime adapters. */
+export const redisRuntimeWaypointStore: AgentSignalRuntimeBackendStore = {
+ append,
+ claim,
+ complete,
+ fail,
+ load,
+ schedule,
+};
diff --git a/src/server/services/agentSignal/store/adapters/redis/shared.ts b/src/server/services/agentSignal/store/adapters/redis/shared.ts
new file mode 100644
index 00000000000..00492afbd06
--- /dev/null
+++ b/src/server/services/agentSignal/store/adapters/redis/shared.ts
@@ -0,0 +1,72 @@
+import type Redis from 'ioredis';
+
+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
+
+interface AgentSignalRedisGlobal {
+ __agentSignalRedisClient?: Redis | null;
+}
+
+export type HashPayload = Record<string, string>;
+
+export const getRedisClient = (): Redis | null => {
+ const testRedis = (globalThis as AgentSignalRedisGlobal).__agentSignalRedisClient;
+ if (testRedis !== undefined) return testRedis;
+
+ return getAgentRuntimeRedisClient();
+};
+
+export const readHashFrom = async (
+ redis: Pick<Redis, 'hgetall'> | null,
+ key: string,
+): Promise<HashPayload | undefined> => {
+ if (!redis) return undefined;
+
+ const value = await redis.hgetall(key);
+ if (!value || Object.keys(value).length === 0) return undefined;
+
+ return value;
+};
+
+export const readHash = async (key: string): Promise<HashPayload | undefined> => {
+ return readHashFrom(getRedisClient(), key);
+};
+
+export const getCasRedisClient = (): Redis | null => {
+ const redis = getRedisClient();
+ if (!redis) return null;
+
+ return redis.duplicate();
+};
+
+export const closeCasRedisClient = async (redis: Pick<Redis, 'quit'> | null) => {
+ if (!redis) return;
+
+ await redis.quit();
+};
+
+export const writeHash = async (
+ key: string,
+ data: HashPayload,
+ ttlSeconds: number,
+): Promise<void> => {
+ const redis = getRedisClient();
+ if (!redis) return;
+ if (Object.keys(data).length === 0) return;
+
+ await redis.hset(key, data);
+ await redis.expire(key, ttlSeconds);
+};
+
+export const trySetNx = async (key: string, ttlSeconds: number): Promise<boolean> => {
+ const redis = getRedisClient();
+ if (!redis) return false;
+
+ const result = await redis.set(key, '1', 'EX', ttlSeconds, 'NX');
+ return result === 'OK';
+};
+
+export const parseJsonField = <T>(value?: string): T | undefined => {
+ if (!value) return undefined;
+
+ return JSON.parse(value) as T;
+};
diff --git a/src/server/services/agentSignal/store/adapters/redis/sourceEventStore.ts b/src/server/services/agentSignal/store/adapters/redis/sourceEventStore.ts
new file mode 100644
index 00000000000..8415329e70c
--- /dev/null
+++ b/src/server/services/agentSignal/store/adapters/redis/sourceEventStore.ts
@@ -0,0 +1,44 @@
+import { AGENT_SIGNAL_KEYS } from '../../../constants';
+import type { AgentSignalSourceEventStore } from '../../types';
+import { getRedisClient, readHash, trySetNx, writeHash } from './shared';
+
+/** Accepts one source-event id once within the configured TTL window. */
+export const tryDedupe = async (eventId: string, ttlSeconds: number) => {
+ return trySetNx(AGENT_SIGNAL_KEYS.dedupe(eventId), ttlSeconds);
+};
+
+/** Reads one persisted source-event window snapshot. */
+export const readWindow = async (scopeKey: string) => {
+ return readHash(AGENT_SIGNAL_KEYS.window(scopeKey));
+};
+
+/** Writes one persisted source-event window snapshot. */
+export const writeWindow = async (
+ scopeKey: string,
+ data: Record<string, string>,
+ ttlSeconds: number,
+) => {
+ await writeHash(AGENT_SIGNAL_KEYS.window(scopeKey), data, ttlSeconds);
+};
+
+/** Acquires the short-lived source-generation lock for one scope. */
+export const acquireScopeLock = async (scopeKey: string, ttlSeconds: number) => {
+ return trySetNx(AGENT_SIGNAL_KEYS.lock(scopeKey), ttlSeconds);
+};
+
+/** Releases the short-lived source-generation lock for one scope. */
+export const releaseScopeLock = async (scopeKey: string) => {
+ const redis = getRedisClient();
+ if (!redis) return;
+
+ await redis.del(AGENT_SIGNAL_KEYS.lock(scopeKey));
+};
+
+/** Redis-backed source-event store used by generation. */
+export const redisSourceEventStore: AgentSignalSourceEventStore = {
+ acquireScopeLock,
+ readWindow,
+ releaseScopeLock,
+ tryDedupe,
+ writeWindow,
+};
diff --git a/src/server/services/agentSignal/store/types.ts b/src/server/services/agentSignal/store/types.ts
new file mode 100644
index 00000000000..1dec3324fe0
--- /dev/null
+++ b/src/server/services/agentSignal/store/types.ts
@@ -0,0 +1,36 @@
+/** Persisted policy-state payload for one AgentSignal scope. */
+export interface AgentSignalPolicyStatePayload {
+ [key: string]: string;
+}
+
+/** Persisted source-event window payload for one AgentSignal scope. */
+export interface AgentSignalSourceEventWindowPayload {
+ [key: string]: string;
+}
+
+/** Storage contract for policy-scoped AgentSignal state. */
+export interface AgentSignalPolicyStateStore {
+ readPolicyState: (
+ policyId: string,
+ scopeKey: string,
+ ) => Promise<AgentSignalPolicyStatePayload | undefined>;
+ writePolicyState: (
+ policyId: string,
+ scopeKey: string,
+ data: AgentSignalPolicyStatePayload,
+ ttlSeconds: number,
+ ) => Promise<void>;
+}
+
+/** Storage contract for AgentSignal source-event generation state. */
+export interface AgentSignalSourceEventStore {
+ acquireScopeLock: (scopeKey: string, ttlSeconds: number) => Promise<boolean>;
+ readWindow: (scopeKey: string) => Promise<AgentSignalSourceEventWindowPayload | undefined>;
+ releaseScopeLock: (scopeKey: string) => Promise<void>;
+ tryDedupe: (eventId: string, ttlSeconds: number) => Promise<boolean>;
+ writeWindow: (
+ scopeKey: string,
+ data: AgentSignalSourceEventWindowPayload,
+ ttlSeconds: number,
+ ) => Promise<void>;
+}
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index de863ae4547..ce399da382a 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -62,6 +62,7 @@ import { getAbortError, isAbortError, throwIfAborted } from '@/server/services/a
import { hookDispatcher } from '@/server/services/agentRuntime/hooks';
import { type AgentHook } from '@/server/services/agentRuntime/hooks/types';
import { type StepLifecycleCallbacks } from '@/server/services/agentRuntime/types';
+import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';
import { DocumentService } from '@/server/services/document';
import { FileService } from '@/server/services/file';
import { KlavisService } from '@/server/services/klavis';
@@ -1286,6 +1287,24 @@ export class AiAgentService {
});
if (userMessageRecord) {
log('execAgent: created user message %s', userMessageRecord.id);
+ await enqueueAgentSignalSourceEvent(
+ {
+ payload: {
+ agentId: resolvedAgentId,
+ message: prompt,
+ threadId: appContext?.threadId ?? undefined,
+ topicId,
+ trigger,
+ messageId: userMessageRecord.id,
+ },
+ sourceId: userMessageRecord.id,
+ sourceType: 'agent.user.message',
+ },
+ {
+ agentId: resolvedAgentId,
+ userId: this.userId,
+ },
+ );
}
// 14. Create assistant message placeholder in database
diff --git a/src/server/services/bot/BotMessageRouter.ts b/src/server/services/bot/BotMessageRouter.ts
index b0e3b936094..c1d4ca85e4e 100644
--- a/src/server/services/bot/BotMessageRouter.ts
+++ b/src/server/services/bot/BotMessageRouter.ts
@@ -9,6 +9,7 @@ import { AgentBotProviderModel } from '@/database/models/agentBotProvider';
import type { LobeChatDatabase } from '@/database/type';
import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import { emitAgentSignalSourceEvent } from '@/server/services/agentSignal';
import { AiAgentService } from '@/server/services/aiAgent';
import { AgentBridgeService } from './AgentBridgeService';
@@ -443,6 +444,25 @@ export class BotMessageRouter {
}
const merged = BotMessageRouter.mergeSkippedMessages(message, context);
+ void emitAgentSignalSourceEvent(
+ {
+ payload: {
+ agentId,
+ applicationId,
+ platform,
+ message: merged.text,
+ platformThreadId: thread.id,
+ },
+ sourceId: merged.id,
+ sourceType: 'bot.message.merged',
+ },
+ {
+ agentId,
+ db: serverDB,
+ userId,
+ },
+ { ignoreError: true },
+ );
log(
'onNewMention: agent=%s, platform=%s, author=%s, thread=%s, merged=%d, mergedAttachments=%d',
@@ -518,6 +538,25 @@ export class BotMessageRouter {
}
const merged = BotMessageRouter.mergeSkippedMessages(message, context);
+ void emitAgentSignalSourceEvent(
+ {
+ payload: {
+ agentId,
+ applicationId,
+ platform,
+ message: merged.text,
+ platformThreadId: thread.id,
+ },
+ sourceId: merged.id,
+ sourceType: 'bot.message.merged',
+ },
+ {
+ agentId,
+ db: serverDB,
+ userId,
+ },
+ { ignoreError: true },
+ );
log(
'onSubscribedMessage: agent=%s, platform=%s, author=%s, thread=%s, merged=%d, mergedAttachments=%d',
@@ -580,6 +619,25 @@ export class BotMessageRouter {
}
const merged = BotMessageRouter.mergeSkippedMessages(message, context);
+ void emitAgentSignalSourceEvent(
+ {
+ payload: {
+ agentId,
+ applicationId,
+ platform,
+ message: merged.text,
+ platformThreadId: thread.id,
+ },
+ sourceId: merged.id,
+ sourceType: 'bot.message.merged',
+ },
+ {
+ agentId,
+ db: serverDB,
+ userId,
+ },
+ { ignoreError: true },
+ );
log(
'onNewMessage (%s catch-all): agent=%s, author=%s, thread=%s, text=%s, mergedAttachments=%d',
diff --git a/src/server/workflows-hono/agent-signal/index.ts b/src/server/workflows-hono/agent-signal/index.ts
new file mode 100644
index 00000000000..d1509f28a47
--- /dev/null
+++ b/src/server/workflows-hono/agent-signal/index.ts
@@ -0,0 +1,18 @@
+import { serve } from '@upstash/workflow/hono';
+import { Hono } from 'hono';
+
+import type { AgentSignalWorkflowRunPayload } from '@/server/workflows/agentSignal';
+import { runAgentSignalWorkflow } from '@/server/workflows/agentSignal/run';
+
+import { createWorkflowQstashClient } from '../qstashClient';
+
+const app = new Hono();
+
+app.post(
+ '/run',
+ serve<AgentSignalWorkflowRunPayload>((context) => runAgentSignalWorkflow(context), {
+ qstashClient: createWorkflowQstashClient(),
+ }),
+);
+
+export default app;
diff --git a/src/server/workflows-hono/index.ts b/src/server/workflows-hono/index.ts
index 6a7018dcf9f..09c4071f34b 100644
--- a/src/server/workflows-hono/index.ts
+++ b/src/server/workflows-hono/index.ts
@@ -1,10 +1,12 @@
import { Hono } from 'hono';
+import agentSignalApp from './agent-signal';
import memoryUserMemoryApp from './memory-user-memory';
import taskApp from './task';
const app = new Hono().basePath('/api/workflows');
+app.route('/agent-signal', agentSignalApp);
app.route('/memory-user-memory', memoryUserMemoryApp);
app.route('/task', taskApp);
diff --git a/src/server/workflows/agentSignal.test.ts b/src/server/workflows/agentSignal.test.ts
new file mode 100644
index 00000000000..99e7e0c6b18
--- /dev/null
+++ b/src/server/workflows/agentSignal.test.ts
@@ -0,0 +1,65 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const triggerMock = vi.fn();
+
+vi.mock('@/envs/app', () => ({
+ appEnv: {
+ APP_URL: 'http://localhost:3011',
+ INTERNAL_APP_URL: 'http://localhost:3011',
+ },
+}));
+
+vi.mock('@/libs/qstash', () => ({
+ workflowClient: {
+ trigger: triggerMock,
+ },
+}));
+
+describe('AgentSignalWorkflow', () => {
+ beforeEach(() => {
+ triggerMock.mockReset();
+ triggerMock.mockResolvedValue({ workflowRunId: 'wfr_agent_signal' });
+ });
+
+ it('normalizes the flow-control key while preserving the workflow payload scope key', async () => {
+ const { AgentSignalWorkflow } = await import('./agentSignal');
+
+ await AgentSignalWorkflow.triggerRun({
+ agentId: 'agent-1',
+ sourceEvent: {
+ payload: {
+ message: 'Remember this',
+ topicId: 'topic-1',
+ },
+ scopeKey: 'topic:topic-1',
+ sourceId: 'source-1',
+ sourceType: 'agent.user.message',
+ timestamp: 1710000000000,
+ },
+ userId: 'user-1',
+ });
+
+ expect(triggerMock).toHaveBeenCalledWith({
+ body: {
+ agentId: 'agent-1',
+ sourceEvent: {
+ payload: {
+ message: 'Remember this',
+ topicId: 'topic-1',
+ },
+ scopeKey: 'topic:topic-1',
+ sourceId: 'source-1',
+ sourceType: 'agent.user.message',
+ timestamp: 1710000000000,
+ },
+ userId: 'user-1',
+ },
+ flowControl: {
+ key: 'agent-signal.run.scope.topic_topic-1',
+ parallelism: 1,
+ },
+ url: 'http://localhost:3011/api/workflows/agent-signal/run',
+ });
+ });
+});
diff --git a/src/server/workflows/agentSignal/__tests__/run.integration.test.ts b/src/server/workflows/agentSignal/__tests__/run.integration.test.ts
new file mode 100644
index 00000000000..6ccb2b3c25b
--- /dev/null
+++ b/src/server/workflows/agentSignal/__tests__/run.integration.test.ts
@@ -0,0 +1,402 @@
+// @vitest-environment node
+import { createAction, createSignal } from '@lobechat/agent-signal';
+import { agents, users } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { describe, expect, it } from 'vitest';
+
+import { UserMemoryModel } from '@/database/models/userMemory';
+import { type AgentSignalSourceEnvelope } from '@/server/services/agentSignal';
+import { projectAgentSignalObservability } from '@/server/services/agentSignal/observability/projector';
+import { createAgentSignalRuntime } from '@/server/services/agentSignal/runtime/AgentSignalRuntime';
+import {
+ defineActionHandler,
+ defineAgentSignalHandlers,
+ defineSignalHandler,
+ defineSourceHandler,
+} from '@/server/services/agentSignal/runtime/middleware';
+import { emitSourceEvent } from '@/server/services/agentSignal/sources';
+import type { AgentSignalSourceType } from '@/server/services/agentSignal/sourceTypes';
+import type { AgentSignalSourceEventStore } from '@/server/services/agentSignal/store/types';
+import {
+ runAgentSignalWorkflow,
+ type RunAgentSignalWorkflowDeps,
+} from '@/server/workflows/agentSignal/run';
+import { uuid } from '@/utils/uuid';
+
+interface WorkflowScenarioCase {
+ expected: {
+ memory?: {
+ descriptionIncludes: string;
+ type: string;
+ };
+ };
+ id: string;
+ scenario: {
+ payload: {
+ agentId?: string;
+ documentPayload?: Record<string, unknown>;
+ intents?: Array<'document' | 'memory' | 'persona' | 'prompt'>;
+ memoryPayload?: Record<string, unknown>;
+ message: string;
+ messageId: string;
+ serializedContext?: string;
+ threadId?: string;
+ topicId?: string;
+ trigger?: string;
+ };
+ sourceType?: string;
+ timestamp?: number;
+ };
+}
+
+const basicMemoryWorkflowCase = {
+ expected: {
+ memory: {
+ descriptionIncludes: 'User prefers concise answers.',
+ type: 'personal',
+ },
+ },
+ id: 'basic-memory',
+ scenario: {
+ payload: {
+ intents: ['memory'],
+ memoryPayload: {
+ base: { content: 'User prefers concise answers.' },
+ identity: {
+ description: 'User prefers concise answers.',
+ tags: ['response-style'],
+ type: 'personal',
+ },
+ },
+ message: 'Remember that I prefer concise answers.',
+ messageId: 'msg-basic-memory',
+ },
+ },
+} satisfies WorkflowScenarioCase;
+
+const rejectedNoFeedbackWorkflowCase = {
+ expected: {},
+ id: 'rejected-no-feedback',
+ scenario: {
+ payload: {
+ message: 'Thanks, that answers my question.',
+ messageId: 'msg-rejected-no-feedback',
+ },
+ },
+} satisfies WorkflowScenarioCase;
+
+const createWorkflowContext = <TPayload>(requestPayload: TPayload) => {
+ return {
+ requestPayload,
+ run: async <TRunResult>(_stepId: string, handler: () => Promise<TRunResult>) => handler(),
+ };
+};
+
+const createInMemorySourceEventStore = (): AgentSignalSourceEventStore => {
+ const dedupeKeys = new Set<string>();
+ const locks = new Set<string>();
+ const windows = new Map<string, Record<string, string>>();
+
+ return {
+ acquireScopeLock: async (scopeKey, ttlSeconds) => {
+ void ttlSeconds;
+ if (locks.has(scopeKey)) return false;
+
+ locks.add(scopeKey);
+ return true;
+ },
+ readWindow: async (scopeKey) => windows.get(scopeKey),
+ releaseScopeLock: async (scopeKey) => {
+ locks.delete(scopeKey);
+ },
+ tryDedupe: async (eventId, ttlSeconds) => {
+ void ttlSeconds;
+ if (dedupeKeys.has(eventId)) return false;
+
+ dedupeKeys.add(eventId);
+ return true;
+ },
+ writeWindow: async (scopeKey, data, ttlSeconds) => {
+ void ttlSeconds;
+ windows.set(scopeKey, data);
+ },
+ };
+};
+
+const normalizeSourceEvent = (sourceEvent: AgentSignalSourceEnvelope) => {
+ return {
+ payload: sourceEvent.payload,
+ scopeKey: sourceEvent.scopeKey ?? `test-scope:${sourceEvent.sourceId}`,
+ sourceId: sourceEvent.sourceId,
+ sourceType: sourceEvent.sourceType,
+ timestamp: sourceEvent.timestamp ?? Date.now(),
+ };
+};
+
+const createExecuteSourceEventWithTestPolicies = (
+ store: AgentSignalSourceEventStore,
+): NonNullable<RunAgentSignalWorkflowDeps['executeSourceEvent']> => {
+ return async (sourceEvent, context) => {
+ const normalizedSourceEvent = normalizeSourceEvent(sourceEvent);
+ const emission = await emitSourceEvent(normalizedSourceEvent, { store });
+ if (emission.deduped) return emission;
+
+ const runtime = await createAgentSignalRuntime({
+ policies: [
+ defineAgentSignalHandlers([
+ defineSourceHandler('agent.user.message', {
+ async handle(source) {
+ const intents = Array.isArray(source.payload.intents)
+ ? source.payload.intents.filter(
+ (intent): intent is string => typeof intent === 'string',
+ )
+ : [];
+ const memoryPayload =
+ source.payload.memoryPayload &&
+ typeof source.payload.memoryPayload === 'object' &&
+ !Array.isArray(source.payload.memoryPayload)
+ ? (source.payload.memoryPayload as Record<string, unknown>)
+ : undefined;
+
+ if (!intents.includes('memory') || !memoryPayload) return;
+
+ return {
+ signals: [
+ createSignal({
+ payload: { memoryPayload },
+ signalType: 'signal.memory.request',
+ source,
+ }),
+ ],
+ status: 'dispatch',
+ } as const;
+ },
+ id: 'test-source-memory-request',
+ }),
+ defineSignalHandler('signal.memory.request', {
+ async handle(signal) {
+ const memoryPayload =
+ signal.payload.memoryPayload &&
+ typeof signal.payload.memoryPayload === 'object' &&
+ !Array.isArray(signal.payload.memoryPayload)
+ ? (signal.payload.memoryPayload as Record<string, unknown>)
+ : undefined;
+
+ if (!memoryPayload) return;
+
+ return {
+ actions: [
+ createAction({
+ actionType: 'action.memory.persist',
+ payload: { memoryPayload },
+ signal,
+ }),
+ ],
+ status: 'dispatch',
+ } as const;
+ },
+ id: 'test-signal-memory-request',
+ }),
+ defineActionHandler('action.memory.persist', {
+ async handle(action) {
+ const memoryPayload =
+ action.payload.memoryPayload &&
+ typeof action.payload.memoryPayload === 'object' &&
+ !Array.isArray(action.payload.memoryPayload)
+ ? (action.payload.memoryPayload as Record<string, unknown>)
+ : undefined;
+ const identity =
+ memoryPayload?.identity &&
+ typeof memoryPayload.identity === 'object' &&
+ !Array.isArray(memoryPayload.identity)
+ ? (memoryPayload.identity as Record<string, unknown>)
+ : undefined;
+ const base =
+ memoryPayload?.base &&
+ typeof memoryPayload.base === 'object' &&
+ !Array.isArray(memoryPayload.base)
+ ? (memoryPayload.base as Record<string, unknown>)
+ : undefined;
+
+ if (identity?.description && identity.type) {
+ await new UserMemoryModel(context.db, context.userId).addIdentityEntry({
+ base: {
+ details: typeof base?.content === 'string' ? base.content : undefined,
+ summary:
+ typeof identity.description === 'string' ? identity.description : undefined,
+ title:
+ typeof identity.description === 'string' ? identity.description : undefined,
+ },
+ identity: {
+ description:
+ typeof identity.description === 'string' ? identity.description : undefined,
+ tags: Array.isArray(identity.tags)
+ ? identity.tags.filter((tag): tag is string => typeof tag === 'string')
+ : undefined,
+ type: typeof identity.type === 'string' ? identity.type : undefined,
+ },
+ });
+ }
+
+ return {
+ actionId: action.actionId,
+ attempt: {
+ completedAt: normalizedSourceEvent.timestamp + 2,
+ current: 1,
+ startedAt: normalizedSourceEvent.timestamp + 1,
+ status: 'succeeded',
+ },
+ detail: 'memory persisted',
+ status: 'applied',
+ } as const;
+ },
+ id: 'test-action-memory-persist',
+ }),
+ ]),
+ ],
+ });
+
+ const runtimeResult = await runtime.emitNormalized(emission.source);
+ const trace =
+ runtimeResult.status === 'completed'
+ ? runtimeResult.trace
+ : {
+ actions: [],
+ results: [],
+ signals: [],
+ source: emission.source,
+ };
+
+ return {
+ ...emission,
+ orchestration: {
+ actions: trace.actions,
+ emittedSignals: trace.signals,
+ observability: projectAgentSignalObservability({
+ actions: trace.actions,
+ results: trace.results,
+ signals: trace.signals,
+ source: trace.source,
+ }),
+ plans: [],
+ results: trace.results,
+ runtimeResult,
+ },
+ } as const;
+ };
+};
+
+const assertScenarioSideEffects = async (input: {
+ testCase: WorkflowScenarioCase;
+ db: Awaited<ReturnType<typeof getTestDB>>;
+ userId: string;
+}) => {
+ const userMemoryModel = new UserMemoryModel(input.db, input.userId);
+
+ if (input.testCase.expected.memory) {
+ const expectedMemory = input.testCase.expected.memory;
+ const identities = await userMemoryModel.getIdentitiesByType(expectedMemory.type);
+ const hasExpectedMemory = identities.some((identity) =>
+ identity.description?.includes(expectedMemory.descriptionIncludes),
+ );
+
+ expect(hasExpectedMemory).toBe(true);
+ return;
+ }
+
+ const identities = await userMemoryModel.getIdentitiesByType('personal');
+ expect(identities).toHaveLength(0);
+};
+
+const createScenarioPayload = (
+ testCase: WorkflowScenarioCase,
+ input: { agentId: string; topicId: string; userId: string },
+) => {
+ const now = Date.now();
+ const payload = {
+ ...testCase.scenario.payload,
+ agentId:
+ 'agentId' in testCase.scenario.payload &&
+ typeof testCase.scenario.payload.agentId === 'string'
+ ? testCase.scenario.payload.agentId
+ : input.agentId,
+ topicId: input.topicId,
+ };
+
+ if (
+ typeof payload.documentPayload === 'object' &&
+ payload.documentPayload !== null &&
+ typeof payload.documentPayload.agentId !== 'string'
+ ) {
+ payload.documentPayload = {
+ ...payload.documentPayload,
+ agentId: input.agentId,
+ };
+ }
+
+ return {
+ agentId: input.agentId,
+ sourceEvent: {
+ payload,
+ scopeKey: `topic:${input.topicId}`,
+ sourceId: `workflow-scenario:${testCase.id}:${now}`,
+ sourceType: ('sourceType' in testCase.scenario
+ ? (testCase.scenario.sourceType ?? 'agent.user.message')
+ : 'agent.user.message') as AgentSignalSourceType,
+ timestamp: 'timestamp' in testCase.scenario ? (testCase.scenario.timestamp ?? now) : now,
+ },
+ userId: input.userId,
+ };
+};
+
+describe('runAgentSignalWorkflow integration', () => {
+ it.each([basicMemoryWorkflowCase, rejectedNoFeedbackWorkflowCase])(
+ 'handles the %s scenario through the workflow runner',
+ async (testCase) => {
+ const db = await getTestDB();
+ const userId = `eval_${uuid()}`;
+ const topicId = `topic_${uuid()}`;
+ const sourceEventStore = createInMemorySourceEventStore();
+ const executeSourceEvent = createExecuteSourceEventWithTestPolicies(sourceEventStore);
+
+ await db.insert(users).values({ id: userId });
+
+ const [agent] = await db
+ .insert(agents)
+ .values({
+ model: 'gpt-4o-mini',
+ plugins: [],
+ provider: 'openai',
+ systemRole: '',
+ title: 'Workflow Scenario Agent',
+ userId,
+ })
+ .returning();
+
+ const result = await runAgentSignalWorkflow(
+ createWorkflowContext(
+ createScenarioPayload(testCase, { agentId: agent.id, topicId, userId }),
+ ),
+ {
+ executeSourceEvent,
+ getDb: async () => db,
+ },
+ );
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ deduped: false,
+ success: true,
+ }),
+ );
+
+ await expect(
+ assertScenarioSideEffects({
+ db,
+ testCase,
+ userId,
+ }),
+ ).resolves.toBeUndefined();
+ },
+ );
+});
diff --git a/src/server/workflows/agentSignal/index.ts b/src/server/workflows/agentSignal/index.ts
new file mode 100644
index 00000000000..580a3f016c4
--- /dev/null
+++ b/src/server/workflows/agentSignal/index.ts
@@ -0,0 +1,96 @@
+import debug from 'debug';
+
+import { appEnv } from '@/envs/app';
+import { workflowClient } from '@/libs/qstash';
+import type {
+ AgentSignalSourcePayloadMap,
+ AgentSignalSourceType,
+} from '@/server/services/agentSignal/sourceTypes';
+
+const log = debug('lobe-server:workflows:agent-signal');
+
+const WORKFLOW_PATHS = {
+ run: '/api/workflows/agent-signal/run',
+} as const;
+
+const normalizeFlowControlKeySegment = (value: string) => {
+ return value.replaceAll(/[^\w.-]/g, '_');
+};
+
+type AgentSignalWorkflowSourceType = AgentSignalSourceType;
+
+type AgentSignalWorkflowSourcePayload<TSourceType extends AgentSignalWorkflowSourceType> =
+ AgentSignalSourcePayloadMap[TSourceType];
+
+/** One normalized Agent Signal source event handed to the workflow worker. */
+export interface AgentSignalWorkflowSourceEventInput<
+ TSourceType extends AgentSignalWorkflowSourceType = AgentSignalWorkflowSourceType,
+> {
+ payload: AgentSignalWorkflowSourcePayload<TSourceType>;
+ scopeKey: string;
+ sourceId: string;
+ sourceType: TSourceType;
+ timestamp: number;
+}
+
+/** One Upstash workflow payload for Agent Signal execution. */
+export interface AgentSignalWorkflowRunPayload {
+ agentId?: string;
+ sourceEvent: AgentSignalWorkflowSourceEventInput;
+ userId: string;
+}
+
+const getWorkflowUrl = (path: string): string => {
+ const baseUrl = appEnv.INTERNAL_APP_URL || appEnv.APP_URL;
+
+ if (!baseUrl) {
+ throw new Error('INTERNAL_APP_URL or APP_URL is required to trigger agent signal workflows');
+ }
+
+ return new URL(path, baseUrl).toString();
+};
+
+/**
+ * Agent Signal workflow trigger helper.
+ *
+ * Use when:
+ * - Server-owned ingress wants to hand off execution to Upstash Workflow
+ * - The caller already normalized the source event envelope
+ *
+ * Expects:
+ * - `sourceEvent.scopeKey` is stable for the policy coordination scope
+ *
+ * Returns:
+ * - Upstash workflow trigger metadata including `workflowRunId`
+ */
+export class AgentSignalWorkflow {
+ static triggerRun(payload: AgentSignalWorkflowRunPayload) {
+ const url = getWorkflowUrl(WORKFLOW_PATHS.run);
+
+ log('Triggering run workflow payload=%O', {
+ agentId: payload.agentId,
+ sourceEvent: payload.sourceEvent,
+ url,
+ userId: payload.userId,
+ });
+
+ return workflowClient.trigger({
+ body: payload,
+ flowControl: {
+ // NOTICE:
+ // Upstash QStash flow control keys reject `:` and other scope-key delimiters used by
+ // AgentSignal. We normalize only the flow-control segment here so runtime scope keys can
+ // keep their richer shape everywhere else.
+ // Source/context:
+ // - Local smoke trigger against real QStash returned:
+ // `flowControlKey must be alphanumeric, hyphen, underscore, or period`
+ // - `payload.sourceEvent.scopeKey` commonly contains delimiters like `topic:...`
+ // Removal condition:
+ // - Safe to remove only if Upstash broadens flow-control key validation.
+ key: `agent-signal.run.scope.${normalizeFlowControlKeySegment(payload.sourceEvent.scopeKey)}`,
+ parallelism: 1,
+ },
+ url,
+ });
+ }
+}
diff --git a/src/server/workflows/agentSignal/run.ts b/src/server/workflows/agentSignal/run.ts
new file mode 100644
index 00000000000..c954fac5724
--- /dev/null
+++ b/src/server/workflows/agentSignal/run.ts
@@ -0,0 +1,107 @@
+import debug from 'debug';
+
+import { getServerDB } from '@/database/server';
+import type { GeneratedAgentSignalEmissionResult } from '@/server/services/agentSignal';
+import { executeAgentSignalSourceEvent } from '@/server/services/agentSignal';
+import { createRedisRuntimeGuardBackend } from '@/server/services/agentSignal/runtime/backend/redisGuard';
+
+import type { AgentSignalWorkflowRunPayload } from './index';
+
+const log = debug('lobe-server:workflows:agent-signal:run');
+
+const isGeneratedEmission = (
+ value: Awaited<ReturnType<typeof executeAgentSignalSourceEvent>> | undefined,
+): value is GeneratedAgentSignalEmissionResult => {
+ return Boolean(value && !value.deduped);
+};
+
+/**
+ * Minimal workflow context contract used by the Agent Signal workflow runner.
+ *
+ * @param TPayload - Workflow request payload type.
+ */
+export interface AgentSignalWorkflowContext<TPayload = AgentSignalWorkflowRunPayload> {
+ requestPayload?: TPayload;
+ run: <TResult>(stepId: string, handler: () => Promise<TResult>) => Promise<TResult>;
+}
+
+/** Dependencies for executing one Agent Signal workflow payload. */
+export interface RunAgentSignalWorkflowDeps {
+ createRuntimeGuardBackend?: typeof createRedisRuntimeGuardBackend;
+ executeSourceEvent?: typeof executeAgentSignalSourceEvent;
+ getDb?: typeof getServerDB;
+}
+
+/**
+ * Runs one normalized Agent Signal source event inside the workflow worker.
+ *
+ * Use when:
+ * - The Next.js Upstash route needs a plain function for testable execution
+ * - Tests or local harnesses need the exact workflow worker logic without HTTP indirection
+ *
+ * Expects:
+ * - `context.requestPayload` contains `userId` and one normalized `sourceEvent`
+ *
+ * Returns:
+ * - A small execution summary mirroring the workflow route response
+ */
+export const runAgentSignalWorkflow = async (
+ context: AgentSignalWorkflowContext,
+ deps: RunAgentSignalWorkflowDeps = {},
+) => {
+ const payload = context.requestPayload;
+
+ if (!payload?.userId || !payload.sourceEvent) {
+ return { error: 'Missing userId or sourceEvent', success: false } as const;
+ }
+
+ log('Worker received payload=%O', payload);
+
+ const getDb = deps.getDb ?? getServerDB;
+ const executeSourceEvent = deps.executeSourceEvent ?? executeAgentSignalSourceEvent;
+ const createGuardBackend = deps.createRuntimeGuardBackend ?? createRedisRuntimeGuardBackend;
+
+ const db = await getDb();
+ const result = await context.run(
+ `agent-signal:execute:${payload.sourceEvent.sourceType}:${payload.sourceEvent.sourceId}`,
+ () =>
+ executeSourceEvent(
+ payload.sourceEvent,
+ {
+ agentId: payload.agentId,
+ db,
+ userId: payload.userId,
+ },
+ {
+ runtimeGuardBackend: createGuardBackend(),
+ },
+ ),
+ );
+
+ log('Processed source event result=%O', {
+ deduped: result?.deduped ?? true,
+ orchestration:
+ result && !result.deduped
+ ? {
+ actionTypes: result.orchestration.actions.map((action) => action.actionType),
+ resultStatuses: result.orchestration.results.map((item) => item.status),
+ runtimeStatus:
+ 'runtimeResult' in result.orchestration
+ ? result.orchestration.runtimeResult.status
+ : undefined,
+ signalTypes: result.orchestration.emittedSignals.map((signal) => signal.signalType),
+ }
+ : undefined,
+ scopeKey: payload.sourceEvent.scopeKey,
+ sourceId: payload.sourceEvent.sourceId,
+ sourceType: payload.sourceEvent.sourceType,
+ });
+
+ return {
+ deduped: result?.deduped ?? true,
+ emittedSignals: isGeneratedEmission(result) ? result.orchestration.emittedSignals.length : 0,
+ scopeKey: payload.sourceEvent.scopeKey,
+ sourceId: payload.sourceEvent.sourceId,
+ success: true,
+ } as const;
+};
diff --git a/src/services/agentSignal.ts b/src/services/agentSignal.ts
new file mode 100644
index 00000000000..2313e2dc2fd
--- /dev/null
+++ b/src/services/agentSignal.ts
@@ -0,0 +1,32 @@
+import { lambdaClient } from '@/libs/trpc/client';
+import type {
+ AgentSignalSourcePayloadMap,
+ AgentSignalSourceType,
+} from '@/server/services/agentSignal/sourceTypes';
+
+type ClientGatewaySourceType = Extract<AgentSignalSourceType, `client.${string}`>;
+
+type ClientGatewaySourceEnvelopeInput<TSourceType extends ClientGatewaySourceType> = {
+ payload: AgentSignalSourcePayloadMap[TSourceType];
+ scopeKey?: string;
+ sourceId: string;
+ sourceType: TSourceType;
+ timestamp?: number;
+};
+
+class AgentSignalService {
+ emitSourceEvent = async (payload: ClientGatewaySourceEnvelopeInput<ClientGatewaySourceType>) => {
+ return lambdaClient.agentSignal.emitSourceEvent.mutate(payload);
+ };
+
+ emitClientGatewaySourceEvent = async <TSourceType extends ClientGatewaySourceType>(
+ payload: ClientGatewaySourceEnvelopeInput<TSourceType>,
+ ) => {
+ return this.emitSourceEvent({
+ ...payload,
+ timestamp: payload.timestamp ?? Date.now(),
+ });
+ };
+}
+
+export const agentSignalService = new AgentSignalService();
diff --git a/src/store/chat/slices/aiChat/actions/agentSignalBridge.test.ts b/src/store/chat/slices/aiChat/actions/agentSignalBridge.test.ts
new file mode 100644
index 00000000000..c48406afc11
--- /dev/null
+++ b/src/store/chat/slices/aiChat/actions/agentSignalBridge.test.ts
@@ -0,0 +1,77 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/services/agentSignal', () => ({
+ agentSignalService: {
+ emitClientGatewaySourceEvent: vi.fn().mockResolvedValue(undefined),
+ },
+}));
+
+describe('emitClientAgentSignalSourceEvent', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('emits the full client.runtime.start payload shape', async () => {
+ const { agentSignalService } = await import('@/services/agentSignal');
+ const { emitClientAgentSignalSourceEvent } = await import('./agentSignalBridge');
+
+ await emitClientAgentSignalSourceEvent({
+ payload: {
+ agentId: 'agent-1',
+ operationId: 'op-1',
+ parentMessageId: 'msg-1',
+ parentMessageType: 'user',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ },
+ sourceId: 'op-1:client:start',
+ sourceType: 'client.runtime.start',
+ timestamp: 1,
+ });
+
+ expect(agentSignalService.emitClientGatewaySourceEvent).toHaveBeenCalledWith({
+ payload: {
+ agentId: 'agent-1',
+ operationId: 'op-1',
+ parentMessageId: 'msg-1',
+ parentMessageType: 'user',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ },
+ sourceId: 'op-1:client:start',
+ sourceType: 'client.runtime.start',
+ timestamp: 1,
+ });
+ });
+
+ it('emits the full client.runtime.complete payload shape', async () => {
+ const { agentSignalService } = await import('@/services/agentSignal');
+ const { emitClientAgentSignalSourceEvent } = await import('./agentSignalBridge');
+
+ await emitClientAgentSignalSourceEvent({
+ payload: {
+ agentId: 'agent-1',
+ operationId: 'op-1',
+ status: 'done',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ },
+ sourceId: 'op-1:client:complete',
+ sourceType: 'client.runtime.complete',
+ timestamp: 2,
+ });
+
+ expect(agentSignalService.emitClientGatewaySourceEvent).toHaveBeenCalledWith({
+ payload: {
+ agentId: 'agent-1',
+ operationId: 'op-1',
+ status: 'done',
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ },
+ sourceId: 'op-1:client:complete',
+ sourceType: 'client.runtime.complete',
+ timestamp: 2,
+ });
+ });
+});
diff --git a/src/store/chat/slices/aiChat/actions/agentSignalBridge.ts b/src/store/chat/slices/aiChat/actions/agentSignalBridge.ts
new file mode 100644
index 00000000000..be06e3d85fb
--- /dev/null
+++ b/src/store/chat/slices/aiChat/actions/agentSignalBridge.ts
@@ -0,0 +1,56 @@
+import type {
+ AgentSignalSourcePayloadMap,
+ AgentSignalSourceType,
+} from '@/server/services/agentSignal/sourceTypes';
+import { agentSignalService } from '@/services/agentSignal';
+
+type ClientAgentSignalSourceType = Extract<AgentSignalSourceType, `client.${string}`>;
+
+type ClientAgentSignalSourcePayload<TSourceType extends ClientAgentSignalSourceType> =
+ AgentSignalSourcePayloadMap[TSourceType];
+
+export interface ClientAgentSignalSourceEvent<TSourceType extends ClientAgentSignalSourceType> {
+ payload: ClientAgentSignalSourcePayload<TSourceType>;
+ scopeKey?: string;
+ sourceId?: string;
+ sourceType: TSourceType;
+ timestamp?: number;
+}
+
+const createSourceId = (sourceType: string, timestamp: number) => {
+ return `${sourceType}:${timestamp}:${Math.random().toString(36).slice(2, 10)}`;
+};
+
+/**
+ * Emits a client-side source event to the server-owned AgentSignal pipeline.
+ *
+ * Use when:
+ * - Browser/runtime code observes a meaningful boundary but must not run policies locally
+ * - The event should be normalized through the same server-side dedupe/backpressure layer
+ *
+ * Expects:
+ * - Payload contains enough routing context (topic or bot thread identifiers)
+ * - Failures must never block the UI path
+ *
+ * @returns Server mutation result when available, otherwise `undefined`
+ */
+export const emitClientAgentSignalSourceEvent = async <
+ TSourceType extends ClientAgentSignalSourceType,
+>(
+ input: ClientAgentSignalSourceEvent<TSourceType>,
+) => {
+ const timestamp = input.timestamp ?? Date.now();
+
+ try {
+ return await agentSignalService.emitClientGatewaySourceEvent({
+ payload: input.payload,
+ scopeKey: input.scopeKey,
+ sourceId: input.sourceId ?? createSourceId(input.sourceType, timestamp),
+ sourceType: input.sourceType,
+ timestamp,
+ });
+ } catch (error) {
+ console.error('[AgentSignal] Failed to emit client source event:', error);
+ return undefined;
+ }
+};
diff --git a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
index 5c3c5b22130..7790ca941cf 100644
--- a/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
+++ b/src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts
@@ -9,6 +9,7 @@ import type { ChatMessageError, ConversationContext } from '@lobechat/types';
import { AgentRuntimeErrorType } from '@lobechat/types';
import { messageService } from '@/services/message';
+import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/aiChat/actions/agentSignalBridge';
import type { ChatStore } from '@/store/chat/store';
import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';
@@ -119,6 +120,16 @@ export const createGatewayEventHandler = (
accumulatedReasoning = '';
// Fetch from DB so the new message exists in dbMessagesMap before chunks arrive
+ void emitClientAgentSignalSourceEvent({
+ payload: {
+ agentId: context.agentId,
+ operationId,
+ stepIndex: event.stepIndex,
+ topicId: context.topicId ?? undefined,
+ },
+ sourceId: `${operationId}:gateway:start:${event.stepIndex}`,
+ sourceType: 'client.gateway.stream_start',
+ });
await fetchAndReplaceMessages(get, context).catch(console.error);
});
break;
@@ -240,6 +251,16 @@ export const createGatewayEventHandler = (
// Refresh on execution_complete to ensure final step state is consistent
if (data?.phase === 'execution_complete') {
enqueue(async () => {
+ void emitClientAgentSignalSourceEvent({
+ payload: {
+ agentId: context.agentId,
+ operationId,
+ stepIndex: event.stepIndex,
+ topicId: context.topicId ?? undefined,
+ },
+ sourceId: `${operationId}:gateway:step_complete:${event.stepIndex}`,
+ sourceType: 'client.gateway.step_complete',
+ });
await fetchAndReplaceMessages(get, context).catch(console.error);
});
}
@@ -248,6 +269,15 @@ export const createGatewayEventHandler = (
case 'agent_runtime_end': {
enqueue(async () => {
+ void emitClientAgentSignalSourceEvent({
+ payload: {
+ agentId: context.agentId,
+ operationId,
+ topicId: context.topicId ?? undefined,
+ },
+ sourceId: `${operationId}:gateway:runtime_end`,
+ sourceType: 'client.gateway.runtime_end',
+ });
get().internal_toggleToolCallingStreaming(currentAssistantMessageId, undefined);
get().completeOperation(operationId);
@@ -264,6 +294,18 @@ export const createGatewayEventHandler = (
case 'error': {
enqueue(async () => {
const messageError = toChatMessageError(event.data);
+ const errorMessage = messageError.message;
+
+ void emitClientAgentSignalSourceEvent({
+ payload: {
+ agentId: context.agentId,
+ errorMessage,
+ operationId,
+ topicId: context.topicId ?? undefined,
+ },
+ sourceId: `${operationId}:gateway:error`,
+ sourceType: 'client.gateway.error',
+ });
get().internal_toggleToolCallingStreaming(currentAssistantMessageId, undefined);
get().completeOperation(operationId);
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index 183ede1c0f5..a075331b8a6 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -28,6 +28,7 @@ import { messageService } from '@/services/message';
import { getAgentStoreState } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { createAgentExecutors } from '@/store/chat/agents/createAgentExecutors';
+import { emitClientAgentSignalSourceEvent } from '@/store/chat/slices/aiChat/actions/agentSignalBridge';
import { type ChatStore, useChatStore } from '@/store/chat/store';
import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';
import { getTaskStoreState } from '@/store/task';
@@ -448,6 +449,18 @@ export class StreamingExecutorActionImpl {
originalMessages.length,
disableTools,
);
+ void emitClientAgentSignalSourceEvent({
+ payload: {
+ agentId,
+ operationId,
+ parentMessageId,
+ parentMessageType,
+ threadId: threadId ?? undefined,
+ topicId: topicId ?? undefined,
+ },
+ sourceId: `${operationId}:client:start`,
+ sourceType: 'client.runtime.start',
+ });
// Create a new array to avoid modifying the original messages
const messages = [...originalMessages];
@@ -798,6 +811,17 @@ export class StreamingExecutorActionImpl {
}
log('[internal_execAgentRuntime] completed');
+ void emitClientAgentSignalSourceEvent({
+ payload: {
+ agentId,
+ operationId,
+ status: state.status,
+ threadId: threadId ?? undefined,
+ topicId: topicId ?? undefined,
+ },
+ sourceId: `${operationId}:client:complete`,
+ sourceType: 'client.runtime.complete',
+ });
// Desktop notification (if not in tools calling mode)
if (isDesktop) {