🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(agent-signal): simplify structure of agent-signal (#14290)
Nekoe5e154afcb39
diff --git a/packages/agent-signal/README.md b/packages/agent-signal/README.mdnew file mode 100644index 00000000000..887db3eb28a--- /dev/null+++ b/packages/agent-signal/README.md@@ -0,0 +1,141 @@+# @lobechat/agent-signal++`@lobechat/agent-signal` is the shared Agent Signal domain package. It defines the language of Agent Signal nodes and source events, but it does not run policies, call model runtimes, read databases, trigger workflows, or import app server modules.++Use this package when code needs browser-safe or server-safe source event types, source event constants, scope-key helpers, and the core Agent Signal node shapes.++Do not add app integration here. Side effects belong in `src/server/services/agentSignal` or the browser service facade.++## Public APIs++### Core node APIs++Import from the package root when building or inspecting source, signal, action, and executor nodes:++```ts+import type { AgentSignalSource, BaseAction, BaseSignal } from '@lobechat/agent-signal';+import { createAction, createSignal, createSource } from '@lobechat/agent-signal';+```++Use these APIs inside runtime, scheduler, policy, and observability code that needs normalized semantic nodes.++### Source event APIs++Import from `@lobechat/agent-signal/source` when producing, typing, validating, or routing source events:++```ts+import {+ AGENT_SIGNAL_SOURCE_TYPES,+ createSourceEvent,+ type AgentSignalSourceEvent,+ type AgentSignalSourceEventInput,+} from '@lobechat/agent-signal/source';++const event = createSourceEvent({+ payload: {+ message: 'Please remember that I prefer concise answers.',+ messageId: 'msg_1',+ topicId: 'topic_1',+ },+ sourceId: 'source_1',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage,+});+```++`createSourceEvent` fills in:++- `scopeKey`, from `topicId` first, then bot thread metadata, then `fallback:global`+- `timestamp`, from `Date.now()` when the caller does not provide one++Use `AgentSignalSourceEventInput<TSourceType>` for producer inputs and `AgentSignalSourceEvent<TSourceType>` once `scopeKey` and `timestamp` are required.++### Scope-key APIs++Use `getSourceEventScopeKey` for source-event payloads and `AgentSignalScopeKey` when code already has structured scope metadata:++```ts+import { AgentSignalScopeKey, getSourceEventScopeKey } from '@lobechat/agent-signal/source';++const topicScopeKey = getSourceEventScopeKey({ topicId: 'topic_1' });+const botScopeKey = AgentSignalScopeKey.forBotThread({+ applicationId: 'discord-app',+ platform: 'discord',+ platformThreadId: 'thread_1',+});+```++## Which Layer To Use++Use this package for:++- Shared browser/server source event types+- Source type constants and payload maps+- Scope-key derivation+- Pure Agent Signal source, signal, action, result, and trigger types+- Pure node builders++Use the browser service facade for:++- Emitting source events from browser runtime code+- Sending events through tRPC+- Keeping UI paths non-blocking++See [src/services/agentSignal.ts](../../src/services/agentSignal.ts) and [src/store/chat/slices/aiChat/actions/agentSignalBridge.ts](../../src/store/chat/slices/aiChat/actions/agentSignalBridge.ts).++Use server services for:++- Feature gating+- DB access+- Workflow handoff+- Policy/runtime execution+- Redis or in-memory dedupe+- Observability persistence++See [src/server/services/agentSignal/emitter.ts](../../src/server/services/agentSignal/emitter.ts), [src/server/services/agentSignal/orchestrator.ts](../../src/server/services/agentSignal/orchestrator.ts), and [src/server/services/agentSignal/sources/index.ts](../../src/server/services/agentSignal/sources/index.ts).++## Supported Source Events++| Source event | Constant | Primary producer | Payload intent |+| ------------------------------ | ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |+| `agent.execution.completed` | `AGENT_SIGNAL_SOURCE_TYPES.agentExecutionCompleted` | [Agent Runtime](../../src/server/services/agentRuntime/AgentRuntimeService.ts) | Server agent execution completed with operation, step, topic, and context metadata. |+| `agent.execution.failed` | `AGENT_SIGNAL_SOURCE_TYPES.agentExecutionFailed` | [Agent Runtime](../../src/server/services/agentRuntime/AgentRuntimeService.ts) | Server agent execution failed with operation, reason, error, topic, and context metadata. |+| `agent.user.message` | `AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage` | [Workflow bridge](../../src/server/workflows/agentSignal/run.ts), [Bot router](../../src/server/services/bot/BotMessageRouter.ts) | User feedback/message content that policies can analyze for memory, prompt, document, or skill changes. |+| `bot.message.merged` | `AGENT_SIGNAL_SOURCE_TYPES.botMessageMerged` | [Bot router](../../src/server/services/bot/BotMessageRouter.ts) | Bot-platform message content merged into a conversation scope. |+| `client.gateway.error` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayError` | [Gateway event handler](../../src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts) | Browser gateway error for a client-side runtime operation. |+| `client.gateway.runtime_end` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayRuntimeEnd` | [Gateway event handler](../../src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts) | Browser gateway runtime finished for a client-side operation. |+| `client.gateway.step_complete` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStepComplete` | [Gateway event handler](../../src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts) | Browser gateway step completed with operation and step index metadata. |+| `client.gateway.stream_start` | `AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStreamStart` | [Gateway event handler](../../src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts) | Browser gateway stream started with operation and first step metadata. |+| `client.runtime.complete` | `AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeComplete` | [Chat streaming executor](../../src/store/chat/slices/aiChat/actions/streamingExecutor.ts) | Browser chat runtime completed with operation, topic, thread, and status metadata. |+| `client.runtime.start` | `AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart` | [Chat streaming executor](../../src/store/chat/slices/aiChat/actions/streamingExecutor.ts) | Browser chat runtime started; workflow may bridge this into `agent.user.message` with serialized context. |+| `runtime.after_step` | `AGENT_SIGNAL_SOURCE_TYPES.runtimeAfterStep` | [Agent Runtime](../../src/server/services/agentRuntime/AgentRuntimeService.ts) | Server runtime step finished with operation, step index, topic, and context metadata. |+| `runtime.before_step` | `AGENT_SIGNAL_SOURCE_TYPES.runtimeBeforeStep` | [Agent Runtime](../../src/server/services/agentRuntime/AgentRuntimeService.ts) | Server runtime step is about to run with operation, step index, topic, and context metadata. |++`AGENT_SIGNAL_CLIENT_SOURCE_TYPES` is the allow-list for browser-originated events accepted by [src/server/routers/lambda/agentSignal.ts](../../src/server/routers/lambda/agentSignal.ts). It currently includes only the `client.*` source events.++## Source Event Modules++- [Source event API](src/source/sourceEvent.ts): input and normalized event types plus `createSourceEvent`.+- [Source type catalog](src/source/sourceTypes.ts): constants, payload map, source variants, and the client allow-list.+- [Scope-key helpers](src/source/scopeKey.ts): topic, bot thread, task, agent/user, and user scope-key builders.+- [Browser service facade](../../src/services/agentSignal.ts): tRPC client wrapper for browser code.+- [Browser bridge](../../src/store/chat/slices/aiChat/actions/agentSignalBridge.ts): feature-gated non-blocking browser emission helper.+- [Lambda router](../../src/server/routers/lambda/agentSignal.ts): authenticated browser ingress and client source type validation.+- [Server emitter](../../src/server/services/agentSignal/emitter.ts): feature-gated immediate execution or workflow handoff.+- [Server orchestrator](../../src/server/services/agentSignal/orchestrator.ts): source event execution through policies, runtime, and observability.+- [Source dedupe store](../../src/server/services/agentSignal/sources/index.ts): source event dedupe, scope locking, and source node rendering.+- [Workflow trigger](../../src/server/workflows/agentSignal/index.ts): async Upstash Workflow handoff.+- [Workflow runner](../../src/server/workflows/agentSignal/run.ts): workflow execution and client runtime bridge.+- [Agent Runtime](../../src/server/services/agentRuntime/AgentRuntimeService.ts): server runtime source event producers.+- [Chat](../../src/store/chat/slices/aiChat/actions/streamingExecutor.ts): browser chat runtime source event producer.+- [Gateway event handler](../../src/store/chat/slices/aiChat/actions/gatewayEventHandler.ts): browser gateway source event producer.+- [Bot router](../../src/server/services/bot/BotMessageRouter.ts): bot-platform source event producer.++## Adding A Source Event++1. Add the constant and payload shape in [src/source/sourceTypes.ts](src/source/sourceTypes.ts).+2. Add a renderer in [src/server/services/agentSignal/sources/renderers](../../src/server/services/agentSignal/sources/renderers) if the generic payload needs normalization before becoming an `AgentSignalSource`.+3. Register the renderer in [src/server/services/agentSignal/sources/buildSource.ts](../../src/server/services/agentSignal/sources/buildSource.ts).+4. Add the source to `AGENT_SIGNAL_CLIENT_SOURCE_TYPES` only when browser code should be allowed to emit it through the lambda router.+5. Add focused tests for source event creation, router validation, renderer normalization, or workflow bridging depending on the new producer path.++Keep source events stable. Source type strings are persisted in traces, dedupe keys, and workflow payloads.diff --git a/packages/agent-signal/package.json b/packages/agent-signal/package.jsonindex 3912ca96a9c..fd11895eb62 100644--- a/packages/agent-signal/package.json+++ b/packages/agent-signal/package.json@@ -8,6 +8,10 @@".": {"types": "./src/index.ts","default": "./src/index.ts"+ },+ "./source": {+ "types": "./src/source/index.ts",+ "default": "./src/source/index.ts"}},"main": "src/index.ts",diff --git a/packages/agent-signal/src/index.ts b/packages/agent-signal/src/index.tsindex 46ce0549d36..95997f3bb35 100644--- a/packages/agent-signal/src/index.ts+++ b/packages/agent-signal/src/index.ts@@ -2,6 +2,7 @@ export * from './base/builders';export * from './base/guards';export * from './base/registries';export * from './base/types';+export * from './source';export {type AgentSignalBuiltInSignalPayloadMap,type AgentSignalBuiltInSignalVariant,diff --git a/packages/agent-signal/src/source/index.ts b/packages/agent-signal/src/source/index.tsnew file mode 100644index 00000000000..1b3131b5a2d--- /dev/null+++ b/packages/agent-signal/src/source/index.ts@@ -0,0 +1,3 @@+export * from './scopeKey';+export * from './sourceEvent';+export * from './sourceTypes';diff --git a/packages/agent-signal/src/source/scopeKey.ts b/packages/agent-signal/src/source/scopeKey.tsnew file mode 100644index 00000000000..d59901e4299--- /dev/null+++ b/packages/agent-signal/src/source/scopeKey.ts@@ -0,0 +1,133 @@+import type { AgentSignalScope } from '../base/types';++/**+ * Bot-thread identity used to route source events that originate outside a LobeChat topic.+ */+export interface AgentSignalBotScopeKeyInput {+ /** Application identifier from the external bot platform. */+ applicationId: string;+ /** Platform identifier, such as `discord` or `slack`. */+ platform: string;+ /** Thread or channel conversation identifier from the external platform. */+ platformThreadId: string;+}++/**+ * Producer metadata used to derive a stable source-event scope key.+ */+export interface AgentSignalProducerScopeInput {+ /** Optional external application identifier for bot-originated events. */+ applicationId?: string;+ /** Optional external platform identifier for bot-originated events. */+ platform?: string;+ /** Optional external thread identifier for bot-originated events. */+ platformThreadId?: string;+ /** Optional LobeChat topic identifier. Takes precedence over bot-thread metadata. */+ topicId?: string;+}++/**+ * Task identity used when an AgentSignal chain is scoped to async task execution.+ */+export interface AgentSignalTaskScopeKeyInput {+ /** Stable task identifier. */+ taskId: string;+}++/**+ * Topic identity used when an AgentSignal chain is scoped to one LobeChat topic.+ */+export interface AgentSignalTopicScopeKeyInput {+ /** Stable LobeChat topic identifier. */+ topicId: string;+}++/**+ * Agent/user identity used when no narrower topic or task scope is available.+ */+export interface AgentSignalUserAgentScopeKeyInput {+ /** Stable assistant or agent identifier. */+ agentId: string;+ /** Stable user identifier. */+ userId: string;+}++/**+ * User identity used as the broadest authenticated AgentSignal scope.+ */+export interface AgentSignalUserScopeKeyInput {+ /** Stable user identifier. */+ userId: string;+}++const joinScopeKey = (prefix: string, ...parts: string[]) => `${prefix}:${parts.join(':')}`;++const pickString = (input: Record<string, unknown>, key: string) => {+ const value = input[key];++ return typeof value === 'string' ? value : undefined;+};++/**+ * Builds stable scope keys for AgentSignal source events and runtime chains.+ *+ * Use when:+ * - Normalizing source events before dedupe or workflow handoff+ * - Routing runtime chains into topic, bot-thread, task, or user lanes+ *+ * Expects:+ * - Input identifiers are already trusted by the caller+ *+ * Returns:+ * - A deterministic scope key string+ */+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;++/**+ * Resolves the default scope key for a source-event payload.+ *+ * Before:+ * - `{ topicId: "topic-1", platform: "discord" }`+ *+ * After:+ * - `"topic:topic-1"`+ */+export const getSourceEventScopeKey = (input: Record<string, unknown>) => {+ return AgentSignalScopeKey.fromProducerInput({+ applicationId: pickString(input, 'applicationId'),+ platform: pickString(input, 'platform'),+ platformThreadId: pickString(input, 'platformThreadId'),+ topicId: pickString(input, 'topicId'),+ });+};diff --git a/packages/agent-signal/src/source/sourceEvent.test.ts b/packages/agent-signal/src/source/sourceEvent.test.tsnew file mode 100644index 00000000000..c4e7eeb9dd6--- /dev/null+++ b/packages/agent-signal/src/source/sourceEvent.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from 'vitest';++import { AGENT_SIGNAL_SOURCE_TYPES, createSourceEvent, getSourceEventScopeKey } from './index';++describe('AgentSignal source events', () => {+ /**+ * @example+ * createSourceEvent({ sourceType: 'bot.message.merged', sourceId: 'src-1', payload })+ * returns a normalized source event with a bot thread scope key.+ */+ it('creates a normalized source event with a derived bot thread scope key', () => {+ const event = createSourceEvent({+ payload: {+ applicationId: 'discord-app',+ message: 'hello',+ platform: 'discord',+ platformThreadId: 'thread-1',+ },+ sourceId: 'src-1',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.botMessageMerged,+ timestamp: 123,+ });++ expect(event).toEqual({+ payload: {+ applicationId: 'discord-app',+ message: 'hello',+ platform: 'discord',+ platformThreadId: 'thread-1',+ },+ scopeKey: 'bot:discord:discord-app:thread-1',+ sourceId: 'src-1',+ sourceType: 'bot.message.merged',+ timestamp: 123,+ });+ });++ /**+ * @example+ * getSourceEventScopeKey({ topicId: 'topic-1' }) returns 'topic:topic-1'.+ */+ it('prefers topic scope over bot thread scope', () => {+ expect(+ getSourceEventScopeKey({+ applicationId: 'discord-app',+ platform: 'discord',+ platformThreadId: 'thread-1',+ topicId: 'topic-1',+ }),+ ).toBe('topic:topic-1');+ });+});diff --git a/packages/agent-signal/src/source/sourceEvent.ts b/packages/agent-signal/src/source/sourceEvent.tsnew file mode 100644index 00000000000..ade06d4323c--- /dev/null+++ b/packages/agent-signal/src/source/sourceEvent.ts@@ -0,0 +1,65 @@+import { getSourceEventScopeKey } from './scopeKey';+import type { AgentSignalSourcePayloadMap, AgentSignalSourceType } from './sourceTypes';++type AgentSignalSourceEventPayload<TSourceType extends AgentSignalSourceType> =+ AgentSignalSourcePayloadMap[TSourceType];++/**+ * Caller-provided data for one AgentSignal source event.+ *+ * @param TSourceType - Source type whose payload shape should be enforced.+ */+export interface AgentSignalSourceEventInput<+ TSourceType extends AgentSignalSourceType = AgentSignalSourceType,+> {+ /** Source-type-specific payload that describes what happened. */+ payload: AgentSignalSourceEventPayload<TSourceType>;+ /** Optional explicit scope key. Defaults to a key derived from payload routing fields. */+ scopeKey?: string;+ /** Stable producer event id used for dedupe. */+ sourceId: string;+ /** Source event type identifier. */+ sourceType: TSourceType;+ /** Optional event timestamp in milliseconds. Defaults to the current time. */+ timestamp?: number;+}++/**+ * Normalized AgentSignal source event ready for persistence, dedupe, or workflow handoff.+ *+ * @param TSourceType - Source type whose payload shape should be enforced.+ */+export interface AgentSignalSourceEvent<+ TSourceType extends AgentSignalSourceType = AgentSignalSourceType,+> extends Omit<AgentSignalSourceEventInput<TSourceType>, 'scopeKey' | 'timestamp'> {+ /** Stable scope key used to coordinate dedupe, workflow, and runtime lanes. */+ scopeKey: string;+ /** Event timestamp in milliseconds. */+ timestamp: number;+}++/**+ * Creates a normalized AgentSignal source event from caller input.+ *+ * Use when:+ * - Browser or server producers need the same event shape before handoff+ * - Callers want scope key and timestamp defaults without importing server services+ *+ * Expects:+ * - `sourceId` is stable for the producer event+ * - `payload` matches `sourceType`+ *+ * Returns:+ * - A source event with `scopeKey` and `timestamp` filled in+ */+export const createSourceEvent = <TSourceType extends AgentSignalSourceType>(+ input: AgentSignalSourceEventInput<TSourceType>,+): AgentSignalSourceEvent<TSourceType> => {+ return {+ payload: input.payload,+ scopeKey: input.scopeKey ?? getSourceEventScopeKey(input.payload),+ sourceId: input.sourceId,+ sourceType: input.sourceType,+ timestamp: input.timestamp ?? Date.now(),+ };+};diff --git a/src/server/services/agentSignal/sourceTypes.ts b/packages/agent-signal/src/source/sourceTypes.tssimilarity index 79%rename from src/server/services/agentSignal/sourceTypes.tsrename to packages/agent-signal/src/source/sourceTypes.tsindex c1f94e0c060..b54869080b5 100644--- a/src/server/services/agentSignal/sourceTypes.ts+++ b/packages/agent-signal/src/source/sourceTypes.ts@@ -1,6 +1,6 @@-import type { AgentSignalSource, BaseSource } from '@lobechat/agent-signal';+import type { AgentSignalSource, BaseSource } from '../base/types';-/** Server-owned AgentSignal source type identifiers. */+/** AgentSignal source type identifiers shared by browser producers and server executors. */export const AGENT_SIGNAL_SOURCE_TYPES = {agentExecutionCompleted: 'agent.execution.completed',agentExecutionFailed: 'agent.execution.failed',@@ -18,10 +18,10 @@ export const AGENT_SIGNAL_SOURCE_TYPES = {type ValueOf<TValue> = TValue[keyof TValue];-/** Server-owned AgentSignal source type union. */+/** AgentSignal source type union derived from {@link AGENT_SIGNAL_SOURCE_TYPES}. */export type AgentSignalSourceType = ValueOf<typeof AGENT_SIGNAL_SOURCE_TYPES>;-/** Server-owned AgentSignal source payloads keyed by source type. */+/** AgentSignal source payloads keyed by source type. */export interface AgentSignalSourcePayloadMap {[AGENT_SIGNAL_SOURCE_TYPES.agentExecutionCompleted]: {agentId?: string;@@ -123,7 +123,7 @@ export interface AgentSignalSourcePayloadMap {};}-/** Server-owned AgentSignal source variant. */+/** AgentSignal source variant with source-type-specific payload typing. */export type AgentSignalSourceVariant<TSourceType extends AgentSignalSourceType = AgentSignalSourceType,> = BaseSource & {@@ -131,50 +131,50 @@ export type AgentSignalSourceVariant<sourceType: TSourceType;};-/** Server-owned AgentSignal source union. */+/** Union of every known AgentSignal source variant. */export type AgentSignalSourceVariants = {[TSourceType in AgentSignalSourceType]: AgentSignalSourceVariant<TSourceType>;}[AgentSignalSourceType];-/** Server-owned alias retained for user-message sources. */+/** User-message source variant. */export type SourceAgentUserMessage = AgentSignalSourceVariant<'agent.user.message'>;-/** Server-owned alias retained for execution-completed sources. */+/** Agent execution-completed source variant. */export type SourceAgentExecutionCompleted = AgentSignalSourceVariant<'agent.execution.completed'>;-/** Server-owned alias retained for execution-failed sources. */+/** Agent execution-failed source variant. */export type SourceAgentExecutionFailed = AgentSignalSourceVariant<'agent.execution.failed'>;-/** Server-owned alias retained for before-step runtime sources. */+/** Runtime before-step source variant. */export type SourceRuntimeBeforeStep = AgentSignalSourceVariant<'runtime.before_step'>;-/** Server-owned alias retained for after-step runtime sources. */+/** Runtime after-step source variant. */export type SourceRuntimeAfterStep = AgentSignalSourceVariant<'runtime.after_step'>;-/** Server-owned alias retained for merged bot-message sources. */+/** Bot-message merged source variant. */export type SourceBotMessageMerged = AgentSignalSourceVariant<'bot.message.merged'>;-/** Server-owned alias retained for client gateway stream-start sources. */+/** Client gateway stream-start source variant. */export type SourceClientGatewayStreamStart =AgentSignalSourceVariant<'client.gateway.stream_start'>;-/** Server-owned alias retained for client gateway step-complete sources. */+/** Client gateway step-complete source variant. */export type SourceClientGatewayStepComplete =AgentSignalSourceVariant<'client.gateway.step_complete'>;-/** Server-owned alias retained for client gateway runtime-end sources. */+/** Client gateway runtime-end source variant. */export type SourceClientGatewayRuntimeEnd = AgentSignalSourceVariant<'client.gateway.runtime_end'>;-/** Server-owned alias retained for client gateway error sources. */+/** Client gateway error source variant. */export type SourceClientGatewayError = AgentSignalSourceVariant<'client.gateway.error'>;-/** Server-owned alias retained for client runtime-start sources. */+/** Client runtime-start source variant. */export type SourceClientRuntimeStart = AgentSignalSourceVariant<'client.runtime.start'>;-/** Server-owned alias retained for client runtime-complete sources. */+/** Client runtime-complete source variant. */export type SourceClientRuntimeComplete = AgentSignalSourceVariant<'client.runtime.complete'>;-/** Client-originated source types accepted by the authenticated browser edge. */+/** Source types accepted by browser producers through the authenticated edge. */export const AGENT_SIGNAL_CLIENT_SOURCE_TYPES = [AGENT_SIGNAL_SOURCE_TYPES.clientGatewayError,AGENT_SIGNAL_SOURCE_TYPES.clientGatewayRuntimeEnd,@@ -184,7 +184,19 @@ export const AGENT_SIGNAL_CLIENT_SOURCE_TYPES = [AGENT_SIGNAL_SOURCE_TYPES.clientRuntimeStart,] as const satisfies readonly Extract<AgentSignalSourceType, `client.${string}`>[];-/** Narrows one generic source node to the server-owned source catalog. */+/**+ * Narrows a generic source node to the shared AgentSignal source catalog.+ *+ * Use when:+ * - Runtime middleware receives generic source nodes+ * - Callers need source-type-specific payload typing after validation+ *+ * Expects:+ * - `source.sourceType` is a string-like type identifier+ *+ * Returns:+ * - Whether the source belongs to the built-in AgentSignal source catalog+ */export const isAgentSignalKnownSource = (source: AgentSignalSource,): source is AgentSignalSourceVariants => {diff --git a/packages/agent-signal/vitest.config.mts b/packages/agent-signal/vitest.config.mtsnew file mode 100644index 00000000000..63187beb93a--- /dev/null+++ b/packages/agent-signal/vitest.config.mts@@ -0,0 +1,8 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ environment: 'node',+ include: ['src/**/*.{test,spec}.?(c|m)[jt]s?(x)'],+ },+});diff --git a/src/server/routers/lambda/agentSignal.ts b/src/server/routers/lambda/agentSignal.tsindex a034d8b6062..60d922fcf81 100644--- a/src/server/routers/lambda/agentSignal.ts+++ b/src/server/routers/lambda/agentSignal.ts@@ -1,12 +1,12 @@+import {+ AGENT_SIGNAL_CLIENT_SOURCE_TYPES,+ type AgentSignalSourceEventInput,+} from '@lobechat/agent-signal/source';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');@@ -14,15 +14,7 @@ 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];+type ClientSourceEventInput = AgentSignalSourceEventInput<ClientSourceType>;export const agentSignalRouter = router({emitSourceEvent: agentSignalProcedurediff --git a/src/server/services/agentSignal/emitter.ts b/src/server/services/agentSignal/emitter.tsindex c8b13b0d66b..d0df012b2f6 100644--- a/src/server/services/agentSignal/emitter.ts+++ b/src/server/services/agentSignal/emitter.ts@@ -1,4 +1,16 @@import type { DedupedSourceEventResult } from '@lobechat/agent-signal';+import {+ type AgentSignalSourceEventInput as SharedAgentSignalSourceEventInput,+ type AgentSignalSourceType,+ createSourceEvent,+ getSourceEventScopeKey,+ type SourceAgentExecutionCompleted,+ type SourceAgentExecutionFailed,+ type SourceAgentUserMessage,+ type SourceBotMessageMerged,+ type SourceRuntimeAfterStep,+ type SourceRuntimeBeforeStep,+} from '@lobechat/agent-signal/source';import debug from 'debug';import { getServerDB } from '@/database/server';@@ -8,18 +20,6 @@ import { AgentSignalWorkflow } from '@/server/workflows/agentSignal';import { isAgentSignalEnabledForUser } from './featureGate';import type { GeneratedAgentSignalEmissionResult } from './orchestrator';import type { CreateDefaultAgentSignalPoliciesOptions } from './policies';-import { AgentSignalScopeKey } from './scopeKey';-import type { EmitSourceEventInput } from './sources';-import type {- AgentSignalSourcePayloadMap,- AgentSignalSourceType,- SourceAgentExecutionCompleted,- SourceAgentExecutionFailed,- SourceAgentUserMessage,- SourceBotMessageMerged,- SourceRuntimeAfterStep,- SourceRuntimeBeforeStep,-} from './sourceTypes';const log = debug('lobe-server:agent-signal:service');@@ -35,18 +35,9 @@ type RuntimeProducerSourceType =| 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;-}+export type AgentSignalSourceEventInput<TSourceType extends AgentSignalSourceType> =+ SharedAgentSignalSourceEventInput<TSourceType>;/** One AgentSignal emission execution option set. */export interface AgentSignalPolicyOptionOverrides extends Omit<@@ -81,23 +72,7 @@ export type UserMessageAgentSignalSourceInput = AgentSignalSourceEventInput<SourceAgentUserMessage['sourceType']>;-export interface AgentSignalSourceEnvelope extends Omit<- AgentSignalSourceEventInput<AgentSignalSourceType>,- 'scopeKey' | 'timestamp'-> {- scopeKey: string;- timestamp: number;-}--export 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,- });-};+export const resolveSourceScopeKey = getSourceEventScopeKey;const withSelfIterationPolicy = (options: AgentSignalEmitOptions,@@ -169,13 +144,7 @@ export const enqueueAgentSignalSourceEvent = async <TSourceType extends AgentSig};}- const sourceEvent = {- payload: input.payload,- scopeKey: input.scopeKey ?? resolveSourceScopeKey(input.payload),- sourceId: input.sourceId,- sourceType: input.sourceType,- timestamp: input.timestamp ?? Date.now(),- };+ const sourceEvent = createSourceEvent(input);log('Enqueueing source event payload=%O', {agentId: context.agentId,diff --git a/src/server/services/agentSignal/orchestrator.ts b/src/server/services/agentSignal/orchestrator.tsindex 7a58264fbdd..1c812fed914 100644--- a/src/server/services/agentSignal/orchestrator.ts+++ b/src/server/services/agentSignal/orchestrator.ts@@ -7,13 +7,12 @@ import type {GeneratedSourceEventResult,SignalPlan,} from '@lobechat/agent-signal';+import { type AgentSignalSourceType, createSourceEvent } from '@lobechat/agent-signal/source';import {type AgentSignalEmitOptions,type AgentSignalExecutionContext,- type AgentSignalSourceEnvelope,type AgentSignalSourceEventInput,- resolveSourceScopeKey,} from './emitter';import { projectAgentSignalObservability } from './observability/projector';import { persistAgentSignalObservability } from './observability/store';@@ -21,7 +20,6 @@ import { createDefaultAgentSignalPolicies } from './policies';import type { RuntimeGuardBackend } from './runtime/AgentSignalRuntime';import { createAgentSignalRuntime } from './runtime/AgentSignalRuntime';import { emitSourceEvent } from './sources';-import type { AgentSignalSourceType } from './sourceTypes';import type { AgentSignalSourceEventStore } from './store/types';export { createAgentSignalRuntime } from './runtime/AgentSignalRuntime';@@ -92,13 +90,7 @@ const executeAgentSignalSourceEventCore = async <TSourceType extends AgentSignaloptions: ExecuteAgentSignalSourceEventOptions = {},): Promise<DedupedSourceEventResult | GeneratedAgentSignalEmissionResult | undefined> => {try {- const sourceEvent: AgentSignalSourceEnvelope = {- payload: input.payload,- scopeKey: input.scopeKey ?? resolveSourceScopeKey(input.payload),- sourceId: input.sourceId,- sourceType: input.sourceType,- timestamp: input.timestamp ?? Date.now(),- };+ const sourceEvent = createSourceEvent(input);const emission = await emitSourceEvent(sourceEvent,diff --git a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.tsindex 8778fcccfe5..db733d11a69 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/__tests__/feedbackSatisfaction.test.ts@@ -1,4 +1,5 @@// @vitest-environment node+import type { SourceAgentUserMessage } from '@lobechat/agent-signal/source';import { RequestTrigger } from '@lobechat/types';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -6,7 +7,6 @@ import type { LobeChatDatabase } from '@/database/type';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { createRuntimeProcessorContext } from '../../../runtime/context';-import type { SourceAgentUserMessage } from '../../../sourceTypes';import { createFeedbackSatisfactionJudgeProcessor } from '../feedbackSatisfaction';vi.mock('@/server/modules/ModelRuntime', () => ({diff --git a/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts b/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.tsindex f272a41703f..d3225ed8fa7 100644--- a/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts+++ b/src/server/services/agentSignal/policies/analyzeIntent/feedbackSatisfaction.ts@@ -1,4 +1,8 @@import type { RuntimeProcessorResult } from '@lobechat/agent-signal';+import {+ AGENT_SIGNAL_SOURCE_TYPES,+ type SourceAgentUserMessage,+} from '@lobechat/agent-signal/source';import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';import type { GenerateObjectSchema } from '@lobechat/model-runtime';import { chainAgentSignalAnalyzeIntentFeedbackSatisfaction } from '@lobechat/prompts';@@ -10,7 +14,6 @@ import type { LobeChatDatabase } from '@/database/type';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { defineSourceHandler } from '../../runtime/middleware';-import { AGENT_SIGNAL_SOURCE_TYPES, type SourceAgentUserMessage } from '../../sourceTypes';import {AGENT_SIGNAL_POLICY_SIGNAL_TYPES,type AgentSignalFeedbackEvidence,diff --git a/src/server/services/agentSignal/policies/types.ts b/src/server/services/agentSignal/policies/types.tsindex 670facf94aa..c3101d6013d 100644--- a/src/server/services/agentSignal/policies/types.ts+++ b/src/server/services/agentSignal/policies/types.ts@@ -1,11 +1,10 @@import type { BaseAction, BaseSignal } from '@lobechat/agent-signal';-import type {SourceAgentExecutionCompleted,SourceAgentExecutionFailed,SourceRuntimeAfterStep,SourceRuntimeBeforeStep,-} from '../sourceTypes';+} from '@lobechat/agent-signal/source';/** Server-owned built-in AgentSignal policy identifiers. */export const AGENT_SIGNAL_POLICIES = {diff --git a/src/server/services/agentSignal/runtime/middleware.ts b/src/server/services/agentSignal/runtime/middleware.tsindex b41f792797e..70cfaf97007 100644--- a/src/server/services/agentSignal/runtime/middleware.ts+++ b/src/server/services/agentSignal/runtime/middleware.ts@@ -1,4 +1,8 @@import type { AgentSignalSource, BaseAction, BaseSignal } from '@lobechat/agent-signal';+import type {+ AgentSignalSourceType,+ AgentSignalSourceVariant,+} from '@lobechat/agent-signal/source';import type {AgentSignalPolicyActionType,@@ -6,7 +10,6 @@ import type {AgentSignalPolicySignalType,AgentSignalPolicySignalVariant,} from '../policies/types';-import type { AgentSignalSourceType, AgentSignalSourceVariant } from '../sourceTypes';import type {AgentSignalSchedulerHandle,AgentSignalSchedulerHandler,diff --git a/src/server/services/agentSignal/runtime/scope.ts b/src/server/services/agentSignal/runtime/scope.tsindex b89affbbc9c..98d75f3f21a 100644--- a/src/server/services/agentSignal/runtime/scope.ts+++ b/src/server/services/agentSignal/runtime/scope.ts@@ -1,6 +1,8 @@import type { AgentSignalScope } from '@lobechat/agent-signal';--import { type AgentSignalProducerScopeInput, AgentSignalScopeKey } from '../scopeKey';+import {+ type AgentSignalProducerScopeInput,+ AgentSignalScopeKey,+} from '@lobechat/agent-signal/source';/** Resolves the canonical runtime scope key for one source scope. */export const resolveRuntimeScopeKey = (scope: AgentSignalScope) => {@@ -8,7 +10,7 @@ export const resolveRuntimeScopeKey = (scope: AgentSignalScope) => {};/**- * Resolves one stable scope key for producers that emit raw source envelopes.+ * Resolves one stable scope key for producers that emit raw source events.** Before:* - `{ topicId: 'topic-1' }`diff --git a/src/server/services/agentSignal/scopeKey.ts b/src/server/services/agentSignal/scopeKey.tsdeleted file mode 100644index 0816bedc993..00000000000--- a/src/server/services/agentSignal/scopeKey.ts+++ /dev/null@@ -1,67 +0,0 @@-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/sources/buildSource.ts b/src/server/services/agentSignal/sources/buildSource.tsindex 0014181ed41..8318061e868 100644--- a/src/server/services/agentSignal/sources/buildSource.ts+++ b/src/server/services/agentSignal/sources/buildSource.ts@@ -21,7 +21,7 @@ const sourceRenderers = new Map<AgentSignalSource['sourceType'], SourceRenderer>** Use when:* - Server producers hand over loosely-shaped payloads- * - The runtime needs one stable source envelope before dedupe/window handling+ * - The runtime needs one stable source event before dedupe/window handling** Expects:* - `input.sourceType` selects the matching renderer when one existsdiff --git a/src/server/services/agentSignal/sources/renderers/agentExecutionCompleted.ts b/src/server/services/agentSignal/sources/renderers/agentExecutionCompleted.tsindex dca77316c33..ffc96e322e5 100644--- a/src/server/services/agentSignal/sources/renderers/agentExecutionCompleted.ts+++ b/src/server/services/agentSignal/sources/renderers/agentExecutionCompleted.ts@@ -1,4 +1,5 @@-import { AGENT_SIGNAL_SOURCE_TYPES } from '../../sourceTypes';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import type { SourceRenderer } from '../types';import { createBaseSource } from './shared';diff --git a/src/server/services/agentSignal/sources/renderers/agentExecutionFailed.ts b/src/server/services/agentSignal/sources/renderers/agentExecutionFailed.tsindex 7a88b7b7a5f..255ac429d8c 100644--- a/src/server/services/agentSignal/sources/renderers/agentExecutionFailed.ts+++ b/src/server/services/agentSignal/sources/renderers/agentExecutionFailed.ts@@ -1,4 +1,5 @@-import { AGENT_SIGNAL_SOURCE_TYPES } from '../../sourceTypes';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import type { SourceRenderer } from '../types';import { createBaseSource } from './shared';diff --git a/src/server/services/agentSignal/sources/renderers/agentUserMessage.ts b/src/server/services/agentSignal/sources/renderers/agentUserMessage.tsindex 5fe0350ce23..362f0cfe3f9 100644--- a/src/server/services/agentSignal/sources/renderers/agentUserMessage.ts+++ b/src/server/services/agentSignal/sources/renderers/agentUserMessage.ts@@ -1,4 +1,5 @@-import { AGENT_SIGNAL_SOURCE_TYPES } from '../../sourceTypes';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import type { SourceRenderer } from '../types';import { createBaseSource } from './shared';diff --git a/src/server/services/agentSignal/sources/renderers/runtimeAfterStep.ts b/src/server/services/agentSignal/sources/renderers/runtimeAfterStep.tsindex 35c9a183a8f..10396d36ae3 100644--- a/src/server/services/agentSignal/sources/renderers/runtimeAfterStep.ts+++ b/src/server/services/agentSignal/sources/renderers/runtimeAfterStep.ts@@ -1,4 +1,5 @@-import { AGENT_SIGNAL_SOURCE_TYPES } from '../../sourceTypes';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import type { SourceRenderer } from '../types';import { createBaseSource } from './shared';diff --git a/src/server/services/agentSignal/sources/renderers/runtimeBeforeStep.ts b/src/server/services/agentSignal/sources/renderers/runtimeBeforeStep.tsindex d148ed8a352..e0c09719db9 100644--- a/src/server/services/agentSignal/sources/renderers/runtimeBeforeStep.ts+++ b/src/server/services/agentSignal/sources/renderers/runtimeBeforeStep.ts@@ -1,4 +1,5 @@-import { AGENT_SIGNAL_SOURCE_TYPES } from '../../sourceTypes';+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import type { SourceRenderer } from '../types';import { createBaseSource } from './shared';diff --git a/src/server/workflows/agentSignal/__tests__/run.test.ts b/src/server/workflows/agentSignal/__tests__/run.test.tsindex 9377597e5ae..f078735340e 100644--- a/src/server/workflows/agentSignal/__tests__/run.test.ts+++ b/src/server/workflows/agentSignal/__tests__/run.test.ts@@ -1,13 +1,13 @@// @vitest-environment node+import {+ AGENT_SIGNAL_SOURCE_TYPES,+ type AgentSignalSourceEvent,+ type SourceAgentUserMessage,+} from '@lobechat/agent-signal/source';import { agents, messages, threads, topics, users } from '@lobechat/database/schemas';import { getTestDB } from '@lobechat/database/test-utils';import { describe, expect, it, vi } from 'vitest';-import type { AgentSignalSourceEnvelope } from '@/server/services/agentSignal';-import {- AGENT_SIGNAL_SOURCE_TYPES,- type SourceAgentUserMessage,-} from '@/server/services/agentSignal/sourceTypes';import {runAgentSignalWorkflow,type RunAgentSignalWorkflowDeps,@@ -32,7 +32,7 @@ describe('runAgentSignalWorkflow', () => {const topicId = `topic_${uuid()}`;const parentMessageId = `msg_${uuid()}`;const baseTimestamp = new Date('2026-01-01T00:00:00.000Z').getTime();- let capturedSourceEvent: AgentSignalSourceEnvelope | undefined;+ let capturedSourceEvent: AgentSignalSourceEvent | undefined;await db.insert(users).values({ id: userId });@@ -177,7 +177,7 @@ describe('runAgentSignalWorkflow', () => {const now = Date.now();const executeSourceEvent: NonNullable<RunAgentSignalWorkflowDeps['executeSourceEvent']> = vi.fn(async (sourceEvent) => {- capturedSourceEvent = sourceEvent as AgentSignalSourceEnvelope;+ capturedSourceEvent = sourceEvent as AgentSignalSourceEvent;return undefined;},);@@ -251,7 +251,7 @@ describe('runAgentSignalWorkflow', () => {const otherThreadId = `thread_${uuid()}`;const feedbackMessageId = `msg_${uuid()}`;const baseTimestamp = new Date('2026-01-02T00:00:00.000Z').getTime();- let capturedSourceEvent: AgentSignalSourceEnvelope | undefined;+ let capturedSourceEvent: AgentSignalSourceEvent | undefined;await db.insert(users).values({ id: userId });@@ -365,7 +365,7 @@ describe('runAgentSignalWorkflow', () => {const executeSourceEvent: NonNullable<RunAgentSignalWorkflowDeps['executeSourceEvent']> = vi.fn(async (sourceEvent) => {- capturedSourceEvent = sourceEvent as AgentSignalSourceEnvelope;+ capturedSourceEvent = sourceEvent as AgentSignalSourceEvent;return undefined;},);diff --git a/src/server/workflows/agentSignal/index.ts b/src/server/workflows/agentSignal/index.tsindex 839da2aae01..c39ab6fa4d8 100644--- a/src/server/workflows/agentSignal/index.ts+++ b/src/server/workflows/agentSignal/index.ts@@ -1,12 +1,9 @@+import type { AgentSignalSourceEvent, AgentSignalSourceType } from '@lobechat/agent-signal/source';import debug from 'debug';import { appEnv } from '@/envs/app';import { injectActiveTraceHeaders } from '@/libs/observability/traceparent';import { workflowClient } from '@/libs/qstash';-import type {- AgentSignalSourcePayloadMap,- AgentSignalSourceType,-} from '@/server/services/agentSignal/sourceTypes';const log = debug('lobe-server:workflows:agent-signal');@@ -20,19 +17,10 @@ const normalizeFlowControlKeySegment = (value: string) => {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;-}+> extends AgentSignalSourceEvent<TSourceType> {}/** One Upstash workflow payload for Agent Signal execution. */export interface AgentSignalWorkflowRunPayload {@@ -56,7 +44,7 @@ const getWorkflowUrl = (path: string): string => {** Use when:* - Server-owned ingress wants to hand off execution to Upstash Workflow- * - The caller already normalized the source event envelope+ * - The caller already normalized the source event** Expects:* - `sourceEvent.scopeKey` is stable for the policy coordination scopediff --git a/src/server/workflows/agentSignal/run.ts b/src/server/workflows/agentSignal/run.tsindex 0d89f67d6cd..75f8352895a 100644--- a/src/server/workflows/agentSignal/run.ts+++ b/src/server/workflows/agentSignal/run.ts@@ -1,3 +1,10 @@+import {+ AGENT_SIGNAL_SOURCE_TYPES,+ type AgentSignalSourceEvent,+ type AgentSignalSourceType,+ type SourceAgentUserMessage,+ type SourceClientRuntimeStart,+} from '@lobechat/agent-signal/source';import type { ExecutionSnapshot, ISnapshotStore, StepSnapshot } from '@lobechat/agent-tracing';import { messages } from '@lobechat/database/schemas';import { context as otContext, SpanStatusCode } from '@lobechat/observability-otel/api';@@ -19,13 +26,6 @@ import type { GeneratedAgentSignalEmissionResult } from '@/server/services/agentimport { executeAgentSignalSourceEvent } from '@/server/services/agentSignal/orchestrator';import { assembleFeedbackContext } from '@/server/services/agentSignal/policies/analyzeIntent/context/feedbackContextAssembler';import { createRedisRuntimeGuardBackend } from '@/server/services/agentSignal/runtime/backend/redisGuard';-import {- AGENT_SIGNAL_SOURCE_TYPES,- type AgentSignalSourcePayloadMap,- type AgentSignalSourceType,- type SourceAgentUserMessage,- type SourceClientRuntimeStart,-} from '@/server/services/agentSignal/sourceTypes';import type { AgentSignalWorkflowRunPayload } from './index';@@ -63,13 +63,7 @@ export interface RunAgentSignalWorkflowDeps {*/interface NormalizedWorkflowSourceEventInput<TSourceType extends AgentSignalSourceType = AgentSignalSourceType,-> {- payload: AgentSignalSourcePayloadMap[TSourceType];- scopeKey: string;- sourceId: string;- sourceType: TSourceType;- timestamp: number;-}+> extends AgentSignalSourceEvent<TSourceType> {}const buildWorkflowMetricAttributes = (sourceType: string,diff --git a/src/services/agentSignal.ts b/src/services/agentSignal.tsindex 2313e2dc2fd..17c4262ac8a 100644--- a/src/services/agentSignal.ts+++ b/src/services/agentSignal.ts@@ -1,26 +1,22 @@-import { lambdaClient } from '@/libs/trpc/client';import type {- AgentSignalSourcePayloadMap,+ AgentSignalSourceEventInput,AgentSignalSourceType,-} from '@/server/services/agentSignal/sourceTypes';+} from '@lobechat/agent-signal/source';++import { lambdaClient } from '@/libs/trpc/client';type ClientGatewaySourceType = Extract<AgentSignalSourceType, `client.${string}`>;-type ClientGatewaySourceEnvelopeInput<TSourceType extends ClientGatewaySourceType> = {- payload: AgentSignalSourcePayloadMap[TSourceType];- scopeKey?: string;- sourceId: string;- sourceType: TSourceType;- timestamp?: number;-};+type ClientGatewaySourceEventInput<TSourceType extends ClientGatewaySourceType> =+ AgentSignalSourceEventInput<TSourceType>;class AgentSignalService {- emitSourceEvent = async (payload: ClientGatewaySourceEnvelopeInput<ClientGatewaySourceType>) => {+ emitSourceEvent = async (payload: ClientGatewaySourceEventInput<ClientGatewaySourceType>) => {return lambdaClient.agentSignal.emitSourceEvent.mutate(payload);};emitClientGatewaySourceEvent = async <TSourceType extends ClientGatewaySourceType>(- payload: ClientGatewaySourceEnvelopeInput<TSourceType>,+ payload: ClientGatewaySourceEventInput<TSourceType>,) => {return this.emitSourceEvent({...payload,diff --git a/src/store/chat/slices/aiChat/actions/agentSignalBridge.ts b/src/store/chat/slices/aiChat/actions/agentSignalBridge.tsindex 2d26036bfad..9780783339e 100644--- a/src/store/chat/slices/aiChat/actions/agentSignalBridge.ts+++ b/src/store/chat/slices/aiChat/actions/agentSignalBridge.ts@@ -1,7 +1,8 @@import type {AgentSignalSourcePayloadMap,AgentSignalSourceType,-} from '@/server/services/agentSignal/sourceTypes';+} from '@lobechat/agent-signal/source';+import { agentSignalService } from '@/services/agentSignal';import { labPreferSelectors, preferenceSelectors } from '@/store/user/selectors';import { getUserStoreState } from '@/store/user/store';